package App::POS::Hardware::Scales::CAS_PR_II;
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;

  #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

  my $wrong = 0;

  while (1) {
    # print STDERR "loop\n";
    $PortObj->write(chr(0x05));
    my( $count_in, $string_in ) = $PortObj->read(1);

    $count_in ||= 0;

    if ($count_in > 0) {
      # print STDERR "##11 $string_in ##\n";

      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) {
          # print STDERR "##22 $string_in ##\n";
          my( $num ) = $string_in =~ /(\d+\.\d+)kg/;

          if (defined $num) {
            $num = sprintf("%.3f", $num);
          }

          if ($wrong == 1) {
            open(N, "> /opt/pos/common/tmp/scale.txt");
            print N "0.000\n";
            close(N);
          }

          if ($num > 0) {
            $wrong = 0;
            open(N, "> /opt/pos/common/tmp/scale.txt");
            print N sprintf("%.3f", $num)."\n";
            close(N);
          }
          else {
            $wrong++;
          }
        }
      }
    }

    sleep($sleep);
  }
}

1;

