#include "serialPort.h" #define LOG( X ) m_pLog->Log( "serialPort", this, X ) #define LOG_ERROR( X ) m_pLog->Log( "serialPort", this, _LOG_ERROR, X ) 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 init(); }; }; // 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 ){ int const 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 ){ int const 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; switch( m_iLineSpeed ){ case 115200: cfsetospeed (&m_sTTY, B115200); cfsetispeed (&m_sTTY, B115200); break; case 19200: cfsetospeed (&m_sTTY, B19200); cfsetispeed (&m_sTTY, B19200); break; case 9600: cfsetospeed (&m_sTTY, B9600); cfsetispeed (&m_sTTY, B9600); break; default:{ close( m_iInFID ); close( m_iOutFID ); sprintf( MsgBuffer, "Error cannot set speed as [%d] bod", Speed ); 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 ){ int const 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 ){ int const 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 // Initialize the DCBlength member. PortDCB.DCBlength = sizeof(DCB); COMMTIMEOUTS CommTimeouts; m_ioFID = CreateFile(m_sDevicePath, // Name of the port GENERIC_WRITE | GENERIC_READ, // Access (read-write) mode 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (m_ioFID == INVALID_HANDLE_VALUE){ sprintf(MsgBuffer, "Port [%s] Open Failed", m_sDevicePath); LOG_ERROR(MsgBuffer); return false; }; // 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; // 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; //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; }; // 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) == 0){ sprintf(MsgBuffer, "Port [%s] Clearing The Port Failed", m_sDevicePath); LOG_ERROR(MsgBuffer); CloseHandle(m_ioFID); return false; }; #endif 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 0; } /* 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_PACKET_LENGTH ); usleep(100); } while (RetVal == -1 && errno == EINTR); #else DWORD RetVal; OVERLAPPED osReader; if (!ReadFile(m_ioFID, Buffer, MAXIMAL_SERIAL_PACKET_LENGTH, &RetVal, &osReader)) { if (GetLastError() != ERROR_IO_PENDING){ // read not delayed? // Error in communications; report it. return RetVal; }else{ //fWaitingOnRead = TRUE; }; } else { // read completed immediately } #endif #ifdef _DEBUG_SERIAL_COMMUNICATION_ if( RetVal > -1 ){ char MsgBuffer[CLOG]; if( RetVal > 1 || RetVal == 0 ) { sprintf( MsgBuffer, "Received %d bytes", RetVal ); } else { sprintf( MsgBuffer, "Received 1 byte"); }; LOG( MsgBuffer ); }; #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