#!/usr/bin/perl -w
use strict;
use Getopt::Std;
use Log::Log4perl qw(:easy);
use Sysadm::Install qw(:all);
use RRDTool::OO;
use OWTemp;

Log::Log4perl->easy_init($DEBUG);

my  $RRDDB   = "/tmp/temperature.rrd";
my  $GRAPH   = "/tmp/temperature.png";

my %sensors = (
    "10.E0E3C7000800" => "Outside",
    "10.B2A7C7000800" => "Inside",
);

getopts("g", \my %o);

    # Constructor     
my $rrd = RRDTool::OO->new(
             file => $RRDDB);

    # Create a round-robin database
$rrd->create(
     step        => 300,
     data_source => { name      => "Outside",
                      type      => "GAUGE" },
     data_source => { name      => "Inside",
                      type      => "GAUGE" },
     archive     => { rows      => 5000 }) unless -f $RRDDB;

if($o{g}) {
        # Draw a graph in a PNG image
    $rrd->graph(
      start          => time() - 24*3600*3,
      image          => $GRAPH,
      vertical_label => 'Temperatures',
      draw           => {
          color  => '00FF00',
          type   => "line",
          dsname => 'Outside',
          legend => 'Outside',
      },
      draw           => {
          type   => "line",
          color  => 'FF0000',
          dsname => 'Inside',
          legend => 'Inside',
      },
      width          => 300,
      height         => 75,
      lower_limit    => 0,
    );
} else {
    my $ow = OWTemp->new();
    my %values = ();
    for my $station ($ow->temperatures()) {
        my($dev, $temp) = @$station;
        $values{$sensors{$dev}} = $temp;
    }
    $rrd->update(time => time(), values => \%values);
}
