Package screenlets :: Module sensors
[hide private]
[frames] | no frames]

Source Code for Module screenlets.sensors

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