#!/usr/bin/perl -wU

use strict;
use IO::Handle;
use Switch;
use bytes;


my $log = "ups_log";
my $serial_line = "/dev/ttyS0";
my $verbose_option = "V";
my $tty_cmd = "stty -F " . $serial_line . " 2400 cs8 ignpar -echo -echok -icrnl -ixon -ixoff ixany -icanon -opost -onlcr time 12 min 0";

open( UPSLOG, ">>",$log) || die( "open error $log $?");
open( TTY,"+<",$serial_line ) || die( "open serial line error: $serial_line $?");

autoflush TTY;
autoflush UPSLOG;

my @args = ( $tty_cmd  );
my $tty_status = system(@args);
if ( $tty_status != 0 ) {
  die ("status:$tty_status stty cmd failed for $tty_cmd $?");
}

logmsg ("$0 started.");

my $response = sendsw("Q1");
print "UPS Status:$response\n";



logmsg ("$0 ended.");

#----------------------------------------------------------


sub logmsg {
    my ( $logmessage ) = @_;
    my $timestamp = localtime;
    print UPSLOG "$timestamp\t$logmessage\n";
}

    
sub sendsw {
    my ( $sendmsg ) = @_;
    my $timeout = 0;
    my $result = "";
    print TTY "$sendmsg\r"; # Megatech terminates with a c/r
    logmsg( "send:$sendmsg");

WAITLOOP:
    while ( $timeout < 5 ) {
        $timeout++;
        while (  ) {
            $result = $_;
            logmsg( "recv: $_");
            last;
        }
	last if ( length( $result ) > 0 );
    }
    return "TIMEOUT" if $timeout >= 5;
    return $result;
}