From 7aa3a163fc03c4d687a53ee13b6c36ff2b681569 Mon Sep 17 00:00:00 2001 From: mcroomp <20727346+mcroomp@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:09:20 +0100 Subject: [PATCH] Add standalone load-cell firmware and four-input CSV plots Include two/four-input acquisition, raw CSV metadata, authenticated opt-in OTA, verified USB backup tooling, configurable Windows launchers, and independent A1/A2/B1/B2 plots. Keep local credentials, network addresses, backups and generated firmware out of Git; document the private configuration files. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- README.md | 1 + design/linkhub.md | 40 ++- linkhub-ui/README.md | 36 ++- linkhub-ui/src/api.ts | 10 + linkhub-ui/src/csv-chart.ts | 95 ++++++ linkhub-ui/src/csv-model.ts | 121 +++++++ linkhub-ui/src/csv-panel.ts | 103 +++++- linkhub-ui/src/demo-backend.ts | 2 +- linkhub-ui/src/styles.css | 3 +- linkhub-ui/src/types.ts | 19 ++ linkhub-ui/tests/api.test.ts | 16 +- linkhub-ui/tests/csv-panel.test.ts | 402 +++++++++++++++++++++++- linkhub-ui/tests/demo-backend.test.ts | 2 +- linkhub/README.md | 44 ++- linkhub/csv-map.json | 10 +- linkhub/src/csv_ingest.rs | 384 +++++++++++++++++++++- linkhub/src/http.rs | 165 ++++++++-- linkhub/src/journal.rs | 258 ++++++++++----- loadcell/.gitignore | 5 + loadcell/AGENTS.md | 78 +++++ loadcell/README.md | 268 ++++++++++++++++ loadcell/backup_esp32.py | 192 +++++++++++ loadcell/include/config.h | 39 +++ loadcell/include/hx711_input.h | 106 +++++++ loadcell/include/local_config.h.example | 6 + loadcell/include/ota.h | 4 + loadcell/include/sample_csv.h | 34 ++ loadcell/launch_config.cmd.example | 3 + loadcell/platformio.ini | 14 + loadcell/src/main.cpp | 354 +++++++++++++++++++++ loadcell/src/ota.cpp | 108 +++++++ loadcell/test/test_hx711.cpp | 172 ++++++++++ run_linkhub_esp.cmd | 23 ++ scripts/configure_esp_csv.ps1 | 62 ++++ tests/unit/test_backup_esp32.py | 191 +++++++++++ tests/unit/test_windows_setup.py | 109 +++++++ 36 files changed, 3316 insertions(+), 163 deletions(-) create mode 100644 linkhub-ui/src/csv-chart.ts create mode 100644 linkhub-ui/src/csv-model.ts create mode 100644 loadcell/.gitignore create mode 100644 loadcell/AGENTS.md create mode 100644 loadcell/README.md create mode 100644 loadcell/backup_esp32.py create mode 100644 loadcell/include/config.h create mode 100644 loadcell/include/hx711_input.h create mode 100644 loadcell/include/local_config.h.example create mode 100644 loadcell/include/ota.h create mode 100644 loadcell/include/sample_csv.h create mode 100644 loadcell/launch_config.cmd.example create mode 100644 loadcell/platformio.ini create mode 100644 loadcell/src/main.cpp create mode 100644 loadcell/src/ota.cpp create mode 100644 loadcell/test/test_hx711.cpp create mode 100644 run_linkhub_esp.cmd create mode 100644 scripts/configure_esp_csv.ps1 create mode 100644 tests/unit/test_backup_esp32.py diff --git a/README.md b/README.md index 766b02b..681c599 100644 --- a/README.md +++ b/README.md @@ -147,6 +147,7 @@ load unrelated documents. | [linkhub/README.md](linkhub/README.md) | Build, run, CLI, HTTP usage and journal queries | | [mavlink-protocol README](linkhub/mavlink-protocol/README.md) | Stable MAVLink protocol crate, pinned definitions and generation workflow | | [linkhub-ui/README.md](linkhub-ui/README.md) | Browser UI setup and behavior | +| [loadcell/README.md](loadcell/README.md) | Standalone ESP32/HX711 sensor firmware, build, wiring, configuration, and CSV transport | | [linkhub_client/README.md](linkhub_client/README.md) | Typed Python HTTP client | | [envelope/CLAUDE.md](envelope/CLAUDE.md) | Agent notes for the flight-envelope package | | [presentations/presentation_sitl_aero.md](presentations/presentation_sitl_aero.md) | Slide deck on the SITL and aero architecture | diff --git a/design/linkhub.md b/design/linkhub.md index 43fae88..94614e3 100644 --- a/design/linkhub.md +++ b/design/linkhub.md @@ -96,11 +96,13 @@ header to skip files without decoding them. Files with any other magic are rejected rather than skipped. LinkHub does not fsync or repair partial tail files. A clean shutdown flushes the active chunk. -For a replay, the actor first fixes one tail sequence and snapshots the active -chunk; the reader then merges that snapshot with completed chunks through the -fixed tail. This ordering prevents a periodic flush from moving records between -the disk and RAM views while a replay is being assembled. Public reads are -finite batches; LinkHub keeps no per-client subscription or queue. +The actor builds an in-memory index from chunk filenames and headers when it +opens the journal and adds each new chunk only after the file has been renamed +into place. Live reads seek by sequence and time without rescanning the +directory or reopening old headers. For a replay, the actor snapshots both +the matching indexed paths and the active records in one step, so a periodic +flush cannot introduce duplicates or gaps. Public reads are finite batches; +LinkHub keeps no per-client subscription or queue. ## Diagnostics @@ -153,7 +155,8 @@ to distinguish unknown state from confirmed disarmed state. `--csv-map` loads a JSON source/column mapping at startup for the generic `/v1/csv` HTTP receiver. The mapping, not Rust code, owns incoming column order, -output field names, value types, and the unsigned sequence column. The checked +output field names, value types, the unsigned sequence column, and an optional +`time_column` containing a device time-of-day string. The checked example describes ESP32 strain measurements, but the receiver is sensor-agnostic. Invalid mappings fail startup; malformed batches are validated before any rows are accepted. Header-only uploads acknowledge file creation without fabricating @@ -164,7 +167,30 @@ and the configured source. The existing journal owns ordering, persistence, retry deduplication (source, filename, device sequence), cursor reads, and experiment inclusion. There is no separate CSV transport archive. A per-run five-row cache exposes recent and latest mapped values and host receive time without -claiming a device clock, units, or freshness. HTTP ingestion works independently +claiming a device clock, units, or freshness. Its `rows_received` counter tracks +newly journaled samples across filenames during the service run, excluding +headers, rejected rows, and duplicate retries; restart resets it. +Rows are journaled immediately on batch arrival, never replayed at device pace. +For periodic feeds with `time_column`, `sample_time_ns` estimates host-aligned +acquisition time by anchoring the final row in each periodic batch to its +receipt time and preserving the other rows' relative device-clock spacing. +Each batch gets a fresh anchor; the device's absolute clock and date are not +treated as synchronized. `received_time_ns` stays the separate batch receipt +time. The raw mapped time string is retained unchanged. + +Midnight is unwrapped using the nearest time-of-day difference (within 12 hours). +Backward clock jumps or a restarting row counter with forward-moving device time +begin a new `clock_epoch` and flag `time_quality=clock_reset`. Counter restarts +can occur inside a batch when the ESP changes CSV files; the final row, not the +largest counter, remains the batch's receipt anchor. +Older sequence rows are flagged `out_of_order` without advancing clock state. +If their epoch cannot be determined after a reset, or a device timestamp would +place a sample after batch receipt, acquisition time is `null`, not fabricated. +Feeds without `time_column` expose null acquisition time with quality +`unavailable`. Duplicate retries never advance the clock state. These timing +fields are present on both CSV readings and journal event fields; estimates +are not proof of synchronization with MAVLink. +HTTP ingestion works independently of MAVLink readiness. It never commands or reconfigures the sending device. See [CSV usage and mapping format](../linkhub/README.md#generic-csv-ingestion). diff --git a/linkhub-ui/README.md b/linkhub-ui/README.md index 40cf250..f203716 100644 --- a/linkhub-ui/README.md +++ b/linkhub-ui/README.md @@ -10,13 +10,43 @@ MAVLink encoding limits still apply at the vehicle boundary; see ## CSVs pane When LinkHub receives CSV rows, the **CSVs** button appears and its pane opens. -It shows the last five newly accepted rows, their filenames and host receive -times, with columns driven by the runtime mapping rather than sensor-specific -code. Use the button to collapse/reopen it. Polling is independent of MAVLink, +It shows the latest raw **A1, A2, B1, B2** values from the current file's recent +readings, its filename and host +receive time, and a live count of newly accepted CSV rows since LinkHub started. +Headers, duplicate retries, and rejected rows do not increase the count; it +continues across CSV files and resets on service restart. Other mapped CSV fields +are not displayed. Use the button to +collapse/reopen it. The values and count refresh once per second. +Polling is independent of MAVLink, so no vehicle heartbeat is needed. Old values retain their receive time; network errors are displayed explicitly, not presented as fresh readings. The offline demo has no CSV feed and does not fabricate samples. +The same graph overlays **raw A1, A2, B1, B2 ADC counts**, each in a distinct +color, with matching dashed **trailing 1-second arithmetic means**. +It splits the firmware's one-reading-per-row `input`/`raw` CSV mapping into +independent traces; alternating inputs are not treated as zeros or as gaps +in another input's curve. There is no force conversion or gain normalization. +The legend wraps to fit narrower panes. The inclusive window is +`[sample time − 1 s, sample time]`; +irregular spacing is supported without assuming a sample rate. The x-axis is +elapsed estimated acquisition time, reconstructed by LinkHub from the relative +device clock and periodic batch receipts, not a synchronized ESP wall clock. +Host receipt time remains separate in the header. + +The chart shows a rolling five minutes of samples for the current source, even +when uploads pause. It reads recent `csv.sample` diagnostics, not the five-row +status preview, with an extra second for smoothing at the left edge. The full +journal and cumulative row count are unchanged. Cursor pages, including empty advancing +pages, are consumed up to each poll's snapshot tail (at most 32 pages per poll). +Every fetched batch redraws immediately, without replay or animation; the next +poll resumes any backlog. The chart retains at most 10,000 samples. Files and +clock epochs have separate curves and averaging windows; out-of-order samples +are sorted within their segment. Old samples without acquisition metadata are +explicitly marked **timing unavailable** and excluded from plots and averages, +never silently assigned host receipt times. Restart/source changes clear history. +Journal errors retain already plotted data with an explicit error. + Enable the receiver with `LINKHUB_CSV_MAP` or `--csv-map`; see [CSV ingestion and the ESP32 example](../linkhub/README.md#generic-csv-ingestion). diff --git a/linkhub-ui/src/api.ts b/linkhub-ui/src/api.ts index 1eeca25..ca1d83d 100644 --- a/linkhub-ui/src/api.ts +++ b/linkhub-ui/src/api.ts @@ -2,6 +2,7 @@ import type { CommandResult, CameraStatus, CsvStatus, + DiagnosticBatch, ExperimentInfo, JsonObject, LinkHubStatus, @@ -158,6 +159,15 @@ export class LinkHubApi { return this.request("GET", "/v1/camera", undefined, AbortSignal.timeout(3_000)); } + csvSamples(after: string, source: string, limit = 1_000, signal?: AbortSignal): Promise { + const query = new URLSearchParams({ after, source, event: "csv.sample", limit: String(limit), last_ms: "301000" }); + const timeout = AbortSignal.timeout(3_000); + return this.request( + "GET", `/v1/diagnostics/events?${query}`, undefined, + signal ? AbortSignal.any([signal, timeout]) : timeout, + ); + } + csvStatus(signal?: AbortSignal): Promise { const timeout = AbortSignal.timeout(3_000); return this.request( diff --git a/linkhub-ui/src/csv-chart.ts b/linkhub-ui/src/csv-chart.ts new file mode 100644 index 0000000..1b05785 --- /dev/null +++ b/linkhub-ui/src/csv-chart.ts @@ -0,0 +1,95 @@ +import { CSV_INPUTS, csvSeries, type CsvModel } from "./csv-model"; + +const COLORS = ["#78b7ff", "#f0c36b", "#71ddb4", "#c792ea"]; +const LINES = CSV_INPUTS.flatMap((input, index) => [ + { input, label: `${input} raw`, color: COLORS[index]!, smooth: false }, + { input, label: `${input} 1 s mean`, color: COLORS[index]!, smooth: true }, +]); + +export function drawCsvChart(canvas: HTMLCanvasElement, model: CsvModel, cutoff: number): void { + const width = Math.max(320, canvas.clientWidth); + const height = 240; + const dpr = window.devicePixelRatio || 1; + canvas.width = Math.round(width * dpr); + canvas.height = Math.round(height * dpr); + const ctx = canvas.getContext("2d"); + if (!ctx) return; + ctx.setTransform(dpr, 0, 0, dpr, 0, 0); + ctx.clearRect(0, 0, width, height); + ctx.font = "10px ui-monospace, 'Cascadia Code', monospace"; + ctx.textAlign = "left"; + let legendX = 56, legendY = 15; + for (const line of LINES) { + const itemWidth = 21 + ctx.measureText(line.label).width + 18; + if (legendX > 56 && legendX + itemWidth > width - 10) { + legendX = 56; + legendY += 20; + } + ctx.strokeStyle = line.color; + ctx.lineWidth = line.smooth ? 2 : 1; + ctx.setLineDash(line.smooth ? [5, 3] : []); + ctx.beginPath(); ctx.moveTo(legendX, legendY - 3); ctx.lineTo(legendX + 15, legendY - 3); ctx.stroke(); + ctx.fillStyle = line.color; + ctx.fillText(line.label, legendX + 21, legendY); + legendX += itemWidth; + } + const top = legendY + 18; + ctx.setLineDash([]); + const groups = csvSeries(model.samples).map((group) => group.filter((point) => point.time >= cutoff)); + const points = groups.flat(); + let t0 = Infinity, t1 = -Infinity, min = Infinity, max = -Infinity; + for (const point of points) { + t0 = Math.min(t0, point.time); + t1 = Math.max(t1, point.time); + for (const line of LINES) { + const value = line.smooth ? point.means[line.input] : point[line.input]; + if (value !== null) { min = Math.min(min, value); max = Math.max(max, value); } + } + } + ctx.fillStyle = "#8fa2bc"; + if (!points.length || !Number.isFinite(min)) { + ctx.fillText("No timed A1/A2/B1/B2 samples to plot", 56, top + 30); + return; + } + const pad = Math.max((max - min) * 0.08, Math.abs(max) * 0.01, 0.01); + min -= pad; max += pad; + const span = Math.max(t1 - t0, 0.001); + const left = 56, plotWidth = width - 66, plotHeight = height - top - 40; + const x = (time: number) => left + (time - t0) / span * plotWidth; + const y = (value: number) => top + (max - value) / (max - min) * plotHeight; + for (let tick = 0; tick <= 4; tick++) { + const fraction = tick / 4; + const py = top + fraction * plotHeight; + ctx.strokeStyle = "rgba(70, 90, 121, 0.35)"; + ctx.beginPath(); ctx.moveTo(left, py); ctx.lineTo(width - 10, py); ctx.stroke(); + ctx.textAlign = "right"; + ctx.fillText((max - fraction * (max - min)).toPrecision(4), left - 6, py + 3); + ctx.textAlign = tick === 0 ? "left" : tick === 4 ? "right" : "center"; + ctx.fillText(((t1 - t0) * fraction).toFixed(2), left + fraction * plotWidth, height - 23); + } + ctx.textAlign = "center"; + ctx.fillText("Estimated acquisition elapsed (s) · raw ADC counts", left + plotWidth / 2, height - 6); + for (const line of LINES) { + ctx.strokeStyle = line.color; + ctx.fillStyle = line.color; + ctx.lineWidth = line.smooth ? 2 : 1; + ctx.setLineDash(line.smooth ? [5, 3] : []); + for (const group of groups) { + ctx.beginPath(); + let connected = false; + for (const point of group) { + const value = line.smooth ? point.means[line.input] : point[line.input]; + if (value === null) { + if (line.smooth) connected = false; + continue; + } + if (connected) ctx.lineTo(x(point.time), y(value)); + else ctx.moveTo(x(point.time), y(value)); + connected = true; + ctx.fillRect(x(point.time) - 1, y(value) - 1, 2, 2); + } + ctx.stroke(); + } + } + ctx.setLineDash([]); +} diff --git a/linkhub-ui/src/csv-model.ts b/linkhub-ui/src/csv-model.ts new file mode 100644 index 0000000..0b49498 --- /dev/null +++ b/linkhub-ui/src/csv-model.ts @@ -0,0 +1,121 @@ +import type { DiagnosticRecord } from "./types"; + +export const CSV_INPUTS = ["A1", "A2", "B1", "B2"] as const; +export type CsvInput = typeof CSV_INPUTS[number]; +type CsvValues = Record; + +export interface CsvSample extends CsvValues { + filename: string; + epoch: number | null; + time: number | null; + receivedTime?: number; + reset: boolean; +} + +export interface CsvPoint extends CsvValues { + time: number; + means: CsvValues; +} + +const numeric = (value: unknown): number | null => + typeof value === "number" && Number.isFinite(value) ? value : null; + +export function csvValues(values: unknown): CsvValues { + const result: CsvValues = { A1: null, A2: null, B1: null, B2: null }; + if (typeof values !== "object" || values === null || !("input" in values) || !("raw" in values)) { + return result; + } + const input = CSV_INPUTS.find((input) => input === values.input); + if (input) result[input] = numeric(values.raw); + return result; +} + +export function csvSample(record: DiagnosticRecord): CsvSample | null { + const fields = record.data.fields; + if (typeof fields.filename !== "string" || typeof fields.values !== "object" + || fields.values === null || Array.isArray(fields.values)) return null; + const quality = fields.time_quality; + const timed = quality === "estimated" || quality === "clock_reset" || quality === "out_of_order"; + const ns = timed ? numeric(fields.sample_time_ns) : null; + const epoch = timed ? numeric(fields.clock_epoch) : null; + return { + filename: fields.filename, epoch, time: ns === null || epoch === null ? null : ns / 1e9, + receivedTime: record.ingest_time_ns === undefined ? undefined : record.ingest_time_ns / 1e9, + reset: quality === "clock_reset", + ...csvValues(fields.values), + }; +} + +/** Inclusive [t - 1, t] arithmetic means, independently for each finite field. */ +export function csvSeries(samples: readonly CsvSample[]): CsvPoint[][] { + const groups: CsvSample[][] = []; + let previous: CsvSample | undefined; + for (const sample of samples) { + if (sample.time === null) { + previous = undefined; + continue; + } + if (!previous || sample.reset || previous.filename !== sample.filename || previous.epoch !== sample.epoch) { + groups.push([]); + } + groups.at(-1)!.push(sample); + previous = sample; + } + return groups.map((group) => { + const sorted = group.slice().sort((a, b) => a.time! - b.time!); + const points: CsvPoint[] = []; + let start = 0; + let end = 0; + const sums = { A1: 0, A2: 0, B1: 0, B2: 0 }; + const counts = { A1: 0, A2: 0, B1: 0, B2: 0 }; + for (const sample of sorted) { + const time = sample.time!; + // Include simultaneous acquisitions regardless of their journal arrival order. + while (end < sorted.length && sorted[end]!.time! <= time) { + const added = sorted[end++]!; + for (const input of CSV_INPUTS) { + if (added[input] !== null) { sums[input] += added[input]; counts[input]++; } + } + } + while (sorted[start]!.time! < time - 1) { + const removed = sorted[start++]!; + for (const input of CSV_INPUTS) { + if (removed[input] !== null) { sums[input] -= removed[input]; counts[input]--; } + } + } + const means = csvValues(null); + for (const input of CSV_INPUTS) { + means[input] = counts[input] ? sums[input] / counts[input] : null; + } + points.push({ + time, A1: sample.A1, A2: sample.A2, B1: sample.B1, B2: sample.B2, means, + }); + } + return points; + }); +} + +export class CsvModel { + readonly samples: CsvSample[] = []; + + append(records: readonly DiagnosticRecord[], cutoff = -Infinity): void { + for (const record of records) { + const sample = csvSample(record); + if (sample) this.samples.push(sample); + } + this.prune(cutoff); + if (this.samples.length > 10_000) this.samples.splice(0, this.samples.length - 10_000); + } + + prune(cutoff: number): boolean { + const length = this.samples.length; + let kept = 0; + for (const sample of this.samples) { + if ((sample.time ?? sample.receivedTime ?? -Infinity) >= cutoff - 1) this.samples[kept++] = sample; + } + this.samples.length = kept; + return kept !== length; + } + + clear(): void { this.samples.length = 0; } +} diff --git a/linkhub-ui/src/csv-panel.ts b/linkhub-ui/src/csv-panel.ts index 1533d31..0e4193f 100644 --- a/linkhub-ui/src/csv-panel.ts +++ b/linkhub-ui/src/csv-panel.ts @@ -1,10 +1,27 @@ import type { LinkHubApi } from "./api"; import type { CsvStatus } from "./types"; +import { CSV_INPUTS, CsvModel, csvValues } from "./csv-model"; +import { drawCsvChart } from "./csv-chart"; + +const WINDOW_SECONDS = 5 * 60; + +function cursorSequence(cursor: string): bigint { + if (!/^v1:\d+$/.test(cursor)) throw new Error(`Invalid journal cursor: ${cursor}`); + return BigInt(cursor.slice(3)); +} export class CsvPanel { private readonly controller = new AbortController(); private readonly state: HTMLElement; private readonly rows: HTMLElement; + private readonly canvas: HTMLCanvasElement; + private readonly timing: HTMLElement; + private readonly observer: ResizeObserver; + private readonly model = new CsvModel(); + private cursor = "v1:0"; + private runId: string | undefined; + private source: string | undefined; + private totalRows = 0; private timer: ReturnType | undefined; private received = false; private disposed = false; @@ -13,15 +30,23 @@ export class CsvPanel { constructor( private readonly button: HTMLButtonElement, private readonly root: HTMLElement, - private readonly api: Pick, + private readonly api: Pick, private readonly onError: (message: string) => void, ) { root.innerHTML = `

