diff --git a/dashboard/src/data/__tests__/contract.test.ts b/dashboard/src/data/__tests__/contract.test.ts index 3b25495..5cbb5e2 100644 --- a/dashboard/src/data/__tests__/contract.test.ts +++ b/dashboard/src/data/__tests__/contract.test.ts @@ -1,9 +1,13 @@ import { describe, expect, it } from "vitest" -import { decode, parseTopic, validate } from "../contract" +import { MAX_BLE_PAYLOAD_BYTES, decode, packBle, parseTopic, validate } from "../contract" +import type { BleReading } from "../contract" const TS = 1_727_340_000_123 -const ble = () => ({ ts: TS, node: "N1", addr: "a91f03c2d4e8", rssi: -58, mfr: "0x004C" as string | null }) +const reading = (): BleReading => ({ ts: TS, addr: "a91f03c2d4e8", rssi: -58, mfr: "0x004C" }) +const ble = () => ({ ts: TS + 877, node: "N1", readings: [reading()] }) +/** A ble message whose one reading has these changes. */ +const bleWith = (changes: Record) => ({ ...ble(), readings: [{ ...reading(), ...changes }] }) const spectrum = () => ({ ts: TS, node: "N1", sweeps: 50, hits: new Array(126).fill(0) }) const status = () => ({ ts: TS, node: "N1", uptime_s: 3600, wifi_rssi: -61, fw: "0.1.0" }) @@ -36,7 +40,7 @@ describe("validate", () => { }) it("accepts a null manufacturer", () => { - expect(validate("ble", { ...ble(), mfr: null }).ok).toBe(true) + expect(validate("ble", bleWith({ mfr: null })).ok).toBe(true) }) it("rejects payloads that are not objects", () => { @@ -47,19 +51,41 @@ describe("validate", () => { it("rejects missing and extra fields", () => { const missing: Record = ble() - delete missing.rssi - expect(reason(validate("ble", missing))).toBe("missing field(s): rssi") + delete missing.readings + expect(reason(validate("ble", missing))).toBe("missing field(s): readings") expect(reason(validate("ble", { ...ble(), name: "x" }))).toBe("unexpected field(s): name") + const noRssi: Record = { ...reading() } + delete noRssi.rssi + expect(reason(validate("ble", { ...ble(), readings: [noRssi] }))).toBe("reading is missing field(s): rssi") + expect(reason(validate("ble", bleWith({ name: "x" })))).toBe("reading has unexpected field(s): name") + }) + + it("rejects the old one-reading shape", () => { + const old = { ts: TS, node: "N1", addr: "a91f03c2d4e8", rssi: -58, mfr: "0x004C" } + expect(validate("ble", old).ok).toBe(false) + }) + + it("accepts several readings and rejects an empty or malformed list", () => { + const two = { ...ble(), readings: [reading(), { ...reading(), ts: TS + 300, addr: "0f5e2b7a91c4", mfr: null }] } + expect(validate("ble", two, "N1").ok).toBe(true) + for (const readings of [[], null, "x", [null], [[1, 2]]]) { + expect(validate("ble", { ...ble(), readings }).ok).toBe(false) + } + }) + + it("rejects the whole message when one reading is bad", () => { + const mixed = { ...ble(), readings: [reading(), { ...reading(), rssi: 3 }] } + expect(reason(validate("ble", mixed))).toBe("reading rssi is out of range -127..0") }) it("rejects a raw MAC, uppercase hex and a short hash", () => { for (const addr of ["A9:1F:03:C2:D4:E8", "A91F03C2D4E8", "a91f03c2d4e", "a91f03c2d4e8f", 123]) { - expect(reason(validate("ble", { ...ble(), addr }))).toMatch(/hashed address/) + expect(reason(validate("ble", bleWith({ addr })))).toMatch(/hashed address/) } }) it("never echoes a rejected value", () => { - const result = validate("ble", { ...ble(), addr: "A9:1F:03:C2:D4:E8" }) + const result = validate("ble", bleWith({ addr: "A9:1F:03:C2:D4:E8" })) expect(reason(result)).not.toContain("A9:1F") }) @@ -67,19 +93,22 @@ describe("validate", () => { expect(reason(validate("ble", { ...ble(), ts: 1_727_340_000 }))).toMatch(/too small/) expect(reason(validate("ble", { ...ble(), ts: TS * 1000 }))).toMatch(/out of range/) expect(reason(validate("ble", { ...ble(), ts: TS + 0.5 }))).toBe("ts must be an integer") + expect(reason(validate("ble", bleWith({ ts: 1_727_340_000 })))).toMatch(/reading ts is too small/) + expect(reason(validate("ble", bleWith({ ts: TS * 1000 })))).toMatch(/out of range/) + expect(reason(validate("ble", bleWith({ ts: TS + 0.5 })))).toBe("reading ts must be an integer") }) it("rejects an rssi that is out of range or not an integer", () => { - expect(validate("ble", { ...ble(), rssi: 1 }).ok).toBe(false) - expect(validate("ble", { ...ble(), rssi: -128 }).ok).toBe(false) - expect(validate("ble", { ...ble(), rssi: -58.5 }).ok).toBe(false) - expect(validate("ble", { ...ble(), rssi: true }).ok).toBe(false) - expect(validate("ble", { ...ble(), rssi: "-58" }).ok).toBe(false) + expect(validate("ble", bleWith({ rssi: 1 })).ok).toBe(false) + expect(validate("ble", bleWith({ rssi: -128 })).ok).toBe(false) + expect(validate("ble", bleWith({ rssi: -58.5 })).ok).toBe(false) + expect(validate("ble", bleWith({ rssi: true })).ok).toBe(false) + expect(validate("ble", bleWith({ rssi: "-58" })).ok).toBe(false) }) it("rejects a malformed manufacturer ID", () => { for (const mfr of ["0x004c", "004C", "0x4C", 76]) { - expect(validate("ble", { ...ble(), mfr }).ok).toBe(false) + expect(validate("ble", bleWith({ mfr })).ok).toBe(false) } }) @@ -133,3 +162,37 @@ describe("decode", () => { expect(reason(decode("invigil/other", "{not json"))).toMatch(/topic is not/) }) }) + +describe("packBle", () => { + const bytes = (value: unknown) => new TextEncoder().encode(JSON.stringify(value)).length + + it("keeps order, stays under the size limit and uses as few messages as it can", () => { + const readings: BleReading[] = Array.from({ length: 200 }, (_, i) => ({ + ts: TS + i, + addr: "a91f03c2d4e8", + rssi: -(i % 128), + mfr: i % 3 ? null : "0x004C", + })) + const messages = packBle(TS + 1000, "N1", readings) + expect(messages.length).toBeGreaterThan(1) + expect(messages.flatMap((m) => m.readings)).toEqual(readings) + for (const m of messages) { + expect(validate("ble", m, "N1").ok).toBe(true) + expect(bytes(m)).toBeLessThanOrEqual(MAX_BLE_PAYLOAD_BYTES) + } + for (let i = 0; i + 1 < messages.length; i++) { + const bigger = { ...messages[i], readings: [...messages[i].readings, messages[i + 1].readings[0]] } + expect(bytes(bigger)).toBeGreaterThan(MAX_BLE_PAYLOAD_BYTES) + } + }) + + it("fits 19 worst-case readings in one message, as docs/contract.md says", () => { + const worst: BleReading = { ts: 9_999_999_999_999, addr: "a91f03c2d4e8", rssi: -127, mfr: "0xFFFF" } + expect(bytes(worst)).toBe(69) + expect(packBle(9_999_999_999_999, "N1", new Array(40).fill(worst))[0].readings).toHaveLength(19) + }) + + it("sends nothing for no readings", () => { + expect(packBle(TS, "N1", [])).toEqual([]) + }) +}) diff --git a/dashboard/src/data/__tests__/store.test.ts b/dashboard/src/data/__tests__/store.test.ts index c2350de..6a63d75 100644 --- a/dashboard/src/data/__tests__/store.test.ts +++ b/dashboard/src/data/__tests__/store.test.ts @@ -21,7 +21,7 @@ function makeStore() { } function ble(ts: number, addr = "a91f03c2d4e8", rssi = -58) { - return JSON.stringify({ ts, node: "N1", addr, rssi, mfr: "0x004C" }) + return JSON.stringify({ ts: ts + 500, node: "N1", readings: [{ ts, addr, rssi, mfr: "0x004C" }] }) } function detection(overrides: Partial = {}): Detection { @@ -48,11 +48,39 @@ describe("message ingest", () => { expect(state.lastRxTs).toBe(T0 + 120) }) + it("stores every reading of a batched message and counts readings", () => { + const store = makeStore() + const msg = { + ts: T0 + 1000, + node: "N1", + readings: [ + { ts: T0, addr: "a91f03c2d4e8", rssi: -58, mfr: "0x004C" }, + { ts: T0 + 200, addr: "0123456789ab", rssi: -80, mfr: null }, + { ts: T0 + 400, addr: "a91f03c2d4e8", rssi: -61, mfr: null }, + ], + } + store.message("invigil/node/N1/ble", JSON.stringify(msg), T0 + 1100) + const state = store.getSnapshot() + expect(state.counts.ble).toBe(3) + expect(state.heard.a91f03c2d4e8.count).toBe(2) + expect(state.heard.a91f03c2d4e8.readings).toEqual([ + { ts: T0, rssi: -58 }, + { ts: T0 + 400, rssi: -61 }, + ]) + expect(state.heard.a91f03c2d4e8.mfr).toBe("0x004C") + expect(state.heard.a91f03c2d4e8.lastTs).toBe(T0 + 400) + expect(state.heard["0123456789ab"].count).toBe(1) + expect(state.rxTimes).toHaveLength(1) + }) + it("drops and counts bad messages without throwing", () => { const store = makeStore() const bad: [string, string][] = [ ["invigil/node/N1/ble", "{broken"], - ["invigil/node/N1/ble", JSON.stringify({ ts: T0, node: "N1", addr: "A9:1F:03:C2:D4:E8", rssi: -58, mfr: null })], + [ + "invigil/node/N1/ble", + JSON.stringify({ ts: T0, node: "N1", readings: [{ ts: T0, addr: "A9:1F:03:C2:D4:E8", rssi: -58, mfr: null }] }), + ], ["invigil/node/N1/spectrum", JSON.stringify({ ts: T0, node: "N1", sweeps: 20, hits: [1, 2, 3] })], ["invigil/node/N1/status", JSON.stringify({ ts: 1_727_340_000, node: "N1", uptime_s: 1, wifi_rssi: -60, fw: "0.1.0" })], ["invigil/node/N7/ble", ble(T0)], diff --git a/dashboard/src/data/contract.ts b/dashboard/src/data/contract.ts index a32f12e..e6bfbe4 100644 --- a/dashboard/src/data/contract.ts +++ b/dashboard/src/data/contract.ts @@ -14,14 +14,21 @@ export const NUM_CHANNELS = 126 export const MIN_TS_MS = 1_600_000_000_000 export const MAX_TS_MS = 9_999_999_999_999 -export interface BleMessage { +/** One advertisement inside a ble message. */ +export interface BleReading { ts: number - node: string addr: string rssi: number mfr: string | null } +/** All the readings from one scan window, or part of them (see MAX_BLE_PAYLOAD_BYTES). */ +export interface BleMessage { + ts: number + node: string + readings: BleReading[] +} + export interface SpectrumMessage { ts: number node: string @@ -46,13 +53,17 @@ export interface MessageByKind { export type Kind = keyof MessageByKind export const FIELDS: { readonly [K in Kind]: readonly (keyof MessageByKind[K] & string)[] } = { - ble: ["ts", "node", "addr", "rssi", "mfr"], + ble: ["ts", "node", "readings"], spectrum: ["ts", "node", "sweeps", "hits"], status: ["ts", "node", "uptime_s", "wifi_rssi", "fw"], } export const KINDS = Object.keys(FIELDS) as Kind[] +export const READING_FIELDS: readonly (keyof BleReading & string)[] = ["ts", "addr", "rssi", "mfr"] +/** The unit keeps every ble payload at or under this many bytes (docs/contract.md, Size limit). */ +export const MAX_BLE_PAYLOAD_BYTES = 1400 + export type ContractMessage = { [K in Kind]: { kind: K; node: string; payload: MessageByKind[K] } }[Kind] @@ -103,6 +114,46 @@ function checkInt( return null } +/** what is "" for the message itself, or "reading" for one reading inside it. */ +function checkFields(p: Record, expected: readonly string[], what: string): string | null { + const missing = expected.filter((k) => !Object.hasOwn(p, k)) + if (missing.length > 0) { + return `${what ? `${what} is missing` : "missing"} field(s): ${missing.join(", ")}` + } + const extra = Object.keys(p) + .filter((k) => !expected.includes(k)) + .sort() + if (extra.length > 0) { + return `${what ? `${what} has unexpected` : "unexpected"} field(s): ${extra.join(", ")}` + } + return null +} + +function readingProblem(reading: unknown): string | null { + if (typeof reading !== "object" || reading === null || Array.isArray(reading)) { + return "each reading must be a JSON object" + } + const r = reading as Record + const fieldsError = checkFields(r, READING_FIELDS, "reading") + if (fieldsError) return fieldsError + + const tsError = checkInt(r, "ts", 0, MAX_TS_MS) + if (tsError) return `reading ${tsError}` + if ((r.ts as number) < MIN_TS_MS) { + return "reading ts is too small: unit clock not synced, or seconds sent instead of ms" + } + if (typeof r.addr !== "string" || !ADDR_RE.test(r.addr)) { + return "reading addr must be a hashed address: 12 lowercase hex chars" + } + const rssiError = checkInt(r, "rssi", -127, 0) + if (rssiError) return `reading ${rssiError}` + // null is allowed: many advertisements carry no manufacturer data. + if (r.mfr !== null && (typeof r.mfr !== "string" || !MFR_RE.test(r.mfr))) { + return 'reading mfr must be null or a company ID like "0x004C"' + } + return null +} + /** Check a decoded JSON payload against the contract. */ export function validate( kind: K, @@ -114,13 +165,8 @@ export function validate( } const p = payload as Record - const expected: readonly string[] = FIELDS[kind] - const missing = expected.filter((k) => !Object.hasOwn(p, k)) - if (missing.length > 0) return fail(`missing field(s): ${missing.join(", ")}`) - const extra = Object.keys(p) - .filter((k) => !expected.includes(k)) - .sort() - if (extra.length > 0) return fail(`unexpected field(s): ${extra.join(", ")}`) + const fieldsError = checkFields(p, FIELDS[kind], "") + if (fieldsError) return fail(fieldsError) const tsError = checkInt(p, "ts", 0, MAX_TS_MS) if (tsError) return fail(tsError) @@ -135,14 +181,13 @@ export function validate( } if (kind === "ble") { - if (typeof p.addr !== "string" || !ADDR_RE.test(p.addr)) { - return fail("addr must be a hashed address: 12 lowercase hex chars") + const readings = p.readings + if (!Array.isArray(readings) || readings.length === 0) { + return fail("readings must be a list of one or more readings") } - const rssiError = checkInt(p, "rssi", -127, 0) - if (rssiError) return fail(rssiError) - // null is allowed: many advertisements carry no manufacturer data. - if (p.mfr !== null && (typeof p.mfr !== "string" || !MFR_RE.test(p.mfr))) { - return fail('mfr must be null or a company ID like "0x004C"') + for (const reading of readings) { + const problem = readingProblem(reading) + if (problem) return fail(problem) } } else if (kind === "spectrum") { const sweepsError = checkInt(p, "sweeps", 1, 65_535) @@ -170,6 +215,37 @@ export function validate( return { ok: true, value: p as unknown as MessageByKind[K] } } +/** + * Split readings into as few ble messages as fit maxBytes each, in order. + * Sizes are those of compact JSON, which is what JSON.stringify writes. + * Mirrors pack_ble() in server/contract.py. + */ +export function packBle( + ts: number, + node: string, + readings: readonly BleReading[], + maxBytes = MAX_BLE_PAYLOAD_BYTES +): BleMessage[] { + const bytes = (value: unknown) => new TextEncoder().encode(JSON.stringify(value)).length + const empty = bytes({ ts, node, readings: [] }) + const messages: BleMessage[] = [] + let current: BleReading[] = [] + let size = empty + for (const reading of readings) { + let add = bytes(reading) + (current.length > 0 ? 1 : 0) // 1 for the comma + if (current.length > 0 && size + add > maxBytes) { + messages.push({ ts, node, readings: current }) + current = [] + size = empty + add -= 1 + } + current.push(reading) + size += add + } + if (current.length > 0) messages.push({ ts, node, readings: current }) + return messages +} + /** Parse and check one raw MQTT message. Never throws. */ export function decode(topicName: string, raw: string): Result { const parsed = parseTopic(topicName) diff --git a/dashboard/src/data/demo/generator.ts b/dashboard/src/data/demo/generator.ts index a928173..43dc452 100644 --- a/dashboard/src/data/demo/generator.ts +++ b/dashboard/src/data/demo/generator.ts @@ -5,15 +5,15 @@ // data has the right shape, not the right physics: every constant below is the // same placeholder guess the fake publisher uses, not a measurement. -import { NUM_CHANNELS, topic } from "../contract" -import type { BleMessage, SpectrumMessage, StatusMessage } from "../contract" +import { NUM_CHANNELS, packBle, topic } from "../contract" +import type { BleReading, SpectrumMessage, StatusMessage } from "../contract" import type { Band, Detection, DeviceType } from "../types" import { BAND_EDGES_M } from "../types" import { createRng } from "./rng" import type { Rng } from "./rng" export const DEMO_NODE = "N1" -export const DEMO_FW = "0.1.0-demo" +export const DEMO_FW = "0.2.0-demo" export const SCAN_MS = 800 export const SEND_MS = 200 export const CYCLE_MS = SCAN_MS + SEND_MS @@ -188,7 +188,7 @@ export function createDemoGenerator(seed: number, epoch: number): DemoGenerator const rxTs = t1 + Math.round(rng.uniform(60, 300)) const out: DemoCycle = { messages: [], detections: [] } - const ble: BleMessage[] = [] + const ble: BleReading[] = [] for (const dev of devices) { const heard: number[] = [] const on = t0 - epoch >= dev.onAtMs @@ -202,7 +202,7 @@ export function createDemoGenerator(seed: number, epoch: number): DemoGenerator if (rssi < BLE_SENSITIVITY_DBM || rng.next() > BLE_CATCH_RATE) continue const reading = clampRssi(rssi) heard.push(reading) - ble.push({ ts: Math.floor(t), node: DEMO_NODE, addr: dev.addr, rssi: reading, mfr: dev.mfr }) + ble.push({ ts: Math.floor(t), addr: dev.addr, rssi: reading, mfr: dev.mfr }) } } const recent = windows.get(dev) ?? [] @@ -210,7 +210,8 @@ export function createDemoGenerator(seed: number, epoch: number): DemoGenerator windows.set(dev, recent.slice(-DETECT_EVERY_CYCLES)) } ble.sort((a, b) => a.ts - b.ts) - for (const m of ble) { + // Like the unit: the window's readings go out together after the scan window. + for (const m of packBle(t1, DEMO_NODE, ble)) { out.messages.push({ topic: topic(DEMO_NODE, "ble"), payload: JSON.stringify(m), rxTs }) } diff --git a/dashboard/src/data/store.ts b/dashboard/src/data/store.ts index 01a9fd4..8d634f4 100644 --- a/dashboard/src/data/store.ts +++ b/dashboard/src/data/store.ts @@ -149,21 +149,22 @@ export function createHallStore(options: StoreOptions = {}): HallStore { received(rxTs) if (msg.kind === "ble") { - const { addr, rssi, mfr, ts } = msg.payload - const previous: HeardDevice | undefined = state.heard[addr] - const readings = previous ? previous.readings.slice(-(MAX_READINGS_PER_DEVICE - 1)) : [] - readings.push({ ts, rssi }) - state.heard = { - ...state.heard, - [addr]: { + // One message carries a whole scan window. Each reading counts on its own. + const heard = { ...state.heard } + for (const { addr, rssi, mfr, ts } of msg.payload.readings) { + const previous: HeardDevice | undefined = heard[addr] + const readings = previous ? previous.readings.slice(-(MAX_READINGS_PER_DEVICE - 1)) : [] + readings.push({ ts, rssi }) + heard[addr] = { addr, mfr: mfr ?? previous?.mfr ?? null, count: (previous?.count ?? 0) + 1, lastTs: Math.max(ts, previous?.lastTs ?? 0), readings, - }, + } } - state.counts = { ...state.counts, ble: state.counts.ble + 1 } + state.heard = heard + state.counts = { ...state.counts, ble: state.counts.ble + msg.payload.readings.length } } else if (msg.kind === "spectrum") { state.spectrum = msg.payload state.counts = { ...state.counts, spectrum: state.counts.spectrum + 1 } diff --git a/dashboard/src/data/types.ts b/dashboard/src/data/types.ts index acd7764..28a292d 100644 --- a/dashboard/src/data/types.ts +++ b/dashboard/src/data/types.ts @@ -87,6 +87,7 @@ export interface HallState { alerts: Alert[] /** Latest detection per device, including allowed ones. */ detections: Record + /** ble counts readings, the rest count messages. */ counts: { ble: number; spectrum: number; status: number; detection: number } rejected: { count: number; reasons: RejectReason[] } /** Receive time of each recent message, oldest first. */ diff --git a/dashboard/src/pages/unit.tsx b/dashboard/src/pages/unit.tsx index a4c0dae..f99561c 100644 --- a/dashboard/src/pages/unit.tsx +++ b/dashboard/src/pages/unit.tsx @@ -133,7 +133,7 @@ export function UnitPage() {
{( [ - ["BLE", hall.counts.ble], + ["BLE readings", hall.counts.ble], ["Spectrum", hall.counts.spectrum], ["Status", hall.counts.status], ["Rejected", hall.rejected.count], diff --git a/docs/contract.md b/docs/contract.md index 615705f..959ef53 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -4,7 +4,10 @@ Node IDs: `N1` (one sensor unit). Timestamps: milliseconds since epoch (the unit ``` invigil/node/{node_id}/ble -{ "ts": 1727340000123, "node": "N1", "addr": "a91f03c2d4e8", "rssi": -58, "mfr": "0x004C" } +{ "ts": 1727340001000, "node": "N1", "readings": [ + { "ts": 1727340000123, "addr": "a91f03c2d4e8", "rssi": -58, "mfr": "0x004C" }, + { "ts": 1727340000410, "addr": "0f5e2b7a91c4", "rssi": -81, "mfr": null } +] } invigil/node/{node_id}/spectrum { "ts": 1727340000123, "node": "N1", "sweeps": 50, "hits": [126 integers, one per channel] } @@ -13,10 +16,41 @@ invigil/node/{node_id}/status { "ts": 1727340000123, "node": "N1", "uptime_s": 3600, "wifi_rssi": -61, "fw": "0.1.0" } ``` -`mfr` is the Bluetooth SIG company ID as `"0x"` plus 4 uppercase hex digits, or `null` when the advertisement carries no manufacturer data. +## BLE readings + +The unit does not send one message per advertisement. After each scan window it sends the readings from that window together, in one or more `ble` messages. + +| Field | Meaning | +| --- | --- | +| `ts` | End of the scan window the message was sent after, ms since epoch. | +| `node` | The unit. Must match the topic. | +| `readings` | One or more readings, oldest first. Each one is a single advertisement. | + +Each reading: + +| Field | Meaning | +| --- | --- | +| `ts` | When the advertisement was heard, ms since epoch. | +| `addr` | The hashed address: 12 lowercase hex chars ([hashing](hashing.md)). | +| `rssi` | Signal strength in dBm, an integer from -127 to 0. | +| `mfr` | The Bluetooth SIG company ID as `"0x"` plus 4 uppercase hex digits, or `null` when the advertisement carries no manufacturer data. | + +A reading that did not fit in the send window is sent after the next scan window, so its `ts` can be older than that window. + +**Size limit.** The unit keeps every `ble` payload at or under **1400 bytes**, and starts another message when the next reading would go over. A reading is at most 69 bytes, so a message carries at least 19 readings, usually about 20. Why 1400: + +- **lwIP.** The unit's MQTT client only accepts a publish when the whole packet fits in its output buffer at once (`MQTT_OUTPUT_RINGBUF_SIZE`, 8 KB in `firmware/src/lwipopts.h`). 1400 bytes leaves room for the spectrum message and several `ble` messages queued together. +- **One TCP segment.** A TCP segment carries at most 1460 bytes (`TCP_MSS`). 1400 bytes of payload plus the MQTT header and topic (at most 38 bytes, even with a 16-char node ID) fits in one segment, so each message leaves the unit as a single Wi-Fi frame, and a lost frame resends one message, not part of two. +- **Broker and dashboard.** Mosquitto has no message size limit by default (MQTT allows up to 256 MB), and paho and the browser client have none either, so 1400 bytes is far inside every limit on the laptop. + +The logger still writes one row per reading to `ble.csv`, with the same columns as before (`rx_ts, ts, node, addr, rssi, mfr`). + +## Spectrum `ts` in a spectrum message is the end of the scan window its sweeps came from. +## Rules + The unit must not scan the 2.4 GHz band while it is transmitting over Wi-Fi. Scan windows and send windows alternate, and readings taken during a send window are dropped. The topic keeps the `{node_id}` level so more units can be added in Phase 2 without changing the format. diff --git a/docs/firmware.md b/docs/firmware.md index ea44782..574ed91 100644 --- a/docs/firmware.md +++ b/docs/firmware.md @@ -2,7 +2,7 @@ The firmware for sensor unit N1: a Raspberry Pi Pico 2 W (RP2350 + CYW43439) with an nRF24L01+PA+LNA on SPI0. -**Status: version 0.1.0 runs on the real unit N1.** On the first hardware run (2026-10-26) every self-check passed, the unit published BLE, spectrum and status messages, and the logger rejected none of them ([first boot report](results/2026-10-26-first-boot/report.md)). The BTstack byte order is checked and correct ([byte-order report](results/2026-10-26-byte-order/report.md)). The timing values are still starting guesses, and the [To measure](#to-measure) section lists what is left to check on the board. +**Status: version 0.2.0 runs on the real unit N1.** On the first hardware run (2026-10-26, version 0.1.0) every self-check passed, the unit published BLE, spectrum and status messages, and the logger rejected none of them ([first boot report](results/2026-10-26-first-boot/report.md)). The BTstack byte order is checked and correct ([byte-order report](results/2026-10-26-byte-order/report.md)). The timing values are still starting guesses, and the [To measure](#to-measure) section lists what is left to check on the board. - Toolchain: the official Pico SDK **2.3.1** in C with CMake, Arm GNU Toolchain **15.2.Rel1**, picotool **2.3.1**, built with the Raspberry Pi Pico VS Code extension. No Arduino, no Arduino-Pico core, no PlatformIO, no ESP code. - Board: `pico2_w`. @@ -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** (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. +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, packed into as few `ble` messages as fit 1400 bytes each (about 20 readings to a message, see the [contract](contract.md#ble-readings)), 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. @@ -162,6 +162,7 @@ Every 10 s the unit prints one line of `key=value` pairs. These are the numbers | `sweep_us`, `sweep_us_max` | Average and longest time for one 126-channel sweep, in microseconds | | `ble_captured` | Advertisements added to the buffer | | `ble_published` | BLE readings handed to MQTT | +| `ble_msgs` | `ble` messages those readings went out in | | `ble_dropped` | Oldest readings dropped because the 1024-reading buffer was full | | `ble_buffered` | Readings still waiting | | `spectrum_sent`, `spectrum_dropped` | Spectrum messages sent, and lost because the send window ran out | @@ -210,7 +211,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)). 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). +**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)). Firmware 0.2.0 sends the BLE readings in batches of up to 1400 bytes: in the same room the unit scanned 85 % of the time, the median longest send window was 170 ms, and BLE latency p95 was 1.0 s, with 1.2 % of readings over 2 s ([report](results/2026-10-27-ble-batches/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-ble-batches/report.md b/docs/results/2026-10-27-ble-batches/report.md new file mode 100644 index 0000000..3bf21bc --- /dev/null +++ b/docs/results/2026-10-27-ble-batches/report.md @@ -0,0 +1,67 @@ +# BLE readings in batches: 2026-10-27 + +Firmware 0.2.0 changes how BLE readings are sent. In 0.1.1 every advertisement was its own MQTT message. Now the readings from each scan window go out together in `ble` messages of up to 1400 bytes each, about 17 readings per message ([contract](../../contract.md#ble-readings)). Everything else matches the [send-window-500 run](../2026-10-27-send-window-500/report.md): the 500 ms send window, the rule that the unit waits for the drain before it scans again, and the same room. + +Ten minutes in the same crowded room (109 devices heard, about 71 BLE readings a second). **The unit scanned 85 % of the time instead of 53 %, BLE latency p95 fell from 4.6 s to 1.0 s, and readings over 2 s fell from 13.4 % to 1.2 %.** Every send window drained before the next scan, and one frame landed in a scan window, at the same 5-minute rhythm as before. Design requirement 4 (2 s) now holds for 98.8 % of readings at this load, not all of them: long send windows still happen in 12 of 60 summaries. + +No raw data or addresses are in this report. The session stays in `data/raw/` on the laptop. `summary.txt` has the unit's 60 summary lines, which hold counts only. + +## Setup + +| Part | Setting | +| --- | --- | +| Unit | N1, firmware 0.2.0. The nRF24L01 still fails its boot self-check (wiring), so this run has BLE and status only, no spectrum, like the 0.1.1 run | +| Network | Router 2.4 GHz fixed on channel 6 | +| Laptop | `python -m invigil start --session batch-10min` | +| Devices nearby | Not controlled, the same crowded room: 109 distinct hashed addresses in 10 minutes (116 in the 0.1.1 run) | +| Window | 600 s, 09:23:52 to 09:33:52, starting about 110 s after the unit booted | + +A first attempt at 09:14 stopped after about 350 s, when the unit's USB connection dropped and it rebooted. It is not used here. Its numbers looked the same as this run's. + +## Clock + +From the session's `clock.json`: the laptop was 167.8 ms behind NTP at the start and 143.5 ms behind at the stop. Latency below is corrected by the mean, -155.7 ms, and is good to about ±100 ms. + +## Results + +| | This run (0.2.0, batches) | [0.1.1](../2026-10-27-send-window-500/report.md) (one message per reading) | +| --- | --- | --- | +| BLE readings a second | **71.1** published | 66.6 published | +| BLE messages a second | **4.2** (2,499 in 600 s) | about 67 | +| Readings per BLE message | 17.1 on average | 1 | +| `mqtt_busy` (waits for the MQTT output buffer) | **0** | 55,641 in 600 s (59 of 60 summaries) | +| `tx_in_scan` | 1 in 600 s | 3 in 600 s | +| Send windows over the limit | **13 in 600 s** (12 of 60 summaries) | 75 in 600 s (45 of 60 summaries) | +| Longest send window per 10 s | **median 170 ms**, worst 2,739 ms | median 2,138 ms, worst 5,000 ms | +| Scan windows per 10 s | **8.5** on average, 4 to 10 | 5.3 on average, 0 to 9 | +| Time spent scanning | **85 %** | 53 % | +| BLE latency p50 / p95 / p99 / max | 590 / **1,025** / 2,108 / 3,473 ms | 747 / 4,604 ms / not reported / 18,081 ms | +| BLE readings over 2 s | **1.16 %** | 13.4 % | +| Status latency p50 / p95 | 69 / 169 ms | 108 / 5,495 ms | +| `ble_dropped` | 0 | 0 | +| Rejected by the logger | 0 | 0 | + +Wi-Fi stayed up and MQTT stayed connected in every summary line. The logger wrote 42,654 rows to `ble.csv`, one per reading, with the same columns as before. + +### The long send windows + +48 of the 60 summaries had a longest send window under 400 ms. The other 12 had one between 1.3 and 2.7 s, and they do not follow the load: the slowest one (2,590 ms at t=354 s) came in a 10 s stretch with only 316 readings, well under the median of 742. `mqtt_busy` stayed 0, so the unit was never waiting for room in its own buffer. It was waiting for the broker's acknowledgement. + +The likely cause is a lost Wi-Fi frame. With only a few messages per send window, TCP has no later segments to trigger a fast resend, so lwIP waits for its retransmission timer, which is around a second or more. This was not confirmed with a packet capture. + +### The frame in a scan window + +`tx_in_scan` was 1 once, at t=294 s of uptime, in a stretch with no overrun. The 0.1.1 run saw the same at t=291, 303 and 582 s. The rhythm points again to the router or the laptop checking the unit's address (ARP), not to MQTT. + +## What this means + +- Batching removes the per-message cost that made the send windows long in a crowded room. The unit now sends about 4 messages a second instead of 67, and it is back to scanning most of the time. +- At about 70 BLE readings a second, design requirement 4 (unit to dashboard within 2 s) holds for 98.8 % of readings. The rest come from the occasional slow acknowledgement, not from the amount of data. +- The hall during an exam should be quieter 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` and the cost of the spectrum message. +2. **Look at the slow acknowledgements**, for example with a packet capture on the laptop during a run, to confirm whether they are TCP retransmissions. If they are, a shorter lwIP retransmission timeout is the thing to test. +3. **Find the 5-minute sender**, for example with a static ARP entry for the unit on the laptop. +4. Repeat in the hall. diff --git a/docs/results/2026-10-27-ble-batches/summary.txt b/docs/results/2026-10-27-ble-batches/summary.txt new file mode 100644 index 0000000..d262d87 --- /dev/null +++ b/docs/results/2026-10-27-ble-batches/summary.txt @@ -0,0 +1,60 @@ +summary t=94s windows=9 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=859 ble_published=859 ble_msgs=50 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=1 send_ms_max=305 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=104s windows=9 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=758 ble_published=758 ble_msgs=42 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=1 send_ms_max=159 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=114s windows=7 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=694 ble_published=694 ble_msgs=39 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=1 send_ms_max=1848 mqtt_busy=0 send_overruns=1 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=127s windows=9 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=993 ble_published=993 ble_msgs=56 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=1 send_ms_max=2623 mqtt_busy=0 send_overruns=1 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=135s windows=7 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=762 ble_published=762 ble_msgs=44 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=1 send_ms_max=205 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=144s windows=6 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=495 ble_published=495 ble_msgs=29 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=0 send_ms_max=2003 mqtt_busy=0 send_overruns=1 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=154s windows=9 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=717 ble_published=717 ble_msgs=42 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=2 send_ms_max=139 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=166s windows=9 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=784 ble_published=784 ble_msgs=46 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=0 send_ms_max=2063 mqtt_busy=0 send_overruns=1 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=174s windows=7 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=575 ble_published=575 ble_msgs=35 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=1 send_ms_max=180 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=184s windows=9 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=771 ble_published=771 ble_msgs=45 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=1 send_ms_max=110 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=195s windows=10 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=756 ble_published=756 ble_msgs=46 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=2 send_ms_max=144 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=205s windows=9 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=758 ble_published=758 ble_msgs=45 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=1 send_ms_max=93 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=214s windows=8 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=661 ble_published=661 ble_msgs=39 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=0 send_ms_max=133 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=224s windows=9 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=704 ble_published=704 ble_msgs=43 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=2 send_ms_max=153 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=234s windows=9 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=693 ble_published=693 ble_msgs=39 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=1 send_ms_max=177 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=244s windows=9 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=726 ble_published=726 ble_msgs=44 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=1 send_ms_max=177 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=254s windows=6 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=523 ble_published=523 ble_msgs=30 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=1 send_ms_max=2739 mqtt_busy=0 send_overruns=1 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=264s windows=9 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=772 ble_published=772 ble_msgs=44 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=1 send_ms_max=99 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=274s windows=9 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=792 ble_published=792 ble_msgs=46 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=1 send_ms_max=105 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=284s windows=9 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=811 ble_published=811 ble_msgs=47 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=1 send_ms_max=109 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=294s windows=9 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=762 ble_published=762 ble_msgs=45 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=1 send_ms_max=171 mqtt_busy=0 send_overruns=0 tx_in_scan=1 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=304s windows=9 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=762 ble_published=762 ble_msgs=44 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=1 send_ms_max=115 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=314s windows=9 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=774 ble_published=774 ble_msgs=45 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=1 send_ms_max=120 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=324s windows=9 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=756 ble_published=756 ble_msgs=43 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=1 send_ms_max=115 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=334s windows=9 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=757 ble_published=757 ble_msgs=44 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=1 send_ms_max=105 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=344s windows=9 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=683 ble_published=683 ble_msgs=40 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=1 send_ms_max=236 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=354s windows=4 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=316 ble_published=316 ble_msgs=19 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=1 send_ms_max=2590 mqtt_busy=0 send_overruns=2 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=364s windows=9 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=903 ble_published=903 ble_msgs=52 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=1 send_ms_max=115 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=374s windows=9 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=745 ble_published=745 ble_msgs=42 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=1 send_ms_max=228 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=384s windows=7 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=572 ble_published=572 ble_msgs=35 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=0 send_ms_max=1500 mqtt_busy=0 send_overruns=1 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=394s windows=9 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=668 ble_published=668 ble_msgs=38 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=2 send_ms_max=128 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=404s windows=7 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=546 ble_published=546 ble_msgs=32 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=1 send_ms_max=1802 mqtt_busy=0 send_overruns=1 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=414s windows=9 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=840 ble_published=840 ble_msgs=48 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=1 send_ms_max=131 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=424s windows=9 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=731 ble_published=731 ble_msgs=41 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=1 send_ms_max=100 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=434s windows=9 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=740 ble_published=740 ble_msgs=42 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=1 send_ms_max=115 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=444s windows=9 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=755 ble_published=755 ble_msgs=45 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=1 send_ms_max=189 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=454s windows=9 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=755 ble_published=755 ble_msgs=43 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=1 send_ms_max=164 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=464s windows=8 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=672 ble_published=672 ble_msgs=39 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=0 send_ms_max=210 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=474s windows=9 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=764 ble_published=764 ble_msgs=45 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=2 send_ms_max=183 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=484s windows=9 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=834 ble_published=834 ble_msgs=49 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=1 send_ms_max=197 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=494s windows=7 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=554 ble_published=554 ble_msgs=32 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=1 send_ms_max=1786 mqtt_busy=0 send_overruns=1 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=505s windows=8 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=644 ble_published=644 ble_msgs=37 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=0 send_ms_max=1520 mqtt_busy=0 send_overruns=1 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=514s windows=8 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=640 ble_published=640 ble_msgs=38 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=1 send_ms_max=168 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=524s windows=9 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=773 ble_published=773 ble_msgs=44 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=2 send_ms_max=265 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=534s windows=9 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=816 ble_published=816 ble_msgs=48 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=1 send_ms_max=156 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=544s windows=7 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=567 ble_published=567 ble_msgs=33 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=1 send_ms_max=1833 mqtt_busy=0 send_overruns=1 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=554s windows=9 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=745 ble_published=745 ble_msgs=44 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=1 send_ms_max=167 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=564s windows=9 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=799 ble_published=799 ble_msgs=47 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=1 send_ms_max=160 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=574s windows=9 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=715 ble_published=715 ble_msgs=42 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=1 send_ms_max=122 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=584s windows=7 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=494 ble_published=494 ble_msgs=31 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=0 send_ms_max=1322 mqtt_busy=0 send_overruns=1 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=594s windows=9 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=737 ble_published=737 ble_msgs=43 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=2 send_ms_max=203 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=604s windows=8 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=645 ble_published=645 ble_msgs=37 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=0 send_ms_max=230 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=614s windows=9 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=622 ble_published=622 ble_msgs=37 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=2 send_ms_max=176 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=624s windows=9 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=723 ble_published=723 ble_msgs=43 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=1 send_ms_max=233 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=634s windows=8 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=650 ble_published=650 ble_msgs=40 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=0 send_ms_max=140 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=645s windows=10 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=768 ble_published=768 ble_msgs=44 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=2 send_ms_max=111 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=654s windows=9 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=700 ble_published=700 ble_msgs=42 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=1 send_ms_max=89 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=664s windows=9 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=765 ble_published=765 ble_msgs=46 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=1 send_ms_max=88 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=674s windows=9 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=817 ble_published=817 ble_msgs=47 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=1 send_ms_max=81 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf +summary t=684s windows=9 sweeps_per_window=0 sweep_us=0 sweep_us_max=0 ble_captured=725 ble_published=725 ble_msgs=42 ble_dropped=0 ble_buffered=0 spectrum_sent=0 spectrum_dropped=0 status_sent=1 send_ms_max=371 mqtt_busy=0 send_overruns=0 tx_in_scan=0 sweeps_discarded=0 wifi=up mqtt=connected SELF-CHECK FAILED: nrf diff --git a/docs/setup.md b/docs/setup.md index 736c642..be0c2c3 100644 --- a/docs/setup.md +++ b/docs/setup.md @@ -119,7 +119,7 @@ Logger data/raw/2026-10-26-live-193000 (PID 4188) Dashboard http://127.0.0.1:8080/?source=live&... (PID 4236) Unit N1 online Last status uptime 22m 11s, Wi-Fi RSSI -46 dBm, fw 0.1.0, 1 s ago -Messages ble 35.2/s, spectrum 0.9/s, status 0.1/s, rejected 0 +Readings ble 35.2/s, spectrum 0.9/s, status 0.1/s, rejected messages 0 Laptop clock 12 ms behind pool.ntp.org ``` @@ -152,7 +152,7 @@ Each session folder holds three CSV files, one per message type: | `status.csv` | `rx_ts, ts, node, uptime_s, wifi_rssi, fw` | - `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`. +- Fake runs show `fw` as `0.2.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. diff --git a/firmware/CMakeLists.txt b/firmware/CMakeLists.txt index 31873cb..7ad26d6 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.1 LANGUAGES C CXX ASM) +project(invigil_fw VERSION 0.2.0 LANGUAGES C CXX ASM) pico_sdk_init() diff --git a/firmware/portable/ble_ring.c b/firmware/portable/ble_ring.c index 0d48024..a7aa0da 100644 --- a/firmware/portable/ble_ring.c +++ b/firmware/portable/ble_ring.c @@ -23,10 +23,14 @@ void ble_ring_push(ble_ring_t *ring, const ble_reading_t *reading) { } bool ble_ring_peek(const ble_ring_t *ring, ble_reading_t *out) { - if (ring->count == 0) { + return ble_ring_peek_at(ring, 0, out); +} + +bool ble_ring_peek_at(const ble_ring_t *ring, uint32_t i, ble_reading_t *out) { + if (i >= ring->count) { return false; } - *out = ring->items[ring->head]; + *out = ring->items[(ring->head + i) % ring->capacity]; return true; } diff --git a/firmware/portable/ble_ring.h b/firmware/portable/ble_ring.h index 90c316a..eb51e57 100644 --- a/firmware/portable/ble_ring.h +++ b/firmware/portable/ble_ring.h @@ -31,6 +31,8 @@ typedef struct { void ble_ring_init(ble_ring_t *ring, ble_reading_t *storage, uint32_t capacity); void ble_ring_push(ble_ring_t *ring, const ble_reading_t *reading); bool ble_ring_peek(const ble_ring_t *ring, ble_reading_t *out); // copies the oldest +// Copies the reading i places after the oldest (0 is the oldest). False past the end. +bool ble_ring_peek_at(const ble_ring_t *ring, uint32_t i, ble_reading_t *out); void ble_ring_pop(ble_ring_t *ring); // removes the oldest #endif diff --git a/firmware/portable/payload.c b/firmware/portable/payload.c index 5405cb4..23963a6 100644 --- a/firmware/portable/payload.c +++ b/firmware/portable/payload.c @@ -136,31 +136,82 @@ size_t payload_topic(char *buf, size_t cap, const char *node, const char *kind) return finish(&w); } -size_t payload_ble(char *buf, size_t cap, uint64_t ts_ms, const char *node, const char *addr, - int rssi, bool has_mfr, uint16_t mfr) { - // The address must already be a hash. A raw address in any printed form - // fails this check, so it can never be published by mistake. - if (!addr_hash_is_valid(addr, strlen(addr)) || !rssi_in_range(rssi)) { - return fail(buf, cap); +// The longest reading: {"ts":9999999999999,"addr":"...","rssi":-127,"mfr":"0xFFFF"} +// is 69 bytes. Room to spare. +#define READING_MAX_LEN 96 +static const char BATCH_TAIL[] = "]}"; + +bool ble_batch_begin(ble_batch_t *b, char *buf, size_t cap, uint64_t ts_ms, const char *node) { + b->buf = buf; + b->limit = cap > 0 ? cap - 1 : 0; + if (b->limit > CONTRACT_MAX_BLE_PAYLOAD) { + b->limit = CONTRACT_MAX_BLE_PAYLOAD; } + b->len = 0; + b->count = 0; writer_t w = writer(buf, cap); if (!put_head(&w, ts_ms, node)) { - return fail(buf, cap); + fail(buf, cap); + return false; } + put_raw(&w, ",\"readings\":["); + if (!w.ok || w.len + strlen(BATCH_TAIL) > b->limit) { + fail(buf, cap); + return false; + } + b->len = w.len; + return true; +} + +ble_batch_result_t ble_batch_add(ble_batch_t *b, const ble_reading_t *r) { + // The address must already be a hash. A raw address in any printed form + // fails this check, so it can never be published by mistake. + if (r->ts_ms < CONTRACT_MIN_TS_MS || r->ts_ms > CONTRACT_MAX_TS_MS || + !addr_hash_is_valid(r->addr, strlen(r->addr)) || !rssi_in_range(r->rssi)) { + return BLE_BATCH_INVALID; + } + char tmp[READING_MAX_LEN]; + writer_t w = writer(tmp, sizeof(tmp)); + put_raw(&w, "{\"ts\":"); + put_u64(&w, r->ts_ms); put_raw(&w, ",\"addr\":"); - put_string(&w, addr); + put_string(&w, r->addr); put_raw(&w, ",\"rssi\":"); - put_int(&w, rssi); + put_int(&w, r->rssi); put_raw(&w, ",\"mfr\":"); - if (has_mfr) { + if (r->has_mfr) { char id[7]; - adv_format_company_id(mfr, id); + adv_format_company_id(r->mfr, id); put_string(&w, id); } else { put_raw(&w, "null"); } put_char(&w, '}'); - return finish(&w); + if (!w.ok) { + return BLE_BATCH_INVALID; + } + + size_t comma = b->count > 0 ? 1 : 0; + if (b->len + comma + w.len + strlen(BATCH_TAIL) > b->limit) { + // In an empty message it can never fit, so do not ask for another. + return b->count > 0 ? BLE_BATCH_FULL : BLE_BATCH_INVALID; + } + if (comma) { + b->buf[b->len++] = ','; + } + memcpy(b->buf + b->len, tmp, w.len); + b->len += w.len; + b->count++; + return BLE_BATCH_ADDED; +} + +size_t ble_batch_finish(ble_batch_t *b) { + if (b->count == 0) { + b->buf[0] = '\0'; + return 0; + } + memcpy(b->buf + b->len, BATCH_TAIL, sizeof(BATCH_TAIL)); // with the NUL + return b->len + strlen(BATCH_TAIL); } size_t payload_spectrum(char *buf, size_t cap, uint64_t ts_ms, const char *node, diff --git a/firmware/portable/payload.h b/firmware/portable/payload.h index ddac0e0..19419b2 100644 --- a/firmware/portable/payload.h +++ b/firmware/portable/payload.h @@ -13,6 +13,7 @@ #include #include +#include "ble_ring.h" #include "spectrum.h" // Limits from server/contract.py. @@ -23,9 +24,15 @@ #define CONTRACT_MAX_UPTIME_S 2147483647UL #define CONTRACT_MAX_FW_LEN 32 +// The longest ble payload the unit sends, MAX_BLE_PAYLOAD_BYTES in +// server/contract.py. With the MQTT header and topic it fits one TCP segment +// (TCP_MSS 1460), and lwIP's MQTT output buffer holds several at once +// (docs/contract.md, Size limit). +#define CONTRACT_MAX_BLE_PAYLOAD 1400 + // Buffer sizes that fit the largest valid message of each kind. #define TOPIC_MAX_LEN 64 -#define PAYLOAD_BLE_MAX_LEN 128 +#define PAYLOAD_BLE_MAX_LEN (CONTRACT_MAX_BLE_PAYLOAD + 1) // plus the NUL #define PAYLOAD_STATUS_MAX_LEN 160 #define PAYLOAD_SPECTRUM_MAX_LEN 1024 // 126 counts of up to 5 digits plus commas @@ -35,10 +42,33 @@ bool payload_node_is_valid(const char *node); // "invigil/node/{node}/{kind}" with kind "ble", "spectrum" or "status". size_t payload_topic(char *buf, size_t cap, const char *node, const char *kind); -// {"ts":...,"node":"N1","addr":"a91f03c2d4e8","rssi":-58,"mfr":"0x004C"} -// addr must be a 12-char lowercase hex hash. mfr is null when has_mfr is false. -size_t payload_ble(char *buf, size_t cap, uint64_t ts_ms, const char *node, const char *addr, - int rssi, bool has_mfr, uint16_t mfr); +// One ble message, built one reading at a time: +// {"ts":...,"node":"N1","readings":[{"ts":...,"addr":"a91f03c2d4e8","rssi":-58,"mfr":"0x004C"},...]} +// ts is the end of the scan window. Each reading keeps its own ts. A reading's +// addr must be a 12-char lowercase hex hash, and mfr is null when has_mfr is +// false. The finished message is at most min(cap - 1, CONTRACT_MAX_BLE_PAYLOAD) +// bytes. +typedef struct { + char *buf; + size_t limit; // longest message allowed, not counting the NUL + size_t len; // bytes written so far, without the closing "]}" + uint32_t count; // readings in the message +} ble_batch_t; + +typedef enum { + BLE_BATCH_ADDED, // the reading is in the message + BLE_BATCH_FULL, // it does not fit: send this message, then start another + BLE_BATCH_INVALID, // off contract, or too big even for an empty message: never sendable +} ble_batch_result_t; + +// Starts a message. False if ts or node is off contract or the buffer is too +// small for an empty message; the batch must not be used then. +bool ble_batch_begin(ble_batch_t *b, char *buf, size_t cap, uint64_t ts_ms, const char *node); +// Adds one reading. A reading that is FULL or INVALID leaves the message unchanged. +ble_batch_result_t ble_batch_add(ble_batch_t *b, const ble_reading_t *r); +// Closes the message and returns its length, or 0 (and an empty string) if +// it has no readings. +size_t ble_batch_finish(ble_batch_t *b); // {"ts":...,"node":"N1","sweeps":50,"hits":[126 integers]} size_t payload_spectrum(char *buf, size_t cap, uint64_t ts_ms, const char *node, diff --git a/firmware/src/ble_scan.c b/firmware/src/ble_scan.c index c3c35de..ddedab1 100644 --- a/firmware/src/ble_scan.c +++ b/firmware/src/ble_scan.c @@ -203,8 +203,8 @@ void ble_scan_stop(void) { async_context_release_lock(context); } -bool ble_scan_peek_locked(ble_reading_t *out) { - return ble_ring_peek(&ring, out); +bool ble_scan_peek_at_locked(uint32_t i, ble_reading_t *out) { + return ble_ring_peek_at(&ring, i, out); } void ble_scan_pop_locked(void) { diff --git a/firmware/src/ble_scan.h b/firmware/src/ble_scan.h index e449f24..d5fbf4d 100644 --- a/firmware/src/ble_scan.h +++ b/firmware/src/ble_scan.h @@ -28,7 +28,8 @@ void ble_scan_stop(void); // Buffer access for the send window. Call with the async context lock held // (cyw43_arch_lwip_begin), since the BTstack callback adds readings. -bool ble_scan_peek_locked(ble_reading_t *out); +// i counts from the oldest reading (0). Pop removes the oldest. +bool ble_scan_peek_at_locked(uint32_t i, ble_reading_t *out); void ble_scan_pop_locked(void); // Counts since the last call, plus the number buffered now. diff --git a/firmware/src/lwipopts.h b/firmware/src/lwipopts.h index 8827392..a548bb4 100644 --- a/firmware/src/lwipopts.h +++ b/firmware/src/lwipopts.h @@ -64,10 +64,12 @@ // --------------------------------------------------------------------------- // MQTT (lwIP MQTT app) // --------------------------------------------------------------------------- -// The default output buffer (256 bytes) cannot hold one spectrum message -// (up to about 850 bytes with topic and header). 4 KB holds a spectrum -// message and a few dozen BLE readings. -#define MQTT_OUTPUT_RINGBUF_SIZE 4096 +// lwIP's MQTT client only takes a publish when the whole packet fits in this +// buffer at once. The default (256 bytes) cannot hold one spectrum message +// (up to about 850 bytes with topic and header). 8 KB holds a spectrum +// message, five full ble messages (1400 bytes each, docs/contract.md) and a +// status message, so a send window rarely waits on it. +#define MQTT_OUTPUT_RINGBUF_SIZE 8192 // A QoS 0 publish holds a request slot until TCP acknowledges it. Enough // slots that the output buffer, not the slots, is the limit. #define MQTT_REQ_MAX_IN_FLIGHT 64 diff --git a/firmware/src/main.c b/firmware/src/main.c index ef758ab..1aaec24 100644 --- a/firmware/src/main.c +++ b/firmware/src/main.c @@ -3,7 +3,8 @@ // The unit repeats one cycle (docs/contract.md): // 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. +// spectrum message, then buffered BLE readings packed into as few ble +// messages as fit (docs/contract.md), 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. @@ -36,7 +37,8 @@ static bool node_ok; static char topic_ble[TOPIC_MAX_LEN]; static char topic_spectrum[TOPIC_MAX_LEN]; static char topic_status[TOPIC_MAX_LEN]; -static char payload[PAYLOAD_SPECTRUM_MAX_LEN]; +// Fits the largest message of any kind. +static char payload[PAYLOAD_BLE_MAX_LEN > PAYLOAD_SPECTRUM_MAX_LEN ? PAYLOAD_BLE_MAX_LEN : PAYLOAD_SPECTRUM_MAX_LEN]; static bool led_on; static absolute_time_t next_status; @@ -51,7 +53,8 @@ static struct { uint32_t sweep_us_max; uint32_t sweeps_timed; uint32_t tx_in_scan; // frames lwIP handed to the radio during scan windows - uint32_t ble_published; + uint32_t ble_published; // readings + uint32_t ble_messages; // ble messages they went out in uint32_t ble_invalid; // readings that failed the contract check, dropped uint32_t spectrum_sent; uint32_t spectrum_dropped; @@ -194,28 +197,49 @@ static void send_window(uint64_t scan_end_ms) { } } - // 2. Buffered BLE readings, oldest first. What does not fit waits for - // the next send window. Peek, publish and pop happen under one lock, - // so a reading leaves the buffer only once lwIP has taken it. + // 2. Buffered BLE readings, oldest first, as many to a message as fit. + // What does not fit waits for the next send window. Each message is + // built, published and its readings popped under one lock, so a + // reading leaves the buffer only once lwIP has taken it. A message + // lwIP is too busy for is built again on the next try. while (!time_reached(stop_queueing)) { tick(); - ble_reading_t r; mqtt_pub_result_t result = MQTT_PUB_OK; + uint32_t taken = 0; // readings looked at: in the message, or invalid + uint32_t invalid = 0; cyw43_arch_lwip_begin(); - bool have = ble_scan_peek_locked(&r); - if (have) { - size_t n = payload_ble(payload, sizeof(payload), r.ts_ms, NODE_ID, r.addr, r.rssi, r.has_mfr, r.mfr); - result = n > 0 ? mqtt_link_publish(topic_ble, payload, n) : MQTT_PUB_ERROR; + ble_batch_t batch; + if (ble_batch_begin(&batch, payload, sizeof(payload), scan_end_ms, NODE_ID)) { + ble_reading_t r; + while (ble_scan_peek_at_locked(taken, &r)) { + ble_batch_result_t added = ble_batch_add(&batch, &r); + if (added == BLE_BATCH_FULL) { + break; + } + if (added == BLE_BATCH_INVALID) { + invalid++; // can never be sent; do not block the rest + } + taken++; + } + size_t n = ble_batch_finish(&batch); + if (n > 0) { + result = mqtt_link_publish(topic_ble, payload, n); + } if (result == MQTT_PUB_OK) { - ble_scan_pop_locked(); - stats.ble_published++; + stats.ble_published += batch.count; + stats.ble_messages += n > 0; } else if (result == MQTT_PUB_ERROR) { - ble_scan_pop_locked(); // can never be sent; do not block the rest - stats.ble_invalid++; + invalid += batch.count; // lwIP refused it for good; do not block the rest + } + if (result == MQTT_PUB_OK || result == MQTT_PUB_ERROR) { + for (uint32_t i = 0; i < taken; i++) { + ble_scan_pop_locked(); + } + stats.ble_invalid += invalid; } } cyw43_arch_lwip_end(); - if (!have || result == MQTT_PUB_DOWN) { + if (taken == 0 || result == MQTT_PUB_DOWN) { break; } if (result == MQTT_PUB_BUSY) { @@ -272,12 +296,12 @@ static void print_summary(void) { uint32_t sweep_us = stats.sweeps_timed ? (uint32_t)(stats.sweep_us_total / stats.sweeps_timed) : 0; printf("summary t=%" PRIu32 "s windows=%" PRIu32 " sweeps_per_window=%" PRIu32 " sweep_us=%" PRIu32 - " sweep_us_max=%" PRIu32 " ble_captured=%" PRIu32 " ble_published=%" PRIu32 " ble_dropped=%" PRIu32 + " sweep_us_max=%" PRIu32 " ble_captured=%" PRIu32 " ble_published=%" PRIu32 " ble_msgs=%" PRIu32 " ble_dropped=%" PRIu32 " ble_buffered=%" PRIu32 " spectrum_sent=%" PRIu32 " spectrum_dropped=%" PRIu32 " status_sent=%" PRIu32 " send_ms_max=%" PRIu32 " mqtt_busy=%" PRIu32 " send_overruns=%" PRIu32 " tx_in_scan=%" PRIu32 " sweeps_discarded=%" PRIu32 " wifi=%s mqtt=%s", (uint32_t)(time_us_64() / 1000000), stats.windows, per_window, sweep_us, stats.sweep_us_max, - ble.captured, stats.ble_published, ble.dropped, ble.buffered, stats.spectrum_sent, + ble.captured, stats.ble_published, stats.ble_messages, ble.dropped, ble.buffered, stats.spectrum_sent, stats.spectrum_dropped, stats.status_sent, stats.send_ms_max, stats.mqtt_busy, stats.send_overruns, stats.tx_in_scan, stats.sweeps_discarded, wifi_sta_state_name(), mqtt_link_state_name()); if (ble.no_rssi || stats.ble_invalid) { diff --git a/firmware/tests/check_contract.py b/firmware/tests/check_contract.py index 832dd85..b2a2e61 100644 --- a/firmware/tests/check_contract.py +++ b/firmware/tests/check_contract.py @@ -43,6 +43,8 @@ def check(path: Path) -> list[str]: node, kind = contract.parse_topic(topic) payload = json.loads(raw, object_pairs_hook=no_duplicate_keys) contract.validate(kind, payload, node) + if kind == "ble" and len(raw.encode("utf-8")) > contract.MAX_BLE_PAYLOAD_BYTES: + raise ValueError(f"ble payload is over {contract.MAX_BLE_PAYLOAD_BYTES} bytes") kinds[kind] += 1 elif fields[0] == "hash" and len(fields) == 4: _, salt_hex, addr_hex, firmware_hash = fields diff --git a/firmware/tests/test_portable.c b/firmware/tests/test_portable.c index 50d96a4..1fee132 100644 --- a/firmware/tests/test_portable.c +++ b/firmware/tests/test_portable.c @@ -266,6 +266,11 @@ static void test_ring_fifo_and_drop_oldest(void) { } CHECK(ring.count == 4); CHECK(ring.dropped == 2); + // peek_at walks from the oldest across the wrap, and stops at the end. + for (uint32_t i = 0; i < 4; i++) { + CHECK(ble_ring_peek_at(&ring, i, &out) && out.ts_ms == 4 + i); + } + CHECK(!ble_ring_peek_at(&ring, 4, &out)); for (uint64_t want = 4; want <= 7; want++) { CHECK(ble_ring_peek(&ring, &out) && out.ts_ms == want); ble_ring_pop(&ring); @@ -292,46 +297,133 @@ static void test_topics(void) { CHECK(payload_topic(t, 10, "N1", "ble") == 0); // too small } -static void test_ble_payload(void) { +static ble_reading_t ble_reading(uint64_t ts, const char *addr, int rssi, bool has_mfr, uint16_t mfr) { + ble_reading_t r; + memset(&r, 0, sizeof(r)); + r.ts_ms = ts; + strncpy(r.addr, addr, sizeof(r.addr) - 1); + r.rssi = (int8_t)rssi; + r.has_mfr = has_mfr; + r.mfr = mfr; + return r; +} + +static void test_ble_batch(void) { char p[PAYLOAD_BLE_MAX_LEN]; - size_t n = payload_ble(p, sizeof(p), TS, "N1", "a91f03c2d4e8", -58, true, 0x004C); - CHECK_STR(p, "{\"ts\":1727340000123,\"node\":\"N1\",\"addr\":\"a91f03c2d4e8\",\"rssi\":-58,\"mfr\":\"0x004C\"}"); + ble_batch_t b; + CHECK(ble_batch_begin(&b, p, sizeof(p), TS + 877, "N1")); + ble_reading_t r1 = ble_reading(TS, "a91f03c2d4e8", -58, true, 0x004C); + ble_reading_t r2 = ble_reading(TS + 287, "0f5e2b7a91c4", -127, false, 0); + ble_reading_t r3 = ble_reading(TS + 300, "a91f03c2d4e8", 0, true, 0xFFFF); + CHECK(ble_batch_add(&b, &r1) == BLE_BATCH_ADDED); + CHECK(ble_batch_add(&b, &r2) == BLE_BATCH_ADDED); + CHECK(ble_batch_add(&b, &r3) == BLE_BATCH_ADDED); + CHECK(b.count == 3); + size_t n = ble_batch_finish(&b); + CHECK_STR(p, "{\"ts\":1727340001000,\"node\":\"N1\",\"readings\":[" + "{\"ts\":1727340000123,\"addr\":\"a91f03c2d4e8\",\"rssi\":-58,\"mfr\":\"0x004C\"}," + "{\"ts\":1727340000410,\"addr\":\"0f5e2b7a91c4\",\"rssi\":-127,\"mfr\":null}," + "{\"ts\":1727340000423,\"addr\":\"a91f03c2d4e8\",\"rssi\":0,\"mfr\":\"0xFFFF\"}]}"); CHECK(n == strlen(p)); - payload_ble(p, sizeof(p), TS, "N1", "a91f03c2d4e8", -127, false, 0); - CHECK_STR(p, "{\"ts\":1727340000123,\"node\":\"N1\",\"addr\":\"a91f03c2d4e8\",\"rssi\":-127,\"mfr\":null}"); + // One reading. + CHECK(ble_batch_begin(&b, p, sizeof(p), TS + 877, "N1")); + CHECK(ble_batch_add(&b, &r1) == BLE_BATCH_ADDED); + ble_batch_finish(&b); + CHECK_STR(p, "{\"ts\":1727340001000,\"node\":\"N1\",\"readings\":[" + "{\"ts\":1727340000123,\"addr\":\"a91f03c2d4e8\",\"rssi\":-58,\"mfr\":\"0x004C\"}]}"); - payload_ble(p, sizeof(p), TS, "N1", "a91f03c2d4e8", 0, true, 0xFFFF); - CHECK_STR(p, "{\"ts\":1727340000123,\"node\":\"N1\",\"addr\":\"a91f03c2d4e8\",\"rssi\":0,\"mfr\":\"0xFFFF\"}"); + // No readings: nothing to send. + CHECK(ble_batch_begin(&b, p, sizeof(p), TS, "N1")); + CHECK(ble_batch_finish(&b) == 0); + CHECK(p[0] == '\0'); } -static void test_ble_payload_rejects_off_contract(void) { +static void test_ble_batch_rejects_off_contract(void) { char p[PAYLOAD_BLE_MAX_LEN]; - // Never a raw address, in any form. - CHECK(payload_ble(p, sizeof(p), TS, "N1", "A9:1F:03:C2:D4:E8", -58, false, 0) == 0); + ble_batch_t b; + const ble_reading_t good = ble_reading(TS, "a91f03c2d4e8", -58, false, 0); + const ble_reading_t bad[] = { + // Never a raw address, in any form. + ble_reading(TS, "A9:1F:03:C2:D4:E8", -58, false, 0), + // A reading holds at most 12 address chars, so a too-long one cannot + // reach the builder. Too short, uppercase and non-hex can. + ble_reading(TS, "a91f03c2d4e", -58, false, 0), + ble_reading(TS, "A91F03C2D4E8", -58, false, 0), + ble_reading(TS, "a91f03c2d4eg", -58, false, 0), + // RSSI outside -127..0. + ble_reading(TS, "a91f03c2d4e8", 1, false, 0), + ble_reading(TS, "a91f03c2d4e8", -128, false, 0), + // Clock not synced, or seconds instead of ms, or microseconds. + ble_reading(0, "a91f03c2d4e8", -58, false, 0), + ble_reading(1727340000ULL, "a91f03c2d4e8", -58, false, 0), + ble_reading(1727340000123000ULL, "a91f03c2d4e8", -58, false, 0), + }; + CHECK(ble_batch_begin(&b, p, sizeof(p), TS, "N1")); + CHECK(ble_batch_add(&b, &good) == BLE_BATCH_ADDED); + size_t before = b.len; + for (size_t i = 0; i < sizeof(bad) / sizeof(bad[0]); i++) { + CHECK(ble_batch_add(&b, &bad[i]) == BLE_BATCH_INVALID); + } + CHECK(b.count == 1 && b.len == before); // unchanged by the bad ones + ble_batch_finish(&b); + CHECK(strstr(p, "A9:1F") == NULL); + + // The message itself: clock, node, buffer. + CHECK(!ble_batch_begin(&b, p, sizeof(p), 1727340000ULL, "N1")); CHECK(p[0] == '\0'); - CHECK(payload_ble(p, sizeof(p), TS, "N1", "a91f03c2d4e8ff", -58, false, 0) == 0); - CHECK(payload_ble(p, sizeof(p), TS, "N1", "A91F03C2D4E8", -58, false, 0) == 0); - // RSSI outside -127..0. - CHECK(payload_ble(p, sizeof(p), TS, "N1", "a91f03c2d4e8", 1, false, 0) == 0); - CHECK(payload_ble(p, sizeof(p), TS, "N1", "a91f03c2d4e8", -128, false, 0) == 0); - // Clock not synced, or seconds instead of ms, or microseconds. - CHECK(payload_ble(p, sizeof(p), 0, "N1", "a91f03c2d4e8", -58, false, 0) == 0); - CHECK(payload_ble(p, sizeof(p), 1727340000ULL, "N1", "a91f03c2d4e8", -58, false, 0) == 0); - CHECK(payload_ble(p, sizeof(p), 1727340000123000ULL, "N1", "a91f03c2d4e8", -58, false, 0) == 0); - // Bad node. - CHECK(payload_ble(p, sizeof(p), TS, "", "a91f03c2d4e8", -58, false, 0) == 0); - CHECK(payload_ble(p, sizeof(p), TS, "N1\"", "a91f03c2d4e8", -58, false, 0) == 0); -} - -static void test_payload_buffer_bounds(void) { + CHECK(!ble_batch_begin(&b, p, sizeof(p), TS, "")); + CHECK(!ble_batch_begin(&b, p, sizeof(p), TS, "N1\"")); + CHECK(!ble_batch_begin(&b, p, 20, TS, "N1")); + CHECK(!ble_batch_begin(&b, p, 0, TS, "N1")); +} + +static void test_ble_batch_size_limit(void) { + // The worst case reading, 69 bytes: 19 fit in 1400 bytes, as docs/contract.md says. char p[PAYLOAD_BLE_MAX_LEN]; - size_t n = payload_ble(p, sizeof(p), TS, "N1", "a91f03c2d4e8", -58, true, 0x004C); - CHECK(n > 0); - char exact[PAYLOAD_BLE_MAX_LEN]; - CHECK(payload_ble(exact, n, TS, "N1", "a91f03c2d4e8", -58, true, 0x004C) == 0); // no room for NUL - CHECK(payload_ble(exact, n + 1, TS, "N1", "a91f03c2d4e8", -58, true, 0x004C) == n); // just fits - CHECK(payload_ble(exact, 0, TS, "N1", "a91f03c2d4e8", -58, true, 0x004C) == 0); + ble_batch_t b; + const ble_reading_t worst = ble_reading(CONTRACT_MAX_TS_MS, "a91f03c2d4e8", -127, true, 0xFFFF); + CHECK(ble_batch_begin(&b, p, sizeof(p), CONTRACT_MAX_TS_MS, "N1")); + int added = 0; + while (ble_batch_add(&b, &worst) == BLE_BATCH_ADDED) { + added++; + } + CHECK(added == 19); + CHECK(ble_batch_add(&b, &worst) == BLE_BATCH_FULL); // still full, still unchanged + size_t n = ble_batch_finish(&b); + CHECK(n > 0 && n <= CONTRACT_MAX_BLE_PAYLOAD); + CHECK(n == strlen(p)); + CHECK(p[n - 2] == ']' && p[n - 1] == '}'); + + // A bigger buffer does not raise the limit. + static char big[4 * PAYLOAD_BLE_MAX_LEN]; + CHECK(ble_batch_begin(&b, big, sizeof(big), CONTRACT_MAX_TS_MS, "N1")); + added = 0; + while (ble_batch_add(&b, &worst) == BLE_BATCH_ADDED) { + added++; + } + CHECK(added == 19); + CHECK(ble_batch_finish(&b) <= CONTRACT_MAX_BLE_PAYLOAD); + + // A smaller buffer lowers it, and the result always fits with its NUL. + for (size_t cap = 20; cap < 400; cap++) { + char small[400]; + memset(small, 'x', sizeof(small)); + if (!ble_batch_begin(&b, small, cap, CONTRACT_MAX_TS_MS, "N1")) { + continue; + } + ble_batch_result_t first = ble_batch_add(&b, &worst); + while (ble_batch_add(&b, &worst) == BLE_BATCH_ADDED) { + } + size_t len = ble_batch_finish(&b); + CHECK(len < cap); + CHECK(small[cap] == 'x'); // nothing written past the buffer + if (first == BLE_BATCH_INVALID) { + CHECK(len == 0); // not even one reading fits: never FULL, so the caller moves on + } else { + CHECK(len == strlen(small)); + } + } } static void test_spectrum_payload(void) { @@ -630,16 +722,30 @@ static int write_samples(const char *path) { perror(path); return 1; } - char p[PAYLOAD_SPECTRUM_MAX_LEN]; + char p[PAYLOAD_BLE_MAX_LEN > PAYLOAD_SPECTRUM_MAX_LEN ? PAYLOAD_BLE_MAX_LEN : PAYLOAD_SPECTRUM_MAX_LEN]; char hash[ADDR_HASH_LEN + 1]; addr_hash("invigil-test-vector", VECTOR_ADDR, hash); - // BLE - CHECK(payload_ble(p, sizeof(p), TS, "N1", hash, -58, true, 0x004C) > 0); + // BLE: one reading, a mixed message, and a full message of worst-case readings. + ble_batch_t b; + const ble_reading_t r1 = ble_reading(TS, hash, -58, true, 0x004C); + const ble_reading_t r2 = ble_reading(TS + 300, hash, -127, false, 0); + const ble_reading_t r3 = ble_reading(CONTRACT_MAX_TS_MS, hash, 0, true, 0xFFFF); + const ble_reading_t worst = ble_reading(CONTRACT_MAX_TS_MS, hash, -127, true, 0xFFFF); + CHECK(ble_batch_begin(&b, p, sizeof(p), TS + 877, "N1")); + CHECK(ble_batch_add(&b, &r1) == BLE_BATCH_ADDED); + CHECK(ble_batch_finish(&b) > 0); write_msg(f, "ble", p); - CHECK(payload_ble(p, sizeof(p), TS, "N1", hash, -127, false, 0) > 0); + CHECK(ble_batch_begin(&b, p, sizeof(p), CONTRACT_MAX_TS_MS, "N1")); + CHECK(ble_batch_add(&b, &r1) == BLE_BATCH_ADDED); + CHECK(ble_batch_add(&b, &r2) == BLE_BATCH_ADDED); + CHECK(ble_batch_add(&b, &r3) == BLE_BATCH_ADDED); + CHECK(ble_batch_finish(&b) > 0); write_msg(f, "ble", p); - CHECK(payload_ble(p, sizeof(p), CONTRACT_MAX_TS_MS, "N1", hash, 0, true, 0xFFFF) > 0); + CHECK(ble_batch_begin(&b, p, sizeof(p), CONTRACT_MAX_TS_MS, "N1")); + while (ble_batch_add(&b, &worst) == BLE_BATCH_ADDED) { + } + CHECK(ble_batch_finish(&b) > 0); write_msg(f, "ble", p); // Spectrum @@ -714,9 +820,9 @@ int main(int argc, char **argv) { test_spectrum_caps_at_contract_max(); test_ring_fifo_and_drop_oldest(); test_topics(); - test_ble_payload(); - test_ble_payload_rejects_off_contract(); - test_payload_buffer_bounds(); + test_ble_batch(); + test_ble_batch_rejects_off_contract(); + test_ble_batch_size_limit(); test_spectrum_payload(); test_spectrum_payload_limits(); test_status_payload(); diff --git a/invigil/__main__.py b/invigil/__main__.py index b2e20e9..8902ec6 100644 --- a/invigil/__main__.py +++ b/invigil/__main__.py @@ -78,7 +78,7 @@ def render( f"fw {s['fw']}, {view.status_age_s:.0f} s ago" ) rates = ", ".join(f"{k} {fmt_rate(view.rates[k])}" for k in contract.KINDS) - lines.append(f"Messages {rates}, rejected {mon.rejected}") + lines.append(f"Readings {rates}, rejected messages {mon.rejected}") lines.append(f"Laptop clock {clock.describe()}") return "\n".join(lines) diff --git a/invigil/monitor.py b/invigil/monitor.py index 05433e0..024ca9e 100644 --- a/invigil/monitor.py +++ b/invigil/monitor.py @@ -1,4 +1,7 @@ -"""Watch the unit's MQTT traffic: online or not, last status, message rates. +"""Watch the unit's MQTT traffic: online or not, last status, reading rates. + +The ble rate counts readings (advertisements), not messages: one ble message +carries all the readings from a scan window. Every message goes through server/contract.py, the same check the logger uses, so a message the logger would reject is counted as rejected here too. @@ -51,8 +54,9 @@ def handle(self, topic: str, raw: bytes, now: float) -> bool: with self._lock: self.rejected += 1 return False + count = len(payload["readings"]) if kind == "ble" else 1 with self._lock: - self._times[(node, kind)].append(now) + self._times[(node, kind)].extend([now] * count) if kind == "status": self._status[node] = (payload, now) if kind == "status": diff --git a/invigil/tests/test_calibrate.py b/invigil/tests/test_calibrate.py index ae48c05..542b8b9 100644 --- a/invigil/tests/test_calibrate.py +++ b/invigil/tests/test_calibrate.py @@ -15,8 +15,8 @@ def ble(addr, rssi, i): - msg = {"ts": TS + i * 100, "node": "N1", "addr": addr, "rssi": rssi, "mfr": "0x004C"} - return json.dumps(msg).encode() + reading = {"ts": TS + i * 100, "addr": addr, "rssi": rssi, "mfr": "0x004C"} + return json.dumps({"ts": TS + i * 100 + 50, "node": "N1", "readings": [reading]}).encode() class FakeUnit: diff --git a/invigil/tests/test_monitor_and_screen.py b/invigil/tests/test_monitor_and_screen.py index 10578b1..56ee5e7 100644 --- a/invigil/tests/test_monitor_and_screen.py +++ b/invigil/tests/test_monitor_and_screen.py @@ -10,8 +10,9 @@ def status(uptime=3725, rssi=-43): return json.dumps({"ts": TS, "node": "N1", "uptime_s": uptime, "wifi_rssi": rssi, "fw": "0.1.0"}).encode() -def ble(): - return json.dumps({"ts": TS, "node": "N1", "addr": "a91f03c2d4e8", "rssi": -60, "mfr": None}).encode() +def ble(n=1): + readings = [{"ts": TS, "addr": "a91f03c2d4e8", "rssi": -60, "mfr": None}] * n + return json.dumps({"ts": TS, "node": "N1", "readings": readings}).encode() def test_rates_count_the_last_window_only(): @@ -24,6 +25,13 @@ def test_rates_count_the_last_window_only(): assert view.rates["spectrum"] == 0.0 +def test_ble_rate_counts_readings_not_messages(): + mon = monitor.UnitMonitor(window_s=10) + for i in range(10): + mon.handle("invigil/node/N1/ble", ble(n=7), now=100 + i) # one message a second, 7 readings each + assert mon.view("N1", now=110).rates["ble"] == 7.0 + + def test_rates_use_the_time_listened_when_shorter_than_the_window(): mon = monitor.UnitMonitor(window_s=10) for i in range(10): @@ -61,7 +69,7 @@ def test_status_screen_shows_every_line(): assert "Logger not running" in screen assert "Unit N1 online" in screen assert "uptime 1h 02m, Wi-Fi RSSI -43 dBm, fw 0.1.0, 4 s ago" in screen - assert "rejected 0" in screen + assert "rejected messages 0" in screen assert "1450 ms behind pool.ntp.org" in screen and "WARNING" in screen diff --git a/ml/synth.py b/ml/synth.py index b6c8968..c28d780 100644 --- a/ml/synth.py +++ b/ml/synth.py @@ -56,9 +56,9 @@ def advertise(addr, mfr_id, base_rssi, every_ms): while t < end: if rng.random() < CATCH_RATE: rssi = max(-127, min(0, round(rng.gauss(base_rssi, RSSI_NOISE)))) - msg = {"ts": int(t), "node": "N1", "addr": addr, "rssi": rssi, "mfr": mfr_id} - contract.validate("ble", msg) - ble_rows.append([int(t) + 30, msg["ts"], "N1", addr, rssi, mfr_id or ""]) + reading = {"ts": int(t), "addr": addr, "rssi": rssi, "mfr": mfr_id} + contract.validate("ble", {"ts": int(t), "node": "N1", "readings": [reading]}) + ble_rows.append([int(t) + 30, reading["ts"], "N1", addr, rssi, mfr_id or ""]) t += every_ms + rng.uniform(0, 10) # BLE adds 0-10 ms of random delay advertise(target, mfr, BAND_RSSI[band] + rng.uniform(-3, 3), interval) diff --git a/server/contract.py b/server/contract.py index 54b2e93..0887c6b 100644 --- a/server/contract.py +++ b/server/contract.py @@ -8,6 +8,7 @@ from __future__ import annotations import hashlib +import json import re TOPIC_ROOT = "invigil/node" @@ -17,12 +18,20 @@ NUM_CHANNELS = 126 # nRF24L01 channels 0..125, channel c is 2400 + c MHz FIELDS = { - "ble": ("ts", "node", "addr", "rssi", "mfr"), + "ble": ("ts", "node", "readings"), "spectrum": ("ts", "node", "sweeps", "hits"), "status": ("ts", "node", "uptime_s", "wifi_rssi", "fw"), } KINDS = tuple(FIELDS) +# One advertisement inside a ble message. +READING_FIELDS = ("ts", "addr", "rssi", "mfr") +# One row of ble.csv: the message's node plus one reading. +BLE_ROW_FIELDS = ("ts", "node", "addr", "rssi", "mfr") +# The unit keeps every ble payload at or under this many bytes, so one message +# fits one TCP segment (docs/contract.md, Size limit). +MAX_BLE_PAYLOAD_BYTES = 1400 + # Timestamps are milliseconds since epoch. A value below MIN_TS_MS means the # node has not synced NTP yet, or it sent seconds instead of milliseconds. # A value above MAX_TS_MS usually means microseconds. @@ -84,14 +93,11 @@ def validate(kind: str, payload: object, node: str | None = None) -> dict: raise ContractError("node in payload does not match node in topic") if kind == "ble": - addr = payload["addr"] - if not isinstance(addr, str) or not _ADDR_RE.fullmatch(addr): - raise ContractError("addr must be a hashed address: 12 lowercase hex chars") - _int(payload, "rssi", -127, 0) - mfr = payload["mfr"] - # null is allowed: many advertisements carry no manufacturer data. - if mfr is not None and (not isinstance(mfr, str) or not _MFR_RE.fullmatch(mfr)): - raise ContractError('mfr must be null or a company ID like "0x004C"') + readings = payload["readings"] + if not isinstance(readings, list) or not readings: + raise ContractError("readings must be a list of one or more readings") + for reading in readings: + _validate_reading(reading) elif kind == "spectrum": sweeps = _int(payload, "sweeps", 1, 65_535) @@ -112,13 +118,69 @@ def validate(kind: str, payload: object, node: str | None = None) -> dict: return payload -def _int(payload: dict, key: str, lo: int, hi: int) -> int: +def _validate_reading(reading: object) -> None: + if not isinstance(reading, dict): + raise ContractError("each reading must be a JSON object") + missing = [k for k in READING_FIELDS if k not in reading] + if missing: + raise ContractError(f"reading is missing field(s): {', '.join(missing)}") + extra = sorted(k for k in reading if k not in READING_FIELDS) + if extra: + raise ContractError(f"reading has unexpected field(s): {', '.join(extra)}") + + ts = _int(reading, "ts", 0, MAX_TS_MS, "reading ") + if ts < MIN_TS_MS: + raise ContractError("reading ts is too small: node clock not synced with NTP, or seconds sent instead of ms") + addr = reading["addr"] + if not isinstance(addr, str) or not _ADDR_RE.fullmatch(addr): + raise ContractError("reading addr must be a hashed address: 12 lowercase hex chars") + _int(reading, "rssi", -127, 0, "reading ") + mfr = reading["mfr"] + # null is allowed: many advertisements carry no manufacturer data. + if mfr is not None and (not isinstance(mfr, str) or not _MFR_RE.fullmatch(mfr)): + raise ContractError('reading mfr must be null or a company ID like "0x004C"') + + +def ble_rows(payload: dict) -> list[dict]: + """One dict per reading of a validated ble message, with BLE_ROW_FIELDS keys.""" + return [{"node": payload["node"], **reading} for reading in payload["readings"]] + + +def pack_ble(ts: int, node: str, readings: list[dict], + max_bytes: int = MAX_BLE_PAYLOAD_BYTES) -> list[dict]: + """Split readings into as few ble messages as fit max_bytes each, in order. + + Sizes are those of compact JSON (no spaces), which is what the unit and + the fake publisher send. + """ + empty = len(encode({"ts": ts, "node": node, "readings": []})) + messages = [] + current: list[dict] = [] + size = empty + for reading in readings: + add = len(encode(reading)) + (1 if current else 0) # 1 for the comma + if current and size + add > max_bytes: + messages.append({"ts": ts, "node": node, "readings": current}) + current, size, add = [], empty, add - 1 + current.append(reading) + size += add + if current: + messages.append({"ts": ts, "node": node, "readings": current}) + return messages + + +def encode(payload: dict) -> bytes: + """Compact JSON, the form every publisher sends.""" + return json.dumps(payload, separators=(",", ":")).encode("utf-8") + + +def _int(payload: dict, key: str, lo: int, hi: int, prefix: str = "") -> int: value = payload[key] # bool is a subclass of int in Python, but true/false is never a valid reading. if isinstance(value, bool) or not isinstance(value, int): - raise ContractError(f"{key} must be an integer") + raise ContractError(f"{prefix}{key} must be an integer") if not lo <= value <= hi: - raise ContractError(f"{key} is out of range {lo}..{hi}") + raise ContractError(f"{prefix}{key} is out of range {lo}..{hi}") return value diff --git a/server/fake_publisher.py b/server/fake_publisher.py index be432a6..3026e0b 100644 --- a/server/fake_publisher.py +++ b/server/fake_publisher.py @@ -13,7 +13,6 @@ from __future__ import annotations import argparse -import json import logging import math import os @@ -34,7 +33,7 @@ log = logging.getLogger("invigil.fake") -FAKE_FW = "0.1.0-fake" # shows up in status.csv, so fake runs are easy to spot +FAKE_FW = "0.2.0-fake" # shows up in status.csv, so fake runs are easy to spot # Distance bands from docs/data-protocol.md: (name, upper edge in metres). BANDS = (("near", 1.0), ("mid", 2.0), ("far", 3.5)) @@ -143,8 +142,10 @@ def simulate_window(node: str, t0: int, t1: int, devices: list[Device], sweeps: int, rng: random.Random) -> list[tuple[str, dict]]: """Messages the unit sends after scanning from t0 to t1 (ms since epoch). - BLE readings carry the time each advertisement was heard. The spectrum - message covers the whole scan window and carries its end time. + BLE readings carry the time each advertisement was heard, and go out + together in as few ble messages as fit the size limit, each carrying the + end of the scan window. The spectrum message covers the whole scan window + and carries its end time. """ ble = [] for dev in devices: @@ -160,10 +161,10 @@ def simulate_window(node: str, t0: int, t1: int, devices: list[Device], rssi = dev.rssi_1m - path_loss_db(dev.distance_m) + rng.gauss(0, RSSI_NOISE_DB) if rssi < BLE_SENSITIVITY_DBM or rng.random() > BLE_CATCH_RATE: continue - ble.append({"ts": int(t), "node": node, "addr": dev.addr, + ble.append({"ts": int(t), "addr": dev.addr, "rssi": max(-127, min(0, round(rssi))), "mfr": dev.mfr}) - ble.sort(key=lambda m: m["ts"]) - msgs = [("ble", m) for m in ble] + ble.sort(key=lambda r: r["ts"]) + msgs = [("ble", m) for m in contract.pack_ble(t1, node, ble)] hits = spectrum_hits(devices, sweeps, rng) msgs.append(("spectrum", {"ts": t1, "node": node, "sweeps": sweeps, "hits": hits})) return msgs @@ -271,7 +272,7 @@ def on_connect(client, userdata, flags, reason_code, properties): def send(kind: str, payload: dict) -> None: contract.validate(kind, payload, payload["node"]) # never publish anything off-contract - client.publish(contract.topic(payload["node"], kind), json.dumps(payload, separators=(",", ":"))) + client.publish(contract.topic(payload["node"], kind), contract.encode(payload)) log.info("fake unit %s publishing to %s:%d (scan %d ms, send %d ms, %d sweeps)", ", ".join(contract.NODE_IDS), host, port, args.scan_ms, args.send_ms, args.sweeps) diff --git a/server/logger.py b/server/logger.py index 00b401f..aa28bdc 100644 --- a/server/logger.py +++ b/server/logger.py @@ -5,7 +5,8 @@ Writes data/raw/-/ble.csv, spectrum.csv and status.csv. Each row starts with rx_ts, the laptop time (ms since epoch) when the message -arrived, so rx_ts - ts is the node-to-laptop latency. +arrived, so rx_ts - ts is the node-to-laptop latency. A ble message carries +several readings; each reading gets its own row with its own ts. Messages that break the MQTT contract are counted and reported on the console but never written to disk, so a firmware bug cannot leak raw data into a file. @@ -34,7 +35,7 @@ log = logging.getLogger("invigil.logger") COLUMNS = { - "ble": ["rx_ts", *contract.FIELDS["ble"]], + "ble": ["rx_ts", *contract.BLE_ROW_FIELDS], "spectrum": ["rx_ts", "ts", "node", "sweeps"] + [f"ch{c:03d}" for c in range(contract.NUM_CHANNELS)], "status": ["rx_ts", *contract.FIELDS["status"]], @@ -45,11 +46,14 @@ def now_ms() -> int: return time.time_ns() // 1_000_000 -def to_row(kind: str, payload: dict, rx_ts: int) -> list: +def to_rows(kind: str, payload: dict, rx_ts: int) -> list[list]: + """CSV rows for one valid message: one per reading for ble, else one.""" if kind == "spectrum": - return [rx_ts, payload["ts"], payload["node"], payload["sweeps"], *payload["hits"]] + return [[rx_ts, payload["ts"], payload["node"], payload["sweeps"], *payload["hits"]]] # A null mfr is written as an empty cell. - return [rx_ts, *(payload[k] for k in contract.FIELDS[kind])] + if kind == "ble": + return [[rx_ts, *(r[k] for k in contract.BLE_ROW_FIELDS)] for r in contract.ble_rows(payload)] + return [[rx_ts, *(payload[k] for k in contract.FIELDS[kind])]] class CsvSink: @@ -88,7 +92,7 @@ def __init__(self, sink: CsvSink): self.sink = sink self.total = 0 self._lock = threading.Lock() - self._accepted = Counter() # (node, kind) -> count since last report + self._accepted = Counter() # (node, kind) -> rows written since last report self._rejected = Counter() # reason -> count since last report self._latencies = [] # rx_ts - ts, ms, since last report self._warned = set() @@ -107,11 +111,13 @@ def handle(self, topic: str, raw: bytes, rx_ts: int) -> bool: log.warning("rejected %s: %s (repeats are only counted)", topic, reason) return False + rows = to_rows(kind, payload, rx_ts) with self._lock: - self.sink.write(kind, to_row(kind, payload, rx_ts)) - self.total += 1 - self._accepted[(node, kind)] += 1 - self._latencies.append(rx_ts - payload["ts"]) + for row in rows: + self.sink.write(kind, row) + self._latencies.append(rx_ts - row[1]) # row[1] is ts + self.total += len(rows) + self._accepted[(node, kind)] += len(rows) return True def report(self) -> str: diff --git a/server/tests/test_contract.py b/server/tests/test_contract.py index c62bf29..97c9ed9 100644 --- a/server/tests/test_contract.py +++ b/server/tests/test_contract.py @@ -1,4 +1,5 @@ import hashlib +import json import pytest @@ -8,9 +9,20 @@ TS = 1727340000123 +def reading(**changes): + r = {"ts": TS, "addr": "a91f03c2d4e8", "rssi": -58, "mfr": "0x004C"} + r.update(changes) + return r + + def ble(**changes): - msg = {"ts": TS, "node": "N1", "addr": "a91f03c2d4e8", "rssi": -58, "mfr": "0x004C"} - msg.update(changes) + """A ble message. Changes to ts and node go to the message, the rest to its reading.""" + msg = {"ts": TS + 877, "node": "N1", "readings": []} + for key in ("ts", "node", "readings"): + if key in changes: + msg[key] = changes.pop(key) + if not msg["readings"]: + msg["readings"] = [reading(**changes)] return msg @@ -54,6 +66,8 @@ def test_bad_topics_rejected(name): def test_timestamp_in_seconds_gets_a_helpful_reason(): with pytest.raises(ContractError, match="NTP"): validate("ble", ble(ts=1727340000)) + with pytest.raises(ContractError, match="NTP"): + validate("ble", ble(readings=[reading(ts=1727340000)])) def test_node_must_match_topic(): @@ -75,6 +89,8 @@ def test_second_node_is_rejected_until_phase_2(): def test_bad_timestamps_rejected(ts): with pytest.raises(ContractError): validate("ble", ble(ts=ts)) + with pytest.raises(ContractError): + validate("ble", ble(readings=[reading(ts=ts)])) @pytest.mark.parametrize("addr", [ @@ -115,11 +131,85 @@ def test_bad_mfr_rejected(mfr): def test_missing_and_extra_fields_rejected(): msg = ble() - del msg["rssi"] + del msg["readings"][0]["rssi"] with pytest.raises(ContractError, match="missing"): validate("ble", msg) with pytest.raises(ContractError, match="unexpected"): validate("ble", ble(payload="deadbeef")) + msg = ble() + del msg["readings"] + with pytest.raises(ContractError, match="missing"): + validate("ble", msg) + msg = ble() + msg["addr"] = "a91f03c2d4e8" # the old one-reading shape at the top level + with pytest.raises(ContractError, match="unexpected"): + validate("ble", msg) + + +def test_old_single_reading_shape_rejected(): + old = {"ts": TS, "node": "N1", "addr": "a91f03c2d4e8", "rssi": -58, "mfr": "0x004C"} + with pytest.raises(ContractError): + validate("ble", old) + + +def test_several_readings_are_valid(): + msg = ble(readings=[reading(), reading(ts=TS + 300, addr="0f5e2b7a91c4", rssi=-81, mfr=None)]) + validate("ble", msg, "N1") + + +@pytest.mark.parametrize("readings", [[], None, "x", {"ts": TS}, [["a91f03c2d4e8", -58]], [None]]) +def test_bad_readings_list_rejected(readings): + with pytest.raises(ContractError): + validate("ble", {"ts": TS, "node": "N1", "readings": readings}) + + +def test_one_bad_reading_rejects_the_message(): + msg = ble(readings=[reading(), reading(rssi=3)]) + with pytest.raises(ContractError, match="reading rssi"): + validate("ble", msg) + + +def test_ble_rows_flatten_one_row_per_reading(): + msg = ble(readings=[reading(), reading(ts=TS + 300, addr="0f5e2b7a91c4", rssi=-81, mfr=None)]) + rows = contract.ble_rows(validate("ble", msg)) + assert [tuple(r[k] for k in contract.BLE_ROW_FIELDS) for r in rows] == [ + (TS, "N1", "a91f03c2d4e8", -58, "0x004C"), + (TS + 300, "N1", "0f5e2b7a91c4", -81, None), + ] + + +def test_pack_ble_keeps_order_and_size_limit(): + readings = [reading(ts=TS + i, rssi=-(i % 128), mfr=None if i % 3 else "0x004C") for i in range(200)] + messages = contract.pack_ble(TS + 1000, "N1", readings) + assert len(messages) > 1 + assert [r for m in messages for r in m["readings"]] == readings + for m in messages: + validate("ble", m, "N1") + assert len(contract.encode(m)) <= contract.MAX_BLE_PAYLOAD_BYTES + # As few messages as possible: each one but the last could not take the next reading. + for m, after in zip(messages, messages[1:]): + bigger = {**m, "readings": [*m["readings"], after["readings"][0]]} + assert len(contract.encode(bigger)) > contract.MAX_BLE_PAYLOAD_BYTES + + +def test_pack_ble_worst_case_reading_count(): + worst = reading(ts=contract.MAX_TS_MS, rssi=-127, mfr="0xFFFF") + messages = contract.pack_ble(contract.MAX_TS_MS, "N1", [worst] * 40) + assert len(contract.encode({"ts": 0, "addr": worst["addr"], "rssi": 0, "mfr": None})) < len( + contract.encode(worst)) == 69 + assert len(messages[0]["readings"]) == 19 # docs/contract.md: at least 19 + + +def test_pack_ble_empty_and_tiny_limit(): + assert contract.pack_ble(TS, "N1", []) == [] + # A limit too small for even one reading still sends each reading on its own. + messages = contract.pack_ble(TS, "N1", [reading(), reading()], max_bytes=10) + assert [len(m["readings"]) for m in messages] == [1, 1] + + +def test_encode_is_compact(): + assert b" " not in contract.encode(ble()) + assert json.loads(contract.encode(ble())) == ble() @pytest.mark.parametrize("hits", [[0] * 125, [0] * 127, [51] + [0] * 125, [-1] + [0] * 125, "0" * 126]) diff --git a/server/tests/test_fake_publisher.py b/server/tests/test_fake_publisher.py index 5c24212..bd06140 100644 --- a/server/tests/test_fake_publisher.py +++ b/server/tests/test_fake_publisher.py @@ -23,6 +23,33 @@ def test_every_message_follows_the_contract(): for kind, payload in msgs: contract.validate(kind, payload, payload["node"]) assert t0 <= payload["ts"] <= t1 # nothing from the send window + if kind == "ble": + assert payload["ts"] == t1 # end of the scan window + assert all(t0 <= r["ts"] < t1 for r in payload["readings"]) + assert len(contract.encode(payload)) <= contract.MAX_BLE_PAYLOAD_BYTES + + +def test_ble_readings_are_batched_in_time_order(): + _, windows = run_windows(30) + for _, _, msgs in windows: + ble = [p for k, p in msgs if k == "ble"] + readings = [r["ts"] for p in ble for r in p["readings"]] + assert readings == sorted(readings) + # Every message but the last is full enough that splitting was needed. + assert len(ble) <= 1 + len(readings) // 19 + + +def test_a_busy_window_is_split_under_the_size_limit(): + rng = random.Random(3) + devices = default_devices("test-salt", rng) + for d in devices: + if d.adv_interval_ms: + d.adv_interval_ms = 20 # far busier than any real device + msgs = simulate_window("N1", T0, T0 + 800, devices, 20, rng) + ble = [p for k, p in msgs if k == "ble"] + assert len(ble) > 1 + for p in ble: + assert len(contract.encode(p)) <= contract.MAX_BLE_PAYLOAD_BYTES def test_one_spectrum_message_per_window(): @@ -35,7 +62,7 @@ def test_only_advertising_devices_show_up_in_ble(): devices, windows = run_windows(30) advertising = {d.addr for d in devices if d.adv_interval_ms} silent = {d.addr for d in devices if not d.adv_interval_ms} - seen = {p["addr"] for _, _, msgs in windows for k, p in msgs if k == "ble"} + seen = {r["addr"] for _, _, msgs in windows for k, p in msgs if k == "ble" for r in p["readings"]} assert seen == advertising assert not seen & silent diff --git a/server/tests/test_logger.py b/server/tests/test_logger.py index 21282fe..000750d 100644 --- a/server/tests/test_logger.py +++ b/server/tests/test_logger.py @@ -15,10 +15,21 @@ def make_recorder(tmp_path): return Recorder(CsvSink(tmp_path / "session")) +def ble(*readings, ts=TS + 900): + return {"ts": ts, "node": "N1", "readings": list(readings)} + + +def reading(ts=TS, addr="a91f03c2d4e8", rssi=-58, mfr="0x004C"): + return {"ts": ts, "addr": addr, "rssi": rssi, "mfr": mfr} + + +def test_ble_csv_columns_are_unchanged(): + assert COLUMNS["ble"] == ["rx_ts", "ts", "node", "addr", "rssi", "mfr"] + + def test_valid_ble_is_written_with_rx_ts(tmp_path): rec = make_recorder(tmp_path) - msg = {"ts": TS, "node": "N1", "addr": "a91f03c2d4e8", "rssi": -58, "mfr": "0x004C"} - assert rec.handle("invigil/node/N1/ble", json.dumps(msg).encode(), TS + 400) + assert rec.handle("invigil/node/N1/ble", json.dumps(ble(reading())).encode(), TS + 400) rec.close() rows = read_csv(tmp_path / "session" / "ble.csv") @@ -26,10 +37,26 @@ def test_valid_ble_is_written_with_rx_ts(tmp_path): assert rows[1] == [str(TS + 400), str(TS), "N1", "a91f03c2d4e8", "-58", "0x004C"] +def test_each_reading_gets_its_own_row_and_ts(tmp_path): + rec = make_recorder(tmp_path) + msg = ble(reading(), reading(ts=TS + 250, addr="0f5e2b7a91c4", rssi=-81, mfr=None)) + assert rec.handle("invigil/node/N1/ble", json.dumps(msg).encode(), TS + 1000) + rec.close() + + rows = read_csv(tmp_path / "session" / "ble.csv") + assert rows[1:] == [ + [str(TS + 1000), str(TS), "N1", "a91f03c2d4e8", "-58", "0x004C"], + [str(TS + 1000), str(TS + 250), "N1", "0f5e2b7a91c4", "-81", ""], + ] + assert rec.total == 2 + line = rec.report() + assert "N1: 2 ble" in line + assert "p50 875 ms" in line # latencies 1000 and 750, from each reading's own ts + + def test_null_mfr_is_an_empty_cell(tmp_path): rec = make_recorder(tmp_path) - msg = {"ts": TS, "node": "N1", "addr": "a91f03c2d4e8", "rssi": -70, "mfr": None} - assert rec.handle("invigil/node/N1/ble", json.dumps(msg).encode(), TS) + assert rec.handle("invigil/node/N1/ble", json.dumps(ble(reading(rssi=-70, mfr=None))).encode(), TS) rec.close() assert read_csv(tmp_path / "session" / "ble.csv")[1][-1] == "" @@ -50,14 +77,17 @@ def test_spectrum_gets_one_column_per_channel(tmp_path): def test_rejected_messages_never_reach_disk(tmp_path): rec = make_recorder(tmp_path) raw_mac = "A9:1F:03:C2:D4:E8" - bad = {"ts": TS, "node": "N1", "addr": raw_mac, "rssi": -58, "mfr": "0x004C"} + # One raw address in an otherwise good message rejects the whole message. + bad = ble(reading(), reading(addr=raw_mac)) assert not rec.handle("invigil/node/N1/ble", json.dumps(bad).encode(), TS) + old_shape = {"ts": TS, "node": "N1", "addr": "a91f03c2d4e8", "rssi": -58, "mfr": "0x004C"} + assert not rec.handle("invigil/node/N1/ble", json.dumps(old_shape).encode(), TS) assert not rec.handle("invigil/node/N1/ble", b"{not json", TS) assert not rec.handle("invigil/node/N9/ble", b"{}", TS) rec.close() assert rec.total == 0 - assert "rejected 3" in rec.report() + assert "rejected 4" in rec.report() written = [p for p in tmp_path.rglob("*") if p.is_file()] assert written == []