Thursday, January 14, 2010

Twitter update your energy usage using a TED 5000

The Energy Detective 5000 has an API that can be polled for data using this simple perl script that I wrote.

You can find my Twitter feed here: http://twitter.com/jgarland79power

Order your own TED 5000 here.

If you are running Debian Linux you will need to install a few dependencies:
sudo apt-get install libxml-simple-perl libwww-curl-perl

And you can automate the execution of this script with an hourly cron job:
Run: crontab -e
and then add this line (assuming you put my script in ~/bin/:
0 * * * * ~/bin/twitterpower.pl

#!/usr/bin/perl

# Written by Jason Garland @ http://blog.jasongarland.com/

my $twitter_user="jgarland79power";
my $twitter_password="super_secret_password";

my $ted_ip="192.168.3.132";

# use module
use XML::Simple;
#use Data::Dumper;
use WWW::Curl::Easy;

sub write_callback {
 my ($chunk,$variable)=@_;
 # store each chunk/line separately
 # This should be faster than using $$varable .= $chunk;
 push @{$variable}, $chunk;
 return length($chunk);
}

my $curl = WWW::Curl::Easy->new();

my @body;
$curl->setopt(CURLOPT_WRITEFUNCTION, \&write_callback);
$curl->setopt(CURLOPT_FILE, \@body);
$curl->setopt(CURLOPT_URL, "http://$ted_ip/api/LiveData.xml");
$curl->perform;
my $body=join("",@body);

# create object
$xml = new XML::Simple;

# parse XML
$data = $xml->XMLin($body);

my $PowerTDY=$data->{Power}->{Total}->{PowerTDY};

$status="used $PowerTDY watt hours of #electricity since midnight today. Find out more here: http://a1.ly/7";

print $status,"\n";
$curl->setopt(CURLOPT_URL, "http://twitter.com/statuses/update.json" );
$curl->setopt(CURLOPT_POST, 1 );
$curl->setopt(CURLOPT_POSTFIELDS, "status=$status" );
$curl->setopt(CURLOPT_USERPWD, "$twitter_user:$twitter_password" );
$curl->perform;

1 comment:

jgarland79 said...

T.E.D. linked to this article! http://theenergydetective.com/3rd-party-apps.html