Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down
2 changes: 1 addition & 1 deletion docs/firmware.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
69 changes: 69 additions & 0 deletions docs/results/2026-10-26-latency/report.md
Original file line number Diff line number Diff line change
@@ -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.
1 change: 1 addition & 0 deletions docs/setup.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
9 changes: 7 additions & 2 deletions invigil/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}")
Expand Down Expand Up @@ -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)])
Expand All @@ -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


Expand Down
21 changes: 21 additions & 0 deletions invigil/ntp.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 <session folder>/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)
Expand Down
16 changes: 16 additions & 0 deletions invigil/tests/test_ntp.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import json
import socket
import threading
import time
Expand Down Expand Up @@ -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
Expand Down
Loading