From 7f5918e4b2e4f275137250b646309d75806e3b14 Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Thu, 10 Sep 2026 22:06:29 +0200 Subject: [PATCH 1/8] feat: add shutdown functionality for Raspberry Pi host and integrate into UI --- .../src/components/MobileMenuSheet.tsx | 25 ++- .../src/components/ShutdownDialog.tsx | 177 ++++++++++++++++++ .../src/routes/settings/DeviceTab.tsx | 25 +++ headless-rust/frontend/src/shared/types.ts | 7 + headless-rust/src/web/rpc.rs | 13 ++ 5 files changed, 241 insertions(+), 6 deletions(-) create mode 100644 headless-rust/frontend/src/components/ShutdownDialog.tsx diff --git a/headless-rust/frontend/src/components/MobileMenuSheet.tsx b/headless-rust/frontend/src/components/MobileMenuSheet.tsx index e2d9f7e..7e91982 100644 --- a/headless-rust/frontend/src/components/MobileMenuSheet.tsx +++ b/headless-rust/frontend/src/components/MobileMenuSheet.tsx @@ -16,10 +16,11 @@ import { Settings, Sliders, Database, - Info, Layers, ChevronRight, + Power, } from "lucide-react"; +import { ShutdownDialog } from "./ShutdownDialog"; import { cn } from "@/lib/utils"; interface MobileMenuSheetProps { @@ -33,7 +34,6 @@ const CORE_NAV_LINKS = [ { label: "Camera Setup", to: "/setup", icon: Sliders }, { label: "System Settings", to: "/settings", icon: Settings }, { label: "Teable Sync", to: "/teable", icon: Database }, - { label: "About & Updates", to: "/about", icon: Info }, ] as const; const MODE_META: Record = { @@ -171,10 +171,23 @@ export function MobileMenuSheet({ open, onOpenChange }: MobileMenuSheetProps) { )} - {/* Footer with Theme Toggle */} -
- Appearance - + {/* Footer with Host Shutdown and Theme Toggle */} +
+
+ Appearance + +
+ + + Shut Down Host (Pi) + + } + />
diff --git a/headless-rust/frontend/src/components/ShutdownDialog.tsx b/headless-rust/frontend/src/components/ShutdownDialog.tsx new file mode 100644 index 0000000..e66fe13 --- /dev/null +++ b/headless-rust/frontend/src/components/ShutdownDialog.tsx @@ -0,0 +1,177 @@ +import { useState } from "react"; +import { toast } from "sonner"; +import { getRpc } from "@/lib/rpc"; +import { + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogDescription, + DialogFooter, + DialogTrigger, + DialogClose, +} from "@/components/ui/dialog"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { AlertTriangle, Power, Loader2, CheckCircle2 } from "lucide-react"; + +interface ShutdownDialogProps { + trigger?: React.ReactNode; + open?: boolean; + onOpenChange?: (open: boolean) => void; +} + +export function ShutdownDialog({ trigger, open: controlledOpen, onOpenChange }: ShutdownDialogProps) { + const [internalOpen, setInternalOpen] = useState(false); + const isControlled = controlledOpen !== undefined; + const open = isControlled ? controlledOpen : internalOpen; + + const setOpen = (next: boolean) => { + if (!next) { + // Reset state when closing + setPassword(""); + setErrorMessage(null); + setCompleted(false); + } + if (isControlled) { + onOpenChange?.(next); + } else { + setInternalOpen(next); + } + }; + + const [password, setPassword] = useState(""); + const [shuttingDown, setShuttingDown] = useState(false); + const [errorMessage, setErrorMessage] = useState(null); + const [completed, setCompleted] = useState(false); + const [simulated, setSimulated] = useState(false); + + const handleShutdown = async (e?: React.FormEvent) => { + if (e) e.preventDefault(); + setShuttingDown(true); + setErrorMessage(null); + try { + const res = await getRpc().request.shutdownHost({ + password: password.trim() ? password.trim() : undefined, + }); + setCompleted(true); + setSimulated(Boolean(res?.simulated)); + toast.success(res?.simulated ? "Shutdown simulated (mock mode)" : "Host system is shutting down..."); + } catch (err: any) { + const msg = err?.message || String(err); + setErrorMessage(msg); + toast.error(`Shutdown failed: ${msg}`); + } finally { + setShuttingDown(false); + } + }; + + return ( + + {trigger && {trigger}} + + +
+
+ +
+ Shut Down Raspberry Pi Host +
+ + This will cleanly shut down the Raspberry Pi operating system and stop all background camera services. + You will need to power cycle the hardware to turn it back on. + +
+ + {completed ? ( +
+
+ +
+

+ {simulated ? "Shutdown Simulated (Mock Mode)" : "System Powering Off"} +

+

+ {simulated + ? "Mock hardware mode is enabled. No actual machine shutdown was initiated." + : "The host Raspberry Pi has received the shutdown command and will power down shortly. You can safely disconnect power once the activity LED stops blinking."} +

+ + + + + +
+ ) : ( +
+ {errorMessage && ( +
+ +
+ Shutdown request failed: + {errorMessage} + + If your Pi user requires a sudo password, please enter it below. + +
+
+ )} + +
+ + setPassword(e.target.value)} + placeholder="Leave empty if passwordless sudo is enabled" + className="font-mono text-xs" + disabled={shuttingDown} + autoFocus + /> +

+ Leave empty if passwordless sudo is configured on your Raspberry Pi. +

+
+ + + + + +
+ )} +
+
+ ); +} diff --git a/headless-rust/frontend/src/routes/settings/DeviceTab.tsx b/headless-rust/frontend/src/routes/settings/DeviceTab.tsx index 2e191be..8311959 100644 --- a/headless-rust/frontend/src/routes/settings/DeviceTab.tsx +++ b/headless-rust/frontend/src/routes/settings/DeviceTab.tsx @@ -19,6 +19,8 @@ import { FilterIcon, } from "@hugeicons/core-free-icons"; import { FirmwareFlasher } from "@/components/FirmwareFlasher"; +import { ShutdownDialog } from "@/components/ShutdownDialog"; +import { Power } from "lucide-react"; export function DeviceTab() { const connectedPort = useAppStore((s) => s.connectedPort); @@ -211,6 +213,29 @@ export function DeviceTab() { )} + {/* Host System Power / Shutdown */} +
+
+
+

+ + Raspberry Pi Host Power +

+

+ Safely shut down the operating system and power off the Raspberry Pi board. +

+
+ + + Shut Down Host + + } + /> +
+
+
); diff --git a/headless-rust/frontend/src/shared/types.ts b/headless-rust/frontend/src/shared/types.ts index 590c4a3..45adc9b 100644 --- a/headless-rust/frontend/src/shared/types.ts +++ b/headless-rust/frontend/src/shared/types.ts @@ -302,6 +302,7 @@ export type SerialStatusPayload = | { status: "LAPWAITING" } | { status: "LAPSTOPPED" } | { status: "BARRIER_STATUS"; sensor1Interrupted: boolean; sensor2Interrupted: boolean; timestamp: number } + | { status: "CONFIG"; key: string; value: number } | { status: "CONNECTED"; port?: string } | { status: "DISCONNECTED" }; @@ -417,6 +418,12 @@ export type SpeedcameraRPC = { response: { armed: boolean }; }; + // System – host power control + shutdownHost: { + params: { password?: string }; + response: { success: boolean; simulated?: boolean; message?: string }; + }; + // DB – settings getSettings: { params: Record; diff --git a/headless-rust/src/web/rpc.rs b/headless-rust/src/web/rpc.rs index 3674f3c..36b3ecf 100644 --- a/headless-rust/src/web/rpc.rs +++ b/headless-rust/src/web/rpc.rs @@ -348,6 +348,19 @@ async fn dispatch_method(ctx: &RpcContext, method: &str, params: Value) -> Resul Ok(Value::Null) } + "shutdownHost" => { + let password = params["password"].as_str().map(|s| s.to_string()); + let mock_mode = ctx.config.mock_mode; + let res = tokio::task::spawn_blocking(move || { + crate::system::shutdown_host(password, mock_mode) + }) + .await + .map_err(|e| e.to_string())? + .map_err(|e| e.to_string())?; + + Ok(res) + } + // ─── Serial ─────────────────────────────────────────────────────────── "listPorts" => { let serial = ctx.serial.clone(); From 42713b4e04db657838064499b880be953fabee3b Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Thu, 10 Sep 2026 22:07:29 +0200 Subject: [PATCH 2/8] refactor: remove About route and update navigation menu --- headless-rust/frontend/src/App.tsx | 2 - .../src/components/NavigationMenu.tsx | 1 - headless-rust/frontend/src/routes/about.tsx | 264 ------------------ 3 files changed, 267 deletions(-) delete mode 100644 headless-rust/frontend/src/routes/about.tsx diff --git a/headless-rust/frontend/src/App.tsx b/headless-rust/frontend/src/App.tsx index 4f60073..90d58b7 100644 --- a/headless-rust/frontend/src/App.tsx +++ b/headless-rust/frontend/src/App.tsx @@ -5,7 +5,6 @@ import { RootRoute } from "@/routes/__root"; import { IndexRoute } from "@/routes/index"; import { ViolationsRoute } from "@/routes/violations"; import { SettingsRoute } from "@/routes/settings"; -import { AboutRoute } from "@/routes/about"; import { TeableRoute } from "@/routes/teable"; import { SetupRoute } from "@/routes/setup"; import { pluginRegistry } from "@/plugins"; @@ -16,7 +15,6 @@ const routeTree = RootRoute.addChildren([ IndexRoute, ViolationsRoute, SettingsRoute, - AboutRoute, TeableRoute, SetupRoute, ...pluginRegistry.getRoutes(RootRoute), diff --git a/headless-rust/frontend/src/components/NavigationMenu.tsx b/headless-rust/frontend/src/components/NavigationMenu.tsx index bfa2643..a9c1f14 100644 --- a/headless-rust/frontend/src/components/NavigationMenu.tsx +++ b/headless-rust/frontend/src/components/NavigationMenu.tsx @@ -10,7 +10,6 @@ const CORE_NAV_ITEMS = [ { label: "Settings", to: "/settings" }, { label: "Setup", to: "/setup" }, { label: "Teable", to: "/teable" }, - { label: "About", to: "/about" }, ] as const; const MODE_META: Record = { diff --git a/headless-rust/frontend/src/routes/about.tsx b/headless-rust/frontend/src/routes/about.tsx deleted file mode 100644 index 6f185a3..0000000 --- a/headless-rust/frontend/src/routes/about.tsx +++ /dev/null @@ -1,264 +0,0 @@ -import { createRoute } from "@tanstack/react-router"; -import { RootRoute } from "./__root"; -import { Button } from "@/components/ui/button"; -import { useEffect, useState, useCallback } from "react"; -import { toast } from "sonner"; -import { HugeiconsIcon } from "@hugeicons/react"; -import { - DownloadCircle02Icon, - RefreshIcon, - Cancel01Icon, - Alert02Icon, - CheckmarkCircle02Icon, -} from "@hugeicons/core-free-icons"; -import { getRpc } from "@/lib/rpc"; -import { useAppStore } from "@/stores/useAppStore"; - -const GITHUB_URL = "https://github.com/LeoLTM/speedcamera"; - -export const AboutRoute = createRoute({ - getParentRoute: () => RootRoute, - path: "/about", - component: AboutPage, -}); - -function AboutPage() { - const [localVersion, setLocalVersion] = useState<{ - version: string; - channel: string; - hash: string; - } | null>(null); - const [versionLoading, setVersionLoading] = useState(true); - - const updatePhase = useAppStore((s) => s.updatePhase); - const updateMessage = useAppStore((s) => s.updateMessage); - const updateProgress = useAppStore((s) => s.updateProgress); - const updateVersion = useAppStore((s) => s.updateVersion); - const updateError = useAppStore((s) => s.updateError); - const resetUpdater = useAppStore((s) => s.resetUpdater); - const setUpdatePhase = useAppStore((s) => s.setUpdatePhase); - const setUpdateVersion = useAppStore((s) => s.setUpdateVersion); - const setUpdateError = useAppStore((s) => s.setUpdateError); - - const handleOpenGitHub = () => { - window.open(GITHUB_URL, "_blank", "noopener,noreferrer"); - }; - - // Load local version on mount - useEffect(() => { - getRpc() - .request.getLocalVersion({}) - .then((info) => setLocalVersion(info)) - .catch(() => setLocalVersion(null)) - .finally(() => setVersionLoading(false)); - }, []); - - const handleCheckForUpdate = useCallback(async () => { - resetUpdater(); - setUpdatePhase("checking"); - try { - const info = await getRpc().request.checkForUpdate({}); - if (info.error) { - setUpdateError(info.error); - setUpdatePhase("error"); - toast.error(info.error); - return; - } - if (info.updateAvailable) { - setUpdateVersion(info.version); - toast.info(`Update available: v${info.version}`); - } else { - setUpdatePhase("idle"); - toast.success("You're on the latest version"); - } - } catch (err) { - const msg = err instanceof Error ? err.message : String(err); - setUpdateError(msg); - setUpdatePhase("error"); - toast.error(`Update check failed: ${msg}`); - } - }, [resetUpdater, setUpdatePhase, setUpdateError, setUpdateVersion]); - - const handleDownloadUpdate = useCallback(async () => { - setUpdatePhase("downloading"); - setUpdateError(null); - try { - const result = await getRpc().request.downloadUpdate({}); - if (!result.ok) { - setUpdateError(result.error ?? "Download failed"); - setUpdatePhase("error"); - toast.error(result.error ?? "Download failed"); - return; - } - setUpdatePhase("ready"); - toast.success("Update downloaded — ready to install"); - } catch (err) { - const msg = err instanceof Error ? err.message : String(err); - setUpdateError(msg); - setUpdatePhase("error"); - toast.error(`Download failed: ${msg}`); - } - }, [setUpdatePhase, setUpdateError]); - - const handleApplyUpdate = useCallback(async () => { - try { - await getRpc().request.applyUpdate({}); - // App quits + relaunches; this line may not run - } catch (err) { - const msg = err instanceof Error ? err.message : String(err); - toast.error(`Failed to apply update: ${msg}`); - } - }, []); - - const isBusy = updatePhase === "checking" || updatePhase === "downloading"; - const canDownload = updateVersion !== null && updatePhase !== "downloading" && updatePhase !== "ready"; - const canApply = updatePhase === "ready"; - - return ( -
-
-
-

