#!/usr/bin/perl
$debug = 0;
$timeout = 20;
open(HLT,"+</dev/ttyS0") or die "serial port: $?";
select HLT; $|=1; select STDOUT; $|=1;
system("stty 1200 </dev/ttyS0");
sub hammer {
    print HLT pack("C", 0x10);
    $SIG{"ALRM"} = "hammer";
    alarm($timeout);
}

$SIG{"ALRM"} = "hammer";
alarm(1);

# orange bank
# orange probe: 10e4e929000000c4  
# green  probe: 1058b029000000d8
# purple probe: 10b8a12900000040
# black  probe: 10e80f0f00000086

# green bank:
# orange probe: 109cfc2900000053  
# green  probe: 10a3b629000000ce
# purple probe: 102bcb2900000004
# black  probe: 1010b32900000042

$colors{"10e4e929000000c4"} = "orange/orange";
$colors{"1058b029000000d8"} = "orange/green";
$colors{"10b8a12900000040"} = "orange/purple";
$colors{"10e80f0f00000086"} = "orange/black";
$colors{"109cfc2900000053"} = "green/orange";
$colors{"10a3b629000000ce"} = "green/green";
$colors{"102bcb2900000004"} = "green/purple";
$colors{"1010b32900000042"} = "green/black";

$location{"orange/orange"}	= "near a/c";
$location{"orange/green"}	= "paycheck drives";
$location{"orange/purple"}	= "marbles cpu";
$location{"orange/black"}	= "b/r door";
$location{"green/orange"}	= "unused 1";
$location{"green/green"}	= "unused 2";
$location{"green/purple"}	= "out window";
$location{"green/black"}	= "unused 3";



$state = "none";
while(<HLT>) {
    chomp;
    if (/^V(\d*)-(\d*)$/) {
	$state = "gotV";
	$firmware = $1;
	$serial = $2;
	$probenum = 2;
	next;
    }
    next if ($state eq "none");	# suck it down until we see the V
    if (/^S(\d)$/) {
	$state = "gotS";
	$bitval = $1;
    }
    if (/^T(.{16}) ([-+]\d\d\d\.\d)/) {
	$state = "gotT";
	$sample{$1} = $2;
	$unit{$1} = $probenum;
	$probes{$probenum} = $1;
	$probenum++;
    }
    if (/^Z$/) {
	print "Firmware: $firmware  Serial: $serial  Wire State: $bitval\n"
	    if $debug;
	my $t = time;
	my @tstmp = localtime($t);
	my $fname = sprintf("T%04d%03d", $tstmp[5]+1900, $tstmp[7]);
	open(OUT, ">>$fname");
 	print OUT ": ".localtime($t)."/$t\n";
	%oldsample = %sample if not defined %oldsample;
	foreach (sort keys %probes) {
	    if ($debug) {
		print "Probe $_ Temp $sample{$probes{$_}} Tag $probes{$_} ";
		print "Color: $colors{$probes{$_}} ";
		print "Delta: ",$sample{$probes{$_}}-$oldsample{$probes{$_}},"\n";
	    }
	    print OUT "$sample{$probes{$_}} (";
	    printf OUT "%4.2f",$sample{$probes{$_}}-$oldsample{$probes{$_}};
	    print OUT "): $location{$colors{$probes{$_}}}\n";
	}
	undef %probes;
	undef %unit;
	%oldsample = %sample;
	undef %sample;
	close(OUT);
    }
}
