#!/usr/bin/perl -w
###########################################
# rrdlog - Graph Temperature Data
# Mike Schilli, 2010 (m@perlmeister.com)
###########################################
use strict;
use local::lib;
use RRDTool::OO;
use DateTime::Format::Strptime;

my $logfile     = "temper.log";
my @data_points = ();
my $rrd_file    = "data.rrd";

my $date_fmt =
  DateTime::Format::Strptime->new(
    pattern   => "%Y/%m/%d %H:%M:%S",
    time_zone => "local",
);

  # Read logged temperature data
open FILE, "$logfile" or
    die "Cannot open $logfile ($!)";
while( <FILE> ) {
  if( /(.*) READ (.*)/ ) {
    my($datestr, $temp) = ($1, $2);

    my $dt = 
      $date_fmt->parse_datetime($datestr);
    push @data_points, 
         [$dt->epoch(), $temp];
  }
}
close FILE;

  # Create RRD
my $rrd = RRDTool::OO->new(
  file        => $rrd_file,
  raise_error => 1,
);

my $rows = 60*24*30;

$rrd->create(
  step => 60*5,
  data_source => {
    name    => "temp",
    type    => "GAUGE" 
  },
  archive => { 
      rows => $rows,
      cpoints => 1,
      cfunc   => 'AVERAGE',
  },
  start => $data_points[0]->[0] - 60,
  hwpredict   => { 
      rows            => $rows,
      alpha           => 0.1,
      beta            => 0.0035,
      gamma           => 0.5,
      seasonal_period => 24*60/5,
      threshold       => 14,
      window_length   => 18,
  },
);

for my $data_point (@data_points) {
  $rrd->update(
      time  => $data_point->[0],
      value => $data_point->[1],
  );
}

  # Draw Graph
$rrd->graph(
  image => "bounds.png",
  width  => 1600,
  height => 800,
  start => $data_points[0]->[0],
  end   => $data_points[-1]->[0],
  draw => {
    type   => "line",
    color  => '000000',
    legend => "Temperature over Time",
    thickness  => 2,
    cfunc      => 'AVERAGE',
  },
  draw           => {
    type   => "line",
    color  => '00FF00',
    cfunc  => 'HWPREDICT',
    name   => 'predict',
    legend => 'hwpredict',
  },
  draw           => {
    type   => "hidden",
    cfunc  => 'DEVPREDICT',
    name   => 'dev',
  },
  draw           => {
    type   => "hidden",
    name   => "failures",
    cfunc  => 'FAILURES',
  },
  tick => {
    draw => "failures",
    color  => '#FF0000',
     legend => "Failures",
  },
  draw => {
    type   => "line",
    color  => '0000FF',
    legend => "Upper Bound",
    cdef   => "predict,dev,2,*,+",
  },
  draw => {
    type   => "line",
    color  => '0000FF',
    legend => "Lower Bound",
    cdef   => "predict,dev,2,*,-",
  },
);
