#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <time.h>
#include <fcntl.h>
#include <strings.h>
#include <termios.h>
#include <signal.h>

#define BAUDRATE B19200
#define SERIALDEVICE "/dev/ttyUSB0"
#define _POSIX_SOURCE 1		/* POSIX compliant source */

#define MAX_BUF_LENGTH 32
#define RESULT_LENGTH 12

#define START_CHAR 'S'

int fd;
struct termios oldtio;

void
sigint_handler (int sig)
{
  //printf ("Caught SIGINT\n");
  tcflush (fd, TCIFLUSH);
  tcsetattr (fd, TCSANOW, &oldtio);
  signal (SIGINT, SIG_DFL);
  close(fd);
  kill (getpid (), SIGINT);
}


int
main (void)
{
  int bytes_read;
  int i;
  int n_read;
  unsigned char input_buf[MAX_BUF_LENGTH];
  unsigned char output_buf[MAX_BUF_LENGTH];
  unsigned char result[RESULT_LENGTH + 1];

  struct timeval now;
  time_t time_sec;
  double seconds;
  suseconds_t time_usec;  


  struct termios newtio;


//Set up to catch SIGINT
  if (signal (SIGINT, sigint_handler) == SIG_ERR)
    {
      perror ("ERROR: Unable to assign SIGINT Handler Routine\n");
      return 1;
    }


// Open Serial Port
  fd = open (SERIALDEVICE, O_RDWR, 0);
  //printf ("fd = %d \n", fd);
  if (fd < 0)
    perror ("ERROR: Can't open file for reading\n");


  tcgetattr (fd, &oldtio);	/* save current port settings */

  bzero (&newtio, sizeof (newtio));
  newtio.c_cflag = BAUDRATE | CS8 | CLOCAL | CREAD;
  newtio.c_iflag = IGNPAR;
  newtio.c_oflag = 0;
/* set input mode (non-canonical, no echo,...) */
  newtio.c_lflag = 0;
  newtio.c_cc[VTIME] = 0;	/* inter-character timer unused */
  newtio.c_cc[VMIN] = 0;	/* blocking read until 1 chars received */

  tcflush (fd, TCIFLUSH);
  tcsetattr (fd, TCSANOW, &newtio);


  output_buf[0] = 'O';
  output_buf[1] = 'D';
  output_buf[2] = 13;
  output_buf[3] = 0;

  write (fd, output_buf, 3);
  while (1)
    {
      while (!read (fd, input_buf, 1));
      if (input_buf[0] == START_CHAR)
	{
	  // Read Payload
	  bytes_read = 0;
	  while (bytes_read < RESULT_LENGTH)
	    {
              gettimeofday (&now, NULL);
              time_sec = now.tv_sec;
              time_usec = now.tv_usec;
	      n_read = read (fd, input_buf, RESULT_LENGTH - bytes_read);
	      for (i = 0; i < n_read; i++)
		result[bytes_read + i] = input_buf[i];
	      bytes_read = bytes_read + n_read;
	    }
          seconds = (double) time_sec + (double) time_usec/1000000;
	  result[RESULT_LENGTH] = 0;
	  printf ("%d.%6.6d %5.5s %5.5s %c\n", time_sec,time_usec,result,result+6,result[11]);
          //usleep(1000000);
	  write (fd, output_buf, 3);
	}

    }





}
