#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <unistd.h>
#include <signal.h>
#include <fcntl.h>

int file_descriptor;

void serial_interrupt(int signo) {
  char c;
  
  fprintf(stderr,"interrupted\n");

  while (read(file_descriptor,&c,1)==1)
    fprintf(stderr,"received 0x%x\n",c);

}

void open_serial_port(char *port) {

  int flags;

  struct termios tty_conf;
  file_descriptor=open(port, O_RDWR | O_NONBLOCK );

  if (file_descriptor<0) {
    perror(port);
    exit(file_descriptor);
  }

  tcgetattr(file_descriptor, &tty_conf);

  cfsetspeed(&tty_conf, B300);  // baudrate
  cfmakeraw(&tty_conf);
	
  // Set the new options for the port...
  tcflush(file_descriptor, TCIFLUSH);
  tcsetattr(file_descriptor, TCSANOW, &tty_conf);


  // set O_ASYNC so that we get SIGIO'd when a character comes in
  flags=fcntl(file_descriptor, F_GETFL);
  fcntl(file_descriptor, F_SETFL, flags | O_ASYNC);
  
}

int main( int argc, char *argv[] ) {
  
  if (argc!=2) {
    printf("one argument, the serial port (e.g. /dev/ttyS1)\n");
    exit(1);
  }

  if (signal (SIGIO, serial_interrupt) == SIG_ERR) {
    printf ("Can't handle SIGIO\n");
    exit(2);
  }

  open_serial_port(argv[1]);

  for (;;) {
    // Well, let's do something in the mainloop...

    int i;
    printf("\nwaiting...");
    for (i=0; i<10; i++) {
      fflush(stdout);
      printf(".");
      sleep(1);
    }
    write(file_descriptor,"abcd",4);
  }
    
}
