#!/usr/bin/perl -w

# Reads data from a Current Cost device via serial port.
# Saves data to an RRD file.
# Taken from http://www.jibble.org/currentcost/

use strict;
use Device::SerialPort qw( :PARAM :STAT 0.07 );
use RRDs;

my $PORT = "/dev/ttyUSB0";
my $rrdfile = "powertemp.rrd";

my $ob = Device::SerialPort->new($PORT);
$ob->baudrate(57600);
$ob->write_settings;
local $| = 1;

if (! -e "$rrdfile") {
	RRDs::create "$rrdfile",
		"--step 5",
		"DS:Power:GAUGE:180:0:U",
		"DS:Temperature: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";
}

open(SERIAL, "+>$PORT");
while (my $line = <SERIAL>) {
	if ($line =~ m!<ch1><watts>0*(\d+)</watts></ch1>.*<tmpr> *([\-\d.]+)</tmpr>!) {
		my $watts = $1;
		my $temp = $2;
		print "$watts, $temp\n";
		RRDs::update "$rrdfile", "N:$watts:$temp";
	}
}

