#!/usr/bin/perl
#
# Protocolo DIGI DS788
#

use strict;
use warnings;
use Device::SerialPort;

my $STX = chr(0x02);
my $ETX = chr(0x03);
my $ACK = chr(0x06);
my $ENQ = chr(0x05);
my $TAB = chr(0x11);
my $LF = chr(10);
my $CR = chr(13);
my $SCALE_ERROR = chr(0x15);

my $port = shift;
my $baud = shift || "9600";
my $parity = shift || "none";
my $databits = shift || "8";
my $stopbits = shift || "1";
my $handshake = shift || "none";

die "missing port" unless defined $port;

my $PortObj = Device::SerialPort->new($port);
$PortObj->baudrate($baud);
$PortObj->parity($parity);
$PortObj->databits($databits);
$PortObj->stopbits($stopbits);
$PortObj->handshake($handshake);

my $count_in;
my $string_in;
my $num;
my $ntries=1;
my $value_found = 0;

while ($ntries < 10) {
	$PortObj->write($ENQ);
      ( $count_in, $string_in ) = $PortObj->read(1);

      if ($count_in > 0) {
        if (ord($string_in) == 0x15) {
          print STDERR "error reading...\n";
        }
        else {
          $PortObj->write(chr(0x11));
          ( $count_in, $string_in ) = $PortObj->read(255);
 	  if ($count_in eq 15) {
 	    my( $num ) = $string_in =~ /(\d+\.\d+)/;
 	    if (defined $num && $num*1 > 0) {
              print  sprintf("%.3f", $num)."\n";
              $value_found =1;
            }
          }	  
	}
       }
sleep 0.5;

$ntries = $ntries+1;
}
if ($value_found eq 0) {
  print "ERROR";

}

