#include "LRF_TwinConnector.h" #include "LRF_Kernel.h" #include "LRF_TargetTracker.h" #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 #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 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 ); #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(); }; #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:{ sendStatus(); break; }; }; return true; }; void LRF_TwinConnector::m_fThreadProc( void ){ TWIN_CMD_REC * tCMD = NULL; int ClientSocket = -1; struct sockaddr ClientAddress; socklen_t ClientAddressSize; m_bThreadStatus = TH_WORKING; while( m_bThreadStatus < TH_ENDED ){ if( m_bCCMD == TWC_NO_COMMAND && tCMD == NULL ){ // No CMD is EXEC so check new cmds CMD_PROTEC.lock(); if( m_qCMD.size() > 0 ){ tCMD = m_qCMD.front(); m_qCMD.pop(); }; CMD_PROTEC.unlock(); }; 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; }; if( tCMD!= NULL ){ if( m_bCCMD == TWC_NO_COMMAND ){ // CMD not issued yet! switch( tCMD->CMD ){ case TWC_PUSH_TARGET:{ break; }; }; } else { // Waiting CMD exe status switch( m_bCCMD ){ case TWC_SET_THDRAW:{ break; }; }; if( m_bCCMD == TWC_NO_COMMAND && tCMD != NULL ){ // The command is finished - Will fetch next command from queue if( tCMD->PTR == NULL ) free( tCMD->PTR ); free( tCMD ); tCMD = NULL; }; }; SLEEP( 5 ); } else { SLEEP( 100 ); }; } 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 ){ cDrawTO = cMilliseconds; if( m_pEngine!= NULL ) { // Store Local TH Draws thresholdNode *tMem; uint32_t tSize; for( uint8_t i=0; i<16; i++ ) { // just in case if we must end work if( m_bThreadStatus != TH_WORKING ) break; tMem = m_pEngine->getTreshold( tSize, i ); if( tMem!= NULL ) { char tBuffer[256]; sprintf( tBuffer, "data/th_data_%d.png", i ); if( !saveTHPicture( tMem, tBuffer, false )){ LOG_ERROR("TH PNG save failure!"); }; }; }; }; }; // 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; continue; }; if( m_bCCMD == TWC_NO_COMMAND ){ // No Current Request Issued switch( m_bWorkingMode ) { case TWI_STAGE_CONNECTED:{ if( requestSoftwareVersion() ){ m_bCCMD = TWC_ACK_VERSION; }; break; }; case TWI_STAGE_INIT_1:{ if( requestCurrentSettings() ){ m_bCCMD = TWC_ACK_CONFIG; }; break; }; case TWI_STAGE_INIT_2:{ if( requestShadow() ){ m_bCCMD = TWC_ACK_SHADOW; }; break; }; case TWI_STAGE_MAIN_LOOP:{ if( ( cMilliseconds - cStatusTO ) > TWI_STATUS_LOOP_MS ) { cStatusTO = cMilliseconds; requestStatus(); m_bCCMD = TWC_ACK_STATUS; LOG("Req Status"); } else { SLEEP( TWI_SLOW_LOOP_SLEEP ); } break; }; }; } else { // Waiting CMD ACK status if( getLastPackageType() == m_bCCMD ) { switch( m_bCCMD ){ case TWC_ACK_VERSION:{ m_bWorkingMode = TWI_STAGE_INIT_1; break; }; case TWC_ACK_CONFIG:{ m_bWorkingMode = TWI_STAGE_INIT_2; break; }; case TWC_ACK_SHADOW:{ m_bWorkingMode = TWI_STAGE_MAIN_LOOP; break; }; case TWC_ACK_STATUS:{ #ifdef DEBUG LOG("Registered Ack Status"); #endif //uint32_t nStatus = getStatus(); if( ( m_nStatus & TWI_STATUS_TARGET_MASK ) > 0 ){ #ifdef DEBUG LOG("Have new Targets!"); #endif //m_pProtocol->setTData( m_pTargets ); requestTargets(); m_bCCMD = TWC_GET_TARGETS; continue; }; break; }; case TWC_GET_TARGETS:{ if( getLastPackageType() == TWC_TARGETS_DATA ){ m_bCCMD = TWC_NO_COMMAND; #ifdef DEBUG LOG("Registered Ack Targets"); #endif if( m_pTracker != NULL ) { uint8_t nCNT = (( m_nStatus & TWI_STATUS_TARGET_MASK ) >> 8 ); for( uint8_t index = 0; index < nCNT; index++ ){ m_pTracker->validateTarget( &m_pTargets[index], false ); }; }; }; break; }; }; m_bCCMD = TWC_NO_COMMAND; }; SLEEP( TWI_QUICK_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(10); 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; }; bool LRF_TwinConnector::saveTHPicture( thresholdNode *ptr, CSTR fileName, bool monochrome ){ 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 ){ return false; }; #ifndef PRU_SLAVE 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 ); #else for( int j = (Q_SCAN_COUNT-1); j < -1; j++ ) { for ( int i = 0; i < TH_LINE_NODES; i++ ) { cNode = ptr+( TH_LINE_NODES * j + i ); #endif cPixel = tMemory+(cSpace*i*j); 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; }; #undef LOG #undef LOG_ERROR