From 3949f5176bf64f200939611c336ce07281ea93ee Mon Sep 17 00:00:00 2001 From: Mohanad Tarek <241946041+mohanvd@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:12:28 +0200 Subject: [PATCH 1/2] feat: watch and search modes with near / not-near detections on MQTT Distance becomes near (under 1 m) or not near, trained on RSSI features only. A detector service runs the saved models on live 5 s windows and publishes the detection topic; invigil start runs it. Allowed devices come from a whitelist of hashes in config.toml. The dashboard takes detections from MQTT and shows a NEAR banner for search mode. Design requirement 3 is now near / not-near accuracy. Results in docs/results/2026-11-23-model-v2. --- CONTRIBUTING.md | 2 +- README.md | 32 ++- .../src/components/invigil/band-chip.tsx | 6 +- dashboard/src/components/invigil/bands.ts | 16 +- dashboard/src/components/invigil/charts.tsx | 13 +- .../components/invigil/detection-alert.tsx | 4 +- dashboard/src/components/invigil/hall-map.tsx | 17 +- .../src/components/invigil/near-banner.tsx | 67 +++++ .../src/components/invigil/signal-rings.tsx | 12 +- dashboard/src/data/__tests__/contract.test.ts | 6 +- dashboard/src/data/__tests__/store.test.ts | 34 ++- dashboard/src/data/contract.ts | 29 +++ dashboard/src/data/demo/fixtures.ts | 4 +- dashboard/src/data/demo/generator.ts | 12 +- dashboard/src/data/hall.ts | 4 +- dashboard/src/data/requirements.ts | 2 +- dashboard/src/data/selectors.ts | 24 ++ dashboard/src/data/store.ts | 100 ++++---- dashboard/src/data/types.ts | 15 +- dashboard/src/pages/live.tsx | 29 ++- dashboard/src/pages/results.tsx | 16 +- docs/brand/README.md | 3 +- docs/contract.md | 27 +- docs/data-protocol.md | 13 +- docs/results/2026-11-23-model-v2/checks.txt | 44 ++++ .../2026-11-23-model-v2/confusion_band.csv | 3 + .../2026-11-23-model-v2/confusion_type.csv | 3 + .../2026-11-23-model-v2/make_checks.py | 218 ++++++++++++++++ docs/results/2026-11-23-model-v2/report.md | 136 ++++++++++ .../2026-11-23-model-v2/response_time.csv | 25 ++ .../2026-11-23-model-v2/train_output.md | 77 ++++++ docs/setup.md | 38 ++- invigil/__main__.py | 17 +- invigil/calibrate.py | 16 +- invigil/tests/test_calibrate.py | 6 +- ml/features.py | 28 +- ml/tests/test_train.py | 6 +- ml/train.py | 17 +- server/config.py | 17 ++ server/config.toml.example | 12 + server/contract.py | 24 ++ server/detector.py | 241 ++++++++++++++++++ server/fake_publisher.py | 6 +- server/logger.py | 2 + server/tests/test_detector.py | 94 +++++++ server/tests/test_fake_publisher.py | 4 +- 46 files changed, 1322 insertions(+), 199 deletions(-) create mode 100644 dashboard/src/components/invigil/near-banner.tsx create mode 100644 docs/results/2026-11-23-model-v2/checks.txt create mode 100644 docs/results/2026-11-23-model-v2/confusion_band.csv create mode 100644 docs/results/2026-11-23-model-v2/confusion_type.csv create mode 100644 docs/results/2026-11-23-model-v2/make_checks.py create mode 100644 docs/results/2026-11-23-model-v2/report.md create mode 100644 docs/results/2026-11-23-model-v2/response_time.csv create mode 100644 docs/results/2026-11-23-model-v2/train_output.md create mode 100644 server/detector.py create mode 100644 server/tests/test_detector.py diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 124ccc3..5b10703 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -55,7 +55,7 @@ These are not optional. A pull request that breaks one will be closed. - **Receive only.** The nRF24L01 is used only as a receiver. We do not accept code that transmits to jam or interfere with any signal. - **Firmware** uses the official Pico SDK in C with CMake. No Arduino, Arduino-Pico core, PlatformIO or ESP boards. -- **The models stay narrow.** They answer device type and distance band. Ask before adding classes, seat zones or multi-unit location. +- **The models stay narrow.** They answer device type and near / not near. Ask before adding classes, seat zones or multi-unit location. - **Do not assume hardware behavior.** If something depends on range, thresholds, timing or byte order, say so and propose a test. - **Results** from a calibration or test run go in `docs/results/YYYY-MM-DD-/` with the raw summary, plots and a short note. - **Writing:** plain, direct English in docs and UI text. diff --git a/README.md b/README.md index 78bd3d5..41d6059 100644 --- a/README.md +++ b/README.md @@ -19,10 +19,17 @@ One sensor unit sits at the edge of a 6-seat mini exam hall. It is a Raspberry P - **BLE scanner.** The Pico's own radio hears Bluetooth Low Energy advertisements and reads the signal strength (RSSI) and the manufacturer ID. The address is hashed on the unit. - **Channel scanner.** The nRF24L01 sweeps 126 channels of the 2.4 GHz band and counts where it hears a carrier. Bluetooth audio shows up as scattered hits across the band because it hops between channels. Wi-Fi shows up as fixed blocks. -The unit sends its readings over Wi-Fi with MQTT to a laptop. On the laptop, a model answers two questions about each device: +The unit sends its readings over Wi-Fi with MQTT to a laptop. On the laptop, two models answer two questions about each device: -1. **Device type:** phone, earpiece, smartwatch, or allowed (a proctor's device). -2. **Distance band from the unit:** near (under 1 m), mid (1 to 2 m), or far (2 to 3.5 m). +1. **Device type:** phone, earpiece or smartwatch. Allowed devices (a proctor's phone) come from a whitelist of hashes. +2. **Near or not near:** is the device within 1 m of the unit? + +It is used in two ways: + +- **Watch mode.** The unit sits on the invigilator's desk and reports every banned device in the hall, with its type. +- **Search mode.** The invigilator carries the unit along the rows. A `NEAR` alert (under 1 m) marks the seat. + +There is no finer distance than near or not near. Calibration showed that the signal strength from one unit cannot tell 1.5 m from 3.5 m indoors ([report](docs/results/2026-11-22-first-model/report.md)). ```mermaid flowchart LR @@ -33,9 +40,9 @@ flowchart LR end U -->|Wi-Fi, MQTT| M["Mosquitto broker on the laptop"] M --> L["Logger: checks each message, writes CSV"] - L --> F["Features per time window"] + M --> F["Detector: features per 5 s window, about once a second"] F --> T["Model 1: device type"] - F --> R["Model 2: distance band"] + F --> R["Model 2: near or not near"] T --> A["Dashboard: alerts and hall map"] R --> A ``` @@ -49,7 +56,7 @@ Invigil is a Grade 12 school capstone and a work in progress. **The sensor unit Working on the real unit (first run 2026-10-26, see [docs/results](docs/results/)): - **Firmware** (`firmware/`): every self-check passes on the Pico 2 W. The unit scans BLE and the 2.4 GHz band and publishes over Wi-Fi with MQTT, with nothing rejected by the contract. The BTstack address byte order is checked and correct. The timing values are still starting guesses. See [Unit firmware](docs/firmware.md). -- **Launcher** (`invigil/`): starts the broker, the logger and the dashboard with one command, and runs guided calibration. +- **Launcher** (`invigil/`): starts the broker, the logger, the detector and the dashboard with one command, and runs guided calibration. - **Dashboard** in Live mode, reading the unit through Mosquitto. 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. @@ -57,6 +64,7 @@ First latency figure, with the laptop clock checked against NTP: over 10 minutes Also working, and testable on a laptop with no hardware: - **Logger** (`server/logger.py`): subscribes to the unit's topics, checks every message against the contract, and writes valid readings to CSV. +- **Detector** (`server/detector.py`): runs the trained models on live 5 s windows about once a second and publishes detections on MQTT. Allowed devices come from a whitelist in `server/config.toml`. - **Fake publisher** (`server/fake_publisher.py`): stands in for the unit and publishes readings in the right format. The numbers are placeholders, not physics. - **ML pipeline** (`ml/`): turns logged sessions into features, trains both models, and tests them on held-out sessions. It has only been run on synthetic data, which proves the code runs and nothing more. - **Dashboard** (`dashboard/`): the web app, with a Demo source that needs no broker and a Live source that reads Mosquitto over WebSockets. Alerts and sessions only exist in Demo so far, and no test results exist at all. See [Dashboard](#dashboard). @@ -161,7 +169,7 @@ You can run the whole laptop side with fake data and no hardware. These commands ### One command for the real unit -When the unit is on the network, the launcher runs the whole laptop side: Mosquitto with `server/mosquitto.conf`, the broker beacon the unit uses to [find the laptop](docs/firmware.md#finding-the-broker), the logger, and the dashboard on `http://127.0.0.1:8080`. It waits for the unit, opens the dashboard in Live mode and shows a status screen (broker, logger session, unit online, last status, message rates, laptop clock offset). +When the unit is on the network, the launcher runs the whole laptop side: Mosquitto with `server/mosquitto.conf`, the broker beacon the unit uses to [find the laptop](docs/firmware.md#finding-the-broker), the logger, the detector, and the dashboard on `http://127.0.0.1:8080`. It waits for the unit, opens the dashboard in Live mode and shows a status screen (broker, logger session, unit online, last status, message rates, laptop clock offset). ```powershell python -m invigil start @@ -202,7 +210,7 @@ The dashboard reads everything through one data interface with two sources. Pick - **Demo** (the default) makes mock readings in the browser. They follow the [MQTT contract](docs/contract.md) and use the same placeholder numbers as the fake publisher: the right shape, not the right physics. A "Demo data" badge stays in the top bar while Demo is active. - **Live** connects to Mosquitto with mqtt.js over WebSockets and subscribes to `invigil/node/+/+`. -Detections (device type and distance band) are not published on MQTT yet. The topic is only a proposal at the end of the [MQTT contract](docs/contract.md). So in Live the hall map and the alerts list stay empty and say why, and Sessions only fills in Demo until the server has an API for it. +In Live, the alerts, the hall map and the `NEAR` banner fill from the detector's messages ([Detections](docs/contract.md#detections)), so the detector must be running (`invigil start` runs it). Sessions only fills in Demo until the server has an API for it. Demo never shows a result. On the Results page every requirement is pending in both sources, and the confusion matrices and the RSSI chart in Demo are marked as sample data. @@ -275,7 +283,7 @@ The hall size and the seat positions on the map are placeholders in `dashboard/s | --- | --- | | `firmware/` | Pico 2 W unit code (Pico SDK, C, CMake) | | `invigil/` | The launcher: `python -m invigil start`, `stop`, `status`, `calibrate` | -| `server/` | MQTT logger, fake data publisher, later the dashboard API | +| `server/` | MQTT logger, detector, fake data publisher, later the dashboard API | | `ml/` | `features.py`, `label.py`, `train.py`, `synth.py` | | `data/raw/` | Recorded sessions. Gitignored, never committed | | `data/samples/` | Small anonymized samples that are safe to commit | @@ -285,13 +293,13 @@ The hall size and the seat positions on the map are placeholders in `dashboard/s ## Design requirements -The prototype is tested against these six requirements. None has been measured yet. +The prototype is tested against these six requirements. First results on the 2026-11-22 calibration sessions are in [model v2](docs/results/2026-11-23-model-v2/report.md); none is a final result yet. | # | Requirement | Target | | --- | --- | --- | | 1 | Response time | At most 5 s from when a device starts transmitting | | 2 | Device type accuracy | At least 85% on held-out sessions | -| 3 | Distance band accuracy | At least 80% on held-out sessions | +| 3 | Near / not-near accuracy | At least 80% on held-out sessions. Near means under 1 m from the unit. This replaced three distance bands (near, mid, far) because calibration showed RSSI cannot separate 1.5 m from 3.5 m indoors with one unit | | 4 | Alert latency | Unit to dashboard within 2 s | | 5 | False alarms | At most 1 per exam hour | | 6 | Detection range | At least 3 m, covering a 6-seat mini hall | @@ -306,7 +314,7 @@ Phase 1, one unit: - [ ] Calibration: signal strength at each distance, sweep timing, thresholds - [ ] Dataset: about 72 labeled sessions plus a sealed test set - [x] Dashboard on demo data and on live readings from the broker -- [ ] Detections on MQTT, so the live hall map and alerts fill from the real models +- [x] Detections on MQTT, so the live hall map and alerts fill from the real models - [ ] Digital twin built from the calibration data Phase 2, later: diff --git a/dashboard/src/components/invigil/band-chip.tsx b/dashboard/src/components/invigil/band-chip.tsx index f7d7e51..7fa7a7e 100644 --- a/dashboard/src/components/invigil/band-chip.tsx +++ b/dashboard/src/components/invigil/band-chip.tsx @@ -3,9 +3,9 @@ import type { ComponentProps } from "react" import type { Band } from "@/data/types" import { cn } from "@/lib/utils" -import { BAND_STYLE } from "./bands" +import { BAND_LABEL, BAND_STYLE } from "./bands" -/** A distance band: its color and always its word, so it reads in grayscale too. */ +/** Near or not near: its color and always its words, so it reads in grayscale too. */ export function BandChip({ band, className, ...props }: ComponentProps<"span"> & { band: Band }) { const style = BAND_STYLE[band] return ( @@ -18,7 +18,7 @@ export function BandChip({ band, className, ...props }: ComponentProps<"span"> & {...props} > ) } diff --git a/dashboard/src/components/invigil/bands.ts b/dashboard/src/components/invigil/bands.ts index 187ea18..109fbaa 100644 --- a/dashboard/src/components/invigil/bands.ts +++ b/dashboard/src/components/invigil/bands.ts @@ -1,17 +1,21 @@ import type { Band, DeviceType } from "@/data/types" -// near, mid and far colors mean a distance band and nothing else. Every class -// name is written out in full so Tailwind can find it. +// The near color means "within 1 m of the unit" and nothing else. not_near +// uses the far color. Every class name is written out in full so Tailwind can find it. export const BAND_STYLE: Record = { near: { mark: "bg-near", soft: "bg-near-soft", text: "text-near", stroke: "var(--near)", softVar: "var(--near-soft)" }, - mid: { mark: "bg-mid", soft: "bg-mid-soft", text: "text-mid", stroke: "var(--mid)", softVar: "var(--mid-soft)" }, - far: { mark: "bg-far", soft: "bg-far-soft", text: "text-far", stroke: "var(--far)", softVar: "var(--far-soft)" }, + not_near: { mark: "bg-far", soft: "bg-far-soft", text: "text-far", stroke: "var(--far)", softVar: "var(--far-soft)" }, +} + +/** The band in words, as it is shown. */ +export const BAND_LABEL: Record = { + near: "near", + not_near: "not near", } export const BAND_RANGE: Record = { near: "under 1 m", - mid: "1 to 2 m", - far: "2 to 3.5 m", + not_near: "1 m or more", } export const DEVICE_LABEL: Record = { diff --git a/dashboard/src/components/invigil/charts.tsx b/dashboard/src/components/invigil/charts.tsx index 2b3a7a8..36f7f5c 100644 --- a/dashboard/src/components/invigil/charts.tsx +++ b/dashboard/src/components/invigil/charts.tsx @@ -7,7 +7,7 @@ import { BANDS, BAND_EDGES_M } from "@/data/types" import type { Band, RssiByDistancePoint, RssiReading } from "@/data/types" import { formatClock } from "@/lib/format" -import { BAND_STYLE, DEVICE_LABEL } from "./bands" +import { BAND_LABEL, BAND_STYLE, DEVICE_LABEL } from "./bands" // Gridlines are line, axes are line-strong, tick labels are ink-muted in mono. const AXIS = { stroke: "var(--input)" } @@ -90,13 +90,12 @@ export function RssiTimeChart({ readings, from, to }: { readings: RssiReading[]; const distanceConfig = { near: { label: "Near", color: "var(--near)" }, - mid: { label: "Mid", color: "var(--mid)" }, - far: { label: "Far", color: "var(--far)" }, + not_near: { label: "Not near", color: "var(--far)" }, } satisfies ChartConfig -const BAND_FROM_M: Record = { near: 0, mid: BAND_EDGES_M.near, far: BAND_EDGES_M.mid } +const BAND_FROM_M: Record = { near: 0, not_near: BAND_EDGES_M.near } -/** Median RSSI of each session against its distance, with the three bands shaded behind. */ +/** Median RSSI of each session against its distance, with near and not near shaded behind. */ export function RssiDistanceChart({ points }: { points: RssiByDistancePoint[] }) { return ( @@ -110,7 +109,7 @@ export function RssiDistanceChart({ points }: { points: RssiByDistancePoint[] }) fillOpacity={1} stroke="none" label={{ - value: band.toUpperCase(), + value: BAND_LABEL[band].toUpperCase(), position: "insideTop", offset: 8, style: { ...TICK, fill: "var(--foreground)", fontWeight: 500, letterSpacing: "0.08em" }, @@ -121,7 +120,7 @@ export function RssiDistanceChart({ points }: { points: RssiByDistancePoint[] }) onSelect(alert)} aria-pressed={selected} - aria-label={`${device}, ${alert.band} band. Show signal strength.`} + aria-label={`${device}, ${BAND_LABEL[alert.band]}. Show signal strength.`} className="grid min-w-0 flex-1 cursor-pointer grid-cols-[auto_minmax(0,1fr)] items-center gap-x-3 gap-y-1 rounded-sm text-left sm:grid-cols-[auto_minmax(0,1fr)_auto_auto]" > diff --git a/dashboard/src/components/invigil/hall-map.tsx b/dashboard/src/components/invigil/hall-map.tsx index d03bb51..27c23f9 100644 --- a/dashboard/src/components/invigil/hall-map.tsx +++ b/dashboard/src/components/invigil/hall-map.tsx @@ -6,7 +6,7 @@ import type { MapDevice } from "@/data/selectors" import { BANDS, BAND_EDGES_M } from "@/data/types" import type { Band } from "@/data/types" -import { BAND_RANGE, BAND_STYLE, DEVICE_LABEL } from "./bands" +import { BAND_LABEL, BAND_RANGE, BAND_STYLE, DEVICE_LABEL } from "./bands" import { DeviceIcon } from "./icons" const PX_PER_M = 100 @@ -25,8 +25,7 @@ const ARC_TO_DEG = 152 // Where each zone's label sits, in metres from the unit, clear of the seats. const LABEL_AT: Record = { near: { x: -0.52, y: 0.3 }, - mid: { x: -1.45, y: 0.4 }, - far: { x: 0, y: 3.2 }, + not_near: { x: 0, y: 3.2 }, } function arcPoint(radiusM: number, angleDeg: number): { x: number; y: number } { @@ -53,13 +52,13 @@ interface HallMapProps { } /** - * The hall from above: the unit on the front wall, the three distance bands - * as soft tints, the six seats, and each detected device in its band. + * The hall from above: the unit on the front wall, the near zone (under 1 m) + * as a soft tint, the six seats, and each detected device in its zone. */ export function HallMap({ devices, selectedKey, onSelect }: HallMapProps) { const clipId = useId() const placed = placeDevices(devices) - const zones: Band[] = ["far", "mid", "near"] + const zones: Band[] = ["not_near", "near"] return ( - {band} + {BAND_LABEL[band]} {BAND_RANGE[band]} @@ -145,12 +144,12 @@ export function HallMap({ devices, selectedKey, onSelect }: HallMapProps) { role="button" tabIndex={0} aria-pressed={selected} - aria-label={`${name}, ${device.band} band`} + aria-label={`${name}, ${BAND_LABEL[device.band]}`} onClick={select} onKeyDown={onKeyDown} className="cursor-pointer" > - {`${name}, ${device.band} band`} + {`${name}, ${BAND_LABEL[device.band]}`} + +

+ Search mode Nothing banned within 1 m of the unit. +

+ + ) + } + + const type = DEVICE_LABEL[top.type] + const others = devices.length - 1 + return ( +
+ +
+

+ Near: {type} +

+

+ Within 1 m of the unit. Check the closest seat. + {top.rssi === null ? null : {formatDbm(top.rssi)}} + + {formatPercent(top.bandConf)} sure + + +

+
+ {others > 0 ? ( +

+ +{others} more near: {devices.slice(1).map((d) => DEVICE_LABEL[d.type]).join(", ")} +

+ ) : null} +
+ ) +} diff --git a/dashboard/src/components/invigil/signal-rings.tsx b/dashboard/src/components/invigil/signal-rings.tsx index 4895da6..4908fb4 100644 --- a/dashboard/src/components/invigil/signal-rings.tsx +++ b/dashboard/src/components/invigil/signal-rings.tsx @@ -4,18 +4,18 @@ import type { Band } from "@/data/types" import { BANDS } from "@/data/types" import { cn } from "@/lib/utils" -import { BAND_STYLE } from "./bands" +import { BAND_LABEL, BAND_STYLE } from "./bands" -const RADIUS: Record = { near: 8, mid: 15, far: 22 } +const RADIUS: Record = { near: 9, not_near: 20 } interface SignalRingsProps extends Omit, "children"> { - /** The band to light. null draws the unit with all three arcs quiet. */ + /** The band to light. null draws the unit with both arcs quiet. */ band: Band | null } /** - * The unit on the front wall with three half arcs spreading into the room. - * Only the current band's arc is lit, in its color. + * The unit on the front wall with two half arcs spreading into the room: + * near and not near. Only the current band's arc is lit, in its color. */ export function SignalRings({ band, className, ...props }: SignalRingsProps) { return ( @@ -26,7 +26,7 @@ export function SignalRings({ band, className, ...props }: SignalRingsProps) { height="22.5" fill="none" role="img" - aria-label={band ? `${band} band` : "no band"} + aria-label={band ? BAND_LABEL[band] : "no band"} className={cn("shrink-0 text-foreground", className)} {...props} > diff --git a/dashboard/src/data/__tests__/contract.test.ts b/dashboard/src/data/__tests__/contract.test.ts index 5cbb5e2..0667230 100644 --- a/dashboard/src/data/__tests__/contract.test.ts +++ b/dashboard/src/data/__tests__/contract.test.ts @@ -20,12 +20,16 @@ describe("parseTopic", () => { expect(parseTopic("invigil/node/N1/ble")).toEqual({ ok: true, value: { node: "N1", kind: "ble" } }) }) + it("accepts the detection topic the laptop detector publishes", () => { + expect(parseTopic("invigil/node/N1/detection")).toEqual({ ok: true, value: { node: "N1", kind: "detection" } }) + }) + it.each([ "invigil/node/N1", "invigil/node/N1/ble/extra", "other/node/N1/ble", "invigil/node/N9/ble", - "invigil/node/N1/detection", + "invigil/node/N1/alert", "invigil/node/N1/toString", ])("rejects %s", (name) => { expect(parseTopic(name).ok).toBe(false) diff --git a/dashboard/src/data/__tests__/store.test.ts b/dashboard/src/data/__tests__/store.test.ts index 6a63d75..c7abb18 100644 --- a/dashboard/src/data/__tests__/store.test.ts +++ b/dashboard/src/data/__tests__/store.test.ts @@ -8,6 +8,7 @@ import { isUnitOnline, mapDevices, messagesPerSecond, + nearDevices, percentile, visibleAlerts, } from "../selectors" @@ -31,7 +32,7 @@ function detection(overrides: Partial = {}): Detection { addr: "a91f03c2d4e8", type: "phone", type_conf: 0.9, - band: "mid", + band: "not_near", band_conf: 0.8, rssi: -60, ...overrides, @@ -225,13 +226,13 @@ describe("selectors", () => { it("filters alerts and hides whitelisted devices", () => { const store = makeStore() store.detection(detection(), T0) - store.detection(detection({ addr: "0123456789ab", type: "smartwatch", band: "far", ts: T0 + 1000 }), T0 + 1000) + store.detection(detection({ addr: "0123456789ab", type: "smartwatch", band: "near", ts: T0 + 1000 }), T0 + 1000) const { alerts } = store.getSnapshot() const all = { type: "all", band: "all" } as const expect(visibleAlerts(alerts, [], all).map((a) => a.id)).toEqual(["0123456789ab", "a91f03c2d4e8"]) expect(visibleAlerts(alerts, [], { type: "phone", band: "all" })).toHaveLength(1) - expect(visibleAlerts(alerts, [], { type: "all", band: "far" })).toHaveLength(1) + expect(visibleAlerts(alerts, [], { type: "all", band: "near" })).toHaveLength(1) expect(visibleAlerts(alerts, [{ addr: "a91f03c2d4e8", label: "Proctor phone" }], all)).toHaveLength(1) expect(alertLatencyP50(alerts)).toBe(0) }) @@ -242,7 +243,32 @@ describe("selectors", () => { store.detection(detection({ addr: "0123456789ab", ts: T0 - 60_000 }), T0) const devices = mapDevices(store.getSnapshot(), [{ addr: "a91f03c2d4e8", label: "Proctor phone" }], T0 + 1000) expect(devices).toEqual([ - { key: "a91f03c2d4e8", addr: "a91f03c2d4e8", type: "allowed", band: "mid", label: "Proctor phone" }, + { key: "a91f03c2d4e8", addr: "a91f03c2d4e8", type: "allowed", band: "not_near", label: "Proctor phone" }, ]) }) + + it("takes detections from the detection topic", () => { + const store = makeStore() + store.message("invigil/node/N1/detection", JSON.stringify(detection({ band: "near" })), T0 + 300) + const state = store.getSnapshot() + expect(state.counts.detection).toBe(1) + expect(state.alerts).toHaveLength(1) + expect(state.alerts[0]).toMatchObject({ type: "phone", band: "near", latencyMs: 300 }) + + store.message("invigil/node/N1/detection", JSON.stringify(detection({ band: "mid" as never })), T0) + expect(store.getSnapshot().rejected.count).toBe(1) + }) + + it("names banned devices within 1 m for the search banner, strongest first", () => { + const store = makeStore() + store.detection(detection({ band: "near", rssi: -65 }), T0) + store.detection(detection({ addr: "0123456789ab", type: "earpiece", band: "near", rssi: -55 }), T0) + store.detection(detection({ addr: "bbbbbbbbbbbb", type: "allowed", band: "near" }), T0) + store.detection(detection({ addr: "cccccccccccc", band: "not_near" }), T0) + const state = store.getSnapshot() + + expect(nearDevices(state, [], T0 + 1000).map((d) => d.type)).toEqual(["earpiece", "phone"]) + expect(nearDevices(state, [{ addr: "0123456789ab", label: "Proctor" }], T0 + 1000)).toHaveLength(1) + expect(nearDevices(state, [], T0 + 10_000)).toEqual([]) + }) }) diff --git a/dashboard/src/data/contract.ts b/dashboard/src/data/contract.ts index e6bfbe4..87bd800 100644 --- a/dashboard/src/data/contract.ts +++ b/dashboard/src/data/contract.ts @@ -3,6 +3,9 @@ // This mirrors server/contract.py field for field. If the contract changes, // change docs/contract.md, server/contract.py and this file together. +import type { Detection } from "./types" +import { BANDS, DEVICE_TYPES } from "./types" + export const TOPIC_ROOT = "invigil/node" export const SUBSCRIPTION = `${TOPIC_ROOT}/+/+` // One sensor unit for now. Phase 2 adds units here; the topic format stays the same. @@ -48,6 +51,8 @@ export interface MessageByKind { ble: BleMessage spectrum: SpectrumMessage status: StatusMessage + /** Published by the laptop's detector (server/detector.py), not by the unit. */ + detection: Detection } export type Kind = keyof MessageByKind @@ -56,6 +61,7 @@ export const FIELDS: { readonly [K in Kind]: readonly (keyof MessageByKind[K] & ble: ["ts", "node", "readings"], spectrum: ["ts", "node", "sweeps", "hits"], status: ["ts", "node", "uptime_s", "wifi_rssi", "fw"], + detection: ["ts", "node", "addr", "type", "type_conf", "band", "band_conf", "rssi"], } export const KINDS = Object.keys(FIELDS) as Kind[] @@ -154,6 +160,26 @@ function readingProblem(reading: unknown): string | null { return null } +function isUnitInterval(value: unknown): boolean { + return typeof value === "number" && value >= 0 && value <= 1 +} + +/** The checks for a detection's own fields, after ts and node. Mirrors server/contract.py. */ +export function detectionFieldProblem(p: Record): string | null { + if (p.addr !== null && (typeof p.addr !== "string" || !ADDR_RE.test(p.addr))) { + return "addr must be null or a hashed address: 12 lowercase hex chars" + } + if (!(DEVICE_TYPES as readonly unknown[]).includes(p.type)) return `type must be one of ${DEVICE_TYPES.join(", ")}` + if (!(BANDS as readonly unknown[]).includes(p.band)) return `band must be one of ${BANDS.join(", ")}` + if (!isUnitInterval(p.type_conf)) return "type_conf must be a number from 0 to 1" + if (!isUnitInterval(p.band_conf)) return "band_conf must be a number from 0 to 1" + if (p.rssi !== null) { + const rssiError = checkInt(p, "rssi", -127, 0) + if (rssiError) return rssiError + } + return null +} + /** Check a decoded JSON payload against the contract. */ export function validate( kind: K, @@ -202,6 +228,9 @@ export function validate( return fail("each hit count must be an integer from 0 to sweeps") } } + } else if (kind === "detection") { + const problem = detectionFieldProblem(p) + if (problem) return fail(problem) } else { const uptimeError = checkInt(p, "uptime_s", 0, 2 ** 31 - 1) if (uptimeError) return fail(uptimeError) diff --git a/dashboard/src/data/demo/fixtures.ts b/dashboard/src/data/demo/fixtures.ts index 4737b5e..b3b9e1b 100644 --- a/dashboard/src/data/demo/fixtures.ts +++ b/dashboard/src/data/demo/fixtures.ts @@ -13,7 +13,7 @@ import type { } from "../types" import { createRng } from "./rng" -const RECORD_AT_M: Record = { near: 0.5, mid: 1.5, far: 3 } +const RECORD_AT_M: Record = { near: 0.5, not_near: 2 } const RSSI_1M: Record = { phone: -62, earpiece: -68, smartwatch: -64, allowed: -59 } const STATES: Record = { phone: ["idle", "screen-on"], @@ -22,7 +22,7 @@ const STATES: Record = { allowed: ["normal"], } const TYPES: DeviceType[] = ["phone", "earpiece", "smartwatch", "allowed"] -const BAND_ORDER: Band[] = ["near", "mid", "far"] +const BAND_ORDER: Band[] = ["near", "not_near"] const FIRST_DAY = Date.UTC(2026, 8, 21, 7, 30) const UNLABELLED = 4 const REQUIREMENT_IDS: RequirementResult["id"][] = [1, 2, 3, 4, 5, 6] diff --git a/dashboard/src/data/demo/generator.ts b/dashboard/src/data/demo/generator.ts index 43dc452..22b591c 100644 --- a/dashboard/src/data/demo/generator.ts +++ b/dashboard/src/data/demo/generator.ts @@ -19,8 +19,10 @@ export const SEND_MS = 200 export const CYCLE_MS = SCAN_MS + SEND_MS export const SWEEPS = 20 const STATUS_EVERY_CYCLES = 10 -/** The model decides once per 5 s window (design requirement 1). */ -const DETECT_EVERY_CYCLES = 5 +/** Each decision covers the last 5 s of readings (design requirement 1). */ +const WINDOW_CYCLES = 5 +/** The detector decides about once a second, after each scan window (docs/contract.md, Detections). */ +const DETECT_EVERY_CYCLES = 1 /** Scan windows a device is on air before the first detection. */ const DETECT_AFTER_CYCLES = 3 @@ -61,9 +63,7 @@ export interface DemoCycle { } export function bandOf(distanceM: number): Band { - if (distanceM < BAND_EDGES_M.near) return "near" - if (distanceM < BAND_EDGES_M.mid) return "mid" - return "far" + return distanceM < BAND_EDGES_M.near ? "near" : "not_near" } function pathLossDb(distanceM: number): number { @@ -207,7 +207,7 @@ export function createDemoGenerator(seed: number, epoch: number): DemoGenerator } const recent = windows.get(dev) ?? [] recent.push(heard) - windows.set(dev, recent.slice(-DETECT_EVERY_CYCLES)) + windows.set(dev, recent.slice(-WINDOW_CYCLES)) } ble.sort((a, b) => a.ts - b.ts) // Like the unit: the window's readings go out together after the scan window. diff --git a/dashboard/src/data/hall.ts b/dashboard/src/data/hall.ts index 21893eb..28f2457 100644 --- a/dashboard/src/data/hall.ts +++ b/dashboard/src/data/hall.ts @@ -18,5 +18,5 @@ export const HALL = { ], } as const -/** Where a band's devices are drawn: the middle of the band, in metres from the unit. */ -export const BAND_DRAW_RADIUS_M: Record = { near: 0.62, mid: 1.5, far: 2.8 } +/** Where a band's devices are drawn, in metres from the unit. */ +export const BAND_DRAW_RADIUS_M: Record = { near: 0.62, not_near: 2.2 } diff --git a/dashboard/src/data/requirements.ts b/dashboard/src/data/requirements.ts index 087d147..8b9add7 100644 --- a/dashboard/src/data/requirements.ts +++ b/dashboard/src/data/requirements.ts @@ -16,7 +16,7 @@ export interface Requirement { export const REQUIREMENTS: readonly Requirement[] = [ { id: 1, title: "Response time", target: "at most 5 s", limit: 5, kind: "max", unit: "s", decimals: 1 }, { id: 2, title: "Device type accuracy", target: "at least 85%", limit: 85, kind: "min", unit: "%", decimals: 1 }, - { id: 3, title: "Distance band accuracy", target: "at least 80%", limit: 80, kind: "min", unit: "%", decimals: 1 }, + { id: 3, title: "Near / not-near accuracy", target: "at least 80%", limit: 80, kind: "min", unit: "%", decimals: 1 }, { id: 4, title: "Alert latency", target: "within 2 s", limit: 2, kind: "max", unit: "s", decimals: 2 }, { id: 5, title: "False alarms", target: "at most 1 per hour", limit: 1, kind: "max", unit: "per hour", decimals: 1 }, { id: 6, title: "Detection range", target: "at least 3 m", limit: 3, kind: "min", unit: "m", decimals: 1 }, diff --git a/dashboard/src/data/selectors.ts b/dashboard/src/data/selectors.ts index cd3906d..65f924d 100644 --- a/dashboard/src/data/selectors.ts +++ b/dashboard/src/data/selectors.ts @@ -107,3 +107,27 @@ export function mapDevices(state: HallState, allowed: AllowedDevice[], now: numb }) .sort((a, b) => a.key.localeCompare(b.key)) } + +/** A device to name in the search-mode banner. */ +export interface NearDevice { + key: string + addr: string | null + type: DeviceType + rssi: number | null + bandConf: number +} + +/** + * Banned devices the model places within 1 m of the unit right now: detected + * in the last NEAR_STALE_MS, not allowed, not on the dashboard's whitelist. + * Strongest signal first, so the banner names the closest one. + */ +export const NEAR_STALE_MS = 3_000 + +export function nearDevices(state: HallState, allowed: AllowedDevice[], now: number): NearDevice[] { + return Object.entries(state.detections) + .filter(([, d]) => d.band === "near" && d.type !== "allowed" && now - d.ts <= NEAR_STALE_MS) + .filter(([, d]) => allowedLabel(d.addr, allowed) === null) + .map(([key, d]) => ({ key, addr: d.addr, type: d.type, rssi: d.rssi, bandConf: d.band_conf })) + .sort((a, b) => (b.rssi ?? -127) - (a.rssi ?? -127)) +} diff --git a/dashboard/src/data/store.ts b/dashboard/src/data/store.ts index 8d634f4..52107e7 100644 --- a/dashboard/src/data/store.ts +++ b/dashboard/src/data/store.ts @@ -1,4 +1,4 @@ -import { decode } from "./contract" +import { decode, detectionFieldProblem } from "./contract" import type { Alert, AlertState, @@ -9,7 +9,6 @@ import type { HeardDevice, RejectReason, } from "./types" -import { BANDS, DEVICE_TYPES } from "./types" export const MAX_READINGS_PER_DEVICE = 600 export const MAX_STATUS_ENTRIES = 50 @@ -17,8 +16,6 @@ export const MAX_REJECT_REASONS = 20 export const RATE_WINDOW_MS = 10_000 export const LATENCY_WINDOW_MS = 60_000 -const ADDR_RE = /^[0-9a-f]{12}$/ - function emptyState(now: number): HallState { return { connection: { phase: "idle", detail: "Not connected" }, @@ -40,23 +37,10 @@ export function deviceKey(d: { addr: string | null; node: string; type: string } return d.addr ?? `${d.node}:spectrum:${d.type}` } -function isUnitInterval(value: unknown): value is number { - return typeof value === "number" && value >= 0 && value <= 1 -} - -/** Check a detection against the proposed payload in docs/contract.md. */ +/** Check a detection against the detection topic in docs/contract.md. */ export function detectionProblem(d: Detection): string | null { if (!Number.isInteger(d.ts)) return "ts must be an integer" - if (d.addr !== null && !ADDR_RE.test(d.addr)) return "addr must be null or a hashed address" - if (!DEVICE_TYPES.includes(d.type)) return "unknown device type" - if (!BANDS.includes(d.band)) return "unknown distance band" - if (!isUnitInterval(d.type_conf) || !isUnitInterval(d.band_conf)) { - return "confidence must be between 0 and 1" - } - if (d.rssi !== null && (!Number.isInteger(d.rssi) || d.rssi < -127 || d.rssi > 0)) { - return "rssi must be null or an integer from -127 to 0" - } - return null + return detectionFieldProblem(d as unknown as Record) } export interface HallStore extends DataSink { @@ -127,6 +111,45 @@ export function createHallStore(options: StoreOptions = {}): HallStore { state.latencies = kept } + function addDetection(d: Detection, rxTs: number) { + const key = deviceKey(d) + state.detections = { ...state.detections, [key]: d } + state.counts = { ...state.counts, detection: state.counts.detection + 1 } + + // Allowed devices are tracked for the hall map but never raise an alert. + if (d.type !== "allowed") { + const existing = state.alerts.find((a) => a.id === key) + if (existing) { + const updated: Alert = { + ...existing, + type: d.type, + band: d.band, + typeConf: d.type_conf, + bandConf: d.band_conf, + rssi: d.rssi, + lastTs: d.ts, + } + state.alerts = state.alerts.map((a) => (a.id === key ? updated : a)) + } else { + const created: Alert = { + id: key, + node: d.node, + addr: d.addr, + type: d.type, + band: d.band, + typeConf: d.type_conf, + bandConf: d.band_conf, + rssi: d.rssi, + firstTs: d.ts, + lastTs: d.ts, + latencyMs: rxTs - d.ts, + state: "new", + } + state.alerts = [created, ...state.alerts] + } + } + } + return { subscribe(listener) { listeners.add(listener) @@ -165,6 +188,8 @@ export function createHallStore(options: StoreOptions = {}): HallStore { } state.heard = heard state.counts = { ...state.counts, ble: state.counts.ble + msg.payload.readings.length } + } else if (msg.kind === "detection") { + addDetection(msg.payload, rxTs) } else if (msg.kind === "spectrum") { state.spectrum = msg.payload state.counts = { ...state.counts, spectrum: state.counts.spectrum + 1 } @@ -183,42 +208,7 @@ export function createHallStore(options: StoreOptions = {}): HallStore { reject(`detection: ${problem}`, rxTs) return } - const key = deviceKey(d) - state.detections = { ...state.detections, [key]: d } - state.counts = { ...state.counts, detection: state.counts.detection + 1 } - - // Allowed devices are tracked for the hall map but never raise an alert. - if (d.type !== "allowed") { - const existing = state.alerts.find((a) => a.id === key) - if (existing) { - const updated: Alert = { - ...existing, - type: d.type, - band: d.band, - typeConf: d.type_conf, - bandConf: d.band_conf, - rssi: d.rssi, - lastTs: d.ts, - } - state.alerts = state.alerts.map((a) => (a.id === key ? updated : a)) - } else { - const created: Alert = { - id: key, - node: d.node, - addr: d.addr, - type: d.type, - band: d.band, - typeConf: d.type_conf, - bandConf: d.band_conf, - rssi: d.rssi, - firstTs: d.ts, - lastTs: d.ts, - latencyMs: rxTs - d.ts, - state: "new", - } - state.alerts = [created, ...state.alerts] - } - } + addDetection(d, rxTs) touch() }, diff --git a/dashboard/src/data/types.ts b/dashboard/src/data/types.ts index 28a292d..062be56 100644 --- a/dashboard/src/data/types.ts +++ b/dashboard/src/data/types.ts @@ -3,16 +3,19 @@ import type { Result, SpectrumMessage, StatusMessage } from "./contract" export const DEVICE_TYPES = ["phone", "earpiece", "smartwatch", "allowed"] as const export type DeviceType = (typeof DEVICE_TYPES)[number] -export const BANDS = ["near", "mid", "far"] as const +/** + * near: under 1 m from the unit. not_near: anything farther. Calibration showed + * that one unit cannot tell 1.5 m from 3.5 m indoors, so there is no mid or far. + */ +export const BANDS = ["near", "not_near"] as const export type Band = (typeof BANDS)[number] -/** Upper edge of each distance band in metres, from docs/data-protocol.md. */ -export const BAND_EDGES_M: Record = { near: 1, mid: 2, far: 3.5 } +/** Upper edge of each band in metres. not_near ends at the 3.5 m detection range. */ +export const BAND_EDGES_M: Record = { near: 1, not_near: 3.5 } /** - * One model output for one device over one decision window. - * This is the payload proposed in docs/contract.md. It is not on MQTT yet, - * so only the Demo source produces it. + * One model output for one device over one decision window: the detection + * topic in docs/contract.md, published by the laptop's detector about once a second. */ export interface Detection { ts: number diff --git a/dashboard/src/pages/live.tsx b/dashboard/src/pages/live.tsx index 34d3ff6..6a046a4 100644 --- a/dashboard/src/pages/live.tsx +++ b/dashboard/src/pages/live.tsx @@ -3,12 +3,13 @@ import { useMemo, useState } from "react" import { useData, useHall, useNow } from "@/app/data" import { useSettings } from "@/app/settings" -import { BAND_RANGE, DEVICE_LABEL } from "@/components/invigil/bands" +import { BAND_LABEL, BAND_RANGE, DEVICE_LABEL } from "@/components/invigil/bands" import { RssiTimeChart } from "@/components/invigil/charts" import { DetectionAlert } from "@/components/invigil/detection-alert" import { EmptyState } from "@/components/invigil/empty-state" import { HallMap } from "@/components/invigil/hall-map" import { Metric } from "@/components/invigil/metric" +import { NearBanner } from "@/components/invigil/near-banner" import { Page, Panel } from "@/components/page" import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select" import { Skeleton } from "@/components/ui/skeleton" @@ -20,6 +21,7 @@ import { falseAlarmsPerHour, mapDevices, messageLatencyP50, + nearDevices, visibleAlerts, } from "@/data/selectors" import type { AlertFilter } from "@/data/selectors" @@ -32,6 +34,7 @@ const ALERT_TYPES = DEVICE_TYPES.filter((t) => t !== "allowed") function LoadingLive() { return ( <> + {[0, 1, 2, 3].map((i) => ( ))} @@ -57,6 +60,7 @@ export function LivePage() { [hall.alerts, settings.allowed] ) const devices = mapDevices(hall, settings.allowed, now) + const near = nearDevices(hall, settings.allowed, now) const heard = devicesHeard(hall, now) const everHeard = useMemo(() => Object.values(hall.heard).sort((a, b) => b.lastTs - a.lastTs), [hall.heard]) @@ -82,12 +86,13 @@ export function LivePage() { return ( {connecting ? ( ) : ( <> + @@ -130,7 +135,7 @@ export function LivePage() {
} title="No devices on the map"> {isDemo - ? "A device appears in its band once the model has flagged it. None was detected in the last 15 s." - : "Devices appear in their band once detections are published. The detection topic is only a proposal so far, so the map fills in Demo only."} + ? "A device appears in its zone once the model has flagged it. None was detected in the last 15 s." + : "A device appears in its zone once the detector flags it. None was detected in the last 15 s. If this stays empty, check that invigil status shows the detector running."}
) : null}

- Devices are placed by distance band only. Where a device sits along its arc is not measured. + Devices are placed by near or not near only. Where a device sits along its arc is not measured.

@@ -179,14 +184,14 @@ export function LivePage() {