#include "LRF_TwinConnector.h" #include "LRF_Kernel.h" #include "LRF_TargetTracker.h" #ifdef TWI_TH_USE_PICTURES #define STB_IMAGE_IMPLEMENTATION #include "../../data/stbi/stb_image.h" #define STB_IMAGE_WRITE_IMPLEMENTATION #include "../../data/stbi/stb_image_write.h" #undef STB_IMAGE_WRITE_IMPLEMENTATION #undef STB_IMAGE_IMPLEMENTATION #endif #define LOG( X ) m_pLog->Log( "TWINC", this, X ) #ifdef DEBUG #define LOG_ERROR( X ) {\ char _tBfrErrMSG234[256];\ sprintf( _tBfrErrMSG234, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ m_pLog->Log( "TWINC", this, _LOG_ERROR, _tBfrErrMSG234 );\ } #else #define LOG_ERROR( X ) m_pLog->Log( "TWINC", this, _LOG_ERROR, X ); #endif #define SLOG( X ) Me->m_pLog->Log( "TWINC", Me, X ) #ifdef DEBUG #define SLOG_ERROR( X ) {\ char _tBfrErrMSG234[256];\ sprintf( _tBfrErrMSG234, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\ Me->m_pLog->Log( "TWINC", Me, _LOG_ERROR, _tBfrErrMSG234 );\ } #else #define SLOG_ERROR( X ) Me->m_pLog->Log( "TWINC", Me, _LOG_ERROR, X ); #endif LRF_TwinConnector::LRF_TwinConnector( config_setting_t *Settings ): basicThread(){ m_pLog = basicLogCollection::getInstance(); m_pSettings = basicSettingsProvider::getInstance()->getSubNode( Settings, (CSTR)"TWIN_3DLRF_CONNECTION" ); m_pPort = NULL; m_pEngine = NULL; m_nStatus = 0; #ifdef PRU_SLAVE m_nMasterPort = 0; m_pMasterAddress = (CSTR) malloc( 16 ); m_bWorkingMode = TWI_STAGE_WAITING_CONNECTION; #else m_nMainSocket = -1; m_nBindPort = 0; m_pBindAddress = (CSTR) malloc( 16 ); m_bWorkingMode = TWI_STAGE_BEFORE_BIND; #endif }; LRF_TwinConnector::~LRF_TwinConnector(){ if( m_pPort != NULL ) delete( m_pPort ); if (m_bDrawThreadStatus > TH_ARMED ) { waitDrawThreadEnd( true ); // JOIN in Wait function!! //pthread_detach(m_sThreadHandler); //pthread_join(m_sThreadHandler, NULL); }; #ifdef PRU_SLAVE if( m_pMasterAddress ) free( m_pMasterAddress ); #else if( m_pBindAddress ) free( m_pBindAddress ); #endif }; bool LRF_TwinConnector::create(){ if( m_pSettings!= NULL ) { config_setting_t *pSetting; int tVal; char tBuffer[256]; #ifdef PRU_SLAVE if (!config_setting_lookup_string(m_pSettings, "MASTER_ADDRESS", (const char**)&m_pMasterAddress)) { strncpy( m_pMasterAddress, "10.0.0.1", 15 ); pSetting = config_setting_add(m_pSettings, "MASTER_ADDRESS", CONFIG_TYPE_STRING); config_setting_set_string(pSetting, m_pMasterAddress); basicSettingsProvider::getInstance()->compromise(); } else { sprintf( tBuffer, "MASTER IP Address Read From Settings: %s", m_pMasterAddress ); LOG( tBuffer ); }; if( !config_setting_lookup_int( m_pSettings, "MASTER_PORT", &tVal ) ){ tVal = m_nMasterPort = 6564; pSetting = config_setting_add( m_pSettings, "MASTER_PORT", CONFIG_TYPE_INT ); config_setting_set_bool( pSetting, tVal ); basicSettingsProvider::getInstance()->compromise(); } else { m_nMasterPort = tVal; sprintf( tBuffer, "MASTER PORT Read From Settings: %d", tVal ); LOG( tBuffer ); }; #else if (!config_setting_lookup_string(m_pSettings, "BIND_ADDRESS", (const char**)&m_pBindAddress)) { strncpy( m_pBindAddress, "10.0.0.1", 15 ); pSetting = config_setting_add(m_pSettings, "BIND_ADDRESS", CONFIG_TYPE_STRING); config_setting_set_string(pSetting, m_pBindAddress); basicSettingsProvider::getInstance()->compromise(); } else { sprintf( tBuffer, "BIND to IP Address Read From Settings: %s", m_pBindAddress ); LOG( tBuffer ); }; if( !config_setting_lookup_int( m_pSettings, "BIND_PORT", &tVal ) ){ tVal = m_nBindPort = 6564; pSetting = config_setting_add( m_pSettings, "BIND_PORT", CONFIG_TYPE_INT ); config_setting_set_bool( pSetting, tVal ); basicSettingsProvider::getInstance()->compromise(); } else { m_nBindPort = tVal; sprintf( tBuffer, "BIND to PORT Read From Settings: %d", tVal ); LOG( tBuffer ); }; #endif if( basicSettingsProvider::getInstance()->isCompromised() ) { LOG("Save Settings"); basicSettingsProvider::getInstance()->validate(); }; } else { LOG_ERROR("No Settings Provided!"); return false; }; #ifdef PRU_SLAVE //m_pProtocol = new protocolInternalLRF3D_SLAVE(); //if( m_pProtocol == NULL ){ // LOG_ERROR("Error creating protocol!"); // return false; //}; if( !protocolInternalLRF3D_SLAVE::create() ) return false; #else int RetCode; struct hostent * h_info; struct sockaddr_in * MainSocketAddress = NULL; //m_pProtocol = new protocolInternalLRF3D_MASTER(); //if( m_pProtocol == NULL ){ // LOG_ERROR("Error creating protocol!"); // return false; //}; if( !protocolInternalLRF3D_MASTER::create() ) return false; m_nMainSocket = socket( AF_INET, SOCK_STREAM, 0 ); if( m_nMainSocket == -1){ LOG_ERROR( "Some trouble with networking on this machine (Socket Error)!"); return false; }; MainSocketAddress = ( struct sockaddr_in * ) malloc( sizeof( struct sockaddr_in ) ); if( MainSocketAddress == NULL ){ LOG_ERROR( "Some trouble with networking on this machine (Cannot Alloc Sockaddr Struct)!" ); return false; }; bzero( MainSocketAddress, sizeof( struct sockaddr_in ) ); h_info = gethostbyname ( m_pBindAddress ); if ( h_info == NULL ){ LOG_ERROR( "Some trouble with networking on this machine (Cannot Get Hostname)!" ); return false; }; //***************************************** //* there we building our network address * //***************************************** bcopy( h_info->h_addr, &(MainSocketAddress->sin_addr), h_info->h_length ); MainSocketAddress->sin_family = h_info->h_addrtype; MainSocketAddress->sin_port = htons( m_nBindPort ); RetCode = bind( m_nMainSocket ,(struct sockaddr *) MainSocketAddress, sizeof( struct sockaddr_in ) ); if ( RetCode != 0 ){ LOG_ERROR( "Error Binding to Port/Address" ); return false; }; RetCode = listen( m_nMainSocket, 128); if ( RetCode != 0 ){ LOG_ERROR( "Cannot Listen Port/Address" ); return false; }; U8 dontblock; dontblock = fcntl( m_nMainSocket, F_GETFL, NULL ); dontblock |= O_NONBLOCK | O_NDELAY; RetCode = ioctl( m_nMainSocket, FIONBIO, (char *) &dontblock ); if ( RetCode == 0 ){ LOG( "Set N-Blocking Mode of Accepting Socket" ); } else { LOG( "Can't set N-Blocking Mode of Accepting Socket" ); }; #endif // PRU_SLAVE m_bWorkingMode = TWI_STAGE_WAITING_CONNECTION; return init(); }; void *LRF_TwinConnector::m_fDrawThreadEntryPoint( void *ptr ){ LRF_TwinConnector *Me; if( ptr == NULL ) return NULL; Me = (LRF_TwinConnector*) ptr; #ifdef DEBUG SLOG("TH Thread OK"); #endif if( Me->m_bDrawThreadStatus == TH_ARMED ) { #ifdef DEBUG SLOG("TH Image Thread ARMED!"); #endif Me->m_bDrawThreadStatus = TH_WORKING; if( Me->m_pEngine!= NULL ) { // Store Local TH Draws thresholdNode *tMem; uint32_t tSize; #ifdef DEBUG SLOG("Kernel is Defined!"); #endif for( uint8_t i=0; i<16; i++ ) { // just in case if we must end work if( Me->m_bDrawThreadStatus != TH_WORKING ) break; tMem = Me->m_pEngine->getTreshold( tSize, i ); if( tMem!= NULL ) { char tBuffer[256]; #ifdef TWI_TH_USE_PICTURES sprintf( tBuffer, "data/th_data_%d.png", i ); #ifdef DEBUG SLOG("SAVE TH Image ..."); SLOG( tBuffer ); #endif if( !Me->saveTHPicture( tMem, tBuffer, false )){ SLOG_ERROR("TH PNG save failure!"); } #ifdef PRU_SLAVE else { Me->m_mStatusProtector.lock(); Me->m_nStatus |= ( 1 << i ) << 16; Me->m_mStatusProtector.unlock(); } #endif ; #ifdef DEBUG SLOG("SAVE TH Image DONE!"); #endif SLEEP(10); #else //TWI_TH_USE_PICTURES sprintf( tBuffer, "data/th_data_%d.raw", i ); #ifdef DEBUG SLOG("SAVE TH Data ..."); SLOG( tBuffer ); #endif FILE *fd; fd = fopen( tBuffer, "wb+"); if( fd != NULL ){ uint32_t Size = TH_SIZE_NODES; fwrite( &Size, sizeof( uint32_t ), 1, fd ); fwrite( tMem, sizeof( thresholdNode ), Size, fd ); fclose( fd ); #ifdef PRU_SLAVE Me->m_mStatusProtector.lock(); Me->m_nStatus |= ( 1 << i ) << 16; Me->m_mStatusProtector.unlock(); #endif } else { SLOG_ERROR("TH RAW save failure!"); }; #ifdef DEBUG SLOG("SAVE TH Data DONE!"); #endif #endif //TWI_TH_USE_PICTURES }; }; }; }; Me->m_bDrawThreadStatus = TH_EXIT; Me->m_mDrawProtector.unlock(); pthread_exit( NULL ); return NULL; }; void LRF_TwinConnector::waitDrawThreadEnd( bool forced ){ if( m_bDrawThreadStatus > TH_WORKING || m_bDrawThreadStatus < TH_ARMED ) return; if( forced ) m_bDrawThreadStatus = TH_ENDED; while( m_bDrawThreadStatus != TH_EXIT ){ SLEEP(DEFAULT_THREAD_SLEEP_TIME); }; pthread_join( m_sDrawThreadHandler, NULL ); }; #ifdef PRU_SLAVE bool LRF_TwinConnector::packetHandler( protocolPackage *Package ){ if( Package == NULL ) return false; TWIN_COMMAND cCMD = (TWIN_COMMAND) Package->m_pData[3]; switch( cCMD ) { case TWC_GET_STATUS:{ m_mStatusProtector.lock(); sendStatus( m_nStatus ); m_mStatusProtector.unlock(); break; }; }; return true; }; void LRF_TwinConnector::m_fThreadProc( void ){ TWIN_CMD_REC * tCMD = NULL; int ClientSocket = -1; struct sockaddr ClientAddress; socklen_t ClientAddressSize; long long cMilliseconds; long long cStatusTO = 0; long long cDrawTO = 0; m_bThreadStatus = TH_WORKING; while( m_bThreadStatus < TH_ENDED ){ cMilliseconds = getMilliseconds(); // TH Saving procedure if( cDrawTO == 0 ) { cDrawTO = cMilliseconds; } else if ( ( cMilliseconds - cDrawTO ) > TWI_DRAW_LOOP_MS ){ #ifdef DEBUG LOG("Try to Dump TH Images"); #endif if( m_mDrawProtector.try_lock() ) { #ifdef DEBUG LOG("Mutex Grabed"); #endif if( m_bDrawThreadStatus > TH_ARMED ) { pthread_join( m_sDrawThreadHandler, NULL ); }; cDrawTO = cMilliseconds; m_bDrawThreadStatus = TH_ARMED; int RetVal = pthread_create( &m_sDrawThreadHandler, NULL, m_fDrawThreadEntryPoint, ( void * ) this ); if( RetVal == -1 ) { LOG_ERROR("Image Draw Thread Creation Failed."); m_mDrawProtector.unlock(); }; } #ifdef DEBUG else { LOG("Mutex NOT Grabed"); } #endif ; }; if( m_pPort != NULL ){ if( m_pPort->getConnectionStatus() == CS_DISCONNECTED ){ m_bWorkingMode = TWI_STAGE_WAITING_CONNECTION; if( tCMD!= NULL ){ //reset commands on disconnect m_bCCMD = TWC_NO_COMMAND; if( tCMD->PTR == NULL ) free( tCMD->PTR ); free( tCMD ); tCMD = NULL; }; delete( m_pPort ); m_pPort = NULL; continue; } else { // Status Send procedure if( cStatusTO == 0 ) { cStatusTO = cMilliseconds; } else if( ( cMilliseconds - cStatusTO ) > TWI_STATUS_LOOP_MS ){ m_mStatusProtector.lock(); if( !sendStatus( m_nStatus ) ){ LOG_ERROR("Status Sending failure!"); m_pPort->disconnect(); }; m_mStatusProtector.unlock(); }; }; } else { LOG("(re)Establish Connection"); m_pPort = new clientPort( m_pMasterAddress, m_nMasterPort, true ); if( m_pPort!= NULL ){ setTransport( m_pPort ); m_bWorkingMode = TWI_STAGE_CONNECTED; }; }; }; }; #else //Master bool LRF_TwinConnector::packetHandler( protocolPackage *Package ){ if( Package == NULL ) return false; TWIN_COMMAND cCMD = (TWIN_COMMAND)Package->m_pData[3]; switch( cCMD ) { case TWC_ACK_STATUS:{ uint32_t tStatus; #ifdef DEBUG LOG("Status ACK reseived"); #endif tStatus = ( Package->m_pData[4] << 24 ) | ( Package->m_pData[5] << 16 ) | ( Package->m_pData[6] << 8 ) | Package->m_pData[7]; m_mStatusProtector.lock(); m_nStatus = tStatus; m_mStatusProtector.unlock(); break; }; case TWC_TH_DATA:{ }; }; m_mLastTypeProtector.lock(); m_bLastPackageType = cCMD; m_mLastTypeProtector.unlock(); return true; }; void LRF_TwinConnector::m_fThreadProc( void ){ int ClientSocket = -1; struct sockaddr ClientAddress; socklen_t ClientAddressSize; long long cMilliseconds; long long cStatusTO = 0; long long cDrawTO = 0; m_bThreadStatus = TH_WORKING; while( m_bThreadStatus < TH_ENDED ){ cMilliseconds = getMilliseconds(); // TH Saving procedure if( cDrawTO == 0 ) { cDrawTO = cMilliseconds; } else if ( ( cMilliseconds - cDrawTO ) > TWI_DRAW_LOOP_MS ){ #ifdef DEBUG LOG("Try to Dump TH Images"); #endif if( m_mDrawProtector.try_lock() ) { #ifdef DEBUG LOG("Mutex Grabed"); #endif if( m_bDrawThreadStatus > TH_ARMED ) { pthread_join( m_sDrawThreadHandler, NULL ); }; cDrawTO = cMilliseconds; m_bDrawThreadStatus = TH_ARMED; int RetVal = pthread_create( &m_sDrawThreadHandler, NULL, m_fDrawThreadEntryPoint, ( void * ) this ); if( RetVal == -1 ) { LOG_ERROR("Image Draw Thread Creation Failed."); m_mDrawProtector.unlock(); }; } #ifdef DEBUG else { LOG("Mutex NOT Grabed"); } #endif ; }; // Port exists - SLAVE is connected if( m_pPort != NULL ){ // Check if still connected if( m_pPort->getConnectionStatus() == CS_DISCONNECTED ){ // Handle Disconnection m_bWorkingMode = TWI_STAGE_WAITING_CONNECTION; delete( m_pPort ); m_pPort = NULL; //Reset Flags cStatusTO = 0; continue; }; SLEEP( TWI_SLOW_LOOP_SLEEP ); } else { // (re)Establish Connection ClientAddressSize = (socklen_t) sizeof( struct sockaddr_in ); ClientSocket = accept ( m_nMainSocket, &ClientAddress, &ClientAddressSize ); if ( ClientSocket == -1 ) { switch( errno ){ case EAGAIN:{ SLEEP( TWI_QUICK_LOOP_SLEEP ); continue; }; //case EWOULDBLOCK: me->Log(" The socket is marked non-blocking and no connections are present to be accepted."); break; case EBADF: LOG_ERROR( "The descriptor is invalid." ); break; case ECONNABORTED: LOG_ERROR( "A connection has been aborted."); break; case EINTR: LOG_ERROR( "The system call was interrupted by a signal that was caught before a valid connection arrived."); break; case EINVAL: LOG_ERROR( "Socket is not listening for connections, or addrlen is invalid (e.g., is negative)."); break; case EMFILE: LOG_ERROR( "The per-process limit of open file descriptors has been reached."); break; case ENFILE: LOG_ERROR( "The system limit on the total number of open files has been reached."); break; case ENOTSOCK: LOG_ERROR( "The descriptor references a file, not a socket."); break; case EOPNOTSUPP: LOG_ERROR( "The referenced socket is not of type SOCK_STREAM."); break; case EFAULT: LOG_ERROR( "The addr argument is not in a writable part of the user address space."); break; case ENOBUFS: case ENOMEM: LOG_ERROR( "Not enough free memory. This often means that the memory allocation is limited by the socket buffer limits, not by the system memory."); break; case EPROTO: LOG_ERROR( "Protocol error."); break; case EPERM: LOG_ERROR( "Firewall rules forbid connection."); break; case ENOSR: case ESOCKTNOSUPPORT: case EPROTONOSUPPORT: case ETIMEDOUT: LOG_ERROR( " Unusual error in Kernel (Timeout, No Socket Support in Kernel, Unsupported Protocol)"); break; //case ERESTARTSYS: me->Log(" Unusual error by Kernel"); break; default: LOG_ERROR( " Unhandled error in Kernel"); break; }; m_bThreadStatus = TH_ENDED; } else { char tstr[CQUERY]; inet_ntop( AF_INET, &(((struct sockaddr_in*) &(ClientAddress ))->sin_addr ), tstr, CQUERY ); LOG( "SLAVE LRF Connection Accepted" ); m_pPort = new serverPort( ClientSocket ); }; if( m_pPort!= NULL ){ setTransport( m_pPort ); // Reset Stage m_bWorkingMode = TWI_STAGE_CONNECTED; }; }; }; }; bool LRF_TwinConnector::attachTargetTracker( LRF_TargetTracker *ptr ){ if(ptr == NULL) return false; m_pTracker = ptr; return false; }; bool LRF_TwinConnector::updateSettings( void ){ return true; }; #endif //!PRU_SLAVE bool LRF_TwinConnector::cleanTHData( uint8_t kid ){ char tBuffer[1024]; FILE *FID = NULL; if( kid > 31 ) kid = 31; sprintf( tBuffer, "data/th_data_%d.raw", kid ); if( !fileExist( "data" ) ){ int RetVal = mkdir( "data", STORAGE_DIR_MODE ); if( RetVal < 0 ) { LOG_ERROR( "Error Creating DATA DIR!" ); return false; }; }; FID = fopen( tBuffer, "wb+" ); if( FID == NULL ){ LOG_ERROR( "Error Creating DATA FILE!" ); return false; }; uint32_t ZZ = 0; for( uint32_t i = 0; i < TH_SIZE_NODES; i++ ){ fwrite( &ZZ, 4, 1, FID ); }; fclose( FID ); return true; }; bool LRF_TwinConnector::loadTHData( uint8_t kid, thresholdNode *ptr ){ FILE *FID; char tBuffer[1024]; if( ptr == NULL ) return false; if( kid > 31 ) kid = 31; sprintf( tBuffer, "data/th_data_%d.raw", kid ); FID = fopen( tBuffer, "rb" ); if( FID == NULL ) { LOG_ERROR( "Error Opening DATA FILE!" ); return false; }; for( uint32_t i = 0; i < TH_SIZE_NODES; i++ ){ fread( &ptr[i], TH_NODE_SIZE, 1, FID ); }; fclose( FID ); return true; }; bool LRF_TwinConnector::saveTHData( uint8_t kid, thresholdNode *ptr ){ FILE *FID; char tBuffer[1024]; if( ptr == NULL ) return false; if( kid > 31 ) kid = 31; sprintf( tBuffer, "data/th_data_%d.raw", kid ); FID = fopen( tBuffer, "wb+" ); if( FID == NULL ) { LOG_ERROR( "Error Creating DATA FILE!" ); return false; }; for( uint32_t i = 0; i < TH_SIZE_NODES; i++ ){ fwrite( &ptr[i], TH_NODE_SIZE, 1, FID ); }; fclose( FID ); return true; }; #ifdef TWI_TH_USE_PICTURES bool LRF_TwinConnector::saveTHPicture( thresholdNode *ptr, CSTR fileName, bool monochrome, bool agressive ){ uint8_t *tMemory = NULL; thresholdNode *cNode = NULL; uint8_t *cPixel = NULL; uint8_t cSpace; if( monochrome ) { cSpace = 1; } else { cSpace = 4; }; tMemory = (uint8_t *) malloc( TH_SIZE_NODES * cSpace ); if( tMemory == NULL ){ LOG_ERROR("Image Memory Alloc Eror!"); return false; }; for( int j = 0; j < Q_SCAN_COUNT; j++ ) { for ( int i = 0; i < TH_LINE_NODES; i++ ) { //cNode = ptr+(j*i); //cNode = &ptr[ ( TH_LINE_NODES * j ) + i ]; #ifdef PRU_SLAVE cNode = ptr+makeIds( i, j , false ); cPixel = tMemory+( cSpace * makeIds( i, j , false )); #else cNode = ptr+makeIds( i, j , true ); cPixel = tMemory+( cSpace * makeIds( i, j , false )); //cNode = ptr + ( i * j ); //cPixel = tMemory + ( cSpace * i * j ); #endif if( !agressive ) SLEEP(1); if( monochrome ) { #ifdef CHECK_SUN_BIT if( cNode->values.sbit ) { cPixel[0] = 0; } else { cPixel[0] = (uint8_t)((((float) cNode->values.min ) * 255.f ) / 4096.f ); }; #else cPixel[0] = (uint8_t)((((float) cNode->values.min ) * 255.f ) / 4096.f ); #endif } else { #ifdef CHECK_SUN_BIT if( cNode->values.sbit ) { // Set Red cPixel[0] = 0x00; cPixel[1] = 0xff; cPixel[2] = 0x00; cPixel[3] = 0xff; } else { if( cNode->values.cnt == 0 ) { // Set Blue cPixel[0] = 0x00; cPixel[1] = 0x00; cPixel[2] = 0xff; cPixel[3] = 0xff; } else { uint32_t tColor; float tVal = ((float) cNode->values.min ) / 4096.f; tColor = interpolate( 0x000000ff, 0xffffffff, tVal ); cPixel[0] = ( tColor >> 24 ) & 0xFF; cPixel[1] = ( tColor >> 16 ) & 0xFF; cPixel[2] = ( tColor >> 8 ) & 0xFF; cPixel[3] = tColor & 0xFF; }; }; #else if( cNode->values.cnt == 0 ) { // Set Blue cPixel[0] = 0x00; cPixel[1] = 0x00; cPixel[2] = 0xff; cPixel[3] = 0xff; } else { uint32_t tColor; float tVal = ((float) cNode->values.min ) / 4096.f; tColor = interpolate( 0x000000ff, 0xffffffff, tVal ); cPixel[0] = ( tColor >> 24 ) & 0xFF; cPixel[1] = ( tColor >> 16 ) & 0xFF; cPixel[2] = ( tColor >> 8 ) & 0xFF; cPixel[3] = tColor & 0xFF; }; #endif }; }; }; int RetVal = stbi_write_png( fileName, TH_LINE_NODES, Q_SCAN_COUNT, cSpace, tMemory, TH_LINE_NODES * cSpace ); free( tMemory ); if( RetVal == 0 ) return false; return true; }; #endif //TWI_TH_USE_PICTURES #undef SLOG #undef SLOG_ERROR #undef LOG #undef LOG_ERROR