#!/usr/bin/perl

#This script is intended for use on a Raspberry Pi Type B, Raspbian “wheezy”
#You should install libdevice-serialport-perl and libdatetime-perl package via "sudo apt-get"
# you can find connected SQM-LU device assigned as follows:
#  ls /dev | grep tty.usbserial
# Use the name shown that matches your serial number from the
# above command in the $serial_device line below.

# Put a link to this script in your crontab for repetetive logs
# to $logbase (defined below).


 use Device::SerialPort;
 use DateTime;

 # Define values for this specific installation
 $timeout_sec = 2;
 #$serial_device = "/dev/tty.usbserial-FTE02BG1";
 $serial_device = "/dev/ttyUSB1";
 $rx_char_count = 56;

 eval {
  local $SIG{ALRM} = sub { die "alarm\n" };
  # Set timeout in seconds
  alarm $timeout_sec; 

  # Define base name for log directory
  $logbase = 'sqmlulog/';
 
  # Get current date and time
  $dt = DateTime->now;
  
  # Define the timezone
  $dt->set_time_zone( 'Europe/Istanbul' );
 
  # Create logfile name for this day
  $logfile =sprintf("%sada%04d%02d%02d.log", $logbase,
                    $dt->year, $dt->month, $dt->day_of_month);

  # Create error file name for this day
  $errfile =sprintf("%sada%04d%02d%02d.err", $logbase,
                    $dt->year, $dt->month, $dt->day_of_month);

  # Open file to capture STDERR messages
  open(STDERR, ">> $errfile") ||
     die("Can't open error file $errfile!\n");

  # Open and configure serial port
  $port= Device::SerialPort->new("$serial_device") ||
     die("Can't open $port: $^E\n");

  $port->user_msg(ON);
  $port->baudrate(115200);
  $port->parity("none");
  $port->stopbits(1);
  $port->databits(8);
  $port->handshake("none");
  $port->write_settings || undef $port;
  $port->read_char_time(1); # Wait for each character

  ($port->write("rx\r") == 3) ||
     die("Issuing command rx for delivery of response string failed!\n");

  $chars = 0;
  $buffer = "";
  while ($chars < $rx_char_count) {
    ($count,$saw)=$port->read(255);
    if ($count > 0) {
       $chars+=$count;
       $buffer.=$saw;
    }
  }

  $time_read = sprintf("%8s", $dt->hms);

  $port->close || 
    die("Serial port failed to close!\n");
  undef $port;

  # If we got this far before the timeout period, reset the alarm
  alarm 0; 
};

if ($@) {
  die unless $@ eq "alarm\n";
  print(STDERR "%s Read of device timed out!\n", $time_read);
} else {
  # Split up returned string
  printf("%s", $buffer);
  #open(LOGFILE, ">> $logfile") ||
  #   die("Can't open logfile $logfile!\n");
  #   printf(LOGFILE "%s %9d %9d %03d\n",
  #                  $time_read, $c5250, $c5777, $status);
  #close(LOGFILE);
}

exit 0;
