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

#define REPLYSZ 128

typedef int Serial_t;


void SerialSetBaud( int serial_fd, int BaudRate ) {
  struct termios termios;   
  tcgetattr(serial_fd, &termios); 
  cfsetspeed(&termios, BaudRate); 
  tcsetattr(serial_fd, TCSANOW, &termios);
}


int main(void) {

   Serial_t port;
   char string[REPLYSZ];
   char * sptr;
   char * eptr;
   
   unsigned char out[REPLYSZ];
   int co;
   int i;
   
   if ((port = open("/dev/ttyS0", O_RDWR)) < 0) return 1; // exit if open fails, dont care why
   SerialSetBaud( port, 9600);

 //  strcpy(string, "Hello world\r\n");
   
printf(" Enter a space-seperated series of hex (0x0B) \n\
or decimal (11) bytes to send to serial port ttyS0 \n\
empty line will exit\n");
 do {
    printf("> ");
    fflush(stdout);
    fgets(string, REPLYSZ, stdin);
    
    if (strlen(string) < 2) break;
    
    sptr = NULL;
    eptr = string;
    co   = 0;
    while(sptr != eptr) {
      sptr = eptr;
      out[co] = strtol(sptr, &eptr, 0);
      co++;
    }
    co --;
//    printf("Found %d numbers\n", co-1);
    
//   printf("%u %s (%d)\n", string, string, strlen(string));
//   write(port, string, strlen(string));

     printf("sending values: ");
     for(i = 0; i < co; i++) {
       printf("0x%X ",out[i]);
     }
     printf("\n");

     write(port, &out[0], co);
        
} while(strlen(string) > 2) ;

   
   close(port);
   
   return 0;

}


// poll()
