#!/usr/bin/perl -w

# Reads data from a Current Cost device via serial port.

use strict;
use Device::SerialPort qw( :PARAM :STAT 0.07 );
use HTTP::Date "str2time";

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

open(SERIAL, "+<$PORT");
while (my $line = <SERIAL>) {
	if ($line =~ m#<time>(.*)</time><tmpr> *([\-\d.]+)</tmpr><sensor>0</sensor><id>[0-9]*</id><type>1</type><ch1><watts>0*(\d+)</watts></ch1></msg#){
		my $reading_time = $1;
		my $temp = $2;
		my $watts = $3;

		my $now = time;
		my $r_stamp = str2time(strftime("%Y-%m-%d", $now)." $reading_time");
		if($r_stamp > $now){
			$r_stamp -= 86400;
		}

		system("/usr/local/bin/mosquitto_pub -q 1 -t sensors/cc128/ch1 -m \"$r_stamp $watts\"");
	}
}
