#!/usr/bin/perl

use Device::SerialPort;

$port_in_use = '/dev/ttyUSB1';

if ($PortObj = new Device::SerialPort ("$port_in_use")){
	print STDERR "opening $port_in_use just fine\n";
} else {
	print STDERR "port $port_in_use not opening!\n";
	exit;
}

$baud = 19200;

print STDERR "*\n" unless $PortObj->baudrate($baud);

$PortObj->parity("none");
$PortObj->databits(8);
$PortObj->stopbits(1);
$PortObj->read_const_time(100);       # 100 milliseconds 
$PortObj->read_char_time(5);       #was 5   # avg time between read char
$PortObj->buffers(4096, 4096);  # read, write
$PortObj->parity_enable(0); 
$PortObj->write_settings || undef $PortObj;
print STDERR "Can't change Device_Control_Block: $^E\n" unless ($PortObj);


$line = "";
$saved_min = {};

while(1){

	($count, $char) = $PortObj->read(1);
	if ($count > 0) {
		if ($char eq "\n") {
			if ($line =~ /ds18b20\[([0-9A-F]+)\]=(\d+\.\d+)/) {
				to_db("ds", $1, $2);
			}
			elsif ($line =~ /ADC\[(\d+)\]=(\d+)/) {
				to_db("adc", $1, $2);
			}
			else {
#				print $line ."\n";
			}
			
			$line = "";
		}
		else {
			$line .= $char;
		}
	}
}
exit;


sub to_db
{
	($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();

	if ($saved_min[$_[0]][$_[1]] != $min) {
#		print $mday .".". $mon .".". ($year + 1900) ." ". $hour .":". $min .": ";
#		print $_[0] ." id=". $_[1] ." = ". $_[2] ."\n";

		$cmd = "echo 'insert into arduino (date, channel, `key`, value) values (unix_timestamp(), \"". $_[0] ."\", \"". $_[1] ."\", ". $_[2] .")' | mysql -pmaster adc";
		`$cmd`;

		$saved_min[$_[0]][$_[1]] = $min;
	}
}