From 09f1480805698b446a7f1138d97139da311a144e Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 22:25:47 +0000 Subject: [PATCH 1/7] Ethernet2UART gateway: fix the reconnect loop, leaked connections and ping check 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 Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16 --- lib/App/common/deviceNode.cpp | 7 +- lib/App/common/deviceNodeEthernet2Serial.cpp | 343 +++++++++++++------ lib/App/common/deviceNodeEthernet2Serial.h | 35 ++ lib/App/common/deviceNodeFactory.cpp | 15 +- lib/App/common/hardwareManager.cpp | 13 +- 5 files changed, 310 insertions(+), 103 deletions(-) diff --git a/lib/App/common/deviceNode.cpp b/lib/App/common/deviceNode.cpp index 8e4c4879..15b69109 100644 --- a/lib/App/common/deviceNode.cpp +++ b/lib/App/common/deviceNode.cpp @@ -88,7 +88,12 @@ bool deviceNode::validate() DBC_NODE_DATA * tDATA = m_pDBC->getNodeData(m_sNodeData.node_id); if (tDATA) { - if (memcmp(&m_sNodeData, tDATA, sizeof(DBC_NODE_DATA)) != 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) || + (m_sNodeData.enabled != tDATA->enabled) || (m_sNodeData.tss != tDATA->tss) || (m_sNodeData.tsm != tDATA->tsm) || + (strncmp(m_sNodeData.name, tDATA->name, sizeof(m_sNodeData.name)) != 0); + if (tChanged) { free(tDATA); LOG("Node Settings Changed!"); diff --git a/lib/App/common/deviceNodeEthernet2Serial.cpp b/lib/App/common/deviceNodeEthernet2Serial.cpp index f9719a21..b7e612fc 100644 --- a/lib/App/common/deviceNodeEthernet2Serial.cpp +++ b/lib/App/common/deviceNodeEthernet2Serial.cpp @@ -3,6 +3,11 @@ #include "../../data/protocol/protocol.h" #include "hardwareManager.h" +#include +#include +#include +#include + // #define DEBUG_EXTRA // #define DEBUG_SERIAL_COMMUNICATION @@ -40,22 +45,45 @@ deviceETH2UART::deviceETH2UART(uint32_t nodeID) : m_iMasterFD = -1; m_iInFID = -1; m_iOutFID = -1; + m_bRegistered = false; + m_bLastPingOk = true; + m_nNextPingMs = 0; + m_nNextConnectMs = 0; + m_nConnectBackoffMs = 0; hardwareResource::create(m_sNodeData.aux_parameter, HARDWARE_PROVIDER_SERIAL); } +// Status of the I/O thread (sender thread in the dual-thread variant) +#ifdef SERIAL_PING_PONG + #define E2U_IO_STATUS m_bThreadStatus +#else + #define E2U_IO_STATUS m_bThreadAStatus +#endif + +static uint64_t e2uNowMs(void) +{ + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return (uint64_t) ts.tv_sec * 1000 + ts.tv_nsec / 1000000; +} + deviceETH2UART::~deviceETH2UART() { - closePort(); + // Leave the hardware manager first: its validate() loop holds the resource list locked while it + // calls validate() / create() on us, so once this returns it no longer uses this object hardwareManager * tH = hardwareManager::getInstance(); if (tH) { tH->resignResource(this); } + std::lock_guard tLock(m_mConnLock); + closePort(); } bool deviceETH2UART::create(void) { - DBC_UART_DATA * tDATA = NULL; + std::lock_guard tLock(m_mConnLock); + DBC_UART_DATA * tDATA = NULL; if (m_sResourceSettings.id == 0) { return false; @@ -73,28 +101,95 @@ bool deviceETH2UART::create(void) LOG(m_sUartData.path); #endif free(tDATA); - m_bValid = create_SOL(); + // Also called by the hardware manager to re-create the resource: obeys the back-off + m_bValid = connectSOL(); }; - if (m_bValid) + if (m_bValid && ! m_bRegistered) { + // Once only: the hardware manager calls create() again with its resource list locked - + // assigning from there locked the (non recursive) list mutex twice and added us twice hardwareManager * tH = hardwareManager::getInstance(); if (tH) { tH->assignResource(this); + m_bRegistered = true; } }; return m_bValid; } +/* + Is the link to the gateway still up? + - TCP (SOL_TCP_SERVER: we are the client): the TCP connection itself (socket, I/O thread and + keepalive). ICMP is not used: gateways reached over the Internet (mobile networks, firewalls) + often do not answer ping although the TCP port works - the working connection was closed every + second ("No Ping to device!"). + - UDP: no connection state, ICMP echo (at most every E2UART_PING_INTERVAL_MS). +*/ +bool deviceETH2UART::linkAlive(void) +{ + if (m_sUartData.mode == SOL_TCP_SERVER) + { + if (m_iDeviceFD < 0 || m_eConnectionStatus != CS_CONNECTED || E2U_IO_STATUS == TH_PRE_INIT || E2U_IO_STATUS >= TH_ENDED) + { + LOG_ERROR("TCP connection to the gateway lost"); + return false; + }; + int tErr = 0; + socklen_t tLen = sizeof(tErr); + if (getsockopt(m_iDeviceFD, SOL_SOCKET, SO_ERROR, &tErr, &tLen) == 0 && tErr != 0) + { + char tB[160]; + snprintf(tB, sizeof(tB), "TCP connection to the gateway failed: %s", strerror(tErr)); + LOG_ERROR(tB); + return false; + }; + return true; + }; + uint64_t tNow = e2uNowMs(); + if (tNow < m_nNextPingMs) + { + return m_bLastPingOk; + }; + m_bLastPingOk = pingDevice(); + m_nNextPingMs = e2uNowMs() + E2UART_PING_INTERVAL_MS; + return m_bLastPingOk; +} + +bool deviceETH2UART::connectSOL(void) +{ + uint64_t tNow = e2uNowMs(); + if (tNow < m_nNextConnectMs) + { + return false; // waiting for the next attempt (a gateway that is down is not hammered) + }; + if (create_SOL()) + { + m_nConnectBackoffMs = 0; + m_nNextConnectMs = 0; + m_nNextPingMs = 0; + m_bLastPingOk = true; + return true; + }; + m_nConnectBackoffMs = (m_nConnectBackoffMs == 0) ? E2UART_RECONNECT_MIN_MS : m_nConnectBackoffMs * 2; + if (m_nConnectBackoffMs > E2UART_RECONNECT_MAX_MS) + { + m_nConnectBackoffMs = E2UART_RECONNECT_MAX_MS; + }; + m_nNextConnectMs = e2uNowMs() + m_nConnectBackoffMs; + return false; +} + bool deviceETH2UART::validate(void) { + std::lock_guard tLock(m_mConnLock); if (m_bValid) { - m_bValid = pingDevice(); + m_bValid = linkAlive(); if (! m_bValid) { - LOG_ERROR("No Ping to device!"); + LOG_ERROR("No connection to the device!"); closePort(); }; }; @@ -123,16 +218,14 @@ bool deviceETH2UART::validate(void) #ifdef DEBUG LOG("Settings Has been Changed!"); #endif - if (m_bValid) - { - closePort(); // if port not closed - } + closePort(); // create_SOL() closes too; also stops the I/O thread of the old settings // Apply new settings memcpy(&m_sUartData, tDATA, sizeof(DBC_UART_DATA)); #ifdef DEBUG LOG("Reconect with new settings"); #endif - m_bValid = create_SOL(); + m_nNextConnectMs = 0; // new address: no back-off + m_bValid = connectSOL(); }; free(tDATA); } @@ -140,13 +233,13 @@ bool deviceETH2UART::validate(void) { LOG_ERROR("Error Fetch DB Data!"); }; - // Finally in any case If Not Connected -> try to Connect! - if (! m_bValid) + // Finally in any case If Not Connected -> try to Connect (after the back-off) + if (! m_bValid && e2uNowMs() >= m_nNextConnectMs) { #ifdef DEBUG LOG("Try to Conncet"); #endif - m_bValid = create_SOL(); + m_bValid = connectSOL(); }; if (m_bValid) { @@ -177,103 +270,122 @@ struct ping_pkt char msg[PING_PKT_S - sizeof(struct icmphdr)]; }; +/* + ICMP echo to the gateway: up to E2UART_PING_ATTEMPTS requests, each waiting E2UART_PING_TIMEOUT_MS. + Before: one request and one recvfrom() (3 s - the 300 ms set first was overwritten). A single lost + packet failed the check, a signal (EINTR) ended the wait at once, and ANY ICMP packet received by + the raw socket (e.g. the reply to another gateway's ping) counted as the answer. + Now only an echo reply from the gateway with our id and sequence number counts. +*/ bool deviceETH2UART::pingDevice() { - bool RetVal = false; - if (m_bValid) + int sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); + if (sockfd < 0) { -#ifdef DEBUG_EXTRA - LOG("Pinging Device!"); -#endif - int sockfd; - int ttl_val = 64, msg_count = 0;//, flag = 1, msg_received_count = 0; - size_t i; - struct ping_pkt pckt; - struct sockaddr_in ping_addr; - struct sockaddr_in r_addr; - struct timeval tv_out; + char tB[160]; + snprintf(tB, sizeof(tB), "ICMP socket failed: %s (needs root / CAP_NET_RAW)", strerror(errno)); + LOG_ERROR(tB); + return false; + }; + int ttl_val = 64; + if (setsockopt(sockfd, SOL_IP, IP_TTL, &ttl_val, sizeof(ttl_val)) != 0) + { + LOG_ERROR("Setting socket options to TTL failed!"); + close(sockfd); + return false; + }; + static std::atomic s_nSequence(0); + uint16_t tId = (uint16_t) (getpid() & 0xFFFF); + char tReason[96] = "no reply"; + bool RetVal = false; + for (int tAttempt = 0; tAttempt < E2UART_PING_ATTEMPTS && ! RetVal; tAttempt++) + { + RetVal = pingOnce(sockfd, tId, ++s_nSequence, tReason, sizeof(tReason)); + }; + close(sockfd); + if (! RetVal) + { + char tB[256]; + snprintf(tB, sizeof(tB), "No ICMP reply from %.64s: %s (%d x %d ms)", m_sUartData.path, tReason, E2UART_PING_ATTEMPTS, E2UART_PING_TIMEOUT_MS); + LOG_ERROR(tB); + }; + return RetVal; +} - tv_out.tv_sec = 0; - tv_out.tv_usec = 300000; // 1/3 of second +bool deviceETH2UART::pingOnce(int sockfd, uint16_t id, uint16_t seq, char * reason, size_t reasonSize) +{ + struct ping_pkt pckt; + struct sockaddr_in ping_addr; + memset(&ping_addr, 0, sizeof(ping_addr)); + ping_addr.sin_family = AF_INET; + ping_addr.sin_addr.s_addr = inet_addr(m_sUartData.path); + + memset(&pckt, 0, sizeof(pckt)); + pckt.hdr.type = ICMP_ECHO; + pckt.hdr.un.echo.id = htons(id); + pckt.hdr.un.echo.sequence = htons(seq); + size_t i; + for (i = 0; i < sizeof(pckt.msg) - 1; i++) + { + pckt.msg[i] = (char) i + '0'; + } + pckt.msg[i] = 0; + pckt.hdr.checksum = checksumPing(&pckt, sizeof(pckt)); - ping_addr.sin_family = AF_INET; - ping_addr.sin_addr.s_addr = inet_addr(m_sUartData.path); - // ping_addr.sin_port = htons( m_nPort ); -#ifdef DEBUG_EXTRA - LOG(m_sUartData.path); -#endif - sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); - if (sockfd < 0) + if (sendto(sockfd, &pckt, sizeof(pckt), 0, (struct sockaddr *) &ping_addr, sizeof(ping_addr)) <= 0) + { + snprintf(reason, reasonSize, "send failed: %s", strerror(errno)); + return false; + }; + uint64_t tDeadline = e2uNowMs() + E2UART_PING_TIMEOUT_MS; + for (;;) + { + uint64_t tNow = e2uNowMs(); + if (tNow >= tDeadline) { - LOG_ERROR("Socket file descriptor not received!"); + snprintf(reason, reasonSize, "timeout"); return false; }; - - // set socket options at ip to TTL and value to 64, - // change to what you want by setting ttl_val - if (setsockopt(sockfd, SOL_IP, IP_TTL, &ttl_val, sizeof(ttl_val)) != 0) + struct pollfd tPfd; + tPfd.fd = sockfd; + tPfd.events = POLLIN; + int tRc = poll(&tPfd, 1, (int) (tDeadline - tNow)); + if (tRc < 0) { - LOG_ERROR("Setting socket options to TTL failed!"); - shutdown(sockfd, SHUT_RDWR); - close(sockfd); + if (errno == EINTR) + { + continue; // a signal is not a missing reply + }; + snprintf(reason, reasonSize, "poll failed: %s", strerror(errno)); return false; }; - - // setting timeout of recv setting - setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char *) &tv_out, sizeof tv_out); - - // flag is whether packet was sent or not - //flag = 1; - - // filling packet - bzero(&pckt, sizeof(pckt)); - - pckt.hdr.type = ICMP_ECHO; - pckt.hdr.un.echo.id = getpid(); - - for (i = 0; i < sizeof(pckt.msg) - 1; i++) + if (tRc == 0) { - pckt.msg[i] = (char)i + '0'; - } - - pckt.msg[i] = 0; - pckt.hdr.un.echo.sequence = msg_count++; - pckt.hdr.checksum = checksumPing(&pckt, sizeof(pckt)); // checksum(&pckt, sizeof(pckt)); - - // send packet - if (sendto(sockfd, &pckt, sizeof(pckt), 0, (struct sockaddr *) &ping_addr, sizeof(ping_addr)) <= 0) + continue; // deadline check above + }; + uint8_t tBuf[1024]; + struct sockaddr_in r_addr; + socklen_t addr_len = sizeof(r_addr); + ssize_t tLen = recvfrom(sockfd, tBuf, sizeof(tBuf), MSG_DONTWAIT, (struct sockaddr *) &r_addr, &addr_len); + if (tLen <= 0) { - LOG_ERROR("Packet Sending Failed!"); - shutdown(sockfd, SHUT_RDWR); - close(sockfd); - return false; + continue; }; - - // receive packet - socklen_t addr_len = sizeof(r_addr); - struct timeval tv; - tv.tv_sec = 3; // timeout_in_seconds; - tv.tv_usec = 0; - setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char *) &tv, sizeof tv); - - if (recvfrom(sockfd, &pckt, sizeof(pckt), 0, (struct sockaddr *) &r_addr, &addr_len) <= 0) + // A raw socket returns the IP header too and gets every ICMP packet of the host + size_t tIpLen = (size_t) (tBuf[0] & 0x0F) * 4; + if ((size_t) tLen < tIpLen + sizeof(struct icmphdr)) { - LOG_ERROR("Packet receive failed!"); - shutdown(sockfd, SHUT_RDWR); - close(sockfd); - return false; - } - else + continue; + }; + struct icmphdr * tIcmp = (struct icmphdr *) (tBuf + tIpLen); + if (r_addr.sin_addr.s_addr == ping_addr.sin_addr.s_addr && tIcmp->type == ICMP_ECHOREPLY && ntohs(tIcmp->un.echo.id) == id && ntohs(tIcmp->un.echo.sequence) == seq) { #ifdef DEBUG_EXTRA LOG("Device Is OK!"); #endif - RetVal = true; + return true; }; - shutdown(sockfd, SHUT_RDWR); - close(sockfd); }; - return RetVal; } bool deviceETH2UART::create_SOL() @@ -300,6 +412,13 @@ bool deviceETH2UART::create_SOL() LOG_ERROR("No Adress Defined!"); return false; }; + // A previous connection / I/O thread is closed first. Before, the socket number was overwritten + // (the connection leaked) and init() failed while the old thread ran: every reconnect left an open + // TCP connection at the gateway and the node stayed invalid although "Connected". + if (m_iDeviceFD != -1 || E2U_IO_STATUS != TH_PRE_INIT) + { + closePort(); + }; switch (m_sUartData.mode) { @@ -450,6 +569,15 @@ bool deviceETH2UART::create_SOL() return false; }; + // Keepalive: a gateway that disappears (no FIN, e.g. mobile link lost) is detected + { + int tOn = 1, tIdle = E2UART_KEEPALIVE_IDLE_S, tIntvl = E2UART_KEEPALIVE_INTVL_S, tCnt = E2UART_KEEPALIVE_CNT; + setsockopt(m_iDeviceFD, SOL_SOCKET, SO_KEEPALIVE, &tOn, sizeof(tOn)); + setsockopt(m_iDeviceFD, IPPROTO_TCP, TCP_KEEPIDLE, &tIdle, sizeof(tIdle)); + setsockopt(m_iDeviceFD, IPPROTO_TCP, TCP_KEEPINTVL, &tIntvl, sizeof(tIntvl)); + setsockopt(m_iDeviceFD, IPPROTO_TCP, TCP_KEEPCNT, &tCnt, sizeof(tCnt)); + } + // assign IP, PORT struct sockaddr_in tServerAddr; memset(&tServerAddr, 0, sizeof(tServerAddr)); @@ -466,15 +594,23 @@ bool deviceETH2UART::create_SOL() #ifdef DEBUG LOG("EINPROGRESS in connect() - selecting"); #endif + // Over the Internet a connect takes longer than on a LAN (the timeout was 1 s) + uint64_t tDeadline = e2uNowMs() + E2UART_CONNECT_TIMEOUT_MS; do { + uint64_t tNow = e2uNowMs(); + uint64_t tLeft = (tNow < tDeadline) ? tDeadline - tNow : 0; fd_set myset; struct timeval tv; - tv.tv_sec = 1; // one second - tv.tv_usec = 0; + tv.tv_sec = tLeft / 1000; + tv.tv_usec = (tLeft % 1000) * 1000; FD_ZERO(&myset); FD_SET(m_iDeviceFD, &myset); retVal = select(m_iDeviceFD + 1, NULL, &myset, NULL, &tv); + if (retVal < 0 && errno == EINTR && e2uNowMs() < tDeadline) + { + continue; // interrupted by a signal: wait the rest of the time + } if (retVal < 0 && errno != EINTR) { char cBuffer[512]; @@ -516,7 +652,9 @@ bool deviceETH2UART::create_SOL() } else { - LOG_ERROR("Timeout in select() - Cancelling!"); + char cBuffer[160]; + snprintf(cBuffer, sizeof(cBuffer), "Timeout (%d ms) connecting to [%.64s:%d] - Cancelling!", E2UART_CONNECT_TIMEOUT_MS, m_sUartData.path, m_sUartData.port); + LOG_ERROR(cBuffer); close(m_iDeviceFD); m_iDeviceFD = -1; @@ -549,7 +687,13 @@ bool deviceETH2UART::create_SOL() break; }; }; - return init(); + if (! init()) + { + LOG_ERROR("Can not start the I/O thread - closing the connection"); + closePort(); + return false; + }; + return true; } /* @@ -961,8 +1105,8 @@ bool deviceETH2UART::sendData(uint8_t * Data, int DataSize) bool deviceETH2UART::reconnect(void) { - closePort(); - m_bValid = create_SOL(); + std::lock_guard tLock(m_mConnLock); + m_bValid = create_SOL(); // closes the old connection first return m_bValid; } @@ -984,9 +1128,11 @@ int deviceETH2UART::recptBlock(unsigned char * Buffer, int * BufferLength) socklen_t addr_len = sizeof(ClientAddress); // len is value/resuslt // RetVal = recvfrom( m_nSocketFD, (char *)Buffer, MAXIMAL_SOCKET_PACKET_LENGTH, MSG_WAITALL, ( struct sockaddr *) &m_sClientAddr, &addr_len ); RetVal = recvfrom(m_iDeviceFD, (char *) Buffer, MAXIMAL_SOCKET_IO_BUFFER_LENGTH, MSG_DONTWAIT, (struct sockaddr *) &ClientAddress, &addr_len); - if (RetVal < 1) + // TCP: 0 = the gateway closed the connection (errno is not set then: the old check read a + // stale errno and could keep a closed connection forever). < 0: an error unless EAGAIN/EINTR + if ((RetVal == 0 && m_sUartData.mode == SOL_TCP_SERVER) || RetVal < 0) { - if (errno != EAGAIN && errno != EINTR) + if (RetVal == 0 || (errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR)) { LOG_ERROR("Peer Closes Connection!"); shutdown(m_iDeviceFD, 2); @@ -1172,5 +1318,6 @@ int deviceETH2UART::sendBlock(unsigned char * Data, int DataSize) return RetVal; } +#undef E2U_IO_STATUS #undef LOG_ERROR #undef LOG diff --git a/lib/App/common/deviceNodeEthernet2Serial.h b/lib/App/common/deviceNodeEthernet2Serial.h index 5d86e7f3..eb341037 100644 --- a/lib/App/common/deviceNodeEthernet2Serial.h +++ b/lib/App/common/deviceNodeEthernet2Serial.h @@ -5,6 +5,29 @@ //#include "../components/base/basicTransport.h" #include "deviceNode.h" #include "hardwareResource.h" + +#include + +// Timeouts for a gateway reached over the Internet (the 1 s connect timeout was a LAN value) +#ifndef E2UART_CONNECT_TIMEOUT_MS + #define E2UART_CONNECT_TIMEOUT_MS 5000 // TCP connect +#endif +#ifndef E2UART_PING_TIMEOUT_MS + #define E2UART_PING_TIMEOUT_MS 2000 // wait for one ICMP echo reply +#endif +#ifndef E2UART_PING_ATTEMPTS + #define E2UART_PING_ATTEMPTS 3 // echo requests before the device counts as unreachable +#endif +#ifndef E2UART_PING_INTERVAL_MS + #define E2UART_PING_INTERVAL_MS 10000 // UDP modes: ping at most this often (validate() runs every second) +#endif +// Reconnect back-off after a failed connect: 2 s, 4 s, ... up to 30 s +#define E2UART_RECONNECT_MIN_MS 2000 +#define E2UART_RECONNECT_MAX_MS 30000 +// TCP keepalive: a dead link is detected in about IDLE + INTVL * CNT seconds +#define E2UART_KEEPALIVE_IDLE_S 20 +#define E2UART_KEEPALIVE_INTVL_S 5 +#define E2UART_KEEPALIVE_CNT 4 #ifdef SERIAL_PING_PONG class deviceETH2UART : public deviceNode, public hardwareResource, public basicTransport, public basicThread #else @@ -25,7 +48,19 @@ DCB PortDCB; HANDLE m_ioFID; #endif + // create() / validate() / reconnect() / closePort() run on the node factory thread AND on the + // hardware manager thread (the class is a deviceNode and a hardwareResource): one at a time + std::recursive_mutex m_mConnLock; + bool m_bRegistered; // assigned to the hardware manager (once) + bool m_bLastPingOk; + uint64_t m_nNextPingMs; + uint64_t m_nNextConnectMs; + uint32_t m_nConnectBackoffMs; + bool pingDevice(); + bool pingOnce(int sockfd, uint16_t id, uint16_t seq, char * reason, size_t reasonSize); + bool linkAlive(void); + bool connectSOL(void); // create_SOL() with the reconnect back-off bool create_SOL(); bool closePort(); int sendBlock(unsigned char * Data, int DataSize); diff --git a/lib/App/common/deviceNodeFactory.cpp b/lib/App/common/deviceNodeFactory.cpp index 9540483d..3caf1427 100644 --- a/lib/App/common/deviceNodeFactory.cpp +++ b/lib/App/common/deviceNodeFactory.cpp @@ -502,6 +502,9 @@ void deviceNodeFactory::deleteNode(deviceNode * ptr) #ifdef DEBUG LOG("Destroying Ethernet to UART Gateway"); #endif + // Was not deleted: the object kept running (still validated by the hardware manager, still + // connected to the gateway) next to the new node created for the same id + delete((deviceETH2UART *) ptr); break; case ARGUS_IP_VIDEO_SERVER: #ifdef DEBUG @@ -682,6 +685,9 @@ void deviceNodeFactory::m_fThreadProc(void) tList = m_pDBC->listNodes(); if (tList != NULL) { + // deleteNode() erases from m_vDeviceNodes: collect first, delete after the loop + // (erasing inside the loop invalidated the iterator and skipped the next node) + vectorDeviceNodes tToDelete; for (vectorDeviceNodes::iterator idx = m_vDeviceNodes.begin(); idx < m_vDeviceNodes.end(); idx++) { bool tRemoved = true; @@ -707,9 +713,13 @@ void deviceNodeFactory::m_fThreadProc(void) #ifdef DEBUG_EXTRA LOG("Node not passed Validation!"); #endif - deleteNode(*idx); + tToDelete.push_back(*idx); }; }; + for (vectorDeviceNodes::iterator idx = tToDelete.begin(); idx != tToDelete.end(); idx++) + { + deleteNode(*idx); + }; tList->clear(); delete(tList); } @@ -718,7 +728,8 @@ void deviceNodeFactory::m_fThreadProc(void) #ifdef DEUBG_EXTRA LOG("All Modules Must be Deleted!"); #endif - for (vectorDeviceNodes::iterator idx = m_vDeviceNodes.begin(); idx < m_vDeviceNodes.end(); idx++) + vectorDeviceNodes tToDelete(m_vDeviceNodes); // deleteNode() erases from m_vDeviceNodes + for (vectorDeviceNodes::iterator idx = tToDelete.begin(); idx != tToDelete.end(); idx++) { deleteNode(*idx); } diff --git a/lib/App/common/hardwareManager.cpp b/lib/App/common/hardwareManager.cpp index 7bf71cb0..d5d8bf01 100644 --- a/lib/App/common/hardwareManager.cpp +++ b/lib/App/common/hardwareManager.cpp @@ -1,5 +1,7 @@ #include "hardwareManager.h" +#include + #include #include #include @@ -1718,8 +1720,15 @@ bool hardwareManager::assignResource(hardwareResource * ptr, bool protected_mode m_mVectorProtector.lock(); } LOG("LOCKED"); - m_vResources.push_back(ptr); - LOG("ADDED"); + if (std::find(m_vResources.begin(), m_vResources.end(), ptr) == m_vResources.end()) + { + m_vResources.push_back(ptr); + LOG("ADDED"); + } + else + { + LOG("ALREADY ASSIGNED"); // validated twice per round otherwise + }; if (protected_mode) { m_mVectorProtector.unlock(); From 1fa1f29a3594383280c2b6243eb2e8664edb48ad Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 08:04:12 +0000 Subject: [PATCH 2/7] Ethernet2UART gateway: wait long enough for the device's reply over the Internet "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 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 Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16 --- lib/App/common/deviceNode2D.cpp | 4 +- lib/App/common/deviceNodeCamera.cpp | 16 +- lib/App/common/deviceNodeEthernet2Serial.cpp | 185 +++++++++++-------- lib/App/common/deviceNodeEthernet2Serial.h | 11 ++ 4 files changed, 133 insertions(+), 83 deletions(-) diff --git a/lib/App/common/deviceNode2D.cpp b/lib/App/common/deviceNode2D.cpp index 7f4ad497..d845274f 100644 --- a/lib/App/common/deviceNode2D.cpp +++ b/lib/App/common/deviceNode2D.cpp @@ -280,14 +280,14 @@ void device2DSensor::connectMode() #endif if (tRES->isValid()) { - m_pPort = static_cast(static_cast(tRES)); + m_pPort = dynamic_cast(tRES); #ifdef DEBUG_EXTRA // Bind To Proto char tB[64]; sprintf(tB, "PortOBJ: %p", m_pPort); LOG(tB); #endif - if (! setTransport(m_pPort, false)) + if (m_pPort == NULL || ! setTransport(m_pPort, false)) { LOG_ERROR("Binding Port Failure!"); } diff --git a/lib/App/common/deviceNodeCamera.cpp b/lib/App/common/deviceNodeCamera.cpp index f8daa0ad..8a72d09d 100644 --- a/lib/App/common/deviceNodeCamera.cpp +++ b/lib/App/common/deviceNodeCamera.cpp @@ -362,8 +362,8 @@ bool deviceNodeCamera::create() { if (tRES->isValid()) { - tTransport = static_cast(static_cast(tRES)); - if (m_pProtocol->setTransport(tTransport)) + tTransport = dynamic_cast(tRES); + if (tTransport != NULL && m_pProtocol->setTransport(tTransport)) { if (! m_pProtocol->create()) { @@ -426,8 +426,8 @@ bool deviceNodeCamera::create() { if (tRES->isValid()) { - tTransport = static_cast(static_cast(tRES)); - if (m_pProtocol->setTransport(tTransport)) + tTransport = dynamic_cast(tRES); + if (tTransport != NULL && m_pProtocol->setTransport(tTransport)) { if (! m_pProtocol->create()) { @@ -1304,8 +1304,8 @@ void deviceNodeCamera::m_fThreadProc(void) { if (tRES->isValid()) { - tTransport = static_cast(static_cast(tRES)); - if (m_pProtocol->setTransport(tTransport)) + tTransport = dynamic_cast(tRES); + if (tTransport != NULL && m_pProtocol->setTransport(tTransport)) { if (! m_pProtocol->create()) { @@ -1368,8 +1368,8 @@ void deviceNodeCamera::m_fThreadProc(void) { if (tRES->isValid()) { - tTransport = static_cast(static_cast(tRES)); - if (m_pProtocol->setTransport(tTransport)) + tTransport = dynamic_cast(tRES); + if (tTransport != NULL && m_pProtocol->setTransport(tTransport)) { if (! m_pProtocol->create()) { diff --git a/lib/App/common/deviceNodeEthernet2Serial.cpp b/lib/App/common/deviceNodeEthernet2Serial.cpp index b7e612fc..43e45ee2 100644 --- a/lib/App/common/deviceNodeEthernet2Serial.cpp +++ b/lib/App/common/deviceNodeEthernet2Serial.cpp @@ -46,6 +46,9 @@ deviceETH2UART::deviceETH2UART(uint32_t nodeID) : m_iInFID = -1; m_iOutFID = -1; m_bRegistered = false; +#ifdef SERIAL_PING_PONG + m_pLastParser = NULL; +#endif m_bLastPingOk = true; m_nNextPingMs = 0; m_nNextConnectMs = 0; @@ -852,100 +855,136 @@ bool deviceETH2UART::closePort() return true; } #ifdef SERIAL_PING_PONG +bool deviceETH2UART::isRecipient(protocolParser * p) +{ + if (p == NULL) + { + return false; + }; + m_mQueueProtectorMutex.lock(); + bool tVal = std::find(m_vParsers.begin(), m_vParsers.end(), p) != m_vParsers.end(); + m_mQueueProtectorMutex.unlock(); + return tVal; +} + void deviceETH2UART::m_fThreadProc(void) { - int index; int RetVal; m_bThreadStatus = TH_WORKING; #ifdef DEBUG LOG("Sender Thread Started!"); #endif - pthread_setname_np( pthread_self(), "E2S IO" ); + pthread_setname_np( pthread_self(), "E2S IO" ); + SIO_TZ * tIdle = (SIO_TZ *) malloc(sizeof(SIO_TZ)); // receive buffer for data between requests while (m_bThreadStatus < TH_ENDED){ + SIO_TZ * tIOData = NULL; m_mBufferProtectorMutex.lock(); if (! m_qIO.empty()){ - SIO_TZ * tIOData; tIOData = m_qIO.front(); - m_mBufferProtectorMutex.unlock(); - if( tIOData ){ - // Remove from Queue - m_mBufferProtectorMutex.lock(); - m_qIO.pop(); - m_mBufferProtectorMutex.unlock(); - - index = 0; - //Sending Data to line - while ((index < tIOData->out_size) && (m_bThreadStatus < TH_ENDED)){ + m_qIO.pop(); + }; + m_mBufferProtectorMutex.unlock(); + + if (tIOData == NULL){ + // No request: still read the socket. A reply that came after the reply window (Internet + // delay) was left in the socket and read with the next request, as that request's reply. + // Now it goes to the parser of the request it answers, as soon as it arrives. + if (tIdle != NULL){ + tIdle->inp_size = 0; + RetVal = recptBlock(tIdle->inp_buffer, &tIdle->inp_size); + if (RetVal == -1){ + setConnectionStatus(CS_DISCONNECTED); + m_bThreadStatus = TH_ENDED; + LOG_ERROR("Connection Droped on Reception Data"); + } else if (tIdle->inp_size > 0){ + if (isRecipient(m_pLastParser)){ + m_pLastParser->parse(tIdle->inp_buffer, tIdle->inp_size); + } #ifdef DEBUG_COMMUNICATION - char TT[128]; - sprintf(TT, "Send \t%d bytes for \t%p", ( tIOData->out_size - index ), tIOData->boundParser ); - LOG(TT); + else { + LOG_ERROR("Data without request dropped"); + } #endif - RetVal = sendBlock(tIOData->out_buffer + index, tIOData->out_size - index); - if (RetVal > 0){ - index += RetVal; - } else { - // if 0 or -(error) - if (RetVal == 0) { - usleep(100); - } else { - setConnectionStatus(CS_DISCONNECTED); - // m_nOutputBufferSize = 0; - tIOData->out_size = 0; - m_bThreadStatus = TH_ENDED; - LOG_ERROR("Connection Droped on Sending Data"); - }; - }; + continue; // more may follow + }; + }; + SLEEP(5); + continue; + }; + + //Sending Data to line + int index = 0; + while ((index < tIOData->out_size) && (m_bThreadStatus < TH_ENDED)){ + #ifdef DEBUG_COMMUNICATION + char TT[128]; + sprintf(TT, "Send \t%d bytes for \t%p", ( tIOData->out_size - index ), tIOData->boundParser ); + LOG(TT); + #endif + RetVal = sendBlock(tIOData->out_buffer + index, tIOData->out_size - index); + if (RetVal > 0){ + index += RetVal; + } else { + // if 0 or -(error) + if (RetVal == 0) { + usleep(100); + } else { + setConnectionStatus(CS_DISCONNECTED); + tIOData->out_size = 0; + m_bThreadStatus = TH_ENDED; + LOG_ERROR("Connection Droped on Sending Data"); }; - //Try to receive data from line - tIOData->out_size = 0; - bool tDataOnline = false; - uint8_t tTOCounter = 20; - do { - RetVal = recptBlock( tIOData->inp_buffer, &tIOData->inp_size ); - if( RetVal == -1 ){ - setConnectionStatus(CS_DISCONNECTED); - tIOData->inp_size = 0; - m_bThreadStatus = TH_ENDED; - LOG_ERROR("Connection Droped on Reception Data"); - } else if( tIOData->inp_size ){ - tDataOnline = true; - if( tIOData->boundParser == NULL ){ - - } else { - #ifdef DEBUG_COMMUNICATION - char tB[128]; - sprintf( tB, "Read \t%d bytes for \t%p", tIOData->inp_size, tIOData->boundParser ); - LOG( tB ); - #endif - tDataOnline = tIOData->boundParser->parse( tIOData->inp_buffer, tIOData->inp_size ); - }; - } else { - if (tTOCounter) { - tTOCounter--; - SLEEP(5); + }; + }; + // A parser detached since the request was queued (sensor disconnected / deleted) gets nothing + protocolParser * tParser = isRecipient(tIOData->boundParser) ? tIOData->boundParser : NULL; + if (tParser != NULL){ + m_pLastParser = tParser; + }; + //Try to receive the reply: up to E2UART_REPLY_TIMEOUT_MS for its start, then while it keeps + //coming (E2UART_REPLY_GAP_MS between chunks); done when the parser has a complete packet and + //no more data is waiting + tIOData->out_size = 0; + bool tDataOnline = false; + uint64_t tDeadline = e2uNowMs() + E2UART_REPLY_TIMEOUT_MS; + do { + RetVal = recptBlock( tIOData->inp_buffer, &tIOData->inp_size ); + if( RetVal == -1 ){ + setConnectionStatus(CS_DISCONNECTED); + tIOData->inp_size = 0; + m_bThreadStatus = TH_ENDED; + LOG_ERROR("Connection Droped on Reception Data"); + } else if( tIOData->inp_size ){ + uint64_t tGapEnd = e2uNowMs() + E2UART_REPLY_GAP_MS; + if (tGapEnd > tDeadline){ + tDeadline = tGapEnd; + }; + if( tParser == NULL ){ + tDataOnline = true; + } else { #ifdef DEBUG_COMMUNICATION - } else { - LOG_ERROR("PACK TIMEOUT!"); + char tB[128]; + sprintf( tB, "Read \t%d bytes for \t%p", tIOData->inp_size, tParser ); + LOG( tB ); #endif - }; - }; - - } while ((m_bThreadStatus < TH_ENDED) && tTOCounter && ! (tDataOnline && RetVal == 0)); // Pack1 conditions -> White Space after Data. - // Free Package - #ifdef DEBUG_COMMUNICATION - LOG("Finishing Read Package"); - #endif - free(tIOData); + tDataOnline = tParser->parse( tIOData->inp_buffer, tIOData->inp_size ) || tDataOnline; + }; } else { - // Mutex already unlocked! + if (tDataOnline){ + break; // complete packet and the socket is empty (as before: white space after data) + }; SLEEP(5); }; - } else { - m_mBufferProtectorMutex.unlock(); - SLEEP(5); + } while ((m_bThreadStatus < TH_ENDED) && (e2uNowMs() < tDeadline)); + #ifdef DEBUG_COMMUNICATION + if (! tDataOnline){ + LOG_ERROR("PACK TIMEOUT!"); }; + LOG("Finishing Read Package"); + #endif + // Free Package + free(tIOData); }; + free(tIdle); } bool deviceETH2UART::sendData(uint8_t * Data, int DataSize, protocolParser *src ){ diff --git a/lib/App/common/deviceNodeEthernet2Serial.h b/lib/App/common/deviceNodeEthernet2Serial.h index eb341037..8ee3ac84 100644 --- a/lib/App/common/deviceNodeEthernet2Serial.h +++ b/lib/App/common/deviceNodeEthernet2Serial.h @@ -21,6 +21,15 @@ #ifndef E2UART_PING_INTERVAL_MS #define E2UART_PING_INTERVAL_MS 10000 // UDP modes: ping at most this often (validate() runs every second) #endif +// Reply of the device to one request (SERIAL_PING_PONG I/O thread). The 20 x 5 ms (~100 ms) of the +// serial line were too short over the Internet: a later reply was read only with the NEXT request +// and given to that request's parser (one reply behind -> retries -> "Communication Wait State TO!") +#ifndef E2UART_REPLY_TIMEOUT_MS + #define E2UART_REPLY_TIMEOUT_MS 800 // first byte of the reply (below the sensor's 1 s per attempt) +#endif +#ifndef E2UART_REPLY_GAP_MS + #define E2UART_REPLY_GAP_MS 150 // a started but incomplete reply: wait this long for the rest +#endif // Reconnect back-off after a failed connect: 2 s, 4 s, ... up to 30 s #define E2UART_RECONNECT_MIN_MS 2000 #define E2UART_RECONNECT_MAX_MS 30000 @@ -70,6 +79,8 @@ #ifdef SERIAL_PING_PONG virtual void m_fThreadProc(void); Q_SIO_TZ m_qIO; + protocolParser * m_pLastParser; // parser of the last request: gets data that arrives between requests + bool isRecipient(protocolParser * p); // still bound to this transport (not deleted / detached) #else U8 m_pInputBuffer[MAXIMAL_SOCKET_IO_BUFFER_LENGTH]; U8 m_pOutputBuffer[MAXIMAL_SOCKET_IO_BUFFER_LENGTH]; From 85ca06a8a2b77ee5dcb986b09ae5670fd8a872c8 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 08:29:26 +0000 Subject: [PATCH 3/7] Sensor behind a network gateway: wait 3 s per attempt instead of 1 s 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 Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16 --- lib/App/common/deviceNode2D.cpp | 127 +++++++++++---------- lib/App/common/deviceNodeEthernet2Serial.h | 6 +- lib/App/common/deviceNodeSensor.cpp | 4 +- lib/App/common/deviceNodeSensor.h | 6 + lib/components/base/basicTransport.h | 6 + 5 files changed, 85 insertions(+), 64 deletions(-) diff --git a/lib/App/common/deviceNode2D.cpp b/lib/App/common/deviceNode2D.cpp index d845274f..3298081f 100644 --- a/lib/App/common/deviceNode2D.cpp +++ b/lib/App/common/deviceNode2D.cpp @@ -76,7 +76,7 @@ void device2DSensor::cleanupDeviceStructures(void) LOG("Clean Basic Structures!"); #endif // m_eCurrentSequence = NO_SEQUENCE; - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; m_bInitialFlips = LGS_INITIAL_FLIPS; m_nCurrentAngle = 0; m_bDrawType = 0; @@ -287,6 +287,9 @@ void device2DSensor::connectMode() sprintf(tB, "PortOBJ: %p", m_pPort); LOG(tB); #endif + // Through a network gateway the replies take longer: wait longer per attempt + m_nTOCounterBase = (m_pPort != NULL && m_pPort->isNetworkLink()) ? LGS_NETWORK_TO_COUNTER : LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; if (m_pPort == NULL || ! setTransport(m_pPort, false)) { LOG_ERROR("Binding Port Failure!"); @@ -329,7 +332,7 @@ void device2DSensor::connectMode() }; case LRF_WS_STAGE_1: { - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; cleanupDeviceStructures(); m_bRequestedDeviceWM = MODE_DETECTOR; if (! setMode(MODE_DETECTOR)) @@ -375,7 +378,7 @@ void device2DSensor::handshakeMode() { if (m_bActualDeviceWM != MODE_DETECTOR) { - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; m_bRequestedDeviceWM = MODE_DETECTOR; if (! setMode(MODE_DETECTOR)) { @@ -396,7 +399,7 @@ void device2DSensor::handshakeMode() }; case LRF_WS_STAGE_1: { - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; if (! getSerialNumber()) { LOG_ERROR("Fall Back to Disconnected!"); @@ -410,7 +413,7 @@ void device2DSensor::handshakeMode() }; case LRF_WS_STAGE_2: { - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; if (! getVersionString()) { LOG_ERROR("Fall Back to Disconnected!"); @@ -461,7 +464,7 @@ void device2DSensor::readMode() case LRF_WS_INIT: { LOG("TryProfiles"); - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; if (! getDetectionProfile()) { LOG_ERROR("Fall Back to Disconnected!"); @@ -476,7 +479,7 @@ void device2DSensor::readMode() case LRF_WS_STAGE_1: { LOG("Get ParamMaster"); - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; if (! getParameters(true)) { LOG_ERROR("Fall Back to Disconnected!"); @@ -493,7 +496,7 @@ void device2DSensor::readMode() LOG("Get ParamSlave"); if (m_sNodeData.type == ARGUS_ALS_SENSOR) { // Read Slave Just for ALS series - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; if (! getParameters(false)) { LOG_ERROR("Fall Back to Disconnected!"); @@ -513,7 +516,7 @@ void device2DSensor::readMode() case LRF_WS_STAGE_3: { LOG("Get RELAY"); - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; if (! getRelayParameters()) { LOG_ERROR("Fall Back to Disconnected!"); @@ -528,7 +531,7 @@ void device2DSensor::readMode() case LRF_WS_STAGE_4: { LOG("Get WidthTable"); - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; if (! getWidthTable()) { LOG_ERROR("Fall Back to Disconnected!"); @@ -543,7 +546,7 @@ void device2DSensor::readMode() case LRF_WS_STAGE_5: { LOG("Get ShadowInfo"); - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; if (! getShadowInfo(m_sShadowHelper.m_bSequence)) { LOG_ERROR("Fall Back to Disconnected!"); @@ -561,7 +564,7 @@ void device2DSensor::readMode() // Have Info -> If No Poly - Skeep to go get DC if (m_sShadow.pPolygones) { - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; if (! getShadowPoly(m_sShadowHelper.m_bSequence, m_sShadowHelper.m_nCurrentPolygon)) { LOG_ERROR("Fall Back to Disconnected!"); @@ -585,7 +588,7 @@ void device2DSensor::readMode() { if (m_sShadowHelper.m_nCurrentPoint < m_sShadow.pPolygones[m_sShadowHelper.m_nCurrentPolygon].wCount) { - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; if (! getShadowPolyPoint(m_sShadowHelper.m_bSequence, m_sShadowHelper.m_nCurrentPolygon, m_sShadowHelper.m_nCurrentPoint)) { LOG_ERROR("Fall Back to Disconnected!"); @@ -650,7 +653,7 @@ bool device2DSensor::reset(){ setWM(LRF_WM_CONNECTION); return false; } else { - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; updateDataStatus(ARGUS_DS_BUSY); DELAY_10MS(1); // 10 ms }; @@ -817,7 +820,7 @@ void device2DSensor::syncMode() if (m_bActualDeviceWM != MODE_MASK) { LOG("Set Mask Mode"); - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; m_bRequestedDeviceWM = MODE_MASK; if (! setMode(MODE_MASK)) { @@ -849,10 +852,10 @@ void device2DSensor::syncMode() }; case LRF_WS_STAGE_1: { - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; if (m_bActualDeviceWM != MODE_MASK) { - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; m_bRequestedDeviceWM = MODE_MASK; if (! setMode(MODE_MASK)) { @@ -872,7 +875,7 @@ void device2DSensor::syncMode() }; case LRF_WS_STAGE_2: { - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; if (! setShadowInfo(m_sShadowHelper.m_bSequence, m_sShadow)) { LOG_ERROR("Fall Back to Disconnected!"); @@ -889,7 +892,7 @@ void device2DSensor::syncMode() if (m_sShadowHelper.m_nCurrentPolygon < m_sShadow.m_nPolygonCount) { m_sShadowHelper.m_nCurrentPoint = 0; - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; if (! setShadowPoly(m_sShadowHelper.m_bSequence, m_sShadow, m_sShadowHelper.m_nCurrentPolygon)) { LOG_ERROR("Fall Back to Disconnected!"); @@ -924,7 +927,7 @@ void device2DSensor::syncMode() }; case LRF_WS_STAGE_4: { - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; #ifdef DEBUG_EXTRA char tBuff[128]; sprintf(tBuff, "Send Point %d of %d", m_sShadowHelper.m_nCurrentPoint + 1, m_sShadow.pPolygones[m_sShadowHelper.m_nCurrentPolygon].wCount); @@ -933,7 +936,7 @@ void device2DSensor::syncMode() if (m_sShadowHelper.m_nCurrentPoint < m_sShadow.pPolygones[m_sShadowHelper.m_nCurrentPolygon].wCount) { LOG("Senfing Point"); - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; if (! setShadowPolyPoint(m_sShadowHelper.m_bSequence, m_sShadow, m_sShadowHelper.m_nCurrentPolygon, m_sShadowHelper.m_nCurrentPoint)) { LOG_ERROR("Fall Back to Disconnected!"); @@ -954,7 +957,7 @@ void device2DSensor::syncMode() }; case LRF_WS_STAGE_5: { - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; #ifdef DEBUG_EXTRA char tBuff[128]; sprintf(tBuff, "Send Shadow for angle %d [%d rays]", m_sShadowHelper.m_nCurrentRayLine, m_sShadow.ray_lines[m_sShadowHelper.m_nCurrentRayLine].nCount); @@ -973,7 +976,7 @@ void device2DSensor::syncMode() }; case LRF_WS_STAGE_6: { - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; #ifdef DEBUG_EXTRA char tBuff[128]; sprintf(tBuff, "Send Shadow RayLine %d for angle %d", m_sShadowHelper.m_nCurrentRay, m_sShadowHelper.m_nCurrentRayLine); @@ -1012,7 +1015,7 @@ void device2DSensor::syncMode() }; case LRF_WS_STAGE_7: { - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; if (! setShadowDone(m_sShadowHelper.m_bSequence)) { LOG_ERROR("Fall Back to Disconnected!"); @@ -1050,7 +1053,7 @@ void device2DSensor::syncMode() PLGS_2D_PARAMETERS tData = m_pDBC->getLRFDetectionProfile(m_sNodeData.aux_id, m_nActiveDetectionProfile, true); if (tData) { - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER << 2; + m_bTimeOutCounter = m_nTOCounterBase << 2; if (! setParameters(tData, true, m_nActiveDetectionProfile)) { LOG_ERROR("Fall Back to Disconnected!"); @@ -1075,7 +1078,7 @@ void device2DSensor::syncMode() PLGS_2D_PARAMETERS tData = m_pDBC->getLRFDetectionProfile(m_sNodeData.aux_id, m_nActiveDetectionProfile, false); if (tData) { - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER << 2; + m_bTimeOutCounter = m_nTOCounterBase << 2; if (! setParameters(tData, false, m_nActiveDetectionProfile)) { LOG_ERROR("Fall Back to Disconnected!"); @@ -1253,7 +1256,7 @@ void device2DSensor::save_ini() // ANODE_WM_2D_SET_GETFILE_MODE if (m_bActualDeviceWM != MODE_GETFILE) { - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; m_bRequestedDeviceWM = MODE_GETFILE; if (! setMode(MODE_GETFILE)) { @@ -1385,7 +1388,7 @@ void device2DSensor::save_ini() break; }; }; - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; if (! sendGF_package(m_sGetFileTransfers.helpers[m_sGetFileTransfers.current]->state | m_sGetFileTransfers.helpers[m_sGetFileTransfers.current]->index, m_sGetFileTransfers.helpers[m_sGetFileTransfers.current]->data_size, m_sGetFileTransfers.helpers[m_sGetFileTransfers.current]->data)) { @@ -1424,7 +1427,7 @@ void device2DSensor::save_ini() case LRF_WS_STAGE_4: { // Issue Full Reset - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; if (! doFullReset()) { LOG_ERROR("Fall Back to Disconnected!"); @@ -1520,7 +1523,7 @@ void device2DSensor::save_detection() PLGS_2D_PARAMETERS tData = m_pDBC->getLRFDetectionProfile(m_sNodeData.aux_id, m_nActiveDetectionProfile, true); if (tData) { - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; if (! setParameters(tData, true, m_nActiveDetectionProfile)) { LOG_ERROR("Fall Back to Disconnected!"); @@ -1546,7 +1549,7 @@ void device2DSensor::save_detection() PLGS_2D_PARAMETERS tData = m_pDBC->getLRFDetectionProfile(m_sNodeData.aux_id, m_nActiveDetectionProfile, false); if (tData) { - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; if (! setParameters(tData, false, m_nActiveDetectionProfile)) { LOG_ERROR("Fall Back to Disconnected!"); @@ -1605,7 +1608,7 @@ void device2DSensor::wait_device() { case LRF_WS_INIT: { - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; if (! getState()) { LOG_ERROR("Fall Back to Disconnected!"); @@ -1760,10 +1763,10 @@ void device2DSensor::save_masks() }; case LRF_WS_STAGE_1: { - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; if (m_bActualDeviceWM != MODE_MASK) { - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; m_bRequestedDeviceWM = MODE_MASK; if (! setMode(MODE_MASK)) { @@ -1783,7 +1786,7 @@ void device2DSensor::save_masks() }; case LRF_WS_STAGE_2: { - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; char tB[129]; sprintf(tB, "Masks Status: 0x%08X", m_sShadow.m_nEnabled); @@ -1803,7 +1806,7 @@ void device2DSensor::save_masks() // V 3 4 ... B 5 6 .. E 7 case LRF_WS_STAGE_5: { - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; if (m_sShadowHelper.m_nCurrentPolygon < m_sShadow.m_nPolygonCount) { m_sShadowHelper.m_nCurrentPoint = 0; @@ -1846,7 +1849,7 @@ void device2DSensor::save_masks() }; case LRF_WS_STAGE_6: { - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; #ifdef DEBUG_EXTRA char tBuff[128]; sprintf(tBuff, "Send Point %d of %d", m_sShadowHelper.m_nCurrentPoint + 1, m_sShadow.pPolygones[m_sShadowHelper.m_nCurrentPolygon].wCount); @@ -1874,7 +1877,7 @@ void device2DSensor::save_masks() case LRF_WS_STAGE_3: { - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; #ifdef DEBUG_EXTRA char tBuff[128]; sprintf(tBuff, "Send Shadow for angle %d [%d rays]", m_sShadowHelper.m_nCurrentRayLine, m_sShadow.ray_lines[m_sShadowHelper.m_nCurrentRayLine].nCount); @@ -1893,7 +1896,7 @@ void device2DSensor::save_masks() }; case LRF_WS_STAGE_4: { - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; #ifdef DEBUG_EXTRA char tBuff[128]; sprintf(tBuff, "Send Shadow RayLine %d for andle %d", m_sShadowHelper.m_nCurrentRay, m_sShadowHelper.m_nCurrentRayLine); @@ -1933,7 +1936,7 @@ void device2DSensor::save_masks() }; case LRF_WS_STAGE_7: { - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; if (! setShadowDone(m_sShadowHelper.m_bSequence)) { LOG_ERROR("Fall Back to Disconnected!"); @@ -2033,7 +2036,7 @@ void device2DSensor::fileTransferSpecialWait() LOG("ATTEMPT RECOVER"); #endif m_bOpRetryCnt--; - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; registerCommError(false); m_sGetFileTransfers.helpers[m_sGetFileTransfers.current]->state |= GF_ERRORMODE; } @@ -2081,7 +2084,7 @@ void device2DSensor::fileTransferMode() { if (m_bActualDeviceWM != MODE_GETFILE) { - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; m_bRequestedDeviceWM = MODE_GETFILE; if (! setMode(MODE_GETFILE)) { @@ -2211,7 +2214,7 @@ void device2DSensor::fileTransferMode() { m_sGetFileTransfers.helpers[m_sGetFileTransfers.current]->state &= (~GF_ERRORMODE); }; - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; char tB[256]; sprintf(tB, "Current Index: %d", m_sGetFileTransfers.helpers[m_sGetFileTransfers.current]->index); LOG(tB); @@ -2256,7 +2259,7 @@ void device2DSensor::fileTransferMode() if (m_sGetFileTransfers.transfer_ending_mode == GF_EM_ISSUE_RESET) { LOG("Must Issue Reset"); - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; if (! doFullReset()) { LOG_ERROR("Fall Back to Disconnected!"); @@ -2307,7 +2310,7 @@ void device2DSensor::getfileMode() case LRF_WS_INIT:{ m_nCurrentAngle = 0; if ( m_bActualDeviceWM != MODE_GETFILE ) { - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; m_bRequestedDeviceWM = MODE_GETFILE; if( !setMode( MODE_GETFILE ) ) { LOG_ERROR("Fall Back to Disconnected!"); @@ -2428,7 +2431,7 @@ void device2DSensor::getfileMode() break; }; }; - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; if( !sendGF_package( ( m_sGetFileTransfers.helpers[m_sGetFileTransfers.current]->state | m_sGetFileTransfers.helpers[m_sGetFileTransfers.current]->index ), m_sGetFileTransfers.helpers[m_sGetFileTransfers.current]->data_size, @@ -2459,7 +2462,7 @@ void device2DSensor::getfileMode() if( m_bOpRetryCnt ){ m_bOpRetryCnt--; - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; registerCommError( false ); LRF_WORK_STAGE pS = getPrevStage(); @@ -2517,7 +2520,7 @@ void device2DSensor::drawMode() { if (m_bActualDeviceWM != MODE_BORDER) { - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; m_bRequestedDeviceWM = MODE_BORDER; if (! setMode(MODE_BORDER)) { @@ -2546,7 +2549,7 @@ void device2DSensor::drawMode() }; case LRF_WS_STAGE_2: { - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER << 4; + m_bTimeOutCounter = m_nTOCounterBase << 4; #ifdef DEBUG_EXTRA LOG("DRAW GET ANGLE"); #endif @@ -2575,7 +2578,7 @@ void device2DSensor::drawMode() AK->releaseExplicitChannel( m_sNodeData.node_id, m_sLRF_DATA.uart_id ); } - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; m_bRequestedDeviceWM = MODE_DETECTOR; if (! setMode(MODE_DETECTOR)) { @@ -2629,7 +2632,7 @@ void device2DSensor::fullDrawMode() #ifdef DEBUG LOG("SET MODE BORDER!"); #endif - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; m_bRequestedDeviceWM = MODE_BORDER; if (! setMode(MODE_BORDER)) { @@ -2649,7 +2652,7 @@ void device2DSensor::fullDrawMode() }; case LRF_WS_STAGE_1: { - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER << 4; + m_bTimeOutCounter = m_nTOCounterBase << 4; #ifdef DEBUG LOG("FULL DRAW GET ANGLE"); #endif @@ -2669,7 +2672,7 @@ void device2DSensor::fullDrawMode() #ifdef DEBUG LOG("FULL DRAW FINISHING"); #endif - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; m_bRequestedDeviceWM = MODE_DETECTOR; if (! setMode(MODE_DETECTOR)) { @@ -2743,7 +2746,7 @@ void device2DSensor::maskMode() { case LRF_WS_INIT: { - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; uint8_t cm = m_pDBC->getLRFMasksStatus(m_sLRF_DATA.id); EVENT_CONTAINER * bEVT = NULL; TARGET_DATA * tData = prepareTargetData(0, 0, 0, 0); @@ -2838,7 +2841,7 @@ void device2DSensor::alarmMode() { if (m_bActualDeviceWM != MODE_DETECTOR) { - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; m_bRequestedDeviceWM = MODE_DETECTOR; if (! setMode(MODE_DETECTOR)) { @@ -2858,7 +2861,7 @@ void device2DSensor::alarmMode() }; case LRF_WS_STAGE_1: { - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; if (! getState2()) { LOG_ERROR("Fall Back to Disconnected!"); @@ -2933,7 +2936,7 @@ void device2DSensor::idleMode() { if (m_bActualDeviceWM != MODE_DETECTOR) { - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; m_bRequestedDeviceWM = MODE_DETECTOR; if (! setMode(MODE_DETECTOR)) { @@ -2953,7 +2956,7 @@ void device2DSensor::idleMode() }; case LRF_WS_STAGE_1: { - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; if (! getState2()) { LOG_ERROR("Fall Back to Disconnected!"); @@ -2998,7 +3001,7 @@ void device2DSensor::proceedDBCommands() } else { - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; updateDataStatus(ARGUS_DS_BUSY); // transactionWaitResult(); DELAY_10MS(10); // 100 ms @@ -3024,7 +3027,7 @@ void device2DSensor::proceedDBCommands() } else { - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; updateDataStatus(ARGUS_DS_STUDY); // transactionWaitResult(); DELAY_10MS(10); // 100 ms @@ -3352,7 +3355,7 @@ bool device2DSensor::packetHandler(protocolPackage * Package) #endif // Have Some Replay from device -> Reset Timeouts m_bOpRetryCnt = LGS_CMD_RETRY_COUNT; - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; switch (Package->m_pData[CMD_IDX]) { case CMD_STATE: transactionSetResult(TRANSACTION_RESULT_OK); break; @@ -3835,7 +3838,7 @@ bool device2DSensor::packetHandler(protocolPackage * Package) // setStage( LRF_WS_STAGE_2 ); while (Package->m_nSize > (cIDX + 2)) { - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; switch (Package->m_pData[cIDX + 1]) { case 0x00: diff --git a/lib/App/common/deviceNodeEthernet2Serial.h b/lib/App/common/deviceNodeEthernet2Serial.h index 8ee3ac84..32076378 100644 --- a/lib/App/common/deviceNodeEthernet2Serial.h +++ b/lib/App/common/deviceNodeEthernet2Serial.h @@ -25,7 +25,7 @@ // serial line were too short over the Internet: a later reply was read only with the NEXT request // and given to that request's parser (one reply behind -> retries -> "Communication Wait State TO!") #ifndef E2UART_REPLY_TIMEOUT_MS - #define E2UART_REPLY_TIMEOUT_MS 800 // first byte of the reply (below the sensor's 1 s per attempt) + #define E2UART_REPLY_TIMEOUT_MS 2500 // first byte of the reply (below the sensor's LGS_NETWORK_TO_COUNTER, 3 s) #endif #ifndef E2UART_REPLY_GAP_MS #define E2UART_REPLY_GAP_MS 150 // a started but incomplete reply: wait this long for the rest @@ -100,6 +100,10 @@ virtual bool sendData(uint8_t * Data, int DataSize); #endif virtual bool reconnect(void); + virtual bool isNetworkLink(void) + { + return true; + } }; #endif diff --git a/lib/App/common/deviceNodeSensor.cpp b/lib/App/common/deviceNodeSensor.cpp index 3a26f30b..fa8acb01 100644 --- a/lib/App/common/deviceNodeSensor.cpp +++ b/lib/App/common/deviceNodeSensor.cpp @@ -169,6 +169,7 @@ deviceNodeSensor::deviceNodeSensor(uint32_t id) : { m_nCommErrorsCounter = 0; + m_nTOCounterBase = LGS_DEFAULT_TO_COUNTER; m_ePPMODE = STG_INIT; m_bValidationSkipCounter = DAFAULT_VALIDATION_SKIP_COUNTER; m_nCommErrorsStatTO = COMMUNICATION_ERROR_STATISTIC_HARVEST_INTERVAL_IN_SECONDS; @@ -252,6 +253,7 @@ deviceNodeSensor::deviceNodeSensor(DBC_NODE_DATA * Data) : m_oPosition() { m_nCommErrorsCounter = 0; + m_nTOCounterBase = LGS_DEFAULT_TO_COUNTER; m_ePPMODE = STG_INIT; m_bValidationSkipCounter = DAFAULT_VALIDATION_SKIP_COUNTER; m_nCommErrorsStatTO = COMMUNICATION_ERROR_STATISTIC_HARVEST_INTERVAL_IN_SECONDS; @@ -1189,7 +1191,7 @@ void deviceNodeSensor::waitStateFunction(LRF_WORK_STAGE boboStage) LOG("ATTEMPT RECOVER"); #endif m_bOpRetryCnt--; - m_bTimeOutCounter = LGS_DEFAULT_TO_COUNTER; + m_bTimeOutCounter = m_nTOCounterBase; registerCommError(false); LRF_WORK_STAGE pS = getPrevStage(); diff --git a/lib/App/common/deviceNodeSensor.h b/lib/App/common/deviceNodeSensor.h index 6901c77e..0dca9599 100644 --- a/lib/App/common/deviceNodeSensor.h +++ b/lib/App/common/deviceNodeSensor.h @@ -11,6 +11,11 @@ #define LGS_DEFAULT_SLEEP_TIME 100 #define LGS_ALERT_SLEEP_TIME 10 #define LGS_DEFAULT_TO_COUNTER 10 // 100ms +// Sensor behind a network link (Ethernet to serial gateway over the Internet): 3 s per attempt. +// The 1 s of a local serial line was shorter than the round trip of a mobile link at times. +#ifndef LGS_NETWORK_TO_COUNTER + #define LGS_NETWORK_TO_COUNTER 30 +#endif #define LGS_DEFAULT_WS_TIME 10 // 100ms #define LGS_INITIAL_FLIPS 8 #define LGS_CMD_RETRY_COUNT 16 @@ -176,6 +181,7 @@ class deviceNodeSensor : public deviceNode, public basicThread targetPipeLine * m_pTargetPipeLine; uint8_t m_bOpRetryCnt; uint16_t m_bTimeOutCounter; + uint16_t m_nTOCounterBase; // wait per attempt (x 100 ms): LGS_DEFAULT_TO_COUNTER or LGS_NETWORK_TO_COUNTER E_MODES m_bActualDeviceWM; E_MODES m_bRequestedDeviceWM; uint32_t m_nChannelTO; diff --git a/lib/components/base/basicTransport.h b/lib/components/base/basicTransport.h index 0e93a4ee..bf327293 100644 --- a/lib/components/base/basicTransport.h +++ b/lib/components/base/basicTransport.h @@ -77,6 +77,12 @@ class basicTransport { return false; } + // The device is reached over a network (e.g. an Ethernet to serial gateway on the Internet): + // replies take longer than on a local serial line + virtual bool isNetworkLink(void) + { + return false; + } bool addRecipient(protocolParser * ProtoParser); bool removeRecipient(protocolParser * ProtoParser); From 2f017a64d8aa6643723294b74dbbf90ae92e22f8 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 08:50:13 +0000 Subject: [PATCH 4/7] Debug: log communication timing of sensors and the Ethernet2UART gateway 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 Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16 --- lib/App/common/deviceNodeEthernet2Serial.cpp | 84 ++++++++++--- lib/App/common/deviceNodeSensor.cpp | 122 ++++++++++++++++++- lib/App/common/deviceNodeSensor.h | 7 ++ 3 files changed, 196 insertions(+), 17 deletions(-) diff --git a/lib/App/common/deviceNodeEthernet2Serial.cpp b/lib/App/common/deviceNodeEthernet2Serial.cpp index 43e45ee2..f1653d55 100644 --- a/lib/App/common/deviceNodeEthernet2Serial.cpp +++ b/lib/App/common/deviceNodeEthernet2Serial.cpp @@ -10,6 +10,12 @@ // #define DEBUG_EXTRA // #define DEBUG_SERIAL_COMMUNICATION +// Request / reply timing of the I/O thread: no reply, slow and late replies, one-minute summary +#define DEBUG_COMMUNICATION +#ifndef E2UART_SLOW_REPLY_MS + #define E2UART_SLOW_REPLY_MS 500 +#endif +#define E2UART_TIMING_REPORT_MS 60000 #define LOG(X) deviceNode::m_pLog->Log("E2UART", this, X) @@ -876,7 +882,23 @@ void deviceETH2UART::m_fThreadProc(void) #endif pthread_setname_np( pthread_self(), "E2S IO" ); SIO_TZ * tIdle = (SIO_TZ *) malloc(sizeof(SIO_TZ)); // receive buffer for data between requests +#ifdef DEBUG_COMMUNICATION + uint32_t tReqNo = 0, tStReq = 0, tStReply = 0, tStNoReply = 0, tStSlow = 0, tStLate = 0; + uint64_t tStSum = 0, tStMax = 0, tStStart = e2uNowMs(), tLastReqMs = 0; + char tDbg[256]; +#endif while (m_bThreadStatus < TH_ENDED){ +#ifdef DEBUG_COMMUNICATION + if (e2uNowMs() - tStStart >= E2UART_TIMING_REPORT_MS){ + snprintf(tDbg, sizeof(tDbg), "IO stats %d s [%.64s:%d]: %u requests, %u replies (first byte avg %llu ms, max %llu ms), %u slow (> %d ms), %u without reply in %d ms, %u late", + E2UART_TIMING_REPORT_MS / 1000, m_sUartData.path, m_sUartData.port, tStReq, tStReply, (unsigned long long) (tStReply ? tStSum / tStReply : 0), + (unsigned long long) tStMax, tStSlow, E2UART_SLOW_REPLY_MS, tStNoReply, E2UART_REPLY_TIMEOUT_MS, tStLate); + LOG(tDbg); + tStReq = tStReply = tStNoReply = tStSlow = tStLate = 0; + tStSum = tStMax = 0; + tStStart = e2uNowMs(); + }; +#endif SIO_TZ * tIOData = NULL; m_mBufferProtectorMutex.lock(); if (! m_qIO.empty()){ @@ -897,6 +919,12 @@ void deviceETH2UART::m_fThreadProc(void) m_bThreadStatus = TH_ENDED; LOG_ERROR("Connection Droped on Reception Data"); } else if (tIdle->inp_size > 0){ +#ifdef DEBUG_COMMUNICATION + tStLate++; + snprintf(tDbg, sizeof(tDbg), "IO: late data %d B, %llu ms after request #%u (reply window %d ms)", tIdle->inp_size, + (unsigned long long) (tLastReqMs ? e2uNowMs() - tLastReqMs : 0), tReqNo, E2UART_REPLY_TIMEOUT_MS); + LOG(tDbg); +#endif if (isRecipient(m_pLastParser)){ m_pLastParser->parse(tIdle->inp_buffer, tIdle->inp_size); } @@ -913,13 +941,15 @@ void deviceETH2UART::m_fThreadProc(void) }; //Sending Data to line +#ifdef DEBUG_COMMUNICATION + int tSentBytes = tIOData->out_size; + uint64_t tSendMs = e2uNowMs(); + tReqNo++; + tStReq++; + tLastReqMs = tSendMs; +#endif int index = 0; while ((index < tIOData->out_size) && (m_bThreadStatus < TH_ENDED)){ - #ifdef DEBUG_COMMUNICATION - char TT[128]; - sprintf(TT, "Send \t%d bytes for \t%p", ( tIOData->out_size - index ), tIOData->boundParser ); - LOG(TT); - #endif RetVal = sendBlock(tIOData->out_buffer + index, tIOData->out_size - index); if (RetVal > 0){ index += RetVal; @@ -946,6 +976,10 @@ void deviceETH2UART::m_fThreadProc(void) tIOData->out_size = 0; bool tDataOnline = false; uint64_t tDeadline = e2uNowMs() + E2UART_REPLY_TIMEOUT_MS; +#ifdef DEBUG_COMMUNICATION + uint64_t tFirstByteMs = 0; + int tReplyBytes = 0; +#endif do { RetVal = recptBlock( tIOData->inp_buffer, &tIOData->inp_size ); if( RetVal == -1 ){ @@ -954,6 +988,12 @@ void deviceETH2UART::m_fThreadProc(void) m_bThreadStatus = TH_ENDED; LOG_ERROR("Connection Droped on Reception Data"); } else if( tIOData->inp_size ){ +#ifdef DEBUG_COMMUNICATION + if (tFirstByteMs == 0){ + tFirstByteMs = e2uNowMs(); + }; + tReplyBytes += tIOData->inp_size; +#endif uint64_t tGapEnd = e2uNowMs() + E2UART_REPLY_GAP_MS; if (tGapEnd > tDeadline){ tDeadline = tGapEnd; @@ -961,11 +1001,6 @@ void deviceETH2UART::m_fThreadProc(void) if( tParser == NULL ){ tDataOnline = true; } else { - #ifdef DEBUG_COMMUNICATION - char tB[128]; - sprintf( tB, "Read \t%d bytes for \t%p", tIOData->inp_size, tParser ); - LOG( tB ); - #endif tDataOnline = tParser->parse( tIOData->inp_buffer, tIOData->inp_size ) || tDataOnline; }; } else { @@ -975,12 +1010,29 @@ void deviceETH2UART::m_fThreadProc(void) SLEEP(5); }; } while ((m_bThreadStatus < TH_ENDED) && (e2uNowMs() < tDeadline)); - #ifdef DEBUG_COMMUNICATION - if (! tDataOnline){ - LOG_ERROR("PACK TIMEOUT!"); - }; - LOG("Finishing Read Package"); - #endif +#ifdef DEBUG_COMMUNICATION + { + uint64_t tDoneMs = e2uNowMs(); + if (tFirstByteMs == 0){ + tStNoReply++; + snprintf(tDbg, sizeof(tDbg), "IO: request #%u (%d B): NO reply in %llu ms", tReqNo, tSentBytes, (unsigned long long) (tDoneMs - tSendMs)); + LOG(tDbg); + } else { + uint64_t tFirst = tFirstByteMs - tSendMs; + tStReply++; + tStSum += tFirst; + if (tFirst > tStMax){ + tStMax = tFirst; + }; + if (tFirst > E2UART_SLOW_REPLY_MS || ! tDataOnline){ + tStSlow++; + snprintf(tDbg, sizeof(tDbg), "IO: request #%u (%d B): reply %d B, first byte %llu ms, done %llu ms%s", tReqNo, tSentBytes, tReplyBytes, + (unsigned long long) tFirst, (unsigned long long) (tDoneMs - tSendMs), tDataOnline ? "" : " - INCOMPLETE packet"); + LOG(tDbg); + }; + }; + } +#endif // Free Package free(tIOData); }; diff --git a/lib/App/common/deviceNodeSensor.cpp b/lib/App/common/deviceNodeSensor.cpp index fa8acb01..db235c28 100644 --- a/lib/App/common/deviceNodeSensor.cpp +++ b/lib/App/common/deviceNodeSensor.cpp @@ -3,6 +3,22 @@ #include "../../components/object/objectSystemAnchor.h" #include "kernelPrototype.h" +// Communication timing: slow replies, timeouts and a one-minute summary (see txTimingReport) +#define DEBUG_COMMUNICATION +#ifndef LGS_SLOW_REPLY_MS + #define LGS_SLOW_REPLY_MS 500 // replies slower than this are logged one by one +#endif +#define LGS_TIMING_REPORT_MS 60000 + +#include + +static uint64_t nsNowMs(void) +{ + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return (uint64_t) ts.tv_sec * 1000 + ts.tv_nsec / 1000000; +} + #define LOG(X) deviceNode::m_pLog->Log("NODSEN", this, X) #define LOG_ERROR(X) deviceNode::m_pLog->Log("NODSEN", this, _LOG_ERROR, X) @@ -143,8 +159,13 @@ void deviceNodeSensor::transactionResetResult(void) void deviceNodeSensor::transactionSetResult(bool ACK) { m_mPPModeProtector.lock(); - m_ePPMODE = (ACK) ? STG_POOL : STG_PUSH; + bool tWasWaiting = (m_ePPMODE == STG_WAIT); + m_ePPMODE = (ACK) ? STG_POOL : STG_PUSH; m_mPPModeProtector.unlock(); + if (tWasWaiting) + { + txTimingDone(ACK); + }; } void deviceNodeSensor::transactionWaitResult(void) @@ -152,6 +173,74 @@ void deviceNodeSensor::transactionWaitResult(void) m_mPPModeProtector.lock(); m_ePPMODE = STG_WAIT; m_mPPModeProtector.unlock(); + m_nTxStartMs = nsNowMs(); + if (m_nTxFirstMs == 0) + { + m_nTxFirstMs = m_nTxStartMs; // a retry keeps the time of the first attempt + }; +} + +/* + A reply ended the wait of the running request: reply time from the request, and from the first + attempt when the command needed retries. +*/ +void deviceNodeSensor::txTimingDone(bool ok) +{ + if (m_nTxStartMs == 0) + { + return; + }; + uint64_t tNow = nsNowMs(); + uint64_t tReply = tNow - m_nTxStartMs; + uint64_t tTotal = (m_nTxFirstMs != 0) ? tNow - m_nTxFirstMs : tReply; + m_nTxCount++; + m_nTxSumMs += tReply; + if (tReply > m_nTxMaxMs) + { + m_nTxMaxMs = tReply; + }; +#ifdef DEBUG_COMMUNICATION + if (tReply > LGS_SLOW_REPLY_MS || tTotal > tReply || ! ok) + { + m_nTxSlow++; + char tB[192]; + snprintf(tB, sizeof(tB), "COMM: %s WM 0x%02X STG 0x%02X reply %llu ms%s (wait %u ms per attempt)", ok ? "reply" : "NACK", (unsigned) getWM(), (unsigned) getStage(), + (unsigned long long) tReply, (tTotal > tReply) ? ", command needed retries" : "", (unsigned) m_nTOCounterBase * 100); + LOG(tB); + if (tTotal > tReply) + { + snprintf(tB, sizeof(tB), "COMM: command done %llu ms after its first attempt", (unsigned long long) tTotal); + LOG(tB); + }; + }; +#endif + m_nTxStartMs = 0; + m_nTxFirstMs = 0; + txTimingReport(false); +} + +void deviceNodeSensor::txTimingReport(bool force) +{ +#ifdef DEBUG_COMMUNICATION + uint64_t tNow = nsNowMs(); + if (! force && tNow - m_nTxStatStartMs < LGS_TIMING_REPORT_MS) + { + return; + }; + char tB[256]; + snprintf(tB, sizeof(tB), "COMM stats %llu s: %u replies, avg %llu ms, max %llu ms, %u slow (> %d ms) | %u attempts timed out (%u ms each), %u commands failed", + (unsigned long long) ((tNow - m_nTxStatStartMs) / 1000), m_nTxCount, (unsigned long long) (m_nTxCount ? m_nTxSumMs / m_nTxCount : 0), + (unsigned long long) m_nTxMaxMs, m_nTxSlow, LGS_SLOW_REPLY_MS, m_nTxAttemptTO, (unsigned) m_nTOCounterBase * 100, m_nTxFailed); + LOG(tB); + m_nTxCount = m_nTxSlow = m_nTxAttemptTO = m_nTxFailed = 0; + m_nTxSumMs = m_nTxMaxMs = 0; + m_nTxStatStartMs = tNow; +#else + if (force) + { + force = false; + }; +#endif } STAGE_PP_CONDITION deviceNodeSensor::getPPStatus() @@ -170,6 +259,10 @@ deviceNodeSensor::deviceNodeSensor(uint32_t id) : m_nCommErrorsCounter = 0; m_nTOCounterBase = LGS_DEFAULT_TO_COUNTER; + m_nTxStartMs = m_nTxFirstMs = 0; + m_nTxCount = m_nTxSlow = m_nTxAttemptTO = m_nTxFailed = 0; + m_nTxSumMs = m_nTxMaxMs = 0; + m_nTxStatStartMs = nsNowMs(); m_ePPMODE = STG_INIT; m_bValidationSkipCounter = DAFAULT_VALIDATION_SKIP_COUNTER; m_nCommErrorsStatTO = COMMUNICATION_ERROR_STATISTIC_HARVEST_INTERVAL_IN_SECONDS; @@ -254,6 +347,10 @@ deviceNodeSensor::deviceNodeSensor(DBC_NODE_DATA * Data) : { m_nCommErrorsCounter = 0; m_nTOCounterBase = LGS_DEFAULT_TO_COUNTER; + m_nTxStartMs = m_nTxFirstMs = 0; + m_nTxCount = m_nTxSlow = m_nTxAttemptTO = m_nTxFailed = 0; + m_nTxSumMs = m_nTxMaxMs = 0; + m_nTxStatStartMs = nsNowMs(); m_ePPMODE = STG_INIT; m_bValidationSkipCounter = DAFAULT_VALIDATION_SKIP_COUNTER; m_nCommErrorsStatTO = COMMUNICATION_ERROR_STATISTIC_HARVEST_INTERVAL_IN_SECONDS; @@ -1189,6 +1286,15 @@ void deviceNodeSensor::waitStateFunction(LRF_WORK_STAGE boboStage) { #ifdef DEBUG_EXTRA LOG("ATTEMPT RECOVER"); +#endif + m_nTxAttemptTO++; +#ifdef DEBUG_COMMUNICATION + { + char tB[160]; + snprintf(tB, sizeof(tB), "COMM: no reply - WM 0x%02X STG 0x%02X attempt %d/%d timed out after %llu ms", (unsigned) getWM(), (unsigned) getStage(), + LGS_CMD_RETRY_COUNT - m_bOpRetryCnt + 1, LGS_CMD_RETRY_COUNT + 1, (unsigned long long) (m_nTxStartMs ? nsNowMs() - m_nTxStartMs : 0)); + LOG(tB); + } #endif m_bOpRetryCnt--; m_bTimeOutCounter = m_nTOCounterBase; @@ -1225,6 +1331,18 @@ void deviceNodeSensor::waitStateFunction(LRF_WORK_STAGE boboStage) else { LOG_ERROR("Communication Wait State TO!"); + m_nTxFailed++; +#ifdef DEBUG_COMMUNICATION + { + char tB[192]; + snprintf(tB, sizeof(tB), "COMM: command failed - WM 0x%02X STG 0x%02X, %d attempts of %u ms, %llu ms since the first attempt", (unsigned) getWM(), (unsigned) getStage(), + LGS_CMD_RETRY_COUNT + 1, (unsigned) m_nTOCounterBase * 100, (unsigned long long) (m_nTxFirstMs ? nsNowMs() - m_nTxFirstMs : 0)); + LOG(tB); + } + txTimingReport(true); +#endif + m_nTxStartMs = 0; + m_nTxFirstMs = 0; registerCommError(true); // setStage( boboStage ); setWM(LRF_WM_CONNECTION); @@ -1249,6 +1367,8 @@ bool deviceNodeSensor::initWModeFunction(uint8_t wm) setWM(wm); setStage(LRF_WS_INIT); transactionResetResult(); + m_nTxStartMs = 0; // a new work mode: no command running + m_nTxFirstMs = 0; m_bOpRetryCnt = LGS_CMD_RETRY_COUNT; return true; }; diff --git a/lib/App/common/deviceNodeSensor.h b/lib/App/common/deviceNodeSensor.h index 0dca9599..4f96ef47 100644 --- a/lib/App/common/deviceNodeSensor.h +++ b/lib/App/common/deviceNodeSensor.h @@ -182,6 +182,13 @@ class deviceNodeSensor : public deviceNode, public basicThread uint8_t m_bOpRetryCnt; uint16_t m_bTimeOutCounter; uint16_t m_nTOCounterBase; // wait per attempt (x 100 ms): LGS_DEFAULT_TO_COUNTER or LGS_NETWORK_TO_COUNTER + // Communication timing (logged with DEBUG_COMMUNICATION in deviceNodeSensor.cpp; always present: class layout) + uint64_t m_nTxStartMs; // transactionWaitResult() of the running request + uint64_t m_nTxFirstMs; // first attempt of the running command (retries included) + uint32_t m_nTxCount, m_nTxSlow, m_nTxAttemptTO, m_nTxFailed; + uint64_t m_nTxSumMs, m_nTxMaxMs, m_nTxStatStartMs; + void txTimingDone(bool ok); + void txTimingReport(bool force); E_MODES m_bActualDeviceWM; E_MODES m_bRequestedDeviceWM; uint32_t m_nChannelTO; From 617e38583d39094f222e580f861b691ff1c52890 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 09:09:01 +0000 Subject: [PATCH 5/7] Ethernet2UART gateway: reconnect when the device goes silent on a live connection 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 Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16 --- lib/App/common/deviceNodeEthernet2Serial.cpp | 51 +++++++++++++++++++- lib/App/common/deviceNodeEthernet2Serial.h | 11 +++++ 2 files changed, 61 insertions(+), 1 deletion(-) diff --git a/lib/App/common/deviceNodeEthernet2Serial.cpp b/lib/App/common/deviceNodeEthernet2Serial.cpp index f1653d55..e4c941f9 100644 --- a/lib/App/common/deviceNodeEthernet2Serial.cpp +++ b/lib/App/common/deviceNodeEthernet2Serial.cpp @@ -585,6 +585,8 @@ bool deviceETH2UART::create_SOL() setsockopt(m_iDeviceFD, IPPROTO_TCP, TCP_KEEPIDLE, &tIdle, sizeof(tIdle)); setsockopt(m_iDeviceFD, IPPROTO_TCP, TCP_KEEPINTVL, &tIntvl, sizeof(tIntvl)); setsockopt(m_iDeviceFD, IPPROTO_TCP, TCP_KEEPCNT, &tCnt, sizeof(tCnt)); + unsigned int tUserTO = E2UART_TCP_USER_TIMEOUT_MS; + setsockopt(m_iDeviceFD, IPPROTO_TCP, TCP_USER_TIMEOUT, &tUserTO, sizeof(tUserTO)); } // assign IP, PORT @@ -808,6 +810,16 @@ bool deviceETH2UART::closePort() { uninit(); }; +#ifdef SERIAL_PING_PONG + // Requests not sent on the closed connection: drop them (the protocols re-send after a reconnect) + m_mBufferProtectorMutex.lock(); + while (! m_qIO.empty()) + { + free(m_qIO.front()); + m_qIO.pop(); + }; + m_mBufferProtectorMutex.unlock(); +#endif if (m_iDeviceFD != -1) { switch (m_sUartData.mode) @@ -873,6 +885,24 @@ bool deviceETH2UART::isRecipient(protocolParser * p) return tVal; } +/* + Which side is silent: unacked > 0 and a growing "last ACK" -> the network path to the gateway is dead; + ACKs keep coming but no reply -> the gateway / serial line / device does not answer. +*/ +void deviceETH2UART::tcpInfoText(char * buf, size_t size) +{ + struct tcp_info tInfo; + socklen_t tLen = sizeof(tInfo); + memset(&tInfo, 0, sizeof(tInfo)); + if (m_iDeviceFD < 0 || m_sUartData.mode != SOL_TCP_SERVER || getsockopt(m_iDeviceFD, IPPROTO_TCP, TCP_INFO, &tInfo, &tLen) != 0) + { + snprintf(buf, size, "no TCP info"); + return; + }; + snprintf(buf, size, "TCP: unacked %u, retransmits %u, rtt %u ms, last ACK %u ms ago, last data %u ms ago", tInfo.tcpi_unacked, tInfo.tcpi_retransmits, + tInfo.tcpi_rtt / 1000, tInfo.tcpi_last_ack_recv, tInfo.tcpi_last_data_recv); +} + void deviceETH2UART::m_fThreadProc(void) { int RetVal; @@ -882,6 +912,7 @@ void deviceETH2UART::m_fThreadProc(void) #endif pthread_setname_np( pthread_self(), "E2S IO" ); SIO_TZ * tIdle = (SIO_TZ *) malloc(sizeof(SIO_TZ)); // receive buffer for data between requests + int tNoReplyStreak = 0; // requests in a row (with a parser) without any reply byte #ifdef DEBUG_COMMUNICATION uint32_t tReqNo = 0, tStReq = 0, tStReply = 0, tStNoReply = 0, tStSlow = 0, tStLate = 0; uint64_t tStSum = 0, tStMax = 0, tStStart = e2uNowMs(), tLastReqMs = 0; @@ -919,6 +950,7 @@ void deviceETH2UART::m_fThreadProc(void) m_bThreadStatus = TH_ENDED; LOG_ERROR("Connection Droped on Reception Data"); } else if (tIdle->inp_size > 0){ + tNoReplyStreak = 0; // the device answers (late) #ifdef DEBUG_COMMUNICATION tStLate++; snprintf(tDbg, sizeof(tDbg), "IO: late data %d B, %llu ms after request #%u (reply window %d ms)", tIdle->inp_size, @@ -974,6 +1006,7 @@ void deviceETH2UART::m_fThreadProc(void) //coming (E2UART_REPLY_GAP_MS between chunks); done when the parser has a complete packet and //no more data is waiting tIOData->out_size = 0; + bool tGotData = false; bool tDataOnline = false; uint64_t tDeadline = e2uNowMs() + E2UART_REPLY_TIMEOUT_MS; #ifdef DEBUG_COMMUNICATION @@ -988,6 +1021,7 @@ void deviceETH2UART::m_fThreadProc(void) m_bThreadStatus = TH_ENDED; LOG_ERROR("Connection Droped on Reception Data"); } else if( tIOData->inp_size ){ + tGotData = true; #ifdef DEBUG_COMMUNICATION if (tFirstByteMs == 0){ tFirstByteMs = e2uNowMs(); @@ -1015,7 +1049,9 @@ void deviceETH2UART::m_fThreadProc(void) uint64_t tDoneMs = e2uNowMs(); if (tFirstByteMs == 0){ tStNoReply++; - snprintf(tDbg, sizeof(tDbg), "IO: request #%u (%d B): NO reply in %llu ms", tReqNo, tSentBytes, (unsigned long long) (tDoneMs - tSendMs)); + char tTcp[160]; + tcpInfoText(tTcp, sizeof(tTcp)); + snprintf(tDbg, sizeof(tDbg), "IO: request #%u (%d B): NO reply in %llu ms - %s", tReqNo, tSentBytes, (unsigned long long) (tDoneMs - tSendMs), tTcp); LOG(tDbg); } else { uint64_t tFirst = tFirstByteMs - tSendMs; @@ -1033,6 +1069,19 @@ void deviceETH2UART::m_fThreadProc(void) }; } #endif + if (tGotData){ + tNoReplyStreak = 0; + } else if (tParser != NULL && m_bThreadStatus < TH_ENDED && ++tNoReplyStreak >= E2UART_NO_REPLY_RECONNECT){ + // The device went silent while the TCP connection stayed "up" (sending works, nothing comes + // back): end the I/O thread - validate() sees the lost link and opens a new connection + char tTcp[160]; + char tB[320]; + tcpInfoText(tTcp, sizeof(tTcp)); + snprintf(tB, sizeof(tB), "No reply to %d requests in a row - reconnecting to the gateway (%s)", tNoReplyStreak, tTcp); + LOG_ERROR(tB); + setConnectionStatus(CS_DISCONNECTED); + m_bThreadStatus = TH_ENDED; + }; // Free Package free(tIOData); }; diff --git a/lib/App/common/deviceNodeEthernet2Serial.h b/lib/App/common/deviceNodeEthernet2Serial.h index 32076378..90daaacf 100644 --- a/lib/App/common/deviceNodeEthernet2Serial.h +++ b/lib/App/common/deviceNodeEthernet2Serial.h @@ -37,6 +37,16 @@ #define E2UART_KEEPALIVE_IDLE_S 20 #define E2UART_KEEPALIVE_INTVL_S 5 #define E2UART_KEEPALIVE_CNT 4 +// Sent data not acknowledged by the gateway for this long: the kernel drops the connection (a dead +// mobile / NAT path otherwise looks alive for many minutes - keepalive only probes idle connections) +#ifndef E2UART_TCP_USER_TIMEOUT_MS + #define E2UART_TCP_USER_TIMEOUT_MS 10000 +#endif +// Requests in a row without any reply byte: reconnect to the gateway (the device went silent while +// the TCP connection stayed up - a new connection resets the gateway session / NAT mapping) +#ifndef E2UART_NO_REPLY_RECONNECT + #define E2UART_NO_REPLY_RECONNECT 5 +#endif #ifdef SERIAL_PING_PONG class deviceETH2UART : public deviceNode, public hardwareResource, public basicTransport, public basicThread #else @@ -81,6 +91,7 @@ Q_SIO_TZ m_qIO; protocolParser * m_pLastParser; // parser of the last request: gets data that arrives between requests bool isRecipient(protocolParser * p); // still bound to this transport (not deleted / detached) + void tcpInfoText(char * buf, size_t size); // unacked data / retransmits / last ACK of the connection #else U8 m_pInputBuffer[MAXIMAL_SOCKET_IO_BUFFER_LENGTH]; U8 m_pOutputBuffer[MAXIMAL_SOCKET_IO_BUFFER_LENGTH]; From 15c4b9b6a38a2d1d90cf93395afb1b53e8e074d6 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 09:11:49 +0000 Subject: [PATCH 6/7] Ethernet2UART gateway: never lose a sensor query around a reconnect 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 Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16 --- lib/App/common/deviceNodeEthernet2Serial.cpp | 71 +++++++++++++++----- lib/App/common/deviceNodeEthernet2Serial.h | 6 ++ 2 files changed, 60 insertions(+), 17 deletions(-) diff --git a/lib/App/common/deviceNodeEthernet2Serial.cpp b/lib/App/common/deviceNodeEthernet2Serial.cpp index e4c941f9..366ffc4f 100644 --- a/lib/App/common/deviceNodeEthernet2Serial.cpp +++ b/lib/App/common/deviceNodeEthernet2Serial.cpp @@ -52,6 +52,7 @@ deviceETH2UART::deviceETH2UART(uint32_t nodeID) : m_iInFID = -1; m_iOutFID = -1; m_bRegistered = false; + m_bConnecting = false; #ifdef SERIAL_PING_PONG m_pLastParser = NULL; #endif @@ -87,6 +88,15 @@ deviceETH2UART::~deviceETH2UART() } std::lock_guard tLock(m_mConnLock); closePort(); +#ifdef SERIAL_PING_PONG + m_mBufferProtectorMutex.lock(); + while (! m_qIO.empty()) + { + free(m_qIO.front()); + m_qIO.pop(); + }; + m_mBufferProtectorMutex.unlock(); +#endif } bool deviceETH2UART::create(void) @@ -181,6 +191,16 @@ bool deviceETH2UART::connectSOL(void) m_bLastPingOk = true; return true; }; +#ifdef SERIAL_PING_PONG + // No connection: the queued requests are stale by the next attempt (the protocols query again) + m_mBufferProtectorMutex.lock(); + while (! m_qIO.empty()) + { + free(m_qIO.front()); + m_qIO.pop(); + }; + m_mBufferProtectorMutex.unlock(); +#endif m_nConnectBackoffMs = (m_nConnectBackoffMs == 0) ? E2UART_RECONNECT_MIN_MS : m_nConnectBackoffMs * 2; if (m_nConnectBackoffMs > E2UART_RECONNECT_MAX_MS) { @@ -428,6 +448,12 @@ bool deviceETH2UART::create_SOL() { closePort(); }; + struct connectingFlag + { + volatile bool & f; + explicit connectingFlag(volatile bool & x) : f(x) { f = true; } + ~connectingFlag() { f = false; } + } tConnecting(m_bConnecting); switch (m_sUartData.mode) { @@ -810,16 +836,8 @@ bool deviceETH2UART::closePort() { uninit(); }; -#ifdef SERIAL_PING_PONG - // Requests not sent on the closed connection: drop them (the protocols re-send after a reconnect) - m_mBufferProtectorMutex.lock(); - while (! m_qIO.empty()) - { - free(m_qIO.front()); - m_qIO.pop(); - }; - m_mBufferProtectorMutex.unlock(); -#endif + // Requests still queued are kept: a query of the sensor queued during a reconnect is sent on the new + // connection (dropping it left the sensor without a query - it only answers when asked) if (m_iDeviceFD != -1) { switch (m_sUartData.mode) @@ -975,6 +993,17 @@ void deviceETH2UART::m_fThreadProc(void) //Sending Data to line #ifdef DEBUG_COMMUNICATION int tSentBytes = tIOData->out_size; + char tReqHex[3 * 12 + 4]; + { + int tN = (tSentBytes < 12) ? tSentBytes : 12; + for (int k = 0; k < tN; k++){ + snprintf(tReqHex + 3 * k, 4, "%02X ", tIOData->out_buffer[k]); + }; + tReqHex[tN ? 3 * tN - 1 : 0] = 0; + if (tSentBytes > 12){ + strcat(tReqHex, ".."); + }; + } uint64_t tSendMs = e2uNowMs(); tReqNo++; tStReq++; @@ -1051,7 +1080,7 @@ void deviceETH2UART::m_fThreadProc(void) tStNoReply++; char tTcp[160]; tcpInfoText(tTcp, sizeof(tTcp)); - snprintf(tDbg, sizeof(tDbg), "IO: request #%u (%d B): NO reply in %llu ms - %s", tReqNo, tSentBytes, (unsigned long long) (tDoneMs - tSendMs), tTcp); + snprintf(tDbg, sizeof(tDbg), "IO: request #%u [%s]: NO reply in %llu ms - %s", tReqNo, tReqHex, (unsigned long long) (tDoneMs - tSendMs), tTcp); LOG(tDbg); } else { uint64_t tFirst = tFirstByteMs - tSendMs; @@ -1089,12 +1118,11 @@ void deviceETH2UART::m_fThreadProc(void) } bool deviceETH2UART::sendData(uint8_t * Data, int DataSize, protocolParser *src ){ - if ( m_bThreadStatus != TH_WORKING ) { - if( m_bThreadStatus < TH_WORKING ) { - LOG_ERROR("Trying to Send Data Before Thread is Started!"); - } else { - LOG_ERROR("Trying to Send Data After Thread is Dead!"); - } + // Queued (sent as soon as the I/O thread runs) while the connection is up, starting (TH_ARMED: the + // first query right after a connect was refused), ended for a reconnect that validate() will do, + // or being opened. Refused only without any connection. + if ( m_bThreadStatus == TH_PRE_INIT && ! m_bConnecting ) { + LOG_ERROR("Trying to Send Data without connection to the gateway!"); return false; }; if (DataSize > MAXIMAL_SERIAL_IO_BUFFER_LENGTH) { @@ -1106,9 +1134,18 @@ bool deviceETH2UART::sendData(uint8_t * Data, int DataSize, protocolParser *src tData->out_size = DataSize; tData->boundParser = src; memcpy( tData->out_buffer, Data, DataSize ); + int tDropped = 0; m_mBufferProtectorMutex.lock(); + while ((int) m_qIO.size() >= E2UART_MAX_QUEUED){ + free(m_qIO.front()); + m_qIO.pop(); + tDropped++; + }; m_qIO.push(tData); m_mBufferProtectorMutex.unlock(); + if (tDropped){ + LOG_ERROR("Request queue full - oldest request dropped"); + }; return true; } else { LOG_ERROR("MemAlloc Error!"); diff --git a/lib/App/common/deviceNodeEthernet2Serial.h b/lib/App/common/deviceNodeEthernet2Serial.h index 90daaacf..5c904a02 100644 --- a/lib/App/common/deviceNodeEthernet2Serial.h +++ b/lib/App/common/deviceNodeEthernet2Serial.h @@ -44,6 +44,11 @@ #endif // Requests in a row without any reply byte: reconnect to the gateway (the device went silent while // the TCP connection stayed up - a new connection resets the gateway session / NAT mapping) +// Requests waiting for the I/O thread (e.g. queries of the sensor during a reconnect): the oldest are +// dropped beyond this (a long outage must not grow the queue without limit) +#ifndef E2UART_MAX_QUEUED + #define E2UART_MAX_QUEUED 16 +#endif #ifndef E2UART_NO_REPLY_RECONNECT #define E2UART_NO_REPLY_RECONNECT 5 #endif @@ -71,6 +76,7 @@ // hardware manager thread (the class is a deviceNode and a hardwareResource): one at a time std::recursive_mutex m_mConnLock; bool m_bRegistered; // assigned to the hardware manager (once) + volatile bool m_bConnecting; // create_SOL() is opening the connection (requests are queued meanwhile) bool m_bLastPingOk; uint64_t m_nNextPingMs; uint64_t m_nNextConnectMs; From 6078ca9659f20eae0127a8858a5812712deac339 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 09:41:25 +0000 Subject: [PATCH 7/7] Turn off the communication timing logs (DEBUG_COMMUNICATION) 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 Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16 --- lib/App/common/deviceNodeEthernet2Serial.cpp | 2 +- lib/App/common/deviceNodeSensor.cpp | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/lib/App/common/deviceNodeEthernet2Serial.cpp b/lib/App/common/deviceNodeEthernet2Serial.cpp index 366ffc4f..4ae0efed 100644 --- a/lib/App/common/deviceNodeEthernet2Serial.cpp +++ b/lib/App/common/deviceNodeEthernet2Serial.cpp @@ -11,7 +11,7 @@ // #define DEBUG_EXTRA // #define DEBUG_SERIAL_COMMUNICATION // Request / reply timing of the I/O thread: no reply, slow and late replies, one-minute summary -#define DEBUG_COMMUNICATION +// #define DEBUG_COMMUNICATION // timing logs (see the commit "Debug: log communication timing ...") #ifndef E2UART_SLOW_REPLY_MS #define E2UART_SLOW_REPLY_MS 500 #endif diff --git a/lib/App/common/deviceNodeSensor.cpp b/lib/App/common/deviceNodeSensor.cpp index db235c28..a59338b0 100644 --- a/lib/App/common/deviceNodeSensor.cpp +++ b/lib/App/common/deviceNodeSensor.cpp @@ -4,7 +4,7 @@ #include "kernelPrototype.h" // Communication timing: slow replies, timeouts and a one-minute summary (see txTimingReport) -#define DEBUG_COMMUNICATION +// #define DEBUG_COMMUNICATION // timing logs (see the commit "Debug: log communication timing ...") #ifndef LGS_SLOW_REPLY_MS #define LGS_SLOW_REPLY_MS 500 // replies slower than this are logged one by one #endif @@ -213,6 +213,9 @@ void deviceNodeSensor::txTimingDone(bool ok) LOG(tB); }; }; +#else + (void) ok; + (void) tTotal; #endif m_nTxStartMs = 0; m_nTxFirstMs = 0;