#!/usr/bin/perl -w

use strict;
use warnings;

use Getopt::Long;

my $opt_help;
my $opt_device;
my $opt_baudrate;

GetOptions (
	    'h|help'        => \$opt_help,
	    'd|device=s'    => \$opt_device,
	    'b|baudrate=i'    => \$opt_baudrate,

);


$opt_baudrate = 115200 if(!defined $opt_baudrate);

if ($opt_help || !defined $opt_device || defined $ARGV[0]) {
  print "Error: No device argument given!\n" if (!defined $opt_device);
  print "Error: more than device as an argument. What should this mean?\n" if (defined $ARGV[0]);

  print <<EOF;
usage: slurp_serial [-h] --device=<device>|-d <device> [--baudrate=<baudrate>|-b <baudrate>]

slurp_serial connects to a serial device and reads the stream and adds some time information to it.

<-d device>: is expected in the format: /dev/xxx, so normally /dev/ttyUSB0 or /dev/hadcon.
[-b <baudrate>]: typically 115200
EOF

exit;
}



my $c = "stty -F $opt_device -opost -onlcr -isig -icanon -iexten -echo -echoe -echok -echoctl -echoke speed $opt_baudrate";

print "setting up interface $opt_device: baud rate: $opt_baudrate\n";
#print "return after stty setting: ";
qx($c);

#$c = "cat $a";

my $ln = 0;

LOOP: while (1) {
    print "trying to read from device $opt_device\n";
    my $fh;
    my $or = open $fh, "<$opt_device";
    if (!defined $or || $or == 0 || !defined $fh) {
	sleep 1;
	next LOOP;
    }
    #print "fh: $fh\n";
    while (<$fh>) {
	my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
	printf "%3.3d %2.2d:%2.2d:%2.2d: %s", $ln, $hour, $min, $sec , $_;
	$ln++;
    }
    sleep 1;
}

