package App::POS::Hardware::Scales::BIZERBA_CS300;

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("odd");
  $PortObj->databits(7);
  $PortObj->stopbits(1);
  $PortObj->handshake("none");
}

sub start {
  my $s = shift;

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

  my $sleep = 0.2;

  while (1) {
    if (-e "/tmp/scale_data.txt") {
      open(N, "< /tmp/scale_data.txt");
      my @t;
      while (<N>) {
        s/\n//g;
        s/\r//g;
        my $line = $_;
        @t = split /#/, $line;
        last;
      }
      close(N);
      unlink "/tmp/scale_data.txt";

      if (scalar @t && scalar(@t) == 2) {
        $t[0] = string_normalize($t[0]);
      }
      else {
        @t = ( '', '' );
      }

      $PortObj->write(
        chr(4).chr(2)."04".chr(27).
        $t[1].chr(27).$t[0].chr(3)
      );

      sleep 0.2;
      $PortObj->write(chr(4).chr(5));
      sleep 0.2;

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

      $s->debug("chars read: $count_in, string_read: #$string_in#");

      if ($count_in > 2) {
        my $weight = substr($string_in, 7, 5);
        $weight ||= 0;

        if ($weight > 0) {
          $weight = $weight / 1000;
        }

        open(N, "> /opt/pos/common/tmp/scale.txt");
        print N sprintf("%.3f", $weight)."\n";
        close(N);
      }
    }

    sleep $sleep;
  }
}

sub string_normalize {
  my $str = shift;

  $str =~ tr/áéíóúàèìòùâêîôûãõç/aeiouaeiouaeiouaoc/;
  $str =~ tr/ÁÉÍÓÚÀÈÌÒÙÂÊÎÔÛÃÕÇ/AEIOUAEIOUAEIOUAOC/;

  return $str;
}

1;

