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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
40 changes: 33 additions & 7 deletions design/linkhub.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

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

Expand Down
36 changes: 33 additions & 3 deletions linkhub-ui/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).

Expand Down
10 changes: 10 additions & 0 deletions linkhub-ui/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type {
CommandResult,
CameraStatus,
CsvStatus,
DiagnosticBatch,
ExperimentInfo,
JsonObject,
LinkHubStatus,
Expand Down Expand Up @@ -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<DiagnosticBatch> {
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<CsvStatus> {
const timeout = AbortSignal.timeout(3_000);
return this.request(
Expand Down
95 changes: 95 additions & 0 deletions linkhub-ui/src/csv-chart.ts
Original file line number Diff line number Diff line change
@@ -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([]);
}
121 changes: 121 additions & 0 deletions linkhub-ui/src/csv-model.ts
Original file line number Diff line number Diff line change
@@ -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<CsvInput, number | null>;

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; }
}
Loading
Loading