#!/usr/bin/perl

use Getopt::Std;
use strict;

our %opt;

$opt{p}="/dev/ttyUSB0";

getopts("mp:h", \%opt);
if ($opt{h})
{
    print <<EOF;
This program queries a Fluke 189 with the QS command to fetch its
present reading.  Data is printed in a human-readable format by default.

Options are:

    -p port     Port to use (currently $opt{p})
    -m	        Print in machine-readable CSV format
EOF
    exit;
}

alarm(3);
$SIG{ALRM} = sub {die "No response!"};

system ("stty -F $opt{p} 9600 raw icrnl opost");

open SER, "+<$opt{p}" or die "Could not open $opt{p}";
select(SER);$|=1;select(STDOUT);
print SER "QS\r";

my $response;
read(SER, $response, 2);
die "Error 1 - unknown meaning" if (substr($response,0,1) eq "1");
die "Unknown error '$response'!" if (substr($response,0,1) ne "0");
read(SER, $response, 3);
die "Unexpected response $response" unless $response eq "QS,";

read(SER, $response, 29);

my (
    $interval,
    $dbreftype,
    $unknown1,
    $dbref,
    $tempoffset,
    $tempunit,
    $unknown2,
    $bloff,
    $timeofday,
    $proff,
    $freq,
    $unknown3,
    $digits,
    $unknown4,
    $beep,
    $unknown5
    )
    =unpack("SCH2SsCH2SLSCH2CH2CH12", $response);
if ($opt{m})
{
#   print "$time, $primaryformatted, $secondaryformatted, \"$modestring\"\n";
    printf "%.1f, %d, %d, %.1f, %d, %.1f, %d, %d, %d, %d, %d\n",
	$interval/10, $dbreftype, $dbref, $tempoffset/10, $tempunit,
	$bloff/10, $timeofday, $proff, $freq, $digits, $beep;
    exit;
}

printf	"Log Int Sec: %.1f\n", $interval/10;
printf	"DBRef is mV: %d\n", $dbreftype;
printf	"*Unknown 1:  %s\n", $unknown1 if $unknown1 ne "00";
printf	"DB Ref Val:  %d\n", $dbref;
printf	"Temp Offset: %.1f\n", $tempoffset/10;
printf	"In Celcius:  %d\n", $tempunit;
printf	"*Unknown 2:  %s\n", $unknown2 if $unknown2 ne "00";
printf	"BL Off Sec:  %.1f\n", $bloff/10;
printf	"Clock:       %d (day %d, %02d:%02d:%02d.%d)\n", $timeofday,
    int $timeofday/(36000*24),
    ($timeofday%(36000*24))/36000,
    ($timeofday%(36000))/600,
    ($timeofday%(600))/10,
    ($timeofday%(10));

printf	"Clock Raw:   %s\n", unpack("H8", pack "L", $timeofday);
printf	"Pwr Off Min: %d\n", $proff;
printf	"60Hz         %d\n", $freq;
printf	"*Unknown 3:  %s\n", $unknown3 if $unknown3 ne "00";
printf	"4 Digits:    %d\n", $digits;
printf	"*Unknown 4:  %s\n", $unknown4 if $unknown4 ne "00";
printf	"Beeps:       %d\n", $beep;
printf	"*Unknown 5:  %s\n", $unknown5 if $unknown5 ne "009001c00000";
