package App::POS::Hardware::Scales::TOWA_OZ15L;
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;
  my $tmp = 0;

  while (1) {
    if ($tmp == 0) {
      $tmp = 1;
      $PortObj->write(chr(5));
    }
    else {
      $tmp = 0;
      $PortObj->write(chr(17));
    }

    #sleep $sleep;

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

    if ($count_in > 0) {
      my @a = split //, $string_in;
      my $str = "";

      for (my $i=0; $i<scalar @a; $i++) {
        $s->debug("BALANCA - ".ord($a[$i]));

        if ($i >= 4 && $i <= 9) {
          $str .= _c($a[$i]);
        }
      }

      my $num = $str;

      if (defined $num && $num ne '') {
        $s->debug("PESO: ".($num*1));

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

    sleep $sleep;
  }
}

sub _c {
  my $c = shift;

  if (ord($c) > 128) {
    return chr(ord($c)-128);
  }
  else {
    return $c;
  }
}

1;

