diff --git a/Projects/la_mojo/build b/Projects/la_mojo/build index 0d3905e9..70621108 100755 --- a/Projects/la_mojo/build +++ b/Projects/la_mojo/build @@ -1,7 +1,7 @@ #! /bin/sh -make clean -e "CFG=Debug" +#make clean -e "CFG=Debug" make -e "CFG=Debug" -j6 #make clean -e "CFG=Debug86" diff --git a/Projects/la_mojo/la_mojo.vpj b/Projects/la_mojo/la_mojo.vpj index f2a33ce1..bc857992 100644 --- a/Projects/la_mojo/la_mojo.vpj +++ b/Projects/la_mojo/la_mojo.vpj @@ -14,7 +14,7 @@ Version="1" OutputFile="%bdmojo_d" CompilerConfigName="Latest Version" - Defines='"/DDEBUG" "/D__STDC_CONSTANT_MACROS__" "/D_CLIENT_APPLICATION_" "/D_OPENCV_" "/DRASPI_HARDWARE"'> + Defines='"/DDEBUG" "/DDEBUG_EXTRA" "/D__STDC_CONSTANT_MACROS__" "/D_CLIENT_APPLICATION_" "/D_OPENCV_" "/DRASPI_HARDWARE"'> Query( tQBuf ); @@ -654,7 +654,7 @@ bool sqliteDBC::addLRFDraw( uint32_t node_id, CSTR uniq_id, uint8_t lrf_id, uint char tQBuf[1024]; sprintf( tQBuf, "INSERT INTO `lrf_draw`(`node_id`,`lrf_id`,`type`,`ts`,`data`) VALUES(%d,%d,%d,STRFTIME('%%s'),'%s')", node_id, lrf_id, type, uniq_id ); -#ifdef DEBUG +#ifdef DEBUG_ALL LOG(tQBuf); #endif m_pDataStorage->SilentQuery( tQBuf ); @@ -879,7 +879,7 @@ uint32_t sqliteDBC::addEvent( DBC_EVT_RECORD *ptr ){ }; default: return 0; }; -#ifdef DEBUG_EXTRA +#ifdef DEBUG_ALL LOG( tQBuf ); #endif if ( m_bRepIsConnected ) { @@ -962,7 +962,7 @@ bool sqliteDBC::addIPCam( OBSERVER_RESULT *tPtr ){ tIpBuf ); } -#ifdef DEBUG +#ifdef DEBUG_ALL LOG(tQBuf); #endif m_pDataStorage->SilentQuery( tQBuf ); @@ -998,7 +998,7 @@ uint32_t sqliteDBC::addLocalCam( CSTR name, CSTR hardware, CSTR path, uint32_t w }; sprintf(tQBuf, "INSERT INTO `media_streams`(`source_id`,`source_type`,`valid`,`name`,`token`,`img_width`,`img_height`,`mrl_proto`,`mrl`,`picture_proto`,`fps`) VALUES(%d,'A',1,'%s','%s',%d,%d,'v4l2','%s','v4l2',%d) ON CONFLICT(`source_id`,`token`) DO UPDATE SET `valid`=1, img_width=%d, img_height=%d, `fps`=%d", camID, name, tM5, width, height, path, fps, width, height, fps ); -#ifdef DEBUG_EXTRA +#ifdef DEBUG_ALL LOG(tQBuf); #endif RetVal = (uint32_t) m_pDataStorage->QueryID( tQBuf ); @@ -1178,12 +1178,12 @@ bool sqliteDBC::cleanLRFMask( uint32_t maskID, bool deleteMask ){ if( m_bStoIsConnected ) { char tQBuf[MAX_PATH_LEN]; //sprintf( tQBuf, "DELETE FROM `lrf_mask_trace_zones` WHERE `zone_id` IN ( SELECT `id` FROM `lrf_mask_traces` WHERE `mask_id`=%d )", maskID ); -#ifdef DEBUG_EXTRA +#ifdef DEBUG_ALL //LOG(tQBuf); #endif //m_pDataStorage->SilentQuery( tQBuf ); //sprintf( tQBuf, "DELETE FROM `lrf_mask_traces` WHERE `mask_id`=%d", maskID ); -#ifdef DEBUG_EXTRA +#ifdef DEBUG_ALL //LOG(tQBuf); #endif //m_pDataStorage->SilentQuery( tQBuf ); @@ -1194,14 +1194,14 @@ bool sqliteDBC::cleanLRFMask( uint32_t maskID, bool deleteMask ){ m_pDataStorage->SilentQuery( tQBuf ); sprintf( tQBuf, "DELETE FROM `lrf_mask_vertexes` WHERE `mask_id`=%d", maskID ); -#ifdef DEBUG +#ifdef DEBUG_ALL LOG(tQBuf); #endif m_pDataStorage->SilentQuery( tQBuf ); //Delete Mask Itself! if ( deleteMask ) { sprintf( tQBuf, "DELETE FROM `lrf_masks` WHERE `id`=%d", maskID ); -#ifdef DEBUG_EXTRA +#ifdef DEBUG_ALL LOG(tQBuf); #endif m_pDataStorage->SilentQuery( tQBuf ); @@ -1215,7 +1215,7 @@ bool sqliteDBC::cleanLRFWidthTable( uint32_t sensorID ){ if( m_bStoIsConnected ) { char tQBuf[MAX_PATH_LEN]; sprintf( tQBuf, "DELETE FROM `lrf_detection_width_tables` WHERE `aux_id`=%d", sensorID ); -#ifdef DEBUG_EXTRA +#ifdef DEBUG_ALL LOG(tQBuf); #endif m_pDataStorage->SilentQuery( tQBuf ); @@ -1286,7 +1286,7 @@ uint32_t sqliteDBC::addLRFMaskPolygone( uint32_t maskID, uint8_t vertexID, uint8 g, b ); -#ifdef DEBUG +#ifdef DEBUG_ALL LOG(tQBuf); #endif RetVal = m_pDataStorage->QueryID( tQBuf ); @@ -1305,7 +1305,7 @@ bool sqliteDBC::addLRFMaskPolygonePoint( uint32_t polyID, int16_t x, int16_t y ) x, y ); -#ifdef DEBUG +#ifdef DEBUG_ALL LOG(tQBuf); #endif m_pDataStorage->SilentQuery( tQBuf ); @@ -1325,7 +1325,7 @@ bool sqliteDBC::addLRFWidthTable( uint32_t sensorID, PWIDTH_TABLE ptr ){ ptr->pTable[i], CC ); -#ifdef DEBUG +#ifdef DEBUG_ALL LOG(tQBuf); #endif m_pDataStorage->SilentQuery( tQBuf ); @@ -1343,7 +1343,7 @@ bool sqliteDBC::addPicture( DBC_SNAPSHOT_DATA *ptr, CSTR ext ){ uint32_t pic_id; sprintf( tQBuf, "%s/%s/%s/%s/%s.%s", m_pDbReportBase, m_sCRepInfo.YEAR, m_sCRepInfo.MONTH, m_sCRepInfo.DAY, ptr->md5, ext ); -#ifdef DEBUG +#ifdef DEBUG_ALL LOG(tQBuf); #endif @@ -1409,7 +1409,7 @@ bool sqliteDBC::addVideoEvent( uint32_t evtID, uint32_t videoID, uint32_t frame, tss, tms ); -#ifdef DEBUG_EXTRA +#ifdef DEBUG_ALL LOG(tQBuf); #endif m_pDataReports->SilentQuery( tQBuf ); @@ -1430,7 +1430,7 @@ uint32_t sqliteDBC::addVideoRecord( uint32_t streamID, CSTR md5, CSTR ext, uint3 ext, fps ); -#ifdef DEBUG_EXTRA +#ifdef DEBUG_ALL LOG(tQBuf); #endif RetVal = (uint32_t) m_pDataReports->QueryID( tQBuf ); @@ -1821,7 +1821,7 @@ DBC_LRF_INI *sqliteDBC::getINIData( uint32_t lrfID ){ char tQBuf[CTEXT]; AAssoc *result; sprintf(tQBuf, "SELECT * FROM `lrf_ini_settings` WHERE `sensor_id`=%d", lrfID ); -#ifdef DEBUG +#ifdef DEBUG_ALL LOG(tQBuf); #endif result = m_pDataStorage->Query( tQBuf ); @@ -2165,7 +2165,7 @@ PLGS_2D_PARAMETERS sqliteDBC::getLRFDetectionProfile( uint32_t lrfID, uint8_t pr AAssoc *result; sprintf(tQBuf, "SELECT * FROM `lrf_detection_profiles` WHERE `aux_id`=%d AND `profile_id`=%d AND `master`=%d", lrfID, profileID,((master)?1:0) ); -#ifdef DEBUG +#ifdef DEBUG_ALL LOG(tQBuf); #endif result = m_pDataStorage->Query( tQBuf ); @@ -2279,7 +2279,7 @@ uint32_t sqliteDBC::getLRFMaskID( uint32_t deviceID, uint8_t lrfID, uint8_t laye char tQBuf[CTEXT]; AAssoc *result; sprintf(tQBuf, "SELECT `id` FROM `lrf_masks` WHERE `sensor_id`=%d AND `lrf_id`=%d AND `layer`=%d ", deviceID, lrfID, layer ); -#ifdef DEBUG +#ifdef DEBUG_ALL LOG(tQBuf); #endif result = m_pDataStorage->Query( tQBuf ); @@ -2305,7 +2305,7 @@ uint32_t sqliteDBC::getLRFMaskPolygoneID( uint32_t maskID, uint8_t vertecID ){ char tQBuf[CTEXT]; AAssoc *result; sprintf(tQBuf, "SELECT `id` FROM `lrf_mask_vertexes` WHERE `mask_id`=%d AND `vertex_id`=%d", maskID, vertecID ); -#ifdef DEBUG +#ifdef DEBUG_ALL LOG(tQBuf); #endif result = m_pDataStorage->Query( tQBuf ); @@ -2331,7 +2331,7 @@ uint8_t sqliteDBC::getLRFMasksStatus( uint32_t deviceID ){ char tQBuf[CTEXT]; AAssoc *result; sprintf(tQBuf, "SELECT `layer` FROM `lrf_masks` WHERE `sensor_id`=%d AND `status`='E'", deviceID ); -#ifdef DEBUG +#ifdef DEBUG_ALL LOG(tQBuf); #endif result = m_pDataStorage->Query( tQBuf ); @@ -2359,7 +2359,7 @@ DBC_LRF_UPLOAD_DATA *sqliteDBC::getLRFUploadData( uint32_t upID ){ char tQBuf[CTEXT]; AAssoc *result; sprintf(tQBuf, "SELECT * FROM `lrf_uploads` WHERE `id`=%d", upID ); -#ifdef DEBUG +#ifdef DEBUG_ALL LOG(tQBuf); #endif result = m_pDataStorage->Query( tQBuf ); @@ -2398,7 +2398,7 @@ DBC_WIDTH_TABLE *sqliteDBC::getLRFWidthTable( uint32_t lrfID ){ char tQBuf[CTEXT]; AAssoc *result; sprintf(tQBuf, "SELECT `range_k`, `width_k` FROM `lrf_detection_width_tables` WHERE `aux_id`=%d ORDER BY `range_k`", lrfID ); -#ifdef DEBUG_EXTRA +#ifdef DEBUG_ALL LOG(tQBuf); #endif memset( retVal, 0 , sizeof( DBC_WIDTH_TABLE )); @@ -2443,7 +2443,7 @@ uint32_t sqliteDBC::getNodeAuxParam( uint32_t NodeID ){ char tQBuf[CTEXT]; AAssoc *result; sprintf(tQBuf, "SELECT `aux_parameter` FROM `nodes` WHERE `id`=%d", NodeID ); -#ifdef DEBUG_EXTRA +#ifdef DEBUG_ALL LOG(tQBuf); #endif result = m_pDataStorage->Query( tQBuf ); @@ -2469,7 +2469,7 @@ DBC_NODE_DATA *sqliteDBC::getNodeData( uint32_t ID ){ char tQBuf[CTEXT]; AAssoc *result; sprintf(tQBuf, "SELECT * FROM `nodes` WHERE `id`=%d", ID ); -#ifdef DEBUG_EXTRA +#ifdef DEBUG_ALL LOG(tQBuf); #endif result = m_pDataStorage->Query( tQBuf ); @@ -2520,7 +2520,7 @@ uint32_t sqliteDBC::getNodeIdByTypeAndAux( uint8_t type, uint32_t aux_id ){ char tQBuf[CTEXT]; AAssoc *result; sprintf(tQBuf, "SELECT `id` FROM `nodes` WHERE `type`=%d AND `aux_id`=%d", type, aux_id); -#ifdef DEBUG_EXTRA +#ifdef DEBUG_ALL LOG(tQBuf); #endif result = m_pDataStorage->Query( tQBuf ); @@ -2546,7 +2546,7 @@ CSTR sqliteDBC::getNodeName( uint32_t NodeID ){ char tQBuf[CTEXT]; AAssoc *result; sprintf(tQBuf, "SELECT `name` FROM `nodes` WHERE `id`=%d", NodeID ); -#ifdef DEBUG_EXTRA +#ifdef DEBUG_ALL LOG(tQBuf); #endif result = m_pDataStorage->Query( tQBuf ); @@ -2572,7 +2572,7 @@ DBC_NET_IF_DATA *sqliteDBC::getNIF_Data( uint32_t nif_id ){ char tQBuf[CTEXT]; AAssoc *result; sprintf(tQBuf, "SELECT `type`, `mode`, `device_name`, `mac`, `aux_id` FROM `network_interfaces` WHERE `id`=%d", nif_id ); -#ifdef DEBUG_EXTRA +#ifdef DEBUG_ALL LOG(tQBuf); #endif result = m_pDataStorage->Query( tQBuf ); @@ -2947,7 +2947,7 @@ DBC_TARGET_FLITER_DATA *sqliteDBC::getTargetFilterData( uint32_t ID ){ char tQBuf[CTEXT]; AAssoc *result; sprintf(tQBuf, "SELECT * FROM `target_filters` WHERE `id`=%d", ID ); -#ifdef DEBUG +#ifdef DEBUG_ALL LOG(tQBuf); #endif result = m_pDataStorage->Query( tQBuf ); @@ -2986,7 +2986,7 @@ TRAIN_FILTER_DATA *sqliteDBC::getTrainFilterData( uint32_t ID ){ char tQBuf[CTEXT]; AAssoc *result; sprintf(tQBuf, "SELECT * FROM `target_filter_train` WHERE `id`=%d", ID ); -#ifdef DEBUG_EXTRA +#ifdef DEBUG_ALL LOG(tQBuf); #endif result = m_pDataStorage->Query( tQBuf ); @@ -3149,7 +3149,7 @@ DBC_INT_LIST *sqliteDBC::listCamPresets( uint32_t SETID ){ char tQBuf[CTEXT]; AAssoc *result; sprintf(tQBuf, "SELECT `id` FROM `cameras_presets` WHERE `preset_id`=%d", SETID ); -#ifdef DEBUG +#ifdef DEBUG_ALL LOG(tQBuf); #endif result = m_pDataStorage->Query( tQBuf ); @@ -3180,7 +3180,7 @@ DBC_INT_LIST *sqliteDBC::listFilters( uint32_t ServerID ){ char tQBuf[CTEXT]; AAssoc *result; sprintf(tQBuf, "SELECT `id` FROM `target_filters` WHERE `enabled`=1" ); -#ifdef DEBUG +#ifdef DEBUG_ALL LOG(tQBuf); #endif result = m_pDataStorage->Query( tQBuf ); @@ -3211,7 +3211,7 @@ DBC_INT_LIST *sqliteDBC::listLRFUploads( uint32_t deviceID ){ char tQBuf[CTEXT]; AAssoc *result; sprintf(tQBuf, "SELECT `id` FROM `lrf_uploads` WHERE `status`=-1 AND `sensor_id`=%d", deviceID ); -#ifdef DEBUG +#ifdef DEBUG_ALL LOG(tQBuf); #endif result = m_pDataStorage->Query( tQBuf ); @@ -3359,7 +3359,7 @@ DBC_INT_LIST *sqliteDBC::listNewNodes( DBC_INT_LIST * old_ids ){ char tQBuf[CTEXT]; AAssoc *result; sprintf(tQBuf, "SELECT id FROM nodes WHERE `type` > 0 AND `enable`=1 AND `id` NOT IN(%s)", tParam ); -#ifdef DEBUG_EXTRA +#ifdef DEBUG_ALL LOG(tQBuf); #endif result = m_pDataStorage->Query( tQBuf ); @@ -3394,7 +3394,7 @@ DBC_INT_LIST *sqliteDBC::listNodes( bool all ){ } else { sprintf(tQBuf, "SELECT `id` FROM `nodes` WHERE `type` > 0 AND `enable`=1" ); }; -#ifdef DEBUG_EXTRA +#ifdef DEBUG_ALL LOG(tQBuf); #endif result = m_pDataStorage->Query( tQBuf ); @@ -3513,7 +3513,7 @@ DBC_INT_LIST *sqliteDBC::listResources( uint32_t NodeID ){ AAssoc *result; if ( NodeID == 0 ) NodeID = m_nServerNodeID; sprintf(tQBuf, "SELECT `id` FROM `resources` WHERE `node_id`=%d", NodeID ); -#ifdef DEBUG +#ifdef DEBUG_ALL LOG(tQBuf); #endif result = m_pDataStorage->Query( tQBuf ); @@ -3805,7 +3805,9 @@ bool sqliteDBC::fillShadow2D( uint32_t ID, SHADOW & SH ){ char tQBuf[CTEXT]; AAssoc *result; sprintf(tQBuf, "SELECT `lv`.`id`, `lm`.`layer`, `lm`.`status` FROM `lrf_mask_vertexes` `lv` LEFT JOIN `lrf_masks` `lm` ON (`lm`.`id` = `lv`.`mask_id`) WHERE `lm`.`sensor_id`=%d ORDER BY `lv`.`id`", ID ); +#ifdef DEBUG_ALL LOG(tQBuf); +#endif result = m_pDataStorage->Query( tQBuf ); if( result!= NULL ) { if( result->size() > 0 ) { @@ -3830,7 +3832,9 @@ bool sqliteDBC::fillShadow2D( uint32_t ID, SHADOW & SH ){ SH.m_nEnabled &= ( it->second.c_str()[0] == 'E' )?0xFFFFFFFF:~(1<Query( tQBuf ); if( v_result!= NULL ) { if( v_result->size() > 0 ) { @@ -4285,7 +4289,7 @@ bool sqliteDBC::updateCamRange( uint32_t camID, float range ){ range, camID ); -#ifdef DEBUG_EXTRA +#ifdef DEBUG_ALL LOG(tQBuf); #endif m_pDataStorage->SilentQuery( tQBuf ); diff --git a/lib/App/common/deviceNode2D.cpp b/lib/App/common/deviceNode2D.cpp index b91cc22e..6cc97c4c 100644 --- a/lib/App/common/deviceNode2D.cpp +++ b/lib/App/common/deviceNode2D.cpp @@ -3086,7 +3086,7 @@ bool device2DSensor::packetHandler( protocolPackage *Package ){ break; }; case 0x02:{ -#ifdef DEBUG_ALL +#ifdef DEBUG_EXTRA LOG("SUB PACKAGE - Maintenance notification"); sprintf( tBuff, "Sub Size: %d", Package->m_pData[cIDX] ); LOG( tBuff ); diff --git a/lib/App/common/deviceNodeCamera.cpp b/lib/App/common/deviceNodeCamera.cpp index 8ffc2a31..bec9bf08 100644 --- a/lib/App/common/deviceNodeCamera.cpp +++ b/lib/App/common/deviceNodeCamera.cpp @@ -1096,7 +1096,9 @@ void deviceNodeCamera::m_fThreadProc( void ){ }; }; } else { +#ifdef DEBUG_EXTRA LOG("Not Found!"); +#endif utilizeROI( m_pCurrentROI ); setWM( CAM_WS_READY ); }; diff --git a/lib/App/common/hardwareResourceSerialProvider.cpp b/lib/App/common/hardwareResourceSerialProvider.cpp index 30a66047..65131f56 100644 --- a/lib/App/common/hardwareResourceSerialProvider.cpp +++ b/lib/App/common/hardwareResourceSerialProvider.cpp @@ -1,1375 +1,1375 @@ -#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__ +#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__ if( m_bManualRTS ){ - setRTS( 1 ); + 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; }; - 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 +#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 diff --git a/lib/App/common/hardwareResourceSerialProvider.h b/lib/App/common/hardwareResourceSerialProvider.h index c27ff1e5..5a3a77f5 100644 --- a/lib/App/common/hardwareResourceSerialProvider.h +++ b/lib/App/common/hardwareResourceSerialProvider.h @@ -36,7 +36,7 @@ #ifdef DEBUG_EXTRA - #define DEBUG_SERIAL_COMMUNICATION + //#define DEBUG_SERIAL_COMMUNICATION #endif #ifndef MAXIMAL_SOCKET_PACKET_LENGTH diff --git a/lib/App/common/kernelModuleEmbedVideo.cpp b/lib/App/common/kernelModuleEmbedVideo.cpp index cedf5024..5ff5e258 100644 --- a/lib/App/common/kernelModuleEmbedVideo.cpp +++ b/lib/App/common/kernelModuleEmbedVideo.cpp @@ -141,8 +141,25 @@ kernelModuleEmbedVideo::~kernelModuleEmbedVideo(){ #ifdef DEBUG LOG("Destructor"); #endif - m_bEnabled = false; - waitThreadAEnd( true ); + m_bEnabled = false; + + LOG("Locking in Destructor!"); + m_mStreamHandlersProtector.lock(); + if( m_mapHANDLERS.size() ){ +#ifdef DEBUG + LOG("Deleting Stream Handlers!"); +#endif + for( mapSTREAMHANDLERS::iterator idx = m_mapHANDLERS.begin(); idx != m_mapHANDLERS.end(); idx++ ){ +#ifdef DEBUG + LOG("Deleting Stream Handler"); +#endif + delete( (*idx).second ); + } + m_mapHANDLERS.clear(); + }; + m_mStreamHandlersProtector.unlock(); + + waitThreadAEnd( true ); if( m_vHandlersPool.size() ) { // Kill-Wait Started Probes #ifdef DEBUG char tB[200]; @@ -172,21 +189,7 @@ kernelModuleEmbedVideo::~kernelModuleEmbedVideo(){ LOG("No More Viewers Left"); #endif - LOG("Locking in Destructor!"); - m_mStreamHandlersProtector.lock(); - if( m_mapHANDLERS.size() ){ -#ifdef DEBUG - LOG("Deleting Stream Handlers!"); -#endif - for( mapSTREAMHANDLERS::iterator idx = m_mapHANDLERS.begin(); idx != m_mapHANDLERS.end(); idx++ ){ -#ifdef DEBUG - LOG("Deleting Stream Handler"); -#endif - delete( (*idx).second ); - } - m_mapHANDLERS.clear(); - }; - m_mStreamHandlersProtector.unlock(); + #ifdef DEBUG LOG("Deleting CAPS"); #endif @@ -255,7 +258,7 @@ void *kernelModuleEmbedVideo::webClientProc( void *ptr ){ uint8_t tBuf[FILESTREAMBUFFERSZ]; int retVal; bool w = true; - + TLOG( "Start WebClient" ); if( CTX ) { char mesg[1024]; size_t RecvSize; @@ -523,6 +526,7 @@ void *kernelModuleEmbedVideo::webClientProc( void *ptr ){ TLOG("WEB Client Handler Ended!"); #endif pthread_exit( NULL ); + TLOG( "After Pthread Ecit!" ); return NULL; }; @@ -552,6 +556,7 @@ void *kernelModuleEmbedVideo::viewClientProc( void *ptr ){ uint8_t baba[2]={0xff,0xd8}; uint8_t yaba[2]={0xff,0xd9}; FILE * tFID = NULL; + TLOG( "Start ViewClient" ); if( CTX ) { char mesg[1024]; size_t RecvSize; @@ -777,11 +782,12 @@ void *kernelModuleEmbedVideo::viewClientProc( void *ptr ){ TLOG("Close Socket"); #endif close( CTX->m_iSocketFID ); - //pthread_exit( NULL ); CTX->bValid = false; #ifdef DEBUG_EXTRA TLOG("View Client Handler Ended!"); #endif + pthread_exit( NULL ); + TLOG( "After Pthread Exit" ); return NULL; }; @@ -1766,6 +1772,7 @@ streamHandler::streamHandler( kernelModuleEmbedVideo *ptr, MS_WORK_MODE M ): m_p }; streamHandler::~streamHandler(){ + LOG("Destructor"); if ( m_sStreamData.id ) { LOG("Deleting Source!"); if( m_pSource != NULL ) { @@ -2926,8 +2933,8 @@ bool streamHandler::initVideoOutput(){ return false; }; - //m_pEncoderA->set( cv::VIDEOWRITER_PROP_QUALITY, 50.0 ); - //m_pEncoderA->set( cv::VIDEOWRITER_PROP_NSTRIPES, 4 ); + m_pEncoderA->set( cv::VIDEOWRITER_PROP_QUALITY, 30.0 ); + m_pEncoderA->set( cv::VIDEOWRITER_PROP_NSTRIPES, -1.0 ); m_pEncoderB = new cv::VideoWriter(); if ( m_pEncoderA == NULL ) { @@ -2935,8 +2942,8 @@ bool streamHandler::initVideoOutput(){ return false; }; - //m_pEncoderB->set( cv::VIDEOWRITER_PROP_QUALITY, 50.0 ); - //m_pEncoderB->set( cv::VIDEOWRITER_PROP_NSTRIPES, 4 ); + m_pEncoderB->set( cv::VIDEOWRITER_PROP_QUALITY, 30.0 ); + m_pEncoderB->set( cv::VIDEOWRITER_PROP_NSTRIPES, -1.0 ); #else if( !initLibAV() ) return false; diff --git a/lib/App/mojo/mojoBackend.cpp b/lib/App/mojo/mojoBackend.cpp index 8500d91d..927a4f39 100644 --- a/lib/App/mojo/mojoBackend.cpp +++ b/lib/App/mojo/mojoBackend.cpp @@ -93,6 +93,7 @@ config_setting_t * Settings = NULL; void (*old_kill_handler_9)(int); void (*old_kill_handler_15)(int); +void (*old_kill_handler_11)(int); void signal_kill_handler( int SIG ){ if( Kernel!= NULL ){ @@ -105,6 +106,22 @@ void signal_kill_handler( int SIG ){ }; }; +#define _GNU_SOURCE 1 +#include +struct sigaction sa; +void segfault_sigaction( int signal, siginfo_t *si, void *arg ){ + ucontext_t *MM = (ucontext_t *)arg; + FILE *fd = fopen( "S_Trace.txt", "w"); + if ( fd ) { + pid_t M = getpid(); + pid_t P = getppid(); + fprintf(fd, "Caught segfault[%d] at address %p\n PID: %p PPID %p\n Gregs %p\n", signal, si->si_addr, M, P, uc->uc_mcontext.gregs[REG_RIP] ); + fclose( fd ); + }; + exit(27); +}; + + int main( int argc, char *argv[] ){ bool WBG; // Working Background @@ -443,6 +460,15 @@ int main( int argc, char *argv[] ){ delete( m_pLog ); return -1; }; + + + memset(&sa, 0, sizeof(struct sigaction)); + sigemptyset(&sa.sa_mask); + sa.sa_sigaction = segfault_sigaction; + sa.sa_flags = SA_SIGINFO; + sigaction(SIGSEGV, &sa, NULL); + //old_kill_handler_11 = signal( 11, segfault_sigaction ); + //Loop till some Restart action if( Kernel != NULL ){ LOG( "++++ Server Started ++++" ); @@ -452,6 +478,7 @@ int main( int argc, char *argv[] ){ //Install Signal Listeners old_kill_handler_15 = signal( 15, signal_kill_handler ); old_kill_handler_9 = signal( 9, signal_kill_handler ); + // Waiting for Worker to Shut Down Kernel->WaitFinish( false ); ExitCode = Kernel->getExitCause(); diff --git a/lib/App/mojo/mojoKernel.cpp b/lib/App/mojo/mojoKernel.cpp index f06784a6..7d473adb 100644 --- a/lib/App/mojo/mojoKernel.cpp +++ b/lib/App/mojo/mojoKernel.cpp @@ -132,6 +132,10 @@ mojoKernel::~mojoKernel(){ }; bool mojoKernel::create(){ + + + int *tt = NULL;*tt+=23; + if( m_pSettings != NULL ) { config_setting_t * pSetting; int tVal; diff --git a/lib/data/protocol/protocol.h b/lib/data/protocol/protocol.h index 91478e80..0f298b2f 100644 --- a/lib/data/protocol/protocol.h +++ b/lib/data/protocol/protocol.h @@ -14,9 +14,9 @@ #define PROTOCOL_PARSER_BUFFER_SIZE 102400 #ifdef DEBUG_EXTRA - #ifndef DUBUG_COMMUNICATION - #define DUBUG_COMMUNICATION - #endif + //#ifndef DUBUG_COMMUNICATION + // #define DUBUG_COMMUNICATION + //#endif #endif typedef struct S_protocolPackage{ diff --git a/lib/data/sqlite/sqlite_class.cpp b/lib/data/sqlite/sqlite_class.cpp index a4fce6a5..45d3703d 100644 --- a/lib/data/sqlite/sqlite_class.cpp +++ b/lib/data/sqlite/sqlite_class.cpp @@ -188,7 +188,7 @@ bool SQLite_Connector::SilentQuery( CSTR QS ){ return false; }; -#ifdef DEBUG_EXTRA +#ifdef DEBUG_ALL LOG( sqlite3_expanded_sql( query ) ); #endif @@ -233,7 +233,7 @@ AAssoc *SQLite_Connector::Query( CSTR QS, bool useCache ){ m_mAccessMutex.unlock(); return RetVal; }; -#ifdef DEBUG_EXTRA +#ifdef DEBUG_ALL LOG( sqlite3_expanded_sql( query ) ); #endif RetVal = new AAssoc(); @@ -377,7 +377,7 @@ uint64_t SQLite_Connector::QueryID( CSTR QS ){ m_mAccessMutex.unlock(); return RetVal; }; -#ifdef DEBUG_EXTRA +#ifdef DEBUG_ALL LOG( sqlite3_expanded_sql( query ) ); #endif tVal = sqlite3_last_insert_rowid( m_pDBLink ); diff --git a/lib/hardware/uart/serialPort.h b/lib/hardware/uart/serialPort.h index f4a17cfa..54691872 100644 --- a/lib/hardware/uart/serialPort.h +++ b/lib/hardware/uart/serialPort.h @@ -17,9 +17,9 @@ #include "../../data/transport/transportSerial.h" #ifdef DEBUG_EXTRA - #ifdef DEBUG_COMMUNICATION - #define DEBUG_SERIAL_COMMUNICATION - #endif + //#ifdef DEBUG_COMMUNICATION + //#define DEBUG_SERIAL_COMMUNICATION + //#endif #endif /** diff --git a/lib/rgoose/rgooseHardwareResourceSerialProvider.h b/lib/rgoose/rgooseHardwareResourceSerialProvider.h index 1065c6b7..b0d7d6fb 100644 --- a/lib/rgoose/rgooseHardwareResourceSerialProvider.h +++ b/lib/rgoose/rgooseHardwareResourceSerialProvider.h @@ -23,7 +23,7 @@ #ifdef DEBUG_EXTRA - #define DEBUG_SERIAL_COMMUNICATION + //#define DEBUG_SERIAL_COMMUNICATION #endif #ifndef MAXIMAL_SOCKET_PACKET_LENGTH