The field test is done: replies avg 113-205 ms, spikes up to 1.5 s, one
slow reply covered by the retry, 0 failed commands. The #define in
deviceNodeEthernet2Serial.cpp and deviceNodeSensor.cpp is commented out;
uncomment it to get the timing lines again. The reconnect error ("No
reply to N requests in a row") is always logged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
The sensor answers only when queried, and it re-sends its query after
every attempt without reply (idle mode: getState2() in stage 1 again).
The gateway must deliver each of these queries:
- Queued requests are no longer dropped by closePort(). A query queued
while the I/O thread ended for a reconnect is sent on the new
connection (the previous commit dropped it, so the sensor stayed
unqueried for that attempt).
- sendData() queues while the connection is up, while the I/O thread is
still starting (TH_ARMED: the first query right after a connect was
refused with "Trying to Send Data Before Thread is Started!"), while
the thread has ended and the reconnect is pending, and while
create_SOL() is connecting. It refuses only without any connection.
- At most E2UART_MAX_QUEUED (16) requests wait; the oldest are dropped.
A failed reconnect clears the queue, because those queries are stale.
- The "NO reply" debug line shows the request bytes (first 12), so a
repeated query can be recognised in the log.
Tested with a fake device that goes silent after 3 replies: the query
sent while the thread was starting and the query queued during the
reconnect were both answered, and nothing was refused (ASan clean).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
Field log (sensor behind 2.54.237.28:8234): normal replies avg 129 ms,
spikes up to 2.6 s handled. Then no reply at all to 19 requests in a
row while the TCP connection stayed "up" (sending never failed). The
sensor failed after 17 attempts and kept using the dead connection. A
dead mobile/NAT path isn't reported by the kernel for many minutes, and
keepalive only probes idle connections.
- TCP_USER_TIMEOUT 10 s (E2UART_TCP_USER_TIMEOUT_MS): sent data not
acknowledged by the gateway drops the connection.
- After 5 requests in a row (E2UART_NO_REPLY_RECONNECT) without a single
reply byte, the I/O thread ends ("No reply to 5 requests in a row -
reconnecting to the gateway"). validate() sees the lost link and opens
a new connection. Late data resets the count.
- closePort() frees the requests still queued for the closed connection.
- "NO reply" log lines (DEBUG_COMMUNICATION) and the reconnect error show
TCP_INFO: unacked data, retransmits, rtt, last ACK / last data received.
Unacked data and an old last ACK mean the network path is dead; ACKs
that keep coming mean the gateway/device side doesn't answer.
Tested with a fake device that goes silent after 3 replies while keeping
the TCP connection open: the reconnect came after the 5th unanswered
request, and requests 9-12 were answered on the new connection (ASan clean).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
DEBUG_COMMUNICATION is turned on in deviceNodeEthernet2Serial.cpp and
deviceNodeSensor.cpp only. It isn't defined project-wide, which would also
enable the per-byte hex dumps of protocol.cpp and the serial transports.
To turn it off, comment out the #define at the top of the two files.
Gateway I/O thread (tag E2UART):
- "IO: request #n (x B): NO reply in N ms": nothing within the reply
window (E2UART_REPLY_TIMEOUT_MS).
- "IO: request #n: reply x B, first byte N ms, done N ms": replies
slower than 500 ms (E2UART_SLOW_REPLY_MS), or an incomplete packet.
- "IO: late data x B, N ms after request #n": a reply that came after
the window (now given to the parser of that request).
- "IO stats 60 s [host:port]": requests, replies, first-byte avg/max, slow,
without reply, late.
Sensor (tag NODSEN):
- "COMM: reply/NACK WM STG reply N ms": replies slower than 500 ms
(LGS_SLOW_REPLY_MS), NACKs and commands that needed retries, with
the time since the first attempt.
- "COMM: no reply - WM STG attempt k/17 timed out after N ms": each
attempt that timed out.
- "COMM: command failed - ...": details next to "Communication Wait State
TO!".
- "COMM stats 60 s": replies, avg/max reply time, slow, timed-out attempts
(with the wait per attempt), failed commands.
The gateway's per-chunk "Send/Read x bytes" debug lines are replaced by
these per-request lines.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
A 2D sensor waited 10 x 100 ms (LGS_DEFAULT_TO_COUNTER) for each reply,
which is a local serial-line value. Through an Ethernet to serial gateway
on a mobile link the round trip is longer at times.
- basicTransport::isNetworkLink() (false by default). deviceETH2UART
returns true.
- deviceNodeSensor::m_nTOCounterBase is the wait per attempt.
device2DSensor sets it when it binds to its port:
LGS_NETWORK_TO_COUNTER (30 = 3 s) for a network link,
LGS_DEFAULT_TO_COUNTER (1 s) for a local serial port, which is unchanged.
All 2D waits use it, including the longer x4 / x16 waits of the
detection profile and mask commands. waitStateFunction() re-arms the
retry with it.
- E2UART_REPLY_TIMEOUT_MS 800 -> 2500 ms, below the sensor's 3 s, so the
gateway's I/O thread waits for the reply before sending the next request.
Tested with the fake device: replies after 300 ms (split), 1200 ms and
2000 ms (split) all reach their own request within the 3 s wait (ASan clean).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
"NODSEN: Communication Wait State TO!" with a sensor behind the gateway:
in SERIAL_PING_PONG mode the I/O thread waited only 20 x 5 ms (~100 ms,
a serial-line value) for the reply to a request, and did not read the
socket while no request was queued. A reply slower than that, which is
normal over a mobile link, stayed in the socket. It was read with the next
request and given to that request's parser, so the sensor ran one reply
behind, retried, and after 16 failed attempts reported the timeout.
deviceETH2UART I/O thread (SERIAL_PING_PONG)
- Waits up to E2UART_REPLY_TIMEOUT_MS (800 ms, below the sensor's 1 s per
attempt) for the reply to start, and E2UART_REPLY_GAP_MS (150 ms)
between the pieces of a reply split over several TCP segments. It is
done as soon as the parser has a complete packet and no more data is
waiting (as before).
- Reads the socket also between requests. Late data goes to the parser
of the last request at once.
- Gives data only to a parser that is still bound to the transport (a
sensor that disconnected or was deleted is no longer called).
Serial resource casts (deviceNode2D, deviceNodeCamera)
- dynamic_cast<basicTransport*> instead of static_cast through
hardwareResourceSerialProvider. The resource can be a deviceETH2UART,
and the old cast was only right because of a matching base-class layout.
A NULL transport isn't bound.
Tested with a fake device answering after 50/300/700 ms, also split into
two TCP pieces. The old code delivered nothing, or the previous
request's answer. Now each request gets its own answer (ASan clean).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
From the la_mojo log of a gateway reached over the Internet (2.54.237.28:8234):
deviceETH2UART
- In TCP mode, link health is the TCP connection itself (socket, I/O
thread, SO_ERROR, TCP keepalive). ICMP isn't used there: gateways on
mobile networks often don't answer ping, and the working connection was
closed every second ("No Ping to device!").
- Ping (UDP modes) up to 3 echoes x 2000 ms, at most every 10 s. Only an
echo reply from the gateway with our id and sequence counts. A signal
(EINTR) no longer ends the wait. The old single recvfrom() with
SO_RCVTIMEO returned EINTR at the first signal, even with SA_RESTART.
- TCP connect timeout 1 s -> 5 s (E2UART_CONNECT_TIMEOUT_MS), and EINTR in
select() continues waiting.
- create_SOL() closes the previous socket and I/O thread first. It
overwrote the socket (the connection leaked) and init() failed while
the old thread ran, so each reconnect left an open TCP connection at the
gateway and the node stayed invalid although "Connected". If init()
fails, the new socket is closed.
- create()/validate()/reconnect() are serialised: they run on the node
factory thread and on the hardware manager thread.
- Registered with the hardware manager once. Re-creation from the
hardware manager locked its non-recursive list mutex again (deadlock).
- Reconnect back-off 2 s -> 30 s.
- recv() == 0 on TCP means the gateway closed the connection (a stale
errno was checked before).
- Destructor resigns from the hardware manager before closing.
deviceNodeFactory
- deleteNode() deletes the gateway object. It was only removed from the
list and kept running next to the new node created for the same id.
- Nodes are deleted after the validation loop (erasing inside it skipped
the next node).
deviceNode::validate
- Compares the configuration only. "online" changes whenever another
object of the same node id is created or deleted.
hardwareManager::assignResource
- Ignores a resource that is already assigned.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
A handler was registered in the basicEventHandler constructor (before
the derived members existed) and removed in its destructor (after they
were destroyed): the event heap could call dispatchEvent() on a half-
built or half-destroyed node or module when one was created or deleted
while la_mojo runs (node / module reload).
- Camera nodes (deviceNodePTZCamControl, deviceNodePresetCamControl,
deviceNodeStaticCamControl): basicEventHandler(false), attachEvents()
at the end of both constructors, detachEvents() first thing in the
destructor.
- Kernel modules: kernelModule no longer registers in its constructor;
kernelModuleFactory attaches a module right after creating it (all
modules are created there), before startService(). Every module
destructor (USB relay, Kafka, FlyHunter, SSDP, ONVIF observer, embed
video (both variants), modem manager, Bosch, attention cloud, report
backupper) calls detachEvents() first.
- basicEventHeap::moveHandlerTop/Bottom no longer register a handler
that is not registered (would have registered an object twice once
attachEvents() runs).
Sensor nodes are not event handlers and are unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
Why the shutdown could hang: the event heap was never stopped, and its
thread called every handler's dispatchEvent() while holding the handler
list mutex. ~mojoKernel deletes the node / module factories, filters,
media helper ... - all of them event handlers - while the heap kept
calling into them (half-destroyed objects, destroyed mutexes); the
deleting thread then waited forever in removeHandler() for the mutex
the dispatch thread held. A dispatchEvent() that created or deleted a
handler deadlocked the dispatch thread itself (non-recursive mutex).
basicEventHeap:
- Handlers are called without the list locked (snapshot + "still
registered" check per handler); removeHandler() waits until the
handler is no longer being called (5 s cap, logged), except when
called from that very dispatchEvent().
- New pause() / resume() / flush() / clearQueue() and
destroyInstance() (stops the thread; leaves it alone if a handler is
stuck instead of hanging); existingInstance(); getInstance() is
thread-safe.
basicEventHandler:
- detachEvents(): stop delivery first thing in a destructor (the base
destructor runs only after the derived members are gone);
basicEventHandler(false) + attachEvents(): register at the end of the
constructor (registration in the base constructor lets the heap call
into an object whose members are not built yet). Defaults unchanged.
- Removal never creates a new heap (late destructors after exit).
la_mojo:
- ~mojoKernel: deliver queued events (2 s), pause the heap before
deleting the components, drop what was queued during the teardown;
the next kernel (restart) resumes it.
- mojoBackend: destroyInstance() before the log is deleted at exit.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
- kernelEventFilterYOLO.h:
* Darknet V3+ (hank-ai) declares load_network(), load_network_custom()
and free_network_ptr() only when DARKNET_INCLUDE_ORIGINAL_API is
defined before darknet.h ("was not declared in this scope"): define it.
* Darknet installs the header as <prefix>/include/darknet.h, not
darknet/darknet.h: include <darknet.h>, fall back to
<darknet/darknet.h>, clear #error if neither exists.
* m_pNET was DarknetNetworkPtr * (void **) although DarknetNetworkPtr is
already void *: "invalid conversion from void* to void**".
- makefile / la_mojo.vpj: -ldarknet was only linked in Release86; the
build script uses Debug86. Added to Debug86 and Debug (the .vpj too,
so a SlickEdit regeneration keeps it).
- kernelEventFilterYOLO::initFilter(): load the settings first
(validate()); m_sYOLOFilterData was still zero, so fileExist("") made
initFilter() always fail. Logs why it fails, frees a previously loaded
network, logs the network dimensions. Destructor stops the thread
before freeing the network.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
- kernelEventFilterYOLO declared m_fThreadProc() but never defined it:
the link failed with "undefined reference to vtable for
kernelEventFilterYOLO". Added a placeholder worker loop (same style
as the Bubble filter) until the YOLO processing is implemented.
- m_sYOLOFilterData is zero-initialised (validate() memcmp's it).
- Silenced the new unused-parameter warnings: validateTarget /
dispatchEvent stubs and dataBinder::getYOLOFilterData (the latter
warned in every file that includes dataBinder.h).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
Leaks that grew without bound:
- Dead module connections were never removed (half-open TCP after a
module power loss / network drop): every one kept 3 threads, 8 MB of
socket buffers, a descriptor and a 10 ms DB poll. servaRPCHadnler now
drops a connection that sends nothing for RPC_IDLE_TIMEOUT_S (60 s;
la_mojo sends a status about every second), and accepted sockets get
TCP keepalive (30 s idle, 3 probes of 10 s).
- The client socket was only closed on an I/O error: a handler removed
for any other reason (module disabled / not registered, idle) leaked
its descriptor until accept() failed with EMFILE - which ended the
accept thread for good. ~serverPort now shuts down and closes it;
transient accept() errors (EMFILE, ENFILE, ENOMEM, ECONNABORTED,
EINTR, ...) no longer stop the server. recv() == 0 (peer closed) is
always a disconnect, whatever errno holds.
- servaSessionManager::reopenSession stored the reopened (expired)
session in the per-track map, overwriting the track's ACTIVE session:
its data and open report.db leaked and it was never closed in MySQL.
Reopened sessions are now kept outside the map and released by the
caller (addVideo, getSessionBase).
- servaVideoComposer leaked its session data, an open SQLite connection
and both video queues on every composition; servaKernel leaked a
composer whose compose() failed, never initialised / released the
automatic composer (it ran at most once) and leaked the media info
of every encoded video (processVideoFile success path).
Crashes / corruption:
- vector erase() with the old iterator reused (netServer client
cleanup, encoder / composer pools, 4 ModBus action loops).
- transportSocket::_close wrote the stop byte into the read end of the
pipe (threads only stopped at the 5 s select timeout, blocking the
accept thread on every disconnect) and left closed pipe numbers set
(a second _close could write into another connection's socket).
- Session map used without the lock from RPC, kernel and ModBus
threads: now a recursive mutex held for each public operation.
- Freeze on the first MySQL error with DB logging enabled: Query() logs
while holding the non-recursive DB mutex and the log service wrote
synchronously into the DB (same-thread and two-thread deadlock).
The DB log service now queues lines (max 1000) and writes them with
MySQL_Connector::TrySilentQuery (never blocks, never logs); reconnect
retries per query are bounded (3) instead of looping forever while
holding the mutex. The log line parser also skips the UTC offset.
- basicMutex::try_lock returned true when the lock was NOT taken: an
uncontended try_lock took the mutex and the caller never released it
(basicEngine, serial transport, ...).
- Kernel restart (web commands): the ModBus singleton was deleted but
not reset (next getInstance returned freed memory), the remote client
kept the deleted kernel and refused to start again, and
EXIT_CODE_RELOAD_SERVICES deleted the DB object every surviving
component still used. Now fixed / the DB object is kept.
- Life monitoring overflowed module_id[4] for platforms with > 4
modules; registerServA overflowed a 120-byte stack buffer, closed a
popen() stream with fclose and leaked the config; 9 config strings in
servaBackend were allocated one byte short; video chunk length is now
checked against the packet; "eased" events copied every field from
itself (all 0); networkServer freed libconfig's host string.
Minor: ModBus action list / sessions freed at shutdown, session-start
event payload freed if the event cannot be created, the per-second
"No History Auto Delete!" log line moved to DEBUG_EXTRA.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
PTZ health per camera (deviceNodeCamera):
- PTZ_HEALTH_INFO: state (NONE / INIT / OK / FAILED), failure and
recovery counters, consecutive failed initialisations, time of the
last state change / failure, next retry and the last error text.
getPtzHealth() returns a copy (mutex-protected, any thread).
- getPtzStatus() - already sent to the remote server as
CAMERA_STATUS_PTZ_OK - now reflects it: 1 for OK (or no PTZ protocol),
0 while PTZ is initialising or failed. Before it was 1 as soon as the
state machine left CAM_WS_INIT, whatever the protocol did.
Failure detection and re-initialisation:
- While idle (CAM_WS_READY) the camera checks the protocol's validate()
every loop and calls the new protocolPTZ::probe() every 30 s
(ONVIF: GetStatus; a SOAP Fault still means "reachable", only a
communication error marks the camera lost). Default probe() is the
protocol's validate(), so serial protocols are unchanged.
- On failure the PTZ protocol is recreated through CAM_WS_INIT: first
attempt at once, then 5, 10, 20, 40, 60 s (capped) between attempts;
recoveries are logged and counted.
- A failed target-driven goAbsolute/goPreset no longer ends the camera
thread (CAM_WS_END rebuilt the whole node): for ONVIF a command the
camera rejected (connection OK) only drops that ROI, anything else
re-initialises the PTZ protocol.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
Target-driven moves of deviceNodePTZCamControl (AbsoluteMove) and
deviceNodePresetCamControl (preset for the ROI) both end in
CAM_WS_WAIT_ONPOS, which waits for the end of the move and then
broadcasts EVT_CAMERA_ON_POSITION (EVT_CLASS_CAMERA_CTRL).
- AbsoluteMove: with video output enabled (m_bSkeepPositioningWait) the
event was broadcast right after the command, before the camera moved.
It now always goes through CAM_WS_WAIT_ONPOS, like the preset path.
- New m_bNoMoveDoneReport: set when the protocol cannot report the end
of a move (waitMoveIsDone() returns false). Then a fixed
CAM_MOVE_FIXED_WAIT_MS (3 s) wait is used before the event. Before, the
same failure set m_bSkeepPositioningWait, which made every later
AbsoluteMove broadcast the event immediately. Reset when the protocol
is (re)created.
- protocolPTZ_ONVIF::goPreset: forget the last AbsoluteMove target so
waitMoveIsDone() cannot end early by comparing with it.
Homing, init go-home and web/IR/wiper presets are unchanged (no event).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
The report engine now keeps a separate SQLite database for every local
hour inside the day folder:
data/reports/YYYY/MM/DD/report_HH.db (REPORT_DB_NAME_FMT "report_%02d.db")
Pictures and videos stay in the day folder; the stat.db day records are
unchanged.
- sqliteDBC::openHourReport(): opens/creates report_HH.db of the given day
and hour (replaces openDayReport); switchReportToCurrentHour() (renamed
from switchReportToCurrentDay) switches when the local day or hour
changes. connect() opens the current hour's file at startup.
- mojoKernel::handleReportPeriodChange() (was handleDayChange): runs the
same close-then-switch sequence every local hour: an open session that
started in the previous hour is closed in the old file (waiting at most
REPORT_SWITCH_MAX_VIDEO_WAIT for a recording with events), then the
report switches to the new hour; the next event opens a new session.
Each hourly file therefore contains complete sessions.
- getLocalHour() helper in basicFunctionality.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
Before, the report (data/reports/YYYY/MM/DD/report.db, plus pictures and
videos stored next to it) only moved to a new day inside
updateStats(SESSION_START) - and that branch never ran, because
updateStats() skipped every call with evt=false/video=false, which is how
all session status changes are reported. So the report only changed day
when the process restarted; everything after midnight went into the
previous day's report.
- mojoKernel::handleDayChange() (every second from validateReports):
at local midnight an open session that started on the previous day is
closed (END event goes into the old report). If a video segment with
events is still recording, wait for it at most DAY_CHANGE_MAX_VIDEO_WAIT
(90 s) so the video is stored next to its events. After the END event is
written, the report is switched to the new day. The next event starts a
new session in the new day's report.
- sqliteDBC::switchReportToCurrentDay() / openDayReport(): opens (creates)
the current local day's report directory and database, retried until it
succeeds. Report state is protected by a recursive mutex because the
switch runs on the kernel thread while events are written on the event
thread.
- updateStats(): no longer drops SESSION_START/END/DROP calls, so the
session counters in stat.db are updated and SESSION_START also switches
the report if needed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
Continuous leaks:
- protocolParser: on package-pool overflow the oldest package was removed
but never freed while the newest (still pooled) one was freed. Every
packet a handler does not consume (e.g. other sensors on a shared bus)
leaked once the pool was full. Free the removed package, free pooled
packages in the destructor and getPackage(), use memmove for the
overlapping buffer shifts.
- SQLite_Connector::Query: loop only while sqlite3_step() returns
SQLITE_ROW. Looping until SQLITE_DONE spun forever allocating rows on
SQLITE_BUSY/ERROR. Set a busy timeout, close handles after a failed
open, fix escapeBinary() writing into uninitialised buffers.
- basicThread/basicDualThread: threads that ended by themselves were never
joined, leaking their stacks on every stream drop/restart. Always join
once (detach when called from the thread itself); check pthread_create
result correctly.
- curlRequest: free the header list; initialise m_pPostData and the
content type; curlRequestsManager deletes requests it cannot queue.
- kernelModuleModemManager: free the phonebook ID list on every reload.
- deviceNodeFactory: do not append the same pending node every cycle.
- streamHandler: free frames left in the encoding queue on destruction.
Heap corruption:
- kernelModuleFactory: module that failed to start was deleted twice.
- mojoRemoteClient: basicRing::push() returns an ID (may be 0), not a
bool; compare with -1. Fix packetExtractor and destructor leaks.
- utilizeBasicEvent: payloads are malloc'ed, release with free().
- videoAVLIBSource: avoid sws context double free, NULL check order.
- trim(): memmove for overlapping copy.
Smaller leaks: dropSession duplicate query, LRF upload data, report
backupper / fly hunter settings, Kafka consumer handle, BVMS uniq ID.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16