#!/usr/bin/env python import pygtk pygtk.require('2.0') import gtk, gnome.applet import time import os import string last=-1 # Conversion done with rgb.txt and bc gtk.rc_parse_string(''' style "red" { bg[NORMAL] = "#ee0000" fg[NORMAL] = "#eedd82" } widget "*.red" style "red" style "green" { bg[NORMAL] = "#00cd66" fg[NORMAL] = "#000000" } widget "*.green" style "green" style "blue" { bg[NORMAL] = "#36648b" fg[NORMAL] = "#eedd82" } widget "*.blue" style "blue" ''') # alternative is to put this into file and use gtk.rc_parse("filename") style=("red","green","blue") def generate_label(): fin=os.popen("cat /proc/acpi/battery/BAT1/[si]*",'r') rate='4000' chargedir = '?' current='0' maxbat='4000' while 1: line = fin.readline() if line == '': break words=string.split(line) if words[0] == 'charging' and words[1] == 'state:': if words[2] == 'discharging': chargedir = '-' elif words[2] == 'charging': chargedir = '+' else: chargedir = '=' if words[0] == 'present' and words[1] == 'rate:': if words[3] == 'mA': rate=words[2] else: print 'unknown units in rpesent rate=',words #sys.exit(1) if words[0] == 'remaining' and words[1] == 'capacity:' : if words[3] == 'mAh': current=words[2] else: print 'unknown units in remaining',words #sys.exit(1) if words[0] == 'last' and words[1] == 'full': if words[2] == 'capacity:': if words[4] == 'mAh': maxbat = words[3] else: print 'unknown units in maxbat',words #sys.exit(1) fin.close() frate=float(rate) fcurrent=float(current) fmaxbat=float(maxbat) ipercent=int( 100*float(current)/float(maxbat)+0.5 ) if chargedir == '-': timeleft=str(int(60*fcurrent/frate)) elif chargedir == '+': timeleft=str(int(60*(fmaxbat-fcurrent)/frate)) else: timeleft='' return ipercent,chargedir,chargedir+str(ipercent)+'% '+timeleft def update_label(): global last global style curr,dir,labstr = generate_label() label.set_text(labstr) if curr>35: curr=2 elif curr>8: curr=1 else: curr=0 # Now beep if going down if last != curr and dir=='-': os.system("/bin/echo -e \a") if last != curr: last=curr for w in [label,event_box,frame]: w.set_name(style[curr]) frame.show_all() return gtk.TRUE app = gnome.applet.Applet("python-battery") frame = gtk.GtkFrame() label = gtk.GtkLabel() label.set_padding(1,1) # Create an EventBox and add it to our toplevel window event_box = gtk.GtkEventBox() frame.add(event_box) event_box.show() event_box.add(label) update_label() app.add(frame) app.set_tooltip("Python battery") app.show() gtk.timeout_add(2000, update_label) gtk.mainloop()