Speedcamera

-

- Companion app for the ESP32-based speed camera -

-
- -
-
- Version - - {versionLoading - ? "…" - : localVersion - ? `v${localVersion.version}` - : "unknown"} - -
-
- Channel - - {localVersion?.channel ?? "—"} - -
-
- Build hash - - {localVersion?.hash?.slice(0, 8) ?? "—"} - -
-
- Runtime - Rust + Rocket -
-
- UI - React + Vite + shadcn -
-
- - {/* ── Update controls ─────────────────────────────────────────────────── */} -
-

- - App Updates -

- - {localVersion?.channel === "dev" && ( -

- Updates disabled in dev channel. -

- )} - - {/* Available version badge */} - {updateVersion && updatePhase !== "idle" && ( -
- Latest: - v{updateVersion} -
- )} - - {/* Progress bar */} - {(updatePhase === "downloading" || updatePhase === "checking") && ( -
-
-
-
-

- {updateMessage} - {updateProgress != null ? ` (${updateProgress}%)` : ""} -

-
- )} - - {/* Error */} - {updatePhase === "error" && ( -

- - {updateError} -

- )} - - {/* Ready */} - {updatePhase === "ready" && ( -

- - Update ready — restart to install -

- )} - - {/* Action buttons */} -
- - - {canDownload && ( - - )} - - {canApply && ( - - )} - - {isBusy && ( - - )} -
-
- - - -

- Built to detect and log speed violations using a webcam and Arduino/ESP32 + light barriers. -

