package App::POS::Hardware::Scales::DIGI_DS_788;
use warnings;
use strict;
use Time::HiRes qw( sleep );
use App::POS::Hardware::Scales;

use base qw( App::POS::Hardware::Scales );

sub setup_port {
  my $s = shift;

  my $PortObj = $s->serial_obj();
  $PortObj->baudrate(9600);
  $PortObj->parity("none");
  $PortObj->databits(8);
  $PortObj->stopbits(1);
  $PortObj->handshake("none");
}

sub start {
  my $s = shift;

  my $PortObj = $s->serial_obj();

  my $sleep = 0.2;
  my $clean_after = 0;

  #SOH  0x01
  #STX  0x02
  #ETX  0x03
  #EOT  0x04
  #CR   0x0d
  #LF   0x0a
  #RS   0x1e
  #ENQ  0x05
  #NAK  0x15
  #NULL 0x00
  #DC1  0x11
  #DC2  0x12
  #CAN  0x18

  while (1) {
    $PortObj->write(chr(0x05));
    my( $count_in, $string_in ) = $PortObj->read(1);

    if ($count_in > 0) {
      if (ord($string_in) == 0x15) {
        print STDERR "error reading...\n";
      }
      else {
        # read mode 1 (only gets weight)
        $PortObj->write(chr(0x11));
        # read mode 2 (includes eur and eur/kg)
        #$PortObj->write(chr(0x12));

        my( $count_in, $string_in ) = $PortObj->read(255);

        if ($count_in > 0) {
          my( $num ) = $string_in =~ /(\d+\.\d+)/;

          if (defined $num && $num*1 > 0) {
            $clean_after = 1;
            open(N, "> /opt/pos/common/tmp/scale.txt");
            print N sprintf("%.3f", $num)."\n";
            close(N);
          }
          elsif (defined $num && $num*1 == 0 && $clean_after == 1) {
            $clean_after = 0;
            open(N, "> /opt/pos/common/tmp/scale.txt");
            print N "0\n";
            close(N);
          }
        }
      }
    }

    sleep($sleep);
  }
}

1;

