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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 76 additions & 13 deletions dashboard/src/data/__tests__/contract.test.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown>) => ({ ...ble(), readings: [{ ...reading(), ...changes }] })
const spectrum = () => ({ ts: TS, node: "N1", sweeps: 50, hits: new Array<number>(126).fill(0) })
const status = () => ({ ts: TS, node: "N1", uptime_s: 3600, wifi_rssi: -61, fw: "0.1.0" })

Expand Down Expand Up @@ -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", () => {
Expand All @@ -47,39 +51,64 @@ describe("validate", () => {

it("rejects missing and extra fields", () => {
const missing: Record<string, unknown> = 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<string, unknown> = { ...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")
})

it("rejects ts in seconds, in microseconds, and as a decimal", () => {
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)
}
})

Expand Down Expand Up @@ -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<BleReading>(40).fill(worst))[0].readings).toHaveLength(19)
})

it("sends nothing for no readings", () => {
expect(packBle(TS, "N1", [])).toEqual([])
})
})
32 changes: 30 additions & 2 deletions dashboard/src/data/__tests__/store.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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> = {}): Detection {
Expand All @@ -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)],
Expand Down
110 changes: 93 additions & 17 deletions dashboard/src/data/contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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]
Expand Down Expand Up @@ -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<string, unknown>, 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<string, unknown>
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<K extends Kind>(
kind: K,
Expand All @@ -114,13 +165,8 @@ export function validate<K extends Kind>(
}
const p = payload as Record<string, unknown>

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)
Expand All @@ -135,14 +181,13 @@ export function validate<K extends Kind>(
}

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)
Expand Down Expand Up @@ -170,6 +215,37 @@ export function validate<K extends Kind>(
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<ContractMessage> {
const parsed = parseTopic(topicName)
Expand Down
13 changes: 7 additions & 6 deletions dashboard/src/data/demo/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -202,15 +202,16 @@ 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) ?? []
recent.push(heard)
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 })
}

Expand Down
Loading
Loading