// Testing serial communication to EyeBot7 I/O board
// Thomas Bräunl, UWA 2018
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <termios.h>

#define BAUD 9600
#define PATH "/dev/ttyACM0"
#define LEN    100 
#define PARITY 0
#define BLOCK  0


void init(int fd)
{ struct termios tty;
  memset (&tty, 0, sizeof tty);
  if (tcgetattr (fd, &tty) != 0) { printf("error tcget\n"); exit(1); }
  cfsetspeed (&tty, B115200);
    
  //start control flags
  tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8;     // 8-bit chars
  tty.c_cflag |= (CLOCAL | CREAD);// ignore modem controls,
  // enable reading
  tty.c_cflag &= ~(PARENB | PARODD);      // shut off parity
  tty.c_cflag |= PARITY;
  tty.c_cflag &= ~CSTOPB;
  //tty.c_cflag &= ~CRTSCTS;          // added back in for 0a0a-bug TB @@@
    
  // disable IGNBRK for mismatched speed tests; otherwise receive break
  // as \000 chars
  tty.c_iflag &= ~IGNBRK;
  tty.c_iflag &= ~(IXON | IXOFF | IXANY); // shut off xon/xoff ctrl
  tty.c_lflag = 0;                // no signaling chars, no echo,

  // no canonical processing
  tty.c_oflag = 0;                // no remapping, no delays
  
  //start special flags
  tty.c_cc[VMIN]  = BLOCK;        // read doesn't block
  tty.c_cc[VTIME] = 5;            // 0.5 seconds read timeout

  if (tcsetattr (fd, TCSANOW, &tty) != 0) { printf("error tcset\n"); exit(1); }
}


int main()
{ char sstr[LEN], rstr[LEN];
  int  n=0, m, i, fd; // port id

  printf("Connect to EyeBot7-IO\n");
  //SERInit(IOBOARD, BAUD, 0); // first USB connection
  fd = open (PATH, O_RDWR | O_NOCTTY | O_SYNC);
  init(fd);
  if (fd<0) { printf("error port\n"); return 1; }
  do
  { printf("Enter string: ");
    i=-1;
    do sstr[++i]=getchar(); while (sstr[i]!='\n');
    sstr[i+1] = (char) 0; // terminate string
    printf("Send(%2d): %s", strlen(sstr), sstr);
    sstr[i  ] = '\r';     // CR required for IO-board ...

    //SERSend(IOBOARD, sstr);
    m = write(fd, sstr, strlen(sstr));
    if (!m) printf("error write\n");
    usleep(100000); // 0.1s

    //n = SERReceive(IOBOARD,rstr,LEN-1);
    n = read(fd, rstr, LEN-1);
    if (n>=0) rstr[n] = (char) 0; // terminate string
         else rstr[0] = (char) 0; // n is neg. for error

    printf(" Rec(%2d): \"%s\"\n", n, rstr);
  } while (strcmp(sstr, "end\r") != 0);

  //SERClose(IOBOARD);
  tcdrain(fd);
    close(fd);
  return 0;
}
