From a77f34253ad48bf3069e2e122c93e396a9cadbca Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 09:04:07 +0000 Subject: [PATCH 01/10] Kernel watchdog: feed from its own thread while the kernel loop makes progress watchDogDaemon kills a client that misses its deadline (signal 9). The mojo kernel loop sent "4000" (next update within 4 s) at the start of each pass and then ran all validations in the same thread. A pass of about 3 s killed la_mojo, for example a gateway connect (5 s), rm -rf of a report day, or a synchronous systemctl restart of MediaMTX. kernelPrototype - A feeder thread (wdStart) sends KERNEL_WD_FEED_MS (4 s) every second while the kernel loop reports progress (wdStep). A loop without progress for KERNEL_WD_STALL_MS (60 s) is a hang: the feeding stops, logged as "Kernel loop stalled in '' for N s - watchdog no longer fed", and the daemon kills the process as before. - wdStep() logs steps slower than 1 s ("Kernel step '' took N ms"). The feeder logs a step that runs longer than 5 s every 5 s ("Kernel loop busy in '' for N s"), so the step is named before any kill. - wdExtend(): stops feeding and grants a one-time deadline. - send(MSG_NOSIGNAL) instead of write(): a watchDogDaemon that restarted closed the socket, and the next write() killed la_mojo with SIGPIPE. A lost connection is logged and closed. - The socket is closed when connect() fails (it leaked). - The feeder is opt-in: servaKernel is unchanged. mojoKernel - The loop calls wdStart() and names each step: debug mode, filters, session, reports, hardwareManager::validate, updateSysInfo, media helper, remote server, kernel commands, cleanNodePushedCMD. - ~mojoKernel grants KERNEL_WD_SHUTDOWN_MS (120 s) before deleting the factories / nodes / threads. Before, the 4 s of the last feed ran out and the daemon killed la_mojo in the middle of a reload / restart / exit. "-1" at the end goes through wdSend(). Tested with the real watchDogDaemon and a test kernel built on kernelPrototype (stall limit 8 s for the test): - old behaviour, one 6 s step: killed (137); - new, normal passes: runs to the end; - new, one 6 s step: not killed; logs "busy ... 5 s" and "took 6000 ms"; - new, a step that hangs: logs "stalled in ''", then killed (137). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16 --- lib/App/common/kernelPrototype.cpp | 144 ++++++++++++++++++++++++++++- lib/App/common/kernelPrototype.h | 37 ++++++++ lib/App/mojo/mojoKernel.cpp | 41 ++++---- 3 files changed, 203 insertions(+), 19 deletions(-) diff --git a/lib/App/common/kernelPrototype.cpp b/lib/App/common/kernelPrototype.cpp index 5d0ad771..5659c1ed 100644 --- a/lib/App/common/kernelPrototype.cpp +++ b/lib/App/common/kernelPrototype.cpp @@ -14,6 +14,16 @@ kernelPrototype * kernelPrototype::_instance = NULL; +#ifdef LINUX_KERNEL_WATCHDOG + #include +static uint64_t wdNowMs(void) +{ + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return (uint64_t) ts.tv_sec * 1000 + ts.tv_nsec / 1000000; +} +#endif + kernelPrototype * kernelPrototype::getInstance() { return _instance; @@ -25,7 +35,12 @@ kernelPrototype::kernelPrototype(config_setting_t * ptr) : { m_pLog = basicLogCollection::getInstance(); #ifdef LINUX_KERNEL_WATCHDOG - m_iWatchdogFd = -1; + m_iWatchdogFd = -1; + m_pWdThread = NULL; + m_bWdRun = false; + m_nWdProgressMs = wdNowMs(); + m_nWdStepStartMs = wdNowMs(); + m_pWdStep = "init"; struct sockaddr_un server_addr; int connection_result; @@ -39,6 +54,10 @@ kernelPrototype::kernelPrototype(config_setting_t * ptr) : if (connection_result == -1) { LOG_ERROR("WD Connection Error"); + if (m_iWatchdogFd > -1) + { + close(m_iWatchdogFd); // was leaked + }; m_iWatchdogFd = -1; }; if (m_iWatchdogFd < 0) @@ -63,8 +82,11 @@ kernelPrototype::kernelPrototype(config_setting_t * ptr) : char tB[64]; sprintf(tB, "%d\n", gettid()); LOG("PID SENT TO WD!"); - // ToDo: Make Error Handling here! - write(m_iWatchdogFd, &tB, strlen(tB)); + // MSG_NOSIGNAL: a daemon that restarted must not kill us with SIGPIPE + if (send(m_iWatchdogFd, tB, strlen(tB), MSG_NOSIGNAL) < 0) + { + LOG_ERROR("Watchdog: PID not sent"); + }; }; #endif m_pSettings = basicSettingsProvider::getInstance()->getSubNode(ptr, "KERNEL"); @@ -89,6 +111,7 @@ kernelPrototype::kernelPrototype(config_setting_t * ptr) : kernelPrototype::~kernelPrototype() { #ifdef LINUX_KERNEL_WATCHDOG + wdStop(); LOG("Closing WD!"); if (! (m_iWatchdogFd < 0)) { @@ -98,6 +121,121 @@ kernelPrototype::~kernelPrototype() #endif } +#ifdef LINUX_KERNEL_WATCHDOG +bool kernelPrototype::wdSend(int64_t ms) +{ + bool tOk = false; + m_mWdWrite.lock(); + if (m_iWatchdogFd > -1) + { + char tB[32]; + int tLen = snprintf(tB, sizeof(tB), "%lld\n", (long long) ms); + if (send(m_iWatchdogFd, tB, tLen, MSG_NOSIGNAL) == tLen) + { + tOk = true; + } + else + { + // Daemon gone (restarted / stopped): not monitored any more - and no SIGPIPE + LOG_ERROR("Watchdog connection lost - not monitored any more"); + close(m_iWatchdogFd); + m_iWatchdogFd = -1; + }; + }; + m_mWdWrite.unlock(); + return tOk; +} + +void kernelPrototype::wdStep(const char * step) +{ + uint64_t tNow = wdNowMs(); + const char * tPrev = m_pWdStep.exchange(step); + uint64_t tTook = tNow - m_nWdStepStartMs.exchange(tNow); + m_nWdProgressMs = tNow; + if (tTook > KERNEL_WD_SLOW_STEP_MS && tPrev != NULL && strcmp(tPrev, "idle") != 0) + { + char tB[128]; + snprintf(tB, sizeof(tB), "Kernel step '%s' took %llu ms", tPrev, (unsigned long long) tTook); + LOG_ERROR(tB); + }; +} + +void kernelPrototype::wdFeederProc(void) +{ + pthread_setname_np(pthread_self(), "KernelWD"); + uint64_t tLastSend = 0; + uint64_t tLastBusyLog = 0; + bool tStalled = false; + while (m_bWdRun) + { + uint64_t tNow = wdNowMs(); + uint64_t tIdle = tNow - m_nWdProgressMs; + uint64_t tBusy = tNow - m_nWdStepStartMs; + const char * tStep = m_pWdStep; + if (tIdle < KERNEL_WD_STALL_MS) + { + if (tStalled) + { + LOG("Kernel loop running again - watchdog fed"); + tStalled = false; + }; + if (tNow - tLastSend >= 1000) + { + wdSend(KERNEL_WD_FEED_MS); + tLastSend = tNow; + }; + if (tBusy >= KERNEL_WD_BUSY_LOG_MS && strcmp(tStep, "idle") != 0 && tNow - tLastBusyLog >= KERNEL_WD_BUSY_LOG_MS) + { + char tB[128]; + snprintf(tB, sizeof(tB), "Kernel loop busy in '%s' for %llu s", tStep, (unsigned long long) (tBusy / 1000)); + LOG_ERROR(tB); + tLastBusyLog = tNow; + }; + } + else if (! tStalled) + { + // A hang: stop feeding, the daemon kills the process after the last deadline + char tB[160]; + snprintf(tB, sizeof(tB), "Kernel loop stalled in '%s' for %llu s - watchdog no longer fed", tStep, (unsigned long long) (tIdle / 1000)); + LOG_ERROR(tB); + tStalled = true; + }; + SLEEP(100); + }; +} + +void kernelPrototype::wdStart(void) +{ + if (m_iWatchdogFd < 0 || m_pWdThread != NULL) + { + return; + }; + wdStep("start"); + m_bWdRun = true; + m_pWdThread = new std::thread(&kernelPrototype::wdFeederProc, this); +} + +void kernelPrototype::wdStop(void) +{ + if (m_pWdThread != NULL) + { + m_bWdRun = false; + if (m_pWdThread->joinable()) + { + m_pWdThread->join(); + }; + delete m_pWdThread; + m_pWdThread = NULL; + }; +} + +void kernelPrototype::wdExtend(uint32_t ms) +{ + wdStop(); + wdSend(ms); +} +#endif + void kernelPrototype::setWM(uint8_t mode) { m_mWMProtector.lock(); diff --git a/lib/App/common/kernelPrototype.h b/lib/App/common/kernelPrototype.h index 66c11aed..29d10d00 100644 --- a/lib/App/common/kernelPrototype.h +++ b/lib/App/common/kernelPrototype.h @@ -28,7 +28,26 @@ #include #include #include + + #include + #include +#endif + +/* + Watchdog (watchDogDaemon, UNIX socket /srv/etc/watchdog): a client sends its PID, then "N\n" = next update + within N ms; without it the daemon kills the process (signal 9), "-1" ends the monitoring. + The kernel loop fed it itself ("4000" at the start of each pass): a pass of ~3 s (gateway connect, rm -rf of + a report day, systemctl restart ...) got la_mojo killed. Now a feeder thread sends KERNEL_WD_FEED_MS every + second as long as the kernel loop reports progress (wdStep); a loop without progress for KERNEL_WD_STALL_MS + is a hang: the feeding stops (logged with the step it hangs in) and the daemon kills the process. +*/ +#define KERNEL_WD_FEED_MS 4000 // deadline sent every second +#ifndef KERNEL_WD_STALL_MS + #define KERNEL_WD_STALL_MS 60000 // kernel loop without progress this long = hung #endif +#define KERNEL_WD_SLOW_STEP_MS 1000 // steps slower than this are logged +#define KERNEL_WD_BUSY_LOG_MS 5000 // a step running longer is logged every 5 s (before the kill) +#define KERNEL_WD_SHUTDOWN_MS 120000 // deadline for the kernel shutdown (deleting factories / nodes / threads) #define EXIT_CODE_KERNEL_CLEAR 0 #define EXIT_CODE_RELOAD_SERVICES 1 @@ -51,6 +70,24 @@ class kernelPrototype : public basicThread, public basicEventHandler #ifdef LINUX_KERNEL_WATCHDOG int m_iWatchdogFd; + + private: + + std::thread * m_pWdThread; + std::atomic m_bWdRun; + std::atomic m_nWdProgressMs; // last wdStep() + std::atomic m_nWdStepStartMs; // start of the current step + std::atomic m_pWdStep; // current step (string literal) + basicMutex m_mWdWrite; + void wdFeederProc(void); + + protected: + + bool wdSend(int64_t ms); // "ms\n" to the daemon (-1 = stop monitoring); false if not connected + void wdStart(void); // start the feeder thread (the kernel loop must call wdStep()) + void wdStop(void); // stop feeding (the last deadline sent stays) + void wdStep(const char * step); // kernel loop progress: a new step begins (string literal!) + void wdExtend(uint32_t ms); // stop feeding and grant ms (e.g. for the shutdown) #endif /* basic */ basicLogCollection * m_pLog; diff --git a/lib/App/mojo/mojoKernel.cpp b/lib/App/mojo/mojoKernel.cpp index f52aa753..4d2b81ee 100644 --- a/lib/App/mojo/mojoKernel.cpp +++ b/lib/App/mojo/mojoKernel.cpp @@ -100,6 +100,11 @@ mojoKernel::mojoKernel(config_setting_t * ptr) : mojoKernel::~mojoKernel() { +#ifdef LINUX_KERNEL_WATCHDOG + // Deleting the factories / nodes / threads takes longer than one feed period: grant the shutdown its + // own deadline instead of the last 4 s (the daemon killed la_mojo in the middle of a reload / exit) + wdExtend(KERNEL_WD_SHUTDOWN_MS); +#endif WaitFinish(true); stopSession(false); @@ -183,13 +188,7 @@ mojoKernel::~mojoKernel() } #ifdef LINUX_KERNEL_WATCHDOG LOG("Disable WD!"); - if (m_iWatchdogFd > -1) - { - char tB[64]; - sprintf(tB, "-1\n"); - // ToDo: Make Error Handling here! - write(m_iWatchdogFd, &tB, strlen(tB)); - }; + wdSend(-1); // MSG_NOSIGNAL: no SIGPIPE if the daemon is gone LOG("WatchDog turned Off!"); #endif // Events broadcast while the components were deleted must not reach the next kernel (restart) @@ -786,7 +785,14 @@ void mojoKernel::m_fThreadProc(void){ time_t tTimeTSeconds = 0; m_bThreadStatus = TH_WORKING; pthread_setname_np( pthread_self(), "Kernel" ); +#ifdef LINUX_KERNEL_WATCHDOG + wdStart(); // the watchdog is fed by its own thread while this loop reports progress (wdStep) + #define KWD_STEP(X) wdStep(X) +#else + #define KWD_STEP(X) +#endif while (m_bThreadStatus < TH_ENDED){ + KWD_STEP("idle"); m_tTimeTSeconds = time(NULL); // Each Second if (m_tTimeTSeconds != tTimeTSeconds){ @@ -800,34 +806,33 @@ void mojoKernel::m_fThreadProc(void){ continue; }; }; -#ifdef LINUX_KERNEL_WATCHDOG - if (m_iWatchdogFd > -1){ - char tB[64]; - sprintf(tB, "4000\n"); - // ToDo: Make Error Handling here! - write(m_iWatchdogFd, &tB, strlen(tB)); - }; -#endif + KWD_STEP("debug mode"); m_bDebugMode = m_pDBC->getAppDebugMode(); + KWD_STEP("validateFilters"); validateFilters(); + KWD_STEP("validateSession"); validateSession(); + KWD_STEP("validateReports"); validateReports(); - //?? + KWD_STEP("hardwareManager::validate"); if (! m_pHardwareManager->validate()){ LOG("Reload Mojo Node Due to Memory Consumption!"); m_bThreadStatus = TH_ENDED; setExitCause(EXIT_CODE_KERNEL_CLEAR); continue; }; + KWD_STEP("updateSysInfo"); m_mSysInfoProtector.lock(); m_pHardwareManager->updateSysInfo(&m_sSysInfo); m_mSysInfoProtector.unlock(); #ifndef LRF_PROXY_ONLY if ( m_pMediaHelper ) { + KWD_STEP("mediaHelper::validateService"); m_pMediaHelper->validateService(); }; #endif + KWD_STEP("remote server"); if (m_sSiteData.use_remote_server){ if (m_pRPC){ m_pRPC->validate(); @@ -848,6 +853,7 @@ void mojoKernel::m_fThreadProc(void){ }; }; }; + KWD_STEP("kernel commands"); DBC_PUSHED_CMD * tCMD = m_pDBC->getNodePushedCMD(m_nServerNodeID); // Kernel if (tCMD != NULL) { m_pDBC->updateNodePushedCMD(tCMD->id, DBC_CMD_STARTED); @@ -1030,11 +1036,14 @@ void mojoKernel::m_fThreadProc(void){ free(tCMD); }; if ( m_pDBC ){ + KWD_STEP("cleanNodePushedCMD"); m_pDBC->cleanNodePushedCMD(); } }; SLEEP(SLEEP_KERNEL_INTERVAL); }; + KWD_STEP("exit"); // the destructor grants the shutdown its own deadline (wdExtend) + #undef KWD_STEP } void mojoKernel::loadFilters() From 0d043cd106f0360bcde6efa8afbc3d8890b8f7ec Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 09:06:59 +0000 Subject: [PATCH 02/10] Kernel loop: move long blocking work out of it Every pass of the mojo kernel loop ran these synchronously; each could stall the loop (and get la_mojo killed by the watchdog): - Report cleanup (validateReports -> deleteReportDate): deleteRDFDir ran "rm -f -R " (seconds to minutes on an SD card), daily or every second while the disk is above preserve_empty. The day is now deleted in a background thread (one at a time; calls during it return false). ~sqliteDBC waits for a running deletion (max 60 s). - MediaMTX (validateService -> restart): "systemctl restart" waited for the service to stop and start, every second if the config kept failing validation. Now "systemctl --no-block restart" (only queues the job), at most once per KH_MTX_RESTART_MIN_S (30 s). - IP UART serial provider (hardwareManager::validate -> create_SOL): a blocking connect() to an address that doesn't answer took ~2 min (SYN retries). Now non-blocking with SERIAL_SOL_CONNECT_TIMEOUT_MS (5 s), the socket mode restored afterwards, and the socket closed on failure (it leaked). - Ethernet2UART gateway nodes: hardwareManager::validate (kernel loop) validated and reconnected them again, although the node factory thread does it (deviceNode::validate). Connects of up to 5 s blocked the kernel loop, plus the wait for the node's connection lock. hardwareResource::selfValidating() (default false) is true for deviceETH2UART, and the hardware manager skips such resources. Tested: the connect timeout on its own (extracted unchanged). A peer that drops the SYN failed after 5002 ms ("Connection timed out") instead of ~2 min; refused and accepted connects are immediate; the socket is blocking again in every case. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16 --- lib/App/common/SQLite_dataBinder.cpp | 46 +++++++++++++++++-- lib/App/common/deviceNodeEthernet2Serial.h | 5 ++ lib/App/common/hardwareManager.cpp | 4 ++ lib/App/common/hardwareResource.h | 7 +++ .../common/hardwareResourceSerialProvider.cpp | 46 +++++++++++++++++-- .../common/hardwareResourceSerialProvider.h | 4 ++ lib/App/common/kernelHelperMediaMTX.cpp | 15 +++++- lib/App/common/kernelHelperMediaMTX.h | 6 +++ 8 files changed, 125 insertions(+), 8 deletions(-) diff --git a/lib/App/common/SQLite_dataBinder.cpp b/lib/App/common/SQLite_dataBinder.cpp index a629deb2..5cd83b28 100644 --- a/lib/App/common/SQLite_dataBinder.cpp +++ b/lib/App/common/SQLite_dataBinder.cpp @@ -1,5 +1,12 @@ #include "SQLite_dataBinder.h" +#include +#include +#include + +// A report day is being deleted in the background (deleteReportDate) +static std::atomic s_bReportDayDeleting(false); + #include "../../components/base/basicEvent.h" #define LOG(X) m_pLog->Log("SDBC", this, X) @@ -109,6 +116,11 @@ sqliteDBC::sqliteDBC(config_setting_t * Settings) : sqliteDBC::~sqliteDBC() { + // A report day still being deleted in the background uses this object (deleteReportStat) + for (int i = 0; i < 600 && s_bReportDayDeleting; i++) + { + SLEEP(100); + }; if (m_pDataStorage) { delete(m_pDataStorage); @@ -2415,18 +2427,44 @@ uint32_t sqliteDBC::getFirstEventTS() return rv; } +/* + Called from the kernel loop (validateReports: daily cleanup, or every second while the disk is above + preserve_empty). deleteRDFDir() runs "rm -f -R " - many seconds (minutes on a big SD card): + the kernel loop stalled and the watchdog killed la_mojo. The day is deleted in a background thread; + while it runs, further calls return false (the oldest day is still listed until it is done). +*/ bool sqliteDBC::deleteReportDate(uint32_t ts) { if (ts) { + bool tFalse = false; + if (! s_bReportDayDeleting.compare_exchange_strong(tFalse, true)) + { + return false; // a day is being deleted + }; REPORT_DIRINFO tRDF;// = {0}; fillRDF(ts, tRDF); - LOG("Delete RDF Dir"); - if (deleteRDFDir(m_pDbReportBase, tRDF)) + std::string tBase(m_pDbReportBase); + LOG("Delete RDF Dir (background)"); + try { - LOG("Dir Deleted OK"); - return deleteReportStat(tRDF); + std::thread([this, tBase, tRDF]() mutable { + pthread_setname_np(pthread_self(), "ReportDelete"); + if (deleteRDFDir((CSTR) tBase.c_str(), tRDF)) + { + LOG("Dir Deleted OK"); + deleteReportStat(tRDF); + }; + s_bReportDayDeleting = false; + }).detach(); + } + catch (const std::exception & e) + { + s_bReportDayDeleting = false; + LOG_ERROR("Can not start the report delete thread"); + return false; }; + return true; }; return false; } diff --git a/lib/App/common/deviceNodeEthernet2Serial.h b/lib/App/common/deviceNodeEthernet2Serial.h index 5c904a02..ea60b3d4 100644 --- a/lib/App/common/deviceNodeEthernet2Serial.h +++ b/lib/App/common/deviceNodeEthernet2Serial.h @@ -121,6 +121,11 @@ { return true; } + // validated and reconnected by the node factory (deviceNode::validate) - not by the hardware manager + virtual bool selfValidating(void) + { + return true; + } }; #endif diff --git a/lib/App/common/hardwareManager.cpp b/lib/App/common/hardwareManager.cpp index d5d8bf01..1b0b8dec 100644 --- a/lib/App/common/hardwareManager.cpp +++ b/lib/App/common/hardwareManager.cpp @@ -451,6 +451,10 @@ bool hardwareManager::validate(void) { for (VECTOR_HW_RESOURCES::iterator idx = m_vResources.begin(); idx < m_vResources.end(); idx++) { + if ((*idx)->selfValidating()) + { + continue; // its node validates / reconnects it (node factory thread) + }; if (! (*idx)->validate()) { // recreate Resource diff --git a/lib/App/common/hardwareResource.h b/lib/App/common/hardwareResource.h index ca9c41e3..f2d7f692 100644 --- a/lib/App/common/hardwareResource.h +++ b/lib/App/common/hardwareResource.h @@ -64,6 +64,13 @@ class hardwareResource : public basicObject virtual bool create(uint32_t id, HARDWARE_PROVIDERS type); + // true: the resource is validated / reconnected by its owner (e.g. a deviceNode in the node factory + // thread) - the hardware manager (kernel loop) must not do it again: a gateway connect blocked the + // kernel loop for seconds, and two threads reconnected the same object + virtual bool selfValidating(void){ + return false; + } + virtual bool validate(void){ return m_bValid; } diff --git a/lib/App/common/hardwareResourceSerialProvider.cpp b/lib/App/common/hardwareResourceSerialProvider.cpp index 3c89ce37..580df8f0 100644 --- a/lib/App/common/hardwareResourceSerialProvider.cpp +++ b/lib/App/common/hardwareResourceSerialProvider.cpp @@ -229,6 +229,43 @@ bool hardwareResourceSerialProvider::pingDevice() return RetVal; } +#include +// connect() bounded by timeoutMs (the socket is left in blocking mode as before). false: errno set +static bool connectWithTimeout(int fd, struct sockaddr * addr, socklen_t len, int timeoutMs) +{ + int tFlags = fcntl(fd, F_GETFL, 0); + fcntl(fd, F_SETFL, tFlags | O_NONBLOCK); + int tRc = connect(fd, addr, len); + if (tRc != 0 && errno == EINPROGRESS) + { + struct pollfd tPfd; + tPfd.fd = fd; + tPfd.events = POLLOUT; + do + { + tRc = poll(&tPfd, 1, timeoutMs); + } + while (tRc < 0 && errno == EINTR); + if (tRc == 0) + { + errno = ETIMEDOUT; + tRc = -1; + } + else if (tRc > 0) + { + int tErr = 0; + socklen_t tL = sizeof(tErr); + getsockopt(fd, SOL_SOCKET, SO_ERROR, &tErr, &tL); + errno = tErr; + tRc = (tErr == 0) ? 0 : -1; + }; + }; + int tErrno = errno; + fcntl(fd, F_SETFL, tFlags); // back to the caller's mode in every case + errno = tErrno; + return tRc == 0; +} + bool hardwareResourceSerialProvider::create_SOL() { @@ -392,12 +429,15 @@ bool hardwareResourceSerialProvider::create_SOL() tServerAddr.sin_addr.s_addr = inet_addr(m_sUartData.path); tServerAddr.sin_port = htons(m_sUartData.port); - // connect the client socket to server socket - if (connect(m_iDeviceFD, (struct sockaddr *) &tServerAddr, sizeof(tServerAddr)) != 0) + // connect the client socket to server socket - with a timeout: a blocking connect() to an address + // that does not answer took ~2 min (SYN retries) inside hardwareManager::validate() = the kernel loop + if (! connectWithTimeout(m_iDeviceFD, (struct sockaddr *) &tServerAddr, sizeof(tServerAddr), SERIAL_SOL_CONNECT_TIMEOUT_MS)) { char cBuffer[256]; - sprintf(cBuffer, "ERROR connect to [%s:%d] (%s)", m_sUartData.path, m_sUartData.port, strerror(errno)); + snprintf(cBuffer, sizeof(cBuffer), "ERROR connect to [%.64s:%d] (%s)", m_sUartData.path, m_sUartData.port, strerror(errno)); LOG_ERROR(cBuffer); + close(m_iDeviceFD); // was leaked + m_iDeviceFD = -1; return false; } #ifdef DEBUG diff --git a/lib/App/common/hardwareResourceSerialProvider.h b/lib/App/common/hardwareResourceSerialProvider.h index f8234808..725a37da 100644 --- a/lib/App/common/hardwareResourceSerialProvider.h +++ b/lib/App/common/hardwareResourceSerialProvider.h @@ -43,6 +43,10 @@ // #define DEBUG_SERIAL_COMMUNICATION #endif +#ifndef SERIAL_SOL_CONNECT_TIMEOUT_MS + #define SERIAL_SOL_CONNECT_TIMEOUT_MS 5000 // TCP connect to an IP UART (serial over LAN / Internet) +#endif + #if defined( HALF_DUPLEX ) || defined( SERIAL_PING_PONG ) class hardwareResourceSerialProvider : public hardwareResource, public basicTransport, public basicThread diff --git a/lib/App/common/kernelHelperMediaMTX.cpp b/lib/App/common/kernelHelperMediaMTX.cpp index dfca069b..ffaac806 100644 --- a/lib/App/common/kernelHelperMediaMTX.cpp +++ b/lib/App/common/kernelHelperMediaMTX.cpp @@ -28,6 +28,7 @@ kernelHelperMediaMTX::kernelHelperMediaMTX(): basicThread() { memset( m_sAppConfigFile, 0, 512 ); m_nLastLogSize = 0; m_bRecordMode = false; + m_tLastRestart = 0; if( loadConfig() ) m_bStatus = KH_STATUS_MTX_INIT; } @@ -49,8 +50,20 @@ bool kernelHelperMediaMTX::create(){ return init(); } +/* + Called from the kernel loop (validateService, every second when the config does not validate). + "systemctl restart" waited for the service to stop and start (many seconds) - the kernel loop stalled + and the watchdog killed la_mojo. --no-block only queues the restart job; at most one restart per + KH_MTX_RESTART_MIN_S (a config that keeps failing validation restarted MediaMTX every second). +*/ bool kernelHelperMediaMTX::restart(){ - int RetVal = system( "systemctl restart mediamtx.service" ); + time_t tNow = time( NULL ); + if ( m_tLastRestart != 0 && ( tNow - m_tLastRestart ) < KH_MTX_RESTART_MIN_S ) { + return true; // restarted a moment ago: the config is re-checked after the period + }; + m_tLastRestart = tNow; + LOG( "Restart MediaMTX (queued)" ); + int RetVal = system( "systemctl --no-block restart mediamtx.service" ); if ( RetVal == -1 ) return false; return true; } diff --git a/lib/App/common/kernelHelperMediaMTX.h b/lib/App/common/kernelHelperMediaMTX.h index 14611ae8..a4abd84c 100644 --- a/lib/App/common/kernelHelperMediaMTX.h +++ b/lib/App/common/kernelHelperMediaMTX.h @@ -44,6 +44,11 @@ typedef std::map M_StreamMap; // inodes -> info typedef std::map M_VideoSegmentInfo; // stream_id -> map +// At most one MediaMTX restart per this period (a config that keeps failing validation restarted it every second) +#ifndef KH_MTX_RESTART_MIN_S + #define KH_MTX_RESTART_MIN_S 30 +#endif + class kernelHelperMediaMTX: public basicThread { private: basicLogCollection * m_pLog; @@ -57,6 +62,7 @@ class kernelHelperMediaMTX: public basicThread { char m_sRecordsBase[MAX_PATH_LEN]; off_t m_nLastLogSize; bool m_bRecordMode; + time_t m_tLastRestart; // last restart() (rate limit) bool loadConfig(); bool loadStreams(); StreamSegmentRecord * createSSR( uint32_t stream_id, uint32_t streamTSS, uint32_t streamTMS, CSTR path ); From 6cdca3c07530046eee1e4425498d4982aeea2511 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 09:09:05 +0000 Subject: [PATCH 03/10] watchDogDaemon: line buffer, end on client EOF, handler cleanup; la_mojo sends getpid() watchDogDaemon (kernel.cpp) - Client lines are assembled in a buffer. readLine() on the non-blocking socket dropped the bytes of a line that had only partly arrived. - EOF (client closed or crashed without "-1") ends the monitoring of that client. Before, EOF read as "no data", and after the deadline kill(9) went to a PID that may belong to another process by then. - The handler record is zeroed. "finished" was uninitialized (malloc), so the accept loop could pthread_join() a live handler and block. - Finished handlers are joined, freed and erased correctly. erase() inside the for loop skipped the next one, and the records were never freed. A record whose thread could not be created is freed. pthread_create() returns an error number, not -1. - The bind() result is checked. - The log says which PID is watched or stopped, and for a stall how long ago the last update was ("WD update STALLED! (PID n, last update N ms ago)"). kernelPrototype - Sends getpid() as the PID to kill (was gettid(): the same value only in the main thread). Tested with the rebuilt daemon: the kernel scenarios as before (normal, 6 s step: not killed; hang: killed). A client that closes without "-1": its process isn't killed later. An update split into 3 pieces, 6 times with a 4 s deadline: understood, not killed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16 --- Projects/watchDogDaemon/kernel.cpp | 164 +++++++++++++++++------------ Projects/watchDogDaemon/kernel.h | 2 +- lib/App/common/kernelPrototype.cpp | 2 +- 3 files changed, 100 insertions(+), 68 deletions(-) diff --git a/Projects/watchDogDaemon/kernel.cpp b/Projects/watchDogDaemon/kernel.cpp index e2bbe9bf..dd9623f6 100644 --- a/Projects/watchDogDaemon/kernel.cpp +++ b/Projects/watchDogDaemon/kernel.cpp @@ -219,10 +219,9 @@ bool SP_KERNEL::create(void) int x = fcntl(m_iServerSocket, F_GETFL, 0); fcntl(m_iServerSocket, F_SETFL, x | O_NONBLOCK); - bind(m_iServerSocket, (struct sockaddr *) &server_addr, slen); - if (m_iServerSocket == INVALID_SOCKET) + if (m_iServerSocket == INVALID_SOCKET || bind(m_iServerSocket, (struct sockaddr *) &server_addr, slen) != 0) { - LOG_ERROR("Could not bind to the UX socket!"); + LOG_ERROR("Could not bind to the UX socket!"); // the bind() result was not checked return false; }; listen(m_iServerSocket, 5); @@ -234,69 +233,102 @@ void SP_KERNEL::WaitFinish(bool force) waitThreadEnd(force); } +/* + One client: first line = PID to kill, then "N" = next update within N ms, "-1" = stop monitoring. + - Lines are assembled in a buffer: readLine() on the non-blocking socket dropped the bytes of a line + that had only partly arrived. + - EOF (the client closed / crashed without "-1") ends the monitoring: before, EOF read as "no data" + and after the deadline kill(9) went to a PID that may belong to another process by then. +*/ void * SP_KERNEL::sw_proc(void * ptr) { - char tB[64]; - uint64_t cMS; - uint64_t tMS; - WATCHDOG_PROC_REC * mR = (WATCHDOG_PROC_REC *) ptr; + WATCHDOG_PROC_REC * mR = (WATCHDOG_PROC_REC *) ptr; pid_t CPID = 0; + char tLine[128]; + size_t tHave = 0; + char jB[192]; if (mR) { - cMS = getMilliseconds(); - tMS = cMS + SW_DEFAULT_TIMEOUT; - while (1) + uint64_t tLastUpdate = getMilliseconds(); + uint64_t tMS = tLastUpdate + SW_DEFAULT_TIMEOUT; + bool tRun = true; + while (tRun) { - cMS = getMilliseconds(); - int retVal = readLine(mR->client_socket, tB, 64); - if (retVal < 0) - { - if (errno != EAGAIN && errno != EINTR) - { - mR->master->m_pLog->Log("K_T", mR->master, "Peer Closes Connection!"); - shutdown(mR->client_socket, 2); - close(mR->client_socket); - mR->client_socket = -1; - break; //-----> exit thread - }; - } - else + uint64_t cMS = getMilliseconds(); + // read what is there (non-blocking) + for (;;) { - if (retVal) + char tB[64]; + ssize_t tN = read(mR->client_socket, tB, sizeof(tB)); + if (tN > 0) { - // char jB[128]; - // sprintf( jB, "Server: I recieved [%d] %s from client!", retVal, tB ); - // mR->master->m_pLog->Log( "K_T", mR->master, jB ); - if (CPID) + for (ssize_t k = 0; k < tN; k++) { - int64_t nMS = atoll(tB); - // Stop WD and exit - if (nMS < 0) + if (tB[k] == '\n' || tB[k] == '\r') + { + if (tHave == 0) + { + continue; + }; + tLine[tHave] = 0; + tHave = 0; + if (CPID == 0) + { + CPID = (pid_t) atoll(tLine); + snprintf(jB, sizeof(jB), "Watching PID %d", (int) CPID); + mR->master->m_pLog->Log("K_T", mR->master, jB); + } + else + { + int64_t nMS = atoll(tLine); + if (nMS < 0) + { + snprintf(jB, sizeof(jB), "PID %d: monitoring stopped by the client", (int) CPID); + mR->master->m_pLog->Log("K_T", mR->master, jB); + tRun = false; // Stop WD and exit + break; + }; + tMS = cMS + nMS; + tLastUpdate = cMS; + }; + } + else if (tHave < sizeof(tLine) - 1) { - shutdown(mR->client_socket, 2); - close(mR->client_socket); - mR->client_socket = -1; - break; + tLine[tHave++] = tB[k]; }; - // sprintf( jB, "Will Wait next [%d] milliseconds", nMS ); - // mR->master->m_pLog->Log( "K_T", mR->master, jB ); - tMS = cMS + nMS; - } - else + }; + if (! tRun) { - CPID = (pid_t) atoll(tB); + break; }; + continue; }; + if (tN == 0) + { + snprintf(jB, sizeof(jB), "PID %d: peer closed the connection - monitoring ended", (int) CPID); + mR->master->m_pLog->Log("K_T", mR->master, jB); + tRun = false; + } + else if (errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR) + { + mR->master->m_pLog->Log("K_T", mR->master, "Peer Closes Connection!"); + tRun = false; + }; + break; + }; + if (! tRun) + { + break; }; if (cMS > tMS) { // WD TO EXIT! - mR->master->m_pLog->Log("K_T", mR->master, "WD update STALLED!"); + snprintf(jB, sizeof(jB), "WD update STALLED! (PID %d, last update %llu ms ago)", (int) CPID, (unsigned long long) (cMS - tLastUpdate)); + mR->master->m_pLog->Log("K_T", mR->master, jB); if (CPID) { // Try Kill Client Process; - char jB[128]; - sprintf(jB, "Try Killing Process[%lld] By Signal 9!", CPID); + snprintf(jB, sizeof(jB), "Try Killing Process[%d] By Signal 9!", (int) CPID); mR->master->m_pLog->Log("K_T", mR->master, jB); kill(CPID, 9); } @@ -308,17 +340,13 @@ void * SP_KERNEL::sw_proc(void * ptr) }; SLEEP(SW_TIMEOUT_PERCISION); }; + shutdown(mR->client_socket, 2); + close(mR->client_socket); + mR->client_socket = -1; + mR->finished = true; }; - mR->finished = true; pthread_exit(NULL); return NULL; - /* - read(client_socket, &ch, 1); - printf("\nServer: I recieved %c from client!\n", ch); - ch++; - write(client_socket, &ch, 1); - close(client_socket); - */ } void SP_KERNEL::m_fThreadProc(void) @@ -338,20 +366,20 @@ void SP_KERNEL::m_fThreadProc(void) { case EAGAIN: { - // Checkup client disconnection - if (m_vWPV.size()) + // Checkup client disconnection: join and free finished handlers + // (erase() inside the for loop skipped the next handler; the records were never freed) + for (WATCHDOG_PROCS_VECTOR::iterator index = m_vWPV.begin(); index != m_vWPV.end();) { - for (WATCHDOG_PROCS_VECTOR::iterator index = m_vWPV.begin(); index < m_vWPV.end(); index++) + if ((*index)->finished) { - if ((*index)->finished) - { - LOG("Detach WD Procedure"); - pthread_join((*index)->handler, NULL); - LOG("WD Procedure Detached"); - // Remove Client Handler - LOG("Remove WD Procedure"); - m_vWPV.erase(index); - }; + pthread_join((*index)->handler, NULL); + LOG("WD Procedure Removed"); + free(*index); + index = m_vWPV.erase(index); + } + else + { + ++index; }; }; SLEEP(10); @@ -391,14 +419,18 @@ void SP_KERNEL::m_fThreadProc(void) int x = fcntl(ClientSocket, F_GETFL, 0); fcntl(ClientSocket, F_SETFL, x | O_NONBLOCK); + memset(tPRC, 0, sizeof(WATCHDOG_PROC_REC)); // finished was uninitialized (malloc): a live handler + // could be joined - the accept loop blocked tPRC->client_socket = ClientSocket; tPRC->master = this; + tPRC->finished = false; int RetVal = pthread_create(&tPRC->handler, NULL, sw_proc, (void *) tPRC); - if (RetVal == -1) + if (RetVal != 0) // pthread_create returns an error number, not -1 { LOG_ERROR("No Client Thread Created!"); shutdown(ClientSocket, 2); close(ClientSocket); + free(tPRC); } else { diff --git a/Projects/watchDogDaemon/kernel.h b/Projects/watchDogDaemon/kernel.h index 95fae411..19bf5c13 100644 --- a/Projects/watchDogDaemon/kernel.h +++ b/Projects/watchDogDaemon/kernel.h @@ -16,7 +16,7 @@ typedef struct S_WATCHDOG_PROC_REC SP_KERNEL * master; int client_socket; uint64_t timeout; - bool finished; + volatile bool finished; pthread_t handler; } WATCHDOG_PROC_REC; diff --git a/lib/App/common/kernelPrototype.cpp b/lib/App/common/kernelPrototype.cpp index 5659c1ed..16652cd5 100644 --- a/lib/App/common/kernelPrototype.cpp +++ b/lib/App/common/kernelPrototype.cpp @@ -80,7 +80,7 @@ kernelPrototype::kernelPrototype(config_setting_t * ptr) : // LOG( (char *) ident.identity ); // LOG( ident.firmware_version ); char tB[64]; - sprintf(tB, "%d\n", gettid()); + sprintf(tB, "%d\n", (int) getpid()); // the process to kill (was gettid(): same value only in the main thread) LOG("PID SENT TO WD!"); // MSG_NOSIGNAL: a daemon that restarted must not kill us with SIGPIPE if (send(m_iWatchdogFd, tB, strlen(tB), MSG_NOSIGNAL) < 0) From ec409b37ca5fcf32e41543a5e0194ea4550854c8 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 11:45:27 +0000 Subject: [PATCH 04/10] Sensor: re-initialise after a gateway reconnect; say why a gateway connection dropped Field: the Ethernet2UART gateway connection dropped and reconnected within a second ("Peer Closes Connection!" -> "Connected to ..."), but the 2D sensor stayed offline until la_mojo was restarted. The sensor was re-initialised (MODE_DETECTOR + handshake) only if its thread saw the transport's short CS_DISCONNECTED. On a fast reconnect it did not, and stayed in idle mode, believing the device to be in detector mode (m_bActualDeviceWM) and only polling getState2. A device that left detector mode while the link was down was never set back. A restart starts from MODE_NONE, which is why it helped. - basicTransport::getConnectEpoch(): +1 on every change to CS_CONNECTED. - device2DSensor remembers the epoch when it binds its port (connectMode). validateCommunicationRessource() (every loop pass above connection mode) runs the connection sequence again when the epoch changed: "Transport reconnected - re-initialising the sensor". - deviceETH2UART: "Peer Closes Connection!" says why: "closed by the gateway" (FIN) or "error: " (e.g. Connection timed out = sent data not acknowledged within E2UART_TCP_USER_TIMEOUT_MS), plus the TCP_INFO figures. Tested with the real gateway class: a device that goes silent (reconnect after 5 unanswered requests) and a gateway that closes the connection. After each reconnect the epoch changes (1 -> 2), so the sensor would re-initialise, and requests are answered again. The close is logged as "closed by the gateway; TCP: ...". ASan clean. The full 2D sensor can't run here. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16 --- lib/App/common/deviceNode2D.cpp | 16 +++++++++++++++ lib/App/common/deviceNode2D.h | 1 + lib/App/common/deviceNodeEthernet2Serial.cpp | 21 +++++++++++++++++++- lib/components/base/basicTransport.cpp | 5 +++++ lib/components/base/basicTransport.h | 7 +++++++ 5 files changed, 49 insertions(+), 1 deletion(-) diff --git a/lib/App/common/deviceNode2D.cpp b/lib/App/common/deviceNode2D.cpp index 3298081f..c855d193 100644 --- a/lib/App/common/deviceNode2D.cpp +++ b/lib/App/common/deviceNode2D.cpp @@ -36,6 +36,7 @@ device2DSensor::device2DSensor(uint32_t id) : protocolLGS_2D() { m_pPort = NULL; + m_nPortEpoch = 0; m_bPortType = 0; m_bOpRetryCnt = LGS_CMD_RETRY_COUNT; m_nProcessingCmdId = 0; @@ -302,6 +303,7 @@ void device2DSensor::connectMode() updateDataStatus(ARGUS_DS_CONNECTING); m_bActualDeviceWM = MODE_NONE; m_bRequestedDeviceWM = MODE_NONE; + m_nPortEpoch = m_pPort->getConnectEpoch(); transactionSetResult(TRANSACTION_RESULT_OK); break; }; @@ -3302,6 +3304,20 @@ void device2DSensor::proceedDBCommands() bool device2DSensor::validateCommunicationRessource() { + /* + The transport (e.g. an Ethernet2UART gateway) reconnected since the sensor was initialised: run the + connection sequence again (MODE_DETECTOR + handshake). The sensor may have left detector mode while + the link was down; a fast reconnect was not seen here as CS_DISCONNECTED, so the sensor was only + polled in idle mode (getState2), believed to be in detector mode, and stayed "offline" until a restart. + */ + if (m_pPort != NULL && m_pPort->getConnectEpoch() != m_nPortEpoch) + { + LOG("Transport reconnected - re-initialising the sensor"); + m_nPortEpoch = m_pPort->getConnectEpoch(); + updateDataStatus(ARGUS_DS_DISCONNECTED); + setWM(LRF_WM_CONNECTION); + return false; + }; if (getConnectionStatus() != CS_CONNECTED) { #ifdef DEBUG_EXTRA diff --git a/lib/App/common/deviceNode2D.h b/lib/App/common/deviceNode2D.h index 190f7d25..8528a223 100644 --- a/lib/App/common/deviceNode2D.h +++ b/lib/App/common/deviceNode2D.h @@ -135,6 +135,7 @@ class device2DSensor : public deviceNodeSensor, public protocolLGS_2D uint8_t m_bPortType; basicTransport * m_pPort; + uint32_t m_nPortEpoch; // m_pPort->getConnectEpoch() when the sensor was (re)initialised uint32_t m_nSleepTime; uint8_t m_bInitialFlips; uint16_t m_nCurrentAngle; diff --git a/lib/App/common/deviceNodeEthernet2Serial.cpp b/lib/App/common/deviceNodeEthernet2Serial.cpp index 4ae0efed..38c333d0 100644 --- a/lib/App/common/deviceNodeEthernet2Serial.cpp +++ b/lib/App/common/deviceNodeEthernet2Serial.cpp @@ -1311,7 +1311,26 @@ int deviceETH2UART::recptBlock(unsigned char * Buffer, int * BufferLength) { if (RetVal == 0 || (errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR)) { - LOG_ERROR("Peer Closes Connection!"); + // Closed by the gateway (FIN) or an error - e.g. ETIMEDOUT: sent data not acknowledged + // within E2UART_TCP_USER_TIMEOUT_MS, ECONNRESET: reset by the gateway / a NAT on the way + char tWhy[96]; + if (RetVal == 0) + { + snprintf(tWhy, sizeof(tWhy), "closed by the gateway"); + } + else + { + snprintf(tWhy, sizeof(tWhy), "error: %s", strerror(errno)); + }; + char tTcp[160]; +#ifdef SERIAL_PING_PONG + tcpInfoText(tTcp, sizeof(tTcp)); +#else + tTcp[0] = 0; +#endif + char tB[320]; + snprintf(tB, sizeof(tB), "Peer Closes Connection! (%s; %s)", tWhy, tTcp); + LOG_ERROR(tB); shutdown(m_iDeviceFD, 2); close(m_iDeviceFD); *BufferLength = 0; diff --git a/lib/components/base/basicTransport.cpp b/lib/components/base/basicTransport.cpp index af59161f..501bb724 100644 --- a/lib/components/base/basicTransport.cpp +++ b/lib/components/base/basicTransport.cpp @@ -11,6 +11,7 @@ basicTransport::basicTransport() : { m_pLog = basicLogCollection::getInstance(); m_eConnectionStatus = CS_UNKNOWN; + m_nConnectEpoch = 0; } basicTransport::~basicTransport() @@ -48,6 +49,10 @@ bool basicTransport::removeRecipient(protocolParser * ProtoParser) void basicTransport::setConnectionStatus(CONNECTION_STATUS CS) { m_mQueueProtectorMutex.lock(); + if (CS == CS_CONNECTED && m_eConnectionStatus != CS_CONNECTED) + { + m_nConnectEpoch = m_nConnectEpoch + 1; + }; m_eConnectionStatus = CS; for (parseQueue::iterator index = m_vParsers.begin(); index != m_vParsers.end(); index++) { diff --git a/lib/components/base/basicTransport.h b/lib/components/base/basicTransport.h index bf327293..e56861e3 100644 --- a/lib/components/base/basicTransport.h +++ b/lib/components/base/basicTransport.h @@ -57,6 +57,7 @@ class basicTransport basicMutex m_mBufferProtectorMutex; CONNECTION_STATUS m_eConnectionStatus; + volatile uint32_t m_nConnectEpoch; // +1 on every change to CS_CONNECTED (a reconnect) public: @@ -93,6 +94,12 @@ class basicTransport } void setConnectionStatus(CONNECTION_STATUS ES); + // Changes on every (re)connect: a user bound to this transport sees a reconnect it did not notice + // as a short CS_DISCONNECTED (a device behind it may have lost its state meanwhile) + uint32_t getConnectEpoch(void) + { + return m_nConnectEpoch; + } CONNECTION_STATUS getConnectionStatus(void); virtual int getRawHandle(void) From 079225e69286f0f0c2e59981e949016acd1082d3 Mon Sep 17 00:00:00 2001 From: Evgeny Gagua Date: Wed, 2 Dec 2026 13:49:29 +0200 Subject: [PATCH 05/10] Fixing Pipeline --- lib/App/common/targetPipeLine.cpp | 3 +-- lib/App/common/targetPipeLine.h | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/lib/App/common/targetPipeLine.cpp b/lib/App/common/targetPipeLine.cpp index 0bf0f697..58583fc8 100644 --- a/lib/App/common/targetPipeLine.cpp +++ b/lib/App/common/targetPipeLine.cpp @@ -122,7 +122,7 @@ bool targetPipeLine::inject( kernelEventFilter *instance, TARGET_DATA * tData ){ if ( (*idx) == instance ) { DownStreamFilter = true; } else { - if ( DownstreamFilter ) { + if ( DownStreamFilter ) { if ((*idx)->isActive()) { if ((*idx)->validateTarget(m_nNodeId, tData)){ propogateTarget = false; @@ -159,7 +159,6 @@ bool targetPipeLine::inject( kernelEventFilter *instance, TARGET_DATA * tData ){ #endif free(tData); }; -}; return false; } diff --git a/lib/App/common/targetPipeLine.h b/lib/App/common/targetPipeLine.h index 834c7d2e..c3fbaebf 100644 --- a/lib/App/common/targetPipeLine.h +++ b/lib/App/common/targetPipeLine.h @@ -37,8 +37,7 @@ class targetPipeLine : public basicThread explicit targetPipeLine(uint32_t node_id, uint32_t bind_cam_id = 0); virtual ~targetPipeLine(); bool push( TARGET_DATA * ptr ); - friend: - class kernelEventFilter; + friend class kernelEventFilter; }; #endif From a7c5e76e543c4a850c765a46e2a008f7d03a0f7d Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 13:11:30 +0000 Subject: [PATCH 06/10] Camera: re-create only the PTZ protocol on ONVIF trouble, keep the node and its stream A pOnvif problem could delete and re-create the whole camera node, which dropped the video stream bound to it, so recordings were cut although the video was fine. deviceNodeCamera::validate() compared the whole camera record with memcmp; any difference rebuilt the node: - CAM_WS_INIT sets m_sCamData.online = false before re-creating the PTZ protocol and writes the DB only afterwards. A validate() during a slow ONVIF re-init saw "online" differ and deleted the camera mid-re-init. - The ONVIF discovery (updateIPCam) wrote online=1 and the whole XAddrs list into onvif_ctrl (the web UI and la_mojo store only the path), so the record changed on discovery rounds. - A failed read (SQLite busy, queries fail at once) returned NULL = "camera deleted". Now: - Field classes (camDataChange): - runtime and discovery fields (online, status, session, max_range, uuid, mac): ignored; - name and hardware: taken over; - PTZ access (onvif_ctrl, onvif_access, port, auth_mode, ptz_token): the camera thread re-creates only the PTZ protocol, keeping the node and the stream; - anything else (ip and credentials used by the stream, stream_id, type, geometry, ...): rebuild as before, logged with the reason. - A lasting PTZ problem rebuilds the camera only after CAM_REBUILD_AFTER_FAILED_INITS (10) failed protocol initialisations in a row (several minutes with the retry back-off). - Node / camera record not read: rebuild only after NODE_DATA_MISSES_TO_REBUILD (3) validations in a row, for all nodes (deviceNode::validate). - updateIPCam: onvif_ctrl = path of the first XAddr. Host and port come from the first XAddr only: ':' was searched in the whole list, so a second, IPv6 XAddr gave a broken IP. A result without an address doesn't wipe the IP. Tested (functions extracted unchanged): camDataChange classifies online / status / max_range / uuid / mac as ignored, rename as cosmetic, port / onvif_ctrl / auth / ptz token as PTZ re-init, and ip / password / stream / geometry as rebuild. The XAddrs parser was checked with a port, without a port, with an IPv6 second XAddr, with a query, and with no address. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16 --- lib/App/common/SQLite_dataBinder.cpp | 75 ++++++++------ lib/App/common/deviceNode.cpp | 7 ++ lib/App/common/deviceNode.h | 7 ++ lib/App/common/deviceNodeCamera.cpp | 149 ++++++++++++++++++++++++++- lib/App/common/deviceNodeCamera.h | 13 +++ 5 files changed, 214 insertions(+), 37 deletions(-) diff --git a/lib/App/common/SQLite_dataBinder.cpp b/lib/App/common/SQLite_dataBinder.cpp index 5cd83b28..f65fec04 100644 --- a/lib/App/common/SQLite_dataBinder.cpp +++ b/lib/App/common/SQLite_dataBinder.cpp @@ -5779,56 +5779,63 @@ bool sqliteDBC::updateIPCam(uint32_t CamID, CSTR Addr) { if (m_bStoIsConnected) { + // onvif_ctrl = path of the device service only (as la_mojo's own discovery INSERT and the web UI + // store it; la_mojo builds http://ip[:port]onvif_ctrl). The whole XAddrs list was stored: the record + // changed on every discovery round and the camera node was rebuilt (its stream dropped). + char tPath[256] = "/onvif/device_service"; + { + const char * tH = strstr(Addr, "//"); + if (tH != NULL) + { + const char * tP = strchr(tH + 2, '/'); + if (tP != NULL) + { + size_t tLen = strcspn(tP, " \t\r\n"); // first XAddr only + if (tLen > 0 && tLen < sizeof(tPath) && memchr(tP, '\'', tLen) == NULL) + { + memcpy(tPath, tP, tLen); + tPath[tLen] = 0; + }; + }; + }; + } char tQBuf[MAX_PATH_LEN]; char tIpBuf[CTEXT]; - char * tPos; - char * tPos2; uint16_t tPort = 0; - tPos = strstr(Addr, "//"); - if (tPos != NULL) + // host[:port] of the FIRST XAddr only: the old parser searched ':' in the whole list (a second, IPv6 + // XAddr or a ':' in the path gave a broken IP / port) + tIpBuf[0] = (char) 0; { - tPos2 = strstr(tPos + 2, ":"); - if (tPos2 != NULL) + const char * tH = strstr(Addr, "//"); + if (tH != NULL) { - //LOG("IP Port Defined!"); - int len;//, len2, len3; - len = tPos2 - tPos - 2; - strncpy(tIpBuf, tPos + 2, len); - tIpBuf[len] = (char) 0; - tPort = atoi(tPos2 + 1); - // strncpy( tPath, tPos + 2 + len, CTEXT ); - } - else - { - tPos2 = strstr(tPos + 2, "/"); - if (tPos2 != NULL) - { - int len;//, len2, len3; - len = tPos2 - tPos - 2; - strncpy(tIpBuf, tPos + 2, len); - tIpBuf[len] = (char) 0; - // strncpy( tPath, tPos + 2 + len, CTEXT ); - } - else + tH += 2; + size_t tLen = strcspn(tH, "/ \t\r\n"); + if (tLen > 0 && tLen < sizeof(tIpBuf)) { - tPos2 = strstr(tPos + 2, "/"); - //LOG_ERROR("Pos 2 - err"); - tIpBuf[0] = (char) 0; + memcpy(tIpBuf, tH, tLen); + tIpBuf[tLen] = (char) 0; + char * tC = strrchr(tIpBuf, ':'); + if (tC != NULL && strchr(tIpBuf, ']') == NULL) // not [IPv6] + { + *tC = (char) 0; + tPort = (uint16_t) atoi(tC + 1); + }; }; }; } - else + if (tIpBuf[0] == (char) 0 || strchr(tIpBuf, '\'') != NULL) { - //LOG_ERROR("Pos 0 - err"); - tIpBuf[0] = (char) 0; + LOG_ERROR("updateIPCam: no address in the discovery result - camera not updated"); + return false; }; if (tPort) { - sprintf(tQBuf, "UPDATE `cameras` SET `online`=1, `onvif_ctrl`='%s', `ip`='%s', `port`=%d WHERE `id`=%d", Addr, tIpBuf, tPort, CamID); + snprintf(tQBuf, sizeof(tQBuf), "UPDATE `cameras` SET `online`=1, `onvif_ctrl`='%s', `ip`='%s', `port`=%d WHERE `id`=%d", tPath, tIpBuf, tPort, CamID); } else { - sprintf(tQBuf, "UPDATE `cameras` SET `online`=1, `onvif_ctrl`='%s', `ip`='%s' WHERE `id`=%d", Addr, tIpBuf, CamID); + snprintf(tQBuf, sizeof(tQBuf), "UPDATE `cameras` SET `online`=1, `onvif_ctrl`='%s', `ip`='%s' WHERE `id`=%d", tPath, tIpBuf, CamID); } #ifdef DEBUG_ALL LOG(tQBuf); diff --git a/lib/App/common/deviceNode.cpp b/lib/App/common/deviceNode.cpp index 15b69109..0beeb2dc 100644 --- a/lib/App/common/deviceNode.cpp +++ b/lib/App/common/deviceNode.cpp @@ -24,6 +24,7 @@ deviceNode::deviceNode(uint32_t id) : basicEngine() { m_pLog = basicLogCollection::getInstance(); + m_nNodeDataMisses = 0; #ifdef USE_MYSQL m_pDBC = mysqlDBC::getInstance(); #else @@ -58,6 +59,7 @@ deviceNode::deviceNode(DBC_NODE_DATA * Data) : basicEngine() { m_pLog = basicLogCollection::getInstance(); + m_nNodeDataMisses = 0; #ifdef USE_MYSQL m_pDBC = mysqlDBC::getInstance(); #else @@ -86,8 +88,13 @@ deviceNode::~deviceNode() bool deviceNode::validate() { DBC_NODE_DATA * tDATA = m_pDBC->getNodeData(m_sNodeData.node_id); + if (tDATA == NULL && ++m_nNodeDataMisses < NODE_DATA_MISSES_TO_REBUILD) + { + return true; // probably a failed read, not a deleted node: check again next time + }; if (tDATA) { + m_nNodeDataMisses = 0; // Configuration only: "online" is written by every node object of this id (setNodeOnline / // setNodeOffline) - deleting a second object of the same node made this one "changed" bool tChanged = (m_sNodeData.aux_id != tDATA->aux_id) || (m_sNodeData.aux_parameter != tDATA->aux_parameter) || (m_sNodeData.type != tDATA->type) || diff --git a/lib/App/common/deviceNode.h b/lib/App/common/deviceNode.h index fe56732d..80eab5ca 100644 --- a/lib/App/common/deviceNode.h +++ b/lib/App/common/deviceNode.h @@ -5,6 +5,12 @@ #include "../../components/base/basicEvent.h" #include "cmdNodeConveyor.h" +// The node record must be missing this many validations in a row before the node is deleted: a single failed +// read (SQLite busy - queries fail at once, no busy wait) deleted the node (a camera dropped its stream) +#ifndef NODE_DATA_MISSES_TO_REBUILD + #define NODE_DATA_MISSES_TO_REBUILD 3 +#endif + class deviceNode : public cmdNodeConveyor, public basicEngine { private: @@ -13,6 +19,7 @@ class deviceNode : public cmdNodeConveyor, public basicEngine basicLogCollection * m_pLog; dataBinder * m_pDBC; DBC_NODE_DATA m_sNodeData; + uint8_t m_nNodeDataMisses; // validate(): node record not read N times in a row public: diff --git a/lib/App/common/deviceNodeCamera.cpp b/lib/App/common/deviceNodeCamera.cpp index 8a72d09d..63466002 100644 --- a/lib/App/common/deviceNodeCamera.cpp +++ b/lib/App/common/deviceNodeCamera.cpp @@ -50,6 +50,9 @@ deviceNodeCamera::deviceNodeCamera(uint32_t NodeID) : m_sPtzHealth.state = PTZ_HEALTH_INIT; m_sPtzHealth.since = time(NULL); m_tPtzLastProbe = 0; + m_bPendingCamData = false; + m_bPendingProtoReinit = false; + memset(&m_sPendingCamData, 0, sizeof(m_sPendingCamData)); m_bNoAbsPositionning = false; m_bCameraOnHomePosition = false; m_bCameraAIControled = false; @@ -88,6 +91,9 @@ deviceNodeCamera::deviceNodeCamera(DBC_NODE_DATA * Data) : m_sPtzHealth.state = PTZ_HEALTH_INIT; m_sPtzHealth.since = time(NULL); m_tPtzLastProbe = 0; + m_bPendingCamData = false; + m_bPendingProtoReinit = false; + memset(&m_sPendingCamData, 0, sizeof(m_sPendingCamData)); m_bNoAbsPositionning = false; m_bCameraOnHomePosition = false; m_tTimeTSeconds = 0; @@ -1256,6 +1262,7 @@ void deviceNodeCamera::m_fThreadProc(void) if ((bNewSecondLoop = (cTimeSeconds != oTimeSeconds))) oTimeSeconds = cTimeSeconds; + applyPendingCamData(); // settings changed in the DB that need no rebuild (validate) uint8_t tState = getWM(); ptzCheck(tState); tState = getWM(); @@ -2880,6 +2887,113 @@ bool deviceNodeCamera::validateStream(void) return true; } +/* + Which camera fields changed (DB record a -> b)? + - runtime state written while running (online, status, session, max_range) and discovery data (uuid, mac): + ignored. Before, any difference rebuilt the node: CAM_WS_INIT set m_sCamData.online = false before + re-creating the PTZ protocol and wrote the DB only afterwards, so a validate() during a slow ONVIF + re-init deleted the camera (and dropped its video stream); so did the ONVIF discovery writing online=1. + - cosmetic (name, hardware): taken over, no action + - PTZ protocol only (onvif_ctrl, onvif_access, port, auth_mode, ptz_token): the protocol is re-created + - anything else (ip, credentials and stream_id used by the stream, type, geometry ...): node rebuilt +*/ +typedef enum E_CAM_DATA_CHANGE +{ + CAM_CHANGE_NONE = 0, + CAM_CHANGE_COSMETIC = 1, + CAM_CHANGE_PROTOCOL = 2, + CAM_CHANGE_NODE = 3 +} CAM_DATA_CHANGE; + +static CAM_DATA_CHANGE camDataChange(const DBC_CAM_DATA * a, const DBC_CAM_DATA * b, const char ** what) +{ + DBC_CAM_DATA tA, tB; + memcpy(&tA, a, sizeof(tA)); + memcpy(&tB, b, sizeof(tB)); + *what = ""; + // runtime / discovery fields: never a change + tA.online = tB.online; + tA.status = tB.status; + memcpy(tA.session, tB.session, sizeof(tA.session)); + tA.max_range = tB.max_range; + memcpy(tA.uuid, tB.uuid, sizeof(tA.uuid)); + memcpy(tA.mac, tB.mac, sizeof(tA.mac)); + // PTZ protocol fields + bool tProto = (tA.port != tB.port) || (tA.auth_mode != tB.auth_mode) || strncmp(tA.onvif_ctrl, tB.onvif_ctrl, sizeof(tA.onvif_ctrl)) != 0 || + strncmp(tA.onvif_access, tB.onvif_access, sizeof(tA.onvif_access)) != 0 || strncmp(tA.ptz_token, tB.ptz_token, sizeof(tA.ptz_token)) != 0; + tA.port = tB.port; + tA.auth_mode = tB.auth_mode; + memcpy(tA.onvif_ctrl, tB.onvif_ctrl, sizeof(tA.onvif_ctrl)); + memcpy(tA.onvif_access, tB.onvif_access, sizeof(tA.onvif_access)); + memcpy(tA.ptz_token, tB.ptz_token, sizeof(tA.ptz_token)); + // cosmetic fields + bool tCosm = strncmp(tA.name, tB.name, sizeof(tA.name)) != 0 || strncmp(tA.hardware, tB.hardware, sizeof(tA.hardware)) != 0; + memcpy(tA.name, tB.name, sizeof(tA.name)); + memcpy(tA.hardware, tB.hardware, sizeof(tA.hardware)); + // everything else (also fields added later) needs the node rebuilt + if (memcmp(&tA, &tB, sizeof(tA)) != 0) + { + if (strncmp(a->ip, b->ip, sizeof(a->ip)) != 0) + { + *what = "ip"; + } + else if (strncmp(a->username, b->username, sizeof(a->username)) != 0 || strncmp(a->password, b->password, sizeof(a->password)) != 0) + { + *what = "credentials"; + } + else if (a->stream_id != b->stream_id) + { + *what = "stream"; + } + else if (a->protocol != b->protocol) + { + *what = "control protocol"; + } + else + { + *what = "camera parameters"; + }; + return CAM_CHANGE_NODE; + }; + if (tProto) + { + *what = "PTZ access"; + return CAM_CHANGE_PROTOCOL; + }; + return tCosm ? CAM_CHANGE_COSMETIC : CAM_CHANGE_NONE; +} + +// Camera thread: take over the fields validate() found changed (only cosmetic / PTZ protocol fields) +void deviceNodeCamera::applyPendingCamData(void) +{ + if (! m_bPendingCamData) + { + return; + }; + m_mPendingCamData.lock(); + DBC_CAM_DATA * tN = &m_sPendingCamData; + memcpy(m_sCamData.name, tN->name, sizeof(m_sCamData.name)); + memcpy(m_sCamData.hardware, tN->hardware, sizeof(m_sCamData.hardware)); + m_sCamData.port = tN->port; + m_sCamData.auth_mode = tN->auth_mode; + memcpy(m_sCamData.onvif_ctrl, tN->onvif_ctrl, sizeof(m_sCamData.onvif_ctrl)); + memcpy(m_sCamData.onvif_access, tN->onvif_access, sizeof(m_sCamData.onvif_access)); + memcpy(m_sCamData.ptz_token, tN->ptz_token, sizeof(m_sCamData.ptz_token)); + bool tReinit = m_bPendingProtoReinit; + m_bPendingCamData = false; + m_bPendingProtoReinit = false; + m_mPendingCamData.unlock(); + if (tReinit && m_sCamData.protocol != 0) + { + LOG("PTZ access settings changed - re-initialising the PTZ protocol (camera and stream kept)"); + m_mPtzHealth.lock(); + m_sPtzHealth.next_retry = 0; // new settings: no back-off + m_sPtzHealth.failed_inits = 0; + m_mPtzHealth.unlock(); + setWM(CAM_WS_INIT); + }; +} + bool deviceNodeCamera::validate() { if (m_pDBC == NULL) @@ -2889,16 +3003,45 @@ bool deviceNodeCamera::validate() DBC_CAM_DATA * tDATA = m_pDBC->getCamData(m_sCamData.id); if (tDATA == NULL) { + // Probably a failed read (SQLite busy), not a deleted camera: rebuild only when it stays missing + if (++m_nNodeDataMisses < NODE_DATA_MISSES_TO_REBUILD) + { + return true; + }; + LOG_ERROR("Camera record not found - rebuilding the camera"); return false; } - if (memcmp(tDATA, &m_sCamData, sizeof(DBC_CAM_DATA)) != 0) + const char * tWhat = ""; + CAM_DATA_CHANGE tChange = camDataChange(&m_sCamData, tDATA, &tWhat); + if (tChange == CAM_CHANGE_NODE) { - // Settings Changed - // memcpy(&m_sCamData, tDATA, sizeof(DBC_CAM_DATA) ); + char tB[128]; + snprintf(tB, sizeof(tB), "Camera settings changed (%s) - rebuilding the camera", tWhat); + LOG(tB); free(tDATA); return false; }; + if (tChange != CAM_CHANGE_NONE) + { + m_mPendingCamData.lock(); + memcpy(&m_sPendingCamData, tDATA, sizeof(DBC_CAM_DATA)); + m_bPendingProtoReinit = m_bPendingProtoReinit || (tChange == CAM_CHANGE_PROTOCOL); + m_bPendingCamData = true; + m_mPendingCamData.unlock(); + }; free(tDATA); + // Only a real, lasting PTZ problem rebuilds the camera (and drops its stream) + m_mPtzHealth.lock(); + bool tGiveUp = (m_sPtzHealth.state == PTZ_HEALTH_FAILED) && (m_sPtzHealth.failed_inits >= CAM_REBUILD_AFTER_FAILED_INITS); + uint32_t tFails = m_sPtzHealth.failed_inits + 1; + m_mPtzHealth.unlock(); + if (tGiveUp) + { + char tB[128]; + snprintf(tB, sizeof(tB), "PTZ protocol failed %u initialisations in a row - rebuilding the camera", tFails); + LOG_ERROR(tB); + return false; + }; if (! validateStream()) { return false; diff --git a/lib/App/common/deviceNodeCamera.h b/lib/App/common/deviceNodeCamera.h index 256d0370..e2d48191 100644 --- a/lib/App/common/deviceNodeCamera.h +++ b/lib/App/common/deviceNodeCamera.h @@ -130,6 +130,11 @@ typedef struct S_PTZ_HEALTH_INFO #define CAM_PTZ_PROBE_INTERVAL_S 30 // idle liveness check of the PTZ protocol (protocolPTZ::probe) #define CAM_PTZ_RETRY_MIN_S 5 // first re-initialisation delay after a failure #define CAM_PTZ_RETRY_MAX_S 60 // delay doubles per failed attempt up to this +// The camera node (and the video stream bound to it) is rebuilt only after this many failed PTZ protocol +// initialisations in a row (with the retry back-off: several minutes); a PTZ problem re-creates the protocol only +#ifndef CAM_REBUILD_AFTER_FAILED_INITS + #define CAM_REBUILD_AFTER_FAILED_INITS 10 +#endif typedef struct S_CAM_TASK { @@ -207,6 +212,14 @@ class deviceNodeCamera : public deviceNode, public basicThread void ptzCheck(uint8_t tState); void ptzLost(const char * reason); void ptzCommandFailed(const char * command); + + // Camera settings changed in the DB (validate, node factory thread) that need only a PTZ protocol + // re-initialisation or no action: applied by the camera thread (it owns m_sCamData) + basicMutex m_mPendingCamData; + DBC_CAM_DATA m_sPendingCamData; + volatile bool m_bPendingCamData; + volatile bool m_bPendingProtoReinit; + void applyPendingCamData(void); // basicTransport * m_pTransport; CAM_TASK_QUEUE m_qCAM_TASK; From ab477ca497dda0730842755fa6a8619af6d2249f Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 14:07:12 +0000 Subject: [PATCH 07/10] Video stream: restart only after a lasting stall, not after one 5 s gap Field log: the PTZ re-init now keeps the camera and its stream (15:36), but at 16:02:30 "Video Stalled" restarted the live555 stream, which cut the recording. streamHandler::validate() (module factory, every ~5 s) restarted the stream as soon as one validation saw no new frame, i.e. after a single gap of ~5 s. That is normal now and then for a camera on a mobile link. - The stream is restarted after STREAM_STALL_CHECKS (3) validations in a row without a new frame (~15 s): "Video Stalled (no frame for N s) - restarting the stream". Shorter gaps are logged ("Video: no new frame for N s (k/3)", "Video: frames again after N s"). - m_nValidatorFrameCounter is initialised (it was not). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16 --- lib/App/common/streamHandler.cpp | 28 +++++++++++++++++++++++++--- lib/App/common/streamHandler.h | 8 ++++++++ 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/lib/App/common/streamHandler.cpp b/lib/App/common/streamHandler.cpp index 701bc23d..6239e6fe 100644 --- a/lib/App/common/streamHandler.cpp +++ b/lib/App/common/streamHandler.cpp @@ -69,6 +69,9 @@ streamHandler::streamHandler(kernelModuleEmbedVideo * ptr, MS_WORK_MODE M, uint8 memset(&m_sStreamData, 0, sizeof(DBC_MEDIA_STREAM_DATA)); m_pSource = NULL; + m_nValidatorFrameCounter = 0; + m_nStallChecks = 0; + m_tLastFrameProgress = time(NULL); m_bEvtMarkerCounter = 0; m_bCamMoveCounter = 0; m_bFlipMode = flip_mode; @@ -3751,12 +3754,31 @@ bool streamHandler::validate(void) { // Frames Received from a source if (m_nGlobalFrameCounter == m_nValidatorFrameCounter) { - // Video Stalled! - LOG_ERROR("Video Stalled"); - return false; // Try use System to recuperate + // No new frame since the last validation: restart only when it lasts (STREAM_STALL_CHECKS) + char tB[128]; + long tSec = (long) (time(NULL) - m_tLastFrameProgress); + if (++m_nStallChecks < STREAM_STALL_CHECKS) + { + snprintf(tB, sizeof(tB), "Video: no new frame for %ld s (%u/%u)", tSec, (unsigned) m_nStallChecks, (unsigned) STREAM_STALL_CHECKS); + LOG(tB); + } + else + { + snprintf(tB, sizeof(tB), "Video Stalled (no frame for %ld s) - restarting the stream", tSec); + LOG_ERROR(tB); + return false; // Try use System to recuperate + }; } else { + if (m_nStallChecks) + { + char tB[96]; + snprintf(tB, sizeof(tB), "Video: frames again after %ld s", (long) (time(NULL) - m_tLastFrameProgress)); + LOG(tB); + }; + m_nStallChecks = 0; + m_tLastFrameProgress = time(NULL); m_nValidatorFrameCounter = m_nGlobalFrameCounter; } }; diff --git a/lib/App/common/streamHandler.h b/lib/App/common/streamHandler.h index c1f732b0..7e114b87 100644 --- a/lib/App/common/streamHandler.h +++ b/lib/App/common/streamHandler.h @@ -27,6 +27,12 @@ //Predefine Classess class kernelModuleEmbedVideo; +// A stream is restarted only after this many validations in a row (module factory: every ~5 s) without a +// new frame. One gap of ~5 s (a camera on a mobile link) restarted the stream and cut the recording. +#ifndef STREAM_STALL_CHECKS + #define STREAM_STALL_CHECKS 3 +#endif + class streamHandler; #define FILESTREAMBUFFERSZ 1048576 @@ -241,6 +247,8 @@ class streamHandler : basicMutex m_mFrameCounterProtector; uint64_t m_nGlobalFrameCounter; uint64_t m_nValidatorFrameCounter; + uint8_t m_nStallChecks; // validate() calls in a row without a new frame + time_t m_tLastFrameProgress; // last validate() that saw new frames #ifndef EVE_SEQUENTAL_OUTPUT uint32_t m_nSegAFrameCounter; uint32_t m_nSegBFrameCounter; From 87a11e66797e6799dd043d931055e9c60dbfa7b7 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 14:32:20 +0000 Subject: [PATCH 08/10] Camera PTZ recovery: no full re-initialisation; a major problem rebuilds the node Field log: after a PTZ liveness failure the protocol was re-created (camera and stream kept), but the camera then ran its whole start-up sequence again (power mode, WB, BLC, AF, home) in the middle of the work. - A successful re-creation of a protocol that worked before in this node (a recovery) goes straight to CAM_WS_READY: "PTZ protocol re-created - camera settings kept, back to ready". The first initialisation of the node still runs the full sequence. - CAM_REBUILD_AFTER_FAILED_INITS 10 -> 3: three failed re-creations in a row (back-off 0, 5, 10 s) are a major problem (camera power supply, network). The node is rebuilt and the new node fully initialises the camera: "PTZ protocol re-creation failed 3 times in a row (camera power / network?) - rebuilding the camera". - Only for a camera whose protocol worked in this node (m_bPtzEverOk): one that never worked (e.g. switched off) keeps retrying with the back-off instead of being rebuilt every few seconds. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16 --- lib/App/common/deviceNodeCamera.cpp | 29 +++++++++++++++++++++++------ lib/App/common/deviceNodeCamera.h | 13 ++++++++++--- 2 files changed, 33 insertions(+), 9 deletions(-) diff --git a/lib/App/common/deviceNodeCamera.cpp b/lib/App/common/deviceNodeCamera.cpp index 63466002..5e2a2103 100644 --- a/lib/App/common/deviceNodeCamera.cpp +++ b/lib/App/common/deviceNodeCamera.cpp @@ -52,6 +52,7 @@ deviceNodeCamera::deviceNodeCamera(uint32_t NodeID) : m_tPtzLastProbe = 0; m_bPendingCamData = false; m_bPendingProtoReinit = false; + m_bPtzEverOk = false; memset(&m_sPendingCamData, 0, sizeof(m_sPendingCamData)); m_bNoAbsPositionning = false; m_bCameraOnHomePosition = false; @@ -93,6 +94,7 @@ deviceNodeCamera::deviceNodeCamera(DBC_NODE_DATA * Data) : m_tPtzLastProbe = 0; m_bPendingCamData = false; m_bPendingProtoReinit = false; + m_bPtzEverOk = false; memset(&m_sPendingCamData, 0, sizeof(m_sPendingCamData)); m_bNoAbsPositionning = false; m_bCameraOnHomePosition = false; @@ -1532,7 +1534,20 @@ void deviceNodeCamera::m_fThreadProc(void) LOG_ERROR("No Kernel Instance!"); }; m_sCamData.online = true; - setWM(CAM_WS_POWER_INIT); + m_mPtzHealth.lock(); + bool tRecovery = m_bPtzEverOk && (m_sPtzHealth.state == PTZ_HEALTH_FAILED); + m_mPtzHealth.unlock(); + if (tRecovery) + { + // The camera kept its settings: only the connection was lost - no full initialisation + // (power mode, WB, BLC, AF, home) in the middle of the work + LOG("PTZ protocol re-created - camera settings kept, back to ready"); + setWM(CAM_WS_READY); + } + else + { + setWM(CAM_WS_POWER_INIT); + }; }; m_pDBC->updateCamOnlineStatus(m_sCamData.id, m_sCamData.online); if (m_sCamData.protocol == 0) @@ -1543,6 +1558,7 @@ void deviceNodeCamera::m_fThreadProc(void) { m_tPtzLastProbe = time(NULL); ptzHealthSet(PTZ_HEALTH_OK); + m_bPtzEverOk = true; } else { @@ -3030,15 +3046,16 @@ bool deviceNodeCamera::validate() m_mPendingCamData.unlock(); }; free(tDATA); - // Only a real, lasting PTZ problem rebuilds the camera (and drops its stream) + // A major PTZ problem (the protocol worked, then CAM_REBUILD_AFTER_FAILED_INITS re-creations failed in a + // row: power supply / network) rebuilds the camera - the new node fully initialises it m_mPtzHealth.lock(); - bool tGiveUp = (m_sPtzHealth.state == PTZ_HEALTH_FAILED) && (m_sPtzHealth.failed_inits >= CAM_REBUILD_AFTER_FAILED_INITS); - uint32_t tFails = m_sPtzHealth.failed_inits + 1; + bool tGiveUp = m_bPtzEverOk && (m_sPtzHealth.state == PTZ_HEALTH_FAILED) && (m_sPtzHealth.failed_inits >= CAM_REBUILD_AFTER_FAILED_INITS); + uint32_t tFails = m_sPtzHealth.failed_inits; m_mPtzHealth.unlock(); if (tGiveUp) { - char tB[128]; - snprintf(tB, sizeof(tB), "PTZ protocol failed %u initialisations in a row - rebuilding the camera", tFails); + char tB[160]; + snprintf(tB, sizeof(tB), "PTZ protocol re-creation failed %u times in a row (camera power / network?) - rebuilding the camera", tFails); LOG_ERROR(tB); return false; }; diff --git a/lib/App/common/deviceNodeCamera.h b/lib/App/common/deviceNodeCamera.h index e2d48191..5a0d7860 100644 --- a/lib/App/common/deviceNodeCamera.h +++ b/lib/App/common/deviceNodeCamera.h @@ -130,10 +130,16 @@ typedef struct S_PTZ_HEALTH_INFO #define CAM_PTZ_PROBE_INTERVAL_S 30 // idle liveness check of the PTZ protocol (protocolPTZ::probe) #define CAM_PTZ_RETRY_MIN_S 5 // first re-initialisation delay after a failure #define CAM_PTZ_RETRY_MAX_S 60 // delay doubles per failed attempt up to this -// The camera node (and the video stream bound to it) is rebuilt only after this many failed PTZ protocol -// initialisations in a row (with the retry back-off: several minutes); a PTZ problem re-creates the protocol only +/* + PTZ trouble: + - the protocol is re-created; when it works again within a few attempts the camera goes straight back to + CAM_WS_READY (no power mode / WB / BLC / AF / home again: its settings are unchanged) + - CAM_REBUILD_AFTER_FAILED_INITS failed re-creations in a row (with the back-off 0, 5, 10 s ...) are a major + problem (camera power supply, network): the node is rebuilt and the new node fully initialises the camera. + Only for a camera whose protocol worked in this node - one that never worked keeps retrying (back-off). +*/ #ifndef CAM_REBUILD_AFTER_FAILED_INITS - #define CAM_REBUILD_AFTER_FAILED_INITS 10 + #define CAM_REBUILD_AFTER_FAILED_INITS 3 #endif typedef struct S_CAM_TASK @@ -219,6 +225,7 @@ class deviceNodeCamera : public deviceNode, public basicThread DBC_CAM_DATA m_sPendingCamData; volatile bool m_bPendingCamData; volatile bool m_bPendingProtoReinit; + volatile bool m_bPtzEverOk; // the PTZ protocol worked in this node (re-creation = recovery) void applyPendingCamData(void); // basicTransport * m_pTransport; From 21674ad9caf4e5247a6b3855a3fbc9c92a7817a6 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 14:58:56 +0000 Subject: [PATCH 09/10] ONVIF PTZ debug: log AbsoluteMove coordinates and the camera's position limits - Every AbsoluteMove is logged with pan/tilt/zoom and speed (DEBUG_PONVIF_PTZ in ponvif.h). - A rejected AbsoluteMove is always logged with the coordinates and the fault, followed by the camera ranges. - The node's absolute position spaces (GetNode) and the profile's PTZConfiguration limits and default position spaces (GetProfiles) are read and logged after the protocol is created. - A move outside the known limits is flagged (PAN/TILT/ZOOM) before it is sent; the request is still sent unchanged. - deviceNodeCamera logs the ROI position and the zoom correction before goAbsolute. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16 --- lib/App/common/deviceNodeCamera.cpp | 7 + lib/data/ponvif/ponvif.cpp | 185 +++++++++++++++++++++++- lib/data/ponvif/ponvif.h | 36 +++++ lib/data/protocol/protocolPTZ_ONVIF.cpp | 2 + 4 files changed, 228 insertions(+), 2 deletions(-) diff --git a/lib/App/common/deviceNodeCamera.cpp b/lib/App/common/deviceNodeCamera.cpp index 5e2a2103..bf6c4bb4 100644 --- a/lib/App/common/deviceNodeCamera.cpp +++ b/lib/App/common/deviceNodeCamera.cpp @@ -1929,6 +1929,13 @@ void deviceNodeCamera::m_fThreadProc(void) m_fCP_Tilt = m_pCurrentROI->cam_orientation.tilt; m_fCP_Zoom = m_pCurrentROI->cam_orientation.zoom; // Do Movement + { + char tB[CTEXT * 2]; + snprintf(tB, sizeof(tB), "Go to ROI (%u targets): pan=%0.6f tilt=%0.6f zoom=%0.6f (x zoom correction %0.4f = %0.6f)", (unsigned) m_pCurrentROI->targets.size(), + m_pCurrentROI->cam_orientation.pan, m_pCurrentROI->cam_orientation.tilt, m_pCurrentROI->cam_orientation.zoom, m_fZoomCorrection, + m_pCurrentROI->cam_orientation.zoom * m_fZoomCorrection); + LOG(tB); + } if (! m_pProtocol->goAbsolute(m_pCurrentROI->cam_orientation.pan, m_pCurrentROI->cam_orientation.tilt, m_pCurrentROI->cam_orientation.zoom * m_fZoomCorrection)) { ptzCommandFailed("goAbsolute"); diff --git a/lib/data/ponvif/ponvif.cpp b/lib/data/ponvif/ponvif.cpp index 4c842cb5..ed6b3e91 100644 --- a/lib/data/ponvif/ponvif.cpp +++ b/lib/data/ponvif/ponvif.cpp @@ -1647,6 +1647,8 @@ bool pOnvif::media_GetVideoSources(void) return false; } +static bool readPtzRange(XMLNode & node, ptzRange * out); + bool pOnvif::media_GetProfiles(void) { char tBuffer[DEFAULT_BUFFER_SIZE]; @@ -1737,6 +1739,16 @@ bool pOnvif::media_GetProfiles(void) { tPtr->ptz = true; safeCopy(tPtr->ptznodetoken, sizeof(tPtr->ptznodetoken), nNode.getChildNode("NodeToken", 0).getText(0)); + safeCopy(tPtr->ptzdefaultptspace, sizeof(tPtr->ptzdefaultptspace), nNode.getChildNode("DefaultAbsolutePantTiltPositionSpace", 0).getText(0)); + safeCopy(tPtr->ptzdefaultzoomspace, sizeof(tPtr->ptzdefaultzoomspace), nNode.getChildNode("DefaultAbsoluteZoomPositionSpace", 0).getText(0)); + { + XMLNode tL = nNode.getChildNode("PanTiltLimits", 0).getChildNode("Range", 0); + readPtzRange(tL, &tPtr->ptzpantiltlimits); + } + { + XMLNode tL = nNode.getChildNode("ZoomLimits", 0).getChildNode("Range", 0); + readPtzRange(tL, &tPtr->ptzzoomlimits); + } }; } m_vVideoProfiles.push_back(tPtr); @@ -2059,6 +2071,95 @@ void pOnvif::setGenericSpeedSpaces(void) safeCopy(m_sPanTiltSpeedSpace.uri, sizeof(m_sPanTiltSpeedSpace.uri), PONVIF_SPACE_PT_GENERIC_SPEED); safeCopy(m_sZoomSpeedSpace.uri, sizeof(m_sZoomSpeedSpace.uri), PONVIF_SPACE_ZOOM_GENERIC_SPEED); m_sPanTiltSpeedSpace.max = m_sZoomSpeedSpace.max = 1.0f; + memset(&m_sPanTiltPosSpace, 0, sizeof(m_sPanTiltPosSpace)); + memset(&m_sZoomPosSpace, 0, sizeof(m_sZoomPosSpace)); +} + +/* + Reads a <...> element with , and optional (a node's position space + or the Range of a PTZConfiguration's PanTiltLimits / ZoomLimits). +*/ +static bool readPtzRange(XMLNode & node, ptzRange * out) +{ + memset(out, 0, sizeof(ptzRange)); + if (node.isEmpty()) + { + return false; + }; + LPCTSTR tUri = node.getChildNode("URI", 0).getText(0); + if (tUri != NULL) + { + safeCopy(out->uri, sizeof(out->uri), tUri); + }; + XMLNode tX = node.getChildNode("XRange", 0); + LPCTSTR tXMin = tX.getChildNode("Min", 0).getText(0); + LPCTSTR tXMax = tX.getChildNode("Max", 0).getText(0); + if (tXMin == NULL || tXMax == NULL) + { + return false; + }; + out->xmin = (float) atof(tXMin); + out->xmax = (float) atof(tXMax); + XMLNode tY = node.getChildNode("YRange", 0); + LPCTSTR tYMin = tY.getChildNode("Min", 0).getText(0); + LPCTSTR tYMax = tY.getChildNode("Max", 0).getText(0); + if (tYMin != NULL && tYMax != NULL) + { + out->ymin = (float) atof(tYMin); + out->ymax = (float) atof(tYMax); + out->hasY = true; + }; + out->valid = true; + return true; +} + +// The position space of the node: the generic one if offered, otherwise the first one +static void pickPositionSpace(XMLNode & spaces, LPCTSTR name, LPCTSTR genericUri, ptzRange * out) +{ + memset(out, 0, sizeof(ptzRange)); + for (int i = 0;; i++) + { + XMLNode tSpace = spaces.getChildNode(name, i); + if (tSpace.isEmpty()) + { + break; + }; + ptzRange tR; + if (! readPtzRange(tSpace, &tR)) + { + continue; + }; + if (! out->valid || strcmp(tR.uri, genericUri) == 0) + { + *out = tR; + }; + if (strcmp(tR.uri, genericUri) == 0) + { + break; + }; + }; +} + +static void ptzRangeText(char * buf, size_t size, const ptzRange & r) +{ + if (! r.valid) + { + snprintf(buf, size, "n/a"); + } + else if (r.hasY) + { + snprintf(buf, size, "x [%.4f .. %.4f] y [%.4f .. %.4f] (%.100s)", r.xmin, r.xmax, r.ymin, r.ymax, r.uri); + } + else + { + snprintf(buf, size, "[%.4f .. %.4f] (%.100s)", r.xmin, r.xmax, r.uri); + }; +} + +// Small tolerance: values read back from the device are printed with limited precision +static bool ptzInRange(float v, float vmin, float vmax) +{ + return (v >= vmin - 0.0001f) && (v <= vmax + 0.0001f); } /* @@ -2139,6 +2240,8 @@ bool pOnvif::ptz_GetNode(CSTR ptzNodeToken) }; bool tPT = pickSpeedSpace(tSpaces, "PanTiltSpeedSpace", PONVIF_SPACE_PT_GENERIC_SPEED, &m_sPanTiltSpeedSpace); bool tZM = pickSpeedSpace(tSpaces, "ZoomSpeedSpace", PONVIF_SPACE_ZOOM_GENERIC_SPEED, &m_sZoomSpeedSpace); + pickPositionSpace(tSpaces, "AbsolutePanTiltPositionSpace", PONVIF_SPACE_PT_GENERIC_POS, &m_sPanTiltPosSpace); + pickPositionSpace(tSpaces, "AbsoluteZoomPositionSpace", PONVIF_SPACE_ZOOM_GENERIC_POS, &m_sZoomPosSpace); return tPT || tZM; } @@ -2208,11 +2311,89 @@ bool pOnvif::ptz_AbsoluteMove(CSTR profileToken, float position_pantilt_x, float // The generic pan/tilt speed is a scalar (x); y is sent with the same value for devices reading it. float tPT = (speed < 0.0f) ? m_sPanTiltSpeedSpace.max : m_sPanTiltSpeedSpace.min + speed * (m_sPanTiltSpeedSpace.max - m_sPanTiltSpeedSpace.min); float tZM = (speed < 0.0f) ? m_sZoomSpeedSpace.max : m_sZoomSpeedSpace.min + speed * (m_sZoomSpeedSpace.max - m_sZoomSpeedSpace.min); - char tBuffer[DEFAULT_BUFFER_SIZE]; + // Limits that apply to this move: the profile's PTZConfiguration limits, else the node's position spaces + const videoSourceProfile * tProfile = NULL; + for (size_t i = 0; i < m_vVideoProfiles.size(); i++) + { + if (m_vVideoProfiles[i] != NULL && strcmp(m_vVideoProfiles[i]->profiletoken, profileToken) == 0) + { + tProfile = m_vVideoProfiles[i]; + break; + }; + }; + const ptzRange & tPTR = (tProfile != NULL && tProfile->ptzpantiltlimits.valid) ? tProfile->ptzpantiltlimits : m_sPanTiltPosSpace; + const ptzRange & tZR = (tProfile != NULL && tProfile->ptzzoomlimits.valid) ? tProfile->ptzzoomlimits : m_sZoomPosSpace; + char tOut[64]; + tOut[0] = (char) 0; + int tLen = 0; + if (tPTR.valid && ! ptzInRange(position_pantilt_x, tPTR.xmin, tPTR.xmax)) + { + tLen += snprintf(tOut + tLen, sizeof(tOut) - tLen, " PAN"); + }; + if (tPTR.valid && tPTR.hasY && ! ptzInRange(position_pantilt_y, tPTR.ymin, tPTR.ymax) && tLen < (int) sizeof(tOut)) + { + tLen += snprintf(tOut + tLen, sizeof(tOut) - tLen, " TILT"); + }; + if (tZR.valid && ! ptzInRange(zoom, tZR.xmin, tZR.xmax) && tLen < (int) sizeof(tOut)) + { + tLen += snprintf(tOut + tLen, sizeof(tOut) - tLen, " ZOOM"); + }; + char tMove[CTEXT * 2]; + snprintf(tMove, sizeof(tMove), "AbsoluteMove pan=%0.6f tilt=%0.6f zoom=%0.6f (speed pt=%0.4f zoom=%0.4f)", position_pantilt_x, position_pantilt_y, zoom, tPT, tZM); + if (tOut[0] != 0) + { + char tB[CTEXT * 4]; + snprintf(tB, sizeof(tB), "%s: OUT OF CAMERA LIMITS:%s", tMove, tOut); + LOG_ERROR(tB); + } +#ifdef DEBUG_PONVIF_PTZ + else + { + LOG(tMove); + }; +#endif + char tBuffer[DEFAULT_BUFFER_SIZE]; _buildRequest(tBuffer, sizeof(tBuffer), PONVIF_BODY_ABSOLUTE_MOVE, xesc(profileToken).c_str(), position_pantilt_x, position_pantilt_y, zoom, tPT, tPT, xesc(m_sPanTiltSpeedSpace.uri).c_str(), tZM, xesc(m_sZoomSpeedSpace.uri).c_str()); // Wait for the answer so that a SOAP Fault (e.g. position out of range) is detected - return _send_request(m_pPTZURI, tBuffer, true); + bool tOk = _send_request(m_pPTZURI, tBuffer, true); + if (! tOk) + { + char tB[CTEXT * 4]; + snprintf(tB, sizeof(tB), "%s REJECTED (%s)", tMove, (m_cLastFault[0] != 0) ? m_cLastFault : "no answer"); + LOG_ERROR(tB); + if (m_eLastError == PONVIF_ERR_FAULT) + { + ptz_LogRanges(profileToken); + }; + }; + return tOk; +} + +void pOnvif::ptz_LogRanges(CSTR profileToken) +{ + char tR1[CTEXT * 2]; + char tR2[CTEXT * 2]; + char tB[CTEXT * 6]; + ptzRangeText(tR1, sizeof(tR1), m_sPanTiltPosSpace); + ptzRangeText(tR2, sizeof(tR2), m_sZoomPosSpace); + snprintf(tB, sizeof(tB), "PTZ node position space: PanTilt %s, Zoom %s", tR1, tR2); + LOG(tB); + for (size_t i = 0; i < m_vVideoProfiles.size(); i++) + { + const videoSourceProfile * tP = m_vVideoProfiles[i]; + if (tP == NULL || ! tP->ptz || (profileToken != NULL && strcmp(tP->profiletoken, profileToken) != 0)) + { + continue; + }; + ptzRangeText(tR1, sizeof(tR1), tP->ptzpantiltlimits); + ptzRangeText(tR2, sizeof(tR2), tP->ptzzoomlimits); + snprintf(tB, sizeof(tB), "PTZ profile %.60s limits: PanTilt %s, Zoom %s", tP->profiletoken, tR1, tR2); + LOG(tB); + snprintf(tB, sizeof(tB), "PTZ profile %.60s default spaces: PanTilt %.120s, Zoom %.120s (the PanTilt position is sent without a space)", tP->profiletoken, + tP->ptzdefaultptspace[0] ? tP->ptzdefaultptspace : "n/a", tP->ptzdefaultzoomspace[0] ? tP->ptzdefaultzoomspace : "n/a"); + LOG(tB); + }; } bool pOnvif::ptz_ContinuousMove(CSTR profileToken, float velocity_pantilt_x, float velocity_pantilt_y) diff --git a/lib/data/ponvif/ponvif.h b/lib/data/ponvif/ponvif.h index 13444944..e64da897 100644 --- a/lib/data/ponvif/ponvif.h +++ b/lib/data/ponvif/ponvif.h @@ -80,6 +80,10 @@ // the PTZConfiguration's DefaultPTZSpeed): there "1" can be a slow speed. #define PONVIF_SPACE_PT_GENERIC_SPEED "http://www.onvif.org/ver10/tptz/PanTiltSpaces/GenericSpeedSpace" #define PONVIF_SPACE_ZOOM_GENERIC_SPEED "http://www.onvif.org/ver10/tptz/ZoomSpaces/ZoomGenericSpeedSpace" +#define PONVIF_SPACE_PT_GENERIC_POS "http://www.onvif.org/ver10/tptz/PanTiltSpaces/PositionGenericSpace" +#define PONVIF_SPACE_ZOOM_GENERIC_POS "http://www.onvif.org/ver10/tptz/ZoomSpaces/PositionGenericSpace" +// Log every AbsoluteMove with its coordinates (a rejected move is always logged with them) +#define DEBUG_PONVIF_PTZ // ContinuousMove is assembled from these parts (pan/tilt and zoom in one request) #define PONVIF_BODY_CONTINUOUS_MOVE_BEGIN "%s" #define PONVIF_BODY_CONTINUOUS_MOVE_PT \ @@ -107,6 +111,18 @@ #define PONVIF_PCK_GET_CAPABILITIES (CSTR) "All" +// A position range of the PTZ node or a PTZConfiguration limit (URI + X range, Y range for pan/tilt) +typedef struct S_ptzRange +{ + char uri[CTEXT]; + float xmin; + float xmax; + float ymin; + float ymax; + bool hasY; + bool valid; // read from the device +} ptzRange; + typedef struct S_videoSourceProfile { char sourcetoken[CTEXT]; @@ -119,6 +135,12 @@ typedef struct S_videoSourceProfile int bitrate; bool ptz; // profile has a PTZConfiguration (PTZ commands need such a profile) char ptznodetoken[CTEXT]; // PTZConfiguration/NodeToken + // PTZConfiguration: default absolute position spaces (used when a Position has no space attribute) + // and the configured limits (a move outside them is answered with ter:InvalidPosition) + char ptzdefaultptspace[CTEXT]; + char ptzdefaultzoomspace[CTEXT]; + ptzRange ptzpantiltlimits; + ptzRange ptzzoomlimits; } videoSourceProfile; // A speed space of the PTZ node (GetNode -> SupportedPTZSpaces/PanTiltSpeedSpace | ZoomSpeedSpace) @@ -561,6 +583,8 @@ class pOnvif char m_cLastFault[CTEXT]; ptzSpeedSpace m_sPanTiltSpeedSpace; // speed space used for AbsoluteMove (generic 0..1 by default) ptzSpeedSpace m_sZoomSpeedSpace; + ptzRange m_sPanTiltPosSpace; // node: absolute pan/tilt position space (generic one if offered) + ptzRange m_sZoomPosSpace; // node: absolute zoom position space #ifndef CURL_MANAGER static int _writer(char * data, size_t size, size_t nmemb, pOnvif * Ptr); #endif @@ -634,6 +658,18 @@ class pOnvif { return m_sZoomSpeedSpace; } + + const ptzRange & getPanTiltPositionSpace(void) const + { + return m_sPanTiltPosSpace; + } + + const ptzRange & getZoomPositionSpace(void) const + { + return m_sZoomPosSpace; + } + // Logs the position spaces of the node and the limits of the profile (debug of out-of-bounds moves) + void ptz_LogRanges(CSTR profileToken); bool ptz_GetStatus(CSTR profileToken, ptzStatus * tStatus); // PTZ service capabilities (ONVIF PTZ GetServiceCapabilities). // Each output is 1 = supported, 0 = not supported, -1 = not reported by the device. diff --git a/lib/data/protocol/protocolPTZ_ONVIF.cpp b/lib/data/protocol/protocolPTZ_ONVIF.cpp index 6e9e1b67..824bd3b3 100644 --- a/lib/data/protocol/protocolPTZ_ONVIF.cpp +++ b/lib/data/protocol/protocolPTZ_ONVIF.cpp @@ -226,6 +226,8 @@ bool protocolPTZ_ONVIF::create(void) snprintf(tB, sizeof(tB), "PTZ speed (%s): PanTilt %.120s max %.3f, Zoom %.120s max %.3f", tRead ? "from node" : "generic default", tPT.uri, tPT.max, tZM.uri, tZM.max); LOG(tB); } + // Camera ranges, to compare with the coordinates of the AbsoluteMove requests + m_pOnVif->ptz_LogRanges(m_pProfile->profiletoken); LOG("DONE"); m_bStatus = 1; return true; From 5dc051623a07986a31b4fea74c904c6e19f986ae Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 15:06:45 +0000 Subject: [PATCH 10/10] ONVIF absolute move: keep the position inside the camera limits The ROI orientation was not limited: a target accepted up to half a field of view outside the mechanical range (or any elevation with a 90 deg tilt camera) gave e.g. tilt=1.344, which the camera rejects with ter:InvalidPosition. - spherical2onvif: endless pan wraps the azimuth into 0..360; pan/tilt are clamped to -1..1 and zoom to 0..1 (the camera goes to its end position). - pOnvif::ptz_AbsoluteMove clamps to the profile limits / node position space as a last safety (covers operator absolute moves too) and logs it. - The "Go to ROI" log also shows the target's fi/tetta/r and the pan/tilt models. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16 --- lib/App/common/deviceNodeCamera.cpp | 12 ++++++++---- lib/alg/generic/Transform.cpp | 17 +++++++++++++++++ lib/data/ponvif/ponvif.cpp | 28 +++++++++++++++++++--------- 3 files changed, 44 insertions(+), 13 deletions(-) diff --git a/lib/App/common/deviceNodeCamera.cpp b/lib/App/common/deviceNodeCamera.cpp index bf6c4bb4..028792af 100644 --- a/lib/App/common/deviceNodeCamera.cpp +++ b/lib/App/common/deviceNodeCamera.cpp @@ -1930,10 +1930,14 @@ void deviceNodeCamera::m_fThreadProc(void) m_fCP_Zoom = m_pCurrentROI->cam_orientation.zoom; // Do Movement { - char tB[CTEXT * 2]; - snprintf(tB, sizeof(tB), "Go to ROI (%u targets): pan=%0.6f tilt=%0.6f zoom=%0.6f (x zoom correction %0.4f = %0.6f)", (unsigned) m_pCurrentROI->targets.size(), - m_pCurrentROI->cam_orientation.pan, m_pCurrentROI->cam_orientation.tilt, m_pCurrentROI->cam_orientation.zoom, m_fZoomCorrection, - m_pCurrentROI->cam_orientation.zoom * m_fZoomCorrection); + char tB[CTEXT * 3]; + snprintf(tB, sizeof(tB), + "Go to ROI (%u targets): pan=%0.6f tilt=%0.6f zoom=%0.6f (x zoom correction %0.4f = %0.6f); target fi=%0.2f tetta=%0.2f r=%0.1f; " + "camera pan model %u / %u deg, tilt model %u / %u deg", + (unsigned) m_pCurrentROI->targets.size(), m_pCurrentROI->cam_orientation.pan, m_pCurrentROI->cam_orientation.tilt, + m_pCurrentROI->cam_orientation.zoom, m_fZoomCorrection, m_pCurrentROI->cam_orientation.zoom * m_fZoomCorrection, + m_pCurrentROI->cam_position.fi, m_pCurrentROI->cam_position.tetta, m_pCurrentROI->cam_position.r, (unsigned) m_sCamData.pan_model, + (unsigned) m_sCamData.pan_angles, (unsigned) m_sCamData.tilt_model, (unsigned) m_sCamData.tilt_angles); LOG(tB); } if (! m_pProtocol->goAbsolute(m_pCurrentROI->cam_orientation.pan, m_pCurrentROI->cam_orientation.tilt, m_pCurrentROI->cam_orientation.zoom * m_fZoomCorrection)) diff --git a/lib/alg/generic/Transform.cpp b/lib/alg/generic/Transform.cpp index 233de3b6..16398754 100644 --- a/lib/alg/generic/Transform.cpp +++ b/lib/alg/generic/Transform.cpp @@ -141,6 +141,16 @@ void spherical2onvif(C3D_SPH_DEGREES in, C3D_ORIENT_ONVIF & out, float maxR, uin out.zoom = .0f; } + // Endless pan: the azimuth may come as -180..180 or above 360, bring it into 0..360 + if (panAngles >= 360.0f) + { + in.fi = fmodf(in.fi, 360.0f); + if (in.fi < 0.0f) + { + in.fi += 360.0f; + }; + }; + switch (panMode) { case 1: @@ -174,6 +184,13 @@ void spherical2onvif(C3D_SPH_DEGREES in, C3D_ORIENT_ONVIF & out, float maxR, uin break; }; }; + // A target is accepted up to half a field of view outside the mechanical range (isInRange), and a camera + // that can tilt 90 degrees accepts any elevation: the camera must then go to its end position, where the + // target is still in the picture. A value outside -1..1 (generic ONVIF space) is rejected by the camera + // with ter:InvalidPosition ("The requested destination is out of bounds"). + out.pan = (out.pan < -1.0f) ? -1.0f : ((out.pan > 1.0f) ? 1.0f : out.pan); + out.tilt = (out.tilt < -1.0f) ? -1.0f : ((out.tilt > 1.0f) ? 1.0f : out.tilt); + out.zoom = (out.zoom < 0.0f) ? 0.0f : ((out.zoom > 1.0f) ? 1.0f : out.zoom); } void spherical2onvif(C3D_SPH_RADIANS inr, C3D_ORIENT_ONVIF & out, float maxR, uint8_t panMode, float panAngles, uint8_t tiltMode, float tiltAngles) diff --git a/lib/data/ponvif/ponvif.cpp b/lib/data/ponvif/ponvif.cpp index ed6b3e91..6dca68e1 100644 --- a/lib/data/ponvif/ponvif.cpp +++ b/lib/data/ponvif/ponvif.cpp @@ -2338,19 +2338,29 @@ bool pOnvif::ptz_AbsoluteMove(CSTR profileToken, float position_pantilt_x, float { tLen += snprintf(tOut + tLen, sizeof(tOut) - tLen, " ZOOM"); }; - char tMove[CTEXT * 2]; - snprintf(tMove, sizeof(tMove), "AbsoluteMove pan=%0.6f tilt=%0.6f zoom=%0.6f (speed pt=%0.4f zoom=%0.4f)", position_pantilt_x, position_pantilt_y, zoom, tPT, tZM); if (tOut[0] != 0) { - char tB[CTEXT * 4]; - snprintf(tB, sizeof(tB), "%s: OUT OF CAMERA LIMITS:%s", tMove, tOut); + char tB[CTEXT * 2]; + snprintf(tB, sizeof(tB), "AbsoluteMove pan=%0.6f tilt=%0.6f zoom=%0.6f: OUT OF CAMERA LIMITS:%s - clamped to the limits", position_pantilt_x, position_pantilt_y, + zoom, tOut); LOG_ERROR(tB); - } -#ifdef DEBUG_PONVIF_PTZ - else - { - LOG(tMove); + if (tPTR.valid) + { + position_pantilt_x = (position_pantilt_x < tPTR.xmin) ? tPTR.xmin : ((position_pantilt_x > tPTR.xmax) ? tPTR.xmax : position_pantilt_x); + if (tPTR.hasY) + { + position_pantilt_y = (position_pantilt_y < tPTR.ymin) ? tPTR.ymin : ((position_pantilt_y > tPTR.ymax) ? tPTR.ymax : position_pantilt_y); + }; + }; + if (tZR.valid) + { + zoom = (zoom < tZR.xmin) ? tZR.xmin : ((zoom > tZR.xmax) ? tZR.xmax : zoom); + }; }; + char tMove[CTEXT * 2]; + snprintf(tMove, sizeof(tMove), "AbsoluteMove pan=%0.6f tilt=%0.6f zoom=%0.6f (speed pt=%0.4f zoom=%0.4f)", position_pantilt_x, position_pantilt_y, zoom, tPT, tZM); +#ifdef DEBUG_PONVIF_PTZ + LOG(tMove); #endif char tBuffer[DEFAULT_BUFFER_SIZE]; _buildRequest(tBuffer, sizeof(tBuffer), PONVIF_BODY_ABSOLUTE_MOVE, xesc(profileToken).c_str(), position_pantilt_x, position_pantilt_y, zoom, tPT, tPT,