#!/s/std/bin/perl -w
# cold-air-aisle.pl
#
# create PNGs of the cold air aisle temperatures
# 
#
# $Id: cold-air-aisle.pl,v 1.2 2010/07/28 18:44:33 koczan Exp $
#

use warnings;

use lib "/s/lab/src/1wire/lib/site_perl";
use GD;
use GD::Graph::Thermometer;

use Data::Dumper;

use CSL::Pg;
use CSL::DBs;
use DBI;

my $tries = 5;
my $dbh;

foreach (1..$tries) {
  $dbh = DBI->connect($CSL::DBs::csdb);
  if ($dbh) {
    $dbh->do("set search_path to sensornet");
    last;
  } else {
    sleep 5;
  }
}

# wow, this *really* failed
die $DBI::errstr if (!$dbh);




#sensor list and nametag that you want graphs for
my %sensorhash = (
    '75000001C8035728', '2350 Liebert',
    '9D000001C8163028', '2N3N Liebert',
    'B7000001C7DDFC28', '8N9N Liebert',
    '13000001C7FD5C28', '11N12N Liebert',
);

################################################################################
# functions
################################################################################



# get_sensor_location -- return xyz location of specified device id
sub get_sensor_data{
    local ($id) = @_;

    my $query = $dbh->prepare("SELECT value
                               FROM data
                               WHERE (id = ? or lower(id) = ?)
                               order by time desc limit 1");


    $query->execute( $id, $id);
    $data = $query->fetchrow_hashref;
    return (($data->{value}) * 1.8 + 32);
}



################################################################################
# do some work 
################################################################################

#iterate over keys in sensor hash, make a png for each
foreach $device (keys %sensorhash) {
    my $temperature = get_sensor_data($device);
    my $filename = "/u/s/t/strivia/public/html/1wire/$device.png";


     my $result = GD::Graph::Thermometer->new({
 	image_path => $filename,
 	type => 'png',
 	goal => '120',
 	current => get_sensor_data($device),
 	title => $sensorhash{$device},
 	width => '200',
 	height => '400',
 	transparent => '0',
     });


}
exit 0;