-
- ); -} From b98ca895c6b37b01039bb98cc71be3d1112d46a8 Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Thu, 10 Sep 2026 22:07:59 +0200 Subject: [PATCH 3/8] refactor: update display preview UI components for improved mobile layout and responsiveness; remove maxSpeed from settings storage --- .../display/components/DisplayPreview.tsx | 14 ++-- .../display/components/DisplaySettingsTab.tsx | 36 ++++---- .../frontend/src/plugins/display/store.ts | 17 +--- headless-rust/frontend/src/routes/__root.tsx | 3 +- headless-rust/frontend/src/routes/index.tsx | 12 --- .../src/routes/settings/SpeedCameraTab.tsx | 10 ++- .../src/stores/slices/measurementSlice.ts | 16 ++++ headless-rust/src/db/settings.rs | 37 +++++++- headless-rust/src/main.rs | 6 +- headless-rust/src/models.rs | 5 ++ headless-rust/src/plugins/display/db.rs | 10 ++- headless-rust/src/plugins/display/mod.rs | 7 +- headless-rust/src/serial/mock.rs | 17 +++- headless-rust/src/serial/mod.rs | 26 ++++++ headless-rust/src/serial/protocol.rs | 9 ++ headless-rust/src/system.rs | 84 +++++++++++++++++++ 16 files changed, 243 insertions(+), 66 deletions(-) create mode 100644 headless-rust/src/system.rs diff --git a/headless-rust/frontend/src/plugins/display/components/DisplayPreview.tsx b/headless-rust/frontend/src/plugins/display/components/DisplayPreview.tsx index e7513e5..3c44a51 100644 --- a/headless-rust/frontend/src/plugins/display/components/DisplayPreview.tsx +++ b/headless-rust/frontend/src/plugins/display/components/DisplayPreview.tsx @@ -105,20 +105,20 @@ export function DisplayPreview() {
{/* Retro OLED Screen Bezel */} -
-
+
+
-
- SSD1306 • I²C - Active Screen: {preview?.activeScreen || "SpeedCamera"} - 128x64 +
+ SSD1306 • I²C + Active: {preview?.activeScreen || "SpeedCamera"} + 128x64
diff --git a/headless-rust/frontend/src/plugins/display/components/DisplaySettingsTab.tsx b/headless-rust/frontend/src/plugins/display/components/DisplaySettingsTab.tsx index 26ccb43..3113426 100644 --- a/headless-rust/frontend/src/plugins/display/components/DisplaySettingsTab.tsx +++ b/headless-rust/frontend/src/plugins/display/components/DisplaySettingsTab.tsx @@ -36,17 +36,17 @@ export function DisplaySettingsTab() { return (
{/* Top Title & Quick Power Status */} -
+
-

- - OLED Monochrome Display (SSD1306) +

+ + OLED Monochrome Display (SSD1306)

Configure the Raspberry Pi 5 I²C OLED screen, live telemetry layouts, and power modes.

-
+
{status?.mockMode ? ( Mock Mode @@ -68,16 +68,16 @@ export function DisplaySettingsTab() { {/* Hardware Disconnected / Error Diagnostic Banner */} {!status?.connected && !status?.mockMode && ( -
+
OLED Hardware: Disconnected {status?.error && ( - + Reason: {status.error} )}
- + Auto-reconnecting every 2s...
@@ -96,14 +96,15 @@ export function DisplaySettingsTab() { {/* Master Power */} -
-
+
+

Turn the OLED panel on or sleep the controller hardware.

void togglePower()} disabled={saving} @@ -253,14 +254,15 @@ export function DisplaySettingsTab() {

Lap Timer Mode

-
-
+
+

Display speed at start and finish line alongside lap time.

void updateConfig({ @@ -277,14 +279,14 @@ export function DisplaySettingsTab() {

Sensor Alignment Mode

-
-
+
+

Display dual live Sick sensor barrier status blocks and lock indicator.

- + Active
@@ -298,12 +300,12 @@ export function DisplaySettingsTab() { Raspberry Pi 5 GPIO Pinout Reference Click to expand -
+
VCC: Pin 1 (3.3V) GND: Pin 6 SDA: Pin 3 (GPIO 2) SCL: Pin 5 (GPIO 3) - Bus: {config.i2cBus} • Addr: 0x{config.i2cAddress.toString(16).toUpperCase()} + Bus: {config.i2cBus} • Addr: 0x{config.i2cAddress.toString(16).toUpperCase()}
diff --git a/headless-rust/frontend/src/plugins/display/store.ts b/headless-rust/frontend/src/plugins/display/store.ts index 49d3380..5ade22a 100644 --- a/headless-rust/frontend/src/plugins/display/store.ts +++ b/headless-rust/frontend/src/plugins/display/store.ts @@ -102,21 +102,12 @@ export const useDisplayStore = create()((set, get) => ({ set({ autoRefresh: enabled }); }, - syncDashboardMode: async (dashboardMode: string) => { + syncDashboardMode: async (_dashboardMode: string) => { const { config } = get(); - // Only auto-switch if mode is set to auto or explicitly matching + // In auto mode, backend OLED render loop automatically matches operating mode. + // Do NOT call setDisplayMode here to avoid overwriting auto mode with a locked screen. if (config?.mode === "auto") { - let targetMode = "speedcamera"; - if (dashboardMode === "laptimer") targetMode = "laptimer"; - else if (dashboardMode === "alignment") targetMode = "alignment"; - - // If active screen is different, set mode - try { - await (getRpc().request as any).setDisplayMode({ mode: targetMode }); - void get().fetchPreview(); - } catch (err) { - console.debug("[plugin:display] Mode sync error:", err); - } + void get().fetchPreview(); } }, })); diff --git a/headless-rust/frontend/src/routes/__root.tsx b/headless-rust/frontend/src/routes/__root.tsx index 875d678..f45e07e 100644 --- a/headless-rust/frontend/src/routes/__root.tsx +++ b/headless-rust/frontend/src/routes/__root.tsx @@ -33,7 +33,6 @@ function Root() { .then((settings) => { loadCameraSettings(settings); if (settings.selectedPort) setSelectedPort(settings.selectedPort); - if (settings.maxSpeed) setMaxSpeed(settings.maxSpeed); }) .catch((err) => console.warn("[root] Failed to load settings:", err)); @@ -42,6 +41,7 @@ function Root() { void refreshSerialStatus(); void refreshArmedStatus(); void loadTeableState(); + void getRpc().request.sendCommand({ json: JSON.stringify({ command: "ping" }) }).catch(() => {}); // 3. Hydrate latest violation for instant preview on home screen getRpc() @@ -55,7 +55,6 @@ function Root() { }, [ loadCameraSettings, setSelectedPort, - setMaxSpeed, refreshCameraStatus, refreshSerialStatus, refreshArmedStatus, diff --git a/headless-rust/frontend/src/routes/index.tsx b/headless-rust/frontend/src/routes/index.tsx index f8c245d..34d2f15 100644 --- a/headless-rust/frontend/src/routes/index.tsx +++ b/headless-rust/frontend/src/routes/index.tsx @@ -28,7 +28,6 @@ function HomePage() { const lastSpeed = useAppStore((s) => s.lastSpeed); const lastDirection = useAppStore((s) => s.lastDirection); const lastViolation = useAppStore((s) => s.lastViolation); - const setMaxSpeed = useAppStore((s) => s.setMaxSpeed); const appMode = useAppStore((s) => s.appMode); const isArmed = useAppStore((s) => s.isArmed); const availableModes = useAppStore((s) => s.availableModes); @@ -70,17 +69,6 @@ function HomePage() { setPendingTargetMode(null); }; - - // Load relevant settings into the store on mount - useEffect(() => { - getRpc() - .request.getSettings({}) - .then((settings) => { - setMaxSpeed(settings.maxSpeed); - }) - .catch(() => toast.error("Failed to load settings")); - }, [setMaxSpeed]); - return (
{/* Top Header: Status Badges & Home Mode Switcher */} diff --git a/headless-rust/frontend/src/routes/settings/SpeedCameraTab.tsx b/headless-rust/frontend/src/routes/settings/SpeedCameraTab.tsx index 18ded97..b2d53af 100644 --- a/headless-rust/frontend/src/routes/settings/SpeedCameraTab.tsx +++ b/headless-rust/frontend/src/routes/settings/SpeedCameraTab.tsx @@ -41,8 +41,10 @@ export function SpeedCameraTab() { const loadFromDb = useCallback(async () => { const settings = await getRpc().request.getSettings({}); - setValues(settings); - setSaved(settings); + // maxSpeed is never stored or read from DB; ESP is the single source of truth + const { maxSpeed: _legacyDbSpeed, ...rest } = settings; + setValues((prev) => ({ ...prev, ...rest })); + setSaved((prev) => ({ ...prev, ...rest })); return settings; }, []); @@ -82,12 +84,14 @@ export function SpeedCameraTab() { const handleSaveHw = async () => { setSavingHw(true); try { + // Save non-ESP settings to DB (do not save maxSpeed) await Promise.all( - SPEED_CAMERA_FIELDS.map(({ key }) => + SPEED_CAMERA_FIELDS.filter(({ key }) => key !== "maxSpeed").map(({ key }) => getRpc().request.saveSetting({ key, value: String(values[key]) }) ) ); + // Send hardware settings to ESP (ESP is single source of truth for maxSpeed) await Promise.all( SPEED_CAMERA_FIELDS.filter(({ key }) => values[key] !== saved[key] && key in SERIAL_SYNC).map( ({ key }) => diff --git a/headless-rust/frontend/src/stores/slices/measurementSlice.ts b/headless-rust/frontend/src/stores/slices/measurementSlice.ts index fac5014..ee2dd96 100644 --- a/headless-rust/frontend/src/stores/slices/measurementSlice.ts +++ b/headless-rust/frontend/src/stores/slices/measurementSlice.ts @@ -3,6 +3,7 @@ import type { SerialStatusPayload, Violation, EspPongConfig } from "@/shared/typ import type { CameraSlice } from "./cameraSlice"; import type { SystemSlice } from "./systemSlice"; import { pluginRegistry } from "@/plugins"; +import { getRpc } from "@/lib/rpc"; export interface MeasurementSlice { /** Last measured speed in km/h (null = no reading yet) */ @@ -40,12 +41,27 @@ export const createMeasurementSlice: StateCreator< // PONG is handled regardless of system state or app mode if (payload.status === "PONG") { set({ lastPongConfig: payload.config }); + if (payload.config?.maxSpeed !== undefined) { + set({ maxSpeed: payload.config.maxSpeed }); + } + return; + } + + if (payload.status === "CONFIG" && payload.key === "maxSpeed") { + const speedVal = payload.value; + set({ maxSpeed: speedVal }); + const current = get().lastPongConfig; + if (current) { + set({ lastPongConfig: { ...current, maxSpeed: speedVal } }); + } return; } if (payload.status === "CONNECTED") { const port = (payload as any).port || (get() as any).selectedPort || "connected"; (get() as any).setConnectedPort(port); + // Immediately query ESP config so UI is always synced with hardware + void getRpc().request.sendCommand({ json: JSON.stringify({ command: "ping" }) }); return; } diff --git a/headless-rust/src/db/settings.rs b/headless-rust/src/db/settings.rs index fe9c269..c3f256a 100644 --- a/headless-rust/src/db/settings.rs +++ b/headless-rust/src/db/settings.rs @@ -3,8 +3,10 @@ use rusqlite::{params, Connection, Result}; use std::collections::HashMap; pub fn init_defaults(conn: &Connection) -> Result<()> { + // Purge legacy maxSpeed from database so ESP is the single source of truth + let _ = conn.execute("DELETE FROM settings WHERE key = 'maxSpeed'", []); + let defaults = [ - ("maxSpeed", "30"), ("selectedPort", ""), ("cameraExposure", "5000"), ("cameraGain", "0"), @@ -65,7 +67,7 @@ pub fn get_settings(conn: &Connection) -> Result { }; Ok(AppSettings { - max_speed: get_f64("maxSpeed", 30.0), + max_speed: 30.0, // Default fallback; ESP is single source of truth and not stored in DB selected_port: get_str("selectedPort", ""), camera_exposure: get_f64("cameraExposure", 5000.0), camera_gain: get_f64("cameraGain", 0.0), @@ -95,9 +97,40 @@ pub fn get_settings(conn: &Connection) -> Result { } pub fn save_setting(conn: &Connection, key: &str, value: &str) -> Result<()> { + if key == "maxSpeed" { + // Speed limit is not stored in DB; ESP is single source of truth + return Ok(()); + } conn.execute( "INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value", params![key, value], )?; Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_max_speed_not_stored_in_db() { + let conn = Connection::open_in_memory().unwrap(); + conn.execute_batch( + "CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT NOT NULL);" + ).unwrap(); + + // Simulate legacy maxSpeed existing + conn.execute("INSERT INTO settings (key, value) VALUES ('maxSpeed', '120')", []).unwrap(); + + init_defaults(&conn).unwrap(); + + // Legacy maxSpeed must be purged by init_defaults + let count: i64 = conn.query_row("SELECT count(*) FROM settings WHERE key = 'maxSpeed'", [], |r| r.get(0)).unwrap(); + assert_eq!(count, 0); + + // Attempting to save maxSpeed must be a no-op + save_setting(&conn, "maxSpeed", "80").unwrap(); + let count_after: i64 = conn.query_row("SELECT count(*) FROM settings WHERE key = 'maxSpeed'", [], |r| r.get(0)).unwrap(); + assert_eq!(count_after, 0); + } +} diff --git a/headless-rust/src/main.rs b/headless-rust/src/main.rs index d017ee3..cfd656e 100644 --- a/headless-rust/src/main.rs +++ b/headless-rust/src/main.rs @@ -8,6 +8,7 @@ mod plugins; mod serial; mod state_machine; mod storage; +mod system; mod web; @@ -169,6 +170,7 @@ async fn main() -> Result<(), Box> { let pipeline_cam = camera.clone(); let pipeline_db = db.clone(); let pipeline_store = store.clone(); + let pipeline_serial = serial.clone(); let mut serial_rx = serial.subscribe(); tokio::spawn(async move { @@ -188,16 +190,16 @@ async fn main() -> Result<(), Box> { let db_clone = pipeline_db.clone(); let store_clone = pipeline_store.clone(); let v_tx = pipeline_violation_tx.clone(); + let cur_limit = pipeline_serial.get_max_speed(); tokio::task::spawn_blocking(move || { if let Some(jpg_bytes) = cam.capture_frame_jpeg(90) { if let Ok(img_path) = store_clone.save_image_bytes(&jpg_bytes, "jpg") { let conn = db_clone.lock(); - let settings = db::settings::get_settings(&conn).unwrap_or_default(); let input = SaveViolationInput { image_base64: None, measured_speed: value, - max_speed: settings.max_speed, + max_speed: cur_limit, direction, }; if let Ok(v) = db::violations::insert_violation(&conn, &input, &img_path) { diff --git a/headless-rust/src/models.rs b/headless-rust/src/models.rs index 4cdff69..08e3e34 100644 --- a/headless-rust/src/models.rs +++ b/headless-rust/src/models.rs @@ -344,6 +344,11 @@ pub enum SerialStatusPayload { }, #[serde(rename = "DISCONNECTED")] Disconnected, + #[serde(rename = "CONFIG")] + Config { + key: String, + value: f64, + }, } #[derive(Debug, Clone, Serialize, Deserialize)] diff --git a/headless-rust/src/plugins/display/db.rs b/headless-rust/src/plugins/display/db.rs index 861f108..b4b8a28 100644 --- a/headless-rust/src/plugins/display/db.rs +++ b/headless-rust/src/plugins/display/db.rs @@ -18,7 +18,9 @@ pub fn get_config(conn: &Connection) -> Result { if let Some(row) = rows.next()? { let json_str: String = row.get(0)?; - if let Ok(cfg) = serde_json::from_str::(&json_str) { + if let Ok(mut cfg) = serde_json::from_str::(&json_str) { + // Default should always be "auto" - do not restore locked display mode from DB + cfg.mode = "auto".to_string(); return Ok(cfg); } } @@ -28,7 +30,11 @@ pub fn get_config(conn: &Connection) -> Result { } pub fn save_config(conn: &Connection, config: &DisplayConfig) -> Result<()> { - let json_str = serde_json::to_string(config).map_err(|e| { + let mut persistent_cfg = config.clone(); + // Do not save locked mode into database - default remains "auto" + persistent_cfg.mode = "auto".to_string(); + + let json_str = serde_json::to_string(&persistent_cfg).map_err(|e| { rusqlite::Error::ToSqlConversionFailure(Box::new(e)) })?; diff --git a/headless-rust/src/plugins/display/mod.rs b/headless-rust/src/plugins/display/mod.rs index 5c28c0d..1052e15 100644 --- a/headless-rust/src/plugins/display/mod.rs +++ b/headless-rust/src/plugins/display/mod.rs @@ -60,10 +60,8 @@ impl Plugin for DisplayPlugin { *c = saved_cfg.clone(); } - // Initialize speed limit from settings - let max_speed = crate::db::settings::get_settings(&conn) - .map(|s| s.max_speed) - .unwrap_or(30.0); + // Initialize speed limit from serial service (ESP is single source of truth) + let max_speed = ctx.serial.get_max_speed(); { let mut t = self.telemetry.lock().unwrap(); t.speed_limit = max_speed; @@ -108,6 +106,7 @@ impl Plugin for DisplayPlugin { t.armed = armed_arc.load(Ordering::Relaxed); t.camera_connected = camera_svc.get_status().connected; t.serial_connected = serial_svc.get_status().connected; + t.speed_limit = serial_svc.get_max_speed(); } let cfg = cfg_thread.lock().unwrap().clone(); diff --git a/headless-rust/src/serial/mock.rs b/headless-rust/src/serial/mock.rs index f993914..67b2df2 100644 --- a/headless-rust/src/serial/mock.rs +++ b/headless-rust/src/serial/mock.rs @@ -19,6 +19,7 @@ struct MockState { lap_start_time: Option, lap_start_speed: f64, alignment_active: bool, + max_speed: f64, } pub struct MockSerial { @@ -37,6 +38,7 @@ impl MockSerial { lap_start_time: None, lap_start_speed: 0.0, alignment_active: false, + max_speed: 30.0, })); let r = running.clone(); @@ -75,7 +77,7 @@ impl MockSerial { let mut guard = s.lock().unwrap(); match guard.lap_state { MockLapState::Idle => { - let payload = if speed > 40.0 { + let payload = if speed > guard.max_speed { SerialStatusPayload::Speeding { value: speed, tolerance: 3.0, @@ -190,11 +192,22 @@ impl MockSerial { let mut guard = self.state.lock().unwrap(); guard.alignment_active = false; } + "setMaxSpeed" => { + let val = v["value"].as_f64().unwrap_or(30.0); + { + let mut guard = self.state.lock().unwrap(); + guard.max_speed = val; + } + let _ = tx.send(SerialStatusPayload::Config { + key: "maxSpeed".to_string(), + value: val, + }); + } "ping" => { let guard = self.state.lock().unwrap(); let _ = tx.send(SerialStatusPayload::Pong { config: EspPongConfig { - max_speed: 30.0, + max_speed: guard.max_speed, flash_delay: Some(0.0), flash_duration: Some(5000.0), sensor_distance: 1.0, diff --git a/headless-rust/src/serial/mod.rs b/headless-rust/src/serial/mod.rs index 08c4c13..a18a00f 100644 --- a/headless-rust/src/serial/mod.rs +++ b/headless-rust/src/serial/mod.rs @@ -17,6 +17,7 @@ pub struct SerialService { session_id: Arc, is_running: Arc, status_sender: broadcast::Sender, + last_max_speed: Arc>, } impl SerialService { @@ -37,6 +38,7 @@ impl SerialService { session_id: Arc::new(AtomicU64::new(0)), is_running: Arc::new(AtomicBool::new(true)), status_sender: status_tx, + last_max_speed: Arc::new(Mutex::new(30.0)), }); if mock_mode { @@ -78,6 +80,15 @@ impl SerialService { } } + pub fn get_max_speed(&self) -> f64 { + *self.last_max_speed.lock().unwrap() + } + + #[allow(dead_code)] + pub fn set_max_speed_internal(&self, speed: f64) { + *self.last_max_speed.lock().unwrap() = speed; + } + pub fn list_ports(&self) -> Vec { if self.mock_mode { return vec![PortInfo { @@ -132,6 +143,7 @@ impl SerialService { let _ = self.status_sender.send(SerialStatusPayload::Connected { port: Some(port_path.to_string()), }); + self.send_command(r#"{"command":"ping"}"#); return; } @@ -173,6 +185,9 @@ impl SerialService { *this.active_port.lock().unwrap() = Some(port); + // Automatically ping ESP so speed limit and settings sync immediately + this.send_command(r#"{"command":"ping"}"#); + let mut reader = BufReader::new(reader_port); let mut line_buf = String::new(); @@ -279,6 +294,17 @@ impl SerialService { fn handle_line(&self, line: &str) { if let Ok(msg) = serde_json::from_str::(line) { + match &msg { + EspMessage::Pong { config } => { + *self.last_max_speed.lock().unwrap() = config.max_speed; + } + EspMessage::Config { key, value } => { + if key == "maxSpeed" { + *self.last_max_speed.lock().unwrap() = *value; + } + } + _ => {} + } let timestamp = chrono::Utc::now().timestamp_millis(); if let Some(payload) = msg.to_serial_status(timestamp) { let _ = self.status_sender.send(payload); diff --git a/headless-rust/src/serial/protocol.rs b/headless-rust/src/serial/protocol.rs index 5127fa7..728a12e 100644 --- a/headless-rust/src/serial/protocol.rs +++ b/headless-rust/src/serial/protocol.rs @@ -47,6 +47,11 @@ pub enum EspMessage { s1: bool, s2: bool, }, + #[serde(rename = "config")] + Config { + key: String, + value: f64, + }, #[serde(rename = "configError")] ConfigError { message: String }, #[serde(other)] @@ -108,6 +113,10 @@ impl EspMessage { sensor2_interrupted: *s2, timestamp, }), + Self::Config { key, value } => Some(SerialStatusPayload::Config { + key: key.clone(), + value: *value, + }), Self::ConfigError { .. } | Self::Unknown => None, } } diff --git a/headless-rust/src/system.rs b/headless-rust/src/system.rs new file mode 100644 index 0000000..1869f2a --- /dev/null +++ b/headless-rust/src/system.rs @@ -0,0 +1,84 @@ +use std::io::Write; +use std::process::{Command, Stdio}; + +/// Cleanly powers off the host machine (Raspberry Pi). +/// Supports passwordless sudo, direct systemctl/shutdown, and password-authenticated sudo. +pub fn shutdown_host(password: Option, mock_mode: bool) -> Result { + if mock_mode { + tracing::info!("[system] Host shutdown simulated (mock mode active)"); + return Ok(serde_json::json!({ + "success": true, + "simulated": true, + "message": "Host shutdown simulated successfully (mock mode)" + })); + } + + tracing::warn!("[system] Host shutdown command received, powering down..."); + + // 1. If password was provided, execute sudo with password through stdin (-S) + if let Some(ref pass) = password { + let trimmed = pass.trim(); + if !trimmed.is_empty() { + let mut child = Command::new("sudo") + .args(["-S", "-k", "shutdown", "-h", "now"]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .map_err(|e| format!("Failed to spawn sudo shutdown: {}", e))?; + + if let Some(mut stdin) = child.stdin.take() { + let _ = stdin.write_all(trimmed.as_bytes()); + let _ = stdin.write_all(b"\n"); + } + + let output = child + .wait_with_output() + .map_err(|e| format!("Failed to execute sudo shutdown: {}", e))?; + + if output.status.success() { + return Ok(serde_json::json!({ "success": true })); + } else { + let stderr = String::from_utf8_lossy(&output.stderr); + return Err(format!("Sudo shutdown failed: {}", stderr.trim())); + } + } + } + + // 2. Try passwordless sudo: sudo -n shutdown -h now (-n prevents interactive hang) + if let Ok(output) = Command::new("sudo").args(["-n", "shutdown", "-h", "now"]).output() { + if output.status.success() { + return Ok(serde_json::json!({ "success": true })); + } + } + + // 3. Try systemctl poweroff (often permitted by logind/polkit) + if let Ok(output) = Command::new("systemctl").arg("poweroff").output() { + if output.status.success() { + return Ok(serde_json::json!({ "success": true })); + } + } + + // 4. Try direct shutdown -h now (if running as root) + if let Ok(output) = Command::new("shutdown").args(["-h", "now"]).output() { + if output.status.success() { + return Ok(serde_json::json!({ "success": true })); + } + } + + Err("Shutdown failed: sudo permission with password is required".to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_shutdown_mock_mode() { + let res = shutdown_host(None, true); + assert!(res.is_ok()); + let val = res.unwrap(); + assert_eq!(val["simulated"], true); + assert_eq!(val["success"], true); + } +} From 08b66a9f400b527eedf5e545effa18e69b282e78 Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Thu, 10 Sep 2026 22:41:00 +0200 Subject: [PATCH 4/8] feat: implement network supervisor and enhance network state management - Added a new `NetworkSupervisor` struct to manage network state and events asynchronously. - Introduced a state machine for Wi-Fi connections with retry logic and fallback mechanisms. - Enhanced `SystemNetworkSummary` model to include additional network state information. - Updated various modules to integrate the network supervisor, including plugins, state machine, and web components. - Implemented RPC methods to retrieve network information and apply network modes. - Added socket.io events to broadcast network status changes to connected clients. --- headless-rust/src/main.rs | 6 + headless-rust/src/models.rs | 10 + headless-rust/src/network/mod.rs | 21 + headless-rust/src/network/state.rs | 388 ++++++++++++++++++ headless-rust/src/network/supervisor.rs | 503 ++++++++++++++++++++++++ headless-rust/src/plugins/mod.rs | 1 + headless-rust/src/state_machine.rs | 4 + headless-rust/src/web/mod.rs | 2 + headless-rust/src/web/rpc.rs | 22 +- headless-rust/src/web/socketio.rs | 19 + 10 files changed, 966 insertions(+), 10 deletions(-) create mode 100644 headless-rust/src/network/state.rs create mode 100644 headless-rust/src/network/supervisor.rs diff --git a/headless-rust/src/main.rs b/headless-rust/src/main.rs index cfd656e..1b1c7bd 100644 --- a/headless-rust/src/main.rs +++ b/headless-rust/src/main.rs @@ -114,6 +114,9 @@ async fn main() -> Result<(), Box> { let operating_mode = std::sync::Arc::new(std::sync::RwLock::new("speedcamera".to_string())); let notify_display = std::sync::Arc::new(tokio::sync::Notify::new()); + // ─── Network Supervisor Initialization ──────────────────────────────────── + let network_supervisor = network::NetworkSupervisor::new(config.mock_mode); + // ─── Plugin System Initialization ──────────────────────────────────────── let plugin_ctx = plugins::PluginContext { config: config.clone(), @@ -125,6 +128,7 @@ async fn main() -> Result<(), Box> { armed_tx: armed_tx.clone(), operating_mode: operating_mode.clone(), notify_display: notify_display.clone(), + network: network_supervisor.clone(), }; let mut plugin_reg = plugins::PluginRegistry::new(); // ponytail: modular plugins isolated from core daemon, respects disabled_plugins config @@ -161,6 +165,7 @@ async fn main() -> Result<(), Box> { plugin_registry.clone(), operating_mode.clone(), notify_display.clone(), + network_supervisor.clone(), )); // ─── Instant Shutter Trigger Pipeline (<10ms latency) ───────────────────── @@ -248,6 +253,7 @@ async fn main() -> Result<(), Box> { armed_tx, plugin_registry, state_machine, + network_supervisor, ); let listener = tokio::net::TcpListener::bind(&bind_addr).await?; diff --git a/headless-rust/src/models.rs b/headless-rust/src/models.rs index 08e3e34..5256d27 100644 --- a/headless-rust/src/models.rs +++ b/headless-rust/src/models.rs @@ -65,6 +65,16 @@ pub struct SystemNetworkSummary { #[serde(default, skip_serializing_if = "Option::is_none")] pub wifi_client: Option, pub interfaces: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub network_state: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub retry_attempt: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub max_attempts: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub connected_stations: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub time_to_next_action: Option, } fn default_network_mode() -> String { diff --git a/headless-rust/src/network/mod.rs b/headless-rust/src/network/mod.rs index 6af2356..9720d65 100644 --- a/headless-rust/src/network/mod.rs +++ b/headless-rust/src/network/mod.rs @@ -1,3 +1,9 @@ +pub mod state; +pub mod supervisor; + +pub use state::{EthernetMode, NetworkEvent, NetworkStateSnapshot, WifiState}; +pub use supervisor::NetworkSupervisor; + use crate::models::{ ApplyNetworkModeInput, NetworkInterfaceDetail, NetworkOperationResult, SubnetInfo, SystemNetworkSummary, WifiClientInfo, WifiScanResult, @@ -198,9 +204,24 @@ pub fn get_system_network_summary() -> SystemNetworkSummary { }, wifi_client: wifi_client_info, interfaces, + network_state: None, + retry_attempt: None, + max_attempts: None, + connected_stations: None, + time_to_next_action: None, } } +pub fn enrich_summary_with_snapshot(summary: &mut SystemNetworkSummary, snap: &NetworkStateSnapshot) { + summary.network_state = Some(snap.wifi_state.as_str().to_string()); + summary.retry_attempt = Some(snap.retry_attempt); + summary.max_attempts = Some(snap.max_attempts); + summary.connected_stations = Some(snap.connected_stations); + summary.time_to_next_action = Some(snap.time_to_next_action); + summary.wifi_mode = snap.wifi_state.as_str().to_string(); + summary.ethernet_mode = snap.ethernet_mode.as_str().to_string(); +} + /// Queries Wi-Fi link information (SSID, signal, power_save, default gateway) via Linux utilities fn query_wifi_runtime_info(wifi_iface: &str) -> (Option, Option, Option, Option) { let mut ssid = None; diff --git a/headless-rust/src/network/state.rs b/headless-rust/src/network/state.rs new file mode 100644 index 0000000..f12d757 --- /dev/null +++ b/headless-rust/src/network/state.rs @@ -0,0 +1,388 @@ +use serde::{Deserialize, Serialize}; + +// ponytail: pure state machine without external IO for deterministic transitions and zero-mock testing +pub const MAX_RETRY_ATTEMPTS: u32 = 6; +pub const RETRY_INTERVAL_SECS: u64 = 10; +pub const IDLE_PROBE_COOLDOWN_SECS: u64 = 60; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum WifiState { + ApSetup, + StationConnecting { + ssid: String, + attempt: u32, + max_attempts: u32, + }, + StationConnected { + ssid: String, + ip: String, + gateway: Option, + signal: Option, + }, + StationReconnecting { + ssid: String, + attempt: u32, + max_attempts: u32, + }, + FallbackAp { + target_ssid: Option, + stations_connected: usize, + probe_countdown_secs: u64, + }, +} + +impl WifiState { + pub fn as_str(&self) -> &'static str { + match self { + Self::ApSetup => "ap_setup", + Self::StationConnecting { .. } => "connecting", + Self::StationConnected { .. } => "connected", + Self::StationReconnecting { .. } => "reconnecting", + Self::FallbackAp { .. } => "fallback_ap", + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum EthernetMode { + CameraLan, + Dhcp, + Unmanaged, +} + +impl EthernetMode { + pub fn as_str(&self) -> &'static str { + match self { + Self::CameraLan => "camera-lan", + Self::Dhcp => "lan-dhcp", + Self::Unmanaged => "unmanaged", + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct NetworkStateSnapshot { + pub wifi_state: WifiState, + pub ethernet_mode: EthernetMode, + pub active_ssid: Option, + pub client_ip: Option, + pub ap_ip: String, + pub retry_attempt: u32, + pub max_attempts: u32, + pub connected_stations: usize, + pub time_to_next_action: u64, + pub timestamp_ms: i64, +} + +impl Default for NetworkStateSnapshot { + fn default() -> Self { + Self { + wifi_state: WifiState::ApSetup, + ethernet_mode: EthernetMode::CameraLan, + active_ssid: None, + client_ip: None, + ap_ip: "192.168.4.1".to_string(), + retry_attempt: 0, + max_attempts: MAX_RETRY_ATTEMPTS, + connected_stations: 0, + time_to_next_action: 0, + timestamp_ms: chrono::Utc::now().timestamp_millis(), + } + } +} + +#[derive(Debug, Clone)] +pub enum NetworkEvent { + UserConnect { ssid: String, password: Option }, + UserForget, + UserSetEthernet(EthernetMode), + ConnectionSucceeded { ip: String, gateway: Option, signal: Option }, + ConnectionAttemptFailed, + LinkLost, + StationsUpdated(usize), + Tick(u64), // elapsed seconds since last tick +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum TransitionEffect { + None, + ApplyApMode, + ApplyClientMode { ssid: String, password: Option }, + ProbeConnect { ssid: String }, + ApplyCameraLan, + ApplyEthernetDhcp, +} + +/// Pure state transition function +pub fn next_state( + current: &WifiState, + event: NetworkEvent, +) -> (WifiState, TransitionEffect) { + match (current, event) { + // User triggers connection from Web UI + (_, NetworkEvent::UserConnect { ssid, password }) => { + ( + WifiState::StationConnecting { + ssid: ssid.clone(), + attempt: 1, + max_attempts: MAX_RETRY_ATTEMPTS, + }, + TransitionEffect::ApplyClientMode { ssid, password }, + ) + } + + // User clicks "Forget Wi-Fi" + (_, NetworkEvent::UserForget) => ( + WifiState::ApSetup, + TransitionEffect::ApplyApMode, + ), + + // ─── StationConnecting ─────────────────────────────────────────────── + (WifiState::StationConnecting { ssid, .. }, NetworkEvent::ConnectionSucceeded { ip, gateway, signal }) => { + ( + WifiState::StationConnected { + ssid: ssid.clone(), + ip, + gateway, + signal, + }, + TransitionEffect::None, + ) + } + + (WifiState::StationConnecting { ssid, attempt, max_attempts }, NetworkEvent::ConnectionAttemptFailed) => { + if *attempt >= *max_attempts { + // Exhausted retries -> enter Fallback AP + ( + WifiState::FallbackAp { + target_ssid: Some(ssid.clone()), + stations_connected: 0, + probe_countdown_secs: IDLE_PROBE_COOLDOWN_SECS, + }, + TransitionEffect::ApplyApMode, + ) + } else { + // Retry again + ( + WifiState::StationConnecting { + ssid: ssid.clone(), + attempt: attempt + 1, + max_attempts: *max_attempts, + }, + TransitionEffect::ProbeConnect { ssid: ssid.clone() }, + ) + } + } + + // ─── StationConnected ──────────────────────────────────────────────── + (WifiState::StationConnected { ssid, .. }, NetworkEvent::LinkLost) => { + ( + WifiState::StationReconnecting { + ssid: ssid.clone(), + attempt: 1, + max_attempts: MAX_RETRY_ATTEMPTS, + }, + TransitionEffect::ProbeConnect { ssid: ssid.clone() }, + ) + } + + // ─── StationReconnecting ───────────────────────────────────────────── + (WifiState::StationReconnecting { ssid, .. }, NetworkEvent::ConnectionSucceeded { ip, gateway, signal }) => { + ( + WifiState::StationConnected { + ssid: ssid.clone(), + ip, + gateway, + signal, + }, + TransitionEffect::None, + ) + } + + (WifiState::StationReconnecting { ssid, attempt, max_attempts }, NetworkEvent::ConnectionAttemptFailed) => { + if *attempt >= *max_attempts { + ( + WifiState::FallbackAp { + target_ssid: Some(ssid.clone()), + stations_connected: 0, + probe_countdown_secs: IDLE_PROBE_COOLDOWN_SECS, + }, + TransitionEffect::ApplyApMode, + ) + } else { + ( + WifiState::StationReconnecting { + ssid: ssid.clone(), + attempt: attempt + 1, + max_attempts: *max_attempts, + }, + TransitionEffect::ProbeConnect { ssid: ssid.clone() }, + ) + } + } + + // ─── FallbackAp ────────────────────────────────────────────────────── + ( + WifiState::FallbackAp { + target_ssid, + probe_countdown_secs, + .. + }, + NetworkEvent::StationsUpdated(count), + ) => { + // If user phone/laptop connects to AP, freeze countdown + let new_countdown = if count > 0 { + IDLE_PROBE_COOLDOWN_SECS + } else { + *probe_countdown_secs + }; + ( + WifiState::FallbackAp { + target_ssid: target_ssid.clone(), + stations_connected: count, + probe_countdown_secs: new_countdown, + }, + TransitionEffect::None, + ) + } + + ( + WifiState::FallbackAp { + target_ssid, + stations_connected, + probe_countdown_secs, + }, + NetworkEvent::Tick(elapsed), + ) => { + // Only count down if 0 stations connected and target SSID is known + if *stations_connected == 0 && target_ssid.is_some() { + if *probe_countdown_secs <= elapsed { + let ssid = target_ssid.clone().unwrap(); + ( + WifiState::StationReconnecting { + ssid: ssid.clone(), + attempt: 1, + max_attempts: MAX_RETRY_ATTEMPTS, + }, + TransitionEffect::ProbeConnect { ssid }, + ) + } else { + ( + WifiState::FallbackAp { + target_ssid: target_ssid.clone(), + stations_connected: 0, + probe_countdown_secs: probe_countdown_secs.saturating_sub(elapsed), + }, + TransitionEffect::None, + ) + } + } else { + (current.clone(), TransitionEffect::None) + } + } + + // Default no-op + _ => (current.clone(), TransitionEffect::None), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_retry_exhaustion_transitions_to_fallback_ap() { + let mut state = WifiState::StationConnecting { + ssid: "TestWiFi".to_string(), + attempt: 1, + max_attempts: 6, + }; + + // Attempts 1 to 5 should remain in StationConnecting + for attempt in 1..6 { + let (next, effect) = next_state(&state, NetworkEvent::ConnectionAttemptFailed); + match next { + WifiState::StationConnecting { attempt: next_att, .. } => { + assert_eq!(next_att, attempt + 1); + } + _ => panic!("Expected StationConnecting on attempt {}", attempt), + } + assert_eq!(effect, TransitionEffect::ProbeConnect { ssid: "TestWiFi".to_string() }); + state = next; + } + + // 6th failed attempt MUST transition to FallbackAp + let (next, effect) = next_state(&state, NetworkEvent::ConnectionAttemptFailed); + match next { + WifiState::FallbackAp { target_ssid, stations_connected, .. } => { + assert_eq!(target_ssid, Some("TestWiFi".to_string())); + assert_eq!(stations_connected, 0); + } + _ => panic!("Expected FallbackAp after 6 failed attempts"), + } + assert_eq!(effect, TransitionEffect::ApplyApMode); + } + + #[test] + fn test_connected_stations_blocks_idle_probing() { + let state = WifiState::FallbackAp { + target_ssid: Some("TestWiFi".to_string()), + stations_connected: 1, // User is connected + probe_countdown_secs: 5, + }; + + // Tick event when user is connected should NOT trigger probe + let (next, effect) = next_state(&state, NetworkEvent::Tick(10)); + match next { + WifiState::FallbackAp { stations_connected, .. } => { + assert_eq!(stations_connected, 1); + } + _ => panic!("Expected to stay in FallbackAp while user is connected"), + } + assert_eq!(effect, TransitionEffect::None); + } + + #[test] + fn test_zero_stations_triggers_probe_after_cooldown() { + let state = WifiState::FallbackAp { + target_ssid: Some("TestWiFi".to_string()), + stations_connected: 0, + probe_countdown_secs: 5, + }; + + // Tick 6 seconds (exceeding 5s cooldown) -> trigger probe + let (next, effect) = next_state(&state, NetworkEvent::Tick(6)); + match next { + WifiState::StationReconnecting { ssid, attempt, .. } => { + assert_eq!(ssid, "TestWiFi"); + assert_eq!(attempt, 1); + } + _ => panic!("Expected StationReconnecting after cooldown"), + } + assert_eq!(effect, TransitionEffect::ProbeConnect { ssid: "TestWiFi".to_string() }); + } + + #[test] + fn test_link_lost_triggers_reconnect() { + let state = WifiState::StationConnected { + ssid: "MyRouter".to_string(), + ip: "192.168.0.50".to_string(), + gateway: Some("192.168.0.1".to_string()), + signal: Some(-55), + }; + + let (next, effect) = next_state(&state, NetworkEvent::LinkLost); + match next { + WifiState::StationReconnecting { ssid, attempt, max_attempts } => { + assert_eq!(ssid, "MyRouter"); + assert_eq!(attempt, 1); + assert_eq!(max_attempts, 6); + } + _ => panic!("Expected StationReconnecting"), + } + assert_eq!(effect, TransitionEffect::ProbeConnect { ssid: "MyRouter".to_string() }); + } +} diff --git a/headless-rust/src/network/supervisor.rs b/headless-rust/src/network/supervisor.rs new file mode 100644 index 0000000..8f85c8e --- /dev/null +++ b/headless-rust/src/network/supervisor.rs @@ -0,0 +1,503 @@ +use super::state::{ + next_state, EthernetMode, NetworkEvent, NetworkStateSnapshot, TransitionEffect, WifiState, + MAX_RETRY_ATTEMPTS, +}; +use crate::models::{ApplyNetworkModeInput, NetworkOperationResult}; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, RwLock}; +use std::time::{Duration, Instant}; +use tokio::sync::{broadcast, mpsc}; + +// ponytail: single background async supervisor actor with serialized command queue +pub struct NetworkSupervisor { + snapshot: Arc>, + cmd_tx: mpsc::Sender, + broadcast_tx: broadcast::Sender, + is_mock: Arc, +} + +#[derive(Debug)] +enum SupervisorCmd { + Event(NetworkEvent), + ApplyMode { + input: ApplyNetworkModeInput, + reply: tokio::sync::oneshot::Sender, + }, +} + +impl NetworkSupervisor { + pub fn new(is_mock: bool) -> Arc { + let (broadcast_tx, _) = broadcast::channel(32); + let (cmd_tx, mut cmd_rx) = mpsc::channel::(32); + let snapshot = Arc::new(RwLock::new(NetworkStateSnapshot::default())); + let is_mock = Arc::new(AtomicBool::new(is_mock)); + + let supervisor = Arc::new(Self { + snapshot: snapshot.clone(), + cmd_tx, + broadcast_tx: broadcast_tx.clone(), + is_mock: is_mock.clone(), + }); + + // Spawn background supervisor loop + tokio::spawn(async move { + let mut ticker = tokio::time::interval(Duration::from_secs(3)); + let mut last_tick = Instant::now(); + let mut current_wifi = WifiState::ApSetup; + let mut current_eth = EthernetMode::CameraLan; + let mut mock_retry_counter: u32 = 0; + + // Initial detection on boot + let initial_summary = super::get_system_network_summary(); + if let Some(ref client) = initial_summary.wifi_client { + if let Some(ref ip) = client.ip { + let ssid = client.ssid.clone().unwrap_or_else(|| "SavedWiFi".to_string()); + current_wifi = WifiState::StationConnected { + ssid, + ip: ip.clone(), + gateway: client.gateway.clone(), + signal: client.signal_dbm, + }; + } + } else if initial_summary.wifi_mode == "ap" || initial_summary.hotspot_ap.status == "ok" { + current_wifi = WifiState::ApSetup; + } + + if initial_summary.ethernet_mode == "dhcp" { + current_eth = EthernetMode::Dhcp; + } + + Self::update_snapshot( + &snapshot, + ¤t_wifi, + current_eth, + &broadcast_tx, + ); + + loop { + tokio::select! { + _ = ticker.tick() => { + let elapsed = last_tick.elapsed().as_secs(); + last_tick = Instant::now(); + + // ─── 1. Health & Link Polling ──────────────────────── + let is_mock_now = is_mock.load(Ordering::Relaxed); + if is_mock_now { + // In mock mode, advance retry counters if connecting + match ¤t_wifi { + WifiState::StationConnecting { ssid, attempt, max_attempts } => { + mock_retry_counter += 1; + if mock_retry_counter > 2 { + // Simulate successful connect after 2 retries + let (next, _) = next_state( + ¤t_wifi, + NetworkEvent::ConnectionSucceeded { + ip: "192.168.1.150".to_string(), + gateway: Some("192.168.1.1".to_string()), + signal: Some(-52), + }, + ); + current_wifi = next; + mock_retry_counter = 0; + Self::update_snapshot(&snapshot, ¤t_wifi, current_eth, &broadcast_tx); + } else { + let (next, _) = next_state(¤t_wifi, NetworkEvent::ConnectionAttemptFailed); + current_wifi = next; + Self::update_snapshot(&snapshot, ¤t_wifi, current_eth, &broadcast_tx); + } + } + WifiState::StationReconnecting { .. } => { + mock_retry_counter += 1; + if mock_retry_counter >= 6 { + // Fallback to AP after 6 retries + let (next, _) = next_state(¤t_wifi, NetworkEvent::ConnectionAttemptFailed); + current_wifi = next; + mock_retry_counter = 0; + Self::update_snapshot(&snapshot, ¤t_wifi, current_eth, &broadcast_tx); + } + } + WifiState::FallbackAp { .. } => { + let (next, _) = next_state(¤t_wifi, NetworkEvent::Tick(elapsed)); + if next != current_wifi { + current_wifi = next; + Self::update_snapshot(&snapshot, ¤t_wifi, current_eth, &broadcast_tx); + } + } + _ => {} + } + continue; + } + + // Physical Hardware Polling + match ¤t_wifi { + WifiState::StationConnected { ssid, .. } => { + // Verify client interface is still alive and has an IP + let summary = super::get_system_network_summary(); + let still_connected = summary.wifi_client.as_ref().map(|c| c.ip.is_some()).unwrap_or(false); + if !still_connected { + tracing::warn!("[network-supervisor] Wi-Fi link lost for SSID: {}", ssid); + let (next, effect) = next_state(¤t_wifi, NetworkEvent::LinkLost); + current_wifi = next; + Self::apply_effect(&effect).await; + Self::update_snapshot(&snapshot, ¤t_wifi, current_eth, &broadcast_tx); + } + } + + WifiState::StationConnecting { ssid, attempt, max_attempts } => { + let summary = super::get_system_network_summary(); + if let Some(ref client) = summary.wifi_client { + if let Some(ref ip) = client.ip { + tracing::info!("[network-supervisor] Connected to {} (IP: {})", ssid, ip); + let (next, _) = next_state( + ¤t_wifi, + NetworkEvent::ConnectionSucceeded { + ip: ip.clone(), + gateway: client.gateway.clone(), + signal: client.signal_dbm, + }, + ); + current_wifi = next; + Self::update_snapshot(&snapshot, ¤t_wifi, current_eth, &broadcast_tx); + continue; + } + } + + // If not yet connected, trigger attempt failed to step retry counter + let (next, effect) = next_state(¤t_wifi, NetworkEvent::ConnectionAttemptFailed); + current_wifi = next; + Self::apply_effect(&effect).await; + Self::update_snapshot(&snapshot, ¤t_wifi, current_eth, &broadcast_tx); + } + + WifiState::StationReconnecting { ssid, .. } => { + let summary = super::get_system_network_summary(); + if let Some(ref client) = summary.wifi_client { + if let Some(ref ip) = client.ip { + tracing::info!("[network-supervisor] Reconnected to {} (IP: {})", ssid, ip); + let (next, _) = next_state( + ¤t_wifi, + NetworkEvent::ConnectionSucceeded { + ip: ip.clone(), + gateway: client.gateway.clone(), + signal: client.signal_dbm, + }, + ); + current_wifi = next; + Self::update_snapshot(&snapshot, ¤t_wifi, current_eth, &broadcast_tx); + continue; + } + } + + let (next, effect) = next_state(¤t_wifi, NetworkEvent::ConnectionAttemptFailed); + current_wifi = next; + Self::apply_effect(&effect).await; + Self::update_snapshot(&snapshot, ¤t_wifi, current_eth, &broadcast_tx); + } + + WifiState::FallbackAp { .. } => { + // Query active AP stations count + let stations = Self::query_ap_stations_count(); + let (next, _) = next_state(¤t_wifi, NetworkEvent::StationsUpdated(stations)); + current_wifi = next; + + // Tick cooldown + let (next, effect) = next_state(¤t_wifi, NetworkEvent::Tick(elapsed)); + if next != current_wifi { + current_wifi = next; + Self::apply_effect(&effect).await; + } + Self::update_snapshot(&snapshot, ¤t_wifi, current_eth, &broadcast_tx); + } + + WifiState::ApSetup => { + // Standalone AP mode - ensure snapshot is accurate + let stations = Self::query_ap_stations_count(); + { + let mut s = snapshot.write().unwrap(); + s.connected_stations = stations; + } + } + } + } + + Some(cmd) = cmd_rx.recv() => { + match cmd { + SupervisorCmd::Event(ev) => { + let (next, effect) = next_state(¤t_wifi, ev); + current_wifi = next; + Self::apply_effect(&effect).await; + Self::update_snapshot(&snapshot, ¤t_wifi, current_eth, &broadcast_tx); + } + + SupervisorCmd::ApplyMode { input, reply } => { + let mode = input.mode.to_lowercase(); + match mode.as_str() { + "ap" | "hotspot" | "field" => { + let (next, effect) = next_state(¤t_wifi, NetworkEvent::UserForget); + current_wifi = next; + let res = Self::execute_script(&["ap"]).await; + Self::update_snapshot(&snapshot, ¤t_wifi, current_eth, &broadcast_tx); + let _ = reply.send(res); + } + "client" | "wifi-client" | "wifi" => { + let ssid = input.ssid.clone().unwrap_or_default(); + let pass = input.password.clone(); + if ssid.is_empty() { + let _ = reply.send(NetworkOperationResult { + success: false, + mode: "client".to_string(), + message: "SSID is required".to_string(), + details: None, + }); + continue; + } + + let (next, _) = next_state( + ¤t_wifi, + NetworkEvent::UserConnect { + ssid: ssid.clone(), + password: pass.clone(), + }, + ); + current_wifi = next; + Self::update_snapshot(&snapshot, ¤t_wifi, current_eth, &broadcast_tx); + + // Execute connect script asynchronously + let mut args = vec!["client", ssid.as_str()]; + if let Some(ref p) = pass { + if !p.is_empty() { + args.push(p.as_str()); + } + } + let res = Self::execute_script(&args).await; + if res.success { + let summary = super::get_system_network_summary(); + let ip = summary.wifi_client.as_ref().and_then(|c| c.ip.clone()).unwrap_or_else(|| "Waiting DHCP".to_string()); + let (succ_next, _) = next_state( + ¤t_wifi, + NetworkEvent::ConnectionSucceeded { + ip, + gateway: summary.wifi_client.as_ref().and_then(|c| c.gateway.clone()), + signal: summary.wifi_client.as_ref().and_then(|c| c.signal_dbm), + }, + ); + current_wifi = succ_next; + } else { + let (fail_next, effect) = next_state(¤t_wifi, NetworkEvent::ConnectionAttemptFailed); + current_wifi = fail_next; + Self::apply_effect(&effect).await; + } + Self::update_snapshot(&snapshot, ¤t_wifi, current_eth, &broadcast_tx); + let _ = reply.send(res); + } + "forget" | "reset-wifi" => { + let (next, _) = next_state(¤t_wifi, NetworkEvent::UserForget); + current_wifi = next; + let res = Self::execute_script(&["forget"]).await; + Self::update_snapshot(&snapshot, ¤t_wifi, current_eth, &broadcast_tx); + let _ = reply.send(res); + } + "camera-lan" | "lan-camera" => { + current_eth = EthernetMode::CameraLan; + let res = Self::execute_script(&["lan-camera"]).await; + Self::update_snapshot(&snapshot, ¤t_wifi, current_eth, &broadcast_tx); + let _ = reply.send(res); + } + "lan-dhcp" | "ethernet-dhcp" => { + current_eth = EthernetMode::Dhcp; + let res = Self::execute_script(&["lan-dhcp"]).await; + Self::update_snapshot(&snapshot, ¤t_wifi, current_eth, &broadcast_tx); + let _ = reply.send(res); + } + other => { + let _ = reply.send(NetworkOperationResult { + success: false, + mode: other.to_string(), + message: format!("Unknown mode: {}", other), + details: None, + }); + } + } + } + } + } + } + } + }); + + supervisor + } + + pub fn snapshot(&self) -> NetworkStateSnapshot { + self.snapshot.read().unwrap().clone() + } + + pub fn subscribe(&self) -> broadcast::Receiver { + self.broadcast_tx.subscribe() + } + + pub async fn apply_mode(&self, input: ApplyNetworkModeInput) -> Result { + let (reply_tx, reply_rx) = tokio::sync::oneshot::channel(); + self.cmd_tx + .send(SupervisorCmd::ApplyMode { input, reply: reply_tx }) + .await + .map_err(|e| format!("Supervisor channel closed: {}", e))?; + + reply_rx.await.map_err(|e| format!("Supervisor dropped reply: {}", e)) + } + + pub async fn send_event(&self, event: NetworkEvent) { + let _ = self.cmd_tx.send(SupervisorCmd::Event(event)).await; + } + + fn update_snapshot( + snapshot: &Arc>, + wifi: &WifiState, + eth: EthernetMode, + broadcast_tx: &broadcast::Sender, + ) { + let mut s = snapshot.write().unwrap(); + s.wifi_state = wifi.clone(); + s.ethernet_mode = eth; + s.timestamp_ms = chrono::Utc::now().timestamp_millis(); + + match wifi { + WifiState::ApSetup => { + s.active_ssid = Some("speedcamera".to_string()); + s.client_ip = None; + s.retry_attempt = 0; + s.time_to_next_action = 0; + } + WifiState::StationConnecting { ssid, attempt, max_attempts } => { + s.active_ssid = Some(ssid.clone()); + s.client_ip = None; + s.retry_attempt = *attempt; + s.max_attempts = *max_attempts; + s.time_to_next_action = (max_attempts - attempt + 1) as u64 * 10; + } + WifiState::StationConnected { ssid, ip, .. } => { + s.active_ssid = Some(ssid.clone()); + s.client_ip = Some(ip.clone()); + s.retry_attempt = 0; + s.time_to_next_action = 0; + } + WifiState::StationReconnecting { ssid, attempt, max_attempts } => { + s.active_ssid = Some(ssid.clone()); + s.client_ip = None; + s.retry_attempt = *attempt; + s.max_attempts = *max_attempts; + s.time_to_next_action = (max_attempts - attempt + 1) as u64 * 10; + } + WifiState::FallbackAp { target_ssid, stations_connected, probe_countdown_secs } => { + s.active_ssid = Some("speedcamera".to_string()); + s.client_ip = None; + s.connected_stations = *stations_connected; + s.time_to_next_action = *probe_countdown_secs; + } + } + + let snap_clone = s.clone(); + drop(s); + let _ = broadcast_tx.send(snap_clone); + } + + async fn apply_effect(effect: &TransitionEffect) { + match effect { + TransitionEffect::None => {} + TransitionEffect::ApplyApMode => { + tracing::info!("[network-supervisor] Applying AP Fallback Mode"); + Self::execute_script(&["ap"]).await; + } + TransitionEffect::ApplyClientMode { ssid, password } => { + tracing::info!("[network-supervisor] Connecting to Wi-Fi client: {}", ssid); + let mut args = vec!["client", ssid.as_str()]; + if let Some(ref p) = password { + if !p.is_empty() { + args.push(p.as_str()); + } + } + Self::execute_script(&args).await; + } + TransitionEffect::ProbeConnect { ssid } => { + tracing::info!("[network-supervisor] Background probe connect to: {}", ssid); + Self::execute_script(&["auto"]).await; + } + TransitionEffect::ApplyCameraLan => { + Self::execute_script(&["lan-camera"]).await; + } + TransitionEffect::ApplyEthernetDhcp => { + Self::execute_script(&["lan-dhcp"]).await; + } + } + } + + fn query_ap_stations_count() -> usize { + // Query station dump via iw + if let Ok(output) = Command::new("iw").args(["dev", "wlan0", "station", "dump"]).output() { + if output.status.success() { + let text = String::from_utf8_lossy(&output.stdout); + return text.lines().filter(|l| l.starts_with("Station ")).count(); + } + } + 0 + } + + async fn execute_script(args: &[&str]) -> NetworkOperationResult { + let script_paths = [ + Path::new("./scripts/setup-network.sh"), + Path::new("../scripts/setup-network.sh"), + Path::new("/home/pi/speedcamera/headless-rust/scripts/setup-network.sh"), + ]; + + let script = script_paths + .iter() + .find(|p| p.exists()) + .map(|p| p.to_path_buf()) + .unwrap_or_else(|| PathBuf::from("./scripts/setup-network.sh")); + + let args_owned: Vec = args.iter().map(|s| s.to_string()).collect(); + + tokio::task::spawn_blocking(move || { + let mut cmd = Command::new("sudo"); + cmd.arg(&script); + for a in &args_owned { + cmd.arg(a); + } + + tracing::info!("[network-supervisor] Executing: {:?}", cmd); + match cmd.output() { + Ok(out) => { + let stdout = String::from_utf8_lossy(&out.stdout).to_string(); + let stderr = String::from_utf8_lossy(&out.stderr).to_string(); + let details = if stderr.is_empty() { stdout } else { format!("{}\n{}", stdout, stderr) }; + + NetworkOperationResult { + success: out.status.success(), + mode: args_owned.first().cloned().unwrap_or_default(), + message: if out.status.success() { + "Network operation succeeded".to_string() + } else { + "Network operation failed".to_string() + }, + details: Some(details), + } + } + Err(err) => NetworkOperationResult { + success: false, + mode: args_owned.first().cloned().unwrap_or_default(), + message: format!("Execution failed: {}", err), + details: None, + }, + } + }) + .await + .unwrap_or_else(|e| NetworkOperationResult { + success: false, + mode: "error".to_string(), + message: format!("Join error: {}", e), + details: None, + }) + } +} diff --git a/headless-rust/src/plugins/mod.rs b/headless-rust/src/plugins/mod.rs index 41a115c..50f27cd 100644 --- a/headless-rust/src/plugins/mod.rs +++ b/headless-rust/src/plugins/mod.rs @@ -30,6 +30,7 @@ pub struct PluginContext { pub armed_tx: broadcast::Sender, pub operating_mode: Arc>, pub notify_display: Arc, + pub network: Arc, } diff --git a/headless-rust/src/state_machine.rs b/headless-rust/src/state_machine.rs index d7b01d6..458a8c5 100644 --- a/headless-rust/src/state_machine.rs +++ b/headless-rust/src/state_machine.rs @@ -77,6 +77,7 @@ pub struct SystemStateMachine { plugins: Arc, operating_mode: Arc>, notify_display: Arc, + network: Arc, } impl SystemStateMachine { @@ -90,6 +91,7 @@ impl SystemStateMachine { plugins: Arc, operating_mode: Arc>, notify_display: Arc, + network: Arc, ) -> Self { let (tx, _) = broadcast::channel(32); Self { @@ -105,6 +107,7 @@ impl SystemStateMachine { plugins, operating_mode, notify_display, + network, } } @@ -128,6 +131,7 @@ impl SystemStateMachine { armed_tx: self.armed_tx.clone(), operating_mode: self.operating_mode.clone(), notify_display: self.notify_display.clone(), + network: self.network.clone(), } } diff --git a/headless-rust/src/web/mod.rs b/headless-rust/src/web/mod.rs index 560fbe3..1f279f1 100644 --- a/headless-rust/src/web/mod.rs +++ b/headless-rust/src/web/mod.rs @@ -32,6 +32,7 @@ pub fn build_app( armed_tx: broadcast::Sender, plugins: Arc, state_machine: Arc, + network: Arc, ) -> Router { let (flash_tx, _) = broadcast::channel::(32); @@ -48,6 +49,7 @@ pub fn build_app( armed_tx, plugins: plugins.clone(), state_machine, + network, }); diff --git a/headless-rust/src/web/rpc.rs b/headless-rust/src/web/rpc.rs index 36b3ecf..2bc3630 100644 --- a/headless-rust/src/web/rpc.rs +++ b/headless-rust/src/web/rpc.rs @@ -44,6 +44,7 @@ pub struct RpcContext { pub armed_tx: broadcast::Sender, pub plugins: Arc, pub state_machine: Arc, + pub network: Arc, } @@ -546,10 +547,17 @@ async fn dispatch_method(ctx: &RpcContext, method: &str, params: Value) -> Resul "getPlatform" => Ok(Value::String(std::env::consts::OS.to_string())), "getNetworkInfo" => { - let summary = get_system_network_summary(); + let mut summary = get_system_network_summary(); + let snap = ctx.network.snapshot(); + crate::network::enrich_summary_with_snapshot(&mut summary, &snap); Ok(serde_json::to_value(summary).unwrap()) } + "getNetworkSnapshot" => { + let snap = ctx.network.snapshot(); + Ok(serde_json::to_value(snap).unwrap()) + } + "scanWifiNetworks" => { let results = tokio::task::spawn_blocking(move || crate::network::scan_wifi_networks()) .await @@ -560,9 +568,7 @@ async fn dispatch_method(ctx: &RpcContext, method: &str, params: Value) -> Resul "applyNetworkMode" => { let input: ApplyNetworkModeInput = serde_json::from_value(params).map_err(|e| e.to_string())?; - let res = tokio::task::spawn_blocking(move || crate::network::apply_network_mode(&input)) - .await - .map_err(|e| e.to_string())?; + let res = ctx.network.apply_mode(input).await?; Ok(serde_json::to_value(res).unwrap()) } @@ -572,9 +578,7 @@ async fn dispatch_method(ctx: &RpcContext, method: &str, params: Value) -> Resul ssid: None, password: None, }; - let res = tokio::task::spawn_blocking(move || crate::network::apply_network_mode(&input)) - .await - .map_err(|e| e.to_string())?; + let res = ctx.network.apply_mode(input).await?; Ok(serde_json::to_value(res).unwrap()) } @@ -585,9 +589,7 @@ async fn dispatch_method(ctx: &RpcContext, method: &str, params: Value) -> Resul ssid: None, password: None, }; - let res = tokio::task::spawn_blocking(move || crate::network::apply_network_mode(&input)) - .await - .map_err(|e| e.to_string())?; + let res = ctx.network.apply_mode(input).await?; Ok(serde_json::to_value(res).unwrap()) } diff --git a/headless-rust/src/web/socketio.rs b/headless-rust/src/web/socketio.rs index 49b2490..d4b8eb8 100644 --- a/headless-rust/src/web/socketio.rs +++ b/headless-rust/src/web/socketio.rs @@ -15,6 +15,7 @@ pub async fn on_connect(s: SocketRef, ctx: Arc) { let _ = s.emit("serialStatus", &ctx.serial.get_status_payload()); let _ = s.emit("armedStatus", &json!({ "armed": ctx.armed.load(Ordering::SeqCst) })); let _ = s.emit("operatingMode", &ctx.state_machine.get_status()); + let _ = s.emit("networkStatus", &ctx.network.snapshot()); // Register RPC handler with AckSender for request-response RPC over Socket.io @@ -53,6 +54,7 @@ pub fn spawn_event_broadcaster(io: SocketIo, ctx: Arc) { let mut violation_rx = ctx.violation_tx.subscribe(); let mut armed_rx = ctx.armed_tx.subscribe(); let mut mode_rx = ctx.state_machine.subscribe(); + let mut network_rx = ctx.network.subscribe(); loop { tokio::select! { @@ -73,6 +75,23 @@ pub fn spawn_event_broadcaster(io: SocketIo, ctx: Arc) { } } + res = network_rx.recv() => { + match res { + Ok(snap) => { + if let Err(e) = io.emit("networkStatusChanged", &snap).await { + tracing::debug!("[socketio] Emit networkStatusChanged error: {:?}", e); + } + } + Err(broadcast::error::RecvError::Lagged(n)) => { + tracing::debug!("[socketio] Network broadcast lagged by {} messages", n); + } + Err(broadcast::error::RecvError::Closed) => { + tracing::warn!("[socketio] Network broadcast channel closed"); + break; + } + } + } + res = serial_rx.recv() => { match res { From 5eb828edac6e07714052694e5c9915cb4c72f3fe Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Thu, 10 Sep 2026 22:41:14 +0200 Subject: [PATCH 5/8] feat: add real-time network status updates and enhance network state management --- headless-rust/frontend/src/lib/rpc.ts | 8 +++ .../src/routes/settings/NetworkTab.tsx | 60 ++++++++++++++++++- headless-rust/frontend/src/shared/types.ts | 21 +++++++ 3 files changed, 87 insertions(+), 2 deletions(-) diff --git a/headless-rust/frontend/src/lib/rpc.ts b/headless-rust/frontend/src/lib/rpc.ts index 50a113d..6669e68 100644 --- a/headless-rust/frontend/src/lib/rpc.ts +++ b/headless-rust/frontend/src/lib/rpc.ts @@ -110,6 +110,14 @@ class SocketIoRpcClient { this.socket.on("operatingModeChanged", (payload: any) => { this.handlePushEvent("operatingModeChanged", payload); }); + + this.socket.on("networkStatus", (payload: any) => { + this.handlePushEvent("networkStatus", payload); + }); + + this.socket.on("networkStatusChanged", (payload: any) => { + this.handlePushEvent("networkStatusChanged", payload); + }); } diff --git a/headless-rust/frontend/src/routes/settings/NetworkTab.tsx b/headless-rust/frontend/src/routes/settings/NetworkTab.tsx index affc43d..0b30d5c 100644 --- a/headless-rust/frontend/src/routes/settings/NetworkTab.tsx +++ b/headless-rust/frontend/src/routes/settings/NetworkTab.tsx @@ -103,8 +103,14 @@ export function NetworkTab() { fetchNetworkSummary(); }, 12000); + // Listen to real-time network state machine transitions + const unbind = (getRpc() as any).on?.("networkStatusChanged", () => { + fetchNetworkSummary(); + }); + return () => { if (scanIntervalRef.current) clearInterval(scanIntervalRef.current); + if (unbind) unbind(); }; }, [fetchNetworkSummary, scanWifi]); @@ -187,6 +193,8 @@ export function NetworkTab() { const isApMode = network?.wifiMode === "ap" || network?.mode === "ap" || network?.mode === "field"; const isClientMode = network?.wifiMode === "client" || network?.mode === "wifi-client" || network?.mode === "client"; + const isConnecting = network?.networkState === "connecting" || network?.networkState === "reconnecting"; + const isFallbackAp = network?.networkState === "fallback_ap"; const isEthernetCameraLan = network?.ethernetMode === "camera-lan" || network?.cameraLan.status === "ok"; const getSignalIcon = (signal: number) => { @@ -235,7 +243,17 @@ export function NetworkTab() { Wireless Interface
- {isApMode ? ( + {isConnecting ? ( + + + {network?.networkState === "reconnecting" ? "Reconnecting" : "Connecting"} ({network?.retryAttempt || 1}/{network?.maxAttempts || 6}) + + ) : isFallbackAp ? ( + + + Fallback AP Active + + ) : isApMode ? ( AP Setup Hotspot @@ -253,7 +271,45 @@ export function NetworkTab() {
- {isClientMode && network?.wifiClient ? ( + {isConnecting ? ( + <> +
+ Target SSID: + {network?.wifiClient?.ssid || "External Wi-Fi"} +
+
+ Attempt: + {network?.retryAttempt || 1} of {network?.maxAttempts || 6} +
+ {network?.timeToNextAction != null && network.timeToNextAction > 0 && ( +
+ Fallback AP in: + {network.timeToNextAction}s +
+ )} + + ) : isFallbackAp ? ( + <> +
+ Fallback SSID: + speedcamera (Open) +
+
+ Static IP: + 192.168.4.1 +
+
+ Connected Devices: + {network?.connectedStations ?? 0} client(s) +
+ {network?.timeToNextAction != null && network.timeToNextAction > 0 && !network?.connectedStations && ( +
+ Auto-Reconnect: + Probe in {network.timeToNextAction}s +
+ )} + + ) : isClientMode && network?.wifiClient ? ( <>
SSID: diff --git a/headless-rust/frontend/src/shared/types.ts b/headless-rust/frontend/src/shared/types.ts index 45adc9b..81a941f 100644 --- a/headless-rust/frontend/src/shared/types.ts +++ b/headless-rust/frontend/src/shared/types.ts @@ -47,6 +47,24 @@ export interface SystemNetworkSummary { }; wifiClient?: WifiClientInfo | null; interfaces: NetworkInterfaceDetail[]; + networkState?: "ap_setup" | "connecting" | "connected" | "reconnecting" | "fallback_ap"; + retryAttempt?: number; + maxAttempts?: number; + connectedStations?: number; + timeToNextAction?: number; +} + +export interface NetworkStateSnapshot { + wifiState: any; + ethernetMode: "camera-lan" | "lan-dhcp" | "unmanaged"; + activeSsid?: string | null; + clientIp?: string | null; + apIp: string; + retryAttempt: number; + maxAttempts: number; + connectedStations: number; + timeToNextAction: number; + timestampMs: number; } export interface WifiScanResult { @@ -678,6 +696,9 @@ export type SpeedcameraRPC = { // Operating mode notifications operatingMode: OperatingModeStatus; operatingModeChanged: OperatingModeStatus; + // Network notifications + networkStatus: NetworkStateSnapshot; + networkStatusChanged: NetworkStateSnapshot; }>; }; From 4992b07c589d6d70406bc0a427ff88209dece24d Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Thu, 10 Sep 2026 22:41:22 +0200 Subject: [PATCH 6/8] feat: add station count functionality to network setup script --- headless-rust/scripts/setup-network.sh | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/headless-rust/scripts/setup-network.sh b/headless-rust/scripts/setup-network.sh index ae71779..a5c03c2 100755 --- a/headless-rust/scripts/setup-network.sh +++ b/headless-rust/scripts/setup-network.sh @@ -19,7 +19,7 @@ echo " Wireless (Hotspot/Wi-Fi): ${WIFI_IFACE}" echo "" # For modifying operations, request sudo privileges -if [ "$MODE" != "status" ] && [ "$MODE" != "scan" ]; then +if [ "$MODE" != "status" ] && [ "$MODE" != "scan" ] && [ "$MODE" != "station-count" ]; then sudo -v || { echo "Error: Sudo privileges required to change network configuration." >&2; exit 1; } fi @@ -399,7 +399,19 @@ show_status() { fi } +count_ap_stations() { + if command -v iw &>/dev/null; then + iw dev "${WIFI_IFACE}" station dump 2>/dev/null | grep -c "Station " || echo 0 + else + echo 0 + fi +} + case "$MODE" in + station-count) + count_ap_stations + ;; + ap|field|hotspot) apply_ap_mode ;; From 9ff5ca663e245badf76e0999e77ca858257c898b Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Thu, 10 Sep 2026 22:41:29 +0200 Subject: [PATCH 7/8] feat: enhance network state telemetry and add user guidance screens for connection status --- headless-rust/src/plugins/display/mod.rs | 44 ++++++++- headless-rust/src/plugins/display/renderer.rs | 92 +++++++++++++++++++ 2 files changed, 131 insertions(+), 5 deletions(-) diff --git a/headless-rust/src/plugins/display/mod.rs b/headless-rust/src/plugins/display/mod.rs index 1052e15..a322ac6 100644 --- a/headless-rust/src/plugins/display/mod.rs +++ b/headless-rust/src/plugins/display/mod.rs @@ -88,6 +88,7 @@ impl Plugin for DisplayPlugin { let is_conn_thread = self.is_connected.clone(); let last_err_thread = self.last_error.clone(); let op_mode_thread = ctx.operating_mode.clone(); + let network_svc = ctx.network.clone(); // Spawn dedicated background render thread (non-blocking for main server) std::thread::Builder::new() @@ -100,6 +101,8 @@ impl Plugin for DisplayPlugin { let mut reconnect_timer = Instant::now(); loop { + let net_snap = network_svc.snapshot(); + // Update live system state { let mut t = telem_thread.lock().unwrap(); @@ -107,6 +110,19 @@ impl Plugin for DisplayPlugin { t.camera_connected = camera_svc.get_status().connected; t.serial_connected = serial_svc.get_status().connected; t.speed_limit = serial_svc.get_max_speed(); + + // Network state machine telemetry + t.network_state = net_snap.wifi_state.as_str().to_string(); + t.network_ssid = net_snap.active_ssid.clone().unwrap_or_default(); + t.network_retry_attempt = net_snap.retry_attempt; + t.network_max_attempts = net_snap.max_attempts; + t.network_stations = net_snap.connected_stations; + t.network_time_to_action = net_snap.time_to_next_action; + if let Some(ref ip) = net_snap.client_ip { + t.wifi_ip = ip.clone(); + } else { + t.wifi_ip = net_snap.ap_ip.clone(); + } } let cfg = cfg_thread.lock().unwrap().clone(); @@ -151,13 +167,29 @@ impl Plugin for DisplayPlugin { *shared_fb = local_fb.clone(); } } else { - // Determine active mode: ponytail: mirror central state machine when in auto mode + // Determine active mode: ponytail: prioritize active measurement when armed; assist with network when idle let mode = if cfg.mode == "auto" { let sm = op_mode_thread.read().unwrap(); - match sm.as_str() { - "alignment" | "setup" => "alignment", - "laptimer" => "laptimer", - _ => "speedcamera", + let is_op_busy = telem.armed + || sm.as_str() == "alignment" + || sm.as_str() == "setup" + || sm.as_str() == "laptimer"; + + if is_op_busy { + match sm.as_str() { + "alignment" | "setup" => "alignment", + "laptimer" => "laptimer", + _ => "speedcamera", + } + } else { + // System is disarmed / idle: display network setup/retry guidance if not connected + match net_snap.wifi_state { + crate::network::WifiState::StationConnecting { .. } + | crate::network::WifiState::StationReconnecting { .. } => "network_connecting", + crate::network::WifiState::FallbackAp { .. } + | crate::network::WifiState::ApSetup => "network_ap", + crate::network::WifiState::StationConnected { .. } => "speedcamera", + } } } else { cfg.mode.as_str() @@ -174,6 +206,8 @@ impl Plugin for DisplayPlugin { "laptimer" => renderer::render_laptimer_screen(&mut local_fb, &cfg, &telem), "alignment" => renderer::render_alignment_screen(&mut local_fb, &cfg, &telem), "system" => renderer::render_system_screen(&mut local_fb, &telem), + "network_connecting" => renderer::render_network_connecting_screen(&mut local_fb, &telem), + "network_ap" => renderer::render_network_fallback_ap_screen(&mut local_fb, &telem), "off" => local_fb.clear(), _ => renderer::render_speed_screen(&mut local_fb, &cfg, &telem), } diff --git a/headless-rust/src/plugins/display/renderer.rs b/headless-rust/src/plugins/display/renderer.rs index 933490a..c7f5de8 100644 --- a/headless-rust/src/plugins/display/renderer.rs +++ b/headless-rust/src/plugins/display/renderer.rs @@ -107,6 +107,13 @@ pub struct RenderTelemetry { // System data pub camera_ip: String, pub wifi_ip: String, + // Network state machine telemetry (OLED user guidance) + pub network_state: String, // "ap_setup" | "connecting" | "connected" | "reconnecting" | "fallback_ap" + pub network_ssid: String, + pub network_retry_attempt: u32, + pub network_max_attempts: u32, + pub network_stations: usize, + pub network_time_to_action: u64, } // ─── Screen Renderers ──────────────────────────────────────────────── @@ -277,6 +284,76 @@ pub fn render_alignment_screen(fb: &mut FrameBuffer, _cfg: &DisplayConfig, telem } } +pub fn render_network_connecting_screen(fb: &mut FrameBuffer, telem: &RenderTelemetry) { + fb.clear(); + let is_reconnecting = telem.network_state == "reconnecting"; + draw_status_bar(fb, telem, if is_reconnecting { "RETRY" } else { "WIFI" }); + + let font_small = MonoTextStyle::new(&FONT_6X10, BinaryColor::On); + let font_tiny = MonoTextStyle::new(&FONT_4X6, BinaryColor::On); + + let title = if is_reconnecting { "RECONNECTING WI-FI" } else { "CONNECTING WI-FI" }; + let _ = Text::new(title, Point::new(4, 20), font_small).draw(fb); + + let ssid = if telem.network_ssid.is_empty() { "Unknown" } else { &telem.network_ssid }; + let ssid_str = format!("SSID: {}", ssid); + let _ = Text::new(&ssid_str, Point::new(4, 32), font_tiny).draw(fb); + + let max_att = if telem.network_max_attempts == 0 { 6 } else { telem.network_max_attempts }; + let att = telem.network_retry_attempt.clamp(1, max_att); + let att_str = format!("Attempt: {} of {}", att, max_att); + let _ = Text::new(&att_str, Point::new(4, 42), font_tiny).draw(fb); + + // Graphical progress bar: 110px width + let bar_rect = Rectangle::new(Point::new(4, 46), Size::new(110, 6)); + let stroke = PrimitiveStyle::with_stroke(BinaryColor::On, 1); + let _ = bar_rect.into_styled(stroke).draw(fb); + + let progress_width = ((110 * att) / max_att).max(1); + let fill_rect = Rectangle::new(Point::new(4, 46), Size::new(progress_width, 6)); + let fill = PrimitiveStyle::with_fill(BinaryColor::On); + let _ = fill_rect.into_styled(fill).draw(fb); + + let cd_str = format!("Fallback AP in: {}s", telem.network_time_to_action); + let _ = Text::new(&cd_str, Point::new(4, 60), font_tiny).draw(fb); +} + +pub fn render_network_fallback_ap_screen(fb: &mut FrameBuffer, telem: &RenderTelemetry) { + fb.clear(); + draw_status_bar(fb, telem, "AP-SETUP"); + + let font_small = MonoTextStyle::new(&FONT_6X10, BinaryColor::On); + let font_tiny = MonoTextStyle::new(&FONT_4X6, BinaryColor::On); + + if telem.network_stations > 0 { + // User actively connected to AP + let badge_rect = Rectangle::new(Point::new(4, 13), Size::new(120, 11)); + let fill = PrimitiveStyle::with_fill(BinaryColor::On); + let _ = badge_rect.into_styled(fill).draw(fb); + let inv_font = MonoTextStyle::new(&FONT_6X10, BinaryColor::Off); + let _ = Text::new("* USER CONNECTED *", Point::new(6, 21), inv_font).draw(fb); + + let _ = Text::new("Web Setup Active", Point::new(4, 34), font_small).draw(fb); + let _ = Text::new("http://192.168.4.1:3000", Point::new(4, 46), font_tiny).draw(fb); + + let clients_str = format!("Connected Devices: {}", telem.network_stations); + let _ = Text::new(&clients_str, Point::new(4, 57), font_tiny).draw(fb); + } else { + // Awaiting connection from user + let _ = Text::new("SETUP / FALLBACK AP", Point::new(4, 20), font_small).draw(fb); + let _ = Text::new("SSID : speedcamera (Open)", Point::new(4, 31), font_tiny).draw(fb); + let _ = Text::new("IP : 192.168.4.1:3000", Point::new(4, 41), font_tiny).draw(fb); + let _ = Text::new("Open browser to configure", Point::new(4, 51), font_tiny).draw(fb); + + let probe_str = if telem.network_time_to_action > 0 { + format!("Auto-reconnect in: {}s", telem.network_time_to_action) + } else { + "Awaiting connection...".to_string() + }; + let _ = Text::new(&probe_str, Point::new(4, 61), font_tiny).draw(fb); + } +} + pub fn render_system_screen(fb: &mut FrameBuffer, telem: &RenderTelemetry) { fb.clear(); draw_status_bar(fb, telem, "SYS"); @@ -340,5 +417,20 @@ mod tests { render_alignment_screen(&mut fb, &cfg, &telem); render_system_screen(&mut fb, &telem); + + // Test network assistance screens + telem.network_state = "connecting".to_string(); + telem.network_ssid = "RaceTrackWiFi".to_string(); + telem.network_retry_attempt = 3; + telem.network_max_attempts = 6; + telem.network_time_to_action = 30; + render_network_connecting_screen(&mut fb, &telem); + + telem.network_state = "fallback_ap".to_string(); + telem.network_stations = 0; + render_network_fallback_ap_screen(&mut fb, &telem); + + telem.network_stations = 2; + render_network_fallback_ap_screen(&mut fb, &telem); } } From a14a4ebded980e176ab5f2cc4e48dc4b1661a142 Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Thu, 10 Sep 2026 22:46:33 +0200 Subject: [PATCH 8/8] refactor: add dead code allowances for unused items in network state and supervisor modules --- headless-rust/src/network/mod.rs | 4 +++- headless-rust/src/network/state.rs | 3 +++ headless-rust/src/network/supervisor.rs | 14 ++++++++------ 3 files changed, 14 insertions(+), 7 deletions(-) diff --git a/headless-rust/src/network/mod.rs b/headless-rust/src/network/mod.rs index 9720d65..7a0bec0 100644 --- a/headless-rust/src/network/mod.rs +++ b/headless-rust/src/network/mod.rs @@ -1,7 +1,8 @@ pub mod state; pub mod supervisor; -pub use state::{EthernetMode, NetworkEvent, NetworkStateSnapshot, WifiState}; +#[allow(unused_imports)] +pub use state::*; pub use supervisor::NetworkSupervisor; use crate::models::{ @@ -364,6 +365,7 @@ pub fn scan_wifi_networks() -> Vec { } /// Applies a network mode switch (AP, Wi-Fi Client, Forget Wi-Fi, Ethernet LAN, Ethernet DHCP, or standard DHCP) +#[allow(dead_code)] pub fn apply_network_mode(input: &ApplyNetworkModeInput) -> NetworkOperationResult { let script_paths = [ Path::new("./scripts/setup-network.sh"), diff --git a/headless-rust/src/network/state.rs b/headless-rust/src/network/state.rs index f12d757..fecec89 100644 --- a/headless-rust/src/network/state.rs +++ b/headless-rust/src/network/state.rs @@ -2,6 +2,7 @@ use serde::{Deserialize, Serialize}; // ponytail: pure state machine without external IO for deterministic transitions and zero-mock testing pub const MAX_RETRY_ATTEMPTS: u32 = 6; +#[allow(dead_code)] pub const RETRY_INTERVAL_SECS: u64 = 10; pub const IDLE_PROBE_COOLDOWN_SECS: u64 = 60; @@ -95,6 +96,7 @@ impl Default for NetworkStateSnapshot { } #[derive(Debug, Clone)] +#[allow(dead_code)] pub enum NetworkEvent { UserConnect { ssid: String, password: Option }, UserForget, @@ -107,6 +109,7 @@ pub enum NetworkEvent { } #[derive(Debug, Clone, PartialEq, Eq)] +#[allow(dead_code)] pub enum TransitionEffect { None, ApplyApMode, diff --git a/headless-rust/src/network/supervisor.rs b/headless-rust/src/network/supervisor.rs index 8f85c8e..fcea116 100644 --- a/headless-rust/src/network/supervisor.rs +++ b/headless-rust/src/network/supervisor.rs @@ -1,6 +1,5 @@ use super::state::{ next_state, EthernetMode, NetworkEvent, NetworkStateSnapshot, TransitionEffect, WifiState, - MAX_RETRY_ATTEMPTS, }; use crate::models::{ApplyNetworkModeInput, NetworkOperationResult}; use std::path::{Path, PathBuf}; @@ -15,10 +14,12 @@ pub struct NetworkSupervisor { snapshot: Arc>, cmd_tx: mpsc::Sender, broadcast_tx: broadcast::Sender, + #[allow(dead_code)] is_mock: Arc, } #[derive(Debug)] +#[allow(dead_code)] enum SupervisorCmd { Event(NetworkEvent), ApplyMode { @@ -87,7 +88,7 @@ impl NetworkSupervisor { if is_mock_now { // In mock mode, advance retry counters if connecting match ¤t_wifi { - WifiState::StationConnecting { ssid, attempt, max_attempts } => { + WifiState::StationConnecting { .. } => { mock_retry_counter += 1; if mock_retry_counter > 2 { // Simulate successful connect after 2 retries @@ -145,7 +146,7 @@ impl NetworkSupervisor { } } - WifiState::StationConnecting { ssid, attempt, max_attempts } => { + WifiState::StationConnecting { ssid, .. } => { let summary = super::get_system_network_summary(); if let Some(ref client) = summary.wifi_client { if let Some(ref ip) = client.ip { @@ -235,7 +236,7 @@ impl NetworkSupervisor { let mode = input.mode.to_lowercase(); match mode.as_str() { "ap" | "hotspot" | "field" => { - let (next, effect) = next_state(¤t_wifi, NetworkEvent::UserForget); + let (next, _effect) = next_state(¤t_wifi, NetworkEvent::UserForget); current_wifi = next; let res = Self::execute_script(&["ap"]).await; Self::update_snapshot(&snapshot, ¤t_wifi, current_eth, &broadcast_tx); @@ -348,6 +349,7 @@ impl NetworkSupervisor { reply_rx.await.map_err(|e| format!("Supervisor dropped reply: {}", e)) } + #[allow(dead_code)] pub async fn send_event(&self, event: NetworkEvent) { let _ = self.cmd_tx.send(SupervisorCmd::Event(event)).await; } @@ -390,7 +392,7 @@ impl NetworkSupervisor { s.max_attempts = *max_attempts; s.time_to_next_action = (max_attempts - attempt + 1) as u64 * 10; } - WifiState::FallbackAp { target_ssid, stations_connected, probe_countdown_secs } => { + WifiState::FallbackAp { stations_connected, probe_countdown_secs, .. } => { s.active_ssid = Some("speedcamera".to_string()); s.client_ip = None; s.connected_stations = *stations_connected; @@ -413,7 +415,7 @@ impl NetworkSupervisor { TransitionEffect::ApplyClientMode { ssid, password } => { tracing::info!("[network-supervisor] Connecting to Wi-Fi client: {}", ssid); let mut args = vec!["client", ssid.as_str()]; - if let Some(ref p) = password { + if let Some(p) = password { if !p.is_empty() { args.push(p.as_str()); }