diff --git a/design/linkhub.md b/design/linkhub.md
index 5e5bd3a..43fae88 100644
--- a/design/linkhub.md
+++ b/design/linkhub.md
@@ -149,6 +149,25 @@ Before any vehicle heartbeat, MAVLink status has an empty `base_mode` mask and
vehicle. Consumers must still use connection/readiness and observed heartbeats
to distinguish unknown state from confirmed disarmed state.
+### Configured CSV feeds
+
+`--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
+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
+measurements.
+
+Accepted rows become ordinary `diagnostic.event` records with event `csv.sample`
+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
+of MAVLink readiness. It never commands or reconfigures the sending device.
+See [CSV usage and mapping format](../linkhub/README.md#generic-csv-ingestion).
+
### Bluetooth bench motor
`--motor-name-prefix` enables the external rotor-drive backend. It starts
diff --git a/linkhub-ui/README.md b/linkhub-ui/README.md
index 22ca886..40cf250 100644
--- a/linkhub-ui/README.md
+++ b/linkhub-ui/README.md
@@ -7,6 +7,19 @@ JavaScript numbers represent all supported Int32 values exactly. Classic
MAVLink encoding limits still apply at the vehicle boundary; see
[Parameter values](../design/linkhub.md#parameter-values).
+## 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,
+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.
+
+Enable the receiver with `LINKHUB_CSV_MAP` or `--csv-map`; see
+[CSV ingestion and the ESP32 example](../linkhub/README.md#generic-csv-ingestion).
+
## Build and launch
### Standalone offline demo / GitHub Pages
diff --git a/linkhub-ui/index.html b/linkhub-ui/index.html
index 8e5fbec..6c4ac42 100644
--- a/linkhub-ui/index.html
+++ b/linkhub-ui/index.html
@@ -22,6 +22,7 @@
Live vehicle state
Wobble
Swash
Motor
+ CSVs
connecting
RX — · TX —
@@ -72,6 +73,7 @@ Live vehicle state
+
diff --git a/linkhub-ui/src/api.ts b/linkhub-ui/src/api.ts
index 142aca3..1eeca25 100644
--- a/linkhub-ui/src/api.ts
+++ b/linkhub-ui/src/api.ts
@@ -1,6 +1,7 @@
import type {
CommandResult,
CameraStatus,
+ CsvStatus,
ExperimentInfo,
JsonObject,
LinkHubStatus,
@@ -157,6 +158,14 @@ export class LinkHubApi {
return this.request("GET", "/v1/camera", undefined, AbortSignal.timeout(3_000));
}
+ csvStatus(signal?: AbortSignal): Promise {
+ const timeout = AbortSignal.timeout(3_000);
+ return this.request(
+ "GET", "/v1/csv", undefined,
+ signal ? AbortSignal.any([signal, timeout]) : timeout,
+ );
+ }
+
async currentCursor(signal?: AbortSignal): Promise {
return (await this.status(signal)).cursor;
}
diff --git a/linkhub-ui/src/csv-panel.ts b/linkhub-ui/src/csv-panel.ts
new file mode 100644
index 0000000..1533d31
--- /dev/null
+++ b/linkhub-ui/src/csv-panel.ts
@@ -0,0 +1,110 @@
+import type { LinkHubApi } from "./api";
+import type { CsvStatus } from "./types";
+
+export class CsvPanel {
+ private readonly controller = new AbortController();
+ private readonly state: HTMLElement;
+ private readonly rows: HTMLElement;
+ private timer: ReturnType | undefined;
+ private received = false;
+ private disposed = false;
+ private lastError: string | null = null;
+
+ constructor(
+ private readonly button: HTMLButtonElement,
+ private readonly root: HTMLElement,
+ 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"]');
+ button.hidden = true;
+ root.hidden = true;
+ button.addEventListener("click", this.toggle);
+ void this.refresh();
+ }
+
+ dispose(): void {
+ this.disposed = true;
+ clearTimeout(this.timer);
+ this.controller.abort();
+ 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));
+ };
+
+ private async refresh(): Promise {
+ try {
+ const status = await this.api.csvStatus(this.controller.signal);
+ if (this.disposed) return;
+ this.lastError = null;
+ this.render(status);
+ } catch (error) {
+ if (this.disposed) return;
+ const message = `CSV status 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);
+ this.lastError = message;
+ } finally {
+ if (!this.disposed) this.timer = setTimeout(() => void this.refresh(), 1_000);
+ }
+ }
+
+ private render(status: CsvStatus): void {
+ if (!status.available || !status.latest || status.recent.length === 0) {
+ this.button.hidden = true;
+ this.root.hidden = true;
+ this.button.setAttribute("aria-pressed", "false");
+ this.rows.replaceChildren();
+ this.received = false;
+ return;
+ }
+ this.button.hidden = false;
+ if (!this.received) {
+ this.root.hidden = false;
+ this.button.setAttribute("aria-pressed", "true");
+ this.received = true;
+ }
+ 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)}`;
+ const table = document.createElement("table");
+ const head = document.createElement("thead");
+ const heading = document.createElement("tr");
+ for (const name of ["File", "Received", ...status.columns]) {
+ 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 tr = document.createElement("tr");
+ for (const value of [
+ row.filename, time(row.received_time_ns),
+ ...status.columns.map((field) => String(row.values[field])),
+ ]) {
+ const cell = document.createElement("td");
+ cell.textContent = value;
+ tr.append(cell);
+ }
+ body.append(tr);
+ }
+ table.append(head, body);
+ this.rows.replaceChildren(table);
+ }
+
+ private element(selector: string): HTMLElement {
+ const element = this.root.querySelector(selector);
+ if (!element) throw new Error(`Missing CSV panel element ${selector}`);
+ return element;
+ }
+}
diff --git a/linkhub-ui/src/demo-backend.ts b/linkhub-ui/src/demo-backend.ts
index 48696c6..1786f20 100644
--- a/linkhub-ui/src/demo-backend.ts
+++ b/linkhub-ui/src/demo-backend.ts
@@ -205,6 +205,9 @@ export class DemoBackend {
const body = init?.body === undefined ? {} : object(JSON.parse(String(init.body)));
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: [] });
+ }
if (path.startsWith("/v1/motor")) return json({ message: READ_ONLY }, 403);
if (method === "GET" && path === "/v1/experiment") return json({ active: null });
if (path.startsWith("/v1/experiment")) return json({ message: READ_ONLY }, 403);
diff --git a/linkhub-ui/src/main.ts b/linkhub-ui/src/main.ts
index 786725a..c974bc2 100644
--- a/linkhub-ui/src/main.ts
+++ b/linkhub-ui/src/main.ts
@@ -11,6 +11,7 @@ import type { LinkHubStatus } from "./types";
import { ExperimentController } from "./experiment";
import { ExperimentButton } from "./experiment-button";
import { CameraPanel } from "./camera-panel";
+import { CsvPanel } from "./csv-panel";
import { formatCopterMode } from "./modes";
import { isArmed } from "./mav";
import { PassiveController, type PassivePhase } from "./passive";
@@ -94,6 +95,13 @@ const experimentButton = new ExperimentButton(
write,
);
const scene = new VehicleScene(required("#scene"), telemetry, sceneOptions);
+const csvPanel = new CsvPanel(
+ required("#csv-toggle"),
+ required("#csv-panel"),
+ api,
+ (message) => write(message, "error"),
+);
+window.addEventListener("beforeunload", () => csvPanel.dispose(), { once: true });
function updateOverlay(): void {
const status = telemetry.status;
diff --git a/linkhub-ui/src/styles.css b/linkhub-ui/src/styles.css
index 3598977..ec208d0 100644
--- a/linkhub-ui/src/styles.css
+++ b/linkhub-ui/src/styles.css
@@ -405,7 +405,8 @@ h2 {
#yaw-toggle,
#wobble-toggle,
#swash-toggle,
-#motor-toggle {
+#motor-toggle,
+#csv-toggle {
padding: 4px 10px;
border: 1px solid #40506b;
border-radius: 999px;
@@ -419,7 +420,8 @@ h2 {
#yaw-toggle[aria-pressed="true"],
#wobble-toggle[aria-pressed="true"],
#swash-toggle[aria-pressed="true"],
-#motor-toggle[aria-pressed="true"] {
+#motor-toggle[aria-pressed="true"],
+#csv-toggle[aria-pressed="true"] {
border-color: #2d8f6f;
color: #71ddb4;
background: rgba(30, 123, 89, 0.14);
@@ -520,6 +522,33 @@ h2 {
.motor-warning, .motor-panel .error { color: #f0c36b; }
.motor-panel small { color: #aebdd2; }
+.csv-panel {
+ position: relative;
+ z-index: 3;
+ flex: none;
+ max-height: 30vh;
+ overflow: auto;
+ padding: 10px;
+ border-top: 1px solid #263249;
+ background: #080d16;
+ font-size: 11px;
+}
+
+.csv-panel[hidden] { display: none; }
+.csv-head { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
+.csv-head h2 { font-size: 13px; }
+.csv-head span { color: #aebdd2; }
+.csv-head .error { color: #f0c36b; }
+.csv-rows { overflow-x: auto; margin-top: 8px; }
+.csv-rows table { width: 100%; border-collapse: collapse; }
+.csv-rows th, .csv-rows td {
+ padding: 4px 8px;
+ border-bottom: 1px solid #263249;
+ text-align: left;
+ white-space: nowrap;
+}
+.csv-rows th { color: #7591b8; }
+
.swash-head, .swash-actions {
display: flex;
flex-wrap: wrap;
diff --git a/linkhub-ui/src/types.ts b/linkhub-ui/src/types.ts
index cd49362..4dafecb 100644
--- a/linkhub-ui/src/types.ts
+++ b/linkhub-ui/src/types.ts
@@ -9,6 +9,22 @@ import type {
export type JsonObject = Record;
+export interface CsvReading {
+ source: string;
+ filename: string;
+ received_time_ns: number;
+ sequence: number;
+ source_sequence: number;
+ values: Record;
+}
+
+export interface CsvStatus {
+ available: boolean;
+ columns: string[];
+ latest: CsvReading | null;
+ recent: CsvReading[];
+}
+
export interface MotorDevice {
id: string;
name: string;
diff --git a/linkhub-ui/tests/api.test.ts b/linkhub-ui/tests/api.test.ts
index 995f4e4..5df5249 100644
--- a/linkhub-ui/tests/api.test.ts
+++ b/linkhub-ui/tests/api.test.ts
@@ -46,6 +46,19 @@ describe("formatMavResult", () => {
});
describe("typed wire contract", () => {
+ it("reads CSV rows independently and propagates caller cancellation", async () => {
+ const status = { available: false, columns: [], latest: null, recent: [] };
+ const fetchMock = stubFetch(status);
+ const controller = new AbortController();
+ expect(await new LinkHubApi().csvStatus(controller.signal)).toEqual(status);
+ expect(fetchMock).toHaveBeenCalledWith(
+ "/v1/csv", 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("uses the motor discovery, exact selection, leased command and stop endpoints", async () => {
const fetchMock = stubFetch({ available: true });
const api = new LinkHubApi();
diff --git a/linkhub-ui/tests/csv-panel.test.ts b/linkhub-ui/tests/csv-panel.test.ts
new file mode 100644
index 0000000..9cac1bf
--- /dev/null
+++ b/linkhub-ui/tests/csv-panel.test.ts
@@ -0,0 +1,112 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { CsvPanel } from "../src/csv-panel";
+import type { CsvReading, CsvStatus } from "../src/types";
+
+class Element extends EventTarget {
+ innerHTML = "";
+ textContent = "";
+ hidden = false;
+ children: Element[] = [];
+ attributes = new Map();
+ classList = { toggle: vi.fn() };
+ append(...children: Element[]): void { this.children.push(...children); }
+ replaceChildren(...children: Element[]): void { this.children = children; }
+ setAttribute(name: string, value: string): void { this.attributes.set(name, value); }
+}
+
+const empty: CsvStatus = { available: true, columns: [], 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: " " },
+};
+const populated: CsvStatus = {
+ available: true, columns: ["temperature_c", "sensor"], latest: reading, recent: [reading],
+};
+
+function setup(initial: CsvStatus = empty) {
+ const state = new Element();
+ const rows = new Element();
+ const root = Object.assign(new Element(), {
+ querySelector: (selector: string) => selector === '[data-csv="state"]' ? state : rows,
+ });
+ 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) };
+ const onError = vi.fn();
+ const panel = new CsvPanel(
+ document.createElement("button"), document.createElement("section"), api, onError,
+ );
+ return { panel, api, onError, root, button, state, rows };
+}
+
+beforeEach(() => vi.useFakeTimers());
+afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+});
+
+describe("CSV pane", () => {
+ it("appears on received data, preserves configured field order and renders text safely", async () => {
+ const { panel, root, button, rows, state, api } = setup();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(button.hidden).toBe(true);
+ expect(root.hidden).toBe(true);
+ api.csvStatus.mockResolvedValue(populated);
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(button.hidden).toBe(false);
+ expect(root.hidden).toBe(false);
+ 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("");
+ expect(state.textContent).toContain("last received");
+ button.dispatchEvent(new Event("click"));
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(root.hidden).toBe(true);
+ expect(button.attributes.get("aria-pressed")).toBe("false");
+ 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(rows.children[0]).toBe(table);
+ expect(onError).toHaveBeenCalledTimes(1);
+ api.csvStatus.mockResolvedValue(populated);
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(state.textContent).toContain("bench.temperature");
+ expect(state.classList.toggle).toHaveBeenLastCalledWith("error", false);
+ api.csvStatus.mockResolvedValue({ ...empty, available: false });
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(rows.children).toEqual([]);
+ panel.dispose();
+ });
+
+ it("serializes polling and ignores a pending result after disposal", async () => {
+ const { panel, api, root, button } = setup();
+ await vi.advanceTimersByTimeAsync(0);
+ let finish!: (value: CsvStatus) => void;
+ api.csvStatus.mockImplementationOnce(() => new Promise((resolve) => { finish = resolve; }));
+ await vi.advanceTimersByTimeAsync(5000);
+ expect(api.csvStatus).toHaveBeenCalledTimes(2);
+ const signal = api.csvStatus.mock.lastCall?.[0];
+ panel.dispose();
+ expect(signal?.aborted).toBe(true);
+ finish(populated);
+ await vi.advanceTimersByTimeAsync(5000);
+ expect(api.csvStatus).toHaveBeenCalledTimes(2);
+ expect(root.hidden).toBe(true);
+ expect(button.hidden).toBe(true);
+ });
+});
diff --git a/linkhub-ui/tests/demo-backend.test.ts b/linkhub-ui/tests/demo-backend.test.ts
index 4bc40bf..bc21af6 100644
--- a/linkhub-ui/tests/demo-backend.test.ts
+++ b/linkhub-ui/tests/demo-backend.test.ts
@@ -31,6 +31,12 @@ 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: [],
+ });
+ });
+
it("disables Bluetooth motor access in the offline replay", async () => {
const { api } = fixture();
expect(await api.motorStatus()).toEqual({ available: false });
diff --git a/linkhub/Cargo.lock b/linkhub/Cargo.lock
index 6564b94..e51f205 100644
--- a/linkhub/Cargo.lock
+++ b/linkhub/Cargo.lock
@@ -406,6 +406,27 @@ dependencies = [
"typenum",
]
+[[package]]
+name = "csv"
+version = "1.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "52cd9d68cf7efc6ddfaaee42e7288d3a99d613d4b50f76ce9827ae0c6e14f938"
+dependencies = [
+ "csv-core",
+ "itoa",
+ "ryu",
+ "serde_core",
+]
+
+[[package]]
+name = "csv-core"
+version = "0.1.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "704a3c26996a80471189265814dbc2c257598b96b8a7feae2d31ace646bb9782"
+dependencies = [
+ "memchr",
+]
+
[[package]]
name = "dashmap"
version = "6.2.1"
@@ -1073,6 +1094,7 @@ dependencies = [
"base64 0.22.1",
"btleplug",
"clap",
+ "csv",
"futures-util",
"hex",
"hostname",
diff --git a/linkhub/Cargo.toml b/linkhub/Cargo.toml
index be073c6..32708ec 100644
--- a/linkhub/Cargo.toml
+++ b/linkhub/Cargo.toml
@@ -14,6 +14,7 @@ axum = "0.8"
base64 = "0.22"
btleplug = "0.13"
clap = { version = "4.5", features = ["derive", "env"] }
+csv = "1.4"
futures-util = "0.3"
mavlink-protocol = { path = "mavlink-protocol" }
reqwest = { version = "0.12", default-features = false, features = ["json"] }
diff --git a/linkhub/README.md b/linkhub/README.md
index 60ec9ab..54870a9 100644
--- a/linkhub/README.md
+++ b/linkhub/README.md
@@ -184,6 +184,7 @@ Defaults come from `linkhub\src\main.rs`.
| `--https-port` | unset | Also serve over HTTPS with a self-signed certificate kept in `\tls\` (needed for phone cameras). Also `LINKHUB_HTTPS_PORT`; `run_linkhub_ui.cmd` uses `9443`. |
| `--data-dir` | `linkhub-data` | Parent directory where each run creates `\run.json` and `\journal\`. |
| `--static-dir` | unset | Optional directory served as fallback static assets. |
+| `--csv-map` | unset | Enable CSV ingestion using this runtime JSON source/column mapping (`LINKHUB_CSV_MAP`). See [CSV ingestion](#generic-csv-ingestion). |
| `--no-cache` | off | Sends `Cache-Control: no-store` on every response. |
| `--run-id` | random UUID | Override the per-run UUID. |
| `--flush-ms` | `60000` | Journal flush interval in milliseconds. |
@@ -230,6 +231,7 @@ Routes come from `linkhub\src\http.rs`.
| `/health/live` | `GET` | Liveness probe. |
| `/health/ready` | `GET` | Ready when MAVLink is connected and has a heartbeat. |
| `/v1/status` | `GET` | Service/run/journal status. |
+| `/v1/csv` | `GET`, `POST` | Latest and recent mapped CSV rows; ingest raw `text/csv` with `?filename=...` when `--csv-map` is configured. |
| `/v1/journal/flush` | `POST` | Flush the active in-memory journal chunk. |
| `/v1/records` | `GET` | Mixed journal view over diagnostic + MAVLink records. |
| `/v1/diagnostics/events` | `GET`, `POST` | Read or ingest diagnostic events. |
@@ -281,6 +283,84 @@ settled full-scale transition. Stop waits for ramp-down; cancelling the request
does not cancel the ramp. Run commands during a stop return HTTP 409.
See [motor lease semantics](../design/linkhub.md#bluetooth-bench-motor).
+### Generic CSV ingestion
+
+Start LinkHub with a runtime mapping, adding these arguments to your usual
+`serve` command:
+
+```powershell
+--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:
+
+```json
+{
+ "source": "bench.temperature",
+ "sequence_column": "sample",
+ "columns": [
+ { "column": "sample", "field": "index", "type": "u64" },
+ { "column": "temperature", "field": "temperature_c", "type": "number" },
+ { "column": "label", "field": "sensor", "type": "string" }
+ ]
+}
+```
+
+`source` identifies the device/feed in the journal. Each ordered entry specifies
+the incoming `column`, output `field`, and `type` (`u64`, `number`, or `string`).
+`sequence_column` selects a mapped `u64` column for retry deduplication; it
+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.
+
+On the ESP32 servo interface (port **88**), set **CSVStorageURL** to
+`http://:8999/v1/csv`. The firmware appends `?filename=...`
+and sends raw CSV in POST bodies with `Content-Type: text/csv`.
+Allow inbound HTTP from the ESP32 through the host firewall; do not enter
+`localhost` or `0.0.0.0` as its destination. Changing this setting requests a
+new CSV file; it does not command servo motion.
+
+For the investigated device, configuration can be sent explicitly:
+
+```powershell
+curl.exe --get "http://192.168.9.122:88/create_new_csv" `
+ --data-urlencode "url=http://:8999/v1/csv"
+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).
+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 host timestamp permits clients to detect stale readings.
+
+POSTs are limited to 64 KiB. A matching header may appear alone or with rows;
+headerless row batches are also supported. Headers alone do not create a
+reading. `filename` is a logical identifier, not a filesystem path: use 1..255
+ASCII letters, digits, dots, underscores or hyphens.
+The complete batch is validated before journaling: wrong column
+counts, invalid UTF-8, non-finite numbers, invalid unsigned counters, and
+empty bodies are rejected with HTTP 400. Missing/wrong content types also
+return 400; oversized bodies return 413. POST returns 409 when no mapping
+is configured.
+
+Successful POSTs return HTTP 200 with `accepted`, `duplicates`, and `cursor`.
+Retries are deduplicated by filename and device sequence within the LinkHub
+run, so each acquisition file must have a unique filename and increasing
+row counters. Latest means the last newly accepted row, not the last retry.
+Samples are journaled as `diagnostic.event` records with the configured source,
+event `csv.sample`, and structured `filename`/`values` fields. They are
+available through the existing diagnostic cursor API and included in active
+experiment recordings; no second CSV archive is created. The latest-value
+and recent-row cache starts empty on each service run. Duplicate retries do not
+change it. The [UI CSVs pane](../linkhub-ui/README.md#csvs-pane) displays this view.
+
### Common query/body parameters
- Journal-backed `GET` projections use opaque cursors of the form `v1:`.
diff --git a/linkhub/csv-map.json b/linkhub/csv-map.json
new file mode 100644
index 0000000..cfe2270
--- /dev/null
+++ b/linkhub/csv-map.json
@@ -0,0 +1,13 @@
+{
+ "source": "esp32.strain",
+ "sequence_column": "_rownum",
+ "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" }
+ ]
+}
diff --git a/linkhub/src/csv_ingest.rs b/linkhub/src/csv_ingest.rs
new file mode 100644
index 0000000..6eca6fa
--- /dev/null
+++ b/linkhub/src/csv_ingest.rs
@@ -0,0 +1,349 @@
+use std::collections::{HashSet, VecDeque};
+
+use serde::{Deserialize, Serialize};
+use serde_json::{Map, Value, json};
+use tokio::sync::Mutex;
+
+use crate::{
+ journal::{JournalError, JournalHandle},
+ records::{DiagnosticEvent, DiagnosticLevel, format_cursor, wall_time_ns},
+};
+
+pub(crate) const MAX_CSV_BYTES: usize = 64 * 1024;
+const RECENT_ROWS: usize = 5;
+
+#[derive(Debug, thiserror::Error)]
+pub enum CsvError {
+ #[error("{0}")]
+ Invalid(String),
+ #[error(transparent)]
+ Journal(#[from] JournalError),
+}
+
+#[derive(Debug)]
+pub struct CsvMapping(MappingFile);
+
+#[derive(Debug, Deserialize)]
+#[serde(deny_unknown_fields)]
+struct MappingFile {
+ source: String,
+ sequence_column: String,
+ columns: Vec,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(deny_unknown_fields)]
+struct CsvColumn {
+ column: String,
+ field: String,
+ #[serde(rename = "type")]
+ kind: ColumnType,
+}
+
+#[derive(Clone, Copy, Debug, Deserialize, PartialEq)]
+#[serde(rename_all = "snake_case")]
+enum ColumnType {
+ U64,
+ Number,
+ String,
+}
+
+impl CsvMapping {
+ pub fn from_json(json: &str) -> Result {
+ let mapping: MappingFile = serde_json::from_str(json)
+ .map_err(|error| CsvError::Invalid(format!("invalid CSV mapping: {error}")))?;
+ if mapping.source.trim().is_empty()
+ || mapping.source.len() > 128
+ || mapping.source.chars().any(char::is_control)
+ {
+ return Err(CsvError::Invalid(
+ "mapping source must contain 1..128 bytes of non-blank text without control characters".to_owned(),
+ ));
+ }
+ if mapping.columns.is_empty() || mapping.columns.len() > 64 {
+ return Err(CsvError::Invalid(
+ "CSV mapping must contain 1..64 columns".to_owned(),
+ ));
+ }
+ let mut columns = HashSet::new();
+ let mut fields = HashSet::new();
+ for column in &mapping.columns {
+ for name in [&column.column, &column.field] {
+ if name.trim().is_empty() || name.len() > 128 || name.chars().any(char::is_control)
+ {
+ return Err(CsvError::Invalid(
+ "mapping names must contain 1..128 bytes without control characters"
+ .to_owned(),
+ ));
+ }
+ }
+ if !columns.insert(&column.column) || !fields.insert(&column.field) {
+ return Err(CsvError::Invalid(
+ "mapping column names and output fields must be unique".to_owned(),
+ ));
+ }
+ }
+ if !mapping.columns.iter().any(|column| {
+ column.column == mapping.sequence_column && column.kind == ColumnType::U64
+ }) {
+ return Err(CsvError::Invalid(
+ "sequence_column must name a mapped u64 column".to_owned(),
+ ));
+ }
+ Ok(Self(mapping))
+ }
+
+ fn parse(&self, body: &str) -> Result, CsvError> {
+ let mut samples = Vec::new();
+ let mut found_content = false;
+ let mut reader = csv::ReaderBuilder::new()
+ .has_headers(false)
+ .from_reader(body.as_bytes());
+ for (index, record) in reader.records().enumerate() {
+ let invalid =
+ |message: String| CsvError::Invalid(format!("CSV record {}: {message}", index + 1));
+ let record = record.map_err(|error| invalid(error.to_string()))?;
+ found_content = true;
+ if record.len() != self.0.columns.len() {
+ return Err(invalid(format!(
+ "expected {} CSV fields, got {}",
+ self.0.columns.len(),
+ record.len()
+ )));
+ }
+ if record
+ .iter()
+ .zip(&self.0.columns)
+ .all(|(value, column)| value == column.column)
+ {
+ continue;
+ }
+ let mut values = Map::new();
+ let mut sequence = None;
+ for (value, column) in record.iter().zip(&self.0.columns) {
+ let error = || {
+ invalid(format!(
+ "invalid {:?} value for {}",
+ column.kind, column.column
+ ))
+ };
+ let value = match column.kind {
+ ColumnType::U64 => {
+ let number = value.trim().parse::().map_err(|_| error())?;
+ if column.column == self.0.sequence_column {
+ sequence = Some(number);
+ }
+ Value::from(number)
+ }
+ ColumnType::Number => {
+ let number = value.trim().parse::().map_err(|_| error())?;
+ if !number.is_finite() {
+ return Err(error());
+ }
+ json!(number)
+ }
+ ColumnType::String => Value::String(value.to_owned()),
+ };
+ values.insert(column.field.clone(), value);
+ }
+ samples.push(ParsedSample {
+ sequence: sequence.expect("validated mapping has a u64 sequence column"),
+ values,
+ });
+ }
+ if !found_content {
+ return Err(CsvError::Invalid("CSV body must not be empty".to_owned()));
+ }
+ Ok(samples)
+ }
+}
+
+struct ParsedSample {
+ sequence: u64,
+ values: Map,
+}
+
+#[derive(Clone, Debug, Serialize)]
+pub(crate) struct CsvReading {
+ source: String,
+ filename: String,
+ received_time_ns: u64,
+ sequence: u64,
+ source_sequence: u64,
+ values: Map,
+}
+
+#[derive(Debug, Serialize)]
+pub(crate) struct CsvBatchResult {
+ accepted: usize,
+ duplicates: usize,
+ cursor: String,
+}
+
+pub(crate) struct CsvStore {
+ journal: JournalHandle,
+ mapping: CsvMapping,
+ readings: Mutex>,
+}
+
+impl CsvStore {
+ pub(crate) fn new(journal: JournalHandle, mapping: CsvMapping) -> Self {
+ Self {
+ journal,
+ mapping,
+ readings: Mutex::new(VecDeque::new()),
+ }
+ }
+
+ pub(crate) async fn status(&self) -> Value {
+ let readings = self.readings.lock().await;
+ let columns: Vec<_> = self
+ .mapping
+ .0
+ .columns
+ .iter()
+ .map(|column| &column.field)
+ .collect();
+ json!({
+ "available": true,
+ "columns": columns,
+ "latest": readings.back(),
+ "recent": &*readings,
+ })
+ }
+
+ pub(crate) async fn ingest(
+ &self,
+ filename: &str,
+ body: &str,
+ ) -> Result {
+ if filename.is_empty()
+ || filename.len() > 255
+ || !filename
+ .bytes()
+ .all(|byte| byte.is_ascii_alphanumeric() || b"._-".contains(&byte))
+ {
+ return Err(CsvError::Invalid(
+ "filename must contain 1..255 ASCII letters, digits, dots, underscores or hyphens"
+ .to_owned(),
+ ));
+ }
+ let samples = self.mapping.parse(body)?;
+ let mut readings = self.readings.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 mut fields = Map::new();
+ fields.insert("filename".to_owned(), Value::String(filename.to_owned()));
+ fields.insert("values".to_owned(), Value::Object(sample.values.clone()));
+ let appended = self
+ .journal
+ .append_diagnostic(DiagnosticEvent {
+ schema_version: crate::records::SCHEMA_VERSION,
+ run_id: self.journal.run_id(),
+ source: self.mapping.0.source.clone(),
+ source_instance: format!("csv:{}:{filename}", self.mapping.0.source),
+ source_sequence: sample.sequence,
+ source_wall_time_ns: received_time_ns,
+ source_monotonic_ns: None,
+ sim_time_ns: None,
+ sim_time_quality: None,
+ level: DiagnosticLevel::Info,
+ category: "csv".to_owned(),
+ event: "csv.sample".to_owned(),
+ message: "CSV sample".to_owned(),
+ correlation_id: None,
+ causation_id: None,
+ fields,
+ related_records: Vec::new(),
+ })
+ .await?;
+ if appended.appended {
+ result.accepted += 1;
+ readings.push_back(CsvReading {
+ source: self.mapping.0.source.clone(),
+ filename: filename.to_owned(),
+ received_time_ns,
+ sequence: appended.sequence,
+ source_sequence: sample.sequence,
+ values: sample.values,
+ });
+ if readings.len() > RECENT_ROWS {
+ readings.pop_front();
+ }
+ } else {
+ result.duplicates += 1;
+ }
+ result.cursor = format_cursor(self.journal.tail());
+ }
+ Ok(result)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn csv_mapping_changes_names_types_and_sequence_position_without_parser_changes() {
+ let mapping = CsvMapping::from_json(
+ r#"{
+ "source": "bench.temperature",
+ "sequence_column": "sample",
+ "columns": [
+ {"column": "temperature", "field": "temperature_c", "type": "number"},
+ {"column": "sample", "field": "index", "type": "u64"},
+ {"column": "label", "field": "sensor", "type": "string"}
+ ]
+ }"#,
+ )
+ .unwrap();
+ let samples = mapping
+ .parse("temperature,sample,label\r\n -12.5 ,42,\" bench, \"\"left\"\"\n \"\r\n")
+ .unwrap();
+ assert_eq!(samples.len(), 1);
+ assert_eq!(samples[0].sequence, 42);
+ assert_eq!(samples[0].values["temperature_c"], -12.5);
+ assert_eq!(samples[0].values["index"], 42);
+ assert_eq!(samples[0].values["sensor"], " bench, \"left\"\n ");
+ assert!(mapping.parse("inf,43,bench").is_err());
+ }
+
+ #[test]
+ fn csv_mapping_rejects_ambiguous_columns_and_invalid_sequence_roles() {
+ for mapping in [
+ json!({
+ "source": "test",
+ "sequence_column": "n",
+ "columns": [{"column": "n", "field": "n", "type": "number"}]
+ }),
+ json!({
+ "source": "test",
+ "sequence_column": "missing",
+ "columns": [{"column": "n", "field": "n", "type": "u64"}]
+ }),
+ json!({
+ "source": "test",
+ "sequence_column": "n",
+ "columns": [
+ {"column": "n", "field": "value", "type": "u64"},
+ {"column": "lift", "field": "value", "type": "number"}
+ ]
+ }),
+ json!({
+ "source": "test",
+ "sequence_column": "n",
+ "columns": [
+ {"column": "n", "field": "n", "type": "u64"},
+ {"column": "n", "field": "other", "type": "number"}
+ ]
+ }),
+ ] {
+ assert!(CsvMapping::from_json(&mapping.to_string()).is_err());
+ }
+ }
+}
diff --git a/linkhub/src/http.rs b/linkhub/src/http.rs
index 41347c0..96e7867 100644
--- a/linkhub/src/http.rs
+++ b/linkhub/src/http.rs
@@ -28,6 +28,7 @@ use tower_http::{services::ServeDir, set_header::SetResponseHeaderLayer};
use uuid::Uuid;
use crate::{
+ csv_ingest::{CsvBatchResult, CsvError, CsvMapping, CsvStore, MAX_CSV_BYTES},
experiment::{CameraConfig, ExperimentConfig, ExperimentError, ExperimentStore},
journal::{JournalError, JournalHandle, TimeWindow},
mavlink::{LinkError, LinkStatus, MavlinkLinkHandle},
@@ -51,6 +52,7 @@ pub struct AppState {
motor: Option,
experiments: Option>,
camera: Option,
+ csv: Option>,
}
fn collapse_state_records(records: Vec) -> Vec {
@@ -91,6 +93,8 @@ enum ApiError {
Motor(#[from] MotorError),
#[error(transparent)]
Experiment(#[from] ExperimentError),
+ #[error(transparent)]
+ Csv(#[from] CsvError),
/// The caller's `expected_generation` no longer matches LinkHub's live
/// generation: the service restarted, the serial link reconnected, or
/// the vehicle rebooted since the caller captured its baseline. A
@@ -159,6 +163,10 @@ impl IntoResponse for ApiError {
(StatusCode::CONFLICT, "experiment_closed")
}
Self::Experiment(_) => (StatusCode::INTERNAL_SERVER_ERROR, "experiment_save_failed"),
+ Self::Csv(CsvError::Invalid(_)) => (StatusCode::BAD_REQUEST, "invalid_csv"),
+ Self::Csv(CsvError::Journal(_)) => {
+ (StatusCode::SERVICE_UNAVAILABLE, "journal_unavailable")
+ }
Self::GenerationChanged { .. } => (StatusCode::CONFLICT, "generation_changed"),
};
let mut body = json!({
@@ -195,7 +203,7 @@ pub fn router_with_motor(
link: Option,
motor: Option,
) -> Router {
- router_with_motor_and_static(journal, link, motor, None, None, false)
+ router_with_motor_and_static(journal, link, motor, None, None, false, None)
}
/// `experiments` enables `/v1/experiment`; experiment directories are created there.
@@ -206,6 +214,7 @@ pub fn router_with_motor_and_static(
experiments: Option,
static_dir: Option,
no_cache: bool,
+ csv_mapping: Option,
) -> Router {
let operations = link
.clone()
@@ -217,6 +226,12 @@ pub fn router_with_motor_and_static(
.route("/health/live", get(live))
.route("/health/ready", get(ready))
.route("/v1/status", get(status))
+ .route(
+ "/v1/csv",
+ get(csv_status)
+ .post(ingest_csv)
+ .layer(DefaultBodyLimit::max(MAX_CSV_BYTES)),
+ )
.route("/v1/records", get(records))
.route("/v1/journal/flush", axum::routing::post(flush_journal))
.route(
@@ -303,6 +318,7 @@ pub fn router_with_motor_and_static(
.route("/camera", get(camera_page))
.route("/v1/mavlink/status", get(mavlink_status))
.with_state(Arc::new(AppState {
+ csv: csv_mapping.map(|mapping| Arc::new(CsvStore::new(journal.clone(), mapping))),
journal,
link,
operations,
@@ -329,6 +345,44 @@ async fn live() -> Json {
Json(json!({"status": "live"}))
}
+#[derive(Debug, Deserialize)]
+struct CsvQuery {
+ filename: String,
+}
+
+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": [],
+ })),
+ }
+}
+
+async fn ingest_csv(
+ State(state): State>,
+ Query(query): Query,
+ headers: HeaderMap,
+ body: Bytes,
+) -> Result, ApiError> {
+ let csv = state
+ .csv
+ .as_ref()
+ .ok_or_else(|| ApiError::Conflict("CSV mapping is not configured".to_owned()))?;
+ let content_type = headers
+ .get(CONTENT_TYPE)
+ .and_then(|value| value.to_str().ok())
+ .and_then(|value| value.split(';').next());
+ if !content_type.is_some_and(|value| value.trim().eq_ignore_ascii_case("text/csv")) {
+ return Err(ApiError::BadRequest(
+ "Content-Type must be text/csv".to_owned(),
+ ));
+ }
+ let body = std::str::from_utf8(&body)
+ .map_err(|_| ApiError::BadRequest("CSV body must be UTF-8".to_owned()))?;
+ Ok(Json(csv.ingest(&query.filename, body).await?))
+}
+
async fn ready(State(state): State>) -> Response {
let Some(link) = &state.link else {
return (
@@ -1785,6 +1839,220 @@ mod tests {
(status, serde_json::from_slice(&body).unwrap_or(Value::Null))
}
+ fn csv_app(journal: JournalHandle) -> Router {
+ let mapping = CsvMapping::from_json(include_str!("../csv-map.json")).expect("CSV mapping");
+ router_with_motor_and_static(journal, None, None, None, None, false, Some(mapping))
+ }
+
+ fn csv_post(filename: &str, body: impl Into) -> Request {
+ Request::post(format!("/v1/csv?filename={filename}"))
+ .header(CONTENT_TYPE, "text/csv; charset=utf-8")
+ .body(body.into())
+ .expect("CSV request")
+ }
+
+ #[tokio::test]
+ async fn csv_is_mapped_deduplicated_readable_and_persisted() {
+ 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 (_, initial) =
+ json_response(&app, Request::get("/v1/csv").body(Body::empty()).unwrap()).await;
+ assert_eq!(initial["available"], true);
+ assert_eq!(initial["latest"], Value::Null);
+ assert_eq!(initial["recent"], json!([]));
+
+ let (status, header) = json_response(
+ &app,
+ csv_post(
+ "test.csv",
+ "_rownum,_time,rpm,flap_angle,pitch_angle,lift,drag\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 (status, accepted) = json_response(&app, csv_post("test.csv", rows)).await;
+ assert_eq!(status, StatusCode::OK);
+ assert_eq!(accepted["accepted"], 2);
+ assert_eq!(accepted["cursor"], "v1:2");
+ let (_, duplicate) = json_response(&app, csv_post("test.csv", rows)).await;
+ assert_eq!(duplicate["accepted"], 0);
+ assert_eq!(duplicate["duplicates"], 2);
+
+ let (_, latest) =
+ json_response(&app, Request::get("/v1/csv").body(Body::empty()).unwrap()).await;
+ assert_eq!(latest["latest"]["filename"], "test.csv");
+ assert_eq!(latest["latest"]["source_sequence"], 2);
+ assert_eq!(latest["latest"]["sequence"], 2);
+ 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["recent"].as_array().unwrap().len(), 2);
+
+ let (_, next_file) = json_response(
+ &app,
+ csv_post("next.csv", "1,12:35:00.001,0,85,0,2.5,0.2\n"),
+ )
+ .await;
+ assert_eq!(next_file["accepted"], 1);
+ journal.shutdown().await.expect("shutdown");
+ task.await.expect("journal task");
+ let saved = crate::journal::read_persisted(temp.path(), 0, None)
+ .await
+ .expect("saved readings");
+ assert_eq!(saved.len(), 3);
+ let RecordPayload::Diagnostic(event) = &saved[0].payload else {
+ panic!("expected CSV diagnostic");
+ };
+ assert_eq!(event.source, "esp32.strain");
+ 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);
+ }
+
+ #[tokio::test]
+ async fn csv_rejects_invalid_batches_without_partial_ingestion() {
+ 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());
+ 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",
+ ] {
+ let (status, error) = json_response(&app, csv_post("test.csv", body)).await;
+ assert_eq!(status, StatusCode::BAD_REQUEST, "{body}");
+ assert_eq!(error["error"], "invalid_csv");
+ assert_eq!(journal.tail(), 0);
+ }
+ for request in [
+ csv_post("..%2Ftest.csv", "1,12:00:00,0,0,0,1,2"),
+ csv_post("test.csv", vec![0xff]),
+ Request::post("/v1/csv?filename=test.csv")
+ .header(CONTENT_TYPE, "application/json")
+ .body(Body::from("{}"))
+ .unwrap(),
+ Request::post("/v1/csv")
+ .header(CONTENT_TYPE, "text/csv")
+ .body(Body::from("1,12:00:00,0,0,0,1,2"))
+ .unwrap(),
+ ] {
+ let (status, _) = json_response(&app, request).await;
+ assert_eq!(status, StatusCode::BAD_REQUEST);
+ assert_eq!(journal.tail(), 0);
+ }
+ let response = app
+ .oneshot(csv_post("test.csv", vec![b'1'; MAX_CSV_BYTES + 1]))
+ .await
+ .unwrap();
+ assert_eq!(response.status(), StatusCode::PAYLOAD_TOO_LARGE);
+ assert_eq!(journal.tail(), 0);
+ journal.shutdown().await.expect("shutdown");
+ task.await.expect("journal task");
+ }
+
+ #[tokio::test]
+ async fn csv_requires_a_runtime_mapping() {
+ 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 = router(journal.clone(), None);
+ let (_, status) =
+ json_response(&app, Request::get("/v1/csv").body(Body::empty()).unwrap()).await;
+ assert_eq!(
+ status,
+ json!({
+ "available": false, "columns": [], "latest": null, "recent": [],
+ })
+ );
+ let (status, error) =
+ json_response(&app, csv_post("test.csv", "1,12:00:00,0,0,0,1,2")).await;
+ assert_eq!(status, StatusCode::CONFLICT);
+ assert_eq!(error["error"], "not_ready");
+ journal.shutdown().await.expect("shutdown");
+ task.await.expect("journal task");
+ }
+
+ #[tokio::test]
+ async fn csv_accepts_a_different_runtime_schema_and_quoted_text() {
+ let temp = TempDir::new().expect("temp directory");
+ let (journal, task) =
+ JournalHandle::start(JournalConfig::for_directory(temp.path(), Uuid::new_v4()))
+ .await
+ .unwrap();
+ let mapping = CsvMapping::from_json(
+ r#"{
+ "source": "bench.temperature",
+ "sequence_column": "sample",
+ "columns": [
+ {"column": "temperature", "field": "temperature_c", "type": "number"},
+ {"column": "sample", "field": "index", "type": "u64"},
+ {"column": "label", "field": "sensor", "type": "string"}
+ ]
+ }"#,
+ )
+ .unwrap();
+ let app = router_with_motor_and_static(
+ journal.clone(),
+ None,
+ None,
+ None,
+ None,
+ false,
+ Some(mapping),
+ );
+ let rows: String = (42..49)
+ .map(|sequence| format!("-12.5,{sequence},\"bench, \"\"left\"\"\"\r\n"))
+ .collect();
+ let (status, result) = json_response(
+ &app,
+ csv_post(
+ "temperature.csv",
+ format!("temperature,sample,label\r\n{rows}"),
+ ),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK);
+ assert_eq!(result["accepted"], 7);
+ let (_, status) =
+ json_response(&app, Request::get("/v1/csv").body(Body::empty()).unwrap()).await;
+ assert_eq!(status["latest"]["source"], "bench.temperature");
+ assert_eq!(
+ status["latest"]["values"],
+ json!({"temperature_c": -12.5, "index": 48, "sensor": "bench, \"left\""})
+ );
+ assert_eq!(
+ status["columns"],
+ json!(["temperature_c", "index", "sensor"])
+ );
+ assert_eq!(status["recent"].as_array().unwrap().len(), 5);
+ assert_eq!(status["recent"][0]["source_sequence"], 44);
+ assert_eq!(status["recent"][4]["source_sequence"], 48);
+ let records = journal.read_after(0).await.unwrap().records;
+ let RecordPayload::Diagnostic(event) = &records[0].payload else {
+ panic!("expected CSV diagnostic");
+ };
+ assert_eq!(event.source, "bench.temperature");
+ journal.shutdown().await.unwrap();
+ task.await.unwrap();
+ }
+
#[tokio::test]
async fn camera_urls_use_local_hostname_for_wildcard_listeners() {
let temp = TempDir::new().expect("temp directory");
@@ -1812,6 +2080,7 @@ mod tests {
}),
None,
false,
+ None,
);
let (status, camera) = json_response(
&app,
@@ -1844,6 +2113,7 @@ mod tests {
}),
None,
false,
+ None,
);
let camera_status = || {
json_response(
@@ -2281,6 +2551,7 @@ mod tests {
None,
Some(static_dir.clone()),
true,
+ None,
);
let index = app
@@ -2327,6 +2598,7 @@ mod tests {
None,
Some(static_dir),
false,
+ None,
)
.oneshot(Request::get("/").body(Body::empty()).expect("request"))
.await
diff --git a/linkhub/src/lib.rs b/linkhub/src/lib.rs
index 531bcab..b069adb 100644
--- a/linkhub/src/lib.rs
+++ b/linkhub/src/lib.rs
@@ -1,4 +1,5 @@
pub mod ble;
+pub mod csv_ingest;
pub mod discovery;
pub mod dronebridge;
pub mod experiment;
diff --git a/linkhub/src/main.rs b/linkhub/src/main.rs
index ced84a0..5a4f9b2 100644
--- a/linkhub/src/main.rs
+++ b/linkhub/src/main.rs
@@ -6,6 +6,7 @@ use std::{
use clap::{Parser, Subcommand};
use linkhub::{
+ csv_ingest::CsvMapping,
discovery::{self, DiscoveryConfig},
dronebridge::DroneBridge,
experiment::{CameraConfig, ExperimentConfig},
@@ -83,6 +84,9 @@ enum Command {
data_dir: PathBuf,
#[arg(long, env = "LINKHUB_STATIC_DIR")]
static_dir: Option,
+ /// Runtime source and column mapping for the generic CSV upload endpoint.
+ #[arg(long, env = "LINKHUB_CSV_MAP")]
+ csv_map: Option,
/// Send `Cache-Control: no-store` on every response so browsers
/// always load the latest rebuilt UI.
#[arg(long)]
@@ -151,6 +155,7 @@ async fn main() -> Result<(), Box> {
https_port,
data_dir,
static_dir,
+ csv_map,
no_cache,
run_id,
flush_ms,
@@ -165,6 +170,10 @@ async fn main() -> Result<(), Box> {
motor_heartbeat_ms,
motor_max_command_timeout_ms,
} => {
+ let csv_mapping = match csv_map {
+ Some(path) => Some(CsvMapping::from_json(&fs::read_to_string(path).await?)?),
+ None => None,
+ };
let mut link_config = link_config(
&connection,
baud,
@@ -244,6 +253,7 @@ async fn main() -> Result<(), Box> {
}),
static_dir,
no_cache,
+ csv_mapping,
);
tracing::info!(%bind, %run_id, "LinkHub listening");
let https_handle = axum_server::Handle::new();