#!/usr/bin/perl my $battery = "/proc/acpi/battery/BAT0/state"; my $timer = "/proc/interrupts"; my $pm = { mamps => 0, volts => 0, capacity => 0, mwatts => 0, time_left => 0, ticks => 0, last_ticks => 0, }; sub get_battery_status() { my $buf = ""; open(IN, "<$battery") or printf "Could not read battery: $!\n"; read(IN, $buf, 256); #printf("Buf: %s\n", $buf); close(IN); my @rows = split("\n", $buf); foreach my $row (@rows) { $row =~ s/ +/ /g; my ($tag, $val) = split(": ", $row); #printf("%s = %s\n", $tag, $val); if ($tag eq "present rate") { ($pm->{mamps}) = split(" mA", $val); next; } if ($tag eq "remaining capacity") { ($pm->{capacity}) = split(" mAh", $val); next; } if ($tag eq "present voltage") { ($pm->{volts}) = split(" mV", $val); next; } } $pm->{mwatts} = $pm->{mamps} * $pm->{volts}; if ($pm->{mamps} > 0) { $pm->{time_left} = ($pm->{capacity} * 60 ) / $pm->{mamps}; } #printf("mamps: %i volts: %i capacity: %i mwats: %i time_left: %i\n", # $pm->{mamps}, $pm->{volts}, $pm->{capacity}, $pm->{mwatts}, $pm->{time_left}); } sub read_timer_ticks() { my $buf = ""; open(IN, "<$timer") or die "Could not open timer: $!"; read(IN, $buf, 128); close(IN); my @rows = split("\n", $buf); foreach my $row (@rows) { $row =~ s/ +/ /g; my ($tag, $val) = split(": ", $row); $tag =~ s/ +//g; #printf("%s = %s\n", $tag, $val); ($val) = split(" ", $val); if ($tag eq "0") { return($val); } } return 0; } my ($rate) = @ARGV; if ($rate eq "") { printf("Usage: %s interval_in_seconds\n", $0); exit(1); } my $mamps_sum = 0; my $volts_sum = 0; my $mwatts_sum = 0; my $measure_count = 0; sub end_up { if ($mamps_sum > 0 && $measure_count > 0){ printf("\nAverage the last %d seconds:\n", $measure_count*$rate); printf("Current: %imA\n", $mamps_sum/$measure_count); printf("Volts: %.2fV\n", $volts_sum/($measure_count * 1000)); printf("mWatts: %.2fmW\n", $mwatts_sum/($measure_count * 1000000)); exit(0); } else{ die ("Could not determine battery averages"); } } $SIG{TERM} = 'end_up'; $SIG{INT} = 'end_up'; $SIG{QUIT} = 'end_up'; my $last_ticks = 0; while (1) { get_battery_status(); $pm->{ticks} = read_timer_ticks(); my $delta_ticks = ($pm->{ticks} - $pm->{last_ticks}) / $rate; if ($pm->{last_ticks} == 0) { $delta_ticks = 0; } $pm->{last_ticks} = $pm->{ticks}; my $hours = $pm->{time_left} / 60; my $mins = $pm->{time_left} % 60; printf("Current: %imA Voltage: %.2fV Power: %.2fW %imAh ". "Time: %02i:%02ih Ticks: %iHZ\n", $pm->{mamps}, $pm->{volts} / 1000, $pm->{mwatts} / 1000000, $pm->{capacity}, $hours, $mins, $delta_ticks); $mamps_sum += $pm->{mamps}; $volts_sum += $pm->{volts}; $mwatts_sum += $pm->{mwatts}; $measure_count++; sleep $rate; }