#!/usr/bin/perl

# Run as "mosquitto_sub -t <topic> | google_powermeter_update.pl"
# Assumes topic messages are in the format "<unix timestamp> <power reading in watts>"
# Or run as "echo <timestamp> <power> | google_powermeter_update_duration.pl"

use strict;
use LWP::UserAgent;
use POSIX qw(strftime);
use Data::Dumper;

# userID is your 20-digit google powermeter id
my $userID = "";

# variableID is the combination of device manufacturer, device model and device
# id and variable name, as when you activated the device.
# Separate the fields with a full stop: mfg.model.id.varname e.g. CurrentCost.CC128.1234.d1
# This code assumes you're using one dvar.
my $variableID = "";

# The auth token you received on activating your device (32 chars)
my $authtoken = "";


my $ua = LWP::UserAgent->new;
my $req = HTTP::Request->new(POST => $posturl);
$req->header('Authorization' => "AuthSub token=\"$authtoken\"");
$req->content_type('application/atom+xml');

while(<STDIN>){
	chomp;
	my @words = split(/ /);
	my $timestamp = @words[0];
	my $power = @words[1];

	my $reading_time = strftime("%Y-%m-%dT%H:%M:%S.000Z", gmtime($timestamp));
	my $kwh = ($power/600)/1000; # http://currentcost.posterous.com/calculating-kwh-from-watts

	my $msg = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".
			"<entry xmlns=\"http://www.w3.org/2005/Atom\" xmlns:meter=\"http://schemas.google.com/meter/2008\">\n".
			"<meter:startTime meter:uncertainty=\"1.0\">$reading_time</meter:startTime>\n".
			"<meter:duration meter:uncertainty=\"0.1\">6.0</meter:duration>\n".
	    		"<meter:quantity meter:uncertainty=\"0.001\" meter:unit=\"kW h\">$kwh</meter:quantity>\n".
			"</entry>\n";


	$req->content($msg);
	my @res = $ua->request($req);
	#print Dumper( @res );
}

