From 8a9e01c1527c14415d9516c305cc55d0b3856f14 Mon Sep 17 00:00:00 2001 From: Mohanad Tarek <241946041+mohanvd@users.noreply.github.com> Date: Mon, 26 Oct 2026 21:20:27 +0300 Subject: [PATCH 1/2] feat: record the laptop clock offset with each launcher session invigil start writes clock.json into the logger session with the laptop's offset from NTP, and invigil stop adds a second measurement, so every latency figure can be checked and corrected later. --- docs/setup.md | 1 + invigil/__main__.py | 9 +++++++-- invigil/ntp.py | 21 +++++++++++++++++++++ invigil/tests/test_ntp.py | 16 ++++++++++++++++ 4 files changed, 45 insertions(+), 2 deletions(-) diff --git a/docs/setup.md b/docs/setup.md index ef543b7..736c642 100644 --- a/docs/setup.md +++ b/docs/setup.md @@ -153,6 +153,7 @@ Each session folder holds three CSV files, one per message type: - `ts` is when the unit took the reading. `rx_ts` is when the laptop received it. Both are milliseconds since epoch, so `rx_ts - ts` is the unit-to-laptop latency (design requirement 4). The two clocks are only as close as SNTP keeps them, so check the clock offset before you report a latency result. A negative latency means the unit clock is ahead. - Fake runs show `fw` as `0.1.0-fake` in `status.csv`. +- A session started by `invigil start` also gets `clock.json`: the laptop clock against NTP when the recording started, and again when `invigil stop` ended it. `laptop_minus_ntp_ms` is how far `rx_ts` ran ahead of real time, so subtract it from `rx_ts - ts` before you report a latency. `null` means the NTP server could not be reached. - Files are flushed after every row, so a crash or Ctrl+C loses nothing. Load a session with pandas: diff --git a/invigil/__main__.py b/invigil/__main__.py index 40bbbe6..b2e20e9 100644 --- a/invigil/__main__.py +++ b/invigil/__main__.py @@ -155,6 +155,7 @@ def cmd_start(args) -> int: lg = procs.spawn("logger", [sys.executable, "-m", "server.logger", "--session", name], out=str(out)) records.append(lg) procs.save_run(records) + ntp.record(out, "start", clock) url = dashboard.live_url(args.port, f"ws://localhost:{broker.WS_PORT}", cfg.username) web = procs.spawn("dashboard", dashboard.serve_cmd(args.port), url=f"http://127.0.0.1:{args.port}") @@ -219,7 +220,11 @@ def show_status(args, records, live: bool, wait_for_unit: bool, clock=None, open monitor.close(client) -def stop_all(records: list[dict]) -> None: +def stop_all(records: list[dict], ntp_server: str = ntp.DEFAULT_SERVER) -> None: + for record in records: + # The clock at the end of a recording goes next to the one at its start. + if record["name"] == "logger" and record.get("out") and procs.is_running(record): + ntp.record(Path(record["out"]), "stop", ntp.check_clock(ntp_server)) for record in reversed(records): print(f"{record['name']} (PID {record['pid']}): {procs.stop(record)}") procs.save_run([r for r in records if procs.is_running(r)]) @@ -230,7 +235,7 @@ def cmd_stop(args) -> int: if not records: print("Nothing to stop: the launcher has not started anything.") return 0 - stop_all(records) + stop_all(records, args.ntp_server) return 0 diff --git a/invigil/ntp.py b/invigil/ntp.py index 5777300..08060a0 100644 --- a/invigil/ntp.py +++ b/invigil/ntp.py @@ -6,10 +6,12 @@ from __future__ import annotations +import json import socket import struct import time from dataclasses import dataclass +from pathlib import Path DEFAULT_SERVER = "pool.ntp.org" WARN_MS = 100 @@ -77,6 +79,25 @@ def describe(self) -> str: return text +def record(folder: Path, when: str, check: ClockCheck, now: float | None = None) -> Path: + """Add one clock measurement to /clock.json under "start" or "stop". + + laptop_minus_ntp_ms is how far the laptop clock (rx_ts) was ahead of NTP. + Subtract it from rx_ts - ts to correct a latency figure. + """ + path = Path(folder) / "clock.json" + data = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {} + data[when] = { + "measured_at_ms": int((time.time() if now is None else now) * 1000), + "server": check.server, + "laptop_minus_ntp_ms": None if check.offset_ms is None else round(-check.offset_ms, 1), + "error": check.error, + } + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8") + return path + + def check_clock(server: str = DEFAULT_SERVER, port: int = 123, timeout: float = 2.0) -> ClockCheck: try: offset, _ = query(server, port, timeout) diff --git a/invigil/tests/test_ntp.py b/invigil/tests/test_ntp.py index 0269fcc..3beca8d 100644 --- a/invigil/tests/test_ntp.py +++ b/invigil/tests/test_ntp.py @@ -1,3 +1,4 @@ +import json import socket import threading import time @@ -70,6 +71,21 @@ def test_a_reply_that_is_not_from_a_server_is_refused(): assert "could not reach" in check.describe() +def test_clock_is_recorded_next_to_the_session(tmp_path): + folder = tmp_path / "2026-10-26-live-120000" + ntp.record(folder, "start", ntp.ClockCheck("pool.ntp.org", -350.0), now=1000.0) + ntp.record(folder, "stop", ntp.ClockCheck("pool.ntp.org", None, "timed out"), now=1600.0) + data = json.loads((folder / "clock.json").read_text()) + # offset_ms is NTP minus laptop, so a laptop 350 ms ahead stores +350. + assert data["start"] == { + "measured_at_ms": 1_000_000, + "server": "pool.ntp.org", + "laptop_minus_ntp_ms": 350.0, + "error": "", + } + assert data["stop"]["laptop_minus_ntp_ms"] is None and data["stop"]["error"] == "timed out" + + def test_no_answer_gives_an_unknown_offset(): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind(("127.0.0.1", 0)) # bound, never answers From 70b68006b125d509c3ae13868672cc385d51391b Mon Sep 17 00:00:00 2001 From: Mohanad Tarek <241946041+mohanvd@users.noreply.github.com> Date: Mon, 26 Oct 2026 21:35:18 +0300 Subject: [PATCH 2/2] docs: add the first latency and window-timing result 10 minutes on unit N1 with the laptop clock checked against NTP: every message within 1.11 s, nothing dropped, send window at most 118 ms. The README and firmware docs point to it. --- README.md | 2 +- docs/firmware.md | 2 +- docs/results/2026-10-26-latency/report.md | 69 +++++++++++++++++++++++ 3 files changed, 71 insertions(+), 2 deletions(-) create mode 100644 docs/results/2026-10-26-latency/report.md diff --git a/README.md b/README.md index d3345c3..db87a13 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,7 @@ Working on the real unit (first run 2026-10-26, see [docs/results](docs/results/ - **Launcher** (`invigil/`): starts the broker, the logger and the dashboard with one command, and runs guided calibration. - **Dashboard** in Live mode, reading the unit through Mosquitto. -Latency figures are not valid yet: the laptop clock was off from NTP during the first runs. +First latency figure, with the laptop clock checked against NTP: over 10 minutes, every message from the unit reached the laptop within 1.11 s, nothing was dropped ([report](docs/results/2026-10-26-latency/report.md)). The figures from the first boot are not valid, because the laptop clock was off then. Also working, and testable on a laptop with no hardware: diff --git a/docs/firmware.md b/docs/firmware.md index 1e1f8a2..36b0d0f 100644 --- a/docs/firmware.md +++ b/docs/firmware.md @@ -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.** 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)). 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-26-latency/report.md b/docs/results/2026-10-26-latency/report.md new file mode 100644 index 0000000..9c56950 --- /dev/null +++ b/docs/results/2026-10-26-latency/report.md @@ -0,0 +1,69 @@ +# Latency and window timing, 10 minutes: 2026-10-26 + +The first latency figure with the laptop clock checked against NTP, plus the window-timing counters over the same 10 minutes. **Unit to laptop, every message arrived within 1.11 s, under the 2 s of design requirement 4.** Nothing was dropped, and no send window ran over. + +No raw data or addresses are in this report. The session stays in `data/raw/` on the laptop. + +## Setup + +| Part | Setting | +| --- | --- | +| Unit | N1, firmware 0.1.0 (same code as the [first boot](../2026-10-26-first-boot/report.md), rebuilt with a new MQTT password), radio on the adapter board | +| Network | Router 2.4 GHz fixed on channel 6. Unit RSSI -44 dBm | +| Laptop | `python -m invigil start --session latency-10min`: Mosquitto with `server/mosquitto.conf`, the logger, the dashboard | +| Devices nearby | Not controlled: whatever was in and around the room. 34 distinct hashed addresses were heard | +| Window | 600 s, timed on the laptop, from about 40 s after the unit booted | + +Latency here is `rx_ts - ts` from the logger's CSV files: the unit's timestamp against the time the laptop received the message. The dashboard uses the same broker, but its own delay in the browser was not measured. + +## Clock + +`invigil start` and `invigil stop` wrote the laptop clock's offset from `pool.ntp.org` into the session's `clock.json`: + +| When | Laptop minus NTP | +| --- | --- | +| Start | -16.3 ms | +| Stop | -77.0 ms | + +Every latency below is corrected by the mean, -46.6 ms. The NTP round trip was about 100 to 220 ms, so each offset is only known to within about ±50 to 100 ms, and the unit's own SNTP clock has an error of the same order. Read the figures below as ±100 ms. + +## Latency, unit to laptop + +| Message | Count | Per second | p50 | p95 | p99 | Max | +| --- | --- | --- | --- | --- | --- | --- | +| BLE | 24,985 | 41.6 | 558 ms | 989 ms | 1,029 ms | 1,108 ms | +| Spectrum | 570 | 0.95 | 52 ms | 96 ms | 134 ms | 144 ms | +| Status | 60 | 0.10 | 59 ms | 104 ms | 137 ms | 139 ms | + +- BLE readings wait in the unit's buffer until the scan window ends, by design, so their latency includes up to one 1,000 ms scan window. A reading heard early in a window waits longest. That is why BLE sits around 0.5 to 1 s while spectrum and status, stamped just before sending, take about 50 to 100 ms. +- No BLE reading took more than 2,000 ms (0.00 %). +- The logger rejected 0 messages. + +Against design requirement 4 (alert latency, unit to dashboard, within 2 s): the transport part is met with room to spare. The full requirement also needs the model's processing time and the dashboard's delay, which do not exist yet because detections are not published. + +## Window timing + +From the unit's 60 summary lines over the same 10 minutes: + +| Counter | Total | Worst 10 s | +| --- | --- | --- | +| Scan windows | 571 | 10 | +| BLE captured / published | 25,071 / 25,071 | 483 | +| `ble_dropped` | 0 | 0 | +| `spectrum_dropped` | 0 | 0 | +| `send_overruns` | 0 | 0 | +| `mqtt_busy` | 0 | 0 | +| `tx_in_scan` | 2 | 1 | +| `sweeps_discarded` | 2 | 1 | + +- **Send window:** at most 118 ms of the 300 ms allowed. +- **Sweeps:** 23.3 ms on average for one 126-channel sweep, 25.4 ms at most, 41 to 42 complete sweeps per scan window. +- **Connection:** Wi-Fi stayed up and MQTT stayed connected in every line. No self-check failure. +- **`tx_in_scan`:** one frame left the Wi-Fi radio during a scan window at t=291 s and another at t=582 s, 291 s apart. Both sweeps it touched were thrown away (`sweeps_discarded`), so no published spectrum contains them. The regular 5-minute spacing points to periodic network traffic, such as the router's address lookups (ARP), which the firmware docs list as the one source that can land in a scan window. Not confirmed. +- **`mqtt_busy`:** 0 in this run. One earlier run showed 8 in a single summary. + +## What this does not cover + +- The devices were not controlled. The window-timing test in the [firmware docs](../../firmware.md#to-measure) asks for 3 to 5 known devices nearby, which is still to do. This run had more traffic than that (about 42 BLE readings a second), so the window margins above are probably on the safe side. +- Dashboard delay and model processing time, as above. +- One 10-minute run. Repeat it on another day and in the hall before quoting it in the portfolio.