Add runtime RS232 bridge diagnostics and wired link probes

This commit is contained in:
mikecarper committed 2026-10-22 11:51:56 -07:00
1 parent e7b863494c
commit 281f1a5199
22 files changed
+1468 -24

No files matched your search

+1 -1
View File
@@ -35,7 +35,7 @@
((defined(MESH_DEBUG) && MESH_DEBUG) || \
(defined(BRIDGE_DEBUG) && BRIDGE_DEBUG) || \
(defined(POWERSAVING_DEBUG) && POWERSAVING_DEBUG) || \
defined(WITH_ESPNOW_BRIDGE))
defined(WITH_ESPNOW_BRIDGE) || defined(WITH_RS232_BRIDGE))
#include <Arduino.h>
#include <atomic>
#include <stdarg.h>
+74
View File
@@ -3051,6 +3051,77 @@ uint8_t CommonCLI::buildAdvertData(uint8_t node_type, uint8_t* app_data) {
}
}
#if defined(WITH_RS232_BRIDGE)
bool CommonCLI::handleRs232DiagnosticCommand(uint32_t sender_timestamp,
const char* command, char* reply) {
constexpr size_t capacity = 157; // Leave room for an infrastructure reply prefix.
if (strncmp(command, "get rs232.transport", 19) == 0) {
if (strcmp(command, "get rs232.transport") != 0) {
snprintf(reply, capacity, "Error: use get rs232.transport");
} else {
_callbacks->formatRs232Transport(reply, capacity);
}
return true;
}
if (strncmp(command, "get rs232.stats", 15) == 0) {
const char* page = command + 15;
if (*page == 0) {
_callbacks->formatRs232Stats("", reply, capacity);
} else if (strcmp(page, " rx") == 0 || strcmp(page, " tx") == 0
|| strcmp(page, " drops") == 0 || strcmp(page, " test") == 0) {
_callbacks->formatRs232Stats(page + 1, reply, capacity);
} else {
snprintf(reply, capacity, "Error: use get rs232.stats [rx|tx|drops|test]");
}
return true;
}
if (strncmp(command, "rs232", 5) != 0
|| (command[5] != 0 && command[5] != ' ')) return false;
if (sender_timestamp != 0) {
snprintf(reply, capacity, "Error: RS232 test/reset requires a local connection");
return true;
}
if (strcmp(command, "rs232 resetstats") == 0) {
snprintf(reply, capacity, "%s", _callbacks->resetRs232Stats()
? "OK - RS232 statistics reset" : "Error: RS232 diagnostics unavailable");
return true;
}
uint32_t nonce = 0;
if (strcmp(command, "rs232 test") == 0) {
nonce = millis(); // Correlation only; this is not a security token.
} else {
if (strncmp(command, "rs232 test ", 11) != 0) {
snprintf(reply, capacity, "Error: use rs232 test [8 hex digits] or rs232 resetstats");
return true;
}
const char* value = command + 11;
if (strlen(value) != 8) {
snprintf(reply, capacity, "Error: use rs232 test [8 hex digits] or rs232 resetstats");
return true;
}
for (size_t i = 0; i < 8; ++i) {
const char c = value[i];
uint8_t digit;
if (c >= '0' && c <= '9') digit = static_cast<uint8_t>(c - '0');
else if (c >= 'a' && c <= 'f') digit = static_cast<uint8_t>(c - 'a' + 10);
else if (c >= 'A' && c <= 'F') digit = static_cast<uint8_t>(c - 'A' + 10);
else {
snprintf(reply, capacity, "Error: use rs232 test [8 hex digits] or rs232 resetstats");
return true;
}
nonce = (nonce << 4) | digit;
}
}
if (_callbacks->sendRs232Test(nonce)) {
snprintf(reply, capacity, "OK - test queued id=%08lX; confirm on peer",
static_cast<unsigned long>(nonce));
} else {
snprintf(reply, capacity, "Error: RS232 test not queued; check status/stats");
}
return true;
}
#endif
#if defined(WITH_ESPNOW_BRIDGE)
bool CommonCLI::handleEspNowDiagnosticCommand(uint32_t sender_timestamp,
const char* command, char* reply) {
@@ -3107,6 +3178,9 @@ bool CommonCLI::handleEspNowDiagnosticCommand(uint32_t sender_timestamp,
void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* reply) {
PrefsSaveReplyGuard save_reply(_prefs_save_failures, reply);
mesh::cli::normalizeCommandVerb(command);
#if defined(WITH_RS232_BRIDGE)
if (handleRs232DiagnosticCommand(sender_timestamp, command, reply)) return;
#endif
#if defined(WITH_ESPNOW_BRIDGE)
if (handleEspNowDiagnosticCommand(sender_timestamp, command, reply)) return;
#endif
+14
View File
@@ -646,6 +646,17 @@ public:
virtual bool isEspNowBridgeRunning() { return isBridgeRunning(); }
virtual bool isRs232BridgeRunning() const { return isBridgeRunning(); }
virtual void formatRs232Status(char* reply) { strcpy(reply, "RS232 unavailable"); }
#if defined(WITH_RS232_BRIDGE)
virtual void formatRs232Transport(char* reply, size_t capacity) {
snprintf(reply, capacity, "Error: RS232 diagnostics unavailable");
}
virtual void formatRs232Stats(const char* page, char* reply, size_t capacity) {
(void)page;
snprintf(reply, capacity, "Error: RS232 diagnostics unavailable");
}
virtual bool sendRs232Test(uint32_t nonce) { (void)nonce; return false; }
virtual bool resetRs232Stats() { return false; }
#endif
#if defined(WITH_ESPNOW_BRIDGE)
virtual void formatEspNowStatus(char* reply, size_t capacity) {
snprintf(reply, capacity, "Error: ESP-NOW diagnostics unavailable");
@@ -908,6 +919,9 @@ class CommonCLI {
void handleRegionCmd(char* command, char* reply);
void handleGetCmd(uint32_t sender_timestamp, char* command, char* reply);
void handleSetCmd(uint32_t sender_timestamp, char* command, char* reply);
#if defined(WITH_RS232_BRIDGE)
bool handleRs232DiagnosticCommand(uint32_t sender_timestamp, const char* command, char* reply);
#endif
#if defined(WITH_ESPNOW_BRIDGE)
bool handleEspNowDiagnosticCommand(uint32_t sender_timestamp, const char* command, char* reply);
#endif
+4 -4
View File
@@ -36,7 +36,7 @@ void BridgeBase::handleReceivedPacket(mesh::Packet *packet) {
if (_initialized == false) {
BRIDGE_DEBUG_PRINTLN("RX packet received before initialization\n");
_mgr->free(packet);
#if defined(WITH_ESPNOW_BRIDGE)
#if defined(WITH_ESPNOW_BRIDGE) || defined(WITH_RS232_BRIDGE)
onIngressResult(IngressResult::Stopped);
#endif
return;
@@ -44,7 +44,7 @@ void BridgeBase::handleReceivedPacket(mesh::Packet *packet) {
if (!preparePacketIngress(packet) || !allowsPacket(packet)) {
_mgr->free(packet);
#if defined(WITH_ESPNOW_BRIDGE)
#if defined(WITH_ESPNOW_BRIDGE) || defined(WITH_RS232_BRIDGE)
onIngressResult(IngressResult::Filtered);
#endif
return;
@@ -58,12 +58,12 @@ void BridgeBase::handleReceivedPacket(mesh::Packet *packet) {
if (!ota) _seen_packets.markSeen(packet);
// bridge_delay provides a buffer to prevent immediate processing conflicts in the mesh network.
_mgr->queueInbound(packet, millis() + _prefs->bridge_delay);
#if defined(WITH_ESPNOW_BRIDGE)
#if defined(WITH_ESPNOW_BRIDGE) || defined(WITH_RS232_BRIDGE)
onIngressResult(IngressResult::Queued);
#endif
} else {
_mgr->free(packet);
#if defined(WITH_ESPNOW_BRIDGE)
#if defined(WITH_ESPNOW_BRIDGE) || defined(WITH_RS232_BRIDGE)
onIngressResult(IngressResult::Duplicate);
#endif
}
+1 -1
View File
@@ -50,7 +50,7 @@ public:
static constexpr uint16_t BRIDGE_CHECKSUM_SIZE = sizeof(uint16_t);
protected:
#if defined(WITH_ESPNOW_BRIDGE)
#if defined(WITH_ESPNOW_BRIDGE) || defined(WITH_RS232_BRIDGE)
// Observe the existing admission decision without evaluating filters twice.
enum class IngressResult : uint8_t { Stopped, Filtered, Duplicate, Queued };
virtual void onIngressResult(IngressResult) {}
+221 -9
View File
@@ -23,12 +23,18 @@ RS232Bridge::RS232Bridge(NodePrefs *prefs, Stream &serial, int16_t rx_pin,
: BridgeBase(prefs, mgr, rtc), _serial(&serial), _rx_pin(rx_pin),
_tx_pin(tx_pin) {}
namespace rsdiag = mesh::bridge::rs232diag;
void RS232Bridge::begin() {
_initialized = false;
resetTransportState();
BRIDGE_DEBUG_PRINTLN("Initializing at %d baud...\n", _prefs->bridge_baud);
#if defined(ESP32)
if (!((HardwareSerial *)_serial)->setPins(_rx_pin, _tx_pin)) return;
if (!((HardwareSerial *)_serial)->setPins(_rx_pin, _tx_pin)) {
_stats.error = rsdiag::Error::Pins;
_debug_dirty = true;
return;
}
#elif defined(NRF52_PLATFORM)
// Tested with RAK_4631 and T114
// The Adafruit Uart object may already be active on its variant defaults.
@@ -52,6 +58,8 @@ void RS232Bridge::begin() {
#else
_initialized = true;
#endif
if (!_initialized) _stats.error = rsdiag::Error::Driver;
_debug_dirty = true;
}
void RS232Bridge::end() {
@@ -61,14 +69,23 @@ void RS232Bridge::end() {
// Update bridge state
_initialized = false;
resetTransportState();
_debug_dirty = true;
}
void RS232Bridge::resetTransportState() {
_rx_buffer_pos = 0;
_rx_packet_ready = false;
_rx_pool_blocked = false;
// Stop/reconfiguration discards pending transport work. As with mesh data,
// an accepted prefix cannot be classified as peer delivery or non-delivery.
if (_tx_is_probe && !_probe_timed_out && _tx_size != 0)
rsdiag::increment(_stats.probe.failed);
_tx_size = _tx_pos = 0;
_tx_wire_pending = false;
_tx_is_ping = false;
_tx_is_probe = false;
_probe_timed_out = false;
_tx_is_data = false;
_tx_ping_challenge = 0;
_outstanding_challenge = 0;
_pong_target = 0;
@@ -120,6 +137,8 @@ void RS232Bridge::expirePartialReceive(uint32_t now) {
if (_rx_buffer_pos != 0 && !_rx_packet_ready
&& static_cast<uint32_t>(now - _rx_started) >= frameAssemblyMs()) {
_rx_buffer_pos = 0;
rsdiag::increment(_stats.rx.timeout);
_debug_dirty = true;
}
}
@@ -195,16 +214,26 @@ void RS232Bridge::formatHeartbeatStatus(char* out, size_t capacity, uint32_t now
}
void RS232Bridge::drainTransmit(uint32_t now, bool blocking) {
expireProbeTransmit(now);
if (!_initialized || _tx_size == 0) return;
size_t amount = static_cast<size_t>(_tx_size - _tx_pos);
if (!blocking) {
const int available = _serial->availableForWrite();
if (available <= 0) return;
if (available <= 0) {
rsdiag::increment(_stats.tx.stalls); _debug_dirty = true;
return;
}
if (amount > static_cast<size_t>(available)) amount = static_cast<size_t>(available);
}
size_t sent = _serial->write(_tx_buffer + _tx_pos, amount);
if (sent > amount) sent = amount;
if (sent == 0) return;
if (sent == 0) {
rsdiag::increment(_stats.tx.stalls); _debug_dirty = true;
return;
}
if (sent < amount) rsdiag::increment(_stats.tx.short_writes);
rsdiag::add(_stats.tx.bytes, sent);
_debug_dirty = true;
_tx_pos = static_cast<uint16_t>(_tx_pos + sent);
const uint32_t baud = _prefs->bridge_baud ? _prefs->bridge_baud : 115200;
uint32_t base = now;
@@ -214,12 +243,16 @@ void RS232Bridge::drainTransmit(uint32_t now, bool blocking) {
_tx_wire_until = base + static_cast<uint32_t>((sent * 10000UL + baud - 1) / baud) + 1;
_tx_wire_pending = true;
if (_tx_pos == _tx_size) {
if (_tx_is_probe) rsdiag::increment(_stats.probe.sent);
if (_tx_is_data) rsdiag::increment(_stats.tx.sent);
if (_tx_is_ping) {
_outstanding_challenge = _tx_ping_challenge;
_outstanding_since = now;
}
_tx_size = _tx_pos = 0;
_tx_is_ping = false;
_tx_is_probe = false;
_tx_is_data = false;
}
}
@@ -236,6 +269,8 @@ bool RS232Bridge::queueControl(char opcode, uint64_t target, uint32_t challenge)
_tx_size = mesh::bridge::rs232heartbeat::FRAME_SIZE;
_tx_pos = 0;
_tx_is_ping = opcode == 'P';
_tx_is_probe = false;
_tx_is_data = false;
_tx_ping_challenge = challenge;
return true;
}
@@ -261,6 +296,17 @@ void RS232Bridge::serviceHeartbeat(uint32_t now) {
}
void RS232Bridge::handleControl(uint32_t now) {
if (rsdiag::isProbeCandidate(_rx_buffer + 4)) {
uint32_t nonce;
if (rsdiag::decodeProbe(_rx_buffer + 4, rsdiag::BodySize, nonce)) {
rsdiag::increment(_stats.probe.received);
_stats.probe.last_rx_nonce = nonce;
} else rsdiag::increment(_stats.probe.bad);
_debug_dirty = true;
// Deliberately do not alter heartbeat, peer timestamps, power policy,
// PacketManager or duplicate tables. A probe is never echoed or forwarded.
return;
}
mesh::bridge::rs232heartbeat::Control control;
if (_session == 0 || !mesh::bridge::rs232heartbeat::decode(_rx_buffer + 4, control)
|| control.sender == _session) return;
@@ -286,17 +332,25 @@ void RS232Bridge::handleControl(uint32_t now) {
void RS232Bridge::drainReceivedPackets() {
if (!_rx_packet_ready) return;
mesh::Packet* pkt = _mgr->allocNew();
if (!pkt) return;
if (!pkt) {
if (!_rx_pool_blocked) {
rsdiag::increment(_stats.rx.pool_wait); _debug_dirty = true;
}
_rx_pool_blocked = true;
return;
}
const uint16_t len = (_rx_buffer[2] << 8) | _rx_buffer[3];
const bool valid = pkt->readFrom(_rx_buffer + 4, len);
_rx_buffer_pos = 0;
_rx_packet_ready = false;
_rx_pool_blocked = false;
if (valid) {
// A cable loopback or replay of our own accepted mesh TX is not peer proof.
// OTA must still reach the mesh's timed retry/echo policy, but it cannot
// refresh UART peer liveness merely by reflecting our own transmission.
const bool seen = _seen_packets.wasSeen(pkt);
if (pkt->getPayloadType() != PAYLOAD_TYPE_OTA && seen) {
rsdiag::increment(_stats.rx.duplicate); _debug_dirty = true;
_mgr->free(pkt);
return;
}
@@ -321,12 +375,16 @@ void RS232Bridge::drainReceivedPackets() {
}
onPacketReceived(pkt);
}
else _mgr->free(pkt);
else {
rsdiag::increment(_stats.rx.packet_bad); _debug_dirty = true;
_mgr->free(pkt);
}
}
void RS232Bridge::loop() {
// Guard against uninitialized state
if (_initialized == false) {
emitDebug();
return;
}
@@ -347,6 +405,7 @@ void RS232Bridge::loop() {
const int value = _serial->read();
if (value < 0) break;
const uint8_t b = static_cast<uint8_t>(value);
rsdiag::increment(_stats.rx.bytes); _debug_dirty = true;
if (_rx_buffer_pos < 2) {
// Waiting for magic word
@@ -356,6 +415,7 @@ void RS232Bridge::loop() {
if (_rx_buffer_pos == 1) _rx_started = now;
} else {
// Invalid magic byte, reset and start over
rsdiag::increment(_stats.rx.noise);
_rx_buffer_pos = 0;
// Check if this byte could be the start of a new magic word
if (b == ((BRIDGE_PACKET_MAGIC >> 8) & 0xFF)) {
@@ -372,6 +432,7 @@ void RS232Bridge::loop() {
// Validate length field
if (len > (MAX_TRANS_UNIT + 1)) {
rsdiag::increment(_stats.rx.length_bad);
BRIDGE_DEBUG_PRINTLN("RX invalid length %d, resetting\n", len);
_rx_buffer_pos = 0; // Invalid length, reset
continue;
@@ -395,11 +456,13 @@ void RS232Bridge::loop() {
uint16_t received_checksum = (_rx_buffer[4 + len] << 8) | _rx_buffer[5 + len];
if (validateChecksum(_rx_buffer + 4, len, received_checksum)) {
rsdiag::increment(_stats.rx.frames);
BRIDGE_DEBUG_PRINTLN("RX, len=%d crc=0x%04x\n", len, received_checksum);
_rx_packet_ready = true;
_rx_packet_received_ms = now;
drainReceivedPackets(); // continue this bounded batch when the pool is available
} else {
rsdiag::increment(_stats.rx.checksum_bad);
BRIDGE_DEBUG_PRINTLN("RX checksum mismatch, rcv=0x%04x\n", received_checksum);
}
if (!_rx_packet_ready) _rx_buffer_pos = 0; // Keep a complete valid frame
@@ -411,11 +474,14 @@ void RS232Bridge::loop() {
expirePartialReceive(now);
serviceHeartbeat(now);
drainTransmit(now);
emitDebug();
}
void RS232Bridge::sendPacket(mesh::Packet *packet) {
rsdiag::increment(_stats.tx.requested); _debug_dirty = true;
// Guard against uninitialized state
if (_initialized == false) {
rsdiag::increment(_stats.tx.stopped);
return;
}
@@ -425,26 +491,32 @@ void RS232Bridge::sendPacket(mesh::Packet *packet) {
return;
}
if (!allowsPacket(packet)) return;
if (!allowsPacket(packet)) { rsdiag::increment(_stats.tx.filtered); return; }
// Preserve the legacy data path's blocking UART acceptance/throughput.
// Finish a partially emitted control/data frame first, never interleave it.
// A genuine failed/short hardware write is retained for later loop service;
// only that failure case cannot accept this caller's additional packet.
drainTransmit(millis(), true);
if (_tx_size != 0) return; // Never interleave mesh traffic with a partial frame.
if (_tx_size != 0) {
rsdiag::increment(_stats.tx.busy);
return; // Never interleave mesh traffic with a partial frame.
}
// The mesh's timed OTA retry cache, not the permanent bridge FIFO, owns
// duplicate suppression for resumable request/data packets.
const bool ota = packet->getPayloadType() == PAYLOAD_TYPE_OTA;
if (ota || !_seen_packets.wasSeen(packet)) {
const int expected = packet->getRawLength();
if (expected <= 0 || expected > MAX_TRANS_UNIT + 1) return;
if (expected <= 0 || expected > MAX_TRANS_UNIT + 1) {
rsdiag::increment(_stats.tx.oversize); return;
}
uint8_t* buffer = _tx_buffer;
uint16_t len = packet->writeTo(buffer + 4);
// Check if packet fits within our maximum payload size
if (len == 0 || len > (MAX_TRANS_UNIT + 1)) {
rsdiag::increment(_stats.tx.oversize);
BRIDGE_DEBUG_PRINTLN("TX packet too large (payload=%d, max=%d)\n", len, MAX_TRANS_UNIT + 1);
return;
}
@@ -466,17 +538,157 @@ void RS232Bridge::sendPacket(mesh::Packet *packet) {
_tx_size = static_cast<uint16_t>(len + SERIAL_OVERHEAD);
_tx_pos = 0;
_tx_is_ping = false;
_tx_is_probe = false;
_tx_is_data = true;
rsdiag::increment(_stats.tx.queued);
// Retain an outgoing OTA hash solely to reject reflected data as UART
// peer-liveness proof. It never suppresses OTA delivery in either direction.
_seen_packets.markSeen(packet);
drainTransmit(millis(), true);
BRIDGE_DEBUG_PRINTLN("TX, len=%d crc=0x%04x\n", len, checksum);
}
} else rsdiag::increment(_stats.tx.duplicate);
}
void RS232Bridge::onPacketReceived(mesh::Packet *packet) {
handleReceivedPacket(packet);
}
void RS232Bridge::onIngressResult(IngressResult result) {
switch (result) {
case IngressResult::Filtered: rsdiag::increment(_stats.rx.filtered); break;
case IngressResult::Duplicate: rsdiag::increment(_stats.rx.duplicate); break;
case IngressResult::Queued: rsdiag::increment(_stats.rx.delivered); break;
case IngressResult::Stopped: break;
}
_debug_dirty = true;
}
void RS232Bridge::resetStats() {
_stats = rsdiag::Stats{};
_debug_dirty = true;
}
bool RS232Bridge::sendTest(uint32_t nonce) {
_debug_dirty = true;
if (!_initialized || _power.suspended() || _power.retrying() || _power.probing()) {
_stats.error = rsdiag::Error::TestStopped;
rsdiag::increment(_stats.probe.failed);
return false;
}
const uint32_t now = millis();
if (txPending(now) || _pong_target != 0 || (_heartbeat_enabled && _session != 0
&& (_ping_due || mesh::bridge::rs232heartbeat::due(now, _next_ping)))) {
_stats.error = rsdiag::Error::TestBusy;
rsdiag::increment(_stats.probe.failed);
return false;
}
rsdiag::encodeProbe(_tx_buffer + 4, sizeof(_tx_buffer) - 4, nonce);
_tx_buffer[0] = 0xC0; _tx_buffer[1] = 0x3E;
_tx_buffer[2] = _tx_buffer[3] = 0;
_tx_pos = 0;
_tx_size = rsdiag::FrameSize;
_tx_is_ping = _tx_is_data = false;
_tx_is_probe = true;
_probe_timed_out = false;
_probe_deadline = now + frameAssemblyMs();
rsdiag::increment(_stats.probe.queued);
_stats.probe.last_tx_nonce = nonce;
return true;
}
void RS232Bridge::expireProbeTransmit(uint32_t now) {
if (!_tx_is_probe || _probe_timed_out || _tx_size == 0
|| !mesh::bridge::rs232heartbeat::due(now, _probe_deadline)) return;
_probe_timed_out = true;
// An entirely unsent probe can be canceled. Once its header starts, retain
// the suffix exactly like a partially emitted heartbeat, so even legacy
// receivers never consume a later mesh header as this control's length/CRC.
// UART recovery drains only the unsent suffix, never retransmits the prefix.
if (_tx_pos == 0) {
_tx_size = 0;
_tx_is_probe = false;
}
rsdiag::increment(_stats.probe.failed);
_stats.error = rsdiag::Error::TestTimeout;
_debug_dirty = true;
}
void RS232Bridge::formatStatus(char* out, size_t capacity) const {
if (!out || capacity == 0) return;
const char* phase = _power.retrying() ? "retrying" : _power.suspended() ? "standby"
: _power.probing() ? "probing" : _initialized ? "ready" : "off";
snprintf(out, capacity,
"> %s baud=%lu pins=%d/%d src=%s rxpart=%u rxready=%u tx=%u heartbeat=%s last=%s",
phase, (unsigned long)_prefs->bridge_baud, (int)_rx_pin, (int)_tx_pin,
_prefs->bridge_pkt_src ? "rx" : "tx", (unsigned)_rx_buffer_pos,
_rx_packet_ready ? 1U : 0U, (unsigned)(_tx_size - _tx_pos),
_heartbeat_enabled ? "on" : "passive", rsdiag::errorName(_stats.error));
out[capacity - 1] = 0;
}
void RS232Bridge::formatStats(const char* page, char* out, size_t capacity) const {
if (!out || capacity == 0) return;
const auto& s = _stats;
if (!page || !page[0]) {
snprintf(out, capacity, "> rx=%lu mesh=%lu tx=%lu sent=%lu; pages: rx tx drops test",
(unsigned long)s.rx.frames, (unsigned long)s.rx.delivered,
(unsigned long)s.tx.queued, (unsigned long)s.tx.sent);
} else if (strcmp(page, "rx") == 0) {
snprintf(out, capacity, "> bytes=%lu frames=%lu crc=%lu length=%lu parse=%lu timeout=%lu pool=%lu",
(unsigned long)s.rx.bytes, (unsigned long)s.rx.frames,
(unsigned long)s.rx.checksum_bad, (unsigned long)s.rx.length_bad,
(unsigned long)s.rx.packet_bad, (unsigned long)s.rx.timeout,
(unsigned long)s.rx.pool_wait);
} else if (strcmp(page, "tx") == 0) {
snprintf(out, capacity, "> req=%lu queued=%lu sent=%lu bytes=%lu stall=%lu short=%lu",
(unsigned long)s.tx.requested, (unsigned long)s.tx.queued,
(unsigned long)s.tx.sent, (unsigned long)s.tx.bytes,
(unsigned long)s.tx.stalls, (unsigned long)s.tx.short_writes);
} else if (strcmp(page, "drops") == 0) {
snprintf(out, capacity, "> noise=%lu filter=%lu dupe=%lu busy=%lu stopped=%lu txfilter=%lu txdupe=%lu big=%lu",
(unsigned long)s.rx.noise, (unsigned long)s.rx.filtered,
(unsigned long)s.rx.duplicate, (unsigned long)s.tx.busy,
(unsigned long)s.tx.stopped, (unsigned long)s.tx.filtered,
(unsigned long)s.tx.duplicate, (unsigned long)s.tx.oversize);
} else if (strcmp(page, "test") == 0) {
snprintf(out, capacity, "> queued=%lu sent=%lu fail=%lu rx=%lu bad=%lu txid=%08lX rxid=%08lX",
(unsigned long)s.probe.queued, (unsigned long)s.probe.sent,
(unsigned long)s.probe.failed, (unsigned long)s.probe.received,
(unsigned long)s.probe.bad, (unsigned long)s.probe.last_tx_nonce,
(unsigned long)s.probe.last_rx_nonce);
} else snprintf(out, capacity, "Error: use get rs232.stats [rx|tx|drops|test]");
out[capacity - 1] = 0;
}
void RS232Bridge::emitDebug() {
#if defined(ARDUINO)
if (!mesh::isUsbDebugLoggingEnabled()) { _debug_was_enabled = false; return; }
if (!_debug_was_enabled) _debug_dirty = true;
_debug_was_enabled = true;
const uint32_t now = millis();
if (!_debug_dirty || static_cast<uint32_t>(now - _debug_last_at) < 1000) return;
_debug_last_at = now;
_debug_dirty = false;
char status[157];
formatStatus(status, sizeof(status));
#if defined(NRF52_PLATFORM) || MESH_ESP32_USB_CONSOLE_COOPERATIVE
mesh::nrf52DebugPrintf("RS232: %s rx=%lu mesh=%lu crc=%lu tx=%lu sent=%lu test.rx=%08lX\n",
status + 2, (unsigned long)_stats.rx.frames, (unsigned long)_stats.rx.delivered,
(unsigned long)_stats.rx.checksum_bad, (unsigned long)_stats.tx.queued,
(unsigned long)_stats.tx.sent, (unsigned long)_stats.probe.last_rx_nonce);
#else
char line[256];
const int length = snprintf(line, sizeof(line),
"RS232: %s rx=%lu mesh=%lu crc=%lu tx=%lu sent=%lu test.rx=%08lX\n",
status + 2, (unsigned long)_stats.rx.frames, (unsigned long)_stats.rx.delivered,
(unsigned long)_stats.rx.checksum_bad, (unsigned long)_stats.tx.queued,
(unsigned long)_stats.tx.sent, (unsigned long)_stats.probe.last_rx_nonce);
if (length > 0 && (size_t)length < sizeof(line)
&& mesh::usbLoggingPort().availableForWrite() >= length)
mesh::usbLoggingPort().write(reinterpret_cast<const uint8_t*>(line), length);
#endif
#endif
}
#endif
+21
View File
@@ -2,6 +2,7 @@
#include "helpers/bridges/BridgeBase.h"
#include "helpers/bridges/RS232Heartbeat.h"
#include "helpers/bridges/RS232BridgeDiagnostics.h"
#include <Stream.h>
@@ -123,6 +124,13 @@ public:
void formatHeartbeatStatus(char* out, size_t capacity, uint32_t now) const;
bool isPowerSuspended() const { return _power.suspended(); }
// Object-lifetime, read-only diagnostics; ordinary firmware needs no special
// BRIDGE_DEBUG build. Test transmission never wakes or claims the UART.
void formatStatus(char* out, size_t capacity) const;
void formatStats(const char* page, char* out, size_t capacity) const;
bool sendTest(uint32_t nonce);
void resetStats();
private:
/**
* RS232 Protocol Structure:
@@ -159,6 +167,7 @@ private:
// Retain the completed parser buffer while the shared pool is exhausted;
// unread bytes remain in the UART driver until this frame is delivered.
bool _rx_packet_ready = false;
bool _rx_pool_blocked = false;
void drainReceivedPackets();
/** Current position in the receive buffer */
@@ -172,6 +181,10 @@ private:
uint32_t _tx_wire_until = 0;
bool _tx_wire_pending = false;
bool _tx_is_ping = false;
bool _tx_is_probe = false;
bool _probe_timed_out = false;
bool _tx_is_data = false;
uint32_t _probe_deadline = 0;
uint32_t _tx_ping_challenge = 0;
mesh::bridge::RS232PowerPolicy _power;
@@ -198,6 +211,14 @@ private:
bool _legacy_fresh = false;
bool _partial_suspend_grace = false;
mesh::bridge::rs232diag::Stats _stats;
uint32_t _debug_last_at = 0;
bool _debug_dirty = true;
bool _debug_was_enabled = false;
void onIngressResult(IngressResult result) override;
void emitDebug();
void expireProbeTransmit(uint32_t now);
void resetTransportState();
void expirePartialReceive(uint32_t now);
void expireHeartbeatFreshness(uint32_t now);
@@ -0,0 +1,85 @@
#pragma once
#include "RS232Heartbeat.h"
#include <string.h>
namespace mesh {
namespace bridge {
namespace rs232diag {
// Observation belongs to the bridge object, not persistent preferences. Soft
// UART stop/start keeps counters; resetstats, object replacement or reboot does
// not. No receive callback, heap allocation or packet-pool entry is involved.
struct RxStats {
uint32_t bytes = 0, frames = 0, checksum_bad = 0, length_bad = 0;
uint32_t packet_bad = 0, noise = 0, timeout = 0, pool_wait = 0;
uint32_t filtered = 0, duplicate = 0, delivered = 0;
};
struct TxStats {
uint32_t requested = 0, queued = 0, sent = 0, bytes = 0;
uint32_t stalls = 0, short_writes = 0, busy = 0, stopped = 0;
uint32_t filtered = 0, duplicate = 0, oversize = 0;
};
struct ProbeStats {
uint32_t queued = 0, sent = 0, failed = 0, received = 0, bad = 0;
uint32_t last_tx_nonce = 0, last_rx_nonce = 0;
};
enum class Error : uint8_t { None, Pins, Driver, TestStopped, TestBusy, TestTimeout };
struct Stats {
RxStats rx;
TxStats tx;
ProbeStats probe;
Error error = Error::None;
};
static_assert(sizeof(Stats) <= 128, "RS232 diagnostics must keep bounded storage");
inline void increment(uint32_t& value) { if (value != UINT32_MAX) ++value; }
inline void add(uint32_t& value, size_t amount) {
const uint32_t room = UINT32_MAX - value;
value = amount >= room ? UINT32_MAX : value + static_cast<uint32_t>(amount);
}
inline const char* errorName(Error error) {
switch (error) {
case Error::None: return "none";
case Error::Pins: return "pins";
case Error::Driver: return "driver";
case Error::TestStopped: return "test.stopped";
case Error::TestBusy: return "test.busy";
case Error::TestTimeout: return "test.timeout";
}
return "unknown";
}
// Same fixed, zero-length control envelope as the heartbeat, with its own
// versioned opcode. Every body byte is ASCII, so legacy parsers which reject
// length zero cannot find a new C0 3E magic word in the body. Existing heartbeat
// decoders reject DG1T. The probe never proves heartbeat liveness or identity.
// Body: DG1T, nonce[8 hex], reserved[32 zeroes], Fletcher16[4 hex].
static constexpr size_t BodySize = rs232heartbeat::BODY_SIZE;
static constexpr size_t FrameSize = rs232heartbeat::FRAME_SIZE;
inline bool isProbeCandidate(const uint8_t* body) {
return body && body[0] == 'D' && body[1] == 'G';
}
inline bool encodeProbe(uint8_t* body, size_t capacity, uint32_t nonce) {
if (!body || capacity < BodySize) return false;
body[0] = 'D'; body[1] = 'G'; body[2] = '1'; body[3] = 'T';
rs232heartbeat::writeHex(body + 4, nonce, 8);
memset(body + 12, '0', 32);
rs232heartbeat::writeHex(body + 44, rs232heartbeat::checksum(body, 44), 4);
return true;
}
inline bool decodeProbe(const uint8_t* body, size_t size, uint32_t& nonce) {
if (!body || size != BodySize || !isProbeCandidate(body)
|| body[2] != '1' || body[3] != 'T') return false;
for (size_t i = 12; i < 44; ++i) if (body[i] != '0') return false;
uint64_t parsed, checksum;
if (!rs232heartbeat::readHex(body + 4, 8, parsed)
|| !rs232heartbeat::readHex(body + 44, 4, checksum)
|| checksum != rs232heartbeat::checksum(body, 44)) return false;
nonce = static_cast<uint32_t>(parsed);
return true;
}
} // namespace rs232diag
} // namespace bridge
} // namespace mesh