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 CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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-<name>/` with the raw summary, plots and a short note.
- **Writing:** plain, direct English in docs and UI text.
Expand Down
32 changes: 20 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
```
Expand All @@ -49,14 +56,15 @@ 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.

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).
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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 |
Expand All @@ -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 |
Expand All @@ -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:
Expand Down
6 changes: 3 additions & 3 deletions dashboard/src/components/invigil/band-chip.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand All @@ -18,7 +18,7 @@ export function BandChip({ band, className, ...props }: ComponentProps<"span"> &
{...props}
>
<span className={cn("size-2 rounded-full", style.mark)} aria-hidden="true" />
{band}
{BAND_LABEL[band]}
</span>
)
}
16 changes: 10 additions & 6 deletions dashboard/src/components/invigil/bands.ts
Original file line number Diff line number Diff line change
@@ -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<Band, { mark: string; soft: string; text: string; stroke: string; softVar: string }> = {
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<Band, string> = {
near: "near",
not_near: "not near",
}

export const BAND_RANGE: Record<Band, string> = {
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<DeviceType, string> = {
Expand Down
13 changes: 6 additions & 7 deletions dashboard/src/components/invigil/charts.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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)" }
Expand Down Expand Up @@ -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<Band, number> = { near: 0, mid: BAND_EDGES_M.near, far: BAND_EDGES_M.mid }
const BAND_FROM_M: Record<Band, number> = { 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 (
<ChartContainer config={distanceConfig} className="aspect-auto h-72 w-full">
Expand All @@ -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" },
Expand All @@ -121,7 +120,7 @@ export function RssiDistanceChart({ points }: { points: RssiByDistancePoint[] })
<XAxis
dataKey="distanceM"
type="number"
domain={[0, BAND_EDGES_M.far]}
domain={[0, BAND_EDGES_M.not_near]}
ticks={[0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5]}
tick={TICK}
axisLine={AXIS}
Expand Down
4 changes: 2 additions & 2 deletions dashboard/src/components/invigil/detection-alert.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { formatAgo, formatClock, formatDbm, formatPercent } from "@/lib/format"
import { cn } from "@/lib/utils"

import { BandChip } from "./band-chip"
import { BAND_STYLE, DEVICE_LABEL } from "./bands"
import { BAND_LABEL, BAND_STYLE, DEVICE_LABEL } from "./bands"
import { DeviceTag, Hash } from "./device-tag"
import { SignalRings } from "./signal-rings"

Expand Down Expand Up @@ -47,7 +47,7 @@ export function DetectionAlert({ alert, now, selected, onSelect, onStateChange }
type="button"
onClick={() => 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]"
>
<SignalRings band={alert.band} className={cn(!isNew && "opacity-70")} />
Expand Down
17 changes: 8 additions & 9 deletions dashboard/src/components/invigil/hall-map.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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<Band, { x: number; y: number }> = {
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 } {
Expand All @@ -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 (
<svg
Expand Down Expand Up @@ -101,7 +100,7 @@ export function HallMap({ devices, selectedKey, onSelect }: HallMapProps) {
const y = TOP + p.y * PX_PER_M
return (
<text key={band} x={x} y={y} textAnchor="middle" className="fill-foreground font-mono text-[11px] font-medium tracking-[0.08em] uppercase">
{band}
{BAND_LABEL[band]}
<tspan x={x} dy="13" className="fill-muted-foreground tracking-normal normal-case">
{BAND_RANGE[band]}
</tspan>
Expand Down Expand Up @@ -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"
>
<title>{`${name}, ${device.band} band`}</title>
<title>{`${name}, ${BAND_LABEL[device.band]}`}</title>
<circle
cx={x}
cy={y}
Expand Down
67 changes: 67 additions & 0 deletions dashboard/src/components/invigil/near-banner.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import type { NearDevice } from "@/data/selectors"
import { formatDbm, formatPercent } from "@/lib/format"
import { cn } from "@/lib/utils"

import { DEVICE_LABEL } from "./bands"
import { Hash } from "./device-tag"
import { DeviceIcon } from "./icons"
import { SignalRings } from "./signal-rings"

interface NearBannerProps {
devices: NearDevice[]
className?: string
}

/**
* Search mode: the invigilator carries the unit along the rows. When a banned
* device is within 1 m, this names it in letters big enough to read at arm's
* length. With nothing near, it stays as a quiet line so the layout does not jump.
*/
export function NearBanner({ devices, className }: NearBannerProps) {
const top = devices[0]
if (!top) {
return (
<section
role="status"
aria-live="polite"
className={cn("flex items-center gap-3 rounded-lg border bg-card px-4 py-3", className)}
>
<SignalRings band={null} />
<p className="text-[15px] text-muted-foreground">
<span className="label-caps text-foreground">Search mode</span> Nothing banned within 1 m of the unit.
</p>
</section>
)
}

const type = DEVICE_LABEL[top.type]
const others = devices.length - 1
return (
<section
role="alert"
aria-live="assertive"
aria-label={`Near: ${type}`}
className={cn("flex flex-wrap items-center gap-x-6 gap-y-3 rounded-lg border-2 border-near bg-near-soft px-5 py-4", className)}
>
<DeviceIcon type={top.type} width="56" height="56" className="shrink-0 text-foreground" />
<div className="flex min-w-0 flex-1 flex-col gap-1">
<p className="font-display text-5xl leading-none font-bold tracking-tight text-foreground uppercase sm:text-6xl">
Near: {type}
</p>
<p className="flex flex-wrap items-baseline gap-x-3 text-[15px] text-foreground">
<span>Within 1 m of the unit. Check the closest seat.</span>
{top.rssi === null ? null : <span className="data">{formatDbm(top.rssi)}</span>}
<span className="data text-muted-foreground" title="Model confidence that the device is near">
{formatPercent(top.bandConf)} sure
</span>
<Hash addr={top.addr} />
</p>
</div>
{others > 0 ? (
<p className="label-caps text-foreground">
+{others} more near: {devices.slice(1).map((d) => DEVICE_LABEL[d.type]).join(", ")}
</p>
) : null}
</section>
)
}
Loading