#!/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.pl"

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

# 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.c1
# If you used cvars=1 then variable is probably c1, dvars then d1 etc.
# This code assumes you're using one cvar.
my $variableID = "";

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


my $posturl = "https://www.google.com/powermeter/feeds/user/$userID/$userID/variable/$variableID/instMeasurement";
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:occurTime meter:uncertainty=\"1.0\">$reading_time</meter:occurTime>\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);
}

