#!/usr/bin/perl -w

#`rrdtool create powertemp.rrd --step 5 DS:Power:GAUGE:180:0:U DS:Kitchen:GAUGE:180:U:U DS:Southampton:GAUGE:180:U:U RRA:AVERAGE:0.5:1:3200 RRA:AVERAGE:0.5:6:3200 RRA:AVERAGE:0.5:36:3200 RRA:AVERAGE:0.5:144:3200 RRA:AVERAGE:0.5:1008:3200 RRA:AVERAGE:0.5:4320:3200 RRA:AVERAGE:0.5:52560:3200 RRA:AVERAGE:0.5:525600:3200 RRA:MIN:0.5:1:3200 RRA:MIN:0.5:6:3200 RRA:MIN:0.5:36:3200 RRA:MIN:0.5:144:3200 RRA:MIN:0.5:1008:3200 RRA:MIN:0.5:4320:3200 RRA:MIN:0.5:52560:3200 RRA:MIN:0.5:525600:3200 RRA:MAX:0.5:1:3200 RRA:MAX:0.5:6:3200 RRA:MAX:0.5:36:3200 RRA:MAX:0.5:144:3200 RRA:MAX:0.5:1008:3200 RRA:MAX:0.5:4320:3200 RRA:MAX:0.5:52560:3200 RRA:MAX:0.5:525600:3200`

#`rrdtool create historical.rrd --start now-26h --step 7200 DS:Power:GAUGE:86400:0:U RRA:AVERAGE:0.5:12:1000 RRA:MIN:0.5:12:1000 RRA:MAX:0.5:12:1000 RRA:LAST:0.5:1:4380`;

use Device::SerialPort qw( :PARAM :STAT 0.07 );
use Time::localtime;
my $PORT = "/dev/ttyUSB0";

my $ob = Device::SerialPort->new($PORT);
$ob->baudrate(9600);
$ob->write_settings;

open (LASTTIME, 'lasttime.txt');
my $lasttime = <LASTTIME>;
close(LASTTIME);


my $update = 0;
my $oldWatts = 0;
while (1) {
	open(SERIAL, "+<$PORT");
	print "Serial port opened\n";
	while (my $line = <SERIAL>) {
		if ($line =~ m!<ch1><watts>0*(\d+)</watts></ch1>.*<tmpr>([\d.]+)</tmpr>.*<h02>([\d.]+)</h02><h04>([\d.]+)</h04><h06>([\d.]+)</h06><h08>([\d.]+)</h08><h10>([\d.]+)</h10><h12>([\d.]+)</h12><h14>([\d.]+)</h14><h16>([\d.]+)</h16><h18>([\d.]+)</h18><h20>([\d.]+)</h20><h22>([\d.]+)</h22><h24>([\d.]+)</h24><h26>([\d.]+)</h26>!) {
			my $watts = $1;
			my $temp = $2;
			my $soton = `cat temperature`;

			my $now = int(time() / 3600);
			if ($now > ($lasttime + 1)) {
				@history = ($3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15);
				print "Need an extra ".($now - $lasttime)."hrs\n";
				for ($count = ($now - $lasttime); $count >= 0; $count--) {
					if ($count < 12) {
						my $power = 1000 * ($history[$count + 1] / 2);
						my $histTime = 3600 * ($now - 2 * $count);
						`nice -n 19 rrdtool update historical.rrd $histTime:$power`;
						print ctime($histTime).": ".$power."\n";
					}
				}
				open(LASTTIME, '>lasttime.txt');
				print LASTTIME $now;
				close(LASTTIME);
				$lasttime = $now;
			} 
			`nice -n 12 rrdtool update powertemp.rrd N:$watts:$temp:$soton`;
			`echo "power = $watts\ntemp = $temp\nsoton = $soton" > bt.properties`;
			`echo "$watts" > /var/www/current.txt`;
			`/home/ed/rrd/colours.pl $watts &`;
			$update++;
			$oldWatts = $watts;
			print "Using $watts watts, kitchen temp: $temp, soton temp: $soton";	
		}
	}
	sleep 5;
}