CSVs

+ +
`; this.state = this.element('[data-csv="state"]'); this.rows = this.element('[data-csv="rows"]'); + const canvas = root.querySelector('[data-csv="chart"]'); + if (!canvas) throw new Error("Missing CSV chart"); + this.canvas = canvas; + this.timing = this.element('[data-csv="timing"]'); + this.observer = new ResizeObserver(() => this.draw()); + this.observer.observe(this.canvas); button.hidden = true; root.hidden = true; button.addEventListener("click", this.toggle); @@ -32,23 +57,54 @@ export class CsvPanel { this.disposed = true; clearTimeout(this.timer); this.controller.abort(); + this.observer.disconnect(); this.button.removeEventListener("click", this.toggle); } private readonly toggle = (): void => { this.root.hidden = !this.root.hidden; this.button.setAttribute("aria-pressed", String(!this.root.hidden)); + if (!this.root.hidden) this.draw(); }; private async refresh(): Promise { try { + if (this.model.samples.some((sample) => (sample.time ?? sample.receivedTime ?? -Infinity) < this.cutoff())) { + this.draw(); + } const status = await this.api.csvStatus(this.controller.signal); if (this.disposed) return; - this.lastError = null; this.render(status); + if (status.available && status.latest) { + const service = await this.api.serviceStatus( + AbortSignal.any([this.controller.signal, AbortSignal.timeout(3_000)]), + ); + if (this.disposed) return; + const tail = cursorSequence(service.cursor); + if (this.runId !== service.run_id || this.source !== status.latest.source + || status.rows_received < this.totalRows || cursorSequence(this.cursor) > tail) { + this.model.clear(); + this.cursor = "v1:0"; + this.draw(); + } + this.runId = service.run_id; + this.source = status.latest.source; + this.totalRows = status.rows_received; + // Bound each poll to a fixed journal snapshot and a finite number of pages. + for (let page = 0; page < 32 && cursorSequence(this.cursor) < tail; page++) { + const batch = await this.api.csvSamples(this.cursor, this.source, 1_000, this.controller.signal); + if (this.disposed) return; + const next = cursorSequence(batch.next_cursor); + if (next <= cursorSequence(this.cursor)) throw new Error("Journal cursor did not advance"); + this.model.append(batch.records.filter((record) => cursorSequence(record.cursor) <= tail), this.cutoff()); + this.cursor = next > tail ? service.cursor : batch.next_cursor; + this.draw(); + } + } + this.lastError = null; } catch (error) { if (this.disposed) return; - const message = `CSV status unavailable: ${error instanceof Error ? error.message : String(error)}`; + const message = `CSV data unavailable: ${error instanceof Error ? error.message : String(error)}`; this.state.textContent = message; this.state.classList.toggle("error", true); if (message !== this.lastError) this.onError(message); @@ -59,11 +115,15 @@ export class CsvPanel { } private render(status: CsvStatus): void { - if (!status.available || !status.latest || status.recent.length === 0) { + if (!status.available || !status.latest) { this.button.hidden = true; this.root.hidden = true; this.button.setAttribute("aria-pressed", "false"); this.rows.replaceChildren(); + this.model.clear(); + this.cursor = "v1:0"; + this.source = undefined; + this.draw(); this.received = false; return; } @@ -75,23 +135,29 @@ export class CsvPanel { } const time = (ns: number) => new Date(ns / 1e6).toLocaleTimeString(); this.state.classList.toggle("error", false); - this.state.textContent = `${status.latest.source} | ${status.latest.filename} | last received ${time(status.latest.received_time_ns)}`; + this.state.textContent = `${status.latest.source} | ${status.latest.filename} | Rows received: ${status.rows_received} | last received ${time(status.latest.received_time_ns)}`; const table = document.createElement("table"); const head = document.createElement("thead"); const heading = document.createElement("tr"); - for (const name of ["File", "Received", ...status.columns]) { + for (const name of ["Field", "Latest value"]) { const cell = document.createElement("th"); cell.textContent = name; heading.append(cell); } head.append(heading); const body = document.createElement("tbody"); - for (const row of status.recent) { + const latest = csvValues(null); + for (const reading of [...status.recent, status.latest]) { + if (reading.source !== status.latest.source || reading.filename !== status.latest.filename) continue; + const values = csvValues(reading.values); + for (const input of CSV_INPUTS) { + if (values[input] !== null) latest[input] = values[input]; + } + } + const fields = CSV_INPUTS.filter((field) => latest[field] !== null); + for (const field of fields) { const tr = document.createElement("tr"); - for (const value of [ - row.filename, time(row.received_time_ns), - ...status.columns.map((field) => String(row.values[field])), - ]) { + for (const value of [field, String(latest[field])]) { const cell = document.createElement("td"); cell.textContent = value; tr.append(cell); @@ -102,6 +168,21 @@ export class CsvPanel { this.rows.replaceChildren(table); } + private draw(): void { + if (this.disposed) return; + const cutoff = this.cutoff(); + this.model.prune(cutoff); + const visible = this.model.samples.filter((sample) => (sample.time ?? sample.receivedTime ?? -Infinity) >= cutoff); + const unavailable = visible.filter((sample) => sample.time === null).length; + this.timing.textContent = !visible.length + ? "No CSV samples in the last 5 minutes" + : `${visible.length} retained samples in the last 5 minutes | Estimated acquisition timing; separate curves per file/clock epoch` + + (unavailable ? ` | Timing unavailable for ${unavailable} samples (not plotted or averaged)` : ""); + drawCsvChart(this.canvas, this.model, cutoff); + } + + private cutoff(): number { return Date.now() / 1_000 - WINDOW_SECONDS; } + private element(selector: string): HTMLElement { const element = this.root.querySelector(selector); if (!element) throw new Error(`Missing CSV panel element ${selector}`); diff --git a/linkhub-ui/src/demo-backend.ts b/linkhub-ui/src/demo-backend.ts index 1786f20..f9f9747 100644 --- a/linkhub-ui/src/demo-backend.ts +++ b/linkhub-ui/src/demo-backend.ts @@ -206,7 +206,7 @@ export class DemoBackend { const path = url.pathname; if (method === "GET" && path === "/v1/motor") return json({ available: false }); if (method === "GET" && path === "/v1/csv") { - return json({ available: false, columns: [], latest: null, recent: [] }); + return json({ available: false, columns: [], rows_received: 0, latest: null, recent: [] }); } if (path.startsWith("/v1/motor")) return json({ message: READ_ONLY }, 403); if (method === "GET" && path === "/v1/experiment") return json({ active: null }); diff --git a/linkhub-ui/src/styles.css b/linkhub-ui/src/styles.css index ec208d0..05b8854 100644 --- a/linkhub-ui/src/styles.css +++ b/linkhub-ui/src/styles.css @@ -526,7 +526,7 @@ h2 { position: relative; z-index: 3; flex: none; - max-height: 30vh; + max-height: 50vh; overflow: auto; padding: 10px; border-top: 1px solid #263249; @@ -539,6 +539,7 @@ h2 { .csv-head h2 { font-size: 13px; } .csv-head span { color: #aebdd2; } .csv-head .error { color: #f0c36b; } +.csv-chart { display: block; width: 100%; height: 240px; margin-top: 8px; } .csv-rows { overflow-x: auto; margin-top: 8px; } .csv-rows table { width: 100%; border-collapse: collapse; } .csv-rows th, .csv-rows td { diff --git a/linkhub-ui/src/types.ts b/linkhub-ui/src/types.ts index 4dafecb..0c1559d 100644 --- a/linkhub-ui/src/types.ts +++ b/linkhub-ui/src/types.ts @@ -15,12 +15,31 @@ export interface CsvReading { received_time_ns: number; sequence: number; source_sequence: number; + sample_time_ns: number | null; + time_quality: "estimated" | "clock_reset" | "out_of_order" | "unavailable"; + clock_epoch: number; values: Record; } +export interface DiagnosticRecord { + cursor: string; + ingest_time_ns?: number; + data: { + source: string; + event: string; + fields: JsonObject; + }; +} + +export interface DiagnosticBatch { + records: DiagnosticRecord[]; + next_cursor: string; +} + export interface CsvStatus { available: boolean; columns: string[]; + rows_received: number; latest: CsvReading | null; recent: CsvReading[]; } diff --git a/linkhub-ui/tests/api.test.ts b/linkhub-ui/tests/api.test.ts index 5df5249..d3b3b3d 100644 --- a/linkhub-ui/tests/api.test.ts +++ b/linkhub-ui/tests/api.test.ts @@ -46,8 +46,22 @@ describe("formatMavResult", () => { }); describe("typed wire contract", () => { + it("queries CSV journal samples with a source filter, cursor, page size, and cancellation", async () => { + const batch = { records: [], next_cursor: "v1:42" }; + const fetchMock = stubFetch(batch); + const controller = new AbortController(); + expect(await new LinkHubApi().csvSamples("v1:8", "bench lift", 1000, controller.signal)).toEqual(batch); + expect(fetchMock).toHaveBeenCalledWith( + "/v1/diagnostics/events?after=v1%3A8&source=bench+lift&event=csv.sample&limit=1000&last_ms=301000", + expect.objectContaining({ method: "GET", signal: expect.any(AbortSignal) }), + ); + const signal = fetchMock.mock.lastCall?.[1].signal as AbortSignal; + controller.abort(); + expect(signal.aborted).toBe(true); + }); + it("reads CSV rows independently and propagates caller cancellation", async () => { - const status = { available: false, columns: [], latest: null, recent: [] }; + const status = { available: false, columns: [], rows_received: 0, latest: null, recent: [] }; const fetchMock = stubFetch(status); const controller = new AbortController(); expect(await new LinkHubApi().csvStatus(controller.signal)).toEqual(status); diff --git a/linkhub-ui/tests/csv-panel.test.ts b/linkhub-ui/tests/csv-panel.test.ts index 9cac1bf..2e9d853 100644 --- a/linkhub-ui/tests/csv-panel.test.ts +++ b/linkhub-ui/tests/csv-panel.test.ts @@ -1,6 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { CsvPanel } from "../src/csv-panel"; -import type { CsvReading, CsvStatus } from "../src/types"; +import { CSV_INPUTS, CsvModel, csvSample, csvSeries, type CsvInput, type CsvSample } from "../src/csv-model"; +import type { CsvReading, CsvStatus, DiagnosticBatch, DiagnosticRecord } from "../src/types"; class Element extends EventTarget { innerHTML = ""; @@ -14,41 +15,94 @@ class Element extends EventTarget { setAttribute(name: string, value: string): void { this.attributes.set(name, value); } } -const empty: CsvStatus = { available: true, columns: [], latest: null, recent: [] }; +const empty: CsvStatus = { available: true, columns: [], rows_received: 0, latest: null, recent: [] }; const reading: CsvReading = { source: "bench.temperature", filename: "bench.csv", received_time_ns: 1_000_000_000, - sequence: 8, source_sequence: 42, values: { temperature_c: -12.5, sensor: "" }, + sample_time_ns: 1_000_000_000, time_quality: "estimated", clock_epoch: 0, + sequence: 8, source_sequence: 42, values: { input: "B2", raw: 40, gain: 32 }, }; const populated: CsvStatus = { - available: true, columns: ["temperature_c", "sensor"], latest: reading, recent: [reading], + available: true, columns: ["input", "raw", "gain"], rows_received: 10, + latest: reading, recent: [ + { ...reading, values: { input: "A1", raw: -12.5, gain: 64 } }, + { ...reading, values: { input: "A2", raw: -20, gain: 32 } }, + { ...reading, values: { input: "B1", raw: 30, gain: 64 } }, + reading, + ], }; -function setup(initial: CsvStatus = empty) { +function setup(initial: CsvStatus = empty, canvasWidth = 800) { const state = new Element(); const rows = new Element(); + const timing = new Element(); + const context = { + strokeStyle: "", lineWidth: 1, + setTransform: vi.fn(), clearRect: vi.fn(), fillText: vi.fn(), setLineDash: vi.fn(), + beginPath: vi.fn(), moveTo: vi.fn(), lineTo: vi.fn(), stroke: vi.fn(), fillRect: vi.fn(), + measureText: vi.fn((text: string) => ({ width: text.length * 10 })), + }; + const canvas = Object.assign(new Element(), { clientWidth: canvasWidth, getContext: () => context }); + const elements = new Map([ + ['[data-csv="state"]', state], ['[data-csv="rows"]', rows], + ['[data-csv="chart"]', canvas], ['[data-csv="timing"]', timing], + ]); const root = Object.assign(new Element(), { - querySelector: (selector: string) => selector === '[data-csv="state"]' ? state : rows, + querySelector: (selector: string) => elements.get(selector), }); const button = new Element(); vi.stubGlobal("document", { createElement: (tag: string) => tag === "section" ? root : tag === "button" ? button : new Element(), }); - const api = { csvStatus: vi.fn(async (_signal?: AbortSignal) => initial) }; + vi.stubGlobal("window", { devicePixelRatio: 2 }); + vi.stubGlobal("ResizeObserver", class { + observe = vi.fn(); + disconnect = vi.fn(); + }); + const api = { + csvStatus: vi.fn(async (_signal?: AbortSignal) => initial), + serviceStatus: vi.fn(async (_signal?: AbortSignal) => ({ + service: "linkhub", api_version: 1, run_id: "run-1", cursor: "v1:0", + })), + csvSamples: vi.fn(async (_after: string, _source: string, _limit?: number, _signal?: AbortSignal): Promise => + ({ records: [], next_cursor: "v1:0" })), + }; const onError = vi.fn(); const panel = new CsvPanel( document.createElement("button"), document.createElement("section"), api, onError, ); - return { panel, api, onError, root, button, state, rows }; + return { panel, api, onError, root, button, state, rows, timing, context }; } -beforeEach(() => vi.useFakeTimers()); +beforeEach(() => { + vi.useFakeTimers(); + vi.setSystemTime(0); +}); afterEach(() => { vi.useRealTimers(); vi.unstubAllGlobals(); }); describe("CSV pane", () => { - it("appears on received data, preserves configured field order and renders text safely", async () => { + it("plots only the last five minutes and ages out samples without new uploads", async () => { + vi.setSystemTime(600_000); + const { panel, api, timing, context, state } = setup(populated); + api.serviceStatus.mockResolvedValue({ + service: "linkhub", api_version: 1, run_id: "run-1", cursor: "v1:3", + }); + api.csvSamples.mockResolvedValueOnce({ + records: [event(1, 100), event(2, 299.5), event(3, 300)], next_cursor: "v1:3", + }); + await vi.advanceTimersByTimeAsync(0); + expect(timing.textContent).toContain("1 retained samples in the last 5 minutes"); + expect(context.fillRect).toHaveBeenCalledTimes(2); + await vi.advanceTimersByTimeAsync(1000); + expect(timing.textContent).toBe("No CSV samples in the last 5 minutes"); + expect(api.csvSamples).toHaveBeenCalledTimes(1); + expect(state.textContent).toContain("Rows received: 10"); + panel.dispose(); + }); + + it("appears on received data and combines alternating rows into four latest input values", async () => { const { panel, root, button, rows, state, api } = setup(); await vi.advanceTimersByTimeAsync(0); expect(button.hidden).toBe(true); @@ -60,12 +114,11 @@ describe("CSV pane", () => { expect(button.attributes.get("aria-pressed")).toBe("true"); const table = rows.children[0]!; expect(table.children[0]!.children[0]!.children.map((cell) => cell.textContent)) - .toEqual(["File", "Received", "temperature_c", "sensor"]); - const cells = table.children[1]!.children[0]!.children; - expect(cells[0]!.textContent).toBe("bench.csv"); - expect(cells[2]!.textContent).toBe("-12.5"); - expect(cells[3]!.textContent).toBe(""); - expect(cells[3]!.innerHTML).toBe(""); + .toEqual(["Field", "Latest value"]); + expect(table.children[1]!.children.map((row) => row.children.map((cell) => cell.textContent))) + .toEqual([["A1", "-12.5"], ["A2", "-20"], ["B1", "30"], ["B2", "40"]]); + expect(table.children[1]!.children[0]!.children[1]!.innerHTML).toBe(""); + expect(state.textContent).toContain("Rows received: 10"); expect(state.textContent).toContain("last received"); button.dispatchEvent(new Event("click")); await vi.advanceTimersByTimeAsync(1000); @@ -74,13 +127,28 @@ describe("CSV pane", () => { panel.dispose(); }); + it("updates latest values and total count rather than showing the recent-row history", async () => { + const { panel, api, rows, state } = setup(populated); + await vi.advanceTimersByTimeAsync(0); + api.csvStatus.mockResolvedValue({ + ...populated, rows_received: 300, + latest: { ...reading, values: { input: "B2", raw: 12, gain: 32 } }, + }); + await vi.advanceTimersByTimeAsync(1000); + const fields = rows.children[0]!.children[1]!.children; + expect(fields.map((row) => row.children.map((cell) => cell.textContent))) + .toEqual([["A1", "-12.5"], ["A2", "-20"], ["B1", "30"], ["B2", "12"]]); + expect(state.textContent).toContain("Rows received: 300"); + panel.dispose(); + }); + it("retains old rows with an explicit error on fetch failure and recovers", async () => { const { panel, rows, state, api, onError } = setup(populated); await vi.advanceTimersByTimeAsync(0); const table = rows.children[0]; api.csvStatus.mockRejectedValue(new Error("network down")); await vi.advanceTimersByTimeAsync(2000); - expect(state.textContent).toBe("CSV status unavailable: network down"); + expect(state.textContent).toBe("CSV data unavailable: network down"); expect(rows.children[0]).toBe(table); expect(onError).toHaveBeenCalledTimes(1); api.csvStatus.mockResolvedValue(populated); @@ -109,4 +177,304 @@ describe("CSV pane", () => { expect(root.hidden).toBe(true); expect(button.hidden).toBe(true); }); + + it("consumes every journal page including empty advancing pages and redraws live before later pages finish", async () => { + const { panel, api, timing, context } = setup(populated); + api.serviceStatus.mockResolvedValue({ + service: "linkhub", api_version: 1, run_id: "run-1", cursor: "v1:12", + }); + let finish!: (batch: DiagnosticBatch) => void; + api.csvSamples + .mockResolvedValueOnce({ records: [event(1, 0), event(2, 0.1)], next_cursor: "v1:2" }) + .mockResolvedValueOnce({ records: [], next_cursor: "v1:7" }) + .mockImplementationOnce(() => new Promise((resolve) => { finish = resolve; })); + await vi.advanceTimersByTimeAsync(0); + expect(timing.textContent).toContain("2 retained samples"); + expect(context.lineTo).toHaveBeenCalled(); + expect(api.csvSamples.mock.calls.map(([after]) => after)).toEqual(["v1:0", "v1:2", "v1:7"]); + finish({ records: Array.from({ length: 5 }, (_, i) => event(i + 8, i / 10 + 1)), next_cursor: "v1:12" }); + await vi.advanceTimersByTimeAsync(0); + expect(timing.textContent).toContain("7 retained samples"); + await vi.advanceTimersByTimeAsync(1000); + expect(api.csvSamples).toHaveBeenCalledTimes(3); + expect(api.csvSamples).toHaveBeenCalledWith("v1:0", reading.source, 1000, expect.any(AbortSignal)); + panel.dispose(); + }); + + it("bounds reads to a snapshot and retains new arrivals for the next poll", async () => { + const { panel, api, timing } = setup(populated); + api.serviceStatus.mockResolvedValue({ + service: "linkhub", api_version: 1, run_id: "run-1", cursor: "v1:2", + }); + api.csvSamples.mockResolvedValueOnce({ + records: [event(1, 0), event(2, 0.1), event(3, 0.2)], next_cursor: "v1:3", + }); + await vi.advanceTimersByTimeAsync(0); + expect(timing.textContent).toContain("2 retained samples"); + api.serviceStatus.mockResolvedValue({ + service: "linkhub", api_version: 1, run_id: "run-1", cursor: "v1:3", + }); + api.csvSamples.mockResolvedValueOnce({ records: [event(3, 0.2)], next_cursor: "v1:3" }); + await vi.advanceTimersByTimeAsync(1000); + expect(api.csvSamples.mock.lastCall?.[0]).toBe("v1:2"); + expect(timing.textContent).toContain("3 retained samples"); + panel.dispose(); + }); + + it("bounds empty advancing backlog work and resumes the cursor next poll", async () => { + const { panel, api } = setup(populated); + api.serviceStatus.mockResolvedValue({ + service: "linkhub", api_version: 1, run_id: "run-1", cursor: "v1:40", + }); + api.csvSamples.mockImplementation(async (after) => ({ + records: [], next_cursor: `v1:${Number(after.slice(3)) + 1}`, + })); + await vi.advanceTimersByTimeAsync(0); + expect(api.csvSamples).toHaveBeenCalledTimes(32); + await vi.advanceTimersByTimeAsync(1000); + expect(api.csvSamples).toHaveBeenCalledTimes(40); + expect(api.csvSamples.mock.calls[32]?.[0]).toBe("v1:32"); + panel.dispose(); + }); + + it("reports unavailable legacy timing, preserves graph on journal errors, and resets on restart", async () => { + const { panel, api, timing, state, context } = setup(populated); + api.serviceStatus.mockResolvedValue({ + service: "linkhub", api_version: 1, run_id: "run-1", cursor: "v1:2", + }); + api.csvSamples.mockResolvedValueOnce({ + records: [event(1, 0), { ...event(2, 1), data: { + source: reading.source, event: "csv.sample", + fields: { filename: "bench.csv", values: { input: "A1", raw: 999 }, device_time: "12:00:00" }, + } }], next_cursor: "v1:2", + }); + await vi.advanceTimersByTimeAsync(0); + expect(timing.textContent).toContain("Timing unavailable for 1 samples"); + const draws = context.clearRect.mock.calls.length; + api.serviceStatus.mockResolvedValue({ + service: "linkhub", api_version: 1, run_id: "run-1", cursor: "v1:3", + }); + api.csvSamples.mockRejectedValueOnce(new Error("journal down")); + await vi.advanceTimersByTimeAsync(1000); + expect(state.textContent).toContain("CSV data unavailable: journal down"); + expect(context.clearRect).toHaveBeenCalledTimes(draws); + api.serviceStatus.mockResolvedValue({ + service: "linkhub", api_version: 1, run_id: "run-2", cursor: "v1:1", + }); + api.csvSamples.mockResolvedValueOnce({ records: [event(1, 2)], next_cursor: "v1:1" }); + await vi.advanceTimersByTimeAsync(1000); + expect(api.csvSamples.mock.lastCall?.[0]).toBe("v1:0"); + expect(timing.textContent).toContain("1 retained samples"); + expect(timing.textContent).not.toContain("Timing unavailable"); + panel.dispose(); + }); + + it("plots four raw input traces and means while retaining filename, receive time, and row count", async () => { + const { panel, api, context, rows, state } = setup({ + ...populated, columns: ["rownum", "device_time", "input", "raw", "gain", "temperature"], + latest: { ...reading, values: { input: "B2", raw: 4, gain: 32, temperature: 999999 } }, + }); + api.serviceStatus.mockResolvedValue({ + service: "linkhub", api_version: 1, run_id: "run-1", cursor: "v1:4", + }); + api.csvSamples.mockResolvedValueOnce({ + records: CSV_INPUTS.map((input, index) => + event(index + 1, 1, { values: { input, raw: index + 1, temperature: 999999 } })), + next_cursor: "v1:4", + }); + await vi.advanceTimersByTimeAsync(0); + const labels = context.fillText.mock.calls.map(([label]) => label); + expect(labels).toEqual(expect.arrayContaining([ + ...CSV_INPUTS.flatMap((input) => [`${input} raw`, `${input} 1 s mean`]), + "Estimated acquisition elapsed (s) · raw ADC counts", + ])); + expect(labels).not.toContain("temperature"); + expect(rows.children[0]!.children[1]!.children.map((row) => row.children[0]!.textContent)) + .toEqual(["A1", "A2", "B1", "B2"]); + expect(state.textContent).toContain("bench.csv"); + expect(state.textContent).toContain("last received"); + expect(state.textContent).toContain("Rows received: 10"); + panel.dispose(); + }); + + it.each([320, 850])("lays out measured legend labels without overlap at %i px", async (width) => { + const { panel, api, context } = setup(populated, width); + api.serviceStatus.mockResolvedValue({ + service: "linkhub", api_version: 1, run_id: "run-1", cursor: "v1:1", + }); + api.csvSamples.mockResolvedValueOnce({ records: [event(1, 0)], next_cursor: "v1:1" }); + await vi.advanceTimersByTimeAsync(0); + const names = CSV_INPUTS.flatMap((input) => [`${input} raw`, `${input} 1 s mean`]); + const labels = context.fillText.mock.calls.filter(([text]) => names.includes(text)).slice(-8); + expect(labels).toHaveLength(8); + for (const [index, [text, x, y]] of labels.entries()) { + const labelWidth = context.measureText(text).width; + expect(x).toBeGreaterThanOrEqual(77); + expect(x + labelWidth).toBeLessThanOrEqual(width - 10); + const previous = labels[index - 1]; + if (previous && previous[2] === y) { + expect(x).toBeGreaterThanOrEqual(previous[1] + context.measureText(previous[0]).width + 18); + } + } + if (width === 320) expect(labels[7]![2]).toBeGreaterThan(labels[0]![2]); + panel.dispose(); + }); + + it("connects each raw input across rows acquired for the other three inputs", async () => { + const { panel, api, context } = setup(populated); + let segments = 0; + const rawStrokes: number[] = []; + context.beginPath.mockImplementation(() => { segments = 0; }); + context.lineTo.mockImplementation(() => { segments++; }); + context.stroke.mockImplementation(() => { + if (context.lineWidth === 1 && ["#78b7ff", "#f0c36b", "#71ddb4", "#c792ea"].includes(context.strokeStyle)) { + rawStrokes.push(segments); + } + }); + api.serviceStatus.mockResolvedValue({ + service: "linkhub", api_version: 1, run_id: "run-1", cursor: "v1:8", + }); + api.csvSamples.mockResolvedValueOnce({ + records: Array.from({ length: 8 }, (_, index) => + event(index + 1, index / 10, { values: { input: CSV_INPUTS[index % 4], raw: index } })), + next_cursor: "v1:8", + }); + await vi.advanceTimersByTimeAsync(0); + expect(rawStrokes.slice(-4)).toEqual([1, 1, 1, 1]); + panel.dispose(); + }); + + it("omits missing sensors and all unrelated mapped fields from the latest table", async () => { + const { panel, rows } = setup({ + ...populated, columns: ["device_time", "input", "raw", "gain"], + latest: { ...reading, values: { input: "A1", raw: 3, gain: 64 } }, + recent: [ + { ...reading, filename: "old.csv", values: { input: "A2", raw: 99 } }, + { ...reading, values: { input: "B1", raw: "" } }, + { ...reading, values: { input: "temperature", raw: 1000 } }, + ], + }); + await vi.advanceTimersByTimeAsync(0); + expect(rows.children[0]!.children[1]!.children.map((row) => row.children.map((cell) => cell.textContent))) + .toEqual([["A1", "3"]]); + panel.dispose(); + }); + + it("deduplicates journal errors and resumes without dropping previously plotted batches", async () => { + const { panel, api, timing, onError } = setup(populated); + api.serviceStatus.mockResolvedValue({ + service: "linkhub", api_version: 1, run_id: "run-1", cursor: "v1:2", + }); + api.csvSamples + .mockResolvedValueOnce({ records: [event(1, 0)], next_cursor: "v1:1" }) + .mockRejectedValue(new Error("journal down")); + await vi.advanceTimersByTimeAsync(1000); + expect(onError).toHaveBeenCalledTimes(1); + expect(timing.textContent).toContain("1 retained samples"); + api.csvSamples.mockResolvedValueOnce({ records: [event(2, 0.5)], next_cursor: "v1:2" }); + await vi.advanceTimersByTimeAsync(1000); + expect(api.csvSamples.mock.lastCall?.[0]).toBe("v1:1"); + expect(timing.textContent).toContain("2 retained samples"); + panel.dispose(); + }); + + it("does not loop on a stalled cursor and cancels pending journal reads on disposal", async () => { + const { panel, api, state, timing } = setup(populated); + api.serviceStatus.mockResolvedValue({ + service: "linkhub", api_version: 1, run_id: "run-1", cursor: "v1:1", + }); + await vi.advanceTimersByTimeAsync(0); + expect(api.csvSamples).toHaveBeenCalledTimes(1); + expect(state.textContent).toContain("Journal cursor did not advance"); + let finish!: (batch: DiagnosticBatch) => void; + api.csvSamples.mockImplementationOnce(() => new Promise((resolve) => { finish = resolve; })); + await vi.advanceTimersByTimeAsync(1000); + const signal = api.csvSamples.mock.lastCall?.[3]; + panel.dispose(); + expect(signal?.aborted).toBe(true); + finish({ records: [event(1, 0)], next_cursor: "v1:1" }); + await vi.advanceTimersByTimeAsync(1000); + expect(timing.textContent).not.toContain("1 retained samples"); + expect(api.csvSamples).toHaveBeenCalledTimes(2); + }); +}); + +function event(sequence: number, time: number, overrides: Record = {}): DiagnosticRecord { + return { + cursor: `v1:${sequence}`, ingest_time_ns: time * 1e9, data: { + source: reading.source, event: "csv.sample", fields: { + filename: "bench.csv", sample_time_ns: time * 1e9, clock_epoch: 0, + time_quality: "estimated", values: { input: "A1", raw: sequence, gain: 64 }, + ...overrides, + }, + }, + }; +} + +function sample(time: number, raw: number | null, input: CsvInput = "A1"): CsvSample { + return { + filename: "bench.csv", epoch: 0, time, reset: false, + A1: null, A2: null, B1: null, B2: null, [input]: raw, + }; +} + +describe("CSV one-second averaging", () => { + it("demultiplexes labeled signed raw counts without copying values into other inputs", () => { + const model = new CsvModel(); + const raw = [-8388608, 0, 8388607, -42]; + model.append(CSV_INPUTS.map((input, index) => + event(index + 1, index / 10, { values: { input, raw: raw[index], gain: index % 2 ? 32 : 64 } }))); + expect(model.samples.map((sample) => CSV_INPUTS.map((input) => sample[input]))).toEqual([ + [-8388608, null, null, null], [null, 0, null, null], + [null, null, 8388607, null], [null, null, null, -42], + ]); + expect(csvSeries(model.samples)[0]!.at(-1)!.means) + .toEqual({ A1: -8388608, A2: 0, B1: 8388607, B2: -42 }); + }); + + it("uses irregular acquisition spacing, inclusive window edges, and independent alternating inputs", () => { + const points = csvSeries([ + sample(0, 2), sample(0.2, 12, "B1"), sample(0.2, 4), + sample(1, 9), sample(1, 18, "B1"), sample(1.01, 11), + ])[0]!; + expect(points.map((point) => point.means.A1)).toEqual([2, 3, 3, 5, 5, 8]); + expect(points.map((point) => point.means.B1)).toEqual([null, 12, 12, 15, 15, 15]); + expect(points.map((point) => point.means.A2)).toEqual([null, null, null, null, null, null]); + expect(points.map((point) => point.means.B2)).toEqual([null, null, null, null, null, null]); + }); + + it("sorts out-of-order rows in one epoch and includes equal timestamps", () => { + const points = csvSeries([sample(0.5, 8), sample(0, 2), sample(0.5, 4)])[0]!; + expect(points.map((point) => [point.time, point.means.A1])).toEqual([[0, 2], [0.5, 14 / 3], [0.5, 14 / 3]]); + }); + + it("neither connects nor averages across filenames, clock resets or unavailable timing", () => { + const groups = csvSeries([ + sample(0, 100), { ...sample(0.1, 2), epoch: 1, reset: true }, + sample(0.2, 3), { ...sample(0.3, 4), filename: "other.csv" }, + { ...sample(0.4, 99), time: null }, { ...sample(0.5, 5), filename: "other.csv" }, + ]); + expect(groups).toHaveLength(5); + expect(groups.map((group) => group[0]!.means.A1)).toEqual([100, 2, 3, 4, 5]); + }); + + it("requires explicit valid acquisition metadata instead of receipt or raw device time", () => { + expect(csvSample(event(1, 0, { sample_time_ns: null }))?.time).toBeNull(); + expect(csvSample(event(1, 0, { time_quality: "unavailable" }))?.time).toBeNull(); + expect(csvSample(event(1, 0, { clock_epoch: null }))?.time).toBeNull(); + expect(csvSample(event(1, 0, { values: { input: "A1", raw: NaN } }))) + .toMatchObject({ A1: null, A2: null, B1: null, B2: null }); + expect(csvSample(event(1, 0, { values: { input: "B2", raw: "10" } }))?.B2).toBeNull(); + expect(csvSample(event(1, 0, { values: { input: "A", raw: 10 } }))) + .toMatchObject({ A1: null, A2: null, B1: null, B2: null }); + }); + + it("retains at most 10,000 samples without relying on the five-row status preview", () => { + const model = new CsvModel(); + model.append(Array.from({ length: 10_005 }, (_, i) => event(i + 1, i / 10))); + expect(model.samples).toHaveLength(10_000); + expect(model.samples[0]?.A1).toBe(6); + model.clear(); + expect(model.samples).toEqual([]); + }); }); diff --git a/linkhub-ui/tests/demo-backend.test.ts b/linkhub-ui/tests/demo-backend.test.ts index bc21af6..bd3648b 100644 --- a/linkhub-ui/tests/demo-backend.test.ts +++ b/linkhub-ui/tests/demo-backend.test.ts @@ -33,7 +33,7 @@ function fixture() { describe("recorded SITL demo", () => { it("reports no CSV feed instead of inventing replay measurements", async () => { expect(await fixture().api.csvStatus()).toEqual({ - available: false, columns: [], latest: null, recent: [], + available: false, columns: [], rows_received: 0, latest: null, recent: [], }); }); diff --git a/linkhub/README.md b/linkhub/README.md index 54870a9..fd6d456 100644 --- a/linkhub/README.md +++ b/linkhub/README.md @@ -285,6 +285,29 @@ See [motor lease semantics](../design/linkhub.md#bluetooth-bench-motor). ### Generic CSV ingestion +On Windows, [run_linkhub_esp.cmd](../run_linkhub_esp.cmd) launches the ESP CSV +receiver alongside a configured MAVLink connection. First copy +`loadcell/launch_config.cmd.example` to the ignored `loadcell/launch_config.cmd` +and edit its addresses, or set `LOADCELL_DEVICE_URL` and `LINKHUB_CONNECTION` +in the launching environment: + +```powershell +.\run_linkhub_esp.cmd --configure-firewall +``` + +It detects this PC's IPv4 address on the route to the ESP32, sets and verifies +the ESP32 CSV destination, selects and verifies four-input capture +(A1, A2, B1, B2), and starts the existing UI launcher on HTTP port +8999 with [csv-map.json](csv-map.json) enabled. `--configure-firewall` requests +administrator approval for the existing Private LAN firewall rule; omit it +once that rule is configured. `--build` rebuilds through the normal setup. +An already-correct destination is not rotated or flushed, so pending samples +do not prevent startup while the receiver is offline. Changing to a different +destination still requires the old receiver to accept pending data. +The CSV destination and four-input mode remain configured after exit, including +if LinkHub startup fails; uploads resume when the launcher runs again. +Servo motion and the sample interval are not changed. + Start LinkHub with a runtime mapping, adding these arguments to your usual `serve` command: @@ -292,8 +315,9 @@ Start LinkHub with a runtime mapping, adding these arguments to your usual --listen 0.0.0.0 --csv-map .\linkhub\csv-map.json ``` -The supplied [example mapping](csv-map.json) describes an ESP32's ordered -columns, but the receiver contains no sensor-specific schema: +The supplied [example mapping](csv-map.json) describes the +[load-cell firmware's two/four-input raw readings, input labels, gains, and timestamps](../loadcell/README.md#configuration-and-csv). +The receiver contains no sensor-specific calibration or schema: ```json { @@ -314,6 +338,11 @@ need not be the first column. Change this JSON and restart LinkHub to change source, names, types, or columns without rebuilding Rust. Invalid mappings prevent startup. Standard CSV quoting, escaped quotes, and CRLF are supported. One mapping configures the endpoint per service run. +The optional `time_column` names a mapped string column in +`HH:MM:SS[.fraction]` format (up to nine fractional digits). The ESP32 example +uses `"time_column": "_time"`; malformed clock values reject the batch. +See [CSV timing semantics](../design/linkhub.md#configured-csv-feeds) for +per-batch acquisition-time estimation and clock-discontinuity handling. On the ESP32 servo interface (port **88**), set **CSVStorageURL** to `http://:8999/v1/csv`. The firmware appends `?filename=...` @@ -331,13 +360,18 @@ curl.exe "http://127.0.0.1:8999/v1/csv" ``` `GET /v1/csv` returns `available`, ordered output-field names in `columns`, -`latest`, and `recent` (at most five newly accepted rows, oldest first). +`rows_received` (newly accepted rows since service startup), `latest`, and +`recent` (at most five newly accepted rows, oldest first). The count continues +across filenames, excludes headers, rejected rows, and duplicate retries, and +resets to zero on service restart. Before the first sample, `latest` is `null` and `recent` is empty, never fabricated zero readings. An accepted reading includes `source`, `filename`, `received_time_ns` (host ingestion time), `sequence` (journal sequence), `source_sequence` (device row counter), and a `values` object with -the configured output fields. Values retain device units and calibration; -LinkHub does not infer Newtons or reinterpret the device's time-of-day string. +the configured output fields. `sample_time_ns` is the estimated acquisition +time, or null when unavailable; `time_quality` and `clock_epoch` identify its +quality and discontinuities. Values retain device units and calibration; +LinkHub does not infer Newtons or change the raw device time string. The host timestamp permits clients to detect stale readings. POSTs are limited to 64 KiB. A matching header may appear alone or with rows; diff --git a/linkhub/csv-map.json b/linkhub/csv-map.json index cfe2270..0aaba2f 100644 --- a/linkhub/csv-map.json +++ b/linkhub/csv-map.json @@ -1,13 +1,13 @@ { "source": "esp32.strain", "sequence_column": "_rownum", + "time_column": "_time", "columns": [ { "column": "_rownum", "field": "rownum", "type": "u64" }, { "column": "_time", "field": "device_time", "type": "string" }, - { "column": "rpm", "field": "rpm", "type": "number" }, - { "column": "flap_angle", "field": "flap_angle", "type": "number" }, - { "column": "pitch_angle", "field": "pitch_angle", "type": "number" }, - { "column": "lift", "field": "lift", "type": "number" }, - { "column": "drag", "field": "drag", "type": "number" } + { "column": "_time_unix_us", "field": "device_time_unix_us", "type": "u64" }, + { "column": "input", "field": "input", "type": "string" }, + { "column": "raw", "field": "raw", "type": "number" }, + { "column": "gain", "field": "gain", "type": "u64" } ] } diff --git a/linkhub/src/csv_ingest.rs b/linkhub/src/csv_ingest.rs index 6eca6fa..5231481 100644 --- a/linkhub/src/csv_ingest.rs +++ b/linkhub/src/csv_ingest.rs @@ -1,4 +1,4 @@ -use std::collections::{HashSet, VecDeque}; +use std::collections::{HashMap, HashSet, VecDeque}; use serde::{Deserialize, Serialize}; use serde_json::{Map, Value, json}; @@ -11,6 +11,8 @@ use crate::{ pub(crate) const MAX_CSV_BYTES: usize = 64 * 1024; const RECENT_ROWS: usize = 5; +const SECOND_NS: u64 = 1_000_000_000; +const DAY_NS: i128 = 86_400 * SECOND_NS as i128; #[derive(Debug, thiserror::Error)] pub enum CsvError { @@ -28,6 +30,7 @@ pub struct CsvMapping(MappingFile); struct MappingFile { source: String, sequence_column: String, + time_column: Option, columns: Vec, } @@ -90,6 +93,17 @@ impl CsvMapping { "sequence_column must name a mapped u64 column".to_owned(), )); } + if let Some(name) = &mapping.time_column + && !mapping + .columns + .iter() + .any(|column| column.column == *name && column.kind == ColumnType::String) + { + return Err(CsvError::Invalid( + "time_column must name a mapped string column containing HH:MM:SS[.fraction]" + .to_owned(), + )); + } Ok(Self(mapping)) } @@ -120,6 +134,7 @@ impl CsvMapping { } let mut values = Map::new(); let mut sequence = None; + let mut time_of_day_ns = None; for (value, column) in record.iter().zip(&self.0.columns) { let error = || { invalid(format!( @@ -127,6 +142,14 @@ impl CsvMapping { column.kind, column.column )) }; + if self.0.time_column.as_deref() == Some(column.column.as_str()) { + time_of_day_ns = Some(parse_time_of_day(value).ok_or_else(|| { + invalid(format!( + "invalid HH:MM:SS[.fraction] value for {}", + column.column + )) + })?); + } let value = match column.kind { ColumnType::U64 => { let number = value.trim().parse::().map_err(|_| error())?; @@ -148,6 +171,7 @@ impl CsvMapping { } samples.push(ParsedSample { sequence: sequence.expect("validated mapping has a u64 sequence column"), + time_of_day_ns, values, }); } @@ -160,6 +184,7 @@ impl CsvMapping { struct ParsedSample { sequence: u64, + time_of_day_ns: Option, values: Map, } @@ -168,6 +193,9 @@ pub(crate) struct CsvReading { source: String, filename: String, received_time_ns: u64, + sample_time_ns: Option, + time_quality: CsvTimeQuality, + clock_epoch: u64, sequence: u64, source_sequence: u64, values: Map, @@ -183,7 +211,131 @@ pub(crate) struct CsvBatchResult { pub(crate) struct CsvStore { journal: JournalHandle, mapping: CsvMapping, - readings: Mutex>, + state: Mutex, +} + +#[derive(Default)] +struct CsvState { + rows_received: u64, + readings: VecDeque, + clocks: HashMap, +} + +#[derive(Clone, Copy, Debug, PartialEq, Serialize)] +#[serde(rename_all = "snake_case")] +enum CsvTimeQuality { + Estimated, + ClockReset, + OutOfOrder, + Unavailable, +} + +struct CsvTiming { + sample_time_ns: Option, + quality: CsvTimeQuality, + epoch: u64, +} + +#[derive(Clone)] +struct CsvClock { + sequence: u64, + time_of_day_ns: u64, + epoch: u64, + reset_sequence: Option, +} + +fn parse_time_of_day(value: &str) -> Option { + let (whole, fraction) = value.trim().split_once('.').unwrap_or((value.trim(), "")); + let mut parts = whole.split(':'); + let mut component = || { + let part = parts.next()?; + (part.len() == 2 && part.bytes().all(|byte| byte.is_ascii_digit())) + .then(|| part.parse::().ok()) + .flatten() + }; + let hour = component()?; + let minute = component()?; + let second = component()?; + if parts.next().is_some() + || hour >= 24 + || minute >= 60 + || second >= 60 + || fraction.len() > 9 + || !fraction.bytes().all(|byte| byte.is_ascii_digit()) + || (value.trim().contains('.') && fraction.is_empty()) + { + return None; + } + let fractional_ns = if fraction.is_empty() { + 0 + } else { + fraction.parse::().ok()? * 10_u64.pow(9 - fraction.len() as u32) + }; + Some((hour * 3600 + minute * 60 + second) * SECOND_NS + fractional_ns) +} + +fn clock_delta(current: u64, previous: u64) -> i128 { + (i128::from(current) - i128::from(previous) + DAY_NS / 2).rem_euclid(DAY_NS) - DAY_NS / 2 +} + +impl CsvClock { + fn estimate( + previous: Option<&Self>, + sequence: u64, + time_of_day_ns: u64, + batch_anchor_ns: u64, + received_time_ns: u64, + ) -> Result<(CsvTiming, Self), CsvError> { + let delta = previous + .map(|clock| clock_delta(time_of_day_ns, clock.time_of_day_ns)) + .unwrap_or(0); + let sequence_restarted = + previous.is_some_and(|clock| sequence < clock.sequence) && delta >= 0; + let out_of_order = + previous.is_some_and(|clock| sequence < clock.sequence) && !sequence_restarted; + let age_ns = clock_delta(batch_anchor_ns, time_of_day_ns); + let reset = !out_of_order + && (sequence_restarted || age_ns < 0 || (previous.is_some() && delta < 0)); + let mut clock = match previous { + Some(clock) if !reset => clock.clone(), + _ => Self { + sequence, + time_of_day_ns, + epoch: previous.map_or(1, |clock| clock.epoch + 1), + reset_sequence: reset.then_some(sequence), + }, + }; + let quality = if out_of_order { + CsvTimeQuality::OutOfOrder + } else if reset { + CsvTimeQuality::ClockReset + } else { + CsvTimeQuality::Estimated + }; + let ambiguous = out_of_order && clock.reset_sequence.is_some_and(|start| sequence < start); + // Each periodic batch gets a fresh receipt anchor; the ESP's absolute clock is not trusted. + let sample_time_ns = if ambiguous || age_ns < 0 { + None + } else { + Some( + u64::try_from(i128::from(received_time_ns) - age_ns).map_err(|_| { + CsvError::Invalid("estimated CSV sample timestamp is out of range".to_owned()) + })?, + ) + }; + if !out_of_order { + clock.sequence = sequence; + clock.time_of_day_ns = time_of_day_ns; + } + Ok(( + CsvTiming { + sample_time_ns, + quality, + epoch: clock.epoch, + }, + clock, + )) + } } impl CsvStore { @@ -191,12 +343,12 @@ impl CsvStore { Self { journal, mapping, - readings: Mutex::new(VecDeque::new()), + state: Mutex::new(CsvState::default()), } } pub(crate) async fn status(&self) -> Value { - let readings = self.readings.lock().await; + let state = self.state.lock().await; let columns: Vec<_> = self .mapping .0 @@ -207,8 +359,9 @@ impl CsvStore { json!({ "available": true, "columns": columns, - "latest": readings.back(), - "recent": &*readings, + "rows_received": state.rows_received, + "latest": state.readings.back(), + "recent": &state.readings, }) } @@ -229,17 +382,41 @@ impl CsvStore { )); } let samples = self.mapping.parse(body)?; - let mut readings = self.readings.lock().await; + let received_time_ns = wall_time_ns(); + let batch_anchor_ns = samples.last().and_then(|sample| sample.time_of_day_ns); + let mut state = self.state.lock().await; let mut result = CsvBatchResult { accepted: 0, duplicates: 0, cursor: format_cursor(self.journal.tail()), }; for sample in samples { - let received_time_ns = wall_time_ns(); + let (timing, clock) = match (sample.time_of_day_ns, batch_anchor_ns) { + (Some(time), Some(anchor)) => { + let (timing, clock) = CsvClock::estimate( + state.clocks.get(filename), + sample.sequence, + time, + anchor, + received_time_ns, + )?; + (timing, Some(clock)) + } + _ => ( + CsvTiming { + sample_time_ns: None, + quality: CsvTimeQuality::Unavailable, + epoch: 0, + }, + None, + ), + }; let mut fields = Map::new(); fields.insert("filename".to_owned(), Value::String(filename.to_owned())); fields.insert("values".to_owned(), Value::Object(sample.values.clone())); + fields.insert("sample_time_ns".to_owned(), json!(timing.sample_time_ns)); + fields.insert("time_quality".to_owned(), json!(timing.quality)); + fields.insert("clock_epoch".to_owned(), json!(timing.epoch)); let appended = self .journal .append_diagnostic(DiagnosticEvent { @@ -252,7 +429,11 @@ impl CsvStore { source_monotonic_ns: None, sim_time_ns: None, sim_time_quality: None, - level: DiagnosticLevel::Info, + level: if timing.quality == CsvTimeQuality::ClockReset { + DiagnosticLevel::Warning + } else { + DiagnosticLevel::Info + }, category: "csv".to_owned(), event: "csv.sample".to_owned(), message: "CSV sample".to_owned(), @@ -263,17 +444,31 @@ impl CsvStore { }) .await?; if appended.appended { + if timing.quality == CsvTimeQuality::ClockReset { + tracing::warn!( + filename, + source_sequence = sample.sequence, + "CSV clock discontinuity: starting a new estimated-time epoch" + ); + } + if let Some(clock) = clock { + state.clocks.insert(filename.to_owned(), clock); + } result.accepted += 1; - readings.push_back(CsvReading { + state.rows_received += 1; + state.readings.push_back(CsvReading { source: self.mapping.0.source.clone(), filename: filename.to_owned(), received_time_ns, + sample_time_ns: timing.sample_time_ns, + time_quality: timing.quality, + clock_epoch: timing.epoch, sequence: appended.sequence, source_sequence: sample.sequence, values: sample.values, }); - if readings.len() > RECENT_ROWS { - readings.pop_front(); + if state.readings.len() > RECENT_ROWS { + state.readings.pop_front(); } } else { result.duplicates += 1; @@ -288,6 +483,171 @@ impl CsvStore { mod tests { use super::*; + #[test] + fn raw_loadcell_mapping_preserves_counts_modes_and_absolute_time() { + let mapping = CsvMapping::from_json(include_str!("../csv-map.json")).unwrap(); + let samples = mapping + .parse(concat!( + "_rownum,_time,_time_unix_us,input,raw,gain\n", + "1,00:00:00.123,1735689600123456,A,-8388608,128\n", + "2,00:00:00.123,1735689600123456,B,8388607,128\n", + "3,00:00:00.223,1735689600223456,A1,17,64\n", + "4,00:00:00.223,1735689600223456,B1,-42,64\n", + "5,00:00:00.823,1735689600823456,A2,18,32\n", + "6,00:00:00.823,1735689600823456,B2,-43,32\n", + )) + .unwrap(); + assert_eq!(samples.len(), 6); + assert_eq!(samples[0].values["raw"], json!(-8388608.0)); + assert_eq!(samples[1].values["raw"], json!(8388607.0)); + assert_eq!( + samples[0].values["device_time_unix_us"], + json!(1735689600123456_u64) + ); + assert_eq!(samples[0].time_of_day_ns, Some(123_000_000)); + assert_eq!(samples[1].sequence, 2); + for (sample, label, gain) in [ + (&samples[0], "A", 128), + (&samples[1], "B", 128), + (&samples[2], "A1", 64), + (&samples[3], "B1", 64), + (&samples[4], "A2", 32), + (&samples[5], "B2", 32), + ] { + assert_eq!(sample.values["input"], json!(label)); + assert_eq!(sample.values["gain"], json!(gain)); + } + } + + #[test] + fn csv_clock_preserves_spacing_and_reanchors_every_periodic_batch() { + let anchor = parse_time_of_day("12:00:00.400").unwrap(); + let (first, clock) = CsvClock::estimate( + None, + 1, + parse_time_of_day("12:00:00.100").unwrap(), + anchor, + 100 * SECOND_NS, + ) + .unwrap(); + assert_eq!(first.sample_time_ns, Some(100 * SECOND_NS - 300_000_000)); + let (last, clock) = + CsvClock::estimate(Some(&clock), 2, anchor, anchor, 100 * SECOND_NS).unwrap(); + assert_eq!(last.sample_time_ns, Some(100 * SECOND_NS)); + assert_eq!(last.quality, CsvTimeQuality::Estimated); + + let next_anchor = parse_time_of_day("12:00:00.900").unwrap(); + let (next, _) = CsvClock::estimate( + Some(&clock), + 3, + parse_time_of_day("12:00:00.500").unwrap(), + next_anchor, + 101 * SECOND_NS, + ) + .unwrap(); + assert_eq!(next.sample_time_ns, Some(101 * SECOND_NS - 400_000_000)); + assert_eq!(next.epoch, 1); + } + + #[test] + fn csv_clock_distinguishes_midnight_resets_and_delayed_rows() { + let anchor = parse_time_of_day("00:00:00.100").unwrap(); + let (first, clock) = CsvClock::estimate( + None, + 1, + parse_time_of_day("23:59:59.900").unwrap(), + anchor, + 100 * SECOND_NS, + ) + .unwrap(); + assert_eq!(first.sample_time_ns, Some(100 * SECOND_NS - 200_000_000)); + let (last, clock) = + CsvClock::estimate(Some(&clock), 2, anchor, anchor, 100 * SECOND_NS).unwrap(); + assert_eq!(last.epoch, 1); + let reset_anchor = parse_time_of_day("00:00:00.050").unwrap(); + let (reset, clock) = + CsvClock::estimate(Some(&clock), 3, reset_anchor, reset_anchor, 101 * SECOND_NS) + .unwrap(); + assert_eq!(reset.quality, CsvTimeQuality::ClockReset); + assert_eq!(reset.epoch, 2); + assert_eq!(reset.sample_time_ns, Some(101 * SECOND_NS)); + let (delayed, unchanged) = CsvClock::estimate( + Some(&clock), + 1, + parse_time_of_day("23:59:59.900").unwrap(), + reset_anchor, + 102 * SECOND_NS, + ) + .unwrap(); + assert_eq!(delayed.quality, CsvTimeQuality::OutOfOrder); + assert_eq!(delayed.sample_time_ns, None); + assert_eq!(unchanged.sequence, 3); + } + + #[test] + fn csv_clock_does_not_invent_future_acquisition_times() { + let (timing, _) = CsvClock::estimate( + None, + 1, + parse_time_of_day("12:00:00.900").unwrap(), + parse_time_of_day("12:00:00.100").unwrap(), + 100 * SECOND_NS, + ) + .unwrap(); + assert_eq!(timing.sample_time_ns, None); + assert_eq!(timing.quality, CsvTimeQuality::ClockReset); + } + + #[test] + fn csv_clock_handles_counter_restart_inside_a_periodic_batch() { + let anchor = parse_time_of_day("12:00:00.300").unwrap(); + let (first, clock) = CsvClock::estimate( + None, + 19000, + parse_time_of_day("12:00:00.100").unwrap(), + anchor, + 100 * SECOND_NS, + ) + .unwrap(); + let (restart, clock) = CsvClock::estimate( + Some(&clock), + 1, + parse_time_of_day("12:00:00.200").unwrap(), + anchor, + 100 * SECOND_NS, + ) + .unwrap(); + let (last, _) = + CsvClock::estimate(Some(&clock), 2, anchor, anchor, 100 * SECOND_NS).unwrap(); + assert_eq!(first.sample_time_ns, Some(100 * SECOND_NS - 200_000_000)); + assert_eq!(restart.sample_time_ns, Some(100 * SECOND_NS - 100_000_000)); + assert_eq!(restart.quality, CsvTimeQuality::ClockReset); + assert_eq!(restart.epoch, 2); + assert_eq!(last.sample_time_ns, Some(100 * SECOND_NS)); + assert_eq!(last.epoch, 2); + } + + #[test] + fn csv_time_parser_accepts_fractional_precision_and_rejects_invalid_clocks() { + assert_eq!(parse_time_of_day("00:00:00.123456789"), Some(123_456_789)); + assert_eq!(parse_time_of_day("23:59:59"), Some(86_399 * SECOND_NS)); + for value in [ + "24:00:00", + "12:60:00", + "12:00:60", + "12:00:00.", + "1:00:00", + "12:00:00.1234567890", + "12:00:00.x", + "not a clock", + ] { + assert_eq!(parse_time_of_day(value), None, "{value}"); + } + let invalid = r#"{"source":"test","sequence_column":"n","time_column":"n", + "columns":[{"column":"n","field":"n","type":"u64"}]}"#; + assert!(CsvMapping::from_json(invalid).is_err()); + } + #[test] fn csv_mapping_changes_names_types_and_sequence_position_without_parser_changes() { let mapping = CsvMapping::from_json( diff --git a/linkhub/src/http.rs b/linkhub/src/http.rs index 96e7867..656edfc 100644 --- a/linkhub/src/http.rs +++ b/linkhub/src/http.rs @@ -354,7 +354,7 @@ async fn csv_status(State(state): State>) -> Json { match &state.csv { Some(csv) => Json(csv.status().await), None => Json(json!({ - "available": false, "columns": [], "latest": null, "recent": [], + "available": false, "columns": [], "rows_received": 0, "latest": null, "recent": [], })), } } @@ -461,6 +461,7 @@ async fn mavlink_status(State(state): State>) -> Result, + last_ms: Option, classes: Option, source: Option, event: Option, @@ -614,6 +615,7 @@ impl RecordFilter { fn from_message_query(query: &MessageQuery) -> Result { let mut filter = Self::from_query(&RecordQuery { after: None, + last_ms: None, classes: Some("mavlink".to_owned()), source: None, event: None, @@ -930,16 +932,32 @@ async fn read_record_batch( let deadline = Instant::now() + Duration::from_millis(query.wait_ms); loop { + let tail_before_read = state.journal.tail(); + let since_ns = query + .last_ms + .map(|ms| wall_time_ns().saturating_sub(ms.saturating_mul(1_000_000))); let read = state .journal - .read_after_bounded(cursor, MAX_JOURNAL_SCAN_RECORDS) + .read_window_bounded( + cursor, + TimeWindow { + since_ns, + until_ns: None, + }, + MAX_JOURNAL_SCAN_RECORDS, + ) .await?; + if since_ns.is_some() && read.records.is_empty() { + cursor = cursor.max(tail_before_read); + } let mut next_clock = read.tail_clock; let mut records = Vec::new(); for record in read.records { cursor = cursor.max(record.sequence); next_clock = record.sim_clock; - if filter.matches(&record) { + if since_ns.is_none_or(|since| record.ingest_time_ns >= since) + && filter.matches(&record) + { records.push(record.to_api_value()); if records.len() == limit { break; @@ -1864,20 +1882,18 @@ mod tests { assert_eq!(initial["available"], true); assert_eq!(initial["latest"], Value::Null); assert_eq!(initial["recent"], json!([])); + assert_eq!(initial["rows_received"], 0); let (status, header) = json_response( &app, - csv_post( - "test.csv", - "_rownum,_time,rpm,flap_angle,pitch_angle,lift,drag\r\n", - ), + csv_post("test.csv", "_rownum,_time,_time_unix_us,input,raw,gain\r\n"), ) .await; assert_eq!(status, StatusCode::OK); assert_eq!(header["accepted"], 0); assert_eq!(journal.tail(), 0); - let rows = "1,12:34:56.001,200,85,-2,1.25,-0.5\r\n2,12:34:56.101,201,86,-1,1.5,-0.4\n"; + let rows = "1,12:34:56.001,1735734896001000,A1,-8388608,64\r\n2,12:34:56.101,1735734896101000,B2,8388607,32\n"; let (status, accepted) = json_response(&app, csv_post("test.csv", rows)).await; assert_eq!(status, StatusCode::OK); assert_eq!(accepted["accepted"], 2); @@ -1894,16 +1910,32 @@ mod tests { assert!(latest["latest"]["received_time_ns"].as_u64().unwrap() > 0); assert_eq!(latest["latest"]["values"]["rownum"], 2); assert_eq!(latest["latest"]["values"]["device_time"], "12:34:56.101"); - assert_eq!(latest["latest"]["values"]["lift"], 1.5); - assert_eq!(latest["latest"]["values"]["drag"], -0.4); + assert_eq!(latest["latest"]["values"]["input"], "B2"); + assert_eq!(latest["latest"]["values"]["raw"], 8388607.0); + assert_eq!(latest["latest"]["values"]["gain"], 32); assert_eq!(latest["recent"].as_array().unwrap().len(), 2); + assert_eq!(latest["rows_received"], 2); + let first = &latest["recent"][0]; + let last = &latest["recent"][1]; + let received = last["received_time_ns"].as_u64().unwrap(); + assert_eq!(first["received_time_ns"], last["received_time_ns"]); + assert_eq!(last["sample_time_ns"], received); + assert_eq!( + first["sample_time_ns"].as_u64().unwrap(), + received - 100_000_000 + ); + assert_eq!(last["time_quality"], "estimated"); + assert_eq!(last["clock_epoch"], 1); let (_, next_file) = json_response( &app, - csv_post("next.csv", "1,12:35:00.001,0,85,0,2.5,0.2\n"), + csv_post("next.csv", "1,12:35:00.001,1735734900001000,A1,25,64\n"), ) .await; assert_eq!(next_file["accepted"], 1); + let (_, latest) = + json_response(&app, Request::get("/v1/csv").body(Body::empty()).unwrap()).await; + assert_eq!(latest["rows_received"], 3); journal.shutdown().await.expect("shutdown"); task.await.expect("journal task"); let saved = crate::journal::read_persisted(temp.path(), 0, None) @@ -1917,7 +1949,74 @@ mod tests { assert_eq!(event.event, "csv.sample"); assert_eq!(event.source_sequence, 1); assert_eq!(event.fields["filename"], "test.csv"); - assert_eq!(event.fields["values"]["lift"], 1.25); + assert_eq!(event.fields["values"]["input"], "A1"); + assert_eq!(event.fields["values"]["raw"], -8388608.0); + assert_eq!(event.fields["sample_time_ns"], received - 100_000_000); + assert_eq!(event.fields["time_quality"], "estimated"); + } + + #[tokio::test] + async fn csv_batch_anchors_final_row_when_device_counter_restarts() { + let temp = TempDir::new().expect("temp directory"); + let (journal, task) = + JournalHandle::start(JournalConfig::for_directory(temp.path(), Uuid::new_v4())) + .await + .expect("journal"); + let app = csv_app(journal.clone()); + let (status, _) = json_response( + &app, + csv_post("transition.csv", + "19000,12:00:00.100,1735732800100000,A1,1,64\n1,12:00:00.200,1735732800200000,B1,2,64\n2,12:00:00.300,1735732800300000,A2,3,32\n"), + ).await; + assert_eq!(status, StatusCode::OK); + let (_, state) = + json_response(&app, Request::get("/v1/csv").body(Body::empty()).unwrap()).await; + assert_eq!(state["rows_received"], 3); + let received = state["latest"]["received_time_ns"].as_u64().unwrap(); + assert_eq!(state["latest"]["sample_time_ns"], received); + assert_eq!(state["latest"]["clock_epoch"], 2); + assert_eq!(state["recent"][0]["sample_time_ns"], received - 200_000_000); + assert_eq!(state["recent"][1]["sample_time_ns"], received - 100_000_000); + journal.shutdown().await.expect("shutdown"); + task.await.expect("journal task"); + } + + #[tokio::test] + async fn csv_count_exceeds_recent_cache_and_excludes_invalid_rows() { + let temp = TempDir::new().expect("temp directory"); + let (journal, task) = + JournalHandle::start(JournalConfig::for_directory(temp.path(), Uuid::new_v4())) + .await + .expect("journal"); + let app = csv_app(journal.clone()); + let rows = (1..=8) + .map(|n| format!("{n},12:00:00,1735732800000000,A1,1,64\n")) + .collect::(); + let (status, _) = json_response(&app, csv_post("test.csv", rows.clone())).await; + assert_eq!(status, StatusCode::OK); + let (_, duplicates) = json_response(&app, csv_post("test.csv", rows)).await; + assert_eq!(duplicates["duplicates"], 8); + let (status, _) = json_response( + &app, + csv_post("test.csv", "9,12:00:00,1735732800000000,A1,NaN,64\n"), + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST); + let (_, state) = + json_response(&app, Request::get("/v1/csv").body(Body::empty()).unwrap()).await; + assert_eq!(state["rows_received"], 8); + assert_eq!(state["recent"].as_array().unwrap().len(), 5); + assert_eq!(state["latest"]["values"]["rownum"], 8); + + let restarted = csv_app(journal.clone()); + let (_, state) = json_response( + &restarted, + Request::get("/v1/csv").body(Body::empty()).unwrap(), + ) + .await; + assert_eq!(state["rows_received"], 0); + journal.shutdown().await.expect("shutdown"); + task.await.expect("journal task"); } #[tokio::test] @@ -1930,9 +2029,10 @@ mod tests { let app = csv_app(journal.clone()); for body in [ "", - "1,12:00:00,0,0,0,1.0,2.0\n2,12:00:01,0,0,0,NaN,2.0\n", - "1,12:00:00,0,0,0,1.0\n", - "-1,12:00:00,0,0,0,1.0,2.0\n", + "1,12:00:00,0,A1,1,64\n2,12:00:01,0,A1,NaN,64\n", + "1,12:00:00,0,A1,1\n", + "-1,12:00:00,0,A1,1,64\n", + "1,12:00:00,0,A1,1,64\n2,25:00:00,0,A1,1,64\n", ] { let (status, error) = json_response(&app, csv_post("test.csv", body)).await; assert_eq!(status, StatusCode::BAD_REQUEST, "{body}"); @@ -1940,7 +2040,7 @@ mod tests { assert_eq!(journal.tail(), 0); } for request in [ - csv_post("..%2Ftest.csv", "1,12:00:00,0,0,0,1,2"), + csv_post("..%2Ftest.csv", "1,12:00:00,0,A1,1,64"), csv_post("test.csv", vec![0xff]), Request::post("/v1/csv?filename=test.csv") .header(CONTENT_TYPE, "application/json") @@ -1948,7 +2048,7 @@ mod tests { .unwrap(), Request::post("/v1/csv") .header(CONTENT_TYPE, "text/csv") - .body(Body::from("1,12:00:00,0,0,0,1,2")) + .body(Body::from("1,12:00:00,0,A1,1,64")) .unwrap(), ] { let (status, _) = json_response(&app, request).await; @@ -1978,11 +2078,11 @@ mod tests { assert_eq!( status, json!({ - "available": false, "columns": [], "latest": null, "recent": [], + "available": false, "columns": [], "rows_received": 0, "latest": null, "recent": [], }) ); let (status, error) = - json_response(&app, csv_post("test.csv", "1,12:00:00,0,0,0,1,2")).await; + json_response(&app, csv_post("test.csv", "1,12:00:00,0,A1,1,64")).await; assert_eq!(status, StatusCode::CONFLICT); assert_eq!(error["error"], "not_ready"); journal.shutdown().await.expect("shutdown"); @@ -2059,7 +2159,11 @@ mod tests { let config = JournalConfig::for_directory(temp.path().join("journal"), Uuid::new_v4()); let (journal, task) = JournalHandle::start(config).await.expect("journal"); let computer_name = hostname::get().unwrap().into_string().unwrap(); - let short_name = computer_name.split('.').next().unwrap().to_ascii_lowercase(); + let short_name = computer_name + .split('.') + .next() + .unwrap() + .to_ascii_lowercase(); let named_url = format!("https://{short_name}.local:9443/camera"); for (listen, expected) in [ ("0.0.0.0", named_url.as_str()), @@ -2505,8 +2609,9 @@ mod tests { .await .expect("response"); let read = app + .clone() .oneshot( - Request::get("/v1/diagnostics/events") + Request::get("/v1/diagnostics/events?last_ms=300000") .body(Body::empty()) .expect("request"), ) @@ -2529,6 +2634,24 @@ mod tests { assert_eq!(batch["records"][0]["data"]["source"], "groundstation"); assert_eq!(batch["next_cursor"], "v1:1"); + journal.flush().await.expect("flush"); + tokio::time::sleep(Duration::from_millis(2)).await; + let expired = app + .oneshot( + Request::get("/v1/diagnostics/events?last_ms=0") + .body(Body::empty()) + .expect("request"), + ) + .await + .expect("response"); + assert_eq!(expired.status(), StatusCode::OK); + let bytes = to_bytes(expired.into_body(), usize::MAX) + .await + .expect("expired batch body"); + let batch: Value = serde_json::from_slice(&bytes).expect("expired batch JSON"); + assert_eq!(batch["records"], json!([])); + assert_eq!(batch["next_cursor"], "v1:1"); + journal.shutdown().await.expect("shutdown"); task.await.expect("journal task"); } diff --git a/linkhub/src/journal.rs b/linkhub/src/journal.rs index 88faa0b..15a17d1 100644 --- a/linkhub/src/journal.rs +++ b/linkhub/src/journal.rs @@ -77,6 +77,69 @@ struct Chunk { records: Vec, } +#[derive(Default)] +struct ChunkIndex { + entries: Vec, +} + +struct ChunkEntry { + path: PathBuf, + last_sequence: u64, + min_ns: u64, + max_ns: u64, + max_ns_through: u64, +} + +impl ChunkIndex { + async fn load(directory: &Path) -> Result { + let mut index = Self::default(); + for path in chunk_paths(directory).await? { + let Some((first, last)) = chunk_sequences(&path) else { + return Err(JournalError::UnsupportedChunk(path)); + }; + if first <= index.tail() || last < first { + return Err(JournalError::UnsupportedChunk(path)); + } + let (min_ns, max_ns) = read_chunk_times(&path).await?; + index.push(path, last, min_ns, max_ns); + } + Ok(index) + } + + fn tail(&self) -> u64 { + self.entries.last().map_or(0, |entry| entry.last_sequence) + } + + fn push(&mut self, path: PathBuf, last_sequence: u64, min_ns: u64, max_ns: u64) { + // The running maximum stays sorted even when the wall clock steps back. + let max_ns_through = self + .entries + .last() + .map_or(max_ns, |entry| max_ns.max(entry.max_ns_through)); + self.entries.push(ChunkEntry { + path, + last_sequence, + min_ns, + max_ns, + max_ns_through, + }); + } + + fn paths_after(&self, after: u64, window: TimeWindow) -> Vec { + let start = self.entries.partition_point(|entry| { + entry.last_sequence <= after + || window + .since_ns + .is_some_and(|since| entry.max_ns_through < since) + }); + self.entries[start..] + .iter() + .filter(|entry| window.overlaps(entry.min_ns, entry.max_ns)) + .map(|entry| entry.path.clone()) + .collect() + } +} + #[derive(Debug, thiserror::Error)] pub enum JournalError { #[error("journal task is unavailable")] @@ -110,6 +173,8 @@ enum Command { reply: oneshot::Sender, }, Snapshot { + after: u64, + window: TimeWindow, reply: oneshot::Sender, }, Flush { @@ -123,6 +188,7 @@ enum Command { struct JournalSnapshot { tail: u64, sim_clock: SimClock, + flushed: Vec, pending: Vec, } @@ -134,7 +200,6 @@ pub struct JournalRead { #[derive(Clone)] pub struct JournalHandle { run_id: Uuid, - directory: Arc, sender: mpsc::Sender, live: broadcast::Sender>, tail: Arc, @@ -144,17 +209,17 @@ impl JournalHandle { pub async fn start(config: JournalConfig) -> Result<(Self, JoinHandle<()>), JournalError> { validate_config(&config); fs::create_dir_all(&config.directory).await?; + let index = ChunkIndex::load(&config.directory).await?; let (sender, receiver) = mpsc::channel(config.command_capacity); let (live, _) = broadcast::channel(config.live_capacity); - let tail = Arc::new(AtomicU64::new(0)); + let tail = Arc::new(AtomicU64::new(index.tail())); let handle = Self { run_id: config.run_id, - directory: Arc::new(config.directory.clone()), sender, live: live.clone(), tail: Arc::clone(&tail), }; - let task = tokio::spawn(run_journal(config, receiver, live, tail)); + let task = tokio::spawn(run_journal(config, receiver, live, tail, index)); Ok((handle, task)) } @@ -266,19 +331,10 @@ impl JournalHandle { max_records: usize, ) -> Result { assert!(max_records > 0, "max_records must be positive"); - let snapshot = self.snapshot().await?; - let mut records = read_flushed_after(&self.directory, after, window, max_records).await?; - records.retain(|record| record.sequence <= snapshot.tail); - let scanned_through = records.last().map_or(after, |record| record.sequence); - let remaining = max_records.saturating_sub(records.len()); - records.extend( - snapshot - .pending - .into_iter() - .filter(|record| record.sequence > scanned_through) - .take(remaining), - ); - records.sort_unstable_by_key(|record| record.sequence); + let snapshot = self.snapshot(after, window).await?; + let mut records = read_flushed_after(snapshot.flushed, after, max_records).await?; + let remaining = max_records - records.len(); + records.extend(snapshot.pending.into_iter().take(remaining)); let tail_clock = records .last() .map_or(snapshot.sim_clock, |record| record.sim_clock); @@ -289,14 +345,22 @@ impl JournalHandle { } pub async fn checkpoint(&self) -> Result<(u64, SimClock), JournalError> { - let snapshot = self.snapshot().await?; + let snapshot = self.snapshot(u64::MAX, TimeWindow::default()).await?; Ok((snapshot.tail, snapshot.sim_clock)) } - async fn snapshot(&self) -> Result { + async fn snapshot( + &self, + after: u64, + window: TimeWindow, + ) -> Result { let (reply, response) = oneshot::channel(); self.sender - .send(Command::Snapshot { reply }) + .send(Command::Snapshot { + after, + window, + reply, + }) .await .map_err(|_| JournalError::Unavailable)?; response.await.map_err(|_| JournalError::Unavailable) @@ -330,6 +394,7 @@ async fn run_journal( mut receiver: mpsc::Receiver, live: broadcast::Sender>, tail: Arc, + mut index: ChunkIndex, ) { let mut pending = Vec::with_capacity(config.max_chunk_records); let mut pending_bytes = 0_usize; @@ -344,7 +409,7 @@ async fn run_journal( biased; command = receiver.recv() => { let Some(command) = command else { - let _ = flush_pending(&config, &mut pending).await; + let _ = flush_pending(&config, &mut pending, &mut index).await; return; }; match command { @@ -406,7 +471,7 @@ async fn run_journal( if pending.len() >= config.max_chunk_records || pending_bytes >= config.max_chunk_bytes { - if let Err(error) = flush_pending(&config, &mut pending).await { + if let Err(error) = flush_pending(&config, &mut pending, &mut index).await { tracing::error!(%error, "journal chunk flush failed"); } pending_bytes = 0; @@ -419,29 +484,31 @@ async fn run_journal( }; let _ = reply.send(sim_clock.epoch); } - Command::Snapshot { reply } => { + Command::Snapshot { after, window, reply } => { + let pending_start = pending.partition_point(|record| record.sequence <= after); let _ = reply.send(JournalSnapshot { tail: tail.load(Ordering::Acquire), sim_clock, - pending: pending.clone(), + flushed: index.paths_after(after, window), + pending: pending[pending_start..].to_vec(), }); } Command::Flush { reply } => { - let result = flush_pending(&config, &mut pending).await; + let result = flush_pending(&config, &mut pending, &mut index).await; if result.is_ok() { pending_bytes = 0; } let _ = reply.send(result); } Command::Shutdown { reply } => { - let result = flush_pending(&config, &mut pending).await; + let result = flush_pending(&config, &mut pending, &mut index).await; let _ = reply.send(result); return; } } } _ = ticker.tick() => { - if let Err(error) = flush_pending(&config, &mut pending).await { + if let Err(error) = flush_pending(&config, &mut pending, &mut index).await { tracing::error!(%error, "periodic journal chunk flush failed"); } else { pending_bytes = 0; @@ -454,6 +521,7 @@ async fn run_journal( async fn flush_pending( config: &JournalConfig, pending: &mut Vec, + index: &mut ChunkIndex, ) -> Result<(), JournalError> { if pending.is_empty() { return Ok(()); @@ -494,11 +562,14 @@ async fn flush_pending( bytes.extend_from_slice(&encoded); let result = async { fs::write(&temporary_path, bytes).await?; - fs::rename(temporary_path, final_path).await + fs::rename(temporary_path, &final_path).await } .await; match result { - Ok(()) => Ok(()), + Ok(()) => { + index.push(final_path, last_sequence, min_ns, max_ns); + Ok(()) + } Err(error) => { pending.extend(chunk.records); Err(JournalError::Io(error)) @@ -506,12 +577,7 @@ async fn flush_pending( } } -async fn read_flushed_after( - directory: &Path, - after: u64, - window: TimeWindow, - max_records: usize, -) -> Result, JournalError> { +async fn chunk_paths(directory: &Path) -> Result, JournalError> { let mut entries = fs::read_dir(directory).await?; let mut paths = Vec::new(); while let Some(entry) = entries.next_entry().await? { @@ -521,18 +587,16 @@ async fn read_flushed_after( } } paths.sort_unstable(); + Ok(paths) +} +async fn read_flushed_after( + paths: impl IntoIterator, + after: u64, + max_records: usize, +) -> Result, JournalError> { let mut records = Vec::new(); for path in paths { - if chunk_last_sequence(&path).is_some_and(|last_sequence| last_sequence <= after) { - continue; - } - if window != TimeWindow::default() { - let (min_ns, max_ns) = read_chunk_times(&path).await?; - if !window.overlaps(min_ns, max_ns) { - continue; - } - } let bytes = fs::read(&path).await?; if bytes.len() < CHUNK_HEADER_LEN || !bytes.starts_with(CHUNK_MAGIC) { return Err(JournalError::UnsupportedChunk(path)); @@ -576,8 +640,10 @@ pub async fn read_persisted( after: u64, through: Option, ) -> Result, JournalError> { - let mut records = - read_flushed_after(directory, after, TimeWindow::default(), usize::MAX).await?; + let paths = chunk_paths(directory).await?.into_iter().filter(|path| { + chunk_sequences(path).is_none_or(|(_, last_sequence)| last_sequence > after) + }); + let mut records = read_flushed_after(paths, after, usize::MAX).await?; if let Some(through) = through { records.retain(|record| record.sequence <= through); } @@ -616,8 +682,9 @@ fn chunk_path(directory: &Path, first_sequence: u64, last_sequence: u64) -> Path directory.join(format!("{first_sequence:020}-{last_sequence:020}.lhc")) } -fn chunk_last_sequence(path: &Path) -> Option { - path.file_stem()?.to_str()?.split_once('-')?.1.parse().ok() +fn chunk_sequences(path: &Path) -> Option<(u64, u64)> { + let (first, last) = path.file_stem()?.to_str()?.split_once('-')?; + Some((first.parse().ok()?, last.parse().ok()?)) } #[cfg(test)] @@ -831,7 +898,7 @@ mod tests { invalid_chunk.push(0xff); fs::write(path, invalid_chunk).await.expect("old chunk"); - let records = read_flushed_after(temp.path(), 10, TimeWindow::default(), usize::MAX) + let records = read_persisted(temp.path(), 10, None) .await .expect("old chunk must not be decoded"); @@ -839,45 +906,78 @@ mod tests { } #[tokio::test] - async fn chunk_time_header_skips_chunks_outside_window() { + async fn indexed_window_reads_do_not_open_old_chunks() { let temp = TempDir::new().expect("temp directory"); let run_id = Uuid::new_v4(); - let mut config = JournalConfig::for_directory(temp.path(), run_id); - config.max_chunk_records = 1; - let (journal, task) = JournalHandle::start(config).await.expect("journal"); - journal - .append_diagnostic(diagnostic(run_id, 1)) + let config = JournalConfig::for_directory(temp.path(), run_id); + let mut index = ChunkIndex::default(); + // Chunk 3 was recorded after a backward wall-clock step. + for (sequence, ingest_time_ns) in [(1, 10), (2, 30), (3, 20)] { + let mut record = JournalRecord::new( + sequence, + None, + SimClock::default(), + RecordPayload::MavlinkFrame(frame()), + ); + record.ingest_time_ns = ingest_time_ns; + flush_pending(&config, &mut vec![record], &mut index) + .await + .expect("seed chunk"); + } + + let (journal, task) = JournalHandle::start(config).await.expect("reopen journal"); + assert_eq!(journal.tail(), 3); + let sequence = journal + .append(RecordPayload::MavlinkFrame(frame()), None) .await - .expect("first"); + .expect("append after indexed tail"); + assert_eq!(sequence, 4); journal.flush().await.expect("flush"); - let (min_ns, max_ns) = read_chunk_times(&chunk_path(temp.path(), 1, 1)) + + // Removing an already indexed, out-of-window chunk detects even a + // header read, not just an attempt to decode its payload. + fs::remove_file(chunk_path(temp.path(), 1, 1)) .await - .expect("chunk header"); - assert!(min_ns > 0 && min_ns == max_ns); - - // A chunk whose header is outside the window must not be decoded. - let mut undecodable = CHUNK_MAGIC.to_vec(); - undecodable.extend_from_slice(&1_u64.to_le_bytes()); - undecodable.extend_from_slice(&2_u64.to_le_bytes()); - undecodable.push(0xc1); - fs::write(chunk_path(temp.path(), 2, 2), undecodable) + .expect("remove old chunk"); + fs::write(chunk_path(temp.path(), 5, 5), b"unindexed") .await - .expect("out-of-window chunk"); + .expect("place unindexed file to detect directory rescans"); let window = TimeWindow { - since_ns: Some(min_ns), + since_ns: Some(20), until_ns: None, }; - let records = read_flushed_after(temp.path(), 0, window, usize::MAX) + let read = journal + .read_window_bounded(0, window, 4) .await .expect("windowed read"); - assert_eq!(records.len(), 1); - assert_eq!(records[0].sequence, 1); + assert_eq!( + read.records + .iter() + .map(|record| record.sequence) + .collect::>(), + vec![2, 3, 4] + ); + + let read = journal + .read_window_bounded( + 0, + TimeWindow { + since_ns: Some(25), + until_ns: Some(30), + }, + 4, + ) + .await + .expect("read across backward clock step"); + assert_eq!(read.records.len(), 1); + assert_eq!(read.records[0].sequence, 2); - let unsupported = read_flushed_after(temp.path(), 0, TimeWindow::default(), usize::MAX) + let error = journal + .records_after(0) .await - .expect_err("full read must decode, and reject, the corrupt chunk"); - assert!(matches!(unsupported, JournalError::Decode(_))); + .expect_err("an in-range missing chunk must still fail"); + assert!(matches!(error, JournalError::Io(_))); journal.shutdown().await.expect("shutdown"); task.await.expect("journal task"); @@ -889,7 +989,7 @@ mod tests { fs::write(chunk_path(temp.path(), 1, 1), b"LHCHNK01\x80") .await .expect("legacy chunk"); - let error = read_flushed_after(temp.path(), 0, TimeWindow::default(), usize::MAX) + let error = read_persisted(temp.path(), 0, None) .await .expect_err("legacy chunk"); assert!(matches!(error, JournalError::UnsupportedChunk(_))); @@ -918,10 +1018,12 @@ mod tests { .await .expect("append"); let records = journal.records_after(0).await.expect("replay"); - assert_eq!(records.len(), source_sequence as usize); assert_eq!( - records.last().map(|record| record.sequence), - Some(source_sequence), + records + .iter() + .map(|record| record.sequence) + .collect::>(), + (1..=source_sequence).collect::>(), ); } diff --git a/loadcell/.gitignore b/loadcell/.gitignore new file mode 100644 index 0000000..9882999 --- /dev/null +++ b/loadcell/.gitignore @@ -0,0 +1,5 @@ +.pio/ +.vscode/ +include/local_config.h +launch_config.cmd +backups/ diff --git a/loadcell/AGENTS.md b/loadcell/AGENTS.md new file mode 100644 index 0000000..2d16271 --- /dev/null +++ b/loadcell/AGENTS.md @@ -0,0 +1,78 @@ +# Load-cell firmware agent guide + +## Purpose and scope + +This directory is an independent PlatformIO project for the CSV-generating ESP32 +load-cell sensor. It is not part of the root Python distribution or the LinkHub +Rust workspace. It extracts a two-HX711 sensor application without servo, pitch, +light-barrier, or InfluxDB code. Browser OTA is retained. +Do not reintroduce actuator control. + +## Structure + +- `platformio.ini`: pinned ESP32 Arduino platform, LOLIN D32 Pro board, HX711 + dependency, and serial-monitor settings. No automatic upload targets. +- `include/config.h`: GPIO assignments, timing/buffer limits, and build defaults. +- `include/hx711_input.h`: two/four-input capture scheduler, input labels/gains, + old-conversion discard, and 400 ms channel/gain settling. +- `include/sample_csv.h`: plain sample record and ordered raw CSV serialization. +- `test/test_hx711.cpp`: native software tests of switching and CSV behavior. +- `include/local_config.h.example`: template for the ignored local Wi-Fi/CSV + configuration. Never put real credentials in tracked files. +- `launch_config.cmd.example`: template for ignored Windows launcher addresses. + Keep local addresses, device identities, and personal paths out of tracked files. +- `src/main.cpp`: setup, HX711 acquisition task, bounded sample queue, CSV + serialization/batching/HTTP retry, NTP timestamps, NVS configuration, and + the HTTP configuration page. +- `include/ota.h`, `src/ota.cpp`: password-protected browser firmware upload on + port 80. Empty local OTA password disables this service. Failed or aborted + uploads must not reboot or return success. +- `README.md`: build, wiring, protocol, configuration, and runtime limitations. +- `backup_esp32.py`: independent uv inline-dependency utility for USB full-flash + backup, size checking, and device verification. Explicit USB port required; + its only permitted device commands are flash-id, read-flash, and verify-flash. + Dumps/logs/manifests in ignored `backups/` may contain credentials; never upload + them, commit them, or treat partial reads as verified backups. + +## Execution and invariants + +The sampling task on core 1 owns both HX711 objects. It reads signed raw values +and timestamps samples, then passes plain-data records through a FreeRTOS queue. +One additional single-element overwrite queue exposes the latest paired raw +reading independently of CSV delivery and NTP. +Arduino `loop()` owns web requests, preferences writes, CSV strings, filenames, +and HTTP uploads. Atomic sample interval and requested/active capture modes +cross this ownership boundary besides the queues. Do not share mutable Arduino +strings between tasks. Web handlers must not access the HX711 objects. + +Keep the raw CSV columns in `sample_csv.h` and HTTP `filename` query parameter +in step with `linkhub/csv-map.json`. The receiver owns all calibration and +post-processing; do not convert counts to force on the ESP32. +Preserve per-sample input/gain tags across queued mode changes. +`/set_hx711?mode=2|4` persists a mode request and returns HTTP 202; +`/hx711` distinguishes requested, active, and last sample modes. +Two-input mode emits A/B at gain 128; four-input mode alternates A1/B1 at +gain 64 and A2/B2 at gain 32, settling on every change. +Each paired record produces two CSV rows with a shared pair-completion time +and independent `input,raw,gain` fields. The six-column header works in both +modes. Keep the 300-row batch size even so pairs are never split. +The configuration helper in `scripts/configure_esp_csv.ps1` depends on the +`/create_new_csv?url=...` endpoint and the `CSVStorageURL` input on `/`. +It preserves an unchanged CSV destination and explicitly requests four-input +capture before the ESP LinkHub launcher starts the receiver. +`/setSamplingRate` takes an interval in milliseconds, not a frequency. +NVS keys are `csv_url`, `interval_ms`, and `capture_mode` under +`rawes-loadcell`. + +Do not silently substitute readings on timeouts, claim upload success for +non-2xx responses, weaken validation, or assume the inherited calibration fits +new hardware. Runtime limitations and bench checks are documented in the README. + +## Validation + +Run `pio run --project-dir loadcell` from the repository root for a firmware build. +If PlatformIO is missing, install using the Microsoft package feed command in +the README. Keep build artifacts in the ignored `.pio` directory. +Do not flash, erase NVS, or interact with physical hardware unless requested. +When changing CSV or hardware behavior, update the README and test that behavior +on the bench when authorized; a compiler check alone is not hardware validation. diff --git a/loadcell/README.md b/loadcell/README.md new file mode 100644 index 0000000..75afea6 --- /dev/null +++ b/loadcell/README.md @@ -0,0 +1,268 @@ +# ESP32 load-cell firmware + +Standalone PlatformIO/Arduino firmware for a **LOLIN D32 Pro (ESP32)**. +Extracted from an existing sensor application without its custom library +dependencies, actuator code, or local configuration. + +The two HX711 amplifiers, 100 ms default sample interval, 300-row upload batches, +and HTTP port 88 are retained. CSV carries raw ADC counts and acquisition +metadata; calibration and derived quantities belong to the receiver. +Browser-based OTA is retained. Servo motion, pitch/RPM/light-barrier sensing, +and InfluxDB are excluded. +There are no actuator outputs. + +## Build + +Install PlatformIO Core if it is not already available: + +```powershell +uv tool install --default-index https://packagefeedproxy.microsoft.io/pypi/simple/ platformio==6.1.18 +``` + +From this directory: + +```powershell +Copy-Item include\local_config.h.example include\local_config.h +# Edit include\local_config.h with your Wi-Fi and receiving server. +pio run +``` + +The local header is ignored by Git. A build also works without it, but logs +missing Wi-Fi configuration and cannot upload. Original credentials are not copied. +Build output is `.pio\build\lolin_d32_pro\firmware.bin`. +PlatformIO downloads the pinned ESP32 platform and HX711 dependency on first build. + +Uploading is a separate, explicit operation; do not connect actuators: + +```powershell +pio run --target upload --upload-port COM_PORT +pio device monitor --port COM_PORT --baud 115200 +``` + +Replace `COM_PORT` with the positively identified ESP32 serial port. +USB uploads use 115200 baud for reliability on the observed CH340 link. +Ordinary `pio run` never uploads or opens a monitor. +No filesystem image or external web assets are required. + +## Private Wi-Fi and OTA configuration + +Store both passwords in **`include/local_config.h`**, which is ignored by Git. +Create it by copying `include/local_config.h.example`, then edit the copy: + +- `LOADCELL_WIFI_SSID`: your Wi-Fi network name. +- `LOADCELL_WIFI_PASSWORD`: your Wi-Fi password. +- `LOADCELL_OTA_PASSWORD`: a strong, unique browser-OTA password. + An empty value disables OTA; the OTA username is `admin`. +- `LOADCELL_CSV_URL`: optional HTTP receiver URL; leave empty to configure it + later through the sensor's web page. + +Never put real values in `include/config.h`, the checked-in example, +`platformio.ini`, documentation, or compiler flags committed to Git. +Rebuild after editing the private header; these credentials are compiled into +the application, not provisioned through the CSV settings page. +Keep generated `.pio/` firmware and `backups/` private too: they can contain +the compiled credentials. Do not force-add ignored files. + +## Back up the existing board over USB + +Before replacing the old firmware, use the independent read-only utility. +Run these commands from the repository root: + +```powershell +uv run --script loadcell\backup_esp32.py --help +uv run --script loadcell\backup_esp32.py --list +uv run --script loadcell\backup_esp32.py --port COM_PORT +``` + +Replace `COM_PORT` with the USB serial port you positively identified from the +listing (description, USB VID/PID, serial number/location). The utility never +guesses or connects during `--list`. Its inline dependency configuration uses +the Microsoft Python feed. It is independent of the installed PlatformIO version. + +Close serial monitors first. Disconnect external mechanisms/actuators and put +the setup in a safe state: entering the bootloader interrupts the old firmware. +The utility resets the selected classic ESP32 into its serial bootloader, +detects the actual flash capacity, reads **all** flash, checks the exact byte +count, then runs esptool's full-image verification against the device. +It never issues flash-write, erase, or eFuse-write commands. It does upload +esptool's temporary helper to RAM, which is not a firmware installation. + +Each attempt has a unique directory under Git-ignored `loadcell\backups`. +Only a completed and verified attempt gets `full_flash.bin` and `manifest.json` +with size, SHA-256, tool version, and USB identity. `esptool.log` records tool +output. Read progress is printed and logged at each 5% threshold, based on actual +bytes received, rather than every block. Unbuffered esptool output makes updates +visible during the read; verification is announced as a separate stage. +Failed attempts retain +`.partial.bin` if any bytes were read; do not +treat these as usable backups. The default baud is 115200 for reliability; +`--baud 460800` is available for known-good links. + +Afterward, press EN/RESET or reconnect USB to resume the original firmware: +the utility intentionally leaves the device in the bootloader between operations +and after completion so the application cannot change NVS during verification. +If automatic bootloader entry fails, hold BOOT, tap EN, release BOOT, and retry. +Stop if security restrictions prevent reading; do not bypass protections. + +The dump includes bootloader, partition table, applications, NVS, and filesystem +contents, **not source code or eFuses**. It may contain passwords: keep the entire +backup directory private, outside Git, and copy it to a safe second location. +An alternative `--output-dir` must also be kept out of version control. +This tool deliberately has no restore operation. Encryption, secure boot, or +changed eFuses can affect restorability; a verified read is not a tested restore. + +## Wi-Fi firmware updates (OTA) + +Set `LOADCELL_OTA_PASSWORD` in the ignored local configuration header before the +initial USB upload. With an empty password, OTA is disabled and reports this over +serial. Once connected, open `http:///` (port 80), sign in as `admin` +using your configured password, and upload +`.pio\build\lolin_d32_pro\firmware.bin` from a subsequent build. +The sensor validates the image using the ESP32 Update library and reboots only +after a completed update. Failed or aborted uploads report failure and do not +intentionally reboot. The page works without internet access or external scripts. +Configuration remains on port 88; `/serverIndex` also opens the OTA form. + +Use the application `firmware.bin`, not a bootloader, filesystem, or merged image. +Keep the same board/partition layout for OTA builds. NVS configuration survives +normal application updates; pending samples do not. OTA is password-protected +on the server, unlike the original browser-only login. Transport is still plain +HTTP, so use only a trusted isolated network. This is not signed-image verification +or an automatic rollback system; keep USB recovery available. + +## Wiring and calibration + +| Amplifier / CSV input labels | HX711 DOUT | HX711 SCK | +|---|---:|---:| +| A (formerly lift) / `A` or `A1`, `A2` | GPIO 33 | GPIO 25 | +| B (formerly drag) / `B` or `B1`, `B2` | GPIO 34 | GPIO 32 | + +Use the ESP32's 3.3 V logic levels and a common ground. Verify your HX711 board's +supply and logic requirements before wiring. GPIO 34 is input-only. +Board selection, pins, timeouts, and UTC offset live in +[include/config.h](include/config.h). Each amplifier has two multiplexed inputs. +No calibration, automatic tare, voltage +conversion, or force conversion is performed on the ESP32. +The receiver must apply calibration for the specific amplifier, input, and gain. +**Verify units, sign, zero, and scale against known loads before relying on +readings.** Gain alone does not determine load-cell sensitivity or zero offset. + +## Configuration and CSV + +The serial monitor prints the acquired IP. Open `http://:88/` to set +the CSV destination, sample interval, and two/four-input capture mode. These settings persist in NVS and +override build defaults. Wi-Fi credentials remain in the local build header. +The existing configuration helper +[configure_esp_csv.ps1](../scripts/configure_esp_csv.ps1) can set the destination. +It also selects and verifies four-input capture. If the destination already +matches, it preserves the current file rather than requesting a flush before +the receiver starts. +For the Windows launcher, copy `launch_config.cmd.example` to the ignored +`launch_config.cmd` and configure the device URL and MAVLink connection locally. +Alternatively set `LOADCELL_DEVICE_URL` and `LINKHUB_CONNECTION` in the launching +environment. Never commit the local headers, launch configuration, firmware +binaries, flash backups, logs, or device-specific identifiers. + +- `GET /create_new_csv?url=` saves the destination and + rotates the file after flushing the current batch. A failed flush leaves the + destination unchanged; restore the old receiver before retrying. +- `GET /setSamplingRate?val=100` sets **milliseconds between sample attempts**, + not Hz. Accepted range: 10..60000 ms. Actual throughput is limited by the + HX711 conversion rate, timeouts, and channel switching/settling. +- `GET /set_hx711?mode=2` selects the primary input of each amplifier at gain + 128, labeled **A** and **B**. This is the default. +- `GET /set_hx711?mode=4` captures **A1, A2, B1, B2** automatically. + A1/B1 are the amplifiers' primary HX711 inputs at gain **64**; A2/B2 are + their secondary HX711 inputs at gain **32**. The HX711 cannot give both + inputs the same gain. Capture alternates A1/B1, then A2/B2, repeatedly. + The labels A/B identify physical amplifiers, not HX711 internal channel names. + Invalid or missing selections return + HTTP 400 without changing the saved/requested configuration. +- Accepted mode changes return **HTTP 202**, with JSON status. Application is + asynchronous: the acquisition task discards the old-channel conversion, + selects the new channel/gain, and waits at least 400 ms for settling. + This applies to every alternation in four-input mode, reducing the per-input + rate substantially (typically about one reading/second/input at the default + interval; actual hardware timing varies). Inputs are not simultaneous. + No paired CSV sample is emitted while either amplifier is settling. +- `GET /hx711` returns `requested_mode` (2 or 4), `active_mode` (0 while + settling or after a timeout), and `last_sample`. The last sample contains + its own `mode`, `age_ms`, `time_synchronized`, and two `readings`, each with + `input`, signed `raw`, and `gain`. In mode 4 the latest pair alternates + between A1/B1 and A2/B2; it is not a cache of all four. + `last_sample` is null before any valid paired reading and retains its actual + acquisition labels/gain during subsequent mode changes. + Raw status works without a CSV receiver or NTP synchronization. +- CSV is posted as `text/csv` with `?filename=_tpdata.csv` (or an + additional query parameter if the destination already has a query). + For LinkHub, use `http://:8999/v1/csv` or the port of your instance. + +The ordered header is: + +```csv +_rownum,_time,_time_unix_us,input,raw,gain +``` + +Each row contains **one input reading**, not one column per input. The same +schema works in both modes without changing the receiver mapping: + +```csv +1,12:00:00.100,1795604400100000,A1,-1234,64 +2,12:00:00.100,1795604400100000,B1,5678,64 +3,12:00:00.700,1795604400700000,A2,-2345,32 +4,12:00:00.700,1795604400700000,B2,6789,32 +``` + +In two-input mode the labels are simply `A` and `B`, both with gain 128. +`raw` is a signed 24-bit ADC count, not a force or voltage. Each queued sample +retains its own labels and gain; changing modes cannot relabel older rows. +The old derived lift/drag and unused RPM/angle columns are not emitted. + +Row numbers start at one per file. Timestamps are captured after the two +sequential amplifier reads, not when uploading; the two adjacent rows share +that pair-completion timestamp. The ADC inputs are not sampled +simultaneously. CSV requires NTP synchronization. +`_time_unix_us` is the UTC Unix timestamp in integer microseconds, including the +date. `_time` remains `HH:MM:SS.mmm` with the original fixed UTC+1 offset +(no daylight saving adjustment) for LinkHub's existing timing interface. +Filenames include milliseconds to reduce rotation collisions. + +The supplied [LinkHub mapping](../linkhub/csv-map.json) matches this raw schema. +Restart a running LinkHub receiver once with the updated mapping before sending +these rows; its mapping is loaded at process startup. Later mode switches do +not require receiver changes. All post-processing, +including calibration and physical-unit conversion, is the receiver's job. + +## Focused software tests + +The dependency-free native tests exercise both capture modes, repeated four-input +alternation, mode changes during settling, discarded old conversions, settling +including timer wraparound, timeouts without phase advancement, and raw CSV metadata. +From the repository root on this Windows workstation with WSL: + +```powershell +New-Item -ItemType Directory -Force tmp\loadcell-tests | Out-Null +wsl.exe --exec g++ -std=c++11 -Wall -Wextra -Werror -Iloadcell/include loadcell/test/test_hx711.cpp -o tmp/loadcell-tests/test_hx711 +wsl.exe --exec tmp/loadcell-tests/test_hx711 +``` + +These are software tests with a fake ADC, not a full ESP32 simulation or a +physical calibration test. Also run the PlatformIO firmware build. + +## Reliability and limits + +Acquisition runs independently of HTTP in a FreeRTOS task; plain-data samples +cross a bounded queue. No Arduino strings are shared between cores. +Missing HX711 conversions and unsynchronized time are reported and do not +produce fabricated rows. HTTP failures, including non-2xx responses, retain the +current batch for retry every five seconds. The 600-pair queue drops new +samples with a rate-limited serial warning when full. This is not durable storage: +power loss discards pending data, and an ambiguous HTTP failure can cause a +duplicate batch on retry. Only full batches are normally sent; file rotation +also flushes a partial batch. + +Wi-Fi, the configuration page, and CSV transport are intended for a **trusted +isolated LAN**. The page has no authentication and HTTP is unencrypted. +There is no access-point provisioning mode, TLS, or on-device CSV storage. +Build success does not validate physical wiring, load calibration, Wi-Fi, +NTP, or end-to-end reception; these require a separate bench test. diff --git a/loadcell/backup_esp32.py b/loadcell/backup_esp32.py new file mode 100644 index 0000000..73cd170 --- /dev/null +++ b/loadcell/backup_esp32.py @@ -0,0 +1,192 @@ +# /// script +# requires-python = ">=3.14" +# dependencies = ["esptool==5.1.0"] +# +# [[tool.uv.index]] +# name = "microsoft-python" +# url = "https://packagefeedproxy.microsoft.io/pypi/simple/" +# default = true +# /// +"""Read and verify a complete ESP32 flash backup without writing device flash.""" + +import argparse +from datetime import datetime, UTC +import hashlib +from importlib.metadata import version +import json +from pathlib import Path +import re +import subprocess +import sys +from typing import TextIO + +from serial.tools import list_ports +from serial.tools.list_ports_common import ListPortInfo + + +DEFAULT_BACKUP_ROOT = Path(__file__).resolve().parent / "backups" +READ_ONLY_COMMANDS = frozenset({"flash-id", "read-flash", "verify-flash"}) + + +def flash_size_bytes(output: str) -> int: + match = re.search(r"Detected flash size:\s*(\d+)\s*(KB|MB)\b", output) + if match is None: + raise ValueError("esptool did not report a recognized flash size; refusing to guess.") + size = int(match[1]) * {"KB": 1024, "MB": 1024 * 1024}[match[2]] + if size <= 0: + raise ValueError("esptool reported an invalid flash size.") + return size + + +def run_esptool( + port: str, baud: int, command: str, arguments: list[str], log: TextIO, +) -> str: + if command not in READ_ONLY_COMMANDS: + raise ValueError(f"Device command is not read-only: {command}") + invocation = [ + sys.executable, "-u", "-m", "esptool", "--chip", "esp32", + "--port", port, "--baud", str(baud), + "--before", "default-reset", "--after", "no-reset", + command, *arguments, + ] + log.write(f"\nCOMMAND: {subprocess.list2cmdline(invocation)}\n") + log.flush() + output: list[str] = [] + next_percent = 5 + with subprocess.Popen( + invocation, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + text=True, encoding="utf-8", errors="replace", + ) as process: + if process.stdout is None: + raise RuntimeError("Cannot read esptool output.") + for line in process.stdout: + progress = re.search(r"(\d+)/([1-9]\d*) bytes", line) if command == "read-flash" else None + if progress is not None: + completed, total = int(progress[1]), int(progress[2]) + while next_percent <= 100 and completed * 100 >= total * next_percent: + message = f"Flash read: {next_percent}% ({completed:,}/{total:,} bytes)\n" + print(message, end="", flush=True) + log.write(message) + log.flush() + output.append(message) + next_percent += 5 + continue + if not line.strip(): + continue + print(line, end="", flush=True) + log.write(line) + log.flush() + output.append(line) + log.flush() + returncode = process.wait() + if returncode != 0: + raise RuntimeError( + f"esptool {command} failed with exit code {returncode}; see esptool.log." + ) + return "".join(output) + + +def port_identity(port: ListPortInfo) -> dict[str, str | int | None]: + return { + "device": port.device, + "description": port.description, + "hardware_id": port.hwid, + "usb_vid": port.vid, + "usb_pid": port.pid, + "usb_serial_number": port.serial_number, + "usb_location": port.location, + } + + +def backup(port: ListPortInfo, baud: int, root: Path) -> Path: + started = datetime.now(UTC) + directory = root / started.strftime("esp32-%Y%m%dT%H%M%S%fZ") + directory.mkdir(parents=True, exist_ok=False) + partial = directory / "full_flash.partial.bin" + image = directory / "full_flash.bin" + print(f"Backup directory: {directory}") + print("Device will reset into its serial bootloader. Flash is not written or erased.") + print("Close serial monitors first. Keep the device powered and USB connected.") + with (directory / "esptool.log").open("x", encoding="utf-8") as log: + identity = run_esptool(port.device, baud, "flash-id", [], log) + expected_size = flash_size_bytes(identity) + print(f"Reading all {expected_size:,} flash bytes; this may take several minutes.", flush=True) + run_esptool( + port.device, baud, "read-flash", ["0", "ALL", str(partial)], log, + ) + actual_size = partial.stat().st_size + if actual_size != expected_size: + raise ValueError( + f"Incomplete flash read: expected {expected_size} bytes, got {actual_size}." + ) + print("Read complete; verifying the entire image against the device.", flush=True) + run_esptool( + port.device, baud, "verify-flash", ["0", str(partial)], log, + ) + with partial.open("rb") as stream: + digest = hashlib.file_digest(stream, "sha256").hexdigest() + manifest = { + "status": "verified_against_device", + "started_utc": started.isoformat(), + "completed_utc": datetime.now(UTC).isoformat(), + "chip": "esp32", + "port": port_identity(port), + "baud": baud, + "esptool_version": version("esptool"), + "flash_size_bytes": expected_size, + "image": image.name, + "sha256": digest, + "verification": "esptool verify-flash against the complete device flash", + "includes_efuses": False, + } + partial.rename(image) + (directory / "manifest.json").write_text( + json.dumps(manifest, indent=2) + "\n", encoding="utf-8", + ) + print(f"\nVERIFIED: {image}\nSHA-256: {digest}") + print("Backup may contain credentials. Keep this directory private and out of Git.") + print("Press the board's EN/RESET button or reconnect USB to resume the old firmware.") + return directory + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--list", action="store_true", help="List serial ports; do not open them.") + parser.add_argument("--port", help="Explicit USB serial port, e.g. COM12; never guessed.") + parser.add_argument("--baud", type=int, default=115200, help="Serial baud (default: 115200).") + parser.add_argument( + "--output-dir", type=Path, default=DEFAULT_BACKUP_ROOT, + help="Backup parent directory (default: loadcell/backups, ignored by Git).", + ) + args = parser.parse_args(argv) + if args.list and args.port: + parser.error("--list and --port cannot be combined.") + if args.baud <= 0: + parser.error("--baud must be positive.") + if not args.list and not args.port: + parser.error("Use --list to identify the board, then --port COM_NUMBER to back it up.") + ports = list(list_ports.comports()) + if args.list: + print(json.dumps([port_identity(port) for port in ports], indent=2)) + return 0 + matches = [port for port in ports if port.device.casefold() == args.port.casefold()] + if len(matches) != 1: + parser.error("Selected port is not uniquely present. Run --list and identify the board.") + port = matches[0] + if port.vid is None or port.pid is None: + parser.error("Selected port has no USB VID/PID; connect and identify the USB adapter.") + try: + backup(port, args.baud, args.output_dir) + except (OSError, ValueError, RuntimeError) as error: + print(f"BACKUP FAILED: {error}", file=sys.stderr) + print( + "Do not flash based on this attempt. Partial files are not verified backups. " + "The board may remain in its bootloader; press EN/RESET to resume.", + file=sys.stderr, + ) + return 1 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/loadcell/include/config.h b/loadcell/include/config.h new file mode 100644 index 0000000..ab027cf --- /dev/null +++ b/loadcell/include/config.h @@ -0,0 +1,39 @@ +#pragma once + +#include +#include + +// Keep credentials in the ignored local header, never in this file. +#if __has_include("local_config.h") +#include "local_config.h" +#endif + +#ifndef LOADCELL_WIFI_SSID +#define LOADCELL_WIFI_SSID "" +#endif +#ifndef LOADCELL_WIFI_PASSWORD +#define LOADCELL_WIFI_PASSWORD "" +#endif +#ifndef LOADCELL_CSV_URL +#define LOADCELL_CSV_URL "" +#endif +#ifndef LOADCELL_OTA_PASSWORD +#define LOADCELL_OTA_PASSWORD "" +#endif + +namespace config { +constexpr uint8_t liftDataPin = 33; +constexpr uint8_t liftClockPin = 25; +constexpr uint8_t dragDataPin = 34; +constexpr uint8_t dragClockPin = 32; +constexpr uint16_t webPort = 88; +constexpr uint32_t sampleIntervalMs = 100; +constexpr uint32_t hx711TimeoutMs = 100; +constexpr size_t batchSize = 300; +constexpr size_t queueSize = 600; +constexpr uint32_t httpTimeoutMs = 3000; +constexpr uint32_t retryIntervalMs = 5000; +constexpr long utcOffsetSeconds = 3600; +constexpr char ntpServer[] = "pool.ntp.org"; + +} diff --git a/loadcell/include/hx711_input.h b/loadcell/include/hx711_input.h new file mode 100644 index 0000000..baf6871 --- /dev/null +++ b/loadcell/include/hx711_input.h @@ -0,0 +1,106 @@ +#pragma once + +#include +#include +#include + +enum class CaptureMode : uint8_t { Two = 2, Four = 4 }; +enum class Hx711ReadStatus { Ready, Settling, Timeout }; + +inline bool parseCaptureMode(const char *text, CaptureMode &mode) { + if (strcmp(text, "2") == 0) { + mode = CaptureMode::Two; + } else if (strcmp(text, "4") == 0) { + mode = CaptureMode::Four; + } else { + return false; + } + return true; +} + +class Hx711Input { +public: + template + Hx711ReadStatus read( + Adc &adc, Clock clock, uint32_t timeoutMs, uint8_t desiredGain, int32_t &raw + ) { + if (desiredGain != selectedGain) { + if (!adc.wait_ready_timeout(timeoutMs)) { + return Hx711ReadStatus::Timeout; + } + adc.set_gain(desiredGain); + // These trailing clock pulses select the NEXT conversion, not the value just read. + adc.read(); + selectedGain = desiredGain; + selectedAt = clock(); + return Hx711ReadStatus::Settling; + } + // Cover the datasheet's worst-case settling time at 10 samples/second. + if (static_cast(clock() - selectedAt) < 400) { + return Hx711ReadStatus::Settling; + } + if (!adc.wait_ready_timeout(timeoutMs)) { + return Hx711ReadStatus::Timeout; + } + raw = static_cast(adc.read()); + return Hx711ReadStatus::Ready; + } + +private: + uint8_t selectedGain = 0; + uint32_t selectedAt = 0; +}; + +struct CaptureValues { + CaptureMode mode; + bool secondary; + int32_t raw[2]; +}; + +inline uint8_t captureGain(const CaptureValues &values) { + return values.mode == CaptureMode::Two ? 128 : (values.secondary ? 32 : 64); +} + +inline const char *captureLabel(const CaptureValues &values, unsigned amplifier) { + if (values.mode == CaptureMode::Two) { + return amplifier == 0 ? "A" : "B"; + } + return amplifier == 0 ? (values.secondary ? "A2" : "A1") : + (values.secondary ? "B2" : "B1"); +} + +class CaptureAcquisition { +public: + std::atomic activeMode{0}; + + template + Hx711ReadStatus read( + Adc &first, Adc &second, Clock clock, uint32_t timeoutMs, + CaptureMode requested, CaptureValues &values + ) { + if (requested != mode) { + mode = requested; + secondary = false; + } + CaptureValues next{mode, secondary, {0, 0}}; + const uint8_t gain = captureGain(next); + const auto firstStatus = inputs[0].read(first, clock, timeoutMs, gain, next.raw[0]); + const auto secondStatus = inputs[1].read(second, clock, timeoutMs, gain, next.raw[1]); + if (firstStatus != Hx711ReadStatus::Ready || secondStatus != Hx711ReadStatus::Ready) { + activeMode.store(0); + return firstStatus == Hx711ReadStatus::Timeout || secondStatus == Hx711ReadStatus::Timeout ? + Hx711ReadStatus::Timeout : Hx711ReadStatus::Settling; + } + values = next; + activeMode.store(static_cast(mode)); + if (mode == CaptureMode::Four) { + secondary = !secondary; + } + return Hx711ReadStatus::Ready; + } + +private: + Hx711Input inputs[2]; + CaptureMode mode = CaptureMode::Two; + bool secondary = false; +}; diff --git a/loadcell/include/local_config.h.example b/loadcell/include/local_config.h.example new file mode 100644 index 0000000..e3a23d1 --- /dev/null +++ b/loadcell/include/local_config.h.example @@ -0,0 +1,6 @@ +#pragma once + +#define LOADCELL_WIFI_SSID "your-wifi-ssid" +#define LOADCELL_WIFI_PASSWORD "your-wifi-password" +#define LOADCELL_CSV_URL "" +#define LOADCELL_OTA_PASSWORD "" diff --git a/loadcell/include/ota.h b/loadcell/include/ota.h new file mode 100644 index 0000000..6ba22d8 --- /dev/null +++ b/loadcell/include/ota.h @@ -0,0 +1,4 @@ +#pragma once + +void setupOTA(); +void handleOTAClient(); diff --git a/loadcell/include/sample_csv.h b/loadcell/include/sample_csv.h new file mode 100644 index 0000000..aa4a783 --- /dev/null +++ b/loadcell/include/sample_csv.h @@ -0,0 +1,34 @@ +#pragma once + +#include +#include +#include +#include + +#include "hx711_input.h" + +constexpr char sampleCsvHeader[] = + "_rownum,_time,_time_unix_us,input,raw,gain\n"; + +struct Sample { + timeval timestamp; + uint32_t uptimeMs; + CaptureValues values; +}; + +inline int formatSampleCsv( + const Sample &sample, unsigned amplifier, uint32_t row, char *buffer, size_t capacity +) { + tm localTime; + if (localtime_r(&sample.timestamp.tv_sec, &localTime) == nullptr) { + return -1; + } + const uint64_t unixUs = static_cast(sample.timestamp.tv_sec) * 1000000 + + sample.timestamp.tv_usec; + return snprintf(buffer, capacity, + "%" PRIu32 ",%02d:%02d:%02d.%03ld,%" PRIu64 ",%s,%" PRId32 ",%u\n", + row, localTime.tm_hour, localTime.tm_min, localTime.tm_sec, + static_cast(sample.timestamp.tv_usec / 1000), unixUs, + captureLabel(sample.values, amplifier), sample.values.raw[amplifier], + static_cast(captureGain(sample.values))); +} diff --git a/loadcell/launch_config.cmd.example b/loadcell/launch_config.cmd.example new file mode 100644 index 0000000..ccb849b --- /dev/null +++ b/loadcell/launch_config.cmd.example @@ -0,0 +1,3 @@ +@rem Copy to launch_config.cmd (ignored by Git) and replace these example hosts. +@set "LOADCELL_DEVICE_URL=http://sensor-host.example:88" +@set "LINKHUB_CONNECTION=tcp:flight-controller.example:5760" diff --git a/loadcell/platformio.ini b/loadcell/platformio.ini new file mode 100644 index 0000000..d23ac3a --- /dev/null +++ b/loadcell/platformio.ini @@ -0,0 +1,14 @@ +[platformio] +default_envs = lolin_d32_pro + +[env:lolin_d32_pro] +platform = espressif32@6.9.0 +board = lolin_d32_pro +framework = arduino +monitor_speed = 115200 +upload_speed = 115200 +lib_deps = + bogde/HX711@0.7.5 +build_flags = + -Wall + -Wextra diff --git a/loadcell/src/main.cpp b/loadcell/src/main.cpp new file mode 100644 index 0000000..0faebd5 --- /dev/null +++ b/loadcell/src/main.cpp @@ -0,0 +1,354 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "config.h" +#include "ota.h" +#include "sample_csv.h" + +namespace { +constexpr time_t earliestValidTime = 1577836800; // 2020-01-01 UTC +static_assert(config::batchSize % 2 == 0, "CSV batches must contain complete amplifier pairs."); + +HX711 liftScale; +HX711 dragScale; +CaptureAcquisition acquisition; +std::atomic captureMode{CaptureMode::Two}; +WebServer server(config::webPort); +Preferences preferences; +QueueHandle_t samples; +QueueHandle_t latestSample; +std::atomic sampleIntervalMs{config::sampleIntervalMs}; +String destination; +String filename; +String batch; +size_t batchRows = 0; +uint32_t rowNumber = 0; +bool headerPending = true; +uint32_t lastPostAttempt = 0; + +[[noreturn]] void halt(const char *message) { + Serial.println(message); + for (;;) { + delay(1000); + } +} + +bool validDestination(const String &url) { + return url.startsWith("http://") && url.length() > 7 && + url.indexOf('#') < 0 && url.indexOf('\r') < 0 && + url.indexOf('\n') < 0 && url.indexOf('\'') < 0 && + url.indexOf('"') < 0 && url.indexOf('<') < 0 && + url.indexOf('>') < 0 && url.indexOf(' ') < 0; +} + +String htmlEscape(String value) { + value.replace("&", "&"); + value.replace("<", "<"); + value.replace(">", ">"); + value.replace("\"", """); + value.replace("'", "'"); + return value; +} + +bool postCsv(const String &content) { + if (WiFi.status() != WL_CONNECTED || destination.isEmpty()) { + Serial.println("CSV upload unavailable: check Wi-Fi and destination."); + return false; + } + HTTPClient http; + const String url = destination + + (destination.indexOf('?') >= 0 ? "&filename=" : "?filename=") + filename; + http.setConnectTimeout(config::httpTimeoutMs); + http.setTimeout(config::httpTimeoutMs); + if (!http.begin(url)) { + Serial.println("CSV upload failed: cannot initialize HTTP request."); + return false; + } + http.addHeader("Content-Type", "text/csv"); + const int status = http.POST(content); + http.end(); + if (status < 200 || status >= 300) { + Serial.printf("CSV upload failed: HTTP status/error %d; retaining batch.\n", status); + return false; + } + return true; +} + +bool flushBatch(bool includePartial = true) { + if (filename.isEmpty()) { + return false; + } + if (headerPending) { + if (!postCsv(sampleCsvHeader)) { + return false; + } + headerPending = false; + } + if (batchRows > 0 && (includePartial || batchRows == config::batchSize)) { + if (!postCsv(batch)) { + return false; + } + batch = ""; + batchRows = 0; + } + return true; +} + +void startFile(const timeval ×tamp) { + tm localTime; + localtime_r(×tamp.tv_sec, &localTime); + char name[96]; + // Milliseconds avoid collisions when rotating files within one second. + snprintf(name, sizeof(name), "%04d%02d%02d_%02d%02d%02d_%03ld_tpdata.csv", + localTime.tm_year + 1900, localTime.tm_mon + 1, localTime.tm_mday, + localTime.tm_hour, localTime.tm_min, localTime.tm_sec, + static_cast(timestamp.tv_usec / 1000)); + filename = name; + rowNumber = 0; + headerPending = true; + Serial.println("CSV file: " + filename); +} + +void appendSample(const Sample &sample) { + for (unsigned amplifier = 0; amplifier < 2; ++amplifier) { + char row[128]; + const int written = formatSampleCsv(sample, amplifier, rowNumber + 1, row, sizeof(row)); + if (written < 0 || static_cast(written) >= sizeof(row)) { + halt("Cannot format complete CSV sample."); + } + ++rowNumber; + batch += row; + ++batchRows; + } +} + +void acquireSamples(void *) { + uint32_t lastWarning = millis() - 10000; + for (;;) { + const uint32_t started = millis(); + Sample sample{}; + const auto status = acquisition.read(liftScale, dragScale, millis, + config::hx711TimeoutMs, captureMode.load(), sample.values); + if (status == Hx711ReadStatus::Timeout) { + if (millis() - lastWarning >= 10000) { + Serial.println("HX711 timeout; no paired readings emitted."); + lastWarning = millis(); + } + } else if (status == Hx711ReadStatus::Ready) { + gettimeofday(&sample.timestamp, nullptr); + sample.uptimeMs = millis(); + xQueueOverwrite(latestSample, &sample); + if (sample.timestamp.tv_sec < earliestValidTime) { + if (millis() - lastWarning >= 10000) { + Serial.println("Waiting for NTP time; no timestamped rows emitted."); + lastWarning = millis(); + } + } else if (xQueueSend(samples, &sample, 0) != pdTRUE) { + if (millis() - lastWarning >= 10000) { + Serial.println("CSV sample queue full; dropping new samples."); + lastWarning = millis(); + } + } + } + const uint32_t elapsed = millis() - started; + const uint32_t interval = sampleIntervalMs.load(); + delay(elapsed < interval ? interval - elapsed : 1); + } +} + +String hx711StatusJson() { + Sample sample; + const bool available = xQueuePeek(latestSample, &sample, 0) == pdTRUE; + String result = "{\"requested_mode\":" + String(static_cast(captureMode.load())) + + ",\"active_mode\":" + String(acquisition.activeMode.load()) + ",\"last_sample\":"; + if (!available) { + return result + "null}"; + } + result += "{\"mode\":" + String(static_cast(sample.values.mode)) + + ",\"age_ms\":" + String(static_cast(millis() - sample.uptimeMs)) + + ",\"time_synchronized\":" + + (sample.timestamp.tv_sec >= earliestValidTime ? "true" : "false") + ",\"readings\":["; + for (unsigned amplifier = 0; amplifier < 2; ++amplifier) { + if (amplifier != 0) { + result += ","; + } + result += String("{\"input\":\"") + captureLabel(sample.values, amplifier) + + "\",\"raw\":" + String(sample.values.raw[amplifier]) + + ",\"gain\":" + String(captureGain(sample.values)) + "}"; + } + return result + "]}}"; +} + +void setupWeb() { + server.on("/", HTTP_GET, [] { + String page = "" + "RAWES Loadcell

RAWES Loadcell

"; + page += "

Two HX711 amplifiers. Sample interval: " + + String(sampleIntervalMs.load()) + " ms. File: " + htmlEscape(filename) + "

"; + page += "
" + "
"; + page += "
" + "
"; + page += "

Capture mode

Raw ADC counts only; " + "calibration belongs to the receiver. Live status

"; + const bool four = captureMode.load() == CaptureMode::Four; + page += String("
" + "
" + "

Four-input mode alternates inputs with settling; readings are not simultaneous.

"; + page += ""; + server.send(200, "text/html", page); + }); + server.on("/hx711", HTTP_GET, [] { + server.send(200, "application/json", hx711StatusJson()); + }); + server.on("/set_hx711", HTTP_GET, [] { + CaptureMode mode; + if (!parseCaptureMode(server.arg("mode").c_str(), mode)) { + server.send(400, "text/plain", "Use mode=2 or mode=4."); + return; + } + if (preferences.putUChar("capture_mode", static_cast(mode)) != sizeof(uint8_t)) { + Serial.println("Failed to persist HX711 mode."); + server.send(500, "text/plain", "Failed to persist HX711 mode."); + return; + } + captureMode.store(mode); + server.send(202, "application/json", hx711StatusJson()); + }); + server.on("/setSamplingRate", HTTP_GET, [] { + const String value = server.arg("val"); + bool digitsOnly = !value.isEmpty() && value.length() <= 5; + for (size_t i = 0; i < value.length(); ++i) { + digitsOnly = digitsOnly && value[i] >= '0' && value[i] <= '9'; + } + const long interval = value.toInt(); + if (!digitsOnly || interval < 10 || interval > 60000) { + server.send(400, "text/plain", "val must be an interval of 10..60000 ms."); + return; + } + if (preferences.putUInt("interval_ms", interval) != sizeof(uint32_t)) { + Serial.println("Failed to persist sample interval."); + server.send(500, "text/plain", "Failed to persist sample interval."); + return; + } + sampleIntervalMs.store(interval); + server.send(200, "text/plain", "Sample interval saved (ms): " + value); + }); + server.on("/create_new_csv", HTTP_GET, [] { + const String url = server.arg("url"); + if (!validDestination(url)) { + server.send(400, "text/plain", "url must be a plain HTTP CSV endpoint."); + return; + } + timeval now; + gettimeofday(&now, nullptr); + if (now.tv_sec < earliestValidTime) { + server.send(503, "text/plain", "Waiting for NTP time."); + return; + } + if (!filename.isEmpty() && !flushBatch()) { + server.send(503, "text/plain", "Cannot flush old CSV; destination unchanged."); + return; + } + if (preferences.putString("csv_url", url) != url.length()) { + Serial.println("Failed to persist CSV destination."); + server.send(500, "text/plain", "Failed to persist CSV destination."); + return; + } + destination = url; + startFile(now); + server.send(200, "text/plain", "CSV destination saved; new CSV queued."); + }); + server.begin(); +} +} + +void setup() { + Serial.begin(115200); + if (!preferences.begin("rawes-loadcell", false)) { + halt("Cannot open loadcell configuration in NVS."); + } + destination = preferences.getString("csv_url", LOADCELL_CSV_URL); + if (!destination.isEmpty() && !validDestination(destination)) { + halt("Invalid CSV destination in configuration."); + } + const uint32_t interval = preferences.getUInt("interval_ms", config::sampleIntervalMs); + if (interval < 10 || interval > 60000) { + halt("Invalid sample interval in NVS."); + } + sampleIntervalMs.store(interval); + const uint8_t mode = preferences.getUChar("capture_mode", 2); + if (mode != 2 && mode != 4) { + halt("Invalid capture mode in NVS."); + } + captureMode.store(static_cast(mode)); + samples = xQueueCreate(config::queueSize, sizeof(Sample)); + latestSample = xQueueCreate(1, sizeof(Sample)); + if (samples == nullptr || latestSample == nullptr || !batch.reserve(config::batchSize * 128)) { + halt("Cannot allocate CSV buffers."); + } + liftScale.begin(config::liftDataPin, config::liftClockPin); + dragScale.begin(config::dragDataPin, config::dragClockPin); + + WiFi.mode(WIFI_STA); + WiFi.setAutoReconnect(true); + if (strlen(LOADCELL_WIFI_SSID) == 0) { + Serial.println("Wi-Fi SSID missing: create include/local_config.h and rebuild."); + } else { + WiFi.begin(LOADCELL_WIFI_SSID, LOADCELL_WIFI_PASSWORD); + } + configTime(config::utcOffsetSeconds, 0, config::ntpServer); + setupWeb(); + setupOTA(); + if (xTaskCreatePinnedToCore(acquireSamples, "loadcell_sampling", 4096, + nullptr, 1, nullptr, 1) != pdPASS) { + halt("Cannot create loadcell sampling task."); + } + Serial.println("RAWES loadcell started; web configuration on port 88."); +} + +void loop() { + handleOTAClient(); + server.handleClient(); + static bool wasConnected = false; + const bool connected = WiFi.status() == WL_CONNECTED; + if (connected != wasConnected) { + Serial.println(connected ? "Wi-Fi connected: " + WiFi.localIP().toString() : + "Wi-Fi disconnected; CSV upload paused."); + wasConnected = connected; + } + if (filename.isEmpty() && !destination.isEmpty()) { + timeval now; + gettimeofday(&now, nullptr); + if (now.tv_sec >= earliestValidTime) { + startFile(now); + } + } + if (!filename.isEmpty()) { + Sample sample; + while (batchRows < config::batchSize && xQueueReceive(samples, &sample, 0) == pdTRUE) { + appendSample(sample); + } + if ((headerPending || batchRows == config::batchSize) && + millis() - lastPostAttempt >= config::retryIntervalMs) { + lastPostAttempt = millis(); + flushBatch(false); + } + } + delay(2); +} diff --git a/loadcell/src/ota.cpp b/loadcell/src/ota.cpp new file mode 100644 index 0000000..8f3078e --- /dev/null +++ b/loadcell/src/ota.cpp @@ -0,0 +1,108 @@ +#include +#include +#include + +#include "config.h" +#include "ota.h" + +namespace { +WebServer otaServer(80); +bool enabled = false; +bool uploading = false; +bool completed = false; + +bool authorized() { + return otaServer.authenticate("admin", LOADCELL_OTA_PASSWORD); +} + +void serveUploadForm() { + if (!authorized()) { + otaServer.requestAuthentication(); + return; + } + otaServer.send(200, "text/html", + "RAWES firmware update" + "

ESP32 firmware update

" + "

Upload the PlatformIO firmware.bin for this board. " + "A successful update reboots the sensor and discards pending samples.

" + "
" + "" + "
"); +} + +void receiveUpload() { + if (!authorized()) { + return; + } + HTTPUpload &upload = otaServer.upload(); + switch (upload.status) { + case UPLOAD_FILE_START: + completed = false; + uploading = Update.begin(UPDATE_SIZE_UNKNOWN, U_FLASH); + if (!uploading) { + Update.printError(Serial); + } else { + Serial.println("OTA firmware upload started."); + } + break; + case UPLOAD_FILE_WRITE: + if (uploading && Update.write(upload.buf, upload.currentSize) != upload.currentSize) { + Update.printError(Serial); + Update.abort(); + uploading = false; + } + break; + case UPLOAD_FILE_END: + if (uploading) { + completed = Update.end(true); + if (!completed) { + Update.printError(Serial); + } + uploading = false; + } + break; + case UPLOAD_FILE_ABORTED: + if (uploading) { + Update.abort(); + } + uploading = false; + completed = false; + Serial.println("OTA upload aborted; not rebooting."); + break; + } +} +} + +void setupOTA() { + if (strlen(LOADCELL_OTA_PASSWORD) == 0) { + Serial.println("OTA disabled: set LOADCELL_OTA_PASSWORD in include/local_config.h."); + return; + } + otaServer.on("/", HTTP_GET, serveUploadForm); + otaServer.on("/serverIndex", HTTP_GET, serveUploadForm); + otaServer.on("/update", HTTP_POST, [] { + if (!authorized()) { + otaServer.requestAuthentication(); + return; + } + otaServer.sendHeader("Connection", "close"); + if (!completed) { + Serial.println("OTA update failed or no complete firmware received; not rebooting."); + otaServer.send(400, "text/plain", "Firmware update failed; device not rebooted."); + return; + } + otaServer.send(200, "text/plain", "Firmware installed; rebooting."); + Serial.println("OTA update complete; rebooting."); + delay(500); + ESP.restart(); + }, receiveUpload); + otaServer.begin(); + enabled = true; + Serial.println("Password-protected OTA available on port 80 (username: admin)."); +} + +void handleOTAClient() { + if (enabled) { + otaServer.handleClient(); + } +} diff --git a/loadcell/test/test_hx711.cpp b/loadcell/test/test_hx711.cpp new file mode 100644 index 0000000..f41602d --- /dev/null +++ b/loadcell/test/test_hx711.cpp @@ -0,0 +1,172 @@ +#include +#include +#include + +#include "sample_csv.h" + +namespace { +uint32_t now = 0; + +struct Adc { + uint8_t currentGain = 32; + uint8_t nextGain = 32; + bool ready = true; + int reads = 0; + + bool wait_ready_timeout(uint32_t) { + now += 10; + return ready; + } + + void set_gain(uint8_t gain) { + nextGain = gain; + } + + int32_t read() { + ++reads; + const int32_t value = currentGain == 128 ? -128 : currentGain; + currentGain = nextGain; + return value; + } +}; + +uint32_t clockMs() { + return now; +} + +void switchingDiscardsPreviousChannelAndWaitsForSettling() { + now = 0; + Adc adc; + Hx711Input input; + int32_t raw = 999; + assert(input.read(adc, clockMs, 100, 128, raw) == Hx711ReadStatus::Settling); + assert(raw == 999 && adc.reads == 1); + now = 409; + assert(input.read(adc, clockMs, 100, 128, raw) == Hx711ReadStatus::Settling); + now = 410; + assert(input.read(adc, clockMs, 100, 128, raw) == Hx711ReadStatus::Ready); + assert(raw == -128); + + assert(input.read(adc, clockMs, 100, 32, raw) == Hx711ReadStatus::Settling); + assert(raw == -128); + now += 400; + assert(input.read(adc, clockMs, 100, 32, raw) == Hx711ReadStatus::Ready); + assert(raw == 32); + + assert(input.read(adc, clockMs, 100, 64, raw) == Hx711ReadStatus::Settling); + now += 400; + assert(input.read(adc, clockMs, 100, 64, raw) == Hx711ReadStatus::Ready); + assert(raw == 64); +} + +void failedReadAndReplacementRequestNeverPublishWrongMode() { + now = UINT32_MAX - 100; + Adc adc; + Hx711Input input; + int32_t raw = 999; + adc.ready = false; + assert(input.read(adc, clockMs, 100, 128, raw) == Hx711ReadStatus::Timeout); + assert(adc.reads == 0 && raw == 999); + adc.ready = true; + assert(input.read(adc, clockMs, 100, 128, raw) == Hx711ReadStatus::Settling); + now += 50; + assert(input.read(adc, clockMs, 100, 32, raw) == Hx711ReadStatus::Settling); + now += 399; + assert(input.read(adc, clockMs, 100, 32, raw) == Hx711ReadStatus::Settling); + ++now; + assert(input.read(adc, clockMs, 100, 32, raw) == Hx711ReadStatus::Ready); + assert(raw == 32); + adc.ready = false; + assert(input.read(adc, clockMs, 100, 32, raw) == Hx711ReadStatus::Timeout); +} + +void captureAlternatesAllFourAndRestartsCleanlyAfterModeChange() { + now = 0; + Adc first, second; + CaptureAcquisition capture; + CaptureValues values{}; + const auto poll = [&](CaptureMode mode) { + return capture.read(first, second, clockMs, 100, mode, values); + }; + assert(poll(CaptureMode::Two) == Hx711ReadStatus::Settling); + now += 420; + assert(poll(CaptureMode::Two) == Hx711ReadStatus::Ready); + assert(captureGain(values) == 128 && values.raw[0] == -128 && values.raw[1] == -128); + assert(std::string(captureLabel(values, 0)) == "A"); + assert(std::string(captureLabel(values, 1)) == "B"); + assert(poll(CaptureMode::Two) == Hx711ReadStatus::Ready); + + assert(poll(CaptureMode::Four) == Hx711ReadStatus::Settling); + assert(capture.activeMode.load() == 0); + now += 420; + assert(poll(CaptureMode::Four) == Hx711ReadStatus::Ready); + const CaptureValues queued = values; + for (unsigned phase = 0; phase < 4; ++phase) { + assert(values.mode == CaptureMode::Four); + assert(values.secondary == (phase % 2 != 0)); + assert(captureGain(values) == (values.secondary ? 32 : 64)); + assert(values.raw[0] == captureGain(values) && values.raw[1] == captureGain(values)); + assert(std::string(captureLabel(values, 0)) == (values.secondary ? "A2" : "A1")); + assert(std::string(captureLabel(values, 1)) == (values.secondary ? "B2" : "B1")); + assert(poll(CaptureMode::Four) == Hx711ReadStatus::Settling); + now += 420; + if (phase == 0) { + second.ready = false; + assert(poll(CaptureMode::Four) == Hx711ReadStatus::Timeout); + assert(capture.activeMode.load() == 0); + assert(!values.secondary); + second.ready = true; + } + assert(poll(CaptureMode::Four) == Hx711ReadStatus::Ready); + } + // Interrupt a pending secondary conversion with a return to two-input capture. + assert(poll(CaptureMode::Four) == Hx711ReadStatus::Settling); + assert(poll(CaptureMode::Two) == Hx711ReadStatus::Settling); + now += 420; + assert(poll(CaptureMode::Two) == Hx711ReadStatus::Ready); + assert(values.mode == CaptureMode::Two && captureGain(values) == 128); + assert(values.raw[0] == -128 && values.raw[1] == -128); + assert(queued.mode == CaptureMode::Four && captureGain(queued) == 64); +} + +void csvPreservesSignedCountsAndPerSampleModes() { + Sample sample{{1735689600, 123456}, 0, {CaptureMode::Two, false, {-8388608, 8388607}}}; + char row[128]; + const int written = formatSampleCsv(sample, 0, 1, row, sizeof(row)); + assert(written > 0 && static_cast(written) < sizeof(row)); + assert(std::string(row) == + "1,00:00:00.123,1735689600123456,A,-8388608,128\n"); + assert(formatSampleCsv(sample, 1, 2, row, sizeof(row)) > 0); + assert(std::string(row) == "2,00:00:00.123,1735689600123456,B,8388607,128\n"); + sample.values = {CaptureMode::Four, false, {17, -42}}; + assert(formatSampleCsv(sample, 0, 3, row, sizeof(row)) > 0); + assert(std::string(row) == "3,00:00:00.123,1735689600123456,A1,17,64\n"); + assert(formatSampleCsv(sample, 1, 4, row, sizeof(row)) > 0); + assert(std::string(row) == "4,00:00:00.123,1735689600123456,B1,-42,64\n"); + sample.values.secondary = true; + assert(formatSampleCsv(sample, 0, 5, row, sizeof(row)) > 0); + assert(std::string(row) == "5,00:00:00.123,1735689600123456,A2,17,32\n"); + assert(formatSampleCsv(sample, 1, 6, row, sizeof(row)) > 0); + assert(std::string(row) == "6,00:00:00.123,1735689600123456,B2,-42,32\n"); + char tooSmall[8]; + assert(formatSampleCsv(sample, 1, 6, tooSmall, sizeof(tooSmall)) >= + static_cast(sizeof(tooSmall))); +} +} + +int main() { + setenv("TZ", "UTC", 1); + tzset(); + CaptureMode mode = CaptureMode::Two; + assert(parseCaptureMode("4", mode) && mode == CaptureMode::Four); + assert(parseCaptureMode("2", mode) && mode == CaptureMode::Two); + for (const char *invalid : {"", "A128", "0", "3", "02", "4extra", " 4"}) { + assert(!parseCaptureMode(invalid, mode)); + assert(mode == CaptureMode::Two); + } + switchingDiscardsPreviousChannelAndWaitsForSettling(); + failedReadAndReplacementRequestNeverPublishWrongMode(); + captureAlternatesAllFourAndRestartsCleanlyAfterModeChange(); + csvPreservesSignedCountsAndPerSampleModes(); + puts("PASS: two/four-input capture, switching, settling, timeout, and raw CSV tests."); +} diff --git a/run_linkhub_esp.cmd b/run_linkhub_esp.cmd new file mode 100644 index 0000000..9ed652b --- /dev/null +++ b/run_linkhub_esp.cmd @@ -0,0 +1,23 @@ +@echo off +setlocal + +if exist "%~dp0loadcell\launch_config.cmd" call "%~dp0loadcell\launch_config.cmd" +if not defined LOADCELL_DEVICE_URL ( + echo ERROR: Set LOADCELL_DEVICE_URL or create loadcell\launch_config.cmd from its example. + exit /b 2 +) +if not defined LINKHUB_CONNECTION ( + echo ERROR: Set LINKHUB_CONNECTION or create loadcell\launch_config.cmd from its example. + exit /b 2 +) + +set "LINKHUB_CSV_MAP=%~dp0linkhub\csv-map.json" + +call powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0scripts\configure_esp_csv.ps1" -DeviceUrl "%LOADCELL_DEVICE_URL%" -HttpPort 8999 +if errorlevel 1 ( + echo ERROR: ESP CSV configuration failed. LinkHub was not started. + exit /b 1 +) + +call "%~dp0run_linkhub_ui.cmd" %* "%LINKHUB_CONNECTION%" auto 8999 +exit /b %ERRORLEVEL% diff --git a/scripts/configure_esp_csv.ps1 b/scripts/configure_esp_csv.ps1 new file mode 100644 index 0000000..28df004 --- /dev/null +++ b/scripts/configure_esp_csv.ps1 @@ -0,0 +1,62 @@ +param( + [Parameter(Mandatory = $true)] + [uri]$DeviceUrl, + [ValidateRange(1, 65535)] + [int]$HttpPort = 8999 +) + +$ErrorActionPreference = 'Stop' +$route = [Net.Sockets.Socket]::new( + [Net.Sockets.AddressFamily]::InterNetwork, + [Net.Sockets.SocketType]::Dgram, + [Net.Sockets.ProtocolType]::Udp +) +try { + $route.Connect($DeviceUrl.Host, $DeviceUrl.Port) + $localAddress = $route.LocalEndPoint.Address.ToString() +} +finally { + $route.Dispose() +} + +$target = "http://${localAddress}:${HttpPort}/v1/csv" + +function Get-CsvDestination { + $page = Invoke-WebRequest -UseBasicParsing -Uri ([uri]::new($DeviceUrl, '/')) -TimeoutSec 15 + $match = [regex]::Match( + $page.Content, + ']*\bid=[''"]CSVStorageURL[''"][^>]*\bvalue=[''"]([^''"]*)[''"]' + ) + if (-not $match.Success) { + throw 'ESP configuration page did not contain the CSV destination.' + } + return [Net.WebUtility]::HtmlDecode($match.Groups[1].Value) +} + +if ((Get-CsvDestination) -ne $target) { + $commandUrl = [uri]::new($DeviceUrl, '/create_new_csv').AbsoluteUri + + '?url=' + [uri]::EscapeDataString($target) + Invoke-WebRequest -UseBasicParsing -Uri $commandUrl -TimeoutSec 15 | Out-Null +} +else { + Write-Host '[INFO] ESP CSV destination is already correct; preserving its current file and pending samples.' +} + +if ((Get-CsvDestination) -ne $target) { + throw "ESP CSV destination read-back did not match $target." +} + +$modeUrl = [uri]::new($DeviceUrl, '/set_hx711').AbsoluteUri + '?mode=4' +$modeResponse = Invoke-WebRequest -UseBasicParsing -Uri $modeUrl -TimeoutSec 15 +if ($modeResponse.StatusCode -ne 202 -or + ($modeResponse.Content | ConvertFrom-Json).requested_mode -ne 4) { + throw 'ESP did not accept four-input capture mode.' +} +$status = Invoke-RestMethod -Uri ([uri]::new($DeviceUrl, '/hx711')) -TimeoutSec 15 +if ($status.requested_mode -ne 4) { + throw 'ESP four-input capture mode read-back did not match.' +} + +Write-Host "[INFO] Verified ESP CSV destination: $target" +Write-Host '[INFO] Verified ESP capture mode: 4 inputs (A1, A2, B1, B2).' +Write-Host '[INFO] Destination and capture mode remain configured after LinkHub stops. Motion and sample interval are unchanged.' diff --git a/tests/unit/test_backup_esp32.py b/tests/unit/test_backup_esp32.py new file mode 100644 index 0000000..62a1809 --- /dev/null +++ b/tests/unit/test_backup_esp32.py @@ -0,0 +1,191 @@ +import hashlib +import io +import json +from pathlib import Path +import re +from typing import TextIO +from unittest.mock import MagicMock + +import pytest +from serial.tools.list_ports_common import ListPortInfo + +from loadcell import backup_esp32 + + +@pytest.fixture +def usb_port() -> ListPortInfo: + port = ListPortInfo("COM42") + port.vid = 0x10C4 + port.pid = 0xEA60 + port.serial_number = "test-board" + return port + + +@pytest.mark.parametrize("size,expected", [("4MB", 4194304), ("16 MB", 16777216), ("512KB", 524288)]) +def test_detected_flash_size(size: str, expected: int) -> None: + assert backup_esp32.flash_size_bytes(f"Device: 4016\nDetected flash size: {size}\n") == expected + + +@pytest.mark.parametrize("output", ["Detected flash size: Unknown", "", "Detected flash size: 0MB"]) +def test_unknown_flash_size_is_not_guessed(output: str) -> None: + with pytest.raises(ValueError): + backup_esp32.flash_size_bytes(output) + + +@pytest.mark.parametrize("failure", [None, "short-read", "verify-failed"]) +def test_backup_requires_complete_verified_image( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, usb_port: ListPortInfo, failure: str | None, +) -> None: + image = bytes(range(256)) * 4 + commands: list[str] = [] + + def fake_esptool( + port: str, baud: int, command: str, arguments: list[str], log: TextIO, + ) -> str: + commands.append(command) + assert port == "COM42" + assert baud == 115200 + if command == "flash-id": + return "Detected flash size: 1KB\n" + if command == "read-flash": + assert arguments[:2] == ["0", "ALL"] + assert len(arguments) == 3 + Path(arguments[2]).write_bytes(image[:-1] if failure == "short-read" else image) + if command == "verify-flash": + assert Path(arguments[1]).read_bytes() == image + if failure == "verify-failed": + raise RuntimeError("Verification mismatch") + return "" + + monkeypatch.setattr(backup_esp32, "run_esptool", fake_esptool) + monkeypatch.setattr(backup_esp32, "version", lambda _: "test-version") + if failure: + with pytest.raises((ValueError, RuntimeError)): + backup_esp32.backup(usb_port, 115200, tmp_path) + directory, = tmp_path.iterdir() + assert (directory / "full_flash.partial.bin").exists() + assert not (directory / "full_flash.bin").exists() + assert not (directory / "manifest.json").exists() + if failure == "short-read": + assert commands == ["flash-id", "read-flash"] + else: + directory = backup_esp32.backup(usb_port, 115200, tmp_path) + assert (directory / "full_flash.bin").read_bytes() == image + manifest = json.loads((directory / "manifest.json").read_text()) + assert manifest["status"] == "verified_against_device" + assert manifest["sha256"] == hashlib.sha256(image).hexdigest() + assert manifest["flash_size_bytes"] == len(image) + assert commands == ["flash-id", "read-flash", "verify-flash"] + + +def test_unknown_capacity_never_reads_flash( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, usb_port: ListPortInfo, +) -> None: + commands: list[str] = [] + + def fake_esptool( + port: str, baud: int, command: str, arguments: list[str], log: TextIO, + ) -> str: + commands.append(command) + return "Detected flash size: Unknown" + + monkeypatch.setattr(backup_esp32, "run_esptool", fake_esptool) + with pytest.raises(ValueError, match="refusing to guess"): + backup_esp32.backup(usb_port, 115200, tmp_path) + assert commands == ["flash-id"] + + +def test_write_commands_are_rejected(tmp_path: Path) -> None: + with (tmp_path / "log").open("w") as log, pytest.raises(ValueError, match="not read-only"): + backup_esp32.run_esptool("COM42", 115200, "write-flash", [], log) + + +def test_read_progress_reports_each_five_percent_once( + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], +) -> None: + lines = [ + "Reading from 0x00000031 [] 5.0% 49/1000 bytes...\n", + "Reading from 0x00000032 [] 5.0% 50/1000 bytes...\n", + "\n", + "Reading from 0x00000033 [] 5.1% 51/1000 bytes...\n", + "Reading from 0x0000015d [] 34.9% 349/1000 bytes...\n", + "Reading from 0x0000015e [] 35.0% 350/1000 bytes...\n", + "Reading from 0x000003e8 [] 100.0% 1000/1000 bytes...\n", + "Read complete.\n", + ] + process = MagicMock() + process.__enter__.return_value = process + process.stdout = iter(lines) + process.wait.return_value = 0 + popen = MagicMock(return_value=process) + monkeypatch.setattr(backup_esp32.subprocess, "Popen", popen) + log = io.StringIO() + + backup_esp32.run_esptool("COM42", 115200, "read-flash", ["0", "ALL", "image.bin"], log) + + output = capsys.readouterr().out + assert [int(value) for value in re.findall(r"Flash read: (\d+)%", output)] == list(range(5, 101, 5)) + assert "Flash read: 5% (50/1,000 bytes)" in output + assert "Flash read: 35% (350/1,000 bytes)" in output + assert "Reading from" not in output + assert "Read complete." in output + assert log.getvalue().endswith(output) + assert popen.call_args.args[0][:4] == [backup_esp32.sys.executable, "-u", "-m", "esptool"] + + +def test_failed_read_keeps_progress_and_errors_without_claiming_completion( + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], +) -> None: + process = MagicMock() + process.__enter__.return_value = process + process.stdout = iter([ + "Reading from 0x00000032 [] 5.0% 50/1000 bytes...\n", + "A fatal error occurred: Serial data stream stopped.\n", + ]) + process.wait.return_value = 2 + monkeypatch.setattr(backup_esp32.subprocess, "Popen", MagicMock(return_value=process)) + log = io.StringIO() + + with pytest.raises(RuntimeError, match="read-flash failed"): + backup_esp32.run_esptool("COM42", 115200, "read-flash", ["0", "ALL", "image.bin"], log) + + output = capsys.readouterr().out + assert "Flash read: 5%" in output + assert "100%" not in output + assert "Serial data stream stopped" in output + assert "Serial data stream stopped" in log.getvalue() + + +def test_missing_port_does_not_discover_or_connect(monkeypatch: pytest.MonkeyPatch) -> None: + def forbidden() -> None: + pytest.fail("Port discovery should not run without an explicit action") + + monkeypatch.setattr(backup_esp32.list_ports, "comports", forbidden) + with pytest.raises(SystemExit) as error: + backup_esp32.main([]) + assert error.value.code == 2 + + +def test_listing_does_not_open_ports( + monkeypatch: pytest.MonkeyPatch, usb_port: ListPortInfo, capsys: pytest.CaptureFixture[str], +) -> None: + monkeypatch.setattr(backup_esp32.list_ports, "comports", lambda: [usb_port]) + + def forbidden(*args: object) -> None: + pytest.fail("Listing must not start a backup") + + monkeypatch.setattr(backup_esp32, "backup", forbidden) + assert backup_esp32.main(["--list"]) == 0 + assert json.loads(capsys.readouterr().out)[0]["device"] == "COM42" + + +@pytest.mark.parametrize("connected", [False, True]) +def test_absent_or_non_usb_port_is_rejected( + monkeypatch: pytest.MonkeyPatch, usb_port: ListPortInfo, connected: bool, +) -> None: + usb_port.vid = None + usb_port.pid = None + monkeypatch.setattr(backup_esp32.list_ports, "comports", lambda: [usb_port] if connected else []) + with pytest.raises(SystemExit) as error: + backup_esp32.main(["--port", "COM42"]) + assert error.value.code == 2 diff --git a/tests/unit/test_windows_setup.py b/tests/unit/test_windows_setup.py index a283b93..67ecfdf 100644 --- a/tests/unit/test_windows_setup.py +++ b/tests/unit/test_windows_setup.py @@ -2,13 +2,16 @@ import os import hashlib +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer import json from pathlib import Path import shutil import subprocess import sys import textwrap +from threading import Thread import tomllib +from urllib.parse import parse_qs, urlsplit import pytest @@ -188,6 +191,112 @@ def commands(bootstrap: tuple[Path, Path, Path, dict[str, str]]) -> list[str]: return log.read_text().splitlines() if log.exists() else [] +@WINDOWS_ONLY +@pytest.mark.parametrize("configure_fails", [False, True]) +def test_esp_launcher_configures_csv_and_preserves_configured_connection( + bootstrap: tuple[Path, Path, Path, dict[str, str]], configure_fails: bool, +): + project, bin_dir, _, env = bootstrap + shutil.copy2(REPO / "run_linkhub_esp.cmd", project / "run_linkhub_esp.cmd") + env["MOCK_CONFIGURE_FAILS"] = str(int(configure_fails)) + env["LOADCELL_DEVICE_URL"] = "http://sensor-host.example:88" + env["LINKHUB_CONNECTION"] = "tcp:flight-controller.example:5760" + write_cmd(bin_dir / "powershell.cmd", r""" + @echo off + echo configure %*>>"%MOCK_LOG%" + exit /b %MOCK_CONFIGURE_FAILS% + """) + write_cmd(project / "run_linkhub_ui.cmd", r""" + @echo off + echo launcher %*>>"%MOCK_LOG%" + echo mapping %LINKHUB_CSV_MAP%>>"%MOCK_LOG%" + exit /b 17 + """) + result = run_script(bootstrap, "run_linkhub_esp.cmd", "--configure-firewall", "--build") + calls = commands(bootstrap) + assert '-DeviceUrl "http://sensor-host.example:88" -HttpPort 8999' in calls[0] + if configure_fails: + assert result.returncode == 1 + assert len(calls) == 1 + assert "LinkHub was not started" in result.stdout + else: + assert result.returncode == 17 + assert calls[1] == 'launcher --configure-firewall --build "tcp:flight-controller.example:5760" auto 8999' + assert calls[2] == f"mapping {project / 'linkhub' / 'csv-map.json'}" + + +@WINDOWS_ONLY +@pytest.mark.parametrize( + ("already_configured", "readback_matches", "mode_applies"), + [(False, True, True), (True, True, True), (False, False, True), (True, True, False)], + ids=["new-destination", "unchanged-destination", "destination-mismatch", "mode-mismatch"], +) +def test_esp_csv_configuration_verifies_routed_destination( + already_configured: bool, readback_matches: bool, mode_applies: bool, +): + requests: list[str] = [] + destination = "http://127.0.0.1:9123/v1/csv" if already_configured else "" + page_reads = 0 + + class Handler(BaseHTTPRequestHandler): + def do_GET(self): + nonlocal destination, page_reads + requests.append(self.path) + url = urlsplit(self.path) + status = 200 + if url.path == "/create_new_csv": + assert not already_configured, "Must not rotate/flush an unchanged destination." + destination = parse_qs(url.query)["url"][0] + body = b"Set URL" + elif url.path in ("/set_hx711", "/hx711"): + if url.path == "/set_hx711": + assert parse_qs(url.query) == {"mode": ["4"]} + status = 202 + body = json.dumps({"requested_mode": 4 if mode_applies else 2}).encode() + else: + page_reads += 1 + value = destination if page_reads == 1 or readback_matches else "http://old.example/csv" + body = f"".encode() + self.send_response(status) + content_type = "application/json" if url.path in ("/set_hx711", "/hx711") else "text/html" + self.send_header("Content-Type", f"{content_type}; charset=utf-8") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, format: str, *args: object) -> None: + pass + + server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + thread = Thread(target=server.serve_forever) + thread.start() + try: + result = subprocess.run( + ["powershell.exe", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", + str(REPO / "scripts" / "configure_esp_csv.ps1"), + "-DeviceUrl", f"http://127.0.0.1:{server.server_port}", "-HttpPort", "9123"], + capture_output=True, text=True, timeout=20, + ) + finally: + server.shutdown() + server.server_close() + thread.join() + assert destination == "http://127.0.0.1:9123/v1/csv" + expected = ["/"] + ([] if already_configured else ["/create_new_csv"]) + ["/"] + if readback_matches: + expected += ["/set_hx711"] + if mode_applies: + expected += ["/hx711"] + assert [urlsplit(path).path for path in requests] == expected + if readback_matches and mode_applies: + assert result.returncode == 0, result.stdout + result.stderr + assert f"Verified ESP CSV destination: {destination}" in result.stdout + assert "Verified ESP capture mode: 4 inputs" in result.stdout + else: + assert result.returncode != 0 + assert ("capture mode" if readback_matches else "read-back did not match") in result.stderr + + @WINDOWS_ONLY def test_setup_bootstraps_all_missing_tools_without_python( bootstrap: tuple[Path, Path, Path, dict[str, str]],