#!/usr/bin/perl -w
use strict;
use Time::HiRes qw(gettimeofday);

my ($buf, $cur_rate, $rem_cap, $cur_volts, $sec, $usec, $last_graph);

open(BAT_FD, "</proc/acpi/battery/BATA/state");
open(LOG_FD, ">>acpi.log");

select(LOG_FD); $| = 1;
select(STDOUT); $| = 1;

$last_graph = 0;
print "set term x11 noraise\n";
print "set xdata time\n";
print "set timefmt \"%s\"\n";
print "set format x \"%H:%M\"\n";
print "set xrange [\"" . (time() - (60*30)) . "\":]\n";
print "set palette defined ( 0 \"red\", 1 \"blue\", 2 \"yellow\", 3 \"green\" )\n";

while (1) {
	while (defined($buf = <BAT_FD>)) {
		if ($buf =~ /^present rate:\s+(\d+) mW/) {
			$cur_rate = $1;
		} elsif ($buf =~ /^remaining capacity:\s+(\d+) mWh/) {
			$rem_cap = $1;
		} elsif ($buf =~ /^present voltage:\s+(\d+) mV/) {
			$cur_volts = $1;
		}
	}
	($sec, $usec) = gettimeofday;
	
	printf(LOG_FD "%d.%06d %d %d %d\n", $sec, $usec, $cur_rate, $rem_cap, $cur_volts);
	
	seek(BAT_FD, 0, 0);
	sleep 1;
	$last_graph++;

	if ($last_graph >= 5) {
		print << '_EOF_';
plot \
"acpi.log" using 1:($2) t "(Dis)charge Rate (mW)" with lines, \
"acpi.log" using 1:($3) t "Remaining (mWh)" with lines, \
"acpi.log" using 1:($2) t "" with lines smooth bezier, \
"acpi.log" using 1:($4) t "Battery Voltage (mV)" with lines
_EOF_
		$last_graph = 0;
	}		
}
