From 736cc917bc1b1ba6c9a7ed6f455b106f1a96a382 Mon Sep 17 00:00:00 2001 From: Evgeny Gagua Date: Tue, 15 Aug 2023 09:55:23 -0700 Subject: [PATCH] Video FPS Ease on High load CPU --- Projects/la_mojo/build | 7 +- lib/App/common/SQLite_dataBinder.cpp | 708 +++- lib/App/common/SQLite_dataBinder.h | 49 +- lib/App/common/dataBinder.h | 13 +- lib/App/common/dataBinder_structures.h | 9 +- lib/App/common/deviceNode2D.cpp | 316 +- lib/App/common/deviceNode2D.h | 7 +- lib/App/common/deviceNodeSensor.cpp | 23 +- lib/App/common/deviceNodeSensor.h | 7 +- .../common/hardwareResourceSerialProvider.cpp | 56 +- .../common/hardwareResourceSerialProvider.h | 2 +- lib/App/common/kernelModuleEmbedVideo.cpp | 387 ++- lib/App/common/kernelModuleEmbedVideo.h | 59 +- lib/App/mojo/mojoBackend.cpp | 8 +- lib/App/mojo/mojoKernel.cpp | 74 +- lib/components/base/basicEvent.h | 12 +- lib/data/media/video/videoAVLIBSource.cpp | 9 +- lib/data/protocol/protocolLGS2D.cpp | 109 +- lib/data/protocol/protocolLGS2D.h | 23 +- lib/data/sqlite/sqlite_class.cpp | 97 + lib/data/sqlite/sqlite_class.h | 4 +- lib/include/dbdata.c | 955 ++++++ lib/include/sqlite3recover.c | 2870 +++++++++++++++++ lib/include/sqlite3recover.h | 249 ++ lib/rgoose/rgooseNode2D.h | 1 + lib/rgoose/rgooseTypes.h | 2 +- 26 files changed, 5542 insertions(+), 514 deletions(-) create mode 100644 lib/include/dbdata.c create mode 100644 lib/include/sqlite3recover.c create mode 100644 lib/include/sqlite3recover.h diff --git a/Projects/la_mojo/build b/Projects/la_mojo/build index d0c09c00..08542c16 100755 --- a/Projects/la_mojo/build +++ b/Projects/la_mojo/build @@ -1,14 +1,11 @@ #! /bin/sh -#make clean -e "CFG=Debug86" -#make -e "CFG=Debug86" -j4 +make clean -e "CFG=Debug86" +make -e "CFG=Debug86" -j4 make clean -e "CFG=Release86" make -e "CFG=Release86" -j4 cd Release86 strip ./mojo cd .. - -#make clean -e "CFG=Debug_SLAVE" -#make -e "CFG=Debug_SLAVE" -j4 diff --git a/lib/App/common/SQLite_dataBinder.cpp b/lib/App/common/SQLite_dataBinder.cpp index fe586ae3..bf17c2ba 100644 --- a/lib/App/common/SQLite_dataBinder.cpp +++ b/lib/App/common/SQLite_dataBinder.cpp @@ -28,14 +28,71 @@ sqliteDBC *sqliteDBC::getInstance( config_setting_t * Settings ) { return _instance; }; +uint32_t sqliteDBC::getTsFromRDF( REPORT_DIRINFO &RDF ){ + struct tm ltm; + memset( <m, 0, sizeof( struct tm )); + ltm.tm_mday = atoi( RDF.DAY ); + ltm.tm_mon = atoi( RDF.MONTH ) - 1; + ltm.tm_year = atoi( RDF.YEAR ) - 1900; + return (uint32_t) timelocal( <m ); +}; + +void sqliteDBC::fillRDF( uint32_t ts, REPORT_DIRINFO &RDF ){ + memset( &RDF, 0, sizeof(REPORT_DIRINFO)); + if ( ts ) { + time_t tt = ts; + struct tm * tmp = localtime( &tt ); + if ( tmp ) { + sprintf( RDF.DAY, "%02d", tmp->tm_mday); + sprintf( RDF.MONTH, "%02d", 1+tmp->tm_mon ); + sprintf( RDF.YEAR, "%04d", 1900+tmp->tm_year ); + RDF.ts = getTsFromRDF( RDF ); + }; + }; +}; + +bool sqliteDBC::checkRDFDir( CSTR basePath, REPORT_DIRINFO &RDF ){ + char tBuff[CLOG]; + int RetVal; + sprintf( tBuff, "%s/%s", basePath, RDF.YEAR ); + if( fileExist( tBuff ) == 0 ){ + RetVal = mkdir( tBuff, STORAGE_DIR_MODE ); + chown( tBuff, web_access_user, web_access_group ); + if( RetVal!= 0 ) { + return false; + }; + }; + sprintf( tBuff, "%s/%s/%s", basePath, RDF.YEAR, RDF.MONTH ); + if( fileExist( tBuff ) == 0 ){ + RetVal = mkdir( tBuff, STORAGE_DIR_MODE ); + chown( tBuff, web_access_user, web_access_group ); + if( RetVal!= 0 ) { + return false; + }; + }; + sprintf( tBuff, "%s/%s/%s/%s", basePath, RDF.YEAR, RDF.MONTH, RDF.DAY ); + if( fileExist( tBuff ) == 0 ){ + RetVal = mkdir( tBuff, STORAGE_DIR_MODE ); + chown( tBuff, web_access_user, web_access_group ); + if( RetVal!= 0 ) { + return false; + }; + }; + return true; +}; sqliteDBC::sqliteDBC( config_setting_t * Settings ):dataBinder(){ m_pLog = basicLogCollection::getInstance(); m_pSettings = basicSettingsProvider::getInstance()->getSubNode( Settings, "DATABASE" ); - m_bIsConnected = false; + m_bStoIsConnected = false; + m_bMemIsConnected = false; + m_bRepIsConnected = false; + m_bStaIsConnected = false; + m_bLastEventWasClosed = false; m_pDataStorage = NULL; m_pDataMemory = NULL; m_pDataReports = NULL; + m_pDataStatistics = NULL; m_nServerID = 1; }; @@ -43,6 +100,11 @@ sqliteDBC::~sqliteDBC(){ if ( m_pDataStorage ) delete( m_pDataStorage ); if ( m_pDataMemory ) delete( m_pDataMemory ); if ( m_pDataReports ) delete( m_pDataReports ); + if ( m_pDataStatistics ) delete( m_pDataStatistics ); + m_bStoIsConnected = false; + m_bMemIsConnected = false; + m_bRepIsConnected = false; + m_bStaIsConnected = false; _instance = NULL; }; @@ -52,9 +114,12 @@ bool sqliteDBC::connect( void ){ config_setting_t * pSetting; const char * tBuff; //Disconnect if Connected - m_bIsConnected = false; - char web_access_user[64]; - char web_access_group[64]; + m_bStoIsConnected = false; + m_bMemIsConnected = false; + m_bRepIsConnected = false; + m_bStaIsConnected = false; + m_bLastEventWasClosed = false; + //Apply New Config #ifdef DEBUG @@ -69,14 +134,14 @@ bool sqliteDBC::connect( void ){ } else { sprintf( m_pDbFile, tBuff ); }; - if(!config_setting_lookup_string(m_pSettings, "REPORT_FILE_NAME", (const char**)&tBuff )){ - pSetting = config_setting_add(m_pSettings, "REPORT_FILE_NAME", CONFIG_TYPE_STRING); - sprintf( m_pDbReport, "data/reports.db" ); - config_setting_set_string( pSetting, m_pDbReport ); + if(!config_setting_lookup_string(m_pSettings, "REPORTS_DIR_NAME", (const char**)&tBuff )){ + pSetting = config_setting_add(m_pSettings, "REPORTS_DIR_NAME", CONFIG_TYPE_STRING); + sprintf( m_pDbReportBase, "data/reports" ); + config_setting_set_string( pSetting, m_pDbReportBase ); basicSettingsProvider::getInstance()->compromise(); LOG("Reports Storage not set - using default"); } else { - sprintf( m_pDbReport, tBuff ); + sprintf( m_pDbReportBase, tBuff ); }; if(!config_setting_lookup_string(m_pSettings, "WEB_ACCESS_USER", (const char**)&tBuff )){ pSetting = config_setting_add(m_pSettings, "WEB_ACCESS_USER", CONFIG_TYPE_STRING); @@ -98,9 +163,9 @@ bool sqliteDBC::connect( void ){ }; if( !fileExist( DB_SHMEM_POINT )) { bRecreateMemStructures = true; - mkdir( DB_SHMEM_POINT, 0775 );// S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IXOTH ); + mkdir( DB_SHMEM_POINT, STORAGE_DIR_MODE );// S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IXOTH ); chown( DB_SHMEM_POINT, web_access_user, web_access_group ); //To make Accessed from PHP - chmod( DB_SHMEM_POINT, 0775 ); + chmod( DB_SHMEM_POINT, STORAGE_DIR_MODE ); }; char tB[128]; if (!config_setting_lookup_string(m_pSettings, "DATA_MEMORY_NAME", (const char **)&tBuff)) { @@ -118,6 +183,11 @@ bool sqliteDBC::connect( void ){ if ( m_pDataStorage ) delete( m_pDataStorage ); if ( m_pDataMemory ) delete( m_pDataMemory ); if ( m_pDataReports ) delete( m_pDataReports ); + if ( m_pDataStatistics ) delete( m_pDataStatistics ); + m_pDataMemory = NULL; + m_pDataStorage = NULL; + m_pDataReports = NULL; + m_pDataStatistics = NULL; #ifdef DEBUG LOG( m_pDbFile ); @@ -130,7 +200,8 @@ bool sqliteDBC::connect( void ){ LOG("DB File Opened"); #endif chown( m_pDbFile, web_access_user, web_access_group ); - chmod( m_pDbFile, 0664 ); + chmod( m_pDbFile, DB_FILE_MODE ); + m_bStoIsConnected = true; } else{ LOG_ERROR("Cannot Connect to DB File"); delete( m_pDataStorage ); @@ -155,27 +226,172 @@ bool sqliteDBC::connect( void ){ LOG("DB Memory Opened"); #endif chown( m_pDbMemory, web_access_user, web_access_group ); - chmod( m_pDbMemory, 0664 ); + chmod( m_pDbMemory, DB_FILE_MODE ); m_pDataMemory->SilentQuery("PRAGMA journal_mode=WAL"); //Recreate at Register Server - //if ( bRecreateMemStructures ) initMemDB(); + m_bMemIsConnected = true; } else{ LOG_ERROR("Cannot Connect to DB Memory"); delete( m_pDataStorage ); delete( m_pDataMemory ); + m_bStoIsConnected = false; m_pDataStorage = NULL; m_pDataMemory = NULL; return false; }; }; + sprintf( m_pDbStat, "%s/stat.db", m_pDbReportBase ); + m_pDataStatistics = new SQLite_Connector(); + if ( m_pDataStatistics ) { + if ( fileExist( m_pDbStat )) { + m_bStaIsCreated = false; + if( m_pDataStatistics->Connect( m_pDbStat, 0, true) ) { +#ifdef DEBUG + LOG("DB Statistics Opened"); +#endif + m_pDataStatistics->SilentQuery("PRAGMA journal_mode=WAL"); + m_bStaIsConnected = true; + } else { + LOG_ERROR("Cannot Connect to DB Statistics"); + delete( m_pDataStorage ); + delete( m_pDataMemory ); + delete( m_pDataStatistics ); + m_bMemIsConnected = false; + m_bStoIsConnected = false; + m_pDataStorage = NULL; + m_pDataMemory = NULL; + m_pDataStatistics = NULL; + return false; + }; + } else { + m_bStaIsCreated = true; + if( m_pDataStatistics->Connect( m_pDbStat, 0, true) ) { +#ifdef DEBUG + LOG("DB Statistics Opened"); +#endif + chown( m_pDbStat, web_access_user, web_access_group ); + chmod( m_pDbStat, DB_FILE_MODE ); + m_pDataStatistics->SilentQuery("PRAGMA journal_mode=WAL"); + m_pDataStatistics->SilentQuery("CREATE TABLE \"days\" (\"year\" INTEGER,\"month\" INTEGER,\"day\" INTEGER,\"evt_count\" INTEGER DEFAULT 0,\"session_count\" INTEGER DEFAULT 0,\"videos_count\" INTEGER DEFAULT 0,\"session_closed\" INTEGER DEFAULT 0, CONSTRAINT \"date_uni\" UNIQUE(\"year\",\"month\",\"day\") );"); + m_bStaIsConnected = true; + } else { + LOG_ERROR("Cannot Connect to DB Statistics"); + delete( m_pDataStorage ); + delete( m_pDataMemory ); + delete( m_pDataStatistics ); + m_bMemIsConnected = false; + m_bStoIsConnected = false; + m_pDataStorage = NULL; + m_pDataMemory = NULL; + m_pDataStatistics = NULL; + return false; + }; + }; + }; + m_pDataReports = new SQLite_Connector(); - if ( m_pDataReports ) { - if( m_pDataReports->Connect( m_pDbReport, 0, true ) ){ + if ( m_pDataReports ) { + LOG("RDB Created!"); + memset( &m_sPRepInfo, 0, sizeof(REPORT_DIRINFO)); + if( !m_bStaIsCreated ){ + LOG("OLD STA PRESENT RDB Created!"); + AAssoc * result = m_pDataStatistics->Query( "SELECT * FROM `days` ORDER BY `last_ts` DESC LIMIT 1" ); + if ( result ) { + if( result->size() > 0 ) { + Assoc * cArr; + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("year"); + if( it != cArr->end() ){ + strncpy( m_sPRepInfo.YEAR, it->second.c_str(), 4 ); + }; + it = cArr->find("month"); + if( it != cArr->end() ){ + strncpy( m_sPRepInfo.MONTH, it->second.c_str(), 2 ); + }; + it = cArr->find("day"); + if( it != cArr->end() ){ + strncpy( m_sPRepInfo.DAY, it->second.c_str(), 2 ); + }; + m_sPRepInfo.ts = getTsFromRDF( m_sPRepInfo ); +#ifdef DEBUG_ALL + } else { + + LOG("No Rows Fetched!"); +#endif + }; + }; + m_pDataMemory->deleteResult( result ); + }; + + if ( m_sPRepInfo.ts != 0 ) { + LOG("Old !!"); + if( checkRDFDir( m_pDbReportBase, m_sCRepInfo ) == 0 ) { + LOG_ERROR("Error Connecting to Prev Report!"); + m_bLastEventWasClosed = true; + } else { + sprintf( m_pDbReport, "%s/%s/%s/%s/report.db", m_pDbReportBase, m_sCRepInfo.YEAR, m_sCRepInfo.MONTH, m_sCRepInfo.DAY ); + SQLite_Connector *tDBC = new SQLite_Connector(); + if ( tDBC ) { + char tQBuf[CTEXT]; + AAssoc *result; + sprintf( tQBuf, "SELECT `evt_type` FROM `events` WHERE `node_id`=%d AND ( `evt_type`=%d OR `evt_type`=%d OR `evt_type`=%d ) ORDER BY `ts` DESC, `ts_ms` DESC LIMIT 1", m_nServerNodeID, EVT_LRF_START_SESSION, EVT_LRF_END_SESSION_MA, EVT_LRF_END_SESSION_TO ); + #ifdef DEBUG_ALL + LOG(tQBuf); + #endif + result = m_pDataReports->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("evt_type"); + if( it != cArr->end() ){ + if( atoi( it->second.c_str() ) != EVT_LRF_START_SESSION ) m_bLastEventWasClosed = true; + }; + } else m_bLastEventWasClosed = true; + }; + deleteResult( result ); + delete( tDBC ); + } else { + LOG_ERROR("Error Connecting to Prev Report!"); + m_bLastEventWasClosed = true; + }; + }; + } else m_bLastEventWasClosed = true; + + if ( m_bLastEventWasClosed ) { + LOG("Event Closed!"); + //If Last Event Was Closed -> Create/Open Today's Report + fillRDF( time( NULL ), m_sCRepInfo ); + } else { + //Stay On Last Report database since Event not closed + memcpy( &m_sCRepInfo, &m_sPRepInfo, sizeof(REPORT_DIRINFO) ); + }; + LOG("Check Path!"); + LOG( m_pDbReportBase ); + if( checkRDFDir( m_pDbReportBase, m_sCRepInfo ) == 0 ) { + LOG_ERROR("Cannot Open Report!!"); + return false; + }; + sprintf( m_pDbReport, "%s/%s/%s/%s/report.db", m_pDbReportBase, m_sCRepInfo.YEAR, m_sCRepInfo.MONTH, m_sCRepInfo.DAY ); + LOG("New Path"); + LOG( m_pDbReport ); + if (m_pDataReports->Connect( m_pDbReport, 0, true )) { #ifdef DEBUG LOG("Report File Opened"); #endif chown( m_pDbReport, web_access_user, web_access_group ); - chmod( m_pDbReport, 0664 ); + chmod( m_pDbReport, DB_FILE_MODE ); + if ( m_sCRepInfo.ts != m_sPRepInfo.ts ) { + // Created New Report ?? + m_pDataReports->SilentQuery("CREATE TABLE \"events\" ( \"id\" INTEGER NOT NULL, \"node_id\" INTEGER NOT NULL, \"uuid\" TEXT NOT NULL UNIQUE, \"ts\" INTEGER NOT NULL, \"ts_ms\" INTEGER NOT NULL, \"evt_type\" INTEGER NOT NULL, \"range_digital\" INTEGER, \"azimuth\" REAL, \"elevation\" REAL, \"range\" REAL, \"area\" REAL, \"lat\" REAL, \"lon\" REAL, \"alt\" REAL, \"ref_id\" INTEGER, \"ref_uuid\" TEXT, PRIMARY KEY(\"id\" AUTOINCREMENT) )"); + m_pDataReports->SilentQuery("CREATE TABLE \"events_2_pictures\" ( \"evt_id\" INTEGER NOT NULL, \"picture_id\" INTEGER NOT NULL )"); + m_pDataReports->SilentQuery("CREATE TABLE \"events_2_videos\" ( \"evt_id\" INTEGER NOT NULL, \"video_id\" INTEGER NOT NULL, \"frame\" INTEGER DEFAULT 0, \"tss\" INTEGER, \"tms\" INTEGER )"); + m_pDataReports->SilentQuery("CREATE TABLE \"pictures\" ( \"id\" INTEGER NOT NULL, \"media_stream_id\" INTEGER NOT NULL, \"md5\" TEXT NOT NULL UNIQUE, \"uts\" INTEGER NOT NULL, \"uts_ms\" INTEGER NOT NULL, \"ext\" TEXT NOT NULL, \"data\" BLOB COLLATE BINARY, PRIMARY KEY(\"id\" AUTOINCREMENT) )"); + m_pDataReports->SilentQuery("CREATE TABLE \"videos\" ( \"id\" INTEGER NOT NULL, \"media_stream_id\" INTEGER NOT NULL, \"md5\" TEXT NOT NULL UNIQUE, \"uts\" INTEGER NOT NULL, \"uts_ms\" INTEGER NOT NULL, \"ext\" TEXT NOT NULL, \"fps\" INTEGER NOT NULL, \"flength\" INTEGER, PRIMARY KEY(\"id\" AUTOINCREMENT) )"); + }; + m_bRepIsConnected = true; } else{ LOG_ERROR("Cannot Connect to DB File"); delete( m_pDataReports ); @@ -184,8 +400,8 @@ bool sqliteDBC::connect( void ){ return false; }; }; - m_bIsConnected = true; - return m_bIsConnected; + + return ( m_bRepIsConnected && m_bMemIsConnected && m_bStoIsConnected && m_bStaIsConnected ); }; void sqliteDBC::initMemDB( uint32_t sid ){ @@ -224,10 +440,19 @@ m_pDataMemory->SilentQuery( tB ); }; +CSTR sqliteDBC::getCurrentReportDir( void ){ + CSTR tV = NULL; + if ( m_sCRepInfo.ts ) { + char tBuf[256]; + sprintf( tBuf, "%s/%s/%s", m_sCRepInfo.YEAR, m_sCRepInfo.MONTH, m_sCRepInfo.DAY ); + tV = strdup( tBuf ); + }; + return tV; +}; DBC_PUSHED_CMD *sqliteDBC::getNodePushedCMD( uint32_t NodeID ){ DBC_PUSHED_CMD * RetVal = NULL; - if ( m_bIsConnected ) { + if ( m_bMemIsConnected ) { char QS[MAX_PATH]; AAssoc * result; sprintf( QS, "select * FROM `nodes_qcq` WHERE `node_id`=%d AND `status`=0 ORDER BY `id` LIMIT 1", NodeID ); @@ -271,7 +496,7 @@ DBC_PUSHED_CMD *sqliteDBC::getNodePushedCMD( uint32_t NodeID ){ }; bool sqliteDBC::updateNodePushedCMD( uint32_t CmdID, uint8_t status ){ - if ( m_bIsConnected ) { + if ( m_bMemIsConnected ) { char QS[MAX_PATH]; sprintf( QS, "UPDATE `nodes_qcq` SET `status`=%d WHERE `id`=%d ", status, CmdID ); return m_pDataMemory->SilentQuery( QS ); @@ -280,14 +505,14 @@ bool sqliteDBC::updateNodePushedCMD( uint32_t CmdID, uint8_t status ){ }; bool sqliteDBC::cleanNodePushedCMD( void ){ - if ( m_bIsConnected ) { + if ( m_bMemIsConnected ) { return m_pDataMemory->SilentQuery( "DELETE FROM `nodes_qcq` WHERE `status` > 200" ); }; return false; }; void sqliteDBC::deleteNIF( uint32_t NifID ){ - if ( m_bIsConnected ) { + if ( m_bStoIsConnected ) { char tQBuf[MAX_PATH_LEN]; sprintf( tQBuf, "", NifID ); #ifdef DEBUG_ALL @@ -316,7 +541,7 @@ void sqliteDBC::deleteUART( uint32_t UARTID ){ bool sqliteDBC::updateServerUtilisation( DBC_SYS_LOAD_INFO *ptr ){ - if( m_bIsConnected ) { + if( m_bMemIsConnected ) { char tQBuf[MAX_PATH_LEN]; sprintf(tQBuf, "UPDATE `servers` SET `ts`=STRFTIME('%%s'), `cpu_cores`=%d, `stat_cpu1`=%0.1f, `stat_cpu5`=%0.1f, `stat_cpu15`=%0.1f, `stat_mem`=%0.1f, `stat_disk`=%0.1f, `temp0`=%0.1f, `val_mem_tottal`=%" PRIu64 ", `val_mem_current`=%" PRIu64 ", `val_disk_tottal`=%" PRIu64 ", `val_disk_current`=%" PRIu64 " WHERE `id`=%d", ptr->CPU_CORES, @@ -348,38 +573,134 @@ bool sqliteDBC::updateServerUtilisation( DBC_SYS_LOAD_INFO *ptr ){ * * ********************************************************************/ bool sqliteDBC::addDeviceDraw( uint32_t DBID, uint8_t type, uint8_t lrf, void *th_data, uint32_t th_size ){ - char tQBuf[1024]; - if ( type == 0 ) { - CSTR uid = getUniqID_MD5(); - if( uid == NULL ) return false; - sprintf( tQBuf, "data/device_draws/%s.raw", uid ); - FILE *fd = fopen( tQBuf, "wb+" ); - if( fd!= NULL ) { - uint32_t sisi = th_size >> 2; - fwrite( &sisi, 4, 1, fd ); - fwrite( th_data, 4, sisi, fd ); - fclose( fd ); - sprintf( tQBuf, "INSERT INTO `lrf_draw`(`node_id`,`lrf_id`,`type`,`ts`,`data`) VALUES(%d,%d,%d,STRFTIME('%%s'),'%s')", - DBID, lrf, type, uid ); - free ( uid ); -#ifdef DEBUG - LOG(tQBuf); -#endif - m_pDataStorage->SilentQuery( tQBuf ); - return true; + if ( m_bStoIsConnected ){ + char tQBuf[1024]; + if ( type == 0 ) { + CSTR uid = getUniqID_MD5(); + if( uid == NULL ) return false; + sprintf( tQBuf, "data/device_draws/%s.raw", uid ); + FILE *fd = fopen( tQBuf, "wb+" ); + if( fd!= NULL ) { + uint32_t sisi = th_size >> 2; + fwrite( &sisi, 4, 1, fd ); + fwrite( th_data, 4, sisi, fd ); + fclose( fd ); + sprintf( tQBuf, "INSERT INTO `lrf_draw`(`node_id`,`lrf_id`,`type`,`ts`,`data`) VALUES(%d,%d,%d,STRFTIME('%%s'),'%s')", + DBID, lrf, type, uid ); + free ( uid ); + #ifdef DEBUG + LOG(tQBuf); + #endif + m_pDataStorage->SilentQuery( tQBuf ); + return true; + }; + free( uid ); + } else { + LOG("No RAW DATA!"); }; - free( uid ); - } else { - LOG("No RAW DATA!"); }; return false; }; +void sqliteDBC::updateStats( bool evt, bool video, uint8_t ses_status ){ + if (m_bStaIsConnected ) { + char tQBuf[1024]; + switch ( ses_status ) { + case SESSION_CONTINUE:{ + if ( video ) { + sprintf(tQBuf, "INSERT INTO `days`(`year`,`month`,`day`,`videos_count`) VALUES(%s,%s,%s,1) ON CONFLICT(`year`,`month`,`day`) DO UPDATE SET `videos_count`=`videos_count`+1", + m_sCRepInfo.YEAR, m_sCRepInfo.MONTH, m_sCRepInfo.DAY ); + } else { + sprintf(tQBuf, "INSERT INTO `days`(`year`,`month`,`day`,`evt_count`) VALUES(%s,%s,%s,1) ON CONFLICT(`year`,`month`,`day`) DO UPDATE SET `evt_count`=`evt_count`+1", + m_sCRepInfo.YEAR, m_sCRepInfo.MONTH, m_sCRepInfo.DAY ); + }; +#ifdef DEBUG_ALL + LOG( tQBuf ); +#endif + m_pDataStatistics->SilentQuery( tQBuf ); + break; + }; + case SESSION_START:{ + sprintf( tQBuf, "INSERT INTO `days`(`year`,`month`,`day`,`session_count`,`session_closed`) VALUES(%s,%s,%s,1,0) ON CONFLICT(`year`,`month`,`day`) DO UPDATE SET `session_count`=`session_count`+1, `session_closed`=0", + m_sCRepInfo.YEAR, m_sCRepInfo.MONTH, m_sCRepInfo.DAY ); +#ifdef DEBUG_ALL + LOG( tQBuf ); +#endif + m_pDataStatistics->SilentQuery( tQBuf ); + break; + }; + case SESSION_END:{ + sprintf( tQBuf, "INSERT INTO `days`(`year`,`month`,`day`,`session_count`,`session_closed`) VALUES(%s,%s,%s,0,1) ON CONFLICT(`year`,`month`,`day`) DO UPDATE SET `session_closed`=1", + m_sCRepInfo.YEAR, m_sCRepInfo.MONTH, m_sCRepInfo.DAY ); +#ifdef DEBUG_ALL + LOG( tQBuf ); +#endif + m_pDataStatistics->SilentQuery( tQBuf ); + REPORT_DIRINFO tRR = {0}; + fillRDF( time( NULL ), tRR ); + if( tRR.ts > m_sCRepInfo.ts ) { + //New Day Report + if ( m_bRepIsConnected ) { + m_bRepIsConnected = false; + LOG("Disconnect Report!"); + m_pDataReports->Disconnect(); + }; + memcpy( &m_sPRepInfo, &m_sCRepInfo, sizeof(REPORT_DIRINFO) ); + memcpy( &m_sCRepInfo, &tRR, sizeof(REPORT_DIRINFO) ); + if( checkRDFDir( m_pDbReportBase, m_sCRepInfo ) ){ + sprintf( m_pDbReport, "%s/%s/%s/%s/report.db", m_pDbReportBase, m_sCRepInfo.YEAR, m_sCRepInfo.MONTH, m_sCRepInfo.DAY ); + LOG("Connect Report!"); + LOG( m_pDbReport ); + if( m_pDataReports->Connect( m_pDbReport, 0, true ) ){ + chown( m_pDbReport, web_access_user, web_access_group ); + chmod( m_pDbReport, DB_FILE_MODE ); + m_pDataReports->SilentQuery("CREATE TABLE \"events\" ( \"id\" INTEGER NOT NULL, \"node_id\" INTEGER NOT NULL, \"uuid\" TEXT NOT NULL UNIQUE, \"ts\" INTEGER NOT NULL, \"ts_ms\" INTEGER NOT NULL, \"evt_type\" INTEGER NOT NULL, \"range_digital\" INTEGER, \"azimuth\" REAL, \"elevation\" REAL, \"range\" REAL, \"area\" REAL, \"lat\" REAL, \"lon\" REAL, \"alt\" REAL, \"ref_id\" INTEGER, \"ref_uuid\" TEXT, PRIMARY KEY(\"id\" AUTOINCREMENT) )"); + m_pDataReports->SilentQuery("CREATE TABLE \"events_2_pictures\" ( \"evt_id\" INTEGER NOT NULL, \"picture_id\" INTEGER NOT NULL )"); + m_pDataReports->SilentQuery("CREATE TABLE \"events_2_videos\" ( \"evt_id\" INTEGER NOT NULL, \"video_id\" INTEGER NOT NULL, \"frame\" INTEGER DEFAULT 0, \"tss\" INTEGER, \"tms\" INTEGER )"); + m_pDataReports->SilentQuery("CREATE TABLE \"pictures\" ( \"id\" INTEGER NOT NULL, \"media_stream_id\" INTEGER NOT NULL, \"md5\" TEXT NOT NULL UNIQUE, \"uts\" INTEGER NOT NULL, \"uts_ms\" INTEGER NOT NULL, \"ext\" TEXT NOT NULL, \"data\" BLOB COLLATE BINARY, PRIMARY KEY(\"id\" AUTOINCREMENT) )"); + m_pDataReports->SilentQuery("CREATE TABLE \"videos\" ( \"id\" INTEGER NOT NULL, \"media_stream_id\" INTEGER NOT NULL, \"md5\" TEXT NOT NULL UNIQUE, \"uts\" INTEGER NOT NULL, \"uts_ms\" INTEGER NOT NULL, \"ext\" TEXT NOT NULL, \"fps\" INTEGER NOT NULL, \"flength\" INTEGER, PRIMARY KEY(\"id\" AUTOINCREMENT) )"); + m_bRepIsConnected = true; + LOG("Report Connected!"); + // Create New Day Record + sprintf(tQBuf, "INSERT INTO `days`(`year`,`month`,`day`,`session_count`,`session_closed`) VALUES(%s,%s,%s,0,1) ON CONFLICT(`year`,`month`,`day`) DO UPDATE SET `session_count`=`session_count`+1, `session_closed`=1", + m_sCRepInfo.YEAR, m_sCRepInfo.MONTH, m_sCRepInfo.DAY ); + LOG( tQBuf ); + m_pDataStatistics->SilentQuery( tQBuf ); + }; + }; + }; + break; + }; + }; + }; +}; + uint32_t sqliteDBC::addEvent( DBC_EVT_RECORD *ptr ){ if ( ptr == NULL ) return 0; - if (m_bIsConnected) { + if ( m_bRepIsConnected ) { char tQBuf[1024]; switch ( ptr->type ) { + case EVT_LRF_END_SESSION_TO: + case EVT_LRF_END_SESSION_MA: + updateStats( false, false, SESSION_END ); + sprintf( tQBuf, "INSERT INTO `events`(`node_id`,`uuid`,`ts`,`ts_ms`,`evt_type`) VALUES(%d,'%s',%d,%d,%d)", + ptr->node_id, + ptr->uuid, + ptr->ts_s, + ptr->ts_ms, + ptr->type + ); + break; + case EVT_LRF_START_SESSION: + updateStats( false, false, SESSION_START ); + sprintf( tQBuf, "INSERT INTO `events`(`node_id`,`uuid`,`ts`,`ts_ms`,`evt_type`) VALUES(%d,'%s',%d,%d,%d)", + ptr->node_id, + ptr->uuid, + ptr->ts_s, + ptr->ts_ms, + ptr->type + ); + break; case EVT_FLT_LATF_CHK: case EVT_FLT_LATF_UP_DETEC: case EVT_FLT_LATF_BT_DETEC: @@ -391,13 +712,21 @@ uint32_t sqliteDBC::addEvent( DBC_EVT_RECORD *ptr ){ case EVT_FLT_LATF_DISABLED: case EVT_FLT_LATF_SUSP_DET: case EVT_FLT_LATF_DIFF_DET: - case EVT_LRF_START_SESSION: - case EVT_LRF_END_SESSION_TO: - case EVT_LRF_END_SESSION_MA: + case EVT_CONNECTED: + case EVT_DISCONNECTED: + case EVT_COMMUNICATION_JAMED: case EVT_STUDY: case EVT_BUSY: case EVT_FLIP: - case EVT_READY:{ + case EVT_READY: + case EVT_ERR_LRF_NO_IRQ: + case EVT_ERR_LRF_ANGLE: + case EVT_ERR_LRF_MAINTENANCE: + case EVT_ERR_LRF_TROUBLE: + case EVT_LRF_VIS_CHANGED: + case EVT_VIDEO_FPS_DEGRADED: + case EVT_VIDEO_FPS_RAISED:{ + updateStats(); sprintf( tQBuf, "INSERT INTO `events`(`node_id`,`uuid`,`ts`,`ts_ms`,`evt_type`) VALUES(%d,'%s',%d,%d,%d)", ptr->node_id, ptr->uuid, @@ -410,6 +739,7 @@ uint32_t sqliteDBC::addEvent( DBC_EVT_RECORD *ptr ){ case EVT_ROI_ACTIVE: case EVT_TARGET_3D_WHITE: case EVT_TARGET_3D_BLACK:{ + updateStats(); sprintf( tQBuf, "INSERT INTO `events`(`node_id`,`uuid`,`ts`,`ts_ms`,`evt_type`,`range_digital`,`azimuth`,`elevation`,`range`,`area`,`lat`,`lon`,`alt`)" \ " VALUES(%d,'%s',%d,%d,%d,%d,%0.2f,%0.2f,%0.2f,%0.2f,%0.7f,%0.7f,%0.2f)", ptr->node_id, @@ -430,6 +760,7 @@ uint32_t sqliteDBC::addEvent( DBC_EVT_RECORD *ptr ){ }; case EVT_TARGET_2D_WHITE: case EVT_TARGET_2D_BLACK:{ + updateStats(); sprintf( tQBuf, "INSERT INTO `events`(`node_id`,`uuid`,`ts`,`ts_ms`,`evt_type`,`range_digital`,`azimuth`,`range`,`area`,`lat`,`lon`,`alt`)" \ " VALUES(%d,'%s',%d,%d,%d,%d,%0.2f,%0.2f,%0.2f,%0.7f,%0.7f,%0.2f)", ptr->node_id, @@ -450,13 +781,17 @@ uint32_t sqliteDBC::addEvent( DBC_EVT_RECORD *ptr ){ default: return 0; }; LOG( tQBuf ); - return ptr->id = m_pDataReports->QueryID( tQBuf ); + if ( m_bRepIsConnected ) { + return ptr->id = m_pDataReports->QueryID(tQBuf); + } else { + LOG_ERROR("Report DB Droped!"); + } }; return 0; }; bool sqliteDBC::addIPCam( OBSERVER_RESULT *tPtr ){ - if(m_bIsConnected) { + if(m_bStoIsConnected) { char tQBuf[1024]; char tIpBuf[32]; char tProto[32]; @@ -537,7 +872,7 @@ bool sqliteDBC::addIPCam( OBSERVER_RESULT *tPtr ){ uint32_t sqliteDBC::addLocalCam( CSTR name, CSTR hardware, CSTR path, uint32_t width, uint32_t height, uint16_t fps, uint16_t den ){ uint32_t RetVal = 0; - if( m_bIsConnected ) { + if( m_bStoIsConnected ) { char tQBuf[1024]; char tM5[33]; @@ -576,7 +911,7 @@ uint32_t sqliteDBC::addLocalCam( CSTR name, CSTR hardware, CSTR path, uint32_t w uint32_t sqliteDBC::addLocalNetwork( uint32_t NIF_ID, NETWORK_TYPE net_type, CSTR address, CSTR mask, CSTR gateway, CSTR broadcast ){ uint32_t RetVal = 0; - if( m_bIsConnected ) { + if( m_bStoIsConnected ) { char tQBuf[MAX_PATH_LEN]; sprintf( tQBuf, "INSERT INTO `networks`(`nif_id`,`type`,`address`,`gateway`,`mask`,`broadcast`) VALUES (%d,%d,'%s','%s','%s','%s') ON CONFLICT(`nif_id`,`type`) DO UPDATE SET `address`='%s', `gateway`='%s', `mask`='%s', `broadcast`='%s'", NIF_ID, @@ -604,7 +939,7 @@ uint32_t sqliteDBC::addLocalNetwork( uint32_t NIF_ID, NETWORK_TYPE net_type, CST uint32_t sqliteDBC::addLocalNetworkInfrastructure( uint32_t NIF_ID, uint32_t OUTBOUND_NIF, bool ena_dhcp, CSTR BRANG, CSTR ERANG, CSTR MASK, CSTR LEASE_TIME ){ uint32_t RetVal = 0; - if( m_bIsConnected ) { + if( m_bStoIsConnected ) { char tQBuf[MAX_PATH_LEN]; bool ena_routing = true; if( OUTBOUND_NIF == 0 ){ @@ -656,7 +991,7 @@ uint32_t sqliteDBC::addLocalNetworkInfrastructure( uint32_t NIF_ID, uint32_t OUT uint32_t sqliteDBC::addLocalNIF( CSTR device, CSTR mac, NIF_TYPE dtype, NIF_MODE dmode, uint32_t aux_id ){ uint32_t RetVal = 0; - if( m_bIsConnected ) { + if( m_bStoIsConnected ) { char tQBuf[MAX_PATH_LEN]; char * tKey = MD5String( device ); if( tKey != NULL ) { @@ -686,7 +1021,7 @@ uint32_t sqliteDBC::addLocalNIF( CSTR device, CSTR mac, NIF_TYPE dtype, NIF_MOD uint32_t sqliteDBC::addLocalUART( uint8_t utype, uint32_t speed, uint8_t bit, char parity, float stop_bit, CSTR PATH, uint8_t mode, uint16_t port ){ uint32_t RetVal = 0; - if( m_bIsConnected ) { + if( m_bStoIsConnected ) { char tQBuf[MAX_PATH_LEN]; sprintf( tQBuf, "INSERT INTO `uart_settings`(`node_id`,`type`,`speed`,`bit`,`parity`,`stop_bit`,`mode`,`port`,`path`) VALUES (%d,%d,%d,%d,'%c',%.1f,%d,%d,'%s') ON CONFLICT(`node_id`,`type`,`path`) DO UPDATE SET `id`=`id`", m_nServerNodeID, @@ -712,7 +1047,7 @@ uint32_t sqliteDBC::addLocalUART( uint8_t utype, uint32_t speed, uint8_t bit, ch uint32_t sqliteDBC::addLocalWiFi( uint32_t NIF_ID, WIFI_MODE mode, CSTR SSID, CSTR password, WIFI_ENCRIPTION encryption, uint32_t router_id ){ uint32_t RetVal = 0; - if( m_bIsConnected ) { + if( m_bStoIsConnected ) { char tQBuf[MAX_PATH_LEN]; sprintf( tQBuf, "INSERT INTO `wifis` (`nif_id`,`mode`,`aux_id`,`SSID`,`password`,`encryption_type`) VALUES (%d,%d,%d,'%s','%s',%d) ON CONFLICT (`nif_id`) DO UPDATE SET `mode`=%d, `aux_id`=%d, `SSID`='%s', `password`='%s', `encryption_type`=%d", NIF_ID, @@ -739,18 +1074,18 @@ uint32_t sqliteDBC::addLocalWiFi( uint32_t NIF_ID, WIFI_MODE mode, CSTR SSID, CS }; bool sqliteDBC::cleanLRFMask( uint32_t maskID, bool deleteMask ){ - if(m_bIsConnected) { + 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 ); + //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 - LOG(tQBuf); + //LOG(tQBuf); #endif - m_pDataStorage->SilentQuery( tQBuf ); - sprintf( tQBuf, "DELETE FROM `lrf_mask_traces` WHERE `mask_id`=%d", maskID ); + //m_pDataStorage->SilentQuery( tQBuf ); + //sprintf( tQBuf, "DELETE FROM `lrf_mask_traces` WHERE `mask_id`=%d", maskID ); #ifdef DEBUG_EXTRA - LOG(tQBuf); + //LOG(tQBuf); #endif - m_pDataStorage->SilentQuery( tQBuf ); + //m_pDataStorage->SilentQuery( tQBuf ); sprintf( tQBuf, "DELETE FROM `lrf_mask_vertex_points` WHERE `vertex_id` IN ( SELECT `id` FROM `lrf_mask_vertexes` WHERE `mask_id`=%d )", maskID ); #ifdef DEBUG_EXTRA LOG(tQBuf); @@ -775,7 +1110,7 @@ bool sqliteDBC::cleanLRFMask( uint32_t maskID, bool deleteMask ){ }; bool sqliteDBC::cleanResources( bool all ){ - if(m_bIsConnected) { + if( m_bStoIsConnected ) { char tQBuf[MAX_PATH_LEN]; if( all ) { sprintf( tQBuf, "UPDATE `resources` SET `active`=0 WHERE `node_id`=%d", m_nServerNodeID ); @@ -792,7 +1127,7 @@ bool sqliteDBC::cleanResources( bool all ){ }; bool sqliteDBC::wipeServerResources(){ - if( m_bIsConnected ) { + if( m_bStoIsConnected ) { char tQBuf[MAX_PATH_LEN]; sprintf( tQBuf, "DELETE FROM `resources` WHERE `node_id`=%d", m_nServerNodeID ); #ifdef DEBUG_ALL @@ -806,7 +1141,7 @@ bool sqliteDBC::wipeServerResources(){ uint32_t sqliteDBC::addLRFMask( uint32_t devID, uint8_t lrfID, uint8_t layerID ){ uint32_t RetVal = 0; - if( m_bIsConnected ) { + if( m_bStoIsConnected ) { char tQBuf[MAX_PATH_LEN]; sprintf( tQBuf, "INSERT INTO `lrf_masks`(`sensor_id`,`lrf_id`,`layer`) VALUES(%d,%d,%d) ON CONFLICT(`sensor_id`,`lrf_id`,`layer`) DO UPDATE SET `layer`=%d", devID, @@ -827,7 +1162,7 @@ uint32_t sqliteDBC::addLRFMask( uint32_t devID, uint8_t lrfID, uint8_t layerID ) uint32_t sqliteDBC::addLRFMaskPolygone( uint32_t maskID, uint8_t r, uint8_t g, uint8_t b ){ uint32_t RetVal = 0; - if( m_bIsConnected ) { + if( m_bStoIsConnected ) { char tQBuf[MAX_PATH_LEN]; sprintf( tQBuf, "INSERT INTO `lrf_mask_vertexes`(`mask_id`,`r`,`g`,`b`) VALUES(%d,%d,%d,%d)", maskID, @@ -844,7 +1179,7 @@ uint32_t sqliteDBC::addLRFMaskPolygone( uint32_t maskID, uint8_t r, uint8_t g, u }; bool sqliteDBC::addLRFMaskPolygonePoint( uint32_t polyID, int16_t x, int16_t y ){ - if( m_bIsConnected ) { + if( m_bStoIsConnected ) { char tQBuf[MAX_PATH_LEN]; sprintf( tQBuf, "INSERT INTO `lrf_mask_vertex_points`(`vertex_id`,`x`,`y`) VALUES(%d,%d,%d)", polyID, @@ -862,7 +1197,7 @@ bool sqliteDBC::addLRFMaskPolygonePoint( uint32_t polyID, int16_t x, int16_t y ) uint32_t sqliteDBC::addResource( uint8_t type, CSTR devName, uint32_t auxID ){ uint32_t RetVal = 0; - if( m_bIsConnected ){ + if( m_bStoIsConnected ){ char tQBuf[2048]; sprintf( tQBuf, "%d:%d:%s", m_nServerNodeID, type, devName ); CSTR tMD5 = MD5String( tQBuf ); @@ -889,7 +1224,7 @@ uint32_t sqliteDBC::addResource( uint8_t type, CSTR devName, uint32_t auxID ){ }; bool sqliteDBC::addVideoEvent( uint32_t evtID, uint32_t videoID, uint32_t frame, uint32_t tss, uint32_t tms ){ - if( m_bIsConnected ){ + if( m_bRepIsConnected ){ char tQBuf[2048]; sprintf( tQBuf, "INSERT INTO `events_2_videos`(`evt_id`,`video_id`,`frame`,`tss`,`tms`) VALUES(%d,%d,%d,%d,%d)", evtID, @@ -908,7 +1243,8 @@ bool sqliteDBC::addVideoEvent( uint32_t evtID, uint32_t videoID, uint32_t frame, uint32_t sqliteDBC::addVideoRecord( uint32_t streamID, CSTR md5, CSTR ext, uint32_t tss, uint32_t tms, uint32_t fps ){ uint32_t RetVal = 0; - if( m_bIsConnected ){ + if( m_bRepIsConnected ){ + updateStats( false, true ); char tQBuf[2048]; sprintf( tQBuf, "INSERT INTO `videos`(`media_stream_id`,`md5`,`uts`,`uts_ms`,`ext`,`fps`) VALUES(%d,'%s',%d,%d,'%s',%d)", streamID, @@ -928,7 +1264,7 @@ uint32_t sqliteDBC::addVideoRecord( uint32_t streamID, CSTR md5, CSTR ext, uint3 DBC_MODULE_EMBED_VIDEO_DATA *sqliteDBC::getEmbedVideoData( uint32_t ID ){ DBC_MODULE_EMBED_VIDEO_DATA *tPtr = NULL; - if( m_bIsConnected ) { + if( m_bStoIsConnected ) { char tQBuf[MAX_PATH_LEN]; AAssoc *result; sprintf( tQBuf, "SELECT * FROM `module_eve` WHERE `id`=%d", ID ); @@ -1063,7 +1399,7 @@ DBC_MODULE_EMBED_VIDEO_DATA *sqliteDBC::getEmbedVideoData( uint32_t ID ){ DBC_MEDIA_STREAM_DATA *sqliteDBC::getMediaStreamData(uint32_t ID){ DBC_MEDIA_STREAM_DATA *tVal = NULL; - if(m_bIsConnected){ + if( m_bStoIsConnected ){ char tQBuf[CTEXT]; AAssoc *result; sprintf(tQBuf, "SELECT * FROM media_streams WHERE `id`=%d", ID ); @@ -1134,7 +1470,7 @@ DBC_MEDIA_STREAM_DATA *sqliteDBC::getMediaStreamData(uint32_t ID){ uint32_t sqliteDBC::getMediaStreamID( uint32_t source_id, CSTR token ){ uint32_t RetVal = 0; - if(m_bIsConnected){ + if( m_bStoIsConnected ){ char tQBuf[CTEXT]; AAssoc *result; sprintf(tQBuf, "SELECT `id` FROM `media_streams` WHERE `source_id`=%d AND `token`='%s'", source_id, token ); @@ -1160,7 +1496,7 @@ uint32_t sqliteDBC::getMediaStreamID( uint32_t source_id, CSTR token ){ DBC_MODULE_DATA *sqliteDBC::getModuleData( uint32_t ID ){ DBC_MODULE_DATA *tVal = NULL; - if(m_bIsConnected){ + if( m_bStoIsConnected ){ char tQBuf[CTEXT]; AAssoc *result; sprintf(tQBuf, "SELECT * FROM modules WHERE `id`=%d", ID ); @@ -1201,7 +1537,7 @@ DBC_MODULE_DATA *sqliteDBC::getModuleData( uint32_t ID ){ DBC_LRF_INI *sqliteDBC::getINIData( uint32_t lrfID ){ DBC_LRF_INI * tVal = NULL; - if(m_bIsConnected){ + if( m_bStoIsConnected ){ char tQBuf[CTEXT]; AAssoc *result; sprintf(tQBuf, "SELECT * FROM `lrf_ini_settings` WHERE `sensor_id`=%d", lrfID ); @@ -1273,9 +1609,9 @@ DBC_LRF_INI *sqliteDBC::getINIData( uint32_t lrfID ){ return tVal; }; -bool sqliteDBC::getLRFEventSessionStatus( uint32_t nodeID ){ +bool sqliteDBC::getEventSessionStatus( uint32_t nodeID ){ bool rv = false; - if(m_bIsConnected){ + if( m_bRepIsConnected ){ char tQBuf[CTEXT]; AAssoc *result; sprintf( tQBuf, "SELECT `evt_type` FROM `events` WHERE `node_id`=%d AND ( `evt_type`=%d OR `evt_type`=%d OR `evt_type`=%d ) ORDER BY `ts` DESC, `ts_ms` DESC LIMIT 1", nodeID, EVT_LRF_START_SESSION, EVT_LRF_END_SESSION_MA, EVT_LRF_END_SESSION_TO ); @@ -1301,7 +1637,7 @@ bool sqliteDBC::getLRFEventSessionStatus( uint32_t nodeID ){ DBC_LRF_DATA *sqliteDBC::getLRFData( uint32_t ID ){ DBC_LRF_DATA * tVal = NULL; - if(m_bIsConnected){ + if( m_bStoIsConnected ){ char tQBuf[CTEXT]; AAssoc *result; sprintf(tQBuf, "SELECT * FROM lrf_sensors WHERE `id`=%d", ID ); @@ -1451,7 +1787,7 @@ DBC_LRF_DATA *sqliteDBC::getLRFData( uint32_t ID ){ PLGS_2D_PARAMETERS sqliteDBC::getLRFDetectionProfile( uint32_t lrfID, uint8_t profileID, bool master ){ PLGS_2D_PARAMETERS retVal = NULL; - if(m_bIsConnected){ + if( m_bStoIsConnected ){ char tQBuf[CTEXT]; 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) ); @@ -1504,7 +1840,7 @@ PLGS_2D_PARAMETERS sqliteDBC::getLRFDetectionProfile( uint32_t lrfID, uint8_t pr uint8_t sqliteDBC::getLRFDataStatus( uint32_t ID ){ uint8_t RetVal = 0; - if(m_bIsConnected){ + if( m_bStoIsConnected ){ char tQBuf[CTEXT]; AAssoc *result; sprintf(tQBuf, "SELECT `data_status` FROM `lrf_sensors` WHERE `id`=%d", ID ); @@ -1529,7 +1865,7 @@ uint8_t sqliteDBC::getLRFDataStatus( uint32_t ID ){ }; uint32_t sqliteDBC::getLRFMaskID( uint32_t deviceID, uint8_t lrfID, uint8_t layer ){ uint32_t RetVal = 0; - if(m_bIsConnected){ + if( m_bStoIsConnected ){ 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 ); @@ -1555,7 +1891,7 @@ uint32_t sqliteDBC::getLRFMaskID( uint32_t deviceID, uint8_t lrfID, uint8_t laye uint8_t sqliteDBC::getLRFMasksStatus( uint32_t deviceID ){ uint8_t RetVal = 0; - if(m_bIsConnected){ + if( m_bStoIsConnected ){ char tQBuf[CTEXT]; AAssoc *result; sprintf(tQBuf, "SELECT `layer` FROM `lrf_masks` WHERE `sensor_id`=%d AND `status`='E'", deviceID ); @@ -1583,7 +1919,7 @@ uint8_t sqliteDBC::getLRFMasksStatus( uint32_t deviceID ){ DBC_LRF_UPLOAD_DATA *sqliteDBC::getLRFUploadData( uint32_t upID ){ DBC_LRF_UPLOAD_DATA *RetVal = NULL; - if(m_bIsConnected){ + if( m_bStoIsConnected ){ char tQBuf[CTEXT]; AAssoc *result; sprintf(tQBuf, "SELECT * FROM `lrf_uploads` WHERE `id`=%d", upID ); @@ -1620,7 +1956,7 @@ DBC_LRF_UPLOAD_DATA *sqliteDBC::getLRFUploadData( uint32_t upID ){ uint32_t sqliteDBC::getNodeAuxParam( uint32_t NodeID ){ uint32_t retVal = 0; - if(m_bIsConnected){ + if( m_bStoIsConnected ){ char tQBuf[CTEXT]; AAssoc *result; sprintf(tQBuf, "SELECT `aux_parameter` FROM `nodes` WHERE `id`=%d", NodeID ); @@ -1646,7 +1982,7 @@ uint32_t sqliteDBC::getNodeAuxParam( uint32_t NodeID ){ DBC_NODE_DATA *sqliteDBC::getNodeData( uint32_t ID ){ DBC_NODE_DATA * tVal = NULL; - if(m_bIsConnected){ + if( m_bStoIsConnected ){ char tQBuf[CTEXT]; AAssoc *result; sprintf(tQBuf, "SELECT * FROM `nodes` WHERE `id`=%d", ID ); @@ -1695,9 +2031,61 @@ DBC_NODE_DATA *sqliteDBC::getNodeData( uint32_t ID ){ return tVal; }; +uint32_t sqliteDBC::getNodeIdByTypeAndAux( uint8_t type, uint32_t aux_id ){ + uint32_t retVal = 0; + if( m_bStoIsConnected ){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT `id` FROM `nodes` WHERE `type`=%d AND `aux_id`=%d", type, aux_id); +#ifdef DEBUG_EXTRA + LOG(tQBuf); +#endif + result = m_pDataStorage->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("id"); + if( it != cArr->end() ){ + retVal = atoi( it->second.c_str() ); + }; + }; + }; + deleteResult( result ); + }; + return retVal; +}; + +CSTR sqliteDBC::getNodeName( uint32_t NodeID ){ + CSTR retVal = NULL; + if( m_bStoIsConnected ){ + char tQBuf[CTEXT]; + AAssoc *result; + sprintf(tQBuf, "SELECT `name` FROM `nodes` WHERE `id`=%d", NodeID ); +#ifdef DEBUG_EXTRA + LOG(tQBuf); +#endif + result = m_pDataStorage->Query( tQBuf ); + if( result!= NULL ) { + if( result->size() > 0 ) { + Assoc *cArr; + Assoc::iterator it; + cArr = result->at(0); + it = cArr->find("name"); + if( it != cArr->end() ){ + retVal = strdup( it->second.c_str() ); + }; + }; + }; + deleteResult( result ); + }; + return retVal; +}; + DBC_NET_IF_DATA *sqliteDBC::getNIF_Data( uint32_t nif_id ){ DBC_NET_IF_DATA * tVal = NULL; - if(m_bIsConnected){ + if( m_bStoIsConnected ){ char tQBuf[CTEXT]; AAssoc *result; sprintf(tQBuf, "SELECT `type`, `mode`, `device_name`, `mac`, `aux_id` FROM `network_interfaces` WHERE `id`=%d", nif_id ); @@ -1745,7 +2133,7 @@ DBC_NET_IF_DATA *sqliteDBC::getNIF_Data( uint32_t nif_id ){ uint32_t sqliteDBC::getNIF_ID( CSTR key ){ uint32_t tVal = 0; - if(m_bIsConnected){ + if( m_bStoIsConnected ){ char tQBuf[CTEXT]; AAssoc *result; sprintf(tQBuf, "SELECT id FROM `network_interfaces` WHERE `key`='%s'", key ); @@ -1773,7 +2161,7 @@ uint32_t sqliteDBC::getNIF_ID( CSTR key ){ uint32_t sqliteDBC::getNIF_IDbyDevice( CSTR device ){ uint32_t tVal = 0; - if(m_bIsConnected){ + if( m_bStoIsConnected ){ char tQBuf[CTEXT]; AAssoc *result; sprintf(tQBuf, "SELECT id FROM `network_interfaces` WHERE `device_name`='%s'", device ); @@ -1799,7 +2187,7 @@ uint32_t sqliteDBC::getNIF_IDbyDevice( CSTR device ){ uint32_t sqliteDBC::getNetworkInfrastructureID( uint32_t nif_id ){ uint32_t tVal = 0; - if(m_bIsConnected){ + if( m_bStoIsConnected ){ char tQBuf[CTEXT]; AAssoc *result; sprintf(tQBuf, "SELECT id FROM `network_infrastructure` WHERE `nif_id`=%d", nif_id ); @@ -1825,7 +2213,7 @@ uint32_t sqliteDBC::getNetworkInfrastructureID( uint32_t nif_id ){ DBC_RESOURCE_DATA *sqliteDBC::getResourceData( uint32_t ResourceID ){ DBC_RESOURCE_DATA *tVal = NULL; - if( m_bIsConnected ){ + if( m_bStoIsConnected ){ char tQBuf[CTEXT]; AAssoc *result; sprintf(tQBuf, "SELECT `node_id`, `type`, `aux_id`, `device` FROM `resources` WHERE `id`=%d", ResourceID ); @@ -1868,7 +2256,7 @@ DBC_RESOURCE_DATA *sqliteDBC::getResourceData( uint32_t ResourceID ){ uint32_t sqliteDBC::getResourceID( uint32_t NodeID, uint8_t type, uint32_t auxID ){ uint32_t RetVal = 0; - if(m_bIsConnected){ + if( m_bStoIsConnected ){ char tQBuf[CTEXT]; sprintf(tQBuf,"SELECT `id` FROM `resources` WHERE `node_id`=%d AND `type`=%d AND `aux_id`=%d", NodeID, type, auxID ); #ifdef DEBUG_ALL @@ -1894,7 +2282,7 @@ uint32_t sqliteDBC::getResourceID( uint32_t NodeID, uint8_t type, uint32_t auxID uint32_t sqliteDBC::getServerID( CSTR identity ){ uint32_t RetVal = 0; - if(m_bIsConnected){ + if( m_bStoIsConnected ){ char tQBuf[CTEXT]; sprintf(tQBuf,"SELECT `id` FROM `servers` WHERE `identity`='%s'", identity ); #ifdef DEBUG_ALL @@ -1920,7 +2308,7 @@ uint32_t sqliteDBC::getServerID( CSTR identity ){ uint32_t sqliteDBC::getServerNode( uint32_t SID ){ uint32_t RetVal = 0; - if(m_bIsConnected){ + if( m_bStoIsConnected ){ char tQBuf[CTEXT]; sprintf(tQBuf,"SELECT id FROM nodes WHERE `type`=0 AND `aux_id`=%d", SID ); #ifdef DEBUG_ALL @@ -1945,7 +2333,7 @@ uint32_t sqliteDBC::getServerNode( uint32_t SID ){ } DBC_TARGET_FLITER_DATA *sqliteDBC::getTargetFilterData( uint32_t ID ){ DBC_TARGET_FLITER_DATA * tVal = NULL; - if(m_bIsConnected){ + if( m_bStoIsConnected ){ char tQBuf[CTEXT]; AAssoc *result; sprintf(tQBuf, "SELECT * FROM `target_filters` WHERE `id`=%d", ID ); @@ -1984,7 +2372,7 @@ DBC_TARGET_FLITER_DATA *sqliteDBC::getTargetFilterData( uint32_t ID ){ TRAIN_FILTER_DATA *sqliteDBC::getTrainFilterData( uint32_t ID ){ TRAIN_FILTER_DATA * tVal = NULL; - if(m_bIsConnected){ + if( m_bStoIsConnected ){ char tQBuf[CTEXT]; AAssoc *result; sprintf(tQBuf, "SELECT * FROM `target_filter_train` WHERE `id`=%d", ID ); @@ -2042,7 +2430,7 @@ TRAIN_FILTER_DATA *sqliteDBC::getTrainFilterData( uint32_t ID ){ DBC_UART_DATA *sqliteDBC::getUartData( uint32_t UartID ){ DBC_UART_DATA *tVal = NULL; - if( m_bIsConnected ) { + if( m_bStoIsConnected ) { char tQBuf[MAX_PATH_LEN]; AAssoc *result; sprintf( tQBuf, "SELECT * FROM uart_settings WHERE id = %d", UartID ); @@ -2087,7 +2475,7 @@ DBC_UART_DATA *sqliteDBC::getUartData( uint32_t UartID ){ uint32_t sqliteDBC::getUartID( uint32_t NodeID, uint8_t Type, CSTR path ){ uint32_t RetVal = 0; - if(m_bIsConnected){ + if( m_bStoIsConnected ){ char tQBuf[CTEXT]; sprintf(tQBuf,"SELECT `id` FROM `uart_settings` WHERE `node_id`=%d AND `type`=%d AND `path`='%s' ", NodeID, Type, path ); #ifdef DEBUG_ALL @@ -2113,7 +2501,7 @@ uint32_t sqliteDBC::getUartID( uint32_t NodeID, uint8_t Type, CSTR path ){ uint32_t sqliteDBC::getWiFi_ID( uint32_t nif_id ){ uint32_t tVal = 0; - if(m_bIsConnected){ + if( m_bStoIsConnected ){ char tQBuf[CTEXT]; AAssoc *result; sprintf(tQBuf, "SELECT `id` FROM `wifis` WHERE `nif_id`=%d", nif_id ); @@ -2139,7 +2527,7 @@ uint32_t sqliteDBC::getWiFi_ID( uint32_t nif_id ){ DBC_INT_LIST *sqliteDBC::listFilters( uint32_t ServerID ){ DBC_INT_LIST * tVal = NULL; - if(m_bIsConnected){ + if( m_bStoIsConnected ){ char tQBuf[CTEXT]; AAssoc *result; sprintf(tQBuf, "SELECT `id` FROM `target_filters` WHERE `enabled`=1" ); @@ -2170,7 +2558,7 @@ DBC_INT_LIST *sqliteDBC::listFilters( uint32_t ServerID ){ DBC_INT_LIST *sqliteDBC::listLRFUploads( uint32_t deviceID ){ DBC_INT_LIST * tVal = NULL; - if(m_bIsConnected){ + if( m_bStoIsConnected ){ char tQBuf[CTEXT]; AAssoc *result; sprintf(tQBuf, "SELECT `id` FROM `lrf_uploads` WHERE `status`=-1 AND `sensor_id`=%d", deviceID ); @@ -2201,7 +2589,7 @@ DBC_INT_LIST *sqliteDBC::listLRFUploads( uint32_t deviceID ){ DBC_INT_LIST *sqliteDBC::listMediaStreams( uint32_t SiteId, uint8_t listMode ){ DBC_INT_LIST * tVal = NULL; - if(m_bIsConnected){ + if( m_bStoIsConnected ){ char tQBuf[CTEXT]; AAssoc *result; switch( listMode ){ @@ -2241,7 +2629,7 @@ DBC_INT_LIST *sqliteDBC::listMediaStreams( uint32_t SiteId, uint8_t listMode ){ DBC_INT_LIST *sqliteDBC::listModules(){ DBC_INT_LIST * tVal = NULL; - if(m_bIsConnected){ + if( m_bStoIsConnected ){ AAssoc *result; result = m_pDataStorage->Query( "SELECT `id` FROM `modules` WHERE `enabled`=1" ); if( result!= NULL ) { @@ -2266,18 +2654,18 @@ DBC_INT_LIST *sqliteDBC::listModules(){ }; DBC_INT_LIST *sqliteDBC::listNewModules( DBC_INT_LIST * old_ids ){ - DBC_INT_LIST * tVal = NULL; - char tParam[CTEXT]; - //memset( tParam, 0, CTEXT ); - sprintf(tParam,"0"); - if( old_ids != NULL ) { - char tBuffer[CTEXT]; - for(int i = 0; i< old_ids->size(); i++ ) { - sprintf( tBuffer, "%s,%d", tParam, old_ids->at(i) ); - strncpy( tParam, tBuffer, CTEXT ); + DBC_INT_LIST * tVal = NULL; + if( m_bStoIsConnected ){ + char tParam[CTEXT]; + //memset( tParam, 0, CTEXT ); + sprintf(tParam,"0"); + if( old_ids != NULL ) { + char tBuffer[CTEXT]; + for(int i = 0; i< old_ids->size(); i++ ) { + sprintf( tBuffer, "%s,%d", tParam, old_ids->at(i) ); + strncpy( tParam, tBuffer, CTEXT ); + }; }; - }; - if(m_bIsConnected){ char tQBuf[CTEXT]; AAssoc *result; sprintf(tQBuf, "SELECT `id` FROM `modules` WHERE `enabled`=1 AND `id` NOT IN (%s)", tParam ); @@ -2307,18 +2695,18 @@ DBC_INT_LIST *sqliteDBC::listNewModules( DBC_INT_LIST * old_ids ){ }; DBC_INT_LIST *sqliteDBC::listNewNodes( DBC_INT_LIST * old_ids ){ - DBC_INT_LIST * tVal = NULL; - char tParam[CTEXT]; - //memset( tParam, 0, CTEXT ); - sprintf(tParam,"0"); - if( old_ids != NULL ) { - char tBuffer[CTEXT]; - for(int i = 0; i< old_ids->size(); i++ ) { - sprintf( tBuffer, "%s,%d", tParam, old_ids->at(i) ); - strncpy( tParam, tBuffer, CTEXT ); + DBC_INT_LIST * tVal = NULL; + if( m_bStoIsConnected ){ + char tParam[CTEXT]; + //memset( tParam, 0, CTEXT ); + sprintf(tParam,"0"); + if( old_ids != NULL ) { + char tBuffer[CTEXT]; + for(int i = 0; i< old_ids->size(); i++ ) { + sprintf( tBuffer, "%s,%d", tParam, old_ids->at(i) ); + strncpy( tParam, tBuffer, CTEXT ); + }; }; - }; - if( m_bIsConnected ){ char tQBuf[CTEXT]; AAssoc *result; sprintf(tQBuf, "SELECT id FROM nodes WHERE `type` > 0 AND `enable`=1 AND `id` NOT IN(%s)", tParam ); @@ -2349,7 +2737,7 @@ DBC_INT_LIST *sqliteDBC::listNewNodes( DBC_INT_LIST * old_ids ){ DBC_INT_LIST *sqliteDBC::listNodes( bool all ){ DBC_INT_LIST * tVal = NULL; - if( m_bIsConnected ){ + if( m_bStoIsConnected ){ char tQBuf[1024]; AAssoc *result; if( all ) { @@ -2384,7 +2772,7 @@ DBC_INT_LIST *sqliteDBC::listNodes( bool all ){ DBC_INT_LIST *sqliteDBC::listResources( uint32_t NodeID ){ DBC_INT_LIST * tVal = NULL; - if(m_bIsConnected){ + if( m_bStoIsConnected ){ char tQBuf[CTEXT]; AAssoc *result; if ( NodeID == 0 ) NodeID = m_nServerNodeID; @@ -2415,7 +2803,7 @@ DBC_INT_LIST *sqliteDBC::listResources( uint32_t NodeID ){ }; void sqliteDBC::registerServer( uint32_t SiteID, CSTR identity, int PID, uint32_t *ServID, uint32_t *ServNode ){ - if( m_bIsConnected ){ + if( m_bStoIsConnected ){ m_nSiteID = SiteID; char tQBuf[MAX_PATH_LEN]; @@ -2492,7 +2880,7 @@ void sqliteDBC::registerServer( uint32_t SiteID, CSTR identity, int PID, uint32_ }; bool sqliteDBC::setLRFDataStatus( uint32_t lrfID, uint8_t ST ){ - if( m_bIsConnected ) { + if( m_bStoIsConnected ) { char tQBuf[MAX_PATH_LEN]; sprintf( tQBuf, "UPDATE `lrf_sensors` SET `data_status`=%d WHERE `id`=%d", ST, lrfID ); #ifdef DEBUG @@ -2505,7 +2893,7 @@ bool sqliteDBC::setLRFDataStatus( uint32_t lrfID, uint8_t ST ){ }; bool sqliteDBC::setLRFDetectionProfile( uint32_t lrfID, uint8_t profileID ){ - if( m_bIsConnected ) { + if( m_bStoIsConnected ) { char tQBuf[MAX_PATH_LEN]; sprintf( tQBuf, "UPDATE `lrf_sensors` SET `detection_profile_id`=%d WHERE `id`=%d", profileID, lrfID ); #ifdef DEBUG_ALL @@ -2518,7 +2906,7 @@ bool sqliteDBC::setLRFDetectionProfile( uint32_t lrfID, uint8_t profileID ){ }; bool sqliteDBC::setLRFMaskStatus( uint32_t maskID, bool status ){ - if( m_bIsConnected ) { + if( m_bStoIsConnected ) { char tQBuf[MAX_PATH_LEN]; char S[2]; if (status ) { @@ -2539,7 +2927,7 @@ bool sqliteDBC::setLRFMaskStatus( uint32_t maskID, bool status ){ }; bool sqliteDBC::setLRFAltSerial( uint32_t lrfID, CSTR Serial ){ - if( m_bIsConnected ) { + if( m_bStoIsConnected ) { char tQBuf[MAX_PATH_LEN]; sprintf( tQBuf, "UPDATE `lrf_sensors` SET `alt_serial`='%s' WHERE `id`=%d", Serial, lrfID ); #ifdef DEBUG_ALL @@ -2552,7 +2940,7 @@ bool sqliteDBC::setLRFAltSerial( uint32_t lrfID, CSTR Serial ){ }; bool sqliteDBC::setLRFAltVerison( uint32_t lrfID, CSTR version ){ - if( m_bIsConnected ) { + if( m_bStoIsConnected ) { char tQBuf[MAX_PATH_LEN]; sprintf( tQBuf, "UPDATE `lrf_sensors` SET `alt_version`='%s' WHERE `id`=%d", version, lrfID ); #ifdef DEBUG_ALL @@ -2565,7 +2953,7 @@ bool sqliteDBC::setLRFAltVerison( uint32_t lrfID, CSTR version ){ }; bool sqliteDBC::setNodeOffline( uint32_t NodeID ){ - if(m_bIsConnected){ + if( m_bStoIsConnected ){ char tQBuf[CTEXT]; if( NodeID ) { sprintf(tQBuf,"UPDATE nodes SET `online`=0 WHERE `id` = %d", NodeID ); @@ -2585,7 +2973,7 @@ bool sqliteDBC::setNodeOffline( uint32_t NodeID ){ }; bool sqliteDBC::setNodeOnline( uint32_t NodeID, uint8_t status ){ - if(m_bIsConnected){ + if( m_bStoIsConnected ){ char tQBuf[CTEXT]; if( NodeID ) { sprintf(tQBuf,"UPDATE `nodes` SET `online`=%d WHERE `id`=%d", status, NodeID ); @@ -2604,7 +2992,7 @@ bool sqliteDBC::setNodeOnline( uint32_t NodeID, uint8_t status ){ return false; }; bool sqliteDBC::setRessourceActive( uint32_t RessourceID, bool Status ){ - if(m_bIsConnected){ + if( m_bStoIsConnected ){ char tQBuf[CTEXT]; if( RessourceID ) { sprintf(tQBuf,"UPDATE `resources` SET `active`=%d WHERE `id`=%d", Status, RessourceID ); @@ -2619,7 +3007,7 @@ bool sqliteDBC::setRessourceActive( uint32_t RessourceID, bool Status ){ }; bool sqliteDBC::setStreamValid( uint32_t streamID, bool status ){ - if( m_bIsConnected ) { + if( m_bStoIsConnected ) { char tQBuf[MAX_PATH_LEN]; if ( status ) { sprintf(tQBuf, "UPDATE `media_streams` SET `valid`=1 WHERE `id`=%d", streamID); @@ -2636,7 +3024,7 @@ bool sqliteDBC::setStreamValid( uint32_t streamID, bool status ){ }; void sqliteDBC::unregisterServer( void ){ - if( m_bIsConnected ) { + if( m_bStoIsConnected ) { char tQBuf[MAX_PATH_LEN]; sprintf(tQBuf,"UPDATE `cameras` SET `online`=0" ); #ifdef DEBUG_ALL @@ -2654,7 +3042,7 @@ void sqliteDBC::unregisterServer( void ){ }; bool sqliteDBC::updateSystemInfo( DBC_SYS_INFO *ptr ){ - if( m_bIsConnected ) { + if( m_bStoIsConnected ) { char tQBuf[MAX_PATH_LEN]; sprintf(tQBuf, "UPDATE `system_props` SET `os_info`='%s', `hw_info`='%s' WHERE `id`=%d", ptr->OS_INFO, @@ -2671,7 +3059,7 @@ bool sqliteDBC::updateSystemInfo( DBC_SYS_INFO *ptr ){ }; bool sqliteDBC::fillShadow2D( uint32_t ID, SHADOW & SH ){ - if( m_bIsConnected ){ + if( m_bStoIsConnected ){ 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 ); @@ -2741,7 +3129,7 @@ bool sqliteDBC::fillShadow2D( uint32_t ID, SHADOW & SH ){ bool sqliteDBC::getAppDebugMode(){ bool rVal = false; - if(m_bIsConnected){ + if( m_bStoIsConnected ){ char tQBuf[CTEXT]; AAssoc *result; sprintf(tQBuf, "SELECT `work_mode` FROM `system_props` WHERE `id`=1" ); @@ -2767,7 +3155,7 @@ bool sqliteDBC::getAppDebugMode(){ DBC_CAM_DATA *sqliteDBC::getCamData( uint32_t ID ){ DBC_CAM_DATA *tVal = NULL; - if(m_bIsConnected){ + if( m_bStoIsConnected ){ char tQBuf[CTEXT]; AAssoc *result; sprintf(tQBuf, "SELECT * FROM cameras WHERE `id`=%d", ID ); @@ -2963,7 +3351,7 @@ DBC_CAM_DATA *sqliteDBC::getCamData( uint32_t ID ){ uint32_t sqliteDBC::getCamId( CSTR UUID ){ uint32_t RetVal = 0; - if(m_bIsConnected){ + if( m_bStoIsConnected ){ char tQBuf[CTEXT]; AAssoc *result; sprintf(tQBuf, "SELECT `id` FROM `cameras` WHERE `uuid`='%s'", UUID ); @@ -2995,7 +3383,7 @@ CSTR sqliteDBC::getDataParam( uint8_t pid ){ }; bool sqliteDBC::updateIPCam( uint32_t CamID, CSTR Addr ){ - if(m_bIsConnected) { + if( m_bStoIsConnected ) { char tQBuf[MAX_PATH_LEN]; char tIpBuf[CTEXT]; char *tPos; @@ -3059,7 +3447,7 @@ bool sqliteDBC::updateIPCam( uint32_t CamID, CSTR Addr ){ }; bool sqliteDBC::updateCamOnlineStatus( uint32_t camID, bool online ){ - if(m_bIsConnected) { + if( m_bStoIsConnected ) { char tQBuf[MAX_PATH_LEN]; if ( online ) { sprintf( tQBuf, "UPDATE `cameras` SET `online`=1 WHERE `id`=%d", camID ); @@ -3079,7 +3467,7 @@ bool sqliteDBC::updateCamOnlineStatus( uint32_t camID, bool online ){ }; bool sqliteDBC::updateIPCam( CSTR uuid, CSTR Addr ){ - if(m_bIsConnected) { + if( m_bStoIsConnected ) { uint32_t cID = getCamId( uuid ); if ( cID ) { return updateIPCam( cID, Addr ); @@ -3089,7 +3477,7 @@ bool sqliteDBC::updateIPCam( CSTR uuid, CSTR Addr ){ }; bool sqliteDBC::updateLocalCam( CSTR uuid ){ - if(m_bIsConnected) { + if( m_bStoIsConnected ) { uint32_t cID = getCamId( uuid ); if ( cID ) { return updateLocalCam( cID ); @@ -3099,7 +3487,7 @@ bool sqliteDBC::updateLocalCam( CSTR uuid ){ }; bool sqliteDBC::updateLocalCam( uint32_t CamID ){ - if(m_bIsConnected) { + if( m_bStoIsConnected ) { char tQBuf[MAX_PATH_LEN]; sprintf(tQBuf,"UPDATE cameras SET `online`=1 WHERE `id`=%d", CamID ); #ifdef DEBUG @@ -3117,7 +3505,7 @@ bool sqliteDBC::updateLocalCam( uint32_t CamID ){ }; bool sqliteDBC::updateLRFComStat( uint32_t lrfID, uint32_t ErrorPerMinute ){ - if( m_bIsConnected ) { + if( m_bStoIsConnected ) { char tQBuf[MAX_PATH_LEN]; sprintf( tQBuf, "UPDATE `lrf_sensors` SET `com_epm`=%d WHERE `id`=%d", ErrorPerMinute, lrfID ); #ifdef DEBUG_ALL @@ -3130,7 +3518,7 @@ bool sqliteDBC::updateLRFComStat( uint32_t lrfID, uint32_t ErrorPerMinute ){ }; bool sqliteDBC::updateLRFFrozenStatus( uint32_t lrfID, bool FFT, bool SFT ){ - if( m_bIsConnected ) { + if( m_bStoIsConnected ) { char tQBuf[MAX_PATH_LEN]; sprintf(tQBuf, "UPDATE `lrf_ini_settings` SET `FREEZ_FIRST_TH`=%d, `SAVE_FIRST_TH`=%d WHERE `sensor_id`=%d", FFT, SFT, lrfID ); #ifdef DEBUG @@ -3143,10 +3531,10 @@ bool sqliteDBC::updateLRFFrozenStatus( uint32_t lrfID, bool FFT, bool SFT ){ }; bool sqliteDBC::updateLRFDetectionProfile( uint32_t lrfID, uint8_t profileID, bool master, uint16_t nOrder, uint16_t nOffset, uint16_t nDelta, uint16_t nWidth, uint16_t nFlip, uint16_t nSun, uint8_t bSST, uint32_t GP, uint32_t spikes ){ - if( m_bIsConnected ) { + if( m_bStoIsConnected ) { char tQBuf[MAX_PATH_LEN]; if( master ) { - sprintf( tQBuf, "UPDATE INTO `lrf_detection_profiles`(`aux_id`,`profile_id`,`master`,`order`,`offset`,`delta`,`flip`,`width`,`sst`,`sun`,`gp`,`spikes`) VALUES(%d,%d,1,%d,%d,%d,%d,%d,%d,%d,%d,%d)ON CONFLICT(`aux_id`,`lrf_id`,`master`) DO UPDATE SET `order`=%d, `offset`=%d, `delta`=%d, `flip`=%d, `width`=%d, `sst`=%d, `sun`=%d, `gp`=%d, `spikes`=%d", + sprintf( tQBuf, "INSERT INTO `lrf_detection_profiles`(`aux_id`,`profile_id`,`master`,`order`,`offset`,`delta`,`flip`,`width`,`sst`,`sun`,`gp`,`spikes`) VALUES(%d,%d,1,%d,%d,%d,%d,%d,%d,%d,%d,%d)ON CONFLICT(`aux_id`,`lrf_id`,`master`) DO UPDATE SET `order`=%d, `offset`=%d, `delta`=%d, `flip`=%d, `width`=%d, `sst`=%d, `sun`=%d, `gp`=%d, `spikes`=%d", lrfID, profileID, nOrder, @@ -3200,7 +3588,7 @@ bool sqliteDBC::updateLRFDetectionProfile( uint32_t lrfID, uint8_t profileID, bo }; bool sqliteDBC::updateLRFSerial( uint32_t lrfID, CSTR Serial ){ - if( m_bIsConnected ) { + if( m_bStoIsConnected ) { char tQBuf[MAX_PATH_LEN]; CSTR tES = m_pDataStorage->escapeString( Serial ); if( tES ) { @@ -3217,7 +3605,7 @@ bool sqliteDBC::updateLRFSerial( uint32_t lrfID, CSTR Serial ){ }; bool sqliteDBC::updateLRFUpload( uint32_t id, uint8_t status ){ - if( m_bIsConnected ) { + if( m_bStoIsConnected ) { char tQBuf[MAX_PATH_LEN]; sprintf( tQBuf, "UPDATE `lrf_uploads` SET `status`=%d WHERE `id`=%d", status, id ); #ifdef DEBUG_ALL @@ -3230,7 +3618,7 @@ bool sqliteDBC::updateLRFUpload( uint32_t id, uint8_t status ){ }; bool sqliteDBC::updateLRFUnfinishedUploads( uint32_t deviceID ){ - if( m_bIsConnected ) { + if( m_bStoIsConnected ) { char tQBuf[MAX_PATH_LEN]; sprintf( tQBuf, "UPDATE `lrf_uploads` SET `status`=-1 WHERE `sensor_id`=%d AND `status` < 101 ", deviceID ); #ifdef DEBUG_ALL @@ -3243,7 +3631,7 @@ bool sqliteDBC::updateLRFUnfinishedUploads( uint32_t deviceID ){ }; bool sqliteDBC::updateLRFVerison( uint32_t lrfID, CSTR version ){ - if( m_bIsConnected ) { + if( m_bStoIsConnected ) { char tQBuf[MAX_PATH_LEN]; CSTR tES = m_pDataStorage->escapeString( version ); if( tES ) { @@ -3260,7 +3648,7 @@ bool sqliteDBC::updateLRFVerison( uint32_t lrfID, CSTR version ){ }; bool sqliteDBC::updateServerIdentity( uint32_t m_nServerID, CSTR m_sIdentity ){ - if( m_bIsConnected ) { + if( m_bStoIsConnected ) { char tQBuf[MAX_PATH_LEN]; CSTR tES = m_pDataStorage->escapeString( m_sIdentity ); if( tES ) { diff --git a/lib/App/common/SQLite_dataBinder.h b/lib/App/common/SQLite_dataBinder.h index 0523208b..a73029f9 100644 --- a/lib/App/common/SQLite_dataBinder.h +++ b/lib/App/common/SQLite_dataBinder.h @@ -11,7 +11,25 @@ #define DB_SHMEM_POINT "/dev/shm/argus" +typedef struct S_REPORT_DIRINFO{ + char YEAR[5]; + char MONTH[3]; + char DAY[3]; + time_t ts; +}REPORT_DIRINFO; +#ifndef STORAGE_DIR_MODE + #define STORAGE_DIR_MODE 0x1F5 //f disabled write by others +#endif +#ifndef STORAGE_FILE_MODE + #define STORAGE_FILE_MODE 0x1B4 //6 +#endif + +#define DB_FILE_MODE 0x1B4 + +#define SESSION_CONTINUE 0x00 +#define SESSION_START 0x01 +#define SESSION_END 0x02 class sqliteDBC: public dataBinder { private: basicLogCollection * m_pLog; @@ -19,23 +37,43 @@ class sqliteDBC: public dataBinder { SQLite_Connector * m_pDataStorage; SQLite_Connector * m_pDataMemory; SQLite_Connector * m_pDataReports; - bool m_bIsConnected; + SQLite_Connector * m_pDataStatistics; + + bool m_bStoIsConnected; + bool m_bMemIsConnected; + bool m_bRepIsConnected; + bool m_bStaIsConnected; + bool m_bStaIsCreated; + bool m_bLastEventWasClosed; + bool m_bRecreateMemStructures; char m_pDbFile[CLOG]; char m_pDbMemory[CLOG]; + char m_pDbReportBase[CLOG]; char m_pDbReport[CLOG]; + char m_pDbStat[CLOG]; char m_pDbUsername[CLOG]; char m_pDbPassword[CLOG]; char m_pDbDatabase[CLOG]; - + + char web_access_user[64]; + char web_access_group[64]; + + REPORT_DIRINFO m_sCRepInfo; + REPORT_DIRINFO m_sPRepInfo; uint32_t m_nSiteID; uint32_t m_nServerID; uint32_t m_nServerNodeID; void initMemDB( uint32_t sid = 1 ); - + uint32_t getTsFromRDF( REPORT_DIRINFO &RDF ); + void fillRDF( uint32_t ts, REPORT_DIRINFO &RDF ); + void updateStats( bool evt = true, bool video = false, uint8_t ses_status = SESSION_CONTINUE ); + bool checkRDFDir( CSTR basePath, REPORT_DIRINFO &RDF ); + static sqliteDBC * _instance; explicit sqliteDBC( config_setting_t * Settings ); + public: static sqliteDBC * getInstance( config_setting_t * Settings = NULL ); virtual ~sqliteDBC(); @@ -74,9 +112,10 @@ class sqliteDBC: public dataBinder { virtual bool getAppDebugMode(); virtual DBC_CAM_DATA * getCamData( uint32_t CamID ); virtual uint32_t getCamId( CSTR UUID ); + virtual CSTR getCurrentReportDir( void ); virtual DBC_MODULE_EMBED_VIDEO_DATA * getEmbedVideoData( uint32_t ID ); virtual DBC_LRF_INI * getINIData( uint32_t lrfID ); - virtual bool getLRFEventSessionStatus( uint32_t nodeID ); + virtual bool getEventSessionStatus( uint32_t nodeID ); virtual DBC_LRF_DATA * getLRFData( uint32_t ID ); virtual uint8_t getLRFDataStatus( uint32_t ID ); virtual PLGS_2D_PARAMETERS getLRFDetectionProfile( uint32_t lrfID, uint8_t profileID, bool master ); @@ -93,6 +132,8 @@ class sqliteDBC: public dataBinder { virtual uint32_t getNetworkInfrastructureID( uint32_t nif_id ); virtual uint32_t getNodeAuxParam( uint32_t NodeID ); virtual DBC_NODE_DATA * getNodeData( uint32_t ID ); + virtual uint32_t getNodeIdByTypeAndAux( uint8_t type, uint32_t aux_id ); + virtual CSTR getNodeName( uint32_t NodeID ); virtual DBC_PUSHED_CMD * getNodePushedCMD( uint32_t NodeID ); virtual DBC_RESOURCE_DATA * getResourceData( uint32_t ResourceID ); virtual uint32_t getResourceID( uint32_t NodeID, uint8_t type, uint32_t auxID ); diff --git a/lib/App/common/dataBinder.h b/lib/App/common/dataBinder.h index 6d06a462..f160a40f 100644 --- a/lib/App/common/dataBinder.h +++ b/lib/App/common/dataBinder.h @@ -79,6 +79,7 @@ class dataBinder{ virtual bool getConnectionStatus(void){return false;}; virtual DBC_CAP_DATA * getCamCapPictureData( uint32_t PicID ){ return NULL;}; + virtual CSTR getCurrentReportDir( void ){ return NULL; }; virtual DBC_EVT_RECORD * getEventByUUID( CSTR UUID ){ return NULL;}; virtual DBC_MODULE_EMBED_VIDEO_DATA * getEmbedVideoData( uint32_t ID ){ return NULL;}; virtual DBC_FH_DATA * getFlyHunterData( uint32_t ID ){ return NULL;}; @@ -86,7 +87,7 @@ class dataBinder{ virtual KAFKA_TEMPLATE * getKafkaTemplateForEvent( uint32_t ModuleID, uint32_t ClassID, uint32_t EventID ){ return NULL;}; //virtual bool getLastEvents( vectorEventRecords &VR, uint32_t tss, uint32_t tsms ); virtual DBC_LRF_INI * getINIData( uint32_t lrfID ){ return NULL; }; - virtual bool getLRFEventSessionStatus( uint32_t nodeID ){ return false; }; + virtual bool getEventSessionStatus( uint32_t nodeID ){ return false; }; virtual DBC_LRF_DATA * getLRFData( uint32_t ID ){ return NULL;}; virtual uint8_t getLRFDataStatus( uint32_t ID ){ return 0;}; virtual PLGS_2D_PARAMETERS getLRFDetectionProfile( uint32_t lrfID, uint8_t profileID, bool master ){ return NULL;}; @@ -103,17 +104,21 @@ class dataBinder{ virtual DBC_MODULE_DATA * getModuleData( uint32_t ID ){ return NULL;}; //virtual * getModuleEveSettings( uint32_t ID ){}; //virtual * getModuleSSDPSettings( uint32_t ID ){}; - virtual CSTR getNodeName( uint32_t NodeID ){ return NULL;}; + virtual uint32_t getNodeAuxParam( uint32_t NodeID ){ return 0;}; virtual uint32_t getNodeAuxID( uint32_t NodeID ){ return 0;}; + virtual DBC_NODE_DATA * getNodeData( uint32_t ID ){ return NULL;}; + virtual uint32_t getNodeIdByTypeAndAux( uint8_t type, uint32_t aux_id ){ return 0;}; + virtual CSTR getNodeName( uint32_t NodeID ){ return NULL;}; + virtual DBC_PUSHED_CMD * getNodePushedCMD( uint32_t NodeID ){ return NULL;}; virtual DBC_NETWORK_DATA * getNetworkData( uint32_t net_id ){ return NULL;}; virtual uint32_t getNetworkInfrastructureID( uint32_t nif_id ){ return 0;}; virtual DBC_NET_IF_DATA * getNIF_Data( uint32_t ID ){ return NULL;}; virtual uint32_t getNIF_ID( CSTR key ){ return 0;}; virtual uint32_t getNIF_IDbyDevice( CSTR device ){ return 0;}; - virtual DBC_NODE_DATA * getNodeData( uint32_t ID ){ return NULL;}; + - virtual DBC_PUSHED_CMD * getNodePushedCMD( uint32_t NodeID ){ return NULL;}; + virtual DBC_PUSHED_CMD * getActivePushedCMD( uint32_t NodeID ){ return NULL;}; virtual DBC_PUSHED_CMD * getPushedCMD( uint32_t CmdID ){ return NULL;}; diff --git a/lib/App/common/dataBinder_structures.h b/lib/App/common/dataBinder_structures.h index f0bd3cb9..f6328090 100644 --- a/lib/App/common/dataBinder_structures.h +++ b/lib/App/common/dataBinder_structures.h @@ -756,6 +756,13 @@ typedef struct S_DBC_LRF_INI{ uint16_t _SAVE_FIRST_TH; }DBC_LRF_INI; - +typedef struct S_DBC_REPORT_INFO{ + uint16_t year; + uint8_t month; + uint8_t day; + uint32_t evt_count; + uint32_t ets; + uint32_t sts; +}DBC_REPORT_INFO; #endif \ No newline at end of file diff --git a/lib/App/common/deviceNode2D.cpp b/lib/App/common/deviceNode2D.cpp index 17a44583..c404f981 100644 --- a/lib/App/common/deviceNode2D.cpp +++ b/lib/App/common/deviceNode2D.cpp @@ -56,7 +56,7 @@ void device2DSensor::cleanupDeviceStructures( void ){ //m_bSupportedFS = false; m_bDeviceIsSynced = false; m_nSleepTime = LGS_DEFAULT_SLEEP_TIME; -#ifdef DEBUG +#ifdef DEBUG_EXTRA LOG("Clean Basic Structures!"); #endif //m_eCurrentSequence = NO_SEQUENCE; @@ -83,11 +83,13 @@ void device2DSensor::cleanupDeviceStructures( void ){ //memset( &m_sOutFSData, 0, sizeof(FS_DATA_EX)); //if( m_pFSHelper ) m_pFSHelper->resetFS(); //ctrl_iteration() +#ifdef DEBUG_EXTRA LOG("cleanupDeviceStructures DONE"); +#endif }; void device2DSensor::cleanShadowStructs(){ -#ifdef DEBUG +#ifdef DEBUG_EXTRA LOG("Clean Shadow Structures!"); #endif if ( m_sShadow.pPolygones ) { @@ -106,7 +108,9 @@ void device2DSensor::cleanShadowStructs(){ m_bVersionStringValid = false; memset(&m_sShadow, 0, sizeof(SHADOW)); memset(&m_sShadowHelper, 0, sizeof(SHADOW_IO_HELPER)); +#ifdef DEBUG_EXTRA LOG("cleanShadowStructs DONE"); +#endif }; device2DSensor::~device2DSensor(){ @@ -184,11 +188,7 @@ bool device2DSensor::validate(){ void device2DSensor::connectMode(){ // Reset State - if ( getOWM() != LRF_WM_CONNECTION ) { - setWM( LRF_WM_CONNECTION ); - setWM( LRF_WM_CONNECTION ); - setStage( LRF_WS_INIT ); - }; + if( initWModeFunction( LRF_WM_CONNECTION ) ) broadcastDisconnected(); switch( getStage() ) { case LRF_WS_INIT:{ updateDataStatus( ARGUS_DS_DISCONNECTED ); @@ -253,24 +253,17 @@ void device2DSensor::connectMode(){ }; break; }; - case LRF_WS_WAIT:{ - if(( m_bTimeOutCounter-- )==0 ){ - LOG_ERROR("Connection TO!"); - RegisterCommError(); - setStage( LRF_WS_STAGE_1 ); - }; - DELAY_10MS( 10 ); // 100 ms - break; - }; - }; + case LRF_WS_WAIT: waitStateFunction( LRF_WS_STAGE_1 ); + }; }; void device2DSensor::handshakeMode(){ - LOG("HSHM"); + // LOG("HSHM"); // Reset State if ( getOWM() != LRF_WM_HANDSHAKE ) { setWM( LRF_WM_HANDSHAKE ); setWM( LRF_WM_HANDSHAKE ); + broadcastConnected(); setStage( LRF_WS_INIT ); }; @@ -307,32 +300,53 @@ void device2DSensor::handshakeMode(){ }; case LRF_WS_STAGE_3:{ m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; - if( !getShadowInfo() ) { + if( !getShadowInfo( m_sShadowHelper.m_bSequence ) ) { LOG_ERROR("Fall Back to Disconnected!"); setWM( LRF_WM_CONNECTION ); } else setStage( LRF_WS_WAIT ); break; }; - case LRF_WS_WAIT:{ - if(( m_bTimeOutCounter-- )==0 ){ - LOG_ERROR("Handshake TO!"); - RegisterCommError(); - setStage( LRF_WS_INIT ); - }; - DELAY_10MS( 10 ); // 100 ms - break; + case LRF_WS_WAIT: waitStateFunction(); + }; +}; + +void device2DSensor::waitStateFunction( LRF_WORK_STAGE boboStage ){ + if( m_bTimeOutCounter ){ + m_bTimeOutCounter--; + DELAY_10MS( LGS_DEFAULT_WS_TIME ); + } else { + if( m_bOpRetryCnt ){ +#ifdef DEBUG_EXTRA + LOG("COM ATTEMPT RECOVER"); +#endif + m_bOpRetryCnt--; + RegisterCommError( false ); + LRF_WORK_STAGE pS = getPrevStage(); + setStage( pS ); + m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + } else { + LOG_ERROR("Communication Wait State TO!"); + RegisterCommError( true ); + setStage( boboStage ); }; }; }; -void device2DSensor::readMode(){ - LOG("READ"); - // Reset State - if ( getOWM() != LRF_WM_SYNC_UP ) { - setWM( LRF_WM_SYNC_UP ); - setWM( LRF_WM_SYNC_UP ); +bool device2DSensor::initWModeFunction( uint8_t wm ){ + if( getOWM() != wm ) { + setWM( wm ); + setWM( wm ); setStage( LRF_WS_INIT ); + m_bOpRetryCnt = LGS_CMD_RETRY_COUNT; + return true; }; + return false; +}; + +void device2DSensor::readMode(){ + //LOG("READ"); + // Reset State + initWModeFunction( LRF_WM_SYNC_UP ); switch( getStage() ) { case LRF_WS_INIT:{ m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; @@ -360,7 +374,7 @@ void device2DSensor::readMode(){ }; case LRF_WS_STAGE_3:{ m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; - if( !getShadowInfo() ) { + if( !getShadowInfo( m_sShadowHelper.m_bSequence ) ) { LOG_ERROR("Fall Back to Disconnected!"); setWM( LRF_WM_CONNECTION ); } else setStage( LRF_WS_WAIT ); @@ -368,7 +382,7 @@ void device2DSensor::readMode(){ }; case LRF_WS_STAGE_4:{ m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; - if( !getShadowPoly( m_sShadowHelper.m_nCurrentPolygon ) ) { + if( !getShadowPoly( m_sShadowHelper.m_bSequence, m_sShadowHelper.m_nCurrentPolygon ) ) { LOG_ERROR("Fall Back to Disconnected!"); setWM( LRF_WM_CONNECTION ); } else setStage( LRF_WS_WAIT ); @@ -376,36 +390,25 @@ void device2DSensor::readMode(){ }; case LRF_WS_STAGE_5:{ m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; - if( !getShadowPolyPoint(m_sShadowHelper.m_nCurrentPolygon, m_sShadowHelper.m_nCurrentPoint) ) { + if( !getShadowPolyPoint( m_sShadowHelper.m_bSequence, m_sShadowHelper.m_nCurrentPolygon, m_sShadowHelper.m_nCurrentPoint ) ) { LOG_ERROR("Fall Back to Disconnected!"); setWM( LRF_WM_CONNECTION ); } else setStage( LRF_WS_WAIT ); break; }; - case LRF_WS_WAIT:{ - if(( m_bTimeOutCounter-- )==0 ){ - LOG_ERROR("Read TO!"); - RegisterCommError(); - setStage( LRF_WS_INIT ); - }; - DELAY_10MS( 10 ); - break; - }; + case LRF_WS_WAIT: waitStateFunction(); }; }; void device2DSensor::syncMode(){ - LOG("SYNC"); - // Reset State - if ( getOWM() != LRF_WM_SYNC_DOWN ) { - setWM( LRF_WM_SYNC_DOWN ); - setWM( LRF_WM_SYNC_DOWN ); - setStage( LRF_WS_INIT ); + //LOG("SYNC"); + // Reset State + if( initWModeFunction( LRF_WM_SYNC_DOWN ) ){ updateDataStatus( ARGUS_DS_BUSY ); memset( m_pTGENFILENAMES[0], 0, 33 ); memset( m_pTGENFILENAMES[1], 0, 33 ); memset( m_pTGENFILENAMES[2], 0, 33 ); - m_bOpRetryCnt = 3; + m_bOpRetryCnt = LGS_CMD_RETRY_COUNT; m_bTGENFILECNT = 0; m_bTGENFILE = 0; m_sGetFileTransfers.current = 0; @@ -528,7 +531,7 @@ void device2DSensor::syncMode(){ case LRF_WS_STAGE_1:{ //ANODE_WM_2D_SET_MASK_INFO m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER << 2; - if (!setShadowInfo( m_sShadow )) { + if (!setShadowInfo( m_sShadowHelper.m_bSequence, m_sShadow )) { LOG_ERROR("Fall Back to Disconnected!"); setWM( LRF_WM_CONNECTION ); } else setStage( LRF_WS_WAIT ); @@ -537,7 +540,7 @@ void device2DSensor::syncMode(){ case LRF_WS_STAGE_2:{ //ANODE_WM_2D_SET_SHADOW_POLY_INFO m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER << 2; - if(!setShadowPoly(m_sShadow, m_sShadowHelper.m_nCurrentPolygon)){ + if(!setShadowPoly( m_sShadowHelper.m_bSequence, m_sShadow, m_sShadowHelper.m_nCurrentPolygon)){ LOG_ERROR("Fall Back to Disconnected!"); setWM( LRF_WM_CONNECTION ); } else setStage( LRF_WS_WAIT ); @@ -546,7 +549,7 @@ void device2DSensor::syncMode(){ case LRF_WS_STAGE_3:{ //ANODE_WM_2D_SET_SHADOW_POLY_POINT m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER << 2; - if (!setShadowPolyPoint(m_sShadow, m_sShadowHelper.m_nCurrentPolygon, m_sShadowHelper.m_nCurrentPoint)) { + if (!setShadowPolyPoint( m_sShadowHelper.m_bSequence, m_sShadow, m_sShadowHelper.m_nCurrentPolygon, m_sShadowHelper.m_nCurrentPoint)) { LOG_ERROR("Fall Back to Disconnected!"); setWM( LRF_WM_CONNECTION ); } else setStage( LRF_WS_WAIT ); @@ -555,7 +558,7 @@ void device2DSensor::syncMode(){ case LRF_WS_STAGE_4:{ //ANODE_WM_2D_SET_SHADOW_RAY_LINE m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER << 2; - if (!setShadowRayLine( m_sShadow, m_sShadowHelper.m_nCurrentRayLine )) { + if (!setShadowRayLine( m_sShadowHelper.m_bSequence, m_sShadow, m_sShadowHelper.m_nCurrentRayLine )) { LOG_ERROR("Fall Back to Disconnected!"); setWM( LRF_WM_CONNECTION ); } else setStage( LRF_WS_WAIT ); @@ -564,7 +567,7 @@ void device2DSensor::syncMode(){ case LRF_WS_STAGE_5:{ //ANODE_WM_2D_SET_SHADOW_RAY m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER << 2; - if (!setShadowRay(m_sShadow, m_sShadowHelper.m_nCurrentRayLine, m_sShadowHelper.m_nCurrentRay )) { + if (!setShadowRay( m_sShadowHelper.m_bSequence, m_sShadow, m_sShadowHelper.m_nCurrentRayLine, m_sShadowHelper.m_nCurrentRay )) { LOG_ERROR("Fall Back to Disconnected!"); setWM( LRF_WM_CONNECTION ); } else setStage( LRF_WS_WAIT ); @@ -573,7 +576,7 @@ void device2DSensor::syncMode(){ case LRF_WS_STAGE_6:{ //ANODE_WM_2D_SET_SHADOW_DONE m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER << 2; - if (!setShadowDone()) { + if (!setShadowDone( m_sShadowHelper.m_bSequence )) { LOG_ERROR("Fall Back to Disconnected!"); setWM( LRF_WM_CONNECTION ); } else setStage( LRF_WS_WAIT ); @@ -769,41 +772,19 @@ void device2DSensor::syncMode(){ } else setStage( LRF_WS_WAIT ); break; }; - case LRF_WS_WAIT:{ - if(( m_bTimeOutCounter-- )==0 ){ - RegisterCommError(); - LOG_ERROR("Sync TO!"); - if ( m_bOpRetryCnt ) { - m_bOpRetryCnt--; - uint8_t tSTG = (uint8_t)getPrevStage(); - if ( tSTG > 1 ) { - setStage( (LRF_WORK_STAGE) tSTG ); - } else { - setStage( LRF_WS_INIT ); - }; - } else { - setWM( LRF_WM_IDLE ); - }; - }; - DELAY_10MSW( 10 ); - break; - }; + case LRF_WS_WAIT: waitStateFunction(); }; }; void device2DSensor::save_ini(){ - LOG("Save HW ini"); - // Reset State - if ( getOWM() != LRF_WM_SAVE_HW ) { - setWM( LRF_WM_SAVE_HW ); - setWM( LRF_WM_SAVE_HW ); - setStage( LRF_WS_INIT ); + //LOG("Save HW ini"); + // Reset State + if( initWModeFunction( LRF_WM_SAVE_HW ) ){ updateDataStatus( ARGUS_DS_BUSY ); memset( m_pTGENFILENAMES[0], 0, 33 ); memset( m_pTGENFILENAMES[1], 0, 33 ); memset( m_pTGENFILENAMES[2], 0, 33 ); - m_bOpRetryCnt = 3; m_bTGENFILECNT = 0; m_bTGENFILE = 0; m_sGetFileTransfers.current = 0; @@ -872,7 +853,7 @@ void device2DSensor::save_ini(){ m_bTGENFILECNT++; }; } else { - LOG("Gen File 1 Failure!"); + LOG_ERROR("Gen File 1 Failure!"); }; if( generateRestartFile( m_bTGENFILE ) ){ GETFILE_IO_HELPER *tH = NULL; @@ -894,7 +875,7 @@ void device2DSensor::save_ini(){ m_bTGENFILECNT++; }; } else { - LOG("Gen File 2 Failure!"); + LOG_ERROR("Gen File 2 Failure!"); }; }; setStage( LRF_WS_STAGE_9 ); @@ -1057,7 +1038,8 @@ void device2DSensor::save_ini(){ } else setStage( LRF_WS_WAIT ); break; }; - case LRF_WS_WAIT:{ + case LRF_WS_WAIT: waitStateFunction(); + /*{ if(( m_bTimeOutCounter-- )==0 ){ RegisterCommError(); LOG_ERROR("SaveINI TO!"); @@ -1072,10 +1054,9 @@ void device2DSensor::save_ini(){ } else { setWM( LRF_WM_IDLE ); }; - }; - DELAY_10MSW( 10 ); + } else DELAY_10MSW( 10 ); break; - }; + };*/ }; }; @@ -1084,13 +1065,9 @@ void device2DSensor::save_detection(){ }; void device2DSensor::save_masks(){ - LOG("Save Masks"); - // Reset State - if ( getOWM() != LRF_WM_SAVE_MASKS ) { - setWM( LRF_WM_SAVE_MASKS ); - setWM( LRF_WM_SAVE_MASKS ); - setStage( LRF_WS_INIT ); - m_bOpRetryCnt = 3; + //LOG("Save Masks"); + // Reset State + if( initWModeFunction( LRF_WM_SAVE_MASKS ) ){ updateDataStatus( ARGUS_DS_BUSY ); memset( m_pTGENFILENAMES[0], 0, 33 ); memset( m_pTGENFILENAMES[1], 0, 33 ); @@ -1165,7 +1142,7 @@ void device2DSensor::save_masks(){ case LRF_WS_STAGE_1:{ //ANODE_WM_2D_SET_MASK_INFO m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER << 2; - if (!setShadowInfo( m_sShadow )) { + if (!setShadowInfo( m_sShadowHelper.m_bSequence, m_sShadow )) { LOG_ERROR("Fall Back to Disconnected!"); setWM( LRF_WM_CONNECTION ); } else setStage( LRF_WS_WAIT ); @@ -1174,7 +1151,7 @@ void device2DSensor::save_masks(){ case LRF_WS_STAGE_2:{ //ANODE_WM_2D_SET_SHADOW_POLY_INFO m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER << 2; - if(!setShadowPoly(m_sShadow, m_sShadowHelper.m_nCurrentPolygon)){ + if(!setShadowPoly( m_sShadowHelper.m_bSequence, m_sShadow, m_sShadowHelper.m_nCurrentPolygon)){ LOG_ERROR("Fall Back to Disconnected!"); setWM( LRF_WM_CONNECTION ); } else setStage( LRF_WS_WAIT ); @@ -1183,7 +1160,7 @@ void device2DSensor::save_masks(){ case LRF_WS_STAGE_3:{ //ANODE_WM_2D_SET_SHADOW_POLY_POINT m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER << 2; - if (!setShadowPolyPoint(m_sShadow, m_sShadowHelper.m_nCurrentPolygon, m_sShadowHelper.m_nCurrentPoint)) { + if (!setShadowPolyPoint( m_sShadowHelper.m_bSequence, m_sShadow, m_sShadowHelper.m_nCurrentPolygon, m_sShadowHelper.m_nCurrentPoint)) { LOG_ERROR("Fall Back to Disconnected!"); setWM( LRF_WM_CONNECTION ); } else setStage( LRF_WS_WAIT ); @@ -1192,7 +1169,7 @@ void device2DSensor::save_masks(){ case LRF_WS_STAGE_4:{ //ANODE_WM_2D_SET_SHADOW_RAY_LINE m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER << 2; - if (!setShadowRayLine( m_sShadow, m_sShadowHelper.m_nCurrentRayLine )) { + if (!setShadowRayLine( m_sShadowHelper.m_bSequence, m_sShadow, m_sShadowHelper.m_nCurrentRayLine )) { LOG_ERROR("Fall Back to Disconnected!"); setWM( LRF_WM_CONNECTION ); } else setStage( LRF_WS_WAIT ); @@ -1201,7 +1178,7 @@ void device2DSensor::save_masks(){ case LRF_WS_STAGE_5:{ //ANODE_WM_2D_SET_SHADOW_RAY m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER << 2; - if (!setShadowRay(m_sShadow, m_sShadowHelper.m_nCurrentRayLine, m_sShadowHelper.m_nCurrentRay )) { + if (!setShadowRay( m_sShadowHelper.m_bSequence, m_sShadow, m_sShadowHelper.m_nCurrentRayLine, m_sShadowHelper.m_nCurrentRay )) { LOG_ERROR("Fall Back to Disconnected!"); setWM( LRF_WM_CONNECTION ); } else setStage( LRF_WS_WAIT ); @@ -1210,7 +1187,7 @@ void device2DSensor::save_masks(){ case LRF_WS_STAGE_6:{ //ANODE_WM_2D_SET_SHADOW_DONE m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER << 2; - if (!setShadowDone()) { + if (!setShadowDone( m_sShadowHelper.m_bSequence )) { LOG_ERROR("Fall Back to Disconnected!"); setWM( LRF_WM_CONNECTION ); } else setStage( LRF_WS_WAIT ); @@ -1219,7 +1196,7 @@ void device2DSensor::save_masks(){ case LRF_WS_STAGE_7: case LRF_WS_STAGE_8: case LRF_WS_STAGE_9:{ - LOG("Sending Update MZ!"); + //LOG("Sending Update MZ!"); //ANODE_WM_2D_SET_GETFILE_MODE if ( m_bActualDeviceWM != MODE_GETFILE ) { m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; @@ -1376,7 +1353,8 @@ void device2DSensor::save_masks(){ } else setStage( LRF_WS_WAIT ); break; }; - case LRF_WS_WAIT:{ + case LRF_WS_WAIT: waitStateFunction(); + /*{ if(( m_bTimeOutCounter-- )==0 ){ RegisterCommError(); LOG_ERROR("SaveMasks TO!"); @@ -1391,10 +1369,9 @@ void device2DSensor::save_masks(){ } else { setWM( LRF_WM_IDLE ); }; - }; - DELAY_10MSW( 10 ); + } else DELAY_10MSW( 10 ); break; - }; + };*/ }; }; @@ -1404,13 +1381,9 @@ void device2DSensor::save_eprom(){ void device2DSensor::getfileMode(){ - // Reset State - if ( getOWM() != LRF_WM_FILE ) { - setWM( LRF_WM_FILE ); - setWM( LRF_WM_FILE ); - setStage( LRF_WS_INIT ); - m_bOpRetryCnt = 3; - }; + //LOG("GETFILE"); + // Reset State + initWModeFunction( LRF_WM_FILE ); switch( getStage() ) { case LRF_WS_INIT:{ m_nCurrentAngle = 0; @@ -1553,7 +1526,8 @@ void device2DSensor::getfileMode(){ setWM( LRF_WM_IDLE ); break; }; - case LRF_WS_WAIT:{ + case LRF_WS_WAIT: waitStateFunction(); + /*{ if(( m_bTimeOutCounter-- )==0 ){ RegisterCommError(); LOG_ERROR("GetFile TO!"); @@ -1568,20 +1542,16 @@ void device2DSensor::getfileMode(){ } else { setWM( LRF_WM_IDLE ); }; - }; - DELAY_10MSW( 10 ); + } else DELAY_10MSW( 10 ); break; - }; + };*/ }; }; void device2DSensor::drawMode(){ - // Reset State - if ( getOWM() != LRF_WM_BORDER ) { - setWM( LRF_WM_BORDER ); - setWM( LRF_WM_BORDER ); - setStage( LRF_WS_INIT ); - }; + //LOG("DRAW"); + // Reset State + initWModeFunction( LRF_WM_BORDER ); switch( getStage() ) { case LRF_WS_INIT:{ m_nCurrentAngle = 0; @@ -1613,30 +1583,19 @@ void device2DSensor::drawMode(){ } else setWM( LRF_WM_IDLE ); break; }; - case LRF_WS_WAIT:{ - if(( m_bTimeOutCounter-- )==0 ){ - RegisterCommError(); - LOG_ERROR("Draw TO!"); - setStage( LRF_WS_INIT ); - }; - DELAY_10MSW( 10 ); - break; - }; + case LRF_WS_WAIT: waitStateFunction(); }; }; + void device2DSensor::maskMode(){ - LOG("MASKOP"); - if ( getOWM() != LRF_WM_STATUS_MASK ) { - setWM( LRF_WM_STATUS_MASK ); - setWM( LRF_WM_STATUS_MASK ); - setStage( LRF_WS_INIT ); + //LOG("MASKOP"); + if( initWModeFunction( LRF_WM_STATUS_MASK ) ){ m_bCurShadowMask = m_pDBC->getLRFMasksStatus( m_sLRF_DATA.id ); #ifdef DEBUG char tBuf[64]; sprintf( tBuf, "CMask: 0x%02X", m_bCurShadowMask ); LOG( tBuf ); #endif - m_bOpRetryCnt = 3; updateDataStatus( ARGUS_DS_BUSY ); memset( m_pTGENFILENAMES[0], 0, 33 ); memset( m_pTGENFILENAMES[1], 0, 33 ); @@ -1852,7 +1811,8 @@ void device2DSensor::maskMode(){ } else setStage( LRF_WS_WAIT ); break; }; - case LRF_WS_WAIT:{ + case LRF_WS_WAIT: waitStateFunction(); + /*{ if(( m_bTimeOutCounter-- )==0 ){ LOG_ERROR("MASKOP TO!"); RegisterCommError(); @@ -1867,23 +1827,18 @@ void device2DSensor::maskMode(){ } else { setWM( LRF_WM_IDLE ); }; - }; - DELAY_10MSW( 10 ); + } else DELAY_10MSW( 10 ); break; - }; + };*/ }; DELAY_10MS( 10 ); // 100 ms }; void device2DSensor::alarmMode(){ //LOG("ALRM"); - // Reset State - if ( getOWM() != LRF_WM_ALARM ) { - setWM( LRF_WM_ALARM ); - setWM( LRF_WM_ALARM ); - setStage( LRF_WS_INIT ); - if( m_sLRF_DATA.data_status!= ARGUS_DS_ALARMED ) updateDataStatus( ARGUS_DS_ALARMED ); - }; + //Reset State + if( initWModeFunction( LRF_WM_ALARM ) ) if( m_sLRF_DATA.data_status!= ARGUS_DS_ALARMED ) updateDataStatus( ARGUS_DS_ALARMED ); + switch( getStage() ) { case LRF_WS_INIT:{ if ( m_bActualDeviceWM != MODE_DETECTOR ) { @@ -1911,25 +1866,14 @@ void device2DSensor::alarmMode(){ //DELAY_10MS( 10 ); // 100 ms break; }; - case LRF_WS_WAIT:{ - if(( m_bTimeOutCounter-- )==0 ){ - LOG_ERROR("Handshake TO!"); - RegisterCommError(); - setStage( LRF_WS_INIT ); - }; - break; - }; - }; - DELAY_10MS( 10 ); // 100 ms + case LRF_WS_WAIT: waitStateFunction(); + }; }; + void device2DSensor::idleMode(){ //LOG("IDLE"); - // Reset State - if ( getOWM() != LRF_WM_IDLE ) { - setWM( LRF_WM_IDLE ); - setWM( LRF_WM_IDLE ); - setStage( LRF_WS_INIT ); - }; + //Reset State + initWModeFunction( LRF_WM_IDLE ); switch( getStage() ) { case LRF_WS_INIT:{ if ( m_bActualDeviceWM != MODE_DETECTOR ) { @@ -1956,16 +1900,8 @@ void device2DSensor::idleMode(){ setStage( LRF_WS_STAGE_1 ); break; }; - case LRF_WS_WAIT:{ - if(( m_bTimeOutCounter-- )==0 ){ - //LOG_ERROR("Idle TO!"); - RegisterCommError(); - setStage( LRF_WS_INIT ); - }; - break; - }; - }; - DELAY_10MS( 30 ); // 300 ms + case LRF_WS_WAIT: waitStateFunction(); + }; }; void device2DSensor::proceedDBCommands(){ @@ -2630,6 +2566,11 @@ bool device2DSensor::packetHandler( protocolPackage *Package ){ sprintf( tBuff, "Sub Size: %d", Package->m_pData[cIDX] ); LOG( tBuff ); #endif + EVENT_CONTAINER *bEVT = createBasicEvent( m_sNodeData.node_id, m_eEventClass, EVT_ERR_LRF_MAINTENANCE, NULL, NULL, NULL ); + if( bEVT != NULL ) { + m_pEventHeap->broadcast(bEVT); + }; + cIDX += 3; break; }; @@ -2639,6 +2580,11 @@ bool device2DSensor::packetHandler( protocolPackage *Package ){ sprintf( tBuff, "Sub Size: %d", Package->m_pData[cIDX] ); LOG( tBuff ); #endif + EVENT_CONTAINER *bEVT = createBasicEvent( m_sNodeData.node_id, m_eEventClass, EVT_ERR_LRF_TROUBLE, NULL, NULL, NULL ); + if( bEVT != NULL ) { + m_pEventHeap->broadcast(bEVT); + }; + cIDX += 4; break; }; @@ -2648,6 +2594,10 @@ bool device2DSensor::packetHandler( protocolPackage *Package ){ sprintf( tBuff, "Sub Size: %d", Package->m_pData[cIDX] ); LOG( tBuff ); #endif + EVENT_CONTAINER *bEVT = createBasicEvent( m_sNodeData.node_id, m_eEventClass, EVT_ERR_LRF_ANGLE, NULL, NULL, NULL ); + if( bEVT != NULL ) { + m_pEventHeap->broadcast(bEVT); + }; cIDX += 4; break; }; @@ -2697,6 +2647,11 @@ bool device2DSensor::packetHandler( protocolPackage *Package ){ sprintf( tBuff, "Sub Size: %d", Package->m_pData[cIDX] ); LOG( tBuff ); #endif + EVENT_CONTAINER *bEVT = createBasicEvent( m_sNodeData.node_id, m_eEventClass, EVT_LRF_VIS_CHANGED, NULL, NULL, NULL ); + if( bEVT != NULL ) { + m_pEventHeap->broadcast(bEVT); + }; + cIDX += 4; break; }; @@ -2762,7 +2717,7 @@ bool device2DSensor::packetHandler( protocolPackage *Package ){ break; }; case CMD_GET_HZ_DATA:{ - //HZ_PACKET tPack = (PHZ_PACKET) Package->m_pData + SUB_CMD_IDX; + //HZ_PACKET tPack = (PHZ_PACKET) Package->m_pData + SUB_CMD_IDX; switch( Package->m_pData[DATA_BEGIN_IDX] ) { case HZIT_EVT_GET_HEADER:{ HZ_EVT_GET_HEADER pC; @@ -2781,6 +2736,7 @@ bool device2DSensor::packetHandler( protocolPackage *Package ){ sprintf( tBuff, "Poly Cnt: %d Ray Cnt: %d Status: 0x%08X", pC.wPolygonCount, pC.wRayCount, pC.dwTypeOn ); LOG( tBuff ); #endif + m_sShadowHelper.m_bSequence = Package->m_pData[DATA_BEGIN_IDX+1]; if ( bCWM != LRF_WM_HANDSHAKE ) { LOG("Sync -> Shadow Info"); if (pC.wPolygonCount) { @@ -2817,6 +2773,7 @@ bool device2DSensor::packetHandler( protocolPackage *Package ){ case HZIT_EVT_GET_POLYGON:{ uint16_t wPointCount = Package->m_pData[DATA_BEGIN_IDX+4]; wPointCount = ( wPointCount << 8 ) | Package->m_pData[DATA_BEGIN_IDX+3]; + m_sShadowHelper.m_bSequence = Package->m_pData[DATA_BEGIN_IDX+1]; #ifdef DEBUG sprintf( tBuff, "Poly[%d] Info: Points %d type: %d", m_sShadowHelper.m_nCurrentPolygon, @@ -2865,7 +2822,9 @@ bool device2DSensor::packetHandler( protocolPackage *Package ){ LOG( tBuff ); #endif m_sShadowHelper.m_nCurrentPoint++; + m_sShadowHelper.m_bSequence = Package->m_pData[DATA_BEGIN_IDX+1]; if( m_sShadowHelper.m_nCurrentPoint < m_sShadow.pPolygones[m_sShadowHelper.m_nCurrentPolygon].wCount ) { + LOG("Back To Read Nex Poly Point!"); setStage( LRF_WS_STAGE_5 ); //setWM( ANODE_WM_2D_GET_SHADOW_POLY_POINT ); } else { @@ -2957,6 +2916,7 @@ bool device2DSensor::packetHandler( protocolPackage *Package ){ sprintf( tBuff,"Replay Set HZ Code: 0x%02X", Package->m_pData[DATA_BEGIN_IDX] ); LOG( tBuff ); #endif + m_sShadowHelper.m_bSequence = Package->m_pData[DATA_BEGIN_IDX+1]; switch( Package->m_pData[DATA_BEGIN_IDX] ) { case HZIT_EVT_SET_HEADER: LOG("Header OK"); diff --git a/lib/App/common/deviceNode2D.h b/lib/App/common/deviceNode2D.h index f3a10437..d922c7a2 100644 --- a/lib/App/common/deviceNode2D.h +++ b/lib/App/common/deviceNode2D.h @@ -22,8 +22,10 @@ #define LGS_DEFAULT_SLEEP_TIME 100 #define LGS_ALERT_SLEEP_TIME 10 -#define LGS_DEFAULT_TO_COUNTER 12 +#define LGS_DEFAULT_TO_COUNTER 10 //100ms +#define LGS_DEFAULT_WS_TIME 1 //10ms #define LGS_INITIAL_FLIPS 8 +#define LGS_CMD_RETRY_COUNT 3 typedef enum E_WORKING_STATE_LRF2D{ WS_2D_BEFORE_START = 0, @@ -83,6 +85,7 @@ typedef struct S_SHADOW_IO_HELPER{ uint16_t m_nCurrentPoint; uint16_t m_nCurrentRayLine; uint16_t m_nCurrentRay; + uint8_t m_bSequence; }SHADOW_IO_HELPER; typedef struct S_GETFILE_IO_HELPER{ @@ -184,6 +187,8 @@ class device2DSensor: public deviceNodeSensor, public protocolLGS_2D{ //COMMAND_SEQUENCE_TYPE m_eCurrentSequence; //uint8_t m_bSequenceStep; //bool runSequence( COMMAND_SEQUENCE_TYPE SequenceID ); + bool initWModeFunction( uint8_t wm ); + void waitStateFunction( LRF_WORK_STAGE boboStage = LRF_WS_INIT ); #ifdef DEBUG void makeShadowPic( CSTR picname ); #endif diff --git a/lib/App/common/deviceNodeSensor.cpp b/lib/App/common/deviceNodeSensor.cpp index 5b810d1a..1bb56c98 100644 --- a/lib/App/common/deviceNodeSensor.cpp +++ b/lib/App/common/deviceNodeSensor.cpp @@ -842,6 +842,19 @@ void deviceNodeSensor::broadcastFlip( uint16_t flipCount ){ if( bEVT != NULL ) m_pEventHeap->broadcast( bEVT ); }; +void deviceNodeSensor::broadcastConnected( void ){ + EVENT_CONTAINER *bEVT = NULL; + bEVT = createBasicEvent( m_sNodeData.node_id, m_eEventClass, EVT_CONNECTED, NULL, NULL, NULL ); + if( bEVT != NULL ) m_pEventHeap->broadcast( bEVT ); +}; + +void deviceNodeSensor::broadcastDisconnected( void ){ + EVENT_CONTAINER *bEVT = NULL; + bEVT = createBasicEvent( m_sNodeData.node_id, m_eEventClass, EVT_DISCONNECTED, NULL, NULL, NULL ); + if( bEVT != NULL ) m_pEventHeap->broadcast( bEVT ); +}; + + void deviceNodeSensor::m_fThreadProc( void ){ time_t tTimeT_Current; time_t tTimeT_Old = time( NULL ); @@ -952,7 +965,15 @@ bool deviceNodeSensor::generateIniFile( uint8_t i ){ } return false; }; - +void deviceNodeSensor::RegisterCommError( bool withEvent ){ + m_nCommErrorsCounter++; + if ( withEvent ) { + EVENT_CONTAINER *bEVT = createBasicEvent(m_sNodeData.node_id, m_eEventClass, EVT_COMMUNICATION_JAMED, NULL, NULL, NULL); + if( bEVT != NULL ) { + m_pEventHeap->broadcast(bEVT); + }; + }; +}; bool deviceNodeSensor::generateRestartFile( uint8_t i ){ if ( m_pDBC == NULL ) return false; diff --git a/lib/App/common/deviceNodeSensor.h b/lib/App/common/deviceNodeSensor.h index 76359681..49712a6a 100644 --- a/lib/App/common/deviceNodeSensor.h +++ b/lib/App/common/deviceNodeSensor.h @@ -143,7 +143,7 @@ class deviceNodeSensor: public deviceNode, public basicThread{ uint8_t * create2dDraw( uint32_t *out_size, uint32_t *th_data, size_t th_size, uint16_t max_digital, int radial_shift, CSTR tpl, bool byMinimum = true ); bool reloadDeviceNodeFromDB(); void setStage( LRF_WORK_STAGE st ); - void RegisterCommError(){ m_nCommErrorsCounter++; }; + void RegisterCommError( bool withEvent = false ); LRF_WORK_STAGE getStage(); LRF_WORK_STAGE getPrevStage(); @@ -173,7 +173,9 @@ class deviceNodeSensor: public deviceNode, public basicThread{ //virtual bool setSensorData(){ return true;}; //virtual bool setCommunicationRessurce(){ return true;}; //virtual bool connectSensor(){ return true;}; - + void broadcastConnected( void ); + void broadcastDisconnected( void ); + void broadcastFlip( uint16_t flipCount ); protected: virtual void m_fThreadProc( void ); public: @@ -182,7 +184,6 @@ class deviceNodeSensor: public deviceNode, public basicThread{ virtual ~deviceNodeSensor(); virtual void simulateTarget( void ){}; bool validate(); - void broadcastFlip( uint16_t flipCount ); }; diff --git a/lib/App/common/hardwareResourceSerialProvider.cpp b/lib/App/common/hardwareResourceSerialProvider.cpp index 57f6081b..d87e8ee0 100644 --- a/lib/App/common/hardwareResourceSerialProvider.cpp +++ b/lib/App/common/hardwareResourceSerialProvider.cpp @@ -1,5 +1,13 @@ #include "hardwareResourceSerialProvider.h" #include "../data/protocol/protocol.h" +#include +#include +#include +#include +#include + +#include + //#include "rgooseDBConnector.h" //#define DEBUG_EXTRA @@ -485,9 +493,10 @@ bool hardwareResourceSerialProvider::create_HW(){ #else #ifdef DEBUG - LOG("NO MANUAL RTS CTL(_)"); + //LOG("NO MANUAL RTS CTL(_)"); + LOG("TEST MANUAL RTS CTL(INTEL)"); #endif - m_bManualRTS = false; + m_bManualRTS = true; #endif #endif @@ -1203,12 +1212,29 @@ int hardwareResourceSerialProvider::recptBlock( unsigned char *Buffer, int *Buff void hardwareResourceSerialProvider::setRTS( uint8_t Val ){ #if defined( USE_WIRINGPI ) || defined( USE_WIRINGX ) - if ( Val ) { - //Use RTS GPIO - digitalWrite( 0, HIGH ); - } else { - digitalWrite( 0, LOW ); - }; + if ( Val ) { + //Use RTS GPIO + digitalWrite( 0, HIGH ); + } else { + digitalWrite( 0, 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 }; @@ -1226,20 +1252,22 @@ int hardwareResourceSerialProvider::sendBlock(unsigned char* Data, int DataSize) #ifdef __linux__ // setRTS( 1 ); do{ - #if defined( USE_WIRINGPI ) || defined( USE_WIRINGX ) if( m_bManualRTS ) { - digitalWrite( 0, HIGH ); + //#if defined( USE_WIRINGPI ) || defined( USE_WIRINGX ) + // digitalWrite( 0, HIGH ); + //#endif + 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( 0, LOW); - #endif + //#if defined( USE_WIRINGPI ) || defined( USE_WIRINGX ) + // digitalWrite( 0, LOW); + //#endif + setRTS( 0 ); }; if( RetVal == DataSize ){ usleep( 10 ); diff --git a/lib/App/common/hardwareResourceSerialProvider.h b/lib/App/common/hardwareResourceSerialProvider.h index 41c7f3ac..e50e1ea9 100644 --- a/lib/App/common/hardwareResourceSerialProvider.h +++ b/lib/App/common/hardwareResourceSerialProvider.h @@ -23,7 +23,7 @@ #include // POSIX terminal control definitions #if defined( __arm__ ) || defined( __aarch64__ ) #define USE_WIRINGX - #include + #include #ifdef RASPI_HARDWARE //#define USE_WIRINGPI //#include diff --git a/lib/App/common/kernelModuleEmbedVideo.cpp b/lib/App/common/kernelModuleEmbedVideo.cpp index 541667a6..15ff6403 100644 --- a/lib/App/common/kernelModuleEmbedVideo.cpp +++ b/lib/App/common/kernelModuleEmbedVideo.cpp @@ -1129,18 +1129,48 @@ streamHandler::streamHandler( kernelModuleEmbedVideo *ptr, MS_WORK_MODE M ): m_p m_pSource = NULL; m_bEvtMarkerCounter = 0; m_bCamMoveCounter = 0; + +#ifdef EVE_ENABLE_EASE_OUTPUT_FPS + #ifdef EVE_ENABLE_VIDEO + m_bAFrameSkeepDivider = 1; + m_bAFrameSkeepDividerCounter = 0; + m_bAOutputFPS = 15; + + m_bBFrameSkeepDivider = 1; + m_bBFrameSkeepDividerCounter = 0; + m_bBOutputFPS = 15; + #endif + m_bWebFrameSkeepDivider = 1; + m_bWebFrameSkeepDividerCounter = 0; + m_bInitialOutputFPS = m_bCurrentOutputFPS = 15; +#endif + #ifdef EVE_ENABLE_VIDEO - m_nPreAlarmFrames = 0; - m_nPostAlarmFrames = 0; + #ifdef EVE_ENABLE_EASE_OUTPUT_FPS + m_nAPreAlarmFrames = 0; + m_nAPostAlarmFrames = 0; + m_nASegmentLimitFrames = 0; + m_nAHardLimitFrames = 0; + + m_nBPreAlarmFrames = 0; + m_nBPostAlarmFrames = 0; + m_nBSegmentLimitFrames = 0; + m_nBHardLimitFrames = 0; + #else + m_nPreAlarmFrames = 0; + m_nPostAlarmFrames = 0; + m_nSegmentLimitFrames = 0; + m_nHardLimitFrames = 0; + #endif m_nSegAFrameCounter = 0; m_nSegBFrameCounter = 0; m_nGlobalFrameCounter = 0; + //m_nVideoRegisteredDBID = 0; m_nSegAShiftFrames = 0; m_nSegBShiftFrames = 0; m_nSegASkippedFrames = m_nSegBSkippedFrames = 0; - m_nSegmentLimitFrames = 0; - m_nHardLimitFrames = 0; + m_bActiveEncoderStream = 0; m_bSegAActive = false; m_bSegADelete = true; @@ -1187,15 +1217,27 @@ bool streamHandler::create( dataBinder *ptr, uint32_t stremID ){ free(tData); DBC_CAM_DATA *tCAM = m_pDBC->getCamData( m_sStreamData.source_id ); if( tCAM ){ - CSTR tNAM = NULL;//m_pDBC->getNodeName( tCAM->node_id ); + m_sSourceDesc.mediaStreamId = stremID; - m_sSourceDesc.mediaSourceId = m_sStreamData.source_id; - if ( tNAM!= NULL ) { - strncpy(m_sSourceDesc.mediaName, tNAM, 127 ); - m_sSourceDesc.mediaName[127] = (char)0; - free( tNAM ); + + m_sSourceDesc.mediaSourceId = m_sStreamData.source_id; + uint32_t tNID = m_pDBC->getNodeIdByTypeAndAux( tCAM->type, m_sStreamData.source_id ); + //ToDo: Check Camera Addition + // Just Work around to handle Wrong tyoe 12 instead of 13 + if ( tNID == 0 ) { + tNID = m_pDBC->getNodeIdByTypeAndAux( 13, m_sStreamData.source_id ); + }; + if (tNID) { + CSTR tNAM = m_pDBC->getNodeName( tNID ); + if ( tNAM!= NULL ) { + strncpy(m_sSourceDesc.mediaName, tNAM, 127 ); + m_sSourceDesc.mediaName[127] = (char)0; + free( tNAM ); + } else { + sprintf(m_sSourceDesc.mediaName, "No Name Cam"); + }; } else { - sprintf(m_sSourceDesc.mediaName, "No Name Cam"); + sprintf(m_sSourceDesc.mediaName, "No-Name-Cam"); }; m_cSourceType = m_sStreamData.source_type[0]; @@ -1288,6 +1330,7 @@ bool streamHandler::pushFrame( AVFrame *Frame, void* src){ }; bool streamHandler::pushFrame( cv::Mat &Frame, void* src ){ + bool SkeepW, SkeepA, SkeepB; if( m_pMaster == NULL ) return false; MEDIA_SOURCE_DESC * tMD = (MEDIA_SOURCE_DESC *) src; char tBuffer[128]; @@ -1318,6 +1361,40 @@ bool streamHandler::pushFrame( cv::Mat &Frame, void* src ){ cv::FILLED ); }; +#ifdef EVE_ENABLE_EASE_OUTPUT_FPS + SkeepW = !((m_bWebFrameSkeepDividerCounter % m_bWebFrameSkeepDivider) == 0 ); + m_bWebFrameSkeepDividerCounter = ( ++m_bWebFrameSkeepDividerCounter ) % m_bWebFrameSkeepDivider; + #ifdef EVE_ENABLE_VIDEO + SkeepA = !((m_bAFrameSkeepDividerCounter % m_bAFrameSkeepDivider) == 0 ); + //m_bAFrameSkeepDividerCounter++; + m_bAFrameSkeepDividerCounter = ( ++m_bAFrameSkeepDividerCounter ) % m_bAFrameSkeepDivider; + SkeepB = !((m_bBFrameSkeepDividerCounter % m_bBFrameSkeepDivider) == 0 ); + //m_bBFrameSkeepDividerCounter++; + m_bBFrameSkeepDividerCounter = ( ++m_bBFrameSkeepDividerCounter ) % m_bBFrameSkeepDivider; + #ifdef DEBUG_EXTRA + if( SkeepW || SkeepA || SkeepB ){ + char tzB[256]; + sprintf( tzB,"SkipF: %d:%d %d:%d %d:%d", m_bWebFrameSkeepDividerCounter, m_bWebFrameSkeepDivider, m_bAFrameSkeepDividerCounter, m_bAFrameSkeepDivider, m_bBFrameSkeepDividerCounter, m_bBFrameSkeepDivider ); + LOG( tzB ); + } else { + LOG( "PushF" ); + }; + #endif + //if( m_bWebFrameSkeepDivider == m_bAFrameSkeepDividerCounter ) = 1; + //if( SkeepB ) m_bBFrameSkeepDividerCounter = 1; + //if( SkeepW ) m_bWebFrameSkeepDividerCounter = 1; + #else + #ifdef DEBUG + if( SkeepW ){ + char tB[256]; + sprintf( tB,"Skip: %d:%d", m_bWebFrameSkeepDividerCounter, m_bWebFrameSkeepDivider ); + LOG( tB ); + }; + #endif + if( SkeepW ) m_bWebFrameSkeepDividerCounter = 1; + #endif +#endif + #ifdef USE_SCALING_IN oK = ((float)m_pMaster->m_sEmbedVideoData.height )/ ((float)m_pMaster->m_sEmbedVideoData.width); mK = ((float)Frame.rows )/ ((float)Frame.cols); @@ -1366,6 +1443,15 @@ bool streamHandler::pushFrame( cv::Mat &Frame, void* src ){ }; }; #endif + +#ifdef EVE_ENABLE_EASE_OUTPUT_FPS + #ifdef EVE_ENABLE_VIDEO + if( SkeepW && SkeepA && SkeepB ) return true; + #else + if( SkeepW ) return true; + #endif +#endif + if ( m_bCamMoveCounter > m_bEvtMarkerCounter ) { cv::rectangle( m_pMaster->m_mapMATS[tMD->mediaStreamId], @@ -1390,10 +1476,12 @@ bool streamHandler::pushFrame( cv::Mat &Frame, void* src ){ }; if (m_pMaster->m_sEmbedVideoData.show_label) { time_t t = time( NULL ); - struct tm * tmp = gmtime( &t ); + //struct tm * tmp = gmtime( &t ); + struct tm * tmp = localtime( &t ); if( tmp ){ char tsb[64]; - if( strftime( tsb, sizeof(tsb), "%F %T GMT", tmp )!=0 ){ + //if( strftime( tsb, sizeof(tsb), "%F %T GMT", tmp )!=0 ){ + if( strftime( tsb, sizeof(tsb), "%F %T", tmp )!=0 ){ //sprintf( tBuffer, ">>%d>%d>%s>%s>", tMD->mediaSourceId, tMD->mediaStreamId, tMD->mediaName, tsb ); sprintf( tBuffer, ">>>%s>%s>", tMD->mediaName, tsb ); @@ -1569,18 +1657,23 @@ bool streamHandler::pushFrame( cv::Mat &Frame, void* src ){ cv::Mat destinationROI = m_pMaster->m_mapMATS[tMD->mediaStreamId]( roi ); m_pMaster->m_mLogoPic.copyTo( destinationROI, m_pMaster->m_mLogoMask ); }; +#ifdef EVE_ENABLE_EASE_OUTPUT_FPS + if ( !SkeepW ) { +#endif + vector compression_params; + //compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION); + //compression_params.push_back(9); + compression_params.push_back( cv::IMWRITE_JPEG_QUALITY ); + compression_params.push_back( m_pMaster->m_sEmbedVideoData.compression_quality ); - vector compression_params; - //compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION); - //compression_params.push_back(9); - compression_params.push_back( cv::IMWRITE_JPEG_QUALITY ); - compression_params.push_back( m_pMaster->m_sEmbedVideoData.compression_quality ); - - m_pMaster->m_mEncodedProtector.lock(); + m_pMaster->m_mEncodedProtector.lock(); - m_pMaster->m_mapCAPTURES[tMD->mediaStreamId].clear(); - cv::imencode( ".jpg", m_pMaster->m_mapMATS[tMD->mediaStreamId], m_pMaster->m_mapCAPTURES[tMD->mediaStreamId], compression_params ); - m_pMaster->m_mEncodedProtector.unlock(); + m_pMaster->m_mapCAPTURES[tMD->mediaStreamId].clear(); + cv::imencode( ".jpg", m_pMaster->m_mapMATS[tMD->mediaStreamId], m_pMaster->m_mapCAPTURES[tMD->mediaStreamId], compression_params ); + m_pMaster->m_mEncodedProtector.unlock(); +#ifdef EVE_ENABLE_EASE_OUTPUT_FPS + }; +#endif #ifdef EVE_ENABLE_VIDEO // encode Video Stream @@ -1596,14 +1689,41 @@ bool streamHandler::pushFrame( cv::Mat &Frame, void* src ){ m_mFrameCounterProtector.lock(); if( m_bSegAActive ){ - do { +#ifdef EVE_ENABLE_EASE_OUTPUT_FPS + //do { + //In Any Case Close Stream if it Long enough + if( m_nSegAFrameCounter > m_nAHardLimitFrames ){ +#ifdef DEBUG + LOG("HardLimit Reached!(A)"); +#endif + closeSegmentA(); + //break; + }; + if( m_nSegAFrameCounter > ( m_nASegmentLimitFrames - ( m_nAPostAlarmFrames + m_nBPreAlarmFrames ))){ + if ( !m_bSegBActive ){ +#ifdef DEBUG + LOG("Start Alt!(A)"); +#endif + openSegmentB(); + }; + }; + if( m_nSegAFrameCounter > ( m_nASegmentLimitFrames - m_nAPostAlarmFrames ) && !m_bActiveEncoderStream ){ +#ifdef DEBUG + LOG("Swap Active!(A)"); +#endif + swapActiveStreams(); + //break; + }; + // } while ( 0 ); +#else + //do { //In Any Case Close Stream if it Long enough if( m_nSegAFrameCounter > m_nHardLimitFrames ){ #ifdef DEBUG LOG("HardLimit Reached!(A)"); #endif closeSegmentA(); - break; + //break; }; if( m_nSegAFrameCounter > ( m_nSegmentLimitFrames - ( m_nPostAlarmFrames + m_nPreAlarmFrames ))){ if ( !m_bSegBActive ){ @@ -1618,20 +1738,48 @@ bool streamHandler::pushFrame( cv::Mat &Frame, void* src ){ LOG("Swap Active!(A)"); #endif swapActiveStreams(); - break; + //break; }; - } while ( 0 ); + // } while ( 0 ); +#endif// !EVE_ENABLE_EASE_OUTPUT_FPS }; if( m_bSegBActive ) { - do { +#ifdef EVE_ENABLE_EASE_OUTPUT_FPS + // do { + //In Any Case Close Stream if it Long enough + if( m_nSegBFrameCounter > m_nBHardLimitFrames ){ +#ifdef DEBUG + LOG("HardLimit Reached!(B)"); +#endif + closeSegmentB(); + //break; + }; + if( m_nSegBFrameCounter > ( m_nBSegmentLimitFrames - ( m_nBPostAlarmFrames + m_nAPreAlarmFrames ))){ + if ( !m_bSegAActive ){ +#ifdef DEBUG + LOG("Start Alt!(B)"); +#endif + openSegmentA(); + }; + }; + if( m_nSegBFrameCounter > ( m_nBSegmentLimitFrames - m_nBPostAlarmFrames ) && m_bActiveEncoderStream ){ +#ifdef DEBUG + LOG("Swap Active!(B)"); +#endif + swapActiveStreams(); + // break; + }; + //} while ( 0 ); +#else + // do { //In Any Case Close Stream if it Long enough if( m_nSegBFrameCounter > m_nHardLimitFrames ){ #ifdef DEBUG LOG("HardLimit Reached!(B)"); #endif closeSegmentB(); - break; + //break; }; if( m_nSegBFrameCounter > ( m_nSegmentLimitFrames - ( m_nPostAlarmFrames + m_nPreAlarmFrames ))){ if ( !m_bSegAActive ){ @@ -1646,15 +1794,20 @@ bool streamHandler::pushFrame( cv::Mat &Frame, void* src ){ LOG("Swap Active!(B)"); #endif swapActiveStreams(); - break; + // break; }; - } while ( 0 ); + //} while ( 0 ); +#endif // !EVE_ENABLE_EASE_OUTPUT_FPS }; m_mFrameCounterProtector.unlock(); ENCODING_BUFFER *tData = (ENCODING_BUFFER *) malloc( sizeof(ENCODING_BUFFER)); if ( tData ) { + #ifdef EVE_ENABLE_EASE_OUTPUT_FPS + tData->flag_sa = SkeepA; + tData->flag_sb = SkeepB; + #endif #ifdef OPENCV_VIDEO_OUTPUT tData->rows = m_pMaster->m_mapMATS[tMD->mediaStreamId].rows; tData->cols = m_pMaster->m_mapMATS[tMD->mediaStreamId].cols; @@ -1831,7 +1984,13 @@ bool streamHandler::openSegmentA( void ){ #ifdef OPENCV_VIDEO_OUTPUT if ( m_pEncoderA ) { int fourcc = cv::VideoWriter::fourcc('H', '2', '6', '4'); +#ifdef EVE_ENABLE_EASE_OUTPUT_FPS + m_bAFrameSkeepDivider = m_bWebFrameSkeepDivider; + m_bAOutputFPS = m_bInitialOutputFPS / m_bAFrameSkeepDivider; + double fps = m_bAOutputFPS; +#else double fps = m_sStreamData.fps; +#endif cv::String mn( m_sStreamSegmentInfo[0].scratchPath ); cv::Size fz( m_sStreamData.width, m_sStreamData.height ); //open (const String &filename, int fourcc, double fps, Size frameSize, bool isColor=true) @@ -1840,8 +1999,9 @@ bool streamHandler::openSegmentA( void ){ return false; #ifdef DEBUG } else { - LOG("VideoStream A is Created"); - LOG( m_sStreamSegmentInfo[0].scratchPath ); + char tB[256]; + sprintf( tB,"VideoStream A is Created [%s] %.2f fps", m_sStreamSegmentInfo[0].scratchPath, fps ); + LOG( tB ); #endif }; m_bSegAActive = true; @@ -1969,7 +2129,13 @@ bool streamHandler::openSegmentB( void ){ #ifdef OPENCV_VIDEO_OUTPUT if ( m_pEncoderB ) { int fourcc = cv::VideoWriter::fourcc('H', '2', '6', '4'); +#ifdef EVE_ENABLE_EASE_OUTPUT_FPS + m_bBFrameSkeepDivider = m_bWebFrameSkeepDivider; + m_bBOutputFPS = m_bInitialOutputFPS / m_bBFrameSkeepDivider; + double fps = m_bBOutputFPS; +#else double fps = m_sStreamData.fps; +#endif cv::String mn( m_sStreamSegmentInfo[1].scratchPath ); cv::Size fz( m_sStreamData.width, m_sStreamData.height ); //open (const String &filename, int fourcc, double fps, Size frameSize, bool isColor=true) @@ -1978,8 +2144,9 @@ bool streamHandler::openSegmentB( void ){ return false; #ifdef DEBUG } else { - LOG("VideoStream B is Created"); - LOG( m_sStreamSegmentInfo[1].scratchPath ); + char tB[256]; + sprintf( tB,"VideoStream B is Created [%s] %.2f fps", m_sStreamSegmentInfo[1].scratchPath, fps ); + LOG( tB ); #endif }; m_bSegBActive = true; @@ -2076,21 +2243,47 @@ bool streamHandler::openSegmentB( void ){ }; bool streamHandler::initVideoOutput(){ + +#ifdef EVE_ENABLE_EASE_OUTPUT_FPS + m_bAFrameSkeepDivider = m_bBFrameSkeepDivider = 1; + m_bAFrameSkeepDividerCounter = m_bBFrameSkeepDividerCounter = 0; + m_bCurrentOutputFPS = m_bInitialOutputFPS = m_sStreamData.fps; + + m_nAPreAlarmFrames = ( PRE_ALARM_TIME_MILSECONDS * m_bAOutputFPS ) / 1000; + m_nAPostAlarmFrames = ( POST_ALARM_TIME_MILSECONDS * m_bAOutputFPS ) / 1000; + m_nASegmentLimitFrames = ( ENCODING_SEGMENT_MILSECONDS * m_bAOutputFPS ) / 1000; + m_nAHardLimitFrames = ( ENCODING_SEGMENT_LIMIT_MILSECONDS * m_bAOutputFPS ) / 1000; + + m_nBPreAlarmFrames = ( PRE_ALARM_TIME_MILSECONDS * m_bBOutputFPS ) / 1000; + m_nBPostAlarmFrames = ( POST_ALARM_TIME_MILSECONDS * m_bBOutputFPS ) / 1000; + m_nBSegmentLimitFrames = ( ENCODING_SEGMENT_MILSECONDS * m_bBOutputFPS ) / 1000; + m_nBHardLimitFrames = ( ENCODING_SEGMENT_LIMIT_MILSECONDS * m_bBOutputFPS ) / 1000; +#else m_nPreAlarmFrames = ( PRE_ALARM_TIME_MILSECONDS * m_sStreamData.fps ) / 1000; m_nPostAlarmFrames = ( POST_ALARM_TIME_MILSECONDS * m_sStreamData.fps ) / 1000; m_nSegmentLimitFrames = ( ENCODING_SEGMENT_MILSECONDS * m_sStreamData.fps ) / 1000; m_nHardLimitFrames = ( ENCODING_SEGMENT_LIMIT_MILSECONDS * m_sStreamData.fps ) / 1000; +#endif + #ifdef OPENCV_VIDEO_OUTPUT m_pEncoderA = new cv::VideoWriter(); if ( m_pEncoderA == NULL ) { LOG_ERROR("Encoder A Create Failure!"); return false; }; + + //m_pEncoderA->set( cv::VIDEOWRITER_PROP_QUALITY, 50.0 ); + //m_pEncoderA->set( cv::VIDEOWRITER_PROP_NSTRIPES, 4 ); + m_pEncoderB = new cv::VideoWriter(); if ( m_pEncoderA == NULL ) { LOG_ERROR("Encoder B Create Failure!"); return false; }; + + //m_pEncoderB->set( cv::VIDEOWRITER_PROP_QUALITY, 50.0 ); + //m_pEncoderB->set( cv::VIDEOWRITER_PROP_NSTRIPES, 4 ); + #else if( !initLibAV() ) return false; @@ -2748,6 +2941,9 @@ bool streamHandler::initVideoOutput(){ void streamHandler::m_fThreadProc( void ){ char tB[128]; +#ifdef EVE_ENABLE_EASE_OUTPUT_FPS + uint32_t nQueueSize; +#endif #ifndef OPENCV_VIDEO_OUTPUT AVPacket mPacket; int bGotPacket; @@ -2770,34 +2966,87 @@ void streamHandler::m_fThreadProc( void ){ }; m_mEncodingQueueProtector.lock(); +#ifdef EVE_ENABLE_EASE_OUTPUT_FPS + nQueueSize = m_qEncodingQueue.size(); + if ( nQueueSize > EVE_EASE_FPS_QUEUE_SIZE_MAXIMUM ) { + //Just in case allredy applied to a streams + if( m_bWebFrameSkeepDivider == m_bAFrameSkeepDivider && m_bWebFrameSkeepDivider == m_bBFrameSkeepDivider ){ + m_bWebFrameSkeepDivider++; + if ( m_bWebFrameSkeepDivider > EVE_EASE_FPS_DIVIDER_MAXIMUM ) { + m_bWebFrameSkeepDivider = EVE_EASE_FPS_DIVIDER_MAXIMUM; + } else { +#ifdef DEBUG + LOG("Video Quality Degraded!"); +#endif + EVENT_CONTAINER *bEVT = createBasicEvent( m_sStreamData.source_id, EVT_CLASS_VIDEO, EVT_VIDEO_FPS_DEGRADED, NULL, NULL, NULL ); + if ( bEVT ) { + basicEventHeap::getInstance()->broadcast( bEVT ); + } else LOG_ERROR( "Event Creation failure!"); + }; + }; + } else if( nQueueSize < EVE_EASE_FPS_QUEUE_SIZE_MINIMUM ){ + //Just in case allredy applied to a streams + if( m_bWebFrameSkeepDivider == m_bAFrameSkeepDivider && m_bWebFrameSkeepDivider == m_bBFrameSkeepDivider ){ + m_bWebFrameSkeepDivider--; + if ( m_bWebFrameSkeepDivider < EVE_EASE_FPS_DIVIDER_MINIMUM ) { + m_bWebFrameSkeepDivider = EVE_EASE_FPS_DIVIDER_MINIMUM; + } else { +#ifdef DEBUG + LOG("Video Quality Upgraded!"); +#endif + EVENT_CONTAINER *bEVT = createBasicEvent( m_sStreamData.source_id, EVT_CLASS_VIDEO, EVT_VIDEO_FPS_RAISED, NULL, NULL, NULL ); + if ( bEVT ) { + basicEventHeap::getInstance()->broadcast( bEVT ); + } else LOG_ERROR( "Event Creation failure!"); + }; + }; + }; + + if ( nQueueSize ) { +#else if ( m_qEncodingQueue.size() ) { +#endif ENCODING_BUFFER *tData = m_qEncodingQueue.front(); if( tData ){ m_qEncodingQueue.pop(); m_mEncodingQueueProtector.unlock(); +#ifdef EVE_ENABLE_EASE_OUTPUT_FPS + bool bSkeepA = tData->flag_sa; + bool bSkeepB = tData->flag_sb; +#endif #ifdef OPENCV_VIDEO_OUTPUT + cv::Mat image( tData->rows, tData->cols, CV_8UC3 ); memcpy( image.data, tData->data, tData->size ); free( tData->data ); - free( tData ); - - if ( m_bSegAActive ) { - if ( m_pEncoderA->isOpened() ) { - m_pEncoderA->write( image ); - m_mFrameCounterProtector.lock(); - m_nSegAFrameCounter++; - m_mFrameCounterProtector.unlock(); + free( tData ); +#ifdef EVE_ENABLE_EASE_OUTPUT_FPS + if( !bSkeepA ){ +#endif + if (m_bSegAActive) { + if ( m_pEncoderA->isOpened() ) { + m_pEncoderA->write( image ); + m_mFrameCounterProtector.lock(); + m_nSegAFrameCounter++; + m_mFrameCounterProtector.unlock(); + }; }; +#ifdef EVE_ENABLE_EASE_OUTPUT_FPS }; - if ( m_bSegBActive ) { - if ( m_pEncoderB->isOpened() ) { - m_pEncoderB->write( image ); - m_mFrameCounterProtector.lock(); - m_nSegBFrameCounter++; - m_mFrameCounterProtector.unlock(); + if( !bSkeepB ){ +#endif + if ( m_bSegBActive ) { + if ( m_pEncoderB->isOpened() ) { + m_pEncoderB->write( image ); + m_mFrameCounterProtector.lock(); + m_nSegBFrameCounter++; + m_mFrameCounterProtector.unlock(); + }; }; +#ifdef EVE_ENABLE_EASE_OUTPUT_FPS }; -#else +#endif +#else // !OPENCV_VIDEO_OUTPUT //av_frame_make_writable( m_pAVFrame ); //m_qEncodingQueue.pop(); //m_mEncodingQueueProtector.unlock(); @@ -2841,18 +3090,25 @@ void streamHandler::m_fThreadProc( void ){ m_nGlobalFrameCounter++; m_mFrameCounterProtector.unlock(); } else m_mEncodingQueueProtector.unlock(); - } else { + } else //{ m_mEncodingQueueProtector.unlock(); // If No Encode Job -> Test Commands! m_mCurrentOperationProtector.lock(); switch ( m_bCOP ) { case 0x01:{ +#ifdef DEBUG + LOG("Actual Closing Video Stream A!"); LOG( m_sStreamSegmentInfo[0].scratchPath ); +#endif m_bSegAActive = false; if ( !m_bSegADelete ) { #ifdef OPENCV_VIDEO_OUTPUT if ( m_pEncoderA->isOpened() ) { m_pEncoderA->release(); +#ifdef DEBUG + } else { + LOG(" Encoder A is NOT Opened!"); +#endif }; #else av_write_trailer( m_pFormatCtxA ); @@ -2869,6 +3125,10 @@ void streamHandler::m_fThreadProc( void ){ #ifdef OPENCV_VIDEO_OUTPUT if ( m_pEncoderA->isOpened() ) { m_pEncoderA->release(); +#ifdef DEBUG + } else { + LOG(" Encoder A is NOT Opened!"); +#endif }; #else #ifdef EVE_DONT_DELETE_SEGMENTS @@ -2899,14 +3159,19 @@ void streamHandler::m_fThreadProc( void ){ break; }; case 0x02:{ - +#ifdef DEBUG + LOG("Actual Closing Video Stream B!"); LOG( m_sStreamSegmentInfo[1].scratchPath ); - +#endif m_bSegBActive = false; if ( !m_bSegBDelete ) { #ifdef OPENCV_VIDEO_OUTPUT if ( m_pEncoderB->isOpened() ) { m_pEncoderB->release(); +#ifdef DEBUG + } else { + LOG(" Encoder B is NOT Opened!"); +#endif }; #else av_write_trailer( m_pFormatCtxB ); @@ -2924,6 +3189,10 @@ void streamHandler::m_fThreadProc( void ){ #ifdef OPENCV_VIDEO_OUTPUT if ( m_pEncoderB->isOpened() ) { m_pEncoderB->release(); +#ifdef DEBUG + } else { + LOG(" Encoder B is NOT Opened!"); +#endif }; #else #ifdef EVE_DONT_DELETE_SEGMENTS @@ -2950,9 +3219,10 @@ void streamHandler::m_fThreadProc( void ){ }; m_bCOP = 0; m_mCurrentOperationProtector.unlock(); - }; + //}; #ifdef OPENCV_VIDEO_OUTPUT -#else // OPENCV_VIDEO_OUTPUT + +#else // !OPENCV_VIDEO_OUTPUT #ifdef SEPARATED_VIDEO_ENCODERS do { mPacket.data = NULL; @@ -3060,7 +3330,8 @@ void streamHandler::m_fThreadProc( void ){ }; } while ( rVal >= 0 && m_bThreadStatus != TH_ENDED ); #endif // ! SEPARATED_VIDEO_ENCODERS -#endif // OPENCV_VIDEO_OUTPUT +#endif // !OPENCV_VIDEO_OUTPUT + SLEEP( 10 ); }; #ifdef DEBUG_EXTRA LOG("Encoder Loop Ended!"); @@ -3081,7 +3352,11 @@ void streamHandler::swapActiveStreams( void ){ #endif // EVE_ENABLE_VIDEO bool streamHandler::triggerEvent( uint32_t eid, uint32_t &dbid, uint32_t &frame ){ + +#ifdef DEBUG LOG("Trig Evt"); +#endif + #ifdef EVE_ENABLE_VIDEO m_mFrameCounterProtector.lock(); // To Mark Events Frames diff --git a/lib/App/common/kernelModuleEmbedVideo.h b/lib/App/common/kernelModuleEmbedVideo.h index 606ebcbc..100769c3 100644 --- a/lib/App/common/kernelModuleEmbedVideo.h +++ b/lib/App/common/kernelModuleEmbedVideo.h @@ -183,9 +183,22 @@ typedef map mapSTREAMMAPS; #define EVE_OUTPUT_VIDEO 2 #define EVE_OUTPUT_PIC_AND_VID 3 +#define EVE_ENABLE_EASE_OUTPUT_FPS + +#ifdef EVE_ENABLE_EASE_OUTPUT_FPS + #define EVE_EASE_FPS_DIVIDER_MINIMUM 1 + #define EVE_EASE_FPS_DIVIDER_MAXIMUM 5 + #define EVE_EASE_FPS_QUEUE_SIZE_MAXIMUM 8 + #define EVE_EASE_FPS_QUEUE_SIZE_MINIMUM 2 +#endif + #ifdef EVE_ENABLE_VIDEO #ifdef OPENCV_VIDEO_OUTPUT typedef struct S_ENCODING_BUFFER{ +#ifdef EVE_ENABLE_EASE_OUTPUT_FPS + bool flag_sa; + bool flag_sb; +#endif int cols; int rows; uint8_t * data; @@ -218,15 +231,50 @@ class streamHandler: kernelModuleEmbedVideo * m_pMaster; uint8_t m_bEvtMarkerCounter; uint8_t m_bCamMoveCounter; + dataBinder * m_pDBC; MS_WORK_MODE m_eWM; basicMutex m_mEvtIDS_Protector; - + +#ifdef EVE_ENABLE_EASE_OUTPUT_FPS + uint8_t m_bWebFrameSkeepDividerCounter; + uint8_t m_bWebFrameSkeepDivider; +#endif + #ifdef EVE_ENABLE_VIDEO - VIDEO_SEGMENT_INFO m_sStreamSegmentInfo[2]; - basicMutex m_mFrameCounterProtector; + + #ifdef EVE_ENABLE_EASE_OUTPUT_FPS + uint8_t m_bAFrameSkeepDivider; + uint8_t m_bAFrameSkeepDividerCounter; + uint8_t m_bAOutputFPS; + + uint8_t m_bBFrameSkeepDivider; + uint8_t m_bBFrameSkeepDividerCounter; + uint8_t m_bBOutputFPS; + + uint8_t m_bInitialOutputFPS; + uint8_t m_bCurrentOutputFPS; + + uint32_t m_nAPreAlarmFrames; + uint32_t m_nAPostAlarmFrames; + uint32_t m_nASegmentLimitFrames; + uint32_t m_nAHardLimitFrames; + + uint32_t m_nBPreAlarmFrames; + uint32_t m_nBPostAlarmFrames; + uint32_t m_nBSegmentLimitFrames; + uint32_t m_nBHardLimitFrames; + #else uint32_t m_nPreAlarmFrames; uint32_t m_nPostAlarmFrames; + uint32_t m_nSegmentLimitFrames; + uint32_t m_nHardLimitFrames; + #endif + + VIDEO_SEGMENT_INFO m_sStreamSegmentInfo[2]; + basicMutex m_mFrameCounterProtector; + + uint32_t m_nGlobalFrameCounter; //uint32_t m_nVideoRegisteredDBID; @@ -239,7 +287,7 @@ class streamHandler: #ifdef OPENCV_VIDEO_OUTPUT cv::VideoWriter * m_pEncoderA; cv::VideoWriter * m_pEncoderB; - #else //OPENCV_VIDEO_OUTPUT + #else //!OPENCV_VIDEO_OUTPUT //char m_pVideoScratchPath[PATH_MAX]; #ifdef SEPARATED_VIDEO_ENCODERS // encoding video stuff @@ -264,8 +312,7 @@ class streamHandler: // Common Pix Converter ( for both streams ) SwsContext * m_pConvertCtx; #endif //OPENCV_VIDEO_OUTPUT - uint32_t m_nSegmentLimitFrames; - uint32_t m_nHardLimitFrames; + uint8_t m_bActiveEncoderStream; bool m_bSegAActive; bool m_bSegADelete; diff --git a/lib/App/mojo/mojoBackend.cpp b/lib/App/mojo/mojoBackend.cpp index a0b88fc4..f33150fd 100644 --- a/lib/App/mojo/mojoBackend.cpp +++ b/lib/App/mojo/mojoBackend.cpp @@ -443,6 +443,7 @@ int main( int argc, char *argv[] ){ CSTR tUSER = DBC->getDataParam( 1 ); CSTR tGROUP = DBC->getDataParam( 2 ); delete( DBC ); + DBC = NULL; if ( tNAME != NULL ) { LOG("FACTORY RESET ISSUED!"); if( !fileExist( "data/factory.db" ) ){ @@ -465,7 +466,12 @@ int main( int argc, char *argv[] ){ } while( ExitCode > 0 ); - unlink( gsCFG_PID_FILE ); + if ( DBC ){ + delete( DBC ); + LOG( "DBC Deleted" ); + }; + + unlink(gsCFG_PID_FILE); LOG( "PID File Deleted" ); delete( m_pLog ); return 0; diff --git a/lib/App/mojo/mojoKernel.cpp b/lib/App/mojo/mojoKernel.cpp index 3523f6de..7e9269ec 100644 --- a/lib/App/mojo/mojoKernel.cpp +++ b/lib/App/mojo/mojoKernel.cpp @@ -168,7 +168,7 @@ bool mojoKernel::create(){ m_bDebugMode = m_pDBC->getAppDebugMode(); - m_bSessionStarted = m_pDBC->getLRFEventSessionStatus( m_nServerNodeID ); + m_bSessionStarted = m_pDBC->getEventSessionStatus( m_nServerNodeID ); stopSession( false ); m_pHardwareManager = hardwareManager::getInstance(); @@ -646,6 +646,22 @@ void mojoKernel::dispatchEvent( EVENT_CONTAINER *Evt ){ }; 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; + }; }; break; }; @@ -755,6 +771,28 @@ void mojoKernel::dispatchEvent( EVENT_CONTAINER *Evt ){ }; break; }; + case EVT_ERR_LRF_NO_IRQ: + case EVT_ERR_LRF_ANGLE: + case EVT_ERR_LRF_MAINTENANCE: + case EVT_ERR_LRF_TROUBLE: + case EVT_LRF_VIS_CHANGED: + case EVT_COMMUNICATION_JAMED: if( !m_bDebugMode ) break; + 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; @@ -807,29 +845,45 @@ void mojoKernel::dispatchEvent( EVENT_CONTAINER *Evt ){ void mojoKernel::handleVideo( VIDEO_SEGMENT_INFO *ptr ){ if ( fileExist( ptr->scratchPath ) ) { - if( ptr->recordMD5[0] ) { - char tB[MAX_PATH]; - char dB[MAX_PATH]; - sprintf( tB, "%s/data/videos/%s.%s", getcwd(dB,MAX_PATH), ptr->recordMD5, ptr->recordEXT ); - + if( ptr->recordMD5[0] ) { //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 LOG("Video File Registered"); +#endif for (int idx = 0; idx < ptr->eventIDS.size(); idx++) { +#ifdef DEBUG 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 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); + chown( tB, "nobody", "nogroup" ); + chmod( tB, 0664 ); + LOG("Video Saved"); + free( tP ); + } else { + LOG_ERROR("Cannot Get Report Path from DB!"); }; + } else { + LOG_ERROR("Failure in registration video!"); }; - fileCopy(ptr->scratchPath, tB); - chown( tB, "nobody", "nogroup" ); - chmod( tB, 0664 ); - LOG("Video Saved"); }; unlink( ptr->scratchPath ); +#ifdef DEBUG LOG("Video Scratch Deleted!"); +#endif } else LOG_ERROR("Video File is Missing!"); }; diff --git a/lib/components/base/basicEvent.h b/lib/components/base/basicEvent.h index 80e24e6d..30a44ea2 100644 --- a/lib/components/base/basicEvent.h +++ b/lib/components/base/basicEvent.h @@ -84,7 +84,17 @@ typedef enum E_basicEventTypeID { EVT_LRF_START_SESSION = 52, EVT_LRF_END_SESSION_TO = 53, EVT_LRF_END_SESSION_MA = 54, - EVT_COUNT = 55 + EVT_CONNECTED = 55, + EVT_DISCONNECTED = 56, + EVT_COMMUNICATION_JAMED = 57, + EVT_VIDEO_FPS_DEGRADED = 58, + EVT_VIDEO_FPS_RAISED = 59, + EVT_ERR_LRF_NO_IRQ = 60, + EVT_ERR_LRF_ANGLE = 61, + EVT_ERR_LRF_MAINTENANCE = 62, + EVT_ERR_LRF_TROUBLE = 63, + EVT_LRF_VIS_CHANGED = 64, + EVT_COUNT = 65 } basicEventTypeID; diff --git a/lib/data/media/video/videoAVLIBSource.cpp b/lib/data/media/video/videoAVLIBSource.cpp index fa97f2ce..6ce5a358 100644 --- a/lib/data/media/video/videoAVLIBSource.cpp +++ b/lib/data/media/video/videoAVLIBSource.cpp @@ -451,8 +451,12 @@ bool videoAVLIBSource::_open( char *URI, bool ShowDeviceMenu, float framerate, i and threaded mode (AVCodecContext::thread_type set to FF_THREAD_FRAME or FF_THREAD_SLICE). Thread pool will be managed by FFmpeg itself, although some answers say that it is also possible using application-provided pool. */ - //m_pVideoState->m_pCodecCtx->thread_count = 2; + m_pVideoState->m_pCodecCtx->thread_count = 4; //m_pVideoState->m_pCodecCtx->thread_type = FF_THREAD_FRAME; + //if (is_live) + m_pVideoState->m_pCodecCtx->thread_count = FF_THREAD_SLICE; + //else + //m_pVideoState->m_pCodecCtx->thread_count = FF_THREAD_SLICE | FF_THREAD_FRAME; #ifdef DEBUG_EXTRA LOG("Before Open2"); #endif @@ -698,7 +702,8 @@ void videoAVLIBSource::m_fThreadProc( void ){ SLEEP( 5 ); }; av_packet_unref( pPacket ); - } else SLEEP( 20 ); + SLEEP( 10 ); + } else SLEEP( 10 ); }; #ifdef DEBUG LOG("Video Source Ended!"); diff --git a/lib/data/protocol/protocolLGS2D.cpp b/lib/data/protocol/protocolLGS2D.cpp index acc26847..9915ab45 100644 --- a/lib/data/protocol/protocolLGS2D.cpp +++ b/lib/data/protocol/protocolLGS2D.cpp @@ -49,10 +49,14 @@ int protocolLGS_2D::FinishUpPackage( uint8_t *Buffer, size_t Size, uint8_t Devic memcpy( Buffer+2, ZUBBI, Size+1 ); Buffer[0]=0; Buffer[1]=0; - Buffer[Size+3]=0; - Buffer[Size+4]=0; - return (int)(Size + 5); -#else + #ifdef LEGACY_2ZEROS_FROM_BOTH_SIDES + Buffer[Size+3]=0; + Buffer[Size+4]=0; + return (int)(Size + 5); + #else + return (int)(Size + 3); + #endif +#else return (int)(Size + 1); #endif }; @@ -163,7 +167,7 @@ bool protocolLGS_2D::getVoltage( void ){ if( m_oDataTransport == NULL )return false; Buffer[CMD_IDX] = CMD_GET_VOLTAGE; -#ifdef DEBUG +#ifdef DEBUG_EXTRA LOG("getVoltage"); #endif return m_oDataTransport->sendData(Buffer, FinishUpPackage( Buffer, 4, m_bDeviceID )); @@ -173,7 +177,7 @@ bool protocolLGS_2D::doFullReset( void ){ U8 Buffer[16]; if( m_oDataTransport == NULL ) return false; Buffer[CMD_IDX] = CMD_FULL_RESET; -#ifdef DEBUG +#ifdef DEBUG_EXTRA LOG("doFullReset"); #endif return m_oDataTransport->sendData(Buffer, FinishUpPackage(Buffer, 4, m_bDeviceID)); @@ -183,7 +187,7 @@ bool protocolLGS_2D::doReset( void ){ U8 Buffer[16]; if( m_oDataTransport == NULL ) return false; Buffer[CMD_IDX] = CMD_RESET; -#ifdef DEBUG +#ifdef DEBUG_EXTRA LOG("doReset"); #endif return m_oDataTransport->sendData(Buffer, FinishUpPackage(Buffer, 4, m_bDeviceID)); @@ -195,7 +199,7 @@ bool protocolLGS_2D::getFullDraw( uint16_t Angle ){ Buffer[CMD_IDX] = CMD_FULL_BORDER; Buffer[4] = (Angle >> 8) & 0x1F; Buffer[5] = Angle & 0xFF; -#ifdef DEBUG +#ifdef DEBUG_EXTRA LOG("getFullDraw"); #endif return m_oDataTransport->sendData(Buffer, FinishUpPackage(Buffer, 6, m_bDeviceID)); @@ -224,7 +228,7 @@ bool protocolLGS_2D::getParameters( bool MASTER ){ } else { Buffer[SUB_CMD_IDX] = 0x40; }; -#ifdef DEBUG +#ifdef DEBUG_EXTRA if( MASTER ) { LOG("getMasterParameters"); } else { @@ -234,33 +238,33 @@ bool protocolLGS_2D::getParameters( bool MASTER ){ return m_oDataTransport->sendData(Buffer, FinishUpPackage(Buffer, 5, m_bDeviceID)); }; -bool protocolLGS_2D::getShadowPoly( uint16_t PolyID ){ +bool protocolLGS_2D::getShadowPoly( uint8_t sequence, uint16_t PolyID ){ U8 Buffer[16]; if( m_oDataTransport == NULL ) return false; Buffer[CMD_IDX] = CMD_GET_HZ_DATA; Buffer[SUB_CMD_IDX] = sizeof( HZ_CMD_GET_POLYGON ) - sizeof( HZ_PACKET ); Buffer[5] = HZIT_CMD_GET_POLYGON; - Buffer[6] = 0; + Buffer[6] = sequence; // 0; Buffer[7] = PolyID & 0xff; Buffer[8] = ( PolyID >> 8 ) & 0xff; -#ifdef DEBUG +#ifdef DEBUG_EXTRA LOG("getShadowPoly"); #endif - return m_oDataTransport->sendData(Buffer, FinishUpPackage(Buffer, 9, m_bDeviceID)); + return m_oDataTransport->sendData( Buffer, FinishUpPackage(Buffer, 9, m_bDeviceID)); }; -bool protocolLGS_2D::getShadowPolyPoint( uint16_t PolyID, uint16_t PointID ){ +bool protocolLGS_2D::getShadowPolyPoint( uint8_t sequence, uint16_t PolyID, uint16_t PointID ){ U8 Buffer[16]; if( m_oDataTransport == NULL ) return false; Buffer[CMD_IDX] = CMD_GET_HZ_DATA; Buffer[SUB_CMD_IDX] = sizeof( HZ_CMD_GET_POLYGON_POINT ) - sizeof( HZ_PACKET ); Buffer[5] = HZIT_CMD_GET_POLYGON_POINT; - Buffer[6] = 0; + Buffer[6] = sequence; //0; Buffer[7] = PolyID & 0xff; Buffer[8] = ( PolyID >> 8 ) & 0xff; Buffer[9] = PointID & 0xff; Buffer[10] = ( PointID >> 8 ) & 0xff; -#ifdef DEBUG +#ifdef DEBUG_EXTRA LOG("getShadowPolyPoint"); #endif return m_oDataTransport->sendData(Buffer, FinishUpPackage(Buffer, 11, m_bDeviceID)); @@ -271,32 +275,32 @@ bool protocolLGS_2D::getShadowStatus( uint8_t MaskID ){ if( m_oDataTransport == NULL ) return false; Buffer[CMD_IDX] = CMD_GET_HZ_STATUS; Buffer[SUB_CMD_IDX] = MaskID; // Future Use - Mask ID -#ifdef DEBUG +#ifdef DEBUG_EXTRA LOG("getShadowStatus");//CMD_GET_HZ_ENABLE #endif return m_oDataTransport->sendData(Buffer, FinishUpPackage(Buffer, 5, m_bDeviceID)); }; -bool protocolLGS_2D::getShadowInfo( void ){ +bool protocolLGS_2D::getShadowInfo( uint8_t sequence ){ U8 Buffer[16]; if( m_oDataTransport == NULL ) return false; Buffer[CMD_IDX] = CMD_GET_HZ_DATA; Buffer[SUB_CMD_IDX] = 0; Buffer[5] = HZIT_CMD_GET_HEADER; - Buffer[6] = 0; -#ifdef DEBUG + Buffer[6] = sequence; //0; +#ifdef DEBUG_EXTRA LOG("getShadowInfo"); #endif return m_oDataTransport->sendData(Buffer, FinishUpPackage(Buffer, 7, m_bDeviceID)); }; -bool protocolLGS_2D::setShadowInfo( SHADOW & SH ){ +bool protocolLGS_2D::setShadowInfo( uint8_t sequence, SHADOW & SH ){ uint8_t Buffer[20]; if( m_oDataTransport == NULL ) return false; Buffer[CMD_IDX] = CMD_SET_HZ_DATA; Buffer[SUB_CMD_IDX] = 8; Buffer[5] = HZIT_CMD_SET_HEADER; - Buffer[6] = 0; + Buffer[6] = sequence;//0; Buffer[7] = SH.m_nPolygonCount & 0xFF; Buffer[8] = ( SH.m_nPolygonCount >> 8 ) & 0xFF; Buffer[9] = 360 & 0xFF; @@ -305,37 +309,37 @@ bool protocolLGS_2D::setShadowInfo( SHADOW & SH ){ Buffer[12] = ( SH.m_nEnabled >> 8 ) & 0xFF; Buffer[13] = ( SH.m_nEnabled >> 16 ) & 0xFF; Buffer[14] = ( SH.m_nEnabled >> 24 ) & 0xFF; -#ifdef DEBUG +#ifdef DEBUG_EXTRA LOG("setShadowInfo"); #endif return m_oDataTransport->sendData(Buffer, FinishUpPackage(Buffer, 15, m_bDeviceID ) ); }; -bool protocolLGS_2D::setShadowPoly( SHADOW & SH, uint16_t PolyID ){ +bool protocolLGS_2D::setShadowPoly( uint8_t sequence, SHADOW & SH, uint16_t PolyID ){ uint8_t Buffer[20]; if( m_oDataTransport == NULL ) return false; Buffer[CMD_IDX] = CMD_SET_HZ_DATA; Buffer[SUB_CMD_IDX] = 5; Buffer[5] = HZIT_CMD_SET_POLYGON; - Buffer[6] = 0; + Buffer[6] = sequence;//0; Buffer[7] = PolyID & 0xFF; Buffer[8] = ( PolyID >> 8 ) & 0xFF; Buffer[9] = SH.pPolygones[PolyID].bType; Buffer[10] = SH.pPolygones[PolyID].wCount & 0xFF; Buffer[11] = ( SH.pPolygones[PolyID].wCount >> 8 ) & 0xFF; -#ifdef DEBUG +#ifdef DEBUG_EXTRA LOG("sendShadowPoly"); #endif return m_oDataTransport->sendData(Buffer, FinishUpPackage(Buffer, 12, m_bDeviceID ) ); }; -bool protocolLGS_2D::setShadowPolyPoint( SHADOW & SH, uint16_t PolyID, uint16_t PointID ){ +bool protocolLGS_2D::setShadowPolyPoint( uint8_t sequence, SHADOW & SH, uint16_t PolyID, uint16_t PointID ){ uint8_t Buffer[20]; if( m_oDataTransport == NULL ) return false; Buffer[CMD_IDX] = CMD_SET_HZ_DATA; Buffer[SUB_CMD_IDX] = 8; Buffer[5] = HZIT_CMD_SET_POLYGON_POINT; - Buffer[6] = 0; + Buffer[6] = sequence;//0; Buffer[7] = PolyID & 0xFF; Buffer[8] = ( PolyID >> 8 ) & 0xFF; Buffer[9] = PointID & 0xFF; @@ -344,34 +348,34 @@ bool protocolLGS_2D::setShadowPolyPoint( SHADOW & SH, uint16_t PolyID, uint16_t Buffer[12] = (SH.pPolygones[PolyID].pPoint[PointID].wX >> 8) & 0xFF; Buffer[13] = SH.pPolygones[PolyID].pPoint[PointID].wY & 0xFF; Buffer[14] = (SH.pPolygones[PolyID].pPoint[PointID].wY >> 8) & 0xFF; -#ifdef DEBUG +#ifdef DEBUG_EXTRA LOG("sendShadowPolyPoint"); #endif return m_oDataTransport->sendData(Buffer, FinishUpPackage(Buffer, 15, m_bDeviceID ) ); }; -bool protocolLGS_2D::setShadowRayLine( SHADOW & SH, uint16_t RLID ){ +bool protocolLGS_2D::setShadowRayLine( uint8_t sequence, SHADOW & SH, uint16_t RLID ){ uint8_t Buffer[20]; if( m_oDataTransport == NULL ) return false; Buffer[CMD_IDX] = CMD_SET_HZ_DATA; Buffer[SUB_CMD_IDX] = 4; Buffer[5] = HZIT_CMD_SET_RAY; - Buffer[6] = 0; + Buffer[6] = sequence;//0; Buffer[7] = RLID & 0xFF; Buffer[8] = ( RLID >> 8 ) & 0xFF; Buffer[9] = SH.ray_lines[RLID].nCount & 0xFF; Buffer[10] = ( SH.ray_lines[RLID].nCount >> 8 ) & 0xFF; -#ifdef DEBUG +#ifdef DEBUG_EXTRA LOG("setShadowRayLine"); #endif return m_oDataTransport->sendData(Buffer, FinishUpPackage(Buffer, 11, m_bDeviceID ) ); }; -bool protocolLGS_2D::setShadowRay( SHADOW & SH, uint16_t RLID, uint16_t RayID ){ +bool protocolLGS_2D::setShadowRay( uint8_t sequence, SHADOW & SH, uint16_t RLID, uint16_t RayID ){ uint8_t Buffer[20]; if( m_oDataTransport == NULL ) return false; Buffer[CMD_IDX] = CMD_SET_HZ_DATA; Buffer[SUB_CMD_IDX] = 9; Buffer[5] = HZIT_CMD_SET_RAY_LINE; - Buffer[6] = 0; + Buffer[6] = sequence;//0; Buffer[7] = RLID & 0xFF; Buffer[8] = ( RLID >> 8 ) & 0xFF; Buffer[9] = RayID & 0xFF; @@ -381,18 +385,18 @@ bool protocolLGS_2D::setShadowRay( SHADOW & SH, uint16_t RLID, uint16_t RayID ){ Buffer[13] = ( SH.ray_lines[RLID].rays[RayID].nMin >> 8 ) & 0xFF; Buffer[14] = SH.ray_lines[RLID].rays[RayID].nMax & 0xFF; Buffer[15] = ( SH.ray_lines[RLID].rays[RayID].nMax >> 8 ) & 0xFF; -#ifdef DEBUG +#ifdef DEBUG_EXTRA LOG("setShadowRay"); #endif return m_oDataTransport->sendData(Buffer, FinishUpPackage(Buffer, 16, m_bDeviceID ) ); }; -bool protocolLGS_2D::setShadowDone( void ){ +bool protocolLGS_2D::setShadowDone( uint8_t sequence ){ uint8_t Buffer[10]; if( m_oDataTransport == NULL ) return false; Buffer[CMD_IDX] = CMD_SET_HZ_DATA; Buffer[SUB_CMD_IDX] = 0; Buffer[5] = HZIT_CMD_SET_DONE; - Buffer[6] = 0; + Buffer[6] = sequence;//0; #ifdef DEBUG LOG("setShadowDone"); #endif @@ -402,7 +406,7 @@ bool protocolLGS_2D::getState( void ){ U8 Buffer[16]; if( m_oDataTransport == NULL ) return false; Buffer[CMD_IDX] = CMD_STATE; -#ifdef DEBUG +#ifdef DEBUG_EXTRA LOG("getState"); #endif return m_oDataTransport->sendData(Buffer, FinishUpPackage( Buffer, 4, m_bDeviceID)); @@ -417,8 +421,8 @@ bool protocolLGS_2D::getState2( void ){ #else Buffer[SUB_CMD_IDX] = 0x00; #endif -#ifdef DEBUG - //LOG("getState2"); +#ifdef DEBUG_EXTRA + LOG("getState2"); #endif return m_oDataTransport->sendData(Buffer, FinishUpPackage( Buffer, 5, m_bDeviceID)); }; @@ -428,7 +432,7 @@ bool protocolLGS_2D::setMode( U8 Mode ){ if( m_oDataTransport == NULL ) return false; Buffer[CMD_IDX] = CMD_MODE; Buffer[SUB_CMD_IDX] = Mode | 0x80; -#ifdef DEBUG +#ifdef DEBUG_EXTRA LOG("setMode"); #endif return m_oDataTransport->sendData(Buffer, FinishUpPackage(Buffer, 5, m_bDeviceID)); @@ -436,11 +440,10 @@ bool protocolLGS_2D::setMode( U8 Mode ){ bool protocolLGS_2D::getMode( void ){ U8 Buffer[16]; - LOG( "Try GetMode "); if( m_oDataTransport == NULL ) return false; Buffer[CMD_IDX] = CMD_MODE; Buffer[SUB_CMD_IDX] = 0x00; -#ifdef DEBUG +#ifdef DEBUG_EXTRA LOG("getMode"); #endif return m_oDataTransport->sendData(Buffer, FinishUpPackage(Buffer, 5, m_bDeviceID)); @@ -454,7 +457,7 @@ bool protocolLGS_2D::setShadowStatus( uint8_t Mask ){ Buffer[5] = 0x00; Buffer[6] = 0x00; Buffer[7] = 0x00; -#ifdef DEBUG +#ifdef DEBUG_EXTRA LOG("setShadowStatus"); #endif return m_oDataTransport->sendData(Buffer, FinishUpPackage(Buffer, 8, m_bDeviceID)); @@ -502,7 +505,7 @@ bool protocolLGS_2D::setComSpeed( uint32_t spd ){ Buffer[5] = ( spd >> 8 ) & 0xFF; Buffer[6] = ( spd >> 16 ) & 0xFF; Buffer[7] = ( spd >> 24 ) & 0xFF; -#ifdef DEBUG +#ifdef DEBUG_EXTRA LOG("setComSpeed"); #endif return m_oDataTransport->sendData(Buffer, FinishUpPackage(Buffer, 8, m_bDeviceID)); @@ -513,7 +516,7 @@ bool protocolLGS_2D::setDeviceAddress( uint8_t DeviceID, CSTR Serial ){ if( m_oDataTransport == NULL ) return false; Buffer[CMD_IDX] = CMD_SET_ADDRESS; Buffer[4] = DeviceID; -#ifdef DEBUG +#ifdef DEBUG_EXTRA LOG("setComSpeed"); #endif if ( Serial ) { @@ -534,7 +537,7 @@ bool protocolLGS_2D::setDetectionProfile( uint8_t profile ){ if( m_oDataTransport == NULL ) return false; Buffer[CMD_IDX] = CMD_SET_ACTIVE_PROFILE; Buffer[SUB_CMD_IDX] = profile; -#ifdef DEBUG +#ifdef DEBUG_EXTRA LOG("setDetectionProfile"); #endif return m_oDataTransport->sendData(Buffer, FinishUpPackage(Buffer, 5, m_bDeviceID)); @@ -563,7 +566,7 @@ bool protocolLGS_2D::setParameters( PLGS_2D_PARAMETERS ptr, bool MASTER, uint8_t Buffer[15] = (ptr->nSun >> 8) & 0xFF; Buffer[16] = ptr->nSun & 0xFF; Buffer[17] = ptr->bSST & 0xFF; -#ifdef DEBUG +#ifdef DEBUG_EXTRA LOG("setParameters"); #endif return m_oDataTransport->sendData(Buffer, FinishUpPackage(Buffer, 18, m_bDeviceID)); @@ -573,7 +576,7 @@ bool protocolLGS_2D::getSerialNumber( void ){ U8 Buffer[16]; if( m_oDataTransport == NULL ) return false; Buffer[CMD_IDX] = CMD_GET_SERIAL_NUMBER; -#ifdef DEBUG +#ifdef DEBUG_EXTRA LOG("getSerialNumber"); #endif return m_oDataTransport->sendData(Buffer, FinishUpPackage(Buffer, 4, m_bDeviceID)); @@ -583,7 +586,7 @@ bool protocolLGS_2D::getVersionString( void ){ U8 Buffer[16]; if( m_oDataTransport == NULL ) return false; Buffer[CMD_IDX] = CMD_GET_SOFTWARE_VERSION; -#ifdef DEBUG +#ifdef DEBUG_EXTRA LOG("getVersionString"); #endif return m_oDataTransport->sendData(Buffer, FinishUpPackage(Buffer, 4, m_bDeviceID)); @@ -593,7 +596,7 @@ bool protocolLGS_2D::getDetectionProfile( void ){ U8 Buffer[16]; if( m_oDataTransport == NULL ) return false; Buffer[CMD_IDX] = CMD_GET_ACTIVE_PROFILE; -#ifdef DEBUG +#ifdef DEBUG_EXTRA LOG("getDetectionProfile"); #endif return m_oDataTransport->sendData(Buffer, FinishUpPackage(Buffer, 4, m_bDeviceID)); @@ -635,14 +638,14 @@ bool protocolLGS_2D::sendFS_package( PFS_DATA pFSData ){ //case FS_CMD_RECEIVE_EVT: nCount += sizeof(FS_RECEIVE_EVT) + pFSData->receiveevt.nSubSize; break; default: break; }; -#ifdef DEBUG +#ifdef DEBUG_EXTRA LOG("sendFS_package"); -#endif for( uint8_t i = 0; i < nCount; i ++ ) { char tT[64]; sprintf( tT, "FS > Dev [%d] 0x%02X", i, Buffer[i] ); LOG( tT ); }; +#endif return m_oDataTransport->sendData(Buffer, FinishUpPackage( Buffer, nCount, m_bDeviceID ) ); }; diff --git a/lib/data/protocol/protocolLGS2D.h b/lib/data/protocol/protocolLGS2D.h index 86877de6..1ad1446f 100644 --- a/lib/data/protocol/protocolLGS2D.h +++ b/lib/data/protocol/protocolLGS2D.h @@ -7,7 +7,10 @@ #include "../../alg/lgs/mask.h" //#include "../../rgoose/rgooseTypes.h" -//#define LEGACY_2ZEROS_BEFORE_PACKAGE +#define LEGACY_2ZEROS_BEFORE_PACKAGE +#ifdef LEGACY_2ZEROS_BEFORE_PACKAGE + //#define LEGACY_2ZEROS_FROM_BOTH_SIDES +#endif //#include "../../App/common/dataBinder_structures.h" @@ -37,9 +40,9 @@ class protocolLGS_2D: public protocolParser{ bool getFastDraw( uint16_t Angle ); bool getParameters( bool MASTER = true ); bool getSerialNumber( void ); - bool getShadowInfo( void ); - bool getShadowPoly( uint16_t PolyID ); - bool getShadowPolyPoint( uint16_t PolyID, uint16_t PointID ); + bool getShadowInfo( uint8_t seq ); + bool getShadowPoly( uint8_t seq, uint16_t PolyID ); + bool getShadowPolyPoint( uint8_t seq, uint16_t PolyID, uint16_t PointID ); bool getShadowStatus( uint8_t MaskID = 0 ); bool getState( void ); bool getState2( void ); @@ -54,12 +57,12 @@ class protocolLGS_2D: public protocolParser{ bool setMode( U8 Mode ); bool setParameters( PLGS_2D_PARAMETERS ptr, bool MASTER = true, uint8_t profile = 0 ); - bool setShadowInfo( SHADOW & SH ); - bool setShadowPoly( SHADOW & SH, uint16_t PolyID ); - bool setShadowPolyPoint( SHADOW & SH, uint16_t PolyID, uint16_t PointID ); - bool setShadowRayLine( SHADOW & SH, uint16_t RLID ); - bool setShadowRay( SHADOW & SH, uint16_t RLID, uint16_t RayID ); - bool setShadowDone( void ); + bool setShadowInfo( uint8_t seq, SHADOW & SH ); + bool setShadowPoly( uint8_t seq, SHADOW & SH, uint16_t PolyID ); + bool setShadowPolyPoint( uint8_t seq, SHADOW & SH, uint16_t PolyID, uint16_t PointID ); + bool setShadowRayLine( uint8_t seq, SHADOW & SH, uint16_t RLID ); + bool setShadowRay( uint8_t seq, SHADOW & SH, uint16_t RLID, uint16_t RayID ); + bool setShadowDone( uint8_t seq ); bool setShadowStatus( uint8_t ShadowMask ); bool sendGF_package( uint8_t CMD, uint8_t cnt, uint8_t *Data ); bool sendFS_package( PFS_DATA pFSData ); diff --git a/lib/data/sqlite/sqlite_class.cpp b/lib/data/sqlite/sqlite_class.cpp index be0ab11a..97cb7710 100644 --- a/lib/data/sqlite/sqlite_class.cpp +++ b/lib/data/sqlite/sqlite_class.cpp @@ -6,6 +6,103 @@ static bool sqlite_global_config_is_set = false; static uint8_t sqlite_global_inctances_count = 0; +//https://www.sqlite.org/recovery.html +/* + +// * +// ** This function is called to recover data from the database. +// * / +static int recoverDatabase(sqlite3 *db){ + int rc; /* Return code from this routine * / + const char *zLAF = "lost_and_found"; /* Name of "lost_and_found" table * / + int bFreelist = 1; /* True to scan the freelist * / + int bRowids = 1; /* True to restore ROWID values * / + sqlite3_recover *p; /* The recovery object * / + + p = sqlite3_recover_init_sql(db, "main", recoverSqlCb, 0); + sqlite3_recover_config(p, SQLITE_RECOVER_LOST_AND_FOUND, (void*)zLAF); + sqlite3_recover_config(p, SQLITE_RECOVER_ROWIDS, (void*)&bRowids); + sqlite3_recover_config(p, SQLITE_RECOVER_FREELIST_CORRUPT,(void*)&bFreelist); + sqlite3_recover_run(p); + if( sqlite3_recover_errcode(p)!=SQLITE_OK ){ + const char *zErr = sqlite3_recover_errmsg(p); + int errCode = sqlite3_recover_errcode(p); + if( eVerbosity>0 ){ + printf("recovery error: %s (%d)\n", zErr, errCode); + } + } + rc = sqlite3_recover_finish(p); + if( eVerbosity>0 && rc ){ + printf("recovery returns error code %d\n", rc); + } + return rc; +} + +// * +// ** This function is called to recover data from the database. A script +// ** to construct a new database containing all recovered data is output +// ** on stream pState->out. +// * / +static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){ + int rc = SQLITE_OK; + const char *zRecoveryDb = ""; /* Name of "recovery" database. Debug only * / + const char *zLAF = "lost_and_found"; + int bFreelist = 1; /* 0 if --ignore-freelist is specified * / + int bRowids = 1; /* 0 if --no-rowids * / + sqlite3_recover *p = 0; + int i = 0; + + for(i=1; iout, azArg[0]); + return 1; + } + } + + p = sqlite3_recover_init_sql( + pState->db, "main", recoverSqlCb, (void*)pState + ); + + sqlite3_recover_config(p, 789, (void*)zRecoveryDb); /* Debug use only * / + sqlite3_recover_config(p, SQLITE_RECOVER_LOST_AND_FOUND, (void*)zLAF); + sqlite3_recover_config(p, SQLITE_RECOVER_ROWIDS, (void*)&bRowids); + sqlite3_recover_config(p, SQLITE_RECOVER_FREELIST_CORRUPT,(void*)&bFreelist); + + sqlite3_recover_run(p); + if( sqlite3_recover_errcode(p)!=SQLITE_OK ){ + const char *zErr = sqlite3_recover_errmsg(p); + int errCode = sqlite3_recover_errcode(p); + raw_printf(stderr, "sql error: %s (%d)\n", zErr, errCode); + } + rc = sqlite3_recover_finish(p); + return rc; +} + +*/ static void errorLogCallback( void *pArg, int iErrCode, const char *zMsg ){ char tB[1024]; diff --git a/lib/data/sqlite/sqlite_class.h b/lib/data/sqlite/sqlite_class.h index 6f96eb0c..aa060584 100644 --- a/lib/data/sqlite/sqlite_class.h +++ b/lib/data/sqlite/sqlite_class.h @@ -22,8 +22,6 @@ class SQLite_Connector{ char m_pDBName[MAX_PATH]; int m_nFLAGS; bool m_bPersistentConnection; - bool ReConnect( void ); - bool Disconnect( void ); public: SQLite_Connector(); SQLite_Connector( CSTR DBHost, CSTR DBUser, CSTR DBPassword, U16 Port = 3306 ); @@ -39,6 +37,8 @@ class SQLite_Connector{ bool SilentQuery( CSTR QS ); AAssoc * Query( CSTR QS, bool useCache = false ); void deleteResult( AAssoc *&R ); + bool ReConnect( void ); + bool Disconnect( void ); }; void deleteResult( AAssoc *&ptr ); diff --git a/lib/include/dbdata.c b/lib/include/dbdata.c new file mode 100644 index 00000000..e3bec33d --- /dev/null +++ b/lib/include/dbdata.c @@ -0,0 +1,955 @@ +/* +** 2019-04-17 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This file contains an implementation of two eponymous virtual tables, +** "sqlite_dbdata" and "sqlite_dbptr". Both modules require that the +** "sqlite_dbpage" eponymous virtual table be available. +** +** SQLITE_DBDATA: +** sqlite_dbdata is used to extract data directly from a database b-tree +** page and its associated overflow pages, bypassing the b-tree layer. +** The table schema is equivalent to: +** +** CREATE TABLE sqlite_dbdata( +** pgno INTEGER, +** cell INTEGER, +** field INTEGER, +** value ANY, +** schema TEXT HIDDEN +** ); +** +** IMPORTANT: THE VIRTUAL TABLE SCHEMA ABOVE IS SUBJECT TO CHANGE. IN THE +** FUTURE NEW NON-HIDDEN COLUMNS MAY BE ADDED BETWEEN "value" AND +** "schema". +** +** Each page of the database is inspected. If it cannot be interpreted as +** a b-tree page, or if it is a b-tree page containing 0 entries, the +** sqlite_dbdata table contains no rows for that page. Otherwise, the +** table contains one row for each field in the record associated with +** each cell on the page. For intkey b-trees, the key value is stored in +** field -1. +** +** For example, for the database: +** +** CREATE TABLE t1(a, b); -- root page is page 2 +** INSERT INTO t1(rowid, a, b) VALUES(5, 'v', 'five'); +** INSERT INTO t1(rowid, a, b) VALUES(10, 'x', 'ten'); +** +** the sqlite_dbdata table contains, as well as from entries related to +** page 1, content equivalent to: +** +** INSERT INTO sqlite_dbdata(pgno, cell, field, value) VALUES +** (2, 0, -1, 5 ), +** (2, 0, 0, 'v' ), +** (2, 0, 1, 'five'), +** (2, 1, -1, 10 ), +** (2, 1, 0, 'x' ), +** (2, 1, 1, 'ten' ); +** +** If database corruption is encountered, this module does not report an +** error. Instead, it attempts to extract as much data as possible and +** ignores the corruption. +** +** SQLITE_DBPTR: +** The sqlite_dbptr table has the following schema: +** +** CREATE TABLE sqlite_dbptr( +** pgno INTEGER, +** child INTEGER, +** schema TEXT HIDDEN +** ); +** +** It contains one entry for each b-tree pointer between a parent and +** child page in the database. +*/ + +#if !defined(SQLITEINT_H) +#include "sqlite3.h" + +typedef unsigned char u8; +typedef unsigned int u32; + +#endif +#include +#include + +#ifndef SQLITE_OMIT_VIRTUALTABLE + +#define DBDATA_PADDING_BYTES 100 + +typedef struct DbdataTable DbdataTable; +typedef struct DbdataCursor DbdataCursor; + +/* Cursor object */ +struct DbdataCursor { + sqlite3_vtab_cursor base; /* Base class. Must be first */ + sqlite3_stmt *pStmt; /* For fetching database pages */ + + int iPgno; /* Current page number */ + u8 *aPage; /* Buffer containing page */ + int nPage; /* Size of aPage[] in bytes */ + int nCell; /* Number of cells on aPage[] */ + int iCell; /* Current cell number */ + int bOnePage; /* True to stop after one page */ + int szDb; + sqlite3_int64 iRowid; + + /* Only for the sqlite_dbdata table */ + u8 *pRec; /* Buffer containing current record */ + sqlite3_int64 nRec; /* Size of pRec[] in bytes */ + sqlite3_int64 nHdr; /* Size of header in bytes */ + int iField; /* Current field number */ + u8 *pHdrPtr; + u8 *pPtr; + u32 enc; /* Text encoding */ + + sqlite3_int64 iIntkey; /* Integer key value */ +}; + +/* Table object */ +struct DbdataTable { + sqlite3_vtab base; /* Base class. Must be first */ + sqlite3 *db; /* The database connection */ + sqlite3_stmt *pStmt; /* For fetching database pages */ + int bPtr; /* True for sqlite3_dbptr table */ +}; + +/* Column and schema definitions for sqlite_dbdata */ +#define DBDATA_COLUMN_PGNO 0 +#define DBDATA_COLUMN_CELL 1 +#define DBDATA_COLUMN_FIELD 2 +#define DBDATA_COLUMN_VALUE 3 +#define DBDATA_COLUMN_SCHEMA 4 +#define DBDATA_SCHEMA \ + "CREATE TABLE x(" \ + " pgno INTEGER," \ + " cell INTEGER," \ + " field INTEGER," \ + " value ANY," \ + " schema TEXT HIDDEN" \ + ")" + +/* Column and schema definitions for sqlite_dbptr */ +#define DBPTR_COLUMN_PGNO 0 +#define DBPTR_COLUMN_CHILD 1 +#define DBPTR_COLUMN_SCHEMA 2 +#define DBPTR_SCHEMA \ + "CREATE TABLE x(" \ + " pgno INTEGER," \ + " child INTEGER," \ + " schema TEXT HIDDEN" \ + ")" + +/* +** Connect to an sqlite_dbdata (pAux==0) or sqlite_dbptr (pAux!=0) virtual +** table. +*/ +static int dbdataConnect( + sqlite3 *db, + void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVtab, + char **pzErr +){ + DbdataTable *pTab = 0; + int rc = sqlite3_declare_vtab(db, pAux ? DBPTR_SCHEMA : DBDATA_SCHEMA); + + (void)argc; + (void)argv; + (void)pzErr; + sqlite3_vtab_config(db, SQLITE_VTAB_USES_ALL_SCHEMAS); + if( rc==SQLITE_OK ){ + pTab = (DbdataTable*)sqlite3_malloc64(sizeof(DbdataTable)); + if( pTab==0 ){ + rc = SQLITE_NOMEM; + }else{ + memset(pTab, 0, sizeof(DbdataTable)); + pTab->db = db; + pTab->bPtr = (pAux!=0); + } + } + + *ppVtab = (sqlite3_vtab*)pTab; + return rc; +} + +/* +** Disconnect from or destroy a sqlite_dbdata or sqlite_dbptr virtual table. +*/ +static int dbdataDisconnect(sqlite3_vtab *pVtab){ + DbdataTable *pTab = (DbdataTable*)pVtab; + if( pTab ){ + sqlite3_finalize(pTab->pStmt); + sqlite3_free(pVtab); + } + return SQLITE_OK; +} + +/* +** This function interprets two types of constraints: +** +** schema=? +** pgno=? +** +** If neither are present, idxNum is set to 0. If schema=? is present, +** the 0x01 bit in idxNum is set. If pgno=? is present, the 0x02 bit +** in idxNum is set. +** +** If both parameters are present, schema is in position 0 and pgno in +** position 1. +*/ +static int dbdataBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdx){ + DbdataTable *pTab = (DbdataTable*)tab; + int i; + int iSchema = -1; + int iPgno = -1; + int colSchema = (pTab->bPtr ? DBPTR_COLUMN_SCHEMA : DBDATA_COLUMN_SCHEMA); + + for(i=0; inConstraint; i++){ + struct sqlite3_index_constraint *p = &pIdx->aConstraint[i]; + if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ){ + if( p->iColumn==colSchema ){ + if( p->usable==0 ) return SQLITE_CONSTRAINT; + iSchema = i; + } + if( p->iColumn==DBDATA_COLUMN_PGNO && p->usable ){ + iPgno = i; + } + } + } + + if( iSchema>=0 ){ + pIdx->aConstraintUsage[iSchema].argvIndex = 1; + pIdx->aConstraintUsage[iSchema].omit = 1; + } + if( iPgno>=0 ){ + pIdx->aConstraintUsage[iPgno].argvIndex = 1 + (iSchema>=0); + pIdx->aConstraintUsage[iPgno].omit = 1; + pIdx->estimatedCost = 100; + pIdx->estimatedRows = 50; + + if( pTab->bPtr==0 && pIdx->nOrderBy && pIdx->aOrderBy[0].desc==0 ){ + int iCol = pIdx->aOrderBy[0].iColumn; + if( pIdx->nOrderBy==1 ){ + pIdx->orderByConsumed = (iCol==0 || iCol==1); + }else if( pIdx->nOrderBy==2 && pIdx->aOrderBy[1].desc==0 && iCol==0 ){ + pIdx->orderByConsumed = (pIdx->aOrderBy[1].iColumn==1); + } + } + + }else{ + pIdx->estimatedCost = 100000000; + pIdx->estimatedRows = 1000000000; + } + pIdx->idxNum = (iSchema>=0 ? 0x01 : 0x00) | (iPgno>=0 ? 0x02 : 0x00); + return SQLITE_OK; +} + +/* +** Open a new sqlite_dbdata or sqlite_dbptr cursor. +*/ +static int dbdataOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){ + DbdataCursor *pCsr; + + pCsr = (DbdataCursor*)sqlite3_malloc64(sizeof(DbdataCursor)); + if( pCsr==0 ){ + return SQLITE_NOMEM; + }else{ + memset(pCsr, 0, sizeof(DbdataCursor)); + pCsr->base.pVtab = pVTab; + } + + *ppCursor = (sqlite3_vtab_cursor *)pCsr; + return SQLITE_OK; +} + +/* +** Restore a cursor object to the state it was in when first allocated +** by dbdataOpen(). +*/ +static void dbdataResetCursor(DbdataCursor *pCsr){ + DbdataTable *pTab = (DbdataTable*)(pCsr->base.pVtab); + if( pTab->pStmt==0 ){ + pTab->pStmt = pCsr->pStmt; + }else{ + sqlite3_finalize(pCsr->pStmt); + } + pCsr->pStmt = 0; + pCsr->iPgno = 1; + pCsr->iCell = 0; + pCsr->iField = 0; + pCsr->bOnePage = 0; + sqlite3_free(pCsr->aPage); + sqlite3_free(pCsr->pRec); + pCsr->pRec = 0; + pCsr->aPage = 0; +} + +/* +** Close an sqlite_dbdata or sqlite_dbptr cursor. +*/ +static int dbdataClose(sqlite3_vtab_cursor *pCursor){ + DbdataCursor *pCsr = (DbdataCursor*)pCursor; + dbdataResetCursor(pCsr); + sqlite3_free(pCsr); + return SQLITE_OK; +} + +/* +** Utility methods to decode 16 and 32-bit big-endian unsigned integers. +*/ +static u32 get_uint16(unsigned char *a){ + return (a[0]<<8)|a[1]; +} +static u32 get_uint32(unsigned char *a){ + return ((u32)a[0]<<24) + | ((u32)a[1]<<16) + | ((u32)a[2]<<8) + | ((u32)a[3]); +} + +/* +** Load page pgno from the database via the sqlite_dbpage virtual table. +** If successful, set (*ppPage) to point to a buffer containing the page +** data, (*pnPage) to the size of that buffer in bytes and return +** SQLITE_OK. In this case it is the responsibility of the caller to +** eventually free the buffer using sqlite3_free(). +** +** Or, if an error occurs, set both (*ppPage) and (*pnPage) to 0 and +** return an SQLite error code. +*/ +static int dbdataLoadPage( + DbdataCursor *pCsr, /* Cursor object */ + u32 pgno, /* Page number of page to load */ + u8 **ppPage, /* OUT: pointer to page buffer */ + int *pnPage /* OUT: Size of (*ppPage) in bytes */ +){ + int rc2; + int rc = SQLITE_OK; + sqlite3_stmt *pStmt = pCsr->pStmt; + + *ppPage = 0; + *pnPage = 0; + if( pgno>0 ){ + sqlite3_bind_int64(pStmt, 2, pgno); + if( SQLITE_ROW==sqlite3_step(pStmt) ){ + int nCopy = sqlite3_column_bytes(pStmt, 0); + if( nCopy>0 ){ + u8 *pPage; + pPage = (u8*)sqlite3_malloc64(nCopy + DBDATA_PADDING_BYTES); + if( pPage==0 ){ + rc = SQLITE_NOMEM; + }else{ + const u8 *pCopy = sqlite3_column_blob(pStmt, 0); + memcpy(pPage, pCopy, nCopy); + memset(&pPage[nCopy], 0, DBDATA_PADDING_BYTES); + } + *ppPage = pPage; + *pnPage = nCopy; + } + } + rc2 = sqlite3_reset(pStmt); + if( rc==SQLITE_OK ) rc = rc2; + } + + return rc; +} + +/* +** Read a varint. Put the value in *pVal and return the number of bytes. +*/ +static int dbdataGetVarint(const u8 *z, sqlite3_int64 *pVal){ + sqlite3_uint64 u = 0; + int i; + for(i=0; i<8; i++){ + u = (u<<7) + (z[i]&0x7f); + if( (z[i]&0x80)==0 ){ *pVal = (sqlite3_int64)u; return i+1; } + } + u = (u<<8) + (z[i]&0xff); + *pVal = (sqlite3_int64)u; + return 9; +} + +/* +** Like dbdataGetVarint(), but set the output to 0 if it is less than 0 +** or greater than 0xFFFFFFFF. This can be used for all varints in an +** SQLite database except for key values in intkey tables. +*/ +static int dbdataGetVarintU32(const u8 *z, sqlite3_int64 *pVal){ + sqlite3_int64 val; + int nRet = dbdataGetVarint(z, &val); + if( val<0 || val>0xFFFFFFFF ) val = 0; + *pVal = val; + return nRet; +} + +/* +** Return the number of bytes of space used by an SQLite value of type +** eType. +*/ +static int dbdataValueBytes(int eType){ + switch( eType ){ + case 0: case 8: case 9: + case 10: case 11: + return 0; + case 1: + return 1; + case 2: + return 2; + case 3: + return 3; + case 4: + return 4; + case 5: + return 6; + case 6: + case 7: + return 8; + default: + if( eType>0 ){ + return ((eType-12) / 2); + } + return 0; + } +} + +/* +** Load a value of type eType from buffer pData and use it to set the +** result of context object pCtx. +*/ +static void dbdataValue( + sqlite3_context *pCtx, + u32 enc, + int eType, + u8 *pData, + sqlite3_int64 nData +){ + if( eType>=0 && dbdataValueBytes(eType)<=nData ){ + switch( eType ){ + case 0: + case 10: + case 11: + sqlite3_result_null(pCtx); + break; + + case 8: + sqlite3_result_int(pCtx, 0); + break; + case 9: + sqlite3_result_int(pCtx, 1); + break; + + case 1: case 2: case 3: case 4: case 5: case 6: case 7: { + sqlite3_uint64 v = (signed char)pData[0]; + pData++; + switch( eType ){ + case 7: + case 6: v = (v<<16) + (pData[0]<<8) + pData[1]; pData += 2; + case 5: v = (v<<16) + (pData[0]<<8) + pData[1]; pData += 2; + case 4: v = (v<<8) + pData[0]; pData++; + case 3: v = (v<<8) + pData[0]; pData++; + case 2: v = (v<<8) + pData[0]; pData++; + } + + if( eType==7 ){ + double r; + memcpy(&r, &v, sizeof(r)); + sqlite3_result_double(pCtx, r); + }else{ + sqlite3_result_int64(pCtx, (sqlite3_int64)v); + } + break; + } + + default: { + int n = ((eType-12) / 2); + if( eType % 2 ){ + switch( enc ){ +#ifndef SQLITE_OMIT_UTF16 + case SQLITE_UTF16BE: + sqlite3_result_text16be(pCtx, (void*)pData, n, SQLITE_TRANSIENT); + break; + case SQLITE_UTF16LE: + sqlite3_result_text16le(pCtx, (void*)pData, n, SQLITE_TRANSIENT); + break; +#endif + default: + sqlite3_result_text(pCtx, (char*)pData, n, SQLITE_TRANSIENT); + break; + } + }else{ + sqlite3_result_blob(pCtx, pData, n, SQLITE_TRANSIENT); + } + } + } + } +} + +/* +** Move an sqlite_dbdata or sqlite_dbptr cursor to the next entry. +*/ +static int dbdataNext(sqlite3_vtab_cursor *pCursor){ + DbdataCursor *pCsr = (DbdataCursor*)pCursor; + DbdataTable *pTab = (DbdataTable*)pCursor->pVtab; + + pCsr->iRowid++; + while( 1 ){ + int rc; + int iOff = (pCsr->iPgno==1 ? 100 : 0); + int bNextPage = 0; + + if( pCsr->aPage==0 ){ + while( 1 ){ + if( pCsr->bOnePage==0 && pCsr->iPgno>pCsr->szDb ) return SQLITE_OK; + rc = dbdataLoadPage(pCsr, pCsr->iPgno, &pCsr->aPage, &pCsr->nPage); + if( rc!=SQLITE_OK ) return rc; + if( pCsr->aPage && pCsr->nPage>=256 ) break; + sqlite3_free(pCsr->aPage); + pCsr->aPage = 0; + if( pCsr->bOnePage ) return SQLITE_OK; + pCsr->iPgno++; + } + + assert( iOff+3+2<=pCsr->nPage ); + pCsr->iCell = pTab->bPtr ? -2 : 0; + pCsr->nCell = get_uint16(&pCsr->aPage[iOff+3]); + } + + if( pTab->bPtr ){ + if( pCsr->aPage[iOff]!=0x02 && pCsr->aPage[iOff]!=0x05 ){ + pCsr->iCell = pCsr->nCell; + } + pCsr->iCell++; + if( pCsr->iCell>=pCsr->nCell ){ + sqlite3_free(pCsr->aPage); + pCsr->aPage = 0; + if( pCsr->bOnePage ) return SQLITE_OK; + pCsr->iPgno++; + }else{ + return SQLITE_OK; + } + }else{ + /* If there is no record loaded, load it now. */ + if( pCsr->pRec==0 ){ + int bHasRowid = 0; + int nPointer = 0; + sqlite3_int64 nPayload = 0; + sqlite3_int64 nHdr = 0; + int iHdr; + int U, X; + int nLocal; + + switch( pCsr->aPage[iOff] ){ + case 0x02: + nPointer = 4; + break; + case 0x0a: + break; + case 0x0d: + bHasRowid = 1; + break; + default: + /* This is not a b-tree page with records on it. Continue. */ + pCsr->iCell = pCsr->nCell; + break; + } + + if( pCsr->iCell>=pCsr->nCell ){ + bNextPage = 1; + }else{ + + iOff += 8 + nPointer + pCsr->iCell*2; + if( iOff>pCsr->nPage ){ + bNextPage = 1; + }else{ + iOff = get_uint16(&pCsr->aPage[iOff]); + } + + /* For an interior node cell, skip past the child-page number */ + iOff += nPointer; + + /* Load the "byte of payload including overflow" field */ + if( bNextPage || iOff>pCsr->nPage ){ + bNextPage = 1; + }else{ + iOff += dbdataGetVarintU32(&pCsr->aPage[iOff], &nPayload); + } + + /* If this is a leaf intkey cell, load the rowid */ + if( bHasRowid && !bNextPage && iOffnPage ){ + iOff += dbdataGetVarint(&pCsr->aPage[iOff], &pCsr->iIntkey); + } + + /* Figure out how much data to read from the local page */ + U = pCsr->nPage; + if( bHasRowid ){ + X = U-35; + }else{ + X = ((U-12)*64/255)-23; + } + if( nPayload<=X ){ + nLocal = nPayload; + }else{ + int M, K; + M = ((U-12)*32/255)-23; + K = M+((nPayload-M)%(U-4)); + if( K<=X ){ + nLocal = K; + }else{ + nLocal = M; + } + } + + if( bNextPage || nLocal+iOff>pCsr->nPage ){ + bNextPage = 1; + }else{ + + /* Allocate space for payload. And a bit more to catch small buffer + ** overruns caused by attempting to read a varint or similar from + ** near the end of a corrupt record. */ + pCsr->pRec = (u8*)sqlite3_malloc64(nPayload+DBDATA_PADDING_BYTES); + if( pCsr->pRec==0 ) return SQLITE_NOMEM; + memset(pCsr->pRec, 0, nPayload+DBDATA_PADDING_BYTES); + pCsr->nRec = nPayload; + + /* Load the nLocal bytes of payload */ + memcpy(pCsr->pRec, &pCsr->aPage[iOff], nLocal); + iOff += nLocal; + + /* Load content from overflow pages */ + if( nPayload>nLocal ){ + sqlite3_int64 nRem = nPayload - nLocal; + u32 pgnoOvfl = get_uint32(&pCsr->aPage[iOff]); + while( nRem>0 ){ + u8 *aOvfl = 0; + int nOvfl = 0; + int nCopy; + rc = dbdataLoadPage(pCsr, pgnoOvfl, &aOvfl, &nOvfl); + assert( rc!=SQLITE_OK || aOvfl==0 || nOvfl==pCsr->nPage ); + if( rc!=SQLITE_OK ) return rc; + if( aOvfl==0 ) break; + + nCopy = U-4; + if( nCopy>nRem ) nCopy = nRem; + memcpy(&pCsr->pRec[nPayload-nRem], &aOvfl[4], nCopy); + nRem -= nCopy; + + pgnoOvfl = get_uint32(aOvfl); + sqlite3_free(aOvfl); + } + } + + iHdr = dbdataGetVarintU32(pCsr->pRec, &nHdr); + if( nHdr>nPayload ) nHdr = 0; + pCsr->nHdr = nHdr; + pCsr->pHdrPtr = &pCsr->pRec[iHdr]; + pCsr->pPtr = &pCsr->pRec[pCsr->nHdr]; + pCsr->iField = (bHasRowid ? -1 : 0); + } + } + }else{ + pCsr->iField++; + if( pCsr->iField>0 ){ + sqlite3_int64 iType; + if( pCsr->pHdrPtr>&pCsr->pRec[pCsr->nRec] ){ + bNextPage = 1; + }else{ + int szField = 0; + pCsr->pHdrPtr += dbdataGetVarintU32(pCsr->pHdrPtr, &iType); + szField = dbdataValueBytes(iType); + if( (pCsr->nRec - (pCsr->pPtr - pCsr->pRec))pPtr = &pCsr->pRec[pCsr->nRec]; + }else{ + pCsr->pPtr += szField; + } + } + } + } + + if( bNextPage ){ + sqlite3_free(pCsr->aPage); + sqlite3_free(pCsr->pRec); + pCsr->aPage = 0; + pCsr->pRec = 0; + if( pCsr->bOnePage ) return SQLITE_OK; + pCsr->iPgno++; + }else{ + if( pCsr->iField<0 || pCsr->pHdrPtr<&pCsr->pRec[pCsr->nHdr] ){ + return SQLITE_OK; + } + + /* Advance to the next cell. The next iteration of the loop will load + ** the record and so on. */ + sqlite3_free(pCsr->pRec); + pCsr->pRec = 0; + pCsr->iCell++; + } + } + } + + assert( !"can't get here" ); + return SQLITE_OK; +} + +/* +** Return true if the cursor is at EOF. +*/ +static int dbdataEof(sqlite3_vtab_cursor *pCursor){ + DbdataCursor *pCsr = (DbdataCursor*)pCursor; + return pCsr->aPage==0; +} + +/* +** Return true if nul-terminated string zSchema ends in "()". Or false +** otherwise. +*/ +static int dbdataIsFunction(const char *zSchema){ + size_t n = strlen(zSchema); + if( n>2 && zSchema[n-2]=='(' && zSchema[n-1]==')' ){ + return (int)n-2; + } + return 0; +} + +/* +** Determine the size in pages of database zSchema (where zSchema is +** "main", "temp" or the name of an attached database) and set +** pCsr->szDb accordingly. If successful, return SQLITE_OK. Otherwise, +** an SQLite error code. +*/ +static int dbdataDbsize(DbdataCursor *pCsr, const char *zSchema){ + DbdataTable *pTab = (DbdataTable*)pCsr->base.pVtab; + char *zSql = 0; + int rc, rc2; + int nFunc = 0; + sqlite3_stmt *pStmt = 0; + + if( (nFunc = dbdataIsFunction(zSchema))>0 ){ + zSql = sqlite3_mprintf("SELECT %.*s(0)", nFunc, zSchema); + }else{ + zSql = sqlite3_mprintf("PRAGMA %Q.page_count", zSchema); + } + if( zSql==0 ) return SQLITE_NOMEM; + + rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0); + sqlite3_free(zSql); + if( rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW ){ + pCsr->szDb = sqlite3_column_int(pStmt, 0); + } + rc2 = sqlite3_finalize(pStmt); + if( rc==SQLITE_OK ) rc = rc2; + return rc; +} + +/* +** Attempt to figure out the encoding of the database by retrieving page 1 +** and inspecting the header field. If successful, set the pCsr->enc variable +** and return SQLITE_OK. Otherwise, return an SQLite error code. +*/ +static int dbdataGetEncoding(DbdataCursor *pCsr){ + int rc = SQLITE_OK; + int nPg1 = 0; + u8 *aPg1 = 0; + rc = dbdataLoadPage(pCsr, 1, &aPg1, &nPg1); + if( rc==SQLITE_OK && nPg1>=(56+4) ){ + pCsr->enc = get_uint32(&aPg1[56]); + } + sqlite3_free(aPg1); + return rc; +} + + +/* +** xFilter method for sqlite_dbdata and sqlite_dbptr. +*/ +static int dbdataFilter( + sqlite3_vtab_cursor *pCursor, + int idxNum, const char *idxStr, + int argc, sqlite3_value **argv +){ + DbdataCursor *pCsr = (DbdataCursor*)pCursor; + DbdataTable *pTab = (DbdataTable*)pCursor->pVtab; + int rc = SQLITE_OK; + const char *zSchema = "main"; + (void)idxStr; + (void)argc; + + dbdataResetCursor(pCsr); + assert( pCsr->iPgno==1 ); + if( idxNum & 0x01 ){ + zSchema = (const char*)sqlite3_value_text(argv[0]); + if( zSchema==0 ) zSchema = ""; + } + if( idxNum & 0x02 ){ + pCsr->iPgno = sqlite3_value_int(argv[(idxNum & 0x01)]); + pCsr->bOnePage = 1; + }else{ + rc = dbdataDbsize(pCsr, zSchema); + } + + if( rc==SQLITE_OK ){ + int nFunc = 0; + if( pTab->pStmt ){ + pCsr->pStmt = pTab->pStmt; + pTab->pStmt = 0; + }else if( (nFunc = dbdataIsFunction(zSchema))>0 ){ + char *zSql = sqlite3_mprintf("SELECT %.*s(?2)", nFunc, zSchema); + if( zSql==0 ){ + rc = SQLITE_NOMEM; + }else{ + rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0); + sqlite3_free(zSql); + } + }else{ + rc = sqlite3_prepare_v2(pTab->db, + "SELECT data FROM sqlite_dbpage(?) WHERE pgno=?", -1, + &pCsr->pStmt, 0 + ); + } + } + if( rc==SQLITE_OK ){ + rc = sqlite3_bind_text(pCsr->pStmt, 1, zSchema, -1, SQLITE_TRANSIENT); + } + + /* Try to determine the encoding of the db by inspecting the header + ** field on page 1. */ + if( rc==SQLITE_OK ){ + rc = dbdataGetEncoding(pCsr); + } + + if( rc!=SQLITE_OK ){ + pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db)); + } + + if( rc==SQLITE_OK ){ + rc = dbdataNext(pCursor); + } + return rc; +} + +/* +** Return a column for the sqlite_dbdata or sqlite_dbptr table. +*/ +static int dbdataColumn( + sqlite3_vtab_cursor *pCursor, + sqlite3_context *ctx, + int i +){ + DbdataCursor *pCsr = (DbdataCursor*)pCursor; + DbdataTable *pTab = (DbdataTable*)pCursor->pVtab; + if( pTab->bPtr ){ + switch( i ){ + case DBPTR_COLUMN_PGNO: + sqlite3_result_int64(ctx, pCsr->iPgno); + break; + case DBPTR_COLUMN_CHILD: { + int iOff = pCsr->iPgno==1 ? 100 : 0; + if( pCsr->iCell<0 ){ + iOff += 8; + }else{ + iOff += 12 + pCsr->iCell*2; + if( iOff>pCsr->nPage ) return SQLITE_OK; + iOff = get_uint16(&pCsr->aPage[iOff]); + } + if( iOff<=pCsr->nPage ){ + sqlite3_result_int64(ctx, get_uint32(&pCsr->aPage[iOff])); + } + break; + } + } + }else{ + switch( i ){ + case DBDATA_COLUMN_PGNO: + sqlite3_result_int64(ctx, pCsr->iPgno); + break; + case DBDATA_COLUMN_CELL: + sqlite3_result_int(ctx, pCsr->iCell); + break; + case DBDATA_COLUMN_FIELD: + sqlite3_result_int(ctx, pCsr->iField); + break; + case DBDATA_COLUMN_VALUE: { + if( pCsr->iField<0 ){ + sqlite3_result_int64(ctx, pCsr->iIntkey); + }else if( &pCsr->pRec[pCsr->nRec] >= pCsr->pPtr ){ + sqlite3_int64 iType; + dbdataGetVarintU32(pCsr->pHdrPtr, &iType); + dbdataValue( + ctx, pCsr->enc, iType, pCsr->pPtr, + &pCsr->pRec[pCsr->nRec] - pCsr->pPtr + ); + } + break; + } + } + } + return SQLITE_OK; +} + +/* +** Return the rowid for an sqlite_dbdata or sqlite_dptr table. +*/ +static int dbdataRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){ + DbdataCursor *pCsr = (DbdataCursor*)pCursor; + *pRowid = pCsr->iRowid; + return SQLITE_OK; +} + + +/* +** Invoke this routine to register the "sqlite_dbdata" virtual table module +*/ +static int sqlite3DbdataRegister(sqlite3 *db){ + static sqlite3_module dbdata_module = { + 0, /* iVersion */ + 0, /* xCreate */ + dbdataConnect, /* xConnect */ + dbdataBestIndex, /* xBestIndex */ + dbdataDisconnect, /* xDisconnect */ + 0, /* xDestroy */ + dbdataOpen, /* xOpen - open a cursor */ + dbdataClose, /* xClose - close a cursor */ + dbdataFilter, /* xFilter - configure scan constraints */ + dbdataNext, /* xNext - advance a cursor */ + dbdataEof, /* xEof - check for end of scan */ + dbdataColumn, /* xColumn - read data */ + dbdataRowid, /* xRowid - read data */ + 0, /* xUpdate */ + 0, /* xBegin */ + 0, /* xSync */ + 0, /* xCommit */ + 0, /* xRollback */ + 0, /* xFindMethod */ + 0, /* xRename */ + 0, /* xSavepoint */ + 0, /* xRelease */ + 0, /* xRollbackTo */ + 0 /* xShadowName */ + }; + + int rc = sqlite3_create_module(db, "sqlite_dbdata", &dbdata_module, 0); + if( rc==SQLITE_OK ){ + rc = sqlite3_create_module(db, "sqlite_dbptr", &dbdata_module, (void*)1); + } + return rc; +} + +int sqlite3_dbdata_init( + sqlite3 *db, + char **pzErrMsg, + const sqlite3_api_routines *pApi +){ + (void)pzErrMsg; + return sqlite3DbdataRegister(db); +} + +#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */ diff --git a/lib/include/sqlite3recover.c b/lib/include/sqlite3recover.c new file mode 100644 index 00000000..c445c517 --- /dev/null +++ b/lib/include/sqlite3recover.c @@ -0,0 +1,2870 @@ +/* +** 2022-08-27 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +*/ + + +#include "sqlite3recover.h" +#include +#include + +#ifndef SQLITE_OMIT_VIRTUALTABLE + +/* +** Declaration for public API function in file dbdata.c. This may be called +** with NULL as the final two arguments to register the sqlite_dbptr and +** sqlite_dbdata virtual tables with a database handle. +*/ +#ifdef _WIN32 +__declspec(dllexport) +#endif +int sqlite3_dbdata_init(sqlite3*, char**, const sqlite3_api_routines*); + +typedef unsigned int u32; +typedef unsigned char u8; +typedef sqlite3_int64 i64; + +typedef struct RecoverTable RecoverTable; +typedef struct RecoverColumn RecoverColumn; + +/* +** When recovering rows of data that can be associated with table +** definitions recovered from the sqlite_schema table, each table is +** represented by an instance of the following object. +** +** iRoot: +** The root page in the original database. Not necessarily (and usually +** not) the same in the recovered database. +** +** zTab: +** Name of the table. +** +** nCol/aCol[]: +** aCol[] is an array of nCol columns. In the order in which they appear +** in the table. +** +** bIntkey: +** Set to true for intkey tables, false for WITHOUT ROWID. +** +** iRowidBind: +** Each column in the aCol[] array has associated with it the index of +** the bind parameter its values will be bound to in the INSERT statement +** used to construct the output database. If the table does has a rowid +** but not an INTEGER PRIMARY KEY column, then iRowidBind contains the +** index of the bind paramater to which the rowid value should be bound. +** Otherwise, it contains -1. If the table does contain an INTEGER PRIMARY +** KEY column, then the rowid value should be bound to the index associated +** with the column. +** +** pNext: +** All RecoverTable objects used by the recovery operation are allocated +** and populated as part of creating the recovered database schema in +** the output database, before any non-schema data are recovered. They +** are then stored in a singly-linked list linked by this variable beginning +** at sqlite3_recover.pTblList. +*/ +struct RecoverTable { + u32 iRoot; /* Root page in original database */ + char *zTab; /* Name of table */ + int nCol; /* Number of columns in table */ + RecoverColumn *aCol; /* Array of columns */ + int bIntkey; /* True for intkey, false for without rowid */ + int iRowidBind; /* If >0, bind rowid to INSERT here */ + RecoverTable *pNext; +}; + +/* +** Each database column is represented by an instance of the following object +** stored in the RecoverTable.aCol[] array of the associated table. +** +** iField: +** The index of the associated field within database records. Or -1 if +** there is no associated field (e.g. for virtual generated columns). +** +** iBind: +** The bind index of the INSERT statement to bind this columns values +** to. Or 0 if there is no such index (iff (iField<0)). +** +** bIPK: +** True if this is the INTEGER PRIMARY KEY column. +** +** zCol: +** Name of column. +** +** eHidden: +** A RECOVER_EHIDDEN_* constant value (see below for interpretation of each). +*/ +struct RecoverColumn { + int iField; /* Field in record on disk */ + int iBind; /* Binding to use in INSERT */ + int bIPK; /* True for IPK column */ + char *zCol; + int eHidden; +}; + +#define RECOVER_EHIDDEN_NONE 0 /* Normal database column */ +#define RECOVER_EHIDDEN_HIDDEN 1 /* Column is __HIDDEN__ */ +#define RECOVER_EHIDDEN_VIRTUAL 2 /* Virtual generated column */ +#define RECOVER_EHIDDEN_STORED 3 /* Stored generated column */ + +/* +** Bitmap object used to track pages in the input database. Allocated +** and manipulated only by the following functions: +** +** recoverBitmapAlloc() +** recoverBitmapFree() +** recoverBitmapSet() +** recoverBitmapQuery() +** +** nPg: +** Largest page number that may be stored in the bitmap. The range +** of valid keys is 1 to nPg, inclusive. +** +** aElem[]: +** Array large enough to contain a bit for each key. For key value +** iKey, the associated bit is the bit (iKey%32) of aElem[iKey/32]. +** In other words, the following is true if bit iKey is set, or +** false if it is clear: +** +** (aElem[iKey/32] & (1 << (iKey%32))) ? 1 : 0 +*/ +typedef struct RecoverBitmap RecoverBitmap; +struct RecoverBitmap { + i64 nPg; /* Size of bitmap */ + u32 aElem[1]; /* Array of 32-bit bitmasks */ +}; + +/* +** State variables (part of the sqlite3_recover structure) used while +** recovering data for tables identified in the recovered schema (state +** RECOVER_STATE_WRITING). +*/ +typedef struct RecoverStateW1 RecoverStateW1; +struct RecoverStateW1 { + sqlite3_stmt *pTbls; + sqlite3_stmt *pSel; + sqlite3_stmt *pInsert; + int nInsert; + + RecoverTable *pTab; /* Table currently being written */ + int nMax; /* Max column count in any schema table */ + sqlite3_value **apVal; /* Array of nMax values */ + int nVal; /* Number of valid entries in apVal[] */ + int bHaveRowid; + i64 iRowid; + i64 iPrevPage; + int iPrevCell; +}; + +/* +** State variables (part of the sqlite3_recover structure) used while +** recovering data destined for the lost and found table (states +** RECOVER_STATE_LOSTANDFOUND[123]). +*/ +typedef struct RecoverStateLAF RecoverStateLAF; +struct RecoverStateLAF { + RecoverBitmap *pUsed; + i64 nPg; /* Size of db in pages */ + sqlite3_stmt *pAllAndParent; + sqlite3_stmt *pMapInsert; + sqlite3_stmt *pMaxField; + sqlite3_stmt *pUsedPages; + sqlite3_stmt *pFindRoot; + sqlite3_stmt *pInsert; /* INSERT INTO lost_and_found ... */ + sqlite3_stmt *pAllPage; + sqlite3_stmt *pPageData; + sqlite3_value **apVal; + int nMaxField; +}; + +/* +** Main recover handle structure. +*/ +struct sqlite3_recover { + /* Copies of sqlite3_recover_init[_sql]() parameters */ + sqlite3 *dbIn; /* Input database */ + char *zDb; /* Name of input db ("main" etc.) */ + char *zUri; /* URI for output database */ + void *pSqlCtx; /* SQL callback context */ + int (*xSql)(void*,const char*); /* Pointer to SQL callback function */ + + /* Values configured by sqlite3_recover_config() */ + char *zStateDb; /* State database to use (or NULL) */ + char *zLostAndFound; /* Name of lost-and-found table (or NULL) */ + int bFreelistCorrupt; /* SQLITE_RECOVER_FREELIST_CORRUPT setting */ + int bRecoverRowid; /* SQLITE_RECOVER_ROWIDS setting */ + int bSlowIndexes; /* SQLITE_RECOVER_SLOWINDEXES setting */ + + int pgsz; + int detected_pgsz; + int nReserve; + u8 *pPage1Disk; + u8 *pPage1Cache; + + /* Error code and error message */ + int errCode; /* For sqlite3_recover_errcode() */ + char *zErrMsg; /* For sqlite3_recover_errmsg() */ + + int eState; + int bCloseTransaction; + + /* Variables used with eState==RECOVER_STATE_WRITING */ + RecoverStateW1 w1; + + /* Variables used with states RECOVER_STATE_LOSTANDFOUND[123] */ + RecoverStateLAF laf; + + /* Fields used within sqlite3_recover_run() */ + sqlite3 *dbOut; /* Output database */ + sqlite3_stmt *pGetPage; /* SELECT against input db sqlite_dbdata */ + RecoverTable *pTblList; /* List of tables recovered from schema */ +}; + +/* +** The various states in which an sqlite3_recover object may exist: +** +** RECOVER_STATE_INIT: +** The object is initially created in this state. sqlite3_recover_step() +** has yet to be called. This is the only state in which it is permitted +** to call sqlite3_recover_config(). +** +** RECOVER_STATE_WRITING: +** +** RECOVER_STATE_LOSTANDFOUND1: +** State to populate the bitmap of pages used by other tables or the +** database freelist. +** +** RECOVER_STATE_LOSTANDFOUND2: +** Populate the recovery.map table - used to figure out a "root" page +** for each lost page from in the database from which records are +** extracted. +** +** RECOVER_STATE_LOSTANDFOUND3: +** Populate the lost-and-found table itself. +*/ +#define RECOVER_STATE_INIT 0 +#define RECOVER_STATE_WRITING 1 +#define RECOVER_STATE_LOSTANDFOUND1 2 +#define RECOVER_STATE_LOSTANDFOUND2 3 +#define RECOVER_STATE_LOSTANDFOUND3 4 +#define RECOVER_STATE_SCHEMA2 5 +#define RECOVER_STATE_DONE 6 + + +/* +** Global variables used by this extension. +*/ +typedef struct RecoverGlobal RecoverGlobal; +struct RecoverGlobal { + const sqlite3_io_methods *pMethods; + sqlite3_recover *p; +}; +static RecoverGlobal recover_g; + +/* +** Use this static SQLite mutex to protect the globals during the +** first call to sqlite3_recover_step(). +*/ +#define RECOVER_MUTEX_ID SQLITE_MUTEX_STATIC_APP2 + + +/* +** Default value for SQLITE_RECOVER_ROWIDS (sqlite3_recover.bRecoverRowid). +*/ +#define RECOVER_ROWID_DEFAULT 1 + +/* +** Mutex handling: +** +** recoverEnterMutex() - Enter the recovery mutex +** recoverLeaveMutex() - Leave the recovery mutex +** recoverAssertMutexHeld() - Assert that the recovery mutex is held +*/ +#if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE==0 +# define recoverEnterMutex() +# define recoverLeaveMutex() +#else +static void recoverEnterMutex(void){ + sqlite3_mutex_enter(sqlite3_mutex_alloc(RECOVER_MUTEX_ID)); +} +static void recoverLeaveMutex(void){ + sqlite3_mutex_leave(sqlite3_mutex_alloc(RECOVER_MUTEX_ID)); +} +#endif +#if SQLITE_THREADSAFE+0>=1 && defined(SQLITE_DEBUG) +static void recoverAssertMutexHeld(void){ + assert( sqlite3_mutex_held(sqlite3_mutex_alloc(RECOVER_MUTEX_ID)) ); +} +#else +# define recoverAssertMutexHeld() +#endif + + +/* +** Like strlen(). But handles NULL pointer arguments. +*/ +static int recoverStrlen(const char *zStr){ + if( zStr==0 ) return 0; + return (int)(strlen(zStr)&0x7fffffff); +} + +/* +** This function is a no-op if the recover handle passed as the first +** argument already contains an error (if p->errCode!=SQLITE_OK). +** +** Otherwise, an attempt is made to allocate, zero and return a buffer nByte +** bytes in size. If successful, a pointer to the new buffer is returned. Or, +** if an OOM error occurs, NULL is returned and the handle error code +** (p->errCode) set to SQLITE_NOMEM. +*/ +static void *recoverMalloc(sqlite3_recover *p, i64 nByte){ + void *pRet = 0; + assert( nByte>0 ); + if( p->errCode==SQLITE_OK ){ + pRet = sqlite3_malloc64(nByte); + if( pRet ){ + memset(pRet, 0, nByte); + }else{ + p->errCode = SQLITE_NOMEM; + } + } + return pRet; +} + +/* +** Set the error code and error message for the recover handle passed as +** the first argument. The error code is set to the value of parameter +** errCode. +** +** Parameter zFmt must be a printf() style formatting string. The handle +** error message is set to the result of using any trailing arguments for +** parameter substitutions in the formatting string. +** +** For example: +** +** recoverError(p, SQLITE_ERROR, "no such table: %s", zTablename); +*/ +static int recoverError( + sqlite3_recover *p, + int errCode, + const char *zFmt, ... +){ + char *z = 0; + va_list ap; + va_start(ap, zFmt); + if( zFmt ){ + z = sqlite3_vmprintf(zFmt, ap); + va_end(ap); + } + sqlite3_free(p->zErrMsg); + p->zErrMsg = z; + p->errCode = errCode; + return errCode; +} + + +/* +** This function is a no-op if p->errCode is initially other than SQLITE_OK. +** In this case it returns NULL. +** +** Otherwise, an attempt is made to allocate and return a bitmap object +** large enough to store a bit for all page numbers between 1 and nPg, +** inclusive. The bitmap is initially zeroed. +*/ +static RecoverBitmap *recoverBitmapAlloc(sqlite3_recover *p, i64 nPg){ + int nElem = (nPg+1+31) / 32; + int nByte = sizeof(RecoverBitmap) + nElem*sizeof(u32); + RecoverBitmap *pRet = (RecoverBitmap*)recoverMalloc(p, nByte); + + if( pRet ){ + pRet->nPg = nPg; + } + return pRet; +} + +/* +** Free a bitmap object allocated by recoverBitmapAlloc(). +*/ +static void recoverBitmapFree(RecoverBitmap *pMap){ + sqlite3_free(pMap); +} + +/* +** Set the bit associated with page iPg in bitvec pMap. +*/ +static void recoverBitmapSet(RecoverBitmap *pMap, i64 iPg){ + if( iPg<=pMap->nPg ){ + int iElem = (iPg / 32); + int iBit = (iPg % 32); + pMap->aElem[iElem] |= (((u32)1) << iBit); + } +} + +/* +** Query bitmap object pMap for the state of the bit associated with page +** iPg. Return 1 if it is set, or 0 otherwise. +*/ +static int recoverBitmapQuery(RecoverBitmap *pMap, i64 iPg){ + int ret = 1; + if( iPg<=pMap->nPg && iPg>0 ){ + int iElem = (iPg / 32); + int iBit = (iPg % 32); + ret = (pMap->aElem[iElem] & (((u32)1) << iBit)) ? 1 : 0; + } + return ret; +} + +/* +** Set the recover handle error to the error code and message returned by +** calling sqlite3_errcode() and sqlite3_errmsg(), respectively, on database +** handle db. +*/ +static int recoverDbError(sqlite3_recover *p, sqlite3 *db){ + return recoverError(p, sqlite3_errcode(db), "%s", sqlite3_errmsg(db)); +} + +/* +** This function is a no-op if recover handle p already contains an error +** (if p->errCode!=SQLITE_OK). +** +** Otherwise, it attempts to prepare the SQL statement in zSql against +** database handle db. If successful, the statement handle is returned. +** Or, if an error occurs, NULL is returned and an error left in the +** recover handle. +*/ +static sqlite3_stmt *recoverPrepare( + sqlite3_recover *p, + sqlite3 *db, + const char *zSql +){ + sqlite3_stmt *pStmt = 0; + if( p->errCode==SQLITE_OK ){ + if( sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0) ){ + recoverDbError(p, db); + } + } + return pStmt; +} + +/* +** This function is a no-op if recover handle p already contains an error +** (if p->errCode!=SQLITE_OK). +** +** Otherwise, argument zFmt is used as a printf() style format string, +** along with any trailing arguments, to create an SQL statement. This +** SQL statement is prepared against database handle db and, if successful, +** the statment handle returned. Or, if an error occurs - either during +** the printf() formatting or when preparing the resulting SQL - an +** error code and message are left in the recover handle. +*/ +static sqlite3_stmt *recoverPreparePrintf( + sqlite3_recover *p, + sqlite3 *db, + const char *zFmt, ... +){ + sqlite3_stmt *pStmt = 0; + if( p->errCode==SQLITE_OK ){ + va_list ap; + char *z; + va_start(ap, zFmt); + z = sqlite3_vmprintf(zFmt, ap); + va_end(ap); + if( z==0 ){ + p->errCode = SQLITE_NOMEM; + }else{ + pStmt = recoverPrepare(p, db, z); + sqlite3_free(z); + } + } + return pStmt; +} + +/* +** Reset SQLite statement handle pStmt. If the call to sqlite3_reset() +** indicates that an error occurred, and there is not already an error +** in the recover handle passed as the first argument, set the error +** code and error message appropriately. +** +** This function returns a copy of the statement handle pointer passed +** as the second argument. +*/ +static sqlite3_stmt *recoverReset(sqlite3_recover *p, sqlite3_stmt *pStmt){ + int rc = sqlite3_reset(pStmt); + if( rc!=SQLITE_OK && rc!=SQLITE_CONSTRAINT && p->errCode==SQLITE_OK ){ + recoverDbError(p, sqlite3_db_handle(pStmt)); + } + return pStmt; +} + +/* +** Finalize SQLite statement handle pStmt. If the call to sqlite3_reset() +** indicates that an error occurred, and there is not already an error +** in the recover handle passed as the first argument, set the error +** code and error message appropriately. +*/ +static void recoverFinalize(sqlite3_recover *p, sqlite3_stmt *pStmt){ + sqlite3 *db = sqlite3_db_handle(pStmt); + int rc = sqlite3_finalize(pStmt); + if( rc!=SQLITE_OK && p->errCode==SQLITE_OK ){ + recoverDbError(p, db); + } +} + +/* +** This function is a no-op if recover handle p already contains an error +** (if p->errCode!=SQLITE_OK). A copy of p->errCode is returned in this +** case. +** +** Otherwise, execute SQL script zSql. If successful, return SQLITE_OK. +** Or, if an error occurs, leave an error code and message in the recover +** handle and return a copy of the error code. +*/ +static int recoverExec(sqlite3_recover *p, sqlite3 *db, const char *zSql){ + if( p->errCode==SQLITE_OK ){ + int rc = sqlite3_exec(db, zSql, 0, 0, 0); + if( rc ){ + recoverDbError(p, db); + } + } + return p->errCode; +} + +/* +** Bind the value pVal to parameter iBind of statement pStmt. Leave an +** error in the recover handle passed as the first argument if an error +** (e.g. an OOM) occurs. +*/ +static void recoverBindValue( + sqlite3_recover *p, + sqlite3_stmt *pStmt, + int iBind, + sqlite3_value *pVal +){ + if( p->errCode==SQLITE_OK ){ + int rc = sqlite3_bind_value(pStmt, iBind, pVal); + if( rc ) recoverError(p, rc, 0); + } +} + +/* +** This function is a no-op if recover handle p already contains an error +** (if p->errCode!=SQLITE_OK). NULL is returned in this case. +** +** Otherwise, an attempt is made to interpret zFmt as a printf() style +** formatting string and the result of using the trailing arguments for +** parameter substitution with it written into a buffer obtained from +** sqlite3_malloc(). If successful, a pointer to the buffer is returned. +** It is the responsibility of the caller to eventually free the buffer +** using sqlite3_free(). +** +** Or, if an error occurs, an error code and message is left in the recover +** handle and NULL returned. +*/ +static char *recoverMPrintf(sqlite3_recover *p, const char *zFmt, ...){ + va_list ap; + char *z; + va_start(ap, zFmt); + z = sqlite3_vmprintf(zFmt, ap); + va_end(ap); + if( p->errCode==SQLITE_OK ){ + if( z==0 ) p->errCode = SQLITE_NOMEM; + }else{ + sqlite3_free(z); + z = 0; + } + return z; +} + +/* +** This function is a no-op if recover handle p already contains an error +** (if p->errCode!=SQLITE_OK). Zero is returned in this case. +** +** Otherwise, execute "PRAGMA page_count" against the input database. If +** successful, return the integer result. Or, if an error occurs, leave an +** error code and error message in the sqlite3_recover handle and return +** zero. +*/ +static i64 recoverPageCount(sqlite3_recover *p){ + i64 nPg = 0; + if( p->errCode==SQLITE_OK ){ + sqlite3_stmt *pStmt = 0; + pStmt = recoverPreparePrintf(p, p->dbIn, "PRAGMA %Q.page_count", p->zDb); + if( pStmt ){ + sqlite3_step(pStmt); + nPg = sqlite3_column_int64(pStmt, 0); + } + recoverFinalize(p, pStmt); + } + return nPg; +} + +/* +** Implementation of SQL scalar function "read_i32". The first argument to +** this function must be a blob. The second a non-negative integer. This +** function reads and returns a 32-bit big-endian integer from byte +** offset (4*) of the blob. +** +** SELECT read_i32(, ) +*/ +static void recoverReadI32( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + const unsigned char *pBlob; + int nBlob; + int iInt; + + assert( argc==2 ); + nBlob = sqlite3_value_bytes(argv[0]); + pBlob = (const unsigned char*)sqlite3_value_blob(argv[0]); + iInt = sqlite3_value_int(argv[1]) & 0xFFFF; + + if( (iInt+1)*4<=nBlob ){ + const unsigned char *a = &pBlob[iInt*4]; + i64 iVal = ((i64)a[0]<<24) + + ((i64)a[1]<<16) + + ((i64)a[2]<< 8) + + ((i64)a[3]<< 0); + sqlite3_result_int64(context, iVal); + } +} + +/* +** Implementation of SQL scalar function "page_is_used". This function +** is used as part of the procedure for locating orphan rows for the +** lost-and-found table, and it depends on those routines having populated +** the sqlite3_recover.laf.pUsed variable. +** +** The only argument to this function is a page-number. It returns true +** if the page has already been used somehow during data recovery, or false +** otherwise. +** +** SELECT page_is_used(); +*/ +static void recoverPageIsUsed( + sqlite3_context *pCtx, + int nArg, + sqlite3_value **apArg +){ + sqlite3_recover *p = (sqlite3_recover*)sqlite3_user_data(pCtx); + i64 pgno = sqlite3_value_int64(apArg[0]); + assert( nArg==1 ); + sqlite3_result_int(pCtx, recoverBitmapQuery(p->laf.pUsed, pgno)); +} + +/* +** The implementation of a user-defined SQL function invoked by the +** sqlite_dbdata and sqlite_dbptr virtual table modules to access pages +** of the database being recovered. +** +** This function always takes a single integer argument. If the argument +** is zero, then the value returned is the number of pages in the db being +** recovered. If the argument is greater than zero, it is a page number. +** The value returned in this case is an SQL blob containing the data for +** the identified page of the db being recovered. e.g. +** +** SELECT getpage(0); -- return number of pages in db +** SELECT getpage(4); -- return page 4 of db as a blob of data +*/ +static void recoverGetPage( + sqlite3_context *pCtx, + int nArg, + sqlite3_value **apArg +){ + sqlite3_recover *p = (sqlite3_recover*)sqlite3_user_data(pCtx); + i64 pgno = sqlite3_value_int64(apArg[0]); + sqlite3_stmt *pStmt = 0; + + assert( nArg==1 ); + if( pgno==0 ){ + i64 nPg = recoverPageCount(p); + sqlite3_result_int64(pCtx, nPg); + return; + }else{ + if( p->pGetPage==0 ){ + pStmt = p->pGetPage = recoverPreparePrintf( + p, p->dbIn, "SELECT data FROM sqlite_dbpage(%Q) WHERE pgno=?", p->zDb + ); + }else if( p->errCode==SQLITE_OK ){ + pStmt = p->pGetPage; + } + + if( pStmt ){ + sqlite3_bind_int64(pStmt, 1, pgno); + if( SQLITE_ROW==sqlite3_step(pStmt) ){ + const u8 *aPg; + int nPg; + assert( p->errCode==SQLITE_OK ); + aPg = sqlite3_column_blob(pStmt, 0); + nPg = sqlite3_column_bytes(pStmt, 0); + if( pgno==1 && nPg==p->pgsz && 0==memcmp(p->pPage1Cache, aPg, nPg) ){ + aPg = p->pPage1Disk; + } + sqlite3_result_blob(pCtx, aPg, nPg-p->nReserve, SQLITE_TRANSIENT); + } + recoverReset(p, pStmt); + } + } + + if( p->errCode ){ + if( p->zErrMsg ) sqlite3_result_error(pCtx, p->zErrMsg, -1); + sqlite3_result_error_code(pCtx, p->errCode); + } +} + +/* +** Find a string that is not found anywhere in z[]. Return a pointer +** to that string. +** +** Try to use zA and zB first. If both of those are already found in z[] +** then make up some string and store it in the buffer zBuf. +*/ +static const char *recoverUnusedString( + const char *z, /* Result must not appear anywhere in z */ + const char *zA, const char *zB, /* Try these first */ + char *zBuf /* Space to store a generated string */ +){ + unsigned i = 0; + if( strstr(z, zA)==0 ) return zA; + if( strstr(z, zB)==0 ) return zB; + do{ + sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++); + }while( strstr(z,zBuf)!=0 ); + return zBuf; +} + +/* +** Implementation of scalar SQL function "escape_crnl". The argument passed to +** this function is the output of built-in function quote(). If the first +** character of the input is "'", indicating that the value passed to quote() +** was a text value, then this function searches the input for "\n" and "\r" +** characters and adds a wrapper similar to the following: +** +** replace(replace(, '\n', char(10), '\r', char(13)); +** +** Or, if the first character of the input is not "'", then a copy of the input +** is returned. +*/ +static void recoverEscapeCrnl( + sqlite3_context *context, + int argc, + sqlite3_value **argv +){ + const char *zText = (const char*)sqlite3_value_text(argv[0]); + (void)argc; + if( zText && zText[0]=='\'' ){ + int nText = sqlite3_value_bytes(argv[0]); + int i; + char zBuf1[20]; + char zBuf2[20]; + const char *zNL = 0; + const char *zCR = 0; + int nCR = 0; + int nNL = 0; + + for(i=0; zText[i]; i++){ + if( zNL==0 && zText[i]=='\n' ){ + zNL = recoverUnusedString(zText, "\\n", "\\012", zBuf1); + nNL = (int)strlen(zNL); + } + if( zCR==0 && zText[i]=='\r' ){ + zCR = recoverUnusedString(zText, "\\r", "\\015", zBuf2); + nCR = (int)strlen(zCR); + } + } + + if( zNL || zCR ){ + int iOut = 0; + i64 nMax = (nNL > nCR) ? nNL : nCR; + i64 nAlloc = nMax * nText + (nMax+64)*2; + char *zOut = (char*)sqlite3_malloc64(nAlloc); + if( zOut==0 ){ + sqlite3_result_error_nomem(context); + return; + } + + if( zNL && zCR ){ + memcpy(&zOut[iOut], "replace(replace(", 16); + iOut += 16; + }else{ + memcpy(&zOut[iOut], "replace(", 8); + iOut += 8; + } + for(i=0; zText[i]; i++){ + if( zText[i]=='\n' ){ + memcpy(&zOut[iOut], zNL, nNL); + iOut += nNL; + }else if( zText[i]=='\r' ){ + memcpy(&zOut[iOut], zCR, nCR); + iOut += nCR; + }else{ + zOut[iOut] = zText[i]; + iOut++; + } + } + + if( zNL ){ + memcpy(&zOut[iOut], ",'", 2); iOut += 2; + memcpy(&zOut[iOut], zNL, nNL); iOut += nNL; + memcpy(&zOut[iOut], "', char(10))", 12); iOut += 12; + } + if( zCR ){ + memcpy(&zOut[iOut], ",'", 2); iOut += 2; + memcpy(&zOut[iOut], zCR, nCR); iOut += nCR; + memcpy(&zOut[iOut], "', char(13))", 12); iOut += 12; + } + + sqlite3_result_text(context, zOut, iOut, SQLITE_TRANSIENT); + sqlite3_free(zOut); + return; + } + } + + sqlite3_result_value(context, argv[0]); +} + +/* +** This function is a no-op if recover handle p already contains an error +** (if p->errCode!=SQLITE_OK). A copy of the error code is returned in +** this case. +** +** Otherwise, attempt to populate temporary table "recovery.schema" with the +** parts of the database schema that can be extracted from the input database. +** +** If no error occurs, SQLITE_OK is returned. Otherwise, an error code +** and error message are left in the recover handle and a copy of the +** error code returned. It is not considered an error if part of all of +** the database schema cannot be recovered due to corruption. +*/ +static int recoverCacheSchema(sqlite3_recover *p){ + return recoverExec(p, p->dbOut, + "WITH RECURSIVE pages(p) AS (" + " SELECT 1" + " UNION" + " SELECT child FROM sqlite_dbptr('getpage()'), pages WHERE pgno=p" + ")" + "INSERT INTO recovery.schema SELECT" + " max(CASE WHEN field=0 THEN value ELSE NULL END)," + " max(CASE WHEN field=1 THEN value ELSE NULL END)," + " max(CASE WHEN field=2 THEN value ELSE NULL END)," + " max(CASE WHEN field=3 THEN value ELSE NULL END)," + " max(CASE WHEN field=4 THEN value ELSE NULL END)" + "FROM sqlite_dbdata('getpage()') WHERE pgno IN (" + " SELECT p FROM pages" + ") GROUP BY pgno, cell" + ); +} + +/* +** If this recover handle is not in SQL callback mode (i.e. was not created +** using sqlite3_recover_init_sql()) of if an error has already occurred, +** this function is a no-op. Otherwise, issue a callback with SQL statement +** zSql as the parameter. +** +** If the callback returns non-zero, set the recover handle error code to +** the value returned (so that the caller will abandon processing). +*/ +static void recoverSqlCallback(sqlite3_recover *p, const char *zSql){ + if( p->errCode==SQLITE_OK && p->xSql ){ + int res = p->xSql(p->pSqlCtx, zSql); + if( res ){ + recoverError(p, SQLITE_ERROR, "callback returned an error - %d", res); + } + } +} + +/* +** Transfer the following settings from the input database to the output +** database: +** +** + page-size, +** + auto-vacuum settings, +** + database encoding, +** + user-version (PRAGMA user_version), and +** + application-id (PRAGMA application_id), and +*/ +static void recoverTransferSettings(sqlite3_recover *p){ + const char *aPragma[] = { + "encoding", + "page_size", + "auto_vacuum", + "user_version", + "application_id" + }; + int ii; + + /* Truncate the output database to 0 pages in size. This is done by + ** opening a new, empty, temp db, then using the backup API to clobber + ** any existing output db with a copy of it. */ + if( p->errCode==SQLITE_OK ){ + sqlite3 *db2 = 0; + int rc = sqlite3_open("", &db2); + if( rc!=SQLITE_OK ){ + recoverDbError(p, db2); + return; + } + + for(ii=0; ii<(int)(sizeof(aPragma)/sizeof(aPragma[0])); ii++){ + const char *zPrag = aPragma[ii]; + sqlite3_stmt *p1 = 0; + p1 = recoverPreparePrintf(p, p->dbIn, "PRAGMA %Q.%s", p->zDb, zPrag); + if( p->errCode==SQLITE_OK && sqlite3_step(p1)==SQLITE_ROW ){ + const char *zArg = (const char*)sqlite3_column_text(p1, 0); + char *z2 = recoverMPrintf(p, "PRAGMA %s = %Q", zPrag, zArg); + recoverSqlCallback(p, z2); + recoverExec(p, db2, z2); + sqlite3_free(z2); + if( zArg==0 ){ + recoverError(p, SQLITE_NOMEM, 0); + } + } + recoverFinalize(p, p1); + } + recoverExec(p, db2, "CREATE TABLE t1(a); DROP TABLE t1;"); + + if( p->errCode==SQLITE_OK ){ + sqlite3 *db = p->dbOut; + sqlite3_backup *pBackup = sqlite3_backup_init(db, "main", db2, "main"); + if( pBackup ){ + sqlite3_backup_step(pBackup, -1); + p->errCode = sqlite3_backup_finish(pBackup); + }else{ + recoverDbError(p, db); + } + } + + sqlite3_close(db2); + } +} + +/* +** This function is a no-op if recover handle p already contains an error +** (if p->errCode!=SQLITE_OK). A copy of the error code is returned in +** this case. +** +** Otherwise, an attempt is made to open the output database, attach +** and create the schema of the temporary database used to store +** intermediate data, and to register all required user functions and +** virtual table modules with the output handle. +** +** If no error occurs, SQLITE_OK is returned. Otherwise, an error code +** and error message are left in the recover handle and a copy of the +** error code returned. +*/ +static int recoverOpenOutput(sqlite3_recover *p){ + struct Func { + const char *zName; + int nArg; + void (*xFunc)(sqlite3_context*,int,sqlite3_value **); + } aFunc[] = { + { "getpage", 1, recoverGetPage }, + { "page_is_used", 1, recoverPageIsUsed }, + { "read_i32", 2, recoverReadI32 }, + { "escape_crnl", 1, recoverEscapeCrnl }, + }; + + const int flags = SQLITE_OPEN_URI|SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE; + sqlite3 *db = 0; /* New database handle */ + int ii; /* For iterating through aFunc[] */ + + assert( p->dbOut==0 ); + + if( sqlite3_open_v2(p->zUri, &db, flags, 0) ){ + recoverDbError(p, db); + } + + /* Register the sqlite_dbdata and sqlite_dbptr virtual table modules. + ** These two are registered with the output database handle - this + ** module depends on the input handle supporting the sqlite_dbpage + ** virtual table only. */ + if( p->errCode==SQLITE_OK ){ + p->errCode = sqlite3_dbdata_init(db, 0, 0); + } + + /* Register the custom user-functions with the output handle. */ + for(ii=0; + p->errCode==SQLITE_OK && ii<(int)(sizeof(aFunc)/sizeof(aFunc[0])); + ii++){ + p->errCode = sqlite3_create_function(db, aFunc[ii].zName, + aFunc[ii].nArg, SQLITE_UTF8, (void*)p, aFunc[ii].xFunc, 0, 0 + ); + } + + p->dbOut = db; + return p->errCode; +} + +/* +** Attach the auxiliary database 'recovery' to the output database handle. +** This temporary database is used during the recovery process and then +** discarded. +*/ +static void recoverOpenRecovery(sqlite3_recover *p){ + char *zSql = recoverMPrintf(p, "ATTACH %Q AS recovery;", p->zStateDb); + recoverExec(p, p->dbOut, zSql); + recoverExec(p, p->dbOut, + "PRAGMA writable_schema = 1;" + "CREATE TABLE recovery.map(pgno INTEGER PRIMARY KEY, parent INT);" + "CREATE TABLE recovery.schema(type, name, tbl_name, rootpage, sql);" + ); + sqlite3_free(zSql); +} + + +/* +** This function is a no-op if recover handle p already contains an error +** (if p->errCode!=SQLITE_OK). +** +** Otherwise, argument zName must be the name of a table that has just been +** created in the output database. This function queries the output db +** for the schema of said table, and creates a RecoverTable object to +** store the schema in memory. The new RecoverTable object is linked into +** the list at sqlite3_recover.pTblList. +** +** Parameter iRoot must be the root page of table zName in the INPUT +** database. +*/ +static void recoverAddTable( + sqlite3_recover *p, + const char *zName, /* Name of table created in output db */ + i64 iRoot /* Root page of same table in INPUT db */ +){ + sqlite3_stmt *pStmt = recoverPreparePrintf(p, p->dbOut, + "PRAGMA table_xinfo(%Q)", zName + ); + + if( pStmt ){ + int iPk = -1; + int iBind = 1; + RecoverTable *pNew = 0; + int nCol = 0; + int nName = recoverStrlen(zName); + int nByte = 0; + while( sqlite3_step(pStmt)==SQLITE_ROW ){ + nCol++; + nByte += (sqlite3_column_bytes(pStmt, 1)+1); + } + nByte += sizeof(RecoverTable) + nCol*sizeof(RecoverColumn) + nName+1; + recoverReset(p, pStmt); + + pNew = recoverMalloc(p, nByte); + if( pNew ){ + int i = 0; + int iField = 0; + char *csr = 0; + pNew->aCol = (RecoverColumn*)&pNew[1]; + pNew->zTab = csr = (char*)&pNew->aCol[nCol]; + pNew->nCol = nCol; + pNew->iRoot = iRoot; + memcpy(csr, zName, nName); + csr += nName+1; + + for(i=0; sqlite3_step(pStmt)==SQLITE_ROW; i++){ + int iPKF = sqlite3_column_int(pStmt, 5); + int n = sqlite3_column_bytes(pStmt, 1); + const char *z = (const char*)sqlite3_column_text(pStmt, 1); + const char *zType = (const char*)sqlite3_column_text(pStmt, 2); + int eHidden = sqlite3_column_int(pStmt, 6); + + if( iPk==-1 && iPKF==1 && !sqlite3_stricmp("integer", zType) ) iPk = i; + if( iPKF>1 ) iPk = -2; + pNew->aCol[i].zCol = csr; + pNew->aCol[i].eHidden = eHidden; + if( eHidden==RECOVER_EHIDDEN_VIRTUAL ){ + pNew->aCol[i].iField = -1; + }else{ + pNew->aCol[i].iField = iField++; + } + if( eHidden!=RECOVER_EHIDDEN_VIRTUAL + && eHidden!=RECOVER_EHIDDEN_STORED + ){ + pNew->aCol[i].iBind = iBind++; + } + memcpy(csr, z, n); + csr += (n+1); + } + + pNew->pNext = p->pTblList; + p->pTblList = pNew; + pNew->bIntkey = 1; + } + + recoverFinalize(p, pStmt); + + pStmt = recoverPreparePrintf(p, p->dbOut, "PRAGMA index_xinfo(%Q)", zName); + while( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){ + int iField = sqlite3_column_int(pStmt, 0); + int iCol = sqlite3_column_int(pStmt, 1); + + assert( iColnCol ); + pNew->aCol[iCol].iField = iField; + + pNew->bIntkey = 0; + iPk = -2; + } + recoverFinalize(p, pStmt); + + if( p->errCode==SQLITE_OK ){ + if( iPk>=0 ){ + pNew->aCol[iPk].bIPK = 1; + }else if( pNew->bIntkey ){ + pNew->iRowidBind = iBind++; + } + } + } +} + +/* +** This function is called after recoverCacheSchema() has cached those parts +** of the input database schema that could be recovered in temporary table +** "recovery.schema". This function creates in the output database copies +** of all parts of that schema that must be created before the tables can +** be populated. Specifically, this means: +** +** * all tables that are not VIRTUAL, and +** * UNIQUE indexes. +** +** If the recovery handle uses SQL callbacks, then callbacks containing +** the associated "CREATE TABLE" and "CREATE INDEX" statements are made. +** +** Additionally, records are added to the sqlite_schema table of the +** output database for any VIRTUAL tables. The CREATE VIRTUAL TABLE +** records are written directly to sqlite_schema, not actually executed. +** If the handle is in SQL callback mode, then callbacks are invoked +** with equivalent SQL statements. +*/ +static int recoverWriteSchema1(sqlite3_recover *p){ + sqlite3_stmt *pSelect = 0; + sqlite3_stmt *pTblname = 0; + + pSelect = recoverPrepare(p, p->dbOut, + "WITH dbschema(rootpage, name, sql, tbl, isVirtual, isIndex) AS (" + " SELECT rootpage, name, sql, " + " type='table', " + " sql LIKE 'create virtual%'," + " (type='index' AND (sql LIKE '%unique%' OR ?1))" + " FROM recovery.schema" + ")" + "SELECT rootpage, tbl, isVirtual, name, sql" + " FROM dbschema " + " WHERE tbl OR isIndex" + " ORDER BY tbl DESC, name=='sqlite_sequence' DESC" + ); + + pTblname = recoverPrepare(p, p->dbOut, + "SELECT name FROM sqlite_schema " + "WHERE type='table' ORDER BY rowid DESC LIMIT 1" + ); + + if( pSelect ){ + sqlite3_bind_int(pSelect, 1, p->bSlowIndexes); + while( sqlite3_step(pSelect)==SQLITE_ROW ){ + i64 iRoot = sqlite3_column_int64(pSelect, 0); + int bTable = sqlite3_column_int(pSelect, 1); + int bVirtual = sqlite3_column_int(pSelect, 2); + const char *zName = (const char*)sqlite3_column_text(pSelect, 3); + const char *zSql = (const char*)sqlite3_column_text(pSelect, 4); + char *zFree = 0; + int rc = SQLITE_OK; + + if( bVirtual ){ + zSql = (const char*)(zFree = recoverMPrintf(p, + "INSERT INTO sqlite_schema VALUES('table', %Q, %Q, 0, %Q)", + zName, zName, zSql + )); + } + rc = sqlite3_exec(p->dbOut, zSql, 0, 0, 0); + if( rc==SQLITE_OK ){ + recoverSqlCallback(p, zSql); + if( bTable && !bVirtual ){ + if( SQLITE_ROW==sqlite3_step(pTblname) ){ + const char *zTbl = (const char*)sqlite3_column_text(pTblname, 0); + recoverAddTable(p, zTbl, iRoot); + } + recoverReset(p, pTblname); + } + }else if( rc!=SQLITE_ERROR ){ + recoverDbError(p, p->dbOut); + } + sqlite3_free(zFree); + } + } + recoverFinalize(p, pSelect); + recoverFinalize(p, pTblname); + + return p->errCode; +} + +/* +** This function is called after the output database has been populated. It +** adds all recovered schema elements that were not created in the output +** database by recoverWriteSchema1() - everything except for tables and +** UNIQUE indexes. Specifically: +** +** * views, +** * triggers, +** * non-UNIQUE indexes. +** +** If the recover handle is in SQL callback mode, then equivalent callbacks +** are issued to create the schema elements. +*/ +static int recoverWriteSchema2(sqlite3_recover *p){ + sqlite3_stmt *pSelect = 0; + + pSelect = recoverPrepare(p, p->dbOut, + p->bSlowIndexes ? + "SELECT rootpage, sql FROM recovery.schema " + " WHERE type!='table' AND type!='index'" + : + "SELECT rootpage, sql FROM recovery.schema " + " WHERE type!='table' AND (type!='index' OR sql NOT LIKE '%unique%')" + ); + + if( pSelect ){ + while( sqlite3_step(pSelect)==SQLITE_ROW ){ + const char *zSql = (const char*)sqlite3_column_text(pSelect, 1); + int rc = sqlite3_exec(p->dbOut, zSql, 0, 0, 0); + if( rc==SQLITE_OK ){ + recoverSqlCallback(p, zSql); + }else if( rc!=SQLITE_ERROR ){ + recoverDbError(p, p->dbOut); + } + } + } + recoverFinalize(p, pSelect); + + return p->errCode; +} + +/* +** This function is a no-op if recover handle p already contains an error +** (if p->errCode!=SQLITE_OK). In this case it returns NULL. +** +** Otherwise, if the recover handle is configured to create an output +** database (was created by sqlite3_recover_init()), then this function +** prepares and returns an SQL statement to INSERT a new record into table +** pTab, assuming the first nField fields of a record extracted from disk +** are valid. +** +** For example, if table pTab is: +** +** CREATE TABLE name(a, b GENERATED ALWAYS AS (a+1) STORED, c, d, e); +** +** And nField is 4, then the SQL statement prepared and returned is: +** +** INSERT INTO (a, c, d) VALUES (?1, ?2, ?3); +** +** In this case even though 4 values were extracted from the input db, +** only 3 are written to the output, as the generated STORED column +** cannot be written. +** +** If the recover handle is in SQL callback mode, then the SQL statement +** prepared is such that evaluating it returns a single row containing +** a single text value - itself an SQL statement similar to the above, +** except with SQL literals in place of the variables. For example: +** +** SELECT 'INSERT INTO (a, c, d) VALUES (' +** || quote(?1) || ', ' +** || quote(?2) || ', ' +** || quote(?3) || ')'; +** +** In either case, it is the responsibility of the caller to eventually +** free the statement handle using sqlite3_finalize(). +*/ +static sqlite3_stmt *recoverInsertStmt( + sqlite3_recover *p, + RecoverTable *pTab, + int nField +){ + sqlite3_stmt *pRet = 0; + const char *zSep = ""; + const char *zSqlSep = ""; + char *zSql = 0; + char *zFinal = 0; + char *zBind = 0; + int ii; + int bSql = p->xSql ? 1 : 0; + + if( nField<=0 ) return 0; + + assert( nField<=pTab->nCol ); + + zSql = recoverMPrintf(p, "INSERT OR IGNORE INTO %Q(", pTab->zTab); + + if( pTab->iRowidBind ){ + assert( pTab->bIntkey ); + zSql = recoverMPrintf(p, "%z_rowid_", zSql); + if( bSql ){ + zBind = recoverMPrintf(p, "%zquote(?%d)", zBind, pTab->iRowidBind); + }else{ + zBind = recoverMPrintf(p, "%z?%d", zBind, pTab->iRowidBind); + } + zSqlSep = "||', '||"; + zSep = ", "; + } + + for(ii=0; iiaCol[ii].eHidden; + if( eHidden!=RECOVER_EHIDDEN_VIRTUAL + && eHidden!=RECOVER_EHIDDEN_STORED + ){ + assert( pTab->aCol[ii].iField>=0 && pTab->aCol[ii].iBind>=1 ); + zSql = recoverMPrintf(p, "%z%s%Q", zSql, zSep, pTab->aCol[ii].zCol); + + if( bSql ){ + zBind = recoverMPrintf(p, + "%z%sescape_crnl(quote(?%d))", zBind, zSqlSep, pTab->aCol[ii].iBind + ); + zSqlSep = "||', '||"; + }else{ + zBind = recoverMPrintf(p, "%z%s?%d", zBind, zSep, pTab->aCol[ii].iBind); + } + zSep = ", "; + } + } + + if( bSql ){ + zFinal = recoverMPrintf(p, "SELECT %Q || ') VALUES (' || %s || ')'", + zSql, zBind + ); + }else{ + zFinal = recoverMPrintf(p, "%s) VALUES (%s)", zSql, zBind); + } + + pRet = recoverPrepare(p, p->dbOut, zFinal); + sqlite3_free(zSql); + sqlite3_free(zBind); + sqlite3_free(zFinal); + + return pRet; +} + + +/* +** Search the list of RecoverTable objects at p->pTblList for one that +** has root page iRoot in the input database. If such an object is found, +** return a pointer to it. Otherwise, return NULL. +*/ +static RecoverTable *recoverFindTable(sqlite3_recover *p, u32 iRoot){ + RecoverTable *pRet = 0; + for(pRet=p->pTblList; pRet && pRet->iRoot!=iRoot; pRet=pRet->pNext); + return pRet; +} + +/* +** This function attempts to create a lost and found table within the +** output db. If successful, it returns a pointer to a buffer containing +** the name of the new table. It is the responsibility of the caller to +** eventually free this buffer using sqlite3_free(). +** +** If an error occurs, NULL is returned and an error code and error +** message left in the recover handle. +*/ +static char *recoverLostAndFoundCreate( + sqlite3_recover *p, /* Recover object */ + int nField /* Number of column fields in new table */ +){ + char *zTbl = 0; + sqlite3_stmt *pProbe = 0; + int ii = 0; + + pProbe = recoverPrepare(p, p->dbOut, + "SELECT 1 FROM sqlite_schema WHERE name=?" + ); + for(ii=-1; zTbl==0 && p->errCode==SQLITE_OK && ii<1000; ii++){ + int bFail = 0; + if( ii<0 ){ + zTbl = recoverMPrintf(p, "%s", p->zLostAndFound); + }else{ + zTbl = recoverMPrintf(p, "%s_%d", p->zLostAndFound, ii); + } + + if( p->errCode==SQLITE_OK ){ + sqlite3_bind_text(pProbe, 1, zTbl, -1, SQLITE_STATIC); + if( SQLITE_ROW==sqlite3_step(pProbe) ){ + bFail = 1; + } + recoverReset(p, pProbe); + } + + if( bFail ){ + sqlite3_clear_bindings(pProbe); + sqlite3_free(zTbl); + zTbl = 0; + } + } + recoverFinalize(p, pProbe); + + if( zTbl ){ + const char *zSep = 0; + char *zField = 0; + char *zSql = 0; + + zSep = "rootpgno INTEGER, pgno INTEGER, nfield INTEGER, id INTEGER, "; + for(ii=0; p->errCode==SQLITE_OK && iidbOut, zSql); + recoverSqlCallback(p, zSql); + sqlite3_free(zSql); + }else if( p->errCode==SQLITE_OK ){ + recoverError( + p, SQLITE_ERROR, "failed to create %s output table", p->zLostAndFound + ); + } + + return zTbl; +} + +/* +** Synthesize and prepare an INSERT statement to write to the lost_and_found +** table in the output database. The name of the table is zTab, and it has +** nField c* fields. +*/ +static sqlite3_stmt *recoverLostAndFoundInsert( + sqlite3_recover *p, + const char *zTab, + int nField +){ + int nTotal = nField + 4; + int ii; + char *zBind = 0; + sqlite3_stmt *pRet = 0; + + if( p->xSql==0 ){ + for(ii=0; iidbOut, "INSERT INTO %s VALUES(%s)", zTab, zBind + ); + }else{ + const char *zSep = ""; + for(ii=0; iidbOut, "SELECT 'INSERT INTO %s VALUES(' || %s || ')'", zTab, zBind + ); + } + + sqlite3_free(zBind); + return pRet; +} + +/* +** Input database page iPg contains data that will be written to the +** lost-and-found table of the output database. This function attempts +** to identify the root page of the tree that page iPg belonged to. +** If successful, it sets output variable (*piRoot) to the page number +** of the root page and returns SQLITE_OK. Otherwise, if an error occurs, +** an SQLite error code is returned and the final value of *piRoot +** undefined. +*/ +static int recoverLostAndFoundFindRoot( + sqlite3_recover *p, + i64 iPg, + i64 *piRoot +){ + RecoverStateLAF *pLaf = &p->laf; + + if( pLaf->pFindRoot==0 ){ + pLaf->pFindRoot = recoverPrepare(p, p->dbOut, + "WITH RECURSIVE p(pgno) AS (" + " SELECT ?" + " UNION" + " SELECT parent FROM recovery.map AS m, p WHERE m.pgno=p.pgno" + ") " + "SELECT p.pgno FROM p, recovery.map m WHERE m.pgno=p.pgno " + " AND m.parent IS NULL" + ); + } + if( p->errCode==SQLITE_OK ){ + sqlite3_bind_int64(pLaf->pFindRoot, 1, iPg); + if( sqlite3_step(pLaf->pFindRoot)==SQLITE_ROW ){ + *piRoot = sqlite3_column_int64(pLaf->pFindRoot, 0); + }else{ + *piRoot = iPg; + } + recoverReset(p, pLaf->pFindRoot); + } + return p->errCode; +} + +/* +** Recover data from page iPage of the input database and write it to +** the lost-and-found table in the output database. +*/ +static void recoverLostAndFoundOnePage(sqlite3_recover *p, i64 iPage){ + RecoverStateLAF *pLaf = &p->laf; + sqlite3_value **apVal = pLaf->apVal; + sqlite3_stmt *pPageData = pLaf->pPageData; + sqlite3_stmt *pInsert = pLaf->pInsert; + + int nVal = -1; + int iPrevCell = 0; + i64 iRoot = 0; + int bHaveRowid = 0; + i64 iRowid = 0; + int ii = 0; + + if( recoverLostAndFoundFindRoot(p, iPage, &iRoot) ) return; + sqlite3_bind_int64(pPageData, 1, iPage); + while( p->errCode==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPageData) ){ + int iCell = sqlite3_column_int64(pPageData, 0); + int iField = sqlite3_column_int64(pPageData, 1); + + if( iPrevCell!=iCell && nVal>=0 ){ + /* Insert the new row */ + sqlite3_bind_int64(pInsert, 1, iRoot); /* rootpgno */ + sqlite3_bind_int64(pInsert, 2, iPage); /* pgno */ + sqlite3_bind_int(pInsert, 3, nVal); /* nfield */ + if( bHaveRowid ){ + sqlite3_bind_int64(pInsert, 4, iRowid); /* id */ + } + for(ii=0; iinMaxField ){ + sqlite3_value *pVal = sqlite3_column_value(pPageData, 2); + apVal[iField] = sqlite3_value_dup(pVal); + assert( iField==nVal || (nVal==-1 && iField==0) ); + nVal = iField+1; + if( apVal[iField]==0 ){ + recoverError(p, SQLITE_NOMEM, 0); + } + } + + iPrevCell = iCell; + } + recoverReset(p, pPageData); + + for(ii=0; iilaf; + if( p->errCode==SQLITE_OK ){ + if( pLaf->pInsert==0 ){ + return SQLITE_DONE; + }else{ + if( p->errCode==SQLITE_OK ){ + int res = sqlite3_step(pLaf->pAllPage); + if( res==SQLITE_ROW ){ + i64 iPage = sqlite3_column_int64(pLaf->pAllPage, 0); + if( recoverBitmapQuery(pLaf->pUsed, iPage)==0 ){ + recoverLostAndFoundOnePage(p, iPage); + } + }else{ + recoverReset(p, pLaf->pAllPage); + return SQLITE_DONE; + } + } + } + } + return SQLITE_OK; +} + +/* +** Initialize resources required in RECOVER_STATE_LOSTANDFOUND3 +** state - during which the lost-and-found table of the output database +** is populated with recovered data that can not be assigned to any +** recovered schema object. +*/ +static void recoverLostAndFound3Init(sqlite3_recover *p){ + RecoverStateLAF *pLaf = &p->laf; + + if( pLaf->nMaxField>0 ){ + char *zTab = 0; /* Name of lost_and_found table */ + + zTab = recoverLostAndFoundCreate(p, pLaf->nMaxField); + pLaf->pInsert = recoverLostAndFoundInsert(p, zTab, pLaf->nMaxField); + sqlite3_free(zTab); + + pLaf->pAllPage = recoverPreparePrintf(p, p->dbOut, + "WITH RECURSIVE seq(ii) AS (" + " SELECT 1 UNION ALL SELECT ii+1 FROM seq WHERE ii<%lld" + ")" + "SELECT ii FROM seq" , p->laf.nPg + ); + pLaf->pPageData = recoverPrepare(p, p->dbOut, + "SELECT cell, field, value " + "FROM sqlite_dbdata('getpage()') d WHERE d.pgno=? " + "UNION ALL " + "SELECT -1, -1, -1" + ); + + pLaf->apVal = (sqlite3_value**)recoverMalloc(p, + pLaf->nMaxField*sizeof(sqlite3_value*) + ); + } +} + +/* +** Initialize resources required in RECOVER_STATE_WRITING state - during which +** tables recovered from the schema of the input database are populated with +** recovered data. +*/ +static int recoverWriteDataInit(sqlite3_recover *p){ + RecoverStateW1 *p1 = &p->w1; + RecoverTable *pTbl = 0; + int nByte = 0; + + /* Figure out the maximum number of columns for any table in the schema */ + assert( p1->nMax==0 ); + for(pTbl=p->pTblList; pTbl; pTbl=pTbl->pNext){ + if( pTbl->nCol>p1->nMax ) p1->nMax = pTbl->nCol; + } + + /* Allocate an array of (sqlite3_value*) in which to accumulate the values + ** that will be written to the output database in a single row. */ + nByte = sizeof(sqlite3_value*) * (p1->nMax+1); + p1->apVal = (sqlite3_value**)recoverMalloc(p, nByte); + if( p1->apVal==0 ) return p->errCode; + + /* Prepare the SELECT to loop through schema tables (pTbls) and the SELECT + ** to loop through cells that appear to belong to a single table (pSel). */ + p1->pTbls = recoverPrepare(p, p->dbOut, + "SELECT rootpage FROM recovery.schema " + " WHERE type='table' AND (sql NOT LIKE 'create virtual%')" + " ORDER BY (tbl_name='sqlite_sequence') ASC" + ); + p1->pSel = recoverPrepare(p, p->dbOut, + "WITH RECURSIVE pages(page) AS (" + " SELECT ?1" + " UNION" + " SELECT child FROM sqlite_dbptr('getpage()'), pages " + " WHERE pgno=page" + ") " + "SELECT page, cell, field, value " + "FROM sqlite_dbdata('getpage()') d, pages p WHERE p.page=d.pgno " + "UNION ALL " + "SELECT 0, 0, 0, 0" + ); + + return p->errCode; +} + +/* +** Clean up resources allocated by recoverWriteDataInit() (stuff in +** sqlite3_recover.w1). +*/ +static void recoverWriteDataCleanup(sqlite3_recover *p){ + RecoverStateW1 *p1 = &p->w1; + int ii; + for(ii=0; iinVal; ii++){ + sqlite3_value_free(p1->apVal[ii]); + } + sqlite3_free(p1->apVal); + recoverFinalize(p, p1->pInsert); + recoverFinalize(p, p1->pTbls); + recoverFinalize(p, p1->pSel); + memset(p1, 0, sizeof(*p1)); +} + +/* +** Perform one step (sqlite3_recover_step()) of work for the connection +** passed as the only argument, which is guaranteed to be in +** RECOVER_STATE_WRITING state - during which tables recovered from the +** schema of the input database are populated with recovered data. +*/ +static int recoverWriteDataStep(sqlite3_recover *p){ + RecoverStateW1 *p1 = &p->w1; + sqlite3_stmt *pSel = p1->pSel; + sqlite3_value **apVal = p1->apVal; + + if( p->errCode==SQLITE_OK && p1->pTab==0 ){ + if( sqlite3_step(p1->pTbls)==SQLITE_ROW ){ + i64 iRoot = sqlite3_column_int64(p1->pTbls, 0); + p1->pTab = recoverFindTable(p, iRoot); + + recoverFinalize(p, p1->pInsert); + p1->pInsert = 0; + + /* If this table is unknown, return early. The caller will invoke this + ** function again and it will move on to the next table. */ + if( p1->pTab==0 ) return p->errCode; + + /* If this is the sqlite_sequence table, delete any rows added by + ** earlier INSERT statements on tables with AUTOINCREMENT primary + ** keys before recovering its contents. The p1->pTbls SELECT statement + ** is rigged to deliver "sqlite_sequence" last of all, so we don't + ** worry about it being modified after it is recovered. */ + if( sqlite3_stricmp("sqlite_sequence", p1->pTab->zTab)==0 ){ + recoverExec(p, p->dbOut, "DELETE FROM sqlite_sequence"); + recoverSqlCallback(p, "DELETE FROM sqlite_sequence"); + } + + /* Bind the root page of this table within the original database to + ** SELECT statement p1->pSel. The SELECT statement will then iterate + ** through cells that look like they belong to table pTab. */ + sqlite3_bind_int64(pSel, 1, iRoot); + + p1->nVal = 0; + p1->bHaveRowid = 0; + p1->iPrevPage = -1; + p1->iPrevCell = -1; + }else{ + return SQLITE_DONE; + } + } + assert( p->errCode!=SQLITE_OK || p1->pTab ); + + if( p->errCode==SQLITE_OK && sqlite3_step(pSel)==SQLITE_ROW ){ + RecoverTable *pTab = p1->pTab; + + i64 iPage = sqlite3_column_int64(pSel, 0); + int iCell = sqlite3_column_int(pSel, 1); + int iField = sqlite3_column_int(pSel, 2); + sqlite3_value *pVal = sqlite3_column_value(pSel, 3); + int bNewCell = (p1->iPrevPage!=iPage || p1->iPrevCell!=iCell); + + assert( bNewCell==0 || (iField==-1 || iField==0) ); + assert( bNewCell || iField==p1->nVal || p1->nVal==pTab->nCol ); + + if( bNewCell ){ + int ii = 0; + if( p1->nVal>=0 ){ + if( p1->pInsert==0 || p1->nVal!=p1->nInsert ){ + recoverFinalize(p, p1->pInsert); + p1->pInsert = recoverInsertStmt(p, pTab, p1->nVal); + p1->nInsert = p1->nVal; + } + if( p1->nVal>0 ){ + sqlite3_stmt *pInsert = p1->pInsert; + for(ii=0; iinCol; ii++){ + RecoverColumn *pCol = &pTab->aCol[ii]; + int iBind = pCol->iBind; + if( iBind>0 ){ + if( pCol->bIPK ){ + sqlite3_bind_int64(pInsert, iBind, p1->iRowid); + }else if( pCol->iFieldnVal ){ + recoverBindValue(p, pInsert, iBind, apVal[pCol->iField]); + } + } + } + if( p->bRecoverRowid && pTab->iRowidBind>0 && p1->bHaveRowid ){ + sqlite3_bind_int64(pInsert, pTab->iRowidBind, p1->iRowid); + } + if( SQLITE_ROW==sqlite3_step(pInsert) ){ + const char *z = (const char*)sqlite3_column_text(pInsert, 0); + recoverSqlCallback(p, z); + } + recoverReset(p, pInsert); + assert( p->errCode || pInsert ); + if( pInsert ) sqlite3_clear_bindings(pInsert); + } + } + + for(ii=0; iinVal; ii++){ + sqlite3_value_free(apVal[ii]); + apVal[ii] = 0; + } + p1->nVal = -1; + p1->bHaveRowid = 0; + } + + if( iPage!=0 ){ + if( iField<0 ){ + p1->iRowid = sqlite3_column_int64(pSel, 3); + assert( p1->nVal==-1 ); + p1->nVal = 0; + p1->bHaveRowid = 1; + }else if( iFieldnCol ){ + assert( apVal[iField]==0 ); + apVal[iField] = sqlite3_value_dup( pVal ); + if( apVal[iField]==0 ){ + recoverError(p, SQLITE_NOMEM, 0); + } + p1->nVal = iField+1; + } + p1->iPrevCell = iCell; + p1->iPrevPage = iPage; + } + }else{ + recoverReset(p, pSel); + p1->pTab = 0; + } + + return p->errCode; +} + +/* +** Initialize resources required by sqlite3_recover_step() in +** RECOVER_STATE_LOSTANDFOUND1 state - during which the set of pages not +** already allocated to a recovered schema element is determined. +*/ +static void recoverLostAndFound1Init(sqlite3_recover *p){ + RecoverStateLAF *pLaf = &p->laf; + sqlite3_stmt *pStmt = 0; + + assert( p->laf.pUsed==0 ); + pLaf->nPg = recoverPageCount(p); + pLaf->pUsed = recoverBitmapAlloc(p, pLaf->nPg); + + /* Prepare a statement to iterate through all pages that are part of any tree + ** in the recoverable part of the input database schema to the bitmap. And, + ** if !p->bFreelistCorrupt, add all pages that appear to be part of the + ** freelist. */ + pStmt = recoverPrepare( + p, p->dbOut, + "WITH trunk(pgno) AS (" + " SELECT read_i32(getpage(1), 8) AS x WHERE x>0" + " UNION" + " SELECT read_i32(getpage(trunk.pgno), 0) AS x FROM trunk WHERE x>0" + ")," + "trunkdata(pgno, data) AS (" + " SELECT pgno, getpage(pgno) FROM trunk" + ")," + "freelist(data, n, freepgno) AS (" + " SELECT data, min(16384, read_i32(data, 1)-1), pgno FROM trunkdata" + " UNION ALL" + " SELECT data, n-1, read_i32(data, 2+n) FROM freelist WHERE n>=0" + ")," + "" + "roots(r) AS (" + " SELECT 1 UNION ALL" + " SELECT rootpage FROM recovery.schema WHERE rootpage>0" + ")," + "used(page) AS (" + " SELECT r FROM roots" + " UNION" + " SELECT child FROM sqlite_dbptr('getpage()'), used " + " WHERE pgno=page" + ") " + "SELECT page FROM used" + " UNION ALL " + "SELECT freepgno FROM freelist WHERE NOT ?" + ); + if( pStmt ) sqlite3_bind_int(pStmt, 1, p->bFreelistCorrupt); + pLaf->pUsedPages = pStmt; +} + +/* +** Perform one step (sqlite3_recover_step()) of work for the connection +** passed as the only argument, which is guaranteed to be in +** RECOVER_STATE_LOSTANDFOUND1 state - during which the set of pages not +** already allocated to a recovered schema element is determined. +*/ +static int recoverLostAndFound1Step(sqlite3_recover *p){ + RecoverStateLAF *pLaf = &p->laf; + int rc = p->errCode; + if( rc==SQLITE_OK ){ + rc = sqlite3_step(pLaf->pUsedPages); + if( rc==SQLITE_ROW ){ + i64 iPg = sqlite3_column_int64(pLaf->pUsedPages, 0); + recoverBitmapSet(pLaf->pUsed, iPg); + rc = SQLITE_OK; + }else{ + recoverFinalize(p, pLaf->pUsedPages); + pLaf->pUsedPages = 0; + } + } + return rc; +} + +/* +** Initialize resources required by RECOVER_STATE_LOSTANDFOUND2 +** state - during which the pages identified in RECOVER_STATE_LOSTANDFOUND1 +** are sorted into sets that likely belonged to the same database tree. +*/ +static void recoverLostAndFound2Init(sqlite3_recover *p){ + RecoverStateLAF *pLaf = &p->laf; + + assert( p->laf.pAllAndParent==0 ); + assert( p->laf.pMapInsert==0 ); + assert( p->laf.pMaxField==0 ); + assert( p->laf.nMaxField==0 ); + + pLaf->pMapInsert = recoverPrepare(p, p->dbOut, + "INSERT OR IGNORE INTO recovery.map(pgno, parent) VALUES(?, ?)" + ); + pLaf->pAllAndParent = recoverPreparePrintf(p, p->dbOut, + "WITH RECURSIVE seq(ii) AS (" + " SELECT 1 UNION ALL SELECT ii+1 FROM seq WHERE ii<%lld" + ")" + "SELECT pgno, child FROM sqlite_dbptr('getpage()') " + " UNION ALL " + "SELECT NULL, ii FROM seq", p->laf.nPg + ); + pLaf->pMaxField = recoverPreparePrintf(p, p->dbOut, + "SELECT max(field)+1 FROM sqlite_dbdata('getpage') WHERE pgno = ?" + ); +} + +/* +** Perform one step (sqlite3_recover_step()) of work for the connection +** passed as the only argument, which is guaranteed to be in +** RECOVER_STATE_LOSTANDFOUND2 state - during which the pages identified +** in RECOVER_STATE_LOSTANDFOUND1 are sorted into sets that likely belonged +** to the same database tree. +*/ +static int recoverLostAndFound2Step(sqlite3_recover *p){ + RecoverStateLAF *pLaf = &p->laf; + if( p->errCode==SQLITE_OK ){ + int res = sqlite3_step(pLaf->pAllAndParent); + if( res==SQLITE_ROW ){ + i64 iChild = sqlite3_column_int(pLaf->pAllAndParent, 1); + if( recoverBitmapQuery(pLaf->pUsed, iChild)==0 ){ + sqlite3_bind_int64(pLaf->pMapInsert, 1, iChild); + sqlite3_bind_value(pLaf->pMapInsert, 2, + sqlite3_column_value(pLaf->pAllAndParent, 0) + ); + sqlite3_step(pLaf->pMapInsert); + recoverReset(p, pLaf->pMapInsert); + sqlite3_bind_int64(pLaf->pMaxField, 1, iChild); + if( SQLITE_ROW==sqlite3_step(pLaf->pMaxField) ){ + int nMax = sqlite3_column_int(pLaf->pMaxField, 0); + if( nMax>pLaf->nMaxField ) pLaf->nMaxField = nMax; + } + recoverReset(p, pLaf->pMaxField); + } + }else{ + recoverFinalize(p, pLaf->pAllAndParent); + pLaf->pAllAndParent =0; + return SQLITE_DONE; + } + } + return p->errCode; +} + +/* +** Free all resources allocated as part of sqlite3_recover_step() calls +** in one of the RECOVER_STATE_LOSTANDFOUND[123] states. +*/ +static void recoverLostAndFoundCleanup(sqlite3_recover *p){ + recoverBitmapFree(p->laf.pUsed); + p->laf.pUsed = 0; + sqlite3_finalize(p->laf.pUsedPages); + sqlite3_finalize(p->laf.pAllAndParent); + sqlite3_finalize(p->laf.pMapInsert); + sqlite3_finalize(p->laf.pMaxField); + sqlite3_finalize(p->laf.pFindRoot); + sqlite3_finalize(p->laf.pInsert); + sqlite3_finalize(p->laf.pAllPage); + sqlite3_finalize(p->laf.pPageData); + p->laf.pUsedPages = 0; + p->laf.pAllAndParent = 0; + p->laf.pMapInsert = 0; + p->laf.pMaxField = 0; + p->laf.pFindRoot = 0; + p->laf.pInsert = 0; + p->laf.pAllPage = 0; + p->laf.pPageData = 0; + sqlite3_free(p->laf.apVal); + p->laf.apVal = 0; +} + +/* +** Free all resources allocated as part of sqlite3_recover_step() calls. +*/ +static void recoverFinalCleanup(sqlite3_recover *p){ + RecoverTable *pTab = 0; + RecoverTable *pNext = 0; + + recoverWriteDataCleanup(p); + recoverLostAndFoundCleanup(p); + + for(pTab=p->pTblList; pTab; pTab=pNext){ + pNext = pTab->pNext; + sqlite3_free(pTab); + } + p->pTblList = 0; + sqlite3_finalize(p->pGetPage); + p->pGetPage = 0; + sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_RESET_CACHE, 0); + + { +#ifndef NDEBUG + int res = +#endif + sqlite3_close(p->dbOut); + assert( res==SQLITE_OK ); + } + p->dbOut = 0; +} + +/* +** Decode and return an unsigned 16-bit big-endian integer value from +** buffer a[]. +*/ +static u32 recoverGetU16(const u8 *a){ + return (((u32)a[0])<<8) + ((u32)a[1]); +} + +/* +** Decode and return an unsigned 32-bit big-endian integer value from +** buffer a[]. +*/ +static u32 recoverGetU32(const u8 *a){ + return (((u32)a[0])<<24) + (((u32)a[1])<<16) + (((u32)a[2])<<8) + ((u32)a[3]); +} + +/* +** Decode an SQLite varint from buffer a[]. Write the decoded value to (*pVal) +** and return the number of bytes consumed. +*/ +static int recoverGetVarint(const u8 *a, i64 *pVal){ + sqlite3_uint64 u = 0; + int i; + for(i=0; i<8; i++){ + u = (u<<7) + (a[i]&0x7f); + if( (a[i]&0x80)==0 ){ *pVal = (sqlite3_int64)u; return i+1; } + } + u = (u<<8) + (a[i]&0xff); + *pVal = (sqlite3_int64)u; + return 9; +} + +/* +** The second argument points to a buffer n bytes in size. If this buffer +** or a prefix thereof appears to contain a well-formed SQLite b-tree page, +** return the page-size in bytes. Otherwise, if the buffer does not +** appear to contain a well-formed b-tree page, return 0. +*/ +static int recoverIsValidPage(u8 *aTmp, const u8 *a, int n){ + u8 *aUsed = aTmp; + int nFrag = 0; + int nActual = 0; + int iFree = 0; + int nCell = 0; /* Number of cells on page */ + int iCellOff = 0; /* Offset of cell array in page */ + int iContent = 0; + int eType = 0; + int ii = 0; + + eType = (int)a[0]; + if( eType!=0x02 && eType!=0x05 && eType!=0x0A && eType!=0x0D ) return 0; + + iFree = (int)recoverGetU16(&a[1]); + nCell = (int)recoverGetU16(&a[3]); + iContent = (int)recoverGetU16(&a[5]); + if( iContent==0 ) iContent = 65536; + nFrag = (int)a[7]; + + if( iContent>n ) return 0; + + memset(aUsed, 0, n); + memset(aUsed, 0xFF, iContent); + + /* Follow the free-list. This is the same format for all b-tree pages. */ + if( iFree && iFree<=iContent ) return 0; + while( iFree ){ + int iNext = 0; + int nByte = 0; + if( iFree>(n-4) ) return 0; + iNext = recoverGetU16(&a[iFree]); + nByte = recoverGetU16(&a[iFree+2]); + if( iFree+nByte>n || nByte<4 ) return 0; + if( iNext && iNextiContent ) return 0; + for(ii=0; iin ){ + return 0; + } + if( eType==0x05 || eType==0x02 ) nByte += 4; + nByte += recoverGetVarint(&a[iOff+nByte], &nPayload); + if( eType==0x0D ){ + i64 dummy = 0; + nByte += recoverGetVarint(&a[iOff+nByte], &dummy); + } + if( eType!=0x05 ){ + int X = (eType==0x0D) ? n-35 : (((n-12)*64/255)-23); + int M = ((n-12)*32/255)-23; + int K = M+((nPayload-M)%(n-4)); + + if( nPayloadn ){ + return 0; + } + for(iByte=iOff; iByte<(iOff+nByte); iByte++){ + if( aUsed[iByte]!=0 ){ + return 0; + } + aUsed[iByte] = 0xFF; + } + } + + nActual = 0; + for(ii=0; iipMethods!=&recover_methods ); + return pFd->pMethods->xClose(pFd); +} + +/* +** Write value v to buffer a[] as a 16-bit big-endian unsigned integer. +*/ +static void recoverPutU16(u8 *a, u32 v){ + a[0] = (v>>8) & 0x00FF; + a[1] = (v>>0) & 0x00FF; +} + +/* +** Write value v to buffer a[] as a 32-bit big-endian unsigned integer. +*/ +static void recoverPutU32(u8 *a, u32 v){ + a[0] = (v>>24) & 0x00FF; + a[1] = (v>>16) & 0x00FF; + a[2] = (v>>8) & 0x00FF; + a[3] = (v>>0) & 0x00FF; +} + +/* +** Detect the page-size of the database opened by file-handle pFd by +** searching the first part of the file for a well-formed SQLite b-tree +** page. If parameter nReserve is non-zero, then as well as searching for +** a b-tree page with zero reserved bytes, this function searches for one +** with nReserve reserved bytes at the end of it. +** +** If successful, set variable p->detected_pgsz to the detected page-size +** in bytes and return SQLITE_OK. Or, if no error occurs but no valid page +** can be found, return SQLITE_OK but leave p->detected_pgsz set to 0. Or, +** if an error occurs (e.g. an IO or OOM error), then an SQLite error code +** is returned. The final value of p->detected_pgsz is undefined in this +** case. +*/ +static int recoverVfsDetectPagesize( + sqlite3_recover *p, /* Recover handle */ + sqlite3_file *pFd, /* File-handle open on input database */ + u32 nReserve, /* Possible nReserve value */ + i64 nSz /* Size of database file in bytes */ +){ + int rc = SQLITE_OK; + const int nMin = 512; + const int nMax = 65536; + const int nMaxBlk = 4; + u32 pgsz = 0; + int iBlk = 0; + u8 *aPg = 0; + u8 *aTmp = 0; + int nBlk = 0; + + aPg = (u8*)sqlite3_malloc(2*nMax); + if( aPg==0 ) return SQLITE_NOMEM; + aTmp = &aPg[nMax]; + + nBlk = (nSz+nMax-1)/nMax; + if( nBlk>nMaxBlk ) nBlk = nMaxBlk; + + do { + for(iBlk=0; rc==SQLITE_OK && iBlk=((iBlk+1)*nMax)) ? nMax : (nSz % nMax); + memset(aPg, 0, nMax); + rc = pFd->pMethods->xRead(pFd, aPg, nByte, iBlk*nMax); + if( rc==SQLITE_OK ){ + int pgsz2; + for(pgsz2=(pgsz ? pgsz*2 : nMin); pgsz2<=nMax; pgsz2=pgsz2*2){ + int iOff; + for(iOff=0; iOff(u32)p->detected_pgsz ){ + p->detected_pgsz = pgsz; + p->nReserve = nReserve; + } + if( nReserve==0 ) break; + nReserve = 0; + }while( 1 ); + + p->detected_pgsz = pgsz; + sqlite3_free(aPg); + return rc; +} + +/* +** The xRead() method of the wrapper VFS. This is used to intercept calls +** to read page 1 of the input database. +*/ +static int recoverVfsRead(sqlite3_file *pFd, void *aBuf, int nByte, i64 iOff){ + int rc = SQLITE_OK; + if( pFd->pMethods==&recover_methods ){ + pFd->pMethods = recover_g.pMethods; + rc = pFd->pMethods->xRead(pFd, aBuf, nByte, iOff); + if( nByte==16 ){ + sqlite3_randomness(16, aBuf); + }else + if( rc==SQLITE_OK && iOff==0 && nByte>=108 ){ + /* Ensure that the database has a valid header file. The only fields + ** that really matter to recovery are: + ** + ** + Database page size (16-bits at offset 16) + ** + Size of db in pages (32-bits at offset 28) + ** + Database encoding (32-bits at offset 56) + ** + ** Also preserved are: + ** + ** + first freelist page (32-bits at offset 32) + ** + size of freelist (32-bits at offset 36) + ** + the wal-mode flags (16-bits at offset 18) + ** + ** We also try to preserve the auto-vacuum, incr-value, user-version + ** and application-id fields - all 32 bit quantities at offsets + ** 52, 60, 64 and 68. All other fields are set to known good values. + ** + ** Byte offset 105 should also contain the page-size as a 16-bit + ** integer. + */ + const int aPreserve[] = {32, 36, 52, 60, 64, 68}; + u8 aHdr[108] = { + 0x53, 0x51, 0x4c, 0x69, 0x74, 0x65, 0x20, 0x66, + 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x20, 0x33, 0x00, + 0xFF, 0xFF, 0x01, 0x01, 0x00, 0x40, 0x20, 0x20, + 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, + 0x00, 0x00, 0x10, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x2e, 0x5b, 0x30, + + 0x0D, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x00 + }; + u8 *a = (u8*)aBuf; + + u32 pgsz = recoverGetU16(&a[16]); + u32 nReserve = a[20]; + u32 enc = recoverGetU32(&a[56]); + u32 dbsz = 0; + i64 dbFileSize = 0; + int ii; + sqlite3_recover *p = recover_g.p; + + if( pgsz==0x01 ) pgsz = 65536; + rc = pFd->pMethods->xFileSize(pFd, &dbFileSize); + + if( rc==SQLITE_OK && p->detected_pgsz==0 ){ + rc = recoverVfsDetectPagesize(p, pFd, nReserve, dbFileSize); + } + if( p->detected_pgsz ){ + pgsz = p->detected_pgsz; + nReserve = p->nReserve; + } + + if( pgsz ){ + dbsz = dbFileSize / pgsz; + } + if( enc!=SQLITE_UTF8 && enc!=SQLITE_UTF16BE && enc!=SQLITE_UTF16LE ){ + enc = SQLITE_UTF8; + } + + sqlite3_free(p->pPage1Cache); + p->pPage1Cache = 0; + p->pPage1Disk = 0; + + p->pgsz = nByte; + p->pPage1Cache = (u8*)recoverMalloc(p, nByte*2); + if( p->pPage1Cache ){ + p->pPage1Disk = &p->pPage1Cache[nByte]; + memcpy(p->pPage1Disk, aBuf, nByte); + aHdr[18] = a[18]; + aHdr[19] = a[19]; + recoverPutU32(&aHdr[28], dbsz); + recoverPutU32(&aHdr[56], enc); + recoverPutU16(&aHdr[105], pgsz-nReserve); + if( pgsz==65536 ) pgsz = 1; + recoverPutU16(&aHdr[16], pgsz); + aHdr[20] = nReserve; + for(ii=0; ii<(int)(sizeof(aPreserve)/sizeof(aPreserve[0])); ii++){ + memcpy(&aHdr[aPreserve[ii]], &a[aPreserve[ii]], 4); + } + memcpy(aBuf, aHdr, sizeof(aHdr)); + memset(&((u8*)aBuf)[sizeof(aHdr)], 0, nByte-sizeof(aHdr)); + + memcpy(p->pPage1Cache, aBuf, nByte); + }else{ + rc = p->errCode; + } + + } + pFd->pMethods = &recover_methods; + }else{ + rc = pFd->pMethods->xRead(pFd, aBuf, nByte, iOff); + } + return rc; +} + +/* +** Used to make sqlite3_io_methods wrapper methods less verbose. +*/ +#define RECOVER_VFS_WRAPPER(code) \ + int rc = SQLITE_OK; \ + if( pFd->pMethods==&recover_methods ){ \ + pFd->pMethods = recover_g.pMethods; \ + rc = code; \ + pFd->pMethods = &recover_methods; \ + }else{ \ + rc = code; \ + } \ + return rc; + +/* +** Methods of the wrapper VFS. All methods except for xRead() and xClose() +** simply uninstall the sqlite3_io_methods wrapper, invoke the equivalent +** method on the lower level VFS, then reinstall the wrapper before returning. +** Those that return an integer value use the RECOVER_VFS_WRAPPER macro. +*/ +static int recoverVfsWrite( + sqlite3_file *pFd, const void *aBuf, int nByte, i64 iOff +){ + RECOVER_VFS_WRAPPER ( + pFd->pMethods->xWrite(pFd, aBuf, nByte, iOff) + ); +} +static int recoverVfsTruncate(sqlite3_file *pFd, sqlite3_int64 size){ + RECOVER_VFS_WRAPPER ( + pFd->pMethods->xTruncate(pFd, size) + ); +} +static int recoverVfsSync(sqlite3_file *pFd, int flags){ + RECOVER_VFS_WRAPPER ( + pFd->pMethods->xSync(pFd, flags) + ); +} +static int recoverVfsFileSize(sqlite3_file *pFd, sqlite3_int64 *pSize){ + RECOVER_VFS_WRAPPER ( + pFd->pMethods->xFileSize(pFd, pSize) + ); +} +static int recoverVfsLock(sqlite3_file *pFd, int eLock){ + RECOVER_VFS_WRAPPER ( + pFd->pMethods->xLock(pFd, eLock) + ); +} +static int recoverVfsUnlock(sqlite3_file *pFd, int eLock){ + RECOVER_VFS_WRAPPER ( + pFd->pMethods->xUnlock(pFd, eLock) + ); +} +static int recoverVfsCheckReservedLock(sqlite3_file *pFd, int *pResOut){ + RECOVER_VFS_WRAPPER ( + pFd->pMethods->xCheckReservedLock(pFd, pResOut) + ); +} +static int recoverVfsFileControl(sqlite3_file *pFd, int op, void *pArg){ + RECOVER_VFS_WRAPPER ( + (pFd->pMethods ? pFd->pMethods->xFileControl(pFd, op, pArg) : SQLITE_NOTFOUND) + ); +} +static int recoverVfsSectorSize(sqlite3_file *pFd){ + RECOVER_VFS_WRAPPER ( + pFd->pMethods->xSectorSize(pFd) + ); +} +static int recoverVfsDeviceCharacteristics(sqlite3_file *pFd){ + RECOVER_VFS_WRAPPER ( + pFd->pMethods->xDeviceCharacteristics(pFd) + ); +} +static int recoverVfsShmMap( + sqlite3_file *pFd, int iPg, int pgsz, int bExtend, void volatile **pp +){ + RECOVER_VFS_WRAPPER ( + pFd->pMethods->xShmMap(pFd, iPg, pgsz, bExtend, pp) + ); +} +static int recoverVfsShmLock(sqlite3_file *pFd, int offset, int n, int flags){ + RECOVER_VFS_WRAPPER ( + pFd->pMethods->xShmLock(pFd, offset, n, flags) + ); +} +static void recoverVfsShmBarrier(sqlite3_file *pFd){ + if( pFd->pMethods==&recover_methods ){ + pFd->pMethods = recover_g.pMethods; + pFd->pMethods->xShmBarrier(pFd); + pFd->pMethods = &recover_methods; + }else{ + pFd->pMethods->xShmBarrier(pFd); + } +} +static int recoverVfsShmUnmap(sqlite3_file *pFd, int deleteFlag){ + RECOVER_VFS_WRAPPER ( + pFd->pMethods->xShmUnmap(pFd, deleteFlag) + ); +} + +static int recoverVfsFetch( + sqlite3_file *pFd, + sqlite3_int64 iOff, + int iAmt, + void **pp +){ + (void)pFd; + (void)iOff; + (void)iAmt; + *pp = 0; + return SQLITE_OK; +} +static int recoverVfsUnfetch(sqlite3_file *pFd, sqlite3_int64 iOff, void *p){ + (void)pFd; + (void)iOff; + (void)p; + return SQLITE_OK; +} + +/* +** Install the VFS wrapper around the file-descriptor open on the input +** database for recover handle p. Mutex RECOVER_MUTEX_ID must be held +** when this function is called. +*/ +static void recoverInstallWrapper(sqlite3_recover *p){ + sqlite3_file *pFd = 0; + assert( recover_g.pMethods==0 ); + recoverAssertMutexHeld(); + sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_FILE_POINTER, (void*)&pFd); + assert( pFd==0 || pFd->pMethods!=&recover_methods ); + if( pFd && pFd->pMethods ){ + int iVersion = 1 + (pFd->pMethods->iVersion>1 && pFd->pMethods->xShmMap!=0); + recover_g.pMethods = pFd->pMethods; + recover_g.p = p; + recover_methods.iVersion = iVersion; + pFd->pMethods = &recover_methods; + } +} + +/* +** Uninstall the VFS wrapper that was installed around the file-descriptor open +** on the input database for recover handle p. Mutex RECOVER_MUTEX_ID must be +** held when this function is called. +*/ +static void recoverUninstallWrapper(sqlite3_recover *p){ + sqlite3_file *pFd = 0; + recoverAssertMutexHeld(); + sqlite3_file_control(p->dbIn, p->zDb,SQLITE_FCNTL_FILE_POINTER,(void*)&pFd); + if( pFd && pFd->pMethods ){ + pFd->pMethods = recover_g.pMethods; + recover_g.pMethods = 0; + recover_g.p = 0; + } +} + +/* +** This function does the work of a single sqlite3_recover_step() call. It +** is guaranteed that the handle is not in an error state when this +** function is called. +*/ +static void recoverStep(sqlite3_recover *p){ + assert( p && p->errCode==SQLITE_OK ); + switch( p->eState ){ + case RECOVER_STATE_INIT: + /* This is the very first call to sqlite3_recover_step() on this object. + */ + recoverSqlCallback(p, "BEGIN"); + recoverSqlCallback(p, "PRAGMA writable_schema = on"); + + recoverEnterMutex(); + recoverInstallWrapper(p); + + /* Open the output database. And register required virtual tables and + ** user functions with the new handle. */ + recoverOpenOutput(p); + + /* Open transactions on both the input and output databases. */ + sqlite3_file_control(p->dbIn, p->zDb, SQLITE_FCNTL_RESET_CACHE, 0); + recoverExec(p, p->dbIn, "PRAGMA writable_schema = on"); + recoverExec(p, p->dbIn, "BEGIN"); + if( p->errCode==SQLITE_OK ) p->bCloseTransaction = 1; + recoverExec(p, p->dbIn, "SELECT 1 FROM sqlite_schema"); + recoverTransferSettings(p); + recoverOpenRecovery(p); + recoverCacheSchema(p); + + recoverUninstallWrapper(p); + recoverLeaveMutex(); + + recoverExec(p, p->dbOut, "BEGIN"); + + recoverWriteSchema1(p); + p->eState = RECOVER_STATE_WRITING; + break; + + case RECOVER_STATE_WRITING: { + if( p->w1.pTbls==0 ){ + recoverWriteDataInit(p); + } + if( SQLITE_DONE==recoverWriteDataStep(p) ){ + recoverWriteDataCleanup(p); + if( p->zLostAndFound ){ + p->eState = RECOVER_STATE_LOSTANDFOUND1; + }else{ + p->eState = RECOVER_STATE_SCHEMA2; + } + } + break; + } + + case RECOVER_STATE_LOSTANDFOUND1: { + if( p->laf.pUsed==0 ){ + recoverLostAndFound1Init(p); + } + if( SQLITE_DONE==recoverLostAndFound1Step(p) ){ + p->eState = RECOVER_STATE_LOSTANDFOUND2; + } + break; + } + case RECOVER_STATE_LOSTANDFOUND2: { + if( p->laf.pAllAndParent==0 ){ + recoverLostAndFound2Init(p); + } + if( SQLITE_DONE==recoverLostAndFound2Step(p) ){ + p->eState = RECOVER_STATE_LOSTANDFOUND3; + } + break; + } + + case RECOVER_STATE_LOSTANDFOUND3: { + if( p->laf.pInsert==0 ){ + recoverLostAndFound3Init(p); + } + if( SQLITE_DONE==recoverLostAndFound3Step(p) ){ + p->eState = RECOVER_STATE_SCHEMA2; + } + break; + } + + case RECOVER_STATE_SCHEMA2: { + int rc = SQLITE_OK; + + recoverWriteSchema2(p); + p->eState = RECOVER_STATE_DONE; + + /* If no error has occurred, commit the write transaction on the output + ** database. Regardless of whether or not an error has occurred, make + ** an attempt to end the read transaction on the input database. */ + recoverExec(p, p->dbOut, "COMMIT"); + rc = sqlite3_exec(p->dbIn, "END", 0, 0, 0); + if( p->errCode==SQLITE_OK ) p->errCode = rc; + + recoverSqlCallback(p, "PRAGMA writable_schema = off"); + recoverSqlCallback(p, "COMMIT"); + p->eState = RECOVER_STATE_DONE; + recoverFinalCleanup(p); + break; + }; + + case RECOVER_STATE_DONE: { + /* no-op */ + break; + }; + } +} + + +/* +** This is a worker function that does the heavy lifting for both init +** functions: +** +** sqlite3_recover_init() +** sqlite3_recover_init_sql() +** +** All this function does is allocate space for the recover handle and +** take copies of the input parameters. All the real work is done within +** sqlite3_recover_run(). +*/ +sqlite3_recover *recoverInit( + sqlite3* db, + const char *zDb, + const char *zUri, /* Output URI for _recover_init() */ + int (*xSql)(void*, const char*),/* SQL callback for _recover_init_sql() */ + void *pSqlCtx /* Context arg for _recover_init_sql() */ +){ + sqlite3_recover *pRet = 0; + int nDb = 0; + int nUri = 0; + int nByte = 0; + + if( zDb==0 ){ zDb = "main"; } + + nDb = recoverStrlen(zDb); + nUri = recoverStrlen(zUri); + + nByte = sizeof(sqlite3_recover) + nDb+1 + nUri+1; + pRet = (sqlite3_recover*)sqlite3_malloc(nByte); + if( pRet ){ + memset(pRet, 0, nByte); + pRet->dbIn = db; + pRet->zDb = (char*)&pRet[1]; + pRet->zUri = &pRet->zDb[nDb+1]; + memcpy(pRet->zDb, zDb, nDb); + if( nUri>0 && zUri ) memcpy(pRet->zUri, zUri, nUri); + pRet->xSql = xSql; + pRet->pSqlCtx = pSqlCtx; + pRet->bRecoverRowid = RECOVER_ROWID_DEFAULT; + } + + return pRet; +} + +/* +** Initialize a recovery handle that creates a new database containing +** the recovered data. +*/ +sqlite3_recover *sqlite3_recover_init( + sqlite3* db, + const char *zDb, + const char *zUri +){ + return recoverInit(db, zDb, zUri, 0, 0); +} + +/* +** Initialize a recovery handle that returns recovered data in the +** form of SQL statements via a callback. +*/ +sqlite3_recover *sqlite3_recover_init_sql( + sqlite3* db, + const char *zDb, + int (*xSql)(void*, const char*), + void *pSqlCtx +){ + return recoverInit(db, zDb, 0, xSql, pSqlCtx); +} + +/* +** Return the handle error message, if any. +*/ +const char *sqlite3_recover_errmsg(sqlite3_recover *p){ + return (p && p->errCode!=SQLITE_NOMEM) ? p->zErrMsg : "out of memory"; +} + +/* +** Return the handle error code. +*/ +int sqlite3_recover_errcode(sqlite3_recover *p){ + return p ? p->errCode : SQLITE_NOMEM; +} + +/* +** Configure the handle. +*/ +int sqlite3_recover_config(sqlite3_recover *p, int op, void *pArg){ + int rc = SQLITE_OK; + if( p==0 ){ + rc = SQLITE_NOMEM; + }else if( p->eState!=RECOVER_STATE_INIT ){ + rc = SQLITE_MISUSE; + }else{ + switch( op ){ + case 789: + /* This undocumented magic configuration option is used to set the + ** name of the auxiliary database that is ATTACH-ed to the database + ** connection and used to hold state information during the + ** recovery process. This option is for debugging use only and + ** is subject to change or removal at any time. */ + sqlite3_free(p->zStateDb); + p->zStateDb = recoverMPrintf(p, "%s", (char*)pArg); + break; + + case SQLITE_RECOVER_LOST_AND_FOUND: { + const char *zArg = (const char*)pArg; + sqlite3_free(p->zLostAndFound); + if( zArg ){ + p->zLostAndFound = recoverMPrintf(p, "%s", zArg); + }else{ + p->zLostAndFound = 0; + } + break; + } + + case SQLITE_RECOVER_FREELIST_CORRUPT: + p->bFreelistCorrupt = *(int*)pArg; + break; + + case SQLITE_RECOVER_ROWIDS: + p->bRecoverRowid = *(int*)pArg; + break; + + case SQLITE_RECOVER_SLOWINDEXES: + p->bSlowIndexes = *(int*)pArg; + break; + + default: + rc = SQLITE_NOTFOUND; + break; + } + } + + return rc; +} + +/* +** Do a unit of work towards the recovery job. Return SQLITE_OK if +** no error has occurred but database recovery is not finished, SQLITE_DONE +** if database recovery has been successfully completed, or an SQLite +** error code if an error has occurred. +*/ +int sqlite3_recover_step(sqlite3_recover *p){ + if( p==0 ) return SQLITE_NOMEM; + if( p->errCode==SQLITE_OK ) recoverStep(p); + if( p->eState==RECOVER_STATE_DONE && p->errCode==SQLITE_OK ){ + return SQLITE_DONE; + } + return p->errCode; +} + +/* +** Do the configured recovery operation. Return SQLITE_OK if successful, or +** else an SQLite error code. +*/ +int sqlite3_recover_run(sqlite3_recover *p){ + while( SQLITE_OK==sqlite3_recover_step(p) ); + return sqlite3_recover_errcode(p); +} + + +/* +** Free all resources associated with the recover handle passed as the only +** argument. The results of using a handle with any sqlite3_recover_** +** API function after it has been passed to this function are undefined. +** +** A copy of the value returned by the first call made to sqlite3_recover_run() +** on this handle is returned, or SQLITE_OK if sqlite3_recover_run() has +** not been called on this handle. +*/ +int sqlite3_recover_finish(sqlite3_recover *p){ + int rc; + if( p==0 ){ + rc = SQLITE_NOMEM; + }else{ + recoverFinalCleanup(p); + if( p->bCloseTransaction && sqlite3_get_autocommit(p->dbIn)==0 ){ + rc = sqlite3_exec(p->dbIn, "END", 0, 0, 0); + if( p->errCode==SQLITE_OK ) p->errCode = rc; + } + rc = p->errCode; + sqlite3_free(p->zErrMsg); + sqlite3_free(p->zStateDb); + sqlite3_free(p->zLostAndFound); + sqlite3_free(p->pPage1Cache); + sqlite3_free(p); + } + return rc; +} + +#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */ diff --git a/lib/include/sqlite3recover.h b/lib/include/sqlite3recover.h new file mode 100644 index 00000000..7a1cd1cd --- /dev/null +++ b/lib/include/sqlite3recover.h @@ -0,0 +1,249 @@ +/* +** 2022-08-27 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** +** This file contains the public interface to the "recover" extension - +** an SQLite extension designed to recover data from corrupted database +** files. +*/ + +/* +** OVERVIEW: +** +** To use the API to recover data from a corrupted database, an +** application: +** +** 1) Creates an sqlite3_recover handle by calling either +** sqlite3_recover_init() or sqlite3_recover_init_sql(). +** +** 2) Configures the new handle using one or more calls to +** sqlite3_recover_config(). +** +** 3) Executes the recovery by repeatedly calling sqlite3_recover_step() on +** the handle until it returns something other than SQLITE_OK. If it +** returns SQLITE_DONE, then the recovery operation completed without +** error. If it returns some other non-SQLITE_OK value, then an error +** has occurred. +** +** 4) Retrieves any error code and English language error message using the +** sqlite3_recover_errcode() and sqlite3_recover_errmsg() APIs, +** respectively. +** +** 5) Destroys the sqlite3_recover handle and frees all resources +** using sqlite3_recover_finish(). +** +** The application may abandon the recovery operation at any point +** before it is finished by passing the sqlite3_recover handle to +** sqlite3_recover_finish(). This is not an error, but the final state +** of the output database, or the results of running the partial script +** delivered to the SQL callback, are undefined. +*/ + +#ifndef _SQLITE_RECOVER_H +#define _SQLITE_RECOVER_H + +#include "sqlite3.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* +** An instance of the sqlite3_recover object represents a recovery +** operation in progress. +** +** Constructors: +** +** sqlite3_recover_init() +** sqlite3_recover_init_sql() +** +** Destructor: +** +** sqlite3_recover_finish() +** +** Methods: +** +** sqlite3_recover_config() +** sqlite3_recover_errcode() +** sqlite3_recover_errmsg() +** sqlite3_recover_run() +** sqlite3_recover_step() +*/ +typedef struct sqlite3_recover sqlite3_recover; + +/* +** These two APIs attempt to create and return a new sqlite3_recover object. +** In both cases the first two arguments identify the (possibly +** corrupt) database to recover data from. The first argument is an open +** database handle and the second the name of a database attached to that +** handle (i.e. "main", "temp" or the name of an attached database). +** +** If sqlite3_recover_init() is used to create the new sqlite3_recover +** handle, then data is recovered into a new database, identified by +** string parameter zUri. zUri may be an absolute or relative file path, +** or may be an SQLite URI. If the identified database file already exists, +** it is overwritten. +** +** If sqlite3_recover_init_sql() is invoked, then any recovered data will +** be returned to the user as a series of SQL statements. Executing these +** SQL statements results in the same database as would have been created +** had sqlite3_recover_init() been used. For each SQL statement in the +** output, the callback function passed as the third argument (xSql) is +** invoked once. The first parameter is a passed a copy of the fourth argument +** to this function (pCtx) as its first parameter, and a pointer to a +** nul-terminated buffer containing the SQL statement formated as UTF-8 as +** the second. If the xSql callback returns any value other than SQLITE_OK, +** then processing is immediately abandoned and the value returned used as +** the recover handle error code (see below). +** +** If an out-of-memory error occurs, NULL may be returned instead of +** a valid handle. In all other cases, it is the responsibility of the +** application to avoid resource leaks by ensuring that +** sqlite3_recover_finish() is called on all allocated handles. +*/ +sqlite3_recover *sqlite3_recover_init( + sqlite3* db, + const char *zDb, + const char *zUri +); +sqlite3_recover *sqlite3_recover_init_sql( + sqlite3* db, + const char *zDb, + int (*xSql)(void*, const char*), + void *pCtx +); + +/* +** Configure an sqlite3_recover object that has just been created using +** sqlite3_recover_init() or sqlite3_recover_init_sql(). This function +** may only be called before the first call to sqlite3_recover_step() +** or sqlite3_recover_run() on the object. +** +** The second argument passed to this function must be one of the +** SQLITE_RECOVER_* symbols defined below. Valid values for the third argument +** depend on the specific SQLITE_RECOVER_* symbol in use. +** +** SQLITE_OK is returned if the configuration operation was successful, +** or an SQLite error code otherwise. +*/ +int sqlite3_recover_config(sqlite3_recover*, int op, void *pArg); + +/* +** SQLITE_RECOVER_LOST_AND_FOUND: +** The pArg argument points to a string buffer containing the name +** of a "lost-and-found" table in the output database, or NULL. If +** the argument is non-NULL and the database contains seemingly +** valid pages that cannot be associated with any table in the +** recovered part of the schema, data is extracted from these +** pages to add to the lost-and-found table. +** +** SQLITE_RECOVER_FREELIST_CORRUPT: +** The pArg value must actually be a pointer to a value of type +** int containing value 0 or 1 cast as a (void*). If this option is set +** (argument is 1) and a lost-and-found table has been configured using +** SQLITE_RECOVER_LOST_AND_FOUND, then is assumed that the freelist is +** corrupt and an attempt is made to recover records from pages that +** appear to be linked into the freelist. Otherwise, pages on the freelist +** are ignored. Setting this option can recover more data from the +** database, but often ends up "recovering" deleted records. The default +** value is 0 (clear). +** +** SQLITE_RECOVER_ROWIDS: +** The pArg value must actually be a pointer to a value of type +** int containing value 0 or 1 cast as a (void*). If this option is set +** (argument is 1), then an attempt is made to recover rowid values +** that are not also INTEGER PRIMARY KEY values. If this option is +** clear, then new rowids are assigned to all recovered rows. The +** default value is 1 (set). +** +** SQLITE_RECOVER_SLOWINDEXES: +** The pArg value must actually be a pointer to a value of type +** int containing value 0 or 1 cast as a (void*). If this option is clear +** (argument is 0), then when creating an output database, the recover +** module creates and populates non-UNIQUE indexes right at the end of the +** recovery operation - after all recoverable data has been inserted +** into the new database. This is faster overall, but means that the +** final call to sqlite3_recover_step() for a recovery operation may +** be need to create a large number of indexes, which may be very slow. +** +** Or, if this option is set (argument is 1), then non-UNIQUE indexes +** are created in the output database before it is populated with +** recovered data. This is slower overall, but avoids the slow call +** to sqlite3_recover_step() at the end of the recovery operation. +** +** The default option value is 0. +*/ +#define SQLITE_RECOVER_LOST_AND_FOUND 1 +#define SQLITE_RECOVER_FREELIST_CORRUPT 2 +#define SQLITE_RECOVER_ROWIDS 3 +#define SQLITE_RECOVER_SLOWINDEXES 4 + +/* +** Perform a unit of work towards the recovery operation. This function +** must normally be called multiple times to complete database recovery. +** +** If no error occurs but the recovery operation is not completed, this +** function returns SQLITE_OK. If recovery has been completed successfully +** then SQLITE_DONE is returned. If an error has occurred, then an SQLite +** error code (e.g. SQLITE_IOERR or SQLITE_NOMEM) is returned. It is not +** considered an error if some or all of the data cannot be recovered +** due to database corruption. +** +** Once sqlite3_recover_step() has returned a value other than SQLITE_OK, +** all further such calls on the same recover handle are no-ops that return +** the same non-SQLITE_OK value. +*/ +int sqlite3_recover_step(sqlite3_recover*); + +/* +** Run the recovery operation to completion. Return SQLITE_OK if successful, +** or an SQLite error code otherwise. Calling this function is the same +** as executing: +** +** while( SQLITE_OK==sqlite3_recover_step(p) ); +** return sqlite3_recover_errcode(p); +*/ +int sqlite3_recover_run(sqlite3_recover*); + +/* +** If an error has been encountered during a prior call to +** sqlite3_recover_step(), then this function attempts to return a +** pointer to a buffer containing an English language explanation of +** the error. If no error message is available, or if an out-of memory +** error occurs while attempting to allocate a buffer in which to format +** the error message, NULL is returned. +** +** The returned buffer remains valid until the sqlite3_recover handle is +** destroyed using sqlite3_recover_finish(). +*/ +const char *sqlite3_recover_errmsg(sqlite3_recover*); + +/* +** If this function is called on an sqlite3_recover handle after +** an error occurs, an SQLite error code is returned. Otherwise, SQLITE_OK. +*/ +int sqlite3_recover_errcode(sqlite3_recover*); + +/* +** Clean up a recovery object created by a call to sqlite3_recover_init(). +** The results of using a recovery object with any API after it has been +** passed to this function are undefined. +** +** This function returns the same value as sqlite3_recover_errcode(). +*/ +int sqlite3_recover_finish(sqlite3_recover*); + + +#ifdef __cplusplus +} /* end of the 'extern "C"' block */ +#endif + +#endif /* ifndef _SQLITE_RECOVER_H */ diff --git a/lib/rgoose/rgooseNode2D.h b/lib/rgoose/rgooseNode2D.h index 8d032d8c..c7fac771 100644 --- a/lib/rgoose/rgooseNode2D.h +++ b/lib/rgoose/rgooseNode2D.h @@ -69,6 +69,7 @@ typedef struct S_SHADOW_IO_HELPER{ uint16_t m_nCurrentPoint; uint16_t m_nCurrentRayLine; uint16_t m_nCurrentRay; + uint8_t m_bSequence; }SHADOW_IO_HELPER; typedef struct S_GETFILE_IO_HELPER{ diff --git a/lib/rgoose/rgooseTypes.h b/lib/rgoose/rgooseTypes.h index ee14e128..782e963d 100644 --- a/lib/rgoose/rgooseTypes.h +++ b/lib/rgoose/rgooseTypes.h @@ -204,7 +204,7 @@ typedef enum E_ARGUS_CAM_TRIGGER_MODE{ typedef struct S_DBC_CAM_DATA{ uint32_t id; // uint32_t site_id; -// uint32_t node_id; + uint32_t node_id; uint32_t stream_id; bool online; uint8_t type;