Package screenlets :: Module sensors

[hide private]
[frames] | no frames]

# Source Code for Module screenlets.sensors

       1  # This application is released under the GNU General Public License
       2  # v3 (or, at your option, any later version). You can find the full
       3  # text of the license under http://www.gnu.org/licenses/gpl.txt.
       4  # By using, editing and/or distributing this software you agree to
       5  # the terms and conditions of this license.
       6  # Thank you for using free software!
       7
       8  # Sensors Module (c) Whise (Helder Fraga) 2008 <helder.fraga@hotmail.com>
       9
      10  import screenlets
      11  import sys
      12  import re
      13  import gobject
      14  import gettext
      15  from datetime import datetime
      16  import commands
      17  import time
      18  import os
      19  import subprocess
      20  import gtk
      21  # translation stuff
      22  gettext.textdomain('screenlets')
      23  gettext.bindtextdomain('screenlets', screenlets.INSTALL_PREFIX +  '/share/locale')
      24
      25 -def _(s):
      26          return gettext.gettext(s)
      27
      28
      29  # ------------------------------------------------------------------------------
      30  # FUNCTIONS
      31  # ------------------------------------------------------------------------------
      32
      33
      34
      35  ###########################################
      36  #                                         #
      37  #                 CPU                     #
      38  #                                         #
      39  ###########################################
      40
      41  # calculate cpu-usage by values from /proc/stat
      42  # (written by Helder Fraga aka Whise
      43 -def cpu_get_load (processor_number=0):
      44          """Calculates the system load."""
      45          try:
      46                  f = open("/proc/stat", "r")
      47                  tmp = f.readlines(2000)
      48                  f.close()
      49          except:
      50                  print _("Failed to open /proc/stat")
      51                  return None
      52          if processor_number == 0 : sufix = ''
      53          else: sufix = str(processor_number -1)
      54          line = tmp[processor_number]
      55
      56          if line.startswith("cpu%s"% (sufix)):
      57                  cuse = float( line.split()[1] )
      58                  cn = float( line.split()[2] )
      59                  csys = float( line.split()[3])
      60                  if sufix == '':
      61                          load = cuse + cn
      62                  else:
      63                          load = cuse + csys + cn
      64                  #load = int(load / .update_interval)
      65                  return load
      66          return None
      67
      68 -def cpu_get_cpu_name():
      69          """Returns Cpu Name"""
      70          try:
      71                  f = open("/proc/cpuinfo", "r")
      72                  tmp = f.readlines(500)
      73                  f.close()
      74          except:
      75                  print _("Failed to open /proc/cpuinfo")
      76                  return None
      77                  list = []
      78          for line in tmp:
      79                  if line.startswith("model name"):
      80                          return line.split(':')[1].strip()
      81          return ''
      82
      83 -def cpu_get_cpu_list ():
      84          """Returns Cpu List"""
      85          try:
      86                  f = open("/proc/stat", "r")
      87                  tmp = f.readlines(2000)
      88                  f.close()
      89          except:
      90                  print _("Failed to open /proc/stat")
      91                  return None
      92          list = []
      93          for line in tmp:
      94                  if line.startswith("cpu"):
      95                          list.append(line.split(' ')[0])
      96
      97          return list
      98
      99 -def cpu_get_nb_cpu ():
     100          """Returns Cpu Number"""
     101          try:
     102                  f = open("/proc/stat", "r")
     103                  tmp = f.readlines(2000)
     104                  f.close()
     105          except:
     106                  print _("Failed to open /proc/stat")
     107                  return None
     108          nb = 0
     109          for line in tmp:
     110                  if line.startswith("cpu"):
     111                          nb = nb+1
     112          return nb -1
     113
     114 -def cpu_get_current_freq():
     115          """Returns Cpu frequency"""
     116          op = commands.getoutput('cat /proc/cpuinfo | grep "cpu MHz"')
     117          try:
     118                  op = int(op.replace(" ","").split(':')[1].split('\n')[0].replace(".",""))
     119                  return op
     120          except: return None
     121
     122 -def cpu_get_current_gov(self):
     123          """Returns Cpu governator"""
     124          try:
     125                  op = commands.getoutput('cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor').strip()
     126                  return op
     127          except: return None
     128
     129 -def get_available_freq(self):
     130          """Returns available frequencies"""
     131          try:
     132                  afreqsh = open("/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies", "r")
     133                  op = afreqsh.readline().strip().split(' ')
     134                  afreqsh.close()
     135                  return op
     136          except:
     137                  return None
     138
     139 -def get_available_gov(self):
     140          """Returns available governators"""
     141          try:
     142                  afreqsh = open("/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors", "r")
     143                  op = afreqsh.readline().strip().split(' ')
     144                  afreqsh.close()
     145                  return op
     146          except:
     147                  return None
     148
     149  ###########################################
     150  #                                         #
     151  #                 System info             #
     152  #                                         #
     153  ###########################################
     154
     155  # written by Hendrik Kaju
     156 -def sys_get_uptime_long ():
     157          """Returns uptime extended version"""
     158          try:
     159                  f = open("/proc/uptime", "r")
     160                  data1 = f.readline(100)
     161                  f.close()
     162                  uptime = float( data1.split()[0] )
     163                  days = int( uptime / 60 / 60 / 24 )
     164                  uptime = uptime - days * 60 * 60 * 24
     165                  hours = int( uptime / 60 / 60 )
     166                  uptime = uptime - hours * 60 * 60
     167                  minutes = int( uptime / 60 )
     168                  return _("%s days, %s hours and %s minutes") % (str(days), str(hours), str(minutes))
     169                  #return str(days) + " days, " + str(hours) + " hours and " + str(minutes) + " minutes"
     170          except:
     171                  print _("Failed to open /proc/uptime")
     172          return 'Error'
     173
     174 -def sys_get_uptime():
     175          """Returns uptime"""
     176          try:
     177                  f = open("/proc/uptime", "r")
     178                  tmp = f.readline(100)
     179                  f.close()
     180                  t = tmp.split()[0]
     181                  h = int(float(t)/3600)
     182                  m = int((float(t)-h*3600)/60)
     183                  if m < 10:
     184                          return str(h)+':'+'0'+str(m)
     185                  else:
     186                          return str(h)+':'+str(m)
     187          except:
     188                  print _("Failed to open /proc/uptime")
     189          return 'Error'
     190
     191
     192 -def sys_get_username():
     193          """Returns username"""
     194          res = commands.getstatusoutput('whoami')
     195          if res[0]==0:
     196                  return res[1].strip()
     197          return ''
     198
     199
     200  # written by Hendrik Kaju
     201 -def sys_get_hostname ():
     202          """Get hostname"""
     203          try:
     204                  f = open("/proc/sys/kernel/hostname", "r")
     205                  hostname = f.readline(100)
     206                  f.close()
     207                  return hostname
     208          except:
     209                  print _("Failed to open /proc/sys/kernel/hostname")
     210          return 'Error'
     211
     212  # written by Hendrik Kaju
     213 -def sys_get_average_load ():
     214          """Get average load (as 3-tuple with floats)."""
     215          try:
     216                  f = open("/proc/loadavg", "r")
     217                  data = f.readline(100)
     218                  f.close()
     219                  load1 = str(float( data.split()[0] ))[:4]
     220                  load2 = str(float( data.split()[1] ))[:4]
     221                  load3 = str(float( data.split()[2] ))[:4]
     222                  return load1+ ','+ load2 +','+ load3
     223          except:
     224                  print _("Failed to open /proc/loadavg")
     225          return 'Error'
     226
     227 -def sys_get_distrib_name():
     228          try:
     229                  if os.path.exists('/etc/lsb-release') and str(commands.getoutput('cat /etc/lsb-release')).lower().find('ubuntu') != -1:
     230                          return str(commands.getoutput('cat /etc/issue')).replace('\\n','').replace('\l','').replace('\r','').strip()
     231
     232                  elif os.path.exists('/etc/lsb-release'):
     233                          return 'Debian ' + str(commands.getoutput('cat /etc/debian_version'))
     234                  elif os.path.exists('/etc/mandriva-release'):
     235                          return 'Mandriva ' + str(commands.getoutput("cat /etc/mandriva-release | sed -e 's/[A-Za-z ]* release //'"))
     236                  elif os.path.exists('/etc/fedora-release'):
     237                          return 'Fedora ' + str(commands.getoutput("cat /etc/fedora-release | sed -e 's/[A-Za-z ]* release //'"))
     238                  elif os.path.exists('/etc/SuSE-release'):
     239
     240                          if str(commands.getoutput('cat /etc/SuSE-release')).lower().find('openSUSE') != -1:
     241                                  return 'openSUSE ' + str(commands.getoutput("""cat /etc/SuSE-release | grep "VERSION" | sed -e 's/VERSION = //'"""))
     242                          else:
     243                                  return 'SUSE ' + str(commands.getoutput("""cat /etc/SuSE-release | grep "VERSION" | sed -e 's/VERSION = //'"""))
     244                  elif os.path.exists('/etc/gentoo-release'):
     245                          return 'Gentoo ' + str(commands.getoutput("cat /etc/gentoo-release | sed -e 's/[A-Za-z ]* release //'"))
     246                  elif os.path.exists('/etc/slackware-version'):
     247                          return 'Slackware ' + str(commands.getoutput("cat /etc/slackware-version | sed -e 's/Slackware //'"))
     248                  elif os.path.exists('/etc/arch-release'):
     249                          return 'Arch Linux'
     250                  elif os.path.exists('/etc/redhat-release'):
     251                          return 'Redhat ' + str(commands.getoutput("cat /etc/redhat-release | sed -e 's/[A-Za-z ]* release //'"))
     252                  else:
     253                          f = open("/etc/issue", "r")
     254                          tmp = f.readlines(100)
     255                          f.close()
     256                          return tmp[0].replace('\\n','').replace('\l','').replace('\r','').strip()
     257          except:
     258                  print _("Error getting distro name")
     259          return 'Error'
     260
     261
     262 -def sys_get_distroshort ():
     263          """Get distro short name"""
     264          distros = commands.getoutput("lsb_release -is")
     265          return distros
     266
     267 -def sys_get_desktop_enviroment():
     268          """ shows kde or gnome or xface"""
     269          if os.environ.get('KDE_FULL_SESSION') == 'true':
     270              desktop_environment = 'kde'
     271          elif os.environ.get('GNOME_DESKTOP_SESSION_ID'):
     272              desktop_environment = 'gnome'
     273          else:
     274              try:
     275                  import commands
     276                  info = commands.getoutput('xprop -root _DT_SAVE_MODE')
     277                  if ' = "xfce4"' in info:
     278                      desktop_environment = 'xfce'
     279              except (OSError, RuntimeError):
     280                  pass
     281          return desktop_environment
     282
     283 -def sys_get_kernel_version():
     284          """Returns kernel version"""
     285          res = commands.getstatusoutput('uname -r')
     286          if res[0]==0:
     287                  return res[1].strip()
     288          return _("Can't get kernel version")
     289
     290 -def sys_get_kde_version():
     291          """Returns kde version"""
     292          res = commands.getstatusoutput('kde-config --version')
     293          if res[0]==0:
     294                  lst = res[1].splitlines()
     295                  for i in lst:
     296                          if i.startswith('KDE:'):
     297                                  return i[4:].strip()
     298          return _("Can't get KDE version")
     299
     300 -def sys_get_gnome_version():
     301          """Returns gnome version"""
     302          res = commands.getstatusoutput('gnome-about --gnome-version')
     303          if res[0]==0:
     304                  lst = res[1].splitlines()
     305                  for i in lst:
     306                          if i.startswith('Version:'):
     307                                  return i[8:].strip()
     308          return _("Can't get Gnome version")
     309
     310  # by whise
     311 -def sys_get_linux_version ():
     312          """Get linux version string."""
     313          try:
     314                  f = open("/proc/version", "r")
     315                  data = f.readline(200)[:-1]
     316                  f.close()
     317                  return data
     318          except:
     319                  return _("Failed to open /proc/version")
     320
     321  # by whise
     322  # TODO: return dict and parse the output of cpuinfo (function does not much yet)
     323 -def sys_get_full_info ():
     324          """Get cpu info from /proc/cpuinfo."""
     325          return commands.getoutput("cat /proc/cpuinfo")
     326
     327 -def sys_get_window_manager():
     328          """Returns window manager name"""
     329          root = gtk.gdk.get_default_root_window()
     330          try:
     331                  ident = root.property_get("_NET_SUPPORTING_WM_CHECK", "WINDOW")[2]
     332                  _WM_NAME_WIN = gtk.gdk.window_foreign_new(long(ident[0]))
     333          except TypeError, exc:
     334                  _WM_NAME_WIN = ""
     335
     336          name = ""
     337          win = _WM_NAME_WIN
     338          if (win != None):
     339                  try:
     340                          name = win.property_get("_NET_WM_NAME")[2]
     341                  except TypeError, exc:
     342
     343                          return name
     344
     345          return name
     346
     347  ###########################################
     348  #                                         #
     349  #               Memory                    #
     350  #                                         #
     351  ###########################################
     352
     353
     354 -def mem_get_freemem ():# written by Hendrik Kaju
     355          """Get free memory."""
     356          cached = commands.getoutput("""cat /proc/meminfo | grep Cached | awk 'BEGIN {FS=":"} {print $2}' | awk '{print $1, $9}'""")
     357          buffers = commands.getoutput("""cat /proc/meminfo | grep Buffers | awk 'BEGIN {FS=":"} {print $2}' | awk '{print $1, $9}'""")
     358          free = commands.getoutput("""cat /proc/meminfo | grep MemFree | awk 'BEGIN {FS=":"} {print $2}' | awk '{print $1, $9}'""")
     359          return int(cached.split()[0])/1024 + int(buffers)/1024 + int(free)/1024
     360
     361
     362 -def mem_get_usedmem ():# written by Hendrik Kaju
     363          """Get used memory."""
     364          total = commands.getoutput("""cat /proc/meminfo | grep MemTotal | awk 'BEGIN {FS=":"} {print $2}' | awk '{print $1, $9}'""")
     365          cached = commands.getoutput("""cat /proc/meminfo | grep Cached | awk 'BEGIN {FS=":"} {print $2}' | awk '{print $1, $9}'""")
     366          buffers = commands.getoutput("""cat /proc/meminfo | grep Buffers | awk 'BEGIN {FS=":"} {print $2}' | awk '{print $1, $9}'""")
     367          free = commands.getoutput("""cat /proc/meminfo | grep MemFree | awk 'BEGIN {FS=":"} {print $2}' | awk '{print $1, $9}'""")
     368          return int(total)/1024 - int(cached.split()[0])/1024 - \
     369                  int(buffers)/1024 - int(free)/1024
     370
     371 -def mem_get_usage():
     372          """Returns memory usage"""
     373          try:
     374                  meminfo_file = open('/proc/meminfo')
     375                  meminfo = {}
     376                  for x in meminfo_file:
     377                          try:
     378                                  (key,value,junk) = x.split(None, 2)
     379                                  key = key[:-1]
     380                                  meminfo[key] = int(value)
     381                          except:
     382                                  pass
     383                  meminfo_file.close()
     384                  return int((100*(int(meminfo['MemTotal'])-int(meminfo['Cached']) - int(meminfo['Buffers']) - int(meminfo['MemFree'])))/int(meminfo['MemTotal']))
     385          except:
     386                  print(_("Can't parse /proc/meminfo"))
     387                  return 0
     388
     389 -def mem_get_total():
     390          try:
     391                  meminfo_file = open('/proc/meminfo')
     392                  meminfo = {}
     393                  for x in meminfo_file:
     394                          try:
     395                                  (key,value,junk) = x.split(None, 2)
     396                                  key = key[:-1]
     397                                  meminfo[key] = int(value)
     398                          except:
     399                                  pass
     400                  meminfo_file.close()
     401                  return int(meminfo['MemTotal'])/1024
     402          except:
     403                  print("Can't parse /proc/meminfo")
     404                  return 0
     405
     406 -def mem_get_usedswap():
     407          """Returns used swap"""
     408          try:
     409                  meminfo_file = open('/proc/meminfo')
     410                  meminfo = {}
     411                  for x in meminfo_file:
     412                          try:
     413                                  (key,value,junk) = x.split(None, 2)
     414                                  key = key[:-1]
     415                                  meminfo[key] = int(value)
     416                          except:
     417                                  pass
     418                  meminfo_file.close()
     419                  if(meminfo['SwapTotal']==0):
     420                          return 0
     421                  return int((100*(int(meminfo['SwapTotal'])-int(meminfo['SwapCached']) - int(meminfo['SwapFree'])))/int(meminfo['SwapTotal']))
     422          except:
     423                  print("Can't parse /proc/meminfo")
     424                  return 0
     425
     426 -def mem_get_totalswap():
     427          """Returns total swap"""
     428          try:
     429                  meminfo_file = open('/proc/meminfo')
     430                  meminfo = {}
     431                  for x in meminfo_file:
     432                          try:
     433                                  (key,value,junk) = x.split(None, 2)
     434                                  key = key[:-1]
     435                                  meminfo[key] = int(value)
     436                          except:
     437                                  pass
     438                  meminfo_file.close()
     439                  if(meminfo['SwapTotal']==0):
     440                          return 0
     441                  return int(meminfo['SwapTotal'])/1024
     442          except:
     443                  print("Can't parse /proc/meminfo")
     444                  return 0
     445
     446  ###########################################
     447  #                                         #
     448  #               Disks                     #
     449  #                                         #
     450  ###########################################
     451
     452
     453 -def disk_get_drive_info (mount_point):
     454          """Returns info about the given mount point (as dict)."""
     455          proc = subprocess.Popen('df -h -a -P | grep ^/dev/ ', shell='true',
     456                  stdout=subprocess.PIPE)
     457          sdevs = proc.stdout.read().rsplit('\n')
     458          sdevs.pop()
     459          for stdev in sdevs:
     460                  sdev = re.findall("(\S*)\s*", stdev)
     461                  dev = {
     462                          'device': sdev[0],
     463                          'size': sdev[1],
     464                          'used': sdev[2],
     465                          'free': sdev[3],
     466                          'quota': sdev[4],
     467                          'mount': sdev[5]
     468                  }
     469                  if dev['mount'] == mount_point:
     470                          return dev
     471          return None
     472
     473 -def disk_get_swap ():
     474          """Get a list of swap partitions."""
     475          try:
     476                  f = open("/proc/swaps", "r")
     477                  swap = f.read()
     478                  f.close()
     479                  swap = str(swap.split()[5:])
     480                  swap = swap.replace("'","")
     481                  swap = swap.replace("[","")
     482                  swap = swap.replace("]","")
     483                  swap = swap.replace(",","")
     484                  return str(swap)
     485          except:
     486                  print _("Failed to open /proc/swaps")
     487          return 'Error'
     488
     489 -def disk_get_usage(disk_disk):
     490          """Returns disk usage"""
     491          res = commands.getoutput('df -h -a -P').splitlines()
     492          for i in res:
     493                  if i.startswith('/dev/'):
     494                          data = re.findall("(\S*)\s*", i)
     495
     496                          if (data[5] == disk_disk) or (data[0] == disk_disk):
     497                                  return data
     498
     499 -def disk_get_disk_list():
     500          """Returns disk list"""
     501          disks = []
     502          res = commands.getoutput('df -h -a -P').splitlines()
     503          for i in res:
     504                  if i.startswith('/dev/'):
     505                          data = re.findall("(\S*)\s*", i)
     506                          disks.append(data[5])
     507          return disks
     508
     509
     510  ###########################################
     511  #                                         #
     512  #             Internet                    #
     513  #                                         #
     514  ###########################################
     515
     516 -def net_get_ip(): # by Whise
     517          """Returns ip if it can"""
     518          ip = commands.getoutput("ifconfig")
     519          x = 0
     520          while True:
     521                  ip = ip[ip.find("inet addr:"):]
     522                  ip = ip[10:]
     523                  ipc = ip[:ip.find(chr(32))]
     524                  if ipc != '127.0.0.1' and ipc != None and ipc !='1':
     525
     526                          return ipc
     527
     528
     529          return _('Cannot get ip')
     530
     531
     532 -def net_get_updown():
     533          """Returns upload and download"""
     534          try:
     535                  f = open("/proc/net/dev", "r")
     536                  data = f.readlines(2000)
     537                  f.close()
     538                  newNetUp = 0
     539                  newNetDown = 0
     540                  for i in data:
     541                          if i.find(':') != -1 and i.strip().startswith('lo:') == False:
     542                                  v = i.split(':')[1].split()
     543                                  newNetUp = float( v[8] )+newNetUp
     544                                  newNetDown = float( v[0] )+newNetDown
     545
     546
     547                  return (newNetUp/1024), (newNetDown/1024)
     548          except:
     549                  print(_("Can't open /proc/net/dev"))
     550                  return 0,0
     551
     552
     553 -def net_get_activity (device):
     554          """This will return the total download and upload this session. As 2-tuple
     555          with floats)."""
     556          data = commands.getoutput("cat /proc/net/dev")
     557          data = data[data.find(device + ":") + 5:]
     558          return (float(data.split()[0]), float(data.split()[8]))
     559
     560
     561 -def net_get_connections ():
     562          """This will return the number of connections."""
     563          data = commands.getoutput("netstat -n | grep -c tcp")
     564
     565          return data
     566
     567  ###########################################
     568  #                                         #
     569  #                 Wireless                #
     570  #                                         #
     571  ###########################################
     572
     573 -def wir_get_interfaces():
     574          """Returns wireless interfaces"""
     575          try:
     576                  interfaces = []
     577                  f = open("/proc/net/wireless")
     578                  cards = f.read(1024)
     579                  f.close()
     580                  for line in cards.splitlines():
     581                          colon = line.find(":")
     582                          if colon > 0:
     583                                  interfaces.append(line[:colon].strip())
     584                  return interfaces
     585          except:
     586                  print(_("Can't open /proc/net/wireless"))
     587                  return []
     588
     589 -def wir_get_stats (interface):
     590          """Returns wireless stats as dict."""
     591          stats = {}
     592          iwcfd = os.popen("iwconfig " + interface)
     593          iwconfig = iwcfd.read(1024)
     594          iwcfd.close()
     595          essid = iwconfig[iwconfig.find('ESSID:"')+7:]
     596          stats['essid'] = essid[:essid.find('"')]
     597          if stats['essid'].strip()[:stats['essid'].strip().find("  ")] == "unassociated":
     598                  return {"essid": _("Not connected"), "percentage": 0}
     599          else:
     600                  bitrate = iwconfig[iwconfig.find("Bit Rate:")+9:]
     601                  stats['bitrate'] = bitrate[:bitrate.find(" ")]
     602                  quality = iwconfig[iwconfig.find("Link Quality")+13:]
     603                  quality = quality[:quality.find(" ")]
     604                  if quality.find("/") > 0:
     605                          stats['quality'], stats['quality_max'] = quality.split("/")
     606                  else:
     607                          stats['quality'] = quality
     608                  try:
     609                          stats['percentage'] = int(float(stats['quality'])/float(stats['quality_max'])*100)
     610                  except:
     611                          return {"essid": _("Not connected"), "percentage": 0}
     612                  signal = iwconfig[iwconfig.find("Signal level")+13:]
     613                  stats['signal'] = signal[:signal.find("  ")]
     614                  noise = iwconfig[iwconfig.find("Noise level")+12:]
     615                  stats['noise'] = noise[:noise.find('\n')]
     616                  return stats
     617
     618  ###########################################
     619  #                                         #
     620  #                calendar                 #
     621  #                                         #
     622  ###########################################
     623
     624
     625  # by whise
     626 -def cal_get_now ():
     627          """Returns full now time and date"""
     628          return str(datetime.now())
     629
     630
     631 -def cal_get_local_date ():
     632          """returns date using local format"""
     633          return str(datetime.now().strftime("%x"))
     634
     635 -def cal_get_date ():
     636          """returns date."""
     637          return str(datetime.now().strftime("%d/%m/%Y"))
     638
     639 -def cal_get_local_time ():
     640          """returns time using local format"""
     641          return str(datetime.now().strftime("%X"))
     642
     643 -def cal_get_time ():
     644          """returns time"""
     645          return str(datetime.now().strftime("%H:%M:%S"))
     646
     647 -def cal_get_time24 ():
     648          """returns 24 hour time"""
     649          return str(datetime.now().strftime("%R"))
     650
     651 -def cal_get_time12 ():
     652          """returns 12 hour time"""
     653          return str(datetime.now().strftime("%r"))
     654
     655 -def cal_get_year ():
     656          """returns the years."""
     657          return str(datetime.now().strftime("%Y"))
     658
     659 -def cal_get_month ():
     660          """returns the month"""
     661          return str(datetime.now().strftime("%m"))
     662
     663 -def cal_get_month_name ():
     664          """returns the month name"""
     665          return str(datetime.now().strftime("%B"))
     666
     667 -def cal_get_day ():
     668          """returns the day"""
     669          return str(datetime.now().strftime("%d"))
     670
     671 -def cal_get_day_monday ():
     672          """returns the number of the day of the week starting from monday"""
     673          return str(datetime.now().strftime("%u"))
     674
     675 -def cal_get_day_sonday ():
     676          """returns the number of the day of the week starting from sonday"""
     677          return str(datetime.now().strftime("%w"))
     678
     679 -def cal_get_day_name ():
     680          """returns the day name"""
     681          return str(datetime.now().strftime("%A"))
     682
     683 -def cal_get_hour ():
     684          """returns the hour"""
     685          return str(datetime.now().strftime("%H"))
     686
     687 -def cal_get_hour24 ():
     688          """returns the hour"""
     689          return str(datetime.now().strftime("%H"))
     690
     691 -def cal_get_hour12 ():
     692          """returns the hours"""
     693          return str(datetime.now().strftime("%I"))
     694
     695 -def cal_get_minute ():
     696          """returns minutes"""
     697          return str(datetime.now().strftime("%M"))
     698
     699 -def cal_get_second ():
     700          """returns seconds"""
     701          return str(datetime.now().strftime("%S"))
     702
     703 -def cal_get_ampm ():
     704          """return am/pm or None if not available"""
     705          return str(datetime.now().strftime("%p"))
     706
     707
     708
     709  ###########################################
     710  #                                         #
     711  #               Battery                   #
     712  #                                         #
     713  ###########################################
     714
     715
     716 -def bat_get_battery_list():
     717          """Returns battery list"""
     718          try:
     719                  path = "/proc/acpi/battery/"
     720                  files = os.listdir(path)
     721                  return files
     722          except:
     723                  return[]
     724
     725 -def bat_get_data(name):
     726          """Returns battery data"""
     727          path = "/proc/acpi/battery/"+name+"/info"
     728          try:
     729                  f = open(path)
     730                  data = f.readlines()
     731                  f.close()
     732                  total = 0
     733                  current = 0
     734                  full = 0
     735                  state = ''
     736                  present = True
     737                  for line in data:
     738                          if line.startswith('present:') and line.find('yes')==-1:
     739                                  present = False
     740                          elif line.startswith('design capacity:'):
     741                                  total = int(line.split(':')[1].strip().split(' ')[0])
     742                          elif line.startswith('last full capacity:'):
     743                                  full = int(line.split(':')[1].strip().split(' ')[0])
     744                  path = "/proc/acpi/battery/"+name+"/state"
     745                  f = open(path)
     746                  data = f.readlines()
     747                  f.close()
     748                  for line in data:
     749                          if line.startswith('present:') and line.find('yes')==-1:
     750                                  present = False
     751                          elif line.startswith('remaining capacity:'):
     752                                  current = int(line.split(':')[1].strip().split(' ')[0])
     753                          elif line.startswith('charging state:'):
     754                                  state = line.split(':')[1].strip().split(' ')[0]
     755                  return total, current, full, state, present
     756          except:
     757                  return 0, 0, 0, '', False
     758
     759 -def bat_get_value(line):
     760          """Returns battery value"""
     761          return line.split(':')[1].strip().split(' ')[0]
     762
     763
     764 -def bat_get_ac():
     765          """Returns battery ac"""
     766          data = commands.getoutput("acpi -V | grep AC | sed 's/.*: //'")
     767          return data
     768
     769  ###########################################
     770  #                                         #
     771  #                 Processes               #
     772  #                                         #
     773  ###########################################
     774
     775
     776 -def process_get_list():
     777          """Returns process list"""
     778          res = commands.getoutput('ps -eo pcpu,pmem,comm --sort pcpu').splitlines()
     779          l = res.__len__()
     780          return res,l
     781
     782 -def process_get_top():
     783          """Returns top list"""
     784          res = commands.getoutput('ps axo comm,user,pcpu --sort=-pcpu | head -n 10')
     785
     786          return res
     787
     788
     789
     790  ###########################################
     791  #                                         #
     792  #                Nvidia                   #
     793  #                                         #
     794  ###########################################
     795
     796
     797 -def getGpuType():
     798          """return GPU Type to its caller"""
     799          output = commands.getoutput("nvidia-settings -q Gpus | cut -d '(' -f 2 -s | cut -d ')' -f 1")
     800          return output
     801
     802
     803
     804 -def getGpuRam():
     805          """return GPU Ram size in MB to its caller"""
     806          output = commands.getoutput("nvidia-settings -q VideoRam | cut -d ':' -f 3 -s | cut -d ' ' -f 2 | cut -d '.' -f 1")
     807          return str(int(output)/1024) + " MB"
     808
     809
     810 -def getGpuDriver():
     811          """return current GPU Driver version to its caller"""
     812          output = commands.getoutput("nvidia-settings -q NvidiaDriverVersion | cut -d ':' -f 3 -s | cut -d ' ' -f 2")
     813          return output
     814
     815
     816 -def getGpuResolution():
     817          """return current screen resolution to its caller"""
     818          output = commands.getoutput("nvidia-settings -q FrontendResolution")
     819          return output[74:83].replace(",", "x")
     820
     821
     822 -def getGpuRefreshRate():
     823          """return current refreshrate to its caller"""
     824          output = commands.getoutput("nvidia-settings -q RefreshRate | cut -d ':' -f 4 -s | cut -d ' ' -f 2 | cut -d ',' -f 1")
     825          return str(int(output)) + " Hz"
     826
     827
     828 -def getGpuClock():
     829          """return current GPU Clock Frequency to its caller"""
     830          output = commands.getoutput("nvidia-settings -q gpuperfmodes | cut -d '=' -f 3 | cut -d ',' -f 1 -s")
     831          return str(output) + " MHz"
     832
     833 -def getGpuMemClock():
     834          """return current GPU Memory Clock Frequency to its caller"""
     835          output = commands.getoutput("nvidia-settings -q gpuperfmodes | grep 'memclock'")
     836          return str(output).lstrip()[9:] + " MHz"
     837
     838 -def getGpuTemp():
     839          """return current GPU Core Temperature to its caller"""
     840          output = commands.getoutput("nvidia-settings -q GPUCoreTemp | cut -d ':' -f 3 -s | cut -d ' ' -f 2 | cut -d '.' -f 1")
     841          return output
     842
     843
     844  ###########################################
     845  #                                         #
     846  #               Custom Sensors            # thanks Mathieu Villegas for you great watermark
     847  #                                         #
     848  ###########################################
     849
     850
     851 -def sensors_get_sensors_list():
     852          res = commands.getstatusoutput('sensors')
     853          output = ['Custom Sensors']
     854          output.remove ('Custom Sensors')
     855          if res[0]==0:
     856                  sol = res[1].replace(':\n ',': ').replace(':\n\t',': ').splitlines()
     857                  for i in sol:
     858                          i = i.strip()
     859                          if (i.find('\xb0')!= -1) or (i.find('\xc2')!= -1) or (i.find('temp')!= -1) or (i.find('Temp')!= -1) or (i.find(' V ')!= -1) or (i.find(' RPM ')!= -1):
     860                                  output.append(i.lstrip())#.split(')')[0]+')')
     861          #now look for nvidia sensors
     862          res = commands.getstatusoutput(' nvidia-settings -q GPUAmbientTemp | grep :')
     863          if res[0] == 0:
     864                  if res[1].strip().startswith('Attribute \'GPUAmbientTemp\''):
     865                          sol = res[1].splitlines()[0].split('):')[1].strip()
     866                          output.append('nvidia GPU ambiant: '+str(float(sol))+' C')
     867          res = commands.getstatusoutput(' nvidia-settings -q GPUCoreTemp | grep :')
     868          if res[0] == 0:
     869                  if res[1].strip().startswith('Attribute \'GPUCoreTemp\''):
     870                          sol = res[1].splitlines()[0].split('):')[1].strip()
     871                          output.append('nvidia GPU core: '+str(float(sol))+'C')
     872
     873
     874          #recherche des senseurs ACPI
     875          try:
     876                  path = "/proc/acpi/thermal_zone/"
     877                  files = os.listdir(path)
     878                  for entry in files:
     879                          try:
     880                                  f = open(path+entry+'/temperature', "r")
     881                                  tmp = f.readlines(200)
     882                                  f.close()
     883                                  val = tmp[0].replace('temperature:','').replace('C','').strip()
     884                                  output.append('acpi temperature '+entry+': '+val+'C')
     885                          except:
     886                                  print(_("Can't open %s/temperature") % path+entry)
     887          except:
     888                  print(_("Can't open folder /proc/acpi/thermal_zone/"))
     889
     890          #recherche des senseurs IBM
     891          path = "/proc/acpi/ibm/thermal"
     892          try:
     893                  f = open(path, "r")
     894                  tmp = f.readlines(200)
     895                  f.close()
     896                  lst = tmp[0].split(' ')
     897                  pos = 0
     898                  for i in lst:
     899                          i = i.strip()
     900                          if i != '' and i != '-128':
     901                                  output.append('ibm temperature '+str(pos)+': '+i+'C')
     902                          pos = pos+1
     903          except:
     904                  print(_("Can't open %s") % path)
     905
     906          path = "/proc/acpi/ibm/fan"
     907          try:
     908                  f = open(path, "r")
     909                  tmp = f.readlines(200)
     910                  f.close()
     911                  for i in tmp:
     912                          if i.startswith('speed:'):
     913                                  output.append('ibm fan: '+i.split(':')[1].strip()+' RPM')
     914          except:
     915                  print(_("Can't open %s") % path)
     916
     917                  #recherche des temperatures de disque
     918          res = commands.getstatusoutput("netcat 127.0.0.1 7634")
     919          if res[0] != 0:
     920                  res = commands.getstatusoutput("nc 127.0.0.1 7634")
     921          if res[0] == 0:
     922                  try:
     923                          hddtemp_data = res[1].lstrip('|').rstrip('|')
     924                          sol = hddtemp_data.split('||')
     925                          for i in sol:
     926                                  if len(i)>1:
     927                                          lst = i.split('|')
     928                                          output.append("hddtemp sensor "+lst[0]+": "+lst[2]+" "+lst[3])
     929                  except:
     930                          print(_('Error during hddtemp drives search'))
     931          else:
     932                  print(_('Hddtemp not installed'))
     933                  return output
     934
     935
     936 -def sensors_get_sensor_value(sensorName):
     937
     938          if sensorName.startswith('nvidia GPU ambiant'):
     939                  res = commands.getstatusoutput(' nvidia-settings -q GPUAmbientTemp | grep :')
     940                  if res[0] == 0:
     941                          if res[1].strip().startswith('Attribute \'GPUAmbientTemp\''):
     942                                  #ici, je fais un str(float()) comme ca ca transforme 48. en 48.0
     943                                  return str(float(res[1].splitlines()[0].split('):')[1].strip()))+'C'
     944          elif sensorName.startswith('nvidia GPU core'):
     945                  res = commands.getstatusoutput(' nvidia-settings -q GPUCoreTemp | grep :')
     946                  if res[0] == 0:
     947                          if res[1].strip().startswith('Attribute \'GPUCoreTemp\''):
     948                                  #ici, je fais un str(float()) comme ca ca transforme 48. en 48.0
     949                                  return str(float(res[1].splitlines()[0].split('):')[1].strip()))+'C'
     950
     951          elif sensorName.startswith('acpi temperature'):
     952                  name = sensorName.split()[2].strip()
     953                  path = "/proc/acpi/thermal_zone/"+name+"/temperature"
     954                  try:
     955                          f = open(path, "r")
     956                          tmp = f.readlines(200)
     957                          f.close()
     958                          val = tmp[0].replace('temperature:','').replace('C','').strip()
     959
     960                          return val+'C'
     961                  except:
     962                          print(_("can't read temperature in: %s") % path)
     963                          return 'Error'
     964
     965          elif sensorName.startswith('ibm temperature'):
     966                  path = "/proc/acpi/ibm/thermal"
     967                  try:
     968                          name = sensorName
     969                          f = open(path, "r")
     970                          tmp = f.readlines(200)
     971                          f.close()
     972                          lst = tmp[0].split(' ')
     973                          val = int(sensorName.split(' ')[2])
     974                          return lst[val]+'C'
     975                  except:
     976                          print(_("Can't read value from %s") % path)
     977                          return 'None'
     978
     979          elif sensorName.startswith('ibm fan'):
     980                  path = "/proc/acpi/ibm/fan"
     981                  try:
     982                          name = sensorName
     983                          f = open(path, "r")
     984                          tmp = f.readlines(200)
     985                          f.close()
     986                          for i in tmp:
     987                                  if i.startswith('speed:'):
     988
     989                                          return i.split(':')[1].strip()+' RPM'
     990                          return 'None'
     991                  except:
     992                          print(_("Can't read value from %s") % path)
     993                          return 'None'
     994
     995          elif sensorName.startswith('hddtemp sensor '):
     996                  res = commands.getstatusoutput("netcat 127.0.0.1 7634")
     997                  if res[0] != 0:
     998                          res = commands.getstatusoutput("nc 127.0.0.1 7634")
     999                  name = sensorName[15:]
    1000                  if res[0] == 0:
    1001                          hddtemp_data = res[1].lstrip('|').rstrip('|')
    1002                          sol = hddtemp_data.split('||')
    1003                          for i in sol:
    1004                                  if len(i)>1:
    1005                                          if i.startswith(name):
    1006                                                  lst = i.split('|')
    1007                                                  return lst[0]+": "+lst[2]+" "+lst[3]
    1008                  else:
    1009                          print(_('Hddtemp not installed'))
    1010                          return ''
    1011
    1012
    1013
    1014                  #maintenant, je recherche dans lm-sensors
    1015          else:
    1016                  res = commands.getstatusoutput('sensors')
    1017                  if res[0] == 0:
    1018                          sol = res[1].replace(':\n ',': ').replace(':\n\t',': ').splitlines()
    1019                          for s in sol:
    1020                                  s.strip()
    1021                                  if s.startswith(sensorName):
    1022                                          try:
    1023                                                  s = s.split(':')[1].strip(' ').strip('\t')
    1024                                                  i = 0
    1025                                                  while(((s[i]>='0') and (s[i]<='9')) or (s[i]=='.') or (s[i]=='+') or (s[i]=='-')):
    1026                                                          i = i+1
    1027                                                  return float(s[0:i])
    1028                                          except:
    1029                                                  return 0
    1030
    1031
    1032
    1033
    1034
    1035
    1036
    1037
    1038
    1039  # ------------------------------------------------------------------------------
    1040  # CLASSES should not be used , calling classes from multiple screenlets instances causes erros due to gobject multiple instaces
    1041  # ------------------------------------------------------------------------------
    1042
    1043 -class Sensor (gobject.GObject):
    1044          """A base class for deriving new Sensor-types from."""
    1045
    1046          # define custom signals
    1047          __gsignals__ = dict( \
    1048                  sensor_updated  = (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, ()),
    1049                  sensor_stopped  = (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, ()) )
    1050
    1051 -        def __init__ (self, interval=1000):
    1052                  """Create a new sensor which updates after the given interval."""
    1053                  gobject.GObject.__init__(self)
    1054                  self._timeout_id        = None
    1055                  self._interval          = interval
    1056                  # start sensor timeout
    1057                  self.set_interval(interval)
    1058
    1059          # + public functions
    1060
    1061 -        def get_interval (self):
    1062                  """Get the update-interval time for this Sensor."""
    1063                  return self._interval
    1064
    1065 -        def set_interval (self, ms):
    1066                  """Set the update-interval time for this Sensor and start it."""
    1067                  if self._timeout_id:
    1068                          gobject.source_remove(self._timeout_id)
    1069                  if ms and ms > 10:
    1070                          self._interval          = ms
    1071                          self._timeout_id        = gobject.timeout_add(ms, self.__timeout)
    1072                          return True
    1073                  return False
    1074
    1075 -        def stop (self):
    1076                  """Immediately stop this sensor and emit the "sensor_stopped"-signal."""
    1077                  self.set_interval(0)
    1078                  self.emit('sensor_stopped')
    1079
    1080          # + handlers to be overridden in subclasses
    1081
    1082 -        def on_update (self):
    1083                  """Override this handler in subclasses to implement your calculations
    1084                  and update the Sensor's attributes. Must return True to emit a signal
    1085                  which can then be handled within the screenlets, returning False
    1086                  causes the Sensor to be stopped.."""
    1087                  return True
    1088
    1089          # + internals
    1090
    1091 -        def __timeout (self):
    1092                  """The timeout function. Does nothing but calling the on_update
    1093                  handler and emitting a signal if the handler returned True."""
    1094                  # call sensor's on_update-handler
    1095                  if self.on_update():
    1096                          self.emit('sensor_updated')
    1097                          return True
    1098                  # on_update returned False? Stop
    1099                  self.stop()
    1100                  return False
    1101
    1102
    1103 -class CPUSensor (Sensor):
    1104          """A very simple CPU-sensor."""
    1105
    1106 -        def __init__ (self, interval=1000, cpu=0):
    1107                  """Create a new CPUSensor which emits an 'sensor_updated'-signal after a
    1108                  given interval (default is 1000ms). The multi-cpu support is untested
    1109                  but theoretically works :)."""
    1110                  Sensor.__init__(self, interval)
    1111                  self._load      = 0
    1112                  self._cpu       = cpu
    1113
    1114          # + public functions
    1115
    1116 -        def get_load (self):
    1117                  """Return the current CPU-load."""
    1118                  return self._load
    1119
    1120          # + internals
    1121
    1122 -        def on_update (self, old_cuse=[0]):
    1123                  """Called on each interval. Calculates the CPU-load and updates the
    1124                  internal load-value."""
    1125                  try:
    1126                          f = open("/proc/stat", "r")
    1127                          tmp = f.readlines(200)
    1128                          f.close()
    1129                  except:
    1130                          print _("CPUSensor: Failed to open /proc/stat. Sensor stopped.")
    1131                          self.stop()
    1132                  line = tmp[self._cpu + 1]
    1133                  if line[0:5] == "cpu%i " % self._cpu:
    1134                          reg = re.compile('[0-9]+')
    1135                          load_values = reg.findall(line[5:])
    1136                          # extract values from /proc/stat
    1137                          cuse = int(load_values[0])
    1138                          csys = int(load_values[2])
    1139                          load = cuse + csys - old_cuse[0]
    1140                          if load < 0: load = 0
    1141                          if load > 99: load = 99
    1142                          self._load = load
    1143                          old_cuse[0] = cuse + csys
    1144                          # return True to emit the "update_event"-signal
    1145                          return True
    1146                  return False
    1147
    1148
    1149 -class MemorySensor (Sensor):
    1150
    1151 -        def __init__ (self, interval=1000):
    1152                  """Create a new RAMSensor which emits an 'sensor_updated'-signal after a
    1153                  given interval (default is 1000ms)."""
    1154                  Sensor.__init__(self, interval)
    1155                  self._freemem   = 0
    1156                  self._usedmem   = 0
    1157
    1158          # + public functions
    1159
    1160 -        def get_freemem (self):
    1161                  """Return the amount of currently free RAM."""
    1162                  return self._freemem
    1163
    1164 -        def get_usedmem (self):
    1165                  """Return the amount of currently used RAM."""
    1166                  return self._usedmem
    1167
    1168          # + internals
    1169
    1170 -        def on_update (self):
    1171                  """Called on each interval. Calculates the load and updates the
    1172                  internal values."""
    1173                  self._freemem = get_freemem()
    1174                  self._usedmem = get_usedmem()
    1175                  return True
    1176
    1177
    1178 -class NetSensor (Sensor):
    1179
    1180 -        def __init__ (self, interval=1000, device='eth0'):
    1181                  """Create a new NetSensor which emits an 'sensor_updated'-signal after a
    1182                  given interval (default is 1000ms)."""
    1183                  Sensor.__init__(self, interval)
    1184                  self._device = device
    1185                  self._downloaded, self._uploaded        = get_net_activity(device)
    1186                  self._last_down, self._last_up          = self._downloaded, self._uploaded
    1187
    1188          # + public functions
    1189
    1190 -        def get_upload_speed (self):
    1191                  """Return the current upload speed in b/s."""
    1192                  return self._uploaded - self._last_up
    1193
    1194 -        def get_download_speed (self):
    1195                  """Return the current download speed in b/s."""
    1196                  return self._downloaded - self._last_down
    1197
    1198 -        def get_uploaded (self):
    1199                  """Return the overall upload amount."""
    1200                  return self._uploaded
    1201
    1202 -        def get_downloaded (self):
    1203                  """Return the overall download amount."""
    1204                  return self._downloaded
    1205
    1206          # + internals
    1207
    1208 -        def on_update (self):
    1209                  """Called on each interval. Calculates the load and updates the
    1210                  internal values."""
    1211                  d, u = get_net_activity(self._device)
    1212                  self._last_up           = self._uploaded
    1213                  self._last_down         = self._downloaded
    1214                  self._downloaded        = int(d)
    1215                  self._uploaded          = int(u)
    1216                  #print get_net_activity(self._device)
    1217                  return True
    1218
    1219
    1220  # TEST:
    1221  if __name__ == '__main__':
    1222
    1223          # some tests
    1224          print get_hostname()
    1225          print get_net_activity('eth0')
    1226          print get_linux_version()
    1227          print get_kernel()
    1228          print get_cpu_info()
    1229
    1230          # callbacks which get notified about updates of sensor's values
    1231 -        def handle_cpusensor_updated (cs):
    1232                  print 'CPU0: %i%%' % cs.get_load()
    1233 -        def handle_ramsensor_updated (rs):
    1234                  print 'USED RAM: %i MB' % rs.get_usedmem()
    1235                  print 'FREE RAM: %i MB' % rs.get_freemem()
    1236 -        def handle_netsensor_updated (ns):
    1237                  #print (ns.get_upload_speed(), ns.get_download_speed())
    1238                  print 'UP/DOWN: %i/%i bytes/s' % (ns.get_upload_speed(),
    1239                          ns.get_download_speed())
    1240
    1241          # create sensors and connect callbacks to them
    1242          cpu = CPUSensor()
    1243          cpu.connect('sensor_updated', handle_cpusensor_updated)
    1244          ram = MemorySensor(5000)
    1245          ram.connect('sensor_updated', handle_ramsensor_updated)
    1246          net = NetSensor(1500, 'eth0')
    1247          net.connect('sensor_updated', handle_netsensor_updated)
    1248
    1249          # start mainloop
    1250          mainloop = gobject.MainLoop()
    1251          mainloop.run()
    1252