From 3dc492e0b5fc1aeb8c3c3aa06816194910839536 Mon Sep 17 00:00:00 2001 From: Mohanad Tarek <241946041+mohanvd@users.noreply.github.com> Date: Tue, 27 Oct 2026 08:52:28 +0300 Subject: [PATCH 1/2] fix: never start a scan window while MQTT is still sending Raise the send window limit to 500 ms. When a send window has not drained by then, keep waiting and count an overrun instead of starting the next scan. Drained now also means the broker has acknowledged every TCP segment, so TCP has nothing left to resend during a scan. Firmware 0.1.1. --- firmware/CMakeLists.txt | 2 +- firmware/src/config.h | 10 ++++++++-- firmware/src/main.c | 13 ++++++++++++- firmware/src/mqtt_link.c | 5 ++++- firmware/src/mqtt_link.h | 6 +++--- 5 files changed, 28 insertions(+), 8 deletions(-) diff --git a/firmware/CMakeLists.txt b/firmware/CMakeLists.txt index c35e95e..31873cb 100644 --- a/firmware/CMakeLists.txt +++ b/firmware/CMakeLists.txt @@ -39,7 +39,7 @@ endif() include(pico_sdk_import.cmake) -project(invigil_fw VERSION 0.1.0 LANGUAGES C CXX ASM) +project(invigil_fw VERSION 0.1.1 LANGUAGES C CXX ASM) pico_sdk_init() diff --git a/firmware/src/config.h b/firmware/src/config.h index ba21e68..39345dd 100644 --- a/firmware/src/config.h +++ b/firmware/src/config.h @@ -41,12 +41,18 @@ // Starting guess, to be measured. #define SCAN_WINDOW_MS 1000 // Longest send window: publish the window's readings, then wait until -// everything has left lwIP. Starting guess, to be measured. -#define SEND_WINDOW_MAX_MS 300 +// everything has left lwIP. 300 ms ran out with about 130 BLE readings a +// second around the unit (2026-10-27), so 500. To be measured again. +#define SEND_WINDOW_MAX_MS 500 // Part of the send window kept for the last messages to leave lwIP. No new // message is handed to MQTT after SEND_WINDOW_MAX_MS - SEND_DRAIN_MS. // Starting guess, to be measured. #define SEND_DRAIN_MS 50 +// A send window that has not drained by SEND_WINDOW_MAX_MS keeps waiting +// (and counts as an overrun): a scan window never starts while MQTT is still +// sending. After this long the cycle hands back to housekeeping so a stuck +// connection can time out, but the next scan still waits for the drain. +#define SEND_OVERRUN_GIVE_UP_MS 5000 // Quiet time after the last publish has left lwIP, before the next scan // window, so the radio has finished transmitting. Starting guess, to be measured. #define QUIET_GAP_MS 50 diff --git a/firmware/src/main.c b/firmware/src/main.c index 764a920..ef758ab 100644 --- a/firmware/src/main.c +++ b/firmware/src/main.c @@ -4,6 +4,8 @@ // 1. Scan window: BLE scan on, nRF sweeps back to back, no MQTT traffic. // 2. Send window: BLE scan off, sweeps stopped. Publish the window's // spectrum message, then buffered BLE readings, then status if due. +// It ends when everything has left lwIP, even if that takes longer +// than SEND_WINDOW_MAX_MS (counted as an overrun). // 3. Quiet gap, then the next scan window. // The cycle only runs while Wi-Fi is up, the clock is set and MQTT is // connected. Reconnecting happens between cycles, never inside a scan window. @@ -242,7 +244,14 @@ static void send_window(uint64_t scan_end_ms) { sleep_us(200); } if (!mqtt_link_drained()) { + // Over the limit. Keep waiting rather than start scanning while the + // unit is still sending, and count it so the window can be tuned. stats.send_overruns++; + absolute_time_t give_up = delayed_by_ms(start, SEND_OVERRUN_GIVE_UP_MS); + while (!mqtt_link_drained() && !time_reached(give_up)) { + tick(); + sleep_us(200); + } } uint32_t send_ms = (uint32_t)(absolute_time_diff_us(start, get_absolute_time()) / 1000); @@ -338,7 +347,9 @@ int main(void) { for (;;) { housekeeping(); - if (running()) { + // A scan window only starts once everything from the last send window + // has left lwIP, even after an overrun gave up waiting. + if (running() && mqtt_link_drained()) { run_cycle(); } else { sleep_ms(10); diff --git a/firmware/src/mqtt_link.c b/firmware/src/mqtt_link.c index 04bb067..e1b4f67 100644 --- a/firmware/src/mqtt_link.c +++ b/firmware/src/mqtt_link.c @@ -191,7 +191,10 @@ bool mqtt_link_drained(void) { cyw43_arch_lwip_begin(); bool drained = true; if (client.conn != NULL) { - drained = client.output.put == client.output.get && client.conn->unsent == NULL; + // unacked too: a segment still waiting for its ack can be sent again + // by TCP at any moment, which could land in the next scan window. + drained = client.output.put == client.output.get && client.conn->unsent == NULL && + client.conn->unacked == NULL; } cyw43_arch_lwip_end(); return drained; diff --git a/firmware/src/mqtt_link.h b/firmware/src/mqtt_link.h index 9b351c2..8a20f8d 100644 --- a/firmware/src/mqtt_link.h +++ b/firmware/src/mqtt_link.h @@ -26,9 +26,9 @@ const char *mqtt_link_state_name(void); // lock is recursive, so it may also be called with the lock already held. mqtt_pub_result_t mqtt_link_publish(const char *topic, const char *payload, size_t len); -// True when everything handed to mqtt_link_publish() has left lwIP for the -// radio: the MQTT output buffer is empty and TCP has no unsent segments. -// Acknowledgements may still be on their way back. +// True when everything handed to mqtt_link_publish() has left lwIP and the +// broker has acknowledged it: the MQTT output buffer is empty and TCP has no +// unsent or unacknowledged segments, so TCP has nothing left to send again. bool mqtt_link_drained(void); #endif From 06bc6c413404f3ba2bb52c192005ae45fc35f91c Mon Sep 17 00:00:00 2001 From: Mohanad Tarek <241946041+mohanvd@users.noreply.github.com> Date: Tue, 27 Oct 2026 08:52:29 +0300 Subject: [PATCH 2/2] docs: add the 500 ms send window result 10 minutes in a crowded room on 0.1.1: MQTT no longer lands in scan windows, but send windows took up to 5 s and BLE latency p95 reached 4.6 s. The firmware docs describe the new send window rule. --- docs/firmware.md | 10 +-- .../2026-10-27-send-window-500/report.md | 74 +++++++++++++++++++ 2 files changed, 79 insertions(+), 5 deletions(-) create mode 100644 docs/results/2026-10-27-send-window-500/report.md diff --git a/docs/firmware.md b/docs/firmware.md index 36b0d0f..ea44782 100644 --- a/docs/firmware.md +++ b/docs/firmware.md @@ -15,7 +15,7 @@ Wiring is in the [README](../README.md#wiring). The message formats are in the [ The unit repeats one cycle, as the [MQTT contract](contract.md) requires: 1. **Scan window** (1000 ms). BLE scan on, nRF24L01 sweeps channels 0 to 125 back to back. No MQTT traffic. -2. **Send window** (up to 300 ms). BLE scan off, sweeps stopped. Publish one spectrum message for the window (`ts` is the end of the scan window), then the buffered BLE readings, oldest first, then a status message if one is due (every 10 s). The window ends when the buffer is empty, or when time runs out. Leftovers wait for the next send window. Then the unit waits until everything has left lwIP for the radio. +2. **Send window** (normally up to 500 ms). BLE scan off, sweeps stopped. Publish one spectrum message for the window (`ts` is the end of the scan window), then the buffered BLE readings, oldest first, then a status message if one is due (every 10 s). New messages stop 50 ms before the limit, and leftovers wait for the next send window. Then the unit waits until everything has left lwIP **and the broker has acknowledged it**, so TCP has nothing it could send again. If that takes longer than 500 ms, it keeps waiting and counts an overrun (`send_overruns`): **a scan window never starts while the unit still has data in flight.** After 5 s it hands back to the reconnect checks, but the next scan still waits for the drain. 3. **Quiet gap** (50 ms), then the next scan window. The cycle only runs while Wi-Fi is up, the clock is set by SNTP and MQTT is connected. Nothing is published before the clock is set, because the contract rejects unsynced timestamps. Reconnecting happens between cycles, never inside a scan window. @@ -168,7 +168,7 @@ Every 10 s the unit prints one line of `key=value` pairs. These are the numbers | `status_sent` | Status messages sent | | `send_ms_max` | Longest send window, in ms | | `mqtt_busy` | Times the MQTT output buffer was full and the unit waited for it to drain | -| `send_overruns` | Send windows that hit 300 ms before everything left lwIP | +| `send_overruns` | Send windows that needed more than 500 ms to drain. The unit waited longer instead of scanning | | `tx_in_scan` | Frames lwIP handed to the radio during scan windows. Should be 0 | | `sweeps_discarded` | Sweeps thrown away because lwIP sent a frame during them | | `wifi`, `mqtt` | Connection state | @@ -181,9 +181,9 @@ The contract says the unit must not scan the 2.4 GHz band while it transmits ove | Source | What happens | Can it land in a scan window? | | --- | --- | --- | -| Publishes | Only in send windows. The send window then waits until the MQTT output buffer is empty and TCP has nothing unsent. Nagle is off, so no segment waits for the broker's delayed ack | No, unless a send window hits 300 ms first (`send_overruns`) | +| Publishes | Only in send windows. The send window then waits until the MQTT output buffer is empty and TCP has nothing unsent or unacknowledged, however long that takes. Nagle is off, so no segment waits for the broker's delayed ack | No | | MQTT keep alive | lwIP's MQTT timer only adds a PINGREQ to the output buffer after 60 s with nothing acknowledged. It does not send it; the next publish does. Every send window publishes | No | -| TCP retransmission | If an ack from the broker is lost, lwIP resends after its timeout, which is at least about a second | Rarely | +| TCP retransmission | lwIP only resends a segment that has not been acknowledged, and a scan window only starts once every segment is acknowledged | No | | TCP acks | The unit only acks data it receives. At QoS 0 the broker sends nothing back except TCP acks | No | | ARP | lwIP answers another host's ARP request as soon as it arrives. Its own ARP refreshes only happen when it sends | Yes, when the laptop or router asks | | DHCP | Lease renewal at half the lease time (12 h for a 24 h lease) | Rarely | @@ -210,7 +210,7 @@ These depend on hardware behavior, so they are tests to run, not numbers to assu **Sweep time.** First result (2026-10-26, 4 MHz SPI over breadboard wires, with the radio on the adapter board): 23.4 ms per 126-channel sweep on average, 25.0 ms at most, 42 sweeps per scan window. Run the unit for 2 minutes with no test devices nearby. Record `sweep_us`, `sweep_us_max` and `sweeps_per_window`. Then raise `NRF_SPI_HZ` (it is 4 MHz because of breadboard jumper wires) and check the sweep time and the nRF self-check still pass. -**Scan window, send window and quiet gap.** First result (2026-10-26, 10 minutes, devices not controlled, about 42 BLE readings a second): `send_ms_max` 118, and `mqtt_busy`, `send_overruns`, `ble_dropped` and `spectrum_dropped` all 0 ([report](results/2026-10-26-latency/report.md)). Still to do with known devices. With 3 to 5 BLE devices nearby, run for 10 minutes and record `send_ms_max`, `mqtt_busy`, `send_overruns`, `ble_dropped` and `spectrum_dropped`. They should all stay at 0 except `send_ms_max`. If `send_overruns` or `ble_dropped` is not 0, lengthen `SEND_WINDOW_MAX_MS` or `SEND_DRAIN_MS`. Then check the cycle against design requirement 1 (at most 5 s from when a device starts transmitting) and the open question on window length in the [contract](contract.md). +**Scan window, send window and quiet gap.** First result (2026-10-26, 10 minutes, devices not controlled, about 42 BLE readings a second): `send_ms_max` 118, and `mqtt_busy`, `send_overruns`, `ble_dropped` and `spectrum_dropped` all 0 ([report](results/2026-10-26-latency/report.md)). In a crowded room on 2026-10-27 (116 devices, about 127 BLE readings a second), 300 ms ran out and MQTT data went out during scan windows. Firmware 0.1.1 raised the limit to 500 ms and waits for a full drain before scanning: MQTT no longer lands in scan windows, but send windows took up to 5 s, the unit scanned 53 % of the time, and BLE latency p95 reached 4.6 s ([report](results/2026-10-27-send-window-500/report.md)). Still to do with known devices. With 3 to 5 BLE devices nearby, run for 10 minutes and record `send_ms_max`, `mqtt_busy`, `send_overruns`, `ble_dropped` and `spectrum_dropped`. They should all stay at 0 except `send_ms_max`. If `send_overruns` or `ble_dropped` is not 0, lengthen `SEND_WINDOW_MAX_MS` or `SEND_DRAIN_MS`. Then check the cycle against design requirement 1 (at most 5 s from when a device starts transmitting) and the open question on window length in the [contract](contract.md). **Does the unit's own Wi-Fi show up in the spectrum.** The unit prints its Wi-Fi channel at connect (for example `nRF channels 27-47`). The router transmits on that channel too, so compare two runs that differ only in the quiet gap. With no test devices, record 5 minutes with `QUIET_GAP_MS` at 50, then 5 minutes at 250. If the hits on the unit's Wi-Fi channels drop with the longer gap, the unit's own frames were reaching scan windows: keep the longer gap. Also check `tx_in_scan` stays at 0 in both runs. diff --git a/docs/results/2026-10-27-send-window-500/report.md b/docs/results/2026-10-27-send-window-500/report.md new file mode 100644 index 0000000..6906a34 --- /dev/null +++ b/docs/results/2026-10-27-send-window-500/report.md @@ -0,0 +1,74 @@ +# Send window 500 ms, and no scanning while sending: 2026-10-27 + +Firmware 0.1.1 changes two things: + +- **The send window limit** goes from 300 to 500 ms. +- **A scan window never starts while the unit still has data in flight.** At the end of a send window the unit waits until the MQTT output buffer is empty and the broker has acknowledged every TCP segment. If that takes longer than 500 ms, it keeps waiting and counts an overrun. + +Ten minutes in a crowded room (116 devices heard). **The MQTT traffic no longer lands in scan windows. Three frames still did, at a regular 5-minute rhythm that points to network housekeeping, not to MQTT.** The cost under this load is large: send windows often took seconds, the unit scanned only 53% of the time, and **BLE latency rose to p95 4.6 s, which fails design requirement 4 at this load.** + +No raw data or addresses are in this report. The session stays in `data/raw/` on the laptop. + +## Why + +At 08:00 this morning on firmware 0.1.0, with many devices around, the unit had about 127 BLE readings a second to send. Send windows hit their 300 ms limit (`send_overruns` 3 in 10 s), and the rest of the data went out during scan windows (`tx_in_scan` 6 in 10 s). The [MQTT contract](../../contract.md) says the unit must not scan the 2.4 GHz band while it transmits. + +## Setup + +| Part | Setting | +| --- | --- | +| Unit | N1, firmware 0.1.1. The nRF24L01 failed its boot self-check this morning (wiring, see below), so this run has BLE and status only, no spectrum | +| Network | Router 2.4 GHz fixed on channel 6 | +| Laptop | `python -m invigil start --session send500-10min` | +| Devices nearby | Not controlled, a crowded room: 116 distinct hashed addresses in 10 minutes | +| Window | 600 s, 08:39:30 to 08:49:30, starting about 30 s after the unit booted | + +## Clock + +From the session's `clock.json`: the laptop was 123.9 ms behind NTP at the start and 136.5 ms behind at the stop. Latency below is corrected by the mean, -130.2 ms, and is good to about ±100 ms. + +## Results + +| | This run (0.1.1, 500 ms, drain first) | 08:00 today (0.1.0, 300 ms), one 10 s line | [Yesterday](../2026-10-26-latency/report.md) (0.1.0, 300 ms, quieter room) | +| --- | --- | --- | --- | +| BLE readings a second | 66.6 published | about 127 captured | 41.6 | +| `tx_in_scan` | **3 in 600 s** | 6 in 10 s | 2 in 600 s | +| Send windows over the limit | 75 in 600 s (45 of 60 summaries) | 3 in 10 s | 0 | +| Longest send window per 10 s | median 2,138 ms, worst 5,000 ms | 300 ms (cut off) | 118 ms | +| Scan windows per 10 s | 5.3 on average, 0 to 9 | about 8 | 9 to 10 | +| Time spent scanning | 53 % | about 80 % | 95 % | +| BLE latency p50 / p95 / max | 747 ms / **4,604 ms** / 18,081 ms | not measured | 558 ms / 989 ms / 1,108 ms | +| BLE readings over 2 s | **13.4 %** | not measured | 0 % | +| Status latency p50 / p95 | 108 ms / 5,495 ms | not measured | 59 ms / 104 ms | +| `ble_dropped` | 0 | 0 | 0 | +| Rejected by the logger | 0 | 0 | 0 | + +Wi-Fi stayed up and MQTT stayed connected in every summary line. + +### The three frames in scan windows + +| Summary | `tx_in_scan` | `send_overruns` in that 10 s | +| --- | --- | --- | +| t=291 s | 1 | 2 | +| t=303 s | 1 | 1 | +| t=582 s | 1 | 0 | + +The one at t=582 s came in a 10 s stretch with no overrun at all, and the times repeat the 291 s spacing seen [yesterday](../2026-10-26-latency/report.md#window-timing). So these are not MQTT data. The likely source is the router or the laptop checking the unit's address (ARP), which lwIP answers at once. The firmware docs list this as the one source the unit cannot hold back. It was not confirmed with a packet capture. When the radio works, a sweep that such a frame touches is thrown away (`sweeps_discarded`), so it never reaches a spectrum message. + +### Why the send windows got so long + +The unit published about 67 BLE readings a second this morning and could not keep up. Yesterday, in a quieter room, a send window of under 120 ms cleared about 55 readings each cycle. Every BLE reading is its own small MQTT message, and the unit now also waits for the broker's acknowledgements before it scans again. In a crowded room the 2.4 GHz channel is busy, so each round trip takes longer. The Wi-Fi airtime was not measured, so this is the likely explanation, not a confirmed one. The longer the send window, the less the unit scans, and the longer readings wait in the buffer, which is where the 4.6 s p95 comes from. + +## What this means + +- The rule "never scan while sending" now holds for everything the unit sends on its own. What is left is a few frames every 5 minutes from network housekeeping. +- At this load, the rule costs latency and scan time. Design requirement 4 (2 s) is not met at about 120 BLE advertisements a second. +- In the hall during an exam, phones should be off or in bags, so the load is likely lower than this room. That needs measuring in the hall, not assuming. + +## Next steps + +1. **Fix the radio wiring** and repeat this run with spectrum on, to see `sweeps_discarded`. +2. **Send fewer, bigger packets.** With the unit now waiting for every acknowledgement before it scans, Nagle's algorithm can be turned back on during send windows, so many small messages share one TCP segment. This needs no contract change. Measure it the same way. +3. **Send less BLE data.** For example one message per device per scan window with its strongest RSSI and a count, instead of one per advertisement. This changes the [MQTT contract](../../contract.md) and the features, so it needs a decision first. +4. **Find the 5-minute sender**, for example by adding a static ARP entry for the unit on the laptop and checking whether the rhythm stops. +5. Repeat in the hall.