#!/usr/bin/perl -w
#
# prologix.pl

use strict;
use vars qw( $OS_win $ob $port );
use POSIX qw(setsid);
use Getopt::Std;
use Device::SerialPort;
use Time::HiRes qw(usleep);

#----------
# some variables that need to be declared
my $quiet = "1";
my $count = 0;
my $lockfile;
my $reading;
my $temp1;
my $temp2;
my $tmp1 = 0;
my $tmp2 = 0;
my $bat;

#----------
# handle signals and errors -- mainly to clear lockfile on termination
sub sig_handler {
	undef $ob;
	if (-e $lockfile) {unlink $lockfile;}
	close LOG;
	exit(0);
}

# there's got to be a better way!
$SIG{'HUP'} = 'sig_handler';
$SIG{'INT'} = 'sig_handler';
$SIG{'KILL'} = 'sig_handler';
$SIG{'STOP'} = 'sig_handler';
$SIG{'TERM'} = 'sig_handler';
#----------

#----------
# display usage
my $opt_string = 'dh:f:p:';

sub usage() {
print STDERR << "EOF";

usage: $0 [-adh] -f logfile -i log_interval -p serial_port
-d	: run as daemon
-h	: this (help) message
-f	: logfile using full pathname;
	  for output to console, use "-f -"
-p	: serial port ("ttyS1")

EOF
}
#----------

#----------
# daemonize
sub daemonize {
	chdir '/' or die "Can't chdir to /: $!";
	umask 0;
	open STDIN, '/dev/null' or die "Can't read /dev/null: $!";
	open STDOUT, '>/dev/null' or die "Can't write to /dev/null: $!";
	open STDERR, '>/dev/null' or die "Can't write to /dev/null: $!";
	defined(my $pid = fork) or die "Can't fork: $!";
	exit if $pid;
	setsid or die "Can't start a new session: $!";
}
#----------

getopts( "$opt_string", \my %opt ) or usage() and exit;

# print usage
usage() and exit if $opt{h};

# run as daemon?
&daemonize if $opt{d};

# set variables to command line params
my $portbase = $opt{p};
my $logfile = $opt{f};

#----------
# set up serial port
my $port = "/dev/" . $portbase;
$lockfile = "/var/lock/LCK.." . $portbase;
$ob = Device::SerialPort->new ($port,$quiet,$lockfile);
die "Can't open serial port $port!\n" unless ($ob);

$ob->baudrate(115200)	|| die "fail setting baud after 0";
$ob->parity("none")	|| die "fail setting parity";
$ob->databits(8)	|| die "fail setting databits";
$ob->stopbits(1)	|| die "fail setting stopbits";
#$ob->handshake("none")	|| die "fail setting handshake";
$ob->write_settings || die "no settings";

#----------
# set up logfile
open (LOG, ">>$logfile") ||
	die "Can't open logfile $logfile!\n";
# set nonbuffered mode
select(LOG), $| = 1;

#----------
$ob->write("+++mode\r\n");
# get serial port reading
$reading = $ob->input;
print $reading,"\n";

exit 0;
