#!/usr/bin/perl
#
# 20060318 by Ewald
# http://www.oiepoie.nl
use RRDs;

sub CreateGraph
{
# creates the graph
# input: $_[0]: interval (ie, day, week, month, year)
#        $_[1]: $rrd
#        $_[2]: $img

	my $rrd = $_[1];
	my $img = $_[2];

	RRDs::graph "$img/logger-$_[0].png",
		"--lazy",
		"-s -1$_[0]",
		"-t Leiden temperature ",
		"-h", "200", "-w", "600",
		"-a", "PNG",
		"-v degrees C",

		"DEF:intemp=$rrd/logger.rrd:in-temp:AVERAGE",
		"LINE2:intemp#FF0000:Room    Temperature",
		"GPRINT:intemp:MIN:  Min\\: %2.lf",
		"GPRINT:intemp:MAX: Max\\: %2.lf",
		"GPRINT:intemp:AVERAGE: Avg\\: %4.1lf",
		"GPRINT:intemp:LAST: Current\\: %2.lf degrees C\\n",

		"DEF:outtemp=$rrd/logger.rrd:out-temp:AVERAGE",
		"LINE3:outtemp#0000FF:Outside Temperature",
		"GPRINT:outtemp:MIN:  Min\\: %2.lf",
		"GPRINT:outtemp:MAX: Max\\: %2.lf",
		"GPRINT:outtemp:AVERAGE: Avg\\: %4.1lf",
		"GPRINT:outtemp:LAST: Current\\: %2.lf degrees C\\n";

	if ($ERROR = RRDs::error) { print "$0: unable to generate $_[0] graph: $ERROR\n"; }
}

# location of rrdtool databases
my $rrd = '/var/rrd';
# location where the images should go
my $img = '/oiepoie/rrdtool';

# get temp for inside and outside sensors
my $tempIN  = `/usr/local/bin/logger.pl -1 -n -c -t 1`;
chop($tempIN);
my $tempOUT = `/usr/local/bin/logger.pl -1 -n -c -t 0`;
chop($tempOUT);
	
# if rrdtool database doesn't exist, create it
if (! -e "$rrd/logger.rrd")
	{
		print "creating rrd database ...\n";
		RRDs::create "$rrd/logger.rrd",
			"-s 300",
			"DS:in-temp:GAUGE:600:-20:100",
			"DS:out-temp:GAUGE:600:-20:100",
			"RRA:AVERAGE:0.5:1:576",
			"RRA:AVERAGE:0.5:6:672",
			"RRA:AVERAGE:0.5:24:732",
			"RRA:AVERAGE:0.5:144:1460";
	}

# insert value into rrd
RRDs::update "$rrd/logger.rrd", "-t", "in-temp:out-temp", "N:$tempIN:$tempOUT";
if ($ERROR = RRDs::error) { print "$0: unable to update $rrd/logger.rrd: $ERROR\n"; }

# create graphs
&CreateGraph("day",$rrd,$img);
&CreateGraph("week",$rrd,$img);
&CreateGraph("month",$rrd,$img);
&CreateGraph("year",$rrd,$img);
