#!/usr/bin/perl -w
 
$PortName = "/dev/ttyS0";
$PortName = "/dev/ftdi_temp";
# $PortName = "/dev/ttyUSB0";
$DBHOST = "charon.rotary.nu";
$DBNAME = "temperature";
$table  = "outdoor_hisingen1";

$MAX_TRIES = 10;
$DEBUG = 1;

# create database temperature;
# use temperature;
# create table outdoor1 (id INTEGER UNSIGNED not null auto_increment, time DATETIME, temp FLOAT, primary key (id));


#AVR2313, Dallas DS1820 Temperature Monitor
#(c) Daniel Vindevåg, 2004
#
#    1 DS1820 Device detected
#Device #    0 ROM Code 64 65 20 36 34 20 36 35 
#
#     5 C
#     5 C



use Device::SerialPort; # qw( :PARAM :STAT 0.07 );
use DBI;

$AVRTemp = new Device::SerialPort ($PortName) || die "Can't open $PortName: $!\n";  

 
	$AVRTemp->baudrate(9600);
	$AVRTemp->parity("none");
	$AVRTemp->databits(8);
	$AVRTemp->stopbits(1);
	$AVRTemp->handshake(CTSRTS);


	$AVRTemp->write("t0\n");			# Get temp0
	sleep 3;
    $result = $AVRTemp->input;	
    $temp = -999.9;						# Error
    if (length($result)) {
    	$temp = substr($result, 0, length($result)-3)/10;
	}

	$count = $MAX_TRIES;	
	while ($temp == -999.9 && ($count)) {
		if ($DEBUG) {
			print "error: ("  . ($MAX_TRIES - $count) . ") " .$result . "";
		}
	    sleep 1;
		$AVRTemp->write("t0\n");			# Get temp0
	    sleep 5;
	    $result = $AVRTemp->input;
	    $temp = -999.9;						# Error
	    if (length($result)) {
	    	$temp = substr($result, 0, length($result)-3)/10;
		}
	    $count--;
    }
	undef $AVRTemp;


	if ($temp == -999.9 && $DEBUG) {
		print "Error! tried $MAX_TRIES times.\n\n";
	    exit;
	}

$temp = $temp * 10;

	$add_query = "INSERT INTO $table VALUES (null, now(), '$temp')";
	if (exists($ARGV[0])) {
		print $temp/10 . " C\n";
#		print $add_query . "\n";
	} else {	
		my $db = DBI->connect("DBI:mysql:$DBNAME:$DBHOST", $DBUSER, $DBPASS);
		$DBI::result = $db->prepare($add_query);
		$DBI::result->execute();
		undef $db;
	}