#!/usr/bin/perl -w

my $PortName = "/dev/temp";
#my $PortName = "/dev/ttyACM0";
my $MAX_TRIES = 10;

# DB
my $DBHOST = "localhost";
#$DBHOST = ""; # no local DB
my $DBNAME = "temperature";

my $tz = "Europe/Berlin";
#my $tz = "America/Los_Angeles";

my $add_query = "INSERT INTO %s VALUES (null, now(), %d)";

# Sensor 1;
my $table1 = "nattsjo_outdoor1";
my $webreport1 = "http://www.rotary.nu/temp/nattsjo/report.php";

# Sensor 2;
my $table2 = "nattsjo_indoor1";
my $webreport2 = "http://www.rotary.nu/temp/nattsjo_indoor1/report.php";

# Sensor 2;
#my $table2 = "sf_bayview_indoor1";
#my $webreport2 = "http://www.rotary.nu/temp/sf_bayview_indoor1/report.php";

# Sensor 1;
#my $table1 = "sf_bayview_outdoor1";
#my $webreport1 = "http://www.rotary.nu/temp/sf_bayview/report.php";


# New commands
my $list_cmd 	= "ATTl";
my $scan_cmd 	= "ATTs";
my $read_cmd 	= "ATTt";
my $reboot_cmd 	= "ATr";


# CREATE TABLE nattsjo_test2 (id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, 
#	time DATETIME, temp SMALLINT, PRIMARY KEY(id));


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


my $n = 0;
my $t = 9999;
my $sensor_count;
my $table = "";
my $webreport;
my $AVRTemp = new Device::SerialPort ($PortName) || die "Can't open $PortName: $!\n";  

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

sub read_temp;

# Get args
if ($ARGV[0]) {
	$n= int($ARGV[0]);
}

# No args, scan and print sensors; exit
if (!$n) { 
#	$AVRTemp->write("$scan_cmd\n");
#	sleep 1;
#	my $result = $AVRTemp->input;
#       print $result;
	$AVRTemp->write("$list_cmd\n");
	sleep 1;
	my $result = $AVRTemp->input;
	print $result;
	$n = get_nsensors();
	while ($n) {
		print "Sensor $n: " . read_temp($n--) / 10 . " C\n";
	}
	exit; 
}

# Read senson n
while ($MAX_TRIES) {
	$sensor_count = get_nsensors();
	if ($sensor_count && ($n <= $sensor_count)) {
		$t = read_temp($n);
#		if ($t != 9999 && $t != 850) {
		if ($t < 500) {
			last;
		}		
	}
	print "Error count: " . $MAX_TRIES-- . ", T = $t\n";
	# reboot();
        $AVRTemp->write("$scan_cmd\n");
        sleep 1;
        my $result = $AVRTemp->input;
	chomp($result);
	print $result . "\n";
}

# Error after x tries
if (!$MAX_TRIES) {
	print "Error: sensors found $sensor_count\n";
	exit(1);
} 

# Which sensor?
if ($n == 1) {
    $table = $table1;
    $webreport = $webreport1;
}
if ($n == 2) {
    $webreport = $webreport2;
    $table = $table2;
}
$add_query = sprintf($add_query, $table, $t);


# If param 2, debug-mode othervise enter into db
if ($ARGV[1]) {
	print "Sensor $n ($sensor_count): " . $t / 10 . " C\n";
	print "$add_query\n";
} else {
	if ($DBHOST) {
		my $db = DBI->connect("DBI:mysql:$DBNAME:$DBHOST", $DBUSER, $DBPASS);
		$DBI::result = $db->prepare($add_query);
		$DBI::result->execute();
		undef $db;
	}
	if ($webreport) {
		get("$webreport?pw=$PASSWORD&temp=$t");
	}
}




# Report number of sensors
sub get_nsensors {
	my $ignore;
	my $n = 0;
	$AVRTemp->write("$list_cmd\n");
	sleep 1;
	my $result = $AVRTemp->input;
	if ($result) {
		my @lines = split(/\n/, $result);	
		if ($lines[0] =~ m/Sensors found: \d/) {
			($ignore, $n) = split": ",($lines[0]);
		}
	} 
	return int($n);
}

# Read temp fronm sensor n
sub read_temp {
	my ($n) = @_;
	my $decicelsius = 9999;	
	my $ignore;
	$AVRTemp->write("$read_cmd$n\n");
	sleep 1;
	my $result = $AVRTemp->input;
	my @lines = split(/\n/, $result);	
	if (($lines[0] =~ m/Sensor \d: \d/) | ($lines[0] =~ m/Sensor \d: -\d/) ) {
		($ignore, $decicelsius) = split":",($lines[0]);
		($decicelsius, $ignore) = split" ",($decicelsius);
	} else {
		$decicelsius = 9999;
	}
	return int($decicelsius);
}

# Reboot firmware
sub reboot {
		$AVRTemp->write("$reboot_cmd\n");
		$AVRTemp->close();
		sleep 4;
		$AVRTemp = new Device::SerialPort ($PortName) || die "Can't open $PortName: $!\n";  
}