#!/usr/bin/perl

# This program reads from Two SQM-LU devices (defined below)
# The sample rate is every one second (defined near end).

# From DOS, type :
#   perl multifast.pl
# or to log to a file:
#   perl multifast.pl >> logfile.csv


use Cwd 'abs_path';

use if ($^O eq "MSWin32"), Win32::SerialPort;
use if ($^O ne "MSWin32"), Device::SerialPort;

if ($^O eq "MSWin32") {
	# Windows
	$Device0="COM113";
	$Device1="COM93";
	$port0= Win32::SerialPort->new($Device0) ||  die("Can't open $port0: $^E\n");
	$port1= Win32::SerialPort->new($Device1) || die("Can't open $port1: $^E\n");
} else {
	# Unix
	$Device0="/dev/ttyUSB0";
	$Device1="/dev/ttyUSB1";
	$port0= Device::SerialPort->new($Device0) ||  die("Can't open $port0: $^E\n");
	$port1= Device::SerialPort->new($Device1) || die("Can't open $port1: $^E\n");
}

$port0->user_msg(ON);
$port0->baudrate(115200);
$port0->parity("none");
$port0->stopbits(1);
$port0->databits(8);
$port0->handshake("none");
$port0->write_settings || undef $port;
$port0->read_char_time(1); # Wait for each character


$port1->user_msg(ON);
$port1->baudrate(115200);
$port1->parity("none");
$port1->stopbits(1);
$port1->databits(8);
$port1->handshake("none");
$port1->write_settings || undef $port;
$port1->read_char_time(1); # Wait for each character

#Continuous loop
while (1) {

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

	printf ("%04d-%02d-%02d, %02d:%02d:%02d, ",$year+1900,$mon+1,$mday,$hour,$min,$sec);
	($port0->write("rx\r") == 3) || die("Issuing command rx for delivery of response string failed!\n");

	($count,$saw)=$port0->read(72);
	printf $Device0;
	if ($saw eq ""){
		printf "  << Error nothing reported >>\n";
	} else {
		printf ", %s",$saw;
	}

	printf ("%04d-%02d-%02d, %02d:%02d:%02d, ",$year+1900,$mon+1,$mday,$hour,$min,$sec);
	($port1->write("rx\r") == 3) || die("Issuing command rx for delivery of response string failed!\n");

	($count,$saw)=$port1->read(72);
	printf $Device1;
	if ($saw eq ""){
		printf "  << Error nothing reported >>\n";
	} else {
		printf ", %s",$saw;
	}

	#-- Delay between readings
	sleep(1);
}


$port0->close || die("Serial port failed to close!\n");
undef $port0;

$port1->close || die("Serial port failed to close!\n");
undef $port1;
