#include "hardwareResourceSerialProvider.h" #include "../data/protocol/protocol.h" #include #include #include #include #include #include //#include "rgooseDBConnector.h" //#define DEBUG_EXTRA //#define DEBUG_SERIAL_COMMUNICATION #define LOG( X ) hardwareResource::m_pLog->Log( "HWR_SERIAL", 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 );\ hardwareResource::m_pLog->Log( "HWR_SERIAL", this, _LOG_ERROR, _tBfrErrMSG2w34 );\ } #else #define LOG_ERROR( X ) hardwareResource::m_pLog->Log( "HWR_SERIAL", this, _LOG_ERROR, X ); #endif #ifndef HALF_DUPLEX hardwareResourceSerialProvider::hardwareResourceSerialProvider( uint32_t dbID ) : hardwareResource( dbID, HARDWARE_PROVIDER_SERIAL ), basicTransport(), basicDualThread(){ m_nInputBufferSize = 0; m_nOutputBufferSize = 0; #else hardwareResourceSerialProvider::hardwareResourceSerialProvider( uint32_t dbID ) : hardwareResource( dbID, HARDWARE_PROVIDER_SERIAL ), basicTransport(), basicThread(){ #endif memset( &m_sUartData, 0, sizeof(m_sUartData)); memset( &m_sTTY, 0, sizeof(m_sTTY)); m_iDeviceFD = -1; m_iMasterFD = -1; #ifdef __linux__ m_iInFID = -1; m_iOutFID = -1; m_bManualRTS = false; #endif }; hardwareResourceSerialProvider::~hardwareResourceSerialProvider(){ closePort(); }; bool hardwareResourceSerialProvider::create( void ){ if( m_pDBC!= NULL ){ DBC_UART_DATA *tDATA = NULL; tDATA = m_pDBC->getUartData(m_sResourceSettings.aux_id); if( tDATA!= NULL ) { memcpy( &m_sUartData, tDATA, sizeof(DBC_UART_DATA)); #ifdef DEBUG LOG( m_sUartData.path ); #endif free( tDATA ); switch( m_sUartData.type ){ case HARDWARE_UART: m_bValid = create_HW(); break; case HARDWARE_IP_UART: m_bValid = create_SOL(); break; }; } else { LOG_ERROR("No Data!!"); }; }; return m_bValid; }; // Calculating the Check Sum unsigned short checksum(void *b, int len){ unsigned short *buf = (unsigned short *) b; unsigned int sum=0; unsigned short result; for ( sum = 0; len > 1; len -= 2 ) sum += *buf++; if ( len == 1 ) sum += *(unsigned char*)buf; sum = (sum >> 16) + (sum & 0xFFFF); sum += (sum >> 16); result = ~sum; return result; } bool hardwareResourceSerialProvider::validate( void ){ if( m_pDBC != NULL ){ DBC_UART_DATA *tDATA = m_pDBC->getUartData(m_sResourceSettings.aux_id); switch( m_sUartData.type ) { case HARDWARE_UART:{ //HW port is valid #ifndef HALF_DUPLEX if( ( m_bThreadBStatus == TH_ENDED ) && ( m_bThreadAStatus == TH_ENDED ) ) { LOG("IO Theads are Finished!"); #else if( m_bThreadStatus == TH_ENDED ) { LOG("IO Thead is Finished!"); #endif m_bValid = false; closePort(); }; break; }; case HARDWARE_IP_UART:{ //Ping E2U device if( m_bValid ) { m_bValid = pingDevice(); if( !m_bValid ){ LOG("No Ping to Device!!"); closePort(); }; }; break; }; }; #ifdef DEBUG_EXTRA LOG("Check Settings For Changes"); #endif if( tDATA!= NULL ){ bool bFlag = true; if( strcmp(tDATA->path,m_sUartData.path)!= 0 ) bFlag = false; if( bFlag && ( m_sUartData.speed != tDATA->speed ) ) bFlag = false; if( bFlag && ( m_sUartData.mode != tDATA->mode ) ) bFlag = false; if( bFlag && ( m_sUartData.port != tDATA->port ) ) bFlag = false; if( !bFlag ) { #ifdef DEBUG_EXTRA LOG("Settings Has been Changed!"); #endif memcpy( &m_sUartData, tDATA, sizeof(DBC_UART_DATA)); #ifdef DEBUG_EXTRA LOG("Reconect with new settings"); #endif if( m_bValid ) closePort(); switch( m_sUartData.type ){ case HARDWARE_UART: m_bValid = create_HW(); break; case HARDWARE_IP_UART: m_bValid = create_SOL(); break; }; }; // Check If Not Connected to Connect! if( !m_bValid ) { #ifdef DEBUG_EXTRA LOG("Try to Conncet"); #endif switch( m_sUartData.type ){ case HARDWARE_UART: m_bValid = create_HW(); break; case HARDWARE_IP_UART: m_bValid = create_SOL(); break; }; }; free( tDATA ); } else { LOG_ERROR("Error Fetch DB Data!"); }; } else m_bValid = false; return m_bValid; }; #include // Define the Packet Constants // ping packet size #define PING_PKT_S 64 // Automatic port number #define PORT_NO 0 // Automatic port number #define PING_SLEEP_RATE 1000000 // Gives the timeout delay for receiving packets // in seconds #define RECV_TIMEOUT 1 // ping packet structure struct ping_pkt { struct icmphdr hdr; char msg[PING_PKT_S-sizeof(struct icmphdr)]; }; bool hardwareResourceSerialProvider::pingDevice(){ bool RetVal = false; if( m_bValid ) { #ifdef DEBUG_EXTRA LOG("Pinging Device!"); #endif int sockfd; int ttl_val=64, msg_count=0, i, flag=1, msg_received_count=0; struct ping_pkt pckt; struct sockaddr_in ping_addr; struct sockaddr_in r_addr; struct timeval tv_out; tv_out.tv_sec = 0; tv_out.tv_usec = 300000; // 1/3 of second ping_addr.sin_family = AF_INET; ping_addr.sin_addr.s_addr = inet_addr( m_sUartData.path ); //ping_addr.sin_port = htons( m_nPort ); LOG( m_sUartData.path ); sockfd = socket( AF_INET, SOCK_RAW, IPPROTO_ICMP ); if( sockfd < 0 ){ LOG_ERROR("Socket file descriptor not received!"); return false; }; // set socket options at ip to TTL and value to 64, // change to what you want by setting ttl_val if( setsockopt( sockfd, SOL_IP, IP_TTL, &ttl_val, sizeof(ttl_val)) != 0 ){ LOG_ERROR("Setting socket options to TTL failed!"); shutdown( sockfd, SHUT_RDWR ); return false; }; // setting timeout of recv setting setsockopt( sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv_out, sizeof tv_out ); // flag is whether packet was sent or not flag=1; //filling packet bzero(&pckt, sizeof(pckt)); pckt.hdr.type = ICMP_ECHO; pckt.hdr.un.echo.id = getpid(); for ( i = 0; i < sizeof(pckt.msg)-1; i++ ) pckt.msg[i] = i+'0'; pckt.msg[i] = 0; pckt.hdr.un.echo.sequence = msg_count++; pckt.hdr.checksum = checksum(&pckt, sizeof(pckt)); //SLEEP( 300 ); //send packet if( sendto( sockfd, &pckt, sizeof(pckt), 0, (struct sockaddr*)&ping_addr, sizeof(ping_addr)) <= 0 ){ LOG_ERROR("Packet Sending Failed!"); shutdown( sockfd, SHUT_RDWR ); return false; }; //receive packet socklen_t addr_len = sizeof(r_addr); if( recvfrom( sockfd, &pckt, sizeof(pckt), 0, (struct sockaddr*)&r_addr, &addr_len) <= 0 ){ LOG_ERROR("Packet receive failed!"); shutdown( sockfd, SHUT_RDWR ); return false; } else { #ifdef DEBUG_EXTRA LOG("Device pinged Sucessfully"); #endif RetVal = true; }; shutdown( sockfd, SHUT_RDWR ); }; return RetVal; }; bool hardwareResourceSerialProvider::create_SOL(){ /* if( m_sUartData.mode == SOL_NOT_DEFINED ) { LOG_ERROR("No Connection Type Defined!"); return false; }; */ if( m_sUartData.port == 0 ) { LOG_ERROR("No Port Defined!"); return false; }; if( m_sUartData.speed == 0 ){ LOG_ERROR("No Speed Defined!"); return false; }; if( m_sUartData.path[0] == (char)0 ) { LOG_ERROR("No Adress Defined!"); return false; }; switch( m_sUartData.mode ) { case SOL_UDP_CLIENT:{ #ifdef DEBUG LOG("PORT IS CLIENT - Create UDP Server"); #endif #ifdef __linux__ // Creating socket file descriptor if ( (m_iDeviceFD = socket( AF_INET, SOCK_DGRAM, 0 )) < 0 ) { LOG_ERROR("UDP Socket Creation Failed!"); return false; }; fcntl( m_iDeviceFD, F_SETFL, O_NONBLOCK); // Filling server information struct sockaddr_in tServerAddr; memset( &tServerAddr, 0, sizeof(tServerAddr) ); tServerAddr.sin_family = AF_INET; // IPv4 tServerAddr.sin_addr.s_addr = INADDR_ANY; tServerAddr.sin_port = htons( m_sUartData.port ); // Bind the socket with the server address if ( bind( m_iDeviceFD, (const struct sockaddr *)&tServerAddr, sizeof(tServerAddr)) < 0 ){ LOG_ERROR("UDP Bind Failed"); return false; }; #else WSADATA wsaData; // Initialize Winsock version 2.2 char tBuff[128]; if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) { sprintf(tBuff, "WSAStartup failed with error %ld", WSAGetLastError()); LOG_ERROR(tBuff); return false; } else { sprintf(tBuff, "The Winsock DLL status is %s.", wsaData.szSystemStatus); LOG(tBuff); }; // Set up a SOCKADDR_IN structure that will tell bind that we // want to receive datagrams from all interfaces using port 5150. // The IPv4 family ReceiverAddr.sin_family = AF_INET; // Port no. 5150 ReceiverAddr.sin_port = htons( m_nPort ); // From all interface (0.0.0.0) ReceiverAddr.sin_addr.s_addr = htonl(INADDR_ANY); // Associate the address information with the socket using bind. // At this point you can receive datagrams on your bound socket. if( bind(m_sSocket, (SOCKADDR*)&ReceiverAddr, sizeof(ReceiverAddr)) == SOCKET_ERROR ){ sprintf( tBuff, "Server: bind() failed!Error : %ld.", WSAGetLastError()); // Close the socket closesocket(m_sSocket); // Do the clean up WSACleanup(); // and exit with error LOG_ERROR(tBuff); return false; } else { LOG("UDP Server: bind() is OK!"); }; // Some info on the receiver side... SOCKADDR_IN tAddr; int tLen = sizeof(SOCKADDR_IN); getsockname(m_sSocket, (SOCKADDR*)&tAddr, &tLen); sprintf( tBuff, "Receiving IP(s) used : %s", inet_ntoa(tAddr.sin_addr)); LOG(tBuff); sprintf(tBuff,"Receiving port used : %d", htons(tAddr.sin_port)); LOG(tBuff); SelectTiming = recvfromTimeOutUDP(m_sSocket, 10, 0); #endif break; }; case SOL_TCP_CLIENT:{ #ifdef DEBUG LOG("PORT IS CLIENT - Create TCP Server"); #endif break; }; case SOL_UDP_SERVER:{ #ifdef DEBUG LOG("PORT IS SERVER - Create UDP Client"); #endif #ifdef __linux__ // Creating socket file descriptor if ( (m_iDeviceFD = socket( AF_INET, SOCK_DGRAM, 0)) < 0 ) { LOG_ERROR("Socket Creation Failed!"); return false; }; fcntl( m_iDeviceFD, F_SETFL, O_NONBLOCK ); // Filling server information struct sockaddr_in tServerAddr; memset( &tServerAddr, 0, sizeof(tServerAddr) ); tServerAddr.sin_family = AF_INET; tServerAddr.sin_addr.s_addr = INADDR_ANY; tServerAddr.sin_port = htons( m_sUartData.port ); #else #endif break; }; case SOL_TCP_SERVER:{ #ifdef DEBUG LOG("PORT IS SERVER - Create TCP Client"); #endif // socket create and varification m_iDeviceFD = socket( AF_INET, SOCK_STREAM, 0 ); if( m_iDeviceFD == -1) { LOG_ERROR("Socket creation failed!"); return false; } #ifdef DEBUG else LOG("Socket successfully created"); #endif // assign IP, PORT struct sockaddr_in tServerAddr; memset( &tServerAddr, 0, sizeof(tServerAddr) ); tServerAddr.sin_family = AF_INET; tServerAddr.sin_addr.s_addr = inet_addr( m_sUartData.path ); tServerAddr.sin_port = htons( m_sUartData.port ); // connect the client socket to server socket if( connect( m_iDeviceFD, (struct sockaddr *)&tServerAddr, sizeof(tServerAddr) ) !=0 ){ char cBuffer[128]; sprintf(cBuffer,"ERROR connect to [%s:%d] (%s)", m_sUartData.path, m_sUartData.port, strerror(errno) ); LOG_ERROR( cBuffer ); return false; } #ifdef DEBUG else LOG("Connected to the server"); #endif // Set non-blocking int arg; if( (arg = fcntl( m_iDeviceFD, F_GETFL, NULL)) < 0) { char tBuf[128]; sprintf( tBuf, "Error fcntl(..., F_GETFL) (%s)", strerror(errno)); LOG_ERROR( tBuf ); return false; }; arg |= O_NONBLOCK; if( fcntl( m_iDeviceFD, F_SETFL, arg) < 0) { char tBuf[128]; sprintf( tBuf, "Error fcntl(..., F_SETFL) (%s)", strerror(errno)); LOG_ERROR( tBuf ); return false; }; setConnectionStatus( CS_CONNECTED ); break; }; }; return init(); }; bool hardwareResourceSerialProvider::create_HW(){ char MsgBuffer[CLOG]; 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; //}; #ifdef __linux__ int result; /* Open File Descriptor */ //m_iFID = open( DevicePath, O_RDWR| O_NONBLOCK | O_NDELAY ); #ifdef __arm__ LOG("ARM Defined!"); #endif #ifdef RASPI_HARDWARE LOG("RASPI_HARDWARE Defined!"); #endif #ifdef __aarch64__ LOG("AARCH64 Defined!"); #endif #ifdef USE_WIRINGX LOG("USE_WIRINGX Defined!"); LOG( WIRINGX_PLATFORM ); #endif #ifdef USE_WIRINGPI LOG("USE_WIRINGPI Defined!"); if( strstr( m_sUartData.path, "USB" ) == NULL ){ #ifdef DEBUG LOG("MANUAL RTS CTL(R)"); #endif m_bManualRTS = true; wiringPiSetup(); //Set RTS Pin pinMode( RTS_PIN_NUMBER, OUTPUT ); } else { #ifdef DEBUG LOG("NO MANUAL RTS CTL(R)"); #endif m_bManualRTS = false; }; #else #ifdef USE_WIRINGX if( strstr( m_sUartData.path, "USB" ) == NULL ){ #ifdef DEBUG LOG("MANUAL RTS CTL(X)"); #endif if( wiringXSetup( WIRINGX_PLATFORM, NULL ) == -1 ){ LOG_ERROR( "WiringX Platform Init Failure!" ); m_bManualRTS = false; } else { //Set RTS Pin //pinMode( 0, OUTPUT ); pinMode( RTS_PIN_NUMBER, PINMODE_OUTPUT); m_bManualRTS = true; }; } else { #ifdef DEBUG LOG("NO MANUAL RTS CTL(X)"); #endif m_bManualRTS = false; }; #else #ifdef DEBUG LOG("NO MANUAL RTS CTL(INTEL)"); #endif m_bManualRTS = false; #endif #endif do{ m_iInFID = open( m_sUartData.path, O_RDONLY | O_NONBLOCK | O_NDELAY ); } while( m_iInFID == -1 && errno == EINTR ); if( m_iInFID == -1 ){ LOG_ERROR("Can not open Input Stream"); 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( m_sUartData.path, O_WRONLY | O_NDELAY ); }while( m_iOutFID == -1 && errno == EINTR); if( m_iOutFID == -1 ){ LOG_ERROR("Can not open Output Stream"); 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 */ int RetVal = 0; switch( m_sUartData.speed ){ 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_sUartData.speed ); LOG_ERROR( MsgBuffer ); return false; }; }; if( RetVal == 0 ) { #ifdef DEBUG sprintf( MsgBuffer, "speed set to [%d] bod", m_sUartData.speed ); LOG( MsgBuffer ); #endif } else { RetVal = cfgetispeed( &m_sTTY ); sprintf( MsgBuffer, "Error cannot set speed as [%d] bod. Current is: %d bod. ", m_sUartData.speed, 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_iflag &= ~(INLCR | ICRNL); // fixing 0x0D->0x0A // 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 // Linux 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 ); if( init() ) { #ifdef DEBUG sprintf( MsgBuffer,"Init %s [%d] OK", m_sUartData.path, m_sUartData.speed ); LOG( MsgBuffer ); #endif return true; } else { LOG_ERROR("HW INIT Failure!"); }; return false; }; bool hardwareResourceSerialProvider::closePort(){ char tBuff[128]; setConnectionStatus( CS_DISCONNECTED ); #ifndef HALF_DUPLEX if( m_bThreadAStatus != TH_PRE_INIT && m_bThreadBStatus != TH_PRE_INIT ){ uninit(); }; #else if( m_bThreadStatus != TH_PRE_INIT ){ uninit(); }; #endif switch( m_sUartData.type ) { case HARDWARE_UART:{ break; }; case HARDWARE_IP_UART:{ if( m_iDeviceFD != -1 ) { switch( m_sUartData.mode ) { case SOL_UDP_CLIENT: case SOL_TCP_CLIENT: case SOL_UDP_SERVER: { #ifdef __linux__ close( m_iDeviceFD ); #else // When your application is finished receiving datagrams close the socket. LOG("Server: Finished receiving.Closing the listening socket..."); if( closesocket(m_sSocket) != 0 ){ sprintf(tBuff, "closesocket() failed!Error code : %ld", WSAGetLastError()); LOG_ERROR(tBuff); } else { LOG("closesocket() is OK..."); }; // When your application is finished call WSACleanup. LOG("Server: Cleaning up..."); if (WSACleanup() != 0) { sprintf(tBuff, "WSACleanup() failed!Error code : %ld", WSAGetLastError()); LOG_ERROR(tBuff); } else { LOG("WSACleanup() is OK"); }; #endif break; }; case SOL_TCP_SERVER:{ close( m_iDeviceFD ); break; }; }; m_iDeviceFD = -1; }; break; }; }; return true; }; #ifndef HALF_DUPLEX void hardwareResourceSerialProvider::m_fThreadAProc(void){ int index; int RetVal; m_bThreadAStatus = TH_WORKING; #ifdef DEBUG LOG("Sender Thread Started!"); #endif while (m_bThreadAStatus < TH_ENDED) { m_mBufferProtectorMutex.lock(); if( m_nOutputBufferSize > 0 ){ index = 0; while ((index < m_nOutputBufferSize) && (m_bThreadAStatus < TH_ENDED)){ #ifdef DEBUG_EXTRA char TT[64]; sprintf( TT, "Have %d Bytes to send!", m_nOutputBufferSize ); LOG( TT ); #endif RetVal = sendBlock( m_pOutputBuffer + index, m_nOutputBufferSize - index ); if( RetVal > 0 ){ index += RetVal; } else { //if 0 or -(error) if( RetVal == 0 ){ usleep( 100 ); } else { setConnectionStatus( CS_DISCONNECTED ); m_nOutputBufferSize = 0; m_bThreadBStatus = TH_ENDED; m_bThreadAStatus = TH_ENDED; LOG_ERROR("Connection Droped on Sending Data"); }; }; }; m_nOutputBufferSize = 0; m_mBufferProtectorMutex.unlock(); } else { m_mBufferProtectorMutex.unlock(); SLEEP(5); }; }; }; void hardwareResourceSerialProvider::m_fThreadBProc(void){ m_bThreadBStatus = TH_WORKING; int RetVal; #ifdef DEBUG LOG("Recipient Thread Started!"); #endif while( m_bThreadBStatus < TH_ENDED ){ RetVal = recptBlock( m_pInputBuffer, &m_nInputBufferSize); if( RetVal == -1 ){ setConnectionStatus(CS_DISCONNECTED); m_nInputBufferSize = 0; //if(!getStatus()) { m_bThreadBStatus = TH_ENDED; m_bThreadAStatus = TH_ENDED; //} else SLEEP(100); LOG_ERROR("Connection Droped on Reception Data"); } else if( m_nInputBufferSize > 0 ){ do{ m_mQueueProtectorMutex.lock(); if( m_vParsers.size() ){ for (parseQueue::iterator index = m_vParsers.begin(); index != m_vParsers.end(); index++) (*index)->parse(m_pInputBuffer, m_nInputBufferSize); m_nInputBufferSize = 0; m_mQueueProtectorMutex.unlock(); } else { #ifdef DEBUG_EXTRA LOG( m_sUartData.path ); LOG( (char *)m_pInputBuffer ); LOG_ERROR("Try to parse data but No Parsers Assigned!"); #endif m_nInputBufferSize = 0; m_mQueueProtectorMutex.unlock(); SLEEP(100); }; } while( ( m_vParsers.size() == 0 ) && ( m_bThreadAStatus < TH_ENDED ) && ( m_bThreadBStatus < TH_ENDED ) ); } else { SLEEP(5); }; }; }; bool hardwareResourceSerialProvider::sendData( uint8_t *Data, int DataSize ){ #ifndef HALF_DUPLEX if( m_bThreadAStatus != TH_WORKING ) { if( m_bThreadAStatus < TH_WORKING ) { LOG_ERROR("Trying to Send Data Before Thread is Started!"); } else { LOG_ERROR("Trying to Send Data After Thread is Dead!"); } return false; }; #else if( m_bThreadStatus != TH_WORKING ) { if( m_bThreadStatus < TH_WORKING ) { LOG_ERROR("Trying to Send Data Before Thread is Started!"); } else { LOG_ERROR("Trying to Send Data After Thread is Dead!"); } return false; }; #endif m_mBufferProtectorMutex.lock(); if (m_nOutputBufferSize + DataSize > MAXIMAL_SOCKET_PACKET_LENGTH ){ m_mBufferProtectorMutex.unlock(); LOG_ERROR("Data Too BIG"); return false; }; memcpy(m_pOutputBuffer + m_nOutputBufferSize, Data, DataSize); m_nOutputBufferSize += DataSize; m_mBufferProtectorMutex.unlock(); return true; }; #else // HALF_DUPLEX void hardwareResourceSerialProvider::m_fThreadProc(void){ int index; int RetVal; m_bThreadStatus = TH_WORKING; #ifdef DEBUG_EXTRA LOG("Sender Thread Started!"); #endif while (m_bThreadStatus < TH_ENDED) { m_mBufferProtectorMutex.lock(); if( !m_qIO.empty() ){ SIO_TZ *tIOData; tIOData = m_qIO.front(); m_mBufferProtectorMutex.unlock(); if( tIOData ){ //Remove from Queue m_mBufferProtectorMutex.lock(); m_qIO.pop(); m_mBufferProtectorMutex.unlock(); index = 0; while( ( index < tIOData->out_size ) && ( m_bThreadStatus < TH_ENDED ) ){ #ifdef DEBUG_EXTRA char TT[64]; sprintf( TT, "Have %d Bytes to send!", ( tIOData->out_size - index ) ); LOG( TT ); #endif RetVal = sendBlock( tIOData->out_buffer + index, tIOData->out_size - index ); if( RetVal > 0 ){ index += RetVal; } else { //if 0 or -(error) if( RetVal == 0 ){ usleep( 100 ); } else { setConnectionStatus( CS_DISCONNECTED ); //m_nOutputBufferSize = 0; tIOData->out_size = 0; m_bThreadStatus = TH_ENDED; LOG_ERROR("Connection Droped on Sending Data"); }; }; }; tIOData->out_size = 0; bool tDataOnline = false; uint8_t tTOCounter = 20; do{ RetVal = recptBlock( tIOData->inp_buffer, &tIOData->inp_size ); if( RetVal == -1 ){ setConnectionStatus(CS_DISCONNECTED); tIOData->inp_size = 0; m_bThreadStatus = TH_ENDED; LOG_ERROR("Connection Droped on Reception Data"); } else if( tIOData->inp_size ){ tDataOnline = true; do{ m_mQueueProtectorMutex.lock(); if( m_vParsers.size() ){ for( parseQueue::iterator idx = m_vParsers.begin(); idx != m_vParsers.end(); idx++) (*idx)->parse( tIOData->inp_buffer, tIOData->inp_size ); tIOData->inp_size = 0; m_mQueueProtectorMutex.unlock(); } else { #ifdef DEBUG_EXTRA LOG( m_sUartData.path ); LOG( (char *)tIOData->inp_buffer ); LOG_ERROR("Try to parse data but No Parsers Assigned!"); #endif tIOData->inp_size = 0; m_mQueueProtectorMutex.unlock(); SLEEP(100); }; } while( ( m_vParsers.size() == 0 ) && ( m_bThreadStatus < TH_ENDED ) ); } else { if( tTOCounter ){ tTOCounter--; SLEEP(5); #ifdef DEBUG } else { LOG_ERROR("PACK TIMEOUT!"); #endif }; }; } while( ( m_bThreadStatus < TH_ENDED ) && tTOCounter && !( tDataOnline && RetVal == 0 ) ); // Pack1 conditions -> White Space after Data. // Free Package //LOG("Del Pack"); free( tIOData ); } else { // Mutex already unlocked! SLEEP(5); }; } else { m_mBufferProtectorMutex.unlock(); SLEEP(5); }; }; }; bool hardwareResourceSerialProvider::sendData( uint8_t *Data, int DataSize ){ if( m_bThreadStatus != TH_WORKING ) { if( m_bThreadStatus < TH_WORKING ) { LOG_ERROR("Trying to Send Data Before Thread is Started!"); } else { LOG_ERROR("Trying to Send Data After Thread is Dead!"); } return false; }; if( DataSize > MAXIMAL_SOCKET_PACKET_LENGTH ){ LOG_ERROR("Data Too BIG"); } else { SIO_TZ *tData = (SIO_TZ *) malloc( sizeof( SIO_TZ )); if( tData ) { memset( tData, 0, sizeof( SIO_TZ ) ); tData->out_size = DataSize; memcpy( tData->out_buffer, Data, DataSize ); m_mBufferProtectorMutex.lock(); m_qIO.push( tData ); m_mBufferProtectorMutex.unlock(); return true; } else { LOG_ERROR("MemAlloc Error!"); }; }; return false; }; #endif //Half Duplex bool hardwareResourceSerialProvider::reconnect( void ){ closePort(); switch( m_sUartData.type ){ case HARDWARE_UART: m_bValid = create_HW(); break; case HARDWARE_IP_UART: m_bValid = create_SOL(); break; }; return m_bValid; }; int hardwareResourceSerialProvider::recptBlock( unsigned char *Buffer, int *BufferLength ){ #ifdef __linux__ int RetVal = 0; #else DWORD RetVal = 0; #endif if( m_eConnectionStatus == CS_CONNECTED ){ switch( m_sUartData.type ) { case HARDWARE_UART:{ #ifdef __linux__ do{ RetVal = read( m_iInFID, Buffer, MAXIMAL_SERIAL_PACKET_LENGTH ); #ifndef HALF_DUPLEX if( RetVal == -1 && errno == EINTR && m_bThreadAStatus == TH_WORKING ) SLEEP(1); } while (RetVal == -1 && errno == EINTR && m_bThreadAStatus == TH_WORKING ); #else if( RetVal == -1 && errno == EINTR && m_bThreadStatus == TH_WORKING ) SLEEP(1); } while (RetVal == -1 && errno == EINTR && m_bThreadStatus == TH_WORKING ); #endif #else //Windows OVERLAPPED osReader = {0}; if( !ReadFile(m_ioFID, Buffer, MAXIMAL_SERIAL_PACKET_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; #ifdef DEBUG_SERIAL_COMMUNICATION } else { //fWaitingOnRead = TRUE; LOG("WREAD!"); #endif }; #ifdef DEBUG_SERIAL_COMMUNICATION } else { // read completed immediately LOG("IMREAD!"); #endif }; #endif // Linux break; }; case HARDWARE_IP_UART:{ //SOL #ifdef __linux__ if( m_iDeviceFD > -1 ) { struct sockaddr ClientAddress; socklen_t addr_len = sizeof( ClientAddress ); //len is value/resuslt //RetVal = recvfrom( m_nSocketFD, (char *)Buffer, MAXIMAL_SOCKET_PACKET_LENGTH, MSG_WAITALL, ( struct sockaddr *) &m_sClientAddr, &addr_len ); RetVal = recvfrom( m_iDeviceFD, (char *)Buffer, MAXIMAL_SOCKET_PACKET_LENGTH, MSG_DONTWAIT, ( struct sockaddr *) &ClientAddress, &addr_len ); if( RetVal < 1 ){ if( errno!=EAGAIN && errno!=EINTR ) { LOG_ERROR("Peer Closes Connection!"); shutdown( m_iDeviceFD, 2 ); close( m_iDeviceFD ); *BufferLength = 0; m_iDeviceFD = -1; setConnectionStatus( CS_DISCONNECTED ); return -1; }; }; } else { LOG_ERROR("Not Connected!"); *BufferLength = 0; setConnectionStatus( CS_DISCONNECTED ); return -1; }; #else switch ( m_eType ) { case SOL_UDP_CLIENT: case SOL_TCP_CLIENT: case SOL_UDP_SERVER: { SOCKADDR_IN tAddr; int tLen = sizeof(SOCKADDR_IN); RetVal = recvfrom( m_sSocket, (char*)Buffer, MAXIMAL_SOCKET_PACKET_LENGTH, 0, (struct sockaddr*) &tAddr, &tLen); if (RetVal == SOCKET_ERROR){ char cBuffer[165]; sprintf(cBuffer,"recvfrom() failed with error code : %d", WSAGetLastError()); LOG_ERROR(cBuffer); }; break; }; }; #endif break; }; // End of SOL }; } else { if( m_sUartData.type == HARDWARE_IP_UART ) { //make prep for connection SOL_TCP_SERVER if( m_sUartData.mode == SOL_TCP_CLIENT ){ //ACCEPT struct sockaddr ClientAddress; socklen_t size = (socklen_t) sizeof( struct sockaddr_in ); //int ClientSocket; m_iDeviceFD = accept( m_iMasterFD, &ClientAddress, &size ); if( m_iDeviceFD < 0 ) { setConnectionStatus( CS_DISCONNECTED ); LOG_ERROR("Connection Accept Failure!"); return -1; }; } else { LOG_ERROR("RCPT ON not connected!"); shutdown( m_iDeviceFD, 2 ); close( m_iDeviceFD ); *BufferLength = 0; m_iDeviceFD = -1; setConnectionStatus( CS_DISCONNECTED ); return -1; }; #ifdef DEBUG } else { LOG( "Port is not Ready to Receive" ); #endif }; return -1; // Exit after unsuccess reconnect }; if( RetVal > 0 ){ #ifdef DEBUG_SERIAL_COMMUNICATION char MsgBuffer[CLOG]; if( RetVal > 1 || RetVal == 0 ) { sprintf( MsgBuffer, "Received %d bytes", RetVal ); } else { sprintf( MsgBuffer, "Received 1 byte"); }; LOG( MsgBuffer ); for (int i = 0; i < RetVal; i++) { sprintf(MsgBuffer, "<0x%02X", Buffer[i]); LOG(MsgBuffer); }; #endif *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; }; void hardwareResourceSerialProvider::setRTS( uint8_t Val ){ #if defined( USE_WIRINGPI ) || defined( USE_WIRINGX ) if ( Val ) { //Use RTS GPIO digitalWrite( RTS_PIN_NUMBER, HIGH ); } else { digitalWrite( RTS_PIN_NUMBER, LOW ); }; #else int flags; if ( Val ) { ioctl( m_iInFID, TIOCMGET, &flags ); flags |= TIOCM_RTS; ioctl( m_iInFID, TIOCMSET, &flags ); ioctl( m_iOutFID, TIOCMGET, &flags ); flags |= TIOCM_RTS; ioctl( m_iOutFID, TIOCMSET, &flags ); } else { ioctl( m_iInFID, TIOCMGET, &flags ); flags &= ~TIOCM_RTS; ioctl( m_iInFID, TIOCMSET, &flags ); ioctl( m_iOutFID, TIOCMGET, &flags ); flags &= ~TIOCM_RTS; ioctl( m_iOutFID, TIOCMSET, &flags ); }; #endif }; #include int hardwareResourceSerialProvider::sendBlock(unsigned char* Data, int DataSize) { #ifdef __linux__ int RetVal = 0; #else DWORD RetVal = 0; #endif if( m_eConnectionStatus== CS_CONNECTED ){ switch( m_sUartData.type ) { case HARDWARE_UART:{ #ifdef __linux__ // setRTS( 1 ); do{ if( m_bManualRTS ) { #if defined( USE_WIRINGPI ) || defined( USE_WIRINGX ) digitalWrite( RTS_PIN_NUMBER, HIGH ); #else setRTS( 1 ); #endif }; RetVal = write( m_iOutFID, Data, DataSize); if( m_bManualRTS ){ uint8_t lsr; do { int r = ioctl( m_iOutFID, TIOCSERGETLSR, &lsr ); } while (!(lsr & TIOCSER_TEMT)); #if defined( USE_WIRINGPI ) || defined( USE_WIRINGX ) digitalWrite( RTS_PIN_NUMBER, LOW ); #else setRTS( 0 ); #endif }; if( RetVal == DataSize ){ usleep( 10 ); }; #ifndef HALF_DUPLEX } while (RetVal == -1 && (errno == EINTR || errno == EWOULDBLOCK) && m_bThreadAStatus == TH_WORKING ); #else } while (RetVal == -1 && (errno == EINTR || errno == EWOULDBLOCK) && m_bThreadStatus == TH_WORKING ); #endif //if( m_bManualRTS ) setRTS( 0 ); #else //!__linux__ WriteFile(m_ioFID, Data, DataSize, &RetVal, NULL); #endif #ifdef DEBUG_EXTRA 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 break; }; case HARDWARE_IP_UART:{ #ifdef __linux__ if( m_iDeviceFD > -1 ){ #ifdef DEBUG_EXTRA char cBuffer[256]; sprintf(cBuffer, "Write into Port %d bytes", DataSize); LOG(cBuffer); #endif struct sockaddr ClientAddress; socklen_t addr_len = sizeof(ClientAddress); RetVal = sendto( m_iDeviceFD, (const char*)Data, DataSize, MSG_CONFIRM, (const struct sockaddr*) &ClientAddress, addr_len); if ((RetVal == -1) && (errno != EINTR) && (errno != EWOULDBLOCK)) { LOG_ERROR("Error acures while writing data into the Socket"); shutdown( m_iDeviceFD, 2); close( m_iDeviceFD); m_iDeviceFD = -1; setConnectionStatus(CS_DISCONNECTED); return -1; }; if (RetVal < 0) RetVal = 0; #ifdef DEBUG_EXTRA sprintf(cBuffer, "Bytes Sent: %ld", RetVal); LOG(cBuffer); #ifdef DEBUG_SERIAL_COMMUNICATION for(int zz=0; zz < RetVal; zz++ ) { sprintf(cBuffer, "SD: 0x%02X", (uint8_t)Data[zz]); LOG(cBuffer); }; #endif #endif } else { LOG_ERROR("Not Connected!"); //m_bConnected = false; setConnectionStatus(CS_DISCONNECTED); return -1; }; #else // Windows if (sendto( m_sSocket, (char *)Data, DataSize, 0, (struct sockaddr*) &ReceiverAddr, sizeof(ReceiverAddr)) == SOCKET_ERROR) { char cBuffer[256]; sprintf(cBuffer, "sendto() failed with error code : %d", WSAGetLastError()); LOG_ERROR( cBuffer ); return -1; }; #endif break; }; }; } else { #ifdef DEBUG_EXTRA LOG( "Port is not Ready to Send" ); #endif return -1; }; return RetVal; }; #undef LOG #undef LOG_ERROR //#undef DEBUG_SERIAL_COMMUNICATION //#undef DEBUG_EXTRA