#!/bin/ksh

# Ksh is needed for some of the math I'm doing.

# Change TTY to the port to which you actually have the UPS connected.

TTY=/dev/ttyS18

# default of 60 seconds between polls
interval=60
if [ $# = 1 ] ; then
    interval=$1
fi

VERBOSE=0
while : ; do

# Set up communications with the UPS

stty  -icanon min 0 time 20 2400 ixon ixoff -crtscts clocal  < $TTY | (
sleep 1
echo "Z" > $TTY
read HUH < $TTY
[ $VERBOSE = 1 ] && echo $HUH

echo "Z" > $TTY
read HUH < $TTY
[ $VERBOSE = 1 ] && echo $HUH

echo "Ax 1" > $TTY
read HUH < $TTY
[ $VERBOSE = 1 ] && echo $HUH
if [ "$HUH" = "OK" ] ; then
    [ "$VERBOSE" = 1 ] && echo "Communications established." >&2
fi


echo "Sg 65535" > $TTY
read HUH < $TTY
[ $VERBOSE = 1 ] && echo $HUH

echo "Sx 7" > $TTY
read HUH < $TTY
[ $VERBOSE = 1 ] && echo $HUH

echo "Sx 1" > $TTY
read HUH < $TTY
[ $VERBOSE = 1 ] && echo $HUH

echo "Si" > $TTY
read HUH < $TTY
[ $VERBOSE = 1 ] && echo $HUH



inner=0
#By this point we should have communication
while : ; do
if [ "$inner"  -gt 10 ] ; then
    echo "I'm missing values consistantly!" >&2
    exit 1
fi
echo "Uv" > $TTY
read UV < $TTY

echo "Ll" > $TTY
read Ll < $TTY

echo "Bn" > $TTY
read Bn < $TTY

echo "Bl" > $TTY
read Bl < $TTY

echo "Bv" > $TTY
read Bv < $TTY

if [ -z "$UV" -a -z "$Ll" -a -z "$Bn" -a -z "$Bl" ] ; then
    tries=$(($tries+1))
    if [ $tries -gt 3 ] ; then
	[ "$VERBOSE" = 1 ] && echo " Bad communications. Syncing to the UPS" >&2
	break # return to outer while
    else
        continue
    fi
fi
tries=0

OK=0
for X in $UV $Bn $Bv ; do
    if [ $X -lt 100 ] ; then	# we got a short reply
	OK=1
    fi
done
if [ "$OK" != 0 ] ; then
    continue
fi


if [ -z "$UV" -o -z "$Ll" -o -z "$Bn" -o -z "$Bl" -o -z "$Bv" ] ; then
    inner=$(($inner+1))
    continue	# we are missing a value
fi

export UV Li Bn
eval `for X in UV  Bn Bv ; do
Y=\`eval echo \$"$X"\`
Y=\`echo $Y | sed "s/\(.*\)\(..\)\$/\1.\2/"\`
    eval  echo \$X="$Y"
done
`
echo "`date +%m%d%H%M` Util = $UV  Load = $Ll% Runtime = $Bn Bat volt/Cap = $Bv/$Bl%"
sleep $interval
inner=0
done  ) 

done	# outer while

