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
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,8 @@ On native Linux, install uv, Node.js 24.x/npm, and Rust/Cargo before running

`run_linkhub_ui.cmd --build <connection>` calls `setup.cmd` before launching.
Without `--build`, the launcher reuses existing artifacts, running setup
automatically if the LinkHub binary or compiled UI is missing.
automatically if the LinkHub binary or compiled UI is missing, or the binary
rejects the launcher's arguments. See the [launcher documentation](linkhub-ui/README.md#live-ui).

Docker image builds:

Expand Down
31 changes: 25 additions & 6 deletions design/linkhub.md
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,11 @@ Route-by-route invocation examples, request bodies, and CLI usage live in
[linkhub/README.md](../linkhub/README.md); this document keeps the shared API
semantics.

Before any vehicle heartbeat, MAVLink status has an empty `base_mode` mask and
`system_status=UNINIT`; generated dialect flag defaults must not imply an armed
vehicle. Consumers must still use connection/readiness and observed heartbeats
to distinguish unknown state from confirmed disarmed state.

### Bluetooth bench motor

`--motor-name-prefix` enables the external rotor-drive backend. It starts
Expand All @@ -154,7 +159,9 @@ an explicit connection selects one exact ID, never another matching device.
The Nordic UART service is verified at connection time.
Connecting initializes the motor off. Switching devices first completes the
previous motor's controlled stop and never starts the selected motor.
Scanning is rejected while running.
Scanning is rejected while connected and running. After Bluetooth loss, scanning
is allowed even if the last running command remains unconfirmed; scanning does
not clear that state. Explicit reconnection initializes the motor off.

Every running command includes the connected `device_id`, speed percentage,
direction, and a finite lease duration. The current motor is forward-only;
Expand Down Expand Up @@ -192,6 +199,10 @@ A zero command does not establish zero mechanical RPM. Link loss, process crash,
power loss, and the motor controller's own watchdog/braking behavior need
motor-firmware/hardware protection. Write failures are reported as unconfirmed
motor state; LinkHub does not send an abrupt brake as an error fallback.
On link/write failure the supervisor exits and releases the Bluetooth peripheral
and adapter handles. Cleanup failures are logged without clearing the original
unconfirmed motor state. A subsequent UI connection acquires fresh handles and
initializes the motor off; it never resumes the previous command.

The browser renews a 2 s lease every 500 ms only for a motor it explicitly
started. Closing its motor panel, hiding the tab, or a request failure revokes
Expand Down Expand Up @@ -321,14 +332,22 @@ experiment without writing `mavlog.json`. The journal still holds the records.
Phone browsers expose the camera only to secure contexts, so
`serve --https-port PORT` also serves the full router over HTTPS. The
self-signed certificate lives in `<data-dir>/tls/` and is regenerated only
when its host set (localhost plus the LAN address) changes, so a phone accepts
the certificate warning once. `GET /v1/camera` returns the phone URL
`https://<lan-ip>:<https-port>/camera`, a QR code SVG (`qr_svg`), the
when its host set changes, so a phone accepts the certificate warning once.
With `--listen 0.0.0.0` or `::`, the certificate covers `localhost`, `127.0.0.1`,
and `<computername>.local`, using the lowercase short OS hostname. Its identity
does not change when DHCP assigns a different LAN IP. An explicit non-loopback
`--listen IP` uses that IP instead of the computer name.
`GET /v1/camera` returns the phone URL
`https://<computername>.local:<https-port>/camera` for all-interface listeners,
a QR code SVG (`qr_svg`), the
connected phones (`phones`), and, while an experiment runs, its
`experiment_id` and the recordings received so far (`videos`). When
`--listen` is loopback or HTTPS is off, it returns `url: null` with a
`reason`. `--listen 0.0.0.0` resolves the LAN address from the default-route
interface.
`reason`. The client network must resolve the computer's `.local` name (normally
through mDNS); the certificate does not advertise a hostname or configure DNS.
Existing IP-based certificates regenerate once when switching to the hostname,
so clients must accept the new self-signed certificate. The certificate remains
self-signed, not publicly trusted.

