#!/usr/bin/perl

use strict;
use warnings;

use lib "/opt/pos/lib";
use Time::HiRes qw( sleep );
use App::POS::Config;
use Device::SerialPort qw( :STAT );

die "Needs to be run by root...\n" unless $ENV{USER} eq 'root';

my $daemon_name = 'DallasReaders';

&init();

# kill other instances running
my @pids = `ps -eo pid,args | grep read_dallas | grep -v grep | cut -c1-6`;

for (@pids) {
  chop;
  s/\s+//g;
  next if $_ eq $$;
  system("kill -9 $_  2> /dev/null");
}

my $cfg = App::POS::Config->new( file => "/opt/pos/etc/config.ini" );

my $devices = $cfg->devices_by_type($daemon_name);

if (! scalar @$devices) {
  &log("No devices configured...");
  die "$0 - No devices configured\n";
}

my $num = $devices->[0]->{num};
my $info = $devices->[0]->{device};

&log("> read_dallas_reader - ".$info->{Device});

if (! exists $info->{Device} || ! $info->{Device}) {
  &log("Missing 'Device' parameter...");
}
else {
  $info->{InitSystemCommand} ||= "";

  if ($info->{InitSystemCommand}) {
    my $device = $info->{Device};
    $info->{InitSystemCommand} =~ s/\@DEVICE\@/$device/g;
    &log("Will execute: ".$info->{InitSystemCommand});
    my $res = system($info->{InitSystemCommand});
    &log("Result: $res");
  }

  my $PortObj = Device::SerialPort->new($info->{Device});

  if (! $PortObj) {
    &log("Can't open ".$info->{Device}.": $!");
    die "ERROR ON PORT - ".$info->{Device};
  } else {
    $PortObj->baudrate(9600);
    $PortObj->parity("none");
    $PortObj->databits(8);
    $PortObj->stopbits(1);
    $PortObj->handshake("none");

    my $collect = 0;
    my $read = "";
    my $logout = 0;

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

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

        for my $c (@chars) {
          my $n = ord($c);

          # logout
          if ($n == 242) {
            $collect = 0;
            $read = "";
            $logout = 1;
          }
          elsif ($n == 241) {
            $collect = 1;
            $logout = 0;
          }
          else {
            if ($collect) {
              $read .= $c;
            }
          }
        }

        if ($logout) {
          &log("### logout: $logout, read: $read");
          open(N, "> /tmp/logout.txt");
          close(N);
        }
        else {
          if (length($read) > 16) {
            $read = substr($read, 0, 15);
          }

          if (length($read) == 16) {
            &log("### login!!!, read: $read");
            open(N, "> /opt/pos/common/tmp/barcode.txt");
            print N "66666".$read;
            close(N);
            
            $read = "";
          }
        }
      }

      sleep 0.2;
    }
  }
}

sub log {
  my $m = shift;

  open(F, ">> /root/logs/$daemon_name.log");
  print F "$m\n";
  close(F);
}

sub init {
  open(F, "> /root/logs/$daemon_name.pid");
  print F "$$\n";
  close(F);

  unlink "/root/logs/$daemon_name.log";
}

