#!/usr/bin/perl -w

## Dependencies
#
# yum install perl-Device-SerialPort 
# apt-get install libdevice-serialport-perl 

use Device::SerialPort; # qw( :PARAM :STAT 0.07 );
use File::Basename;
use strict;

my $PortName = "/dev/ttyACM0";
if ($ARGV[0]) {
	if (-e $ARGV[0]) { 
		$PortName = $ARGV[0];
	} else {
		my $n= int($ARGV[0]);
		$PortName = "/dev/ttyACM$n";
	}
}
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");

my $pn =  basename($PortName);
my $timefile = $pn . "_settime";
if ($ARGV[2]) {
	if (-e $ARGV[2]) { 
		$timefile = $ARGV[2];
	}
}

my $settime = 0;

$AVRTemp->write("ATRTCGET\n");
my $t = time();
my $local_time = $t;
sleep 1;
my $device_time = int($AVRTemp->input);

$AVRTemp->write("ATRTCOGET\n");
sleep 1;
my $device_drift = int($AVRTemp->input);

print localtime($t) . " (" . $t . ")\n";
print "port: $PortName ($pn)\n";

my $new_drift = 0;
my $new_device_drift = 0;
my $diff = $device_time - $local_time;

if (-e $timefile) {
	print "Timefile: $timefile\n";
	open TIMEFILE, "<$timefile";
	$settime = int(<TIMEFILE>);
	close TIMEFILE;
	$t = $settime;

	if ($diff) {
		$new_drift = int ( abs(($local_time-$settime)/$diff) );
		if ($device_drift) {
	 		$new_device_drift = int( abs (($device_drift*$new_drift) / ($device_drift+$new_drift)) );
		} else { $new_device_drift = $new_drift; }
	}
}


if ( (!$ARGV[1]) || ($ARGV[1] && $ARGV[1]) eq "get") {
	print "Device: " . localtime($device_time) . ", " . ($diff . "s \n");
	if ($settime) { 
		print "Last settime: $settime, [-" . ($local_time-$settime) . "], " . localtime ($settime) . "\n"; 
	}
	if ($device_drift) { print "Device drift: $device_drift \n"; }
	if ($new_drift) { print "New abs drift: $new_drift \n"; }
	if ($new_device_drift && $device_drift) { print "New device drift: $new_device_drift \n"; }
}

if ( $ARGV[1] && ($ARGV[1] eq "set")) {
	$t = time();
	$AVRTemp->write("ATRTCSET $t\n");
	sleep 1;
	my $result = $AVRTemp->input;

	#if ($new_device_drift && ( (abs($diff)<60) && (abs($diff)>10) ) && ($new_device_drift>=5) ) {
#	if ( (abs($diff) >= 10) || ($device_drift && abs($diff) >= 5)) {
	if ( (abs($diff)<20) && (  (abs($diff)>=10) || ($device_drift && abs($diff)>=5) ) ) {
		$AVRTemp->write("ATRTCOSET $new_device_drift\n");
		sleep 1;
		$result = $AVRTemp->input;
	}

	open TIMEFILE, ">$timefile";
	print TIMEFILE "$t\n";
	close TIMEFILE;
}


print "\n";
$AVRTemp->close();

