/* Allows low-level device communication over the 
   serial port. */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <sys/types.h>
#include <sys/time.h>

#define TIMEOUT 256

char device[32];
int serial_fd;

void init_serial_port(void)  {
  struct termios term;
  int val;

  serial_fd=open(device, O_RDWR | O_NONBLOCK);
  if( isatty(serial_fd) == 0 ) {
    printf("Fatal: invalid port.\n");
    exit(1);
  }
  
  /* get, modify, and save terminal characteristics */
  tcgetattr(serial_fd, &term);
  term.c_cflag=CS8; /* 8N1 */
  term.c_cflag |= (CREAD | /* enable receiver */
		   HUPCL | /* lower modem lines on last close */
		   CLOCAL ); /* ignore modem status lines */
   term.c_oflag = 0; /* turn off all output processing */
  term.c_iflag = IGNBRK | IGNPAR; /* ignore break, parity errors
				     also no XON/XOFF flow control */
  term.c_lflag = 0; /* turn off canonical mode, sig generation, echo */
  term.c_cc[VMIN]=1; /* return at least 1 byte */
  term.c_cc[VTIME]=0; /* block indefinately */
  
  /* 4800 baud both ways */
  cfsetispeed(&term, B9600);
  cfsetospeed(&term, B9600);
  
  /* set attribs */
  tcsetattr(serial_fd, TCSANOW, &term);
  /* turn off nonblocking */
  /*val=fcntl(serial_fd, F_GETFL, 0);
  val &= ~O_NONBLOCK;
  fcntl(serial_fd, F_SETFL, val);*/
}

int wait_for_input(void)
{
  fd_set rset;
  unsigned char byte;
  struct timeval time = {5,0}; /* wait 5 seconds */

  FD_ZERO(&rset);  /* clear the descriptor set */
  FD_SET(serial_fd,&rset); /* this is the descriptor we care about */
  if(select(serial_fd+1,&rset,NULL,NULL,&time)) { /* check the return val */
    read(serial_fd,&byte,1); /* read 1 byte */
    return byte;
  }
  /* something went wrong */
  return TIMEOUT;
}



/* The way to write data to the port is:
  write(serial_fd, buffer, n) where n is # of chars, buffer is
  a char array
*/

void main(int argc, char **argv) {
  char buffer[100];
  int i;

  if (argc < 2) {
    fprintf(stderr, "usage: %s [water|drain|abort]\n", argv[0]);
    exit(1);
  }

  strcpy(device, "/dev/cua0");

  init_serial_port();
  write(serial_fd, argv[1], 1);

  for (i=0; i<10; i++) {
    if (read(serial_fd, buffer, 1) > 0) 
      printf("%c", buffer[0]);
  }
  printf("\n");

  exit(0);
}



