#!/usr/bin/perl
#
# subscribe.pl
#
# Subscribe to a MQTT topic
# and display message to STDOUT
#

use WebSphere::MQTT::Client;
use Data::Dumper;
use RRDs;
use strict;

my $rrdfile = "powertemp.rrd";

# Create rrd file if it doesn't already exist
if (! -e $rrdfile){
	RRDs::create($rrdfile,
		"-s 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");
	my $ERR=RRDs::error;
	die "ERROR while creating $rrdfile: $ERR\n" if $ERR;
}

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

# Connect to Broker
my $res = $mqtt->connect();
die "Failed to connect: $res\n" if ($res);

print Dumper( $mqtt );

sleep 1;
print "status=".$mqtt->status()."\n";
sleep 1;
print "status=".$mqtt->status()."\n";

# Subscribe to topic
my $res = $mqtt->subscribe( 'sensors/cc128/raw' );
print "Subscribe result=$res\n";

sleep 2;
print "status=".$mqtt->status()."\n";

#$| = 1;

# Get Messages
while( 1 ) {
	my @res = $mqtt->receivePub();
	my $data = $res[1];

	if ($data =~ m!<tmpr>\s*(-*[\d.]+)</tmpr><sensor>0</sensor>.*<ch1><watts>0*(\d+)</watts></ch1>!) {
		my $watts = $2;
		my $temp = $1;
		RRDs::update $rrdfile, "N:$watts:$temp";
	}
}

# Unsubscribe from topic
my $res = $mqtt->unsubscribe( 'sensors/cc128/raw' );
print "Unsubscribe result=$res\n";

sleep 2;

print "status=".$mqtt->status()."\n";

# Clean up
$mqtt->terminate();

print Dumper( $mqtt );

