#!/usr/bin/perl
#
# Copyright (c) 2002-2003 Michael Stella
# email: rrd@ this domian
#
# Simple routines to read temperature from a Dallas Semiconductor DS1920
# temperature iButton.  See http://www.ibutton.com/ for more details on the
# hardware.
#
# NOTE: this seems to fail with Linux 2.6.  I'm using 'owfs' now, rather than
# querying the serial ports directly.  Sample code to come.
#
# See http://people.ee.ethz.ch/~oetiker/webtools/rrdtool/ for more info about
# RRDTool.
#

use strict;
use RRDs;
use Hardware::iButton::Connection;


sub temp_update {
	my ($rrdpath,$host) = @_;

	my $c = new Hardware::iButton::Connection "/dev/ttyS0" or die;
	$c->reset();

	my @bs = $c->scan("10"); 

	my $temp;

	foreach my $b (@bs) {
		if ($b) {
			$temp = (($b->read_temperature_hires())*9/5 +32);
			last;
		}
	}

	my $rrd = $rrdpath . $host . '_temp.rrd'; RRDs::update($rrd, "--template",
			"temp", "N:$temp"); if (RRDs::error) { print STDERR RRDs::error .
				"\n"; } }

sub temp_create {
	my ($rrdpath, $host) = @_;

	my $rrd = $rrdpath . $host . '_temp.rrd';

	if (! -f $rrd) {
		RRDs::create($rrd, '-b' , time, '-s', 300,
				 	"DS:temp:GAUGE:300:0:U",
				 	"RRA:AVERAGE:0.5:1:600",
				 	"RRA:AVERAGE:0.5:6:700",
				 	"RRA:AVERAGE:0.5:24:775",
				 	"RRA:AVERAGE:0.5:288:797");
		if (RRDs::error) {
			print STDERR "create: " . RRDs::error . "\n";
		}
	}
}

sub temp_graph {
	my ($rrdpath,$imgpath,$host,$interval,$label) = @_;

	my $rrd = $rrdpath . $host . '_temp.rrd';
	my $image = $imgpath . $host . $label . '_temp.jpg';

	RRDs::graph($image, '--start',"-$interval", '--end', '-60',
				'-l', 50, '-u', 110, '-r',
				'--width','450',
				'--height','250',
				"DEF:temp=$rrd:temp:AVERAGE",
				'AREA:temp#00FF00:temperature',
				'COMMENT:\n',
				'COMMENT:\n',
				'GPRINT:temp:LAST: 1min   Current\\: %4.3lf ',
				'GPRINT:temp:AVERAGE:Average\\: %4.3lf ',
				'GPRINT:temp:MAX:Max\\: %4.3lf \n');

	if (RRDs::error) {
		print STDERR "Temperature graph error: " . RRDs::error . "\n";
	}
}
1;

