//
// siftcom.c - help utility to communicate with topfield sift
//

#include <stdio.h>   
#include <stdlib.h>   
#include <string.h>  
#include <unistd.h>  
#include <fcntl.h>   
#include <errno.h>   
#include <termios.h> 

#define BUFZ 1000

int main(int ar, char *as[])
{
  struct termios options;
  int fd, fdo;
  char buffer[1024];  
  char cmd[255];  
  int nbytes;      

  if (ar < 2) { 
    perror("parameter missing");
    exit(0);
  }
	 
  fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NDELAY);
  if (fd == -1)
    perror("open_port: Unable to open /dev/ttyUSB0");
  
  fdo = open("output.dat", O_RDWR | O_CREAT | O_TRUNC);
  if (fd == -1)
    perror("open_file: error");
  
  fcntl(fd, F_SETFL, 0);

  tcgetattr(fd, &options);
  cfsetispeed(&options, B115200);
  cfsetospeed(&options, B115200);

  options.c_cflag     |= (CLOCAL | CREAD);
  options.c_lflag     &= ~(ICANON | ECHO | ECHOE | ISIG);
  options.c_oflag     &= ~OPOST;
  options.c_cc[VMIN]  = 0;
  options.c_cc[VTIME] = 15;
  
  /* set the options */
  tcsetattr(fd, TCSANOW, &options);

  sprintf(cmd, "\r\n*\r\n%s\r\n", as[1]);
  write(fd, cmd, strlen(cmd));
  
  while(1) {
    nbytes = read(fd, buffer, BUFZ);
    if (nbytes == 0) break;
    write(fdo, buffer, nbytes);
    buffer[nbytes]=0;
    if (strstr(buffer, "READY") != NULL) 
      break;
  }
    
  sprintf(cmd, "\r\n#\r\n");
  write(fd, cmd, strlen(cmd));

  close(fd);
  close(fdo);
  
  return 0;
}

