#!/usr/bin/perl

# Get thermostat temperatures & setpoint, and post to Pachube

use HTTP::Request::Common qw(POST);
use WWW::Mechanize;
use LWP::UserAgent;
use MIME::Lite;
use MIME::Base64;
use Getopt::Std;
use JSON;
use strict;

use vars qw/ %opt /;

my $debug = 0;

my $apikey = "API_KEY";
my $feed_id = "FEED_ID";
my $url="http://www.pachube.com/api/feeds/" . $feed_id . ".csv";
my $a = WWW::Mechanize->new();


my $temp1 = my $temp2 = my $target1 = my $target2 = "";

my $host;
my $tempurl;
my $scalar;

my $ua = LWP::UserAgent->new;

# Yes, ok, this should be a function...

# Main Floor
$host = "thermostat1";
$tempurl = "http://$host/tstat";
my $req = HTTP::Request->new(GET => $tempurl);
my $res = $ua->request($req);
if ($res->is_success) {
	$scalar = from_json($res->content);
	$temp1 = $scalar->{ 'temp' };
	$target1 = $scalar->{ 't_heat' } if $scalar->{ 't_heat' };
}
print $res->content . "\n" if $debug;

# Basement
$host = "thermostat2";
$tempurl = "http://$host/tstat";
my $req = HTTP::Request->new(GET => $tempurl);
my $res = $ua->request($req);
if ($res->is_success) {
	$scalar = from_json($res->content);
	$temp2 = $scalar->{ 'temp' };
	$target2 = $scalar->{ 't_heat' } if $scalar->{ 't_heat' };
}
print $res->content . "\n" if $debug;

print $res->content . "\n" if ($temp1 == -1);

print $temp1 . ", " . $temp2 . ", " . $target1 . ", " . $target2 . "\n" if $debug;


# Send it all to Pachube
my $ua = LWP::UserAgent->new;
$ua->default_header(
                "X-PachubeApiKey" => $apikey,
                "Content-Type" => "text/csv; charset=utf-8");
my $request = HTTP::Request->new(PUT => $url);
$request->content($temp1. "," . $temp2. "," . $target1. "," . $target2);

my $res = $ua->request($request);
if (! $res->is_success) {
	print $res->status_line, "\n" if $debug;
}
print " sent  " if $debug;

exit;


