//---------------------------------------------------------------------------- // Dr.Frucht Systems Ltd. // Copyright © 2000-2022. All Rights Reserved. // Version 1.0 11/19/2022 // Last modification: 11/19/2022 // PROJECT: // SUBSYSTEM: // FILE: mojoKernel.cpp // AUTHOR: gagua // OVERVIEW // ~~~~~~~~ // LRF_Kernel.cpp //---------------------------------------------------------------------------- // #include "mojoKernel.h" static int getLocalReportPeriod(void); #include "../common/kernelEventFilterAPF.h" #include "../common/kernelEventFilterBubble.h" #include "../common/kernelEventFilterTrain.h" #include "../common/kernelModuleEmbedVideo.h" #include "../data/json/json_tool.h" #include #include #include #include #include #include #ifdef USE_MYSQL #include "../common/MySQL_dataBinder.h" #else #include "../common/SQLite_dataBinder.h" #endif #define LOG(X) kernelPrototype::m_pLog->Log("KRNL", 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); \ kernelPrototype::m_pLog->Log("KRNL", this, _LOG_ERROR, _tBfrErrMSG234); \ } #else #define LOG_ERROR(X) kernelPrototype::m_pLog->Log("KRNL", this, _LOG_ERROR, X); #endif mojoKernel * mojoKernel::_instance = NULL; mojoKernel * mojoKernel::getInstance(config_setting_t * ptr) { if (_instance == NULL) { _instance = new mojoKernel(ptr); }; return _instance; } mojoKernel::mojoKernel(config_setting_t * ptr) : kernelPrototype(ptr) { m_pEventHeap = basicEventHeap::getInstance(); memset(&m_sSysInfo, 0, sizeof(DBC_SYS_LOAD_INFO)); m_pShadow = NULL; m_pSystemAnchor = NULL; m_bSessionStarted = false; m_bSessionMustPreserve = false; m_bFirstSession = true; m_bWorkWithRemoteServer = false; m_bKeepLocalReport = true; m_bMediaMode = 0; m_bApplicationFirstRun = false; m_bForceCloseSessionOnEndOfTheDay = false; m_mDateOfToday = getLocalDay(); m_nReportPeriod = getLocalReportPeriod(); m_bReportSwitchPending = false; m_tReportSwitchDetected = 0; m_nSessionPeriod = -1; m_pRPC = NULL; #ifndef LRF_PROXY_ONLY m_pMediaHelper = NULL; #endif #ifdef EMBED_AUTORESET m_bEnableAutoReset = false; m_nSessionCounter = 0; m_nAutoResetTime = 0; #endif #ifdef PEREODIC_SENSORS_RESET m_bEnablePereodicReset = false; m_nPereodicResetTime = 0; m_nPereodicResetCounter = 0; #endif // setWM( WM_NONE ); } mojoKernel::~mojoKernel() { WaitFinish(true); stopSession(false); #ifndef LRF_PROXY_ONLY if ( m_pMediaHelper ) { delete( m_pMediaHelper ); } #endif #ifdef DEBUG LOG(" Deleting Node Factory..."); #endif if (m_pNodeFactory != NULL) { delete(m_pNodeFactory); } #ifdef DEBUG LOG(" Deleting Module Factory..."); #endif if (m_pModuleFactory != NULL) { delete(m_pModuleFactory); } #ifdef DEBUG LOG(" Deleting Target Filters..."); #endif unloadFilters(); if (EXIT_CODE_KERNEL_CLEAR == getExitCause()) { #ifdef DEBUG LOG("Unregister Server"); #endif m_pDBC->unregisterServer(); #ifdef DEBUG // LOG("Close DataBase Connection..."); #endif // if( m_pDBC != NULL ) delete( m_pDBC );//Deleting in Backend // m_pDBC = NULL; } else { if (EXIT_CODE_DETECT_HARDWARE == getExitCause()) { #ifdef DEBUG LOG("HW PNP Detection Requested..."); #endif // m_pDBC->updateNodePushedCMD( tCMD->id, 30 ); m_pHardwareManager->enumerateHardware(); // m_pDBC->updateNodePushedCMD( tCMD->id, 60 ); }; #ifdef DEBUG // LOG("Close DataBase Connection..."); #endif // if( m_pDBC != NULL ) delete( m_pDBC ); // m_pDBC = NULL; }; delete(m_pHardwareManager); // while(1){ // char tB[200]; // sprintf( tB, "[%d] Seconds Till System Restart", timeout ); // LOG( "BopBop!" ); // SLEEP(1000); // }; if (m_pRPC) { #ifdef DEBUG LOG("Deleting Remote Server Connection..."); #endif delete(m_pRPC); #ifdef DEBUG LOG("Remote Server Connection Destroyed!"); #endif } #ifdef LINUX_KERNEL_WATCHDOG LOG("Disable WD!"); if (m_iWatchdogFd > -1) { char tB[64]; sprintf(tB, "-1\n"); // ToDo: Make Error Handling here! write(m_iWatchdogFd, &tB, strlen(tB)); }; LOG("WatchDog turned Off!"); #endif _instance = NULL; } bool mojoKernel::create() { m_bSessionStarted = false; m_bSessionMustPreserve = false; m_bFirstSession = true; if (m_pSettings != NULL) { config_setting_t * pSetting; int tVal; const char * tBuf; char tBuffer[128]; LOG("Getting Settings ..."); if (! config_setting_lookup_string(m_pSettings, MOJO_KERNEL_TAG_SERVER_IDENTITY, &tBuf)) { char * tVar; char * tTS; tTS = getTStr(NULL); tVar = MD5String(tTS); free(tTS); sprintf(m_sIdentity, tVar); pSetting = config_setting_add(m_pSettings, MOJO_KERNEL_TAG_SERVER_IDENTITY, CONFIG_TYPE_STRING); config_setting_set_string(pSetting, tVar); free(tVar); basicSettingsProvider::getInstance()->compromise(); LOG("Server Identity not defined - generating new!"); } else { sprintf(m_sIdentity, tBuf); sprintf(tBuffer, "Server Identity Read From Settings: %s", tBuf); LOG(tBuffer); }; if (! config_setting_lookup_int(m_pSettings, MOJO_KERNEL_TAG_SITE_ID, &tVal)) { tVal = m_nInstanceID = 1; pSetting = config_setting_add(m_pSettings, MOJO_KERNEL_TAG_SITE_ID, CONFIG_TYPE_INT); config_setting_set_int(pSetting, tVal); basicSettingsProvider::getInstance()->compromise(); LOG("Site ID not defined - using [1] as number!"); } else { m_nInstanceID = tVal; sprintf(tBuffer, "App Instance ID Read From Settings: %d", m_nInstanceID); LOG(tBuffer); }; #ifdef EMBED_AUTORESET if (! config_setting_lookup_int(m_pSettings, "AUTORESET", &tVal)) { m_bEnableAutoReset = false; tVal = m_nAutoResetTime = 0; pSetting = config_setting_add(m_pSettings, "AUTORESET", CONFIG_TYPE_INT); config_setting_set_int(pSetting, tVal); basicSettingsProvider::getInstance()->compromise(); LOG("Autoreset not defined - Set Disabled!"); } else { m_nAutoResetTime = tVal; m_bEnableAutoReset = (m_nAutoResetTime > 0); sprintf(tBuffer, "App Autoreset Read From Settings: %d", m_nAutoResetTime); LOG(tBuffer); }; #endif #ifdef PEREODIC_SENSORS_RESET if (! config_setting_lookup_int(m_pSettings, "PEREODICRESET", &tVal)) { m_bEnablePereodicReset = false; tVal = m_nPereodicResetTime = 0; pSetting = config_setting_add(m_pSettings, "PEREODICRESET", CONFIG_TYPE_INT); config_setting_set_int(pSetting, tVal); basicSettingsProvider::getInstance()->compromise(); LOG("Pereodic Sensor Reset not defined - Set Disabled!"); } else { m_nPereodicResetTime = tVal; m_bEnablePereodicReset = (m_nPereodicResetTime > 0); sprintf(tBuffer, "Pereodic Sensor Reset Read From Settings: %d", m_nPereodicResetTime); LOG(tBuffer); }; #endif } else { LOG_ERROR("Failed Read Config Settings!"); return false; }; basicSettingsProvider::getInstance()->validate(); LOG("Register Server ... "); m_pDBC->registerServer(m_nInstanceID, m_sIdentity, getpid(), &m_nServerID, &m_nServerNodeID); char tBuffer[128]; sprintf(tBuffer, "Server Registered as [%d] nodeID[%d]", m_nServerID, m_nServerNodeID); LOG(tBuffer); DBC_SITE_DATA * tSiteData = m_pDBC->getSiteData(1); if (tSiteData) { C3D_WGS84_LOC t; t.lat = tSiteData->lat; t.lon = tSiteData->lon; t.alt = tSiteData->alt; m_pSystemAnchor = systemAnchor::getInstance( &t, tSiteData->local_binding ); memcpy(&m_sSiteData, tSiteData, sizeof(DBC_SITE_DATA)); free(tSiteData); } else { LOG_ERROR("Error Loading Site DATA!"); C3D_WGS84_LOC t; t.lat = 0; t.lon = 0; t.alt = 0; memset(&m_sSiteData, 0, sizeof(DBC_SITE_DATA)); m_pSystemAnchor = systemAnchor::getInstance( &t, true ); }; m_bKeepLocalReport = ! m_sSiteData.skip_local_report; m_bDebugMode = m_pDBC->getAppDebugMode(); if (m_bDebugMode) { m_bKeepLocalReport = true; // Forced in case of debug mode } /// m_bWorkWithRemoteServer = m_sSiteData.use_remote_server; -> /// since Connection is delayed - must be not set at beginning // Check date/Time if correct! // Just in case that we have local reports if (m_bKeepLocalReport) { #ifdef DEBUG LOG("Working With Local Reports"); #endif // On some systems the System Date may be in past cause last session was interrupted by power loose uint32_t tTS = m_pDBC->getLastEventTS(); if (tTS) { // Have last TS struct timespec tS;// = {0}; will filed by gettime function if (clock_gettime(CLOCK_REALTIME, &tS) == 0) { // time_t cTS = time(NULL); if (tTS > tS.tv_sec) { // System Time is in the Past LOG("Correcting System Time!"); tS.tv_sec = tTS; tS.tv_nsec = tTS * 1000000; if (clock_settime(CLOCK_REALTIME, &tS) != 0) { LOG_ERROR("Time Correction Failed!"); } }; }; #ifdef DEBUG } else { LOG("No Last TS fetched from DB!"); #endif }; m_bSessionStarted = m_pDBC->getEventSessionStatus();//m_nServerNodeID); stopSession(false); }; m_pHardwareManager = hardwareManager::getInstance(); loadFilters(); m_pModuleFactory = kernelModuleFactory::getInstance(m_nInstanceID); if (! m_pModuleFactory) { LOG_ERROR("Module Factory Failure!"); return false; }; m_pModuleFactory->loadModules(); // Reald Media Mode ( Video/Pictures ) #ifndef LRF_PROXY_ONLY m_pMediaHelper = new kernelHelperMediaMTX(); if ( m_pMediaHelper ) { m_pMediaHelper->create(); }; kernelModuleEmbedVideo * tMO = (kernelModuleEmbedVideo *) m_pModuleFactory->getModule(KERNEL_MODULE_EMBED_VIDEO); if (tMO) { m_bMediaMode = tMO->getMediaMode(); } else { LOG_ERROR("No Embed Video Processing Module!"); }; #else LOG("MOJO is DATA PROXY Processing Module!"); m_bMediaMode = 0; #endif m_pNodeFactory = deviceNodeFactory::getInstance(); if (! m_pNodeFactory) { LOG_ERROR("Node Factory Failure!"); return false; }; if ((m_bApplicationFirstRun = m_pDBC->isDatabaseNew())) { LOG("DATABASE IS NEW - Will Detect Hardware!"); } else { LOG("DATABASE IS OLD - Will SKIP Detection of Hardware!"); } // Must Be moved elsewhere To be connected after all Nodes are Loadded ?? at Node's Validation ?? /* if ( m_bWorkWithRemoteServer ) { #ifdef DEBUG LOG("Working With Remote Server"); #endif if ( m_pRPC = new mojoRemoteClient( this ) ) { if( m_bWorkWithRemoteServer = m_pRPC->create() ){ } else LOG_ERROR("Cannot Connect to Remote Server!"); } else m_bWorkWithRemoteServer = false; }; */ return init(); } #include "../common/deviceNode2D.h" void mojoKernel::releaseExplicitChannel( uint32_t node_id, uint32_t channel_id ){ if ( m_pNodeFactory ) { deviceNode ** tA = NULL; uint32_t tCNT = m_pNodeFactory->fetchNodes(ARGUS_ALS_SENSOR, tA ); for ( uint32_t i = 0; i < tCNT; i++ ) { if ( tA[i]->getNodeID() != node_id ) ( (device2DSensor *)tA[i] )->setChannelReady( channel_id ); }; if (tCNT){ free(tA); tA = NULL; }; tCNT = m_pNodeFactory->fetchNodes(ARGUS_LFS_SENSOR, tA ); for ( uint32_t i = 0; i < tCNT; i++ ) { if ( tA[i]->getNodeID() != node_id ) ( (device2DSensor *)tA[i] )->setChannelReady( channel_id ); }; if (tCNT){ free(tA); tA = NULL; }; tCNT = m_pNodeFactory->fetchNodes(ARGUS_PLS_200_SENSOR, tA ); for ( uint32_t i = 0; i < tCNT; i++ ) { if ( tA[i]->getNodeID() != node_id ) ( (device2DSensor *)tA[i] )->setChannelReady( channel_id ); }; if (tCNT){ free(tA); tA = NULL; }; tCNT = m_pNodeFactory->fetchNodes(ARGUS_PLS_360_SENSOR, tA ); for ( uint32_t i = 0; i < tCNT; i++ ) { if ( tA[i]->getNodeID() != node_id ) ( (device2DSensor *)tA[i] )->setChannelReady( channel_id ); }; if (tCNT){ free(tA); tA = NULL; }; }; } void mojoKernel::requestExplicitChannel( uint32_t node_id, uint32_t channel_id, uint8_t seconds_to ){ if ( m_pNodeFactory ) { deviceNode ** tA = NULL; uint32_t tCNT = m_pNodeFactory->fetchNodes(ARGUS_ALS_SENSOR, tA ); for ( uint32_t i = 0; i < tCNT; i++ ) { if ( tA[i]->getNodeID() != node_id ) ( (device2DSensor *)tA[i] )->setChannelBusy( channel_id, seconds_to ); }; if (tCNT){ free(tA); tA = NULL; }; tCNT = m_pNodeFactory->fetchNodes(ARGUS_LFS_SENSOR, tA ); for ( uint32_t i = 0; i < tCNT; i++ ) { if ( tA[i]->getNodeID() != node_id ) ( (device2DSensor *)tA[i] )->setChannelBusy( channel_id, seconds_to ); }; if (tCNT){ free(tA); tA = NULL; }; tCNT = m_pNodeFactory->fetchNodes(ARGUS_PLS_200_SENSOR, tA ); for ( uint32_t i = 0; i < tCNT; i++ ) { if ( tA[i]->getNodeID() != node_id ) ( (device2DSensor *)tA[i] )->setChannelBusy( channel_id, seconds_to ); }; if (tCNT){ free(tA); tA = NULL; }; tCNT = m_pNodeFactory->fetchNodes(ARGUS_PLS_360_SENSOR, tA ); for ( uint32_t i = 0; i < tCNT; i++ ) { if ( tA[i]->getNodeID() != node_id ) ( (device2DSensor *)tA[i] )->setChannelBusy( channel_id, seconds_to ); }; if (tCNT){ free(tA); tA = NULL; }; }; } void mojoKernel::startSession() { m_mSessionProtector.lock(); m_nNoAlarmCounter = 0; if (! m_bSessionStarted) { if (! m_bFirstSession) { if (! m_bSessionMustPreserve) { m_pDBC->dropSession(); } m_bSessionMustPreserve = false; } else { m_bFirstSession = false; } uint64_t TS_64 = getMilliseconds() - 20; // -20 msec before uint32_t ts_s = TS_64 / 1000; uint16_t ts_ms = TS_64 % 1000; EVENT_CONTAINER * bEVT = createBasicEvent(m_nServerNodeID, EVT_CLASS_SYSTEM, EVT_LRF_START_SESSION, NULL, NULL, NULL, ts_s, ts_ms); if (bEVT) { m_pEventHeap->broadcast(bEVT); }; m_bSessionStarted = true; m_nSessionPeriod = getLocalReportPeriod(); #ifdef EMBED_AUTORESET m_nSessionCounter = 0; #endif }; m_mSessionProtector.unlock(); } void mojoKernel::stopSession(bool forced) { m_mSessionProtector.lock(); if (m_bSessionStarted) { uint64_t TS_64 = getMilliseconds() + 20; // +20 msec after uint32_t ts_s = TS_64 / 1000; uint16_t ts_ms = TS_64 % 1000; EVENT_CONTAINER * bEVT = createBasicEvent(m_nServerNodeID, EVT_CLASS_SYSTEM, forced ? EVT_LRF_END_SESSION_MA : EVT_LRF_END_SESSION_TO, NULL, NULL, NULL, ts_s, ts_ms); if (bEVT) { m_pEventHeap->broadcast(bEVT); }; m_bSessionStarted = false; #ifdef EMBED_AUTORESET m_nSessionCounter = 0; #endif }; m_mSessionProtector.unlock(); } void mojoKernel::validateSession(){ m_mSessionProtector.lock(); if( m_bSessionStarted ){ if( m_nNoAlarmCounter < NOTARGET_SESSION_CLOSE ){ m_nNoAlarmCounter++; } else { m_mSessionProtector.unlock(); stopSession( m_bForceCloseSessionOnEndOfTheDay ); m_mSessionProtector.lock(); }; #ifdef EMBED_AUTORESET if (m_bEnableAutoReset) { if (m_nSessionCounter < m_nAutoResetTime) { m_nSessionCounter++; } else { m_nSessionCounter = 0; // Reset All Sensors DBC_INT_LIST * tL = m_pDBC->listNodes(false); if (tL){ for (DBC_INT_LIST::iterator idx = tL->begin(); idx < tL->end(); idx++){ m_pDBC->pushMemCMD(*idx, 1, "'A'"); }; delete(tL); }; m_nNoAlarmCounter = NOTARGET_SESSION_CLOSE; // Session will be closed on next validation }; }; #endif }; m_mSessionProtector.unlock(); #ifdef PEREODIC_SENSORS_RESET if ( m_bEnablePereodicReset ) { m_nPereodicResetCounter++; if ( m_nPereodicResetCounter > m_nPereodicResetTime ) { m_nPereodicResetCounter = 0; // Reset All Sensors #ifdef DEBUG LOG("Pereodic Reset to All Sensors"); #endif DBC_INT_LIST * tL = m_pDBC->listNodes(false); if (tL){ for (DBC_INT_LIST::iterator idx = tL->begin(); idx < tL->end(); idx++){ m_pDBC->pushMemCMD(*idx, 1, "'A'"); }; delete(tL); }; }; }; #endif } #ifdef __MOJO_REMOTE_CLIENT_HEADER__ bool mojoKernel::getTrainPresence() { bool RetValue = false; if (m_vTargetFilters.size()) { for (vectorKernelEventFilters::iterator idx = m_vTargetFilters.begin(); idx < m_vTargetFilters.end(); idx++) { if ((*idx)->getType() == TF_LA_METRO_TRAIN_FILTER) { kernelEventFilterTrain * tFT = (kernelEventFilterTrain *) (*idx); RetValue = tFT->getTrainStatus(); break; }; }; }; return RetValue; } bool mojoKernel::fillMojoInfo(ARGUS_DATA_MOJO_INFO * ptr) { if (ptr == NULL) { return false; } memset(ptr, 0, sizeof(ARGUS_DATA_MOJO_INFO)); ptr->MOJO_WORK_MODE = (m_bKeepLocalReport ? 4 : 0) | (m_bMediaMode ? 2 : 0) | (m_bDebugMode ? 1 : 0); if (m_vTargetFilters.size()) { for (vectorKernelEventFilters::iterator idx = m_vTargetFilters.begin(); idx < m_vTargetFilters.end(); idx++) { #ifdef DEBUG_EXTRA LOG("check Filter"); #endif if ((*idx)->getType() == TF_LA_METRO_TRAIN_FILTER) { #ifdef DEBUG_EXTRA LOG("T Filter Found!"); #endif kernelEventFilterTrain * tFT = (kernelEventFilterTrain *) (*idx); ptr->UPPER_ID = tFT->getUpperId(); ptr->BOTTOM_ID = tFT->getBottomId(); ptr->MOJO_WORK_MODE |= (tFT->getMode() << 3); break; }; }; }; #ifndef LRF_PROXY_ONLY if ( m_pMediaHelper ) { m_pMediaHelper->validateService(); }; #endif deviceNode ** tA = NULL; uint32_t tCNT = m_pNodeFactory->fetchNodes(ARGUS_ANALOG_STATIC_CAMERA, tA); if (tCNT) { // deviceNodeCamera *tCAM = (deviceNodeCamera*) tA[0]; // ptr->CAM_ID = tCAM->getNodeID(); // ptr->CAM_STREAM_ID = tCAM->getCamStream(); // ptr->CAM_ID = tA[0]->getDeviceID(); ptr->CAM_ID = tA[0]->getNodeID(); ptr->CAM_STREAM_ID = tA[0]->getDeviceParam(); } else { LOG("FIMO Cannot Get ARGUS_ANALOG_STATIC_CAMERA Camera!"); tCNT = m_pNodeFactory->fetchNodes(ARGUS_ANALOG_PTZ_CAMERA, tA); if (tCNT) { // deviceNodeCamera *tCAM = (deviceNodeCamera*) tA[0]; // ptr->CAM_ID = tCAM->getNodeID(); // ptr->CAM_STREAM_ID = tCAM->getCamStream(); // ptr->CAM_ID = tA[0]->getDeviceID(); ptr->CAM_ID = tA[0]->getNodeID(); ptr->CAM_STREAM_ID = tA[0]->getDeviceParam(); } else { LOG("FIMO Cannot Get ARGUS_ANALOG_PTZ_CAMERA Camera!"); tCNT = m_pNodeFactory->fetchNodes(ARGUS_IP_STATIC_CAMERA, tA); if (tCNT) { // deviceNodeCamera *tCAM = (deviceNodeCamera*) tA[0]; // ptr->CAM_ID = tCAM->getNodeID(); // ptr->CAM_STREAM_ID = tCAM->getCamStream(); // ptr->CAM_ID = tA[0]->getDeviceID(); ptr->CAM_ID = tA[0]->getNodeID(); ptr->CAM_STREAM_ID = tA[0]->getDeviceParam(); } else { LOG("FIMO Cannot Get ARGUS_IP_STATIC_CAMERA Camera!"); tCNT = m_pNodeFactory->fetchNodes(ARGUS_IP_PTZ_CAMERA, tA); if (tCNT) { // deviceNodeCamera *tCAM = (deviceNodeCamera*) tA[0]; // ptr->CAM_ID = tCAM->getNodeID(); // ptr->CAM_STREAM_ID = tCAM->getCamStream(); // ptr->CAM_ID = tA[0]->getDeviceID(); ptr->CAM_ID = tA[0]->getNodeID(); ptr->CAM_STREAM_ID = tA[0]->getDeviceParam(); } else { LOG("FIMO Cannot Get ARGUS_IP_PTZ_CAMERA Camera!"); tCNT = m_pNodeFactory->fetchNodes(ARGUS_IP_PRESET_CAMERA, tA); if (tCNT) { // deviceNodeCamera *tCAM = (deviceNodeCamera*) tA[0]; // ptr->CAM_ID = tCAM->getNodeID(); // ptr->CAM_STREAM_ID = tCAM->getCamStream(); // ptr->CAM_ID = tA[0]->getDeviceID(); ptr->CAM_ID = tA[0]->getNodeID(); ptr->CAM_STREAM_ID = tA[0]->getDeviceParam(); } else { LOG("FIMO Cannot Get ARGUS_IP_PRESET_CAMERA Camera!"); tCNT = m_pNodeFactory->fetchNodes(ARGUS_ANALOG_PRESET_CAMERA, tA); if (tCNT) { // deviceNodeCamera *tCAM = (deviceNodeCamera*) tA[0]; // ptr->CAM_ID = tCAM->getNodeID(); // ptr->CAM_STREAM_ID = tCAM->getCamStream(); // ptr->CAM_ID = tA[0]->getDeviceID(); ptr->CAM_ID = tA[0]->getNodeID(); ptr->CAM_STREAM_ID = tA[0]->getDeviceParam(); } else { LOG("FIMO Cannot Get ARGUS_ANALOG_PRESET_CAMERA Camera!"); LOG("No Camera Defined In the system!"); }; }; }; }; }; }; if (tCNT) { free(tA); tA = NULL; }; ptr->CPU_COUNT = m_sSysInfo.CPU_CORES; ptr->TOT_DISK = m_sSysInfo.T_DISK; ptr->TOT_MEMO = m_sSysInfo.T_MEM; strncpy(ptr->TLS_VERSION, _BUILD_STRING_, 64); ptr->TLS_VERSION[63] = (char) 0; strncpy(ptr->LLS_VERSION, m_pHardwareManager->getSysInfo()->OS_INFO, 64); ptr->LLS_VERSION[63] = (char) 0; LOG("FIMO Overall info"); return true; } #endif void mojoKernel::getSystemUtilization(DBC_SYS_LOAD_INFO * ptr) { if (ptr == NULL) { return; } m_mSysInfoProtector.lock(); memcpy(ptr, &m_sSysInfo, sizeof(DBC_SYS_LOAD_INFO)); m_mSysInfoProtector.unlock(); } void mojoKernel::m_fThreadProc(void){ time_t tTimeTSeconds = 0; m_bThreadStatus = TH_WORKING; pthread_setname_np( pthread_self(), "Kernel" ); while (m_bThreadStatus < TH_ENDED){ m_tTimeTSeconds = time(NULL); // Each Second if (m_tTimeTSeconds != tTimeTSeconds){ tTimeTSeconds = m_tTimeTSeconds; if (m_bApplicationFirstRun){ if (m_pHardwareManager != NULL){ LOG_ERROR("Restart and Detect HardWare!"); // Must be shutdowned all service that uses hardware prior to detection! m_bThreadStatus = TH_ENDED; setExitCause(EXIT_CODE_DETECT_HARDWARE); // Go -> Detect Hardware in BACKEND continue; }; }; #ifdef LINUX_KERNEL_WATCHDOG if (m_iWatchdogFd > -1){ char tB[64]; sprintf(tB, "4000\n"); // ToDo: Make Error Handling here! write(m_iWatchdogFd, &tB, strlen(tB)); }; #endif m_bDebugMode = m_pDBC->getAppDebugMode(); validateFilters(); validateSession(); validateReports(); //?? if (! m_pHardwareManager->validate()){ LOG("Reload Mojo Node Due to Memory Consumption!"); m_bThreadStatus = TH_ENDED; setExitCause(EXIT_CODE_KERNEL_CLEAR); continue; }; m_mSysInfoProtector.lock(); m_pHardwareManager->updateSysInfo(&m_sSysInfo); m_mSysInfoProtector.unlock(); #ifndef LRF_PROXY_ONLY if ( m_pMediaHelper ) { m_pMediaHelper->validateService(); }; #endif if (m_sSiteData.use_remote_server){ if (m_pRPC){ m_pRPC->validate(); m_bWorkWithRemoteServer = (m_pRPC->getConnectionStatus() == CS_CONNECTED); } else { // Checking if Nodes are Loadded if (m_pNodeFactory->nodesAreLoaded()) { #ifdef DEBUG LOG("Initial Connect to Remote Server"); #endif if ((m_pRPC = new mojoRemoteClient(this))) { if (! (m_bWorkWithRemoteServer = m_pRPC->create())) { LOG_ERROR("Cannot Connect to Remote Server!"); } } else { m_bWorkWithRemoteServer = false; } }; }; }; DBC_PUSHED_CMD * tCMD = m_pDBC->getNodePushedCMD(m_nServerNodeID); // Kernel if (tCMD != NULL) { m_pDBC->updateNodePushedCMD(tCMD->id, DBC_CMD_STARTED); switch (tCMD->CMD) { case CMD_KRNL_RELOAD:{ LOG("Reload Mojo Node!"); m_bThreadStatus = TH_ENDED; setExitCause(EXIT_CODE_RELOAD_SERVICES); break; }; case CMD_KRNL_RESTART:{ LOG("Restart Mojo Node!"); m_bThreadStatus = TH_ENDED; setExitCause(EXIT_CODE_KERNEL_CLEAR); break; }; case CMD_KRNL_FACTORY_RESET:{ LOG("Restart Mojo -> Factory Reset!"); m_bThreadStatus = TH_ENDED; setExitCause(EXIT_CODE_FACTORY_RESET); break; }; case CMD_NODES_RELOAD:{ if (m_pNodeFactory != NULL){ m_pNodeFactory->reloadNodes(); }; break; }; case CMD_NODE_RELOAD:{ uint32_t tNodeID = atoi(tCMD->PARAM); if (m_pNodeFactory != NULL){ m_pNodeFactory->reloadNode(tNodeID); }; break; }; case CMD_KRNL_PNP:{ if (m_pHardwareManager != NULL){ LOG_ERROR("Restart and Detect HardWare!"); // Must be shutdowned all service that uses hardware prior to detection! m_bThreadStatus = TH_ENDED; setExitCause(EXIT_CODE_DETECT_HARDWARE); // Go -> Detect Hardware in BACKEND }; break; }; case CMD_KRNL_UPDATE_IDENT:{ LOG("Restart Mojo -> Update Ident!"); sprintf(m_sIdentity, tCMD->PARAM); config_setting_remove(m_pSettings, MOJO_KERNEL_TAG_SERVER_IDENTITY); config_setting_t * pSetting = config_setting_add(m_pSettings, MOJO_KERNEL_TAG_SERVER_IDENTITY, CONFIG_TYPE_STRING); config_setting_set_string(pSetting, tCMD->PARAM); basicSettingsProvider::getInstance()->compromise(); basicSettingsProvider::getInstance()->validate(); m_pDBC->updateServerIdentity(m_nServerID, m_sIdentity); m_bThreadStatus = TH_ENDED; setExitCause(EXIT_CODE_KERNEL_CLEAR); break; }; case CMD_KRNL_REPLACE_DATABASE:{ LOG("Restart Mojo -> Replace Database!"); CSTR tNAME = m_pDBC->getDataParam(0); CSTR tUSER = m_pDBC->getDataParam(1); CSTR tGROUP = m_pDBC->getDataParam(2); if (tNAME){ char tB[512]; sprintf(tB, "./data/%s.db", tCMD->PARAM); if (fileExist(tB)){ LOG("Restart Mojo -> Close Database!"); // Closing Database delete(m_pDBC); m_pDBC = NULL; LOG("Restart Mojo -> Delete Database!"); // unlink( tNAME ); LOG("Restart Mojo -> Copy Database!"); fileCopy(tB, tNAME); LOG("Restart Mojo -> Chown Database!"); ch_chown(tNAME, tUSER, tGROUP); LOG("Restart Mojo -> Delete Old Database!"); unlink(tB); m_bThreadStatus = TH_ENDED; LOG("Restart Mojo -> Exit!"); setExitCause(EXIT_CODE_NO_DATABASE); // EXIT_CODE_RELOAD_SERVICES ); m_bThreadStatus = TH_ENDED; } else { LOG_ERROR("New Database Does not Exists!"); }; // free( tNAME ); // free( tUSER ); // free( tGROUP ); }; break; }; case CMD_KRNL_SYNC_TIME:{ uint32_t uts = atoi(tCMD->PARAM); if (uts){ #if (__GLIBC__ < 3) && (__GLIBC_MINOR__ < 31) time_t ts = (time_t) uts; if (stime(&ts) == 0){ // Restert Server; m_bThreadStatus = TH_ENDED; setExitCause(EXIT_CODE_KERNEL_CLEAR); }; #else timespec ts; ts.tv_sec = (time_t) uts; ts.tv_nsec = 0; if (clock_settime(CLOCK_REALTIME, &ts) == 0){ // Restert Server; m_bThreadStatus = TH_ENDED; setExitCause(EXIT_CODE_KERNEL_CLEAR); }; #endif }; break; }; case CMD_KRNL_SYSTEM_TASK:{ break; }; case NODE_FORCE_FINISH_ALARM:{ stopSession(); break; }; case CMD_FORCE_FREEZE_BUBBLES:{ LOG("Freeze Bubbles NCQ"); EVENT_CONTAINER * tTT = createBasicEvent(m_nServerNodeID, EVT_CLASS_SYSTEM, EVT_FLT_BUBBLES_BLOCK); if (tTT){ m_pEventHeap->broadcast(tTT); }; break; }; case CMD_FORCE_POP_BUBBLE:{ LOG("POP Bubbles NCQ"); EVENT_CONTAINER * tTT = createBasicEvent(m_nServerNodeID, EVT_CLASS_SYSTEM, EVT_FLT_BUBBLES_DEL_FB); if (tTT){ m_pEventHeap->broadcast(tTT); }; break; }; case CMD_FORCE_RELOAD_BUBBLES:{ LOG("Reload Bubbles NCQ"); EVENT_CONTAINER * tTT = createBasicEvent(m_nServerNodeID, EVT_CLASS_SYSTEM, EVT_FLT_BUBBLES_RELOAD); if (tTT){ m_pEventHeap->broadcast(tTT); }; break; }; case CMD_FORCE_SENORS_RESET:{ LOG("Reset All Sensors NCQ"); if ( m_pNodeFactory ) { deviceNode ** tA = NULL; uint32_t tCNT = m_pNodeFactory->fetchNodes(ARGUS_ALS_SENSOR, tA ); for ( uint32_t i = 0; i < tCNT; i++ ) ( (device2DSensor *)tA[i] )->reset(); if (tCNT){ free(tA); tA = NULL; }; tCNT = m_pNodeFactory->fetchNodes(ARGUS_LFS_SENSOR, tA ); for ( uint32_t i = 0; i < tCNT; i++ ) ( (device2DSensor *)tA[i] )->reset(); if (tCNT){ free(tA); tA = NULL; }; tCNT = m_pNodeFactory->fetchNodes(ARGUS_PLS_200_SENSOR, tA ); for ( uint32_t i = 0; i < tCNT; i++ ) ( (device2DSensor *)tA[i] )->reset(); if (tCNT){ free(tA); tA = NULL; }; tCNT = m_pNodeFactory->fetchNodes(ARGUS_PLS_360_SENSOR, tA ); for ( uint32_t i = 0; i < tCNT; i++ ) ( (device2DSensor *)tA[i] )->reset(); if (tCNT){ free(tA); tA = NULL; }; }; stopSession(); break; }; }; free(tCMD); }; if ( m_pDBC ){ m_pDBC->cleanNodePushedCMD(); } }; SLEEP(SLEEP_KERNEL_INTERVAL); }; } void mojoKernel::loadFilters() { if (m_pDBC == NULL) { return; } #ifdef DEBUG LOG("Loadding Filters ..."); #endif DBC_INT_LIST * tList = m_pDBC->listFilters(m_nServerID); if (tList != NULL) { if (tList->size() > 0) { for (DBC_INT_LIST::iterator idx = tList->begin(); idx < tList->end(); idx++) { #ifdef DEBUG_EXTRA LOG("Load Filter!"); #endif DBC_TARGET_FLITER_DATA * tData = NULL; tData = m_pDBC->getTargetFilterData(*idx); if (tData != NULL) { #ifdef DEBUG_EXTRA LOG("Filter Data OK!"); #endif switch (tData->type) { case TF_LA_METRO_TRAIN_FILTER: { #ifdef DEBUG LOG("Create Train Filter"); #endif kernelEventFilterTrain * tFilter = new kernelEventFilterTrain(*idx); if (tFilter != NULL) { if (tFilter->initFilter()) { #ifdef DEBUG LOG("Add Train Filter"); #endif m_vTargetFilters.push_back((kernelEventFilter *) tFilter); } else { #ifdef DEBUG LOG_ERROR("Error in Filter Init!"); #endif delete(tFilter); }; }; break; }; case TF_AUTHORISED_PEOPLE_FILTER: { LOG("Create APF"); kernelEventFilterAPF * tFilter = new kernelEventFilterAPF(*idx); if (tFilter != NULL) { if (tFilter->initFilter()) { #ifdef DEBUG LOG("Add APF"); #endif m_vTargetFilters.push_back((kernelEventFilter *) tFilter); } else { #ifdef DEBUG LOG_ERROR("Error in Filter Init!"); #endif delete(tFilter); }; }; break; }; case TF_BUBBLE_SEGMENTATION_FILTER: { #ifdef DEBUG LOG("Create Bubble Filter"); #endif kernelEventFilterBubble * tFilter = new kernelEventFilterBubble(*idx); if (tFilter != NULL) { #ifdef DEBUG_EXTRA LOG("Init Bubble Filter"); #endif if (tFilter->initFilter()) { #ifdef DEBUG LOG("Add Bubble Filter"); #endif m_vTargetFilters.push_back((kernelEventFilter *) tFilter); } else { #ifdef DEBUG LOG_ERROR("Error in Filter Init!"); #endif delete(tFilter); }; }; break; }; case TF_YOLO_FILTER: { break; }; default: LOG("Unknoun Filter"); break; }; #ifdef DEBUG_EXTRA LOG("Delete Filter Data"); #endif free(tData); }; }; #ifdef DEBUG_EXTRA LOG("Clear Filter List"); #endif tList->clear(); }; #ifdef DEBUG_EXTRA LOG("Delete Filter List"); #endif delete(tList); #ifdef DEBUG } else { LOG("No Target Filters Assigned!"); #endif }; #ifdef DEBUG LOG("Done Load Filters!"); #endif } void mojoKernel::unloadFilters() { if (m_vTargetFilters.size() > 0) { #ifdef DEBUG LOG("Have Filters to Unload"); #endif for (vectorKernelEventFilters::iterator idx = m_vTargetFilters.begin(); idx < m_vTargetFilters.end(); idx++) { switch ((*idx)->getType()) { case TF_LA_METRO_TRAIN_FILTER: { delete((kernelEventFilterTrain *) (*idx)); break; }; case TF_AUTHORISED_PEOPLE_FILTER: { delete((kernelEventFilterAPF *) (*idx)); break; }; case TF_BUBBLE_SEGMENTATION_FILTER: { delete((kernelEventFilterBubble *) (*idx)); break; }; case TF_YOLO_FILTER: { // ToDo: Must be changed according to Steph's code // delete( (kernelEventFilterYOLO*)(*idx) ); break; }; default: { char tBuffer[64]; sprintf(tBuffer, "Unknown Filter: %d", (*idx)->getType()); LOG(tBuffer); }; }; }; m_vTargetFilters.clear(); LOG("Unload Filters Done!"); #ifdef DEBUG } else { LOG("No Filters to Unload!"); #endif }; } void mojoKernel::validateFilters() { if (m_vTargetFilters.size() > 0) { #ifdef DEBUG_EXTRA LOG("Filters Validation"); #endif for (vectorKernelEventFilters::iterator idx = m_vTargetFilters.begin(); idx < m_vTargetFilters.end(); idx++) { if (! (*idx)->validate()) { LOG_ERROR("Filter is Invalid!"); /*switch ((*idx)->getType()) { case TF_LA_METRO_TRAIN_FILTER:{ delete( (kernelEventFilterTrain*)(*idx) ); break; }; case TF_AUTHORISED_PEOPLE_FILTER:{ delete( (kernelEventFilterAPF*)(*idx) ); break; }; default:{ char tBuffer[64]; sprintf( tBuffer, "Unknown Filter: %d", (*idx)->getType() ); LOG( tBuffer ); }; }; */ }; }; }; } bool mojoKernel::dispatchEvent(EVENT_CONTAINER * Evt) { if (Evt == NULL) { return false; } if (m_bWorkWithRemoteServer && (m_pRPC != NULL)) { m_pRPC->addEvent(Evt); } if (! m_bKeepLocalReport) { return true; } if (m_pDBC == NULL) { return false; } if( m_bForceCloseSessionOnEndOfTheDay && m_bSessionStarted ) { #ifndef LRF_PROXY_ONLY kernelModuleEmbedVideo * tMO = (kernelModuleEmbedVideo *) m_pModuleFactory->getModule(KERNEL_MODULE_EMBED_VIDEO); if( tMO ){ if( !tMO->isProcessingVideoStream() ) { stopSession(); m_bForceCloseSessionOnEndOfTheDay = false; }; } else { LOG_ERROR("No Embed Video Processing Module!"); }; #else stopSession(); m_bForceCloseSessionOnEndOfTheDay = false; #endif } switch (Evt->m_eClass) { case EVT_CLASS_SYSTEM: switch (Evt->m_eType) { case EVT_LRF_START_SESSION: case EVT_LRF_END_SESSION_TO: case EVT_LRF_END_SESSION_MA: { DBC_EVT_RECORD tRecord; memset(&tRecord, 0, sizeof(DBC_EVT_RECORD)); tRecord.ts_s = Evt->m_UMSTS / 1000; tRecord.ts_ms = Evt->m_UMSTS % 1000; tRecord.node_id = m_nServerNodeID; tRecord.type = Evt->m_eType; strncpy(tRecord.uuid, Evt->m_UUID, 64); m_pDBC->addEvent(&tRecord); break; }; default: break; }; break; /* case EVT_CLASS_EXTERNAL_CMD: switch( Evt->m_eType ){ case EVT_FH_JAMER_ON:{ uint32_t TS_A, TS_B; TS_A = Evt->m_UMSTS / 1000; TS_B = Evt->m_UMSTS % 1000; #ifdef SIMULATE_KERNEL_TARGETS m_bJamingTO = SIMULATE_JAMER_TO; #endif FH_CTRL_DATA * tData = (FH_CTRL_DATA *) Evt->m_pEvtData; if( tData ) { if( m_pDBC->addEvent( 0, Evt->m_UUID, TS_A, TS_B, EVT_FH_JAMER_ON, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, tData->evtUUID ) ){ //Simulate FH Module Event; EVENT_CONTAINER *ttt; FH_MISSION_DATA * nnn = (FH_MISSION_DATA *) malloc( sizeof(FH_MISSION_DATA)); if( nnn ){ nnn->location.lat = 0; nnn->location.lon = 0; nnn->location.alt = 0; sprintf( nnn->missionID, tData->evtUUID ); ttt = createBasicEvent( 0, EVT_CLASS_FLY_HUNTER, EVT_FH_JAMER_ON, NULL, NULL, nnn ); if( ttt ) { m_pEventHeap->broadcast( ttt ); } else { free( nnn ); }; }; }; free(tData); }; break; }; case EVT_FH_MISSION_END:{ FH_CTRL_DATA * tData = (FH_CTRL_DATA *) Evt->m_pEvtData; if( tData ) { //DBC_EVT_DATA * tEVT = m_pDBC->getEventByUUID( tData->targetUUID ); if( 1 / *tEVT* / ) { uint32_t TS_A, TS_B; TS_A = Evt->m_UMSTS / 1000; TS_B = Evt->m_UMSTS % 1000; if( m_pDBC->addEvent( 0, Evt->m_UUID, TS_A, TS_B, EVT_FH_LANDED ) ){ //Simulate FH Module Event; EVENT_CONTAINER *ttt; FH_MISSION_DATA * nnn = (FH_MISSION_DATA *) malloc( sizeof(FH_MISSION_DATA)); if( nnn ){ nnn->location.lat = 0; nnn->location.lon = 0; nnn->location.alt = 0; sprintf( nnn->missionID, tData->evtUUID ); ttt = createBasicEvent( 0, EVT_CLASS_FLY_HUNTER, EVT_FH_LANDED, NULL, NULL, nnn ); if( ttt ) { m_pEventHeap->broadcast( ttt ); } else { free( nnn ); }; }; }; //free( tEVT ); } else { LOG_ERROR("Linked Event Was Not Found!"); }; }; break; } case EVT_FH_MISSION_BEGIN:{ FH_CTRL_DATA * tData = (FH_CTRL_DATA *) Evt->m_pEvtData; #ifdef SIMULATE_KERNEL_TARGETS m_bLandingTO = SIMULATE_LANDING_TO; #endif if( tData ) { #ifdef SIMULATE_KERNEL_TARGETS sprintf( m_cCurrentMission, tData->evtUUID ); #endif DBC_EVT_RECORD * tEVT = m_pDBC->getEventByUUID( tData->targetUUID ); if( tEVT ) { uint32_t TS_A, TS_B; TS_A = Evt->m_UMSTS / 1000; TS_B = Evt->m_UMSTS % 1000; if( Evt->m_db_id = m_pDBC->addEvent( 0, Evt->m_UUID, TS_A, TS_B, EVT_FH_FLY_TO, 0, 0, 0, 0, 0, 0, tEVT->lat, tEVT->lon, tEVT->alt, tEVT->id, tEVT->uuid ) ){ //Simulate FH Module Event; EVENT_CONTAINER * ttt; FH_MISSION_DATA * nnn = (FH_MISSION_DATA *) malloc( sizeof(FH_MISSION_DATA)); if( nnn ){ nnn->location.lat = tEVT->lat; nnn->location.lon = tEVT->lon; nnn->location.alt = tEVT->alt; sprintf( nnn->missionID, tData->evtUUID ); ttt = createBasicEvent( 0, EVT_CLASS_FLY_HUNTER, EVT_FH_MISSION_BEGIN, NULL, NULL, nnn ); if( ttt ) { m_pEventHeap->broadcast( ttt ); } else { free( nnn ); }; }; }; free( tEVT ); } else { LOG_ERROR("Linked Event Was Not Found!"); }; }; break; }; }; break; */ case EVT_CLASS_VIDEO: { switch (Evt->m_eType) { case EVT_CAPTURE_DONE: case EVT_CAPTURE_END: { if (Evt->m_pEvtData) { handleVideo((VIDEO_SEGMENT_INFO *) Evt->m_pEvtData); // Dont free Data - it points to static struct of Encoder!! memset(Evt->m_pEvtData, 0, sizeof(VIDEO_SEGMENT_INFO)); Evt->m_pEvtData = NULL; #ifdef DEBUG_EXTRA LOG("VIDEO_SEGMENT_INFO Cleared!"); #endif }; break; }; case EVT_VIDEO_FPS_DEGRADED: case EVT_VIDEO_FPS_RAISED: { if (! m_bDebugMode) { break; } DBC_EVT_RECORD tRecord; memset(&tRecord, 0, sizeof(DBC_EVT_RECORD)); uint32_t TS_A, TS_B; TS_A = Evt->m_UMSTS / 1000; TS_B = Evt->m_UMSTS % 1000; tRecord.node_id = Evt->m_nSourceNodeID; tRecord.type = Evt->m_eType; strncpy(tRecord.uuid, Evt->m_UUID, 64); tRecord.ts_s = TS_A; tRecord.ts_ms = TS_B; Evt->m_db_id = m_pDBC->addEvent(&tRecord); break; }; default: break; }; break; }; case EVT_CLASS_SENSOR_CLD: case EVT_CLASS_SENSOR_LGS: case EVT_CLASS_SENSOR_LFS: case EVT_CLASS_SENSOR_MND: case EVT_CLASS_SENSOR_PLS_210: case EVT_CLASS_SENSOR_PLS_360: case EVT_CLASS_SENSOR_ALS: case EVT_CLASS_SENSOR_3D: case EVT_CLASS_SENSOR_ACC: #ifdef DEBUG_EXTRA char tB[128]; sprintf(tB, "Evt Class: %d Evt Type: %d ", Evt->m_eClass, Evt->m_eType); LOG(tB); #endif switch (Evt->m_eType) { case EVT_TARGET_1D: { // startSession(); preserveSession(); TARGET_DATA * tDATA = (TARGET_DATA *) Evt->m_pEvtData; if (tDATA != NULL) { DBC_EVT_RECORD tRecord; memset(&tRecord, 0, sizeof(DBC_EVT_RECORD)); uint32_t TS_A, TS_B; TS_A = Evt->m_UMSTS / 1000; TS_B = Evt->m_UMSTS % 1000; tRecord.node_id = Evt->m_nSourceNodeID; tRecord.type = Evt->m_eType; strncpy(tRecord.uuid, Evt->m_UUID, 64); tRecord.ts_s = TS_A; tRecord.ts_ms = TS_B; tRecord.range_digital = tDATA->digital; tRecord.ra = tDATA->local_target.r; tRecord.area = tDATA->area; tRecord.lat = tDATA->global_target.lat; tRecord.lon = tDATA->global_target.lon; tRecord.alt = tDATA->global_target.alt; Evt->m_db_id = m_pDBC->addEvent(&tRecord); }; break; }; // While Camera Always Records Video on each Absolute Move // an Event Must be generated to see video in report case EVT_ROI_ACTIVE: // if( !m_bDebugMode ) break; case EVT_TARGET_2D_BLACK: case EVT_TARGET_2D_WHITE: { // startSession(); preserveSession(); TARGET_DATA * tDATA = (TARGET_DATA *) Evt->m_pEvtData; if (tDATA != NULL) { DBC_EVT_RECORD tRecord; memset(&tRecord, 0, sizeof(DBC_EVT_RECORD)); uint32_t TS_A, TS_B; TS_A = Evt->m_UMSTS / 1000; TS_B = Evt->m_UMSTS % 1000; tRecord.node_id = Evt->m_nSourceNodeID; tRecord.type = Evt->m_eType; strncpy(tRecord.uuid, Evt->m_UUID, 64); tRecord.ts_s = TS_A; tRecord.ts_ms = TS_B; tRecord.lrf_id = tDATA->lrf_id; tRecord.range_digital = tDATA->digital; tRecord.az = tDATA->local_target.fi; tRecord.ra = tDATA->local_target.r; tRecord.area = tDATA->area; tRecord.lat = tDATA->global_target.lat; tRecord.lon = tDATA->global_target.lon; tRecord.alt = tDATA->global_target.alt; Evt->m_db_id = m_pDBC->addEvent(&tRecord); }; break; }; case EVT_TARGET_3D_BLACK: case EVT_TARGET_3D_WHITE: { // startSession(); preserveSession(); TARGET_DATA * tDATA = (TARGET_DATA *) Evt->m_pEvtData; if (tDATA != NULL) { DBC_EVT_RECORD tRecord; memset(&tRecord, 0, sizeof(DBC_EVT_RECORD)); uint32_t TS_A, TS_B; TS_A = Evt->m_UMSTS / 1000; TS_B = Evt->m_UMSTS % 1000; tRecord.node_id = Evt->m_nSourceNodeID; tRecord.type = Evt->m_eType; strncpy(tRecord.uuid, Evt->m_UUID, 64); tRecord.ts_s = TS_A; tRecord.ts_ms = TS_B; tRecord.lrf_id = tDATA->lrf_id; tRecord.range_digital = tDATA->digital; tRecord.az = tDATA->local_target.fi; tRecord.el = tDATA->local_target.tetta; tRecord.ra = tDATA->local_target.r; tRecord.area = tDATA->area; tRecord.lat = tDATA->global_target.lat; tRecord.lon = tDATA->global_target.lon; tRecord.alt = tDATA->global_target.alt; Evt->m_db_id = m_pDBC->addEvent(&tRecord); }; break; }; case EVT_ERR_LRF_NO_IRQ: case EVT_ERR_LRF_NO_ZERO: case EVT_ERR_LRF_ANGLE: case EVT_ERR_LRF_VOLTAGE: case EVT_ERR_LRF_BROKEN: case EVT_LRF_VIS_CHANGED: case EVT_ERR_OVERFLOW: case EVT_SST_OVERFLOW: case EVT_COMMUNICATION_JAMED: if (! m_bDebugMode) { break; } /* fall through */ case EVT_OP_ACK_MASK: case EVT_OP_NACK_MASK: case EVT_OP_ON_MASK: case EVT_OP_OFF_MASK: case EVT_CONNECTED: case EVT_DISCONNECTED: { DBC_EVT_RECORD tRecord; memset(&tRecord, 0, sizeof(DBC_EVT_RECORD)); uint32_t TS_A, TS_B; TS_A = Evt->m_UMSTS / 1000; TS_B = Evt->m_UMSTS % 1000; tRecord.node_id = Evt->m_nSourceNodeID; tRecord.type = Evt->m_eType; strncpy(tRecord.uuid, Evt->m_UUID, 64); tRecord.ts_s = TS_A; tRecord.ts_ms = TS_B; Evt->m_db_id = m_pDBC->addEvent(&tRecord); break; }; case EVT_FLIP: { if (! m_bDebugMode) { break; } DBC_EVT_RECORD tRecord; memset(&tRecord, 0, sizeof(DBC_EVT_RECORD)); uint32_t TS_A, TS_B; TS_A = Evt->m_UMSTS / 1000; TS_B = Evt->m_UMSTS % 1000; tRecord.node_id = Evt->m_nSourceNodeID; tRecord.type = Evt->m_eType; strncpy(tRecord.uuid, Evt->m_UUID, 64); tRecord.ts_s = TS_A; tRecord.ts_ms = TS_B; Evt->m_db_id = m_pDBC->addEvent(&tRecord); break; }; default: break; }; break; case EVT_CLASS_KRNL_FILTER_LATF: { TARGET_DATA * tDATA = (TARGET_DATA *) Evt->m_pEvtData; if ((Evt->m_eType > EVT_FLT_LATF_DIFF_DET) || (tDATA == NULL)) { // AUX messages (no additional target data) DBC_EVT_RECORD tRecord; memset(&tRecord, 0, sizeof(DBC_EVT_RECORD)); uint32_t TS_A, TS_B; TS_A = Evt->m_UMSTS / 1000; TS_B = Evt->m_UMSTS % 1000; tRecord.node_id = m_nServerNodeID; tRecord.type = Evt->m_eType; strncpy(tRecord.uuid, Evt->m_UUID, 64); tRecord.ts_s = TS_A; tRecord.ts_ms = TS_B; Evt->m_db_id = m_pDBC->addEvent(&tRecord); } else { // If First Suspiciouse -> Start session to collect Fliter Messages // if( Evt->m_eType == EVT_FLT_LATF_SUSP_START ) startSession(); // Regular LATF with target Info DBC_EVT_RECORD tRecord; memset(&tRecord, 0, sizeof(DBC_EVT_RECORD)); uint32_t TS_A, TS_B; TS_A = Evt->m_UMSTS / 1000; TS_B = Evt->m_UMSTS % 1000; tRecord.node_id = Evt->m_nSourceNodeID; // m_nServerNodeID;//?? tRecord.type = Evt->m_eType; strncpy(tRecord.uuid, Evt->m_UUID, 64); tRecord.ts_s = TS_A; tRecord.ts_ms = TS_B; tRecord.lrf_id = tDATA->lrf_id; tRecord.range_digital = tDATA->digital; tRecord.az = tDATA->local_target.fi; tRecord.el = tDATA->local_target.tetta; tRecord.ra = tDATA->local_target.r; tRecord.area = tDATA->area; tRecord.lat = 0; tRecord.lon = 0; tRecord.alt = 0; #ifdef DEBUG_EXTRA char tB[243]; sprintf(tB, "Az: %0.3f El: %0.3f Ra: %0.3f Dig: %d Width: %0.3f", tRecord.az, tRecord.el, tRecord.ra, tRecord.range_digital, tRecord.area); LOG(tB); #endif Evt->m_db_id = m_pDBC->addEvent(&tRecord); }; break; }; case EVT_CLASS_KRNL_FILTER_BUBBLE: { if (Evt->m_eType == EVT_FLT_BUBBLE_POPED || Evt->m_eType == EVT_FLT_BUBBLE_CREATED || Evt->m_eType == EVT_FLT_BUBBLE_BLOCK_T || Evt->m_eType == EVT_FLT_BUBBLE_BLOCK_P) { preserveSession(); TARGET_DATA * tDATA = (TARGET_DATA *) Evt->m_pEvtData; DBC_EVT_RECORD tRecord; memset(&tRecord, 0, sizeof(DBC_EVT_RECORD)); uint32_t TS_A, TS_B; TS_A = Evt->m_UMSTS / 1000; TS_B = Evt->m_UMSTS % 1000; tRecord.node_id = Evt->m_nSourceNodeID; // m_nServerNodeID;//?? tRecord.type = Evt->m_eType; strncpy(tRecord.uuid, Evt->m_UUID, 64); tRecord.ts_s = TS_A; tRecord.ts_ms = TS_B; tRecord.lrf_id = tDATA->lrf_id; tRecord.range_digital = tDATA->digital; tRecord.az = tDATA->local_target.fi; tRecord.el = tDATA->local_target.tetta; tRecord.ra = tDATA->local_target.r; tRecord.area = tDATA->area; tRecord.lat = 0; tRecord.lon = 0; tRecord.alt = 0; #ifdef DEBUG_EXTRA char tB[243]; sprintf(tB, "Az: %0.3f El: %0.3f Ra: %0.3f Dig: %d Width: %0.3f", tRecord.az, tRecord.el, tRecord.ra, tRecord.range_digital, tRecord.area); LOG(tB); #endif Evt->m_db_id = m_pDBC->addEvent(&tRecord); }; break; }; case EVT_CLASS_REMOTE_SERVER_CMD: { switch (Evt->m_eType) { case EVT_RPC_FRIZE_ACTIVE_B: { // getFilterId break; }; default: break; }; break; }; default: break; }; return true; } /* typedef struct S_VIDEO_SEGMENT_INFO{ uint32_t stream_id; uint32_t streamTSS; uint32_t streamTMS; DBC_INT_LIST eventIDS; DBC_INT_LIST eventFrames; DBC_INT_LIST eventTSS; DBC_INT_LIST eventTMS; char recordMD5[33]; char recordEXT[6]; uint8_t streamFPS; char scratchPath[PATH_MAX]; uint32_t dataSize; uint32_t db_id; }VIDEO_SEGMENT_INFO; */ void mojoKernel::handleVideo(VIDEO_SEGMENT_INFO * ptr) { if (fileExist(ptr->scratchPath)) { bool bKeepVideoFile = false; if (ptr->recordMD5[0]) { if (m_bKeepLocalReport) { // if wm is debug -> add all to database, else send to server ptr->db_id = m_pDBC->addVideoRecord(ptr->stream_id, ptr->recordMD5, ptr->recordEXT, ptr->streamTSS, ptr->streamTMS, ptr->streamFPS); if (ptr->db_id) { #ifdef DEBUG_EXTRA LOG("Video File Registered"); #endif for (size_t idx = 0; idx < ptr->eventIDS.size(); idx++) { #ifdef DEBUG_EXTRA LOG("Binding Event to a Video File!"); #endif if (m_pDBC->addVideoEvent(ptr->eventIDS[idx], ptr->db_id, ptr->eventFrames[idx], ptr->eventTSS[idx], ptr->eventTMS[idx])) { #ifdef DEBUG_EXTRA LOG("OK"); #endif }; }; CSTR tP = m_pDBC->getCurrentReportDir(); if (tP) { char tB[MAX_PATH]; char dB[MAX_PATH]; // sprintf( tB, "%s/data/videos/%s.%s", getcwd(dB,MAX_PATH), ptr->recordMD5, ptr->recordEXT ); sprintf(tB, "%s/data/reports/%s/%s.%s", getcwd(dB, MAX_PATH), tP, ptr->recordMD5, ptr->recordEXT); fileCopy(ptr->scratchPath, tB); ch_chown(tB, "nobody", "nogroup"); chmod(tB, 0664); #ifdef DEBUG_EXTRA LOG("Video Saved"); #endif free(tP); } else { LOG_ERROR("Cannot Get Report Path from DB!"); }; } else { LOG_ERROR("Failure in registration video!"); }; }; if (m_bWorkWithRemoteServer && (m_pRPC != NULL)) { bKeepVideoFile = m_pRPC->addVideo(ptr); } }; if (! bKeepVideoFile) { unlink(ptr->scratchPath); #ifdef DEBUG_EXTRA LOG("Video Scratch Deleted!"); #endif }; } else { LOG_ERROR("Video File is Missing!"); }; //In case end of the day Force Session Close after Video File is saved if ( m_bForceCloseSessionOnEndOfTheDay ) { stopSession( m_bForceCloseSessionOnEndOfTheDay ); m_bForceCloseSessionOnEndOfTheDay = false; }; } /* * Local "report period" = day-of-month * 100 + hour: changes every local hour (and at midnight). */ static int getLocalReportPeriod(void){ time_t t = time(NULL); tm lt; if ( localtime_r( &t, < ) == NULL ) return -1; return lt.tm_mday * 100 + lt.tm_hour; } /* * Called every second from the kernel thread. * Every local hour the current report (data/reports/YYYY/MM/DD/report_HH.db) is closed and * the next hour's report is opened - at midnight in the next day's directory. * * Order of operations: * 1. an open session that started in the previous hour is closed (END event goes into the old * report) - if a video segment with events is still recording, wait for it at most * REPORT_SWITCH_MAX_VIDEO_WAIT seconds so the video is stored next to its events; * 2. once the END event is written (event thread), the report is switched to the new hour. * The next event opens a new session in the new report. * A session started after the hour change already switched the report itself (SESSION_START). */ void mojoKernel::handleReportPeriodChange(void){ int cp = getLocalReportPeriod(); if ( cp < 0 ) return; time_t now = time(NULL); if ( !m_bReportSwitchPending ) { if ( m_nReportPeriod == cp ) return; m_bReportSwitchPending = true; m_tReportSwitchDetected = now; LOG("Local hour changed - closing hour report"); }; bool bTimeOut = ( now - m_tReportSwitchDetected ) >= REPORT_SWITCH_MAX_VIDEO_WAIT; if ( m_bSessionStarted && ( m_nSessionPeriod != cp ) ) { // Session belongs to the previous hour - close it in the previous hour's report m_bForceCloseSessionOnEndOfTheDay = true; #ifndef LRF_PROXY_ONLY kernelModuleEmbedVideo * tMO = (kernelModuleEmbedVideo *) m_pModuleFactory->getModule(KERNEL_MODULE_EMBED_VIDEO); if ( tMO && tMO->isProcessingVideoStream() ) { if ( !bTimeOut ) return; // let the running recording finish into the old report LOG_ERROR("Hour change: video still recording - forcing session close"); }; #endif stopSession( true ); return; // switch on a next call, after the END event is written by the event thread }; // Wait until the END of the previous session is stored in the old report if ( !m_bSessionStarted && m_pDBC->getEventSessionStatus() && !bTimeOut ) return; if ( m_pDBC->switchReportToCurrentHour() ) { m_nReportPeriod = cp; m_bReportSwitchPending = false; m_bForceCloseSessionOnEndOfTheDay = false; LOG("Report switched to the new hour"); } else { LOG_ERROR("Hour report switch failed - will retry"); }; } bool mojoKernel::validateReports(void){ /// @todo Stephane needs to follow this function... if ( m_bKeepLocalReport ){ // Every local hour: close the hour report and open the next one (next day's folder at midnight) handleReportPeriodChange(); DBC_SITE_DATA * tSiteData = m_pDBC->getSiteData(1); if (tSiteData){ // Check if settings has been changed in DB if (tSiteData->report_cleanup != m_sSiteData.report_cleanup || tSiteData->preserve_empty != m_sSiteData.preserve_empty){ memcpy(&m_sSiteData, tSiteData, sizeof(DBC_SITE_DATA)); }; free(tSiteData); } else { LOG_ERROR("Error Loading Site DATA!"); return false; }; if (m_sSiteData.report_cleanup) { cleanUpReportDir(m_sSiteData.report_cleanup); }; if (m_sSiteData.preserve_empty) { float tT = 100.0f * (1.0f - (1.0f / ((float) m_sSiteData.preserve_empty))); #ifdef DEBUG_EXTRA char tB[128]; sprintf(tB, "Check Disk Size: %0.3f %0.3f %d [%d]", m_sSysInfo.disk, tT, m_sSiteData.preserve_empty); LOG(tB); #endif if (m_sSysInfo.disk > tT) { #ifdef DEBUG_EXTRA LOG("Delete Some Reports!"); #endif // delete some oldest report date m_pDBC->deleteReportDate(m_pDBC->getFirstEventTS()); }; }; }; return true; } void mojoKernel::backupReports(uint32_t days) { if (! m_bKeepLocalReport) { return; } REPORT_DIRINFO tRDI;// = {0}; //memset( &tRDI, 0, sizeof(REPORT_DIRINFO)); will be initialized by fillRDF uint32_t cTS = (uint32_t) time(NULL); cTS -= 86400 * days; fillRDF(cTS, tRDI); DBC_INT_LIST * TL = m_pDBC->listOlderReportStat(tRDI.YEAR, tRDI.MONTH, tRDI.DAY); if (TL) { for (DBC_INT_LIST::iterator idx = TL->begin(); idx < TL->end(); idx++) { REPORT_DIRINFO * tRDI = m_pDBC->getReportDirInfo(*idx); if (tRDI) { char tB[MAX_PATH]; char dB[MAX_PATH]; sprintf(tB, "%s/data/reports/%s/%s/%s", getcwd(dB, MAX_PATH), tRDI->YEAR, tRDI->MONTH, tRDI->DAY); char tPATH[MAX_PATH]; sprintf(tPATH, "%s/data/archive/%s_%s_%s", getcwd(dB, MAX_PATH), tRDI->YEAR, tRDI->MONTH, tRDI->DAY); if (fileExist(tB)) { if (! fileExist(tPATH)) { // Try Create Job if sucess then create dir to skip next validation if (createCronJob(0, tPATH, cTS)) { // Create Backup Dir uid_t uid = getUserUid(m_pDBC->getDataParam(1)); gid_t gid = getUserGid(m_pDBC->getDataParam(2)); if (createAccessibleDir(tPATH, STORAGE_DIR_MODE, uid, gid)) { // Create Just One Backup Per Time! free(tRDI); break; }; }; }; // else proceed next }; free(tRDI); }; }; delete(TL); }; } void mojoKernel::cleanUpReportDir(uint32_t days) { // Cleanup Current reports no Backup uint32_t oTS = m_pDBC->getFirstEventTS(); uint32_t cTS = (uint32_t) time(NULL); cTS -= 86400 * days; #ifdef DEBUG_EXTRA char tB[128]; sprintf(tB, "Oldest %d border %d", oTS, cTS); LOG(tB); #endif if (oTS <= cTS) { #ifdef DEBUG_EXTRA LOG("Deleting Old Reports"); #endif /// @todo Stephane needs to see when this gets called... m_pDBC->deleteReportDate(oTS); }; } bool mojoKernel::createCronJob(uint8_t job, CSTR param_str, int param_int) { if (! fileExist("/srv/etc/cron.lock")) { Json::Value root; // Json::Value data; switch (job) { case CRON_JOB_CREATE_BACKUP: { root["operation"] = CRON_JOB_CREATE_BACKUP; // data["number"] = 1; root["ts"] = param_int; root["backup_dst"] = std::string(param_str); break; }; // No default JOB! default: return false; }; FILE * fd = fopen("/srv/etc/cron_.json", "w+"); if (fd) { if (HUMAN_FRIENDLY_JSON) { //Json::FastWriter writer; //const std::string json_file = writer.write(root); //fprintf(fd, json_file.c_str()); Json::StreamWriterBuilder builder; const std::string json_file = Json::writeString(builder, root); fprintf(fd, json_file.c_str()); } else { Json::StreamWriterBuilder builder; const std::string json_file = Json::writeString(builder, root); fprintf(fd, json_file.c_str()); }; fclose(fd); return true; }; }; return false; } #undef LOG #undef LOG_ERROR