// Testing serial communication to EyeBot7 I/O board
// Thomas Bräunl, UWA 2018
// Serial init code from:
//https://os.mbed.com/users/4180_1/notebook/raspberry-pi-and-mbed-communication-using-the-usb-/
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
#include <stdlib.h>

#define BAUD 9600
#define PATH "/dev/ttyACM0"
#define LEN    100 

void init(int fd)
{ // Open the Port. We want read/write, no "controlling tty" status, 
  fd = open("/dev/ttyACM0", O_RDWR | O_NOCTTY | O_NDELAY);  
  //open mbed's USB virtual com port
  if (fd == -1) { printf("error open /dev/ttyACM0\n"); exit(1); }
  // Turn off blocking for reads, use (fd, F_SETFL, FNDELAY) if you want that
  fcntl(fd, F_SETFL, 0);
  //Linux Raw serial setup options
  struct termios options; 
  tcgetattr(fd,&options);   //Get current serial settings in structure
  cfsetspeed(&options, B9600);   //Change a only few
  options.c_cflag &= ~CSTOPB;
  options.c_cflag |= CLOCAL;
  options.c_cflag |= CREAD;
  cfmakeraw(&options);
  tcsetattr(fd,TCSANOW,&options);    //Set serial to new settings
  sleep(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;
}
