// // Created by h44z on 07.05.19. // #include "SerialPort.h" SerialPort::SerialPort() { fd = -1; tioBaud = B0; tio.c_cflag = CS8 | CREAD | CLOCAL; // 8n1 tio.c_cc[VMIN] = 0; tio.c_cc[VTIME] = 5; } int SerialPort::getTioBaud(int baud) { switch (baud) { case 9600: return B9600; case 19200: return B19200; case 38400: return B38400; case 57600: return B57600; case 115200: return B115200; default: return B0; } } SerialPort::SerialPort(const string &serialPort, int baud) : SerialPort() { tioBaud = getTioBaud(baud); fd = open(serialPort.c_str(), O_RDWR | O_NOCTTY | O_NDELAY); if (fd == -1) { // if open is unsucessful cout << "Unable to open serial port: " << serialPort << endl; } else { fcntl(fd, F_SETFL, 0); cout << "Serial port opened: " << serialPort << endl; if (cfsetspeed(&tio, tioBaud) == 0) { // set baud speed if (tcsetattr(fd, TCSANOW, &tio) == 0) { // apply baud speed change cout << "Serial port initialized successfully to BAUD: " << baud << " (" << tioBaud << ")" << endl; } } else { // something failed close(fd); fd = -1; } } } bool SerialPort::isOpen() { return fd != -1; } SerialPort::~SerialPort() { serialClose(); } vector SerialPort::serialRead(int length) { auto *buf = reinterpret_cast (calloc(length, sizeof(uint8_t))); read(fd, buf, length); vector result(buf, buf + length); free(buf); return result; } int SerialPort::serialWrite(const string &data) { return write(fd, data.c_str(), data.length()); } bool SerialPort::clearInput(int size) { char ch; // flush input stream for (int i = 0; i < size; i++) { if (read(fd, &ch, 1) == 0) return true; // found end of stream } return false; // still data left in the buffer } bool SerialPort::serialClose() { cout << "Closing serial port" << endl; if (isOpen()) { bool result = close(fd) == 0; fd = -1; return result; } return false; }