#!/usr/bin/perl -w

use strict;
use HTTP::Date "str2time";
use WebSphere::MQTT::Client;
use FileHandle;

local $| = 1;

my $pubclient = "/usr/local/bin/mosquitto_pub -t sensors/cc128 -q 2 -l";
my $pubclient_ch1 = "/usr/local/bin/mosquitto_pub -t sensors/cc128/ch1 -q 2 -l";
my $pubclient_ch9 = "/usr/local/bin/mosquitto_pub -t sensors/cc128/ch9 -q 2 -l";

local $| = 1;
open(PUB, "|$pubclient");
open(PUB_CH1, "|$pubclient_ch1");
open(PUB_CH9, "|$pubclient_ch9");

PUB->autoflush(1);
PUB_CH1->autoflush(1);
PUB_CH9->autoflush(1);

my $mqtt = new WebSphere::MQTT::Client(
	Hostname => 'localhost',
	Port => 1883,
);

my $mres = $mqtt->connect();
die "Failed to connect: $mres\n" if ($mres);

my $res = $mqtt->subscribe( "sensors/cc128/raw" );

while (1) {
	my @res = $mqtt->receivePub();
	my $line = $res[1];
	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;

		print PUB "$temp,$watts\n";
		print PUB_CH1 "$watts\n";
	}
	if ($line =~ m#<time>(.*)</time><tmpr>.*</tmpr><sensor>9</sensor><id>[0-9]*</id><type>2</type><imp>0*(\d+)</imp><ipu>1000</ipu></msg#){
		my $imps = $2;

		print PUB_CH9 "$imps\n";
	}
}
