#!/usr/bin/perl
#
# CGI script to create image using RRD graph 
use CGI qw(:all);
use RRDs;
use strict;

# path to database
my $rrd='/media/pi/SSD/Data/temperature.rrd';

# size
my $width=700;
my $height=250;
my $currentyear = (localtime)[5] + 1900;
my $copyright = $currentyear .= " © www.tiarora.no";

# read and check query params
my $query=new CGI;
my $interval=$query->param('interval');
$interval='day' unless $interval =~ /hour|day|week|month|year/; 

# write image into temp file
my $tmpfile="/media/pi/SSD/temp/graphx_$$.png";
my @opts=("-v", "°C",
"-t Temperature/$interval",
"-w", $width,
"-h", $height,
"-s", "now - 1 $interval",
"-e", "now",
"--slope-mode",
"-a", "PNG",
"-W",$copyright,
"-D");

RRDs::graph($tmpfile,
  @opts,
  "DEF:Inside=$rrd:Inside:AVERAGE",
  "LINE2:Inside#E1E400:Inside",
  "VDEF:Insidelast=Inside,LAST",
  "GPRINT:Insidelast:%.1lf°C",
  "DEF:Engine=$rrd:Engine:AVERAGE",
  "LINE2:Engine#00FF00:Engine",
  "VDEF:Enginelast=Engine,LAST",
  "GPRINT:Enginelast:%.1lf°C",
  "DEF:Exhaust=$rrd:Exhaust:AVERAGE",
  "LINE2:Exhaust#0000FF:Exhaust",
  "VDEF:Exhaustlast=Exhaust,LAST",
  "GPRINT:Exhaustlast:%.1lf°C"
);

# check error
my $err=RRDs::error;
die "$err\n" if $err;

# feed tmpfile to stdout
open(IMG, $tmpfile) or die "can't open $tmpfile\n";
print header(-type=>'image/png', -expires=>'+1m');
print <IMG>;
close IMG;
unlink $tmpfile;

