/*
 *Serial control code inspired by Chuck Schied's serial routines.
 */

#include "SerialPort.hh"

bool SerialPort::closePort(void)
   {
   return close(port) == 0;
   }

bool SerialPort::openPort(void) {
  if((port = open(SERIAL_PORT, O_RDWR|O_NOCTTY, 0)) == -1) {
      return false;
  }
  termios termios_p;
  if(tcgetattr(port, &termios_p) == -1) {
    return false;
  }
  
  termios_p.c_cflag &= (B9600 | ~PARENB | ~CSTOPB | ~CSIZE);
  termios_p.c_cflag |= CS8;

  termios_p.c_oflag &= ~OPOST;      //raw output
  termios_p.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);  //raw input
  
  termios_p.c_cc[VMIN]=0;
  termios_p.c_cc[VTIME]=10;         //timeout after 10 .1 sec intervals
  
  cfsetospeed(&termios_p, B9600);
  cfsetispeed(&termios_p, B9600);
  
  tcflush(port, TCIFLUSH);
  tcsetattr(port,TCSANOW,&termios_p);
    
  return true;
}

byte SerialPort::receive() {
  byte result;
  int retval = read(port, &result, 1);
  if (retval <= 0)
    return 0;
  else
    return result;
}

bool SerialPort::send(byte cmd) {
  if(write(port, &cmd, sizeof(cmd)) == -1) {
    return false;
  }
  return true;
}







