#!/usr/bin/perl
use warnings;
use strict;
# sudo apt install libdevice-serialport-perl libdata-dump-perl
use Device::SerialPort;
use Time::HiRes;
use Data::Dump qw(dump);

my $debug = $ENV{DEBUG} || 1; # FIXME 0
$|=1;

my $port;

print "Plug in USB serial adapter connected to ZC sensor\n";

open(my $udev, '-|', 'udevadm monitor -k');
while(<$udev>) {
	chomp;
	if ( m{\sadd\s.*/(ttyUSB\d+)\s} ) {
		$port = $1;
		print "Found new serial port $port\n";
		sleep 1;
		last;
	} else {
		print "## $_\n" if $debug;
	}
}

my $s = new Device::SerialPort( "/dev/$port" ) || die "serial /dev/$port: $!";
$s->baudrate(115200);
$s->databits(8);
$s->parity('none');
$s->stopbits(1);
$s->handshake('none');
$s->read_char_time(100);
$s->read_const_time(15000); # ms - 1.5s
$s->debug(1);

while (1) {

	my $string = $s->lookfor;
	if ( $string ) {
		$string =~ s{\r$}{}; # remove cr
		my $t = int( Time::HiRes::time() * 1_000_000_000 );

		print "# $string\n" if $debug;

		if ( $string eq 'L620 power on fail' ) {
			print "ERROR: $string\n";
		}
	} else {
		sleep 1;
	}
};


$s->close;
