From 14682de00e3b90f309aef36389224b7c50096ce6 Mon Sep 17 00:00:00 2001 From: mikecarper Date: Thu, 22 Oct 2026 11:30:28 -0700 Subject: [PATCH] Add runtime ESP-NOW bridge diagnostics and link probes --- .github/workflows/run-unit-tests.yml | 2 + docs/cli_commands.md | 81 ++++ docs/espnow_bridge_setup.md | 104 ++++- examples/simple_repeater/MyMesh.h | 21 + examples/simple_room_server/MyMesh.h | 16 + src/MeshCore.h | 3 +- src/helpers/CommonCLI.cpp | 59 +++ src/helpers/CommonCLI.h | 14 + src/helpers/bridges/BridgeBase.cpp | 12 + src/helpers/bridges/BridgeBase.h | 6 + src/helpers/bridges/ESPNowBridge.cpp | 377 ++++++++++++++++-- src/helpers/bridges/ESPNowBridge.h | 23 +- src/helpers/bridges/ESPNowBridgeDiagnostics.h | 173 ++++++++ .../espnow_bridge_diagnostic_runtime.cpp | 369 +++++++++++++++++ test/fixtures/espnow_bridge_diagnostics.cpp | 242 +++++++++++ test/fixtures/espnow_wifi_handoff.cpp | 7 +- test/test_bridge_recovery.py | 33 +- test/test_espnow_bridge_diagnostics.py | 182 +++++++++ test/test_espnow_diagnostic_cli.py | 240 +++++++++++ test/test_espnow_radio_lifecycle.py | 7 +- test/test_transport_filter_wiring.py | 42 +- webui/index.html | 2 +- 22 files changed, 1947 insertions(+), 68 deletions(-) create mode 100644 src/helpers/bridges/ESPNowBridgeDiagnostics.h create mode 100644 test/fixtures/espnow_bridge_diagnostic_runtime.cpp create mode 100644 test/fixtures/espnow_bridge_diagnostics.cpp create mode 100644 test/test_espnow_bridge_diagnostics.py create mode 100644 test/test_espnow_diagnostic_cli.py diff --git a/.github/workflows/run-unit-tests.yml b/.github/workflows/run-unit-tests.yml index 952e91e20..4e85d4b00 100644 --- a/.github/workflows/run-unit-tests.yml +++ b/.github/workflows/run-unit-tests.yml @@ -862,6 +862,8 @@ jobs: python3 -B test/test_espnow_radio_lifecycle.py -v python3 -B test/test_wifi_ap_lr_safety.py -v python3 -B test/test_espnow_runtime.py -v + python3 -B test/test_espnow_bridge_diagnostics.py -v + python3 -B test/test_espnow_diagnostic_cli.py -v python3 -B test/test_wifi_ota_lifecycle.py -v - name: Verify message reader buttons, touch targets, and footer layouts diff --git a/docs/cli_commands.md b/docs/cli_commands.md index 7a42189f4..cced8630d 100644 --- a/docs/cli_commands.md +++ b/docs/cli_commands.md @@ -5576,6 +5576,87 @@ For a complete two-repeater setup with each option explained, see the --- +#### Diagnose the ESP-NOW bridge + +Available when the optional ESP-NOW bridge is compiled in. These are runtime +diagnostics; no `BRIDGE_DEBUG` build flag is required. + +**Read-only commands:** + +```text +get espnow.status +get espnow.stats +get espnow.stats rx +get espnow.stats tx +get espnow.stats drops +get espnow.stats test +``` + +Status reports local state (`off`, `teardown-error`, `driver-error`, +`channel-mismatch` or `ready`), then these compact fields: + +| Field | Meaning | +| --- | --- | +| `ch` | Configured/actual 2.4 GHz channel; actual `0` means unavailable. | +| `fmt`, `src` | Packet format and configured LoRa packet source (`rx` or `tx`). | +| `wifi` | Shared WiFi enable setting, not proof of WiFi association. | +| `mode`, `ps`, `proto` | WiFi SDK mode and power-save integers, and protocol bitmask in hexadecimal. An unavailable mode or power-save query returns `-1`. | +| `q` | Current receive/transmit queue depths. | +| `last` | Last recorded SDK error stage/code, which may remain after recovery. | + +`espnow.running on` means the local bridge initialized; it does not prove a +peer is reachable. The statistics pages use these keys: + +| Page | Keys and meaning | +| --- | --- | +| Default | `rx`: received callback frames; `mesh`: inbound MeshCore packets queued; `tx`: outbound MeshCore packets queued; `sent`: successful frame callbacks. | +| `rx` | `frames`: received callback frames; `decoded`: parsed MeshCore packets; `mesh`: queued for mesh processing; `crc`: checksum failures; `bad`: malformed frames; `parse`: packet parse failures. | +| `tx` | `req`: mesh TX requests; `queued`: mesh packets queued; `start`: SDK-accepted frames; `ok`: successful frame callbacks; `err`: SDK start failures; `cbfail`: failed frame callbacks; `timeout`: callback timeouts. | +| `drops` | `rxq`: RX queue drops; `foreign`: foreign-group packets; `filter`/`dupe`: inbound filter/duplicate drops; `txq`: total mesh TX drops; `txfilter`/`txdupe`: outbound filter/duplicate drops; `big`: oversize TX drops. | +| `test` | `queued`, `start`, `ok`, `fail`, `timeout`: probe TX stages; `rx`, `bad`: valid/invalid probes received; `txid`, `rxid`: last queued/received IDs in hexadecimal. | + +Mesh admission means queued for normal processing, not confirmed LoRa +forwarding or end-to-end delivery. Packet and frame counters have different +units: fragmentation can produce several frames for one mesh packet. Counters +survive bridge stop/start; reboot or the explicit reset starts a new window. + +**Local-only actions:** + +```text +espnow test +espnow test A1B2C3D4 +espnow resetstats +``` + +The optional test ID is exactly eight hexadecimal digits, case-insensitive, +without `0x`, spaces or trailing arguments. Omitting it uses uptime in +milliseconds. The reply `OK - test queued id=...; confirm on peer` confirms +local queueing only. Read the other updated board's `get espnow.stats test` +and match `rxid`, with an increased `rx`, to establish one-way probe receipt. Send a +different ID from the other board to test the reverse direction. + +A probe is unencrypted, CRC-checked transport diagnostic data, not a MeshCore +packet or a security token. It does not verify packet-format compatibility or +`bridge.secret`, authenticate the peer or establish normal packet delivery. +There is no automatic echo, +retry or LoRa forwarding; older firmware ignores it. Resetting statistics +does not restart the bridge or write preferences. Test/reset commands are +rejected over LoRa; use a local console. Every reply fits the bounded CLI +frame, and diagnostics do not print from WiFi callbacks. + +For a short USB debug capture, record both `get usb.logging` and +`get usb.debug`, then enable both `set usb.logging on` and `set usb.debug on`. +Run the test and restore both original settings. The ordinary image emits +bounded `ESPNOW:` updates from its main loop at most once per second when +diagnostic state changes, even with `BRIDGE_DEBUG=0`. Updates can be skipped +when USB is busy; read the counter pages for exact values. The CLI counter +pages and probes do not require either logging gate. + +See the [two-board diagnostic flow](espnow_bridge_setup.md#test-the-24-ghz-path-without-lora-forwarding). +Do not include `get bridge.secret` or WiFi credentials in shared debug logs. + +--- + #### View or change the bridge enabled flag **Search terms:** enable bridge, disable bridge, serial bridge, RS232 bridge. diff --git a/docs/espnow_bridge_setup.md b/docs/espnow_bridge_setup.md index 711b49ae6..6d2c0d122 100644 --- a/docs/espnow_bridge_setup.md +++ b/docs/espnow_bridge_setup.md @@ -112,17 +112,23 @@ Run on both boards: ```text get espnow.enabled get espnow.running +get espnow.status get bridge.channel get bridge.format -get bridge.secret get bridge.source get bridge.delay get repeat get radio ``` -Expected: enabled and running `on`, matching channel/format/secret, source -`tx`, delay `500`, repeat `on`, and the intended LoRa settings on each side. +For the example above, expect enabled and running `on`, matching channel and +format, source `tx`, delay `500`, repeat `on`, and the intended LoRa settings +on each side. An existing `bridge.source rx` setup is also valid; diagnose +the selected source rather than changing it just to match this example. +Compare the shared secret privately; omit `get bridge.secret` from logs you +share. `get espnow.status` distinguishes the configured channel from the actual +2.4 GHz channel. Its `last` error stage/code is historical and may remain after +recovery. A running bridge is not proof that the other board received anything. Send a message from a Companion on network A to one on network B, then reply from B to A. Check both directions; configuration readback alone does not test @@ -137,6 +143,98 @@ If it does not work: and secret; confirm each board's LoRa settings were applied with a reboot, and check the networks' forwarding and scope rules. +If those saved settings already match, use the bounded test below before +changing them again. + +### Test the 2.4 GHz path without LoRa forwarding + +Updated ESP-NOW bridge firmware includes runtime diagnostics in the ordinary +image. No `BRIDGE_DEBUG` build flag or continuous USB logging is needed. Use +the USB console so a WiFi change cannot disconnect your diagnostic session. + +On both boards, start a fresh observation window: + +```text +espnow resetstats +get espnow.status +get espnow.stats test +``` + +On A, send one probe: + +```text +espnow test A1B2C3D4 +``` + +`OK - test queued id=A1B2C3D4; confirm on peer` means queued locally. On B, run +`get espnow.stats test`: `rx` must increase and `rxid` must be `A1B2C3D4`. +Then send `espnow test B1C2D3E4` on B and confirm that ID on A. The two +commands are two one-way tests; there is no +automatic reply or retry. Sender completion alone does not prove peer receipt. +The optional ID is exactly eight hexadecimal digits, without `0x`; omitting +it uses the current uptime in milliseconds as a correlation ID. + +These small, unencrypted CRC-checked probes test transport reachability only. +They do not validate packet-format compatibility or the wrapped shared secret, +authenticate the peer or prove MeshCore packet delivery. They are never +injected into the mesh or forwarded +onto LoRa. Older firmware ignores them and cannot report the received ID; +use an updated peer for confirmation. Sending a probe and resetting +statistics require a local connection; neither changes saved preferences. + +### Locate a mesh forwarding failure + +If both probe directions work, send one fresh identifiable message from a +Companion on A's LoRa network and read these pages on both bridge boards: + +```text +get espnow.stats +get espnow.stats rx +get espnow.stats tx +get espnow.stats drops +``` + +Repeat in the opposite direction with a new message. Counters accumulate until +`espnow resetstats` or reboot and survive an ESP-NOW stop/start. Inspect changes +across the one message, rather than assuming old totals describe the current +attempt. + +- **No source-side bridge TX request:** check the configured source. + `bridge.source rx` exports LoRa receptions; confirm the board heard the + fresh message. `bridge.source tx` exports LoRa transmissions; confirm it + forwards the message with repeat on and the intended routing, scope and + flood-filter settings. Either source is valid. +- **TX requested but not sent:** the TX/drops pages separate queued traffic, + filtering, duplicates, size/queue drops and SDK start/completion failures. + Check the configured/live 2.4 GHz channel and last error stage/code. +- **Peer sees frames but accepts no MeshCore packet:** inspect RX rejection + counters, format and the privately compared wrapped secret. A successful + diagnostic probe does not rule out a packet-format or secret mismatch. +- **Peer admits the packet but no LoRa delivery follows:** admission means + queued for normal mesh processing, not a completed LoRa transmission. Check + repeat, scope, filters, duplicate suppression and the destination network. + +An absent counter change narrows a stage; these checks do not assume a cause +for a particular pair of boards. + +If both bridge boards also hear the same message directly on LoRa, normal +duplicate suppression can discard its later bridged copy. That alone does +not show a broken ESP-NOW link. This is a possibility to check with the +counters, not an established cause of a reported delivery failure. + +### Optional short USB debug capture + +For a brief observation window, run `get usb.logging` and `get usb.debug` +and record both original settings. Enable both gates with `set usb.logging on` +and `set usb.debug on`. The bridge emits bounded `ESPNOW:` status/counter +updates from its main loop, at most once per second when diagnostic state +changes. No `BRIDGE_DEBUG` build flag is required, and WiFi callbacks do not +print to USB. Send the two probes or one fresh message, then restore both +original settings. The CLI counter pages and probes do not require either +logging gate. Use the counter pages for exact values; a busy USB console can +skip a debug update. Do not include secrets or WiFi credentials in a shared +capture. + A running bridge keeps the device awake, even with device power saving enabled. ESP-NOW shares the WiFi radio: use the connected WiFi network's channel when WiFi is active. Browser OTA pauses ESP-NOW on ordinary non-MQTT repeaters, diff --git a/examples/simple_repeater/MyMesh.h b/examples/simple_repeater/MyMesh.h index 9a6a166d2..6863620fa 100644 --- a/examples/simple_repeater/MyMesh.h +++ b/examples/simple_repeater/MyMesh.h @@ -651,6 +651,27 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks #endif #if defined(WITH_ESPNOW_BRIDGE) + ESPNowBridge& diagnosticEspNowBridge() { +#if defined(WITH_MQTT_BRIDGE) || defined(WITH_RS232_BRIDGE) + return espnow_bridge; +#else + return bridge; +#endif + } + void formatEspNowStatus(char* reply, size_t capacity) override { + diagnosticEspNowBridge().formatStatus(reply, capacity); + } + void formatEspNowStats(const char* page, char* reply, size_t capacity) override { + diagnosticEspNowBridge().formatStats(page, reply, capacity); + } + bool sendEspNowTest(uint32_t nonce) override { + return diagnosticEspNowBridge().sendTest(nonce); + } + bool resetEspNowStats() override { + diagnosticEspNowBridge().resetStats(); + return true; + } + // Retry ESP-NOW without taking over an active OTA session. MQTT creates its // WiFi task asynchronously, so it must first associate on the shared channel. bool startSharedEspNowBridgeIfReady() { diff --git a/examples/simple_room_server/MyMesh.h b/examples/simple_room_server/MyMesh.h index 2f65c6aef..ee5d4b15c 100644 --- a/examples/simple_room_server/MyMesh.h +++ b/examples/simple_room_server/MyMesh.h @@ -669,6 +669,22 @@ public: #if defined(WITH_BRIDGE) +#if defined(WITH_MQTT_BRIDGE) && defined(WITH_ESPNOW_BRIDGE) + void formatEspNowStatus(char* reply, size_t capacity) override { + espnow_bridge.formatStatus(reply, capacity); + } + void formatEspNowStats(const char* page, char* reply, size_t capacity) override { + espnow_bridge.formatStats(page, reply, capacity); + } + bool sendEspNowTest(uint32_t nonce) override { + return espnow_bridge.sendTest(nonce); + } + bool resetEspNowStats() override { + espnow_bridge.resetStats(); + return true; + } +#endif + #if defined(WITH_MQTT_BRIDGE) && defined(WITH_ESPNOW_BRIDGE) // MQTT's WiFi task associates asynchronously. ESP-NOW must wait for that // station interface so it can share the AP-selected channel safely. diff --git a/src/MeshCore.h b/src/MeshCore.h index d6695fcc3..52f0485c9 100644 --- a/src/MeshCore.h +++ b/src/MeshCore.h @@ -34,7 +34,8 @@ (defined(NRF52_PLATFORM) || MESH_ESP32_USB_CONSOLE_COOPERATIVE) && \ ((defined(MESH_DEBUG) && MESH_DEBUG) || \ (defined(BRIDGE_DEBUG) && BRIDGE_DEBUG) || \ - (defined(POWERSAVING_DEBUG) && POWERSAVING_DEBUG)) + (defined(POWERSAVING_DEBUG) && POWERSAVING_DEBUG) || \ + defined(WITH_ESPNOW_BRIDGE)) #include #include #include diff --git a/src/helpers/CommonCLI.cpp b/src/helpers/CommonCLI.cpp index cc7b20ff3..c1a3819f0 100644 --- a/src/helpers/CommonCLI.cpp +++ b/src/helpers/CommonCLI.cpp @@ -33,6 +33,9 @@ #ifdef WITH_RS232_BRIDGE #include "bridges/RS232PowerSettings.h" #endif +#if defined(WITH_ESPNOW_BRIDGE) +#include "bridges/ESPNowBridgeDiagnostics.h" +#endif #include "GpsPowerPolicy.h" #include "FloodAdvertCLI.h" #include "StorageLayout.h" @@ -3048,9 +3051,65 @@ uint8_t CommonCLI::buildAdvertData(uint8_t node_type, uint8_t* app_data) { } } +#if defined(WITH_ESPNOW_BRIDGE) +bool CommonCLI::handleEspNowDiagnosticCommand(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 espnow.status", 17) == 0) { + if (strcmp(command, "get espnow.status") != 0) { + snprintf(reply, capacity, "Error: use get espnow.status"); + } else { + _callbacks->formatEspNowStatus(reply, capacity); + } + return true; + } + if (strncmp(command, "get espnow.stats", 16) == 0) { + const char* page = command + 16; + if (*page == 0) { + _callbacks->formatEspNowStats("", reply, capacity); + } else if (strcmp(page, " rx") == 0 || strcmp(page, " tx") == 0 + || strcmp(page, " drops") == 0 || strcmp(page, " test") == 0) { + _callbacks->formatEspNowStats(page + 1, reply, capacity); + } else { + snprintf(reply, capacity, "Error: use get espnow.stats [rx|tx|drops|test]"); + } + return true; + } + if (strncmp(command, "espnow", 6) != 0 + || (command[6] != 0 && command[6] != ' ')) return false; + if (sender_timestamp != 0) { + snprintf(reply, capacity, "Error: ESP-NOW test/reset requires a local connection"); + return true; + } + if (strcmp(command, "espnow resetstats") == 0) { + snprintf(reply, capacity, "%s", _callbacks->resetEspNowStats() + ? "OK - ESP-NOW statistics reset" : "Error: ESP-NOW diagnostics unavailable"); + return true; + } + uint32_t nonce = 0; + if (strcmp(command, "espnow test") == 0) { + nonce = millis(); // Correlation only; this is not a security token. + } else if (strncmp(command, "espnow test ", 12) != 0 + || !mesh::bridge::diag::parseNonce(command + 12, nonce)) { + snprintf(reply, capacity, "Error: use espnow test [8 hex digits] or espnow resetstats"); + return true; + } + if (_callbacks->sendEspNowTest(nonce)) { + snprintf(reply, capacity, "OK - test queued id=%08lX; confirm on peer", + static_cast(nonce)); + } else { + snprintf(reply, capacity, "Error: ESP-NOW test not queued; check status/stats"); + } + return true; +} +#endif + 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_ESPNOW_BRIDGE) + if (handleEspNowDiagnosticCommand(sender_timestamp, command, reply)) return; +#endif #if MESH_ENABLE_FLEET_CONTROL if (handleFleetCommand(command, reply)) return; #endif diff --git a/src/helpers/CommonCLI.h b/src/helpers/CommonCLI.h index cbdf655f9..e91da7832 100644 --- a/src/helpers/CommonCLI.h +++ b/src/helpers/CommonCLI.h @@ -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_ESPNOW_BRIDGE) + virtual void formatEspNowStatus(char* reply, size_t capacity) { + snprintf(reply, capacity, "Error: ESP-NOW diagnostics unavailable"); + } + virtual void formatEspNowStats(const char* page, char* reply, size_t capacity) { + (void)page; + snprintf(reply, capacity, "Error: ESP-NOW diagnostics unavailable"); + } + virtual bool sendEspNowTest(uint32_t nonce) { (void)nonce; return false; } + virtual bool resetEspNowStats() { return false; } +#endif virtual void restartBridgeSlot(int slot) { // Default: fall back to full restart @@ -897,6 +908,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_ESPNOW_BRIDGE) + bool handleEspNowDiagnosticCommand(uint32_t sender_timestamp, const char* command, char* reply); +#endif void handleDelCmd(char* command, char* reply); #if defined(NRF52_PLATFORM) && defined(OTA_SD_STORE) bool handleSdCardGetCmd(const char* config, char* reply); diff --git a/src/helpers/bridges/BridgeBase.cpp b/src/helpers/bridges/BridgeBase.cpp index 68716fd27..e98546160 100644 --- a/src/helpers/bridges/BridgeBase.cpp +++ b/src/helpers/bridges/BridgeBase.cpp @@ -36,11 +36,17 @@ 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) + onIngressResult(IngressResult::Stopped); +#endif return; } if (!preparePacketIngress(packet) || !allowsPacket(packet)) { _mgr->free(packet); +#if defined(WITH_ESPNOW_BRIDGE) + onIngressResult(IngressResult::Filtered); +#endif return; } @@ -52,7 +58,13 @@ 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) + onIngressResult(IngressResult::Queued); +#endif } else { _mgr->free(packet); +#if defined(WITH_ESPNOW_BRIDGE) + onIngressResult(IngressResult::Duplicate); +#endif } } diff --git a/src/helpers/bridges/BridgeBase.h b/src/helpers/bridges/BridgeBase.h index 05a3ff6e8..8afd9305b 100644 --- a/src/helpers/bridges/BridgeBase.h +++ b/src/helpers/bridges/BridgeBase.h @@ -50,6 +50,12 @@ public: static constexpr uint16_t BRIDGE_CHECKSUM_SIZE = sizeof(uint16_t); protected: +#if defined(WITH_ESPNOW_BRIDGE) + // Observe the existing admission decision without evaluating filters twice. + enum class IngressResult : uint8_t { Stopped, Filtered, Duplicate, Queued }; + virtual void onIngressResult(IngressResult) {} +#endif + /** Tracks bridge state */ bool _initialized = false; diff --git a/src/helpers/bridges/ESPNowBridge.cpp b/src/helpers/bridges/ESPNowBridge.cpp index ed936c739..77016ec6a 100644 --- a/src/helpers/bridges/ESPNowBridge.cpp +++ b/src/helpers/bridges/ESPNowBridge.cpp @@ -3,6 +3,7 @@ #include #include +#include #ifdef WITH_ESPNOW_BRIDGE #include @@ -73,7 +74,12 @@ ESPNowBridge::ESPNowBridge(NodePrefs *prefs, mesh::PacketManager *mgr, mesh::RTC } void ESPNowBridge::begin() { - if (mesh::wireless::control().blocked(mesh::wireless::EspNow)) return; + using mesh::bridge::diag::Stage; + if (mesh::wireless::control().blocked(mesh::wireless::EspNow)) { + recordError(Stage::Policy, ESP_ERR_INVALID_STATE); + emitDebug(); + return; + } BRIDGE_DEBUG_PRINTLN("Initializing...\n"); if (_initialized) return; @@ -86,6 +92,8 @@ void ESPNowBridge::begin() { ? _prefs->bridge_format : mesh::bridge::ESPNOW_FORMAT_WRAPPED; const bool raw_format = _active_format == mesh::bridge::ESPNOW_FORMAT_RAW; if (raw_format && mesh::wifi::checkLongRangeRadioStart() != ESP_OK) { + recordError(Stage::WiFiProtocol, ESP_ERR_INVALID_STATE); + emitDebug(); BRIDGE_DEBUG_PRINTLN("ESP-NOW LR start deferred while a WiFi AP is active\n"); return; } @@ -111,6 +119,8 @@ void ESPNowBridge::begin() { if (!mesh::bridge::isValidEspNowBridgeChannel( _prefs->bridge_channel, _active_format)) { + recordError(Stage::Channel, ESP_ERR_INVALID_ARG); + emitDebug(); BRIDGE_DEBUG_PRINTLN("ESP-NOW channel must be 1-13\n"); return; } @@ -122,18 +132,28 @@ void ESPNowBridge::begin() { if (shared_wifi) { uint8_t channel = 0; wifi_second_chan_t secondary = WIFI_SECOND_CHAN_NONE; - if (esp_wifi_get_channel(&channel, &secondary) != ESP_OK || channel != _prefs->bridge_channel) { + const esp_err_t result = esp_wifi_get_channel(&channel, &secondary); + if (result != ESP_OK || channel != _prefs->bridge_channel) { + recordError(Stage::ChannelConflict, + result != ESP_OK ? result : ESP_ERR_INVALID_STATE); + emitDebug(); BRIDGE_DEBUG_PRINTLN("ESP-NOW bridge channel must match the active WiFi channel\n"); return; } } wifi_init_config_t wifi_config = WIFI_INIT_CONFIG_DEFAULT(); - if (!shared_wifi && (esp_wifi_init(&wifi_config) != ESP_OK || - esp_wifi_set_storage(WIFI_STORAGE_RAM) != ESP_OK || - esp_wifi_set_mode(WIFI_MODE_STA) != ESP_OK || - esp_wifi_start() != ESP_OK)) { + auto failed = [this](esp_err_t result, Stage stage) { + if (result == ESP_OK) return false; + recordError(stage, result); stopBridgeWiFiIfUnused(); - return; + emitDebug(); + return true; + }; + if (!shared_wifi) { + if (failed(esp_wifi_init(&wifi_config), Stage::WiFiInit) + || failed(esp_wifi_set_storage(WIFI_STORAGE_RAM), Stage::WiFiStorage) + || failed(esp_wifi_set_mode(WIFI_MODE_STA), Stage::WiFiMode) + || failed(esp_wifi_start(), Stage::WiFiStart)) return; } if (raw_format) { @@ -141,7 +161,10 @@ void ESPNowBridge::begin() { // support as well, but force this peer's outgoing frames to LR below. const uint8_t protocols = WIFI_PROTOCOL_11B | WIFI_PROTOCOL_11G | WIFI_PROTOCOL_11N | WIFI_PROTOCOL_LR; - if (mesh::wifi::applyStationProtocolMask(protocols, true) != ESP_OK) { + const esp_err_t result = mesh::wifi::applyStationProtocolMask(protocols, true); + if (result != ESP_OK) { + recordError(Stage::WiFiProtocol, result); + emitDebug(); BRIDGE_DEBUG_PRINTLN("Error enabling ESP-NOW LR protocol\n"); stopBridgeWiFiIfUnused(); return; @@ -149,21 +172,34 @@ void ESPNowBridge::begin() { } // Set Wi-Fi channel - if (!shared_wifi && esp_wifi_set_channel(_prefs->bridge_channel, WIFI_SECOND_CHAN_NONE) != ESP_OK) { + const esp_err_t channel_result = shared_wifi ? ESP_OK + : esp_wifi_set_channel(_prefs->bridge_channel, WIFI_SECOND_CHAN_NONE); + if (channel_result != ESP_OK) { + recordError(Stage::WiFiChannel, channel_result); + emitDebug(); BRIDGE_DEBUG_PRINTLN("Error setting WIFI channel to %d\n", _prefs->bridge_channel); stopBridgeWiFiIfUnused(); return; } // Initialize ESP-NOW - if (esp_now_init() != ESP_OK) { + const esp_err_t init_result = esp_now_init(); + if (init_result != ESP_OK) { + recordError(Stage::EspNowInit, init_result); + emitDebug(); BRIDGE_DEBUG_PRINTLN("Error initializing ESP-NOW\n"); stopBridgeWiFiIfUnused(); return; } // Register callbacks - if (esp_now_register_recv_cb(recv_cb) != ESP_OK || esp_now_register_send_cb(send_cb) != ESP_OK) { + const esp_err_t recv_result = esp_now_register_recv_cb(recv_cb); + const esp_err_t send_result = recv_result == ESP_OK + ? esp_now_register_send_cb(send_cb) : ESP_OK; + if (recv_result != ESP_OK || send_result != ESP_OK) { + recordError(recv_result != ESP_OK ? Stage::RecvCallback : Stage::SendCallback, + recv_result != ESP_OK ? recv_result : send_result); + emitDebug(); BRIDGE_DEBUG_PRINTLN("Error registering ESP-NOW callbacks\n"); esp_now_register_recv_cb(nullptr); esp_now_register_send_cb(nullptr); @@ -180,7 +216,10 @@ void ESPNowBridge::begin() { peerInfo.ifidx = WIFI_IF_STA; peerInfo.encrypt = false; - if (esp_now_add_peer(&peerInfo) != ESP_OK) { + const esp_err_t peer_result = esp_now_add_peer(&peerInfo); + if (peer_result != ESP_OK) { + recordError(Stage::PeerAdd, peer_result); + emitDebug(); BRIDGE_DEBUG_PRINTLN("Failed to add broadcast peer\n"); esp_now_register_recv_cb(nullptr); esp_now_register_send_cb(nullptr); @@ -203,6 +242,8 @@ void ESPNowBridge::begin() { WIFI_IF_STA, WIFI_PHY_RATE_LORA_250K); #endif if (rate_result != ESP_OK) { + recordError(Stage::PeerRate, rate_result); + emitDebug(); BRIDGE_DEBUG_PRINTLN("Error configuring ESP-NOW LR peer rate\n"); esp_now_del_peer(peerInfo.peer_addr); esp_now_register_recv_cb(nullptr); @@ -217,6 +258,8 @@ void ESPNowBridge::begin() { _initialized = true; mesh::wifi::setLongRangeOwner(mesh::wifi::kLongRangeBridgeOwner, raw_format); mesh::wifi::bridgeEspNowChannel().store(_prefs->bridge_channel); + _debug_dirty.store(true, std::memory_order_relaxed); + emitDebug(); } void ESPNowBridge::end() { @@ -225,7 +268,9 @@ void ESPNowBridge::end() { // Remove broadcast peer uint8_t broadcastAddress[] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; - if (esp_now_del_peer(broadcastAddress) != ESP_OK) { + const esp_err_t remove_result = esp_now_del_peer(broadcastAddress); + if (remove_result != ESP_OK) { + recordError(mesh::bridge::diag::Stage::PeerRemove, remove_result); BRIDGE_DEBUG_PRINTLN("Error removing broadcast peer\n"); } @@ -234,8 +279,10 @@ void ESPNowBridge::end() { esp_now_register_send_cb(nullptr); // Deinitialize ESP-NOW - _sdk_teardown_failed = esp_now_deinit() != ESP_OK; + const esp_err_t deinit_result = esp_now_deinit(); + _sdk_teardown_failed = deinit_result != ESP_OK; if (_sdk_teardown_failed) { + recordError(mesh::bridge::diag::Stage::EspNowDeinit, deinit_result); BRIDGE_DEBUG_PRINTLN("Error deinitializing ESP-NOW\n"); } @@ -257,7 +304,7 @@ void ESPNowBridge::end() { uint8_t tx_index = _tx_tail; for (uint8_t i = 0; i < _tx_count; ++i) { const QueuedTransmit& queued_tx = _tx_queue[tx_index]; - if (!queued_tx.started) _seen_packets.clear(&queued_tx.packet); + if (!queued_tx.started && !queued_tx.diagnostic) _seen_packets.clear(&queued_tx.packet); tx_index = static_cast((tx_index + 1) % TX_QUEUE_DEPTH); } portENTER_CRITICAL(&_tx_mux); @@ -270,25 +317,20 @@ void ESPNowBridge::end() { // Update bridge state _initialized = false; + _debug_dirty.store(true, std::memory_order_relaxed); + emitDebug(); } void ESPNowBridge::loop() { - if (!_initialized) return; + if (!_initialized) { emitDebug(); return; } pumpTransmitQueue(); - if (!_initialized) return; + if (!_initialized) { emitDebug(); return; } uint8_t frame[MAX_ESPNOW_PACKET_SIZE]; uint8_t source[mesh::espnow::ESPNOW_RAW_SOURCE_MAC_SIZE]; for (uint8_t processed = 0; processed < RX_QUEUE_DEPTH; ++processed) { - // Reserve a mesh slot before removing a callback frame. Even a completing - // raw fragment must remain queued until the reconstructed packet can live. - mesh::Packet* packet = _mgr->allocNew(); - if (packet == nullptr) break; size_t frame_len = 0; - uint32_t dropped = 0; - portENTER_CRITICAL(&_rx_mux); - dropped = _rx_dropped; if (_rx_count > 0) { frame_len = _rx_lengths[_rx_tail]; if (frame_len > 0 && frame_len <= sizeof(frame)) { @@ -297,26 +339,42 @@ void ESPNowBridge::loop() { } else { frame_len = 0; } - _rx_tail = static_cast((_rx_tail + 1) % RX_QUEUE_DEPTH); - _rx_count--; } portEXIT_CRITICAL(&_rx_mux); + if (frame_len == 0) break; - if (dropped != _rx_dropped_reported) { - BRIDGE_DEBUG_PRINTLN("RX queue full, dropped=%lu\n", - (unsigned long)dropped); - _rx_dropped_reported = dropped; - } - if (frame_len == 0) { _mgr->free(packet); break; } - if (!processReceivedFrame(packet, source, frame, frame_len)) { - _mgr->free(packet); + const bool diagnostic = mesh::bridge::diag::isProbeCandidate(frame, frame_len); + // Diagnostic frames never consume a mesh slot, even under pool pressure. + // Ordinary frames remain queued until an allocation succeeds. + mesh::Packet* packet = diagnostic ? nullptr : _mgr->allocNew(); + if (!diagnostic && packet == nullptr) break; + portENTER_CRITICAL(&_rx_mux); + _rx_tail = static_cast((_rx_tail + 1) % RX_QUEUE_DEPTH); + _rx_count--; + portEXIT_CRITICAL(&_rx_mux); + + if (diagnostic) { + mesh::bridge::diag::Probe probe; + const bool valid = mesh::bridge::diag::decodeProbe(frame, frame_len, probe); + portENTER_CRITICAL(&_rx_mux); + if (valid) { + mesh::bridge::diag::increment(_stats.probe.rx_ok); + _stats.probe.last_rx_nonce = probe.nonce; + } else { + mesh::bridge::diag::increment(_stats.probe.rx_bad); + } + portEXIT_CRITICAL(&_rx_mux); + _debug_dirty.store(true, std::memory_order_relaxed); + continue; // Never decode, echo, deduplicate, or relay a probe as MeshCore. } + if (!processReceivedFrame(packet, source, frame, frame_len)) _mgr->free(packet); } + emitDebug(); } bool ESPNowBridge::queueTransmitFrames( const mesh::espnow::ESPNowRawFrames& frames, - const mesh::Packet& packet) { + const mesh::Packet& packet, bool diagnostic) { if (frames.count == 0 || frames.count > mesh::espnow::ESPNOW_RAW_FRAGMENT_COUNT) { return false; } @@ -332,15 +390,22 @@ bool ESPNowBridge::queueTransmitFrames( if (_tx_count < TX_QUEUE_DEPTH) { QueuedTransmit& queued_tx = _tx_queue[_tx_head]; queued_tx.frames = frames; - queued_tx.packet = packet; + if (!diagnostic) queued_tx.packet = packet; queued_tx.next_frame = 0; queued_tx.started = false; queued_tx.start_retries = 0; + queued_tx.diagnostic = diagnostic; + if (diagnostic) mesh::bridge::diag::increment(_stats.probe.tx_queued); + else mesh::bridge::diag::increment(_stats.tx.queued); + _debug_dirty.store(true, std::memory_order_relaxed); _tx_head = static_cast((_tx_head + 1) % TX_QUEUE_DEPTH); _tx_count++; queued = true; } else { _tx_dropped++; + if (diagnostic) mesh::bridge::diag::increment(_stats.probe.tx_fail); + else mesh::bridge::diag::increment(_stats.tx.drops); + _debug_dirty.store(true, std::memory_order_relaxed); } portEXIT_CRITICAL(&_tx_mux); return queued; @@ -360,8 +425,14 @@ void ESPNowBridge::pumpTransmitQueue() { portENTER_CRITICAL(&_tx_mux); timed_out = _tx_waiting && !_tx_callback_done && static_cast(now - _tx_started_at) >= TX_CALLBACK_TIMEOUT_MS; + if (timed_out) { + if (_tx_count > 0 && _tx_queue[_tx_tail].diagnostic) + mesh::bridge::diag::increment(_stats.probe.tx_timeout); + else mesh::bridge::diag::increment(_stats.tx.callback_timeout); + } portEXIT_CRITICAL(&_tx_mux); if (timed_out) { + recordError(mesh::bridge::diag::Stage::TxTimeout, ESP_ERR_TIMEOUT); // A completion carries no frame identity. Continuing after timeout could // mistake a late callback for the next fragment. Tear down that SDK session // before accepting another frame; never transmit an orphan sibling. @@ -391,13 +462,14 @@ void ESPNowBridge::pumpTransmitQueue() { (_tx_tail + 1) % TX_QUEUE_DEPTH); _tx_count--; } - } else if (queued_tx.start_retries < TX_MAX_START_RETRIES) { + } else if (!queued_tx.diagnostic && queued_tx.start_retries < TX_MAX_START_RETRIES) { // This completion is definite, unlike a missing callback. Retry the // same frame within the shared start/callback budget; its sibling // cannot be submitted until this frame succeeds. ++queued_tx.start_retries; _tx_retry_at = now + TX_RETRY_DELAY_MS; } else { + if (!queued_tx.diagnostic) mesh::bridge::diag::increment(_stats.tx.drops); _tx_tail = static_cast((_tx_tail + 1) % TX_QUEUE_DEPTH); _tx_count--; } @@ -430,6 +502,7 @@ void ESPNowBridge::pumpTransmitQueue() { _tx_dropped_reported = dropped; } if (completed && completed_status != ESP_NOW_SEND_SUCCESS) { + recordError(mesh::bridge::diag::Stage::TxCallback, completed_status); BRIDGE_DEBUG_PRINTLN("TX callback failed, status=%d\n", completed_status); } @@ -440,23 +513,27 @@ void ESPNowBridge::pumpTransmitQueue() { const esp_err_t result = esp_now_send( broadcast_address, frame, frame_len); if (result != ESP_OK) { + recordError(mesh::bridge::diag::Stage::TxStart, result); portENTER_CRITICAL(&_tx_mux); _tx_waiting = false; _tx_callback_done = false; if (_tx_count > 0) { QueuedTransmit& queued_tx = _tx_queue[_tx_tail]; - if (result == ESP_ERR_ESPNOW_NO_MEM + if (queued_tx.diagnostic) mesh::bridge::diag::increment(_stats.probe.tx_fail); + else mesh::bridge::diag::increment(_stats.tx.start_fail); + if (!queued_tx.diagnostic && result == ESP_ERR_ESPNOW_NO_MEM && queued_tx.start_retries < TX_MAX_START_RETRIES) { ++queued_tx.start_retries; _tx_retry_at = now + TX_RETRY_DELAY_MS; } else { - if (!queued_tx.started) { + if (!queued_tx.started && !queued_tx.diagnostic) { unsent_packet = queued_tx.packet; clear_unsent_seen = true; } _tx_tail = static_cast((_tx_tail + 1) % TX_QUEUE_DEPTH); _tx_count--; _tx_retry_at = 0; + if (!queued_tx.diagnostic) mesh::bridge::diag::increment(_stats.tx.drops); } } portEXIT_CRITICAL(&_tx_mux); @@ -466,15 +543,21 @@ void ESPNowBridge::pumpTransmitQueue() { BRIDGE_DEBUG_PRINTLN("TX failed to start, error=%d\n", (int)result); } else { portENTER_CRITICAL(&_tx_mux); - if (_tx_count > 0) _tx_queue[_tx_tail].started = true; + if (_tx_count > 0) { + _tx_queue[_tx_tail].started = true; + if (_tx_queue[_tx_tail].diagnostic) mesh::bridge::diag::increment(_stats.probe.tx_start); + else mesh::bridge::diag::increment(_stats.tx.start_ok); + } portEXIT_CRITICAL(&_tx_mux); } + _debug_dirty.store(true, std::memory_order_relaxed); } bool ESPNowBridge::xorCrypt(uint8_t *data, size_t len) { size_t keyLen = 0; while (keyLen < sizeof(_prefs->bridge_secret) && _prefs->bridge_secret[keyLen] != 0) keyLen++; if (keyLen == 0 || keyLen == sizeof(_prefs->bridge_secret)) { + recordError(mesh::bridge::diag::Stage::Secret, ESP_ERR_INVALID_ARG); BRIDGE_DEBUG_PRINTLN("Invalid empty or unterminated bridge secret\n"); return false; } @@ -487,28 +570,37 @@ bool ESPNowBridge::xorCrypt(uint8_t *data, size_t len) { void ESPNowBridge::receiveMeshPacket(mesh::Packet* pkt, const uint8_t *data, size_t len) { if (pkt->readFrom(data, len)) { + noteRx(&mesh::bridge::diag::RxStats::packet_ok); onPacketReceived(pkt); } else { + noteRx(&mesh::bridge::diag::RxStats::packet_bad); _mgr->free(pkt); } } void ESPNowBridge::queueReceivedFrame(const uint8_t *mac, const uint8_t *data, int len) { + portENTER_CRITICAL(&_rx_mux); + mesh::bridge::diag::increment(_stats.rx.frames); + _debug_dirty.store(true, std::memory_order_relaxed); if (data == nullptr || len <= 0 || len > MAX_ESPNOW_PACKET_SIZE) { + mesh::bridge::diag::increment(_stats.rx.badframe); + portEXIT_CRITICAL(&_rx_mux); return; } // Wrapped deployments share the WiFi channel with unrelated ESP-NOW users. // Reject obvious foreign traffic before it can occupy a queue slot. - if (_active_format == mesh::bridge::ESPNOW_FORMAT_WRAPPED + if (!mesh::bridge::diag::isProbeCandidate(data, static_cast(len)) + && _active_format == mesh::bridge::ESPNOW_FORMAT_WRAPPED && (len < BRIDGE_MAGIC_SIZE || data[0] != static_cast(BRIDGE_PACKET_MAGIC >> 8) || data[1] != static_cast(BRIDGE_PACKET_MAGIC & 0xFF))) { + mesh::bridge::diag::increment(_stats.rx.foreign); + portEXIT_CRITICAL(&_rx_mux); return; } - portENTER_CRITICAL(&_rx_mux); if (_rx_count < RX_QUEUE_DEPTH) { memcpy(_rx_buffers[_rx_head], data, static_cast(len)); _rx_lengths[_rx_head] = static_cast(len); @@ -523,6 +615,7 @@ void ESPNowBridge::queueReceivedFrame(const uint8_t *mac, const uint8_t *data, _rx_count++; } else { _rx_dropped++; + mesh::bridge::diag::increment(_stats.rx.queue_drop); } portEXIT_CRITICAL(&_rx_mux); } @@ -530,6 +623,7 @@ void ESPNowBridge::queueReceivedFrame(const uint8_t *mac, const uint8_t *data, bool ESPNowBridge::processReceivedFrame(mesh::Packet* packet_slot, const uint8_t *mac, const uint8_t *data, size_t len) { if (data == nullptr || len == 0 || len > MAX_ESPNOW_PACKET_SIZE) { + noteRx(&mesh::bridge::diag::RxStats::badframe); return false; } @@ -551,6 +645,7 @@ bool ESPNowBridge::processReceivedFrame(mesh::Packet* packet_slot, const uint8_t } else if (result == mesh::espnow::ESPNowRawReassemblyResult::REJECTED || result == mesh::espnow::ESPNowRawReassemblyResult::OUTPUT_TOO_SMALL) { + noteRx(&mesh::bridge::diag::RxStats::badframe); BRIDGE_DEBUG_PRINTLN("RX raw fragment rejected, result=%u len=%u\n", (unsigned)result, (unsigned)len); } @@ -560,6 +655,7 @@ bool ESPNowBridge::processReceivedFrame(mesh::Packet* packet_slot, const uint8_t // Wrapped mode is strict: ignore packets too small to contain its header // and checksum rather than trying to auto-detect raw MeshCore traffic. if (len < (BRIDGE_MAGIC_SIZE + BRIDGE_CHECKSUM_SIZE)) { + noteRx(&mesh::bridge::diag::RxStats::badframe); BRIDGE_DEBUG_PRINTLN("RX packet too small, len=%u\n", (unsigned)len); return false; } @@ -567,6 +663,7 @@ bool ESPNowBridge::processReceivedFrame(mesh::Packet* packet_slot, const uint8_t // Check packet header magic uint16_t received_magic = (data[0] << 8) | data[1]; if (received_magic != BRIDGE_PACKET_MAGIC) { + noteRx(&mesh::bridge::diag::RxStats::foreign); BRIDGE_DEBUG_PRINTLN("RX invalid magic 0x%04X\n", received_magic); return false; } @@ -584,6 +681,7 @@ bool ESPNowBridge::processReceivedFrame(mesh::Packet* packet_slot, const uint8_t const size_t payloadLen = encryptedDataLen - BRIDGE_CHECKSUM_SIZE; if (!validateChecksum(decrypted + BRIDGE_CHECKSUM_SIZE, payloadLen, received_checksum)) { + noteRx(&mesh::bridge::diag::RxStats::checksum_bad); // Failed to decrypt - likely from a different network BRIDGE_DEBUG_PRINTLN("RX checksum mismatch, rcv=0x%04X\n", received_checksum); return false; @@ -597,26 +695,38 @@ bool ESPNowBridge::processReceivedFrame(mesh::Packet* packet_slot, const uint8_t void ESPNowBridge::onDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) { (void)mac_addr; portENTER_CRITICAL(&_tx_mux); - if (_tx_waiting) { + if (_tx_waiting && !_tx_callback_done) { _tx_callback_status = static_cast(status); _tx_callback_done = true; + if (_tx_count > 0 && _tx_queue[_tx_tail].diagnostic) { + if (status == ESP_NOW_SEND_SUCCESS) mesh::bridge::diag::increment(_stats.probe.tx_ok); + else mesh::bridge::diag::increment(_stats.probe.tx_fail); + } else { + if (status == ESP_NOW_SEND_SUCCESS) mesh::bridge::diag::increment(_stats.tx.callback_ok); + else mesh::bridge::diag::increment(_stats.tx.callback_fail); + } + _debug_dirty.store(true, std::memory_order_relaxed); } portEXIT_CRITICAL(&_tx_mux); } void ESPNowBridge::sendPacket(mesh::Packet *packet) { + using mesh::bridge::diag::TxStats; + noteTx(&TxStats::requested); // Guard against uninitialized state if (_initialized == false) { + noteTx(&TxStats::drops); return; } // First validate the packet pointer if (!packet) { + noteTx(&TxStats::drops); BRIDGE_DEBUG_PRINTLN("TX invalid packet pointer\n"); return; } - if (!allowsPacket(packet)) return; + if (!allowsPacket(packet)) { noteTx(&TxStats::filtered); return; } // Core OTA forwarding already bounds repeated requests and rejects longer // downstream echoes. Do not permanently suppress its byte-identical retry. @@ -628,6 +738,7 @@ void ESPNowBridge::sendPacket(mesh::Packet *packet) { mesh::bridge::espNowMaxMeshPacketSize(_active_format); if (expectedMeshPacketLen < 0 || (size_t)expectedMeshPacketLen > maxPayload) { + noteTx(&TxStats::oversize); BRIDGE_DEBUG_PRINTLN("TX packet too large (payload=%d, max=%u)\n", expectedMeshPacketLen, (unsigned)maxPayload); return; @@ -636,6 +747,7 @@ void ESPNowBridge::sendPacket(mesh::Packet *packet) { uint8_t buffer[MAX_TRANS_UNIT]; uint16_t meshPacketLen = packet->writeTo(buffer); if (meshPacketLen != (uint16_t)expectedMeshPacketLen) { + noteTx(&TxStats::drops); BRIDGE_DEBUG_PRINTLN("TX packet length mismatch (actual=%d, expected=%d)\n", meshPacketLen, expectedMeshPacketLen); return; @@ -655,6 +767,7 @@ void ESPNowBridge::sendPacket(mesh::Packet *packet) { buffer[3] = checksum & 0xFF; if (!xorCrypt(buffer + BRIDGE_MAGIC_SIZE, meshPacketLen + BRIDGE_CHECKSUM_SIZE)) { + noteTx(&TxStats::drops); return; } totalPacketSize = packetOffset + meshPacketLen; @@ -678,8 +791,11 @@ void ESPNowBridge::sendPacket(mesh::Packet *packet) { mesh::bridge::espNowFormatName(_active_format), meshPacketLen, (unsigned)frames.count); } else { + if (!encoded) noteTx(&TxStats::drops); BRIDGE_DEBUG_PRINTLN("TX queue/encode failed!\n"); } + } else { + noteTx(&TxStats::duplicate); } } @@ -687,4 +803,177 @@ void ESPNowBridge::onPacketReceived(mesh::Packet *packet) { handleReceivedPacket(packet); } +void ESPNowBridge::noteRx(uint32_t mesh::bridge::diag::RxStats::* field) { + portENTER_CRITICAL(&_rx_mux); + mesh::bridge::diag::increment(_stats.rx.*field); + portEXIT_CRITICAL(&_rx_mux); + _debug_dirty.store(true, std::memory_order_relaxed); +} + +void ESPNowBridge::noteTx(uint32_t mesh::bridge::diag::TxStats::* field) { + portENTER_CRITICAL(&_tx_mux); + mesh::bridge::diag::increment(_stats.tx.*field); + portEXIT_CRITICAL(&_tx_mux); + _debug_dirty.store(true, std::memory_order_relaxed); +} + +void ESPNowBridge::onIngressResult(IngressResult result) { + using mesh::bridge::diag::RxStats; + if (result == IngressResult::Queued) noteRx(&RxStats::delivered); + else if (result == IngressResult::Duplicate) noteRx(&RxStats::duplicate); + else noteRx(&RxStats::filtered); +} + +mesh::bridge::diag::Stats ESPNowBridge::snapshotStats() { + portENTER_CRITICAL(&_rx_mux); + portENTER_CRITICAL(&_tx_mux); + const mesh::bridge::diag::Stats snapshot = _stats; + portEXIT_CRITICAL(&_tx_mux); + portEXIT_CRITICAL(&_rx_mux); + return snapshot; +} + +void ESPNowBridge::recordError(mesh::bridge::diag::Stage stage, int32_t code) { + portENTER_CRITICAL(&_tx_mux); + _stats.error.stage = stage; + _stats.error.code = code; + _stats.error.at_ms = millis(); + portEXIT_CRITICAL(&_tx_mux); + _debug_dirty.store(true, std::memory_order_relaxed); +} + +void ESPNowBridge::resetStats() { + portENTER_CRITICAL(&_rx_mux); + portENTER_CRITICAL(&_tx_mux); + _stats = mesh::bridge::diag::Stats{}; + _rx_dropped = _rx_dropped_reported = 0; + _tx_dropped = _tx_dropped_reported = 0; + portEXIT_CRITICAL(&_tx_mux); + portEXIT_CRITICAL(&_rx_mux); + _debug_dirty.store(true, std::memory_order_relaxed); +} + +bool ESPNowBridge::sendTest(uint32_t nonce) { + using namespace mesh::bridge::diag; + if (!_initialized) { + recordError(Stage::TestQueue, ESP_ERR_INVALID_STATE); + return false; + } + mesh::espnow::ESPNowRawFrames frames; + Probe probe; + probe.nonce = nonce; + probe.format = _active_format; + probe.channel = _prefs->bridge_channel; + if (!encodeProbe(frames.data[0], sizeof(frames.data[0]), probe)) { + recordError(Stage::TestQueue, ESP_ERR_INVALID_ARG); + return false; + } + frames.count = 1; + frames.lengths[0] = ProbeSize; + const mesh::Packet unused_packet; + if (!queueTransmitFrames(frames, unused_packet, true)) { + recordError(Stage::TestQueue, ESP_ERR_ESPNOW_NO_MEM); + return false; + } + portENTER_CRITICAL(&_tx_mux); + _stats.probe.last_tx_nonce = nonce; + portEXIT_CRITICAL(&_tx_mux); + return true; +} + +void ESPNowBridge::formatStatus(char* reply, size_t reply_size) { + uint8_t channel = 0, protocols = 0; + wifi_second_chan_t secondary = WIFI_SECOND_CHAN_NONE; + wifi_mode_t mode = WIFI_MODE_NULL; + wifi_ps_type_t power_save = WIFI_PS_NONE; + const bool channel_ok = esp_wifi_get_channel(&channel, &secondary) == ESP_OK; + const bool mode_ok = esp_wifi_get_mode(&mode) == ESP_OK; + const bool ps_ok = esp_wifi_get_ps(&power_save) == ESP_OK; + (void)esp_wifi_get_protocol(WIFI_IF_STA, &protocols); + uint8_t rx_depth, tx_depth; + portENTER_CRITICAL(&_rx_mux); rx_depth = _rx_count; portEXIT_CRITICAL(&_rx_mux); + portENTER_CRITICAL(&_tx_mux); tx_depth = _tx_count; portEXIT_CRITICAL(&_tx_mux); + const auto stats = snapshotStats(); + const char* state = !_initialized ? (_sdk_teardown_failed ? "teardown-error" : "off") + : (!channel_ok || !mode_ok || !(mode & WIFI_MODE_STA)) ? "driver-error" + : (channel != _prefs->bridge_channel) ? "channel-mismatch" : "ready"; + snprintf(reply, reply_size, + "> %s ch=%u/%u fmt=%s src=%s wifi=%s mode=%d ps=%d proto=%02X q=%u/%u last=%s/%ld", + state, (unsigned)_prefs->bridge_channel, (unsigned)(channel_ok ? channel : 0), + mesh::bridge::espNowFormatName(_initialized ? _active_format : _prefs->bridge_format), + _prefs->bridge_pkt_src ? "rx" : "tx", + (mesh::wireless::control().enabled() & mesh::wireless::WiFi) ? "on" : "off", + mode_ok ? static_cast(mode) : -1, ps_ok ? static_cast(power_save) : -1, + (unsigned)protocols, (unsigned)rx_depth, (unsigned)tx_depth, + mesh::bridge::diag::stageName(stats.error.stage), (long)stats.error.code); +} + +void ESPNowBridge::formatStats(const char* page, char* reply, size_t reply_size) { + const auto s = snapshotStats(); + if (page == nullptr || page[0] == 0) { + snprintf(reply, reply_size, "> 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.callback_ok); + } else if (strcmp(page, "rx") == 0) { + snprintf(reply, reply_size, "> frames=%lu decoded=%lu mesh=%lu crc=%lu bad=%lu parse=%lu", + (unsigned long)s.rx.frames, (unsigned long)s.rx.packet_ok, + (unsigned long)s.rx.delivered, (unsigned long)s.rx.checksum_bad, + (unsigned long)s.rx.badframe, (unsigned long)s.rx.packet_bad); + } else if (strcmp(page, "tx") == 0) { + snprintf(reply, reply_size, "> req=%lu queued=%lu start=%lu ok=%lu err=%lu cbfail=%lu timeout=%lu", + (unsigned long)s.tx.requested, (unsigned long)s.tx.queued, + (unsigned long)s.tx.start_ok, (unsigned long)s.tx.callback_ok, + (unsigned long)s.tx.start_fail, (unsigned long)s.tx.callback_fail, + (unsigned long)s.tx.callback_timeout); + } else if (strcmp(page, "drops") == 0) { + snprintf(reply, reply_size, "> rxq=%lu foreign=%lu filter=%lu dupe=%lu txq=%lu txfilter=%lu txdupe=%lu big=%lu", + (unsigned long)s.rx.queue_drop, (unsigned long)s.rx.foreign, + (unsigned long)s.rx.filtered, (unsigned long)s.rx.duplicate, + (unsigned long)s.tx.drops, (unsigned long)s.tx.filtered, + (unsigned long)s.tx.duplicate, (unsigned long)s.tx.oversize); + } else if (strcmp(page, "test") == 0) { + snprintf(reply, reply_size, "> queued=%lu start=%lu ok=%lu fail=%lu timeout=%lu rx=%lu bad=%lu txid=%08lX rxid=%08lX", + (unsigned long)s.probe.tx_queued, (unsigned long)s.probe.tx_start, + (unsigned long)s.probe.tx_ok, (unsigned long)s.probe.tx_fail, + (unsigned long)s.probe.tx_timeout, (unsigned long)s.probe.rx_ok, + (unsigned long)s.probe.rx_bad, (unsigned long)s.probe.last_tx_nonce, + (unsigned long)s.probe.last_rx_nonce); + } else { + snprintf(reply, reply_size, "Error: use get espnow.stats [rx|tx|drops|test]"); + } +} + +void ESPNowBridge::emitDebug() { +#if defined(ARDUINO) + if (!mesh::isUsbDebugLoggingEnabled()) { _debug_was_enabled = false; return; } + if (!_debug_was_enabled) _debug_dirty.store(true, std::memory_order_relaxed); + _debug_was_enabled = true; + const uint32_t now = millis(); + if (static_cast(now - _debug_last_at) < 1000 + || !_debug_dirty.exchange(false, std::memory_order_relaxed)) return; + _debug_last_at = now; + char status[157]; + formatStatus(status, sizeof(status)); + const auto s = snapshotStats(); +#if MESH_ESP32_USB_CONSOLE_COOPERATIVE + mesh::nrf52DebugPrintf("ESPNOW: %s rx=%lu mesh=%lu crc=%lu dup=%lu tx=%lu ok=%lu test.rx=%08lX\n", + status + 2, (unsigned long)s.rx.frames, (unsigned long)s.rx.delivered, + (unsigned long)s.rx.checksum_bad, (unsigned long)s.rx.duplicate, + (unsigned long)s.tx.queued, (unsigned long)s.tx.callback_ok, + (unsigned long)s.probe.last_rx_nonce); +#else + char line[256]; + const int size = snprintf(line, sizeof(line), + "ESPNOW: %s rx=%lu mesh=%lu crc=%lu dup=%lu tx=%lu ok=%lu test.rx=%08lX\n", + status + 2, (unsigned long)s.rx.frames, (unsigned long)s.rx.delivered, + (unsigned long)s.rx.checksum_bad, (unsigned long)s.rx.duplicate, + (unsigned long)s.tx.queued, (unsigned long)s.tx.callback_ok, + (unsigned long)s.probe.last_rx_nonce); + if (size > 0 && static_cast(size) < sizeof(line) + && mesh::usbLoggingPort().availableForWrite() >= size) + mesh::usbLoggingPort().write(reinterpret_cast(line), size); +#endif +#endif +} + #endif diff --git a/src/helpers/bridges/ESPNowBridge.h b/src/helpers/bridges/ESPNowBridge.h index b574baa3c..0174007c3 100644 --- a/src/helpers/bridges/ESPNowBridge.h +++ b/src/helpers/bridges/ESPNowBridge.h @@ -7,6 +7,8 @@ #include "helpers/ESPNowRawFragmentation.h" #include "helpers/bridges/BridgeBase.h" #include "helpers/bridges/ESPNowBridgeFormat.h" +#include "helpers/bridges/ESPNowBridgeDiagnostics.h" +#include #ifdef WITH_ESPNOW_BRIDGE @@ -106,6 +108,7 @@ private: uint8_t next_frame; bool started; uint8_t start_retries; + bool diagnostic; }; QueuedTransmit _tx_queue[TX_QUEUE_DEPTH]; portMUX_TYPE _tx_mux = portMUX_INITIALIZER_UNLOCKED; @@ -129,6 +132,17 @@ private: // Snapshotted by begin() and immutable until end(), so callbacks and sends // never observe a partially applied preference change. uint8_t _active_format; + mesh::bridge::diag::Stats _stats; + std::atomic _debug_dirty{true}; + uint32_t _debug_last_at = 0; + bool _debug_was_enabled = false; + + mesh::bridge::diag::Stats snapshotStats(); + void noteRx(uint32_t mesh::bridge::diag::RxStats::* field); + void noteTx(uint32_t mesh::bridge::diag::TxStats::* field); + void recordError(mesh::bridge::diag::Stage stage, int32_t code); + void emitDebug(); + void onIngressResult(IngressResult result) override; /** * Performs XOR encryption/decryption of data @@ -162,7 +176,7 @@ private: /** Atomically append one logical packet's one or two transport frames. */ bool queueTransmitFrames(const mesh::espnow::ESPNowRawFrames& frames, - const mesh::Packet& packet); + const mesh::Packet& packet, bool diagnostic = false); /** Submit at most one queued frame after the previous send callback. */ void pumpTransmitQueue(); @@ -227,6 +241,13 @@ public: * @param packet The mesh packet to transmit */ void sendPacket(mesh::Packet *packet) override; + + // Runtime diagnostics work in ordinary firmware, without BRIDGE_DEBUG. + // All output is bounded and generated on the main loop, never a callback. + void formatStatus(char* reply, size_t reply_size); + void formatStats(const char* page, char* reply, size_t reply_size); + bool sendTest(uint32_t nonce); + void resetStats(); }; #endif diff --git a/src/helpers/bridges/ESPNowBridgeDiagnostics.h b/src/helpers/bridges/ESPNowBridgeDiagnostics.h new file mode 100644 index 000000000..8a133bcf8 --- /dev/null +++ b/src/helpers/bridges/ESPNowBridgeDiagnostics.h @@ -0,0 +1,173 @@ +#pragma once + +#include +#include +#include +#include + +namespace mesh { +namespace bridge { +namespace diag { + +// These records have fixed storage and no synchronization or I/O. The bridge +// owns their callback/loop locking. Counters survive bridge stop/start; an +// explicit local reset or reboot starts a new observation window. +struct RxStats { + uint32_t frames = 0, foreign = 0, badframe = 0, queue_drop = 0; + uint32_t checksum_bad = 0, packet_bad = 0, packet_ok = 0; + uint32_t filtered = 0, duplicate = 0, delivered = 0; +}; + +struct TxStats { + uint32_t requested = 0, filtered = 0, duplicate = 0, oversize = 0; + uint32_t queued = 0, start_ok = 0, start_fail = 0; + uint32_t callback_ok = 0, callback_fail = 0, callback_timeout = 0, drops = 0; +}; + +struct ProbeStats { + uint32_t tx_queued = 0, tx_start = 0, tx_ok = 0, tx_fail = 0, tx_timeout = 0; + uint32_t rx_ok = 0, rx_bad = 0, last_tx_nonce = 0, last_rx_nonce = 0; +}; + +enum class Stage : uint8_t { + None, Policy, Channel, ChannelConflict, WiFiInit, WiFiStorage, WiFiMode, + WiFiStart, WiFiProtocol, WiFiChannel, EspNowInit, RecvCallback, SendCallback, + PeerAdd, PeerRate, PeerRemove, EspNowDeinit, TxStart, TxCallback, TxTimeout, + Secret, TestQueue +}; + +inline const char* stageName(Stage stage) { + switch (stage) { + case Stage::None: return "none"; + case Stage::Policy: return "policy"; + case Stage::Channel: return "channel"; + case Stage::ChannelConflict: return "channel.conflict"; + case Stage::WiFiInit: return "wifi.init"; + case Stage::WiFiStorage: return "wifi.storage"; + case Stage::WiFiMode: return "wifi.mode"; + case Stage::WiFiStart: return "wifi.start"; + case Stage::WiFiProtocol: return "wifi.protocol"; + case Stage::WiFiChannel: return "wifi.channel"; + case Stage::EspNowInit: return "espnow.init"; + case Stage::RecvCallback: return "callback.rx"; + case Stage::SendCallback: return "callback.tx"; + case Stage::PeerAdd: return "peer.add"; + case Stage::PeerRate: return "peer.rate"; + case Stage::PeerRemove: return "peer.remove"; + case Stage::EspNowDeinit: return "espnow.deinit"; + case Stage::TxStart: return "tx.start"; + case Stage::TxCallback: return "tx.callback"; + case Stage::TxTimeout: return "tx.timeout"; + case Stage::Secret: return "secret"; + case Stage::TestQueue: return "test.queue"; + } + return "unknown"; +} + +struct Error { + Stage stage = Stage::None; + int32_t code = 0; + uint32_t at_ms = 0; +}; + +struct Stats { + RxStats rx; + TxStats tx; + ProbeStats probe; + Error error; +}; + +static_assert(sizeof(Stats) <= 160, + "ESP-NOW diagnostics must keep bounded counter storage"); + +// Saturation keeps a long-running observation from looking newly empty after +// integer wrap. Call only while the bridge owns the corresponding counter. +inline void increment(uint32_t& value) { + if (value != UINT32_MAX) ++value; +} + +// Reachability-only probe, not a MeshCore packet and not a secret/key test. +// No authentication is implied by the CRC or nonce. Never echo, relay onto +// LoRa, admit to PacketManager, or automatically retry a diagnostic probe. +// +// 0xFE has unsupported MeshCore payload-version bits. Existing raw receivers +// reserve the entire 0xFE prefix and reject this distinct MCD magic; existing +// wrapped receivers reject it because their magic is C0 3E. +// Wire: magic[4], version[1], kind[1], format[1], channel[1], nonce[4], crc[4]. +// Both integers use network byte order; CRC32 covers exactly the first12 bytes. +static constexpr uint8_t ProbeMagic[] = {0xFE, 'M', 'C', 'D'}; +static constexpr uint8_t ProbeVersion = 1; +static constexpr uint8_t ProbeKind = 1; +static constexpr size_t ProbeSize = 16; + +struct Probe { + uint32_t nonce = 0; + uint8_t format = 0; + uint8_t channel = 0; +}; + +inline bool validProbeMetadata(const Probe& probe) { + return probe.format <= 1 && probe.channel >= 1 && probe.channel <= 13; +} + +// Candidate detection is intentionally broader than decoding. Consume a full +// MCD prefix even when its version, length, metadata or CRC is malformed. +inline bool isProbeCandidate(const uint8_t* frame, size_t len) { + return frame != nullptr && len >= sizeof(ProbeMagic) + && memcmp(frame, ProbeMagic, sizeof(ProbeMagic)) == 0; +} + +// No output byte is changed when validation fails. Larger output buffers are +// accepted, but only the fixed16-byte frame is written. +inline bool encodeProbe(uint8_t* output, size_t capacity, const Probe& probe) { + if (output == nullptr || capacity < ProbeSize || !validProbeMetadata(probe)) { + return false; + } + memcpy(output, ProbeMagic, sizeof(ProbeMagic)); + output[4] = ProbeVersion; + output[5] = ProbeKind; + output[6] = probe.format; + output[7] = probe.channel; + mesh::espnow::writeEspNowRawUint32(output + 8, probe.nonce); + mesh::espnow::writeEspNowRawUint32( + output + 12, mesh::espnow::espNowRawCrc32(output, 12)); + return true; +} + +// No output field is changed on rejection, including truncated/oversize input. +inline bool decodeProbe(const uint8_t* frame, size_t len, Probe& output) { + if (len != ProbeSize || !isProbeCandidate(frame, len) + || frame[4] != ProbeVersion || frame[5] != ProbeKind) return false; + Probe decoded; + decoded.format = frame[6]; + decoded.channel = frame[7]; + decoded.nonce = mesh::espnow::readEspNowRawUint32(frame + 8); + if (!validProbeMetadata(decoded) + || mesh::espnow::readEspNowRawUint32(frame + 12) + != mesh::espnow::espNowRawCrc32(frame, 12)) return false; + output = decoded; + return true; +} + +// Exact8 hexadecimal digits; no signs, whitespace, 0x prefix or trailing text. +// Zero is valid. As with the wire decoder, failure preserves the caller's value. +inline bool parseNonce(const char* text, uint32_t& output) { + if (text == nullptr) return false; + uint32_t parsed = 0; + for (size_t i = 0; i < 8; ++i) { + const char c = text[i]; + uint8_t digit; + if (c >= '0' && c <= '9') digit = static_cast(c - '0'); + else if (c >= 'a' && c <= 'f') digit = static_cast(c - 'a' + 10); + else if (c >= 'A' && c <= 'F') digit = static_cast(c - 'A' + 10); + else return false; + parsed = (parsed << 4) | digit; + } + if (text[8] != '\0') return false; + output = parsed; + return true; +} + +} // namespace diag +} // namespace bridge +} // namespace mesh diff --git a/test/fixtures/espnow_bridge_diagnostic_runtime.cpp b/test/fixtures/espnow_bridge_diagnostic_runtime.cpp new file mode 100644 index 000000000..4a213d3bf --- /dev/null +++ b/test/fixtures/espnow_bridge_diagnostic_runtime.cpp @@ -0,0 +1,369 @@ +// Appended to the real bridge source by test_bridge_recovery.code(). Only +// SDK APIs, clocks, Packet allocation and the bounded debug sink are mocked. +namespace diag = mesh::bridge::diag; + +static void startBackend(Backend& backend) { + backend.wifi = true; + mesh::wireless::control().begin(backend); + sdk_initialized = sdk_started = true; + sdk_mode = WIFI_STA; +} + +static void deliver(ESPNowBridge& bridge, const uint8_t* bytes, int len) { + const uint8_t mac[6] = {1, 2, 3, 4, 5, 6}; + mesh::in_sdk_callback = true; +#if ESP_IDF_VERSION_MAJOR >= 5 + const esp_now_recv_info_t info{mac}; + ESPNowBridge::recv_cb(&info, bytes, len); +#else + ESPNowBridge::recv_cb(mac, bytes, len); +#endif + mesh::in_sdk_callback = false; + (void)bridge; +} + +static void deliverCompletion(ESPNowBridge& bridge, int status) { + mesh::in_sdk_callback = true; +#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 5, 0) + const uint8_t mac[6] = {255, 255, 255, 255, 255, 255}; + const esp_now_send_info_t info{mac}; + ESPNowBridge::send_cb(&info, static_cast(status)); +#else + ESPNowBridge::send_cb(nullptr, static_cast(status)); +#endif + mesh::in_sdk_callback = false; + (void)bridge; +} + +static void receiveProbes() { + Backend backend; + startBackend(backend); + NodePrefs prefs; + mesh::PacketManager mgr; + mesh::RTCClock rtc; + ESPNowBridge bridge(&prefs, &mgr, &rtc); + uint8_t bytes[16]; + assert(diag::encodeProbe(bytes, sizeof(bytes), {0x12345678U, 0, 6})); + mgr.exhausted = true; + for (uint8_t format : {uint8_t(0), uint8_t(1)}) { + prefs.bridge_format = format; + bridge.begin(); + assert(bridge._initialized); + const auto allocations = mgr.allocs; + const auto received = bridge._stats.probe.rx_ok; + deliver(bridge, bytes, sizeof(bytes)); + assert(bridge._stats.probe.rx_ok == received); // callback only copies + bridge.loop(); + assert(bridge._stats.probe.rx_ok == received + 1); + assert(bridge._stats.probe.last_rx_nonce == 0x12345678U); + assert(bridge._rx_count == 0 && mgr.allocs == allocations); + assert(mgr.received.empty() && bridge._seen_packets.ids.empty()); + assert(send_calls == 0 && sent.empty()); // no echo or LoRa admission + bytes[15] ^= 1; + deliver(bridge, bytes, sizeof(bytes)); + bridge.loop(); + bytes[15] ^= 1; + assert(bridge._stats.probe.rx_bad == uint32_t(format + 1)); + assert(bridge._rx_count == 0 && mgr.allocs == allocations); + bridge.end(); + } + assert(bridge._stats.probe.rx_ok == 2 && bridge._stats.probe.rx_bad == 2); +} + +static void probeOneShot() { + Backend backend; + startBackend(backend); + NodePrefs prefs; + mesh::PacketManager mgr; + mesh::RTCClock rtc; + ESPNowBridge bridge(&prefs, &mgr, &rtc); + assert(!bridge.sendTest(1) && send_calls == 0); + bridge.begin(); + assert(bridge.sendTest(0x01020304U)); + assert(send_calls == 0 && mgr.allocs == 0); + bridge.loop(); + assert(send_calls == 1 && sent.size() == 1); + diag::Probe parsed; + assert(diag::decodeProbe(sent[0].data(), sent[0].size(), parsed)); + assert(parsed.nonce == 0x01020304U && parsed.channel == 6 && parsed.format == 1); + deliverCompletion(bridge, ESP_NOW_SEND_FAIL); + bridge.loop(); + assert(bridge._tx_count == 0 && bridge._stats.probe.tx_fail == 1); + for (unsigned i = 0; i < 4; ++i) { now_ms += 20; bridge.loop(); } + assert(send_calls == 1); // callback failure never retries a probe + + send_result = ESP_ERR_ESPNOW_NO_MEM; + assert(bridge.sendTest(2)); + bridge.loop(); + assert(send_calls == 2 && bridge._tx_count == 0); + assert(bridge._stats.probe.tx_fail == 2); + for (unsigned i = 0; i < 4; ++i) { now_ms += 20; bridge.loop(); } + assert(send_calls == 2); // ordinary data retry policy does not apply + + send_result = ESP_OK; + assert(bridge.sendTest(3)); + bridge.loop(); + assert(send_calls == 3 && bridge._tx_waiting); + now_ms += 1000; + bridge.loop(); + assert(bridge._initialized && bridge._tx_count == 0); + assert(send_calls == 3 && bridge._stats.probe.tx_timeout == 1); + assert(bridge._stats.tx.callback_timeout == 0); // probes have separate counters + deliverCompletion(bridge, ESP_NOW_SEND_SUCCESS); + bridge.loop(); + assert(send_calls == 3 && bridge._stats.probe.tx_ok == 0); + assert(bridge._seen_packets.ids.empty() && mgr.allocs == 0); + assert(bridge.sendTest(3)); // a new explicit command may reuse its nonce + bridge.loop(); + deliverCompletion(bridge, ESP_NOW_SEND_SUCCESS); + bridge.loop(); + assert(send_calls == 4 && bridge._stats.probe.tx_ok == 1); + bridge.end(); +} + +static void queueOwnership() { + Backend backend; + startBackend(backend); + NodePrefs prefs; + mesh::PacketManager mgr; + mesh::RTCClock rtc; + ESPNowBridge bridge(&prefs, &mgr, &rtc); + bridge.begin(); + auto normal = packet(1); + bridge.sendPacket(&normal); + assert(bridge.sendTest(0xABCDEF01U)); + bridge.loop(); + assert(send_calls == 1 && sent[0][0] == normal.data[0]); + bridge.loop(); + assert(send_calls == 1); + deliverCompletion(bridge, ESP_NOW_SEND_SUCCESS); + bridge.loop(); + assert(send_calls == 2 && diag::isProbeCandidate(sent[1].data(), sent[1].size())); + deliverCompletion(bridge, ESP_NOW_SEND_SUCCESS); + bridge.loop(); + assert(bridge._tx_count == 0 && bridge._stats.probe.tx_ok == 1); + assert(bridge._seen_packets.ids == std::vector{1}); + assert(mgr.allocs == 0 && mgr.received.empty()); + + auto zero = packet(0); + bridge._seen_packets.markSeen(&zero); + assert(bridge.sendTest(9)); + bridge.end(); + assert(bridge._seen_packets.wasSeen(&zero)); // no fake-packet dedup clear + bridge.begin(); + for (uint8_t id = 10; id < 16; ++id) { + auto p = packet(id); + bridge.sendPacket(&p); + } + assert(bridge._tx_count == 6); + const auto seen = bridge._seen_packets.ids; + assert(!bridge.sendTest(10)); + assert(bridge._tx_count == 6 && bridge._seen_packets.ids == seen); + bridge.end(); +} + +static void admissionCounters() { + Backend backend; + startBackend(backend); + NodePrefs prefs; + mesh::PacketManager mgr; + mesh::RTCClock rtc; + ESPNowBridge bridge(&prefs, &mgr, &rtc); + bridge.begin(); + auto good = packet(1), filtered = packet(2), invalid = packet(0xEE); + deliver(bridge, good.data, good.length); + bridge.loop(); + deliver(bridge, good.data, good.length); + bridge.loop(); + bridge.allowed = false; + deliver(bridge, filtered.data, filtered.length); + bridge.loop(); + bridge.allowed = true; + deliver(bridge, invalid.data, invalid.length); + bridge.loop(); + assert(bridge._stats.rx.delivered == 1 && bridge._stats.rx.duplicate == 1); + assert(bridge._stats.rx.filtered == 1 && bridge._stats.rx.packet_bad == 1); + assert(bridge._stats.rx.packet_ok == 3); + assert(mgr.received == std::vector{1} && mgr.allocs == mgr.frees); + bridge.resetStats(); + auto tx = packet(3), oversize = packet(4, 256); + bridge.sendPacket(&tx); + bridge.sendPacket(&tx); + bridge.allowed = false; + bridge.sendPacket(&filtered); + bridge.allowed = true; + bridge.sendPacket(&oversize); + assert(bridge._stats.tx.requested == 4 && bridge._stats.tx.queued == 1); + assert(bridge._stats.tx.duplicate == 1 && bridge._stats.tx.filtered == 1); + assert(bridge._stats.tx.oversize == 1); + bridge.loop(); + deliverCompletion(bridge, ESP_NOW_SEND_SUCCESS); + bridge.loop(); + assert(bridge._stats.tx.start_ok == 1 && bridge._stats.tx.callback_ok == 1); + bridge.end(); +} + +static void overflowAndReset() { + Backend backend; + startBackend(backend); + NodePrefs prefs; + mesh::PacketManager mgr; + mesh::RTCClock rtc; + ESPNowBridge bridge(&prefs, &mgr, &rtc); + bridge.begin(); + uint8_t probe[16]; + assert(diag::encodeProbe(probe, sizeof(probe), {7, 1, 6})); + for (unsigned i = 0; i < 5; ++i) deliver(bridge, probe, sizeof(probe)); + assert(bridge._rx_count == 4 && bridge._stats.rx.queue_drop == 1); + bridge.loop(); + assert(bridge._stats.probe.rx_ok == 4 && bridge._rx_count == 0); + bridge.end(); + bridge.begin(); + assert(bridge._stats.probe.rx_ok == 4 && bridge._stats.rx.queue_drop == 1); + assert(bridge.sendTest(8)); + bridge.loop(); + assert(bridge._tx_count == 1 && bridge._tx_waiting); + const int writes = send_calls; + bridge.resetStats(); + assert(bridge._initialized && bridge._tx_count == 1 && bridge._tx_waiting); + assert(send_calls == writes && prefs.bridge_channel == 6 && prefs.bridge_format == 1); + assert(bridge._stats.rx.frames == 0 && bridge._stats.probe.rx_ok == 0); + deliverCompletion(bridge, ESP_NOW_SEND_SUCCESS); + bridge.loop(); + assert(bridge._tx_count == 0 && bridge._stats.probe.tx_ok == 1); + bridge.end(); +} + +static void startupErrors() { + Backend backend; + startBackend(backend); + NodePrefs prefs; + mesh::PacketManager mgr; + mesh::RTCClock rtc; + ESPNowBridge bridge(&prefs, &mgr, &rtc); + struct Expected { int failure; diag::Stage stage; }; + for (const auto& row : { + Expected{2, diag::Stage::WiFiProtocol}, {4, diag::Stage::EspNowInit}, + {8, diag::Stage::RecvCallback}, {7, diag::Stage::SendCallback}, + {9, diag::Stage::PeerAdd}, {10, diag::Stage::PeerRate}}) { + failure = row.failure; + bridge.begin(); + assert(!bridge._initialized && bridge._stats.error.stage == row.stage); + assert(bridge._stats.error.code == -1 && !espnow_active); + } + failure = 0; + wifi_channel = 3; + bridge.begin(); + assert(!bridge._initialized && bridge._stats.error.stage == diag::Stage::ChannelConflict); + assert(sdk_started); // failed bridge setup cannot shut down shared WiFi + wifi_channel = 6; + bridge.begin(); + assert(bridge._initialized); + bridge.end(); +} + +static void boundedReplies() { + Backend backend; + startBackend(backend); + NodePrefs prefs; + mesh::PacketManager mgr; + mesh::RTCClock rtc; + ESPNowBridge bridge(&prefs, &mgr, &rtc); + bridge.begin(); + memset(&bridge._stats.rx, 0xFF, sizeof(bridge._stats.rx)); + memset(&bridge._stats.tx, 0xFF, sizeof(bridge._stats.tx)); + memset(&bridge._stats.probe, 0xFF, sizeof(bridge._stats.probe)); + bridge._stats.error = {diag::Stage::ChannelConflict, INT32_MIN, UINT32_MAX}; + for (const char* page : {"rx", "tx", "drops", "test"}) { + char reply[160]; + memset(reply, 0xA5, sizeof(reply)); + bridge.formatStats(page, reply, 157); + assert(memchr(reply, 0, 157) != nullptr); + assert(static_cast(reply[157]) == 0xA5); + assert(strlen(reply) < 157); + printf("%s: %s\n", page, reply); + } + char status[160]; + memset(status, 0xA5, sizeof(status)); + bridge.formatStatus(status, 157); + assert(memchr(status, 0, 157) != nullptr && strlen(status) < 157); + assert(static_cast(status[157]) == 0xA5); + printf("status: %s\n", status); + for (wifi_mode_t mode : {WIFI_AP, WIFI_OFF}) { + sdk_mode = mode; + bridge.formatStatus(status, 157); + assert(strstr(status, "> driver-error ") == status); + assert(strstr(status, "ch=6/6") != nullptr); // matching channel is insufficient + } + sdk_mode = WIFI_AP_STA; + bridge.formatStatus(status, 157); + assert(strstr(status, "> ready ") == status); + sdk_mode = WIFI_STA; + for (size_t capacity : {size_t(0), size_t(1), size_t(2), size_t(10)}) { + char reply[160]; + memset(reply, 0xA5, sizeof(reply)); + bridge.formatStats("tx", reply, capacity); + assert(static_cast(reply[capacity]) == 0xA5); + if (capacity) assert(memchr(reply, 0, capacity) != nullptr); + } + bridge.end(); +} + +static void ownerOnlyLogging() { + Backend backend; + startBackend(backend); + NodePrefs prefs; + mesh::PacketManager mgr; + mesh::RTCClock rtc; + ESPNowBridge bridge(&prefs, &mgr, &rtc); + bridge.begin(); + uint8_t probe[16]; + assert(diag::encodeProbe(probe, sizeof(probe), {1, 1, 6})); + mesh::master_logging = true; + mesh::verbose_logging = false; + deliver(bridge, probe, sizeof(probe)); + bridge.loop(); + assert(mesh::debug_output.empty()); + mesh::master_logging = false; + mesh::verbose_logging = true; + deliver(bridge, probe, sizeof(probe)); + bridge.loop(); + assert(mesh::debug_output.empty()); + mesh::master_logging = mesh::verbose_logging = true; + const auto before = mesh::debug_output.size(); +#if !MESH_ESP32_USB_CONSOLE_COOPERATIVE + mesh::debug_port.capacity = 0; + deliver(bridge, probe, sizeof(probe)); + now_ms += 2000; + bridge.loop(); + assert(mesh::debug_output.size() == before); // full UART never blocks/writes + mesh::debug_port.capacity = 1024; +#endif + deliver(bridge, probe, sizeof(probe)); + assert(mesh::debug_output.size() == before); + now_ms += 2000; + bridge.loop(); + assert(mesh::debug_output.size() > before); + assert(bridge.sendTest(2)); + bridge.loop(); + const auto after_start = mesh::debug_output.size(); + deliverCompletion(bridge, ESP_NOW_SEND_SUCCESS); + assert(mesh::debug_output.size() == after_start); + now_ms += 2000; + bridge.loop(); + assert(mesh::debug_output.size() > after_start); + bridge.end(); +} + +int main(int argc, char** argv) { + assert(argc == 2); + if (!strcmp(argv[1], "rx-probes")) receiveProbes(); + else if (!strcmp(argv[1], "one-shot")) probeOneShot(); + else if (!strcmp(argv[1], "ownership")) queueOwnership(); + else if (!strcmp(argv[1], "admission")) admissionCounters(); + else if (!strcmp(argv[1], "overflow-reset")) overflowAndReset(); + else if (!strcmp(argv[1], "startup")) startupErrors(); + else if (!strcmp(argv[1], "replies")) boundedReplies(); + else if (!strcmp(argv[1], "logging")) ownerOnlyLogging(); + else assert(false); +} diff --git a/test/fixtures/espnow_bridge_diagnostics.cpp b/test/fixtures/espnow_bridge_diagnostics.cpp new file mode 100644 index 000000000..07d05b041 --- /dev/null +++ b/test/fixtures/espnow_bridge_diagnostics.cpp @@ -0,0 +1,242 @@ +#include +#include + +#include +#include +#include +#include +#include + +namespace diag = mesh::bridge::diag; + +static diag::Probe sentinel() { + return {0x76543210U, 0, 6}; +} + +static void unchanged(const diag::Probe& value) { + assert(value.nonce == 0x76543210U && value.format == 0 && value.channel == 6); +} + +static void makeProbe(uint8_t* bytes) { + assert(diag::encodeProbe(bytes, diag::ProbeSize, {0x01234567U, 1, 13})); +} + +static void checksum(uint8_t* bytes) { + mesh::espnow::writeEspNowRawUint32( + bytes + 12, mesh::espnow::espNowRawCrc32(bytes, 12)); +} + +static void roundtrip() { + const uint32_t nonces[] = {0, 1, 0x80000000U, UINT32_MAX, 0x01234567U}; + for (uint8_t format = 0; format <= 1; ++format) { + for (uint8_t channel = 1; channel <= 13; ++channel) { + for (uint32_t nonce : nonces) { + uint8_t bytes[18]; + memset(bytes, 0xA5, sizeof(bytes)); + assert(diag::encodeProbe(bytes + 1, 16, {nonce, format, channel})); + assert(bytes[0] == 0xA5 && bytes[17] == 0xA5); + diag::Probe parsed = sentinel(); + assert(diag::isProbeCandidate(bytes + 1, 16)); + assert(diag::decodeProbe(bytes + 1, 16, parsed)); + assert(parsed.nonce == nonce && parsed.format == format + && parsed.channel == channel); + } + } + } + uint8_t bytes[diag::ProbeSize]; + makeProbe(bytes); + for (uint8_t byte : bytes) printf("%02X", byte); + puts(""); +} + +static void bounds() { + uint8_t bytes[250]; + memset(bytes, 0xA5, sizeof(bytes)); + makeProbe(bytes); + for (size_t length = 0; length <= sizeof(bytes); ++length) { + if (length == diag::ProbeSize) continue; + diag::Probe parsed = sentinel(); + assert(!diag::decodeProbe(bytes, length, parsed)); + unchanged(parsed); + } + diag::Probe parsed = sentinel(); + assert(!diag::decodeProbe(nullptr, diag::ProbeSize, parsed)); + unchanged(parsed); + assert(!diag::isProbeCandidate(nullptr, diag::ProbeSize)); + for (size_t length = 0; length < diag::ProbeSize; ++length) { + memset(bytes, 0xA5, sizeof(bytes)); + assert(!diag::encodeProbe(bytes, length, {1, 1, 1})); + for (uint8_t byte : bytes) assert(byte == 0xA5); + } + assert(!diag::encodeProbe(nullptr, diag::ProbeSize, {1, 1, 1})); +} + +static void metadata() { + const uint8_t invalid_formats[] = {2, 127, 255}; + const uint8_t invalid_channels[] = {0, 14, 127, 255}; + for (uint8_t format : invalid_formats) { + uint8_t bytes[16]; + memset(bytes, 0xA5, sizeof(bytes)); + assert(!diag::encodeProbe(bytes, sizeof(bytes), {0, format, 6})); + for (uint8_t byte : bytes) assert(byte == 0xA5); + makeProbe(bytes); + bytes[6] = format; + checksum(bytes); + diag::Probe parsed = sentinel(); + assert(!diag::decodeProbe(bytes, sizeof(bytes), parsed)); + unchanged(parsed); + } + for (uint8_t channel : invalid_channels) { + uint8_t bytes[16]; + memset(bytes, 0xA5, sizeof(bytes)); + assert(!diag::encodeProbe(bytes, sizeof(bytes), {0, 0, channel})); + for (uint8_t byte : bytes) assert(byte == 0xA5); + makeProbe(bytes); + bytes[7] = channel; + checksum(bytes); + diag::Probe parsed = sentinel(); + assert(!diag::decodeProbe(bytes, sizeof(bytes), parsed)); + unchanged(parsed); + } + for (size_t field : {size_t(4), size_t(5)}) { + for (uint8_t value : {uint8_t(0), uint8_t(2), uint8_t(255)}) { + uint8_t bytes[16]; + makeProbe(bytes); + bytes[field] = value; + checksum(bytes); + diag::Probe parsed = sentinel(); + assert(diag::isProbeCandidate(bytes, sizeof(bytes))); + assert(!diag::decodeProbe(bytes, sizeof(bytes), parsed)); + unchanged(parsed); + } + } +} + +static void corruption() { + uint8_t original[16]; + makeProbe(original); + for (size_t byte = 0; byte < sizeof(original); ++byte) { + for (uint8_t bit = 0; bit < 8; ++bit) { + uint8_t bytes[16]; + memcpy(bytes, original, sizeof(bytes)); + bytes[byte] ^= uint8_t(1U << bit); + diag::Probe parsed = sentinel(); + assert(!diag::decodeProbe(bytes, sizeof(bytes), parsed)); + unchanged(parsed); + } + } +} + +static void candidate() { + uint8_t bytes[250]; + memset(bytes, 0, sizeof(bytes)); + makeProbe(bytes); + for (size_t length = 0; length < 4; ++length) { + assert(!diag::isProbeCandidate(bytes, length)); + } + for (size_t length = 4; length <= sizeof(bytes); ++length) { + assert(diag::isProbeCandidate(bytes, length)); + } + bytes[3] = 'F'; + assert(!diag::isProbeCandidate(bytes, 16)); + assert(memcmp(bytes, mesh::espnow::ESPNOW_RAW_FRAGMENT_MAGIC, 4) == 0); +} + +static void nonce() { + struct Valid { const char* text; uint32_t expected; }; + for (const Valid& valid : {Valid{"00000000", 0}, Valid{"00000001", 1}, + Valid{"ffffffff", UINT32_MAX}, Valid{"ABCDef01", 0xABCDEF01U}, + Valid{"01234567", 0x01234567U}}) { + uint32_t value = 7; + assert(diag::parseNonce(valid.text, value) && value == valid.expected); + } + const char* invalid[] = {nullptr, "", "0", "1234567", "123456789", + "0x123456", " 1234567", "1234567 ", "+1234567", "-1234567", + "1234567g", "12345678x", "12345678\n", "1234 678", "\t1234567"}; + for (const char* text : invalid) { + uint32_t value = 0x89ABCDEFU; + assert(!diag::parseNonce(text, value) && value == 0x89ABCDEFU); + } +} + +static void legacy() { + // These are actual production Packet and raw reassembler implementations. + uint8_t probe[16]; + makeProbe(probe); + mesh::Packet parsed; + assert(!parsed.readFrom(probe, sizeof(probe))); + assert((probe[0] >> PH_VER_SHIFT) > PAYLOAD_VER_1); + assert((uint16_t(probe[0]) << 8 | probe[1]) != WRAPPED_BRIDGE_MAGIC); + mesh::espnow::ESPNowRawReassemblerT<1> raw; + uint8_t output[255]; + uint8_t source[] = {1, 2, 3, 4, 5, 6}; + size_t output_len = 999; + assert(raw.acceptFrame(source, probe, sizeof(probe), 0, output, + sizeof(output), output_len) + == mesh::espnow::ESPNowRawReassemblyResult::REJECTED); + assert(output_len == 0); + + // Rejecting a probe must not disturb a real in-progress raw packet. + mesh::Packet packet; + packet.header = (PAYLOAD_TYPE_RAW_CUSTOM << PH_TYPE_SHIFT) + | ROUTE_TYPE_TRANSPORT_DIRECT; + packet.setPathHashSizeAndCount(2, 32); + packet.payload_len = MAX_PACKET_PAYLOAD; + memset(packet.path, 0x23, sizeof(packet.path)); + memset(packet.payload, 0x42, sizeof(packet.payload)); + uint8_t wire[255]; + const size_t wire_len = packet.writeTo(wire); + assert(wire_len == 254); + mesh::espnow::ESPNowRawFrames frames; + assert(mesh::espnow::encodeEspNowRawFrames(wire, wire_len, frames)); + assert(frames.count == 2); + assert(raw.acceptFrame(source, frames.data[0], frames.lengths[0], 1, + output, sizeof(output), output_len) + == mesh::espnow::ESPNowRawReassemblyResult::FRAGMENT_STORED); + assert(raw.acceptFrame(source, probe, sizeof(probe), 2, + output, sizeof(output), output_len) + == mesh::espnow::ESPNowRawReassemblyResult::REJECTED); + assert(!diag::isProbeCandidate(frames.data[1], frames.lengths[1])); + assert(raw.acceptFrame(source, frames.data[1], frames.lengths[1], 3, + output, sizeof(output), output_len) + == mesh::espnow::ESPNowRawReassemblyResult::PACKET_COMPLETE); + assert(output_len == wire_len && memcmp(output, wire, wire_len) == 0); + assert(parsed.readFrom(output, static_cast(output_len))); +} + +static void counters() { + static_assert(std::is_trivially_copyable::value, + "Snapshots must copy without heap ownership"); + static_assert(sizeof(diag::Stats) <= 160, "Counter storage is bounded"); + diag::Stats stats; + assert(stats.rx.frames == 0 && stats.tx.requested == 0 + && stats.probe.rx_ok == 0 && stats.error.stage == diag::Stage::None); + uint32_t count = UINT32_MAX - 1; + diag::increment(count); + assert(count == UINT32_MAX); + diag::increment(count); + assert(count == UINT32_MAX); + count = 0; + diag::increment(count); + assert(count == 1); + for (uint8_t stage = 0; stage <= static_cast(diag::Stage::TestQueue); + ++stage) { + assert(strcmp(diag::stageName(static_cast(stage)), "unknown") != 0); + } + assert(strcmp(diag::stageName(static_cast(255)), "unknown") == 0); + printf("counter_bytes=%zu\n", sizeof(stats)); +} + +int main(int argc, char** argv) { + assert(argc == 2); + if (!strcmp(argv[1], "roundtrip")) roundtrip(); + else if (!strcmp(argv[1], "bounds")) bounds(); + else if (!strcmp(argv[1], "metadata")) metadata(); + else if (!strcmp(argv[1], "corruption")) corruption(); + else if (!strcmp(argv[1], "candidate")) candidate(); + else if (!strcmp(argv[1], "nonce")) nonce(); + else if (!strcmp(argv[1], "legacy")) legacy(); + else if (!strcmp(argv[1], "counters")) counters(); + else assert(false); + return 0; +} diff --git a/test/fixtures/espnow_wifi_handoff.cpp b/test/fixtures/espnow_wifi_handoff.cpp index d4c9ca9f3..f63db1330 100644 --- a/test/fixtures/espnow_wifi_handoff.cpp +++ b/test/fixtures/espnow_wifi_handoff.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #define ESP_IDF_VERSION_VAL(a,b,c) ((a)*10000+(b)*100+(c)) #define BRIDGE_DEBUG_PRINTLN(...) ((void)0) @@ -156,6 +157,10 @@ struct Backend : mesh::wireless::Backend { }; class Bridge { public: + static constexpr int ESP_ERR_INVALID_STATE=-78,ESP_ERR_INVALID_ARG=-79; + std::atomic _debug_dirty{false}; + void recordError(mesh::bridge::diag::Stage, int32_t) {} + void emitDebug() {} struct Prefs { int bridge_format=mesh::bridge::ESPNOW_FORMAT_RAW; uint8_t bridge_channel=6; } prefs; Prefs* _prefs=&prefs; bool _initialized=false; @@ -163,7 +168,7 @@ public: int _tx_mux=0, _tx_head=0, _tx_tail=0, _tx_count=0, _tx_waiting=0, _tx_callback_done=0; int _tx_callback_status=0, _tx_dropped=0, _tx_dropped_reported=0; mesh::espnow::ESPNowRawReassembler _raw_reassembler; - struct QueuedTransmit { bool started=false; int packet=0; }; + struct QueuedTransmit { bool started=false, diagnostic=false; int packet=0; }; static constexpr int TX_QUEUE_DEPTH=2; QueuedTransmit _tx_queue[TX_QUEUE_DEPTH]; struct { void clear(const int*) {} } _seen_packets; diff --git a/test/test_bridge_recovery.py b/test/test_bridge_recovery.py index 117ea17b4..4d69fe5aa 100644 --- a/test/test_bridge_recovery.py +++ b/test/test_bridge_recovery.py @@ -15,7 +15,10 @@ MOCKS = r''' #include #include #include +#include +#include #include +#include #define MAX_TRANS_UNIT 255 #define PAYLOAD_TYPE_OTA 0x0c using portMUX_TYPE=int; @@ -23,6 +26,11 @@ using portMUX_TYPE=int; struct esp_now_recv_info_t {const uint8_t* src_addr;}; struct esp_now_send_info_t {const uint8_t* des_addr;}; constexpr int ESP_ERR_ESPNOW_NO_MEM=-77; +constexpr int ESP_ERR_INVALID_STATE=-78,ESP_ERR_INVALID_ARG=-79; +constexpr int ESP_ERR_TIMEOUT=-80; +enum wifi_ps_type_t {WIFI_PS_NONE=0,WIFI_PS_MIN_MODEM=1}; +int esp_wifi_get_ps(wifi_ps_type_t* value){*value=WIFI_PS_NONE;return sdk_initialized?ESP_OK:-1;} +int esp_wifi_get_protocol(int,uint8_t* value){*value=15;return sdk_initialized?ESP_OK:-1;} uint32_t now_ms=100; uint32_t millis(){return now_ms;} int send_result=0,send_calls=0; @@ -33,6 +41,23 @@ int esp_now_send(const uint8_t*,const uint8_t* bytes,size_t len){ sent.emplace_back(bytes,bytes+len);return ESP_OK; } namespace mesh { +bool master_logging=false,verbose_logging=false,in_sdk_callback=false; +std::vector debug_output; +bool isUsbDebugLoggingEnabled(){return master_logging&&verbose_logging;} +struct DebugPort { + int capacity=1024; + int availableForWrite()const{return capacity;} + size_t write(const uint8_t* bytes,size_t length){ + assert(!in_sdk_callback&&length<=static_cast(capacity)); + debug_output.emplace_back(reinterpret_cast(bytes),length);return length; + } +} debug_port; +DebugPort& usbLoggingPort(){return debug_port;} +size_t nrf52DebugPrintf(const char* format,...){ + assert(!in_sdk_callback);char output[256];va_list args;va_start(args,format); + const int count=vsnprintf(output,sizeof(output),format,args);va_end(args); + if(count>0)debug_output.emplace_back(output);return count>0?static_cast(count):0; +} struct RTCClock {}; struct Packet { uint8_t data[MAX_TRANS_UNIT]={};uint16_t length=4; @@ -61,6 +86,7 @@ struct PacketManager { struct NodePrefs { int bridge_format=mesh::bridge::ESPNOW_FORMAT_RAW; uint8_t bridge_channel=6;uint32_t bridge_baud=115200,bridge_delay=1; + uint8_t bridge_pkt_src=0; char bridge_secret[32]="fleet-test"; }; struct Seen { @@ -71,6 +97,7 @@ struct Seen { }; class BridgeBase { public: +@INGRESS_HOOK@ static constexpr uint16_t BRIDGE_PACKET_MAGIC=0xc03e; static constexpr uint16_t BRIDGE_MAGIC_SIZE=2,BRIDGE_LENGTH_SIZE=2,BRIDGE_CHECKSUM_SIZE=2; NodePrefs* _prefs;mesh::PacketManager* _mgr;mesh::RTCClock* _rtc; @@ -110,6 +137,10 @@ def code(): sdk = sdk.replace("int esp_now_deinit() { assert(espnow_active); espnow_active=false; return ESP_OK; }", "int esp_now_deinit() { assert(espnow_active); if(failure==18)return -1; espnow_active=false; return ESP_OK; }") base = (ROOT / "src/helpers/bridges/BridgeBase.cpp").read_text() + base_header = (ROOT / "src/helpers/bridges/BridgeBase.h").read_text() + ingress_hook = "#if defined(WITH_ESPNOW_BRIDGE)\n" + ingress_hook += method(base_header, "enum class IngressResult") + ";\n" + ingress_hook += method(base_header, "virtual void onIngressResult(") + "\n#endif\n" base_methods = "\n".join(method(base, signature) for signature in ( "uint16_t BridgeBase::fletcher16(", "bool BridgeBase::validateChecksum(", "void BridgeBase::handleReceivedPacket(")) @@ -119,7 +150,7 @@ def code(): source = (ROOT / f"src/helpers/bridges/{name}.cpp").read_text() headers.append(re.sub(r"^\s*#(?:include|pragma).*?$", "", header, flags=re.MULTILINE).replace("private:", "public:")) sources.append(re.sub(r"^\s*#include.*?$", "", source, flags=re.MULTILINE)) - return sdk + MOCKS + "\n".join(headers) + base_methods + "\n".join(sources) + return sdk + MOCKS.replace("@INGRESS_HOOK@", ingress_hook) + "\n".join(headers) + base_methods + "\n".join(sources) COMMON = r''' diff --git a/test/test_espnow_bridge_diagnostics.py b/test/test_espnow_bridge_diagnostics.py new file mode 100644 index 000000000..6203640b4 --- /dev/null +++ b/test/test_espnow_bridge_diagnostics.py @@ -0,0 +1,182 @@ +#!/usr/bin/env python3 +"""Exercise bounded ESP-NOW diagnostics and actual legacy wire rejection.""" + +from pathlib import Path +import os +import re +import shutil +import subprocess +import sys +import tempfile +import unittest +import zlib + + +ROOT = Path(__file__).resolve().parents[1] + + +class ESPNowBridgeDiagnosticsTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.compiler = os.environ.get("CXX") or shutil.which("g++") or shutil.which("clang++") + if not cls.compiler: + raise RuntimeError("A host C++17 compiler is required") + cls.temporary = tempfile.TemporaryDirectory(prefix="espnow-diagnostics-") + cls.addClassCleanup(cls.temporary.cleanup) + cls.work = Path(cls.temporary.name) + cls.binary = cls.work / "diagnostics" + base = (ROOT / "src/helpers/bridges/BridgeBase.h").read_text(encoding="ascii") + magic = re.findall(r"BRIDGE_PACKET_MAGIC\s*=\s*(0x[0-9A-Fa-f]+)\s*;", base) + if len(magic) != 1: + raise AssertionError("Expected one production wrapped bridge magic") + flags = (["-fsanitize=address,undefined", "-fno-sanitize-recover=all", + "-fno-pie", "-no-pie"] if sys.platform.startswith("linux") else []) + built = subprocess.run([ + cls.compiler, "-std=c++17", "-Wall", "-Wextra", "-Werror", + "-Wno-unused-parameter", *flags, + "-DWRAPPED_BRIDGE_MAGIC=" + magic[0], + "-I" + str(ROOT / "src"), "-I" + str(ROOT / "test/mocks"), + str(ROOT / "test/fixtures/espnow_bridge_diagnostics.cpp"), + str(ROOT / "src/Packet.cpp"), "-o", str(cls.binary), + ], capture_output=True, text=True, timeout=60) + if built.returncode: + raise AssertionError(built.stdout + built.stderr) + + def run_case(self, scenario): + result = subprocess.run([str(self.binary), scenario], capture_output=True, + text=True, timeout=10) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + return result.stdout + + def test_roundtrip_and_independent_wire_crc(self): + wire = bytes.fromhex(self.run_case("roundtrip").strip()) + self.assertEqual(wire[:12], bytes.fromhex("FE4D43440101010D01234567")) + self.assertEqual(int.from_bytes(wire[12:], "big"), zlib.crc32(wire[:12])) + + def test_null_short_and_oversize_inputs_preserve_outputs(self): + self.run_case("bounds") + + def test_semantics_reject_invalid_metadata_with_valid_crc(self): + self.run_case("metadata") + + def test_every_single_bit_corruption_is_rejected(self): + self.run_case("corruption") + + def test_candidates_include_malformed_but_exclude_raw_fragments(self): + self.run_case("candidate") + + def test_nonce_is_exactly_eight_hex_digits(self): + self.run_case("nonce") + + def test_actual_legacy_packet_and_reassembler_reject_probe(self): + self.run_case("legacy") + + def test_fixed_counters_saturate_and_unknown_error_is_safe(self): + self.assertIn("counter_bytes=132", self.run_case("counters")) + + def test_helper_has_no_allocator_sdk_clock_or_output_dependencies(self): + source = self.work / "pure.cpp" + binary = self.work / "pure.o" + source.write_text('''#include +namespace diag = mesh::bridge::diag; +bool encode(uint8_t* out, size_t len, const diag::Probe& probe) { + return diag::encodeProbe(out, len, probe); +} +bool decode(const uint8_t* bytes, size_t len, diag::Probe& probe) { + return diag::decodeProbe(bytes, len, probe); +} +bool nonce(const char* text, uint32_t& value) { + return diag::parseNonce(text, value); +} +''', encoding="ascii") + result = subprocess.run([self.compiler, "-std=c++17", "-O2", "-c", + "-I" + str(ROOT / "src"), str(source), "-o", str(binary)], + capture_output=True, text=True, timeout=30) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + nm = shutil.which("nm") + self.assertIsNotNone(nm, "nm is required for dependency inspection") + symbols = subprocess.run([nm, "-u", str(binary)], capture_output=True, + text=True, timeout=10, check=True).stdout + self.assertNotRegex(symbols, r"(?i)malloc|calloc|realloc|free|_Zn[aw]|esp_|Serial|printf|millis|micros|atomic|mutex") + + +class ESPNowBridgeProductionDiagnosticsTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + from test_bridge_recovery import code, COMMON + cls.compiler = os.environ.get("CXX") or shutil.which("g++") or shutil.which("clang++") + if not cls.compiler: + raise RuntimeError("A host C++17 compiler is required") + cls.temporary = tempfile.TemporaryDirectory(prefix="espnow-production-diagnostics-") + cls.addClassCleanup(cls.temporary.cleanup) + cls.work = Path(cls.temporary.name) + cls.source = cls.work / "production.cpp" + fixture = (ROOT / "test/fixtures/espnow_bridge_diagnostic_runtime.cpp").read_text(encoding="ascii") + cls.source.write_text(code() + COMMON + fixture, encoding="ascii") + cls.binary = cls.build(50200) + + @classmethod + def build(cls, version, cooperative=1): + binary = cls.work / ("production-" + str(version) + "-usb-" + str(cooperative)) + result = subprocess.run([ + cls.compiler, "-std=c++17", "-O1", "-Wall", "-Wextra", + "-fsanitize=address,undefined", "-fno-sanitize-recover=all", + "-fno-omit-frame-pointer", "-fno-pie", "-no-pie", + "-DESP32=1", "-DARDUINO=1", + "-DMESH_ESP32_USB_CONSOLE_COOPERATIVE=" + str(cooperative), + "-DWITH_ESPNOW_BRIDGE=1", "-DWITH_RS232_BRIDGE=1", + "-DESP_IDF_VERSION=" + str(version), + "-DESP_IDF_VERSION_MAJOR=" + str(version // 10000), + "-I" + str(ROOT / "src"), str(cls.source), "-o", str(binary), + ], capture_output=True, text=True, timeout=60) + if result.returncode: + raise AssertionError(result.stdout + result.stderr) + return binary + + def run_case(self, scenario, binary=None): + result = subprocess.run([str(binary or self.binary), scenario], + capture_output=True, text=True, timeout=10) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + return result.stdout + + def test_receive_probes_never_allocate_echo_or_admit_mesh_in_either_format(self): + self.run_case("rx-probes") + + def test_probe_sdk_rejection_callback_failure_and_timeout_never_retry(self): + self.run_case("one-shot") + + def test_probe_and_mesh_queue_order_and_seen_ownership(self): + self.run_case("ownership") + + def test_existing_admission_decisions_drive_exact_counters(self): + self.run_case("admission") + + def test_queue_overflow_restart_persistence_and_reset_preserve_accepted_work(self): + self.run_case("overflow-reset") + + def test_startup_error_stage_and_code_preserve_shared_wifi(self): + self.run_case("startup") + + def test_saturated_pages_and_status_fit_reserved_reply_capacity(self): + reply = self.run_case("replies") + for suffix in ("parse=4294967295", "timeout=4294967295", + "big=4294967295", "rxid=FFFFFFFF", + "last=channel.conflict/-2147483648"): + self.assertIn(suffix, reply) + + def test_callbacks_never_print_and_loop_logging_requires_both_gates(self): + self.run_case("logging") + + def test_uart_logging_has_the_same_owner_gates_and_drops_without_capacity(self): + self.run_case("logging", self.build(50200, cooperative=0)) + + def test_diagnostic_callbacks_support_each_sdk_signature(self): + for version in (40400, 50500): + with self.subTest(idf=version): + binary = self.build(version) + self.run_case("rx-probes", binary) + self.run_case("one-shot", binary) + + +if __name__ == "__main__": + unittest.main() diff --git a/test/test_espnow_diagnostic_cli.py b/test/test_espnow_diagnostic_cli.py new file mode 100644 index 000000000..7f5a28261 --- /dev/null +++ b/test/test_espnow_diagnostic_cli.py @@ -0,0 +1,240 @@ +"""Compile actual ESP-NOW diagnostic dispatch/forwarders with native fakes.""" +from pathlib import Path +import re +import shutil +import subprocess +import tempfile +import unittest + +from test_replay_reset_integration import extract_braced + +ROOT = Path(__file__).resolve().parents[1] + + +class EspNowDiagnosticCliTests(unittest.TestCase): + def compile_run(self, source, flags=()): + compiler = shutil.which("g++") or shutil.which("clang++") + self.assertIsNotNone(compiler) + with tempfile.TemporaryDirectory(prefix="espnow-cli-") as directory: + source_path = Path(directory) / "main.cpp" + binary = Path(directory) / "check" + source_path.write_text(source, encoding="ascii") + subprocess.run([compiler, "-std=c++17", "-Wall", "-Wextra", "-Werror", + "-fsanitize=address,undefined", "-fno-omit-frame-pointer", + "-I", str(ROOT / "src"), *flags, str(source_path), + "-o", str(binary)], check=True, capture_output=True, text=True) + subprocess.run([str(binary)], check=True, capture_output=True, text=True) + + def test_actual_dispatch_strict_local_actions_and_bounded_replies(self): + source = (ROOT / "src/helpers/CommonCLI.cpp").read_text(encoding="ascii") + header = (ROOT / "src/helpers/CommonCLI.h").read_text(encoding="ascii") + body = extract_braced(source, "bool CommonCLI::handleEspNowDiagnosticCommand(") + defaults = "\n".join(extract_braced(header, signature) for signature in ( + "virtual void formatEspNowStatus(", "virtual void formatEspNowStats(", + "virtual bool sendEspNowTest(", "virtual bool resetEspNowStats(")) + self.assertIn("if (handleEspNowDiagnosticCommand(sender_timestamp, command, reply)) return;", source) + self.compile_run(r''' +#include +#include +#include +#include +#include +#include +static uint32_t now_ms = 0x1234ABCD; +uint32_t millis() { return now_ms; } +struct Callbacks { + virtual ~Callbacks() = default; +''' + defaults + r''' +}; +struct Fake : Callbacks { + int statuses = 0, stats = 0, sends = 0, resets = 0; + uint32_t nonce = 0; + size_t capacity = 0; + std::string page; + bool send_result = true, reset_result = true, long_reply = false; + void fill(char* reply, size_t cap, const char* value) { + capacity = cap; + const std::string text = long_reply ? std::string(300, 'x') : value; + snprintf(reply, cap, "%s", text.c_str()); + } + void formatEspNowStatus(char* r, size_t cap) override { + ++statuses; fill(r, cap, "status"); + } + void formatEspNowStats(const char* p, char* r, size_t cap) override { + ++stats; page = p; fill(r, cap, "stats"); + } + bool sendEspNowTest(uint32_t n) override { + ++sends; nonce = n; return send_result; + } + bool resetEspNowStats() override { ++resets; return reset_result; } + int count() const { return statuses + stats + sends + resets; } +}; +struct CommonCLI { + Callbacks* _callbacks; + bool handleEspNowDiagnosticCommand(uint32_t, const char*, char*); +}; +''' + body + r''' +int main() { + Fake callbacks; + CommonCLI cli{&callbacks}; + char reply[160]; + auto command = [&](const char* text, uint32_t sender = 0) { + memset(reply, 'Z', sizeof(reply)); + const bool handled = cli.handleEspNowDiagnosticCommand(sender, text, reply); + assert(reply[157] == 'Z' && reply[158] == 'Z' && reply[159] == 'Z'); + if (handled) assert(memchr(reply, 0, 157) != nullptr); + return handled; + }; + assert(command("get espnow.status", 77)); + assert(callbacks.statuses == 1 && callbacks.capacity == 157); + for (const char* page : {"", "rx", "tx", "drops", "test"}) { + const std::string text = std::string("get espnow.stats") + (*page ? " " : "") + page; + assert(command(text.c_str(), 77)); + assert(callbacks.page == page && callbacks.capacity == 157); + } + callbacks.long_reply = true; + assert(command("get espnow.status")); + assert(strlen(reply) == 156); + assert(command("get espnow.stats rx")); + assert(strlen(reply) == 156); + callbacks.long_reply = false; + for (const char* text : { + "get espnow.status extra", "get espnow.statusx", "get espnow.status ", + "get espnow.statsrx", "get espnow.stats x", "get espnow.stats rx junk", + "get espnow.stats ", "get espnow.stats\trx", "get espnow.stats rx", + "espnow", "espnow testx", "espnow test ", "espnow test 1234567", + "espnow test 123456789", "espnow test 0x123456", "espnow test +1234567", + "espnow test 1234567Z", "espnow test 12345678 ", "espnow test 12345678 x", + "espnow resetstatsx", "espnow resetstats ", "espnow resetstats now"}) { + const int before = callbacks.count(); + assert(command(text)); + assert(strncmp(reply, "Error:", 6) == 0 && callbacks.count() == before); + } + for (const char* text : {"espnowtest", "espnowx test", "get espnow.enabled", "get repeat"}) { + const int before = callbacks.count(); + assert(!command(text)); + assert(callbacks.count() == before); + } + for (uint32_t remote : {1U, UINT32_MAX}) { + for (const char* text : {"espnow test", "espnow test 12345678", "espnow resetstats"}) { + const int before = callbacks.count(); + assert(command(text, remote)); + assert(strstr(reply, "local connection") && callbacks.count() == before); + } + } + assert(command("espnow test")); + assert(callbacks.sends == 1 && callbacks.nonce == now_ms); + assert(strcmp(reply, "OK - test queued id=1234ABCD; confirm on peer") == 0); + assert(command("espnow test 89abcDEF")); + assert(callbacks.sends == 2 && callbacks.nonce == 0x89ABCDEF); + assert(command("espnow test 00000000")); + assert(callbacks.sends == 3 && callbacks.nonce == 0); + callbacks.send_result = false; + assert(command("espnow test DEADBEEF")); + assert(callbacks.sends == 4 && strstr(reply, "not queued")); + assert(command("espnow resetstats")); + assert(callbacks.resets == 1 && strcmp(reply, "OK - ESP-NOW statistics reset") == 0); + callbacks.reset_result = false; + assert(command("espnow resetstats")); + assert(callbacks.resets == 2 && strstr(reply, "unavailable")); + Callbacks unsupported; + cli._callbacks = &unsupported; + assert(command("get espnow.status") && strstr(reply, "unavailable")); + assert(command("get espnow.stats") && strstr(reply, "unavailable")); + assert(command("espnow test") && strstr(reply, "not queued")); + assert(command("espnow resetstats") && strstr(reply, "unavailable")); +} +''') + + def test_actual_role_forwarders_select_only_the_espnow_transport(self): + repeater = (ROOT / "examples/simple_repeater/MyMesh.h").read_text(encoding="ascii") + start = repeater.index("#if defined(WITH_ESPNOW_BRIDGE)\n ESPNowBridge& diagnosticEspNowBridge()") + end = repeater.index(" // Retry ESP-NOW", start) + repeater = repeater[start:end] + "\n#endif\n" + room = (ROOT / "examples/simple_room_server/MyMesh.h").read_text(encoding="ascii") + start = room.index("#if defined(WITH_BRIDGE)\n#if defined(WITH_MQTT_BRIDGE) && defined(WITH_ESPNOW_BRIDGE)\n void formatEspNowStatus(") + end = room.index("\n#endif", start) + len("\n#endif") + room = room[start:end] + "\n#endif\n" + prefix = r''' +#include +#include +#include +#include +struct Base { + virtual void formatEspNowStatus(char*, size_t) {} + virtual void formatEspNowStats(const char*, char*, size_t) {} + virtual bool sendEspNowTest(uint32_t) { return false; } + virtual bool resetEspNowStats() { return false; } +}; +struct ESPNowBridge { + int calls = 0; uint32_t nonce = 0; + void formatStatus(char* r, size_t cap) { ++calls; snprintf(r, cap, "status"); } + void formatStats(const char* page, char* r, size_t cap) { ++calls; assert(strcmp(page,"rx")==0); snprintf(r, cap, "rx"); } + bool sendTest(uint32_t n) { ++calls; nonce = n; return true; } + void resetStats() { ++calls; } +}; +struct Role : Base { + ESPNowBridge bridge, espnow_bridge; +''' + suffix = r''' +}; +int main() { + Role role; char reply[157]; + role.formatEspNowStatus(reply, sizeof(reply)); + role.formatEspNowStats("rx", reply, sizeof(reply)); + assert(role.sendEspNowTest(0xABCD)); + assert(role.resetEspNowStats()); + assert(role.EXPECTED.calls == 4 && role.EXPECTED.nonce == 0xABCD); + assert(role.OTHER.calls == 0); +} +''' + for macros in ((), ("WITH_RS232_BRIDGE",), ("WITH_MQTT_BRIDGE",), + ("WITH_MQTT_BRIDGE", "WITH_RS232_BRIDGE")): + with self.subTest(role="repeater", macros=macros): + selected = "espnow_bridge" if macros else "bridge" + code = prefix + repeater + suffix.replace("EXPECTED", selected).replace( + "OTHER", "bridge" if macros else "espnow_bridge") + self.compile_run(code, ["-DWITH_ESPNOW_BRIDGE=1", *["-D" + m for m in macros]]) + with self.subTest(role="room"): + code = prefix + room + suffix.replace("EXPECTED", "espnow_bridge").replace("OTHER", "bridge") + self.compile_run(code, ["-DWITH_BRIDGE=1", "-DWITH_MQTT_BRIDGE=1", "-DWITH_ESPNOW_BRIDGE=1"]) + + def test_diagnostic_virtuals_are_absent_without_espnow(self): + header = (ROOT / "src/helpers/CommonCLI.h").read_text(encoding="ascii") + start = header.index("#if defined(WITH_ESPNOW_BRIDGE)\n virtual void formatEspNowStatus(") + end = header.index("\n#endif", start) + len("\n#endif") + block = header[start:end] + source = r''' +#include +#include +#include +#include +#include +struct Callbacks { +''' + block + r''' +}; +template struct HasDiagnostics : std::false_type {}; +template struct HasDiagnostics().formatEspNowStatus(nullptr, 0)), + decltype(std::declval().formatEspNowStats(nullptr, nullptr, 0)), + decltype(std::declval().sendEspNowTest(0)), + decltype(std::declval().resetEspNowStats())>> : std::true_type {}; +int main() { +#if defined(WITH_ESPNOW_BRIDGE) + static_assert(HasDiagnostics::value); + Callbacks callbacks; char reply[157]; + callbacks.formatEspNowStatus(reply, sizeof(reply)); + assert(reply[0] == 'E'); + assert(!callbacks.sendEspNowTest(0) && !callbacks.resetEspNowStats()); +#else + static_assert(!HasDiagnostics::value); + static_assert(sizeof(Callbacks) == 1); +#endif +} +''' + self.compile_run(source) + self.compile_run(source, ["-DWITH_ESPNOW_BRIDGE=1"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/test/test_espnow_radio_lifecycle.py b/test/test_espnow_radio_lifecycle.py index d1f587a8b..8c71e62cb 100644 --- a/test/test_espnow_radio_lifecycle.py +++ b/test/test_espnow_radio_lifecycle.py @@ -14,6 +14,7 @@ STUBS = r''' #include #include #include +#include #define ESP_IDF_VERSION_VAL(a,b,c) ((a)*10000+(b)*100+(c)) #define ESPNOW_DEBUG_PRINTLN(...) ((void)0) #define portENTER_CRITICAL(x) ((void)0) @@ -213,6 +214,10 @@ struct Backend : mesh::wireless::Backend { }; class Bridge { public: + static constexpr int ESP_ERR_INVALID_STATE=-78,ESP_ERR_INVALID_ARG=-79; + std::atomic _debug_dirty{false}; + void recordError(mesh::bridge::diag::Stage,int32_t){} + void emitDebug(){} struct Prefs {int bridge_format=mesh::bridge::ESPNOW_FORMAT_RAW;uint8_t bridge_channel=6;} prefs; Prefs* _prefs=&prefs;bool _initialized=false; int _active_format=0,_rx_mux=0,_rx_head=0,_rx_tail=0,_rx_count=0,_rx_dropped=0,_rx_dropped_reported=0; @@ -220,7 +225,7 @@ public: int _tx_callback_status=0,_tx_dropped=0,_tx_dropped_reported=0; uint32_t _tx_started_at=0,_tx_retry_at=0;bool _sdk_teardown_failed=false; mesh::espnow::ESPNowRawReassembler _raw_reassembler; - struct QueuedTransmit {bool started=false;int packet=0;}; + struct QueuedTransmit {bool started=false,diagnostic=false;int packet=0;}; static constexpr int TX_QUEUE_DEPTH=2; QueuedTransmit _tx_queue[TX_QUEUE_DEPTH]; struct {void clear(const int*){}} _seen_packets; diff --git a/test/test_transport_filter_wiring.py b/test/test_transport_filter_wiring.py index e1ac3c623..9e9035231 100644 --- a/test/test_transport_filter_wiring.py +++ b/test/test_transport_filter_wiring.py @@ -40,6 +40,8 @@ HARNESS = r''' #include #include #include +#include +#include #define BRIDGE_DEBUG_PRINTLN(...) ((void)0) #define PUB_KEY_SIZE 32 #define PAYLOAD_TYPE_ADVERT 4 @@ -57,15 +59,6 @@ struct Identity { explicit Identity(const uint8_t*) {} bool verify(const uint8_t*,const uint8_t*,int) {assert(false);return false;} }; -namespace espnow { - struct ESPNowRawFrames {uint8_t count=0;uint16_t lengths[2]={};uint8_t data[2][256]={};}; - bool encodeEspNowRawFrames(const uint8_t*,size_t,ESPNowRawFrames& f) {f.count=1;return true;} -} -namespace bridge { - enum {ESPNOW_FORMAT_RAW=0}; - size_t espNowMaxMeshPacketSize(int) {return 256;} - const char* espNowFormatName(int) {return "raw";} -} } namespace AdvertSignature { constexpr unsigned kMaxMessageLen=68; @@ -83,6 +76,7 @@ struct Manager { }; struct Prefs {unsigned bridge_delay=10;unsigned bridge_baud=115200;}; struct BridgeBase : AbstractBridge { +@INGRESS_HOOK@ bool _initialized=true; Seen _seen_packets; Manager manager; Manager* _mgr=&manager; @@ -120,8 +114,16 @@ struct RS232Bridge : BridgeBase { }; struct ESPNowBridge : BridgeBase { int _active_format=0; + mesh::bridge::diag::Stats _stats; + std::atomic _debug_dirty{false}; + void noteTx(uint32_t mesh::bridge::diag::TxStats::* field) { + mesh::bridge::diag::increment(_stats.tx.*field); + } + void recordError(mesh::bridge::diag::Stage stage,int32_t code) { + _stats.error={stage,code,millis()}; + } bool xorCrypt(uint8_t*,size_t) {return true;} - bool queueTransmitFrames(mesh::espnow::ESPNowRawFrames&,const mesh::Packet&) {++queued;return true;} + bool queueTransmitFrames(const mesh::espnow::ESPNowRawFrames&,const mesh::Packet&,bool=false) {++queued;return true;} void sendPacket(mesh::Packet*) override; }; struct MQTTBridge : BridgeBase { @@ -205,6 +207,14 @@ int main() { } ''' +# Importers use this shared harness directly, so expand its production hook +# here rather than leaving fixture setup to one test's compilation path. +_base_header = (ROOT / 'src/helpers/bridges/BridgeBase.h').read_text(encoding='ascii') +_ingress_hook = '#if defined(WITH_ESPNOW_BRIDGE)\n' +_ingress_hook += method(_base_header, 'enum class IngressResult') + ';\n' +_ingress_hook += method(_base_header, 'virtual void onIngressResult(') + '\n#endif\n' +HARNESS = HARNESS.replace('@INGRESS_HOOK@', _ingress_hook) + class TransportFilterWiring(unittest.TestCase): def test_aliases_dispatch_the_original_suffix_without_expanding_a_command_buffer(self): source = (ROOT/'examples/simple_repeater/MyMesh.cpp').read_text() @@ -394,11 +404,13 @@ int main() { (work/'Mesh.h').write_text(PACKET) code = '#include \n' + HARNESS.replace('@METHODS@', '\n'.join(methods)) (work/'test.cpp').write_text(code) - result = subprocess.run(['g++', '-std=c++17', '-Wall', '-Wextra', '-Werror', - '-I', str(work), '-I', str(ROOT/'src'), str(work/'test.cpp'), - '-o', str(work/'test')], text=True, capture_output=True) - self.assertEqual(result.returncode, 0, result.stdout + result.stderr) - subprocess.run([str(work/'test')], check=True) + for macros in [[], ['-DWITH_ESPNOW_BRIDGE=1']]: + with self.subTest(macros=macros): + result = subprocess.run(['g++', '-std=c++17', '-Wall', '-Wextra', '-Werror', + *macros, '-I', str(work), '-I', str(ROOT/'src'), str(work/'test.cpp'), + '-o', str(work/'test')], text=True, capture_output=True) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + subprocess.run([str(work/'test')], check=True) def test_roles_wire_filter_at_every_bridge_start_and_cross_hook(self): for role in ['simple_repeater', 'simple_room_server']: diff --git a/webui/index.html b/webui/index.html index d8577c60d..d28bde2c4 100644 --- a/webui/index.html +++ b/webui/index.html @@ -2174,7 +2174,7 @@ var CLI_KEYS=[ ["bridge.source","Packets the bridge carries",0,"rx|tx"], ["bridge.baud","Bridge serial baud rate",0], ["bridge.delay","Bridge send delay",0], - ["bridge.channel","Bridge channel",0], + ["bridge.channel","ESP-NOW 2.4 GHz channel",0], ["bridge.format","ESP-NOW bridge wire format",0,"wrapped|raw"], ["bridge.secret","Bridge shared secret",0] ];