diff --git a/README.md b/README.md index 1da11b2..c1d0645 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,37 @@ # speedcamera -This repo contains three submodules: +An end-to-end vehicle speed measurement, GigE Vision camera capture, and remote management suite. -| Submodule | Description | +--- + +## Submodules & Modules + +| Directory | Description | | --------- | ----------- | -| [arduino](./arduino) | The firmware for an ESP8266 that reads two light barriers and measures the speed of passing vehicles. It sends the measurement data to the companion app using serial communication. | -| [electronbun](./electronbun) | A fast and improved rewrite of the speedcamera companion app made with electronbun. | -| [electron](./electron) | (LEGACY) The companion app made with Electron that displays the speed measurements, triggers the camera and provides a user interface for configuring the speed camera. | +| [**`headless-rust`**](./headless-rust) | **(Recommended)** High-performance single-binary headless daemon and responsive Web UI controller for Raspberry Pi 5 built with Rust (Axum 0.8, Socket.io, native Aravis C FFI, SQLite) and embedded React + Vite frontend. Features IoT-style open AP setup hotspot (`192.168.4.1`) with captive portal redirect, Client Wi-Fi operation mode with scannable connect QR codes, and a dedicated GigE Vision Camera LAN (`192.168.1.100`). | +| [**`arduino`**](./arduino) | Microcontroller firmware (ESP8266 / ESP32) reading dual optical light barriers to calculate vehicle speeds and transmit telemetry over Serial. | +| [**`electronbun`**](./electronbun) | Desktop companion application rewrite built with Electron and Bun. | +| [**`electron`**](./electron) | *(Legacy)* Desktop companion app made with classic Electron. | + +--- + +## Quick Deployment Commands (Raspberry Pi 5) + +All deployment and maintenance commands are executed from your development laptop over SSH. The scripts pull the repository and perform all frontend asset builds and native Rust compilation directly on the Raspberry Pi. + +```bash +cd headless-rust + +# 1. Fresh Pi Setup (Pi connected to Home LAN/Wi-Fi with DHCP) +bun run install:pi pi@raspberrypi.local + +# 2. Upgrade Existing Pi (in Client Wi-Fi Mode or Home LAN) +bun run deploy:pi pi@raspberrypi.local +# or when connected to Pi Wi-Fi hotspot during setup: +bun run deploy:pi pi@192.168.4.1 + +# 3. Complete Cleanup & Reset Network to DHCP +bun run cleanup:pi pi@raspberrypi.local +``` +For full documentation on architecture, network onboarding flow, offline/client operation, dependencies, migration guide, and local mock testing, see the [**Headless Rust Documentation**](./headless-rust/README.md). diff --git a/electronbun/src/bun/industrial-camera.ts b/electronbun/src/bun/industrial-camera.ts index 318dee2..8137d26 100644 --- a/electronbun/src/bun/industrial-camera.ts +++ b/electronbun/src/bun/industrial-camera.ts @@ -24,6 +24,88 @@ function notifyStatus() { } } +// ───────────────────────────────────────────────────────────────────────────── +// GENICAM TRIGGER CONFIGURATION QUIRKS (CRITICAL) +// +// 1. Independent Trigger Modes: GenICam cameras maintain independent TriggerMode +// states for EACH TriggerSelector (FrameStart, FrameBurstStart, AcquisitionStart). +// 2. Hardware Quirks: Some Hikrobot cameras ONLY support "FrameBurstStart" and +// will silently reject/ignore attempts to configure "FrameStart". +// 3. Fallback Logic: We must dynamically probe which selector the camera supports, +// explicitly disable TriggerMode on all OTHER selectors (to prevent them from +// causing free-run behavior), and only enable it on the supported selector. +// 4. Burst Count: When using FrameBurstStart, AcquisitionBurstFrameCount MUST be 1. +// 5. Frame Rate Limiter: AcquisitionFrameRateEnable MUST be false. Enabling it forces +// the internal clock to generate frames, silently overriding the software trigger +// and causing the flash to strobe continuously. +// ───────────────────────────────────────────────────────────────────────────── +function configureTriggerMode(cam: Camera, mode: "On" | "Off") { + console.log(`[industrial-camera] configureTriggerMode: Attempting to set mode '${mode}'`); + if (!cam.isFeatureAvailable("TriggerMode")) { + console.log("[industrial-camera] configureTriggerMode: TriggerMode feature is NOT available on this camera."); + return; + } + + const selectors = ["FrameStart", "FrameBurstStart", "AcquisitionStart"]; + let active: string | null = null; + for (const sel of selectors) { + try { + cam.setStringFeature("TriggerSelector", sel); + console.log(`[industrial-camera] configureTriggerMode: Successfully selected TriggerSelector = '${sel}'`); + active = sel; + break; + } catch (e) { + console.log(`[industrial-camera] configureTriggerMode: Failed to select TriggerSelector = '${sel}' - ${e}`); + } + } + + if (!active) { + console.log("[industrial-camera] configureTriggerMode: Could not select ANY known TriggerSelector!"); + return; + } + + if (mode === "On") { + // Disable all other selectors explicitly to prevent free-run strobing + for (const sel of selectors) { + if (sel !== active) { + try { + cam.setStringFeature("TriggerSelector", sel); + cam.setStringFeature("TriggerMode", "Off"); + console.log(`[industrial-camera] configureTriggerMode: Disabled TriggerMode on alternate selector '${sel}'`); + } catch (e) { + console.log(`[industrial-camera] configureTriggerMode: Failed to disable TriggerMode on alternate selector '${sel}' - ${e}`); + } + } + } + // Enable on active selector + try { + cam.setStringFeature("TriggerSelector", active); + cam.setStringFeature("TriggerMode", "On"); + console.log(`[industrial-camera] configureTriggerMode: Enabled TriggerMode on active selector '${active}'`); + + try { + cam.setStringFeature("TriggerSource", "Software"); + console.log(`[industrial-camera] configureTriggerMode: Set TriggerSource = 'Software' on '${active}'`); + } catch (e) { + console.log(`[industrial-camera] configureTriggerMode: Failed to set TriggerSource = 'Software' - ${e}`); + } + } catch (e) { + console.log(`[industrial-camera] configureTriggerMode: Failed to enable TriggerMode on active selector '${active}' - ${e}`); + } + } else { + // Disable on ALL selectors to ensure full free-run (or complete trigger disablement) + for (const sel of selectors) { + try { + cam.setStringFeature("TriggerSelector", sel); + cam.setStringFeature("TriggerMode", "Off"); + console.log(`[industrial-camera] configureTriggerMode: Disabled TriggerMode on selector '${sel}'`); + } catch (e) { + console.log(`[industrial-camera] configureTriggerMode: Failed to disable TriggerMode on selector '${sel}' - ${e}`); + } + } + } +} + export function initCamera() { if (isConnected) return; try { @@ -59,10 +141,7 @@ export function initCamera() { if (camera.isFeatureAvailable("AcquisitionMode")) { camera.setStringFeature("AcquisitionMode", "Continuous"); } - if (camera.isFeatureAvailable("TriggerMode")) { - camera.setStringFeature("TriggerMode", "On"); - camera.setStringFeature("TriggerSource", "Software"); - } + configureTriggerMode(camera, "On"); if (camera.isFeatureAvailable("LineSelector")) { try { @@ -78,7 +157,7 @@ export function initCamera() { } try { - camera.setStringFeature("LineSource", "ExposureActive"); + camera.setStringFeature("LineSource", "ExposureStartActive"); } catch { /* ignore */ } @@ -115,15 +194,18 @@ export function initCamera() { /* ignore */ } - // additional features based on DB - if (settings.frameRate) { - try { - camera.setBooleanFeature("AcquisitionFrameRateEnable", true); - camera.setFrameRate(Number(settings.frameRate)); - } catch { - /* ignore */ - } - } + try { + camera.setIntegerFeature("AcquisitionBurstFrameCount", 1); + console.log("[industrial-camera] initCamera: Set AcquisitionBurstFrameCount = 1"); + } catch { /* ignore */ } + + // Frame rate limit must be disabled in triggered mode on Hikrobot cameras. + // Enabling it forces the camera's internal frame generator to run, + // which breaks TriggerMode and causes the flash to fire continuously! + try { + camera.setBooleanFeature("AcquisitionFrameRateEnable", false); + console.log("[industrial-camera] initCamera: Disabled AcquisitionFrameRateEnable"); + } catch { /* ignore */ } if (settings.cameraWidth) { try { camera.setIntegerFeature("Width", Number(settings.cameraWidth)); } catch { /* ignore */ } } @@ -148,8 +230,19 @@ export function initCamera() { } export function disconnectCamera() { + setupStreamLoopActive = false; if (stream) { try { stream.stopAcquisition(); } catch { /* ignore */ } + } + // Restore safe camera state before disposing so the camera's volatile + // memory is never left with TriggerMode=Off (which causes free-run strobing). + if (camera) { + configureTriggerMode(camera, "On"); + try { camera.setBooleanFeature("StrobeEnable", false); } catch { + try { camera.setIntegerFeature("StrobeEnable", 0); } catch { /* ignore */ } + } + } + if (stream) { try { stream.dispose(); } catch { /* ignore */ } stream = null; } @@ -206,7 +299,15 @@ export async function captureFrame(): Promise { camera.executeCommand("TriggerSoftware"); } - const buffer = stream.timeoutPopBuffer(2_000_000); + // Non-blocking wait loop with deadline to prevent freezing the Bun event loop + const deadline = Date.now() + 2000; + let buffer = null; + while (Date.now() < deadline) { + buffer = stream.tryPopBuffer(); + if (buffer) break; + await new Promise((r) => setTimeout(r, 10)); + } + if (!buffer || !buffer.isSuccess) { if (buffer) stream.pushBuffer(buffer); console.error("[industrial-camera] Capture timeout or error"); @@ -260,10 +361,16 @@ export async function startSetupStream(pushFrame: (base64: string) => void) { try { stream.stopAcquisition(); } catch { /* ignore */ } try { camera.setIntegerFeature("StrobeEnable", 0); } catch { /* ignore */ } - try { camera.setStringFeature("TriggerMode", "Off"); } catch { /* ignore */ } + configureTriggerMode(camera, "Off"); try { camera.setStringFeature("GainAuto", "Continuous"); } catch { /* ignore */ } try { camera.setStringFeature("ExposureAuto", "Continuous"); } catch { /* ignore */ } + // Cap camera frame rate during setup preview to 10 FPS to prevent GigE network flood + try { + camera.setBooleanFeature("AcquisitionFrameRateEnable", true); + camera.setFrameRate(10); + } catch { /* ignore */ } + // Disable strobe properly by turning off StrobeEnable and unlinking LineSource try { camera.setBooleanFeature("StrobeEnable", false); } catch { try { camera.setIntegerFeature("StrobeEnable", 0); } catch { /* ignore */ } @@ -284,15 +391,30 @@ export async function startSetupStream(pushFrame: (base64: string) => void) { } async function pumpSetupFrames(pushFrame: (base64: string) => void) { + let isProcessing = false; + while (setupStreamLoopActive && stream && camera) { try { - const buffer = stream.timeoutPopBuffer(500_000); - if (!buffer || !buffer.isSuccess) { - if (buffer) stream.pushBuffer(buffer); - await new Promise(r => setTimeout(r, 10)); + // Non-blocking tryPopBuffer ensures Bun event loop is never frozen by C FFI + const buffer = stream.tryPopBuffer(); + if (!buffer) { + await new Promise((r) => setTimeout(r, 20)); + continue; + } + + if (!buffer.isSuccess) { + stream.pushBuffer(buffer); + await new Promise((r) => setTimeout(r, 20)); + continue; + } + + // If previous frame encoding/sending is still running, drop this frame to prevent buffer lag + if (isProcessing) { + stream.pushBuffer(buffer); continue; } + isProcessing = true; const w = buffer.width; const h = buffer.height; const fmt = buffer.pixelFormatName; @@ -308,12 +430,22 @@ async function pumpSetupFrames(pushFrame: (base64: string) => void) { sharpInst = sharp(data, { raw: { width: w, height: h, channels: 1 } }); } - // Encode as JPEG for live stream performance - const jpegBuffer = await sharpInst.jpeg({ quality: 80 }).toBuffer(); + // Downscale setup preview frame to max 800px width and compress to 60% quality JPEG + // to avoid CPU saturation on Pi and avoid saturating Wi-Fi AP bandwidth + const jpegBuffer = await sharpInst + .resize(800, null, { fit: "inside", withoutEnlargement: true }) + .jpeg({ quality: 60 }) + .toBuffer(); + pushFrame(jpegBuffer.toString("base64")); + isProcessing = false; + + // Throttle preview delivery to ~10 FPS + await new Promise((r) => setTimeout(r, 50)); } catch (e) { + isProcessing = false; console.error("Setup stream pump error", e); - await new Promise(r => setTimeout(r, 100)); + await new Promise((r) => setTimeout(r, 100)); } } } @@ -324,10 +456,13 @@ export function stopSetupStream() { try { stream.stopAcquisition(); } catch { /* ignore */ } + // CRITICAL: Restore TriggerMode FIRST to stop free-running acquisition + // before re-enabling strobe output, preventing any flash-strobing window. + configureTriggerMode(camera, "On"); + // Restore settings to those saved in DB const settings = getSettings(); try { camera.setIntegerFeature("StrobeEnable", 1); } catch { /* ignore */ } - try { camera.setStringFeature("TriggerMode", "On"); } catch { /* ignore */ } const exposureAuto = settings.exposureAuto || "Off"; const gainAuto = settings.gainAuto || "Off"; try { camera.setStringFeature("GainAuto", gainAuto); } catch { /* ignore */ } @@ -340,7 +475,7 @@ export function stopSetupStream() { if (camera.isFeatureAvailable("LineSelector")) { try { camera.setStringFeature("LineSelector", "Line1"); } catch { /* ignore */ } - try { camera.setStringFeature("LineSource", "ExposureActive"); } catch { /* ignore */ } + try { camera.setStringFeature("LineSource", "ExposureStartActive"); } catch { /* ignore */ } } if (gainAuto === "Off") { @@ -350,6 +485,14 @@ export function stopSetupStream() { try { camera.setExposureTime(Number(settings.cameraExposure) || 5000); } catch { /* ignore */ } } + // Frame rate limit must be disabled in triggered mode. + // Enabling it forces the camera's internal frame generator to run, + // which causes the flash to fire continuously! + try { + camera.setBooleanFeature("AcquisitionFrameRateEnable", false); + console.log("[industrial-camera] stopSetupStream: Disabled AcquisitionFrameRateEnable"); + } catch { /* ignore */ } + try { stream.startAcquisition(); } catch { /* ignore */ } } diff --git a/electronbun/src/components/LastCapturedImage.tsx b/electronbun/src/components/LastCapturedImage.tsx index 42dd6d0..32f8a68 100644 --- a/electronbun/src/components/LastCapturedImage.tsx +++ b/electronbun/src/components/LastCapturedImage.tsx @@ -21,7 +21,7 @@ export function LastCapturedImage() { Last capture ) : (
diff --git a/electronbun/src/stores/slices/lapSlice.ts b/electronbun/src/stores/slices/lapSlice.ts index aba2102..87bf75c 100644 --- a/electronbun/src/stores/slices/lapSlice.ts +++ b/electronbun/src/stores/slices/lapSlice.ts @@ -2,6 +2,7 @@ import type { StateCreator } from "zustand"; import type { Lap, LapSession, LapSessionWithLaps, SerialStatusPayload, AppSettings } from "@/shared/types"; import type { CameraSlice } from "./cameraSlice"; import type { TeableSlice } from "./teableSlice"; +import type { SystemSlice } from "./systemSlice"; import { getRpc } from "@/lib/rpc"; import { toast } from "sonner"; @@ -49,7 +50,7 @@ let lapSaving = false; // ─── Slice ──────────────────────────────────────────────────────────────────── export const createLapSlice: StateCreator< - LapSlice & CameraSlice & TeableSlice, + LapSlice & CameraSlice & TeableSlice & SystemSlice, [], [], LapSlice @@ -79,6 +80,7 @@ export const createLapSlice: StateCreator< currentLaps: [], lapNumber: 0, lapState: "waiting", + appMode: "laptimer", }); // Tell the ESP to start a lap session — it will drive all subsequent lap events await getRpc().request @@ -100,6 +102,7 @@ export const createLapSlice: StateCreator< set({ lapState: "idle", currentSession: null, + lapTimingStartedAt: null, // Keep currentLaps so the UI can show the final session summary }); }, @@ -107,13 +110,30 @@ export const createLapSlice: StateCreator< // ── State machine ────────────────────────────────────────────────────────── handleSerialStatusForLap: (payload) => { + // ── LAPWAITING: firmware opened session, waiting for first pass ─────────── + if (payload.status === "LAPWAITING") { + const { lapState, currentSession } = get(); + if (currentSession && lapState === "idle") { + set({ lapState: "waiting" }); + } + return; + } + + // ── LAPSTOPPED: session stopped on firmware ─────────────────────────────── + if (payload.status === "LAPSTOPPED") { + pendingStartImageBase64 = null; + lapSaving = false; + set({ lapState: "idle", lapTimingStartedAt: null }); + return; + } + // ── LAPSTART: first car pass — firmware opened a new lap ────────────────── if (payload.status === "LAPSTART") { - const { lapState, lapSettings } = get(); + const { lapState, lapSettings, currentSession } = get(); - // Accept "waiting" (first lap) or "timing" (MULTI lap N+1 boundary) + // Accept "waiting", "idle" (if session active), or "timing" (MULTI lap N+1 boundary) const isMultiContinuation = lapState === "timing" && lapSettings.lapMode === "multi"; - if (lapState !== "waiting" && !isMultiContinuation) return; + if (lapState !== "waiting" && (lapState !== "idle" || !currentSession) && !isMultiContinuation) return; set({ lapState: "timing", lapNumber: payload.lapNumber, lapTimingStartedAt: Date.now() }); diff --git a/electronbun/src/stores/slices/measurementSlice.ts b/electronbun/src/stores/slices/measurementSlice.ts index dc1f741..11a94d6 100644 --- a/electronbun/src/stores/slices/measurementSlice.ts +++ b/electronbun/src/stores/slices/measurementSlice.ts @@ -45,24 +45,32 @@ export const createMeasurementSlice: StateCreator< return; } - const { systemState, appMode } = get(); - // In PASSIVE mode, ignore all serial measurements - if (systemState === "PASSIVE") return; + // Lap-specific events MUST ALWAYS be forwarded to the lap state machine, + // regardless of systemState (e.g. even if camera is disconnected / PASSIVE) + if ( + payload.status === "LAPSTART" || + payload.status === "LAPEND" || + payload.status === "LAPWAITING" || + payload.status === "LAPSTOPPED" + ) { + get().handleSerialStatusForLap(payload); + return; + } - // In lap timer mode, delegate lap-specific events to the lap state machine - if (appMode === "laptimer") { - if (payload.status === "LAPSTART" || payload.status === "LAPEND" || - payload.status === "LAPWAITING" || payload.status === "LAPSTOPPED") { - get().handleSerialStatusForLap(payload); - return; - } - // Speed events still update the display but do not create violations in lap mode + const { systemState, appMode, currentSession } = get(); + + // If in lap timer mode or an active lap session is running, speed events + // update the display without creating speed camera violations + if (appMode === "laptimer" || currentSession !== null) { if (payload.status === "SPEEDING" || payload.status === "OK") { set({ lastSpeed: payload.value, lastDirection: payload.direction }); } return; } + // In PASSIVE mode, ignore all serial measurements + if (systemState === "PASSIVE") return; + if (payload.status === "SPEEDING") { const { value, direction } = payload; set({ lastSpeed: value, lastDirection: direction }); diff --git a/headless-rust/.gitignore b/headless-rust/.gitignore new file mode 100644 index 0000000..e96f1b3 --- /dev/null +++ b/headless-rust/.gitignore @@ -0,0 +1,31 @@ +# Generated by Cargo +# will have compiled files and executables +/target/ + +# Diagnostics +/diagnostics-output* + +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* +lerna-debug.log* + +node_modules +dist +dist-ssr +*.local + +# Editor directories and files +.vscode/* +!.vscode/extensions.json +.idea +.DS_Store +*.suo +*.ntvs* +*.njsproj +*.sln +*.sw? diff --git a/headless-rust/Cargo.lock b/headless-rust/Cargo.lock new file mode 100644 index 0000000..06a02fa --- /dev/null +++ b/headless-rust/Cargo.lock @@ -0,0 +1,3588 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ab_glyph" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01c0457472c38ea5bd1c3b5ada5e368271cb550be7a4ca4a0b4634e9913f6cc2" +dependencies = [ + "ab_glyph_rasterizer", + "owned_ttf_parser", +] + +[[package]] +name = "ab_glyph_rasterizer" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "366ffbaa4442f4684d91e2cd7c5ea7c4ed8add41959a31447066e279e432b618" + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "aligned" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee4508988c62edf04abd8d92897fca0c2995d907ce1dfeaf369dac3716a40685" +dependencies = [ + "as-slice", +] + +[[package]] +name = "aligned-vec" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc890384c8602f339876ded803c97ad529f3842aba97f6392b3dba0dd171769b" +dependencies = [ + "equator", +] + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "approx" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cab112f0a86d568ea0e627cc1d6be74a1e9cd55214684db5561995f6dad897c6" +dependencies = [ + "num-traits", +] + +[[package]] +name = "arbitrary" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1" +dependencies = [ + "derive_arbitrary", +] + +[[package]] +name = "arg_enum_proc_macro" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ae92a5119aa49cdbcf6b9f893fe4e1d98b04ccbf82ee0584ad948a44a734dea" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + +[[package]] +name = "as-slice" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "516b6b4f0e40d50dcda9365d53964ec74560ad4284da2e7fc97122cd83174516" +dependencies = [ + "stable_deref_trait", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "av-scenechange" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f321d77c20e19b92c39e7471cf986812cbb46659d2af674adc4331ef3f18394" +dependencies = [ + "aligned", + "anyhow", + "arg_enum_proc_macro", + "arrayvec", + "log", + "num-rational", + "num-traits", + "pastey", + "rayon", + "thiserror", + "v_frame", + "y4m", +] + +[[package]] +name = "av1-grain" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8cfddb07216410377231960af4fcab838eaa12e013417781b78bd95ee22077f8" +dependencies = [ + "anyhow", + "arrayvec", + "log", + "nom", + "num-rational", + "v_frame", +] + +[[package]] +name = "avif-serialize" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7178fe5f7d460b13895ebb9dcb28a3a6216d2df2574a0806cb51b555d297f38" +dependencies = [ + "arrayvec", +] + +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit 0.8.4", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "bit_field" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e4b40c7323adcfc0a41c4b88143ed58346ff65a288fc144329c5c45e05d70c6" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" + +[[package]] +name = "bitstream-io" +version = "4.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7eff00be299a18769011411c9def0d827e8f2d7bf0c3dbf53633147a8867fd1f" +dependencies = [ + "no_std_io2", +] + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "built" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c0e531d93d39c34eef561e929e8a7f86d77a5af08aac4f6d6e39976c51858e9" + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" + +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +dependencies = [ + "serde", +] + +[[package]] +name = "cc" +version = "1.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "509591b7bcd67f4ef775afad7662703b4935daaa6ec0e5605cfb1090b32a2b6d" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d524456ba66e72eb8b115ff89e01e497f8e6d11d78b70b1aa13c0fbd97540a81" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.0", + "rand_core 0.10.1", +] + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-traits", + "serde", + "wasm-bindgen", + "windows-link", +] + +[[package]] +name = "clap" +version = "4.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "473c7e07f409a8d772161724aa8db6a765a2532a70f9667eeb7b49d3d02fbdca" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b48fea5a88e9ae728a2dcbedbfc0e730f7d60da42e1cb049a83c9fb8b789889" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d012d2b9d65aca7f18f4d9878a045bc17899bba951561ba5ec3c2ba1eed9a061" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "clap_lex" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" + +[[package]] +name = "color_quant" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-channel" +version = "0.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d85363c37faeca707aef026efa9f3b34d077bce547e48f770770625c6013679e" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5181e0de7b61eb03a81e347d6dd8797bae9da5146707b51077e2d71a54ec0ceb" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17" + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + +[[package]] +name = "deranged" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" + +[[package]] +name = "derive_arbitrary" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer 0.10.4", + "crypto-common 0.1.7", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid", + "crypto-common 0.2.2", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "document-features" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", +] + +[[package]] +name = "either" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e5e8f6c15a24b9a3ee5efec809ccd006d3b30e8b3bb63c39af737c7f87daa1d" + +[[package]] +name = "engineioxide" +version = "0.17.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c48884059941b2b6255eabe1e9dca48e1aa01242299a7ef60844ded113b1d50" +dependencies = [ + "bytes", + "engineioxide-core", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "pin-project-lite", + "serde", + "serde_json", + "smallvec", + "thiserror", + "tokio", + "tokio-tungstenite", + "tokio-util", + "tower-layer", + "tower-service", +] + +[[package]] +name = "engineioxide-core" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06c5f98b2d2338ec0713bc222c753bfd18746bd76cbb115afa18aa07c6096553" +dependencies = [ + "base64", + "bytes", + "futures-util", + "http", + "http-body", + "http-body-util", + "pin-project-lite", + "rand 0.10.2", + "serde", + "serde_json", + "smallvec", +] + +[[package]] +name = "equator" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4711b213838dfee0117e3be6ac926007d7f433d7bbe33595975d4190cb07e6fc" +dependencies = [ + "equator-macro", +] + +[[package]] +name = "equator-macro" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44f23cf4b44bfce11a86ace86f8a73ffdec849c9fd00a386a53d278bd9e81fb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "exr" +version = "1.74.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "711fe42c9964295e01ee3fba3f9fe0e1d24b98886950d68efe81b1c76e21adf3" +dependencies = [ + "bit_field", + "half", + "lebe", + "miniz_oxide", + "num-complex", + "pulp", + "rayon-core", + "smallvec", + "zune-inflate", +] + +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + +[[package]] +name = "fast_image_resize" +version = "5.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbc7fe45cf92b43817ff62a3723e862b85bd1d06288f63007f7645d1d2f7a060" +dependencies = [ + "bytemuck", + "cfg-if", + "document-features", + "image", + "num-traits", + "rayon", + "thiserror", +] + +[[package]] +name = "fax" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a" + +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d45db016d36b838f563236e9193d0ee6ce38f3f68b6c94e914b4929c96bbb890" + +[[package]] +name = "flate2" +version = "1.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c" +dependencies = [ + "crc32fast", + "miniz_oxide", +] + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 6.0.0", + "rand_core 0.10.1", + "wasm-bindgen", +] + +[[package]] +name = "gif" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159" +dependencies = [ + "color_quant", + "weezl", +] + +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "zerocopy", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" +dependencies = [ + "ahash", +] + +[[package]] +name = "hashlink" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af" +dependencies = [ + "hashbrown", +] + +[[package]] +name = "headless-rust" +version = "0.1.0" +dependencies = [ + "ab_glyph", + "axum", + "base64", + "chrono", + "clap", + "fast_image_resize", + "futures", + "image", + "imageproc", + "mime_guess", + "nix 0.29.0", + "pkg-config", + "rayon", + "reqwest", + "rusqlite", + "rust-embed", + "serde", + "serde_json", + "serialport", + "socketioxide", + "tokio", + "tokio-stream", + "tower", + "tower-http", + "tracing", + "tracing-appender", + "tracing-subscriber", + "url", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hybrid-array" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "707114b52a152fa7bdb290cd7cd5912d9467273b6d74e21b8d81aca1f8533f6b" +dependencies = [ + "typenum", +] + +[[package]] +name = "hyper" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d22053281f852e11534f5198498373cbb59295120a20771d90f7ed1897490a72" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", + "webpki-roots", +] + +[[package]] +name = "hyper-util" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" +dependencies = [ + "base64", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "icu_collections" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" + +[[package]] +name = "icu_properties" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" + +[[package]] +name = "icu_provider" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92a7ed671a6aad807a8651a2e1782a6598fda9ce5185dd8158549e95a91c6428" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "image" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" +dependencies = [ + "bytemuck", + "byteorder-lite", + "color_quant", + "exr", + "gif", + "image-webp", + "moxcms", + "num-traits", + "png", + "qoi", + "ravif", + "rayon", + "rgb", + "tiff", + "zune-core", + "zune-jpeg", +] + +[[package]] +name = "image-webp" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" +dependencies = [ + "byteorder-lite", + "quick-error", +] + +[[package]] +name = "imageproc" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "602b4e8a4cc3e98372b766cd184ab532999bc0e839b7469e759511ccabc65d77" +dependencies = [ + "ab_glyph", + "approx", + "getrandom 0.2.17", + "image", + "itertools 0.12.1", + "nalgebra", + "num", + "rand 0.8.7", + "rand_distr", + "rayon", +] + +[[package]] +name = "imgref" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89194689a993ab15268672e99e7b0e19da2da3268ac682e8f02d29d4d1434cd7" + +[[package]] +name = "interpolate_name" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c34819042dc3d3971c46c2190835914dfbe0c3c13f61449b2997f4e9722dfa60" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "io-kit-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "617ee6cf8e3f66f3b4ea67a4058564628cde41901316e19f559e14c7c72c5e7b" +dependencies = [ + "core-foundation-sys", + "mach2", +] + +[[package]] +name = "ipnet" +version = "2.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a756c3fac73139e83f14c2d742155dd2b78d3ee56597b419a0579b7bdd6dd78" + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itertools" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569" +dependencies = [ + "either", +] + +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e0c1080212aad755ea003d18543e8768dd432c48819efd73a7bf1e39b7a5a3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" + +[[package]] +name = "lebe" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8" + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "libfuzzer-sys" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9fd2f41a1cba099f79a0b6b6c35656cf7c03351a7bae8ff0f28f25270f929d2" +dependencies = [ + "arbitrary", + "cc", +] + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "libsqlite3-sys" +version = "0.30.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "libudev" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78b324152da65df7bb95acfcaab55e3097ceaab02fb19b228a9eb74d55f135e0" +dependencies = [ + "libc", + "libudev-sys", +] + +[[package]] +name = "libudev-sys" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c8469b4a23b962c1396b9b451dda50ef5b283e8dd309d69033475fa9b334324" +dependencies = [ + "libc", + "pkg-config", +] + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "litrs" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" + +[[package]] +name = "loop9" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fae87c125b03c1d2c0150c90365d7d6bcc53fb73a9acaef207d2d065860f062" +dependencies = [ + "imgref", +] + +[[package]] +name = "lru-slab" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" + +[[package]] +name = "mach2" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d640282b302c0bb0a2a8e0233ead9035e3bed871f0b7e81fe4a1ec829765db44" +dependencies = [ + "libc", +] + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "matchit" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8863b587001c1b9a8a4e36008cebc6b3612cb1226fe2de94858e06092687b608" + +[[package]] +name = "matrixmultiply" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f607c237553f086e7043417a51df26b2eb899d3caff94e6a67592ff992fedc7" +dependencies = [ + "autocfg", + "rawpointer", +] + +[[package]] +name = "maybe-rayon" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ea1f30cedd69f0a2954655f7188c6a834246d2bcf1e315e2ac40c4b24dc9519" +dependencies = [ + "cfg-if", + "rayon", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "mime_guess" +version = "2.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e" +dependencies = [ + "mime", + "unicase", +] + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "mio" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30d65c71f1ce40ab09135ce117d742b9f8a19ff91a41a8b57ed50bc2de59c427" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "moxcms" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" +dependencies = [ + "num-traits", + "pxfm", +] + +[[package]] +name = "nalgebra" +version = "0.32.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b5c17de023a86f59ed79891b2e5d5a94c705dbe904a5b5c9c952ea6221b03e4" +dependencies = [ + "approx", + "matrixmultiply", + "num-complex", + "num-rational", + "num-traits", + "simba", + "typenum", +] + +[[package]] +name = "new_debug_unreachable" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" + +[[package]] +name = "nix" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "598beaf3cc6fdd9a5dfb1630c2800c7acd31df7aaf0f565796fba2b53ca1af1b" +dependencies = [ + "bitflags 1.3.2", + "cfg-if", + "libc", +] + +[[package]] +name = "nix" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46" +dependencies = [ + "bitflags 2.13.1", + "cfg-if", + "cfg_aliases", + "libc", + "memoffset", +] + +[[package]] +name = "no_std_io2" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "418abd1b6d34fbf6cae440dc874771b0525a604428704c76e48b29a5e67b8003" +dependencies = [ + "memchr", +] + +[[package]] +name = "nom" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405" +dependencies = [ + "memchr", +] + +[[package]] +name = "noop_proc_macro" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0676bb32a98c1a483ce53e500a81ad9c3d5b3f7c920c28c24e9cb0980d0b5bc8" + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "num" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23" +dependencies = [ + "num-bigint", + "num-complex", + "num-integer", + "num-iter", + "num-rational", + "num-traits", +] + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-complex" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" +dependencies = [ + "bytemuck", + "num-traits", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-derive" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-iter" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-bigint", + "num-integer", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", + "libm", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "owned_ttf_parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36820e9051aca1014ddc75770aab4d68bc1e9e632f0f5627c4086bc216fb583b" +dependencies = [ + "ttf-parser", +] + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + +[[package]] +name = "pastey" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags 2.13.1", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide", +] + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "profiling" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5" +dependencies = [ + "profiling-procmacros", +] + +[[package]] +name = "profiling-procmacros" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4488a4a36b9a4ba6b9334a32a39971f77c1436ec82c38707bce707699cc3bbcb" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "pulp" +version = "0.22.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "046aa45b989642ec2e4717c8e72d677b13edd831a4d3b6cf37d9a3e54912496a" +dependencies = [ + "bytemuck", + "cfg-if", + "libm", + "num-complex", + "paste", + "pulp-wasm-simd-flag", + "raw-cpuid", + "reborrow", + "version_check", +] + +[[package]] +name = "pulp-wasm-simd-flag" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d8f70e07b9c3962945a74e59ca1c511bba65b6419468acc217c457d93f3c740" + +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + +[[package]] +name = "qoi" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f6d64c71eb498fe9eae14ce4ec935c555749aef511cca85b5568910d6e48001" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "quick-error" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" + +[[package]] +name = "quinn" +version = "0.11.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c1a41e437b6bbd489372cd4971de128e85c855f56c57f283d20ff016cf7c0a8" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4bfc015262b9df63c8845072ce59068853ff5872180c2ce2f13038b970e560" +dependencies = [ + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand 0.10.2", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35a133f956daabe89a61a685c2649f13d82d5aa4bd5d12d1277e1072a21c0694" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22f6172bdec972074665ed81ed53b71da00bfc44b65a753cfde883ec4c702a1a" +dependencies = [ + "libc", + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.5", +] + +[[package]] +name = "rand" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_distr" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32cb0b9bc82b0a0876c2dd994a7e7a2683d3e7390ca40e6886785ef0c7e3ee31" +dependencies = [ + "num-traits", + "rand 0.8.7", +] + +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core 0.10.1", +] + +[[package]] +name = "rav1e" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43b6dd56e85d9483277cde964fd1bdb0428de4fec5ebba7540995639a21cb32b" +dependencies = [ + "aligned-vec", + "arbitrary", + "arg_enum_proc_macro", + "arrayvec", + "av-scenechange", + "av1-grain", + "bitstream-io", + "built", + "cfg-if", + "interpolate_name", + "itertools 0.14.0", + "libc", + "libfuzzer-sys", + "log", + "maybe-rayon", + "new_debug_unreachable", + "noop_proc_macro", + "num-derive", + "num-traits", + "paste", + "profiling", + "rand 0.9.5", + "rand_chacha 0.9.0", + "simd_helpers", + "thiserror", + "v_frame", + "wasm-bindgen", +] + +[[package]] +name = "ravif" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e52310197d971b0f5be7fe6b57530dcd27beb35c1b013f29d66c1ad73fbbcc45" +dependencies = [ + "avif-serialize", + "imgref", + "loop9", + "quick-error", + "rav1e", + "rayon", + "rgb", +] + +[[package]] +name = "raw-cpuid" +version = "11.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "498cd0dc59d73224351ee52a95fee0f1a617a2eae0e7d9d720cc622c73a54186" +dependencies = [ + "bitflags 2.13.1", +] + +[[package]] +name = "rawpointer" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3" + +[[package]] +name = "rayon" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + +[[package]] +name = "reborrow" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03251193000f4bd3b042892be858ee50e8b3719f2b08e5833ac4353724632430" + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags 2.13.1", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64", + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "webpki-roots", +] + +[[package]] +name = "rgb" +version = "0.8.53" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4" + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rusqlite" +version = "0.32.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7753b721174eb8ff87a9a0e799e2d7bc3749323e773db92e0984debb00019d6e" +dependencies = [ + "bitflags 2.13.1", + "chrono", + "fallible-iterator", + "fallible-streaming-iterator", + "hashlink", + "libsqlite3-sys", + "smallvec", +] + +[[package]] +name = "rust-embed" +version = "8.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9e7760e252aaba7b09f4be00e36476cf585bdb68a53552ac954cdf504ab4bc9" +dependencies = [ + "rust-embed-impl", + "rust-embed-utils", + "walkdir", +] + +[[package]] +name = "rust-embed-impl" +version = "8.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bcfc4d6f53af43755f7a723e4b6b8794fcce052a178dd8c6c1dadc5f5343097" +dependencies = [ + "mime_guess", + "proc-macro2", + "quote", + "rust-embed-utils", + "syn 2.0.119", + "walkdir", +] + +[[package]] +name = "rust-embed-utils" +version = "8.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42ffa149f6aa81b58a5b3011d01a857c4ed12c7a732d2c51947a4c7c692185f0" +dependencies = [ + "mime_guess", + "sha2", + "walkdir", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustls" +version = "0.23.43" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0283386ce02abc0151e1761d08802dfe86c173b0b494af5cbc086574e453da06" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0527518605e68109d875e248ea259b6758801cf165e4b2c2733ae3b51f12535a" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "safe_arch" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96b02de82ddbe1b636e6170c21be622223aea188ef2e139be0a5b219ec215323" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "serialport" +version = "4.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4d91116f97173694f1642263b2ff837f80d933aa837e2314969f6728f661df3" +dependencies = [ + "bitflags 2.13.1", + "cfg-if", + "core-foundation", + "core-foundation-sys", + "io-kit-sys", + "libudev", + "mach2", + "nix 0.26.4", + "scopeguard", + "unescaper", + "windows-sys 0.52.0", +] + +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + +[[package]] +name = "sha2" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.0", + "digest 0.11.3", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "simba" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "061507c94fc6ab4ba1c9a0305018408e312e17c041eb63bef8aa726fa33aceae" +dependencies = [ + "approx", + "num-complex", + "num-traits", + "paste", + "wide", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "simd_helpers" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95890f873bec569a0362c235787f3aca6e1e887302ba4840839bcc6459c42da6" +dependencies = [ + "quote", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.15.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" +dependencies = [ + "serde", +] + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "socketioxide" +version = "0.18.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b4ccb119c03dd29d44ad7de4dd7049ec0812d1aa05bdca5cc6f1cb5210d4f96" +dependencies = [ + "bytes", + "engineioxide", + "futures-core", + "futures-util", + "http", + "http-body", + "hyper", + "matchit 0.9.2", + "pin-project-lite", + "serde", + "socketioxide-core", + "socketioxide-parser-common", + "thiserror", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "socketioxide-core" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71e520fedd1addc257506026a31268d9a6eeee79b158c7fc8b270c4c7a1cfc4f" +dependencies = [ + "arbitrary", + "bytes", + "engineioxide-core", + "futures-core", + "serde", + "smallvec", + "thiserror", +] + +[[package]] +name = "socketioxide-parser-common" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ba9a856b0de7f665fe0d66fb7d60c74ad2e1810552c60a31f72e9aa6372cc02" +dependencies = [ + "bytes", + "itoa", + "serde", + "serde_json", + "socketioxide-core", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "symlink" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7973cce6668464ea31f176d85b13c7ab3bba2cb3b77a2ed26abd7801688010a" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "thiserror" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "tiff" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52" +dependencies = [ + "fax", + "flate2", + "half", + "quick-error", + "weezl", + "zune-jpeg", +] + +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinystr" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb4ebadaa0af04fab11ae01eb5f9fdb5f9c5b875506e210e71c07873528baa7f" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + +[[package]] +name = "tokio" +version = "1.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" +dependencies = [ + "bytes", + "libc", + "mio", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-stream" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b" +dependencies = [ + "futures-core", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tokio-tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f72a05e828585856dacd553fba484c242c46e391fb0e58917c942ee9202915c" +dependencies = [ + "futures-util", + "log", + "tokio", + "tungstenite", +] + +[[package]] +name = "tokio-util" +version = "0.7.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags 2.13.1", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-appender" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "050686193eb999b4bb3bc2acfa891a13da00f79734704c4b8b4ef1a10b368a3c" +dependencies = [ + "crossbeam-channel", + "symlink", + "thiserror", + "time", + "tracing-subscriber", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "ttf-parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" + +[[package]] +name = "tungstenite" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c01152af293afb9c7c2a57e4b559c5620b421f6d133261c60dd2d0cdb38e6b8" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.9.5", + "sha1", + "thiserror", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unescaper" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7285e83a80ce76f5e7bce79fa41f68d78ba62d1003cf27bf748ab24413808cf4" +dependencies = [ + "thiserror", +] + +[[package]] +name = "unicase" +version = "2.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "v_frame" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "666b7727c8875d6ab5db9533418d7c764233ac9c0cff1d469aec8fa127597be2" +dependencies = [ + "aligned-vec", + "num-traits", + "wasm-bindgen", +] + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b70935747edd64d89de3efa29d73789b806c15798f8e7dca4d8ac356b50ce70" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.77" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b7777d5cc23d0e91404e53ce2d5e8ec7acae3026b16233dba62cd3246457950" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77775f8f3f7217702089053b94958f8f54061a3f663417df76e19cbdcca29bc1" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e11d33f857dc2fb11b8bc75aee111aa9cbeb12cd9f25efd3d4c2a3dd4e235284" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 2.0.119", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef64dbcc55df09c7e5a46182d181c2cfa3e925f3da937ea764728b4bbb9dcbf" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-sys" +version = "0.3.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c435338968042f4f59a557f690a253676d47ce13ceb55d70100e7facf6620a30" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "weezl" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" + +[[package]] +name = "wide" +version = "0.7.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ce5da8ecb62bcd8ec8b7ea19f69a51275e91299be594ea5cc6ef7819e16cd03" +dependencies = [ + "bytemuck", + "safe_arch", +] + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "y4m" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a5a4b21e1a62b67a2970e6831bc091d7b87e119e7f9791aef9702e3bef04448" + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.56" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "556764e583adb45a9f8d413c2a147fa7e8d821e48e12b14fd560b607998b75eb" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.56" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2ab42fc20575779bd240faa45f94a74256f755c0fa9e89f0ede20d91d0cdfc1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94b5c6b5976d66c1d703c4fd17d3f5e43c8cedaacf604961b171adc7130896d8" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47402523226a02bfe5230160dc3ccc089aa6f6f19e7fcbb4e6f824bbb1b4aa62" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zune-core" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" + +[[package]] +name = "zune-inflate" +version = "0.2.54" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73ab332fe2f6680068f3582b16a24f90ad7096d5d39b974d1c0aff0125116f02" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "zune-jpeg" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" +dependencies = [ + "zune-core", +] diff --git a/headless-rust/Cargo.toml b/headless-rust/Cargo.toml new file mode 100644 index 0000000..71b7e3f --- /dev/null +++ b/headless-rust/Cargo.toml @@ -0,0 +1,36 @@ +[package] +name = "headless-rust" +version = "0.1.0" +edition = "2024" + +[dependencies] +axum = "0.8" +tower = "0.5" +tower-http = { version = "0.6", features = ["cors"] } +serialport = "4.9.0" +rusqlite = { version = "0.32", features = ["bundled", "chrono"] } +tokio = { version = "1", features = ["full"] } +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" +image = { version = "0.25", default-features = false, features = ["png", "jpeg", "webp"] } +fast_image_resize = { version = "5", features = ["rayon", "image"] } +rayon = "1.10" +imageproc = "0.25" +ab_glyph = "0.2" +chrono = { version = "0.4", features = ["serde"] } +reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] } +base64 = "0.22" +rust-embed = { version = "8.5", features = ["mime-guess"] } +mime_guess = "2.0" +clap = { version = "4.5", features = ["derive"] } +futures = "0.3" +tokio-stream = "0.1" +nix = { version = "0.29", features = ["net"] } +url = "2.5" +tracing = "0.1" +tracing-subscriber = { version = "0.3", features = ["env-filter"] } +tracing-appender = "0.2" +socketioxide = "0.18.6" + +[build-dependencies] +pkg-config = "0.3" diff --git a/headless-rust/README.md b/headless-rust/README.md new file mode 100644 index 0000000..cc09f50 --- /dev/null +++ b/headless-rust/README.md @@ -0,0 +1,314 @@ +# Speedcamera Headless (Rust & Axum / Socket.io) + +A lightweight, high-performance, single-binary speedcamera daemon and responsive web controller written in **Rust** using **Axum 0.8**, **Socketioxide (Socket.io v4)**, **native Aravis C FFI**, **SQLite**, and an embedded **React + Vite** frontend. + +Engineered specifically for **Raspberry Pi 5 with Raspberry Pi OS Lite** (zero desktop or GUI dependencies) with ultra-low latency hardware shutter triggering (<10ms) and rock-solid 24/7 reliability. Features an IoT-style onboarding workflow (similar to WLED/ESPHome) with an open 5GHz setup hotspot, captive portal redirection, scannable QR code Wi-Fi onboarding, and dedicated GigE Vision industrial camera networking. + +--- + +## Architecture & Network Operation Modes + +``` +┌────────────────────────────────────────────────────────────────────────┐ +│ Raspberry Pi 5 (Raspberry Pi OS Lite ARM64) │ +│ │ +│ • eth0 (Camera LAN): 192.168.1.100/24 <── GigE Vision Industrial │ +│ (or DHCP toggle) Camera (MTU 9000) │ +│ │ +│ • wlan0 (Wireless): 192.168.4.1/24 <── Open AP Setup Hotspot │ +│ or DHCP Client IP <── Client Mode (Operation) │ +│ │ +│ • speedcamera-rust Daemon (Single Standalone Binary) │ +│ ├── Axum 0.8 HTTP Server (REST API & Embedded Static Frontend) │ +│ ├── Socketioxide (Socket.io v4 RPC Server & Event Broadcaster) │ +│ ├── Native Aravis C FFI (Direct libaravis-0.8 on eth0) │ +│ ├── Serial Port Reader (serialport @ 115200 baud) │ +│ ├── Instant Trigger Pipeline (Serial Event -> Camera Shutter <10ms)│ +│ ├── SQLite Database (rusqlite WAL mode @ ~/.speedcamera) │ +│ └── Pure Rust Poliscan Overlay Renderer (image + imageproc) │ +└───────────────────────┬─────────────────────────────▲──────────────────┘ + │ Wi-Fi (AP or Client) │ Ethernet Cable + ▼ │ +┌──────────────────────────────────────────┐ ┌──────────────────────────┐ +│ Client Device (Phone / Tablet / Laptop) │ │ Industrial GigE Camera │ +│ │ │ │ +│ • Setup: Connect to open "speedcamera" │ │ • Subnet: 192.168.1.0/24 │ +│ • Normal: Access via local router IP │ │ • GenICam / Aravis 0.8 │ +│ • Scannable QR Code Wi-Fi onboarding │ │ • Jumbo frames (MTU 9000)│ +└──────────────────────────────────────────┘ └──────────────────────────┘ +``` + +--- + +## Network Onboarding Flow (WLED-Style) + +```mermaid +flowchart TD + A[Pi Boot / Fresh Install] --> B{Saved Wi-Fi Profile?} + B -->|No| C[Start Open 5GHz AP: 'speedcamera' @ 192.168.4.1] + B -->|Yes| D[Connect to Saved Wi-Fi Network] + D -->|Fail / Unreachable| C + D -->|Success| E[Client Mode Active: UI at Assigned DHCP IP] + C --> F[Connect Phone/PC to open 'speedcamera' Wi-Fi] + F --> G[Captive Portal Redirects to Network Settings] + G --> H[Scan & Select Wi-Fi Network] + H --> I[Enter Password & Click Connect] + I --> J[Popup: Scan QR Code to connect phone to same Wi-Fi] + J --> K[Pi switches wlan0 to Client Mode] + K --> E + E --> L[Access Settings > Network at any time to reconfigure or reset] + L -->|Forget Network| C +``` + +1. **Initial / Fallback AP Mode**: + - Open 5GHz Wi-Fi Hotspot: SSID **`speedcamera`** (No password, Channel 36, IP `192.168.4.1`). + - Built-in captive portal automatically opens the web dashboard when connecting from iOS, Android, macOS, or Windows. +2. **Wi-Fi Scanner & QR Code Transition**: + - Open the **Settings > Network** page (icons only, no emojis). + - Auto-scans nearby 2.4GHz & 5GHz networks with signal strength %, BSSID, channel, and security. + - Select your Wi-Fi, enter the password, and click **Connect**. + - A modal displays a **scannable Wi-Fi QR Code** so your smartphone can instantly switch to the same target network. +3. **Client Operation Mode**: + - The Pi connects to your local router via DHCP and serves the Web UI and API at its assigned IPv4 address. + - The dedicated Camera LAN on `eth0` remains active at static `192.168.1.100` (MTU 9000). +4. **Internet / Software Updates**: + - The Pi has internet access via Wi-Fi client mode. + - If Wi-Fi is not available, the **Network** tab includes an Ethernet toggle to switch `eth0` to standard DHCP for wired internet access. + +--- + +## Key Improvements Over Legacy Daemon + +| Feature | Legacy Bun / Electron | **Native Rust Daemon (`headless-rust`)** | +| :--- | :--- | :--- | +| **Runtime** | Bun / V8 JavaScript VM | **Pure native compiled binary (ELF ARM64 / x86_64)** | +| **Memory Footprint** | ~250MB+ | **~15MB** | +| **Camera Integration** | Flawed FFI / unstable wrapper | **Direct C FFI to `libaravis-0.8` (zero intermediate overhead)** | +| **Shutter Latency** | ~50–150ms JS event loop lag | **<10ms Instant Hardware Shutter Pipeline** | +| **Poliscan Skinning** | Heavy native canvas node addons | **Pure Rust `image` + `imageproc` + embedded TTF font** | +| **Frontend Serving** | Node / Bun file serving | **Baked into binary via `rust-embed` (Single binary deployment!)** | +| **Network Management** | Flaky AP password / drops | **Open AP setup + Client mode + QR Code + Captive Portal** | +| **Database** | Bun SQLite bindings | **Native `rusqlite` with WAL mode & foreign keys** | +| **Stability** | Event loop crashes on buffer overflows | **Ring buffer pool + safe Rust error handling + auto-reconnect** | + +--- + +## Migration Guide (From Old System) + +If you are running an existing version of Speedcamera on your Raspberry Pi, follow one of these migration methods: + +### Method 1: Remote Automated Update (Recommended) + +From your development laptop: + +```bash +cd headless-rust + +# 1. If Pi is connected to Home LAN / Wi-Fi via DHCP: +bun run deploy:pi pi@raspberrypi.local --build + +# 2. Or if currently connected to the Pi's old hotspot (192.168.4.1): +ssh pi@192.168.4.1 '~/speedcamera/headless-rust/scripts/setup-network.sh client "MyHomeWiFi" "MyPassword"' +# Then run deploy: +bun run deploy:pi pi@raspberrypi.local --build +``` + +### Method 2: Clean Re-Installation (Full Wipe & Fresh Setup) + +To remove all legacy services, network profiles, and start completely fresh: + +```bash +cd headless-rust + +# 1. Clean up old installation and restore DHCP network: +bun run cleanup:pi pi@raspberrypi.local --yes + +# 2. Run fresh installation: +bun run install:pi pi@raspberrypi.local +``` + +### Method 3: Direct on Raspberry Pi (via SSH / Console) + +If executing directly on the Raspberry Pi: + +```bash +# 1. Pull latest code +cd ~/speedcamera +git pull origin main + +# 2. Install new frontend dependency & build +cd ~/speedcamera/headless-rust +bun install +bun run build + +# 3. Compile release binary +cargo build --release + +# 4. Restart systemd service +sudo systemctl restart speedcamera + +# 5. Switch to new Open AP Setup Mode +sudo ./scripts/setup-network.sh ap +``` + +--- + +## Fresh Pi OS Requirements & Dependencies + +To set up a fresh Raspberry Pi OS image (recommended: **Raspberry Pi OS Lite 64-bit**), the automated installer handles all steps: + +```bash +cd headless-rust +bun run install:pi pi@raspberrypi.local +``` + +### Manual Dependency Reference + +#### 1. System Packages (APT) +```bash +sudo apt-get update +sudo apt-get install -y \ + libaravis-0.8-0 \ + libaravis-dev \ + libglib2.0-dev \ + libgobject-2.0-0 \ + libudev-dev \ + pkg-config \ + build-essential \ + esptool \ + network-manager \ + dnsmasq \ + iptables \ + curl \ + unzip \ + git \ + rsync \ + sqlite3 \ + libsqlite3-dev +``` + +#### 2. Rust Toolchain (`rustup`) +```bash +curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y +source "$HOME/.cargo/env" +``` + +#### 3. Bun Runtime (`bun.sh`) +```bash +curl -fsSL https://bun.sh/install | bash +source "$HOME/.bashrc" +``` + +#### 4. GigE Vision Network Socket Buffer & FQ-CoDel Tuning +```bash +sudo bash -c 'cat > /etc/sysctl.d/60-gige-camera.conf < HTTP server port (default: 3000) + -H, --host HTTP server bind address (default: 0.0.0.0) + -h, --help Print help +``` diff --git a/headless-rust/build.rs b/headless-rust/build.rs new file mode 100644 index 0000000..07b35a5 --- /dev/null +++ b/headless-rust/build.rs @@ -0,0 +1,28 @@ +fn main() { + println!("cargo:rerun-if-changed=build.rs"); + + // Probe aravis-0.8, glib-2.0, and gobject-2.0 via pkg-config + let probed = pkg_config::Config::new().atleast_version("0.8.0").probe("aravis-0.8"); + if let Ok(lib) = probed { + for path in &lib.link_paths { + println!("cargo:rustc-link-search=native={}", path.display()); + println!("cargo:rustc-link-arg=-Wl,-rpath,{}", path.display()); + } + for l in lib.libs { + println!("cargo:rustc-link-lib={}", l); + } + } else { + println!("cargo:warning=pkg-config aravis-0.8 failed. Using direct fallback linking."); + println!("cargo:rustc-link-lib=aravis-0.8"); + } + + // Always link glib-2.0 and gobject-2.0 required for g_error_free and g_object_unref + println!("cargo:rustc-link-lib=glib-2.0"); + println!("cargo:rustc-link-lib=gobject-2.0"); + + // Ensure standard library search paths and rpaths + println!("cargo:rustc-link-search=native=/usr/lib/aarch64-linux-gnu"); + println!("cargo:rustc-link-search=native=/usr/local/lib"); + println!("cargo:rustc-link-arg=-Wl,-rpath,/usr/local/lib64:/usr/local/lib:/usr/lib64:/usr/lib:/usr/lib/aarch64-linux-gnu"); +} + diff --git a/headless-rust/bun.lock b/headless-rust/bun.lock new file mode 100644 index 0000000..5a3efd5 --- /dev/null +++ b/headless-rust/bun.lock @@ -0,0 +1,1177 @@ +{ + "lockfileVersion": 1, + "configVersion": 1, + "workspaces": { + "": { + "name": "speedcamera-rust-ui", + "dependencies": { + "@fontsource-variable/figtree": "^5.2.10", + "@hugeicons/core-free-icons": "^4.1.1", + "@hugeicons/react": "^1.1.6", + "@tailwindcss/postcss": "^4.2.4", + "@tailwindcss/vite": "^4.2.4", + "@tanstack/react-router": "^1.168.23", + "class-variance-authority": "^0.7.1", + "clsx": "^2.1.1", + "lucide-react": "^1.8.0", + "next-themes": "^0.4.6", + "qrcode.react": "^4.2.0", + "radix-ui": "^1.4.3", + "react": "^18.3.1", + "react-dom": "^18.3.1", + "react-webcam": "^7.2.0", + "shadcn": "^4.7.0", + "socket.io-client": "^4.8.3", + "sonner": "^2.0.7", + "tailwind-merge": "^3.5.0", + "tw-animate-css": "^1.4.0", + "zod": "^4.3.6", + "zustand": "^5.0.12", + }, + "devDependencies": { + "@types/node": "^25.6.0", + "@types/react": "^18.3.12", + "@types/react-dom": "^18.3.1", + "@types/react-webcam": "^3.0.0", + "@vitejs/plugin-react": "^4.3.4", + "autoprefixer": "^10.4.20", + "concurrently": "^9.1.0", + "postcss": "^8.4.49", + "tailwindcss": "^4.2.4", + "typescript": "^5.7.2", + "vite": "^6.0.3", + }, + }, + }, + "packages": { + "@alloc/quick-lru": ["@alloc/quick-lru@5.2.0", "", {}, "sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw=="], + + "@babel/code-frame": ["@babel/code-frame@7.29.7", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.29.7", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw=="], + + "@babel/compat-data": ["@babel/compat-data@7.29.7", "", {}, "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg=="], + + "@babel/core": ["@babel/core@7.29.7", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/generator": "^7.29.7", "@babel/helper-compilation-targets": "^7.29.7", "@babel/helper-module-transforms": "^7.29.7", "@babel/helpers": "^7.29.7", "@babel/parser": "^7.29.7", "@babel/template": "^7.29.7", "@babel/traverse": "^7.29.7", "@babel/types": "^7.29.7", "@jridgewell/remapping": "^2.3.5", "convert-source-map": "^2.0.0", "debug": "^4.1.0", "gensync": "^1.0.0-beta.2", "json5": "^2.2.3", "semver": "^6.3.1" } }, "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA=="], + + "@babel/generator": ["@babel/generator@7.29.8", "", { "dependencies": { "@babel/parser": "^7.29.8", "@babel/types": "^7.29.8", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "jsesc": "^3.0.2" } }, "sha512-gZbepsdh3WDtgZKWL+vTPh71LSBrm/Y4/QDZBVCcYfmeTEEuoOYwlSy+G1StfJg+/Zy550u/3TATbm7qDbbMtg=="], + + "@babel/helper-annotate-as-pure": ["@babel/helper-annotate-as-pure@7.29.7", "", { "dependencies": { "@babel/types": "^7.29.7" } }, "sha512-OoK6239jHPuSQOoS0kfTVKn0b/rVTk0seKq4Gd2UMLtmOVLjDC0ki3e+c90Trqv2gMfvJFqkiljrr568+qddiw=="], + + "@babel/helper-compilation-targets": ["@babel/helper-compilation-targets@7.29.7", "", { "dependencies": { "@babel/compat-data": "^7.29.7", "@babel/helper-validator-option": "^7.29.7", "browserslist": "^4.24.0", "lru-cache": "^5.1.1", "semver": "^6.3.1" } }, "sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g=="], + + "@babel/helper-create-class-features-plugin": ["@babel/helper-create-class-features-plugin@7.29.7", "", { "dependencies": { "@babel/helper-annotate-as-pure": "^7.29.7", "@babel/helper-member-expression-to-functions": "^7.29.7", "@babel/helper-optimise-call-expression": "^7.29.7", "@babel/helper-replace-supers": "^7.29.7", "@babel/helper-skip-transparent-expression-wrappers": "^7.29.7", "@babel/traverse": "^7.29.7", "semver": "^6.3.1" }, "peerDependencies": { "@babel/core": "^7.0.0" } }, "sha512-IY3ZD9Tmooqr3TUhc3DUWxiuo8xx1DWLhd5M7hQ+ZWJamqM2BbalrBJb2MisSLoYorOj75U03qULCxQTY9r3hg=="], + + "@babel/helper-globals": ["@babel/helper-globals@7.29.7", "", {}, "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA=="], + + "@babel/helper-member-expression-to-functions": ["@babel/helper-member-expression-to-functions@7.29.7", "", { "dependencies": { "@babel/traverse": "^7.29.7", "@babel/types": "^7.29.7" } }, "sha512-j+7JYmk1JYDtACIGj0QJqqWZjoUpMoEikQGADMaHgCMCSDqd2+P32rfcibUNrGOMWrlzK1WJBdxrB3JJQZwWtg=="], + + "@babel/helper-module-imports": ["@babel/helper-module-imports@7.29.7", "", { "dependencies": { "@babel/traverse": "^7.29.7", "@babel/types": "^7.29.7" } }, "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g=="], + + "@babel/helper-module-transforms": ["@babel/helper-module-transforms@7.29.7", "", { "dependencies": { "@babel/helper-module-imports": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7", "@babel/traverse": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0" } }, "sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg=="], + + "@babel/helper-optimise-call-expression": ["@babel/helper-optimise-call-expression@7.29.7", "", { "dependencies": { "@babel/types": "^7.29.7" } }, "sha512-+kmGVjcT9RGYzoDwdwEqEvGgKe3BYq+O1iGzjFubaNgZHwYHP6lsF2Yghf4kEuv9BV7tYDZ913aBW9am6YKong=="], + + "@babel/helper-plugin-utils": ["@babel/helper-plugin-utils@7.29.7", "", {}, "sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw=="], + + "@babel/helper-replace-supers": ["@babel/helper-replace-supers@7.29.7", "", { "dependencies": { "@babel/helper-member-expression-to-functions": "^7.29.7", "@babel/helper-optimise-call-expression": "^7.29.7", "@babel/traverse": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0" } }, "sha512-atfGXWSeCiF4DnKZIfmJfQRkSw9b9gNNXR1kqKjbhG4pGYCOnkp8OcTB8E3NXjBu8NpheSnOeNKz8KT7UNFTmQ=="], + + "@babel/helper-skip-transparent-expression-wrappers": ["@babel/helper-skip-transparent-expression-wrappers@7.29.7", "", { "dependencies": { "@babel/traverse": "^7.29.7", "@babel/types": "^7.29.7" } }, "sha512-brcMGQaVzIeUb+6/bs1Av0f8YuNNjKY2JyvfRCsFuFsdKccEQ5Ges2y74D74NZ1Rz8lKJ9ksJkfqwQFJ/iNEyQ=="], + + "@babel/helper-string-parser": ["@babel/helper-string-parser@7.29.7", "", {}, "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw=="], + + "@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@7.29.7", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="], + + "@babel/helper-validator-option": ["@babel/helper-validator-option@7.29.7", "", {}, "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw=="], + + "@babel/helpers": ["@babel/helpers@7.29.7", "", { "dependencies": { "@babel/template": "^7.29.7", "@babel/types": "^7.29.7" } }, "sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg=="], + + "@babel/parser": ["@babel/parser@7.29.8", "", { "dependencies": { "@babel/types": "^7.29.8" }, "bin": "./bin/babel-parser.js" }, "sha512-E8lTAYNB1KW+FH+VGJuZM1ioAx2E6oVlvQFRrf5P8ZZmsiJXYAD9vTFV7yyEURNzgh1dFqMZuO6tUwcARbqFCA=="], + + "@babel/plugin-syntax-jsx": ["@babel/plugin-syntax-jsx@7.29.7", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-TSu8+mHCoEaaCDEZ0I3+6mvTBYR4PCxQwf2z9/r5Tbztv6NaLR3B9thGTTxX2WGuGHJqRiAbKPeGTJ5XWXVg6A=="], + + "@babel/plugin-syntax-typescript": ["@babel/plugin-syntax-typescript@7.29.7", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-ngr+82Sh0xMz25TPCZi+nC2iTzjfCdWS2ONXTp/PtSCHCgaCNBpdMqgvJ2ccdLlClVZ7sisIgB914j/JFe+RZA=="], + + "@babel/plugin-transform-modules-commonjs": ["@babel/plugin-transform-modules-commonjs@7.29.7", "", { "dependencies": { "@babel/helper-module-transforms": "^7.29.7", "@babel/helper-plugin-utils": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-j0vCldybPC5b5dwCQOJ21uKtHzt7hxLygJTg9eF1ScfaikEDNfzn94XoW5Fi+seBR0nCyL23xaBFFkq7dTM8XQ=="], + + "@babel/plugin-transform-react-jsx-self": ["@babel/plugin-transform-react-jsx-self@7.29.7", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-TL0hMc9xzy86VD31nUiwzd5otRAcyEPcsegCxolO0PvcXuH1v0kECe/UIznYFihpkvU5wg/jk4v0TTEFfm53fw=="], + + "@babel/plugin-transform-react-jsx-source": ["@babel/plugin-transform-react-jsx-source@7.29.7", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-06IyK09H3wi4cGbhDBwp5gUGo0IKtnYa8tyTiephirPCK6fbobVGiXMMI5zLQ4aKEYP3wZ3ArU44o+8KMrSG/Q=="], + + "@babel/plugin-transform-typescript": ["@babel/plugin-transform-typescript@7.29.7", "", { "dependencies": { "@babel/helper-annotate-as-pure": "^7.29.7", "@babel/helper-create-class-features-plugin": "^7.29.7", "@babel/helper-plugin-utils": "^7.29.7", "@babel/helper-skip-transparent-expression-wrappers": "^7.29.7", "@babel/plugin-syntax-typescript": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-jK52h8LaLc7JarhQV2ofeFMts4H7vnOXnqZNA6fYglBTZewRBE51KWt3BUltW1P+KoPsYkHoJeXePuz4zo2LMw=="], + + "@babel/preset-typescript": ["@babel/preset-typescript@7.29.7", "", { "dependencies": { "@babel/helper-plugin-utils": "^7.29.7", "@babel/helper-validator-option": "^7.29.7", "@babel/plugin-syntax-jsx": "^7.29.7", "@babel/plugin-transform-modules-commonjs": "^7.29.7", "@babel/plugin-transform-typescript": "^7.29.7" }, "peerDependencies": { "@babel/core": "^7.0.0-0" } }, "sha512-/Foi8vKY2EVbed/1eZx0gJEEwHAIxogrySI7rULcRIvhZzbvoE/b5qG5Ghc0WKAFKOHA9SD1x7RsFlOYdutIiQ=="], + + "@babel/template": ["@babel/template@7.29.7", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/parser": "^7.29.7", "@babel/types": "^7.29.7" } }, "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg=="], + + "@babel/traverse": ["@babel/traverse@7.29.8", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/generator": "^7.29.8", "@babel/helper-globals": "^7.29.7", "@babel/parser": "^7.29.8", "@babel/template": "^7.29.7", "@babel/types": "^7.29.8", "debug": "^4.3.1" } }, "sha512-I5z7H3bf/41ktsNVLtpN0wAa336HkqIHQ5BuPLEhTkt1jVSyZpeNKIzTgEWmlxjdg81R0IgUCcaE+Ok3NvrfZg=="], + + "@babel/types": ["@babel/types@7.29.8", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg=="], + + "@dotenvx/dotenvx": ["@dotenvx/dotenvx@1.75.1", "", { "dependencies": { "@dotenvx/primitives": "^0.8.0", "commander": "^11.1.0", "conf": "^10.2.0", "dotenv": "^17.2.1", "enquirer": "^2.4.1", "env-paths": "^2.2.1", "execa": "^5.1.1", "fdir": "^6.2.0", "ignore": "^5.3.0", "object-treeify": "1.1.33", "open": "^8.4.2", "picomatch": "^4.0.4", "systeminformation": "^5.22.11", "undici": "^7.11.0", "which": "^4.0.0", "yocto-spinner": "^1.1.0" }, "bin": { "dotenvx": "src/cli/dotenvx.js" } }, "sha512-/BITOC9dmS/edY2zQwZNicQ059O6RKabtQfyEafV0nGtfYRNHYy1DIPiYVcov40+tob9hfmBnbR963dS+EQ1DQ=="], + + "@dotenvx/primitives": ["@dotenvx/primitives@0.8.0", "", {}, "sha512-VYJy0uhFm9zTJ1TxBaW/pA8bjbOM/OttaNMwZ1RHG4JKyRG7DhSdiqD1ipQoAyoD22olUtxbP78W9xY3Wd11bg=="], + + "@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.25.12", "", { "os": "aix", "cpu": "ppc64" }, "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA=="], + + "@esbuild/android-arm": ["@esbuild/android-arm@0.25.12", "", { "os": "android", "cpu": "arm" }, "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg=="], + + "@esbuild/android-arm64": ["@esbuild/android-arm64@0.25.12", "", { "os": "android", "cpu": "arm64" }, "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg=="], + + "@esbuild/android-x64": ["@esbuild/android-x64@0.25.12", "", { "os": "android", "cpu": "x64" }, "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg=="], + + "@esbuild/darwin-arm64": ["@esbuild/darwin-arm64@0.25.12", "", { "os": "darwin", "cpu": "arm64" }, "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg=="], + + "@esbuild/darwin-x64": ["@esbuild/darwin-x64@0.25.12", "", { "os": "darwin", "cpu": "x64" }, "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA=="], + + "@esbuild/freebsd-arm64": ["@esbuild/freebsd-arm64@0.25.12", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg=="], + + "@esbuild/freebsd-x64": ["@esbuild/freebsd-x64@0.25.12", "", { "os": "freebsd", "cpu": "x64" }, "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ=="], + + "@esbuild/linux-arm": ["@esbuild/linux-arm@0.25.12", "", { "os": "linux", "cpu": "arm" }, "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw=="], + + "@esbuild/linux-arm64": ["@esbuild/linux-arm64@0.25.12", "", { "os": "linux", "cpu": "arm64" }, "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ=="], + + "@esbuild/linux-ia32": ["@esbuild/linux-ia32@0.25.12", "", { "os": "linux", "cpu": "ia32" }, "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA=="], + + "@esbuild/linux-loong64": ["@esbuild/linux-loong64@0.25.12", "", { "os": "linux", "cpu": "none" }, "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng=="], + + "@esbuild/linux-mips64el": ["@esbuild/linux-mips64el@0.25.12", "", { "os": "linux", "cpu": "none" }, "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw=="], + + "@esbuild/linux-ppc64": ["@esbuild/linux-ppc64@0.25.12", "", { "os": "linux", "cpu": "ppc64" }, "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA=="], + + "@esbuild/linux-riscv64": ["@esbuild/linux-riscv64@0.25.12", "", { "os": "linux", "cpu": "none" }, "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w=="], + + "@esbuild/linux-s390x": ["@esbuild/linux-s390x@0.25.12", "", { "os": "linux", "cpu": "s390x" }, "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg=="], + + "@esbuild/linux-x64": ["@esbuild/linux-x64@0.25.12", "", { "os": "linux", "cpu": "x64" }, "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw=="], + + "@esbuild/netbsd-arm64": ["@esbuild/netbsd-arm64@0.25.12", "", { "os": "none", "cpu": "arm64" }, "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg=="], + + "@esbuild/netbsd-x64": ["@esbuild/netbsd-x64@0.25.12", "", { "os": "none", "cpu": "x64" }, "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ=="], + + "@esbuild/openbsd-arm64": ["@esbuild/openbsd-arm64@0.25.12", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A=="], + + "@esbuild/openbsd-x64": ["@esbuild/openbsd-x64@0.25.12", "", { "os": "openbsd", "cpu": "x64" }, "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw=="], + + "@esbuild/openharmony-arm64": ["@esbuild/openharmony-arm64@0.25.12", "", { "os": "none", "cpu": "arm64" }, "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg=="], + + "@esbuild/sunos-x64": ["@esbuild/sunos-x64@0.25.12", "", { "os": "sunos", "cpu": "x64" }, "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w=="], + + "@esbuild/win32-arm64": ["@esbuild/win32-arm64@0.25.12", "", { "os": "win32", "cpu": "arm64" }, "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg=="], + + "@esbuild/win32-ia32": ["@esbuild/win32-ia32@0.25.12", "", { "os": "win32", "cpu": "ia32" }, "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ=="], + + "@esbuild/win32-x64": ["@esbuild/win32-x64@0.25.12", "", { "os": "win32", "cpu": "x64" }, "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA=="], + + "@floating-ui/core": ["@floating-ui/core@1.8.0", "", { "dependencies": { "@floating-ui/utils": "^0.2.12" } }, "sha512-0CIZ5itps/8x7BG8dEIhs53BvCUH2PCoogtakwRTut+Arm58sJooJ0AuZhLw2HJYIR5cMLNPBSS728sPho2khQ=="], + + "@floating-ui/dom": ["@floating-ui/dom@1.8.0", "", { "dependencies": { "@floating-ui/core": "^1.8.0", "@floating-ui/utils": "^0.2.12" } }, "sha512-yXSrzeHZBTZadLOlfyhCkJHNeLJnHRnRInwdZ40L7ZiaAtrBwoYlsDrX3v5zB1Utk7CLfzcOVnVVWoXEky7Ceg=="], + + "@floating-ui/react-dom": ["@floating-ui/react-dom@2.1.9", "", { "dependencies": { "@floating-ui/dom": "^1.8.0" }, "peerDependencies": { "react": ">=16.8.0", "react-dom": ">=16.8.0" } }, "sha512-JDjEFGCpImxDCA7JJKviA0M9+RtmJdj0m/NVU5IMgBK+AmZouAQQ7/+2GLH0GXXY0YMw9oXPB8hKdbPYg5QLYg=="], + + "@floating-ui/utils": ["@floating-ui/utils@0.2.12", "", {}, "sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww=="], + + "@fontsource-variable/figtree": ["@fontsource-variable/figtree@5.3.0", "", {}, "sha512-VRVodD7OiG7apQwE8/2fMjaqpY/a0qRJqL5HtYj8CKIVps+9amaFcdfKmDIf7iqYQx6iPLlArVXAfKeIZmVcNQ=="], + + "@hono/node-server": ["@hono/node-server@2.1.1", "", { "peerDependencies": { "hono": "^4" } }, "sha512-ELuehkj5VCBdgEw9zs+ivkKwyzzUCSQuE96YmiPvn1ECBoZCczbFXJLeEGMTYjphP6gydh4pHMqEYPVMYUVgQg=="], + + "@hugeicons/core-free-icons": ["@hugeicons/core-free-icons@4.2.3", "", {}, "sha512-fpiU0qFZkv4ABi23xJ2m4qNr0BBfuIaYjPboN8WDA6aj9D+OzXa7eykxKOpACZRuGbDz1U9S5DsNx1d5KNnsgA=="], + + "@hugeicons/react": ["@hugeicons/react@1.1.9", "", { "peerDependencies": { "react": ">=16.0.0" } }, "sha512-O+lWSWjbijoAvMCxn4K2bQWCGN5+mP1y5j+X99j23mXMj+s0X25fs71T6t9YJLaBodwmZdaewD27dzS/PiboQw=="], + + "@jridgewell/gen-mapping": ["@jridgewell/gen-mapping@0.3.13", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA=="], + + "@jridgewell/remapping": ["@jridgewell/remapping@2.3.5", "", { "dependencies": { "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ=="], + + "@jridgewell/resolve-uri": ["@jridgewell/resolve-uri@3.1.2", "", {}, "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw=="], + + "@jridgewell/sourcemap-codec": ["@jridgewell/sourcemap-codec@1.5.5", "", {}, "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og=="], + + "@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.31", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="], + + "@modelcontextprotocol/sdk": ["@modelcontextprotocol/sdk@1.30.0", "", { "dependencies": { "@hono/node-server": "^1.19.9 || ^2.0.5", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-xKd8OIzlqNzcqcNumGAa6g+PW2kjD5vrpcKOnfldAUPP3j7lnqMPwlTXQm8gF+UwH72z0lqaRbjr9hqGz0eITA=="], + + "@napi-rs/lzma-linux-x64-gnu": ["@napi-rs/lzma-linux-x64-gnu@1.5.1", "", { "os": "linux", "cpu": "x64" }, "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ=="], + + "@nodelib/fs.scandir": ["@nodelib/fs.scandir@2.1.5", "", { "dependencies": { "@nodelib/fs.stat": "2.0.5", "run-parallel": "^1.1.9" } }, "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g=="], + + "@nodelib/fs.stat": ["@nodelib/fs.stat@2.0.5", "", {}, "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A=="], + + "@nodelib/fs.walk": ["@nodelib/fs.walk@1.2.8", "", { "dependencies": { "@nodelib/fs.scandir": "2.1.5", "fastq": "^1.6.0" } }, "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg=="], + + "@radix-ui/number": ["@radix-ui/number@1.1.3", "", {}, "sha512-Road2bidD0uu/1BGDOWNdPI06g0lIRy6IF9GZcIrDK2KGItfor8IQwQa+yM2ERgHM1MmHxaxpTzk0/Jp42lNfA=="], + + "@radix-ui/primitive": ["@radix-ui/primitive@1.1.7", "", {}, "sha512-rqWnm76nYT8HoNNqEjpgJ7Pw/DrBj5iBTrmEPo6HTX5+VJyBNOqTdv4g89G63HuR5g0AaENoAcH7Is5fF2kZ8Q=="], + + "@radix-ui/react-accessible-icon": ["@radix-ui/react-accessible-icon@1.1.15", "", { "dependencies": { "@radix-ui/react-visually-hidden": "1.2.11" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-WTQwcAvQf5sOcuUyi90lKPbhwcvQ+j55cjrSmeaN+L2vKU3DooOvlKw2MDeiJ5IkV5N905KW0/fGojKOBhD11A=="], + + "@radix-ui/react-accordion": ["@radix-ui/react-accordion@1.2.20", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-collapsible": "1.1.20", "@radix-ui/react-collection": "1.1.15", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-direction": "1.1.4", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-controllable-state": "1.2.6" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-jDhG9FvAEnlhnjrsINbNXcUa4G+L1KqSkJSunkbKEzFRcAb52jvM0PjPxPRvhe1HNc5F5yc0yzzWeeqlH4yBIg=="], + + "@radix-ui/react-alert-dialog": ["@radix-ui/react-alert-dialog@1.1.23", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-dialog": "1.1.23", "@radix-ui/react-primitive": "2.1.10" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-VAYOiQRqj3GPpYJE0I9J+X8Ip05cyVlNdKOFeiGS2Ou1HHGfpl0BxOyZm6nmVDyU+W+NF3/XLzmjHmVGydhwgA=="], + + "@radix-ui/react-arrow": ["@radix-ui/react-arrow@1.1.15", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.10" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-v4zggRcjadnI+ClKDuijlQEW4tw3NoaeHc/PwpKnLoLLKNUG4InLegkstooLcRIUWCs+8L22dGURCVuFfOKfnA=="], + + "@radix-ui/react-aspect-ratio": ["@radix-ui/react-aspect-ratio@1.1.15", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.10" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-fy+dyVR+90nelK8rqIznFlxzx7uPcGbhxH8Nfr2bHb4UfSe+e3hklOC0luK0hDwVwnRX7xTRySpsrQVeW+/oNQ=="], + + "@radix-ui/react-avatar": ["@radix-ui/react-avatar@1.2.6", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-callback-ref": "1.1.4", "@radix-ui/react-use-is-hydrated": "0.1.3", "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-4ULOTJ/mqy2hT9GlWa/MFHxHSvH3nJzHnZM1waNsc5Bonv7i70aNenghXmD97S6OJ81ekXONGGt4nT1r0PfEdA=="], + + "@radix-ui/react-checkbox": ["@radix-ui/react-checkbox@1.3.11", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-presence": "1.1.10", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-controllable-state": "1.2.6", "@radix-ui/react-use-size": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Gnptr9pDDQxD3hgq2dtPbtrp/c2qH1mBwIzw3X/ivrMb2e1t0jMTi606fVEqFPaQR1ggXIVQWKj3P2WW9v7zGQ=="], + + "@radix-ui/react-collapsible": ["@radix-ui/react-collapsible@1.1.20", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-presence": "1.1.10", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-controllable-state": "1.2.6", "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-mcGesGplBnzN2sbvJETzpCNfSMyPnb29q1GRLU+Ib7bJrpIG2ywmRoh2V5VbA2uNvKikKUlVbAPks7JDjz4A8Q=="], + + "@radix-ui/react-collection": ["@radix-ui/react-collection@1.1.15", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-9W+B9NPF0NaaPh/1NJd3+KqsnlLqU9H7T2rvww+fp+T/evVXdNAyYcnfRQZFOjkR1ajQp3yORlqnI8soawLvNA=="], + + "@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.1.5", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-+48PbAAbq3didjJxa+OaWY2ZwgAKsNiRGyeHKszblZMQ+kcpd9pAaT11cMkGEie0vsOi3QdeTE6d5Fe3Gn61kA=="], + + "@radix-ui/react-context": ["@radix-ui/react-context@1.2.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RHCUGwKHDr0hDGg4X7ma4JG4/+12qxw8rkh5QKdDldlCvtja6nUx1Ef/8HVrJze81lEsgLQlqjzjGNHantgnQA=="], + + "@radix-ui/react-context-menu": ["@radix-ui/react-context-menu@2.3.7", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-menu": "2.1.24", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-controllable-state": "1.2.6" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-CtXP35dxaB5T3zXSd+E3uHe/QpXcpYnZmxp6OaIbfthtfW4wyb77M23BG+bwIJDtsMwEP/YssdsmNyZu7jhWew=="], + + "@radix-ui/react-dialog": ["@radix-ui/react-dialog@1.1.23", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-dismissable-layer": "1.1.19", "@radix-ui/react-focus-guards": "1.1.6", "@radix-ui/react-focus-scope": "1.1.16", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-portal": "1.1.17", "@radix-ui/react-presence": "1.1.10", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-slot": "1.3.3", "@radix-ui/react-use-controllable-state": "1.2.6", "@radix-ui/react-use-layout-effect": "1.1.4", "aria-hidden": "^1.2.4", "react-remove-scroll": "^2.7.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Ksw4WeROkO4rC9k/onilX/Ao2Cr1ku1unMNH+XSCcP4jSXYu7HDsg9n4ojMjVb22XpYjAQ9qfrFlVbru1vXDUA=="], + + "@radix-ui/react-direction": ["@radix-ui/react-direction@1.1.4", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-5pzg4FGQNpExhnhT2zlrP1wZFaYCd1K0nYWoFAdcYoYK868IEigqMX3B3f8yIoRlAhAeDWciLI6ZdCKHF9P4Vg=="], + + "@radix-ui/react-dismissable-layer": ["@radix-ui/react-dismissable-layer@1.1.19", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-callback-ref": "1.1.4", "@radix-ui/react-use-effect-event": "0.0.5" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-8g4pfOL9HoKKLWGiypT+dphVqjFfmcXO5GBnhsG6zI+lxAx/8feQpr+1LSN8Re3hiZ+XkLNS4O9ztK11/LzQ6w=="], + + "@radix-ui/react-dropdown-menu": ["@radix-ui/react-dropdown-menu@2.1.24", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-menu": "2.1.24", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-controllable-state": "1.2.6" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-geq8l2rJkxvkXsT9RMgtUE3P8pITFpTsvYpbySi1IH4fZEABD/Gp85myayFgxk0ktljGMJnCbeFkyTusvSvv7g=="], + + "@radix-ui/react-focus-guards": ["@radix-ui/react-focus-guards@1.1.6", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RNOJjfZMTyBM6xYmV3IVGXkPjIhcBAuv48POevAXwrGJhkWZ9p1rFoIS1JFooPuT193AZmRsCPhpoVJxx6OPoQ=="], + + "@radix-ui/react-focus-scope": ["@radix-ui/react-focus-scope@1.1.16", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-callback-ref": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-wmRZ2WWLvmt6KHy2rNPOdPUjwq5xOHY02+m+udwJTn0aNIox/rkskAvJTyTLGhPK6KgrUjlJUJpgmx/+wFiFIQ=="], + + "@radix-ui/react-form": ["@radix-ui/react-form@0.1.16", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-label": "2.1.15", "@radix-ui/react-primitive": "2.1.10" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Q4TLEn2A7TAypxwmd6R9EwrlXDvkfYSDMrq9/887AXAGh+G1rH+kYJKSTv+Si9Y0JPKTwKYv6PviAJosysNimA=="], + + "@radix-ui/react-hover-card": ["@radix-ui/react-hover-card@1.1.23", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-dismissable-layer": "1.1.19", "@radix-ui/react-popper": "1.3.7", "@radix-ui/react-portal": "1.1.17", "@radix-ui/react-presence": "1.1.10", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-controllable-state": "1.2.6" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-H8qONfZd3ltrU3+jHCIgITbWo6e1iTKvP9DHdrvYbX48ooRM5FjEDTn16AMwdfuOGkWdZEhpl3PLL/Wk/AnHDQ=="], + + "@radix-ui/react-id": ["@radix-ui/react-id@1.1.4", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-TMQp2llA+RYn7JcjnrMnz7wN4pcVttPZnRZo52PLQsoLVKzNlVwUeHmfePgTgRluXFvlD3GD5g5MOVVTJCO0qA=="], + + "@radix-ui/react-label": ["@radix-ui/react-label@2.1.15", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.10" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-o/rdYEwZTTo5tjknnPeyQFU45kUC4i/XyeDPP+HGyi6XqpOP6Zf5Ya5vh/Yfe9Id5JiuWnnAx2XqIeD3UYZt0g=="], + + "@radix-ui/react-menu": ["@radix-ui/react-menu@2.1.24", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-collection": "1.1.15", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-direction": "1.1.4", "@radix-ui/react-dismissable-layer": "1.1.19", "@radix-ui/react-focus-guards": "1.1.6", "@radix-ui/react-focus-scope": "1.1.16", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-popper": "1.3.7", "@radix-ui/react-portal": "1.1.17", "@radix-ui/react-presence": "1.1.10", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-roving-focus": "1.1.19", "@radix-ui/react-slot": "1.3.3", "@radix-ui/react-use-callback-ref": "1.1.4", "aria-hidden": "^1.2.4", "react-remove-scroll": "^2.7.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-uW7RVuU6Lp/ZtfeY4b3kL32zccgEWvPv1+cf17ubYzHa9cL8AHokmk36cG/XEiH/smbQvumnieXX9j/e9RqJWA=="], + + "@radix-ui/react-menubar": ["@radix-ui/react-menubar@1.1.24", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-collection": "1.1.15", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-direction": "1.1.4", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-menu": "2.1.24", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-roving-focus": "1.1.19", "@radix-ui/react-use-controllable-state": "1.2.6" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-eeVs0vf7cuqXaM0qLQCPcufImiJNVBXdJDLu7ZGYl2732UH23Qat/foNGrr6vYV3/DdTsBqASoggUFgH14OcZA=="], + + "@radix-ui/react-navigation-menu": ["@radix-ui/react-navigation-menu@1.2.22", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-collection": "1.1.15", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-direction": "1.1.4", "@radix-ui/react-dismissable-layer": "1.1.19", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-presence": "1.1.10", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-callback-ref": "1.1.4", "@radix-ui/react-use-controllable-state": "1.2.6", "@radix-ui/react-use-layout-effect": "1.1.4", "@radix-ui/react-use-previous": "1.1.4", "@radix-ui/react-visually-hidden": "1.2.11" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-ou7iLEJ+yrhQndkkA4U21XIdS/CS45F4iXIkTZcb6/Ne9EMsOuDudVmCwmDnfFZZ+y1FZqXRNSIgBy+YMvZVZg=="], + + "@radix-ui/react-one-time-password-field": ["@radix-ui/react-one-time-password-field@0.1.16", "", { "dependencies": { "@radix-ui/number": "1.1.3", "@radix-ui/primitive": "1.1.7", "@radix-ui/react-collection": "1.1.15", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-direction": "1.1.4", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-roving-focus": "1.1.19", "@radix-ui/react-use-controllable-state": "1.2.6", "@radix-ui/react-use-effect-event": "0.0.5", "@radix-ui/react-use-is-hydrated": "0.1.3", "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Tj9P6ntAJEw52oq/F0AGknXR4XncxEt7XU47O3xJQOiWfLzEy3d9gtgKfvjSzGxzHkfL+VzvxGu2KTFsloJqXw=="], + + "@radix-ui/react-password-toggle-field": ["@radix-ui/react-password-toggle-field@0.1.11", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-controllable-state": "1.2.6", "@radix-ui/react-use-effect-event": "0.0.5", "@radix-ui/react-use-is-hydrated": "0.1.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-4gvFnmDXu3dgj21CqsufzIameRvlRd4SBqaWhcrlrNhRo0Y5i/49AmRJYe1fdAM3G2VNBbmin4b0D6cdQocwgw=="], + + "@radix-ui/react-popover": ["@radix-ui/react-popover@1.1.23", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-dismissable-layer": "1.1.19", "@radix-ui/react-focus-guards": "1.1.6", "@radix-ui/react-focus-scope": "1.1.16", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-popper": "1.3.7", "@radix-ui/react-portal": "1.1.17", "@radix-ui/react-presence": "1.1.10", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-slot": "1.3.3", "@radix-ui/react-use-controllable-state": "1.2.6", "aria-hidden": "^1.2.4", "react-remove-scroll": "^2.7.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-mw58MrBlyHWFisTOYignD0vf/3gdcgAR+9of1s9G/38CbFiUwH1nCDkc0AUM9IrXFgN5Ue8n45j9WCgyM1sbiQ=="], + + "@radix-ui/react-popper": ["@radix-ui/react-popper@1.3.7", "", { "dependencies": { "@floating-ui/react-dom": "^2.0.0", "@radix-ui/react-arrow": "1.1.15", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-callback-ref": "1.1.4", "@radix-ui/react-use-layout-effect": "1.1.4", "@radix-ui/react-use-rect": "1.1.4", "@radix-ui/react-use-size": "1.1.4", "@radix-ui/rect": "1.1.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-UsJrrd7w4wuKKTdvd/DNERVlwSlUcyXzjhyDwBk+3aPOsCjOY6ZSbxuw8E6lZTjjfP8Cpd0J8VVkrYUWyGYXyg=="], + + "@radix-ui/react-portal": ["@radix-ui/react-portal@1.1.17", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-vKQLcWypUnwZVvfV7UkGahH2g6ySe8M8R+zYBwPrv5byZ9QAW6cQVvNKo7GgmD+p8aYb6D9JBuvy8/WhOno2wQ=="], + + "@radix-ui/react-presence": ["@radix-ui/react-presence@1.1.10", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-3wyzCQ6+ubRA+D4uv9m95JYLXxmOHp05qjrkjeA7uKHHtjpPggQzc6DAb0URl7j67oR0K2foO4ip27TiX037Bw=="], + + "@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.10", "", { "dependencies": { "@radix-ui/react-slot": "1.3.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-MucOnzh6hR5mid6VpkbglRAMYMjKLqRnGBbjXkzjK52fuQDd1qbkx78a5P40mkcnVXJdEVxm26E9OPAiUq7nBg=="], + + "@radix-ui/react-progress": ["@radix-ui/react-progress@1.1.16", "", { "dependencies": { "@radix-ui/react-context": "1.2.2", "@radix-ui/react-primitive": "2.1.10" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-5XnomAsoZZCY+KNTxbIghpGqPruZvKFNlvcAljVAOdDRDsH4/OZQxhtwo5wdtoDM5R6MhJBb2sPnDuRFep3lzg=="], + + "@radix-ui/react-radio-group": ["@radix-ui/react-radio-group@1.4.7", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-direction": "1.1.4", "@radix-ui/react-presence": "1.1.10", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-roving-focus": "1.1.19", "@radix-ui/react-use-controllable-state": "1.2.6", "@radix-ui/react-use-size": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-cgYFEkntCxppHZgtSZ+7vh0wbZQ+IC7PPMw8DSnRG27B6kDd32/Zw0OJt7dGDigCoprMuWHjg2PvUn3PYvPFoQ=="], + + "@radix-ui/react-roving-focus": ["@radix-ui/react-roving-focus@1.1.19", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-collection": "1.1.15", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-direction": "1.1.4", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-callback-ref": "1.1.4", "@radix-ui/react-use-controllable-state": "1.2.6", "@radix-ui/react-use-is-hydrated": "0.1.3", "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-V9jI6hDjT7l3jsCQD9bLNvDLM3tH/gdbOTp7Tefp3hbbgCGQoK7tUvrWiRlcoBHIZ809ElXwNQwVo0B98LuTXQ=="], + + "@radix-ui/react-scroll-area": ["@radix-ui/react-scroll-area@1.2.18", "", { "dependencies": { "@radix-ui/number": "1.1.3", "@radix-ui/primitive": "1.1.7", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-direction": "1.1.4", "@radix-ui/react-presence": "1.1.10", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-callback-ref": "1.1.4", "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Zn5Cd171wxsO3Dfg8HaW6RifTb9CYTKQJHs/G4+LN1GfmJpaQMZQyQxMprVPHpaz7QY4l9BxK2JwQuzHsXC8nA=="], + + "@radix-ui/react-select": ["@radix-ui/react-select@2.3.7", "", { "dependencies": { "@radix-ui/number": "1.1.3", "@radix-ui/primitive": "1.1.7", "@radix-ui/react-collection": "1.1.15", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-direction": "1.1.4", "@radix-ui/react-dismissable-layer": "1.1.19", "@radix-ui/react-focus-guards": "1.1.6", "@radix-ui/react-focus-scope": "1.1.16", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-popper": "1.3.7", "@radix-ui/react-portal": "1.1.17", "@radix-ui/react-presence": "1.1.10", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-slot": "1.3.3", "@radix-ui/react-use-callback-ref": "1.1.4", "@radix-ui/react-use-controllable-state": "1.2.6", "@radix-ui/react-use-layout-effect": "1.1.4", "@radix-ui/react-use-previous": "1.1.4", "@radix-ui/react-visually-hidden": "1.2.11", "aria-hidden": "^1.2.4", "react-remove-scroll": "^2.7.2" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-WFGImkmbzcfxeIwq/+4HvRN0pizBwbwQUED4I13ezQsDdfl38ZntN6TmR8XaSzPBqoCToe8rF75j6NPNDSzhbg=="], + + "@radix-ui/react-separator": ["@radix-ui/react-separator@1.1.15", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.10" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-jOLO4lssEzWpoDu7G+Ze4VjwMRUBt291pnZD0gmalREZipnTX3wadQo7Fy48GCTfe14/YRN6rw/rOJqrE85Wxw=="], + + "@radix-ui/react-slider": ["@radix-ui/react-slider@1.4.7", "", { "dependencies": { "@radix-ui/number": "1.1.3", "@radix-ui/primitive": "1.1.7", "@radix-ui/react-collection": "1.1.15", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-direction": "1.1.4", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-controllable-state": "1.2.6", "@radix-ui/react-use-layout-effect": "1.1.4", "@radix-ui/react-use-previous": "1.1.4", "@radix-ui/react-use-size": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-mTSLf1GC/C0moWjTbvCM6Qn/gBjvlFt1azuWF2v7MN5C3Zq2U2J2lN3ZEYkpujuOU5Ro7A28wkviSxaKnG0BYg=="], + + "@radix-ui/react-slot": ["@radix-ui/react-slot@1.3.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.5" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-qx7oqnYbxnK9kYI9m317qmFmEgo6ywqWvbTogdj7cL9p3/yx4M48p7Rnw5z3H890cL/ow/EeWJsuTykeZVXP5Q=="], + + "@radix-ui/react-switch": ["@radix-ui/react-switch@1.3.7", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-controllable-state": "1.2.6", "@radix-ui/react-use-size": "1.1.4" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-48tB/4dn2UVLBCYhTu9AuR63IHl73l/qLbLgxd86noTUor4/K4LFDAcYjK+isP5313qxaFpjPVogE7+Y0/V3Kw=="], + + "@radix-ui/react-tabs": ["@radix-ui/react-tabs@1.1.21", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-direction": "1.1.4", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-presence": "1.1.10", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-roving-focus": "1.1.19", "@radix-ui/react-use-controllable-state": "1.2.6" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-UKxJlZid7FVtsk/WTxj4i4uSEgj2Au+KBbS7SQyTlzMhhn+86Cz3tISZdTa87bfEfcuvZezf2ZsxD4xuEKtkog=="], + + "@radix-ui/react-toast": ["@radix-ui/react-toast@1.2.23", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-collection": "1.1.15", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-dismissable-layer": "1.1.19", "@radix-ui/react-portal": "1.1.17", "@radix-ui/react-presence": "1.1.10", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-callback-ref": "1.1.4", "@radix-ui/react-use-controllable-state": "1.2.6", "@radix-ui/react-use-layout-effect": "1.1.4", "@radix-ui/react-visually-hidden": "1.2.11" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-ofhyAsYaocRGOs/n0XWdUOSVzEAG6BfrMVM8z0c0kLEWY38w/0WuMFPTJP/HVaZPYkMvHZoKIIhNcjbTCBILPg=="], + + "@radix-ui/react-toggle": ["@radix-ui/react-toggle@1.1.18", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-use-controllable-state": "1.2.6" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-7lonPlKfSacd20GlOBx2ltuVKz9oqWYZz+oMQyOltw6t1y2nyftj2ZmwwUHYn49kqfDWcp8dNZm5NgV+5Z+mug=="], + + "@radix-ui/react-toggle-group": ["@radix-ui/react-toggle-group@1.1.19", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-direction": "1.1.4", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-roving-focus": "1.1.19", "@radix-ui/react-toggle": "1.1.18", "@radix-ui/react-use-controllable-state": "1.2.6" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-OtnwuSVjd1Ofi+AdnvhsjQdyuhCDwYs1w9RyB5BN/OavXOVQo42SYqQjwUnbPnaiPFBpQ9aX70dWeee+v2oBLA=="], + + "@radix-ui/react-toolbar": ["@radix-ui/react-toolbar@1.1.19", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-direction": "1.1.4", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-roving-focus": "1.1.19", "@radix-ui/react-separator": "1.1.15", "@radix-ui/react-toggle-group": "1.1.19" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Ph0IvtYw4VB12ZnZg+YtrGs8yJQsnizwo/zu0R4Y/nWugtJzA7Pg1eWeuDR9+LSqn+xjamss+UOSOJJJ4gx8jw=="], + + "@radix-ui/react-tooltip": ["@radix-ui/react-tooltip@1.2.16", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-dismissable-layer": "1.1.19", "@radix-ui/react-id": "1.1.4", "@radix-ui/react-popper": "1.3.7", "@radix-ui/react-portal": "1.1.17", "@radix-ui/react-presence": "1.1.10", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-slot": "1.3.3", "@radix-ui/react-use-controllable-state": "1.2.6", "@radix-ui/react-use-layout-effect": "1.1.4", "@radix-ui/react-visually-hidden": "1.2.11" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-6EamKFRRnlpdadndbZ6LMwycfwkwPte1B42hs6QA0gYhjaOKqW4PZ4pjaW9UrlDX5eVt/OjncE7BFTPL5nmZhg=="], + + "@radix-ui/react-use-callback-ref": ["@radix-ui/react-use-callback-ref@1.1.4", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-R6OUY2e2fA6Yn6s+VSx5KBV6Nx8LQEhu+cz7LCej18rQ1HLyg9PSC9jP/ZNx0o6FAIK9c0F1kHylzSxKsdlkrQ=="], + + "@radix-ui/react-use-controllable-state": ["@radix-ui/react-use-controllable-state@1.2.6", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-use-effect-event": "0.0.5", "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-uEQJGT97ZA/TgP/Hydw47lHu+/vQj6z/0jA+WeTbK1o9Rx45GImjpD0tc3W5ad3D6XTSR6e1yEO0FvGq6WQfVQ=="], + + "@radix-ui/react-use-effect-event": ["@radix-ui/react-use-effect-event@0.0.5", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-7cshFL8HGS/7HEiHH+9kL9HBwp2sa9yX18Knwek6KYWmXwM7pegMgta2AXMQKI+rq3JnfSj9x8wYqFMTdG1Jgg=="], + + "@radix-ui/react-use-escape-keydown": ["@radix-ui/react-use-escape-keydown@1.1.5", "", { "dependencies": { "@radix-ui/react-use-callback-ref": "1.1.4" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-ge3ipobwSXTj4JyVtswQ7qZj0ZHdtbGuOno/LrgAAeSxtsJ6Vs4Gz5IkPH2bmqpjcLUFoqGhA/mueuIf63UXlA=="], + + "@radix-ui/react-use-is-hydrated": ["@radix-ui/react-use-is-hydrated@0.1.3", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-umO/aJ+82CpOnhDZUTbILCQf7kU/g0iv+oGs/Q8jw7IkhWBzaEP4sA268PhFAJTFetbwp3ICc6ktpI4TqtxcIw=="], + + "@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.4", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-K20DkRkUwDnxEYMBPcg3Y6voLkEy5p5QQmszZgLngKKiC7dzBR/aEuK3w1qlx2JWDUNH6FluahYdgR3BP+QbYw=="], + + "@radix-ui/react-use-previous": ["@radix-ui/react-use-previous@1.1.4", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-XoSLhbRbqxFtgJoi2fNHA3C6pDlY34x508vUpUGoFZfvePfHXHbE1lC4FYFMnJWgiCRroSTw6fOsXQoVS9RwZg=="], + + "@radix-ui/react-use-rect": ["@radix-ui/react-use-rect@1.1.4", "", { "dependencies": { "@radix-ui/rect": "1.1.3" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-cSOCh6JlkmfjLyNcLiu2nB4v+nm+dkZ+Q5KHWk/soo4U7ZLiEQFKHK9/YmtBHjfCEaU43IBKQOc4/uJmCaiCTQ=="], + + "@radix-ui/react-use-size": ["@radix-ui/react-use-size@1.1.4", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.4" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-D3anSY15EJoxrihpsXI6SMrmmonnQtR2ni7arO+Lfdg3O95b9hNXxONk8jA5C8ANdF/h5HMAxejgs8PWJ6rlhw=="], + + "@radix-ui/react-visually-hidden": ["@radix-ui/react-visually-hidden@1.2.11", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.10" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-NFS86RYYZb4/exihaESBGOpMJFz8MGLAfu3mOBSGByVnVPC9JPASfYubxd/8KbkQK0sYAv8lVQDEQukDX/qXvQ=="], + + "@radix-ui/rect": ["@radix-ui/rect@1.1.3", "", {}, "sha512-JtyZR+mqgBibTo8xea3B6ZRmzZiM/YeVBtUkas6zMuXjAlfIFIW2FgqeM9eLyvEaYX66vr6DJMK+4U6LV0KhNw=="], + + "@rolldown/pluginutils": ["@rolldown/pluginutils@1.0.0-beta.27", "", {}, "sha512-+d0F4MKMCbeVUJwG96uQ4SgAznZNSq93I3V+9NHA4OpvqG8mRCpGdKmK8l/dl02h2CCDHwW2FqilnTyDcAnqjA=="], + + "@rollup/rollup-android-arm-eabi": ["@rollup/rollup-android-arm-eabi@4.62.4", "", { "os": "android", "cpu": "arm" }, "sha512-RrPokAb7dmbxFoeO3TloqHyOjgye8RkBhSqmp4aJMIex4c9r46ZstPnleDQOq1t46VOVjwIuwNogIqbodV1Vvg=="], + + "@rollup/rollup-android-arm64": ["@rollup/rollup-android-arm64@4.62.4", "", { "os": "android", "cpu": "arm64" }, "sha512-JKuJc+pnpks2pjy7L/N3v/cAkZxYlnmuZoD840ldbMI5KDbC4iO9NKwPKYdjYFCMAIIlBzYSFHxIJVYzRo2/8A=="], + + "@rollup/rollup-darwin-arm64": ["@rollup/rollup-darwin-arm64@4.62.4", "", { "os": "darwin", "cpu": "arm64" }, "sha512-krw5uS2STmvJ02x0uTXHbqQNuz+9eZ1iw+qXk9dmW2gvV4jV7O2hEoOnuhFrpOPiel1mBFtqbxYZZtC46hXLOw=="], + + "@rollup/rollup-darwin-x64": ["@rollup/rollup-darwin-x64@4.62.4", "", { "os": "darwin", "cpu": "x64" }, "sha512-wsTxtgApb4PrOsNJIm0FZ1h3WvCC+k9uxLJ4ad75hgoS4NiRes2SoJFlDAyMwiUY8IssDqGcHbXuN0sx1tfF1A=="], + + "@rollup/rollup-freebsd-arm64": ["@rollup/rollup-freebsd-arm64@4.62.4", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-GUOnQlyZe3yAXhWOtOMsn5Qkrv5E5mZXa0thbARWi5Ei2szlVXJFQhddZ4HbAzh8q92w5twp+CQvs/eFanz9YQ=="], + + "@rollup/rollup-freebsd-x64": ["@rollup/rollup-freebsd-x64@4.62.4", "", { "os": "freebsd", "cpu": "x64" }, "sha512-/Y7f3QuxjzPKsjA/rfEDa3+0vXqyjmJ50Ln8dPpCmWkKTrUoWHG1cWhTqaAMLob2m2nESWuC7yGrREz019Ztqg=="], + + "@rollup/rollup-linux-arm-gnueabihf": ["@rollup/rollup-linux-arm-gnueabihf@4.62.4", "", { "os": "linux", "cpu": "arm" }, "sha512-81wiiX3v7aqy+T+bT61TJ78yJjRquqFFTTbAPt08imfQQzkPIW8t6aJbkTagtCCrXMNc9D66+geqlK7ydLPNqA=="], + + "@rollup/rollup-linux-arm-musleabihf": ["@rollup/rollup-linux-arm-musleabihf@4.62.4", "", { "os": "linux", "cpu": "arm" }, "sha512-9kmDIvNZqdoHOBZgNtpTBeLWYO/LVipM3H/j62P8848/l/VPEQL6N3uxU9pvP1oZAsXyC2MEnFP3ovRjo7WYNQ=="], + + "@rollup/rollup-linux-arm64-gnu": ["@rollup/rollup-linux-arm64-gnu@4.62.4", "", { "os": "linux", "cpu": "arm64" }, "sha512-CcnXHWnXg69g+DX5VWL3FHts3qMRN2uVEHX+BZvGLdd07/gXkn3ePjYtO1LDJvxkGKVHMclKBRa1QUTH+6toYQ=="], + + "@rollup/rollup-linux-arm64-musl": ["@rollup/rollup-linux-arm64-musl@4.62.4", "", { "os": "linux", "cpu": "arm64" }, "sha512-iFOibiHnTRuhrWLlRsOQFdZJJIa7S8OwkneJr4ocALP16u5yk6lWLINFwhHaEqBFMsKDUZofLkGos7+CPzGB3g=="], + + "@rollup/rollup-linux-loong64-gnu": ["@rollup/rollup-linux-loong64-gnu@4.62.4", "", { "os": "linux", "cpu": "none" }, "sha512-XnWYMI7euHlb5a871xPja+Gm7DRCFU+FGRrtS2sMq9N8FvqtpagUy6gD4YOemC5MRk9xbh8+jYMEJbigFQwsgA=="], + + "@rollup/rollup-linux-loong64-musl": ["@rollup/rollup-linux-loong64-musl@4.62.4", "", { "os": "linux", "cpu": "none" }, "sha512-qGDAlO0U8xedCcsdRm9oaoQY8DAx/QT7uIxJWhCdx0ceIWX783UC9QSYkdpzAe29wNiVfp24+bZdQmn49o45SQ=="], + + "@rollup/rollup-linux-ppc64-gnu": ["@rollup/rollup-linux-ppc64-gnu@4.62.4", "", { "os": "linux", "cpu": "ppc64" }, "sha512-ru4H6ezD7ysA5EiEK6qkkaEb4modH8CTej6kUy/gQi20u3kB3G7Zn8snXXkeJSCOFKG/rbPPtM/+9Wgas1961w=="], + + "@rollup/rollup-linux-ppc64-musl": ["@rollup/rollup-linux-ppc64-musl@4.62.4", "", { "os": "linux", "cpu": "ppc64" }, "sha512-2W4MO5WQVJnbJaZdvDb9rhBDuFU1nKIepPFpJUBsTh2k1YY2g+ODViaWuyOAjQ5cOP7NvrvLzt3wvHOoiAvc7w=="], + + "@rollup/rollup-linux-riscv64-gnu": ["@rollup/rollup-linux-riscv64-gnu@4.62.4", "", { "os": "linux", "cpu": "none" }, "sha512-+fxjfuoAmVMCYV5QyjoIpu0cp5DOiOTeqYFk1AVaxGr+/ravWLX89XfQmptsoWcaVy/TGf2hexzbUOrCQIL1CQ=="], + + "@rollup/rollup-linux-riscv64-musl": ["@rollup/rollup-linux-riscv64-musl@4.62.4", "", { "os": "linux", "cpu": "none" }, "sha512-jTn8JfHGL4djjFxPuM06LmNUJDsst2jeVlsd9OmIH6zc5sC9K6rIuO4YajXatLUpBmBKl6b35ro1QZocLi+tcA=="], + + "@rollup/rollup-linux-s390x-gnu": ["@rollup/rollup-linux-s390x-gnu@4.62.4", "", { "os": "linux", "cpu": "s390x" }, "sha512-oCJCJL4pXsoDcP2QZ+JVlPTIRc6266zsIaeJJsWImmF7HO0W8nb6HuSgZlMWxJwaPf8ehbSw8yo0EUw925hKsA=="], + + "@rollup/rollup-linux-x64-gnu": ["@rollup/rollup-linux-x64-gnu@4.62.4", "", { "os": "linux", "cpu": "x64" }, "sha512-W69hukhZ3KKNRCaMIEzKvcFye42hh0FE1+YoYaf5+Ikacuftoco6yO/xouz0hc5d5W/s3yBro5jRiuEE/Q5vUw=="], + + "@rollup/rollup-linux-x64-musl": ["@rollup/rollup-linux-x64-musl@4.62.4", "", { "os": "linux", "cpu": "x64" }, "sha512-qiXbGG2jkjXhzXpsFZSR2Xpb8DN/UaxYsbb/STbuR/6fpaDgRmmaq1B/LmtF2wQFOFOSsK2jdE0RZ3a0zHn4QA=="], + + "@rollup/rollup-openbsd-x64": ["@rollup/rollup-openbsd-x64@4.62.4", "", { "os": "openbsd", "cpu": "x64" }, "sha512-nWeM//hxv8mIo6jD7Hu4o48DVmV9pbV6gsKaWU+4NFyqHoPKwrkRiZGLKUhOBk8qNmDmpwFtPKg80Bo/Tn4xiQ=="], + + "@rollup/rollup-openharmony-arm64": ["@rollup/rollup-openharmony-arm64@4.62.4", "", { "os": "none", "cpu": "arm64" }, "sha512-s62SQ/vgsRSvMwDkOEfTqfgASF0f26ZNaQuTA6Aok5lrikf89yI2W0gFHvZb2Jpgc6N8JnOKZgCK2iciO3CsxQ=="], + + "@rollup/rollup-win32-arm64-msvc": ["@rollup/rollup-win32-arm64-msvc@4.62.4", "", { "os": "win32", "cpu": "arm64" }, "sha512-J6wGf8TVGbXJq+HH+ttTvrcfNKPbuZecV6KT1B8I18BC5IURUh5kl4Yl5OEP5eFIUoI5BWxCsyYMhFsDx8kekw=="], + + "@rollup/rollup-win32-ia32-msvc": ["@rollup/rollup-win32-ia32-msvc@4.62.4", "", { "os": "win32", "cpu": "ia32" }, "sha512-zmfrQd/0wu6oJs8Vq8KwY/YtsKSsLtKe/HwAP4Wqy8LhWjeT55fHRAkOhYQ12wI3ayS4Tt12d5CDRD7N96SAYQ=="], + + "@rollup/rollup-win32-x64-gnu": ["@rollup/rollup-win32-x64-gnu@4.62.4", "", { "os": "win32", "cpu": "x64" }, "sha512-qPzHqdj9rfUD+w79dtE07zi/kFwKyCJqplp5K5ygeLTp7jLpAoc16OAH39HSmRC9UpozaecsleI8uAdEj6v2yw=="], + + "@rollup/rollup-win32-x64-msvc": ["@rollup/rollup-win32-x64-msvc@4.62.4", "", { "os": "win32", "cpu": "x64" }, "sha512-zD6NdeWEByGE9QF9vCrlJ5YQB4oq9q91kPZS37Jwj5hOkvR1lTBSpsKhKDw4IJtbQ35LsTS1HD9DZYGKIshU1Q=="], + + "@sec-ant/readable-stream": ["@sec-ant/readable-stream@0.4.1", "", {}, "sha512-831qok9r2t8AlxLko40y2ebgSDhenenCatLVeW/uBtnHPyhHOvG0C7TvfgecV+wHzIm5KUICgzmVpWS+IMEAeg=="], + + "@sindresorhus/merge-streams": ["@sindresorhus/merge-streams@4.0.0", "", {}, "sha512-tlqY9xq5ukxTUZBmoOp+m61cqwQD5pHJtFY3Mn8CA8ps6yghLH/Hw8UPdqg4OLmFW3IFlcXnQNmo/dh8HzXYIQ=="], + + "@socket.io/component-emitter": ["@socket.io/component-emitter@3.1.2", "", {}, "sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA=="], + + "@tailwindcss/node": ["@tailwindcss/node@4.3.3", "", { "dependencies": { "@jridgewell/remapping": "^2.3.5", "enhanced-resolve": "^5.24.1", "jiti": "^2.7.0", "lightningcss": "1.32.0", "magic-string": "^0.30.21", "source-map-js": "^1.2.1", "tailwindcss": "4.3.3" } }, "sha512-/T8IKEsf9VTU6tLjgC7+sv2mOPtQxzE2jMw7u4Tt40Tx+QSZxpzh95/H6cMKoja9XuW7iMdLJYBB0o9G1CaAgg=="], + + "@tailwindcss/oxide": ["@tailwindcss/oxide@4.3.3", "", { "optionalDependencies": { "@tailwindcss/oxide-android-arm64": "4.3.3", "@tailwindcss/oxide-darwin-arm64": "4.3.3", "@tailwindcss/oxide-darwin-x64": "4.3.3", "@tailwindcss/oxide-freebsd-x64": "4.3.3", "@tailwindcss/oxide-linux-arm-gnueabihf": "4.3.3", "@tailwindcss/oxide-linux-arm64-gnu": "4.3.3", "@tailwindcss/oxide-linux-arm64-musl": "4.3.3", "@tailwindcss/oxide-linux-x64-gnu": "4.3.3", "@tailwindcss/oxide-linux-x64-musl": "4.3.3", "@tailwindcss/oxide-wasm32-wasi": "4.3.3", "@tailwindcss/oxide-win32-arm64-msvc": "4.3.3", "@tailwindcss/oxide-win32-x64-msvc": "4.3.3" } }, "sha512-krXjAikiaFSPaK/FkAQT5UTx3VormQaiZ5hBFlJZ9UFQGB/rwg1MZIhHAG9smMQRTdyJxP6Qt5MwMtdyU5FWrA=="], + + "@tailwindcss/oxide-android-arm64": ["@tailwindcss/oxide-android-arm64@4.3.3", "", { "os": "android", "cpu": "arm64" }, "sha512-Y85A2gmPSkl5Ve5qR86GL4HT509cFqQh1aes9p3sSkyTPwt0Pppf3GkwGe4JPACcRYjgJIEhQgM6dBClnr0NYw=="], + + "@tailwindcss/oxide-darwin-arm64": ["@tailwindcss/oxide-darwin-arm64@4.3.3", "", { "os": "darwin", "cpu": "arm64" }, "sha512-BiaWatpBcERQFDlOjRDpIVXuFK5PJez5SA4JMg6VYZdBYU+qKfV/vqjcIs+IYmtitf1xYQZTwXvU/8y4lfZUGw=="], + + "@tailwindcss/oxide-darwin-x64": ["@tailwindcss/oxide-darwin-x64@4.3.3", "", { "os": "darwin", "cpu": "x64" }, "sha512-fAeUqfV5ndhxRwai8cXGzdLvul9utWOmeTkv69unv4ZXixjn61Z+p9lCWdwOwA3TYboG3BwdVuN/RDjhBRl0mw=="], + + "@tailwindcss/oxide-freebsd-x64": ["@tailwindcss/oxide-freebsd-x64@4.3.3", "", { "os": "freebsd", "cpu": "x64" }, "sha512-iyf5bV6+wnAlflVeEy7R25dupxTNECZN5QMI0qNT6eT+EgaGdZcKhGkr5SdoaWiLJ3spLqIY9VCeSGrwmtg4kw=="], + + "@tailwindcss/oxide-linux-arm-gnueabihf": ["@tailwindcss/oxide-linux-arm-gnueabihf@4.3.3", "", { "os": "linux", "cpu": "arm" }, "sha512-aAYUprJAJQWWbRrPvtjdroZ56Md+JM8pMiopS6xGEwDfLhqj+2ver2p4nU4Mb3CRqcMmNBjo8KkUgcxhkzVQGQ=="], + + "@tailwindcss/oxide-linux-arm64-gnu": ["@tailwindcss/oxide-linux-arm64-gnu@4.3.3", "", { "os": "linux", "cpu": "arm64" }, "sha512-nDxldcEENOxZRzC2uu9jrutZdAAQtb+8WWDCSnWL1zvBk1+FN+x6MtDViPB5AJMfttVCUhehGWus3XBPgatM/w=="], + + "@tailwindcss/oxide-linux-arm64-musl": ["@tailwindcss/oxide-linux-arm64-musl@4.3.3", "", { "os": "linux", "cpu": "arm64" }, "sha512-Md44bD6veX/PC5iyF8cDVnw4HBIANZepRZZ7a8DQOvkfo5WUBwcp6iAuCUz23u+4SUkhJlD3eL7hNdW8ezd/kA=="], + + "@tailwindcss/oxide-linux-x64-gnu": ["@tailwindcss/oxide-linux-x64-gnu@4.3.3", "", { "os": "linux", "cpu": "x64" }, "sha512-tx7us1muwOKAKWao2v/GaafFeQboE6aj88vC6ziN2NCGcRm8gWUhwjzg+YdVB1e4boAtdtma4L43onunI6NS4w=="], + + "@tailwindcss/oxide-linux-x64-musl": ["@tailwindcss/oxide-linux-x64-musl@4.3.3", "", { "os": "linux", "cpu": "x64" }, "sha512-SJxX60smvHgasZoBy11dX6YRjXJFovwWBoedhbQPOBzgFWBHGB+TVPWB9BxzR7TTxU8FQZAI2AyiNCMzFm8Img=="], + + "@tailwindcss/oxide-wasm32-wasi": ["@tailwindcss/oxide-wasm32-wasi@4.3.3", "", { "dependencies": { "@emnapi/core": "^1.11.1", "@emnapi/runtime": "^1.11.1", "@emnapi/wasi-threads": "^1.2.2", "@napi-rs/wasm-runtime": "^1.1.4", "@tybys/wasm-util": "^0.10.2", "tslib": "^2.8.1" }, "cpu": "none" }, "sha512-jx1+rPhY/5Ympkktd656HBWEBLxP7dH06losBLjjf5vgCODXvi9KhtftWcMIwTFIDqBr7cRnQkdLnAG+IOlGvQ=="], + + "@tailwindcss/oxide-win32-arm64-msvc": ["@tailwindcss/oxide-win32-arm64-msvc@4.3.3", "", { "os": "win32", "cpu": "arm64" }, "sha512-3rc292Ca2ceK6Ulcc/bAVnTs/3nDtoPhyEKlgPv+yQJQi/JS/AMJlqzxvlDacL1nekbrcf6bTqp/jV4qgnPxNQ=="], + + "@tailwindcss/oxide-win32-x64-msvc": ["@tailwindcss/oxide-win32-x64-msvc@4.3.3", "", { "os": "win32", "cpu": "x64" }, "sha512-yJ0pwIVc/nYeGoV02WtsN8KYyLQv7kyI2wDnkezyJlGGjkd4QLwDGAwl47YpPJeuI0M0ObaXGSPjvWDPeTPggw=="], + + "@tailwindcss/postcss": ["@tailwindcss/postcss@4.3.3", "", { "dependencies": { "@alloc/quick-lru": "^5.2.0", "@tailwindcss/node": "4.3.3", "@tailwindcss/oxide": "4.3.3", "postcss": "^8.5.16", "tailwindcss": "4.3.3" } }, "sha512-JTSZZGQi1AyKirbLN3azmjVzef92tcX7h+iSqPdaeStyFpGpDlKvvpxeOE8njhbUanbRwr3z8DyzhICWnMtQeg=="], + + "@tailwindcss/vite": ["@tailwindcss/vite@4.3.3", "", { "dependencies": { "@tailwindcss/node": "4.3.3", "@tailwindcss/oxide": "4.3.3", "tailwindcss": "4.3.3" }, "peerDependencies": { "vite": "^5.2.0 || ^6 || ^7 || ^8" } }, "sha512-yYU8cogLeSh/ms2jh8Fj7jaba/EWa7Ja6GoUqYZaraEuCI5YS6ms6ObZgjjedm+jm6XZjdNRWBpPP6Z86oOxcw=="], + + "@tanstack/history": ["@tanstack/history@1.162.1", "", {}, "sha512-DR9t6lfLVdrjgCwpglrR9DR7Ok8/HlXjcOE+goWXF3zyuLUO/ug7vMbSFxTqrQTtbRghJfyhmIZ0S6LhPIy44w=="], + + "@tanstack/react-router": ["@tanstack/react-router@1.170.28", "", { "dependencies": { "@tanstack/history": "1.162.1", "@tanstack/react-store": "^0.9.3", "@tanstack/router-core": "1.171.23", "isbot": "^5.1.22" }, "peerDependencies": { "react": ">=18.0.0 || >=19.0.0", "react-dom": ">=18.0.0 || >=19.0.0" } }, "sha512-62GU/aV27w1O663K4L01+N5zw4hqwT5Gvq+nMG34ISxQlCgVCBxXff3IscZn2d/tUktnxc9USAdCcdWh00Oi/w=="], + + "@tanstack/react-store": ["@tanstack/react-store@0.9.3", "", { "dependencies": { "@tanstack/store": "0.9.3", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-y2iHd/N9OkoQbFJLUX1T9vbc2O9tjH0pQRgTcx1/Nz4IlwLvkgpuglXUx+mXt0g5ZDFrEeDnONPqkbfxXJKwRg=="], + + "@tanstack/router-core": ["@tanstack/router-core@1.171.23", "", { "dependencies": { "@tanstack/history": "1.162.1", "cookie-es": "^3.0.0", "seroval": "^1.6.2", "seroval-plugins": "^1.6.2" } }, "sha512-jdo0oyJ5cj7kz04z7I2hvmWswmqLD+zOGDnT2VZlLk20sQ25vF1QVq5uTVi1Lnp/dlHZtZpAuA7fLJuwy+67/A=="], + + "@tanstack/store": ["@tanstack/store@0.9.3", "", {}, "sha512-8reSzl/qGWGGVKhBoxXPMWzATSbZLZFWhwBAFO9NAyp0TxzfBP0mIrGb8CP8KrQTmvzXlR/vFPPUrHTLBGyFyw=="], + + "@ts-morph/common": ["@ts-morph/common@0.27.0", "", { "dependencies": { "fast-glob": "^3.3.3", "minimatch": "^10.0.1", "path-browserify": "^1.0.1" } }, "sha512-Wf29UqxWDpc+i61k3oIOzcUfQt79PIT9y/MWfAGlrkjg6lBC1hwDECLXPVJAhWjiGbfBCxZd65F/LIZF3+jeJQ=="], + + "@types/babel__core": ["@types/babel__core@7.20.5", "", { "dependencies": { "@babel/parser": "^7.20.7", "@babel/types": "^7.20.7", "@types/babel__generator": "*", "@types/babel__template": "*", "@types/babel__traverse": "*" } }, "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA=="], + + "@types/babel__generator": ["@types/babel__generator@7.27.0", "", { "dependencies": { "@babel/types": "^7.0.0" } }, "sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg=="], + + "@types/babel__template": ["@types/babel__template@7.4.4", "", { "dependencies": { "@babel/parser": "^7.1.0", "@babel/types": "^7.0.0" } }, "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A=="], + + "@types/babel__traverse": ["@types/babel__traverse@7.28.0", "", { "dependencies": { "@babel/types": "^7.28.2" } }, "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q=="], + + "@types/estree": ["@types/estree@1.0.9", "", {}, "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg=="], + + "@types/node": ["@types/node@25.9.5", "", { "dependencies": { "undici-types": ">=7.24.0 <7.24.7" } }, "sha512-OScDchr2fwuUmWdf4kZ9h7PcJiYDVInhJizG/biAq3cAvqwYktuy/TYGGdZNMtNTFUP7rnb0NU4TUdm82kt4Rg=="], + + "@types/prop-types": ["@types/prop-types@15.7.15", "", {}, "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw=="], + + "@types/react": ["@types/react@18.3.31", "", { "dependencies": { "@types/prop-types": "*", "csstype": "^3.2.2" } }, "sha512-vfEqpXTvwT91yhmwdfouStN2hSKwTvyRs8qpLfADyrq/kxDw0hZM7Wk9Ug1FELj8hIby+S/+kQCSRFF32nv2Qw=="], + + "@types/react-dom": ["@types/react-dom@18.3.7", "", { "peerDependencies": { "@types/react": "^18.0.0" } }, "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ=="], + + "@types/react-webcam": ["@types/react-webcam@3.0.0", "", { "dependencies": { "react-webcam": "*" } }, "sha512-iX4G+V0HEvZhfMuk5qUp4ZJUpV6M9ZW4mxjmDxmXrIN1fDSUajX4wtGYX+9yh6KShFlEXOjGyOc24j7wJagG6w=="], + + "@types/validate-npm-package-name": ["@types/validate-npm-package-name@4.0.2", "", {}, "sha512-lrpDziQipxCEeK5kWxvljWYhUvOiB2A9izZd9B2AFarYAkqZshb4lPbRs7zKEic6eGtH8V/2qJW+dPp9OtF6bw=="], + + "@vitejs/plugin-react": ["@vitejs/plugin-react@4.7.0", "", { "dependencies": { "@babel/core": "^7.28.0", "@babel/plugin-transform-react-jsx-self": "^7.27.1", "@babel/plugin-transform-react-jsx-source": "^7.27.1", "@rolldown/pluginutils": "1.0.0-beta.27", "@types/babel__core": "^7.20.5", "react-refresh": "^0.17.0" }, "peerDependencies": { "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0" } }, "sha512-gUu9hwfWvvEDBBmgtAowQCojwZmJ5mcLn3aufeCsitijs3+f2NsrPtlAWIR6OPiqljl96GVCUbLe0HyqIpVaoA=="], + + "accepts": ["accepts@2.0.0", "", { "dependencies": { "mime-types": "^3.0.0", "negotiator": "^1.0.0" } }, "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng=="], + + "ajv": ["ajv@8.20.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="], + + "ajv-formats": ["ajv-formats@3.0.1", "", { "dependencies": { "ajv": "^8.0.0" } }, "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ=="], + + "ansi-colors": ["ansi-colors@4.1.3", "", {}, "sha512-/6w/C21Pm1A7aZitlI5Ni/2J6FFQN8i1Cvz3kHABAAbw93v/NlvKdVOqz7CCWz/3iv/JplRSEEZ83XION15ovw=="], + + "ansi-regex": ["ansi-regex@6.3.0", "", {}, "sha512-WpDfL7NO6j7tH88IDBNVdUJxDh9nmCteAVW9dsep846XdwF4naCBK+/tGLX3KJgcpgMRXCFlTM2hKGoK9FsdrQ=="], + + "ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="], + + "argparse": ["argparse@2.0.1", "", {}, "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="], + + "aria-hidden": ["aria-hidden@1.2.6", "", { "dependencies": { "tslib": "^2.0.0" } }, "sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA=="], + + "ast-types": ["ast-types@0.16.1", "", { "dependencies": { "tslib": "^2.0.1" } }, "sha512-6t10qk83GOG8p0vKmaCr8eiilZwO171AvbROMtvvNiwrTly62t+7XkA8RdIIVbpMhCASAsxgAzdRSwh6nw/5Dg=="], + + "atomically": ["atomically@1.7.0", "", {}, "sha512-Xcz9l0z7y9yQ9rdDaxlmaI4uJHf/T8g9hOEzJcsEqX2SjCj4J20uK7+ldkDHMbpJDK76wF7xEIgxc/vSlsfw5w=="], + + "autoprefixer": ["autoprefixer@10.5.4", "", { "dependencies": { "browserslist": "^4.28.6", "caniuse-lite": "^1.0.30001806", "fraction.js": "^5.3.4", "picocolors": "^1.1.1", "postcss-value-parser": "^4.2.0" }, "peerDependencies": { "postcss": "^8.1.0" }, "bin": { "autoprefixer": "bin/autoprefixer" } }, "sha512-MaU0U/za7N3r6brxD4YB/l4NSrFzLPlANv6wEuQVaIPlD3L4W9rFcQPbL/EilY9BHhHvhfcz3gInDLrEtWT4EA=="], + + "balanced-match": ["balanced-match@4.0.4", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="], + + "baseline-browser-mapping": ["baseline-browser-mapping@2.11.14", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-JyJ954WzuIR8/FFzX0o5krdSTrBAkcCSRfWSleRsIHSWV+cZe2FI1PKggVkFke1hBldRs+LRxUczzE9iPmgZww=="], + + "body-parser": ["body-parser@2.3.0", "", { "dependencies": { "bytes": "^3.1.2", "content-type": "^2.0.0", "debug": "^4.4.3", "http-errors": "^2.0.1", "iconv-lite": "^0.7.2", "on-finished": "^2.4.1", "qs": "^6.15.2", "raw-body": "^3.0.2", "type-is": "^2.1.0" } }, "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw=="], + + "brace-expansion": ["brace-expansion@5.0.9", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg=="], + + "braces": ["braces@3.0.3", "", { "dependencies": { "fill-range": "^7.1.1" } }, "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA=="], + + "browserslist": ["browserslist@4.28.8", "", { "dependencies": { "baseline-browser-mapping": "^2.11.12", "caniuse-lite": "^1.0.30001809", "electron-to-chromium": "^1.5.402", "node-releases": "^2.0.53", "update-browserslist-db": "^1.3.0" }, "bin": { "browserslist": "cli.js" } }, "sha512-V2NpofLblG64mfOtSgDhOJESZEGogzDMBv/q+W6oc4LXWP/q75eOXoOaaOu1EOadB9U4Bwx/e0yzbvwKH8zalA=="], + + "bundle-name": ["bundle-name@4.1.0", "", { "dependencies": { "run-applescript": "^7.0.0" } }, "sha512-tjwM5exMg6BGRI+kNmTntNsvdZS1X8BFYS6tnJ2hdH0kVxM6/eVZ2xy+FqStSWvYmtfFMDLIxurorHwDKfDz5Q=="], + + "bytes": ["bytes@3.1.2", "", {}, "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg=="], + + "call-bind-apply-helpers": ["call-bind-apply-helpers@1.0.2", "", { "dependencies": { "es-errors": "^1.3.0", "function-bind": "^1.1.2" } }, "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ=="], + + "call-bound": ["call-bound@1.0.4", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "get-intrinsic": "^1.3.0" } }, "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg=="], + + "callsites": ["callsites@3.1.0", "", {}, "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ=="], + + "caniuse-lite": ["caniuse-lite@1.0.30001809", "", {}, "sha512-xxWVywk6a6Arlk+hymeycyn/VgqEfLDxupvhH/xiY5SJ/18kmi9o6MiO320DCUzypORHLtvh0I4i04tUhCNHNQ=="], + + "chalk": ["chalk@4.1.2", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="], + + "class-variance-authority": ["class-variance-authority@0.7.1", "", { "dependencies": { "clsx": "^2.1.1" } }, "sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg=="], + + "cli-cursor": ["cli-cursor@5.0.0", "", { "dependencies": { "restore-cursor": "^5.0.0" } }, "sha512-aCj4O5wKyszjMmDT4tZj93kxyydN/K5zPWSCe6/0AV/AA1pqe5ZBIw0a2ZfPQV7lL5/yb5HsUreJ6UFAF1tEQw=="], + + "cli-spinners": ["cli-spinners@2.9.2", "", {}, "sha512-ywqV+5MmyL4E7ybXgKys4DugZbX0FC6LnwrhjuykIjnK9k8OQacQ7axGKnjDXWNhns0xot3bZI5h55H8yo9cJg=="], + + "cliui": ["cliui@8.0.1", "", { "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.1", "wrap-ansi": "^7.0.0" } }, "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ=="], + + "clsx": ["clsx@2.1.1", "", {}, "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA=="], + + "code-block-writer": ["code-block-writer@13.0.3", "", {}, "sha512-Oofo0pq3IKnsFtuHqSF7TqBfr71aeyZDVJ0HpmqB7FBM2qEigL0iPONSCZSO9pE9dZTAxANe5XHG9Uy0YMv8cg=="], + + "color-convert": ["color-convert@2.0.1", "", { "dependencies": { "color-name": "~1.1.4" } }, "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ=="], + + "color-name": ["color-name@1.1.4", "", {}, "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="], + + "commander": ["commander@14.0.3", "", {}, "sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw=="], + + "concurrently": ["concurrently@9.2.4", "", { "dependencies": { "chalk": "4.1.2", "rxjs": "7.8.2", "shell-quote": "1.9.0", "supports-color": "8.1.1", "tree-kill": "1.2.2", "yargs": "17.7.2" }, "bin": { "conc": "dist/bin/concurrently.js", "concurrently": "dist/bin/concurrently.js" } }, "sha512-TZ0CEhyzvFjgtAvHTusDMgj7wNdihCh7LLLrzdUOXIhdlnL2JBBGA9eJxR24rtqgmdjh3OA3hrN1rCHj6HM8qA=="], + + "conf": ["conf@10.2.0", "", { "dependencies": { "ajv": "^8.6.3", "ajv-formats": "^2.1.1", "atomically": "^1.7.0", "debounce-fn": "^4.0.0", "dot-prop": "^6.0.1", "env-paths": "^2.2.1", "json-schema-typed": "^7.0.3", "onetime": "^5.1.2", "pkg-up": "^3.1.0", "semver": "^7.3.5" } }, "sha512-8fLl9F04EJqjSqH+QjITQfJF8BrOVaYr1jewVgSRAEWePfxT0sku4w2hrGQ60BC/TNLGQ2pgxNlTbWQmMPFvXg=="], + + "content-disposition": ["content-disposition@1.1.0", "", {}, "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g=="], + + "content-type": ["content-type@1.0.5", "", {}, "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA=="], + + "convert-source-map": ["convert-source-map@2.0.0", "", {}, "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg=="], + + "cookie": ["cookie@0.7.2", "", {}, "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w=="], + + "cookie-es": ["cookie-es@3.1.1", "", {}, "sha512-UaXxwISYJPTr9hwQxMFYZ7kNhSXboMXP+Z3TRX6f1/NyaGPfuNUZOWP1pUEb75B2HjfklIYLVRfWiFZJyC6Npg=="], + + "cookie-signature": ["cookie-signature@1.2.2", "", {}, "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg=="], + + "cors": ["cors@2.8.6", "", { "dependencies": { "object-assign": "^4", "vary": "^1" } }, "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw=="], + + "cosmiconfig": ["cosmiconfig@9.0.2", "", { "dependencies": { "env-paths": "^2.2.1", "import-fresh": "^3.3.0", "js-yaml": "^4.1.0", "parse-json": "^5.2.0" }, "peerDependencies": { "typescript": ">=4.9.5" }, "optionalPeers": ["typescript"] }, "sha512-gtTZxTDau1wL7Y7zifc2dd8jHSK/k6BTx/2Xp/BpdlAdnlYWFVt7qhJqgwi7637yRwRQ3qL4ZidbB4I8tA5VOg=="], + + "cross-spawn": ["cross-spawn@7.0.6", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="], + + "cssesc": ["cssesc@3.0.0", "", { "bin": { "cssesc": "bin/cssesc" } }, "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg=="], + + "csstype": ["csstype@3.2.3", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="], + + "debounce-fn": ["debounce-fn@4.0.0", "", { "dependencies": { "mimic-fn": "^3.0.0" } }, "sha512-8pYCQiL9Xdcg0UPSD3d+0KMlOjp+KGU5EPwYddgzQ7DATsg4fuUDjQtsYLmWjnk2obnNHgV3vE2Y4jejSOJVBQ=="], + + "debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" }, "peerDependencies": { "supports-color": "*" }, "optionalPeers": ["supports-color"] }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], + + "dedent": ["dedent@1.7.2", "", { "peerDependencies": { "babel-plugin-macros": "^3.1.0" }, "optionalPeers": ["babel-plugin-macros"] }, "sha512-WzMx3mW98SN+zn3hgemf4OzdmyNhhhKz5Ay0pUfQiMQ3e1g+xmTJWp/pKdwKVXhdSkAEGIIzqeuWrL3mV/AXbA=="], + + "deepmerge": ["deepmerge@4.3.1", "", {}, "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A=="], + + "default-browser": ["default-browser@5.5.0", "", { "dependencies": { "bundle-name": "^4.1.0", "default-browser-id": "^5.0.0" } }, "sha512-H9LMLr5zwIbSxrmvikGuI/5KGhZ8E2zH3stkMgM5LpOWDutGM2JZaj460Udnf1a+946zc7YBgrqEWwbk7zHvGw=="], + + "default-browser-id": ["default-browser-id@5.0.1", "", {}, "sha512-x1VCxdX4t+8wVfd1so/9w+vQ4vx7lKd2Qp5tDRutErwmR85OgmfX7RlLRMWafRMY7hbEiXIbudNrjOAPa/hL8Q=="], + + "define-lazy-prop": ["define-lazy-prop@3.0.0", "", {}, "sha512-N+MeXYoqr3pOgn8xfyRPREN7gHakLYjhsHhWGT3fWAiL4IkAt0iDw14QiiEm2bE30c5XX5q0FtAA3CK5f9/BUg=="], + + "depd": ["depd@2.0.0", "", {}, "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw=="], + + "detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="], + + "detect-node-es": ["detect-node-es@1.1.0", "", {}, "sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ=="], + + "diff": ["diff@8.0.4", "", {}, "sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw=="], + + "dot-prop": ["dot-prop@6.0.1", "", { "dependencies": { "is-obj": "^2.0.0" } }, "sha512-tE7ztYzXHIeyvc7N+hR3oi7FIbf/NIjVP9hmAt3yMXzrQ072/fpjGLx2GxNxGxUl5V73MEqYzioOMoVhGMJ5cA=="], + + "dotenv": ["dotenv@17.4.2", "", {}, "sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw=="], + + "dunder-proto": ["dunder-proto@1.0.1", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="], + + "ee-first": ["ee-first@1.1.1", "", {}, "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="], + + "electron-to-chromium": ["electron-to-chromium@1.5.406", "", {}, "sha512-hWH5ORBi3d0IipnMh7BN5GDTaAmrSSSWmznwt2zltdiRNEWoEQyTwF0FFSBxzHO7hLSRT6loQu3IQGV0wg/Tvg=="], + + "emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="], + + "encodeurl": ["encodeurl@2.0.0", "", {}, "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg=="], + + "engine.io-client": ["engine.io-client@6.6.6", "", { "dependencies": { "@socket.io/component-emitter": "~3.1.0", "debug": "~4.4.1", "engine.io-parser": "~5.2.1", "ws": "~8.21.0", "xmlhttprequest-ssl": "~2.1.1" } }, "sha512-iY6QdftLQ9pyiPoX082bpf/u1UewnOaJrtJIF9T0++QB34lZrj0uP+Q/bj8AlUsAxqhnkTV2BS8SBZSxOmoV5Q=="], + + "engine.io-parser": ["engine.io-parser@5.2.3", "", {}, "sha512-HqD3yTBfnBxIrbnM1DoD6Pcq8NECnh8d4As1Qgh0z5Gg3jRRIqijury0CL3ghu/edArpUYiYqQiDUQBIs4np3Q=="], + + "enhanced-resolve": ["enhanced-resolve@5.24.5", "", { "dependencies": { "graceful-fs": "^4.2.4", "tapable": "^2.3.3" } }, "sha512-L1l8TNvomm6UVW5B253AGxQagSQr+vGwhMlrrfRS2qmhx46AMpMVJKQYLvWYbysTMY8VoicOvzHzoHMbyzB+4A=="], + + "enquirer": ["enquirer@2.4.1", "", { "dependencies": { "ansi-colors": "^4.1.1", "strip-ansi": "^6.0.1" } }, "sha512-rRqJg/6gd538VHvR3PSrdRBb/1Vy2YfzHqzvbhGIQpDRKIa4FgV/54b5Q1xYSxOOwKvjXweS26E0Q+nAMwp2pQ=="], + + "env-paths": ["env-paths@2.2.1", "", {}, "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A=="], + + "error-ex": ["error-ex@1.3.4", "", { "dependencies": { "is-arrayish": "^0.2.1" } }, "sha512-sqQamAnR14VgCr1A618A3sGrygcpK+HEbenA/HiEAkkUwcZIIB/tgWqHFxWgOyDh4nB4JCRimh79dR5Ywc9MDQ=="], + + "es-define-property": ["es-define-property@1.0.1", "", {}, "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g=="], + + "es-errors": ["es-errors@1.3.0", "", {}, "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw=="], + + "es-object-atoms": ["es-object-atoms@1.1.2", "", { "dependencies": { "es-errors": "^1.3.0" } }, "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw=="], + + "esbuild": ["esbuild@0.25.12", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.25.12", "@esbuild/android-arm": "0.25.12", "@esbuild/android-arm64": "0.25.12", "@esbuild/android-x64": "0.25.12", "@esbuild/darwin-arm64": "0.25.12", "@esbuild/darwin-x64": "0.25.12", "@esbuild/freebsd-arm64": "0.25.12", "@esbuild/freebsd-x64": "0.25.12", "@esbuild/linux-arm": "0.25.12", "@esbuild/linux-arm64": "0.25.12", "@esbuild/linux-ia32": "0.25.12", "@esbuild/linux-loong64": "0.25.12", "@esbuild/linux-mips64el": "0.25.12", "@esbuild/linux-ppc64": "0.25.12", "@esbuild/linux-riscv64": "0.25.12", "@esbuild/linux-s390x": "0.25.12", "@esbuild/linux-x64": "0.25.12", "@esbuild/netbsd-arm64": "0.25.12", "@esbuild/netbsd-x64": "0.25.12", "@esbuild/openbsd-arm64": "0.25.12", "@esbuild/openbsd-x64": "0.25.12", "@esbuild/openharmony-arm64": "0.25.12", "@esbuild/sunos-x64": "0.25.12", "@esbuild/win32-arm64": "0.25.12", "@esbuild/win32-ia32": "0.25.12", "@esbuild/win32-x64": "0.25.12" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg=="], + + "escalade": ["escalade@3.2.0", "", {}, "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA=="], + + "escape-html": ["escape-html@1.0.3", "", {}, "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow=="], + + "esprima": ["esprima@4.0.1", "", { "bin": { "esparse": "./bin/esparse.js", "esvalidate": "./bin/esvalidate.js" } }, "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A=="], + + "etag": ["etag@1.8.1", "", {}, "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg=="], + + "eventsource": ["eventsource@3.0.7", "", { "dependencies": { "eventsource-parser": "^3.0.1" } }, "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA=="], + + "eventsource-parser": ["eventsource-parser@3.1.1", "", {}, "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ=="], + + "execa": ["execa@9.6.1", "", { "dependencies": { "@sindresorhus/merge-streams": "^4.0.0", "cross-spawn": "^7.0.6", "figures": "^6.1.0", "get-stream": "^9.0.0", "human-signals": "^8.0.1", "is-plain-obj": "^4.1.0", "is-stream": "^4.0.1", "npm-run-path": "^6.0.0", "pretty-ms": "^9.2.0", "signal-exit": "^4.1.0", "strip-final-newline": "^4.0.0", "yoctocolors": "^2.1.1" } }, "sha512-9Be3ZoN4LmYR90tUoVu2te2BsbzHfhJyfEiAVfz7N5/zv+jduIfLrV2xdQXOHbaD6KgpGdO9PRPM1Y4Q9QkPkA=="], + + "express": ["express@5.2.1", "", { "dependencies": { "accepts": "^2.0.0", "body-parser": "^2.2.1", "content-disposition": "^1.0.0", "content-type": "^1.0.5", "cookie": "^0.7.1", "cookie-signature": "^1.2.1", "debug": "^4.4.0", "depd": "^2.0.0", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "finalhandler": "^2.1.0", "fresh": "^2.0.0", "http-errors": "^2.0.0", "merge-descriptors": "^2.0.0", "mime-types": "^3.0.0", "on-finished": "^2.4.1", "once": "^1.4.0", "parseurl": "^1.3.3", "proxy-addr": "^2.0.7", "qs": "^6.14.0", "range-parser": "^1.2.1", "router": "^2.2.0", "send": "^1.1.0", "serve-static": "^2.2.0", "statuses": "^2.0.1", "type-is": "^2.0.1", "vary": "^1.1.2" } }, "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw=="], + + "express-rate-limit": ["express-rate-limit@8.6.2", "", { "dependencies": { "debug": "^4.4.3", "ip-address": "^10.2.0" }, "peerDependencies": { "express": ">= 4.11" } }, "sha512-YH4ru+eOJxQABscKFfRCy9R7x9QFGdezclVMwwgFFndzS2Xnm0uo6B0ABZsLhcpeptGv2qvuJVWlQr9gQZoC3A=="], + + "fast-deep-equal": ["fast-deep-equal@3.1.3", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="], + + "fast-glob": ["fast-glob@3.3.3", "", { "dependencies": { "@nodelib/fs.stat": "^2.0.2", "@nodelib/fs.walk": "^1.2.3", "glob-parent": "^5.1.2", "merge2": "^1.3.0", "micromatch": "^4.0.8" } }, "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg=="], + + "fast-uri": ["fast-uri@3.1.5", "", {}, "sha512-gHwA1O9LDIcKunMKhObS/HimwtehO1nPUECKAu5TpKgaO19fcWEl4bliWe1jWxVFvIXztJjjQ4L8XQ1EU9f7Jw=="], + + "fastq": ["fastq@1.20.1", "", { "dependencies": { "reusify": "^1.0.4" } }, "sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw=="], + + "fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="], + + "figures": ["figures@6.1.0", "", { "dependencies": { "is-unicode-supported": "^2.0.0" } }, "sha512-d+l3qxjSesT4V7v2fh+QnmFnUWv9lSpjarhShNTgBOfA0ttejbQUAlHLitbjkoRiDulW0OPoQPYIGhIC8ohejg=="], + + "fill-range": ["fill-range@7.1.1", "", { "dependencies": { "to-regex-range": "^5.0.1" } }, "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg=="], + + "finalhandler": ["finalhandler@2.1.1", "", { "dependencies": { "debug": "^4.4.0", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "on-finished": "^2.4.1", "parseurl": "^1.3.3", "statuses": "^2.0.1" } }, "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA=="], + + "find-up": ["find-up@3.0.0", "", { "dependencies": { "locate-path": "^3.0.0" } }, "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg=="], + + "forwarded": ["forwarded@0.2.0", "", {}, "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow=="], + + "fraction.js": ["fraction.js@5.3.4", "", {}, "sha512-1X1NTtiJphryn/uLQz3whtY6jK3fTqoE3ohKs0tT+Ujr1W59oopxmoEh7Lu5p6vBaPbgoM0bzveAW4Qi5RyWDQ=="], + + "fresh": ["fresh@2.0.0", "", {}, "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A=="], + + "fs-extra": ["fs-extra@11.4.0", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", "universalify": "^2.0.0" } }, "sha512-EQsFzMUJkCKGr1ePqlYADkIUmHW1s3ZXr5Yqy6wbGrfUCphpl2maM/kyOIRA2HpP3AaFQTZXD4ldjek+nccddA=="], + + "fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="], + + "function-bind": ["function-bind@1.1.2", "", {}, "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="], + + "fuzzysort": ["fuzzysort@3.1.0", "", {}, "sha512-sR9BNCjBg6LNgwvxlBd0sBABvQitkLzoVY9MYYROQVX/FvfJ4Mai9LsGhDgd8qYdds0bY77VzYd5iuB+v5rwQQ=="], + + "gensync": ["gensync@1.0.0-beta.2", "", {}, "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg=="], + + "get-caller-file": ["get-caller-file@2.0.5", "", {}, "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg=="], + + "get-east-asian-width": ["get-east-asian-width@1.6.0", "", {}, "sha512-QRbvDIbx6YklUe6RxeTeleMR0yv3cYH6PsPZHcnVn7xv7zO1BHN8r0XETu8n6Ye3Q+ahtSarc3WgtNWmehIBfA=="], + + "get-intrinsic": ["get-intrinsic@1.3.0", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "es-define-property": "^1.0.1", "es-errors": "^1.3.0", "es-object-atoms": "^1.1.1", "function-bind": "^1.1.2", "get-proto": "^1.0.1", "gopd": "^1.2.0", "has-symbols": "^1.1.0", "hasown": "^2.0.2", "math-intrinsics": "^1.1.0" } }, "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ=="], + + "get-nonce": ["get-nonce@1.0.1", "", {}, "sha512-FJhYRoDaiatfEkUK8HKlicmu/3SGFD51q3itKDGoSTysQJBnfOcxU5GxnhE1E6soB76MbT0MBtnKJuXyAx+96Q=="], + + "get-own-enumerable-keys": ["get-own-enumerable-keys@1.0.0", "", {}, "sha512-PKsK2FSrQCyxcGHsGrLDcK0lx+0Ke+6e8KFFozA9/fIQLhQzPaRvJFdcz7+Axg3jUH/Mq+NI4xa5u/UT2tQskA=="], + + "get-proto": ["get-proto@1.0.1", "", { "dependencies": { "dunder-proto": "^1.0.1", "es-object-atoms": "^1.0.0" } }, "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g=="], + + "get-stream": ["get-stream@9.0.1", "", { "dependencies": { "@sec-ant/readable-stream": "^0.4.1", "is-stream": "^4.0.1" } }, "sha512-kVCxPF3vQM/N0B1PmoqVUqgHP+EeVjmZSQn+1oCRPxd2P21P2F19lIgbR3HBosbB1PUhOAoctJnfEn2GbN2eZA=="], + + "glob-parent": ["glob-parent@5.1.2", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="], + + "gopd": ["gopd@1.2.0", "", {}, "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg=="], + + "graceful-fs": ["graceful-fs@4.2.11", "", {}, "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ=="], + + "has-flag": ["has-flag@4.0.0", "", {}, "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ=="], + + "has-symbols": ["has-symbols@1.1.0", "", {}, "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ=="], + + "hasown": ["hasown@2.0.4", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A=="], + + "hono": ["hono@4.13.2", "", {}, "sha512-JydRilDRkYBQMt9qR9U92mXxmbGqsqSn/IKOrh4e7/gEbn+0zSr8igTu0obwJoNGN4sez28DIql7FBHWydoJpA=="], + + "http-errors": ["http-errors@2.0.1", "", { "dependencies": { "depd": "~2.0.0", "inherits": "~2.0.4", "setprototypeof": "~1.2.0", "statuses": "~2.0.2", "toidentifier": "~1.0.1" } }, "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ=="], + + "human-signals": ["human-signals@8.0.1", "", {}, "sha512-eKCa6bwnJhvxj14kZk5NCPc6Hb6BdsU9DZcOnmQKSnO1VKrfV0zCvtttPZUsBvjmNDn8rpcJfpwSYnHBjc95MQ=="], + + "iconv-lite": ["iconv-lite@0.7.3", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ=="], + + "ignore": ["ignore@5.3.2", "", {}, "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g=="], + + "import-fresh": ["import-fresh@3.3.1", "", { "dependencies": { "parent-module": "^1.0.0", "resolve-from": "^4.0.0" } }, "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ=="], + + "inherits": ["inherits@2.0.4", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="], + + "ip-address": ["ip-address@10.5.0", "", {}, "sha512-R5SnVLJmgYYvf2F2ZgwSBnelz5G4q5AxIC277GDfUaNbrZKNANcBC7RHqYYePlszf4kBolVkJauG0ZjHHFh55g=="], + + "ipaddr.js": ["ipaddr.js@1.9.1", "", {}, "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g=="], + + "is-arrayish": ["is-arrayish@0.2.1", "", {}, "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg=="], + + "is-docker": ["is-docker@2.2.1", "", { "bin": { "is-docker": "cli.js" } }, "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ=="], + + "is-extglob": ["is-extglob@2.1.1", "", {}, "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ=="], + + "is-fullwidth-code-point": ["is-fullwidth-code-point@3.0.0", "", {}, "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg=="], + + "is-glob": ["is-glob@4.0.3", "", { "dependencies": { "is-extglob": "^2.1.1" } }, "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg=="], + + "is-in-ssh": ["is-in-ssh@1.0.0", "", {}, "sha512-jYa6Q9rH90kR1vKB6NM7qqd1mge3Fx4Dhw5TVlK1MUBqhEOuCagrEHMevNuCcbECmXZ0ThXkRm+Ymr51HwEPAw=="], + + "is-inside-container": ["is-inside-container@1.0.0", "", { "dependencies": { "is-docker": "^3.0.0" }, "bin": { "is-inside-container": "cli.js" } }, "sha512-KIYLCCJghfHZxqjYBE7rEy0OBuTd5xCHS7tHVgvCLkx7StIoaxwNW3hCALgEUjFfeRk+MG/Qxmp/vtETEF3tRA=="], + + "is-interactive": ["is-interactive@2.0.0", "", {}, "sha512-qP1vozQRI+BMOPcjFzrjXuQvdak2pHNUMZoeG2eRbiSqyvbEf/wQtEOTOX1guk6E3t36RkaqiSt8A/6YElNxLQ=="], + + "is-number": ["is-number@7.0.0", "", {}, "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng=="], + + "is-obj": ["is-obj@3.0.0", "", {}, "sha512-IlsXEHOjtKhpN8r/tRFj2nDyTmHvcfNeu/nrRIcXE17ROeatXchkojffa1SpdqW4cr/Fj6QkEf/Gn4zf6KKvEQ=="], + + "is-plain-obj": ["is-plain-obj@4.1.0", "", {}, "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg=="], + + "is-promise": ["is-promise@4.0.0", "", {}, "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ=="], + + "is-regexp": ["is-regexp@3.1.0", "", {}, "sha512-rbku49cWloU5bSMI+zaRaXdQHXnthP6DZ/vLnfdSKyL4zUzuWnomtOEiZZOd+ioQ+avFo/qau3KPTc7Fjy1uPA=="], + + "is-stream": ["is-stream@4.0.1", "", {}, "sha512-Dnz92NInDqYckGEUJv689RbRiTSEHCQ7wOVeALbkOz999YpqT46yMRIGtSNl2iCL1waAZSx40+h59NV/EwzV/A=="], + + "is-unicode-supported": ["is-unicode-supported@2.1.0", "", {}, "sha512-mE00Gnza5EEB3Ds0HfMyllZzbBrmLOX3vfWoj9A9PEnTfratQ/BcaJOuMhnkhjXvb2+FkY3VuHqtAGpTPmglFQ=="], + + "is-wsl": ["is-wsl@2.2.0", "", { "dependencies": { "is-docker": "^2.0.0" } }, "sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww=="], + + "isbot": ["isbot@5.2.1", "", {}, "sha512-dJ+LpKyClQZ7NG+j3OensC/mAZkGpukE9YUrgPYvAZj2doVL0edfDgywTUh5CXa0o+nW9a1V9e5+CJTX8+SxRw=="], + + "isexe": ["isexe@3.1.5", "", {}, "sha512-6B3tLtFqtQS4ekarvLVMZ+X+VlvQekbe4taUkf/rhVO3d/h0M2rfARm/pXLcPEsjjMsFgrFgSrhQIxcSVrBz8w=="], + + "jiti": ["jiti@2.7.0", "", { "bin": { "jiti": "lib/jiti-cli.mjs" } }, "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ=="], + + "jose": ["jose@6.2.8", "", {}, "sha512-Bsdjwm3Qsd/P0jR+BHDe3LytDfY7WBq2HmCCLIwuVRHMuEC9ae7/R474GIUdF1NgCyZjzVo/A9DOiOBtXq8ZoQ=="], + + "js-tokens": ["js-tokens@4.0.0", "", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="], + + "js-yaml": ["js-yaml@4.3.1", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-CY6crGq313MX8GkwvB7tzgp99vjQxY1++5y10/BKN/GUfHqWaOGQMNZkBvqSzsZKWk/ijwHlWzzkLulsGHhjWQ=="], + + "jsesc": ["jsesc@3.1.0", "", { "bin": { "jsesc": "bin/jsesc" } }, "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA=="], + + "json-parse-even-better-errors": ["json-parse-even-better-errors@2.3.1", "", {}, "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w=="], + + "json-schema-traverse": ["json-schema-traverse@1.0.0", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="], + + "json-schema-typed": ["json-schema-typed@8.0.2", "", {}, "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA=="], + + "json5": ["json5@2.2.3", "", { "bin": { "json5": "lib/cli.js" } }, "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg=="], + + "jsonfile": ["jsonfile@6.2.1", "", { "dependencies": { "universalify": "^2.0.0" }, "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q=="], + + "kleur": ["kleur@4.1.5", "", {}, "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ=="], + + "lightningcss": ["lightningcss@1.32.0", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.32.0", "lightningcss-darwin-arm64": "1.32.0", "lightningcss-darwin-x64": "1.32.0", "lightningcss-freebsd-x64": "1.32.0", "lightningcss-linux-arm-gnueabihf": "1.32.0", "lightningcss-linux-arm64-gnu": "1.32.0", "lightningcss-linux-arm64-musl": "1.32.0", "lightningcss-linux-x64-gnu": "1.32.0", "lightningcss-linux-x64-musl": "1.32.0", "lightningcss-win32-arm64-msvc": "1.32.0", "lightningcss-win32-x64-msvc": "1.32.0" } }, "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ=="], + + "lightningcss-android-arm64": ["lightningcss-android-arm64@1.32.0", "", { "os": "android", "cpu": "arm64" }, "sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg=="], + + "lightningcss-darwin-arm64": ["lightningcss-darwin-arm64@1.32.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ=="], + + "lightningcss-darwin-x64": ["lightningcss-darwin-x64@1.32.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w=="], + + "lightningcss-freebsd-x64": ["lightningcss-freebsd-x64@1.32.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig=="], + + "lightningcss-linux-arm-gnueabihf": ["lightningcss-linux-arm-gnueabihf@1.32.0", "", { "os": "linux", "cpu": "arm" }, "sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw=="], + + "lightningcss-linux-arm64-gnu": ["lightningcss-linux-arm64-gnu@1.32.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ=="], + + "lightningcss-linux-arm64-musl": ["lightningcss-linux-arm64-musl@1.32.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg=="], + + "lightningcss-linux-x64-gnu": ["lightningcss-linux-x64-gnu@1.32.0", "", { "os": "linux", "cpu": "x64" }, "sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA=="], + + "lightningcss-linux-x64-musl": ["lightningcss-linux-x64-musl@1.32.0", "", { "os": "linux", "cpu": "x64" }, "sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg=="], + + "lightningcss-win32-arm64-msvc": ["lightningcss-win32-arm64-msvc@1.32.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw=="], + + "lightningcss-win32-x64-msvc": ["lightningcss-win32-x64-msvc@1.32.0", "", { "os": "win32", "cpu": "x64" }, "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q=="], + + "lines-and-columns": ["lines-and-columns@1.2.4", "", {}, "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg=="], + + "locate-path": ["locate-path@3.0.0", "", { "dependencies": { "p-locate": "^3.0.0", "path-exists": "^3.0.0" } }, "sha512-7AO748wWnIhNqAuaty2ZWHkQHRSNfPVIsPIfwEOWO22AmaoVrWavlOcMR5nzTLNYvp36X220/maaRsrec1G65A=="], + + "log-symbols": ["log-symbols@6.0.0", "", { "dependencies": { "chalk": "^5.3.0", "is-unicode-supported": "^1.3.0" } }, "sha512-i24m8rpwhmPIS4zscNzK6MSEhk0DUWa/8iYQWxhffV8jkI4Phvs3F+quL5xvS0gdQR0FyTCMMH33Y78dDTzzIw=="], + + "loose-envify": ["loose-envify@1.4.0", "", { "dependencies": { "js-tokens": "^3.0.0 || ^4.0.0" }, "bin": { "loose-envify": "cli.js" } }, "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q=="], + + "lru-cache": ["lru-cache@5.1.1", "", { "dependencies": { "yallist": "^3.0.2" } }, "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w=="], + + "lucide-react": ["lucide-react@1.31.0", "", { "peerDependencies": { "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-G8u2eEtoHUnUa9f8lbvqDhCiORMnYLdUEo06EEG9MQvHQrInKcX3Pa2TH39MM5qyzRcWETxB0+aOwAPI1g1kEg=="], + + "magic-string": ["magic-string@0.30.21", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="], + + "math-intrinsics": ["math-intrinsics@1.1.0", "", {}, "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g=="], + + "media-typer": ["media-typer@1.1.1", "", {}, "sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ=="], + + "merge-descriptors": ["merge-descriptors@2.0.0", "", {}, "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g=="], + + "merge-stream": ["merge-stream@2.0.0", "", {}, "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w=="], + + "merge2": ["merge2@1.4.1", "", {}, "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg=="], + + "micromatch": ["micromatch@4.0.8", "", { "dependencies": { "braces": "^3.0.3", "picomatch": "^2.3.1" } }, "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA=="], + + "mime-db": ["mime-db@1.54.0", "", {}, "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ=="], + + "mime-types": ["mime-types@3.0.2", "", { "dependencies": { "mime-db": "^1.54.0" } }, "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A=="], + + "mimic-fn": ["mimic-fn@3.1.0", "", {}, "sha512-Ysbi9uYW9hFyfrThdDEQuykN4Ey6BuwPD2kpI5ES/nFTDn/98yxYNLZJcgUAKPT/mcrLLKaGzJR9YVxJrIdASQ=="], + + "mimic-function": ["mimic-function@5.0.1", "", {}, "sha512-VP79XUPxV2CigYP3jWwAUFSku2aKqBH7uTAapFWCBqutsbmDo96KY5o8uh6U+/YSIn5OxJnXp73beVkpqMIGhA=="], + + "minimatch": ["minimatch@10.2.6", "", { "dependencies": { "brace-expansion": "^5.0.8" } }, "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A=="], + + "minimist": ["minimist@1.2.8", "", {}, "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA=="], + + "ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], + + "nanoid": ["nanoid@3.3.18", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w=="], + + "negotiator": ["negotiator@1.0.0", "", {}, "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg=="], + + "next-themes": ["next-themes@0.4.6", "", { "peerDependencies": { "react": "^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc", "react-dom": "^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc" } }, "sha512-pZvgD5L0IEvX5/9GWyHMf3m8BKiVQwsCMHfoFosXtXBMnaS0ZnIJ9ST4b4NqLVKDEm8QBxoNNGNaBv2JNF6XNA=="], + + "node-releases": ["node-releases@2.0.53", "", {}, "sha512-D9UOmYG3UH1V+ENW56t5QXBwJw1YEY18ruVeus89Rw+SyIgjPkCO84bRzO3uNIYosJbNwiabWVn48o3uJLjxFQ=="], + + "npm-run-path": ["npm-run-path@6.0.0", "", { "dependencies": { "path-key": "^4.0.0", "unicorn-magic": "^0.3.0" } }, "sha512-9qny7Z9DsQU8Ou39ERsPU4OZQlSTP47ShQzuKZ6PRXpYLtIFgl/DEBYEXKlvcEa+9tHVcK8CF81Y2V72qaZhWA=="], + + "object-assign": ["object-assign@4.1.1", "", {}, "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="], + + "object-inspect": ["object-inspect@1.13.4", "", {}, "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew=="], + + "object-treeify": ["object-treeify@1.1.33", "", {}, "sha512-EFVjAYfzWqWsBMRHPMAXLCDIJnpMhdWAqR7xG6M6a2cs6PMFpl/+Z20w9zDW4vkxOFfddegBKq9Rehd0bxWE7A=="], + + "on-finished": ["on-finished@2.4.1", "", { "dependencies": { "ee-first": "1.1.1" } }, "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg=="], + + "once": ["once@1.4.0", "", { "dependencies": { "wrappy": "1" } }, "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w=="], + + "onetime": ["onetime@5.1.2", "", { "dependencies": { "mimic-fn": "^2.1.0" } }, "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg=="], + + "open": ["open@11.0.1", "", { "dependencies": { "default-browser": "^5.4.0", "define-lazy-prop": "^3.0.0", "is-in-ssh": "^1.0.0", "is-inside-container": "^1.0.0", "powershell-utils": "^0.2.0", "wsl-utils": "^1.0.0" } }, "sha512-NzwMUB6C1D0+Kd+9iMS/H4k+Ck3cTX6Ckyfr/gAGlmvSE1LUQZnEZvWBi4PYmMwH/S5SMeTXnE+9uAz8uF+pWw=="], + + "ora": ["ora@8.2.0", "", { "dependencies": { "chalk": "^5.3.0", "cli-cursor": "^5.0.0", "cli-spinners": "^2.9.2", "is-interactive": "^2.0.0", "is-unicode-supported": "^2.0.0", "log-symbols": "^6.0.0", "stdin-discarder": "^0.2.2", "string-width": "^7.2.0", "strip-ansi": "^7.1.0" } }, "sha512-weP+BZ8MVNnlCm8c0Qdc1WSWq4Qn7I+9CJGm7Qali6g44e/PUzbjNqJX5NJ9ljlNMosfJvg1fKEGILklK9cwnw=="], + + "p-limit": ["p-limit@2.3.0", "", { "dependencies": { "p-try": "^2.0.0" } }, "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w=="], + + "p-locate": ["p-locate@3.0.0", "", { "dependencies": { "p-limit": "^2.0.0" } }, "sha512-x+12w/To+4GFfgJhBEpiDcLozRJGegY+Ei7/z0tSLkMmxGZNybVMSfWj9aJn8Z5Fc7dBUNJOOVgPv2H7IwulSQ=="], + + "p-try": ["p-try@2.2.0", "", {}, "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ=="], + + "parent-module": ["parent-module@1.0.1", "", { "dependencies": { "callsites": "^3.0.0" } }, "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g=="], + + "parse-json": ["parse-json@5.2.0", "", { "dependencies": { "@babel/code-frame": "^7.0.0", "error-ex": "^1.3.1", "json-parse-even-better-errors": "^2.3.0", "lines-and-columns": "^1.1.6" } }, "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg=="], + + "parse-ms": ["parse-ms@4.0.0", "", {}, "sha512-TXfryirbmq34y8QBwgqCVLi+8oA3oWx2eAnSn62ITyEhEYaWRlVZ2DvMM9eZbMs/RfxPu/PK/aBLyGj4IrqMHw=="], + + "parseurl": ["parseurl@1.3.3", "", {}, "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ=="], + + "path-browserify": ["path-browserify@1.0.1", "", {}, "sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g=="], + + "path-exists": ["path-exists@3.0.0", "", {}, "sha512-bpC7GYwiDYQ4wYLe+FA8lhRjhQCMcQGuSgGGqDkg/QerRWw9CmGRT0iSOVRSZJ29NMLZgIzqaljJ63oaL4NIJQ=="], + + "path-key": ["path-key@3.1.1", "", {}, "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="], + + "path-to-regexp": ["path-to-regexp@8.4.2", "", {}, "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA=="], + + "picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="], + + "picomatch": ["picomatch@4.0.5", "", {}, "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A=="], + + "pkce-challenge": ["pkce-challenge@5.0.1", "", {}, "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ=="], + + "pkg-up": ["pkg-up@3.1.0", "", { "dependencies": { "find-up": "^3.0.0" } }, "sha512-nDywThFk1i4BQK4twPQ6TA4RT8bDY96yeuCVBWL3ePARCiEKDRSrNGbFIgUJpLp+XeIR65v8ra7WuJOFUBtkMA=="], + + "postcss": ["postcss@8.5.26", "", { "dependencies": { "nanoid": "^3.3.17", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ=="], + + "postcss-selector-parser": ["postcss-selector-parser@7.1.5", "", { "dependencies": { "cssesc": "^3.0.0", "util-deprecate": "^1.0.2" } }, "sha512-KvvtD7SrlBP7dlgkBghEE3r84CABm5SmV2aNcG4oCA+qDnJ/tvKonFVvwWAyyWUEwxuNawdfEAZKP9zM3oZ2Uw=="], + + "postcss-value-parser": ["postcss-value-parser@4.2.0", "", {}, "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ=="], + + "powershell-utils": ["powershell-utils@0.2.0", "", {}, "sha512-ZlsFlG7MtSFCoc5xreOvBAozCJ6Pf06opgJjh9ONEv418xpZSAzNjstD36C6+JwOnfSqOW/9uDkqKjezTdxZhw=="], + + "pretty-ms": ["pretty-ms@9.3.0", "", { "dependencies": { "parse-ms": "^4.0.0" } }, "sha512-gjVS5hOP+M3wMm5nmNOucbIrqudzs9v/57bWRHQWLYklXqoXKrVfYW2W9+glfGsqtPgpiz5WwyEEB+ksXIx3gQ=="], + + "prompts": ["prompts@2.4.2", "", { "dependencies": { "kleur": "^3.0.3", "sisteransi": "^1.0.5" } }, "sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q=="], + + "proxy-addr": ["proxy-addr@2.0.7", "", { "dependencies": { "forwarded": "0.2.0", "ipaddr.js": "1.9.1" } }, "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg=="], + + "qrcode.react": ["qrcode.react@4.2.0", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-QpgqWi8rD9DsS9EP3z7BT+5lY5SFhsqGjpgW5DY/i3mK4M9DTBNz3ErMi8BWYEfI3L0d8GIbGmcdFAS1uIRGjA=="], + + "qs": ["qs@6.15.3", "", { "dependencies": { "es-define-property": "^1.0.1", "side-channel": "^1.1.1" } }, "sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A=="], + + "queue-microtask": ["queue-microtask@1.2.3", "", {}, "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A=="], + + "radix-ui": ["radix-ui@1.6.7", "", { "dependencies": { "@radix-ui/primitive": "1.1.7", "@radix-ui/react-accessible-icon": "1.1.15", "@radix-ui/react-accordion": "1.2.20", "@radix-ui/react-alert-dialog": "1.1.23", "@radix-ui/react-arrow": "1.1.15", "@radix-ui/react-aspect-ratio": "1.1.15", "@radix-ui/react-avatar": "1.2.6", "@radix-ui/react-checkbox": "1.3.11", "@radix-ui/react-collapsible": "1.1.20", "@radix-ui/react-collection": "1.1.15", "@radix-ui/react-compose-refs": "1.1.5", "@radix-ui/react-context": "1.2.2", "@radix-ui/react-context-menu": "2.3.7", "@radix-ui/react-dialog": "1.1.23", "@radix-ui/react-direction": "1.1.4", "@radix-ui/react-dismissable-layer": "1.1.19", "@radix-ui/react-dropdown-menu": "2.1.24", "@radix-ui/react-focus-guards": "1.1.6", "@radix-ui/react-focus-scope": "1.1.16", "@radix-ui/react-form": "0.1.16", "@radix-ui/react-hover-card": "1.1.23", "@radix-ui/react-label": "2.1.15", "@radix-ui/react-menu": "2.1.24", "@radix-ui/react-menubar": "1.1.24", "@radix-ui/react-navigation-menu": "1.2.22", "@radix-ui/react-one-time-password-field": "0.1.16", "@radix-ui/react-password-toggle-field": "0.1.11", "@radix-ui/react-popover": "1.1.23", "@radix-ui/react-popper": "1.3.7", "@radix-ui/react-portal": "1.1.17", "@radix-ui/react-presence": "1.1.10", "@radix-ui/react-primitive": "2.1.10", "@radix-ui/react-progress": "1.1.16", "@radix-ui/react-radio-group": "1.4.7", "@radix-ui/react-roving-focus": "1.1.19", "@radix-ui/react-scroll-area": "1.2.18", "@radix-ui/react-select": "2.3.7", "@radix-ui/react-separator": "1.1.15", "@radix-ui/react-slider": "1.4.7", "@radix-ui/react-slot": "1.3.3", "@radix-ui/react-switch": "1.3.7", "@radix-ui/react-tabs": "1.1.21", "@radix-ui/react-toast": "1.2.23", "@radix-ui/react-toggle": "1.1.18", "@radix-ui/react-toggle-group": "1.1.19", "@radix-ui/react-toolbar": "1.1.19", "@radix-ui/react-tooltip": "1.2.16", "@radix-ui/react-use-callback-ref": "1.1.4", "@radix-ui/react-use-controllable-state": "1.2.6", "@radix-ui/react-use-effect-event": "0.0.5", "@radix-ui/react-use-escape-keydown": "1.1.5", "@radix-ui/react-use-is-hydrated": "0.1.3", "@radix-ui/react-use-layout-effect": "1.1.4", "@radix-ui/react-use-size": "1.1.4", "@radix-ui/react-visually-hidden": "1.2.11" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-QBdhh1arIEUvPC0dQ5+nwWAxt7+N+oP/9jPwjJkGFoSk/sqxg32gJtSXGtFh8frAIcS6oC9cx2Q+7KYCQLOAeA=="], + + "range-parser": ["range-parser@1.3.0", "", {}, "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw=="], + + "raw-body": ["raw-body@3.0.2", "", { "dependencies": { "bytes": "~3.1.2", "http-errors": "~2.0.1", "iconv-lite": "~0.7.0", "unpipe": "~1.0.0" } }, "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA=="], + + "react": ["react@18.3.1", "", { "dependencies": { "loose-envify": "^1.1.0" } }, "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ=="], + + "react-dom": ["react-dom@18.3.1", "", { "dependencies": { "loose-envify": "^1.1.0", "scheduler": "^0.23.2" }, "peerDependencies": { "react": "^18.3.1" } }, "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw=="], + + "react-refresh": ["react-refresh@0.17.0", "", {}, "sha512-z6F7K9bV85EfseRCp2bzrpyQ0Gkw1uLoCel9XBVWPg/TjRj94SkJzUTGfOa4bs7iJvBWtQG0Wq7wnI0syw3EBQ=="], + + "react-remove-scroll": ["react-remove-scroll@2.7.2", "", { "dependencies": { "react-remove-scroll-bar": "^2.3.7", "react-style-singleton": "^2.2.3", "tslib": "^2.1.0", "use-callback-ref": "^1.3.3", "use-sidecar": "^1.1.3" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Iqb9NjCCTt6Hf+vOdNIZGdTiH1QSqr27H/Ek9sv/a97gfueI/5h1s3yRi1nngzMUaOOToin5dI1dXKdXiF+u0Q=="], + + "react-remove-scroll-bar": ["react-remove-scroll-bar@2.3.8", "", { "dependencies": { "react-style-singleton": "^2.2.2", "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" }, "optionalPeers": ["@types/react"] }, "sha512-9r+yi9+mgU33AKcj6IbT9oRCO78WriSj6t/cF8DWBZJ9aOGPOTEDvdUDz1FwKim7QXWwmHqtdHnRJfhAxEG46Q=="], + + "react-style-singleton": ["react-style-singleton@2.2.3", "", { "dependencies": { "get-nonce": "^1.0.0", "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-b6jSvxvVnyptAiLjbkWLE/lOnR4lfTtDAl+eUC7RZy+QQWc6wRzIV2CE6xBuMmDxc2qIihtDCZD5NPOFl7fRBQ=="], + + "react-webcam": ["react-webcam@7.2.0", "", { "peerDependencies": { "react": ">=16.2.0", "react-dom": ">=16.2.0" } }, "sha512-xkrzYPqa1ag2DP+2Q/kLKBmCIfEx49bVdgCCCcZf88oF+0NPEbkwYk3/s/C7Zy0mhM8k+hpdNkBLzxg8H0aWcg=="], + + "recast": ["recast@0.23.21", "", { "dependencies": { "ast-types": "^0.16.1", "esprima": "~4.0.0", "source-map": "~0.6.1", "tiny-invariant": "^1.3.3", "tslib": "^2.0.1" } }, "sha512-mFAyJq9vUbSTARLZUvAEf1z3YxlvAwswbmxMx2mPA/MSm4KmpwvwvhsH/NIrZhyOuwD60Lzyw2qh83uCbgTPYw=="], + + "require-directory": ["require-directory@2.1.1", "", {}, "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q=="], + + "require-from-string": ["require-from-string@2.0.2", "", {}, "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw=="], + + "resolve-from": ["resolve-from@4.0.0", "", {}, "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g=="], + + "restore-cursor": ["restore-cursor@5.1.0", "", { "dependencies": { "onetime": "^7.0.0", "signal-exit": "^4.1.0" } }, "sha512-oMA2dcrw6u0YfxJQXm342bFKX/E4sG9rbTzO9ptUcR/e8A33cHuvStiYOwH7fszkZlZ1z/ta9AAoPk2F4qIOHA=="], + + "reusify": ["reusify@1.1.0", "", {}, "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw=="], + + "rollup": ["rollup@4.62.4", "", { "dependencies": { "@types/estree": "1.0.9" }, "optionalDependencies": { "@napi-rs/lzma-linux-x64-gnu": "1.5.1", "@rollup/rollup-android-arm-eabi": "4.62.4", "@rollup/rollup-android-arm64": "4.62.4", "@rollup/rollup-darwin-arm64": "4.62.4", "@rollup/rollup-darwin-x64": "4.62.4", "@rollup/rollup-freebsd-arm64": "4.62.4", "@rollup/rollup-freebsd-x64": "4.62.4", "@rollup/rollup-linux-arm-gnueabihf": "4.62.4", "@rollup/rollup-linux-arm-musleabihf": "4.62.4", "@rollup/rollup-linux-arm64-gnu": "4.62.4", "@rollup/rollup-linux-arm64-musl": "4.62.4", "@rollup/rollup-linux-loong64-gnu": "4.62.4", "@rollup/rollup-linux-loong64-musl": "4.62.4", "@rollup/rollup-linux-ppc64-gnu": "4.62.4", "@rollup/rollup-linux-ppc64-musl": "4.62.4", "@rollup/rollup-linux-riscv64-gnu": "4.62.4", "@rollup/rollup-linux-riscv64-musl": "4.62.4", "@rollup/rollup-linux-s390x-gnu": "4.62.4", "@rollup/rollup-linux-x64-gnu": "4.62.4", "@rollup/rollup-linux-x64-musl": "4.62.4", "@rollup/rollup-openbsd-x64": "4.62.4", "@rollup/rollup-openharmony-arm64": "4.62.4", "@rollup/rollup-win32-arm64-msvc": "4.62.4", "@rollup/rollup-win32-ia32-msvc": "4.62.4", "@rollup/rollup-win32-x64-gnu": "4.62.4", "@rollup/rollup-win32-x64-msvc": "4.62.4", "fsevents": "~2.3.2" }, "bin": { "rollup": "dist/bin/rollup" } }, "sha512-RXOqwaPsBGjMNMa4sQjDjHieHEZDFoj/Rdr46l2MU5DfEs16wHJPC2RPTPHWhNl+M3aI472LLqFkFKut4SblOg=="], + + "router": ["router@2.2.0", "", { "dependencies": { "debug": "^4.4.0", "depd": "^2.0.0", "is-promise": "^4.0.0", "parseurl": "^1.3.3", "path-to-regexp": "^8.0.0" } }, "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ=="], + + "run-applescript": ["run-applescript@7.1.0", "", {}, "sha512-DPe5pVFaAsinSaV6QjQ6gdiedWDcRCbUuiQfQa2wmWV7+xC9bGulGI8+TdRmoFkAPaBXk8CrAbnlY2ISniJ47Q=="], + + "run-parallel": ["run-parallel@1.2.0", "", { "dependencies": { "queue-microtask": "^1.2.2" } }, "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA=="], + + "rxjs": ["rxjs@7.8.2", "", { "dependencies": { "tslib": "^2.1.0" } }, "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA=="], + + "safer-buffer": ["safer-buffer@2.1.2", "", {}, "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="], + + "scheduler": ["scheduler@0.23.2", "", { "dependencies": { "loose-envify": "^1.1.0" } }, "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ=="], + + "semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="], + + "send": ["send@1.2.1", "", { "dependencies": { "debug": "^4.4.3", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "fresh": "^2.0.0", "http-errors": "^2.0.1", "mime-types": "^3.0.2", "ms": "^2.1.3", "on-finished": "^2.4.1", "range-parser": "^1.2.1", "statuses": "^2.0.2" } }, "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ=="], + + "seroval": ["seroval@1.6.2", "", {}, "sha512-mPT+SD2TrlB6wvte1KkYOYUkubaTbd6pZ/6Kk3C9nxzrHmCZyhxOO7XGAeL7f+yLKZglzGtM9odUVvg/EhO+vQ=="], + + "seroval-plugins": ["seroval-plugins@1.6.2", "", { "peerDependencies": { "seroval": "^1.0" } }, "sha512-TfxuUjlbBESzUOWdTkTKqvSmav0ABym+itetDXLK6mDz8SmrpdI30aF8RTXE8Bvq+tH/1yIDkvy3W0lfQb1ipQ=="], + + "serve-static": ["serve-static@2.2.1", "", { "dependencies": { "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "parseurl": "^1.3.3", "send": "^1.2.0" } }, "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw=="], + + "setprototypeof": ["setprototypeof@1.2.0", "", {}, "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw=="], + + "shadcn": ["shadcn@4.18.0", "", { "dependencies": { "@babel/core": "^7.28.0", "@babel/parser": "^7.28.0", "@babel/plugin-transform-typescript": "^7.28.0", "@babel/preset-typescript": "^7.27.1", "@dotenvx/dotenvx": "^1.48.4", "@modelcontextprotocol/sdk": "^1.26.0", "@types/validate-npm-package-name": "^4.0.2", "browserslist": "^4.26.2", "commander": "^14.0.0", "cosmiconfig": "^9.0.0", "dedent": "^1.6.0", "deepmerge": "^4.3.1", "diff": "^8.0.2", "execa": "^9.6.0", "fast-glob": "^3.3.3", "fs-extra": "^11.3.1", "fuzzysort": "^3.1.0", "kleur": "^4.1.5", "open": "^11.0.0", "ora": "^8.2.0", "postcss": "^8.5.6", "postcss-selector-parser": "^7.1.0", "prompts": "^2.4.2", "recast": "^0.23.11", "socks": "^2.8.8", "stringify-object": "^5.0.0", "tailwind-merge": "^3.0.1", "ts-morph": "^26.0.0", "tsconfig-paths": "^4.2.0", "undici": "^7.27.2", "validate-npm-package-name": "^7.0.1", "zod": "^3.24.1", "zod-to-json-schema": "^3.24.6" }, "bin": { "shadcn": "dist/index.js" } }, "sha512-tUFZgkYmfVNQVm3xX7lhSzOvDsp+O14ac5dwgXIr5mIsr79ISueb/Mu+ZtWMz0DH6v77u4eYyvbQ9TTMpSn3aw=="], + + "shebang-command": ["shebang-command@2.0.0", "", { "dependencies": { "shebang-regex": "^3.0.0" } }, "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA=="], + + "shebang-regex": ["shebang-regex@3.0.0", "", {}, "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="], + + "shell-quote": ["shell-quote@1.9.0", "", {}, "sha512-Iov+JwFv/2HcTpcwNMKd8+IWNb8tboQJNQTkAY/LLVK7gGH9jy+LGkVqPxfekHl+yMmiqXszdGWXgkfml7hjqA=="], + + "side-channel": ["side-channel@1.1.1", "", { "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.4", "side-channel-list": "^1.0.1", "side-channel-map": "^1.0.1", "side-channel-weakmap": "^1.0.2" } }, "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ=="], + + "side-channel-list": ["side-channel-list@1.0.1", "", { "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.4" } }, "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w=="], + + "side-channel-map": ["side-channel-map@1.0.1", "", { "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.5", "object-inspect": "^1.13.3" } }, "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA=="], + + "side-channel-weakmap": ["side-channel-weakmap@1.0.2", "", { "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", "get-intrinsic": "^1.2.5", "object-inspect": "^1.13.3", "side-channel-map": "^1.0.1" } }, "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A=="], + + "signal-exit": ["signal-exit@4.1.0", "", {}, "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw=="], + + "sisteransi": ["sisteransi@1.0.5", "", {}, "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg=="], + + "smart-buffer": ["smart-buffer@4.2.0", "", {}, "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg=="], + + "socket.io-client": ["socket.io-client@4.8.3", "", { "dependencies": { "@socket.io/component-emitter": "~3.1.0", "debug": "~4.4.1", "engine.io-client": "~6.6.1", "socket.io-parser": "~4.2.4" } }, "sha512-uP0bpjWrjQmUt5DTHq9RuoCBdFJF10cdX9X+a368j/Ft0wmaVgxlrjvK3kjvgCODOMMOz9lcaRzxmso0bTWZ/g=="], + + "socket.io-parser": ["socket.io-parser@4.2.7", "", { "dependencies": { "@socket.io/component-emitter": "~3.1.0", "debug": "~4.4.1" } }, "sha512-IH/iSeO9T6gz1KkFleGDWkG9N3dl4jXVYUtMhIqH10Md0ttMer8nUNWiP1DKuNrybD2xBrixLJdCC9J6ECoYkg=="], + + "socks": ["socks@2.8.9", "", { "dependencies": { "ip-address": "^10.1.1", "smart-buffer": "^4.2.0" } }, "sha512-LJhUYUvItdQ0LkJTmPeaEObWXAqFyfmP85x0tch/ez9cahmhlBBLbIqDFnvBnUJGagb0JbIQrkBs1wJ+yRYpEw=="], + + "sonner": ["sonner@2.0.8", "", { "peerDependencies": { "@types/react": "^18.0.0 || ^19.0.0", "react": "^18.0.0 || ^19.0.0 || ^19.0.0-rc", "react-dom": "^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-UM/ByIoFra8yzV75n1o0Puu0bw5U/9UNnDacrJNspekBewIfsQ3D6ez1nvlWpt7aTsO6rujQtifBpycwIivqlg=="], + + "source-map": ["source-map@0.6.1", "", {}, "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="], + + "source-map-js": ["source-map-js@1.2.1", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="], + + "statuses": ["statuses@2.0.2", "", {}, "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw=="], + + "stdin-discarder": ["stdin-discarder@0.2.2", "", {}, "sha512-UhDfHmA92YAlNnCfhmq0VeNL5bDbiZGg7sZ2IvPsXubGkiNa9EC+tUTsjBRsYUAz87btI6/1wf4XoVvQ3uRnmQ=="], + + "string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="], + + "stringify-object": ["stringify-object@5.0.0", "", { "dependencies": { "get-own-enumerable-keys": "^1.0.0", "is-obj": "^3.0.0", "is-regexp": "^3.1.0" } }, "sha512-zaJYxz2FtcMb4f+g60KsRNFOpVMUyuJgA51Zi5Z1DOTC3S59+OQiVOzE9GZt0x72uBGWKsQIuBKeF9iusmKFsg=="], + + "strip-ansi": ["strip-ansi@7.2.0", "", { "dependencies": { "ansi-regex": "^6.2.2" } }, "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w=="], + + "strip-bom": ["strip-bom@3.0.0", "", {}, "sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA=="], + + "strip-final-newline": ["strip-final-newline@4.0.0", "", {}, "sha512-aulFJcD6YK8V1G7iRB5tigAP4TsHBZZrOV8pjV++zdUwmeV8uzbY7yn6h9MswN62adStNZFuCIx4haBnRuMDaw=="], + + "supports-color": ["supports-color@8.1.1", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q=="], + + "systeminformation": ["systeminformation@5.33.1", "", { "os": "!aix", "bin": { "systeminformation": "lib/cli.js" } }, "sha512-DEN6ICHk3Tk0Uf/hrAHh7xlt7iL5CJFBtPZinA0H62DrGG/KPKqq/Nzj6lCXPS4Ay/sf/14zNnk9LpqKzBIc+w=="], + + "tailwind-merge": ["tailwind-merge@3.6.0", "", {}, "sha512-uxL7qAVQriqRQPAyK3pj66VqskWqoZ37PW94jwOTwNfq/z9oyu1V+eqrZqtR2+fCiXdYOZe/Modt8GtvqNzu+w=="], + + "tailwindcss": ["tailwindcss@4.3.3", "", {}, "sha512-gOhV3P7ufE62QDGg1zVaTgCR+EtPv92k2nIhVcVKcLmxT1sUBsQGhnZj175j+MqRt4zLF7ic+sCYjfhxMxj7YQ=="], + + "tapable": ["tapable@2.3.3", "", {}, "sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A=="], + + "tiny-invariant": ["tiny-invariant@1.3.3", "", {}, "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg=="], + + "tinyglobby": ["tinyglobby@0.2.17", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g=="], + + "to-regex-range": ["to-regex-range@5.0.1", "", { "dependencies": { "is-number": "^7.0.0" } }, "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ=="], + + "toidentifier": ["toidentifier@1.0.1", "", {}, "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA=="], + + "tree-kill": ["tree-kill@1.2.2", "", { "bin": { "tree-kill": "cli.js" } }, "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A=="], + + "ts-morph": ["ts-morph@26.0.0", "", { "dependencies": { "@ts-morph/common": "~0.27.0", "code-block-writer": "^13.0.3" } }, "sha512-ztMO++owQnz8c/gIENcM9XfCEzgoGphTv+nKpYNM1bgsdOVC/jRZuEBf6N+mLLDNg68Kl+GgUZfOySaRiG1/Ug=="], + + "tsconfig-paths": ["tsconfig-paths@4.2.0", "", { "dependencies": { "json5": "^2.2.2", "minimist": "^1.2.6", "strip-bom": "^3.0.0" } }, "sha512-NoZ4roiN7LnbKn9QqE1amc9DJfzvZXxF4xDavcOWt1BPkdx+m+0gJuPM+S0vCe7zTJMYUP0R8pO2XMr+Y8oLIg=="], + + "tslib": ["tslib@2.8.1", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="], + + "tw-animate-css": ["tw-animate-css@1.4.0", "", {}, "sha512-7bziOlRqH0hJx80h/3mbicLW7o8qLsH5+RaLR2t+OHM3D0JlWGODQKQ4cxbK7WlvmUxpcj6Kgu6EKqjrGFe3QQ=="], + + "type-is": ["type-is@2.1.0", "", { "dependencies": { "content-type": "^2.0.0", "media-typer": "^1.1.0", "mime-types": "^3.0.0" } }, "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA=="], + + "typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="], + + "undici": ["undici@7.29.0", "", {}, "sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw=="], + + "undici-types": ["undici-types@7.24.6", "", {}, "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg=="], + + "unicorn-magic": ["unicorn-magic@0.3.0", "", {}, "sha512-+QBBXBCvifc56fsbuxZQ6Sic3wqqc3WWaqxs58gvJrcOuN83HGTCwz3oS5phzU9LthRNE9VrJCFCLUgHeeFnfA=="], + + "universalify": ["universalify@2.0.1", "", {}, "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw=="], + + "unpipe": ["unpipe@1.0.0", "", {}, "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ=="], + + "update-browserslist-db": ["update-browserslist-db@1.3.1", "", { "dependencies": { "escalade": "^3.2.0", "picocolors": "^1.1.1" }, "peerDependencies": { "browserslist": ">= 4.21.0" }, "bin": { "update-browserslist-db": "cli.js" } }, "sha512-ZZ61DsRsOnakl74HAmp3oSN4aXUmEWXf+i/yv0h7tIBfICc3VdrFErQKUUKPgu3AMsTUMbcongALEN4l6GSUrQ=="], + + "use-callback-ref": ["use-callback-ref@1.3.3", "", { "dependencies": { "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jQL3lRnocaFtu3V00JToYz/4QkNWswxijDaCVNZRiRTO3HQDLsdu1ZtmIUvV4yPp+rvWm5j0y0TG/S61cuijTg=="], + + "use-sidecar": ["use-sidecar@1.1.3", "", { "dependencies": { "detect-node-es": "^1.1.0", "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Fedw0aZvkhynoPYlA5WXrMCAMm+nSWdZt6lzJQ7Ok8S6Q+VsHmHpRWndVRJ8Be0ZbkfPc5LRYH+5XrzXcEeLRQ=="], + + "use-sync-external-store": ["use-sync-external-store@1.6.0", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w=="], + + "util-deprecate": ["util-deprecate@1.0.2", "", {}, "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="], + + "validate-npm-package-name": ["validate-npm-package-name@7.0.2", "", {}, "sha512-hVDIBwsRruT73PbK7uP5ebUt+ezEtCmzZz3F59BSr2F6OVFnJ/6h8liuvdLrQ88Xmnk6/+xGGuq+pG9WwTuy3A=="], + + "vary": ["vary@1.1.2", "", {}, "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg=="], + + "vite": ["vite@6.4.3", "", { "dependencies": { "esbuild": "^0.25.0", "fdir": "^6.4.4", "picomatch": "^4.0.2", "postcss": "^8.5.3", "rollup": "^4.34.9", "tinyglobby": "^0.2.13" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", "jiti": ">=1.21.0", "less": "*", "lightningcss": "^1.21.0", "sass": "*", "sass-embedded": "*", "stylus": "*", "sugarss": "*", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-NTKlcQjlAK7MlQoyb6LgaqHc8sso/pVyUJYWMws3jg21uTJw/LddqIFPcPqP6PzpgbIcZyKI85sFE4HBrQDA8A=="], + + "which": ["which@4.0.0", "", { "dependencies": { "isexe": "^3.1.1" }, "bin": { "node-which": "bin/which.js" } }, "sha512-GlaYyEb07DPxYCKhKzplCWBJtvxZcZMrL+4UkrTSJHHPyZU4mYYTv3qaOe77H7EODLSSopAUFAc6W8U4yqvscg=="], + + "wrap-ansi": ["wrap-ansi@7.0.0", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q=="], + + "wrappy": ["wrappy@1.0.2", "", {}, "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="], + + "ws": ["ws@8.21.3", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw=="], + + "wsl-utils": ["wsl-utils@1.0.0", "", { "dependencies": { "is-wsl": "^3.1.0", "powershell-utils": "^0.1.0" } }, "sha512-Hl0ZOAs672vg+06kfujwRhoS6/jehvULrlFkuF2dRu6pHgA8U06h3xqNIqNNU1LTXPcedxByAR4GS6pwQK0mgA=="], + + "xmlhttprequest-ssl": ["xmlhttprequest-ssl@2.1.2", "", {}, "sha512-TEU+nJVUUnA4CYJFLvK5X9AOeH4KvDvhIfm0vV1GaQRtchnG0hgK5p8hw/xjv8cunWYCsiPCSDzObPyhEwq3KQ=="], + + "y18n": ["y18n@5.0.8", "", {}, "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA=="], + + "yallist": ["yallist@3.1.1", "", {}, "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g=="], + + "yargs": ["yargs@17.7.2", "", { "dependencies": { "cliui": "^8.0.1", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "require-directory": "^2.1.1", "string-width": "^4.2.3", "y18n": "^5.0.5", "yargs-parser": "^21.1.1" } }, "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w=="], + + "yargs-parser": ["yargs-parser@21.1.1", "", {}, "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw=="], + + "yocto-spinner": ["yocto-spinner@1.2.2", "", { "dependencies": { "yoctocolors": "^2.1.1" } }, "sha512-DODGl1wJjA/s5pnJFKau9lIYHT81lnhob1i3e1TjxZRxEhWRKl74nTbWE6H5KlkViQQTo/Z29YFdxzTZAMY3ng=="], + + "yoctocolors": ["yoctocolors@2.2.0", "", {}, "sha512-xYqdZFUK/VYazNl/oCDYN+3WloWQwMfZxBoiNt6qNyk+xfOdi598muWE42rNZFp1kNOiqW936q5RhUdnpqElSg=="], + + "zod": ["zod@4.4.3", "", {}, "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ=="], + + "zod-to-json-schema": ["zod-to-json-schema@3.25.2", "", { "peerDependencies": { "zod": "^3.25.28 || ^4" } }, "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA=="], + + "zustand": ["zustand@5.0.15", "", { "peerDependencies": { "@types/react": ">=18.0.0", "immer": ">=9.0.6", "react": ">=18.0.0", "use-sync-external-store": ">=1.2.0" }, "optionalPeers": ["@types/react", "immer", "react", "use-sync-external-store"] }, "sha512-MpSEjRiBkA9crSYeOUH32rJC7SVqAbm0Fqcqge/bUi2PPoLcBWKOsG+C8mevmpr8TwXHBVkChbbJiyvkE+i/3A=="], + + "@dotenvx/dotenvx/commander": ["commander@11.1.0", "", {}, "sha512-yPVavfyCcRhmorC7rWlkHn15b4wDVgVmBA7kV4QVBsF7kv/9TKJAbAXVTxvTnwP8HHKjRCJDClKbciiYS7p0DQ=="], + + "@dotenvx/dotenvx/execa": ["execa@5.1.1", "", { "dependencies": { "cross-spawn": "^7.0.3", "get-stream": "^6.0.0", "human-signals": "^2.1.0", "is-stream": "^2.0.0", "merge-stream": "^2.0.0", "npm-run-path": "^4.0.1", "onetime": "^5.1.2", "signal-exit": "^3.0.3", "strip-final-newline": "^2.0.0" } }, "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg=="], + + "@dotenvx/dotenvx/open": ["open@8.4.2", "", { "dependencies": { "define-lazy-prop": "^2.0.0", "is-docker": "^2.1.1", "is-wsl": "^2.2.0" } }, "sha512-7x81NCL719oNbsq/3mh+hVrAWmFuEYUqrq/Iw3kUzH8ReypT9QQ0BLoJS7/G9k6N81XjW4qHWtjWwe/9eLy1EQ=="], + + "@tailwindcss/oxide-wasm32-wasi/@emnapi/core": ["@emnapi/core@1.11.3", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.3", "tslib": "^2.4.0" }, "bundled": true }, "sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg=="], + + "@tailwindcss/oxide-wasm32-wasi/@emnapi/runtime": ["@emnapi/runtime@1.11.3", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA=="], + + "@tailwindcss/oxide-wasm32-wasi/@emnapi/wasi-threads": ["@emnapi/wasi-threads@1.2.3", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-ELEBe8PsLvvJ6QMr0zLt8ffvOHW/dc1m3CEzNMg7aJUv3bMaoDtw2TXyDAwkYBuroxxuHEwhRTLJSe5sya547g=="], + + "@tailwindcss/oxide-wasm32-wasi/@napi-rs/wasm-runtime": ["@napi-rs/wasm-runtime@1.2.3", "", { "dependencies": { "@tybys/wasm-util": "^0.10.3" }, "peerDependencies": { "@emnapi/core": "^1.7.1 || ^2.0.0-alpha.4", "@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.4" }, "bundled": true }, "sha512-UMduMbqO5s5zF2NkNacMT/yK5Y5QiKvWr2+50bzIIxFDwVJ2h49b+oyjaCGPhJxd2/gC2x39EHv/gHVuu36x2Q=="], + + "@tailwindcss/oxide-wasm32-wasi/@tybys/wasm-util": ["@tybys/wasm-util@0.10.3", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg=="], + + "@tailwindcss/oxide-wasm32-wasi/tslib": ["tslib@2.8.1", "", { "bundled": true }, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="], + + "body-parser/content-type": ["content-type@2.1.0", "", {}, "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag=="], + + "chalk/supports-color": ["supports-color@7.2.0", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw=="], + + "cliui/strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="], + + "conf/ajv-formats": ["ajv-formats@2.1.1", "", { "dependencies": { "ajv": "^8.0.0" } }, "sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA=="], + + "conf/json-schema-typed": ["json-schema-typed@7.0.3", "", {}, "sha512-7DE8mpG+/fVw+dTpjbxnx47TaMnDfOI1jwft9g1VybltZCduyRQPJPvc+zzKY9WPHxhPWczyFuYa6I8Mw4iU5A=="], + + "conf/semver": ["semver@7.8.5", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="], + + "cross-spawn/which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="], + + "dot-prop/is-obj": ["is-obj@2.0.0", "", {}, "sha512-drqDG3cbczxxEJRoOXcOjtdp1J/lyp1mNn0xaznRs8+muBhgQcrnbspox5X5fOw0HnMnbfDzvnEMEtqDEJEo8w=="], + + "enquirer/strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="], + + "is-inside-container/is-docker": ["is-docker@3.0.0", "", { "bin": { "is-docker": "cli.js" } }, "sha512-eljcgEDlEns/7AXFosB5K/2nCM4P7FQPkGc/DWLy5rmFEWvZayGrik1d9/QIY5nJ4f9YsVvBkA6kJpHn9rISdQ=="], + + "log-symbols/chalk": ["chalk@5.6.2", "", {}, "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA=="], + + "log-symbols/is-unicode-supported": ["is-unicode-supported@1.3.0", "", {}, "sha512-43r2mRvz+8JRIKnWJ+3j8JtjRKZ6GmjzfaE/qiBJnikNnYv/6bagRJ1kUhNk8R5EX/GkobD+r+sfxCPJsiKBLQ=="], + + "micromatch/picomatch": ["picomatch@2.3.2", "", {}, "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA=="], + + "npm-run-path/path-key": ["path-key@4.0.0", "", {}, "sha512-haREypq7xkM7ErfgIyA0z+Bj4AGKlMSdlQE2jvJo6huWD1EdkKYV+G/T4nq0YEF2vgTT8kqMFKo1uHn950r4SQ=="], + + "onetime/mimic-fn": ["mimic-fn@2.1.0", "", {}, "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg=="], + + "ora/chalk": ["chalk@5.6.2", "", {}, "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA=="], + + "ora/string-width": ["string-width@7.2.0", "", { "dependencies": { "emoji-regex": "^10.3.0", "get-east-asian-width": "^1.0.0", "strip-ansi": "^7.1.0" } }, "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ=="], + + "prompts/kleur": ["kleur@3.0.3", "", {}, "sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w=="], + + "restore-cursor/onetime": ["onetime@7.0.0", "", { "dependencies": { "mimic-function": "^5.0.0" } }, "sha512-VXJjc87FScF88uafS3JllDgvAm+c/Slfz06lorj2uAY34rlUu0Nt+v8wreiImcrgAjjIHp1rXpTDlLOGw29WwQ=="], + + "shadcn/zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="], + + "string-width/strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="], + + "type-is/content-type": ["content-type@2.1.0", "", {}, "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag=="], + + "wrap-ansi/strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="], + + "wsl-utils/is-wsl": ["is-wsl@3.1.1", "", { "dependencies": { "is-inside-container": "^1.0.0" } }, "sha512-e6rvdUCiQCAuumZslxRJWR/Doq4VpPR82kqclvcS0efgt430SlGIk05vdCN58+VrzgtIcfNODjozVielycD4Sw=="], + + "wsl-utils/powershell-utils": ["powershell-utils@0.1.0", "", {}, "sha512-dM0jVuXJPsDN6DvRpea484tCUaMiXWjuCn++HGTqUWzGDjv5tZkEZldAJ/UMlqRYGFrD/etByo4/xOuC/snX2A=="], + + "@dotenvx/dotenvx/execa/get-stream": ["get-stream@6.0.1", "", {}, "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg=="], + + "@dotenvx/dotenvx/execa/human-signals": ["human-signals@2.1.0", "", {}, "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw=="], + + "@dotenvx/dotenvx/execa/is-stream": ["is-stream@2.0.1", "", {}, "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg=="], + + "@dotenvx/dotenvx/execa/npm-run-path": ["npm-run-path@4.0.1", "", { "dependencies": { "path-key": "^3.0.0" } }, "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw=="], + + "@dotenvx/dotenvx/execa/signal-exit": ["signal-exit@3.0.7", "", {}, "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="], + + "@dotenvx/dotenvx/execa/strip-final-newline": ["strip-final-newline@2.0.0", "", {}, "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA=="], + + "@dotenvx/dotenvx/open/define-lazy-prop": ["define-lazy-prop@2.0.0", "", {}, "sha512-Ds09qNh8yw3khSjiJjiUInaGX9xlqZDY7JVryGxdxV7NPeuqQfplOpQ66yJFZut3jLa5zOwkXw1g9EI2uKh4Og=="], + + "cliui/strip-ansi/ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="], + + "cross-spawn/which/isexe": ["isexe@2.0.0", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="], + + "enquirer/strip-ansi/ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="], + + "ora/string-width/emoji-regex": ["emoji-regex@10.6.0", "", {}, "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A=="], + + "string-width/strip-ansi/ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="], + + "wrap-ansi/strip-ansi/ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="], + } +} diff --git a/headless-rust/components.json b/headless-rust/components.json new file mode 100644 index 0000000..3391810 --- /dev/null +++ b/headless-rust/components.json @@ -0,0 +1,25 @@ +{ + "$schema": "https://ui.shadcn.com/schema.json", + "style": "radix-maia", + "rsc": false, + "tsx": true, + "tailwind": { + "config": "tailwind.config.js", + "css": "frontend/src/index.css", + "baseColor": "zinc", + "cssVariables": true, + "prefix": "" + }, + "iconLibrary": "hugeicons", + "rtl": false, + "aliases": { + "components": "@/components", + "utils": "@/lib/utils", + "ui": "@/components/ui", + "lib": "@/lib", + "hooks": "@/hooks" + }, + "menuColor": "default", + "menuAccent": "subtle", + "registries": {} +} diff --git a/headless-rust/diagnostics/analyzer/report-generator.ts b/headless-rust/diagnostics/analyzer/report-generator.ts new file mode 100644 index 0000000..984da7b --- /dev/null +++ b/headless-rust/diagnostics/analyzer/report-generator.ts @@ -0,0 +1,156 @@ +import { mkdirSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import type { DiagConfig } from "../config"; +import type { AnalysisSummary } from "./rule-engine"; +import type { ScenarioResult } from "../scenarios/baseline"; + +export function generateReportFiles( + config: DiagConfig, + analysis: AnalysisSummary, + results: Record +): { jsonPath: string; mdPath: string } { + try { + mkdirSync(config.outputDir, { recursive: true }); + } catch (_) {} + + const jsonPath = join(config.outputDir, "diagnostic-report.json"); + const mdPath = join(config.outputDir, "diagnostic-report.md"); + + // 1. JSON Report + const jsonReport = { + timestamp: new Date().toISOString(), + target: config.target, + host: config.host, + port: config.port, + overallHealth: analysis.overallHealth, + primaryRootCause: analysis.primaryRootCause, + findings: analysis.findings, + scenarioResults: results, + }; + writeFileSync(jsonPath, JSON.stringify(jsonReport, null, 2), "utf-8"); + + // 2. Markdown Report + const mdContent = buildMarkdownReport(config, analysis, results); + writeFileSync(mdPath, mdContent, "utf-8"); + + return { jsonPath, mdPath }; +} + +export function printTerminalSummary( + config: DiagConfig, + analysis: AnalysisSummary, + results: Record +): void { + const line = "=".repeat(70); + console.log("\n" + line); + console.log(" 🔍 SPEEDCAMERA NETWORK & HOTSPOT DIAGNOSTIC SUMMARY"); + console.log(line); + console.log(` Target: ${config.target} (${config.host}:${config.port})`); + console.log(` Status: [ ${analysis.overallHealth} ]`); + console.log(` Time: ${new Date().toLocaleString()}`); + console.log("-".repeat(70)); + + if (results.baseline?.latencyStats) { + const l = results.baseline.latencyStats; + console.log(` Latency (Ping): Avg: ${l.avgRttMs}ms | Max: ${l.maxRttMs}ms | Loss: ${l.lossPercent.toFixed(1)}% | Jitter: ${l.jitterMs}ms`); + } + if (results.baseline?.wsStats) { + const w = results.baseline.wsStats; + console.log(` WebSocket RPC: Success: ${w.successfulCalls}/${w.totalCalls} | Avg RTT: ${w.avgRpcRttMs}ms | Timeouts: ${w.timedOutCalls} | Clustered Bursts: ${w.burstEventsCount}`); + } + if (results.baseline?.httpStats) { + const h = results.baseline.httpStats; + console.log(` HTTP API / Web: Requests: ${h.successfulRequests}/${h.totalRequests} | Avg TTFB: ${h.avgTtfbMs}ms`); + } + + console.log("-".repeat(70)); + console.log(" ROOT-CAUSE FINDINGS & EVIDENCE:"); + + if (analysis.findings.length === 0) { + console.log(" ✅ No major network anomalies or link stalls detected. Connection is healthy."); + } else { + for (let idx = 0; idx < analysis.findings.length; idx++) { + const f = analysis.findings[idx]; + const badge = f.severity === "CRITICAL" ? "🔴 CRITICAL" : f.severity === "HIGH" ? "🟠 HIGH" : "🟡 MEDIUM"; + console.log(`\n [${idx + 1}] ${badge} (${f.confidenceScore}% Confidence): ${f.title}`); + console.log(` Summary: ${f.summary}`); + console.log(" Evidence:"); + for (const ev of f.empiricalEvidence) { + console.log(` • ${ev}`); + } + console.log(" Remediation:"); + console.log(` ${f.remediation.description}`); + console.log(" Suggested Commands:"); + for (const cmd of f.remediation.commands) { + console.log(` ${cmd}`); + } + } + } + + console.log("\n" + line); +} + +function buildMarkdownReport( + config: DiagConfig, + analysis: AnalysisSummary, + results: Record +): string { + let md = `# Speedcamera Network & Wi-Fi Hotspot Diagnostic Report\n\n`; + md += `**Date:** ${new Date().toISOString()}\n`; + md += `**Target:** \`${config.target}\` (\`${config.host}:${config.port}\`)\n`; + md += `**Overall Health:** **${analysis.overallHealth}**\n\n`; + + md += `## 1. Executive Summary\n\n`; + if (analysis.findings.length === 0) { + md += `> [!NOTE]\n> All diagnostic probes completed successfully with no critical network stalls or socket timeouts detected.\n\n`; + } else { + const primary = analysis.primaryRootCause!; + md += `> [!IMPORTANT]\n`; + md += `> **Primary Root Cause (${primary.confidenceScore}% Confidence):** ${primary.title}\n>\n`; + md += `> ${primary.summary}\n\n`; + } + + md += `## 2. Empirical Findings & Remediation\n\n`; + for (let i = 0; i < analysis.findings.length; i++) { + const f = analysis.findings[i]; + md += `### ${i + 1}. [${f.severity}] ${f.title} (Confidence: ${f.confidenceScore}%)\n\n`; + md += `${f.summary}\n\n`; + + md += `**Empirical Evidence:**\n`; + for (const ev of f.empiricalEvidence) { + md += `- ${ev}\n`; + } + md += `\n**Remediation Steps:**\n`; + md += `${f.remediation.description}\n\n`; + md += `\`\`\`bash\n`; + for (const cmd of f.remediation.commands) { + md += `${cmd}\n`; + } + md += `\`\`\`\n\n`; + } + + md += `## 3. Detailed Telemetry Metrics\n\n`; + if (results.baseline?.latencyStats) { + const l = results.baseline.latencyStats; + md += `### Latency & ICMP Ping\n`; + md += `- **Packets Transmitted:** ${l.transmitted}\n`; + md += `- **Packets Received:** ${l.received}\n`; + md += `- **Packet Loss:** ${l.lossPercent.toFixed(2)}%\n`; + md += `- **Average RTT:** ${l.avgRttMs} ms\n`; + md += `- **Max Latency Spike:** ${l.maxRttMs} ms\n`; + md += `- **Jitter:** ${l.jitterMs} ms\n`; + md += `- **Stall Events (>250ms):** ${l.stallCount}\n\n`; + } + + if (results.baseline?.wsStats) { + const w = results.baseline.wsStats; + md += `### WebSocket RPC & Push Broadcasts\n`; + md += `- **RPC Calls:** ${w.successfulCalls} / ${w.totalCalls} successful\n`; + md += `- **RPC Timeouts:** ${w.timedOutCalls}\n`; + md += `- **Average RPC Latency:** ${w.avgRpcRttMs} ms\n`; + md += `- **Push Events Received:** ${w.pushEventsCount}\n`; + md += `- **Clustered Burst Events:** ${w.burstEventsCount}\n\n`; + } + + return md; +} diff --git a/headless-rust/diagnostics/analyzer/rule-engine.ts b/headless-rust/diagnostics/analyzer/rule-engine.ts new file mode 100644 index 0000000..6aafd8a --- /dev/null +++ b/headless-rust/diagnostics/analyzer/rule-engine.ts @@ -0,0 +1,243 @@ +import type { ScenarioResult } from "../scenarios/baseline"; +import type { FreezeReproducerResult } from "../scenarios/freeze-reproducer"; +import type { ViolationStressResult } from "../scenarios/violation-stress"; +import type { GigeContentionResult } from "../scenarios/gige-wifi-contention"; + +export interface DiagnosticFinding { + id: string; + title: string; + category: "WIFI_LINK" | "BUFFERBLOAT" | "STORAGE_IO" | "CPU_IRQ" | "APP_RUNTIME"; + severity: "CRITICAL" | "HIGH" | "MEDIUM" | "LOW" | "INFO"; + confidenceScore: number; // 0 to 100 + summary: string; + empiricalEvidence: string[]; + remediation: { + description: string; + commands: string[]; + automatedFixScript?: string; + }; +} + +export interface AnalysisSummary { + overallHealth: "HEALTHY" | "DEGRADED" | "CRITICAL"; + primaryRootCause?: DiagnosticFinding; + findings: DiagnosticFinding[]; +} + +export function evaluateDiagnosticFindings(results: { + baseline?: ScenarioResult; + freeze?: FreezeReproducerResult; + violation?: ViolationStressResult; + gige?: GigeContentionResult; +}): AnalysisSummary { + const findings: DiagnosticFinding[] = []; + + // =========================================================================== + // RULE 1: Wi-Fi Power-Save & 802.11 Inactivity Stall (Keystroke Unclog Effect) + // =========================================================================== + let wifiPsConfidence = 0; + const wifiPsEvidence: string[] = []; + + if (results.freeze?.unclogTriggerSuccess) { + wifiPsConfidence += 45; + wifiPsEvidence.push( + `Outbound burst immediately unclogged latency from ${results.freeze.preBurstMaxLatencyMs}ms to ${results.freeze.postBurstAvgLatencyMs}ms` + ); + } + if (results.freeze?.idleFreezeObserved) { + wifiPsConfidence += 30; + wifiPsEvidence.push( + `Link latency spiked to ${results.freeze.preBurstMaxLatencyMs}ms specifically during idle periods` + ); + } + if (results.freeze?.wifiPowerSaveActive) { + wifiPsConfidence += 25; + wifiPsEvidence.push("Wi-Fi power_save is reported ON in the Pi kernel"); + } + + // Also check baseline push event clustering + if ((results.baseline?.wsStats.burstEventsCount || 0) > 0) { + wifiPsConfidence += 15; + wifiPsEvidence.push( + `${results.baseline?.wsStats.burstEventsCount} WebSocket push events arrived in rapid bursts after idle gaps` + ); + } + + wifiPsConfidence = Math.min(100, wifiPsConfidence); + + if (wifiPsConfidence >= 30) { + findings.push({ + id: "WIFI_POWER_SAVE_AP_STALL", + title: "Wi-Fi AP / Client 802.11 Power-Save Sleep & Frame Aggregation Queue Stall", + category: "WIFI_LINK", + severity: wifiPsConfidence >= 70 ? "CRITICAL" : "HIGH", + confidenceScore: wifiPsConfidence, + summary: + "The Pi Wi-Fi driver (brcmfmac) or client 802.11 power management puts the Wi-Fi radio or transmission queue into sleep state during inactivity. Outbound traffic (such as typing in SSH or sending requests) immediately wakes up the queue and flushes buffered frames.", + empiricalEvidence: wifiPsEvidence, + remediation: { + description: + "Disable Wi-Fi power saving permanently, configure hostapd / nmcli DTIM period to 1, and disable brcmfmac TxGlom/P2P sleep options.", + commands: [ + "# 1. Force Wi-Fi power save off immediately on Pi", + "sudo iw dev wlan0 set power_save off", + "# 2. Disable brcmfmac driver power management module parameters", + "sudo bash -c 'echo \"options brcmfmac feature_disable=0x82000\" > /etc/modprobe.d/brcmfmac.conf'", + "# 3. Optimize NetworkManager Wi-Fi AP settings (5GHz, powersave off, no MAC randomization, never-default)", + "sudo nmcli connection modify 'Speedcamera-Hotspot' 802-11-wireless.powersave 2 802-11-wireless.band a 802-11-wireless.channel 36 802-11-wireless.mac-address-randomization 1 ipv4.never-default yes", + "# 4. Permanently disable Wi-Fi power save via systemd service", + "sudo systemctl enable --now wifi-power-off.service", + ], + }, + }); + } + + // =========================================================================== + // RULE 2: Global Socket Buffer Defaults (67MB) Bufferbloat on Wi-Fi + // =========================================================================== + let bufferConfidence = 0; + const bufferEvidence: string[] = []; + + const latestKernel = results.baseline?.kernelSnapshots[results.baseline.kernelSnapshots.length - 1]; + const rmemDefault = latestKernel?.sysctl.rmem_default || 0; + const wmemDefault = latestKernel?.sysctl.wmem_default || 0; + + if (rmemDefault > 10485760 || wmemDefault > 10485760) { + bufferConfidence += 60; + bufferEvidence.push( + `net.core.rmem_default (${(rmemDefault / 1024 / 1024).toFixed(1)}MB) and wmem_default (${(wmemDefault / 1024 / 1024).toFixed(1)}MB) are set globally to GigE extreme sizes` + ); + } + if ((results.baseline?.wsStats.timedOutCalls || 0) > 0 && (results.baseline?.latencyStats.lossPercent || 0) < 5) { + bufferConfidence += 30; + bufferEvidence.push( + `WebSocket RPCs timed out after 5s while basic ICMP ping packets succeeded with low loss (${results.baseline?.latencyStats.lossPercent.toFixed(1)}%)` + ); + } + + bufferConfidence = Math.min(100, bufferConfidence); + + if (bufferConfidence >= 40) { + findings.push({ + id: "GIGE_SYSCTL_BUFFERBLOAT", + title: "Global Socket Buffer Defaults (67MB) Inducing Severe Wi-Fi TCP Bufferbloat", + category: "BUFFERBLOAT", + severity: "HIGH", + confidenceScore: bufferConfidence, + summary: + "Setting net.core.rmem_default and wmem_default to 67MB affects EVERY TCP socket on the Pi (including WebSocket, HTTP, and SSH). When Wi-Fi packet drops occur, massive un-flushed TCP send buffers and inflated congestion windows cause 10-second TCP head-of-line blocking.", + empiricalEvidence: bufferEvidence, + remediation: { + description: + "Keep GigE camera buffer maximums (rmem_max / wmem_max = 128MB) so camera capture sockets can allocate large buffers explicitly via SO_RCVBUF, restore default socket buffer sizes (rmem_default / wmem_default = 262KB) for general TCP/Wi-Fi sockets, and enable fq_codel smart queueing.", + commands: [ + "# Restore sensible default socket buffers while keeping max limits for GigE camera and enable fq_codel", + "sudo bash -c 'cat > /etc/sysctl.d/60-gige-camera.conf < 0) { + storageConfidence += 30; + storageEvidence.push( + `${results.violation?.dStateProcessCount} processes entered D-state (uninterruptible disk sleep) during capture sync` + ); + } + + storageConfidence = Math.min(100, storageConfidence); + + if (storageConfidence >= 30) { + findings.push({ + id: "STORAGE_WRITEBACK_STALL", + title: "Storage Writeback / Dirty Page Flush Freeze during Image Save", + category: "STORAGE_IO", + severity: storageConfidence >= 70 ? "HIGH" : "MEDIUM", + confidenceScore: storageConfidence, + summary: + "When an image is saved to SD card or slow storage, the Linux kernel dirty page ratio triggers synchronous writeback flushes, blocking I/O threads and kernel memory allocation for network buffers.", + empiricalEvidence: storageEvidence, + remediation: { + description: + "Tune Linux virtual memory dirty background ratios to force small, smooth background flushes instead of giant blocking sync bursts.", + commands: [ + "# Lower dirty ratio to trigger early background flushes and prevent large I/O blocking spikes", + "sudo bash -c 'cat > /etc/sysctl.d/70-dirty-writeback.conf < /sys/class/net/eth0/queues/rx-0/rps_cpus 2>/dev/null || echo f > /sys/class/net/end0/queues/rx-0/rps_cpus 2>/dev/null || true'", + "sudo bash -c 'echo f > /sys/class/net/wlan0/queues/rx-0/rps_cpus 2>/dev/null || true'", + ], + }, + }); + } + + // Sort findings by confidence and severity + findings.sort((a, b) => b.confidenceScore - a.confidenceScore); + + let overallHealth: "HEALTHY" | "DEGRADED" | "CRITICAL" = "HEALTHY"; + if (findings.some((f) => f.severity === "CRITICAL")) { + overallHealth = "CRITICAL"; + } else if (findings.some((f) => f.severity === "HIGH" || f.severity === "MEDIUM")) { + overallHealth = "DEGRADED"; + } + + return { + overallHealth, + primaryRootCause: findings[0], + findings, + }; +} diff --git a/headless-rust/diagnostics/cli.ts b/headless-rust/diagnostics/cli.ts new file mode 100755 index 0000000..f74a0e9 --- /dev/null +++ b/headless-rust/diagnostics/cli.ts @@ -0,0 +1,250 @@ +#!/usr/bin/env bun +import { parseArgs } from "./config"; +import { SshClient } from "./ssh-client"; +import { runBaselineScenario } from "./scenarios/baseline"; +import { runFreezeReproducerScenario } from "./scenarios/freeze-reproducer"; +import { runViolationStressScenario } from "./scenarios/violation-stress"; +import { runGigeContentionScenario } from "./scenarios/gige-wifi-contention"; +import { evaluateDiagnosticFindings } from "./analyzer/rule-engine"; +import { generateReportFiles, printTerminalSummary } from "./analyzer/report-generator"; +import { LatencyProbe } from "./probes/latency-probe"; +import { WsRpcProbe } from "./probes/ws-rpc-probe"; +import { PiKernelProbe } from "./probes/pi-kernel-probe"; + +async function main() { + const rawArgs = process.argv.slice(2); + const { command, config } = parseArgs(rawArgs); + + if (command === "help") { + printHelp(); + process.exit(0); + } + + console.log("================================================================================"); + console.log(" 📡 Speedcamera Network & Wi-Fi Hotspot Diagnostic Suite"); + console.log(` Target: ${config.target} | Web/WS: ${config.wsUrl}`); + console.log("================================================================================"); + + const ssh = new SshClient(config); + + // Setup graceful exit + process.on("SIGINT", async () => { + console.log("\n[!] Diagnostic interrupted. Cleaning up..."); + await ssh.close(); + process.exit(0); + }); + + try { + switch (command) { + case "quick": { + console.log("[*] Checking SSH connection to Pi..."); + const sshCheck = await ssh.checkConnection(); + if (!sshCheck.ok) { + console.warn(`[!] SSH check warning: ${sshCheck.error}`); + console.log("[*] Proceeding with network-only probes (WS/HTTP/Ping)..."); + } else { + console.log(`[+] SSH connection verified (latency: ${Math.round(sshCheck.latencyMs || 0)}ms)`); + } + + console.log(`[*] Running ${config.durationSec}s baseline telemetry scan...`); + const baseline = await runBaselineScenario(config, ssh, config.durationSec, (msg) => { + if (config.verbose) console.log(msg); + }); + + const analysis = evaluateDiagnosticFindings({ baseline }); + printTerminalSummary(config, analysis, { baseline }); + const { jsonPath, mdPath } = generateReportFiles(config, analysis, { baseline }); + console.log(`\n📄 Diagnostic Reports saved:`); + console.log(` • Markdown: ${mdPath}`); + console.log(` • JSON: ${jsonPath}`); + break; + } + + case "reproduce": { + console.log("[*] Running Freeze & Unclog Reproducer Scenario..."); + const freeze = await runFreezeReproducerScenario(config, ssh, (msg) => console.log(msg)); + const analysis = evaluateDiagnosticFindings({ freeze }); + printTerminalSummary(config, analysis, { freeze }); + generateReportFiles(config, analysis, { freeze }); + break; + } + + case "full": { + console.log("[*] Running Complete Multi-Scenario Diagnostic Suite..."); + console.log("--- 1/4: Baseline Telemetry ---"); + const baseline = await runBaselineScenario(config, ssh, 15, (msg) => { + if (config.verbose) console.log(msg); + }); + + console.log("--- 2/4: Freeze & Unclog Reproducer ---"); + const freeze = await runFreezeReproducerScenario(config, ssh, (msg) => console.log(msg)); + + console.log("--- 3/4: Storage Writeback Stress ---"); + const violation = await runViolationStressScenario(config, ssh, (msg) => console.log(msg)); + + console.log("--- 4/4: GigE vs Wi-Fi SoftIRQ Contention ---"); + const gige = await runGigeContentionScenario(config, ssh, (msg) => console.log(msg)); + + const analysis = evaluateDiagnosticFindings({ baseline, freeze, violation, gige }); + printTerminalSummary(config, analysis, { baseline, freeze, violation, gige }); + const { mdPath, jsonPath } = generateReportFiles(config, analysis, { baseline, freeze, violation, gige }); + console.log(`\n📄 Full Diagnostic Report saved to: ${mdPath}`); + break; + } + + case "monitor": { + await runLiveMonitor(config, ssh); + break; + } + + case "fix": { + await applyRemediations(config, ssh); + break; + } + + default: { + console.error(`Unknown command: ${command}`); + printHelp(); + process.exit(1); + } + } + } catch (err: any) { + console.error(`[!] Diagnostic Error:`, err); + } finally { + await ssh.close(); + } +} + +async function runLiveMonitor(config: any, ssh: SshClient) { + console.log("[*] Starting Real-Time Live Streaming Diagnostics Monitor (Press Ctrl+C to exit)..."); + console.log("--------------------------------------------------------------------------------"); + console.log(" Time | Ping RTT | WS RPC Avg/Max | Inactive | Signal | Dirty RAM | PowerSave"); + console.log("--------------------------------------------------------------------------------"); + + const latencyProbe = new LatencyProbe({ ...config, pingIntervalMs: 150 }); + const wsProbe = new WsRpcProbe({ ...config, rpcIntervalMs: 500 }); + const kernelProbe = new PiKernelProbe(config, ssh); + + latencyProbe.start(); + await wsProbe.start(); + kernelProbe.start(); + + while (true) { + await new Promise((r) => setTimeout(r, 1000)); + const lStats = latencyProbe.getStats(); + const wStats = wsProbe.getStats(); + const kernel = kernelProbe.getLatest(); + + const timeStr = new Date().toLocaleTimeString(); + const pingStr = lStats.avgRttMs > 0 ? `${lStats.avgRttMs}ms` : "loss"; + const wsStr = `${wStats.avgRpcRttMs}ms / ${wStats.maxRpcRttMs}ms`; + const inactiveStr = kernel ? `${kernel.wifi.inactive_time_ms}ms` : "N/A"; + const signalStr = kernel ? `${kernel.wifi.signal_dbm}dBm` : "N/A"; + const dirtyStr = kernel ? `${(kernel.memory.dirty_kb / 1024).toFixed(1)}MB` : "N/A"; + const psStr = kernel ? kernel.wifi.power_save : "N/A"; + + const pingPad = pingStr.padEnd(8); + const wsPad = wsStr.padEnd(14); + const inactPad = inactiveStr.padEnd(8); + const sigPad = signalStr.padEnd(6); + const dirtyPad = dirtyStr.padEnd(9); + + console.log(` ${timeStr} | ${pingPad} | ${wsPad} | ${inactPad} | ${sigPad} | ${dirtyPad} | ${psStr}`); + } +} + +async function applyRemediations(config: any, ssh: SshClient) { + console.log("[*] Applying verified kernel & Wi-Fi hotspot optimizations to Pi..."); + + const fixScript = ` + echo "=== 1. Disabling Wi-Fi Power Save on wlan0 ===" + sudo iw dev wlan0 set power_save off 2>/dev/null || sudo iwconfig wlan0 power off 2>/dev/null || true + sudo mkdir -p /etc/NetworkManager/conf.d + sudo bash -c 'cat > /etc/NetworkManager/conf.d/default-wifi-powersave-off.conf < /etc/ssh/sshd_config.d/99-speedcamera-keepalive.conf </dev/null || sudo systemctl reload sshd 2>/dev/null || true + + echo "=== 3. Tuning Sysctl Network Buffers for Wi-Fi + GigE (with fq_codel) ===" + sudo bash -c 'cat > /etc/sysctl.d/60-speedcamera-optimized.conf </dev/null || sudo sysctl --system + + echo "=== 4. Optimizing NetworkManager Hotspot Connection (5GHz Band A, Ch 36, No MAC Rand) ===" + sudo nmcli connection modify "Speedcamera-Hotspot" 802-11-wireless.powersave 2 802-11-wireless.band a 802-11-wireless.channel 36 802-11-wireless.mac-address-randomization 1 ipv4.never-default yes 2>/dev/null || true + + echo "=== 5. Locking Down Wi-Fi Power Management Permanently ===" + sudo bash -c 'cat > /etc/systemd/system/wifi-power-off.service </dev/null || true + sudo systemctl enable --now wifi-power-off.service 2>/dev/null || true + + echo "=== Optimization Complete! ===" + `; + + const res = await ssh.execScript(fixScript, 10000); + console.log(res.stdout); + if (res.exitCode === 0) { + console.log("[+] All optimizations successfully applied to the Pi!"); + } else { + console.error(`[!] Error applying optimizations: ${res.stderr}`); + } +} + +function printHelp() { + console.log(` +Usage: bun ./diagnostics/cli.ts [command] [options] + +Commands: + quick Run fast 20s baseline check and root-cause analysis (default) + monitor Run live real-time streaming telemetry dashboard + reproduce Test Wi-Fi idle freeze and keystroke unclogging response + full Run complete suite of all 4 test scenarios and generate report + fix Apply verified kernel and Wi-Fi optimizations to the Pi via SSH + help Show this help message + +Options: + --target, -t SSH & network target (default: pi@192.168.4.1) + --port, -p Web/WebSocket port (default: 3000) + --ssh-port SSH port (default: 22) + --password, --pass SSH password if not using SSH keys + --duration, -d Test duration in seconds (default: 20) + --output, -o Output directory for reports (default: ./diagnostics-output) + --verbose, -v Print verbose logs during execution +`); +} + +main().catch(console.error); diff --git a/headless-rust/diagnostics/config.ts b/headless-rust/diagnostics/config.ts new file mode 100644 index 0000000..6979e09 --- /dev/null +++ b/headless-rust/diagnostics/config.ts @@ -0,0 +1,122 @@ +/** + * Speedcamera Diagnostics Configuration & CLI Arg Parser + */ + +export interface DiagConfig { + target: string; // e.g. "pi@192.168.4.1" or "192.168.4.1" + host: string; // e.g. "192.168.4.1" + user: string; // e.g. "pi" + port: number; // Web/WS port, default 3000 + sshPort: number;// SSH port, default 22 + password?: string; + usePasswordAuth: boolean; + wsUrl: string; + httpUrl: string; + durationSec: number; + pingIntervalMs: number; + rpcIntervalMs: number; + kernelProbeIntervalMs: number; + outputDir: string; + verbose: boolean; +} + +export function parseArgs(args: string[]): { command: string; config: DiagConfig } { + let command = "quick"; + let target = "pi@192.168.4.1"; + let port = 3000; + let sshPort = 22; + let password: string | undefined = undefined; + let usePasswordAuth = false; + let durationSec = 20; + let pingIntervalMs = 100; + let rpcIntervalMs = 500; + let kernelProbeIntervalMs = 1000; + let outputDir = "./diagnostics-output"; + let verbose = false; + + let i = 0; + while (i < args.length) { + const arg = args[i]; + if (arg === "quick" || arg === "monitor" || arg === "reproduce" || arg === "full" || arg === "baseline" || arg === "stress" || arg === "fix" || arg === "help") { + command = arg; + i++; + continue; + } + + if (arg === "--target" || arg === "-t") { + target = args[i + 1] || target; + i += 2; + } else if (arg === "--port" || arg === "-p") { + port = parseInt(args[i + 1], 10) || port; + i += 2; + } else if (arg === "--ssh-port") { + sshPort = parseInt(args[i + 1], 10) || sshPort; + i += 2; + } else if (arg === "--password" || arg === "--pass") { + usePasswordAuth = true; + if (args[i + 1] && !args[i + 1].startsWith("-")) { + password = args[i + 1]; + i += 2; + } else { + i++; + } + } else if (arg === "--duration" || arg === "-d") { + durationSec = parseInt(args[i + 1], 10) || durationSec; + i += 2; + } else if (arg === "--ping-interval") { + pingIntervalMs = parseInt(args[i + 1], 10) || pingIntervalMs; + i += 2; + } else if (arg === "--rpc-interval") { + rpcIntervalMs = parseInt(args[i + 1], 10) || rpcIntervalMs; + i += 2; + } else if (arg === "--output" || arg === "-o") { + outputDir = args[i + 1] || outputDir; + i += 2; + } else if (arg === "--verbose" || arg === "-v") { + verbose = true; + i++; + } else if (arg === "--help" || arg === "-h") { + command = "help"; + i++; + } else { + // Positional target if not a flag + if (!arg.startsWith("-")) { + target = arg; + } + i++; + } + } + + // Parse user and host from target + let user = "pi"; + let host = target; + if (target.includes("@")) { + const parts = target.split("@"); + user = parts[0]; + host = parts[1]; + } + + const wsUrl = `ws://${host}:${port}/ws/rpc`; + const httpUrl = `http://${host}:${port}`; + + return { + command, + config: { + target, + host, + user, + port, + sshPort, + password, + usePasswordAuth, + wsUrl, + httpUrl, + durationSec, + pingIntervalMs, + rpcIntervalMs, + kernelProbeIntervalMs, + outputDir, + verbose, + }, + }; +} diff --git a/headless-rust/diagnostics/pi-probe.sh b/headless-rust/diagnostics/pi-probe.sh new file mode 100755 index 0000000..39fe687 --- /dev/null +++ b/headless-rust/diagnostics/pi-probe.sh @@ -0,0 +1,143 @@ +#!/usr/bin/env bash +# ============================================================================== +# Speedcamera Pi-Side Hardware, Kernel, Wi-Fi & Socket Diagnostics Probe +# Outputs a single structured JSON payload on stdout. +# ============================================================================== + +set -o pipefail 2>/dev/null || true + +TIMESTAMP=$(date +%s%3N 2>/dev/null || date +%s) +WIFI_IFACE=$(ip -o link show | awk -F': ' '{print $2}' | grep -E '^(wlan|wifi|wlp)' | head -n 1 || echo "wlan0") +ETH_IFACE=$(ip -o link show | awk -F': ' '{print $2}' | grep -E '^(eth|end|enp)' | head -n 1 || echo "eth0") + +# --- 1. Wi-Fi Power Save & Station Link Status --- +WIFI_POWER_SAVE="unknown" +if command -v iw &>/dev/null; then + WIFI_POWER_SAVE=$(iw dev "${WIFI_IFACE}" get power_save 2>/dev/null | awk '{print $NF}' || echo "unknown") +elif command -v iwconfig &>/dev/null; then + WIFI_POWER_SAVE=$(iwconfig "${WIFI_IFACE}" 2>/dev/null | grep -i "power management" | awk -F':' '{print $2}' | tr -d ' ' || echo "unknown") +fi + +STATION_DUMP_RAW="" +if command -v iw &>/dev/null; then + STATION_DUMP_RAW=$(iw dev "${WIFI_IFACE}" station dump 2>/dev/null || true) +fi + +CLIENT_MAC=$(echo "$STATION_DUMP_RAW" | grep -i "^Station" | head -n 1 | awk '{print $2}' || echo "") +INACTIVE_TIME_MS=$(echo "$STATION_DUMP_RAW" | grep -i "inactive time" | head -n 1 | awk '{print $3}' || echo "0") +SIGNAL_DBM=$(echo "$STATION_DUMP_RAW" | grep -i "signal:" | head -n 1 | awk '{print $2}' || echo "0") +TX_RETRIES=$(echo "$STATION_DUMP_RAW" | grep -i "tx retries:" | head -n 1 | awk '{print $3}' || echo "0") +TX_FAILED=$(echo "$STATION_DUMP_RAW" | grep -i "tx failed:" | head -n 1 | awk '{print $3}' || echo "0") +TX_BITRATE=$(echo "$STATION_DUMP_RAW" | grep -i "tx bitrate:" | head -n 1 | sed 's/.*tx bitrate:[ \t]*//' | tr -d '"' || echo "unknown") +RX_BITRATE=$(echo "$STATION_DUMP_RAW" | grep -i "rx bitrate:" | head -n 1 | sed 's/.*rx bitrate:[ \t]*//' | tr -d '"' || echo "unknown") +AUTHORIZED=$(echo "$STATION_DUMP_RAW" | grep -i "authorized:" | head -n 1 | awk '{print $2}' || echo "unknown") +AUTHENTICATED=$(echo "$STATION_DUMP_RAW" | grep -i "authenticated:" | head -n 1 | awk '{print $2}' || echo "unknown") + +# --- 2. TCP Sockets & Queues --- +TCP_SOCKETS="[]" +if command -v ss &>/dev/null; then + # Grab sockets on web port 3000 and ssh port 22 + TCP_SOCKETS=$(ss -t -i -a -n 2>/dev/null | awk ' + BEGIN { printf "[" ; first=1 } + /ESTAB/ || /LISTEN/ { + state=$1; recvq=$2; sendq=$3; local=$4; peer=$5; + getline info; + if (!first) { printf "," } + first=0; + gsub(/"/, "\\\"", info); + printf "{\"state\":\"%s\",\"recv_q\":%s,\"send_q\":%s,\"local\":\"%s\",\"peer\":\"%s\",\"info\":\"%s\"}", state, recvq, sendq, local, peer, info; + } + END { printf "]" } + ' || echo "[]") +fi + +# --- 3. Kernel Sysctl Parameters --- +RMEM_DEFAULT=$(cat /proc/sys/net/core/rmem_default 2>/dev/null || echo "0") +WMEM_DEFAULT=$(cat /proc/sys/net/core/wmem_default 2>/dev/null || echo "0") +RMEM_MAX=$(cat /proc/sys/net/core/rmem_max 2>/dev/null || echo "0") +WMEM_MAX=$(cat /proc/sys/net/core/wmem_max 2>/dev/null || echo "0") +TCP_CONGESTION=$(cat /proc/sys/net/ipv4/tcp_congestion_control 2>/dev/null || echo "unknown") +NETDEV_MAX_BACKLOG=$(cat /proc/sys/net/core/netdev_max_backlog 2>/dev/null || echo "0") + +# --- 4. Memory & Storage Dirty Page Writeback --- +MEM_DIRTY_KB=$(grep -i "^Dirty:" /proc/meminfo 2>/dev/null | awk '{print $2}' || echo "0") +MEM_WRITEBACK_KB=$(grep -i "^Writeback:" /proc/meminfo 2>/dev/null | awk '{print $2}' || echo "0") +MEM_AVAILABLE_KB=$(grep -i "^MemAvailable:" /proc/meminfo 2>/dev/null | awk '{print $2}' || echo "0") +MEM_TOTAL_KB=$(grep -i "^MemTotal:" /proc/meminfo 2>/dev/null | awk '{print $2}' || echo "0") + +# D-state (Uninterruptible disk sleep processes) +D_STATE_COUNT=$(ps -eo state 2>/dev/null | grep -c "D" || echo "0") + +# --- 5. SoftIRQs & CPU Interrupt Distribution --- +NET_RX_SOFTIRQS="[]" +if [ -f /proc/softirqs ]; then + NET_RX_SOFTIRQS=$(grep "NET_RX:" /proc/softirqs | awk '{printf "["; for(i=2;i<=NF;i++){printf "%s%s", $i, (i/dev/null; then + THROTTLED_HEX=$(vcgencmd get_throttled 2>/dev/null | awk -F'=' '{print $2}' || echo "0x0") + TEMP_C=$(vcgencmd measure_temp 2>/dev/null | sed -e 's/temp=//' -e "s/'C//" || echo "0") + ARM_FREQ_MHZ=$(vcgencmd measure_clock arm 2>/dev/null | awk -F'=' '{print int($2/1000000)}' || echo "0") +fi + +# --- 7. Speedcamera Service Status --- +SPEEDCAMERA_PID=$(pgrep -f "speedcamera" 2>/dev/null | head -n 1 || echo "0") +SPEEDCAMERA_CPU=$(ps -p "$SPEEDCAMERA_PID" -o %cpu= 2>/dev/null | tr -d ' ' || echo "0") +SPEEDCAMERA_MEM_KB=$(ps -p "$SPEEDCAMERA_PID" -o rss= 2>/dev/null | tr -d ' ' || echo "0") + +# --- 8. Recent Kernel dmesg warnings related to Wi-Fi / brcmfmac --- +DMESG_SNIPPET=$(dmesg 2>/dev/null | grep -iE 'brcm|wlan|wifi|timeout|drop|failed' | tail -n 5 | sed 's/"/\\"/g' | tr '\n' ';' || echo "") + +# --- Construct Final JSON --- +cat < { + const url = `${this.config.httpUrl}${path}`; + const start = performance.now(); + const timestamp = Date.now(); + + try { + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), 4000); + + const res = await fetch(url, { signal: controller.signal }); + const ttfb = performance.now() - start; + await res.text(); + const total = performance.now() - start; + clearTimeout(timeout); + + const sample: HttpSample = { + url, + status: res.status, + ttfbMs: Math.round(ttfb * 10) / 10, + totalMs: Math.round(total * 10) / 10, + timestamp, + }; + this.samples.push(sample); + return sample; + } catch (err: any) { + const sample: HttpSample = { + url, + status: null, + ttfbMs: null, + totalMs: null, + error: err.name === "AbortError" ? "Timed out (4000ms)" : err.message, + timestamp, + }; + this.samples.push(sample); + return sample; + } + } + + public start(intervalMs = 2000) { + if (this.isRunning) return; + this.isRunning = true; + this.samples = []; + + const poll = async () => { + if (!this.isRunning) return; + await this.measureEndpoint("/"); + if (this.isRunning) { + this.timer = setTimeout(poll, intervalMs); + } + }; + + poll(); + } + + public stop() { + this.isRunning = false; + if (this.timer) { + clearTimeout(this.timer); + this.timer = null; + } + } + + public getStats(): HttpStats { + const totalRequests = this.samples.length; + const successful = this.samples.filter((s) => s.status !== null && s.status >= 200 && s.status < 400); + const failedRequests = totalRequests - successful.length; + + const ttfbs = successful.map((s) => s.ttfbMs!).filter((t) => t !== null); + const avgTtfbMs = ttfbs.length > 0 ? ttfbs.reduce((a, b) => a + b, 0) / ttfbs.length : 0; + const maxTtfbMs = ttfbs.length > 0 ? Math.max(...ttfbs) : 0; + const minTtfbMs = ttfbs.length > 0 ? Math.min(...ttfbs) : 0; + + return { + totalRequests, + successfulRequests: successful.length, + failedRequests, + avgTtfbMs: Math.round(avgTtfbMs * 10) / 10, + maxTtfbMs: Math.round(maxTtfbMs * 10) / 10, + minTtfbMs: Math.round(minTtfbMs * 10) / 10, + }; + } + + public getSamples(): HttpSample[] { + return [...this.samples]; + } +} diff --git a/headless-rust/diagnostics/probes/latency-probe.ts b/headless-rust/diagnostics/probes/latency-probe.ts new file mode 100644 index 0000000..a52669d --- /dev/null +++ b/headless-rust/diagnostics/probes/latency-probe.ts @@ -0,0 +1,179 @@ +import { spawn } from "node:child_process"; +import type { DiagConfig } from "../config"; + +export interface LatencySample { + timestamp: number; + rttMs: number | null; // null if lost / timeout + seq: number; +} + +export interface LatencyStats { + samplesCount: number; + transmitted: number; + received: number; + lossPercent: number; + minRttMs: number; + maxRttMs: number; + avgRttMs: number; + jitterMs: number; + stallCount: number; // Count of samples with RTT > 300ms or dropped + longestStallDurationMs: number; +} + +export class LatencyProbe { + private config: DiagConfig; + private isRunning = false; + private samples: LatencySample[] = []; + private seqCounter = 0; + private timer: NodeJS.Timeout | null = null; + private onSampleCallback?: (sample: LatencySample) => void; + + constructor(config: DiagConfig) { + this.config = config; + } + + public onSample(cb: (sample: LatencySample) => void) { + this.onSampleCallback = cb; + } + + public start() { + if (this.isRunning) return; + this.isRunning = true; + this.samples = []; + this.seqCounter = 0; + + const interval = Math.max(50, this.config.pingIntervalMs); + + const pingNext = async () => { + if (!this.isRunning) return; + const seq = ++this.seqCounter; + const sample = await this.measureSinglePing(seq); + this.samples.push(sample); + if (this.onSampleCallback) { + this.onSampleCallback(sample); + } + if (this.isRunning) { + this.timer = setTimeout(pingNext, interval); + } + }; + + pingNext(); + } + + public stop() { + this.isRunning = false; + if (this.timer) { + clearTimeout(this.timer); + this.timer = null; + } + } + + public getSamples(): LatencySample[] { + return [...this.samples]; + } + + public getStats(): LatencyStats { + const transmitted = this.samples.length; + const receivedSamples = this.samples.filter((s) => s.rttMs !== null); + const received = receivedSamples.length; + const lossPercent = transmitted > 0 ? ((transmitted - received) / transmitted) * 100 : 0; + + if (received === 0) { + return { + samplesCount: transmitted, + transmitted, + received: 0, + lossPercent: 100, + minRttMs: 0, + maxRttMs: 0, + avgRttMs: 0, + jitterMs: 0, + stallCount: transmitted, + longestStallDurationMs: transmitted * this.config.pingIntervalMs, + }; + } + + const rtts = receivedSamples.map((s) => s.rttMs!); + const minRttMs = Math.min(...rtts); + const maxRttMs = Math.max(...rtts); + const avgRttMs = rtts.reduce((a, b) => a + b, 0) / rtts.length; + + // Calculate jitter (mean deviation between consecutive packets) + let jitterSum = 0; + let jitterPairs = 0; + for (let i = 1; i < receivedSamples.length; i++) { + jitterSum += Math.abs(receivedSamples[i].rttMs! - receivedSamples[i - 1].rttMs!); + jitterPairs++; + } + const jitterMs = jitterPairs > 0 ? jitterSum / jitterPairs : 0; + + // Detect stall episodes (>250ms or loss) + let stallCount = 0; + let maxStallMs = 0; + let currentStallMs = 0; + + for (const sample of this.samples) { + if (sample.rttMs === null || sample.rttMs > 250) { + stallCount++; + currentStallMs += (sample.rttMs ?? this.config.pingIntervalMs); + if (currentStallMs > maxStallMs) maxStallMs = currentStallMs; + } else { + currentStallMs = 0; + } + } + + return { + samplesCount: transmitted, + transmitted, + received, + lossPercent, + minRttMs: Math.round(minRttMs * 100) / 100, + maxRttMs: Math.round(maxRttMs * 100) / 100, + avgRttMs: Math.round(avgRttMs * 100) / 100, + jitterMs: Math.round(jitterMs * 100) / 100, + stallCount, + longestStallDurationMs: Math.round(maxStallMs), + }; + } + + private measureSinglePing(seq: number): Promise { + return new Promise((resolve) => { + const start = performance.now(); + const child = spawn("ping", ["-c", "1", "-W", "1", this.config.host], { + stdio: ["ignore", "pipe", "pipe"], + }); + + let stdout = ""; + const timer = setTimeout(() => { + child.kill("SIGKILL"); + resolve({ timestamp: Date.now(), rttMs: null, seq }); + }, 1200); + + child.stdout.on("data", (chunk) => { + stdout += chunk.toString(); + }); + + child.on("close", (code) => { + clearTimeout(timer); + if (code === 0) { + // Parse time=X.XX ms + const match = stdout.match(/time=([0-9.]+)\s*ms/); + if (match) { + const rtt = parseFloat(match[1]); + resolve({ timestamp: Date.now(), rttMs: rtt, seq }); + return; + } + const fallbackRtt = performance.now() - start; + resolve({ timestamp: Date.now(), rttMs: fallbackRtt, seq }); + } else { + resolve({ timestamp: Date.now(), rttMs: null, seq }); + } + }); + + child.on("error", () => { + clearTimeout(timer); + resolve({ timestamp: Date.now(), rttMs: null, seq }); + }); + }); + } +} diff --git a/headless-rust/diagnostics/probes/pi-kernel-probe.ts b/headless-rust/diagnostics/probes/pi-kernel-probe.ts new file mode 100644 index 0000000..71e10d4 --- /dev/null +++ b/headless-rust/diagnostics/probes/pi-kernel-probe.ts @@ -0,0 +1,144 @@ +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import type { DiagConfig } from "../config"; +import type { SshClient } from "../ssh-client"; + +export interface PiKernelSnapshot { + timestamp: number; + wifi: { + interface: string; + power_save: string; + client_mac: string; + inactive_time_ms: number; + signal_dbm: number; + tx_retries: number; + tx_failed: number; + tx_bitrate: string; + rx_bitrate: string; + authorized: string; + authenticated: string; + }; + sysctl: { + rmem_default: number; + wmem_default: number; + rmem_max: number; + wmem_max: number; + tcp_congestion_control: string; + netdev_max_backlog: number; + }; + memory: { + dirty_kb: number; + writeback_kb: number; + available_kb: number; + total_kb: number; + d_state_processes: number; + }; + hardware: { + temp_c: string; + throttled_hex: string; + arm_freq_mhz: number; + }; + softirqs: { + net_rx_per_cpu: number[]; + }; + service: { + pid: number; + cpu_percent: string; + rss_kb: number; + }; + tcp_sockets: Array<{ + state: string; + recv_q: number; + send_q: number; + local: string; + peer: string; + info: string; + }>; + dmesg_snippet: string; +} + +export class PiKernelProbe { + private config: DiagConfig; + private ssh: SshClient; + private scriptContent: string; + private isRunning = false; + private snapshots: PiKernelSnapshot[] = []; + private timer: NodeJS.Timeout | null = null; + private onSnapshotCallback?: (snapshot: PiKernelSnapshot) => void; + + constructor(config: DiagConfig, ssh: SshClient) { + this.config = config; + this.ssh = ssh; + try { + this.scriptContent = readFileSync(join(__dirname, "../pi-probe.sh"), "utf-8"); + } catch (_) { + this.scriptContent = ""; + } + } + + public onSnapshot(cb: (snapshot: PiKernelSnapshot) => void) { + this.onSnapshotCallback = cb; + } + + public async fetchSingleSnapshot(): Promise { + if (!this.scriptContent) { + try { + this.scriptContent = readFileSync(join(__dirname, "../pi-probe.sh"), "utf-8"); + } catch (_) {} + } + + const res = await this.ssh.execScript(this.scriptContent, 4000); + if (res.exitCode === 0 && res.stdout) { + try { + const trimmed = res.stdout.trim(); + const firstBrace = trimmed.indexOf("{"); + const lastBrace = trimmed.lastIndexOf("}"); + if (firstBrace !== -1 && lastBrace !== -1 && lastBrace > firstBrace) { + const jsonStr = trimmed.substring(firstBrace, lastBrace + 1); + return JSON.parse(jsonStr) as PiKernelSnapshot; + } + } catch (_) {} + } + return null; + } + + public start() { + if (this.isRunning) return; + this.isRunning = true; + this.snapshots = []; + + const interval = Math.max(500, this.config.kernelProbeIntervalMs); + + const pollNext = async () => { + if (!this.isRunning) return; + const snapshot = await this.fetchSingleSnapshot(); + if (snapshot) { + this.snapshots.push(snapshot); + if (this.onSnapshotCallback) { + this.onSnapshotCallback(snapshot); + } + } + if (this.isRunning) { + this.timer = setTimeout(pollNext, interval); + } + }; + + pollNext(); + } + + public stop() { + this.isRunning = false; + if (this.timer) { + clearTimeout(this.timer); + this.timer = null; + } + } + + public getSnapshots(): PiKernelSnapshot[] { + return [...this.snapshots]; + } + + public getLatest(): PiKernelSnapshot | null { + return this.snapshots.length > 0 ? this.snapshots[this.snapshots.length - 1] : null; + } +} diff --git a/headless-rust/diagnostics/probes/ws-rpc-probe.ts b/headless-rust/diagnostics/probes/ws-rpc-probe.ts new file mode 100644 index 0000000..ec77640 --- /dev/null +++ b/headless-rust/diagnostics/probes/ws-rpc-probe.ts @@ -0,0 +1,255 @@ +import type { DiagConfig } from "../config"; +import { io, Socket } from "socket.io-client"; + +export interface RpcCallRecord { + id: number; + method: string; + sentAt: number; + receivedAt?: number; + rttMs?: number; + timedOut: boolean; + error?: string; +} + +export interface PushEventRecord { + event: string; + timestamp: number; + deltaFromPrevMs: number; + isBurst: boolean; // true if arrived in a clustered burst after a stall +} + +export interface WsRpcStats { + connected: boolean; + connectAttempts: number; + disconnects: number; + totalCalls: number; + successfulCalls: number; + timedOutCalls: number; + avgRpcRttMs: number; + maxRpcRttMs: number; + minRpcRttMs: number; + pushEventsCount: number; + burstEventsCount: number; // Events arriving in rapid bursts (>3 events in <50ms after >1.5s silence) + eventBreakdown: Record; +} + +export class WsRpcProbe { + private config: DiagConfig; + private socket: Socket | null = null; + private isRunning = false; + private reqIdCounter = 1000; + private completedCalls: RpcCallRecord[] = []; + private pushEvents: PushEventRecord[] = []; + private lastPushTimestamp = 0; + private connectAttempts = 0; + private disconnects = 0; + private loopTimer: NodeJS.Timeout | null = null; + private onUpdateCallback?: () => void; + + constructor(config: DiagConfig) { + this.config = config; + } + + public onUpdate(cb: () => void) { + this.onUpdateCallback = cb; + } + + public async start(): Promise { + if (this.isRunning) return true; + this.isRunning = true; + this.completedCalls = []; + this.pushEvents = []; + this.lastPushTimestamp = Date.now(); + + const connected = await this.connect(); + + // Start periodic RPC call loop + const interval = Math.max(200, this.config.rpcIntervalMs); + const rpcMethods = ["getSettings", "getCameraStatus", "getViolations"]; + let methodIdx = 0; + + const rpcLoop = async () => { + if (!this.isRunning) return; + if (this.socket && this.socket.connected) { + const method = rpcMethods[methodIdx % rpcMethods.length]; + methodIdx++; + const params = method === "getViolations" ? { page: 1, limit: 5 } : {}; + this.sendRpc(method, params); + } + if (this.isRunning) { + this.loopTimer = setTimeout(rpcLoop, interval); + } + }; + + rpcLoop(); + return connected; + } + + public stop() { + this.isRunning = false; + if (this.loopTimer) { + clearTimeout(this.loopTimer); + this.loopTimer = null; + } + + if (this.socket) { + try { + this.socket.disconnect(); + } catch (_) {} + this.socket = null; + } + } + + public getStats(): WsRpcStats { + const totalCalls = this.completedCalls.length; + const successfulCalls = this.completedCalls.filter((c) => !c.timedOut && !c.error).length; + const timedOutCalls = this.completedCalls.filter((c) => c.timedOut).length; + + const successfulRtts = this.completedCalls + .filter((c) => c.rttMs !== undefined && !c.timedOut && !c.error) + .map((c) => c.rttMs!); + + const avgRpcRttMs = successfulRtts.length > 0 ? successfulRtts.reduce((a, b) => a + b, 0) / successfulRtts.length : 0; + const maxRpcRttMs = successfulRtts.length > 0 ? Math.max(...successfulRtts) : 0; + const minRpcRttMs = successfulRtts.length > 0 ? Math.min(...successfulRtts) : 0; + + const eventBreakdown: Record = {}; + for (const evt of this.pushEvents) { + eventBreakdown[evt.event] = (eventBreakdown[evt.event] || 0) + 1; + } + + const burstEventsCount = this.pushEvents.filter((e) => e.isBurst).length; + + return { + connected: this.socket !== null && this.socket.connected, + connectAttempts: this.connectAttempts, + disconnects: this.disconnects, + totalCalls, + successfulCalls, + timedOutCalls, + avgRpcRttMs: Math.round(avgRpcRttMs * 10) / 10, + maxRpcRttMs: Math.round(maxRpcRttMs * 10) / 10, + minRpcRttMs: Math.round(minRpcRttMs * 10) / 10, + pushEventsCount: this.pushEvents.length, + burstEventsCount, + eventBreakdown, + }; + } + + public getCompletedCalls(): RpcCallRecord[] { + return [...this.completedCalls]; + } + + public getPushEvents(): PushEventRecord[] { + return [...this.pushEvents]; + } + + private connect(): Promise { + return new Promise((resolve) => { + this.connectAttempts++; + try { + const socket = io(this.config.httpUrl, { + transports: ["websocket", "polling"], + reconnection: true, + reconnectionAttempts: Infinity, + reconnectionDelay: 1000, + timeout: 4000, + }); + this.socket = socket; + + let resolved = false; + const connectTimer = setTimeout(() => { + if (!resolved) { + resolved = true; + resolve(false); + } + }, 4000); + + socket.on("connect", () => { + if (!resolved) { + resolved = true; + clearTimeout(connectTimer); + resolve(true); + } + if (this.onUpdateCallback) this.onUpdateCallback(); + }); + + const recordPush = (event: string) => { + const now = Date.now(); + const delta = this.lastPushTimestamp > 0 ? now - this.lastPushTimestamp : 0; + const isBurst = delta < 40 && this.pushEvents.length > 0 && (this.pushEvents[this.pushEvents.length - 1].deltaFromPrevMs > 1500); + + this.pushEvents.push({ + event, + timestamp: now, + deltaFromPrevMs: delta, + isBurst, + }); + this.lastPushTimestamp = now; + if (this.onUpdateCallback) this.onUpdateCallback(); + }; + + socket.on("cameraStatus", () => recordPush("cameraStatus")); + socket.on("serialStatus", () => recordPush("serialStatus")); + socket.on("liveFrame", () => recordPush("liveFrame")); + socket.on("violation", () => recordPush("violation")); + socket.on("flashProgress", () => recordPush("flashProgress")); + socket.on("armedStatus", () => recordPush("armedStatus")); + + socket.on("connect_error", () => { + if (!resolved) { + resolved = true; + clearTimeout(connectTimer); + resolve(false); + } + }); + + socket.on("disconnect", () => { + this.disconnects++; + if (this.onUpdateCallback) this.onUpdateCallback(); + }); + } catch (_) { + resolve(false); + } + }); + } + + private async sendRpc(method: string, params: any) { + const id = ++this.reqIdCounter; + const now = Date.now(); + + const record: RpcCallRecord = { + id, + method, + sentAt: now, + timedOut: false, + }; + + if (!this.socket || !this.socket.connected) { + record.error = "Not connected"; + this.completedCalls.push(record); + if (this.onUpdateCallback) this.onUpdateCallback(); + return; + } + + try { + const resp: any = await this.socket.timeout(5000).emitWithAck("rpc", { method, params }); + const recAt = Date.now(); + record.receivedAt = recAt; + record.rttMs = Math.max(0, recAt - now); + if (resp && resp.error) { + record.error = resp.error; + } + } catch (err: any) { + if (err?.name === "TimeoutError" || err?.message?.includes("timeout")) { + record.timedOut = true; + record.rttMs = 5000; + } else { + record.error = err.message; + } + } + + this.completedCalls.push(record); + if (this.onUpdateCallback) this.onUpdateCallback(); + } +} diff --git a/headless-rust/diagnostics/scenarios/baseline.ts b/headless-rust/diagnostics/scenarios/baseline.ts new file mode 100644 index 0000000..d352a61 --- /dev/null +++ b/headless-rust/diagnostics/scenarios/baseline.ts @@ -0,0 +1,104 @@ +import type { DiagConfig } from "../config"; +import type { SshClient } from "../ssh-client"; +import { LatencyProbe, type LatencyStats } from "../probes/latency-probe"; +import { WsRpcProbe, type WsRpcStats } from "../probes/ws-rpc-probe"; +import { PiKernelProbe, type PiKernelSnapshot } from "../probes/pi-kernel-probe"; +import { HttpProbe, type HttpStats } from "../probes/http-probe"; + +export interface ScenarioResult { + scenarioName: string; + durationSec: number; + latencyStats: LatencyStats; + wsStats: WsRpcStats; + httpStats: HttpStats; + kernelSnapshots: PiKernelSnapshot[]; + anomaliesDetected: string[]; +} + +export async function runBaselineScenario( + config: DiagConfig, + ssh: SshClient, + durationSec = config.durationSec, + onProgress?: (status: string) => void +): Promise { + const log = (msg: string) => { + if (onProgress) onProgress(msg); + }; + + log(`[baseline] Starting ${durationSec}s baseline stability test against ${config.host}...`); + + const latencyProbe = new LatencyProbe(config); + const wsProbe = new WsRpcProbe(config); + const kernelProbe = new PiKernelProbe(config, ssh); + const httpProbe = new HttpProbe(config); + + latencyProbe.start(); + await wsProbe.start(); + kernelProbe.start(); + httpProbe.start(3000); + + // Monitor progress + const startTime = Date.now(); + const endTime = startTime + durationSec * 1000; + + while (Date.now() < endTime) { + const elapsed = Math.round((Date.now() - startTime) / 1000); + const remaining = Math.max(0, durationSec - elapsed); + const lStats = latencyProbe.getStats(); + const wStats = wsProbe.getStats(); + log(`[baseline] ${elapsed}s / ${durationSec}s | Ping: ${lStats.avgRttMs}ms (max: ${lStats.maxRttMs}ms, loss: ${lStats.lossPercent.toFixed(1)}%) | WS RPCs: ${wStats.successfulCalls}/${wStats.totalCalls} (avg: ${wStats.avgRpcRttMs}ms)`); + await new Promise((r) => setTimeout(r, 2000)); + } + + latencyProbe.stop(); + wsProbe.stop(); + kernelProbe.stop(); + httpProbe.stop(); + + const latencyStats = latencyProbe.getStats(); + const wsStats = wsProbe.getStats(); + const httpStats = httpProbe.getStats(); + const kernelSnapshots = kernelProbe.getSnapshots(); + + // Detect basic anomalies + const anomaliesDetected: string[] = []; + if (latencyStats.lossPercent > 5) { + anomaliesDetected.push(`High ICMP packet loss: ${latencyStats.lossPercent.toFixed(1)}%`); + } + if (latencyStats.maxRttMs > 300) { + anomaliesDetected.push(`Severe ping latency spikes detected (max ${latencyStats.maxRttMs}ms)`); + } + if (wsStats.timedOutCalls > 0) { + anomaliesDetected.push(`WebSocket RPC timeouts observed: ${wsStats.timedOutCalls} timed out calls`); + } + if (wsStats.burstEventsCount > 0) { + anomaliesDetected.push(`Clustered event bursts detected (${wsStats.burstEventsCount} events delivered in burst after silence)`); + } + + // Check kernel snapshots + const latestKernel = kernelSnapshots.length > 0 ? kernelSnapshots[kernelSnapshots.length - 1] : null; + if (latestKernel) { + if (latestKernel.wifi.power_save.toLowerCase() === "on") { + anomaliesDetected.push(`Pi Wi-Fi power save is ENABLED on ${latestKernel.wifi.interface}`); + } + if (latestKernel.wifi.inactive_time_ms > 2000) { + anomaliesDetected.push(`Wi-Fi station inactive time is high (${latestKernel.wifi.inactive_time_ms}ms)`); + } + if (latestKernel.sysctl.rmem_default > 10485760 || latestKernel.sysctl.wmem_default > 10485760) { + anomaliesDetected.push(`Kernel socket buffer defaults are excessively high (rmem_default: ${(latestKernel.sysctl.rmem_default / 1024 / 1024).toFixed(1)}MB, wmem_default: ${(latestKernel.sysctl.wmem_default / 1024 / 1024).toFixed(1)}MB)`); + } + if (latestKernel.memory.dirty_kb > 50000) { + anomaliesDetected.push(`High dirty page memory: ${(latestKernel.memory.dirty_kb / 1024).toFixed(1)}MB`); + } + } + + return { + scenarioName: "Baseline Network Stability", + durationSec, + latencyStats, + wsStats, + httpStats, + kernelSnapshots, + anomaliesDetected, + }; +} diff --git a/headless-rust/diagnostics/scenarios/freeze-reproducer.ts b/headless-rust/diagnostics/scenarios/freeze-reproducer.ts new file mode 100644 index 0000000..b1b3cf7 --- /dev/null +++ b/headless-rust/diagnostics/scenarios/freeze-reproducer.ts @@ -0,0 +1,125 @@ +import type { DiagConfig } from "../config"; +import type { SshClient } from "../ssh-client"; +import { LatencyProbe } from "../probes/latency-probe"; +import { WsRpcProbe } from "../probes/ws-rpc-probe"; +import { PiKernelProbe } from "../probes/pi-kernel-probe"; +import type { ScenarioResult } from "./baseline"; +import { HttpProbe } from "../probes/http-probe"; + +export interface FreezeReproducerResult extends ScenarioResult { + idleFreezeObserved: boolean; + unclogTriggerSuccess: boolean; + unclogRecoveryTimeMs: number; + preBurstMaxLatencyMs: number; + postBurstAvgLatencyMs: number; + wifiPowerSaveActive: boolean; +} + +export async function runFreezeReproducerScenario( + config: DiagConfig, + ssh: SshClient, + onProgress?: (status: string) => void +): Promise { + const log = (msg: string) => { + if (onProgress) onProgress(msg); + }; + + log("[freeze-reproducer] Initializing Wi-Fi Hotspot Freeze & Unclog Reproducer..."); + + const latencyProbe = new LatencyProbe({ ...config, pingIntervalMs: 100 }); + const wsProbe = new WsRpcProbe({ ...config, rpcIntervalMs: 1000 }); + const kernelProbe = new PiKernelProbe(config, ssh); + const httpProbe = new HttpProbe(config); + + latencyProbe.start(); + await wsProbe.start(); + kernelProbe.start(); + + // Phase 1: Establish baseline with minimal activity (5 seconds) + log("[freeze-reproducer] [Phase 1/3] Measuring active link baseline (5s)..."); + await new Promise((r) => setTimeout(r, 5000)); + + // Phase 2: Inactivity silence period to allow Wi-Fi AP or client power-save to engage (8 seconds) + log("[freeze-reproducer] [Phase 2/3] Entering 8s idle period to observe Wi-Fi power-save sleep / freeze..."); + + // Pause high-rate RPCs during idle phase to observe sleep + const preBurstLatencies: number[] = []; + const idleStartTime = Date.now(); + while (Date.now() - idleStartTime < 8000) { + const samples = latencyProbe.getSamples(); + if (samples.length > 0) { + const latest = samples[samples.length - 1]; + if (latest.rttMs !== null) { + preBurstLatencies.push(latest.rttMs); + } + } + await new Promise((r) => setTimeout(r, 1000)); + } + + const preBurstMaxLatencyMs = preBurstLatencies.length > 0 ? Math.max(...preBurstLatencies) : 0; + const idleFreezeObserved = preBurstMaxLatencyMs > 200 || preBurstLatencies.some((l) => l > 150); + + log(`[freeze-reproducer] Idle phase complete. Max latency during idle: ${preBurstMaxLatencyMs}ms (Freeze observed: ${idleFreezeObserved})`); + + // Phase 3: Trigger Unclog Burst (Simulate keystroke / packet spam) + log("[freeze-reproducer] [Phase 3/3] Sending outbound packet burst to test 'pipe unclogging' effect..."); + const burstStart = performance.now(); + + // Send 10 rapid SSH probes / TCP pings within 500ms + const burstPromises = Array.from({ length: 8 }).map((_, i) => + ssh.exec(`echo "unclog-ping-${i}"`, 1500).catch(() => ({ exitCode: 1, stdout: "", stderr: "" })) + ); + + await Promise.all(burstPromises); + const burstDuration = performance.now() - burstStart; + + // Measure recovery + log(`[freeze-reproducer] Burst dispatched in ${Math.round(burstDuration)}ms. Measuring recovery latency (5s)...`); + await new Promise((r) => setTimeout(r, 5000)); + + latencyProbe.stop(); + wsProbe.stop(); + kernelProbe.stop(); + + const allSamples = latencyProbe.getSamples(); + const postBurstSamples = allSamples.slice(-40).filter((s) => s.rttMs !== null); + const postBurstAvgLatencyMs = postBurstSamples.length > 0 + ? postBurstSamples.reduce((a, b) => a + b.rttMs!, 0) / postBurstSamples.length + : 0; + + const unclogTriggerSuccess = preBurstMaxLatencyMs > 100 && postBurstAvgLatencyMs < 30; + const unclogRecoveryTimeMs = Math.round(burstDuration); + + const kernelSnapshots = kernelProbe.getSnapshots(); + const latestKernel = kernelSnapshots.length > 0 ? kernelSnapshots[kernelSnapshots.length - 1] : null; + const wifiPowerSaveActive = latestKernel?.wifi.power_save.toLowerCase() === "on"; + + const anomaliesDetected: string[] = []; + if (idleFreezeObserved) { + anomaliesDetected.push(`Wi-Fi link latency degraded during idle periods (up to ${preBurstMaxLatencyMs}ms)`); + } + if (unclogTriggerSuccess) { + anomaliesDetected.push(`Unclog confirmed: Outbound client traffic instantly restored low latency from ${preBurstMaxLatencyMs}ms down to ${Math.round(postBurstAvgLatencyMs)}ms`); + } + if (wifiPowerSaveActive) { + anomaliesDetected.push("Wi-Fi interface power_save is active on the Pi"); + } + + log(`[freeze-reproducer] Result: Idle Freeze = ${idleFreezeObserved}, Unclog Response = ${unclogTriggerSuccess}, Recovery Avg = ${Math.round(postBurstAvgLatencyMs)}ms`); + + return { + scenarioName: "Wi-Fi Hotspot Idle Freeze & Unclog Reproducer", + durationSec: 18, + latencyStats: latencyProbe.getStats(), + wsStats: wsProbe.getStats(), + httpStats: httpProbe.getStats(), + kernelSnapshots, + anomaliesDetected, + idleFreezeObserved, + unclogTriggerSuccess, + unclogRecoveryTimeMs, + preBurstMaxLatencyMs: Math.round(preBurstMaxLatencyMs * 10) / 10, + postBurstAvgLatencyMs: Math.round(postBurstAvgLatencyMs * 10) / 10, + wifiPowerSaveActive, + }; +} diff --git a/headless-rust/diagnostics/scenarios/gige-wifi-contention.ts b/headless-rust/diagnostics/scenarios/gige-wifi-contention.ts new file mode 100644 index 0000000..8e6ec70 --- /dev/null +++ b/headless-rust/diagnostics/scenarios/gige-wifi-contention.ts @@ -0,0 +1,83 @@ +import type { DiagConfig } from "../config"; +import type { SshClient } from "../ssh-client"; +import { LatencyProbe } from "../probes/latency-probe"; +import { WsRpcProbe } from "../probes/ws-rpc-probe"; +import { PiKernelProbe } from "../probes/pi-kernel-probe"; +import { HttpProbe } from "../probes/http-probe"; +import type { ScenarioResult } from "./baseline"; + +export interface GigeContentionResult extends ScenarioResult { + coreImbalanceDetected: boolean; + netRxSoftirqPerCpu: number[]; + bufferBloatObserved: boolean; +} + +export async function runGigeContentionScenario( + config: DiagConfig, + ssh: SshClient, + onProgress?: (status: string) => void +): Promise { + const log = (msg: string) => { + if (onProgress) onProgress(msg); + }; + + log("[gige-wifi-contention] Testing GigE Ethernet vs Wi-Fi SoftIRQ core balance & socket buffer bloat..."); + + const latencyProbe = new LatencyProbe(config); + const wsProbe = new WsRpcProbe(config); + const kernelProbe = new PiKernelProbe(config, ssh); + const httpProbe = new HttpProbe(config); + + latencyProbe.start(); + await wsProbe.start(); + kernelProbe.start(); + + // Let it collect data for 6 seconds + await new Promise((r) => setTimeout(r, 6000)); + + latencyProbe.stop(); + wsProbe.stop(); + kernelProbe.stop(); + + const latencyStats = latencyProbe.getStats(); + const wsStats = wsProbe.getStats(); + const httpStats = httpProbe.getStats(); + const kernelSnapshots = kernelProbe.getSnapshots(); + + const latestKernel = kernelSnapshots.length > 0 ? kernelSnapshots[kernelSnapshots.length - 1] : null; + const netRx = latestKernel?.softirqs.net_rx_per_cpu || []; + + // Check if one CPU core has >80% of all NET_RX softirqs + let coreImbalanceDetected = false; + const totalNetRx = netRx.reduce((a, b) => a + b, 0); + if (totalNetRx > 0 && netRx.length > 1) { + const maxCoreNetRx = Math.max(...netRx); + if (maxCoreNetRx / totalNetRx > 0.8) { + coreImbalanceDetected = true; + } + } + + // Check if buffer defaults are set to GigE extreme 67MB + const bufferBloatObserved = (latestKernel?.sysctl.rmem_default || 0) > 10485760; + + const anomaliesDetected: string[] = []; + if (coreImbalanceDetected) { + anomaliesDetected.push(`NET_RX softirqs are heavily clustered on a single CPU core (${JSON.stringify(netRx)})`); + } + if (bufferBloatObserved) { + anomaliesDetected.push(`GigE socket buffer defaults (67MB) are active globally on all sockets (causing TCP window bufferbloat on Wi-Fi)`); + } + + return { + scenarioName: "GigE Ethernet vs Wi-Fi Contention", + durationSec: 6, + latencyStats, + wsStats, + httpStats, + kernelSnapshots, + anomaliesDetected, + coreImbalanceDetected, + netRxSoftirqPerCpu: netRx, + bufferBloatObserved, + }; +} diff --git a/headless-rust/diagnostics/scenarios/violation-stress.ts b/headless-rust/diagnostics/scenarios/violation-stress.ts new file mode 100644 index 0000000..a495d61 --- /dev/null +++ b/headless-rust/diagnostics/scenarios/violation-stress.ts @@ -0,0 +1,103 @@ +import type { DiagConfig } from "../config"; +import type { SshClient } from "../ssh-client"; +import { LatencyProbe } from "../probes/latency-probe"; +import { WsRpcProbe } from "../probes/ws-rpc-probe"; +import { PiKernelProbe } from "../probes/pi-kernel-probe"; +import { HttpProbe } from "../probes/http-probe"; +import type { ScenarioResult } from "./baseline"; + +export interface ViolationStressResult extends ScenarioResult { + maxDirtyMemoryKb: number; + dStateProcessCount: number; + coincidentRpcTimeouts: number; + diskIoStallDetected: boolean; +} + +export async function runViolationStressScenario( + config: DiagConfig, + ssh: SshClient, + onProgress?: (status: string) => void +): Promise { + const log = (msg: string) => { + if (onProgress) onProgress(msg); + }; + + log("[violation-stress] Testing correlation between image capture / storage writeback and network stalls..."); + + const latencyProbe = new LatencyProbe({ ...config, pingIntervalMs: 80 }); + const wsProbe = new WsRpcProbe({ ...config, rpcIntervalMs: 250 }); + const kernelProbe = new PiKernelProbe(config, ssh); + const httpProbe = new HttpProbe(config); + + latencyProbe.start(); + await wsProbe.start(); + kernelProbe.start(); + + log("[violation-stress] Generating synthetic image capture writes (5 x 5MB bursts) on Pi storage..."); + + // Generate 5 rapid violation capture bursts on Pi disk to stress I/O writeback & sqlite + const stressCmd = ` + TMP_DIR=$(mktemp -d /tmp/speedcam-stress-XXXXXX) + for i in {1..5}; do + dd if=/dev/urandom of="$TMP_DIR/img_$i.jpg" bs=1M count=5 2>/dev/null + sync + sleep 0.4 + done + rm -rf "$TMP_DIR" + `; + + // Start background write stress + const stressPromise = ssh.exec(stressCmd, 15000); + + // Monitor while stress is running + const start = Date.now(); + while (Date.now() - start < 10000) { + const lStats = latencyProbe.getStats(); + const wStats = wsProbe.getStats(); + log(`[violation-stress] Latency: ${lStats.avgRttMs}ms (max: ${lStats.maxRttMs}ms) | WS RPC timeouts: ${wStats.timedOutCalls}`); + await new Promise((r) => setTimeout(r, 1500)); + } + + await stressPromise.catch(() => ({ exitCode: 1, stdout: "", stderr: "" })); + + latencyProbe.stop(); + wsProbe.stop(); + kernelProbe.stop(); + + const latencyStats = latencyProbe.getStats(); + const wsStats = wsProbe.getStats(); + const httpStats = httpProbe.getStats(); + const kernelSnapshots = kernelProbe.getSnapshots(); + + const maxDirtyMemoryKb = kernelSnapshots.length > 0 + ? Math.max(...kernelSnapshots.map((k) => k.memory.dirty_kb)) + : 0; + + const dStateProcessCount = kernelSnapshots.length > 0 + ? Math.max(...kernelSnapshots.map((k) => k.memory.d_state_processes)) + : 0; + + const diskIoStallDetected = (latencyStats.maxRttMs > 300 || wsStats.timedOutCalls > 0) && maxDirtyMemoryKb > 20000; + + const anomaliesDetected: string[] = []; + if (diskIoStallDetected) { + anomaliesDetected.push(`Storage writeback coincides with network stall: Dirty memory peaked at ${(maxDirtyMemoryKb / 1024).toFixed(1)}MB with ${wsStats.timedOutCalls} RPC timeouts`); + } + if (dStateProcessCount > 0) { + anomaliesDetected.push(`D-state (uninterruptible disk sleep) processes observed during disk sync: ${dStateProcessCount}`); + } + + return { + scenarioName: "Image Capture & Storage Writeback Stress", + durationSec: 10, + latencyStats, + wsStats, + httpStats, + kernelSnapshots, + anomaliesDetected, + maxDirtyMemoryKb, + dStateProcessCount, + coincidentRpcTimeouts: wsStats.timedOutCalls, + diskIoStallDetected, + }; +} diff --git a/headless-rust/diagnostics/ssh-client.ts b/headless-rust/diagnostics/ssh-client.ts new file mode 100644 index 0000000..cb9aa60 --- /dev/null +++ b/headless-rust/diagnostics/ssh-client.ts @@ -0,0 +1,214 @@ +import { spawn } from "node:child_process"; +import { mkdirSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { DiagConfig } from "./config"; + +export interface SshResult { + stdout: string; + stderr: string; + exitCode: number; +} + +export class SshClient { + private config: DiagConfig; + private socketDir: string; + private socketPath: string; + private isConnected = false; + + constructor(config: DiagConfig) { + this.config = config; + const randomId = Math.random().toString(36).substring(2, 8); + this.socketDir = join(tmpdir(), `speedcam-diag-ssh-${process.pid}-${randomId}`); + try { + mkdirSync(this.socketDir, { recursive: true }); + } catch (_) {} + this.socketPath = join(this.socketDir, "socket"); + } + + public getSshTarget(): string { + return `${this.config.user}@${this.config.host}`; + } + + private getBaseSshArgs(): string[] { + const args: string[] = [ + "-p", String(this.config.sshPort), + "-o", "StrictHostKeyChecking=no", + "-o", "UserKnownHostsFile=/dev/null", + "-o", "LogLevel=ERROR", + "-o", "ConnectTimeout=5", + "-o", `ControlPath=${this.socketPath}`, + ]; + + if (this.config.usePasswordAuth) { + args.push("-o", "PubkeyAuthentication=no"); + args.push("-o", "PreferredAuthentications=password,keyboard-interactive"); + } + + return args; + } + + /** + * Test if SSH target is reachable and initialize ControlMaster + */ + public async checkConnection(): Promise<{ ok: boolean; error?: string; latencyMs?: number }> { + const start = performance.now(); + const args = [ + "-o", "ControlMaster=auto", + "-o", "ControlPersist=120s", + ...this.getBaseSshArgs(), + this.getSshTarget(), + "echo 'speedcamera-ssh-ok'", + ]; + + try { + const res = await this.runProcess("ssh", args, 6000); + const latencyMs = performance.now() - start; + if (res.exitCode === 0 && res.stdout.includes("speedcamera-ssh-ok")) { + this.isConnected = true; + return { ok: true, latencyMs }; + } + return { ok: false, error: res.stderr || res.stdout || `Exit code ${res.exitCode}` }; + } catch (err: any) { + return { ok: false, error: err.message || String(err) }; + } + } + + /** + * Run a command on the remote host + */ + public async exec(cmd: string, timeoutMs: number = 10000): Promise { + const args = [ + "-o", "ControlMaster=auto", + "-o", "ControlPersist=120s", + ...this.getBaseSshArgs(), + this.getSshTarget(), + cmd, + ]; + + return this.runProcess("ssh", args, timeoutMs); + } + + /** + * Run a remote command and parse output as JSON + */ + public async execJson(cmd: string, timeoutMs: number = 10000): Promise<{ ok: boolean; data?: T; error?: string }> { + const res = await this.exec(cmd, timeoutMs); + if (res.exitCode !== 0) { + return { ok: false, error: res.stderr || `Exit code ${res.exitCode}` }; + } + try { + // Find JSON block if wrapped in stdout noise + const trimmed = res.stdout.trim(); + const firstBrace = trimmed.indexOf("{"); + const lastBrace = trimmed.lastIndexOf("}"); + if (firstBrace !== -1 && lastBrace !== -1 && lastBrace > firstBrace) { + const jsonStr = trimmed.substring(firstBrace, lastBrace + 1); + const data = JSON.parse(jsonStr) as T; + return { ok: true, data }; + } + return { ok: true, data: JSON.parse(trimmed) as T }; + } catch (err: any) { + return { ok: false, error: `JSON Parse error: ${err.message}. Raw output: ${res.stdout.slice(0, 200)}` }; + } + } + + /** + * Execute a remote script by sending content over stdin to bash + */ + public async execScript(scriptContent: string, timeoutMs: number = 15000): Promise { + const args = [ + "-o", "ControlMaster=auto", + "-o", "ControlPersist=120s", + ...this.getBaseSshArgs(), + this.getSshTarget(), + "bash -s", + ]; + + return new Promise((resolve) => { + const child = spawn("ssh", args, { stdio: ["pipe", "pipe", "pipe"] }); + let stdout = ""; + let stderr = ""; + let timedOut = false; + + const timer = setTimeout(() => { + timedOut = true; + child.kill("SIGKILL"); + }, timeoutMs); + + child.stdout.on("data", (chunk) => { + stdout += chunk.toString(); + }); + + child.stderr.on("data", (chunk) => { + stderr += chunk.toString(); + }); + + child.on("close", (code) => { + clearTimeout(timer); + resolve({ + stdout, + stderr: timedOut ? `Execution timed out after ${timeoutMs}ms. ${stderr}` : stderr, + exitCode: timedOut ? 124 : (code ?? 1), + }); + }); + + child.stdin.write(scriptContent); + child.stdin.end(); + }); + } + + private runProcess(cmd: string, args: string[], timeoutMs: number): Promise { + return new Promise((resolve) => { + const child = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"] }); + let stdout = ""; + let stderr = ""; + let timedOut = false; + + const timer = setTimeout(() => { + timedOut = true; + child.kill("SIGKILL"); + }, timeoutMs); + + child.stdout.on("data", (chunk) => { + stdout += chunk.toString(); + }); + + child.stderr.on("data", (chunk) => { + stderr += chunk.toString(); + }); + + child.on("close", (code) => { + clearTimeout(timer); + resolve({ + stdout, + stderr: timedOut ? `Execution timed out after ${timeoutMs}ms. ${stderr}` : stderr, + exitCode: timedOut ? 124 : (code ?? 1), + }); + }); + + child.on("error", (err) => { + clearTimeout(timer); + resolve({ + stdout: "", + stderr: err.message, + exitCode: 1, + }); + }); + }); + } + + /** + * Close SSH control master connection + */ + public async close(): Promise { + if (this.isConnected) { + try { + await this.runProcess("ssh", ["-O", "exit", "-o", `ControlPath=${this.socketPath}`, this.getSshTarget()], 2000); + } catch (_) {} + } + try { + rmSync(this.socketDir, { recursive: true, force: true }); + } catch (_) {} + } +} diff --git a/headless-rust/frontend/index.html b/headless-rust/frontend/index.html new file mode 100644 index 0000000..cca04dd --- /dev/null +++ b/headless-rust/frontend/index.html @@ -0,0 +1,12 @@ + + + + + + Speedcamera + + +
+ + + diff --git a/headless-rust/frontend/src/App.tsx b/headless-rust/frontend/src/App.tsx new file mode 100644 index 0000000..ffaa34b --- /dev/null +++ b/headless-rust/frontend/src/App.tsx @@ -0,0 +1,46 @@ +import { createMemoryHistory, createRouter, RouterProvider } from "@tanstack/react-router"; +import { Toaster } from "sonner"; +import { ErrorBoundary } from "@/components/ErrorBoundary"; +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 { LapsRoute } from "@/routes/laps"; +import { TeableRoute } from "@/routes/teable"; +import { SetupRoute } from "@/routes/setup"; + +// ─── Router ───────────────────────────────────────────────────────────────────── + +const routeTree = RootRoute.addChildren([ + IndexRoute, + ViolationsRoute, + SettingsRoute, + AboutRoute, + LapsRoute, + TeableRoute, + SetupRoute, +]); + +const history = createMemoryHistory({ initialEntries: ["/"] }); + +const router = createRouter({ routeTree, history }); + +declare module "@tanstack/react-router" { + interface Register { + router: typeof router; + } +} + +// ─── App ───────────────────────────────────────────────────────────────────── + +function App() { + return ( + + + + + ); +} + +export default App; diff --git a/headless-rust/frontend/src/components/ArmingButton.tsx b/headless-rust/frontend/src/components/ArmingButton.tsx new file mode 100644 index 0000000..fd8e828 --- /dev/null +++ b/headless-rust/frontend/src/components/ArmingButton.tsx @@ -0,0 +1,237 @@ +import { useCallback, useEffect, useRef, useState } from "react"; +import { HugeiconsIcon } from "@hugeicons/react"; +import { + Shield01Icon, + ShieldHalfIcon, + ShieldKeyIcon, +} from "@hugeicons/core-free-icons"; +import { cn } from "@/lib/utils"; +import { useAppStore } from "@/stores/useAppStore"; + +const HOLD_DURATION_MS = 3000; +/** How long after a successful arm to ignore click-to-disarm (ms) */ +const POST_ARM_DEBOUNCE_MS = 600; + +export function ArmingButton() { + const systemState = useAppStore((s) => s.systemState); + const setArmed = useAppStore((s) => s.setArmed); + const connectedPort = useAppStore((s) => s.connectedPort); + const cameraConnected = useAppStore((s) => s.cameraConnected); + + const [progress, setProgress] = useState(0); // 0–1 + const [isHolding, setIsHolding] = useState(false); + + const startTimeRef = useRef(null); + const rafRef = useRef(null); + const completedRef = useRef(false); + /** Set to true right after arm completes; cleared after debounce window */ + const justArmedRef = useRef(false); + const debounceTimerRef = useRef | null>(null); + + const cancelHold = useCallback(() => { + if (rafRef.current !== null) { + cancelAnimationFrame(rafRef.current); + rafRef.current = null; + } + startTimeRef.current = null; + completedRef.current = false; + setIsHolding(false); + setProgress(0); + }, []); + + const startHold = useCallback(() => { + // Can only arm from DISARMED (conditions met, not yet armed) + if (systemState !== "DISARMED") return; + + completedRef.current = false; + startTimeRef.current = performance.now(); + setIsHolding(true); + setProgress(0); + + const tick = (now: number) => { + if (!startTimeRef.current) return; + const elapsed = now - startTimeRef.current; + const p = Math.min(elapsed / HOLD_DURATION_MS, 1); + setProgress(p); + + if (p >= 1 && !completedRef.current) { + completedRef.current = true; + setIsHolding(false); + setProgress(0); + // Mark debounce window so the imminent click event is ignored + justArmedRef.current = true; + if (debounceTimerRef.current !== null) clearTimeout(debounceTimerRef.current); + debounceTimerRef.current = setTimeout(() => { + justArmedRef.current = false; + }, POST_ARM_DEBOUNCE_MS); + void setArmed(true); + return; + } + + if (p < 1) { + rafRef.current = requestAnimationFrame(tick); + } + }; + + rafRef.current = requestAnimationFrame(tick); + }, [systemState, setArmed]); + + const handlePointerDown = useCallback(() => { + if (systemState === "DISARMED") { + startHold(); + } + }, [systemState, startHold]); + + const handleClick = useCallback(() => { + // Ignore the click that fires right after a successful hold-to-arm + if (justArmedRef.current) return; + if (systemState === "ARMED") { + void setArmed(false); + } + }, [systemState, setArmed]); + + // Cleanup on unmount + useEffect(() => { + return () => { + if (rafRef.current !== null) cancelAnimationFrame(rafRef.current); + if (debounceTimerRef.current !== null) clearTimeout(debounceTimerRef.current); + }; + }, []); + + const isArmed = systemState === "ARMED"; + const isPassive = systemState === "PASSIVE"; + const isDisarmed = systemState === "DISARMED"; + + // Derive which conditions are missing for the hint text + const missingCamera = !cameraConnected; + const missingSerial = !connectedPort; + + return ( +
+ {/* Header */} +
+
+ + + System + +
+ + {/* State pill */} + + {systemState} + +
+ + {/* Arming / disarming button */} + + + {/* Hint */} +

+ {isArmed + ? "Violations are being recorded" + : isDisarmed + ? "Monitoring only — no violations recorded" + : [missingCamera && "camera", missingSerial && "serial connection"] + .filter(Boolean) + .join(" & ") + " required"} +

+
+ ); +} diff --git a/headless-rust/frontend/src/components/ConnectionIndicator.tsx b/headless-rust/frontend/src/components/ConnectionIndicator.tsx new file mode 100644 index 0000000..21e4c95 --- /dev/null +++ b/headless-rust/frontend/src/components/ConnectionIndicator.tsx @@ -0,0 +1,67 @@ +import { useState } from "react"; +import { useBackendEvent } from "@/hooks/useBackendEvent"; +import { HugeiconsIcon } from "@hugeicons/react"; +import { Wifi01Icon, WifiDisconnected01Icon } from "@hugeicons/core-free-icons"; +import { cn } from "@/lib/utils"; + +interface HeartbeatPayload { + connected: boolean; + latencyMs: number | null; + degraded: boolean; +} + +export function ConnectionIndicator() { + const [isConnected, setIsConnected] = useState(true); + const [latencyMs, setLatencyMs] = useState(null); + const [isDegraded, setIsDegraded] = useState(false); + + useBackendEvent("connectionChange", (connected) => { + setIsConnected(connected as boolean); + if (!connected) { + setLatencyMs(null); + setIsDegraded(true); + } + }); + + useBackendEvent("heartbeat" as any, (data: any) => { + const payload = data as HeartbeatPayload; + setIsConnected(payload.connected); + setLatencyMs(payload.latencyMs); + setIsDegraded(payload.degraded); + }); + + const getStatusText = () => { + if (!isConnected) return "Stalled / Reconnecting..."; + if (latencyMs !== null) { + return `${latencyMs}ms`; + } + return "Connected"; + }; + + return ( +
+ + {getStatusText()} +
+ ); +} diff --git a/headless-rust/frontend/src/components/ErrorBoundary.tsx b/headless-rust/frontend/src/components/ErrorBoundary.tsx new file mode 100644 index 0000000..ac8984f --- /dev/null +++ b/headless-rust/frontend/src/components/ErrorBoundary.tsx @@ -0,0 +1,60 @@ +import { Component } from "react"; +import type { ReactNode, ErrorInfo } from "react"; +import { Button } from "@/components/ui/button"; + +interface ErrorBoundaryProps { + children: ReactNode; + fallback?: ReactNode; +} + +interface ErrorBoundaryState { + hasError: boolean; + error: Error | null; +} + +export class ErrorBoundary extends Component { + constructor(props: ErrorBoundaryProps) { + super(props); + this.state = { hasError: false, error: null }; + } + + static getDerivedStateFromError(error: Error): ErrorBoundaryState { + return { hasError: true, error }; + } + + componentDidCatch(error: Error, info: ErrorInfo) { + console.error("[ErrorBoundary] Uncaught error:", error, info); + } + + handleReset = () => { + this.setState({ hasError: false, error: null }); + }; + + render() { + if (this.state.hasError) { + if (this.props.fallback) { + return this.props.fallback; + } + return ( +
+
+ ⚠ +
+
+

Something went wrong

+ {this.state.error && ( +

+ {this.state.error.message} +

+ )} +
+ +
+ ); + } + + return this.props.children; + } +} diff --git a/headless-rust/frontend/src/components/FirmwareFlasher.tsx b/headless-rust/frontend/src/components/FirmwareFlasher.tsx new file mode 100644 index 0000000..50db99b --- /dev/null +++ b/headless-rust/frontend/src/components/FirmwareFlasher.tsx @@ -0,0 +1,363 @@ +import { useState, useEffect, useRef, useCallback } from "react"; +import { toast } from "sonner"; +import { HugeiconsIcon } from "@hugeicons/react"; +import { + DownloadCircle02Icon, + RefreshIcon, + Cancel01Icon, + CpuIcon, + Alert02Icon, + ViewIcon, + ViewOffSlashIcon, + CheckmarkCircle02Icon, +} from "@hugeicons/core-free-icons"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select"; +import { getRpc } from "@/lib/rpc"; +import { useAppStore } from "@/stores/useAppStore"; +import type { GithubRelease } from "@/shared/types"; + +export function FirmwareFlasher() { + const isFlashing = useAppStore((s) => s.isFlashing); + const flashProgressLines = useAppStore((s) => s.flashProgressLines); + const flashError = useAppStore((s) => s.flashError); + const flashDone = useAppStore((s) => s.flashDone); + const resetFlash = useAppStore((s) => s.resetFlash); + const connectedPort = useAppStore((s) => s.connectedPort); + const setConnectedPort = useAppStore((s) => s.setConnectedPort); + + // ── Token state ──────────────────────────────────────────────────────────── + const [token, setToken] = useState(""); + const [showToken, setShowToken] = useState(false); + const [testingToken, setTestingToken] = useState(false); + const [tokenTestResult, setTokenTestResult] = useState< + { valid: boolean; login?: string; error?: string } | null + >(null); + + // ── Release state ────────────────────────────────────────────────────────── + const [releases, setReleases] = useState([]); + const [loadingReleases, setLoadingReleases] = useState(false); + const [selectedTag, setSelectedTag] = useState(""); + + const logRef = useRef(null); + + // Load saved token on mount + useEffect(() => { + getRpc() + .request.getSettings({}) + .then((s) => setToken(s.githubToken)) + .catch(() => {}); + }, []); + + // Auto-scroll progress log + useEffect(() => { + const el = logRef.current; + if (el) el.scrollTop = el.scrollHeight; + }, [flashProgressLines]); + + // Toast on completion / error + useEffect(() => { + if (flashDone) { + toast.success("Firmware flashed successfully. Reconnect the device manually."); + } + }, [flashDone]); + + useEffect(() => { + if (flashError) { + toast.error(`Flash failed: ${flashError}`); + } + }, [flashError]); + + // ── Token handlers ───────────────────────────────────────────────────────── + + const handleTokenChange = (value: string) => { + setToken(value); + setTokenTestResult(null); + }; + + const handleTokenBlur = () => { + getRpc() + .request.saveSetting({ key: "githubToken", value: token }) + .catch(() => toast.error("Failed to save token")); + }; + + const handleTestToken = async () => { + setTestingToken(true); + setTokenTestResult(null); + try { + const result = await getRpc().request.testGithubToken({ token }); + setTokenTestResult(result); + if (result.valid) { + toast.success(`Connected as ${result.login ?? "unknown"}`); + } else { + toast.error(result.error ?? "Connection test failed"); + } + } catch (err) { + const msg = err instanceof Error ? err.message : String(err); + setTokenTestResult({ valid: false, error: msg }); + } finally { + setTestingToken(false); + } + }; + + // ── Release handlers ─────────────────────────────────────────────────────── + + const fetchReleases = useCallback(async () => { + setLoadingReleases(true); + try { + const data = await getRpc().request.listFirmwareReleases({}); + setReleases(data); + if (data.length > 0 && !selectedTag) { + setSelectedTag(data[0].tag); + } + } catch (err) { + const msg = err instanceof Error ? err.message : String(err); + toast.error(msg.includes("authentication") ? msg : "Failed to fetch firmware releases"); + } finally { + setLoadingReleases(false); + } + }, [selectedTag]); + + useEffect(() => { + void fetchReleases(); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + + const handleFlash = async () => { + if (!selectedTag) return; + resetFlash(); + + const selectedRelease = releases.find((r) => r.tag === selectedTag); + if (!selectedRelease?.firmwareAssetApiUrl) { + toast.error( + "No firmware.bin asset found for this release. Make sure the release includes a firmware.bin file.", + ); + return; + } + + const portToFlash = + connectedPort || + (await getRpc() + .request.listPorts({}) + .then( + (p) => + p.find((x) => /\/dev\/(ttyUSB|ttyACM)|COM\d|cu\.usb|tty\.usb/i.test(x.path))?.path ?? + "", + ) + .catch(() => "")); + + if (!portToFlash) { + toast.error("No serial port found. Connect the device and try again."); + return; + } + + try { + await getRpc().request.flashFirmware({ + releaseTag: selectedTag, + port: portToFlash, + firmwareAssetApiUrl: selectedRelease.firmwareAssetApiUrl, + }); + setConnectedPort(""); + } catch (err) { + const msg = err instanceof Error ? err.message : String(err); + toast.error(`Flash failed: ${msg}`); + } + }; + + const handleCancel = async () => { + try { + await getRpc().request.cancelFlash({}); + } catch { + // ignore + } + resetFlash(); + }; + + const showLog = flashProgressLines.length > 0 || isFlashing; + + return ( +
+

+ + Firmware Update +

+ + {/* ── GitHub token config ─────────────────────────────────────────────── */} +
+

GitHub Access Token

+
+
+ handleTokenChange(e.target.value)} + onBlur={handleTokenBlur} + placeholder="github_pat_…" + className="pr-9 font-mono text-xs" + disabled={isFlashing} + /> + +
+ +
+ + {/* Test result feedback */} + {tokenTestResult && ( +

+ {tokenTestResult.valid ? ( + <> + + Connected as {tokenTestResult.login ?? "GitHub user"} + + ) : ( + <> + + {tokenTestResult.error} + + )} +

+ )} + +

+ A fine-grained PAT with "Contents: Read" access to the speedcamera repository is + required to fetch and download firmware releases from the private repo. +

+
+ + {/* ── Release selector ─────────────────────────────────────────────────── */} +
+ + + +
+ + {/* Info note */} +

+ The serial connection will be closed automatically before flashing. Reconnect manually after + the update completes. +

+ + {/* Action buttons */} +
+ + + {isFlashing && ( + + )} + + {(flashDone || flashError) && !isFlashing && ( + + )} +
+ + {/* Status badge */} + {flashDone && !isFlashing && ( +

+ Flash complete — device is rebooting. +

+ )} + {flashError && !isFlashing && ( +

+ + {flashError} +

+ )} + + {/* Progress log */} + {showLog && ( +
+          {flashProgressLines.join("\n")}
+          {isFlashing && ▋}
+        
+ )} +
+ ); +} diff --git a/headless-rust/frontend/src/components/LapImageThumbnails.tsx b/headless-rust/frontend/src/components/LapImageThumbnails.tsx new file mode 100644 index 0000000..33f3069 --- /dev/null +++ b/headless-rust/frontend/src/components/LapImageThumbnails.tsx @@ -0,0 +1,93 @@ +import { useState, useEffect } from "react"; +import { Dialog, DialogContent } from "@/components/ui/dialog"; +import { getRpc } from "@/lib/rpc"; + +interface LapImageThumbnailsProps { + startImagePath: string | null; + endImagePath: string | null; + /** Optional extra node rendered after the thumbnails (e.g. a delete button). */ + trailing?: React.ReactNode; +} + +/** + * Renders start/end lap capture thumbnails with a shared lightbox. + * Uses 120px compressed thumbnails over the network, opening full-resolution on click. + */ +export function LapImageThumbnails({ + startImagePath, + endImagePath, + trailing, +}: LapImageThumbnailsProps) { + const [startImageUrl, setStartImageUrl] = useState(null); + const [endImageUrl, setEndImageUrl] = useState(null); + const [lightboxUrl, setLightboxUrl] = useState(null); + + useEffect(() => { + let cancelled = false; + setStartImageUrl(null); + setEndImageUrl(null); + // ponytail: 120px mini-thumbnails for lap icons + if (startImagePath) { + getRpc() + .request.getImageData({ imagePath: startImagePath, width: 120, quality: 75 }) + .then((data) => { if (!cancelled) setStartImageUrl(data); }) + .catch(() => {}); + } + if (endImagePath) { + getRpc() + .request.getImageData({ imagePath: endImagePath, width: 120, quality: 75 }) + .then((data) => { if (!cancelled) setEndImageUrl(data); }) + .catch(() => {}); + } + return () => { cancelled = true; }; + }, [startImagePath, endImagePath]); + + return ( + <> +
+ {(startImageUrl || endImageUrl) ? ( + <> + {startImageUrl && ( + + )} + {endImageUrl && ( + + )} + + ) : ( + — + )} + {trailing} +
+ + !open && setLightboxUrl(null)}> + + {lightboxUrl && ( + Lap capture full resolution + )} + + + + ); +} diff --git a/headless-rust/frontend/src/components/LapTimerDisplay.tsx b/headless-rust/frontend/src/components/LapTimerDisplay.tsx new file mode 100644 index 0000000..6d46702 --- /dev/null +++ b/headless-rust/frontend/src/components/LapTimerDisplay.tsx @@ -0,0 +1,113 @@ +import { cn } from "@/lib/utils"; +import { formatDuration } from "@/lib/format"; +import { useAppStore } from "@/stores/useAppStore"; +import { useLiveLapTimer } from "@/hooks/useLiveLapTimer"; +import type { Lap } from "@/shared/types"; + +function formatDurationParts(ms: number) { + const total = Math.round(ms); + const totalSeconds = Math.floor(total / 1000); + const minutes = Math.floor(totalSeconds / 60); + const seconds = totalSeconds % 60; + const millis = total % 1000; + return { + main: `${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`, + millis: `.${String(millis).padStart(3, "0")}`, + }; +} + +interface LapTimerDisplayProps { + /** Compact variant for narrower containers (e.g. side panel) */ + compact?: boolean; + /** Laps to display best/last time from. If omitted, no comparison shown. */ + laps?: Lap[]; + className?: string; +} + +export function LapTimerDisplay({ compact = false, laps = [], className }: LapTimerDisplayProps) { + const lapState = useAppStore((s) => s.lapState); + const lapNumber = useAppStore((s) => s.lapNumber); + const elapsed = useLiveLapTimer(); + + const bestLap = laps.length > 0 + ? laps.reduce((b, l) => l.durationMs < b.durationMs ? l : b) + : null; + const lastLap = laps.length > 0 ? laps[laps.length - 1] : null; + + const isTiming = lapState === "timing" && elapsed !== null; + const isWaiting = lapState === "waiting"; + + const parts = isTiming ? formatDurationParts(elapsed!) : null; + + return ( +
+ {/* State label */} +

+ {isTiming + ? `Lap ${lapNumber}` + : isWaiting + ? "Waiting for car…" + : "Idle"} +

+ + {/* Big timer */} +
+ {isTiming && parts ? ( + <> + {parts.main} + + {parts.millis} + + + ) : ( + {isWaiting ? "—" : "00:00"}.000 + )} +
+ + {/* Comparison row */} + {laps.length > 0 && ( +
+ {lastLap && ( + + Last:{" "} + + {formatDuration(lastLap.durationMs)} + + + )} + {bestLap && ( + + Best:{" "} + + {formatDuration(bestLap.durationMs)} + + + )} +
+ )} +
+ ); +} diff --git a/headless-rust/frontend/src/components/LastCapturedImage.tsx b/headless-rust/frontend/src/components/LastCapturedImage.tsx new file mode 100644 index 0000000..5eb56a6 --- /dev/null +++ b/headless-rust/frontend/src/components/LastCapturedImage.tsx @@ -0,0 +1,84 @@ +import { useEffect, useState } from "react"; +import { getRpc } from "@/lib/rpc"; +import { useAppStore } from "@/stores/useAppStore"; +import { Dialog, DialogContent } from "@/components/ui/dialog"; +import { Image as ImageIcon } from "lucide-react"; + +export function LastCapturedImage() { + const lastViolation = useAppStore((s) => s.lastViolation); + const [imageSrc, setImageSrc] = useState(null); + const [lightboxOpen, setLightboxOpen] = useState(false); + + const loadImage = (imagePath: string) => { + // ponytail: 800px preview for dashboard view saves Wi-Fi payload + getRpc() + .request.getImageData({ imagePath, width: 800, quality: 80 }) + .then((src) => { + setImageSrc(`${src}&_t=${Date.now()}`); + }) + .catch(() => setImageSrc(null)); + }; + + useEffect(() => { + if (lastViolation && lastViolation.imagePath) { + loadImage(lastViolation.imagePath); + } else { + setImageSrc(null); + } + }, [lastViolation]); + + const fullResUrl = lastViolation?.imagePath + ? `/image?path=${encodeURIComponent(lastViolation.imagePath)}` + : null; + + return ( + <> +
imageSrc && setLightboxOpen(true)} + > + {imageSrc ? ( + Last capture + ) : ( +
+ +

Awaiting Capture

+
+ )} + + {lastViolation && ( +
+ + {new Date(lastViolation.timestamp).toLocaleTimeString()} + +
+ + {lastViolation.measuredSpeed} + + km/h +
+
+ )} +
+ + + + {fullResUrl && ( + Last capture full resolution + )} + + + + ); +} diff --git a/headless-rust/frontend/src/components/NavigationMenu.tsx b/headless-rust/frontend/src/components/NavigationMenu.tsx new file mode 100644 index 0000000..48f56b1 --- /dev/null +++ b/headless-rust/frontend/src/components/NavigationMenu.tsx @@ -0,0 +1,78 @@ +import { Link } from "@tanstack/react-router"; +import { HugeiconsIcon } from "@hugeicons/react"; +import { Timer01Icon, DashboardCircleIcon } from "@hugeicons/core-free-icons"; +import { cn } from "@/lib/utils"; +import { useAppStore } from "@/stores/useAppStore"; +import { ConnectionIndicator } from "./ConnectionIndicator"; + +const NAV_ITEMS = [ + { label: "Home", to: "/" }, + { label: "Violations", to: "/violations" }, + { label: "Laps", to: "/laps" }, + { label: "Settings", to: "/settings" }, + { label: "Setup", to: "/setup" }, + { label: "Teable", to: "/teable" }, + { label: "About", to: "/about" }, +] as const; + +interface NavigationMenuProps { + className?: string; +} + +export function NavigationMenu({ className }: NavigationMenuProps) { + const appMode = useAppStore((s) => s.appMode); + const setAppMode = useAppStore((s) => s.setAppMode); + + return ( + + ); +} diff --git a/headless-rust/frontend/src/components/StatusBadge.tsx b/headless-rust/frontend/src/components/StatusBadge.tsx new file mode 100644 index 0000000..1117706 --- /dev/null +++ b/headless-rust/frontend/src/components/StatusBadge.tsx @@ -0,0 +1,46 @@ +import { cn } from "@/lib/utils"; + +export type ConnectionStatus = "connected" | "disconnected" | "unknown"; + +interface StatusBadgeProps { + status: ConnectionStatus; + label: string; + className?: string; +} + +const STATUS_STYLES: Record = { + connected: { + dot: "bg-green-500", + label: "text-green-600 dark:text-green-400", + }, + disconnected: { + dot: "bg-red-500", + label: "text-red-600 dark:text-red-400", + }, + unknown: { + dot: "bg-muted-foreground/40", + label: "text-muted-foreground", + }, +}; + +export function StatusBadge({ status, label, className }: StatusBadgeProps) { + const { dot, label: labelClass } = STATUS_STYLES[status]; + + return ( +
+
+ ); +} diff --git a/headless-rust/frontend/src/components/ThemeToggle.tsx b/headless-rust/frontend/src/components/ThemeToggle.tsx new file mode 100644 index 0000000..304782e --- /dev/null +++ b/headless-rust/frontend/src/components/ThemeToggle.tsx @@ -0,0 +1,29 @@ +import { useTheme } from "next-themes"; +import { HugeiconsIcon } from "@hugeicons/react"; +import { Sun01Icon, Moon01Icon } from "@hugeicons/core-free-icons"; +import { Button } from "@/components/ui/button"; +import { cn } from "@/lib/utils"; + +interface ThemeToggleProps { + className?: string; +} + +export function ThemeToggle({ className }: ThemeToggleProps) { + const { resolvedTheme, setTheme } = useTheme(); + + const toggle = () => setTheme(resolvedTheme === "dark" ? "light" : "dark"); + + return ( + + ); +} diff --git a/headless-rust/frontend/src/components/ViolationCard.tsx b/headless-rust/frontend/src/components/ViolationCard.tsx new file mode 100644 index 0000000..2d45114 --- /dev/null +++ b/headless-rust/frontend/src/components/ViolationCard.tsx @@ -0,0 +1,143 @@ +import { useState, useEffect } from "react"; +import { toast } from "sonner"; +import { HugeiconsIcon } from "@hugeicons/react"; +import { Delete02Icon } from "@hugeicons/core-free-icons"; +import { cn } from "@/lib/utils"; +import { Button } from "@/components/ui/button"; +import { getRpc } from "@/lib/rpc"; +import type { Violation } from "@/shared/types"; + +interface ViolationCardProps { + violation: Violation; + /** Called after successful deletion — use to remove from parent list */ + onDelete?: (id: number) => void; + /** Called when the thumbnail is clicked — receives the data-URL for a lightbox */ + onImageClick?: (dataUrl: string) => void; + className?: string; +} + +export function ViolationCard({ + violation, + onDelete, + onImageClick, + className, +}: ViolationCardProps) { + const [imageData, setImageData] = useState(null); + const [imageLoading, setImageLoading] = useState(true); + const [deleting, setDeleting] = useState(false); + + useEffect(() => { + let cancelled = false; + setImageLoading(true); + + // ponytail: 240px thumbnail for dashboard card + getRpc() + .request.getImageData({ imagePath: violation.imagePath, width: 240, quality: 75 }) + .then((data) => { + if (!cancelled) setImageData(data); + }) + .catch(() => { + if (!cancelled) setImageData(null); + }) + .finally(() => { + if (!cancelled) setImageLoading(false); + }); + + return () => { + cancelled = true; + }; + }, [violation.imagePath]); + + const fullResUrl = `/image?path=${encodeURIComponent(violation.imagePath)}`; + + const handleDelete = async () => { + setDeleting(true); + try { + await getRpc().request.deleteViolation({ id: violation.id }); + onDelete?.(violation.id); + } catch { + toast.error("Failed to delete violation"); + setDeleting(false); + } + }; + + const formattedTime = new Date(violation.timestamp).toLocaleString(undefined, { + year: "numeric", + month: "short", + day: "numeric", + hour: "2-digit", + minute: "2-digit", + second: "2-digit", + }); + + const overSpeed = (violation.measuredSpeed - violation.maxSpeed).toFixed(1); + + return ( +
+ {/* Thumbnail */} + + + {/* Info */} +
+
+
+

+ {violation.measuredSpeed} km/h +

+

+ Limit {violation.maxSpeed} km/h + (+{overSpeed}) +

+
+ + +
+ +

{formattedTime}

+
+
+ ); +} diff --git a/headless-rust/frontend/src/components/WifiConnectDialog.tsx b/headless-rust/frontend/src/components/WifiConnectDialog.tsx new file mode 100644 index 0000000..6470243 --- /dev/null +++ b/headless-rust/frontend/src/components/WifiConnectDialog.tsx @@ -0,0 +1,194 @@ +import { useState } from "react"; +import { QRCodeSVG } from "qrcode.react"; +import { toast } from "sonner"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog"; +import { Button } from "@/components/ui/button"; +import { Badge } from "@/components/ui/badge"; +import { Wifi, Copy, Check, ExternalLink, Loader2 } from "lucide-react"; + +interface WifiConnectDialogProps { + open: boolean; + onOpenChange: (open: boolean) => void; + ssid: string; + password?: string; + security?: string; + connecting: boolean; + assignedIp?: string | null; +} + +export function WifiConnectDialog({ + open, + onOpenChange, + ssid, + password, + security, + connecting, + assignedIp, +}: WifiConnectDialogProps) { + const [copied, setCopied] = useState(false); + + const isSecured = security && security !== "Open" && password && password.length > 0; + const qrSecurityType = isSecured ? "WPA" : "nopass"; + const qrString = isSecured + ? `WIFI:S:${ssid};T:${qrSecurityType};P:${password};;` + : `WIFI:S:${ssid};T:nopass;;`; + + const targetUrl = assignedIp + ? `http://${assignedIp}:3000` + : "http://raspberrypi.local:3000"; + + const handleCopyUrl = async () => { + try { + await navigator.clipboard.writeText(targetUrl); + setCopied(true); + toast.success("Target URL copied to clipboard"); + setTimeout(() => setCopied(false), 2000); + } catch { + toast.error("Failed to copy URL"); + } + }; + + return ( + + + +
+
+ +
+
+ + {connecting ? "Connecting to Network..." : "Switched to Client Mode"} + + + {connecting + ? "Configuring interface and establishing connection." + : "Device is connecting to your Wi-Fi network."} + +
+
+
+ +
+ {connecting ? ( +
+ +
+

Applying network settings...

+

+ Connecting to: {ssid} +

+
+
+ ) : ( + <> + {/* QR Code Card */} +
+
+ +
+
+ + Scan with smartphone camera to connect + +

+ Automatically joins {ssid} +

+
+
+ + {/* Instructions */} +
+
+
+ Target Network: + + {ssid} + +
+ {isSecured && ( +
+ Password: + + {password} + +
+ )} + {assignedIp && ( +
+ Assigned IP: + + {assignedIp} + +
+ )} +
+ +
+

+ The standalone setup hotspot is now shutting down. Connect your phone or laptop to{" "} + {ssid} and open the dashboard: +

+
+
+ {targetUrl} +
+ + +
+
+
+ + )} +
+ +
+ +
+
+
+ ); +} diff --git a/headless-rust/frontend/src/components/ui/badge.tsx b/headless-rust/frontend/src/components/ui/badge.tsx new file mode 100644 index 0000000..f428bc5 --- /dev/null +++ b/headless-rust/frontend/src/components/ui/badge.tsx @@ -0,0 +1,49 @@ +import * as React from "react" +import { cva, type VariantProps } from "class-variance-authority" +import { Slot } from "radix-ui" + +import { cn } from "@/lib/utils" + +const badgeVariants = cva( + "group/badge inline-flex h-5 w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-4xl border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-all focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3!", + { + variants: { + variant: { + default: "bg-primary text-primary-foreground [a]:hover:bg-primary/80", + secondary: + "bg-secondary text-secondary-foreground [a]:hover:bg-secondary/80", + destructive: + "bg-destructive/10 text-destructive focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:focus-visible:ring-destructive/40 [a]:hover:bg-destructive/20", + outline: + "border-border bg-input/30 text-foreground [a]:hover:bg-muted [a]:hover:text-muted-foreground", + ghost: + "hover:bg-muted hover:text-muted-foreground dark:hover:bg-muted/50", + link: "text-primary underline-offset-4 hover:underline", + }, + }, + defaultVariants: { + variant: "default", + }, + } +) + +function Badge({ + className, + variant = "default", + asChild = false, + ...props +}: React.ComponentProps<"span"> & + VariantProps & { asChild?: boolean }) { + const Comp = asChild ? Slot.Root : "span" + + return ( + + ) +} + +export { Badge, badgeVariants } diff --git a/headless-rust/frontend/src/components/ui/button.tsx b/headless-rust/frontend/src/components/ui/button.tsx new file mode 100644 index 0000000..652d5d3 --- /dev/null +++ b/headless-rust/frontend/src/components/ui/button.tsx @@ -0,0 +1,65 @@ +import * as React from "react" +import { cva, type VariantProps } from "class-variance-authority" +import { Slot } from "radix-ui" + +import { cn } from "@/lib/utils" + +const buttonVariants = cva( + "group/button inline-flex shrink-0 items-center justify-center rounded-4xl border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", + { + variants: { + variant: { + default: "bg-primary text-primary-foreground hover:bg-primary/80", + outline: + "border-border bg-input/30 hover:bg-input/50 hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground", + secondary: + "bg-secondary text-secondary-foreground hover:bg-secondary/80 aria-expanded:bg-secondary aria-expanded:text-secondary-foreground", + ghost: + "hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50", + destructive: + "bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40", + link: "text-primary underline-offset-4 hover:underline", + }, + size: { + default: + "h-9 gap-1.5 px-3 has-data-[icon=inline-end]:pr-2.5 has-data-[icon=inline-start]:pl-2.5", + xs: "h-6 gap-1 px-2.5 text-xs has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2 [&_svg:not([class*='size-'])]:size-3", + sm: "h-8 gap-1 px-3 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2", + lg: "h-10 gap-1.5 px-4 has-data-[icon=inline-end]:pr-3 has-data-[icon=inline-start]:pl-3", + icon: "size-9", + "icon-xs": "size-6 [&_svg:not([class*='size-'])]:size-3", + "icon-sm": "size-8", + "icon-lg": "size-10", + }, + }, + defaultVariants: { + variant: "default", + size: "default", + }, + } +) + +function Button({ + className, + variant = "default", + size = "default", + asChild = false, + ...props +}: React.ComponentProps<"button"> & + VariantProps & { + asChild?: boolean + }) { + const Comp = asChild ? Slot.Root : "button" + + return ( + + ) +} + +export { Button, buttonVariants } diff --git a/headless-rust/frontend/src/components/ui/card.tsx b/headless-rust/frontend/src/components/ui/card.tsx new file mode 100644 index 0000000..593879d --- /dev/null +++ b/headless-rust/frontend/src/components/ui/card.tsx @@ -0,0 +1,100 @@ +import * as React from "react" + +import { cn } from "@/lib/utils" + +function Card({ + className, + size = "default", + ...props +}: React.ComponentProps<"div"> & { size?: "default" | "sm" }) { + return ( +
img:first-child]:pt-0 data-[size=sm]:gap-4 data-[size=sm]:py-4 *:[img:first-child]:rounded-t-xl *:[img:last-child]:rounded-b-xl", + className + )} + {...props} + /> + ) +} + +function CardHeader({ className, ...props }: React.ComponentProps<"div">) { + return ( +
+ ) +} + +function CardTitle({ className, ...props }: React.ComponentProps<"div">) { + return ( +
+ ) +} + +function CardDescription({ className, ...props }: React.ComponentProps<"div">) { + return ( +
+ ) +} + +function CardAction({ className, ...props }: React.ComponentProps<"div">) { + return ( +
+ ) +} + +function CardContent({ className, ...props }: React.ComponentProps<"div">) { + return ( +
+ ) +} + +function CardFooter({ className, ...props }: React.ComponentProps<"div">) { + return ( +
+ ) +} + +export { + Card, + CardHeader, + CardFooter, + CardTitle, + CardAction, + CardDescription, + CardContent, +} diff --git a/headless-rust/frontend/src/components/ui/checkbox.tsx b/headless-rust/frontend/src/components/ui/checkbox.tsx new file mode 100644 index 0000000..3eb403b --- /dev/null +++ b/headless-rust/frontend/src/components/ui/checkbox.tsx @@ -0,0 +1,31 @@ +import * as React from "react" +import { Checkbox as CheckboxPrimitive } from "radix-ui" + +import { cn } from "@/lib/utils" +import { HugeiconsIcon } from "@hugeicons/react" +import { Tick02Icon } from "@hugeicons/core-free-icons" + +function Checkbox({ + className, + ...props +}: React.ComponentProps) { + return ( + + + + + + ) +} + +export { Checkbox } diff --git a/headless-rust/frontend/src/components/ui/collapsible.tsx b/headless-rust/frontend/src/components/ui/collapsible.tsx new file mode 100644 index 0000000..63fc8ef --- /dev/null +++ b/headless-rust/frontend/src/components/ui/collapsible.tsx @@ -0,0 +1,31 @@ +import { Collapsible as CollapsiblePrimitive } from "radix-ui" + +function Collapsible({ + ...props +}: React.ComponentProps) { + return +} + +function CollapsibleTrigger({ + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function CollapsibleContent({ + ...props +}: React.ComponentProps) { + return ( + + ) +} + +export { Collapsible, CollapsibleTrigger, CollapsibleContent } diff --git a/headless-rust/frontend/src/components/ui/dialog.tsx b/headless-rust/frontend/src/components/ui/dialog.tsx new file mode 100644 index 0000000..545c411 --- /dev/null +++ b/headless-rust/frontend/src/components/ui/dialog.tsx @@ -0,0 +1,166 @@ +import * as React from "react" +import { Dialog as DialogPrimitive } from "radix-ui" + +import { cn } from "@/lib/utils" +import { Button } from "@/components/ui/button" +import { HugeiconsIcon } from "@hugeicons/react" +import { Cancel01Icon } from "@hugeicons/core-free-icons" + +function Dialog({ + ...props +}: React.ComponentProps) { + return +} + +function DialogTrigger({ + ...props +}: React.ComponentProps) { + return +} + +function DialogPortal({ + ...props +}: React.ComponentProps) { + return +} + +function DialogClose({ + ...props +}: React.ComponentProps) { + return +} + +function DialogOverlay({ + className, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function DialogContent({ + className, + children, + showCloseButton = true, + ...props +}: React.ComponentProps & { + showCloseButton?: boolean +}) { + return ( + + + + {children} + {showCloseButton && ( + + + + )} + + + ) +} + +function DialogHeader({ className, ...props }: React.ComponentProps<"div">) { + return ( +
+ ) +} + +function DialogFooter({ + className, + showCloseButton = false, + children, + ...props +}: React.ComponentProps<"div"> & { + showCloseButton?: boolean +}) { + return ( +
+ {children} + {showCloseButton && ( + + + + )} +
+ ) +} + +function DialogTitle({ + className, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function DialogDescription({ + className, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +export { + Dialog, + DialogClose, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogOverlay, + DialogPortal, + DialogTitle, + DialogTrigger, +} diff --git a/headless-rust/frontend/src/components/ui/input.tsx b/headless-rust/frontend/src/components/ui/input.tsx new file mode 100644 index 0000000..e49996f --- /dev/null +++ b/headless-rust/frontend/src/components/ui/input.tsx @@ -0,0 +1,19 @@ +import * as React from "react" + +import { cn } from "@/lib/utils" + +function Input({ className, type, ...props }: React.ComponentProps<"input">) { + return ( + + ) +} + +export { Input } diff --git a/headless-rust/frontend/src/components/ui/label.tsx b/headless-rust/frontend/src/components/ui/label.tsx new file mode 100644 index 0000000..f752f82 --- /dev/null +++ b/headless-rust/frontend/src/components/ui/label.tsx @@ -0,0 +1,22 @@ +import * as React from "react" +import { Label as LabelPrimitive } from "radix-ui" + +import { cn } from "@/lib/utils" + +function Label({ + className, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +export { Label } diff --git a/headless-rust/frontend/src/components/ui/progress.tsx b/headless-rust/frontend/src/components/ui/progress.tsx new file mode 100644 index 0000000..0bcb123 --- /dev/null +++ b/headless-rust/frontend/src/components/ui/progress.tsx @@ -0,0 +1,29 @@ +import * as React from "react" +import { Progress as ProgressPrimitive } from "radix-ui" + +import { cn } from "@/lib/utils" + +function Progress({ + className, + value, + ...props +}: React.ComponentProps) { + return ( + + + + ) +} + +export { Progress } diff --git a/headless-rust/frontend/src/components/ui/scroll-area.tsx b/headless-rust/frontend/src/components/ui/scroll-area.tsx new file mode 100644 index 0000000..f49b0a8 --- /dev/null +++ b/headless-rust/frontend/src/components/ui/scroll-area.tsx @@ -0,0 +1,53 @@ +import * as React from "react" +import { ScrollArea as ScrollAreaPrimitive } from "radix-ui" + +import { cn } from "@/lib/utils" + +function ScrollArea({ + className, + children, + ...props +}: React.ComponentProps) { + return ( + + + {children} + + + + + ) +} + +function ScrollBar({ + className, + orientation = "vertical", + ...props +}: React.ComponentProps) { + return ( + + + + ) +} + +export { ScrollArea, ScrollBar } diff --git a/headless-rust/frontend/src/components/ui/select.tsx b/headless-rust/frontend/src/components/ui/select.tsx new file mode 100644 index 0000000..f3b0139 --- /dev/null +++ b/headless-rust/frontend/src/components/ui/select.tsx @@ -0,0 +1,192 @@ +import * as React from "react" +import { Select as SelectPrimitive } from "radix-ui" + +import { cn } from "@/lib/utils" +import { HugeiconsIcon } from "@hugeicons/react" +import { UnfoldMoreIcon, Tick02Icon, ArrowUp01Icon, ArrowDown01Icon } from "@hugeicons/core-free-icons" + +function Select({ + ...props +}: React.ComponentProps) { + return +} + +function SelectGroup({ + className, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function SelectValue({ + ...props +}: React.ComponentProps) { + return +} + +function SelectTrigger({ + className, + size = "default", + children, + ...props +}: React.ComponentProps & { + size?: "sm" | "default" +}) { + return ( + + {children} + + + + + ) +} + +function SelectContent({ + className, + children, + position = "item-aligned", + align = "center", + ...props +}: React.ComponentProps) { + return ( + + + + + {children} + + + + + ) +} + +function SelectLabel({ + className, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function SelectItem({ + className, + children, + ...props +}: React.ComponentProps) { + return ( + + + + + + + {children} + + ) +} + +function SelectSeparator({ + className, + ...props +}: React.ComponentProps) { + return ( + + ) +} + +function SelectScrollUpButton({ + className, + ...props +}: React.ComponentProps) { + return ( + + + + ) +} + +function SelectScrollDownButton({ + className, + ...props +}: React.ComponentProps) { + return ( + + + + ) +} + +export { + Select, + SelectContent, + SelectGroup, + SelectItem, + SelectLabel, + SelectScrollDownButton, + SelectScrollUpButton, + SelectSeparator, + SelectTrigger, + SelectValue, +} diff --git a/headless-rust/frontend/src/components/ui/skeleton.tsx b/headless-rust/frontend/src/components/ui/skeleton.tsx new file mode 100644 index 0000000..ed70d9e --- /dev/null +++ b/headless-rust/frontend/src/components/ui/skeleton.tsx @@ -0,0 +1,12 @@ +import { cn } from "@/lib/utils"; + +function Skeleton({ className, ...props }: React.HTMLAttributes) { + return ( +
+ ); +} + +export { Skeleton }; diff --git a/headless-rust/frontend/src/components/ui/slider.tsx b/headless-rust/frontend/src/components/ui/slider.tsx new file mode 100644 index 0000000..5a4db16 --- /dev/null +++ b/headless-rust/frontend/src/components/ui/slider.tsx @@ -0,0 +1,57 @@ +import * as React from "react" +import { Slider as SliderPrimitive } from "radix-ui" + +import { cn } from "@/lib/utils" + +function Slider({ + className, + defaultValue, + value, + min = 0, + max = 100, + ...props +}: React.ComponentProps) { + const _values = React.useMemo( + () => + Array.isArray(value) + ? value + : Array.isArray(defaultValue) + ? defaultValue + : [min, max], + [value, defaultValue, min, max] + ) + + return ( + + + + + {Array.from({ length: _values.length }, (_, index) => ( + + ))} + + ) +} + +export { Slider } diff --git a/headless-rust/frontend/src/components/ui/sonner.tsx b/headless-rust/frontend/src/components/ui/sonner.tsx new file mode 100644 index 0000000..bd6eb71 --- /dev/null +++ b/headless-rust/frontend/src/components/ui/sonner.tsx @@ -0,0 +1,48 @@ +import { useTheme } from "next-themes" +import { Toaster as Sonner, type ToasterProps } from "sonner" +import { HugeiconsIcon } from "@hugeicons/react" +import { CheckmarkCircle02Icon, InformationCircleIcon, Alert02Icon, MultiplicationSignCircleIcon, Loading03Icon } from "@hugeicons/core-free-icons" + +const Toaster = ({ ...props }: ToasterProps) => { + const { theme = "system" } = useTheme() + + return ( + + ), + info: ( + + ), + warning: ( + + ), + error: ( + + ), + loading: ( + + ), + }} + style={ + { + "--normal-bg": "var(--popover)", + "--normal-text": "var(--popover-foreground)", + "--normal-border": "var(--border)", + "--border-radius": "var(--radius)", + } as React.CSSProperties + } + toastOptions={{ + classNames: { + toast: "cn-toast", + }, + }} + {...props} + /> + ) +} + +export { Toaster } diff --git a/headless-rust/frontend/src/components/ui/switch.tsx b/headless-rust/frontend/src/components/ui/switch.tsx new file mode 100644 index 0000000..134e8e2 --- /dev/null +++ b/headless-rust/frontend/src/components/ui/switch.tsx @@ -0,0 +1,31 @@ +import * as React from "react" +import { Switch as SwitchPrimitive } from "radix-ui" + +import { cn } from "@/lib/utils" + +function Switch({ + className, + size = "default", + ...props +}: React.ComponentProps & { + size?: "sm" | "default" +}) { + return ( + + + + ) +} + +export { Switch } diff --git a/headless-rust/frontend/src/components/ui/toggle-group.tsx b/headless-rust/frontend/src/components/ui/toggle-group.tsx new file mode 100644 index 0000000..f62c08c --- /dev/null +++ b/headless-rust/frontend/src/components/ui/toggle-group.tsx @@ -0,0 +1,89 @@ +"use client" + +import * as React from "react" +import { type VariantProps } from "class-variance-authority" +import { ToggleGroup as ToggleGroupPrimitive } from "radix-ui" + +import { cn } from "@/lib/utils" +import { toggleVariants } from "@/components/ui/toggle" + +const ToggleGroupContext = React.createContext< + VariantProps & { + spacing?: number + orientation?: "horizontal" | "vertical" + } +>({ + size: "default", + variant: "default", + spacing: 0, + orientation: "horizontal", +}) + +function ToggleGroup({ + className, + variant, + size, + spacing = 0, + orientation = "horizontal", + children, + ...props +}: React.ComponentProps & + VariantProps & { + spacing?: number + orientation?: "horizontal" | "vertical" + }) { + return ( + + + {children} + + + ) +} + +function ToggleGroupItem({ + className, + children, + variant = "default", + size = "default", + ...props +}: React.ComponentProps & + VariantProps) { + const context = React.useContext(ToggleGroupContext) + + return ( + + {children} + + ) +} + +export { ToggleGroup, ToggleGroupItem } diff --git a/headless-rust/frontend/src/components/ui/toggle.tsx b/headless-rust/frontend/src/components/ui/toggle.tsx new file mode 100644 index 0000000..15b3df4 --- /dev/null +++ b/headless-rust/frontend/src/components/ui/toggle.tsx @@ -0,0 +1,45 @@ +import * as React from "react" +import { cva, type VariantProps } from "class-variance-authority" +import { Toggle as TogglePrimitive } from "radix-ui" + +import { cn } from "@/lib/utils" + +const toggleVariants = cva( + "group/toggle inline-flex items-center justify-center gap-1 rounded-4xl text-sm font-medium whitespace-nowrap transition-colors outline-none hover:bg-muted hover:text-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 aria-pressed:bg-muted dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4", + { + variants: { + variant: { + default: "bg-transparent", + outline: "border border-input bg-transparent hover:bg-muted", + }, + size: { + default: + "h-9 min-w-9 px-3 has-data-[icon=inline-end]:pr-2.5 has-data-[icon=inline-start]:pl-2.5", + sm: "h-8 min-w-8 px-3 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2", + lg: "h-10 min-w-10 px-4 has-data-[icon=inline-end]:pr-3 has-data-[icon=inline-start]:pl-3", + }, + }, + defaultVariants: { + variant: "default", + size: "default", + }, + } +) + +function Toggle({ + className, + variant = "default", + size = "default", + ...props +}: React.ComponentProps & + VariantProps) { + return ( + + ) +} + +export { Toggle, toggleVariants } diff --git a/headless-rust/frontend/src/hooks/useBackendEvent.ts b/headless-rust/frontend/src/hooks/useBackendEvent.ts new file mode 100644 index 0000000..9d122ea --- /dev/null +++ b/headless-rust/frontend/src/hooks/useBackendEvent.ts @@ -0,0 +1,30 @@ +import { useEffect, useRef } from "react"; +import { rpcClient } from "@/lib/rpc"; +import type { SpeedcameraRPC } from "@/shared/types"; + +type PushMessageMap = SpeedcameraRPC["webview"]["messages"]; + +/** + * Reusable hook to subscribe to backend WebSocket broadcast events + * with automatic unbind / cleanup on unmount. + * + * @param event The event name to subscribe to + * @param handler Callback invoked whenever the backend emits the event + */ +export function useBackendEvent( + event: K, + handler: (payload: K extends keyof PushMessageMap ? PushMessageMap[K] : boolean) => void +) { + const handlerRef = useRef(handler); + handlerRef.current = handler; + + useEffect(() => { + const unsubscribe = rpcClient.on(event, (payload) => { + handlerRef.current(payload); + }); + + return () => { + unsubscribe(); + }; + }, [event]); +} diff --git a/headless-rust/frontend/src/hooks/useLiveLapTimer.ts b/headless-rust/frontend/src/hooks/useLiveLapTimer.ts new file mode 100644 index 0000000..f2d4171 --- /dev/null +++ b/headless-rust/frontend/src/hooks/useLiveLapTimer.ts @@ -0,0 +1,27 @@ +import { useState, useEffect } from "react"; +import { useAppStore } from "@/stores/useAppStore"; + +/** + * Returns the elapsed milliseconds for the current lap being timed, + * updated every 50 ms. Returns null when not actively timing. + */ +export function useLiveLapTimer(): number | null { + const lapState = useAppStore((s) => s.lapState); + const lapTimingStartedAt = useAppStore((s) => s.lapTimingStartedAt); + const [elapsed, setElapsed] = useState(null); + + useEffect(() => { + if (lapState !== "timing" || !lapTimingStartedAt) { + setElapsed(null); + return; + } + // Tick immediately, then every 50 ms + setElapsed(Date.now() - lapTimingStartedAt); + const id = setInterval(() => { + setElapsed(Date.now() - lapTimingStartedAt); + }, 50); + return () => clearInterval(id); + }, [lapState, lapTimingStartedAt]); + + return elapsed; +} diff --git a/headless-rust/frontend/src/hooks/useSystemStateSync.ts b/headless-rust/frontend/src/hooks/useSystemStateSync.ts new file mode 100644 index 0000000..dc4ece0 --- /dev/null +++ b/headless-rust/frontend/src/hooks/useSystemStateSync.ts @@ -0,0 +1,33 @@ +import { useEffect } from "react"; +import { useAppStore } from "@/stores/useAppStore"; + +/** + * Watches the conditions required for system operation and automatically + * transitions between PASSIVE and DISARMED. Must be mounted once at the root. + * + * PASSIVE → DISARMED : all conditions become satisfied + * DISARMED → PASSIVE : any condition is lost + * ARMED → PASSIVE : any condition is lost (also disarms) + */ +export function useSystemStateSync() { + const systemState = useAppStore((s) => s.systemState); + const setSystemState = useAppStore((s) => s.setSystemState); + const isArmed = useAppStore((s) => s.isArmed); + const connectedPort = useAppStore((s) => s.connectedPort); + const cameraConnected = useAppStore((s) => s.cameraConnected); + + const conditionsMet = !!connectedPort && cameraConnected; + + useEffect(() => { + if (conditionsMet) { + const targetState = isArmed ? "ARMED" : "DISARMED"; + if (systemState !== targetState) { + setSystemState(targetState); + } + } else { + if (systemState !== "PASSIVE") { + setSystemState("PASSIVE"); + } + } + }, [conditionsMet, isArmed, systemState, setSystemState]); +} diff --git a/headless-rust/frontend/src/index.css b/headless-rust/frontend/src/index.css new file mode 100644 index 0000000..d2d6a02 --- /dev/null +++ b/headless-rust/frontend/src/index.css @@ -0,0 +1,135 @@ +@import "tailwindcss"; +@import "tw-animate-css"; +@import "shadcn/tailwind.css"; +@import "@fontsource-variable/figtree"; +@source ".."; + +@tailwind base; +@tailwind components; +@tailwind utilities; + +@custom-variant dark (&:is(.dark *)); + +@theme inline { + --font-heading: var(--font-sans); + --font-sans: 'Figtree Variable', sans-serif; + --color-sidebar-ring: var(--sidebar-ring); + --color-sidebar-border: var(--sidebar-border); + --color-sidebar-accent-foreground: var(--sidebar-accent-foreground); + --color-sidebar-accent: var(--sidebar-accent); + --color-sidebar-primary-foreground: var(--sidebar-primary-foreground); + --color-sidebar-primary: var(--sidebar-primary); + --color-sidebar-foreground: var(--sidebar-foreground); + --color-sidebar: var(--sidebar); + --color-chart-5: var(--chart-5); + --color-chart-4: var(--chart-4); + --color-chart-3: var(--chart-3); + --color-chart-2: var(--chart-2); + --color-chart-1: var(--chart-1); + --color-ring: var(--ring); + --color-input: var(--input); + --color-border: var(--border); + --color-destructive: var(--destructive); + --color-accent-foreground: var(--accent-foreground); + --color-accent: var(--accent); + --color-muted-foreground: var(--muted-foreground); + --color-muted: var(--muted); + --color-secondary-foreground: var(--secondary-foreground); + --color-secondary: var(--secondary); + --color-primary-foreground: var(--primary-foreground); + --color-primary: var(--primary); + --color-popover-foreground: var(--popover-foreground); + --color-popover: var(--popover); + --color-card-foreground: var(--card-foreground); + --color-card: var(--card); + --color-foreground: var(--foreground); + --color-background: var(--background); + --radius-sm: calc(var(--radius) * 0.6); + --radius-md: calc(var(--radius) * 0.8); + --radius-lg: var(--radius); + --radius-xl: calc(var(--radius) * 1.4); + --radius-2xl: calc(var(--radius) * 1.8); + --radius-3xl: calc(var(--radius) * 2.2); + --radius-4xl: calc(var(--radius) * 2.6); +} + +:root { + --background: oklch(1 0 0); + --foreground: oklch(0.141 0.005 285.823); + --card: oklch(1 0 0); + --card-foreground: oklch(0.141 0.005 285.823); + --popover: oklch(1 0 0); + --popover-foreground: oklch(0.141 0.005 285.823); + --primary: oklch(0.21 0.006 285.885); + --primary-foreground: oklch(0.985 0 0); + --secondary: oklch(0.967 0.001 286.375); + --secondary-foreground: oklch(0.21 0.006 285.885); + --muted: oklch(0.967 0.001 286.375); + --muted-foreground: oklch(0.552 0.016 285.938); + --accent: oklch(0.967 0.001 286.375); + --accent-foreground: oklch(0.21 0.006 285.885); + --destructive: oklch(0.577 0.245 27.325); + --border: oklch(0.92 0.004 286.32); + --input: oklch(0.92 0.004 286.32); + --ring: oklch(0.705 0.015 286.067); + --chart-1: oklch(0.871 0.006 286.286); + --chart-2: oklch(0.552 0.016 285.938); + --chart-3: oklch(0.442 0.017 285.786); + --chart-4: oklch(0.37 0.013 285.805); + --chart-5: oklch(0.274 0.006 286.033); + --radius: 0.625rem; + --sidebar: oklch(0.985 0 0); + --sidebar-foreground: oklch(0.141 0.005 285.823); + --sidebar-primary: oklch(0.21 0.006 285.885); + --sidebar-primary-foreground: oklch(0.985 0 0); + --sidebar-accent: oklch(0.967 0.001 286.375); + --sidebar-accent-foreground: oklch(0.21 0.006 285.885); + --sidebar-border: oklch(0.92 0.004 286.32); + --sidebar-ring: oklch(0.705 0.015 286.067); +} + +.dark { + --background: oklch(0.141 0.005 285.823); + --foreground: oklch(0.985 0 0); + --card: oklch(0.21 0.006 285.885); + --card-foreground: oklch(0.985 0 0); + --popover: oklch(0.21 0.006 285.885); + --popover-foreground: oklch(0.985 0 0); + --primary: oklch(0.92 0.004 286.32); + --primary-foreground: oklch(0.21 0.006 285.885); + --secondary: oklch(0.274 0.006 286.033); + --secondary-foreground: oklch(0.985 0 0); + --muted: oklch(0.274 0.006 286.033); + --muted-foreground: oklch(0.705 0.015 286.067); + --accent: oklch(0.274 0.006 286.033); + --accent-foreground: oklch(0.985 0 0); + --destructive: oklch(0.704 0.191 22.216); + --border: oklch(1 0 0 / 10%); + --input: oklch(1 0 0 / 15%); + --ring: oklch(0.552 0.016 285.938); + --chart-1: oklch(0.871 0.006 286.286); + --chart-2: oklch(0.552 0.016 285.938); + --chart-3: oklch(0.442 0.017 285.786); + --chart-4: oklch(0.37 0.013 285.805); + --chart-5: oklch(0.274 0.006 286.033); + --sidebar: oklch(0.21 0.006 285.885); + --sidebar-foreground: oklch(0.985 0 0); + --sidebar-primary: oklch(0.488 0.243 264.376); + --sidebar-primary-foreground: oklch(0.985 0 0); + --sidebar-accent: oklch(0.274 0.006 286.033); + --sidebar-accent-foreground: oklch(0.985 0 0); + --sidebar-border: oklch(1 0 0 / 10%); + --sidebar-ring: oklch(0.552 0.016 285.938); +} + +@layer base { + * { + @apply border-border outline-ring/50; + } + body { + @apply bg-background text-foreground; + } + html { + @apply font-sans; + } +} diff --git a/headless-rust/frontend/src/lib/format.ts b/headless-rust/frontend/src/lib/format.ts new file mode 100644 index 0000000..e2ebb7d --- /dev/null +++ b/headless-rust/frontend/src/lib/format.ts @@ -0,0 +1,26 @@ +export function formatDuration(ms: number): string { + const total = Math.round(ms); + const totalSeconds = Math.floor(total / 1000); + const minutes = Math.floor(totalSeconds / 60); + const seconds = totalSeconds % 60; + const millis = total % 1000; + return `${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}.${String(millis).padStart(3, "0")}`; +} + +export function formatTimestamp(ts: number): string { + return new Date(ts).toLocaleTimeString(undefined, { + hour: "2-digit", + minute: "2-digit", + second: "2-digit", + }); +} + +export function formatSessionDate(iso: string): string { + return new Date(iso).toLocaleString(undefined, { + year: "numeric", + month: "short", + day: "numeric", + hour: "2-digit", + minute: "2-digit", + }); +} diff --git a/headless-rust/frontend/src/lib/rpc.ts b/headless-rust/frontend/src/lib/rpc.ts new file mode 100644 index 0000000..c4575c3 --- /dev/null +++ b/headless-rust/frontend/src/lib/rpc.ts @@ -0,0 +1,335 @@ +import type { SpeedcameraRPC, Violation, SerialStatusPayload, CameraStatusPayload, FlashProgressPayload } from "@/shared/types"; +import { useAppStore } from "@/stores/useAppStore"; +import { io, Socket } from "socket.io-client"; +import { toast } from "sonner"; + +type RequestMap = SpeedcameraRPC["bun"]["requests"]; +type PushMessageMap = SpeedcameraRPC["webview"]["messages"]; + +export type SpeedcameraClientRPC = { + request: { + [K in keyof RequestMap]: ( + params: RequestMap[K]["params"] + ) => Promise; + }; +}; + +type EventCallback = (payload: T) => void; + +class SocketIoRpcClient { + private socket: Socket; + private listeners = new Map>(); + private heartbeatInterval: ReturnType | null = null; + private missedHeartbeats = 0; + private isProbing = false; + + constructor() { + const socketUrl = this.getSocketUrl(); + this.socket = io(socketUrl, { + transports: ["websocket", "polling"], + upgrade: true, + reconnection: true, + reconnectionAttempts: Infinity, + reconnectionDelay: 500, + reconnectionDelayMax: 5000, + randomizationFactor: 0.2, + timeout: 20000, + autoConnect: true, + }); + + this.setupListeners(); + this.setupLifecycleListeners(); + } + + private getSocketUrl(): string { + if (typeof window === "undefined") return "http://127.0.0.1:3000"; + return window.location.origin; + } + + private setupListeners() { + this.socket.on("connect", () => { + console.log(`[rpc-client] Socket.io connected (id: ${this.socket.id}, transport: ${this.socket.io.engine?.transport?.name})`); + this.missedHeartbeats = 0; + this.emit("connectionChange", true); + this.startHeartbeat(); + + // Resync state on connection / reconnection + const store = useAppStore.getState(); + void store.refreshCameraStatus?.(); + void store.refreshSerialStatus?.(); + void store.refreshArmedStatus?.(); + }); + + this.socket.on("disconnect", (reason) => { + console.log(`[rpc-client] Socket.io disconnected (reason: ${reason})`); + this.stopHeartbeat(); + this.emit("connectionChange", false); + this.emit("heartbeat" as any, { connected: false, latencyMs: null, degraded: true }); + + // If disconnected by transport close or server disconnect, proactively attempt reconnect + if (reason === "io server disconnect" || reason === "transport close") { + this.socket.connect(); + } + }); + + this.socket.on("connect_error", (err) => { + console.warn("[rpc-client] Socket.io connection error:", err.message); + }); + + // Server push events + this.socket.on("serialStatus", (payload: SerialStatusPayload) => { + this.handlePushEvent("serialStatus", payload); + }); + + this.socket.on("cameraStatus", (payload: CameraStatusPayload) => { + this.handlePushEvent("cameraStatus", payload); + }); + + this.socket.on("liveFrame", (payload: string) => { + this.handlePushEvent("liveFrame", payload); + }); + + this.socket.on("violation", (payload: Violation) => { + this.handlePushEvent("violation", payload); + }); + + this.socket.on("flashProgress", (payload: FlashProgressPayload) => { + this.handlePushEvent("flashProgress", payload); + }); + + this.socket.on("armedStatus", (payload: { armed: boolean }) => { + this.handlePushEvent("armedStatus", payload); + }); + } + + /** + * Monitor browser lifecycle events (tab switching, screen sleep/wake, Wi-Fi reconnect) + * to immediately wake and verify the socket instead of waiting for OS TCP timeouts. + */ + private setupLifecycleListeners() { + if (typeof window === "undefined" || typeof document === "undefined") return; + + // 1. Tab visibility / device wake + document.addEventListener("visibilitychange", () => { + if (document.visibilityState === "visible") { + console.log("[rpc-client] Tab became active — verifying connection liveness"); + if (!this.socket.connected) { + this.socket.connect(); + } else { + void this.probeAndRecover(); + } + } + }); + + // 2. Network adapter online event (Wi-Fi reconnected) + window.addEventListener("online", () => { + console.log("[rpc-client] Wi-Fi / network online event triggered"); + if (!this.socket.connected) { + this.socket.connect(); + } else { + void this.probeAndRecover(); + } + }); + + // 3. Window focus + window.addEventListener("focus", () => { + if (!this.socket.connected) { + this.socket.connect(); + } + }); + + // 4. Back-forward cache restore + window.addEventListener("pageshow", () => { + if (!this.socket.connected) { + this.socket.connect(); + } + }); + } + + private async probeAndRecover() { + if (this.isProbing) return; + this.isProbing = true; + try { + if (!this.socket.connected) { + this.socket.connect(); + return; + } + await this.socket.timeout(5000).emitWithAck("ping"); + this.missedHeartbeats = 0; + } catch (_) { + console.warn("[rpc-client] Zombie connection detected during wake probe — resetting socket"); + this.socket.disconnect().connect(); + } finally { + this.isProbing = false; + } + } + + private startHeartbeat() { + this.stopHeartbeat(); + // 2000ms active heartbeat with 5s timeout: + // 1. Sends continuous micro-packets to prevent 802.11 Wi-Fi DTIM sleep + // 2. Real-time RTT latency telemetry + // 3. Resilient tolerance (4 missed heartbeats) to prevent disconnect storms during Wi-Fi jitter + this.heartbeatInterval = setInterval(async () => { + if (!this.socket.connected) return; + const start = performance.now(); + try { + await this.socket.timeout(5000).emitWithAck("ping"); + const rtt = Math.round(performance.now() - start); + this.missedHeartbeats = 0; + this.emit("heartbeat" as any, { connected: true, latencyMs: rtt, degraded: rtt > 250 }); + } catch (_) { + this.missedHeartbeats++; + if (this.missedHeartbeats >= 4) { + this.emit("heartbeat" as any, { connected: false, latencyMs: null, degraded: true }); + console.warn("[rpc-client] Missed 4 heartbeats (Wi-Fi queue stall) — resetting socket transport"); + this.socket.disconnect().connect(); + } + } + }, 2000); + } + + private stopHeartbeat() { + if (this.heartbeatInterval) { + clearInterval(this.heartbeatInterval); + this.heartbeatInterval = null; + } + } + + public on( + event: K, + callback: EventCallback + ): () => void { + if (!this.listeners.has(event)) { + this.listeners.set(event, new Set()); + } + this.listeners.get(event)!.add(callback); + + // Return unbind function for clean useEffect hook integration + return () => { + this.off(event, callback); + }; + } + + public off( + event: K, + callback: EventCallback + ) { + const set = this.listeners.get(event); + if (set) { + set.delete(callback); + if (set.size === 0) { + this.listeners.delete(event); + } + } + } + + private emit( + event: K, + payload: K extends keyof PushMessageMap ? PushMessageMap[K] : boolean + ) { + const set = this.listeners.get(event); + if (set) { + for (const callback of set) { + try { + callback(payload); + } catch (err) { + console.error(`[rpc-client] Error in listener for '${String(event)}':`, err); + } + } + } + } + + private handlePushEvent(event: K, payload: PushMessageMap[K]) { + // 1. Notify global Zustand store + const store = useAppStore.getState(); + switch (event) { + case "serialStatus": { + const serialPayload = payload as SerialStatusPayload; + if (serialPayload?.status === "CONNECTED") { + const port = serialPayload.port || store.selectedPort || "connected"; + store.setConnectedPort(port); + if (serialPayload.port) store.setSelectedPort(serialPayload.port); + } else if (serialPayload?.status === "DISCONNECTED") { + store.setConnectedPort(""); + } + store.handleSerialStatus(serialPayload); + break; + } + case "cameraStatus": { + const camPayload = payload as CameraStatusPayload; + store.setCameraStatus(camPayload); + break; + } + case "liveFrame": + store.setLiveFrame(payload as string); + break; + case "violation": { + const violationPayload = payload as Violation; + store.setLastViolation(violationPayload); + toast.error( + `⚡ Violation recorded: ${violationPayload.measuredSpeed} km/h (Limit: ${violationPayload.maxSpeed} km/h)`, + { + description: `Captured at ${new Date(violationPayload.timestamp).toLocaleTimeString()}`, + duration: 4000, + } + ); + break; + } + case "flashProgress": + store.handleFlashProgress(payload as FlashProgressPayload); + break; + case "armedStatus": { + const armedPayload = payload as { armed: boolean }; + store.handleArmedStatus(armedPayload.armed); + break; + } + case "updateAvailable": + store.setUpdateVersion((payload as any).version); + store.setUpdatePhase("ready"); + break; + case "updateProgress": + store.handleUpdateProgress(payload as any); + break; + default: + break; + } + + // 2. Dispatch to custom pub-sub event listeners + this.emit(event, payload); + } + + public async call(method: string, params: any): Promise { + try { + const response: any = await this.socket.timeout(10000).emitWithAck("rpc", { method, params }); + if (response && response.error) { + throw new Error(response.error); + } + return response?.result; + } catch (err: any) { + if (err?.name === "TimeoutError" || err?.message?.includes("timeout")) { + throw new Error(`RPC request '${method}' timed out after 10000ms`); + } + throw err; + } + } + + public getRawSocket(): Socket { + return this.socket; + } +} + +export const rpcClient = new SocketIoRpcClient(); + +// Proxy accessor so `getRpc().request.someMethod(params)` works transparently +const rpcProxy: SpeedcameraClientRPC = { + request: new Proxy({} as any, { + get(_target, prop: string) { + return (params: any = {}) => rpcClient.call(prop, params); + }, + }), +}; + +export function getRpc(): SpeedcameraClientRPC { + return rpcProxy; +} diff --git a/headless-rust/frontend/src/lib/sound.ts b/headless-rust/frontend/src/lib/sound.ts new file mode 100644 index 0000000..5e3aaf8 --- /dev/null +++ b/headless-rust/frontend/src/lib/sound.ts @@ -0,0 +1,44 @@ +let _ctx: AudioContext | null = null; + +function getAudioContext(): AudioContext { + if (!_ctx) { + _ctx = new AudioContext(); + } + return _ctx; +} + +export function playBeep(frequency = 880, duration = 0.15, volume = 0.4): void { + try { + const ctx = getAudioContext(); + + if (ctx.state === "suspended") { + ctx.resume().catch(() => {/* ignore */}); + } + + const oscillator = ctx.createOscillator(); + const gainNode = ctx.createGain(); + + oscillator.connect(gainNode); + gainNode.connect(ctx.destination); + + oscillator.type = "sine"; + oscillator.frequency.setValueAtTime(frequency, ctx.currentTime); + + gainNode.gain.setValueAtTime(0, ctx.currentTime); + gainNode.gain.linearRampToValueAtTime(volume, ctx.currentTime + 0.01); + gainNode.gain.linearRampToValueAtTime(0, ctx.currentTime + duration); + + oscillator.start(ctx.currentTime); + oscillator.stop(ctx.currentTime + duration + 0.01); + } catch (err) { + console.warn("[sound] playBeep failed:", err); + } +} + +export function resumeAudioContext(): void { + try { + getAudioContext().resume().catch(() => {/* ignore */}); + } catch { + /* ignore */ + } +} diff --git a/headless-rust/frontend/src/lib/utils.ts b/headless-rust/frontend/src/lib/utils.ts new file mode 100644 index 0000000..a5ef193 --- /dev/null +++ b/headless-rust/frontend/src/lib/utils.ts @@ -0,0 +1,6 @@ +import { clsx, type ClassValue } from "clsx"; +import { twMerge } from "tailwind-merge"; + +export function cn(...inputs: ClassValue[]) { + return twMerge(clsx(inputs)); +} diff --git a/headless-rust/frontend/src/main.tsx b/headless-rust/frontend/src/main.tsx new file mode 100644 index 0000000..07c9565 --- /dev/null +++ b/headless-rust/frontend/src/main.tsx @@ -0,0 +1,13 @@ +import { StrictMode } from "react"; +import { createRoot } from "react-dom/client"; +import { ThemeProvider } from "next-themes"; +import "./index.css"; +import App from "./App"; + +createRoot(document.getElementById("root")!).render( + + + + + , +); diff --git a/headless-rust/frontend/src/routes/__root.tsx b/headless-rust/frontend/src/routes/__root.tsx new file mode 100644 index 0000000..c403c8e --- /dev/null +++ b/headless-rust/frontend/src/routes/__root.tsx @@ -0,0 +1,80 @@ +import { useEffect } from "react"; +import { Outlet, createRootRoute } from "@tanstack/react-router"; +import { NavigationMenu } from "@/components/NavigationMenu"; +import { ThemeToggle } from "@/components/ThemeToggle"; +import { useSystemStateSync } from "@/hooks/useSystemStateSync"; +import { useAppStore } from "@/stores/useAppStore"; +import { getRpc } from "@/lib/rpc"; + +export const RootRoute = createRootRoute({ + component: Root, +}); + +function Root() { + useSystemStateSync(); + const loadLapSettings = useAppStore((s) => s.loadLapSettings); + const loadTeableState = useAppStore((s) => s.loadTeableState); + const refreshCameraStatus = useAppStore((s) => s.refreshCameraStatus); + const refreshSerialStatus = useAppStore((s) => s.refreshSerialStatus); + const refreshArmedStatus = useAppStore((s) => s.refreshArmedStatus); + const loadCameraSettings = useAppStore((s) => s.loadCameraSettings); + const setSelectedPort = useAppStore((s) => s.setSelectedPort); + const setMaxSpeed = useAppStore((s) => s.setMaxSpeed); + const setLastViolation = useAppStore((s) => s.setLastViolation); + + useEffect(() => { + // 1. Load full persistent settings from database + getRpc() + .request.getSettings({}) + .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)); + + // 2. Hydrate hardware and system armed states + void refreshCameraStatus(); + void refreshSerialStatus(); + void refreshArmedStatus(); + void loadLapSettings(); + void loadTeableState(); + + // 3. Hydrate latest violation for instant preview on home screen + getRpc() + .request.getViolations({ page: 1, limit: 1 }) + .then((res) => { + if (res.violations && res.violations.length > 0) { + setLastViolation(res.violations[0]); + } + }) + .catch(() => {}); + }, [ + loadCameraSettings, + setSelectedPort, + setMaxSpeed, + refreshCameraStatus, + refreshSerialStatus, + refreshArmedStatus, + loadLapSettings, + loadTeableState, + setLastViolation, + ]); + + return ( +
+ {/* App-level navigation bar */} +
+ +
+ +
+
+ + {/* Page content */} +
+ +
+
+ ); +} diff --git a/headless-rust/frontend/src/routes/about.tsx b/headless-rust/frontend/src/routes/about.tsx new file mode 100644 index 0000000..6f185a3 --- /dev/null +++ b/headless-rust/frontend/src/routes/about.tsx @@ -0,0 +1,264 @@ +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. +

+
+ ); +} diff --git a/headless-rust/frontend/src/routes/index.tsx b/headless-rust/frontend/src/routes/index.tsx new file mode 100644 index 0000000..4560f2d --- /dev/null +++ b/headless-rust/frontend/src/routes/index.tsx @@ -0,0 +1,129 @@ +import { useEffect } from "react"; +import { createRoute } from "@tanstack/react-router"; +import { toast } from "sonner"; +import { RootRoute } from "./__root"; +import { LastCapturedImage } from "@/components/LastCapturedImage"; +import { StatusBadge } from "@/components/StatusBadge"; +import { ViolationCard } from "@/components/ViolationCard"; +import { ArmingButton } from "@/components/ArmingButton"; +import { LapTimerDisplay } from "@/components/LapTimerDisplay"; +import { useAppStore } from "@/stores/useAppStore"; +import { getRpc } from "@/lib/rpc"; +import { HugeiconsIcon } from "@hugeicons/react"; +import { ArrowUpBigIcon, ArrowDownBigIcon } from "@hugeicons/core-free-icons"; + +export const IndexRoute = createRoute({ + getParentRoute: () => RootRoute, + path: "/", + component: HomePage, +}); + +function HomePage() { + const connectedPort = useAppStore((s) => s.connectedPort); + const cameraConnected = useAppStore((s) => s.cameraConnected); + 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 currentLaps = useAppStore((s) => s.currentLaps); + + const serialStatus = connectedPort ? "connected" : "disconnected"; + const cameraStatus = cameraConnected ? "connected" : "unknown"; + + // 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 ( +
+ {/* Status bar */} +
+ + +
+ + {/* Content */} +
+ {/* Main: camera feed */} +
+ +
+ + {/* Side panel */} +
+ {appMode === "laptimer" ? ( + /* ── Lap timer panel ── */ + + ) : ( + /* ── Speed camera panel ── */ + <> + {/* Arming control — most important element */} + + + {/* Speed reading */} +
+ {lastSpeed !== null && lastDirection !== null && ( +

+ +

+ )} +
+

+ Current Speed +

+

+ {lastSpeed !== null ? lastSpeed : "—"} +

+ {lastSpeed !== null && ( +

km/h

+ )} +
+
+ + {/* Last violation */} +
+

+ Last Violation +

+ {lastViolation ? ( + + ) : ( +
+

No violations yet

+
+ )} +
+ + )} +
+
+
+ ); +} diff --git a/headless-rust/frontend/src/routes/laps.tsx b/headless-rust/frontend/src/routes/laps.tsx new file mode 100644 index 0000000..6d458a4 --- /dev/null +++ b/headless-rust/frontend/src/routes/laps.tsx @@ -0,0 +1,44 @@ +import { createRoute } from "@tanstack/react-router"; +import { Tabs as TabsPrimitive } from "radix-ui"; +import { RootRoute } from "./__root"; +import { cn } from "@/lib/utils"; +import { LiveSessionTab } from "./laps/LiveSessionTab"; +import { HistoryTab } from "./laps/HistoryTab"; + +export const LapsRoute = createRoute({ + getParentRoute: () => RootRoute, + path: "/laps", + component: LapsPage, +}); + +function LapsPage() { + return ( +
+ + + {(["live", "history"] as const).map((tab) => ( + + {tab === "live" ? "Live Session" : "History"} + + ))} + + + + + + + + + +
+ ); +} diff --git a/headless-rust/frontend/src/routes/laps/HistoryTab.tsx b/headless-rust/frontend/src/routes/laps/HistoryTab.tsx new file mode 100644 index 0000000..e99400b --- /dev/null +++ b/headless-rust/frontend/src/routes/laps/HistoryTab.tsx @@ -0,0 +1,110 @@ +import { useState, useEffect, useCallback } from "react"; +import { toast } from "sonner"; +import { HugeiconsIcon } from "@hugeicons/react"; +import { Clock01Icon } from "@hugeicons/core-free-icons"; +import { Button } from "@/components/ui/button"; +import { Skeleton } from "@/components/ui/skeleton"; +import { useAppStore } from "@/stores/useAppStore"; +import { SessionCard } from "./SessionCard"; + +const HISTORY_PAGE_SIZE = 10; + +export function HistoryTab() { + const lapHistory = useAppStore((s) => s.lapHistory); + const fetchLapHistory = useAppStore((s) => s.fetchLapHistory); + const deleteHistorySession = useAppStore((s) => s.deleteHistorySession); + + const [page, setPage] = useState(1); + const [loading, setLoading] = useState(false); + const [deletingId, setDeletingId] = useState(null); + + const totalPages = Math.max(1, Math.ceil(lapHistory.total / HISTORY_PAGE_SIZE)); + + const load = useCallback(async (p: number) => { + setLoading(true); + try { + await fetchLapHistory(p, HISTORY_PAGE_SIZE); + } catch { + toast.error("Failed to load lap history"); + } finally { + setLoading(false); + } + }, [fetchLapHistory]); + + useEffect(() => { + void load(page); + }, [load, page]); + + const handleDeleteSession = async (id: number) => { + if (!confirm("Delete this session and all its laps?")) return; + setDeletingId(id); + try { + await deleteHistorySession(id); + if (page > 1 && lapHistory.sessions.length === 1) { + setPage((p) => p - 1); + } + toast.success("Session deleted"); + } catch { + toast.error("Failed to delete session"); + } finally { + setDeletingId(null); + } + }; + + if (loading) { + return ( +
+ {Array.from({ length: 3 }).map((_, i) => ( + + ))} +
+ ); + } + + if (lapHistory.sessions.length === 0 && !loading) { + return ( +
+ +

No past sessions found.

+
+ ); + } + + return ( +
+ {lapHistory.sessions.map((session) => ( + handleDeleteSession(session.id)} + /> + ))} + + {/* Pagination */} + {totalPages > 1 && ( +
+ + + {page} / {totalPages} + + +
+ )} +
+ ); +} diff --git a/headless-rust/frontend/src/routes/laps/LapRow.tsx b/headless-rust/frontend/src/routes/laps/LapRow.tsx new file mode 100644 index 0000000..7ad4a96 --- /dev/null +++ b/headless-rust/frontend/src/routes/laps/LapRow.tsx @@ -0,0 +1,103 @@ +import { useState } from "react"; +import { toast } from "sonner"; +import { HugeiconsIcon } from "@hugeicons/react"; +import { Delete02Icon, CheckmarkCircle01Icon } from "@hugeicons/core-free-icons"; +import { cn } from "@/lib/utils"; +import { formatDuration, formatTimestamp } from "@/lib/format"; +import { useAppStore } from "@/stores/useAppStore"; +import { LapImageThumbnails } from "@/components/LapImageThumbnails"; +import type { Lap } from "@/shared/types"; + +interface LapRowProps { + lap: Lap; + isBest: boolean; + /** Show the hover-revealed delete button. Defaults to false (live session). */ + deletable?: boolean; + /** Override the default store-based deletion. Falls back to `deleteHistoryLap(lap.id)`. */ + onDelete?: () => Promise; +} + +/** + * Single lap table row used by both the live session table and the history + * session expansion. `deletable` opts in to the history-only delete affordance. + */ +export function LapRow({ lap, isBest, deletable = false, onDelete }: LapRowProps) { + const deleteHistoryLap = useAppStore((s) => s.deleteHistoryLap); + const [deleting, setDeleting] = useState(false); + + const handleDelete = async () => { + if (!confirm("Delete this lap?")) return; + setDeleting(true); + try { + if (onDelete) { + await onDelete(); + } else { + await deleteHistoryLap(lap.id); + } + } catch { + toast.error("Failed to delete lap"); + setDeleting(false); + } + }; + + const deleteButton = deletable && ( + + ); + + return ( + + +
+ {lap.lapNumber} + {isBest && ( + + )} +
+ + + + {formatDuration(lap.durationMs)} + + + + {lap.speedAtStart} km/h + + + {lap.speedAtEnd} km/h + + + {formatTimestamp(lap.startTimestamp)} + + + + + + ); +} diff --git a/headless-rust/frontend/src/routes/laps/LiveSessionTab.tsx b/headless-rust/frontend/src/routes/laps/LiveSessionTab.tsx new file mode 100644 index 0000000..5e52f5f --- /dev/null +++ b/headless-rust/frontend/src/routes/laps/LiveSessionTab.tsx @@ -0,0 +1,195 @@ +import { useState } from "react"; +import { toast } from "sonner"; +import { HugeiconsIcon } from "@hugeicons/react"; +import { PlayIcon, StopIcon, Timer01Icon } from "@hugeicons/core-free-icons"; +import { cn } from "@/lib/utils"; +import { formatDuration } from "@/lib/format"; +import { Button } from "@/components/ui/button"; +import { LapTimerDisplay } from "@/components/LapTimerDisplay"; +import { useAppStore } from "@/stores/useAppStore"; +import type { LapState } from "@/stores/slices/lapSlice"; +import { LapRow } from "./LapRow"; +import type { Lap } from "@/shared/types"; + +const LAP_TABLE_COLS = 6; + +const stateLabel: Record = { + idle: "Idle", + waiting: "Waiting for car…", + timing: "Timing…", +}; + +const stateColor: Record = { + idle: "text-muted-foreground", + waiting: "text-yellow-500 dark:text-yellow-400", + timing: "text-green-500 dark:text-green-400", +}; + +export function LiveSessionTab() { + const lapState = useAppStore((s) => s.lapState); + const currentSession = useAppStore((s) => s.currentSession); + const currentLaps = useAppStore((s) => s.currentLaps); + const lapSettings = useAppStore((s) => s.lapSettings); + const isLapSaving = useAppStore((s) => s.isLapSaving); + const startLapSession = useAppStore((s) => s.startLapSession); + const stopLapSession = useAppStore((s) => s.stopLapSession); + const connectedPort = useAppStore((s) => s.connectedPort); + + const [starting, setStarting] = useState(false); + const [stopping, setStopping] = useState(false); + + const canStart = !!connectedPort; + + const handleStart = async () => { + setStarting(true); + try { + await startLapSession(); + } catch { + toast.error("Failed to start lap session"); + } finally { + setStarting(false); + } + }; + + const handleStop = async () => { + setStopping(true); + try { + await stopLapSession(); + } catch { + toast.error("Failed to stop lap session"); + } finally { + setStopping(false); + } + }; + + // Find best lap (shortest duration) + const bestLapId = currentLaps.length > 0 + ? currentLaps.reduce((best, lap) => lap.durationMs < best.durationMs ? lap : best).id + : null; + + const empty = currentLaps.length === 0 && lapState === "idle" && !currentSession; + + return ( +
+ {/* Control bar */} +
+
+
+ + {stateLabel[lapState]} + + {isLapSaving && ( + Saving… + )} +
+

+ Mode: {lapSettings.lapMode === "single" ? "Single lap" : "Multi-lap"} + {currentSession && ( + <> · Session #{currentSession.id} + )} +

+
+ +
+ {lapState === "idle" ? ( + + ) : ( + + )} +
+
+ + {/* Laps table */} + {empty ? ( +
+ +

No active session. Press Start to begin.

+
+ ) : ( + <> + {/* Big running timer — always shown while session is active */} +
+ +
+ +
+ + + + + + + + + + + + + {currentLaps.length === 0 ? ( + + + + ) : ( + currentLaps.map((lap) => ( + + )) + )} + +
#DurationSpeed InSpeed OutStartImages
+ {lapState === "waiting" ? "Waiting for first car to pass…" : "Timing first lap…"} +
+
+ + )} + + {/* Summary */} + {currentLaps.length > 1 && ( + + )} +
+ ); +} + +function LapSummary({ laps }: { laps: Lap[] }) { + const best = laps.reduce((b, l) => l.durationMs < b.durationMs ? l : b); + const worst = laps.reduce((b, l) => l.durationMs > b.durationMs ? l : b); + const avg = laps.reduce((sum, l) => sum + l.durationMs, 0) / laps.length; + + return ( +
+ {[ + { label: "Best", value: formatDuration(best.durationMs), color: "text-green-600 dark:text-green-400" }, + { label: "Average", value: formatDuration(Math.round(avg)), color: "" }, + { label: "Worst", value: formatDuration(worst.durationMs), color: "text-red-500 dark:text-red-400" }, + ].map(({ label, value, color }) => ( +
+

{label}

+

{value}

+
+ ))} +
+ ); +} diff --git a/headless-rust/frontend/src/routes/laps/SessionCard.tsx b/headless-rust/frontend/src/routes/laps/SessionCard.tsx new file mode 100644 index 0000000..e1b74bb --- /dev/null +++ b/headless-rust/frontend/src/routes/laps/SessionCard.tsx @@ -0,0 +1,115 @@ +import { useState } from "react"; +import { HugeiconsIcon } from "@hugeicons/react"; +import { ArrowDown01Icon, ArrowUp01Icon, Delete02Icon } from "@hugeicons/core-free-icons"; +import { Button } from "@/components/ui/button"; +import { formatDuration, formatSessionDate } from "@/lib/format"; +import { LapRow } from "./LapRow"; +import type { LapSessionWithLaps } from "@/shared/types"; + +interface SessionCardProps { + session: LapSessionWithLaps; + deleting: boolean; + onDelete: () => void; +} + +export function SessionCard({ session, deleting, onDelete }: SessionCardProps) { + const [expanded, setExpanded] = useState(false); + + const lapCount = session.laps.length; + const bestLap = lapCount > 0 + ? session.laps.reduce((b, l) => l.durationMs < b.durationMs ? l : b) + : null; + + const duration = session.endedAt + ? new Date(session.endedAt).getTime() - new Date(session.startedAt).getTime() + : null; + + return ( +
+ {/* Header row */} +
+ + + +
+ + {/* Expanded laps */} + {expanded && ( +
+ {lapCount === 0 ? ( +

No laps recorded.

+ ) : ( + + + + + + + + + + + + + {session.laps.map((lap) => ( + + ))} + +
#DurationSpeed InSpeed OutTimeImages
+ )} +
+ )} +
+ ); +} diff --git a/headless-rust/frontend/src/routes/settings.tsx b/headless-rust/frontend/src/routes/settings.tsx new file mode 100644 index 0000000..7a08e12 --- /dev/null +++ b/headless-rust/frontend/src/routes/settings.tsx @@ -0,0 +1,64 @@ +import { createRoute } from "@tanstack/react-router"; +import { Tabs as TabsPrimitive } from "radix-ui"; +import { RootRoute } from "./__root"; +import { cn } from "@/lib/utils"; +import { DeviceTab } from "./settings/DeviceTab"; +import { NetworkTab } from "./settings/NetworkTab"; +import { CameraTab } from "./settings/CameraTab"; +import { SpeedCameraTab } from "./settings/SpeedCameraTab"; +import { LapTimerTab } from "./settings/LapTimerTab"; + +export const SettingsRoute = createRoute({ + getParentRoute: () => RootRoute, + path: "/settings", + component: SettingsPage, +}); + +function SettingsPage() { + return ( +
+ + + {(["device", "network", "camera", "speed-camera", "lap-timer"] as const).map((tab) => ( + + {tab === "device" + ? "Device" + : tab === "network" + ? "Network" + : tab === "camera" + ? "Camera" + : tab === "speed-camera" + ? "Speed Camera" + : "Lap Timer"} + + ))} + + + + + + + + + + + + + + + + + + +
+ ); +} diff --git a/headless-rust/frontend/src/routes/settings/CameraTab.tsx b/headless-rust/frontend/src/routes/settings/CameraTab.tsx new file mode 100644 index 0000000..803937c --- /dev/null +++ b/headless-rust/frontend/src/routes/settings/CameraTab.tsx @@ -0,0 +1,342 @@ +import { useState, useEffect } from "react"; +import type { ChangeEvent } from "react"; +import { toast } from "sonner"; +import { useAppStore } from "@/stores/useAppStore"; +import type { HwControl } from "@/shared/types"; +import { Button } from "@/components/ui/button"; +import { Checkbox } from "@/components/ui/checkbox"; +import { Label } from "@/components/ui/label"; +import { Badge } from "@/components/ui/badge"; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; +import { Slider } from "@/components/ui/slider"; +import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"; +import { Upload, CheckCircle2, XCircle, ChevronDown } from "lucide-react"; + +export function CameraTab() { + const connected = useAppStore((s) => s.cameraConnected); + const vendor = useAppStore((s) => s.cameraVendor); + const model = useAppStore((s) => s.cameraModel); + const serial = useAppStore((s) => s.cameraSerial); + + const connectCamera = useAppStore((s) => s.connectCamera); + const disconnectCamera = useAppStore((s) => s.disconnectCamera); + const applyMfsConfig = useAppStore((s) => s.applyMfsConfig); + const clearMfsResult = useAppStore((s) => s.clearMfsResult); + const mfsResult = useAppStore((s) => s.mfsResult); + const setCameraFeature = useAppStore((s) => s.setCameraFeature); + + const exposure = useAppStore((s) => s.cameraExposure); + const gain = useAppStore((s) => s.cameraGain); + const pixelFormat = useAppStore((s) => s.pixelFormat); + const exposureAuto = useAppStore((s) => s.exposureAuto); + const gainAuto = useAppStore((s) => s.gainAuto); + const frameRate = useAppStore((s) => s.frameRate); + const cameraWidth = useAppStore((s) => s.cameraWidth); + const cameraHeight = useAppStore((s) => s.cameraHeight); + const blackLevel = useAppStore((s) => s.blackLevel); + const strobeLineDuration = useAppStore((s) => s.strobeLineDuration); + + const [saveAsDefault, setSaveAsDefault] = useState(true); + const [mfsLoading, setMfsLoading] = useState(false); + + const handleMfsUpload = async (e: ChangeEvent) => { + const file = e.target.files?.[0]; + if (!file) return; + setMfsLoading(true); + clearMfsResult(); + + try { + const text = await file.text(); + await applyMfsConfig(text, saveAsDefault); + } catch { + toast.error("Failed to apply config file"); + } finally { + setMfsLoading(false); + e.target.value = ""; + } + }; + + return ( +
+
+
+

Industrial Camera

+ {connected ? ( +

+ Connected to {vendor} {model} ({serial}) +

+ ) : ( +

+ No camera connected. +

+ )} +
+
+ + +
+
+ +
+

Load .mfs Config

+
+
+ setSaveAsDefault(!!c)} /> + +
+
+ +
+ + {mfsResult && ( +
+ + +
+ + Applied Features + {mfsResult.applied.length} +
+ +
+ +
+ {mfsResult.applied.map((f) => ( +
{f}
+ ))} + {mfsResult.applied.length === 0 &&
No features applied
} +
+
+
+ + + +
+ + Failed Features + 0 ? "destructive" : "secondary"}> + {mfsResult.failed.length} + +
+ +
+ +
+ {mfsResult.failed.map((f) => ( +
{f}
+ ))} + {mfsResult.failed.length === 0 &&
No failures
} +
+
+
+
+ )} +
+
+ +
+

Camera Settings

+
+
+ + +
+ +
+ + +
+ + setCameraFeature("cameraExposure", v)} + /> + +
+ + +
+ + setCameraFeature("cameraGain", v)} + /> + + setCameraFeature("frameRate", v)} + /> + + setCameraFeature("cameraWidth", v)} + /> + + setCameraFeature("cameraHeight", v)} + /> + + setCameraFeature("blackLevel", v)} + /> + + setCameraFeature("strobeLineDuration", v)} + /> +
+
+
+ ); +} + +interface HwControlRowProps { + control: HwControl; + currentValue: number; + saving: boolean; + onChange: (value: number) => Promise | void; +} + +function HwControlRow({ control, currentValue, saving, onChange }: HwControlRowProps) { + const [draft, setDraft] = useState(currentValue); + const [showCheck, setShowCheck] = useState(false); + const [isApplying, setIsApplying] = useState(false); + + useEffect(() => { + setDraft(currentValue); + }, [currentValue]); + + const handleApply = async (value: number) => { + setIsApplying(true); + try { + await onChange(value); + setShowCheck(true); + setTimeout(() => setShowCheck(false), 2000); + } catch (e) { + console.error(e); + } finally { + setIsApplying(false); + } + }; + + const isBusy = saving || isApplying; + + if (control.type === "bool") { + return ( +
+ + +
+ ); + } + + const min = control.min ?? 0; + const max = control.max ?? 100; + const step = control.step ?? 1; + + return ( +
+
+ +
+ {draft} + +
+
+ setDraft(v)} + onValueCommit={([v]) => handleApply(v)} + /> +
+ {min} + {max} +
+
+ ); +} diff --git a/headless-rust/frontend/src/routes/settings/DeviceTab.tsx b/headless-rust/frontend/src/routes/settings/DeviceTab.tsx new file mode 100644 index 0000000..ef53260 --- /dev/null +++ b/headless-rust/frontend/src/routes/settings/DeviceTab.tsx @@ -0,0 +1,236 @@ +import { useState, useEffect, useCallback } from "react"; +import { toast } from "sonner"; +import { getRpc } from "@/lib/rpc"; +import { useAppStore } from "@/stores/useAppStore"; +import type { PortInfo, EspPongConfig } from "@/shared/types"; +import { Button } from "@/components/ui/button"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select"; +import { HugeiconsIcon } from "@hugeicons/react"; +import { + RefreshIcon, + LinkSquare02Icon, + Unlink04Icon, + FilterIcon, +} from "@hugeicons/core-free-icons"; +import { FirmwareFlasher } from "@/components/FirmwareFlasher"; + +export function DeviceTab() { + const connectedPort = useAppStore((s) => s.connectedPort); + const setConnectedPort = useAppStore((s) => s.setConnectedPort); + const selectedPort = useAppStore((s) => s.selectedPort); + const setSelectedPort = useAppStore((s) => s.setSelectedPort); + const availablePorts = useAppStore((s) => s.availablePorts); + const setAvailablePorts = useAppStore((s) => s.setAvailablePorts); + const lastPongConfig = useAppStore((s) => s.lastPongConfig); + + const [loadingPorts, setLoadingPorts] = useState(false); + const [connecting, setConnecting] = useState(false); + const [pinging, setPinging] = useState(false); + const [showAllPorts, setShowAllPorts] = useState(false); + + const filteredPorts = showAllPorts + ? availablePorts + : availablePorts.filter((p) => + /\/dev\/(ttyUSB|ttyACM)|COM\d|cu\.usb|tty\.usb/i.test(p.path) + ); + + const sendPing = useCallback(async () => { + setPinging(true); + try { + await getRpc().request.sendCommand({ json: JSON.stringify({ command: "ping" }) }); + } catch { + // silently ignore — port may not be open yet + } finally { + setPinging(false); + } + }, []); + + const refreshPorts = useCallback(async () => { + setLoadingPorts(true); + try { + const ports: PortInfo[] = await getRpc().request.listPorts({}); + setAvailablePorts(ports); + } catch { + toast.error("Failed to list serial ports"); + } finally { + setLoadingPorts(false); + } + }, [setAvailablePorts]); + + useEffect(() => { + getRpc() + .request.getSettings({}) + .then((settings) => { + if (settings.selectedPort) setSelectedPort(settings.selectedPort); + }) + .catch(() => {}); + void refreshPorts(); + }, [refreshPorts, setSelectedPort]); + + useEffect(() => { + if (connectedPort) void sendPing(); + }, [connectedPort, sendPing]); + + const handleConnect = async () => { + if (!selectedPort) return; + setConnecting(true); + try { + await getRpc().request.openPort({ path: selectedPort }); + setConnectedPort(selectedPort); + await getRpc().request.saveSetting({ key: "selectedPort", value: selectedPort }); + toast.success(`Connected to ${selectedPort}`); + } catch { + toast.error(`Failed to connect to ${selectedPort}`); + } finally { + setConnecting(false); + } + }; + + const handleDisconnect = async () => { + setConnecting(true); + try { + await getRpc().request.closePort({}); + setConnectedPort(""); + toast.success("Disconnected"); + } catch { + toast.error("Failed to disconnect"); + } finally { + setConnecting(false); + } + }; + + return ( +
+
+

Serial Port

+
+ + + {connectedPort ? ( + + ) : ( + + )} +
+ + {connectedPort && ( +

+ Connected: {connectedPort} +

+ )} +
+ + {connectedPort && ( +
+
+

Device Config

+ +
+ {lastPongConfig ? ( + + ) : ( +

+ {pinging ? "Fetching config…" : "No config yet — click refresh"} +

+ )} +
+ )} + + +
+ ); +} + +function PongConfigDisplay({ config }: { config: EspPongConfig }) { + const rows: [string, string][] = [ + ["Speed limit", `${config.maxSpeed} km/h`], + ["Flash delay", `${config.flashDelay} ms`], + ["Flash duration", `${config.flashDuration} ms`], + ["Sensor distance", `${config.sensorDistance} mm`], + ["Debug output", config.debugEnabled ? "On" : "Off"], + ]; + + return ( +
+

+ ESP Config +

+ {rows.map(([label, value]) => ( +
+ {label} + {value} +
+ ))} +
+ ); +} diff --git a/headless-rust/frontend/src/routes/settings/LapTimerTab.tsx b/headless-rust/frontend/src/routes/settings/LapTimerTab.tsx new file mode 100644 index 0000000..6cb860c --- /dev/null +++ b/headless-rust/frontend/src/routes/settings/LapTimerTab.tsx @@ -0,0 +1,119 @@ +import { useState } from "react"; +import { toast } from "sonner"; +import { useAppStore } from "@/stores/useAppStore"; +import type { AppSettings } from "@/shared/types"; +import { Button } from "@/components/ui/button"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select"; + +export function LapTimerTab() { + const lapSettings = useAppStore((s) => s.lapSettings); + const updateLapSetting = useAppStore((s) => s.updateLapSetting); + const [saving, setSaving] = useState(null); + + const handleUpdate = async (key: keyof AppSettings, value: string) => { + setSaving(key); + try { + await updateLapSetting(key, value); + } catch { + toast.error("Failed to save setting"); + } finally { + setSaving(null); + } + }; + + return ( +
+
+
+

Lap Mode

+

+ Single: one lap per session cycle, resets to waiting after each lap. + Multi: continuous recording until stopped. +

+
+ +
+ +
+

Image Capture

+ handleUpdate("lapSaveImages", v ? "true" : "false")} + /> +
+ +
+
+

Direction Filter

+

+ Which direction a car must pass the sensors to start or end a lap. + Use this when cars always travel the same way past the device. +

+
+ +
+
+ ); +} + +interface ToggleSettingProps { + label: string; + description?: string; + checked: boolean; + disabled?: boolean; + onChange: (value: boolean) => void; +} + +function ToggleSetting({ label, description, checked, disabled, onChange }: ToggleSettingProps) { + return ( +
+
+ + {description &&

{description}

} +
+ +
+ ); +} diff --git a/headless-rust/frontend/src/routes/settings/NetworkTab.tsx b/headless-rust/frontend/src/routes/settings/NetworkTab.tsx new file mode 100644 index 0000000..49d6dd7 --- /dev/null +++ b/headless-rust/frontend/src/routes/settings/NetworkTab.tsx @@ -0,0 +1,652 @@ +import { useState, useEffect, useRef, useCallback } from "react"; +import { toast } from "sonner"; +import { getRpc } from "@/lib/rpc"; +import type { SystemNetworkSummary, WifiScanResult } from "@/shared/types"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { Badge } from "@/components/ui/badge"; +import { + Wifi, + WifiOff, + Lock, + Unlock, + RefreshCw, + Router, + Cable, + Globe, + Radio, + Eye, + EyeOff, + ChevronDown, + ChevronUp, + AlertTriangle, + RotateCcw, + CheckCircle2, + SignalHigh, + SignalMedium, + SignalLow, + Plus, +} from "lucide-react"; +import { WifiConnectDialog } from "@/components/WifiConnectDialog"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog"; + +export function NetworkTab() { + const [network, setNetwork] = useState(null); + const [loading, setLoading] = useState(false); + const [scanning, setScanning] = useState(false); + const [networks, setNetworks] = useState([]); + + // Selected Network for inline connection + const [expandedSsid, setExpandedSsid] = useState(null); + const [password, setPassword] = useState(""); + const [showPassword, setShowPassword] = useState(false); + const [connecting, setConnecting] = useState(false); + + // Manual Network Entry + const [showManual, setShowManual] = useState(false); + const [manualSsid, setManualSsid] = useState(""); + const [manualPassword, setManualPassword] = useState(""); + + // Dialogs + const [connectDialogOpen, setConnectDialogOpen] = useState(false); + const [connectDialogData, setConnectDialogData] = useState<{ + ssid: string; + password?: string; + security?: string; + assignedIp?: string | null; + }>({ ssid: "" }); + const [forgetDialogOpen, setForgetDialogOpen] = useState(false); + const [forgetting, setForgetting] = useState(false); + const [switchingEth, setSwitchingEth] = useState(false); + + const scanIntervalRef = useRef | null>(null); + + const fetchNetworkSummary = useCallback(async () => { + try { + const summary = await getRpc().request.getNetworkInfo({}); + setNetwork(summary); + } catch (e) { + console.error("Failed to fetch network summary", e); + } + }, []); + + const scanWifi = useCallback(async (isSilent = false) => { + if (!isSilent) setScanning(true); + try { + const list = await getRpc().request.scanWifiNetworks({}); + setNetworks(list); + if (!isSilent && list.length > 0) { + toast.success(`Found ${list.length} Wi-Fi networks`); + } + } catch { + if (!isSilent) toast.error("Failed to scan Wi-Fi networks"); + } finally { + if (!isSilent) setScanning(false); + } + }, []); + + useEffect(() => { + setLoading(true); + Promise.all([fetchNetworkSummary(), scanWifi(true)]).finally(() => setLoading(false)); + + // Auto-rescan every 12 seconds + scanIntervalRef.current = setInterval(() => { + scanWifi(true); + fetchNetworkSummary(); + }, 12000); + + return () => { + if (scanIntervalRef.current) clearInterval(scanIntervalRef.current); + }; + }, [fetchNetworkSummary, scanWifi]); + + const handleConnect = async (targetSsid: string, targetPass: string, targetSec?: string) => { + if (!targetSsid.trim()) { + toast.error("Please enter a valid SSID"); + return; + } + + setConnecting(true); + setConnectDialogData({ + ssid: targetSsid, + password: targetPass, + security: targetSec, + }); + setConnectDialogOpen(true); + + try { + const res = await getRpc().request.applyNetworkMode({ + mode: "client", + ssid: targetSsid.trim(), + password: targetPass || undefined, + }); + + if (res.success) { + toast.success(res.message); + setTimeout(async () => { + await fetchNetworkSummary(); + }, 4000); + } else { + toast.error(res.message || "Failed to connect to network"); + } + } catch (err: any) { + toast.error(err?.message || "Error applying Wi-Fi settings"); + } finally { + setConnecting(false); + } + }; + + const handleForgetWifi = async () => { + setForgetting(true); + try { + const res = await getRpc().request.forgetWifi({}); + if (res.success) { + toast.success("Wi-Fi credentials removed. AP Setup Hotspot started."); + setForgetDialogOpen(false); + setExpandedSsid(null); + setPassword(""); + setTimeout(fetchNetworkSummary, 3000); + } else { + toast.error(res.message || "Failed to reset network"); + } + } catch (err: any) { + toast.error(err?.message || "Failed to reset network"); + } finally { + setForgetting(false); + } + }; + + const handleToggleEthernetMode = async () => { + if (!network) return; + const isCameraLan = network.ethernetMode === "camera-lan" || network.cameraLan.status === "ok"; + const targetMode = isCameraLan ? "lan-dhcp" : "lan-camera"; + + setSwitchingEth(true); + try { + const res = await getRpc().request.setEthernetMode({ mode: targetMode }); + if (res.success) { + toast.success(res.message); + setTimeout(fetchNetworkSummary, 3000); + } else { + toast.error(res.message || "Failed to change Ethernet configuration"); + } + } catch (err: any) { + toast.error(err?.message || "Failed to change Ethernet configuration"); + } finally { + setSwitchingEth(false); + } + }; + + const isApMode = network?.wifiMode === "ap" || network?.mode === "ap" || network?.mode === "field"; + const isClientMode = network?.wifiMode === "client" || network?.mode === "wifi-client" || network?.mode === "client"; + const isEthernetCameraLan = network?.ethernetMode === "camera-lan" || network?.cameraLan.status === "ok"; + + const getSignalIcon = (signal: number) => { + if (signal >= 70) return ; + if (signal >= 40) return ; + return ; + }; + + return ( +
+ {/* Header */} +
+
+

Network & Wi-Fi Management

+

+ Configure standalone AP hotspot onboarding and client Wi-Fi connectivity. +

+
+
+ +
+
+ + {/* Live Status Cards */} +
+ {/* Wireless Status Card */} +
+
+
+
+ {isApMode ? : } +
+ + Wireless Interface + +
+ {isApMode ? ( + + + AP Setup Hotspot + + ) : isClientMode ? ( + + + Client Connected + + ) : ( + + Disconnected + + )} +
+ +
+ {isClientMode && network?.wifiClient ? ( + <> +
+ SSID: + {network.wifiClient.ssid || "Unknown"} +
+
+ IP Address: + {network.wifiClient.ip || "Waiting DHCP..."} +
+ {network.wifiClient.gateway && ( +
+ Gateway: + {network.wifiClient.gateway} +
+ )} + + ) : ( + <> +
+ Hotspot SSID: + speedcamera (Open) +
+
+ Static IP: + {network?.hotspotAp.ip || "192.168.4.1"} +
+
+ Band / Channel: + 5 GHz • Channel 36 +
+ + )} + + {network?.wifiMac && ( +
+ Wi-Fi MAC: + {network.wifiMac} +
+ )} +
+ + {isClientMode && ( +
+ +
+ )} +
+ + {/* Ethernet LAN Status Card */} +
+
+
+
+ +
+ + Ethernet Interface + +
+ {isEthernetCameraLan ? ( + + Camera LAN + + ) : ( + + Standard DHCP + + )} +
+ +
+
+ Interface: + + {network?.cameraLan.interfaceName || "eth0"} + +
+
+ IP Address: + + {network?.cameraLan.ip || "Unassigned"} + +
+
+ Config: + + {isEthernetCameraLan ? "Static 192.168.1.100 (MTU 9000)" : "Auto DHCP (Internet/Updates)"} + +
+ {network?.ethernetMac && ( +
+ Ethernet MAC: + {network.ethernetMac} +
+ )} +
+ +
+ +
+
+
+ + {/* Available Wi-Fi Networks */} +
+
+
+

Available Wi-Fi Networks

+ + {networks.length} + +
+ +
+ + {/* Manual Hidden Network Form */} + {showManual && ( +
+
Connect to Hidden Network
+
+
+ + setManualSsid(e.target.value)} + /> +
+
+ + setManualPassword(e.target.value)} + /> +
+
+
+ +
+
+ )} + + {/* Networks List */} +
+ {networks.length === 0 ? ( +
+ +

+ {scanning ? "Scanning for nearby networks..." : "No Wi-Fi networks found."} +

+ +
+ ) : ( + networks.map((net) => { + const isExpanded = expandedSsid === net.ssid; + const isConnected = net.inUse || (isClientMode && network?.wifiClient?.ssid === net.ssid); + const isSecured = net.security && net.security !== "Open"; + + return ( +
+ {/* Network Header Row */} +
{ + if (isExpanded) { + setExpandedSsid(null); + } else { + setExpandedSsid(net.ssid); + setPassword(""); + } + }} + className={`flex items-center justify-between p-3.5 cursor-pointer hover:bg-accent/40 transition-colors ${ + isConnected ? "bg-primary/5" : "" + }`} + > +
+
+ {isSecured ? ( + + ) : ( + + )} +
+ +
+
+ + {net.ssid} + + {isConnected && ( + + Active + + )} +
+
+ {net.security} + {net.channel ? • Ch {net.channel} : null} + {net.bssid ? ({net.bssid}) : null} +
+
+
+ +
+
+ {getSignalIcon(net.signal)} + {net.signal}% +
+ {isExpanded ? ( + + ) : ( + + )} +
+
+ + {/* Expanded Connect Form */} + {isExpanded && ( +
+ {isConnected ? ( +
+ + + Connected to this network. + + +
+ ) : ( +
+ {isSecured ? ( +
+ +
+ setPassword(e.target.value)} + onKeyDown={(e) => { + if (e.key === "Enter") { + handleConnect(net.ssid, password, net.security); + } + }} + autoFocus + /> + +
+
+ ) : ( +

+ This is an open network. No password required. +

+ )} + +
+ + +
+
+ )} +
+ )} +
+ ); + }) + )} +
+
+ + {/* QR Code & Connect Guidance Modal */} + + + {/* Confirmation Dialog: Forget Network & Return to AP Mode */} + + + +
+ + Reset Wi-Fi Connection? +
+ + This will remove all saved Wi-Fi credentials and immediately revert the Raspberry Pi to the standalone + open speedcamera Setup Hotspot. + +
+ + + + + +
+
+
+ ); +} diff --git a/headless-rust/frontend/src/routes/settings/SpeedCameraTab.tsx b/headless-rust/frontend/src/routes/settings/SpeedCameraTab.tsx new file mode 100644 index 0000000..18ded97 --- /dev/null +++ b/headless-rust/frontend/src/routes/settings/SpeedCameraTab.tsx @@ -0,0 +1,263 @@ +import { useState, useEffect, useCallback } from "react"; +import { toast } from "sonner"; +import { getRpc } from "@/lib/rpc"; +import { useAppStore } from "@/stores/useAppStore"; +import type { AppSettings } from "@/shared/types"; +import { Button } from "@/components/ui/button"; +import { Slider } from "@/components/ui/slider"; +import { Skeleton } from "@/components/ui/skeleton"; +import { HugeiconsIcon } from "@hugeicons/react"; +import { RefreshIcon } from "@hugeicons/core-free-icons"; + +const SPEED_CAMERA_FIELDS: Array<{ + key: keyof AppSettings; + label: string; + unit: string; + min: number; + max: number; + step: number; +}> = [ + { key: "maxSpeed", label: "Max Speed", unit: "km/h", min: 1, max: 200, step: 1 }, + { key: "strobeLineDuration", label: "Strobe Duration", unit: "ms", min: 10, max: 20000, step: 10 }, +]; + +const ESP_SYNCED_KEYS = new Set(["maxSpeed"]); + +const SERIAL_SYNC: Partial> = { + maxSpeed: "setMaxSpeed", +}; + +export function SpeedCameraTab() { + const setMaxSpeedInStore = useAppStore((s) => s.setMaxSpeed); + const connectedPort = useAppStore((s) => s.connectedPort); + const lastPongConfig = useAppStore((s) => s.lastPongConfig); + + const [values, setValues] = useState>({}); + const [saved, setSaved] = useState>({}); + const [loading, setLoading] = useState(true); + const [savingHw, setSavingHw] = useState(false); + const [savingCosmetic, setSavingCosmetic] = useState(false); + const [refreshing, setRefreshing] = useState(false); + + const loadFromDb = useCallback(async () => { + const settings = await getRpc().request.getSettings({}); + setValues(settings); + setSaved(settings); + return settings; + }, []); + + useEffect(() => { + loadFromDb() + .catch(() => toast.error("Failed to load settings")) + .finally(() => setLoading(false)); + }, [loadFromDb]); + + useEffect(() => { + if (!lastPongConfig) return; + const patch: Partial = { + maxSpeed: lastPongConfig.maxSpeed, + }; + setValues((prev) => ({ ...prev, ...patch })); + setSaved((prev) => ({ ...prev, ...patch })); + }, [lastPongConfig]); + + const handleRefresh = useCallback(async () => { + setRefreshing(true); + try { + await loadFromDb(); + if (connectedPort) { + await getRpc().request.sendCommand({ json: JSON.stringify({ command: "ping" }) }); + } + } catch { + toast.error("Failed to refresh settings"); + } finally { + setRefreshing(false); + } + }, [loadFromDb, connectedPort]); + + const isHwDirty = SPEED_CAMERA_FIELDS.some(({ key }) => values[key] !== saved[key]); + const isCosmeticDirty = + (values.skinMeasuringLocation ?? "") !== (saved.skinMeasuringLocation ?? ""); + + const handleSaveHw = async () => { + setSavingHw(true); + try { + await Promise.all( + SPEED_CAMERA_FIELDS.map(({ key }) => + getRpc().request.saveSetting({ key, value: String(values[key]) }) + ) + ); + + await Promise.all( + SPEED_CAMERA_FIELDS.filter(({ key }) => values[key] !== saved[key] && key in SERIAL_SYNC).map( + ({ key }) => + getRpc().request.sendCommand({ + json: JSON.stringify({ command: SERIAL_SYNC[key], value: values[key] }), + }) + ) + ); + + setSaved((prev) => { + const next = { ...prev }; + for (const { key } of SPEED_CAMERA_FIELDS) { + next[key] = values[key] as never; + } + return next; + }); + if (values.maxSpeed !== undefined) setMaxSpeedInStore(values.maxSpeed); + toast.success("Hardware settings saved"); + } catch { + toast.error("Failed to save hardware settings"); + } finally { + setSavingHw(false); + } + }; + + const handleSaveCosmetic = async () => { + setSavingCosmetic(true); + try { + await getRpc().request.saveSetting({ + key: "skinMeasuringLocation", + value: String(values.skinMeasuringLocation ?? ""), + }); + + setSaved((prev) => ({ + ...prev, + skinMeasuringLocation: values.skinMeasuringLocation, + })); + toast.success("Display settings saved"); + } catch { + toast.error("Failed to save display settings"); + } finally { + setSavingCosmetic(false); + } + }; + + if (loading) { + return ( +
+ {Array.from({ length: 4 }).map((_, i) => ( +
+
+ + +
+ +
+ ))} +
+ ); + } + + const hwSaveDisabledReason = !connectedPort + ? "Connect to the ESP before saving hardware settings" + : undefined; + + return ( +
+
+
+
+

Speed Camera Hardware Settings

+

+ {connectedPort + ? lastPongConfig + ? "Values synced from device" + : "Connect to device to sync values" + : Serial not connected — hardware save disabled} +

+
+ +
+ + {SPEED_CAMERA_FIELDS.map(({ key, label, unit, min, max, step }) => { + const val = (values[key] as number) ?? min; + const isEspSynced = ESP_SYNCED_KEYS.has(key); + return ( +
+
+ +
+ + setValues((prev) => ({ + ...prev, + [key]: Math.min(max, Math.max(min, Number(e.target.value))), + })) + } + className="w-20 h-7 px-2 text-sm text-right rounded-lg border border-input bg-input/30 focus:outline-none focus:ring-2 focus:ring-ring/50 focus:border-ring" + /> + {unit} +
+
+ setValues((prev) => ({ ...prev, [key]: v }))} + /> +
+ {min} {unit} + {max} {unit} +
+
+ ); + })} + +
+ +
+
+ +
+

Display & Cosmetic Options

+
+ +

+ Shown in Poliscan skin bottom bar. e.g. "BAB 2 Km 81,2, Ri. Hannover" +

+ + setValues((prev) => ({ ...prev, skinMeasuringLocation: e.target.value })) + } + placeholder="e.g. BAB 2 Km 81,2, Ri. Hannover" + className="w-full h-8 px-3 text-sm rounded-lg border border-input bg-input/30 focus:outline-none focus:ring-2 focus:ring-ring/50 focus:border-ring" + /> +
+ +
+ +
+
+
+ ); +} diff --git a/headless-rust/frontend/src/routes/setup.tsx b/headless-rust/frontend/src/routes/setup.tsx new file mode 100644 index 0000000..aa8240e --- /dev/null +++ b/headless-rust/frontend/src/routes/setup.tsx @@ -0,0 +1,140 @@ +import { useEffect, useState, useRef } from "react"; +import { createRoute } from "@tanstack/react-router"; +import { RootRoute } from "./__root"; +import { useAppStore } from "@/stores/useAppStore"; +import { useBackendEvent } from "@/hooks/useBackendEvent"; +import { Button } from "@/components/ui/button"; +import { Badge } from "@/components/ui/badge"; +import { PlayIcon, SquareIcon, AlertCircleIcon, Loader2Icon } from "lucide-react"; +import { toast } from "sonner"; + +export const SetupRoute = createRoute({ + getParentRoute: () => RootRoute, + path: "/setup", + component: SetupPage, +}); + +function SetupPage() { + const connected = useAppStore((s) => s.cameraConnected); + const setupStreamActive = useAppStore((s) => s.setupStreamActive); + const startSetupStream = useAppStore((s) => s.startSetupStream); + const stopSetupStream = useAppStore((s) => s.stopSetupStream); + const refreshCameraStatus = useAppStore((s) => s.refreshCameraStatus); + + const [frame, setFrame] = useState(null); + const [isToggling, setIsToggling] = useState(false); + + const setupStreamActiveRef = useRef(setupStreamActive); + setupStreamActiveRef.current = setupStreamActive; + + // Real-time frame listener + useBackendEvent("liveFrame", (newFrame) => { + setFrame(newFrame as string); + }); + + // Refresh hardware status on mount + useEffect(() => { + void refreshCameraStatus(); + }, [refreshCameraStatus]); + + // Clean unmount: Stop stream only if it was active + useEffect(() => { + return () => { + if (setupStreamActiveRef.current) { + stopSetupStream().catch(console.error); + } + }; + }, [stopSetupStream]); + + const handleStart = async () => { + if (!connected) { + toast.error("Camera is not connected!"); + return; + } + setIsToggling(true); + try { + await startSetupStream(); + toast.success("Preview stream started"); + } catch { + toast.error("Failed to start setup stream"); + } finally { + setIsToggling(false); + } + }; + + const handleStop = async () => { + setIsToggling(true); + try { + await stopSetupStream(); + setFrame(null); + toast.info("Preview stream stopped"); + } catch { + toast.error("Failed to stop setup stream"); + } finally { + setIsToggling(false); + } + }; + + return ( +
+
+
+

Camera Setup

+

+ + Flash strobe is temporarily disabled during setup. Auto-gain is active. +

+
+
+ + {setupStreamActive ? "Streaming" : "Stopped"} + + {!setupStreamActive ? ( + + ) : ( + + )} +
+
+ +
+ {setupStreamActive ? ( + frame ? ( + Camera Livestream + ) : ( +
+ Waiting for frame from camera... +
+ ) + ) : ( +
+

{connected ? "Click Start Stream to begin setup preview" : "Camera disconnected"}

+ {connected && ( +

+ Preview renders at 10 FPS with continuous auto-exposure +

+ )} +
+ )} +
+
+ ); +} diff --git a/headless-rust/frontend/src/routes/teable.tsx b/headless-rust/frontend/src/routes/teable.tsx new file mode 100644 index 0000000..a7a92e7 --- /dev/null +++ b/headless-rust/frontend/src/routes/teable.tsx @@ -0,0 +1,29 @@ +import { createRoute } from "@tanstack/react-router"; +import { RootRoute } from "./__root"; +import { ConnectionSection } from "./teable/ConnectionSection"; +import { TableTargetSection } from "./teable/TableTargetSection"; +import { SyncToggleSection } from "./teable/SyncToggleSection"; + +export const TeableRoute = createRoute({ + getParentRoute: () => RootRoute, + path: "/teable", + component: TeablePage, +}); + +function TeablePage() { + return ( +
+
+
+

Teable Integration

+

+ Sync lap times to a self-hosted Teable instance. +

+
+ + + +
+
+ ); +} diff --git a/headless-rust/frontend/src/routes/teable/ConnectionSection.tsx b/headless-rust/frontend/src/routes/teable/ConnectionSection.tsx new file mode 100644 index 0000000..745db77 --- /dev/null +++ b/headless-rust/frontend/src/routes/teable/ConnectionSection.tsx @@ -0,0 +1,159 @@ +import { useState } from "react"; +import { toast } from "sonner"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { useAppStore } from "@/stores/useAppStore"; +import { HugeiconsIcon } from "@hugeicons/react"; +import { + LinkSquare02Icon, + Unlink04Icon, + Loading03Icon, + Alert01Icon, +} from "@hugeicons/core-free-icons"; + +export function ConnectionSection() { + const teableConnected = useAppStore((s) => s.teableConnected); + const teableUrl = useAppStore((s) => s.teableUrl); + const teableUserName = useAppStore((s) => s.teableUserName); + const teableUserEmail = useAppStore((s) => s.teableUserEmail); + const teableUserAvatar = useAppStore((s) => s.teableUserAvatar); + const isTeableLoading = useAppStore((s) => s.isTeableLoading); + const connectTeable = useAppStore((s) => s.connectTeable); + const disconnectTeable = useAppStore((s) => s.disconnectTeable); + + const [url, setUrl] = useState(""); + const [token, setToken] = useState(""); + const [error, setError] = useState(null); + + const handleConnect = async () => { + setError(null); + const trimUrl = url.trim().replace(/\/+$/, ""); + const trimToken = token.trim(); + if (!trimUrl) { setError("Please enter the Teable instance URL."); return; } + if (!trimToken) { setError("Please enter your Personal Access Token."); return; } + try { + await connectTeable(trimUrl, trimToken); + setUrl(""); + setToken(""); + toast.success("Connected to Teable"); + } catch (e) { + setError(String(e)); + } + }; + + const handleDisconnect = async () => { + await disconnectTeable(); + toast.success("Teable integration removed"); + }; + + return ( +
+

+ Connection +

+ + {teableConnected ? ( + // ── Connected state ────────────────────────────────────────────────── +
+
+ {teableUserAvatar ? ( + {teableUserName} + ) : ( +
+ + {teableUserName.charAt(0).toUpperCase() || "T"} + +
+ )} +
+

{teableUserName || "Teable User"}

+ {teableUserEmail && ( +

{teableUserEmail}

+ )} +

{teableUrl}

+
+
+ + + Connected + +
+
+ + +
+ ) : ( + // ── Disconnected state ─────────────────────────────────────────────── +
+
+ + setUrl(e.target.value)} + disabled={isTeableLoading} + /> +
+ +
+ + setToken(e.target.value)} + disabled={isTeableLoading} + onKeyDown={(e) => { if (e.key === "Enter") void handleConnect(); }} + /> +

+ Create a token under{" "} + Settings → Personal Access Tokens in your + Teable instance. +

+
+ + {error && ( +
+ + {error} +
+ )} + + +
+ )} +
+ ); +} diff --git a/headless-rust/frontend/src/routes/teable/SchemaStatus.tsx b/headless-rust/frontend/src/routes/teable/SchemaStatus.tsx new file mode 100644 index 0000000..fb35d59 --- /dev/null +++ b/headless-rust/frontend/src/routes/teable/SchemaStatus.tsx @@ -0,0 +1,97 @@ +import { Button } from "@/components/ui/button"; +import { HugeiconsIcon } from "@hugeicons/react"; +import { + RefreshIcon, + CheckmarkCircle02Icon, + Alert01Icon, + PlusSignSquareIcon, + Loading03Icon, +} from "@hugeicons/core-free-icons"; + +interface SchemaStatusProps { + status: "unchecked" | "valid" | "missing"; + missingFields: string[]; + isLoading: boolean; + onVerify: () => void; + onPatch: () => void; + onCreateNew: () => void; +} + +export function SchemaStatus({ + status, + missingFields, + isLoading, + onVerify, + onPatch, + onCreateNew, +}: SchemaStatusProps) { + if (status === "unchecked") { + return ( + + ); + } + + if (status === "valid") { + return ( +
+ + All required columns are present +
+ ); + } + + // status === "missing" + return ( +
+
+
+ + Missing {missingFields.length} required column{missingFields.length > 1 ? "s" : ""} +
+
    + {missingFields.map((f) => ( +
  • {f}
  • + ))} +
+
+
+ + +
+
+ ); +} diff --git a/headless-rust/frontend/src/routes/teable/SyncToggleSection.tsx b/headless-rust/frontend/src/routes/teable/SyncToggleSection.tsx new file mode 100644 index 0000000..40e6a13 --- /dev/null +++ b/headless-rust/frontend/src/routes/teable/SyncToggleSection.tsx @@ -0,0 +1,39 @@ +import { Switch } from "@/components/ui/switch"; +import { useAppStore } from "@/stores/useAppStore"; + +export function SyncToggleSection() { + const teableConnected = useAppStore((s) => s.teableConnected); + const teableTableId = useAppStore((s) => s.teableTableId); + const teableSchemaStatus = useAppStore((s) => s.teableSchemaStatus); + const teableSyncEnabled = useAppStore((s) => s.teableSyncEnabled); + const setTeableSyncEnabled = useAppStore((s) => s.setTeableSyncEnabled); + + const canSync = teableConnected && !!teableTableId && teableSchemaStatus === "valid"; + + if (!canSync) return null; + + return ( +
+

+ Sync Settings +

+ +
+
+
+

Enable Teable Sync

+

+ Each completed lap will be saved to Teable in the background. Local storage is + always used regardless of this setting. +

+
+ void setTeableSyncEnabled(checked)} + aria-label="Enable Teable sync" + /> +
+
+
+ ); +} diff --git a/headless-rust/frontend/src/routes/teable/TableTargetSection.tsx b/headless-rust/frontend/src/routes/teable/TableTargetSection.tsx new file mode 100644 index 0000000..db59c59 --- /dev/null +++ b/headless-rust/frontend/src/routes/teable/TableTargetSection.tsx @@ -0,0 +1,277 @@ +import { useState, useEffect } from "react"; +import { toast } from "sonner"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select"; +import { Skeleton } from "@/components/ui/skeleton"; +import { useAppStore } from "@/stores/useAppStore"; +import { getRpc } from "@/lib/rpc"; +import type { TeableSpace, TeableBase, TeableTable } from "@/shared/types"; +import { HugeiconsIcon } from "@hugeicons/react"; +import { + SaveIcon, + PlusSignSquareIcon, + Loading03Icon, +} from "@hugeicons/core-free-icons"; +import { SchemaStatus } from "./SchemaStatus"; + +export function TableTargetSection() { + const teableConnected = useAppStore((s) => s.teableConnected); + const teableSpaceId = useAppStore((s) => s.teableSpaceId); + const teableBaseId = useAppStore((s) => s.teableBaseId); + const teableTableId = useAppStore((s) => s.teableTableId); + const teableSchemaStatus = useAppStore((s) => s.teableSchemaStatus); + const teableMissingFields = useAppStore((s) => s.teableMissingFields); + const isTeableLoading = useAppStore((s) => s.isTeableLoading); + const saveTeableTableTarget = useAppStore((s) => s.saveTeableTableTarget); + const verifyTeableSchema = useAppStore((s) => s.verifyTeableSchema); + const patchTeableSchema = useAppStore((s) => s.patchTeableSchema); + const createAndSelectTable = useAppStore((s) => s.createAndSelectTable); + + const [spaces, setSpaces] = useState([]); + const [bases, setBases] = useState([]); + const [tables, setTables] = useState([]); + const [loadingSpaces, setLoadingSpaces] = useState(false); + const [loadingBases, setLoadingBases] = useState(false); + const [loadingTables, setLoadingTables] = useState(false); + + const [selectedSpaceId, setSelectedSpaceId] = useState(teableSpaceId); + const [selectedBaseId, setSelectedBaseId] = useState(teableBaseId); + const [selectedTableId, setSelectedTableId] = useState(teableTableId); + + const [newTableName, setNewTableName] = useState(""); + const [showNewTableForm, setShowNewTableForm] = useState(false); + + // Sync from store when connection changes + useEffect(() => { + setSelectedSpaceId(teableSpaceId); + setSelectedBaseId(teableBaseId); + setSelectedTableId(teableTableId); + }, [teableSpaceId, teableBaseId, teableTableId]); + + // Load spaces when connected + useEffect(() => { + if (!teableConnected) { setSpaces([]); return; } + setLoadingSpaces(true); + getRpc().request.listTeableSpaces({}) + .then(setSpaces) + .catch((e) => toast.error(`Failed to load spaces: ${String(e)}`)) + .finally(() => setLoadingSpaces(false)); + }, [teableConnected]); + + // Load bases when space selected + useEffect(() => { + setBases([]); + if (!selectedSpaceId) return; + setLoadingBases(true); + getRpc().request.listTeableBases({ spaceId: selectedSpaceId }) + .then(setBases) + .catch((e) => toast.error(`Failed to load bases: ${String(e)}`)) + .finally(() => setLoadingBases(false)); + }, [selectedSpaceId]); + + // Load tables when base selected + useEffect(() => { + setTables([]); + if (!selectedBaseId) return; + setLoadingTables(true); + getRpc().request.listTeableTables({ baseId: selectedBaseId }) + .then(setTables) + .catch((e) => toast.error(`Failed to load tables: ${String(e)}`)) + .finally(() => setLoadingTables(false)); + }, [selectedBaseId]); + + const handleSpaceChange = (id: string) => { + setSelectedSpaceId(id); + setSelectedBaseId(""); + setSelectedTableId(""); + }; + + const handleBaseChange = (id: string) => { + setSelectedBaseId(id); + setSelectedTableId(""); + }; + + const handleTableChange = (id: string) => { + setSelectedTableId(id); + }; + + const hasChanges = + selectedSpaceId !== teableSpaceId || + selectedBaseId !== teableBaseId || + selectedTableId !== teableTableId; + + const canSave = hasChanges && selectedSpaceId && selectedBaseId && selectedTableId; + + const handleSave = async () => { + if (!canSave) return; + await saveTeableTableTarget(selectedSpaceId, selectedBaseId, selectedTableId); + await verifyTeableSchema(selectedTableId); + toast.success("Table target saved"); + }; + + const handleCreateTable = async () => { + const name = newTableName.trim(); + if (!name) { toast.error("Please enter a table name."); return; } + await createAndSelectTable(selectedBaseId, name); + setNewTableName(""); + setShowNewTableForm(false); + // Refresh tables list + setLoadingTables(true); + getRpc().request.listTeableTables({ baseId: selectedBaseId }) + .then(setTables) + .catch(() => {}) + .finally(() => setLoadingTables(false)); + }; + + if (!teableConnected) return null; + + return ( +
+

+ Table Target +

+ +
+ {/* Space */} +
+ + {loadingSpaces ? ( + + ) : ( + + )} +
+ + {/* Base */} +
+ + {loadingBases ? ( + + ) : ( + + )} +
+ + {/* Table */} +
+ + {loadingTables ? ( + + ) : ( + + )} +
+ + {/* Save button */} + {canSave && ( + + )} + + {/* Schema status (shown after table is saved) */} + {teableTableId && !hasChanges && ( + void verifyTeableSchema()} + onPatch={() => void patchTeableSchema()} + onCreateNew={() => setShowNewTableForm(true)} + /> + )} + + {/* Create new table form */} + {showNewTableForm && selectedBaseId && ( +
+ +
+ setNewTableName(e.target.value)} + onKeyDown={(e) => { if (e.key === "Enter") void handleCreateTable(); }} + disabled={isTeableLoading} + className="flex-1" + /> + + +
+
+ )} +
+
+ ); +} diff --git a/headless-rust/frontend/src/routes/violations.tsx b/headless-rust/frontend/src/routes/violations.tsx new file mode 100644 index 0000000..e88e45d --- /dev/null +++ b/headless-rust/frontend/src/routes/violations.tsx @@ -0,0 +1,176 @@ +import { useState } from "react"; +import { createRoute } from "@tanstack/react-router"; +import { HugeiconsIcon } from "@hugeicons/react"; +import { ArrowLeft01Icon, ArrowRight01Icon } from "@hugeicons/core-free-icons"; +import { RootRoute } from "./__root"; +import { Button } from "@/components/ui/button"; +import { Dialog, DialogContent } from "@/components/ui/dialog"; +import { ViolationsToolbar } from "./violations/ViolationsToolbar"; +import { ViolationsTable } from "./violations/ViolationsTable"; +import { ViolationsGrid } from "./violations/ViolationsGrid"; +import { ExportImagesDialog } from "./violations/ExportImagesDialog"; +import { + useViolations, + readViewMode, + writeViewMode, + type ViewMode, +} from "./violations/useViolations"; + +export const ViolationsRoute = createRoute({ + getParentRoute: () => RootRoute, + path: "/violations", + component: ViolationsPage, +}); + +function ViolationsPage() { + const v = useViolations(); + + const [viewMode, setViewMode] = useState(readViewMode); + const handleViewModeChange = (mode: ViewMode) => { + setViewMode(mode); + writeViewMode(mode); + }; + + const [skinEnabled, setSkinEnabled] = useState(false); + const [lightboxUrl, setLightboxUrl] = useState(null); + const [exportDialogOpen, setExportDialogOpen] = useState(false); + const [exporting, setExporting] = useState(false); + const [bulkDeleting, setBulkDeleting] = useState(false); + + const handleExportCsv = async () => { + setExporting(true); + try { + await v.exportCsv(); + } finally { + setExporting(false); + } + }; + + const handleBulkDelete = async () => { + setBulkDeleting(true); + try { + await v.bulkDelete(); + } finally { + setBulkDeleting(false); + } + }; + + return ( +
+ setExportDialogOpen(true)} + onSkinToggle={setSkinEnabled} + onLimitChange={(l) => { + v.setLimit(l); + v.setPage(1); + }} + onViewModeChange={handleViewModeChange} + /> + +
+ {viewMode === "grid" ? ( + + ) : ( + + )} +
+ + {!v.loading && v.violations.length > 0 && ( +
+

+ {(v.page - 1) * v.limit + 1}–{Math.min(v.page * v.limit, v.total)} of {v.total} violations +

+
+ + + {v.page} / {v.totalPages} + + +
+
+ )} + + !open && setLightboxUrl(null)}> + + {lightboxUrl && ( +
+ Violation Full Resolution +
+ )} +
+
+ + x.id)} + violations={v.violations} + /> +
+ ); +} diff --git a/headless-rust/frontend/src/routes/violations/ExportImagesDialog.tsx b/headless-rust/frontend/src/routes/violations/ExportImagesDialog.tsx new file mode 100644 index 0000000..fd533e8 --- /dev/null +++ b/headless-rust/frontend/src/routes/violations/ExportImagesDialog.tsx @@ -0,0 +1,201 @@ +import { useState } from "react"; +import { toast } from "sonner"; +import { HugeiconsIcon } from "@hugeicons/react"; +import { Folder01Icon, Download01Icon } from "@hugeicons/core-free-icons"; +import { Button } from "@/components/ui/button"; +import { Progress } from "@/components/ui/progress"; +import { + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogFooter, +} from "@/components/ui/dialog"; +import type { Violation } from "@/shared/types"; + +interface ExportImagesDialogProps { + open: boolean; + onOpenChange: (open: boolean) => void; + selectedIds: number[]; + pageViolationIds: number[]; + violations?: Violation[]; +} + +export function ExportImagesDialog({ + open, + onOpenChange, + selectedIds, + pageViolationIds, + violations = [], +}: ExportImagesDialogProps) { + const selectedCount = selectedIds.length; + const pageViolationCount = pageViolationIds.length; + const targetIds = selectedCount > 0 ? selectedIds : pageViolationIds; + const totalCount = targetIds.length; + + const [exporting, setExporting] = useState(false); + const [exportedCount, setExportedCount] = useState(0); + + const supportsDirectoryPicker = + typeof window !== "undefined" && "showDirectoryPicker" in window; + + const handleExport = async () => { + if (totalCount === 0) { + toast.error("No violations selected to export"); + return; + } + + let dirHandle: any = null; + + if (supportsDirectoryPicker) { + try { + dirHandle = await (window as any).showDirectoryPicker({ + mode: "readwrite", + startIn: "downloads", + }); + } catch (err: any) { + if (err?.name === "AbortError") { + // User closed/cancelled the native folder picker + return; + } + console.warn("[export] Directory picker failed, falling back to download:", err); + } + } + + setExporting(true); + setExportedCount(0); + + let successCount = 0; + let failedCount = 0; + + try { + for (let i = 0; i < targetIds.length; i++) { + const id = targetIds[i]; + try { + const res = await fetch(`/skinned-image?violationId=${id}`); + if (!res.ok) { + throw new Error(`Server returned ${res.status}`); + } + const blob = await res.blob(); + const isPng = blob.type.includes("png"); + const ext = isPng ? "png" : "jpg"; + + const violation = violations.find((v) => v.id === id); + const timePart = violation?.timestamp + ? violation.timestamp.replace(/[:.]/g, "-") + : new Date().toISOString().replace(/[:.]/g, "-"); + const fileName = `violation-${id}-${timePart}.${ext}`; + + if (dirHandle) { + // Native File System Access API + const fileHandle = await dirHandle.getFileHandle(fileName, { create: true }); + const writable = await fileHandle.createWritable(); + await writable.write(blob); + await writable.close(); + } else { + // Fallback direct browser download + const url = URL.createObjectURL(blob); + const a = document.createElement("a"); + a.href = url; + a.download = fileName; + document.body.appendChild(a); + a.click(); + a.remove(); + URL.revokeObjectURL(url); + // Delay slightly between multi-downloads in fallback mode + if (targetIds.length > 1) { + await new Promise((r) => setTimeout(r, 150)); + } + } + + successCount++; + } catch (err) { + console.error(`[export] Failed to export violation #${id}:`, err); + failedCount++; + } + + setExportedCount(i + 1); + } + + if (successCount > 0) { + toast.success( + `Successfully exported ${successCount} image${successCount > 1 ? "s" : ""}${ + failedCount > 0 ? ` (${failedCount} failed)` : "" + } to your device.` + ); + onOpenChange(false); + } else { + toast.error("Failed to export images."); + } + } catch (err: any) { + toast.error(`Export failed: ${err?.message || "Unknown error"}`); + } finally { + setExporting(false); + } + }; + + const handleDialogChange = (nextOpen: boolean) => { + if (!exporting) { + onOpenChange(nextOpen); + } + }; + + const progressPercent = totalCount > 0 ? (exportedCount / totalCount) * 100 : 0; + + return ( + + + + + + Export Skinned Images + + + +
+

+ {selectedCount > 0 + ? `Export ${selectedCount} selected violation(s) with Poliscan overlay to your device.` + : `Export all ${pageViolationCount} violation(s) on this page with Poliscan overlay to your device.`} +

+ + {exporting ? ( +
+
+ Exporting images… + + {exportedCount} / {totalCount} + +
+ +
+ ) : ( +
+ {supportsDirectoryPicker + ? "Clicking export will prompt your device's native folder picker to select a destination directory." + : "Images will be saved directly into your browser's default downloads location."} +
+ )} +
+ + + + + +
+
+ ); +} diff --git a/headless-rust/frontend/src/routes/violations/ViolationGridTile.tsx b/headless-rust/frontend/src/routes/violations/ViolationGridTile.tsx new file mode 100644 index 0000000..9030713 --- /dev/null +++ b/headless-rust/frontend/src/routes/violations/ViolationGridTile.tsx @@ -0,0 +1,138 @@ +import { useState } from "react"; +import { HugeiconsIcon } from "@hugeicons/react"; +import { + ArrowDownBigIcon, + ArrowUpBigIcon, + Delete02Icon, +} from "@hugeicons/core-free-icons"; +import { Button } from "@/components/ui/button"; +import { Checkbox } from "@/components/ui/checkbox"; +import { cn } from "@/lib/utils"; +import type { Violation } from "@/shared/types"; +import { useViolationImage } from "./useViolationImage"; + +interface ViolationGridTileProps { + violation: Violation; + selected: boolean; + skinEnabled: boolean; + onToggleSelect: () => void; + onDelete: () => void; + onImageClick: (url: string) => void; +} + +export function ViolationGridTile({ + violation, + selected, + skinEnabled, + onToggleSelect, + onDelete, + onImageClick, +}: ViolationGridTileProps) { + // ponytail: 400px compressed thumbnail for fast grid rendering over Wi-Fi + const { imageData, imageLoading } = useViolationImage(violation, skinEnabled, { width: 400, quality: 80 }); + const [deleting, setDeleting] = useState(false); + + const over = (violation.measuredSpeed - violation.maxSpeed).toFixed(1); + const formattedTime = new Date(violation.timestamp).toLocaleString(undefined, { + year: "numeric", + month: "short", + day: "numeric", + hour: "2-digit", + minute: "2-digit", + second: "2-digit", + }); + + const fullResUrl = skinEnabled + ? `/skinned-image?violationId=${violation.id}` + : `/image?path=${encodeURIComponent(violation.imagePath)}`; + + const handleDelete = async (e: React.MouseEvent) => { + e.stopPropagation(); + setDeleting(true); + try { + await onDelete(); + } finally { + setDeleting(false); + } + }; + + return ( +
+
onImageClick(fullResUrl)} + > +
e.stopPropagation()} + > + +
+ +
e.stopPropagation()} + > + +
+ + {imageLoading ? ( +
+ ) : imageData ? ( + {`Violation + ) : ( +
+ No image available +
+ )} + +
+ + + + + {violation.measuredSpeed} km/h + +
+
+ +
+
+ Limit: {violation.maxSpeed} km/h + + +{over} km/h + +
+
+ {formattedTime} +
+
+
+ ); +} diff --git a/headless-rust/frontend/src/routes/violations/ViolationRow.tsx b/headless-rust/frontend/src/routes/violations/ViolationRow.tsx new file mode 100644 index 0000000..daae5c5 --- /dev/null +++ b/headless-rust/frontend/src/routes/violations/ViolationRow.tsx @@ -0,0 +1,116 @@ +import { useState } from "react"; +import { HugeiconsIcon } from "@hugeicons/react"; +import { + ArrowDownBigIcon, + ArrowUpBigIcon, + Delete02Icon, +} from "@hugeicons/core-free-icons"; +import { Button } from "@/components/ui/button"; +import { Checkbox } from "@/components/ui/checkbox"; +import type { Violation } from "@/shared/types"; +import { useViolationImage } from "./useViolationImage"; + +interface ViolationRowProps { + violation: Violation; + selected: boolean; + skinEnabled: boolean; + onToggleSelect: () => void; + onDelete: () => void; + onImageClick: (url: string) => void; +} + +export function ViolationRow({ + violation, + selected, + skinEnabled, + onToggleSelect, + onDelete, + onImageClick, +}: ViolationRowProps) { + // ponytail: 160px compressed thumbnail for fast row rendering over Wi-Fi + const { imageData, imageLoading } = useViolationImage(violation, skinEnabled, { width: 160, quality: 75 }); + const [deleting, setDeleting] = useState(false); + + const over = (violation.measuredSpeed - violation.maxSpeed).toFixed(1); + const formattedTime = new Date(violation.timestamp).toLocaleString(undefined, { + year: "numeric", + month: "short", + day: "numeric", + hour: "2-digit", + minute: "2-digit", + second: "2-digit", + }); + + const fullResUrl = skinEnabled + ? `/skinned-image?violationId=${violation.id}` + : `/image?path=${encodeURIComponent(violation.imagePath)}`; + + const handleDelete = async () => { + setDeleting(true); + try { + await onDelete(); + } finally { + setDeleting(false); + } + }; + + return ( + + + + + + + + {formattedTime} + + + + + + + {violation.measuredSpeed} + + {violation.maxSpeed} + +{over} + + + + + ); +} diff --git a/headless-rust/frontend/src/routes/violations/ViolationsGrid.tsx b/headless-rust/frontend/src/routes/violations/ViolationsGrid.tsx new file mode 100644 index 0000000..c763607 --- /dev/null +++ b/headless-rust/frontend/src/routes/violations/ViolationsGrid.tsx @@ -0,0 +1,87 @@ +import { HugeiconsIcon } from "@hugeicons/react"; +import { FilterIcon } from "@hugeicons/core-free-icons"; +import { Checkbox } from "@/components/ui/checkbox"; +import { Skeleton } from "@/components/ui/skeleton"; +import type { Violation } from "@/shared/types"; +import { ViolationGridTile } from "./ViolationGridTile"; + +interface ViolationsGridProps { + violations: Violation[]; + loading: boolean; + limit: number; + skinEnabled: boolean; + selected: Set; + selectedCount: number; + allSelected: boolean; + someSelected: boolean; + onToggleSelect: (id: number) => void; + onToggleSelectAll: () => void; + onDelete: (id: number) => void; + onImageClick: (url: string) => void; +} + +export function ViolationsGrid(props: ViolationsGridProps) { + if (props.loading) { + return ( +
+ {Array.from({ length: props.limit > 25 ? 12 : 8 }).map((_, i) => ( +
+ +
+
+ + +
+ +
+
+ ))} +
+ ); + } + + if (props.violations.length === 0) { + return ( +
+
+ +
+

No violations found

+

+ Speed violations will appear here once the camera detects them, or try adjusting your filters. +

+
+ ); + } + + return ( +
+
+
+ + +
+ {props.violations.length} items on page +
+
+ {props.violations.map((v) => ( + props.onToggleSelect(v.id)} + onDelete={() => props.onDelete(v.id)} + onImageClick={props.onImageClick} + /> + ))} +
+
+ ); +} diff --git a/headless-rust/frontend/src/routes/violations/ViolationsTable.tsx b/headless-rust/frontend/src/routes/violations/ViolationsTable.tsx new file mode 100644 index 0000000..4b673ea --- /dev/null +++ b/headless-rust/frontend/src/routes/violations/ViolationsTable.tsx @@ -0,0 +1,105 @@ +import { HugeiconsIcon } from "@hugeicons/react"; +import { FilterIcon } from "@hugeicons/core-free-icons"; +import { Checkbox } from "@/components/ui/checkbox"; +import { Skeleton } from "@/components/ui/skeleton"; +import type { Violation } from "@/shared/types"; +import { ViolationRow } from "./ViolationRow"; + +interface ViolationsTableProps { + violations: Violation[]; + loading: boolean; + limit: number; + skinEnabled: boolean; + selected: Set; + allSelected: boolean; + someSelected: boolean; + onToggleSelect: (id: number) => void; + onToggleSelectAll: () => void; + onDelete: (id: number) => void; + onImageClick: (url: string) => void; +} + +export function ViolationsTable(props: ViolationsTableProps) { + if (props.loading) { + return ( + + + + + + + + + + + + + {Array.from({ length: 8 }).map((_, i) => ( + + + + + + + + + + + ))} + +
+ ImageTimestampDirSpeed (km/h)Limit (km/h)Over +
+ ); + } + + if (props.violations.length === 0) { + return ( +
+
+ +
+

No violations found

+

+ Speed violations will appear here once the camera detects them, or try adjusting your filters. +

+
+ ); + } + + return ( + + + + + + + + + + + + + + {props.violations.map((v) => ( + props.onToggleSelect(v.id)} + onDelete={() => props.onDelete(v.id)} + onImageClick={props.onImageClick} + /> + ))} + +
+ + ImageTimestampDirSpeed (km/h)Limit (km/h)Over +
+ ); +} diff --git a/headless-rust/frontend/src/routes/violations/ViolationsToolbar.tsx b/headless-rust/frontend/src/routes/violations/ViolationsToolbar.tsx new file mode 100644 index 0000000..7f27ab2 --- /dev/null +++ b/headless-rust/frontend/src/routes/violations/ViolationsToolbar.tsx @@ -0,0 +1,157 @@ +import { HugeiconsIcon } from "@hugeicons/react"; +import { + Delete02Icon, + Download01Icon, + FilterIcon, + GridViewIcon, + Image01Icon, + LayoutList, +} from "@hugeicons/core-free-icons"; +import { Button } from "@/components/ui/button"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select"; +import { Switch } from "@/components/ui/switch"; +import { PAGE_SIZE_OPTIONS, type PageSize, type ViewMode } from "./useViolations"; + +interface ViolationsToolbarProps { + dateFrom: string; + dateTo: string; + minSpeed: string; + selectedCount: number; + total: number; + exporting: boolean; + bulkDeleting: boolean; + skinEnabled: boolean; + limit: PageSize; + viewMode: ViewMode; + onDateFrom: (v: string) => void; + onDateTo: (v: string) => void; + onMinSpeed: (v: string) => void; + onApplyFilters: () => void; + onBulkDelete: () => void; + onExportCsv: () => void; + onOpenExportImages: () => void; + onSkinToggle: (v: boolean) => void; + onLimitChange: (l: PageSize) => void; + onViewModeChange: (m: ViewMode) => void; +} + +export function ViolationsToolbar(props: ViolationsToolbarProps) { + return ( +
+
+ + props.onDateFrom(e.target.value)} + className="h-8 px-2 text-sm rounded-lg border border-input bg-input/30 focus:outline-none focus:ring-2 focus:ring-ring/50 focus:border-ring" + /> +
+
+ + props.onDateTo(e.target.value)} + className="h-8 px-2 text-sm rounded-lg border border-input bg-input/30 focus:outline-none focus:ring-2 focus:ring-ring/50 focus:border-ring" + /> +
+
+ + props.onMinSpeed(e.target.value)} + placeholder="e.g. 50" + className="h-8 w-28 px-2 text-sm rounded-lg border border-input bg-input/30 focus:outline-none focus:ring-2 focus:ring-ring/50 focus:border-ring" + /> +
+ +
+ {props.selectedCount > 0 && ( + + )} + + +
+ + Poliscan Skin +
+ + +
+ + +
+
+
+ ); +} diff --git a/headless-rust/frontend/src/routes/violations/useViolationImage.ts b/headless-rust/frontend/src/routes/violations/useViolationImage.ts new file mode 100644 index 0000000..259ff4b --- /dev/null +++ b/headless-rust/frontend/src/routes/violations/useViolationImage.ts @@ -0,0 +1,43 @@ +import { useEffect, useState } from "react"; +import { getRpc } from "@/lib/rpc"; +import type { Violation } from "@/shared/types"; + +export interface ViolationImageOptions { + width?: number; + height?: number; + quality?: number; + format?: "webp" | "jpeg" | "png" | "auto"; +} + +/** + * Fetches a compressed violation thumbnail or full-res image (raw or Poliscan-skinned). + * Shared by ViolationRow and ViolationGridTile to dedupe fetch effects. + */ +export function useViolationImage( + violation: Violation, + skinEnabled: boolean, + options?: ViolationImageOptions, +) { + const [imageData, setImageData] = useState(null); + const [imageLoading, setImageLoading] = useState(true); + + const width = options?.width; + const height = options?.height; + const quality = options?.quality; + const format = options?.format; + + useEffect(() => { + let cancelled = false; + setImageLoading(true); + const fetchImage = skinEnabled + ? getRpc().request.getSkinnedImageData({ violationId: violation.id, width, height, quality, format }) + : getRpc().request.getImageData({ imagePath: violation.imagePath, width, height, quality, format }); + fetchImage + .then((data) => { if (!cancelled) setImageData(data); }) + .catch(() => { if (!cancelled) setImageData(null); }) + .finally(() => { if (!cancelled) setImageLoading(false); }); + return () => { cancelled = true; }; + }, [violation.imagePath, violation.id, skinEnabled, width, height, quality, format]); + + return { imageData, imageLoading }; +} diff --git a/headless-rust/frontend/src/routes/violations/useViolations.ts b/headless-rust/frontend/src/routes/violations/useViolations.ts new file mode 100644 index 0000000..6a4a7f6 --- /dev/null +++ b/headless-rust/frontend/src/routes/violations/useViolations.ts @@ -0,0 +1,202 @@ +import { useCallback, useEffect, useState } from "react"; +import { toast } from "sonner"; +import { getRpc } from "@/lib/rpc"; +import { useBackendEvent } from "@/hooks/useBackendEvent"; +import type { Violation, ViolationQuery } from "@/shared/types"; + +export const PAGE_SIZE_OPTIONS = [25, 50, 100] as const; +export type PageSize = (typeof PAGE_SIZE_OPTIONS)[number]; + +export type ViewMode = "list" | "grid"; + +const VIEW_MODE_KEY = "violations_view_mode"; + +export function readViewMode(): ViewMode { + return (localStorage.getItem(VIEW_MODE_KEY) as ViewMode) || "list"; +} + +export function writeViewMode(mode: ViewMode) { + localStorage.setItem(VIEW_MODE_KEY, mode); +} + +export interface ViolationsState { + violations: Violation[]; + total: number; + page: number; + limit: PageSize; + dateFrom: string; + dateTo: string; + minSpeed: string; + loading: boolean; + selected: Set; + totalPages: number; + allSelected: boolean; + someSelected: boolean; + setPage: (p: number) => void; + setLimit: (l: PageSize) => void; + setDateFrom: (v: string) => void; + setDateTo: (v: string) => void; + setMinSpeed: (v: string) => void; + applyFilters: () => void; + toggleSelect: (id: number) => void; + toggleSelectAll: () => void; + deleteViolation: (id: number) => Promise; + bulkDelete: () => Promise; + exportCsv: () => Promise; + refetch: () => Promise; +} + +export function useViolations(): ViolationsState { + const [violations, setViolations] = useState([]); + const [total, setTotal] = useState(0); + const [page, setPage] = useState(1); + const [limit, setLimit] = useState(25); + const [dateFrom, setDateFrom] = useState(""); + const [dateTo, setDateTo] = useState(""); + const [minSpeed, setMinSpeed] = useState(""); + const [loading, setLoading] = useState(false); + const [selected, setSelected] = useState>(new Set()); + + const totalPages = Math.max(1, Math.ceil(total / limit)); + + const fetchViolations = useCallback(async () => { + setLoading(true); + setSelected(new Set()); + try { + const query: ViolationQuery = { + page, + limit, + ...(dateFrom ? { dateFrom } : {}), + ...(dateTo ? { dateTo } : {}), + ...(minSpeed ? { minSpeed: Number(minSpeed) } : {}), + }; + const result = await getRpc().request.getViolations(query); + setViolations(result.violations); + setTotal(result.total); + } catch { + toast.error("Failed to load violations"); + } finally { + setLoading(false); + } + }, [page, limit, dateFrom, dateTo, minSpeed]); + + useEffect(() => { + void fetchViolations(); + }, [fetchViolations]); + + // Real-time listener for newly captured violations + useBackendEvent("violation", (newViolation) => { + // If on first page and no active filter, prepend directly for zero-latency UI update + if (page === 1 && !dateFrom && !dateTo && !minSpeed) { + setViolations((prev) => { + if (prev.some((v) => v.id === newViolation.id)) return prev; + return [newViolation, ...prev.slice(0, limit - 1)]; + }); + setTotal((prev) => prev + 1); + } else { + // Otherwise trigger refetch to keep pagination counts consistent + void fetchViolations(); + } + }); + + const deleteViolation = useCallback(async (id: number) => { + try { + await getRpc().request.deleteViolation({ id }); + setViolations((prev) => prev.filter((v) => v.id !== id)); + setTotal((prev) => prev - 1); + setSelected((prev) => { + const next = new Set(prev); + next.delete(id); + return next; + }); + } catch { + toast.error("Failed to delete violation"); + } + }, []); + + const bulkDelete = useCallback(async () => { + if (selected.size === 0) return; + try { + await Promise.all( + [...selected].map((id) => getRpc().request.deleteViolation({ id })), + ); + await fetchViolations(); + toast.success(`Deleted ${selected.size} violations`); + } catch { + toast.error("Failed to delete some violations"); + } + }, [selected, fetchViolations]); + + const exportCsv = useCallback(async () => { + try { + const csv = await getRpc().request.exportViolationsCsv({ + ...(dateFrom ? { dateFrom } : {}), + ...(dateTo ? { dateTo } : {}), + ...(minSpeed ? { minSpeed: Number(minSpeed) } : {}), + }); + const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" }); + const url = URL.createObjectURL(blob); + const a = document.createElement("a"); + a.href = url; + a.download = `violations-${new Date().toISOString().slice(0, 10)}.csv`; + document.body.appendChild(a); + a.click(); + a.remove(); + URL.revokeObjectURL(url); + } catch { + toast.error("Failed to export CSV"); + } + }, [dateFrom, dateTo, minSpeed]); + + const toggleSelect = useCallback((id: number) => { + setSelected((prev) => { + const next = new Set(prev); + if (next.has(id)) next.delete(id); + else next.add(id); + return next; + }); + }, []); + + const allSelected = violations.length > 0 && violations.every((v) => selected.has(v.id)); + const someSelected = violations.some((v) => selected.has(v.id)); + + const toggleSelectAll = useCallback(() => { + setSelected((prev) => + violations.length > 0 && violations.every((v) => prev.has(v.id)) + ? new Set() + : new Set(violations.map((v) => v.id)), + ); + }, [violations]); + + const applyFilters = useCallback(() => { + setPage(1); + void fetchViolations(); + }, [fetchViolations]); + + return { + violations, + total, + page, + limit, + dateFrom, + dateTo, + minSpeed, + loading, + selected, + totalPages, + allSelected, + someSelected, + setPage, + setLimit, + setDateFrom, + setDateTo, + setMinSpeed, + applyFilters, + toggleSelect, + toggleSelectAll, + deleteViolation, + bulkDelete, + exportCsv, + refetch: fetchViolations, + }; +} diff --git a/headless-rust/frontend/src/shared/schemas.ts b/headless-rust/frontend/src/shared/schemas.ts new file mode 100644 index 0000000..a3a34a9 --- /dev/null +++ b/headless-rust/frontend/src/shared/schemas.ts @@ -0,0 +1,99 @@ +import { z } from "zod"; + +// ─── Incoming: ESP → Host ───────────────────────────────────────────────────── + +const EspSpeedingSchema = z.object({ + status: z.literal("speeding"), + value: z.number().nonnegative().max(300), + tolerance: z.number().nonnegative(), + direction: z.enum(["forward", "reverse"]), +}); + +const EspLegalSchema = z.object({ + status: z.literal("legal"), + value: z.number().nonnegative().max(300), + tolerance: z.number().nonnegative(), + direction: z.enum(["forward", "reverse"]), +}); + +export const EspPongConfigSchema = z.object({ + maxSpeed: z.number().positive(), + sensorDistance: z.number().positive(), + debugEnabled: z.boolean(), + lapMode: z.enum(["single", "multi"]), + lapActive: z.boolean(), + lapAutoFlash: z.boolean().optional(), + lapDirFilter: z.enum(["both", "forward", "reverse"]), +}); + +const EspPongSchema = z.object({ + status: z.literal("pong"), + config: EspPongConfigSchema, +}); + +const EspConfigAckSchema = z.object({ + status: z.literal("config"), + key: z.string(), + value: z.number(), +}); + +const EspConfigErrorSchema = z.object({ + status: z.literal("configError"), + message: z.string(), +}); + +// Simple statuses with no extra fields +const EspReadySchema = z.object({ status: z.literal("ready") }); +const EspMeasuringSchema = z.object({ status: z.literal("measuring") }); +const EspTimeoutSchema = z.object({ status: z.literal("timeout") }); +const EspJsonErrorSchema = z.object({ status: z.literal("jsonError") }); + +// ─── Lap Timer Messages ─────────────────────────────────────────────────────── + +const EspLapWaitingSchema = z.object({ status: z.literal("lapWaiting") }); +const EspLapStoppedSchema = z.object({ status: z.literal("lapStopped") }); + +const EspLapStartSchema = z.object({ + status: z.literal("lapStart"), + lapNumber: z.number().int().positive(), + speedAtStart: z.number().nonnegative(), +}); + +const EspLapEndSchema = z.object({ + status: z.literal("lapEnd"), + lapNumber: z.number().int().positive(), + durationMs: z.number().positive(), + speedAtStart: z.number().nonnegative(), + speedAtEnd: z.number().nonnegative(), +}); + +export const EspMessageSchema = z.discriminatedUnion("status", [ + EspSpeedingSchema, + EspLegalSchema, + EspPongSchema, + EspConfigAckSchema, + EspConfigErrorSchema, + EspReadySchema, + EspMeasuringSchema, + EspTimeoutSchema, + EspJsonErrorSchema, + EspLapWaitingSchema, + EspLapStoppedSchema, + EspLapStartSchema, + EspLapEndSchema, +]); + +export type EspMessage = z.infer; +export type EspPongConfig = z.infer; + +// ─── Outgoing: Host → ESP ───────────────────────────────────────────────────── + +export const EspCommandSchema = z.discriminatedUnion("command", [ + z.object({ command: z.literal("ping") }), + z.object({ command: z.literal("setMaxSpeed"), value: z.number().min(1).max(250) }), + z.object({ command: z.literal("setDebug"), value: z.union([z.literal(0), z.literal(1)]) }), + z.object({ command: z.literal("startLapSession"), mode: z.enum(["single", "multi"]), autoFlash: z.boolean().optional(), dirFilter: z.enum(["both", "forward", "reverse"]).optional() }), + z.object({ command: z.literal("stopLapSession") }), +]); + +export type EspCommand = z.infer; diff --git a/headless-rust/frontend/src/shared/types.ts b/headless-rust/frontend/src/shared/types.ts new file mode 100644 index 0000000..015831a --- /dev/null +++ b/headless-rust/frontend/src/shared/types.ts @@ -0,0 +1,635 @@ +// ─── Domain Types ─────────────────────────────────────────────────────────── + +export interface NetworkInterfaceDetail { + name: string; + role: "camera-lan" | "hotspot-ap" | "wifi-client" | "other" | "loopback"; + address: string; + family: string; + netmask: string; + mac: string; + expectedIp?: string; + isConfigured: boolean; +} + +export interface WifiClientInfo { + interfaceName: string | null; + ssid: string | null; + ip: string | null; + subnet: string | null; + gateway: string | null; + signalDbm?: number; + powerSave?: string; + status: "connected" | "connecting" | "disconnected" | "inactive"; + description: string; +} + +export interface SystemNetworkSummary { + mode: "ap" | "client" | "field" | "wifi-client" | "dhcp" | "custom"; + wifiMode?: "ap" | "client" | "disconnected"; + ethernetMode?: "camera-lan" | "dhcp" | "unmanaged"; + wifiMac?: string | null; + ethernetMac?: string | null; + cameraLan: { + interfaceName: string | null; + ip: string | null; + expectedIp: string; + subnet: string; + status: "ok" | "ip_mismatch" | "missing" | "inactive"; + description: string; + }; + hotspotAp: { + interfaceName: string | null; + ip: string | null; + expectedIp: string; + subnet: string; + status: "ok" | "ip_mismatch" | "missing" | "inactive"; + description: string; + }; + wifiClient?: WifiClientInfo | null; + interfaces: NetworkInterfaceDetail[]; +} + +export interface WifiScanResult { + ssid: string; + bssid?: string; + channel?: number; + signal: number; + security: string; + inUse: boolean; +} + +export interface ApplyNetworkModeInput { + mode: "ap" | "client" | "forget" | "lan-camera" | "lan-dhcp" | "field" | "wifi-client" | "dhcp"; + ssid?: string; + password?: string; +} + +export interface NetworkOperationResult { + success: boolean; + mode: string; + message: string; + details?: string; +} + +export interface Violation { + id: number; + timestamp: string; // ISO 8601 + measuredSpeed: number; + maxSpeed: number; + direction: "forward" | "reverse"; + imagePath: string; + createdAt: string; // ISO 8601 +} + +export interface SaveViolationInput { + imageBase64?: string; // raw base64 (optional if captured backend-side) + measuredSpeed: number; + maxSpeed: number; + direction: "forward" | "reverse"; +} + +export interface AppSettings { + maxSpeed: number; // km/h, default 30 + selectedPort: string; // serial port path, default "" + // Industrial Camera Settings + cameraExposure: number; + cameraGain: number; + strobeLineDuration: number; + pixelFormat: string; // "Mono" | "Color" + exposureAuto: string; // "Off" | "Once" | "Continuous" + gainAuto: string; // "Off" | "Once" | "Continuous" + frameRate: number; + cameraWidth: number; + cameraHeight: number; + blackLevel: number; + // Lap timer settings + lapMode: string; // "single" | "multi", default "single" + lapSaveImages: string; // "true" | "false", default "true" + lapDirFilter: string; // "both" | "forward" | "reverse", default "both" + // Teable integration + teableUrl: string; + teableToken: string; + teableUserName: string; + teableUserEmail: string; + teableUserAvatar: string; + teableSpaceId: string; + teableBaseId: string; + teableTableId: string; + teableSyncEnabled: string; // "true" | "false" + // GitHub access + githubToken: string; + // Poliscan skin + skinMeasuringLocation: string; // e.g. "BAB 2 Km 81,2, Ri. Hannover" +} + +export interface PortInfo { + path: string; + manufacturer?: string; + serialNumber?: string; + pnpId?: string; + locationId?: string; + productId?: string; + vendorId?: string; +} + +export interface CameraInfo { + id: string; + vendor: string; + model: string; +} + +export interface HwControl { + name: string; + type: "int" | "bool"; + min?: number; + max?: number; + step?: number; + default?: number; + value: number; +} + +export interface MfsConfigResult { + applied: string[]; + failed: string[]; +} + +export interface CameraStatusPayload { + connected: boolean; + vendor: string | null; + model: string | null; + serial: string | null; + isStreaming: boolean; +} + +export interface ViolationQuery { + page: number; + limit: number; + dateFrom?: string; + dateTo?: string; + minSpeed?: number; +} + +export interface ViolationPage { + violations: Violation[]; + total: number; +} + +// ─── Lap Timer Types ───────────────────────────────────────────────────────── + +export interface LapSession { + id: number; + startedAt: string; // ISO 8601 + endedAt: string | null; // ISO 8601, null while session is active + lapMode: string; // "single" | "multi" + createdAt: string; // ISO 8601 +} + +export interface Lap { + id: number; + sessionId: number; + lapNumber: number; + startTimestamp: number; // ms (Date.now()) + endTimestamp: number; // ms (Date.now()) + durationMs: number; + speedAtStart: number; + speedAtEnd: number; + startImagePath: string | null; + endImagePath: string | null; +} + +export interface LapSessionWithLaps extends LapSession { + laps: Lap[]; +} + +export interface SaveLapInput { + sessionId: number; + lapNumber: number; + startTimestamp: number; + endTimestamp: number; + durationMs: number; + speedAtStart: number; + speedAtEnd: number; + startImageBase64: string | null; // raw base64, no data-URL prefix + endImageBase64: string | null; // raw base64, no data-URL prefix +} + +// ─── Teable Types ──────────────────────────────────────────────────────────── + +export interface TeableUser { + id: string; + name: string; + email: string; + avatar: string | null; +} + +export interface TeableSpace { + id: string; + name: string; +} + +export interface TeableBase { + id: string; + name: string; + spaceId: string; +} + +export interface TeableTable { + id: string; + name: string; +} + +export interface TeableSchemaCheck { + missingFields: string[]; +} + +export interface SyncLapInput { + lap: Lap; + session: LapSession; +} + +// ─── ESP Pong Config ────────────────────────────────────────────────────────── + +export interface EspPongConfig { + maxSpeed: number; + flashDelay?: number; + flashDuration?: number; + sensorDistance: number; + debugEnabled: boolean; + lapMode: "single" | "multi"; + lapActive: boolean; + lapAutoFlash?: boolean; + lapDirFilter: "both" | "forward" | "reverse"; +} + +// ─── Firmware Flasher Types ─────────────────────────────────────────────────── + +export interface GithubRelease { + tag: string; + name: string; + publishedAt: string; + prerelease: boolean; + /** API URL for the firmware.bin asset — use with auth header for private repos */ + firmwareAssetApiUrl: string; +} + +export type FlashProgressPayload = + | { type: "downloading" } + | { type: "output"; line: string } + | { type: "done" } + | { type: "error"; message: string }; + +// ─── Serial Status Message ─────────────────────────────────────────────────── + +export type SerialStatusPayload = + | { status: "SPEEDING"; value: number; tolerance: number; direction: "forward" | "reverse"; timestamp: number } + | { status: "OK"; value: number; tolerance: number; direction: "forward" | "reverse"; timestamp: number } + | { status: "PONG"; config: EspPongConfig } + | { status: "LAPSTART"; lapNumber: number; speedAtStart: number; timestamp: number } + | { status: "LAPEND"; lapNumber: number; durationMs: number; speedAtStart: number; speedAtEnd: number; timestamp: number } + | { status: "LAPWAITING" } + | { status: "LAPSTOPPED" } + | { status: "CONNECTED"; port?: string } + | { status: "DISCONNECTED" }; + +// ─── RPC Schema Definition ──────────────────────────────────────────────────── + +export interface RPCDefinition< + TRequests extends Record, + TMessages extends Record +> { + requests: TRequests; + messages: TMessages; +} + +export type SpeedcameraRPC = { + bun: RPCDefinition<{ + // DB – violations + getViolations: { + params: ViolationQuery; + response: ViolationPage; + }; + getViolationById: { + params: { id: number }; + response: Violation | null; + }; + deleteViolation: { + params: { id: number }; + response: void; + }; + exportViolationsCsv: { + params: { dateFrom?: string; dateTo?: string; minSpeed?: number }; + response: string; // CSV text + }; + saveViolation: { + params: SaveViolationInput; + response: Violation; + }; + + // DB – lap sessions + createLapSession: { + params: { lapMode: string }; + response: LapSession; + }; + closeLapSession: { + params: { id: number }; + response: void; + }; + saveLap: { + params: SaveLapInput; + response: Lap; + }; + getLapSessions: { + params: { page: number; limit: number }; + response: { sessions: LapSessionWithLaps[]; total: number }; + }; + getLapSessionById: { + params: { id: number }; + response: LapSessionWithLaps | null; + }; + deleteLapSession: { + params: { id: number }; + response: void; + }; + deleteLap: { + params: { id: number }; + response: void; + }; + + // DB – images + getImageData: { + params: { + imagePath: string; + width?: number; + height?: number; + quality?: number; + format?: "webp" | "jpeg" | "png" | "auto"; + }; + response: string; // data-URL or path + }; + getSkinnedImageData: { + params: { + violationId: number; + width?: number; + height?: number; + quality?: number; + format?: "webp" | "jpeg" | "png" | "auto"; + }; + response: string; // data-URL or URL of skinned image + }; + exportSkinnedImages: { + params: { violationIds: number[]; targetDir: string }; + response: { exported: number; failed: number }; + }; + + // System / Armed State + getArmedState: { + params: Record; + response: { armed: boolean }; + }; + setArmed: { + params: { armed: boolean }; + response: { armed: boolean }; + }; + + // DB – settings + getSettings: { + params: Record; + response: AppSettings; + }; + saveSetting: { + params: { key: keyof AppSettings; value: string }; + response: void; + }; + + // Serial + listPorts: { + params: Record; + response: PortInfo[]; + }; + getSerialStatus: { + params: Record; + response: { connected: boolean; port: string | null }; + }; + openPort: { + params: { path: string }; + response: void; + }; + closePort: { + params: Record; + response: void; + }; + sendCommand: { + params: { json: string }; + response: void; + }; + + // Camera HW (Industrial / bun-aravis) + connectCamera: { + params: Record; + response: void; + }; + disconnectCamera: { + params: Record; + response: void; + }; + getCameraStatus: { + params: Record; + response: CameraStatusPayload; + }; + captureFrame: { + params: Record; + response: string | null; // base64 + }; + setCameraExposure: { + params: { value: number }; + response: void; + }; + setCameraGain: { + params: { value: number }; + response: void; + }; + applyMfsConfig: { + params: { mfsContent: string; saveAsDefault: boolean }; + response: MfsConfigResult; + }; + startSetupStream: { + params: Record; + response: void; + }; + stopSetupStream: { + params: Record; + response: void; + }; + setCameraPixelFormat: { + params: { format: string }; + response: void; + }; + getCameraPixelFormat: { + params: Record; + response: string; + }; + setCameraStrobeDuration: { + params: { value: number }; + response: void; + }; + setCameraFeatureStr: { + params: { feature: string; value: string }; + response: void; + }; + setCameraFeatureInt: { + params: { feature: string; value: number }; + response: void; + }; + + // Window (stubs in headless mode) + minimizeWindow: { + params: Record; + response: void; + }; + maximizeWindow: { + params: Record; + response: void; + }; + closeWindow: { + params: Record; + response: void; + }; + + // System & Network + getPlatform: { + params: Record; + response: string; + }; + getNetworkInfo: { + params: Record; + response: SystemNetworkSummary; + }; + scanWifiNetworks: { + params: Record; + response: WifiScanResult[]; + }; + applyNetworkMode: { + params: ApplyNetworkModeInput; + response: NetworkOperationResult; + }; + forgetWifi: { + params: Record; + response: NetworkOperationResult; + }; + setEthernetMode: { + params: { mode: "camera-lan" | "lan-dhcp" }; + response: NetworkOperationResult; + }; + + // Teable integration + testTeableConnection: { + params: { url: string; token: string }; + response: TeableUser; + }; + saveTeableConfig: { + params: { url: string; token: string; userName: string; userEmail: string; userAvatar: string | null }; + response: void; + }; + removeTeableConfig: { + params: Record; + response: void; + }; + listTeableSpaces: { + params: Record; + response: TeableSpace[]; + }; + listTeableBases: { + params: { spaceId: string }; + response: TeableBase[]; + }; + listTeableTables: { + params: { baseId: string }; + response: TeableTable[]; + }; + verifyTeableTable: { + params: { tableId: string }; + response: TeableSchemaCheck; + }; + ensureTeableFields: { + params: { tableId: string }; + response: string[]; + }; + createTeableTable: { + params: { baseId: string; tableName: string }; + response: TeableTable; + }; + saveTeableTarget: { + params: { spaceId: string; baseId: string; tableId: string }; + response: void; + }; + syncLapToTeable: { + params: SyncLapInput; + response: void; + }; + + // Updater + getLocalVersion: { + params: Record; + response: { version: string; channel: string; hash: string }; + }; + checkForUpdate: { + params: Record; + response: { + version: string; + hash: string; + updateAvailable: boolean; + updateReady: boolean; + error: string; + }; + }; + downloadUpdate: { + params: Record; + response: { ok: boolean; error?: string }; + }; + applyUpdate: { + params: Record; + response: void; + }; + + // Firmware flasher + listFirmwareReleases: { + params: Record; + response: GithubRelease[]; + }; + flashFirmware: { + params: { releaseTag: string; port: string; firmwareAssetApiUrl: string }; + response: void; + }; + cancelFlash: { + params: Record; + response: void; + }; + testGithubToken: { + params: { token: string }; + response: { valid: boolean; login?: string; error?: string }; + }; + }, Record>; + + webview: RPCDefinition, { + // Serial measurement updates + serialStatus: SerialStatusPayload; + // Camera connection status + cameraStatus: CameraStatusPayload; + // App update notifications + updateAvailable: { version: string }; + // Updater status stream + updateProgress: { + status: string; + message: string; + progress?: number; + }; + // Esptool progress stream + flashProgress: FlashProgressPayload; + // Live stream frame + liveFrame: string; + // Armed status notification + armedStatus: { armed: boolean }; + // Violation notification + violation: Violation; + }>; +}; diff --git a/headless-rust/frontend/src/stores/slices/cameraSlice.ts b/headless-rust/frontend/src/stores/slices/cameraSlice.ts new file mode 100644 index 0000000..0752646 --- /dev/null +++ b/headless-rust/frontend/src/stores/slices/cameraSlice.ts @@ -0,0 +1,147 @@ +import type { StateCreator } from "zustand"; +import type { CameraStatusPayload, MfsConfigResult, AppSettings } from "@/shared/types"; +import { getRpc } from "@/lib/rpc"; + +export interface CameraSlice { + cameraConnected: boolean; + cameraVendor: string | null; + cameraModel: string | null; + cameraSerial: string | null; + cameraExposure: number; + cameraGain: number; + pixelFormat: string; + exposureAuto: string; + gainAuto: string; + frameRate: number; + cameraWidth: number; + cameraHeight: number; + blackLevel: number; + strobeLineDuration: number; + setupStreamActive: boolean; + liveFrame: string | null; + mfsResult: MfsConfigResult | null; + setCameraStatus: (status: CameraStatusPayload) => void; + refreshCameraStatus: () => Promise; + connectCamera: () => Promise; + disconnectCamera: () => Promise; + setCameraExposure: (value: number) => Promise; + setCameraGain: (value: number) => Promise; + setCameraFeature: (key: string, value: string | number) => Promise; + startSetupStream: () => Promise; + stopSetupStream: () => Promise; + setLiveFrame: (frame: string) => void; + applyMfsConfig: (mfsContent: string, saveAsDefault: boolean) => Promise; + clearMfsResult: () => void; + loadCameraSettings: (settings: AppSettings) => void; +} + +export const createCameraSlice: StateCreator = (set) => ({ + cameraConnected: false, + cameraVendor: null, + cameraModel: null, + cameraSerial: null, + cameraExposure: 5000, + cameraGain: 0, + pixelFormat: "Mono", + exposureAuto: "Off", + gainAuto: "Off", + frameRate: 30, + cameraWidth: 1280, + cameraHeight: 1024, + blackLevel: 0, + strobeLineDuration: 5000, + setupStreamActive: false, + liveFrame: null, + mfsResult: null, + loadCameraSettings: (settings) => set({ + cameraExposure: settings.cameraExposure ?? 5000, + cameraGain: settings.cameraGain ?? 0, + pixelFormat: settings.pixelFormat ?? "Mono", + exposureAuto: settings.exposureAuto ?? "Off", + gainAuto: settings.gainAuto ?? "Off", + frameRate: settings.frameRate ?? 30, + cameraWidth: settings.cameraWidth ?? 1280, + cameraHeight: settings.cameraHeight ?? 1024, + blackLevel: settings.blackLevel ?? 0, + strobeLineDuration: settings.strobeLineDuration ?? 5000, + }), + setCameraStatus: (status) => set({ + cameraConnected: status.connected, + cameraVendor: status.vendor, + cameraModel: status.model, + cameraSerial: status.serial, + setupStreamActive: status.isStreaming, + }), + + connectCamera: async () => { + await getRpc().request.connectCamera({}); + }, + + refreshCameraStatus: async () => { + const status = await getRpc().request.getCameraStatus({}); + set({ + cameraConnected: status.connected, + cameraVendor: status.vendor, + cameraModel: status.model, + cameraSerial: status.serial, + setupStreamActive: status.isStreaming, + }); + }, + + disconnectCamera: async () => { + await getRpc().request.disconnectCamera({}); + }, + + setCameraExposure: async (value) => { + await getRpc().request.setCameraExposure({ value }); + await getRpc().request.saveSetting({ key: "cameraExposure", value: value.toString() }); + set({ cameraExposure: value }); + }, + + setCameraGain: async (value) => { + await getRpc().request.setCameraGain({ value }); + await getRpc().request.saveSetting({ key: "cameraGain", value: value.toString() }); + set({ cameraGain: value }); + }, + + setCameraFeature: async (key, value) => { + if (typeof value === "string") { + if (key === "pixelFormat") { + await getRpc().request.setCameraPixelFormat({ format: value }); + } else { + await getRpc().request.setCameraFeatureStr({ feature: key.charAt(0).toUpperCase() + key.slice(1), value }); + } + } else { + if (key === "strobeLineDuration") { + await getRpc().request.setCameraStrobeDuration({ value }); + } else if (key === "cameraExposure") { + await getRpc().request.setCameraExposure({ value }); + } else if (key === "cameraGain") { + await getRpc().request.setCameraGain({ value }); + } else { + await getRpc().request.setCameraFeatureInt({ feature: key.charAt(0).toUpperCase() + key.slice(1), value }); + } + } + await getRpc().request.saveSetting({ key: key as keyof AppSettings, value: value.toString() }); + set({ [key]: value } as Partial); + }, + + startSetupStream: async () => { + set({ setupStreamActive: true, liveFrame: null }); + await getRpc().request.startSetupStream({}); + }, + + stopSetupStream: async () => { + set({ setupStreamActive: false, liveFrame: null }); + await getRpc().request.stopSetupStream({}); + }, + + setLiveFrame: (frame) => set({ liveFrame: frame }), + + applyMfsConfig: async (mfsContent, saveAsDefault) => { + const result = await getRpc().request.applyMfsConfig({ mfsContent, saveAsDefault }); + set({ mfsResult: result }); + }, + + clearMfsResult: () => set({ mfsResult: null }), +}); diff --git a/headless-rust/frontend/src/stores/slices/flasherSlice.ts b/headless-rust/frontend/src/stores/slices/flasherSlice.ts new file mode 100644 index 0000000..c0d670c --- /dev/null +++ b/headless-rust/frontend/src/stores/slices/flasherSlice.ts @@ -0,0 +1,38 @@ +import type { StateCreator } from "zustand"; +import type { FlashProgressPayload } from "@/shared/types"; + +export interface FlasherSlice { + isFlashing: boolean; + flashProgressLines: string[]; + flashError: string | null; + flashDone: boolean; + handleFlashProgress: (payload: FlashProgressPayload) => void; + resetFlash: () => void; +} + +export const createFlasherSlice: StateCreator = (set) => ({ + isFlashing: false, + flashProgressLines: [], + flashError: null, + flashDone: false, + + handleFlashProgress: (payload) => { + switch (payload.type) { + case "downloading": + set({ isFlashing: true, flashProgressLines: ["Downloading firmware…"], flashError: null, flashDone: false }); + break; + case "output": + set((s) => ({ flashProgressLines: [...s.flashProgressLines, payload.line] })); + break; + case "done": + set({ isFlashing: false, flashDone: true }); + break; + case "error": + set({ isFlashing: false, flashError: payload.message }); + break; + } + }, + + resetFlash: () => + set({ isFlashing: false, flashProgressLines: [], flashError: null, flashDone: false }), +}); diff --git a/headless-rust/frontend/src/stores/slices/lapSlice.ts b/headless-rust/frontend/src/stores/slices/lapSlice.ts new file mode 100644 index 0000000..e7542e3 --- /dev/null +++ b/headless-rust/frontend/src/stores/slices/lapSlice.ts @@ -0,0 +1,280 @@ +import type { StateCreator } from "zustand"; +import type { Lap, LapSession, LapSessionWithLaps, SerialStatusPayload, AppSettings } from "@/shared/types"; +import type { CameraSlice } from "./cameraSlice"; +import type { TeableSlice } from "./teableSlice"; +import type { SystemSlice } from "./systemSlice"; +import { getRpc } from "@/lib/rpc"; +import { toast } from "sonner"; + +// ─── Types ──────────────────────────────────────────────────────────────────── + +export type LapState = "idle" | "waiting" | "timing"; + +export interface LapSettings { + lapMode: "single" | "multi"; + saveImages: boolean; + dirFilter: "both" | "forward" | "reverse"; +} + +export interface LapSlice { + lapState: LapState; + currentSession: LapSession | null; + currentLaps: Lap[]; + /** Lap number that is currently being timed (1-based) */ + lapNumber: number; + /** Host-side timestamp (Date.now()) captured when LAPSTART was received, for the live timer */ + lapTimingStartedAt: number | null; + lapSettings: LapSettings; + lapHistory: { sessions: LapSessionWithLaps[]; total: number }; + isLapSaving: boolean; + + startLapSession: () => Promise; + stopLapSession: () => Promise; + handleSerialStatusForLap: (payload: SerialStatusPayload) => void; + loadLapSettings: () => Promise; + updateLapSetting: (key: keyof AppSettings, value: string) => Promise; + fetchLapHistory: (page: number, limit: number) => Promise; + deleteHistorySession: (id: number) => Promise; + deleteHistoryLap: (id: number) => Promise; +} + +// ─── Module-level state (survives re-renders) ───────────────────────────────── + +/** Base64 of the start image captured when timing began, awaiting lap completion */ +let pendingStartImageBase64: string | null = null; +/** Guard to prevent re-entrant lap saves */ +let lapSaving = false; + +// ─── Slice ──────────────────────────────────────────────────────────────────── + +export const createLapSlice: StateCreator< + LapSlice & CameraSlice & TeableSlice & SystemSlice, + [], + [], + LapSlice +> = (set, get) => ({ + lapState: "idle", + currentSession: null, + currentLaps: [], + lapNumber: 0, + lapTimingStartedAt: null, + lapHistory: { sessions: [], total: 0 }, + isLapSaving: false, + lapSettings: { + lapMode: "single", + saveImages: true, + dirFilter: "both", + }, + + // ── Session control ──────────────────────────────────────────────────────── + + startLapSession: async () => { + const { lapSettings } = get(); + const session = await getRpc().request.createLapSession({ lapMode: lapSettings.lapMode }); + pendingStartImageBase64 = null; + lapSaving = false; + set({ + currentSession: session, + currentLaps: [], + lapNumber: 0, + lapState: "waiting", + appMode: "laptimer", + }); + // Tell the ESP to start a lap session — it will drive all subsequent lap events + await getRpc().request + .sendCommand({ json: JSON.stringify({ command: "startLapSession", mode: lapSettings.lapMode, autoFlash: true, dirFilter: lapSettings.dirFilter }) }) + .catch((err: unknown) => console.error("[lapSlice] startLapSession command failed:", err)); + }, + + stopLapSession: async () => { + const { currentSession } = get(); + if (currentSession) { + await getRpc().request.closeLapSession({ id: currentSession.id }); + } + // Tell the ESP to stop emitting lap events + await getRpc().request + .sendCommand({ json: JSON.stringify({ command: "stopLapSession" }) }) + .catch((err: unknown) => console.error("[lapSlice] stopLapSession command failed:", err)); + pendingStartImageBase64 = null; + lapSaving = false; + set({ + lapState: "idle", + currentSession: null, + lapTimingStartedAt: null, + // Keep currentLaps so the UI can show the final session summary + }); + }, + + // ── State machine ────────────────────────────────────────────────────────── + + handleSerialStatusForLap: (payload) => { + // ── LAPWAITING: firmware opened session, waiting for first pass ─────────── + if (payload.status === "LAPWAITING") { + const { lapState, currentSession } = get(); + if (currentSession && lapState === "idle") { + set({ lapState: "waiting" }); + } + return; + } + + // ── LAPSTOPPED: session stopped on firmware ─────────────────────────────── + if (payload.status === "LAPSTOPPED") { + pendingStartImageBase64 = null; + lapSaving = false; + set({ lapState: "idle", lapTimingStartedAt: null }); + return; + } + + // ── LAPSTART: first car pass — firmware opened a new lap ────────────────── + if (payload.status === "LAPSTART") { + const { lapState, lapSettings, currentSession } = get(); + + // Accept "waiting", "idle" (if session active), or "timing" (MULTI lap N+1 boundary) + const isMultiContinuation = lapState === "timing" && lapSettings.lapMode === "multi"; + if (lapState !== "waiting" && (lapState !== "idle" || !currentSession) && !isMultiContinuation) return; + + set({ lapState: "timing", lapNumber: payload.lapNumber, lapTimingStartedAt: Date.now() }); + + (async () => { + // In MULTI continuation, pendingStartImageBase64 is already set by LAPEND + // to the end image of the previous lap — reuse it, no new capture needed here. + if (isMultiContinuation) return; + + if (lapSettings.saveImages) { + const b64 = await getRpc().request.captureFrame({}); + pendingStartImageBase64 = b64; + } else { + pendingStartImageBase64 = null; + } + })().catch((err: unknown) => + console.error("[lapSlice] Start image capture failed:", err) + ); + return; + } + + // ── LAPEND: second car pass — firmware computed the lap duration ─────────── + if (payload.status === "LAPEND") { + const { lapState, currentSession, lapSettings, lapNumber } = get(); + if (lapState !== "timing" || !currentSession) return; + if (lapSaving) return; // Guard against re-entrant saves + lapSaving = true; + + const currentLapNumber = lapNumber; + const savedStartImage = pendingStartImageBase64; + pendingStartImageBase64 = null; + + const capturedSessionId = currentSession.id; + const capturedSession = currentSession; + + // durationMs is authoritative from the ESP (µs-precise float); round to ms for storage + const durationMs = Math.round(payload.durationMs); + const { speedAtStart, speedAtEnd } = payload; + // Derive wall-clock timestamps for DB storage / display + const endTimestamp = payload.timestamp; + const startTimestamp = endTimestamp - durationMs; + + // Advance UI state immediately + if (lapSettings.lapMode === "multi") { + set({ lapTimingStartedAt: null, isLapSaving: true }); + // Stay in "timing"; the incoming LAPSTART for lap N+1 carries the authoritative lapNumber + } else { + // single → back to waiting for the next run + set({ lapState: "waiting", lapNumber: 1, lapTimingStartedAt: null, isLapSaving: true }); + } + + (async () => { + // Capture end image + const endImageBase64 = lapSettings.saveImages ? await getRpc().request.captureFrame({}) : null; + + // Persist the lap + const lap = await getRpc().request.saveLap({ + sessionId: capturedSessionId, + lapNumber: currentLapNumber, + startTimestamp, + endTimestamp, + durationMs, + speedAtStart, + speedAtEnd, + startImageBase64: savedStartImage, + endImageBase64, + }); + + set((state) => ({ currentLaps: [...state.currentLaps, lap], isLapSaving: false })); + + // Fire-and-forget Teable sync (never blocks local save) + if (get().teableSyncEnabled && capturedSession) { + getRpc().request.syncLapToTeable({ lap, session: capturedSession }).catch((e: unknown) => { + toast.error(`Teable sync failed: ${String(e)}`); + }); + } + + // In multi mode, reuse end image as start image of the next lap + if (lapSettings.lapMode === "multi") { + pendingStartImageBase64 = endImageBase64; + } + })() + .catch((err: unknown) => { + console.error("[lapSlice] Lap save failed:", err); + set({ isLapSaving: false }); + }) + .finally(() => { + lapSaving = false; + }); + } + }, + + // ── Settings ─────────────────────────────────────────────────────────────── + + loadLapSettings: async () => { + const settings = await getRpc().request.getSettings({}); + set({ + lapSettings: { + lapMode: settings.lapMode === "multi" ? "multi" : "single", + saveImages: settings.lapSaveImages === "true", + dirFilter: (settings.lapDirFilter === "forward" || settings.lapDirFilter === "reverse") + ? settings.lapDirFilter + : "both", + }, + }); + }, + + updateLapSetting: async (key, value) => { + await getRpc().request.saveSetting({ key, value }); + set((state) => { + const s = { ...state.lapSettings }; + if (key === "lapMode") s.lapMode = value === "multi" ? "multi" : "single"; + else if (key === "lapSaveImages") s.saveImages = value === "true"; + else if (key === "lapDirFilter") s.dirFilter = (value === "forward" || value === "reverse") ? value : "both"; + return { lapSettings: s }; + }); + }, + + // ── History ──────────────────────────────────────────────────────────────── + + fetchLapHistory: async (page, limit) => { + const result = await getRpc().request.getLapSessions({ page, limit }); + set({ lapHistory: result }); + }, + + deleteHistorySession: async (id) => { + await getRpc().request.deleteLapSession({ id }); + // Re-fetch page 1 after deletion + const result = await getRpc().request.getLapSessions({ page: 1, limit: 20 }); + set({ lapHistory: result }); + }, + + deleteHistoryLap: async (id) => { + await getRpc().request.deleteLap({ id }); + // Update in-place to avoid a full re-fetch + set((state) => ({ + currentLaps: state.currentLaps.filter((l) => l.id !== id), + lapHistory: { + ...state.lapHistory, + sessions: state.lapHistory.sessions.map((s) => ({ + ...s, + laps: s.laps.filter((l) => l.id !== id), + })), + }, + })); + }, +}); diff --git a/headless-rust/frontend/src/stores/slices/measurementSlice.ts b/headless-rust/frontend/src/stores/slices/measurementSlice.ts new file mode 100644 index 0000000..d0d05dd --- /dev/null +++ b/headless-rust/frontend/src/stores/slices/measurementSlice.ts @@ -0,0 +1,92 @@ +import type { StateCreator } from "zustand"; +import type { SerialStatusPayload, Violation, EspPongConfig } from "@/shared/types"; +import type { CameraSlice } from "./cameraSlice"; +import type { SystemSlice } from "./systemSlice"; +import type { LapSlice } from "./lapSlice"; +import { getRpc } from "@/lib/rpc"; +import { toast } from "sonner"; + +export interface MeasurementSlice { + /** Last measured speed in km/h (null = no reading yet) */ + lastSpeed: number | null; + /** Direction of last measurement (null = no reading yet) */ + lastDirection: "forward" | "reverse" | null; + /** Max allowed speed (km/h) from settings */ + maxSpeed: number; + /** Most recently captured violation (event-driven, no polling) */ + lastViolation: Violation | null; + /** Config returned by the last successful ping */ + lastPongConfig: EspPongConfig | null; + setMaxSpeed: (speed: number) => void; + setLastViolation: (v: Violation | null) => void; + handleSerialStatus: (payload: SerialStatusPayload) => void; +} + +export const createMeasurementSlice: StateCreator< + MeasurementSlice & CameraSlice & SystemSlice & LapSlice, + [], + [], + MeasurementSlice +> = (set, get) => ({ + lastSpeed: null, + lastDirection: null, + maxSpeed: 30, + lastViolation: null, + lastPongConfig: null, + + setMaxSpeed: (speed) => set({ maxSpeed: speed }), + + setLastViolation: (v) => set({ lastViolation: v }), + + handleSerialStatus: (payload) => { + // PONG is handled regardless of system state or app mode + if (payload.status === "PONG") { + set({ lastPongConfig: payload.config }); + return; + } + + if (payload.status === "CONNECTED") { + const port = (payload as any).port || get().selectedPort || "connected"; + get().setConnectedPort(port); + return; + } + + if (payload.status === "DISCONNECTED") { + get().setConnectedPort(""); + return; + } + + // Lap-specific events MUST ALWAYS be forwarded to the lap state machine, + // regardless of systemState (e.g. even if camera is disconnected / PASSIVE) + if ( + payload.status === "LAPSTART" || + payload.status === "LAPEND" || + payload.status === "LAPWAITING" || + payload.status === "LAPSTOPPED" + ) { + get().handleSerialStatusForLap(payload); + return; + } + + const { systemState, appMode, currentSession } = get(); + + // If in lap timer mode or an active lap session is running, speed events + // update the display without creating speed camera violations + if (appMode === "laptimer" || currentSession !== null) { + if (payload.status === "SPEEDING" || payload.status === "OK") { + set({ lastSpeed: payload.value, lastDirection: payload.direction }); + } + return; + } + + // In PASSIVE mode, ignore all serial measurements + if (systemState === "PASSIVE") return; + + if (payload.status === "SPEEDING") { + const { value, direction } = payload; + set({ lastSpeed: value, lastDirection: direction }); + } else if (payload.status === "OK") { + set({ lastSpeed: payload.value, lastDirection: payload.direction }); + } + }, +}); diff --git a/headless-rust/frontend/src/stores/slices/serialSlice.ts b/headless-rust/frontend/src/stores/slices/serialSlice.ts new file mode 100644 index 0000000..0626869 --- /dev/null +++ b/headless-rust/frontend/src/stores/slices/serialSlice.ts @@ -0,0 +1,50 @@ +import type { StateCreator } from "zustand"; +import type { PortInfo } from "@/shared/types"; +import { getRpc } from "@/lib/rpc"; + +export interface SerialSlice { + availablePorts: PortInfo[]; + /** Path of the selected port (from settings or UI) */ + selectedPort: string; + /** Path of the currently open/connected port, or "" */ + connectedPort: string; + setAvailablePorts: (ports: PortInfo[]) => void; + setSelectedPort: (path: string) => void; + setConnectedPort: (path: string) => void; + refreshSerialStatus: () => Promise; + connectPort: (path: string) => Promise; + disconnectPort: () => Promise; +} + +export const createSerialSlice: StateCreator = (set) => ({ + availablePorts: [], + selectedPort: "", + connectedPort: "", + setAvailablePorts: (ports) => set({ availablePorts: ports }), + setSelectedPort: (path) => set({ selectedPort: path }), + setConnectedPort: (path) => set({ connectedPort: path }), + + refreshSerialStatus: async () => { + try { + const status = await getRpc().request.getSerialStatus({}); + if (status.connected && status.port) { + set({ connectedPort: status.port, selectedPort: status.port }); + } else if (!status.connected) { + set({ connectedPort: "" }); + } + } catch (e) { + console.warn("[serialSlice] Failed to get serial status:", e); + } + }, + + connectPort: async (path: string) => { + await getRpc().request.openPort({ path }); + await getRpc().request.saveSetting({ key: "selectedPort", value: path }); + set({ connectedPort: path, selectedPort: path }); + }, + + disconnectPort: async () => { + await getRpc().request.closePort({}); + set({ connectedPort: "" }); + }, +}); diff --git a/headless-rust/frontend/src/stores/slices/systemSlice.ts b/headless-rust/frontend/src/stores/slices/systemSlice.ts new file mode 100644 index 0000000..a861c2e --- /dev/null +++ b/headless-rust/frontend/src/stores/slices/systemSlice.ts @@ -0,0 +1,61 @@ +import type { StateCreator } from "zustand"; +import { getRpc } from "@/lib/rpc"; +import type { SerialSlice } from "./serialSlice"; +import type { CameraSlice } from "./cameraSlice"; +import type { MeasurementSlice } from "./measurementSlice"; +import type { LapSlice } from "./lapSlice"; + +export type SystemState = "PASSIVE" | "DISARMED" | "ARMED"; +export type AppMode = "speedcamera" | "laptimer"; + +export interface SystemSlice { + /** Underlying daemon armed state */ + isArmed: boolean; + /** Current operational state of the speed camera system */ + systemState: SystemState; + setSystemState: (state: SystemState) => void; + setArmed: (armed: boolean) => Promise; + handleArmedStatus: (armed: boolean) => void; + refreshArmedStatus: () => Promise; + /** Active mode — routes serial events to violation or lap handler */ + appMode: AppMode; + setAppMode: (mode: AppMode) => void; +} + +export const createSystemSlice: StateCreator< + SystemSlice & SerialSlice & CameraSlice & MeasurementSlice & LapSlice, + [], + [], + SystemSlice +> = (set, get) => ({ + isArmed: false, + systemState: "PASSIVE", + setSystemState: (state) => set({ systemState: state }), + handleArmedStatus: (armed) => { + const { connectedPort, cameraConnected } = get(); + const conditionsMet = !!connectedPort && cameraConnected; + set({ + isArmed: armed, + systemState: !conditionsMet ? "PASSIVE" : armed ? "ARMED" : "DISARMED", + }); + }, + setArmed: async (armed) => { + try { + await getRpc().request.setArmed({ armed }); + get().handleArmedStatus(armed); + } catch (e) { + console.error("[systemSlice] Failed to update armed state:", e); + } + }, + refreshArmedStatus: async () => { + try { + const res = await getRpc().request.getArmedState({}); + get().handleArmedStatus(res.armed); + } catch (e) { + console.warn("[systemSlice] Failed to get armed status:", e); + } + }, + appMode: "speedcamera", + setAppMode: (mode) => set({ appMode: mode }), +}); + diff --git a/headless-rust/frontend/src/stores/slices/teableSlice.ts b/headless-rust/frontend/src/stores/slices/teableSlice.ts new file mode 100644 index 0000000..d457de9 --- /dev/null +++ b/headless-rust/frontend/src/stores/slices/teableSlice.ts @@ -0,0 +1,206 @@ +import type { StateCreator } from "zustand"; +import { toast } from "sonner"; +import type { AppSettings, TeableUser, TeableSchemaCheck } from "@/shared/types"; +import { getRpc } from "@/lib/rpc"; + +// ─── Types ──────────────────────────────────────────────────────────────────── + +export type TeableSchemaStatus = "unchecked" | "valid" | "missing"; + +export interface TeableSlice { + // Persisted state (mirrors settings) + teableUrl: string; + teableUserName: string; + teableUserEmail: string; + teableUserAvatar: string; + teableSpaceId: string; + teableBaseId: string; + teableTableId: string; + teableSyncEnabled: boolean; + + // Derived / transient + teableConnected: boolean; + isTeableLoading: boolean; + teableSchemaStatus: TeableSchemaStatus; + teableMissingFields: string[]; + + // Actions + loadTeableState: () => Promise; + connectTeable: (url: string, token: string) => Promise; + disconnectTeable: () => Promise; + saveTeableTableTarget: (spaceId: string, baseId: string, tableId: string) => Promise; + verifyTeableSchema: (tableId?: string) => Promise; + patchTeableSchema: (tableId?: string) => Promise; + createAndSelectTable: (baseId: string, tableName: string) => Promise; + setTeableSyncEnabled: (enabled: boolean) => Promise; +} + +// ─── Slice ──────────────────────────────────────────────────────────────────── + +export const createTeableSlice: StateCreator = (set, get) => ({ + teableUrl: "", + teableUserName: "", + teableUserEmail: "", + teableUserAvatar: "", + teableSpaceId: "", + teableBaseId: "", + teableTableId: "", + teableSyncEnabled: false, + teableConnected: false, + isTeableLoading: false, + teableSchemaStatus: "unchecked", + teableMissingFields: [], + + // ── Load persisted settings ──────────────────────────────────────────────── + + loadTeableState: async () => { + const settings = await getRpc().request.getSettings({}); + const connected = !!(settings.teableUrl && settings.teableToken); + set({ + teableUrl: settings.teableUrl, + teableUserName: settings.teableUserName, + teableUserEmail: settings.teableUserEmail, + teableUserAvatar: settings.teableUserAvatar, + teableSpaceId: settings.teableSpaceId, + teableBaseId: settings.teableBaseId, + teableTableId: settings.teableTableId, + teableSyncEnabled: false, // always start disabled until schema is verified + teableConnected: connected, + teableSchemaStatus: "unchecked", + }); + }, + + // ── Connection ───────────────────────────────────────────────────────────── + + connectTeable: async (url, token) => { + set({ isTeableLoading: true }); + try { + const user = await getRpc().request.testTeableConnection({ url, token }); + await getRpc().request.saveTeableConfig({ + url, + token, + userName: user.name, + userEmail: user.email, + userAvatar: user.avatar, + }); + set({ + teableUrl: url, + teableUserName: user.name, + teableUserEmail: user.email, + teableUserAvatar: user.avatar ?? "", + teableConnected: true, + teableSchemaStatus: "unchecked", + teableMissingFields: [], + }); + return user; + } finally { + set({ isTeableLoading: false }); + } + }, + + disconnectTeable: async () => { + set({ isTeableLoading: true }); + try { + await getRpc().request.removeTeableConfig({}); + set({ + teableUrl: "", + teableUserName: "", + teableUserEmail: "", + teableUserAvatar: "", + teableSpaceId: "", + teableBaseId: "", + teableTableId: "", + teableSyncEnabled: false, + teableConnected: false, + teableSchemaStatus: "unchecked", + teableMissingFields: [], + }); + } finally { + set({ isTeableLoading: false }); + } + }, + + // ── Table target ─────────────────────────────────────────────────────────── + + saveTeableTableTarget: async (spaceId, baseId, tableId) => { + await getRpc().request.saveTeableTarget({ spaceId, baseId, tableId }); + set({ + teableSpaceId: spaceId, + teableBaseId: baseId, + teableTableId: tableId, + teableSchemaStatus: "unchecked", + teableMissingFields: [], + }); + }, + + // ── Schema management ────────────────────────────────────────────────────── + + verifyTeableSchema: async (tableId?: string) => { + const id = tableId ?? get().teableTableId; + if (!id) return; + set({ isTeableLoading: true }); + try { + const check: TeableSchemaCheck = await getRpc().request.verifyTeableTable({ tableId: id }); + set({ + teableSchemaStatus: check.missingFields.length === 0 ? "valid" : "missing", + teableMissingFields: check.missingFields, + }); + } catch (e) { + toast.error(`Schema check failed: ${String(e)}`); + } finally { + set({ isTeableLoading: false }); + } + }, + + patchTeableSchema: async (tableId?: string) => { + const id = tableId ?? get().teableTableId; + if (!id) return; + set({ isTeableLoading: true }); + try { + const created = await getRpc().request.ensureTeableFields({ tableId: id }); + toast.success( + created.length > 0 + ? `Added ${created.length} missing field${created.length > 1 ? "s" : ""}` + : "All fields already present" + ); + set({ teableSchemaStatus: "valid", teableMissingFields: [] }); + } catch (e) { + toast.error(`Failed to add fields: ${String(e)}`); + } finally { + set({ isTeableLoading: false }); + } + }, + + createAndSelectTable: async (baseId, tableName) => { + set({ isTeableLoading: true }); + try { + const table = await getRpc().request.createTeableTable({ baseId, tableName }); + await getRpc().request.saveTeableTarget({ + spaceId: get().teableSpaceId, + baseId, + tableId: table.id, + }); + set({ + teableBaseId: baseId, + teableTableId: table.id, + teableSchemaStatus: "valid", + teableMissingFields: [], + }); + toast.success(`Table "${table.name}" created`); + } catch (e) { + toast.error(`Failed to create table: ${String(e)}`); + } finally { + set({ isTeableLoading: false }); + } + }, + + // ── Sync toggle ──────────────────────────────────────────────────────────── + + setTeableSyncEnabled: async (enabled) => { + await getRpc().request.saveSetting({ + key: "teableSyncEnabled" as keyof AppSettings, + value: enabled ? "true" : "false", + }); + set({ teableSyncEnabled: enabled }); + }, +}); diff --git a/headless-rust/frontend/src/stores/slices/updaterSlice.ts b/headless-rust/frontend/src/stores/slices/updaterSlice.ts new file mode 100644 index 0000000..c42fb46 --- /dev/null +++ b/headless-rust/frontend/src/stores/slices/updaterSlice.ts @@ -0,0 +1,81 @@ +import type { StateCreator } from "zustand"; + +export type UpdatePhase = "idle" | "checking" | "downloading" | "ready" | "error"; + +export interface UpdaterSlice { + updatePhase: UpdatePhase; + updateMessage: string; + updateProgress: number | null; + updateVersion: string | null; + updateError: string | null; + handleUpdateProgress: (payload: { + status: string; + message: string; + progress?: number; + }) => void; + resetUpdater: () => void; + setUpdatePhase: (phase: UpdatePhase) => void; + setUpdateVersion: (version: string | null) => void; + setUpdateError: (error: string | null) => void; +} + +export const createUpdaterSlice: StateCreator = (set) => ({ + updatePhase: "idle", + updateMessage: "", + updateProgress: null, + updateVersion: null, + updateError: null, + + handleUpdateProgress: (payload) => { + const { status, message, progress } = payload; + let phase: UpdatePhase = "idle"; + if (status === "checking" || status === "check-complete" || status === "no-update" || status === "update-available") { + phase = "checking"; + } else if ( + status === "downloading" || + status === "download-starting" || + status === "checking-local-tar" || + status === "local-tar-found" || + status === "local-tar-missing" || + status === "fetching-patch" || + status === "patch-found" || + status === "patch-not-found" || + status === "downloading-patch" || + status === "applying-patch" || + status === "patch-applied" || + status === "patch-failed" || + status === "extracting-version" || + status === "patch-chain-complete" || + status === "downloading-full-bundle" || + status === "download-progress" || + status === "decompressing" || + status === "download-complete" + ) { + phase = "downloading"; + } else if (status === "complete" || status === "applying" || status === "extracting" || status === "replacing-app" || status === "launching-new-version") { + phase = "ready"; + } else if (status === "error") { + phase = "error"; + } + + set((s) => ({ + updatePhase: phase === "idle" ? s.updatePhase : phase, + updateMessage: message, + updateProgress: progress ?? s.updateProgress, + updateError: status === "error" ? message : s.updateError, + })); + }, + + resetUpdater: () => + set({ + updatePhase: "idle", + updateMessage: "", + updateProgress: null, + updateVersion: null, + updateError: null, + }), + + setUpdatePhase: (phase) => set({ updatePhase: phase }), + setUpdateVersion: (version) => set({ updateVersion: version }), + setUpdateError: (error) => set({ updateError: error }), +}); diff --git a/headless-rust/frontend/src/stores/useAppStore.ts b/headless-rust/frontend/src/stores/useAppStore.ts new file mode 100644 index 0000000..0fd3c84 --- /dev/null +++ b/headless-rust/frontend/src/stores/useAppStore.ts @@ -0,0 +1,22 @@ +import { create } from "zustand"; +import { createCameraSlice, type CameraSlice } from "./slices/cameraSlice"; +import { createSerialSlice, type SerialSlice } from "./slices/serialSlice"; +import { createMeasurementSlice, type MeasurementSlice } from "./slices/measurementSlice"; +import { createSystemSlice, type SystemSlice } from "./slices/systemSlice"; +import { createLapSlice, type LapSlice } from "./slices/lapSlice"; +import { createTeableSlice, type TeableSlice } from "./slices/teableSlice"; +import { createFlasherSlice, type FlasherSlice } from "./slices/flasherSlice"; +import { createUpdaterSlice, type UpdaterSlice } from "./slices/updaterSlice"; + +export type AppStore = CameraSlice & SerialSlice & MeasurementSlice & SystemSlice & LapSlice & TeableSlice & FlasherSlice & UpdaterSlice; + +export const useAppStore = create()((...a) => ({ + ...createCameraSlice(...a), + ...createSerialSlice(...a), + ...createMeasurementSlice(...a), + ...createSystemSlice(...a), + ...createLapSlice(...a), + ...createTeableSlice(...a), + ...createFlasherSlice(...a), + ...createUpdaterSlice(...a), +})); diff --git a/headless-rust/package.json b/headless-rust/package.json new file mode 100644 index 0000000..43484ae --- /dev/null +++ b/headless-rust/package.json @@ -0,0 +1,62 @@ +{ + "name": "speedcamera-rust-ui", + "type": "module", + "version": "0.5.0", + "description": "Speedcamera Web UI for Raspberry Pi and remote browser control", + "scripts": { + "dev": "vite", + "dev:server": "cargo run -- --mock", + "dev:all": "concurrently \"bun run dev\" \"cargo run -- --mock\"", + "build": "vite build", + "build:all": "vite build && cargo build --release", + "serve": "cargo run --release", + "install:pi": "./scripts/install-remote.sh", + "deploy:pi": "./scripts/deploy-to-pi.sh", + "cleanup:pi": "./scripts/cleanup-remote.sh", + "test:server": "bun ./scripts/test-server.ts", + "diag": "bun ./diagnostics/cli.ts", + "diag:quick": "bun ./diagnostics/cli.ts quick", + "diag:monitor": "bun ./diagnostics/cli.ts monitor", + "diag:reproduce": "bun ./diagnostics/cli.ts reproduce", + "diag:full": "bun ./diagnostics/cli.ts full", + "diag:fix": "bun ./diagnostics/cli.ts fix", + "setup:esptool": "mkdir -p resources && curl -fsSL https://github.com/espressif/esptool/releases/download/v5.2.0/esptool-v5.2.0-linux-amd64.tar.gz | tar -xz --wildcards '*/esptool' --strip-components=1 && mv esptool resources/esptool && chmod +x resources/esptool" + }, + "dependencies": { + "@fontsource-variable/figtree": "^5.2.10", + "@hugeicons/core-free-icons": "^4.1.1", + "@hugeicons/react": "^1.1.6", + "@tailwindcss/postcss": "^4.2.4", + "@tailwindcss/vite": "^4.2.4", + "@tanstack/react-router": "^1.168.23", + "class-variance-authority": "^0.7.1", + "clsx": "^2.1.1", + "lucide-react": "^1.8.0", + "next-themes": "^0.4.6", + "qrcode.react": "^4.2.0", + "radix-ui": "^1.4.3", + "react": "^18.3.1", + "react-dom": "^18.3.1", + "react-webcam": "^7.2.0", + "shadcn": "^4.7.0", + "socket.io-client": "^4.8.3", + "sonner": "^2.0.7", + "tailwind-merge": "^3.5.0", + "tw-animate-css": "^1.4.0", + "zod": "^4.3.6", + "zustand": "^5.0.12" + }, + "devDependencies": { + "@types/node": "^25.6.0", + "@types/react": "^18.3.12", + "@types/react-dom": "^18.3.1", + "@types/react-webcam": "^3.0.0", + "@vitejs/plugin-react": "^4.3.4", + "autoprefixer": "^10.4.20", + "concurrently": "^9.1.0", + "postcss": "^8.4.49", + "tailwindcss": "^4.2.4", + "typescript": "^5.7.2", + "vite": "^6.0.3" + } +} diff --git a/headless-rust/postcss.config.js b/headless-rust/postcss.config.js new file mode 100644 index 0000000..f69c5d4 --- /dev/null +++ b/headless-rust/postcss.config.js @@ -0,0 +1,6 @@ +export default { + plugins: { + "@tailwindcss/postcss": {}, + autoprefixer: {}, + }, +}; diff --git a/headless-rust/resources/font.ttf b/headless-rust/resources/font.ttf new file mode 100755 index 0000000..e0c576f Binary files /dev/null and b/headless-rust/resources/font.ttf differ diff --git a/headless-rust/scripts/cleanup-pi.sh b/headless-rust/scripts/cleanup-pi.sh new file mode 100755 index 0000000..be4bb0d --- /dev/null +++ b/headless-rust/scripts/cleanup-pi.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +set -e + +# Target user and directories +TARGET_USER="${SUDO_USER:-$(whoami)}" +TARGET_HOME=$(getent passwd "$TARGET_USER" | cut -d: -f6) + +PURGE_DATA=false +CONFIRM_YES=false + +for arg in "$@"; do + case "$arg" in + --purge) + PURGE_DATA=true + ;; + --yes|-y) + CONFIRM_YES=true + ;; + --help|-h) + echo "Speedcamera Raspberry Pi Complete Uninstaller & Network Reset" + echo "" + echo "Usage: $0 [options]" + echo "" + echo "Options:" + echo " --purge Also delete data directory (${TARGET_HOME}/.speedcamera - database & images)" + echo " --yes, -y Non-interactive mode (skip confirmation prompts)" + echo " --help, -h Show this help message" + exit 0 + ;; + esac +done + +echo "=========================================================" +echo " Speedcamera Complete Teardown & Reset" +echo " Target user: ${TARGET_USER} (${TARGET_HOME})" +echo "=========================================================" + +if [ "$CONFIRM_YES" = false ] && [ -t 0 ]; then + read -p "Are you sure you want to completely uninstall Speedcamera and reset network? (y/N) " -n 1 -r + echo "" + if [[ ! $REPLY =~ ^[Yy]$ ]]; then + echo "Aborted." + exit 0 + fi +fi + +# Refresh sudo credentials upfront +echo "[*] Requesting sudo credentials..." +sudo -v || { echo "Error: Sudo privileges required to reset network and services." >&2; exit 1; } + +# 1. Stop & remove systemd service +echo "[1/4] Stopping and removing systemd service..." +sudo systemctl stop speedcamera.service 2>/dev/null || true +sudo systemctl disable speedcamera.service 2>/dev/null || true +sudo rm -f /etc/systemd/system/speedcamera.service +sudo systemctl daemon-reload 2>/dev/null || true +sudo systemctl reset-failed 2>/dev/null || true + +# 2. Remove application files & optional data purge +echo "[2/4] Removing speedcamera application files..." +rm -rf "${TARGET_HOME}/speedcamera" + +if [ "$PURGE_DATA" = true ]; then + echo " Purging data directory (${TARGET_HOME}/.speedcamera)..." + rm -rf "${TARGET_HOME}/.speedcamera" +else + echo " Preserving data directory (${TARGET_HOME}/.speedcamera). Use --purge to delete." +fi + +# 3. Reset Ethernet interface to standard DHCP first +echo "[3/4] Resetting Ethernet to standard auto-DHCP..." +if command -v nmcli &>/dev/null; then + sudo nmcli connection delete "Speedcamera-CameraLAN" 2>/dev/null || true + sudo nmcli connection delete "Speedcamera-Ethernet-DHCP" 2>/dev/null || true + + ETH_IFACE=$(ip -o link show | awk -F': ' '{print $2}' | grep -E '^(eth|end|enp)' | head -n 1 || echo "") + if [ -n "$ETH_IFACE" ]; then + echo " Re-enabling standard DHCP on Ethernet (${ETH_IFACE})..." + sudo nmcli device set "${ETH_IFACE}" managed yes 2>/dev/null || true + sudo nmcli connection add type ethernet ifname "${ETH_IFACE}" con-name "Wired connection 1" autoconnect yes ipv4.method auto 2>/dev/null || true + sudo nmcli connection up "Wired connection 1" 2>/dev/null || true + fi +fi + +# 4. Reset Wi-Fi interface (handle active hotspot SSH session safely) +echo "[4/4] Resetting Wi-Fi & Hotspot profiles..." +IS_HOTSPOT_SSH=false +if echo "${SSH_CONNECTION:-}" | grep -q "192.168.4."; then + IS_HOTSPOT_SSH=true +fi + +if [ "$IS_HOTSPOT_SSH" = true ]; then + echo " [!] Active SSH session over Wi-Fi Hotspot (192.168.4.1) detected." + echo " Scheduling Hotspot teardown in background (2s delay) to close SSH cleanly..." + sudo nohup bash -c ' + sleep 2 + nmcli connection delete "Speedcamera-Hotspot" 2>/dev/null || true + nmcli connection delete "Speedcamera-ClientWiFi" 2>/dev/null || true + WIFI_IFACE=$(ip -o link show | awk -F": " "{print \$2}" | grep -E "^(wlan|wifi|wlp)" | head -n 1 || echo "") + if [ -n "$WIFI_IFACE" ]; then + nmcli device set "$WIFI_IFACE" managed yes 2>/dev/null || true + fi + ' >/dev/null 2>&1 & +else + if command -v nmcli &>/dev/null; then + sudo nmcli connection delete "Speedcamera-Hotspot" 2>/dev/null || true + sudo nmcli connection delete "Speedcamera-ClientWiFi" 2>/dev/null || true + WIFI_IFACE=$(ip -o link show | awk -F': ' '{print $2}' | grep -E '^(wlan|wifi|wlp)' | head -n 1 || echo "") + if [ -n "$WIFI_IFACE" ]; then + sudo nmcli device set "${WIFI_IFACE}" managed yes 2>/dev/null || true + fi + fi +fi + +echo "" +echo "=========================================================" +echo " Speedcamera uninstallation complete!" +echo " • Services stopped & removed" +echo " • Application files deleted" +echo " • Ethernet reverted to standard DHCP (connect cable to router)" +if [ "$IS_HOTSPOT_SSH" = true ]; then + echo " • Wi-Fi Hotspot is shutting down now." +else + echo " • Wi-Fi reset to client DHCP mode." +fi +echo "=========================================================" diff --git a/headless-rust/scripts/cleanup-remote.sh b/headless-rust/scripts/cleanup-remote.sh new file mode 100755 index 0000000..0d38d3f --- /dev/null +++ b/headless-rust/scripts/cleanup-remote.sh @@ -0,0 +1,102 @@ +#!/usr/bin/env bash +set -e + +# Usage: ./scripts/cleanup-remote.sh [pi_target] [options] +# Examples: +# ./scripts/cleanup-remote.sh pi@raspberrypi.local +# ./scripts/cleanup-remote.sh pi@192.168.4.1 --password --purge +# bun run cleanup:pi pi@raspberrypi.local + +PI_TARGET="pi@raspberrypi.local" +USE_PASSWORD=false +PURGE_FLAG="" +CONFIRM_YES=false + +# Parse arguments +for arg in "$@"; do + case "$arg" in + --password|-p|--pass) + USE_PASSWORD=true + ;; + --purge) + PURGE_FLAG="--purge" + ;; + --yes|-y) + CONFIRM_YES=true + ;; + --help|-h) + echo "Speedcamera Headless Rust Remote Pi Complete Teardown & Cleanup" + echo "" + echo "Usage: $0 [user@host] [options]" + echo "" + echo "Positional Arguments:" + echo " [user@host] SSH target (default: pi@raspberrypi.local or 192.168.4.1)" + echo "" + echo "Options:" + echo " --password, -p Force password authentication (disables SSH keys)" + echo " --purge Also remove database and captured images (~/.speedcamera)" + echo " --yes, -y Skip interactive confirmation prompt" + echo " --help, -h Show this help message" + echo "" + echo "Notes:" + echo " • Safely handles active Wi-Fi Hotspot connections (192.168.4.1):" + echo " Deletes files, services, and enables Ethernet DHCP before shutting down Hotspot." + exit 0 + ;; + *) + if [[ "$arg" != -* ]]; then + PI_TARGET="$arg" + fi + ;; + esac +done + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +SSH_OPTS=(-o "ConnectTimeout=10") + +if [ "$USE_PASSWORD" = true ]; then + echo "[*] Password authentication enabled (-o PubkeyAuthentication=no)" + SSH_OPTS+=(-o "PubkeyAuthentication=no" -o "PreferredAuthentications=password,keyboard-interactive") +fi + +echo "=========================================================" +echo " Speedcamera Rust Remote Teardown & Cleanup" +echo " Target: ${PI_TARGET}" +echo "=========================================================" + +if [[ "$PI_TARGET" == *"192.168.4."* ]]; then + echo ">>> [!] Note: Connected via Pi Wi-Fi Hotspot (192.168.4.1)." + echo ">>> All services & files will be cleaned up and Ethernet restored to DHCP" + echo ">>> before the Wi-Fi Hotspot shuts down." + echo "" +fi + +if [ "$CONFIRM_YES" = false ]; then + read -p "Are you sure you want to completely uninstall Speedcamera from ${PI_TARGET} and restore DHCP network settings? (y/N) " -n 1 -r + echo "" + if [[ ! $REPLY =~ ^[Yy]$ ]]; then + echo "Aborted." + exit 0 + fi +fi + +# Encode cleanup-pi.sh to base64 to avoid all nested shell escaping/quoting issues +CLEANUP_B64=$(base64 < "${SCRIPT_DIR}/cleanup-pi.sh" | tr -d '\r\n') + +echo "[*] Connecting to ${PI_TARGET} and executing teardown..." + +REMOTE_CMD="echo '${CLEANUP_B64}' | base64 -d > /tmp/speedcamera-cleanup-pi.sh && chmod +x /tmp/speedcamera-cleanup-pi.sh && /tmp/speedcamera-cleanup-pi.sh ${PURGE_FLAG} --yes; rm -f /tmp/speedcamera-cleanup-pi.sh" + +# Execute with forced TTY so sudo can prompt interactively +ssh -tt "${SSH_OPTS[@]}" "${PI_TARGET}" "${REMOTE_CMD}" + +echo "" +echo "=========================================================" +echo " Cleanup complete! Speedcamera removed from ${PI_TARGET}." +echo " Ethernet interface restored to standard DHCP." +if [[ "$PI_TARGET" == *"192.168.4."* ]]; then + echo " Wi-Fi Hotspot is now shutting down." + echo " Plug Pi into your home router via Ethernet to access via DHCP." +fi +echo "=========================================================" diff --git a/headless-rust/scripts/deploy-to-pi.sh b/headless-rust/scripts/deploy-to-pi.sh new file mode 100755 index 0000000..ec420ae --- /dev/null +++ b/headless-rust/scripts/deploy-to-pi.sh @@ -0,0 +1,128 @@ +#!/usr/bin/env bash +set -e + +# Usage: ./scripts/deploy-to-pi.sh [pi_target] [options] +# Examples: +# ./scripts/deploy-to-pi.sh pi@raspberrypi.local +# ./scripts/deploy-to-pi.sh pi@192.168.1.50 --password +# ./scripts/deploy-to-pi.sh pi@raspberrypi.local --branch feature/headless +# bun run deploy:pi pi@raspberrypi.local + +PI_TARGET="pi@raspberrypi.local" +USE_PASSWORD=false +FORCE_BUILD=false +BUILD_FLAG="" +BRANCH="" + +# Parse arguments +while [[ $# -gt 0 ]]; do + case "$1" in + --password|-p|--pass) + USE_PASSWORD=true + shift + ;; + --build|-b|--force-build) + FORCE_BUILD=true + BUILD_FLAG="--build" + shift + ;; + --branch) + BRANCH="$2" + shift 2 + ;; + --help|-h) + echo "Speedcamera Headless Rust Fast Deploy / Upgrade Script" + echo "" + echo "Usage: $0 [user@host] [options]" + echo "" + echo "Positional Arguments:" + echo " [user@host] SSH target (default: pi@raspberrypi.local or 192.168.1.x)" + echo "" + echo "Options:" + echo " --password, -p Force password authentication (disables SSH keys)" + echo " --build, -b Force compiling release binary & frontend on Pi" + echo " --branch Checkout and pull a specific git branch on Pi" + echo " --help, -h Show this help message" + echo "" + echo "Notes:" + echo " • Requires Pi to be in Internet or DHCP Mode (not Field Mode) to pull from git." + echo " • Pulls latest git commits in ~/speedcamera directly on the Pi." + echo " • Compiles and updates frontend & Rust release binary entirely on Pi." + echo " • No local laptop build or file transfer required." + exit 0 + ;; + *) + if [[ "$1" != -* ]]; then + PI_TARGET="$1" + fi + shift + ;; + esac +done + +if [[ "$PI_TARGET" == *"192.168.4."* ]]; then + echo "Error: Target is in Field Mode Hotspot (${PI_TARGET})." >&2 + echo "Deployment requires the Pi to be connected to the internet (Home LAN / DHCP or Client Wi-Fi Mode) to perform git pull and build." >&2 + echo "To connect the Pi to Wi-Fi for updates, run:" >&2 + echo " ssh ${PI_TARGET} '~/speedcamera/headless-rust/scripts/setup-network.sh internet '" >&2 + echo " or plug in Ethernet and run: ssh ${PI_TARGET} '~/speedcamera/headless-rust/scripts/setup-network.sh dhcp'" >&2 + exit 1 +fi + +# Setup SSH Connection Multiplexing so password is typed at most once +SOCKET_DIR="/tmp/speedcamera-deploy-ssh-$$" +mkdir -p "$SOCKET_DIR" +SOCKET_PATH="${SOCKET_DIR}/socket" + +SSH_OPTS=(-o "ControlMaster=auto" -o "ControlPath=${SOCKET_PATH}" -o "ControlPersist=60s" -o "ConnectTimeout=10") + +if [ "$USE_PASSWORD" = true ]; then + echo "[*] Password authentication enabled (-o PubkeyAuthentication=no)" + SSH_OPTS+=(-o "PubkeyAuthentication=no" -o "PreferredAuthentications=password,keyboard-interactive") +fi + +cleanup() { + ssh -O exit -o "ControlPath=${SOCKET_PATH}" "${PI_TARGET}" 2>/dev/null || true + rm -rf "$SOCKET_DIR" +} +trap cleanup EXIT INT TERM + +echo "=========================================================" +echo " Deploying / Upgrading Speedcamera Rust: ${PI_TARGET}" +echo "=========================================================" + +# 1. Check internet connectivity and pull latest repository changes on the Pi +echo "[1/2] Checking Pi internet connectivity and pulling git updates (~/speedcamera)..." +GIT_CMD="if ! ping -c 1 -W 2 1.1.1.1 &>/dev/null && ! curl -s --connect-timeout 2 https://github.com &>/dev/null; then + echo 'Error: Pi has no active internet connection. Deployment requires DHCP or Internet mode.' >&2 + echo 'Switch to internet mode: ~/speedcamera/headless-rust/scripts/setup-network.sh internet ' >&2 + exit 1 +fi +if [ ! -d ~/speedcamera/.git ]; then + echo 'Error: ~/speedcamera git repository not found on Pi. Run install:pi first.' >&2 + exit 1 +fi +cd ~/speedcamera" + +if [ -n "$BRANCH" ]; then + GIT_CMD+=" && git fetch origin && git checkout ${BRANCH} && git pull origin ${BRANCH}" +else + GIT_CMD+=" && git pull" +fi + +ssh -tt "${SSH_OPTS[@]}" "${PI_TARGET}" "${GIT_CMD}" + +# 2. Update frontend/binary & restart service on Pi +echo "[2/2] Running build and updating service directly on Pi..." +# Use -tt to force pseudo-terminal allocation so sudo can prompt for password interactively +ssh -tt "${SSH_OPTS[@]}" "${PI_TARGET}" "cd ~/speedcamera/headless-rust && chmod +x scripts/*.sh && ./scripts/update-pi.sh ${BUILD_FLAG}" + +echo "" +echo "=========================================================" +echo " Deployment / Upgrade successful on ${PI_TARGET}!" +if [ "$USE_PASSWORD" = true ]; then + echo " Check live logs: ssh -o PubkeyAuthentication=no ${PI_TARGET} 'sudo journalctl -u speedcamera -f'" +else + echo " Check live logs: ssh ${PI_TARGET} 'sudo journalctl -u speedcamera -f'" +fi +echo "=========================================================" diff --git a/headless-rust/scripts/install-remote.sh b/headless-rust/scripts/install-remote.sh new file mode 100755 index 0000000..57cde44 --- /dev/null +++ b/headless-rust/scripts/install-remote.sh @@ -0,0 +1,162 @@ +#!/usr/bin/env bash +set -e + +# Usage: ./scripts/install-remote.sh [pi_target] [options] +# Examples: +# ./scripts/install-remote.sh pi@raspberrypi.local +# ./scripts/install-remote.sh pi@192.168.1.50 --password +# ./scripts/install-remote.sh pi@raspberrypi.local --field +# ./scripts/install-remote.sh pi@raspberrypi.local --branch feature/headless +# bun run install:pi pi@raspberrypi.local + +PI_TARGET="pi@raspberrypi.local" +USE_PASSWORD=false +NETWORK_FLAG="" +PURGE_FIRST=false +REPO_URL="https://github.com/LeoLTM/speedcamera.git" +BRANCH="" + +# Parse arguments +while [[ $# -gt 0 ]]; do + case "$1" in + --password|-p|--pass) + USE_PASSWORD=true + shift + ;; + --field) + NETWORK_FLAG="--field" + shift + ;; + --lan|--no-field|--skip-network) + NETWORK_FLAG="--skip-network" + shift + ;; + --purge) + PURGE_FIRST=true + shift + ;; + --repo) + REPO_URL="$2" + shift 2 + ;; + --branch) + BRANCH="$2" + shift 2 + ;; + --help|-h) + echo "Speedcamera Headless Rust Remote Installer" + echo "" + echo "Usage: $0 [user@host] [options]" + echo "" + echo "Positional Arguments:" + echo " [user@host] SSH target (default: pi@raspberrypi.local)" + echo "" + echo "Options:" + echo " --password, -p Force password authentication (disables SSH keys)" + echo " --field Automatically switch Pi to Field Mode (Camera LAN + Hotspot AP)" + echo " --lan, --skip-network Keep Pi connected to Home LAN/Wi-Fi (skip field network setup)" + echo " --purge Clean up any existing speedcamera files/services before install" + echo " --repo Git repository URL (default: https://github.com/LeoLTM/speedcamera.git)" + echo " --branch Git branch to checkout on Pi" + echo " --help, -h Show this help message" + echo "" + echo "Notes:" + echo " • Requires Pi to be in Internet or DHCP Mode (not Field Mode) for package installation." + echo " • Clones/pulls the speedcamera repo directly to ~/speedcamera on the Pi." + echo " • Provisions system dependencies, Rust toolchain, and Bun runtime on the Pi." + echo " • Builds the frontend and compiles the native Rust release binary directly on the Pi." + echo " • All internet-dependent steps complete before optionally transitioning to Field Mode." + exit 0 + ;; + *) + if [[ "$1" != -* ]]; then + PI_TARGET="$1" + fi + shift + ;; + esac +done + +if [[ "$PI_TARGET" == *"192.168.4."* ]]; then + echo "Error: Target is in Field Mode Hotspot (${PI_TARGET})." >&2 + echo "Fresh installation requires the Pi to be in DHCP or Internet Mode to install packages and dependencies." >&2 + echo "Please connect the Pi to your home router / Wi-Fi via DHCP before installing." >&2 + exit 1 +fi + +# Setup SSH Connection Multiplexing so password is typed at most once +SOCKET_DIR="/tmp/speedcamera-install-ssh-$$" +mkdir -p "$SOCKET_DIR" +SOCKET_PATH="${SOCKET_DIR}/socket" + +SSH_OPTS=(-o "ControlMaster=auto" -o "ControlPath=${SOCKET_PATH}" -o "ControlPersist=60s" -o "ConnectTimeout=10") + +if [ "$USE_PASSWORD" = true ]; then + echo "[*] Password authentication enabled (-o PubkeyAuthentication=no)" + SSH_OPTS+=(-o "PubkeyAuthentication=no" -o "PreferredAuthentications=password,keyboard-interactive") +fi + +cleanup() { + ssh -O exit -o "ControlPath=${SOCKET_PATH}" "${PI_TARGET}" 2>/dev/null || true + rm -rf "$SOCKET_DIR" +} +trap cleanup EXIT INT TERM + +echo "=========================================================" +echo " Speedcamera Rust Remote Pi Fresh Installer" +echo " Target: ${PI_TARGET}" +echo "=========================================================" + +# 1. Test SSH connectivity & internet reachability on Pi +echo "[1/3] Connecting to ${PI_TARGET} and verifying internet reachability..." +if ! ssh "${SSH_OPTS[@]}" "${PI_TARGET}" "echo 'Connected successfully to '\$(hostname)" ; then + echo "Error: Cannot connect to ${PI_TARGET} via SSH." >&2 + exit 1 +fi + +CHECK_NET_CMD="if ! ping -c 1 -W 2 1.1.1.1 &>/dev/null && ! curl -s --connect-timeout 2 https://github.com &>/dev/null; then + echo 'Error: Pi has no active internet connection. Installation requires DHCP or Internet mode.' >&2 + exit 1 +fi" +ssh "${SSH_OPTS[@]}" "${PI_TARGET}" "${CHECK_NET_CMD}" + +# Optional cleanup before fresh install +if [ "$PURGE_FIRST" = true ]; then + echo "[*] Purging existing speedcamera installation on Pi..." + ssh -tt "${SSH_OPTS[@]}" "${PI_TARGET}" "sudo -v || true; sudo systemctl stop speedcamera 2>/dev/null || true; sudo systemctl disable speedcamera 2>/dev/null || true; sudo rm -f /etc/systemd/system/speedcamera.service; sudo systemctl daemon-reload 2>/dev/null || true; rm -rf ~/speedcamera" +fi + +# 2. Clone or update repository on the Pi +echo "[2/3] Setting up speedcamera repository in ~/speedcamera on Pi..." +if [ -n "$BRANCH" ]; then + GIT_SETUP="if [ ! -d ~/speedcamera/.git ]; then sudo apt-get update -qq && sudo apt-get install -y git && git clone -b ${BRANCH} ${REPO_URL} ~/speedcamera; else cd ~/speedcamera && git fetch origin && git checkout ${BRANCH} && git pull origin ${BRANCH}; fi" +else + GIT_SETUP="if [ ! -d ~/speedcamera/.git ]; then sudo apt-get update -qq && sudo apt-get install -y git && git clone ${REPO_URL} ~/speedcamera; else cd ~/speedcamera && git pull; fi" +fi + +ssh -tt "${SSH_OPTS[@]}" "${PI_TARGET}" "${GIT_SETUP}" + +# 3. Execute installer on Pi (all internet tasks complete before any Field Mode switch) +echo "[3/3] Running system provisioning, dependencies setup, frontend & native Rust compilation on Pi..." +REMOTE_CMD="cd ~/speedcamera/headless-rust && chmod +x scripts/*.sh && ./scripts/install-rpi.sh ${NETWORK_FLAG}" + +# Use -tt to force pseudo-terminal allocation so sudo can prompt for password interactively +ssh -tt "${SSH_OPTS[@]}" "${PI_TARGET}" "${REMOTE_CMD}" + +echo "" +echo "=========================================================" +echo " Installation Complete on ${PI_TARGET}!" +echo "=========================================================" +if [ "$NETWORK_FLAG" = "--field" ]; then + echo " Network: Standalone Field Mode Active" + echo " • Connect Wi-Fi: SSID 'speedcamera' (Pass: 'speedcamerapass')" + echo " • Web UI: http://192.168.4.1:3000" + echo " • Camera LAN: http://192.168.1.100:3000" +else + echo " Network: Home LAN / DHCP Mode Active" + echo " • Web UI: http://${PI_TARGET#*@}:3000 (or http://raspberrypi.local:3000)" + echo " • Switch to field mode when ready: ssh ${PI_TARGET} '~/speedcamera/headless-rust/scripts/setup-network.sh field'" +fi +echo "" +echo " View logs: ssh ${PI_TARGET} 'sudo journalctl -u speedcamera -f'" +echo "=========================================================" diff --git a/headless-rust/scripts/install-rpi.sh b/headless-rust/scripts/install-rpi.sh new file mode 100755 index 0000000..583a8c0 --- /dev/null +++ b/headless-rust/scripts/install-rpi.sh @@ -0,0 +1,318 @@ +#!/usr/bin/env bash +set -e + +# Detect non-root target user if executed via sudo +TARGET_USER="${SUDO_USER:-$(whoami)}" +TARGET_HOME=$(getent passwd "$TARGET_USER" | cut -d: -f6) +PROJECT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" + +echo "=========================================================" +echo " Speedcamera Rust Raspberry Pi Provisioning & Setup" +echo "=========================================================" +echo " Target user: ${TARGET_USER} (${TARGET_HOME})" +echo " Project dir: ${PROJECT_DIR}" +echo "=========================================================" + +# Parse arguments +SKIP_NETWORK=false +ONLY_NETWORK=false +FORCE_BUILD=false +AUTO_FIELD=false +CLIENT_SSID="" +CLIENT_PASS="" + +while [[ $# -gt 0 ]]; do + case "$1" in + --skip-network|--app-only|--lan|--no-field) + SKIP_NETWORK=true + shift + ;; + --field) + AUTO_FIELD=true + shift + ;; + --client|--wifi-client) + CLIENT_SSID="$2" + CLIENT_PASS="$3" + shift 2 + if [[ "$1" != --* && -n "$1" ]]; then + CLIENT_PASS="$1" + shift + fi + ;; + --network-only) + ONLY_NETWORK=true + shift + ;; + --force-build|--build) + FORCE_BUILD=true + shift + ;; + --help|-h) + echo "Usage: $0 [options]" + echo "" + echo "Options:" + echo " --app-only, --skip-network, --lan Provision packages, Rust, Bun, binary, and service (keeps network)" + echo " --field Provision and switch to Field Mode (Hotspot AP + Camera LAN) at end" + echo " --client [PASS] Provision and switch to Wi-Fi Client + Camera LAN Mode at end" + echo " --network-only Only configure network" + echo " --build, --force-build Force building release binary and frontend on the Pi" + echo " --help, -h Show this help message" + exit 0 + ;; + *) + shift + ;; + esac +done + +run_as_user() { + if [ "$(whoami)" = "${TARGET_USER}" ]; then + env PATH="$PATH" "$@" + else + sudo -u "${TARGET_USER}" env PATH="$PATH" "$@" + fi +} + +# Request sudo credentials early so user is prompted interactively if needed +echo "[*] Requesting sudo credentials on Pi..." +sudo -v || { echo "Error: Sudo privileges required to install system packages and services." >&2; exit 1; } + +if [ "$ONLY_NETWORK" = true ]; then + chmod +x "${PROJECT_DIR}/scripts/setup-network.sh" + "${PROJECT_DIR}/scripts/setup-network.sh" field + exit 0 +fi + +# Pre-flight internet check: installation MUST be done in DHCP/Internet mode +echo "[*] Checking internet connectivity..." +if ! ping -c 1 -W 2 1.1.1.1 &>/dev/null && ! curl -s --connect-timeout 2 https://bun.sh &>/dev/null; then + echo "Error: No active internet connection detected on Pi." >&2 + echo "Installation must be performed in DHCP or Internet Mode (not offline Field Mode) to download system packages and build tools." >&2 + echo "If currently in Field Mode, switch to internet mode first: ~/speedcamera/headless-rust/scripts/setup-network.sh internet " >&2 + echo "or connect an Ethernet cable and run: ~/speedcamera/headless-rust/scripts/setup-network.sh dhcp" >&2 + exit 1 +fi + +# 1. System packages (APT) +echo "[1/5] Installing system packages (libaravis, glib, udev, pkg-config, esptool, NetworkManager)..." +sudo apt-get update +sudo apt-get install -y \ + libaravis-0.8-0 \ + libaravis-dev \ + libglib2.0-dev \ + libgobject-2.0-0 \ + libudev-dev \ + pkg-config \ + build-essential \ + esptool \ + network-manager \ + dnsmasq \ + iptables \ + curl \ + unzip \ + git \ + rsync \ + sqlite3 \ + libsqlite3-dev + +# Configure fake-internet DNS rules for Windows NCSI, Fedora hotspot, and Linux connectivity checks +echo "[*] Configuring DNS interception for OS connectivity checks (Windows / Fedora / Linux)..." +sudo mkdir -p /etc/NetworkManager/dnsmasq-shared.d /etc/dnsmasq.d +sudo bash -c 'cat > /etc/NetworkManager/dnsmasq-shared.d/fake-internet.conf </dev/null || true + +# Apply GigE Vision socket buffer tuning with fq_codel to prevent bufferbloat +echo "[*] Configuring Linux socket buffers for GigE camera (with fq_codel)..." +sudo bash -c 'cat > /etc/sysctl.d/60-gige-camera.conf </dev/null || sudo sysctl --system 2>/dev/null || true + +# 2. Check/Install Rust toolchain +echo "[2/5] Checking Rust toolchain..." +export PATH="${TARGET_HOME}/.cargo/bin:${TARGET_HOME}/.bun/bin:/usr/local/bin:/usr/bin:$PATH" +if ! command -v cargo &> /dev/null && [ ! -x "${TARGET_HOME}/.cargo/bin/cargo" ]; then + echo ">>> Installing Rust toolchain via rustup..." + run_as_user bash -c "curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile default" + export PATH="${TARGET_HOME}/.cargo/bin:$PATH" +else + echo ">>> Rust toolchain ready: $(cargo --version 2>/dev/null || echo "${TARGET_HOME}/.cargo/bin/cargo")" +fi + +# 3. Check/Install Bun runtime +echo "[3/5] Checking Bun runtime..." +BUN_BIN=$(command -v bun || echo "${TARGET_HOME}/.bun/bin/bun") +if [ ! -x "${BUN_BIN}" ] && ! command -v bun &> /dev/null; then + echo ">>> Installing Bun runtime for ARM64..." + run_as_user bash -c "curl -fsSL https://bun.sh/install | bash" + export BUN_INSTALL="${TARGET_HOME}/.bun" + export PATH="${BUN_INSTALL}/bin:$PATH" + BUN_BIN="${TARGET_HOME}/.bun/bin/bun" +else + echo ">>> Bun runtime ready: ${BUN_BIN}" +fi + +# 4. Binary and frontend bundle compilation on Pi +echo "[4/5] Building frontend and compiling native Rust daemon on Pi..." +cd "${PROJECT_DIR}" + +# Build frontend bundle +if [ -x "${BUN_BIN}" ] || command -v bun &> /dev/null; then + if [ ! -d "node_modules" ] || [ "package.json" -nt "node_modules" ]; then + echo ">>> Installing frontend dependencies with Bun..." + run_as_user "${BUN_BIN}" install + fi + echo ">>> Building frontend assets with Bun..." + run_as_user "${BUN_BIN}" run build +else + if [ ! -f "${PROJECT_DIR}/dist/index.html" ]; then + echo "Error: Missing frontend dist/ and Bun runtime unavailable to build it." >&2 + exit 1 + fi +fi + +# Build Rust binary on Pi +CARGO_BIN=$(command -v cargo || echo "${TARGET_HOME}/.cargo/bin/cargo") +if [ ! -x "${CARGO_BIN}" ] && ! command -v cargo &> /dev/null; then + echo "Error: Cargo not available to build release binary." >&2 + exit 1 +fi +echo ">>> Compiling native Rust release binary on Pi..." +run_as_user "${CARGO_BIN}" build --release + +# 5. Systemd daemon installation +echo "[5/5] Configuring systemd autostart service..." +SERVICE_FILE="/etc/systemd/system/speedcamera.service" + +sudo bash -c "cat > ${SERVICE_FILE}" </dev/null || sudo bash -c "cat > /etc/systemd/system/wifi-power-off.service <<'EOF' +[Unit] +Description=Disable WiFi Power Management +After=network.target + +[Service] +Type=oneshot +ExecStart=/sbin/iwconfig wlan0 power off +RemainAfterExit=yes + +[Install] +WantedBy=multi-user.target +EOF" + +sudo systemctl daemon-reload +sudo systemctl enable speedcamera.service +sudo systemctl enable wifi-power-off.service +sudo systemctl restart wifi-power-off.service 2>/dev/null || true +sudo systemctl restart speedcamera.service + +echo "" +echo "=========================================================" +echo " Speedcamera Rust Daemon is installed & active!" +echo " Daemon status: sudo systemctl status speedcamera" +echo " Daemon logs: sudo journalctl -u speedcamera -f" +echo "=========================================================" + +# Step 6: Network Mode Transition (executed ONLY after all builds & services are fully running) +if [ -n "$CLIENT_SSID" ]; then + echo "[*] Switching network to Wi-Fi Client + Camera LAN Mode (SSID: ${CLIENT_SSID})..." + chmod +x "${PROJECT_DIR}/scripts/setup-network.sh" + "${PROJECT_DIR}/scripts/setup-network.sh" client "${CLIENT_SSID}" "${CLIENT_PASS}" + exit 0 +fi + +if [ "$AUTO_FIELD" = true ]; then + echo "[*] Switching network to Open AP Setup Mode (Camera LAN + Open Hotspot AP)..." + chmod +x "${PROJECT_DIR}/scripts/setup-network.sh" + "${PROJECT_DIR}/scripts/setup-network.sh" ap + exit 0 +fi + +if [ "$SKIP_NETWORK" = true ]; then + echo "Keeping current network configuration (--skip-network / --lan)." + echo "When ready for initial Wi-Fi setup, run:" + echo " ~/speedcamera/headless-rust/scripts/setup-network.sh ap" + echo "Or for Wi-Fi Client + Camera LAN mode, run:" + echo " ~/speedcamera/headless-rust/scripts/setup-network.sh client [PASS]" + exit 0 +fi + +# If running in interactive terminal, prompt user +if [ -t 0 ]; then + echo "" + echo "=========================================================================" + echo " INITIAL AP SETUP MODE (Camera LAN + Open Hotspot AP)" + echo "=========================================================================" + echo " All software and services have been installed and built successfully." + echo " Ready to switch Pi into Open AP Setup Mode:" + echo " • Ethernet (eth0) -> Static IP 192.168.1.100 (GigE Camera LAN)" + echo " • Wi-Fi (wlan0) -> Open Hotspot AP 192.168.4.1 (SSID: speedcamera, no password)" + echo " • Captive portal redirects to Network settings for Client Wi-Fi onboarding." + echo "" + echo " WARNING: This will disconnect current Wi-Fi/SSH internet connection!" + echo "=========================================================================" + read -p "Switch to Open AP Setup Mode now? (y/N) " -n 1 -r + echo "" + + if [[ $REPLY =~ ^[Yy]$ ]]; then + chmod +x "${PROJECT_DIR}/scripts/setup-network.sh" + echo "[*] Launching Open AP Setup Mode in background..." + nohup sudo "${PROJECT_DIR}/scripts/setup-network.sh" ap > /tmp/setup-network.log 2>&1 & + sleep 1 + echo "" + echo "=========================================================================" + echo " Open AP Setup Mode is now starting!" + echo " • Open Hotspot: 'speedcamera' (No password)" + echo " • Web UI: http://192.168.4.1:3000" + echo " Connect your phone or laptop to 'speedcamera' now." + echo "=========================================================================" + else + echo "Skipping AP Setup Mode network switch for now." + echo "Run anytime later: ~/speedcamera/headless-rust/scripts/setup-network.sh ap" + fi +else + echo "Non-interactive session: Keeping existing network configuration." + echo "Switch to AP mode when ready: ~/speedcamera/headless-rust/scripts/setup-network.sh ap" +fi diff --git a/headless-rust/scripts/setup-network.sh b/headless-rust/scripts/setup-network.sh new file mode 100755 index 0000000..ae71779 --- /dev/null +++ b/headless-rust/scripts/setup-network.sh @@ -0,0 +1,454 @@ +#!/usr/bin/env bash +set -e +trap '' HUP PIPE INT TERM + +MODE="${1:-status}" + +echo "=========================================================" +echo " Speedcamera Network Manager" +echo "=========================================================" + +# Detect Ethernet Interface (eth0, end0, enp*, etc.) +ETH_IFACE=$(ip -o link show | awk -F': ' '{print $2}' | grep -E '^(eth|end|enp)' | head -n 1 || echo "eth0") +# Detect Wi-Fi Interface (wlan0, wifi0, wlp*, etc.) +WIFI_IFACE=$(ip -o link show | awk -F': ' '{print $2}' | grep -E '^(wlan|wifi|wlp)' | head -n 1 || echo "wlan0") + +echo "[*] Detected Interfaces:" +echo " Ethernet (Camera LAN): ${ETH_IFACE}" +echo " Wireless (Hotspot/Wi-Fi): ${WIFI_IFACE}" +echo "" + +# For modifying operations, request sudo privileges +if [ "$MODE" != "status" ] && [ "$MODE" != "scan" ]; then + sudo -v || { echo "Error: Sudo privileges required to change network configuration." >&2; exit 1; } +fi + +apply_camera_lan_config() { + echo "[*] Configuring Camera LAN on ${ETH_IFACE} (Static IP 192.168.1.100/24, MTU 9000)..." + + # Apply GigE Vision kernel socket buffer optimizations without causing Wi-Fi bufferbloat + sudo bash -c 'cat > /etc/sysctl.d/60-gige-camera.conf </dev/null || sudo sysctl --system 2>/dev/null || true + + # Enable jumbo frames on camera NIC + sudo ip link set dev "${ETH_IFACE}" mtu 9000 2>/dev/null || true + + sudo nmcli connection delete "Speedcamera-CameraLAN" 2>/dev/null || true + sudo nmcli connection delete "Speedcamera-Ethernet-DHCP" 2>/dev/null || true + sudo nmcli connection add type ethernet \ + ifname "${ETH_IFACE}" \ + con-name "Speedcamera-CameraLAN" \ + autoconnect yes \ + ipv4.method manual \ + ipv4.addresses 192.168.1.100/24 \ + ipv4.never-default yes \ + 802-3-ethernet.mtu 9000 2>/dev/null || true + sudo nmcli connection up "Speedcamera-CameraLAN" 2>/dev/null || echo "Note: Ethernet link active when camera cable is connected." +} + +apply_ethernet_dhcp() { + echo "[*] Configuring Ethernet on ${ETH_IFACE} to standard DHCP (Internet / Updates)..." + sudo nmcli connection delete "Speedcamera-CameraLAN" 2>/dev/null || true + sudo nmcli connection delete "Speedcamera-Ethernet-DHCP" 2>/dev/null || true + sudo nmcli connection add type ethernet \ + ifname "${ETH_IFACE}" \ + con-name "Speedcamera-Ethernet-DHCP" \ + autoconnect yes \ + ipv4.method auto 2>/dev/null || true + sudo nmcli connection up "Speedcamera-Ethernet-DHCP" 2>/dev/null || echo "Note: Ethernet link active when cable is connected." +} + +enforce_wifi_powersave_off() { + echo "[*] Locking down Wi-Fi power management permanently (wifi.powersave=2)..." + sudo mkdir -p /etc/NetworkManager/conf.d + sudo bash -c 'cat > /etc/NetworkManager/conf.d/default-wifi-powersave-off.conf < /etc/systemd/system/wifi-power-off.service </dev/null || true + sudo systemctl enable wifi-power-off.service 2>/dev/null || true + sudo systemctl restart wifi-power-off.service 2>/dev/null || sudo iw dev "${WIFI_IFACE}" set power_save off 2>/dev/null || sudo iwconfig "${WIFI_IFACE}" power off 2>/dev/null || true +} + +apply_ap_mode() { + echo ">>> Applying SETUP / AP MODE (Open Hotspot + Captive Portal):" + echo " 1. Wi-Fi Hotspot (${WIFI_IFACE}) -> Open AP (SSID: speedcamera, No password)" + echo " 2. Static Hotspot IP: 192.168.4.1/24" + echo " 3. Captive portal active -> redirects to web setup at http://192.168.4.1:3000" + echo "" + + # 1. Enforce power save off & disable standalone dnsmasq service to prevent port 53 collision + enforce_wifi_powersave_off + sudo systemctl stop dnsmasq 2>/dev/null || true + sudo systemctl disable dnsmasq 2>/dev/null || true + + # 2. Configure Open Wi-Fi Hotspot AP + echo "[*] Configuring Open Wi-Fi Hotspot AP on ${WIFI_IFACE}..." + SSID="speedcamera" + + # Unblock Wi-Fi radio and ensure link is up + sudo rfkill unblock wifi 2>/dev/null || true + sudo ip link set dev "${WIFI_IFACE}" up 2>/dev/null || true + + sudo nmcli connection delete "Speedcamera-Hotspot" 2>/dev/null || true + sudo nmcli connection delete "Speedcamera-ClientWiFi" 2>/dev/null || true + + # Try 5GHz Band A (Channel 36) first, fallback to 2.4GHz Band BG if 5GHz AP is restricted + local AP_SUCCESS=0 + if sudo nmcli connection add type wifi \ + ifname "${WIFI_IFACE}" \ + con-name "Speedcamera-Hotspot" \ + autoconnect yes \ + ssid "${SSID}" \ + mode ap \ + 802-11-wireless.band a \ + 802-11-wireless.channel 36 \ + 802-11-wireless.powersave 2 \ + 802-11-wireless.mac-address-randomization 1 \ + ipv4.method shared \ + ipv4.addresses 192.168.4.1/24 \ + ipv4.never-default yes 2>/dev/null && sudo nmcli connection up "Speedcamera-Hotspot" 2>/dev/null; then + AP_SUCCESS=1 + echo "[*] 5GHz Open AP Hotspot initialized on channel 36." + else + echo "[-] 5GHz AP restricted or failed. Initializing 2.4GHz Open AP on channel 6..." + sudo nmcli connection delete "Speedcamera-Hotspot" 2>/dev/null || true + if sudo nmcli connection add type wifi \ + ifname "${WIFI_IFACE}" \ + con-name "Speedcamera-Hotspot" \ + autoconnect yes \ + ssid "${SSID}" \ + mode ap \ + 802-11-wireless.band bg \ + 802-11-wireless.channel 6 \ + 802-11-wireless.powersave 2 \ + 802-11-wireless.mac-address-randomization 1 \ + ipv4.method shared \ + ipv4.addresses 192.168.4.1/24 \ + ipv4.never-default yes 2>/dev/null && sudo nmcli connection up "Speedcamera-Hotspot" 2>/dev/null; then + AP_SUCCESS=1 + echo "[*] 2.4GHz Open AP Hotspot initialized on channel 6." + else + echo "[-] Warning: Hotspot connection up failed. Retrying..." + sudo nmcli connection up "Speedcamera-Hotspot" 2>/dev/null || true + fi + fi + + # 3. Configure DNS interception for captive portal (192.168.4.1) + echo "[*] Configuring captive portal DNS interception (192.168.4.1)..." + sudo mkdir -p /etc/NetworkManager/dnsmasq-shared.d /etc/dnsmasq.d + sudo bash -c 'cat > /etc/NetworkManager/dnsmasq-shared.d/fake-internet.conf </dev/null || true + + # Redirect port 80 to port 3000 on hotspot interface so OS HTTP probe requests hit the web server + echo "[*] Redirecting HTTP probe port 80 -> 3000 on ${WIFI_IFACE}..." + sudo iptables -t nat -D PREROUTING -i "${WIFI_IFACE}" -p tcp --dport 80 -j REDIRECT --to-port 3000 2>/dev/null || true + sudo iptables -t nat -A PREROUTING -i "${WIFI_IFACE}" -p tcp --dport 80 -j REDIRECT --to-port 3000 2>/dev/null || true + + # Block Bluetooth to free 2.4GHz spectrum and internal resources + echo "[*] Blocking Bluetooth to improve Wi-Fi performance..." + sudo rfkill block bluetooth 2>/dev/null || true + + # 4. Configure Camera LAN on eth0 LAST (so Ethernet drop does not abort Wi-Fi setup) + if ! nmcli -t -f NAME connection show --active 2>/dev/null | grep -qx "Speedcamera-Ethernet-DHCP"; then + apply_camera_lan_config + fi + + echo "" + echo "=========================================================" + echo " AP / Setup Mode Active!" + echo " • Open Hotspot: SSID '${SSID}' (No password)" + echo " • Web UI: http://192.168.4.1:3000" + echo " • Camera LAN: http://192.168.1.100:3000" + echo "=========================================================" +} + +apply_client_mode() { + local WIFI_SSID="$1" + local WIFI_PASS="$2" + + if [ -z "$WIFI_SSID" ]; then + echo "Usage: $0 client [Wi-Fi-Password]" + echo "Example: $0 client MyHomeWiFi SecretPassword123" + exit 1 + fi + + echo ">>> Applying WI-FI CLIENT MODE (Normal Operation):" + echo " 1. Wi-Fi Client (${WIFI_IFACE}) -> Connecting to SSID: '${WIFI_SSID}' (DHCP)" + echo " 2. Camera LAN (${ETH_IFACE}) -> Static IP 192.168.1.100/24" + echo "" + + # Ensure Camera LAN is active on eth0 if not already in DHCP mode + if ! nmcli -t -f NAME connection show --active 2>/dev/null | grep -qx "Speedcamera-Ethernet-DHCP"; then + apply_camera_lan_config + fi + + # Enforce Wi-Fi Power-Save OFF + enforce_wifi_powersave_off + + # Clean up fake-internet DNS interception and port 80 redirect + echo "[*] Cleaning up captive portal DNS rules & port redirects..." + sudo rm -f /etc/NetworkManager/dnsmasq-shared.d/fake-internet.conf /etc/dnsmasq.d/fake-internet.conf 2>/dev/null || true + sudo iptables -t nat -D PREROUTING -i "${WIFI_IFACE}" -p tcp --dport 80 -j REDIRECT --to-port 3000 2>/dev/null || true + + # Tear down Hotspot AP profile + echo "[*] Stopping Wi-Fi Hotspot AP and connecting as Client Station..." + sudo nmcli connection delete "Speedcamera-Hotspot" 2>/dev/null || true + sudo nmcli connection delete "Speedcamera-ClientWiFi" 2>/dev/null || true + + # Scan and connect to external Wi-Fi network + sudo nmcli dev wifi rescan 2>/dev/null || true + sleep 1 + + local CONNECT_SUCCESS=0 + if [ -n "$WIFI_PASS" ]; then + if sudo nmcli dev wifi connect "${WIFI_SSID}" password "${WIFI_PASS}" ifname "${WIFI_IFACE}" name "Speedcamera-ClientWiFi"; then + CONNECT_SUCCESS=1 + fi + else + if sudo nmcli dev wifi connect "${WIFI_SSID}" ifname "${WIFI_IFACE}" name "Speedcamera-ClientWiFi"; then + CONNECT_SUCCESS=1 + fi + fi + + if [ "$CONNECT_SUCCESS" -ne 1 ]; then + echo "" >&2 + echo "[-] Error: Failed to connect to Wi-Fi network '${WIFI_SSID}'." >&2 + echo "[*] Falling back to AP Mode..." >&2 + apply_ap_mode + exit 1 + fi + + # Optimize client connection: powersave off, no MAC randomization, autoconnect on boot + sudo nmcli connection modify "Speedcamera-ClientWiFi" 802-11-wireless.powersave 2 2>/dev/null || true + sudo nmcli connection modify "Speedcamera-ClientWiFi" 802-11-wireless.mac-address-randomization 1 2>/dev/null || true + sudo nmcli connection modify "Speedcamera-ClientWiFi" connection.autoconnect yes 2>/dev/null || true + + echo "" + echo "[*] Connected to '${WIFI_SSID}'. Waiting for DHCP lease..." + sleep 3 + + local WIFI_IP + WIFI_IP=$(ip -4 -o addr show dev "${WIFI_IFACE}" 2>/dev/null | awk '{print $4}' | cut -d/ -f1 | head -n 1 || echo "") + + echo "" + echo "=========================================================" + echo " Wi-Fi Client Mode Active!" + echo " • Connected Wi-Fi: SSID '${WIFI_SSID}'" + if [ -n "$WIFI_IP" ]; then + echo " • Wi-Fi Client IP: ${WIFI_IP}" + echo " • Web UI: http://${WIFI_IP}:3000" + else + echo " • Wi-Fi Client IP: Waiting for DHCP..." + echo " • Web UI: http://raspberrypi.local:3000" + fi + echo " • Camera LAN: http://192.168.1.100:3000" + echo "=========================================================" +} + +apply_auto_mode() { + echo ">>> Boot Auto Network Check..." + + # Check if saved client profile exists + if nmcli connection show "Speedcamera-ClientWiFi" &>/dev/null; then + echo "[*] Found saved client connection profile. Attempting connect..." + enforce_wifi_powersave_off + sudo rm -f /etc/NetworkManager/dnsmasq-shared.d/fake-internet.conf /etc/dnsmasq.d/fake-internet.conf 2>/dev/null || true + sudo iptables -t nat -D PREROUTING -i "${WIFI_IFACE}" -p tcp --dport 80 -j REDIRECT --to-port 3000 2>/dev/null || true + + if sudo nmcli connection up "Speedcamera-ClientWiFi" --timeout 15 2>/dev/null; then + echo "[*] Successfully connected to saved Wi-Fi network!" + if ! nmcli -t -f NAME connection show --active 2>/dev/null | grep -qx "Speedcamera-Ethernet-DHCP"; then + apply_camera_lan_config + fi + return 0 + else + echo "[-] Failed to connect to saved Wi-Fi. Falling back to Open AP mode..." + fi + else + echo "[*] No saved Wi-Fi profile found. Starting Open AP Setup mode..." + fi + + apply_ap_mode +} + +forget_wifi() { + echo ">>> Forgetting saved Wi-Fi network..." + sudo nmcli connection delete "Speedcamera-ClientWiFi" 2>/dev/null || true + echo "[*] Saved Wi-Fi forgotten. Switching to Open AP Setup mode..." + apply_ap_mode +} + +apply_dhcp_mode() { + echo ">>> Reverting Ethernet and Wi-Fi to standard DHCP..." + + sudo rm -f /etc/NetworkManager/dnsmasq-shared.d/fake-internet.conf /etc/dnsmasq.d/fake-internet.conf 2>/dev/null || true + sudo iptables -t nat -D PREROUTING -i "${WIFI_IFACE}" -p tcp --dport 80 -j REDIRECT --to-port 3000 2>/dev/null || true + + sudo nmcli connection delete "Speedcamera-Ethernet-DHCP" 2>/dev/null || true + sudo nmcli connection add type ethernet ifname "${ETH_IFACE}" con-name "Speedcamera-Ethernet-DHCP" autoconnect yes ipv4.method auto 2>/dev/null || true + sudo nmcli connection up "Speedcamera-Ethernet-DHCP" 2>/dev/null || true + + sudo nmcli connection delete "Speedcamera-CameraLAN" 2>/dev/null || true + sudo nmcli connection delete "Speedcamera-Hotspot" 2>/dev/null || true + sudo nmcli connection delete "Speedcamera-ClientWiFi" 2>/dev/null || true + echo "Interfaces set to standard DHCP." +} + +scan_wifi_networks() { + echo "--- Scanning Visible Wi-Fi Networks ---" + sudo nmcli dev wifi rescan 2>/dev/null || true + nmcli -f IN-USE,SSID,BSSID,CHAN,SIGNAL,SECURITY dev wifi list || true +} + +show_status() { + echo "--- Network Configuration Mode ---" + local HAS_HOTSPOT=0 + local HAS_CLIENT=0 + local HAS_CAM_LAN=0 + local HAS_ETH_DHCP=0 + + if nmcli -t -f NAME connection show --active 2>/dev/null | grep -qx "Speedcamera-Hotspot"; then + HAS_HOTSPOT=1 + fi + if nmcli -t -f NAME connection show --active 2>/dev/null | grep -qx "Speedcamera-ClientWiFi"; then + HAS_CLIENT=1 + fi + if nmcli -t -f NAME connection show --active 2>/dev/null | grep -qx "Speedcamera-CameraLAN"; then + HAS_CAM_LAN=1 + fi + if nmcli -t -f NAME connection show --active 2>/dev/null | grep -qx "Speedcamera-Ethernet-DHCP"; then + HAS_ETH_DHCP=1 + fi + + if [ "$HAS_HOTSPOT" -eq 1 ]; then + echo "Wi-Fi Mode: AP / SETUP (Open Hotspot 192.168.4.1)" + elif [ "$HAS_CLIENT" -eq 1 ]; then + echo "Wi-Fi Mode: CLIENT (Connected to external router)" + else + echo "Wi-Fi Mode: DISCONNECTED / UNMANAGED" + fi + + if [ "$HAS_CAM_LAN" -eq 1 ]; then + echo "Ethernet Mode: CAMERA LAN (Static 192.168.1.100 MTU 9000)" + elif [ "$HAS_ETH_DHCP" -eq 1 ]; then + echo "Ethernet Mode: STANDARD DHCP (Internet / Updates)" + else + echo "Ethernet Mode: UNMANAGED" + fi + echo "" + + echo "--- Active Network Connections ---" + nmcli connection show --active || true + echo "" + + echo "--- IP Addresses ---" + ip -br addr show || true + echo "" + + echo "--- Wi-Fi Power Management ---" + if command -v iw &>/dev/null; then + iw dev "${WIFI_IFACE}" get power_save 2>/dev/null || echo "Power Save: N/A" + elif command -v iwconfig &>/dev/null; then + iwconfig "${WIFI_IFACE}" 2>/dev/null | grep -i "Power Management" || echo "Power Save: N/A" + fi + echo "" + + echo "--- Internet Reachability ---" + if ping -c 1 -W 2 1.1.1.1 &>/dev/null; then + echo "Status: ONLINE (Internet reachable)" + else + echo "Status: OFFLINE (Isolated AP setup mode or no default route)" + fi +} + +case "$MODE" in + ap|field|hotspot) + apply_ap_mode + ;; + + client|wifi-client|internet|wifi) + apply_client_mode "$2" "$3" + ;; + + auto) + apply_auto_mode + ;; + + forget|reset-wifi) + forget_wifi + ;; + + lan-camera|camera-lan) + apply_camera_lan_config + ;; + + lan-dhcp|ethernet-dhcp) + apply_ethernet_dhcp + ;; + + dhcp|reset) + apply_dhcp_mode + ;; + + scan) + scan_wifi_networks + ;; + + status) + show_status + ;; + + *) + echo "Usage: $0 {ap|client [PASS]|auto|forget|lan-camera|lan-dhcp|scan|dhcp|status}" + echo "" + echo "Commands:" + echo " ap Start Open AP Hotspot (192.168.4.1) for setup" + echo " client [PASS] Connect Wi-Fi client to router (main operation mode)" + echo " auto Try connect to saved Wi-Fi, fallback to AP if unavailable" + echo " forget Delete saved Wi-Fi credentials and switch to AP mode" + echo " lan-camera Set Ethernet to Camera LAN (192.168.1.100, MTU 9000)" + echo " lan-dhcp Set Ethernet to standard DHCP (for updates/wired internet)" + echo " scan Scan visible 2.4GHz & 5GHz Wi-Fi networks" + echo " dhcp Reset ethernet & Wi-Fi to standard DHCP" + echo " status Check current network mode, IP addresses, and connectivity" + exit 1 + ;; +esac diff --git a/headless-rust/scripts/speedcamera.service b/headless-rust/scripts/speedcamera.service new file mode 100644 index 0000000..d38f2a6 --- /dev/null +++ b/headless-rust/scripts/speedcamera.service @@ -0,0 +1,24 @@ +[Unit] +Description=Speedcamera Native Rust Daemon & Web Server +After=network.target network-online.target +Wants=network-online.target + +[Service] +Type=simple +User=pi +WorkingDirectory=/home/pi/speedcamera/headless-rust +Environment=PORT=3000 +Environment=HOST=0.0.0.0 +Environment=DATA_DIR=/home/pi/.speedcamera +Environment=PATH=/home/pi/.cargo/bin:/home/pi/.bun/bin:/usr/local/bin:/usr/bin:/bin +ExecStart=/home/pi/speedcamera/headless-rust/target/release/headless-rust +Restart=always +RestartSec=2 +KillSignal=SIGINT +LimitNOFILE=65536 +LimitMEMLOCK=infinity +AmbientCapabilities=CAP_NET_RAW CAP_NET_ADMIN +CapabilityBoundingSet=CAP_NET_RAW CAP_NET_ADMIN + +[Install] +WantedBy=multi-user.target diff --git a/headless-rust/scripts/test-live-events.ts b/headless-rust/scripts/test-live-events.ts new file mode 100644 index 0000000..8072192 --- /dev/null +++ b/headless-rust/scripts/test-live-events.ts @@ -0,0 +1,147 @@ +#!/usr/bin/env bun +import { spawn } from "child_process"; +import { existsSync, statSync } from "fs"; +import { io } from "socket.io-client"; + +console.log("Starting speedcamera headless-rust server in mock mode on port 3099 for live event testing..."); + +let binaryPath = "cargo"; +const relPath = "./target/release/headless-rust"; +const dbgPath = "./target/debug/headless-rust"; + +if (existsSync(relPath) && existsSync(dbgPath)) { + binaryPath = statSync(relPath).mtimeMs > statSync(dbgPath).mtimeMs ? relPath : dbgPath; +} else if (existsSync(relPath)) { + binaryPath = relPath; +} else if (existsSync(dbgPath)) { + binaryPath = dbgPath; +} + +const args = binaryPath === "cargo" + ? ["run", "--", "--mock", "--port", "3099"] + : ["--mock", "--port", "3099"]; + +const proc = spawn(binaryPath, args, { + cwd: process.cwd(), + stdio: "pipe", +}); + +proc.stdout?.on("data", (data) => console.log(`[server stdout] ${data}`)); +proc.stderr?.on("data", (data) => console.error(`[server stderr] ${data}`)); + +// Wait up to 15s for server to start +let ready = false; +for (let i = 0; i < 30; i++) { + await new Promise((r) => setTimeout(r, 500)); + try { + const res = await fetch("http://127.0.0.1:3099/api/health"); + if (res.ok) { + ready = true; + break; + } + } catch {} +} + +if (!ready) { + proc.kill(); + console.error("Server failed to start within timeout."); + process.exit(1); +} + +try { + const socket = io("http://127.0.0.1:3099", { + transports: ["websocket", "polling"], + timeout: 5000, + }); + + await new Promise((resolve, reject) => { + const testTimer = setTimeout(() => reject(new Error("Live events test timed out after 15s")), 15000); + + let receivedLiveFrames = 0; + let receivedViolation = false; + let setupStreamActive = false; + + socket.on("connect", async () => { + console.log("Socket.io connected successfully! Testing live events..."); + + socket.on("liveFrame", (b64Frame) => { + receivedLiveFrames++; + console.log(`[EVENT] Received liveFrame #${receivedLiveFrames} (length: ${b64Frame?.length || 0})`); + }); + + socket.on("violation", (violation) => { + console.log(`[EVENT] Received violation event: ID #${violation.id} (${violation.measuredSpeed} km/h)`); + receivedViolation = true; + }); + + socket.on("cameraStatus", (status) => { + console.log("[EVENT] Received cameraStatus:", status); + if (status.isStreaming) { + setupStreamActive = true; + } + }); + + try { + // 1. Arm the system + console.log("Arming system..."); + await socket.emitWithAck("rpc", { method: "setArmed", params: { armed: true } }); + + // 2. Start Setup Stream + console.log("Starting setup preview stream via RPC..."); + await socket.emitWithAck("rpc", { method: "startSetupStream", params: {} }); + + // Wait 1.5 seconds for frames to arrive + await new Promise((r) => setTimeout(r, 1500)); + + if (receivedLiveFrames === 0) { + throw new Error("No live frames received from setup stream!"); + } + console.log(`SUCCESS: Received ${receivedLiveFrames} live preview frames over Socket.io!`); + + // 3. Trigger a violation via saveViolation RPC + console.log("Triggering violation via saveViolation RPC..."); + const saveResp: any = await socket.emitWithAck("rpc", { + method: "saveViolation", + params: { + measuredSpeed: 67.5, + maxSpeed: 30.0, + direction: "approaching", + }, + }); + console.log("saveViolation RPC response:", saveResp); + + // Wait 500ms for broadcast to arrive + await new Promise((r) => setTimeout(r, 500)); + + if (!receivedViolation) { + throw new Error("Violation push broadcast was not received over Socket.io!"); + } + console.log("SUCCESS: Violation push broadcast received over Socket.io!"); + + // 4. Stop setup stream + console.log("Stopping setup stream..."); + await socket.emitWithAck("rpc", { method: "stopSetupStream", params: {} }); + + clearTimeout(testTimer); + socket.disconnect(); + resolve(); + } catch (err) { + clearTimeout(testTimer); + socket.disconnect(); + reject(err); + } + }); + + socket.on("connect_error", (err) => { + clearTimeout(testTimer); + reject(err); + }); + }); + + console.log("\n========================================================="); + console.log(" ALL LIVE EVENTS & PREVIEW STREAM CHECKS PASSED!"); + console.log("========================================================="); +} finally { + proc.kill(); +} +process.exit(0); diff --git a/headless-rust/scripts/test-server.ts b/headless-rust/scripts/test-server.ts new file mode 100755 index 0000000..87edfc1 --- /dev/null +++ b/headless-rust/scripts/test-server.ts @@ -0,0 +1,161 @@ +#!/usr/bin/env bun +import { spawn } from "child_process"; +import { existsSync } from "fs"; +import { io } from "socket.io-client"; + +console.log("Starting speedcamera headless-rust server in mock mode on port 3099..."); + +import { statSync } from "fs"; + +let binaryPath = "cargo"; +const relPath = "./target/release/headless-rust"; +const dbgPath = "./target/debug/headless-rust"; + +if (existsSync(relPath) && existsSync(dbgPath)) { + binaryPath = statSync(relPath).mtimeMs > statSync(dbgPath).mtimeMs ? relPath : dbgPath; +} else if (existsSync(relPath)) { + binaryPath = relPath; +} else if (existsSync(dbgPath)) { + binaryPath = dbgPath; +} + +const args = binaryPath === "cargo" + ? ["run", "--", "--mock", "--port", "3099"] + : ["--mock", "--port", "3099"]; + +const proc = spawn(binaryPath, args, { + cwd: process.cwd(), + stdio: "pipe", +}); + +proc.stdout?.on("data", (data) => console.log(`[server stdout] ${data}`)); +proc.stderr?.on("data", (data) => console.error(`[server stderr] ${data}`)); + +// Wait up to 15s for server to start +let ready = false; +for (let i = 0; i < 30; i++) { + await new Promise((r) => setTimeout(r, 500)); + try { + const res = await fetch("http://127.0.0.1:3099/api/health"); + if (res.ok) { + ready = true; + break; + } + } catch {} +} + +if (!ready) { + proc.kill(); + console.error("Server failed to start within timeout."); + process.exit(1); +} + +try { + // 1. Test Health endpoint + console.log("Testing GET http://127.0.0.1:3099/api/health ..."); + const healthRes = await fetch("http://127.0.0.1:3099/api/health"); + const healthData = await healthRes.json(); + console.log("Health response:", healthData); + if (healthData.status !== "ok") throw new Error("Health check failed"); + + // 2. Test Network endpoint + console.log("Testing GET http://127.0.0.1:3099/api/network ..."); + const netRes = await fetch("http://127.0.0.1:3099/api/network"); + const netData = await netRes.json(); + console.log("Network status:", netData.status); + + // 3. Test SPA index.html + console.log("Testing GET http://127.0.0.1:3099/ ..."); + const indexRes = await fetch("http://127.0.0.1:3099/"); + const indexHtml = await indexRes.text(); + if (!indexHtml.includes("") && !indexHtml.includes("((resolve, reject) => { + const timer = setTimeout(() => reject(new Error("Socket.io test timed out")), 10000); + + let initialCameraStatusReceived = false; + let initialSerialStatusReceived = false; + + socket.on("cameraStatus", (status) => { + console.log("Push event received: cameraStatus", status); + initialCameraStatusReceived = true; + }); + + socket.on("serialStatus", (status) => { + console.log("Push event received: serialStatus", status); + initialSerialStatusReceived = true; + }); + + socket.on("connect", async () => { + console.log("Socket.io connected successfully! Socket ID:", socket.id); + + try { + // Test RPC: ping + const pingResp: any = await socket.timeout(3000).emitWithAck("ping"); + console.log("Ping response:", pingResp); + if (!pingResp?.pong) throw new Error("Ping failed"); + + // Test RPC: getSettings + const settingsResp: any = await socket.timeout(3000).emitWithAck("rpc", { method: "getSettings", params: {} }); + console.log("RPC getSettings response:", settingsResp); + if (settingsResp.error || typeof settingsResp.result?.maxSpeed !== "number") { + throw new Error("getSettings RPC failed"); + } + console.log("SUCCESS: Settings RPC validated!"); + + // Test RPC: getViolations + const violationsResp: any = await socket.timeout(3000).emitWithAck("rpc", { method: "getViolations", params: { page: 1, limit: 10 } }); + console.log("RPC getViolations response:", violationsResp); + if (violationsResp.error || !Array.isArray(violationsResp.result?.violations)) { + throw new Error("getViolations RPC failed"); + } + console.log("SUCCESS: Violations RPC validated!"); + + // Test RPC: getArmedState + const armedStateResp: any = await socket.timeout(3000).emitWithAck("rpc", { method: "getArmedState", params: {} }); + console.log("RPC getArmedState response:", armedStateResp); + if (armedStateResp.error || typeof armedStateResp.result?.armed !== "boolean") { + throw new Error("getArmedState RPC failed"); + } + + // Test RPC: setArmed + const setArmedResp: any = await socket.timeout(3000).emitWithAck("rpc", { method: "setArmed", params: { armed: true } }); + console.log("RPC setArmed response:", setArmedResp); + if (setArmedResp.error || setArmedResp.result?.armed !== true) { + throw new Error("setArmed RPC failed"); + } + console.log("SUCCESS: Armed RPC validated!"); + + clearTimeout(timer); + socket.disconnect(); + resolve(); + } catch (err) { + clearTimeout(timer); + socket.disconnect(); + reject(err); + } + }); + + socket.on("connect_error", (err) => { + clearTimeout(timer); + reject(err); + }); + }); + + console.log("\n========================================================="); + console.log(" ALL SOCKET.IO INTEGRATION TESTS PASSED SUCCESSFULLY!"); + console.log("========================================================="); +} finally { + proc.kill(); +} +process.exit(0); diff --git a/headless-rust/scripts/update-pi.sh b/headless-rust/scripts/update-pi.sh new file mode 100755 index 0000000..2045ce8 --- /dev/null +++ b/headless-rust/scripts/update-pi.sh @@ -0,0 +1,172 @@ +#!/usr/bin/env bash +set -e + +# Usage: ./scripts/update-pi.sh [options] +# Options: +# --build, -b, --force-build Force rebuilding frontend bundle and Rust release binary +# --pull Run git pull in ~/speedcamera before building +# --help, -h Show help message + +FORCE_BUILD=false +DO_PULL=false + +for arg in "$@"; do + case "$arg" in + --build|-b|--force-build) + FORCE_BUILD=true + ;; + --pull) + DO_PULL=true + ;; + --help|-h) + echo "Speedcamera Headless Rust Pi Update & Build Script" + echo "" + echo "Usage: $0 [options]" + echo "" + echo "Options:" + echo " --build, -b, --force-build Force compiling frontend and Rust binary on Pi" + echo " --pull Run git pull in ~/speedcamera before building" + echo " --help, -h Show this help message" + exit 0 + ;; + esac +done + +TARGET_USER="${SUDO_USER:-$(whoami)}" +TARGET_HOME=$(getent passwd "$TARGET_USER" | cut -d: -f6) +export PATH="${TARGET_HOME}/.cargo/bin:${TARGET_HOME}/.bun/bin:/usr/local/bin:/usr/bin:$PATH" + +PROJECT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +REPO_DIR="$(cd "${PROJECT_DIR}/.." && pwd)" +cd "${PROJECT_DIR}" + +run_as_user() { + if [ "$(whoami)" = "${TARGET_USER}" ]; then + env PATH="$PATH" "$@" + else + sudo -u "${TARGET_USER}" env PATH="$PATH" "$@" + fi +} + +# Pre-flight internet check: update scripts require active DHCP or Internet Mode +echo "[*] Checking internet connectivity on Pi..." +if ! ping -c 1 -W 2 1.1.1.1 &>/dev/null && ! curl -s --connect-timeout 2 https://bun.sh &>/dev/null; then + echo "Error: No active internet connection detected on Pi." >&2 + echo "Updates and builds must be performed in DHCP or Internet Mode (not offline Field Mode)." >&2 + echo "If currently in Field Mode, switch to internet mode first: ~/speedcamera/headless-rust/scripts/setup-network.sh internet " >&2 + echo "or connect an Ethernet cable and run: ~/speedcamera/headless-rust/scripts/setup-network.sh dhcp" >&2 + exit 1 +fi + +# Optional git pull if requested +if [ "$DO_PULL" = true ] && [ -d "${REPO_DIR}/.git" ]; then + echo "[*] Pulling latest git commits in ${REPO_DIR}..." + cd "${REPO_DIR}" + run_as_user git pull + cd "${PROJECT_DIR}" +fi + +# Request sudo credentials upfront so service operations don't block later +echo "[*] Requesting sudo credentials on Pi..." +sudo -v || { echo "Error: Sudo privileges required to configure services." >&2; exit 1; } + +# Locate tool binaries +BUN_BIN=$(command -v bun || echo "${TARGET_HOME}/.bun/bin/bun") +CARGO_BIN=$(command -v cargo || echo "${TARGET_HOME}/.cargo/bin/cargo") + +# 1. Check if frontend rebuild is needed +NEEDS_FRONTEND_BUILD=false +if [ "$FORCE_BUILD" = true ] || [ ! -f "dist/index.html" ]; then + NEEDS_FRONTEND_BUILD=true +elif [ -d "frontend" ] && [ $(find frontend index.html vite.config.ts package.json tailwind.config.js tsconfig.json components.json -newer "dist/index.html" 2>/dev/null | wc -l) -gt 0 ]; then + NEEDS_FRONTEND_BUILD=true +fi + +if [ "$NEEDS_FRONTEND_BUILD" = true ]; then + echo "[*] Frontend changes detected. Building frontend with Bun on Pi..." + if [ ! -x "${BUN_BIN}" ] && ! command -v bun &>/dev/null; then + echo ">>> Installing Bun runtime for ARM64..." + run_as_user bash -c "curl -fsSL https://bun.sh/install | bash" + BUN_BIN="${TARGET_HOME}/.bun/bin/bun" + fi + + if [ ! -d "node_modules" ] || [ "package.json" -nt "node_modules" ]; then + echo ">>> Installing/updating frontend dependencies with Bun..." + run_as_user "${BUN_BIN}" install + fi + + echo ">>> Compiling frontend bundle..." + run_as_user "${BUN_BIN}" run build +else + echo "[*] Frontend bundle is up to date." +fi + +# 2. Check if Rust binary rebuild is needed +NEEDS_RUST_BUILD=false +if [ "$FORCE_BUILD" = true ] || [ ! -f "target/release/headless-rust" ] || [ "$NEEDS_FRONTEND_BUILD" = true ]; then + NEEDS_RUST_BUILD=true +elif [ -d "src" ] && [ $(find src Cargo.toml Cargo.lock build.rs dist -newer "target/release/headless-rust" 2>/dev/null | wc -l) -gt 0 ]; then + NEEDS_RUST_BUILD=true +fi + +if [ "$NEEDS_RUST_BUILD" = true ]; then + echo "[*] Building native release binary with Cargo on Pi..." + if [ ! -x "${CARGO_BIN}" ] && ! command -v cargo &>/dev/null; then + echo ">>> Installing Rust toolchain via rustup..." + run_as_user bash -c "curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile default" + CARGO_BIN="${TARGET_HOME}/.cargo/bin/cargo" + fi + + run_as_user "${CARGO_BIN}" build --release +else + echo "[*] Release binary is up to date." +fi + +# 3. Ensure systemd service exists and is up to date +SERVICE_FILE="/etc/systemd/system/speedcamera.service" + +if [ ! -f "$SERVICE_FILE" ]; then + echo "[*] Creating systemd service file..." + sudo bash -c "cat > ${SERVICE_FILE}" << SERVICE_EOF +[Unit] +Description=Speedcamera Native Rust Daemon & Web Server +After=network.target network-online.target +Wants=network-online.target + +[Service] +Type=simple +User=${TARGET_USER} +WorkingDirectory=${PROJECT_DIR} +Environment=PORT=3000 +Environment=HOST=0.0.0.0 +Environment=DATA_DIR=${TARGET_HOME}/.speedcamera +Environment=PATH=${TARGET_HOME}/.cargo/bin:${TARGET_HOME}/.bun/bin:/usr/local/bin:/usr/bin:/bin +ExecStart=${PROJECT_DIR}/target/release/headless-rust +Restart=always +RestartSec=2 +KillSignal=SIGINT +LimitNOFILE=65536 +LimitMEMLOCK=infinity +AmbientCapabilities=CAP_NET_RAW CAP_NET_ADMIN +CapabilityBoundingSet=CAP_NET_RAW CAP_NET_ADMIN + +[Install] +WantedBy=multi-user.target +SERVICE_EOF + sudo systemctl daemon-reload + sudo systemctl enable speedcamera.service +fi + +# Ensure WiFi power management disable service is active +if [ -f "${PROJECT_DIR}/scripts/wifi-power-off.service" ]; then + sudo cp "${PROJECT_DIR}/scripts/wifi-power-off.service" /etc/systemd/system/wifi-power-off.service 2>/dev/null || true + sudo systemctl daemon-reload + sudo systemctl enable wifi-power-off.service 2>/dev/null || true + sudo systemctl restart wifi-power-off.service 2>/dev/null || true +fi + +echo "[*] Restarting speedcamera service on Pi..." +sudo systemctl daemon-reload +sudo systemctl restart speedcamera.service +sleep 1 +sudo systemctl status speedcamera --no-pager diff --git a/headless-rust/scripts/verify-ws.ts b/headless-rust/scripts/verify-ws.ts new file mode 100755 index 0000000..2776fdf --- /dev/null +++ b/headless-rust/scripts/verify-ws.ts @@ -0,0 +1,57 @@ +#!/usr/bin/env bun +import { io } from "socket.io-client"; + +console.log("Connecting to Socket.io on http://127.0.0.1:3000 ..."); +const socket = io("http://127.0.0.1:3000", { + transports: ["websocket", "polling"], + timeout: 5000, +}); + +let receivedCameraPush = false; +let receivedSettingsResponse = false; +let receivedViolationsResponse = false; + +socket.on("connect", async () => { + console.log("[Socket.io] Connected to Speedcamera Headless Rust Daemon! Socket ID:", socket.id); + + try { + // 1. Request getSettings + const settingsResp: any = await socket.timeout(3000).emitWithAck("rpc", { method: "getSettings", params: {} }); + if (settingsResp.result && typeof settingsResp.result.maxSpeed === "number") { + receivedSettingsResponse = true; + console.log("-> RPC 'getSettings' verified! Max speed:", settingsResp.result.maxSpeed); + } + + // 2. Request getViolations + const violationsResp: any = await socket.timeout(3000).emitWithAck("rpc", { method: "getViolations", params: { page: 1, limit: 10 } }); + if (violationsResp.result && Array.isArray(violationsResp.result.violations)) { + receivedViolationsResponse = true; + console.log("-> RPC 'getViolations' verified! Total violations:", violationsResp.result.total); + } + + if (receivedSettingsResponse && receivedViolationsResponse) { + console.log("\n>>> ALL SOCKET.IO RPC CHECKS PASSED PERFECTLY! <<<"); + socket.disconnect(); + process.exit(0); + } + } catch (err) { + console.error("RPC error:", err); + socket.disconnect(); + process.exit(1); + } +}); + +socket.on("cameraStatus", (status) => { + receivedCameraPush = true; + console.log("-> Push message 'cameraStatus' verified:", status); +}); + +socket.on("connect_error", (err) => { + console.error("Socket.io error:", err.message); + process.exit(1); +}); + +setTimeout(() => { + console.error("Test timeout after 5s"); + process.exit(1); +}, 5000); diff --git a/headless-rust/scripts/wifi-power-off.service b/headless-rust/scripts/wifi-power-off.service new file mode 100644 index 0000000..770c3ec --- /dev/null +++ b/headless-rust/scripts/wifi-power-off.service @@ -0,0 +1,11 @@ +[Unit] +Description=Disable WiFi Power Management +After=network.target + +[Service] +Type=oneshot +ExecStart=/sbin/iwconfig wlan0 power off +RemainAfterExit=yes + +[Install] +WantedBy=multi-user.target diff --git a/headless-rust/src/camera/ffi.rs b/headless-rust/src/camera/ffi.rs new file mode 100644 index 0000000..9b5fd3f --- /dev/null +++ b/headless-rust/src/camera/ffi.rs @@ -0,0 +1,239 @@ +#![allow(dead_code)] + +use std::ffi::{c_char, c_void}; + +pub enum ArvCamera {} +pub enum ArvDevice {} +pub enum ArvStream {} +pub enum ArvBuffer {} + +#[repr(C)] +pub struct GError { + pub domain: u32, + pub code: i32, + pub message: *const c_char, +} + +// ─── ArvBufferStatus Constants ──────────────────────────────────────────────── +pub const ARV_BUFFER_STATUS_SUCCESS: i32 = 0; +pub const ARV_BUFFER_STATUS_CLEARED: i32 = 1; +pub const ARV_BUFFER_STATUS_TIMEOUT: i32 = 2; +pub const ARV_BUFFER_STATUS_MISSING_PACKETS: i32 = 3; +pub const ARV_BUFFER_STATUS_WRONG_PACKET_ID: i32 = 4; +pub const ARV_BUFFER_STATUS_SIZE_MISMATCH: i32 = 5; +pub const ARV_BUFFER_STATUS_FILLING: i32 = 6; +pub const ARV_BUFFER_STATUS_ABORTED: i32 = 7; + +pub fn buffer_status_name(status: i32) -> &'static str { + match status { + ARV_BUFFER_STATUS_SUCCESS => "SUCCESS", + ARV_BUFFER_STATUS_CLEARED => "CLEARED", + ARV_BUFFER_STATUS_TIMEOUT => "TIMEOUT", + ARV_BUFFER_STATUS_MISSING_PACKETS => "MISSING_PACKETS", + ARV_BUFFER_STATUS_WRONG_PACKET_ID => "WRONG_PACKET_ID", + ARV_BUFFER_STATUS_SIZE_MISMATCH => "SIZE_MISMATCH", + ARV_BUFFER_STATUS_FILLING => "FILLING", + ARV_BUFFER_STATUS_ABORTED => "ABORTED", + _ => "UNKNOWN", + } +} + +// ─── GenICam PFNC Pixel Formats ─────────────────────────────────────────────── +pub const ARV_PIXEL_FORMAT_MONO_8: u32 = 0x01080001; +pub const ARV_PIXEL_FORMAT_MONO_10: u32 = 0x01100003; +pub const ARV_PIXEL_FORMAT_MONO_12: u32 = 0x01100005; +pub const ARV_PIXEL_FORMAT_MONO_14: u32 = 0x01100025; +pub const ARV_PIXEL_FORMAT_MONO_16: u32 = 0x01100007; + +pub const ARV_PIXEL_FORMAT_BAYER_GR_8: u32 = 0x01080008; +pub const ARV_PIXEL_FORMAT_BAYER_RG_8: u32 = 0x01080009; +pub const ARV_PIXEL_FORMAT_BAYER_GB_8: u32 = 0x0108000a; +pub const ARV_PIXEL_FORMAT_BAYER_BG_8: u32 = 0x0108000b; + +pub const ARV_PIXEL_FORMAT_BAYER_GR_12: u32 = 0x01100010; +pub const ARV_PIXEL_FORMAT_BAYER_RG_12: u32 = 0x01100011; +pub const ARV_PIXEL_FORMAT_BAYER_GB_12: u32 = 0x01100012; +pub const ARV_PIXEL_FORMAT_BAYER_BG_12: u32 = 0x01100013; + +pub const ARV_PIXEL_FORMAT_RGB_8_PACKED: u32 = 0x02180014; +pub const ARV_PIXEL_FORMAT_BGR_8_PACKED: u32 = 0x02180015; +pub const ARV_PIXEL_FORMAT_YUV_422_PACKED: u32 = 0x02100032; + +pub fn pixel_format_name(format: u32) -> &'static str { + match format { + ARV_PIXEL_FORMAT_MONO_8 => "Mono8", + ARV_PIXEL_FORMAT_MONO_10 => "Mono10", + ARV_PIXEL_FORMAT_MONO_12 => "Mono12", + ARV_PIXEL_FORMAT_MONO_14 => "Mono14", + ARV_PIXEL_FORMAT_MONO_16 => "Mono16", + ARV_PIXEL_FORMAT_BAYER_GR_8 => "BayerGR8", + ARV_PIXEL_FORMAT_BAYER_RG_8 => "BayerRG8", + ARV_PIXEL_FORMAT_BAYER_GB_8 => "BayerGB8", + ARV_PIXEL_FORMAT_BAYER_BG_8 => "BayerBG8", + ARV_PIXEL_FORMAT_BAYER_GR_12 => "BayerGR12", + ARV_PIXEL_FORMAT_BAYER_RG_12 => "BayerRG12", + ARV_PIXEL_FORMAT_BAYER_GB_12 => "BayerGB12", + ARV_PIXEL_FORMAT_BAYER_BG_12 => "BayerBG12", + ARV_PIXEL_FORMAT_RGB_8_PACKED => "RGB8Packed", + ARV_PIXEL_FORMAT_BGR_8_PACKED => "BGR8Packed", + ARV_PIXEL_FORMAT_YUV_422_PACKED => "YUV422Packed", + _ => "UnknownPixelFormat", + } +} + +// ─── Aravis C Functions ─────────────────────────────────────────────────────── +unsafe extern "C" { + pub fn arv_update_device_list(); + pub fn arv_get_n_devices() -> u32; + pub fn arv_get_device_id(index: u32) -> *const c_char; + pub fn arv_get_device_vendor(index: u32) -> *const c_char; + pub fn arv_get_device_model(index: u32) -> *const c_char; + pub fn arv_get_device_serial_nbr(index: u32) -> *const c_char; + pub fn arv_get_device_address(index: u32) -> *const c_char; + + // ----- ArvCamera: construction & info ----- + pub fn arv_camera_new(name: *const c_char, err: *mut *mut GError) -> *mut ArvCamera; + pub fn arv_camera_get_vendor_name(cam: *mut ArvCamera, err: *mut *mut GError) -> *const c_char; + pub fn arv_camera_get_model_name(cam: *mut ArvCamera, err: *mut *mut GError) -> *const c_char; + pub fn arv_camera_get_device_id(cam: *mut ArvCamera, err: *mut *mut GError) -> *const c_char; + pub fn arv_camera_get_device(cam: *mut ArvCamera) -> *mut ArvDevice; + + pub fn arv_camera_is_feature_available( + cam: *mut ArvCamera, + feature: *const c_char, + err: *mut *mut GError, + ) -> i32; + pub fn arv_camera_execute_command( + cam: *mut ArvCamera, + feature: *const c_char, + err: *mut *mut GError, + ); + + // ----- ArvCamera: exposure, gain, framerate, format, payload ----- + pub fn arv_camera_set_exposure_time(cam: *mut ArvCamera, us: f64, err: *mut *mut GError); + pub fn arv_camera_get_exposure_time(cam: *mut ArvCamera, err: *mut *mut GError) -> f64; + pub fn arv_camera_set_gain(cam: *mut ArvCamera, gain: f64, err: *mut *mut GError); + pub fn arv_camera_get_gain(cam: *mut ArvCamera, err: *mut *mut GError) -> f64; + pub fn arv_camera_set_frame_rate(cam: *mut ArvCamera, fps: f64, err: *mut *mut GError); + pub fn arv_camera_get_frame_rate(cam: *mut ArvCamera, err: *mut *mut GError) -> f64; + // NOTE: arv_camera_set_frame_rate_enable does NOT exist in the Aravis C API. + // Use arv_device_set_boolean_feature_value(dev, "AcquisitionFrameRateEnable", ...) instead. + pub fn arv_camera_set_pixel_format(cam: *mut ArvCamera, format: u32, err: *mut *mut GError); + pub fn arv_camera_set_pixel_format_from_string(cam: *mut ArvCamera, format: *const c_char, err: *mut *mut GError); + pub fn arv_camera_get_pixel_format(cam: *mut ArvCamera, err: *mut *mut GError) -> u32; + pub fn arv_camera_get_payload(cam: *mut ArvCamera, err: *mut *mut GError) -> u32; + + // ----- ArvCamera: Trigger control ----- + pub fn arv_camera_set_trigger(cam: *mut ArvCamera, source: *const c_char, err: *mut *mut GError); + pub fn arv_camera_set_trigger_source(cam: *mut ArvCamera, source: *const c_char, err: *mut *mut GError); + pub fn arv_camera_clear_triggers(cam: *mut ArvCamera, err: *mut *mut GError); + pub fn arv_camera_software_trigger(cam: *mut ArvCamera, err: *mut *mut GError); + pub fn arv_camera_is_software_trigger_supported(cam: *mut ArvCamera, err: *mut *mut GError) -> i32; + pub fn arv_camera_is_enumeration_entry_available( + cam: *mut ArvCamera, + feature: *const c_char, + entry: *const c_char, + err: *mut *mut GError, + ) -> i32; + + // ----- ArvDevice: generic GenICam feature access ----- + pub fn arv_device_set_string_feature_value( + device: *mut ArvDevice, + feature: *const c_char, + value: *const c_char, + err: *mut *mut GError, + ); + pub fn arv_device_get_string_feature_value( + device: *mut ArvDevice, + feature: *const c_char, + err: *mut *mut GError, + ) -> *const c_char; + + pub fn arv_device_set_integer_feature_value( + device: *mut ArvDevice, + feature: *const c_char, + value: i64, + err: *mut *mut GError, + ); + pub fn arv_device_get_integer_feature_value( + device: *mut ArvDevice, + feature: *const c_char, + err: *mut *mut GError, + ) -> i64; + + pub fn arv_device_set_float_feature_value( + device: *mut ArvDevice, + feature: *const c_char, + value: f64, + err: *mut *mut GError, + ); + pub fn arv_device_get_float_feature_value( + device: *mut ArvDevice, + feature: *const c_char, + err: *mut *mut GError, + ) -> f64; + + pub fn arv_device_set_boolean_feature_value( + device: *mut ArvDevice, + feature: *const c_char, + value: i32, + err: *mut *mut GError, + ); + pub fn arv_device_get_boolean_feature_value( + device: *mut ArvDevice, + feature: *const c_char, + err: *mut *mut GError, + ) -> i32; + + pub fn arv_device_set_features_from_string( + device: *mut ArvDevice, + string: *const c_char, + err: *mut *mut GError, + ) -> i32; + + // ----- GigE Vision specifics ----- + pub fn arv_camera_is_gv_device(cam: *mut ArvCamera) -> i32; + pub fn arv_camera_gv_auto_packet_size(cam: *mut ArvCamera, err: *mut *mut GError) -> u32; + pub fn arv_camera_gv_set_packet_size( + cam: *mut ArvCamera, + packet_size: i32, + err: *mut *mut GError, + ); + pub fn arv_camera_gv_get_packet_size(cam: *mut ArvCamera, err: *mut *mut GError) -> i32; + pub fn arv_camera_gv_set_packet_delay( + cam: *mut ArvCamera, + packet_delay: i64, + err: *mut *mut GError, + ); + + // ----- Stream & Acquisition ----- + pub fn arv_camera_create_stream( + cam: *mut ArvCamera, + callback: *const c_void, + user_data: *const c_void, + err: *mut *mut GError, + ) -> *mut ArvStream; + + pub fn arv_camera_start_acquisition(cam: *mut ArvCamera, err: *mut *mut GError); + pub fn arv_camera_stop_acquisition(cam: *mut ArvCamera, err: *mut *mut GError); + + pub fn arv_stream_push_buffer(stream: *mut ArvStream, buffer: *mut ArvBuffer); + pub fn arv_stream_try_pop_buffer(stream: *mut ArvStream) -> *mut ArvBuffer; + pub fn arv_stream_timeout_pop_buffer(stream: *mut ArvStream, timeout_us: u64) -> *mut ArvBuffer; + pub fn arv_stream_get_statistics( + stream: *mut ArvStream, + n_completed_buffers: *mut u64, + n_failures: *mut u64, + n_underruns: *mut u64, + ); + + pub fn arv_buffer_new_allocate(size: usize) -> *mut ArvBuffer; + pub fn arv_buffer_get_data(buffer: *mut ArvBuffer, size: *mut usize) -> *const u8; + pub fn arv_buffer_get_image_width(buffer: *mut ArvBuffer) -> i32; + pub fn arv_buffer_get_image_height(buffer: *mut ArvBuffer) -> i32; + pub fn arv_buffer_get_image_pixel_format(buffer: *mut ArvBuffer) -> u32; + pub fn arv_buffer_get_status(buffer: *mut ArvBuffer) -> i32; + + pub fn g_object_unref(ptr: *mut c_void); + pub fn g_error_free(ptr: *mut GError); +} diff --git a/headless-rust/src/camera/mock.rs b/headless-rust/src/camera/mock.rs new file mode 100644 index 0000000..64aa962 --- /dev/null +++ b/headless-rust/src/camera/mock.rs @@ -0,0 +1,120 @@ +use crate::models::CameraStatusPayload; +use image::{ImageBuffer, Rgb}; +use std::io::Cursor; + +pub struct MockCamera { + connected: bool, +} + +impl MockCamera { + pub fn new() -> Self { + Self { connected: true } + } + + pub fn status(&self, is_streaming: bool) -> CameraStatusPayload { + CameraStatusPayload { + connected: self.connected, + vendor: if self.connected { + Some("HIKROBOT (MOCK)".to_string()) + } else { + None + }, + model: if self.connected { + Some("MV-CA016-10GM".to_string()) + } else { + None + }, + serial: if self.connected { + Some("MOCK12345678".to_string()) + } else { + None + }, + is_streaming, + } + } + + pub fn connect(&mut self) { + self.connected = true; + } + + pub fn disconnect(&mut self) { + self.connected = false; + } + + #[allow(dead_code)] + pub fn capture_frame(&self) -> Option> { + if !self.connected { + return None; + } + + // Generate synthetic 1280x1024 image with timestamp + let width = 1280u32; + let height = 1024u32; + let mut img: ImageBuffer, Vec> = ImageBuffer::new(width, height); + + let t = (chrono::Utc::now().timestamp_millis() % 255) as u8; + for (x, y, pixel) in img.enumerate_pixels_mut() { + let r = ((x * 255 / width) as u8).wrapping_add(t); + let g = (y * 255 / height) as u8; + let b = 128u8; + *pixel = Rgb([r, g, b]); + } + + let mut buf = Vec::new(); + let mut cursor = Cursor::new(&mut buf); + img.write_to(&mut cursor, image::ImageFormat::Png).ok()?; + + Some(buf) + } + + pub fn capture_jpeg_frame(&self) -> Option> { + if !self.connected { + return None; + } + + let width = 1280u32; + let height = 1024u32; + let mut img: ImageBuffer, Vec> = ImageBuffer::new(width, height); + + let t = (chrono::Utc::now().timestamp_millis() % 255) as u8; + for (x, y, pixel) in img.enumerate_pixels_mut() { + let r = ((x * 255 / width) as u8).wrapping_add(t); + let g = (y * 255 / height) as u8; + let b = 128u8; + *pixel = Rgb([r, g, b]); + } + + let mut buf = Vec::new(); + let mut cursor = Cursor::new(&mut buf); + let mut encoder = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut cursor, 90); + encoder.encode(img.as_raw(), width, height, image::ExtendedColorType::Rgb8).ok()?; + + Some(buf) + } + + pub fn capture_jpeg_preview(&self) -> Option> { + if !self.connected { + return None; + } + + let width = 800u32; + let height = 600u32; + let mut img: ImageBuffer, Vec> = ImageBuffer::new(width, height); + + let t = (chrono::Utc::now().timestamp_millis() % 255) as u8; + for (x, y, pixel) in img.enumerate_pixels_mut() { + let r = ((x * 255 / width) as u8).wrapping_add(t); + let g = (y * 255 / height) as u8; + let b = 100u8; + *pixel = Rgb([r, g, b]); + } + + let mut buf = Vec::new(); + let mut cursor = Cursor::new(&mut buf); + let mut encoder = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut cursor, 60); + encoder.encode(img.as_raw(), width, height, image::ExtendedColorType::Rgb8).ok()?; + + Some(buf) + } +} + diff --git a/headless-rust/src/camera/mod.rs b/headless-rust/src/camera/mod.rs new file mode 100644 index 0000000..dba72ab --- /dev/null +++ b/headless-rust/src/camera/mod.rs @@ -0,0 +1,1691 @@ +pub mod ffi; +pub mod mock; + +use crate::models::{AppSettings, CameraStatusPayload, MfsConfigResult}; +use base64::Engine; +use ffi::*; +use image::{DynamicImage, ImageBuffer, Luma, Rgb}; +use std::ffi::{CStr, CString}; +use std::io::Cursor; +use std::ptr::null_mut; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; +use tokio::sync::broadcast; + +pub struct CameraService { + mock_mode: bool, + mock_camera: Mutex, + camera_ptr: Mutex<*mut ArvCamera>, + stream_ptr: Mutex<*mut ArvStream>, + is_connected: AtomicBool, + setup_stream_active: Arc, + status_sender: broadcast::Sender, + frame_sender: broadcast::Sender, // Base64 JPEG frames for preview +} + +// Safety: Aravis C library calls are synchronized via internal Mutexes +unsafe impl Send for CameraService {} +unsafe impl Sync for CameraService {} + +impl CameraService { + pub fn new(mock_mode: bool) -> Arc { + let (status_tx, _) = broadcast::channel(16); + let (frame_tx, _) = broadcast::channel(32); + + let service = Arc::new(Self { + mock_mode, + mock_camera: Mutex::new(mock::MockCamera::new()), + camera_ptr: Mutex::new(null_mut()), + stream_ptr: Mutex::new(null_mut()), + is_connected: AtomicBool::new(false), + setup_stream_active: Arc::new(AtomicBool::new(false)), + status_sender: status_tx, + frame_sender: frame_tx, + }); + + if !mock_mode { + // Auto connect if hardware is attached + let svc = service.clone(); + std::thread::spawn(move || { + let default_settings = AppSettings::default(); + svc.connect(&default_settings); + }); + } + + service + } + + pub fn subscribe_status(&self) -> broadcast::Receiver { + self.status_sender.subscribe() + } + + pub fn subscribe_frames(&self) -> broadcast::Receiver { + self.frame_sender.subscribe() + } + + pub fn get_status(&self) -> CameraStatusPayload { + let is_streaming = self.setup_stream_active.load(Ordering::SeqCst); + if self.mock_mode { + return self.mock_camera.lock().unwrap().status(is_streaming); + } + + let is_conn = self.is_connected.load(Ordering::SeqCst); + let cam_guard = self.camera_ptr.lock().unwrap(); + let cam = *cam_guard; + + if is_conn && !cam.is_null() { + unsafe { + let mut err = null_mut(); + let vendor_ptr = arv_camera_get_vendor_name(cam, &mut err); + let model_ptr = arv_camera_get_model_name(cam, &mut err); + let id_ptr = arv_camera_get_device_id(cam, &mut err); + + let vendor = if !vendor_ptr.is_null() { + Some(CStr::from_ptr(vendor_ptr).to_string_lossy().to_string()) + } else { + None + }; + let model = if !model_ptr.is_null() { + Some(CStr::from_ptr(model_ptr).to_string_lossy().to_string()) + } else { + None + }; + let serial = if !id_ptr.is_null() { + Some(CStr::from_ptr(id_ptr).to_string_lossy().to_string()) + } else { + None + }; + + CameraStatusPayload { + connected: true, + vendor, + model, + serial, + is_streaming, + } + } + } else { + CameraStatusPayload { + connected: false, + vendor: None, + model: None, + serial: None, + is_streaming: false, + } + } + } + + pub fn connect(&self, settings: &AppSettings) { + if self.mock_mode { + self.mock_camera.lock().unwrap().connect(); + let _ = self.status_sender.send(self.get_status()); + return; + } + + if self.is_connected.load(Ordering::SeqCst) { + return; + } + + unsafe { + arv_update_device_list(); + let n = arv_get_n_devices(); + if n == 0 { + tracing::info!("[camera] No GigE Vision cameras detected on network"); + return; + } + + let mut target_id = None; + for i in 0..n { + let v_ptr = arv_get_device_vendor(i); + let id_ptr = arv_get_device_id(i); + if !v_ptr.is_null() && !id_ptr.is_null() { + let v = CStr::from_ptr(v_ptr).to_string_lossy(); + let id = CStr::from_ptr(id_ptr).to_string_lossy(); + tracing::info!("[camera] Found device [{}]: {} ({})", i, v, id); + if v.to_lowercase().contains("hikrobot") || target_id.is_none() { + target_id = Some(id.to_string()); + } + } + } + + let mut err = null_mut(); + let cam_name = target_id.as_deref().and_then(|s| CString::new(s).ok()); + let cam_cstr = cam_name.as_ref().map(|s| s.as_ptr()).unwrap_or(null_mut()); + + let cam = arv_camera_new(cam_cstr, &mut err); + if cam.is_null() { + if !err.is_null() { + let msg = CStr::from_ptr((*err).message).to_string_lossy(); + tracing::info!("[camera] Failed to open camera: {}", msg); + g_error_free(err); + } + return; + } + + // Configure packet size & delay if GigE Vision device + if arv_camera_is_gv_device(cam) != 0 { + let packet_size = arv_camera_gv_auto_packet_size(cam, &mut err); + if !err.is_null() { + g_error_free(err); + } else { + tracing::info!("[camera] GigE Vision auto packet size set to: {} bytes", packet_size); + } + + // Set GevSCPD (Stream Channel Packet Delay) to space out UDP packets. + // 2000 ticks caused NIC packet storms on the Pi 5 (SSH/journald stalls, + // softirq starvation on the shared SoC). 20000 ticks still allows + // ~10 FPS preview at full resolution with jumbo frames, while leaving + // headroom for the Wi-Fi hotspot and system responsiveness. + // Override via GEV_SCPD env var if tuning is needed in the field. + let scpd: i64 = std::env::var("GEV_SCPD") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(20000); + let mut delay_err = null_mut(); + arv_camera_gv_set_packet_delay(cam, scpd, &mut delay_err); + if !delay_err.is_null() { + g_error_free(delay_err); + Self::set_feature_int_internal(cam, "GevSCPD", scpd); + } + tracing::info!("[camera] GigE Vision GevSCPD packet delay set to: {}", scpd); + } + + // Set PixelFormat + Self::set_pixel_format_internal(cam, &settings.pixel_format); + + // ── ROI (Width/Height must be set before payload calculation) ───── + if settings.camera_width > 0 { + Self::set_feature_int_internal(cam, "Width", settings.camera_width); + } + if settings.camera_height > 0 { + Self::set_feature_int_internal(cam, "Height", settings.camera_height); + } + if settings.black_level >= 0.0 { + Self::set_black_level_internal(cam, settings.black_level); + } + + // ── Exposure & Gain (set before trigger so auto-exposure can initialize) ── + Self::set_feature_str_internal(cam, "ExposureAuto", &settings.exposure_auto); + if settings.exposure_auto == "Off" { + Self::set_exposure_internal(cam, settings.camera_exposure); + } + + Self::set_feature_str_internal(cam, "GainAuto", &settings.gain_auto); + if settings.gain_auto == "Off" { + Self::set_gain_internal(cam, settings.camera_gain); + } + + // ── Line & Strobe Flash Configuration ────────────────────────────── + // Configure Line1 strobe wiring. In electronbun this works flawlessly + // and does not strobe permanently as long as TriggerMode is properly set. + Self::configure_strobe_internal(cam, settings); + + // ── Trigger Mode & Acquisition ──────────────────────────────────── + if Self::is_feature_available_internal(cam, "AcquisitionMode") { + Self::set_feature_str_internal(cam, "AcquisitionMode", "Continuous"); + } + // Explicitly set burst frame count to 1 (one frame per trigger) + Self::set_feature_int_internal(cam, "AcquisitionBurstFrameCount", 1); + Self::set_trigger_mode_internal(cam, "Software"); + + // ── Frame Rate ───────────────────────────────────── + // Frame rate limit must be disabled in triggered mode. + // Enabling it forces the camera's internal frame generator to run, + // which causes the flash to fire continuously! + Self::set_frame_rate_enable_internal(cam, false); + tracing::info!("[camera] Frame rate limiting disabled (triggered mode)"); + + // Create Stream with 24 pre-allocated buffers for robust throughput without underruns + let stream = arv_camera_create_stream(cam, null_mut(), null_mut(), &mut err); + if stream.is_null() { + tracing::info!("[camera] Failed to create stream"); + g_object_unref(cam as *mut _); + return; + } + + let mut payload_err = null_mut(); + let payload_size = (arv_camera_get_payload(cam, &mut payload_err) as usize) + .max(Self::get_feature_int_internal(cam, "PayloadSize") as usize) + .max(1024 * 1024); + if !payload_err.is_null() { + g_error_free(payload_err); + } + + for _ in 0..24 { + let buf = arv_buffer_new_allocate(payload_size); + arv_stream_push_buffer(stream, buf); + } + + // ── Start Acquisition ───────────────────────────────────────────── + // Critical: Tells camera and Aravis engine to start receiving packets + arv_camera_start_acquisition(cam, &mut err); + if !err.is_null() { + let msg = CStr::from_ptr((*err).message).to_string_lossy(); + tracing::warn!("[camera] arv_camera_start_acquisition returned error: {}", msg); + g_error_free(err); + } + + *self.camera_ptr.lock().unwrap() = cam; + *self.stream_ptr.lock().unwrap() = stream; + self.is_connected.store(true, Ordering::SeqCst); + + tracing::info!("[camera] Connected and acquisition started successfully"); + let _ = self.status_sender.send(self.get_status()); + } + } + + pub fn disconnect(&self) { + if self.mock_mode { + self.mock_camera.lock().unwrap().disconnect(); + let _ = self.status_sender.send(self.get_status()); + return; + } + + self.setup_stream_active.store(false, Ordering::SeqCst); + self.is_connected.store(false, Ordering::SeqCst); + + unsafe { + let mut cam_guard = self.camera_ptr.lock().unwrap(); + let cam = *cam_guard; + + if !cam.is_null() { + let mut err = null_mut(); + arv_camera_stop_acquisition(cam, &mut err); + if !err.is_null() { + g_error_free(err); + } + } + + let mut stream_guard = self.stream_ptr.lock().unwrap(); + if !stream_guard.is_null() { + g_object_unref(*stream_guard as *mut _); + *stream_guard = null_mut(); + } + + if !cam.is_null() { + g_object_unref(cam as *mut _); + *cam_guard = null_mut(); + } + } + + tracing::info!("[camera] Disconnected"); + let _ = self.status_sender.send(self.get_status()); + } + + #[allow(dead_code)] + pub fn capture_frame(&self) -> Option> { + self.capture_frame_jpeg(90) + } + + + pub fn capture_frame_jpeg(&self, quality: u8) -> Option> { + if self.mock_mode { + return self.mock_camera.lock().unwrap().capture_jpeg_frame(); + } + + if !self.is_connected.load(Ordering::SeqCst) { + return None; + } + + // Grab buffer & raw pixel data with minimal mutex holding time + let (raw_vec, width, height, pixel_format) = { + let cam = *self.camera_ptr.lock().unwrap(); + let stream = *self.stream_ptr.lock().unwrap(); + if cam.is_null() || stream.is_null() { + return None; + } + + unsafe { + // Flush any stale buffers lingering in stream output queue + loop { + let stale = arv_stream_try_pop_buffer(stream); + if stale.is_null() { + break; + } + arv_stream_push_buffer(stream, stale); + } + + // Software trigger + Self::fire_software_trigger_internal(cam); + + // Wait up to 2.0 seconds for completed frame + let buffer = arv_stream_timeout_pop_buffer(stream, 2_000_000); + + if buffer.is_null() { + tracing::warn!("[camera] Capture frame timed out"); + return None; + } + + let status = arv_buffer_get_status(buffer); + if status != ARV_BUFFER_STATUS_SUCCESS { + tracing::info!( + "[camera] Capture buffer failed with status: {} ({})", + buffer_status_name(status), + status + ); + arv_stream_push_buffer(stream, buffer); + return None; + } + + let width = arv_buffer_get_image_width(buffer) as u32; + let height = arv_buffer_get_image_height(buffer) as u32; + let pixel_format = arv_buffer_get_image_pixel_format(buffer); + let mut size: usize = 0; + let data_ptr = arv_buffer_get_data(buffer, &mut size); + + let raw_vec = std::slice::from_raw_parts(data_ptr, size).to_vec(); + + // Recycle buffer immediately back to stream pool + arv_stream_push_buffer(stream, buffer); + + (raw_vec, width, height, pixel_format) + } + }; // Mutex on camera_ptr and stream_ptr is released immediately here! + + // Perform fast JPEG conversion outside of camera mutex lock (<10ms) + Self::raw_buffer_to_jpeg(&raw_vec, width, height, pixel_format, quality) + } + + pub fn start_setup_stream(self: &Arc) { + if self.setup_stream_active.load(Ordering::SeqCst) { + return; + } + + self.setup_stream_active.store(true, Ordering::SeqCst); + let _ = self.status_sender.send(self.get_status()); + let this = self.clone(); + + tokio::task::spawn_blocking(move || { + tracing::info!("[camera] Setup preview stream starting..."); + + if !this.mock_mode { + let cam = *this.camera_ptr.lock().unwrap(); + if !cam.is_null() { + // 1. Stop acquisition before reconfiguring + unsafe { + let mut err = null_mut(); + arv_camera_stop_acquisition(cam, &mut err); + if !err.is_null() { + g_error_free(err); + } + } + + // 2. Flush any pending buffers + Self::flush_stream_buffers(&this); + + // 3. Disable strobe during setup preview + Self::disable_strobe_internal(cam); + + // 4. Switch to free-running mode (disable triggers) + // Must use direct device features — arv_camera_clear_triggers + // uses wrong TriggerSelector for Hikrobot + Self::clear_triggers_internal(cam); + + // 5. Enable auto exposure/gain for preview + Self::set_feature_str_internal(cam, "ExposureAuto", "Continuous"); + Self::set_feature_str_internal(cam, "GainAuto", "Continuous"); + + // 6. Enable frame rate limiting BEFORE setting the rate + Self::set_frame_rate_enable_internal(cam, true); + Self::set_frame_rate_internal(cam, 10.0); + + // 7. Verify frame rate took effect — if not, camera will flood Pi + Self::verify_frame_rate(cam, 10.0); + + // 8. Start acquisition in free-run mode + unsafe { + let mut err = null_mut(); + arv_camera_start_acquisition(cam, &mut err); + if !err.is_null() { + let msg = CStr::from_ptr((*err).message).to_string_lossy(); + tracing::info!("[camera] Error restarting acquisition for setup stream: {}", msg); + g_error_free(err); + } + } + } + } + + tracing::info!("[camera] Setup preview stream active"); + + let is_encoding = Arc::new(AtomicBool::new(false)); + + while this.setup_stream_active.load(Ordering::SeqCst) { + if this.mock_mode { + if let Some(jpeg) = this.mock_camera.lock().unwrap().capture_jpeg_preview() { + let b64 = base64::engine::general_purpose::STANDARD.encode(&jpeg); + let _ = this.frame_sender.send(b64); + } + std::thread::sleep(std::time::Duration::from_millis(80)); + continue; + } + + let stream = *this.stream_ptr.lock().unwrap(); + if stream.is_null() { + std::thread::sleep(std::time::Duration::from_millis(50)); + continue; + } + + unsafe { + let buffer = arv_stream_try_pop_buffer(stream); + if !buffer.is_null() { + let status = arv_buffer_get_status(buffer); + if status == ARV_BUFFER_STATUS_SUCCESS { + // If previous frame is still encoding, drop intermediate frame to keep queue empty + if !is_encoding.swap(true, Ordering::SeqCst) { + let width = arv_buffer_get_image_width(buffer) as u32; + let height = arv_buffer_get_image_height(buffer) as u32; + let pixel_format = arv_buffer_get_image_pixel_format(buffer); + let mut size: usize = 0; + let data_ptr = arv_buffer_get_data(buffer, &mut size); + + let slice_vec = std::slice::from_raw_parts(data_ptr, size).to_vec(); + + // Recycle buffer immediately back to Aravis pool + arv_stream_push_buffer(stream, buffer); + + let encoder_flag = is_encoding.clone(); + let tx = this.frame_sender.clone(); + tokio::task::spawn_blocking(move || { + if let Some(jpeg) = Self::raw_buffer_to_downscaled_jpeg( + &slice_vec, + width, + height, + pixel_format, + ) { + let b64 = base64::engine::general_purpose::STANDARD.encode(&jpeg); + let _ = tx.send(b64); + } + encoder_flag.store(false, Ordering::SeqCst); + }); + } else { + // Encoder busy: recycle buffer instantly to prevent underruns + arv_stream_push_buffer(stream, buffer); + } + } else { + // Status not SUCCESS: recycle buffer back to pool + arv_stream_push_buffer(stream, buffer); + } + } else { + // No buffer ready, brief yield to prevent tight spin + std::thread::sleep(std::time::Duration::from_millis(5)); + } + } + } + + tracing::info!("[camera] Setup preview stream thread exited"); + }); + } + + pub fn stop_setup_stream(&self, settings: &AppSettings) { + if !self.setup_stream_active.swap(false, Ordering::SeqCst) { + return; + } + + // Wait 60ms for stream thread to exit pump loop cleanly + std::thread::sleep(std::time::Duration::from_millis(60)); + + if !self.mock_mode { + let cam = *self.camera_ptr.lock().unwrap(); + if !cam.is_null() { + // 1. Stop acquisition + unsafe { + let mut err = null_mut(); + arv_camera_stop_acquisition(cam, &mut err); + if !err.is_null() { + g_error_free(err); + } + } + + // 2. Flush stream buffers + Self::flush_stream_buffers(self); + + // 3. Restore trigger mode + Self::set_trigger_mode_internal(cam, "Software"); + + // 4. Restore strobe configuration + Self::configure_strobe_internal(cam, settings); + + // 5. Restore exposure & gain + Self::set_feature_str_internal(cam, "ExposureAuto", &settings.exposure_auto); + if settings.exposure_auto == "Off" { + Self::set_exposure_internal(cam, settings.camera_exposure); + } + Self::set_feature_str_internal(cam, "GainAuto", &settings.gain_auto); + if settings.gain_auto == "Off" { + Self::set_gain_internal(cam, settings.camera_gain); + } + + // 6. Disable frame rate limiting in triggered mode + Self::set_frame_rate_enable_internal(cam, false); + + // 7. Restart acquisition in triggered mode + unsafe { + let mut err = null_mut(); + arv_camera_start_acquisition(cam, &mut err); + if !err.is_null() { + g_error_free(err); + } + } + } + } + tracing::info!("[camera] Setup preview stream stopped, restored triggered capture mode"); + let _ = self.status_sender.send(self.get_status()); + } + + pub fn save_user_set(&self, user_set_name: &str, set_as_default: bool) -> bool { + if self.mock_mode { + return true; + } + let cam = *self.camera_ptr.lock().unwrap(); + if cam.is_null() { + return false; + } + Self::set_feature_str_internal(cam, "UserSetSelector", user_set_name); + Self::execute_command_internal(cam, "UserSetSave"); + if set_as_default { + Self::set_feature_str_internal(cam, "UserSetDefault", user_set_name); + } + true + } + + pub fn apply_mfs_config(&self, mfs_content: &str, save_as_default: bool) -> MfsConfigResult { + let mut applied = Vec::new(); + let mut failed = Vec::new(); + + if self.mock_mode { + for line in mfs_content.lines() { + let trimmed = line.trim(); + if !trimmed.is_empty() && !trimmed.starts_with('#') { + applied.push(trimmed.to_string()); + } + } + return MfsConfigResult { applied, failed }; + } + + let cam = *self.camera_ptr.lock().unwrap(); + if cam.is_null() { + return MfsConfigResult { applied, failed }; + } + + let mut pending: Vec<(String, String)> = Vec::new(); + for line in mfs_content.lines() { + let line = line.trim(); + if line.is_empty() || line.starts_with('#') { + continue; + } + + let pair = if let Some((k, v)) = line.split_once('=') { + Some((k.trim().to_string(), v.trim().to_string())) + } else { + let mut parts = line.split_whitespace(); + if let Some(feature) = parts.next() { + let value = parts.collect::>().join(" "); + if !value.is_empty() { + Some((feature.to_string(), value)) + } else { + None + } + } else { + None + } + }; + + if let Some((k, v)) = pair { + pending.push((k, v)); + } + } + + // Multi-pass application (up to 3 passes to resolve GenICam feature dependencies) + for _pass in 0..3 { + let mut failed_this_pass = Vec::new(); + let prev_len = pending.len(); + for (feature, value) in pending { + if Self::set_any_feature_internal(cam, &feature, &value) { + applied.push(format!("{}\t{}", feature, value)); + } else { + failed_this_pass.push((feature, value)); + } + } + + if failed_this_pass.len() == prev_len { + pending = failed_this_pass; + break; + } + + pending = failed_this_pass; + if pending.is_empty() { + break; + } + } + + for (feature, value) in pending { + failed.push(format!("{}\t{}", feature, value)); + } + + if save_as_default { + self.save_user_set("UserSet1", true); + } + + MfsConfigResult { applied, failed } + } + + pub fn set_exposure(&self, val: f64) { + if !self.mock_mode { + let cam = *self.camera_ptr.lock().unwrap(); + if !cam.is_null() { + Self::set_exposure_internal(cam, val); + } + } + } + + pub fn set_gain(&self, val: f64) { + if !self.mock_mode { + let cam = *self.camera_ptr.lock().unwrap(); + if !cam.is_null() { + Self::set_gain_internal(cam, val); + } + } + } + + pub fn set_strobe_duration(&self, val: i64) { + if !self.mock_mode { + let cam = *self.camera_ptr.lock().unwrap(); + if !cam.is_null() { + Self::set_feature_str_internal(cam, "LineSelector", "Line1"); + Self::set_feature_int_internal(cam, "StrobeLineDuration", val); + } + } + } + + pub fn set_pixel_format(&self, format: &str) { + if !self.mock_mode { + let cam = *self.camera_ptr.lock().unwrap(); + if !cam.is_null() { + Self::set_pixel_format_internal(cam, format); + } + } + } + + pub fn set_feature_str(&self, feature: &str, value: &str) -> bool { + if self.mock_mode { + return true; + } + let cam = *self.camera_ptr.lock().unwrap(); + if !cam.is_null() { + Self::set_feature_str_internal(cam, feature, value) + } else { + false + } + } + + pub fn set_feature_int(&self, feature: &str, value: i64) -> bool { + if self.mock_mode { + return true; + } + let cam = *self.camera_ptr.lock().unwrap(); + if !cam.is_null() { + Self::set_feature_int_internal(cam, feature, value) + } else { + false + } + } + + #[allow(dead_code)] + pub fn set_feature_float(&self, feature: &str, value: f64) -> bool { + if self.mock_mode { + return true; + } + let cam = *self.camera_ptr.lock().unwrap(); + if !cam.is_null() { + Self::set_feature_float_internal(cam, feature, value) + } else { + false + } + } + + #[allow(dead_code)] + pub fn set_feature_bool(&self, feature: &str, value: bool) -> bool { + if self.mock_mode { + return true; + } + let cam = *self.camera_ptr.lock().unwrap(); + if !cam.is_null() { + Self::set_feature_bool_internal(cam, feature, value) + } else { + false + } + } + + // ── Pixel Format & Image Decoding ────────────────────────────────────────── + fn raw_to_dynamic_image( + raw: &[u8], + width: u32, + height: u32, + pixel_format: u32, + ) -> Option { + let w = width as usize; + let h = height as usize; + let total_pixels = w * h; + + match pixel_format { + ARV_PIXEL_FORMAT_RGB_8_PACKED => { + if raw.len() >= total_pixels * 3 { + let img: ImageBuffer, Vec> = + ImageBuffer::from_raw(width, height, raw[..total_pixels * 3].to_vec())?; + Some(DynamicImage::ImageRgb8(img)) + } else { + None + } + } + ARV_PIXEL_FORMAT_BGR_8_PACKED => { + if raw.len() >= total_pixels * 3 { + let mut rgb = vec![0u8; total_pixels * 3]; + for i in 0..total_pixels { + rgb[i * 3] = raw[i * 3 + 2]; // R + rgb[i * 3 + 1] = raw[i * 3 + 1]; // G + rgb[i * 3 + 2] = raw[i * 3]; // B + } + let img: ImageBuffer, Vec> = + ImageBuffer::from_raw(width, height, rgb)?; + Some(DynamicImage::ImageRgb8(img)) + } else { + None + } + } + ARV_PIXEL_FORMAT_BAYER_RG_8 + | ARV_PIXEL_FORMAT_BAYER_BG_8 + | ARV_PIXEL_FORMAT_BAYER_GR_8 + | ARV_PIXEL_FORMAT_BAYER_GB_8 => { + let rgb_bytes = Self::debayer_8bit(raw, w, h, pixel_format)?; + let img: ImageBuffer, Vec> = + ImageBuffer::from_raw(width, height, rgb_bytes)?; + Some(DynamicImage::ImageRgb8(img)) + } + ARV_PIXEL_FORMAT_MONO_10 + | ARV_PIXEL_FORMAT_MONO_12 + | ARV_PIXEL_FORMAT_MONO_14 + | ARV_PIXEL_FORMAT_MONO_16 => { + if raw.len() >= total_pixels * 2 { + let mut mono8 = vec![0u8; total_pixels]; + for i in 0..total_pixels { + // Take most significant byte (little endian) + mono8[i] = raw[i * 2 + 1]; + } + let img: ImageBuffer, Vec> = + ImageBuffer::from_raw(width, height, mono8)?; + Some(DynamicImage::ImageLuma8(img)) + } else { + None + } + } + ARV_PIXEL_FORMAT_MONO_8 | _ => { + // Fallback: If 3-channel size, treat as RGB, else Mono + if raw.len() >= total_pixels * 3 { + let img: ImageBuffer, Vec> = + ImageBuffer::from_raw(width, height, raw[..total_pixels * 3].to_vec())?; + Some(DynamicImage::ImageRgb8(img)) + } else if raw.len() >= total_pixels { + let img: ImageBuffer, Vec> = + ImageBuffer::from_raw(width, height, raw[..total_pixels].to_vec())?; + Some(DynamicImage::ImageLuma8(img)) + } else { + None + } + } + } + } + + /// Fast 2x2 bilinear debayering for Bayer raw sensor arrays + fn debayer_8bit(raw: &[u8], width: usize, height: usize, format: u32) -> Option> { + if raw.len() < width * height || width < 2 || height < 2 { + return None; + } + + let mut rgb = vec![0u8; width * height * 3]; + + // Offsets determine sensor pattern at (y%2, x%2) + // RG8: (0,0)=R, (0,1)=G, (1,0)=G, (1,1)=B + // BG8: (0,0)=B, (0,1)=G, (1,0)=G, (1,1)=R + // GR8: (0,0)=G, (0,1)=R, (1,0)=B, (1,1)=G + // GB8: (0,0)=G, (0,1)=B, (1,0)=R, (1,1)=G + + for y in 0..height { + let y_prev = if y > 0 { y - 1 } else { y + 1 }; + let y_next = if y + 1 < height { y + 1 } else { y - 1 }; + + for x in 0..width { + let x_prev = if x > 0 { x - 1 } else { x + 1 }; + let x_next = if x + 1 < width { x + 1 } else { x - 1 }; + + let idx = y * width + x; + let c = raw[idx] as u32; + + let (r, g, b) = match format { + ARV_PIXEL_FORMAT_BAYER_RG_8 => { + match (y % 2, x % 2) { + (0, 0) => { + // Red pixel + let r = c; + let g = (raw[y_prev * width + x] as u32 + + raw[y_next * width + x] as u32 + + raw[y * width + x_prev] as u32 + + raw[y * width + x_next] as u32) + / 4; + let b = (raw[y_prev * width + x_prev] as u32 + + raw[y_prev * width + x_next] as u32 + + raw[y_next * width + x_prev] as u32 + + raw[y_next * width + x_next] as u32) + / 4; + (r, g, b) + } + (0, 1) => { + // Green on Red row + let g = c; + let r = (raw[y * width + x_prev] as u32 + raw[y * width + x_next] as u32) / 2; + let b = (raw[y_prev * width + x] as u32 + raw[y_next * width + x] as u32) / 2; + (r, g, b) + } + (1, 0) => { + // Green on Blue row + let g = c; + let b = (raw[y * width + x_prev] as u32 + raw[y * width + x_next] as u32) / 2; + let r = (raw[y_prev * width + x] as u32 + raw[y_next * width + x] as u32) / 2; + (r, g, b) + } + (1, 1) => { + // Blue pixel + let b = c; + let g = (raw[y_prev * width + x] as u32 + + raw[y_next * width + x] as u32 + + raw[y * width + x_prev] as u32 + + raw[y * width + x_next] as u32) + / 4; + let r = (raw[y_prev * width + x_prev] as u32 + + raw[y_prev * width + x_next] as u32 + + raw[y_next * width + x_prev] as u32 + + raw[y_next * width + x_next] as u32) + / 4; + (r, g, b) + } + _ => unreachable!(), + } + } + ARV_PIXEL_FORMAT_BAYER_BG_8 => { + match (y % 2, x % 2) { + (0, 0) => { + // Blue pixel + let b = c; + let g = (raw[y_prev * width + x] as u32 + + raw[y_next * width + x] as u32 + + raw[y * width + x_prev] as u32 + + raw[y * width + x_next] as u32) + / 4; + let r = (raw[y_prev * width + x_prev] as u32 + + raw[y_prev * width + x_next] as u32 + + raw[y_next * width + x_prev] as u32 + + raw[y_next * width + x_next] as u32) + / 4; + (r, g, b) + } + (0, 1) => { + // Green on Blue row + let g = c; + let b = (raw[y * width + x_prev] as u32 + raw[y * width + x_next] as u32) / 2; + let r = (raw[y_prev * width + x] as u32 + raw[y_next * width + x] as u32) / 2; + (r, g, b) + } + (1, 0) => { + // Green on Red row + let g = c; + let r = (raw[y * width + x_prev] as u32 + raw[y * width + x_next] as u32) / 2; + let b = (raw[y_prev * width + x] as u32 + raw[y_next * width + x] as u32) / 2; + (r, g, b) + } + (1, 1) => { + // Red pixel + let r = c; + let g = (raw[y_prev * width + x] as u32 + + raw[y_next * width + x] as u32 + + raw[y * width + x_prev] as u32 + + raw[y * width + x_next] as u32) + / 4; + let b = (raw[y_prev * width + x_prev] as u32 + + raw[y_prev * width + x_next] as u32 + + raw[y_next * width + x_prev] as u32 + + raw[y_next * width + x_next] as u32) + / 4; + (r, g, b) + } + _ => unreachable!(), + } + } + _ => { + // Default GR8 / GB8 simple interpolation + (c, c, c) + } + }; + + let out_idx = idx * 3; + rgb[out_idx] = r.min(255) as u8; + rgb[out_idx + 1] = g.min(255) as u8; + rgb[out_idx + 2] = b.min(255) as u8; + } + } + + Some(rgb) + } + + #[allow(dead_code)] + fn raw_buffer_to_png( + raw: &[u8], + width: u32, + height: u32, + pixel_format: u32, + ) -> Option> { + let dynamic_img = Self::raw_to_dynamic_image(raw, width, height, pixel_format)?; + let mut buf = Vec::new(); + let mut cursor = Cursor::new(&mut buf); + dynamic_img.write_to(&mut cursor, image::ImageFormat::Png).ok()?; + Some(buf) + } + + fn raw_buffer_to_jpeg( + raw: &[u8], + width: u32, + height: u32, + pixel_format: u32, + quality: u8, + ) -> Option> { + let dynamic_img = Self::raw_to_dynamic_image(raw, width, height, pixel_format)?; + let mut buf = Vec::new(); + let mut cursor = Cursor::new(&mut buf); + let mut encoder = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut cursor, quality); + match dynamic_img { + DynamicImage::ImageRgb8(rgb) => { + encoder.encode(rgb.as_raw(), width, height, image::ExtendedColorType::Rgb8).ok()?; + } + DynamicImage::ImageLuma8(luma) => { + encoder.encode(luma.as_raw(), width, height, image::ExtendedColorType::L8).ok()?; + } + _ => { + let rgb = dynamic_img.to_rgb8(); + encoder.encode(rgb.as_raw(), width, height, image::ExtendedColorType::Rgb8).ok()?; + } + } + Some(buf) + } + + fn raw_buffer_to_downscaled_jpeg( + raw: &[u8], + width: u32, + height: u32, + pixel_format: u32, + ) -> Option> { + let dynamic_img = Self::raw_to_dynamic_image(raw, width, height, pixel_format)?; + let resized = dynamic_img.resize(800, 600, image::imageops::FilterType::Nearest); + + let mut buf = Vec::new(); + let mut cursor = Cursor::new(&mut buf); + let mut encoder = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut cursor, 60); + match resized { + DynamicImage::ImageRgb8(rgb) => { + encoder.encode(rgb.as_raw(), rgb.width(), rgb.height(), image::ExtendedColorType::Rgb8).ok()?; + } + DynamicImage::ImageLuma8(luma) => { + encoder.encode(luma.as_raw(), luma.width(), luma.height(), image::ExtendedColorType::L8).ok()?; + } + _ => { + let rgb = resized.to_rgb8(); + encoder.encode(rgb.as_raw(), rgb.width(), rgb.height(), image::ExtendedColorType::Rgb8).ok()?; + } + } + + Some(buf) + } + + + // ── Shared Helper Functions ──────────────────────────────────────────────── + + /// Configure Line1 as strobe output for flash synchronization. + /// + /// Uses LineSource=ExposureStartActive so the flash fires a single edge + /// pulse at the START of each triggered exposure only. ExposureActive + /// (level signal) must NOT be used — it mirrors all internal sensor + /// exposure activity and causes continuous strobing. + /// StrobeEnable=true with StrobeLineDuration gates the pulse to a fixed + /// duration, matching the verified-working MVS/electronbun configuration. + fn configure_strobe_internal(cam: *mut ArvCamera, _settings: &AppSettings) { + if cam.is_null() { + return; + } + if !Self::is_feature_available_internal(cam, "LineSelector") { + return; + } + Self::set_feature_str_internal(cam, "LineSelector", "Line1"); + Self::set_feature_str_internal(cam, "LineMode", "Strobe"); + + // ExposureStartActive = discrete edge pulse at exposure start (correct) + // ExposureActive = level signal mirroring all sensor activity (causes strobing!) + // FrameStartActive = does not trigger Line1 on MV-CU013-80GC + if Self::is_enumeration_entry_available_internal(cam, "LineSource", "ExposureStartActive") { + Self::set_feature_str_internal(cam, "LineSource", "ExposureStartActive"); + } else if Self::is_enumeration_entry_available_internal(cam, "LineSource", "ExposureActive") { + Self::set_feature_str_internal(cam, "LineSource", "ExposureActive"); + } else if Self::is_enumeration_entry_available_internal(cam, "LineSource", "FrameStartActive") { + Self::set_feature_str_internal(cam, "LineSource", "FrameStartActive"); + } + Self::set_line_inverter_internal(cam, false); + + // Enable the strobe subsystem for controlled pulse generation + if Self::is_feature_available_internal(cam, "StrobeEnable") { + if !Self::set_feature_bool_internal(cam, "StrobeEnable", true) { + Self::set_feature_int_internal(cam, "StrobeEnable", 1); + } + } + Self::set_feature_int_internal(cam, "StrobeLineDuration", 5000); + Self::set_feature_int_internal(cam, "StrobeLineDelay", 0); + Self::set_feature_int_internal(cam, "StrobeLinePreDelay", 0); + tracing::info!("[camera] Strobe configured on Line1 (LineSource=ExposureStartActive, StrobeEnable=true, StrobeLineDuration=5000)"); + } + + /// Disable strobe output during setup preview to prevent flash from firing. + fn disable_strobe_internal(cam: *mut ArvCamera) { + if cam.is_null() { + return; + } + // Disable strobe subsystem so the flash doesn't fire during preview. + Self::set_feature_bool_internal(cam, "StrobeEnable", false); + tracing::info!("[camera] Strobe disabled for preview mode"); + } + + /// Flush all pending buffers from the stream output queue back to the input pool. + fn flush_stream_buffers(&self) { + let stream = *self.stream_ptr.lock().unwrap(); + if stream.is_null() { + return; + } + unsafe { + let mut flushed = 0u32; + loop { + let stale = arv_stream_try_pop_buffer(stream); + if stale.is_null() { + break; + } + arv_stream_push_buffer(stream, stale); + flushed += 1; + } + if flushed > 0 { + tracing::debug!("[camera] Flushed {} stale buffers", flushed); + } + } + } + + /// Read back AcquisitionFrameRate and warn if it doesn't match the target. + fn verify_frame_rate(cam: *mut ArvCamera, target_fps: f64) { + if cam.is_null() { + return; + } + unsafe { + let mut err = null_mut(); + let actual = arv_camera_get_frame_rate(cam, &mut err); + if !err.is_null() { + g_error_free(err); + tracing::warn!("[camera] Could not read back frame rate for verification"); + return; + } + let diff = (actual - target_fps).abs(); + if diff > 1.0 { + tracing::info!( + "[camera] WARNING: Frame rate readback {:.1} FPS differs from target {:.1} FPS — camera may not be respecting frame rate limit!", + actual, target_fps + ); + } else { + tracing::debug!("[camera] Frame rate verified: {:.1} FPS (target: {:.1})", actual, target_fps); + } + } + } + + pub fn is_feature_available_internal(cam: *mut ArvCamera, feature: &str) -> bool { + if cam.is_null() { + return false; + } + unsafe { + let f_cstr = match CString::new(feature) { + Ok(s) => s, + Err(_) => return false, + }; + let mut err = null_mut(); + let res = arv_camera_is_feature_available(cam, f_cstr.as_ptr(), &mut err); + if !err.is_null() { + g_error_free(err); + false + } else { + res != 0 + } + } + } + + pub fn execute_command_internal(cam: *mut ArvCamera, command: &str) -> bool { + if cam.is_null() { + return false; + } + unsafe { + let cmd_cstr = match CString::new(command) { + Ok(s) => s, + Err(_) => return false, + }; + let mut err = null_mut(); + arv_camera_execute_command(cam, cmd_cstr.as_ptr(), &mut err); + if !err.is_null() { + let msg = CStr::from_ptr((*err).message).to_string_lossy(); + tracing::warn!("[camera] execute_command({}) failed: {}", command, msg); + g_error_free(err); + false + } else { + tracing::debug!("[camera] execute_command({}) succeeded", command); + true + } + } + } + + fn set_feature_str_internal(cam: *mut ArvCamera, feature: &str, value: &str) -> bool { + if cam.is_null() { + return false; + } + unsafe { + let dev = arv_camera_get_device(cam); + if dev.is_null() { + return false; + } + let f_cstr = match CString::new(feature) { + Ok(s) => s, + Err(_) => return false, + }; + let v_cstr = match CString::new(value) { + Ok(s) => s, + Err(_) => return false, + }; + let mut err = null_mut(); + arv_device_set_string_feature_value(dev, f_cstr.as_ptr(), v_cstr.as_ptr(), &mut err); + if !err.is_null() { + let msg = CStr::from_ptr((*err).message).to_string_lossy(); + tracing::warn!("[camera] set_feature_str({}, {}) failed: {}", feature, value, msg); + g_error_free(err); + false + } else { + tracing::debug!("[camera] set_feature_str({}, {}) succeeded", feature, value); + true + } + } + } + + fn get_feature_str_internal(cam: *mut ArvCamera, feature: &str) -> Option { + if cam.is_null() { + return None; + } + unsafe { + let dev = arv_camera_get_device(cam); + if dev.is_null() { + return None; + } + let f_cstr = match CString::new(feature) { + Ok(s) => s, + Err(_) => return None, + }; + let mut err = null_mut(); + let res_ptr = arv_device_get_string_feature_value(dev, f_cstr.as_ptr(), &mut err); + if !err.is_null() { + g_error_free(err); + None + } else if !res_ptr.is_null() { + Some(CStr::from_ptr(res_ptr).to_string_lossy().to_string()) + } else { + None + } + } + } + + fn set_feature_int_internal(cam: *mut ArvCamera, feature: &str, value: i64) -> bool { + if cam.is_null() { + return false; + } + unsafe { + let dev = arv_camera_get_device(cam); + if dev.is_null() { + return false; + } + let f_cstr = match CString::new(feature) { + Ok(s) => s, + Err(_) => return false, + }; + let mut err = null_mut(); + arv_device_set_integer_feature_value(dev, f_cstr.as_ptr(), value, &mut err); + if !err.is_null() { + let msg = CStr::from_ptr((*err).message).to_string_lossy(); + tracing::warn!("[camera] set_feature_int({}, {}) failed: {}", feature, value, msg); + g_error_free(err); + false + } else { + tracing::debug!("[camera] set_feature_int({}, {}) succeeded", feature, value); + true + } + } + } + + fn get_feature_int_internal(cam: *mut ArvCamera, feature: &str) -> i64 { + if cam.is_null() { + return 0; + } + unsafe { + let dev = arv_camera_get_device(cam); + if dev.is_null() { + return 0; + } + let f_cstr = match CString::new(feature) { + Ok(s) => s, + Err(_) => return 0, + }; + let mut err = null_mut(); + let res = arv_device_get_integer_feature_value(dev, f_cstr.as_ptr(), &mut err); + if !err.is_null() { + g_error_free(err); + 0 + } else { + res + } + } + } + + fn set_feature_float_internal(cam: *mut ArvCamera, feature: &str, value: f64) -> bool { + if cam.is_null() { + return false; + } + unsafe { + let dev = arv_camera_get_device(cam); + if dev.is_null() { + return false; + } + let f_cstr = match CString::new(feature) { + Ok(s) => s, + Err(_) => return false, + }; + let mut err = null_mut(); + arv_device_set_float_feature_value(dev, f_cstr.as_ptr(), value, &mut err); + if !err.is_null() { + let msg = CStr::from_ptr((*err).message).to_string_lossy(); + tracing::warn!("[camera] set_feature_float({}, {}) failed: {}", feature, value, msg); + g_error_free(err); + false + } else { + tracing::debug!("[camera] set_feature_float({}, {}) succeeded", feature, value); + true + } + } + } + + fn set_feature_bool_internal(cam: *mut ArvCamera, feature: &str, value: bool) -> bool { + if cam.is_null() { + return false; + } + unsafe { + let dev = arv_camera_get_device(cam); + if dev.is_null() { + return false; + } + let f_cstr = match CString::new(feature) { + Ok(s) => s, + Err(_) => return false, + }; + let mut err = null_mut(); + arv_device_set_boolean_feature_value( + dev, + f_cstr.as_ptr(), + if value { 1 } else { 0 }, + &mut err, + ); + if !err.is_null() { + let msg = CStr::from_ptr((*err).message).to_string_lossy(); + tracing::warn!("[camera] set_feature_bool({}, {}) failed: {}", feature, value, msg); + g_error_free(err); + false + } else { + tracing::debug!("[camera] set_feature_bool({}, {}) succeeded", feature, value); + true + } + } + } + + fn set_exposure_internal(cam: *mut ArvCamera, us: f64) -> bool { + if cam.is_null() { + return false; + } + unsafe { + let mut err = null_mut(); + arv_camera_set_exposure_time(cam, us, &mut err); + if !err.is_null() { + let msg = CStr::from_ptr((*err).message).to_string_lossy(); + tracing::warn!("[camera] arv_camera_set_exposure_time({}) failed: {}", us, msg); + g_error_free(err); + false + } else { + tracing::info!("[camera] Set exposure time to {} µs", us); + true + } + } + } + + fn set_gain_internal(cam: *mut ArvCamera, gain: f64) -> bool { + if cam.is_null() { + return false; + } + unsafe { + let mut err = null_mut(); + arv_camera_set_gain(cam, gain, &mut err); + if !err.is_null() { + let msg = CStr::from_ptr((*err).message).to_string_lossy(); + tracing::warn!("[camera] arv_camera_set_gain({}) failed: {}", gain, msg); + g_error_free(err); + false + } else { + tracing::info!("[camera] Set gain to {}", gain); + true + } + } + } + + fn set_frame_rate_internal(cam: *mut ArvCamera, fps: f64) -> bool { + if cam.is_null() { + return false; + } + unsafe { + let mut err = null_mut(); + arv_camera_set_frame_rate(cam, fps, &mut err); + if !err.is_null() { + let msg = CStr::from_ptr((*err).message).to_string_lossy(); + tracing::warn!("[camera] arv_camera_set_frame_rate({}) failed: {}", fps, msg); + g_error_free(err); + false + } else { + tracing::info!("[camera] Set frame rate to {} FPS", fps); + true + } + } + } + + pub fn is_enumeration_entry_available_internal( + cam: *mut ArvCamera, + feature: &str, + entry: &str, + ) -> bool { + if cam.is_null() { + return false; + } + unsafe { + let f_cstr = match CString::new(feature) { + Ok(s) => s, + Err(_) => return false, + }; + let e_cstr = match CString::new(entry) { + Ok(s) => s, + Err(_) => return false, + }; + let mut err = null_mut(); + let res = arv_camera_is_enumeration_entry_available( + cam, + f_cstr.as_ptr(), + e_cstr.as_ptr(), + &mut err, + ); + if !err.is_null() { + g_error_free(err); + false + } else { + res != 0 + } + } + } + + /// Configure triggered capture mode using direct GenICam device features. + /// + /// Matches electronbun behavior: enable trigger on ONE selector only and + /// explicitly disable all others. Enabling multiple selectors (e.g. both + /// FrameStart and FrameBurstStart) makes the camera free-run and strobe + /// the flash continuously. + fn set_trigger_mode_internal(cam: *mut ArvCamera, trigger_source: &str) -> bool { + if cam.is_null() { + return false; + } + + // Pick first available selector, prefer FrameStart (per-frame trigger). + let selectors = ["FrameStart", "FrameBurstStart", "AcquisitionStart"]; + let mut chosen: Option<&str> = None; + for sel in selectors { + if Self::set_feature_str_internal(cam, "TriggerSelector", sel) { + chosen = Some(sel); + break; + } + } + + let Some(active) = chosen else { + tracing::error!("[camera] Failed to select any TriggerSelector"); + return false; + }; + + // Explicitly disable trigger mode on all OTHER selectors first. + for sel in selectors { + if sel != active && Self::set_feature_str_internal(cam, "TriggerSelector", sel) { + let _ = Self::set_feature_str_internal(cam, "TriggerMode", "Off"); + } + } + + // Enable trigger on the chosen selector. + if !Self::set_feature_str_internal(cam, "TriggerSelector", active) { + tracing::error!("[camera] Failed to re-select TriggerSelector={}", active); + return false; + } + let mode_ok = Self::set_feature_str_internal(cam, "TriggerMode", "On"); + let src_ok = Self::set_feature_str_internal(cam, "TriggerSource", trigger_source); + if mode_ok && src_ok { + tracing::info!( + "[camera] Trigger configured: Selector={}, Mode=On, Source={}", + active, trigger_source + ); + if let Some(readback) = Self::get_feature_str_internal(cam, "TriggerMode") { + if readback != "On" { + tracing::warn!( + "[camera] TriggerMode readback is '{}' (expected 'On')", + readback + ); + } + } + return true; + } + + tracing::error!("[camera] Failed to configure trigger mode on selector {}", active); + false + } + + /// Disable triggers for free-running (continuous) mode using direct GenICam features. + /// + /// Avoids `arv_camera_clear_triggers()` which may use wrong selectors for Hikrobot. + fn clear_triggers_internal(cam: *mut ArvCamera) -> bool { + if cam.is_null() { + return false; + } + + // Disable triggers on all known selectors to ensure free-run + let mut any_success = false; + for sel in ["FrameBurstStart", "FrameStart", "AcquisitionStart"] { + if Self::set_feature_str_internal(cam, "TriggerSelector", sel) { + if Self::set_feature_str_internal(cam, "TriggerMode", "Off") { + tracing::info!("[camera] Trigger disabled: Selector={}, Mode=Off", sel); + any_success = true; + } + } + } + + if any_success { + tracing::info!("[camera] Triggers cleared — camera in free-running mode"); + } else { + tracing::warn!("[camera] Could not clear triggers on any selector"); + } + any_success + } + + fn fire_software_trigger_internal(cam: *mut ArvCamera) -> bool { + if cam.is_null() { + return false; + } + unsafe { + let mut err = null_mut(); + arv_camera_software_trigger(cam, &mut err); + if err.is_null() { + true + } else { + let msg = CStr::from_ptr((*err).message).to_string_lossy(); + tracing::info!("[camera] arv_camera_software_trigger returned: {}. Trying command execution fallback...", msg); + g_error_free(err); + Self::execute_command_internal(cam, "TriggerSoftware") + } + } + } + + fn set_line_inverter_internal(cam: *mut ArvCamera, inverted: bool) -> bool { + if cam.is_null() { + return false; + } + if Self::set_feature_bool_internal(cam, "LineInverter", inverted) { + return true; + } + if Self::set_feature_int_internal(cam, "LineInverter", if inverted { 1 } else { 0 }) { + return true; + } + false + } + + fn set_black_level_internal(cam: *mut ArvCamera, val: f64) -> bool { + if cam.is_null() { + return false; + } + if Self::is_feature_available_internal(cam, "BlackLevelEnable") { + Self::set_feature_bool_internal(cam, "BlackLevelEnable", val > 0.0); + } + if Self::set_feature_float_internal(cam, "BlackLevel", val) { + return true; + } + if Self::set_feature_int_internal(cam, "BlackLevel", val as i64) { + return true; + } + false + } + + /// Enable or disable the camera's internal frame rate limiter. + /// + /// Uses direct GenICam device feature access only. + /// The Aravis C API does NOT have an `arv_camera_set_frame_rate_enable` function. + fn set_frame_rate_enable_internal(cam: *mut ArvCamera, enable: bool) -> bool { + if cam.is_null() { + return false; + } + let ok = Self::set_feature_bool_internal(cam, "AcquisitionFrameRateEnable", enable); + if !ok { + // Some cameras expose it as integer (0/1) rather than boolean + return Self::set_feature_int_internal( + cam, + "AcquisitionFrameRateEnable", + if enable { 1 } else { 0 }, + ); + } + tracing::info!( + "[camera] AcquisitionFrameRateEnable = {}", + if enable { "true" } else { "false" } + ); + ok + } + + fn set_pixel_format_internal(cam: *mut ArvCamera, format: &str) -> bool { + if cam.is_null() { + return false; + } + let candidates: Vec<&str> = if format.eq_ignore_ascii_case("color") { + vec![ + "BayerRG8", + "BayerBG8", + "BayerGR8", + "BayerGB8", + "RGB8Packed", + "BGR8Packed", + "RGB8", + "Mono8", + ] + } else if format.eq_ignore_ascii_case("mono") || format.eq_ignore_ascii_case("mono8") { + vec![ + "Mono8", + "BayerRG8", + "BayerBG8", + "BayerGR8", + "BayerGB8", + "RGB8Packed", + ] + } else { + vec![format, "BayerRG8", "BayerBG8", "Mono8"] + }; + + for fmt in candidates { + unsafe { + let fmt_cstr = match CString::new(fmt) { + Ok(s) => s, + Err(_) => continue, + }; + let mut err = null_mut(); + arv_camera_set_pixel_format_from_string(cam, fmt_cstr.as_ptr(), &mut err); + if err.is_null() { + tracing::info!("[camera] PixelFormat set to {}", fmt); + return true; + } else { + g_error_free(err); + } + } + if Self::set_feature_str_internal(cam, "PixelFormat", fmt) { + tracing::info!("[camera] PixelFormat set to {}", fmt); + return true; + } + } + tracing::warn!("[camera] Could not configure requested PixelFormat {}, retaining current format", format); + false + } + + fn set_any_feature_internal(cam: *mut ArvCamera, feature: &str, value: &str) -> bool { + if cam.is_null() { + return false; + } + // 1. Try String / Enumeration + if Self::set_feature_str_internal(cam, feature, value) { + return true; + } + // 2. Try Boolean + if value.eq_ignore_ascii_case("true") || value.eq_ignore_ascii_case("false") { + if Self::set_feature_bool_internal(cam, feature, value.eq_ignore_ascii_case("true")) { + return true; + } + } + // 3. Try Integer + if let Ok(int_val) = value.parse::() { + if Self::set_feature_int_internal(cam, feature, int_val) { + return true; + } + if int_val == 0 || int_val == 1 { + if Self::set_feature_bool_internal(cam, feature, int_val != 0) { + return true; + } + } + } + // 4. Try Float + if let Ok(float_val) = value.parse::() { + if Self::set_feature_float_internal(cam, feature, float_val) { + return true; + } + } + false + } +} diff --git a/headless-rust/src/config.rs b/headless-rust/src/config.rs new file mode 100644 index 0000000..d1b1e7d --- /dev/null +++ b/headless-rust/src/config.rs @@ -0,0 +1,53 @@ +use std::path::PathBuf; + +#[derive(Debug, Clone)] +pub struct AppConfig { + pub host: String, + pub port: u16, + pub data_dir: PathBuf, + pub images_dir: PathBuf, + pub db_path: PathBuf, + pub mock_mode: bool, +} + +impl AppConfig { + pub fn new(mock: bool, port_override: Option, host_override: Option) -> Self { + let host = host_override + .or_else(|| std::env::var("HOST").ok()) + .unwrap_or_else(|| "0.0.0.0".to_string()); + let port = port_override.unwrap_or_else(|| { + std::env::var("PORT") + .ok() + .and_then(|p| p.parse::().ok()) + .unwrap_or(3000) + }); + + let data_dir = if let Ok(custom) = std::env::var("DATA_DIR") { + PathBuf::from(custom) + } else if let Ok(home) = std::env::var("HOME") { + PathBuf::from(home).join(".speedcamera") + } else { + PathBuf::from(".speedcamera") + }; + + let images_dir = data_dir.join("images"); + let db_path = data_dir.join("speedcamera.db"); + + // Ensure directories exist + let _ = std::fs::create_dir_all(&data_dir); + let _ = std::fs::create_dir_all(&images_dir); + + let mock_mode = mock + || std::env::var("MOCK_MODE").map(|v| v == "true" || v == "1").unwrap_or(false) + || std::env::var("SPEEDCAMERA_MOCK").map(|v| v == "true" || v == "1").unwrap_or(false); + + Self { + host, + port, + data_dir, + images_dir, + db_path, + mock_mode, + } + } +} diff --git a/headless-rust/src/db/laps.rs b/headless-rust/src/db/laps.rs new file mode 100644 index 0000000..ba11eb5 --- /dev/null +++ b/headless-rust/src/db/laps.rs @@ -0,0 +1,223 @@ +use crate::models::{Lap, LapSession, LapSessionWithLaps, SaveLapInput}; +use chrono::Utc; +use rusqlite::{params, Connection, Result}; + +pub fn create_lap_session(conn: &Connection, lap_mode: &str) -> Result { + let now = Utc::now().to_rfc3339(); + conn.execute( + "INSERT INTO lap_sessions (startedAt, lapMode, createdAt) VALUES (?, ?, ?)", + params![now, lap_mode, now], + )?; + + let id = conn.last_insert_rowid(); + + Ok(LapSession { + id, + started_at: now.clone(), + ended_at: None, + lap_mode: lap_mode.to_string(), + created_at: now, + }) +} + +pub fn close_lap_session(conn: &Connection, id: i64) -> Result<()> { + let now = Utc::now().to_rfc3339(); + conn.execute( + "UPDATE lap_sessions SET endedAt = ? WHERE id = ?", + params![now, id], + )?; + Ok(()) +} + +pub fn insert_lap( + conn: &Connection, + input: &SaveLapInput, + start_image_path: Option<&str>, + end_image_path: Option<&str>, +) -> Result { + conn.execute( + "INSERT INTO laps ( + sessionId, lapNumber, startTimestamp, endTimestamp, durationMs, + speedAtStart, speedAtEnd, startImagePath, endImagePath + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", + params![ + input.session_id, + input.lap_number, + input.start_timestamp, + input.end_timestamp, + input.duration_ms, + input.speed_at_start, + input.speed_at_end, + start_image_path, + end_image_path, + ], + )?; + + let id = conn.last_insert_rowid(); + + Ok(Lap { + id, + session_id: input.session_id, + lap_number: input.lap_number, + start_timestamp: input.start_timestamp, + end_timestamp: input.end_timestamp, + duration_ms: input.duration_ms, + speed_at_start: input.speed_at_start, + speed_at_end: input.speed_at_end, + start_image_path: start_image_path.map(|s| s.to_string()), + end_image_path: end_image_path.map(|s| s.to_string()), + }) +} + +pub fn get_lap_sessions( + conn: &Connection, + page: i64, + limit: i64, +) -> Result<(Vec, i64)> { + let mut count_stmt = conn.prepare("SELECT COUNT(*) FROM lap_sessions")?; + let total: i64 = count_stmt.query_row([], |r| r.get(0))?; + + let offset = (page.max(1) - 1) * limit; + let mut session_stmt = conn.prepare( + "SELECT id, startedAt, endedAt, lapMode, createdAt + FROM lap_sessions ORDER BY startedAt DESC LIMIT ? OFFSET ?", + )?; + + let session_rows = session_stmt.query_map(params![limit, offset], |row| { + Ok(LapSession { + id: row.get(0)?, + started_at: row.get(1)?, + ended_at: row.get(2)?, + lap_mode: row.get(3)?, + created_at: row.get(4)?, + }) + })?; + + let mut sessions = Vec::new(); + for s in session_rows { + let session = s?; + let laps = get_laps_for_session(conn, session.id)?; + sessions.push(LapSessionWithLaps { + id: session.id, + started_at: session.started_at, + ended_at: session.ended_at, + lap_mode: session.lap_mode, + created_at: session.created_at, + laps, + }); + } + + Ok((sessions, total)) +} + +pub fn get_lap_session_by_id(conn: &Connection, id: i64) -> Result> { + let mut stmt = conn.prepare( + "SELECT id, startedAt, endedAt, lapMode, createdAt FROM lap_sessions WHERE id = ?", + )?; + + let mut rows = stmt.query_map(params![id], |row| { + Ok(LapSession { + id: row.get(0)?, + started_at: row.get(1)?, + ended_at: row.get(2)?, + lap_mode: row.get(3)?, + created_at: row.get(4)?, + }) + })?; + + if let Some(row) = rows.next() { + let s = row?; + let laps = get_laps_for_session(conn, s.id)?; + Ok(Some(LapSessionWithLaps { + id: s.id, + started_at: s.started_at, + ended_at: s.ended_at, + lap_mode: s.lap_mode, + created_at: s.created_at, + laps, + })) + } else { + Ok(None) + } +} + +fn get_laps_for_session(conn: &Connection, session_id: i64) -> Result> { + let mut stmt = conn.prepare( + "SELECT id, sessionId, lapNumber, startTimestamp, endTimestamp, durationMs, + speedAtStart, speedAtEnd, startImagePath, endImagePath + FROM laps WHERE sessionId = ? ORDER BY lapNumber ASC", + )?; + + let rows = stmt.query_map(params![session_id], |row| { + Ok(Lap { + id: row.get(0)?, + session_id: row.get(1)?, + lap_number: row.get(2)?, + start_timestamp: row.get(3)?, + end_timestamp: row.get(4)?, + duration_ms: row.get(5)?, + speed_at_start: row.get(6)?, + speed_at_end: row.get(7)?, + start_image_path: row.get(8)?, + end_image_path: row.get(9)?, + }) + })?; + + let mut laps = Vec::new(); + for l in rows { + laps.push(l?); + } + Ok(laps) +} + +pub fn get_lap_image_paths_for_session(conn: &Connection, session_id: i64) -> Result> { + let mut stmt = conn.prepare("SELECT startImagePath, endImagePath FROM laps WHERE sessionId = ?")?; + let rows = stmt.query_map(params![session_id], |row| { + let start: Option = row.get(0)?; + let end: Option = row.get(1)?; + Ok((start, end)) + })?; + + let mut paths = Vec::new(); + for r in rows { + let (start, end) = r?; + if let Some(s) = start { + paths.push(s); + } + if let Some(e) = end { + paths.push(e); + } + } + Ok(paths) +} + +pub fn get_lap_image_paths_for_lap(conn: &Connection, lap_id: i64) -> Result> { + let mut stmt = conn.prepare("SELECT startImagePath, endImagePath FROM laps WHERE id = ?")?; + let mut rows = stmt.query_map(params![lap_id], |row| { + let start: Option = row.get(0)?; + let end: Option = row.get(1)?; + Ok((start, end)) + })?; + + let mut paths = Vec::new(); + if let Some(r) = rows.next() { + let (start, end) = r?; + if let Some(s) = start { + paths.push(s); + } + if let Some(e) = end { + paths.push(e); + } + } + Ok(paths) +} + +pub fn delete_lap_session(conn: &Connection, id: i64) -> Result<()> { + conn.execute("DELETE FROM lap_sessions WHERE id = ?", params![id])?; + Ok(()) +} + +pub fn delete_lap(conn: &Connection, id: i64) -> Result<()> { + conn.execute("DELETE FROM laps WHERE id = ?", params![id])?; + Ok(()) +} diff --git a/headless-rust/src/db/mod.rs b/headless-rust/src/db/mod.rs new file mode 100644 index 0000000..4e2152f --- /dev/null +++ b/headless-rust/src/db/mod.rs @@ -0,0 +1,78 @@ +pub mod laps; +pub mod settings; +pub mod violations; + +use rusqlite::{Connection, Result}; +use std::path::Path; +use std::sync::{Arc, Mutex}; + +#[derive(Clone)] +pub struct Database { + conn: Arc>, +} + +impl Database { + pub fn new(path: &Path) -> Result { + let conn = Connection::open(path)?; + + // WAL mode + foreign keys for high concurrency & safety on Pi + conn.execute_batch( + "PRAGMA journal_mode = WAL; + PRAGMA foreign_keys = ON; + PRAGMA busy_timeout = 5000;", + )?; + + // Tables + conn.execute_batch( + "CREATE TABLE IF NOT EXISTS speed_violations ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + timestamp TEXT NOT NULL, + measuredSpeed REAL NOT NULL, + maxSpeed REAL NOT NULL, + direction TEXT NOT NULL DEFAULT 'forward', + imagePath TEXT NOT NULL, + createdAt TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP + ); + CREATE INDEX IF NOT EXISTS idx_timestamp ON speed_violations(timestamp); + + CREATE TABLE IF NOT EXISTS settings ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL + ); + + CREATE TABLE IF NOT EXISTS lap_sessions ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + startedAt TEXT NOT NULL, + endedAt TEXT, + lapMode TEXT NOT NULL, + createdAt TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP + ); + CREATE INDEX IF NOT EXISTS idx_lap_sessions_started ON lap_sessions(startedAt); + + CREATE TABLE IF NOT EXISTS laps ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + sessionId INTEGER NOT NULL REFERENCES lap_sessions(id) ON DELETE CASCADE, + lapNumber INTEGER NOT NULL, + startTimestamp INTEGER NOT NULL, + endTimestamp INTEGER NOT NULL, + durationMs INTEGER NOT NULL, + speedAtStart REAL NOT NULL, + speedAtEnd REAL NOT NULL, + startImagePath TEXT, + endImagePath TEXT + ); + CREATE INDEX IF NOT EXISTS idx_laps_session ON laps(sessionId);", + )?; + + // Initialize default settings if not existing + settings::init_defaults(&conn)?; + + Ok(Self { + conn: Arc::new(Mutex::new(conn)), + }) + } + + pub fn lock(&self) -> std::sync::MutexGuard<'_, Connection> { + self.conn.lock().unwrap() + } +} diff --git a/headless-rust/src/db/settings.rs b/headless-rust/src/db/settings.rs new file mode 100644 index 0000000..fe9c269 --- /dev/null +++ b/headless-rust/src/db/settings.rs @@ -0,0 +1,103 @@ +use crate::models::AppSettings; +use rusqlite::{params, Connection, Result}; +use std::collections::HashMap; + +pub fn init_defaults(conn: &Connection) -> Result<()> { + let defaults = [ + ("maxSpeed", "30"), + ("selectedPort", ""), + ("cameraExposure", "5000"), + ("cameraGain", "0"), + ("strobeLineDuration", "5000"), + ("pixelFormat", "Mono"), + ("exposureAuto", "Off"), + ("gainAuto", "Off"), + ("frameRate", "30"), + ("cameraWidth", "1280"), + ("cameraHeight", "1024"), + ("blackLevel", "0"), + ("lapMode", "single"), + ("lapSaveImages", "true"), + ("lapDirFilter", "both"), + ("teableUrl", ""), + ("teableToken", ""), + ("teableUserName", ""), + ("teableUserEmail", ""), + ("teableUserAvatar", ""), + ("teableSpaceId", ""), + ("teableBaseId", ""), + ("teableTableId", ""), + ("teableSyncEnabled", "false"), + ("githubToken", ""), + ("skinMeasuringLocation", ""), + ]; + + let mut stmt = conn.prepare("INSERT OR IGNORE INTO settings (key, value) VALUES (?, ?)")?; + for (k, v) in defaults { + stmt.execute(params![k, v])?; + } + Ok(()) +} + +pub fn get_settings(conn: &Connection) -> Result { + let mut stmt = conn.prepare("SELECT key, value FROM settings")?; + let rows = stmt.query_map([], |row| { + Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)) + })?; + + let mut map = HashMap::new(); + for item in rows { + if let Ok((k, v)) = item { + map.insert(k, v); + } + } + + let get_str = |k: &str, default: &str| map.get(k).cloned().unwrap_or_else(|| default.to_string()); + let get_f64 = |k: &str, default: f64| { + map.get(k) + .and_then(|v| v.parse::().ok()) + .unwrap_or(default) + }; + let get_i64 = |k: &str, default: i64| { + map.get(k) + .and_then(|v| v.parse::().ok()) + .unwrap_or(default) + }; + + Ok(AppSettings { + max_speed: get_f64("maxSpeed", 30.0), + selected_port: get_str("selectedPort", ""), + camera_exposure: get_f64("cameraExposure", 5000.0), + camera_gain: get_f64("cameraGain", 0.0), + strobe_line_duration: get_f64("strobeLineDuration", 5000.0), + pixel_format: get_str("pixelFormat", "Mono"), + exposure_auto: get_str("exposureAuto", "Off"), + gain_auto: get_str("gainAuto", "Off"), + frame_rate: get_f64("frameRate", 30.0), + camera_width: get_i64("cameraWidth", 1280), + camera_height: get_i64("cameraHeight", 1024), + black_level: get_f64("blackLevel", 0.0), + lap_mode: get_str("lapMode", "single"), + lap_save_images: get_str("lapSaveImages", "true"), + lap_dir_filter: get_str("lapDirFilter", "both"), + teable_url: get_str("teableUrl", ""), + teable_token: get_str("teableToken", ""), + teable_user_name: get_str("teableUserName", ""), + teable_user_email: get_str("teableUserEmail", ""), + teable_user_avatar: get_str("teableUserAvatar", ""), + teable_space_id: get_str("teableSpaceId", ""), + teable_base_id: get_str("teableBaseId", ""), + teable_table_id: get_str("teableTableId", ""), + teable_sync_enabled: get_str("teableSyncEnabled", "false"), + github_token: get_str("githubToken", ""), + skin_measuring_location: get_str("skinMeasuringLocation", ""), + }) +} + +pub fn save_setting(conn: &Connection, key: &str, value: &str) -> Result<()> { + conn.execute( + "INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value", + params![key, value], + )?; + Ok(()) +} diff --git a/headless-rust/src/db/violations.rs b/headless-rust/src/db/violations.rs new file mode 100644 index 0000000..724528b --- /dev/null +++ b/headless-rust/src/db/violations.rs @@ -0,0 +1,188 @@ +use crate::models::{SaveViolationInput, Violation, ViolationPage, ViolationQuery}; +use chrono::Utc; +use rusqlite::{params, Connection, Result}; + +pub fn insert_violation( + conn: &Connection, + input: &SaveViolationInput, + image_path: &str, +) -> Result { + let now = Utc::now().to_rfc3339(); + conn.execute( + "INSERT INTO speed_violations (timestamp, measuredSpeed, maxSpeed, direction, imagePath, createdAt) + VALUES (?, ?, ?, ?, ?, ?)", + params![ + now, + input.measured_speed, + input.max_speed, + input.direction, + image_path, + now + ], + )?; + + let id = conn.last_insert_rowid(); + + Ok(Violation { + id, + timestamp: now.clone(), + measured_speed: input.measured_speed, + max_speed: input.max_speed, + direction: input.direction.clone(), + image_path: image_path.to_string(), + created_at: now, + }) +} + +pub fn query_violations(conn: &Connection, q: &ViolationQuery) -> Result { + let mut conditions = Vec::new(); + let mut params_vec: Vec> = Vec::new(); + + if let Some(from) = &q.date_from { + conditions.push("timestamp >= ?"); + params_vec.push(Box::new(from.clone())); + } + if let Some(to) = &q.date_to { + conditions.push("timestamp <= ?"); + params_vec.push(Box::new(to.clone())); + } + if let Some(min) = q.min_speed { + conditions.push("measuredSpeed >= ?"); + params_vec.push(Box::new(min)); + } + + let where_clause = if conditions.is_empty() { + String::new() + } else { + format!("WHERE {}", conditions.join(" AND ")) + }; + + let count_query = format!("SELECT COUNT(*) FROM speed_violations {}", where_clause); + let mut count_stmt = conn.prepare(&count_query)?; + let rusqlite_params: Vec<&dyn rusqlite::ToSql> = params_vec.iter().map(|b| b.as_ref()).collect(); + let total: i64 = count_stmt.query_row(rusqlite_params.as_slice(), |r| r.get(0))?; + + let offset = (q.page.max(1) - 1) * q.limit; + let data_query = format!( + "SELECT id, timestamp, measuredSpeed, maxSpeed, direction, imagePath, createdAt + FROM speed_violations {} ORDER BY timestamp DESC LIMIT ? OFFSET ?", + where_clause + ); + + let mut data_stmt = conn.prepare(&data_query)?; + let mut query_params = params_vec; + query_params.push(Box::new(q.limit)); + query_params.push(Box::new(offset)); + + let final_params: Vec<&dyn rusqlite::ToSql> = query_params.iter().map(|b| b.as_ref()).collect(); + + let rows = data_stmt.query_map(final_params.as_slice(), |row| { + Ok(Violation { + id: row.get(0)?, + timestamp: row.get(1)?, + measured_speed: row.get(2)?, + max_speed: row.get(3)?, + direction: row.get(4)?, + image_path: row.get(5)?, + created_at: row.get(6)?, + }) + })?; + + let mut violations = Vec::new(); + for v in rows { + violations.push(v?); + } + + Ok(ViolationPage { violations, total }) +} + +pub fn get_violation_by_id(conn: &Connection, id: i64) -> Result> { + let mut stmt = conn.prepare( + "SELECT id, timestamp, measuredSpeed, maxSpeed, direction, imagePath, createdAt + FROM speed_violations WHERE id = ?", + )?; + + let mut rows = stmt.query_map(params![id], |row| { + Ok(Violation { + id: row.get(0)?, + timestamp: row.get(1)?, + measured_speed: row.get(2)?, + max_speed: row.get(3)?, + direction: row.get(4)?, + image_path: row.get(5)?, + created_at: row.get(6)?, + }) + })?; + + if let Some(row) = rows.next() { + Ok(Some(row?)) + } else { + Ok(None) + } +} + +pub fn remove_violation(conn: &Connection, id: i64) -> Result<()> { + conn.execute("DELETE FROM speed_violations WHERE id = ?", params![id])?; + Ok(()) +} + +pub fn export_csv( + conn: &Connection, + date_from: Option<&str>, + date_to: Option<&str>, + min_speed: Option, +) -> Result { + let mut conditions = Vec::new(); + let mut params_vec: Vec> = Vec::new(); + + if let Some(from) = date_from { + conditions.push("timestamp >= ?"); + params_vec.push(Box::new(from.to_string())); + } + if let Some(to) = date_to { + conditions.push("timestamp <= ?"); + params_vec.push(Box::new(to.to_string())); + } + if let Some(min) = min_speed { + conditions.push("measuredSpeed >= ?"); + params_vec.push(Box::new(min)); + } + + let where_clause = if conditions.is_empty() { + String::new() + } else { + format!("WHERE {}", conditions.join(" AND ")) + }; + + let query = format!( + "SELECT id, timestamp, measuredSpeed, maxSpeed, direction, imagePath, createdAt + FROM speed_violations {} ORDER BY timestamp DESC", + where_clause + ); + + let mut stmt = conn.prepare(&query)?; + let slice: Vec<&dyn rusqlite::ToSql> = params_vec.iter().map(|b| b.as_ref()).collect(); + + let rows = stmt.query_map(slice.as_slice(), |row| { + Ok(Violation { + id: row.get(0)?, + timestamp: row.get(1)?, + measured_speed: row.get(2)?, + max_speed: row.get(3)?, + direction: row.get(4)?, + image_path: row.get(5)?, + created_at: row.get(6)?, + }) + })?; + + let mut csv = String::from("id,timestamp,measuredSpeed,maxSpeed,direction,imagePath,createdAt\n"); + for item in rows { + let v = item?; + csv.push_str(&format!( + "{},\"{}\",{},{},{},\"{}\",\"{}\"\n", + v.id, v.timestamp, v.measured_speed, v.max_speed, v.direction, v.image_path, v.created_at + )); + } + + Ok(csv) +} diff --git a/headless-rust/src/integrations/flasher.rs b/headless-rust/src/integrations/flasher.rs new file mode 100644 index 0000000..d09a453 --- /dev/null +++ b/headless-rust/src/integrations/flasher.rs @@ -0,0 +1,206 @@ +use crate::models::{FlashProgressPayload, GithubRelease}; +use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION, USER_AGENT}; +use std::process::Stdio; +use tokio::io::{AsyncBufReadExt, BufReader}; +use tokio::process::Command; +use tokio::sync::broadcast; + +const GITHUB_API_URL: &str = "https://api.github.com/repos/LeoLTM/speedcamera/releases"; +const GITHUB_USER_URL: &str = "https://api.github.com/user"; + +fn github_headers(token: &str) -> HeaderMap { + let mut headers = HeaderMap::new(); + headers.insert(USER_AGENT, HeaderValue::from_static("speedcamera-rust")); + if !token.is_empty() { + if let Ok(val) = HeaderValue::from_str(&format!("Bearer {}", token)) { + headers.insert(AUTHORIZATION, val); + } + } + headers +} + +pub async fn test_github_token( + token: &str, +) -> Result<(bool, Option), String> { + if token.trim().is_empty() { + return Ok((false, None)); + } + + let client = reqwest::Client::new(); + let res = client + .get(GITHUB_USER_URL) + .headers(github_headers(token)) + .send() + .await + .map_err(|e| e.to_string())?; + + if res.status().is_success() { + let json: serde_json::Value = res.json().await.map_err(|e| e.to_string())?; + let login = json["login"].as_str().map(|s| s.to_string()); + Ok((true, login)) + } else { + Ok((false, None)) + } +} + +pub async fn list_firmware_releases(token: &str) -> Result, String> { + let client = reqwest::Client::new(); + let res = client + .get(GITHUB_API_URL) + .headers(github_headers(token)) + .send() + .await + .map_err(|e| e.to_string())?; + + if !res.status().is_success() { + return Err(format!("GitHub API error: HTTP {}", res.status())); + } + + let json: serde_json::Value = res.json().await.map_err(|e| e.to_string())?; + let mut list = Vec::new(); + + if let Some(releases) = json.as_array() { + for r in releases { + let tag = r["tag_name"].as_str().unwrap_or("").to_string(); + let name = r["name"].as_str().unwrap_or(&tag).to_string(); + let published_at = r["published_at"].as_str().unwrap_or("").to_string(); + let prerelease = r["prerelease"].as_bool().unwrap_or(false); + + let mut firmware_asset_api_url = String::new(); + if let Some(assets) = r["assets"].as_array() { + for a in assets { + let asset_name = a["name"].as_str().unwrap_or(""); + if asset_name.ends_with(".bin") || asset_name.contains("firmware") { + firmware_asset_api_url = a["url"].as_str().unwrap_or("").to_string(); + break; + } + } + } + + list.push(GithubRelease { + tag, + name, + published_at, + prerelease, + firmware_asset_api_url, + }); + } + } + + Ok(list) +} + +pub async fn flash_firmware( + _release_tag: &str, + port: &str, + firmware_asset_api_url: &str, + token: &str, + tx: broadcast::Sender, +) { + let _ = tx.send(FlashProgressPayload::Downloading); + + let client = reqwest::Client::new(); + let mut req = client.get(firmware_asset_api_url).headers(github_headers(token)); + req = req.header("Accept", "application/octet-stream"); + + let bytes = match req.send().await { + Ok(res) if res.status().is_success() => match res.bytes().await { + Ok(b) => b, + Err(e) => { + let _ = tx.send(FlashProgressPayload::Error { + message: format!("Failed to read binary: {}", e), + }); + return; + } + }, + Ok(res) => { + let _ = tx.send(FlashProgressPayload::Error { + message: format!("Failed to download firmware asset: HTTP {}", res.status()), + }); + return; + } + Err(e) => { + let _ = tx.send(FlashProgressPayload::Error { + message: format!("Download network error: {}", e), + }); + return; + } + }; + + let temp_file = std::env::temp_dir().join("speedcamera_firmware.bin"); + if let Err(e) = std::fs::write(&temp_file, &bytes) { + let _ = tx.send(FlashProgressPayload::Error { + message: format!("Failed to write temp firmware file: {}", e), + }); + return; + } + + let esptool_cmd = "esptool.py"; + let mut child = match Command::new(esptool_cmd) + .arg("--chip") + .arg("esp8266") + .arg("--port") + .arg(port) + .arg("--baud") + .arg("460800") + .arg("write_flash") + .arg("0x0") + .arg(temp_file.to_str().unwrap_or("")) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + { + Ok(c) => c, + Err(_) => { + // Try standard esptool + match Command::new("esptool") + .arg("--chip") + .arg("esp8266") + .arg("--port") + .arg(port) + .arg("--baud") + .arg("460800") + .arg("write_flash") + .arg("0x0") + .arg(temp_file.to_str().unwrap_or("")) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + { + Ok(c) => c, + Err(e) => { + let _ = tx.send(FlashProgressPayload::Error { + message: format!("esptool not found or failed to spawn: {}", e), + }); + return; + } + } + } + }; + + if let Some(stdout) = child.stdout.take() { + let mut reader = BufReader::new(stdout).lines(); + let tx_clone = tx.clone(); + tokio::spawn(async move { + while let Ok(Some(line)) = reader.next_line().await { + let _ = tx_clone.send(FlashProgressPayload::Output { line }); + } + }); + } + + match child.wait().await { + Ok(status) if status.success() => { + let _ = tx.send(FlashProgressPayload::Done); + } + Ok(status) => { + let _ = tx.send(FlashProgressPayload::Error { + message: format!("esptool exited with status {}", status), + }); + } + Err(e) => { + let _ = tx.send(FlashProgressPayload::Error { + message: format!("esptool execution error: {}", e), + }); + } + } +} diff --git a/headless-rust/src/integrations/mod.rs b/headless-rust/src/integrations/mod.rs new file mode 100644 index 0000000..2d0e320 --- /dev/null +++ b/headless-rust/src/integrations/mod.rs @@ -0,0 +1,2 @@ +pub mod flasher; +pub mod teable; diff --git a/headless-rust/src/integrations/teable.rs b/headless-rust/src/integrations/teable.rs new file mode 100644 index 0000000..47b2728 --- /dev/null +++ b/headless-rust/src/integrations/teable.rs @@ -0,0 +1,336 @@ +use crate::models::{ + SyncLapInput, TeableBase, TeableSchemaCheck, TeableSpace, TeableTable, TeableUser, +}; +use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION, CONTENT_TYPE}; +use serde_json::json; + +pub struct TeableClient { + client: reqwest::Client, +} + +impl TeableClient { + pub fn new() -> Self { + Self { + client: reqwest::Client::builder() + .danger_accept_invalid_certs(true) + .build() + .unwrap_or_default(), + } + } + + fn headers(token: &str) -> HeaderMap { + let mut headers = HeaderMap::new(); + if let Ok(val) = HeaderValue::from_str(&format!("Bearer {}", token)) { + headers.insert(AUTHORIZATION, val); + } + headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json")); + headers + } + + pub async fn test_connection(&self, url: &str, token: &str) -> Result { + let base = url.trim_end_matches('/'); + let endpoint = format!("{}/api/user/me", base); + + let res = self + .client + .get(&endpoint) + .headers(Self::headers(token)) + .send() + .await + .map_err(|e| e.to_string())?; + + if !res.status().is_success() { + return Err(format!("HTTP {}", res.status())); + } + + let user: serde_json::Value = res.json().await.map_err(|e| e.to_string())?; + Ok(TeableUser { + id: user["id"].as_str().unwrap_or("").to_string(), + name: user["name"].as_str().unwrap_or("").to_string(), + email: user["email"].as_str().unwrap_or("").to_string(), + avatar: user["avatar"].as_str().map(|s| s.to_string()), + }) + } + + pub async fn list_spaces(&self, url: &str, token: &str) -> Result, String> { + let base = url.trim_end_matches('/'); + let endpoint = format!("{}/api/space", base); + + let res = self + .client + .get(&endpoint) + .headers(Self::headers(token)) + .send() + .await + .map_err(|e| e.to_string())?; + + let json: serde_json::Value = res.json().await.map_err(|e| e.to_string())?; + let list = json + .as_array() + .map(|arr| { + arr.iter() + .filter_map(|s| { + Some(TeableSpace { + id: s["id"].as_str()?.to_string(), + name: s["name"].as_str()?.to_string(), + }) + }) + .collect() + }) + .unwrap_or_default(); + + Ok(list) + } + + pub async fn list_bases(&self, url: &str, token: &str, space_id: &str) -> Result, String> { + let base = url.trim_end_matches('/'); + let endpoint = format!("{}/api/space/{}/base", base, space_id); + + let res = self + .client + .get(&endpoint) + .headers(Self::headers(token)) + .send() + .await + .map_err(|e| e.to_string())?; + + let json: serde_json::Value = res.json().await.map_err(|e| e.to_string())?; + let list = json + .as_array() + .map(|arr| { + arr.iter() + .filter_map(|b| { + Some(TeableBase { + id: b["id"].as_str()?.to_string(), + name: b["name"].as_str()?.to_string(), + space_id: space_id.to_string(), + }) + }) + .collect() + }) + .unwrap_or_default(); + + Ok(list) + } + + pub async fn list_tables(&self, url: &str, token: &str, base_id: &str) -> Result, String> { + let base = url.trim_end_matches('/'); + let endpoint = format!("{}/api/base/{}/table", base, base_id); + + let res = self + .client + .get(&endpoint) + .headers(Self::headers(token)) + .send() + .await + .map_err(|e| e.to_string())?; + + let json: serde_json::Value = res.json().await.map_err(|e| e.to_string())?; + let list = json + .as_array() + .map(|arr| { + arr.iter() + .filter_map(|t| { + Some(TeableTable { + id: t["id"].as_str()?.to_string(), + name: t["name"].as_str()?.to_string(), + }) + }) + .collect() + }) + .unwrap_or_default(); + + Ok(list) + } + + async fn list_fields(&self, url: &str, token: &str, table_id: &str) -> Result, String> { + let base = url.trim_end_matches('/'); + let endpoint = format!("{}/api/table/{}/field", base, table_id); + + let res = self + .client + .get(&endpoint) + .headers(Self::headers(token)) + .send() + .await + .map_err(|e| e.to_string())?; + + let json: serde_json::Value = res.json().await.map_err(|e| e.to_string())?; + let names = json + .as_array() + .map(|arr| { + arr.iter() + .filter_map(|f| f["name"].as_str().map(|s| s.to_string())) + .collect() + }) + .unwrap_or_default(); + + Ok(names) + } + + pub async fn verify_table(&self, url: &str, token: &str, table_id: &str) -> Result { + let required_fields = [ + "Session Started At", + "Lap Mode", + "Lap Number", + "Start Time", + "End Time", + "Duration", + "Speed At Start", + "Speed At End", + ]; + + let existing = self.list_fields(url, token, table_id).await?; + let existing_set: std::collections::HashSet<_> = existing.into_iter().collect(); + + let missing_fields = required_fields + .iter() + .filter(|f| !existing_set.contains(**f)) + .map(|f| f.to_string()) + .collect(); + + Ok(TeableSchemaCheck { missing_fields }) + } + + pub async fn ensure_fields(&self, url: &str, token: &str, table_id: &str) -> Result, String> { + let required_fields: &[(&str, &str)] = &[ + ("Session Started At", "singleLineText"), + ("Lap Mode", "singleLineText"), + ("Lap Number", "number"), + ("Start Time", "singleLineText"), + ("End Time", "singleLineText"), + ("Duration", "singleLineText"), + ("Speed At Start", "number"), + ("Speed At End", "number"), + ]; + + let existing = self.list_fields(url, token, table_id).await?; + let existing_set: std::collections::HashSet<_> = existing.into_iter().collect(); + + let base = url.trim_end_matches('/'); + let endpoint = format!("{}/api/table/{}/field", base, table_id); + + let mut created = Vec::new(); + for (name, field_type) in required_fields { + if existing_set.contains(*name) { + continue; + } + + let body = json!({ + "name": name, + "type": field_type + }); + + let res = self + .client + .post(&endpoint) + .headers(Self::headers(token)) + .json(&body) + .send() + .await + .map_err(|e| e.to_string())?; + + if res.status().is_success() { + created.push(name.to_string()); + } + } + + Ok(created) + } + + pub async fn create_table( + &self, + url: &str, + token: &str, + base_id: &str, + table_name: &str, + ) -> Result { + let base = url.trim_end_matches('/'); + let endpoint = format!("{}/api/base/{}/table", base, base_id); + + let fields = json!([ + { "name": "Session Started At", "type": "singleLineText" }, + { "name": "Lap Mode", "type": "singleLineText" }, + { "name": "Lap Number", "type": "number" }, + { "name": "Start Time", "type": "singleLineText" }, + { "name": "End Time", "type": "singleLineText" }, + { "name": "Duration", "type": "singleLineText" }, + { "name": "Speed At Start", "type": "number" }, + { "name": "Speed At End", "type": "number" } + ]); + + let body = json!({ + "name": table_name, + "fields": fields + }); + + let res = self + .client + .post(&endpoint) + .headers(Self::headers(token)) + .json(&body) + .send() + .await + .map_err(|e| e.to_string())?; + + if !res.status().is_success() { + let body_text = res.text().await.unwrap_or_default(); + return Err(format!("Failed to create table: {}", body_text)); + } + + let data: serde_json::Value = res.json().await.map_err(|e| e.to_string())?; + Ok(TeableTable { + id: data["id"].as_str().unwrap_or("").to_string(), + name: data["name"].as_str().unwrap_or(table_name).to_string(), + }) + } + + pub async fn sync_lap(&self, url: &str, token: &str, table_id: &str, input: &SyncLapInput) -> Result<(), String> { + let base = url.trim_end_matches('/'); + let endpoint = format!("{}/api/table/{}/record", base, table_id); + + let start_dt = chrono::DateTime::from_timestamp_millis(input.lap.start_timestamp) + .map(|dt| dt.to_rfc3339()) + .unwrap_or_default(); + + let end_dt = chrono::DateTime::from_timestamp_millis(input.lap.end_timestamp) + .map(|dt| dt.to_rfc3339()) + .unwrap_or_default(); + + let total_sec = input.lap.duration_ms as f64 / 1000.0; + let min = (total_sec / 60.0).floor() as i64; + let sec = (total_sec % 60.0).floor() as i64; + let ms = input.lap.duration_ms % 1000; + let dur_str = format!("{:02}:{:02}.{:03}", min, sec, ms); + + let body = json!({ + "records": [{ + "fields": { + "Session Started At": input.session.started_at, + "Lap Mode": input.session.lap_mode, + "Lap Number": input.lap.lap_number, + "Start Time": start_dt, + "End Time": end_dt, + "Duration": dur_str, + "Speed At Start": input.lap.speed_at_start, + "Speed At End": input.lap.speed_at_end + } + }] + }); + + let res = self + .client + .post(&endpoint) + .headers(Self::headers(token)) + .json(&body) + .send() + .await + .map_err(|e| e.to_string())?; + + if !res.status().is_success() { + return Err(format!("Teable sync error: HTTP {}", res.status())); + } + + Ok(()) + } +} diff --git a/headless-rust/src/main.rs b/headless-rust/src/main.rs new file mode 100644 index 0000000..f7a3be1 --- /dev/null +++ b/headless-rust/src/main.rs @@ -0,0 +1,185 @@ +mod camera; +mod config; +mod db; +mod integrations; +mod models; +mod network; +mod serial; +mod storage; +mod web; + +use camera::CameraService; +use clap::Parser; +use config::AppConfig; +use db::Database; +use models::SaveViolationInput; +use serial::SerialService; +use storage::FileStore; + +#[derive(Parser, Debug)] +#[command(name = "speedcamera-rust")] +#[command(about = "High-performance headless Speedcamera daemon for Raspberry Pi 5", long_about = None)] +struct Args { + #[arg(short, long, help = "Run in mock hardware mode (no physical camera/serial required)")] + mock: bool, + + #[arg(short, long, help = "HTTP server port (default: 3000)")] + port: Option, + + #[arg(short = 'H', long, help = "HTTP server bind address (default: 0.0.0.0)")] + host: Option, +} + +#[tokio::main] +async fn main() -> Result<(), Box> { + // Non-blocking logging: tracing-appender writes on dedicated thread. + // Prevents journald/SSH backpressure from stalling tokio workers. + let (nb_writer, _guard) = tracing_appender::non_blocking(std::io::stdout()); + tracing_subscriber::fmt() + .with_writer(nb_writer) + .with_env_filter( + tracing_subscriber::EnvFilter::try_from_default_env() + .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")), + ) + .with_target(false) + .init(); + + let args = Args::parse(); + let config = AppConfig::new(args.mock, args.port, args.host); + + tracing::info!("─────────────────────────────────────────────────────────────────"); + tracing::info!(" ⚡ Speedcamera Headless Daemon (Rust & Axum / Socket.io)"); + tracing::info!(" • Port: http://{}:{}", config.host, config.port); + tracing::info!(" • Data Dir: {}", config.data_dir.display()); + tracing::info!(" • Mock Mode: {}", config.mock_mode); + tracing::info!("─────────────────────────────────────────────────────────────────"); + + let network_summary = network::get_system_network_summary(); + tracing::info!(" • Network Mode: [{}]", network_summary.mode.to_uppercase()); + tracing::info!(" • Camera LAN [{}]: {} -> [{}]", + network_summary.camera_lan.interface_name.as_deref().unwrap_or("eth0"), + network_summary.camera_lan.ip.as_deref().unwrap_or("Not configured"), + network_summary.camera_lan.status.to_uppercase() + ); + if let Some(ref client) = network_summary.wifi_client { + tracing::info!(" • Wi-Fi Client [{}]: {} (SSID: {}) -> [{}]", + client.interface_name.as_deref().unwrap_or("wlan0"), + client.ip.as_deref().unwrap_or("Waiting DHCP"), + client.ssid.as_deref().unwrap_or("Unknown"), + client.status.to_uppercase() + ); + } else { + tracing::info!(" • Hotspot AP [{}]: {} -> [{}]", + network_summary.hotspot_ap.interface_name.as_deref().unwrap_or("wlan0"), + network_summary.hotspot_ap.ip.as_deref().unwrap_or("Not configured"), + network_summary.hotspot_ap.status.to_uppercase() + ); + } + tracing::info!("─────────────────────────────────────────────────────────────────"); + + // Initialize Database + let db = Database::new(&config.db_path).expect("Failed to initialize SQLite database"); + + // Initialize FileStore + let store = FileStore::new(&config.images_dir); + + // Initialize Camera Service + let camera = CameraService::new(config.mock_mode); + + // Initialize Serial Service + let serial = SerialService::new(config.mock_mode); + + // Auto-connect configured serial port if present + if !config.mock_mode { + let conn = db.lock(); + if let Ok(settings) = db::settings::get_settings(&conn) { + if !settings.selected_port.is_empty() { + tracing::info!("[serial] Auto-connecting configured port: {}", settings.selected_port); + serial.open_port(&settings.selected_port); + } + } + } + + // ─── Armed System State ────────────────────────────────────────────────── + let armed = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let (armed_tx, _) = tokio::sync::broadcast::channel::(32); + let pipeline_armed = armed.clone(); + + // ─── Instant Shutter Trigger Pipeline (<10ms latency) ───────────────────── + let (violation_tx, _) = tokio::sync::broadcast::channel::(32); + let pipeline_violation_tx = violation_tx.clone(); + let pipeline_cam = camera.clone(); + let pipeline_db = db.clone(); + let pipeline_store = store.clone(); + let mut serial_rx = serial.subscribe(); + + tokio::spawn(async move { + loop { + match serial_rx.recv().await { + Ok(msg) => { + if let models::SerialStatusPayload::Speeding { value, direction, .. } = msg { + if !pipeline_armed.load(std::sync::atomic::Ordering::SeqCst) { + tracing::debug!("[trigger-pipeline] Speeding detected ({} km/h) but system is DISARMED — skipping capture", value); + continue; + } + + tracing::info!("[trigger-pipeline] Speeding detected ({} km/h) -> Triggering camera shutter!", value); + + let cam = pipeline_cam.clone(); + let db_clone = pipeline_db.clone(); + let store_clone = pipeline_store.clone(); + let v_tx = pipeline_violation_tx.clone(); + + 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, + direction, + }; + if let Ok(v) = db::violations::insert_violation(&conn, &input, &img_path) { + tracing::info!("[trigger-pipeline] Recorded violation #{} ({} km/h)", v.id, v.measured_speed); + let _ = v_tx.send(v); + + // ponytail: pre-cache thumbnails in background across multicore pool + let store_pre = store_clone.clone(); + let pre_bytes = jpg_bytes.clone(); + let pre_path = img_path.clone(); + rayon::spawn(move || { + let p_grid = storage::compress::CompressParams { width: Some(400), quality: Some(80), ..Default::default() }; + let p_row = storage::compress::CompressParams { width: Some(160), quality: Some(75), ..Default::default() }; + let _ = store_pre.compressor.process_image(&pre_bytes, &pre_path, &p_grid); + let _ = store_pre.compressor.process_image(&pre_bytes, &pre_path, &p_row); + }); + } + } + } else { + tracing::warn!("[trigger-pipeline] Failed to capture frame during speeding event"); + } + }); + } + } + Err(tokio::sync::broadcast::error::RecvError::Lagged(missed)) => { + tracing::warn!("[trigger-pipeline] Serial receiver lagged by {} messages", missed); + } + Err(tokio::sync::broadcast::error::RecvError::Closed) => { + tracing::info!("[trigger-pipeline] Serial channel closed, exiting pipeline task"); + break; + } + } + } + }); + + // Build and launch Axum web server + let bind_addr = format!("{}:{}", config.host, config.port); + let app = web::build_app(config, db, store, camera, serial, violation_tx, armed, armed_tx); + let listener = tokio::net::TcpListener::bind(&bind_addr).await?; + tracing::info!(" 🚀 Server listening on http://{}", bind_addr); + axum::serve(listener, app).await?; + + Ok(()) +} diff --git a/headless-rust/src/models.rs b/headless-rust/src/models.rs new file mode 100644 index 0000000..07aaca5 --- /dev/null +++ b/headless-rust/src/models.rs @@ -0,0 +1,472 @@ +use serde::{Deserialize, Serialize}; + +// ─── Domain Models ──────────────────────────────────────────────────────────── + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct NetworkInterfaceDetail { + pub name: string_or_empty::StringOrEmpty, + pub role: String, // "camera-lan" | "hotspot-ap" | "wifi-client" | "other" | "loopback" + pub address: String, + pub family: String, + pub netmask: String, + pub mac: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub expected_ip: Option, + pub is_configured: bool, +} + +mod string_or_empty { + pub type StringOrEmpty = String; +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SubnetInfo { + pub interface_name: Option, + pub ip: Option, + pub expected_ip: String, + pub subnet: String, + pub status: String, // "ok" | "ip_mismatch" | "missing" | "inactive" + pub description: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WifiClientInfo { + pub interface_name: Option, + pub ssid: Option, + pub ip: Option, + pub subnet: Option, + pub gateway: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub signal_dbm: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub power_save: Option, + pub status: String, // "connected" | "connecting" | "disconnected" | "inactive" + pub description: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SystemNetworkSummary { + #[serde(default = "default_network_mode")] + pub mode: String, // "ap" | "client" | "field" | "wifi-client" | "dhcp" | "custom" + #[serde(default = "default_wifi_mode")] + pub wifi_mode: String, // "ap" | "client" | "disconnected" + #[serde(default = "default_ethernet_mode")] + pub ethernet_mode: String, // "camera-lan" | "dhcp" | "unmanaged" + #[serde(default, skip_serializing_if = "Option::is_none")] + pub wifi_mac: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ethernet_mac: Option, + pub camera_lan: SubnetInfo, + pub hotspot_ap: SubnetInfo, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub wifi_client: Option, + pub interfaces: Vec, +} + +fn default_network_mode() -> String { + "ap".to_string() +} + +fn default_wifi_mode() -> String { + "ap".to_string() +} + +fn default_ethernet_mode() -> String { + "camera-lan".to_string() +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WifiScanResult { + pub ssid: String, + #[serde(default)] + pub bssid: String, + #[serde(default)] + pub channel: u32, + pub signal: i32, + pub security: String, + pub in_use: bool, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ApplyNetworkModeInput { + pub mode: String, // "ap" | "client" | "forget" | "lan-camera" | "lan-dhcp" | "dhcp" + #[serde(default)] + pub ssid: Option, + #[serde(default)] + pub password: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct NetworkOperationResult { + pub success: bool, + pub mode: String, + pub message: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub details: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Violation { + pub id: i64, + pub timestamp: String, + pub measured_speed: f64, + pub max_speed: f64, + pub direction: String, // "forward" | "reverse" + pub image_path: String, + pub created_at: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SaveViolationInput { + #[serde(default)] + pub image_base64: Option, + pub measured_speed: f64, + pub max_speed: f64, + #[serde(default = "default_direction")] + pub direction: String, +} + +fn default_direction() -> String { + "forward".to_string() +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AppSettings { + pub max_speed: f64, + pub selected_port: String, + // Industrial Camera Settings + pub camera_exposure: f64, + pub camera_gain: f64, + pub strobe_line_duration: f64, + pub pixel_format: String, + pub exposure_auto: String, + pub gain_auto: String, + pub frame_rate: f64, + pub camera_width: i64, + pub camera_height: i64, + pub black_level: f64, + // Lap timer settings + pub lap_mode: String, + pub lap_save_images: String, + pub lap_dir_filter: String, + // Teable integration + pub teable_url: String, + pub teable_token: String, + pub teable_user_name: String, + pub teable_user_email: String, + pub teable_user_avatar: String, + pub teable_space_id: String, + pub teable_base_id: String, + pub teable_table_id: String, + pub teable_sync_enabled: String, + // GitHub + pub github_token: String, + // Poliscan skin + pub skin_measuring_location: String, +} + +impl Default for AppSettings { + fn default() -> Self { + Self { + max_speed: 30.0, + selected_port: String::new(), + camera_exposure: 5000.0, + camera_gain: 0.0, + strobe_line_duration: 5000.0, + pixel_format: "Mono".to_string(), + exposure_auto: "Off".to_string(), + gain_auto: "Off".to_string(), + frame_rate: 30.0, + camera_width: 1280, + camera_height: 1024, + black_level: 0.0, + lap_mode: "single".to_string(), + lap_save_images: "true".to_string(), + lap_dir_filter: "both".to_string(), + teable_url: String::new(), + teable_token: String::new(), + teable_user_name: String::new(), + teable_user_email: String::new(), + teable_user_avatar: String::new(), + teable_space_id: String::new(), + teable_base_id: String::new(), + teable_table_id: String::new(), + teable_sync_enabled: "false".to_string(), + github_token: String::new(), + skin_measuring_location: String::new(), + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PortInfo { + pub path: String, + pub manufacturer: Option, + pub serial_number: Option, + pub pnp_id: Option, + pub location_id: Option, + pub product_id: Option, + pub vendor_id: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CameraStatusPayload { + pub connected: bool, + pub vendor: Option, + pub model: Option, + pub serial: Option, + pub is_streaming: bool, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct MfsConfigResult { + pub applied: Vec, + pub failed: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ViolationQuery { + pub page: i64, + pub limit: i64, + pub date_from: Option, + pub date_to: Option, + pub min_speed: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ViolationPage { + pub violations: Vec, + pub total: i64, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LapSession { + pub id: i64, + pub started_at: String, + pub ended_at: Option, + pub lap_mode: String, + pub created_at: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Lap { + pub id: i64, + pub session_id: i64, + pub lap_number: i64, + pub start_timestamp: i64, + pub end_timestamp: i64, + pub duration_ms: i64, + pub speed_at_start: f64, + pub speed_at_end: f64, + pub start_image_path: Option, + pub end_image_path: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LapSessionWithLaps { + pub id: i64, + pub started_at: String, + pub ended_at: Option, + pub lap_mode: String, + pub created_at: String, + pub laps: Vec, +} + +fn deserialize_duration_ms<'de, D>(deserializer: D) -> Result +where + D: serde::Deserializer<'de>, +{ + #[derive(Deserialize)] + #[serde(untagged)] + enum IntOrFloat { + Int(i64), + Float(f64), + } + match IntOrFloat::deserialize(deserializer)? { + IntOrFloat::Int(i) => Ok(i), + IntOrFloat::Float(f) => Ok(f.round() as i64), + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SaveLapInput { + pub session_id: i64, + pub lap_number: i64, + pub start_timestamp: i64, + pub end_timestamp: i64, + #[serde(deserialize_with = "deserialize_duration_ms")] + pub duration_ms: i64, + pub speed_at_start: f64, + pub speed_at_end: f64, + pub start_image_base64: Option, + pub end_image_base64: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct EspPongConfig { + pub max_speed: f64, + #[serde(default)] + pub flash_delay: Option, + #[serde(default)] + pub flash_duration: Option, + pub sensor_distance: f64, + pub debug_enabled: bool, + pub lap_mode: String, + pub lap_active: bool, + #[serde(default)] + pub lap_auto_flash: Option, + pub lap_dir_filter: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SerialStatusInfo { + pub connected: bool, + pub port: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(tag = "status")] +pub enum SerialStatusPayload { + #[serde(rename = "SPEEDING")] + Speeding { + value: f64, + tolerance: f64, + direction: String, + timestamp: i64, + }, + #[serde(rename = "OK")] + Ok { + value: f64, + tolerance: f64, + direction: String, + timestamp: i64, + }, + #[serde(rename = "PONG")] + Pong { config: EspPongConfig }, + #[serde(rename = "LAPSTART")] + LapStart { + #[serde(rename = "lapNumber")] + lap_number: i64, + #[serde(rename = "speedAtStart")] + speed_at_start: f64, + timestamp: i64, + }, + #[serde(rename = "LAPEND")] + LapEnd { + #[serde(rename = "lapNumber")] + lap_number: i64, + #[serde(rename = "durationMs")] + duration_ms: f64, + #[serde(rename = "speedAtStart")] + speed_at_start: f64, + #[serde(rename = "speedAtEnd")] + speed_at_end: f64, + timestamp: i64, + }, + #[serde(rename = "LAPWAITING")] + LapWaiting, + #[serde(rename = "LAPSTOPPED")] + LapStopped, + #[serde(rename = "CONNECTED")] + Connected { + #[serde(default, skip_serializing_if = "Option::is_none")] + port: Option, + }, + #[serde(rename = "DISCONNECTED")] + Disconnected, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(tag = "type")] +pub enum FlashProgressPayload { + #[serde(rename = "downloading")] + Downloading, + #[serde(rename = "output")] + Output { line: String }, + #[serde(rename = "done")] + Done, + #[serde(rename = "error")] + Error { message: String }, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct GithubRelease { + pub tag: String, + pub name: String, + pub published_at: String, + pub prerelease: bool, + pub firmware_asset_api_url: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TeableUser { + pub id: String, + pub name: String, + pub email: String, + pub avatar: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TeableSpace { + pub id: String, + pub name: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TeableBase { + pub id: String, + pub name: String, + pub space_id: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TeableTable { + pub id: String, + pub name: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +#[allow(dead_code)] +pub struct TeableSchemaCheck { + pub missing_fields: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SyncLapInput { + pub lap: Lap, + pub session: LapSession, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ExportSkinnedResult { + pub exported: usize, + pub failed: usize, +} diff --git a/headless-rust/src/network/mod.rs b/headless-rust/src/network/mod.rs new file mode 100644 index 0000000..6af2356 --- /dev/null +++ b/headless-rust/src/network/mod.rs @@ -0,0 +1,452 @@ +use crate::models::{ + ApplyNetworkModeInput, NetworkInterfaceDetail, NetworkOperationResult, SubnetInfo, + SystemNetworkSummary, WifiClientInfo, WifiScanResult, +}; +use std::collections::HashMap; +use std::path::Path; +use std::process::Command; + +/// Reads hardware MAC address from Linux sysfs (/sys/class/net//address) +fn get_interface_mac(iface: &str) -> String { + let path = format!("/sys/class/net/{}/address", iface); + std::fs::read_to_string(&path) + .map(|s| s.trim().to_uppercase()) + .unwrap_or_default() +} + +pub fn get_system_network_summary() -> SystemNetworkSummary { + let mut interfaces = Vec::new(); + let mut camera_lan_iface: Option = None; + let mut hotspot_ap_iface: Option = None; + let mut wifi_client_iface: Option = None; + let mut detected_wifi_name: Option = None; + let mut detected_eth_name: Option = None; + + // Use nix getifaddrs to inspect active IPv4 network interfaces + if let Ok(ifaddrs) = nix::ifaddrs::getifaddrs() { + let mut map: HashMap = HashMap::new(); // name -> (ip, netmask) + + for ifaddr in ifaddrs { + if let Some(addr) = ifaddr.address { + if let Some(sock_addr) = addr.as_sockaddr_in() { + let ip = std::net::Ipv4Addr::from(sock_addr.ip()).to_string(); + let netmask = ifaddr + .netmask + .and_then(|nm| nm.as_sockaddr_in().map(|s| std::net::Ipv4Addr::from(s.ip()).to_string())) + .unwrap_or_else(|| "255.255.255.0".to_string()); + + map.insert(ifaddr.interface_name.clone(), (ip, netmask)); + } + } + } + + for (name, (ip, netmask)) in map { + let is_loopback = name == "lo" || ip.starts_with("127."); + let is_camera_ip = ip == "192.168.1.100" || ip.starts_with("192.168.1."); + let is_hotspot_ip = ip == "192.168.4.1"; + let is_eth_name = name.starts_with("eth") || name.starts_with("end") || name.starts_with("enp"); + let is_wifi_name = name.starts_with("wlan") || name.starts_with("wifi") || name.starts_with("wlp"); + + if is_wifi_name { + detected_wifi_name = Some(name.clone()); + } + if is_eth_name && detected_eth_name.is_none() { + detected_eth_name = Some(name.clone()); + } + + let role = if is_loopback { + "loopback" + } else if is_camera_ip || is_eth_name { + "camera-lan" + } else if is_hotspot_ip { + "hotspot-ap" + } else if is_wifi_name { + "wifi-client" + } else { + "other" + }; + + let expected_ip = if role == "camera-lan" { + Some("192.168.1.100".to_string()) + } else if role == "hotspot-ap" { + Some("192.168.4.1".to_string()) + } else { + None + }; + + let is_configured = match &expected_ip { + Some(exp) => &ip == exp, + None => true, + }; + + let mac = get_interface_mac(&name); + + let detail = NetworkInterfaceDetail { + name: name.clone(), + role: role.to_string(), + address: ip.clone(), + family: "IPv4".to_string(), + netmask, + mac, + expected_ip, + is_configured, + }; + + if role == "camera-lan" && (camera_lan_iface.is_none() || ip == "192.168.1.100") { + camera_lan_iface = Some(detail.clone()); + } + + if role == "hotspot-ap" { + hotspot_ap_iface = Some(detail.clone()); + } else if role == "wifi-client" { + wifi_client_iface = Some(detail.clone()); + } + + interfaces.push(detail); + } + } + + let wifi_iface_name = detected_wifi_name.unwrap_or_else(|| "wlan0".to_string()); + let eth_iface_name = detected_eth_name.unwrap_or_else(|| "eth0".to_string()); + + let wifi_mac = { + let mac = get_interface_mac(&wifi_iface_name); + if mac.is_empty() { None } else { Some(mac) } + }; + + let ethernet_mac = { + let mac = get_interface_mac(ð_iface_name); + if mac.is_empty() { None } else { Some(mac) } + }; + + let camera_status = match &camera_lan_iface { + None => "missing", + Some(iface) if iface.address == "192.168.1.100" => "ok", + Some(_) => "ip_mismatch", + }; + + // Determine Ethernet mode + let ethernet_mode = if let Some(ref iface) = camera_lan_iface { + if iface.address == "192.168.1.100" { + "camera-lan".to_string() + } else { + "dhcp".to_string() + } + } else { + "unmanaged".to_string() + }; + + // Determine Wi-Fi active connection mode & details + let (active_ssid, signal_dbm, power_save_status, default_gateway) = query_wifi_runtime_info(&wifi_iface_name); + + let (mode, wifi_mode, hotspot_status, wifi_client_info) = if let Some(ref hs) = hotspot_ap_iface { + let status = if hs.address == "192.168.4.1" { "ok" } else { "ip_mismatch" }; + ( + "ap".to_string(), + "ap".to_string(), + status.to_string(), + None, + ) + } else if let Some(ref client) = wifi_client_iface { + let client_info = WifiClientInfo { + interface_name: Some(client.name.clone()), + ssid: active_ssid, + ip: Some(client.address.clone()), + subnet: Some(format!("{}/24", client.address.rsplit_once('.').map(|(p, _)| p).unwrap_or("192.168.0"))), + gateway: default_gateway, + signal_dbm, + power_save: power_save_status, + status: "connected".to_string(), + description: "Wi-Fi Client connected to external router (Station mode)".to_string(), + }; + ( + "client".to_string(), + "client".to_string(), + "inactive".to_string(), + Some(client_info), + ) + } else { + ( + "ap".to_string(), + "disconnected".to_string(), + "missing".to_string(), + None, + ) + }; + + SystemNetworkSummary { + mode, + wifi_mode, + ethernet_mode, + wifi_mac, + ethernet_mac, + camera_lan: SubnetInfo { + interface_name: camera_lan_iface.as_ref().map(|i| i.name.clone()), + ip: camera_lan_iface.as_ref().map(|i| i.address.clone()), + expected_ip: "192.168.1.100".to_string(), + subnet: "192.168.1.0/24".to_string(), + status: camera_status.to_string(), + description: "Dedicated GigE Vision Industrial Camera LAN (eth0/end0)".to_string(), + }, + hotspot_ap: SubnetInfo { + interface_name: hotspot_ap_iface.as_ref().map(|i| i.name.clone()).or(Some(wifi_iface_name)), + ip: hotspot_ap_iface.as_ref().map(|i| i.address.clone()), + expected_ip: "192.168.4.1".to_string(), + subnet: "192.168.4.0/24".to_string(), + status: hotspot_status, + description: "Open Wi-Fi Hotspot AP & Web Setup (wlan0/wifi0)".to_string(), + }, + wifi_client: wifi_client_info, + interfaces, + } +} + +/// 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; + let mut signal_dbm = None; + let mut power_save = None; + let mut gateway = None; + + // 1. Query active SSID via nmcli or iw + if let Ok(output) = Command::new("nmcli") + .args(["-t", "-f", "ACTIVE,SSID", "dev", "wifi"]) + .output() + { + if output.status.success() { + let text = String::from_utf8_lossy(&output.stdout); + for line in text.lines() { + if line.starts_with("yes:") { + let s = line.trim_start_matches("yes:").trim(); + if !s.is_empty() { + ssid = Some(s.to_string()); + break; + } + } + } + } + } + + if ssid.is_none() { + if let Ok(output) = Command::new("iw").args(["dev", wifi_iface, "link"]).output() { + if output.status.success() { + let text = String::from_utf8_lossy(&output.stdout); + for line in text.lines() { + let trimmed = line.trim(); + if trimmed.starts_with("SSID: ") { + ssid = Some(trimmed.trim_start_matches("SSID: ").to_string()); + } else if trimmed.starts_with("signal: ") { + if let Some(dbm_str) = trimmed.split_whitespace().nth(1) { + signal_dbm = dbm_str.parse::().ok(); + } + } + } + } + } + } + + // 2. Query power save status + if let Ok(output) = Command::new("iw").args(["dev", wifi_iface, "get", "power_save"]).output() { + if output.status.success() { + let text = String::from_utf8_lossy(&output.stdout); + power_save = text.split_whitespace().last().map(|s| s.to_string()); + } + } + + // 3. Query default gateway via `ip route` + if let Ok(output) = Command::new("ip").args(["route", "show", "default"]).output() { + if output.status.success() { + let text = String::from_utf8_lossy(&output.stdout); + let parts: Vec<&str> = text.split_whitespace().collect(); + if parts.len() >= 3 && parts[0] == "default" && parts[1] == "via" { + gateway = Some(parts[2].to_string()); + } + } + } + + (ssid, signal_dbm, power_save, gateway) +} + +/// Scans for visible 2.4GHz & 5GHz Wi-Fi networks +pub fn scan_wifi_networks() -> Vec { + let mut seen_ssids: HashMap = HashMap::new(); + + if let Ok(output) = Command::new("nmcli") + .args(["-t", "-f", "SSID,BSSID,CHAN,SIGNAL,SECURITY,IN-USE", "dev", "wifi", "list", "--rescan", "auto"]) + .output() + { + if output.status.success() { + let text = String::from_utf8_lossy(&output.stdout); + for line in text.lines() { + // Split with care: BSSID has colons, so nmcli escapes or separates with colon. + // When using -t (terse), nmcli escapes colons inside fields with \: + let parts: Vec<&str> = line.split(':').collect(); + if parts.len() >= 4 { + // With BSSID having 5 colons (e.g. AA:BB:CC:DD:EE:FF), parts length is typically >= 10 + let (ssid, bssid, channel, signal, security, in_use) = if parts.len() >= 10 { + let ssid = parts[0].trim().to_string(); + let bssid = format!("{}:{}:{}:{}:{}:{}", parts[1], parts[2], parts[3], parts[4], parts[5], parts[6]); + let chan = parts[7].trim().parse::().unwrap_or(0); + let sig = parts[8].trim().parse::().unwrap_or(0); + let sec = parts[9].trim().to_string(); + let in_u = parts.get(10).map(|s| s.trim().eq_ignore_ascii_case("yes") || *s == "*").unwrap_or(false); + (ssid, bssid, chan, sig, sec, in_u) + } else { + // Fallback parsing + let ssid = parts[0].trim().to_string(); + let sig = parts.iter().find_map(|p| p.trim().parse::().ok()).unwrap_or(0); + let sec = parts.last().map(|s| s.trim().to_string()).unwrap_or_default(); + let in_u = parts.iter().any(|p| p.trim().eq_ignore_ascii_case("yes") || *p == "*"); + (ssid, String::new(), 0, sig, sec, in_u) + }; + + if ssid.is_empty() || ssid == "--" { + continue; + } + + let item = WifiScanResult { + ssid: ssid.clone(), + bssid, + channel, + signal, + security: if security.is_empty() { "Open".to_string() } else { security }, + in_use, + }; + + if let Some(existing) = seen_ssids.get_mut(&ssid) { + if item.in_use { + existing.in_use = true; + } + if item.signal > existing.signal { + existing.signal = item.signal; + existing.bssid = item.bssid; + existing.channel = item.channel; + } + } else { + seen_ssids.insert(ssid, item); + } + } + } + } + } + + let mut results: Vec = seen_ssids.into_values().collect(); + results.sort_by(|a, b| { + if a.in_use != b.in_use { + b.in_use.cmp(&a.in_use) + } else { + b.signal.cmp(&a.signal) + } + }); + + results +} + +/// Applies a network mode switch (AP, Wi-Fi Client, Forget Wi-Fi, Ethernet LAN, Ethernet DHCP, or standard DHCP) +pub fn apply_network_mode(input: &ApplyNetworkModeInput) -> 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"), + Path::new("/root/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(|| Path::new("./scripts/setup-network.sh").to_path_buf()); + + let normalized_mode = input.mode.to_lowercase(); + let mut cmd = Command::new("sudo"); + cmd.arg(&script); + + match normalized_mode.as_str() { + "ap" | "field" | "hotspot" => { + cmd.arg("ap"); + } + "client" | "wifi-client" | "internet" | "wifi" => { + let ssid = match &input.ssid { + Some(s) if !s.trim().is_empty() => s.trim(), + _ => { + return NetworkOperationResult { + success: false, + mode: input.mode.clone(), + message: "SSID is required to connect to a Wi-Fi network in Client mode.".to_string(), + details: None, + }; + } + }; + cmd.arg("client").arg(ssid); + if let Some(pass) = &input.password { + if !pass.is_empty() { + cmd.arg(pass); + } + } + } + "forget" | "reset-wifi" => { + cmd.arg("forget"); + } + "lan-camera" | "camera-lan" => { + cmd.arg("lan-camera"); + } + "lan-dhcp" | "ethernet-dhcp" => { + cmd.arg("lan-dhcp"); + } + "auto" => { + cmd.arg("auto"); + } + "dhcp" | "reset" => { + cmd.arg("dhcp"); + } + other => { + return NetworkOperationResult { + success: false, + mode: input.mode.clone(), + message: format!("Unknown network mode '{}'.", other), + details: None, + }; + } + } + + tracing::info!("[network] Executing mode transition: {:?}", cmd); + + match cmd.output() { + Ok(output) => { + let stdout = String::from_utf8_lossy(&output.stdout).to_string(); + let stderr = String::from_utf8_lossy(&output.stderr).to_string(); + let details = if !stderr.is_empty() { + format!("{}\n{}", stdout, stderr) + } else { + stdout.clone() + }; + + if output.status.success() { + tracing::info!("[network] Mode transition to '{}' succeeded", normalized_mode); + NetworkOperationResult { + success: true, + mode: normalized_mode, + message: format!("Network mode '{}' applied successfully.", input.mode), + details: Some(details), + } + } else { + tracing::warn!("[network] Mode transition failed with exit code {:?}: {}", output.status.code(), details); + NetworkOperationResult { + success: false, + mode: normalized_mode, + message: format!("Failed to apply network mode '{}'.", input.mode), + details: Some(details), + } + } + } + Err(err) => { + tracing::error!("[network] Failed to spawn network script: {}", err); + NetworkOperationResult { + success: false, + mode: normalized_mode, + message: format!("Failed to execute network script: {}", err), + details: None, + } + } + } +} diff --git a/headless-rust/src/serial/mock.rs b/headless-rust/src/serial/mock.rs new file mode 100644 index 0000000..fe08121 --- /dev/null +++ b/headless-rust/src/serial/mock.rs @@ -0,0 +1,176 @@ +use crate::models::{EspPongConfig, SerialStatusPayload}; +use serde_json::Value; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::Instant; +use tokio::sync::broadcast; + +#[derive(Clone, Copy, PartialEq, Eq)] +enum MockLapState { + Idle, + Waiting, + Timing, +} + +struct MockState { + lap_state: MockLapState, + lap_mode: String, + lap_number: i64, + lap_start_time: Option, + lap_start_speed: f64, +} + +pub struct MockSerial { + #[allow(dead_code)] + running: Arc, + state: Arc>, +} + +impl MockSerial { + pub fn new(tx: broadcast::Sender) -> Self { + let running = Arc::new(AtomicBool::new(true)); + let state = Arc::new(Mutex::new(MockState { + lap_state: MockLapState::Idle, + lap_mode: "single".to_string(), + lap_number: 1, + lap_start_time: None, + lap_start_speed: 0.0, + })); + + let r = running.clone(); + let s = state.clone(); + + tokio::spawn(async move { + let mut counter = 0; + while r.load(Ordering::SeqCst) { + tokio::time::sleep(tokio::time::Duration::from_secs(4)).await; + counter += 1; + + let now = chrono::Utc::now().timestamp_millis(); + let speed = 35.0 + (counter % 15) as f64; + + let mut guard = s.lock().unwrap(); + match guard.lap_state { + MockLapState::Idle => { + let payload = if speed > 40.0 { + SerialStatusPayload::Speeding { + value: speed, + tolerance: 3.0, + direction: "forward".to_string(), + timestamp: now, + } + } else { + SerialStatusPayload::Ok { + value: speed, + tolerance: 3.0, + direction: "forward".to_string(), + timestamp: now, + } + }; + let _ = tx.send(payload); + } + MockLapState::Waiting => { + // First car pass starts the lap + let _ = tx.send(SerialStatusPayload::Ok { + value: speed, + tolerance: 0.5, + direction: "forward".to_string(), + timestamp: now, + }); + guard.lap_state = MockLapState::Timing; + guard.lap_start_time = Some(Instant::now()); + guard.lap_start_speed = speed; + let _ = tx.send(SerialStatusPayload::LapStart { + lap_number: guard.lap_number, + speed_at_start: speed, + timestamp: now, + }); + } + MockLapState::Timing => { + // Second car pass finishes the lap + let start_time = guard.lap_start_time.unwrap_or_else(Instant::now); + let duration_ms = start_time.elapsed().as_secs_f64() * 1000.0; + let start_speed = guard.lap_start_speed; + let end_speed = speed; + let lap_num = guard.lap_number; + + let _ = tx.send(SerialStatusPayload::Ok { + value: end_speed, + tolerance: 0.5, + direction: "forward".to_string(), + timestamp: now, + }); + + let _ = tx.send(SerialStatusPayload::LapEnd { + lap_number: lap_num, + duration_ms, + speed_at_start: start_speed, + speed_at_end: end_speed, + timestamp: now, + }); + + if guard.lap_mode == "multi" { + guard.lap_number += 1; + guard.lap_start_time = Some(Instant::now()); + guard.lap_start_speed = end_speed; + let _ = tx.send(SerialStatusPayload::LapStart { + lap_number: guard.lap_number, + speed_at_start: end_speed, + timestamp: now, + }); + } else { + guard.lap_state = MockLapState::Waiting; + guard.lap_number = 1; + guard.lap_start_time = None; + guard.lap_start_speed = 0.0; + } + } + } + } + }); + + Self { running, state } + } + + pub fn send_command(&self, json: &str, tx: &broadcast::Sender) { + if let Ok(v) = serde_json::from_str::(json) { + let cmd = v["command"].as_str().unwrap_or(""); + match cmd { + "startLapSession" => { + let mode = v["mode"].as_str().unwrap_or("single").to_string(); + let mut guard = self.state.lock().unwrap(); + guard.lap_state = MockLapState::Waiting; + guard.lap_mode = mode; + guard.lap_number = 1; + guard.lap_start_time = None; + guard.lap_start_speed = 0.0; + let _ = tx.send(SerialStatusPayload::LapWaiting); + } + "stopLapSession" => { + let mut guard = self.state.lock().unwrap(); + guard.lap_state = MockLapState::Idle; + guard.lap_start_time = None; + guard.lap_start_speed = 0.0; + let _ = tx.send(SerialStatusPayload::LapStopped); + } + "ping" => { + let guard = self.state.lock().unwrap(); + let _ = tx.send(SerialStatusPayload::Pong { + config: EspPongConfig { + max_speed: 30.0, + flash_delay: Some(0.0), + flash_duration: Some(5000.0), + sensor_distance: 1.0, + debug_enabled: false, + lap_mode: guard.lap_mode.clone(), + lap_active: guard.lap_state != MockLapState::Idle, + lap_auto_flash: Some(true), + lap_dir_filter: "both".to_string(), + }, + }); + } + _ => {} + } + } + } +} diff --git a/headless-rust/src/serial/mod.rs b/headless-rust/src/serial/mod.rs new file mode 100644 index 0000000..08c4c13 --- /dev/null +++ b/headless-rust/src/serial/mod.rs @@ -0,0 +1,293 @@ +pub mod mock; +pub mod protocol; + +use crate::models::{PortInfo, SerialStatusInfo, SerialStatusPayload}; +use protocol::EspMessage; +use std::io::{BufRead, BufReader, Write}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; +use tokio::sync::broadcast; + +pub struct SerialService { + mock_mode: bool, + mock_serial: Mutex>, + active_port: Mutex>>, + active_path: Mutex, + session_id: Arc, + is_running: Arc, + status_sender: broadcast::Sender, +} + +impl SerialService { + pub fn new(mock_mode: bool) -> Arc { + let (status_tx, _) = broadcast::channel(32); + + let initial_path = if mock_mode { + "/dev/ttyUSB0 (MOCK)".to_string() + } else { + String::new() + }; + + let service = Arc::new(Self { + mock_mode, + mock_serial: Mutex::new(None), + active_port: Mutex::new(None), + active_path: Mutex::new(initial_path), + session_id: Arc::new(AtomicU64::new(0)), + is_running: Arc::new(AtomicBool::new(true)), + status_sender: status_tx, + }); + + if mock_mode { + let mock = mock::MockSerial::new(service.status_sender.clone()); + *service.mock_serial.lock().unwrap() = Some(mock); + } + + service + } + + pub fn subscribe(&self) -> broadcast::Receiver { + self.status_sender.subscribe() + } + + pub fn get_status(&self) -> SerialStatusInfo { + let active_path = self.active_path.lock().unwrap().clone(); + let is_conn = if self.mock_mode { + self.mock_serial.lock().unwrap().is_some() && !active_path.is_empty() + } else { + self.active_port.lock().unwrap().is_some() + }; + + SerialStatusInfo { + connected: is_conn, + port: if is_conn && !active_path.is_empty() { + Some(active_path) + } else { + None + }, + } + } + + pub fn get_status_payload(&self) -> SerialStatusPayload { + let status = self.get_status(); + if status.connected { + SerialStatusPayload::Connected { port: status.port } + } else { + SerialStatusPayload::Disconnected + } + } + + pub fn list_ports(&self) -> Vec { + if self.mock_mode { + return vec![PortInfo { + path: "/dev/ttyUSB0 (MOCK)".to_string(), + manufacturer: Some("FTDI (MOCK)".to_string()), + serial_number: Some("MOCK_SERIAL_PORT".to_string()), + pnp_id: None, + location_id: None, + product_id: Some("0x6001".to_string()), + vendor_id: Some("0x0403".to_string()), + }]; + } + + match serialport::available_ports() { + Ok(ports) => ports + .into_iter() + .map(|p| { + let mut manufacturer = None; + let mut serial_number = None; + let mut product_id = None; + let mut vendor_id = None; + + if let serialport::SerialPortType::UsbPort(info) = p.port_type { + manufacturer = info.manufacturer; + serial_number = info.serial_number; + product_id = Some(format!("0x{:04x}", info.pid)); + vendor_id = Some(format!("0x{:04x}", info.vid)); + } + + PortInfo { + path: p.port_name, + manufacturer, + serial_number, + pnp_id: None, + location_id: None, + product_id, + vendor_id, + } + }) + .collect(), + Err(e) => { + tracing::warn!("[serial] Failed to list ports: {}", e); + Vec::new() + } + } + } + + pub fn open_port(self: &Arc, port_path: &str) { + if self.mock_mode { + tracing::info!("[serial] Opened mock port {}", port_path); + *self.active_path.lock().unwrap() = port_path.to_string(); + let _ = self.status_sender.send(SerialStatusPayload::Connected { + port: Some(port_path.to_string()), + }); + return; + } + + // Invalidate previous session and close previous port handles + let session = self.session_id.fetch_add(1, Ordering::SeqCst) + 1; + { + let mut current_path = self.active_path.lock().unwrap(); + *current_path = port_path.to_string(); + let mut port_guard = self.active_port.lock().unwrap(); + *port_guard = None; + } + + let this = self.clone(); + let path = port_path.to_string(); + + tokio::task::spawn_blocking(move || { + // Give OS 50ms to release the descriptor from any previous reader thread + std::thread::sleep(Duration::from_millis(50)); + + if this.session_id.load(Ordering::SeqCst) != session { + return; + } + + let builder = serialport::new(&path, 115_200).timeout(Duration::from_millis(500)); + match builder.open() { + Ok(port) => { + tracing::info!("[serial] Successfully opened {}", path); + let _ = this.status_sender.send(SerialStatusPayload::Connected { + port: Some(path.clone()), + }); + + let reader_port = match port.try_clone() { + Ok(p) => p, + Err(e) => { + tracing::warn!("[serial] Failed to clone port for reading: {}", e); + return; + } + }; + + *this.active_port.lock().unwrap() = Some(port); + + let mut reader = BufReader::new(reader_port); + let mut line_buf = String::new(); + + while this.is_running.load(Ordering::SeqCst) + && this.session_id.load(Ordering::SeqCst) == session + { + line_buf.clear(); + match reader.read_line(&mut line_buf) { + Ok(0) => { + // EOF: Serial hardware disconnected or reset + tracing::warn!("[serial] EOF on {} (device disconnected)", path); + break; + } + Ok(_) => { + let trimmed = line_buf.trim(); + if !trimmed.is_empty() { + this.handle_line(trimmed); + } + } + Err(ref e) if e.kind() == std::io::ErrorKind::TimedOut => { + // Expected timeout when idle + } + Err(e) => { + tracing::warn!("[serial] Read error on {}: {}", path, e); + break; + } + } + } + + // Only clean up state if this session is still the active one + if this.session_id.load(Ordering::SeqCst) == session { + tracing::info!("[serial] Port {} closed / disconnected", path); + *this.active_port.lock().unwrap() = None; + let _ = this.status_sender.send(SerialStatusPayload::Disconnected); + + // Trigger auto-reconnect if not explicitly closed by user + let configured_path = this.active_path.lock().unwrap().clone(); + if !configured_path.is_empty() && configured_path == path { + this.schedule_auto_reconnect(session, configured_path); + } + } + } + Err(e) => { + tracing::warn!("[serial] Failed to open {}: {}", path, e); + if this.session_id.load(Ordering::SeqCst) == session { + let _ = this.status_sender.send(SerialStatusPayload::Disconnected); + let configured_path = this.active_path.lock().unwrap().clone(); + if !configured_path.is_empty() && configured_path == path { + this.schedule_auto_reconnect(session, configured_path); + } + } + } + } + }); + } + + fn schedule_auto_reconnect(self: &Arc, session: u64, path: String) { + let this = self.clone(); + tokio::spawn(async move { + tokio::time::sleep(Duration::from_secs(2)).await; + + if !this.is_running.load(Ordering::SeqCst) + || this.session_id.load(Ordering::SeqCst) != session + { + return; + } + + let configured = this.active_path.lock().unwrap().clone(); + if configured.is_empty() || configured != path { + return; + } + + tracing::info!("[serial] Attempting auto-reconnect to {}...", path); + this.open_port(&path); + }); + } + + pub fn close_port(&self) { + // Invalidate current session so reader thread terminates immediately + self.session_id.fetch_add(1, Ordering::SeqCst); + *self.active_port.lock().unwrap() = None; + *self.active_path.lock().unwrap() = String::new(); + let _ = self.status_sender.send(SerialStatusPayload::Disconnected); + tracing::info!("[serial] Port manually closed"); + } + + pub fn send_command(&self, json: &str) { + if self.mock_mode { + if let Some(ref mock) = *self.mock_serial.lock().unwrap() { + mock.send_command(json, &self.status_sender); + } + return; + } + + let mut guard = self.active_port.lock().unwrap(); + if let Some(ref mut port) = *guard { + let mut data = json.as_bytes().to_vec(); + data.push(b'\n'); + if let Err(e) = port.write_all(&data).and_then(|_| port.flush()) { + tracing::warn!("[serial] Failed to write command: {}", e); + } + } + } + + fn handle_line(&self, line: &str) { + if let Ok(msg) = serde_json::from_str::(line) { + let timestamp = chrono::Utc::now().timestamp_millis(); + if let Some(payload) = msg.to_serial_status(timestamp) { + let _ = self.status_sender.send(payload); + } + } else { + // Check if debug message + if !line.contains("\"debug\"") { + tracing::debug!("[serial] Raw: {}", line); + } + } + } +} diff --git a/headless-rust/src/serial/protocol.rs b/headless-rust/src/serial/protocol.rs new file mode 100644 index 0000000..aa7452f --- /dev/null +++ b/headless-rust/src/serial/protocol.rs @@ -0,0 +1,100 @@ +use crate::models::{EspPongConfig, SerialStatusPayload}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(tag = "status")] +pub enum EspMessage { + #[serde(rename = "speeding")] + Speeding { + value: f64, + tolerance: f64, + direction: String, + }, + #[serde(rename = "legal")] + Legal { + value: f64, + tolerance: f64, + direction: String, + }, + #[serde(rename = "pong")] + Pong { config: EspPongConfig }, + #[serde(rename = "lapStart")] + LapStart { + #[serde(rename = "lapNumber")] + lap_number: i64, + #[serde(rename = "speedAtStart")] + speed_at_start: f64, + }, + #[serde(rename = "lapEnd")] + LapEnd { + #[serde(rename = "lapNumber")] + lap_number: i64, + #[serde(rename = "durationMs")] + duration_ms: f64, + #[serde(rename = "speedAtStart")] + speed_at_start: f64, + #[serde(rename = "speedAtEnd")] + speed_at_end: f64, + }, + #[serde(rename = "lapWaiting")] + LapWaiting, + #[serde(rename = "lapStopped")] + LapStopped, + #[serde(rename = "configError")] + ConfigError { message: String }, + #[serde(other)] + Unknown, +} + +impl EspMessage { + pub fn to_serial_status(&self, timestamp: i64) -> Option { + match self { + Self::Speeding { + value, + tolerance, + direction, + } => Some(SerialStatusPayload::Speeding { + value: *value, + tolerance: *tolerance, + direction: direction.clone(), + timestamp, + }), + Self::Legal { + value, + tolerance, + direction, + } => Some(SerialStatusPayload::Ok { + value: *value, + tolerance: *tolerance, + direction: direction.clone(), + timestamp, + }), + Self::Pong { config } => Some(SerialStatusPayload::Pong { + config: config.clone(), + }), + Self::LapStart { + lap_number, + speed_at_start, + } => Some(SerialStatusPayload::LapStart { + lap_number: *lap_number, + speed_at_start: *speed_at_start, + timestamp, + }), + Self::LapEnd { + lap_number, + duration_ms, + speed_at_start, + speed_at_end, + } => Some(SerialStatusPayload::LapEnd { + lap_number: *lap_number, + duration_ms: *duration_ms, + speed_at_start: *speed_at_start, + speed_at_end: *speed_at_end, + timestamp, + }), + Self::LapWaiting => Some(SerialStatusPayload::LapWaiting), + Self::LapStopped => Some(SerialStatusPayload::LapStopped), + Self::ConfigError { .. } | Self::Unknown => None, + } + } +} diff --git a/headless-rust/src/storage/compress.rs b/headless-rust/src/storage/compress.rs new file mode 100644 index 0000000..9ae0d36 --- /dev/null +++ b/headless-rust/src/storage/compress.rs @@ -0,0 +1,250 @@ +use fast_image_resize as fir; +use fast_image_resize::images::Image; +use fast_image_resize::IntoImageView; +use image::{DynamicImage, GenericImageView, ImageFormat}; +use std::fs; +use std::io::Cursor; +use std::path::{Path, PathBuf}; + +// ponytail: lightweight query/resize param struct with sensible defaults +#[derive(Debug, Clone, Default)] +pub struct CompressParams { + pub width: Option, + pub height: Option, + pub quality: Option, + pub format: Option, +} + +#[derive(Clone)] +pub struct ImageCompressor { + cache_dir: PathBuf, +} + +impl ImageCompressor { + pub fn new(images_dir: &Path) -> Self { + // ponytail: store thumbnails in a dedicated sibling cache folder + let cache_dir = images_dir.join(".thumbnails_cache"); + let _ = fs::create_dir_all(&cache_dir); + Self { cache_dir } + } + + /// Fast cache lookup or multicore SIMD compression + pub fn process_image( + &self, + raw_bytes: &[u8], + cache_identifier: &str, + params: &CompressParams, + ) -> Result<(Vec, &'static str), String> { + let width = params.width; + let height = params.height; + let quality = params.quality.unwrap_or(80).clamp(10, 100); + let requested_fmt = params.format.as_deref().unwrap_or("auto"); + + // If no resizing or format conversion requested, return original directly + if width.is_none() && height.is_none() && (requested_fmt == "auto" || requested_fmt == "original") { + let mime = if raw_bytes.starts_with(&[0xFF, 0xD8, 0xFF]) { + "image/jpeg" + } else if raw_bytes.starts_with(&[0x89, 0x50, 0x4E, 0x47]) { + "image/png" + } else if raw_bytes.starts_with(b"RIFF") && raw_bytes.len() > 12 && &raw_bytes[8..12] == b"WEBP" { + "image/webp" + } else { + "image/jpeg" + }; + return Ok((raw_bytes.to_vec(), mime)); + } + + // Generate deterministic cache filename + let ext = match requested_fmt { + "png" => "png", + "webp" => "webp", + _ => "jpg", + }; + let sanitized_id = cache_identifier + .chars() + .map(|c| if c.is_alphanumeric() || c == '-' || c == '_' { c } else { '_' }) + .collect::(); + let cache_filename = format!( + "{}_w{}_h{}_q{}.{}", + sanitized_id, + width.unwrap_or(0), + height.unwrap_or(0), + quality, + ext + ); + let cache_path = self.cache_dir.join(&cache_filename); + + // 1. Cache hit check (zero CPU overhead) + if cache_path.exists() { + if let Ok(cached_bytes) = fs::read(&cache_path) { + let mime = match ext { + "png" => "image/png", + "webp" => "image/webp", + _ => "image/jpeg", + }; + return Ok((cached_bytes, mime)); + } + } + + // 2. Multicore SIMD resize and compress + let img = image::load_from_memory(raw_bytes) + .map_err(|e| format!("Failed to decode image: {}", e))?; + let (orig_w, orig_h) = img.dimensions(); + + let (target_w, target_h) = match (width, height) { + (Some(w), Some(h)) => { + let ratio = (w as f64 / orig_w as f64).min(h as f64 / orig_h as f64); + let tw = (orig_w as f64 * ratio).round().max(1.0) as u32; + let th = (orig_h as f64 * ratio).round().max(1.0) as u32; + (tw, th) + } + (Some(w), None) => { + if w >= orig_w { + (orig_w, orig_h) + } else { + let ratio = w as f64 / orig_w as f64; + let th = (orig_h as f64 * ratio).round().max(1.0) as u32; + (w, th) + } + } + (None, Some(h)) => { + if h >= orig_h { + (orig_w, orig_h) + } else { + let ratio = h as f64 / orig_h as f64; + let tw = (orig_w as f64 * ratio).round().max(1.0) as u32; + (tw, h) + } + } + (None, None) => (orig_w, orig_h), + }; + + // Resize with fast_image_resize if dimensions changed + let resized_img = if target_w != orig_w || target_h != orig_h { + let mut dst_image = Image::new( + target_w, + target_h, + img.pixel_type().ok_or("Unsupported pixel format")?, + ); + let mut resizer = fir::Resizer::new(); + let options = fir::ResizeOptions::default() + .resize_alg(fir::ResizeAlg::Convolution(fir::FilterType::CatmullRom)); + + resizer + .resize(&img, &mut dst_image, &options) + .map_err(|e| format!("Resizing failed: {}", e))?; + + // Convert back to DynamicImage based on buffer format + match img { + DynamicImage::ImageRgb8(_) => { + DynamicImage::ImageRgb8(image::RgbImage::from_raw(target_w, target_h, dst_image.into_vec()).ok_or("Buffer mismatch")?) + } + DynamicImage::ImageRgba8(_) => { + DynamicImage::ImageRgba8(image::RgbaImage::from_raw(target_w, target_h, dst_image.into_vec()).ok_or("Buffer mismatch")?) + } + DynamicImage::ImageLuma8(_) => { + DynamicImage::ImageLuma8(image::GrayImage::from_raw(target_w, target_h, dst_image.into_vec()).ok_or("Buffer mismatch")?) + } + _ => { + let rgb = img.to_rgb8(); + let mut fallback_dst = Image::new(target_w, target_h, fir::PixelType::U8x3); + resizer.resize(&rgb, &mut fallback_dst, &options).map_err(|e| format!("Resizing fallback failed: {}", e))?; + DynamicImage::ImageRgb8(image::RgbImage::from_raw(target_w, target_h, fallback_dst.into_vec()).ok_or("Buffer mismatch")?) + } + } + } else { + img + }; + + // Encode to target format + let mut out_buffer = Cursor::new(Vec::new()); + let mime = match ext { + "png" => { + resized_img + .write_to(&mut out_buffer, ImageFormat::Png) + .map_err(|e| format!("PNG encode error: {}", e))?; + "image/png" + } + "webp" => { + // ponytail: fallback to JPEG if webp encoder fails + if resized_img.write_to(&mut out_buffer, ImageFormat::WebP).is_ok() { + "image/webp" + } else { + out_buffer.get_mut().clear(); + let mut enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out_buffer, quality); + enc.encode_image(&resized_img).map_err(|e| format!("JPEG fallback error: {}", e))?; + "image/jpeg" + } + } + _ => { + let mut enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out_buffer, quality); + enc.encode_image(&resized_img).map_err(|e| format!("JPEG encode error: {}", e))?; + "image/jpeg" + } + }; + + let result_bytes = out_buffer.into_inner(); + + // Save to cache asynchronously or synchronously (atomic best effort) + let _ = fs::write(&cache_path, &result_bytes); + + Ok((result_bytes, mime)) + } + + /// Clear cache directory + #[allow(dead_code)] + pub fn clear_cache(&self) -> std::io::Result<()> { + if self.cache_dir.exists() { + fs::remove_dir_all(&self.cache_dir)?; + fs::create_dir_all(&self.cache_dir)?; + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use image::{ImageBuffer, Rgb}; + + fn make_test_jpeg(width: u32, height: u32) -> Vec { + let img: ImageBuffer, Vec> = ImageBuffer::from_fn(width, height, |x, y| { + Rgb([(x % 255) as u8, (y % 255) as u8, 128]) + }); + let mut buf = Cursor::new(Vec::new()); + img.write_to(&mut buf, ImageFormat::Jpeg).unwrap(); + buf.into_inner() + } + + #[test] + fn test_image_compressor_resize_and_cache() { + let temp_dir = std::env::temp_dir().join(format!("speedcamera_test_{}", chrono::Utc::now().timestamp_nanos_opt().unwrap_or(0))); + let compressor = ImageCompressor::new(&temp_dir); + + let raw = make_test_jpeg(1280, 720); + let params = CompressParams { + width: Some(320), + quality: Some(75), + format: Some("jpeg".to_string()), + ..Default::default() + }; + + // First pass: compression & cache write + let (compressed1, mime1) = compressor.process_image(&raw, "test_cap_1", ¶ms).unwrap(); + assert_eq!(mime1, "image/jpeg"); + assert!(compressed1.len() < raw.len()); + + let decoded = image::load_from_memory(&compressed1).unwrap(); + assert_eq!(decoded.dimensions().0, 320); + assert_eq!(decoded.dimensions().1, 180); + + // Second pass: should hit cache with exact same bytes + let (compressed2, mime2) = compressor.process_image(&raw, "test_cap_1", ¶ms).unwrap(); + assert_eq!(mime2, "image/jpeg"); + assert_eq!(compressed1, compressed2); + + // Cleanup + let _ = compressor.clear_cache(); + let _ = fs::remove_dir_all(&temp_dir); + } +} diff --git a/headless-rust/src/storage/mod.rs b/headless-rust/src/storage/mod.rs new file mode 100644 index 0000000..e15f017 --- /dev/null +++ b/headless-rust/src/storage/mod.rs @@ -0,0 +1,83 @@ +pub mod compress; +pub mod skin; + +use base64::Engine; +use chrono::Utc; +use std::fs; +use std::path::{Path, PathBuf}; + +#[derive(Clone)] +pub struct FileStore { + pub images_dir: PathBuf, + pub compressor: compress::ImageCompressor, +} + +impl FileStore { + pub fn new(images_dir: &Path) -> Self { + let _ = fs::create_dir_all(images_dir); + let compressor = compress::ImageCompressor::new(images_dir); + Self { + images_dir: images_dir.to_path_buf(), + compressor, + } + } + + pub fn save_image_bytes(&self, bytes: &[u8], extension: &str) -> std::io::Result { + let ts = Utc::now().format("%Y%m%d_%H%M%S_%3f").to_string(); + let filename = format!("capture_{}.{}", ts, extension); + let target_path = self.images_dir.join(&filename); + + fs::write(&target_path, bytes)?; + Ok(target_path.to_string_lossy().to_string()) + } + + pub fn save_base64_image(&self, b64_raw: &str) -> std::io::Result { + // Strip optional data:image/png;base64, prefix + let clean_b64 = if let Some(pos) = b64_raw.find(",") { + &b64_raw[pos + 1..] + } else { + b64_raw + }; + + let decoded = base64::engine::general_purpose::STANDARD + .decode(clean_b64.trim()) + .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?; + + let ext = if decoded.starts_with(&[0xFF, 0xD8, 0xFF]) { + "jpg" + } else { + "png" + }; + + self.save_image_bytes(&decoded, ext) + } + + pub fn read_image(&self, path_str: &str) -> Option> { + let path = Path::new(path_str); + if path.exists() { + fs::read(path).ok() + } else { + // Check inside images_dir directly if relative or basename + let inside = self.images_dir.join(path_str); + if inside.exists() { + fs::read(inside).ok() + } else { + None + } + } + } + + pub fn delete_image(&self, path_str: &str) -> bool { + let path = Path::new(path_str); + if path.exists() { + fs::remove_file(path).is_ok() + } else { + let inside = self.images_dir.join(path_str); + if inside.exists() { + fs::remove_file(inside).is_ok() + } else { + false + } + } + } +} diff --git a/headless-rust/src/storage/skin.rs b/headless-rust/src/storage/skin.rs new file mode 100644 index 0000000..a1e3893 --- /dev/null +++ b/headless-rust/src/storage/skin.rs @@ -0,0 +1,87 @@ +use crate::models::Violation; +use ab_glyph::{FontRef, PxScale}; +use chrono::{DateTime, Utc}; +use image::{ImageBuffer, Rgb, RgbImage}; +use imageproc::drawing::draw_text_mut; +use std::io::Cursor; + +const FONT_DATA: &[u8] = include_bytes!("../../resources/font.ttf"); +const SYSTEM_NR: &str = "PS-847291"; + +const TOP_BAR_H: u32 = 40; +const BOTTOM_BAR_H: u32 = 30; + +pub fn render_poliscan_skin( + src_image_bytes: &[u8], + violation: &Violation, + measuring_location: &str, +) -> Option> { + let src = image::load_from_memory(src_image_bytes).ok()?.to_rgb8(); + let (src_w, src_h) = (src.width(), src.height()); + let total_h = src_h + TOP_BAR_H + BOTTOM_BAR_H; + + let mut canvas: RgbImage = ImageBuffer::from_pixel(src_w, total_h, Rgb([0, 0, 0])); + + // Copy source image between top and bottom bars + image::imageops::overlay(&mut canvas, &src, 0, TOP_BAR_H as i64); + + let font = FontRef::try_from_slice(FONT_DATA).ok()?; + + let label_color = Rgb([170, 170, 170]); + let value_color = Rgb([255, 255, 255]); + + let scale_sm = PxScale::from(12.0); + let scale_md = PxScale::from(14.0); + + // ─── Top Bar Labels ─────────────────────────────────────────────────────── + draw_text_mut(&mut canvas, label_color, 10, 4, scale_sm, &font, "Datum / Zeit"); + draw_text_mut(&mut canvas, label_color, 260, 4, scale_sm, &font, "Limit PKW"); + draw_text_mut(&mut canvas, label_color, 400, 4, scale_sm, &font, "Geschw."); + draw_text_mut(&mut canvas, label_color, 530, 4, scale_sm, &font, "Richtung"); + + // ─── Top Bar Values ─────────────────────────────────────────────────────── + let parsed_dt = DateTime::parse_from_rfc3339(&violation.timestamp) + .map(|dt| dt.with_timezone(&Utc)) + .unwrap_or_else(|_| Utc::now()); + + let dt_str = parsed_dt.format("%d.%m.%Y %H:%M:%S").to_string(); + let limit_str = format!("{:.0} km/h", violation.max_speed); + let speed_str = format!("{:.0} km/h", violation.measured_speed); + let dir_str = if violation.direction == "forward" { + "abgehend" + } else { + "ankommend" + }; + + draw_text_mut(&mut canvas, value_color, 10, 20, scale_md, &font, &dt_str); + draw_text_mut(&mut canvas, value_color, 260, 20, scale_md, &font, &limit_str); + draw_text_mut(&mut canvas, value_color, 400, 20, scale_md, &font, &speed_str); + draw_text_mut(&mut canvas, value_color, 530, 20, scale_md, &font, dir_str); + + // ─── Bottom Bar Labels ──────────────────────────────────────────────────── + let bottom_y = TOP_BAR_H + src_h; + draw_text_mut(&mut canvas, label_color, 10, (bottom_y + 3) as i32, scale_sm, &font, "System"); + draw_text_mut(&mut canvas, label_color, 200, (bottom_y + 3) as i32, scale_sm, &font, "Bildnummer"); + draw_text_mut(&mut canvas, label_color, 420, (bottom_y + 3) as i32, scale_sm, &font, "Ort"); + + // ─── Bottom Bar Values ──────────────────────────────────────────────────── + let img_nr = format!("847291 - {:03} - 1", violation.id); + let loc_str = if measuring_location.is_empty() { + "—" + } else { + measuring_location + }; + + draw_text_mut(&mut canvas, value_color, 10, (bottom_y + 15) as i32, scale_sm, &font, SYSTEM_NR); + draw_text_mut(&mut canvas, value_color, 200, (bottom_y + 15) as i32, scale_sm, &font, &img_nr); + draw_text_mut(&mut canvas, value_color, 420, (bottom_y + 15) as i32, scale_sm, &font, loc_str); + + // Encode to fast high-quality JPEG buffer (<10ms) + let mut out = Vec::new(); + let mut cursor = Cursor::new(&mut out); + let mut encoder = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut cursor, 90); + encoder.encode(canvas.as_raw(), src_w, total_h, image::ExtendedColorType::Rgb8).ok()?; + + Some(out) +} + diff --git a/headless-rust/src/web/embedded.rs b/headless-rust/src/web/embedded.rs new file mode 100644 index 0000000..e1fcd17 --- /dev/null +++ b/headless-rust/src/web/embedded.rs @@ -0,0 +1,44 @@ +use axum::body::Body; +use axum::http::{header, Response, StatusCode}; +use rust_embed::RustEmbed; + +#[derive(RustEmbed)] +#[folder = "dist/"] +pub struct Asset; + +pub fn serve_embedded_asset(path: &str) -> Response { + let clean_path = path.trim_start_matches('/'); + let target = if clean_path.is_empty() { + "index.html" + } else { + clean_path + }; + + if let Some(file) = Asset::get(target) { + let mime = mime_guess::from_path(target).first_or_octet_stream(); + Response::builder() + .status(StatusCode::OK) + .header(header::CONTENT_TYPE, mime.as_ref()) + .body(Body::from(file.data.into_owned())) + .unwrap() + } else if !target.contains('.') { + // SPA Fallback: Return index.html for client-side navigation routes + if let Some(index) = Asset::get("index.html") { + Response::builder() + .status(StatusCode::OK) + .header(header::CONTENT_TYPE, "text/html; charset=utf-8") + .body(Body::from(index.data.into_owned())) + .unwrap() + } else { + Response::builder() + .status(StatusCode::NOT_FOUND) + .body(Body::from("404 Not Found")) + .unwrap() + } + } else { + Response::builder() + .status(StatusCode::NOT_FOUND) + .body(Body::from("404 Not Found")) + .unwrap() + } +} diff --git a/headless-rust/src/web/mod.rs b/headless-rust/src/web/mod.rs new file mode 100644 index 0000000..4ce0429 --- /dev/null +++ b/headless-rust/src/web/mod.rs @@ -0,0 +1,98 @@ +pub mod embedded; +pub mod routes; +pub mod rpc; +pub mod socketio; + +use crate::camera::CameraService; +use crate::config::AppConfig; +use crate::db::Database; +use crate::integrations::teable::TeableClient; +use crate::models::{FlashProgressPayload, Violation}; +use crate::serial::SerialService; +use crate::storage::FileStore; +use crate::web::rpc::RpcContext; +use axum::routing::get; +use axum::Router; +use socketioxide::extract::SocketRef; +use socketioxide::SocketIo; +use std::sync::atomic::AtomicBool; +use std::sync::Arc; +use std::time::Duration; +use tokio::sync::broadcast; +use tower_http::cors::{Any, CorsLayer}; + +pub fn build_app( + config: AppConfig, + db: Database, + store: FileStore, + camera: Arc, + serial: Arc, + violation_tx: broadcast::Sender, + armed: Arc, + armed_tx: broadcast::Sender, +) -> Router { + let (flash_tx, _) = broadcast::channel::(32); + + let ctx = Arc::new(RpcContext { + config, + db, + store, + camera, + serial, + teable: TeableClient::new(), + flash_tx, + violation_tx, + armed, + armed_tx, + }); + + // 10 MB payload capacity, 5s keepalive ping interval to keep Wi-Fi sleep-disabled, + // widened 20s ping timeout to tolerate Wi-Fi jitter, and large 4096 buffer size for live stream bursts. + let (layer, io) = SocketIo::builder() + .max_payload(10_000_000) + .max_buffer_size(4096) + .ping_interval(Duration::from_secs(5)) + .ping_timeout(Duration::from_secs(20)) + .connect_timeout(Duration::from_secs(10)) + .upgrade_timeout(Duration::from_secs(10)) + .ack_timeout(Duration::from_secs(20)) + .build_layer(); + + let ctx_connect = ctx.clone(); + io.ns("/", move |s: SocketRef| { + let ctx = ctx_connect.clone(); + async move { + socketio::on_connect(s, ctx).await; + } + }); + socketio::spawn_event_broadcaster(io, ctx.clone()); + + let cors = CorsLayer::new() + .allow_origin(Any) + .allow_methods(Any) + .allow_headers(Any); + + Router::new() + .route("/api/health", get(routes::health)) + .route("/api/network", get(routes::network)) + .route("/image", get(routes::get_image)) + .route("/skinned-image", get(routes::get_skinned_image)) + // Windows NCSI & Connect Test + .route("/ncsi.txt", get(routes::ncsi_handler)) + .route("/connecttest.txt", get(routes::connecttest_handler)) + // Fedora / Linux / NetworkManager probes + .route("/static/hotspot.txt", get(routes::hotspot_txt_handler)) + .route("/hotspot.txt", get(routes::hotspot_txt_handler)) + .route("/ping.txt", get(routes::ping_txt_handler)) + .route("/check_network_status.txt", get(routes::hotspot_txt_handler)) + .route("/nm", get(routes::hotspot_txt_handler)) + // Android / Chromium / Google probe + .route("/generate_204", get(routes::generate_204_handler)) + .route("/gen_204", get(routes::generate_204_handler)) + // Apple / macOS captive portal probe + .route("/hotspot-detect.html", get(routes::apple_hotspot_handler)) + .fallback(routes::static_handler) + .layer(layer) + .layer(cors) + .with_state(ctx) +} diff --git a/headless-rust/src/web/routes.rs b/headless-rust/src/web/routes.rs new file mode 100644 index 0000000..969306e --- /dev/null +++ b/headless-rust/src/web/routes.rs @@ -0,0 +1,249 @@ +use crate::network::get_system_network_summary; +use crate::storage::compress::CompressParams; +use crate::storage::skin::render_poliscan_skin; +use crate::web::embedded::serve_embedded_asset; +use crate::web::rpc::RpcContext; +use axum::body::Body; +use axum::extract::{Query, State}; +use axum::http::{header, HeaderMap, Response, StatusCode, Uri}; +use axum::response::IntoResponse; +use axum::Json; +use serde::Deserialize; +use serde_json::json; +use std::sync::atomic::Ordering; +use std::sync::Arc; + +pub async fn health(State(ctx): State>) -> impl IntoResponse { + Json(json!({ + "status": "ok", + "platform": std::env::consts::OS, + "camera": ctx.camera.get_status(), + "network": get_system_network_summary(), + "mockMode": ctx.config.mock_mode, + "armed": ctx.armed.load(Ordering::SeqCst), + })) +} + +pub async fn network() -> impl IntoResponse { + Json(get_system_network_summary()) +} + +// ponytail: unified query params for dynamic resizing and compression +#[derive(Deserialize, Debug, Clone)] +pub struct ImageQuery { + pub path: Option, + pub w: Option, + pub width: Option, + pub h: Option, + pub height: Option, + pub q: Option, + pub quality: Option, + pub fmt: Option, + pub format: Option, +} + +impl ImageQuery { + fn to_params(&self) -> CompressParams { + CompressParams { + width: self.w.or(self.width), + height: self.h.or(self.height), + quality: self.q.or(self.quality), + format: self.fmt.clone().or_else(|| self.format.clone()), + } + } +} + +pub async fn get_image( + headers: HeaderMap, + Query(query): Query, + State(ctx): State>, +) -> Result, StatusCode> { + let path = query.path.clone().ok_or(StatusCode::BAD_REQUEST)?; + let params = query.to_params(); + + // Generate lightweight ETag + let etag = format!( + "\"img-{}-w{}-h{}-q{}\"", + path.replace('/', "_"), + params.width.unwrap_or(0), + params.height.unwrap_or(0), + params.quality.unwrap_or(0) + ); + + // 304 Not Modified check to save Wi-Fi network bandwidth + if let Some(if_none_match) = headers.get(header::IF_NONE_MATCH) { + if if_none_match.as_bytes() == etag.as_bytes() { + return Response::builder() + .status(StatusCode::NOT_MODIFIED) + .body(Body::empty()) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR); + } + } + + let store = ctx.store.clone(); + let cache_id = path.clone(); + let file_path = path.clone(); + + // Offload disk read + multicore SIMD resize and compression to blocking thread pool + let res = tokio::task::spawn_blocking(move || -> Result<(Vec, &'static str), StatusCode> { + let bytes = store.read_image(&file_path).ok_or(StatusCode::NOT_FOUND)?; + store + .compressor + .process_image(&bytes, &cache_id, ¶ms) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR) + }) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + + let (compressed_bytes, content_type) = res?; + + Response::builder() + .status(StatusCode::OK) + .header(header::CONTENT_TYPE, content_type) + .header(header::ETAG, etag) + .header(header::CACHE_CONTROL, "public, max-age=31536000, immutable") + .body(Body::from(compressed_bytes)) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR) +} + +#[derive(Deserialize, Debug, Clone)] +pub struct SkinnedImageQuery { + #[serde(rename = "violationId")] + pub violation_id: Option, + pub w: Option, + pub width: Option, + pub h: Option, + pub height: Option, + pub q: Option, + pub quality: Option, + pub fmt: Option, + pub format: Option, +} + +impl SkinnedImageQuery { + fn to_params(&self) -> CompressParams { + CompressParams { + width: self.w.or(self.width), + height: self.h.or(self.height), + quality: self.q.or(self.quality), + format: self.fmt.clone().or_else(|| self.format.clone()), + } + } +} + +pub async fn get_skinned_image( + headers: HeaderMap, + Query(query): Query, + State(ctx): State>, +) -> Result, StatusCode> { + let id = query.violation_id.ok_or(StatusCode::BAD_REQUEST)?; + let params = query.to_params(); + + let etag = format!( + "\"skin-{}-w{}-h{}-q{}\"", + id, + params.width.unwrap_or(0), + params.height.unwrap_or(0), + params.quality.unwrap_or(0) + ); + + if let Some(if_none_match) = headers.get(header::IF_NONE_MATCH) { + if if_none_match.as_bytes() == etag.as_bytes() { + return Response::builder() + .status(StatusCode::NOT_MODIFIED) + .body(Body::empty()) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR); + } + } + + let store = ctx.store.clone(); + let db = ctx.db.clone(); + let cache_id = format!("skin_v{}", id); + + // Offload DB lookup, disk read, skin rendering, and compression to blocking thread pool + let res = tokio::task::spawn_blocking(move || -> Result<(Vec, &'static str), StatusCode> { + let (violation, measuring_location, image_bytes) = { + let conn = db.lock(); + let violation = crate::db::violations::get_violation_by_id(&conn, id) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .ok_or(StatusCode::NOT_FOUND)?; + + let settings = crate::db::settings::get_settings(&conn) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + let image_bytes = store.read_image(&violation.image_path).ok_or(StatusCode::NOT_FOUND)?; + (violation, settings.skin_measuring_location, image_bytes) + }; + + let rendered = render_poliscan_skin( + &image_bytes, + &violation, + &measuring_location, + ) + .ok_or(StatusCode::INTERNAL_SERVER_ERROR)?; + + store + .compressor + .process_image(&rendered, &cache_id, ¶ms) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR) + }) + .await + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + + let (compressed_bytes, content_type) = res?; + + Response::builder() + .status(StatusCode::OK) + .header(header::CONTENT_TYPE, content_type) + .header(header::ETAG, etag) + .header(header::CACHE_CONTROL, "public, max-age=31536000, immutable") + .body(Body::from(compressed_bytes)) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR) +} + +use axum::response::Redirect; + +// ─── Captive Portal Interception & Redirect Handlers ───────────────────────── +// In AP mode, OS captive portal probes are redirected to http://192.168.4.1:3000/ +// so smartphones and laptops automatically open the web setup onboarding page. +pub async fn ncsi_handler() -> impl IntoResponse { + Redirect::temporary("http://192.168.4.1:3000/") +} + +pub async fn connecttest_handler() -> impl IntoResponse { + Redirect::temporary("http://192.168.4.1:3000/") +} + +pub async fn hotspot_txt_handler() -> impl IntoResponse { + Redirect::temporary("http://192.168.4.1:3000/") +} + +pub async fn ping_txt_handler() -> impl IntoResponse { + ( + [(header::CONTENT_TYPE, "text/plain")], + "OK\n", + ) +} + +pub async fn generate_204_handler() -> impl IntoResponse { + // Returning 302/307 Redirect triggers Android / ChromeOS "Sign in to network" + Redirect::temporary("http://192.168.4.1:3000/") +} + +pub async fn apple_hotspot_handler() -> impl IntoResponse { + // Returning Redirect triggers Apple iOS Captive Network Assistant (CNA) + Redirect::temporary("http://192.168.4.1:3000/") +} + +pub async fn static_handler(headers: HeaderMap, uri: Uri) -> impl IntoResponse { + let path = uri.path(); + if let Some(host) = headers.get(header::HOST).and_then(|h| h.to_str().ok()) { + if host.contains("ping.archlinux.org") { + return Response::builder() + .status(StatusCode::OK) + .header(header::CONTENT_TYPE, "text/plain") + .body(Body::from("OK\n")) + .unwrap(); + } + } + serve_embedded_asset(path) +} diff --git a/headless-rust/src/web/rpc.rs b/headless-rust/src/web/rpc.rs new file mode 100644 index 0000000..94833a7 --- /dev/null +++ b/headless-rust/src/web/rpc.rs @@ -0,0 +1,953 @@ +use crate::camera::CameraService; +use crate::db::Database; +use crate::integrations::flasher::{flash_firmware, list_firmware_releases, test_github_token}; +use crate::integrations::teable::TeableClient; +use crate::models::*; +use crate::network::get_system_network_summary; +use crate::serial::SerialService; +use crate::storage::skin::render_poliscan_skin; +use crate::storage::FileStore; +use base64::Engine; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::path::Path; +use std::sync::Arc; +use tokio::sync::broadcast; + +#[derive(Debug, Deserialize)] +pub struct RpcRequest { + pub id: Option, + pub method: String, + #[serde(default)] + pub params: Value, +} + +#[derive(Debug, Serialize)] +pub struct RpcResponse { + pub id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub result: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub error: Option, +} + +pub struct RpcContext { + pub config: crate::config::AppConfig, + pub db: Database, + pub store: FileStore, + pub camera: Arc, + pub serial: Arc, + pub teable: TeableClient, + pub flash_tx: broadcast::Sender, + pub violation_tx: broadcast::Sender, + pub armed: Arc, + pub armed_tx: broadcast::Sender, +} + +pub async fn handle_rpc(ctx: &RpcContext, req: RpcRequest) -> RpcResponse { + let id = req.id; + let res = dispatch_method(ctx, &req.method, req.params).await; + + match res { + Ok(val) => RpcResponse { + id, + result: Some(val), + error: None, + }, + Err(e) => RpcResponse { + id, + result: None, + error: Some(e), + }, + } +} + +async fn dispatch_method(ctx: &RpcContext, method: &str, params: Value) -> Result { + match method { + // ─── Violations ─────────────────────────────────────────────────────── + "getViolations" => { + let q: ViolationQuery = serde_json::from_value(params).map_err(|e| e.to_string())?; + let db = ctx.db.clone(); + let page = tokio::task::spawn_blocking(move || { + let conn = db.lock(); + crate::db::violations::query_violations(&conn, &q) + }) + .await + .map_err(|e| e.to_string())? + .map_err(|e| e.to_string())?; + Ok(serde_json::to_value(page).unwrap()) + } + + "getViolationById" => { + let id = params["id"].as_i64().ok_or("Missing id parameter")?; + let db = ctx.db.clone(); + let violation = tokio::task::spawn_blocking(move || { + let conn = db.lock(); + crate::db::violations::get_violation_by_id(&conn, id) + }) + .await + .map_err(|e| e.to_string())? + .map_err(|e| e.to_string())?; + Ok(serde_json::to_value(violation).unwrap()) + } + + "deleteViolation" => { + let id = params["id"].as_i64().ok_or("Missing id parameter")?; + let db = ctx.db.clone(); + let store = ctx.store.clone(); + tokio::task::spawn_blocking(move || { + let conn = db.lock(); + if let Ok(Some(v)) = crate::db::violations::get_violation_by_id(&conn, id) { + let _ = crate::db::violations::remove_violation(&conn, id); + store.delete_image(&v.image_path); + } + }) + .await + .map_err(|e| e.to_string())?; + Ok(Value::Null) + } + + "exportViolationsCsv" => { + let date_from = params["dateFrom"].as_str().map(|s| s.to_string()); + let date_to = params["dateTo"].as_str().map(|s| s.to_string()); + let min_speed = params["minSpeed"].as_f64(); + let db = ctx.db.clone(); + let csv = tokio::task::spawn_blocking(move || { + let conn = db.lock(); + crate::db::violations::export_csv(&conn, date_from.as_deref(), date_to.as_deref(), min_speed) + }) + .await + .map_err(|e| e.to_string())? + .map_err(|e| e.to_string())?; + Ok(Value::String(csv)) + } + + "saveViolation" => { + let input: SaveViolationInput = + serde_json::from_value(params).map_err(|e| e.to_string())?; + + let cam = ctx.camera.clone(); + let store = ctx.store.clone(); + let db = ctx.db.clone(); + let v_tx = ctx.violation_tx.clone(); + + let v = tokio::task::spawn_blocking(move || -> Result { + let (raw_bytes, ext) = if let Some(ref b64) = input.image_base64 { + let clean = if let Some(pos) = b64.find(',') { + &b64[pos + 1..] + } else { + b64 + }; + let decoded = base64::engine::general_purpose::STANDARD + .decode(clean.trim()) + .map_err(|e| e.to_string())?; + let ext = if decoded.starts_with(&[0xFF, 0xD8, 0xFF]) { + "jpg" + } else { + "png" + }; + (decoded, ext) + } else { + let jpg = cam + .capture_frame_jpeg(90) + .ok_or_else(|| "Failed to capture frame from industrial camera".to_string())?; + (jpg, "jpg") + }; + + let image_path = store + .save_image_bytes(&raw_bytes, ext) + .map_err(|e| e.to_string())?; + + let conn = db.lock(); + let violation = crate::db::violations::insert_violation(&conn, &input, &image_path) + .map_err(|e| e.to_string())?; + let _ = v_tx.send(violation.clone()); + Ok(violation) + }) + .await + .map_err(|e| e.to_string())??; + + Ok(serde_json::to_value(v).unwrap()) + } + + // ─── Lap Sessions ───────────────────────────────────────────────────── + "createLapSession" => { + let lap_mode = params["lapMode"].as_str().unwrap_or("single").to_string(); + let db = ctx.db.clone(); + let session = tokio::task::spawn_blocking(move || { + let conn = db.lock(); + crate::db::laps::create_lap_session(&conn, &lap_mode) + }) + .await + .map_err(|e| e.to_string())? + .map_err(|e| e.to_string())?; + Ok(serde_json::to_value(session).unwrap()) + } + + "closeLapSession" => { + let id = params["id"].as_i64().ok_or("Missing id parameter")?; + let db = ctx.db.clone(); + tokio::task::spawn_blocking(move || { + let conn = db.lock(); + crate::db::laps::close_lap_session(&conn, id) + }) + .await + .map_err(|e| e.to_string())? + .map_err(|e| e.to_string())?; + Ok(Value::Null) + } + + "saveLap" => { + let input: SaveLapInput = serde_json::from_value(params).map_err(|e| e.to_string())?; + let store = ctx.store.clone(); + let db = ctx.db.clone(); + let lap = tokio::task::spawn_blocking(move || -> Result { + let start_img_path = if let Some(ref b64) = input.start_image_base64 { + store.save_base64_image(b64).ok() + } else { + None + }; + + let end_img_path = if let Some(ref b64) = input.end_image_base64 { + store.save_base64_image(b64).ok() + } else { + None + }; + + let conn = db.lock(); + crate::db::laps::insert_lap( + &conn, + &input, + start_img_path.as_deref(), + end_img_path.as_deref(), + ) + .map_err(|e| e.to_string()) + }) + .await + .map_err(|e| e.to_string())??; + + Ok(serde_json::to_value(lap).unwrap()) + } + + "getLapSessions" => { + let page = params["page"].as_i64().unwrap_or(1); + let limit = params["limit"].as_i64().unwrap_or(20); + let db = ctx.db.clone(); + let (sessions, total) = tokio::task::spawn_blocking(move || { + let conn = db.lock(); + crate::db::laps::get_lap_sessions(&conn, page, limit) + }) + .await + .map_err(|e| e.to_string())? + .map_err(|e| e.to_string())?; + + Ok(json!({ + "sessions": sessions, + "total": total + })) + } + + "getLapSessionById" => { + let id = params["id"].as_i64().ok_or("Missing id parameter")?; + let db = ctx.db.clone(); + let session = tokio::task::spawn_blocking(move || { + let conn = db.lock(); + crate::db::laps::get_lap_session_by_id(&conn, id) + }) + .await + .map_err(|e| e.to_string())? + .map_err(|e| e.to_string())?; + Ok(serde_json::to_value(session).unwrap()) + } + + "deleteLapSession" => { + let id = params["id"].as_i64().ok_or("Missing id parameter")?; + let db = ctx.db.clone(); + let store = ctx.store.clone(); + tokio::task::spawn_blocking(move || -> Result<(), String> { + let img_paths = { + let conn = db.lock(); + crate::db::laps::get_lap_image_paths_for_session(&conn, id).unwrap_or_default() + }; + { + let conn = db.lock(); + crate::db::laps::delete_lap_session(&conn, id).map_err(|e| e.to_string())?; + } + for p in img_paths { + store.delete_image(&p); + } + Ok(()) + }) + .await + .map_err(|e| e.to_string())??; + Ok(Value::Null) + } + + "deleteLap" => { + let id = params["id"].as_i64().ok_or("Missing id parameter")?; + let db = ctx.db.clone(); + let store = ctx.store.clone(); + tokio::task::spawn_blocking(move || -> Result<(), String> { + let img_paths = { + let conn = db.lock(); + crate::db::laps::get_lap_image_paths_for_lap(&conn, id).unwrap_or_default() + }; + { + let conn = db.lock(); + crate::db::laps::delete_lap(&conn, id).map_err(|e| e.to_string())?; + } + for p in img_paths { + store.delete_image(&p); + } + Ok(()) + }) + .await + .map_err(|e| e.to_string())??; + Ok(Value::Null) + } + + // ─── Images ─────────────────────────────────────────────────────────── + "getImageData" => { + let image_path = params["imagePath"].as_str().unwrap_or(""); + if image_path.is_empty() { + return Ok(Value::String(String::new())); + } + let mut url = format!("/image?path={}", urlencoding::encode(image_path)); + if let Some(w) = params["width"].as_u64().or_else(|| params["w"].as_u64()) { + url.push_str(&format!("&w={}", w)); + } + if let Some(h) = params["height"].as_u64().or_else(|| params["h"].as_u64()) { + url.push_str(&format!("&h={}", h)); + } + if let Some(q) = params["quality"].as_u64().or_else(|| params["q"].as_u64()) { + url.push_str(&format!("&q={}", q)); + } + if let Some(fmt) = params["format"].as_str().or_else(|| params["fmt"].as_str()) { + url.push_str(&format!("&fmt={}", fmt)); + } + Ok(Value::String(url)) + } + + "getSkinnedImageData" => { + let violation_id = params["violationId"].as_i64().ok_or("Missing violationId")?; + let mut url = format!("/skinned-image?violationId={}", violation_id); + if let Some(w) = params["width"].as_u64().or_else(|| params["w"].as_u64()) { + url.push_str(&format!("&w={}", w)); + } + if let Some(h) = params["height"].as_u64().or_else(|| params["h"].as_u64()) { + url.push_str(&format!("&h={}", h)); + } + if let Some(q) = params["quality"].as_u64().or_else(|| params["q"].as_u64()) { + url.push_str(&format!("&q={}", q)); + } + if let Some(fmt) = params["format"].as_str().or_else(|| params["fmt"].as_str()) { + url.push_str(&format!("&fmt={}", fmt)); + } + Ok(Value::String(url)) + } + + "exportSkinnedImages" => { + let ids = params["violationIds"] + .as_array() + .ok_or("Missing violationIds")? + .clone(); + let target_dir = params["targetDir"].as_str().ok_or("Missing targetDir")?.to_string(); + + let db = ctx.db.clone(); + let store = ctx.store.clone(); + + let res = tokio::task::spawn_blocking(move || -> Result { + let conn = db.lock(); + let settings = crate::db::settings::get_settings(&conn).map_err(|e| e.to_string())?; + + let mut exported = 0; + let mut failed = 0; + + for val in ids { + if let Some(id) = val.as_i64() { + if let Ok(Some(v)) = crate::db::violations::get_violation_by_id(&conn, id) { + if let Some(bytes) = store.read_image(&v.image_path) { + if let Some(skinned) = render_poliscan_skin( + &bytes, + &v, + &settings.skin_measuring_location, + ) { + let ext = if skinned.starts_with(&[0xFF, 0xD8, 0xFF]) { + "jpg" + } else { + "png" + }; + let out_path = Path::new(&target_dir) + .join(format!("violation-{}-{}.{}", v.id, v.timestamp.replace(":", "-"), ext)); + if std::fs::write(out_path, skinned).is_ok() { + exported += 1; + continue; + } + } + } + } + failed += 1; + } + } + + Ok(ExportSkinnedResult { exported, failed }) + }) + .await + .map_err(|e| e.to_string())??; + + Ok(serde_json::to_value(res).unwrap()) + } + + // ─── Armed / System State ───────────────────────────────────────────── + "getArmedState" => { + let is_armed = ctx.armed.load(std::sync::atomic::Ordering::SeqCst); + Ok(json!({ "armed": is_armed })) + } + + "setArmed" => { + let is_armed = params["armed"] + .as_bool() + .ok_or("Missing armed parameter")?; + ctx.armed.store(is_armed, std::sync::atomic::Ordering::SeqCst); + let _ = ctx.armed_tx.send(is_armed); + tracing::info!("[system] Armed state updated: {}", is_armed); + Ok(json!({ "armed": is_armed })) + } + + // ─── Settings ───────────────────────────────────────────────────────── + "getSettings" => { + let db = ctx.db.clone(); + let settings = tokio::task::spawn_blocking(move || { + let conn = db.lock(); + crate::db::settings::get_settings(&conn) + }) + .await + .map_err(|e| e.to_string())? + .map_err(|e| e.to_string())?; + Ok(serde_json::to_value(settings).unwrap()) + } + + "saveSetting" => { + let key = params["key"].as_str().ok_or("Missing key")?.to_string(); + let value = params["value"].as_str().ok_or("Missing value")?.to_string(); + let db = ctx.db.clone(); + tokio::task::spawn_blocking(move || { + let conn = db.lock(); + crate::db::settings::save_setting(&conn, &key, &value) + }) + .await + .map_err(|e| e.to_string())? + .map_err(|e| e.to_string())?; + Ok(Value::Null) + } + + // ─── Serial ─────────────────────────────────────────────────────────── + "listPorts" => { + let serial = ctx.serial.clone(); + let ports = tokio::task::spawn_blocking(move || serial.list_ports()) + .await + .map_err(|e| e.to_string())?; + Ok(serde_json::to_value(ports).unwrap()) + } + + "getSerialStatus" => { + let status = ctx.serial.get_status(); + Ok(serde_json::to_value(status).unwrap()) + } + + "openPort" => { + let path = params["path"].as_str().ok_or("Missing port path")?; + ctx.serial.open_port(path); + Ok(Value::Null) + } + + "closePort" => { + ctx.serial.close_port(); + Ok(Value::Null) + } + + "sendCommand" => { + let json_cmd = params["json"].as_str().ok_or("Missing json command")?.to_string(); + let serial = ctx.serial.clone(); + tokio::task::spawn_blocking(move || serial.send_command(&json_cmd)) + .await + .map_err(|e| e.to_string())?; + Ok(Value::Null) + } + + // ─── Camera HW ──────────────────────────────────────────────────────── + "connectCamera" => { + let cam = ctx.camera.clone(); + let db = ctx.db.clone(); + tokio::task::spawn_blocking(move || { + let conn = db.lock(); + let settings = crate::db::settings::get_settings(&conn).unwrap_or_default(); + cam.connect(&settings); + }) + .await + .map_err(|e| e.to_string())?; + Ok(Value::Null) + } + + "disconnectCamera" => { + let cam = ctx.camera.clone(); + tokio::task::spawn_blocking(move || { + cam.disconnect(); + }) + .await + .map_err(|e| e.to_string())?; + Ok(Value::Null) + } + + "getCameraStatus" => { + let status = ctx.camera.get_status(); + Ok(serde_json::to_value(status).unwrap()) + } + + "captureFrame" => { + let cam = ctx.camera.clone(); + let b64 = tokio::task::spawn_blocking(move || { + if let Some(jpg_bytes) = cam.capture_frame_jpeg(90) { + let b64 = base64::engine::general_purpose::STANDARD.encode(&jpg_bytes); + Some(format!("data:image/jpeg;base64,{}", b64)) + } else { + None + } + }) + .await + .map_err(|e| e.to_string())?; + + if let Some(data) = b64 { + Ok(Value::String(data)) + } else { + Ok(Value::Null) + } + } + + "setCameraExposure" => { + let val = params["value"].as_f64().ok_or("Missing exposure value")?; + let cam = ctx.camera.clone(); + tokio::task::spawn_blocking(move || cam.set_exposure(val)) + .await + .map_err(|e| e.to_string())?; + Ok(Value::Null) + } + + "setCameraGain" => { + let val = params["value"].as_f64().ok_or("Missing gain value")?; + let cam = ctx.camera.clone(); + tokio::task::spawn_blocking(move || cam.set_gain(val)) + .await + .map_err(|e| e.to_string())?; + Ok(Value::Null) + } + + "setCameraFeatureStr" => { + let feature = params["feature"].as_str().ok_or("Missing feature name")?.to_string(); + let value = params["value"].as_str().ok_or("Missing feature value")?.to_string(); + let cam = ctx.camera.clone(); + tokio::task::spawn_blocking(move || cam.set_feature_str(&feature, &value)) + .await + .map_err(|e| e.to_string())?; + Ok(Value::Null) + } + + "setCameraFeatureInt" => { + let feature = params["feature"].as_str().ok_or("Missing feature name")?.to_string(); + let value = params["value"].as_i64().ok_or("Missing feature value")?; + let cam = ctx.camera.clone(); + tokio::task::spawn_blocking(move || cam.set_feature_int(&feature, value)) + .await + .map_err(|e| e.to_string())?; + Ok(Value::Null) + } + + "applyMfsConfig" => { + let mfs = params["mfsContent"].as_str().ok_or("Missing mfsContent")?.to_string(); + let save_default = params["saveAsDefault"].as_bool().unwrap_or(false); + let cam = ctx.camera.clone(); + let res = tokio::task::spawn_blocking(move || cam.apply_mfs_config(&mfs, save_default)) + .await + .map_err(|e| e.to_string())?; + Ok(serde_json::to_value(res).unwrap()) + } + + "startSetupStream" => { + let cam = ctx.camera.clone(); + tokio::task::spawn_blocking(move || cam.start_setup_stream()) + .await + .map_err(|e| e.to_string())?; + Ok(Value::Null) + } + + "stopSetupStream" => { + let cam = ctx.camera.clone(); + let db = ctx.db.clone(); + tokio::task::spawn_blocking(move || { + let conn = db.lock(); + let settings = crate::db::settings::get_settings(&conn).unwrap_or_default(); + cam.stop_setup_stream(&settings); + }) + .await + .map_err(|e| e.to_string())?; + Ok(Value::Null) + } + + "setCameraPixelFormat" => { + let fmt = params["format"].as_str().ok_or("Missing format")?.to_string(); + let cam = ctx.camera.clone(); + tokio::task::spawn_blocking(move || cam.set_pixel_format(&fmt)) + .await + .map_err(|e| e.to_string())?; + Ok(Value::Null) + } + + "getCameraPixelFormat" => { + let db = ctx.db.clone(); + let format = tokio::task::spawn_blocking(move || { + let conn = db.lock(); + crate::db::settings::get_settings(&conn).unwrap_or_default().pixel_format + }) + .await + .map_err(|e| e.to_string())?; + Ok(Value::String(format)) + } + + "setCameraStrobeDuration" => { + let val = params["value"].as_i64().ok_or("Missing value")?; + let cam = ctx.camera.clone(); + tokio::task::spawn_blocking(move || cam.set_strobe_duration(val)) + .await + .map_err(|e| e.to_string())?; + Ok(Value::Null) + } + + // ─── System & Network ───────────────────────────────────────────────── + "getPlatform" => Ok(Value::String(std::env::consts::OS.to_string())), + + "getNetworkInfo" => { + let summary = get_system_network_summary(); + Ok(serde_json::to_value(summary).unwrap()) + } + + "scanWifiNetworks" => { + let results = tokio::task::spawn_blocking(move || crate::network::scan_wifi_networks()) + .await + .map_err(|e| e.to_string())?; + Ok(serde_json::to_value(results).unwrap()) + } + + "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())?; + Ok(serde_json::to_value(res).unwrap()) + } + + "forgetWifi" => { + let input = ApplyNetworkModeInput { + mode: "forget".to_string(), + ssid: None, + password: None, + }; + let res = tokio::task::spawn_blocking(move || crate::network::apply_network_mode(&input)) + .await + .map_err(|e| e.to_string())?; + Ok(serde_json::to_value(res).unwrap()) + } + + "setEthernetMode" => { + let mode = params["mode"].as_str().unwrap_or("camera-lan").to_string(); + let input = ApplyNetworkModeInput { + mode, + ssid: None, + password: None, + }; + let res = tokio::task::spawn_blocking(move || crate::network::apply_network_mode(&input)) + .await + .map_err(|e| e.to_string())?; + Ok(serde_json::to_value(res).unwrap()) + } + + // ─── Teable ─────────────────────────────────────────────────────────── + "testTeableConnection" => { + let url = params["url"].as_str().ok_or("Missing url")?; + let token = params["token"].as_str().ok_or("Missing token")?; + let user = ctx.teable.test_connection(url, token).await?; + Ok(serde_json::to_value(user).unwrap()) + } + + "saveTeableConfig" => { + let url = params["url"].as_str().unwrap_or("").to_string(); + let token = params["token"].as_str().unwrap_or("").to_string(); + let name = params["userName"].as_str().unwrap_or("").to_string(); + let email = params["userEmail"].as_str().unwrap_or("").to_string(); + let avatar = params["userAvatar"].as_str().unwrap_or("").to_string(); + + let db = ctx.db.clone(); + tokio::task::spawn_blocking(move || { + let conn = db.lock(); + let _ = crate::db::settings::save_setting(&conn, "teableUrl", &url); + let _ = crate::db::settings::save_setting(&conn, "teableToken", &token); + let _ = crate::db::settings::save_setting(&conn, "teableUserName", &name); + let _ = crate::db::settings::save_setting(&conn, "teableUserEmail", &email); + let _ = crate::db::settings::save_setting(&conn, "teableUserAvatar", &avatar); + }) + .await + .map_err(|e| e.to_string())?; + Ok(Value::Null) + } + + "removeTeableConfig" => { + let db = ctx.db.clone(); + tokio::task::spawn_blocking(move || { + let conn = db.lock(); + let _ = crate::db::settings::save_setting(&conn, "teableUrl", ""); + let _ = crate::db::settings::save_setting(&conn, "teableToken", ""); + let _ = crate::db::settings::save_setting(&conn, "teableUserName", ""); + let _ = crate::db::settings::save_setting(&conn, "teableUserEmail", ""); + let _ = crate::db::settings::save_setting(&conn, "teableUserAvatar", ""); + let _ = crate::db::settings::save_setting(&conn, "teableSpaceId", ""); + let _ = crate::db::settings::save_setting(&conn, "teableBaseId", ""); + let _ = crate::db::settings::save_setting(&conn, "teableTableId", ""); + let _ = crate::db::settings::save_setting(&conn, "teableSyncEnabled", "false"); + }) + .await + .map_err(|e| e.to_string())?; + Ok(Value::Null) + } + + "saveTeableTarget" => { + let space_id = params["spaceId"].as_str().unwrap_or("").to_string(); + let base_id = params["baseId"].as_str().unwrap_or("").to_string(); + let table_id = params["tableId"].as_str().unwrap_or("").to_string(); + + let db = ctx.db.clone(); + tokio::task::spawn_blocking(move || { + let conn = db.lock(); + let _ = crate::db::settings::save_setting(&conn, "teableSpaceId", &space_id); + let _ = crate::db::settings::save_setting(&conn, "teableBaseId", &base_id); + let _ = crate::db::settings::save_setting(&conn, "teableTableId", &table_id); + }) + .await + .map_err(|e| e.to_string())?; + Ok(Value::Null) + } + + "listTeableSpaces" => { + let db = ctx.db.clone(); + let settings = tokio::task::spawn_blocking(move || { + let conn = db.lock(); + crate::db::settings::get_settings(&conn) + }) + .await + .map_err(|e| e.to_string())? + .map_err(|e| e.to_string())?; + + let spaces = ctx + .teable + .list_spaces(&settings.teable_url, &settings.teable_token) + .await?; + Ok(serde_json::to_value(spaces).unwrap()) + } + + "listTeableBases" => { + let space_id = params["spaceId"].as_str().ok_or("Missing spaceId")?; + let db = ctx.db.clone(); + let settings = tokio::task::spawn_blocking(move || { + let conn = db.lock(); + crate::db::settings::get_settings(&conn) + }) + .await + .map_err(|e| e.to_string())? + .map_err(|e| e.to_string())?; + + let bases = ctx + .teable + .list_bases(&settings.teable_url, &settings.teable_token, space_id) + .await?; + Ok(serde_json::to_value(bases).unwrap()) + } + + "listTeableTables" => { + let base_id = params["baseId"].as_str().ok_or("Missing baseId")?; + let db = ctx.db.clone(); + let settings = tokio::task::spawn_blocking(move || { + let conn = db.lock(); + crate::db::settings::get_settings(&conn) + }) + .await + .map_err(|e| e.to_string())? + .map_err(|e| e.to_string())?; + + let tables = ctx + .teable + .list_tables(&settings.teable_url, &settings.teable_token, base_id) + .await?; + Ok(serde_json::to_value(tables).unwrap()) + } + + "verifyTeableTable" => { + let table_id = params["tableId"].as_str().ok_or("Missing tableId")?; + let db = ctx.db.clone(); + let settings = tokio::task::spawn_blocking(move || { + let conn = db.lock(); + crate::db::settings::get_settings(&conn) + }) + .await + .map_err(|e| e.to_string())? + .map_err(|e| e.to_string())?; + + let check = ctx + .teable + .verify_table(&settings.teable_url, &settings.teable_token, table_id) + .await?; + Ok(serde_json::to_value(check).unwrap()) + } + + "ensureTeableFields" => { + let table_id = params["tableId"].as_str().ok_or("Missing tableId")?; + let db = ctx.db.clone(); + let settings = tokio::task::spawn_blocking(move || { + let conn = db.lock(); + crate::db::settings::get_settings(&conn) + }) + .await + .map_err(|e| e.to_string())? + .map_err(|e| e.to_string())?; + + let created = ctx + .teable + .ensure_fields(&settings.teable_url, &settings.teable_token, table_id) + .await?; + Ok(serde_json::to_value(created).unwrap()) + } + + "createTeableTable" => { + let base_id = params["baseId"].as_str().ok_or("Missing baseId")?; + let table_name = params["tableName"].as_str().ok_or("Missing tableName")?; + let db = ctx.db.clone(); + let settings = tokio::task::spawn_blocking(move || { + let conn = db.lock(); + crate::db::settings::get_settings(&conn) + }) + .await + .map_err(|e| e.to_string())? + .map_err(|e| e.to_string())?; + + let table = ctx + .teable + .create_table( + &settings.teable_url, + &settings.teable_token, + base_id, + table_name, + ) + .await?; + Ok(serde_json::to_value(table).unwrap()) + } + + "syncLapToTeable" => { + let input: SyncLapInput = serde_json::from_value(params).map_err(|e| e.to_string())?; + let db = ctx.db.clone(); + let settings = tokio::task::spawn_blocking(move || { + let conn = db.lock(); + crate::db::settings::get_settings(&conn) + }) + .await + .map_err(|e| e.to_string())? + .map_err(|e| e.to_string())?; + + ctx.teable + .sync_lap( + &settings.teable_url, + &settings.teable_token, + &settings.teable_table_id, + &input, + ) + .await?; + Ok(Value::Null) + } + + // ─── Firmware Flasher ───────────────────────────────────────────────── + "testGithubToken" => { + let token = params["token"].as_str().unwrap_or(""); + let (valid, login) = test_github_token(token).await?; + Ok(json!({ "valid": valid, "login": login })) + } + + "listFirmwareReleases" => { + let db = ctx.db.clone(); + let settings = tokio::task::spawn_blocking(move || { + let conn = db.lock(); + crate::db::settings::get_settings(&conn).unwrap_or_default() + }) + .await + .map_err(|e| e.to_string())?; + + let releases = list_firmware_releases(&settings.github_token).await?; + Ok(serde_json::to_value(releases).unwrap()) + } + + "flashFirmware" => { + let release_tag = params["releaseTag"].as_str().unwrap_or("").to_string(); + let port = params["port"].as_str().unwrap_or("").to_string(); + let asset_url = params["firmwareAssetApiUrl"] + .as_str() + .unwrap_or("") + .to_string(); + + let db = ctx.db.clone(); + let settings = tokio::task::spawn_blocking(move || { + let conn = db.lock(); + crate::db::settings::get_settings(&conn).unwrap_or_default() + }) + .await + .map_err(|e| e.to_string())?; + + let token = settings.github_token; + let tx = ctx.flash_tx.clone(); + + ctx.serial.close_port(); + + tokio::spawn(async move { + flash_firmware(&release_tag, &port, &asset_url, &token, tx).await; + }); + + Ok(Value::Null) + } + + // ─── Stubs for Window & Updater ─────────────────────────────────────── + "minimizeWindow" | "maximizeWindow" | "closeWindow" | "cancelFlash" | "applyUpdate" => { + Ok(Value::Null) + } + + "getLocalVersion" => Ok(json!({ + "version": "0.5.0-rust", + "channel": "rust", + "hash": "rpi5-native" + })), + + "checkForUpdate" => Ok(json!({ + "version": "0.5.0-rust", + "hash": "rpi5-native", + "updateAvailable": false, + "updateReady": false, + "error": "Native binary managed by system" + })), + + "downloadUpdate" => Ok(json!({ + "ok": true + })), + + _ => Err(format!("Method '{}' not found", method)), + } +} + +mod urlencoding { + pub fn encode(s: &str) -> String { + url::form_urlencoded::byte_serialize(s.as_bytes()).collect() + } +} diff --git a/headless-rust/src/web/socketio.rs b/headless-rust/src/web/socketio.rs new file mode 100644 index 0000000..0af0754 --- /dev/null +++ b/headless-rust/src/web/socketio.rs @@ -0,0 +1,164 @@ +use crate::web::rpc::{handle_rpc, RpcContext, RpcRequest}; +use serde_json::json; +use socketioxide::extract::{AckSender, Data, SocketRef}; +use socketioxide::socket::DisconnectReason; +use socketioxide::SocketIo; +use std::sync::atomic::Ordering; +use std::sync::Arc; +use tokio::sync::broadcast; + +pub async fn on_connect(s: SocketRef, ctx: Arc) { + tracing::info!("[socketio] Client connected: {}", s.id); + + // Push initial states directly to the newly connected client + let _ = s.emit("cameraStatus", &ctx.camera.get_status()); + let _ = s.emit("serialStatus", &ctx.serial.get_status_payload()); + let _ = s.emit("armedStatus", &json!({ "armed": ctx.armed.load(Ordering::SeqCst) })); + + // Register RPC handler with AckSender for request-response RPC over Socket.io + let ctx_rpc = ctx.clone(); + s.on( + "rpc", + move |_s: SocketRef, Data(req): Data, ack: AckSender| { + let ctx = ctx_rpc.clone(); + async move { + let resp = handle_rpc(&ctx, req).await; + ack.send(&resp).ok(); + } + }, + ); + + // Heartbeat ping handler + s.on("ping", |ack: AckSender| async move { + ack.send(&json!({ + "pong": true, + "timestamp": chrono::Utc::now().timestamp_millis() + })) + .ok(); + }); + + s.on_disconnect(|s: SocketRef, reason: DisconnectReason| async move { + tracing::info!("[socketio] Client disconnected: {} ({:?})", s.id, reason); + }); +} + +pub fn spawn_event_broadcaster(io: SocketIo, ctx: Arc) { + tokio::spawn(async move { + let mut serial_rx = ctx.serial.subscribe(); + let mut camera_status_rx = ctx.camera.subscribe_status(); + let mut live_frame_rx = ctx.camera.subscribe_frames(); + let mut flash_rx = ctx.flash_tx.subscribe(); + let mut violation_rx = ctx.violation_tx.subscribe(); + let mut armed_rx = ctx.armed_tx.subscribe(); + + loop { + tokio::select! { + res = serial_rx.recv() => { + match res { + Ok(payload) => { + if let Err(e) = io.emit("serialStatus", &payload).await { + tracing::debug!("[socketio] Emit serialStatus error: {:?}", e); + } + } + Err(broadcast::error::RecvError::Lagged(n)) => { + tracing::debug!("[socketio] Serial broadcast lagged by {} messages", n); + } + Err(broadcast::error::RecvError::Closed) => { + tracing::warn!("[socketio] Serial broadcast channel closed"); + break; + } + } + } + + res = camera_status_rx.recv() => { + match res { + Ok(payload) => { + if let Err(e) = io.emit("cameraStatus", &payload).await { + tracing::debug!("[socketio] Emit cameraStatus error: {:?}", e); + } + } + Err(broadcast::error::RecvError::Lagged(n)) => { + tracing::debug!("[socketio] Camera status broadcast lagged by {} messages", n); + } + Err(broadcast::error::RecvError::Closed) => { + tracing::warn!("[socketio] Camera status broadcast channel closed"); + break; + } + } + } + + res = live_frame_rx.recv() => { + match res { + Ok(b64_frame) => { + // Volatile / drop if congested so live preview doesn't buffer stale frames + if let Err(e) = io.volatile().emit("liveFrame", &b64_frame).await { + tracing::debug!("[socketio] Emit liveFrame error: {:?}", e); + } + } + Err(broadcast::error::RecvError::Lagged(_)) => { + // Frame skipping is expected under high framerate or low bandwidth + } + Err(broadcast::error::RecvError::Closed) => { + tracing::warn!("[socketio] Live frame channel closed"); + break; + } + } + } + + res = violation_rx.recv() => { + match res { + Ok(v) => { + tracing::info!("[socketio] Broadcasting violation #{} to all clients", v.id); + if let Err(e) = io.emit("violation", &v).await { + tracing::warn!("[socketio] Emit violation error: {:?}", e); + } + } + Err(broadcast::error::RecvError::Lagged(n)) => { + tracing::debug!("[socketio] Violation broadcast lagged by {} messages", n); + } + Err(broadcast::error::RecvError::Closed) => { + tracing::warn!("[socketio] Violation channel closed"); + break; + } + } + } + + res = flash_rx.recv() => { + match res { + Ok(payload) => { + if let Err(e) = io.emit("flashProgress", &payload).await { + tracing::debug!("[socketio] Emit flashProgress error: {:?}", e); + } + } + Err(broadcast::error::RecvError::Lagged(n)) => { + tracing::debug!("[socketio] Flash progress broadcast lagged by {} messages", n); + } + Err(broadcast::error::RecvError::Closed) => { + tracing::warn!("[socketio] Flash progress channel closed"); + break; + } + } + } + + res = armed_rx.recv() => { + match res { + Ok(is_armed) => { + if let Err(e) = io.emit("armedStatus", &json!({ "armed": is_armed })).await { + tracing::debug!("[socketio] Emit armedStatus error: {:?}", e); + } + } + Err(broadcast::error::RecvError::Lagged(n)) => { + tracing::debug!("[socketio] Armed status broadcast lagged by {} messages", n); + } + Err(broadcast::error::RecvError::Closed) => { + tracing::warn!("[socketio] Armed status channel closed"); + break; + } + } + } + } + } + + tracing::info!("[socketio] Event broadcaster task exiting"); + }); +} diff --git a/headless-rust/tailwind.config.js b/headless-rust/tailwind.config.js new file mode 100644 index 0000000..74a6906 --- /dev/null +++ b/headless-rust/tailwind.config.js @@ -0,0 +1,8 @@ +/** @type {import('tailwindcss').Config} */ +export default { + content: ["./frontend/**/*.{html,js,ts,jsx,tsx}"], + theme: { + extend: {}, + }, + plugins: [], +}; diff --git a/headless-rust/tsconfig.json b/headless-rust/tsconfig.json new file mode 100644 index 0000000..bf36fb1 --- /dev/null +++ b/headless-rust/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "target": "ES2022", + "useDefineForClassFields": true, + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "module": "ESNext", + "skipLibCheck": true, + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "isolatedModules": true, + "moduleDetection": "force", + "noEmit": true, + "jsx": "react-jsx", + "strict": true, + "noUnusedLocals": false, + "noUnusedParameters": false, + "noFallthroughCasesInSwitch": true, + "paths": { + "@/*": ["./frontend/src/*"] + } + }, + "include": ["frontend/src"], + "exclude": ["node_modules", "dist"] +} diff --git a/headless-rust/vite.config.ts b/headless-rust/vite.config.ts new file mode 100644 index 0000000..ddc3c25 --- /dev/null +++ b/headless-rust/vite.config.ts @@ -0,0 +1,30 @@ +import path from "path"; +import { defineConfig } from "vite"; +import react from "@vitejs/plugin-react"; + +export default defineConfig({ + plugins: [react()], + root: "frontend", + resolve: { + alias: { + "@": path.resolve(__dirname, "./frontend/src"), + }, + }, + build: { + outDir: "../dist", + emptyOutDir: true, + }, + server: { + port: 5173, + strictPort: true, + proxy: { + "/image": "http://127.0.0.1:3000", + "/skinned-image": "http://127.0.0.1:3000", + "/api": "http://127.0.0.1:3000", + "/socket.io": { + target: "http://127.0.0.1:3000", + ws: true, + }, + }, + }, +});