`GET /camera` serves a self-contained page (`linkhub/src/camera.html`). A
phone enables its camera once (one permission prompt; reloads reconnect
Expand Down
38 changes: 37 additions & 1 deletion linkhub-ui/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,9 @@ Add `--build` to run the complete project setup before launching
`setup.cmd` owns tool installation, uv-managed Python, dependencies, and both
builds; see the [root setup instructions](../README.md#running-tests).
The launcher also runs setup automatically when either build artifact is
missing. With both artifacts present, a normal launch needs no Python or uv.
missing or the existing LinkHub binary rejects the launcher's arguments. It
checks argument compatibility with `serve --help` before opening connections.
With compatible artifacts present, a normal launch needs no Python or uv.

`run_linkhub_ui.cmd` also:

Expand All @@ -115,11 +117,36 @@ missing. With both artifacts present, a normal launch needs no Python or uv.
telemetry radio; set a numeric baud only when intentionally restricting the
scan;
- defaults the HTTP port to `8999`;
- listens on `0.0.0.0` (all network interfaces) for HTTP and HTTPS. From another
device, use `http://<computername>.local:8999` or
`https://<computername>.local:9443`, not `0.0.0.0`. The HTTPS certificate and
camera QR code use that `.local` hostname; the client network must resolve it.
Windows Firewall must allow the selected ports on the trusted network.
See [phone HTTPS identity](../design/linkhub.md#phone-video);
- serves `linkhub-ui\dist` through LinkHub's `--static-dir`;
- enables the optional external motor backend with `--motor-name-prefix BLDC`,
initially disconnected;
- adds `--no-cache` so a browser refresh picks up a new build immediately.

For trusted LAN access, opt in to a persistent Windows Firewall rule:

```powershell
.\run_linkhub_ui.cmd --configure-firewall auto
```

Approve the administrator prompt. Only the firewall helper is elevated; LinkHub
continues under the original user. The rule allows inbound TCP for this
checkout's LinkHub executable, using the selected HTTP and HTTPS ports, from
`LocalSubnet` on **Private** networks only. Repeating the option updates the
same `RAWES-LinkHub-Private-LAN` rule, including changed ports or executable path.
Normal launches never change firewall rules. Cancellation or configuration
failure prevents startup. Public networks, explicit block rules, and managed
firewall policy are not overridden; rule creation does not prove remote
reachability. Use only a trusted LAN, not Internet port forwarding.

To remove the rule, run `Remove-NetFirewallRule -Name RAWES-LinkHub-Private-LAN`
in an administrator PowerShell.

## Bluetooth motor panel

Click **Motor**, then **Scan**, select the intended device by name and ID, and
Expand All @@ -145,6 +172,10 @@ the supervisor starts controlled ramp-down on its next profile tick. Stops are
not immediate; the request waits for the server-owned ramp to finish. There is no
automatic restart after expiry, reconnect, or reopening the panel.
Another client's running motor is displayed but never adopted for renewal.
Bluetooth loss revokes renewal and disables speed/start/stop controls. The panel
shows the motor state as unconfirmed, not off, and keeps Scan and Connect
available even if the last command was running or stopping. Reconnect explicitly,
then click Turn on to restart; reconnecting alone never resumes the motor.
The offline demo shows the backend as unavailable and never accesses Bluetooth.
Keep clear of the mechanism; a transport-level stop is not physical stop feedback.
See [LinkHub motor semantics](../design/linkhub.md#bluetooth-bench-motor).
Expand All @@ -169,6 +200,11 @@ Stop runs these steps in order:
directory. With `run_linkhub_ui.cmd`, experiment directories land in
`simulation/logs/linkhub/experiments/`.

An experiment started with no motor or vehicle connected can stop and save
without sending hardware commands. Initial MAVLink status has no mode flags
until a heartbeat arrives; absence of telemetry is not a disarm confirmation
for a previously connected vehicle.

If a step fails, for example the rotor is still turning or the motor stop
times out, the experiment stays open so you can press Stop again. Experiment
state lives on the server, so a page reload picks up a running experiment.
Expand Down
22 changes: 18 additions & 4 deletions linkhub-ui/src/motor-panel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,16 @@ export class MotorPanel {
}

private update(status: MotorStatus): void {
if (!status.available || !status.connected) {
if (this.status?.available && this.status.connected && status.available) {
this.write("Motor: Bluetooth disconnected; motor state is unconfirmed. Reconnect before restarting.", "error");
}
if (this.ownedDevice) {
this.ownedDevice = null;
this.leaseDeadline = 0;
this.revision += 1;
}
}
this.status = status;
if (status.available && status.device_id && !Array.from(this.device.options).some((option) => option.value === status.device_id)) {
this.device.add(new Option(`${status.device ?? "Motor"} (${status.device_id})`, status.device_id));
Expand All @@ -259,25 +269,29 @@ export class MotorPanel {
const status = this.status;
const available = status?.available === true;
const connected = available && status.connected;
const running = available && status.running;
const running = connected && status.running;
const busy = this.busy > 0;
const speedText = `${this.speed.value}%`;
if (this.speedValue.textContent !== speedText) this.speedValue.textContent = speedText;
const stateText = this.error
const disconnected = available && !connected;
const detail = this.error ?? (available ? status.error : null);
const stateText = disconnected
? `Disconnected - motor state unconfirmed. Reconnect before restarting.${detail ? ` ${detail}` : ""}`
: this.error
?? (available ? status.error : null)
?? (status?.available === false ? "Motor backend disabled in LinkHub" : !status ? "Loading"
: status.available && status.stopping ? `STOPPING - ${status.speed_percent}%`
: running ? `ON - ${status.speed_percent}% -> ${status.target_speed_percent}%${this.ownedDevice ? "" : " (another client)"}`
: connected ? `OFF - ${status.device}` : "Disconnected");
if (this.state.textContent !== stateText) this.state.textContent = stateText;
this.state.classList.toggle("error", Boolean(this.error || (available && status.error)));
this.state.classList.toggle("error", disconnected || Boolean(this.error || (available && status.error)));
this.scanButton.disabled = !available || busy || running;
this.device.disabled = !available || busy || running;
this.connectButton.disabled = !available || busy || running || !this.device.value;
this.experimentHint.hidden = this.experiment.running;
this.onButton.disabled = !this.experiment.running || !connected || busy || running || Boolean(this.error)
|| this.device.value !== (available ? status.device_id : null) || Number(this.speed.value) === 0;
this.offButton.disabled = !available;
this.offButton.disabled = !connected;
this.speed.disabled = !connected || busy || (running && !this.ownedDevice);
}
}
22 changes: 21 additions & 1 deletion linkhub-ui/tests/experiment.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const INFO: ExperimentInfo = {
id: "e1", name: "Spin", description: "", run_id: "r1", started_at_ns: 0, start_cursor: "v1:1", directory: "x",
};

function motor(speed: number, stopping = false): MotorStatus {
function motor(speed: number, stopping = false): Extract<MotorStatus, { available: true }> {
return {
available: true, connected: true, device: "BLDC", device_id: "m1",
running: speed > 0 && !stopping, stopping, speed_percent: speed, target_speed_percent: 0,
Expand Down Expand Up @@ -94,6 +94,26 @@ describe("experiment controller", () => {
expect(controller.running).toBe(true);
});

it("saves without hardware commands when no motor or vehicle has connected", async () => {
const { controller, api, passive, calls } = setup([]);
passive.phase = "idle";
api.motorStatus.mockResolvedValue({
...motor(0), connected: false, device: null, device_id: null,
});
api.status.mockResolvedValue({
connected: false, ready: false, base_mode: "", received_messages: 0,
} as LinkHubStatus);
await controller.refresh();

await controller.stop();

expect(api.stopMotor).not.toHaveBeenCalled();
expect(passive.stop).not.toHaveBeenCalled();
expect(calls).toEqual(["save"]);
expect(controller.active).toBeNull();
expect(controller.stage).toBe("idle");
});

it("refuses gated actions without an active experiment", async () => {
const { controller, api } = setup([]);
api.experiment.mockResolvedValue(null);
Expand Down
66 changes: 66 additions & 0 deletions linkhub-ui/tests/motor-panel.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,72 @@ afterEach(() => {
});

describe("Bluetooth motor panel", () => {
it.each([
{ running: false, stopping: false },
{ running: true, stopping: false },
{ running: true, stopping: true },
])("allows recovery after disconnect with last command $running/$stopping", async (lastCommand) => {
const { panel, api, elements, setStatus, write, speed } = setup();
await vi.advanceTimersByTimeAsync(0);
setStatus({
...connected(), ...lastCommand, connected: false,
speed_percent: 30, target_speed_percent: 80, error: "Bluetooth motor is disconnected",
});
await vi.advanceTimersByTimeAsync(500);
expect(elements.get("state")!.textContent).toContain("Disconnected - motor state unconfirmed");
expect(elements.get("state")!.textContent).toContain("Bluetooth motor is disconnected");
expect(elements.get("scan")!.disabled).toBe(false);
expect(elements.get("device")!.disabled).toBe(false);
expect(elements.get("connect")!.disabled).toBe(false);
expect(elements.get("on")!.disabled).toBe(true);
expect(elements.get("off")!.disabled).toBe(true);
expect(speed.disabled).toBe(true);
expect(api.stopMotor).not.toHaveBeenCalled();
expect(write).toHaveBeenCalledTimes(1);
await panel.connect();
expect(elements.get("on")!.disabled).toBe(false);
expect(api.runMotor).not.toHaveBeenCalled();
panel.dispose();
});

it("revokes its lease on Bluetooth loss without attempting an impossible stop or restarting", async () => {
const { panel, api, setStatus, elements } = setup();
await panel.turnOn();
setStatus({
...connected(), connected: false, running: true, speed_percent: 10,
target_speed_percent: 10, error: "Bluetooth motor is disconnected",
});
api.stopMotor.mockRejectedValue(new Error("Bluetooth motor is disconnected"));
await vi.advanceTimersByTimeAsync(1500);
expect(api.runMotor).toHaveBeenCalledTimes(1);
expect(api.stopMotor).not.toHaveBeenCalled();
expect(elements.get("connect")!.disabled).toBe(false);
await panel.connect();
await vi.advanceTimersByTimeAsync(1500);
expect(api.runMotor).toHaveBeenCalledTimes(1);
await panel.turnOn();
expect(api.runMotor).toHaveBeenCalledTimes(2);
panel.dispose();
});

it("handles disconnect in a run response without retaining renewal ownership", async () => {
const { panel, api, setStatus, elements } = setup();
const disconnected: MotorStatus = {
...connected(), connected: false, running: true, error: "Bluetooth motor is disconnected",
};
api.runMotor.mockImplementationOnce(async () => {
setStatus(disconnected);
return disconnected;
});
await panel.turnOn();
await vi.advanceTimersByTimeAsync(1500);
expect(api.runMotor).toHaveBeenCalledTimes(1);
expect(api.stopMotor).not.toHaveBeenCalled();
expect(elements.get("on")!.disabled).toBe(true);
expect(elements.get("connect")!.disabled).toBe(false);
panel.dispose();
});

it("shows applied versus target commands and a server-owned stop", async () => {
const { panel, elements, api, setStatus } = setup({
...connected(), running: true, speed_percent: 30, target_speed_percent: 80,
Expand Down
Loading
Loading