#include "serialPort.h" #define LOG(X) m_pLog->Log("UART", this, X) #ifdef DEBUG #define LOG_ERROR(X) \ { \ char _tBfrErrMSG2w34[256]; \ sprintf(_tBfrErrMSG2w34, "In file %s[%d] in func:%s %s", __FILE__, __LINE__, __func__, X); \ m_pLog->Log("UART", this, _LOG_ERROR, _tBfrErrMSG2w34); \ } #else #define LOG_ERROR(X) m_pLog->Log("UART", this, _LOG_ERROR, X); #endif serialPort::serialPort() : transportSerial() { #ifdef __linux__ memset(&m_sTTY, 0, sizeof(m_sTTY)); m_iInFID = -1; m_iOutFID = -1; #else memset(&PortDCB, 0, sizeof(PortDCB)); m_ioFID = INVALID_HANDLE_VALUE; #endif m_pLog = basicLogCollection::getInstance(); // m_bConnected = false; m_bInitComplete = false; m_sDevicePath = NULL; m_iLineSpeed = 9600; } serialPort::serialPort(CSTR DevicePath, int Speed) : transportSerial() { #ifdef __linux__ memset(&m_sTTY, 0, sizeof(m_sTTY)); m_iInFID = -1; m_iOutFID = -1; #else memset(&PortDCB, 0, sizeof(PortDCB)); m_ioFID = INVALID_HANDLE_VALUE; #endif m_pLog = basicLogCollection::getInstance(); // m_bConnected = false; m_iLineSpeed = Speed; m_sDevicePath = (CSTR) malloc(strlen(DevicePath) + 1); strcpy(m_sDevicePath, DevicePath); m_bInitComplete = HW_init(m_sDevicePath, m_iLineSpeed); if (m_bInitComplete) { #ifdef DEBUG char MsgBuffer[CLOG]; sprintf(MsgBuffer, "Init %s [%d] OK", m_sDevicePath, m_iLineSpeed); LOG(MsgBuffer); #endif m_bInitComplete = init(); }; } bool serialPort::create(CSTR DevicePath, int Speed) { if (m_eConnectionStatus == CS_CONNECTED) { LOG_ERROR("TRYING TO CONNECT ON OPENED PORT!"); return false; }; if (m_bInitComplete) { LOG_ERROR("TRYING TO CREATE CREATED PORT!"); return false; }; m_iLineSpeed = Speed; m_sDevicePath = (CSTR) malloc(strlen(DevicePath) + 1); strcpy(m_sDevicePath, DevicePath); m_bInitComplete = HW_init(m_sDevicePath, m_iLineSpeed); if (m_bInitComplete) { #ifdef DEBUG char MsgBuffer[CLOG]; sprintf(MsgBuffer, "Init %s [%d] OK", m_sDevicePath, m_iLineSpeed); LOG(MsgBuffer); #endif return m_bInitComplete = init(); }; return false; } // Destructor implementation serialPort::~serialPort() { int result; #ifdef __linux__ if (m_iInFID != -1) { do { result = close(m_iInFID); } while (result == -1 && errno == EINTR); if (result == -1) { #else if (m_ioFID != INVALID_HANDLE_VALUE) { result = CloseHandle(m_ioFID); if (result == 0) { #endif char MsgBuffer[CLOG]; sprintf(MsgBuffer, "Error %d closing input [%s]: %s", errno, m_sDevicePath, strerror(errno)); LOG_ERROR(MsgBuffer); }; }; #ifdef __linux__ if (m_iOutFID != -1) { do { result = close(m_iOutFID); } while (result == -1 && errno == EINTR); if (result == -1) { char MsgBuffer[CLOG]; sprintf(MsgBuffer, "Error %d closing output [%s]: %s", errno, m_sDevicePath, strerror(errno)); LOG_ERROR(MsgBuffer); }; }; #endif waitThreadAEnd(true); waitThreadBEnd(true); } bool serialPort::HW_init(CSTR DevicePath, int Speed) { char MsgBuffer[CLOG]; m_bInitComplete = false; sprintf(m_sDevicePath, "%s", DevicePath); #ifdef __linux__ int result; /* Open File Descriptor */ // m_iFID = open( DevicePath, O_RDWR| O_NONBLOCK | O_NDELAY ); do { m_iInFID = open(m_sDevicePath, O_RDONLY | O_NONBLOCK | O_NDELAY); } while (m_iInFID == -1 && errno == EINTR); if (m_iInFID == -1) { return false; } do { result = fcntl(m_iInFID, F_SETFL, O_NONBLOCK); } while (result == -1 && errno == EINTR); if (result == -1) { const int error = errno; do { result = close(m_iInFID); } while (result == -1 && errno == EINTR); errno = error; sprintf(MsgBuffer, "Error %d openning port: %s", errno, strerror(errno)); LOG_ERROR(MsgBuffer); return false; }; do { m_iOutFID = open(DevicePath, O_WRONLY | O_NDELAY); } while (m_iOutFID == -1 && errno == EINTR); if (m_iOutFID == -1) { return false; } /* *** Configure Port *** */ memset(&m_sTTY, 0, sizeof(m_sTTY)); /* Error Handling */ do { result = tcgetattr(m_iInFID, &m_sTTY); } while (result == -1 && errno == EINTR); if (result == -1) { const int error = errno; do { result = close(m_iInFID); } while (result == -1 && errno == EINTR); errno = error; sprintf(MsgBuffer, "Error %d from tcgetattr: %s", errno, strerror(errno)); LOG_ERROR(MsgBuffer); return false; }; /* Set Baud Rate */ m_iLineSpeed = Speed; int RetVal = 0; switch (m_iLineSpeed) { case 4000000: cfsetspeed(&m_sTTY, B4000000); break; case 3500000: cfsetspeed(&m_sTTY, B3500000); break; case 3000000: cfsetspeed(&m_sTTY, B3000000); break; case 2500000: cfsetspeed(&m_sTTY, B2500000); break; case 2000000: cfsetspeed(&m_sTTY, B2000000); break; case 1500000: cfsetspeed(&m_sTTY, B1500000); break; case 1152000: cfsetspeed(&m_sTTY, B1152000); break; case 1000000: cfsetspeed(&m_sTTY, B1000000); break; case 921600 : cfsetspeed(&m_sTTY, B921600); break; case 460800 : cfsetspeed(&m_sTTY, B460800); break; case 230400 : cfsetspeed(&m_sTTY, B230400); break; case 115200 : cfsetspeed(&m_sTTY, B115200); break; case 19200 : cfsetspeed(&m_sTTY, B19200); break; case 9600 : cfsetspeed(&m_sTTY, B9600); break; default: { close(m_iInFID); close(m_iOutFID); sprintf(MsgBuffer, "Error cannot set speed as [%d] bod", m_iLineSpeed); LOG_ERROR(MsgBuffer); return false; }; }; if (RetVal == 0) { #ifdef DEBUG sprintf(MsgBuffer, "speed set to [%d] bod", m_iLineSpeed); LOG(MsgBuffer); #endif } else { RetVal = cfgetispeed(&m_sTTY); sprintf(MsgBuffer, "Error cannot set speed as [%d] bod. Current is: %d bod. ", m_iLineSpeed, RetVal); LOG_ERROR(MsgBuffer); return false; }; /* Setting other Port Stuff */ m_sTTY.c_cflag &= ~PARENB; // Make 8n1 m_sTTY.c_cflag &= ~CSTOPB; m_sTTY.c_cflag &= ~CSIZE; m_sTTY.c_cflag |= CS8; m_sTTY.c_cflag &= ~CRTSCTS; // no flow control m_sTTY.c_lflag = 0; // no signaling chars, no echo, no canonical processing m_sTTY.c_oflag = 0; // no remapping, no delays m_sTTY.c_cc[VMIN] = 0; // read doesn't block m_sTTY.c_cc[VTIME] = 5; // 0.5 seconds read timeout m_sTTY.c_cflag |= CREAD | CLOCAL; // turn on READ & ignore ctrl lines m_sTTY.c_iflag &= ~(IXON | IXOFF | IXANY); // turn off s/w flow ctrl m_sTTY.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // make raw m_sTTY.c_oflag &= ~OPOST; // make raw /* Flush Port, then applies attributes */ tcflush(m_iOutFID, TCIFLUSH); do { result = tcsetattr(m_iOutFID, TCSANOW, &m_sTTY); } while (result == -1 && errno == EINTR); if (result == -1) { const int error = errno; do { result = close(m_iOutFID); } while (result == -1 && errno == EINTR); errno = error; sprintf(MsgBuffer, "Error %d from tcsetattr: %s", errno, strerror(errno)); LOG_ERROR(MsgBuffer); return false; }; do { result = tcsetattr(m_iInFID, TCSANOW, &m_sTTY); } while (result == -1 && errno == EINTR); if (result == -1) { const int error = errno; do { result = close(m_iInFID); } while (result == -1 && errno == EINTR); errno = error; sprintf(MsgBuffer, "Error %d from tcsetattr: %s", errno, strerror(errno)); LOG_ERROR(MsgBuffer); return false; }; #else m_ioFID = CreateFile((LPCSTR) m_sDevicePath, GENERIC_READ | GENERIC_WRITE, 0UL, NULL, OPEN_EXISTING, FILE_FLAG_NO_BUFFERING, // FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING, NULL); if (m_ioFID == INVALID_HANDLE_VALUE) { setConnectionStatus(CS_DISCONNECTED); sprintf(MsgBuffer, "Port [%s] Open Failed Err: %d", m_sDevicePath, GetLastError()); LOG_ERROR(MsgBuffer); return false; }; // Initialize the DCBlength member. PortDCB.DCBlength = sizeof(DCB); // Get the default port setting information. GetCommState(m_ioFID, &PortDCB); // Change the DCB structure settings /* PortDCB.fBinary = TRUE; // Binary mode; no EOF check PortDCB.fParity = NOPARITY; // Enable parity checking PortDCB.fDsrSensitivity = FALSE; // DSR sensitivity PortDCB.fErrorChar = FALSE; // Disable error replacement PortDCB.fOutxDsrFlow = FALSE; // No DSR output flow control PortDCB.fAbortOnError = FALSE; // Do not abort reads/writes on error PortDCB.fNull = FALSE; // Disable null stripping PortDCB.fTXContinueOnXoff = TRUE; // XOFF continues Tx PortDCB.BaudRate = Speed; PortDCB.StopBits = ONESTOPBIT; */ PortDCB.BaudRate = Speed; PortDCB.ByteSize = 8; PortDCB.Parity = NOPARITY; PortDCB.StopBits = ONESTOPBIT; PortDCB.EvtChar = 0; PortDCB.fParity = (PortDCB.Parity != NOPARITY); PortDCB.fOutxCtsFlow = FALSE; PortDCB.fOutxDsrFlow = FALSE; PortDCB.fDtrControl = DTR_CONTROL_DISABLE; PortDCB.fDsrSensitivity = FALSE; PortDCB.fOutX = FALSE; PortDCB.fInX = FALSE; PortDCB.fErrorChar = FALSE; PortDCB.fNull = FALSE; // dcb.fRtsControl = RTS_CONTROL_DISABLE; PortDCB.fRtsControl = RTS_CONTROL_ENABLE; // dcb.fRtsControl = RTS_CONTROL_TOGGLE; // specially for PROMAG USB->RS485 converter PortDCB.fAbortOnError = FALSE; PortDCB.fBinary = TRUE; PortDCB.fTXContinueOnXoff = TRUE; // Re-configure the port with the new DCB structure. if (! SetCommState(m_ioFID, &PortDCB)) { sprintf(MsgBuffer, "Port [%s] Could not create the read thread.(SetCommState Failed)", m_sDevicePath); LOG_ERROR(MsgBuffer); CloseHandle(m_ioFID); return false; }; COMMTIMEOUTS CommTimeouts; // Retrieve the time-out parameters for all read and write operations GetCommTimeouts(m_ioFID, &CommTimeouts); /* CommTimeouts.ReadIntervalTimeout = 20; CommTimeouts.ReadTotalTimeoutMultiplier = 10; CommTimeouts.ReadTotalTimeoutConstant = 100; CommTimeouts.WriteTotalTimeoutMultiplier = 10; CommTimeouts.WriteTotalTimeoutConstant = 100; */ CommTimeouts.ReadIntervalTimeout = 20UL; CommTimeouts.ReadTotalTimeoutMultiplier = 1UL; CommTimeouts.ReadTotalTimeoutConstant = 5UL; CommTimeouts.WriteTotalTimeoutMultiplier = 1UL; CommTimeouts.WriteTotalTimeoutConstant = 1UL; // Set the time-out parameters for all read and write operations on the port. if (! SetCommTimeouts(m_ioFID, &CommTimeouts)) { sprintf(MsgBuffer, "Port [%s] Could not create the read thread.(SetCommTimeouts Failed)", m_sDevicePath); LOG_ERROR(MsgBuffer); CloseHandle(m_ioFID); return false; }; // Clear the port of any existing data. if (PurgeComm(m_ioFID, PURGE_TXCLEAR | PURGE_RXCLEAR | PURGE_TXABORT | PURGE_RXABORT) == 0) { sprintf(MsgBuffer, "Port [%s] Clearing The Port Failed", m_sDevicePath); LOG_ERROR(MsgBuffer); CloseHandle(m_ioFID); return false; }; EscapeCommFunction(m_ioFID, SETRTS); EscapeCommFunction(m_ioFID, SETDTR); // Set DataTerminalReady 1 #endif setConnectionStatus(CS_CONNECTED); return true; } int serialPort::sendBlock(unsigned char * Data, int DataSize) { if (! m_bInitComplete) { #ifdef DEBUG LOG("Port is not Ready to Send"); #endif return -1; }; #ifdef __linux__ int RetVal; do { RetVal = write(m_iOutFID, Data, DataSize); usleep(100); } while (RetVal == -1 && (errno == EINTR || errno == EWOULDBLOCK)); #else DWORD RetVal; // OVERLAPPED ov; // if (! WriteFile(m_ioFID, Data, DataSize, &RetVal, NULL); //){ // RetVal = 0; // }; #endif #ifdef DEBUG char MsgBuffer[CLOG]; sprintf(MsgBuffer, "Sent %d byte(s) of %d", RetVal, DataSize); LOG(MsgBuffer); #ifdef DEBUG_SERIAL_COMMUNICATION for (int i = 0; i < DataSize; i++) { sprintf(MsgBuffer, "0x%02X", Data[i]); LOG(MsgBuffer); }; #endif #endif return RetVal; //*/ /* char const *p = (char const *)Data; char const *const q = (char const *)Data + DataSize; ssize_t n; char MsgBuffer[CLOG]; sprintf( MsgBuffer, "Prepare to Send %d Bytes", DataSize ); Log( MsgBuffer ); while (p < q) { do { n = write( m_iOutFID, p, (size_t)(q - p)); } while (n == (ssize_t)-1 && errno == EINTR); if (n == (ssize_t)-1 && errno == EWOULDBLOCK) { // Sleep for a millisecond, then retry. usleep(1000); continue; } if (n == (ssize_t)-1) return errno; else if (n < (ssize_t)1) return EIO; p += (size_t)n; } sprintf( MsgBuffer, "Sent %d Bytes", DataSize ); Log( MsgBuffer ); if (p != q) return EIO; return DataSize; */ } int serialPort::recptBlock(unsigned char * Buffer, int * BufferLength) { if (! m_bInitComplete) { #ifdef DEBUG LOG("Port is Not Ready to Read"); #endif return -1; }; /* int n_read = read( m_iInFID, Buffer, sizeof(Buffer) ); (*BufferLength) = n_read; #ifdef _DEBUG_SERIAL_COMMUNICATION_ char MsgBuffer[CLOG]; sprintf( MsgBuffer, "Received %d bytes", n_read ); Log( MsgBuffer ); #endif // Error Handling if( n_read < 0 ){ #ifndef _DEBUG_SERIAL_COMMUNICATION_ char MsgBuffer[CLOG]; #endif sprintf( MsgBuffer, "Error %d reading: %s", errno, strerror (errno) ); Log( _ERROR, MsgBuffer ); }; return n_read; */ #ifdef __linux__ int RetVal; do { RetVal = read(m_iInFID, Buffer, MAXIMAL_SERIAL_IO_BUFFER_LENGTH); if (RetVal == -1 && errno == EINTR) { SLEEP(1); } } while (RetVal == -1 && errno == EINTR); #else DWORD RetVal = 0; OVERLAPPED osReader = {0}; if (! ReadFile(m_ioFID, Buffer, MAXIMAL_SERIAL_IO_BUFFER_LENGTH, &RetVal, &osReader)) { if (GetLastError() != ERROR_IO_PENDING) { // read not delayed? char tBuffer[256]; sprintf(tBuffer, "Communication Error %d!", GetLastError()); LOG_ERROR(tBuffer); // Error in communications; report it. return -1; // RetVal; } else { // fWaitingOnRead = TRUE; #ifdef DEBUG_EXTRA LOG("WREAD!"); #endif }; } else { // read completed immediately #ifdef DEBUG_EXTRA LOG("IMREAD!"); #endif }; #endif // Linux #ifdef DEBUG if (RetVal > 0) { char MsgBuffer[CLOG]; if (RetVal > 1 || RetVal == 0) { sprintf(MsgBuffer, "Received %d bytes", RetVal); } else { sprintf(MsgBuffer, "Received 1 byte"); }; LOG(MsgBuffer); #ifdef DEBUG_SERIAL_COMMUNICATION for (int i = 0; i < RetVal; i++) { sprintf(MsgBuffer, "0x%02X", Buffer[i]); LOG(MsgBuffer); }; #endif }; #endif if (RetVal > 0) { *BufferLength = RetVal; return RetVal; }; *BufferLength = 0; if (RetVal == -1) { return 0; } if (RetVal == 0) { errno = 0; return 0; }; /* r < -1, should never happen. */ errno = EIO; return 0; } #undef LOG #undef LOG_ERROR