#include <termios.h>
#include <exception>
#include <string>
#include <iostream>
#include "cSerial.h"
#include "gVar.h"
cSerial::cSerial() : cFile(){
}
cSerial::~cSerial(){
try{
this->closeFile();
}
catch( ... ){}
}
bool cSerial::openFile( const char* device, const int mode ){
if(!cFile::openFile(device, O_RDWR|O_NOCTTY))
return false;
if(tcgetattr(iDescriptor, &aOriginalTermSettings) != 0 )
throw(std::string("tcgetattr"));
setupBaudRate(B19200);
setupTimeOuts(1, PACKET_SIZE);
return true;
}
void cSerial::closeFile(void){
if(isOpen()){
if(tcsetattr(iDescriptor, TCSADRAIN, &aOriginalTermSettings ) != 0 )
throw(std::string("tcsetattr"));
cFile::closeFile();
}
}
bool cSerial::setupBaudRate(const unsigned int iSpeed){
struct termios aTermIoSettings;
if(!isOpen())
return false;
if( tcgetattr(iDescriptor, &aTermIoSettings) != 0)
throw(std::string( "tcgetattr" ));
aTermIoSettings.c_cflag = iSpeed | CS8 | CLOCAL | CREAD;
aTermIoSettings.c_lflag = 0;
aTermIoSettings.c_oflag = 0;
aTermIoSettings.c_iflag = 0;
configurePort(aTermIoSettings);
return true;
}
bool cSerial::setupTimeOuts(const unsigned int timeout, const unsigned int min){
struct termios aTermIoSettings;
if(!isOpen())
return false;
if(tcgetattr(iDescriptor, &aTermIoSettings ) != 0)
throw(std::string("tcgetattr"));
aTermIoSettings.c_cc[VMIN] = min;
aTermIoSettings.c_cc[VTIME] = timeout;
configurePort(aTermIoSettings);
return true;
}
void cSerial::configurePort(const struct termios& aTermIoSettings){
if( tcflush(iDescriptor, TCIFLUSH) != 0)
throw(std::string("tcflush"));
if(tcsetattr(iDescriptor, TCSANOW, &aTermIoSettings ) != 0 )
throw(std::string("tcsetattr"));
}
bool cSerial::sendACK(){
std::cerr << "sending ACK!" << std::endl;
writeToFile('A');
return true;
};
bool cSerial::waitForACK(){
char sRead;
setupTimeOuts(5, 0);
sRead = 0;
std::cerr << "waiting fo ACK..." << std::endl;
readFromFile(sRead);
setupTimeOuts(1, PACKET_SIZE);
if (sRead != 'A'){
std::cerr << "no ACK recived!" << std::endl;
return false;
}
std::cerr << "ACK recived!" << std::endl;
return true;
};