#!/usr/bin/perl # # A Perl/Tk wrapper to graphically show the battery status. # # It calls 'acpi' to get the text of the battery status and # then displays a graphical bar indicating the charge status # setting the color as appropriate. # # Written by FNA on 2008/05/07 # use Tk; use Tk::ProgressBar; ### set variables $DELAY=10000; # 10 second delay $command = '/usr/bin/acpi -V'; # command to get battery status $debug = 0; # the minimum value and color for critical, low, good, and full status @Status = ( [0, "red"], [20, "yellow"], [40, "blue"], [75, "green"] ); my $rheight=10; my $rwidth=5; # create main window $mw = MainWindow->new(); $mw->geometry('70x60'); $mw->resizable(1, 0); # set up quit key bindings $mw->bind('', sub {exit}); $mw->bind('', sub {exit;}); $percentlabel= $mw->Label->pack; $canvas = $mw->Canvas(-height=>8, -width=>48, -background=>"white", -borderwidth=>2)->pack; # create 10 rectangles for the battery indicator (canvas) # each gets 2 tags, a common one ("all") and an individual one (rx) for (my $i=0; $i<10; $i++) { $canvas->createRectangle($i*$rwidth, 0, $i*$rwidth+$rwidth, $rheight, -outline=>"black", -fill=>"yellow", -tags=>["all", "r$i"]); } $extralabel= $mw->Label(-font=>"Helvetica -10 bold", -wraplength=>"80")->pack; # call the power checker now checkPower ($canvas, $percentlabel, $extralabel); # and call the power checker every $DELAY milliseconds from now on $mw->repeat($DELAY, \&checkPower, $canvas, $percentlabel, $extralabel); MainLoop; ############ # end main # ############ # # subroutine to set the value of the canvas widget # sub setVal { my ($canvas, $value) = @_; my ($color); # set the colors as appropriate $color = $Status[0][1]; # default color value (critical) for (my $i = $#Status; $i >= 0; $i--) { if ($value > $Status[$i][0]) { $color=$Status[$i][1]; last ; } } # hide all of the squares at once $canvas->itemconfigure("all", -state=>"hidden"); # set the appropriate squares to be visible and the appropriate color for (my $i=0; $i < $value/10; $i++) { $canvas->itemconfigure("r$i", -state=>"normal", -fill=>$color); } } # # subroutine to run the checking command, parse its output and # call the update subroutine # sub checkPower { my ($canvas, $label1, $label2) = @_; my ($state, $percent, $extra); # open a pipe to the acpi command and read the battery value # and a few other parameters open (ACPI, "$command |") || die "can't open pipe!"; while () { m/Battery 1: (\w+), (\d+)%,? ?([^\n]+)?/; ($state, $percent, $extra) = ($1, $2, $3); # we only care about the first line, so break out of the loop last; } close ACPI; print "Battery 1: state: [$state] $percent%, extra:[$extra]\n" if ($debug); # set the labels and battery indicator $label1->configure(-text=>"$percent%"); $label2->configure(-text=>"$extra"); setVal ($canvas, $percent); }