From 4283aa21b1c4ba4beb16b0bfa7f337385d5bac5f Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Mon, 10 Aug 2026 23:43:12 +0200 Subject: [PATCH 01/65] feat: initial commit --- headless/.gitignore | 11 + headless/README.md | 100 ++ headless/bun.lock | 1252 +++++++++++++++++ headless/components.json | 25 + headless/package.json | 58 + headless/postcss.config.js | 6 + headless/scripts/install-rpi.sh | 105 ++ headless/scripts/setup-network.sh | 67 + headless/scripts/speedcamera.service | 21 + headless/scripts/test-server.ts | 64 + headless/scripts/verify-ws.ts | 54 + headless/src/components/ArmingButton.tsx | 237 ++++ headless/src/components/ErrorBoundary.tsx | 60 + headless/src/components/FirmwareFlasher.tsx | 363 +++++ .../src/components/LapImageThumbnails.tsx | 92 ++ headless/src/components/LapTimerDisplay.tsx | 113 ++ headless/src/components/LastCapturedImage.tsx | 48 + headless/src/components/NavigationMenu.tsx | 73 + headless/src/components/StatusBadge.tsx | 46 + headless/src/components/ThemeToggle.tsx | 29 + headless/src/components/ViolationCard.tsx | 140 ++ headless/src/components/ui/badge.tsx | 49 + headless/src/components/ui/button.tsx | 65 + headless/src/components/ui/card.tsx | 100 ++ headless/src/components/ui/checkbox.tsx | 31 + headless/src/components/ui/collapsible.tsx | 31 + headless/src/components/ui/dialog.tsx | 166 +++ headless/src/components/ui/input.tsx | 19 + headless/src/components/ui/label.tsx | 22 + headless/src/components/ui/progress.tsx | 29 + headless/src/components/ui/scroll-area.tsx | 53 + headless/src/components/ui/select.tsx | 192 +++ headless/src/components/ui/skeleton.tsx | 12 + headless/src/components/ui/slider.tsx | 57 + headless/src/components/ui/sonner.tsx | 48 + headless/src/components/ui/switch.tsx | 31 + headless/src/components/ui/toggle-group.tsx | 89 ++ headless/src/components/ui/toggle.tsx | 45 + headless/src/hooks/useLiveLapTimer.ts | 27 + headless/src/hooks/useSystemStateSync.ts | 31 + headless/src/lib/format.ts | 26 + headless/src/lib/rpc.ts | 173 +++ headless/src/lib/sound.ts | 44 + headless/src/lib/utils.ts | 6 + headless/src/mainview/App.tsx | 46 + headless/src/mainview/index.css | 135 ++ headless/src/mainview/index.html | 12 + headless/src/mainview/main.tsx | 13 + headless/src/routes/__root.tsx | 40 + headless/src/routes/about.tsx | 264 ++++ headless/src/routes/index.tsx | 129 ++ headless/src/routes/laps.tsx | 44 + headless/src/routes/laps/HistoryTab.tsx | 110 ++ headless/src/routes/laps/LapRow.tsx | 103 ++ headless/src/routes/laps/LiveSessionTab.tsx | 195 +++ headless/src/routes/laps/SessionCard.tsx | 115 ++ headless/src/routes/settings.tsx | 58 + headless/src/routes/settings/CameraTab.tsx | 424 ++++++ headless/src/routes/settings/DeviceTab.tsx | 236 ++++ headless/src/routes/settings/LapTimerTab.tsx | 119 ++ .../src/routes/settings/SpeedCameraTab.tsx | 263 ++++ headless/src/routes/setup.tsx | 97 ++ headless/src/routes/teable.tsx | 32 + .../src/routes/teable/ConnectionSection.tsx | 159 +++ headless/src/routes/teable/SchemaStatus.tsx | 97 ++ .../src/routes/teable/SyncToggleSection.tsx | 39 + .../src/routes/teable/TableTargetSection.tsx | 277 ++++ headless/src/routes/violations.tsx | 174 +++ .../routes/violations/ExportImagesDialog.tsx | 79 ++ .../routes/violations/ViolationGridTile.tsx | 133 ++ .../src/routes/violations/ViolationRow.tsx | 111 ++ .../src/routes/violations/ViolationsGrid.tsx | 87 ++ .../src/routes/violations/ViolationsTable.tsx | 105 ++ .../routes/violations/ViolationsToolbar.tsx | 157 +++ .../routes/violations/useViolationImage.ts | 27 + .../src/routes/violations/useViolations.ts | 186 +++ headless/src/server/database.ts | 431 ++++++ headless/src/server/env.ts | 28 + headless/src/server/filestore.ts | 60 + headless/src/server/flasher.ts | 210 +++ headless/src/server/index.ts | 442 ++++++ headless/src/server/industrial-camera.ts | 411 ++++++ headless/src/server/mock/serial.ts | 96 ++ headless/src/server/network.ts | 130 ++ headless/src/server/rpc.ts | 68 + headless/src/server/serial.ts | 184 +++ headless/src/server/skin-renderer.ts | 85 ++ headless/src/server/teable.ts | 252 ++++ headless/src/shared/schemas.ts | 99 ++ headless/src/shared/types.ts | 548 ++++++++ headless/src/stores/slices/cameraSlice.ts | 128 ++ headless/src/stores/slices/flasherSlice.ts | 38 + headless/src/stores/slices/lapSlice.ts | 262 ++++ .../src/stores/slices/measurementSlice.ts | 90 ++ headless/src/stores/slices/serialSlice.ts | 22 + headless/src/stores/slices/systemSlice.ts | 20 + headless/src/stores/slices/teableSlice.ts | 206 +++ headless/src/stores/slices/updaterSlice.ts | 82 ++ headless/src/stores/useAppStore.ts | 23 + headless/tailwind.config.js | 8 + headless/tsconfig.json | 24 + headless/vite.config.ts | 30 + 102 files changed, 12353 insertions(+) create mode 100644 headless/.gitignore create mode 100644 headless/README.md create mode 100644 headless/bun.lock create mode 100644 headless/components.json create mode 100644 headless/package.json create mode 100644 headless/postcss.config.js create mode 100644 headless/scripts/install-rpi.sh create mode 100644 headless/scripts/setup-network.sh create mode 100644 headless/scripts/speedcamera.service create mode 100644 headless/scripts/test-server.ts create mode 100644 headless/scripts/verify-ws.ts create mode 100644 headless/src/components/ArmingButton.tsx create mode 100644 headless/src/components/ErrorBoundary.tsx create mode 100644 headless/src/components/FirmwareFlasher.tsx create mode 100644 headless/src/components/LapImageThumbnails.tsx create mode 100644 headless/src/components/LapTimerDisplay.tsx create mode 100644 headless/src/components/LastCapturedImage.tsx create mode 100644 headless/src/components/NavigationMenu.tsx create mode 100644 headless/src/components/StatusBadge.tsx create mode 100644 headless/src/components/ThemeToggle.tsx create mode 100644 headless/src/components/ViolationCard.tsx create mode 100644 headless/src/components/ui/badge.tsx create mode 100644 headless/src/components/ui/button.tsx create mode 100644 headless/src/components/ui/card.tsx create mode 100644 headless/src/components/ui/checkbox.tsx create mode 100644 headless/src/components/ui/collapsible.tsx create mode 100644 headless/src/components/ui/dialog.tsx create mode 100644 headless/src/components/ui/input.tsx create mode 100644 headless/src/components/ui/label.tsx create mode 100644 headless/src/components/ui/progress.tsx create mode 100644 headless/src/components/ui/scroll-area.tsx create mode 100644 headless/src/components/ui/select.tsx create mode 100644 headless/src/components/ui/skeleton.tsx create mode 100644 headless/src/components/ui/slider.tsx create mode 100644 headless/src/components/ui/sonner.tsx create mode 100644 headless/src/components/ui/switch.tsx create mode 100644 headless/src/components/ui/toggle-group.tsx create mode 100644 headless/src/components/ui/toggle.tsx create mode 100644 headless/src/hooks/useLiveLapTimer.ts create mode 100644 headless/src/hooks/useSystemStateSync.ts create mode 100644 headless/src/lib/format.ts create mode 100644 headless/src/lib/rpc.ts create mode 100644 headless/src/lib/sound.ts create mode 100644 headless/src/lib/utils.ts create mode 100644 headless/src/mainview/App.tsx create mode 100644 headless/src/mainview/index.css create mode 100644 headless/src/mainview/index.html create mode 100644 headless/src/mainview/main.tsx create mode 100644 headless/src/routes/__root.tsx create mode 100644 headless/src/routes/about.tsx create mode 100644 headless/src/routes/index.tsx create mode 100644 headless/src/routes/laps.tsx create mode 100644 headless/src/routes/laps/HistoryTab.tsx create mode 100644 headless/src/routes/laps/LapRow.tsx create mode 100644 headless/src/routes/laps/LiveSessionTab.tsx create mode 100644 headless/src/routes/laps/SessionCard.tsx create mode 100644 headless/src/routes/settings.tsx create mode 100644 headless/src/routes/settings/CameraTab.tsx create mode 100644 headless/src/routes/settings/DeviceTab.tsx create mode 100644 headless/src/routes/settings/LapTimerTab.tsx create mode 100644 headless/src/routes/settings/SpeedCameraTab.tsx create mode 100644 headless/src/routes/setup.tsx create mode 100644 headless/src/routes/teable.tsx create mode 100644 headless/src/routes/teable/ConnectionSection.tsx create mode 100644 headless/src/routes/teable/SchemaStatus.tsx create mode 100644 headless/src/routes/teable/SyncToggleSection.tsx create mode 100644 headless/src/routes/teable/TableTargetSection.tsx create mode 100644 headless/src/routes/violations.tsx create mode 100644 headless/src/routes/violations/ExportImagesDialog.tsx create mode 100644 headless/src/routes/violations/ViolationGridTile.tsx create mode 100644 headless/src/routes/violations/ViolationRow.tsx create mode 100644 headless/src/routes/violations/ViolationsGrid.tsx create mode 100644 headless/src/routes/violations/ViolationsTable.tsx create mode 100644 headless/src/routes/violations/ViolationsToolbar.tsx create mode 100644 headless/src/routes/violations/useViolationImage.ts create mode 100644 headless/src/routes/violations/useViolations.ts create mode 100644 headless/src/server/database.ts create mode 100644 headless/src/server/env.ts create mode 100644 headless/src/server/filestore.ts create mode 100644 headless/src/server/flasher.ts create mode 100644 headless/src/server/index.ts create mode 100644 headless/src/server/industrial-camera.ts create mode 100644 headless/src/server/mock/serial.ts create mode 100644 headless/src/server/network.ts create mode 100644 headless/src/server/rpc.ts create mode 100644 headless/src/server/serial.ts create mode 100644 headless/src/server/skin-renderer.ts create mode 100644 headless/src/server/teable.ts create mode 100644 headless/src/shared/schemas.ts create mode 100644 headless/src/shared/types.ts create mode 100644 headless/src/stores/slices/cameraSlice.ts create mode 100644 headless/src/stores/slices/flasherSlice.ts create mode 100644 headless/src/stores/slices/lapSlice.ts create mode 100644 headless/src/stores/slices/measurementSlice.ts create mode 100644 headless/src/stores/slices/serialSlice.ts create mode 100644 headless/src/stores/slices/systemSlice.ts create mode 100644 headless/src/stores/slices/teableSlice.ts create mode 100644 headless/src/stores/slices/updaterSlice.ts create mode 100644 headless/src/stores/useAppStore.ts create mode 100644 headless/tailwind.config.js create mode 100644 headless/tsconfig.json create mode 100644 headless/vite.config.ts diff --git a/headless/.gitignore b/headless/.gitignore new file mode 100644 index 0000000..480c59e --- /dev/null +++ b/headless/.gitignore @@ -0,0 +1,11 @@ +# Node modules +node_modules + +# Build output +dist +build +target +artifacts + +# Bundled native binaries (downloaded by CI, not committed) +resources/ \ No newline at end of file diff --git a/headless/README.md b/headless/README.md new file mode 100644 index 0000000..e495b10 --- /dev/null +++ b/headless/README.md @@ -0,0 +1,100 @@ +# Speedcamera Headless & Remote Web Controller + +A lightweight, high-performance headless speedcamera daemon and responsive web controller built with **Bun**, **Vite**, **React**, and **TypeScript**. + +Engineered to run natively on **Raspberry Pi 4 / 5 with Raspberry Pi OS Lite** (zero desktop or GUI dependencies) inside the camera enclosure, creating a standalone Wi-Fi hotspot for laptops, tablets, and phones to connect and manage the system via web browser. + +--- + +## Architecture & Dual-Subnet Network Setup + +``` +┌─────────────────────────────────────────────────────────────────────────┐ +│ Raspberry Pi 4 / 5 (Raspberry Pi OS Lite ARM64) │ +│ │ +│ • eth0 (Camera LAN): 192.168.1.100/24 <── GigE Vision (192.168.1.x)│ +│ • wlan0 (Hotspot AP): 192.168.4.1/24 <── Web UI (SSID: speedcamera)│ +│ │ +│ • systemd Daemon: Pure Headless Bun Service │ +│ ├── Bun.serve() HTTP Server (Vite SPA + Image API) │ +│ ├── WebSocket RPC Server (/ws/rpc) │ +│ ├── Industrial Camera (Aravis GigE Vision on eth0: 192.168.1.100) │ +│ ├── Serial Port (Arduino / Radar Telemetry) │ +│ ├── Network Diagnostics (/api/network) │ +│ └── SQLite Database (bun:sqlite @ ~/.speedcamera) │ +└───────────────────────┬─────────────────────────────▲───────────────────┘ + │ Wi-Fi AP │ Ethernet Cable + ▼ │ +┌──────────────────────────────────────────┐ ┌──────────────────────────┐ +│ Client Device (Laptop / Tablet / Phone) │ │ Industrial GigE Camera │ +│ │ │ │ +│ • Connect Wi-Fi SSID: speedcamera │ │ • Subnet: 192.168.1.0/24 │ +│ • Open Browser: http://192.168.4.1:3000 │ │ • GigE Vision / Aravis │ +│ • Live Radar, Live View, Settings, Laps │ │ • Direct link to eth0 │ +└──────────────────────────────────────────┘ └──────────────────────────┘ +``` + +--- + +## Quick Start (Development) + +### 1. Install Dependencies +```bash +cd headless +bun install +``` + +### 2. Run in Development Mode (with HMR & Mock Hardware) +```bash +bun run dev:mock +``` +* **Frontend (Vite HMR):** `http://localhost:5173` +* **Backend Daemon:** `http://localhost:3000` (WebSocket on `/ws/rpc`) + +### 3. Build & Run Production Bundle Locally +```bash +bun run build +bun run start:mock +``` +Open `http://localhost:3000` in your browser. + +--- + +## Raspberry Pi 4 / 5 Deployment (Raspberry Pi OS Lite) + +### Automated Setup +Run the automated installation script on your Raspberry Pi: +```bash +cd headless +chmod +x scripts/install-rpi.sh +./scripts/install-rpi.sh +``` + +This script will automatically: +1. Install system libraries (`libaravis-0.8-0`, `python3-esptool`, `network-manager`). +2. Install the **Bun** ARM64 runtime. +3. Build the production React web bundle. +4. Configure the dual-subnet network interfaces (`scripts/setup-network.sh`): + - **`eth0` Camera LAN:** Static IP `192.168.1.100/24` (Subnet `192.168.1.0/24` for industrial GigE camera). + - **`wlan0` Hotspot AP:** Static IP `192.168.4.1/24` (SSID: `speedcamera`, password: `speedcamerapass`). +5. Install and enable the `systemd` service for automatic startup on boot. + +### Managing the Service +```bash +# Start service +sudo systemctl start speedcamera + +# Stop service +sudo systemctl stop speedcamera + +# View live real-time logs +sudo journalctl -u speedcamera -f +``` + +--- + +## Connecting in the Field +1. Power on the speedcamera Raspberry Pi. +2. On your laptop or phone, connect to the Wi-Fi network **`speedcamera`** (Password: `speedcamerapass`). +3. Open your browser and navigate to: + **`http://192.168.4.1:3000`** diff --git a/headless/bun.lock b/headless/bun.lock new file mode 100644 index 0000000..c5e5a13 --- /dev/null +++ b/headless/bun.lock @@ -0,0 +1,1252 @@ +{ + "lockfileVersion": 1, + "configVersion": 1, + "workspaces": { + "": { + "name": "speedcamera-headless", + "dependencies": { + "@asl-gokart/bun-aravis": "^0.2.0", + "@fontsource-variable/figtree": "^5.2.10", + "@hugeicons/core-free-icons": "^4.1.1", + "@hugeicons/react": "^1.1.6", + "@napi-rs/canvas": "^1.0.3", + "@tailwindcss/postcss": "^4.2.4", + "@tailwindcss/vite": "^4.2.4", + "@tanstack/react-router": "^1.168.23", + "bun-serialport": "^0.1.1", + "class-variance-authority": "^0.7.1", + "clsx": "^2.1.1", + "lucide-react": "^1.8.0", + "next-themes": "^0.4.6", + "radix-ui": "^1.4.3", + "react": "^18.3.1", + "react-dom": "^18.3.1", + "react-webcam": "^7.2.0", + "shadcn": "^4.7.0", + "sharp": "^0.35.2", + "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/bun": "latest", + "@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=="], + + "@asl-gokart/bun-aravis": ["@asl-gokart/bun-aravis@0.2.0", "https://registry.leotm.de/@asl-gokart/bun-aravis/-/bun-aravis-0.2.0.tgz", { "peerDependencies": { "typescript": "^5.0.0" } }, "sha512-PqQWZZD45sOZijdUJmLpTjnf4ZqFR9ltmYWBh4fQfXBobIJiZJiUWJQ/EevvR9KuhtIAvXqlvO3B2KtSoWV21Q=="], + + "@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=="], + + "@emnapi/runtime": ["@emnapi/runtime@1.11.3", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA=="], + + "@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.0", "", { "peerDependencies": { "hono": "^4" } }, "sha512-XovyyCCnBzW+zKu+z/zq8hwNs4KOR5rEMAOxo2f40Q5xoOI37IMm6MIg2COOUtUApo0i6850MTBKH2u4QLGIqg=="], + + "@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=="], + + "@img/colour": ["@img/colour@1.1.0", "", {}, "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ=="], + + "@img/sharp-darwin-arm64": ["@img/sharp-darwin-arm64@0.35.3", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-arm64": "1.3.2" }, "os": "darwin", "cpu": "arm64" }, "sha512-RMnFX7YQsMoh7lWfcM4NEHHymBX/rLuKNPVM84XE9ONPcaSCDgE7CHIHpSgPcO2xcRthgBy1HfNO319mwhIAkg=="], + + "@img/sharp-darwin-x64": ["@img/sharp-darwin-x64@0.35.3", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-x64": "1.3.2" }, "os": "darwin", "cpu": "x64" }, "sha512-Xo+5uFBtLN0BKqieTxiFzFPQAUlBbbH5iBKyRX/z1JrbnYsHTfKJnUfL8+p2TPXr1pXqao4eeL4Rl144uDpK9w=="], + + "@img/sharp-freebsd-wasm32": ["@img/sharp-freebsd-wasm32@0.35.3", "", { "dependencies": { "@img/sharp-wasm32": "0.35.3" }, "os": "freebsd" }, "sha512-lUxcqWIj2wMQ9BrwNjngcr1gWUr5xgaGThBRqPPalIC2n67Cqj1uPh8NnA/ZhAg8hUbKl+kVHKwgUIwe6ZYPrg=="], + + "@img/sharp-libvips-darwin-arm64": ["@img/sharp-libvips-darwin-arm64@1.3.2", "", { "os": "darwin", "cpu": "arm64" }, "sha512-9J6ypZFpQBj4YnePGoq/S38w6nz+vqg5WZLrLGY4YuSemdMq47GMLBPO42MzwdGwpg/agZ7xzZcFHa48xlywfg=="], + + "@img/sharp-libvips-darwin-x64": ["@img/sharp-libvips-darwin-x64@1.3.2", "", { "os": "darwin", "cpu": "x64" }, "sha512-m2pW1n6cns9VaubNwsZ+c3CRYjxNQWgJ5gPlnL1nbBcpkBvFm6SCFN5o0psFHI8w9n11NKhFkeEDns98tiqbEw=="], + + "@img/sharp-libvips-linux-arm": ["@img/sharp-libvips-linux-arm@1.3.2", "", { "os": "linux", "cpu": "arm" }, "sha512-1eMLzy92I4J6rmi4mAT8yC3HxOtniyGELlzGbNMLLeqe052ahFQ0h6LFq+lh5DsDIdYViIDst08abvSbcEdLXQ=="], + + "@img/sharp-libvips-linux-arm64": ["@img/sharp-libvips-linux-arm64@1.3.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-dqVSFynCox4C/J8kT16V7SIFAns0IjgLwkvYT7p8LQVmJ5OS5b6tI9IGflxTeuBS//zXeFIUbwt5dwxyZ17cnA=="], + + "@img/sharp-libvips-linux-ppc64": ["@img/sharp-libvips-linux-ppc64@1.3.2", "", { "os": "linux", "cpu": "ppc64" }, "sha512-3z0NHDxD6n5I9gc05U1eW1AyRm+Gznzq3naMrthPNqE6oYykcogW0l/jfpJdjYnuNl8R7yI9pNbE1XiUeyq0Aw=="], + + "@img/sharp-libvips-linux-riscv64": ["@img/sharp-libvips-linux-riscv64@1.3.2", "", { "os": "linux", "cpu": "none" }, "sha512-bsb4rI+NldGOsXuej2r8OdSS8+zXDVaCWxyWrcv6kneTOlgAHtZABRzBBCwdsPiD90J4myNJuHpg6kA20ImW/w=="], + + "@img/sharp-libvips-linux-s390x": ["@img/sharp-libvips-linux-s390x@1.3.2", "", { "os": "linux", "cpu": "s390x" }, "sha512-/ABshyj8gCpyIrNXnHn4LorDJ0HHm1VhXPBlxZ8zAtfVPAaSafXPGn+sUSIRiwaSBy0mmFjSjiXI5mkcwdChKQ=="], + + "@img/sharp-libvips-linux-x64": ["@img/sharp-libvips-linux-x64@1.3.2", "", { "os": "linux", "cpu": "x64" }, "sha512-ITPEtgffGJ0S6G9dRyw/366tJQqFRcHWPHhC+Stpg3Z8AEMrDrTr2lhdz4f/Y/HMbRh//7Z5mBzEpVdi62Oc3w=="], + + "@img/sharp-libvips-linuxmusl-arm64": ["@img/sharp-libvips-linuxmusl-arm64@1.3.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-zE9EdiUzUmg5mDT5a1rk5fYJ6GWPloTwWBYDS14naqHsL+EaMpDj1AWnpLgh3u0YCORv2Tt50wrcrpYqkP97Kw=="], + + "@img/sharp-libvips-linuxmusl-x64": ["@img/sharp-libvips-linuxmusl-x64@1.3.2", "", { "os": "linux", "cpu": "x64" }, "sha512-m0lrLiUt+lBYnCFr8qV/65yMR4E/c7/wf78I5eKTdkEakFAlZ9QlzEM3QIhhAwVeUhLAHLcCq7a7Vszq/oFNZQ=="], + + "@img/sharp-linux-arm": ["@img/sharp-linux-arm@0.35.3", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm": "1.3.2" }, "os": "linux", "cpu": "arm" }, "sha512-affVWCTLooy8TSxbDx2qkzuDeaWLNVBA+P//FNBirHsXpP2fuBhk5AuboYUnrDnzoXes8GFjpTx0SBFOCRg+FA=="], + + "@img/sharp-linux-arm64": ["@img/sharp-linux-arm64@0.35.3", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm64": "1.3.2" }, "os": "linux", "cpu": "arm64" }, "sha512-QgKDspHPnrU+GQ55XPhGwyhC8acLVOOSyAvo1oVfFmrIXLkDNmGWzAfDZ4xK8oSA1qBQrALcHX0G5UZni/SuFQ=="], + + "@img/sharp-linux-ppc64": ["@img/sharp-linux-ppc64@0.35.3", "", { "optionalDependencies": { "@img/sharp-libvips-linux-ppc64": "1.3.2" }, "os": "linux", "cpu": "ppc64" }, "sha512-sMd8rDxmpLOwv/7N44klFjOD5DUO7FLdjiXDI0hoxYaf7Ar262dQIEkosE98bps+5HPLtp/EvNqeqQtOycP/IA=="], + + "@img/sharp-linux-riscv64": ["@img/sharp-linux-riscv64@0.35.3", "", { "optionalDependencies": { "@img/sharp-libvips-linux-riscv64": "1.3.2" }, "os": "linux", "cpu": "none" }, "sha512-0Eob78yjlYPfL5vMNWAW55l3R9Y6BQS/gOfe0ZcP9mEz9ohhKSt4im1hayiknXgf8AWrFqMvJcKIdmLmEe7yeQ=="], + + "@img/sharp-linux-s390x": ["@img/sharp-linux-s390x@0.35.3", "", { "optionalDependencies": { "@img/sharp-libvips-linux-s390x": "1.3.2" }, "os": "linux", "cpu": "s390x" }, "sha512-KgAxQ0DxpNOq1rG2t5cgTgShJFGSuU7XO45cqC+1NVOuZnP6tlgZRuSYOfNupGkHID0o3cJOsw4DVeJpMovcGw=="], + + "@img/sharp-linux-x64": ["@img/sharp-linux-x64@0.35.3", "", { "optionalDependencies": { "@img/sharp-libvips-linux-x64": "1.3.2" }, "os": "linux", "cpu": "x64" }, "sha512-8pqvxubL2PGdhlPy6GLqzDYMUjyRmKAwKHYKixpdJYBUK7PJ0C029XdsnpFIdgRZG68fZiGdHVWcKPvtiPB4cA=="], + + "@img/sharp-linuxmusl-arm64": ["@img/sharp-linuxmusl-arm64@0.35.3", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-arm64": "1.3.2" }, "os": "linux", "cpu": "arm64" }, "sha512-Vz0iQjzzcSX3HCbfwFfCSG/9SCIqyO0mH2sXyiHaAYfBk0cRsCWXRyQYX0ovCK/PAQBbTzQ0dsPQHh5MAFL59w=="], + + "@img/sharp-linuxmusl-x64": ["@img/sharp-linuxmusl-x64@0.35.3", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-x64": "1.3.2" }, "os": "linux", "cpu": "x64" }, "sha512-6O1NPKcDVj9QEdg7Hx549EX8U0rp6yXQERqru6yRN7fGBn32UvIRJUlWnk+8xDCiG76hXVBbX82NZ/ZKr0euIg=="], + + "@img/sharp-wasm32": ["@img/sharp-wasm32@0.35.3", "", { "dependencies": { "@emnapi/runtime": "^1.11.1" } }, "sha512-cZ0XkcYGpHZkqW6iCkqTcmUC0CD9DhD5d/qeZlZkfRBn6GnHniZXLUo5+9xw8Iv76YE6LQFN9YNBlKREcCG76w=="], + + "@img/sharp-webcontainers-wasm32": ["@img/sharp-webcontainers-wasm32@0.35.3", "", { "dependencies": { "@img/sharp-wasm32": "0.35.3" }, "cpu": "none" }, "sha512-2rnq7bX3NzeR2T4YWgz8qiG4h3TSdMe+vN1iQXpJleSJ3SM5zQ8Fy2SyyXAWlbxpEZ2Y+Z4u1BePgJEYbSy80Q=="], + + "@img/sharp-win32-arm64": ["@img/sharp-win32-arm64@0.35.3", "", { "os": "win32", "cpu": "arm64" }, "sha512-4bPwFdMbeC4JQ8L8LOyWp6nsHcboP5fxkp6iPOXz2Vg49R42TuMs2whkJ5OAP4/Ul035qOzy0AecOF9VOscn4w=="], + + "@img/sharp-win32-ia32": ["@img/sharp-win32-ia32@0.35.3", "", { "os": "win32", "cpu": "ia32" }, "sha512-r53mXsBN6lFUDiST764SvgwUdHAqM4rPAiDzAmf4fLoB6X/rkfyTrLCg6+g17wJJiCmB3JYgHuUldCWUIRFSXw=="], + + "@img/sharp-win32-x64": ["@img/sharp-win32-x64@0.35.3", "", { "os": "win32", "cpu": "x64" }, "sha512-D4y1vNeZrIIJCN+uHaWVtH86B+aCrdMYYjicy9pXHvbGZeGYLLSd3wdVuC37FxVXlU1ARsk84eKWfWMXGYEqvA=="], + + "@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/canvas": ["@napi-rs/canvas@1.0.5", "", { "optionalDependencies": { "@napi-rs/canvas-android-arm64": "1.0.5", "@napi-rs/canvas-darwin-arm64": "1.0.5", "@napi-rs/canvas-darwin-x64": "1.0.5", "@napi-rs/canvas-linux-arm-gnueabihf": "1.0.5", "@napi-rs/canvas-linux-arm64-gnu": "1.0.5", "@napi-rs/canvas-linux-arm64-musl": "1.0.5", "@napi-rs/canvas-linux-riscv64-gnu": "1.0.5", "@napi-rs/canvas-linux-x64-gnu": "1.0.5", "@napi-rs/canvas-linux-x64-musl": "1.0.5", "@napi-rs/canvas-win32-arm64-msvc": "1.0.5", "@napi-rs/canvas-win32-x64-msvc": "1.0.5" } }, "sha512-GaPlicMtnvgPr5SowFRprkEJicDSrV3qCq17U4jiF5u0kNORZo3IbdN2Bk4SfcZJAMYFHbMVJ81O3w21CYxazg=="], + + "@napi-rs/canvas-android-arm64": ["@napi-rs/canvas-android-arm64@1.0.5", "", { "os": "android", "cpu": "arm64" }, "sha512-ZzDlpKQocwFfCwhMh17UWre6Qt5yZN3kNIJoUpGfRZqwDDZ164IKOsPOHsRd3d8Tuj5KM6bDjGuPmZxuPuG3NQ=="], + + "@napi-rs/canvas-darwin-arm64": ["@napi-rs/canvas-darwin-arm64@1.0.5", "", { "os": "darwin", "cpu": "arm64" }, "sha512-Hr8v6CA/TBe+OJOePdV3sXWxzQHQKfQsTKPbc8wG7iPqVeAx6MMdzKGXlYID6SVvpfwV/zqkvGcdImYWSlhrZg=="], + + "@napi-rs/canvas-darwin-x64": ["@napi-rs/canvas-darwin-x64@1.0.5", "", { "os": "darwin", "cpu": "x64" }, "sha512-9BXlLHBXpYnK4jSae1MdFdyPq09Xi1I3PeCNpvRzqgmUUBhgJS7aC1z7SZEP8JUXDHtbfIrolCS3sFuT9IGP2A=="], + + "@napi-rs/canvas-linux-arm-gnueabihf": ["@napi-rs/canvas-linux-arm-gnueabihf@1.0.5", "", { "os": "linux", "cpu": "arm" }, "sha512-zEW4fgvtYsOJ/N56Us4TQPfaFrUf0shGr9CgGSj3GACc+NHfUM3ci0YF9xFTjwJWGDmaEhYPL6KqCfFCxwm/qg=="], + + "@napi-rs/canvas-linux-arm64-gnu": ["@napi-rs/canvas-linux-arm64-gnu@1.0.5", "", { "os": "linux", "cpu": "arm64" }, "sha512-HFprwLspelJxCEtZvdMcz95Mwvfs63GzFVedLFmC/wslHnaOXhjXxgYxPCM/VdM4Jhx3CV4Lk0vVmh6hJv2etQ=="], + + "@napi-rs/canvas-linux-arm64-musl": ["@napi-rs/canvas-linux-arm64-musl@1.0.5", "", { "os": "linux", "cpu": "arm64" }, "sha512-FNMGFAx8DvtDwlLfWyBJ+oQjgPXoIAqCnNTJYqtJCFRwwzK3AyAe5B1Ll3NZ6hcOzqw7HylZsq4nQxVyPCQX1Q=="], + + "@napi-rs/canvas-linux-riscv64-gnu": ["@napi-rs/canvas-linux-riscv64-gnu@1.0.5", "", { "os": "linux", "cpu": "none" }, "sha512-2vd5v8Lui+37Hh/spITKIvTT384ip4dnUc5XBn0E+sMNS4b7au7IswyT5YDG2udPTjSh/eLUs3sGuB5YHooFOA=="], + + "@napi-rs/canvas-linux-x64-gnu": ["@napi-rs/canvas-linux-x64-gnu@1.0.5", "", { "os": "linux", "cpu": "x64" }, "sha512-iQIPy+Uey0expZTOszLri5n8rY7x4WUpMaY82mcXNIgbil30iHvc01OsiizhZC1KQHTK90RFMFWSpwFU+ON3aA=="], + + "@napi-rs/canvas-linux-x64-musl": ["@napi-rs/canvas-linux-x64-musl@1.0.5", "", { "os": "linux", "cpu": "x64" }, "sha512-Npthji25t7FUqIAKsoEkFS0qY5CYVkHjvI3tuZjDTG92wX8g4dst+Lfb4hhubdqPazlDcIwalPzInsFCtf3FFg=="], + + "@napi-rs/canvas-win32-arm64-msvc": ["@napi-rs/canvas-win32-arm64-msvc@1.0.5", "", { "os": "win32", "cpu": "arm64" }, "sha512-bi+JsdCdbfVJDoAQybTYmkLKwh1xpYpptg5j/BNr2BB56u4/R26jrVvtjqff+CxYMXV6Kz1/jeDVhZCuj6bDng=="], + + "@napi-rs/canvas-win32-x64-msvc": ["@napi-rs/canvas-win32-x64-msvc@1.0.5", "", { "os": "win32", "cpu": "x64" }, "sha512-KQQwG9/sBmcGxqaLFIQf+k2OefREGoyEaIBmRuTM8bUuFKOEE9Xk5pel90hE6pmBwk/vo4RB0OdX+FxobJGMFw=="], + + "@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=="], + + "@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.25", "", { "dependencies": { "@tanstack/history": "1.162.1", "@tanstack/react-store": "^0.9.3", "@tanstack/router-core": "1.171.21", "isbot": "^5.1.22" }, "peerDependencies": { "react": ">=18.0.0 || >=19.0.0", "react-dom": ">=18.0.0 || >=19.0.0" } }, "sha512-XiWYvkLAGhcZHhV2xUvicpF/VfTVSnewP6CqviDONAjmD50tBob5x/93u2W8QZAc/JgkPd+jijCmu6t4NCzmew=="], + + "@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.21", "", { "dependencies": { "@tanstack/history": "1.162.1", "cookie-es": "^3.0.0", "seroval": "^1.6.2", "seroval-plugins": "^1.6.2" } }, "sha512-t6xUHBO94nQDrPHPh6ag5UuKHWIkVjq9s63q2ctbxgzq3vtSoGKmAIdLD5o+NU6JUS1ppXRHgL0YGzEHvH32Ng=="], + + "@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/bun": ["@types/bun@1.3.14", "", { "dependencies": { "bun-types": "1.3.14" } }, "sha512-h1hFqFVcvAvD9j9K7ZW7vd82aSA+rTdznZa+5bwvCwqSB1jmmfLcbIWhOLx1/+boy/xmjgCs/OMUL8hRJSmnPw=="], + + "@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.2.2", "", {}, "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg=="], + + "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.13", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-k9HNuUVMlqVjQ9UHzfPjIqiDbWw7WqT1AoT7GL8VwvF3r0ZfArtgiSPAlmupyNquNgOJHTuH4CKYf8ttMTWBTQ=="], + + "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=="], + + "bun-serialport": ["bun-serialport@0.1.1", "", { "os": [ "linux", "darwin", ] }, "sha512-hObWOJD/TyEjCFln7TGWQEdzd/XTo+rQIQ8BNb1pR/5caJ2KbDitzq+TaTfuoxqJd+1bBQWIc7QsVul8Xq7elQ=="], + + "bun-types": ["bun-types@1.3.14", "", { "dependencies": { "@types/node": "*" } }, "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ=="], + + "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.403", "", {}, "sha512-MQsYmdaLzvaCX5j+ZZBr5Fm6uCCnPQcRtlvmvRlWqrXy+BH2O4ffXIAScF+JQznQWB9brWp4lSD9Z4yNmaf2BA=="], + + "emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="], + + "encodeurl": ["encodeurl@2.0.0", "", {}, "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg=="], + + "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.1", "", {}, "sha512-kdJoFVv2xmayw6cY09H7AbMJMt8Jn5jdlEdXsP7AGBdF2DIptVlKlOLKXP41yPip4/a3yQPv9gVcJYI8YY04dw=="], + + "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.0", "", { "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.1.0", "wsl-utils": "^0.3.0" } }, "sha512-smsWv2LzFjP03xmvFoJ331ss6h+jixfA4UUV/Bsiyuu4YJPfN+FIQGOIiv4w9/+MoHkfkJ22UIaQWRVFRfH6Vw=="], + + "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.1.0", "", {}, "sha512-dM0jVuXJPsDN6DvRpea484tCUaMiXWjuCn++HGTqUWzGDjv5tZkEZldAJ/UMlqRYGFrD/etByo4/xOuC/snX2A=="], + + "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=="], + + "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@7.8.5", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="], + + "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.16.2", "", { "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", "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-M1AvZKFWcCzWRDoyApIqJMSLIpY8Ev4uBGuiPLSFmiTbixXhPmzotSTvLzFmBrfoIxG9aIg2dZOETblEaXGUnQ=="], + + "sharp": ["sharp@0.35.3", "", { "dependencies": { "@img/colour": "^1.1.0", "detect-libc": "^2.1.2", "semver": "^7.8.5" }, "optionalDependencies": { "@img/sharp-darwin-arm64": "0.35.3", "@img/sharp-darwin-x64": "0.35.3", "@img/sharp-freebsd-wasm32": "0.35.3", "@img/sharp-libvips-darwin-arm64": "1.3.2", "@img/sharp-libvips-darwin-x64": "1.3.2", "@img/sharp-libvips-linux-arm": "1.3.2", "@img/sharp-libvips-linux-arm64": "1.3.2", "@img/sharp-libvips-linux-ppc64": "1.3.2", "@img/sharp-libvips-linux-riscv64": "1.3.2", "@img/sharp-libvips-linux-s390x": "1.3.2", "@img/sharp-libvips-linux-x64": "1.3.2", "@img/sharp-libvips-linuxmusl-arm64": "1.3.2", "@img/sharp-libvips-linuxmusl-x64": "1.3.2", "@img/sharp-linux-arm": "0.35.3", "@img/sharp-linux-arm64": "0.35.3", "@img/sharp-linux-ppc64": "0.35.3", "@img/sharp-linux-riscv64": "0.35.3", "@img/sharp-linux-s390x": "0.35.3", "@img/sharp-linux-x64": "0.35.3", "@img/sharp-linuxmusl-arm64": "0.35.3", "@img/sharp-linuxmusl-x64": "0.35.3", "@img/sharp-webcontainers-wasm32": "0.35.3", "@img/sharp-win32-arm64": "0.35.3", "@img/sharp-win32-ia32": "0.35.3", "@img/sharp-win32-x64": "0.35.3" }, "peerDependencies": { "@types/node": "*" }, "optionalPeers": ["@types/node"] }, "sha512-ej0zVHuZGHCiABXcNxeYhpRnPNPAcvbG8RMdBAhDAxLKkCRVSpK3Iyu7qbqw3JMzoj0REeM6f3tJLtVwl0023Q=="], + + "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=="], + + "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=="], + + "wsl-utils": ["wsl-utils@0.3.1", "", { "dependencies": { "is-wsl": "^3.1.0", "powershell-utils": "^0.1.0" } }, "sha512-g/eziiSUNBSsdDJtCLB8bdYEUMj4jR7AGeUo96p/3dTafgjHhpF4RiCFPiRILwjQoDXx5MqkBr4fwWtR3Ky4Wg=="], + + "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.14", "", { "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-/8tAspM5LMPr28b3fwLYrtdj77ECpfZviaP75CMTnwO8ISyaE4GDIG/9rDDYq/cH9D2Xw2A2RXglLInmVBQB/g=="], + + "@babel/core/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="], + + "@babel/helper-compilation-targets/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="], + + "@babel/helper-create-class-features-plugin/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="], + + "@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.2", "", { "dependencies": { "@tybys/wasm-util": "^0.10.3" }, "peerDependencies": { "@emnapi/core": "^1.7.1 || ^2.0.0-alpha.3", "@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.3" }, "bundled": true }, "sha512-JfB4kuJQjaoHuCTseIINHtHWeJnvgEcxjwA5t/Y00ZgaOO1Crz3fjT/p8kT28zA/Caz7oiUMn3d6H2yOVCVwuw=="], + + "@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.0.0", "", {}, "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ=="], + + "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=="], + + "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.0.0", "", {}, "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ=="], + + "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=="], + + "@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/components.json b/headless/components.json new file mode 100644 index 0000000..6c10365 --- /dev/null +++ b/headless/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": "src/mainview/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/package.json b/headless/package.json new file mode 100644 index 0000000..592eaea --- /dev/null +++ b/headless/package.json @@ -0,0 +1,58 @@ +{ + "name": "speedcamera-headless", + "type": "module", + "version": "0.4.0", + "description": "Headless Speedcamera daemon and Web UI for Raspberry Pi 4/5 and remote browser control", + "scripts": { + "dev": "concurrently \"bun run dev:client\" \"bun run dev:server\"", + "dev:mock": "concurrently \"bun run dev:client\" \"MOCK_MODE=true bun --watch src/server/index.ts\"", + "dev:client": "vite", + "dev:server": "bun --watch src/server/index.ts", + "build": "vite build", + "start": "vite build && bun src/server/index.ts", + "start:mock": "MOCK_MODE=true vite build && MOCK_MODE=true bun src/server/index.ts", + "serve": "bun src/server/index.ts", + "serve:mock": "MOCK_MODE=true bun src/server/index.ts", + "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": { + "@asl-gokart/bun-aravis": "^0.2.0", + "@fontsource-variable/figtree": "^5.2.10", + "@hugeicons/core-free-icons": "^4.1.1", + "@hugeicons/react": "^1.1.6", + "@napi-rs/canvas": "^1.0.3", + "@tailwindcss/postcss": "^4.2.4", + "@tailwindcss/vite": "^4.2.4", + "@tanstack/react-router": "^1.168.23", + "bun-serialport": "^0.1.1", + "class-variance-authority": "^0.7.1", + "clsx": "^2.1.1", + "lucide-react": "^1.8.0", + "next-themes": "^0.4.6", + "radix-ui": "^1.4.3", + "react": "^18.3.1", + "react-dom": "^18.3.1", + "react-webcam": "^7.2.0", + "shadcn": "^4.7.0", + "sharp": "^0.35.2", + "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/bun": "latest", + "@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/postcss.config.js b/headless/postcss.config.js new file mode 100644 index 0000000..f69c5d4 --- /dev/null +++ b/headless/postcss.config.js @@ -0,0 +1,6 @@ +export default { + plugins: { + "@tailwindcss/postcss": {}, + autoprefixer: {}, + }, +}; diff --git a/headless/scripts/install-rpi.sh b/headless/scripts/install-rpi.sh new file mode 100644 index 0000000..8114010 --- /dev/null +++ b/headless/scripts/install-rpi.sh @@ -0,0 +1,105 @@ +#!/usr/bin/env bash +set -e + +echo "=========================================================" +echo " Speedcamera Raspberry Pi OS Lite Setup & Install Script" +echo "=========================================================" + +# 1. Update and install required system packages +echo "[1/5] Installing system packages (Aravis, esptool, NetworkManager)..." +sudo apt-get update +sudo apt-get install -y \ + libaravis-0.8-0 \ + libaravis-dev \ + python3-esptool \ + network-manager \ + curl \ + unzip \ + git + +# 2. Check/Install Bun runtime +if ! command -v bun &> /dev/null; then + echo "[2/5] Installing Bun runtime for ARM64..." + curl -fsSL https://bun.sh/install | bash + export BUN_INSTALL="$HOME/.bun" + export PATH="$BUN_INSTALL/bin:$PATH" +else + echo "[2/5] Bun already installed: $(bun --version)" +fi + +# 3. Install project dependencies and build frontend +echo "[3/5] Installing project dependencies & building frontend..." +bun install +bun run build + +# 4. Configure Networking (Camera LAN 192.168.1.100 + Wi-Fi Hotspot 192.168.4.1) +echo "[4/5] Network Configuration (Camera LAN & Wi-Fi Hotspot)" +read -p "Do you want to configure the dual-subnet network interfaces? (y/N) " -n 1 -r +echo +if [[ $REPLY =~ ^[Yy]$ ]]; then + # Detect interfaces + ETH_IFACE=$(ip -o link show | awk -F': ' '{print $2}' | grep -E '^(eth|end|enp)' | head -n 1 || echo "eth0") + WIFI_IFACE=$(ip -o link show | awk -F': ' '{print $2}' | grep -E '^(wlan|wifi|wlp)' | head -n 1 || echo "wlan0") + + # 4a. Camera Ethernet LAN + echo "Configuring Camera LAN on ${ETH_IFACE} (Static IP: 192.168.1.100/24)..." + sudo nmcli connection delete "Speedcamera-CameraLAN" 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 + sudo nmcli connection up "Speedcamera-CameraLAN" || echo "Note: Ethernet link active when camera connected." + + # 4b. Wi-Fi Hotspot + SSID="speedcamera" + PASS="speedcamerapass" + echo "Configuring Wi-Fi Hotspot on ${WIFI_IFACE} (SSID: '${SSID}', IP: 192.168.4.1/24)..." + sudo nmcli connection delete "Speedcamera-Hotspot" 2>/dev/null || true + sudo nmcli connection add type wifi ifname "${WIFI_IFACE}" con-name "Speedcamera-Hotspot" autoconnect yes \ + ssid "${SSID}" mode ap 802-11-wireless.band bg \ + ipv4.method shared ipv4.addresses 192.168.4.1/24 \ + wifi-sec.key-mgmt wpa-psk wifi-sec.psk "${PASS}" + sudo nmcli connection up "Speedcamera-Hotspot" || echo "Note: Run 'sudo nmcli connection up Speedcamera-Hotspot' once wireless interface is ready." +fi + +# 5. Install and enable systemd service +echo "[5/5] Installing systemd autostart service..." +CURRENT_USER=$(whoami) +PROJECT_DIR=$(pwd) +BUN_BIN=$(command -v bun || echo "$HOME/.bun/bin/bun") + +SERVICE_FILE="/etc/systemd/system/speedcamera.service" + +sudo bash -c "cat > ${SERVICE_FILE}" < Static IP 192.168.1.100/24 (Subnet 192.168.1.0/24 for GigE camera)" +echo " 2. Hotspot AP (wlan0) -> Static IP 192.168.4.1/24 (Subnet 192.168.4.0/24 for Web UI clients)" +echo "=========================================================" + +# Detect Ethernet Interface (eth0, end0, 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, 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 AP): ${WIFI_IFACE}" +echo "" + +# 1. Configure Ethernet Camera LAN (192.168.1.100/24) +echo "[1/2] Configuring Camera LAN on ${ETH_IFACE}..." +echo " Setting static IPv4: 192.168.1.100/24 (Camera subnet)..." + +sudo nmcli connection delete "Speedcamera-CameraLAN" 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 + +sudo nmcli connection up "Speedcamera-CameraLAN" || echo "Note: Ethernet link will come up when camera cable is connected." + +# 2. Configure Wi-Fi Hotspot AP (192.168.4.1/24) +echo "" +echo "[2/2] Configuring Wi-Fi Hotspot AP on ${WIFI_IFACE}..." +SSID="speedcamera" +PASS="speedcamerapass" + +sudo nmcli connection delete "Speedcamera-Hotspot" 2>/dev/null || true + +sudo nmcli connection add type wifi \ + ifname "${WIFI_IFACE}" \ + con-name "Speedcamera-Hotspot" \ + autoconnect yes \ + ssid "${SSID}" \ + mode ap \ + 802-11-wireless.band bg \ + ipv4.method shared \ + ipv4.addresses 192.168.4.1/24 \ + wifi-sec.key-mgmt wpa-psk \ + wifi-sec.psk "${PASS}" + +sudo nmcli connection up "Speedcamera-Hotspot" || echo "Note: Run 'sudo nmcli connection up Speedcamera-Hotspot' once wireless interface is ready." + +echo "" +echo "=========================================================" +echo " Network setup complete!" +echo " • Industrial Camera LAN: ${ETH_IFACE} @ 192.168.1.100" +echo " • Wi-Fi Access Point: ${WIFI_IFACE} @ 192.168.4.1 (SSID: ${SSID})" +echo " • Web UI Accessible at: http://192.168.4.1:3000" +echo "=========================================================" diff --git a/headless/scripts/speedcamera.service b/headless/scripts/speedcamera.service new file mode 100644 index 0000000..08c1b02 --- /dev/null +++ b/headless/scripts/speedcamera.service @@ -0,0 +1,21 @@ +[Unit] +Description=Speedcamera Headless Daemon & Web Server +After=network.target network-online.target +Wants=network-online.target + +[Service] +Type=simple +User=pi +WorkingDirectory=/home/pi/speedcamera/headless +Environment=NODE_ENV=production +Environment=PORT=3000 +Environment=HOST=0.0.0.0 +Environment=DATA_DIR=/home/pi/.speedcamera +ExecStart=/home/pi/.bun/bin/bun src/server/index.ts +Restart=always +RestartSec=3 +KillSignal=SIGINT +LimitNOFILE=65536 + +[Install] +WantedBy=multi-user.target diff --git a/headless/scripts/test-server.ts b/headless/scripts/test-server.ts new file mode 100644 index 0000000..a8ec06d --- /dev/null +++ b/headless/scripts/test-server.ts @@ -0,0 +1,64 @@ +import { spawn } from "child_process"; + +console.log("Starting speedcamera headless server in mock mode..."); +const proc = spawn("bun", ["src/server/index.ts"], { + cwd: process.cwd(), + env: { ...process.env, MOCK_MODE: "true", PORT: "3099" }, + stdio: "pipe", +}); + +proc.stdout?.on("data", (data) => console.log(`[server stdout] ${data}`)); +proc.stderr?.on("data", (data) => console.error(`[server stderr] ${data}`)); + +// Wait 1s for server to start +await new Promise((r) => setTimeout(r, 1200)); + +try { + // 1. Test Health endpoint + console.log("Testing GET http://localhost:3099/api/health ..."); + const healthRes = await fetch("http://localhost: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 SPA index.html + console.log("Testing GET http://localhost:3099/ ..."); + const indexRes = await fetch("http://localhost:3099/"); + const indexHtml = await indexRes.text(); + if (!indexHtml.includes("")) throw new Error("SPA index.html not served"); + console.log("SPA index.html served correctly! Length:", indexHtml.length); + + // 3. Test WebSocket RPC + console.log("Testing WebSocket RPC on ws://localhost:3099/ws/rpc ..."); + const ws = new WebSocket("ws://localhost:3099/ws/rpc"); + + await new Promise((resolve, reject) => { + ws.onopen = () => { + console.log("WebSocket connected successfully!"); + // Send RPC request for getSettings + ws.send(JSON.stringify({ id: 1, method: "getSettings", params: {} })); + }; + + ws.onmessage = (event) => { + console.log("WS message received:", event.data); + const data = JSON.parse(event.data); + if (data.id === 1) { + console.log("RPC getSettings result:", data.result); + if (data.result && typeof data.result.maxSpeed === "number") { + console.log("SUCCESS: Settings RPC validated!"); + resolve(); + } else { + reject(new Error("Unexpected RPC response")); + } + } + }; + + ws.onerror = (err) => reject(err); + setTimeout(() => reject(new Error("WS Timeout")), 5000); + }); + + console.log("ALL TESTS PASSED SUCCESSFULLY!"); +} finally { + proc.kill(); +} +process.exit(0); diff --git a/headless/scripts/verify-ws.ts b/headless/scripts/verify-ws.ts new file mode 100644 index 0000000..3ebfdf5 --- /dev/null +++ b/headless/scripts/verify-ws.ts @@ -0,0 +1,54 @@ +console.log("Connecting to WebSocket on ws://127.0.0.1:3099/ws/rpc ..."); +const ws = new WebSocket("ws://127.0.0.1:3099/ws/rpc"); + +let receivedCameraPush = false; +let receivedSettingsResponse = false; +let receivedViolationsResponse = false; + +ws.onopen = () => { + console.log("[WS] Connected to Speedcamera Headless Daemon!"); + // 1. Request getSettings + ws.send(JSON.stringify({ id: 101, method: "getSettings", params: {} })); + // 2. Request getViolations + ws.send(JSON.stringify({ id: 102, method: "getViolations", params: { page: 1, limit: 10 } })); +}; + +ws.onmessage = (event) => { + console.log("[WS] Message received:", event.data); + const data = JSON.parse(event.data); + + if (data.event === "cameraStatus") { + receivedCameraPush = true; + console.log("-> Push message 'cameraStatus' verified!"); + } + + if (data.id === 101) { + if (data.result && typeof data.result.maxSpeed === "number") { + receivedSettingsResponse = true; + console.log("-> RPC 'getSettings' verified! Max speed:", data.result.maxSpeed); + } + } + + if (data.id === 102) { + if (data.result && Array.isArray(data.result.violations)) { + receivedViolationsResponse = true; + console.log("-> RPC 'getViolations' verified! Total violations:", data.result.total); + } + } + + if (receivedCameraPush && receivedSettingsResponse && receivedViolationsResponse) { + console.log("\n>>> ALL WEBSOCKET RPC CHECKS PASSED PERFECTLY! <<<"); + ws.close(); + process.exit(0); + } +}; + +ws.onerror = (err) => { + console.error("WS error:", err); + process.exit(1); +}; + +setTimeout(() => { + console.error("Test timeout after 5s"); + process.exit(1); +}, 5000); diff --git a/headless/src/components/ArmingButton.tsx b/headless/src/components/ArmingButton.tsx new file mode 100644 index 0000000..071b056 --- /dev/null +++ b/headless/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 setSystemState = useAppStore((s) => s.setSystemState); + 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); + setSystemState("ARMED"); + return; + } + + if (p < 1) { + rafRef.current = requestAnimationFrame(tick); + } + }; + + rafRef.current = requestAnimationFrame(tick); + }, [systemState, setSystemState]); + + 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") { + setSystemState("DISARMED"); + } + }, [systemState, setSystemState]); + + // 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/src/components/ErrorBoundary.tsx b/headless/src/components/ErrorBoundary.tsx new file mode 100644 index 0000000..ac8984f --- /dev/null +++ b/headless/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/src/components/FirmwareFlasher.tsx b/headless/src/components/FirmwareFlasher.tsx new file mode 100644 index 0000000..50db99b --- /dev/null +++ b/headless/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/src/components/LapImageThumbnails.tsx b/headless/src/components/LapImageThumbnails.tsx new file mode 100644 index 0000000..04f2b89 --- /dev/null +++ b/headless/src/components/LapImageThumbnails.tsx @@ -0,0 +1,92 @@ +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. + * Fetches image data lazily via the RPC and cancels pending fetches on unmount. + */ +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); + if (startImagePath) { + getRpc() + .request.getImageData({ imagePath: startImagePath }) + .then((data) => { if (!cancelled) setStartImageUrl(data); }) + .catch(() => {}); + } + if (endImagePath) { + getRpc() + .request.getImageData({ imagePath: endImagePath }) + .then((data) => { if (!cancelled) setEndImageUrl(data); }) + .catch(() => {}); + } + return () => { cancelled = true; }; + }, [startImagePath, endImagePath]); + + return ( + <> +
+ {(startImageUrl || endImageUrl) ? ( + <> + {startImageUrl && ( + + )} + {endImageUrl && ( + + )} + + ) : ( + — + )} + {trailing} +
+ + !open && setLightboxUrl(null)}> + + {lightboxUrl && ( + Lap capture + )} + + + + ); +} diff --git a/headless/src/components/LapTimerDisplay.tsx b/headless/src/components/LapTimerDisplay.tsx new file mode 100644 index 0000000..6d46702 --- /dev/null +++ b/headless/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/src/components/LastCapturedImage.tsx b/headless/src/components/LastCapturedImage.tsx new file mode 100644 index 0000000..42dd6d0 --- /dev/null +++ b/headless/src/components/LastCapturedImage.tsx @@ -0,0 +1,48 @@ +import { useEffect, useState } from "react"; +import { getRpc } from "@/lib/rpc"; +import { useAppStore } from "@/stores/useAppStore"; +import { Image as ImageIcon } from "lucide-react"; + +export function LastCapturedImage() { + const lastViolation = useAppStore((s) => s.lastViolation); + const [imageSrc, setImageSrc] = useState(null); + + useEffect(() => { + if (lastViolation) { + getRpc().request.getImageData({ imagePath: lastViolation.imagePath }).then(setImageSrc).catch(() => setImageSrc(null)); + } else { + setImageSrc(null); + } + }, [lastViolation]); + + return ( +
+ {imageSrc ? ( + Last capture + ) : ( +
+ +

Awaiting Capture

+
+ )} + + {lastViolation && ( +
+ + {new Date(lastViolation.timestamp).toLocaleTimeString()} + +
+ + {lastViolation.measuredSpeed} + + km/h +
+
+ )} +
+ ); +} diff --git a/headless/src/components/NavigationMenu.tsx b/headless/src/components/NavigationMenu.tsx new file mode 100644 index 0000000..72efed8 --- /dev/null +++ b/headless/src/components/NavigationMenu.tsx @@ -0,0 +1,73 @@ +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"; + +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/src/components/StatusBadge.tsx b/headless/src/components/StatusBadge.tsx new file mode 100644 index 0000000..1117706 --- /dev/null +++ b/headless/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/src/components/ThemeToggle.tsx b/headless/src/components/ThemeToggle.tsx new file mode 100644 index 0000000..304782e --- /dev/null +++ b/headless/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/src/components/ViolationCard.tsx b/headless/src/components/ViolationCard.tsx new file mode 100644 index 0000000..5b92539 --- /dev/null +++ b/headless/src/components/ViolationCard.tsx @@ -0,0 +1,140 @@ +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); + + getRpc() + .request.getImageData({ imagePath: violation.imagePath }) + .then((data) => { + if (!cancelled) setImageData(data); + }) + .catch(() => { + if (!cancelled) setImageData(null); + }) + .finally(() => { + if (!cancelled) setImageLoading(false); + }); + + return () => { + cancelled = true; + }; + }, [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/src/components/ui/badge.tsx b/headless/src/components/ui/badge.tsx new file mode 100644 index 0000000..f428bc5 --- /dev/null +++ b/headless/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/src/components/ui/button.tsx b/headless/src/components/ui/button.tsx new file mode 100644 index 0000000..652d5d3 --- /dev/null +++ b/headless/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/src/components/ui/card.tsx b/headless/src/components/ui/card.tsx new file mode 100644 index 0000000..593879d --- /dev/null +++ b/headless/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/src/components/ui/checkbox.tsx b/headless/src/components/ui/checkbox.tsx new file mode 100644 index 0000000..3eb403b --- /dev/null +++ b/headless/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/src/components/ui/collapsible.tsx b/headless/src/components/ui/collapsible.tsx new file mode 100644 index 0000000..63fc8ef --- /dev/null +++ b/headless/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/src/components/ui/dialog.tsx b/headless/src/components/ui/dialog.tsx new file mode 100644 index 0000000..545c411 --- /dev/null +++ b/headless/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/src/components/ui/input.tsx b/headless/src/components/ui/input.tsx new file mode 100644 index 0000000..e49996f --- /dev/null +++ b/headless/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/src/components/ui/label.tsx b/headless/src/components/ui/label.tsx new file mode 100644 index 0000000..f752f82 --- /dev/null +++ b/headless/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/src/components/ui/progress.tsx b/headless/src/components/ui/progress.tsx new file mode 100644 index 0000000..0bcb123 --- /dev/null +++ b/headless/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/src/components/ui/scroll-area.tsx b/headless/src/components/ui/scroll-area.tsx new file mode 100644 index 0000000..f49b0a8 --- /dev/null +++ b/headless/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/src/components/ui/select.tsx b/headless/src/components/ui/select.tsx new file mode 100644 index 0000000..f3b0139 --- /dev/null +++ b/headless/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/src/components/ui/skeleton.tsx b/headless/src/components/ui/skeleton.tsx new file mode 100644 index 0000000..ed70d9e --- /dev/null +++ b/headless/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/src/components/ui/slider.tsx b/headless/src/components/ui/slider.tsx new file mode 100644 index 0000000..5a4db16 --- /dev/null +++ b/headless/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/src/components/ui/sonner.tsx b/headless/src/components/ui/sonner.tsx new file mode 100644 index 0000000..bd6eb71 --- /dev/null +++ b/headless/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/src/components/ui/switch.tsx b/headless/src/components/ui/switch.tsx new file mode 100644 index 0000000..134e8e2 --- /dev/null +++ b/headless/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/src/components/ui/toggle-group.tsx b/headless/src/components/ui/toggle-group.tsx new file mode 100644 index 0000000..f62c08c --- /dev/null +++ b/headless/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/src/components/ui/toggle.tsx b/headless/src/components/ui/toggle.tsx new file mode 100644 index 0000000..15b3df4 --- /dev/null +++ b/headless/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/src/hooks/useLiveLapTimer.ts b/headless/src/hooks/useLiveLapTimer.ts new file mode 100644 index 0000000..f2d4171 --- /dev/null +++ b/headless/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/src/hooks/useSystemStateSync.ts b/headless/src/hooks/useSystemStateSync.ts new file mode 100644 index 0000000..bbc7915 --- /dev/null +++ b/headless/src/hooks/useSystemStateSync.ts @@ -0,0 +1,31 @@ +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 connectedPort = useAppStore((s) => s.connectedPort); + const cameraConnected = useAppStore((s) => s.cameraConnected); + + const conditionsMet = !!connectedPort && cameraConnected; + + useEffect(() => { + if (conditionsMet) { + if (systemState === "PASSIVE") { + setSystemState("DISARMED"); + } + } else { + if (systemState !== "PASSIVE") { + setSystemState("PASSIVE"); + } + } + }, [conditionsMet, systemState, setSystemState]); +} diff --git a/headless/src/lib/format.ts b/headless/src/lib/format.ts new file mode 100644 index 0000000..e2ebb7d --- /dev/null +++ b/headless/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/src/lib/rpc.ts b/headless/src/lib/rpc.ts new file mode 100644 index 0000000..2d544a6 --- /dev/null +++ b/headless/src/lib/rpc.ts @@ -0,0 +1,173 @@ +import type { SpeedcameraRPC } from "@/shared/types"; +import { useAppStore } from "@/stores/useAppStore"; + +type RequestMap = SpeedcameraRPC["bun"]["requests"]; +type PushMessageMap = SpeedcameraRPC["webview"]["messages"]; + +export type SpeedcameraClientRPC = { + request: { + [K in keyof RequestMap]: ( + params: RequestMap[K]["params"] + ) => Promise; + }; +}; + +class WebSocketRpcClient { + private ws: WebSocket | null = null; + private reqIdCounter = 0; + private pendingRequests = new Map< + string | number, + { + resolve: (val: any) => void; + reject: (err: any) => void; + timer: ReturnType; + } + >(); + private reconnectTimeout: ReturnType | null = null; + private isConnecting = false; + + constructor() { + this.connect(); + } + + private getWebSocketUrl(): string { + if (typeof window === "undefined") return "ws://127.0.0.1:3000/ws/rpc"; + const protocol = window.location.protocol === "https:" ? "wss:" : "ws:"; + const host = window.location.host; // includes port (e.g. localhost:5173 or 192.168.4.1:3000) + return `${protocol}//${host}/ws/rpc`; + } + + private connect() { + if (typeof window === "undefined" || this.isConnecting) return; + this.isConnecting = true; + + try { + const url = this.getWebSocketUrl(); + const ws = new WebSocket(url); + this.ws = ws; + + ws.onopen = () => { + console.log("[rpc-client] Connected to speedcamera daemon"); + this.isConnecting = false; + }; + + ws.onmessage = (event) => { + try { + const data = JSON.parse(event.data); + + // Case 1: Response to a pending request + if (data.id !== undefined && this.pendingRequests.has(data.id)) { + const pending = this.pendingRequests.get(data.id)!; + this.pendingRequests.delete(data.id); + clearTimeout(pending.timer); + + if (data.error) { + pending.reject(new Error(data.error)); + } else { + pending.resolve(data.result); + } + return; + } + + // Case 2: Server push broadcast event + if (data.event) { + this.handlePushEvent(data.event as keyof PushMessageMap, data.payload); + return; + } + } catch (err) { + console.error("[rpc-client] Error handling message:", err); + } + }; + + ws.onerror = (err) => { + console.warn("[rpc-client] WebSocket error:", err); + }; + + ws.onclose = () => { + console.log("[rpc-client] Disconnected. Reconnecting in 2s..."); + this.isConnecting = false; + this.ws = null; + if (!this.reconnectTimeout) { + this.reconnectTimeout = setTimeout(() => { + this.reconnectTimeout = null; + this.connect(); + }, 2000); + } + }; + } catch (err) { + this.isConnecting = false; + console.error("[rpc-client] Connection failed:", err); + } + } + + private handlePushEvent(event: K, payload: PushMessageMap[K]) { + const store = useAppStore.getState(); + switch (event) { + case "serialStatus": + store.handleSerialStatus(payload as any); + break; + case "flashProgress": + store.handleFlashProgress(payload as any); + break; + case "cameraStatus": + store.setCameraStatus(payload as any); + break; + case "liveFrame": + store.setLiveFrame(payload as any); + break; + case "updateAvailable": + store.setUpdateVersion((payload as any).version); + store.setUpdatePhase("ready"); + break; + case "updateProgress": + store.handleUpdateProgress(payload as any); + break; + default: + break; + } + } + + public call(method: string, params: any): Promise { + return new Promise((resolve, reject) => { + const id = ++this.reqIdCounter; + const timer = setTimeout(() => { + if (this.pendingRequests.has(id)) { + this.pendingRequests.delete(id); + reject(new Error(`RPC request '${method}' timed out after 10000ms`)); + } + }, 10000); + + this.pendingRequests.set(id, { resolve, reject, timer }); + + if (this.ws && this.ws.readyState === WebSocket.OPEN) { + this.ws.send(JSON.stringify({ id, method, params })); + } else { + // If websocket not ready yet, wait briefly or connect + const checkInterval = setInterval(() => { + if (this.ws && this.ws.readyState === WebSocket.OPEN) { + clearInterval(checkInterval); + this.ws.send(JSON.stringify({ id, method, params })); + } + }, 100); + + // Cancel retry if request times out + setTimeout(() => clearInterval(checkInterval), 9500); + } + }); + } +} + +const client = new WebSocketRpcClient(); + +// Proxy accessor so `getRpc().request.someMethod(params)` works transparently +const rpcProxy: SpeedcameraClientRPC = { + request: new Proxy({} as any, { + get(_target, prop: string) { + return (params: any = {}) => client.call(prop, params); + }, + }), +}; + +export function getRpc(): SpeedcameraClientRPC { + return rpcProxy; +} diff --git a/headless/src/lib/sound.ts b/headless/src/lib/sound.ts new file mode 100644 index 0000000..5e3aaf8 --- /dev/null +++ b/headless/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/src/lib/utils.ts b/headless/src/lib/utils.ts new file mode 100644 index 0000000..a5ef193 --- /dev/null +++ b/headless/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/src/mainview/App.tsx b/headless/src/mainview/App.tsx new file mode 100644 index 0000000..ffaa34b --- /dev/null +++ b/headless/src/mainview/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/src/mainview/index.css b/headless/src/mainview/index.css new file mode 100644 index 0000000..805a3da --- /dev/null +++ b/headless/src/mainview/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; + } +} \ No newline at end of file diff --git a/headless/src/mainview/index.html b/headless/src/mainview/index.html new file mode 100644 index 0000000..a174d4c --- /dev/null +++ b/headless/src/mainview/index.html @@ -0,0 +1,12 @@ + + + + + + React + Tailwind + Vite + + +
+ + + diff --git a/headless/src/mainview/main.tsx b/headless/src/mainview/main.tsx new file mode 100644 index 0000000..07c9565 --- /dev/null +++ b/headless/src/mainview/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/src/routes/__root.tsx b/headless/src/routes/__root.tsx new file mode 100644 index 0000000..c077548 --- /dev/null +++ b/headless/src/routes/__root.tsx @@ -0,0 +1,40 @@ +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"; + +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); + + useEffect(() => { + void loadLapSettings(); + void loadTeableState(); + void refreshCameraStatus(); + }, [loadLapSettings, loadTeableState, refreshCameraStatus]); + + return ( +
+ {/* App-level navigation bar */} +
+ +
+ +
+
+ + {/* Page content */} +
+ +
+
+ ); +} diff --git a/headless/src/routes/about.tsx b/headless/src/routes/about.tsx new file mode 100644 index 0000000..4c411da --- /dev/null +++ b/headless/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 + Electrobun + Bun +
+
+ UI + React + shadcn/ui +
+
+ + {/* ── 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/src/routes/index.tsx b/headless/src/routes/index.tsx new file mode 100644 index 0000000..4560f2d --- /dev/null +++ b/headless/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/src/routes/laps.tsx b/headless/src/routes/laps.tsx new file mode 100644 index 0000000..6d458a4 --- /dev/null +++ b/headless/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/src/routes/laps/HistoryTab.tsx b/headless/src/routes/laps/HistoryTab.tsx new file mode 100644 index 0000000..e99400b --- /dev/null +++ b/headless/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/src/routes/laps/LapRow.tsx b/headless/src/routes/laps/LapRow.tsx new file mode 100644 index 0000000..7ad4a96 --- /dev/null +++ b/headless/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/src/routes/laps/LiveSessionTab.tsx b/headless/src/routes/laps/LiveSessionTab.tsx new file mode 100644 index 0000000..5e52f5f --- /dev/null +++ b/headless/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/src/routes/laps/SessionCard.tsx b/headless/src/routes/laps/SessionCard.tsx new file mode 100644 index 0000000..e1b74bb --- /dev/null +++ b/headless/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/src/routes/settings.tsx b/headless/src/routes/settings.tsx new file mode 100644 index 0000000..1efef51 --- /dev/null +++ b/headless/src/routes/settings.tsx @@ -0,0 +1,58 @@ +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 { 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", "camera", "speed-camera", "lap-timer"] as const).map((tab) => ( + + {tab === "device" + ? "Device" + : tab === "camera" + ? "Camera" + : tab === "speed-camera" + ? "Speed Camera" + : "Lap Timer"} + + ))} + + + + + + + + + + + + + + + +
+ ); +} diff --git a/headless/src/routes/settings/CameraTab.tsx b/headless/src/routes/settings/CameraTab.tsx new file mode 100644 index 0000000..f206ed6 --- /dev/null +++ b/headless/src/routes/settings/CameraTab.tsx @@ -0,0 +1,424 @@ +import { useState, useEffect } from "react"; +import type { ChangeEvent } from "react"; +import { toast } from "sonner"; +import { useAppStore } from "@/stores/useAppStore"; +import type { HwControl, SystemNetworkSummary } from "@/shared/types"; +import { getRpc } from "@/lib/rpc"; +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, Network } 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} +
+
+ ); +} + +function NetworkStatusSection() { + const [network, setNetwork] = useState(null); + const [loading, setLoading] = useState(false); + + const fetchNetwork = () => { + setLoading(true); + getRpc() + .request.getNetworkInfo({}) + .then(setNetwork) + .catch(() => {}) + .finally(() => setLoading(false)); + }; + + useEffect(() => { + fetchNetwork(); + }, []); + + if (!network) return null; + + return ( +
+
+

+ + Network & Subnet Architecture +

+ +
+ +
+ {/* Camera LAN */} +
+
+ Camera LAN (eth0) + {network.cameraLan.status === "ok" ? ( + 192.168.1.100 OK + ) : network.cameraLan.status === "ip_mismatch" ? ( + {network.cameraLan.ip || "Mismatch"} + ) : ( + Not Found + )} +
+
+
IP: {network.cameraLan.ip || "Unassigned"}
+
Subnet: {network.cameraLan.subnet}
+
+

+ Dedicated interface for GigE Vision camera streaming. +

+
+ + {/* Wi-Fi Hotspot */} +
+
+ Hotspot AP (wlan0) + {network.hotspotAp.status === "ok" ? ( + 192.168.4.1 OK + ) : network.hotspotAp.status === "ip_mismatch" ? ( + {network.hotspotAp.ip} + ) : ( + Inactive + )} +
+
+
IP: {network.hotspotAp.ip || "Unassigned"}
+
Web UI: :3000
+
+

+ Wi-Fi access point for remote browser controller. +

+
+
+
+ ); +} + diff --git a/headless/src/routes/settings/DeviceTab.tsx b/headless/src/routes/settings/DeviceTab.tsx new file mode 100644 index 0000000..ef53260 --- /dev/null +++ b/headless/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/src/routes/settings/LapTimerTab.tsx b/headless/src/routes/settings/LapTimerTab.tsx new file mode 100644 index 0000000..6cb860c --- /dev/null +++ b/headless/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/src/routes/settings/SpeedCameraTab.tsx b/headless/src/routes/settings/SpeedCameraTab.tsx new file mode 100644 index 0000000..18ded97 --- /dev/null +++ b/headless/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/src/routes/setup.tsx b/headless/src/routes/setup.tsx new file mode 100644 index 0000000..f71136b --- /dev/null +++ b/headless/src/routes/setup.tsx @@ -0,0 +1,97 @@ +import { useEffect } from "react"; +import { createRoute } from "@tanstack/react-router"; +import { RootRoute } from "./__root"; +import { useAppStore } from "@/stores/useAppStore"; +import { Button } from "@/components/ui/button"; +import { Badge } from "@/components/ui/badge"; +import { PlayIcon, SquareIcon, AlertCircleIcon } 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 liveFrame = useAppStore((s) => s.liveFrame); + const startSetupStream = useAppStore((s) => s.startSetupStream); + const stopSetupStream = useAppStore((s) => s.stopSetupStream); + + useEffect(() => { + // Stop stream on unmount + return () => { + stopSetupStream().catch(console.error); + }; + }, [stopSetupStream]); + + const handleStart = async () => { + if (!connected) { + toast.error("Camera is not connected!"); + return; + } + try { + await startSetupStream(); + } catch { + toast.error("Failed to start setup stream"); + } + }; + + const handleStop = async () => { + try { + await stopSetupStream(); + } catch { + toast.error("Failed to stop setup stream"); + } + }; + + return ( +
+
+
+

Camera Setup

+

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

+
+
+ + {setupStreamActive ? "Streaming" : "Stopped"} + + {!setupStreamActive ? ( + + ) : ( + + )} +
+
+ +
+ {setupStreamActive ? ( + liveFrame ? ( + Camera Livestream + ) : ( +
+ Waiting for frame... +
+ ) + ) : ( +
+ {connected ? "Click Start Stream to begin setup" : "Camera disconnected"} +
+ )} +
+
+ ); +} diff --git a/headless/src/routes/teable.tsx b/headless/src/routes/teable.tsx new file mode 100644 index 0000000..edee3c3 --- /dev/null +++ b/headless/src/routes/teable.tsx @@ -0,0 +1,32 @@ +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, +}); + +// ─── Page shell ─────────────────────────────────────────────────────────────── + +function TeablePage() { + return ( +
+
+
+

Teable Integration

+

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

+
+ + + +
+
+ ); +} + diff --git a/headless/src/routes/teable/ConnectionSection.tsx b/headless/src/routes/teable/ConnectionSection.tsx new file mode 100644 index 0000000..745db77 --- /dev/null +++ b/headless/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/src/routes/teable/SchemaStatus.tsx b/headless/src/routes/teable/SchemaStatus.tsx new file mode 100644 index 0000000..fb35d59 --- /dev/null +++ b/headless/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/src/routes/teable/SyncToggleSection.tsx b/headless/src/routes/teable/SyncToggleSection.tsx new file mode 100644 index 0000000..40e6a13 --- /dev/null +++ b/headless/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/src/routes/teable/TableTargetSection.tsx b/headless/src/routes/teable/TableTargetSection.tsx new file mode 100644 index 0000000..db59c59 --- /dev/null +++ b/headless/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/src/routes/violations.tsx b/headless/src/routes/violations.tsx new file mode 100644 index 0000000..241d84d --- /dev/null +++ b/headless/src/routes/violations.tsx @@ -0,0 +1,174 @@ +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(); + + // ponytail: view preference stored in localStorage + 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 + )} + + + + x.id)} + /> +
+ ); +} diff --git a/headless/src/routes/violations/ExportImagesDialog.tsx b/headless/src/routes/violations/ExportImagesDialog.tsx new file mode 100644 index 0000000..bf922ee --- /dev/null +++ b/headless/src/routes/violations/ExportImagesDialog.tsx @@ -0,0 +1,79 @@ +import { useState } from "react"; +import { toast } from "sonner"; +import { getRpc } from "@/lib/rpc"; +import { Button } from "@/components/ui/button"; +import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog"; + +interface ExportImagesDialogProps { + open: boolean; + onOpenChange: (open: boolean) => void; + selectedIds: number[]; + pageViolationIds: number[]; +} + +export function ExportImagesDialog({ + open, + onOpenChange, + selectedIds, + pageViolationIds, +}: ExportImagesDialogProps) { + const selectedCount = selectedIds.length; + const pageViolationCount = pageViolationIds.length; + const [exportDir, setExportDir] = useState(""); + const [exporting, setExporting] = useState(false); + + const handleExport = async () => { + if (!exportDir.trim()) { + toast.error("Please enter an export directory"); + return; + } + setExporting(true); + try { + // ponytail: export selected if any, else all on current page + const ids = selectedCount > 0 ? selectedIds : pageViolationIds; + const result = await getRpc().request.exportSkinnedImages({ + violationIds: ids, + targetDir: exportDir.trim(), + }); + toast.success(`Exported ${result.exported} images${result.failed ? `, ${result.failed} failed` : ""}`); + onOpenChange(false); + } catch { + toast.error("Failed to export images"); + } finally { + setExporting(false); + } + }; + + return ( + + + + Export Skinned Images + +

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

+
+ + setExportDir(e.target.value)} + placeholder="/home/user/exports" + 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/src/routes/violations/ViolationGridTile.tsx b/headless/src/routes/violations/ViolationGridTile.tsx new file mode 100644 index 0000000..b1dc7e6 --- /dev/null +++ b/headless/src/routes/violations/ViolationGridTile.tsx @@ -0,0 +1,133 @@ +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) { + const { imageData, imageLoading } = useViolationImage(violation, skinEnabled); + 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 handleDelete = async (e: React.MouseEvent) => { + e.stopPropagation(); + setDeleting(true); + try { + await onDelete(); + } finally { + setDeleting(false); + } + }; + + return ( +
+
imageData && onImageClick(imageData)} + > +
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/src/routes/violations/ViolationRow.tsx b/headless/src/routes/violations/ViolationRow.tsx new file mode 100644 index 0000000..1db1ddb --- /dev/null +++ b/headless/src/routes/violations/ViolationRow.tsx @@ -0,0 +1,111 @@ +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) { + const { imageData, imageLoading } = useViolationImage(violation, skinEnabled); + 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 handleDelete = async () => { + setDeleting(true); + try { + await onDelete(); + } finally { + setDeleting(false); + } + }; + + return ( + + + + + + + + {formattedTime} + + + + + + + {violation.measuredSpeed} + + {violation.maxSpeed} + +{over} + + + + + ); +} diff --git a/headless/src/routes/violations/ViolationsGrid.tsx b/headless/src/routes/violations/ViolationsGrid.tsx new file mode 100644 index 0000000..c763607 --- /dev/null +++ b/headless/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/src/routes/violations/ViolationsTable.tsx b/headless/src/routes/violations/ViolationsTable.tsx new file mode 100644 index 0000000..4b673ea --- /dev/null +++ b/headless/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/src/routes/violations/ViolationsToolbar.tsx b/headless/src/routes/violations/ViolationsToolbar.tsx new file mode 100644 index 0000000..7f27ab2 --- /dev/null +++ b/headless/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/src/routes/violations/useViolationImage.ts b/headless/src/routes/violations/useViolationImage.ts new file mode 100644 index 0000000..621c636 --- /dev/null +++ b/headless/src/routes/violations/useViolationImage.ts @@ -0,0 +1,27 @@ +import { useEffect, useState } from "react"; +import { getRpc } from "@/lib/rpc"; +import type { Violation } from "@/shared/types"; + +/** + * Fetches a violation's image (raw or Poliscan-skinned) as a data-URL. + * Shared by ViolationRow and ViolationGridTile to dedupe the fetch effect. + */ +export function useViolationImage(violation: Violation, skinEnabled: boolean) { + const [imageData, setImageData] = useState(null); + const [imageLoading, setImageLoading] = useState(true); + + useEffect(() => { + let cancelled = false; + setImageLoading(true); + const fetchImage = skinEnabled + ? getRpc().request.getSkinnedImageData({ violationId: violation.id }) + : getRpc().request.getImageData({ imagePath: violation.imagePath }); + 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]); + + return { imageData, imageLoading }; +} diff --git a/headless/src/routes/violations/useViolations.ts b/headless/src/routes/violations/useViolations.ts new file mode 100644 index 0000000..29fc17a --- /dev/null +++ b/headless/src/routes/violations/useViolations.ts @@ -0,0 +1,186 @@ +import { useCallback, useEffect, useState } from "react"; +import { toast } from "sonner"; +import { getRpc } from "@/lib/rpc"; +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]); + + 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/src/server/database.ts b/headless/src/server/database.ts new file mode 100644 index 0000000..6dff97e --- /dev/null +++ b/headless/src/server/database.ts @@ -0,0 +1,431 @@ +import { Database } from "bun:sqlite"; +import path from "path"; +import { existsSync, mkdirSync } from "fs"; +import type { + Violation, + SaveViolationInput, + AppSettings, + ViolationQuery, + ViolationPage, + Lap, + LapSession, + LapSessionWithLaps, + SaveLapInput, +} from "../shared/types"; + +// ─── Default settings ──────────────────────────────────────────────────────── + +const DEFAULT_SETTINGS: AppSettings = { + maxSpeed: 30, + selectedPort: "", + // Industrial Camera Settings + cameraExposure: 5000, + cameraGain: 0, + strobeLineDuration: 5000, + pixelFormat: "Mono", + exposureAuto: "Off", + gainAuto: "Off", + frameRate: 30, + cameraWidth: 1280, + cameraHeight: 1024, + blackLevel: 0, + // Lap timer settings + lapMode: "single", + lapSaveImages: "true", + lapDirFilter: "both", + // Teable integration + teableUrl: "", + teableToken: "", + teableUserName: "", + teableUserEmail: "", + teableUserAvatar: "", + teableSpaceId: "", + teableBaseId: "", + teableTableId: "", + teableSyncEnabled: "false", + githubToken: "", + // Poliscan skin + skinMeasuringLocation: "", +}; + +// ─── Database directory resolution ────────────────────────────────────────── + +export function getUserDataDir(): string { + const dir = process.env.DATA_DIR || path.join(process.env.HOME || process.cwd(), ".speedcamera"); + if (!existsSync(dir)) { + mkdirSync(dir, { recursive: true }); + } + return dir; +} + +let _db: Database | null = null; + +export function getDb(): Database { + if (_db) return _db; + + const userDataDir = getUserDataDir(); + const dbPath = path.join(userDataDir, "speedcamera.db"); + const db = new Database(dbPath, { create: true }); + + db.run("PRAGMA journal_mode = WAL"); + db.run("PRAGMA foreign_keys = ON"); + + db.run(` + 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 + ) + `); + + try { + db.run("ALTER TABLE speed_violations ADD COLUMN direction TEXT NOT NULL DEFAULT 'forward'"); + } catch { + // Column already exists + } + + db.run(` + CREATE INDEX IF NOT EXISTS idx_timestamp ON speed_violations(timestamp) + `); + + db.run(` + CREATE TABLE IF NOT EXISTS settings ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL + ) + `); + + db.run(` + 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 + ) + `); + + db.run(` + 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 + ) + `); + + db.run(` + CREATE INDEX IF NOT EXISTS idx_laps_session ON laps(sessionId) + `); + + db.run(` + CREATE INDEX IF NOT EXISTS idx_lap_sessions_started ON lap_sessions(startedAt) + `); + + const insertDefault = db.prepare( + "INSERT OR IGNORE INTO settings (key, value) VALUES (?, ?)" + ); + for (const [key, value] of Object.entries(DEFAULT_SETTINGS)) { + insertDefault.run(key, String(value)); + } + + _db = db; + return db; +} + +// ─── Violation queries ─────────────────────────────────────────────────────── + +export function insertViolation(input: SaveViolationInput & { imagePath: string }): Violation { + const db = getDb(); + const now = new Date().toISOString(); + const stmt = db.prepare(` + INSERT INTO speed_violations (timestamp, measuredSpeed, maxSpeed, direction, imagePath, createdAt) + VALUES (?, ?, ?, ?, ?, ?) + `); + const result = stmt.run(now, input.measuredSpeed, input.maxSpeed, input.direction, input.imagePath, now); + return { + id: result.lastInsertRowid as number, + timestamp: now, + measuredSpeed: input.measuredSpeed, + maxSpeed: input.maxSpeed, + direction: input.direction, + imagePath: input.imagePath, + createdAt: now, + }; +} + +export function queryViolations(q: ViolationQuery): ViolationPage { + const db = getDb(); + const conditions: string[] = []; + const params: (string | number)[] = []; + + if (q.dateFrom) { + conditions.push("timestamp >= ?"); + params.push(q.dateFrom); + } + if (q.dateTo) { + conditions.push("timestamp <= ?"); + params.push(q.dateTo); + } + if (q.minSpeed != null) { + conditions.push("measuredSpeed >= ?"); + params.push(q.minSpeed); + } + + const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : ""; + + const countRow = db + .prepare(`SELECT COUNT(*) as total FROM speed_violations ${where}`) + .get(...params) as { total: number }; + + const offset = (q.page - 1) * q.limit; + const violations = db + .prepare( + `SELECT * FROM speed_violations ${where} ORDER BY timestamp DESC LIMIT ? OFFSET ?` + ) + .all(...params, q.limit, offset) as Violation[]; + + return { violations, total: countRow.total }; +} + +export function getViolationById(id: number): Violation | null { + const db = getDb(); + return ( + (db.prepare("SELECT * FROM speed_violations WHERE id = ?").get(id) as Violation | undefined) ?? + null + ); +} + +export function removeViolation(id: number): void { + const db = getDb(); + db.prepare("DELETE FROM speed_violations WHERE id = ?").run(id); +} + +export function exportCsv(opts: { + dateFrom?: string; + dateTo?: string; + minSpeed?: number; +}): string { + const db = getDb(); + const conditions: string[] = []; + const params: (string | number)[] = []; + + if (opts.dateFrom) { + conditions.push("timestamp >= ?"); + params.push(opts.dateFrom); + } + if (opts.dateTo) { + conditions.push("timestamp <= ?"); + params.push(opts.dateTo); + } + if (opts.minSpeed != null) { + conditions.push("measuredSpeed >= ?"); + params.push(opts.minSpeed); + } + + const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : ""; + const rows = db + .prepare(`SELECT * FROM speed_violations ${where} ORDER BY timestamp DESC`) + .all(...params) as Violation[]; + + const header = "id,timestamp,measuredSpeed,maxSpeed,direction,imagePath,createdAt"; + const lines = rows.map( + (r) => + `${r.id},"${r.timestamp}",${r.measuredSpeed},${r.maxSpeed},${r.direction},"${r.imagePath}","${r.createdAt}"` + ); + return [header, ...lines].join("\n"); +} + +// ─── Settings queries ──────────────────────────────────────────────────────── + +export function getSettings(): AppSettings { + const db = getDb(); + const rows = db.prepare("SELECT key, value FROM settings").all() as { + key: string; + value: string; + }[]; + + const map = Object.fromEntries(rows.map((r) => [r.key, r.value])); + + return { + maxSpeed: Number(map.maxSpeed ?? DEFAULT_SETTINGS.maxSpeed), + selectedPort: map.selectedPort ?? DEFAULT_SETTINGS.selectedPort, + cameraExposure: Number(map.cameraExposure ?? DEFAULT_SETTINGS.cameraExposure), + cameraGain: Number(map.cameraGain ?? DEFAULT_SETTINGS.cameraGain), + strobeLineDuration: Number(map.strobeLineDuration ?? DEFAULT_SETTINGS.strobeLineDuration), + pixelFormat: map.pixelFormat ?? DEFAULT_SETTINGS.pixelFormat, + exposureAuto: map.exposureAuto ?? DEFAULT_SETTINGS.exposureAuto, + gainAuto: map.gainAuto ?? DEFAULT_SETTINGS.gainAuto, + frameRate: Number(map.frameRate ?? DEFAULT_SETTINGS.frameRate), + cameraWidth: Number(map.cameraWidth ?? DEFAULT_SETTINGS.cameraWidth), + cameraHeight: Number(map.cameraHeight ?? DEFAULT_SETTINGS.cameraHeight), + blackLevel: Number(map.blackLevel ?? DEFAULT_SETTINGS.blackLevel), + lapMode: map.lapMode ?? DEFAULT_SETTINGS.lapMode, + lapSaveImages: map.lapSaveImages ?? DEFAULT_SETTINGS.lapSaveImages, + lapDirFilter: map.lapDirFilter ?? DEFAULT_SETTINGS.lapDirFilter, + teableUrl: map.teableUrl ?? DEFAULT_SETTINGS.teableUrl, + teableToken: map.teableToken ?? DEFAULT_SETTINGS.teableToken, + teableUserName: map.teableUserName ?? DEFAULT_SETTINGS.teableUserName, + teableUserEmail: map.teableUserEmail ?? DEFAULT_SETTINGS.teableUserEmail, + teableUserAvatar: map.teableUserAvatar ?? DEFAULT_SETTINGS.teableUserAvatar, + teableSpaceId: map.teableSpaceId ?? DEFAULT_SETTINGS.teableSpaceId, + teableBaseId: map.teableBaseId ?? DEFAULT_SETTINGS.teableBaseId, + teableTableId: map.teableTableId ?? DEFAULT_SETTINGS.teableTableId, + teableSyncEnabled: map.teableSyncEnabled ?? DEFAULT_SETTINGS.teableSyncEnabled, + githubToken: map.githubToken ?? DEFAULT_SETTINGS.githubToken, + skinMeasuringLocation: map.skinMeasuringLocation ?? DEFAULT_SETTINGS.skinMeasuringLocation, + }; +} + +export function saveSetting(key: keyof AppSettings, value: string): void { + const db = getDb(); + db.prepare("INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)").run( + key, + value + ); +} + +// ─── Lap session queries ─────────────────────────────────────────────────────── + +export function createLapSession(lapMode: string): LapSession { + const db = getDb(); + const now = new Date().toISOString(); + const result = db + .prepare( + "INSERT INTO lap_sessions (startedAt, endedAt, lapMode, createdAt) VALUES (?, NULL, ?, ?)" + ) + .run(now, lapMode, now); + return { + id: result.lastInsertRowid as number, + startedAt: now, + endedAt: null, + lapMode, + createdAt: now, + }; +} + +export function closeLapSession(id: number): void { + const db = getDb(); + const now = new Date().toISOString(); + db.prepare("UPDATE lap_sessions SET endedAt = ? WHERE id = ?").run(now, id); +} + +export function getLapSessions( + page: number, + limit: number +): { sessions: LapSessionWithLaps[]; total: number } { + const db = getDb(); + const countRow = db + .prepare("SELECT COUNT(*) as total FROM lap_sessions") + .get() as { total: number }; + + const offset = (page - 1) * limit; + const rows = db + .prepare( + "SELECT * FROM lap_sessions ORDER BY startedAt DESC LIMIT ? OFFSET ?" + ) + .all(limit, offset) as LapSession[]; + + const sessions: LapSessionWithLaps[] = rows.map((session) => { + const laps = db + .prepare( + "SELECT * FROM laps WHERE sessionId = ? ORDER BY lapNumber ASC" + ) + .all(session.id) as Lap[]; + return { ...session, laps }; + }); + + return { sessions, total: countRow.total }; +} + +export function getLapSessionById(id: number): LapSessionWithLaps | null { + const db = getDb(); + const session = db + .prepare("SELECT * FROM lap_sessions WHERE id = ?") + .get(id) as LapSession | undefined; + if (!session) return null; + + const laps = db + .prepare("SELECT * FROM laps WHERE sessionId = ? ORDER BY lapNumber ASC") + .all(id) as Lap[]; + + return { ...session, laps }; +} + +export async function deleteLapSession(id: number): Promise { + const db = getDb(); + const laps = db + .prepare("SELECT startImagePath, endImagePath FROM laps WHERE sessionId = ?") + .all(id) as Pick[]; + + db.prepare("DELETE FROM lap_sessions WHERE id = ?").run(id); + + const { deleteImage } = await import("./filestore"); + for (const lap of laps) { + if (lap.startImagePath) await deleteImage(lap.startImagePath); + if (lap.endImagePath) await deleteImage(lap.endImagePath); + } +} + +// ─── Lap queries ────────────────────────────────────────────────────────────── + +export async function insertLap( + input: SaveLapInput & { startImagePath: string | null; endImagePath: string | null } +): Promise { + const db = getDb(); + const result = db + .prepare( + `INSERT INTO laps + (sessionId, lapNumber, startTimestamp, endTimestamp, durationMs, + speedAtStart, speedAtEnd, startImagePath, endImagePath) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)` + ) + .run( + input.sessionId, + input.lapNumber, + input.startTimestamp, + input.endTimestamp, + input.durationMs, + input.speedAtStart, + input.speedAtEnd, + input.startImagePath, + input.endImagePath + ); + return { + id: result.lastInsertRowid as number, + sessionId: input.sessionId, + lapNumber: input.lapNumber, + startTimestamp: input.startTimestamp, + endTimestamp: input.endTimestamp, + durationMs: input.durationMs, + speedAtStart: input.speedAtStart, + speedAtEnd: input.speedAtEnd, + startImagePath: input.startImagePath, + endImagePath: input.endImagePath, + }; +} + +export async function deleteLap(id: number): Promise { + const db = getDb(); + const lap = db.prepare("SELECT startImagePath, endImagePath FROM laps WHERE id = ?").get( + id + ) as Pick | undefined; + + db.prepare("DELETE FROM laps WHERE id = ?").run(id); + + if (lap) { + const { deleteImage } = await import("./filestore"); + if (lap.startImagePath) await deleteImage(lap.startImagePath); + if (lap.endImagePath) await deleteImage(lap.endImagePath); + } +} diff --git a/headless/src/server/env.ts b/headless/src/server/env.ts new file mode 100644 index 0000000..886ffb9 --- /dev/null +++ b/headless/src/server/env.ts @@ -0,0 +1,28 @@ +import { join, dirname } from "path"; +import { existsSync } from "fs"; + +function resolveAravisPath(): string | undefined { + const binDir = dirname(process.execPath || process.argv[0] || ""); + const candidates = [ + // Standard system paths + "/usr/lib/aarch64-linux-gnu/libaravis-0.8.so", + "/usr/lib/x86_64-linux-gnu/libaravis-0.8.so", + "/usr/local/lib/libaravis-0.8.so", + "/usr/lib/libaravis-0.8.so", + // Development / project layout + join(import.meta.dir, "..", "..", "vendor", "libaravis-0.8.so"), + join(import.meta.dir, "..", "vendor", "libaravis-0.8.so"), + join(process.cwd(), "vendor", "libaravis-0.8.so"), + join(process.cwd(), "resources", "libaravis-0.8.so"), + join(binDir, "libaravis-0.8.so"), + ]; + return candidates.find((p) => existsSync(p)); +} + +const libPath = resolveAravisPath(); +if (libPath) { + console.log(`[entry] Setting BUN_ARAVIS_LIB_PATH to ${libPath}`); + process.env.BUN_ARAVIS_LIB_PATH = libPath; +} else { + console.log(`[entry] libaravis-0.8.so not found in bundled paths, falling back to system dynamic linker`); +} diff --git a/headless/src/server/filestore.ts b/headless/src/server/filestore.ts new file mode 100644 index 0000000..ed926b8 --- /dev/null +++ b/headless/src/server/filestore.ts @@ -0,0 +1,60 @@ +import path from "path"; +import { getUserDataDir } from "./database"; + +function getImageDir(): string { + return path.join(getUserDataDir(), "images"); +} + +async function ensureImageDir(): Promise { + await Bun.write(path.join(getImageDir(), ".keep"), ""); +} + +/** + * Save an image from a raw base64 string (no data-URL prefix). + * Returns the absolute path of the saved file. + */ +export async function saveImage(base64: string): Promise { + await ensureImageDir(); + + const timestamp = new Date().toISOString().replace(/[:.]/g, "-"); + const filename = `speed-violation-${timestamp}.png`; + const filePath = path.join(getImageDir(), filename); + + const buffer = Buffer.from(base64, "base64"); + await Bun.write(filePath, buffer); + + return filePath; +} + +/** + * Read an image from disk and return it as a data-URL. + * Returns null if the file does not exist. + */ +export async function readImageAsDataUrl(imagePath: string): Promise { + const file = Bun.file(imagePath); + const exists = await file.exists(); + if (!exists) return null; + + const buffer = await file.arrayBuffer(); + const base64 = Buffer.from(buffer).toString("base64"); + const ext = path.extname(imagePath).toLowerCase(); + const mime = ext === ".png" ? "image/png" : "image/jpeg"; + + return `data:${mime};base64,${base64}`; +} + +/** + * Delete an image file from disk. Silently ignores missing files. + */ +export async function deleteImage(imagePath: string): Promise { + try { + const file = Bun.file(imagePath); + const exists = await file.exists(); + if (exists) { + const { unlink } = await import("fs/promises"); + await unlink(imagePath); + } + } catch (err) { + console.error(`[filestore] Failed to delete image ${imagePath}:`, err); + } +} diff --git a/headless/src/server/flasher.ts b/headless/src/server/flasher.ts new file mode 100644 index 0000000..c4e2f13 --- /dev/null +++ b/headless/src/server/flasher.ts @@ -0,0 +1,210 @@ +import { join, dirname } from "path"; +import { tmpdir } from "os"; +import { existsSync } from "fs"; +import type { GithubRelease, FlashProgressPayload } from "../shared/types"; + +// ─── Constants ──────────────────────────────────────────────────────────────── + +const GITHUB_API_URL = "https://api.github.com/repos/LeoLTM/speedcamera/releases"; +const GITHUB_USER_URL = "https://api.github.com/user"; + +// Only allow well-formed version tags from our own repo +const TAG_PATTERN = /^v\d+\.\d+\.\d+(-canary)?$/; + +// ─── esptool binary path resolution ────────────────────────────────────────── + +function resolveEsptoolPath(): string { + const binDir = dirname(process.execPath || process.argv[0] || ""); + const candidates = [ + join(process.cwd(), "resources", "esptool"), + join(import.meta.dir, "..", "..", "resources", "esptool"), + join(import.meta.dir, "..", "resources", "esptool"), + join(binDir, "esptool"), + "/usr/bin/esptool", + "/usr/local/bin/esptool", + "/usr/bin/esptool.py", + ]; + return candidates.find((p) => existsSync(p)) ?? "esptool"; +} + +const ESPTOOL_PATH = resolveEsptoolPath(); + +// ─── Helpers ────────────────────────────────────────────────────────────────── + +function githubHeaders(token: string, accept = "application/vnd.github+json"): HeadersInit { + const h: HeadersInit = { Accept: accept, "User-Agent": "speedcamera-app" }; + if (token) h["Authorization"] = `Bearer ${token}`; + return h; +} + +// ─── Push callback ──────────────────────────────────────────────────────────── + +type PushFn = (payload: FlashProgressPayload) => void; +let _push: PushFn | null = null; + +export function initFlasher(push: PushFn): void { + _push = push; +} + +function push(payload: FlashProgressPayload): void { + _push?.(payload); +} + +// ─── Active process handle ──────────────────────────────────────────────────── + +let _activeProc: ReturnType | null = null; + +// ─── Public API ─────────────────────────────────────────────────────────────── + +export async function testGithubToken( + token: string, +): Promise<{ valid: boolean; login?: string; error?: string }> { + if (!token.trim()) { + return { valid: false, error: "Token is empty" }; + } + + let resp: Response; + try { + resp = await fetch(`${GITHUB_API_URL}?per_page=1`, { + headers: githubHeaders(token), + }); + } catch (e) { + return { valid: false, error: `Network error: ${e instanceof Error ? e.message : String(e)}` }; + } + + if (resp.status === 401) return { valid: false, error: "Invalid token — authentication failed" }; + if (resp.status === 403) return { valid: false, error: "Forbidden — check token scopes (needs repo read)" }; + if (resp.status === 404) return { valid: false, error: "Repository not found — check token permissions" }; + if (!resp.ok) return { valid: false, error: `GitHub API error: ${resp.status} ${resp.statusText}` }; + + let login: string | undefined; + try { + const userResp = await fetch(GITHUB_USER_URL, { headers: githubHeaders(token) }); + if (userResp.ok) { + login = ((await userResp.json()) as { login: string }).login; + } + } catch { + // Non-critical — token is still valid + } + + return { valid: true, login }; +} + +export async function listFirmwareReleases(token: string): Promise { + const resp = await fetch(GITHUB_API_URL, { headers: githubHeaders(token) }); + if (resp.status === 401 || resp.status === 403) { + throw new Error("GitHub authentication failed — check your token in the Firmware Update settings"); + } + if (!resp.ok) { + throw new Error(`GitHub API error: ${resp.status} ${resp.statusText}`); + } + + const data = (await resp.json()) as Array<{ + tag_name: string; + name: string; + published_at: string; + prerelease: boolean; + assets: Array<{ name: string; url: string }>; + }>; + + return data.map((r) => { + const firmwareAsset = r.assets.find((a) => a.name === "firmware.bin"); + return { + tag: r.tag_name, + name: r.name, + publishedAt: r.published_at, + prerelease: r.prerelease, + firmwareAssetApiUrl: firmwareAsset?.url ?? "", + }; + }); +} + +export async function flashFirmware( + releaseTag: string, + port: string, + firmwareAssetApiUrl: string, + token: string, +): Promise { + if (!TAG_PATTERN.test(releaseTag)) { + throw new Error(`Invalid release tag: "${releaseTag}"`); + } + + const ALLOWED_PREFIX = "https://api.github.com/repos/LeoLTM/speedcamera/releases/assets/"; + if (!firmwareAssetApiUrl.startsWith(ALLOWED_PREFIX)) { + throw new Error("Invalid firmware asset URL"); + } + + const tmpPath = join(tmpdir(), `speedcamera-firmware-${releaseTag}.bin`); + + push({ type: "downloading" }); + const dlResp = await fetch(firmwareAssetApiUrl, { + headers: githubHeaders(token, "application/octet-stream"), + redirect: "follow", + }); + if (!dlResp.ok) { + throw new Error(`Failed to download firmware: ${dlResp.status} ${dlResp.statusText}`); + } + await Bun.write(tmpPath, dlResp); + + const proc = Bun.spawn( + [ + ESPTOOL_PATH, + "--port", port, + "--baud", "460800", + "--chip", "esp8266", + "write_flash", + "--flash_mode", "dout", + "--flash_freq", "40m", + "--flash_size", "detect", + "0x0", + tmpPath, + ], + { stdout: "pipe", stderr: "pipe" }, + ); + _activeProc = proc; + + const decoder = new TextDecoder(); + let lineBuffer = ""; + + function flushLines(chunk: string): void { + lineBuffer += chunk; + const parts = lineBuffer.split("\n"); + lineBuffer = parts.pop() ?? ""; + for (const line of parts) { + const trimmed = line.replace(/\r$/, "").trim(); + if (trimmed) push({ type: "output", line: trimmed }); + } + } + + async function drainStream(stream: ReadableStream): Promise { + const reader = stream.getReader(); + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + flushLines(decoder.decode(value, { stream: true })); + } + } finally { + reader.releaseLock(); + flushLines(decoder.decode()); + } + } + + await Promise.all([drainStream(proc.stdout), drainStream(proc.stderr)]); + + const exitCode = await proc.exited; + _activeProc = null; + + if (exitCode !== 0) { + throw new Error(`esptool exited with code ${exitCode}`); + } + + push({ type: "done" }); +} + +export function cancelFlash(): void { + if (_activeProc) { + _activeProc.kill(); + _activeProc = null; + } +} diff --git a/headless/src/server/index.ts b/headless/src/server/index.ts new file mode 100644 index 0000000..964ef2a --- /dev/null +++ b/headless/src/server/index.ts @@ -0,0 +1,442 @@ +import "./env"; +import path from "path"; +import { RpcServer, type RequestHandlers } from "./rpc"; +import { + insertViolation, + queryViolations, + getViolationById, + removeViolation, + exportCsv, + getSettings, + saveSetting, + createLapSession, + closeLapSession, + insertLap, + getLapSessions, + getLapSessionById, + deleteLapSession, + deleteLap, + getUserDataDir, +} from "./database"; +import { saveImage, deleteImage } from "./filestore"; +import { renderPoliscanSkin } from "./skin-renderer"; +import { + initCamera, + disconnectCamera, + getCameraStatus, + captureFrame, + setExposure, + setGain, + initCameraPush, + applyMfsConfig, + startSetupStream, + stopSetupStream, + setPixelFormat, + getPixelFormat, + setStrobeDuration, + setCameraFeatureStr, + setCameraFeatureInt, +} from "./industrial-camera"; +import { initFlasher, listFirmwareReleases, flashFirmware, cancelFlash, testGithubToken } from "./flasher"; +import { + testTeableConnection, + saveTeableConfig, + removeTeableConfig, + listTeableSpaces, + listTeableBases, + listTeableTables, + verifyTeableTable, + ensureTeableFields, + createTeableTable, + saveTeableTarget, + syncLapToTeable, +} from "./teable"; +import { getSystemNetworkSummary, logNetworkStatus } from "./network"; + +// ─── Serial module (real or mock) ──────────────────────────────────────────── +const isMock = !!process.env.MOCK_MODE; +const { initSerial, listPorts, openPort, closePort, sendCommand } = await ( + isMock ? import("./mock/serial") : import("./serial") +); + +// ─── RPC Request Handlers ──────────────────────────────────────────────────── +const handlers: RequestHandlers = { + // ── Violations ────────────────────────────────────────────────────────── + getViolations: (q) => queryViolations(q), + + getViolationById: ({ id }) => getViolationById(id), + + deleteViolation: async ({ id }) => { + const v = getViolationById(id); + if (v) { + removeViolation(id); + await deleteImage(v.imagePath); + } + }, + + exportViolationsCsv: ({ dateFrom, dateTo, minSpeed }) => + exportCsv({ dateFrom, dateTo, minSpeed }), + + saveViolation: async ({ measuredSpeed, maxSpeed, direction }) => { + let raw = await captureFrame(); + if (!raw && isMock) { + // In mock mode, generate a simple 1x1 base64 png if camera is not active + raw = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="; + } + if (!raw) throw new Error("Failed to capture frame from industrial camera"); + const imagePath = await saveImage(raw); + const v = insertViolation({ imageBase64: raw, imagePath, measuredSpeed, maxSpeed, direction }); + return v; + }, + + // ── Lap Sessions ──────────────────────────────────────────────────────── + createLapSession: ({ lapMode }) => createLapSession(lapMode), + + closeLapSession: ({ id }) => { + closeLapSession(id); + }, + + saveLap: async ({ + sessionId, lapNumber, startTimestamp, endTimestamp, durationMs, + speedAtStart, speedAtEnd, startImageBase64, endImageBase64, + }) => { + const startRaw = startImageBase64 + ? startImageBase64.replace(/^data:image\/\w+;base64,/, "") + : null; + const endRaw = endImageBase64 + ? endImageBase64.replace(/^data:image\/\w+;base64,/, "") + : null; + const startImagePath = startRaw ? await saveImage(startRaw) : null; + const endImagePath = endRaw ? await saveImage(endRaw) : null; + return insertLap({ + sessionId, lapNumber, startTimestamp, endTimestamp, durationMs, + speedAtStart, speedAtEnd, + startImageBase64: null, + endImageBase64: null, + startImagePath, + endImagePath, + }); + }, + + getLapSessions: ({ page, limit }) => getLapSessions(page, limit), + + getLapSessionById: ({ id }) => getLapSessionById(id), + + deleteLapSession: ({ id }) => deleteLapSession(id), + + deleteLap: ({ id }) => deleteLap(id), + + // ── Images ────────────────────────────────────────────────────────────── + getImageData: async ({ imagePath }) => { + if (!imagePath) return ""; + return `/image?path=${encodeURIComponent(imagePath)}`; + }, + + getSkinnedImageData: async ({ violationId }) => { + return `/skinned-image?violationId=${violationId}`; + }, + + exportSkinnedImages: async ({ violationIds, targetDir }) => { + const settings = getSettings(); + let exported = 0; + let failed = 0; + for (const id of violationIds) { + try { + const v = getViolationById(id); + if (!v) { failed++; continue; } + const buf = await renderPoliscanSkin(v.imagePath, v, { + measuringLocation: settings.skinMeasuringLocation, + }); + const ts = new Date(v.timestamp).toISOString().replace(/[:.]/g, "-"); + const outPath = path.join(targetDir, `violation-${v.id}-${ts}.png`); + await Bun.write(outPath, buf); + exported++; + } catch (err) { + console.error(`[skin-export] Failed to export violation ${id}:`, err); + failed++; + } + } + return { exported, failed }; + }, + + // ── Settings ──────────────────────────────────────────────────────────── + getSettings: () => getSettings(), + + saveSetting: ({ key, value }) => { + saveSetting(key, value); + }, + + // ── Serial ────────────────────────────────────────────────────────────── + listPorts: () => listPorts(), + + openPort: ({ path: portPath }) => openPort(portPath), + + closePort: () => closePort(), + + sendCommand: ({ json }) => { + sendCommand(json); + }, + + // ── Camera HW ─────────────────────────────────────────────────────────── + connectCamera: () => { + initCamera(); + }, + + disconnectCamera: () => { + disconnectCamera(); + }, + + getCameraStatus: () => getCameraStatus(), + + captureFrame: async () => { + const b64 = await captureFrame(); + return b64 ?? null; + }, + + setCameraExposure: ({ value }) => { + setExposure(value); + }, + + setCameraGain: ({ value }) => { + setGain(value); + }, + + applyMfsConfig: ({ mfsContent, saveAsDefault }) => { + return applyMfsConfig(mfsContent, saveAsDefault); + }, + + startSetupStream: () => { + startSetupStream((base64) => { + rpcServer.broadcast("liveFrame", base64); + }); + }, + + stopSetupStream: () => { + stopSetupStream(); + }, + + setCameraPixelFormat: ({ format }) => { + setPixelFormat(format); + }, + + getCameraPixelFormat: () => getPixelFormat(), + + setCameraStrobeDuration: ({ value }) => { + setStrobeDuration(value); + }, + + setCameraFeatureStr: ({ feature, value }) => { + setCameraFeatureStr(feature, value); + }, + + setCameraFeatureInt: ({ feature, value }) => { + setCameraFeatureInt(feature, value); + }, + + // ── Window (Headless Stubs) ───────────────────────────────────────────── + minimizeWindow: () => {}, + maximizeWindow: () => {}, + closeWindow: () => {}, + + // ── System & Network ─────────────────────────────────────────────────── + getPlatform: () => process.platform, + getNetworkInfo: () => getSystemNetworkSummary(), + + // ── Teable ─────────────────────────────────────────────────────────────── + testTeableConnection: ({ url, token }) => testTeableConnection(url, token), + + saveTeableConfig: ({ url, token, userName, userEmail, userAvatar }) => { + saveTeableConfig(url, token, userName, userEmail, userAvatar); + }, + + removeTeableConfig: () => { + removeTeableConfig(); + }, + + listTeableSpaces: () => listTeableSpaces(), + + listTeableBases: ({ spaceId }) => listTeableBases(spaceId), + + listTeableTables: ({ baseId }) => listTeableTables(baseId), + + verifyTeableTable: ({ tableId }) => verifyTeableTable(tableId), + + ensureTeableFields: ({ tableId }) => ensureTeableFields(tableId), + + createTeableTable: ({ baseId, tableName }) => createTeableTable(baseId, tableName), + + saveTeableTarget: ({ spaceId, baseId, tableId }) => { + saveTeableTarget(spaceId, baseId, tableId); + }, + + syncLapToTeable: ({ lap, session }) => syncLapToTeable(lap, session), + + // ── Updater (Headless Service Stubs) ──────────────────────────────────── + getLocalVersion: async () => { + return { version: "0.4.0-headless", channel: "headless", hash: "rpi-build" }; + }, + + checkForUpdate: async () => { + return { + version: "0.4.0-headless", + hash: "rpi-build", + updateAvailable: false, + updateReady: false, + error: "Updater is managed by system package manager or git on headless Pi", + }; + }, + + downloadUpdate: async () => { + return { ok: false, error: "Not supported in headless mode" }; + }, + + applyUpdate: async () => {}, + + // ── Firmware Flasher ──────────────────────────────────────────────────── + listFirmwareReleases: async () => { + const { githubToken } = getSettings(); + return listFirmwareReleases(githubToken); + }, + + flashFirmware: async ({ releaseTag, port, firmwareAssetApiUrl }) => { + const { githubToken } = getSettings(); + try { closePort(); } catch { /* ignore */ } + await flashFirmware(releaseTag, port, firmwareAssetApiUrl, githubToken); + }, + + cancelFlash: () => cancelFlash(), + + testGithubToken: ({ token }) => testGithubToken(token), +}; + +const rpcServer = new RpcServer(handlers); + +// ─── Push Bridges ───────────────────────────────────────────────────────────── +initSerial((payload) => { + rpcServer.broadcast("serialStatus", payload); +}); + +initCameraPush((payload) => { + rpcServer.broadcast("cameraStatus", payload); +}); + +initFlasher((payload) => { + rpcServer.broadcast("flashProgress", payload); +}); + +// Auto-connect hardware on startup if configured +initCamera(); + +// ─── HTTP & WebSocket Server ────────────────────────────────────────────────── +const PORT = parseInt(process.env.PORT || "3000", 10); +const HOST = process.env.HOST || "0.0.0.0"; +const DIST_DIR = path.resolve(import.meta.dir, "../../dist"); + +const server = Bun.serve({ + port: PORT, + hostname: HOST, + websocket: { + open(ws) { + rpcServer.registerSocket(ws); + console.log("[ws] Client connected"); + // Push current statuses immediately + ws.send(JSON.stringify({ event: "cameraStatus", payload: getCameraStatus() })); + }, + message(ws, message) { + rpcServer.handleMessage(ws, message); + }, + close(ws) { + rpcServer.unregisterSocket(ws); + console.log("[ws] Client disconnected"); + }, + }, + async fetch(req, server) { + const url = new URL(req.url); + + // WebSocket upgrade + if (url.pathname === "/ws/rpc" || url.pathname === "/ws") { + const upgraded = server.upgrade(req); + if (upgraded) return undefined; + return new Response("WebSocket upgrade failed", { status: 400 }); + } + + // Health check endpoint + if (url.pathname === "/api/health") { + return Response.json({ + status: "ok", + uptime: process.uptime(), + platform: process.platform, + camera: getCameraStatus(), + network: getSystemNetworkSummary(), + mockMode: isMock, + }); + } + + // Network status endpoint + if (url.pathname === "/api/network") { + return Response.json(getSystemNetworkSummary()); + } + + // Image serving endpoint + if (url.pathname === "/image") { + const imgPath = url.searchParams.get("path"); + if (!imgPath) return new Response("Missing path parameter", { status: 400 }); + const resolvedPath = path.resolve(imgPath); + const allowedDir = path.resolve(getUserDataDir()); + if (!resolvedPath.startsWith(allowedDir)) { + return new Response("Forbidden", { status: 403 }); + } + const file = Bun.file(resolvedPath); + if (!(await file.exists())) { + return new Response("Not Found", { status: 404 }); + } + return new Response(file); + } + + // Skinned image rendering endpoint + if (url.pathname === "/skinned-image") { + const idStr = url.searchParams.get("violationId"); + if (!idStr) return new Response("Missing violationId parameter", { status: 400 }); + const violationId = parseInt(idStr, 10); + const v = getViolationById(violationId); + if (!v) return new Response("Violation not found", { status: 404 }); + try { + const settings = getSettings(); + const buf = await renderPoliscanSkin(v.imagePath, v, { + measuringLocation: settings.skinMeasuringLocation, + }); + return new Response(new Uint8Array(buf), { + headers: { "Content-Type": "image/png" }, + }); + } catch (err) { + console.error("[skinned-image] Rendering failed:", err); + return new Response("Rendering failed", { status: 500 }); + } + } + + // Static files from built frontend (dist/) + let filePath = path.join(DIST_DIR, url.pathname); + let file = Bun.file(filePath); + + if (await file.exists()) { + return new Response(file); + } + + // SPA fallback: return index.html for client-side routing + const indexFile = Bun.file(path.join(DIST_DIR, "index.html")); + if (await indexFile.exists()) { + return new Response(indexFile, { + headers: { "Content-Type": "text/html; charset=utf-8" }, + }); + } + + return new Response( + "Speedcamera Headless Server running. Build the frontend (`bun run build`) or run `bun run dev` for development.", + { status: 200, headers: { "Content-Type": "text/plain" } } + ); + }, +}); + +console.log(`[speedcamera-headless] Server listening on http://${HOST}:${PORT} (Mock mode: ${isMock})`); +console.log(`[speedcamera-headless] Data directory: ${getUserDataDir()}`); +logNetworkStatus(); diff --git a/headless/src/server/industrial-camera.ts b/headless/src/server/industrial-camera.ts new file mode 100644 index 0000000..143c8ac --- /dev/null +++ b/headless/src/server/industrial-camera.ts @@ -0,0 +1,411 @@ +import { Camera, Stream, updateDeviceList, getDevices } from "@asl-gokart/bun-aravis"; +import sharp from "sharp"; +import { getSettings } from "./database"; + +let camera: Camera | null = null; +let stream: Stream | null = null; +let isConnected = false; + +type PushCameraStatus = (payload: { connected: boolean; vendor: string | null; model: string | null; serial: string | null }) => void; +let pushCameraStatus: PushCameraStatus | null = null; + +export function initCameraPush(pushFn: PushCameraStatus) { + pushCameraStatus = pushFn; +} + +function notifyStatus() { + if (pushCameraStatus) { + pushCameraStatus({ + connected: isConnected, + vendor: camera ? camera.vendor : null, + model: camera ? camera.model : null, + serial: camera ? camera.serialNumber : null, + }); + } +} + +export function initCamera() { + if (isConnected) return; + try { + updateDeviceList(); + const devices = getDevices(); + const hikDevice = devices.find((d) => d.vendor.toLowerCase().includes("hikrobot")); + + if (!hikDevice && devices.length === 0) { + console.warn("[industrial-camera] No cameras found"); + return; + } + + camera = Camera.open(hikDevice ? hikDevice.id : undefined); + + try { + camera.autoPacketSize(); + } catch { + console.warn("[industrial-camera] autoPacketSize not supported/needed"); + } + + const settings = getSettings(); + const exposure = Number(settings.cameraExposure) || 5000; + const gain = Number(settings.cameraGain) || 0; + const strobeDuration = Number(settings.strobeLineDuration) || 5000; + + const exposureAuto = settings.exposureAuto || "Off"; + const gainAuto = settings.gainAuto || "Off"; + + if (camera.isFeatureAvailable("PixelFormat")) { + setPixelFormat(settings.pixelFormat); + } + + if (camera.isFeatureAvailable("AcquisitionMode")) { + camera.setStringFeature("AcquisitionMode", "Continuous"); + } + if (camera.isFeatureAvailable("TriggerMode")) { + camera.setStringFeature("TriggerMode", "On"); + camera.setStringFeature("TriggerSource", "Software"); + } + + if (camera.isFeatureAvailable("LineSelector")) { + try { + camera.setStringFeature("LineSelector", "Line1"); + } catch { + /* ignore */ + } + + try { + camera.setStringFeature("LineMode", "Strobe"); + } catch { + /* ignore */ + } + + try { + camera.setStringFeature("LineSource", "ExposureActive"); + } catch { + /* ignore */ + } + + try { + if (camera.isFeatureAvailable("StrobeEnable")) { + try { camera.setBooleanFeature("StrobeEnable", true); } + catch { camera.setIntegerFeature("StrobeEnable", 1); } + + camera.setIntegerFeature("StrobeLineDuration", strobeDuration); + camera.setIntegerFeature("StrobeLineDelay", 0); + camera.setIntegerFeature("StrobeLinePreDelay", 0); + } + } catch { + console.warn("[industrial-camera] Standard Strobe features missing, relying on LineSource = ExposureActive"); + } + } + + try { + camera.setStringFeature("ExposureAuto", exposureAuto); + if (exposureAuto === "Off") { + camera.setExposureTime(exposure); + } + } catch { + /* ignore */ + } + + try { + camera.setStringFeature("GainAuto", gainAuto); + if (gainAuto === "Off") { + camera.setGain(gain); + } + } catch { + /* ignore */ + } + + if (settings.frameRate) { + try { + camera.setBooleanFeature("AcquisitionFrameRateEnable", true); + camera.setFrameRate(Number(settings.frameRate)); + } catch { + /* ignore */ + } + } + if (settings.cameraWidth) { + try { camera.setIntegerFeature("Width", Number(settings.cameraWidth)); } catch { /* ignore */ } + } + if (settings.cameraHeight) { + try { camera.setIntegerFeature("Height", Number(settings.cameraHeight)); } catch { /* ignore */ } + } + if (settings.blackLevel !== undefined && settings.blackLevel !== null && settings.blackLevel.toString() !== "") { + try { camera.setIntegerFeature("BlackLevel", Number(settings.blackLevel)); } catch { /* ignore */ } + } + + stream = camera.createStream(5); + stream.startAcquisition(); + + isConnected = true; + console.log(`[industrial-camera] Connected: ${camera.vendor} ${camera.model} (${camera.serialNumber})`); + notifyStatus(); + + } catch (e) { + console.error("[industrial-camera] Init failed:", e); + disconnectCamera(); + } +} + +export function disconnectCamera() { + if (stream) { + try { stream.stopAcquisition(); } catch { /* ignore */ } + try { stream.dispose(); } catch { /* ignore */ } + stream = null; + } + if (camera) { + try { camera.dispose(); } catch { /* ignore */ } + camera = null; + } + isConnected = false; + notifyStatus(); +} + +export function getCameraStatus() { + return { + connected: isConnected, + vendor: camera ? camera.vendor : null, + model: camera ? camera.model : null, + serial: camera ? camera.serialNumber : null, + }; +} + +export function setExposure(value: number) { + if (!camera || !isConnected) return; + try { + camera.setExposureTime(value); + } catch (e) { + console.error("[industrial-camera] setExposure failed", e); + } +} + +export function setGain(value: number) { + if (!camera || !isConnected) return; + try { + camera.setGain(value); + } catch (e) { + console.error("[industrial-camera] setGain failed", e); + } +} + +export async function captureFrame(): Promise { + if (!camera || !stream || !isConnected) { + console.warn("[industrial-camera] captureFrame: not connected"); + return null; + } + + try { + let staleBuffer; + while ((staleBuffer = stream.tryPopBuffer()) !== null) { + console.warn("[industrial-camera] Discarding stale frame before new capture"); + stream.pushBuffer(staleBuffer); + } + + if (camera.isFeatureAvailable("TriggerSoftware")) { + camera.executeCommand("TriggerSoftware"); + } + + const buffer = stream.timeoutPopBuffer(2_000_000); + if (!buffer || !buffer.isSuccess) { + if (buffer) stream.pushBuffer(buffer); + console.error("[industrial-camera] Capture timeout or error"); + return null; + } + + const w = buffer.width; + const h = buffer.height; + const fmt = buffer.pixelFormatName; + const data = buffer.copyData(); + + stream.pushBuffer(buffer); + + let sharpInst; + if (fmt === "RGB8" || fmt === "RGB8Packed") { + sharpInst = sharp(data, { raw: { width: w, height: h, channels: 3 } }); + } else if (fmt === "Mono8") { + sharpInst = sharp(data, { raw: { width: w, height: h, channels: 1 } }); + } else { + sharpInst = sharp(data, { raw: { width: w, height: h, channels: 1 } }); + } + + const pngBuffer = await sharpInst.png().toBuffer(); + return pngBuffer.toString("base64"); + + } catch (e) { + console.error("[industrial-camera] Capture frame failed:", e); + return null; + } +} + +export function applyMfsConfig(mfsContent: string, saveAsDefault: boolean): { applied: string[], failed: string[] } { + if (!camera || !isConnected) return { applied: [], failed: [] }; + const result = camera.applyMfsConfig(mfsContent); + if (saveAsDefault) { + try { + camera.saveUserSet("UserSet1", true); + } catch (e) { + console.warn("Failed to save UserSet", e); + } + } + return result; +} + +let setupStreamLoopActive = false; + +export async function startSetupStream(pushFrame: (base64: string) => void) { + if (!camera || !stream || !isConnected) return; + setupStreamLoopActive = true; + + try { stream.stopAcquisition(); } catch { /* ignore */ } + + try { camera.setIntegerFeature("StrobeEnable", 0); } catch { /* ignore */ } + try { camera.setStringFeature("TriggerMode", "Off"); } catch { /* ignore */ } + try { camera.setStringFeature("GainAuto", "Continuous"); } catch { /* ignore */ } + try { camera.setStringFeature("ExposureAuto", "Continuous"); } catch { /* ignore */ } + + try { camera.setBooleanFeature("StrobeEnable", false); } catch { + try { camera.setIntegerFeature("StrobeEnable", 0); } catch { /* ignore */ } + } + + if (camera.isFeatureAvailable("LineSelector")) { + for (const line of ["Line1", "Line2"]) { + try { + camera.setStringFeature("LineSelector", line); + camera.setStringFeature("LineSource", "Off"); + } catch { /* ignore */ } + } + } + + try { stream.startAcquisition(); } catch { /* ignore */ } + + pumpSetupFrames(pushFrame); +} + +async function pumpSetupFrames(pushFrame: (base64: string) => void) { + 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)); + continue; + } + + const w = buffer.width; + const h = buffer.height; + const fmt = buffer.pixelFormatName; + const data = buffer.copyData(); + stream.pushBuffer(buffer); + + let sharpInst; + if (fmt === "RGB8" || fmt === "RGB8Packed") { + sharpInst = sharp(data, { raw: { width: w, height: h, channels: 3 } }); + } else { + sharpInst = sharp(data, { raw: { width: w, height: h, channels: 1 } }); + } + + const jpegBuffer = await sharpInst.jpeg({ quality: 80 }).toBuffer(); + pushFrame(jpegBuffer.toString("base64")); + } catch (e) { + console.error("Setup stream pump error", e); + await new Promise(r => setTimeout(r, 100)); + } + } +} + +export function stopSetupStream() { + setupStreamLoopActive = false; + if (!camera || !stream || !isConnected) return; + + try { stream.stopAcquisition(); } catch { /* ignore */ } + + 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 */ } + try { camera.setStringFeature("ExposureAuto", exposureAuto); } catch { /* ignore */ } + + try { camera.setBooleanFeature("StrobeEnable", true); } catch { + try { camera.setIntegerFeature("StrobeEnable", 1); } catch { /* ignore */ } + } + + if (camera.isFeatureAvailable("LineSelector")) { + try { camera.setStringFeature("LineSelector", "Line1"); } catch { /* ignore */ } + try { camera.setStringFeature("LineSource", "ExposureActive"); } catch { /* ignore */ } + } + + if (gainAuto === "Off") { + try { camera.setGain(Number(settings.cameraGain) || 0); } catch { /* ignore */ } + } + if (exposureAuto === "Off") { + try { camera.setExposureTime(Number(settings.cameraExposure) || 5000); } catch { /* ignore */ } + } + + try { stream.startAcquisition(); } catch { /* ignore */ } +} + +export function setPixelFormat(format: string) { + if (!camera || !isConnected) return; + + const wasAcquiring = !!stream; + if (wasAcquiring) { + try { stream!.stopAcquisition(); } catch { /* ignore */ } + } + + if (format === "Color") { + const fallbacks = ["BayerBG8", "BayerRG8", "BayerGR8", "BayerGB8", "RGB8Packed", "RGB8"]; + let success = false; + for (const fmt of fallbacks) { + try { + camera.setStringFeature("PixelFormat", fmt); + console.log(`[industrial-camera] Set PixelFormat to ${fmt}`); + success = true; + break; + } catch { /* ignore */ } + } + if (!success) { + console.error("[industrial-camera] Failed to set PixelFormat for Color. No formats accepted."); + } + } else { + try { + camera.setStringFeature("PixelFormat", "Mono8"); + console.log(`[industrial-camera] Set PixelFormat to Mono8`); + } catch (e) { + console.error("[industrial-camera] Failed to set PixelFormat to Mono8", e); + } + } + + if (wasAcquiring) { + try { stream!.startAcquisition(); } catch { /* ignore */ } + } +} + +export function getPixelFormat(): string { + if (!camera || !isConnected) return "Mono"; + try { + const fmt = camera.getStringFeature("PixelFormat"); + return (fmt.startsWith("Bayer") || fmt.startsWith("RGB")) ? "Color" : "Mono"; + } catch { + return "Mono"; + } +} + +export function setStrobeDuration(value: number) { + if (!camera || !isConnected) return; + try { + camera.setIntegerFeature("StrobeLineDuration", value); + } catch (e) { + console.error("Failed to set StrobeLineDuration", e); + } +} + +export function setCameraFeatureStr(feature: string, value: string) { + if (!camera || !isConnected) return; + try { camera.setStringFeature(feature, value); } catch (e) { console.error(`Failed to set ${feature}`, e); } +} + +export function setCameraFeatureInt(feature: string, value: number) { + if (!camera || !isConnected) return; + try { camera.setIntegerFeature(feature, value); } catch (e) { console.error(`Failed to set ${feature}`, e); } +} diff --git a/headless/src/server/mock/serial.ts b/headless/src/server/mock/serial.ts new file mode 100644 index 0000000..5197403 --- /dev/null +++ b/headless/src/server/mock/serial.ts @@ -0,0 +1,96 @@ +import type { PortInfo, SerialStatusPayload } from "../../shared/types"; + +// ─── State ──────────────────────────────────────────────────────────────────── + +let pushToView: ((payload: SerialStatusPayload) => void) | null = null; +let connected = false; +let autoFireTimer: ReturnType | null = null; + +const MOCK_PORT_PATH = "/dev/mock-speedcamera"; + +// ─── Serial API (mirrors src/server/serial.ts) ──────────────────────────────── + +let onSpeeding: ((msg: unknown) => void) | null = null; + +export function initSerial( + push: (payload: SerialStatusPayload) => void, + onSpeedingCapture?: (msg: unknown) => void +): void { + pushToView = push; + onSpeeding = onSpeedingCapture || null; + console.log("[mock/serial] Initialized"); +} + +export async function listPorts(): Promise { + return [{ path: MOCK_PORT_PATH, manufacturer: "Speedcamera Mock" }]; +} + +export async function openPort(_portPath: string): Promise { + if (connected) return; + console.debug(`[mock/serial] openPort called with path: ${_portPath}`); + connected = true; + console.log("[mock/serial] Port opened"); + pushToView?.({ status: "CONNECTED" }); +} + +export async function closePort(): Promise { + if (!connected) return; + stopAutoFire(); + connected = false; + console.log("[mock/serial] Port closed"); + pushToView?.({ status: "DISCONNECTED" }); +} + +export function sendCommand(_json: string): void { + console.log("[mock/serial] sendCommand (no-op):", _json); +} + +export function isConnected(): boolean { + return connected; +} + +// ─── Mock-only API ─────────────────────────────────────────────────────────── + +export interface TriggerOptions { + speed: number; + tolerance: number; + isSpeeding: boolean; +} + +export function triggerMeasurement({ speed, tolerance, isSpeeding }: TriggerOptions): void { + if (!connected) { + console.warn("[mock/serial] triggerMeasurement called but not connected — ignoring"); + return; + } + const timestamp = Date.now(); + if (isSpeeding) { + const msg = { status: "SPEEDING", value: speed, tolerance, direction: "forward", timestamp }; + pushToView?.(msg as SerialStatusPayload); + onSpeeding?.(msg); + console.log(`[mock/serial] Triggered SPEEDING @ ${speed} km/h (tol ${tolerance})`); + } else { + pushToView?.({ status: "OK", value: speed, tolerance, direction: "forward", timestamp }); + console.log(`[mock/serial] Triggered OK @ ${speed} km/h (tol ${tolerance})`); + } +} + +export interface AutoFireOptions { + speed: number; + tolerance: number; + isSpeeding: boolean; + interval: number; +} + +export function startAutoFire(options: AutoFireOptions): void { + stopAutoFire(); + console.log(`[mock/serial] Auto-fire started: every ${options.interval}ms`); + autoFireTimer = setInterval(() => triggerMeasurement(options), options.interval); +} + +export function stopAutoFire(): void { + if (autoFireTimer !== null) { + clearInterval(autoFireTimer); + autoFireTimer = null; + console.log("[mock/serial] Auto-fire stopped"); + } +} diff --git a/headless/src/server/network.ts b/headless/src/server/network.ts new file mode 100644 index 0000000..34657d9 --- /dev/null +++ b/headless/src/server/network.ts @@ -0,0 +1,130 @@ +import os from "os"; + +export interface NetworkInterfaceDetail { + name: string; + role: "camera-lan" | "hotspot-ap" | "other" | "loopback"; + address: string; + family: string; + netmask: string; + mac: string; + expectedIp?: string; + isConfigured: boolean; +} + +export interface SystemNetworkSummary { + cameraLan: { + interfaceName: string | null; + ip: string | null; + expectedIp: "192.168.1.100"; + subnet: "192.168.1.0/24"; + status: "ok" | "ip_mismatch" | "missing"; + description: string; + }; + hotspotAp: { + interfaceName: string | null; + ip: string | null; + expectedIp: "192.168.4.1"; + subnet: "192.168.4.0/24"; + status: "ok" | "ip_mismatch" | "missing"; + description: string; + }; + interfaces: NetworkInterfaceDetail[]; +} + +export function getSystemNetworkSummary(): SystemNetworkSummary { + const rawInterfaces = os.networkInterfaces(); + const interfaceList: NetworkInterfaceDetail[] = []; + + let cameraEthIface: { name: string; address: string; netmask: string; mac: string } | null = null; + let wifiHotspotIface: { name: string; address: string; netmask: string; mac: string } | null = null; + + for (const [name, addrs] of Object.entries(rawInterfaces)) { + if (!addrs) continue; + for (const addr of addrs) { + if (addr.family !== "IPv4") continue; + + const isLoopback = addr.internal || addr.address.startsWith("127."); + const isCameraSubnet = addr.address === "192.168.1.100" || addr.address.startsWith("192.168.1."); + const isHotspotSubnet = addr.address === "192.168.4.1" || addr.address.startsWith("192.168.4."); + const isEthName = /^(eth|end|enp|eno|enx)/i.test(name); + const isWifiName = /^(wlan|wifi|wlp|wlx)/i.test(name); + + let role: "camera-lan" | "hotspot-ap" | "other" | "loopback" = "other"; + let expectedIp: string | undefined = undefined; + + if (isLoopback) { + role = "loopback"; + } else if (isCameraSubnet || isEthName) { + role = "camera-lan"; + expectedIp = "192.168.1.100"; + if (!cameraEthIface || addr.address === "192.168.1.100") { + cameraEthIface = { name, address: addr.address, netmask: addr.netmask, mac: addr.mac }; + } + } else if (isHotspotSubnet || isWifiName) { + role = "hotspot-ap"; + expectedIp = "192.168.4.1"; + if (!wifiHotspotIface || addr.address === "192.168.4.1") { + wifiHotspotIface = { name, address: addr.address, netmask: addr.netmask, mac: addr.mac }; + } + } + + interfaceList.push({ + name, + role, + address: addr.address, + family: addr.family, + netmask: addr.netmask, + mac: addr.mac, + expectedIp, + isConfigured: expectedIp ? addr.address === expectedIp : true, + }); + } + } + + // Determine Camera LAN (eth0: 192.168.1.100) status + const cameraStatus: "ok" | "ip_mismatch" | "missing" = !cameraEthIface + ? "missing" + : cameraEthIface.address === "192.168.1.100" + ? "ok" + : "ip_mismatch"; + + // Determine Wi-Fi Hotspot (wlan0/wifi0: 192.168.4.1) status + const hotspotStatus: "ok" | "ip_mismatch" | "missing" = !wifiHotspotIface + ? "missing" + : wifiHotspotIface.address === "192.168.4.1" + ? "ok" + : "ip_mismatch"; + + return { + cameraLan: { + interfaceName: cameraEthIface ? cameraEthIface.name : null, + ip: cameraEthIface ? cameraEthIface.address : null, + expectedIp: "192.168.1.100", + subnet: "192.168.1.0/24", + status: cameraStatus, + description: "Dedicated GigE Vision Industrial Camera LAN (eth0/end0)", + }, + hotspotAp: { + interfaceName: wifiHotspotIface ? wifiHotspotIface.name : null, + ip: wifiHotspotIface ? wifiHotspotIface.address : null, + expectedIp: "192.168.4.1", + subnet: "192.168.4.0/24", + status: hotspotStatus, + description: "Wi-Fi Access Point & Remote Web UI Control (wlan0/wifi0)", + }, + interfaces: interfaceList, + }; +} + +export function logNetworkStatus(): void { + const summary = getSystemNetworkSummary(); + console.log("─────────────────────────────────────────────────────────────────"); + console.log(" Network Interfaces & Subnet Configuration:"); + console.log( + ` • Camera LAN [${summary.cameraLan.interfaceName || "eth0"}]: ${summary.cameraLan.ip || "Not configured"} (Expected: 192.168.1.100, Subnet: 192.168.1.0/24) -> [${summary.cameraLan.status.toUpperCase()}]` + ); + console.log( + ` • Hotspot AP [${summary.hotspotAp.interfaceName || "wlan0/wifi0"}]: ${summary.hotspotAp.ip || "Not configured"} (Expected: 192.168.4.1, Web UI: http://${summary.hotspotAp.ip || "192.168.4.1"}:3000) -> [${summary.hotspotAp.status.toUpperCase()}]` + ); + console.log("─────────────────────────────────────────────────────────────────"); +} diff --git a/headless/src/server/rpc.ts b/headless/src/server/rpc.ts new file mode 100644 index 0000000..97a7e81 --- /dev/null +++ b/headless/src/server/rpc.ts @@ -0,0 +1,68 @@ +import type { ServerWebSocket } from "bun"; +import type { SpeedcameraRPC } from "../shared/types"; + +export type RequestHandlers = { + [K in keyof SpeedcameraRPC["bun"]["requests"]]: ( + params: SpeedcameraRPC["bun"]["requests"][K]["params"] + ) => Promise | SpeedcameraRPC["bun"]["requests"][K]["response"]; +}; + +export type PushMessages = SpeedcameraRPC["webview"]["messages"]; + +export class RpcServer { + private sockets = new Set>(); + private handlers: RequestHandlers; + + constructor(handlers: RequestHandlers) { + this.handlers = handlers; + } + + public registerSocket(ws: ServerWebSocket) { + this.sockets.add(ws); + } + + public unregisterSocket(ws: ServerWebSocket) { + this.sockets.delete(ws); + } + + public async handleMessage(ws: ServerWebSocket, message: string | Buffer) { + let msgStr = typeof message === "string" ? message : message.toString("utf-8"); + let parsed: any; + try { + parsed = JSON.parse(msgStr); + } catch { + ws.send(JSON.stringify({ error: "Invalid JSON" })); + return; + } + + const { id, method, params } = parsed; + if (!id || !method) { + return; + } + + const handler = (this.handlers as any)[method]; + if (!handler) { + ws.send(JSON.stringify({ id, error: `Method '${method}' not found` })); + return; + } + + try { + const result = await handler(params ?? {}); + ws.send(JSON.stringify({ id, result: result !== undefined ? result : null })); + } catch (err: any) { + console.error(`[rpc] Error executing method '${method}':`, err); + ws.send(JSON.stringify({ id, error: err?.message || String(err) })); + } + } + + public broadcast(event: K, payload: PushMessages[K]) { + const data = JSON.stringify({ event, payload }); + for (const ws of this.sockets) { + try { + ws.send(data); + } catch (err) { + console.error("[rpc] Failed to push to socket:", err); + } + } + } +} diff --git a/headless/src/server/serial.ts b/headless/src/server/serial.ts new file mode 100644 index 0000000..f426b3a --- /dev/null +++ b/headless/src/server/serial.ts @@ -0,0 +1,184 @@ +import { SerialPort, list, readlineParser } from "bun-serialport"; +import type { PortInfo, SerialStatusPayload } from "../shared/types"; +import { EspMessageSchema, EspCommandSchema, type EspMessage } from "../shared/schemas"; + +// ─── State ──────────────────────────────────────────────────────────────────── + +let activePort: SerialPort | null = null; +let pushToView: ((payload: SerialStatusPayload) => void) | null = null; +let onSpeeding: ((msg: EspMessage) => void) | null = null; + +// ─── Initialization ─────────────────────────────────────────────────────────── + +export function initSerial( + push: (payload: SerialStatusPayload) => void, + onSpeedingCapture?: (msg: EspMessage) => void +): void { + pushToView = push; + onSpeeding = onSpeedingCapture || null; +} + +// ─── Public API ─────────────────────────────────────────────────────────────── + +export async function listPorts(): Promise { + return list(); +} + +export async function openPort(portPath: string): Promise { + if (activePort?.isOpen) { + await closePort(); + } + + const port = new SerialPort({ + path: portPath, + baudRate: 115200, + autoOpen: false, + }); + + const parser = port.pipe(readlineParser()); + + parser.on("data", (line: string) => { + handleIncoming(line.trim()); + }); + + port.on("error", (err: Error) => { + console.error(`[serial] Port error on ${portPath}:`, err); + }); + + port.on("close", () => { + console.log(`[serial] Port ${portPath} closed`); + activePort = null; + pushToView?.({ status: "DISCONNECTED" }); + }); + + await port.open(); + + activePort = port; + console.log(`[serial] Opened ${portPath}`); + pushToView?.({ status: "CONNECTED" }); +} + +export async function closePort(): Promise { + if (!activePort) return; + await activePort.close(); +} + +export function sendCommand(json: string): void { + if (!activePort?.isOpen) { + console.warn("[serial] sendCommand called but no port is open"); + return; + } + + let parsed: unknown; + try { + parsed = JSON.parse(json); + } catch { + console.error("[serial] sendCommand: invalid JSON:", json); + return; + } + + const validation = EspCommandSchema.safeParse(parsed); + if (!validation.success) { + console.error("[serial] sendCommand: invalid command schema:", validation.error.issues); + return; + } + + activePort.write(json + "\n").catch((err: Error) => { + console.error("[serial] Write error:", err); + }); + console.debug("[serial] Sent command:", json); +} + +export function isConnected(): boolean { + return activePort?.isOpen === true; +} + +// ─── Incoming data parser ───────────────────────────────────────────────────── + +function handleIncoming(raw: string): void { + const timestamp = Date.now(); + console.log("[serial] Received:", raw); + + let parsed: unknown; + try { + parsed = JSON.parse(raw); + } catch { + console.warn("[serial] Non-JSON data received:", raw); + return; + } + + if (typeof parsed === "object" && parsed !== null && "debug" in parsed) { + console.debug("[serial] ESP debug:", (parsed as Record).debug); + return; + } + + const result = EspMessageSchema.safeParse(parsed); + if (!result.success) { + console.warn("[serial] Schema validation failed:", result.error.issues, "raw:", raw); + return; + } + + const msg = result.data; + + switch (msg.status) { + case "speeding": + pushToView?.({ + status: "SPEEDING", + value: msg.value, + tolerance: msg.tolerance, + direction: msg.direction, + timestamp, + }); + onSpeeding?.(msg); + break; + + case "legal": + pushToView?.({ + status: "OK", + value: msg.value, + tolerance: msg.tolerance, + direction: msg.direction, + timestamp, + }); + break; + + case "pong": + pushToView?.({ status: "PONG", config: msg.config }); + break; + + case "lapStart": + pushToView?.({ + status: "LAPSTART", + lapNumber: msg.lapNumber, + speedAtStart: msg.speedAtStart, + timestamp, + }); + break; + + case "lapEnd": + pushToView?.({ + status: "LAPEND", + lapNumber: msg.lapNumber, + durationMs: msg.durationMs, + speedAtStart: msg.speedAtStart, + speedAtEnd: msg.speedAtEnd, + timestamp, + }); + break; + + case "lapWaiting": + pushToView?.({ status: "LAPWAITING" }); + break; + + case "lapStopped": + pushToView?.({ status: "LAPSTOPPED" }); + break; + + case "configError": + console.warn("[serial] ESP config error:", msg.message); + break; + + default: + break; + } +} diff --git a/headless/src/server/skin-renderer.ts b/headless/src/server/skin-renderer.ts new file mode 100644 index 0000000..19c4823 --- /dev/null +++ b/headless/src/server/skin-renderer.ts @@ -0,0 +1,85 @@ +import { createCanvas, loadImage } from "@napi-rs/canvas"; +import type { Violation } from "../shared/types"; + +const SYSTEM_NR = "PS-847291"; + +const TOP_BAR_H = 40; +const BOTTOM_BAR_H = 30; +const FONT = "bold 13px monospace"; +const FONT_SM = "12px monospace"; +const LABEL_FONT = "11px monospace"; + +/** + * Render a Vitronic Poliscan-style skin on a violation image. + * Returns a PNG buffer. Source image is NOT modified. + */ +export async function renderPoliscanSkin( + imagePath: string, + violation: Violation, + opts: { measuringLocation: string }, +): Promise { + const src = await loadImage(imagePath); + const w = src.width; + const totalH = src.height + TOP_BAR_H + BOTTOM_BAR_H; + + const canvas = createCanvas(w, totalH); + const ctx = canvas.getContext("2d"); + + // ── Top bar ───────────────────────────────────────────────────────────────── + ctx.fillStyle = "#000"; + ctx.fillRect(0, 0, w, TOP_BAR_H); + + // Labels row (y ~12) + ctx.fillStyle = "#aaa"; + ctx.font = LABEL_FONT; + const labelY = 13; + ctx.fillText("Datum / Zeit", 10, labelY); + ctx.fillText("Limit PKW", 260, labelY); + ctx.fillText("Geschw.", 400, labelY); + ctx.fillText("Richtung", 530, labelY); + + // Values row (y ~32) + ctx.fillStyle = "#fff"; + ctx.font = FONT; + const valY = 32; + + const ts = new Date(violation.timestamp); + const dateStr = ts.toLocaleDateString("de-DE", { + day: "2-digit", month: "2-digit", year: "numeric", + }); + const timeStr = ts.toLocaleTimeString("de-DE", { + hour: "2-digit", minute: "2-digit", second: "2-digit", + }); + ctx.fillText(`${dateStr} ${timeStr}`, 10, valY); + ctx.fillText(`${violation.maxSpeed} km/h`, 260, valY); + ctx.fillText(`${violation.measuredSpeed} km/h`, 400, valY); + + const dirText = violation.direction === "forward" ? "abgehend" : "ankommend"; + ctx.fillText(dirText, 530, valY); + + // ── Source image ──────────────────────────────────────────────────────────── + ctx.drawImage(src, 0, TOP_BAR_H); + + // ── Bottom bar ────────────────────────────────────────────────────────────── + const bottomY = TOP_BAR_H + src.height; + ctx.fillStyle = "#000"; + ctx.fillRect(0, bottomY, w, BOTTOM_BAR_H); + + ctx.fillStyle = "#aaa"; + ctx.font = LABEL_FONT; + const bLabelY = bottomY + 11; + ctx.fillText("System", 10, bLabelY); + ctx.fillText("Bildnummer", 200, bLabelY); + ctx.fillText("Ort", 420, bLabelY); + + ctx.fillStyle = "#fff"; + ctx.font = FONT_SM; + const bValY = bottomY + 24; + ctx.fillText(SYSTEM_NR, 10, bValY); + + const imgNr = `${SYSTEM_NR.replace("PS-", "")} - ${String(violation.id).padStart(3, "0")} - 1`; + ctx.fillText(imgNr, 200, bValY); + ctx.fillText(opts.measuringLocation || "—", 420, bValY); + + return Buffer.from(canvas.toBuffer("image/png")); +} diff --git a/headless/src/server/teable.ts b/headless/src/server/teable.ts new file mode 100644 index 0000000..930fa74 --- /dev/null +++ b/headless/src/server/teable.ts @@ -0,0 +1,252 @@ +import { getSettings, saveSetting } from "./database"; +import type { Lap, LapSession, TeableUser, TeableSpace, TeableBase, TeableTable, TeableSchemaCheck } from "../shared/types"; + +// ─── Required fields for the Laps table ────────────────────────────────────── + +interface RequiredField { + name: string; + type: string; +} + +const REQUIRED_FIELDS: RequiredField[] = [ + { 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" }, +]; + +// ─── Helpers ────────────────────────────────────────────────────────────────── + +const FETCH_OPTS = { tls: { rejectUnauthorized: false } } as RequestInit; + +function buildHeaders(token: string): Record { + return { + "Authorization": `Bearer ${token}`, + "Content-Type": "application/json", + }; +} + +function apiFetch(url: string, init?: RequestInit): Promise { + return fetch(url, { ...FETCH_OPTS, ...init, headers: { ...init?.headers } }); +} + +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")}`; +} + +function getConfig(): { url: string; token: string } { + const settings = getSettings(); + const url = settings.teableUrl.replace(/\/+$/, ""); + const token = settings.teableToken; + if (!url) throw new Error("Teable not configured"); + if (!token) throw new Error("Teable token not found"); + return { url, token }; +} + +// ─── Connection test ────────────────────────────────────────────────────────── + +export async function testTeableConnection(url: string, token: string): Promise { + const base = url.replace(/\/+$/, ""); + + let spacesResp: Response; + try { + spacesResp = await apiFetch(`${base}/api/space`, { headers: buildHeaders(token) }); + } catch (e) { + throw new Error(`Could not connect to ${base} — check the URL and your network connection. Details: ${String(e)}`); + } + + if (spacesResp.status === 401) { + throw new Error("Invalid or expired access token. Please check your Personal Access Token."); + } + if (!spacesResp.ok) { + const body = await spacesResp.text().catch(() => ""); + throw new Error(`Teable API returned ${spacesResp.status} — ${body}`); + } + + let user: TeableUser = { id: "", name: "Teable User", email: "", avatar: null }; + try { + const userResp = await apiFetch(`${base}/api/auth/user/me`, { headers: buildHeaders(token) }); + if (userResp.ok) { + const data = await userResp.json() as { id?: string; name?: string; email?: string; avatar?: string }; + user = { + id: data.id ?? "", + name: data.name ?? "Teable User", + email: data.email ?? "", + avatar: data.avatar ?? null, + }; + } + } catch { + // Fallback + } + + return user; +} + +// ─── Config management ──────────────────────────────────────────────────────── + +export function saveTeableConfig( + url: string, + token: string, + userName: string, + userEmail: string, + userAvatar: string | null, +): void { + saveSetting("teableUrl", url); + saveSetting("teableToken", token); + saveSetting("teableUserName", userName); + saveSetting("teableUserEmail", userEmail); + saveSetting("teableUserAvatar", userAvatar ?? ""); +} + +export function removeTeableConfig(): void { + saveSetting("teableUrl", ""); + saveSetting("teableToken", ""); + saveSetting("teableUserName", ""); + saveSetting("teableUserEmail", ""); + saveSetting("teableUserAvatar", ""); + saveSetting("teableSpaceId", ""); + saveSetting("teableBaseId", ""); + saveSetting("teableTableId", ""); + saveSetting("teableSyncEnabled", "false"); +} + +export function saveTeableTarget(spaceId: string, baseId: string, tableId: string): void { + saveSetting("teableSpaceId", spaceId); + saveSetting("teableBaseId", baseId); + saveSetting("teableTableId", tableId); +} + +// ─── Spaces / Bases / Tables ────────────────────────────────────────────────── + +export async function listTeableSpaces(): Promise { + const { url, token } = getConfig(); + const resp = await apiFetch(`${url}/api/space`, { headers: buildHeaders(token) }); + if (!resp.ok) throw new Error(`Failed to fetch spaces: ${resp.status}`); + return resp.json() as Promise; +} + +export async function listTeableBases(spaceId: string): Promise { + const { url, token } = getConfig(); + const resp = await apiFetch(`${url}/api/space/${encodeURIComponent(spaceId)}/base`, { + headers: buildHeaders(token), + }); + if (!resp.ok) throw new Error(`Failed to fetch bases: ${resp.status}`); + return resp.json() as Promise; +} + +export async function listTeableTables(baseId: string): Promise { + const { url, token } = getConfig(); + const resp = await apiFetch(`${url}/api/base/${encodeURIComponent(baseId)}/table`, { + headers: buildHeaders(token), + }); + if (!resp.ok) throw new Error(`Failed to fetch tables: ${resp.status}`); + return resp.json() as Promise; +} + +// ─── Schema verification & provisioning ────────────────────────────────────── + +async function listFields(url: string, token: string, tableId: string): Promise> { + const resp = await apiFetch(`${url}/api/table/${encodeURIComponent(tableId)}/field`, { + headers: buildHeaders(token), + }); + if (!resp.ok) throw new Error(`Failed to fetch fields: ${resp.status}`); + return resp.json() as Promise>; +} + +export async function verifyTeableTable(tableId: string): Promise { + const { url, token } = getConfig(); + const fields = await listFields(url, token, tableId); + const existing = new Set(fields.map((f) => f.name)); + const missingFields = REQUIRED_FIELDS.filter((f) => !existing.has(f.name)).map((f) => f.name); + return { missingFields }; +} + +export async function ensureTeableFields(tableId: string): Promise { + const { url, token } = getConfig(); + const fields = await listFields(url, token, tableId); + const existing = new Set(fields.map((f) => f.name)); + + const created: string[] = []; + for (const field of REQUIRED_FIELDS) { + if (existing.has(field.name)) continue; + + const resp = await apiFetch(`${url}/api/table/${encodeURIComponent(tableId)}/field`, { + method: "POST", + headers: buildHeaders(token), + body: JSON.stringify({ type: field.type, name: field.name }), + }); + + if (!resp.ok) { + const body = await resp.text().catch(() => ""); + throw new Error(`Failed to create field '${field.name}': ${resp.status} — ${body}`); + } + created.push(field.name); + } + + return created; +} + +export async function createTeableTable(baseId: string, tableName: string): Promise { + const { url, token } = getConfig(); + + const resp = await apiFetch(`${url}/api/base/${encodeURIComponent(baseId)}/table`, { + method: "POST", + headers: buildHeaders(token), + body: JSON.stringify({ + name: tableName, + fields: REQUIRED_FIELDS.map((f) => ({ type: f.type, name: f.name })), + }), + }); + + if (!resp.ok) { + const body = await resp.text().catch(() => ""); + throw new Error(`Failed to create table: ${resp.status} — ${body}`); + } + + const data = await resp.json() as { id: string; name: string }; + return { id: data.id, name: data.name }; +} + +// ─── Lap sync ───────────────────────────────────────────────────────────────── + +export async function syncLapToTeable(lap: Lap, session: LapSession): Promise { + const { url, token } = getConfig(); + const settings = getSettings(); + const tableId = settings.teableTableId; + if (!tableId) throw new Error("No Teable table selected"); + + const fields: Record = { + "Session Started At": session.startedAt, + "Lap Mode": session.lapMode, + "Lap Number": lap.lapNumber, + "Start Time": new Date(lap.startTimestamp).toISOString(), + "End Time": new Date(lap.endTimestamp).toISOString(), + "Duration": formatDuration(lap.durationMs), + "Speed At Start": lap.speedAtStart, + "Speed At End": lap.speedAtEnd, + }; + + const resp = await apiFetch(`${url}/api/table/${encodeURIComponent(tableId)}/record`, { + method: "POST", + headers: buildHeaders(token), + body: JSON.stringify({ + fieldKeyType: "name", + typecast: true, + records: [{ fields }], + }), + }); + + if (!resp.ok) { + const body = await resp.text().catch(() => ""); + throw new Error(`Failed to create Teable record: ${resp.status} — ${body}`); + } +} diff --git a/headless/src/shared/schemas.ts b/headless/src/shared/schemas.ts new file mode 100644 index 0000000..a3a34a9 --- /dev/null +++ b/headless/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/src/shared/types.ts b/headless/src/shared/types.ts new file mode 100644 index 0000000..e2dc204 --- /dev/null +++ b/headless/src/shared/types.ts @@ -0,0 +1,548 @@ +// ─── Domain Types ─────────────────────────────────────────────────────────── + +export interface NetworkInterfaceDetail { + name: string; + role: "camera-lan" | "hotspot-ap" | "other" | "loopback"; + address: string; + family: string; + netmask: string; + mac: string; + expectedIp?: string; + isConfigured: boolean; +} + +export interface SystemNetworkSummary { + cameraLan: { + interfaceName: string | null; + ip: string | null; + expectedIp: "192.168.1.100"; + subnet: "192.168.1.0/24"; + status: "ok" | "ip_mismatch" | "missing"; + description: string; + }; + hotspotAp: { + interfaceName: string | null; + ip: string | null; + expectedIp: "192.168.4.1"; + subnet: "192.168.4.0/24"; + status: "ok" | "ip_mismatch" | "missing"; + description: string; + }; + interfaces: NetworkInterfaceDetail[]; +} + +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; +} + +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" } + | { 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 }; + response: string; // data-URL or path + }; + getSkinnedImageData: { + params: { violationId: number }; + response: string; // data-URL or URL of skinned image + }; + exportSkinnedImages: { + params: { violationIds: number[]; targetDir: string }; + response: { exported: number; failed: number }; + }; + + // DB – settings + getSettings: { + params: Record; + response: AppSettings; + }; + saveSetting: { + params: { key: keyof AppSettings; value: string }; + response: void; + }; + + // Serial + listPorts: { + params: Record; + response: PortInfo[]; + }; + 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; + }; + + // 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, { + // Bun pushes serial measurement updates to the view + serialStatus: SerialStatusPayload; + // Bun pushes camera connection status to the view + cameraStatus: CameraStatusPayload; + // Bun notifies the view that a new app version is ready to install + updateAvailable: { version: string }; + // Bun streams updater status events to the view + updateProgress: { + status: string; + message: string; + progress?: number; + }; + // Bun streams esptool progress events to the view + flashProgress: FlashProgressPayload; + // Push setup live stream frame + liveFrame: string; + }>; +}; diff --git a/headless/src/stores/slices/cameraSlice.ts b/headless/src/stores/slices/cameraSlice.ts new file mode 100644 index 0000000..69fc04e --- /dev/null +++ b/headless/src/stores/slices/cameraSlice.ts @@ -0,0 +1,128 @@ +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; +} + +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, + setCameraStatus: (status) => set({ + cameraConnected: status.connected, + cameraVendor: status.vendor, + cameraModel: status.model, + cameraSerial: status.serial, + }), + + 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, + }); + }, + + 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 { + 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/src/stores/slices/flasherSlice.ts b/headless/src/stores/slices/flasherSlice.ts new file mode 100644 index 0000000..c0d670c --- /dev/null +++ b/headless/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/src/stores/slices/lapSlice.ts b/headless/src/stores/slices/lapSlice.ts new file mode 100644 index 0000000..aba2102 --- /dev/null +++ b/headless/src/stores/slices/lapSlice.ts @@ -0,0 +1,262 @@ +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 { 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; + +// ─── Helpers ────────────────────────────────────────────────────────────────── +// Removed grabFrame (using bun side captureFrame) +// ─── Slice ──────────────────────────────────────────────────────────────────── + +export const createLapSlice: StateCreator< + LapSlice & CameraSlice & TeableSlice, + [], + [], + 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", + }); + // 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, + // Keep currentLaps so the UI can show the final session summary + }); + }, + + // ── State machine ────────────────────────────────────────────────────────── + + handleSerialStatusForLap: (payload) => { + // ── LAPSTART: first car pass — firmware opened a new lap ────────────────── + if (payload.status === "LAPSTART") { + const { lapState, lapSettings } = get(); + + // Accept "waiting" (first lap) or "timing" (MULTI lap N+1 boundary) + const isMultiContinuation = lapState === "timing" && lapSettings.lapMode === "multi"; + if (lapState !== "waiting" && !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/src/stores/slices/measurementSlice.ts b/headless/src/stores/slices/measurementSlice.ts new file mode 100644 index 0000000..dc1f741 --- /dev/null +++ b/headless/src/stores/slices/measurementSlice.ts @@ -0,0 +1,90 @@ +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; + } + + const { systemState, appMode } = get(); + // In PASSIVE mode, ignore all serial measurements + if (systemState === "PASSIVE") 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 + if (payload.status === "SPEEDING" || payload.status === "OK") { + set({ lastSpeed: payload.value, lastDirection: payload.direction }); + } + return; + } + + if (payload.status === "SPEEDING") { + const { value, direction } = payload; + set({ lastSpeed: value, lastDirection: direction }); + + // Only save violations and flash when fully ARMED + if (systemState !== "ARMED") return; + + const { maxSpeed } = get(); + + // Trigger bun-side capture and save + getRpc() + .request.saveViolation({ measuredSpeed: value, maxSpeed, direction }) + .then((v) => { + get().setLastViolation(v); + }) + .catch((err: unknown) => { + console.error("[measurement] Capture/save failed:", err); + toast.error("Failed to save violation"); + }); + } else if (payload.status === "OK") { + set({ lastSpeed: payload.value, lastDirection: payload.direction }); + } + // CONNECTED / DISCONNECTED handled by serialSlice indirectly via store + }, +}); diff --git a/headless/src/stores/slices/serialSlice.ts b/headless/src/stores/slices/serialSlice.ts new file mode 100644 index 0000000..d4710ce --- /dev/null +++ b/headless/src/stores/slices/serialSlice.ts @@ -0,0 +1,22 @@ +import type { StateCreator } from "zustand"; +import type { PortInfo } from "@/shared/types"; + +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; +} + +export const createSerialSlice: StateCreator = (set) => ({ + availablePorts: [], + selectedPort: "", + connectedPort: "", + setAvailablePorts: (ports) => set({ availablePorts: ports }), + setSelectedPort: (path) => set({ selectedPort: path }), + setConnectedPort: (path) => set({ connectedPort: path }), +}); diff --git a/headless/src/stores/slices/systemSlice.ts b/headless/src/stores/slices/systemSlice.ts new file mode 100644 index 0000000..8add0b7 --- /dev/null +++ b/headless/src/stores/slices/systemSlice.ts @@ -0,0 +1,20 @@ +import type { StateCreator } from "zustand"; + +export type SystemState = "PASSIVE" | "DISARMED" | "ARMED"; +export type AppMode = "speedcamera" | "laptimer"; + +export interface SystemSlice { + /** Current operational state of the speed camera system */ + systemState: SystemState; + setSystemState: (state: SystemState) => void; + /** Active mode — routes serial events to violation or lap handler */ + appMode: AppMode; + setAppMode: (mode: AppMode) => void; +} + +export const createSystemSlice: StateCreator = (set) => ({ + systemState: "PASSIVE", + setSystemState: (state) => set({ systemState: state }), + appMode: "speedcamera", + setAppMode: (mode) => set({ appMode: mode }), +}); diff --git a/headless/src/stores/slices/teableSlice.ts b/headless/src/stores/slices/teableSlice.ts new file mode 100644 index 0000000..d457de9 --- /dev/null +++ b/headless/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/src/stores/slices/updaterSlice.ts b/headless/src/stores/slices/updaterSlice.ts new file mode 100644 index 0000000..95a089b --- /dev/null +++ b/headless/src/stores/slices/updaterSlice.ts @@ -0,0 +1,82 @@ +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; + // Map granular electrobun status to coarse UI phase + 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 }), +}); \ No newline at end of file diff --git a/headless/src/stores/useAppStore.ts b/headless/src/stores/useAppStore.ts new file mode 100644 index 0000000..9820e67 --- /dev/null +++ b/headless/src/stores/useAppStore.ts @@ -0,0 +1,23 @@ +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/tailwind.config.js b/headless/tailwind.config.js new file mode 100644 index 0000000..05e1c9a --- /dev/null +++ b/headless/tailwind.config.js @@ -0,0 +1,8 @@ +/** @type {import('tailwindcss').Config} */ +export default { + content: ["./src/**/*.{html,js,ts,jsx,tsx}"], + theme: { + extend: {}, + }, + plugins: [], +}; diff --git a/headless/tsconfig.json b/headless/tsconfig.json new file mode 100644 index 0000000..bc5f54f --- /dev/null +++ b/headless/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": { + "@/*": ["./src/*"] + } + }, + "include": ["src"], + "exclude": ["node_modules", "dist"] +} diff --git a/headless/vite.config.ts b/headless/vite.config.ts new file mode 100644 index 0000000..5cc127b --- /dev/null +++ b/headless/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: "src/mainview", + resolve: { + alias: { + "@": path.resolve(__dirname, "./src"), + }, + }, + build: { + outDir: "../../dist", + emptyOutDir: true, + }, + server: { + port: 5173, + strictPort: true, + proxy: { + "/image": "http://localhost:3000", + "/skinned-image": "http://localhost:3000", + "/api": "http://localhost:3000", + "/ws": { + target: "ws://localhost:3000", + ws: true, + }, + }, + }, +}); From 087c755c3aa9a12f57c86f836fd5ac08699d3a61 Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Mon, 10 Aug 2026 23:54:28 +0200 Subject: [PATCH 02/65] fix: update package name from python3-esptool to esptool in installation script --- headless/README.md | 2 +- headless/scripts/install-rpi.sh | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/headless/README.md b/headless/README.md index e495b10..b8da53c 100644 --- a/headless/README.md +++ b/headless/README.md @@ -71,7 +71,7 @@ chmod +x scripts/install-rpi.sh ``` This script will automatically: -1. Install system libraries (`libaravis-0.8-0`, `python3-esptool`, `network-manager`). +1. Install system libraries (`libaravis-0.8-0`, `esptool`, `network-manager`). 2. Install the **Bun** ARM64 runtime. 3. Build the production React web bundle. 4. Configure the dual-subnet network interfaces (`scripts/setup-network.sh`): diff --git a/headless/scripts/install-rpi.sh b/headless/scripts/install-rpi.sh index 8114010..15d6742 100644 --- a/headless/scripts/install-rpi.sh +++ b/headless/scripts/install-rpi.sh @@ -11,7 +11,7 @@ sudo apt-get update sudo apt-get install -y \ libaravis-0.8-0 \ libaravis-dev \ - python3-esptool \ + esptool \ network-manager \ curl \ unzip \ From efa4aefb675783c53c2995d22ea0a3c2d2dde01c Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Tue, 11 Aug 2026 00:03:21 +0200 Subject: [PATCH 03/65] fix: update install script for production bundle and enhance network configuration prompts --- headless/scripts/install-rpi.sh | 77 +++++++++++++++++-------------- headless/scripts/setup-network.sh | 0 2 files changed, 42 insertions(+), 35 deletions(-) mode change 100644 => 100755 headless/scripts/install-rpi.sh mode change 100644 => 100755 headless/scripts/setup-network.sh diff --git a/headless/scripts/install-rpi.sh b/headless/scripts/install-rpi.sh old mode 100644 new mode 100755 index 15d6742..d630161 --- a/headless/scripts/install-rpi.sh +++ b/headless/scripts/install-rpi.sh @@ -27,41 +27,17 @@ else echo "[2/5] Bun already installed: $(bun --version)" fi -# 3. Install project dependencies and build frontend -echo "[3/5] Installing project dependencies & building frontend..." +# Ensure bun is in PATH for current script +export PATH="$HOME/.bun/bin:$PATH" + +# 3. Install project dependencies and build production frontend +echo "[3/5] Installing project dependencies & building production bundle..." +cd "$(dirname "$0")/.." bun install bun run build -# 4. Configure Networking (Camera LAN 192.168.1.100 + Wi-Fi Hotspot 192.168.4.1) -echo "[4/5] Network Configuration (Camera LAN & Wi-Fi Hotspot)" -read -p "Do you want to configure the dual-subnet network interfaces? (y/N) " -n 1 -r -echo -if [[ $REPLY =~ ^[Yy]$ ]]; then - # Detect interfaces - ETH_IFACE=$(ip -o link show | awk -F': ' '{print $2}' | grep -E '^(eth|end|enp)' | head -n 1 || echo "eth0") - WIFI_IFACE=$(ip -o link show | awk -F': ' '{print $2}' | grep -E '^(wlan|wifi|wlp)' | head -n 1 || echo "wlan0") - - # 4a. Camera Ethernet LAN - echo "Configuring Camera LAN on ${ETH_IFACE} (Static IP: 192.168.1.100/24)..." - sudo nmcli connection delete "Speedcamera-CameraLAN" 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 - sudo nmcli connection up "Speedcamera-CameraLAN" || echo "Note: Ethernet link active when camera connected." - - # 4b. Wi-Fi Hotspot - SSID="speedcamera" - PASS="speedcamerapass" - echo "Configuring Wi-Fi Hotspot on ${WIFI_IFACE} (SSID: '${SSID}', IP: 192.168.4.1/24)..." - sudo nmcli connection delete "Speedcamera-Hotspot" 2>/dev/null || true - sudo nmcli connection add type wifi ifname "${WIFI_IFACE}" con-name "Speedcamera-Hotspot" autoconnect yes \ - ssid "${SSID}" mode ap 802-11-wireless.band bg \ - ipv4.method shared ipv4.addresses 192.168.4.1/24 \ - wifi-sec.key-mgmt wpa-psk wifi-sec.psk "${PASS}" - sudo nmcli connection up "Speedcamera-Hotspot" || echo "Note: Run 'sudo nmcli connection up Speedcamera-Hotspot' once wireless interface is ready." -fi - -# 5. Install and enable systemd service -echo "[5/5] Installing systemd autostart service..." +# 4. Install and enable systemd service +echo "[4/5] Installing systemd autostart service..." CURRENT_USER=$(whoami) PROJECT_DIR=$(pwd) BUN_BIN=$(command -v bun || echo "$HOME/.bun/bin/bun") @@ -97,9 +73,40 @@ sudo systemctl enable speedcamera.service echo "" echo "=========================================================" -echo " Setup complete!" +echo " Daemon & Frontend installation complete!" echo " Start daemon: sudo systemctl start speedcamera" echo " Check daemon logs: sudo journalctl -u speedcamera -f" -echo " Camera LAN (eth0): Static IP 192.168.1.100/24" -echo " Wi-Fi Hotspot: http://192.168.4.1:3000" +echo "=========================================================" + +# 5. Network Configuration (Final Step with SSH Disconnection Warning) +echo "" +echo "[5/5] Network Configuration (Camera LAN & Wi-Fi Hotspot)" +echo "" +echo "************************************************************************" +echo " CAUTION: NETWORK INTERFACE CONFIGURATION" +echo " Applying these network settings may immediately DISCONNECT your" +echo " current SSH session if you are connected via Wi-Fi or Ethernet!" +echo "" +echo " • Ethernet (eth0/end0) -> Reconfigured to Static IP 192.168.1.100/24" +echo " • Wireless (wlan0) -> Reconfigured as Standalone Hotspot 192.168.4.1" +echo "************************************************************************" +echo "" +read -p "Do you want to configure the dual-subnet network interfaces now? (y/N) " -n 1 -r +echo +if [[ $REPLY =~ ^[Yy]$ ]]; then + # Run dedicated network setup script + chmod +x scripts/setup-network.sh + ./scripts/setup-network.sh +else + echo "Skipping network interface reconfiguration." + echo "You can run network setup anytime later via: ./scripts/setup-network.sh" +fi + +echo "" +echo "=========================================================" +echo " Speedcamera setup finished!" +echo " Web UI access:" +echo " • Hotspot AP: http://192.168.4.1:3000 (SSID: speedcamera)" +echo " • Camera LAN: http://192.168.1.100:3000" +echo " • Local: http://localhost:3000" echo "=========================================================" diff --git a/headless/scripts/setup-network.sh b/headless/scripts/setup-network.sh old mode 100644 new mode 100755 From 25aaf7b6332bbdca7bc4edcad1e6485ca91cded0 Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Fri, 14 Aug 2026 17:06:26 +0200 Subject: [PATCH 04/65] docs: update docs with installer script instructions --- README.md | 37 ++++++-- headless/README.md | 214 +++++++++++++++++++++++++++++++++++++-------- 2 files changed, 211 insertions(+), 40 deletions(-) diff --git a/README.md b/README.md index 1da11b2..783c5b2 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`**](./headless) | **(Recommended)** Lightweight, high-performance headless Raspberry Pi 4/5 daemon and responsive Web UI controller built with Bun, Vite, and React. Creates standalone Wi-Fi hotspot (`192.168.4.1`) & 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) + +All commands are executed from your development laptop. The React frontend is built on the laptop in ~2s (`bun run build`) and synced over SSH, avoiding slow builds on the Pi. + +```bash +cd headless + +# 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 Field Hotspot Mode or Home LAN) +bun run deploy:pi pi@raspberrypi.local +# or when connected to Pi Wi-Fi hotspot in the field: +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 modes, offline field use, and local mock testing, see the [**Headless Documentation**](./headless/README.md). diff --git a/headless/README.md b/headless/README.md index b8da53c..bfa1da3 100644 --- a/headless/README.md +++ b/headless/README.md @@ -36,65 +36,209 @@ Engineered to run natively on **Raspberry Pi 4 / 5 with Raspberry Pi OS Lite** ( --- -## Quick Start (Development) +## ⚡ Critical Rule: Build on Laptop, Not on Pi -### 1. Install Dependencies +Building the React / Vite frontend (`dist/`) directly on a Raspberry Pi can take **over 20 minutes** and easily exhausts memory on low-resource ARM boards. + +The built frontend output is 100% platform-independent static web assets. Therefore: +- **`bun run build` always executes locally on your development laptop** (takes ~2 seconds). +- Pre-built static assets in `dist/` are automatically synced to the Pi over SSH. +- The installer and deploy scripts enforce this workflow by default. + +--- + +## Scenarios & Deployment Procedures + +All deployment and maintenance procedures can be executed directly from your laptop via SSH. + +``` +┌────────────────────────────────────────────────────────────────────────┐ +│ Command │ Purpose │ +├──────────────────────────────┼─────────────────────────────────────────┤ +│ bun run install:pi [target] │ Fresh Pi install on Home LAN / DHCP │ +│ bun run deploy:pi [target] │ Upgrade existing Pi (Field or Home LAN) │ +│ bun run cleanup:pi [target] │ Complete teardown & restore DHCP network│ +└──────────────────────────────┴─────────────────────────────────────────┘ +``` + +--- + +### Scenario 1: Fresh Pi Setup (Home LAN / Wi-Fi with DHCP) + +Use this scenario when you have a freshly flashed Raspberry Pi connected to your home router / Wi-Fi via DHCP and want to provision the complete speedcamera suite. + +#### Run from your laptop: ```bash cd headless -bun install + +# Standard fresh installation (SSH key auth): +bun run install:pi pi@raspberrypi.local + +# With password prompt (if SSH keys are not configured): +bun run install:pi pi@raspberrypi.local --password + +# Using direct IP and automatically switching to Field Mode at the end: +bun run install:pi pi@192.168.1.50 --field + +# Stay in Home LAN mode (skip field network setup): +bun run install:pi pi@raspberrypi.local --lan ``` -### 2. Run in Development Mode (with HMR & Mock Hardware) +#### What this command does: +1. Builds the frontend bundle on your laptop (`bun run build`, ~2s). +2. Establishes an SSH multiplexed connection (password requested once). +3. Rsyncs the codebase and pre-built `dist/` to `~/speedcamera/headless` on the Pi. +4. Updates Pi system packages (`libaravis-0.8-0`, `libaravis-dev`, `esptool`, `network-manager`, `curl`, etc.). +5. Installs the ARM64 Bun runtime on the Pi (if not installed). +6. Installs production node dependencies on the Pi. +7. Registers, enables, and starts the `speedcamera.service` systemd daemon. +8. Configures the network mode (Field Mode or Home LAN Mode). + +--- + +### Scenario 2: Upgrading an Existing Installation + +Use this scenario to push code updates to an already configured Pi. The Pi can either be in **Field Mode** (offline Wi-Fi hotspot) or connected to your **Home LAN**. + +#### Run from your laptop: ```bash -bun run dev:mock +cd headless + +# Deploy to Pi on Home LAN: +bun run deploy:pi pi@raspberrypi.local + +# Deploy to Pi in Field Mode (connected to 'speedcamera' Wi-Fi): +bun run deploy:pi pi@192.168.4.1 + +# With password authentication: +bun run deploy:pi pi@192.168.4.1 --password ``` -* **Frontend (Vite HMR):** `http://localhost:5173` -* **Backend Daemon:** `http://localhost:3000` (WebSocket on `/ws/rpc`) -### 3. Build & Run Production Bundle Locally +#### What this command does: +1. Re-builds the frontend bundle locally (`bun run build`). +2. Syncs changed files (`dist/`, `src/`, `scripts/`, `package.json`, etc.) to the Pi. +3. Automatically detects internet connectivity on the Pi: + - **Online (Home LAN):** Updates production dependencies if `package.json` changed. + - **Offline (Field Mode):** Safely skips dependency downloads and reuses existing `node_modules`. +4. Updates the systemd service file if needed and runs `sudo systemctl daemon-reload`. +5. Restarts `speedcamera.service` and verifies that the daemon is active and running. +6. **Preserves existing network configuration** without causing unexpected disconnections. + +--- + +### Scenario 3: Complete Cleanup & Network Reset + +Use this scenario to completely uninstall Speedcamera, remove systemd services, delete application files, and restore standard DHCP networking on Ethernet and Wi-Fi. + +#### Option A: Remote cleanup from your laptop ```bash -bun run build -bun run start:mock +cd headless + +# Clean up speedcamera and restore DHCP network: +bun run cleanup:pi pi@raspberrypi.local + +# Clean up in Field Mode and purge all SQLite databases/images: +bun run cleanup:pi pi@192.168.4.1 --password --purge + +# Non-interactive cleanup: +bun run cleanup:pi pi@raspberrypi.local --yes --purge ``` -Open `http://localhost:3000` in your browser. + +#### Option B: Direct cleanup on the Raspberry Pi +```bash +# SSH into Pi +ssh pi@raspberrypi.local + +# Run cleanup script +~/speedcamera/headless/scripts/cleanup-pi.sh + +# Or with complete data purge (database & images): +~/speedcamera/headless/scripts/cleanup-pi.sh --purge --yes +``` + +#### What cleanup does: +1. Stops and disables `speedcamera.service`. +2. Deletes `/etc/systemd/system/speedcamera.service` and reloads systemd. +3. Deletes repository files `~/speedcamera` (and purges `~/.speedcamera` if `--purge`). +4. Restores Ethernet `eth0` to standard automatic DHCP (ready for router connection). +5. **Safe Hotspot Teardown:** If triggered while connected to the Pi's Wi-Fi hotspot (`192.168.4.1`), the script completes all service/file/Ethernet cleanup first, then schedules Wi-Fi AP shutdown with a 2-second background delay (`nohup`), allowing the SSH session to return cleanly before the hotspot turns off. --- -## Raspberry Pi 4 / 5 Deployment (Raspberry Pi OS Lite) +## Network Mode Management (`setup-network.sh`) + +You can switch the Pi's networking mode at any time using the network management script: -### Automated Setup -Run the automated installation script on your Raspberry Pi: ```bash -cd headless -chmod +x scripts/install-rpi.sh -./scripts/install-rpi.sh +# Switch to Standalone Field Mode (Camera LAN 192.168.1.100 + Hotspot AP 192.168.4.1) +~/speedcamera/headless/scripts/setup-network.sh field + +# Connect Pi Wi-Fi to a router for internet updates (Client Mode) +~/speedcamera/headless/scripts/setup-network.sh internet "MyHomeWiFi" "SecretPassword123" + +# Revert Ethernet and Wi-Fi to standard DHCP +~/speedcamera/headless/scripts/setup-network.sh dhcp + +# Check active connections, IP addresses, and internet reachability +~/speedcamera/headless/scripts/setup-network.sh status ``` -This script will automatically: -1. Install system libraries (`libaravis-0.8-0`, `esptool`, `network-manager`). -2. Install the **Bun** ARM64 runtime. -3. Build the production React web bundle. -4. Configure the dual-subnet network interfaces (`scripts/setup-network.sh`): - - **`eth0` Camera LAN:** Static IP `192.168.1.100/24` (Subnet `192.168.1.0/24` for industrial GigE camera). - - **`wlan0` Hotspot AP:** Static IP `192.168.4.1/24` (SSID: `speedcamera`, password: `speedcamerapass`). -5. Install and enable the `systemd` service for automatic startup on boot. +--- + +## Managing the Service on Raspberry Pi + +The Speedcamera backend daemon runs as a `systemd` background service: -### Managing the Service ```bash -# Start service -sudo systemctl start speedcamera +# Check service status +sudo systemctl status speedcamera + +# View live streaming logs +sudo journalctl -u speedcamera -f + +# Restart service +sudo systemctl restart speedcamera # Stop service sudo systemctl stop speedcamera -# View live real-time logs -sudo journalctl -u speedcamera -f +# Start service +sudo systemctl start speedcamera ``` --- -## Connecting in the Field -1. Power on the speedcamera Raspberry Pi. -2. On your laptop or phone, connect to the Wi-Fi network **`speedcamera`** (Password: `speedcamerapass`). -3. Open your browser and navigate to: - **`http://192.168.4.1:3000`** +## Field Operation Quick Reference + +1. Power on the Raspberry Pi. +2. On your laptop, phone, or tablet, connect to the Wi-Fi network: + - **SSID:** `speedcamera` + - **Password:** `speedcamerapass` +3. Open your web browser and go to: + - **`http://192.168.4.1:3000`** +4. Connect the industrial GigE Vision camera to the Pi's Ethernet port (assigned to `192.168.1.100`). + +--- + +## Local Development & Testing + +You can develop and test the entire headless system on your local laptop without physical hardware using mock mode: + +```bash +cd headless + +# Install local dependencies +bun install + +# Run frontend (Vite HMR on :5173) + backend (Bun on :3000) with mock camera & radar +bun run dev:mock + +# Build production bundle +bun run build + +# Run production server locally with mock hardware +bun run start:mock +``` + +- **Web UI:** `http://localhost:5173` (dev) or `http://localhost:3000` (production) +- **WebSocket RPC:** `ws://localhost:3000/ws/rpc` From 13baa35c238eb6c8edb9260fbada9e8dda693c38 Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Fri, 14 Aug 2026 17:06:46 +0200 Subject: [PATCH 05/65] Add headless scripts for deployment, cleanup, and installation on Raspberry Pi - Implement cleanup-pi.sh for complete uninstallation and network reset. - Create cleanup-remote.sh for remote teardown and cleanup via SSH. - Add deploy-to-pi.sh for fast deployment and upgrade of Speedcamera on Raspberry Pi. - Introduce install-remote.sh for remote installation with network configuration options. - Enhance install-rpi.sh for improved provisioning and setup with network mode options. - Update setup-network.sh to support field mode and internet connection setup. - Create update-pi.sh for managing package installations and service updates. - Modify speedcamera.service for correct environment variable settings and execution path. --- headless/package.json | 3 + headless/scripts/cleanup-pi.sh | 126 ++++++++++++++ headless/scripts/cleanup-remote.sh | 102 ++++++++++++ headless/scripts/deploy-to-pi.sh | 110 ++++++++++++ headless/scripts/install-remote.sh | 142 ++++++++++++++++ headless/scripts/install-rpi.sh | 239 +++++++++++++++++++-------- headless/scripts/setup-network.sh | 172 +++++++++++++------ headless/scripts/speedcamera.service | 3 +- headless/scripts/update-pi.sh | 89 ++++++++++ 9 files changed, 868 insertions(+), 118 deletions(-) create mode 100755 headless/scripts/cleanup-pi.sh create mode 100755 headless/scripts/cleanup-remote.sh create mode 100755 headless/scripts/deploy-to-pi.sh create mode 100755 headless/scripts/install-remote.sh create mode 100755 headless/scripts/update-pi.sh diff --git a/headless/package.json b/headless/package.json index 592eaea..9431791 100644 --- a/headless/package.json +++ b/headless/package.json @@ -13,6 +13,9 @@ "start:mock": "MOCK_MODE=true vite build && MOCK_MODE=true bun src/server/index.ts", "serve": "bun src/server/index.ts", "serve:mock": "MOCK_MODE=true bun src/server/index.ts", + "install:pi": "./scripts/install-remote.sh", + "deploy:pi": "./scripts/deploy-to-pi.sh", + "cleanup:pi": "./scripts/cleanup-remote.sh", "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": { diff --git a/headless/scripts/cleanup-pi.sh b/headless/scripts/cleanup-pi.sh new file mode 100755 index 0000000..be4bb0d --- /dev/null +++ b/headless/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/scripts/cleanup-remote.sh b/headless/scripts/cleanup-remote.sh new file mode 100755 index 0000000..1bdde14 --- /dev/null +++ b/headless/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 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 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/scripts/deploy-to-pi.sh b/headless/scripts/deploy-to-pi.sh new file mode 100755 index 0000000..b66c7fe --- /dev/null +++ b/headless/scripts/deploy-to-pi.sh @@ -0,0 +1,110 @@ +#!/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.4.1 --password +# bun run deploy:pi pi@raspberrypi.local + +PI_TARGET="pi@raspberrypi.local" +USE_PASSWORD=false +FORCE_INSTALL=false +INSTALL_FLAG="" + +# Parse arguments +for arg in "$@"; do + case "$arg" in + --password|-p|--pass) + USE_PASSWORD=true + ;; + --install|-i) + FORCE_INSTALL=true + INSTALL_FLAG="--install" + ;; + --help|-h) + echo "Speedcamera Headless 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.4.1)" + echo "" + echo "Options:" + echo " --password, -p Force password authentication (disables SSH keys)" + echo " --install, -i Force running 'bun install' on Pi (requires internet on Pi)" + echo " --help, -h Show this help message" + echo "" + echo "Notes:" + echo " • Automatically builds frontend locally on host (fast: <2s)." + echo " • Works seamlessly in Field Mode (offline) or Home LAN Mode (online)." + exit 0 + ;; + *) + if [[ "$arg" != -* ]]; then + PI_TARGET="$arg" + fi + ;; + esac +done + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +HEADLESS_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)" + +# 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 Headless: ${PI_TARGET}" +echo "=========================================================" + +# 1. Build frontend bundle on host (fast!) +echo "[1/3] Building frontend bundle locally on host machine..." +cd "${HEADLESS_DIR}" +bun run build + +# 2. Sync files to Pi (skipping heavy node_modules & git) +echo "[2/3] Syncing files to Pi..." +ssh "${SSH_OPTS[@]}" "${PI_TARGET}" "mkdir -p ~/speedcamera/headless" + +RSYNC_SSH="ssh" +for opt in "${SSH_OPTS[@]}"; do + RSYNC_SSH+=" $(printf "%q" "$opt")" +done + +rsync -avz --delete \ + -e "${RSYNC_SSH}" \ + --exclude 'node_modules' \ + --exclude '.git' \ + --exclude '*.log' \ + "${HEADLESS_DIR}/" "${PI_TARGET}:~/speedcamera/headless/" + +# 3. Update dependencies & restart service on Pi +echo "[3/3] Updating service on Pi..." +# Use -tt to force pseudo-terminal allocation so sudo can prompt for password interactively +ssh -tt "${SSH_OPTS[@]}" "${PI_TARGET}" "chmod +x ~/speedcamera/headless/scripts/*.sh && ~/speedcamera/headless/scripts/update-pi.sh ${INSTALL_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/scripts/install-remote.sh b/headless/scripts/install-remote.sh new file mode 100755 index 0000000..ac4d472 --- /dev/null +++ b/headless/scripts/install-remote.sh @@ -0,0 +1,142 @@ +#!/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 +# bun run install:pi pi@raspberrypi.local + +PI_TARGET="pi@raspberrypi.local" +USE_PASSWORD=false +NETWORK_FLAG="" +PURGE_FIRST=false + +# Parse arguments +for arg in "$@"; do + case "$arg" in + --password|-p|--pass) + USE_PASSWORD=true + ;; + --field) + NETWORK_FLAG="--field" + ;; + --lan|--no-field|--skip-network) + NETWORK_FLAG="--skip-network" + ;; + --purge) + PURGE_FIRST=true + ;; + --help|-h) + echo "Speedcamera Headless 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 " --help, -h Show this help message" + echo "" + echo "Notes:" + echo " • The React frontend is built on this machine (fast: <2s) and synced to the Pi." + echo " • The Pi is never required to run slow Vite/React builds." + exit 0 + ;; + *) + if [[ "$arg" != -* ]]; then + PI_TARGET="$arg" + fi + ;; + esac +done + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +HEADLESS_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)" + +# 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 Remote Pi Fresh Installer" +echo " Target: ${PI_TARGET}" +echo "=========================================================" + +# 1. Build frontend bundle on local laptop +echo "[1/4] Building frontend bundle locally on host machine..." +cd "${HEADLESS_DIR}" +bun run build + +# 2. Test SSH connectivity +echo "[2/4] Connecting to ${PI_TARGET}..." +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 + +# 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 + +# 3. Sync repository & pre-built dist to Pi +echo "[3/4] Syncing application and pre-built frontend to Pi..." +ssh "${SSH_OPTS[@]}" "${PI_TARGET}" "mkdir -p ~/speedcamera/headless" + +RSYNC_SSH="ssh" +for opt in "${SSH_OPTS[@]}"; do + RSYNC_SSH+=" $(printf "%q" "$opt")" +done + +rsync -avz --delete \ + -e "${RSYNC_SSH}" \ + --exclude 'node_modules' \ + --exclude '.git' \ + --exclude '*.log' \ + "${HEADLESS_DIR}/" "${PI_TARGET}:~/speedcamera/headless/" + +# 4. Execute installer on Pi +echo "[4/4] Running system provisioning and service installation on Pi..." +REMOTE_CMD="chmod +x ~/speedcamera/headless/scripts/*.sh && ~/speedcamera/headless/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 Mode Active" + echo " • Web UI: http://${PI_TARGET#*@}:3000 (or http://raspberrypi.local:3000)" + echo " • Switch to field mode later: ssh ${PI_TARGET} '~/speedcamera/headless/scripts/setup-network.sh field'" +fi +echo "" +echo " View logs: ssh ${PI_TARGET} 'sudo journalctl -u speedcamera -f'" +echo "=========================================================" diff --git a/headless/scripts/install-rpi.sh b/headless/scripts/install-rpi.sh index d630161..875d85a 100755 --- a/headless/scripts/install-rpi.sh +++ b/headless/scripts/install-rpi.sh @@ -1,47 +1,141 @@ #!/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 Raspberry Pi Provisioning & Setup" echo "=========================================================" -echo " Speedcamera Raspberry Pi OS Lite Setup & Install Script" +echo " Target user: ${TARGET_USER} (${TARGET_HOME})" +echo " Project dir: ${PROJECT_DIR}" echo "=========================================================" -# 1. Update and install required system packages -echo "[1/5] Installing system packages (Aravis, esptool, NetworkManager)..." -sudo apt-get update -sudo apt-get install -y \ - libaravis-0.8-0 \ - libaravis-dev \ - esptool \ - network-manager \ - curl \ - unzip \ - git +# Parse arguments +SKIP_NETWORK=false +ONLY_NETWORK=false +FORCE_BUILD=false +AUTO_FIELD=false -# 2. Check/Install Bun runtime -if ! command -v bun &> /dev/null; then - echo "[2/5] Installing Bun runtime for ARM64..." - curl -fsSL https://bun.sh/install | bash - export BUN_INSTALL="$HOME/.bun" - export PATH="$BUN_INSTALL/bin:$PATH" +for arg in "$@"; do + case "$arg" in + --skip-network|--app-only|--lan|--no-field) + SKIP_NETWORK=true + ;; + --field) + AUTO_FIELD=true + ;; + --network-only) + ONLY_NETWORK=true + ;; + --force-build) + FORCE_BUILD=true + ;; + --help|-h) + echo "Usage: $0 [options]" + echo "" + echo "Options:" + echo " --app-only, --skip-network, --lan Provision packages, Bun, dependencies, and service (keeps network)" + echo " --field Provision and immediately switch to Field Mode" + echo " --network-only Only configure dual-subnet network (Hotspot AP + Camera LAN)" + echo " --force-build Force Vite frontend build on Pi (NOT recommended: takes >20 mins)" + echo " --help, -h Show this help message" + exit 0 + ;; + esac +done + +# 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 +echo "[*] Checking internet connectivity..." +HAS_INTERNET=true +if ! ping -c 1 -W 2 1.1.1.1 &>/dev/null && ! curl -s --connect-timeout 2 https://bun.sh &>/dev/null; then + HAS_INTERNET=false + echo ">>> WARNING: No active internet connection detected on Pi!" + if [ ! -d "${PROJECT_DIR}/node_modules" ] && [ ! -f "${TARGET_HOME}/.bun/bin/bun" ]; then + echo "Error: Cannot proceed with initial setup without internet (missing node_modules or Bun)." >&2 + echo "Connect Pi to Wi-Fi/Ethernet with internet first." >&2 + exit 1 + fi +fi + +# 1. System packages +if [ "$HAS_INTERNET" = true ]; then + echo "[1/4] Installing system packages (libaravis, esptool, NetworkManager)..." + sudo apt-get update + sudo apt-get install -y \ + libaravis-0.8-0 \ + libaravis-dev \ + esptool \ + network-manager \ + curl \ + unzip \ + git \ + rsync else - echo "[2/5] Bun already installed: $(bun --version)" + echo "[1/4] Skipping apt package updates (offline mode)." fi -# Ensure bun is in PATH for current script -export PATH="$HOME/.bun/bin:$PATH" +# 2. Check/Install Bun runtime +BUN_BIN=$(command -v bun || echo "${TARGET_HOME}/.bun/bin/bun") +if [ ! -x "${BUN_BIN}" ] && ! command -v bun &> /dev/null; then + if [ "$HAS_INTERNET" = true ]; then + echo "[2/4] Installing Bun runtime for ARM64..." + sudo -u "${TARGET_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 "Error: Bun not found and no internet connection to download it." >&2 + exit 1 + fi +else + export PATH="${TARGET_HOME}/.bun/bin:$PATH" + echo "[2/4] Bun runtime ready: ${BUN_BIN}" +fi -# 3. Install project dependencies and build production frontend -echo "[3/5] Installing project dependencies & building production bundle..." -cd "$(dirname "$0")/.." -bun install -bun run build +# 3. Dependencies and frontend bundle check +echo "[3/4] Checking project dependencies & frontend bundle..." +cd "${PROJECT_DIR}" +if [ "$HAS_INTERNET" = true ]; then + sudo -u "${TARGET_USER}" env PATH="$PATH" "${BUN_BIN}" install --production +fi -# 4. Install and enable systemd service -echo "[4/5] Installing systemd autostart service..." -CURRENT_USER=$(whoami) -PROJECT_DIR=$(pwd) -BUN_BIN=$(command -v bun || echo "$HOME/.bun/bin/bun") +if [ -f "${PROJECT_DIR}/dist/index.html" ]; then + echo ">>> Verified pre-built frontend in dist/! (Built locally on dev host)" +elif [ "$FORCE_BUILD" = true ]; then + echo ">>> [!] WARNING: Building production frontend bundle on Pi..." + sudo -u "${TARGET_USER}" env PATH="$PATH" "${BUN_BIN}" run build +else + echo "=========================================================================" + echo " ERROR: Pre-built frontend bundle missing (${PROJECT_DIR}/dist/index.html)" + echo "=========================================================================" + echo " Building the React/Vite frontend directly on Raspberry Pi can take" + echo " over 20 minutes and exhausts Pi memory." + echo "" + echo " Recommended: Build frontend on your laptop and deploy using:" + echo " bun run install:pi ${TARGET_USER}@$(hostname).local" + echo " (or: bun run deploy:pi ${TARGET_USER}@$(hostname).local)" + echo "" + echo " If you truly want to build directly on the Pi, rerun with:" + echo " $0 --force-build" + echo "=========================================================================" + exit 1 +fi +# 4. Systemd daemon installation +echo "[4/4] Configuring systemd autostart service..." SERVICE_FILE="/etc/systemd/system/speedcamera.service" sudo bash -c "cat > ${SERVICE_FILE}" < Reconfigured to Static IP 192.168.1.100/24" -echo " • Wireless (wlan0) -> Reconfigured as Standalone Hotspot 192.168.4.1" -echo "************************************************************************" -echo "" -read -p "Do you want to configure the dual-subnet network interfaces now? (y/N) " -n 1 -r -echo -if [[ $REPLY =~ ^[Yy]$ ]]; then - # Run dedicated network setup script - chmod +x scripts/setup-network.sh - ./scripts/setup-network.sh -else - echo "Skipping network interface reconfiguration." - echo "You can run network setup anytime later via: ./scripts/setup-network.sh" +# Step 5: Network Mode Transition +if [ "$AUTO_FIELD" = true ]; then + echo "[*] Switching directly to Standalone Field Mode..." + chmod +x "${PROJECT_DIR}/scripts/setup-network.sh" + "${PROJECT_DIR}/scripts/setup-network.sh" field + exit 0 fi -echo "" -echo "=========================================================" -echo " Speedcamera setup finished!" -echo " Web UI access:" -echo " • Hotspot AP: http://192.168.4.1:3000 (SSID: speedcamera)" -echo " • Camera LAN: http://192.168.1.100:3000" -echo " • Local: http://localhost:3000" -echo "=========================================================" +if [ "$SKIP_NETWORK" = true ]; then + echo "Keeping current network configuration (--skip-network / --lan)." + echo "When ready for field deployment, run:" + echo " ~/speedcamera/headless/scripts/setup-network.sh field" + exit 0 +fi + +# If running in interactive terminal, prompt user +if [ -t 0 ]; then + echo "" + echo "=========================================================================" + echo " FIELD NETWORK CONFIGURATION (Camera LAN + Hotspot AP)" + echo "=========================================================================" + echo " Ready to switch Pi into Standalone Field Mode:" + echo " • Ethernet (eth0) -> Static IP 192.168.1.100 (GigE Camera LAN)" + echo " • Wi-Fi (wlan0) -> Standalone Hotspot AP 192.168.4.1 (SSID: speedcamera)" + echo "" + echo " WARNING: This will disconnect current Wi-Fi/SSH internet connection!" + echo "=========================================================================" + read -p "Switch to Standalone Field Mode now? (y/N) " -n 1 -r + echo "" + + if [[ $REPLY =~ ^[Yy]$ ]]; then + chmod +x "${PROJECT_DIR}/scripts/setup-network.sh" + "${PROJECT_DIR}/scripts/setup-network.sh" field + else + echo "Skipping Field Mode network switch for now." + echo "Run anytime later: ~/speedcamera/headless/scripts/setup-network.sh field" + fi +else + echo "Non-interactive session: Keeping existing network configuration." + echo "Switch to field mode when ready: ~/speedcamera/headless/scripts/setup-network.sh field" +fi diff --git a/headless/scripts/setup-network.sh b/headless/scripts/setup-network.sh index 616a6b7..5606552 100755 --- a/headless/scripts/setup-network.sh +++ b/headless/scripts/setup-network.sh @@ -1,67 +1,139 @@ #!/usr/bin/env bash set -e +MODE="${1:-status}" + echo "=========================================================" -echo " Speedcamera Network Configuration (Dual Subnet Setup)" -echo "=========================================================" -echo "" -echo " Architecture:" -echo " 1. Camera LAN (eth0) -> Static IP 192.168.1.100/24 (Subnet 192.168.1.0/24 for GigE camera)" -echo " 2. Hotspot AP (wlan0) -> Static IP 192.168.4.1/24 (Subnet 192.168.4.0/24 for Web UI clients)" +echo " Speedcamera Network Manager" echo "=========================================================" -# Detect Ethernet Interface (eth0, end0, etc.) +# 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, etc.) +# 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 AP): ${WIFI_IFACE}" +echo " Ethernet (Camera LAN): ${ETH_IFACE}" +echo " Wireless (Hotspot/Wi-Fi): ${WIFI_IFACE}" echo "" -# 1. Configure Ethernet Camera LAN (192.168.1.100/24) -echo "[1/2] Configuring Camera LAN on ${ETH_IFACE}..." -echo " Setting static IPv4: 192.168.1.100/24 (Camera subnet)..." +# For modifying operations, request sudo privileges +if [ "$MODE" != "status" ]; then + sudo -v || { echo "Error: Sudo privileges required to change network configuration." >&2; exit 1; } +fi -sudo nmcli connection delete "Speedcamera-CameraLAN" 2>/dev/null || true +case "$MODE" in + field|ap) + echo ">>> Applying FIELD MODE (Standalone Offline Dual-Subnet):" + echo " 1. Camera LAN (${ETH_IFACE}) -> Static IP 192.168.1.100/24" + echo " 2. Hotspot AP (${WIFI_IFACE}) -> Static IP 192.168.4.1/24 (SSID: speedcamera)" + echo " NOTE: In this mode, Pi operates standalone/offline." + echo "" -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 + # Configure Ethernet Camera LAN + echo "[1/2] Configuring Camera LAN on ${ETH_IFACE}..." + sudo nmcli connection delete "Speedcamera-CameraLAN" 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 + sudo nmcli connection up "Speedcamera-CameraLAN" 2>/dev/null || echo "Note: Ethernet link active when camera cable is connected." -sudo nmcli connection up "Speedcamera-CameraLAN" || echo "Note: Ethernet link will come up when camera cable is connected." + # Configure Wi-Fi Hotspot AP + echo "[2/2] Configuring Wi-Fi Hotspot AP on ${WIFI_IFACE}..." + SSID="speedcamera" + PASS="speedcamerapass" + sudo nmcli connection delete "Speedcamera-Hotspot" 2>/dev/null || true + sudo nmcli connection delete "Speedcamera-ClientWiFi" 2>/dev/null || true + sudo nmcli connection add type wifi \ + ifname "${WIFI_IFACE}" \ + con-name "Speedcamera-Hotspot" \ + autoconnect yes \ + ssid "${SSID}" \ + mode ap \ + 802-11-wireless.band bg \ + ipv4.method shared \ + ipv4.addresses 192.168.4.1/24 \ + wifi-sec.key-mgmt wpa-psk \ + wifi-sec.psk "${PASS}" + sudo nmcli connection up "Speedcamera-Hotspot" 2>/dev/null || echo "Note: Hotspot initialized." -# 2. Configure Wi-Fi Hotspot AP (192.168.4.1/24) -echo "" -echo "[2/2] Configuring Wi-Fi Hotspot AP on ${WIFI_IFACE}..." -SSID="speedcamera" -PASS="speedcamerapass" - -sudo nmcli connection delete "Speedcamera-Hotspot" 2>/dev/null || true - -sudo nmcli connection add type wifi \ - ifname "${WIFI_IFACE}" \ - con-name "Speedcamera-Hotspot" \ - autoconnect yes \ - ssid "${SSID}" \ - mode ap \ - 802-11-wireless.band bg \ - ipv4.method shared \ - ipv4.addresses 192.168.4.1/24 \ - wifi-sec.key-mgmt wpa-psk \ - wifi-sec.psk "${PASS}" - -sudo nmcli connection up "Speedcamera-Hotspot" || echo "Note: Run 'sudo nmcli connection up Speedcamera-Hotspot' once wireless interface is ready." + echo "" + echo "=========================================================" + echo " Field Mode Active!" + echo " • Wi-Fi Hotspot: SSID '${SSID}' (Password: '${PASS}')" + echo " • Web UI: http://192.168.4.1:3000" + echo " • Camera LAN: http://192.168.1.100:3000" + echo "=========================================================" + ;; -echo "" -echo "=========================================================" -echo " Network setup complete!" -echo " • Industrial Camera LAN: ${ETH_IFACE} @ 192.168.1.100" -echo " • Wi-Fi Access Point: ${WIFI_IFACE} @ 192.168.4.1 (SSID: ${SSID})" -echo " • Web UI Accessible at: http://192.168.4.1:3000" -echo "=========================================================" + internet|client|wifi) + WIFI_SSID="$2" + WIFI_PASS="$3" + if [ -z "$WIFI_SSID" ]; then + echo "Usage: $0 internet [Wi-Fi-Password]" + echo "Example: $0 internet MyHomeWiFi SecretPassword123" + exit 1 + fi + echo ">>> Switching to INTERNET / CLIENT MODE (for updates/provisioning)..." + echo " Connecting ${WIFI_IFACE} to Wi-Fi SSID: ${WIFI_SSID}" + + sudo nmcli connection delete "Speedcamera-Hotspot" 2>/dev/null || true + sudo nmcli connection delete "Speedcamera-ClientWiFi" 2>/dev/null || true + + if [ -n "$WIFI_PASS" ]; then + sudo nmcli dev wifi connect "${WIFI_SSID}" password "${WIFI_PASS}" ifname "${WIFI_IFACE}" name "Speedcamera-ClientWiFi" + else + sudo nmcli dev wifi connect "${WIFI_SSID}" ifname "${WIFI_IFACE}" name "Speedcamera-ClientWiFi" + fi + + echo "" + echo ">>> Checking internet connectivity..." + if ping -c 2 -W 3 1.1.1.1 &>/dev/null; then + echo " Connected to Internet successfully!" + else + echo " Wi-Fi connected, but ping to 1.1.1.1 failed. Check gateway/DNS." + fi + ;; + + dhcp|reset) + echo ">>> Reverting Ethernet and Wi-Fi to standard DHCP..." + 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 + 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 + echo "Interfaces set to standard DHCP." + ;; + + status) + echo "--- Active Network Connections ---" + nmcli connection show --active || true + echo "" + echo "--- IP Addresses ---" + ip -br addr show || true + 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 field mode or no route)" + fi + ;; + + *) + echo "Usage: $0 {field|internet|dhcp|status}" + echo "" + echo "Commands:" + echo " field Set Camera LAN (192.168.1.100) + Hotspot AP (192.168.4.1) [Offline]" + echo " internet [PASS] Connect Wi-Fi to home/lab router for updates [Online]" + echo " dhcp Reset ethernet & Wi-Fi to standard DHCP" + echo " status Check current IP addresses and connectivity" + exit 1 + ;; +esac diff --git a/headless/scripts/speedcamera.service b/headless/scripts/speedcamera.service index 08c1b02..094723f 100644 --- a/headless/scripts/speedcamera.service +++ b/headless/scripts/speedcamera.service @@ -11,7 +11,8 @@ Environment=NODE_ENV=production Environment=PORT=3000 Environment=HOST=0.0.0.0 Environment=DATA_DIR=/home/pi/.speedcamera -ExecStart=/home/pi/.bun/bin/bun src/server/index.ts +Environment=PATH=/home/pi/.bun/bin:/usr/local/bin:/usr/bin:/bin +ExecStart=/home/pi/.bun/bin/bun /home/pi/speedcamera/headless/src/server/index.ts Restart=always RestartSec=3 KillSignal=SIGINT diff --git a/headless/scripts/update-pi.sh b/headless/scripts/update-pi.sh new file mode 100755 index 0000000..eb2fd59 --- /dev/null +++ b/headless/scripts/update-pi.sh @@ -0,0 +1,89 @@ +#!/usr/bin/env bash +set -e + +FORCE_INSTALL=false + +for arg in "$@"; do + case "$arg" in + --install|-i) + FORCE_INSTALL=true + ;; + esac +done + +TARGET_USER="${SUDO_USER:-$(whoami)}" +TARGET_HOME=$(getent passwd "$TARGET_USER" | cut -d: -f6) +export PATH="${TARGET_HOME}/.bun/bin:/usr/local/bin:/usr/bin:$PATH" +PROJECT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "${PROJECT_DIR}" + +# 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 configure services." >&2; exit 1; } + +# Check internet availability +HAS_NET=false +if ping -c 1 -W 2 1.1.1.1 &>/dev/null; then + HAS_NET=true +fi + +BUN_BIN=$(command -v bun || echo "${TARGET_HOME}/.bun/bin/bun") + +if [ "${FORCE_INSTALL}" = true ]; then + echo "[*] Force install requested: running bun install..." + sudo -u "${TARGET_USER}" env PATH="$PATH" "${BUN_BIN}" install --production +elif [ ! -d "node_modules" ]; then + if [ "$HAS_NET" = true ]; then + echo "[*] Initial dependencies missing: running bun install..." + sudo -u "${TARGET_USER}" env PATH="$PATH" "${BUN_BIN}" install --production + else + echo ">>> WARNING: node_modules missing and Pi has no internet access." + echo ">>> Connect Pi to home Wi-Fi to install dependencies: ./scripts/setup-network.sh internet " + fi +elif [ "$HAS_NET" = true ]; then + if [ "package.json" -nt "node_modules" ]; then + echo "[*] package.json updated: updating production dependencies..." + sudo -u "${TARGET_USER}" env PATH="$PATH" "${BUN_BIN}" install --production + fi +else + echo "[*] Pi in offline mode: skipping package updates (existing dependencies reused)." +fi + +# 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 Headless Daemon & Web Server +After=network.target network-online.target +Wants=network-online.target + +[Service] +Type=simple +User=${TARGET_USER} +WorkingDirectory=${PROJECT_DIR} +Environment=NODE_ENV=production +Environment=PORT=3000 +Environment=HOST=0.0.0.0 +Environment=DATA_DIR=${TARGET_HOME}/.speedcamera +Environment=PATH=${TARGET_HOME}/.bun/bin:/usr/local/bin:/usr/bin:/bin +ExecStart=${BUN_BIN} ${PROJECT_DIR}/src/server/index.ts +Restart=always +RestartSec=3 +KillSignal=SIGINT +LimitNOFILE=65536 + +[Install] +WantedBy=multi-user.target +SERVICE_EOF + sudo systemctl daemon-reload + sudo systemctl enable speedcamera.service +fi + +echo "[*] Restarting speedcamera service..." +sudo systemctl daemon-reload +sudo systemctl restart speedcamera.service +sleep 1 +sudo systemctl status speedcamera --no-pager From 936c4ec43a6315f30433712bc87a9b9b9970ea5f Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Fri, 14 Aug 2026 17:41:33 +0200 Subject: [PATCH 06/65] feat: optimize camera streaming and network configuration for GigE Vision support --- electronbun/src/bun/industrial-camera.ts | 67 +++++++++++++++++++++--- headless/scripts/install-rpi.sh | 12 +++++ headless/scripts/setup-network.sh | 15 ++++++ headless/scripts/speedcamera.service | 1 + headless/src/bun-serialport.d.ts | 43 +++++++++++++++ headless/src/server/industrial-camera.ts | 66 ++++++++++++++++++++--- 6 files changed, 189 insertions(+), 15 deletions(-) create mode 100644 headless/src/bun-serialport.d.ts diff --git a/electronbun/src/bun/industrial-camera.ts b/electronbun/src/bun/industrial-camera.ts index 318dee2..808745b 100644 --- a/electronbun/src/bun/industrial-camera.ts +++ b/electronbun/src/bun/industrial-camera.ts @@ -206,7 +206,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"); @@ -264,6 +272,12 @@ export async function startSetupStream(pushFrame: (base64: string) => void) { 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 +298,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 +337,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)); } } } @@ -350,6 +389,18 @@ export function stopSetupStream() { try { camera.setExposureTime(Number(settings.cameraExposure) || 5000); } catch { /* ignore */ } } + // Restore configured frame rate + if (settings.frameRate) { + try { + camera.setBooleanFeature("AcquisitionFrameRateEnable", true); + camera.setFrameRate(Number(settings.frameRate)); + } catch { /* ignore */ } + } else { + try { + camera.setBooleanFeature("AcquisitionFrameRateEnable", false); + } catch { /* ignore */ } + } + try { stream.startAcquisition(); } catch { /* ignore */ } } diff --git a/headless/scripts/install-rpi.sh b/headless/scripts/install-rpi.sh index 875d85a..133d217 100755 --- a/headless/scripts/install-rpi.sh +++ b/headless/scripts/install-rpi.sh @@ -87,6 +87,17 @@ else echo "[1/4] Skipping apt package updates (offline mode)." fi +# Apply GigE Vision socket buffer tuning (64MB) +echo "[*] Configuring Linux socket buffers for GigE camera..." +sudo bash -c 'cat > /etc/sysctl.d/60-gige-camera.conf </dev/null || sudo sysctl --system 2>/dev/null || true + # 2. Check/Install Bun runtime BUN_BIN=$(command -v bun || echo "${TARGET_HOME}/.bun/bin/bun") if [ ! -x "${BUN_BIN}" ] && ! command -v bun &> /dev/null; then @@ -158,6 +169,7 @@ Restart=always RestartSec=3 KillSignal=SIGINT LimitNOFILE=65536 +LimitMEMLOCK=infinity [Install] WantedBy=multi-user.target diff --git a/headless/scripts/setup-network.sh b/headless/scripts/setup-network.sh index 5606552..a253544 100755 --- a/headless/scripts/setup-network.sh +++ b/headless/scripts/setup-network.sh @@ -30,6 +30,17 @@ case "$MODE" in echo " NOTE: In this mode, Pi operates standalone/offline." echo "" + # Apply GigE Vision kernel socket buffer optimizations + echo "[*] Applying GigE Vision network socket buffer optimizations (64MB)..." + sudo bash -c 'cat > /etc/sysctl.d/60-gige-camera.conf </dev/null || sudo sysctl --system 2>/dev/null || true + # Configure Ethernet Camera LAN echo "[1/2] Configuring Camera LAN on ${ETH_IFACE}..." sudo nmcli connection delete "Speedcamera-CameraLAN" 2>/dev/null || true @@ -61,6 +72,10 @@ case "$MODE" in wifi-sec.psk "${PASS}" sudo nmcli connection up "Speedcamera-Hotspot" 2>/dev/null || echo "Note: Hotspot initialized." + # Disable Wi-Fi power saving on AP interface to eliminate latency spikes and disconnects + echo "[*] Disabling Wi-Fi power saving on ${WIFI_IFACE}..." + sudo iw dev "${WIFI_IFACE}" set power_save off 2>/dev/null || sudo iwconfig "${WIFI_IFACE}" power off 2>/dev/null || true + echo "" echo "=========================================================" echo " Field Mode Active!" diff --git a/headless/scripts/speedcamera.service b/headless/scripts/speedcamera.service index 094723f..efd663d 100644 --- a/headless/scripts/speedcamera.service +++ b/headless/scripts/speedcamera.service @@ -17,6 +17,7 @@ Restart=always RestartSec=3 KillSignal=SIGINT LimitNOFILE=65536 +LimitMEMLOCK=infinity [Install] WantedBy=multi-user.target diff --git a/headless/src/bun-serialport.d.ts b/headless/src/bun-serialport.d.ts new file mode 100644 index 0000000..07e454f --- /dev/null +++ b/headless/src/bun-serialport.d.ts @@ -0,0 +1,43 @@ +declare module "bun-serialport" { + export interface PortInfo { + path: string; + manufacturer?: string; + serialNumber?: string; + pnpId?: string; + locationId?: string; + productId?: string; + vendorId?: string; + } + + export interface SerialPortOptions { + path: string; + baudRate?: number; + dataBits?: 5 | 6 | 7 | 8; + stopBits?: 1 | 2; + parity?: "none" | "even" | "mark" | "odd" | "space"; + autoOpen?: boolean; + } + + export class SerialPort { + constructor(options: SerialPortOptions); + readonly isOpen: boolean; + readonly path: string; + readonly baudRate: number; + open(): Promise; + close(): Promise; + write(data: string | Uint8Array | Buffer): Promise; + flush(): Promise; + drain(): Promise; + pipe(destination: T): T; + on(event: "data", listener: (chunk: Buffer) => void): this; + on(event: "error", listener: (error: Error) => void): this; + on(event: "close", listener: () => void): this; + on(event: "open", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + off(event: string, listener: (...args: any[]) => void): this; + removeAllListeners(event?: string): this; + } + + export function list(): Promise; + export function readlineParser(options?: { delimiter?: string | Buffer | Uint8Array; encoding?: BufferEncoding }): any; +} diff --git a/headless/src/server/industrial-camera.ts b/headless/src/server/industrial-camera.ts index 143c8ac..39b9e41 100644 --- a/headless/src/server/industrial-camera.ts +++ b/headless/src/server/industrial-camera.ts @@ -204,7 +204,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"); @@ -262,6 +270,12 @@ export async function startSetupStream(pushFrame: (base64: string) => void) { 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 */ } + try { camera.setBooleanFeature("StrobeEnable", false); } catch { try { camera.setIntegerFeature("StrobeEnable", 0); } catch { /* ignore */ } } @@ -281,15 +295,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; @@ -303,11 +332,22 @@ async function pumpSetupFrames(pushFrame: (base64: string) => void) { sharpInst = sharp(data, { raw: { width: w, height: h, channels: 1 } }); } - 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)); } } } @@ -342,6 +382,18 @@ export function stopSetupStream() { try { camera.setExposureTime(Number(settings.cameraExposure) || 5000); } catch { /* ignore */ } } + // Restore configured frame rate + if (settings.frameRate) { + try { + camera.setBooleanFeature("AcquisitionFrameRateEnable", true); + camera.setFrameRate(Number(settings.frameRate)); + } catch { /* ignore */ } + } else { + try { + camera.setBooleanFeature("AcquisitionFrameRateEnable", false); + } catch { /* ignore */ } + } + try { stream.startAcquisition(); } catch { /* ignore */ } } From de7fac923ccb3e73fd25c5f0aac4b8e87236144e Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Fri, 14 Aug 2026 22:40:09 +0200 Subject: [PATCH 07/65] feat: add rust only impl --- headless-rust/.cargo/config.toml | 2 + headless-rust/.gitignore | 28 + headless-rust/Cargo.lock | 4050 +++++++++++++++++++++ headless-rust/Cargo.toml | 29 + headless-rust/README.md | 124 + headless-rust/build.rs | 24 + headless-rust/resources/font.ttf | Bin 0 -> 197004 bytes headless-rust/scripts/speedcamera.service | 21 + headless-rust/src/camera/ffi.rs | 114 + headless-rust/src/camera/mock.rs | 91 + headless-rust/src/camera/mod.rs | 644 ++++ headless-rust/src/config.rs | 51 + headless-rust/src/db/laps.rs | 181 + headless-rust/src/db/mod.rs | 78 + headless-rust/src/db/settings.rs | 103 + headless-rust/src/db/violations.rs | 188 + headless-rust/src/integrations/flasher.rs | 206 ++ headless-rust/src/integrations/mod.rs | 2 + headless-rust/src/integrations/teable.rs | 201 + headless-rust/src/main.rs | 110 + headless-rust/src/models.rs | 368 ++ headless-rust/src/network/mod.rs | 111 + headless-rust/src/serial/mock.rs | 65 + headless-rust/src/serial/mod.rs | 198 + headless-rust/src/serial/protocol.rs | 98 + headless-rust/src/storage/mod.rs | 73 + headless-rust/src/storage/skin.rs | 85 + headless-rust/src/web/embedded.rs | 52 + headless-rust/src/web/mod.rs | 51 + headless-rust/src/web/routes.rs | 78 + headless-rust/src/web/rpc.rs | 507 +++ headless-rust/src/web/ws.rs | 132 + 32 files changed, 8065 insertions(+) create mode 100644 headless-rust/.cargo/config.toml create mode 100644 headless-rust/.gitignore create mode 100644 headless-rust/Cargo.lock create mode 100644 headless-rust/Cargo.toml create mode 100644 headless-rust/README.md create mode 100644 headless-rust/build.rs create mode 100755 headless-rust/resources/font.ttf create mode 100644 headless-rust/scripts/speedcamera.service create mode 100644 headless-rust/src/camera/ffi.rs create mode 100644 headless-rust/src/camera/mock.rs create mode 100644 headless-rust/src/camera/mod.rs create mode 100644 headless-rust/src/config.rs create mode 100644 headless-rust/src/db/laps.rs create mode 100644 headless-rust/src/db/mod.rs create mode 100644 headless-rust/src/db/settings.rs create mode 100644 headless-rust/src/db/violations.rs create mode 100644 headless-rust/src/integrations/flasher.rs create mode 100644 headless-rust/src/integrations/mod.rs create mode 100644 headless-rust/src/integrations/teable.rs create mode 100644 headless-rust/src/main.rs create mode 100644 headless-rust/src/models.rs create mode 100644 headless-rust/src/network/mod.rs create mode 100644 headless-rust/src/serial/mock.rs create mode 100644 headless-rust/src/serial/mod.rs create mode 100644 headless-rust/src/serial/protocol.rs create mode 100644 headless-rust/src/storage/mod.rs create mode 100644 headless-rust/src/storage/skin.rs create mode 100644 headless-rust/src/web/embedded.rs create mode 100644 headless-rust/src/web/mod.rs create mode 100644 headless-rust/src/web/routes.rs create mode 100644 headless-rust/src/web/rpc.rs create mode 100644 headless-rust/src/web/ws.rs diff --git a/headless-rust/.cargo/config.toml b/headless-rust/.cargo/config.toml new file mode 100644 index 0000000..ff7f758 --- /dev/null +++ b/headless-rust/.cargo/config.toml @@ -0,0 +1,2 @@ +[target.aarch64-unknown-linux-gnu] +linker = "aarch64-linux-gnu-gcc" \ No newline at end of file diff --git a/headless-rust/.gitignore b/headless-rust/.gitignore new file mode 100644 index 0000000..84593dd --- /dev/null +++ b/headless-rust/.gitignore @@ -0,0 +1,28 @@ +# Generated by Cargo +# will have compiled files and executables +/target/ + +# 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..75227b9 --- /dev/null +++ b/headless-rust/Cargo.lock @@ -0,0 +1,4050 @@ +# 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" + +[[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 = "async-stream" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5a71a6f37880a80d1d7f19efd781e4b5de42c88f0722cc13bcb6cc2cfe8476" +dependencies = [ + "async-stream-impl", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-stream-impl" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[package]] +name = "atomic" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c59bdb34bc650a32731b31bd8f0829cc15d24a708ee31559e0bb34f2bc320cba" + +[[package]] +name = "atomic" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89cbf775b137e9b968e67227ef7f775587cde3fd31b0d8599dbd0f598a48340" +dependencies = [ + "bytemuck", +] + +[[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 2.0.20", + "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 = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "binascii" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "383d29d513d8764dcdc42ea295d979eb99c3c9f00607b3692cf68a431f7dca72" + +[[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" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[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" + +[[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 = "cookie" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a373e3602691c3cdea496d2f0ee5935151e6168fe87739483c463db1b2f2f87" +dependencies = [ + "percent-encoding", + "time", + "version_check", +] + +[[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-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 = "devise" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1d90b0c4c777a2cad215e3c7be59ac7c15adf45cf76317009b7d096d46f651d" +dependencies = [ + "devise_codegen", + "devise_core", +] + +[[package]] +name = "devise_codegen" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71b28680d8be17a570a2334922518be6adc3f58ecc880cbb404eaeb8624fd867" +dependencies = [ + "devise_core", + "quote", +] + +[[package]] +name = "devise_core" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b035a542cf7abf01f2e3c4d5a7acbaebfefe120ae4efc7bde3df98186e4b8af7" +dependencies = [ + "bitflags 2.13.1", + "proc-macro2", + "proc-macro2-diagnostics", + "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 = "either" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e5e8f6c15a24b9a3ee5efec809ccd006d3b30e8b3bb63c39af737c7f87daa1d" + +[[package]] +name = "encoding_rs" +version = "0.8.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3" +dependencies = [ + "cfg-if", +] + +[[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 = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[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 = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[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 = "figment" +version = "0.10.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8cb01cd46b0cf372153850f4c6c272d9cbea2da513e07538405148f95bd789f3" +dependencies = [ + "atomic 0.6.1", + "pear", + "serde", + "toml", + "uncased", + "version_check", +] + +[[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 = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[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 = "generator" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5cc16584ff22b460a382b7feec54b23d2908d858152e5739a120b949293bd74e" +dependencies = [ + "cc", + "libc", + "log", + "rustversion", + "windows", +] + +[[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 = "glob" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + +[[package]] +name = "h2" +version = "0.3.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0beca50380b1fc32983fc1cb4587bfa4bb9e78fc259aad4a0032d2080309222d" +dependencies = [ + "bytes", + "fnv", + "futures-core", + "futures-sink", + "futures-util", + "http 0.2.12", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[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 = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "hashlink" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af" +dependencies = [ + "hashbrown 0.14.5", +] + +[[package]] +name = "headless-rust" +version = "0.1.0" +dependencies = [ + "ab_glyph", + "base64", + "chrono", + "clap", + "futures", + "image", + "imageproc", + "mime_guess", + "nix 0.29.0", + "pkg-config", + "reqwest", + "rocket", + "rocket_ws", + "rusqlite", + "rust-embed", + "serde", + "serde_json", + "serialport", + "tokio", + "tokio-stream", + "url", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hermit-abi" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c" + +[[package]] +name = "http" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "601cbb57e577e2f5ef5be8e7b83f0f63994f25aa94d673e54a92d5c516d101f1" +dependencies = [ + "bytes", + "fnv", + "itoa", +] + +[[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 = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ceab25649e9960c0311ea418d17bee82c0dcec1bd053b5f9a66e265a693bed2" +dependencies = [ + "bytes", + "http 0.2.12", + "pin-project-lite", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http 1.5.0", +] + +[[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 1.5.0", + "http-body 1.1.0", + "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 = "0.14.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41dfc780fdec9373c01bae43289ea34c972e40ee3c9f6b3c8801a35f35586ce7" +dependencies = [ + "bytes", + "futures-channel", + "futures-core", + "futures-util", + "h2", + "http 0.2.12", + "http-body 0.4.6", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "socket2 0.5.10", + "tokio", + "tower-service", + "tracing", + "want", +] + +[[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 1.5.0", + "http-body 1.1.0", + "httparse", + "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 1.5.0", + "hyper 1.11.0", + "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 1.5.0", + "http-body 1.1.0", + "hyper 1.11.0", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2 0.6.5", + "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 = "indexmap" +version = "2.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", + "serde", + "serde_core", +] + +[[package]] +name = "inlinable_string" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8fae54786f62fb2918dcfae3d568594e50eb9b5c25bf04371af6fe7516452fb" + +[[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" +version = "0.4.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46" +dependencies = [ + "hermit-abi", + "libc", + "windows-sys 0.61.2", +] + +[[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 = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[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 = "loom" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff50ecb28bb86013e935fb6683ab1f6d3a20016f123c76fd4c27470076ac30f5" +dependencies = [ + "cfg-if", + "generator", + "scoped-tls", + "serde", + "serde_json", + "tracing", + "tracing-subscriber", +] + +[[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 = "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 = "multer" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83e87776546dc87511aa5ee218730c92b666d7264ab6ed41f9d215af9cd5224b" +dependencies = [ + "bytes", + "encoding_rs", + "futures-util", + "http 1.5.0", + "httparse", + "memchr", + "mime", + "spin", + "tokio", + "tokio-util", + "version_check", +] + +[[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 = "num_cpus" +version = "1.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b" +dependencies = [ + "hermit-abi", + "libc", +] + +[[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 = "pear" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdeeaa00ce488657faba8ebf44ab9361f9365a97bd39ffb8a60663f57ff4b467" +dependencies = [ + "inlinable_string", + "pear_codegen", + "yansi", +] + +[[package]] +name = "pear_codegen" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bab5b985dc082b345f812b7df84e1bef27e7207b39e448439ba8bd69c93f147" +dependencies = [ + "proc-macro2", + "proc-macro2-diagnostics", + "quote", + "syn 2.0.119", +] + +[[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 = "proc-macro2-diagnostics" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "version_check", + "yansi", +] + +[[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 0.6.5", + "thiserror 2.0.20", + "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 2.0.20", + "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 0.6.5", + "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 2.0.20", + "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 = "ref-cast" +version = "1.0.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "216e8f773d7923bcba9ceb86a86c93cabb3903a11872fc3f138c49630e50b96d" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c9283685feec7d69af75fb0e858d5e7378f33fe4fc699383b2916ab9273e03c" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.3", +] + +[[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 1.5.0", + "http-body 1.1.0", + "http-body-util", + "hyper 1.11.0", + "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 = "rocket" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a516907296a31df7dc04310e7043b61d71954d703b603cc6867a026d7e72d73f" +dependencies = [ + "async-stream", + "async-trait", + "atomic 0.5.3", + "binascii", + "bytes", + "either", + "figment", + "futures", + "indexmap", + "log", + "memchr", + "multer", + "num_cpus", + "parking_lot", + "pin-project-lite", + "rand 0.8.7", + "ref-cast", + "rocket_codegen", + "rocket_http", + "serde", + "serde_json", + "state", + "tempfile", + "time", + "tokio", + "tokio-stream", + "tokio-util", + "ubyte", + "version_check", + "yansi", +] + +[[package]] +name = "rocket_codegen" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "575d32d7ec1a9770108c879fc7c47815a80073f96ca07ff9525a94fcede1dd46" +dependencies = [ + "devise", + "glob", + "indexmap", + "proc-macro2", + "quote", + "rocket_http", + "syn 2.0.119", + "unicode-xid", + "version_check", +] + +[[package]] +name = "rocket_http" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e274915a20ee3065f611c044bd63c40757396b6dbc057d6046aec27f14f882b9" +dependencies = [ + "cookie", + "either", + "futures", + "http 0.2.12", + "hyper 0.14.32", + "indexmap", + "log", + "memchr", + "pear", + "percent-encoding", + "pin-project-lite", + "ref-cast", + "serde", + "smallvec", + "stable-pattern", + "state", + "time", + "tokio", + "uncased", +] + +[[package]] +name = "rocket_ws" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25f1877668c937b701177c349f21383c556cd3bb4ba8fa1d07fa96ccb3a8782e" +dependencies = [ + "rocket", + "tokio-tungstenite", +] + +[[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 = "rustix" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +dependencies = [ + "bitflags 2.13.1", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[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 = "scoped-tls" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" + +[[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_spanned" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" +dependencies = [ + "serde", +] + +[[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" + +[[package]] +name = "socket2" +version = "0.5.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e22376abed350d73dd1cd119b57ffccad95b4e585a7cda43e286245ce23c0678" +dependencies = [ + "libc", + "windows-sys 0.52.0", +] + +[[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 = "spin" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" + +[[package]] +name = "stable-pattern" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4564168c00635f88eaed410d5efa8131afa8d8699a612c80c455a0ba05c21045" +dependencies = [ + "memchr", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "state" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b8c4a4445d81357df8b1a650d0d0d6fbbbfe99d064aa5e02f3e4022061476d8" +dependencies = [ + "loom", +] + +[[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 = "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 = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" +dependencies = [ + "thiserror-impl 2.0.20", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[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 0.6.5", + "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.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c83b561d025642014097b66e6c1bb422783339e0909e4429cde4749d1990bc38" +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", + "libc", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "toml" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" +dependencies = [ + "serde", + "serde_spanned", + "toml_datetime", + "toml_edit", +] + +[[package]] +name = "toml_datetime" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_edit" +version = "0.22.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" +dependencies = [ + "indexmap", + "serde", + "serde_spanned", + "toml_datetime", + "toml_write", + "winnow", +] + +[[package]] +name = "toml_write" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" + +[[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", +] + +[[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 1.5.0", + "http-body 1.1.0", + "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 = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[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.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ef1a641ea34f399a848dea702823bbecfb4c486f911735368f1f137cb8257e1" +dependencies = [ + "byteorder", + "bytes", + "data-encoding", + "http 1.5.0", + "httparse", + "log", + "rand 0.8.7", + "sha1", + "thiserror 1.0.69", + "url", + "utf-8", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "ubyte" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f720def6ce1ee2fc44d40ac9ed6d3a59c361c80a75a7aa8e75bb9baed31cf2ea" +dependencies = [ + "serde", +] + +[[package]] +name = "uncased" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1b88fcfe09e89d3866a5c11019378088af2d24c3fbd4f0543f96b479ec90697" +dependencies = [ + "serde", + "version_check", +] + +[[package]] +name = "unescaper" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7285e83a80ce76f5e7bce79fa41f68d78ba62d1003cf27bf748ab24413808cf4" +dependencies = [ + "thiserror 2.0.20", +] + +[[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 = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[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 = "utf-8" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" + +[[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" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e686886bc078bc1b0b600cac0147aadb815089b6e4da64016cbd754b6342700f" +dependencies = [ + "windows-targets 0.48.5", +] + +[[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 0.52.6", +] + +[[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.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" +dependencies = [ + "windows_aarch64_gnullvm 0.48.5", + "windows_aarch64_msvc 0.48.5", + "windows_i686_gnu 0.48.5", + "windows_i686_msvc 0.48.5", + "windows_x86_64_gnu 0.48.5", + "windows_x86_64_gnullvm 0.48.5", + "windows_x86_64_msvc 0.48.5", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" + +[[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.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" + +[[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.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" + +[[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.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" + +[[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.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" + +[[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.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" + +[[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.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" +dependencies = [ + "memchr", +] + +[[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 = "yansi" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" +dependencies = [ + "is-terminal", +] + +[[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..c9c11bc --- /dev/null +++ b/headless-rust/Cargo.toml @@ -0,0 +1,29 @@ +[package] +name = "headless-rust" +version = "0.1.0" +edition = "2024" + +[dependencies] +rocket = { version = "0.5.1", features = ["json"] } +rocket_ws = "0.1.1" +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"] } +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" + +[build-dependencies] +pkg-config = "0.3" diff --git a/headless-rust/README.md b/headless-rust/README.md new file mode 100644 index 0000000..df4de5e --- /dev/null +++ b/headless-rust/README.md @@ -0,0 +1,124 @@ +# Speedcamera Headless (Rust & Rocket) + +A high-performance, single-binary headless speedcamera daemon and web controller written in **Rust** using **Rocket 0.5**, **native Aravis C FFI**, **SQLite**, and 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 stability. + +--- + +## 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!)** | +| **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** | + +--- + +## Architecture + +``` +┌────────────────────────────────────────────────────────────────────────┐ +│ Raspberry Pi 5 (Raspberry Pi OS Lite ARM64) │ +│ │ +│ • eth0 (Camera LAN): 192.168.1.100/24 <── GigE Vision HIKROBOT │ +│ • wlan0 (Hotspot AP): 192.168.4.1/24 <── Web UI Browser Clients │ +│ │ +│ • speedcamera-rust Daemon (Single Binary) │ +│ ├── Rocket 0.5 HTTP Server (REST API & Embedded Static Frontend) │ +│ ├── Rocket WS (/ws/rpc JSON-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 │ +└───────────────────────┬─────────────────────────────▲──────────────────┘ + │ Wi-Fi AP │ Ethernet Cable + ▼ │ +┌──────────────────────────────────────────┐ ┌──────────────────────────┐ +│ Client Device (Phone / Tablet / Laptop) │ │ Industrial GigE Camera │ +│ │ │ │ +│ • Wi-Fi SSID: speedcamera │ │ • Subnet: 192.168.1.0/24 │ +│ • Open: http://192.168.4.1:3000 │ │ • GenICam / Aravis 0.8 │ +│ • Live Radar, Live View, Settings, Laps │ │ • Direct link to eth0 │ +└──────────────────────────────────────────┘ └──────────────────────────┘ +``` + +--- + +## Quick Start + +### 1. Local Development & Testing (Mock Mode) + +Run on your laptop without physical camera or Arduino hardware: + +```bash +cd headless-rust + +# Run in mock mode on port 3000 +cargo run -- --mock +``` + +- **Web UI:** `http://localhost:3000` +- **Health Check:** `http://localhost:3000/api/health` +- **Network Info:** `http://localhost:3000/api/network` +- **WebSocket RPC:** `ws://localhost:3000/ws/rpc` + +--- + +### 2. Building for Release + +```bash +# Build optimized release binary with embedded frontend +cargo build --release + +# The standalone binary is generated at: +# target/release/headless-rust +``` + +--- + +### 3. Deploying to Raspberry Pi 5 + +Copy the single executable and systemd unit to the Pi: + +```bash +# 1. Transfer binary to Pi +scp target/release/headless-rust pi@192.168.4.1:/home/pi/speedcamera/headless-rust/ + +# 2. Register systemd service +sudo cp scripts/speedcamera.service /etc/systemd/system/ +sudo systemctl daemon-reload +sudo systemctl enable speedcamera +sudo systemctl restart speedcamera +``` + +--- + +## CLI Options + +``` +Usage: headless-rust [OPTIONS] + +Options: + -m, --mock Run in mock hardware mode (no physical camera/serial required) + -p, --port HTTP server port (default: 3000) + -h, --help Print help +``` + +--- + +## System Requirements on Pi 5 + +Install runtime dependencies on Raspberry Pi OS: + +```bash +sudo apt-get update +sudo apt-get install -y libaravis-0.8-0 libaravis-dev libudev-dev +``` diff --git a/headless-rust/build.rs b/headless-rust/build.rs new file mode 100644 index 0000000..a3dc5ef --- /dev/null +++ b/headless-rust/build.rs @@ -0,0 +1,24 @@ +fn main() { + println!("cargo:rerun-if-changed=build.rs"); + + // Probe aravis-0.8 and gobject-2.0 via pkg-config + match pkg_config::Config::new().atleast_version("0.8.0").probe("aravis-0.8") { + Ok(lib) => { + 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); + } + } + Err(e) => { + println!("cargo:warning=pkg-config aravis-0.8 failed: {}. Trying fallback link.", e); + println!("cargo:rustc-link-lib=aravis-0.8"); + println!("cargo:rustc-link-lib=gobject-2.0"); + } + } + + // Always ensure standard library search and rpaths for common Aravis install directories + println!("cargo:rustc-link-arg=-Wl,-rpath,/usr/local/lib64:/usr/local/lib:/usr/lib64:/usr/lib"); +} diff --git a/headless-rust/resources/font.ttf b/headless-rust/resources/font.ttf new file mode 100755 index 0000000000000000000000000000000000000000..e0c576f1b02314a890f50d6fa096f0566f636153 GIT binary patch literal 197004 zcmdSC349J$`^SCG%$YlpP4+#L`_6J_l|(`iTM!X@L`v+TC@HF_s#;Q8HC0tx6;)Mj z6(vPAR25ZKRaH$@6;)ITMQ!b)B=7H-tJ{zgoS>4;W>-KZwXPI(g4P$}l+GVxPK2q`ZP8>hXm@=hZ zZrARW`(0-<<&|8&SrkewnZ6X)3!LAYku4SF`B6I-^czsO z*)3K_y?_+<(pbFS8;JcRZ3Ng8f)B19y9*7 z)TI>sJ(qd1B4#m#huER8=Wgs$dKC822h<{1rORPb&){R=PWjq!hZhNgZehkPfmzUoadb zf=ocinu09wFvtL{fgN-NF@Ua11>u0MsS5<~2A-fXXby5f8;}edfjrOvP|!l zHxf`fo$JtX*lq~wgBF0EN6(2iw<#Y~p8pY5_uyF*;~5USk?m?j`KS%qn(|4u{U`eW z#c{gNAFmZnH)I}WHm{S#Ez{tAZl_JGRS3Q!D??WulIefw{q zy8nM&S39p3obPA@s2!+H1okN}wV^iRKZShs$7`sK`3I^lpk5!xIg~fTW-8^k>wic* z&Zjo4HveQJH=IjtodZW6{zj{g;N03a`ggXe4*Wak{qY>i8@0LJO{MKYCMi&Ai~k8K zcOIbj`tP82{C|a`e{j?t(!Z+1wbTCCHaPalHV&VVk5PxJet=T@=13={IHS0B*pm7M z+8zZcE)_ucB>Pc1-HU8P+qK)7X4tQN->%pvf#OJJKfr9U~A+Ro9?&J=Jr% zH^o2@s9g`pp9Gyl^^fjJ?Kwg11oBmN3rh8zp5w4*7`Ca7IBbJ^8tuOm(ky_kZEI>1 zsKXv)E6U4%1NCA5&2@iuO*h=@zoDynokPjiG}a*djR0gH>L027C12VB9m@iBK?Wcj z5Oj>r=?Gc^y4KNFdSlzqOjBXosv78iw9j1S`NnoUw#nCY4f&A#(gPqyjhLf)NNqp) zn4U>-K>d0eZ~=5J*@^r{ex~CTQxr4)fUc!;$d>_to=4B1`#ah;x|gFK(>0V%`*bbE zI`VDA8r^p*C^NYLJpd@qz5>I*4R913G5HL-3D7x3V7RGcq4P|remw%{`lrB`;0y2_ zp!*hs$)?ir*G=j`DQ^V%klH-*AqPo->_s4+tA2-)4{5))|I)Ef{v+Fv56ORYPCcN5 zFhH?F_NV92xdeP$J+>p8(etT|AU`E84#f_zHtQa+$|gUU(yRRH<8y-8;% zn#Pw4(sE;{djb#58%y%m^hv?KemPYePNfp0)} zK<69)Xy=W3PutmG8`ubTfdoMLr*sFo*k-_?bf4K^JXi##gNdN`U+hmpS}!mc&^_qh zrhTd&#P+*j3ZVQB14Ups=m0L&Qt}<$hiC^VPA7ntz!}gzN$I@4z;Qo^E=1Ze@TsYe zbRX;!LuAZV{fcde@2ULxU{WpU{!_slfZ8A8nOeF8+jGn`YO_8Bm%&-^-(E-e+zXb2 z*TJi%u7bV;C@-tQQSb?HJnz4~?giYV7|aB;y%ekklr|f@2k02(=Ph%4C6s(gexYjlrOr^VlWR-owozBE7|WwK=-W;-Gkz40ib&jR8A_}G4Lj!I!0|oCTIi5Z`4*7 z0;-2y0i}lkU*HV-nA?<2b(7Aan4&f?(uB@!0K95J$Lao#v;cFP+DA%rsN?uQDLt2t zXPe}kT2?D<9JZs%|5lNviIe`a85Pjv@Z5PJmy)w@4%3BNnPEfFp0@XR;C5 zn{0FnYzAZ_sz(I1Wn?Ql_L#|O=n^xHj?w-oFcMJubg%|couK=^5B35)-?-OH&`p5u zxewd|bnj_^?nCyZ`z)%ZbkAb&444S$zDEE(bDX(N`;UVOfS$h{P##_dj{8$vN`5Av z&^_sXXTfKH%0c(|8ql>+9s#9iz5NF$jh;= zcmX)P#^~j2BO+!ZUmD)5I5B5D-G#X_ zH|EYfSY5nv@nYW0hxsx;=Fb9HAPZu_EQE!!Fm;Q%U42(fRyT-mna;xTro_e~@TMe+ zMKe2#VX-WZ#j^yK$m+2qmdsLEeU{47SOeCOrL#urR&|^Do|uXIALHZr>wGnTgRfCP5VJ%(k)?j9 zu2gsNWoo&4MEzPE7iYy3)|I_4W{OE-qIgoY6(!MX60HD*oO8|(xAth!8Hu0F5MQ=e1kigDr)|A^fXy+pRUP+erP zSe(?I>MQCC>U`0UWw3#)344$YU{A4WYz8Z4tJ&));cM(`c9fO#p5i-kMw}BriVNbr zxF~)S72*UF9;JBSREA)1Vr4kn9oEW(J*Kb^*_Z5l_6slOCH#55fWOL1`5u0PpXERC zOZ*nEQbLqQN*kpc-hlO0hABnLC}q6zq%uXBq0CnnDK9CnD65p!%9~25vRT=t>`*>b zb}I*!FO^fuIn_<|QLSpcnyA)S8>r3I)@oaI0HWnFb)q^2R+)n`zpAcNOVvHwr6aMY%kf?*uIKj5o&}bqHctDgkMB(M0iA8L_$QP zh@6Ol5kn%CNY6-H^sCY9qqj%zjouf1F#3z=Z==uKz3hJWX7)^bYkQ&nLHkhq!!bTF zc`<`yeo6{Viax#S^yc4{$|}5@r9bYd1u3i*qF^Q4#g4Gk?7HE(`Fthc2+w`a&+zlS zg5Tu7DS?LPa+N%#m(m}edsulynV?Koij}98g~}3Tx$-JJ_Xa$-NqJ9sU)c%I?Nbgb z$CT45Q|qdMY9u_D1kW|8_S`tbb2H$%xroTu)b;8+>PPC~`#i^lr$`Zl#27J8EEX%p zTCqWF72Cxw@r5Wybe9~W=y`g9K0=?O&xPk! zhJO(LdHBijpTqANp7XX^;kjgMDm>T3+6C)f1;W=J)%kbWPe^r)OJ!&TOx$gk0T3T5b?~G?u z&BEU^tDdf!4Q63$deuxivua}1n5sv)akb*F_$j^sZ2@)@Z0=4|Aimp z-{8%6a#bW_l|O=y9A{SUtbD)nERl`2y$78y3XH#vZQ64D z5xqs!v0oezhs9BG8ujafxGrvr z+v1L>)SNXJ%~SKnFoE!u$ZIHF3)OVZswHWeS`V#28>NlYkP~gbCCk#ul55Gg80E3_ zu;9xL%V>F>1z&VnMq9?=Z(ybw$LK8jV<|Fqm{g<;GE)lgPqAR%Qs_8}ZPQAY0?Qz$ z)lO@i%Ft<{#7+m~b+m16?Qv|G`&*s1JMD6!)c;?PSF}Qm7BJdCT(wo-S3eYI)gvN6 zT`ZnbUsB7_x6cxj)F0F{7=M(gyVO_2MfJ1@QePDP(O(v-B^XyU!8oC*G3x1xanAts z^aC+wC^p9ol^6%TW{ex&U~h`C?0r^lj2@1$Usx4ihS8A)<0EH`klZkOv0;3aXpE3L zVT?p0q(c}ZJ&IA%Sd5S!6XW zdh#gNi`!X09?u5z6gGs{XG3`!dx)p9K|G0#;Vsx$-ja>und~v%icREg*;L+%X_fdygQr4dvb*zVRLu^dyed;`0}ccS;*!)~zO@D0`-et`Xpf6ABhaFN5F zU|aZf_9K6nwc;M^X`aW{@d@lCf17>JH?q^bl>NZpVQ2Uz){X0IJa5g`^C#G&yg6IW zhqFxX&T@Ge+rdlN0ltJC=CAOt`ALk*&ha17zyHK9@Qdi>FY(L#ilXyV{AYd*E&Xi~ zDH724rlKW~Bftvuw?BzvqKSwWiK4#95SKA-lC8sUM*F}tMY9;Kgu5oRx|)~fgBBqi zZGugU)S|T*Ef!;hHOdH#^G0Iy_lPn^8K*2&hA2aohcF@>Zj3BOD`S-xFd|%lk;O9Q zF^mx($5`VDWg^CklQ8C(qD;lO<0)mDG94qwnaXp@EQ~^CE6*q;%CpKGj3k#Rim8uG&tyr{*Y?YI~(h?SPR=N0qCc zR7LHqs%jT}hoz}q)m+u0c2k|yJk?q4uGUfWRTuRE)m80*F=O)LtS)grOym z5_SWL)Qom*LN9>eGyiSr+$VZMiqg z=02<)_hmWUkG1FitOE~V9eE(@#DiF89?ZJ%5H^fAV8eMsR>afU!@Ln2!5g!Yya^k{ zGuR`%DSL+Jvl9LQdz(*W8~BrKBcH@d`DFGEpTairscbVZX7A$LzO8&FdymgzW&CNj zjn8Ih`DS*GZ(-;8R`wHrk6qwp>>}UBD)@GGjqhT&_{Z!v-^YICpD62;waR*BE9M0> z#@wR3gE_*x7;Ba(8~4%x8tVTir-=AB-p$81ta{>Iazfth5Nx4>N;(m>JKPsC}*-(!S6RYhP+dw6C;s?Q89*_KkK-`&K)yeW#t!PHLyL@3qs~ z584^+taeWOQ9G~wq+QT1Y8Bcg?Xvc>c163YUDJNiu4^~6o7yeyw)U&`oAxj5j`q8D zSG%WGYWR@R!YztL#hh%tx(c&^x5Y+Ls;*XF7w?Eo>Kp2tn5k_RThuk`TjE`@Rb8vD z6J?kI9Ku}SlDb}O6MMzS;&aRh_E?-Pbu2CxSBsm)-Qq#BU5kd*0sM(FMjq(QjS&~6 z;17+-+)Wgy)kKBbBr3*&SSK)0=RhMR>bKA+iD(0jmKftQJGOyZ2#t}b&q8BC9MUmf z#9D)ax&xXZ5i|x*l&I68^(5*NXp%&o2BncOP%)ap{EeZ9X6is_255@y8PH}DF#+0K zBE~~oNW>G+mJ;UL;9iTW-Sqh3Nxh7ORZ8=!>} zthg|Y85o-gbnv7^-3px~QMWS4l)W=xY*@1zjx> zt)Z_=L|f<^67_xPn-cXy=o*PQ3w=wX9)Yfvhydt1iMklNULu}?zAaH-f>N1*S`OVP z5$B*-FCoM%D87Lv1eKfOU^CAD0ZR4-;y9FS3TTwh$VNcj1tq%x^%W@j9*B!jvK>%Q zL&-Nl1VO2sKz$Lq1MEaP{DgHH1B~t%+XeQ5#^7UP_h@`WJ@X=z-X9pY!Xzb zIW`Pjpo)a*H&;zup+bUh-VIxjJus4H+#+EQK%Gn?pw1H316s!<5=zeitN=>)C87ar zYS^_W6m6+N6x2h)dO_)VgdKQFsQtkBLlO`5maxH4ACnZQuY?VO`kB;+`b*eQXn;u? zG*H4Gf}#!>q(XxwY!EcWBngT*Fk)d0G|Yr-s7n}Pl82kLgjyvGKBc%Z$b^#Z0DBBd z_99vVvIU^F&#)KStSum005%mGW6}{CD`C^2aVA}%WFx?4LK957K@%nHSt$Ao1M(e} z4Y1kJWRvbtvMFG*pkzmad`C7S6hL+)j(`RdHV4|!gkm6F!k&XRG9h0#Ht7p(B4P8O z87AcSrV=(E+RS7ClwumN7og+=qCX(J1NI^`(}d!L>;&gm*R>5A7nMJ_IvP$y3l=3H39W zg-RZW=1JHGQ1TN&KFya<+l}$HgnU6h25dK!{6~;4$Txu6cuxKx=7Qc5YU452kSu_b zp8&P@nDkc37ES|-h`4r0QCvf&Ki&n$$x+yhmJHMn~#!E|ABdvWF3@z38+7zHril4 zbc}@h6a1WxWCN7yIWYPFs@ud)Kt2Z4-eUzovIjarf_Xf{9Nd7~e$0y``=L)t*d6F3 zlLOGn66zl?Z<3Jxr7Mp}aOC&V*!kkcoEMZP)fRzJ=l?Vf@AuzsDLgNg~6D8B3 z8zt0FVl6@PE|kgxlrZS$5*iy)pJ(6!C4U3Z39W>DQr;0J7z;&m8bI7A^MMOk2o?bI9G!_fBud?m=vJHdz8Mtm!~C4%g{ z4;)1LcTl;eSc@3cfT zfue2@A{t890FekKUjk7ddQKuTFi$|365=wHO9cF@DiQ(zsyKlVs0XT$2-sYOFA4D* z)FKggpiUA|33Zm>G^W;(XmoG*p3vwzSBXaFx=A!TURR=_?x>y;jh^o%(df9hM58nx ziAEX-thm1)G!odctwUoZ8l}ZbG}uaw1MxVAj>BGrMrla^Hq&rSZ6MJo4YpRBBRv_~ zTB6bMwh}EJIzXbKUaA8nT4U%q@ECl6I8`S~l((Q$BoxaupC>4O)tM4y4Rn@783BD- zLUB)XW18D3BcXF7%A?S^5@ihZd5J>LpC?h4LSF!QrjieR4InSd5a?QoG8(#0qKt*E z2ODt?T~{hmmOW)|- zQQJUKenR;d^hJr91%-_W1@%k7E(FDzfd2^PcPM;7sM$~|Cs6J}UzMospokShxd(-> z2{i`_UlR)ItbnfxwLNr$M5%(p=Y-k;S}IY=mhd~Fc7$${P+KB4OVm!#trBWi#CsC8 zGjzMeXkXsPHc-1jcY)p5hO@*TiP{zVg+$GT9+ptsLv1mkc7v8ns2!rVm{9YeMNMlTgtqBIZ=}r=Eg`&&^ts&|tCqZ*u z9c3dJo}<^5(0o_-l+fCu?j@nQukJ5lqoDy3nlI|~48R_T+9Vuy(otrD))e(<35UIO zl%Jq=N1gHkcs7)t4QS0#r{@9Q9vUxUXoK|x2}hjksS^BbKhvrFfaXLGu!wYy{XIDA@(@c~J5`yIN%#xU{t{Z3)CWjtPNNq}Xx&jKdjU>mA0(kQ zNc}+xr?QWb(7K~efVH7W~ zOK7c5e?!73cHWfGx}Cm8!YGd3lF%BSzE;90Z|fwqo~N&uFp96YCA7AuZ;&vmcN-mI#4@(&Nmb8l&DLg-V*g?s1NYP*lZcpPol1X`b%gIV-1kdJjWUcf^hzG&|nG8nXDla zbpbRKgyEd$p}It!548dt(m#MkNYs^3yM*R*)?|rAKvN{5A2b!DVchjJw4p?xj$506 z4BT@ew3&qFTh`_h6+X4L04;G2>~GDIh+fck5}K1)b0jKa!`fb=?uCw)sPKXHQHh|u zj{{HOo~Rer$zTe$5v$gz5)lI}2FRldzgfv%bFq!MvQl1wXas##BIuc~Nkjp3wM2A) zz5(9E`5mEeNknHTVv!JCpol+0WJ3`Xgm?goc(NkaL|5n*fH)G}pr~Vn=mFgZP=`c! zDES76o{ZTv3C+E1h!a9Afg&~tn$z0?BTt&Z&bi{1*R`4Fu-+>~&q7hpv{1UxgLi63|9e`pC*GKOJAL1PND0&yz zjda{AdJp&r>Gb@)5<&OdC!x7`^rsS_hWO3544BxDWqxl1CJta}-`{|V zPvMNjj%BP)Zoxa8&+S#lt7ew5tgvmY4jP93^~&&S)@p4#Jgbx!Vn<0tLc9%IYN9o} zRE^HgD~Rl6EwPrgA6#P1whkLOxKu&+S@(kB_&dMAR+`x>q(vWqS*ml298Vq|Xy(}odA7vkxU;-V_kz;QkW$vGq=fF-y&%$7T3k{RQi5`r`(~6pvheIWi5Xv#cp6Q;gJ-c}J_8jUt#&e2iiRWU^Q=S!Gy}gEdjq#e| zRpPbSYn9g~ubo~8ypDRE@w)Dv?_KCU!uy2x1@D_a%*V|q&?m|##iyB1j!(W%U!P4r zJADrL9Q8TlbH(S5uf^Bfcf9X3-?_d^ec$liL7`z`VfzfklDi1E&Sf4O|-dM&PEvoq-1e zj|QFz$_wfrR1`EmXj;(Rprt`;gFS;ogJXjm1ZM_!3N8pf6MQA4Lr9O1K_R0;CWg!k zSsbz|WJAdIkbNOXLQaKLgxn5QLPvy72%Ql+FLZh6n$Rnucfu@T-eG!Jd{}x|>##0i zy~Bov?F%~+b}FnQ?6$7x9(o~u?q`BNL!YNF*VpJ<^j-Qv{g{4Ezoy>}cMkUrw}vN% zHxADV&kgSzJ}i7(cyahCtJONqdfH~SjkXor=Gd0lR@+K#J8b)H<+jriSrNGr=OV5} z+>LaO^o_JeCPp@k%!$m8EQ}lxIVs8>l^WF|YH!rxs1s2aqHf~neB7evMK6zD6TQWr zf}hOFvFGC_vqsn_*k{BjF&;6&G4`0$m=-Y|VtT|3iWw6#C8i{1am=ci4Kdqe_Qf2D zITce8b30av^@t6QwZ~40Es0$myDD}=?Dp7wu}5N0#a6`LiL=Bd#bv~0$K}QKk6RhH zKCUcoZ`|Ry({Y#M)8kvmcZu&EKQw+!{FL~T_{H(7;y1)^kKdP&lF%$6Cm}zfFkwW( zgoGIh^AeRrkHp|adtz#0i^L9zy%UEfj!8V8cs}uZVr4y-dj9oR)LWa>I4LVBH>q#Z zu%vNGGm_>dEl*mLv?Xa*(!r!-N#~NTB^M=^ChthzpIn}NI{9+)Zz+9KhNX;4DNdP_ zvLt17N@>cDl>I5?^|R~e)$d=wsQ&o+)9TNye>+u4^+*j)wWp@0wn*)e+9P#P>ZsI- zsk2h&r>;m{o4Pf1PwJu6k2^b3u~G}_rX zt8sagK}~jLG{|U{vAk(g)1^&UHS=sXsM($7)0&@X(W%9rmcA_~wXDpvWO`@jWaeis z&s@_=Z`Hrmp;p&h4{d#_O;MY}S&g%1WSwf8*Y;qxZ+7qOo$d5?1?|?fyOT35=TQ6j z_T$^{?~u}AUWYRs13MOXEbrveX=tZIos&9ObQ#>`de;VB$9FxDtLKi$J>D&&TkCFJ zy7lfhwA+|&Q@WLOTik6`x5_-1Jpa6iyrjI0yzIQZyg_-R@+RiZ%A23Js(a(^ncX{e zFX%qF`{?eIy3g*uu=~pH>${)oUeWz_zLM{eADnN`Pt9+U-yy$u{?Pm}`MVwne4xhz zD|>kN2<{QlqeG7wJ?8XS*kgH*+dV3KT6#9?nbosX&yt?=d+zMHufS5^QQ%)Np`f_n zP_K+$^LridZS6g{_vqe7`ULig>a(zKXy3Jc@Aezt?_B>b{nroh9*{p^d!eOpQsK^l z`2$xBVuK0?l?|$Vu*-vc20ITPH~7quj3H%16Nj!IS~_&c(EUTphn^mKdFXEsiHAHN z3VkT{p_LC+4$B)hYgpN^y~7R-J2vdfaAmm5aDBLac+&7e!;6NG89s6NwBaSg=MP^x zeAV!^!#54zK77yc1H+FDKVBq?l8Ravbtsxvw7uy1!?6!fd-&AD=SMUc(QHK4h}9$3 zk8CmWjggl}{x&Lq)ap^|M{OCkW7OVJ2S=5UI`N48kr|K7dE~%okI~tq=Z!w`Xv(AG z9z8Io@tE0T7LHjtR*dx=J8bOeu@lD57&~X2GH&p=(s4V+?H^bEnCD}I9@{nEb9{^O zQy!0aeE9^o2_q(yJ>mOA=o6!!I59DG;<$;ECeEI?aN_cbYbKUX+%a+g#KRL$OuR7h z+LObcJox0zNu4I;PdYU@XY%67t0v!>k~L-hl=D-rObwnIF*SZ_{?xw3!Nn29g~h9i zk3SXl)TpO+O%v04Pun@&V|ws(`}7sl*Uk_#+-3yMh?w6lB_;DqR+OwQ z*;KN#7e2pmUhuqmFIZj}_rjVN z?#%Byf93o;3zP*(3(^;?Ug*DY#=^2imPKP0?OYtXc<$moFLrow$CA_~y_Xa(nX_cc zl7laams-3u@1@Hx-CgRkG-YZ2(m_i{FP*q__R{rBcP>4=^wiSJOK&c{yG$(eTo$@4 zc3H}@jAgx-l`LDbZ2htw%Z@BNv+TF!F3YXUQIsvHofWjW|ubyy;=0;m^UleIIrZ9DC=tP4SyLZJM-c z{if5KmCc!(hi;y|dG+Q4n{RKiZ^_s)am)61-QLZ5cig+B?;hXku{D3|gsro-F5S9e z>z?;K-y8SdiL#8cvTgdd;_bfM7rr0+{+u0AI~INr@xh#({yS&vJpEz*hYLSEw5!3c zDZA$HTDoi1u1&k+cW3PGu)Fu}qTLgBm+W4;d+qM+yASL>zPn=gojoplg7?Jl$=EY% z&*D90dk*fo^HIh}Ss&$oRQS>SkM``f?9JIbWABE&*FH}CxbeqbKJNc<@yGM_dF<=3 zulK&8`^N8^vhUg_v7cmrGW3&KpUnMa@h7ME2k%eWKYIVd{dYbc_35!suN`ncU_H?I zK<`&mzSR?Klkc^Eo9{KV5dGGV- z=X;-@cYgm*`cFN6n)}na>i@3&RC&SeLhyx@3mq;Dx-jX&k_%-Q$}il!C@%V6v|miW zn0>Lw#i19+Uz~Mu@x?bTZoRng;?axeFW#BOZgm&N7a%So3rFXvw#c6s9E`IpyT-gEi* z@J%6?GTHv*eYx&oTu9aL{eQo=-W7qEd68uZfFN1$6 z{$=?uWxpKw<-{+Q*Ilj$UXQw-dOh=cm+O767hRupeeU&@*Ee0?cm3G)itBf8c-*kw zNWGDDqsNV5HzwYgb7RGg(i?kjl;5~;)9q%boBM7azj@^ryXAW;_Ew8q1-C}snsIB% ztxdP~(|@;fZtuT+``5<5X8zjc*FnFI{&g19SR~dS8{&&474tne=FR+Ab6QhwTY!09 za>zEunR|;~W`ary_}Q`+y|&>>ezS}@oxo|H+nA@Z=W!yXewvrfD>^NiN7m(yVgk}y z^2l(-D^l^Ue0_CHoQQj}fB)4Y-nu0GvHr@!dn5XE9yG{(+xF1|nl^oF8@^XmkPD`C zRpvmwSXW0*Th=5eOCI}@|cffd531r>W^&DU}WV?WzM~E%a)6EKzSdJOFica3fFx$Sl9rpES(MB5CEX=SO!(rd&06r_;9u;2MyCA`i*CZ?*za1(AU#94+iK7grA!~eG zQ-(6;g1mWE=Q7C1r52H-G;Gj9NlWz)a7yBl5gy30Kl0fqz`_SNAKATrO8%HuEe6}V z1vH9^%t#3A+aa=PV7G2=3Hg)rx=k%eO0)Ly3l2-~Qh&%J*5F=+FfF}%QyRd&ZY+p3 zbmZ(GthTUKFR|O`thhjX%X&dU^;+5kl{xmV z6Z7*Yb&Gx6zkY7hjIPPPWShRogFo`%iZ^V37yq?wL(j%R()1@6Pon1z$8&>?cyIIn`ng8!GoLn`zf*bU=1n~5 z#Yy+@oJ9CO626bDDc^tS`|XGuX4W(vB@H*q_xJJ8FtTBqmj~xPTaN6Ol-zAp%hvs@ z-TYExtm&}CkK`e0p|FC4mViN>4;wYjFAbTC#DAF!HZ54NNtyHe@At-W&&q4`Osel5#xq+v zo~cpQ)@rptHL*Z#Bt1og&xNt&glEw+UFcc#oQ5{PNUt=%4ojBsy-Su%;tMBDsvH6L zvdYa-u+p5^g3&vG`N;DKkkVJoFR**~TcRltVy94|B*+$$ubaRa{xnzTtv zt>W{8GWxl>2FK}ra?-MR%#)RQDGy{~H4)FwLOJvBY&U%Q@_)ztcCx0~rcvoEhik{a zv~7+34J&)4`J|~nk*bql)*^NHYkQBr_H0LGPUS7`T6wSXaqjmZR-bWCtdS~K?$hI||UY6nVWd)uO`nv3rDuiN5s#^8Cwx%9tJ~s# zXeqXlg%JJJR|Ho_r0gMNZx&>}eCY zpQCH-_*27vZDZrI`!>k$IH7q{#HnBXZcUryrw5 zVvJQ%5r;9bb#hIe2qwb@*Rpi&HW3Vb<)|wd`LG#jG01nYQ75zrdrTw4nlwI0 z=1J;(BN+V zk=frZIeCa~w+49ycze1;xmXjLM8&pis3*qv3kuQ0!os~G0`uF(wQq#HphhvJ32g4f z(i|2yhtz*P{!&o}{Bt{q6pPVo$$sR_M@sNVisz(B_pafdnXnV}k6tzR6l5pyH+HIH z+)uz;?zkr`($Fi-%NW2J8y224Vf=!`aPRt*(nQ zw8!(@SyM+D{xNFsKFVxkEy=Q1bfvPWX+Am+NNd3xp@%5{czKt)0Un}mphxG$d(kc( zP9Ktv|9Q&2ar8`qXXfLXwtur-H~zIEc$`Muj@H}JqRTw^AyO$~1JP!NnK`VTE41wa zHTjD)XAO0EpPn!I;@74KCokv3{&CKp&H`_7yr0iqVYj#_s_JaP(5~|J_|Em}b&lV< zHLgp&dR^jpA2j>nnPFj>;ndtCN8Tt;Hp&xJQ=UJ?f!VAWa|w*m z^Ctt+!o$-7o~+zaSvE5`P1ndHBgGd2{Xbx@4l zB1aAH%aPxiBP&{a=yipsUbpqqBPV$2%l4d@m>m1dmANORts3K*k+4;rntAD;;=2w# z6R#_2UP|o%e0&%$7Vob;4Y>`&FmCf}%7T%|;D9R5VGa?akr?qPk8h5NT;q?c*Dy zJ(f9a!UR`g@6Bx)!Hsg_y`tR$;?k}0EfYgfpM(4g!|bERRGw=b7BeQqH&6BO3-t^P zfEig1${447fc80pO>~se9BtN=(TNJ}#OnTKp-~l?hfyF4ifBO*sSA*1pdtnuMWo@W zoZeDlX`&$AVKs_P&2Xd>4Tzo405~SS#xNl=g66(FFS2d8a2vZoQ$us2k~*e^Mm6i) zF|Ki+PN`ZdWM+%{@L+s?C+KJ`Y+gcxmuGDgCWp?{j=)|9Zu zi*no|S1&00G*6df>gt}sE=MkoF1TmY!5!n1yAEs8bbvLhQKQV<&MjhEg*2@)NehXZ;1>kLXJvPwsRV0OZTkq; z%@JRJDrb%Lw_}u9T`bfghXf7&OVJREl#%TagmD3lV;}~GKO@BPsr() z+N7YVt|^rpTst+7Xl|>YFswylQ`d4=!$Zvnwuy|&?3v~pT_-)&+pAYdIA4;K+|P&| ze3yZ~?NbDC??2?erZSj~PmSAZiX&rOP6o;9GOVbp^@Y!9$`oLBYLc!Cpfe}NpQ~@ZBxqcN9|t%xF~J(;>KdEachE!eoklecPfQFCPe@2?)*&&WMM$KF zk7t{&>V~J-n%jkYtTiarTX?rhtk@+)(ViClV~8vYt$juWDwde_4}`@^ms{`2&oAs>@@pVbp}KIdH2f zU`;I7O!jL}@|`ifz_ON6PNO_tX^qloc<IVm3nbuzUpz`7U2P%($)@3qI zrGC|F*tL4i(L!dl{AELjE(PYQSwo{9)f}Z7iyJ!D9kJ5rq4H<@4|st`xd()KdPN7= zd?O<4ZjTJ$PmjA-6%g*@>{Mrj#l;D$F~<6K3)Ghg{M3x;SF?kwu|rLK( zmaL*1B$ra5@yiyC=9i9>gQ=IND&z&6kZ0Mq`(ux)KCP9~7|qdk!SyuQrA1RmC-3k- z0>Oxb$VXg+M{0t#ULB8y3F%GdxYhOWbsZb(;p@V$HP;j3Vk43t=vcX$=LPr&23Eeq z^XicxUuNv0jJ|Bh-!x1~`I5 zuA4+g#6$-8`A|D4hebK)jrA_ENgW!5U_2C`l`fnfh?j$+GG$F_NMuxN42T|V8031vU^RBVb)WlbyHAbX`)YEwkNX~Gr&ehsGFvMsp+1LcCpraM)j(Z`C^8aGXiwXAh04F+om|BWzyjE zIJ;{|O4N`7Yt#IOZAQklw&%r1Ml@*Iq*J1|wRs=6L~GwLJG7(B}>L`Xp-#WT;zgJeK~7^{JHaMXcMc~w*O)1M$<>Ktrx8|81|<1I$B|;L7gLi zG`|MPG;^z2H)(_g6k{a){R5pA=<%Tm!5B6RTdv!P{yeqvht#A%8_%xvY-dN0ZLR?! zU+%1W4*jRttm%)olg-Q=(E!p-uAP``6Evwm{{F%)ZvL*q)z7WVb6fef3VWxRm`?VJ zN?P#1wZ_^Bp7-aqlfUv)&GY_#?S%R`>iq)#xOP&LtC}sfX3gP&Zga!&OI20P#X0<8 ztFs$^v8pCQXLou#1ixriVC^KBUppV2W4CvRT)mn!C;EJ)=d0G71Z!6Et5g=ewNO$~ zmRjp3=K8~5m&FO~yX?O)Q#V#3w&N~N=8T-yB;1V^6g1U_>($-+J{wbo6X0&2<- zz5dk|X|AE}!o|-eap|h{E1GzOc?j1)*ZN$!lIxe?=a=Z4TlGtxU!tF1f`1;K7GBjt zX^K3Duy&5N$b6gqr#z$Om34&T5Z`oH$05B*M4dtI{E<7vo_yiclHa$O;-Nn8Z}$xL z@lB}j=JL(_?jC_|!X?nP{j+<$jrSy>|f1^PdIP~d}xp+R~}9)MMQOj2vV`}p&>2G6Cn4Dg-bw0l@Y z%QUZ`ATRKz&kvMs>Ggu++^6Tox+Yocr8f%n^$iH{^$o1CTeTfD#0>u68;Yth{1)Ol z=r3YxRv7>ER?(e0Ja_8w-lwjcN{IIq?ufEFs1-IGk_$aHtoFMa5lAgItuWfrCAuRz z<;dK414auv_@=^GuyQPwR2zr?UO&q#NOzCL_Z5rrody0a0rx;JcVB#W+_dt9;}eXa zv-Oh$<01l`mo1|&FBI<}tEZ2zi=~67pHk2KCFw@IUsQd5`}@*As!qpysha$#jySaoic>RJwVr>n`nt}J>)@=e zYE3%kc(u+yRDFK8`_ezFPVeqWCwr)lIJOIl=@tP zcwywneef#W=+x8vYz-rwszUQs_t47g$NAV7#*bfGd2W0?KDZzEuivloQGC1b6uw?q zvAzAsW^UBh&^IMC=B>vbbd>rZ-{Z?!8$aQAk8i~m zzT+|8D@8M_QA!#OL>xxz2aSZ%TmM9(glYKT0b>E<&7!6H6CQkyB0u4wLN|2ms>-OV z*~owG^xH_M{AVNoHR;IzRhduxZKPWmYCGbS#x-s6elQUJt^Q)ooYU0Abj?T#Ef+k6 z_p#_nspq26ru?FbK2o8fGRE@evYhelRU^lDL@_(;5h1~i8e~}83~T@VikNnTnmV}$ z#fEu$h9~JtuxrDJ$av5G!TDKfJ(@?Ze5=RQJbYP{me)MJb7~M;Ae5;u^6GEc9!o^j z?_quIuhOsGmrg#B=ij(5oosBRYp(aDQ@DwPQI1t zRg{jNp+EYQdZ|HH)2R;l*Gg|!>-1J+g`Soh`bv@1N zjBmV*IHUC{w2}0|7RoKtDV}8djr-Cm4rKb>`_d^6WO`L~x)*&z=1AA*hlXqJPj)iS z*IcX5$GaGn;!ob^*Zb0|&lk5S9Wg`sEL2l5Gphc^(nf<6j76%KvCT=dF=|Q0H3>$X z*$_$c+bfzU%ZT&Bb#m_Pg@}_gOKwcqt3O#ZKT)e$jtHo31LVhzG>29K|Mb;bOUEZ| ze%|QOq8r%4W9kMwyEzAh`Y3IyKW}t=$3|a1(kE^zew}+r{U|?YZKNuK0s?JhyG+DP zpy6v8y;+R0Lrpr>X(Rprq3uoJ-QY3lJcAY+nfELBe9=*iIn0 z_5Dv(-KD2T!oS~p4>RiS)3@)fI#qS*EdO&#)n#WeHxTa^bg|3hK0(M$9o>|=aFmVB z%mu%mZu~8DrSC(2LNdvFu%_MEA#YYzbxRalbBdfN4wBr(swT^c!haNl?!YTq@LhOy zR~sS1WUZ|M0L z`)&>A*s|g@FT8>vu4l=^RQI)eu_q1}2X8(5seyl$5{=c5?3^L3?v zlWISxMSt1&I{L?Ok&GYY6vDoMf9ZNor@71N%G@18|A3uNY2|-3KlrfpEeB?{54?VQ5kV>@R|l`0*O9u&tS%Pz}wF&ExZ z&{xyO6r3E7yX!@XKB6nl4a{5JKI{0tv9N;hJi0R%hj8(o4Nk8M)EA~F8lYYkOtLpfmJxqQPeS^J^J(7O68G zMH&<_1}fY((3wrSla@Z`P~_Hd@&0|y&|Am|-WT$PeF}ZmWXDFj;>+W78WVQC>Vx5Q zn!EfyFVhd${Vl{RLEkvGq~mhlUrxM-F5$lL9eDwjnR*e?EuuOYEIGVJZR+2B3&gf-nsCLJfo3nO5c)ajE@7i9g}R73gXVRRlEpCGe1DK9T@1#rfWMF{Q(+}JyXLw7ueem%kq=KTy^5+>IA*B zme+=k6;3V^dbhMXbY=d;JdKUC$CGsYXY7W?vnOtFCG7vjbV$Y%Cf88mL>VLW)s6jz z{5~FN8!E>4_sm0%-sRXrve~#7TC>?`HWEsTbdLUkxDv?IygF%U9V{s*B1_S+V_S2D zm21YO#0T%V<0FkPI2^sXklh~2<#wI9?6Ny|WbS$pc`&z09{>b+e0H&d7=Z4B{Y|6Oobw2u1n6vEr~6=E z$9=@N;&+Qpzk3D0BYlHmm05dxczeNkdJd=4{=w=0(L|?yFuKXoL??N}>HAf>ld#Y# zJw+}bcK>F2oZRZ_bBQ1Pxfj&?SakQHo*94lHS7e0Azonnhicyk$?gj3>@ICRDKQEw zzUQ;UiaEjc(IDO_8DmOt_#EV5cbgS!i0vpMS!F0wkr?igK?p=X8DBEen+JFJ5li(& zYBQF-UB%F$v!U_*lZRgKS>H0*Q(3Ym!}}A-aBRe}_wHEmfyOcE6R0VWxMuzK%>LQT z+(3wUz_8ZLA4Nv0=8uYEP5^@q-f(&f-?HmB(BmrIqPt#`Pf_R?+I@tM0bVK?Z-*9l z6mfJ-Ht8|4R`}QKOukqN0f(KKxXJzP27IExI=5^oa|xCcxf#W3gXwhmNS5H>4?Xml z6kIfaed$;w_^6Q3L5moUZ6c8``7VRx{9p2n(OpV(dbl z)_AYif(Vn(Z7U6~WraROHZ18yy*iH+BzqH3zP-sS1=Yvy?P8q<}!aS?b)2qOpg+B;W5KpTdZwb*=Jj@*Lu02QSQ%fZJf zBwh&Z1>gyfmUOUW3wo?fUzr_m&OeaM_K?q$fTmK7OwC#vAEI;wF-IO_bNpY?Crv-0 zKI!R-e!}V0S9ZOspKv_SGx~=6)84_a zS8PIux@Qty;{(4B@sr<2(ZM;L_{s01@N)$1Pcr^M|Dy2{dlRSA^^C6WiJVUD;nypB z8K+afI9=IWN6=2>3kW*3vx|+(2;{Y%{tDcXaSPj^InZ%Ak zViQ&{1{p0t?)XF+68CCTY={6*1R2s|L&)pa78mv+8xUYDtS;)GN{ zAjsF8ue`nA^Fd~a$dGbvat-p%fpx2*D+QWFlXxO1!t6e@3%(U&@jUG**a3}2250gr zAbjM*Ax6bg&6m#}R1)G2t|Lzij+U#ulrX)!7P#w$>#L+TgMXys^h0+D!fsJBr(0}K zO-h`D-VTkP@h<_7AkSwdo0IQ(#68Y4o>^Rv>yjflFfNM(?>e$ArOL>mg|tDs&OBXD z);tS|L(@oxOJ^32jCzw{HxBr9h0<2CE`5Q^w+B7f#PX%f@7}rdp3BSk+7n}i;%JiP zw6)Em4}Iu^&L{VKbIo8iqoq8vkZ>ae@%CUo1n{1N;wWP@z_2Dl?;*T8rKWS-FXcZF z7L*y)(s56}E!J+g*nRen{$il+dF<_xrM}{7J-W}@*>Ru2;LxlUE+Q zBT;k)fGvsz9&;78P)z>QUFMsNrc6P;=hZjmmuoTDV;M|>S99yjeq0`!EAr1fIpX$yphQE%Nk#}a2&7g@PWODeb4fKn9fg@p4s>dVIyp$ zKd-0DKZAVX*T2|Ar@ffdUuvR%U!j{|jA_r6X|LzkztTkisY?H?o^EJY=q5AK!9Cv2 zlaPY>wh_wcer-ubm%ypKhJ2%4b8~+GyT`W`@^f>p-d-2}UPB6!^v%g)plG{mC21Ls z7bok%9&a${?SZn2eVp|}{x7wEU95kUmlc-Fz)cPy%6m$Y&mtJN@-Q14%VU<$6h_aQro|ncoX;8_+M@$J+iXzpR5f<>9Ye1jzH9AMWPl8=C!79jSj{=Hh)LdJN*?UkL$++gZ^yP-!T@>ZkEyItOk0$ z9p+i5TUyp=Tve2iaFX^tIG7PHMZ`IL# zIDuTuW7CRCM|;$Dk}=Xc5v|h3+i+U_-J1G4dcH>A-b5!`fUOtP&L;YzN?%v$^n7I< zWsJ0r)aOHPInd8t439h7HiMHYAdSe6bTL#kL&Xe{pPcPnL)f`Enw3xm96L(DX#On$ zqk9nhil~$bW*14jGMin5A0dgC!!jeE3qGRteV+`^*bu5Z} z`nM}1AkdMUC8cl-WH(SbJR_m!`;?>6*4D$ugg9yj|0vIxMxY(10zFe-Z+<DU&DWb|W2suplMP56FHsnKA5V$&7*Y?LOagPRIO~ zl?CZ($#v{wjL#L=6Uf~Jf8uB^Nsta^PgF2odipD%lP|D>@zUrRuYV_g^4ynoHrI<< zCX&c6-i&$BCNX#2>Rj)FHLb+gX?9bFG0k`-X^*TdjhPfLc)BeFW|E&;iz|>Os>Bc& z3lSt{Vfc1kGN{OSm85>k1)W&S6~_I>_QxMTJ2$7~gCd7+V$hnHJv2Uccs3F4-BwuJ zvSrEi>UUU9Xy8-v>A8hz#y^%5%Ji!QS_u7$Lc!qEM*8!5I-9@z`WKt%G=CZ0)YU{M z{fg6Bs9Cu`)35k_UTM0X_61J=EzvPPb?6zCH{6eX|DZD4-Q)#z>k|I-k$FYWIEM-A z7TBgBWDmvZxiv^Q$N|QG@{11P9ruJlrfbTC0vJ@&St;k63wDv$`b2du8MC@f7fEl; z3`VTco`5ITGkrJ9bA=X>90|!1r8{j*cMW8sVTaFWpL4q9n_1qg$}5rqoF@&HSFoj- z>>)bMeJh*$eC$Z4VAq>u^?Jx8nRH-&pOZA_=&*DnZq6f!2Mqc7>MuQ6SNU%ypH zPcmJD(^phF+5DuF6CJt+=%Tf{xpq=%muau~9m}OUumKfUpf6HPQUOoOxzH|o2A+K{KtiB z+a`dO{Vt=w1=lmWN#bm!MK*d;HkWWF$gg%tIF4!|R3@Q{jd-Par~?v@Bpg}Rq-7~+O|~PG+eDNPXiBEV zF8t|FcN+BxwS40(9%Wgz{~}pfR_$}tj~#7o(ubM8ayc9SUzGUxgD!XI=+Eou4w@Gt z2lquC-AD6Y&|lKg{W4?|r<)K~XZ)k*{*viK{JF1abnG3N7vlOZg?=F{{XOOW%J?Pb zsgnCk_c>?4IuzH->h%^~u5gB3PwSzCXpiW(ER$|5+WTAj9mbFD_hICLm{4^`?Dqnn zqFGv+9nbSyDcv1$KvsK9>iLp%K)U-B%RK^rk(-SE5Wl{`+O6J_^D3i{6J4TTP#Ag5c< zi5oKG)mA3=DDFg774Bo_yxmCug`UoQ4(xhUR}-D&Ex*r83Z3L3doI5|4uMDQWcR1_ zDXwp**F)Z_*Hb&qyqzR(b@W$2hcEiVH_`qFanh6ra$AkWwj`=*E0BEA0p>{~xk;XA zebzdco`l7uB-YoI!!2cNbu-LKSe@M4_D{%U3~w1+Sv=bt@yB}_k7kdXJG=7LT48iz zuk^x9v~=U)##g2IKq=sFd{RnmuN*QA7RvQKtLt}j-caq6JlkXY*qHnR{}RtO(x2DU z+1|^qf3b;9W5Ve#HPK1`V|2LY@jvDMO#kE8zoMrby4CAD^mH~C_m;7j7pVkm^t zO#htK-P2XtHJL0d9UL4uv{dLVPiHf!7}CbtW1g8Ik?juc5AZ5qrztmgaD?j7kQz9+ zHqqyF4g38)ohEW0t!$sC4EXu&f>##mqu>e6Q;zrJV?=r$=ZQ=#5xkvcdK;%N2)dh% zHTje{eMxtHf$4Lcj`gD6C(rabPG3>!XpcGvpwEFWTBZGt`F7av2-B?54W#Gs`|TyV zu)TKSgmcQ-Q^&BylGWA~*FW3>k431sbI?Az+Onz#0g>a2;<2b;A7zj<1G1Ew1hv6% zy1nB>w{vbNS)^hG8;cZpyGngy!1=uJ{B4L64xu7H()LNE5@Z8GA99vtYWWPDoAOZBJi5-R3{`$E($At5x%ReO9-pR<6e{ud!lI^~y+W zAA2hqW4%wicm2bz*;wFd59c@d!N%duV4N5S_)ch_Bj2J0GGiPkVG3QUhpfpSoi(Y) z`a%zZolZU}?pN$#vV*eydl+`+>9!Q}A(GdSFd|R4Rq#s4`(eCNd7cqAC*cfHg@)c; zqK2BJE@ZM39?yI-Ge+*hpL7hP#)_vJ-V#Zz zdOTBq-IF%oCI@ar5shuzP)Or8rL;z2V4xtJg+l|~Hh2rOmHrG$EDgg&NIW}@1({;| zL51^dfX}(z*jrJv0c)4hP4V||I=i09WlrxB*K<1Ux%@s2K|coFK)Vm-?uGZTJ(tnh zen8h}jIZE&@hxjtKlWt(?_R<0$e+XNHn8^g^Y&VKyBM9xC{9=W6r4`B9iyv$3Vxq; zmA+5CkD^oX>ysAc{>}6_fnt>QFkOQ`SFzQH(QmF(5S`X+JHvL79ypGgR-+mMFh%n) zwQ2nwrG6gGC$hJA<(pn1_u!kxT#LYUSH|xtBUBgJ#I!3LDO4h+A5}OaSQn4kLUlB< zN)&G^OeY3>s3_+1CGrWMyT={s&1cSrM)r>OZ!P=W_>bs4eX~}#>uP(q&*KjH1Br4x z(w8fS1IdYMBOpCr-Z>r*S0-brfo$CE^!tP9YAP|&M^FjuzU!D{RL9GMY!R{cT53OB zQW>V2O=Q?`#~GWps<~dK%vaHm?UTZ?*f7-*|z|TmIY|)aSNc_#w{wmUw$mw$sdfr9n9e+QApz?e43~L-~hWop{yX%I?3n7^L^^@ zp=;GV$Z}UJdQeDhQW`wNYkGY4vr1KuK`Qj|e=nK$vBDnv*1AM#4=VOyA%3v>9&B9> zfrzRLNuk^a1%&ekix{>3Ib>6M)RQWKr@N=7%eHPOjO!>@m(iB7&DPXDc*&f>QG zK4u-=&Gb-C@6ge^nY`olE}~=Hrl5zWVC&|zaT7&}v~kl%K{YK@9|i3~lwLzKa~!W$ zuZrpslRug3t-@ES#y*=Xp6C@-=~GImGrqH?7C{*sP~w|VNr8a#cdTSk*i2Uw#qO;3 z`g|;)$>um8yHSOQrWrj?47aNE(I)zFl|I)**RG#X=@zO9Bd(`4WM^xLKbQ1e&U2Zr zXFPvNJ_&zTQp+E2kt3R}!{dM)yFi(5G2DamI);@%If*gf8lbdvd(*!3pH7v(-oZ{+uRi4;vnw-CReHxgarZxnmeDC2uo(7Am9Hzu%hWUmjg z_9*)5M*8#kmhR8!Yz_14Uu>e&T4i+A24uBY*!^q#{$%XoJ{#%J>*?(N{Q4K0=yZQZ zH?eeG)rBJ)?cC%AI|;m+sgICPjMevy&g4UnBSb==Osah{RICm@u$w( z|2zeGa34lzGJ?@fT}^b-iTL%6COY}YIsHY2&U6M^4@9SSTG)D^+`_C2N*+GpEedRN)kmdpLJO36hDP$KX%u8k zO-Lwlg-i-^LrK}{f%#l&YDZsc-e;>M-<7+qFgTOhns{^W=9z7Yxhv|3)&@pmwP|;( z&zhLpUq@}tXfRw_j;=0D1bzFRdEer~$i#a09kh>QBDM4U5K&&9N4UX&n?HG3W+Dd(e8UD31h; zBL(3cOqYNt4nl?vPYfV{90$uaDUVt?M5R)qmz`ztx=7w0=yG=T_OSApR9cHw8Fb}l z&v#NHb+#aRd7(_DifhU|mJnGxfi|iQHQrl65n_~X7 zJYD0a2&ZHIkm_w@&OHi#@cMxSkE0Em;Bf>Zp)g5Kz~l@%x1D<6wa;CpO zgTKFs5^r6Wu7&8Uw*9~`mYb_?fs(giYVz}@l z$b>gwkEEK8)wU~@o?fEHCsoDvu#RcD4P@2x3=)d?#LzYBVhXQh;b!nkJ7x)8B}@#0 z4S*;rzGz9`IeNe0>!0kt?9dOp99|3Rz{dRPUSI|R63qVy%GRU!^KCo(P}5j8UflY}SKp668q8-mj^N8%KYi?R{Bb$= zlAOSrC;Z^+l+pXWzA+OTW`Z4P#w6vQ9FKU%QLr?ge997_gBQ9~avQnLK>kp!VK!I2 zg!4?KsT-IE1bN>su%N+Hxd2XHQ0m@ZK%^nmxua7OZq z3g|(P(qCThGtu^XrN0-G3d{n6)*7Q^kY5SJ2@HU&Ev`w`Mlh2G{CO8$PBvAp4bJz}* zq%Rs`4xb`JkG64|t4h6S>MnuZxQwT2@5~vXl&0JaOvU@YJGn&lKK<48@zj_*=#1No z1(O*;h*WtQj2K^A&5a!JmwYG$ACK3hmx|lQ6Sj^M=8jx>Ef`5oAFPwx?)KT`yFG!Y z-5lRN1R3SU9M_#_)8dQM>+$>y0ot+%-`%ti;M@=zC044RkKC)n$BPqz$@J_lZ>m2O z8;vc*uAi=7wOZ<1z0R7<9CnA+W@AHXkIQ>7oKf6l;4pNI`3oPEOK4Xo#_Dcmti0r% z@#?&UB_folPTObjD;fk7zArJGoYr6mzBI8f&|v}Wm+Y<|E~4aVPgt3Mu3RkmM0I(axY zGdL5k=Y6*RD+`O;1A|-3TgLoX_d4V8sO8y#+2Qy;7L7#7ig)LinUZbU-e)}di0qbEllRzve7@6tgO{gNPjg~7y)?dtlQtw-4U>*8vo|c zyFGp0^vK{x{DpdC+OO8KWjM6m>4edM*(~+2B~4&7K37QhK7n;j{CRl8Txns)=Ih#~ zifEb)TtLxw8^sTG7<@OGM1J_jj@ela=MiT+Z5xKD*PB7Rl` z?Y8>JTy4|jp;|rJBPGZ7O+<{cwA->YiZdemi`NZ~9^H~FY&ldfjdgw7VolHTGa~w( z&V9jXa{kImg3{em88`~&qWv=F+|6izA8dKmKD-2aoY&ZlGF#XraN#7O6!dp1j-1XA zRlcP@(vmv|9UJy3lWFAZAmljhPjm(#vyH_eGBBJ~J&IhcSzSyLW;8y1WpH^QU}$s~ z!@-hoAhV8Q1i{sL$>Zy^nIpD@#~F|KJ5sV7scq|z<)wF8bJo<7!9EFLvYL z$g5p<;5EudohmYOkT7wB#FH{_b%#$V3WnD+E_tz`X`W_ja`?bpX0lePq-ORH*N^uN z$F^oh2dCZp^9S4f#dN^H(nF0r_?`fg>LkakmOP8OY$Id zQ4*CUd5@)u(PPW`(#p|laoboTSE-IBC-?NFN`1*#G@MLEN0%0?vDqtU=Z?+B9LZWb zF=jD#jSXf-v+i5M!9dSdJw9LWmhJ1a+=fQ}4b?AJ>u6tW3}MXh>@vzQge8Pta7~Iv zj%UhIJ}?>oRLj`QtvMlCsopmS8nO6*-qQZ)M`3F}^pMWl{?jG%8&3V(+WVQoEhDBe z1;69l!2JnrEw;#iO*1%8TN=2nZzWa#KqfC+Sr&TF-i1Nq+4&Up=x1A^1@EftT^R2O z)ywyjx|os5UV)>J^(bG0TPqtRj~;o<&2{gsg=_l;lFQMNLD^*JolVeY3HWt3Gvdc) zS(xkh$GQU@-C^HD$NV{10#Ks{|27!9(&H>8r+uN+?Ec#5;n`H!pNx!ELMGEq#&oh# zz4BUVu_y2`mwj$}Y7Wzt%~#;^urA~1(f!Jva|wR&anv}37!YHI7gA&r4}GGFpg}z%nWlHuiyFAQU>@{Uwp~4(sFyR&Ih#Ka z@dO95zOAFF(4p_fZm>pYj?PUVn@@JR{I-3a4vX299?dSUId&iWbtJ>bFp6`4;8Vx` znb)vl7puU}+(|a7iOb{*uM~F<{otpQkqu#MOR^d71(nx*ruD1zi08mHl^ds%1w?&o z((?$TR9U{f)9JH+?6Gx=3l-_zmi4!N#O`-?UcTb#@pw!wkMAFL&bbrGtY3QXKgWiW z$)VUkH?H^RQVI9m&O;%;n>;QqKfKd2eDp7&f4@U(Dq0O|Q8+`>>9pO0&$mvD0A>5w zMNjQa&hXlJ$;-8b4?zQV!M{=>JW zqJfbB{vSnafZ3+=Iq0l{L&|Dw8A*|nzPX`8$EI@=kW4=joW(otai!s=Vm&x}gJC|@ zLKak4PP)4zj8j|0=|g9qem6UPhzIEc0crKseKg;c^O2r|wx;@qTYP*irmKE<$l2G; zSntG=;S-Up5At!5J;I$tv{i5wuDYqmpb6})cM=qhO{niC$G~9*{r;h3A1noW8(-x8 zp%@43sea81BqX3_P36e)&go3?*Wmolp#$9cox)FfWo$xI@Sz~77ZXxK*(ZiI*SE4i zFjY?YNYGo!>J&He&ThhpUo!tV^q8$!Xqb1< zW3c4#c?Uk18P0qccqDM<7<;03Vt!h1@E6t)c{s&%+-xN(&*Yy!f8-XH#D-_Q-wjKbuq0lm~6(sZ*^Wz!Ucsb=q z@aK(h)Wf!YN3IA2%vP^G9F&~SaL(5^;=c2AFuh_BH-r;swLN=IUgh^o7 zbI2{V`b3LN(6lb@_vJH!XE`3?@0Bf~!wAUX>Nwm%$FR_!o&fk26Ts!^hPHKvS zAMC}}a2`JR%i%LhX_?_I(MUh7VZUw->l?(TvXEL_vZ7t2vyzqV7ecBVqe6~NUeiOd zo>|L<-XcmmWb0JQ7Ip2t?X)>!(Y|i$)ycWu$xPqKaM9c29QfmJVa7lB&f;v*o1VVx z*-GM|FH*0T`c3UyzT9{~{_C%8|AHw|olVvEj6od2AAs7xnDedYqHn(Lh_}3ELfm`D zSqaOf@xUqECxAIQjQi-$Kx@(A#S~>+P;ekL7b)&S>zA-T{49WOcB~bJr!Ivhq3{K1 zg5(J10$t)>1+y z5!BD5=J{^1$TiHRkP-U%pd?nt0pB2yEMJxcwxnc{PIQFtTjUStY9F~AxKZlGRbh0P zjyw<|UU&{K-d~8AkKoj|Ql6dqRu~%Bo%;63)9<=6+Q*N5Yw0fuAy_b2e{{B81;{SZ zo0iH5!eh#3H%V@-zY5fpiXrgc5NsudUea;d98}815XEd=_%5t|N2U+&cO2jGBvcYh zPq$@Biju<&NsOo^qEL*kPmY~$ zH{E24#-syH2jEFBOhuK$@!pe~slcsy;RS|YAp1tuRa)jj)2iQ`FEkqn(AEWG#|nY$ zWn58G(RfsZyr?2T!27F3uhkPC(Zi__bgnk4|(n~gEot+-lDdKXviX@lX;Gn%y&b!6Z^ zP%N^9Nok& z#_M-ujrz12ZI_6O)8Uig0%JUB5LPsmlt!AURF9mNBa?XS#Hq40DUt6I2oivt!_vyb z4|Yeb22;md@Fr$4nxMpdqi3S0d@%EthT|LF2_L;9*+JNLt9^f_}rBVl~?I~1C`1^;~#FgfpiVZw;-H(0Gg&6%lthp=4YAFSuK2N6E}U} zst=Rg1I?9J%=h4XzTZ(L6wSibyi#1IHw6HodXV~oKRUj;?qpglX(PWb?3~JErgj#B zeTiRw;J*9*;yyrwZyA7AF`Kcj?K*-n~j;;Pj9!DNI8oj}G_ulUC045NFzLpEdv zLamNUt~e^hgvxc!DakO*Gk2(xJ>Tuyz3(k&GG!@6|9-u&eJq(A+g>=My!o$%WuufZ zE-&D<@k8TsWpN(V`r% z8Tgh-VzUcv;Om#_1KK#|QRq-)i?XQ0W7;8#XIaavU0r87aEzk#_pi>Mn3!N~!Pz%V zpE;t)#Fn!Z#WL7TCX(CTCjunoz~QDD*{2*3OAA+%gK$hTb%nPRXjn8<3;unhJe9T^ z!~6O@g`S8j>TzV#aqC%M*y8Joy36N7mFeV7wc$<+dSK}-L?k;vG;y=(#tw+zw$s?B z=$y)!mM<;TlNSAs%~-C8P)MFUHb@{~a#0D+^E@-H3l!}UvPau=+4&dn9&0^V9^X~% z**FCT>Y@IgV0_1U!dpw<&}PGr2#0+m9kEF5hY+Ind!d1d1=eDd33Y>w1F@J#)OE%^ z^N)q4)6v;$mTK$ah%49|aQO!FK}i}uG@rF}-i7eL67Cpsaup(w5VuDCLSc=bacx@pVa zTy_W2ADx-$^4M1QU;W9SNTyVD0z8qSW8-{^jqPhW@lPCE$hbnj@HXscv{q!UVxXPe zhtP#rULAP{M7#8}`c-!^L zxV4x`6|$QEZ&Gb(O>ac%5gJ1#DK)y%=4Xv26N!TB6t?oWRTzy{(lBc@kV})2s4oX= z6kGI$Xt8=$DF6oA?EKEY<==m7>BQ)0Z`k7M3fS}KZ#YtYEk~F-U6Gj4a2y&5&Eq2M z$N~6*bodaVFKQOM)_oJKJ-WuI8P2QOSNXCW7Q zH62f|Pm^n!y{R}X&1fiDo1Nm7kSsKT2zUfP2i7FD(2h6}6|LcR1#mduYCRHG`rYPd z!iroOv`dXRxAqG0wQzq=Aij%>)gvsorSWH) zNJUinW$1MKAU`^=E2!u4v{>s}9U2A40IOWopdo(+)zBbM1=sN?;zl-o4_>LNkRPvv zucR76)HBj@LfDPd1Z9E$sHdG)tEjU9{RSEx-P^*tc_eef{h^&+grOdzT@$ z^149y*mx~>_l<|QFPh(n|E)G&SDAO`G?IMt%<+Y(0e}t^QBh62Z{pBQyd1v#2jRH2HyaoljE8@4 zdAJ;(Ib=DAFdIpN+qJi3~`;*=r0Zz8ug0Spz(Ga|bn(zd9`$`<=e z-+nTvi2FwJ<)QUtdT}F+?|f8GP|+aRB-Ufeq{4~&&JLFP2LlmHm(vEc>TEd}n>lK| z{Wht)@$$^r!Cez|!%ZfGzq-A)<U+res%gU8*7OX8^{BgFF3)|=k%Az`;^$JM+h zyX4l+w@tdGdo~;>+;AvI3gZczo+sR*dkH5T8&4njL4G9i2hnrQP_oFzAd^~oN0mdV zhTA!)UHlz(Ien{`MQ4++_TAdSyt3gn94OpyY&=p}dOkHRZ(2th%QRY6!`$?@RcruKe&~xhLfedYt*P)ulVBSMDrt z9q6TldUN4YBdi?M%hnNg1QzeJBUeL=@oPH!m>g1MFQZMvP4PSLPrmTJnl0ooI)cuj zKmOZyNe6CBPG>UH$r~Gg{w}_DDG%gMjJjX*xwoucy$!-ju@myK7Y4!6%{2Zru^WMC@ZEe;kwEj$aPdo5jf zySxqU4M7D_Yk0M!Xb9*v8_nLYE7&2@0WDawgz=?p431pj?jJ}U@Gt>CJh!4uz(^*C z-BgF)5Ro)&WD(UDS^hOtvUcgZl}_s~p8vY^2fswRYiOx&V9eV$SB{vimxn_kd(81V z+fao%v7_-#S&|pm>b1yl&gUO}rq>yWrMS&CA@`s^DNS~^=xG|el{%Dmj2EAmbmAIU z1ia`KDQMg}2ngA!cVDCS1pL?NQM<_4l>)i>k&0(NyrooIn629o%IfZa_P?YLf3mzf z9L_HueAeEZa2*O}Mu*Eo@UfV-eEHP&zl~HEvLk!PsfM9^;WyB$Zh+lxX`5;LoHA>N zNU!+i;=vUWY(WU00wEwj5YuoH}K1N z$G3Dco5;mM;Lw^#vG;>vqfB7amRQ3TJSsT?hA|+cQW{V7ZwfVpJpb7wN~b7}9$uf2 zg#uVHh^Op+le;&Nh)Ln{d~g(=vurBRY3VATymPKUi)lJ+9grJa({#8)kk1xkj}lF%{Vc^;mc?^8F2;2FC%vi1gcIIIW>`6KyyCOw|-xhWLzL_^_pf86*tL%@-smgt21 zR><)Y4FQy=S(4Yyv?vjxx{0OVs5S^MMFK?8XL1HWI$%l=CY($9DEb|ThDxt=4sagd z^y9jwxR8^2s}yM^At(5=!S-PR-diJiTL4x}ujk2-FN`z3tEtj-&b6@Wy7NhQVW}EO z*Z}_Ni27XlSv8~Mo-Y;BT{oJop}{T1=ZI7O%+hd7d zeZyu0SvI7%kS#n#X{aR6bddLU=hp@na<18t!jgYEb@TS>!Nq)Uc_t@~M#_b}zke_v zKAas54DT4u&yEa-8x6E!5p75|x8V~0BfeSC@}xE>HF7j?UqtpfU(U^zd-IEjs@rZ( zFZ-7YBeTx@{GcRWgC1oMy^!RT&ihxJg37i&@>(K6%+F4Rx{qTGyGk>^VKfI91 zEF7-;z+sHO&sRh#+E~#SDHJ03vz87%eCXiA2m1OBJbdub!v{;Z`9_aySv)lA_m3W0 z+;U{p_m{aytXPaia_Aa(Hiw$_INuPyCKZz@G9|Q%{~A=~Jn1s{9r4|beo#GR8+`qQ zO(8AT&CV#`mSLFnQAMUC4Lp#7sJ7dOhy{gLC|-AGEawPzIy!ruU2h&SnjCL?H-EvA z<)7{_Q&MJ7T70y2X6&c(BaLVNaOmE#pNazm7&T&VdVEw@~Al-`P-bX=5KR4)urawzoLIGtB=U(ztz*JmV>wt zb00ymVD~Yc#L7!T)=ssxX#pQBuTA0fJZEuQ;>W}Zd>QlP_52>B{lq4<_ftqHm^?b4 zY6ag*U%f=lecpenH_7^G>QeiOn#WX&htVl7T&a1CabxuW`1MNuI^AcP>Vb*-EQtFA zX`FTRCH4L<;rzrw_4=(kx`XP0iTkXmbgIFuj5q3mfi7C5n?I--FMhYC{*Ion(YH6z z?@+Jb*+fS@6>*<+l}^v6dYRO3)RG5XeLnOpsu7oikDvhC?5&EVX|akmkJow9qQr_M zkC&25*ae%M+r|N`OI|yI>}QhWVb~@lCkazQo*h&lhUBF1MVY;$r0WWMN7m>d-Z4#t zgjLho1*DnLl+@SnXoeyGO=;TJaz3hAc2IECGyX|6@q=o6u47})=`S|X zX)HMXw@q}^J`nWA=5$k{iB5B$-N)3`L?@ZR@6T%0tL-7#!s#!G>w%P$hZtUMj0H&lbwJs)#GJpZ@K@6@qa=g$#iv4iU8Vk`oh53eQ8 zrg>D)V{cSeCmD&{WkG&YC2C1NJX%*U`T)7puO#V;fd#ui>L?&%p_-3*yL&7+--Fk` z33O6v+@_j0G*5^(Xj@p@%Ujx}`B=_FE+}my=L*LKYON#*LDn1919kAdoE)T-FE7x6 zO|9MDzc3W}9-CM1ui}h4s}IecL37K~ZZXl^Rli!Ihvqe)Rx;&-bmQIA7r}yx4nU_O z(3D9S*OawIoV82)Syc)9emd3{0dsIr1<`j!CBhiJof@59=A^wB38;gA2*qWQq7udQBl>eMx8 z4lrlHtFpP3*8KG?d2GU^$UPXa8p(^uJu@+A!93OnD5|J{=m3SoQYp)gd`_gN;mi`I zvC*j_1Z0JL2hfFL)65GF1SlJ0IuF=Ko_xhu@d1n98roSa%vJn*clOcDG=ztJjnBkV z?fJfNAo`PF*%OZWa<%Bhams*(1%!#k@-dV6}^HoG5k26+SW4xFiGhOR^Fe+8ch z*=G~hnbdXypL^LEP^x_?BC?u3s`rsotd);>)rm9BohPJ^HlQh8k9@tF$r;oK|eHgx7T)xAh+_N1^c zHg6?ih4`LLv3bhBz$SwB!h-Ki}0n8_?29Ur@rUezO= zoex_p`|jDP9H_nXo_&>jPhEBFH`<7j{-0Y8DlbFe&VAncV*YB$)Q{rDFj-){HWjCQ|m8yy}d_1CVc;r|VG zR{a>BMQ6;LF`KC^*uez%5YwCUS7uyor}@gb+77P5<^<14=J1*> zRk%1M{H5_XCw;4Ni?r6bQ~KPQGm`7ByBcTCP+P>Yma-U|L#lD-!y*nr++S`_rLJ(`_Fvg8)sO1#JWR! zeC#tuhMjk8h6jx1yyL>ZOp=gR$1zb9=z@Lhr9NG=NM6WiSeB0s3H|bo(Ipp zT7SfzqV-3UU3^dBv#S%ci~BFgZ$aKc(hfv2yc0GLR+V6IpI{Dn^Puir(#uscSKmXjxQyt%>`M}5HJ#b{J^FbI9o3%}8jdC&! zCDteyHnJEpY$cFh+0WWk6$mz^L}xqsRffsmM>Q_EKf~vZUhRkno$1A+6B9UF(HV?8 zuKuwr;Owx4^TA*~Z0m3aT(=n={o`Bm3%Belm3G~-kl!-i?=aqWLuj}@ohfXshQrmZ zh0Jt)ICKN15$2HrJl`RI0_&6@scOco@CRyr(=c3wO?0uNgk-D^p4(1nbdnAH6UB$g zcSJZD^3Y-ywJYM^K#~bHR}5LVPx5!)(rs~f8!fJ%eez?Ucs%we@mr3R?vYj|CICpKokI)37lNEc16YwT$Bva@H%IE* z%F3%F;Ogvj1sslES67#-_hod!THbfhuFLMetWdx|m)*O!?_OVZ*ZBC(ey_KG=Qu!l zzMt_KNHe}oz6E`-qZjH)%$LxIC<78YBC77S3ynyN0>?K*fr+!yp?AC~*Ximsc6hq- z_rIg@Ry6PX(#PJPU&>^*kV@FA>jz&O$P~z}}IUhpIpD zN)Jl#2wof;(u~yj5^4g%k2obyO9Z?o`Q7uYKGaM~j;-eUmU|73KkDjncL%+Q+u4ed zp(&f8+V2Sa5pT3te9maEy=YC&!H;-sK2;pKym;l|-JxEO`9ynHy0m_~Go0<&TPiq` z!|AQ_n2x9wxI-?(zaE9p>x^OvUJN;*MQ#OVo0*0gh(SuT2fP}>h&oLv=J~b^Xaoh} zN%%auo=*WXo4AvU63GR!P%AS{RT01uDpHim!U}SWTIdwJ67dy2vrSKE5drs^s%7rJ5IxMPmP!f%wtxxKE zj;&AL_f6}OAPnpkCOPH0q5QtIGIn$!GdWx-Q$>>D<9)T**3{_0)rnMJp;nz(imqnH zMz6EFGh>;-8tkaCNV=AAM#5M4+(BQ_aNN)n2t?eWBRQILdx6#Ik^dTFuw7Y=E&0rv zj|+0P8A-}l8R2nwHWwL8q%dN`V~d9%yU+~b^upYO9g!r_13^o}X_mfw%G+xRloFZc z(PU=pb+hitrKOM^aic z8stLBUhu>MOV)60t#bZUcF*pWU^&^@al(Q-v@KtFSzclLuc}?NRD%%e2HRW=q^&b) z<-tZ`VbY51OR|ar;3;|E=!9P7JF?l5(0;j3t=)$7F+LF}k*qpppaqMxUZ3=5k;SCR zV)FF7#n|xiJbY(9jRn` z$F?oNlHhFBm*pAE4UdL76th;F7ebw9eUV{r^Bg$R3ApV*TCx+G1No{cQUu)~>xR2a zg=+Np;EhRs{)vAwSO#Ohs590(Si1cB_)||@WwcnN7wy?}N5^elmaA@Rv`gFhdYeIP zW*Ot0ZF_?vLqs#QeJf5Fn)pTX0!Vq$nrA`tC}Wf}pE5=XR6@>Asz<@IMFY5of?@9W|uYHJ22X9@JyxL>2AqrdRG2a z<43hZydVwr9X)&*Ff;N^ruI^QvDE39xC+ItC9El=Gh;q^aYBob94)?NZBA3Q8~8fe zEFx>4ta}F#(^zy(yYde$`PyXUUEX3g++oaOKeojCX9`OX-f?3&mN;yJ4KZSGOov&zgv>sNFkei7z6UX-DI`c~k;S$_*3cL@&P%=} z(A)&v?U>|rTw^gBkr!ijSZyi>+buq09t443R=`x|3EH~|>9H|fW z`tte30|UzIV1NH0{-6?HIYkvkl~?T~CaJB9*#s|Oqg1W%--8WTvMLEzO1eKs+L7ev zS(qf_V|;)FlyEo+1BV6+@E6*4We-#Nx%j+L7{R&Jz+-fn&vsjmtxCUH$A0STK_uVR zow52$Q(4Qv)M9l1m#^-;_6xgDnoq}4@3B71=27GY3OB{?ZHuy;0{U)WcX!k%P2>CWU6lb7}9%NAeEo3E6u z@!2C&Ge@VRcgWb!jNUz?wLKHD+vX<2Ls{SS*4ZVw`kv{S%*??0b!d`b^${MK5=f8E6`PAgC z#hBmJagt6?=D7_4wx_C?ab3#`L1RUp4=|CGS^EMs0R#dB2L2>*6WCL4@NJH|hUhslM;~h(S&Dz58x0)%PQq z!Wf7Ag?V`axS+EUxC5h zo=txK-JkpXAKhj=_{UE^_eb{_|Jo|;mFltY{9WVe#`zc>{w5)(e22UUp6A>| zN#nPstSBZC3AA2t){j@J4nd!lU5J`TjvOBx(39lrXH&=QVFx?F`-tpnZT_@-pC8{b z=ry+gfypRI9j-{vU4?wN=K+uF?;@T-b}V@&d~Pu)K;xp)~q z<|O2v2Lsf2#nw~&LzE8bGLh^W~ zRxH{^`@ON8H8^p_!Y`_OXHwoixQ4cSjmBvIWRh^Q(ziV+;JD+tKt8+LINo2%jda_5 z*;>qol{<>QlU-;2gp>kqu_fW6g{#KK5k2eWb?1ndO z3&+QHl;^HlOx+<%zEaHAIkctZmZZw7-;4|`W)uBBOSR{atABl_J2|&AmftcI89e;Z z`covKe2^ovvJvWkNvpylB84rx%Vv^SU3mY{l2(@qHW; zd;ZF)xwj7Q>EBl!U+s8&{)&mvy|14-wwN^(_Y|b(O8ZLfORHO_s+iL7i!=YQVG5X} z*Mnd-{+it5pfjHnqu;^lF-~W`4Mx9<)2Wm!uBY?*LX3Vlr~h0>r?bRmMmMzyI@62U z^$+mt@h{zn&a?_J`oo<58y%h9htW-Kg3jb4yZ#Y=J^tOKJ*IK-+zt0PjnjRYELvc8 zdQm&4tOX6DZO^(~$?sFN0uc_ZY|1%ti~JHoEOTu`NiR>R-w{rnl^cTWLiuC36EAMJ z+YHi|KbqbWiY_EBZoNBGiRd$y+}=Xw`h`nd@qzjvIZ|cR0^Y%}pB9+0s^_i6OC=Cd z+C0}5_-BZ1u!;$`$rU|F{7ovp~1l+{5i7o1L49VoeI2I z2=&ipWRraLjzv1*cX3DK=TCMOr!T82M$F*u>AtSg9{6h8RN@Ek|ZH+p5?z)r{AgQ&WkNpNjh*)?wU^_tzONMZL(u5b0)u}|a|huxi`LE-zl7FKE-ZL#lQ43`RB|m4_yK_; zh=J46`x?KLfAgP4Jvu3LI5zR+a)uA8skc4GXU zAN|7d!K-LJefmOH`ly_cvxYZf+~?cO2CQ4qpO#Y62W1$*jNUJ3p91X(LHitQhJK+EmA?fmW~sG&jKl0hQISw zj=JytAC2$OvtO3W(qCZhLu#?#{eyH+x(Bg5@}X(ZV3EQB#LakA48OZx9+O_6-aa@nw0eruaulLL2(mxuu;QMLD z*KbHqN^g<>2-4Dr@sU8II4W(7?NGTpz7GvRXmd>cw8@Q&_C@>Hac8*4-{YPStM>#FjNOwAqE2y7iB`C}yGjQ_(2v#*Ig6>FQ+m?ih~Q?U z@`}Ol@_EhpIqvyA>1pY-{DGEvRQE}~iMvD6)8BG^oBAu}n{1Z=RrdErPqcR^Tg=&=unB0Xufd7^3O+E#C(c%Gj3)L4hdn2S`_aFD7SBt9pPTiM0wHAKP@!OVbKh_X-+%GGIn(IdeCX~8 z>8TBU%Y57QEjD%^lFmw>l;4k;nTBVT&Q14YCXthf&nT)xK{?j+EV5k5n`*@jqo^mD z;ZeMgVFpX^Z>YX(rJyOKvEDY6u5bo@o-T{kFm28Qo7Cg6@b`Ch+8n`5_xjwTJkn+D zvN$@csjluWi?eem`Jsy3(a~v@#|`mlI@8o8&aapM*%Ju&O8tnp+u~w~66&y^8XY%);3O z)dWS6q|Y|KeXx3PA(xpyP`zU3#OU}qkiuskaF@2$Ms^JNP8BNUG__T<4cJ2X(ee2N z+6v4t*8E;J2G$D;@*3LS1Fr8?{E$LRYH7QsM`>joKLZ9R(Mu8xd@^$w1tsv3D`c1g zIru--$!(`(cQ-b8K;vx&zct+HcDuXUtrm+}+P}m4VB?<;S;C$t_n6G)_Gi9-$PgUf zJziW|T&cYJ!lCa!^NehsyDlv~7Af^rSbredHT*Dm32ve`En)ZGuJlGIfi1mZF`f$H zmY7vr0skowOOo9!3Mmo7pN|RE08la^J<% zZ3WEIYEzgfB1a{ly}VWMMYH;;WQBo1t4V|OxFkYV zeb!)SkI7=TdD{c8dw4E=dwNbfcwfjX%WsxVU4g#%doNsgZ@e$iWdcF=hVE;8NOCoP zMSmD`sjUnfr4KwRYPk>aC{Uz*Gae}@ZyV`ntXEXUkfZh~xI}rc6il)+6g?>wY91p^ zRqccfp32h?`p!arU^chqsI@qF zZ8Ba)8TXsA$xI>?IF>6O+10<|HrjTK4{oc%hpgg+-I|Z-6047Dp(tyP_HHtDX`HMW zIg*wX@#APbL;$LFH>Ge;E=Rjz<{_KOF!I>D`HTF>Psi>Z`a@~q)zd#6J5zhKah}%K z4CbHTFb{k2tGJih_$q+F#Pdba*TM6Ec2=YC?`_6&?zofCG6}wxUNtJ+3(gzaa#ITE zktf0^;5^g|AI&sE5^grH7SE2YIn#yykS%2Kci2t7m}~qiANb&e{K$oOCdxrn>U_u` z`IEOb{!E!G7ycV_1^9c6y^7%zKCaE$tz_?0OO(|@zAmaI1VNz84ERHsG{8J3+tIKk zkZ=UryF0p^P8SOBIP9I$!LyfJ+%`wDuWmJ(AC%?J*wpaA!2<^e2*0aXZ zMm#&?Kf@VYn0#o$lq=)I)H^=d&zpg)7sNp$efuW`a%nWGH6~bb35xXXg(d zU#l6179V>qa)q_se4oJ-aZCU5*~cIMY@=g!5Bc>RXwz2AEfek?*6`FVxyf375X3X` zU%23=%2aNA;+7k&1{oBJl#!exOduJ?bQGo=Kx$Elv)0~%4u8kdfr>PQgPOi|)9YV< z(`ougTE5FA`8wyOr{_8w|K|Gc0n6Q|ZoSj8Z=dDPTTk6>IRO4{#D&jbKRN>bTHDqX z`Q5UX1;e%7NZVSK15t}f@Z6!*8*1UX@E!d=p0_rDn+lZPB}RZZhsGg%&+6&bd&aG&bPeL8f&4D; zU=%!XK#x^XJR&-?ndEu8%>X$=cvhaX#mB{mapBG#y-r0M$OfINDE;{(QZ!iJJ)KTY ztXE>ba{pB>*>UDqzJax2s?_=VVigLLfz_F;p z`&c_)%PhKdD=*Tjm9u;6M;0=<#VcyNSH@=VTG`MX^qbC;i9r_?;JfpTQpsg+-3yv!*?_#H&SuR zE>{^TIlKEktZxQ%(2aRZRjO3fgb3hj>q%dui)y3Fm_IzfNya$vj7Sq+dA(FRnv!}0 zX*Z1HJKWq18<(7h>ad91-?#kM5C6sJVs7E!(9i$p+S=IU8wTWLn$rgiWILMnA6<%Zj`f z_=8pz!n&kW;i(2AKNW-53*?yxq(_-B&mg*|5V=txiX=LcUK%Gp*`y~5L0>miacg@q zW$m?`eOUVJpE}dd%u+4p&yQNWZZVnN@nChpXlVQ^t^^e(O)Nh&W zF|!dFYOH^C^ly}{8&&#UVlN_nQ5hes9D!-?LBB}zqM6x(woocXLC5u?YCD55n5FAx zZeFhpTz1R!^wsh0{*mOw9@{_vxNChOH|^iPZq2UWbNS`>?I~0fM||P=<-7K*Bm;+z zvVIW0BFpq9JRjpmcBek)k$v8nCxYw7@jD~a*RYb1^Yd$bUc|WOP}S)QWetkWXY-Mz zig9$NF1!b9G|7&mnabCrQp15N^bjNl78~9XzJG&0Dgn`xRaM@2-CDY;ySA?N)xPgrcUN_F^}eJ#onDge^pZV<00F|9fItZQ zVptTy64c0`1Bxh!$^gm|9dT6L(2vh?*HOo921UggSA^>CckX+ysyf{Xj5G89C#k%u zx7~ZsJ@@SA+>%q-8XaCY-#NOYB3z#kS9PKWdNfTv$-jg zkE&jh$V1defg^?a1#pyQa0^IoA4<$fMH2TwOL2*?r^WG|HnO zo8_S+Pab(tFN>p>AmyIZU4^n=3HckiF(t2qIzbaRe57qnkC8xu2gp4{VJS^8iqVmb zd?d(=>TP}csfaJ8pVHoz3mMSW4;?sgANr_4@GPft~6HZ3eJit`HXPPq^C)m_gOS-}nK z;1;uIWqlmaN*j6*2NZSNlB#5bZxAeeh;cS9*5PZ?s=o61`({moS#7YH;?CI#Pr&Te zv^EPK-9Z#-dQr^HzJ2FH6SQ1))L$)%{Ug5MQ+2~PTZ<7p31tvhzZz3dmPO)qw0^>f zKB6ptzx`T$^|#8~9<6={8PH-~IsrJnvX;bZ6t*!2mnwBCfmrpDqC|bDmIP5@am`l9 z<3|W)xn})(_U`JdciqL@;~JK_>e1=yztNgvSW{;L_FamHWXwL1Ojuu2(jtS{C2DqJ zFBpZuh3r8~Jb??*d-AmT^?a3nik0ajhm zeab8ekR30u(vDY$ql87=3n=Djn29m+5mVt(Q7H*v?6f4Qs(h;y52u@0m8U3yoGOVg}r5sbOJZra}grn~fx zSOF$x^^Hm)c2)IZZZU){7V|^)n^r|Fj&TLuI*I*;3}mv1LuTfc+|%%)DEQPw8PTUe z8kA_)*?-zcl(!*ank)$O?inQGzmF2MkC#YmP zZ4PLY)~$&n@3Sz$pom9}T8sWBQ0s=m<;#Y`7w2~?>r5__+Tb#bz2_gF_`s0f1?KF~ z_rCXu%eG*79`cj|fs*GCn`Hx63Z-DMBwShjb9~KdYKd`T_0Or zkT|i?kVJJ-)5x820`nnvp0R5j*+62rA9f3N=U{#N$qVA#Rrd|v}VuFp~#)xgZ@OT^0r@-J#+h-r=K1xLlXZM z@b`E<5G^RTa5?+SKoo(;9J)#-?i_K&FPjVgZ?_RMWZzZy4wRmf6wNgo?WA{0~14QD&DAP6NPYr zOhc?zMiJ9y1Lum@X_JI+DIGJzjj`Ypu&YsJ}qM7+!`FJvS3VX#EEXG5<2DPDF zN>n1PtPNGxT-9&+-A*_+NxrxQ(Zif9PdNQeLc@-#jc1_rMWuAkm}8IDNW4YBPLHWiD<|ozXmD!S{xnVK$1gU#a-<~ ztmbHcN#ig-c;UB=!Dh3`)FiM=XHC~sf5uumrhKgB^>2TAx5k!UQ~rGQ#@(NO^ijfZ zvO7gN9!EGllo-Tj#JK0{6*eVGz51M{YSKqanp1Qe9ZjL5Iq(?j)W`R)(IxT0F+MGl?ItZC6$bryYo z)Da8p55yd!c|F40aMtY7IWD?+B(py=!u0)~R=CmC%5>j3pZUx=eQBi{F7#GUfAtS9 z;1A6yL+mMHg#nXX-Tv<*x!c!J;=E2*Wgnmk*Tr>Q_n%Wa1=1f$%s#RIT(W#121iuc zYuL|(feZV4GV{^#!F=KJeG45!*@<*l>HLANZ6ncmsZvgjpK1tXPVu|^UXSyPHmA$( zJvAJ(M7rX^UX$9`RZ8?E#Tro%_R-M2s0)MXyijDomlpw zn^a~tc^G~#LsWnLO^05Pazo3!{$t|o)l?$@-m>eyvR_B9!G z#(6`N22S*Fdg|`!YAd_CvahnZmG=pj97Ii0EOITs`){0gSOWRHlTapqL*6`xGRK9w zNJ$YDhyj4}A6v_CSuLRQv-rb(%~l2QRQmXY{eb-!%-lJD5HAq8x<&i*_ z*V`3%q}qC|y}Q515uOVD{ojYCLyn&QZu_--JQElX_Ev|zu2#G5q~if`mGIzARAwqi z9TP|1cjU(;F{&!XXCncap0fGiX2i_{QJ z7cmpGGl9DAVmt6uLe}i{Mni=w?QOqClga{}MSsz8u4OyP30tlHpML9@hl9ZT2J~+8bGjX3zyrF<& zFOCjep@eL36MP#GS5&z|E_+^LmLjsK>SKclMY&|CZ&a+n`XM^EWV46X;rxxp5_gQw zy3?ILchs!8N@L9l!D7tjPIn<=)uMT~&8)K_TQ&I4o{-0Hvss_Mc3N+H+Z9wiyj4GO zn%y z@$4kJwoLY9+w`ij5)(&mI|7*jcz7e>A;bhUjWsijzUa`ly-v#{J*eJx9oJ5*_V8GV zG6B9GD}lXTE$mVu8ExCp6FibD$NWbg)~Foq8@dl2Dx|gFtU?K--wflUN?T}_;r1ziyAs4&V=Yg zBKqA5u2QqWzu~GE<0PC|&!R*^o|R`Y) zgGDhC)H4l2Boa5q5^LIhl#3Jd4-NTQ(~azv#@_v$2r9YWHNe0)TGHXAYc zWIYsRo#SCOcjTP5xxPrGZ?5f}Gd6ENV|iCZ94>=~J0QcXjE`8Y7qTp=hnYZ}IX$3- zDkY#~@*X+MWCJNcLJYkWUDmI6UVtF|@#xT;;s1QqG~GL1915P**L(K*Tz2{_gFm*} z>S*siqm+qm@z+|Z6r*6mEt4NS1Yu!n*MN|4w`a)!z~0Ng>BCkB_Kl zXtCQycNscwyRB^6xn^e$zFMK_wMU&yz%-20~+#Y4hgUgE8=2u7gp1d5SiIy!)~N2l+hZ5Q^uKj85Yb z_h3qZC%4u2mGzQ7;%&%ml`y%kVM-nsksqVu+?ff^aT%Q<0e!XMi+O4xd_Fuc(XE9Lqe6f|L@3 zQ4obLkZz)BZZaS(y+y;khU93`=PQmTZ!T$?TMVPjp_!UO{wJv_f&99|b2ZA%t{%E_ zXzlb>U@xFUG5j}#v5{}QHnx*;m*sI2BC3-?MHYQ%gk*t`VQnoDp@5g>ihRyKB~lm|qK@%<1AdQl zJa+TBBQcN8bA6Ye7xmqj3C(ey%i^R5b6FgEFxeh~_tTI|NUzkRvN-UT{D3Q3k{QS(v$H|=@FiQeT(ZTI zf><&liY0(wO;2O6Dg$mLPfvqhtc(GubAdXTj*kIA9UM;mm&E|obll}J0N?tDBh%Pp z4!Ui#!?|_@F#xV6Q?uQvgGut2@eRr3`ozT6%}tuCcnHAf(YMRdw^rqStN8y{?;B0t zYX1MI<#J|l9B6)xz4B=FUrCX~K1X;r**I7F|5tlAMPq8DvDTw8DHeiaosaYXQ@JD_ zB1cZ68x|JW?XMm^`rKO0FWz$T^mEj<61aK>U|w9|`(M#^9akmf<-Cfbx=-x;7t71( z!TMJ7{fiqei(HOMj5slXD30X&&p@#(fS}ZU|Lr32hc`(yBQE#-pTOwIJxsrkb8F(w zZ)|rQ9yC4rC|MRyY_YBj=E&1$TOWN;6AGThAUQB)c!=<1 z1I9a#@%rmkZdX{%SI9JftDj#q!BU!y80;#$9>}xHXMct9k5BV=N|((ZSz!P?bt|Uy z`RAA00Pn&ia+(7-gK`1m@~-gjub4-U?v!J;+`sRsS=gzbV%@(_lIOFa$#9AC2_~K< zW&`nfcb*R<1tpo8K*RdToy=AW>HX2P%V`zh-8VV)!fm(gEkUJwYDYLF=(M*emDbSO zSIL0MV1E+r4J&>7^}e6P-tf2k_PO1S+aWgJ#!YXe{gU;KWWGi6S76~D@7J&QX$79t z*M;cU7uNyJx)_E=*iRcGXd27%EH5Gpx4vDIpY95@&F<~#J2f;`sSI!2FqjYpwz8VIa9lO3v3Zi=!oX@B6l&hGjqR$T=KY=R8yXW}_qPaOCV8m#*RTdl=)I!njt(4b;c=KM^-@ zoGA?@kx7C@lquWmh==m)D}f`K4vW_Wqu$jItJRLS$@1;Dr;=*bHzng9P`(Mb$54n>_8P1c>JH+ox*M19JJ|!PG?vvzM%1@gk9fv{b!E;={<@bsD z?Oz-8+X%n!NBlm~?}Po$B)`ueB{`VOaa<41Q9BS$@CWZ*Cg0(=C@ zU4{fovSeM;lxlcWmZa#*7mGe~mv=)AZzqelEeu56+5VU_6|@F=HWsrzaks(i9E}tQ zLM^svn{RYOWN3Ra)t8TU4)+>@JqxAGXep|14aZYLvJ^C{l$s`;<~n1m5-yi!ZL`_t zw&l*9>)bLJInXzl?e&<}c9*+3e92~3-yaV9$&uOuIE&|x+pkWcUivxUd8zVdSgR*d zZETz3W|{Ix)(JhuayI$`!10bDb^ukid0_KKd>iJ0%>*k^Ng)FTg*NLbiV5FIe2emW zWKo5e^F1%_rFzYj6M%{3=eFR^E*LYWxJUA>SdMy}8-r^R(2? zvS(fSh}|B^yQq4)J)C#7n$4|di)HF@gHm~s#m9c0IP<)-Q);)*quy~v$Em}k{B+fu zIP?6olWMo$EuCg=TY4y$9ZuWr>EUc{C~eyw&gCMJTrT|2Gc&XxR6JH?3Nde4;Qxr? zMj85&Yi32fB%n_su`ze^9UrEx8W4`o=;OeAqk;6u7|C*VwH zpF#98eIrewpTtQCmXc`NqW8?8{8*RS0Rj|2op-^s8D9m9&!8uvoSsQC1E`u24+?yCT4GF$K*18}>BbJ{*k>Q)O}S=t>8y)irlZj`eF#Swq$aW}T?vL+ ztH&(WXIy<;63;|a|mWL|NggjZ;YOQ=K;2FM~lz?`fCT!4$8Hm z=JL&mU#eN#B|NOR6DFf2uW>D|U{TSd-N3>ea)enF3`0W3psJ>aAOuKUnef)34p#5j z{*Ae=Vq(ZU>+Yxw#EbKN;l#*d!8_!B*J95Zo7YF$I+C7QcfxJ-m!}G;g@uKbN^=$Z zNVVi_=wrU_vygPGdLQdlUACB+p`(aYrXD`ss8X5v{((f>>va)eF)hng#_G2DhPaOT z%i?39*<9zSH8<70YeO-Y7!FUhoj2Ht{S}6L`scC#x}hU|iZ7OoIU<5_Z(AZ94|ujG zvO<11Q(Ws*w{95Bt!*O$t>k{P0_K=vt7=srCFyUqksSjp7%+lTN=X0EW2R}g>3b87 zH0zXBLV1nkpP~G}a2X*UB~N}*8{87Br) zHbNd!Jn9l+Gk8b1!MV%43vWrT2~Fm^){c}~-7Zh-h=m=hzN&X7T)El)C@NGNN{LfE z@nT1NQKd69XV}P92XtCj`&6ks-$UXK;7l=pVc<^$){Ry@S)mQ~{*b?%_9!C@vCO)1 zAU-tTVT*cOJ2Sq1f0Gc18Di@XEN;7DF`W-?wR#$}4-46j(6>Goe}a3{STSzjbk z3L3>Zqu5d}=FEhZjd>uOqZGup+MH3Kn(Se0CVD~TA7Cd!km6_5LUycJ{S5n;{;7;r zJ$vZjTZXRMK6>fZcbr1Bm)B(kOyjVR57wb7)yrG0t!GgCg*^6peQ z)U&azeM6VOoN(tt*3iIqQ+pv7?HF&(SDYxR=8di~xC_Hce_JA8Q2W-EQX>VIJ3o@l zkGs@{V5$^K47YjNHQ8c3A49BS^_$6*GvIa@?ZsdQ20Owp@)dXh3v(lWrHN>!6?I5R zW)dz-5rwBDF|x0=D$<;aQp}l(Lnw`JVh*94?0{NI$f`yeZgC$Y?3OMXe-NxAy6Ee` zLG>1of56)$1Y#=zw~H;7q0O~$d4tR`^{k?)2o0Eqq^kuHckJke?j@vG!6qH`2oDBf4c z0GXGlB28Kw6}>7bX`60T9tkL$lAUv!atQ7zZyiy4RywK_GDd{J+wQN9p;SY*YP zr3&PMgDM2MG;_BiPxR9T;cbaC}!etvR|uN~6GMt7W~i}i)r_~=N8qzhV! znWcvyU(7%+>6h_Yk}uH5W5mdC8)bBYsbY~6Tlm`r2~N0}aB@K+(3x;Tl-N$9L_C{z zMqS3e#Y{NGMG047B-1%5sCB+%DO8x~Kv*ASiKWMt1?3tpOYl*U9!At(k|$~-!4|0K zKa~k2AXA(&6iYMmy)A9pW1gfp5%kzA-Li zp2Rmev;^QAW(Jt|<`~9*nN9dLLNH-p#wL8Flux}1n`jQkGCfg~!ISZKbynX)(umLA zHq#r4c{*pyrTOjvv58aPwk?a!%DNfRPTKG3cs_yAN$6RZ+usbI5bXzKof7$kykqq0 zd_v$N0kMfBuiMU6a0z?d{6rHm3HgiRcsj~{XSDohq^&ZQvsDk8Eq@5-yVp~Ri24|h zo`65BrpK?wALIxJiiP~&(?5CU^)v;WFb^bv4f3>}|PGSd<17I5Y!y9Ow zYxmEt&^m`ViCSmxo-G@qot31UYn{RF+4l6};$pha7fA0sx{BVpIt)aO=Z*AEF>RMH z_J2d~OeaNVk&Gpa+A<{n=LrNui{I%9K|O=4YjDx%voCqFXw%VqiV8fv`sX%*@RLtp8W=)&>w7J5Rpf-lm zoneZMWjE!zl5NRks!)9)opFXdPNS_Wlwq54aE-m_*~r?cAbaAE7+oM&`< zh3l0}@igkd->>))=F=rheT~DSg5^@usATWJ&IZGlK-S~Q1}wvd(V{yWvRXq~cX5>F zR;;0~_%>ii_32HBJ)pYwLUNELn<#!ChCgo6Z~A_G6nl_p9m#-oq-}8U-0yA{CJW5y zNx0j(cg*d6D`a8bw`KMCZ{WV9RqOOi`-yK;Jc*VCvS-4DQ){hsg6}&r#bO4Z4<2_k zRMP3nY9CqyUj)qVM9prha+a5&wqnok#y}IQqOAZZE2?Bkt7i?JdCji5TVrp}_Vi@& zSz?|;hpNA*{-GzIuT=7R@}^LG^XyKBr{ly{nV``7u}ONFOgM1t9rZQ5RSCIo@Nnt zyOP4PXnm1WoYt3!QQQwKEiabu9@w%q(b=tT(WgpXEV8(M{_50>Yph+>ktxs|V-E_v z>+kWdR{k!k3`_5_CA%tEs`a(=yW}}d%`NFtSEi?bGmFf$?Nk-n{ax@UfFQRvL9Ql5`5}?5&%T@!C~Nw=_4M!y>7x=chMS3Yns6 zCmBhZ;$sRoJIa1Uv9|GK871@uw*A8&9=!Hi_q})DTS53L?s*RPJS^T*N#d{IsN#mf z54&-_a_`-|uUUm#>1RJeU+jIJuEM{e^w|a9)A)TgCGOEbLHjrPC+6A9Eqy51s!$-pM~&OPZ(8_39fuYqg$Niurm%~qDPbRF;}VN@LBM+k0cT!l%XRYr+W*9Ui#43-l4dd zeU{zJVPOed-oXkNvsCpv7@HE_>)q^|>``3P0#djdM~%rF*?jf&C!gHS)>oe#e-8IC z#T9tR581P{{wieV9sUN#o&Bm&qgyl(z9Q@s^%6@?Bhz$_$h?kPvUsS(X{pRD_ zcB|Rt)mzl#kMVcCL$Szyz>s%HEtWJ6%{x@|o<+6?@8o^zWJ~Nj(!2N_Lo9itiXE)p zJo>SZb+QNX+JoD+i~X8MzwV`X#Z{PS70Wz^_sp{~wYvIAG{^haj=nuAzE8X>S&6dD zi+GW8+vDx*a@>2%P3Rm$ROBLH#ru|LWaYkMG&F>m9px(S6Vrl#{S+-AC=%aK|9~fpT(T zfnQrXW67=j!_s#^PZgpP3{NpU86f{GckrdN6CLMYaBf@Mxfh(@kvRLMe;XJY^(LGx zEzX2@bZCIy{qdy@?0ZU*pNJlVqHvmoovO*hiMQ~e9Cpj;7hQDv{I)s7VdS6K^0UK- zf3{_0%dyM)&e_dPRCv!dc+dN5?|~hLzXx&?`LM~sf|9Q<&gT)!F}H0VZ+l`SyKVP5 zeU}}>i|BpSmoF~uMds({fc*mCMiuO7C&6V9MBO#YlKLV`J^l1i)y|pMhi5n(6npXP zowaAlw=0@Pk?{v}tO$Lc?PuBh^wTVLbVm8y%xe#d&z>u_TY-jn3^JeSc|C@R5(Zs| zdH_p0xHS2guwNbzyQ_(n+*8I~^;|fFb6#>R)%F13_A;Dj@87*0n=%?g-G_`sishNCFsaf4z z>M5*GJG`w;Gw9hl=>KmqcCr7^$k0pbbsY+1AolS7n{bVMWQ2`U*;krrvC=t>h3{s- zLst0I!+l9d3?_O`I+%1etEsQ*W@j>(-hlCFXgujOjYos=9Ob=CuP;cw%+I8FF9+s4 z*e@yE04#@>^Is6lOQTY8KwDZhxm z#euVk8^d1`W+_jP%45<|wkuJEbit-ABNk3uaU^ZOYkuH?=F8|m>?5VStob7!X}(PN z`m4*{OSS)xQ6vi1A>mTJ1+q)((E=T*CI)S}PMLw!A_d8kC5s9@(b2)>cWSv(YhIu} z2)qxqe(=7a7lv!DF^K(PGgYBE<1}Sc)&CaM*}q zm|H4H`*8DbIaoxSIo5L`NfI(}9g;pA!IJbPhK&Q)Awf4`Q%4HgQUUWt!*{ZY*(>Kp z7EAp>f3k0FUow|4nNQi&yE8NGD13VYqHh{gzeU1lf7-M;h~ z)fa}Gh;&|Ann9|i4fw}G9b48w%-GzK>Ad^%{=O|eLz~LZYESi7${)NQ!@wagU5@qf zugc#bw)C0XfrqMRE)mZU!N)Er-wV0#=A{ETrB&UGxJCM-R_JhT40@9rcr~P$uIHYu zs88%6Ma83lGDW*80hjTi3dEwfoiLjs<;Xc!z>(5V$~by(9L6z(<2Ye{qE>nuI=1YY zUZ!x_-uRZ8W>+-iw3zIsk-$_kSV;-7bU@Q7X*Lf_SDl8{t}eB$>#GEut`^f`z;BBd zgXO8g!E{|yWBNC^fy0gbUNYRWpu`KZ&Y2=GA>**-rODBWoCvofV3r`*0V3qHpmjtM zRw4{@I72y!MI5OFU;K>$!B!~f?5vZHzWR5|75Fz8E7Pyg@I{>QNjO7er&_)g0myx( ztD(utp~~n&=#j&a2|bE$5hUJc955C3LsxlGyOu(b5$6aD_V)Mfo03;hvK zs*rHA?o?-ID%sh&^uC=tQ+mM@vZu2C;B=uw$POga{e@^CXs!OCD?_HC4AnYODt2O@ zP8VztG>)35K;$bEIoLxkN z(c4ctnBSdnFxVqTUmpzQM=-`$l+OXCBzGhJ2je5jk9HV~T1aMu(DynqP=+jW1?0s~ zOZV1gbW|BChe2H-BPuVNd3}WL{o>LUc<+_cy$up2=rCl_{ZHSdVy|x?K@{)By?55` zr8C5rxwM75_ddPT5evZq&;(Lf!Yw)z_>aMp>BTM2vdvCdg?YtSU5rts!HF)Mr%*o~N?Q2rRoJo1S+DM!6i9utMM+p+YjQ1?pbJm7@e#2Qk^08xMPcYcCu|qlzB!&te zU;9ubS+-a7f+?O%gl%3^n^0*kY`Jn~=88@E{H7~rX0F^)7)Va+864QNE|FNbXJBy8 zL~`0!n#||c6}^7@fZjNeFZCPsV>T$a>Sb{0LR8^4nID}5GRG9%n5j-+4oRjf;gkW4 z2v%J*bBWGId?3JL7U^x`QqYWG>4a z17i!jz!WIP;$1Pzjt>s|J%o2^Sc59C1Am3%M;UM!z&bc5I6lEY?haz;8#ggxSF=fv%|>?SvyAJDjQRXtX=!l#kt?4@E3~-G=`D zJr=#*40^KkpX^-hzxE)sW-ng}+O|fT0-l3dVVYagJ}AYQ0+vV{q4YM2b*3XpAT9Wi z+(y*`NTQ?EQL0V_+bVLODF7OD5A_Jeig(yGE}D!Ajy1Ed&s=nN#G$rF&R*23%e`G{ zJv;ZOTekd^_3m1?ZddjB-EX<)p116#c~LI?iS0sPKL*LDUz9P?S5$B2TIwRZw4Va(kzL;^SBC@RKEI4aH{ zC3TaoWr2=q#jJ`EJbl1tC$yZW6@3_gh>xEl|9V$aF$<=w9_?Bo#a}dA)V4#VP#+}P z0X%G>f8XX(`}_q1Jqu;ej9zW)PkY-Uw&=*tp4Lz?93AhD#`@N$^L>7V#0bu)WxU6C zr2UL{opsic-Gu}kchzr}d{OKV>`(Qj-P%@PF)2i*E}frw%Z9kaGU@iSX`5xIJ{A_l zn2O-izX29hJAYVl;5fQfm!s=$K5_N_S0O_&0|^czqIG~bu;qUYTE)eEgO!b)?&F{p zYzsywdgCjg<<2Z#w`J#B7gLe`*?jdEMXv;{lv}5D0AqZh_Cvb{19mGxtJQAVp^rwK z9>@^mSWHgk+pyw;iXAenq#7vocxh=n!}C@j<6hITW5;$~xa$M>gTpcA z<_1s(>#l%(alQz9$sqMy))*wmBWyopK!Hh;qckU45TS`+5h*a@Nasv2G1$0=qh>z& z!tned;V{f6hlNA)!)G!fcU$*F=-uxQO?2OuyN2iw*_OWmyEpkHNLG|BWst&QV7-d% z=AH=Bp{4uabND{jsh9o6)5A-*BhKbG=%x|e^K86}V1^x~uwF?Hi{jg}xGyRt>$c!p zln=;+&eIw;V^FkDq6^W(L|x!h@xSq`AVe82Ggpx*kwlf z0vY zj|q!dSMzg!uAO_C?ZX>?hx`6gJNHw?AJ}F59BgX@ z1EBM@OTFy7itm8e1-ZW9#qqc57Tit?oX%v_&o3H z+R%ZG{CvLh`i_nbUB3D5@wHuDYsb4ezCQ$C^Y0Ze0Q-Us_%7n89<7S@Io(vKKIS5kz)2hR_ontTi}LjurPx)N7fbhNm`(J-?#bx@irg z-r^mx<^BFdA!PBH^A@J~aFaRM;w>heu56z;KSkw4x^65*i^5Ger)4 z;^gA)^5P(sQCOCDm5cRdgj_rt7E}J2<^hGSbh|v*fbqL|-ErFB} zDOuFEOu(J=nY&9p0kx$R7t#UCt7fOcZnvAAj!${*2D8DSGx{ucU*kOLrPW0%nAYtv z;F!q$X;0=b-;@G83G)c3BGx1hv9KT&hi#~dMzW+-RaVsXSb|TLM~H+pZT+^4B`&lT zq^V4Gg)$>F%j>)}U2d<(_pfgAn874XWhw6PcdaiVJ&yuHnd1A^m)W}+74A{60{n@h zf0F>lru-SN(dfxMv2KpCh07U}h9zfNGZY3LIR{r8lq?p>BOnRg7 zk?LnF#;7mo_eMI}d*h}+^O2M+_ce;dv>eIhN79n0%D)j~33ZWn*%gwH zHb1KP`uzr1ZZMe~%nCx5jyczCvQ&!4OQj@@?{oO?I@S#y7FewpFl6H|0So0KMW(_W zb2gvLX;}Eiu&PO?*Hy`Er+_=3eGKCfV24DPDceRML%BeP@?&sMGdQDYG(=KFg_M{} zElFC;FqXK>hoN2zPN&~9=pRn^j~9bGEA~`8WVAV>$iV9@MTh-c@WKxOhL5AoOg&er z5rTC`Fu6~OHH)wWVMjph-@zvm;(3!K<@sjr72B%Q`5)LC zRjEn^Ar$~wP%7Ssx%@a_;)70C%l~QYDPbbzn;j$U0V^e9ZN(6EynnPtP&G_a0cDm| ztCI~mnmSwSro^#`VRcW;I1u0$>JlVqtnuCk9JsWR5&a}~QO@!6qLY^kv8|_Zo9hrfTx9GgKaPTuuTfbhP4}06%Xu{pO!FYH8+7VNH zYw3gRF7_Z6hoUji2JCE2si&tjo6cm?+qw^IoITLp-hOta`|Ng_OQ!e&p1VPMuExhG zu!cGLGqZSl8=mN{oZa5uePDJYId}2g%dobckEpRX#lM1uWvo^6Gt zPQuN`D)%xABZelHv=jyY6Em|LyA4r)(C>*B+j};md(g3uvMhT}c_nnGzoNSpe(rOy z+g^v=E48ZEYUl35xsUPtUay_|0G@rEpR3l+J%IbZ&dXWJu>;h7Iz3hPY8R;=ZJFKUF*lU6Ib|YUl2PPWgiJONg_CF&l8Y4!=LA{33q$ z@!yB=`=9ys6b7YKNcV#jLj;D=Qw(q5RF+dN>}o|;KM*g;vbR*~+jEgR7!Zoycyul^ zHnX5p3Oy|Xjh#?(J**v#bX>AjR*11xpvM1Ud@ESdAUpC6VacR+F-?=_Bns+T` zikrMQ>In#nNAUiyE58K7jJKb}#j+zY-0lsQM&psPwcY48CfnL#_K+#<8D{&0{7@P} zYc8i{Sg&i(q}$E9VJE3F=s$-i`frDvixz6s9#(wOK3XA2$C`vdJIONNr(ke1!gV!#l3d7)zgZbzj5h+ zB{(_wm46KST20^QxbrYh-={hcjG43&K)GaD7H^-p`WKZzA`$Q>lYs18^%Lx}h|d>` z`Fs)n{2|4k*qwNu#~D{-2SwKa_JA%~07r58iuRIU_}lFPo8J)eT=NTatiM}&@1Kk< zlg&+`=+Eb>Uky~!ZuZAo3rul8`u9hS5fSznqlL`1@JVSM_wQ9+bn#V(_Rr;MT-85c zbIU(nljk}GVnJ!W;TakcRs+=|w$vS&SB&+q{fJL!v70PHob8()Vr;JZh~KHvY}8=6 z01cf587k6Y|`l4J_e$8;x_fNvm>{7Q=?l;XSAE`BI$BCBGtjq)yWoM{VhzzZ_y4G zO&!*f+f3{D)@Gf`IUIF*P4-ro%~Q6~#7(ACx~44}O*Ho*alT}pgi>6z@M~pudDYS7 zZa9>wBUvVwSwNmnIpFuS2kptQedBm`%+uz`xjfE%(4G!E=Gi{4W5{AP8O)aECdiPE zwq9TBfYD^on_8Qj%tFXn7$jVIC-FyBgwsLr4_aGrSvrXR5nA&g=?hZbk=C_S#x2)h zABqOOR(px=vgqH5cYRU$8IE_6!~k9+t_+z~{1xQFM&x4e zCY{n*X8R@vzWQ9iXS9E}`iX)|v}0TX2z?LlfZS(WRzCFC2luw?j5?*xpld(lQi9`A zcgf=^xsO&qfwmJ^R~F@SP+aIa(M2i#uZp&@sF__pe^$VxvLzN$HkCPW>g?tIR%NRX z@0mQZXU`G(RG+$b`}S+`uB)Uzxbd#a^4g#E9YwF&w|8GqYt^YVrY6t%=j_`TX|^>h zbtbK!9r*Cycba@A{OhD|eiQz6;=R`^{=&Y6vB9`hr)EQJ*)UD27g`;9tHz*ld$gJx z_O|KtT4j^IDRssrdT*@o7qw~wQwf$3o0uQ;zoeuzpDf@YwAX9Tf?vg~joj@x_n`1x&bz;%_s zym0I~6wNys>-}5XZ|^*B-Gy)1e(}1os_W$KL)L)2NwP)bh)128P$|FCFM1+J*d3?`8di_AF+u_h-Q$}^0 z-o);&`ck7j)K!7xQN55+B-CH zw%?uYgB;Wp3F`HOcB_yZNhcxl&G^D$prg$1XJDBH9pkB15)m_t+t@d7g2is| znLI9}rY@5L=6k30P3tvUk7vjdoEZGn$3l<>zKZeO2pQ>HSf4Ja(K5`JAwG#lO(J6< z0i1-NwvJxAZSUTU#@M9N8no#%&a^ptI^bS0s#;nMzb@xdVT&1VLg70h;<%~$hfv;~ zFAtmbrhwBKFj2e*QyjsX_&=%*koO^hh=x&OxT3KFjR+2=c4YzD zQ5y#ywnmdVU!)YZL_8x_m){?*#J)=OT9S!@KQ^o%E(P#PVFGa#t~@LkiSm67DeKmD;=&rwOk+;+X20RE(2Ks1_t1%#2JPdS(4@T>g4Tm z&^5^64)26NDirOph*D|69%QAs9h;JQTsfOkx3FW4*aIOJ`HR&yYSjB236s^8?T^Oc zuC&>M)lUtNea~Ro59vIWqymvj#Y2GO%aFzNL}9reAQ^R4+!aO~gH8Jr34b7&{Ol!X zeeGQ3uVqQA`nI_b&HaVsC+KI~2dI1wan%r=;qT+VKo!G9ruYu~GxXVEP>ALJW*g#Z zzVjjW=ZOj2hWkFqUV|1mu*!X5#|K#pdu?Qd-#3WpQ_l(RLxPZWAMGPDgnG6M(9kjp ziZLXgg^!!TP=kV-eR%c(rxT!+7&zr1a62jz5oj`!Tv{Px9Z>3m$+?K7b>rl=_O8z2 zHvF(!<|nrcot{eJ%viA)!)It}zAzH1IOnIfyWQKTkn>meZFXdOB)fU> z^p3r6+2aqp91fqyml-UKY&P6@gEkvlbh`^ym&=zO%nzMnddJ-w%C;HBY$s5&E>o}F zw<6#oL&ofkXv`)Lf@sX9C_1r%0>cO__~qh8sb-8NfHRa^5f;td@S!H5%gMF-8kf1G ze8CtOc8qqeQSD#U=_CD%#ldaSS$odkUeReDzMC<(k41ObXSebW(NTi}(Ftt4kQ=uP(mCU>pAHMbd?;0@q%xZ`l14rI} z>m!dma%8+R&fIPHMwL)mIt&;Xj*4i_tD&F1^PP=-u2irWPQ6 ztyS;4Je8QWx%#`OnhZ@^W7AYmzt6Ki--f{}6}y+djrDW~%$_k|qL{Tt@h76mn>^-X z{WtPOtKc=DI@4-=Cl3NenrNkn6Pg{WJxw!3F@RR-yNyC^z*Z0zW|R00?S)0lE0MHF zdvZH|8;{0f6R33<4E4^m%_WDNqXDlYX72NkMOZ06Vt%!CxO(8!rqsyRuJY!gwC=Q1 z)P7;ROI3YEZ8MzW_G?ZB4i=W~=P_Ve#Tt1YrQN&`0akay9V7QLCu8EI(PYKY?N%IV zvpA4DxYxKn7n-PQ2r59Ogp%VFT2T`MfM?iB{BXEvw7dOwpUu={*)r|Y=mN#b&K9rN zrSs{178otGZ@E@z67uVIH*3$=Dw!eFmA(7Srfg-V=u&C4>I*g6Y_xLTr}8tsVa$h0 zF$?-uQvMQ=07m$N56a_^s;Jl3QXA2RHZdba_Ov3-2i=Fy8d%nb0hKT}c?`;p?@r_m zv>?`iV*RKxi&K&3tIr3z7?XYxW{Y=F)T&nH6l@8tUBDjNHcmsjhA?Xqu_r(zRpR_f zu|!(7uUXw;6-ws&BI$TSX`0@8-35lCzNOV-C>blMIgpEXciK7^-&!`5^m>QhfGz&2 zXBbrM5!JU&>t?42d#aYVgx_`9Z6C7l)$UZCr9I!CnZ-`j)$=qS`}$NtbB1;&Q!CHK z^vU$ILvg7LBWat4I*c0EtR7x=TC?@IJ))izu}aj2VyR3x(*CF7nx#mqDDI#uF&ybm ziX^3|s*FTkY0*Lir6pXm14@FFyl`pxqU0|T*}|Z1|EyP~(`+AAEu*yT;}5E}s(0S4 zatk1~){*>JlhI{dt2P=N$gM`JnKHPIQ=W_fdaD8FQz-jEZz=CP3aurp_<#(D6?{Z0 zT+QjO5!M|Q+!~0GliXNFjHnf3R{|4|mm_gV1I{+%Y#3v1!iU1@vD8;c<_y?vA5CoZaLtu2+5E_i5 z@R%Wzc|~oAR{wn*e{NaacPgnw>U^s!P0?pa^~FJQ@PopjBa#|E<3a_n>*anMfK^s z^mnkUHfcU!fsuAcb}()GwlX-8h`gMD{g=;+Lb;L8cQbmFRD4jLZ7IjDK9agai)Oin zZ(Q^&yo6@Sjgr=Wf`qacdoig=~Gw#Ei^qA zy51ah9&jei2mC{81NXYU&JlHs+M{H@y!F=VHFu{{ud+x_6IF5fkN=?mhpInhk?Ifk z;tHSl9hmo`^6gyaE1ru$Xx_d;cY;??iu8_LwRFLGSXK+6ahKkqZFrYk+Wqb&~^B5fAcMeCAXox8iUzeF9 zou}wix{ua+8AqCZI(A4aMaKWeHQ*#chN6Du#gK>!h(d+1*42qc!Pf*1|p=!_~wKoD9oF8ChdcaEx9Kkn{CQu|E zQ9C;F8rjE*HCX9f?ZLnZ9V|rtS)z!9yKw(P>GaIBpM@d~37RN;^IfBv9h>73PT|~b%I1*i#`K1)O#91Dw7#N=v zp^0z|F1R}Ee1>VB!`xiKjioBK?)(eY{ZkGhaL?4o&DLnhU-FDcHxHe1Uh~)`rl95V z>Th(-@zlt~fTP%1Hk`FtXkFXncYp=@EdG$kGn;Hbbw22xGP(8BdZ#fE@84w)*r`^8 zQj(Q^%w^XzW&B?ux!1X$?7k;iT+LU36{EBR9&~hIw8Y(sYpHOQxfVf%2trJfWHF(~ zOR|swEL=d>I(|}YYwtL%ynQ4_yHd<$W`c9A5qmZ|7oKfnLz~XEvimLPzP_}lseS(9 zsdX1GcIr;qp-F~jjdo3SdrNA4EU!D0=6f3kXaK$U)^T`6gnm6umMFbZ;o@F%P&TyOy&-ZpuO>zi{o7{@D< z?1^{wnm0^0Pjr3q!3V!|>AJC|pzG49=+M;goc+gNBI2pAF8xlKM86}7tK}Iv2}L43 zP{Fh8MV>;M15qNvO6sc;ADR;)#6*!uDkIKBREeY#`c0ge=8woTVXMf6g)+i~_^0H6 zae{va#kwLqXz1Wr^lbb)a!2%W{0sKvJWO>^*SGI}!@q}yJ1XJf;`7(69o}5Q=YuLo zB$&` zmU;%viur4#r+UcT;z;xu3GoP$nQ0uf%4i%k!xZKxat(x1k}ODlM<#5zCf{DSem#44 z_0@m*mpkq_ZIgyQch$iwH*P;ogs(;6gB@Z&m+2Ki5rIBCr=Km|QF`CBZ}KB;?`;3V zBy5J#eTeA*m00Ds6})0Xc?)cce_gr(@lFZ#HW(C}RDZpe+R-9!?DxuX@Dc>tK|Z4F z`*o;2AVq(0_wjOqLM5=xBeSBVrqZ71iTOCIe6Ap5IlSt6vxlCX;SYA{iXCMLGiV z?X|NQE{BgoIj6h|@OW+MVi6v=(4<--cu3dRt+=jLy{@=}Ul)KYa~z&k`FRB4G(6Ak zN5{WktEx)RoA`B_kJshrX&!3VEvr9|AR)2+6FgtLEm#Wo8}T(*TVH2zlZtvFRzBuciu9rF`IvN zJz?=Fh+M&U!wC?V@Un(CwRK#_8_=+E#V*t!?1DAN56higyFip)NRLy3GEp5LE{94w z_8%X6?EJ?b+x0XmTI~h>Lajnxmk&=L?_&r%#@P$ZxpyzxMBbfZKl1LPXe-TYezkBb zf*$&%SgVNSN8;9WB>Jrpxf~HOUY_VZlZOva-f;*2fB)1ScTU}je|JpXNj9%>#U#ct zjdu&+092cZGMq%)BNg|cDlt@_h-{Bm91W1f8t73|V-QUoEDS~a3WaFHr}`(1=eW`g%5S@nXOQItD*# z>Hj4cdVPr^$o{B22rAo$aZrr|F`tLD1)39WtsXGV4)F~&&QMq>RZ_$K;Fj$jRFuwv z!g}nF)oa)d=zeqX)w5nb^pN@?nv2uX#?NYP$TiPIEu1(KliHvh!X|0MXR^b{t&xS0 zup*AX8pr9Z84cVJq_-b>^(^#Z9P8PtZ09&p+dWp=$DAun)T9_)tOC=+5P7lZCWVHx zdO`teijLYB<-#umT?;ULGCDV!>f8fv{=NH)FpyLjrK)@s207^};dZrhQ`A27$nDf~SkIk`1E|Rwz%SYFm>B&XULm&unht3bQDA6g{Cu{17yC~2 zPNKuArT#8N3Mt{Al-y1L znv^d3PKqx1KZ<;nl7AhhYtgYzEKiI`6T>VTGrI6y49`Q@#k1wPlv)@m1Ui$>?UQZ8 zf;zgsglefCPupPi86jq}B%K~lkd-5eY^*CMv>z-CCkj5q8tmGeOO@OFrSWumuG@de z8;l3S9#2Zu9!eLc+9;twi5Seo>{H5*0)NFkSS)3!_5)=#iuqM14b963kmDmH%K;pn zDAXAU#N+f~hfz->)L36*JRJ_D)1fe&{Y>!-b_QzjeiSwX1y-4v{lam?-G+11cR}w4 zZe7IA0B`&#aO>u`LoQU`d>J}}=e~@4E*76d_2ZI_S=-!49PEr|@2Y;Bo*Q23S5BgO zPLuLF+%N8v=U3hj`)*s^E9@dGkE@{;SY0a-Ymrdh#%F=O;+`z9%VG+}jk`%3CLK!D z`N{6rn9c>C9A((n78ZpXQXQ6Bsvc9M)}f|p&rDl%%w6j97lq;U)^hI_lx$ePx6Kv{ zx^<3{H&ZDXsH9A3^FSozw=C`!oZJ5&Z|?yZS8?qR-aWuJL z83&iA-?q&WZkdj->$+ZF&92REUgCQru_SR$5&zDyFG{;obLtntKGp|4UybLTAi$|_ z&D(I+AFX(3wQC7oKL*ac(1*06vLY)H2A7p1js2*Kk&1o@s**5ZR8U43 zEefiBs4Ap(3u;-kaKcbssm3l1l2T)r8dU;SR7zEXKvkZTgn_1$KBGXf_M$i=`bGB74wVfRCfb z7R_AQ=iJlu42=w`sU5xA0)z1wuC{kKkjo3vi*o7kdmNLjd?MSGyU>##8krhZli^C4 zC?mC{FU0 z&Wb%b)5RvvE!j}*%*J37mDhC0xsYFpYT1nz7}^XpBc;deW-1+OU$xyTvgM@BXC<;+ z1fQan$#QaWD|a#qD@`+cAWe>Y0rM6~LkNkcE4y)k*0$C;b6U66QRwS3Es?%tcGcFr z!r8lCW~q+w^p?WeOVWiES+(i(mX^~uRZ$pf9(IITnb`|G^Ov%Xj>D1R>9evkupswM zYJ5gbe#~om7?od(RbhPqiUFpveIK&qmV>OvckRJA7Gbi8w)4i$Bm2*u{5{4H;|M+_ zE~E&@=!O)<{rS8$4V2EdA8cmHz7LxZ`o6B>DC6F&t-DIuc93Mooq42qG$sdcCRG9jcT5*;A@I-&;xqUH7R|PJONcJraHi% zlGoOMOpyLVu*E-+3#(YB@9g4YcBb#$RXQ)4*5#Rb>zab~h4eK#H}c}JD+_*SP-lvQ zzE@?-D&ITotm0zdSxl`@&qn@J{t$hcKQ&cFfm{lLUWN2=ZJP4&`6c<6`GtxnDAxiB zDCdG@k@+|IxslGh*;_=v0E0C(Iaq;6dz4`(y!-Bzn|yC>T6s4@mcMDG&pbT8zkmK= z6)62JpL`bQ<+>#QdB`2uB<81KlQ5g|De$#FT(ybKQrLX&ZCXX?sm<2TXUV>D0xTMp zK+!ZTIK2I%DR^!j7#N?9iot_#wfR2l6&kJsZHhDzycK~5a*!v4s& zgEjabX-6c!jnQ6C@NUCeR7z^%YI5R2B=j=&-A3Q#IJWUy?d*><9vYSi(? zyo=}-gmG4iqZ$%fVjcWKqVJFRUT^f^tm5Ue4<+w9sQwtiK-#t960hj(6yfO6ock*J$q55MOl4&y8VV`p+dkx^g75GlL?7I#W(DDyIRB&hQ zM1zg^S_8gh-_E}4-~-@U!`{aI1!(Lk-fS4)3%cuo0QvA?4SNfi!`>lotyAbNnfM0p z4x%T}`CN&%*b?MT3VNt2=h3MMJ}fS9^rf=zQf^EdHCq}B3L3Z6*kS(sIcaHg=I85h zB|GYKn1v0Ss;f8Q2x}d#pfio^vyCVunFZ!E*5kf$I_IJYqj3MWG)(6Qw>@oaC@5&y z=(WTAg>-Dv!hAbSRrf!o>TrF2{id4gO;jE?Ro5U~npR$4RJ6Dp3x5|E71fugRmVHa z($h+FusgjpExpW%)(g%ve0TD%(DxzO7VJL6Z}*w4d`bPp2W-;E!g+uF#PzLnIV4l? zKNe+Z`(zvb@i4upHqd_1%isbpvZ)7|9a!^1$N#7sbg@YZO{5qamBJJ@_E}LMAH^?+ z7A;s{NUzU~3we81L;04x%0x4BZKdxNHd(bX*SEKoJ(p3NxiO(Ip}v2`SxpOShU&WS zZ=d)*dvEOvUpODE7d23yiF&4!oI=-7!oSjJdn&@=2nc*?1 z33;x}sOCnA$_wn{kozZfwNY+v9&1P?GM?5XGpW_%teKsX z+AtQm_0m0k)vjfpbZ=9WH{G+$Ro%DeQo;!%Bbkp$qaKOEiIh8ETzajD={zA%*c+lhzBBW#b#%inR$tHnB&rUg-eqh zVVQGk^XjbB(k8d3u&pt_Ixj9P!b~bD%8kw_%Z`uFF3X6{Eh6}~sy&o!)JFn#YtHTo%5Alza&>HX}9EMBV66jD|3R!8>@anR%)x%AVyC~e% z=;@$w#SV`SGt)9N)9|}MhkXsJLn|Wcii+wYDneJE6CE9WYjkwftg_WZ4GlwtL4}RE z3s0)@u3wm&yKud?>ZFCa9~U~Eg~7jj8|o6A_%ETZ;qzGiAJptXTgrvoXSyLjjZ#wI z6q{Y9w@HF`d8>(hj76a@7J}Z3+(Uw63bWXWbizs(^|h9iwDv91;pJ%=8EN=Es>8W0 zZP69c^XAN%hoEg%Xn1%ie%I^JRnpqKaA7ZDP$4TW%%UyQf#36s<|kz5?aA@n}?oaJ5IaB4oUJV zav)aknkQSRu91~%VV)eyqvM1LPOZp-UroVx+LxnxfjFduG)(goK5Kg*q^zJNYU4 zXTAI&dc2jgBxyU+cW|h!EoP0}dn9+v!DiGzW_3*t%t!4c#}SvbC@))W-P2F3w0+Nt zg0jkl_(hdrQHjptlA@R^BO)pn#V1sj6|C61wr;iMd(T?kmCa-0G5n=PHbLK=x&UKa5=0u)a zwO~Qj^E@{*Gnd!b)YSW9$nRevzt5EUU4XW5BT9?(7KKG}hn3nELSms8uUhhQ_)_Mz z_Ri7`|0`kPLzMBr7+C2km*h1hrKfyt_wKKyq$f4xU2;lg$HLsb0|R?=7q+`Mosv=6 zR8rDZnQ_XWog{lKcarS6H%xhoi%E$|!T+VN%ianMF|N-3uafBEay4cIjA&X$Nm-_8xax`5sP6`VPs4`z!!)O7_ZGi zo>$Q*3C=~t*fr*>Xq=l?aZ@c%bHTYZz4kIf8udX)Ge@-FBn7=Uj}jLrSD;H*fIg+H z_m$$3Qv^QCcw=#KdFRHBo#p7#zBfB@c1k*??Q<(K(#x;RFD%S&aq?*ArJK9EH(%~{W>*y^B^BaS?<%?~tSb4!3(J;!GYguw)YfikD#-LMFT=_E^OK8fa&pvJYdJYJ z#mT;l`g@mQ{dilM=j8f=g8Gv^Wo?V*gf8ptM?3Mu$)kKX-;WibuHe>43hvXva7A8? zzl=<6mmeX5M7X|s*V!yzh|bW?)FsykbYWdCl|io zoV_D!*=+BI`hv~GrxRDHq!iaUiBHlE`smTTo1YKeV2gdhG~J|Nk4#ct6}-JXkQU>- z@c-CUsCNmWEAL;6i1YGP6FNhOzge5^?9Wc?ShhAi+Un{Gi(kEL&8+PHn9S(4%hn`> zb#+8M6#Z9PRUH{x!7EF}jc6Q$D%z#=SS*xX{Gyp>^~poULK2eRue7 z|H8g4oA>S8j3P`p^6;lh;=l}zCk{B!6UMAF=4ta@+WnHRmpPX=nN7>t4p!m&neXat z@9h~L-h-qV*Vgk+Sm$+te7;ZJgUKBNL%{g1@3O@6#Yn)6w>T~Y67@7+kx->(<*KTc zwY}vkD|1!1x{{M!tvtOgFDECjjU^V<<`)H-H%x=vV4 zNU*XxNu^6<5)a8q`--2yzT*1-cwg}otJS_@Z(dwp`r`Q1tjwJ1f-%C0^SXfeZk`OU zfEFHY8xTb~Avc^IefA}1v)HrWc!SM<;|-#H1Dmhm3c9~{#ZVbX(gSkxb3#$mRP?d9)520Dj9OlDu5jW;`e zR{{2Fz8Ys(-HNn-oe}pG+Jp=1H1=Zk2XN7B|KaS7*?6OH4dSSZ5Ba;m^|{0~z~?bs z>jXZ)#tgL1<@4FA{C&V5mEUjTwd@XoqZKSvyMVtLR+}uM@QiT-JU`DDVh;2(!29I$ zgOhRWD@Fvq!@}|X$;nK1v%&F<7B(hI$|pbLvvEfZt?9|dxc*$sw68U`8mAe%aqa_6 zVFcAkCurr#trcpul_Mtz{Qu=WCLQgHFqkTv6PKDAmynwJ#kjPzxVW^`$70jcV&l_% z_sB3cg>Aw5MSMu{brM8;S_->df~KeXwjBra!c;6*YUEKV*b0FbSW1Q+QDNEIl*Gi8 z;NL(BzyO?LhXbjJ$w^7ciK!`xNy%vLq^wN_06>x%-T-V)MrtA@NlcY?r)>weqVBmv z-HHP>>1Ye)zNh;dUipo#d&xep;Wx3%#g}G+TXWy4Tlh_TPPvHS?!rwRT_SBJIAhf% zIegA*sc#aTE*~?&6)wG|n^!Kqw~OGO2Hi(zrW;a!%PM};@{7>uWyW84IlDsx5W0ve}*^)1pj4W<@kr{S;~v6(NPE903CMEQcm)Wq~mYt?duH3&#Y z+xgw>&!Ph*Etn?JqB${pJ&jE>X(pP=A&zDgJJTbh6U8ZJOI1*u-yNSEpPUi0qDh6V z%~DqFzjWTv_<_7j8H3^AVovbfzL`=kwcJ9VMlu zC5~3Co(8`C{C?Ddt7pJRdrWC1=5&0mYeH6sl;q}?AXvliZ)uFiUZ(8m#ukb1bl`gn z_V^#j?P@GZWMAae3C4ol#F7SnKL)k399g-!_~XjM^a9qUC|?fG5PW}Y@QO+(u%>1X zete;8_H2)5HqNMG#?Se~?0nJvFVhvf-NpFvhsz5K%F7E1%Te-lU4(SBzViXd=8&2u z%cOQYO{2#{JHh9d1rLBcoL5$shu?!bHR@T1-Ep|m3ewQ^k$8W|E)u)Z+9Z4Y*LY9~ms}=qMf}9Dl&-(Lqs-wRpkp8Z@nA*r$$jag}a9i|@Ka*+2uYVz&!g z^Q3h5@8rI%ziUGee!S`jrT66F2kGkgz3fN-f$n~I`qu8z)3^5UdoS^RI~PCjd@lHS z74?kr7ctuV(H=LZ>lvKo9(=sSFJ+ZAC#VwRRkCcUI?RP`J?UaUc%!qNRQ-h;IizLK zvTMRi`^@N!_`snezd|L`>aTM6y(l$Qp@vfloOU$-`dOaB zlmrYtg_Y)~CtzVobXq}r24>sXMv)XB8$*Nn=m&wzRErqENix?sf)B>` z`PrNWrn$RPahaK0SytYH_J{W8=(~`GFymF{{wts+meGaJ$mxDu*3W& z_dG=bP+nY3Y;v8@EcB=fS;SN2CM50TUph1yY3M@z%-hz;`Rk zAy!C$mhbCJmdHNkWCXi-@-duWj6UVD7iB+kU^0#U0b_t6P@Hk>E&1-INyhG&d>QXh zqaS-t;*|YQCAYpThN=#XZay6`uQV%n*6IblAI}pBanbRjI;6P3Qwh0WggsuzKa;u& zx~v{&Xm14gR+*63N@y`p#K$9TfEFZ;!3s6l7_Hh0Y$_&0Mq$H`3LP1spC6ALXpjYE(zu?z>bId2qI-Y;E1(%FZ_QlH%@3v3rVR+PfH53>f`7@|EJLZzY+fOzoId>vMCNUHfB0A z;vy14^AhL1TUn7>lA9Kq;z~_Sh_IH&Vz;{SsqZt^JNX#dQ385#pE^!+_&$3Pc7ty> zPv*1RC+{MgrByh2Re4D_GslX-H!r?;$r6!?&;j+sV)2grQY`$E-S?x7Ak+^d|Ca#&Op{`C$q{*J+S(wye%~sb?KAH+SLd71%-{-5LGG8sI{DU2-rxNH1 z2CK>|uo_9~d0`+dcPG%l_t0l-oZ|-c2VA zq!eL7R&NbRj$v|8-M{7G(RMbLQ50r|6{pXyW$g(GiLotliSY@43IAq#Mn?LoHQ^Q6 z*{R9Nso9uC18)!TYIZ%JB%gw21R4@(N1(6%hss5ZD(mazUtV2WTUT0BQ(9MBT0=f$ z`nZ?w3#0F-^5nD0V)o6+=TNWFh!f6W#i?4D0-KAqcrfm+g_WoAq*&7t5*?BGdegkz zh~$vODBebnhE2LA8%6Qtx1o!vd*kRJkC(;YAKtoE>U44&njL@PzXXjm>>;5IL23yx z?F^=!G@;08;jf7WU7EP3u=j&~`#$I`tn42+t)k+zfqtIaxM;zGMU5GS$>HJ2g|Hpt zY>eUkQj9E!H z;l=r1_7d&0(3g5$eEPpc`{9h-T%!Gi<_`taCHiL+T?Q)^#tuH0eS$F` z^0-swj=~$e^-KHxsm@QPc1~ba&p}p$<7E9U`y0~o^3w2|SGZ&47j&F2&B>sXMKf~5 zKjJ=%wjch_b$&_rj5;6pe)<1i=a+wR^C>gv{LH$`i1rY#!CiSdGw3{8x39?7PN;J# ztU)^eUP?|*N@`BdDa(5E)*?*BGhdpWo}QJ3?LTp^CcP=_2fxmjNLwq%jJIv)C_SJV z7$H#k?L>*n#E(uVNu@Yo=ro%-)9fI41fgiAF*ds(*kN;O{;ag9=y+?f#>+4H5`}Okf|0!S7HTB%)d0Wk`^JegHU*BG| zY*`WQvAv2{^LjBG^>75%B<AbS_&s`U19xqmgTjl*w(i)UQz^*Hke+S+QkoOT~8c zuG+R$yqY@L^&zEadVu!|%qNwJGyhAxFU{NdrH%78n_n;OuEeNzcX!cJ?mlTg@Ft*c ze&WC4mvYbM_qM)O?KZ!Ayk`P$1;*T;`mgvUyf(iFdt9A1zbogh*ZM6HI8PUKXJwFn z!%m=II&lO`AyF=4WgpVkwcHV+x)#yg7UQDu=-7D7T42t7FANQIeOM zlZ@del^3(cRp24%|A7a8cS3e=Y>B@T5gngV7`3*(QOg}tAtIu{zvD9fg2+=l1dk1Me9W55p1w#7-p>!&pw*Ae}X0;VFKPf9MDIz7b(NSI) zh(bjj9p2ilQL#~lA$7QJQ3lj@k~%{EKk@$qkGAF(COOlS!_yrt!c~H3QiO~`i<>tW zE!qf|UKm7f!PVP;gL&pY9(3h)R_fE5<@*pL(2;a z%0riiteLwMO)i>Y$ScCW-bNf=zrPOp|G$yVJGOqyakA~L$Fwiy`Tx3Xn@7>K36|~5 zy8V9H_CbR=SV=eY*f*7W$~QVED-FMNsmp2kH^m9ekd>>#qT@4*qT3r2oW~7^pW)#c zm5&vxg?CPBZc?OQ{+E!qbo$OrGf#oMC6APZU-ArjJdLd>*}XF|I$;)E)Z%!!s36r0 zXg9Gyl;tF6C!wpwjY}~{@T_Qto@l+ittUFgF<#nSV5Uv2wMv0!pcA*~3_v;ylUif> z@DS5x;bo79MjuyJvcP8o_@&k1bkZB$G)(#J zlza!z@~O7sv_5%h>k7vbM`1}xA%Yb#GrN#S7I-3)v$K;UJqs=)2jcf5Rm$$a#l7r4 z(EwkU2A;{ws-4mve8<$tUM5*cy|O zpBRU`juPS$^D|L z>3o_E-Z#Gw!v{#O=665-AEn1E@x7JT&Zn8;T@5?e$nZN1kNZKEb@XHf3pc6VblX^2W>XSgD-g3qrLlN0fQpg{Z z=j0`=S{qX6Op2bLyJrbsBx2GEGRms?S{@%08!hI)nS!w>=&ld6eynLxFJmTJc2A9J zaXGI#l^&GzP7u9wTK41|M{mWeDHsm}y-T?VzF{@!6kuPCP45AWKV%&zBefpr5DD_7 zbS@~BIogSVtLtceG>y1GU~10Lj6u5C6s%t z!h)F8*l<2iM1+Ng@-zKS3Gxl#^)%?_#UR}rKZC0BfO@fh-GCdc1+`mv*qxbjO=NVE zvoK`ss-(O*zgnBSn=hIxqGMy?kr&lv83k!ENwIIzkzkVELlww?N~&*aG_g0pGB-_vnT4+aY|r$NrWRM~U=Df!h6jj9w5e>P=xsA7(W4 zFX#LQ`~zwFkNU|uIM=C0(pRvcWB*gIk{x16vxPM8PY$tN{Cyig&0z@rQn*lY z{fNdPz~2)Lk0Ys|1NsGF4^CvFrhT6``(;3>4wizXiQiQq|7lrB8afv`9`ZE%<)L(b zd6Zmsx**B{*-Xf`9y-S%LQ;1~PtxHsL;ugFck@FJ9ku@l-9t!s&(w5uqEg^Djoy^x zDzBw|V45d^&eDl{pWW+w1!r)u0~7oG-|wOMGknKC`+KwRqX`=F2MlZ?7)Ktg;^+|@ zh5x%BhyS}m0UITIgU&$%Hi{k3&FtO-?;kie$!P(u{avOn0tf0l38aTL zW0&GbHUgFY9^?(-momujHUii?l@Zu9zEiH{B)xxtmA)_7#D2^E02A`HNn3_gp|))sj&RBRh5a;92_W_9 zVibfEGANwN5)`0hZYn;BD?nFUj8#XmUwO20il(xYhNOH zBuj+U{2el!1F%EC{$$;y=q70>b}yOY0pM#QNXlYG*AFWXu8|m7DS0{Igq9!=xtSnX z$s_qXn>KJtxG6YyksVTpU!-^=O(&5zfj^VR0EY%#+8_Dz4I0!?zE^+`hQI$nlh#QPth8r3K0smg zEtfc9{L^4HkG3_yS4x}!v~enbD|sX+PZC-75kHI5c~mfY3hGD@hf`&dwDO z@&-SsOB{J~zhju1hSuI_Uq@w6RRC1_D2?Ai1k#XwNO;mQ@N8iSuoEJ$4m`q`E#f4}5;E83e!VfT_3 z)#~uXZQXxhzv{~P`#Q2+1Um4O2~@V}pKAZAMvpi^Y3K|IW&kI6+GWF%mFLB6<%ceVxt}HQJwQ!5gzXz!Wt$kdiEETZsgKeF#4}iCA06B6 z*9Y3il;40QpQ8RXBWL!j8b>v>rCmul$%m=|n1qL(_fP!z(EhFa1%sj!fPH$KSmq?S zu&o5SNI9e0#!?|w5f9y-N$L4h!)Lx*%B12HnEAYDqjvRrGrRN6qdN)}?& zU%prPJ6lnV<7G124s^MLY^p7$N*;}8$o!SnoviW%@hI_A{z8wG!z35!P*NddPk`x#1Q`x>%S)z*>xktXE7Bx!wzZ1Y2YBWsjj zgAO%+N^=Tc@<$RK@>3z9Y)XN;Ai>UK+Y$qLZChj@&$V5ujGuxdP)?{O)jE~*gNu!{ zQ{_+Si~y-$%|ETNhP4s*$_|vRD{Vu1vRAStWw^4yPLS4=QA{ylD(|X~3ZEwJAA^|l zSQ4$@N{V}bZuj{so10x7i}K;tFI{m#_uK>di#lAsVdW?E*aFf~ZsWumT&zOFp74hR z*4#`fC?#PyFt_^x+rOwjInpsYXH=%bK5bYsU{)xC0^Prr=WBxOQpu;zZ^_aub@E&>NchXMF~4CGBPaR4C`z6sGoXPO`It?{infV0iNbb#H? zZrA+-$S&)BS*GCqP*GDJ=y3{+3zC<9pE~oh8d2Y5{YT$WVlhgj(`fw%jV01FfKRphsgtlAcUQ)h}@=>4C?4sHK9k zkJ3*yDD?!m0V2C9f=H{7U_^yddY#3g60+^2`aK^c! zCEI&b;EXT_r@*w%2-9lAuu`&(<6tc42Nt9`qVZ{&uYludEr-)d$VpWx zIXJ5+2d6c~;g`jt;gXlL=!u)M_*~yBcz)LHW}mw!-hc*|v&UhM3u%9Zrf1`c$J|Fc z=AZ~4?%hl9$n&4*45&b?s>qX)wfErNxJHdF-|Jh*4)0Y|7G|*`)@KNn}wmSBIo8>g|)rSmNmKZ++2%op)CjX#@L z+=@uNN`A{)`^pa9UH0~58F5|a+t02lBi73%KI3!BB>xkiWwDQaQi%Oo>|`m)+gVRQ znAWT^$a9AKb}7;xw{N|YYnOXsixO_9``9*;uoZUxOe=}mijwo=R+6<9W%0q*qtCXU z(W=TVKcw@RW~=FBX7qD#9&?=Z0Q``20S4nyC$I%i9FMXsM*9IWjv2}(EJnH=Y_TO= z$HDmRNxfzzoq&jrNh&H0XV50h*|6)zi2}v zOC)YzB*Rt!zi&gDneg)szE@CSj>E5DgZ(afLWTQSDq)5mX7tf$#whu;gxqhJYW_xf zb4y8>#WFKgq*2d`MJH#V~~2CR&t7H?Lh zqu;V}3bRIi=dw?Hu|XT2k-yxCz!`HJamHL4R_dH%OYbDvoJK%;eTZ}5#c}F5PWr&* zeg9tibm*Z#7QGY7Zebq13iA8+Hmp2Oc;+hfW=CHUA7+Mx#6{-Mq=CrPISUGT-o!6c z;`x9@rzR})9pR^&`O4QO&XEMw97g>woDJxjdLA3pr);th-D6co5yJnX>^epu?ZesUvE5m%$^Bp3^zTLw#{ zQWt^~pJ*2a>JQ9rhoR;Ok?VwMy_>xnJO*oH<4{uRKz6LCpuA5Kaky8OdJwo)HYKV4 z>=!@1`~tJ!>?_VU3)p=)we`Xs6W?KP`M&e!Ilf%B<@GPq{tpc{iA` zklaXP45jjjRXov;PiTLAGFi-biI=IZoKh6VYFPam_MtC%4R^i18W%vAt0#Wo$FW)A z2;+S7#0`8iuwKcp1djKCV~4_Fg|U<{##1I<=B_oqWcK0fyn}bFo;WsfjOZE0KI<;2 z1&W`BA8CaC#^6cCIrOwo#|2geoT1}%KkT=3+(Nx{w~jk7UyKoFi6_K36%iE=HPYFs zIv$4j={g<(C4g%QAH^v#Dg1Q%uu|DG|xc2MRA7sejVq) zf0d34yuVY&A*1=Qj$4R7r{mbGYQC!DAx6CUwvLD59;wfC95?=0bj}LV3O7ouMLHf~ zR9k&I9%(dL-_-FaW3KhCjz=4_9GN;EW4Il4IvyLuCvFdP?9}h${dh1&WxV3JK)w%y z2C_mn={Pq+Lul_fGsEz=CFE=!H;v+uXLQ^$#zJU47r{7;{LpPW9%4KeYU2zwykSf9 z`!K}6pyLsSJB<1UloqY&Fr||)v=x^|(WolkL;tZ+%XFL}ezJ~pBR)#$B#c4-Q5q*~ zEIvxpg^k5WU8CV)|53N-IP@Q-@+gdj8u?K_)$hX$XOzl|FzCNDIzhjWFkI0pFTxnk zH;Nw8@1u;`=<9Sm+9-@x`5VS!jQP?3)bC?K%jPrA$c?Gd@8kV=(ja4ejFJnE2XU20 zX$#Cs)68e~k5c}l-`ApTn&4*~o?bUf5>#nN7QW~Q+)qd0bf zjzh-S9vzP`ys?+*c%)GqYvYVE=EqLx_tAzcu1?2ejHPi(t~3@K#Alr0j#FhJ4dqDV z2@T3e#Qph*xIZ5e_va(x{(MB-pO1+9^AT}>J|gbVN5uX4h`2u=5%=dK;{JR@+@Ft# z`|}ZTe?B7a&qu`l`G~m8$Ht-IeItFnJI0)DSEZ|z{<@v@-9ueH&h~wyV?6_-&Sit! zhDL^mMmooOx}C*4#>R%{R#fcSv!}e1z{Z>Gukt<8(=L%gJaHB zodZ42SK5chN4E96TCPH8<4|{xbM?qj!%%;>yBsv<)i*V?%~N0LBfgc8ZTdJ8z(KXV1{s_VWI|E_ZoVd9}yu zsy?2I#@{#U>~xNebawX)bdKzF4sHKeI_Mj8j_v4it{dzljkJ$JF-ShxT`@G`9Kx3o z=eD8o!LgCPp3(9Xt8#Vcc)zo$+_@B>rOu9?A!o<<&_Lf{&)|$I9@{tE)3F15O4YUx zZ6DjyInv|Ai~hcCJ%gj*WPGq2w28I$Wh(blp;BRP(v?!Hk--!)F^ zK|Xa3I$x=8cP?vx)!9(rzO22}xqey4(zbOS&h_sOuZY+bghsnpp6(}G|aF*@9{ zt#5nZHfMk5VDETmZ%?UnxMyUbZOwcaO8HXROnX zgXzG-@Q%Lro{_FTsIjZ35v8>sx#sK|>Dk>g+TS_41ISMA85weJa&3W;4E2t5BE>f6 zj(x*BU;&%Tro8P$nI7pI-Ray^vc*o_J=EXdIpQ4c>jilJRPcU)4@v{yR91>4TAEU) z%_^~N%NBSm1t>-K*nHd420*~1xKlhP9uz+@oJMC*ycZWWJHQWHFyQVAir*I$e;V+&;`uIdKQKLNIL%6gPvOn|p!}eG z3;Htso#GksB6!)vUpKZ84RJTp5_ZMQ1E72#czBZV;0k6Jpq>P-$Hb%JhroEJcv|AS z4JjVO(~H1=r-Up!0pz3Nalqawo&cVEfZ=w;z$Lu}{t~2m0$3gbcaH)Ws1j}Q6vDgZ zn>%G1^=4)s^G`te2f%R;GWyx|b{Rd0wqGUWii&6X7RfRiz#a^eWc z9$@bQzTNms*jj*nQ1ZA67zXeb$E$&xA!8g++l(G(8iv<`o{@$m>?TNKHDHE}2K@T* z#tld%=RC;Pg!gS&C>@;EPN~wB`BN(RHas^^fj^#>)1T%fDaR;eBMC^a0qU!P#R-km z8~Qg7(hosO(&!*$x4)GewYZvc9^~#cb^;&4Y)7hoVC|9^tMF8fOXj`6Qay#Y6Uh=R zuM>DEH#_kgletKGBWfd{=LEg&`1{}4L7$YG@|AL89iAwcRj#%prYuHLA4Kj{fZB+p zsnSrK^f8W<#9JTIjzZf1hMU!(HV&;hk?ZC7yHsN(d+z|=AsLP%8~~j`yczrttauD% zV;E^VkVfeLP2wjj3SeF_ z1p`Sk-Qvi;=tnZzoK2-`bJGc%>jb`j{O!VD;xkYx$vRq~_caJ9*XAN5zY!?oqmYGi zXc+G(kI3r#5mJu!B4^u>e#JCS0+O6aN8P|eK8G-OK|i+jsPfbaeUUGymt|?0(GE{Q zrH`KRBt6S|#5$1MZLq%%d|i*PYw@oh7o>FH8Wx%f)4RXmN_ErnmAM5C{XGs4RJ}bP~HZ<_ktRE;Spe@GSLfM z`|ytZE?Fztt?eO*qkm`l<HbQc;GDO!V-Qe86@$j z^xCpLa~y4|eTi4{?M{59+FxNu%jI8S@7LG|k&@_;?fBa*5>Iemki{LZ;i)+$TP?>y z$+pdOJ)4zN@@^*VPn(O(#pXh@-fY0%Iz~fweaX}hzNV=vrvgDhf7US&#vk_kTrWcr`reqqlQ%}f84LEU`s2OA$lFCIK$aJu;8EMs;RXRuJ zOZkcS2E?Ed&7*7^PtQ$Yg&j!APLxN->073lW+$-!e}#u~^f=4-mnoj6fnm%H(0^DL z;YPsZL(m@wt=!=l#S%uoQGnUuA~cw1qYE$xsLSBwD$tOtL|SUnRiQ~&gC<}ds@!?T ze9VG0p~`A8mY_;oh8t>IQK_y(h17bH+2q zZAKR}F-o?LIamk_Wf=8h5iF8Lv1k^2YuH-W&N__kY#lp^t!EpIUl=bNKf|h#UUo9u$TqRfYzy1UPGP6APS%B+wYyml z+s=B~4%Wv`V>^w@Sif-x8(@QMh|#{T5jM)k*tqc?+s*c{y*PFMboK@IMRo@J5<8Qf z#m+WfGhQ)XW#*tzUH_GNZHyMSHD_Ok=*E9@fnRopgy3FbU5W0$il*p=)mc94CI zUCpjxUpM~1t~DNH-(c6V>v6llw{TO#x7l~tA$EiDf$=ByU3Me;9=nO%jCqoH%ue0U9x%Se9%K)(huI@=aIKWD#SuNePeud>(J zFWKwtSL_Y;YxXAl4SS3ImK{d5IA-i-ZyS5qJM3Nd9{U~pJ$v8yB|E}CU>~wSus^at zVTt3%>=X7W`?K*b`wa8Ie_?-Re`9}V|1kFA9@BraV{C%?jMGtleF3vgUu2Wq;EZ!F zFac)aX6g_g%ENd#kKmC!3b$v(;D*RJoIo3I+{qJgTVWDU#vO>MJPr3qWEj80-IT`|M=Q^=`tQVq5rDehNR8ck(X24R@FH@a?#TXb11Z9dA2% zKOf+Odm+(t*gVg2x3d{^%#SikY@vHeY{OkN${tbQ|zn*`Se~W*ce+O$Y zZs6bLH}dcCoA}NA`}`LE1Dx@58^4|3!SCdE@gMTL`8_z{_ecCbem{SJKgb{A5A#R( zqx>=cWBxdQfu{ycwy|AfEDU*bRIFY}-ApYvbvSNN;^HU3NfI{y`a zgZ~=0M*N1q#ed5W^SAjs{9XPY{~iB5?ut0VKj0toKkz^DKk<+F$NUriDgQI>g!mk% z-~E;U4YywWgCFJpcor^pexxQ#qt6o^7mB#OmsQ6lDuQc)(#MTKyQO5w(} z8eUN)szr^c6?I}RHX+X!3vd$8BC%N1iw4msnnbf`5lh5Uu}mx%tzv~(DOQO#v0AJV zYel>05bMNAV!hZPP8J)*Cb3y;5nIJ6;#AQoy2LioEqcUu(JOX{K5?4ZDf-2L7!*Td zSnLubVpNQYaj{$M5qrfxak}_|_@X#Nd`X-s&Jt&fbHusgJn?05zPLbKDE5m3;w$1J z@l|oLxI|nkE)$oFE5w!JDsfPJO$ zZW1?(?~7Y7cy_C}4MSXaU>NBx44B=G0jPU1$abF`czO`STn~#!Fs$_$hMgXlLt;;1 zKG_^EhV{7n2@{6f4UUKOv2Uy9eouf!XeaZkYfaS~QorC?D; z8s`2pj9KE>;!W`z@s{|lI4s^4?}&HBd*XNE_u_qVM0_AV6n_wZ6n_#QiI2r6I5#j3 zv(%YbpLGlE6*h8>?_l+pW!!802y@Z*7*85ci9Z{U7>^n^8{fyA?q}k2<1XWe;xFQ_ z#uLT`;&0;b;veFu_@_7~CWKE+nuf_R!!C>l(=;s;bHzB7ZlSRlYxqyaoc1ZW8|(RHE_ZK{KeztVVMQ z4L&s4=Ao%cO*LwQP(!s5O|fRP1&ynv<}!0R8gnbmmF6n5&0KA+G1r>yW{0`XJjq;d zTxV`Dt~XCMH=3Kw&E^(!t9gofs@Z9FncK{6v&Yv%R zM)P~-O~&QMx#rF0_sv_(9~f5~-!N}AZ!^AY-frGu-f7-t{?NF___}$wd5?Lo`6Kf_ z^M3OI^Fi|=^I`K5^HK9L^T+1n<`d?V=2Pa=<}>EA=5yxr<_qRe%ooj<%%7Ssn?Eyu zZvMi2#eCI#&HSbLy7?>f4fEILo91uKx6I#~ht0Rmcg%Oq_srj!zc=4EkC-2r9~$?Y ze=z@O{>l8v{Mh`&{M7uj`I-4Sx_VzVUN_!0|6=~t{G0iA^B=~qjEjvoj9(kSF@9^j zX}o0|HjkSBG>@4Rrq7(T42xOZ5|(LMmct6MLai_>+={@Z=uuX*6=TI(aaO#QU?t+h z;AAVsO109gbSuM}Wo24fR<`A|a;#h{&&sz7tU{~EDz;`@CDt6P)GD*etqRL!Ra$P# zV|lGAtJtt)AwaMCSZLzjmr&y<2omQ8%&FZ##tnF5>wZrPOPP2Ae z{nmgrXboAz)-G$r8nwo(acj4=$J%S{vrf0ZV13a#!}^kSrgfHewsnqmu63UEW$S$F z0_#F+zjeU+igl6oRqJBw66;dyGV5~d3hPSiD(j&2HS22Y8td!UwbnPR>#XaoZ(857 zzHNQSI%M5oeb>6t`kr-@b+h$->lW(=)~(iU*6r3E)}7W})(@?_t$VC{tshzUS@&BH zSPxncSr1!}SdUtdSwFTOx1O+`w4Sn_ww|$`wVtz{w_dP*V!dd+Wc}27+4`CFbL$t@ zE7q&lYt}EV*R5Y!Z&<&!-n4#Wy=DE@I&8gdy<@#=y=VQ-`n~nOb;SC>`q27=^+)SZ z)<@RI)+g4d)}O7yjLf5J#vZ z%n|O0a6~$y9MO&#N30{x5${NFBpQzyKXxQJk{v0IR7aX4-H~CgTDM{aZ(JKvKhU{t zWN6S)FQ=cv>qjt4hFPnzo{;guK38R9Q%L<#@6ce+PI|6vu6OCstwXO4t94kb!+ISy z>abab4LW^;PT!!@H&lnzHwV#emfu}&uScbGRYx>#>l@iNKCr#NXK#38_YkJjFiSe- zXxi2Z{xy`Q=F-$EUHCjQ)Hz0mAFaE+UpsC4+^I znv6#a>G3*N$eePl@G}jl2E~*gS|j$wN~Q8@ z`MjDDZ*54Mk}0Zf$2iP&WPG5%b9~IvCM8gUHdU&yS!Z3N&bmg;LX&2pNlVqFi8N^< zO|@3rj-e54SWOyBlg84du{3Ke%3Ld(tK1Q7auQZ4Xsr(XLIFbR#Z_6Q=~QXVRT^_u zv!h+6if9jHL|D7Tp!JBvlDx}Zsg+!<*{IgS)HORg{4`ya>NUVMt!hoHy4ma?Ls_Q` zWt}b*>!cd3b>s@7)&*-=tJV{;E?`5h$|jjl2y68BIvr}0Xx6H2uC~?%RNAb0w=<|& zGu5nB+oENvX?Co~4EXLI$9kog^+9@B-`&@PB?Nt=j*}%!#L0n=#6)Ftt&L7I(W3PZ zTiYn{g>Rfv8Y`RYG~qg1nKC83M~lGZK3}#xMwQM+m#d)$rL<9&)=G~XrL{7oQ!BAk zd6v%U{Qjo0M4fEh=o#=^J$V2A#g4CZw}R z%BS+8S$>BQS~yot#I}H{!ngT#;OO=nPGz%8Q*&u*m6eVj^%<*bWVO+wid>J9DZIyz zN3*BdZ_w;FXoL+KVWVchQM2Eu*>BY1S89`LsfxgDzJB-LJB17uIC&hsL2Tn{4VgvN z(t$?o2&7b8xixmTrdFqI!mYV=H<&x9T=c1O(WhipiiF?j3(mksou;wD(I<5gaoSXJ zaE+RrM+@nxirm>d($h1D#Vg%?+Z_EepB(*u36Mk=27gjb#nWK+Lv|&GM=Q~*mFV?2 z27|J^rOq)JgwpRlwa{M8mA5Wpuyc3_>wAWeT8jq5TqE|p-7OaD4PgP!4V0wxB(D$Nt2t~yj@glF4h z>KtvZvBm=mZPpUlxz((hYu3!QXvu0?9D9_1-J`U#CrCSc{Qh;H@~`^>A62H;+UPVB zEjqJdeWy!&;ipe2tnjazaGf@jx+>8#*h|=4Zch#GJ5Bl5YVBXEZU2h45d5nItCC*K z<*rf|>8{clQKek9yGk;H?@Dv-D#;X{l?L5a8c&_n5#HOOtRV3$GZdlJFhX75+SZ}! zTbEl|2SUw8&sC6rJU`X{x>zUxOcC zgCAc5;nPhI2-~Ytp=$z&sGzzPQuJymA_LW|4ebWzP*v61WZfVeMWVS>bqnNu<(=Uu z^!-@diD+n_t<*kSseMzFs;XHiwJ%7iy3(}?H@Ohg6|YUX(XW_Btr)Zfv|>Gg0z-&4h(ckm*as+H4kH@?9iaO5uZde zK6lWfPIDQ$qE>6?@Ng&kMFU;koqXjuUp3A*^r4&5N3A5jx=*a#F=Vy(^$v83j?VFr zbqbYOjU|(f_^lr8Q)KGv!X^E&p~0ciNKH{bgo2`sgb_jYonp4mA~iAfMH7$@G5W!V z3~w92VpjRd>XgFLl25CbgtfYR`o}s$dbFsg?ZR|?W48)sT0`Zn0n8u)ZQ&1ef(2u7nDBc)^r%A@8w!D?9dh=GQYQS5m z+_|?>RXg5F<@UXm%I$mg@QYXXBD|`*?DDF{9YR$Nc~$!j&#D^oR;pa|R;udGTdArc zuUpf1Yx-_Y->vDZff$!p^(zpnYRRkm8+caLpjY)X@T}>(RW;~!Yx-_Y->vDpHGP++ zubV+$m!_`=iM%c?ze~&S()3-b8uq$0eV4LYuS?T+Y5FcrUv>LjUNww{P}A4V9ItLx zc(wI3cO_YVZ^9HGMT8hG#90>cZh! z)AwrnxQ2ylHm_Ibt5?(aYWiMH->dUgH>bV2S?tx#YOiiqdv&wgtDDtc-K_TNX0=y0 ztG&7z?Nwu1F0XDzdv!C~t9oL1uj%XNv{yHqy}Fs|)y-3{Zti(iPXYF%^{t!j-a0Lx zZr*v-APVfuey`Wo5O4_I}`l42A~B z2SPFYUM?eJdxm5rd~65C4`eiKJ9f0_7&e_KxY5473T_lzN(NQ5hxUXiKcX%2q6qpbPx-bWMqV>5DXC^7)66(iUa{k3Wz8I+oE=jqY|Y3EhE_0B$e+{ zBU!XZEqr@l@AybhH+H^A9iSI3!zxv7-Brp@Ae8xv-kB^92sNAxGHY?~@#YoHesI~>!rZtM@jWjJ8p&X}(HZ6)O z(^4_YbO}efF5y(R%c#nC2`Dq3V$s9c%r@BHvwcj0$H+&yFHt^6V7pe|P`5&b4Tl4r zGOCPzbiB*v3=zdySAerFKW7wEoB>X81~{8DL~YIhs5$GJ%30UwRL;6a1Dqkf%^A|m zGSWRbq>7`A5N8z8I-{u4nTio-5{@{NaEdb-Rh&sc$r;6hbViTCoYAw*8O1ec6jhwT zPmIXilo8^LBAPRbD$Z1lIFoS1nS@iE$*AH?0!q#(7Q`7n26INwHfI#qoKZAtXrz04 z4|YJ3zv*k%Ato ztK|dv2A5k+6a9bfeRq5m)fWHEY)P^Sp@bR&tf50T%$C_Ap@amacR>RJ$tHndNH7V3 zAR+`r5S|5j2q+K)0TGZUPY{$Y0yab`N>x!2DH=f$<@Y^j?uI3zzTbQJ`Mp1WEcxCt zcW%Guo^xjI8MrRJ6H?9G!c;RiEfrk`xsua|iv_F~mqRpBkIxuU<~OzkJ_J$wK#G zW@HzPEc2!na6KG4+YJh>x7VSw?GD_oU)R}2hh1mWLD8LI8TkcJc;Ixc-V!j>sd;(1 zqeqPtVMiE;({o4j14%SV^rg-cAc)O215d#2cPb>1C&u-?fY(a9Pfb>n1k>QGTtP3N(&_v#hYz-#gKbiLx5 zm^zxy%Oiigem$>1ce68Tk0$+4cAzGDlia%W2c4^^f!!HCVpP5u$Bf7zKlW(Tu#D8a z0;4~BR9Z-SRw~v|&9MiB|93`e(RfoQ0;Oe}mLw{8OVO~0Lb>7e+WEY2!T^xefbm+3U z>d+s^!{t`P)p>b`J`M;oFOPoHd3vX+zbpWknK7yh`E`9d6z0rz!VS7=FT3gxR~>Yf z+W{rJh;s(TxkQ{RC{7b`T2P#u`C6yyj`xeJ@THE7&}#+%&0;(vfhXv8uZZ&o#rZ^> z?`E7`G#Nb2&HNHYy2PNkb|S7_P@MiW!Ko%uoTzS+&U~ZeI*2=NDjl45(S>&ILcNph z4*gEMBhZyt!`w)_vn)mz%A7*k;1tRRr%*NszEBl>AzXc;2)`c$YNoI?HJ6lw>jP&YV*y1^;LVy6&`ok9$D3NhCy z#9XHkbDcuWbqX=p=@Qe+6*Rqs2<_Ge93iy>a$J2hP`hA@*{xMJ(m)nW+i5}c;1 z#Sj+arP!D>u`ywz(CekECGoIPh^qmyR#!_RUgv`}At`D)r9iwWU#AoZ3z9D+NKHtP znvfthol@XosJ=03LW0zU1gQxLQWFxSCioIfS4-kP(SDsSAS}w))shH{@^!T&!c3{) ziuUVt0uNzD`MUZHVV&R6bh?4C=zm>(hOlVAu0BIp-{>`+t{^P>U#BYwi~bj~xh7={xll#qW${QXoSW1yG8%&Poohp+OI!-Mp(38fBKBDXutl{84uY- z`MP=-VNt%WCPr9{zy8!2VKM&t(`ST5`TAoHghlxt(SH3YG~z}3J)(U5X*3@0i}LlS z(Flw3^{3GYi}Jmq{rb~s#EbR|c|p^kP9t8FuRoneShQb%I*qU>Usr!a{1fHtYH)-_ z`TEmnghly+ch>~(t_j{<6TG{otILsIl&`-nfUqcEe>(tSy?j+)hj{A4;r4=V!sYtF z<@L~B)z#~8MZ7NkAEDd&xW%Q@{N9+1I55v9bHle;#wN=^B~TLpNtcR3BWe^ z$v8;g4%h=f8D|I|01m-V#-Yifz%lqK(p3CpX*PZ`-s)clT#28IGaO`5@D2QAoHW=9 z{0Ki8@5!G4eux5yJrv1MGPzIGu>^X5e%ptjytbB5ID)i4}n{atyGM zj4wIjq+v7o$yTh4GlmXeqMV5MWH}kwNA81|{&IidAbAjC{IVbZQ8?`<5e4=eab65H$BD7WfKwIpKhBHI0Pa$D0pC#$0N+z! z`4DHf4gwD=hk+-Rlfcu;=Rlms0^TrSF5t{n2r$Bce#Ut#^fOLe)d1Eqpj|js6%TA{ zNCc)BP-mPuS|}NDM&eu8i92r!mkc=3;0F3kgK?r&kxU#bBetp};|v3G!8rvDNGWLU z(Vs<{C!fD%?l$AO+m+|;K+H+}!>mUYaZV)?>E%AX+gWkqNRNdbNwT=lDPTtu_Lpzo zVL1LH;`gG|-CTaAvMw|=6=Pvj@*j>aqCf#qw*&v)~B7in8M2%4ZpPM(?HD^Sc4q93w$l2h6>C6y zOk~&e|6v^UG1ca;a4b?4;x7+>Irt+>q?!0j!(SMBwJy#$lZl$vIJev#XOn6C6`WHZ z#A7DogffktY}zZ_GrAknL3b@r3wMKX&*E?e(ua@1`Q*Sqxk7cx^xL6dmrLX`vg@vZ zl_o{VDL54^888Ddmv#4#{DJG`-9Y;C@&9d@^1a<(`FsQA2d6Ec=I;szm#O>D%cpQI znDBd?`~3~>DV*)KD3#z=$6pL+ViP5v;sZaN%XQ%lZd;tS?TQn%_u=#`=pD|=j>Ngx zaq=;of}M&JuU&D{bso+n+_stQNS)n|{hV;jToEl;`Wn@lE8kOBpHd8%KHI zw-4owLwpHNv3`ORt7mXJ^#V?!PUX9`i??F;HSgz8RdfSJ@LoC3|miO=yk-PsPO zI`N0I%~K6eqr}-b!8zM7TiIoJ5q~czyU?!hMcZPyr6oAax!SM+c`Y|=MxJ~f=QZ~j z4#=kr2l00VXDzqse(EXwxfB=9T%J?9qV#cwO9)-jdxdJFwB>eOSEf>&QNdrRF;bal ztcv*8DHgk2oML1w0Xh}JRK_I6Zj7B7J2JK-l(w_q&DfUFuDpnQZR~F&;*qm7Q~3<> z{kW8^?Dw*NKKoVj;|t}K=6>a8_+Mgw6~;s*6!9%NeG;RKaR_6GG80#uu)ibY<6Lf2 z#zICn$9ov>XY9;5w`P9~`(xSPmvJG-Y-3EI80j#_cV_I(*pRUfr)f-nDUbZ<6Zqw3 z3U*f+#-D*s#!SXIPCt+R^Vt6w-}N)c$lR86j&H#+O&Mz{G)A5Is)haWoW{pj+f$Fp z?S-HEsw?~3F;-`6z}T9512YXnKez*g*q1^^`0fIv$jAm>{D6M6j&M`e0PceQ#h}uzlJL4tBwv2}v z`!QBy^fERkl%8Qf?T0cfUJ#N2Z(06?5NDjp?_nIxNS`m3<)e&;7*{d68P_wu##oc_ zBgO`dI~ltZhE55^eu&W+PTxF|U-;Yp7En*4mwUo8$3WQLXwAQ2u(YB33Se1d0{f@H zh6csWz~4;R%2)v364<_20E-tJarYKjv)GGk@5zUl=FvW*=fQi8VhrR7-vXpvz;|xp zGz+j(oJZVy*ey1~ogvQvy~S>Xt38o!EbmG)Kqc>%H)1d1-AHb&^p5%e z&DfXG#n_P1egj|emG39NbcOx793Ri<;P{ywznxIp&hbvhhZuc~5uC=u{;rI%j3XJ7 z`D#t}4`WQ=mjoMp>{WiYpCX_yBf4>_f3qHjDXwI!O`+IZxF6^&Pe(6a|e@w*NvBvUZ*!YU7=dY@)^^UR5P8YmWLrK2Y=-Lkw0*~yca(MttT(g0cj~2_MLjtsL{R&EMdIP zc!qH^<6OqejP)5mW!#4yR)*b(0T?-a6^Z3?33541Yr#@LOQ|a?1+QK z0P9tx4N72bP%G93wPtNl8`cK3Wo=L*YlGUcz9*UWJ?&Z3(}8t7_pn~4BkOfKu|}se z>vFoVE~hK&a=NiDr#owLdaxF!Cu?zfu@}NgA z0oK#J%X*qatfx7_dYZ3UPjiknG|a&fqrouj13t^i~!wl$w@!X26V=yAq(CH(K-DXv4FjEzgQXo)ztQRwVI!Nap#_9-6!=QYYA) zijf{iovqSSuomT&p62=R3}!-i=~>u->MPCSnJ|Y(d@hgpJRa-kc}!p6-k#6B4SgAQ zg^E&B?s3^v6JdO%0CsZX#2CP$2jZ-VCA}=yl@yF7^+#zNEBglflmMZi+YMOY{)g;kQD*#5|Gusoue%*Y=)HYKjYv0HR(X{=-W ziF9moJCu)q(1g{4LpruJpa+M)>$zcqz|l#b~b{2Ju;@;4z}}p!baX8Sh6EyqD8PIHU$=5 zW=YRO?s!>R11m&tO1mL%d;}XW0Zn3G)+EjoeWq&?YhfH4L%XG6%#uK_d%^DBVC>2x zU`cI)^f+w9{1dXwV%RWRi|-e`1sUdD*p&NJv{BbUMq~arfz>}ZTleb%D}MK5^vN{m zDA-Y(2zvSy*1>#f32Y^;lQuyTdRux=`WRMcX!NXD$)vlijTzJwtJ8y>qdoYAKHvgU zVMdfpxIPTKN7Ep?JSQ!XUII;C4|!_4v=?^xK7sw36ZEF4$<3I+*p9IyV|T{Bj46Kq zh>@ltj5&2D;5{89Oj`W$ev(ALAg#bfCvPoN**$A>%m4V#cYAPXfK> zS&Z`-OBk0ju4G)t_&U&Mev@$*<37d@7(ZeBjPZ=W5Oz?$X1u^y%6N@1L}D~EMgZ+0 zRTyhB)@5wK*o;wSbORkB35@L+J2G}>?8}(KI0Wbl$z;rC%wrtGIG%Ab;}bwF`!FZ1G65|!d>x7{SV<^AE7|B?Z zF_tlo(aqSFv2%8=KRdK9V+vy$<1oe?dhs>1fN?D21jZ?hGZ<$w&f!=37ceeiT*0`8 zaU_ZYVm!-uJ|Ax+hJH^N7Qxtvu`Oc?V*%rn`B^!cVapj; zGj3qq%(#tl595LSeAOOykntGf8OC#r-!on#v?xG_#ll#HF`6-!u^FR-@ou2g(vGn! zV?V|rjKdiV7{>!$mZ^+SGR|V0$5_I+lyN0cv#ev>%(#PbALBvBV~l5jZp%5wON>_- zuM>tVjG>H?^eTFIRmNyWD`O+ZI7SDfm*3cJ&DfE#H{(FYOvaInW9d!u@X3r%Fh0#V zoACw47a5mh&y=yl{d;ICFKL%Il_o% zgYX|<+{3ty5mE)>cK{X37RHT?YZzBBE@522xD;rxlrYX?oW)3zqQNqiv6%4*pwTj! zaXjM~#yrMs#!SW>pvf|fF^zE`BRxGbSs)bwJ2UnMnk`)!J219oyqnR*NIaR@;s%CV zRK{kE#0!U7>M|0a7HT2AWvC?@7-GTmOJF2pD5F9c1_=y!h4D9FSlCaD-!no>fS9w4 zrx=eho&j3IXe=yYpD=#FxQ}rcP@lMA!nx zIgB$IXE077N??~&r>bJj5Mh$IO~!2jJVGPpdd-Ctl>3|fZvgjE%8gmCe81;vM6 z7jCI=&kOf!xOl%L^ptRq2=@cw?iKDf;o`gCoPGml3Ra{P8oHv)S5oGiUFMrn<|{7q zjVbfx(TIc+6;MJm8HX^YF!p8a&e#>@8YFWl-t}NNLAWmAl9qz5HxMrM2Zd>kM}*QE zj|h!mG&544Muc2rEG7JRdbuo(0W*zkpwfEz&wZd8oa0}i71B#*$OtKr%!We>8Vlb3 z2}n}&Ai1o7e6SfZ#z9CeXQcD6)Oj5izbnZ#Wh?A+t9T;PR_=)Qp}jKEHFA@MOO%zu zV}x5M+ydd!=+O0%!p#vbjTgla7cS9k3eyOZn~uKMubbf-V99!){262x@}H5fC>EB~ zWJQ02LpD_5YYLuCM(a5kj|lgB-8Dt%cf+1$j458kxrHlgWtu9&PYRc)CTd|?s+VS_ znSii4UQ*2Sq!>uncR{wUf772Besg%AILP@jCo_GH7G$-@MkgYg3>7F)@IBvb7zjL%l9efF=p(+W_`r;IN6NZ zV~*ui_23%@T2cuTe>!vxN8s1BBz2_*rVf$`7_JZ*oCHL3$VD2z>{AHYve`5ktkxwoP)nFXr9>tJ8&3LdZ zhA$u_{>hZC?4L}Or|chE9rRCT?N=ZIUquM|Clhrl`zI40Q}#~|E%U;IcNByE$(Eo1 zUQoIvM0-l$pJJRXMc&r_G})ep4Qlj60lsSdJL}d)BU`Q}`_?kPL%f*#2o%>y?_QPl z5q+W9I3_4Yf$e9|ZDVFxoMOz8>KLQ{L#x&vNiiHk{cdOJo2-1p+BaGd3(6$yT_gPx zr2j5p{oC+8S@b4r-fYDi*1Yj%;cwu*@FI~EFB_G`x3!gi1a_G(!5;IEu)+K@+giQ> zJIe;xR}O=1>hW4&Ep=hciacIj{BpVz=>k_lQ7FA zxf1>=;}1N6fw&(FI9|+DrAJ_XDnvCJqW%XZk0}j$*bnhtfL{0}K+oHb4n~GY=)bO~ z$&cEYL80oRb|$$t>PK&9)`UI!UQ#V%4Ol3T#`uxtb>eLr;3vtgXg7y_aw~WVd?8qB zL|@Rj_4^s(>lqiQ6$TAsgdGN}20w*%d|4UCh__-f7T1g<>&S*mK!YI_?=y`?X)>(P zLkr4Rwh$VVfJV|q!>ToQFZ5z6X!lFfa(oL!#aA{8m2VA1?~RCm332&+7x7z0q+5yiSI_>yD<*uyoxWR<3))!gW8& zM@a;lk!NE(MY(cR-z&LQ{KAS^-|{8shM_iu4J-CQ%?A z$6H^K^!~GS*I%}+K5T&hRr~I`11kgb2xE-5H|dK6_`W*68-SLg?+nD}<15=nyg7?7 z(wT+;6~iw^P(yygh&R$X1)lSe4_Ao3A}v`Fr#mo@@yw9E4}-7ApOjDHSp!BNZ^q4` zuNm+?TsC6k6Rs)q+0;cJ1Fp|7-C3Vc{Nc24M%38)aiX5-_xcATk>wc^H{{8q6+pXwd$Cvoc1v z%N^4yR<+s@c@tt=Tf!1XrsBia$a93vq2ZEU9fl(q*_y-Vwinvm4t1DK^ZK$8vTF9R zu`SAOA&VicV(VvSX2$aEcCQtu;)ZEXN1^6+;V!4+Hpw&6?S6+#zXNB+tX`ix+v~R3 zRlmn+bGThrhuv*+c|BIAN42?~_H3KxvT3T{hI8yzyJojJd~U1L=dd}E*6nZ(v$^~> zhsWl1+1x&x9XHwSUYo<^!Hr1h^=lrhm)hmD+C6Yxs@37~P%{#!bKv}kUGKb8T`&4E zxMS=t9tmH(7U&x{+K8Gv>^7MFLErdnZkH>lZ`|k`7y8DBzVX@6cUHI4&3)sv+q^!T z$78d59X6O{Mki~5zHvLPKD*U!#~<~PX16+g+8yW{jPIS9mZEPQzSOh~%ypWjc8?dM z>2Udd4lAaz$6><=lVf*#3T-acH+<8j%AN3P|d7+niQ6<_8+>$aW&y>9=b( zr`?K9@u1_Vd+b)#=0Rt>xU1}TxIQ=LAEuiP_qsG2W|+r;*{v4h#Gc=Vfv`C>o1K;m zq0fmNVAH{>VNz4g>>iYj3b;I04@OC~!?^=pto@B$44VdOh);Y=_%p!zpN2q0{Y*xBpQAE*}>F=Vk$J${CZK z@<%O@v4@s9IVhtLGzXN*i5cQn??4~B?{FUnFL9>|as~sPAcml6n%C;UDs_56|KQ>* zDs{1wC?F=F*9L;XE@&PRI1n~WHkS*t8|0Y?pqCdp2%rPkU6{3Sy;vZ0r`63FSdkHR znagQ)p*XjXin5}pVXiySSKhz1uk7(yuIR07htG+nNDDn1)Qv6<;tuW38+D1MAkt|$9N2-88 zEMLMV&v$V$8{MV*I1vaW?xI*wRAh4#xNbr9fN{M4clAhUfqg%yGO$HMmGPoVekW}e zE+2MDLbod)>kbaKT}E0sU{9=Ah~RgC?ALp~jFAEXDwiKP66ELA^CJg&=(%!!KF*I3 zn78m&hzj1lYBF zlt-E9Xa#)+^QGAkMHK{=pAF#W%H@T6qmq;t+JYO&OWFKEUOb}z9YaU!@{TU{V5S9( z85;OEE_T1$nd;3bH$?w`vC}dyzu4VOd5FF7gRR5Xcym4G(=wt3UVcH++6}DWa*G{i zZE5ZX<#&@_Aivuaj9>~Al;8jCV#f!UsF8LeIjRj@gT5STecpCa1`&hbt#yrw?QOGi z(E27Z&jz|gL`$a_0lK316piP9xzz8N*enLjm!Ya!x=x*S#tsH&G`|l`AW4=4Q%JAm zx*!G+sU+^q20N74T|Dd(AqTUD)VRrmhC795tJ%Q+LApf*UC><+L!^cz=;0i!$O+pP zgf|GcU?JTk?f9%H>`w4@jyo;tW;!y`Gdy~CxxlP@G?yQe7K!HQ7ZP(Z^w@)C4Lr+vfB%d1s1E*McM&084MJp5pc}pKpdbRK^`P>IbCkZgyTbtt4rFx&``5&=6S0$^y+!FGhHPS__g`I*&*^*$;Frg`xM%~?h+z1f|LJy`0#d*E@Iw)iG z{GK%IFXd>z6C1wfb@)kdL-K&?Mi3JWJb@Py5*nhB%tVMhsex9i5KTYyDHJNYSc_hw z2ugq+1ii#S@EtB14wA32QaRJ#t#jN(6#z4WY|)bld*CN&4Yv}f!RSDXkqHeX#>lOvt&LmwgNv5AGHi^#cGCQ$D~7Z5C$ESYz}?sZ?e^bO}|+P`i2T2RuP4`xDa9%%M}8~6op_)Qz57X3EHL@Z@Bt7EDI_2aa6FpliHEkx;dT2-w!(~n z;XEvFA8x1XpbdITC^Q}MV8UJT*d#bd%ACDH-5_cRMM8$>mZ|6UK|~I&At)0n!!@K# zu!vo#AxKQ11dL3e1jq$}Mu}Kz6lOARfg*@2#W6QqdklupWPBChJzdyhtplBD7I*qi2(ClI{W3G^g)Z4U%iQlpl4FT=v zcwNm!tC|`{@)CLIGEjA5u8^7xw^KIc{(jmxo!H4~xx&62Xt4vE5|IfocbFaQ=!Jv) zfb?QZ1&e`o>{dacp;aNW0S93})c`xK73nD|P*~Y$sJ{~ziM4UNy?$(bXb`Vh+Q)g} zf~wGVt}k57H=R1r;s!Zl&8q_o7d6DrWW-ew7_Aajzvj$8kt7f5`@H%mxfp}UF zckD^Xi1K0I2-34_J{4KHNWLItJaQpcfjDGv2*kr-0+E9tj!;1B2i`4ciqo`qV1M$t z?9eY$$$p!Y_-^QjZ7wGvvIS$oV}#WYmKs$AABiai^r8*44bvn-Wx%WWkPjw1@$6V& zR30jh1sSYa#`8cttHqC8sV3PFpm%HWujX#GxaM|qShFb|r(CTdhbSe*HP<0(wE|NH z;cA%K)I8FlM4Kcv)of{Q#w&xx9z`~m^ig}MaX~RLFV>w9gM&`=>w(t~^QBxIpUS{1 zNf|hFgr9m>P-e!e=L@4ZxL(TK7d>j<^@rAnR%w)4w5y~zYL;4TxPZU@B?g%NQYwvq z_S;{^?dg91xi0fYA2MHWsa7bfs%%1~CQj!{8tyfkqm-0Hdo?x6j6i5qM1L4(&dAHL zCZ&$duvb;9P;^LCc=D*cwA7qJ`ig+PB635lCCc1)SnBA440|25HbsO-Rn;S`Nf~(s zS(#aWd_XKW$6imZLzfLv)y3t$StC$N>WGne{Ao=}RO{BL0F4!?!1!NEjS3KW9FVk} zup;M6Q3nN8_TD~$;w({B`xK2xg=K2LH7Pf5WNw~b91N4{#WgOwOa)r|1WN3akyn`I z&&Ws7R-5%6hgvMh26qtNTrw2nRTjislw!Qev3BM9PJO#P7gNP@q+!uBvHhFne)f8! zT}k;5?szM{XUZ>CcN9LEBsWaju;@(t(y#yZ@Xmq*v4=Ozl9a36zI$uKzmgj~`0n8L zEk8_tFR4m?jpFH98=CK*TX$t%?MB@ms<+mD{Fh#-N}r`Ge(V%y8q@xz7SrDQYVKFR z%{bG)O{+aKKkNL{!_F^?EWcbDH8t^t8@mm?=B_xLz3|zr$1|EvdThs#s=M~S)3WNZ zZ4)omt59%aX6!5buKrRmuJPHcoohe3Z07>o>L<=EJ-ecD^+!^#&UvWvmNPvUb@}pv zYhOk#i(9xN!}`&Y*@oK0V)cLi}+YFAK$NHcmY0X=|j$R0dBuzm~^CrXB}=btLN_~`xWii^WuyY_iloi}gR`7$-U?0)xOFG}lkN(AGV$E;qy5{|8Qtme zX4TDumU@TBR$1Ju)}-+p)nemftoZ3-#Yeth>fQU>TUw6s$nZI}qkERC@!!6N^fgSM z+znpC4qspmr~O~8VSMaKABpCFwTAJPxtxqVTF0)xT*oi^!+puGzfpf#a;G;UZ!Ef$ zYU%UrnmM1YimTXpcg~F|34QLZSnWMyo94g1JbU)hH&ctk2fWjDO5vBMlDfqH^TLki zN!u458MficwmmL9=G|0zcm40v@4HmZk=wohqSaHED2JQXeYeZ$OGnfF|OW%ZTJR`;wNnfKMquLi$cY16Jr>9cBWZ8+id z*9T)?`e3s%cG2i(2W0HLP@`Z=;*@5eg?61WbH+2a1*4Pe4f|wy!RSvT2RNqpo9^6t z)W5gW{JVGWKIaTSczJQ{(&=v=UEhCt%M-?BV`JAfSRMcN$lY&tpVTPym+-AG_m~@c zx>A$874PcnxLEFwp6a7U(B$W3r>K%zok9(1Y5d8O37Meg2bL2S_)s-NZ59Y)f!7sl zv>@NcYkV}mLLn$LFLX~?T4hS}n`u+CQsc`dZGq!(Hh-#ZD2!=m*dFuwqL0h70GlHN+f$@AIPl zcMUTi+vwOZ;;quSMtU+LfcXHh~$E|xFs`&0d3qIR8 z@WfV6y`(W`$GrA#6QgzUipyPgO>O#22&1h=FLx? zYTEGr@?>h_zFX-;4Ye9N9lSSs3aS9B|ML`d56#P0J-(^tl{Gm5}!BxnoD>A3py~-Ss<@>-Mcv{QP(KM_o`yex5z+bX>?s zPt7=&`p&>ty3A?z_@-m6J(Dcz=GT(v{CaWgiV51#zscz|QNim3 z!XSh-gE^f-Ok8{(H0KX_oeT_G9jkGWI#5k98{w7I-fE*jc8Xj*T4XnRG(Oz}f{Iy2 znYHkb%m;B3)ld{QCi;(3=8a56g_(%j)aGi_lEx(sr_>kO5(N#eWQ&phRHtnyK6L@& zNvu2gsOoCfKtTqj%xCx=N7amyS2osH?^=TCYOk%tkmS3jyy}E*<2KZG z_z!iq4DNQq@N=h5byl@1jG4W;cGB6>DN4IhW8RL~@#Xwot{#yuf75xxn~9SjKUezr zhOVDh>eTY;$!bq;p8V6l?)i2=M$aD>cYdf+^@n3l|My7(+l=qnZ5Yod84BC-gBvSo80i8O|zSi z>8f7;Vn{?(+fTfsUJfZr|8-x&7Z*D|8-B{t@kYplEtN?hW`4Zs^qkVjg;~4e?~Rvd zKQexD#Dv08?)|@ZNG;7e5IsM=`DSCzH{%9=^Lw%jveY2$9vShpeJ&D1&m z{R>SOCOmfG_&;Y}z0mWJ|Ffr-G$?ut)OH%E?L&gvDo-veseIqrhptVU->v3Hjdzyo zGWCCq01*#~?<_!l#s5Gr@&1_yruPH%veX`>RyKzVc{)Ln4N(dNLgL$lB9*G4$r;(H zqwz_$fUHZEo0++JIa#Up%4$W542cNslbU1goSUCv$8@JCOGI>HdTttsY7vC!5&5)J3BeR9 z-70D&N)#Ru*0*S62KJtug20W2s(*6hU$V6)-Opb>U9Zj0(H*Xx`gFzBxbS_s_b+O9 z@$>N`-kGy`f7QpY^qrq_`OB5-ZU6kSYuMbH;r&n9JAB?dYEG@5E$f*-eH z?Y6nWN=u!K@AumDuN(d9E~|2~@u)7nPkddoW6`)?6J;9T9`Hdg%IpB+JyX=tVM87pZM?O(~a!S)r{2{sBr`~%d@s+~b`=>T6J@EW% z-*tQN%R{ra9@&3k%ZxKkQ@&BYK71mq`Gl-?)3*Kc?5vhg4@#bOuWeBAq3S<8{o0;I zlNMZiBFY!i#GKZB?#AbRzG@9;-B?oEX7uiVoV~d5vAI9F4&UG9g?{0~ADR5tgR?`v z4AA9=(Nm*Y_y+}QtTrsEA0Skrh7vFm5mEQ{u?1!Z)Tlh*Jlu7njKl-C!}x#@w^V&F zU=luLN=JFhPwnN98W0r!ZF=mZJn9+g?d%-Ubb(k%B^*~9UHFK4IFqd>w8;jeH&sty4e<6 z?r)FRT>Xpt(d0MNJMP{-V)B|UX_Kn-J=}6%vy{ONch}r>JmJ1;pY%KO%%QYXrJs$S zwtV-O*%Pz}VonuQNS~P0yI+fH{rjC#TFyxxv%E>xzSD;~9=`m_$faTF?ho4=PNbK9 zueDe>=f}JSEAuAL{@8qE?4&CP{O`wHOn+*Ia{38vY}mX{-rv?s?$CX9vnFpomiXg| zODBt7=u^gPn=&kH z{Ib2nu?O}%d#1tXFNSQt&pygtY+MLp{JbK|>cmC=W5iae^t;XBrqZ%x;x2650p(_x z!5$H$vNWnOL7{MaBqYh3D$Z(Z{hK!$?a&kTeP`ypmXDpVbgFh}$>-%EGvnSiU_Ep3K2kLz@zI$xvpZ>8W z_QS7cqU- z0nR%>YwWbA{BF`&;~sh2@XOUVDwr}{H@N>V?gi8S>5gq6yJGR+en^ z%-ueF@3^xKEF&s^(c{WR(#I6r`Nh4`fYpx={rIJSFN79e$)dWr4&v&`t83gXTR9Eckukdk0ngsICyn}XW)C^emh&Pd*-<@i+*ih O>BEC*{a+;mBL4>`Q~#F$ literal 0 HcmV?d00001 diff --git a/headless-rust/scripts/speedcamera.service b/headless-rust/scripts/speedcamera.service new file mode 100644 index 0000000..be69591 --- /dev/null +++ b/headless-rust/scripts/speedcamera.service @@ -0,0 +1,21 @@ +[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 +ExecStart=/home/pi/speedcamera/headless-rust/target/release/headless-rust +Restart=always +RestartSec=2 +KillSignal=SIGINT +LimitNOFILE=65536 +LimitMEMLOCK=infinity + +[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..cb804df --- /dev/null +++ b/headless-rust/src/camera/ffi.rs @@ -0,0 +1,114 @@ +#![allow(dead_code)] + +use std::ffi::{c_char, c_void}; + +pub enum ArvCamera {} +pub enum ArvStream {} +pub enum ArvBuffer {} + +#[repr(C)] +pub struct GError { + pub domain: u32, + pub code: i32, + pub message: *const c_char, +} + +pub const ARV_BUFFER_STATUS_SUCCESS: i32 = 0; + +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; + + 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_is_feature_available( + cam: *mut ArvCamera, + feature: *const c_char, + err: *mut *mut GError, + ) -> i32; + + pub fn arv_camera_set_string( + cam: *mut ArvCamera, + feature: *const c_char, + value: *const c_char, + err: *mut *mut GError, + ); + pub fn arv_camera_get_string( + cam: *mut ArvCamera, + feature: *const c_char, + err: *mut *mut GError, + ) -> *const c_char; + + pub fn arv_camera_set_integer( + cam: *mut ArvCamera, + feature: *const c_char, + value: i64, + err: *mut *mut GError, + ); + pub fn arv_camera_get_integer( + cam: *mut ArvCamera, + feature: *const c_char, + err: *mut *mut GError, + ) -> i64; + + pub fn arv_camera_set_float( + cam: *mut ArvCamera, + feature: *const c_char, + value: f64, + err: *mut *mut GError, + ); + pub fn arv_camera_get_float( + cam: *mut ArvCamera, + feature: *const c_char, + err: *mut *mut GError, + ) -> f64; + + pub fn arv_camera_set_boolean( + cam: *mut ArvCamera, + feature: *const c_char, + value: i32, + err: *mut *mut GError, + ); + pub fn arv_camera_get_boolean( + 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, + ); + + pub fn arv_camera_gv_auto_packet_size(cam: *mut ArvCamera, err: *mut *mut GError) -> u32; + + 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_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_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..88bb5ac --- /dev/null +++ b/headless-rust/src/camera/mock.rs @@ -0,0 +1,91 @@ +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) -> 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 + }, + } + } + + pub fn connect(&mut self) { + self.connected = true; + } + + pub fn disconnect(&mut self) { + self.connected = false; + } + + 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_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); + img.write_to(&mut cursor, image::ImageFormat::Jpeg).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..8824044 --- /dev/null +++ b/headless-rust/src/camera/mod.rs @@ -0,0 +1,644 @@ +pub mod ffi; +pub mod mock; + +use crate::models::{AppSettings, CameraStatusPayload, MfsConfigResult}; +use ffi::*; +use base64::Engine; +use image::{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 { + if self.mock_mode { + return self.mock_camera.lock().unwrap().status(); + } + + 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, + } + } + } else { + CameraStatusPayload { + connected: false, + vendor: None, + model: None, + serial: None, + } + } + } + + 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 { + println!("[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(); + println!("[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(); + println!("[camera] Failed to open camera: {}", msg); + g_error_free(err); + } + return; + } + + arv_camera_gv_auto_packet_size(cam, &mut err); + + // Configure Trigger mode & strobe + Self::set_feature_str_internal(cam, "AcquisitionMode", "Continuous"); + Self::set_feature_str_internal(cam, "TriggerMode", "On"); + Self::set_feature_str_internal(cam, "TriggerSource", "Software"); + + Self::set_feature_str_internal(cam, "LineSelector", "Line1"); + Self::set_feature_str_internal(cam, "LineMode", "Strobe"); + Self::set_feature_str_internal(cam, "LineSource", "ExposureActive"); + Self::set_feature_bool_internal(cam, "StrobeEnable", true); + Self::set_feature_int_internal( + cam, + "StrobeLineDuration", + settings.strobe_line_duration as i64, + ); + + // Exposure & Gain + Self::set_feature_str_internal(cam, "ExposureAuto", &settings.exposure_auto); + if settings.exposure_auto == "Off" { + Self::set_feature_float_internal(cam, "ExposureTime", settings.camera_exposure); + } + + Self::set_feature_str_internal(cam, "GainAuto", &settings.gain_auto); + if settings.gain_auto == "Off" { + Self::set_feature_float_internal(cam, "Gain", settings.camera_gain); + } + + if settings.frame_rate > 0.0 { + Self::set_feature_bool_internal(cam, "AcquisitionFrameRateEnable", true); + Self::set_feature_float_internal( + cam, + "AcquisitionFrameRate", + settings.frame_rate, + ); + } + + // Create Stream with 5 pre-allocated buffers + let stream = arv_camera_create_stream(cam, null_mut(), null_mut(), &mut err); + if stream.is_null() { + println!("[camera] Failed to create stream"); + g_object_unref(cam as *mut _); + return; + } + + let payload_size = Self::get_feature_int_internal(cam, "PayloadSize").max(1024 * 1024); + for _ in 0..5 { + let buf = arv_buffer_new_allocate(payload_size as usize); + arv_stream_push_buffer(stream, buf); + } + + *self.camera_ptr.lock().unwrap() = cam; + *self.stream_ptr.lock().unwrap() = stream; + self.is_connected.store(true, Ordering::SeqCst); + + println!("[camera] Connected successfully to industrial camera"); + 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 stream_guard = self.stream_ptr.lock().unwrap(); + if !stream_guard.is_null() { + g_object_unref(*stream_guard as *mut _); + *stream_guard = null_mut(); + } + + let mut cam_guard = self.camera_ptr.lock().unwrap(); + if !cam_guard.is_null() { + g_object_unref(*cam_guard as *mut _); + *cam_guard = null_mut(); + } + } + + println!("[camera] Disconnected"); + let _ = self.status_sender.send(self.get_status()); + } + + pub fn capture_frame(&self) -> Option> { + if self.mock_mode { + return self.mock_camera.lock().unwrap().capture_frame(); + } + + if !self.is_connected.load(Ordering::SeqCst) { + return None; + } + + let cam = *self.camera_ptr.lock().unwrap(); + let stream = *self.stream_ptr.lock().unwrap(); + if cam.is_null() || stream.is_null() { + return None; + } + + unsafe { + // Discard stale buffers + loop { + let stale = arv_stream_try_pop_buffer(stream); + if stale.is_null() { + break; + } + arv_stream_push_buffer(stream, stale); + } + + // Software trigger + let mut err = null_mut(); + let trigger_cmd = CString::new("TriggerSoftware").unwrap(); + arv_camera_execute_command(cam, trigger_cmd.as_ptr(), &mut err); + + // Wait up to 2 seconds for frame + let buffer = arv_stream_timeout_pop_buffer(stream, 2_000_000); + if buffer.is_null() { + println!("[camera] Capture frame timed out"); + return None; + } + + if arv_buffer_get_status(buffer) != ARV_BUFFER_STATUS_SUCCESS { + println!("[camera] Capture buffer status != SUCCESS"); + 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_slice = std::slice::from_raw_parts(data_ptr, size); + + // Convert to PNG buffer + let png_bytes = Self::raw_buffer_to_png(raw_slice, width, height, pixel_format); + + // Return buffer back to stream pool + arv_stream_push_buffer(stream, buffer); + + png_bytes + } + } + + 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 this = self.clone(); + + tokio::task::spawn_blocking(move || { + println!("[camera] Setup preview stream started"); + + if !this.mock_mode { + let cam = *this.camera_ptr.lock().unwrap(); + if !cam.is_null() { + Self::set_feature_str_internal(cam, "TriggerMode", "Off"); + Self::set_feature_str_internal(cam, "ExposureAuto", "Continuous"); + Self::set_feature_str_internal(cam, "GainAuto", "Continuous"); + Self::set_feature_bool_internal(cam, "AcquisitionFrameRateEnable", true); + Self::set_feature_float_internal(cam, "AcquisitionFrameRate", 10.0); + } + } + + 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(100)); + continue; + } + + let stream = *this.stream_ptr.lock().unwrap(); + if stream.is_null() { + std::thread::sleep(std::time::Duration::from_millis(100)); + continue; + } + + unsafe { + let buffer = arv_stream_timeout_pop_buffer(stream, 100_000); + if !buffer.is_null() { + if arv_buffer_get_status(buffer) == ARV_BUFFER_STATUS_SUCCESS { + 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 = std::slice::from_raw_parts(data_ptr, size); + + if let Some(jpeg) = + Self::raw_buffer_to_downscaled_jpeg(slice, width, height, pixel_format) + { + let b64 = + base64::engine::general_purpose::STANDARD.encode(&jpeg); + let _ = this.frame_sender.send(b64); + } + } + arv_stream_push_buffer(stream, buffer); + } + } + std::thread::sleep(std::time::Duration::from_millis(40)); + } + + println!("[camera] Setup preview stream stopped"); + }); + } + + pub fn stop_setup_stream(&self, settings: &AppSettings) { + self.setup_stream_active.store(false, Ordering::SeqCst); + + if !self.mock_mode { + let cam = *self.camera_ptr.lock().unwrap(); + if !cam.is_null() { + Self::set_feature_str_internal(cam, "TriggerMode", "On"); + Self::set_feature_str_internal(cam, "ExposureAuto", &settings.exposure_auto); + if settings.exposure_auto == "Off" { + Self::set_feature_float_internal(cam, "ExposureTime", settings.camera_exposure); + } + Self::set_feature_str_internal(cam, "GainAuto", &settings.gain_auto); + if settings.gain_auto == "Off" { + Self::set_feature_float_internal(cam, "Gain", settings.camera_gain); + } + if settings.frame_rate > 0.0 { + Self::set_feature_float_internal( + cam, + "AcquisitionFrameRate", + settings.frame_rate, + ); + } + } + } + } + + pub fn apply_mfs_config(&self, mfs_content: &str) -> 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 }; + } + + for line in mfs_content.lines() { + let line = line.trim(); + if line.is_empty() || line.starts_with('#') { + continue; + } + + if let Some((k, v)) = line.split_once('=') { + let key = k.trim(); + let val = v.trim(); + + let ok = if let Ok(int_val) = val.parse::() { + Self::set_feature_int_internal(cam, key, int_val) + } else if let Ok(float_val) = val.parse::() { + Self::set_feature_float_internal(cam, key, float_val) + } else { + Self::set_feature_str_internal(cam, key, val) + }; + + if ok { + applied.push(line.to_string()); + } else { + failed.push(line.to_string()); + } + } + } + + 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_feature_float_internal(cam, "ExposureTime", 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_feature_float_internal(cam, "Gain", 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_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() { + if format == "Color" { + for fmt in ["BayerBG8", "BayerRG8", "RGB8Packed", "RGB8"] { + if Self::set_feature_str_internal(cam, "PixelFormat", fmt) { + break; + } + } + } else { + Self::set_feature_str_internal(cam, "PixelFormat", "Mono8"); + } + } + } + } + + // Helper functions for raw buffer decoding + fn raw_buffer_to_png(raw: &[u8], width: u32, height: u32, _pixel_format: u32) -> Option> { + let expected_mono = (width * height) as usize; + let expected_rgb = (width * height * 3) as usize; + + let mut buf = Vec::new(); + let mut cursor = Cursor::new(&mut buf); + + if raw.len() >= expected_rgb { + let img: ImageBuffer, &[u8]> = + ImageBuffer::from_raw(width, height, &raw[..expected_rgb])?; + img.write_to(&mut cursor, image::ImageFormat::Png).ok()?; + } else if raw.len() >= expected_mono { + let img: ImageBuffer, &[u8]> = + ImageBuffer::from_raw(width, height, &raw[..expected_mono])?; + img.write_to(&mut cursor, image::ImageFormat::Png).ok()?; + } else { + return None; + } + + Some(buf) + } + + fn raw_buffer_to_downscaled_jpeg( + raw: &[u8], + width: u32, + height: u32, + _pixel_format: u32, + ) -> Option> { + let expected_mono = (width * height) as usize; + let expected_rgb = (width * height * 3) as usize; + + let dynamic_img = if raw.len() >= expected_rgb { + let img: ImageBuffer, Vec> = + ImageBuffer::from_raw(width, height, raw[..expected_rgb].to_vec())?; + image::DynamicImage::ImageRgb8(img) + } else if raw.len() >= expected_mono { + let img: ImageBuffer, Vec> = + ImageBuffer::from_raw(width, height, raw[..expected_mono].to_vec())?; + image::DynamicImage::ImageLuma8(img) + } else { + return None; + }; + + // Resize down to 800px width max for fast preview bandwidth over Wi-Fi + let resized = dynamic_img.resize(800, 600, image::imageops::FilterType::Nearest); + + let mut buf = Vec::new(); + let mut cursor = Cursor::new(&mut buf); + resized.write_to(&mut cursor, image::ImageFormat::Jpeg).ok()?; + + Some(buf) + } + + fn set_feature_str_internal(cam: *mut ArvCamera, feature: &str, value: &str) -> bool { + unsafe { + 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_camera_set_string(cam, f_cstr.as_ptr(), v_cstr.as_ptr(), &mut err); + if !err.is_null() { + g_error_free(err); + false + } else { + true + } + } + } + + fn set_feature_int_internal(cam: *mut ArvCamera, feature: &str, value: i64) -> bool { + unsafe { + let f_cstr = match CString::new(feature) { + Ok(s) => s, + Err(_) => return false, + }; + let mut err = null_mut(); + arv_camera_set_integer(cam, f_cstr.as_ptr(), value, &mut err); + if !err.is_null() { + g_error_free(err); + false + } else { + true + } + } + } + + fn set_feature_float_internal(cam: *mut ArvCamera, feature: &str, value: f64) -> bool { + unsafe { + let f_cstr = match CString::new(feature) { + Ok(s) => s, + Err(_) => return false, + }; + let mut err = null_mut(); + arv_camera_set_float(cam, f_cstr.as_ptr(), value, &mut err); + if !err.is_null() { + g_error_free(err); + false + } else { + true + } + } + } + + fn set_feature_bool_internal(cam: *mut ArvCamera, feature: &str, value: bool) -> bool { + unsafe { + let f_cstr = match CString::new(feature) { + Ok(s) => s, + Err(_) => return false, + }; + let mut err = null_mut(); + arv_camera_set_boolean( + cam, + f_cstr.as_ptr(), + if value { 1 } else { 0 }, + &mut err, + ); + if !err.is_null() { + g_error_free(err); + false + } else { + true + } + } + } + + fn get_feature_int_internal(cam: *mut ArvCamera, feature: &str) -> i64 { + unsafe { + let f_cstr = match CString::new(feature) { + Ok(s) => s, + Err(_) => return 0, + }; + let mut err = null_mut(); + let res = arv_camera_get_integer(cam, f_cstr.as_ptr(), &mut err); + if !err.is_null() { + g_error_free(err); + 0 + } else { + res + } + } + } +} diff --git a/headless-rust/src/config.rs b/headless-rust/src/config.rs new file mode 100644 index 0000000..22a1cd9 --- /dev/null +++ b/headless-rust/src/config.rs @@ -0,0 +1,51 @@ +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) -> Self { + let host = std::env::var("HOST").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..a5c3f4e --- /dev/null +++ b/headless-rust/src/db/laps.rs @@ -0,0 +1,181 @@ +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 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..c1f2641 --- /dev/null +++ b/headless-rust/src/integrations/teable.rs @@ -0,0 +1,201 @@ +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) + } + + #[allow(dead_code)] + pub async fn verify_table(&self, _url: &str, _token: &str, _table_id: &str) -> Result { + Ok(TeableSchemaCheck { + missing_fields: Vec::new(), + }) + } + + 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..7e40921 --- /dev/null +++ b/headless-rust/src/main.rs @@ -0,0 +1,110 @@ +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, +} + +#[rocket::main] +async fn main() -> Result<(), rocket::Error> { + let args = Args::parse(); + let config = AppConfig::new(args.mock, args.port); + + println!("─────────────────────────────────────────────────────────────────"); + println!(" ⚡ Speedcamera Headless Daemon (Rust & Rocket)"); + println!(" • Port: http://{}:{}", config.host, config.port); + println!(" • Data Dir: {}", config.data_dir.display()); + println!(" • Mock Mode: {}", config.mock_mode); + println!("─────────────────────────────────────────────────────────────────"); + + let network_summary = network::get_system_network_summary(); + println!(" • 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() + ); + println!(" • 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() + ); + println!("─────────────────────────────────────────────────────────────────"); + + // 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); + + // ─── Instant Shutter Trigger Pipeline (<10ms latency) ───────────────────── + 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 { + while let Ok(msg) = serial_rx.recv().await { + if let models::SerialStatusPayload::Speeding { value, direction, .. } = msg { + println!("[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(); + + tokio::task::spawn_blocking(move || { + if let Some(png_bytes) = cam.capture_frame() { + if let Ok(img_path) = store_clone.save_image_bytes(&png_bytes, "png") { + 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) { + println!("[trigger-pipeline] Recorded violation #{} ({} km/h)", v.id, v.measured_speed); + } + } + } else { + println!("[trigger-pipeline] Failed to capture frame during speeding event"); + } + }); + } + } + }); + + // Build and launch Rocket web server + let server = web::build_rocket(config, db, store, camera, serial); + server.launch().await?; + + Ok(()) +} diff --git a/headless-rust/src/models.rs b/headless-rust/src/models.rs new file mode 100644 index 0000000..5c36df7 --- /dev/null +++ b/headless-rust/src/models.rs @@ -0,0 +1,368 @@ +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" | "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" + pub description: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SystemNetworkSummary { + pub camera_lan: SubnetInfo, + pub hotspot_ap: SubnetInfo, + pub interfaces: Vec, +} + +#[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, +} + +#[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, +} + +#[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, + 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, + pub flash_delay: Option, + pub flash_duration: Option, + pub sensor_distance: f64, + pub debug_enabled: bool, + pub lap_mode: String, + pub lap_active: bool, + pub lap_auto_flash: Option, + pub lap_dir_filter: String, +} + +#[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: i64, + #[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(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..f95e57e --- /dev/null +++ b/headless-rust/src/network/mod.rs @@ -0,0 +1,111 @@ +use crate::models::{NetworkInterfaceDetail, SubnetInfo, SystemNetworkSummary}; +use std::collections::HashMap; + +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; + + // 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" || ip.starts_with("192.168.4."); + 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"); + + let role = if is_loopback { + "loopback" + } else if is_camera_ip || is_eth_name { + "camera-lan" + } else if is_hotspot_ip || is_wifi_name { + "hotspot-ap" + } 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 detail = NetworkInterfaceDetail { + name: name.clone(), + role: role.to_string(), + address: ip.clone(), + family: "IPv4".to_string(), + netmask, + mac: String::new(), + 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.is_none() || ip == "192.168.4.1") { + hotspot_ap_iface = Some(detail.clone()); + } + + interfaces.push(detail); + } + } + + let camera_status = match &camera_lan_iface { + None => "missing", + Some(iface) if iface.address == "192.168.1.100" => "ok", + Some(_) => "ip_mismatch", + }; + + let hotspot_status = match &hotspot_ap_iface { + None => "missing", + Some(iface) if iface.address == "192.168.4.1" => "ok", + Some(_) => "ip_mismatch", + }; + + SystemNetworkSummary { + 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()), + 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.to_string(), + description: "Wi-Fi Access Point & Remote Web UI Control (wlan0/wifi0)".to_string(), + }, + interfaces, + } +} diff --git a/headless-rust/src/serial/mock.rs b/headless-rust/src/serial/mock.rs new file mode 100644 index 0000000..ba408c3 --- /dev/null +++ b/headless-rust/src/serial/mock.rs @@ -0,0 +1,65 @@ +use crate::models::{EspPongConfig, SerialStatusPayload}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; +use tokio::sync::broadcast; + +pub struct MockSerial { + #[allow(dead_code)] + running: Arc, +} + +impl MockSerial { + pub fn new(tx: broadcast::Sender) -> Self { + let running = Arc::new(AtomicBool::new(true)); + let r = running.clone(); + + tokio::spawn(async move { + let mut counter = 0; + while r.load(Ordering::SeqCst) { + tokio::time::sleep(tokio::time::Duration::from_secs(5)).await; + counter += 1; + + let now = chrono::Utc::now().timestamp_millis(); + let speed = 35.0 + (counter % 15) as f64; + + 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); + } + }); + + Self { running } + } + + pub fn send_command(&self, json: &str, tx: &broadcast::Sender) { + if json.contains("\"PING\"") { + 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: "single".to_string(), + lap_active: false, + 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..633a0f6 --- /dev/null +++ b/headless-rust/src/serial/mod.rs @@ -0,0 +1,198 @@ +pub mod mock; +pub mod protocol; + +use crate::models::{PortInfo, SerialStatusPayload}; +use protocol::EspMessage; +use std::io::{BufRead, BufReader, Write}; +use std::sync::atomic::{AtomicBool, 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, + is_running: Arc, + status_sender: broadcast::Sender, +} + +impl SerialService { + pub fn new(mock_mode: bool) -> Arc { + let (status_tx, _) = broadcast::channel(32); + + let service = Arc::new(Self { + mock_mode, + mock_serial: Mutex::new(None), + active_port: Mutex::new(None), + active_path: Mutex::new(String::new()), + 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 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) => { + println!("[serial] Failed to list ports: {}", e); + Vec::new() + } + } + } + + pub fn open_port(self: &Arc, port_path: &str) { + if self.mock_mode { + println!("[serial] Opened mock port {}", port_path); + let _ = self.status_sender.send(SerialStatusPayload::Connected); + return; + } + + let mut current_path = self.active_path.lock().unwrap(); + *current_path = port_path.to_string(); + + let this = self.clone(); + let path = port_path.to_string(); + + tokio::task::spawn_blocking(move || { + let builder = serialport::new(&path, 115_200).timeout(Duration::from_millis(500)); + match builder.open() { + Ok(port) => { + println!("[serial] Successfully opened {}", path); + let _ = this.status_sender.send(SerialStatusPayload::Connected); + + let reader_port = match port.try_clone() { + Ok(p) => p, + Err(e) => { + println!("[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) { + line_buf.clear(); + match reader.read_line(&mut line_buf) { + Ok(0) => { + // EOF / disconnected + std::thread::sleep(Duration::from_millis(50)); + } + Ok(_) => { + let trimmed = line_buf.trim(); + if !trimmed.is_empty() { + this.handle_line(trimmed); + } + } + Err(ref e) if e.kind() == std::io::ErrorKind::TimedOut => { + // Timeout is normal for non-blocking read + } + Err(e) => { + println!("[serial] Read error: {}", e); + break; + } + } + } + + println!("[serial] Port {} closed", path); + *this.active_port.lock().unwrap() = None; + let _ = this.status_sender.send(SerialStatusPayload::Disconnected); + } + Err(e) => { + println!("[serial] Failed to open {}: {}", path, e); + let _ = this.status_sender.send(SerialStatusPayload::Disconnected); + } + } + }); + } + + pub fn close_port(&self) { + *self.active_port.lock().unwrap() = None; + *self.active_path.lock().unwrap() = String::new(); + let _ = self.status_sender.send(SerialStatusPayload::Disconnected); + } + + 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) { + println!("[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\"") { + println!("[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..1010327 --- /dev/null +++ b/headless-rust/src/serial/protocol.rs @@ -0,0 +1,98 @@ +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: i64, + #[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 }, +} + +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 { .. } => None, + } + } +} diff --git a/headless-rust/src/storage/mod.rs b/headless-rust/src/storage/mod.rs new file mode 100644 index 0000000..3029ba7 --- /dev/null +++ b/headless-rust/src/storage/mod.rs @@ -0,0 +1,73 @@ +pub mod skin; + +use base64::Engine; +use chrono::Utc; +use std::fs; +use std::path::{Path, PathBuf}; + +#[derive(Clone)] +pub struct FileStore { + images_dir: PathBuf, +} + +impl FileStore { + pub fn new(images_dir: &Path) -> Self { + let _ = fs::create_dir_all(images_dir); + Self { + images_dir: images_dir.to_path_buf(), + } + } + + 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))?; + + self.save_image_bytes(&decoded, "png") + } + + 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..b7741f4 --- /dev/null +++ b/headless-rust/src/storage/skin.rs @@ -0,0 +1,85 @@ +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 PNG buffer + let mut out = Vec::new(); + let mut cursor = Cursor::new(&mut out); + canvas.write_to(&mut cursor, image::ImageFormat::Png).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..5148629 --- /dev/null +++ b/headless-rust/src/web/embedded.rs @@ -0,0 +1,52 @@ +use rocket::http::ContentType; +use rocket::response::{self, Responder, Response}; +use rocket::Request; +use rust_embed::RustEmbed; +use std::io::Cursor; + +#[derive(RustEmbed)] +#[folder = "dist/"] +pub struct Asset; + +pub struct EmbeddedFile { + pub data: Vec, + pub content_type: ContentType, +} + +impl<'r> Responder<'r, 'static> for EmbeddedFile { + fn respond_to(self, _: &'r Request<'_>) -> response::Result<'static> { + Response::build() + .header(self.content_type) + .sized_body(self.data.len(), Cursor::new(self.data)) + .ok() + } +} + +pub fn get_asset(path: &str) -> Option { + 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 ext = std::path::Path::new(target) + .extension() + .and_then(|e| e.to_str()) + .unwrap_or(""); + let content_type = ContentType::from_extension(ext).unwrap_or(ContentType::HTML); + Some(EmbeddedFile { + data: file.data.into_owned(), + content_type, + }) + } else if let Some(index) = Asset::get("index.html") { + // SPA Fallback: Return index.html for client-side routing + Some(EmbeddedFile { + data: index.data.into_owned(), + content_type: ContentType::HTML, + }) + } else { + None + } +} diff --git a/headless-rust/src/web/mod.rs b/headless-rust/src/web/mod.rs new file mode 100644 index 0000000..d29c70e --- /dev/null +++ b/headless-rust/src/web/mod.rs @@ -0,0 +1,51 @@ +pub mod embedded; +pub mod routes; +pub mod rpc; +pub mod ws; + +use crate::camera::CameraService; +use crate::config::AppConfig; +use crate::db::Database; +use crate::models::FlashProgressPayload; +use crate::serial::SerialService; +use crate::storage::FileStore; +use rocket::figment::Figment; +use rocket::{Build, Rocket}; +use std::net::Ipv4Addr; +use std::sync::Arc; +use tokio::sync::broadcast; + +pub fn build_rocket( + config: AppConfig, + db: Database, + store: FileStore, + camera: Arc, + serial: Arc, +) -> Rocket { + let (flash_tx, _) = broadcast::channel::(32); + + let figment = Figment::from(rocket::Config::default()) + .merge(("port", config.port)) + .merge(("address", config.host.parse::().unwrap_or(Ipv4Addr::new(0, 0, 0, 0)))); + + rocket::custom(figment) + .manage(config) + .manage(db) + .manage(store) + .manage(camera) + .manage(serial) + .manage(flash_tx) + .mount( + "/", + rocket::routes![ + routes::health, + routes::network, + routes::get_image, + routes::get_skinned_image, + ws::ws_rpc, + ws::ws_alias, + routes::index, + routes::static_assets, + ], + ) +} diff --git a/headless-rust/src/web/routes.rs b/headless-rust/src/web/routes.rs new file mode 100644 index 0000000..cdeb318 --- /dev/null +++ b/headless-rust/src/web/routes.rs @@ -0,0 +1,78 @@ +use crate::camera::CameraService; +use crate::config::AppConfig; +use crate::db::Database; +use crate::network::get_system_network_summary; +use crate::storage::skin::render_poliscan_skin; +use crate::storage::FileStore; +use crate::web::embedded::{get_asset, EmbeddedFile}; +use rocket::http::{ContentType, Status}; +use rocket::serde::json::Json; +use rocket::State; +use serde_json::json; +use std::sync::Arc; + +#[rocket::get("/api/health")] +pub fn health( + config: &State, + camera: &State>, +) -> Json { + Json(json!({ + "status": "ok", + "platform": std::env::consts::OS, + "camera": camera.get_status(), + "network": get_system_network_summary(), + "mockMode": config.mock_mode, + })) +} + +#[rocket::get("/api/network")] +pub fn network() -> Json { + Json(get_system_network_summary()) +} + +#[rocket::get("/image?")] +pub fn get_image( + path: Option, + store: &State, +) -> Result<(ContentType, Vec), Status> { + let p = path.ok_or(Status::BadRequest)?; + let bytes = store.read_image(&p).ok_or(Status::NotFound)?; + Ok((ContentType::PNG, bytes)) +} + +#[rocket::get("/skinned-image?")] +pub fn get_skinned_image( + #[allow(non_snake_case)] violationId: Option, + db: &State, + store: &State, +) -> Result<(ContentType, Vec), Status> { + let id = violationId.ok_or(Status::BadRequest)?; + let conn = db.lock(); + + let violation = crate::db::violations::get_violation_by_id(&conn, id) + .map_err(|_| Status::InternalServerError)? + .ok_or(Status::NotFound)?; + + let settings = crate::db::settings::get_settings(&conn).map_err(|_| Status::InternalServerError)?; + let image_bytes = store.read_image(&violation.image_path).ok_or(Status::NotFound)?; + + let rendered = render_poliscan_skin( + &image_bytes, + &violation, + &settings.skin_measuring_location, + ) + .ok_or(Status::InternalServerError)?; + + Ok((ContentType::PNG, rendered)) +} + +#[rocket::get("/", rank = 20)] +pub fn static_assets(file: std::path::PathBuf) -> Result { + let path_str = file.to_string_lossy().to_string(); + get_asset(&path_str).ok_or(Status::NotFound) +} + +#[rocket::get("/", rank = 10)] +pub fn index() -> Result { + get_asset("index.html").ok_or(Status::NotFound) +} diff --git a/headless-rust/src/web/rpc.rs b/headless-rust/src/web/rpc.rs new file mode 100644 index 0000000..eece988 --- /dev/null +++ b/headless-rust/src/web/rpc.rs @@ -0,0 +1,507 @@ +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 db: Database, + pub store: FileStore, + pub camera: Arc, + pub serial: Arc, + pub teable: TeableClient, + pub flash_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 conn = ctx.db.lock(); + let page = crate::db::violations::query_violations(&conn, &q).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 conn = ctx.db.lock(); + let violation = + crate::db::violations::get_violation_by_id(&conn, id).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 conn = ctx.db.lock(); + if let Ok(Some(v)) = crate::db::violations::get_violation_by_id(&conn, id) { + let _ = crate::db::violations::remove_violation(&conn, id); + ctx.store.delete_image(&v.image_path); + } + Ok(Value::Null) + } + + "exportViolationsCsv" => { + let date_from = params["dateFrom"].as_str(); + let date_to = params["dateTo"].as_str(); + let min_speed = params["minSpeed"].as_f64(); + let conn = ctx.db.lock(); + let csv = crate::db::violations::export_csv(&conn, date_from, date_to, min_speed) + .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 raw_png = if let Some(ref b64) = input.image_base64 { + let clean = b64.trim_start_matches("data:image/png;base64,"); + base64::engine::general_purpose::STANDARD + .decode(clean) + .map_err(|e| e.to_string())? + } else { + ctx.camera + .capture_frame() + .ok_or_else(|| "Failed to capture frame from industrial camera".to_string())? + }; + + let image_path = ctx + .store + .save_image_bytes(&raw_png, "png") + .map_err(|e| e.to_string())?; + + let conn = ctx.db.lock(); + let v = crate::db::violations::insert_violation(&conn, &input, &image_path) + .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"); + let conn = ctx.db.lock(); + let session = + crate::db::laps::create_lap_session(&conn, lap_mode).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 conn = ctx.db.lock(); + crate::db::laps::close_lap_session(&conn, id).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 start_img_path = if let Some(ref b64) = input.start_image_base64 { + ctx.store.save_base64_image(b64).ok() + } else { + None + }; + + let end_img_path = if let Some(ref b64) = input.end_image_base64 { + ctx.store.save_base64_image(b64).ok() + } else { + None + }; + + let conn = ctx.db.lock(); + let lap = crate::db::laps::insert_lap( + &conn, + &input, + start_img_path.as_deref(), + end_img_path.as_deref(), + ) + .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 conn = ctx.db.lock(); + let (sessions, total) = + crate::db::laps::get_lap_sessions(&conn, page, limit).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 conn = ctx.db.lock(); + let session = + crate::db::laps::get_lap_session_by_id(&conn, id).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 conn = ctx.db.lock(); + crate::db::laps::delete_lap_session(&conn, id).map_err(|e| e.to_string())?; + Ok(Value::Null) + } + + "deleteLap" => { + let id = params["id"].as_i64().ok_or("Missing id parameter")?; + let conn = ctx.db.lock(); + crate::db::laps::delete_lap(&conn, id).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())); + } + Ok(Value::String(format!( + "/image?path={}", + urlencoding::encode(image_path) + ))) + } + + "getSkinnedImageData" => { + let violation_id = params["violationId"].as_i64().ok_or("Missing violationId")?; + Ok(Value::String(format!( + "/skinned-image?violationId={}", + violation_id + ))) + } + + "exportSkinnedImages" => { + let ids = params["violationIds"] + .as_array() + .ok_or("Missing violationIds")?; + let target_dir = params["targetDir"].as_str().ok_or("Missing targetDir")?; + + let conn = ctx.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) = ctx.store.read_image(&v.image_path) { + if let Some(skinned) = render_poliscan_skin( + &bytes, + &v, + &settings.skin_measuring_location, + ) { + let out_path = Path::new(target_dir) + .join(format!("violation-{}-{}.png", v.id, v.timestamp.replace(":", "-"))); + if std::fs::write(out_path, skinned).is_ok() { + exported += 1; + continue; + } + } + } + } + failed += 1; + } + } + + Ok(serde_json::to_value(ExportSkinnedResult { exported, failed }).unwrap()) + } + + // ─── Settings ───────────────────────────────────────────────────────── + "getSettings" => { + let conn = ctx.db.lock(); + let settings = crate::db::settings::get_settings(&conn).map_err(|e| e.to_string())?; + Ok(serde_json::to_value(settings).unwrap()) + } + + "saveSetting" => { + let key = params["key"].as_str().ok_or("Missing key")?; + let value = params["value"].as_str().ok_or("Missing value")?; + let conn = ctx.db.lock(); + crate::db::settings::save_setting(&conn, key, value).map_err(|e| e.to_string())?; + Ok(Value::Null) + } + + // ─── Serial ─────────────────────────────────────────────────────────── + "listPorts" => { + let ports = ctx.serial.list_ports(); + Ok(serde_json::to_value(ports).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")?; + ctx.serial.send_command(json_cmd); + Ok(Value::Null) + } + + // ─── Camera HW ──────────────────────────────────────────────────────── + "connectCamera" => { + let conn = ctx.db.lock(); + let settings = crate::db::settings::get_settings(&conn).unwrap_or_default(); + ctx.camera.connect(&settings); + Ok(Value::Null) + } + + "disconnectCamera" => { + ctx.camera.disconnect(); + Ok(Value::Null) + } + + "getCameraStatus" => { + let status = ctx.camera.get_status(); + Ok(serde_json::to_value(status).unwrap()) + } + + "captureFrame" => { + if let Some(png_bytes) = ctx.camera.capture_frame() { + let b64 = base64::engine::general_purpose::STANDARD.encode(&png_bytes); + Ok(Value::String(b64)) + } else { + Ok(Value::Null) + } + } + + "setCameraExposure" => { + let val = params["value"].as_f64().ok_or("Missing exposure value")?; + ctx.camera.set_exposure(val); + Ok(Value::Null) + } + + "setCameraGain" => { + let val = params["value"].as_f64().ok_or("Missing gain value")?; + ctx.camera.set_gain(val); + Ok(Value::Null) + } + + "applyMfsConfig" => { + let mfs = params["mfsContent"].as_str().ok_or("Missing mfsContent")?; + let res = ctx.camera.apply_mfs_config(mfs); + Ok(serde_json::to_value(res).unwrap()) + } + + "startSetupStream" => { + ctx.camera.start_setup_stream(); + Ok(Value::Null) + } + + "stopSetupStream" => { + let conn = ctx.db.lock(); + let settings = crate::db::settings::get_settings(&conn).unwrap_or_default(); + ctx.camera.stop_setup_stream(&settings); + Ok(Value::Null) + } + + "setCameraPixelFormat" => { + let fmt = params["format"].as_str().ok_or("Missing format")?; + ctx.camera.set_pixel_format(fmt); + Ok(Value::Null) + } + + "getCameraPixelFormat" => { + let conn = ctx.db.lock(); + let settings = crate::db::settings::get_settings(&conn).unwrap_or_default(); + Ok(Value::String(settings.pixel_format)) + } + + "setCameraStrobeDuration" => { + let val = params["value"].as_i64().ok_or("Missing value")?; + ctx.camera.set_strobe_duration(val); + 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()) + } + + // ─── 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()) + } + + "listTeableSpaces" => { + let settings = { + let conn = ctx.db.lock(); + crate::db::settings::get_settings(&conn).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 settings = { + let conn = ctx.db.lock(); + crate::db::settings::get_settings(&conn).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 settings = { + let conn = ctx.db.lock(); + crate::db::settings::get_settings(&conn).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()) + } + + "syncLapToTeable" => { + let input: SyncLapInput = serde_json::from_value(params).map_err(|e| e.to_string())?; + let settings = { + let conn = ctx.db.lock(); + crate::db::settings::get_settings(&conn).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 settings = { + let conn = ctx.db.lock(); + crate::db::settings::get_settings(&conn).unwrap_or_default() + }; + 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 conn = ctx.db.lock(); + let settings = crate::db::settings::get_settings(&conn).unwrap_or_default(); + 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" => 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" + })), + + _ => 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/ws.rs b/headless-rust/src/web/ws.rs new file mode 100644 index 0000000..65417c9 --- /dev/null +++ b/headless-rust/src/web/ws.rs @@ -0,0 +1,132 @@ +use crate::camera::CameraService; +use crate::db::Database; +use crate::integrations::teable::TeableClient; +use crate::models::FlashProgressPayload; +use crate::serial::SerialService; +use crate::storage::FileStore; +use crate::web::rpc::{handle_rpc, RpcContext, RpcRequest}; +use futures::{SinkExt, StreamExt}; +use rocket::State; +use rocket_ws::stream::DuplexStream; +use rocket_ws::{Channel, Message, WebSocket}; +use serde_json::json; +use std::sync::Arc; +use tokio::sync::broadcast; + +#[rocket::get("/ws/rpc")] +pub fn ws_rpc( + ws: WebSocket, + db: &State, + store: &State, + camera: &State>, + serial: &State>, + flash_tx: &State>, +) -> Channel<'static> { + let ctx = Arc::new(RpcContext { + db: (*db).clone(), + store: (*store).clone(), + camera: (*camera).clone(), + serial: (*serial).clone(), + teable: TeableClient::new(), + flash_tx: (*flash_tx).clone(), + }); + + let mut serial_rx = serial.subscribe(); + let mut camera_status_rx = camera.subscribe_status(); + let mut live_frame_rx = camera.subscribe_frames(); + let mut flash_rx = flash_tx.subscribe(); + + ws.channel(move |mut stream: DuplexStream| { + Box::pin(async move { + println!("[ws] Client connected"); + + // Push initial camera status immediately + let init_status = json!({ + "event": "cameraStatus", + "payload": ctx.camera.get_status() + }); + let _ = stream.send(Message::Text(init_status.to_string())).await; + + loop { + tokio::select! { + // Incoming message from client + Some(msg) = stream.next() => { + match msg { + Ok(Message::Text(text)) => { + if let Ok(req) = serde_json::from_str::(&text) { + let resp = handle_rpc(&ctx, req).await; + let resp_json = serde_json::to_string(&resp).unwrap_or_default(); + if stream.send(Message::Text(resp_json)).await.is_err() { + break; + } + } + } + Ok(Message::Close(_)) => break, + Err(_) => break, + _ => {} + } + } + + // Serial telemetry broadcast + Ok(payload) = serial_rx.recv() => { + let msg = json!({ + "event": "serialStatus", + "payload": payload + }); + if stream.send(Message::Text(msg.to_string())).await.is_err() { + break; + } + } + + // Camera status broadcast + Ok(payload) = camera_status_rx.recv() => { + let msg = json!({ + "event": "cameraStatus", + "payload": payload + }); + if stream.send(Message::Text(msg.to_string())).await.is_err() { + break; + } + } + + // Live frame broadcast + Ok(b64_frame) = live_frame_rx.recv() => { + let msg = json!({ + "event": "liveFrame", + "payload": b64_frame + }); + if stream.send(Message::Text(msg.to_string())).await.is_err() { + break; + } + } + + // Flash progress broadcast + Ok(payload) = flash_rx.recv() => { + let msg = json!({ + "event": "flashProgress", + "payload": payload + }); + if stream.send(Message::Text(msg.to_string())).await.is_err() { + break; + } + } + } + } + + println!("[ws] Client disconnected"); + Ok(()) + }) + }) +} + +#[rocket::get("/ws")] +pub fn ws_alias( + ws: WebSocket, + db: &State, + store: &State, + camera: &State>, + serial: &State>, + flash_tx: &State>, +) -> Channel<'static> { + ws_rpc(ws, db, store, camera, serial, flash_tx) +} From 18011a8395072c8bd12d959feb6c3475bd373b16 Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Fri, 14 Aug 2026 22:55:16 +0200 Subject: [PATCH 08/65] feat: remove config.toml --- headless-rust/.cargo/config.toml | 2 -- 1 file changed, 2 deletions(-) delete mode 100644 headless-rust/.cargo/config.toml diff --git a/headless-rust/.cargo/config.toml b/headless-rust/.cargo/config.toml deleted file mode 100644 index ff7f758..0000000 --- a/headless-rust/.cargo/config.toml +++ /dev/null @@ -1,2 +0,0 @@ -[target.aarch64-unknown-linux-gnu] -linker = "aarch64-linux-gnu-gcc" \ No newline at end of file From 42b2a781d0051128e2e0fc618f9e81d92db1e2d4 Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Fri, 14 Aug 2026 23:03:42 +0200 Subject: [PATCH 09/65] feat: enhance pkg-config probing for Aravis and ensure proper linking for glib and gobject --- headless-rust/build.rs | 36 ++++++++++++++++++++---------------- 1 file changed, 20 insertions(+), 16 deletions(-) diff --git a/headless-rust/build.rs b/headless-rust/build.rs index a3dc5ef..07b35a5 100644 --- a/headless-rust/build.rs +++ b/headless-rust/build.rs @@ -1,24 +1,28 @@ fn main() { println!("cargo:rerun-if-changed=build.rs"); - // Probe aravis-0.8 and gobject-2.0 via pkg-config - match pkg_config::Config::new().atleast_version("0.8.0").probe("aravis-0.8") { - Ok(lib) => { - 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); - } + // 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()); } - Err(e) => { - println!("cargo:warning=pkg-config aravis-0.8 failed: {}. Trying fallback link.", e); - println!("cargo:rustc-link-lib=aravis-0.8"); - println!("cargo:rustc-link-lib=gobject-2.0"); + 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 ensure standard library search and rpaths for common Aravis install directories - println!("cargo:rustc-link-arg=-Wl,-rpath,/usr/local/lib64:/usr/local/lib:/usr/lib64:/usr/lib"); + // 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"); } + From 40d3c4267b959a4085ba788ada8619145df5bba0 Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Fri, 14 Aug 2026 23:24:02 +0200 Subject: [PATCH 10/65] feat: add frontend code to headless-rust --- headless-rust/bun.lock | 1159 +++++++++++++++++ headless-rust/components.json | 25 + headless-rust/frontend/index.html | 12 + headless-rust/frontend/src/App.tsx | 46 + .../frontend/src/components/ArmingButton.tsx | 237 ++++ .../frontend/src/components/ErrorBoundary.tsx | 60 + .../src/components/FirmwareFlasher.tsx | 363 ++++++ .../src/components/LapImageThumbnails.tsx | 92 ++ .../src/components/LapTimerDisplay.tsx | 113 ++ .../src/components/LastCapturedImage.tsx | 48 + .../src/components/NavigationMenu.tsx | 73 ++ .../frontend/src/components/StatusBadge.tsx | 46 + .../frontend/src/components/ThemeToggle.tsx | 29 + .../frontend/src/components/ViolationCard.tsx | 140 ++ .../frontend/src/components/ui/badge.tsx | 49 + .../frontend/src/components/ui/button.tsx | 65 + .../frontend/src/components/ui/card.tsx | 100 ++ .../frontend/src/components/ui/checkbox.tsx | 31 + .../src/components/ui/collapsible.tsx | 31 + .../frontend/src/components/ui/dialog.tsx | 166 +++ .../frontend/src/components/ui/input.tsx | 19 + .../frontend/src/components/ui/label.tsx | 22 + .../frontend/src/components/ui/progress.tsx | 29 + .../src/components/ui/scroll-area.tsx | 53 + .../frontend/src/components/ui/select.tsx | 192 +++ .../frontend/src/components/ui/skeleton.tsx | 12 + .../frontend/src/components/ui/slider.tsx | 57 + .../frontend/src/components/ui/sonner.tsx | 48 + .../frontend/src/components/ui/switch.tsx | 31 + .../src/components/ui/toggle-group.tsx | 89 ++ .../frontend/src/components/ui/toggle.tsx | 45 + .../frontend/src/hooks/useLiveLapTimer.ts | 27 + .../frontend/src/hooks/useSystemStateSync.ts | 31 + headless-rust/frontend/src/index.css | 135 ++ headless-rust/frontend/src/lib/format.ts | 26 + headless-rust/frontend/src/lib/rpc.ts | 173 +++ headless-rust/frontend/src/lib/sound.ts | 44 + headless-rust/frontend/src/lib/utils.ts | 6 + headless-rust/frontend/src/main.tsx | 13 + headless-rust/frontend/src/routes/__root.tsx | 40 + headless-rust/frontend/src/routes/about.tsx | 264 ++++ headless-rust/frontend/src/routes/index.tsx | 129 ++ headless-rust/frontend/src/routes/laps.tsx | 44 + .../frontend/src/routes/laps/HistoryTab.tsx | 110 ++ .../frontend/src/routes/laps/LapRow.tsx | 103 ++ .../src/routes/laps/LiveSessionTab.tsx | 195 +++ .../frontend/src/routes/laps/SessionCard.tsx | 115 ++ .../frontend/src/routes/settings.tsx | 58 + .../src/routes/settings/CameraTab.tsx | 423 ++++++ .../src/routes/settings/DeviceTab.tsx | 236 ++++ .../src/routes/settings/LapTimerTab.tsx | 119 ++ .../src/routes/settings/SpeedCameraTab.tsx | 263 ++++ headless-rust/frontend/src/routes/setup.tsx | 97 ++ headless-rust/frontend/src/routes/teable.tsx | 29 + .../src/routes/teable/ConnectionSection.tsx | 159 +++ .../src/routes/teable/SchemaStatus.tsx | 97 ++ .../src/routes/teable/SyncToggleSection.tsx | 39 + .../src/routes/teable/TableTargetSection.tsx | 277 ++++ .../frontend/src/routes/violations.tsx | 173 +++ .../routes/violations/ExportImagesDialog.tsx | 78 ++ .../routes/violations/ViolationGridTile.tsx | 133 ++ .../src/routes/violations/ViolationRow.tsx | 111 ++ .../src/routes/violations/ViolationsGrid.tsx | 87 ++ .../src/routes/violations/ViolationsTable.tsx | 105 ++ .../routes/violations/ViolationsToolbar.tsx | 157 +++ .../routes/violations/useViolationImage.ts | 27 + .../src/routes/violations/useViolations.ts | 186 +++ headless-rust/frontend/src/shared/schemas.ts | 99 ++ headless-rust/frontend/src/shared/types.ts | 548 ++++++++ .../frontend/src/stores/slices/cameraSlice.ts | 128 ++ .../src/stores/slices/flasherSlice.ts | 38 + .../frontend/src/stores/slices/lapSlice.ts | 260 ++++ .../src/stores/slices/measurementSlice.ts | 90 ++ .../frontend/src/stores/slices/serialSlice.ts | 22 + .../frontend/src/stores/slices/systemSlice.ts | 20 + .../frontend/src/stores/slices/teableSlice.ts | 206 +++ .../src/stores/slices/updaterSlice.ts | 81 ++ .../frontend/src/stores/useAppStore.ts | 22 + headless-rust/package.json | 49 + headless-rust/postcss.config.js | 6 + headless-rust/scripts/setup-network.sh | 154 +++ headless-rust/tailwind.config.js | 8 + headless-rust/tsconfig.json | 24 + headless-rust/vite.config.ts | 30 + 84 files changed, 9576 insertions(+) create mode 100644 headless-rust/bun.lock create mode 100644 headless-rust/components.json create mode 100644 headless-rust/frontend/index.html create mode 100644 headless-rust/frontend/src/App.tsx create mode 100644 headless-rust/frontend/src/components/ArmingButton.tsx create mode 100644 headless-rust/frontend/src/components/ErrorBoundary.tsx create mode 100644 headless-rust/frontend/src/components/FirmwareFlasher.tsx create mode 100644 headless-rust/frontend/src/components/LapImageThumbnails.tsx create mode 100644 headless-rust/frontend/src/components/LapTimerDisplay.tsx create mode 100644 headless-rust/frontend/src/components/LastCapturedImage.tsx create mode 100644 headless-rust/frontend/src/components/NavigationMenu.tsx create mode 100644 headless-rust/frontend/src/components/StatusBadge.tsx create mode 100644 headless-rust/frontend/src/components/ThemeToggle.tsx create mode 100644 headless-rust/frontend/src/components/ViolationCard.tsx create mode 100644 headless-rust/frontend/src/components/ui/badge.tsx create mode 100644 headless-rust/frontend/src/components/ui/button.tsx create mode 100644 headless-rust/frontend/src/components/ui/card.tsx create mode 100644 headless-rust/frontend/src/components/ui/checkbox.tsx create mode 100644 headless-rust/frontend/src/components/ui/collapsible.tsx create mode 100644 headless-rust/frontend/src/components/ui/dialog.tsx create mode 100644 headless-rust/frontend/src/components/ui/input.tsx create mode 100644 headless-rust/frontend/src/components/ui/label.tsx create mode 100644 headless-rust/frontend/src/components/ui/progress.tsx create mode 100644 headless-rust/frontend/src/components/ui/scroll-area.tsx create mode 100644 headless-rust/frontend/src/components/ui/select.tsx create mode 100644 headless-rust/frontend/src/components/ui/skeleton.tsx create mode 100644 headless-rust/frontend/src/components/ui/slider.tsx create mode 100644 headless-rust/frontend/src/components/ui/sonner.tsx create mode 100644 headless-rust/frontend/src/components/ui/switch.tsx create mode 100644 headless-rust/frontend/src/components/ui/toggle-group.tsx create mode 100644 headless-rust/frontend/src/components/ui/toggle.tsx create mode 100644 headless-rust/frontend/src/hooks/useLiveLapTimer.ts create mode 100644 headless-rust/frontend/src/hooks/useSystemStateSync.ts create mode 100644 headless-rust/frontend/src/index.css create mode 100644 headless-rust/frontend/src/lib/format.ts create mode 100644 headless-rust/frontend/src/lib/rpc.ts create mode 100644 headless-rust/frontend/src/lib/sound.ts create mode 100644 headless-rust/frontend/src/lib/utils.ts create mode 100644 headless-rust/frontend/src/main.tsx create mode 100644 headless-rust/frontend/src/routes/__root.tsx create mode 100644 headless-rust/frontend/src/routes/about.tsx create mode 100644 headless-rust/frontend/src/routes/index.tsx create mode 100644 headless-rust/frontend/src/routes/laps.tsx create mode 100644 headless-rust/frontend/src/routes/laps/HistoryTab.tsx create mode 100644 headless-rust/frontend/src/routes/laps/LapRow.tsx create mode 100644 headless-rust/frontend/src/routes/laps/LiveSessionTab.tsx create mode 100644 headless-rust/frontend/src/routes/laps/SessionCard.tsx create mode 100644 headless-rust/frontend/src/routes/settings.tsx create mode 100644 headless-rust/frontend/src/routes/settings/CameraTab.tsx create mode 100644 headless-rust/frontend/src/routes/settings/DeviceTab.tsx create mode 100644 headless-rust/frontend/src/routes/settings/LapTimerTab.tsx create mode 100644 headless-rust/frontend/src/routes/settings/SpeedCameraTab.tsx create mode 100644 headless-rust/frontend/src/routes/setup.tsx create mode 100644 headless-rust/frontend/src/routes/teable.tsx create mode 100644 headless-rust/frontend/src/routes/teable/ConnectionSection.tsx create mode 100644 headless-rust/frontend/src/routes/teable/SchemaStatus.tsx create mode 100644 headless-rust/frontend/src/routes/teable/SyncToggleSection.tsx create mode 100644 headless-rust/frontend/src/routes/teable/TableTargetSection.tsx create mode 100644 headless-rust/frontend/src/routes/violations.tsx create mode 100644 headless-rust/frontend/src/routes/violations/ExportImagesDialog.tsx create mode 100644 headless-rust/frontend/src/routes/violations/ViolationGridTile.tsx create mode 100644 headless-rust/frontend/src/routes/violations/ViolationRow.tsx create mode 100644 headless-rust/frontend/src/routes/violations/ViolationsGrid.tsx create mode 100644 headless-rust/frontend/src/routes/violations/ViolationsTable.tsx create mode 100644 headless-rust/frontend/src/routes/violations/ViolationsToolbar.tsx create mode 100644 headless-rust/frontend/src/routes/violations/useViolationImage.ts create mode 100644 headless-rust/frontend/src/routes/violations/useViolations.ts create mode 100644 headless-rust/frontend/src/shared/schemas.ts create mode 100644 headless-rust/frontend/src/shared/types.ts create mode 100644 headless-rust/frontend/src/stores/slices/cameraSlice.ts create mode 100644 headless-rust/frontend/src/stores/slices/flasherSlice.ts create mode 100644 headless-rust/frontend/src/stores/slices/lapSlice.ts create mode 100644 headless-rust/frontend/src/stores/slices/measurementSlice.ts create mode 100644 headless-rust/frontend/src/stores/slices/serialSlice.ts create mode 100644 headless-rust/frontend/src/stores/slices/systemSlice.ts create mode 100644 headless-rust/frontend/src/stores/slices/teableSlice.ts create mode 100644 headless-rust/frontend/src/stores/slices/updaterSlice.ts create mode 100644 headless-rust/frontend/src/stores/useAppStore.ts create mode 100644 headless-rust/package.json create mode 100644 headless-rust/postcss.config.js create mode 100644 headless-rust/scripts/setup-network.sh create mode 100644 headless-rust/tailwind.config.js create mode 100644 headless-rust/tsconfig.json create mode 100644 headless-rust/vite.config.ts diff --git a/headless-rust/bun.lock b/headless-rust/bun.lock new file mode 100644 index 0000000..038b919 --- /dev/null +++ b/headless-rust/bun.lock @@ -0,0 +1,1159 @@ +{ + "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", + "radix-ui": "^1.4.3", + "react": "^18.3.1", + "react-dom": "^18.3.1", + "react-webcam": "^7.2.0", + "shadcn": "^4.7.0", + "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=="], + + "@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=="], + + "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=="], + + "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=="], + + "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=="], + + "wsl-utils": ["wsl-utils@1.0.0", "", { "dependencies": { "is-wsl": "^3.1.0", "powershell-utils": "^0.1.0" } }, "sha512-Hl0ZOAs672vg+06kfujwRhoS6/jehvULrlFkuF2dRu6pHgA8U06h3xqNIqNNU1LTXPcedxByAR4GS6pwQK0mgA=="], + + "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/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..071b056 --- /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 setSystemState = useAppStore((s) => s.setSystemState); + 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); + setSystemState("ARMED"); + return; + } + + if (p < 1) { + rafRef.current = requestAnimationFrame(tick); + } + }; + + rafRef.current = requestAnimationFrame(tick); + }, [systemState, setSystemState]); + + 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") { + setSystemState("DISARMED"); + } + }, [systemState, setSystemState]); + + // 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/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..04f2b89 --- /dev/null +++ b/headless-rust/frontend/src/components/LapImageThumbnails.tsx @@ -0,0 +1,92 @@ +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. + * Fetches image data lazily via the RPC and cancels pending fetches on unmount. + */ +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); + if (startImagePath) { + getRpc() + .request.getImageData({ imagePath: startImagePath }) + .then((data) => { if (!cancelled) setStartImageUrl(data); }) + .catch(() => {}); + } + if (endImagePath) { + getRpc() + .request.getImageData({ imagePath: endImagePath }) + .then((data) => { if (!cancelled) setEndImageUrl(data); }) + .catch(() => {}); + } + return () => { cancelled = true; }; + }, [startImagePath, endImagePath]); + + return ( + <> +
+ {(startImageUrl || endImageUrl) ? ( + <> + {startImageUrl && ( + + )} + {endImageUrl && ( + + )} + + ) : ( + — + )} + {trailing} +
+ + !open && setLightboxUrl(null)}> + + {lightboxUrl && ( + Lap capture + )} + + + + ); +} 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..42dd6d0 --- /dev/null +++ b/headless-rust/frontend/src/components/LastCapturedImage.tsx @@ -0,0 +1,48 @@ +import { useEffect, useState } from "react"; +import { getRpc } from "@/lib/rpc"; +import { useAppStore } from "@/stores/useAppStore"; +import { Image as ImageIcon } from "lucide-react"; + +export function LastCapturedImage() { + const lastViolation = useAppStore((s) => s.lastViolation); + const [imageSrc, setImageSrc] = useState(null); + + useEffect(() => { + if (lastViolation) { + getRpc().request.getImageData({ imagePath: lastViolation.imagePath }).then(setImageSrc).catch(() => setImageSrc(null)); + } else { + setImageSrc(null); + } + }, [lastViolation]); + + return ( +
+ {imageSrc ? ( + Last capture + ) : ( +
+ +

Awaiting Capture

+
+ )} + + {lastViolation && ( +
+ + {new Date(lastViolation.timestamp).toLocaleTimeString()} + +
+ + {lastViolation.measuredSpeed} + + km/h +
+
+ )} +
+ ); +} diff --git a/headless-rust/frontend/src/components/NavigationMenu.tsx b/headless-rust/frontend/src/components/NavigationMenu.tsx new file mode 100644 index 0000000..72efed8 --- /dev/null +++ b/headless-rust/frontend/src/components/NavigationMenu.tsx @@ -0,0 +1,73 @@ +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"; + +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..5b92539 --- /dev/null +++ b/headless-rust/frontend/src/components/ViolationCard.tsx @@ -0,0 +1,140 @@ +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); + + getRpc() + .request.getImageData({ imagePath: violation.imagePath }) + .then((data) => { + if (!cancelled) setImageData(data); + }) + .catch(() => { + if (!cancelled) setImageData(null); + }) + .finally(() => { + if (!cancelled) setImageLoading(false); + }); + + return () => { + cancelled = true; + }; + }, [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/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/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..bbc7915 --- /dev/null +++ b/headless-rust/frontend/src/hooks/useSystemStateSync.ts @@ -0,0 +1,31 @@ +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 connectedPort = useAppStore((s) => s.connectedPort); + const cameraConnected = useAppStore((s) => s.cameraConnected); + + const conditionsMet = !!connectedPort && cameraConnected; + + useEffect(() => { + if (conditionsMet) { + if (systemState === "PASSIVE") { + setSystemState("DISARMED"); + } + } else { + if (systemState !== "PASSIVE") { + setSystemState("PASSIVE"); + } + } + }, [conditionsMet, 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..2d544a6 --- /dev/null +++ b/headless-rust/frontend/src/lib/rpc.ts @@ -0,0 +1,173 @@ +import type { SpeedcameraRPC } from "@/shared/types"; +import { useAppStore } from "@/stores/useAppStore"; + +type RequestMap = SpeedcameraRPC["bun"]["requests"]; +type PushMessageMap = SpeedcameraRPC["webview"]["messages"]; + +export type SpeedcameraClientRPC = { + request: { + [K in keyof RequestMap]: ( + params: RequestMap[K]["params"] + ) => Promise; + }; +}; + +class WebSocketRpcClient { + private ws: WebSocket | null = null; + private reqIdCounter = 0; + private pendingRequests = new Map< + string | number, + { + resolve: (val: any) => void; + reject: (err: any) => void; + timer: ReturnType; + } + >(); + private reconnectTimeout: ReturnType | null = null; + private isConnecting = false; + + constructor() { + this.connect(); + } + + private getWebSocketUrl(): string { + if (typeof window === "undefined") return "ws://127.0.0.1:3000/ws/rpc"; + const protocol = window.location.protocol === "https:" ? "wss:" : "ws:"; + const host = window.location.host; // includes port (e.g. localhost:5173 or 192.168.4.1:3000) + return `${protocol}//${host}/ws/rpc`; + } + + private connect() { + if (typeof window === "undefined" || this.isConnecting) return; + this.isConnecting = true; + + try { + const url = this.getWebSocketUrl(); + const ws = new WebSocket(url); + this.ws = ws; + + ws.onopen = () => { + console.log("[rpc-client] Connected to speedcamera daemon"); + this.isConnecting = false; + }; + + ws.onmessage = (event) => { + try { + const data = JSON.parse(event.data); + + // Case 1: Response to a pending request + if (data.id !== undefined && this.pendingRequests.has(data.id)) { + const pending = this.pendingRequests.get(data.id)!; + this.pendingRequests.delete(data.id); + clearTimeout(pending.timer); + + if (data.error) { + pending.reject(new Error(data.error)); + } else { + pending.resolve(data.result); + } + return; + } + + // Case 2: Server push broadcast event + if (data.event) { + this.handlePushEvent(data.event as keyof PushMessageMap, data.payload); + return; + } + } catch (err) { + console.error("[rpc-client] Error handling message:", err); + } + }; + + ws.onerror = (err) => { + console.warn("[rpc-client] WebSocket error:", err); + }; + + ws.onclose = () => { + console.log("[rpc-client] Disconnected. Reconnecting in 2s..."); + this.isConnecting = false; + this.ws = null; + if (!this.reconnectTimeout) { + this.reconnectTimeout = setTimeout(() => { + this.reconnectTimeout = null; + this.connect(); + }, 2000); + } + }; + } catch (err) { + this.isConnecting = false; + console.error("[rpc-client] Connection failed:", err); + } + } + + private handlePushEvent(event: K, payload: PushMessageMap[K]) { + const store = useAppStore.getState(); + switch (event) { + case "serialStatus": + store.handleSerialStatus(payload as any); + break; + case "flashProgress": + store.handleFlashProgress(payload as any); + break; + case "cameraStatus": + store.setCameraStatus(payload as any); + break; + case "liveFrame": + store.setLiveFrame(payload as any); + break; + case "updateAvailable": + store.setUpdateVersion((payload as any).version); + store.setUpdatePhase("ready"); + break; + case "updateProgress": + store.handleUpdateProgress(payload as any); + break; + default: + break; + } + } + + public call(method: string, params: any): Promise { + return new Promise((resolve, reject) => { + const id = ++this.reqIdCounter; + const timer = setTimeout(() => { + if (this.pendingRequests.has(id)) { + this.pendingRequests.delete(id); + reject(new Error(`RPC request '${method}' timed out after 10000ms`)); + } + }, 10000); + + this.pendingRequests.set(id, { resolve, reject, timer }); + + if (this.ws && this.ws.readyState === WebSocket.OPEN) { + this.ws.send(JSON.stringify({ id, method, params })); + } else { + // If websocket not ready yet, wait briefly or connect + const checkInterval = setInterval(() => { + if (this.ws && this.ws.readyState === WebSocket.OPEN) { + clearInterval(checkInterval); + this.ws.send(JSON.stringify({ id, method, params })); + } + }, 100); + + // Cancel retry if request times out + setTimeout(() => clearInterval(checkInterval), 9500); + } + }); + } +} + +const client = new WebSocketRpcClient(); + +// Proxy accessor so `getRpc().request.someMethod(params)` works transparently +const rpcProxy: SpeedcameraClientRPC = { + request: new Proxy({} as any, { + get(_target, prop: string) { + return (params: any = {}) => client.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..c077548 --- /dev/null +++ b/headless-rust/frontend/src/routes/__root.tsx @@ -0,0 +1,40 @@ +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"; + +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); + + useEffect(() => { + void loadLapSettings(); + void loadTeableState(); + void refreshCameraStatus(); + }, [loadLapSettings, loadTeableState, refreshCameraStatus]); + + 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..1efef51 --- /dev/null +++ b/headless-rust/frontend/src/routes/settings.tsx @@ -0,0 +1,58 @@ +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 { 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", "camera", "speed-camera", "lap-timer"] as const).map((tab) => ( + + {tab === "device" + ? "Device" + : 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..31358b7 --- /dev/null +++ b/headless-rust/frontend/src/routes/settings/CameraTab.tsx @@ -0,0 +1,423 @@ +import { useState, useEffect } from "react"; +import type { ChangeEvent } from "react"; +import { toast } from "sonner"; +import { useAppStore } from "@/stores/useAppStore"; +import type { HwControl, SystemNetworkSummary } from "@/shared/types"; +import { getRpc } from "@/lib/rpc"; +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, Network } 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} +
+
+ ); +} + +function NetworkStatusSection() { + const [network, setNetwork] = useState(null); + const [loading, setLoading] = useState(false); + + const fetchNetwork = () => { + setLoading(true); + getRpc() + .request.getNetworkInfo({}) + .then(setNetwork) + .catch(() => {}) + .finally(() => setLoading(false)); + }; + + useEffect(() => { + fetchNetwork(); + }, []); + + if (!network) return null; + + return ( +
+
+

+ + Network & Subnet Architecture +

+ +
+ +
+ {/* Camera LAN */} +
+
+ Camera LAN (eth0) + {network.cameraLan.status === "ok" ? ( + 192.168.1.100 OK + ) : network.cameraLan.status === "ip_mismatch" ? ( + {network.cameraLan.ip || "Mismatch"} + ) : ( + Not Found + )} +
+
+
IP: {network.cameraLan.ip || "Unassigned"}
+
Subnet: {network.cameraLan.subnet}
+
+

+ Dedicated interface for GigE Vision camera streaming. +

+
+ + {/* Wi-Fi Hotspot */} +
+
+ Hotspot AP (wlan0) + {network.hotspotAp.status === "ok" ? ( + 192.168.4.1 OK + ) : network.hotspotAp.status === "ip_mismatch" ? ( + {network.hotspotAp.ip} + ) : ( + Inactive + )} +
+
+
IP: {network.hotspotAp.ip || "Unassigned"}
+
Web UI: :3000
+
+

+ Wi-Fi access point for remote browser controller. +

+
+
+
+ ); +} 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/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..f71136b --- /dev/null +++ b/headless-rust/frontend/src/routes/setup.tsx @@ -0,0 +1,97 @@ +import { useEffect } from "react"; +import { createRoute } from "@tanstack/react-router"; +import { RootRoute } from "./__root"; +import { useAppStore } from "@/stores/useAppStore"; +import { Button } from "@/components/ui/button"; +import { Badge } from "@/components/ui/badge"; +import { PlayIcon, SquareIcon, AlertCircleIcon } 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 liveFrame = useAppStore((s) => s.liveFrame); + const startSetupStream = useAppStore((s) => s.startSetupStream); + const stopSetupStream = useAppStore((s) => s.stopSetupStream); + + useEffect(() => { + // Stop stream on unmount + return () => { + stopSetupStream().catch(console.error); + }; + }, [stopSetupStream]); + + const handleStart = async () => { + if (!connected) { + toast.error("Camera is not connected!"); + return; + } + try { + await startSetupStream(); + } catch { + toast.error("Failed to start setup stream"); + } + }; + + const handleStop = async () => { + try { + await stopSetupStream(); + } catch { + toast.error("Failed to stop setup stream"); + } + }; + + return ( +
+
+
+

Camera Setup

+

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

+
+
+ + {setupStreamActive ? "Streaming" : "Stopped"} + + {!setupStreamActive ? ( + + ) : ( + + )} +
+
+ +
+ {setupStreamActive ? ( + liveFrame ? ( + Camera Livestream + ) : ( +
+ Waiting for frame... +
+ ) + ) : ( +
+ {connected ? "Click Start Stream to begin setup" : "Camera disconnected"} +
+ )} +
+
+ ); +} 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..865af7b --- /dev/null +++ b/headless-rust/frontend/src/routes/violations.tsx @@ -0,0 +1,173 @@ +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 + )} + + + + x.id)} + /> +
+ ); +} 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..d327016 --- /dev/null +++ b/headless-rust/frontend/src/routes/violations/ExportImagesDialog.tsx @@ -0,0 +1,78 @@ +import { useState } from "react"; +import { toast } from "sonner"; +import { getRpc } from "@/lib/rpc"; +import { Button } from "@/components/ui/button"; +import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog"; + +interface ExportImagesDialogProps { + open: boolean; + onOpenChange: (open: boolean) => void; + selectedIds: number[]; + pageViolationIds: number[]; +} + +export function ExportImagesDialog({ + open, + onOpenChange, + selectedIds, + pageViolationIds, +}: ExportImagesDialogProps) { + const selectedCount = selectedIds.length; + const pageViolationCount = pageViolationIds.length; + const [exportDir, setExportDir] = useState(""); + const [exporting, setExporting] = useState(false); + + const handleExport = async () => { + if (!exportDir.trim()) { + toast.error("Please enter an export directory"); + return; + } + setExporting(true); + try { + const ids = selectedCount > 0 ? selectedIds : pageViolationIds; + const result = await getRpc().request.exportSkinnedImages({ + violationIds: ids, + targetDir: exportDir.trim(), + }); + toast.success(`Exported ${result.exported} images${result.failed ? `, ${result.failed} failed` : ""}`); + onOpenChange(false); + } catch { + toast.error("Failed to export images"); + } finally { + setExporting(false); + } + }; + + return ( + + + + Export Skinned Images + +

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

+
+ + setExportDir(e.target.value)} + placeholder="/home/user/exports" + 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/violations/ViolationGridTile.tsx b/headless-rust/frontend/src/routes/violations/ViolationGridTile.tsx new file mode 100644 index 0000000..b1dc7e6 --- /dev/null +++ b/headless-rust/frontend/src/routes/violations/ViolationGridTile.tsx @@ -0,0 +1,133 @@ +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) { + const { imageData, imageLoading } = useViolationImage(violation, skinEnabled); + 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 handleDelete = async (e: React.MouseEvent) => { + e.stopPropagation(); + setDeleting(true); + try { + await onDelete(); + } finally { + setDeleting(false); + } + }; + + return ( +
+
imageData && onImageClick(imageData)} + > +
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..1db1ddb --- /dev/null +++ b/headless-rust/frontend/src/routes/violations/ViolationRow.tsx @@ -0,0 +1,111 @@ +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) { + const { imageData, imageLoading } = useViolationImage(violation, skinEnabled); + 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 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..621c636 --- /dev/null +++ b/headless-rust/frontend/src/routes/violations/useViolationImage.ts @@ -0,0 +1,27 @@ +import { useEffect, useState } from "react"; +import { getRpc } from "@/lib/rpc"; +import type { Violation } from "@/shared/types"; + +/** + * Fetches a violation's image (raw or Poliscan-skinned) as a data-URL. + * Shared by ViolationRow and ViolationGridTile to dedupe the fetch effect. + */ +export function useViolationImage(violation: Violation, skinEnabled: boolean) { + const [imageData, setImageData] = useState(null); + const [imageLoading, setImageLoading] = useState(true); + + useEffect(() => { + let cancelled = false; + setImageLoading(true); + const fetchImage = skinEnabled + ? getRpc().request.getSkinnedImageData({ violationId: violation.id }) + : getRpc().request.getImageData({ imagePath: violation.imagePath }); + 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]); + + 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..29fc17a --- /dev/null +++ b/headless-rust/frontend/src/routes/violations/useViolations.ts @@ -0,0 +1,186 @@ +import { useCallback, useEffect, useState } from "react"; +import { toast } from "sonner"; +import { getRpc } from "@/lib/rpc"; +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]); + + 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..dc0a0ae --- /dev/null +++ b/headless-rust/frontend/src/shared/types.ts @@ -0,0 +1,548 @@ +// ─── Domain Types ─────────────────────────────────────────────────────────── + +export interface NetworkInterfaceDetail { + name: string; + role: "camera-lan" | "hotspot-ap" | "other" | "loopback"; + address: string; + family: string; + netmask: string; + mac: string; + expectedIp?: string; + isConfigured: boolean; +} + +export interface SystemNetworkSummary { + cameraLan: { + interfaceName: string | null; + ip: string | null; + expectedIp: "192.168.1.100"; + subnet: "192.168.1.0/24"; + status: "ok" | "ip_mismatch" | "missing"; + description: string; + }; + hotspotAp: { + interfaceName: string | null; + ip: string | null; + expectedIp: "192.168.4.1"; + subnet: "192.168.4.0/24"; + status: "ok" | "ip_mismatch" | "missing"; + description: string; + }; + interfaces: NetworkInterfaceDetail[]; +} + +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; +} + +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" } + | { 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 }; + response: string; // data-URL or path + }; + getSkinnedImageData: { + params: { violationId: number }; + response: string; // data-URL or URL of skinned image + }; + exportSkinnedImages: { + params: { violationIds: number[]; targetDir: string }; + response: { exported: number; failed: number }; + }; + + // DB – settings + getSettings: { + params: Record; + response: AppSettings; + }; + saveSetting: { + params: { key: keyof AppSettings; value: string }; + response: void; + }; + + // Serial + listPorts: { + params: Record; + response: PortInfo[]; + }; + 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; + }; + + // 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; + }>; +}; 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..69fc04e --- /dev/null +++ b/headless-rust/frontend/src/stores/slices/cameraSlice.ts @@ -0,0 +1,128 @@ +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; +} + +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, + setCameraStatus: (status) => set({ + cameraConnected: status.connected, + cameraVendor: status.vendor, + cameraModel: status.model, + cameraSerial: status.serial, + }), + + 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, + }); + }, + + 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 { + 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..5900c39 --- /dev/null +++ b/headless-rust/frontend/src/stores/slices/lapSlice.ts @@ -0,0 +1,260 @@ +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 { 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, + [], + [], + 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", + }); + // 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, + // Keep currentLaps so the UI can show the final session summary + }); + }, + + // ── State machine ────────────────────────────────────────────────────────── + + handleSerialStatusForLap: (payload) => { + // ── LAPSTART: first car pass — firmware opened a new lap ────────────────── + if (payload.status === "LAPSTART") { + const { lapState, lapSettings } = get(); + + // Accept "waiting" (first lap) or "timing" (MULTI lap N+1 boundary) + const isMultiContinuation = lapState === "timing" && lapSettings.lapMode === "multi"; + if (lapState !== "waiting" && !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..7049e9b --- /dev/null +++ b/headless-rust/frontend/src/stores/slices/measurementSlice.ts @@ -0,0 +1,90 @@ +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; + } + + const { systemState, appMode } = get(); + // In PASSIVE mode, ignore all serial measurements + if (systemState === "PASSIVE") 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 + if (payload.status === "SPEEDING" || payload.status === "OK") { + set({ lastSpeed: payload.value, lastDirection: payload.direction }); + } + return; + } + + if (payload.status === "SPEEDING") { + const { value, direction } = payload; + set({ lastSpeed: value, lastDirection: direction }); + + // Only save violations and flash when fully ARMED + if (systemState !== "ARMED") return; + + const { maxSpeed } = get(); + + // Trigger server-side capture and save + getRpc() + .request.saveViolation({ measuredSpeed: value, maxSpeed, direction }) + .then((v) => { + get().setLastViolation(v); + }) + .catch((err: unknown) => { + console.error("[measurement] Capture/save failed:", err); + toast.error("Failed to save violation"); + }); + } else if (payload.status === "OK") { + set({ lastSpeed: payload.value, lastDirection: payload.direction }); + } + // CONNECTED / DISCONNECTED handled by serialSlice indirectly via store + }, +}); 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..d4710ce --- /dev/null +++ b/headless-rust/frontend/src/stores/slices/serialSlice.ts @@ -0,0 +1,22 @@ +import type { StateCreator } from "zustand"; +import type { PortInfo } from "@/shared/types"; + +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; +} + +export const createSerialSlice: StateCreator = (set) => ({ + availablePorts: [], + selectedPort: "", + connectedPort: "", + setAvailablePorts: (ports) => set({ availablePorts: ports }), + setSelectedPort: (path) => set({ selectedPort: path }), + setConnectedPort: (path) => set({ connectedPort: path }), +}); 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..8add0b7 --- /dev/null +++ b/headless-rust/frontend/src/stores/slices/systemSlice.ts @@ -0,0 +1,20 @@ +import type { StateCreator } from "zustand"; + +export type SystemState = "PASSIVE" | "DISARMED" | "ARMED"; +export type AppMode = "speedcamera" | "laptimer"; + +export interface SystemSlice { + /** Current operational state of the speed camera system */ + systemState: SystemState; + setSystemState: (state: SystemState) => void; + /** Active mode — routes serial events to violation or lap handler */ + appMode: AppMode; + setAppMode: (mode: AppMode) => void; +} + +export const createSystemSlice: StateCreator = (set) => ({ + systemState: "PASSIVE", + setSystemState: (state) => set({ systemState: state }), + 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..d35e8f0 --- /dev/null +++ b/headless-rust/package.json @@ -0,0 +1,49 @@ +{ + "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" + }, + "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", + "radix-ui": "^1.4.3", + "react": "^18.3.1", + "react-dom": "^18.3.1", + "react-webcam": "^7.2.0", + "shadcn": "^4.7.0", + "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/scripts/setup-network.sh b/headless-rust/scripts/setup-network.sh new file mode 100644 index 0000000..a253544 --- /dev/null +++ b/headless-rust/scripts/setup-network.sh @@ -0,0 +1,154 @@ +#!/usr/bin/env bash +set -e + +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" ]; then + sudo -v || { echo "Error: Sudo privileges required to change network configuration." >&2; exit 1; } +fi + +case "$MODE" in + field|ap) + echo ">>> Applying FIELD MODE (Standalone Offline Dual-Subnet):" + echo " 1. Camera LAN (${ETH_IFACE}) -> Static IP 192.168.1.100/24" + echo " 2. Hotspot AP (${WIFI_IFACE}) -> Static IP 192.168.4.1/24 (SSID: speedcamera)" + echo " NOTE: In this mode, Pi operates standalone/offline." + echo "" + + # Apply GigE Vision kernel socket buffer optimizations + echo "[*] Applying GigE Vision network socket buffer optimizations (64MB)..." + sudo bash -c 'cat > /etc/sysctl.d/60-gige-camera.conf </dev/null || sudo sysctl --system 2>/dev/null || true + + # Configure Ethernet Camera LAN + echo "[1/2] Configuring Camera LAN on ${ETH_IFACE}..." + sudo nmcli connection delete "Speedcamera-CameraLAN" 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 + sudo nmcli connection up "Speedcamera-CameraLAN" 2>/dev/null || echo "Note: Ethernet link active when camera cable is connected." + + # Configure Wi-Fi Hotspot AP + echo "[2/2] Configuring Wi-Fi Hotspot AP on ${WIFI_IFACE}..." + SSID="speedcamera" + PASS="speedcamerapass" + sudo nmcli connection delete "Speedcamera-Hotspot" 2>/dev/null || true + sudo nmcli connection delete "Speedcamera-ClientWiFi" 2>/dev/null || true + sudo nmcli connection add type wifi \ + ifname "${WIFI_IFACE}" \ + con-name "Speedcamera-Hotspot" \ + autoconnect yes \ + ssid "${SSID}" \ + mode ap \ + 802-11-wireless.band bg \ + ipv4.method shared \ + ipv4.addresses 192.168.4.1/24 \ + wifi-sec.key-mgmt wpa-psk \ + wifi-sec.psk "${PASS}" + sudo nmcli connection up "Speedcamera-Hotspot" 2>/dev/null || echo "Note: Hotspot initialized." + + # Disable Wi-Fi power saving on AP interface to eliminate latency spikes and disconnects + echo "[*] Disabling Wi-Fi power saving on ${WIFI_IFACE}..." + sudo iw dev "${WIFI_IFACE}" set power_save off 2>/dev/null || sudo iwconfig "${WIFI_IFACE}" power off 2>/dev/null || true + + echo "" + echo "=========================================================" + echo " Field Mode Active!" + echo " • Wi-Fi Hotspot: SSID '${SSID}' (Password: '${PASS}')" + echo " • Web UI: http://192.168.4.1:3000" + echo " • Camera LAN: http://192.168.1.100:3000" + echo "=========================================================" + ;; + + internet|client|wifi) + WIFI_SSID="$2" + WIFI_PASS="$3" + if [ -z "$WIFI_SSID" ]; then + echo "Usage: $0 internet [Wi-Fi-Password]" + echo "Example: $0 internet MyHomeWiFi SecretPassword123" + exit 1 + fi + echo ">>> Switching to INTERNET / CLIENT MODE (for updates/provisioning)..." + echo " Connecting ${WIFI_IFACE} to Wi-Fi SSID: ${WIFI_SSID}" + + sudo nmcli connection delete "Speedcamera-Hotspot" 2>/dev/null || true + sudo nmcli connection delete "Speedcamera-ClientWiFi" 2>/dev/null || true + + if [ -n "$WIFI_PASS" ]; then + sudo nmcli dev wifi connect "${WIFI_SSID}" password "${WIFI_PASS}" ifname "${WIFI_IFACE}" name "Speedcamera-ClientWiFi" + else + sudo nmcli dev wifi connect "${WIFI_SSID}" ifname "${WIFI_IFACE}" name "Speedcamera-ClientWiFi" + fi + + echo "" + echo ">>> Checking internet connectivity..." + if ping -c 2 -W 3 1.1.1.1 &>/dev/null; then + echo " Connected to Internet successfully!" + else + echo " Wi-Fi connected, but ping to 1.1.1.1 failed. Check gateway/DNS." + fi + ;; + + dhcp|reset) + echo ">>> Reverting Ethernet and Wi-Fi to standard DHCP..." + 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 + 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 + echo "Interfaces set to standard DHCP." + ;; + + status) + echo "--- Active Network Connections ---" + nmcli connection show --active || true + echo "" + echo "--- IP Addresses ---" + ip -br addr show || true + 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 field mode or no route)" + fi + ;; + + *) + echo "Usage: $0 {field|internet|dhcp|status}" + echo "" + echo "Commands:" + echo " field Set Camera LAN (192.168.1.100) + Hotspot AP (192.168.4.1) [Offline]" + echo " internet [PASS] Connect Wi-Fi to home/lab router for updates [Online]" + echo " dhcp Reset ethernet & Wi-Fi to standard DHCP" + echo " status Check current IP addresses and connectivity" + exit 1 + ;; +esac 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..ebfaf0b --- /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", + "/ws": { + target: "ws://127.0.0.1:3000", + ws: true, + }, + }, + }, +}); From c8caee0aa1706fe9f85532d1ad580204a956503c Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Fri, 14 Aug 2026 23:35:22 +0200 Subject: [PATCH 11/65] feat: add host option for HTTP server bind address in README --- headless-rust/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/headless-rust/README.md b/headless-rust/README.md index df4de5e..32073ce 100644 --- a/headless-rust/README.md +++ b/headless-rust/README.md @@ -109,6 +109,7 @@ Usage: headless-rust [OPTIONS] Options: -m, --mock Run in mock hardware mode (no physical camera/serial required) -p, --port HTTP server port (default: 3000) + -H, --host HTTP server bind address (default: 0.0.0.0) -h, --help Print help ``` From 5a76382c92e5ce8d7a0bea4bdc898b3e77d8174b Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Fri, 14 Aug 2026 23:35:27 +0200 Subject: [PATCH 12/65] feat: enhance AppConfig to support host override and add CORS headers to responses --- headless-rust/src/config.rs | 6 ++++-- headless-rust/src/main.rs | 5 ++++- headless-rust/src/web/embedded.rs | 8 +++---- headless-rust/src/web/mod.rs | 35 +++++++++++++++++++++++++------ 4 files changed, 41 insertions(+), 13 deletions(-) diff --git a/headless-rust/src/config.rs b/headless-rust/src/config.rs index 22a1cd9..d1b1e7d 100644 --- a/headless-rust/src/config.rs +++ b/headless-rust/src/config.rs @@ -11,8 +11,10 @@ pub struct AppConfig { } impl AppConfig { - pub fn new(mock: bool, port_override: Option) -> Self { - let host = std::env::var("HOST").unwrap_or_else(|_| "0.0.0.0".to_string()); + 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() diff --git a/headless-rust/src/main.rs b/headless-rust/src/main.rs index 7e40921..59b427b 100644 --- a/headless-rust/src/main.rs +++ b/headless-rust/src/main.rs @@ -25,12 +25,15 @@ struct Args { #[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, } #[rocket::main] async fn main() -> Result<(), rocket::Error> { let args = Args::parse(); - let config = AppConfig::new(args.mock, args.port); + let config = AppConfig::new(args.mock, args.port, args.host); println!("─────────────────────────────────────────────────────────────────"); println!(" ⚡ Speedcamera Headless Daemon (Rust & Rocket)"); diff --git a/headless-rust/src/web/embedded.rs b/headless-rust/src/web/embedded.rs index 5148629..df47365 100644 --- a/headless-rust/src/web/embedded.rs +++ b/headless-rust/src/web/embedded.rs @@ -35,14 +35,14 @@ pub fn get_asset(path: &str) -> Option { .extension() .and_then(|e| e.to_str()) .unwrap_or(""); - let content_type = ContentType::from_extension(ext).unwrap_or(ContentType::HTML); + let content_type = ContentType::from_extension(ext).unwrap_or(ContentType::Bytes); Some(EmbeddedFile { data: file.data.into_owned(), content_type, }) - } else if let Some(index) = Asset::get("index.html") { - // SPA Fallback: Return index.html for client-side routing - Some(EmbeddedFile { + } else if !target.contains('.') { + // SPA Fallback: Return index.html only for client-side navigation routes (routes without file extensions) + Asset::get("index.html").map(|index| EmbeddedFile { data: index.data.into_owned(), content_type: ContentType::HTML, }) diff --git a/headless-rust/src/web/mod.rs b/headless-rust/src/web/mod.rs index d29c70e..a8411d3 100644 --- a/headless-rust/src/web/mod.rs +++ b/headless-rust/src/web/mod.rs @@ -9,12 +9,34 @@ use crate::db::Database; use crate::models::FlashProgressPayload; use crate::serial::SerialService; use crate::storage::FileStore; -use rocket::figment::Figment; -use rocket::{Build, Rocket}; -use std::net::Ipv4Addr; +use rocket::fairing::{Fairing, Info, Kind}; +use rocket::http::Header; +use rocket::{Build, Request, Response, Rocket}; use std::sync::Arc; use tokio::sync::broadcast; +pub struct Cors; + +#[rocket::async_trait] +impl Fairing for Cors { + fn info(&self) -> Info { + Info { + name: "Add CORS Headers", + kind: Kind::Response, + } + } + + async fn on_response<'r>(&self, _request: &'r Request<'_>, response: &mut Response<'r>) { + response.set_header(Header::new("Access-Control-Allow-Origin", "*")); + response.set_header(Header::new( + "Access-Control-Allow-Methods", + "GET, POST, PUT, DELETE, OPTIONS, HEAD", + )); + response.set_header(Header::new("Access-Control-Allow-Headers", "*")); + response.set_header(Header::new("Access-Control-Allow-Credentials", "true")); + } +} + pub fn build_rocket( config: AppConfig, db: Database, @@ -24,11 +46,12 @@ pub fn build_rocket( ) -> Rocket { let (flash_tx, _) = broadcast::channel::(32); - let figment = Figment::from(rocket::Config::default()) - .merge(("port", config.port)) - .merge(("address", config.host.parse::().unwrap_or(Ipv4Addr::new(0, 0, 0, 0)))); + let figment = rocket::Config::figment() + .merge(("address", config.host.as_str())) + .merge(("port", config.port)); rocket::custom(figment) + .attach(Cors) .manage(config) .manage(db) .manage(store) From ab466f275bc217349cd15c45cabde68b9d0e9c15 Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Fri, 14 Aug 2026 23:45:03 +0200 Subject: [PATCH 13/65] feat: remove failed poc headless typescript implementation --- headless/.gitignore | 11 - headless/README.md | 244 ---- headless/bun.lock | 1252 ----------------- headless/components.json | 25 - headless/package.json | 61 - headless/postcss.config.js | 6 - headless/scripts/cleanup-pi.sh | 126 -- headless/scripts/cleanup-remote.sh | 102 -- headless/scripts/deploy-to-pi.sh | 110 -- headless/scripts/install-remote.sh | 142 -- headless/scripts/install-rpi.sh | 229 --- headless/scripts/setup-network.sh | 154 -- headless/scripts/speedcamera.service | 23 - headless/scripts/test-server.ts | 64 - headless/scripts/update-pi.sh | 89 -- headless/scripts/verify-ws.ts | 54 - headless/src/bun-serialport.d.ts | 43 - headless/src/components/ArmingButton.tsx | 237 ---- headless/src/components/ErrorBoundary.tsx | 60 - headless/src/components/FirmwareFlasher.tsx | 363 ----- .../src/components/LapImageThumbnails.tsx | 92 -- headless/src/components/LapTimerDisplay.tsx | 113 -- headless/src/components/LastCapturedImage.tsx | 48 - headless/src/components/NavigationMenu.tsx | 73 - headless/src/components/StatusBadge.tsx | 46 - headless/src/components/ThemeToggle.tsx | 29 - headless/src/components/ViolationCard.tsx | 140 -- headless/src/components/ui/badge.tsx | 49 - headless/src/components/ui/button.tsx | 65 - headless/src/components/ui/card.tsx | 100 -- headless/src/components/ui/checkbox.tsx | 31 - headless/src/components/ui/collapsible.tsx | 31 - headless/src/components/ui/dialog.tsx | 166 --- headless/src/components/ui/input.tsx | 19 - headless/src/components/ui/label.tsx | 22 - headless/src/components/ui/progress.tsx | 29 - headless/src/components/ui/scroll-area.tsx | 53 - headless/src/components/ui/select.tsx | 192 --- headless/src/components/ui/skeleton.tsx | 12 - headless/src/components/ui/slider.tsx | 57 - headless/src/components/ui/sonner.tsx | 48 - headless/src/components/ui/switch.tsx | 31 - headless/src/components/ui/toggle-group.tsx | 89 -- headless/src/components/ui/toggle.tsx | 45 - headless/src/hooks/useLiveLapTimer.ts | 27 - headless/src/hooks/useSystemStateSync.ts | 31 - headless/src/lib/format.ts | 26 - headless/src/lib/rpc.ts | 173 --- headless/src/lib/sound.ts | 44 - headless/src/lib/utils.ts | 6 - headless/src/mainview/App.tsx | 46 - headless/src/mainview/index.css | 135 -- headless/src/mainview/index.html | 12 - headless/src/mainview/main.tsx | 13 - headless/src/routes/__root.tsx | 40 - headless/src/routes/about.tsx | 264 ---- headless/src/routes/index.tsx | 129 -- headless/src/routes/laps.tsx | 44 - headless/src/routes/laps/HistoryTab.tsx | 110 -- headless/src/routes/laps/LapRow.tsx | 103 -- headless/src/routes/laps/LiveSessionTab.tsx | 195 --- headless/src/routes/laps/SessionCard.tsx | 115 -- headless/src/routes/settings.tsx | 58 - headless/src/routes/settings/CameraTab.tsx | 424 ------ headless/src/routes/settings/DeviceTab.tsx | 236 ---- headless/src/routes/settings/LapTimerTab.tsx | 119 -- .../src/routes/settings/SpeedCameraTab.tsx | 263 ---- headless/src/routes/setup.tsx | 97 -- headless/src/routes/teable.tsx | 32 - .../src/routes/teable/ConnectionSection.tsx | 159 --- headless/src/routes/teable/SchemaStatus.tsx | 97 -- .../src/routes/teable/SyncToggleSection.tsx | 39 - .../src/routes/teable/TableTargetSection.tsx | 277 ---- headless/src/routes/violations.tsx | 174 --- .../routes/violations/ExportImagesDialog.tsx | 79 -- .../routes/violations/ViolationGridTile.tsx | 133 -- .../src/routes/violations/ViolationRow.tsx | 111 -- .../src/routes/violations/ViolationsGrid.tsx | 87 -- .../src/routes/violations/ViolationsTable.tsx | 105 -- .../routes/violations/ViolationsToolbar.tsx | 157 --- .../routes/violations/useViolationImage.ts | 27 - .../src/routes/violations/useViolations.ts | 186 --- headless/src/server/database.ts | 431 ------ headless/src/server/env.ts | 28 - headless/src/server/filestore.ts | 60 - headless/src/server/flasher.ts | 210 --- headless/src/server/index.ts | 442 ------ headless/src/server/industrial-camera.ts | 463 ------ headless/src/server/mock/serial.ts | 96 -- headless/src/server/network.ts | 130 -- headless/src/server/rpc.ts | 68 - headless/src/server/serial.ts | 184 --- headless/src/server/skin-renderer.ts | 85 -- headless/src/server/teable.ts | 252 ---- headless/src/shared/schemas.ts | 99 -- headless/src/shared/types.ts | 548 -------- headless/src/stores/slices/cameraSlice.ts | 128 -- headless/src/stores/slices/flasherSlice.ts | 38 - headless/src/stores/slices/lapSlice.ts | 262 ---- .../src/stores/slices/measurementSlice.ts | 90 -- headless/src/stores/slices/serialSlice.ts | 22 - headless/src/stores/slices/systemSlice.ts | 20 - headless/src/stores/slices/teableSlice.ts | 206 --- headless/src/stores/slices/updaterSlice.ts | 82 -- headless/src/stores/useAppStore.ts | 23 - headless/tailwind.config.js | 8 - headless/tsconfig.json | 24 - headless/vite.config.ts | 30 - 108 files changed, 13377 deletions(-) delete mode 100644 headless/.gitignore delete mode 100644 headless/README.md delete mode 100644 headless/bun.lock delete mode 100644 headless/components.json delete mode 100644 headless/package.json delete mode 100644 headless/postcss.config.js delete mode 100755 headless/scripts/cleanup-pi.sh delete mode 100755 headless/scripts/cleanup-remote.sh delete mode 100755 headless/scripts/deploy-to-pi.sh delete mode 100755 headless/scripts/install-remote.sh delete mode 100755 headless/scripts/install-rpi.sh delete mode 100755 headless/scripts/setup-network.sh delete mode 100644 headless/scripts/speedcamera.service delete mode 100644 headless/scripts/test-server.ts delete mode 100755 headless/scripts/update-pi.sh delete mode 100644 headless/scripts/verify-ws.ts delete mode 100644 headless/src/bun-serialport.d.ts delete mode 100644 headless/src/components/ArmingButton.tsx delete mode 100644 headless/src/components/ErrorBoundary.tsx delete mode 100644 headless/src/components/FirmwareFlasher.tsx delete mode 100644 headless/src/components/LapImageThumbnails.tsx delete mode 100644 headless/src/components/LapTimerDisplay.tsx delete mode 100644 headless/src/components/LastCapturedImage.tsx delete mode 100644 headless/src/components/NavigationMenu.tsx delete mode 100644 headless/src/components/StatusBadge.tsx delete mode 100644 headless/src/components/ThemeToggle.tsx delete mode 100644 headless/src/components/ViolationCard.tsx delete mode 100644 headless/src/components/ui/badge.tsx delete mode 100644 headless/src/components/ui/button.tsx delete mode 100644 headless/src/components/ui/card.tsx delete mode 100644 headless/src/components/ui/checkbox.tsx delete mode 100644 headless/src/components/ui/collapsible.tsx delete mode 100644 headless/src/components/ui/dialog.tsx delete mode 100644 headless/src/components/ui/input.tsx delete mode 100644 headless/src/components/ui/label.tsx delete mode 100644 headless/src/components/ui/progress.tsx delete mode 100644 headless/src/components/ui/scroll-area.tsx delete mode 100644 headless/src/components/ui/select.tsx delete mode 100644 headless/src/components/ui/skeleton.tsx delete mode 100644 headless/src/components/ui/slider.tsx delete mode 100644 headless/src/components/ui/sonner.tsx delete mode 100644 headless/src/components/ui/switch.tsx delete mode 100644 headless/src/components/ui/toggle-group.tsx delete mode 100644 headless/src/components/ui/toggle.tsx delete mode 100644 headless/src/hooks/useLiveLapTimer.ts delete mode 100644 headless/src/hooks/useSystemStateSync.ts delete mode 100644 headless/src/lib/format.ts delete mode 100644 headless/src/lib/rpc.ts delete mode 100644 headless/src/lib/sound.ts delete mode 100644 headless/src/lib/utils.ts delete mode 100644 headless/src/mainview/App.tsx delete mode 100644 headless/src/mainview/index.css delete mode 100644 headless/src/mainview/index.html delete mode 100644 headless/src/mainview/main.tsx delete mode 100644 headless/src/routes/__root.tsx delete mode 100644 headless/src/routes/about.tsx delete mode 100644 headless/src/routes/index.tsx delete mode 100644 headless/src/routes/laps.tsx delete mode 100644 headless/src/routes/laps/HistoryTab.tsx delete mode 100644 headless/src/routes/laps/LapRow.tsx delete mode 100644 headless/src/routes/laps/LiveSessionTab.tsx delete mode 100644 headless/src/routes/laps/SessionCard.tsx delete mode 100644 headless/src/routes/settings.tsx delete mode 100644 headless/src/routes/settings/CameraTab.tsx delete mode 100644 headless/src/routes/settings/DeviceTab.tsx delete mode 100644 headless/src/routes/settings/LapTimerTab.tsx delete mode 100644 headless/src/routes/settings/SpeedCameraTab.tsx delete mode 100644 headless/src/routes/setup.tsx delete mode 100644 headless/src/routes/teable.tsx delete mode 100644 headless/src/routes/teable/ConnectionSection.tsx delete mode 100644 headless/src/routes/teable/SchemaStatus.tsx delete mode 100644 headless/src/routes/teable/SyncToggleSection.tsx delete mode 100644 headless/src/routes/teable/TableTargetSection.tsx delete mode 100644 headless/src/routes/violations.tsx delete mode 100644 headless/src/routes/violations/ExportImagesDialog.tsx delete mode 100644 headless/src/routes/violations/ViolationGridTile.tsx delete mode 100644 headless/src/routes/violations/ViolationRow.tsx delete mode 100644 headless/src/routes/violations/ViolationsGrid.tsx delete mode 100644 headless/src/routes/violations/ViolationsTable.tsx delete mode 100644 headless/src/routes/violations/ViolationsToolbar.tsx delete mode 100644 headless/src/routes/violations/useViolationImage.ts delete mode 100644 headless/src/routes/violations/useViolations.ts delete mode 100644 headless/src/server/database.ts delete mode 100644 headless/src/server/env.ts delete mode 100644 headless/src/server/filestore.ts delete mode 100644 headless/src/server/flasher.ts delete mode 100644 headless/src/server/index.ts delete mode 100644 headless/src/server/industrial-camera.ts delete mode 100644 headless/src/server/mock/serial.ts delete mode 100644 headless/src/server/network.ts delete mode 100644 headless/src/server/rpc.ts delete mode 100644 headless/src/server/serial.ts delete mode 100644 headless/src/server/skin-renderer.ts delete mode 100644 headless/src/server/teable.ts delete mode 100644 headless/src/shared/schemas.ts delete mode 100644 headless/src/shared/types.ts delete mode 100644 headless/src/stores/slices/cameraSlice.ts delete mode 100644 headless/src/stores/slices/flasherSlice.ts delete mode 100644 headless/src/stores/slices/lapSlice.ts delete mode 100644 headless/src/stores/slices/measurementSlice.ts delete mode 100644 headless/src/stores/slices/serialSlice.ts delete mode 100644 headless/src/stores/slices/systemSlice.ts delete mode 100644 headless/src/stores/slices/teableSlice.ts delete mode 100644 headless/src/stores/slices/updaterSlice.ts delete mode 100644 headless/src/stores/useAppStore.ts delete mode 100644 headless/tailwind.config.js delete mode 100644 headless/tsconfig.json delete mode 100644 headless/vite.config.ts diff --git a/headless/.gitignore b/headless/.gitignore deleted file mode 100644 index 480c59e..0000000 --- a/headless/.gitignore +++ /dev/null @@ -1,11 +0,0 @@ -# Node modules -node_modules - -# Build output -dist -build -target -artifacts - -# Bundled native binaries (downloaded by CI, not committed) -resources/ \ No newline at end of file diff --git a/headless/README.md b/headless/README.md deleted file mode 100644 index bfa1da3..0000000 --- a/headless/README.md +++ /dev/null @@ -1,244 +0,0 @@ -# Speedcamera Headless & Remote Web Controller - -A lightweight, high-performance headless speedcamera daemon and responsive web controller built with **Bun**, **Vite**, **React**, and **TypeScript**. - -Engineered to run natively on **Raspberry Pi 4 / 5 with Raspberry Pi OS Lite** (zero desktop or GUI dependencies) inside the camera enclosure, creating a standalone Wi-Fi hotspot for laptops, tablets, and phones to connect and manage the system via web browser. - ---- - -## Architecture & Dual-Subnet Network Setup - -``` -┌─────────────────────────────────────────────────────────────────────────┐ -│ Raspberry Pi 4 / 5 (Raspberry Pi OS Lite ARM64) │ -│ │ -│ • eth0 (Camera LAN): 192.168.1.100/24 <── GigE Vision (192.168.1.x)│ -│ • wlan0 (Hotspot AP): 192.168.4.1/24 <── Web UI (SSID: speedcamera)│ -│ │ -│ • systemd Daemon: Pure Headless Bun Service │ -│ ├── Bun.serve() HTTP Server (Vite SPA + Image API) │ -│ ├── WebSocket RPC Server (/ws/rpc) │ -│ ├── Industrial Camera (Aravis GigE Vision on eth0: 192.168.1.100) │ -│ ├── Serial Port (Arduino / Radar Telemetry) │ -│ ├── Network Diagnostics (/api/network) │ -│ └── SQLite Database (bun:sqlite @ ~/.speedcamera) │ -└───────────────────────┬─────────────────────────────▲───────────────────┘ - │ Wi-Fi AP │ Ethernet Cable - ▼ │ -┌──────────────────────────────────────────┐ ┌──────────────────────────┐ -│ Client Device (Laptop / Tablet / Phone) │ │ Industrial GigE Camera │ -│ │ │ │ -│ • Connect Wi-Fi SSID: speedcamera │ │ • Subnet: 192.168.1.0/24 │ -│ • Open Browser: http://192.168.4.1:3000 │ │ • GigE Vision / Aravis │ -│ • Live Radar, Live View, Settings, Laps │ │ • Direct link to eth0 │ -└──────────────────────────────────────────┘ └──────────────────────────┘ -``` - ---- - -## ⚡ Critical Rule: Build on Laptop, Not on Pi - -Building the React / Vite frontend (`dist/`) directly on a Raspberry Pi can take **over 20 minutes** and easily exhausts memory on low-resource ARM boards. - -The built frontend output is 100% platform-independent static web assets. Therefore: -- **`bun run build` always executes locally on your development laptop** (takes ~2 seconds). -- Pre-built static assets in `dist/` are automatically synced to the Pi over SSH. -- The installer and deploy scripts enforce this workflow by default. - ---- - -## Scenarios & Deployment Procedures - -All deployment and maintenance procedures can be executed directly from your laptop via SSH. - -``` -┌────────────────────────────────────────────────────────────────────────┐ -│ Command │ Purpose │ -├──────────────────────────────┼─────────────────────────────────────────┤ -│ bun run install:pi [target] │ Fresh Pi install on Home LAN / DHCP │ -│ bun run deploy:pi [target] │ Upgrade existing Pi (Field or Home LAN) │ -│ bun run cleanup:pi [target] │ Complete teardown & restore DHCP network│ -└──────────────────────────────┴─────────────────────────────────────────┘ -``` - ---- - -### Scenario 1: Fresh Pi Setup (Home LAN / Wi-Fi with DHCP) - -Use this scenario when you have a freshly flashed Raspberry Pi connected to your home router / Wi-Fi via DHCP and want to provision the complete speedcamera suite. - -#### Run from your laptop: -```bash -cd headless - -# Standard fresh installation (SSH key auth): -bun run install:pi pi@raspberrypi.local - -# With password prompt (if SSH keys are not configured): -bun run install:pi pi@raspberrypi.local --password - -# Using direct IP and automatically switching to Field Mode at the end: -bun run install:pi pi@192.168.1.50 --field - -# Stay in Home LAN mode (skip field network setup): -bun run install:pi pi@raspberrypi.local --lan -``` - -#### What this command does: -1. Builds the frontend bundle on your laptop (`bun run build`, ~2s). -2. Establishes an SSH multiplexed connection (password requested once). -3. Rsyncs the codebase and pre-built `dist/` to `~/speedcamera/headless` on the Pi. -4. Updates Pi system packages (`libaravis-0.8-0`, `libaravis-dev`, `esptool`, `network-manager`, `curl`, etc.). -5. Installs the ARM64 Bun runtime on the Pi (if not installed). -6. Installs production node dependencies on the Pi. -7. Registers, enables, and starts the `speedcamera.service` systemd daemon. -8. Configures the network mode (Field Mode or Home LAN Mode). - ---- - -### Scenario 2: Upgrading an Existing Installation - -Use this scenario to push code updates to an already configured Pi. The Pi can either be in **Field Mode** (offline Wi-Fi hotspot) or connected to your **Home LAN**. - -#### Run from your laptop: -```bash -cd headless - -# Deploy to Pi on Home LAN: -bun run deploy:pi pi@raspberrypi.local - -# Deploy to Pi in Field Mode (connected to 'speedcamera' Wi-Fi): -bun run deploy:pi pi@192.168.4.1 - -# With password authentication: -bun run deploy:pi pi@192.168.4.1 --password -``` - -#### What this command does: -1. Re-builds the frontend bundle locally (`bun run build`). -2. Syncs changed files (`dist/`, `src/`, `scripts/`, `package.json`, etc.) to the Pi. -3. Automatically detects internet connectivity on the Pi: - - **Online (Home LAN):** Updates production dependencies if `package.json` changed. - - **Offline (Field Mode):** Safely skips dependency downloads and reuses existing `node_modules`. -4. Updates the systemd service file if needed and runs `sudo systemctl daemon-reload`. -5. Restarts `speedcamera.service` and verifies that the daemon is active and running. -6. **Preserves existing network configuration** without causing unexpected disconnections. - ---- - -### Scenario 3: Complete Cleanup & Network Reset - -Use this scenario to completely uninstall Speedcamera, remove systemd services, delete application files, and restore standard DHCP networking on Ethernet and Wi-Fi. - -#### Option A: Remote cleanup from your laptop -```bash -cd headless - -# Clean up speedcamera and restore DHCP network: -bun run cleanup:pi pi@raspberrypi.local - -# Clean up in Field Mode and purge all SQLite databases/images: -bun run cleanup:pi pi@192.168.4.1 --password --purge - -# Non-interactive cleanup: -bun run cleanup:pi pi@raspberrypi.local --yes --purge -``` - -#### Option B: Direct cleanup on the Raspberry Pi -```bash -# SSH into Pi -ssh pi@raspberrypi.local - -# Run cleanup script -~/speedcamera/headless/scripts/cleanup-pi.sh - -# Or with complete data purge (database & images): -~/speedcamera/headless/scripts/cleanup-pi.sh --purge --yes -``` - -#### What cleanup does: -1. Stops and disables `speedcamera.service`. -2. Deletes `/etc/systemd/system/speedcamera.service` and reloads systemd. -3. Deletes repository files `~/speedcamera` (and purges `~/.speedcamera` if `--purge`). -4. Restores Ethernet `eth0` to standard automatic DHCP (ready for router connection). -5. **Safe Hotspot Teardown:** If triggered while connected to the Pi's Wi-Fi hotspot (`192.168.4.1`), the script completes all service/file/Ethernet cleanup first, then schedules Wi-Fi AP shutdown with a 2-second background delay (`nohup`), allowing the SSH session to return cleanly before the hotspot turns off. - ---- - -## Network Mode Management (`setup-network.sh`) - -You can switch the Pi's networking mode at any time using the network management script: - -```bash -# Switch to Standalone Field Mode (Camera LAN 192.168.1.100 + Hotspot AP 192.168.4.1) -~/speedcamera/headless/scripts/setup-network.sh field - -# Connect Pi Wi-Fi to a router for internet updates (Client Mode) -~/speedcamera/headless/scripts/setup-network.sh internet "MyHomeWiFi" "SecretPassword123" - -# Revert Ethernet and Wi-Fi to standard DHCP -~/speedcamera/headless/scripts/setup-network.sh dhcp - -# Check active connections, IP addresses, and internet reachability -~/speedcamera/headless/scripts/setup-network.sh status -``` - ---- - -## Managing the Service on Raspberry Pi - -The Speedcamera backend daemon runs as a `systemd` background service: - -```bash -# Check service status -sudo systemctl status speedcamera - -# View live streaming logs -sudo journalctl -u speedcamera -f - -# Restart service -sudo systemctl restart speedcamera - -# Stop service -sudo systemctl stop speedcamera - -# Start service -sudo systemctl start speedcamera -``` - ---- - -## Field Operation Quick Reference - -1. Power on the Raspberry Pi. -2. On your laptop, phone, or tablet, connect to the Wi-Fi network: - - **SSID:** `speedcamera` - - **Password:** `speedcamerapass` -3. Open your web browser and go to: - - **`http://192.168.4.1:3000`** -4. Connect the industrial GigE Vision camera to the Pi's Ethernet port (assigned to `192.168.1.100`). - ---- - -## Local Development & Testing - -You can develop and test the entire headless system on your local laptop without physical hardware using mock mode: - -```bash -cd headless - -# Install local dependencies -bun install - -# Run frontend (Vite HMR on :5173) + backend (Bun on :3000) with mock camera & radar -bun run dev:mock - -# Build production bundle -bun run build - -# Run production server locally with mock hardware -bun run start:mock -``` - -- **Web UI:** `http://localhost:5173` (dev) or `http://localhost:3000` (production) -- **WebSocket RPC:** `ws://localhost:3000/ws/rpc` diff --git a/headless/bun.lock b/headless/bun.lock deleted file mode 100644 index c5e5a13..0000000 --- a/headless/bun.lock +++ /dev/null @@ -1,1252 +0,0 @@ -{ - "lockfileVersion": 1, - "configVersion": 1, - "workspaces": { - "": { - "name": "speedcamera-headless", - "dependencies": { - "@asl-gokart/bun-aravis": "^0.2.0", - "@fontsource-variable/figtree": "^5.2.10", - "@hugeicons/core-free-icons": "^4.1.1", - "@hugeicons/react": "^1.1.6", - "@napi-rs/canvas": "^1.0.3", - "@tailwindcss/postcss": "^4.2.4", - "@tailwindcss/vite": "^4.2.4", - "@tanstack/react-router": "^1.168.23", - "bun-serialport": "^0.1.1", - "class-variance-authority": "^0.7.1", - "clsx": "^2.1.1", - "lucide-react": "^1.8.0", - "next-themes": "^0.4.6", - "radix-ui": "^1.4.3", - "react": "^18.3.1", - "react-dom": "^18.3.1", - "react-webcam": "^7.2.0", - "shadcn": "^4.7.0", - "sharp": "^0.35.2", - "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/bun": "latest", - "@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=="], - - "@asl-gokart/bun-aravis": ["@asl-gokart/bun-aravis@0.2.0", "https://registry.leotm.de/@asl-gokart/bun-aravis/-/bun-aravis-0.2.0.tgz", { "peerDependencies": { "typescript": "^5.0.0" } }, "sha512-PqQWZZD45sOZijdUJmLpTjnf4ZqFR9ltmYWBh4fQfXBobIJiZJiUWJQ/EevvR9KuhtIAvXqlvO3B2KtSoWV21Q=="], - - "@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=="], - - "@emnapi/runtime": ["@emnapi/runtime@1.11.3", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA=="], - - "@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.0", "", { "peerDependencies": { "hono": "^4" } }, "sha512-XovyyCCnBzW+zKu+z/zq8hwNs4KOR5rEMAOxo2f40Q5xoOI37IMm6MIg2COOUtUApo0i6850MTBKH2u4QLGIqg=="], - - "@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=="], - - "@img/colour": ["@img/colour@1.1.0", "", {}, "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ=="], - - "@img/sharp-darwin-arm64": ["@img/sharp-darwin-arm64@0.35.3", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-arm64": "1.3.2" }, "os": "darwin", "cpu": "arm64" }, "sha512-RMnFX7YQsMoh7lWfcM4NEHHymBX/rLuKNPVM84XE9ONPcaSCDgE7CHIHpSgPcO2xcRthgBy1HfNO319mwhIAkg=="], - - "@img/sharp-darwin-x64": ["@img/sharp-darwin-x64@0.35.3", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-x64": "1.3.2" }, "os": "darwin", "cpu": "x64" }, "sha512-Xo+5uFBtLN0BKqieTxiFzFPQAUlBbbH5iBKyRX/z1JrbnYsHTfKJnUfL8+p2TPXr1pXqao4eeL4Rl144uDpK9w=="], - - "@img/sharp-freebsd-wasm32": ["@img/sharp-freebsd-wasm32@0.35.3", "", { "dependencies": { "@img/sharp-wasm32": "0.35.3" }, "os": "freebsd" }, "sha512-lUxcqWIj2wMQ9BrwNjngcr1gWUr5xgaGThBRqPPalIC2n67Cqj1uPh8NnA/ZhAg8hUbKl+kVHKwgUIwe6ZYPrg=="], - - "@img/sharp-libvips-darwin-arm64": ["@img/sharp-libvips-darwin-arm64@1.3.2", "", { "os": "darwin", "cpu": "arm64" }, "sha512-9J6ypZFpQBj4YnePGoq/S38w6nz+vqg5WZLrLGY4YuSemdMq47GMLBPO42MzwdGwpg/agZ7xzZcFHa48xlywfg=="], - - "@img/sharp-libvips-darwin-x64": ["@img/sharp-libvips-darwin-x64@1.3.2", "", { "os": "darwin", "cpu": "x64" }, "sha512-m2pW1n6cns9VaubNwsZ+c3CRYjxNQWgJ5gPlnL1nbBcpkBvFm6SCFN5o0psFHI8w9n11NKhFkeEDns98tiqbEw=="], - - "@img/sharp-libvips-linux-arm": ["@img/sharp-libvips-linux-arm@1.3.2", "", { "os": "linux", "cpu": "arm" }, "sha512-1eMLzy92I4J6rmi4mAT8yC3HxOtniyGELlzGbNMLLeqe052ahFQ0h6LFq+lh5DsDIdYViIDst08abvSbcEdLXQ=="], - - "@img/sharp-libvips-linux-arm64": ["@img/sharp-libvips-linux-arm64@1.3.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-dqVSFynCox4C/J8kT16V7SIFAns0IjgLwkvYT7p8LQVmJ5OS5b6tI9IGflxTeuBS//zXeFIUbwt5dwxyZ17cnA=="], - - "@img/sharp-libvips-linux-ppc64": ["@img/sharp-libvips-linux-ppc64@1.3.2", "", { "os": "linux", "cpu": "ppc64" }, "sha512-3z0NHDxD6n5I9gc05U1eW1AyRm+Gznzq3naMrthPNqE6oYykcogW0l/jfpJdjYnuNl8R7yI9pNbE1XiUeyq0Aw=="], - - "@img/sharp-libvips-linux-riscv64": ["@img/sharp-libvips-linux-riscv64@1.3.2", "", { "os": "linux", "cpu": "none" }, "sha512-bsb4rI+NldGOsXuej2r8OdSS8+zXDVaCWxyWrcv6kneTOlgAHtZABRzBBCwdsPiD90J4myNJuHpg6kA20ImW/w=="], - - "@img/sharp-libvips-linux-s390x": ["@img/sharp-libvips-linux-s390x@1.3.2", "", { "os": "linux", "cpu": "s390x" }, "sha512-/ABshyj8gCpyIrNXnHn4LorDJ0HHm1VhXPBlxZ8zAtfVPAaSafXPGn+sUSIRiwaSBy0mmFjSjiXI5mkcwdChKQ=="], - - "@img/sharp-libvips-linux-x64": ["@img/sharp-libvips-linux-x64@1.3.2", "", { "os": "linux", "cpu": "x64" }, "sha512-ITPEtgffGJ0S6G9dRyw/366tJQqFRcHWPHhC+Stpg3Z8AEMrDrTr2lhdz4f/Y/HMbRh//7Z5mBzEpVdi62Oc3w=="], - - "@img/sharp-libvips-linuxmusl-arm64": ["@img/sharp-libvips-linuxmusl-arm64@1.3.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-zE9EdiUzUmg5mDT5a1rk5fYJ6GWPloTwWBYDS14naqHsL+EaMpDj1AWnpLgh3u0YCORv2Tt50wrcrpYqkP97Kw=="], - - "@img/sharp-libvips-linuxmusl-x64": ["@img/sharp-libvips-linuxmusl-x64@1.3.2", "", { "os": "linux", "cpu": "x64" }, "sha512-m0lrLiUt+lBYnCFr8qV/65yMR4E/c7/wf78I5eKTdkEakFAlZ9QlzEM3QIhhAwVeUhLAHLcCq7a7Vszq/oFNZQ=="], - - "@img/sharp-linux-arm": ["@img/sharp-linux-arm@0.35.3", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm": "1.3.2" }, "os": "linux", "cpu": "arm" }, "sha512-affVWCTLooy8TSxbDx2qkzuDeaWLNVBA+P//FNBirHsXpP2fuBhk5AuboYUnrDnzoXes8GFjpTx0SBFOCRg+FA=="], - - "@img/sharp-linux-arm64": ["@img/sharp-linux-arm64@0.35.3", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm64": "1.3.2" }, "os": "linux", "cpu": "arm64" }, "sha512-QgKDspHPnrU+GQ55XPhGwyhC8acLVOOSyAvo1oVfFmrIXLkDNmGWzAfDZ4xK8oSA1qBQrALcHX0G5UZni/SuFQ=="], - - "@img/sharp-linux-ppc64": ["@img/sharp-linux-ppc64@0.35.3", "", { "optionalDependencies": { "@img/sharp-libvips-linux-ppc64": "1.3.2" }, "os": "linux", "cpu": "ppc64" }, "sha512-sMd8rDxmpLOwv/7N44klFjOD5DUO7FLdjiXDI0hoxYaf7Ar262dQIEkosE98bps+5HPLtp/EvNqeqQtOycP/IA=="], - - "@img/sharp-linux-riscv64": ["@img/sharp-linux-riscv64@0.35.3", "", { "optionalDependencies": { "@img/sharp-libvips-linux-riscv64": "1.3.2" }, "os": "linux", "cpu": "none" }, "sha512-0Eob78yjlYPfL5vMNWAW55l3R9Y6BQS/gOfe0ZcP9mEz9ohhKSt4im1hayiknXgf8AWrFqMvJcKIdmLmEe7yeQ=="], - - "@img/sharp-linux-s390x": ["@img/sharp-linux-s390x@0.35.3", "", { "optionalDependencies": { "@img/sharp-libvips-linux-s390x": "1.3.2" }, "os": "linux", "cpu": "s390x" }, "sha512-KgAxQ0DxpNOq1rG2t5cgTgShJFGSuU7XO45cqC+1NVOuZnP6tlgZRuSYOfNupGkHID0o3cJOsw4DVeJpMovcGw=="], - - "@img/sharp-linux-x64": ["@img/sharp-linux-x64@0.35.3", "", { "optionalDependencies": { "@img/sharp-libvips-linux-x64": "1.3.2" }, "os": "linux", "cpu": "x64" }, "sha512-8pqvxubL2PGdhlPy6GLqzDYMUjyRmKAwKHYKixpdJYBUK7PJ0C029XdsnpFIdgRZG68fZiGdHVWcKPvtiPB4cA=="], - - "@img/sharp-linuxmusl-arm64": ["@img/sharp-linuxmusl-arm64@0.35.3", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-arm64": "1.3.2" }, "os": "linux", "cpu": "arm64" }, "sha512-Vz0iQjzzcSX3HCbfwFfCSG/9SCIqyO0mH2sXyiHaAYfBk0cRsCWXRyQYX0ovCK/PAQBbTzQ0dsPQHh5MAFL59w=="], - - "@img/sharp-linuxmusl-x64": ["@img/sharp-linuxmusl-x64@0.35.3", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-x64": "1.3.2" }, "os": "linux", "cpu": "x64" }, "sha512-6O1NPKcDVj9QEdg7Hx549EX8U0rp6yXQERqru6yRN7fGBn32UvIRJUlWnk+8xDCiG76hXVBbX82NZ/ZKr0euIg=="], - - "@img/sharp-wasm32": ["@img/sharp-wasm32@0.35.3", "", { "dependencies": { "@emnapi/runtime": "^1.11.1" } }, "sha512-cZ0XkcYGpHZkqW6iCkqTcmUC0CD9DhD5d/qeZlZkfRBn6GnHniZXLUo5+9xw8Iv76YE6LQFN9YNBlKREcCG76w=="], - - "@img/sharp-webcontainers-wasm32": ["@img/sharp-webcontainers-wasm32@0.35.3", "", { "dependencies": { "@img/sharp-wasm32": "0.35.3" }, "cpu": "none" }, "sha512-2rnq7bX3NzeR2T4YWgz8qiG4h3TSdMe+vN1iQXpJleSJ3SM5zQ8Fy2SyyXAWlbxpEZ2Y+Z4u1BePgJEYbSy80Q=="], - - "@img/sharp-win32-arm64": ["@img/sharp-win32-arm64@0.35.3", "", { "os": "win32", "cpu": "arm64" }, "sha512-4bPwFdMbeC4JQ8L8LOyWp6nsHcboP5fxkp6iPOXz2Vg49R42TuMs2whkJ5OAP4/Ul035qOzy0AecOF9VOscn4w=="], - - "@img/sharp-win32-ia32": ["@img/sharp-win32-ia32@0.35.3", "", { "os": "win32", "cpu": "ia32" }, "sha512-r53mXsBN6lFUDiST764SvgwUdHAqM4rPAiDzAmf4fLoB6X/rkfyTrLCg6+g17wJJiCmB3JYgHuUldCWUIRFSXw=="], - - "@img/sharp-win32-x64": ["@img/sharp-win32-x64@0.35.3", "", { "os": "win32", "cpu": "x64" }, "sha512-D4y1vNeZrIIJCN+uHaWVtH86B+aCrdMYYjicy9pXHvbGZeGYLLSd3wdVuC37FxVXlU1ARsk84eKWfWMXGYEqvA=="], - - "@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/canvas": ["@napi-rs/canvas@1.0.5", "", { "optionalDependencies": { "@napi-rs/canvas-android-arm64": "1.0.5", "@napi-rs/canvas-darwin-arm64": "1.0.5", "@napi-rs/canvas-darwin-x64": "1.0.5", "@napi-rs/canvas-linux-arm-gnueabihf": "1.0.5", "@napi-rs/canvas-linux-arm64-gnu": "1.0.5", "@napi-rs/canvas-linux-arm64-musl": "1.0.5", "@napi-rs/canvas-linux-riscv64-gnu": "1.0.5", "@napi-rs/canvas-linux-x64-gnu": "1.0.5", "@napi-rs/canvas-linux-x64-musl": "1.0.5", "@napi-rs/canvas-win32-arm64-msvc": "1.0.5", "@napi-rs/canvas-win32-x64-msvc": "1.0.5" } }, "sha512-GaPlicMtnvgPr5SowFRprkEJicDSrV3qCq17U4jiF5u0kNORZo3IbdN2Bk4SfcZJAMYFHbMVJ81O3w21CYxazg=="], - - "@napi-rs/canvas-android-arm64": ["@napi-rs/canvas-android-arm64@1.0.5", "", { "os": "android", "cpu": "arm64" }, "sha512-ZzDlpKQocwFfCwhMh17UWre6Qt5yZN3kNIJoUpGfRZqwDDZ164IKOsPOHsRd3d8Tuj5KM6bDjGuPmZxuPuG3NQ=="], - - "@napi-rs/canvas-darwin-arm64": ["@napi-rs/canvas-darwin-arm64@1.0.5", "", { "os": "darwin", "cpu": "arm64" }, "sha512-Hr8v6CA/TBe+OJOePdV3sXWxzQHQKfQsTKPbc8wG7iPqVeAx6MMdzKGXlYID6SVvpfwV/zqkvGcdImYWSlhrZg=="], - - "@napi-rs/canvas-darwin-x64": ["@napi-rs/canvas-darwin-x64@1.0.5", "", { "os": "darwin", "cpu": "x64" }, "sha512-9BXlLHBXpYnK4jSae1MdFdyPq09Xi1I3PeCNpvRzqgmUUBhgJS7aC1z7SZEP8JUXDHtbfIrolCS3sFuT9IGP2A=="], - - "@napi-rs/canvas-linux-arm-gnueabihf": ["@napi-rs/canvas-linux-arm-gnueabihf@1.0.5", "", { "os": "linux", "cpu": "arm" }, "sha512-zEW4fgvtYsOJ/N56Us4TQPfaFrUf0shGr9CgGSj3GACc+NHfUM3ci0YF9xFTjwJWGDmaEhYPL6KqCfFCxwm/qg=="], - - "@napi-rs/canvas-linux-arm64-gnu": ["@napi-rs/canvas-linux-arm64-gnu@1.0.5", "", { "os": "linux", "cpu": "arm64" }, "sha512-HFprwLspelJxCEtZvdMcz95Mwvfs63GzFVedLFmC/wslHnaOXhjXxgYxPCM/VdM4Jhx3CV4Lk0vVmh6hJv2etQ=="], - - "@napi-rs/canvas-linux-arm64-musl": ["@napi-rs/canvas-linux-arm64-musl@1.0.5", "", { "os": "linux", "cpu": "arm64" }, "sha512-FNMGFAx8DvtDwlLfWyBJ+oQjgPXoIAqCnNTJYqtJCFRwwzK3AyAe5B1Ll3NZ6hcOzqw7HylZsq4nQxVyPCQX1Q=="], - - "@napi-rs/canvas-linux-riscv64-gnu": ["@napi-rs/canvas-linux-riscv64-gnu@1.0.5", "", { "os": "linux", "cpu": "none" }, "sha512-2vd5v8Lui+37Hh/spITKIvTT384ip4dnUc5XBn0E+sMNS4b7au7IswyT5YDG2udPTjSh/eLUs3sGuB5YHooFOA=="], - - "@napi-rs/canvas-linux-x64-gnu": ["@napi-rs/canvas-linux-x64-gnu@1.0.5", "", { "os": "linux", "cpu": "x64" }, "sha512-iQIPy+Uey0expZTOszLri5n8rY7x4WUpMaY82mcXNIgbil30iHvc01OsiizhZC1KQHTK90RFMFWSpwFU+ON3aA=="], - - "@napi-rs/canvas-linux-x64-musl": ["@napi-rs/canvas-linux-x64-musl@1.0.5", "", { "os": "linux", "cpu": "x64" }, "sha512-Npthji25t7FUqIAKsoEkFS0qY5CYVkHjvI3tuZjDTG92wX8g4dst+Lfb4hhubdqPazlDcIwalPzInsFCtf3FFg=="], - - "@napi-rs/canvas-win32-arm64-msvc": ["@napi-rs/canvas-win32-arm64-msvc@1.0.5", "", { "os": "win32", "cpu": "arm64" }, "sha512-bi+JsdCdbfVJDoAQybTYmkLKwh1xpYpptg5j/BNr2BB56u4/R26jrVvtjqff+CxYMXV6Kz1/jeDVhZCuj6bDng=="], - - "@napi-rs/canvas-win32-x64-msvc": ["@napi-rs/canvas-win32-x64-msvc@1.0.5", "", { "os": "win32", "cpu": "x64" }, "sha512-KQQwG9/sBmcGxqaLFIQf+k2OefREGoyEaIBmRuTM8bUuFKOEE9Xk5pel90hE6pmBwk/vo4RB0OdX+FxobJGMFw=="], - - "@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=="], - - "@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.25", "", { "dependencies": { "@tanstack/history": "1.162.1", "@tanstack/react-store": "^0.9.3", "@tanstack/router-core": "1.171.21", "isbot": "^5.1.22" }, "peerDependencies": { "react": ">=18.0.0 || >=19.0.0", "react-dom": ">=18.0.0 || >=19.0.0" } }, "sha512-XiWYvkLAGhcZHhV2xUvicpF/VfTVSnewP6CqviDONAjmD50tBob5x/93u2W8QZAc/JgkPd+jijCmu6t4NCzmew=="], - - "@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.21", "", { "dependencies": { "@tanstack/history": "1.162.1", "cookie-es": "^3.0.0", "seroval": "^1.6.2", "seroval-plugins": "^1.6.2" } }, "sha512-t6xUHBO94nQDrPHPh6ag5UuKHWIkVjq9s63q2ctbxgzq3vtSoGKmAIdLD5o+NU6JUS1ppXRHgL0YGzEHvH32Ng=="], - - "@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/bun": ["@types/bun@1.3.14", "", { "dependencies": { "bun-types": "1.3.14" } }, "sha512-h1hFqFVcvAvD9j9K7ZW7vd82aSA+rTdznZa+5bwvCwqSB1jmmfLcbIWhOLx1/+boy/xmjgCs/OMUL8hRJSmnPw=="], - - "@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.2.2", "", {}, "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg=="], - - "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.13", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-k9HNuUVMlqVjQ9UHzfPjIqiDbWw7WqT1AoT7GL8VwvF3r0ZfArtgiSPAlmupyNquNgOJHTuH4CKYf8ttMTWBTQ=="], - - "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=="], - - "bun-serialport": ["bun-serialport@0.1.1", "", { "os": [ "linux", "darwin", ] }, "sha512-hObWOJD/TyEjCFln7TGWQEdzd/XTo+rQIQ8BNb1pR/5caJ2KbDitzq+TaTfuoxqJd+1bBQWIc7QsVul8Xq7elQ=="], - - "bun-types": ["bun-types@1.3.14", "", { "dependencies": { "@types/node": "*" } }, "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ=="], - - "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.403", "", {}, "sha512-MQsYmdaLzvaCX5j+ZZBr5Fm6uCCnPQcRtlvmvRlWqrXy+BH2O4ffXIAScF+JQznQWB9brWp4lSD9Z4yNmaf2BA=="], - - "emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="], - - "encodeurl": ["encodeurl@2.0.0", "", {}, "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg=="], - - "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.1", "", {}, "sha512-kdJoFVv2xmayw6cY09H7AbMJMt8Jn5jdlEdXsP7AGBdF2DIptVlKlOLKXP41yPip4/a3yQPv9gVcJYI8YY04dw=="], - - "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.0", "", { "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.1.0", "wsl-utils": "^0.3.0" } }, "sha512-smsWv2LzFjP03xmvFoJ331ss6h+jixfA4UUV/Bsiyuu4YJPfN+FIQGOIiv4w9/+MoHkfkJ22UIaQWRVFRfH6Vw=="], - - "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.1.0", "", {}, "sha512-dM0jVuXJPsDN6DvRpea484tCUaMiXWjuCn++HGTqUWzGDjv5tZkEZldAJ/UMlqRYGFrD/etByo4/xOuC/snX2A=="], - - "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=="], - - "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@7.8.5", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="], - - "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.16.2", "", { "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", "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-M1AvZKFWcCzWRDoyApIqJMSLIpY8Ev4uBGuiPLSFmiTbixXhPmzotSTvLzFmBrfoIxG9aIg2dZOETblEaXGUnQ=="], - - "sharp": ["sharp@0.35.3", "", { "dependencies": { "@img/colour": "^1.1.0", "detect-libc": "^2.1.2", "semver": "^7.8.5" }, "optionalDependencies": { "@img/sharp-darwin-arm64": "0.35.3", "@img/sharp-darwin-x64": "0.35.3", "@img/sharp-freebsd-wasm32": "0.35.3", "@img/sharp-libvips-darwin-arm64": "1.3.2", "@img/sharp-libvips-darwin-x64": "1.3.2", "@img/sharp-libvips-linux-arm": "1.3.2", "@img/sharp-libvips-linux-arm64": "1.3.2", "@img/sharp-libvips-linux-ppc64": "1.3.2", "@img/sharp-libvips-linux-riscv64": "1.3.2", "@img/sharp-libvips-linux-s390x": "1.3.2", "@img/sharp-libvips-linux-x64": "1.3.2", "@img/sharp-libvips-linuxmusl-arm64": "1.3.2", "@img/sharp-libvips-linuxmusl-x64": "1.3.2", "@img/sharp-linux-arm": "0.35.3", "@img/sharp-linux-arm64": "0.35.3", "@img/sharp-linux-ppc64": "0.35.3", "@img/sharp-linux-riscv64": "0.35.3", "@img/sharp-linux-s390x": "0.35.3", "@img/sharp-linux-x64": "0.35.3", "@img/sharp-linuxmusl-arm64": "0.35.3", "@img/sharp-linuxmusl-x64": "0.35.3", "@img/sharp-webcontainers-wasm32": "0.35.3", "@img/sharp-win32-arm64": "0.35.3", "@img/sharp-win32-ia32": "0.35.3", "@img/sharp-win32-x64": "0.35.3" }, "peerDependencies": { "@types/node": "*" }, "optionalPeers": ["@types/node"] }, "sha512-ej0zVHuZGHCiABXcNxeYhpRnPNPAcvbG8RMdBAhDAxLKkCRVSpK3Iyu7qbqw3JMzoj0REeM6f3tJLtVwl0023Q=="], - - "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=="], - - "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=="], - - "wsl-utils": ["wsl-utils@0.3.1", "", { "dependencies": { "is-wsl": "^3.1.0", "powershell-utils": "^0.1.0" } }, "sha512-g/eziiSUNBSsdDJtCLB8bdYEUMj4jR7AGeUo96p/3dTafgjHhpF4RiCFPiRILwjQoDXx5MqkBr4fwWtR3Ky4Wg=="], - - "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.14", "", { "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-/8tAspM5LMPr28b3fwLYrtdj77ECpfZviaP75CMTnwO8ISyaE4GDIG/9rDDYq/cH9D2Xw2A2RXglLInmVBQB/g=="], - - "@babel/core/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="], - - "@babel/helper-compilation-targets/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="], - - "@babel/helper-create-class-features-plugin/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="], - - "@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.2", "", { "dependencies": { "@tybys/wasm-util": "^0.10.3" }, "peerDependencies": { "@emnapi/core": "^1.7.1 || ^2.0.0-alpha.3", "@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.3" }, "bundled": true }, "sha512-JfB4kuJQjaoHuCTseIINHtHWeJnvgEcxjwA5t/Y00ZgaOO1Crz3fjT/p8kT28zA/Caz7oiUMn3d6H2yOVCVwuw=="], - - "@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.0.0", "", {}, "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ=="], - - "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=="], - - "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.0.0", "", {}, "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ=="], - - "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=="], - - "@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/components.json b/headless/components.json deleted file mode 100644 index 6c10365..0000000 --- a/headless/components.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "$schema": "https://ui.shadcn.com/schema.json", - "style": "radix-maia", - "rsc": false, - "tsx": true, - "tailwind": { - "config": "tailwind.config.js", - "css": "src/mainview/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/package.json b/headless/package.json deleted file mode 100644 index 9431791..0000000 --- a/headless/package.json +++ /dev/null @@ -1,61 +0,0 @@ -{ - "name": "speedcamera-headless", - "type": "module", - "version": "0.4.0", - "description": "Headless Speedcamera daemon and Web UI for Raspberry Pi 4/5 and remote browser control", - "scripts": { - "dev": "concurrently \"bun run dev:client\" \"bun run dev:server\"", - "dev:mock": "concurrently \"bun run dev:client\" \"MOCK_MODE=true bun --watch src/server/index.ts\"", - "dev:client": "vite", - "dev:server": "bun --watch src/server/index.ts", - "build": "vite build", - "start": "vite build && bun src/server/index.ts", - "start:mock": "MOCK_MODE=true vite build && MOCK_MODE=true bun src/server/index.ts", - "serve": "bun src/server/index.ts", - "serve:mock": "MOCK_MODE=true bun src/server/index.ts", - "install:pi": "./scripts/install-remote.sh", - "deploy:pi": "./scripts/deploy-to-pi.sh", - "cleanup:pi": "./scripts/cleanup-remote.sh", - "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": { - "@asl-gokart/bun-aravis": "^0.2.0", - "@fontsource-variable/figtree": "^5.2.10", - "@hugeicons/core-free-icons": "^4.1.1", - "@hugeicons/react": "^1.1.6", - "@napi-rs/canvas": "^1.0.3", - "@tailwindcss/postcss": "^4.2.4", - "@tailwindcss/vite": "^4.2.4", - "@tanstack/react-router": "^1.168.23", - "bun-serialport": "^0.1.1", - "class-variance-authority": "^0.7.1", - "clsx": "^2.1.1", - "lucide-react": "^1.8.0", - "next-themes": "^0.4.6", - "radix-ui": "^1.4.3", - "react": "^18.3.1", - "react-dom": "^18.3.1", - "react-webcam": "^7.2.0", - "shadcn": "^4.7.0", - "sharp": "^0.35.2", - "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/bun": "latest", - "@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/postcss.config.js b/headless/postcss.config.js deleted file mode 100644 index f69c5d4..0000000 --- a/headless/postcss.config.js +++ /dev/null @@ -1,6 +0,0 @@ -export default { - plugins: { - "@tailwindcss/postcss": {}, - autoprefixer: {}, - }, -}; diff --git a/headless/scripts/cleanup-pi.sh b/headless/scripts/cleanup-pi.sh deleted file mode 100755 index be4bb0d..0000000 --- a/headless/scripts/cleanup-pi.sh +++ /dev/null @@ -1,126 +0,0 @@ -#!/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/scripts/cleanup-remote.sh b/headless/scripts/cleanup-remote.sh deleted file mode 100755 index 1bdde14..0000000 --- a/headless/scripts/cleanup-remote.sh +++ /dev/null @@ -1,102 +0,0 @@ -#!/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 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 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/scripts/deploy-to-pi.sh b/headless/scripts/deploy-to-pi.sh deleted file mode 100755 index b66c7fe..0000000 --- a/headless/scripts/deploy-to-pi.sh +++ /dev/null @@ -1,110 +0,0 @@ -#!/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.4.1 --password -# bun run deploy:pi pi@raspberrypi.local - -PI_TARGET="pi@raspberrypi.local" -USE_PASSWORD=false -FORCE_INSTALL=false -INSTALL_FLAG="" - -# Parse arguments -for arg in "$@"; do - case "$arg" in - --password|-p|--pass) - USE_PASSWORD=true - ;; - --install|-i) - FORCE_INSTALL=true - INSTALL_FLAG="--install" - ;; - --help|-h) - echo "Speedcamera Headless 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.4.1)" - echo "" - echo "Options:" - echo " --password, -p Force password authentication (disables SSH keys)" - echo " --install, -i Force running 'bun install' on Pi (requires internet on Pi)" - echo " --help, -h Show this help message" - echo "" - echo "Notes:" - echo " • Automatically builds frontend locally on host (fast: <2s)." - echo " • Works seamlessly in Field Mode (offline) or Home LAN Mode (online)." - exit 0 - ;; - *) - if [[ "$arg" != -* ]]; then - PI_TARGET="$arg" - fi - ;; - esac -done - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -HEADLESS_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)" - -# 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 Headless: ${PI_TARGET}" -echo "=========================================================" - -# 1. Build frontend bundle on host (fast!) -echo "[1/3] Building frontend bundle locally on host machine..." -cd "${HEADLESS_DIR}" -bun run build - -# 2. Sync files to Pi (skipping heavy node_modules & git) -echo "[2/3] Syncing files to Pi..." -ssh "${SSH_OPTS[@]}" "${PI_TARGET}" "mkdir -p ~/speedcamera/headless" - -RSYNC_SSH="ssh" -for opt in "${SSH_OPTS[@]}"; do - RSYNC_SSH+=" $(printf "%q" "$opt")" -done - -rsync -avz --delete \ - -e "${RSYNC_SSH}" \ - --exclude 'node_modules' \ - --exclude '.git' \ - --exclude '*.log' \ - "${HEADLESS_DIR}/" "${PI_TARGET}:~/speedcamera/headless/" - -# 3. Update dependencies & restart service on Pi -echo "[3/3] Updating service on Pi..." -# Use -tt to force pseudo-terminal allocation so sudo can prompt for password interactively -ssh -tt "${SSH_OPTS[@]}" "${PI_TARGET}" "chmod +x ~/speedcamera/headless/scripts/*.sh && ~/speedcamera/headless/scripts/update-pi.sh ${INSTALL_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/scripts/install-remote.sh b/headless/scripts/install-remote.sh deleted file mode 100755 index ac4d472..0000000 --- a/headless/scripts/install-remote.sh +++ /dev/null @@ -1,142 +0,0 @@ -#!/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 -# bun run install:pi pi@raspberrypi.local - -PI_TARGET="pi@raspberrypi.local" -USE_PASSWORD=false -NETWORK_FLAG="" -PURGE_FIRST=false - -# Parse arguments -for arg in "$@"; do - case "$arg" in - --password|-p|--pass) - USE_PASSWORD=true - ;; - --field) - NETWORK_FLAG="--field" - ;; - --lan|--no-field|--skip-network) - NETWORK_FLAG="--skip-network" - ;; - --purge) - PURGE_FIRST=true - ;; - --help|-h) - echo "Speedcamera Headless 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 " --help, -h Show this help message" - echo "" - echo "Notes:" - echo " • The React frontend is built on this machine (fast: <2s) and synced to the Pi." - echo " • The Pi is never required to run slow Vite/React builds." - exit 0 - ;; - *) - if [[ "$arg" != -* ]]; then - PI_TARGET="$arg" - fi - ;; - esac -done - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -HEADLESS_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)" - -# 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 Remote Pi Fresh Installer" -echo " Target: ${PI_TARGET}" -echo "=========================================================" - -# 1. Build frontend bundle on local laptop -echo "[1/4] Building frontend bundle locally on host machine..." -cd "${HEADLESS_DIR}" -bun run build - -# 2. Test SSH connectivity -echo "[2/4] Connecting to ${PI_TARGET}..." -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 - -# 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 - -# 3. Sync repository & pre-built dist to Pi -echo "[3/4] Syncing application and pre-built frontend to Pi..." -ssh "${SSH_OPTS[@]}" "${PI_TARGET}" "mkdir -p ~/speedcamera/headless" - -RSYNC_SSH="ssh" -for opt in "${SSH_OPTS[@]}"; do - RSYNC_SSH+=" $(printf "%q" "$opt")" -done - -rsync -avz --delete \ - -e "${RSYNC_SSH}" \ - --exclude 'node_modules' \ - --exclude '.git' \ - --exclude '*.log' \ - "${HEADLESS_DIR}/" "${PI_TARGET}:~/speedcamera/headless/" - -# 4. Execute installer on Pi -echo "[4/4] Running system provisioning and service installation on Pi..." -REMOTE_CMD="chmod +x ~/speedcamera/headless/scripts/*.sh && ~/speedcamera/headless/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 Mode Active" - echo " • Web UI: http://${PI_TARGET#*@}:3000 (or http://raspberrypi.local:3000)" - echo " • Switch to field mode later: ssh ${PI_TARGET} '~/speedcamera/headless/scripts/setup-network.sh field'" -fi -echo "" -echo " View logs: ssh ${PI_TARGET} 'sudo journalctl -u speedcamera -f'" -echo "=========================================================" diff --git a/headless/scripts/install-rpi.sh b/headless/scripts/install-rpi.sh deleted file mode 100755 index 133d217..0000000 --- a/headless/scripts/install-rpi.sh +++ /dev/null @@ -1,229 +0,0 @@ -#!/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 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 - -for arg in "$@"; do - case "$arg" in - --skip-network|--app-only|--lan|--no-field) - SKIP_NETWORK=true - ;; - --field) - AUTO_FIELD=true - ;; - --network-only) - ONLY_NETWORK=true - ;; - --force-build) - FORCE_BUILD=true - ;; - --help|-h) - echo "Usage: $0 [options]" - echo "" - echo "Options:" - echo " --app-only, --skip-network, --lan Provision packages, Bun, dependencies, and service (keeps network)" - echo " --field Provision and immediately switch to Field Mode" - echo " --network-only Only configure dual-subnet network (Hotspot AP + Camera LAN)" - echo " --force-build Force Vite frontend build on Pi (NOT recommended: takes >20 mins)" - echo " --help, -h Show this help message" - exit 0 - ;; - esac -done - -# 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 -echo "[*] Checking internet connectivity..." -HAS_INTERNET=true -if ! ping -c 1 -W 2 1.1.1.1 &>/dev/null && ! curl -s --connect-timeout 2 https://bun.sh &>/dev/null; then - HAS_INTERNET=false - echo ">>> WARNING: No active internet connection detected on Pi!" - if [ ! -d "${PROJECT_DIR}/node_modules" ] && [ ! -f "${TARGET_HOME}/.bun/bin/bun" ]; then - echo "Error: Cannot proceed with initial setup without internet (missing node_modules or Bun)." >&2 - echo "Connect Pi to Wi-Fi/Ethernet with internet first." >&2 - exit 1 - fi -fi - -# 1. System packages -if [ "$HAS_INTERNET" = true ]; then - echo "[1/4] Installing system packages (libaravis, esptool, NetworkManager)..." - sudo apt-get update - sudo apt-get install -y \ - libaravis-0.8-0 \ - libaravis-dev \ - esptool \ - network-manager \ - curl \ - unzip \ - git \ - rsync -else - echo "[1/4] Skipping apt package updates (offline mode)." -fi - -# Apply GigE Vision socket buffer tuning (64MB) -echo "[*] Configuring Linux socket buffers for GigE camera..." -sudo bash -c 'cat > /etc/sysctl.d/60-gige-camera.conf </dev/null || sudo sysctl --system 2>/dev/null || true - -# 2. Check/Install Bun runtime -BUN_BIN=$(command -v bun || echo "${TARGET_HOME}/.bun/bin/bun") -if [ ! -x "${BUN_BIN}" ] && ! command -v bun &> /dev/null; then - if [ "$HAS_INTERNET" = true ]; then - echo "[2/4] Installing Bun runtime for ARM64..." - sudo -u "${TARGET_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 "Error: Bun not found and no internet connection to download it." >&2 - exit 1 - fi -else - export PATH="${TARGET_HOME}/.bun/bin:$PATH" - echo "[2/4] Bun runtime ready: ${BUN_BIN}" -fi - -# 3. Dependencies and frontend bundle check -echo "[3/4] Checking project dependencies & frontend bundle..." -cd "${PROJECT_DIR}" -if [ "$HAS_INTERNET" = true ]; then - sudo -u "${TARGET_USER}" env PATH="$PATH" "${BUN_BIN}" install --production -fi - -if [ -f "${PROJECT_DIR}/dist/index.html" ]; then - echo ">>> Verified pre-built frontend in dist/! (Built locally on dev host)" -elif [ "$FORCE_BUILD" = true ]; then - echo ">>> [!] WARNING: Building production frontend bundle on Pi..." - sudo -u "${TARGET_USER}" env PATH="$PATH" "${BUN_BIN}" run build -else - echo "=========================================================================" - echo " ERROR: Pre-built frontend bundle missing (${PROJECT_DIR}/dist/index.html)" - echo "=========================================================================" - echo " Building the React/Vite frontend directly on Raspberry Pi can take" - echo " over 20 minutes and exhausts Pi memory." - echo "" - echo " Recommended: Build frontend on your laptop and deploy using:" - echo " bun run install:pi ${TARGET_USER}@$(hostname).local" - echo " (or: bun run deploy:pi ${TARGET_USER}@$(hostname).local)" - echo "" - echo " If you truly want to build directly on the Pi, rerun with:" - echo " $0 --force-build" - echo "=========================================================================" - exit 1 -fi - -# 4. Systemd daemon installation -echo "[4/4] Configuring systemd autostart service..." -SERVICE_FILE="/etc/systemd/system/speedcamera.service" - -sudo bash -c "cat > ${SERVICE_FILE}" < Static IP 192.168.1.100 (GigE Camera LAN)" - echo " • Wi-Fi (wlan0) -> Standalone Hotspot AP 192.168.4.1 (SSID: speedcamera)" - echo "" - echo " WARNING: This will disconnect current Wi-Fi/SSH internet connection!" - echo "=========================================================================" - read -p "Switch to Standalone Field Mode now? (y/N) " -n 1 -r - echo "" - - if [[ $REPLY =~ ^[Yy]$ ]]; then - chmod +x "${PROJECT_DIR}/scripts/setup-network.sh" - "${PROJECT_DIR}/scripts/setup-network.sh" field - else - echo "Skipping Field Mode network switch for now." - echo "Run anytime later: ~/speedcamera/headless/scripts/setup-network.sh field" - fi -else - echo "Non-interactive session: Keeping existing network configuration." - echo "Switch to field mode when ready: ~/speedcamera/headless/scripts/setup-network.sh field" -fi diff --git a/headless/scripts/setup-network.sh b/headless/scripts/setup-network.sh deleted file mode 100755 index a253544..0000000 --- a/headless/scripts/setup-network.sh +++ /dev/null @@ -1,154 +0,0 @@ -#!/usr/bin/env bash -set -e - -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" ]; then - sudo -v || { echo "Error: Sudo privileges required to change network configuration." >&2; exit 1; } -fi - -case "$MODE" in - field|ap) - echo ">>> Applying FIELD MODE (Standalone Offline Dual-Subnet):" - echo " 1. Camera LAN (${ETH_IFACE}) -> Static IP 192.168.1.100/24" - echo " 2. Hotspot AP (${WIFI_IFACE}) -> Static IP 192.168.4.1/24 (SSID: speedcamera)" - echo " NOTE: In this mode, Pi operates standalone/offline." - echo "" - - # Apply GigE Vision kernel socket buffer optimizations - echo "[*] Applying GigE Vision network socket buffer optimizations (64MB)..." - sudo bash -c 'cat > /etc/sysctl.d/60-gige-camera.conf </dev/null || sudo sysctl --system 2>/dev/null || true - - # Configure Ethernet Camera LAN - echo "[1/2] Configuring Camera LAN on ${ETH_IFACE}..." - sudo nmcli connection delete "Speedcamera-CameraLAN" 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 - sudo nmcli connection up "Speedcamera-CameraLAN" 2>/dev/null || echo "Note: Ethernet link active when camera cable is connected." - - # Configure Wi-Fi Hotspot AP - echo "[2/2] Configuring Wi-Fi Hotspot AP on ${WIFI_IFACE}..." - SSID="speedcamera" - PASS="speedcamerapass" - sudo nmcli connection delete "Speedcamera-Hotspot" 2>/dev/null || true - sudo nmcli connection delete "Speedcamera-ClientWiFi" 2>/dev/null || true - sudo nmcli connection add type wifi \ - ifname "${WIFI_IFACE}" \ - con-name "Speedcamera-Hotspot" \ - autoconnect yes \ - ssid "${SSID}" \ - mode ap \ - 802-11-wireless.band bg \ - ipv4.method shared \ - ipv4.addresses 192.168.4.1/24 \ - wifi-sec.key-mgmt wpa-psk \ - wifi-sec.psk "${PASS}" - sudo nmcli connection up "Speedcamera-Hotspot" 2>/dev/null || echo "Note: Hotspot initialized." - - # Disable Wi-Fi power saving on AP interface to eliminate latency spikes and disconnects - echo "[*] Disabling Wi-Fi power saving on ${WIFI_IFACE}..." - sudo iw dev "${WIFI_IFACE}" set power_save off 2>/dev/null || sudo iwconfig "${WIFI_IFACE}" power off 2>/dev/null || true - - echo "" - echo "=========================================================" - echo " Field Mode Active!" - echo " • Wi-Fi Hotspot: SSID '${SSID}' (Password: '${PASS}')" - echo " • Web UI: http://192.168.4.1:3000" - echo " • Camera LAN: http://192.168.1.100:3000" - echo "=========================================================" - ;; - - internet|client|wifi) - WIFI_SSID="$2" - WIFI_PASS="$3" - if [ -z "$WIFI_SSID" ]; then - echo "Usage: $0 internet [Wi-Fi-Password]" - echo "Example: $0 internet MyHomeWiFi SecretPassword123" - exit 1 - fi - echo ">>> Switching to INTERNET / CLIENT MODE (for updates/provisioning)..." - echo " Connecting ${WIFI_IFACE} to Wi-Fi SSID: ${WIFI_SSID}" - - sudo nmcli connection delete "Speedcamera-Hotspot" 2>/dev/null || true - sudo nmcli connection delete "Speedcamera-ClientWiFi" 2>/dev/null || true - - if [ -n "$WIFI_PASS" ]; then - sudo nmcli dev wifi connect "${WIFI_SSID}" password "${WIFI_PASS}" ifname "${WIFI_IFACE}" name "Speedcamera-ClientWiFi" - else - sudo nmcli dev wifi connect "${WIFI_SSID}" ifname "${WIFI_IFACE}" name "Speedcamera-ClientWiFi" - fi - - echo "" - echo ">>> Checking internet connectivity..." - if ping -c 2 -W 3 1.1.1.1 &>/dev/null; then - echo " Connected to Internet successfully!" - else - echo " Wi-Fi connected, but ping to 1.1.1.1 failed. Check gateway/DNS." - fi - ;; - - dhcp|reset) - echo ">>> Reverting Ethernet and Wi-Fi to standard DHCP..." - 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 - 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 - echo "Interfaces set to standard DHCP." - ;; - - status) - echo "--- Active Network Connections ---" - nmcli connection show --active || true - echo "" - echo "--- IP Addresses ---" - ip -br addr show || true - 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 field mode or no route)" - fi - ;; - - *) - echo "Usage: $0 {field|internet|dhcp|status}" - echo "" - echo "Commands:" - echo " field Set Camera LAN (192.168.1.100) + Hotspot AP (192.168.4.1) [Offline]" - echo " internet [PASS] Connect Wi-Fi to home/lab router for updates [Online]" - echo " dhcp Reset ethernet & Wi-Fi to standard DHCP" - echo " status Check current IP addresses and connectivity" - exit 1 - ;; -esac diff --git a/headless/scripts/speedcamera.service b/headless/scripts/speedcamera.service deleted file mode 100644 index efd663d..0000000 --- a/headless/scripts/speedcamera.service +++ /dev/null @@ -1,23 +0,0 @@ -[Unit] -Description=Speedcamera Headless Daemon & Web Server -After=network.target network-online.target -Wants=network-online.target - -[Service] -Type=simple -User=pi -WorkingDirectory=/home/pi/speedcamera/headless -Environment=NODE_ENV=production -Environment=PORT=3000 -Environment=HOST=0.0.0.0 -Environment=DATA_DIR=/home/pi/.speedcamera -Environment=PATH=/home/pi/.bun/bin:/usr/local/bin:/usr/bin:/bin -ExecStart=/home/pi/.bun/bin/bun /home/pi/speedcamera/headless/src/server/index.ts -Restart=always -RestartSec=3 -KillSignal=SIGINT -LimitNOFILE=65536 -LimitMEMLOCK=infinity - -[Install] -WantedBy=multi-user.target diff --git a/headless/scripts/test-server.ts b/headless/scripts/test-server.ts deleted file mode 100644 index a8ec06d..0000000 --- a/headless/scripts/test-server.ts +++ /dev/null @@ -1,64 +0,0 @@ -import { spawn } from "child_process"; - -console.log("Starting speedcamera headless server in mock mode..."); -const proc = spawn("bun", ["src/server/index.ts"], { - cwd: process.cwd(), - env: { ...process.env, MOCK_MODE: "true", PORT: "3099" }, - stdio: "pipe", -}); - -proc.stdout?.on("data", (data) => console.log(`[server stdout] ${data}`)); -proc.stderr?.on("data", (data) => console.error(`[server stderr] ${data}`)); - -// Wait 1s for server to start -await new Promise((r) => setTimeout(r, 1200)); - -try { - // 1. Test Health endpoint - console.log("Testing GET http://localhost:3099/api/health ..."); - const healthRes = await fetch("http://localhost: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 SPA index.html - console.log("Testing GET http://localhost:3099/ ..."); - const indexRes = await fetch("http://localhost:3099/"); - const indexHtml = await indexRes.text(); - if (!indexHtml.includes("")) throw new Error("SPA index.html not served"); - console.log("SPA index.html served correctly! Length:", indexHtml.length); - - // 3. Test WebSocket RPC - console.log("Testing WebSocket RPC on ws://localhost:3099/ws/rpc ..."); - const ws = new WebSocket("ws://localhost:3099/ws/rpc"); - - await new Promise((resolve, reject) => { - ws.onopen = () => { - console.log("WebSocket connected successfully!"); - // Send RPC request for getSettings - ws.send(JSON.stringify({ id: 1, method: "getSettings", params: {} })); - }; - - ws.onmessage = (event) => { - console.log("WS message received:", event.data); - const data = JSON.parse(event.data); - if (data.id === 1) { - console.log("RPC getSettings result:", data.result); - if (data.result && typeof data.result.maxSpeed === "number") { - console.log("SUCCESS: Settings RPC validated!"); - resolve(); - } else { - reject(new Error("Unexpected RPC response")); - } - } - }; - - ws.onerror = (err) => reject(err); - setTimeout(() => reject(new Error("WS Timeout")), 5000); - }); - - console.log("ALL TESTS PASSED SUCCESSFULLY!"); -} finally { - proc.kill(); -} -process.exit(0); diff --git a/headless/scripts/update-pi.sh b/headless/scripts/update-pi.sh deleted file mode 100755 index eb2fd59..0000000 --- a/headless/scripts/update-pi.sh +++ /dev/null @@ -1,89 +0,0 @@ -#!/usr/bin/env bash -set -e - -FORCE_INSTALL=false - -for arg in "$@"; do - case "$arg" in - --install|-i) - FORCE_INSTALL=true - ;; - esac -done - -TARGET_USER="${SUDO_USER:-$(whoami)}" -TARGET_HOME=$(getent passwd "$TARGET_USER" | cut -d: -f6) -export PATH="${TARGET_HOME}/.bun/bin:/usr/local/bin:/usr/bin:$PATH" -PROJECT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -cd "${PROJECT_DIR}" - -# 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 configure services." >&2; exit 1; } - -# Check internet availability -HAS_NET=false -if ping -c 1 -W 2 1.1.1.1 &>/dev/null; then - HAS_NET=true -fi - -BUN_BIN=$(command -v bun || echo "${TARGET_HOME}/.bun/bin/bun") - -if [ "${FORCE_INSTALL}" = true ]; then - echo "[*] Force install requested: running bun install..." - sudo -u "${TARGET_USER}" env PATH="$PATH" "${BUN_BIN}" install --production -elif [ ! -d "node_modules" ]; then - if [ "$HAS_NET" = true ]; then - echo "[*] Initial dependencies missing: running bun install..." - sudo -u "${TARGET_USER}" env PATH="$PATH" "${BUN_BIN}" install --production - else - echo ">>> WARNING: node_modules missing and Pi has no internet access." - echo ">>> Connect Pi to home Wi-Fi to install dependencies: ./scripts/setup-network.sh internet " - fi -elif [ "$HAS_NET" = true ]; then - if [ "package.json" -nt "node_modules" ]; then - echo "[*] package.json updated: updating production dependencies..." - sudo -u "${TARGET_USER}" env PATH="$PATH" "${BUN_BIN}" install --production - fi -else - echo "[*] Pi in offline mode: skipping package updates (existing dependencies reused)." -fi - -# 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 Headless Daemon & Web Server -After=network.target network-online.target -Wants=network-online.target - -[Service] -Type=simple -User=${TARGET_USER} -WorkingDirectory=${PROJECT_DIR} -Environment=NODE_ENV=production -Environment=PORT=3000 -Environment=HOST=0.0.0.0 -Environment=DATA_DIR=${TARGET_HOME}/.speedcamera -Environment=PATH=${TARGET_HOME}/.bun/bin:/usr/local/bin:/usr/bin:/bin -ExecStart=${BUN_BIN} ${PROJECT_DIR}/src/server/index.ts -Restart=always -RestartSec=3 -KillSignal=SIGINT -LimitNOFILE=65536 - -[Install] -WantedBy=multi-user.target -SERVICE_EOF - sudo systemctl daemon-reload - sudo systemctl enable speedcamera.service -fi - -echo "[*] Restarting speedcamera service..." -sudo systemctl daemon-reload -sudo systemctl restart speedcamera.service -sleep 1 -sudo systemctl status speedcamera --no-pager diff --git a/headless/scripts/verify-ws.ts b/headless/scripts/verify-ws.ts deleted file mode 100644 index 3ebfdf5..0000000 --- a/headless/scripts/verify-ws.ts +++ /dev/null @@ -1,54 +0,0 @@ -console.log("Connecting to WebSocket on ws://127.0.0.1:3099/ws/rpc ..."); -const ws = new WebSocket("ws://127.0.0.1:3099/ws/rpc"); - -let receivedCameraPush = false; -let receivedSettingsResponse = false; -let receivedViolationsResponse = false; - -ws.onopen = () => { - console.log("[WS] Connected to Speedcamera Headless Daemon!"); - // 1. Request getSettings - ws.send(JSON.stringify({ id: 101, method: "getSettings", params: {} })); - // 2. Request getViolations - ws.send(JSON.stringify({ id: 102, method: "getViolations", params: { page: 1, limit: 10 } })); -}; - -ws.onmessage = (event) => { - console.log("[WS] Message received:", event.data); - const data = JSON.parse(event.data); - - if (data.event === "cameraStatus") { - receivedCameraPush = true; - console.log("-> Push message 'cameraStatus' verified!"); - } - - if (data.id === 101) { - if (data.result && typeof data.result.maxSpeed === "number") { - receivedSettingsResponse = true; - console.log("-> RPC 'getSettings' verified! Max speed:", data.result.maxSpeed); - } - } - - if (data.id === 102) { - if (data.result && Array.isArray(data.result.violations)) { - receivedViolationsResponse = true; - console.log("-> RPC 'getViolations' verified! Total violations:", data.result.total); - } - } - - if (receivedCameraPush && receivedSettingsResponse && receivedViolationsResponse) { - console.log("\n>>> ALL WEBSOCKET RPC CHECKS PASSED PERFECTLY! <<<"); - ws.close(); - process.exit(0); - } -}; - -ws.onerror = (err) => { - console.error("WS error:", err); - process.exit(1); -}; - -setTimeout(() => { - console.error("Test timeout after 5s"); - process.exit(1); -}, 5000); diff --git a/headless/src/bun-serialport.d.ts b/headless/src/bun-serialport.d.ts deleted file mode 100644 index 07e454f..0000000 --- a/headless/src/bun-serialport.d.ts +++ /dev/null @@ -1,43 +0,0 @@ -declare module "bun-serialport" { - export interface PortInfo { - path: string; - manufacturer?: string; - serialNumber?: string; - pnpId?: string; - locationId?: string; - productId?: string; - vendorId?: string; - } - - export interface SerialPortOptions { - path: string; - baudRate?: number; - dataBits?: 5 | 6 | 7 | 8; - stopBits?: 1 | 2; - parity?: "none" | "even" | "mark" | "odd" | "space"; - autoOpen?: boolean; - } - - export class SerialPort { - constructor(options: SerialPortOptions); - readonly isOpen: boolean; - readonly path: string; - readonly baudRate: number; - open(): Promise; - close(): Promise; - write(data: string | Uint8Array | Buffer): Promise; - flush(): Promise; - drain(): Promise; - pipe(destination: T): T; - on(event: "data", listener: (chunk: Buffer) => void): this; - on(event: "error", listener: (error: Error) => void): this; - on(event: "close", listener: () => void): this; - on(event: "open", listener: () => void): this; - once(event: string, listener: (...args: any[]) => void): this; - off(event: string, listener: (...args: any[]) => void): this; - removeAllListeners(event?: string): this; - } - - export function list(): Promise; - export function readlineParser(options?: { delimiter?: string | Buffer | Uint8Array; encoding?: BufferEncoding }): any; -} diff --git a/headless/src/components/ArmingButton.tsx b/headless/src/components/ArmingButton.tsx deleted file mode 100644 index 071b056..0000000 --- a/headless/src/components/ArmingButton.tsx +++ /dev/null @@ -1,237 +0,0 @@ -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 setSystemState = useAppStore((s) => s.setSystemState); - 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); - setSystemState("ARMED"); - return; - } - - if (p < 1) { - rafRef.current = requestAnimationFrame(tick); - } - }; - - rafRef.current = requestAnimationFrame(tick); - }, [systemState, setSystemState]); - - 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") { - setSystemState("DISARMED"); - } - }, [systemState, setSystemState]); - - // 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/src/components/ErrorBoundary.tsx b/headless/src/components/ErrorBoundary.tsx deleted file mode 100644 index ac8984f..0000000 --- a/headless/src/components/ErrorBoundary.tsx +++ /dev/null @@ -1,60 +0,0 @@ -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/src/components/FirmwareFlasher.tsx b/headless/src/components/FirmwareFlasher.tsx deleted file mode 100644 index 50db99b..0000000 --- a/headless/src/components/FirmwareFlasher.tsx +++ /dev/null @@ -1,363 +0,0 @@ -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/src/components/LapImageThumbnails.tsx b/headless/src/components/LapImageThumbnails.tsx deleted file mode 100644 index 04f2b89..0000000 --- a/headless/src/components/LapImageThumbnails.tsx +++ /dev/null @@ -1,92 +0,0 @@ -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. - * Fetches image data lazily via the RPC and cancels pending fetches on unmount. - */ -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); - if (startImagePath) { - getRpc() - .request.getImageData({ imagePath: startImagePath }) - .then((data) => { if (!cancelled) setStartImageUrl(data); }) - .catch(() => {}); - } - if (endImagePath) { - getRpc() - .request.getImageData({ imagePath: endImagePath }) - .then((data) => { if (!cancelled) setEndImageUrl(data); }) - .catch(() => {}); - } - return () => { cancelled = true; }; - }, [startImagePath, endImagePath]); - - return ( - <> -
- {(startImageUrl || endImageUrl) ? ( - <> - {startImageUrl && ( - - )} - {endImageUrl && ( - - )} - - ) : ( - — - )} - {trailing} -
- - !open && setLightboxUrl(null)}> - - {lightboxUrl && ( - Lap capture - )} - - - - ); -} diff --git a/headless/src/components/LapTimerDisplay.tsx b/headless/src/components/LapTimerDisplay.tsx deleted file mode 100644 index 6d46702..0000000 --- a/headless/src/components/LapTimerDisplay.tsx +++ /dev/null @@ -1,113 +0,0 @@ -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/src/components/LastCapturedImage.tsx b/headless/src/components/LastCapturedImage.tsx deleted file mode 100644 index 42dd6d0..0000000 --- a/headless/src/components/LastCapturedImage.tsx +++ /dev/null @@ -1,48 +0,0 @@ -import { useEffect, useState } from "react"; -import { getRpc } from "@/lib/rpc"; -import { useAppStore } from "@/stores/useAppStore"; -import { Image as ImageIcon } from "lucide-react"; - -export function LastCapturedImage() { - const lastViolation = useAppStore((s) => s.lastViolation); - const [imageSrc, setImageSrc] = useState(null); - - useEffect(() => { - if (lastViolation) { - getRpc().request.getImageData({ imagePath: lastViolation.imagePath }).then(setImageSrc).catch(() => setImageSrc(null)); - } else { - setImageSrc(null); - } - }, [lastViolation]); - - return ( -
- {imageSrc ? ( - Last capture - ) : ( -
- -

Awaiting Capture

-
- )} - - {lastViolation && ( -
- - {new Date(lastViolation.timestamp).toLocaleTimeString()} - -
- - {lastViolation.measuredSpeed} - - km/h -
-
- )} -
- ); -} diff --git a/headless/src/components/NavigationMenu.tsx b/headless/src/components/NavigationMenu.tsx deleted file mode 100644 index 72efed8..0000000 --- a/headless/src/components/NavigationMenu.tsx +++ /dev/null @@ -1,73 +0,0 @@ -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"; - -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/src/components/StatusBadge.tsx b/headless/src/components/StatusBadge.tsx deleted file mode 100644 index 1117706..0000000 --- a/headless/src/components/StatusBadge.tsx +++ /dev/null @@ -1,46 +0,0 @@ -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/src/components/ThemeToggle.tsx b/headless/src/components/ThemeToggle.tsx deleted file mode 100644 index 304782e..0000000 --- a/headless/src/components/ThemeToggle.tsx +++ /dev/null @@ -1,29 +0,0 @@ -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/src/components/ViolationCard.tsx b/headless/src/components/ViolationCard.tsx deleted file mode 100644 index 5b92539..0000000 --- a/headless/src/components/ViolationCard.tsx +++ /dev/null @@ -1,140 +0,0 @@ -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); - - getRpc() - .request.getImageData({ imagePath: violation.imagePath }) - .then((data) => { - if (!cancelled) setImageData(data); - }) - .catch(() => { - if (!cancelled) setImageData(null); - }) - .finally(() => { - if (!cancelled) setImageLoading(false); - }); - - return () => { - cancelled = true; - }; - }, [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/src/components/ui/badge.tsx b/headless/src/components/ui/badge.tsx deleted file mode 100644 index f428bc5..0000000 --- a/headless/src/components/ui/badge.tsx +++ /dev/null @@ -1,49 +0,0 @@ -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/src/components/ui/button.tsx b/headless/src/components/ui/button.tsx deleted file mode 100644 index 652d5d3..0000000 --- a/headless/src/components/ui/button.tsx +++ /dev/null @@ -1,65 +0,0 @@ -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/src/components/ui/card.tsx b/headless/src/components/ui/card.tsx deleted file mode 100644 index 593879d..0000000 --- a/headless/src/components/ui/card.tsx +++ /dev/null @@ -1,100 +0,0 @@ -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/src/components/ui/checkbox.tsx b/headless/src/components/ui/checkbox.tsx deleted file mode 100644 index 3eb403b..0000000 --- a/headless/src/components/ui/checkbox.tsx +++ /dev/null @@ -1,31 +0,0 @@ -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/src/components/ui/collapsible.tsx b/headless/src/components/ui/collapsible.tsx deleted file mode 100644 index 63fc8ef..0000000 --- a/headless/src/components/ui/collapsible.tsx +++ /dev/null @@ -1,31 +0,0 @@ -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/src/components/ui/dialog.tsx b/headless/src/components/ui/dialog.tsx deleted file mode 100644 index 545c411..0000000 --- a/headless/src/components/ui/dialog.tsx +++ /dev/null @@ -1,166 +0,0 @@ -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/src/components/ui/input.tsx b/headless/src/components/ui/input.tsx deleted file mode 100644 index e49996f..0000000 --- a/headless/src/components/ui/input.tsx +++ /dev/null @@ -1,19 +0,0 @@ -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/src/components/ui/label.tsx b/headless/src/components/ui/label.tsx deleted file mode 100644 index f752f82..0000000 --- a/headless/src/components/ui/label.tsx +++ /dev/null @@ -1,22 +0,0 @@ -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/src/components/ui/progress.tsx b/headless/src/components/ui/progress.tsx deleted file mode 100644 index 0bcb123..0000000 --- a/headless/src/components/ui/progress.tsx +++ /dev/null @@ -1,29 +0,0 @@ -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/src/components/ui/scroll-area.tsx b/headless/src/components/ui/scroll-area.tsx deleted file mode 100644 index f49b0a8..0000000 --- a/headless/src/components/ui/scroll-area.tsx +++ /dev/null @@ -1,53 +0,0 @@ -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/src/components/ui/select.tsx b/headless/src/components/ui/select.tsx deleted file mode 100644 index f3b0139..0000000 --- a/headless/src/components/ui/select.tsx +++ /dev/null @@ -1,192 +0,0 @@ -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/src/components/ui/skeleton.tsx b/headless/src/components/ui/skeleton.tsx deleted file mode 100644 index ed70d9e..0000000 --- a/headless/src/components/ui/skeleton.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import { cn } from "@/lib/utils"; - -function Skeleton({ className, ...props }: React.HTMLAttributes) { - return ( -
- ); -} - -export { Skeleton }; diff --git a/headless/src/components/ui/slider.tsx b/headless/src/components/ui/slider.tsx deleted file mode 100644 index 5a4db16..0000000 --- a/headless/src/components/ui/slider.tsx +++ /dev/null @@ -1,57 +0,0 @@ -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/src/components/ui/sonner.tsx b/headless/src/components/ui/sonner.tsx deleted file mode 100644 index bd6eb71..0000000 --- a/headless/src/components/ui/sonner.tsx +++ /dev/null @@ -1,48 +0,0 @@ -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/src/components/ui/switch.tsx b/headless/src/components/ui/switch.tsx deleted file mode 100644 index 134e8e2..0000000 --- a/headless/src/components/ui/switch.tsx +++ /dev/null @@ -1,31 +0,0 @@ -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/src/components/ui/toggle-group.tsx b/headless/src/components/ui/toggle-group.tsx deleted file mode 100644 index f62c08c..0000000 --- a/headless/src/components/ui/toggle-group.tsx +++ /dev/null @@ -1,89 +0,0 @@ -"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/src/components/ui/toggle.tsx b/headless/src/components/ui/toggle.tsx deleted file mode 100644 index 15b3df4..0000000 --- a/headless/src/components/ui/toggle.tsx +++ /dev/null @@ -1,45 +0,0 @@ -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/src/hooks/useLiveLapTimer.ts b/headless/src/hooks/useLiveLapTimer.ts deleted file mode 100644 index f2d4171..0000000 --- a/headless/src/hooks/useLiveLapTimer.ts +++ /dev/null @@ -1,27 +0,0 @@ -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/src/hooks/useSystemStateSync.ts b/headless/src/hooks/useSystemStateSync.ts deleted file mode 100644 index bbc7915..0000000 --- a/headless/src/hooks/useSystemStateSync.ts +++ /dev/null @@ -1,31 +0,0 @@ -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 connectedPort = useAppStore((s) => s.connectedPort); - const cameraConnected = useAppStore((s) => s.cameraConnected); - - const conditionsMet = !!connectedPort && cameraConnected; - - useEffect(() => { - if (conditionsMet) { - if (systemState === "PASSIVE") { - setSystemState("DISARMED"); - } - } else { - if (systemState !== "PASSIVE") { - setSystemState("PASSIVE"); - } - } - }, [conditionsMet, systemState, setSystemState]); -} diff --git a/headless/src/lib/format.ts b/headless/src/lib/format.ts deleted file mode 100644 index e2ebb7d..0000000 --- a/headless/src/lib/format.ts +++ /dev/null @@ -1,26 +0,0 @@ -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/src/lib/rpc.ts b/headless/src/lib/rpc.ts deleted file mode 100644 index 2d544a6..0000000 --- a/headless/src/lib/rpc.ts +++ /dev/null @@ -1,173 +0,0 @@ -import type { SpeedcameraRPC } from "@/shared/types"; -import { useAppStore } from "@/stores/useAppStore"; - -type RequestMap = SpeedcameraRPC["bun"]["requests"]; -type PushMessageMap = SpeedcameraRPC["webview"]["messages"]; - -export type SpeedcameraClientRPC = { - request: { - [K in keyof RequestMap]: ( - params: RequestMap[K]["params"] - ) => Promise; - }; -}; - -class WebSocketRpcClient { - private ws: WebSocket | null = null; - private reqIdCounter = 0; - private pendingRequests = new Map< - string | number, - { - resolve: (val: any) => void; - reject: (err: any) => void; - timer: ReturnType; - } - >(); - private reconnectTimeout: ReturnType | null = null; - private isConnecting = false; - - constructor() { - this.connect(); - } - - private getWebSocketUrl(): string { - if (typeof window === "undefined") return "ws://127.0.0.1:3000/ws/rpc"; - const protocol = window.location.protocol === "https:" ? "wss:" : "ws:"; - const host = window.location.host; // includes port (e.g. localhost:5173 or 192.168.4.1:3000) - return `${protocol}//${host}/ws/rpc`; - } - - private connect() { - if (typeof window === "undefined" || this.isConnecting) return; - this.isConnecting = true; - - try { - const url = this.getWebSocketUrl(); - const ws = new WebSocket(url); - this.ws = ws; - - ws.onopen = () => { - console.log("[rpc-client] Connected to speedcamera daemon"); - this.isConnecting = false; - }; - - ws.onmessage = (event) => { - try { - const data = JSON.parse(event.data); - - // Case 1: Response to a pending request - if (data.id !== undefined && this.pendingRequests.has(data.id)) { - const pending = this.pendingRequests.get(data.id)!; - this.pendingRequests.delete(data.id); - clearTimeout(pending.timer); - - if (data.error) { - pending.reject(new Error(data.error)); - } else { - pending.resolve(data.result); - } - return; - } - - // Case 2: Server push broadcast event - if (data.event) { - this.handlePushEvent(data.event as keyof PushMessageMap, data.payload); - return; - } - } catch (err) { - console.error("[rpc-client] Error handling message:", err); - } - }; - - ws.onerror = (err) => { - console.warn("[rpc-client] WebSocket error:", err); - }; - - ws.onclose = () => { - console.log("[rpc-client] Disconnected. Reconnecting in 2s..."); - this.isConnecting = false; - this.ws = null; - if (!this.reconnectTimeout) { - this.reconnectTimeout = setTimeout(() => { - this.reconnectTimeout = null; - this.connect(); - }, 2000); - } - }; - } catch (err) { - this.isConnecting = false; - console.error("[rpc-client] Connection failed:", err); - } - } - - private handlePushEvent(event: K, payload: PushMessageMap[K]) { - const store = useAppStore.getState(); - switch (event) { - case "serialStatus": - store.handleSerialStatus(payload as any); - break; - case "flashProgress": - store.handleFlashProgress(payload as any); - break; - case "cameraStatus": - store.setCameraStatus(payload as any); - break; - case "liveFrame": - store.setLiveFrame(payload as any); - break; - case "updateAvailable": - store.setUpdateVersion((payload as any).version); - store.setUpdatePhase("ready"); - break; - case "updateProgress": - store.handleUpdateProgress(payload as any); - break; - default: - break; - } - } - - public call(method: string, params: any): Promise { - return new Promise((resolve, reject) => { - const id = ++this.reqIdCounter; - const timer = setTimeout(() => { - if (this.pendingRequests.has(id)) { - this.pendingRequests.delete(id); - reject(new Error(`RPC request '${method}' timed out after 10000ms`)); - } - }, 10000); - - this.pendingRequests.set(id, { resolve, reject, timer }); - - if (this.ws && this.ws.readyState === WebSocket.OPEN) { - this.ws.send(JSON.stringify({ id, method, params })); - } else { - // If websocket not ready yet, wait briefly or connect - const checkInterval = setInterval(() => { - if (this.ws && this.ws.readyState === WebSocket.OPEN) { - clearInterval(checkInterval); - this.ws.send(JSON.stringify({ id, method, params })); - } - }, 100); - - // Cancel retry if request times out - setTimeout(() => clearInterval(checkInterval), 9500); - } - }); - } -} - -const client = new WebSocketRpcClient(); - -// Proxy accessor so `getRpc().request.someMethod(params)` works transparently -const rpcProxy: SpeedcameraClientRPC = { - request: new Proxy({} as any, { - get(_target, prop: string) { - return (params: any = {}) => client.call(prop, params); - }, - }), -}; - -export function getRpc(): SpeedcameraClientRPC { - return rpcProxy; -} diff --git a/headless/src/lib/sound.ts b/headless/src/lib/sound.ts deleted file mode 100644 index 5e3aaf8..0000000 --- a/headless/src/lib/sound.ts +++ /dev/null @@ -1,44 +0,0 @@ -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/src/lib/utils.ts b/headless/src/lib/utils.ts deleted file mode 100644 index a5ef193..0000000 --- a/headless/src/lib/utils.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { clsx, type ClassValue } from "clsx"; -import { twMerge } from "tailwind-merge"; - -export function cn(...inputs: ClassValue[]) { - return twMerge(clsx(inputs)); -} diff --git a/headless/src/mainview/App.tsx b/headless/src/mainview/App.tsx deleted file mode 100644 index ffaa34b..0000000 --- a/headless/src/mainview/App.tsx +++ /dev/null @@ -1,46 +0,0 @@ -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/src/mainview/index.css b/headless/src/mainview/index.css deleted file mode 100644 index 805a3da..0000000 --- a/headless/src/mainview/index.css +++ /dev/null @@ -1,135 +0,0 @@ -@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; - } -} \ No newline at end of file diff --git a/headless/src/mainview/index.html b/headless/src/mainview/index.html deleted file mode 100644 index a174d4c..0000000 --- a/headless/src/mainview/index.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - React + Tailwind + Vite - - -
- - - diff --git a/headless/src/mainview/main.tsx b/headless/src/mainview/main.tsx deleted file mode 100644 index 07c9565..0000000 --- a/headless/src/mainview/main.tsx +++ /dev/null @@ -1,13 +0,0 @@ -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/src/routes/__root.tsx b/headless/src/routes/__root.tsx deleted file mode 100644 index c077548..0000000 --- a/headless/src/routes/__root.tsx +++ /dev/null @@ -1,40 +0,0 @@ -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"; - -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); - - useEffect(() => { - void loadLapSettings(); - void loadTeableState(); - void refreshCameraStatus(); - }, [loadLapSettings, loadTeableState, refreshCameraStatus]); - - return ( -
- {/* App-level navigation bar */} -
- -
- -
-
- - {/* Page content */} -
- -
-
- ); -} diff --git a/headless/src/routes/about.tsx b/headless/src/routes/about.tsx deleted file mode 100644 index 4c411da..0000000 --- a/headless/src/routes/about.tsx +++ /dev/null @@ -1,264 +0,0 @@ -import { createRoute } from "@tanstack/react-router"; -import { RootRoute } from "./__root"; -import { Button } from "@/components/ui/button"; -import { useEffect, useState, useCallback } from "react"; -import { toast } from "sonner"; -import { HugeiconsIcon } from "@hugeicons/react"; -import { - DownloadCircle02Icon, - RefreshIcon, - Cancel01Icon, - Alert02Icon, - CheckmarkCircle02Icon, -} from "@hugeicons/core-free-icons"; -import { getRpc } from "@/lib/rpc"; -import { useAppStore } from "@/stores/useAppStore"; - -const GITHUB_URL = "https://github.com/LeoLTM/speedcamera"; - -export const AboutRoute = createRoute({ - getParentRoute: () => RootRoute, - path: "/about", - component: AboutPage, -}); - -function AboutPage() { - const [localVersion, setLocalVersion] = useState<{ - version: string; - channel: string; - hash: string; - } | null>(null); - const [versionLoading, setVersionLoading] = useState(true); - - const updatePhase = useAppStore((s) => s.updatePhase); - const updateMessage = useAppStore((s) => s.updateMessage); - const updateProgress = useAppStore((s) => s.updateProgress); - const updateVersion = useAppStore((s) => s.updateVersion); - const updateError = useAppStore((s) => s.updateError); - const resetUpdater = useAppStore((s) => s.resetUpdater); - const setUpdatePhase = useAppStore((s) => s.setUpdatePhase); - const setUpdateVersion = useAppStore((s) => s.setUpdateVersion); - const setUpdateError = useAppStore((s) => s.setUpdateError); - - const handleOpenGitHub = () => { - window.open(GITHUB_URL, "_blank", "noopener,noreferrer"); - }; - - // Load local version on mount - useEffect(() => { - getRpc() - .request.getLocalVersion({}) - .then((info) => setLocalVersion(info)) - .catch(() => setLocalVersion(null)) - .finally(() => setVersionLoading(false)); - }, []); - - const handleCheckForUpdate = useCallback(async () => { - resetUpdater(); - setUpdatePhase("checking"); - try { - const info = await getRpc().request.checkForUpdate({}); - if (info.error) { - setUpdateError(info.error); - setUpdatePhase("error"); - toast.error(info.error); - return; - } - if (info.updateAvailable) { - setUpdateVersion(info.version); - toast.info(`Update available: v${info.version}`); - } else { - setUpdatePhase("idle"); - toast.success("You're on the latest version"); - } - } catch (err) { - const msg = err instanceof Error ? err.message : String(err); - setUpdateError(msg); - setUpdatePhase("error"); - toast.error(`Update check failed: ${msg}`); - } - }, [resetUpdater, setUpdatePhase, setUpdateError, setUpdateVersion]); - - const handleDownloadUpdate = useCallback(async () => { - setUpdatePhase("downloading"); - setUpdateError(null); - try { - const result = await getRpc().request.downloadUpdate({}); - if (!result.ok) { - setUpdateError(result.error ?? "Download failed"); - setUpdatePhase("error"); - toast.error(result.error ?? "Download failed"); - return; - } - setUpdatePhase("ready"); - toast.success("Update downloaded — ready to install"); - } catch (err) { - const msg = err instanceof Error ? err.message : String(err); - setUpdateError(msg); - setUpdatePhase("error"); - toast.error(`Download failed: ${msg}`); - } - }, [setUpdatePhase, setUpdateError]); - - const handleApplyUpdate = useCallback(async () => { - try { - await getRpc().request.applyUpdate({}); - // App quits + relaunches; this line may not run - } catch (err) { - const msg = err instanceof Error ? err.message : String(err); - toast.error(`Failed to apply update: ${msg}`); - } - }, []); - - const isBusy = updatePhase === "checking" || updatePhase === "downloading"; - const canDownload = updateVersion !== null && updatePhase !== "downloading" && updatePhase !== "ready"; - const canApply = updatePhase === "ready"; - - return ( -
-
-
-

Speedcamera

-

- Companion app for the ESP32-based speed camera -

-
- -
-
- Version - - {versionLoading - ? "…" - : localVersion - ? `v${localVersion.version}` - : "unknown"} - -
-
- Channel - - {localVersion?.channel ?? "—"} - -
-
- Build hash - - {localVersion?.hash?.slice(0, 8) ?? "—"} - -
-
- Runtime - Electrobun + Bun -
-
- UI - React + shadcn/ui -
-
- - {/* ── 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/src/routes/index.tsx b/headless/src/routes/index.tsx deleted file mode 100644 index 4560f2d..0000000 --- a/headless/src/routes/index.tsx +++ /dev/null @@ -1,129 +0,0 @@ -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/src/routes/laps.tsx b/headless/src/routes/laps.tsx deleted file mode 100644 index 6d458a4..0000000 --- a/headless/src/routes/laps.tsx +++ /dev/null @@ -1,44 +0,0 @@ -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/src/routes/laps/HistoryTab.tsx b/headless/src/routes/laps/HistoryTab.tsx deleted file mode 100644 index e99400b..0000000 --- a/headless/src/routes/laps/HistoryTab.tsx +++ /dev/null @@ -1,110 +0,0 @@ -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/src/routes/laps/LapRow.tsx b/headless/src/routes/laps/LapRow.tsx deleted file mode 100644 index 7ad4a96..0000000 --- a/headless/src/routes/laps/LapRow.tsx +++ /dev/null @@ -1,103 +0,0 @@ -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/src/routes/laps/LiveSessionTab.tsx b/headless/src/routes/laps/LiveSessionTab.tsx deleted file mode 100644 index 5e52f5f..0000000 --- a/headless/src/routes/laps/LiveSessionTab.tsx +++ /dev/null @@ -1,195 +0,0 @@ -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/src/routes/laps/SessionCard.tsx b/headless/src/routes/laps/SessionCard.tsx deleted file mode 100644 index e1b74bb..0000000 --- a/headless/src/routes/laps/SessionCard.tsx +++ /dev/null @@ -1,115 +0,0 @@ -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/src/routes/settings.tsx b/headless/src/routes/settings.tsx deleted file mode 100644 index 1efef51..0000000 --- a/headless/src/routes/settings.tsx +++ /dev/null @@ -1,58 +0,0 @@ -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 { 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", "camera", "speed-camera", "lap-timer"] as const).map((tab) => ( - - {tab === "device" - ? "Device" - : tab === "camera" - ? "Camera" - : tab === "speed-camera" - ? "Speed Camera" - : "Lap Timer"} - - ))} - - - - - - - - - - - - - - - -
- ); -} diff --git a/headless/src/routes/settings/CameraTab.tsx b/headless/src/routes/settings/CameraTab.tsx deleted file mode 100644 index f206ed6..0000000 --- a/headless/src/routes/settings/CameraTab.tsx +++ /dev/null @@ -1,424 +0,0 @@ -import { useState, useEffect } from "react"; -import type { ChangeEvent } from "react"; -import { toast } from "sonner"; -import { useAppStore } from "@/stores/useAppStore"; -import type { HwControl, SystemNetworkSummary } from "@/shared/types"; -import { getRpc } from "@/lib/rpc"; -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, Network } 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} -
-
- ); -} - -function NetworkStatusSection() { - const [network, setNetwork] = useState(null); - const [loading, setLoading] = useState(false); - - const fetchNetwork = () => { - setLoading(true); - getRpc() - .request.getNetworkInfo({}) - .then(setNetwork) - .catch(() => {}) - .finally(() => setLoading(false)); - }; - - useEffect(() => { - fetchNetwork(); - }, []); - - if (!network) return null; - - return ( -
-
-

- - Network & Subnet Architecture -

- -
- -
- {/* Camera LAN */} -
-
- Camera LAN (eth0) - {network.cameraLan.status === "ok" ? ( - 192.168.1.100 OK - ) : network.cameraLan.status === "ip_mismatch" ? ( - {network.cameraLan.ip || "Mismatch"} - ) : ( - Not Found - )} -
-
-
IP: {network.cameraLan.ip || "Unassigned"}
-
Subnet: {network.cameraLan.subnet}
-
-

- Dedicated interface for GigE Vision camera streaming. -

-
- - {/* Wi-Fi Hotspot */} -
-
- Hotspot AP (wlan0) - {network.hotspotAp.status === "ok" ? ( - 192.168.4.1 OK - ) : network.hotspotAp.status === "ip_mismatch" ? ( - {network.hotspotAp.ip} - ) : ( - Inactive - )} -
-
-
IP: {network.hotspotAp.ip || "Unassigned"}
-
Web UI: :3000
-
-

- Wi-Fi access point for remote browser controller. -

-
-
-
- ); -} - diff --git a/headless/src/routes/settings/DeviceTab.tsx b/headless/src/routes/settings/DeviceTab.tsx deleted file mode 100644 index ef53260..0000000 --- a/headless/src/routes/settings/DeviceTab.tsx +++ /dev/null @@ -1,236 +0,0 @@ -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/src/routes/settings/LapTimerTab.tsx b/headless/src/routes/settings/LapTimerTab.tsx deleted file mode 100644 index 6cb860c..0000000 --- a/headless/src/routes/settings/LapTimerTab.tsx +++ /dev/null @@ -1,119 +0,0 @@ -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/src/routes/settings/SpeedCameraTab.tsx b/headless/src/routes/settings/SpeedCameraTab.tsx deleted file mode 100644 index 18ded97..0000000 --- a/headless/src/routes/settings/SpeedCameraTab.tsx +++ /dev/null @@ -1,263 +0,0 @@ -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/src/routes/setup.tsx b/headless/src/routes/setup.tsx deleted file mode 100644 index f71136b..0000000 --- a/headless/src/routes/setup.tsx +++ /dev/null @@ -1,97 +0,0 @@ -import { useEffect } from "react"; -import { createRoute } from "@tanstack/react-router"; -import { RootRoute } from "./__root"; -import { useAppStore } from "@/stores/useAppStore"; -import { Button } from "@/components/ui/button"; -import { Badge } from "@/components/ui/badge"; -import { PlayIcon, SquareIcon, AlertCircleIcon } 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 liveFrame = useAppStore((s) => s.liveFrame); - const startSetupStream = useAppStore((s) => s.startSetupStream); - const stopSetupStream = useAppStore((s) => s.stopSetupStream); - - useEffect(() => { - // Stop stream on unmount - return () => { - stopSetupStream().catch(console.error); - }; - }, [stopSetupStream]); - - const handleStart = async () => { - if (!connected) { - toast.error("Camera is not connected!"); - return; - } - try { - await startSetupStream(); - } catch { - toast.error("Failed to start setup stream"); - } - }; - - const handleStop = async () => { - try { - await stopSetupStream(); - } catch { - toast.error("Failed to stop setup stream"); - } - }; - - return ( -
-
-
-

Camera Setup

-

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

-
-
- - {setupStreamActive ? "Streaming" : "Stopped"} - - {!setupStreamActive ? ( - - ) : ( - - )} -
-
- -
- {setupStreamActive ? ( - liveFrame ? ( - Camera Livestream - ) : ( -
- Waiting for frame... -
- ) - ) : ( -
- {connected ? "Click Start Stream to begin setup" : "Camera disconnected"} -
- )} -
-
- ); -} diff --git a/headless/src/routes/teable.tsx b/headless/src/routes/teable.tsx deleted file mode 100644 index edee3c3..0000000 --- a/headless/src/routes/teable.tsx +++ /dev/null @@ -1,32 +0,0 @@ -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, -}); - -// ─── Page shell ─────────────────────────────────────────────────────────────── - -function TeablePage() { - return ( -
-
-
-

Teable Integration

-

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

-
- - - -
-
- ); -} - diff --git a/headless/src/routes/teable/ConnectionSection.tsx b/headless/src/routes/teable/ConnectionSection.tsx deleted file mode 100644 index 745db77..0000000 --- a/headless/src/routes/teable/ConnectionSection.tsx +++ /dev/null @@ -1,159 +0,0 @@ -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/src/routes/teable/SchemaStatus.tsx b/headless/src/routes/teable/SchemaStatus.tsx deleted file mode 100644 index fb35d59..0000000 --- a/headless/src/routes/teable/SchemaStatus.tsx +++ /dev/null @@ -1,97 +0,0 @@ -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/src/routes/teable/SyncToggleSection.tsx b/headless/src/routes/teable/SyncToggleSection.tsx deleted file mode 100644 index 40e6a13..0000000 --- a/headless/src/routes/teable/SyncToggleSection.tsx +++ /dev/null @@ -1,39 +0,0 @@ -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/src/routes/teable/TableTargetSection.tsx b/headless/src/routes/teable/TableTargetSection.tsx deleted file mode 100644 index db59c59..0000000 --- a/headless/src/routes/teable/TableTargetSection.tsx +++ /dev/null @@ -1,277 +0,0 @@ -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/src/routes/violations.tsx b/headless/src/routes/violations.tsx deleted file mode 100644 index 241d84d..0000000 --- a/headless/src/routes/violations.tsx +++ /dev/null @@ -1,174 +0,0 @@ -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(); - - // ponytail: view preference stored in localStorage - 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 - )} - - - - x.id)} - /> -
- ); -} diff --git a/headless/src/routes/violations/ExportImagesDialog.tsx b/headless/src/routes/violations/ExportImagesDialog.tsx deleted file mode 100644 index bf922ee..0000000 --- a/headless/src/routes/violations/ExportImagesDialog.tsx +++ /dev/null @@ -1,79 +0,0 @@ -import { useState } from "react"; -import { toast } from "sonner"; -import { getRpc } from "@/lib/rpc"; -import { Button } from "@/components/ui/button"; -import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog"; - -interface ExportImagesDialogProps { - open: boolean; - onOpenChange: (open: boolean) => void; - selectedIds: number[]; - pageViolationIds: number[]; -} - -export function ExportImagesDialog({ - open, - onOpenChange, - selectedIds, - pageViolationIds, -}: ExportImagesDialogProps) { - const selectedCount = selectedIds.length; - const pageViolationCount = pageViolationIds.length; - const [exportDir, setExportDir] = useState(""); - const [exporting, setExporting] = useState(false); - - const handleExport = async () => { - if (!exportDir.trim()) { - toast.error("Please enter an export directory"); - return; - } - setExporting(true); - try { - // ponytail: export selected if any, else all on current page - const ids = selectedCount > 0 ? selectedIds : pageViolationIds; - const result = await getRpc().request.exportSkinnedImages({ - violationIds: ids, - targetDir: exportDir.trim(), - }); - toast.success(`Exported ${result.exported} images${result.failed ? `, ${result.failed} failed` : ""}`); - onOpenChange(false); - } catch { - toast.error("Failed to export images"); - } finally { - setExporting(false); - } - }; - - return ( - - - - Export Skinned Images - -

- {selectedCount > 0 - ? `Export ${selectedCount} selected violation(s) with Poliscan skin.` - : `Export all ${pageViolationCount} violations on this page with Poliscan skin.`} -

-
- - setExportDir(e.target.value)} - placeholder="/home/user/exports" - 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/src/routes/violations/ViolationGridTile.tsx b/headless/src/routes/violations/ViolationGridTile.tsx deleted file mode 100644 index b1dc7e6..0000000 --- a/headless/src/routes/violations/ViolationGridTile.tsx +++ /dev/null @@ -1,133 +0,0 @@ -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) { - const { imageData, imageLoading } = useViolationImage(violation, skinEnabled); - 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 handleDelete = async (e: React.MouseEvent) => { - e.stopPropagation(); - setDeleting(true); - try { - await onDelete(); - } finally { - setDeleting(false); - } - }; - - return ( -
-
imageData && onImageClick(imageData)} - > -
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/src/routes/violations/ViolationRow.tsx b/headless/src/routes/violations/ViolationRow.tsx deleted file mode 100644 index 1db1ddb..0000000 --- a/headless/src/routes/violations/ViolationRow.tsx +++ /dev/null @@ -1,111 +0,0 @@ -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) { - const { imageData, imageLoading } = useViolationImage(violation, skinEnabled); - 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 handleDelete = async () => { - setDeleting(true); - try { - await onDelete(); - } finally { - setDeleting(false); - } - }; - - return ( - - - - - - - - {formattedTime} - - - - - - - {violation.measuredSpeed} - - {violation.maxSpeed} - +{over} - - - - - ); -} diff --git a/headless/src/routes/violations/ViolationsGrid.tsx b/headless/src/routes/violations/ViolationsGrid.tsx deleted file mode 100644 index c763607..0000000 --- a/headless/src/routes/violations/ViolationsGrid.tsx +++ /dev/null @@ -1,87 +0,0 @@ -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/src/routes/violations/ViolationsTable.tsx b/headless/src/routes/violations/ViolationsTable.tsx deleted file mode 100644 index 4b673ea..0000000 --- a/headless/src/routes/violations/ViolationsTable.tsx +++ /dev/null @@ -1,105 +0,0 @@ -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/src/routes/violations/ViolationsToolbar.tsx b/headless/src/routes/violations/ViolationsToolbar.tsx deleted file mode 100644 index 7f27ab2..0000000 --- a/headless/src/routes/violations/ViolationsToolbar.tsx +++ /dev/null @@ -1,157 +0,0 @@ -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/src/routes/violations/useViolationImage.ts b/headless/src/routes/violations/useViolationImage.ts deleted file mode 100644 index 621c636..0000000 --- a/headless/src/routes/violations/useViolationImage.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { useEffect, useState } from "react"; -import { getRpc } from "@/lib/rpc"; -import type { Violation } from "@/shared/types"; - -/** - * Fetches a violation's image (raw or Poliscan-skinned) as a data-URL. - * Shared by ViolationRow and ViolationGridTile to dedupe the fetch effect. - */ -export function useViolationImage(violation: Violation, skinEnabled: boolean) { - const [imageData, setImageData] = useState(null); - const [imageLoading, setImageLoading] = useState(true); - - useEffect(() => { - let cancelled = false; - setImageLoading(true); - const fetchImage = skinEnabled - ? getRpc().request.getSkinnedImageData({ violationId: violation.id }) - : getRpc().request.getImageData({ imagePath: violation.imagePath }); - 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]); - - return { imageData, imageLoading }; -} diff --git a/headless/src/routes/violations/useViolations.ts b/headless/src/routes/violations/useViolations.ts deleted file mode 100644 index 29fc17a..0000000 --- a/headless/src/routes/violations/useViolations.ts +++ /dev/null @@ -1,186 +0,0 @@ -import { useCallback, useEffect, useState } from "react"; -import { toast } from "sonner"; -import { getRpc } from "@/lib/rpc"; -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]); - - 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/src/server/database.ts b/headless/src/server/database.ts deleted file mode 100644 index 6dff97e..0000000 --- a/headless/src/server/database.ts +++ /dev/null @@ -1,431 +0,0 @@ -import { Database } from "bun:sqlite"; -import path from "path"; -import { existsSync, mkdirSync } from "fs"; -import type { - Violation, - SaveViolationInput, - AppSettings, - ViolationQuery, - ViolationPage, - Lap, - LapSession, - LapSessionWithLaps, - SaveLapInput, -} from "../shared/types"; - -// ─── Default settings ──────────────────────────────────────────────────────── - -const DEFAULT_SETTINGS: AppSettings = { - maxSpeed: 30, - selectedPort: "", - // Industrial Camera Settings - cameraExposure: 5000, - cameraGain: 0, - strobeLineDuration: 5000, - pixelFormat: "Mono", - exposureAuto: "Off", - gainAuto: "Off", - frameRate: 30, - cameraWidth: 1280, - cameraHeight: 1024, - blackLevel: 0, - // Lap timer settings - lapMode: "single", - lapSaveImages: "true", - lapDirFilter: "both", - // Teable integration - teableUrl: "", - teableToken: "", - teableUserName: "", - teableUserEmail: "", - teableUserAvatar: "", - teableSpaceId: "", - teableBaseId: "", - teableTableId: "", - teableSyncEnabled: "false", - githubToken: "", - // Poliscan skin - skinMeasuringLocation: "", -}; - -// ─── Database directory resolution ────────────────────────────────────────── - -export function getUserDataDir(): string { - const dir = process.env.DATA_DIR || path.join(process.env.HOME || process.cwd(), ".speedcamera"); - if (!existsSync(dir)) { - mkdirSync(dir, { recursive: true }); - } - return dir; -} - -let _db: Database | null = null; - -export function getDb(): Database { - if (_db) return _db; - - const userDataDir = getUserDataDir(); - const dbPath = path.join(userDataDir, "speedcamera.db"); - const db = new Database(dbPath, { create: true }); - - db.run("PRAGMA journal_mode = WAL"); - db.run("PRAGMA foreign_keys = ON"); - - db.run(` - 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 - ) - `); - - try { - db.run("ALTER TABLE speed_violations ADD COLUMN direction TEXT NOT NULL DEFAULT 'forward'"); - } catch { - // Column already exists - } - - db.run(` - CREATE INDEX IF NOT EXISTS idx_timestamp ON speed_violations(timestamp) - `); - - db.run(` - CREATE TABLE IF NOT EXISTS settings ( - key TEXT PRIMARY KEY, - value TEXT NOT NULL - ) - `); - - db.run(` - 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 - ) - `); - - db.run(` - 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 - ) - `); - - db.run(` - CREATE INDEX IF NOT EXISTS idx_laps_session ON laps(sessionId) - `); - - db.run(` - CREATE INDEX IF NOT EXISTS idx_lap_sessions_started ON lap_sessions(startedAt) - `); - - const insertDefault = db.prepare( - "INSERT OR IGNORE INTO settings (key, value) VALUES (?, ?)" - ); - for (const [key, value] of Object.entries(DEFAULT_SETTINGS)) { - insertDefault.run(key, String(value)); - } - - _db = db; - return db; -} - -// ─── Violation queries ─────────────────────────────────────────────────────── - -export function insertViolation(input: SaveViolationInput & { imagePath: string }): Violation { - const db = getDb(); - const now = new Date().toISOString(); - const stmt = db.prepare(` - INSERT INTO speed_violations (timestamp, measuredSpeed, maxSpeed, direction, imagePath, createdAt) - VALUES (?, ?, ?, ?, ?, ?) - `); - const result = stmt.run(now, input.measuredSpeed, input.maxSpeed, input.direction, input.imagePath, now); - return { - id: result.lastInsertRowid as number, - timestamp: now, - measuredSpeed: input.measuredSpeed, - maxSpeed: input.maxSpeed, - direction: input.direction, - imagePath: input.imagePath, - createdAt: now, - }; -} - -export function queryViolations(q: ViolationQuery): ViolationPage { - const db = getDb(); - const conditions: string[] = []; - const params: (string | number)[] = []; - - if (q.dateFrom) { - conditions.push("timestamp >= ?"); - params.push(q.dateFrom); - } - if (q.dateTo) { - conditions.push("timestamp <= ?"); - params.push(q.dateTo); - } - if (q.minSpeed != null) { - conditions.push("measuredSpeed >= ?"); - params.push(q.minSpeed); - } - - const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : ""; - - const countRow = db - .prepare(`SELECT COUNT(*) as total FROM speed_violations ${where}`) - .get(...params) as { total: number }; - - const offset = (q.page - 1) * q.limit; - const violations = db - .prepare( - `SELECT * FROM speed_violations ${where} ORDER BY timestamp DESC LIMIT ? OFFSET ?` - ) - .all(...params, q.limit, offset) as Violation[]; - - return { violations, total: countRow.total }; -} - -export function getViolationById(id: number): Violation | null { - const db = getDb(); - return ( - (db.prepare("SELECT * FROM speed_violations WHERE id = ?").get(id) as Violation | undefined) ?? - null - ); -} - -export function removeViolation(id: number): void { - const db = getDb(); - db.prepare("DELETE FROM speed_violations WHERE id = ?").run(id); -} - -export function exportCsv(opts: { - dateFrom?: string; - dateTo?: string; - minSpeed?: number; -}): string { - const db = getDb(); - const conditions: string[] = []; - const params: (string | number)[] = []; - - if (opts.dateFrom) { - conditions.push("timestamp >= ?"); - params.push(opts.dateFrom); - } - if (opts.dateTo) { - conditions.push("timestamp <= ?"); - params.push(opts.dateTo); - } - if (opts.minSpeed != null) { - conditions.push("measuredSpeed >= ?"); - params.push(opts.minSpeed); - } - - const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : ""; - const rows = db - .prepare(`SELECT * FROM speed_violations ${where} ORDER BY timestamp DESC`) - .all(...params) as Violation[]; - - const header = "id,timestamp,measuredSpeed,maxSpeed,direction,imagePath,createdAt"; - const lines = rows.map( - (r) => - `${r.id},"${r.timestamp}",${r.measuredSpeed},${r.maxSpeed},${r.direction},"${r.imagePath}","${r.createdAt}"` - ); - return [header, ...lines].join("\n"); -} - -// ─── Settings queries ──────────────────────────────────────────────────────── - -export function getSettings(): AppSettings { - const db = getDb(); - const rows = db.prepare("SELECT key, value FROM settings").all() as { - key: string; - value: string; - }[]; - - const map = Object.fromEntries(rows.map((r) => [r.key, r.value])); - - return { - maxSpeed: Number(map.maxSpeed ?? DEFAULT_SETTINGS.maxSpeed), - selectedPort: map.selectedPort ?? DEFAULT_SETTINGS.selectedPort, - cameraExposure: Number(map.cameraExposure ?? DEFAULT_SETTINGS.cameraExposure), - cameraGain: Number(map.cameraGain ?? DEFAULT_SETTINGS.cameraGain), - strobeLineDuration: Number(map.strobeLineDuration ?? DEFAULT_SETTINGS.strobeLineDuration), - pixelFormat: map.pixelFormat ?? DEFAULT_SETTINGS.pixelFormat, - exposureAuto: map.exposureAuto ?? DEFAULT_SETTINGS.exposureAuto, - gainAuto: map.gainAuto ?? DEFAULT_SETTINGS.gainAuto, - frameRate: Number(map.frameRate ?? DEFAULT_SETTINGS.frameRate), - cameraWidth: Number(map.cameraWidth ?? DEFAULT_SETTINGS.cameraWidth), - cameraHeight: Number(map.cameraHeight ?? DEFAULT_SETTINGS.cameraHeight), - blackLevel: Number(map.blackLevel ?? DEFAULT_SETTINGS.blackLevel), - lapMode: map.lapMode ?? DEFAULT_SETTINGS.lapMode, - lapSaveImages: map.lapSaveImages ?? DEFAULT_SETTINGS.lapSaveImages, - lapDirFilter: map.lapDirFilter ?? DEFAULT_SETTINGS.lapDirFilter, - teableUrl: map.teableUrl ?? DEFAULT_SETTINGS.teableUrl, - teableToken: map.teableToken ?? DEFAULT_SETTINGS.teableToken, - teableUserName: map.teableUserName ?? DEFAULT_SETTINGS.teableUserName, - teableUserEmail: map.teableUserEmail ?? DEFAULT_SETTINGS.teableUserEmail, - teableUserAvatar: map.teableUserAvatar ?? DEFAULT_SETTINGS.teableUserAvatar, - teableSpaceId: map.teableSpaceId ?? DEFAULT_SETTINGS.teableSpaceId, - teableBaseId: map.teableBaseId ?? DEFAULT_SETTINGS.teableBaseId, - teableTableId: map.teableTableId ?? DEFAULT_SETTINGS.teableTableId, - teableSyncEnabled: map.teableSyncEnabled ?? DEFAULT_SETTINGS.teableSyncEnabled, - githubToken: map.githubToken ?? DEFAULT_SETTINGS.githubToken, - skinMeasuringLocation: map.skinMeasuringLocation ?? DEFAULT_SETTINGS.skinMeasuringLocation, - }; -} - -export function saveSetting(key: keyof AppSettings, value: string): void { - const db = getDb(); - db.prepare("INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)").run( - key, - value - ); -} - -// ─── Lap session queries ─────────────────────────────────────────────────────── - -export function createLapSession(lapMode: string): LapSession { - const db = getDb(); - const now = new Date().toISOString(); - const result = db - .prepare( - "INSERT INTO lap_sessions (startedAt, endedAt, lapMode, createdAt) VALUES (?, NULL, ?, ?)" - ) - .run(now, lapMode, now); - return { - id: result.lastInsertRowid as number, - startedAt: now, - endedAt: null, - lapMode, - createdAt: now, - }; -} - -export function closeLapSession(id: number): void { - const db = getDb(); - const now = new Date().toISOString(); - db.prepare("UPDATE lap_sessions SET endedAt = ? WHERE id = ?").run(now, id); -} - -export function getLapSessions( - page: number, - limit: number -): { sessions: LapSessionWithLaps[]; total: number } { - const db = getDb(); - const countRow = db - .prepare("SELECT COUNT(*) as total FROM lap_sessions") - .get() as { total: number }; - - const offset = (page - 1) * limit; - const rows = db - .prepare( - "SELECT * FROM lap_sessions ORDER BY startedAt DESC LIMIT ? OFFSET ?" - ) - .all(limit, offset) as LapSession[]; - - const sessions: LapSessionWithLaps[] = rows.map((session) => { - const laps = db - .prepare( - "SELECT * FROM laps WHERE sessionId = ? ORDER BY lapNumber ASC" - ) - .all(session.id) as Lap[]; - return { ...session, laps }; - }); - - return { sessions, total: countRow.total }; -} - -export function getLapSessionById(id: number): LapSessionWithLaps | null { - const db = getDb(); - const session = db - .prepare("SELECT * FROM lap_sessions WHERE id = ?") - .get(id) as LapSession | undefined; - if (!session) return null; - - const laps = db - .prepare("SELECT * FROM laps WHERE sessionId = ? ORDER BY lapNumber ASC") - .all(id) as Lap[]; - - return { ...session, laps }; -} - -export async function deleteLapSession(id: number): Promise { - const db = getDb(); - const laps = db - .prepare("SELECT startImagePath, endImagePath FROM laps WHERE sessionId = ?") - .all(id) as Pick[]; - - db.prepare("DELETE FROM lap_sessions WHERE id = ?").run(id); - - const { deleteImage } = await import("./filestore"); - for (const lap of laps) { - if (lap.startImagePath) await deleteImage(lap.startImagePath); - if (lap.endImagePath) await deleteImage(lap.endImagePath); - } -} - -// ─── Lap queries ────────────────────────────────────────────────────────────── - -export async function insertLap( - input: SaveLapInput & { startImagePath: string | null; endImagePath: string | null } -): Promise { - const db = getDb(); - const result = db - .prepare( - `INSERT INTO laps - (sessionId, lapNumber, startTimestamp, endTimestamp, durationMs, - speedAtStart, speedAtEnd, startImagePath, endImagePath) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)` - ) - .run( - input.sessionId, - input.lapNumber, - input.startTimestamp, - input.endTimestamp, - input.durationMs, - input.speedAtStart, - input.speedAtEnd, - input.startImagePath, - input.endImagePath - ); - return { - id: result.lastInsertRowid as number, - sessionId: input.sessionId, - lapNumber: input.lapNumber, - startTimestamp: input.startTimestamp, - endTimestamp: input.endTimestamp, - durationMs: input.durationMs, - speedAtStart: input.speedAtStart, - speedAtEnd: input.speedAtEnd, - startImagePath: input.startImagePath, - endImagePath: input.endImagePath, - }; -} - -export async function deleteLap(id: number): Promise { - const db = getDb(); - const lap = db.prepare("SELECT startImagePath, endImagePath FROM laps WHERE id = ?").get( - id - ) as Pick | undefined; - - db.prepare("DELETE FROM laps WHERE id = ?").run(id); - - if (lap) { - const { deleteImage } = await import("./filestore"); - if (lap.startImagePath) await deleteImage(lap.startImagePath); - if (lap.endImagePath) await deleteImage(lap.endImagePath); - } -} diff --git a/headless/src/server/env.ts b/headless/src/server/env.ts deleted file mode 100644 index 886ffb9..0000000 --- a/headless/src/server/env.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { join, dirname } from "path"; -import { existsSync } from "fs"; - -function resolveAravisPath(): string | undefined { - const binDir = dirname(process.execPath || process.argv[0] || ""); - const candidates = [ - // Standard system paths - "/usr/lib/aarch64-linux-gnu/libaravis-0.8.so", - "/usr/lib/x86_64-linux-gnu/libaravis-0.8.so", - "/usr/local/lib/libaravis-0.8.so", - "/usr/lib/libaravis-0.8.so", - // Development / project layout - join(import.meta.dir, "..", "..", "vendor", "libaravis-0.8.so"), - join(import.meta.dir, "..", "vendor", "libaravis-0.8.so"), - join(process.cwd(), "vendor", "libaravis-0.8.so"), - join(process.cwd(), "resources", "libaravis-0.8.so"), - join(binDir, "libaravis-0.8.so"), - ]; - return candidates.find((p) => existsSync(p)); -} - -const libPath = resolveAravisPath(); -if (libPath) { - console.log(`[entry] Setting BUN_ARAVIS_LIB_PATH to ${libPath}`); - process.env.BUN_ARAVIS_LIB_PATH = libPath; -} else { - console.log(`[entry] libaravis-0.8.so not found in bundled paths, falling back to system dynamic linker`); -} diff --git a/headless/src/server/filestore.ts b/headless/src/server/filestore.ts deleted file mode 100644 index ed926b8..0000000 --- a/headless/src/server/filestore.ts +++ /dev/null @@ -1,60 +0,0 @@ -import path from "path"; -import { getUserDataDir } from "./database"; - -function getImageDir(): string { - return path.join(getUserDataDir(), "images"); -} - -async function ensureImageDir(): Promise { - await Bun.write(path.join(getImageDir(), ".keep"), ""); -} - -/** - * Save an image from a raw base64 string (no data-URL prefix). - * Returns the absolute path of the saved file. - */ -export async function saveImage(base64: string): Promise { - await ensureImageDir(); - - const timestamp = new Date().toISOString().replace(/[:.]/g, "-"); - const filename = `speed-violation-${timestamp}.png`; - const filePath = path.join(getImageDir(), filename); - - const buffer = Buffer.from(base64, "base64"); - await Bun.write(filePath, buffer); - - return filePath; -} - -/** - * Read an image from disk and return it as a data-URL. - * Returns null if the file does not exist. - */ -export async function readImageAsDataUrl(imagePath: string): Promise { - const file = Bun.file(imagePath); - const exists = await file.exists(); - if (!exists) return null; - - const buffer = await file.arrayBuffer(); - const base64 = Buffer.from(buffer).toString("base64"); - const ext = path.extname(imagePath).toLowerCase(); - const mime = ext === ".png" ? "image/png" : "image/jpeg"; - - return `data:${mime};base64,${base64}`; -} - -/** - * Delete an image file from disk. Silently ignores missing files. - */ -export async function deleteImage(imagePath: string): Promise { - try { - const file = Bun.file(imagePath); - const exists = await file.exists(); - if (exists) { - const { unlink } = await import("fs/promises"); - await unlink(imagePath); - } - } catch (err) { - console.error(`[filestore] Failed to delete image ${imagePath}:`, err); - } -} diff --git a/headless/src/server/flasher.ts b/headless/src/server/flasher.ts deleted file mode 100644 index c4e2f13..0000000 --- a/headless/src/server/flasher.ts +++ /dev/null @@ -1,210 +0,0 @@ -import { join, dirname } from "path"; -import { tmpdir } from "os"; -import { existsSync } from "fs"; -import type { GithubRelease, FlashProgressPayload } from "../shared/types"; - -// ─── Constants ──────────────────────────────────────────────────────────────── - -const GITHUB_API_URL = "https://api.github.com/repos/LeoLTM/speedcamera/releases"; -const GITHUB_USER_URL = "https://api.github.com/user"; - -// Only allow well-formed version tags from our own repo -const TAG_PATTERN = /^v\d+\.\d+\.\d+(-canary)?$/; - -// ─── esptool binary path resolution ────────────────────────────────────────── - -function resolveEsptoolPath(): string { - const binDir = dirname(process.execPath || process.argv[0] || ""); - const candidates = [ - join(process.cwd(), "resources", "esptool"), - join(import.meta.dir, "..", "..", "resources", "esptool"), - join(import.meta.dir, "..", "resources", "esptool"), - join(binDir, "esptool"), - "/usr/bin/esptool", - "/usr/local/bin/esptool", - "/usr/bin/esptool.py", - ]; - return candidates.find((p) => existsSync(p)) ?? "esptool"; -} - -const ESPTOOL_PATH = resolveEsptoolPath(); - -// ─── Helpers ────────────────────────────────────────────────────────────────── - -function githubHeaders(token: string, accept = "application/vnd.github+json"): HeadersInit { - const h: HeadersInit = { Accept: accept, "User-Agent": "speedcamera-app" }; - if (token) h["Authorization"] = `Bearer ${token}`; - return h; -} - -// ─── Push callback ──────────────────────────────────────────────────────────── - -type PushFn = (payload: FlashProgressPayload) => void; -let _push: PushFn | null = null; - -export function initFlasher(push: PushFn): void { - _push = push; -} - -function push(payload: FlashProgressPayload): void { - _push?.(payload); -} - -// ─── Active process handle ──────────────────────────────────────────────────── - -let _activeProc: ReturnType | null = null; - -// ─── Public API ─────────────────────────────────────────────────────────────── - -export async function testGithubToken( - token: string, -): Promise<{ valid: boolean; login?: string; error?: string }> { - if (!token.trim()) { - return { valid: false, error: "Token is empty" }; - } - - let resp: Response; - try { - resp = await fetch(`${GITHUB_API_URL}?per_page=1`, { - headers: githubHeaders(token), - }); - } catch (e) { - return { valid: false, error: `Network error: ${e instanceof Error ? e.message : String(e)}` }; - } - - if (resp.status === 401) return { valid: false, error: "Invalid token — authentication failed" }; - if (resp.status === 403) return { valid: false, error: "Forbidden — check token scopes (needs repo read)" }; - if (resp.status === 404) return { valid: false, error: "Repository not found — check token permissions" }; - if (!resp.ok) return { valid: false, error: `GitHub API error: ${resp.status} ${resp.statusText}` }; - - let login: string | undefined; - try { - const userResp = await fetch(GITHUB_USER_URL, { headers: githubHeaders(token) }); - if (userResp.ok) { - login = ((await userResp.json()) as { login: string }).login; - } - } catch { - // Non-critical — token is still valid - } - - return { valid: true, login }; -} - -export async function listFirmwareReleases(token: string): Promise { - const resp = await fetch(GITHUB_API_URL, { headers: githubHeaders(token) }); - if (resp.status === 401 || resp.status === 403) { - throw new Error("GitHub authentication failed — check your token in the Firmware Update settings"); - } - if (!resp.ok) { - throw new Error(`GitHub API error: ${resp.status} ${resp.statusText}`); - } - - const data = (await resp.json()) as Array<{ - tag_name: string; - name: string; - published_at: string; - prerelease: boolean; - assets: Array<{ name: string; url: string }>; - }>; - - return data.map((r) => { - const firmwareAsset = r.assets.find((a) => a.name === "firmware.bin"); - return { - tag: r.tag_name, - name: r.name, - publishedAt: r.published_at, - prerelease: r.prerelease, - firmwareAssetApiUrl: firmwareAsset?.url ?? "", - }; - }); -} - -export async function flashFirmware( - releaseTag: string, - port: string, - firmwareAssetApiUrl: string, - token: string, -): Promise { - if (!TAG_PATTERN.test(releaseTag)) { - throw new Error(`Invalid release tag: "${releaseTag}"`); - } - - const ALLOWED_PREFIX = "https://api.github.com/repos/LeoLTM/speedcamera/releases/assets/"; - if (!firmwareAssetApiUrl.startsWith(ALLOWED_PREFIX)) { - throw new Error("Invalid firmware asset URL"); - } - - const tmpPath = join(tmpdir(), `speedcamera-firmware-${releaseTag}.bin`); - - push({ type: "downloading" }); - const dlResp = await fetch(firmwareAssetApiUrl, { - headers: githubHeaders(token, "application/octet-stream"), - redirect: "follow", - }); - if (!dlResp.ok) { - throw new Error(`Failed to download firmware: ${dlResp.status} ${dlResp.statusText}`); - } - await Bun.write(tmpPath, dlResp); - - const proc = Bun.spawn( - [ - ESPTOOL_PATH, - "--port", port, - "--baud", "460800", - "--chip", "esp8266", - "write_flash", - "--flash_mode", "dout", - "--flash_freq", "40m", - "--flash_size", "detect", - "0x0", - tmpPath, - ], - { stdout: "pipe", stderr: "pipe" }, - ); - _activeProc = proc; - - const decoder = new TextDecoder(); - let lineBuffer = ""; - - function flushLines(chunk: string): void { - lineBuffer += chunk; - const parts = lineBuffer.split("\n"); - lineBuffer = parts.pop() ?? ""; - for (const line of parts) { - const trimmed = line.replace(/\r$/, "").trim(); - if (trimmed) push({ type: "output", line: trimmed }); - } - } - - async function drainStream(stream: ReadableStream): Promise { - const reader = stream.getReader(); - try { - while (true) { - const { done, value } = await reader.read(); - if (done) break; - flushLines(decoder.decode(value, { stream: true })); - } - } finally { - reader.releaseLock(); - flushLines(decoder.decode()); - } - } - - await Promise.all([drainStream(proc.stdout), drainStream(proc.stderr)]); - - const exitCode = await proc.exited; - _activeProc = null; - - if (exitCode !== 0) { - throw new Error(`esptool exited with code ${exitCode}`); - } - - push({ type: "done" }); -} - -export function cancelFlash(): void { - if (_activeProc) { - _activeProc.kill(); - _activeProc = null; - } -} diff --git a/headless/src/server/index.ts b/headless/src/server/index.ts deleted file mode 100644 index 964ef2a..0000000 --- a/headless/src/server/index.ts +++ /dev/null @@ -1,442 +0,0 @@ -import "./env"; -import path from "path"; -import { RpcServer, type RequestHandlers } from "./rpc"; -import { - insertViolation, - queryViolations, - getViolationById, - removeViolation, - exportCsv, - getSettings, - saveSetting, - createLapSession, - closeLapSession, - insertLap, - getLapSessions, - getLapSessionById, - deleteLapSession, - deleteLap, - getUserDataDir, -} from "./database"; -import { saveImage, deleteImage } from "./filestore"; -import { renderPoliscanSkin } from "./skin-renderer"; -import { - initCamera, - disconnectCamera, - getCameraStatus, - captureFrame, - setExposure, - setGain, - initCameraPush, - applyMfsConfig, - startSetupStream, - stopSetupStream, - setPixelFormat, - getPixelFormat, - setStrobeDuration, - setCameraFeatureStr, - setCameraFeatureInt, -} from "./industrial-camera"; -import { initFlasher, listFirmwareReleases, flashFirmware, cancelFlash, testGithubToken } from "./flasher"; -import { - testTeableConnection, - saveTeableConfig, - removeTeableConfig, - listTeableSpaces, - listTeableBases, - listTeableTables, - verifyTeableTable, - ensureTeableFields, - createTeableTable, - saveTeableTarget, - syncLapToTeable, -} from "./teable"; -import { getSystemNetworkSummary, logNetworkStatus } from "./network"; - -// ─── Serial module (real or mock) ──────────────────────────────────────────── -const isMock = !!process.env.MOCK_MODE; -const { initSerial, listPorts, openPort, closePort, sendCommand } = await ( - isMock ? import("./mock/serial") : import("./serial") -); - -// ─── RPC Request Handlers ──────────────────────────────────────────────────── -const handlers: RequestHandlers = { - // ── Violations ────────────────────────────────────────────────────────── - getViolations: (q) => queryViolations(q), - - getViolationById: ({ id }) => getViolationById(id), - - deleteViolation: async ({ id }) => { - const v = getViolationById(id); - if (v) { - removeViolation(id); - await deleteImage(v.imagePath); - } - }, - - exportViolationsCsv: ({ dateFrom, dateTo, minSpeed }) => - exportCsv({ dateFrom, dateTo, minSpeed }), - - saveViolation: async ({ measuredSpeed, maxSpeed, direction }) => { - let raw = await captureFrame(); - if (!raw && isMock) { - // In mock mode, generate a simple 1x1 base64 png if camera is not active - raw = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="; - } - if (!raw) throw new Error("Failed to capture frame from industrial camera"); - const imagePath = await saveImage(raw); - const v = insertViolation({ imageBase64: raw, imagePath, measuredSpeed, maxSpeed, direction }); - return v; - }, - - // ── Lap Sessions ──────────────────────────────────────────────────────── - createLapSession: ({ lapMode }) => createLapSession(lapMode), - - closeLapSession: ({ id }) => { - closeLapSession(id); - }, - - saveLap: async ({ - sessionId, lapNumber, startTimestamp, endTimestamp, durationMs, - speedAtStart, speedAtEnd, startImageBase64, endImageBase64, - }) => { - const startRaw = startImageBase64 - ? startImageBase64.replace(/^data:image\/\w+;base64,/, "") - : null; - const endRaw = endImageBase64 - ? endImageBase64.replace(/^data:image\/\w+;base64,/, "") - : null; - const startImagePath = startRaw ? await saveImage(startRaw) : null; - const endImagePath = endRaw ? await saveImage(endRaw) : null; - return insertLap({ - sessionId, lapNumber, startTimestamp, endTimestamp, durationMs, - speedAtStart, speedAtEnd, - startImageBase64: null, - endImageBase64: null, - startImagePath, - endImagePath, - }); - }, - - getLapSessions: ({ page, limit }) => getLapSessions(page, limit), - - getLapSessionById: ({ id }) => getLapSessionById(id), - - deleteLapSession: ({ id }) => deleteLapSession(id), - - deleteLap: ({ id }) => deleteLap(id), - - // ── Images ────────────────────────────────────────────────────────────── - getImageData: async ({ imagePath }) => { - if (!imagePath) return ""; - return `/image?path=${encodeURIComponent(imagePath)}`; - }, - - getSkinnedImageData: async ({ violationId }) => { - return `/skinned-image?violationId=${violationId}`; - }, - - exportSkinnedImages: async ({ violationIds, targetDir }) => { - const settings = getSettings(); - let exported = 0; - let failed = 0; - for (const id of violationIds) { - try { - const v = getViolationById(id); - if (!v) { failed++; continue; } - const buf = await renderPoliscanSkin(v.imagePath, v, { - measuringLocation: settings.skinMeasuringLocation, - }); - const ts = new Date(v.timestamp).toISOString().replace(/[:.]/g, "-"); - const outPath = path.join(targetDir, `violation-${v.id}-${ts}.png`); - await Bun.write(outPath, buf); - exported++; - } catch (err) { - console.error(`[skin-export] Failed to export violation ${id}:`, err); - failed++; - } - } - return { exported, failed }; - }, - - // ── Settings ──────────────────────────────────────────────────────────── - getSettings: () => getSettings(), - - saveSetting: ({ key, value }) => { - saveSetting(key, value); - }, - - // ── Serial ────────────────────────────────────────────────────────────── - listPorts: () => listPorts(), - - openPort: ({ path: portPath }) => openPort(portPath), - - closePort: () => closePort(), - - sendCommand: ({ json }) => { - sendCommand(json); - }, - - // ── Camera HW ─────────────────────────────────────────────────────────── - connectCamera: () => { - initCamera(); - }, - - disconnectCamera: () => { - disconnectCamera(); - }, - - getCameraStatus: () => getCameraStatus(), - - captureFrame: async () => { - const b64 = await captureFrame(); - return b64 ?? null; - }, - - setCameraExposure: ({ value }) => { - setExposure(value); - }, - - setCameraGain: ({ value }) => { - setGain(value); - }, - - applyMfsConfig: ({ mfsContent, saveAsDefault }) => { - return applyMfsConfig(mfsContent, saveAsDefault); - }, - - startSetupStream: () => { - startSetupStream((base64) => { - rpcServer.broadcast("liveFrame", base64); - }); - }, - - stopSetupStream: () => { - stopSetupStream(); - }, - - setCameraPixelFormat: ({ format }) => { - setPixelFormat(format); - }, - - getCameraPixelFormat: () => getPixelFormat(), - - setCameraStrobeDuration: ({ value }) => { - setStrobeDuration(value); - }, - - setCameraFeatureStr: ({ feature, value }) => { - setCameraFeatureStr(feature, value); - }, - - setCameraFeatureInt: ({ feature, value }) => { - setCameraFeatureInt(feature, value); - }, - - // ── Window (Headless Stubs) ───────────────────────────────────────────── - minimizeWindow: () => {}, - maximizeWindow: () => {}, - closeWindow: () => {}, - - // ── System & Network ─────────────────────────────────────────────────── - getPlatform: () => process.platform, - getNetworkInfo: () => getSystemNetworkSummary(), - - // ── Teable ─────────────────────────────────────────────────────────────── - testTeableConnection: ({ url, token }) => testTeableConnection(url, token), - - saveTeableConfig: ({ url, token, userName, userEmail, userAvatar }) => { - saveTeableConfig(url, token, userName, userEmail, userAvatar); - }, - - removeTeableConfig: () => { - removeTeableConfig(); - }, - - listTeableSpaces: () => listTeableSpaces(), - - listTeableBases: ({ spaceId }) => listTeableBases(spaceId), - - listTeableTables: ({ baseId }) => listTeableTables(baseId), - - verifyTeableTable: ({ tableId }) => verifyTeableTable(tableId), - - ensureTeableFields: ({ tableId }) => ensureTeableFields(tableId), - - createTeableTable: ({ baseId, tableName }) => createTeableTable(baseId, tableName), - - saveTeableTarget: ({ spaceId, baseId, tableId }) => { - saveTeableTarget(spaceId, baseId, tableId); - }, - - syncLapToTeable: ({ lap, session }) => syncLapToTeable(lap, session), - - // ── Updater (Headless Service Stubs) ──────────────────────────────────── - getLocalVersion: async () => { - return { version: "0.4.0-headless", channel: "headless", hash: "rpi-build" }; - }, - - checkForUpdate: async () => { - return { - version: "0.4.0-headless", - hash: "rpi-build", - updateAvailable: false, - updateReady: false, - error: "Updater is managed by system package manager or git on headless Pi", - }; - }, - - downloadUpdate: async () => { - return { ok: false, error: "Not supported in headless mode" }; - }, - - applyUpdate: async () => {}, - - // ── Firmware Flasher ──────────────────────────────────────────────────── - listFirmwareReleases: async () => { - const { githubToken } = getSettings(); - return listFirmwareReleases(githubToken); - }, - - flashFirmware: async ({ releaseTag, port, firmwareAssetApiUrl }) => { - const { githubToken } = getSettings(); - try { closePort(); } catch { /* ignore */ } - await flashFirmware(releaseTag, port, firmwareAssetApiUrl, githubToken); - }, - - cancelFlash: () => cancelFlash(), - - testGithubToken: ({ token }) => testGithubToken(token), -}; - -const rpcServer = new RpcServer(handlers); - -// ─── Push Bridges ───────────────────────────────────────────────────────────── -initSerial((payload) => { - rpcServer.broadcast("serialStatus", payload); -}); - -initCameraPush((payload) => { - rpcServer.broadcast("cameraStatus", payload); -}); - -initFlasher((payload) => { - rpcServer.broadcast("flashProgress", payload); -}); - -// Auto-connect hardware on startup if configured -initCamera(); - -// ─── HTTP & WebSocket Server ────────────────────────────────────────────────── -const PORT = parseInt(process.env.PORT || "3000", 10); -const HOST = process.env.HOST || "0.0.0.0"; -const DIST_DIR = path.resolve(import.meta.dir, "../../dist"); - -const server = Bun.serve({ - port: PORT, - hostname: HOST, - websocket: { - open(ws) { - rpcServer.registerSocket(ws); - console.log("[ws] Client connected"); - // Push current statuses immediately - ws.send(JSON.stringify({ event: "cameraStatus", payload: getCameraStatus() })); - }, - message(ws, message) { - rpcServer.handleMessage(ws, message); - }, - close(ws) { - rpcServer.unregisterSocket(ws); - console.log("[ws] Client disconnected"); - }, - }, - async fetch(req, server) { - const url = new URL(req.url); - - // WebSocket upgrade - if (url.pathname === "/ws/rpc" || url.pathname === "/ws") { - const upgraded = server.upgrade(req); - if (upgraded) return undefined; - return new Response("WebSocket upgrade failed", { status: 400 }); - } - - // Health check endpoint - if (url.pathname === "/api/health") { - return Response.json({ - status: "ok", - uptime: process.uptime(), - platform: process.platform, - camera: getCameraStatus(), - network: getSystemNetworkSummary(), - mockMode: isMock, - }); - } - - // Network status endpoint - if (url.pathname === "/api/network") { - return Response.json(getSystemNetworkSummary()); - } - - // Image serving endpoint - if (url.pathname === "/image") { - const imgPath = url.searchParams.get("path"); - if (!imgPath) return new Response("Missing path parameter", { status: 400 }); - const resolvedPath = path.resolve(imgPath); - const allowedDir = path.resolve(getUserDataDir()); - if (!resolvedPath.startsWith(allowedDir)) { - return new Response("Forbidden", { status: 403 }); - } - const file = Bun.file(resolvedPath); - if (!(await file.exists())) { - return new Response("Not Found", { status: 404 }); - } - return new Response(file); - } - - // Skinned image rendering endpoint - if (url.pathname === "/skinned-image") { - const idStr = url.searchParams.get("violationId"); - if (!idStr) return new Response("Missing violationId parameter", { status: 400 }); - const violationId = parseInt(idStr, 10); - const v = getViolationById(violationId); - if (!v) return new Response("Violation not found", { status: 404 }); - try { - const settings = getSettings(); - const buf = await renderPoliscanSkin(v.imagePath, v, { - measuringLocation: settings.skinMeasuringLocation, - }); - return new Response(new Uint8Array(buf), { - headers: { "Content-Type": "image/png" }, - }); - } catch (err) { - console.error("[skinned-image] Rendering failed:", err); - return new Response("Rendering failed", { status: 500 }); - } - } - - // Static files from built frontend (dist/) - let filePath = path.join(DIST_DIR, url.pathname); - let file = Bun.file(filePath); - - if (await file.exists()) { - return new Response(file); - } - - // SPA fallback: return index.html for client-side routing - const indexFile = Bun.file(path.join(DIST_DIR, "index.html")); - if (await indexFile.exists()) { - return new Response(indexFile, { - headers: { "Content-Type": "text/html; charset=utf-8" }, - }); - } - - return new Response( - "Speedcamera Headless Server running. Build the frontend (`bun run build`) or run `bun run dev` for development.", - { status: 200, headers: { "Content-Type": "text/plain" } } - ); - }, -}); - -console.log(`[speedcamera-headless] Server listening on http://${HOST}:${PORT} (Mock mode: ${isMock})`); -console.log(`[speedcamera-headless] Data directory: ${getUserDataDir()}`); -logNetworkStatus(); diff --git a/headless/src/server/industrial-camera.ts b/headless/src/server/industrial-camera.ts deleted file mode 100644 index 39b9e41..0000000 --- a/headless/src/server/industrial-camera.ts +++ /dev/null @@ -1,463 +0,0 @@ -import { Camera, Stream, updateDeviceList, getDevices } from "@asl-gokart/bun-aravis"; -import sharp from "sharp"; -import { getSettings } from "./database"; - -let camera: Camera | null = null; -let stream: Stream | null = null; -let isConnected = false; - -type PushCameraStatus = (payload: { connected: boolean; vendor: string | null; model: string | null; serial: string | null }) => void; -let pushCameraStatus: PushCameraStatus | null = null; - -export function initCameraPush(pushFn: PushCameraStatus) { - pushCameraStatus = pushFn; -} - -function notifyStatus() { - if (pushCameraStatus) { - pushCameraStatus({ - connected: isConnected, - vendor: camera ? camera.vendor : null, - model: camera ? camera.model : null, - serial: camera ? camera.serialNumber : null, - }); - } -} - -export function initCamera() { - if (isConnected) return; - try { - updateDeviceList(); - const devices = getDevices(); - const hikDevice = devices.find((d) => d.vendor.toLowerCase().includes("hikrobot")); - - if (!hikDevice && devices.length === 0) { - console.warn("[industrial-camera] No cameras found"); - return; - } - - camera = Camera.open(hikDevice ? hikDevice.id : undefined); - - try { - camera.autoPacketSize(); - } catch { - console.warn("[industrial-camera] autoPacketSize not supported/needed"); - } - - const settings = getSettings(); - const exposure = Number(settings.cameraExposure) || 5000; - const gain = Number(settings.cameraGain) || 0; - const strobeDuration = Number(settings.strobeLineDuration) || 5000; - - const exposureAuto = settings.exposureAuto || "Off"; - const gainAuto = settings.gainAuto || "Off"; - - if (camera.isFeatureAvailable("PixelFormat")) { - setPixelFormat(settings.pixelFormat); - } - - if (camera.isFeatureAvailable("AcquisitionMode")) { - camera.setStringFeature("AcquisitionMode", "Continuous"); - } - if (camera.isFeatureAvailable("TriggerMode")) { - camera.setStringFeature("TriggerMode", "On"); - camera.setStringFeature("TriggerSource", "Software"); - } - - if (camera.isFeatureAvailable("LineSelector")) { - try { - camera.setStringFeature("LineSelector", "Line1"); - } catch { - /* ignore */ - } - - try { - camera.setStringFeature("LineMode", "Strobe"); - } catch { - /* ignore */ - } - - try { - camera.setStringFeature("LineSource", "ExposureActive"); - } catch { - /* ignore */ - } - - try { - if (camera.isFeatureAvailable("StrobeEnable")) { - try { camera.setBooleanFeature("StrobeEnable", true); } - catch { camera.setIntegerFeature("StrobeEnable", 1); } - - camera.setIntegerFeature("StrobeLineDuration", strobeDuration); - camera.setIntegerFeature("StrobeLineDelay", 0); - camera.setIntegerFeature("StrobeLinePreDelay", 0); - } - } catch { - console.warn("[industrial-camera] Standard Strobe features missing, relying on LineSource = ExposureActive"); - } - } - - try { - camera.setStringFeature("ExposureAuto", exposureAuto); - if (exposureAuto === "Off") { - camera.setExposureTime(exposure); - } - } catch { - /* ignore */ - } - - try { - camera.setStringFeature("GainAuto", gainAuto); - if (gainAuto === "Off") { - camera.setGain(gain); - } - } catch { - /* ignore */ - } - - if (settings.frameRate) { - try { - camera.setBooleanFeature("AcquisitionFrameRateEnable", true); - camera.setFrameRate(Number(settings.frameRate)); - } catch { - /* ignore */ - } - } - if (settings.cameraWidth) { - try { camera.setIntegerFeature("Width", Number(settings.cameraWidth)); } catch { /* ignore */ } - } - if (settings.cameraHeight) { - try { camera.setIntegerFeature("Height", Number(settings.cameraHeight)); } catch { /* ignore */ } - } - if (settings.blackLevel !== undefined && settings.blackLevel !== null && settings.blackLevel.toString() !== "") { - try { camera.setIntegerFeature("BlackLevel", Number(settings.blackLevel)); } catch { /* ignore */ } - } - - stream = camera.createStream(5); - stream.startAcquisition(); - - isConnected = true; - console.log(`[industrial-camera] Connected: ${camera.vendor} ${camera.model} (${camera.serialNumber})`); - notifyStatus(); - - } catch (e) { - console.error("[industrial-camera] Init failed:", e); - disconnectCamera(); - } -} - -export function disconnectCamera() { - if (stream) { - try { stream.stopAcquisition(); } catch { /* ignore */ } - try { stream.dispose(); } catch { /* ignore */ } - stream = null; - } - if (camera) { - try { camera.dispose(); } catch { /* ignore */ } - camera = null; - } - isConnected = false; - notifyStatus(); -} - -export function getCameraStatus() { - return { - connected: isConnected, - vendor: camera ? camera.vendor : null, - model: camera ? camera.model : null, - serial: camera ? camera.serialNumber : null, - }; -} - -export function setExposure(value: number) { - if (!camera || !isConnected) return; - try { - camera.setExposureTime(value); - } catch (e) { - console.error("[industrial-camera] setExposure failed", e); - } -} - -export function setGain(value: number) { - if (!camera || !isConnected) return; - try { - camera.setGain(value); - } catch (e) { - console.error("[industrial-camera] setGain failed", e); - } -} - -export async function captureFrame(): Promise { - if (!camera || !stream || !isConnected) { - console.warn("[industrial-camera] captureFrame: not connected"); - return null; - } - - try { - let staleBuffer; - while ((staleBuffer = stream.tryPopBuffer()) !== null) { - console.warn("[industrial-camera] Discarding stale frame before new capture"); - stream.pushBuffer(staleBuffer); - } - - if (camera.isFeatureAvailable("TriggerSoftware")) { - camera.executeCommand("TriggerSoftware"); - } - - // 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"); - return null; - } - - const w = buffer.width; - const h = buffer.height; - const fmt = buffer.pixelFormatName; - const data = buffer.copyData(); - - stream.pushBuffer(buffer); - - let sharpInst; - if (fmt === "RGB8" || fmt === "RGB8Packed") { - sharpInst = sharp(data, { raw: { width: w, height: h, channels: 3 } }); - } else if (fmt === "Mono8") { - sharpInst = sharp(data, { raw: { width: w, height: h, channels: 1 } }); - } else { - sharpInst = sharp(data, { raw: { width: w, height: h, channels: 1 } }); - } - - const pngBuffer = await sharpInst.png().toBuffer(); - return pngBuffer.toString("base64"); - - } catch (e) { - console.error("[industrial-camera] Capture frame failed:", e); - return null; - } -} - -export function applyMfsConfig(mfsContent: string, saveAsDefault: boolean): { applied: string[], failed: string[] } { - if (!camera || !isConnected) return { applied: [], failed: [] }; - const result = camera.applyMfsConfig(mfsContent); - if (saveAsDefault) { - try { - camera.saveUserSet("UserSet1", true); - } catch (e) { - console.warn("Failed to save UserSet", e); - } - } - return result; -} - -let setupStreamLoopActive = false; - -export async function startSetupStream(pushFrame: (base64: string) => void) { - if (!camera || !stream || !isConnected) return; - setupStreamLoopActive = true; - - try { stream.stopAcquisition(); } catch { /* ignore */ } - - try { camera.setIntegerFeature("StrobeEnable", 0); } catch { /* ignore */ } - try { camera.setStringFeature("TriggerMode", "Off"); } catch { /* ignore */ } - 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 */ } - - try { camera.setBooleanFeature("StrobeEnable", false); } catch { - try { camera.setIntegerFeature("StrobeEnable", 0); } catch { /* ignore */ } - } - - if (camera.isFeatureAvailable("LineSelector")) { - for (const line of ["Line1", "Line2"]) { - try { - camera.setStringFeature("LineSelector", line); - camera.setStringFeature("LineSource", "Off"); - } catch { /* ignore */ } - } - } - - try { stream.startAcquisition(); } catch { /* ignore */ } - - pumpSetupFrames(pushFrame); -} - -async function pumpSetupFrames(pushFrame: (base64: string) => void) { - let isProcessing = false; - - while (setupStreamLoopActive && stream && camera) { - try { - // 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; - const data = buffer.copyData(); - stream.pushBuffer(buffer); - - let sharpInst; - if (fmt === "RGB8" || fmt === "RGB8Packed") { - sharpInst = sharp(data, { raw: { width: w, height: h, channels: 3 } }); - } else { - sharpInst = sharp(data, { raw: { width: w, height: h, channels: 1 } }); - } - - // 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)); - } - } -} - -export function stopSetupStream() { - setupStreamLoopActive = false; - if (!camera || !stream || !isConnected) return; - - try { stream.stopAcquisition(); } catch { /* ignore */ } - - 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 */ } - try { camera.setStringFeature("ExposureAuto", exposureAuto); } catch { /* ignore */ } - - try { camera.setBooleanFeature("StrobeEnable", true); } catch { - try { camera.setIntegerFeature("StrobeEnable", 1); } catch { /* ignore */ } - } - - if (camera.isFeatureAvailable("LineSelector")) { - try { camera.setStringFeature("LineSelector", "Line1"); } catch { /* ignore */ } - try { camera.setStringFeature("LineSource", "ExposureActive"); } catch { /* ignore */ } - } - - if (gainAuto === "Off") { - try { camera.setGain(Number(settings.cameraGain) || 0); } catch { /* ignore */ } - } - if (exposureAuto === "Off") { - try { camera.setExposureTime(Number(settings.cameraExposure) || 5000); } catch { /* ignore */ } - } - - // Restore configured frame rate - if (settings.frameRate) { - try { - camera.setBooleanFeature("AcquisitionFrameRateEnable", true); - camera.setFrameRate(Number(settings.frameRate)); - } catch { /* ignore */ } - } else { - try { - camera.setBooleanFeature("AcquisitionFrameRateEnable", false); - } catch { /* ignore */ } - } - - try { stream.startAcquisition(); } catch { /* ignore */ } -} - -export function setPixelFormat(format: string) { - if (!camera || !isConnected) return; - - const wasAcquiring = !!stream; - if (wasAcquiring) { - try { stream!.stopAcquisition(); } catch { /* ignore */ } - } - - if (format === "Color") { - const fallbacks = ["BayerBG8", "BayerRG8", "BayerGR8", "BayerGB8", "RGB8Packed", "RGB8"]; - let success = false; - for (const fmt of fallbacks) { - try { - camera.setStringFeature("PixelFormat", fmt); - console.log(`[industrial-camera] Set PixelFormat to ${fmt}`); - success = true; - break; - } catch { /* ignore */ } - } - if (!success) { - console.error("[industrial-camera] Failed to set PixelFormat for Color. No formats accepted."); - } - } else { - try { - camera.setStringFeature("PixelFormat", "Mono8"); - console.log(`[industrial-camera] Set PixelFormat to Mono8`); - } catch (e) { - console.error("[industrial-camera] Failed to set PixelFormat to Mono8", e); - } - } - - if (wasAcquiring) { - try { stream!.startAcquisition(); } catch { /* ignore */ } - } -} - -export function getPixelFormat(): string { - if (!camera || !isConnected) return "Mono"; - try { - const fmt = camera.getStringFeature("PixelFormat"); - return (fmt.startsWith("Bayer") || fmt.startsWith("RGB")) ? "Color" : "Mono"; - } catch { - return "Mono"; - } -} - -export function setStrobeDuration(value: number) { - if (!camera || !isConnected) return; - try { - camera.setIntegerFeature("StrobeLineDuration", value); - } catch (e) { - console.error("Failed to set StrobeLineDuration", e); - } -} - -export function setCameraFeatureStr(feature: string, value: string) { - if (!camera || !isConnected) return; - try { camera.setStringFeature(feature, value); } catch (e) { console.error(`Failed to set ${feature}`, e); } -} - -export function setCameraFeatureInt(feature: string, value: number) { - if (!camera || !isConnected) return; - try { camera.setIntegerFeature(feature, value); } catch (e) { console.error(`Failed to set ${feature}`, e); } -} diff --git a/headless/src/server/mock/serial.ts b/headless/src/server/mock/serial.ts deleted file mode 100644 index 5197403..0000000 --- a/headless/src/server/mock/serial.ts +++ /dev/null @@ -1,96 +0,0 @@ -import type { PortInfo, SerialStatusPayload } from "../../shared/types"; - -// ─── State ──────────────────────────────────────────────────────────────────── - -let pushToView: ((payload: SerialStatusPayload) => void) | null = null; -let connected = false; -let autoFireTimer: ReturnType | null = null; - -const MOCK_PORT_PATH = "/dev/mock-speedcamera"; - -// ─── Serial API (mirrors src/server/serial.ts) ──────────────────────────────── - -let onSpeeding: ((msg: unknown) => void) | null = null; - -export function initSerial( - push: (payload: SerialStatusPayload) => void, - onSpeedingCapture?: (msg: unknown) => void -): void { - pushToView = push; - onSpeeding = onSpeedingCapture || null; - console.log("[mock/serial] Initialized"); -} - -export async function listPorts(): Promise { - return [{ path: MOCK_PORT_PATH, manufacturer: "Speedcamera Mock" }]; -} - -export async function openPort(_portPath: string): Promise { - if (connected) return; - console.debug(`[mock/serial] openPort called with path: ${_portPath}`); - connected = true; - console.log("[mock/serial] Port opened"); - pushToView?.({ status: "CONNECTED" }); -} - -export async function closePort(): Promise { - if (!connected) return; - stopAutoFire(); - connected = false; - console.log("[mock/serial] Port closed"); - pushToView?.({ status: "DISCONNECTED" }); -} - -export function sendCommand(_json: string): void { - console.log("[mock/serial] sendCommand (no-op):", _json); -} - -export function isConnected(): boolean { - return connected; -} - -// ─── Mock-only API ─────────────────────────────────────────────────────────── - -export interface TriggerOptions { - speed: number; - tolerance: number; - isSpeeding: boolean; -} - -export function triggerMeasurement({ speed, tolerance, isSpeeding }: TriggerOptions): void { - if (!connected) { - console.warn("[mock/serial] triggerMeasurement called but not connected — ignoring"); - return; - } - const timestamp = Date.now(); - if (isSpeeding) { - const msg = { status: "SPEEDING", value: speed, tolerance, direction: "forward", timestamp }; - pushToView?.(msg as SerialStatusPayload); - onSpeeding?.(msg); - console.log(`[mock/serial] Triggered SPEEDING @ ${speed} km/h (tol ${tolerance})`); - } else { - pushToView?.({ status: "OK", value: speed, tolerance, direction: "forward", timestamp }); - console.log(`[mock/serial] Triggered OK @ ${speed} km/h (tol ${tolerance})`); - } -} - -export interface AutoFireOptions { - speed: number; - tolerance: number; - isSpeeding: boolean; - interval: number; -} - -export function startAutoFire(options: AutoFireOptions): void { - stopAutoFire(); - console.log(`[mock/serial] Auto-fire started: every ${options.interval}ms`); - autoFireTimer = setInterval(() => triggerMeasurement(options), options.interval); -} - -export function stopAutoFire(): void { - if (autoFireTimer !== null) { - clearInterval(autoFireTimer); - autoFireTimer = null; - console.log("[mock/serial] Auto-fire stopped"); - } -} diff --git a/headless/src/server/network.ts b/headless/src/server/network.ts deleted file mode 100644 index 34657d9..0000000 --- a/headless/src/server/network.ts +++ /dev/null @@ -1,130 +0,0 @@ -import os from "os"; - -export interface NetworkInterfaceDetail { - name: string; - role: "camera-lan" | "hotspot-ap" | "other" | "loopback"; - address: string; - family: string; - netmask: string; - mac: string; - expectedIp?: string; - isConfigured: boolean; -} - -export interface SystemNetworkSummary { - cameraLan: { - interfaceName: string | null; - ip: string | null; - expectedIp: "192.168.1.100"; - subnet: "192.168.1.0/24"; - status: "ok" | "ip_mismatch" | "missing"; - description: string; - }; - hotspotAp: { - interfaceName: string | null; - ip: string | null; - expectedIp: "192.168.4.1"; - subnet: "192.168.4.0/24"; - status: "ok" | "ip_mismatch" | "missing"; - description: string; - }; - interfaces: NetworkInterfaceDetail[]; -} - -export function getSystemNetworkSummary(): SystemNetworkSummary { - const rawInterfaces = os.networkInterfaces(); - const interfaceList: NetworkInterfaceDetail[] = []; - - let cameraEthIface: { name: string; address: string; netmask: string; mac: string } | null = null; - let wifiHotspotIface: { name: string; address: string; netmask: string; mac: string } | null = null; - - for (const [name, addrs] of Object.entries(rawInterfaces)) { - if (!addrs) continue; - for (const addr of addrs) { - if (addr.family !== "IPv4") continue; - - const isLoopback = addr.internal || addr.address.startsWith("127."); - const isCameraSubnet = addr.address === "192.168.1.100" || addr.address.startsWith("192.168.1."); - const isHotspotSubnet = addr.address === "192.168.4.1" || addr.address.startsWith("192.168.4."); - const isEthName = /^(eth|end|enp|eno|enx)/i.test(name); - const isWifiName = /^(wlan|wifi|wlp|wlx)/i.test(name); - - let role: "camera-lan" | "hotspot-ap" | "other" | "loopback" = "other"; - let expectedIp: string | undefined = undefined; - - if (isLoopback) { - role = "loopback"; - } else if (isCameraSubnet || isEthName) { - role = "camera-lan"; - expectedIp = "192.168.1.100"; - if (!cameraEthIface || addr.address === "192.168.1.100") { - cameraEthIface = { name, address: addr.address, netmask: addr.netmask, mac: addr.mac }; - } - } else if (isHotspotSubnet || isWifiName) { - role = "hotspot-ap"; - expectedIp = "192.168.4.1"; - if (!wifiHotspotIface || addr.address === "192.168.4.1") { - wifiHotspotIface = { name, address: addr.address, netmask: addr.netmask, mac: addr.mac }; - } - } - - interfaceList.push({ - name, - role, - address: addr.address, - family: addr.family, - netmask: addr.netmask, - mac: addr.mac, - expectedIp, - isConfigured: expectedIp ? addr.address === expectedIp : true, - }); - } - } - - // Determine Camera LAN (eth0: 192.168.1.100) status - const cameraStatus: "ok" | "ip_mismatch" | "missing" = !cameraEthIface - ? "missing" - : cameraEthIface.address === "192.168.1.100" - ? "ok" - : "ip_mismatch"; - - // Determine Wi-Fi Hotspot (wlan0/wifi0: 192.168.4.1) status - const hotspotStatus: "ok" | "ip_mismatch" | "missing" = !wifiHotspotIface - ? "missing" - : wifiHotspotIface.address === "192.168.4.1" - ? "ok" - : "ip_mismatch"; - - return { - cameraLan: { - interfaceName: cameraEthIface ? cameraEthIface.name : null, - ip: cameraEthIface ? cameraEthIface.address : null, - expectedIp: "192.168.1.100", - subnet: "192.168.1.0/24", - status: cameraStatus, - description: "Dedicated GigE Vision Industrial Camera LAN (eth0/end0)", - }, - hotspotAp: { - interfaceName: wifiHotspotIface ? wifiHotspotIface.name : null, - ip: wifiHotspotIface ? wifiHotspotIface.address : null, - expectedIp: "192.168.4.1", - subnet: "192.168.4.0/24", - status: hotspotStatus, - description: "Wi-Fi Access Point & Remote Web UI Control (wlan0/wifi0)", - }, - interfaces: interfaceList, - }; -} - -export function logNetworkStatus(): void { - const summary = getSystemNetworkSummary(); - console.log("─────────────────────────────────────────────────────────────────"); - console.log(" Network Interfaces & Subnet Configuration:"); - console.log( - ` • Camera LAN [${summary.cameraLan.interfaceName || "eth0"}]: ${summary.cameraLan.ip || "Not configured"} (Expected: 192.168.1.100, Subnet: 192.168.1.0/24) -> [${summary.cameraLan.status.toUpperCase()}]` - ); - console.log( - ` • Hotspot AP [${summary.hotspotAp.interfaceName || "wlan0/wifi0"}]: ${summary.hotspotAp.ip || "Not configured"} (Expected: 192.168.4.1, Web UI: http://${summary.hotspotAp.ip || "192.168.4.1"}:3000) -> [${summary.hotspotAp.status.toUpperCase()}]` - ); - console.log("─────────────────────────────────────────────────────────────────"); -} diff --git a/headless/src/server/rpc.ts b/headless/src/server/rpc.ts deleted file mode 100644 index 97a7e81..0000000 --- a/headless/src/server/rpc.ts +++ /dev/null @@ -1,68 +0,0 @@ -import type { ServerWebSocket } from "bun"; -import type { SpeedcameraRPC } from "../shared/types"; - -export type RequestHandlers = { - [K in keyof SpeedcameraRPC["bun"]["requests"]]: ( - params: SpeedcameraRPC["bun"]["requests"][K]["params"] - ) => Promise | SpeedcameraRPC["bun"]["requests"][K]["response"]; -}; - -export type PushMessages = SpeedcameraRPC["webview"]["messages"]; - -export class RpcServer { - private sockets = new Set>(); - private handlers: RequestHandlers; - - constructor(handlers: RequestHandlers) { - this.handlers = handlers; - } - - public registerSocket(ws: ServerWebSocket) { - this.sockets.add(ws); - } - - public unregisterSocket(ws: ServerWebSocket) { - this.sockets.delete(ws); - } - - public async handleMessage(ws: ServerWebSocket, message: string | Buffer) { - let msgStr = typeof message === "string" ? message : message.toString("utf-8"); - let parsed: any; - try { - parsed = JSON.parse(msgStr); - } catch { - ws.send(JSON.stringify({ error: "Invalid JSON" })); - return; - } - - const { id, method, params } = parsed; - if (!id || !method) { - return; - } - - const handler = (this.handlers as any)[method]; - if (!handler) { - ws.send(JSON.stringify({ id, error: `Method '${method}' not found` })); - return; - } - - try { - const result = await handler(params ?? {}); - ws.send(JSON.stringify({ id, result: result !== undefined ? result : null })); - } catch (err: any) { - console.error(`[rpc] Error executing method '${method}':`, err); - ws.send(JSON.stringify({ id, error: err?.message || String(err) })); - } - } - - public broadcast(event: K, payload: PushMessages[K]) { - const data = JSON.stringify({ event, payload }); - for (const ws of this.sockets) { - try { - ws.send(data); - } catch (err) { - console.error("[rpc] Failed to push to socket:", err); - } - } - } -} diff --git a/headless/src/server/serial.ts b/headless/src/server/serial.ts deleted file mode 100644 index f426b3a..0000000 --- a/headless/src/server/serial.ts +++ /dev/null @@ -1,184 +0,0 @@ -import { SerialPort, list, readlineParser } from "bun-serialport"; -import type { PortInfo, SerialStatusPayload } from "../shared/types"; -import { EspMessageSchema, EspCommandSchema, type EspMessage } from "../shared/schemas"; - -// ─── State ──────────────────────────────────────────────────────────────────── - -let activePort: SerialPort | null = null; -let pushToView: ((payload: SerialStatusPayload) => void) | null = null; -let onSpeeding: ((msg: EspMessage) => void) | null = null; - -// ─── Initialization ─────────────────────────────────────────────────────────── - -export function initSerial( - push: (payload: SerialStatusPayload) => void, - onSpeedingCapture?: (msg: EspMessage) => void -): void { - pushToView = push; - onSpeeding = onSpeedingCapture || null; -} - -// ─── Public API ─────────────────────────────────────────────────────────────── - -export async function listPorts(): Promise { - return list(); -} - -export async function openPort(portPath: string): Promise { - if (activePort?.isOpen) { - await closePort(); - } - - const port = new SerialPort({ - path: portPath, - baudRate: 115200, - autoOpen: false, - }); - - const parser = port.pipe(readlineParser()); - - parser.on("data", (line: string) => { - handleIncoming(line.trim()); - }); - - port.on("error", (err: Error) => { - console.error(`[serial] Port error on ${portPath}:`, err); - }); - - port.on("close", () => { - console.log(`[serial] Port ${portPath} closed`); - activePort = null; - pushToView?.({ status: "DISCONNECTED" }); - }); - - await port.open(); - - activePort = port; - console.log(`[serial] Opened ${portPath}`); - pushToView?.({ status: "CONNECTED" }); -} - -export async function closePort(): Promise { - if (!activePort) return; - await activePort.close(); -} - -export function sendCommand(json: string): void { - if (!activePort?.isOpen) { - console.warn("[serial] sendCommand called but no port is open"); - return; - } - - let parsed: unknown; - try { - parsed = JSON.parse(json); - } catch { - console.error("[serial] sendCommand: invalid JSON:", json); - return; - } - - const validation = EspCommandSchema.safeParse(parsed); - if (!validation.success) { - console.error("[serial] sendCommand: invalid command schema:", validation.error.issues); - return; - } - - activePort.write(json + "\n").catch((err: Error) => { - console.error("[serial] Write error:", err); - }); - console.debug("[serial] Sent command:", json); -} - -export function isConnected(): boolean { - return activePort?.isOpen === true; -} - -// ─── Incoming data parser ───────────────────────────────────────────────────── - -function handleIncoming(raw: string): void { - const timestamp = Date.now(); - console.log("[serial] Received:", raw); - - let parsed: unknown; - try { - parsed = JSON.parse(raw); - } catch { - console.warn("[serial] Non-JSON data received:", raw); - return; - } - - if (typeof parsed === "object" && parsed !== null && "debug" in parsed) { - console.debug("[serial] ESP debug:", (parsed as Record).debug); - return; - } - - const result = EspMessageSchema.safeParse(parsed); - if (!result.success) { - console.warn("[serial] Schema validation failed:", result.error.issues, "raw:", raw); - return; - } - - const msg = result.data; - - switch (msg.status) { - case "speeding": - pushToView?.({ - status: "SPEEDING", - value: msg.value, - tolerance: msg.tolerance, - direction: msg.direction, - timestamp, - }); - onSpeeding?.(msg); - break; - - case "legal": - pushToView?.({ - status: "OK", - value: msg.value, - tolerance: msg.tolerance, - direction: msg.direction, - timestamp, - }); - break; - - case "pong": - pushToView?.({ status: "PONG", config: msg.config }); - break; - - case "lapStart": - pushToView?.({ - status: "LAPSTART", - lapNumber: msg.lapNumber, - speedAtStart: msg.speedAtStart, - timestamp, - }); - break; - - case "lapEnd": - pushToView?.({ - status: "LAPEND", - lapNumber: msg.lapNumber, - durationMs: msg.durationMs, - speedAtStart: msg.speedAtStart, - speedAtEnd: msg.speedAtEnd, - timestamp, - }); - break; - - case "lapWaiting": - pushToView?.({ status: "LAPWAITING" }); - break; - - case "lapStopped": - pushToView?.({ status: "LAPSTOPPED" }); - break; - - case "configError": - console.warn("[serial] ESP config error:", msg.message); - break; - - default: - break; - } -} diff --git a/headless/src/server/skin-renderer.ts b/headless/src/server/skin-renderer.ts deleted file mode 100644 index 19c4823..0000000 --- a/headless/src/server/skin-renderer.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { createCanvas, loadImage } from "@napi-rs/canvas"; -import type { Violation } from "../shared/types"; - -const SYSTEM_NR = "PS-847291"; - -const TOP_BAR_H = 40; -const BOTTOM_BAR_H = 30; -const FONT = "bold 13px monospace"; -const FONT_SM = "12px monospace"; -const LABEL_FONT = "11px monospace"; - -/** - * Render a Vitronic Poliscan-style skin on a violation image. - * Returns a PNG buffer. Source image is NOT modified. - */ -export async function renderPoliscanSkin( - imagePath: string, - violation: Violation, - opts: { measuringLocation: string }, -): Promise { - const src = await loadImage(imagePath); - const w = src.width; - const totalH = src.height + TOP_BAR_H + BOTTOM_BAR_H; - - const canvas = createCanvas(w, totalH); - const ctx = canvas.getContext("2d"); - - // ── Top bar ───────────────────────────────────────────────────────────────── - ctx.fillStyle = "#000"; - ctx.fillRect(0, 0, w, TOP_BAR_H); - - // Labels row (y ~12) - ctx.fillStyle = "#aaa"; - ctx.font = LABEL_FONT; - const labelY = 13; - ctx.fillText("Datum / Zeit", 10, labelY); - ctx.fillText("Limit PKW", 260, labelY); - ctx.fillText("Geschw.", 400, labelY); - ctx.fillText("Richtung", 530, labelY); - - // Values row (y ~32) - ctx.fillStyle = "#fff"; - ctx.font = FONT; - const valY = 32; - - const ts = new Date(violation.timestamp); - const dateStr = ts.toLocaleDateString("de-DE", { - day: "2-digit", month: "2-digit", year: "numeric", - }); - const timeStr = ts.toLocaleTimeString("de-DE", { - hour: "2-digit", minute: "2-digit", second: "2-digit", - }); - ctx.fillText(`${dateStr} ${timeStr}`, 10, valY); - ctx.fillText(`${violation.maxSpeed} km/h`, 260, valY); - ctx.fillText(`${violation.measuredSpeed} km/h`, 400, valY); - - const dirText = violation.direction === "forward" ? "abgehend" : "ankommend"; - ctx.fillText(dirText, 530, valY); - - // ── Source image ──────────────────────────────────────────────────────────── - ctx.drawImage(src, 0, TOP_BAR_H); - - // ── Bottom bar ────────────────────────────────────────────────────────────── - const bottomY = TOP_BAR_H + src.height; - ctx.fillStyle = "#000"; - ctx.fillRect(0, bottomY, w, BOTTOM_BAR_H); - - ctx.fillStyle = "#aaa"; - ctx.font = LABEL_FONT; - const bLabelY = bottomY + 11; - ctx.fillText("System", 10, bLabelY); - ctx.fillText("Bildnummer", 200, bLabelY); - ctx.fillText("Ort", 420, bLabelY); - - ctx.fillStyle = "#fff"; - ctx.font = FONT_SM; - const bValY = bottomY + 24; - ctx.fillText(SYSTEM_NR, 10, bValY); - - const imgNr = `${SYSTEM_NR.replace("PS-", "")} - ${String(violation.id).padStart(3, "0")} - 1`; - ctx.fillText(imgNr, 200, bValY); - ctx.fillText(opts.measuringLocation || "—", 420, bValY); - - return Buffer.from(canvas.toBuffer("image/png")); -} diff --git a/headless/src/server/teable.ts b/headless/src/server/teable.ts deleted file mode 100644 index 930fa74..0000000 --- a/headless/src/server/teable.ts +++ /dev/null @@ -1,252 +0,0 @@ -import { getSettings, saveSetting } from "./database"; -import type { Lap, LapSession, TeableUser, TeableSpace, TeableBase, TeableTable, TeableSchemaCheck } from "../shared/types"; - -// ─── Required fields for the Laps table ────────────────────────────────────── - -interface RequiredField { - name: string; - type: string; -} - -const REQUIRED_FIELDS: RequiredField[] = [ - { 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" }, -]; - -// ─── Helpers ────────────────────────────────────────────────────────────────── - -const FETCH_OPTS = { tls: { rejectUnauthorized: false } } as RequestInit; - -function buildHeaders(token: string): Record { - return { - "Authorization": `Bearer ${token}`, - "Content-Type": "application/json", - }; -} - -function apiFetch(url: string, init?: RequestInit): Promise { - return fetch(url, { ...FETCH_OPTS, ...init, headers: { ...init?.headers } }); -} - -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")}`; -} - -function getConfig(): { url: string; token: string } { - const settings = getSettings(); - const url = settings.teableUrl.replace(/\/+$/, ""); - const token = settings.teableToken; - if (!url) throw new Error("Teable not configured"); - if (!token) throw new Error("Teable token not found"); - return { url, token }; -} - -// ─── Connection test ────────────────────────────────────────────────────────── - -export async function testTeableConnection(url: string, token: string): Promise { - const base = url.replace(/\/+$/, ""); - - let spacesResp: Response; - try { - spacesResp = await apiFetch(`${base}/api/space`, { headers: buildHeaders(token) }); - } catch (e) { - throw new Error(`Could not connect to ${base} — check the URL and your network connection. Details: ${String(e)}`); - } - - if (spacesResp.status === 401) { - throw new Error("Invalid or expired access token. Please check your Personal Access Token."); - } - if (!spacesResp.ok) { - const body = await spacesResp.text().catch(() => ""); - throw new Error(`Teable API returned ${spacesResp.status} — ${body}`); - } - - let user: TeableUser = { id: "", name: "Teable User", email: "", avatar: null }; - try { - const userResp = await apiFetch(`${base}/api/auth/user/me`, { headers: buildHeaders(token) }); - if (userResp.ok) { - const data = await userResp.json() as { id?: string; name?: string; email?: string; avatar?: string }; - user = { - id: data.id ?? "", - name: data.name ?? "Teable User", - email: data.email ?? "", - avatar: data.avatar ?? null, - }; - } - } catch { - // Fallback - } - - return user; -} - -// ─── Config management ──────────────────────────────────────────────────────── - -export function saveTeableConfig( - url: string, - token: string, - userName: string, - userEmail: string, - userAvatar: string | null, -): void { - saveSetting("teableUrl", url); - saveSetting("teableToken", token); - saveSetting("teableUserName", userName); - saveSetting("teableUserEmail", userEmail); - saveSetting("teableUserAvatar", userAvatar ?? ""); -} - -export function removeTeableConfig(): void { - saveSetting("teableUrl", ""); - saveSetting("teableToken", ""); - saveSetting("teableUserName", ""); - saveSetting("teableUserEmail", ""); - saveSetting("teableUserAvatar", ""); - saveSetting("teableSpaceId", ""); - saveSetting("teableBaseId", ""); - saveSetting("teableTableId", ""); - saveSetting("teableSyncEnabled", "false"); -} - -export function saveTeableTarget(spaceId: string, baseId: string, tableId: string): void { - saveSetting("teableSpaceId", spaceId); - saveSetting("teableBaseId", baseId); - saveSetting("teableTableId", tableId); -} - -// ─── Spaces / Bases / Tables ────────────────────────────────────────────────── - -export async function listTeableSpaces(): Promise { - const { url, token } = getConfig(); - const resp = await apiFetch(`${url}/api/space`, { headers: buildHeaders(token) }); - if (!resp.ok) throw new Error(`Failed to fetch spaces: ${resp.status}`); - return resp.json() as Promise; -} - -export async function listTeableBases(spaceId: string): Promise { - const { url, token } = getConfig(); - const resp = await apiFetch(`${url}/api/space/${encodeURIComponent(spaceId)}/base`, { - headers: buildHeaders(token), - }); - if (!resp.ok) throw new Error(`Failed to fetch bases: ${resp.status}`); - return resp.json() as Promise; -} - -export async function listTeableTables(baseId: string): Promise { - const { url, token } = getConfig(); - const resp = await apiFetch(`${url}/api/base/${encodeURIComponent(baseId)}/table`, { - headers: buildHeaders(token), - }); - if (!resp.ok) throw new Error(`Failed to fetch tables: ${resp.status}`); - return resp.json() as Promise; -} - -// ─── Schema verification & provisioning ────────────────────────────────────── - -async function listFields(url: string, token: string, tableId: string): Promise> { - const resp = await apiFetch(`${url}/api/table/${encodeURIComponent(tableId)}/field`, { - headers: buildHeaders(token), - }); - if (!resp.ok) throw new Error(`Failed to fetch fields: ${resp.status}`); - return resp.json() as Promise>; -} - -export async function verifyTeableTable(tableId: string): Promise { - const { url, token } = getConfig(); - const fields = await listFields(url, token, tableId); - const existing = new Set(fields.map((f) => f.name)); - const missingFields = REQUIRED_FIELDS.filter((f) => !existing.has(f.name)).map((f) => f.name); - return { missingFields }; -} - -export async function ensureTeableFields(tableId: string): Promise { - const { url, token } = getConfig(); - const fields = await listFields(url, token, tableId); - const existing = new Set(fields.map((f) => f.name)); - - const created: string[] = []; - for (const field of REQUIRED_FIELDS) { - if (existing.has(field.name)) continue; - - const resp = await apiFetch(`${url}/api/table/${encodeURIComponent(tableId)}/field`, { - method: "POST", - headers: buildHeaders(token), - body: JSON.stringify({ type: field.type, name: field.name }), - }); - - if (!resp.ok) { - const body = await resp.text().catch(() => ""); - throw new Error(`Failed to create field '${field.name}': ${resp.status} — ${body}`); - } - created.push(field.name); - } - - return created; -} - -export async function createTeableTable(baseId: string, tableName: string): Promise { - const { url, token } = getConfig(); - - const resp = await apiFetch(`${url}/api/base/${encodeURIComponent(baseId)}/table`, { - method: "POST", - headers: buildHeaders(token), - body: JSON.stringify({ - name: tableName, - fields: REQUIRED_FIELDS.map((f) => ({ type: f.type, name: f.name })), - }), - }); - - if (!resp.ok) { - const body = await resp.text().catch(() => ""); - throw new Error(`Failed to create table: ${resp.status} — ${body}`); - } - - const data = await resp.json() as { id: string; name: string }; - return { id: data.id, name: data.name }; -} - -// ─── Lap sync ───────────────────────────────────────────────────────────────── - -export async function syncLapToTeable(lap: Lap, session: LapSession): Promise { - const { url, token } = getConfig(); - const settings = getSettings(); - const tableId = settings.teableTableId; - if (!tableId) throw new Error("No Teable table selected"); - - const fields: Record = { - "Session Started At": session.startedAt, - "Lap Mode": session.lapMode, - "Lap Number": lap.lapNumber, - "Start Time": new Date(lap.startTimestamp).toISOString(), - "End Time": new Date(lap.endTimestamp).toISOString(), - "Duration": formatDuration(lap.durationMs), - "Speed At Start": lap.speedAtStart, - "Speed At End": lap.speedAtEnd, - }; - - const resp = await apiFetch(`${url}/api/table/${encodeURIComponent(tableId)}/record`, { - method: "POST", - headers: buildHeaders(token), - body: JSON.stringify({ - fieldKeyType: "name", - typecast: true, - records: [{ fields }], - }), - }); - - if (!resp.ok) { - const body = await resp.text().catch(() => ""); - throw new Error(`Failed to create Teable record: ${resp.status} — ${body}`); - } -} diff --git a/headless/src/shared/schemas.ts b/headless/src/shared/schemas.ts deleted file mode 100644 index a3a34a9..0000000 --- a/headless/src/shared/schemas.ts +++ /dev/null @@ -1,99 +0,0 @@ -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/src/shared/types.ts b/headless/src/shared/types.ts deleted file mode 100644 index e2dc204..0000000 --- a/headless/src/shared/types.ts +++ /dev/null @@ -1,548 +0,0 @@ -// ─── Domain Types ─────────────────────────────────────────────────────────── - -export interface NetworkInterfaceDetail { - name: string; - role: "camera-lan" | "hotspot-ap" | "other" | "loopback"; - address: string; - family: string; - netmask: string; - mac: string; - expectedIp?: string; - isConfigured: boolean; -} - -export interface SystemNetworkSummary { - cameraLan: { - interfaceName: string | null; - ip: string | null; - expectedIp: "192.168.1.100"; - subnet: "192.168.1.0/24"; - status: "ok" | "ip_mismatch" | "missing"; - description: string; - }; - hotspotAp: { - interfaceName: string | null; - ip: string | null; - expectedIp: "192.168.4.1"; - subnet: "192.168.4.0/24"; - status: "ok" | "ip_mismatch" | "missing"; - description: string; - }; - interfaces: NetworkInterfaceDetail[]; -} - -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; -} - -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" } - | { 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 }; - response: string; // data-URL or path - }; - getSkinnedImageData: { - params: { violationId: number }; - response: string; // data-URL or URL of skinned image - }; - exportSkinnedImages: { - params: { violationIds: number[]; targetDir: string }; - response: { exported: number; failed: number }; - }; - - // DB – settings - getSettings: { - params: Record; - response: AppSettings; - }; - saveSetting: { - params: { key: keyof AppSettings; value: string }; - response: void; - }; - - // Serial - listPorts: { - params: Record; - response: PortInfo[]; - }; - 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; - }; - - // 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, { - // Bun pushes serial measurement updates to the view - serialStatus: SerialStatusPayload; - // Bun pushes camera connection status to the view - cameraStatus: CameraStatusPayload; - // Bun notifies the view that a new app version is ready to install - updateAvailable: { version: string }; - // Bun streams updater status events to the view - updateProgress: { - status: string; - message: string; - progress?: number; - }; - // Bun streams esptool progress events to the view - flashProgress: FlashProgressPayload; - // Push setup live stream frame - liveFrame: string; - }>; -}; diff --git a/headless/src/stores/slices/cameraSlice.ts b/headless/src/stores/slices/cameraSlice.ts deleted file mode 100644 index 69fc04e..0000000 --- a/headless/src/stores/slices/cameraSlice.ts +++ /dev/null @@ -1,128 +0,0 @@ -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; -} - -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, - setCameraStatus: (status) => set({ - cameraConnected: status.connected, - cameraVendor: status.vendor, - cameraModel: status.model, - cameraSerial: status.serial, - }), - - 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, - }); - }, - - 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 { - 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/src/stores/slices/flasherSlice.ts b/headless/src/stores/slices/flasherSlice.ts deleted file mode 100644 index c0d670c..0000000 --- a/headless/src/stores/slices/flasherSlice.ts +++ /dev/null @@ -1,38 +0,0 @@ -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/src/stores/slices/lapSlice.ts b/headless/src/stores/slices/lapSlice.ts deleted file mode 100644 index aba2102..0000000 --- a/headless/src/stores/slices/lapSlice.ts +++ /dev/null @@ -1,262 +0,0 @@ -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 { 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; - -// ─── Helpers ────────────────────────────────────────────────────────────────── -// Removed grabFrame (using bun side captureFrame) -// ─── Slice ──────────────────────────────────────────────────────────────────── - -export const createLapSlice: StateCreator< - LapSlice & CameraSlice & TeableSlice, - [], - [], - 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", - }); - // 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, - // Keep currentLaps so the UI can show the final session summary - }); - }, - - // ── State machine ────────────────────────────────────────────────────────── - - handleSerialStatusForLap: (payload) => { - // ── LAPSTART: first car pass — firmware opened a new lap ────────────────── - if (payload.status === "LAPSTART") { - const { lapState, lapSettings } = get(); - - // Accept "waiting" (first lap) or "timing" (MULTI lap N+1 boundary) - const isMultiContinuation = lapState === "timing" && lapSettings.lapMode === "multi"; - if (lapState !== "waiting" && !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/src/stores/slices/measurementSlice.ts b/headless/src/stores/slices/measurementSlice.ts deleted file mode 100644 index dc1f741..0000000 --- a/headless/src/stores/slices/measurementSlice.ts +++ /dev/null @@ -1,90 +0,0 @@ -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; - } - - const { systemState, appMode } = get(); - // In PASSIVE mode, ignore all serial measurements - if (systemState === "PASSIVE") 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 - if (payload.status === "SPEEDING" || payload.status === "OK") { - set({ lastSpeed: payload.value, lastDirection: payload.direction }); - } - return; - } - - if (payload.status === "SPEEDING") { - const { value, direction } = payload; - set({ lastSpeed: value, lastDirection: direction }); - - // Only save violations and flash when fully ARMED - if (systemState !== "ARMED") return; - - const { maxSpeed } = get(); - - // Trigger bun-side capture and save - getRpc() - .request.saveViolation({ measuredSpeed: value, maxSpeed, direction }) - .then((v) => { - get().setLastViolation(v); - }) - .catch((err: unknown) => { - console.error("[measurement] Capture/save failed:", err); - toast.error("Failed to save violation"); - }); - } else if (payload.status === "OK") { - set({ lastSpeed: payload.value, lastDirection: payload.direction }); - } - // CONNECTED / DISCONNECTED handled by serialSlice indirectly via store - }, -}); diff --git a/headless/src/stores/slices/serialSlice.ts b/headless/src/stores/slices/serialSlice.ts deleted file mode 100644 index d4710ce..0000000 --- a/headless/src/stores/slices/serialSlice.ts +++ /dev/null @@ -1,22 +0,0 @@ -import type { StateCreator } from "zustand"; -import type { PortInfo } from "@/shared/types"; - -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; -} - -export const createSerialSlice: StateCreator = (set) => ({ - availablePorts: [], - selectedPort: "", - connectedPort: "", - setAvailablePorts: (ports) => set({ availablePorts: ports }), - setSelectedPort: (path) => set({ selectedPort: path }), - setConnectedPort: (path) => set({ connectedPort: path }), -}); diff --git a/headless/src/stores/slices/systemSlice.ts b/headless/src/stores/slices/systemSlice.ts deleted file mode 100644 index 8add0b7..0000000 --- a/headless/src/stores/slices/systemSlice.ts +++ /dev/null @@ -1,20 +0,0 @@ -import type { StateCreator } from "zustand"; - -export type SystemState = "PASSIVE" | "DISARMED" | "ARMED"; -export type AppMode = "speedcamera" | "laptimer"; - -export interface SystemSlice { - /** Current operational state of the speed camera system */ - systemState: SystemState; - setSystemState: (state: SystemState) => void; - /** Active mode — routes serial events to violation or lap handler */ - appMode: AppMode; - setAppMode: (mode: AppMode) => void; -} - -export const createSystemSlice: StateCreator = (set) => ({ - systemState: "PASSIVE", - setSystemState: (state) => set({ systemState: state }), - appMode: "speedcamera", - setAppMode: (mode) => set({ appMode: mode }), -}); diff --git a/headless/src/stores/slices/teableSlice.ts b/headless/src/stores/slices/teableSlice.ts deleted file mode 100644 index d457de9..0000000 --- a/headless/src/stores/slices/teableSlice.ts +++ /dev/null @@ -1,206 +0,0 @@ -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/src/stores/slices/updaterSlice.ts b/headless/src/stores/slices/updaterSlice.ts deleted file mode 100644 index 95a089b..0000000 --- a/headless/src/stores/slices/updaterSlice.ts +++ /dev/null @@ -1,82 +0,0 @@ -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; - // Map granular electrobun status to coarse UI phase - 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 }), -}); \ No newline at end of file diff --git a/headless/src/stores/useAppStore.ts b/headless/src/stores/useAppStore.ts deleted file mode 100644 index 9820e67..0000000 --- a/headless/src/stores/useAppStore.ts +++ /dev/null @@ -1,23 +0,0 @@ -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/tailwind.config.js b/headless/tailwind.config.js deleted file mode 100644 index 05e1c9a..0000000 --- a/headless/tailwind.config.js +++ /dev/null @@ -1,8 +0,0 @@ -/** @type {import('tailwindcss').Config} */ -export default { - content: ["./src/**/*.{html,js,ts,jsx,tsx}"], - theme: { - extend: {}, - }, - plugins: [], -}; diff --git a/headless/tsconfig.json b/headless/tsconfig.json deleted file mode 100644 index bc5f54f..0000000 --- a/headless/tsconfig.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "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": { - "@/*": ["./src/*"] - } - }, - "include": ["src"], - "exclude": ["node_modules", "dist"] -} diff --git a/headless/vite.config.ts b/headless/vite.config.ts deleted file mode 100644 index 5cc127b..0000000 --- a/headless/vite.config.ts +++ /dev/null @@ -1,30 +0,0 @@ -import path from "path"; -import { defineConfig } from "vite"; -import react from "@vitejs/plugin-react"; - -export default defineConfig({ - plugins: [react()], - root: "src/mainview", - resolve: { - alias: { - "@": path.resolve(__dirname, "./src"), - }, - }, - build: { - outDir: "../../dist", - emptyOutDir: true, - }, - server: { - port: 5173, - strictPort: true, - proxy: { - "/image": "http://localhost:3000", - "/skinned-image": "http://localhost:3000", - "/api": "http://localhost:3000", - "/ws": { - target: "ws://localhost:3000", - ws: true, - }, - }, - }, -}); From 20bd1cd4a38addadf9344707c9c654f0eed42c64 Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Fri, 14 Aug 2026 23:45:20 +0200 Subject: [PATCH 14/65] feat: migrate scripts to headless-rust --- README.md | 10 +- headless-rust/README.md | 288 ++++++++++++++++++---- headless-rust/package.json | 7 +- headless-rust/scripts/cleanup-pi.sh | 126 ++++++++++ headless-rust/scripts/cleanup-remote.sh | 102 ++++++++ headless-rust/scripts/deploy-to-pi.sh | 112 +++++++++ headless-rust/scripts/install-remote.sh | 144 +++++++++++ headless-rust/scripts/install-rpi.sh | 246 ++++++++++++++++++ headless-rust/scripts/setup-network.sh | 0 headless-rust/scripts/speedcamera.service | 1 + headless-rust/scripts/test-server.ts | 123 +++++++++ headless-rust/scripts/update-pi.sh | 80 ++++++ headless-rust/scripts/verify-ws.ts | 55 +++++ 13 files changed, 1235 insertions(+), 59 deletions(-) create mode 100755 headless-rust/scripts/cleanup-pi.sh create mode 100755 headless-rust/scripts/cleanup-remote.sh create mode 100755 headless-rust/scripts/deploy-to-pi.sh create mode 100755 headless-rust/scripts/install-remote.sh create mode 100755 headless-rust/scripts/install-rpi.sh mode change 100644 => 100755 headless-rust/scripts/setup-network.sh create mode 100755 headless-rust/scripts/test-server.ts create mode 100755 headless-rust/scripts/update-pi.sh create mode 100755 headless-rust/scripts/verify-ws.ts diff --git a/README.md b/README.md index 783c5b2..391bd1a 100644 --- a/README.md +++ b/README.md @@ -8,19 +8,19 @@ An end-to-end vehicle speed measurement, GigE Vision camera capture, and remote | Directory | Description | | --------- | ----------- | -| [**`headless`**](./headless) | **(Recommended)** Lightweight, high-performance headless Raspberry Pi 4/5 daemon and responsive Web UI controller built with Bun, Vite, and React. Creates standalone Wi-Fi hotspot (`192.168.4.1`) & GigE Vision Camera LAN (`192.168.1.100`). | +| [**`headless-rust`**](./headless-rust) | **(Recommended)** High-performance single-binary headless daemon and responsive Web UI controller for Raspberry Pi 5 built with Rust (Rocket 0.5, native Aravis C FFI, SQLite) and embedded React + Vite frontend. Creates standalone Wi-Fi hotspot (`192.168.4.1`) & 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) +## Quick Deployment Commands (Raspberry Pi 5) -All commands are executed from your development laptop. The React frontend is built on the laptop in ~2s (`bun run build`) and synced over SSH, avoiding slow builds on the Pi. +All deployment and maintenance commands are executed from your development laptop. The React frontend is built on the laptop in ~2s (`bun run build`) and synced over SSH to the Pi. ```bash -cd headless +cd headless-rust # 1. Fresh Pi Setup (Pi connected to Home LAN/Wi-Fi with DHCP) bun run install:pi pi@raspberrypi.local @@ -34,4 +34,4 @@ bun run deploy:pi pi@192.168.4.1 bun run cleanup:pi pi@raspberrypi.local ``` -For full documentation on architecture, network modes, offline field use, and local mock testing, see the [**Headless Documentation**](./headless/README.md). +For full documentation on architecture, network modes, offline field use, dependencies, and local mock testing, see the [**Headless Rust Documentation**](./headless-rust/README.md). diff --git a/headless-rust/README.md b/headless-rust/README.md index 32073ce..323bed5 100644 --- a/headless-rust/README.md +++ b/headless-rust/README.md @@ -1,27 +1,12 @@ # Speedcamera Headless (Rust & Rocket) -A high-performance, single-binary headless speedcamera daemon and web controller written in **Rust** using **Rocket 0.5**, **native Aravis C FFI**, **SQLite**, and embedded **React + Vite** frontend. +A lightweight, high-performance, single-binary speedcamera daemon and responsive web controller written in **Rust** using **Rocket 0.5**, **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 stability. +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. Creates a standalone Wi-Fi hotspot for laptops, tablets, and phones to connect and manage the system via web browser while communicating with industrial GigE cameras on a dedicated Ethernet subnet. --- -## 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!)** | -| **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** | - ---- - -## Architecture +## Architecture & Dual-Subnet Network Setup ``` ┌────────────────────────────────────────────────────────────────────────┐ @@ -30,14 +15,14 @@ Engineered specifically for **Raspberry Pi 5 with Raspberry Pi OS Lite** (zero d │ • eth0 (Camera LAN): 192.168.1.100/24 <── GigE Vision HIKROBOT │ │ • wlan0 (Hotspot AP): 192.168.4.1/24 <── Web UI Browser Clients │ │ │ -│ • speedcamera-rust Daemon (Single Binary) │ +│ • speedcamera-rust Daemon (Single Standalone Binary) │ │ ├── Rocket 0.5 HTTP Server (REST API & Embedded Static Frontend) │ │ ├── Rocket WS (/ws/rpc JSON-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 │ +│ └── Pure Rust Poliscan Overlay Renderer (image + imageproc) │ └───────────────────────┬─────────────────────────────▲──────────────────┘ │ Wi-Fi AP │ Ethernet Cable ▼ │ @@ -52,55 +37,263 @@ Engineered specifically for **Raspberry Pi 5 with Raspberry Pi OS Lite** (zero d --- -## Quick Start +## 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!)** | +| **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** | + +--- + +## Fresh Pi OS Requirements & Dependencies -### 1. Local Development & Testing (Mock Mode) +To set up a fresh Raspberry Pi OS image (recommended: **Raspberry Pi OS Lite 64-bit**), the following tools and packages are required. -Run on your laptop without physical camera or Arduino hardware: +> [!TIP] +> The automated installer `bun run install:pi` (or `./scripts/install-rpi.sh` directly on the Pi) automatically checks and installs all of these dependencies for you. + +### 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 \ + curl \ + unzip \ + git \ + rsync \ + sqlite3 \ + libsqlite3-dev +``` + +### 2. Rust Toolchain (`rustup`) + +Required for building and compiling the native daemon on ARM64: + +```bash +curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y +source "$HOME/.cargo/env" +``` + +### 3. Bun Runtime (`bun.sh`) + +Required on your developer laptop (and optional on the Pi) for building the React/Vite frontend bundle and running automation/test scripts: + +```bash +curl -fsSL https://bun.sh/install | bash +source "$HOME/.bashrc" +``` + +### 4. GigE Vision Network Socket Buffer Tuning + +Industrial GigE Vision cameras stream high-throughput packet bursts. Increase Linux UDP socket buffer limits: + +```bash +sudo bash -c 'cat > /etc/sysctl.d/60-gige-camera.conf < HTTP server bind address (default: 0.0.0.0) -h, --help Print help ``` - ---- - -## System Requirements on Pi 5 - -Install runtime dependencies on Raspberry Pi OS: - -```bash -sudo apt-get update -sudo apt-get install -y libaravis-0.8-0 libaravis-dev libudev-dev -``` diff --git a/headless-rust/package.json b/headless-rust/package.json index d35e8f0..966ff9a 100644 --- a/headless-rust/package.json +++ b/headless-rust/package.json @@ -9,7 +9,12 @@ "dev:all": "concurrently \"bun run dev\" \"cargo run -- --mock\"", "build": "vite build", "build:all": "vite build && cargo build --release", - "serve": "cargo run --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", + "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", 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..67645a3 --- /dev/null +++ b/headless-rust/scripts/deploy-to-pi.sh @@ -0,0 +1,112 @@ +#!/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.4.1 --password +# bun run deploy:pi pi@raspberrypi.local + +PI_TARGET="pi@raspberrypi.local" +USE_PASSWORD=false +FORCE_BUILD=false +BUILD_FLAG="" + +# Parse arguments +for arg in "$@"; do + case "$arg" in + --password|-p|--pass) + USE_PASSWORD=true + ;; + --build|-b|--force-build) + FORCE_BUILD=true + BUILD_FLAG="--build" + ;; + --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.4.1)" + echo "" + echo "Options:" + echo " --password, -p Force password authentication (disables SSH keys)" + echo " --build, -b Force compiling release binary on Pi" + echo " --help, -h Show this help message" + echo "" + echo "Notes:" + echo " • Automatically builds frontend locally on host (fast: ~2s)." + echo " • Works seamlessly in Field Mode (offline) or Home LAN Mode (online)." + exit 0 + ;; + *) + if [[ "$arg" != -* ]]; then + PI_TARGET="$arg" + fi + ;; + esac +done + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +HEADLESS_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)" + +# 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. Build frontend bundle on host (fast!) +echo "[1/3] Building frontend bundle locally on host machine..." +cd "${HEADLESS_DIR}" +bun run build + +# 2. Sync files to Pi (skipping heavy debug targets, node_modules & git) +echo "[2/3] Syncing files to Pi..." +ssh "${SSH_OPTS[@]}" "${PI_TARGET}" "mkdir -p ~/speedcamera/headless-rust" + +RSYNC_SSH="ssh" +for opt in "${SSH_OPTS[@]}"; do + RSYNC_SSH+=" $(printf "%q" "$opt")" +done + +rsync -avz --delete \ + -e "${RSYNC_SSH}" \ + --exclude 'target/debug' \ + --exclude 'target/release/incremental' \ + --exclude 'node_modules' \ + --exclude '.git' \ + --exclude '*.log' \ + "${HEADLESS_DIR}/" "${PI_TARGET}:~/speedcamera/headless-rust/" + +# 3. Update binary & restart service on Pi +echo "[3/3] Updating service on Pi..." +# Use -tt to force pseudo-terminal allocation so sudo can prompt for password interactively +ssh -tt "${SSH_OPTS[@]}" "${PI_TARGET}" "chmod +x ~/speedcamera/headless-rust/scripts/*.sh && ~/speedcamera/headless-rust/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..ac62d90 --- /dev/null +++ b/headless-rust/scripts/install-remote.sh @@ -0,0 +1,144 @@ +#!/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 +# bun run install:pi pi@raspberrypi.local + +PI_TARGET="pi@raspberrypi.local" +USE_PASSWORD=false +NETWORK_FLAG="" +PURGE_FIRST=false + +# Parse arguments +for arg in "$@"; do + case "$arg" in + --password|-p|--pass) + USE_PASSWORD=true + ;; + --field) + NETWORK_FLAG="--field" + ;; + --lan|--no-field|--skip-network) + NETWORK_FLAG="--skip-network" + ;; + --purge) + PURGE_FIRST=true + ;; + --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 " --help, -h Show this help message" + echo "" + echo "Notes:" + echo " • The React frontend is built on this machine (fast: ~2s) and synced to the Pi." + echo " • On Pi 5, the release binary is compiled natively or synced directly." + exit 0 + ;; + *) + if [[ "$arg" != -* ]]; then + PI_TARGET="$arg" + fi + ;; + esac +done + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +HEADLESS_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)" + +# 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. Build frontend bundle on local laptop +echo "[1/4] Building frontend bundle locally on host machine..." +cd "${HEADLESS_DIR}" +bun run build + +# 2. Test SSH connectivity +echo "[2/4] Connecting to ${PI_TARGET}..." +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 + +# 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 + +# 3. Sync repository & pre-built dist to Pi +echo "[3/4] Syncing application and pre-built frontend to Pi..." +ssh "${SSH_OPTS[@]}" "${PI_TARGET}" "mkdir -p ~/speedcamera/headless-rust" + +RSYNC_SSH="ssh" +for opt in "${SSH_OPTS[@]}"; do + RSYNC_SSH+=" $(printf "%q" "$opt")" +done + +rsync -avz --delete \ + -e "${RSYNC_SSH}" \ + --exclude 'target/debug' \ + --exclude 'target/release/incremental' \ + --exclude 'node_modules' \ + --exclude '.git' \ + --exclude '*.log' \ + "${HEADLESS_DIR}/" "${PI_TARGET}:~/speedcamera/headless-rust/" + +# 4. Execute installer on Pi +echo "[4/4] Running system provisioning and service installation on Pi..." +REMOTE_CMD="chmod +x ~/speedcamera/headless-rust/scripts/*.sh && ~/speedcamera/headless-rust/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 Mode Active" + echo " • Web UI: http://${PI_TARGET#*@}:3000 (or http://raspberrypi.local:3000)" + echo " • Switch to field mode later: 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..83ca4a5 --- /dev/null +++ b/headless-rust/scripts/install-rpi.sh @@ -0,0 +1,246 @@ +#!/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 + +for arg in "$@"; do + case "$arg" in + --skip-network|--app-only|--lan|--no-field) + SKIP_NETWORK=true + ;; + --field) + AUTO_FIELD=true + ;; + --network-only) + ONLY_NETWORK=true + ;; + --force-build|--build) + FORCE_BUILD=true + ;; + --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 immediately switch to Field Mode" + echo " --network-only Only configure dual-subnet network (Hotspot AP + Camera LAN)" + echo " --build, --force-build Force building release binary and frontend on the Pi" + echo " --help, -h Show this help message" + exit 0 + ;; + esac +done + +# 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 +echo "[*] Checking internet connectivity..." +HAS_INTERNET=true +if ! ping -c 1 -W 2 1.1.1.1 &>/dev/null && ! curl -s --connect-timeout 2 https://bun.sh &>/dev/null; then + HAS_INTERNET=false + echo ">>> WARNING: No active internet connection detected on Pi!" +fi + +# 1. System packages +if [ "$HAS_INTERNET" = true ]; then + 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 \ + curl \ + unzip \ + git \ + rsync \ + sqlite3 \ + libsqlite3-dev +else + echo "[1/5] Skipping apt package updates (offline mode)." +fi + +# Apply GigE Vision socket buffer tuning (64MB) +echo "[*] Configuring Linux socket buffers for GigE camera..." +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:$PATH" +if ! command -v cargo &> /dev/null && [ ! -x "${TARGET_HOME}/.cargo/bin/cargo" ]; then + if [ "$HAS_INTERNET" = true ]; then + echo ">>> Installing Rust toolchain via rustup..." + sudo -u "${TARGET_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 ">>> Note: Rust toolchain not found on offline Pi (relying on pre-built binary if available)." + fi +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..." +export PATH="${TARGET_HOME}/.bun/bin:$PATH" +BUN_BIN=$(command -v bun || echo "${TARGET_HOME}/.bun/bin/bun") +if [ ! -x "${BUN_BIN}" ] && ! command -v bun &> /dev/null; then + if [ "$HAS_INTERNET" = true ]; then + echo ">>> Installing Bun runtime for ARM64..." + sudo -u "${TARGET_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 ">>> Note: Bun not found on offline Pi (relying on pre-built frontend bundle)." + fi +else + echo ">>> Bun runtime ready: ${BUN_BIN}" +fi + +# 4. Binary and frontend bundle check +echo "[4/5] Checking release binary and frontend bundle..." +cd "${PROJECT_DIR}" + +# Build frontend if dist/ missing and Bun is available +if [ ! -f "${PROJECT_DIR}/dist/index.html" ]; then + if [ -x "${BUN_BIN}" ] || command -v bun &> /dev/null; then + echo ">>> Building frontend bundle..." + if [ "$HAS_INTERNET" = true ] && [ ! -d "node_modules" ]; then + sudo -u "${TARGET_USER}" env PATH="$PATH" "${BUN_BIN}" install + fi + sudo -u "${TARGET_USER}" env PATH="$PATH" "${BUN_BIN}" run build + else + echo "Error: Missing frontend dist/ and Bun runtime unavailable to build it." >&2 + exit 1 + fi +fi + +# Build Rust binary if missing or forced +if [ ! -f "${PROJECT_DIR}/target/release/headless-rust" ] || [ "$FORCE_BUILD" = true ]; then + echo ">>> Compiling native Rust release binary on Pi..." + if ! command -v cargo &> /dev/null && [ ! -x "${TARGET_HOME}/.cargo/bin/cargo" ]; then + echo "Error: Cargo not available to build release binary." >&2 + exit 1 + fi + sudo -u "${TARGET_USER}" env PATH="$PATH" cargo build --release +else + echo ">>> Verified release binary at ${PROJECT_DIR}/target/release/headless-rust" +fi + +# 5. Systemd daemon installation +echo "[5/5] Configuring systemd autostart service..." +SERVICE_FILE="/etc/systemd/system/speedcamera.service" + +sudo bash -c "cat > ${SERVICE_FILE}" < Static IP 192.168.1.100 (GigE Camera LAN)" + echo " • Wi-Fi (wlan0) -> Standalone Hotspot AP 192.168.4.1 (SSID: speedcamera)" + echo "" + echo " WARNING: This will disconnect current Wi-Fi/SSH internet connection!" + echo "=========================================================================" + read -p "Switch to Standalone Field Mode now? (y/N) " -n 1 -r + echo "" + + if [[ $REPLY =~ ^[Yy]$ ]]; then + chmod +x "${PROJECT_DIR}/scripts/setup-network.sh" + "${PROJECT_DIR}/scripts/setup-network.sh" field + else + echo "Skipping Field Mode network switch for now." + echo "Run anytime later: ~/speedcamera/headless-rust/scripts/setup-network.sh field" + fi +else + echo "Non-interactive session: Keeping existing network configuration." + echo "Switch to field mode when ready: ~/speedcamera/headless-rust/scripts/setup-network.sh field" +fi diff --git a/headless-rust/scripts/setup-network.sh b/headless-rust/scripts/setup-network.sh old mode 100644 new mode 100755 diff --git a/headless-rust/scripts/speedcamera.service b/headless-rust/scripts/speedcamera.service index be69591..26fd7ca 100644 --- a/headless-rust/scripts/speedcamera.service +++ b/headless-rust/scripts/speedcamera.service @@ -10,6 +10,7 @@ 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 diff --git a/headless-rust/scripts/test-server.ts b/headless-rust/scripts/test-server.ts new file mode 100755 index 0000000..00ca903 --- /dev/null +++ b/headless-rust/scripts/test-server.ts @@ -0,0 +1,123 @@ +#!/usr/bin/env bun +import { spawn } from "child_process"; +import { existsSync } from "fs"; + +console.log("Starting speedcamera headless-rust server in mock mode on port 3099..."); + +const binaryPath = existsSync("./target/release/headless-rust") + ? "./target/release/headless-rust" + : existsSync("./target/debug/headless-rust") + ? "./target/debug/headless-rust" + : "cargo"; + +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) => { + let settingsOk = false; + let violationsOk = false; + + ws.onopen = () => { + console.log("WebSocket connected successfully!"); + // Send RPC request for getSettings + ws.send(JSON.stringify({ id: 1, method: "getSettings", params: {} })); + // Send RPC request for getViolations + ws.send(JSON.stringify({ id: 2, method: "getViolations", params: { page: 1, limit: 10 } })); + }; + + ws.onmessage = (event) => { + console.log("WS message received:", event.data); + const data = JSON.parse(event.data); + + if (data.id === 1) { + console.log("RPC getSettings result:", data.result); + if (data.result && typeof data.result.maxSpeed === "number") { + settingsOk = true; + console.log("SUCCESS: Settings RPC validated!"); + } else { + reject(new Error("Unexpected getSettings response")); + } + } + + if (data.id === 2) { + console.log("RPC getViolations result:", data.result); + if (data.result && Array.isArray(data.result.violations)) { + violationsOk = true; + console.log("SUCCESS: Violations RPC validated!"); + } else { + reject(new Error("Unexpected getViolations response")); + } + } + + if (settingsOk && violationsOk) { + ws.close(); + resolve(); + } + }; + + ws.onerror = (err) => reject(err); + setTimeout(() => reject(new Error("WS Timeout")), 8000); + }); + + console.log("\n========================================================="); + console.log(" ALL 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..89b7016 --- /dev/null +++ b/headless-rust/scripts/update-pi.sh @@ -0,0 +1,80 @@ +#!/usr/bin/env bash +set -e + +FORCE_BUILD=false + +for arg in "$@"; do + case "$arg" in + --build|-b|--force-build) + FORCE_BUILD=true + ;; + 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)" +cd "${PROJECT_DIR}" + +# 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 configure services." >&2; exit 1; } + +# Check if binary rebuild is needed +NEEDS_BUILD=false +if [ "$FORCE_BUILD" = true ] || [ ! -f "target/release/headless-rust" ]; then + NEEDS_BUILD=true +elif [ -d "src" ] && [ $(find src Cargo.toml build.rs -newer "target/release/headless-rust" 2>/dev/null | wc -l) -gt 0 ]; then + NEEDS_BUILD=true +fi + +if [ "$NEEDS_BUILD" = true ]; then + echo "[*] Building release binary with cargo..." + if ! command -v cargo &> /dev/null && [ ! -x "${TARGET_HOME}/.cargo/bin/cargo" ]; then + echo "Error: Cargo not found. Please install Rust or run install-rpi.sh first." >&2 + exit 1 + fi + sudo -u "${TARGET_USER}" env PATH="$PATH" cargo build --release +else + echo "[*] Release binary is up to date." +fi + +# 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 + +[Install] +WantedBy=multi-user.target +SERVICE_EOF + sudo systemctl daemon-reload + sudo systemctl enable speedcamera.service +fi + +echo "[*] Restarting speedcamera service..." +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..39b2025 --- /dev/null +++ b/headless-rust/scripts/verify-ws.ts @@ -0,0 +1,55 @@ +#!/usr/bin/env bun +console.log("Connecting to WebSocket on ws://127.0.0.1:3000/ws/rpc ..."); +const ws = new WebSocket("ws://127.0.0.1:3000/ws/rpc"); + +let receivedCameraPush = false; +let receivedSettingsResponse = false; +let receivedViolationsResponse = false; + +ws.onopen = () => { + console.log("[WS] Connected to Speedcamera Headless Rust Daemon!"); + // 1. Request getSettings + ws.send(JSON.stringify({ id: 101, method: "getSettings", params: {} })); + // 2. Request getViolations + ws.send(JSON.stringify({ id: 102, method: "getViolations", params: { page: 1, limit: 10 } })); +}; + +ws.onmessage = (event) => { + console.log("[WS] Message received:", event.data); + const data = JSON.parse(event.data); + + if (data.event === "cameraStatus") { + receivedCameraPush = true; + console.log("-> Push message 'cameraStatus' verified!"); + } + + if (data.id === 101) { + if (data.result && typeof data.result.maxSpeed === "number") { + receivedSettingsResponse = true; + console.log("-> RPC 'getSettings' verified! Max speed:", data.result.maxSpeed); + } + } + + if (data.id === 102) { + if (data.result && Array.isArray(data.result.violations)) { + receivedViolationsResponse = true; + console.log("-> RPC 'getViolations' verified! Total violations:", data.result.total); + } + } + + if (receivedSettingsResponse && receivedViolationsResponse) { + console.log("\n>>> ALL WEBSOCKET RPC CHECKS PASSED PERFECTLY! <<<"); + ws.close(); + process.exit(0); + } +}; + +ws.onerror = (err) => { + console.error("WS error:", err); + process.exit(1); +}; + +setTimeout(() => { + console.error("Test timeout after 5s"); + process.exit(1); +}, 5000); From abd4f86f48bbb3175110f303849e0fe5a98b901f Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Fri, 14 Aug 2026 23:56:44 +0200 Subject: [PATCH 15/65] feat: update deployment and installation scripts for improved internet connectivity checks and branch support --- README.md | 2 +- headless-rust/README.md | 56 ++++++---- headless-rust/scripts/deploy-to-pi.sh | 84 +++++++++------ headless-rust/scripts/install-remote.sh | 90 +++++++++------- headless-rust/scripts/install-rpi.sh | 134 ++++++++++++------------ headless-rust/scripts/update-pi.sh | 112 +++++++++++++++++--- 6 files changed, 302 insertions(+), 176 deletions(-) diff --git a/README.md b/README.md index 391bd1a..977c77a 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ An end-to-end vehicle speed measurement, GigE Vision camera capture, and remote ## Quick Deployment Commands (Raspberry Pi 5) -All deployment and maintenance commands are executed from your development laptop. The React frontend is built on the laptop in ~2s (`bun run build`) and synced over SSH to the Pi. +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 diff --git a/headless-rust/README.md b/headless-rust/README.md index 323bed5..24d2de4 100644 --- a/headless-rust/README.md +++ b/headless-rust/README.md @@ -118,14 +118,25 @@ sudo sysctl -p /etc/sysctl.d/60-gige-camera.conf ## Deployment Procedures -All deployment and maintenance procedures can be executed directly from your development laptop over SSH: +All deployment and maintenance procedures can be executed directly from your development laptop over SSH. + +> [!IMPORTANT] +> **Internet Requirement for Build/Deploy**: Because the Pi compiles dependencies and pulls from Git, `bun run install:pi` and `bun run deploy:pi` must be executed while the Pi is in **Home LAN / DHCP** or **Client Wi-Fi Mode** (with internet access). +> If your Pi is currently in standalone **Field Mode** (`192.168.4.1` hotspot), connect the Pi to your Wi-Fi router first via SSH: +> ```bash +> ssh pi@192.168.4.1 '~/speedcamera/headless-rust/scripts/setup-network.sh internet "MyHomeWiFi" "MyPassword"' +> ``` +> Or plug in an Ethernet cable and run: +> ```bash +> ssh pi@192.168.4.1 '~/speedcamera/headless-rust/scripts/setup-network.sh dhcp' +> ``` ``` ┌────────────────────────────────────────────────────────────────────────┐ │ Command │ Purpose │ ├──────────────────────────────┼─────────────────────────────────────────┤ │ bun run install:pi [target] │ Fresh Pi install on Home LAN / DHCP │ -│ bun run deploy:pi [target] │ Upgrade existing Pi (Field or Home LAN) │ +│ bun run deploy:pi [target] │ Upgrade existing Pi (in Internet Mode) │ │ bun run cleanup:pi [target] │ Complete teardown & restore DHCP network│ └──────────────────────────────┴─────────────────────────────────────────┘ ``` @@ -146,28 +157,30 @@ bun run install:pi pi@raspberrypi.local # With password prompt (if SSH keys are not configured): bun run install:pi pi@raspberrypi.local --password -# Using direct IP and automatically switching to Field Mode at the end: +# Using direct IP and automatically switching to Field Mode at the very end: bun run install:pi pi@192.168.1.50 --field # Stay in Home LAN mode (skip field network setup): bun run install:pi pi@raspberrypi.local --lan + +# Deploy a specific branch: +bun run install:pi pi@raspberrypi.local --branch feature/headless ``` #### What this command does: -1. Builds the frontend bundle on your laptop (`bun run build`, ~2s). -2. Establishes an SSH multiplexed connection (password requested once). -3. Rsyncs the codebase and pre-built `dist/` to `~/speedcamera/headless-rust` on the Pi. -4. Updates Pi system packages (`libaravis-0.8-0`, `libaravis-dev`, `libglib2.0-dev`, `libudev-dev`, `build-essential`, `esptool`, `network-manager`, etc.). -5. Installs the Rust toolchain (`rustup`) and Bun runtime on the Pi if missing. -6. Builds the release binary (`cargo build --release`) natively on Pi 5. -7. Registers, enables, and starts the `speedcamera.service` systemd daemon. -8. Configures the network mode (Field Mode or Home LAN Mode). +1. Connects to the Raspberry Pi over SSH and verifies internet reachability. +2. Clones or pulls the `speedcamera` git repository directly to `~/speedcamera` on the Pi. +3. Updates Pi system packages (`libaravis-0.8-0`, `libaravis-dev`, `libglib2.0-dev`, `libudev-dev`, `build-essential`, `esptool`, `network-manager`, etc.). +4. Installs the Rust toolchain (`rustup`) and Bun runtime on the Pi. +5. Builds the frontend assets (`bun run build`) and compiles the release binary (`cargo build --release`) natively on Pi 5. +6. Registers, enables, and starts the `speedcamera.service` systemd daemon. +7. **Only after all software and builds succeed**: Transitions network mode to Field Mode if requested (`--field`). --- ### Scenario 2: Upgrading an Existing Installation -Use this scenario to push code updates to an already configured Pi. The Pi can either be in **Field Mode** (offline Wi-Fi hotspot) or connected to your **Home LAN**. +Use this scenario to push code updates to an already configured Pi while connected to your **Home LAN** or **Client Wi-Fi**. #### Run from your laptop: ```bash @@ -176,19 +189,20 @@ cd headless-rust # Deploy to Pi on Home LAN: bun run deploy:pi pi@raspberrypi.local -# Deploy to Pi in Field Mode (connected to 'speedcamera' Wi-Fi): -bun run deploy:pi pi@192.168.4.1 - # With password authentication: -bun run deploy:pi pi@192.168.4.1 --password +bun run deploy:pi pi@raspberrypi.local --password + +# Force rebuild frontend & Rust binary: +bun run deploy:pi pi@raspberrypi.local --build ``` #### What this command does: -1. Re-builds the frontend bundle locally (`bun run build`). -2. Syncs changed files (`dist/`, `src/`, `Cargo.toml`, `scripts/`, etc.) to the Pi. -3. Automatically re-compiles the Rust release binary if sources changed. -4. Restarts `speedcamera.service` and verifies that the daemon is active and running. -5. **Preserves existing network configuration** without causing unexpected disconnections. +1. Connects to the Pi via SSH and verifies active internet connectivity. +2. Runs `git pull` in `~/speedcamera` to fetch and apply the latest commits. +3. Automatically rebuilds the frontend bundle on the Pi if frontend files changed. +4. Automatically recompiles the native Rust release binary on the Pi if Rust code or frontend bundle changed. +5. Restarts `speedcamera.service` and verifies that the daemon is active and running. +6. Preserves existing network configuration without causing unexpected disconnections. --- diff --git a/headless-rust/scripts/deploy-to-pi.sh b/headless-rust/scripts/deploy-to-pi.sh index 67645a3..ec420ae 100755 --- a/headless-rust/scripts/deploy-to-pi.sh +++ b/headless-rust/scripts/deploy-to-pi.sh @@ -4,23 +4,31 @@ 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.4.1 --password +# ./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 -for arg in "$@"; do - case "$arg" in +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" @@ -28,28 +36,38 @@ for arg in "$@"; do 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 " [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 on Pi" + 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 " • Automatically builds frontend locally on host (fast: ~2s)." - echo " • Works seamlessly in Field Mode (offline) or Home LAN Mode (online)." + 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 [[ "$arg" != -* ]]; then - PI_TARGET="$arg" + if [[ "$1" != -* ]]; then + PI_TARGET="$1" fi + shift ;; esac done -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -HEADLESS_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)" +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-$$" @@ -73,33 +91,31 @@ echo "=========================================================" echo " Deploying / Upgrading Speedcamera Rust: ${PI_TARGET}" echo "=========================================================" -# 1. Build frontend bundle on host (fast!) -echo "[1/3] Building frontend bundle locally on host machine..." -cd "${HEADLESS_DIR}" -bun run build - -# 2. Sync files to Pi (skipping heavy debug targets, node_modules & git) -echo "[2/3] Syncing files to Pi..." -ssh "${SSH_OPTS[@]}" "${PI_TARGET}" "mkdir -p ~/speedcamera/headless-rust" +# 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" -RSYNC_SSH="ssh" -for opt in "${SSH_OPTS[@]}"; do - RSYNC_SSH+=" $(printf "%q" "$opt")" -done +if [ -n "$BRANCH" ]; then + GIT_CMD+=" && git fetch origin && git checkout ${BRANCH} && git pull origin ${BRANCH}" +else + GIT_CMD+=" && git pull" +fi -rsync -avz --delete \ - -e "${RSYNC_SSH}" \ - --exclude 'target/debug' \ - --exclude 'target/release/incremental' \ - --exclude 'node_modules' \ - --exclude '.git' \ - --exclude '*.log' \ - "${HEADLESS_DIR}/" "${PI_TARGET}:~/speedcamera/headless-rust/" +ssh -tt "${SSH_OPTS[@]}" "${PI_TARGET}" "${GIT_CMD}" -# 3. Update binary & restart service on Pi -echo "[3/3] Updating service on Pi..." +# 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}" "chmod +x ~/speedcamera/headless-rust/scripts/*.sh && ~/speedcamera/headless-rust/scripts/update-pi.sh ${BUILD_FLAG}" +ssh -tt "${SSH_OPTS[@]}" "${PI_TARGET}" "cd ~/speedcamera/headless-rust && chmod +x scripts/*.sh && ./scripts/update-pi.sh ${BUILD_FLAG}" echo "" echo "=========================================================" diff --git a/headless-rust/scripts/install-remote.sh b/headless-rust/scripts/install-remote.sh index ac62d90..57cde44 100755 --- a/headless-rust/scripts/install-remote.sh +++ b/headless-rust/scripts/install-remote.sh @@ -6,27 +6,42 @@ set -e # ./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 -for arg in "$@"; do - case "$arg" in +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" @@ -41,23 +56,33 @@ for arg in "$@"; do 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 " • The React frontend is built on this machine (fast: ~2s) and synced to the Pi." - echo " • On Pi 5, the release binary is compiled natively or synced directly." + 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 [[ "$arg" != -* ]]; then - PI_TARGET="$arg" + if [[ "$1" != -* ]]; then + PI_TARGET="$1" fi + shift ;; esac done -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -HEADLESS_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)" +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-$$" @@ -82,45 +107,38 @@ echo " Speedcamera Rust Remote Pi Fresh Installer" echo " Target: ${PI_TARGET}" echo "=========================================================" -# 1. Build frontend bundle on local laptop -echo "[1/4] Building frontend bundle locally on host machine..." -cd "${HEADLESS_DIR}" -bun run build - -# 2. Test SSH connectivity -echo "[2/4] Connecting to ${PI_TARGET}..." +# 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 -# 3. Sync repository & pre-built dist to Pi -echo "[3/4] Syncing application and pre-built frontend to Pi..." -ssh "${SSH_OPTS[@]}" "${PI_TARGET}" "mkdir -p ~/speedcamera/headless-rust" - -RSYNC_SSH="ssh" -for opt in "${SSH_OPTS[@]}"; do - RSYNC_SSH+=" $(printf "%q" "$opt")" -done +# 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 -rsync -avz --delete \ - -e "${RSYNC_SSH}" \ - --exclude 'target/debug' \ - --exclude 'target/release/incremental' \ - --exclude 'node_modules' \ - --exclude '.git' \ - --exclude '*.log' \ - "${HEADLESS_DIR}/" "${PI_TARGET}:~/speedcamera/headless-rust/" +ssh -tt "${SSH_OPTS[@]}" "${PI_TARGET}" "${GIT_SETUP}" -# 4. Execute installer on Pi -echo "[4/4] Running system provisioning and service installation on Pi..." -REMOTE_CMD="chmod +x ~/speedcamera/headless-rust/scripts/*.sh && ~/speedcamera/headless-rust/scripts/install-rpi.sh ${NETWORK_FLAG}" +# 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}" @@ -135,9 +153,9 @@ if [ "$NETWORK_FLAG" = "--field" ]; then echo " • Web UI: http://192.168.4.1:3000" echo " • Camera LAN: http://192.168.1.100:3000" else - echo " Network: Home LAN Mode Active" + echo " Network: Home LAN / DHCP Mode Active" echo " • Web UI: http://${PI_TARGET#*@}:3000 (or http://raspberrypi.local:3000)" - echo " • Switch to field mode later: ssh ${PI_TARGET} '~/speedcamera/headless-rust/scripts/setup-network.sh field'" + 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'" diff --git a/headless-rust/scripts/install-rpi.sh b/headless-rust/scripts/install-rpi.sh index 83ca4a5..cf9906c 100755 --- a/headless-rust/scripts/install-rpi.sh +++ b/headless-rust/scripts/install-rpi.sh @@ -38,7 +38,7 @@ for arg in "$@"; do echo "" echo "Options:" echo " --app-only, --skip-network, --lan Provision packages, Rust, Bun, binary, and service (keeps network)" - echo " --field Provision and immediately switch to Field Mode" + echo " --field Provision and switch to Field Mode at the very end" echo " --network-only Only configure dual-subnet network (Hotspot AP + Camera LAN)" echo " --build, --force-build Force building release binary and frontend on the Pi" echo " --help, -h Show this help message" @@ -47,6 +47,14 @@ for arg in "$@"; do 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; } @@ -57,37 +65,35 @@ if [ "$ONLY_NETWORK" = true ]; then exit 0 fi -# Pre-flight internet check +# Pre-flight internet check: installation MUST be done in DHCP/Internet mode echo "[*] Checking internet connectivity..." -HAS_INTERNET=true if ! ping -c 1 -W 2 1.1.1.1 &>/dev/null && ! curl -s --connect-timeout 2 https://bun.sh &>/dev/null; then - HAS_INTERNET=false - echo ">>> WARNING: No active internet connection detected on Pi!" + 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 -if [ "$HAS_INTERNET" = true ]; then - 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 \ - curl \ - unzip \ - git \ - rsync \ - sqlite3 \ - libsqlite3-dev -else - echo "[1/5] Skipping apt package updates (offline mode)." -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 \ + curl \ + unzip \ + git \ + rsync \ + sqlite3 \ + libsqlite3-dev # Apply GigE Vision socket buffer tuning (64MB) echo "[*] Configuring Linux socket buffers for GigE camera..." @@ -102,66 +108,55 @@ sudo sysctl -p /etc/sysctl.d/60-gige-camera.conf 2>/dev/null || sudo sysctl --sy # 2. Check/Install Rust toolchain echo "[2/5] Checking Rust toolchain..." -export PATH="${TARGET_HOME}/.cargo/bin:$PATH" +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 - if [ "$HAS_INTERNET" = true ]; then - echo ">>> Installing Rust toolchain via rustup..." - sudo -u "${TARGET_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 ">>> Note: Rust toolchain not found on offline Pi (relying on pre-built binary if available)." - fi + 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..." -export PATH="${TARGET_HOME}/.bun/bin:$PATH" BUN_BIN=$(command -v bun || echo "${TARGET_HOME}/.bun/bin/bun") if [ ! -x "${BUN_BIN}" ] && ! command -v bun &> /dev/null; then - if [ "$HAS_INTERNET" = true ]; then - echo ">>> Installing Bun runtime for ARM64..." - sudo -u "${TARGET_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 ">>> Note: Bun not found on offline Pi (relying on pre-built frontend bundle)." - fi + 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 check -echo "[4/5] Checking release binary and frontend bundle..." +# 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 if dist/ missing and Bun is available -if [ ! -f "${PROJECT_DIR}/dist/index.html" ]; then - if [ -x "${BUN_BIN}" ] || command -v bun &> /dev/null; then - echo ">>> Building frontend bundle..." - if [ "$HAS_INTERNET" = true ] && [ ! -d "node_modules" ]; then - sudo -u "${TARGET_USER}" env PATH="$PATH" "${BUN_BIN}" install - fi - sudo -u "${TARGET_USER}" env PATH="$PATH" "${BUN_BIN}" run build - else +# 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 if missing or forced -if [ ! -f "${PROJECT_DIR}/target/release/headless-rust" ] || [ "$FORCE_BUILD" = true ]; then - echo ">>> Compiling native Rust release binary on Pi..." - if ! command -v cargo &> /dev/null && [ ! -x "${TARGET_HOME}/.cargo/bin/cargo" ]; then - echo "Error: Cargo not available to build release binary." >&2 - exit 1 - fi - sudo -u "${TARGET_USER}" env PATH="$PATH" cargo build --release -else - echo ">>> Verified release binary at ${PROJECT_DIR}/target/release/headless-rust" +# 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..." @@ -203,9 +198,9 @@ echo " Daemon status: sudo systemctl status speedcamera" echo " Daemon logs: sudo journalctl -u speedcamera -f" echo "=========================================================" -# Step 6: Network Mode Transition +# Step 6: Network Mode Transition (executed ONLY after all builds & services are fully running) if [ "$AUTO_FIELD" = true ]; then - echo "[*] Switching directly to Standalone Field Mode..." + echo "[*] Switching network to Standalone Field Mode (Camera LAN + Hotspot AP)..." chmod +x "${PROJECT_DIR}/scripts/setup-network.sh" "${PROJECT_DIR}/scripts/setup-network.sh" field exit 0 @@ -224,6 +219,7 @@ if [ -t 0 ]; then echo "=========================================================================" echo " FIELD NETWORK CONFIGURATION (Camera LAN + Hotspot AP)" echo "=========================================================================" + echo " All software and services have been installed and built successfully." echo " Ready to switch Pi into Standalone Field Mode:" echo " • Ethernet (eth0) -> Static IP 192.168.1.100 (GigE Camera LAN)" echo " • Wi-Fi (wlan0) -> Standalone Hotspot AP 192.168.4.1 (SSID: speedcamera)" diff --git a/headless-rust/scripts/update-pi.sh b/headless-rust/scripts/update-pi.sh index 89b7016..875cb0e 100755 --- a/headless-rust/scripts/update-pi.sh +++ b/headless-rust/scripts/update-pi.sh @@ -1,46 +1,128 @@ #!/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}" -# Request sudo credentials early so user is prompted interactively if needed +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; } -# Check if binary rebuild is needed -NEEDS_BUILD=false -if [ "$FORCE_BUILD" = true ] || [ ! -f "target/release/headless-rust" ]; then - NEEDS_BUILD=true -elif [ -d "src" ] && [ $(find src Cargo.toml build.rs -newer "target/release/headless-rust" 2>/dev/null | wc -l) -gt 0 ]; then - NEEDS_BUILD=true +# 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_BUILD" = true ]; then - echo "[*] Building release binary with cargo..." - if ! command -v cargo &> /dev/null && [ ! -x "${TARGET_HOME}/.cargo/bin/cargo" ]; then - echo "Error: Cargo not found. Please install Rust or run install-rpi.sh first." >&2 - exit 1 +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 - sudo -u "${TARGET_USER}" env PATH="$PATH" cargo build --release + + 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 -# Ensure systemd service exists and is up to date +# 3. Ensure systemd service exists and is up to date SERVICE_FILE="/etc/systemd/system/speedcamera.service" if [ ! -f "$SERVICE_FILE" ]; then @@ -73,7 +155,7 @@ SERVICE_EOF sudo systemctl enable speedcamera.service fi -echo "[*] Restarting speedcamera service..." +echo "[*] Restarting speedcamera service on Pi..." sudo systemctl daemon-reload sudo systemctl restart speedcamera.service sleep 1 From 067e172c0128fd1be957d6ebf9ae205a345bebbe Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Sat, 15 Aug 2026 00:17:59 +0200 Subject: [PATCH 16/65] fix: Fix camera acquisition and serial port EOF lockup --- headless-rust/scripts/speedcamera.service | 2 + headless-rust/scripts/update-pi.sh | 2 + headless-rust/src/camera/ffi.rs | 82 ++++++ headless-rust/src/camera/mod.rs | 335 ++++++++++++++++++---- headless-rust/src/serial/mod.rs | 83 +++++- 5 files changed, 437 insertions(+), 67 deletions(-) diff --git a/headless-rust/scripts/speedcamera.service b/headless-rust/scripts/speedcamera.service index 26fd7ca..d38f2a6 100644 --- a/headless-rust/scripts/speedcamera.service +++ b/headless-rust/scripts/speedcamera.service @@ -17,6 +17,8 @@ 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/update-pi.sh b/headless-rust/scripts/update-pi.sh index 875cb0e..0f794ad 100755 --- a/headless-rust/scripts/update-pi.sh +++ b/headless-rust/scripts/update-pi.sh @@ -147,6 +147,8 @@ 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/src/camera/ffi.rs b/headless-rust/src/camera/ffi.rs index cb804df..9a2c5db 100644 --- a/headless-rust/src/camera/ffi.rs +++ b/headless-rust/src/camera/ffi.rs @@ -13,8 +13,74 @@ pub struct GError { 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; @@ -89,7 +155,14 @@ unsafe extern "C" { err: *mut *mut GError, ); + 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_create_stream( cam: *mut ArvCamera, @@ -98,9 +171,18 @@ unsafe extern "C" { 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; diff --git a/headless-rust/src/camera/mod.rs b/headless-rust/src/camera/mod.rs index 8824044..908658e 100644 --- a/headless-rust/src/camera/mod.rs +++ b/headless-rust/src/camera/mod.rs @@ -2,9 +2,9 @@ pub mod ffi; pub mod mock; use crate::models::{AppSettings, CameraStatusPayload, MfsConfigResult}; -use ffi::*; use base64::Engine; -use image::{ImageBuffer, Luma, Rgb}; +use ffi::*; +use image::{DynamicImage, ImageBuffer, Luma, Rgb}; use std::ffi::{CStr, CString}; use std::io::Cursor; use std::ptr::null_mut; @@ -159,7 +159,10 @@ impl CameraService { return; } - arv_camera_gv_auto_packet_size(cam, &mut err); + if arv_camera_is_gv_device(cam) != 0 { + let packet_size = arv_camera_gv_auto_packet_size(cam, &mut err); + println!("[camera] GigE Vision auto packet size set to: {} bytes", packet_size); + } // Configure Trigger mode & strobe Self::set_feature_str_internal(cam, "AcquisitionMode", "Continuous"); @@ -196,7 +199,7 @@ impl CameraService { ); } - // Create Stream with 5 pre-allocated buffers + // Create Stream with 8 pre-allocated buffers for robust throughput let stream = arv_camera_create_stream(cam, null_mut(), null_mut(), &mut err); if stream.is_null() { println!("[camera] Failed to create stream"); @@ -205,16 +208,25 @@ impl CameraService { } let payload_size = Self::get_feature_int_internal(cam, "PayloadSize").max(1024 * 1024); - for _ in 0..5 { + for _ in 0..8 { let buf = arv_buffer_new_allocate(payload_size as usize); 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(); + println!("[camera] Warning: 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); - println!("[camera] Connected successfully to industrial camera"); + println!("[camera] Connected and acquisition started successfully"); let _ = self.status_sender.send(self.get_status()); } } @@ -230,15 +242,25 @@ impl CameraService { 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(); } - let mut cam_guard = self.camera_ptr.lock().unwrap(); - if !cam_guard.is_null() { - g_object_unref(*cam_guard as *mut _); + if !cam.is_null() { + g_object_unref(cam as *mut _); *cam_guard = null_mut(); } } @@ -263,7 +285,7 @@ impl CameraService { } unsafe { - // Discard stale buffers + // Flush any stale buffers lingering in stream output queue loop { let stale = arv_stream_try_pop_buffer(stream); if stale.is_null() { @@ -276,16 +298,26 @@ impl CameraService { let mut err = null_mut(); let trigger_cmd = CString::new("TriggerSoftware").unwrap(); arv_camera_execute_command(cam, trigger_cmd.as_ptr(), &mut err); + if !err.is_null() { + let msg = CStr::from_ptr((*err).message).to_string_lossy(); + println!("[camera] TriggerSoftware failed: {}", msg); + g_error_free(err); + } - // Wait up to 2 seconds for frame - let buffer = arv_stream_timeout_pop_buffer(stream, 2_000_000); + // Wait up to 1.5 seconds for completed frame + let buffer = arv_stream_timeout_pop_buffer(stream, 1_500_000); if buffer.is_null() { println!("[camera] Capture frame timed out"); return None; } - if arv_buffer_get_status(buffer) != ARV_BUFFER_STATUS_SUCCESS { - println!("[camera] Capture buffer status != SUCCESS"); + let status = arv_buffer_get_status(buffer); + if status != ARV_BUFFER_STATUS_SUCCESS { + println!( + "[camera] Capture buffer failed with status: {} ({})", + buffer_status_name(status), + status + ); arv_stream_push_buffer(stream, buffer); return None; } @@ -301,7 +333,7 @@ impl CameraService { // Convert to PNG buffer let png_bytes = Self::raw_buffer_to_png(raw_slice, width, height, pixel_format); - // Return buffer back to stream pool + // Recycle buffer back to stream pool arv_stream_push_buffer(stream, buffer); png_bytes @@ -326,7 +358,7 @@ impl CameraService { Self::set_feature_str_internal(cam, "ExposureAuto", "Continuous"); Self::set_feature_str_internal(cam, "GainAuto", "Continuous"); Self::set_feature_bool_internal(cam, "AcquisitionFrameRateEnable", true); - Self::set_feature_float_internal(cam, "AcquisitionFrameRate", 10.0); + Self::set_feature_float_internal(cam, "AcquisitionFrameRate", 12.0); } } @@ -336,20 +368,21 @@ impl CameraService { let b64 = base64::engine::general_purpose::STANDARD.encode(&jpeg); let _ = this.frame_sender.send(b64); } - std::thread::sleep(std::time::Duration::from_millis(100)); + 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(100)); + std::thread::sleep(std::time::Duration::from_millis(80)); continue; } unsafe { - let buffer = arv_stream_timeout_pop_buffer(stream, 100_000); + let buffer = arv_stream_timeout_pop_buffer(stream, 150_000); if !buffer.is_null() { - if arv_buffer_get_status(buffer) == ARV_BUFFER_STATUS_SUCCESS { + let status = arv_buffer_get_status(buffer); + if status == ARV_BUFFER_STATUS_SUCCESS { 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); @@ -369,7 +402,7 @@ impl CameraService { arv_stream_push_buffer(stream, buffer); } } - std::thread::sleep(std::time::Duration::from_millis(40)); + std::thread::sleep(std::time::Duration::from_millis(20)); } println!("[camera] Setup preview stream stopped"); @@ -494,26 +527,235 @@ impl CameraService { } } - // Helper functions for raw buffer decoding - fn raw_buffer_to_png(raw: &[u8], width: u32, height: u32, _pixel_format: u32) -> Option> { - let expected_mono = (width * height) as usize; - let expected_rgb = (width * height * 3) as usize; - - let mut buf = Vec::new(); - let mut cursor = Cursor::new(&mut buf); + // ── 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 + } + } + } + } - if raw.len() >= expected_rgb { - let img: ImageBuffer, &[u8]> = - ImageBuffer::from_raw(width, height, &raw[..expected_rgb])?; - img.write_to(&mut cursor, image::ImageFormat::Png).ok()?; - } else if raw.len() >= expected_mono { - let img: ImageBuffer, &[u8]> = - ImageBuffer::from_raw(width, height, &raw[..expected_mono])?; - img.write_to(&mut cursor, image::ImageFormat::Png).ok()?; - } else { + /// 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) + } + + 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) } @@ -521,24 +763,9 @@ impl CameraService { raw: &[u8], width: u32, height: u32, - _pixel_format: u32, + pixel_format: u32, ) -> Option> { - let expected_mono = (width * height) as usize; - let expected_rgb = (width * height * 3) as usize; - - let dynamic_img = if raw.len() >= expected_rgb { - let img: ImageBuffer, Vec> = - ImageBuffer::from_raw(width, height, raw[..expected_rgb].to_vec())?; - image::DynamicImage::ImageRgb8(img) - } else if raw.len() >= expected_mono { - let img: ImageBuffer, Vec> = - ImageBuffer::from_raw(width, height, raw[..expected_mono].to_vec())?; - image::DynamicImage::ImageLuma8(img) - } else { - return None; - }; - - // Resize down to 800px width max for fast preview bandwidth over Wi-Fi + 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(); diff --git a/headless-rust/src/serial/mod.rs b/headless-rust/src/serial/mod.rs index 633a0f6..8d65035 100644 --- a/headless-rust/src/serial/mod.rs +++ b/headless-rust/src/serial/mod.rs @@ -4,7 +4,7 @@ pub mod protocol; use crate::models::{PortInfo, SerialStatusPayload}; use protocol::EspMessage; use std::io::{BufRead, BufReader, Write}; -use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; use std::time::Duration; use tokio::sync::broadcast; @@ -14,6 +14,7 @@ pub struct SerialService { mock_serial: Mutex>, active_port: Mutex>>, active_path: Mutex, + session_id: Arc, is_running: Arc, status_sender: broadcast::Sender, } @@ -27,6 +28,7 @@ impl SerialService { mock_serial: Mutex::new(None), active_port: Mutex::new(None), active_path: Mutex::new(String::new()), + session_id: Arc::new(AtomicU64::new(0)), is_running: Arc::new(AtomicBool::new(true)), status_sender: status_tx, }); @@ -97,13 +99,26 @@ impl SerialService { return; } - let mut current_path = self.active_path.lock().unwrap(); - *current_path = port_path.to_string(); + // 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) => { @@ -123,12 +138,15 @@ impl SerialService { let mut reader = BufReader::new(reader_port); let mut line_buf = String::new(); - while this.is_running.load(Ordering::SeqCst) { + 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 / disconnected - std::thread::sleep(Duration::from_millis(50)); + // EOF: Serial hardware disconnected or reset + println!("[serial] EOF on {} (device disconnected)", path); + break; } Ok(_) => { let trimmed = line_buf.trim(); @@ -137,31 +155,70 @@ impl SerialService { } } Err(ref e) if e.kind() == std::io::ErrorKind::TimedOut => { - // Timeout is normal for non-blocking read + // Expected timeout when idle } Err(e) => { - println!("[serial] Read error: {}", e); + println!("[serial] Read error on {}: {}", path, e); break; } } } - println!("[serial] Port {} closed", path); - *this.active_port.lock().unwrap() = None; - let _ = this.status_sender.send(SerialStatusPayload::Disconnected); + // Only clean up state if this session is still the active one + if this.session_id.load(Ordering::SeqCst) == session { + println!("[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) => { println!("[serial] Failed to open {}: {}", path, e); - let _ = this.status_sender.send(SerialStatusPayload::Disconnected); + 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; + } + + println!("[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); + println!("[serial] Port manually closed"); } pub fn send_command(&self, json: &str) { @@ -176,7 +233,7 @@ impl SerialService { 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) { + if let Err(e) = port.write_all(&data).and_then(|_| port.flush()) { println!("[serial] Failed to write command: {}", e); } } From 0c3cfe2f9a443e7bdd03218a88f732f6ed50e4d0 Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Sat, 15 Aug 2026 00:33:48 +0200 Subject: [PATCH 17/65] feat: enhance serial status handling and integrate with application state --- headless-rust/frontend/src/lib/rpc.ts | 13 +- headless-rust/frontend/src/routes/__root.tsx | 41 ++++- headless-rust/frontend/src/shared/types.ts | 6 +- .../frontend/src/stores/slices/cameraSlice.ts | 13 ++ .../src/stores/slices/measurementSlice.ts | 11 ++ .../frontend/src/stores/slices/serialSlice.ts | 28 ++++ headless-rust/src/camera/mod.rs | 139 ++++++++++++++++- headless-rust/src/integrations/teable.rs | 143 +++++++++++++++++- headless-rust/src/main.rs | 11 ++ headless-rust/src/models.rs | 12 +- headless-rust/src/serial/mock.rs | 2 +- headless-rust/src/serial/mod.rs | 46 +++++- headless-rust/src/web/rpc.rs | 114 +++++++++++++- headless-rust/src/web/ws.rs | 11 +- 14 files changed, 569 insertions(+), 21 deletions(-) diff --git a/headless-rust/frontend/src/lib/rpc.ts b/headless-rust/frontend/src/lib/rpc.ts index 2d544a6..89f5fae 100644 --- a/headless-rust/frontend/src/lib/rpc.ts +++ b/headless-rust/frontend/src/lib/rpc.ts @@ -103,9 +103,18 @@ class WebSocketRpcClient { private handlePushEvent(event: K, payload: PushMessageMap[K]) { const store = useAppStore.getState(); switch (event) { - case "serialStatus": - store.handleSerialStatus(payload as any); + case "serialStatus": { + const serialPayload = payload as any; + 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 "flashProgress": store.handleFlashProgress(payload as any); break; diff --git a/headless-rust/frontend/src/routes/__root.tsx b/headless-rust/frontend/src/routes/__root.tsx index c077548..b739dbe 100644 --- a/headless-rust/frontend/src/routes/__root.tsx +++ b/headless-rust/frontend/src/routes/__root.tsx @@ -4,6 +4,7 @@ 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, @@ -14,12 +15,48 @@ function Root() { 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 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 connection states + void refreshCameraStatus(); + void refreshSerialStatus(); void loadLapSettings(); void loadTeableState(); - void refreshCameraStatus(); - }, [loadLapSettings, loadTeableState, refreshCameraStatus]); + + // 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, + loadLapSettings, + loadTeableState, + setLastViolation, + ]); return (
diff --git a/headless-rust/frontend/src/shared/types.ts b/headless-rust/frontend/src/shared/types.ts index dc0a0ae..eecaaf6 100644 --- a/headless-rust/frontend/src/shared/types.ts +++ b/headless-rust/frontend/src/shared/types.ts @@ -247,7 +247,7 @@ export type SerialStatusPayload = | { status: "LAPEND"; lapNumber: number; durationMs: number; speedAtStart: number; speedAtEnd: number; timestamp: number } | { status: "LAPWAITING" } | { status: "LAPSTOPPED" } - | { status: "CONNECTED" } + | { status: "CONNECTED"; port?: string } | { status: "DISCONNECTED" }; // ─── RPC Schema Definition ──────────────────────────────────────────────────── @@ -343,6 +343,10 @@ export type SpeedcameraRPC = { params: Record; response: PortInfo[]; }; + getSerialStatus: { + params: Record; + response: { connected: boolean; port: string | null }; + }; openPort: { params: { path: string }; response: void; diff --git a/headless-rust/frontend/src/stores/slices/cameraSlice.ts b/headless-rust/frontend/src/stores/slices/cameraSlice.ts index 69fc04e..594a3c6 100644 --- a/headless-rust/frontend/src/stores/slices/cameraSlice.ts +++ b/headless-rust/frontend/src/stores/slices/cameraSlice.ts @@ -32,6 +32,7 @@ export interface CameraSlice { setLiveFrame: (frame: string) => void; applyMfsConfig: (mfsContent: string, saveAsDefault: boolean) => Promise; clearMfsResult: () => void; + loadCameraSettings: (settings: AppSettings) => void; } export const createCameraSlice: StateCreator = (set) => ({ @@ -52,6 +53,18 @@ export const createCameraSlice: StateCreator = 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, diff --git a/headless-rust/frontend/src/stores/slices/measurementSlice.ts b/headless-rust/frontend/src/stores/slices/measurementSlice.ts index 7049e9b..5f873be 100644 --- a/headless-rust/frontend/src/stores/slices/measurementSlice.ts +++ b/headless-rust/frontend/src/stores/slices/measurementSlice.ts @@ -45,6 +45,17 @@ export const createMeasurementSlice: StateCreator< 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; + } + const { systemState, appMode } = get(); // In PASSIVE mode, ignore all serial measurements if (systemState === "PASSIVE") return; diff --git a/headless-rust/frontend/src/stores/slices/serialSlice.ts b/headless-rust/frontend/src/stores/slices/serialSlice.ts index d4710ce..0626869 100644 --- a/headless-rust/frontend/src/stores/slices/serialSlice.ts +++ b/headless-rust/frontend/src/stores/slices/serialSlice.ts @@ -1,5 +1,6 @@ import type { StateCreator } from "zustand"; import type { PortInfo } from "@/shared/types"; +import { getRpc } from "@/lib/rpc"; export interface SerialSlice { availablePorts: PortInfo[]; @@ -10,6 +11,9 @@ export interface SerialSlice { 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) => ({ @@ -19,4 +23,28 @@ export const createSerialSlice: StateCreator = 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/src/camera/mod.rs b/headless-rust/src/camera/mod.rs index 908658e..6219cab 100644 --- a/headless-rust/src/camera/mod.rs +++ b/headless-rust/src/camera/mod.rs @@ -354,11 +354,52 @@ impl CameraService { if !this.mock_mode { let cam = *this.camera_ptr.lock().unwrap(); if !cam.is_null() { + unsafe { + let mut err = null_mut(); + arv_camera_stop_acquisition(cam, &mut err); + if !err.is_null() { + g_error_free(err); + } + } + + // Flush any pending buffers + let stream = *this.stream_ptr.lock().unwrap(); + if !stream.is_null() { + unsafe { + loop { + let stale = arv_stream_try_pop_buffer(stream); + if stale.is_null() { + break; + } + arv_stream_push_buffer(stream, stale); + } + } + } + + // Disable strobe during setup preview + Self::set_feature_bool_internal(cam, "StrobeEnable", false); + Self::set_feature_int_internal(cam, "StrobeEnable", 0); + Self::set_feature_str_internal(cam, "LineSelector", "Line1"); + Self::set_feature_str_internal(cam, "LineSource", "Off"); + Self::set_feature_str_internal(cam, "LineSelector", "Line2"); + Self::set_feature_str_internal(cam, "LineSource", "Off"); + + // Set free-running stream features Self::set_feature_str_internal(cam, "TriggerMode", "Off"); Self::set_feature_str_internal(cam, "ExposureAuto", "Continuous"); Self::set_feature_str_internal(cam, "GainAuto", "Continuous"); Self::set_feature_bool_internal(cam, "AcquisitionFrameRateEnable", true); - Self::set_feature_float_internal(cam, "AcquisitionFrameRate", 12.0); + Self::set_feature_float_internal(cam, "AcquisitionFrameRate", 10.0); + + 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(); + println!("[camera] Error restarting acquisition for setup stream: {}", msg); + g_error_free(err); + } + } } } @@ -379,7 +420,7 @@ impl CameraService { } unsafe { - let buffer = arv_stream_timeout_pop_buffer(stream, 150_000); + let buffer = arv_stream_timeout_pop_buffer(stream, 200_000); if !buffer.is_null() { let status = arv_buffer_get_status(buffer); if status == ARV_BUFFER_STATUS_SUCCESS { @@ -402,7 +443,7 @@ impl CameraService { arv_stream_push_buffer(stream, buffer); } } - std::thread::sleep(std::time::Duration::from_millis(20)); + std::thread::sleep(std::time::Duration::from_millis(30)); } println!("[camera] Setup preview stream stopped"); @@ -415,7 +456,43 @@ impl CameraService { if !self.mock_mode { let cam = *self.camera_ptr.lock().unwrap(); if !cam.is_null() { + unsafe { + let mut err = null_mut(); + arv_camera_stop_acquisition(cam, &mut err); + if !err.is_null() { + g_error_free(err); + } + } + + // Flush stream buffers + let stream = *self.stream_ptr.lock().unwrap(); + if !stream.is_null() { + unsafe { + loop { + let stale = arv_stream_try_pop_buffer(stream); + if stale.is_null() { + break; + } + arv_stream_push_buffer(stream, stale); + } + } + } + + // Restore trigger mode & strobe Self::set_feature_str_internal(cam, "TriggerMode", "On"); + Self::set_feature_str_internal(cam, "TriggerSource", "Software"); + + Self::set_feature_str_internal(cam, "LineSelector", "Line1"); + Self::set_feature_str_internal(cam, "LineMode", "Strobe"); + Self::set_feature_str_internal(cam, "LineSource", "ExposureActive"); + Self::set_feature_bool_internal(cam, "StrobeEnable", true); + Self::set_feature_int_internal( + cam, + "StrobeLineDuration", + settings.strobe_line_duration as i64, + ); + + // Restore exposure & gain Self::set_feature_str_internal(cam, "ExposureAuto", &settings.exposure_auto); if settings.exposure_auto == "Off" { Self::set_feature_float_internal(cam, "ExposureTime", settings.camera_exposure); @@ -431,6 +508,14 @@ impl CameraService { settings.frame_rate, ); } + + unsafe { + let mut err = null_mut(); + arv_camera_start_acquisition(cam, &mut err); + if !err.is_null() { + g_error_free(err); + } + } } } } @@ -527,6 +612,54 @@ impl CameraService { } } + 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 + } + } + + 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 + } + } + + 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], diff --git a/headless-rust/src/integrations/teable.rs b/headless-rust/src/integrations/teable.rs index c1f2641..47b2728 100644 --- a/headless-rust/src/integrations/teable.rs +++ b/headless-rust/src/integrations/teable.rs @@ -143,10 +143,145 @@ impl TeableClient { Ok(list) } - #[allow(dead_code)] - pub async fn verify_table(&self, _url: &str, _token: &str, _table_id: &str) -> Result { - Ok(TeableSchemaCheck { - missing_fields: Vec::new(), + 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(), }) } diff --git a/headless-rust/src/main.rs b/headless-rust/src/main.rs index 59b427b..c392b67 100644 --- a/headless-rust/src/main.rs +++ b/headless-rust/src/main.rs @@ -67,6 +67,17 @@ async fn main() -> Result<(), rocket::Error> { // 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() { + println!("[serial] Auto-connecting configured port: {}", settings.selected_port); + serial.open_port(&settings.selected_port); + } + } + } + // ─── Instant Shutter Trigger Pipeline (<10ms latency) ───────────────────── let pipeline_cam = camera.clone(); let pipeline_db = db.clone(); diff --git a/headless-rust/src/models.rs b/headless-rust/src/models.rs index 5c36df7..ff120d3 100644 --- a/headless-rust/src/models.rs +++ b/headless-rust/src/models.rs @@ -244,6 +244,13 @@ pub struct EspPongConfig { 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 { @@ -288,7 +295,10 @@ pub enum SerialStatusPayload { #[serde(rename = "LAPSTOPPED")] LapStopped, #[serde(rename = "CONNECTED")] - Connected, + Connected { + #[serde(default, skip_serializing_if = "Option::is_none")] + port: Option, + }, #[serde(rename = "DISCONNECTED")] Disconnected, } diff --git a/headless-rust/src/serial/mock.rs b/headless-rust/src/serial/mock.rs index ba408c3..b0dd734 100644 --- a/headless-rust/src/serial/mock.rs +++ b/headless-rust/src/serial/mock.rs @@ -46,7 +46,7 @@ impl MockSerial { } pub fn send_command(&self, json: &str, tx: &broadcast::Sender) { - if json.contains("\"PING\"") { + if json.to_lowercase().contains("\"ping\"") { let _ = tx.send(SerialStatusPayload::Pong { config: EspPongConfig { max_speed: 30.0, diff --git a/headless-rust/src/serial/mod.rs b/headless-rust/src/serial/mod.rs index 8d65035..113254a 100644 --- a/headless-rust/src/serial/mod.rs +++ b/headless-rust/src/serial/mod.rs @@ -1,7 +1,7 @@ pub mod mock; pub mod protocol; -use crate::models::{PortInfo, SerialStatusPayload}; +use crate::models::{PortInfo, SerialStatusInfo, SerialStatusPayload}; use protocol::EspMessage; use std::io::{BufRead, BufReader, Write}; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; @@ -23,11 +23,17 @@ 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(String::new()), + active_path: Mutex::new(initial_path), session_id: Arc::new(AtomicU64::new(0)), is_running: Arc::new(AtomicBool::new(true)), status_sender: status_tx, @@ -45,6 +51,33 @@ impl SerialService { 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 { @@ -95,7 +128,10 @@ impl SerialService { pub fn open_port(self: &Arc, port_path: &str) { if self.mock_mode { println!("[serial] Opened mock port {}", port_path); - let _ = self.status_sender.send(SerialStatusPayload::Connected); + *self.active_path.lock().unwrap() = port_path.to_string(); + let _ = self.status_sender.send(SerialStatusPayload::Connected { + port: Some(port_path.to_string()), + }); return; } @@ -123,7 +159,9 @@ impl SerialService { match builder.open() { Ok(port) => { println!("[serial] Successfully opened {}", path); - let _ = this.status_sender.send(SerialStatusPayload::Connected); + let _ = this.status_sender.send(SerialStatusPayload::Connected { + port: Some(path.clone()), + }); let reader_port = match port.try_clone() { Ok(p) => p, diff --git a/headless-rust/src/web/rpc.rs b/headless-rust/src/web/rpc.rs index eece988..3c34cd7 100644 --- a/headless-rust/src/web/rpc.rs +++ b/headless-rust/src/web/rpc.rs @@ -278,6 +278,11 @@ async fn dispatch_method(ctx: &RpcContext, method: &str, params: Value) -> Resul 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); @@ -334,6 +339,20 @@ async fn dispatch_method(ctx: &RpcContext, method: &str, params: Value) -> Resul Ok(Value::Null) } + "setCameraFeatureStr" => { + let feature = params["feature"].as_str().ok_or("Missing feature name")?; + let value = params["value"].as_str().ok_or("Missing feature value")?; + ctx.camera.set_feature_str(feature, value); + Ok(Value::Null) + } + + "setCameraFeatureInt" => { + let feature = params["feature"].as_str().ok_or("Missing feature name")?; + let value = params["value"].as_i64().ok_or("Missing feature value")?; + ctx.camera.set_feature_int(feature, value); + Ok(Value::Null) + } + "applyMfsConfig" => { let mfs = params["mfsContent"].as_str().ok_or("Missing mfsContent")?; let res = ctx.camera.apply_mfs_config(mfs); @@ -386,6 +405,48 @@ async fn dispatch_method(ctx: &RpcContext, method: &str, params: Value) -> Resul Ok(serde_json::to_value(user).unwrap()) } + "saveTeableConfig" => { + let url = params["url"].as_str().unwrap_or(""); + let token = params["token"].as_str().unwrap_or(""); + let name = params["userName"].as_str().unwrap_or(""); + let email = params["userEmail"].as_str().unwrap_or(""); + let avatar = params["userAvatar"].as_str().unwrap_or(""); + + let conn = ctx.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); + Ok(Value::Null) + } + + "removeTeableConfig" => { + let conn = ctx.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"); + Ok(Value::Null) + } + + "saveTeableTarget" => { + let space_id = params["spaceId"].as_str().unwrap_or(""); + let base_id = params["baseId"].as_str().unwrap_or(""); + let table_id = params["tableId"].as_str().unwrap_or(""); + + let conn = ctx.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); + Ok(Value::Null) + } + "listTeableSpaces" => { let settings = { let conn = ctx.db.lock(); @@ -424,6 +485,51 @@ async fn dispatch_method(ctx: &RpcContext, method: &str, params: Value) -> Resul Ok(serde_json::to_value(tables).unwrap()) } + "verifyTeableTable" => { + let table_id = params["tableId"].as_str().ok_or("Missing tableId")?; + let settings = { + let conn = ctx.db.lock(); + crate::db::settings::get_settings(&conn).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 settings = { + let conn = ctx.db.lock(); + crate::db::settings::get_settings(&conn).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 settings = { + let conn = ctx.db.lock(); + crate::db::settings::get_settings(&conn).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 settings = { @@ -480,7 +586,9 @@ async fn dispatch_method(ctx: &RpcContext, method: &str, params: Value) -> Resul } // ─── Stubs for Window & Updater ─────────────────────────────────────── - "minimizeWindow" | "maximizeWindow" | "closeWindow" | "cancelFlash" => Ok(Value::Null), + "minimizeWindow" | "maximizeWindow" | "closeWindow" | "cancelFlash" | "applyUpdate" => { + Ok(Value::Null) + } "getLocalVersion" => Ok(json!({ "version": "0.5.0-rust", @@ -496,6 +604,10 @@ async fn dispatch_method(ctx: &RpcContext, method: &str, params: Value) -> Resul "error": "Native binary managed by system" })), + "downloadUpdate" => Ok(json!({ + "ok": true + })), + _ => Err(format!("Method '{}' not found", method)), } } diff --git a/headless-rust/src/web/ws.rs b/headless-rust/src/web/ws.rs index 65417c9..714c531 100644 --- a/headless-rust/src/web/ws.rs +++ b/headless-rust/src/web/ws.rs @@ -41,11 +41,18 @@ pub fn ws_rpc( println!("[ws] Client connected"); // Push initial camera status immediately - let init_status = json!({ + let init_camera = json!({ "event": "cameraStatus", "payload": ctx.camera.get_status() }); - let _ = stream.send(Message::Text(init_status.to_string())).await; + let _ = stream.send(Message::Text(init_camera.to_string())).await; + + // Push initial serial status immediately + let init_serial = json!({ + "event": "serialStatus", + "payload": ctx.serial.get_status_payload() + }); + let _ = stream.send(Message::Text(init_serial.to_string())).await; loop { tokio::select! { From f08e4ebc3a0b484ca3a56e8beea34c555d567aa5 Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Sat, 15 Aug 2026 00:46:57 +0200 Subject: [PATCH 18/65] feat: add violation handling and notification to WebSocket RPC --- headless-rust/frontend/src/lib/rpc.ts | 3 ++ headless-rust/frontend/src/shared/types.ts | 2 ++ .../src/stores/slices/measurementSlice.ts | 16 ---------- headless-rust/src/camera/mod.rs | 31 ++++++++++++++----- headless-rust/src/main.rs | 6 +++- headless-rust/src/web/mod.rs | 4 ++- headless-rust/src/web/rpc.rs | 2 ++ headless-rust/src/web/ws.rs | 30 +++++++++++++----- 8 files changed, 62 insertions(+), 32 deletions(-) diff --git a/headless-rust/frontend/src/lib/rpc.ts b/headless-rust/frontend/src/lib/rpc.ts index 89f5fae..a6c52d5 100644 --- a/headless-rust/frontend/src/lib/rpc.ts +++ b/headless-rust/frontend/src/lib/rpc.ts @@ -124,6 +124,9 @@ class WebSocketRpcClient { case "liveFrame": store.setLiveFrame(payload as any); break; + case "violation": + store.setLastViolation(payload as any); + break; case "updateAvailable": store.setUpdateVersion((payload as any).version); store.setUpdatePhase("ready"); diff --git a/headless-rust/frontend/src/shared/types.ts b/headless-rust/frontend/src/shared/types.ts index eecaaf6..db528a6 100644 --- a/headless-rust/frontend/src/shared/types.ts +++ b/headless-rust/frontend/src/shared/types.ts @@ -548,5 +548,7 @@ export type SpeedcameraRPC = { flashProgress: FlashProgressPayload; // Live stream frame liveFrame: string; + // Violation notification + violation: Violation; }>; }; diff --git a/headless-rust/frontend/src/stores/slices/measurementSlice.ts b/headless-rust/frontend/src/stores/slices/measurementSlice.ts index 5f873be..e8fa80a 100644 --- a/headless-rust/frontend/src/stores/slices/measurementSlice.ts +++ b/headless-rust/frontend/src/stores/slices/measurementSlice.ts @@ -77,22 +77,6 @@ export const createMeasurementSlice: StateCreator< if (payload.status === "SPEEDING") { const { value, direction } = payload; set({ lastSpeed: value, lastDirection: direction }); - - // Only save violations and flash when fully ARMED - if (systemState !== "ARMED") return; - - const { maxSpeed } = get(); - - // Trigger server-side capture and save - getRpc() - .request.saveViolation({ measuredSpeed: value, maxSpeed, direction }) - .then((v) => { - get().setLastViolation(v); - }) - .catch((err: unknown) => { - console.error("[measurement] Capture/save failed:", err); - toast.error("Failed to save violation"); - }); } else if (payload.status === "OK") { set({ lastSpeed: payload.value, lastDirection: payload.direction }); } diff --git a/headless-rust/src/camera/mod.rs b/headless-rust/src/camera/mod.rs index 6219cab..10831ce 100644 --- a/headless-rust/src/camera/mod.rs +++ b/headless-rust/src/camera/mod.rs @@ -166,6 +166,7 @@ impl CameraService { // Configure Trigger mode & strobe Self::set_feature_str_internal(cam, "AcquisitionMode", "Continuous"); + Self::set_feature_str_internal(cam, "TriggerSelector", "FrameStart"); Self::set_feature_str_internal(cam, "TriggerMode", "On"); Self::set_feature_str_internal(cam, "TriggerSource", "Software"); @@ -349,7 +350,7 @@ impl CameraService { let this = self.clone(); tokio::task::spawn_blocking(move || { - println!("[camera] Setup preview stream started"); + println!("[camera] Setup preview stream starting..."); if !this.mock_mode { let cam = *this.camera_ptr.lock().unwrap(); @@ -384,7 +385,8 @@ impl CameraService { Self::set_feature_str_internal(cam, "LineSelector", "Line2"); Self::set_feature_str_internal(cam, "LineSource", "Off"); - // Set free-running stream features + // Set free-running stream features (capped to 10 FPS to prevent GigE flood) + Self::set_feature_str_internal(cam, "TriggerSelector", "FrameStart"); Self::set_feature_str_internal(cam, "TriggerMode", "Off"); Self::set_feature_str_internal(cam, "ExposureAuto", "Continuous"); Self::set_feature_str_internal(cam, "GainAuto", "Continuous"); @@ -403,6 +405,8 @@ impl CameraService { } } + println!("[camera] Setup preview stream active"); + while this.setup_stream_active.load(Ordering::SeqCst) { if this.mock_mode { if let Some(jpeg) = this.mock_camera.lock().unwrap().capture_jpeg_preview() { @@ -415,12 +419,12 @@ impl CameraService { let stream = *this.stream_ptr.lock().unwrap(); if stream.is_null() { - std::thread::sleep(std::time::Duration::from_millis(80)); + std::thread::sleep(std::time::Duration::from_millis(50)); continue; } unsafe { - let buffer = arv_stream_timeout_pop_buffer(stream, 200_000); + 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 { @@ -441,17 +445,26 @@ impl CameraService { } } arv_stream_push_buffer(stream, buffer); + // Throttle stream loop to ~12 FPS + std::thread::sleep(std::time::Duration::from_millis(75)); + } else { + // No buffer waiting, brief yield + std::thread::sleep(std::time::Duration::from_millis(20)); } } - std::thread::sleep(std::time::Duration::from_millis(30)); } - println!("[camera] Setup preview stream stopped"); + println!("[camera] Setup preview stream thread exited"); }); } pub fn stop_setup_stream(&self, settings: &AppSettings) { - self.setup_stream_active.store(false, Ordering::SeqCst); + 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(); @@ -479,6 +492,7 @@ impl CameraService { } // Restore trigger mode & strobe + Self::set_feature_str_internal(cam, "TriggerSelector", "FrameStart"); Self::set_feature_str_internal(cam, "TriggerMode", "On"); Self::set_feature_str_internal(cam, "TriggerSource", "Software"); @@ -518,6 +532,7 @@ impl CameraService { } } } + println!("[camera] Setup preview stream stopped, restored triggered capture mode"); } pub fn apply_mfs_config(&self, mfs_content: &str) -> MfsConfigResult { @@ -636,6 +651,7 @@ impl CameraService { } } + #[allow(dead_code)] pub fn set_feature_float(&self, feature: &str, value: f64) -> bool { if self.mock_mode { return true; @@ -648,6 +664,7 @@ impl CameraService { } } + #[allow(dead_code)] pub fn set_feature_bool(&self, feature: &str, value: bool) -> bool { if self.mock_mode { return true; diff --git a/headless-rust/src/main.rs b/headless-rust/src/main.rs index c392b67..306d4f3 100644 --- a/headless-rust/src/main.rs +++ b/headless-rust/src/main.rs @@ -79,6 +79,8 @@ async fn main() -> Result<(), rocket::Error> { } // ─── 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(); @@ -92,6 +94,7 @@ async fn main() -> Result<(), rocket::Error> { 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(png_bytes) = cam.capture_frame() { @@ -106,6 +109,7 @@ async fn main() -> Result<(), rocket::Error> { }; if let Ok(v) = db::violations::insert_violation(&conn, &input, &img_path) { println!("[trigger-pipeline] Recorded violation #{} ({} km/h)", v.id, v.measured_speed); + let _ = v_tx.send(v); } } } else { @@ -117,7 +121,7 @@ async fn main() -> Result<(), rocket::Error> { }); // Build and launch Rocket web server - let server = web::build_rocket(config, db, store, camera, serial); + let server = web::build_rocket(config, db, store, camera, serial, violation_tx); server.launch().await?; Ok(()) diff --git a/headless-rust/src/web/mod.rs b/headless-rust/src/web/mod.rs index a8411d3..ec838db 100644 --- a/headless-rust/src/web/mod.rs +++ b/headless-rust/src/web/mod.rs @@ -6,7 +6,7 @@ pub mod ws; use crate::camera::CameraService; use crate::config::AppConfig; use crate::db::Database; -use crate::models::FlashProgressPayload; +use crate::models::{FlashProgressPayload, Violation}; use crate::serial::SerialService; use crate::storage::FileStore; use rocket::fairing::{Fairing, Info, Kind}; @@ -43,6 +43,7 @@ pub fn build_rocket( store: FileStore, camera: Arc, serial: Arc, + violation_tx: broadcast::Sender, ) -> Rocket { let (flash_tx, _) = broadcast::channel::(32); @@ -58,6 +59,7 @@ pub fn build_rocket( .manage(camera) .manage(serial) .manage(flash_tx) + .manage(violation_tx) .mount( "/", rocket::routes![ diff --git a/headless-rust/src/web/rpc.rs b/headless-rust/src/web/rpc.rs index 3c34cd7..2d904a9 100644 --- a/headless-rust/src/web/rpc.rs +++ b/headless-rust/src/web/rpc.rs @@ -38,6 +38,7 @@ pub struct RpcContext { pub serial: Arc, pub teable: TeableClient, pub flash_tx: broadcast::Sender, + pub violation_tx: broadcast::Sender, } pub async fn handle_rpc(ctx: &RpcContext, req: RpcRequest) -> RpcResponse { @@ -119,6 +120,7 @@ async fn dispatch_method(ctx: &RpcContext, method: &str, params: Value) -> Resul let conn = ctx.db.lock(); let v = crate::db::violations::insert_violation(&conn, &input, &image_path) .map_err(|e| e.to_string())?; + let _ = ctx.violation_tx.send(v.clone()); Ok(serde_json::to_value(v).unwrap()) } diff --git a/headless-rust/src/web/ws.rs b/headless-rust/src/web/ws.rs index 714c531..f2dfea5 100644 --- a/headless-rust/src/web/ws.rs +++ b/headless-rust/src/web/ws.rs @@ -1,7 +1,7 @@ use crate::camera::CameraService; use crate::db::Database; use crate::integrations::teable::TeableClient; -use crate::models::FlashProgressPayload; +use crate::models::{FlashProgressPayload, Violation}; use crate::serial::SerialService; use crate::storage::FileStore; use crate::web::rpc::{handle_rpc, RpcContext, RpcRequest}; @@ -21,6 +21,7 @@ pub fn ws_rpc( camera: &State>, serial: &State>, flash_tx: &State>, + violation_tx: &State>, ) -> Channel<'static> { let ctx = Arc::new(RpcContext { db: (*db).clone(), @@ -29,17 +30,20 @@ pub fn ws_rpc( serial: (*serial).clone(), teable: TeableClient::new(), flash_tx: (*flash_tx).clone(), + violation_tx: (*violation_tx).clone(), }); - let mut serial_rx = serial.subscribe(); - let mut camera_status_rx = camera.subscribe_status(); - let mut live_frame_rx = camera.subscribe_frames(); - let mut flash_rx = flash_tx.subscribe(); - ws.channel(move |mut stream: DuplexStream| { + let ctx = ctx.clone(); Box::pin(async move { println!("[ws] Client connected"); + 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(); + // Push initial camera status immediately let init_camera = json!({ "event": "cameraStatus", @@ -107,6 +111,17 @@ pub fn ws_rpc( } } + // Violation broadcast + Ok(v) = violation_rx.recv() => { + let msg = json!({ + "event": "violation", + "payload": v + }); + if stream.send(Message::Text(msg.to_string())).await.is_err() { + break; + } + } + // Flash progress broadcast Ok(payload) = flash_rx.recv() => { let msg = json!({ @@ -134,6 +149,7 @@ pub fn ws_alias( camera: &State>, serial: &State>, flash_tx: &State>, + violation_tx: &State>, ) -> Channel<'static> { - ws_rpc(ws, db, store, camera, serial, flash_tx) + ws_rpc(ws, db, store, camera, serial, flash_tx, violation_tx) } From 93f43badf2f3cf064a0214501868018508daf60c Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Sat, 15 Aug 2026 01:05:59 +0200 Subject: [PATCH 19/65] fix: performance issues and blocking (hopefully) --- headless-rust/src/camera/mock.rs | 30 +++- headless-rust/src/camera/mod.rs | 219 ++++++++++++++++++++---------- headless-rust/src/main.rs | 4 +- headless-rust/src/storage/skin.rs | 6 +- headless-rust/src/web/routes.rs | 16 ++- headless-rust/src/web/rpc.rs | 174 ++++++++++++++++-------- headless-rust/src/web/ws.rs | 23 +++- 7 files changed, 330 insertions(+), 142 deletions(-) diff --git a/headless-rust/src/camera/mock.rs b/headless-rust/src/camera/mock.rs index 88bb5ac..c80f743 100644 --- a/headless-rust/src/camera/mock.rs +++ b/headless-rust/src/camera/mock.rs @@ -40,6 +40,7 @@ impl MockCamera { self.connected = false; } + #[allow(dead_code)] pub fn capture_frame(&self) -> Option> { if !self.connected { return None; @@ -65,6 +66,31 @@ impl MockCamera { 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; @@ -84,8 +110,10 @@ impl MockCamera { let mut buf = Vec::new(); let mut cursor = Cursor::new(&mut buf); - img.write_to(&mut cursor, image::ImageFormat::Jpeg).ok()?; + 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 index 10831ce..bfe2067 100644 --- a/headless-rust/src/camera/mod.rs +++ b/headless-rust/src/camera/mod.rs @@ -162,6 +162,11 @@ impl CameraService { if arv_camera_is_gv_device(cam) != 0 { let packet_size = arv_camera_gv_auto_packet_size(cam, &mut err); println!("[camera] GigE Vision auto packet size set to: {} bytes", packet_size); + + // Set GevSCPD (Stream Channel Packet Delay) to 2000 ticks + // This spaces out UDP packets to prevent NIC packet storms and SSH stalls + Self::set_feature_int_internal(cam, "GevSCPD", 2000); + println!("[camera] GigE Vision GevSCPD packet delay set to: 2000"); } // Configure Trigger mode & strobe @@ -200,7 +205,7 @@ impl CameraService { ); } - // Create Stream with 8 pre-allocated buffers for robust throughput + // 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() { println!("[camera] Failed to create stream"); @@ -209,11 +214,12 @@ impl CameraService { } let payload_size = Self::get_feature_int_internal(cam, "PayloadSize").max(1024 * 1024); - for _ in 0..8 { + for _ in 0..24 { let buf = arv_buffer_new_allocate(payload_size as usize); 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); @@ -270,75 +276,84 @@ impl CameraService { 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_frame(); + return self.mock_camera.lock().unwrap().capture_jpeg_frame(); } if !self.is_connected.load(Ordering::SeqCst) { return None; } - let cam = *self.camera_ptr.lock().unwrap(); - let stream = *self.stream_ptr.lock().unwrap(); - if cam.is_null() || stream.is_null() { - 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; + 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); } - arv_stream_push_buffer(stream, stale); - } - // Software trigger - let mut err = null_mut(); - let trigger_cmd = CString::new("TriggerSoftware").unwrap(); - arv_camera_execute_command(cam, trigger_cmd.as_ptr(), &mut err); - if !err.is_null() { - let msg = CStr::from_ptr((*err).message).to_string_lossy(); - println!("[camera] TriggerSoftware failed: {}", msg); - g_error_free(err); - } + // Software trigger + let mut err = null_mut(); + let trigger_cmd = CString::new("TriggerSoftware").unwrap(); + arv_camera_execute_command(cam, trigger_cmd.as_ptr(), &mut err); + if !err.is_null() { + let msg = CStr::from_ptr((*err).message).to_string_lossy(); + println!("[camera] TriggerSoftware failed: {}", msg); + g_error_free(err); + } - // Wait up to 1.5 seconds for completed frame - let buffer = arv_stream_timeout_pop_buffer(stream, 1_500_000); - if buffer.is_null() { - println!("[camera] Capture frame timed out"); - return None; - } + // Wait up to 1.5 seconds for completed frame + let buffer = arv_stream_timeout_pop_buffer(stream, 1_500_000); + if buffer.is_null() { + println!("[camera] Capture frame timed out"); + return None; + } - let status = arv_buffer_get_status(buffer); - if status != ARV_BUFFER_STATUS_SUCCESS { - println!( - "[camera] Capture buffer failed with status: {} ({})", - buffer_status_name(status), - status - ); - arv_stream_push_buffer(stream, buffer); - return None; - } + let status = arv_buffer_get_status(buffer); + if status != ARV_BUFFER_STATUS_SUCCESS { + println!( + "[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 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_slice = std::slice::from_raw_parts(data_ptr, size); + let raw_vec = std::slice::from_raw_parts(data_ptr, size).to_vec(); - // Convert to PNG buffer - let png_bytes = Self::raw_buffer_to_png(raw_slice, width, height, pixel_format); + // Recycle buffer immediately back to stream pool + arv_stream_push_buffer(stream, buffer); - // Recycle buffer 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! - png_bytes - } + // 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) { @@ -407,6 +422,8 @@ impl CameraService { println!("[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() { @@ -428,28 +445,44 @@ impl CameraService { if !buffer.is_null() { let status = arv_buffer_get_status(buffer); if status == ARV_BUFFER_STATUS_SUCCESS { - 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 = std::slice::from_raw_parts(data_ptr, size); - - if let Some(jpeg) = - Self::raw_buffer_to_downscaled_jpeg(slice, width, height, pixel_format) - { - let b64 = - base64::engine::general_purpose::STANDARD.encode(&jpeg); - let _ = this.frame_sender.send(b64); + // 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); } - arv_stream_push_buffer(stream, buffer); - // Throttle stream loop to ~12 FPS - std::thread::sleep(std::time::Duration::from_millis(75)); } else { - // No buffer waiting, brief yield - std::thread::sleep(std::time::Duration::from_millis(20)); + // No buffer ready, brief yield to prevent tight spin + std::thread::sleep(std::time::Duration::from_millis(5)); } } } @@ -896,6 +929,7 @@ impl CameraService { Some(rgb) } + #[allow(dead_code)] fn raw_buffer_to_png( raw: &[u8], width: u32, @@ -909,6 +943,32 @@ impl CameraService { 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, @@ -920,11 +980,24 @@ impl CameraService { let mut buf = Vec::new(); let mut cursor = Cursor::new(&mut buf); - resized.write_to(&mut cursor, image::ImageFormat::Jpeg).ok()?; + 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) } + fn set_feature_str_internal(cam: *mut ArvCamera, feature: &str, value: &str) -> bool { unsafe { let f_cstr = match CString::new(feature) { diff --git a/headless-rust/src/main.rs b/headless-rust/src/main.rs index 306d4f3..849306a 100644 --- a/headless-rust/src/main.rs +++ b/headless-rust/src/main.rs @@ -97,8 +97,8 @@ async fn main() -> Result<(), rocket::Error> { let v_tx = pipeline_violation_tx.clone(); tokio::task::spawn_blocking(move || { - if let Some(png_bytes) = cam.capture_frame() { - if let Ok(img_path) = store_clone.save_image_bytes(&png_bytes, "png") { + 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 { diff --git a/headless-rust/src/storage/skin.rs b/headless-rust/src/storage/skin.rs index b7741f4..a1e3893 100644 --- a/headless-rust/src/storage/skin.rs +++ b/headless-rust/src/storage/skin.rs @@ -76,10 +76,12 @@ pub fn render_poliscan_skin( 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 PNG buffer + // Encode to fast high-quality JPEG buffer (<10ms) let mut out = Vec::new(); let mut cursor = Cursor::new(&mut out); - canvas.write_to(&mut cursor, image::ImageFormat::Png).ok()?; + 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/routes.rs b/headless-rust/src/web/routes.rs index cdeb318..43bbc5c 100644 --- a/headless-rust/src/web/routes.rs +++ b/headless-rust/src/web/routes.rs @@ -37,7 +37,12 @@ pub fn get_image( ) -> Result<(ContentType, Vec), Status> { let p = path.ok_or(Status::BadRequest)?; let bytes = store.read_image(&p).ok_or(Status::NotFound)?; - Ok((ContentType::PNG, bytes)) + let content_type = if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) { + ContentType::JPEG + } else { + ContentType::PNG + }; + Ok((content_type, bytes)) } #[rocket::get("/skinned-image?")] @@ -63,9 +68,16 @@ pub fn get_skinned_image( ) .ok_or(Status::InternalServerError)?; - Ok((ContentType::PNG, rendered)) + let content_type = if rendered.starts_with(&[0xFF, 0xD8, 0xFF]) { + ContentType::JPEG + } else { + ContentType::PNG + }; + + Ok((content_type, rendered)) } + #[rocket::get("/", rank = 20)] pub fn static_assets(file: std::path::PathBuf) -> Result { let path_str = file.to_string_lossy().to_string(); diff --git a/headless-rust/src/web/rpc.rs b/headless-rust/src/web/rpc.rs index 2d904a9..c5c2515 100644 --- a/headless-rust/src/web/rpc.rs +++ b/headless-rust/src/web/rpc.rs @@ -101,26 +101,47 @@ async fn dispatch_method(ctx: &RpcContext, method: &str, params: Value) -> Resul let input: SaveViolationInput = serde_json::from_value(params).map_err(|e| e.to_string())?; - let raw_png = if let Some(ref b64) = input.image_base64 { - let clean = b64.trim_start_matches("data:image/png;base64,"); - base64::engine::general_purpose::STANDARD - .decode(clean) - .map_err(|e| e.to_string())? - } else { - ctx.camera - .capture_frame() - .ok_or_else(|| "Failed to capture frame from industrial camera".to_string())? - }; - - let image_path = ctx - .store - .save_image_bytes(&raw_png, "png") - .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())??; - let conn = ctx.db.lock(); - let v = crate::db::violations::insert_violation(&conn, &input, &image_path) - .map_err(|e| e.to_string())?; - let _ = ctx.violation_tx.send(v.clone()); Ok(serde_json::to_value(v).unwrap()) } @@ -225,38 +246,53 @@ async fn dispatch_method(ctx: &RpcContext, method: &str, params: Value) -> Resul "exportSkinnedImages" => { let ids = params["violationIds"] .as_array() - .ok_or("Missing violationIds")?; - let target_dir = params["targetDir"].as_str().ok_or("Missing targetDir")?; - - let conn = ctx.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) = ctx.store.read_image(&v.image_path) { - if let Some(skinned) = render_poliscan_skin( - &bytes, - &v, - &settings.skin_measuring_location, - ) { - let out_path = Path::new(target_dir) - .join(format!("violation-{}-{}.png", v.id, v.timestamp.replace(":", "-"))); - if std::fs::write(out_path, skinned).is_ok() { - exported += 1; - continue; + .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; } - failed += 1; } - } - Ok(serde_json::to_value(ExportSkinnedResult { exported, failed }).unwrap()) + Ok(ExportSkinnedResult { exported, failed }) + }) + .await + .map_err(|e| e.to_string())??; + + Ok(serde_json::to_value(res).unwrap()) } // ─── Settings ───────────────────────────────────────────────────────── @@ -304,14 +340,25 @@ async fn dispatch_method(ctx: &RpcContext, method: &str, params: Value) -> Resul // ─── Camera HW ──────────────────────────────────────────────────────── "connectCamera" => { - let conn = ctx.db.lock(); - let settings = crate::db::settings::get_settings(&conn).unwrap_or_default(); - ctx.camera.connect(&settings); + 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" => { - ctx.camera.disconnect(); + let cam = ctx.camera.clone(); + tokio::task::spawn_blocking(move || { + cam.disconnect(); + }) + .await + .map_err(|e| e.to_string())?; Ok(Value::Null) } @@ -321,9 +368,20 @@ async fn dispatch_method(ctx: &RpcContext, method: &str, params: Value) -> Resul } "captureFrame" => { - if let Some(png_bytes) = ctx.camera.capture_frame() { - let b64 = base64::engine::general_purpose::STANDARD.encode(&png_bytes); - Ok(Value::String(b64)) + 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) } @@ -367,9 +425,15 @@ async fn dispatch_method(ctx: &RpcContext, method: &str, params: Value) -> Resul } "stopSetupStream" => { - let conn = ctx.db.lock(); - let settings = crate::db::settings::get_settings(&conn).unwrap_or_default(); - ctx.camera.stop_setup_stream(&settings); + 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) } diff --git a/headless-rust/src/web/ws.rs b/headless-rust/src/web/ws.rs index f2dfea5..6493b08 100644 --- a/headless-rust/src/web/ws.rs +++ b/headless-rust/src/web/ws.rs @@ -101,16 +101,25 @@ pub fn ws_rpc( } // Live frame broadcast - Ok(b64_frame) = live_frame_rx.recv() => { - let msg = json!({ - "event": "liveFrame", - "payload": b64_frame - }); - if stream.send(Message::Text(msg.to_string())).await.is_err() { - break; + res = live_frame_rx.recv() => { + match res { + Ok(b64_frame) => { + let msg = json!({ + "event": "liveFrame", + "payload": b64_frame + }); + if stream.send(Message::Text(msg.to_string())).await.is_err() { + break; + } + } + Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => { + // Expected when live frames exceed client WebSocket consumption rate + } + Err(tokio::sync::broadcast::error::RecvError::Closed) => break, } } + // Violation broadcast Ok(v) = violation_rx.recv() => { let msg = json!({ From 081a2914be758f73e1237d1eb8d5d0653e64b1df Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Sat, 15 Aug 2026 01:24:10 +0200 Subject: [PATCH 20/65] fix: trigger pipeline bug, websocket blocking, camera status, pub sub event pipelines --- .../src/components/LastCapturedImage.tsx | 20 +- .../frontend/src/hooks/useBackendEvent.ts | 30 +++ headless-rust/frontend/src/lib/rpc.ts | 154 +++++++++++--- headless-rust/frontend/src/routes/setup.tsx | 73 +++++-- .../src/routes/violations/useViolations.ts | 16 ++ headless-rust/frontend/src/shared/types.ts | 1 + .../frontend/src/stores/slices/cameraSlice.ts | 2 + headless-rust/src/camera/mock.rs | 3 +- headless-rust/src/camera/mod.rs | 7 +- headless-rust/src/main.rs | 65 +++--- headless-rust/src/models.rs | 1 + headless-rust/src/web/ws.rs | 194 ++++++++++++------ 12 files changed, 429 insertions(+), 137 deletions(-) create mode 100644 headless-rust/frontend/src/hooks/useBackendEvent.ts diff --git a/headless-rust/frontend/src/components/LastCapturedImage.tsx b/headless-rust/frontend/src/components/LastCapturedImage.tsx index 42dd6d0..1a6b42d 100644 --- a/headless-rust/frontend/src/components/LastCapturedImage.tsx +++ b/headless-rust/frontend/src/components/LastCapturedImage.tsx @@ -1,15 +1,31 @@ import { useEffect, useState } from "react"; import { getRpc } from "@/lib/rpc"; import { useAppStore } from "@/stores/useAppStore"; +import { useBackendEvent } from "@/hooks/useBackendEvent"; import { Image as ImageIcon } from "lucide-react"; export function LastCapturedImage() { const lastViolation = useAppStore((s) => s.lastViolation); const [imageSrc, setImageSrc] = useState(null); + const loadImage = (imagePath: string) => { + getRpc() + .request.getImageData({ imagePath }) + .then((src) => { + setImageSrc(`${src}&_t=${Date.now()}`); + }) + .catch(() => setImageSrc(null)); + }; + + useBackendEvent("violation", (v) => { + if (v && v.imagePath) { + loadImage(v.imagePath); + } + }); + useEffect(() => { - if (lastViolation) { - getRpc().request.getImageData({ imagePath: lastViolation.imagePath }).then(setImageSrc).catch(() => setImageSrc(null)); + if (lastViolation && lastViolation.imagePath) { + loadImage(lastViolation.imagePath); } else { setImageSrc(null); } 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/lib/rpc.ts b/headless-rust/frontend/src/lib/rpc.ts index a6c52d5..f015b2d 100644 --- a/headless-rust/frontend/src/lib/rpc.ts +++ b/headless-rust/frontend/src/lib/rpc.ts @@ -1,5 +1,6 @@ -import type { SpeedcameraRPC } from "@/shared/types"; +import type { SpeedcameraRPC, Violation, SerialStatusPayload, CameraStatusPayload, FlashProgressPayload } from "@/shared/types"; import { useAppStore } from "@/stores/useAppStore"; +import { toast } from "sonner"; type RequestMap = SpeedcameraRPC["bun"]["requests"]; type PushMessageMap = SpeedcameraRPC["webview"]["messages"]; @@ -12,6 +13,8 @@ export type SpeedcameraClientRPC = { }; }; +type EventCallback = (payload: T) => void; + class WebSocketRpcClient { private ws: WebSocket | null = null; private reqIdCounter = 0; @@ -21,10 +24,17 @@ class WebSocketRpcClient { resolve: (val: any) => void; reject: (err: any) => void; timer: ReturnType; + method: string; } >(); + private messageQueue: string[] = []; private reconnectTimeout: ReturnType | null = null; + private reconnectDelay = 500; + private maxReconnectDelay = 5000; private isConnecting = false; + private isExplicitlyClosed = false; + + private listeners = new Map>(); constructor() { this.connect(); @@ -37,8 +47,10 @@ class WebSocketRpcClient { return `${protocol}//${host}/ws/rpc`; } - private connect() { + public connect() { if (typeof window === "undefined" || this.isConnecting) return; + if (this.ws && (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING)) return; + this.isConnecting = true; try { @@ -49,13 +61,23 @@ class WebSocketRpcClient { ws.onopen = () => { console.log("[rpc-client] Connected to speedcamera daemon"); this.isConnecting = false; + this.reconnectDelay = 500; + this.emit("connectionChange", true); + + // Flush any queued messages + while (this.messageQueue.length > 0) { + const queued = this.messageQueue.shift(); + if (queued && ws.readyState === WebSocket.OPEN) { + ws.send(queued); + } + } }; ws.onmessage = (event) => { try { const data = JSON.parse(event.data); - - // Case 1: Response to a pending request + + // Case 1: Response to a pending RPC request if (data.id !== undefined && this.pendingRequests.has(data.id)) { const pending = this.pendingRequests.get(data.id)!; this.pendingRequests.delete(data.id); @@ -80,31 +102,86 @@ class WebSocketRpcClient { }; ws.onerror = (err) => { - console.warn("[rpc-client] WebSocket error:", err); + console.warn("[rpc-client] WebSocket transport error:", err); + this.isConnecting = false; }; - ws.onclose = () => { - console.log("[rpc-client] Disconnected. Reconnecting in 2s..."); + ws.onclose = (event) => { + console.log(`[rpc-client] Disconnected (code: ${event.code}). Reconnecting in ${this.reconnectDelay}ms...`); this.isConnecting = false; this.ws = null; - if (!this.reconnectTimeout) { + this.emit("connectionChange", false); + + if (!this.isExplicitlyClosed && !this.reconnectTimeout) { this.reconnectTimeout = setTimeout(() => { this.reconnectTimeout = null; + this.reconnectDelay = Math.min(this.reconnectDelay * 1.5, this.maxReconnectDelay); this.connect(); - }, 2000); + }, this.reconnectDelay); } }; } catch (err) { this.isConnecting = false; - console.error("[rpc-client] Connection failed:", err); + console.error("[rpc-client] Failed to create WebSocket connection:", err); + if (!this.reconnectTimeout) { + this.reconnectTimeout = setTimeout(() => { + this.reconnectTimeout = null; + this.connect(); + }, this.reconnectDelay); + } + } + } + + 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 any; + const serialPayload = payload as SerialStatusPayload; if (serialPayload?.status === "CONNECTED") { const port = serialPayload.port || store.selectedPort || "connected"; store.setConnectedPort(port); @@ -115,17 +192,28 @@ class WebSocketRpcClient { store.handleSerialStatus(serialPayload); break; } - case "flashProgress": - store.handleFlashProgress(payload as any); - break; - case "cameraStatus": - store.setCameraStatus(payload as any); + case "cameraStatus": { + const camPayload = payload as CameraStatusPayload; + store.setCameraStatus(camPayload); break; + } case "liveFrame": - store.setLiveFrame(payload as any); + store.setLiveFrame(payload as string); break; - case "violation": - store.setLastViolation(payload as any); + 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 "updateAvailable": store.setUpdateVersion((payload as any).version); @@ -137,6 +225,9 @@ class WebSocketRpcClient { default: break; } + + // 2. Dispatch to custom pub-sub event listeners + this.emit(event, payload); } public call(method: string, params: any): Promise { @@ -149,33 +240,29 @@ class WebSocketRpcClient { } }, 10000); - this.pendingRequests.set(id, { resolve, reject, timer }); + this.pendingRequests.set(id, { resolve, reject, timer, method }); + const payloadStr = JSON.stringify({ id, method, params }); if (this.ws && this.ws.readyState === WebSocket.OPEN) { - this.ws.send(JSON.stringify({ id, method, params })); + this.ws.send(payloadStr); } else { - // If websocket not ready yet, wait briefly or connect - const checkInterval = setInterval(() => { - if (this.ws && this.ws.readyState === WebSocket.OPEN) { - clearInterval(checkInterval); - this.ws.send(JSON.stringify({ id, method, params })); - } - }, 100); - - // Cancel retry if request times out - setTimeout(() => clearInterval(checkInterval), 9500); + // Queue message and ensure connection is active + this.messageQueue.push(payloadStr); + if (!this.ws || this.ws.readyState === WebSocket.CLOSED) { + this.connect(); + } } }); } } -const client = new WebSocketRpcClient(); +export const rpcClient = new WebSocketRpcClient(); // Proxy accessor so `getRpc().request.someMethod(params)` works transparently const rpcProxy: SpeedcameraClientRPC = { request: new Proxy({} as any, { get(_target, prop: string) { - return (params: any = {}) => client.call(prop, params); + return (params: any = {}) => rpcClient.call(prop, params); }, }), }; @@ -183,3 +270,4 @@ const rpcProxy: SpeedcameraClientRPC = { export function getRpc(): SpeedcameraClientRPC { return rpcProxy; } + diff --git a/headless-rust/frontend/src/routes/setup.tsx b/headless-rust/frontend/src/routes/setup.tsx index f71136b..aa8240e 100644 --- a/headless-rust/frontend/src/routes/setup.tsx +++ b/headless-rust/frontend/src/routes/setup.tsx @@ -1,10 +1,11 @@ -import { useEffect } from "react"; +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 } from "lucide-react"; +import { PlayIcon, SquareIcon, AlertCircleIcon, Loader2Icon } from "lucide-react"; import { toast } from "sonner"; export const SetupRoute = createRoute({ @@ -16,14 +17,32 @@ export const SetupRoute = createRoute({ function SetupPage() { const connected = useAppStore((s) => s.cameraConnected); const setupStreamActive = useAppStore((s) => s.setupStreamActive); - const liveFrame = useAppStore((s) => s.liveFrame); 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(() => { - // Stop stream on unmount return () => { - stopSetupStream().catch(console.error); + if (setupStreamActiveRef.current) { + stopSetupStream().catch(console.error); + } }; }, [stopSetupStream]); @@ -32,18 +51,27 @@ function SetupPage() { 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); } }; @@ -62,12 +90,22 @@ function SetupPage() { {setupStreamActive ? "Streaming" : "Stopped"} {!setupStreamActive ? ( - ) : ( - )}
@@ -75,20 +113,25 @@ function SetupPage() {
{setupStreamActive ? ( - liveFrame ? ( + frame ? ( Camera Livestream ) : (
- Waiting for frame... + Waiting for frame from camera...
) ) : ( -
- {connected ? "Click Start Stream to begin setup" : "Camera disconnected"} +
+

{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/violations/useViolations.ts b/headless-rust/frontend/src/routes/violations/useViolations.ts index 29fc17a..6a4a7f6 100644 --- a/headless-rust/frontend/src/routes/violations/useViolations.ts +++ b/headless-rust/frontend/src/routes/violations/useViolations.ts @@ -1,6 +1,7 @@ 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; @@ -83,6 +84,21 @@ export function useViolations(): ViolationsState { 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 }); diff --git a/headless-rust/frontend/src/shared/types.ts b/headless-rust/frontend/src/shared/types.ts index db528a6..5644f11 100644 --- a/headless-rust/frontend/src/shared/types.ts +++ b/headless-rust/frontend/src/shared/types.ts @@ -118,6 +118,7 @@ export interface CameraStatusPayload { vendor: string | null; model: string | null; serial: string | null; + isStreaming: boolean; } export interface ViolationQuery { diff --git a/headless-rust/frontend/src/stores/slices/cameraSlice.ts b/headless-rust/frontend/src/stores/slices/cameraSlice.ts index 594a3c6..cc56c2e 100644 --- a/headless-rust/frontend/src/stores/slices/cameraSlice.ts +++ b/headless-rust/frontend/src/stores/slices/cameraSlice.ts @@ -70,6 +70,7 @@ export const createCameraSlice: StateCreator = cameraVendor: status.vendor, cameraModel: status.model, cameraSerial: status.serial, + setupStreamActive: status.isStreaming, }), connectCamera: async () => { @@ -83,6 +84,7 @@ export const createCameraSlice: StateCreator = cameraVendor: status.vendor, cameraModel: status.model, cameraSerial: status.serial, + setupStreamActive: status.isStreaming, }); }, diff --git a/headless-rust/src/camera/mock.rs b/headless-rust/src/camera/mock.rs index c80f743..64aa962 100644 --- a/headless-rust/src/camera/mock.rs +++ b/headless-rust/src/camera/mock.rs @@ -11,7 +11,7 @@ impl MockCamera { Self { connected: true } } - pub fn status(&self) -> CameraStatusPayload { + pub fn status(&self, is_streaming: bool) -> CameraStatusPayload { CameraStatusPayload { connected: self.connected, vendor: if self.connected { @@ -29,6 +29,7 @@ impl MockCamera { } else { None }, + is_streaming, } } diff --git a/headless-rust/src/camera/mod.rs b/headless-rust/src/camera/mod.rs index bfe2067..717c1fd 100644 --- a/headless-rust/src/camera/mod.rs +++ b/headless-rust/src/camera/mod.rs @@ -64,8 +64,9 @@ impl CameraService { } 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(); + return self.mock_camera.lock().unwrap().status(is_streaming); } let is_conn = self.is_connected.load(Ordering::SeqCst); @@ -100,6 +101,7 @@ impl CameraService { vendor, model, serial, + is_streaming, } } } else { @@ -108,6 +110,7 @@ impl CameraService { vendor: None, model: None, serial: None, + is_streaming: false, } } } @@ -362,6 +365,7 @@ impl CameraService { } 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 || { @@ -566,6 +570,7 @@ impl CameraService { } } println!("[camera] Setup preview stream stopped, restored triggered capture mode"); + let _ = self.status_sender.send(self.get_status()); } pub fn apply_mfs_config(&self, mfs_content: &str) -> MfsConfigResult { diff --git a/headless-rust/src/main.rs b/headless-rust/src/main.rs index 849306a..fc5584f 100644 --- a/headless-rust/src/main.rs +++ b/headless-rust/src/main.rs @@ -87,35 +87,46 @@ async fn main() -> Result<(), rocket::Error> { let mut serial_rx = serial.subscribe(); tokio::spawn(async move { - while let Ok(msg) = serial_rx.recv().await { - if let models::SerialStatusPayload::Speeding { value, direction, .. } = msg { - println!("[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) { - println!("[trigger-pipeline] Recorded violation #{} ({} km/h)", v.id, v.measured_speed); - let _ = v_tx.send(v); + loop { + match serial_rx.recv().await { + Ok(msg) => { + if let models::SerialStatusPayload::Speeding { value, direction, .. } = msg { + println!("[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) { + println!("[trigger-pipeline] Recorded violation #{} ({} km/h)", v.id, v.measured_speed); + let _ = v_tx.send(v); + } + } + } else { + println!("[trigger-pipeline] Failed to capture frame during speeding event"); } - } - } else { - println!("[trigger-pipeline] Failed to capture frame during speeding event"); + }); } - }); + } + Err(tokio::sync::broadcast::error::RecvError::Lagged(missed)) => { + println!("[trigger-pipeline] Warning: Serial receiver lagged by {} messages", missed); + } + Err(tokio::sync::broadcast::error::RecvError::Closed) => { + println!("[trigger-pipeline] Serial channel closed, exiting pipeline task"); + break; + } } } }); diff --git a/headless-rust/src/models.rs b/headless-rust/src/models.rs index ff120d3..8737ff6 100644 --- a/headless-rust/src/models.rs +++ b/headless-rust/src/models.rs @@ -154,6 +154,7 @@ pub struct CameraStatusPayload { pub vendor: Option, pub model: Option, pub serial: Option, + pub is_streaming: bool, } #[derive(Debug, Clone, Serialize, Deserialize)] diff --git a/headless-rust/src/web/ws.rs b/headless-rust/src/web/ws.rs index 6493b08..ae5625f 100644 --- a/headless-rust/src/web/ws.rs +++ b/headless-rust/src/web/ws.rs @@ -11,7 +11,8 @@ use rocket_ws::stream::DuplexStream; use rocket_ws::{Channel, Message, WebSocket}; use serde_json::json; use std::sync::Arc; -use tokio::sync::broadcast; +use std::time::Duration; +use tokio::sync::{broadcast, mpsc}; #[rocket::get("/ws/rpc")] pub fn ws_rpc( @@ -33,74 +34,132 @@ pub fn ws_rpc( violation_tx: (*violation_tx).clone(), }); - ws.channel(move |mut stream: DuplexStream| { + ws.channel(move |stream: DuplexStream| { let ctx = ctx.clone(); Box::pin(async move { println!("[ws] Client connected"); - 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 ws_sink, mut ws_stream) = stream.split(); + + // MPSC channel for multiplexing outgoing messages onto the WebSocket sink + let (out_tx, mut out_rx) = mpsc::channel::(128); - // Push initial camera status immediately + // Dedicated Writer Task + let writer_handle = tokio::spawn(async move { + while let Some(msg) = out_rx.recv().await { + if let Err(e) = ws_sink.send(msg).await { + println!("[ws-writer] Send error or client disconnected: {}", e); + break; + } + } + let _ = ws_sink.close().await; + }); + + // Push initial camera status immediately (with isStreaming state) let init_camera = json!({ "event": "cameraStatus", "payload": ctx.camera.get_status() }); - let _ = stream.send(Message::Text(init_camera.to_string())).await; + let _ = out_tx.send(Message::Text(init_camera.to_string())).await; // Push initial serial status immediately let init_serial = json!({ "event": "serialStatus", "payload": ctx.serial.get_status_payload() }); - let _ = stream.send(Message::Text(init_serial.to_string())).await; + let _ = out_tx.send(Message::Text(init_serial.to_string())).await; + + // Subscribe to all backend event channels + 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(); + + // Heartbeat ping interval + let mut ping_interval = tokio::time::interval(Duration::from_secs(15)); + ping_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); loop { tokio::select! { // Incoming message from client - Some(msg) = stream.next() => { - match msg { - Ok(Message::Text(text)) => { + incoming = ws_stream.next() => { + match incoming { + Some(Ok(Message::Text(text))) => { if let Ok(req) = serde_json::from_str::(&text) { - let resp = handle_rpc(&ctx, req).await; - let resp_json = serde_json::to_string(&resp).unwrap_or_default(); - if stream.send(Message::Text(resp_json)).await.is_err() { - break; - } + let ctx_clone = ctx.clone(); + let out_tx_clone = out_tx.clone(); + // Handle RPC asynchronously in independent task to prevent blocking the select loop + tokio::spawn(async move { + let resp = handle_rpc(&ctx_clone, req).await; + if let Ok(resp_json) = serde_json::to_string(&resp) { + let _ = out_tx_clone.send(Message::Text(resp_json)).await; + } + }); } } - Ok(Message::Close(_)) => break, - Err(_) => break, + Some(Ok(Message::Ping(payload))) => { + let _ = out_tx.send(Message::Pong(payload)).await; + } + Some(Ok(Message::Pong(_))) => {} + Some(Ok(Message::Close(_))) | None => { + println!("[ws] Client disconnected cleanly"); + break; + } + Some(Err(e)) => { + println!("[ws] Error reading from stream: {}", e); + break; + } _ => {} } } - // Serial telemetry broadcast - Ok(payload) = serial_rx.recv() => { - let msg = json!({ - "event": "serialStatus", - "payload": payload - }); - if stream.send(Message::Text(msg.to_string())).await.is_err() { + // Periodic Ping keepalive + _ = ping_interval.tick() => { + if out_tx.send(Message::Ping(Vec::new())).await.is_err() { break; } } + // Serial telemetry broadcast + res = serial_rx.recv() => { + match res { + Ok(payload) => { + let msg = json!({ + "event": "serialStatus", + "payload": payload + }); + if out_tx.send(Message::Text(msg.to_string())).await.is_err() { + break; + } + } + Err(broadcast::error::RecvError::Lagged(n)) => { + println!("[ws] Serial broadcast lagged by {} messages", n); + } + Err(broadcast::error::RecvError::Closed) => break, + } + } + // Camera status broadcast - Ok(payload) = camera_status_rx.recv() => { - let msg = json!({ - "event": "cameraStatus", - "payload": payload - }); - if stream.send(Message::Text(msg.to_string())).await.is_err() { - break; + res = camera_status_rx.recv() => { + match res { + Ok(payload) => { + let msg = json!({ + "event": "cameraStatus", + "payload": payload + }); + if out_tx.send(Message::Text(msg.to_string())).await.is_err() { + break; + } + } + Err(broadcast::error::RecvError::Lagged(n)) => { + println!("[ws] Camera status broadcast lagged by {} messages", n); + } + Err(broadcast::error::RecvError::Closed) => break, } } - // Live frame broadcast + // Live frame broadcast (conflated: drop frame if channel is busy to prevent backpressure stalls) res = live_frame_rx.recv() => { match res { Ok(b64_frame) => { @@ -108,43 +167,62 @@ pub fn ws_rpc( "event": "liveFrame", "payload": b64_frame }); - if stream.send(Message::Text(msg.to_string())).await.is_err() { - break; - } + // Use try_send so slow WebSocket consumers never stall critical telemetry or RPCs + let _ = out_tx.try_send(Message::Text(msg.to_string())); } - Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => { - // Expected when live frames exceed client WebSocket consumption rate + Err(broadcast::error::RecvError::Lagged(_)) => { + // Frame skipping is normal when preview rate exceeds network bandwidth } - Err(tokio::sync::broadcast::error::RecvError::Closed) => break, + Err(broadcast::error::RecvError::Closed) => break, } } - - // Violation broadcast - Ok(v) = violation_rx.recv() => { - let msg = json!({ - "event": "violation", - "payload": v - }); - if stream.send(Message::Text(msg.to_string())).await.is_err() { - break; + // Violation broadcast (high priority) + res = violation_rx.recv() => { + match res { + Ok(v) => { + println!("[ws] Broadcasting violation #{} to client", v.id); + let msg = json!({ + "event": "violation", + "payload": v + }); + if out_tx.send(Message::Text(msg.to_string())).await.is_err() { + break; + } + } + Err(broadcast::error::RecvError::Lagged(n)) => { + println!("[ws] Violation broadcast lagged by {} messages", n); + } + Err(broadcast::error::RecvError::Closed) => break, } } // Flash progress broadcast - Ok(payload) = flash_rx.recv() => { - let msg = json!({ - "event": "flashProgress", - "payload": payload - }); - if stream.send(Message::Text(msg.to_string())).await.is_err() { - break; + res = flash_rx.recv() => { + match res { + Ok(payload) => { + let msg = json!({ + "event": "flashProgress", + "payload": payload + }); + if out_tx.send(Message::Text(msg.to_string())).await.is_err() { + break; + } + } + Err(broadcast::error::RecvError::Lagged(n)) => { + println!("[ws] Flash progress broadcast lagged by {} messages", n); + } + Err(broadcast::error::RecvError::Closed) => break, } } } } - println!("[ws] Client disconnected"); + // Drop out_tx so writer task finishes + drop(out_tx); + let _ = writer_handle.await; + + println!("[ws] Client session ended"); Ok(()) }) }) From 7ddd9600bfc95772f7a00008276483436bb48c3e Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Sat, 15 Aug 2026 01:52:41 +0200 Subject: [PATCH 21/65] fix: GenICam camera configuration --- .../frontend/src/stores/slices/cameraSlice.ts | 4 + headless-rust/src/camera/ffi.rs | 62 ++- headless-rust/src/camera/mod.rs | 495 ++++++++++++++---- headless-rust/src/web/rpc.rs | 3 +- 4 files changed, 445 insertions(+), 119 deletions(-) diff --git a/headless-rust/frontend/src/stores/slices/cameraSlice.ts b/headless-rust/frontend/src/stores/slices/cameraSlice.ts index cc56c2e..0752646 100644 --- a/headless-rust/frontend/src/stores/slices/cameraSlice.ts +++ b/headless-rust/frontend/src/stores/slices/cameraSlice.ts @@ -114,6 +114,10 @@ export const createCameraSlice: StateCreator = } 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 }); } diff --git a/headless-rust/src/camera/ffi.rs b/headless-rust/src/camera/ffi.rs index 9a2c5db..4bd0cd4 100644 --- a/headless-rust/src/camera/ffi.rs +++ b/headless-rust/src/camera/ffi.rs @@ -3,6 +3,7 @@ use std::ffi::{c_char, c_void}; pub enum ArvCamera {} +pub enum ArvDevice {} pub enum ArvStream {} pub enum ArvBuffer {} @@ -90,71 +91,91 @@ unsafe extern "C" { 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_set_string( + 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; + pub fn arv_camera_set_pixel_format(cam: *mut ArvCamera, format: u32, 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; + + // ----- 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_camera_get_string( - cam: *mut ArvCamera, + 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_camera_set_integer( - cam: *mut ArvCamera, + pub fn arv_device_set_integer_feature_value( + device: *mut ArvDevice, feature: *const c_char, value: i64, err: *mut *mut GError, ); - pub fn arv_camera_get_integer( - cam: *mut ArvCamera, + pub fn arv_device_get_integer_feature_value( + device: *mut ArvDevice, feature: *const c_char, err: *mut *mut GError, ) -> i64; - pub fn arv_camera_set_float( - cam: *mut ArvCamera, + pub fn arv_device_set_float_feature_value( + device: *mut ArvDevice, feature: *const c_char, value: f64, err: *mut *mut GError, ); - pub fn arv_camera_get_float( - cam: *mut ArvCamera, + pub fn arv_device_get_float_feature_value( + device: *mut ArvDevice, feature: *const c_char, err: *mut *mut GError, ) -> f64; - pub fn arv_camera_set_boolean( - cam: *mut ArvCamera, + pub fn arv_device_set_boolean_feature_value( + device: *mut ArvDevice, feature: *const c_char, value: i32, err: *mut *mut GError, ); - pub fn arv_camera_get_boolean( - cam: *mut ArvCamera, + pub fn arv_device_get_boolean_feature_value( + device: *mut ArvDevice, feature: *const c_char, err: *mut *mut GError, ) -> i32; - pub fn arv_camera_execute_command( - cam: *mut ArvCamera, - feature: *const c_char, + 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( @@ -164,6 +185,7 @@ unsafe extern "C" { ); pub fn arv_camera_gv_get_packet_size(cam: *mut ArvCamera, err: *mut *mut GError) -> i32; + // ----- Stream & Acquisition ----- pub fn arv_camera_create_stream( cam: *mut ArvCamera, callback: *const c_void, diff --git a/headless-rust/src/camera/mod.rs b/headless-rust/src/camera/mod.rs index 717c1fd..506ab12 100644 --- a/headless-rust/src/camera/mod.rs +++ b/headless-rust/src/camera/mod.rs @@ -162,6 +162,7 @@ impl CameraService { 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); println!("[camera] GigE Vision auto packet size set to: {} bytes", packet_size); @@ -172,40 +173,72 @@ impl CameraService { println!("[camera] GigE Vision GevSCPD packet delay set to: 2000"); } - // Configure Trigger mode & strobe - Self::set_feature_str_internal(cam, "AcquisitionMode", "Continuous"); - Self::set_feature_str_internal(cam, "TriggerSelector", "FrameStart"); - Self::set_feature_str_internal(cam, "TriggerMode", "On"); - Self::set_feature_str_internal(cam, "TriggerSource", "Software"); - - Self::set_feature_str_internal(cam, "LineSelector", "Line1"); - Self::set_feature_str_internal(cam, "LineMode", "Strobe"); - Self::set_feature_str_internal(cam, "LineSource", "ExposureActive"); - Self::set_feature_bool_internal(cam, "StrobeEnable", true); - Self::set_feature_int_internal( - cam, - "StrobeLineDuration", - settings.strobe_line_duration as i64, - ); + // Set PixelFormat + if Self::is_feature_available_internal(cam, "PixelFormat") { + Self::set_pixel_format_internal(cam, &settings.pixel_format); + } + + // ── Trigger Mode & Acquisition ──────────────────────────────────── + // Crucial: Set TriggerMode = On and TriggerSource = Software so camera + // does not free-run upon starting acquisition (which would strobe the flash forever). + if Self::is_feature_available_internal(cam, "AcquisitionMode") { + Self::set_feature_str_internal(cam, "AcquisitionMode", "Continuous"); + } + if Self::is_feature_available_internal(cam, "TriggerSelector") { + Self::set_feature_str_internal(cam, "TriggerSelector", "FrameStart"); + } + if Self::is_feature_available_internal(cam, "TriggerMode") { + Self::set_feature_str_internal(cam, "TriggerMode", "On"); + Self::set_feature_str_internal(cam, "TriggerSource", "Software"); + } + + // ── Line & Strobe Flash Configuration ────────────────────────────── + // Configure Line1 as Strobe output driven by ExposureActive + if Self::is_feature_available_internal(cam, "LineSelector") { + Self::set_feature_str_internal(cam, "LineSelector", "Line1"); + Self::set_feature_str_internal(cam, "LineMode", "Strobe"); + Self::set_feature_str_internal(cam, "LineSource", "ExposureActive"); + Self::set_feature_int_internal(cam, "LineInverter", 0); + Self::set_feature_int_internal(cam, "LineDebouncerTime", 50); + + 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", + settings.strobe_line_duration as i64, + ); + Self::set_feature_int_internal(cam, "StrobeLineDelay", 0); + Self::set_feature_int_internal(cam, "StrobeLinePreDelay", 0); + } + } - // Exposure & Gain + // ── Exposure & Gain ─────────────────────────────────────────────── Self::set_feature_str_internal(cam, "ExposureAuto", &settings.exposure_auto); if settings.exposure_auto == "Off" { - Self::set_feature_float_internal(cam, "ExposureTime", settings.camera_exposure); + 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_feature_float_internal(cam, "Gain", settings.camera_gain); + Self::set_gain_internal(cam, settings.camera_gain); } if settings.frame_rate > 0.0 { Self::set_feature_bool_internal(cam, "AcquisitionFrameRateEnable", true); - Self::set_feature_float_internal( - cam, - "AcquisitionFrameRate", - settings.frame_rate, - ); + Self::set_frame_rate_internal(cam, settings.frame_rate); + } + + 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_feature_float_internal(cam, "BlackLevel", settings.black_level); } // Create Stream with 24 pre-allocated buffers for robust throughput without underruns @@ -216,13 +249,19 @@ impl CameraService { return; } - let payload_size = Self::get_feature_int_internal(cam, "PayloadSize").max(1024 * 1024); + 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 as usize); + 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); @@ -313,13 +352,8 @@ impl CameraService { } // Software trigger - let mut err = null_mut(); - let trigger_cmd = CString::new("TriggerSoftware").unwrap(); - arv_camera_execute_command(cam, trigger_cmd.as_ptr(), &mut err); - if !err.is_null() { - let msg = CStr::from_ptr((*err).message).to_string_lossy(); - println!("[camera] TriggerSoftware failed: {}", msg); - g_error_free(err); + if Self::is_feature_available_internal(cam, "TriggerSoftware") { + Self::execute_command_internal(cam, "TriggerSoftware"); } // Wait up to 1.5 seconds for completed frame @@ -396,21 +430,27 @@ impl CameraService { } } - // Disable strobe during setup preview + // Disable strobe during setup preview so preview stream does not trigger flash Self::set_feature_bool_internal(cam, "StrobeEnable", false); Self::set_feature_int_internal(cam, "StrobeEnable", 0); - Self::set_feature_str_internal(cam, "LineSelector", "Line1"); - Self::set_feature_str_internal(cam, "LineSource", "Off"); - Self::set_feature_str_internal(cam, "LineSelector", "Line2"); - Self::set_feature_str_internal(cam, "LineSource", "Off"); + if Self::is_feature_available_internal(cam, "LineSelector") { + for line in ["Line1", "Line2"] { + Self::set_feature_str_internal(cam, "LineSelector", line); + Self::set_feature_str_internal(cam, "LineSource", "Off"); + } + } // Set free-running stream features (capped to 10 FPS to prevent GigE flood) - Self::set_feature_str_internal(cam, "TriggerSelector", "FrameStart"); - Self::set_feature_str_internal(cam, "TriggerMode", "Off"); + if Self::is_feature_available_internal(cam, "TriggerSelector") { + Self::set_feature_str_internal(cam, "TriggerSelector", "FrameStart"); + } + if Self::is_feature_available_internal(cam, "TriggerMode") { + Self::set_feature_str_internal(cam, "TriggerMode", "Off"); + } Self::set_feature_str_internal(cam, "ExposureAuto", "Continuous"); Self::set_feature_str_internal(cam, "GainAuto", "Continuous"); Self::set_feature_bool_internal(cam, "AcquisitionFrameRateEnable", true); - Self::set_feature_float_internal(cam, "AcquisitionFrameRate", 10.0); + Self::set_frame_rate_internal(cam, 10.0); unsafe { let mut err = null_mut(); @@ -529,35 +569,49 @@ impl CameraService { } // Restore trigger mode & strobe - Self::set_feature_str_internal(cam, "TriggerSelector", "FrameStart"); - Self::set_feature_str_internal(cam, "TriggerMode", "On"); - Self::set_feature_str_internal(cam, "TriggerSource", "Software"); + if Self::is_feature_available_internal(cam, "TriggerSelector") { + Self::set_feature_str_internal(cam, "TriggerSelector", "FrameStart"); + } + if Self::is_feature_available_internal(cam, "TriggerMode") { + Self::set_feature_str_internal(cam, "TriggerMode", "On"); + Self::set_feature_str_internal(cam, "TriggerSource", "Software"); + } - Self::set_feature_str_internal(cam, "LineSelector", "Line1"); - Self::set_feature_str_internal(cam, "LineMode", "Strobe"); - Self::set_feature_str_internal(cam, "LineSource", "ExposureActive"); - Self::set_feature_bool_internal(cam, "StrobeEnable", true); - Self::set_feature_int_internal( - cam, - "StrobeLineDuration", - settings.strobe_line_duration as i64, - ); + if Self::is_feature_available_internal(cam, "LineSelector") { + Self::set_feature_str_internal(cam, "LineSelector", "Line1"); + Self::set_feature_str_internal(cam, "LineMode", "Strobe"); + Self::set_feature_str_internal(cam, "LineSource", "ExposureActive"); + Self::set_feature_int_internal(cam, "LineInverter", 0); + Self::set_feature_int_internal(cam, "LineDebouncerTime", 50); + + 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", + settings.strobe_line_duration as i64, + ); + Self::set_feature_int_internal(cam, "StrobeLineDelay", 0); + Self::set_feature_int_internal(cam, "StrobeLinePreDelay", 0); + } + } // Restore exposure & gain Self::set_feature_str_internal(cam, "ExposureAuto", &settings.exposure_auto); if settings.exposure_auto == "Off" { - Self::set_feature_float_internal(cam, "ExposureTime", settings.camera_exposure); + 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_feature_float_internal(cam, "Gain", settings.camera_gain); + Self::set_gain_internal(cam, settings.camera_gain); } if settings.frame_rate > 0.0 { - Self::set_feature_float_internal( - cam, - "AcquisitionFrameRate", - settings.frame_rate, - ); + Self::set_feature_bool_internal(cam, "AcquisitionFrameRateEnable", true); + Self::set_frame_rate_internal(cam, settings.frame_rate); + } else { + Self::set_feature_bool_internal(cam, "AcquisitionFrameRateEnable", false); } unsafe { @@ -573,7 +627,23 @@ impl CameraService { let _ = self.status_sender.send(self.get_status()); } - pub fn apply_mfs_config(&self, mfs_content: &str) -> MfsConfigResult { + 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(); @@ -592,30 +662,62 @@ impl CameraService { 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; } - if let Some((k, v)) = line.split_once('=') { - let key = k.trim(); - let val = v.trim(); - - let ok = if let Ok(int_val) = val.parse::() { - Self::set_feature_int_internal(cam, key, int_val) - } else if let Ok(float_val) = val.parse::() { - Self::set_feature_float_internal(cam, key, float_val) + 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 { - Self::set_feature_str_internal(cam, key, val) - }; + None + } + }; - if ok { - applied.push(line.to_string()); + 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(); + for (feature, value) in pending { + if Self::set_feature_str_internal(cam, &feature, &value) { + applied.push(format!("{}\t{}", feature, value)); } else { - failed.push(line.to_string()); + failed_this_pass.push((feature, value)); } } + + if failed_this_pass.len() == pending.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 } @@ -625,7 +727,7 @@ impl CameraService { if !self.mock_mode { let cam = *self.camera_ptr.lock().unwrap(); if !cam.is_null() { - Self::set_feature_float_internal(cam, "ExposureTime", val); + Self::set_exposure_internal(cam, val); } } } @@ -634,7 +736,7 @@ impl CameraService { if !self.mock_mode { let cam = *self.camera_ptr.lock().unwrap(); if !cam.is_null() { - Self::set_feature_float_internal(cam, "Gain", val); + Self::set_gain_internal(cam, val); } } } @@ -643,6 +745,7 @@ impl CameraService { 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); } } @@ -652,15 +755,7 @@ impl CameraService { if !self.mock_mode { let cam = *self.camera_ptr.lock().unwrap(); if !cam.is_null() { - if format == "Color" { - for fmt in ["BayerBG8", "BayerRG8", "RGB8Packed", "RGB8"] { - if Self::set_feature_str_internal(cam, "PixelFormat", fmt) { - break; - } - } - } else { - Self::set_feature_str_internal(cam, "PixelFormat", "Mono8"); - } + Self::set_pixel_format_internal(cam, format); } } } @@ -1003,8 +1098,58 @@ impl CameraService { } + 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(); + println!("[camera] Warning: execute_command({}) failed: {}", command, msg); + g_error_free(err); + false + } else { + println!("[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, @@ -1014,85 +1159,239 @@ impl CameraService { Err(_) => return false, }; let mut err = null_mut(); - arv_camera_set_string(cam, f_cstr.as_ptr(), v_cstr.as_ptr(), &mut err); + 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(); + println!("[camera] Warning: set_feature_str({}, {}) failed: {}", feature, value, msg); g_error_free(err); false } else { + println!("[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_camera_set_integer(cam, f_cstr.as_ptr(), value, &mut err); + 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(); + println!("[camera] Warning: set_feature_int({}, {}) failed: {}", feature, value, msg); g_error_free(err); false } else { + println!("[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_camera_set_float(cam, f_cstr.as_ptr(), value, &mut err); + 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(); + println!("[camera] Warning: set_feature_float({}, {}) failed: {}", feature, value, msg); g_error_free(err); false } else { + println!("[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_camera_set_boolean( - cam, + 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(); + println!("[camera] Warning: set_feature_bool({}, {}) failed: {}", feature, value, msg); g_error_free(err); false } else { + println!("[camera] set_feature_bool({}, {}) succeeded", feature, value); true } } } - fn get_feature_int_internal(cam: *mut ArvCamera, feature: &str) -> i64 { + fn set_exposure_internal(cam: *mut ArvCamera, us: f64) -> bool { + if cam.is_null() { + return false; + } unsafe { - let f_cstr = match CString::new(feature) { - Ok(s) => s, - Err(_) => return 0, - }; let mut err = null_mut(); - let res = arv_camera_get_integer(cam, f_cstr.as_ptr(), &mut err); + arv_camera_set_exposure_time(cam, us, &mut err); if !err.is_null() { + let msg = CStr::from_ptr((*err).message).to_string_lossy(); + println!("[camera] Warning: arv_camera_set_exposure_time({}) failed: {}", us, msg); g_error_free(err); - 0 + false } else { - res + println!("[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(); + println!("[camera] Warning: arv_camera_set_gain({}) failed: {}", gain, msg); + g_error_free(err); + false + } else { + println!("[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(); + println!("[camera] Warning: arv_camera_set_frame_rate({}) failed: {}", fps, msg); + g_error_free(err); + false + } else { + println!("[camera] Set frame rate to {} FPS", fps); + true + } + } + } + + fn set_pixel_format_internal(cam: *mut ArvCamera, format: &str) -> bool { + if cam.is_null() { + return false; + } + if format == "Color" { + let fallbacks = [ + "BayerBG8", + "BayerRG8", + "BayerGR8", + "BayerGB8", + "RGB8Packed", + "RGB8", + ]; + for fmt in fallbacks { + if Self::set_feature_str_internal(cam, "PixelFormat", fmt) { + println!("[camera] Set PixelFormat to {}", fmt); + return true; + } + } + println!("[camera] Failed to set PixelFormat for Color"); + false + } else { + if Self::set_feature_str_internal(cam, "PixelFormat", "Mono8") { + println!("[camera] Set PixelFormat to Mono8"); + true + } else { + false } } } diff --git a/headless-rust/src/web/rpc.rs b/headless-rust/src/web/rpc.rs index c5c2515..2c1fc02 100644 --- a/headless-rust/src/web/rpc.rs +++ b/headless-rust/src/web/rpc.rs @@ -415,7 +415,8 @@ async fn dispatch_method(ctx: &RpcContext, method: &str, params: Value) -> Resul "applyMfsConfig" => { let mfs = params["mfsContent"].as_str().ok_or("Missing mfsContent")?; - let res = ctx.camera.apply_mfs_config(mfs); + let save_default = params["saveAsDefault"].as_bool().unwrap_or(false); + let res = ctx.camera.apply_mfs_config(mfs, save_default); Ok(serde_json::to_value(res).unwrap()) } From 7d49ac43ff8e416459f2b0a107e6ab0fa08b2ed3 Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Sat, 15 Aug 2026 01:57:26 +0200 Subject: [PATCH 22/65] fix: correct logic for handling failed feature application in GenICam setup --- headless-rust/src/camera/mod.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/headless-rust/src/camera/mod.rs b/headless-rust/src/camera/mod.rs index 506ab12..e1fa4e7 100644 --- a/headless-rust/src/camera/mod.rs +++ b/headless-rust/src/camera/mod.rs @@ -693,6 +693,7 @@ impl CameraService { // 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_feature_str_internal(cam, &feature, &value) { applied.push(format!("{}\t{}", feature, value)); @@ -701,7 +702,7 @@ impl CameraService { } } - if failed_this_pass.len() == pending.len() { + if failed_this_pass.len() == prev_len { pending = failed_this_pass; break; } From abd925e1d1aefa8cfb35a65a4e5045743e285eed Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Sat, 15 Aug 2026 02:22:01 +0200 Subject: [PATCH 23/65] feat: enhance camera control with trigger management and pixel format settings --- headless-rust/src/camera/ffi.rs | 20 ++ headless-rust/src/camera/mod.rs | 324 ++++++++++++++++++++++++++------ 2 files changed, 288 insertions(+), 56 deletions(-) diff --git a/headless-rust/src/camera/ffi.rs b/headless-rust/src/camera/ffi.rs index 4bd0cd4..73e1e9a 100644 --- a/headless-rust/src/camera/ffi.rs +++ b/headless-rust/src/camera/ffi.rs @@ -116,10 +116,25 @@ unsafe extern "C" { 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; + pub fn arv_camera_set_frame_rate_enable(cam: *mut ArvCamera, enable: i32, err: *mut *mut GError); 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, @@ -184,6 +199,11 @@ unsafe extern "C" { 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( diff --git a/headless-rust/src/camera/mod.rs b/headless-rust/src/camera/mod.rs index e1fa4e7..695ae0c 100644 --- a/headless-rust/src/camera/mod.rs +++ b/headless-rust/src/camera/mod.rs @@ -165,18 +165,25 @@ impl CameraService { // 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); - println!("[camera] GigE Vision auto packet size set to: {} bytes", packet_size); + if !err.is_null() { + g_error_free(err); + } else { + println!("[camera] GigE Vision auto packet size set to: {} bytes", packet_size); + } // Set GevSCPD (Stream Channel Packet Delay) to 2000 ticks // This spaces out UDP packets to prevent NIC packet storms and SSH stalls - Self::set_feature_int_internal(cam, "GevSCPD", 2000); + let mut delay_err = null_mut(); + arv_camera_gv_set_packet_delay(cam, 2000, &mut delay_err); + if !delay_err.is_null() { + g_error_free(delay_err); + Self::set_feature_int_internal(cam, "GevSCPD", 2000); + } println!("[camera] GigE Vision GevSCPD packet delay set to: 2000"); } // Set PixelFormat - if Self::is_feature_available_internal(cam, "PixelFormat") { - Self::set_pixel_format_internal(cam, &settings.pixel_format); - } + Self::set_pixel_format_internal(cam, &settings.pixel_format); // ── Trigger Mode & Acquisition ──────────────────────────────────── // Crucial: Set TriggerMode = On and TriggerSource = Software so camera @@ -184,21 +191,21 @@ impl CameraService { if Self::is_feature_available_internal(cam, "AcquisitionMode") { Self::set_feature_str_internal(cam, "AcquisitionMode", "Continuous"); } - if Self::is_feature_available_internal(cam, "TriggerSelector") { - Self::set_feature_str_internal(cam, "TriggerSelector", "FrameStart"); - } - if Self::is_feature_available_internal(cam, "TriggerMode") { - Self::set_feature_str_internal(cam, "TriggerMode", "On"); - Self::set_feature_str_internal(cam, "TriggerSource", "Software"); - } + Self::set_trigger_mode_internal(cam, "Software"); // ── Line & Strobe Flash Configuration ────────────────────────────── - // Configure Line1 as Strobe output driven by ExposureActive + // Configure Line1 as Strobe output if Self::is_feature_available_internal(cam, "LineSelector") { Self::set_feature_str_internal(cam, "LineSelector", "Line1"); Self::set_feature_str_internal(cam, "LineMode", "Strobe"); - Self::set_feature_str_internal(cam, "LineSource", "ExposureActive"); - Self::set_feature_int_internal(cam, "LineInverter", 0); + if Self::is_enumeration_entry_available_internal(cam, "LineSource", "FrameStartActive") { + Self::set_feature_str_internal(cam, "LineSource", "FrameStartActive"); + } 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", "Strobe") { + Self::set_feature_str_internal(cam, "LineSource", "Strobe"); + } + Self::set_line_inverter_internal(cam, false); Self::set_feature_int_internal(cam, "LineDebouncerTime", 50); if Self::is_feature_available_internal(cam, "StrobeEnable") { @@ -227,7 +234,7 @@ impl CameraService { } if settings.frame_rate > 0.0 { - Self::set_feature_bool_internal(cam, "AcquisitionFrameRateEnable", true); + Self::set_frame_rate_enable_internal(cam, true); Self::set_frame_rate_internal(cam, settings.frame_rate); } @@ -238,7 +245,7 @@ impl CameraService { Self::set_feature_int_internal(cam, "Height", settings.camera_height); } if settings.black_level >= 0.0 { - Self::set_feature_float_internal(cam, "BlackLevel", settings.black_level); + Self::set_black_level_internal(cam, settings.black_level); } // Create Stream with 24 pre-allocated buffers for robust throughput without underruns @@ -352,12 +359,10 @@ impl CameraService { } // Software trigger - if Self::is_feature_available_internal(cam, "TriggerSoftware") { - Self::execute_command_internal(cam, "TriggerSoftware"); - } + Self::fire_software_trigger_internal(cam); - // Wait up to 1.5 seconds for completed frame - let buffer = arv_stream_timeout_pop_buffer(stream, 1_500_000); + // Wait up to 2.0 seconds for completed frame + let buffer = arv_stream_timeout_pop_buffer(stream, 2_000_000); if buffer.is_null() { println!("[camera] Capture frame timed out"); return None; @@ -441,15 +446,10 @@ impl CameraService { } // Set free-running stream features (capped to 10 FPS to prevent GigE flood) - if Self::is_feature_available_internal(cam, "TriggerSelector") { - Self::set_feature_str_internal(cam, "TriggerSelector", "FrameStart"); - } - if Self::is_feature_available_internal(cam, "TriggerMode") { - Self::set_feature_str_internal(cam, "TriggerMode", "Off"); - } + Self::clear_triggers_internal(cam); Self::set_feature_str_internal(cam, "ExposureAuto", "Continuous"); Self::set_feature_str_internal(cam, "GainAuto", "Continuous"); - Self::set_feature_bool_internal(cam, "AcquisitionFrameRateEnable", true); + Self::set_frame_rate_enable_internal(cam, true); Self::set_frame_rate_internal(cam, 10.0); unsafe { @@ -569,19 +569,19 @@ impl CameraService { } // Restore trigger mode & strobe - if Self::is_feature_available_internal(cam, "TriggerSelector") { - Self::set_feature_str_internal(cam, "TriggerSelector", "FrameStart"); - } - if Self::is_feature_available_internal(cam, "TriggerMode") { - Self::set_feature_str_internal(cam, "TriggerMode", "On"); - Self::set_feature_str_internal(cam, "TriggerSource", "Software"); - } + Self::set_trigger_mode_internal(cam, "Software"); if Self::is_feature_available_internal(cam, "LineSelector") { Self::set_feature_str_internal(cam, "LineSelector", "Line1"); Self::set_feature_str_internal(cam, "LineMode", "Strobe"); - Self::set_feature_str_internal(cam, "LineSource", "ExposureActive"); - Self::set_feature_int_internal(cam, "LineInverter", 0); + if Self::is_enumeration_entry_available_internal(cam, "LineSource", "FrameStartActive") { + Self::set_feature_str_internal(cam, "LineSource", "FrameStartActive"); + } 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", "Strobe") { + Self::set_feature_str_internal(cam, "LineSource", "Strobe"); + } + Self::set_line_inverter_internal(cam, false); Self::set_feature_int_internal(cam, "LineDebouncerTime", 50); if Self::is_feature_available_internal(cam, "StrobeEnable") { @@ -608,10 +608,10 @@ impl CameraService { Self::set_gain_internal(cam, settings.camera_gain); } if settings.frame_rate > 0.0 { - Self::set_feature_bool_internal(cam, "AcquisitionFrameRateEnable", true); + Self::set_frame_rate_enable_internal(cam, true); Self::set_frame_rate_internal(cam, settings.frame_rate); } else { - Self::set_feature_bool_internal(cam, "AcquisitionFrameRateEnable", false); + Self::set_frame_rate_enable_internal(cam, false); } unsafe { @@ -695,7 +695,7 @@ impl CameraService { let mut failed_this_pass = Vec::new(); let prev_len = pending.len(); for (feature, value) in pending { - if Self::set_feature_str_internal(cam, &feature, &value) { + if Self::set_any_feature_internal(cam, &feature, &value) { applied.push(format!("{}\t{}", feature, value)); } else { failed_this_pass.push((feature, value)); @@ -1173,6 +1173,7 @@ impl CameraService { } } + #[allow(dead_code)] fn get_feature_str_internal(cam: *mut ArvCamera, feature: &str) -> Option { if cam.is_null() { return None; @@ -1366,34 +1367,245 @@ impl CameraService { } } + 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 + } + } + } + + fn set_trigger_mode_internal(cam: *mut ArvCamera, trigger_source: &str) -> bool { + if cam.is_null() { + return false; + } + unsafe { + let src_cstr = match CString::new(trigger_source) { + Ok(s) => s, + Err(_) => return false, + }; + let mut err = null_mut(); + arv_camera_set_trigger(cam, src_cstr.as_ptr(), &mut err); + if err.is_null() { + println!("[camera] Set trigger mode: On, TriggerSource: {}", trigger_source); + true + } else { + let msg = CStr::from_ptr((*err).message).to_string_lossy(); + println!("[camera] arv_camera_set_trigger({}) returned: {}. Trying fallback sequence...", trigger_source, msg); + g_error_free(err); + + // Fallback sequence: Try FrameBurstStart (Hikrobot), then FrameStart, then AcquisitionStart + let selectors = ["FrameBurstStart", "FrameStart", "AcquisitionStart"]; + let mut success = false; + for sel in selectors { + if Self::set_feature_str_internal(cam, "TriggerSelector", sel) { + Self::set_feature_str_internal(cam, "TriggerMode", "On"); + Self::set_feature_str_internal(cam, "TriggerSource", trigger_source); + println!("[camera] Configured TriggerSelector {} to On / {}", sel, trigger_source); + success = true; + break; + } + } + success + } + } + } + + fn clear_triggers_internal(cam: *mut ArvCamera) -> bool { + if cam.is_null() { + return false; + } + unsafe { + let mut err = null_mut(); + arv_camera_clear_triggers(cam, &mut err); + if err.is_null() { + println!("[camera] Cleared triggers (continuous streaming mode enabled)"); + true + } else { + let msg = CStr::from_ptr((*err).message).to_string_lossy(); + println!("[camera] arv_camera_clear_triggers returned: {}. Disabling TriggerMode on all selectors...", msg); + g_error_free(err); + + for sel in ["FrameBurstStart", "FrameStart", "AcquisitionStart"] { + if Self::set_feature_str_internal(cam, "TriggerSelector", sel) { + Self::set_feature_str_internal(cam, "TriggerMode", "Off"); + } + } + true + } + } + } + + 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(); + println!("[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 + } + + fn set_frame_rate_enable_internal(cam: *mut ArvCamera, enable: bool) -> bool { + if cam.is_null() { + return false; + } + unsafe { + let mut err = null_mut(); + arv_camera_set_frame_rate_enable(cam, if enable { 1 } else { 0 }, &mut err); + if err.is_null() { + return true; + } + g_error_free(err); + } + Self::set_feature_bool_internal(cam, "AcquisitionFrameRateEnable", enable) + } + fn set_pixel_format_internal(cam: *mut ArvCamera, format: &str) -> bool { if cam.is_null() { return false; } - if format == "Color" { - let fallbacks = [ - "BayerBG8", + let candidates: Vec<&str> = if format.eq_ignore_ascii_case("color") { + vec![ "BayerRG8", + "BayerBG8", "BayerGR8", "BayerGB8", "RGB8Packed", + "BGR8Packed", "RGB8", - ]; - for fmt in fallbacks { - if Self::set_feature_str_internal(cam, "PixelFormat", fmt) { - println!("[camera] Set PixelFormat to {}", fmt); + "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() { + println!("[camera] PixelFormat set to {}", fmt); return true; + } else { + g_error_free(err); } } - println!("[camera] Failed to set PixelFormat for Color"); - false - } else { - if Self::set_feature_str_internal(cam, "PixelFormat", "Mono8") { - println!("[camera] Set PixelFormat to Mono8"); - true - } else { - false + if Self::set_feature_str_internal(cam, "PixelFormat", fmt) { + println!("[camera] PixelFormat set to {}", fmt); + return true; + } + } + println!("[camera] Warning: 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 } } From 9b6805e45f64646bb7cfc5a8a2ff9f9b390a45c7 Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Sat, 15 Aug 2026 02:39:05 +0200 Subject: [PATCH 24/65] fix: order camera configuration for triggered capture mode and strobe settings --- headless-rust/src/camera/mod.rs | 383 ++++++++++++++++++-------------- 1 file changed, 218 insertions(+), 165 deletions(-) diff --git a/headless-rust/src/camera/mod.rs b/headless-rust/src/camera/mod.rs index 695ae0c..f96f5c4 100644 --- a/headless-rust/src/camera/mod.rs +++ b/headless-rust/src/camera/mod.rs @@ -185,44 +185,18 @@ impl CameraService { // Set PixelFormat Self::set_pixel_format_internal(cam, &settings.pixel_format); - // ── Trigger Mode & Acquisition ──────────────────────────────────── - // Crucial: Set TriggerMode = On and TriggerSource = Software so camera - // does not free-run upon starting acquisition (which would strobe the flash forever). - if Self::is_feature_available_internal(cam, "AcquisitionMode") { - Self::set_feature_str_internal(cam, "AcquisitionMode", "Continuous"); + // ── ROI (Width/Height must be set before payload calculation) ───── + if settings.camera_width > 0 { + Self::set_feature_int_internal(cam, "Width", settings.camera_width); } - Self::set_trigger_mode_internal(cam, "Software"); - - // ── Line & Strobe Flash Configuration ────────────────────────────── - // Configure Line1 as Strobe output - if Self::is_feature_available_internal(cam, "LineSelector") { - Self::set_feature_str_internal(cam, "LineSelector", "Line1"); - Self::set_feature_str_internal(cam, "LineMode", "Strobe"); - if Self::is_enumeration_entry_available_internal(cam, "LineSource", "FrameStartActive") { - Self::set_feature_str_internal(cam, "LineSource", "FrameStartActive"); - } 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", "Strobe") { - Self::set_feature_str_internal(cam, "LineSource", "Strobe"); - } - Self::set_line_inverter_internal(cam, false); - Self::set_feature_int_internal(cam, "LineDebouncerTime", 50); - - 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", - settings.strobe_line_duration as i64, - ); - Self::set_feature_int_internal(cam, "StrobeLineDelay", 0); - Self::set_feature_int_internal(cam, "StrobeLinePreDelay", 0); - } + 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 ─────────────────────────────────────────────── + // ── 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); @@ -233,20 +207,25 @@ impl CameraService { Self::set_gain_internal(cam, settings.camera_gain); } - if settings.frame_rate > 0.0 { - Self::set_frame_rate_enable_internal(cam, true); - Self::set_frame_rate_internal(cam, settings.frame_rate); - } + // ── Line & Strobe Flash Configuration ────────────────────────────── + // Configure Line1 as Strobe output + Self::configure_strobe_internal(cam, settings); - 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); + // ── Trigger Mode & Acquisition ──────────────────────────────────── + // Set AcquisitionMode=Continuous, then configure FrameBurstStart + // trigger for software-triggered capture. This prevents the camera + // from free-running and strobing the flash continuously. + if Self::is_feature_available_internal(cam, "AcquisitionMode") { + Self::set_feature_str_internal(cam, "AcquisitionMode", "Continuous"); } + Self::set_trigger_mode_internal(cam, "Software"); + + // ── Frame Rate ──────────────────────────────────────────────────── + // In triggered mode, frame rate limiting is unnecessary and should + // be disabled. The trigger timing controls capture rate. + // (Matches reference MFS: AcquisitionFrameRateEnable = 0) + Self::set_frame_rate_enable_internal(cam, false); + println!("[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); @@ -413,6 +392,7 @@ impl CameraService { 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); @@ -421,37 +401,29 @@ impl CameraService { } } - // Flush any pending buffers - let stream = *this.stream_ptr.lock().unwrap(); - if !stream.is_null() { - unsafe { - loop { - let stale = arv_stream_try_pop_buffer(stream); - if stale.is_null() { - break; - } - arv_stream_push_buffer(stream, stale); - } - } - } + // 2. Flush any pending buffers + Self::flush_stream_buffers(&this); - // Disable strobe during setup preview so preview stream does not trigger flash - Self::set_feature_bool_internal(cam, "StrobeEnable", false); - Self::set_feature_int_internal(cam, "StrobeEnable", 0); - if Self::is_feature_available_internal(cam, "LineSelector") { - for line in ["Line1", "Line2"] { - Self::set_feature_str_internal(cam, "LineSelector", line); - Self::set_feature_str_internal(cam, "LineSource", "Off"); - } - } + // 3. Disable strobe during setup preview + Self::disable_strobe_internal(cam); - // Set free-running stream features (capped to 10 FPS to prevent GigE flood) + // 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); @@ -546,6 +518,7 @@ impl CameraService { 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); @@ -554,51 +527,16 @@ impl CameraService { } } - // Flush stream buffers - let stream = *self.stream_ptr.lock().unwrap(); - if !stream.is_null() { - unsafe { - loop { - let stale = arv_stream_try_pop_buffer(stream); - if stale.is_null() { - break; - } - arv_stream_push_buffer(stream, stale); - } - } - } + // 2. Flush stream buffers + Self::flush_stream_buffers(self); - // Restore trigger mode & strobe + // 3. Restore trigger mode (FrameBurstStart/On/Software) Self::set_trigger_mode_internal(cam, "Software"); - if Self::is_feature_available_internal(cam, "LineSelector") { - Self::set_feature_str_internal(cam, "LineSelector", "Line1"); - Self::set_feature_str_internal(cam, "LineMode", "Strobe"); - if Self::is_enumeration_entry_available_internal(cam, "LineSource", "FrameStartActive") { - Self::set_feature_str_internal(cam, "LineSource", "FrameStartActive"); - } 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", "Strobe") { - Self::set_feature_str_internal(cam, "LineSource", "Strobe"); - } - Self::set_line_inverter_internal(cam, false); - Self::set_feature_int_internal(cam, "LineDebouncerTime", 50); - - 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", - settings.strobe_line_duration as i64, - ); - Self::set_feature_int_internal(cam, "StrobeLineDelay", 0); - Self::set_feature_int_internal(cam, "StrobeLinePreDelay", 0); - } - } + // 4. Restore strobe configuration + Self::configure_strobe_internal(cam, settings); - // Restore exposure & gain + // 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); @@ -607,13 +545,12 @@ impl CameraService { if settings.gain_auto == "Off" { Self::set_gain_internal(cam, settings.camera_gain); } - if settings.frame_rate > 0.0 { - Self::set_frame_rate_enable_internal(cam, true); - Self::set_frame_rate_internal(cam, settings.frame_rate); - } else { - Self::set_frame_rate_enable_internal(cam, false); - } + // 6. Disable frame rate limiting in triggered mode + // (trigger timing controls capture rate, not AcquisitionFrameRate) + 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); @@ -1099,6 +1036,108 @@ impl CameraService { } + // ── Shared Helper Functions ──────────────────────────────────────────────── + + /// Configure Line1 as strobe output with full settings from AppSettings. + /// Used during connect() and stop_setup_stream() to restore strobe. + 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"); + if Self::is_enumeration_entry_available_internal(cam, "LineSource", "FrameStartActive") { + Self::set_feature_str_internal(cam, "LineSource", "FrameStartActive"); + } 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", "Strobe") { + Self::set_feature_str_internal(cam, "LineSource", "Strobe"); + } + Self::set_line_inverter_internal(cam, false); + Self::set_feature_int_internal(cam, "LineDebouncerTime", 50); + + 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", + settings.strobe_line_duration as i64, + ); + Self::set_feature_int_internal(cam, "StrobeLineDelay", 0); + Self::set_feature_int_internal(cam, "StrobeLinePreDelay", 0); + } + println!("[camera] Strobe configured on Line1"); + } + + /// Disable strobe output during setup preview to prevent flash from firing. + fn disable_strobe_internal(cam: *mut ArvCamera) { + if cam.is_null() { + return; + } + Self::set_feature_bool_internal(cam, "StrobeEnable", false); + Self::set_feature_int_internal(cam, "StrobeEnable", 0); + if Self::is_feature_available_internal(cam, "LineSelector") { + for line in ["Line1", "Line2"] { + Self::set_feature_str_internal(cam, "LineSelector", line); + Self::set_feature_str_internal(cam, "LineSource", "Off"); + } + } + println!("[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 { + println!("[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); + println!("[camera] WARNING: Could not read back frame rate for verification"); + return; + } + let diff = (actual - target_fps).abs(); + if diff > 1.0 { + println!( + "[camera] WARNING: Frame rate readback {:.1} FPS differs from target {:.1} FPS — camera may not be respecting frame rate limit!", + actual, target_fps + ); + } else { + println!("[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; @@ -1400,65 +1439,70 @@ impl CameraService { } } + /// Configure triggered capture mode using direct GenICam device features. + /// + /// Avoids `arv_camera_set_trigger()` which uses TriggerSelector=AcquisitionStart + /// internally — wrong for Hikrobot cameras that use FrameBurstStart. + /// Uses explicit 3-step sequence: TriggerSelector → TriggerMode → TriggerSource. fn set_trigger_mode_internal(cam: *mut ArvCamera, trigger_source: &str) -> bool { if cam.is_null() { return false; } - unsafe { - let src_cstr = match CString::new(trigger_source) { - Ok(s) => s, - Err(_) => return false, - }; - let mut err = null_mut(); - arv_camera_set_trigger(cam, src_cstr.as_ptr(), &mut err); - if err.is_null() { - println!("[camera] Set trigger mode: On, TriggerSource: {}", trigger_source); - true - } else { - let msg = CStr::from_ptr((*err).message).to_string_lossy(); - println!("[camera] arv_camera_set_trigger({}) returned: {}. Trying fallback sequence...", trigger_source, msg); - g_error_free(err); - // Fallback sequence: Try FrameBurstStart (Hikrobot), then FrameStart, then AcquisitionStart - let selectors = ["FrameBurstStart", "FrameStart", "AcquisitionStart"]; - let mut success = false; - for sel in selectors { - if Self::set_feature_str_internal(cam, "TriggerSelector", sel) { - Self::set_feature_str_internal(cam, "TriggerMode", "On"); - Self::set_feature_str_internal(cam, "TriggerSource", trigger_source); - println!("[camera] Configured TriggerSelector {} to On / {}", sel, trigger_source); - success = true; - break; + // Try FrameBurstStart first (Hikrobot), then FrameStart, then AcquisitionStart + let selectors = ["FrameBurstStart", "FrameStart", "AcquisitionStart"]; + for sel in selectors { + if Self::set_feature_str_internal(cam, "TriggerSelector", sel) { + 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 { + println!( + "[camera] Trigger configured: Selector={}, Mode=On, Source={}", + sel, trigger_source + ); + // Verify TriggerMode actually stuck + if let Some(readback) = Self::get_feature_str_internal(cam, "TriggerMode") { + if readback != "On" { + println!( + "[camera] WARNING: TriggerMode readback is '{}' (expected 'On')", + readback + ); + } } + return true; } - success } } + + println!("[camera] ERROR: Failed to configure trigger mode on any selector"); + 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; } - unsafe { - let mut err = null_mut(); - arv_camera_clear_triggers(cam, &mut err); - if err.is_null() { - println!("[camera] Cleared triggers (continuous streaming mode enabled)"); - true - } else { - let msg = CStr::from_ptr((*err).message).to_string_lossy(); - println!("[camera] arv_camera_clear_triggers returned: {}. Disabling TriggerMode on all selectors...", msg); - g_error_free(err); - for sel in ["FrameBurstStart", "FrameStart", "AcquisitionStart"] { - if Self::set_feature_str_internal(cam, "TriggerSelector", sel) { - Self::set_feature_str_internal(cam, "TriggerMode", "Off"); - } + // 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") { + println!("[camera] Trigger disabled: Selector={}, Mode=Off", sel); + any_success = true; } - true } } + + if any_success { + println!("[camera] Triggers cleared — camera in free-running mode"); + } else { + println!("[camera] WARNING: Could not clear triggers on any selector"); + } + any_success } fn fire_software_trigger_internal(cam: *mut ArvCamera) -> bool { @@ -1508,19 +1552,28 @@ impl CameraService { 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; } - unsafe { - let mut err = null_mut(); - arv_camera_set_frame_rate_enable(cam, if enable { 1 } else { 0 }, &mut err); - if err.is_null() { - return true; - } - g_error_free(err); + 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 }, + ); } - Self::set_feature_bool_internal(cam, "AcquisitionFrameRateEnable", enable) + println!( + "[camera] AcquisitionFrameRateEnable = {}", + if enable { "true" } else { "false" } + ); + ok } fn set_pixel_format_internal(cam: *mut ArvCamera, format: &str) -> bool { From 49520f08c1ee78eec41fcde8b91f45318af00e82 Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Sat, 15 Aug 2026 02:39:11 +0200 Subject: [PATCH 25/65] fix: update arv_camera_set_frame_rate_enable documentation to reflect absence in Aravis C API --- headless-rust/src/camera/ffi.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/headless-rust/src/camera/ffi.rs b/headless-rust/src/camera/ffi.rs index 73e1e9a..9b5fd3f 100644 --- a/headless-rust/src/camera/ffi.rs +++ b/headless-rust/src/camera/ffi.rs @@ -116,7 +116,8 @@ unsafe extern "C" { 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; - pub fn arv_camera_set_frame_rate_enable(cam: *mut ArvCamera, enable: i32, err: *mut *mut GError); + // 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; From 7b300cfca495d0922b1e75ec734af414d11b748c Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Sat, 15 Aug 2026 02:57:50 +0200 Subject: [PATCH 26/65] fix: enhance strobe and frame rate handling in triggered mode --- headless-rust/src/camera/mod.rs | 77 +++++++++++++++++++++------------ 1 file changed, 50 insertions(+), 27 deletions(-) diff --git a/headless-rust/src/camera/mod.rs b/headless-rust/src/camera/mod.rs index f96f5c4..2c0329d 100644 --- a/headless-rust/src/camera/mod.rs +++ b/headless-rust/src/camera/mod.rs @@ -208,24 +208,26 @@ impl CameraService { } // ── Line & Strobe Flash Configuration ────────────────────────────── - // Configure Line1 as Strobe output + // Configure Line1 strobe wiring but keep StrobeEnable=false. + // Strobe is ONLY enabled briefly during capture_frame_jpeg() to + // prevent permanent flash firing if trigger mode doesn't stick. Self::configure_strobe_internal(cam, settings); // ── Trigger Mode & Acquisition ──────────────────────────────────── - // Set AcquisitionMode=Continuous, then configure FrameBurstStart - // trigger for software-triggered capture. This prevents the camera - // from free-running and strobing the flash continuously. 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 ──────────────────────────────────────────────────── - // In triggered mode, frame rate limiting is unnecessary and should - // be disabled. The trigger timing controls capture rate. - // (Matches reference MFS: AcquisitionFrameRateEnable = 0) - Self::set_frame_rate_enable_internal(cam, false); - println!("[camera] Frame rate limiting disabled (triggered mode)"); + // ── Frame Rate (safety net) ───────────────────────────────────── + // Keep frame rate limiting enabled at a low rate even in triggered + // mode. If trigger mode fails for any reason, this prevents the + // camera from flooding the network at 63 FPS. + Self::set_frame_rate_enable_internal(cam, true); + Self::set_frame_rate_internal(cam, 5.0); + println!("[camera] Frame rate safety net: 5 FPS (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); @@ -261,6 +263,15 @@ impl CameraService { *self.stream_ptr.lock().unwrap() = stream; self.is_connected.store(true, Ordering::SeqCst); + // Post-acquisition diagnostic: verify trigger mode survived start_acquisition + if let Some(readback) = Self::get_feature_str_internal(cam, "TriggerMode") { + println!("[camera] POST-ACQUISITION TriggerMode readback: {}", readback); + if readback != "On" { + println!("[camera] WARNING: Camera reset TriggerMode to '{}' after acquisition start! Re-applying...", readback); + Self::set_trigger_mode_internal(cam, "Software"); + } + } + println!("[camera] Connected and acquisition started successfully"); let _ = self.status_sender.send(self.get_status()); } @@ -337,11 +348,18 @@ impl CameraService { arv_stream_push_buffer(stream, stale); } + // Enable strobe for this capture only + Self::set_feature_bool_internal(cam, "StrobeEnable", true); + // 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); + + // Disable strobe immediately after frame received (or timeout) + Self::set_feature_bool_internal(cam, "StrobeEnable", false); + if buffer.is_null() { println!("[camera] Capture frame timed out"); return None; @@ -533,7 +551,8 @@ impl CameraService { // 3. Restore trigger mode (FrameBurstStart/On/Software) Self::set_trigger_mode_internal(cam, "Software"); - // 4. Restore strobe configuration + // 4. Restore strobe wiring but keep StrobeEnable=false + // (strobe only enabled during capture_frame_jpeg) Self::configure_strobe_internal(cam, settings); // 5. Restore exposure & gain @@ -546,9 +565,9 @@ impl CameraService { Self::set_gain_internal(cam, settings.camera_gain); } - // 6. Disable frame rate limiting in triggered mode - // (trigger timing controls capture rate, not AcquisitionFrameRate) - Self::set_frame_rate_enable_internal(cam, false); + // 6. Frame rate safety net (low rate in case trigger fails) + Self::set_frame_rate_enable_internal(cam, true); + Self::set_frame_rate_internal(cam, 5.0); // 7. Restart acquisition in triggered mode unsafe { @@ -558,6 +577,15 @@ impl CameraService { g_error_free(err); } } + + // 8. Post-acquisition diagnostic: verify trigger mode survived + if let Some(readback) = Self::get_feature_str_internal(cam, "TriggerMode") { + println!("[camera] POST-ACQUISITION TriggerMode readback: {}", readback); + if readback != "On" { + println!("[camera] WARNING: Camera reset TriggerMode after start! Re-applying..."); + Self::set_trigger_mode_internal(cam, "Software"); + } + } } } println!("[camera] Setup preview stream stopped, restored triggered capture mode"); @@ -1039,7 +1067,9 @@ impl CameraService { // ── Shared Helper Functions ──────────────────────────────────────────────── /// Configure Line1 as strobe output with full settings from AppSettings. - /// Used during connect() and stop_setup_stream() to restore strobe. + /// Strobe wiring is configured but StrobeEnable is left OFF. + /// Strobe is only enabled briefly during capture_frame_jpeg() to prevent + /// permanent flash firing if trigger mode doesn't work as expected. fn configure_strobe_internal(cam: *mut ArvCamera, settings: &AppSettings) { if cam.is_null() { return; @@ -1061,9 +1091,8 @@ impl CameraService { Self::set_feature_int_internal(cam, "LineDebouncerTime", 50); 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); - } + // Keep strobe DISABLED — only enabled during capture_frame_jpeg() + Self::set_feature_bool_internal(cam, "StrobeEnable", false); Self::set_feature_int_internal( cam, "StrobeLineDuration", @@ -1072,7 +1101,7 @@ impl CameraService { Self::set_feature_int_internal(cam, "StrobeLineDelay", 0); Self::set_feature_int_internal(cam, "StrobeLinePreDelay", 0); } - println!("[camera] Strobe configured on Line1"); + println!("[camera] Strobe wiring configured on Line1 (StrobeEnable=false, armed for capture)"); } /// Disable strobe output during setup preview to prevent flash from firing. @@ -1080,14 +1109,9 @@ impl CameraService { if cam.is_null() { return; } + // Just disable strobe — don't try to set LineSource to 'Off' as Hikrobot + // doesn't support that value (confirmed from logs: "'Off' not an entry") Self::set_feature_bool_internal(cam, "StrobeEnable", false); - Self::set_feature_int_internal(cam, "StrobeEnable", 0); - if Self::is_feature_available_internal(cam, "LineSelector") { - for line in ["Line1", "Line2"] { - Self::set_feature_str_internal(cam, "LineSelector", line); - Self::set_feature_str_internal(cam, "LineSource", "Off"); - } - } println!("[camera] Strobe disabled for preview mode"); } @@ -1212,7 +1236,6 @@ impl CameraService { } } - #[allow(dead_code)] fn get_feature_str_internal(cam: *mut ArvCamera, feature: &str) -> Option { if cam.is_null() { return None; From 644e31522be6a5977534ec24829e519756b0abf9 Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Sat, 15 Aug 2026 03:10:16 +0200 Subject: [PATCH 27/65] fix: align with electronbun implementation --- headless-rust/src/camera/mod.rs | 65 +++++++++------------------------ 1 file changed, 18 insertions(+), 47 deletions(-) diff --git a/headless-rust/src/camera/mod.rs b/headless-rust/src/camera/mod.rs index 2c0329d..7061bfc 100644 --- a/headless-rust/src/camera/mod.rs +++ b/headless-rust/src/camera/mod.rs @@ -208,23 +208,18 @@ impl CameraService { } // ── Line & Strobe Flash Configuration ────────────────────────────── - // Configure Line1 strobe wiring but keep StrobeEnable=false. - // Strobe is ONLY enabled briefly during capture_frame_jpeg() to - // prevent permanent flash firing if trigger mode doesn't stick. + // 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 (safety net) ───────────────────────────────────── - // Keep frame rate limiting enabled at a low rate even in triggered - // mode. If trigger mode fails for any reason, this prevents the - // camera from flooding the network at 63 FPS. + // Frame rate limit helps prevent network flood if trigger mode fails. Self::set_frame_rate_enable_internal(cam, true); Self::set_frame_rate_internal(cam, 5.0); println!("[camera] Frame rate safety net: 5 FPS (triggered mode)"); @@ -263,15 +258,6 @@ impl CameraService { *self.stream_ptr.lock().unwrap() = stream; self.is_connected.store(true, Ordering::SeqCst); - // Post-acquisition diagnostic: verify trigger mode survived start_acquisition - if let Some(readback) = Self::get_feature_str_internal(cam, "TriggerMode") { - println!("[camera] POST-ACQUISITION TriggerMode readback: {}", readback); - if readback != "On" { - println!("[camera] WARNING: Camera reset TriggerMode to '{}' after acquisition start! Re-applying...", readback); - Self::set_trigger_mode_internal(cam, "Software"); - } - } - println!("[camera] Connected and acquisition started successfully"); let _ = self.status_sender.send(self.get_status()); } @@ -348,18 +334,12 @@ impl CameraService { arv_stream_push_buffer(stream, stale); } - // Enable strobe for this capture only - Self::set_feature_bool_internal(cam, "StrobeEnable", true); - // 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); - // Disable strobe immediately after frame received (or timeout) - Self::set_feature_bool_internal(cam, "StrobeEnable", false); - if buffer.is_null() { println!("[camera] Capture frame timed out"); return None; @@ -548,11 +528,10 @@ impl CameraService { // 2. Flush stream buffers Self::flush_stream_buffers(self); - // 3. Restore trigger mode (FrameBurstStart/On/Software) + // 3. Restore trigger mode Self::set_trigger_mode_internal(cam, "Software"); - // 4. Restore strobe wiring but keep StrobeEnable=false - // (strobe only enabled during capture_frame_jpeg) + // 4. Restore strobe configuration Self::configure_strobe_internal(cam, settings); // 5. Restore exposure & gain @@ -577,15 +556,6 @@ impl CameraService { g_error_free(err); } } - - // 8. Post-acquisition diagnostic: verify trigger mode survived - if let Some(readback) = Self::get_feature_str_internal(cam, "TriggerMode") { - println!("[camera] POST-ACQUISITION TriggerMode readback: {}", readback); - if readback != "On" { - println!("[camera] WARNING: Camera reset TriggerMode after start! Re-applying..."); - Self::set_trigger_mode_internal(cam, "Software"); - } - } } } println!("[camera] Setup preview stream stopped, restored triggered capture mode"); @@ -1067,9 +1037,6 @@ impl CameraService { // ── Shared Helper Functions ──────────────────────────────────────────────── /// Configure Line1 as strobe output with full settings from AppSettings. - /// Strobe wiring is configured but StrobeEnable is left OFF. - /// Strobe is only enabled briefly during capture_frame_jpeg() to prevent - /// permanent flash firing if trigger mode doesn't work as expected. fn configure_strobe_internal(cam: *mut ArvCamera, settings: &AppSettings) { if cam.is_null() { return; @@ -1079,11 +1046,12 @@ impl CameraService { } Self::set_feature_str_internal(cam, "LineSelector", "Line1"); Self::set_feature_str_internal(cam, "LineMode", "Strobe"); - if Self::is_enumeration_entry_available_internal(cam, "LineSource", "FrameStartActive") { - Self::set_feature_str_internal(cam, "LineSource", "FrameStartActive"); - } else if Self::is_enumeration_entry_available_internal(cam, "LineSource", "ExposureActive") - { + + // Match electronbun: prefer ExposureActive to limit flash strictly to the exposure window + 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"); } else if Self::is_enumeration_entry_available_internal(cam, "LineSource", "Strobe") { Self::set_feature_str_internal(cam, "LineSource", "Strobe"); } @@ -1091,8 +1059,9 @@ impl CameraService { Self::set_feature_int_internal(cam, "LineDebouncerTime", 50); if Self::is_feature_available_internal(cam, "StrobeEnable") { - // Keep strobe DISABLED — only enabled during capture_frame_jpeg() - Self::set_feature_bool_internal(cam, "StrobeEnable", false); + if !Self::set_feature_bool_internal(cam, "StrobeEnable", true) { + Self::set_feature_int_internal(cam, "StrobeEnable", 1); + } Self::set_feature_int_internal( cam, "StrobeLineDuration", @@ -1101,7 +1070,7 @@ impl CameraService { Self::set_feature_int_internal(cam, "StrobeLineDelay", 0); Self::set_feature_int_internal(cam, "StrobeLinePreDelay", 0); } - println!("[camera] Strobe wiring configured on Line1 (StrobeEnable=false, armed for capture)"); + println!("[camera] Strobe configured on Line1 (StrobeEnable=true)"); } /// Disable strobe output during setup preview to prevent flash from firing. @@ -1472,8 +1441,10 @@ impl CameraService { return false; } - // Try FrameBurstStart first (Hikrobot), then FrameStart, then AcquisitionStart - let selectors = ["FrameBurstStart", "FrameStart", "AcquisitionStart"]; + // IMPORTANT: FrameStart must be preferred over FrameBurstStart. + // If FrameBurstStart is set to On but FrameStart remains Off (free-run), + // the camera will continuously expose and strobe the flash indefinitely! + let selectors = ["FrameStart", "FrameBurstStart", "AcquisitionStart"]; for sel in selectors { if Self::set_feature_str_internal(cam, "TriggerSelector", sel) { let mode_ok = Self::set_feature_str_internal(cam, "TriggerMode", "On"); From dfd9dd005453c77dfa04708b0ffd0afbe0644e18 Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Sat, 15 Aug 2026 03:17:03 +0200 Subject: [PATCH 28/65] fix: adjust frame rate handling and burst frame count for triggered mode --- headless-rust/src/camera/mod.rs | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/headless-rust/src/camera/mod.rs b/headless-rust/src/camera/mod.rs index 7061bfc..768894f 100644 --- a/headless-rust/src/camera/mod.rs +++ b/headless-rust/src/camera/mod.rs @@ -216,13 +216,16 @@ impl CameraService { 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 (safety net) ───────────────────────────────────── - // Frame rate limit helps prevent network flood if trigger mode fails. - Self::set_frame_rate_enable_internal(cam, true); - Self::set_frame_rate_internal(cam, 5.0); - println!("[camera] Frame rate safety net: 5 FPS (triggered mode)"); + // ── 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); + println!("[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); @@ -544,9 +547,8 @@ impl CameraService { Self::set_gain_internal(cam, settings.camera_gain); } - // 6. Frame rate safety net (low rate in case trigger fails) - Self::set_frame_rate_enable_internal(cam, true); - Self::set_frame_rate_internal(cam, 5.0); + // 6. Disable frame rate limiting in triggered mode + Self::set_frame_rate_enable_internal(cam, false); // 7. Restart acquisition in triggered mode unsafe { From da63583ce4f7777c5ffd2cf73b584f5ec4a6ed14 Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Sat, 15 Aug 2026 17:52:18 +0200 Subject: [PATCH 29/65] fix: add tracing and related dependencies for improved logging --- headless-rust/Cargo.lock | 31 +++++++++++++++++++++++++++++++ headless-rust/Cargo.toml | 3 +++ 2 files changed, 34 insertions(+) diff --git a/headless-rust/Cargo.lock b/headless-rust/Cargo.lock index 75227b9..4a24b36 100644 --- a/headless-rust/Cargo.lock +++ b/headless-rust/Cargo.lock @@ -526,6 +526,15 @@ 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" @@ -1043,6 +1052,9 @@ dependencies = [ "serialport", "tokio", "tokio-stream", + "tracing", + "tracing-appender", + "tracing-subscriber", "url", ] @@ -2987,6 +2999,12 @@ 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" @@ -3332,6 +3350,19 @@ dependencies = [ "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 2.0.20", + "time", + "tracing-subscriber", +] + [[package]] name = "tracing-attributes" version = "0.1.31" diff --git a/headless-rust/Cargo.toml b/headless-rust/Cargo.toml index c9c11bc..e387e44 100644 --- a/headless-rust/Cargo.toml +++ b/headless-rust/Cargo.toml @@ -24,6 +24,9 @@ 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" [build-dependencies] pkg-config = "0.3" From 9810551ee2d573fcfd1775b272783288e7b5763f Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Sat, 15 Aug 2026 17:53:20 +0200 Subject: [PATCH 30/65] fix: replace println! with tracing! for improved logging consistency --- headless-rust/src/camera/mod.rs | 210 ++++++++++++++++++-------------- headless-rust/src/main.rs | 42 ++++--- headless-rust/src/serial/mod.rs | 24 ++-- headless-rust/src/web/ws.rs | 56 +++++---- 4 files changed, 188 insertions(+), 144 deletions(-) diff --git a/headless-rust/src/camera/mod.rs b/headless-rust/src/camera/mod.rs index 768894f..309f994 100644 --- a/headless-rust/src/camera/mod.rs +++ b/headless-rust/src/camera/mod.rs @@ -130,7 +130,7 @@ impl CameraService { arv_update_device_list(); let n = arv_get_n_devices(); if n == 0 { - println!("[camera] No GigE Vision cameras detected on network"); + tracing::info!("[camera] No GigE Vision cameras detected on network"); return; } @@ -141,7 +141,7 @@ impl CameraService { 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(); - println!("[camera] Found device [{}]: {} ({})", i, v, id); + tracing::info!("[camera] Found device [{}]: {} ({})", i, v, id); if v.to_lowercase().contains("hikrobot") || target_id.is_none() { target_id = Some(id.to_string()); } @@ -156,7 +156,7 @@ impl CameraService { if cam.is_null() { if !err.is_null() { let msg = CStr::from_ptr((*err).message).to_string_lossy(); - println!("[camera] Failed to open camera: {}", msg); + tracing::info!("[camera] Failed to open camera: {}", msg); g_error_free(err); } return; @@ -168,18 +168,26 @@ impl CameraService { if !err.is_null() { g_error_free(err); } else { - println!("[camera] GigE Vision auto packet size set to: {} bytes", packet_size); + tracing::info!("[camera] GigE Vision auto packet size set to: {} bytes", packet_size); } - // Set GevSCPD (Stream Channel Packet Delay) to 2000 ticks - // This spaces out UDP packets to prevent NIC packet storms and SSH stalls + // 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, 2000, &mut delay_err); + 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", 2000); + Self::set_feature_int_internal(cam, "GevSCPD", scpd); } - println!("[camera] GigE Vision GevSCPD packet delay set to: 2000"); + tracing::info!("[camera] GigE Vision GevSCPD packet delay set to: {}", scpd); } // Set PixelFormat @@ -225,12 +233,12 @@ impl CameraService { // 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); - println!("[camera] Frame rate limiting disabled (triggered mode)"); + 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() { - println!("[camera] Failed to create stream"); + tracing::info!("[camera] Failed to create stream"); g_object_unref(cam as *mut _); return; } @@ -253,7 +261,7 @@ impl CameraService { arv_camera_start_acquisition(cam, &mut err); if !err.is_null() { let msg = CStr::from_ptr((*err).message).to_string_lossy(); - println!("[camera] Warning: arv_camera_start_acquisition returned error: {}", msg); + tracing::warn!("[camera] arv_camera_start_acquisition returned error: {}", msg); g_error_free(err); } @@ -261,7 +269,7 @@ impl CameraService { *self.stream_ptr.lock().unwrap() = stream; self.is_connected.store(true, Ordering::SeqCst); - println!("[camera] Connected and acquisition started successfully"); + tracing::info!("[camera] Connected and acquisition started successfully"); let _ = self.status_sender.send(self.get_status()); } } @@ -300,7 +308,7 @@ impl CameraService { } } - println!("[camera] Disconnected"); + tracing::info!("[camera] Disconnected"); let _ = self.status_sender.send(self.get_status()); } @@ -344,13 +352,13 @@ impl CameraService { let buffer = arv_stream_timeout_pop_buffer(stream, 2_000_000); if buffer.is_null() { - println!("[camera] Capture frame timed out"); + tracing::warn!("[camera] Capture frame timed out"); return None; } let status = arv_buffer_get_status(buffer); if status != ARV_BUFFER_STATUS_SUCCESS { - println!( + tracing::info!( "[camera] Capture buffer failed with status: {} ({})", buffer_status_name(status), status @@ -388,7 +396,7 @@ impl CameraService { let this = self.clone(); tokio::task::spawn_blocking(move || { - println!("[camera] Setup preview stream starting..."); + tracing::info!("[camera] Setup preview stream starting..."); if !this.mock_mode { let cam = *this.camera_ptr.lock().unwrap(); @@ -430,14 +438,14 @@ impl CameraService { arv_camera_start_acquisition(cam, &mut err); if !err.is_null() { let msg = CStr::from_ptr((*err).message).to_string_lossy(); - println!("[camera] Error restarting acquisition for setup stream: {}", msg); + tracing::info!("[camera] Error restarting acquisition for setup stream: {}", msg); g_error_free(err); } } } } - println!("[camera] Setup preview stream active"); + tracing::info!("[camera] Setup preview stream active"); let is_encoding = Arc::new(AtomicBool::new(false)); @@ -504,7 +512,7 @@ impl CameraService { } } - println!("[camera] Setup preview stream thread exited"); + tracing::info!("[camera] Setup preview stream thread exited"); }); } @@ -560,7 +568,7 @@ impl CameraService { } } } - println!("[camera] Setup preview stream stopped, restored triggered capture mode"); + tracing::info!("[camera] Setup preview stream stopped, restored triggered capture mode"); let _ = self.status_sender.send(self.get_status()); } @@ -1038,8 +1046,14 @@ impl CameraService { // ── Shared Helper Functions ──────────────────────────────────────────────── - /// Configure Line1 as strobe output with full settings from AppSettings. - fn configure_strobe_internal(cam: *mut ArvCamera, settings: &AppSettings) { + /// Configure Line1 as strobe output, matching electronbun behavior. + /// + /// Uses LineSource=ExposureActive so the flash fires ONLY during the + /// exposure window of a triggered frame. StrobeEnable/StrobeLineDuration + /// are intentionally NOT set: on Hikrobot cameras, enabling StrobeEnable + /// with a duration makes the line free-run on its own timer, causing the + /// flash to strobe continuously regardless of trigger state. + fn configure_strobe_internal(cam: *mut ArvCamera, _settings: &AppSettings) { if cam.is_null() { return; } @@ -1048,31 +1062,24 @@ impl CameraService { } Self::set_feature_str_internal(cam, "LineSelector", "Line1"); Self::set_feature_str_internal(cam, "LineMode", "Strobe"); - - // Match electronbun: prefer ExposureActive to limit flash strictly to the exposure window + + // Prefer ExposureActive to limit flash strictly to the exposure window 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", "ExposureStartActive") { + Self::set_feature_str_internal(cam, "LineSource", "ExposureStartActive"); } else if Self::is_enumeration_entry_available_internal(cam, "LineSource", "FrameStartActive") { Self::set_feature_str_internal(cam, "LineSource", "FrameStartActive"); - } else if Self::is_enumeration_entry_available_internal(cam, "LineSource", "Strobe") { - Self::set_feature_str_internal(cam, "LineSource", "Strobe"); } Self::set_line_inverter_internal(cam, false); - Self::set_feature_int_internal(cam, "LineDebouncerTime", 50); + // Ensure the free-running strobe timer is OFF — LineSource drives the pulse. 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); + if !Self::set_feature_bool_internal(cam, "StrobeEnable", false) { + Self::set_feature_int_internal(cam, "StrobeEnable", 0); } - Self::set_feature_int_internal( - cam, - "StrobeLineDuration", - settings.strobe_line_duration as i64, - ); - Self::set_feature_int_internal(cam, "StrobeLineDelay", 0); - Self::set_feature_int_internal(cam, "StrobeLinePreDelay", 0); } - println!("[camera] Strobe configured on Line1 (StrobeEnable=true)"); + tracing::info!("[camera] Strobe configured on Line1 (LineSource=ExposureActive, StrobeEnable=false)"); } /// Disable strobe output during setup preview to prevent flash from firing. @@ -1080,10 +1087,10 @@ impl CameraService { if cam.is_null() { return; } - // Just disable strobe — don't try to set LineSource to 'Off' as Hikrobot - // doesn't support that value (confirmed from logs: "'Off' not an entry") + // Disable strobe timer; LineSource=ExposureActive alone won't fire + // without exposures, but belt-and-braces for preview mode. Self::set_feature_bool_internal(cam, "StrobeEnable", false); - println!("[camera] Strobe disabled for preview mode"); + tracing::info!("[camera] Strobe disabled for preview mode"); } /// Flush all pending buffers from the stream output queue back to the input pool. @@ -1103,7 +1110,7 @@ impl CameraService { flushed += 1; } if flushed > 0 { - println!("[camera] Flushed {} stale buffers", flushed); + tracing::debug!("[camera] Flushed {} stale buffers", flushed); } } } @@ -1118,17 +1125,17 @@ impl CameraService { let actual = arv_camera_get_frame_rate(cam, &mut err); if !err.is_null() { g_error_free(err); - println!("[camera] WARNING: Could not read back frame rate for verification"); + tracing::warn!("[camera] Could not read back frame rate for verification"); return; } let diff = (actual - target_fps).abs(); if diff > 1.0 { - println!( + 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 { - println!("[camera] Frame rate verified: {:.1} FPS (target: {:.1})", actual, target_fps); + tracing::debug!("[camera] Frame rate verified: {:.1} FPS (target: {:.1})", actual, target_fps); } } } @@ -1166,11 +1173,11 @@ impl CameraService { 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(); - println!("[camera] Warning: execute_command({}) failed: {}", command, msg); + tracing::warn!("[camera] execute_command({}) failed: {}", command, msg); g_error_free(err); false } else { - println!("[camera] execute_command({}) succeeded", command); + tracing::debug!("[camera] execute_command({}) succeeded", command); true } } @@ -1197,11 +1204,11 @@ impl CameraService { 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(); - println!("[camera] Warning: set_feature_str({}, {}) failed: {}", feature, value, msg); + tracing::warn!("[camera] set_feature_str({}, {}) failed: {}", feature, value, msg); g_error_free(err); false } else { - println!("[camera] set_feature_str({}, {}) succeeded", feature, value); + tracing::debug!("[camera] set_feature_str({}, {}) succeeded", feature, value); true } } @@ -1250,11 +1257,11 @@ impl CameraService { 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(); - println!("[camera] Warning: set_feature_int({}, {}) failed: {}", feature, value, msg); + tracing::warn!("[camera] set_feature_int({}, {}) failed: {}", feature, value, msg); g_error_free(err); false } else { - println!("[camera] set_feature_int({}, {}) succeeded", feature, value); + tracing::debug!("[camera] set_feature_int({}, {}) succeeded", feature, value); true } } @@ -1301,11 +1308,11 @@ impl CameraService { 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(); - println!("[camera] Warning: set_feature_float({}, {}) failed: {}", feature, value, msg); + tracing::warn!("[camera] set_feature_float({}, {}) failed: {}", feature, value, msg); g_error_free(err); false } else { - println!("[camera] set_feature_float({}, {}) succeeded", feature, value); + tracing::debug!("[camera] set_feature_float({}, {}) succeeded", feature, value); true } } @@ -1333,11 +1340,11 @@ impl CameraService { ); if !err.is_null() { let msg = CStr::from_ptr((*err).message).to_string_lossy(); - println!("[camera] Warning: set_feature_bool({}, {}) failed: {}", feature, value, msg); + tracing::warn!("[camera] set_feature_bool({}, {}) failed: {}", feature, value, msg); g_error_free(err); false } else { - println!("[camera] set_feature_bool({}, {}) succeeded", feature, value); + tracing::debug!("[camera] set_feature_bool({}, {}) succeeded", feature, value); true } } @@ -1352,11 +1359,11 @@ impl CameraService { arv_camera_set_exposure_time(cam, us, &mut err); if !err.is_null() { let msg = CStr::from_ptr((*err).message).to_string_lossy(); - println!("[camera] Warning: arv_camera_set_exposure_time({}) failed: {}", us, msg); + tracing::warn!("[camera] arv_camera_set_exposure_time({}) failed: {}", us, msg); g_error_free(err); false } else { - println!("[camera] Set exposure time to {} µs", us); + tracing::info!("[camera] Set exposure time to {} µs", us); true } } @@ -1371,11 +1378,11 @@ impl CameraService { arv_camera_set_gain(cam, gain, &mut err); if !err.is_null() { let msg = CStr::from_ptr((*err).message).to_string_lossy(); - println!("[camera] Warning: arv_camera_set_gain({}) failed: {}", gain, msg); + tracing::warn!("[camera] arv_camera_set_gain({}) failed: {}", gain, msg); g_error_free(err); false } else { - println!("[camera] Set gain to {}", gain); + tracing::info!("[camera] Set gain to {}", gain); true } } @@ -1390,11 +1397,11 @@ impl CameraService { arv_camera_set_frame_rate(cam, fps, &mut err); if !err.is_null() { let msg = CStr::from_ptr((*err).message).to_string_lossy(); - println!("[camera] Warning: arv_camera_set_frame_rate({}) failed: {}", fps, msg); + tracing::warn!("[camera] arv_camera_set_frame_rate({}) failed: {}", fps, msg); g_error_free(err); false } else { - println!("[camera] Set frame rate to {} FPS", fps); + tracing::info!("[camera] Set frame rate to {} FPS", fps); true } } @@ -1435,42 +1442,61 @@ impl CameraService { /// Configure triggered capture mode using direct GenICam device features. /// - /// Avoids `arv_camera_set_trigger()` which uses TriggerSelector=AcquisitionStart - /// internally — wrong for Hikrobot cameras that use FrameBurstStart. - /// Uses explicit 3-step sequence: TriggerSelector → TriggerMode → TriggerSource. + /// 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; } - // IMPORTANT: FrameStart must be preferred over FrameBurstStart. - // If FrameBurstStart is set to On but FrameStart remains Off (free-run), - // the camera will continuously expose and strobe the flash indefinitely! + // 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) { - 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 { - println!( - "[camera] Trigger configured: Selector={}, Mode=On, Source={}", - sel, trigger_source + 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 ); - // Verify TriggerMode actually stuck - if let Some(readback) = Self::get_feature_str_internal(cam, "TriggerMode") { - if readback != "On" { - println!( - "[camera] WARNING: TriggerMode readback is '{}' (expected 'On')", - readback - ); - } - } - return true; } } + return true; } - println!("[camera] ERROR: Failed to configure trigger mode on any selector"); + tracing::error!("[camera] Failed to configure trigger mode on selector {}", active); false } @@ -1487,16 +1513,16 @@ impl CameraService { for sel in ["FrameBurstStart", "FrameStart", "AcquisitionStart"] { if Self::set_feature_str_internal(cam, "TriggerSelector", sel) { if Self::set_feature_str_internal(cam, "TriggerMode", "Off") { - println!("[camera] Trigger disabled: Selector={}, Mode=Off", sel); + tracing::info!("[camera] Trigger disabled: Selector={}, Mode=Off", sel); any_success = true; } } } if any_success { - println!("[camera] Triggers cleared — camera in free-running mode"); + tracing::info!("[camera] Triggers cleared — camera in free-running mode"); } else { - println!("[camera] WARNING: Could not clear triggers on any selector"); + tracing::warn!("[camera] Could not clear triggers on any selector"); } any_success } @@ -1512,7 +1538,7 @@ impl CameraService { true } else { let msg = CStr::from_ptr((*err).message).to_string_lossy(); - println!("[camera] arv_camera_software_trigger returned: {}. Trying command execution fallback...", msg); + tracing::info!("[camera] arv_camera_software_trigger returned: {}. Trying command execution fallback...", msg); g_error_free(err); Self::execute_command_internal(cam, "TriggerSoftware") } @@ -1565,7 +1591,7 @@ impl CameraService { if enable { 1 } else { 0 }, ); } - println!( + tracing::info!( "[camera] AcquisitionFrameRateEnable = {}", if enable { "true" } else { "false" } ); @@ -1609,18 +1635,18 @@ impl CameraService { let mut err = null_mut(); arv_camera_set_pixel_format_from_string(cam, fmt_cstr.as_ptr(), &mut err); if err.is_null() { - println!("[camera] PixelFormat set to {}", fmt); + tracing::info!("[camera] PixelFormat set to {}", fmt); return true; } else { g_error_free(err); } } if Self::set_feature_str_internal(cam, "PixelFormat", fmt) { - println!("[camera] PixelFormat set to {}", fmt); + tracing::info!("[camera] PixelFormat set to {}", fmt); return true; } } - println!("[camera] Warning: Could not configure requested PixelFormat {}, retaining current format", format); + tracing::warn!("[camera] Could not configure requested PixelFormat {}, retaining current format", format); false } diff --git a/headless-rust/src/main.rs b/headless-rust/src/main.rs index fc5584f..9dfd8c7 100644 --- a/headless-rust/src/main.rs +++ b/headless-rust/src/main.rs @@ -32,28 +32,40 @@ struct Args { #[rocket::main] async fn main() -> Result<(), rocket::Error> { + // 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); - println!("─────────────────────────────────────────────────────────────────"); - println!(" ⚡ Speedcamera Headless Daemon (Rust & Rocket)"); - println!(" • Port: http://{}:{}", config.host, config.port); - println!(" • Data Dir: {}", config.data_dir.display()); - println!(" • Mock Mode: {}", config.mock_mode); - println!("─────────────────────────────────────────────────────────────────"); + tracing::info!("─────────────────────────────────────────────────────────────────"); + tracing::info!(" ⚡ Speedcamera Headless Daemon (Rust & Rocket)"); + 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(); - println!(" • Camera LAN [{}]: {} -> [{}]", + 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() ); - println!(" • Hotspot AP [{}]: {} -> [{}]", + 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() ); - println!("─────────────────────────────────────────────────────────────────"); + tracing::info!("─────────────────────────────────────────────────────────────────"); // Initialize Database let db = Database::new(&config.db_path).expect("Failed to initialize SQLite database"); @@ -72,7 +84,7 @@ async fn main() -> Result<(), rocket::Error> { let conn = db.lock(); if let Ok(settings) = db::settings::get_settings(&conn) { if !settings.selected_port.is_empty() { - println!("[serial] Auto-connecting configured port: {}", settings.selected_port); + tracing::info!("[serial] Auto-connecting configured port: {}", settings.selected_port); serial.open_port(&settings.selected_port); } } @@ -91,7 +103,7 @@ async fn main() -> Result<(), rocket::Error> { match serial_rx.recv().await { Ok(msg) => { if let models::SerialStatusPayload::Speeding { value, direction, .. } = msg { - println!("[trigger-pipeline] Speeding detected ({} km/h) -> Triggering camera shutter!", value); + tracing::info!("[trigger-pipeline] Speeding detected ({} km/h) -> Triggering camera shutter!", value); let cam = pipeline_cam.clone(); let db_clone = pipeline_db.clone(); @@ -110,21 +122,21 @@ async fn main() -> Result<(), rocket::Error> { direction, }; if let Ok(v) = db::violations::insert_violation(&conn, &input, &img_path) { - println!("[trigger-pipeline] Recorded violation #{} ({} km/h)", v.id, v.measured_speed); + tracing::info!("[trigger-pipeline] Recorded violation #{} ({} km/h)", v.id, v.measured_speed); let _ = v_tx.send(v); } } } else { - println!("[trigger-pipeline] Failed to capture frame during speeding event"); + tracing::warn!("[trigger-pipeline] Failed to capture frame during speeding event"); } }); } } Err(tokio::sync::broadcast::error::RecvError::Lagged(missed)) => { - println!("[trigger-pipeline] Warning: Serial receiver lagged by {} messages", missed); + tracing::warn!("[trigger-pipeline] Serial receiver lagged by {} messages", missed); } Err(tokio::sync::broadcast::error::RecvError::Closed) => { - println!("[trigger-pipeline] Serial channel closed, exiting pipeline task"); + tracing::info!("[trigger-pipeline] Serial channel closed, exiting pipeline task"); break; } } diff --git a/headless-rust/src/serial/mod.rs b/headless-rust/src/serial/mod.rs index 113254a..08c4c13 100644 --- a/headless-rust/src/serial/mod.rs +++ b/headless-rust/src/serial/mod.rs @@ -119,7 +119,7 @@ impl SerialService { }) .collect(), Err(e) => { - println!("[serial] Failed to list ports: {}", e); + tracing::warn!("[serial] Failed to list ports: {}", e); Vec::new() } } @@ -127,7 +127,7 @@ impl SerialService { pub fn open_port(self: &Arc, port_path: &str) { if self.mock_mode { - println!("[serial] Opened mock port {}", port_path); + 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()), @@ -158,7 +158,7 @@ impl SerialService { let builder = serialport::new(&path, 115_200).timeout(Duration::from_millis(500)); match builder.open() { Ok(port) => { - println!("[serial] Successfully opened {}", path); + tracing::info!("[serial] Successfully opened {}", path); let _ = this.status_sender.send(SerialStatusPayload::Connected { port: Some(path.clone()), }); @@ -166,7 +166,7 @@ impl SerialService { let reader_port = match port.try_clone() { Ok(p) => p, Err(e) => { - println!("[serial] Failed to clone port for reading: {}", e); + tracing::warn!("[serial] Failed to clone port for reading: {}", e); return; } }; @@ -183,7 +183,7 @@ impl SerialService { match reader.read_line(&mut line_buf) { Ok(0) => { // EOF: Serial hardware disconnected or reset - println!("[serial] EOF on {} (device disconnected)", path); + tracing::warn!("[serial] EOF on {} (device disconnected)", path); break; } Ok(_) => { @@ -196,7 +196,7 @@ impl SerialService { // Expected timeout when idle } Err(e) => { - println!("[serial] Read error on {}: {}", path, e); + tracing::warn!("[serial] Read error on {}: {}", path, e); break; } } @@ -204,7 +204,7 @@ impl SerialService { // Only clean up state if this session is still the active one if this.session_id.load(Ordering::SeqCst) == session { - println!("[serial] Port {} closed / disconnected", path); + tracing::info!("[serial] Port {} closed / disconnected", path); *this.active_port.lock().unwrap() = None; let _ = this.status_sender.send(SerialStatusPayload::Disconnected); @@ -216,7 +216,7 @@ impl SerialService { } } Err(e) => { - println!("[serial] Failed to open {}: {}", path, 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(); @@ -245,7 +245,7 @@ impl SerialService { return; } - println!("[serial] Attempting auto-reconnect to {}...", path); + tracing::info!("[serial] Attempting auto-reconnect to {}...", path); this.open_port(&path); }); } @@ -256,7 +256,7 @@ impl SerialService { *self.active_port.lock().unwrap() = None; *self.active_path.lock().unwrap() = String::new(); let _ = self.status_sender.send(SerialStatusPayload::Disconnected); - println!("[serial] Port manually closed"); + tracing::info!("[serial] Port manually closed"); } pub fn send_command(&self, json: &str) { @@ -272,7 +272,7 @@ impl SerialService { let mut data = json.as_bytes().to_vec(); data.push(b'\n'); if let Err(e) = port.write_all(&data).and_then(|_| port.flush()) { - println!("[serial] Failed to write command: {}", e); + tracing::warn!("[serial] Failed to write command: {}", e); } } } @@ -286,7 +286,7 @@ impl SerialService { } else { // Check if debug message if !line.contains("\"debug\"") { - println!("[serial] Raw: {}", line); + tracing::debug!("[serial] Raw: {}", line); } } } diff --git a/headless-rust/src/web/ws.rs b/headless-rust/src/web/ws.rs index ae5625f..aeb0a5c 100644 --- a/headless-rust/src/web/ws.rs +++ b/headless-rust/src/web/ws.rs @@ -37,7 +37,7 @@ pub fn ws_rpc( ws.channel(move |stream: DuplexStream| { let ctx = ctx.clone(); Box::pin(async move { - println!("[ws] Client connected"); + tracing::info!("[ws] Client connected"); let (mut ws_sink, mut ws_stream) = stream.split(); @@ -48,7 +48,7 @@ pub fn ws_rpc( let writer_handle = tokio::spawn(async move { while let Some(msg) = out_rx.recv().await { if let Err(e) = ws_sink.send(msg).await { - println!("[ws-writer] Send error or client disconnected: {}", e); + tracing::warn!("[ws-writer] Send error or client disconnected: {}", e); break; } } @@ -103,11 +103,11 @@ pub fn ws_rpc( } Some(Ok(Message::Pong(_))) => {} Some(Ok(Message::Close(_))) | None => { - println!("[ws] Client disconnected cleanly"); + tracing::info!("[ws] Client disconnected cleanly"); break; } Some(Err(e)) => { - println!("[ws] Error reading from stream: {}", e); + tracing::warn!("[ws] Error reading from stream: {}", e); break; } _ => {} @@ -121,7 +121,7 @@ pub fn ws_rpc( } } - // Serial telemetry broadcast + // Serial telemetry broadcast (drop on slow client — next update follows soon) res = serial_rx.recv() => { match res { Ok(payload) => { @@ -129,18 +129,16 @@ pub fn ws_rpc( "event": "serialStatus", "payload": payload }); - if out_tx.send(Message::Text(msg.to_string())).await.is_err() { - break; - } + let _ = out_tx.try_send(Message::Text(msg.to_string())); } Err(broadcast::error::RecvError::Lagged(n)) => { - println!("[ws] Serial broadcast lagged by {} messages", n); + tracing::debug!("[ws] Serial broadcast lagged by {} messages", n); } Err(broadcast::error::RecvError::Closed) => break, } } - // Camera status broadcast + // Camera status broadcast (drop on slow client — status is re-sent on change) res = camera_status_rx.recv() => { match res { Ok(payload) => { @@ -148,12 +146,10 @@ pub fn ws_rpc( "event": "cameraStatus", "payload": payload }); - if out_tx.send(Message::Text(msg.to_string())).await.is_err() { - break; - } + let _ = out_tx.try_send(Message::Text(msg.to_string())); } Err(broadcast::error::RecvError::Lagged(n)) => { - println!("[ws] Camera status broadcast lagged by {} messages", n); + tracing::debug!("[ws] Camera status broadcast lagged by {} messages", n); } Err(broadcast::error::RecvError::Closed) => break, } @@ -177,27 +173,39 @@ pub fn ws_rpc( } } - // Violation broadcast (high priority) + // Violation broadcast (high priority — retry briefly, then drop rather than stall) res = violation_rx.recv() => { match res { Ok(v) => { - println!("[ws] Broadcasting violation #{} to client", v.id); + tracing::info!("[ws] Broadcasting violation #{} to client", v.id); let msg = json!({ "event": "violation", "payload": v }); - if out_tx.send(Message::Text(msg.to_string())).await.is_err() { - break; + let text = Message::Text(msg.to_string()); + // Try a few times with tiny yields; never block the select loop + let mut sent = false; + for _ in 0..10 { + match out_tx.try_send(text.clone()) { + Ok(_) => { sent = true; break; } + Err(mpsc::error::TrySendError::Full(_)) => { + tokio::time::sleep(Duration::from_millis(20)).await; + } + Err(_) => break, + } + } + if !sent { + tracing::warn!("[ws] Dropped violation #{} — client too slow", v.id); } } Err(broadcast::error::RecvError::Lagged(n)) => { - println!("[ws] Violation broadcast lagged by {} messages", n); + tracing::debug!("[ws] Violation broadcast lagged by {} messages", n); } Err(broadcast::error::RecvError::Closed) => break, } } - // Flash progress broadcast + // Flash progress broadcast (drop on slow client) res = flash_rx.recv() => { match res { Ok(payload) => { @@ -205,12 +213,10 @@ pub fn ws_rpc( "event": "flashProgress", "payload": payload }); - if out_tx.send(Message::Text(msg.to_string())).await.is_err() { - break; - } + let _ = out_tx.try_send(Message::Text(msg.to_string())); } Err(broadcast::error::RecvError::Lagged(n)) => { - println!("[ws] Flash progress broadcast lagged by {} messages", n); + tracing::debug!("[ws] Flash progress broadcast lagged by {} messages", n); } Err(broadcast::error::RecvError::Closed) => break, } @@ -222,7 +228,7 @@ pub fn ws_rpc( drop(out_tx); let _ = writer_handle.await; - println!("[ws] Client session ended"); + tracing::info!("[ws] Client session ended"); Ok(()) }) }) From 2a7ef23e7628f4bfebaa6e6276ee5c5ef78c0c37 Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Sat, 15 Aug 2026 17:53:26 +0200 Subject: [PATCH 31/65] fix: update GigE Vision socket buffer optimizations to 128MB and adjust MTU settings --- headless-rust/scripts/setup-network.sh | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/headless-rust/scripts/setup-network.sh b/headless-rust/scripts/setup-network.sh index a253544..9174e0f 100755 --- a/headless-rust/scripts/setup-network.sh +++ b/headless-rust/scripts/setup-network.sh @@ -31,16 +31,21 @@ case "$MODE" in echo "" # Apply GigE Vision kernel socket buffer optimizations - echo "[*] Applying GigE Vision network socket buffer optimizations (64MB)..." + echo "[*] Applying GigE Vision network socket buffer optimizations (128MB)..." 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 — critical for GigE Vision throughput. + # Larger MTU = fewer packets = fewer interrupts = less CPU/softirq pressure. + echo "[*] Enabling jumbo frames (MTU 9000) on ${ETH_IFACE}..." + sudo ip link set dev "${ETH_IFACE}" mtu 9000 2>/dev/null || echo "Note: MTU 9000 not supported by NIC/driver, keeping default." + # Configure Ethernet Camera LAN echo "[1/2] Configuring Camera LAN on ${ETH_IFACE}..." sudo nmcli connection delete "Speedcamera-CameraLAN" 2>/dev/null || true @@ -50,7 +55,8 @@ EOF' autoconnect yes \ ipv4.method manual \ ipv4.addresses 192.168.1.100/24 \ - ipv4.never-default yes + ipv4.never-default yes \ + 802-3-ethernet.mtu 9000 sudo nmcli connection up "Speedcamera-CameraLAN" 2>/dev/null || echo "Note: Ethernet link active when camera cable is connected." # Configure Wi-Fi Hotspot AP From 13be116a7dc2ab0702682176fe2cc6d86f910a0c Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Sun, 16 Aug 2026 15:19:18 +0200 Subject: [PATCH 32/65] fix: update strobe configuration for flash synchronization and improve logging --- headless-rust/src/camera/mod.rs | 37 +++++++++++++++++++-------------- 1 file changed, 21 insertions(+), 16 deletions(-) diff --git a/headless-rust/src/camera/mod.rs b/headless-rust/src/camera/mod.rs index 309f994..dba72ab 100644 --- a/headless-rust/src/camera/mod.rs +++ b/headless-rust/src/camera/mod.rs @@ -1046,13 +1046,14 @@ impl CameraService { // ── Shared Helper Functions ──────────────────────────────────────────────── - /// Configure Line1 as strobe output, matching electronbun behavior. + /// Configure Line1 as strobe output for flash synchronization. /// - /// Uses LineSource=ExposureActive so the flash fires ONLY during the - /// exposure window of a triggered frame. StrobeEnable/StrobeLineDuration - /// are intentionally NOT set: on Hikrobot cameras, enabling StrobeEnable - /// with a duration makes the line free-run on its own timer, causing the - /// flash to strobe continuously regardless of trigger state. + /// 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; @@ -1063,23 +1064,28 @@ impl CameraService { Self::set_feature_str_internal(cam, "LineSelector", "Line1"); Self::set_feature_str_internal(cam, "LineMode", "Strobe"); - // Prefer ExposureActive to limit flash strictly to the exposure window - 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", "ExposureStartActive") { + // 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); - // Ensure the free-running strobe timer is OFF — LineSource drives the pulse. + // Enable the strobe subsystem for controlled pulse generation if Self::is_feature_available_internal(cam, "StrobeEnable") { - if !Self::set_feature_bool_internal(cam, "StrobeEnable", false) { - Self::set_feature_int_internal(cam, "StrobeEnable", 0); + if !Self::set_feature_bool_internal(cam, "StrobeEnable", true) { + Self::set_feature_int_internal(cam, "StrobeEnable", 1); } } - tracing::info!("[camera] Strobe configured on Line1 (LineSource=ExposureActive, StrobeEnable=false)"); + 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. @@ -1087,8 +1093,7 @@ impl CameraService { if cam.is_null() { return; } - // Disable strobe timer; LineSource=ExposureActive alone won't fire - // without exposures, but belt-and-braces for preview mode. + // 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"); } From 1608dfdfb14684d83f65f91e654d2bcf275a1269 Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Sun, 16 Aug 2026 15:29:47 +0200 Subject: [PATCH 33/65] fix: implement GenICam trigger mode configuration and ensure proper handling of frame rate in triggered mode --- electronbun/src/bun/industrial-camera.ts | 148 ++++++++++++++++++----- 1 file changed, 120 insertions(+), 28 deletions(-) diff --git a/electronbun/src/bun/industrial-camera.ts b/electronbun/src/bun/industrial-camera.ts index 808745b..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; } @@ -268,7 +361,7 @@ 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 */ } @@ -363,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 */ } @@ -379,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") { @@ -389,17 +485,13 @@ export function stopSetupStream() { try { camera.setExposureTime(Number(settings.cameraExposure) || 5000); } catch { /* ignore */ } } - // Restore configured frame rate - if (settings.frameRate) { - try { - camera.setBooleanFeature("AcquisitionFrameRateEnable", true); - camera.setFrameRate(Number(settings.frameRate)); - } catch { /* ignore */ } - } else { - try { - camera.setBooleanFeature("AcquisitionFrameRateEnable", false); - } 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 */ } } From d97d12317f5fcc0cb3f121ff8ba59387f94e44a3 Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Sun, 16 Aug 2026 15:43:27 +0200 Subject: [PATCH 34/65] feat: add ConnectionIndicator component and integrate it into NavigationMenu --- .../src/components/ConnectionIndicator.tsx | 32 +++++++++++++++++++ .../src/components/NavigationMenu.tsx | 5 +++ 2 files changed, 37 insertions(+) create mode 100644 headless-rust/frontend/src/components/ConnectionIndicator.tsx diff --git a/headless-rust/frontend/src/components/ConnectionIndicator.tsx b/headless-rust/frontend/src/components/ConnectionIndicator.tsx new file mode 100644 index 0000000..42c86f8 --- /dev/null +++ b/headless-rust/frontend/src/components/ConnectionIndicator.tsx @@ -0,0 +1,32 @@ +import { useState, useEffect } 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"; + +export function ConnectionIndicator() { + const [isConnected, setIsConnected] = useState(true); + + useBackendEvent("connectionChange", (connected) => { + setIsConnected(connected as boolean); + }); + + return ( +
+ + {isConnected ? "Connected" : "Reconnecting..."} +
+ ); +} diff --git a/headless-rust/frontend/src/components/NavigationMenu.tsx b/headless-rust/frontend/src/components/NavigationMenu.tsx index 72efed8..48f56b1 100644 --- a/headless-rust/frontend/src/components/NavigationMenu.tsx +++ b/headless-rust/frontend/src/components/NavigationMenu.tsx @@ -3,6 +3,7 @@ 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: "/" }, @@ -68,6 +69,10 @@ export function NavigationMenu({ className }: NavigationMenuProps) { Laps
+ +
+ +
); } From 6d50b8d33fe32cfd138992a9ba23785545a9b8b4 Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Sun, 16 Aug 2026 15:44:00 +0200 Subject: [PATCH 35/65] fix: reorder network configuration steps and enhance Wi-Fi performance by blocking Bluetooth --- headless-rust/scripts/setup-network.sh | 41 +++++++++++++++----------- 1 file changed, 23 insertions(+), 18 deletions(-) diff --git a/headless-rust/scripts/setup-network.sh b/headless-rust/scripts/setup-network.sh index 9174e0f..175307b 100755 --- a/headless-rust/scripts/setup-network.sh +++ b/headless-rust/scripts/setup-network.sh @@ -46,21 +46,8 @@ EOF' echo "[*] Enabling jumbo frames (MTU 9000) on ${ETH_IFACE}..." sudo ip link set dev "${ETH_IFACE}" mtu 9000 2>/dev/null || echo "Note: MTU 9000 not supported by NIC/driver, keeping default." - # Configure Ethernet Camera LAN - echo "[1/2] Configuring Camera LAN on ${ETH_IFACE}..." - sudo nmcli connection delete "Speedcamera-CameraLAN" 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 - sudo nmcli connection up "Speedcamera-CameraLAN" 2>/dev/null || echo "Note: Ethernet link active when camera cable is connected." - # Configure Wi-Fi Hotspot AP - echo "[2/2] Configuring Wi-Fi Hotspot AP on ${WIFI_IFACE}..." + echo "[1/2] Configuring Wi-Fi Hotspot AP on ${WIFI_IFACE}..." SSID="speedcamera" PASS="speedcamerapass" sudo nmcli connection delete "Speedcamera-Hotspot" 2>/dev/null || true @@ -78,10 +65,27 @@ EOF' wifi-sec.psk "${PASS}" sudo nmcli connection up "Speedcamera-Hotspot" 2>/dev/null || echo "Note: Hotspot initialized." + # Configure Ethernet Camera LAN + echo "[2/2] Configuring Camera LAN on ${ETH_IFACE}..." + sudo nmcli connection delete "Speedcamera-CameraLAN" 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 + sudo nmcli connection up "Speedcamera-CameraLAN" 2>/dev/null || echo "Note: Ethernet link active when camera cable is connected." + # Disable Wi-Fi power saving on AP interface to eliminate latency spikes and disconnects echo "[*] Disabling Wi-Fi power saving on ${WIFI_IFACE}..." sudo iw dev "${WIFI_IFACE}" set power_save off 2>/dev/null || sudo iwconfig "${WIFI_IFACE}" power off 2>/dev/null || true + # Block Bluetooth to free 2.4GHz spectrum and internal resources for Wi-Fi + echo "[*] Blocking Bluetooth to improve Wi-Fi performance..." + sudo rfkill block bluetooth 2>/dev/null || true + echo "" echo "=========================================================" echo " Field Mode Active!" @@ -122,13 +126,14 @@ EOF' dhcp|reset) echo ">>> Reverting Ethernet and Wi-Fi to standard DHCP..." - 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 + 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." ;; From 929fc8b204ae06f130ca9313673ddee7e695f3c6 Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Sun, 16 Aug 2026 15:48:25 +0200 Subject: [PATCH 36/65] fix: add HUP trap to prevent script termination on hangup --- headless-rust/scripts/setup-network.sh | 1 + 1 file changed, 1 insertion(+) diff --git a/headless-rust/scripts/setup-network.sh b/headless-rust/scripts/setup-network.sh index 175307b..a5da3a2 100755 --- a/headless-rust/scripts/setup-network.sh +++ b/headless-rust/scripts/setup-network.sh @@ -1,5 +1,6 @@ #!/usr/bin/env bash set -e +trap '' HUP MODE="${1:-status}" From 6faac4d011d2d4a6429197d721b8fa6c49144c9f Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Sun, 16 Aug 2026 22:31:06 +0200 Subject: [PATCH 37/65] fix: add diagnostics output to .gitignore --- headless-rust/.gitignore | 3 +++ 1 file changed, 3 insertions(+) diff --git a/headless-rust/.gitignore b/headless-rust/.gitignore index 84593dd..e96f1b3 100644 --- a/headless-rust/.gitignore +++ b/headless-rust/.gitignore @@ -2,6 +2,9 @@ # will have compiled files and executables /target/ +# Diagnostics +/diagnostics-output* + # Logs logs *.log From 7900cb578c7ba7e8f4e4bbe40b72f6a6a9f351fe Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Sun, 16 Aug 2026 22:31:14 +0200 Subject: [PATCH 38/65] feat: add diagnostic commands to package.json for enhanced troubleshooting --- headless-rust/package.json | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/headless-rust/package.json b/headless-rust/package.json index 966ff9a..2e39c62 100644 --- a/headless-rust/package.json +++ b/headless-rust/package.json @@ -14,6 +14,12 @@ "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": { From 4ba52f00d9fa282dac0f7ccfbc4138ee2f2bd6ac Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Sun, 16 Aug 2026 22:31:36 +0200 Subject: [PATCH 39/65] feat: Add diagnostic probes and scenarios for network stability and performance testing - Implement LatencyProbe for measuring round-trip time (RTT) and packet loss. - Create PiKernelProbe to gather system and network statistics from Raspberry Pi. - Develop WsRpcProbe for monitoring WebSocket RPC calls and push events. - Introduce baseline scenario to assess network stability over a defined duration. - Add freeze reproducer scenario to test Wi-Fi idle freeze and recovery. - Implement GigE Wi-Fi contention scenario to analyze network performance under load. - Create violation stress scenario to evaluate the impact of storage writeback on network latency. - Add SSH client for executing remote commands and scripts on the Raspberry Pi. --- .../diagnostics/analyzer/report-generator.ts | 156 ++++++++++ .../diagnostics/analyzer/rule-engine.ts | 238 +++++++++++++++ headless-rust/diagnostics/cli.ts | 232 +++++++++++++++ headless-rust/diagnostics/config.ts | 122 ++++++++ headless-rust/diagnostics/pi-probe.sh | 143 +++++++++ .../diagnostics/probes/http-probe.ts | 116 ++++++++ .../diagnostics/probes/latency-probe.ts | 179 +++++++++++ .../diagnostics/probes/pi-kernel-probe.ts | 144 +++++++++ .../diagnostics/probes/ws-rpc-probe.ts | 277 ++++++++++++++++++ .../diagnostics/scenarios/baseline.ts | 104 +++++++ .../scenarios/freeze-reproducer.ts | 125 ++++++++ .../scenarios/gige-wifi-contention.ts | 83 ++++++ .../diagnostics/scenarios/violation-stress.ts | 103 +++++++ headless-rust/diagnostics/ssh-client.ts | 214 ++++++++++++++ 14 files changed, 2236 insertions(+) create mode 100644 headless-rust/diagnostics/analyzer/report-generator.ts create mode 100644 headless-rust/diagnostics/analyzer/rule-engine.ts create mode 100755 headless-rust/diagnostics/cli.ts create mode 100644 headless-rust/diagnostics/config.ts create mode 100755 headless-rust/diagnostics/pi-probe.sh create mode 100644 headless-rust/diagnostics/probes/http-probe.ts create mode 100644 headless-rust/diagnostics/probes/latency-probe.ts create mode 100644 headless-rust/diagnostics/probes/pi-kernel-probe.ts create mode 100644 headless-rust/diagnostics/probes/ws-rpc-probe.ts create mode 100644 headless-rust/diagnostics/scenarios/baseline.ts create mode 100644 headless-rust/diagnostics/scenarios/freeze-reproducer.ts create mode 100644 headless-rust/diagnostics/scenarios/gige-wifi-contention.ts create mode 100644 headless-rust/diagnostics/scenarios/violation-stress.ts create mode 100644 headless-rust/diagnostics/ssh-client.ts 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..58aae56 --- /dev/null +++ b/headless-rust/diagnostics/analyzer/rule-engine.ts @@ -0,0 +1,238 @@ +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 to keep connection active", + "sudo nmcli connection modify 'Speedcamera-Hotspot' 802-11-wireless.powersave 2", + ], + }, + }); + } + + // =========================================================================== + // 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, but restore default socket buffer sizes (rmem_default / wmem_default = 212KB) for general TCP/Wi-Fi sockets.", + commands: [ + "# Restore sensible default socket buffers while keeping max limits for GigE camera", + "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..c5a1c98 --- /dev/null +++ b/headless-rust/diagnostics/cli.ts @@ -0,0 +1,232 @@ +#!/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 ===" + sudo bash -c 'cat > /etc/sysctl.d/60-speedcamera-optimized.conf </dev/null || sudo sysctl --system + + echo "=== 4. Optimizing NetworkManager Hotspot Connection ===" + sudo nmcli connection modify "Speedcamera-Hotspot" 802-11-wireless.powersave 2 802-11-wireless.channel 6 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..fb68b7b --- /dev/null +++ b/headless-rust/diagnostics/probes/ws-rpc-probe.ts @@ -0,0 +1,277 @@ +import type { DiagConfig } from "../config"; + +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 ws: WebSocket | null = null; + private isRunning = false; + private reqIdCounter = 1000; + private pendingCalls = new Map(); + 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.ws && this.ws.readyState === WebSocket.OPEN) { + 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; + } + for (const [, pending] of this.pendingCalls) { + clearTimeout(pending.timeoutTimer); + } + this.pendingCalls.clear(); + + if (this.ws) { + try { + this.ws.close(); + } catch (_) {} + this.ws = null; + } + } + + public getStats(): WsRpcStats { + const totalCalls = this.completedCalls.length + this.pendingCalls.size; + 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) + .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.ws !== null && this.ws.readyState === WebSocket.OPEN, + 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 ws = new WebSocket(this.config.wsUrl); + this.ws = ws; + + let resolved = false; + const connectTimer = setTimeout(() => { + if (!resolved) { + resolved = true; + resolve(false); + } + }, 4000); + + ws.onopen = () => { + if (!resolved) { + resolved = true; + clearTimeout(connectTimer); + resolve(true); + } + if (this.onUpdateCallback) this.onUpdateCallback(); + }; + + ws.onmessage = (event) => { + this.handleMessage(event.data); + }; + + ws.onerror = () => { + if (!resolved) { + resolved = true; + clearTimeout(connectTimer); + resolve(false); + } + }; + + ws.onclose = () => { + this.disconnects++; + if (this.isRunning) { + // Auto reconnect after 1s + setTimeout(() => { + if (this.isRunning) void this.connect(); + }, 1000); + } + if (this.onUpdateCallback) this.onUpdateCallback(); + }; + } catch (_) { + resolve(false); + } + }); + } + + private sendRpc(method: string, params: any): number { + const id = ++this.reqIdCounter; + const now = Date.now(); + + const record: RpcCallRecord = { + id, + method, + sentAt: now, + timedOut: false, + }; + + // RPC timeout after 5000ms + const timeoutTimer = setTimeout(() => { + if (this.pendingCalls.has(id)) { + const pending = this.pendingCalls.get(id)!; + this.pendingCalls.delete(id); + pending.record.timedOut = true; + pending.record.rttMs = 5000; + this.completedCalls.push(pending.record); + if (this.onUpdateCallback) this.onUpdateCallback(); + } + }, 5000); + + this.pendingCalls.set(id, { record, timeoutTimer }); + + try { + this.ws?.send(JSON.stringify({ id, method, params })); + } catch (err: any) { + clearTimeout(timeoutTimer); + this.pendingCalls.delete(id); + record.error = err.message; + this.completedCalls.push(record); + } + + return id; + } + + private handleMessage(data: any) { + const now = Date.now(); + try { + const msg = typeof data === "string" ? JSON.parse(data) : JSON.parse(data.toString()); + + // Case 1: RPC Response + if (msg.id !== undefined && this.pendingCalls.has(msg.id)) { + const pending = this.pendingCalls.get(msg.id)!; + this.pendingCalls.delete(msg.id); + clearTimeout(pending.timeoutTimer); + + pending.record.receivedAt = now; + pending.record.rttMs = Math.max(0, now - pending.record.sentAt); + if (msg.error) { + pending.record.error = String(msg.error); + } + this.completedCalls.push(pending.record); + } + + // Case 2: Server Push Event + if (msg.event) { + const delta = this.lastPushTimestamp > 0 ? now - this.lastPushTimestamp : 0; + // If delta < 40ms and previous event had a gap > 1500ms, mark as burst! + const isBurst = delta < 40 && this.pushEvents.length > 0 && (this.pushEvents[this.pushEvents.length - 1].deltaFromPrevMs > 1500); + + this.pushEvents.push({ + event: msg.event, + timestamp: now, + deltaFromPrevMs: delta, + isBurst, + }); + this.lastPushTimestamp = now; + } + } catch (_) {} + + 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 (_) {} + } +} From 44c68b4f03eb4bd279ac72a2bf6816d516e1db1e Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Sun, 16 Aug 2026 22:31:59 +0200 Subject: [PATCH 40/65] feat: Add ping and heartbeat response handling in WebSocket RPC --- headless-rust/src/web/ws.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/headless-rust/src/web/ws.rs b/headless-rust/src/web/ws.rs index aeb0a5c..fc4653a 100644 --- a/headless-rust/src/web/ws.rs +++ b/headless-rust/src/web/ws.rs @@ -87,6 +87,15 @@ pub fn ws_rpc( match incoming { Some(Ok(Message::Text(text))) => { if let Ok(req) = serde_json::from_str::(&text) { + if req.method == "ping" || req.method == "heartbeat" { + let resp = json!({ + "id": req.id, + "result": { "pong": true, "timestamp": chrono::Utc::now().timestamp_millis() } + }); + let _ = out_tx.send(Message::Text(resp.to_string())).await; + continue; + } + let ctx_clone = ctx.clone(); let out_tx_clone = out_tx.clone(); // Handle RPC asynchronously in independent task to prevent blocking the select loop From 7ed83f634e177aadde26e99f5fc182f3332bdecd Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Sun, 16 Aug 2026 22:32:03 +0200 Subject: [PATCH 41/65] feat: Implement heartbeat mechanism for WebSocket connection stability --- headless-rust/frontend/src/lib/rpc.ts | 38 +++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/headless-rust/frontend/src/lib/rpc.ts b/headless-rust/frontend/src/lib/rpc.ts index f015b2d..ebdd5c5 100644 --- a/headless-rust/frontend/src/lib/rpc.ts +++ b/headless-rust/frontend/src/lib/rpc.ts @@ -36,6 +36,10 @@ class WebSocketRpcClient { private listeners = new Map>(); + private heartbeatInterval: ReturnType | null = null; + private lastLatencyMs: number | null = null; + private missedHeartbeats = 0; + constructor() { this.connect(); } @@ -47,6 +51,35 @@ class WebSocketRpcClient { return `${protocol}//${host}/ws/rpc`; } + private startHeartbeat() { + this.stopHeartbeat(); + // 1000ms active heartbeat forces the client Wi-Fi chipset out of 802.11 power-save sleep + // and continuously drains any buffered packets in the AP DTIM queue. + this.heartbeatInterval = setInterval(async () => { + if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return; + const start = performance.now(); + try { + await this.call("ping", {}); + const rtt = Math.round(performance.now() - start); + this.lastLatencyMs = rtt; + this.missedHeartbeats = 0; + this.emit("heartbeat" as any, { connected: true, latencyMs: rtt, degraded: rtt > 250 }); + } catch (_) { + this.missedHeartbeats++; + if (this.missedHeartbeats >= 2) { + this.emit("heartbeat" as any, { connected: false, latencyMs: null, degraded: true }); + } + } + }, 1000); + } + + private stopHeartbeat() { + if (this.heartbeatInterval) { + clearInterval(this.heartbeatInterval); + this.heartbeatInterval = null; + } + } + public connect() { if (typeof window === "undefined" || this.isConnecting) return; if (this.ws && (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING)) return; @@ -62,7 +95,9 @@ class WebSocketRpcClient { console.log("[rpc-client] Connected to speedcamera daemon"); this.isConnecting = false; this.reconnectDelay = 500; + this.missedHeartbeats = 0; this.emit("connectionChange", true); + this.startHeartbeat(); // Flush any queued messages while (this.messageQueue.length > 0) { @@ -109,8 +144,10 @@ class WebSocketRpcClient { ws.onclose = (event) => { console.log(`[rpc-client] Disconnected (code: ${event.code}). Reconnecting in ${this.reconnectDelay}ms...`); this.isConnecting = false; + this.stopHeartbeat(); this.ws = null; this.emit("connectionChange", false); + this.emit("heartbeat" as any, { connected: false, latencyMs: null, degraded: true }); if (!this.isExplicitlyClosed && !this.reconnectTimeout) { this.reconnectTimeout = setTimeout(() => { @@ -122,6 +159,7 @@ class WebSocketRpcClient { }; } catch (err) { this.isConnecting = false; + this.stopHeartbeat(); console.error("[rpc-client] Failed to create WebSocket connection:", err); if (!this.reconnectTimeout) { this.reconnectTimeout = setTimeout(() => { From f0ea56da226e59c86aac8605aa243d4b90bef1ca Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Sun, 16 Aug 2026 22:32:10 +0200 Subject: [PATCH 42/65] feat: Enhance ConnectionIndicator with latency and degradation handling --- .../src/components/ConnectionIndicator.tsx | 49 ++++++++++++++++--- .../src/components/LastCapturedImage.tsx | 6 --- 2 files changed, 42 insertions(+), 13 deletions(-) diff --git a/headless-rust/frontend/src/components/ConnectionIndicator.tsx b/headless-rust/frontend/src/components/ConnectionIndicator.tsx index 42c86f8..21e4c95 100644 --- a/headless-rust/frontend/src/components/ConnectionIndicator.tsx +++ b/headless-rust/frontend/src/components/ConnectionIndicator.tsx @@ -1,32 +1,67 @@ -import { useState, useEffect } from "react"; +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 (
- {isConnected ? "Connected" : "Reconnecting..."} + {getStatusText()}
); } diff --git a/headless-rust/frontend/src/components/LastCapturedImage.tsx b/headless-rust/frontend/src/components/LastCapturedImage.tsx index 1a6b42d..6bd0b44 100644 --- a/headless-rust/frontend/src/components/LastCapturedImage.tsx +++ b/headless-rust/frontend/src/components/LastCapturedImage.tsx @@ -17,12 +17,6 @@ export function LastCapturedImage() { .catch(() => setImageSrc(null)); }; - useBackendEvent("violation", (v) => { - if (v && v.imagePath) { - loadImage(v.imagePath); - } - }); - useEffect(() => { if (lastViolation && lastViolation.imagePath) { loadImage(lastViolation.imagePath); From def0027d5c960b8d381f9103155e0476568faeec Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Sun, 16 Aug 2026 22:32:14 +0200 Subject: [PATCH 43/65] feat: Optimize GigE Vision socket buffer settings and disable Wi-Fi power-save globally --- headless-rust/scripts/setup-network.sh | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/headless-rust/scripts/setup-network.sh b/headless-rust/scripts/setup-network.sh index a5da3a2..808cb66 100755 --- a/headless-rust/scripts/setup-network.sh +++ b/headless-rust/scripts/setup-network.sh @@ -31,14 +31,21 @@ case "$MODE" in echo " NOTE: In this mode, Pi operates standalone/offline." echo "" - # Apply GigE Vision kernel socket buffer optimizations - echo "[*] Applying GigE Vision network socket buffer optimizations (128MB)..." + # Apply GigE Vision kernel socket buffer optimizations without causing Wi-Fi bufferbloat + echo "[*] Applying optimized network socket buffer configuration (128MB max, clean TCP defaults)..." sudo bash -c 'cat > /etc/sysctl.d/60-gige-camera.conf </dev/null || sudo sysctl --system 2>/dev/null || true @@ -51,6 +58,14 @@ EOF' echo "[1/2] Configuring Wi-Fi Hotspot AP on ${WIFI_IFACE}..." SSID="speedcamera" PASS="speedcamerapass" + + # Ensure NetworkManager globally disables Wi-Fi power-save on all connections + sudo mkdir -p /etc/NetworkManager/conf.d + sudo bash -c 'cat > /etc/NetworkManager/conf.d/default-wifi-powersave-off.conf </dev/null || true sudo nmcli connection delete "Speedcamera-ClientWiFi" 2>/dev/null || true sudo nmcli connection add type wifi \ @@ -60,6 +75,8 @@ EOF' ssid "${SSID}" \ mode ap \ 802-11-wireless.band bg \ + 802-11-wireless.channel 6 \ + 802-11-wireless.powersave 2 \ ipv4.method shared \ ipv4.addresses 192.168.4.1/24 \ wifi-sec.key-mgmt wpa-psk \ From 31d95d4d0cbfe6b3e60e1d12f7bdaf749adb179f Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Sun, 16 Aug 2026 23:03:26 +0200 Subject: [PATCH 44/65] feat: Add Wi-Fi rescan before connection to ensure SSID visibility and avoid stale connections --- headless-rust/scripts/setup-network.sh | 2 ++ 1 file changed, 2 insertions(+) diff --git a/headless-rust/scripts/setup-network.sh b/headless-rust/scripts/setup-network.sh index 808cb66..cb779b5 100755 --- a/headless-rust/scripts/setup-network.sh +++ b/headless-rust/scripts/setup-network.sh @@ -128,6 +128,8 @@ EOF' sudo nmcli connection delete "Speedcamera-ClientWiFi" 2>/dev/null || true if [ -n "$WIFI_PASS" ]; then + # Scan before trying to connect, to ensure the SSID is visible and avoid stale connection issues + sudo nmcli dev wifi rescan sudo nmcli dev wifi connect "${WIFI_SSID}" password "${WIFI_PASS}" ifname "${WIFI_IFACE}" name "Speedcamera-ClientWiFi" else sudo nmcli dev wifi connect "${WIFI_SSID}" ifname "${WIFI_IFACE}" name "Speedcamera-ClientWiFi" From 76bcac66f5153577756b5b5bdd75ebbb3d2ffb6f Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Sun, 16 Aug 2026 23:06:34 +0200 Subject: [PATCH 45/65] feat: Refactor network setup script to modularize mode applications and enhance Wi-Fi connection handling --- headless-rust/scripts/setup-network.sh | 261 +++++++++++++++---------- 1 file changed, 156 insertions(+), 105 deletions(-) diff --git a/headless-rust/scripts/setup-network.sh b/headless-rust/scripts/setup-network.sh index cb779b5..a887054 100755 --- a/headless-rust/scripts/setup-network.sh +++ b/headless-rust/scripts/setup-network.sh @@ -23,17 +23,16 @@ if [ "$MODE" != "status" ]; then sudo -v || { echo "Error: Sudo privileges required to change network configuration." >&2; exit 1; } fi -case "$MODE" in - field|ap) - echo ">>> Applying FIELD MODE (Standalone Offline Dual-Subnet):" - echo " 1. Camera LAN (${ETH_IFACE}) -> Static IP 192.168.1.100/24" - echo " 2. Hotspot AP (${WIFI_IFACE}) -> Static IP 192.168.4.1/24 (SSID: speedcamera)" - echo " NOTE: In this mode, Pi operates standalone/offline." - echo "" - - # Apply GigE Vision kernel socket buffer optimizations without causing Wi-Fi bufferbloat - echo "[*] Applying optimized network socket buffer configuration (128MB max, clean TCP defaults)..." - sudo bash -c 'cat > /etc/sysctl.d/60-gige-camera.conf <>> Applying FIELD MODE (Standalone Offline Dual-Subnet):" + echo " 1. Camera LAN (${ETH_IFACE}) -> Static IP 192.168.1.100/24" + echo " 2. Hotspot AP (${WIFI_IFACE}) -> Static IP 192.168.4.1/24 (SSID: speedcamera)" + echo " NOTE: In this mode, Pi operates standalone/offline." + echo "" + + # Apply GigE Vision kernel socket buffer optimizations without causing Wi-Fi bufferbloat + echo "[*] Applying optimized network socket buffer configuration (128MB max, clean TCP defaults)..." + 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 — critical for GigE Vision throughput. - # Larger MTU = fewer packets = fewer interrupts = less CPU/softirq pressure. - echo "[*] Enabling jumbo frames (MTU 9000) on ${ETH_IFACE}..." - sudo ip link set dev "${ETH_IFACE}" mtu 9000 2>/dev/null || echo "Note: MTU 9000 not supported by NIC/driver, keeping default." - - # Configure Wi-Fi Hotspot AP - echo "[1/2] Configuring Wi-Fi Hotspot AP on ${WIFI_IFACE}..." - SSID="speedcamera" - PASS="speedcamerapass" - - # Ensure NetworkManager globally disables Wi-Fi power-save on all connections - sudo mkdir -p /etc/NetworkManager/conf.d - sudo bash -c 'cat > /etc/NetworkManager/conf.d/default-wifi-powersave-off.conf </dev/null || sudo sysctl --system 2>/dev/null || true + + # Enable jumbo frames on camera NIC — critical for GigE Vision throughput. + # Larger MTU = fewer packets = fewer interrupts = less CPU/softirq pressure. + echo "[*] Enabling jumbo frames (MTU 9000) on ${ETH_IFACE}..." + sudo ip link set dev "${ETH_IFACE}" mtu 9000 2>/dev/null || echo "Note: MTU 9000 not supported by NIC/driver, keeping default." + + # Configure Wi-Fi Hotspot AP + echo "[1/2] Configuring Wi-Fi Hotspot AP on ${WIFI_IFACE}..." + SSID="speedcamera" + PASS="speedcamerapass" + + # Ensure NetworkManager globally disables Wi-Fi power-save on all connections + sudo mkdir -p /etc/NetworkManager/conf.d + sudo bash -c 'cat > /etc/NetworkManager/conf.d/default-wifi-powersave-off.conf </dev/null || true + sudo nmcli connection delete "Speedcamera-Hotspot" 2>/dev/null || true + sudo nmcli connection delete "Speedcamera-ClientWiFi" 2>/dev/null || true + 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 \ + ipv4.method shared \ + ipv4.addresses 192.168.4.1/24 \ + wifi-sec.key-mgmt wpa-psk \ + wifi-sec.psk "${PASS}" + sudo nmcli connection up "Speedcamera-Hotspot" 2>/dev/null || echo "Note: Hotspot initialized." + + # Configure Ethernet Camera LAN + echo "[2/2] Configuring Camera LAN on ${ETH_IFACE}..." + sudo nmcli connection delete "Speedcamera-CameraLAN" 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 + sudo nmcli connection up "Speedcamera-CameraLAN" 2>/dev/null || echo "Note: Ethernet link active when camera cable is connected." + + # Disable Wi-Fi power saving on AP interface to eliminate latency spikes and disconnects + echo "[*] Disabling Wi-Fi power saving on ${WIFI_IFACE}..." + sudo iw dev "${WIFI_IFACE}" set power_save off 2>/dev/null || sudo iwconfig "${WIFI_IFACE}" power off 2>/dev/null || true + + # Block Bluetooth to free 2.4GHz spectrum and internal resources for Wi-Fi + echo "[*] Blocking Bluetooth to improve Wi-Fi performance..." + sudo rfkill block bluetooth 2>/dev/null || true + + echo "" + echo "=========================================================" + echo " Field Mode Active!" + echo " • Wi-Fi Hotspot: SSID '${SSID}' (Password: '${PASS}')" + echo " • Web UI: http://192.168.4.1:3000" + echo " • Camera LAN: http://192.168.1.100:3000" + echo "=========================================================" +} + +apply_dhcp_mode() { + echo ">>> Reverting Ethernet and Wi-Fi to standard DHCP..." + + 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." +} + +apply_internet_mode() { + local WIFI_SSID="$1" + local WIFI_PASS="$2" + if [ -z "$WIFI_SSID" ]; then + echo "Usage: $0 internet [Wi-Fi-Password]" + echo "Example: $0 internet MyHomeWiFi SecretPassword123" + exit 1 + fi + + # Record previous mode before changing configuration so we can revert if needed + local PREV_MODE="field" + if nmcli -t -f NAME connection show --active 2>/dev/null | grep -qx "Speedcamera-Ethernet-DHCP"; then + PREV_MODE="dhcp" + elif nmcli -t -f NAME connection show 2>/dev/null | grep -qx "Speedcamera-Ethernet-DHCP"; then + PREV_MODE="dhcp" + else + PREV_MODE="field" + fi + + revert_mode() { + local reason="$1" + echo "" >&2 + echo "[-] Error: ${reason}" >&2 + echo "[!] Reverting to ${PREV_MODE} mode to preserve connectivity..." >&2 + echo "" >&2 sudo nmcli connection delete "Speedcamera-ClientWiFi" 2>/dev/null || true - 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 \ - ipv4.method shared \ - ipv4.addresses 192.168.4.1/24 \ - wifi-sec.key-mgmt wpa-psk \ - wifi-sec.psk "${PASS}" - sudo nmcli connection up "Speedcamera-Hotspot" 2>/dev/null || echo "Note: Hotspot initialized." - - # Configure Ethernet Camera LAN - echo "[2/2] Configuring Camera LAN on ${ETH_IFACE}..." - sudo nmcli connection delete "Speedcamera-CameraLAN" 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 - sudo nmcli connection up "Speedcamera-CameraLAN" 2>/dev/null || echo "Note: Ethernet link active when camera cable is connected." - - # Disable Wi-Fi power saving on AP interface to eliminate latency spikes and disconnects - echo "[*] Disabling Wi-Fi power saving on ${WIFI_IFACE}..." - sudo iw dev "${WIFI_IFACE}" set power_save off 2>/dev/null || sudo iwconfig "${WIFI_IFACE}" power off 2>/dev/null || true - - # Block Bluetooth to free 2.4GHz spectrum and internal resources for Wi-Fi - echo "[*] Blocking Bluetooth to improve Wi-Fi performance..." - sudo rfkill block bluetooth 2>/dev/null || true + if [ "$PREV_MODE" = "dhcp" ]; then + apply_dhcp_mode + else + apply_field_mode + fi + } - echo "" - echo "=========================================================" - echo " Field Mode Active!" - echo " • Wi-Fi Hotspot: SSID '${SSID}' (Password: '${PASS}')" - echo " • Web UI: http://192.168.4.1:3000" - echo " • Camera LAN: http://192.168.1.100:3000" - echo "=========================================================" - ;; + echo ">>> Switching to INTERNET / CLIENT MODE (for updates/provisioning)..." + echo " Connecting ${WIFI_IFACE} to Wi-Fi SSID: ${WIFI_SSID}" - internet|client|wifi) - WIFI_SSID="$2" - WIFI_PASS="$3" - if [ -z "$WIFI_SSID" ]; then - echo "Usage: $0 internet [Wi-Fi-Password]" - echo "Example: $0 internet MyHomeWiFi SecretPassword123" - exit 1 + sudo nmcli connection delete "Speedcamera-Hotspot" 2>/dev/null || true + sudo nmcli connection delete "Speedcamera-ClientWiFi" 2>/dev/null || true + + local CONNECT_SUCCESS=0 + if [ -n "$WIFI_PASS" ]; then + # Scan before trying to connect, to ensure the SSID is visible and avoid stale connection issues + sudo nmcli dev wifi rescan 2>/dev/null || true + if sudo nmcli dev wifi connect "${WIFI_SSID}" password "${WIFI_PASS}" ifname "${WIFI_IFACE}" name "Speedcamera-ClientWiFi"; then + CONNECT_SUCCESS=1 fi - echo ">>> Switching to INTERNET / CLIENT MODE (for updates/provisioning)..." - echo " Connecting ${WIFI_IFACE} to Wi-Fi SSID: ${WIFI_SSID}" + else + if sudo nmcli dev wifi connect "${WIFI_SSID}" ifname "${WIFI_IFACE}" name "Speedcamera-ClientWiFi"; then + CONNECT_SUCCESS=1 + fi + fi - sudo nmcli connection delete "Speedcamera-Hotspot" 2>/dev/null || true - sudo nmcli connection delete "Speedcamera-ClientWiFi" 2>/dev/null || true + if [ "$CONNECT_SUCCESS" -ne 1 ]; then + revert_mode "Failed to connect to Wi-Fi network '${WIFI_SSID}'." + exit 1 + fi - if [ -n "$WIFI_PASS" ]; then - # Scan before trying to connect, to ensure the SSID is visible and avoid stale connection issues - sudo nmcli dev wifi rescan - sudo nmcli dev wifi connect "${WIFI_SSID}" password "${WIFI_PASS}" ifname "${WIFI_IFACE}" name "Speedcamera-ClientWiFi" - else - sudo nmcli dev wifi connect "${WIFI_SSID}" ifname "${WIFI_IFACE}" name "Speedcamera-ClientWiFi" - fi + echo "" + echo "[*] Connected to Wi-Fi '${WIFI_SSID}'. Waiting 5 seconds for DHCP lease / route assignment before connectivity check..." + sleep 5 - echo "" - echo ">>> Checking internet connectivity..." - if ping -c 2 -W 3 1.1.1.1 &>/dev/null; then - echo " Connected to Internet successfully!" - else - echo " Wi-Fi connected, but ping to 1.1.1.1 failed. Check gateway/DNS." - fi + echo ">>> Checking internet connectivity (pinging 1.1.1.1)..." + if ping -c 2 -W 3 1.1.1.1 &>/dev/null; then + echo " Connected to Internet successfully!" + else + revert_mode "Wi-Fi connected to '${WIFI_SSID}', but ping to 1.1.1.1 failed (no internet reachability)." + exit 1 + fi +} + +case "$MODE" in + field|ap) + apply_field_mode + ;; + + internet|client|wifi) + apply_internet_mode "$2" "$3" ;; dhcp|reset) - echo ">>> Reverting Ethernet and Wi-Fi to standard DHCP..." - - 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." + apply_dhcp_mode ;; status) From 02ba2625cff61243eca799bfe4ec56b083f55c7c Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Sun, 16 Aug 2026 23:35:29 +0200 Subject: [PATCH 46/65] feat: Implement armed state management and WebSocket integration for system status updates --- .../frontend/src/components/ArmingButton.tsx | 10 +- .../frontend/src/hooks/useSystemStateSync.ts | 8 +- headless-rust/frontend/src/lib/rpc.ts | 5 + headless-rust/frontend/src/routes/__root.tsx | 5 +- .../frontend/src/routes/violations.tsx | 1 + .../routes/violations/ExportImagesDialog.tsx | 191 ++++++++++++++---- headless-rust/frontend/src/shared/types.ts | 12 ++ .../frontend/src/stores/slices/systemSlice.ts | 43 +++- headless-rust/scripts/test-server.ts | 25 ++- headless-rust/src/main.rs | 12 +- headless-rust/src/web/mod.rs | 6 + headless-rust/src/web/routes.rs | 4 + headless-rust/src/web/rpc.rs | 18 ++ headless-rust/src/web/ws.rs | 34 +++- 14 files changed, 327 insertions(+), 47 deletions(-) diff --git a/headless-rust/frontend/src/components/ArmingButton.tsx b/headless-rust/frontend/src/components/ArmingButton.tsx index 071b056..fd8e828 100644 --- a/headless-rust/frontend/src/components/ArmingButton.tsx +++ b/headless-rust/frontend/src/components/ArmingButton.tsx @@ -14,7 +14,7 @@ const POST_ARM_DEBOUNCE_MS = 600; export function ArmingButton() { const systemState = useAppStore((s) => s.systemState); - const setSystemState = useAppStore((s) => s.setSystemState); + const setArmed = useAppStore((s) => s.setArmed); const connectedPort = useAppStore((s) => s.connectedPort); const cameraConnected = useAppStore((s) => s.cameraConnected); @@ -64,7 +64,7 @@ export function ArmingButton() { debounceTimerRef.current = setTimeout(() => { justArmedRef.current = false; }, POST_ARM_DEBOUNCE_MS); - setSystemState("ARMED"); + void setArmed(true); return; } @@ -74,7 +74,7 @@ export function ArmingButton() { }; rafRef.current = requestAnimationFrame(tick); - }, [systemState, setSystemState]); + }, [systemState, setArmed]); const handlePointerDown = useCallback(() => { if (systemState === "DISARMED") { @@ -86,9 +86,9 @@ export function ArmingButton() { // Ignore the click that fires right after a successful hold-to-arm if (justArmedRef.current) return; if (systemState === "ARMED") { - setSystemState("DISARMED"); + void setArmed(false); } - }, [systemState, setSystemState]); + }, [systemState, setArmed]); // Cleanup on unmount useEffect(() => { diff --git a/headless-rust/frontend/src/hooks/useSystemStateSync.ts b/headless-rust/frontend/src/hooks/useSystemStateSync.ts index bbc7915..dc4ece0 100644 --- a/headless-rust/frontend/src/hooks/useSystemStateSync.ts +++ b/headless-rust/frontend/src/hooks/useSystemStateSync.ts @@ -12,6 +12,7 @@ import { useAppStore } from "@/stores/useAppStore"; 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); @@ -19,13 +20,14 @@ export function useSystemStateSync() { useEffect(() => { if (conditionsMet) { - if (systemState === "PASSIVE") { - setSystemState("DISARMED"); + const targetState = isArmed ? "ARMED" : "DISARMED"; + if (systemState !== targetState) { + setSystemState(targetState); } } else { if (systemState !== "PASSIVE") { setSystemState("PASSIVE"); } } - }, [conditionsMet, systemState, setSystemState]); + }, [conditionsMet, isArmed, systemState, setSystemState]); } diff --git a/headless-rust/frontend/src/lib/rpc.ts b/headless-rust/frontend/src/lib/rpc.ts index ebdd5c5..429727f 100644 --- a/headless-rust/frontend/src/lib/rpc.ts +++ b/headless-rust/frontend/src/lib/rpc.ts @@ -253,6 +253,11 @@ class WebSocketRpcClient { 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"); diff --git a/headless-rust/frontend/src/routes/__root.tsx b/headless-rust/frontend/src/routes/__root.tsx index b739dbe..c403c8e 100644 --- a/headless-rust/frontend/src/routes/__root.tsx +++ b/headless-rust/frontend/src/routes/__root.tsx @@ -16,6 +16,7 @@ function Root() { 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); @@ -32,9 +33,10 @@ function Root() { }) .catch((err) => console.warn("[root] Failed to load settings:", err)); - // 2. Hydrate hardware connection states + // 2. Hydrate hardware and system armed states void refreshCameraStatus(); void refreshSerialStatus(); + void refreshArmedStatus(); void loadLapSettings(); void loadTeableState(); @@ -53,6 +55,7 @@ function Root() { setMaxSpeed, refreshCameraStatus, refreshSerialStatus, + refreshArmedStatus, loadLapSettings, loadTeableState, setLastViolation, diff --git a/headless-rust/frontend/src/routes/violations.tsx b/headless-rust/frontend/src/routes/violations.tsx index 865af7b..8085d9e 100644 --- a/headless-rust/frontend/src/routes/violations.tsx +++ b/headless-rust/frontend/src/routes/violations.tsx @@ -167,6 +167,7 @@ function ViolationsPage() { onOpenChange={setExportDialogOpen} selectedIds={[...v.selected]} pageViolationIds={v.violations.map((x) => 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 index d327016..fd533e8 100644 --- a/headless-rust/frontend/src/routes/violations/ExportImagesDialog.tsx +++ b/headless-rust/frontend/src/routes/violations/ExportImagesDialog.tsx @@ -1,14 +1,24 @@ import { useState } from "react"; import { toast } from "sonner"; -import { getRpc } from "@/lib/rpc"; +import { HugeiconsIcon } from "@hugeicons/react"; +import { Folder01Icon, Download01Icon } from "@hugeicons/core-free-icons"; import { Button } from "@/components/ui/button"; -import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog"; +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({ @@ -16,60 +26,173 @@ export function ExportImagesDialog({ onOpenChange, selectedIds, pageViolationIds, + violations = [], }: ExportImagesDialogProps) { const selectedCount = selectedIds.length; const pageViolationCount = pageViolationIds.length; - const [exportDir, setExportDir] = useState(""); + 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 (!exportDir.trim()) { - toast.error("Please enter an export directory"); + 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 { - const ids = selectedCount > 0 ? selectedIds : pageViolationIds; - const result = await getRpc().request.exportSkinnedImages({ - violationIds: ids, - targetDir: exportDir.trim(), - }); - toast.success(`Exported ${result.exported} images${result.failed ? `, ${result.failed} failed` : ""}`); - onOpenChange(false); - } catch { - toast.error("Failed to export images"); + 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 + + + Export Skinned Images + -

- {selectedCount > 0 - ? `Export ${selectedCount} selected violation(s) with Poliscan skin.` - : `Export all ${pageViolationCount} violations on this page with Poliscan skin.`} -

-
- - setExportDir(e.target.value)} - placeholder="/home/user/exports" - 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" - /> + +
+

+ {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/shared/types.ts b/headless-rust/frontend/src/shared/types.ts index 5644f11..bd6227c 100644 --- a/headless-rust/frontend/src/shared/types.ts +++ b/headless-rust/frontend/src/shared/types.ts @@ -329,6 +329,16 @@ export type SpeedcameraRPC = { 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; @@ -549,6 +559,8 @@ export type SpeedcameraRPC = { 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/systemSlice.ts b/headless-rust/frontend/src/stores/slices/systemSlice.ts index 8add0b7..a861c2e 100644 --- a/headless-rust/frontend/src/stores/slices/systemSlice.ts +++ b/headless-rust/frontend/src/stores/slices/systemSlice.ts @@ -1,20 +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 = (set) => ({ +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/scripts/test-server.ts b/headless-rust/scripts/test-server.ts index 00ca903..cb8754e 100755 --- a/headless-rust/scripts/test-server.ts +++ b/headless-rust/scripts/test-server.ts @@ -71,6 +71,7 @@ try { await new Promise((resolve, reject) => { let settingsOk = false; let violationsOk = false; + let armedOk = false; ws.onopen = () => { console.log("WebSocket connected successfully!"); @@ -78,6 +79,8 @@ try { ws.send(JSON.stringify({ id: 1, method: "getSettings", params: {} })); // Send RPC request for getViolations ws.send(JSON.stringify({ id: 2, method: "getViolations", params: { page: 1, limit: 10 } })); + // Send RPC request for getArmedState + ws.send(JSON.stringify({ id: 3, method: "getArmedState", params: {} })); }; ws.onmessage = (event) => { @@ -104,7 +107,27 @@ try { } } - if (settingsOk && violationsOk) { + if (data.id === 3) { + console.log("RPC getArmedState result:", data.result); + if (data.result && typeof data.result.armed === "boolean") { + // Now test setArmed + ws.send(JSON.stringify({ id: 4, method: "setArmed", params: { armed: true } })); + } else { + reject(new Error("Unexpected getArmedState response")); + } + } + + if (data.id === 4) { + console.log("RPC setArmed result:", data.result); + if (data.result && data.result.armed === true) { + armedOk = true; + console.log("SUCCESS: Armed RPC validated!"); + } else { + reject(new Error("Unexpected setArmed response")); + } + } + + if (settingsOk && violationsOk && armedOk) { ws.close(); resolve(); } diff --git a/headless-rust/src/main.rs b/headless-rust/src/main.rs index 9dfd8c7..fd1619d 100644 --- a/headless-rust/src/main.rs +++ b/headless-rust/src/main.rs @@ -90,6 +90,11 @@ async fn main() -> Result<(), rocket::Error> { } } + // ─── 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(); @@ -103,6 +108,11 @@ async fn main() -> Result<(), rocket::Error> { 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(); @@ -144,7 +154,7 @@ async fn main() -> Result<(), rocket::Error> { }); // Build and launch Rocket web server - let server = web::build_rocket(config, db, store, camera, serial, violation_tx); + let server = web::build_rocket(config, db, store, camera, serial, violation_tx, armed, armed_tx); server.launch().await?; Ok(()) diff --git a/headless-rust/src/web/mod.rs b/headless-rust/src/web/mod.rs index ec838db..6dabe64 100644 --- a/headless-rust/src/web/mod.rs +++ b/headless-rust/src/web/mod.rs @@ -37,6 +37,8 @@ impl Fairing for Cors { } } +use std::sync::atomic::AtomicBool; + pub fn build_rocket( config: AppConfig, db: Database, @@ -44,6 +46,8 @@ pub fn build_rocket( camera: Arc, serial: Arc, violation_tx: broadcast::Sender, + armed: Arc, + armed_tx: broadcast::Sender, ) -> Rocket { let (flash_tx, _) = broadcast::channel::(32); @@ -60,6 +64,8 @@ pub fn build_rocket( .manage(serial) .manage(flash_tx) .manage(violation_tx) + .manage(armed) + .manage(armed_tx) .mount( "/", rocket::routes![ diff --git a/headless-rust/src/web/routes.rs b/headless-rust/src/web/routes.rs index 43bbc5c..1b10f3e 100644 --- a/headless-rust/src/web/routes.rs +++ b/headless-rust/src/web/routes.rs @@ -11,10 +11,13 @@ use rocket::State; use serde_json::json; use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; + #[rocket::get("/api/health")] pub fn health( config: &State, camera: &State>, + armed: &State>, ) -> Json { Json(json!({ "status": "ok", @@ -22,6 +25,7 @@ pub fn health( "camera": camera.get_status(), "network": get_system_network_summary(), "mockMode": config.mock_mode, + "armed": armed.load(Ordering::SeqCst), })) } diff --git a/headless-rust/src/web/rpc.rs b/headless-rust/src/web/rpc.rs index 2c1fc02..d33d36b 100644 --- a/headless-rust/src/web/rpc.rs +++ b/headless-rust/src/web/rpc.rs @@ -39,6 +39,8 @@ pub struct RpcContext { 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 { @@ -295,6 +297,22 @@ async fn dispatch_method(ctx: &RpcContext, method: &str, params: Value) -> Resul 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 conn = ctx.db.lock(); diff --git a/headless-rust/src/web/ws.rs b/headless-rust/src/web/ws.rs index fc4653a..cd89184 100644 --- a/headless-rust/src/web/ws.rs +++ b/headless-rust/src/web/ws.rs @@ -12,6 +12,7 @@ use rocket_ws::{Channel, Message, WebSocket}; use serde_json::json; use std::sync::Arc; use std::time::Duration; +use std::sync::atomic::{AtomicBool, Ordering}; use tokio::sync::{broadcast, mpsc}; #[rocket::get("/ws/rpc")] @@ -23,6 +24,8 @@ pub fn ws_rpc( serial: &State>, flash_tx: &State>, violation_tx: &State>, + armed: &State>, + armed_tx: &State>, ) -> Channel<'static> { let ctx = Arc::new(RpcContext { db: (*db).clone(), @@ -32,6 +35,8 @@ pub fn ws_rpc( teable: TeableClient::new(), flash_tx: (*flash_tx).clone(), violation_tx: (*violation_tx).clone(), + armed: (*armed).clone(), + armed_tx: (*armed_tx).clone(), }); ws.channel(move |stream: DuplexStream| { @@ -69,12 +74,20 @@ pub fn ws_rpc( }); let _ = out_tx.send(Message::Text(init_serial.to_string())).await; + // Push initial armed status immediately + let init_armed = json!({ + "event": "armedStatus", + "payload": { "armed": ctx.armed.load(Ordering::SeqCst) } + }); + let _ = out_tx.send(Message::Text(init_armed.to_string())).await; + // Subscribe to all backend event channels 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(); // Heartbeat ping interval let mut ping_interval = tokio::time::interval(Duration::from_secs(15)); @@ -230,6 +243,23 @@ pub fn ws_rpc( Err(broadcast::error::RecvError::Closed) => break, } } + + // Armed status broadcast (drop on slow client) + res = armed_rx.recv() => { + match res { + Ok(is_armed) => { + let msg = json!({ + "event": "armedStatus", + "payload": { "armed": is_armed } + }); + let _ = out_tx.try_send(Message::Text(msg.to_string())); + } + Err(broadcast::error::RecvError::Lagged(n)) => { + tracing::debug!("[ws] Armed status broadcast lagged by {} messages", n); + } + Err(broadcast::error::RecvError::Closed) => break, + } + } } } @@ -252,6 +282,8 @@ pub fn ws_alias( serial: &State>, flash_tx: &State>, violation_tx: &State>, + armed: &State>, + armed_tx: &State>, ) -> Channel<'static> { - ws_rpc(ws, db, store, camera, serial, flash_tx, violation_tx) + ws_rpc(ws, db, store, camera, serial, flash_tx, violation_tx, armed, armed_tx) } From 1e5c79e6d8011e57cec5345fccbe6721b6083101 Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Sun, 16 Aug 2026 23:56:52 +0200 Subject: [PATCH 47/65] feat: Enhance lap and measurement slices with improved state handling and image path retrieval --- electronbun/src/stores/slices/lapSlice.ts | 28 ++- .../src/stores/slices/measurementSlice.ts | 30 +-- .../frontend/src/stores/slices/lapSlice.ts | 28 ++- .../src/stores/slices/measurementSlice.ts | 31 ++-- headless-rust/src/db/laps.rs | 42 +++++ headless-rust/src/models.rs | 22 ++- headless-rust/src/serial/mock.rs | 173 ++++++++++++++---- headless-rust/src/serial/protocol.rs | 6 +- headless-rust/src/storage/mod.rs | 8 +- headless-rust/src/web/rpc.rs | 26 ++- 10 files changed, 324 insertions(+), 70 deletions(-) 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/frontend/src/stores/slices/lapSlice.ts b/headless-rust/frontend/src/stores/slices/lapSlice.ts index 5900c39..e7542e3 100644 --- a/headless-rust/frontend/src/stores/slices/lapSlice.ts +++ b/headless-rust/frontend/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"; @@ -47,7 +48,7 @@ let lapSaving = false; // ─── Slice ──────────────────────────────────────────────────────────────────── export const createLapSlice: StateCreator< - LapSlice & CameraSlice & TeableSlice, + LapSlice & CameraSlice & TeableSlice & SystemSlice, [], [], LapSlice @@ -77,6 +78,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 @@ -98,6 +100,7 @@ export const createLapSlice: StateCreator< set({ lapState: "idle", currentSession: null, + lapTimingStartedAt: null, // Keep currentLaps so the UI can show the final session summary }); }, @@ -105,13 +108,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/headless-rust/frontend/src/stores/slices/measurementSlice.ts b/headless-rust/frontend/src/stores/slices/measurementSlice.ts index e8fa80a..d0d05dd 100644 --- a/headless-rust/frontend/src/stores/slices/measurementSlice.ts +++ b/headless-rust/frontend/src/stores/slices/measurementSlice.ts @@ -56,30 +56,37 @@ 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 }); } else if (payload.status === "OK") { set({ lastSpeed: payload.value, lastDirection: payload.direction }); } - // CONNECTED / DISCONNECTED handled by serialSlice indirectly via store }, }); diff --git a/headless-rust/src/db/laps.rs b/headless-rust/src/db/laps.rs index a5c3f4e..ba11eb5 100644 --- a/headless-rust/src/db/laps.rs +++ b/headless-rust/src/db/laps.rs @@ -170,6 +170,48 @@ fn get_laps_for_session(conn: &Connection, session_id: i64) -> Result> 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(()) diff --git a/headless-rust/src/models.rs b/headless-rust/src/models.rs index 8737ff6..56a572c 100644 --- a/headless-rust/src/models.rs +++ b/headless-rust/src/models.rs @@ -217,6 +217,22 @@ pub struct LapSessionWithLaps { 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 { @@ -224,6 +240,7 @@ pub struct SaveLapInput { 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, @@ -235,12 +252,15 @@ pub struct SaveLapInput { #[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, } @@ -284,7 +304,7 @@ pub enum SerialStatusPayload { #[serde(rename = "lapNumber")] lap_number: i64, #[serde(rename = "durationMs")] - duration_ms: i64, + duration_ms: f64, #[serde(rename = "speedAtStart")] speed_at_start: f64, #[serde(rename = "speedAtEnd")] diff --git a/headless-rust/src/serial/mock.rs b/headless-rust/src/serial/mock.rs index b0dd734..fe08121 100644 --- a/headless-rust/src/serial/mock.rs +++ b/headless-rust/src/serial/mock.rs @@ -1,65 +1,176 @@ use crate::models::{EspPongConfig, SerialStatusPayload}; +use serde_json::Value; use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::Arc; +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(5)).await; + 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 payload = if speed > 40.0 { - SerialStatusPayload::Speeding { - value: speed, - tolerance: 3.0, - direction: "forward".to_string(), - timestamp: now, + 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); } - } else { - SerialStatusPayload::Ok { - value: speed, - tolerance: 3.0, - direction: "forward".to_string(), - timestamp: now, + 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(payload); + 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 } + Self { running, state } } pub fn send_command(&self, json: &str, tx: &broadcast::Sender) { - if json.to_lowercase().contains("\"ping\"") { - 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: "single".to_string(), - lap_active: false, - lap_auto_flash: Some(true), - lap_dir_filter: "both".to_string(), - }, - }); + 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/protocol.rs b/headless-rust/src/serial/protocol.rs index 1010327..aa7452f 100644 --- a/headless-rust/src/serial/protocol.rs +++ b/headless-rust/src/serial/protocol.rs @@ -30,7 +30,7 @@ pub enum EspMessage { #[serde(rename = "lapNumber")] lap_number: i64, #[serde(rename = "durationMs")] - duration_ms: i64, + duration_ms: f64, #[serde(rename = "speedAtStart")] speed_at_start: f64, #[serde(rename = "speedAtEnd")] @@ -42,6 +42,8 @@ pub enum EspMessage { LapStopped, #[serde(rename = "configError")] ConfigError { message: String }, + #[serde(other)] + Unknown, } impl EspMessage { @@ -92,7 +94,7 @@ impl EspMessage { }), Self::LapWaiting => Some(SerialStatusPayload::LapWaiting), Self::LapStopped => Some(SerialStatusPayload::LapStopped), - Self::ConfigError { .. } => None, + Self::ConfigError { .. } | Self::Unknown => None, } } } diff --git a/headless-rust/src/storage/mod.rs b/headless-rust/src/storage/mod.rs index 3029ba7..92d2de0 100644 --- a/headless-rust/src/storage/mod.rs +++ b/headless-rust/src/storage/mod.rs @@ -39,7 +39,13 @@ impl FileStore { .decode(clean_b64.trim()) .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?; - self.save_image_bytes(&decoded, "png") + 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> { diff --git a/headless-rust/src/web/rpc.rs b/headless-rust/src/web/rpc.rs index d33d36b..5397b5b 100644 --- a/headless-rust/src/web/rpc.rs +++ b/headless-rust/src/web/rpc.rs @@ -213,15 +213,33 @@ async fn dispatch_method(ctx: &RpcContext, method: &str, params: Value) -> Resul "deleteLapSession" => { let id = params["id"].as_i64().ok_or("Missing id parameter")?; - let conn = ctx.db.lock(); - crate::db::laps::delete_lap_session(&conn, id).map_err(|e| e.to_string())?; + let img_paths = { + let conn = ctx.db.lock(); + crate::db::laps::get_lap_image_paths_for_session(&conn, id).unwrap_or_default() + }; + { + let conn = ctx.db.lock(); + crate::db::laps::delete_lap_session(&conn, id).map_err(|e| e.to_string())?; + } + for p in img_paths { + ctx.store.delete_image(&p); + } Ok(Value::Null) } "deleteLap" => { let id = params["id"].as_i64().ok_or("Missing id parameter")?; - let conn = ctx.db.lock(); - crate::db::laps::delete_lap(&conn, id).map_err(|e| e.to_string())?; + let img_paths = { + let conn = ctx.db.lock(); + crate::db::laps::get_lap_image_paths_for_lap(&conn, id).unwrap_or_default() + }; + { + let conn = ctx.db.lock(); + crate::db::laps::delete_lap(&conn, id).map_err(|e| e.to_string())?; + } + for p in img_paths { + ctx.store.delete_image(&p); + } Ok(Value::Null) } From 495c309a86bd41140aec30bd93d55c8bda8f1728 Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Mon, 17 Aug 2026 20:40:04 +0200 Subject: [PATCH 48/65] refactor: migrate from Rocket to Axum and update dependencies - Replaced Rocket and Rocket WS with Axum, Tower, and Tower HTTP for improved performance and flexibility. - Updated dependencies in Cargo.toml, including serialport, rusqlite, tokio, tracing, and added socketioxide. - Updated bun.lock and package.json to include socket.io-client for real-time communication. --- headless-rust/Cargo.lock | 951 +++++++++---------------------------- headless-rust/Cargo.toml | 6 +- headless-rust/bun.lock | 15 + headless-rust/package.json | 1 + 4 files changed, 233 insertions(+), 740 deletions(-) diff --git a/headless-rust/Cargo.lock b/headless-rust/Cargo.lock index 4a24b36..a303b05 100644 --- a/headless-rust/Cargo.lock +++ b/headless-rust/Cargo.lock @@ -142,6 +142,9 @@ 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" @@ -169,54 +172,6 @@ dependencies = [ "stable_deref_trait", ] -[[package]] -name = "async-stream" -version = "0.3.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b5a71a6f37880a80d1d7f19efd781e4b5de42c88f0722cc13bcb6cc2cfe8476" -dependencies = [ - "async-stream-impl", - "futures-core", - "pin-project-lite", -] - -[[package]] -name = "async-stream-impl" -version = "0.3.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "async-trait" -version = "0.1.92" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.3", -] - -[[package]] -name = "atomic" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c59bdb34bc650a32731b31bd8f0829cc15d24a708ee31559e0bb34f2bc320cba" - -[[package]] -name = "atomic" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89cbf775b137e9b968e67227ef7f775587cde3fd31b0d8599dbd0f598a48340" -dependencies = [ - "bytemuck", -] - [[package]] name = "atomic-waker" version = "1.1.2" @@ -244,7 +199,7 @@ dependencies = [ "num-traits", "pastey", "rayon", - "thiserror 2.0.20", + "thiserror", "v_frame", "y4m", ] @@ -273,16 +228,62 @@ dependencies = [ ] [[package]] -name = "base64" -version = "0.22.1" +name = "axum" +version = "0.8.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +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 = "binascii" -version = "0.1.4" +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 = "383d29d513d8764dcdc42ea295d979eb99c3c9f00607b3692cf68a431f7dca72" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" [[package]] name = "bit_field" @@ -347,12 +348,6 @@ version = "1.25.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" -[[package]] -name = "byteorder" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" - [[package]] name = "byteorder-lite" version = "0.1.0" @@ -364,6 +359,9 @@ name = "bytes" version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +dependencies = [ + "serde", +] [[package]] name = "cc" @@ -472,17 +470,6 @@ version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" -[[package]] -name = "cookie" -version = "0.18.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a373e3602691c3cdea496d2f0ee5935151e6168fe87739483c463db1b2f2f87" -dependencies = [ - "percent-encoding", - "time", - "version_check", -] - [[package]] name = "core-foundation" version = "0.10.1" @@ -598,34 +585,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" [[package]] -name = "devise" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1d90b0c4c777a2cad215e3c7be59ac7c15adf45cf76317009b7d096d46f651d" -dependencies = [ - "devise_codegen", - "devise_core", -] - -[[package]] -name = "devise_codegen" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "71b28680d8be17a570a2334922518be6adc3f58ecc880cbb404eaeb8624fd867" -dependencies = [ - "devise_core", - "quote", -] - -[[package]] -name = "devise_core" -version = "0.4.2" +name = "derive_arbitrary" +version = "1.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b035a542cf7abf01f2e3c4d5a7acbaebfefe120ae4efc7bde3df98186e4b8af7" +checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a" dependencies = [ - "bitflags 2.13.1", "proc-macro2", - "proc-macro2-diagnostics", "quote", "syn 2.0.119", ] @@ -669,12 +634,49 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e5e8f6c15a24b9a3ee5efec809ccd006d3b30e8b3bb63c39af737c7f87daa1d" [[package]] -name = "encoding_rs" -version = "0.8.35" +name = "engineioxide" +version = "0.17.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3" +checksum = "1c48884059941b2b6255eabe1e9dca48e1aa01242299a7ef60844ded113b1d50" dependencies = [ - "cfg-if", + "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]] @@ -697,12 +699,6 @@ dependencies = [ "syn 2.0.119", ] -[[package]] -name = "equivalent" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" - [[package]] name = "errno" version = "0.3.14" @@ -742,12 +738,6 @@ version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" -[[package]] -name = "fastrand" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" - [[package]] name = "fax" version = "0.2.7" @@ -763,20 +753,6 @@ dependencies = [ "simd-adler32", ] -[[package]] -name = "figment" -version = "0.10.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8cb01cd46b0cf372153850f4c6c272d9cbea2da513e07538405148f95bd789f3" -dependencies = [ - "atomic 0.6.1", - "pear", - "serde", - "toml", - "uncased", - "version_check", -] - [[package]] name = "find-msvc-tools" version = "0.1.11" @@ -793,12 +769,6 @@ dependencies = [ "miniz_oxide", ] -[[package]] -name = "fnv" -version = "1.0.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" - [[package]] name = "form_urlencoded" version = "1.2.2" @@ -896,19 +866,6 @@ dependencies = [ "slab", ] -[[package]] -name = "generator" -version = "0.7.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5cc16584ff22b460a382b7feec54b23d2908d858152e5739a120b949293bd74e" -dependencies = [ - "cc", - "libc", - "log", - "rustversion", - "windows", -] - [[package]] name = "generic-array" version = "0.14.7" @@ -968,31 +925,6 @@ dependencies = [ "weezl", ] -[[package]] -name = "glob" -version = "0.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" - -[[package]] -name = "h2" -version = "0.3.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0beca50380b1fc32983fc1cb4587bfa4bb9e78fc259aad4a0032d2080309222d" -dependencies = [ - "bytes", - "fnv", - "futures-core", - "futures-sink", - "futures-util", - "http 0.2.12", - "indexmap", - "slab", - "tokio", - "tokio-util", - "tracing", -] - [[package]] name = "half" version = "2.7.1" @@ -1013,19 +945,13 @@ dependencies = [ "ahash", ] -[[package]] -name = "hashbrown" -version = "0.17.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" - [[package]] name = "hashlink" version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af" dependencies = [ - "hashbrown 0.14.5", + "hashbrown", ] [[package]] @@ -1033,6 +959,7 @@ name = "headless-rust" version = "0.1.0" dependencies = [ "ab_glyph", + "axum", "base64", "chrono", "clap", @@ -1043,15 +970,16 @@ dependencies = [ "nix 0.29.0", "pkg-config", "reqwest", - "rocket", - "rocket_ws", "rusqlite", "rust-embed", "serde", "serde_json", "serialport", + "socketioxide", "tokio", "tokio-stream", + "tower", + "tower-http", "tracing", "tracing-appender", "tracing-subscriber", @@ -1064,23 +992,6 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" -[[package]] -name = "hermit-abi" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c" - -[[package]] -name = "http" -version = "0.2.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "601cbb57e577e2f5ef5be8e7b83f0f63994f25aa94d673e54a92d5c516d101f1" -dependencies = [ - "bytes", - "fnv", - "itoa", -] - [[package]] name = "http" version = "1.5.0" @@ -1091,17 +1002,6 @@ dependencies = [ "itoa", ] -[[package]] -name = "http-body" -version = "0.4.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ceab25649e9960c0311ea418d17bee82c0dcec1bd053b5f9a66e265a693bed2" -dependencies = [ - "bytes", - "http 0.2.12", - "pin-project-lite", -] - [[package]] name = "http-body" version = "1.1.0" @@ -1109,7 +1009,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" dependencies = [ "bytes", - "http 1.5.0", + "http", ] [[package]] @@ -1120,8 +1020,8 @@ checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" dependencies = [ "bytes", "futures-core", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "pin-project-lite", ] @@ -1146,30 +1046,6 @@ dependencies = [ "typenum", ] -[[package]] -name = "hyper" -version = "0.14.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41dfc780fdec9373c01bae43289ea34c972e40ee3c9f6b3c8801a35f35586ce7" -dependencies = [ - "bytes", - "futures-channel", - "futures-core", - "futures-util", - "h2", - "http 0.2.12", - "http-body 0.4.6", - "httparse", - "httpdate", - "itoa", - "pin-project-lite", - "socket2 0.5.10", - "tokio", - "tower-service", - "tracing", - "want", -] - [[package]] name = "hyper" version = "1.11.0" @@ -1180,9 +1056,10 @@ dependencies = [ "bytes", "futures-channel", "futures-core", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "httparse", + "httpdate", "itoa", "pin-project-lite", "smallvec", @@ -1196,8 +1073,8 @@ version = "0.27.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" dependencies = [ - "http 1.5.0", - "hyper 1.11.0", + "http", + "hyper", "hyper-util", "rustls", "tokio", @@ -1216,14 +1093,14 @@ dependencies = [ "bytes", "futures-channel", "futures-util", - "http 1.5.0", - "http-body 1.1.0", - "hyper 1.11.0", + "http", + "http-body", + "hyper", "ipnet", "libc", "percent-encoding", "pin-project-lite", - "socket2 0.6.5", + "socket2", "tokio", "tower-service", "tracing", @@ -1415,24 +1292,6 @@ version = "1.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "89194689a993ab15268672e99e7b0e19da2da3268ac682e8f02d29d4d1434cd7" -[[package]] -name = "indexmap" -version = "2.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" -dependencies = [ - "equivalent", - "hashbrown 0.17.1", - "serde", - "serde_core", -] - -[[package]] -name = "inlinable_string" -version = "0.1.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8fae54786f62fb2918dcfae3d568594e50eb9b5c25bf04371af6fe7516452fb" - [[package]] name = "interpolate_name" version = "0.2.4" @@ -1460,17 +1319,6 @@ version = "2.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6a756c3fac73139e83f14c2d742155dd2b78d3ee56597b419a0579b7bdd6dd78" -[[package]] -name = "is-terminal" -version = "0.4.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46" -dependencies = [ - "hermit-abi", - "libc", - "windows-sys 0.61.2", -] - [[package]] name = "is_terminal_polyfill" version = "1.70.2" @@ -1587,12 +1435,6 @@ dependencies = [ "pkg-config", ] -[[package]] -name = "linux-raw-sys" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" - [[package]] name = "litemap" version = "0.8.3" @@ -1614,21 +1456,6 @@ version = "0.4.33" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" -[[package]] -name = "loom" -version = "0.5.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff50ecb28bb86013e935fb6683ab1f6d3a20016f123c76fd4c27470076ac30f5" -dependencies = [ - "cfg-if", - "generator", - "scoped-tls", - "serde", - "serde_json", - "tracing", - "tracing-subscriber", -] - [[package]] name = "loop9" version = "0.1.5" @@ -1662,6 +1489,18 @@ 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" @@ -1744,25 +1583,6 @@ dependencies = [ "pxfm", ] -[[package]] -name = "multer" -version = "3.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "83e87776546dc87511aa5ee218730c92b666d7264ab6ed41f9d215af9cd5224b" -dependencies = [ - "bytes", - "encoding_rs", - "futures-util", - "http 1.5.0", - "httparse", - "memchr", - "mime", - "spin", - "tokio", - "tokio-util", - "version_check", -] - [[package]] name = "nalgebra" version = "0.32.6" @@ -1932,16 +1752,6 @@ dependencies = [ "libm", ] -[[package]] -name = "num_cpus" -version = "1.17.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b" -dependencies = [ - "hermit-abi", - "libc", -] - [[package]] name = "once_cell" version = "1.21.4" @@ -1998,29 +1808,6 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec" -[[package]] -name = "pear" -version = "0.2.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bdeeaa00ce488657faba8ebf44ab9361f9365a97bd39ffb8a60663f57ff4b467" -dependencies = [ - "inlinable_string", - "pear_codegen", - "yansi", -] - -[[package]] -name = "pear_codegen" -version = "0.2.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4bab5b985dc082b345f812b7df84e1bef27e7207b39e448439ba8bd69c93f147" -dependencies = [ - "proc-macro2", - "proc-macro2-diagnostics", - "quote", - "syn 2.0.119", -] - [[package]] name = "percent-encoding" version = "2.3.2" @@ -2085,19 +1872,6 @@ dependencies = [ "unicode-ident", ] -[[package]] -name = "proc-macro2-diagnostics" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", - "version_check", - "yansi", -] - [[package]] name = "profiling" version = "1.0.18" @@ -2174,8 +1948,8 @@ dependencies = [ "quinn-udp", "rustc-hash", "rustls", - "socket2 0.6.5", - "thiserror 2.0.20", + "socket2", + "thiserror", "tokio", "tracing", "web-time", @@ -2197,7 +1971,7 @@ dependencies = [ "rustls", "rustls-pki-types", "slab", - "thiserror 2.0.20", + "thiserror", "tinyvec", "tracing", "web-time", @@ -2212,7 +1986,7 @@ dependencies = [ "cfg_aliases", "libc", "once_cell", - "socket2 0.6.5", + "socket2", "tracing", "windows-sys 0.61.2", ] @@ -2363,7 +2137,7 @@ dependencies = [ "rand 0.9.5", "rand_chacha 0.9.0", "simd_helpers", - "thiserror 2.0.20", + "thiserror", "v_frame", "wasm-bindgen", ] @@ -2433,26 +2207,6 @@ dependencies = [ "bitflags 2.13.1", ] -[[package]] -name = "ref-cast" -version = "1.0.26" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "216e8f773d7923bcba9ceb86a86c93cabb3903a11872fc3f138c49630e50b96d" -dependencies = [ - "ref-cast-impl", -] - -[[package]] -name = "ref-cast-impl" -version = "1.0.26" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c9283685feec7d69af75fb0e858d5e7378f33fe4fc699383b2916ab9273e03c" -dependencies = [ - "proc-macro2", - "quote", - "syn 3.0.3", -] - [[package]] name = "regex-automata" version = "0.4.18" @@ -2479,10 +2233,10 @@ dependencies = [ "base64", "bytes", "futures-core", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "http-body-util", - "hyper 1.11.0", + "hyper", "hyper-rustls", "hyper-util", "js-sys", @@ -2528,98 +2282,6 @@ dependencies = [ "windows-sys 0.52.0", ] -[[package]] -name = "rocket" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a516907296a31df7dc04310e7043b61d71954d703b603cc6867a026d7e72d73f" -dependencies = [ - "async-stream", - "async-trait", - "atomic 0.5.3", - "binascii", - "bytes", - "either", - "figment", - "futures", - "indexmap", - "log", - "memchr", - "multer", - "num_cpus", - "parking_lot", - "pin-project-lite", - "rand 0.8.7", - "ref-cast", - "rocket_codegen", - "rocket_http", - "serde", - "serde_json", - "state", - "tempfile", - "time", - "tokio", - "tokio-stream", - "tokio-util", - "ubyte", - "version_check", - "yansi", -] - -[[package]] -name = "rocket_codegen" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "575d32d7ec1a9770108c879fc7c47815a80073f96ca07ff9525a94fcede1dd46" -dependencies = [ - "devise", - "glob", - "indexmap", - "proc-macro2", - "quote", - "rocket_http", - "syn 2.0.119", - "unicode-xid", - "version_check", -] - -[[package]] -name = "rocket_http" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e274915a20ee3065f611c044bd63c40757396b6dbc057d6046aec27f14f882b9" -dependencies = [ - "cookie", - "either", - "futures", - "http 0.2.12", - "hyper 0.14.32", - "indexmap", - "log", - "memchr", - "pear", - "percent-encoding", - "pin-project-lite", - "ref-cast", - "serde", - "smallvec", - "stable-pattern", - "state", - "time", - "tokio", - "uncased", -] - -[[package]] -name = "rocket_ws" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25f1877668c937b701177c349f21383c556cd3bb4ba8fa1d07fa96ccb3a8782e" -dependencies = [ - "rocket", - "tokio-tungstenite", -] - [[package]] name = "rusqlite" version = "0.32.1" @@ -2677,19 +2339,6 @@ version = "2.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" -[[package]] -name = "rustix" -version = "1.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" -dependencies = [ - "bitflags 2.13.1", - "errno", - "libc", - "linux-raw-sys", - "windows-sys 0.61.2", -] - [[package]] name = "rustls" version = "0.23.43" @@ -2755,12 +2404,6 @@ dependencies = [ "winapi-util", ] -[[package]] -name = "scoped-tls" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" - [[package]] name = "scopeguard" version = "1.2.0" @@ -2811,12 +2454,14 @@ dependencies = [ ] [[package]] -name = "serde_spanned" -version = "0.6.9" +name = "serde_path_to_error" +version = "0.1.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" dependencies = [ + "itoa", "serde", + "serde_core", ] [[package]] @@ -2936,15 +2581,8 @@ name = "smallvec" version = "1.15.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" - -[[package]] -name = "socket2" -version = "0.5.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e22376abed350d73dd1cd119b57ffccad95b4e585a7cda43e286245ce23c0678" dependencies = [ - "libc", - "windows-sys 0.52.0", + "serde", ] [[package]] @@ -2958,34 +2596,62 @@ dependencies = [ ] [[package]] -name = "spin" -version = "0.9.9" +name = "socketioxide" +version = "0.18.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" +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 = "stable-pattern" -version = "0.1.0" +name = "socketioxide-core" +version = "0.18.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4564168c00635f88eaed410d5efa8131afa8d8699a612c80c455a0ba05c21045" +checksum = "71e520fedd1addc257506026a31268d9a6eeee79b158c7fc8b270c4c7a1cfc4f" dependencies = [ - "memchr", + "arbitrary", + "bytes", + "engineioxide-core", + "futures-core", + "serde", + "smallvec", + "thiserror", ] [[package]] -name = "stable_deref_trait" -version = "1.2.1" +name = "socketioxide-parser-common" +version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" +checksum = "5ba9a856b0de7f665fe0d66fb7d60c74ad2e1810552c60a31f72e9aa6372cc02" +dependencies = [ + "bytes", + "itoa", + "serde", + "serde_json", + "socketioxide-core", +] [[package]] -name = "state" -version = "0.6.0" +name = "stable_deref_trait" +version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b8c4a4445d81357df8b1a650d0d0d6fbbbfe99d064aa5e02f3e4022061476d8" -dependencies = [ - "loom", -] +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" [[package]] name = "strsim" @@ -3047,46 +2713,13 @@ dependencies = [ "syn 2.0.119", ] -[[package]] -name = "tempfile" -version = "3.27.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" -dependencies = [ - "fastrand", - "getrandom 0.4.3", - "once_cell", - "rustix", - "windows-sys 0.61.2", -] - -[[package]] -name = "thiserror" -version = "1.0.69" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" -dependencies = [ - "thiserror-impl 1.0.69", -] - [[package]] name = "thiserror" version = "2.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" dependencies = [ - "thiserror-impl 2.0.20", -] - -[[package]] -name = "thiserror-impl" -version = "1.0.69" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", + "thiserror-impl", ] [[package]] @@ -3190,7 +2823,7 @@ dependencies = [ "parking_lot", "pin-project-lite", "signal-hook-registry", - "socket2 0.6.5", + "socket2", "tokio-macros", "windows-sys 0.61.2", ] @@ -3229,9 +2862,9 @@ dependencies = [ [[package]] name = "tokio-tungstenite" -version = "0.21.0" +version = "0.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c83b561d025642014097b66e6c1bb422783339e0909e4429cde4749d1990bc38" +checksum = "8f72a05e828585856dacd553fba484c242c46e391fb0e58917c942ee9202915c" dependencies = [ "futures-util", "log", @@ -3248,52 +2881,10 @@ dependencies = [ "bytes", "futures-core", "futures-sink", - "libc", "pin-project-lite", "tokio", ] -[[package]] -name = "toml" -version = "0.8.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" -dependencies = [ - "serde", - "serde_spanned", - "toml_datetime", - "toml_edit", -] - -[[package]] -name = "toml_datetime" -version = "0.6.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" -dependencies = [ - "serde", -] - -[[package]] -name = "toml_edit" -version = "0.22.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" -dependencies = [ - "indexmap", - "serde", - "serde_spanned", - "toml_datetime", - "toml_write", - "winnow", -] - -[[package]] -name = "toml_write" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" - [[package]] name = "tower" version = "0.5.3" @@ -3307,6 +2898,7 @@ dependencies = [ "tokio", "tower-layer", "tower-service", + "tracing", ] [[package]] @@ -3318,8 +2910,8 @@ dependencies = [ "bitflags 2.13.1", "bytes", "futures-util", - "http 1.5.0", - "http-body 1.1.0", + "http", + "http-body", "pin-project-lite", "tower", "tower-layer", @@ -3345,6 +2937,7 @@ 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", @@ -3358,7 +2951,7 @@ checksum = "050686193eb999b4bb3bc2acfa891a13da00f79734704c4b8b4ef1a10b368a3c" dependencies = [ "crossbeam-channel", "symlink", - "thiserror 2.0.20", + "thiserror", "time", "tracing-subscriber", ] @@ -3427,21 +3020,18 @@ checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" [[package]] name = "tungstenite" -version = "0.21.0" +version = "0.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ef1a641ea34f399a848dea702823bbecfb4c486f911735368f1f137cb8257e1" +checksum = "6c01152af293afb9c7c2a57e4b559c5620b421f6d133261c60dd2d0cdb38e6b8" dependencies = [ - "byteorder", "bytes", "data-encoding", - "http 1.5.0", + "http", "httparse", "log", - "rand 0.8.7", + "rand 0.9.5", "sha1", - "thiserror 1.0.69", - "url", - "utf-8", + "thiserror", ] [[package]] @@ -3450,32 +3040,13 @@ version = "1.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" -[[package]] -name = "ubyte" -version = "0.10.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f720def6ce1ee2fc44d40ac9ed6d3a59c361c80a75a7aa8e75bb9baed31cf2ea" -dependencies = [ - "serde", -] - -[[package]] -name = "uncased" -version = "0.9.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1b88fcfe09e89d3866a5c11019378088af2d24c3fbd4f0543f96b479ec90697" -dependencies = [ - "serde", - "version_check", -] - [[package]] name = "unescaper" version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7285e83a80ce76f5e7bce79fa41f68d78ba62d1003cf27bf748ab24413808cf4" dependencies = [ - "thiserror 2.0.20", + "thiserror", ] [[package]] @@ -3490,12 +3061,6 @@ version = "1.0.24" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" -[[package]] -name = "unicode-xid" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" - [[package]] name = "untrusted" version = "0.9.0" @@ -3514,12 +3079,6 @@ dependencies = [ "serde", ] -[[package]] -name = "utf-8" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" - [[package]] name = "utf8_iter" version = "1.0.4" @@ -3704,15 +3263,6 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "windows" -version = "0.48.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e686886bc078bc1b0b600cac0147aadb815089b6e4da64016cbd754b6342700f" -dependencies = [ - "windows-targets 0.48.5", -] - [[package]] name = "windows-core" version = "0.62.2" @@ -3778,7 +3328,7 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ - "windows-targets 0.52.6", + "windows-targets", ] [[package]] @@ -3790,67 +3340,34 @@ dependencies = [ "windows-link", ] -[[package]] -name = "windows-targets" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" -dependencies = [ - "windows_aarch64_gnullvm 0.48.5", - "windows_aarch64_msvc 0.48.5", - "windows_i686_gnu 0.48.5", - "windows_i686_msvc 0.48.5", - "windows_x86_64_gnu 0.48.5", - "windows_x86_64_gnullvm 0.48.5", - "windows_x86_64_msvc 0.48.5", -] - [[package]] name = "windows-targets" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ - "windows_aarch64_gnullvm 0.52.6", - "windows_aarch64_msvc 0.52.6", - "windows_i686_gnu 0.52.6", + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", "windows_i686_gnullvm", - "windows_i686_msvc 0.52.6", - "windows_x86_64_gnu 0.52.6", - "windows_x86_64_gnullvm 0.52.6", - "windows_x86_64_msvc 0.52.6", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", ] -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" - [[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.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" - [[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.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" - [[package]] name = "windows_i686_gnu" version = "0.52.6" @@ -3863,63 +3380,30 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" -[[package]] -name = "windows_i686_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" - [[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.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" - [[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.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" - [[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.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" - [[package]] name = "windows_x86_64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" -[[package]] -name = "winnow" -version = "0.7.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" -dependencies = [ - "memchr", -] - [[package]] name = "wit-bindgen" version = "0.57.1" @@ -3938,15 +3422,6 @@ version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a5a4b21e1a62b67a2970e6831bc091d7b87e119e7f9791aef9702e3bef04448" -[[package]] -name = "yansi" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" -dependencies = [ - "is-terminal", -] - [[package]] name = "yoke" version = "0.8.3" diff --git a/headless-rust/Cargo.toml b/headless-rust/Cargo.toml index e387e44..03d7a2c 100644 --- a/headless-rust/Cargo.toml +++ b/headless-rust/Cargo.toml @@ -4,8 +4,9 @@ version = "0.1.0" edition = "2024" [dependencies] -rocket = { version = "0.5.1", features = ["json"] } -rocket_ws = "0.1.1" +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"] } @@ -27,6 +28,7 @@ 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/bun.lock b/headless-rust/bun.lock index 038b919..6d99dbb 100644 --- a/headless-rust/bun.lock +++ b/headless-rust/bun.lock @@ -20,6 +20,7 @@ "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", @@ -372,6 +373,8 @@ "@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=="], @@ -568,6 +571,10 @@ "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=="], @@ -956,6 +963,10 @@ "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=="], @@ -1042,8 +1053,12 @@ "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=="], diff --git a/headless-rust/package.json b/headless-rust/package.json index 2e39c62..beb839b 100644 --- a/headless-rust/package.json +++ b/headless-rust/package.json @@ -38,6 +38,7 @@ "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", From 0d30494545503b6f7b9e60b3abb8bfb6f36de7af Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Mon, 17 Aug 2026 20:40:45 +0200 Subject: [PATCH 49/65] feat: refactor WebSocket implementation to Socket.io - Replaced WebSocket implementation with Socket.io in test-server.ts and verify-ws.ts for improved real-time communication. - Updated main.rs to use Axum instead of Rocket for the web server. - Refactored embedded.rs to serve assets using Axum's response types. - Removed the old WebSocket handling code and replaced it with Socket.io event handling in socketio.rs. - Updated routes.rs to handle API requests using Axum and integrated Socket.io for real-time updates. - Adjusted vite.config.ts to route Socket.io requests correctly. - Cleaned up unused WebSocket code and dependencies. --- headless-rust/README.md | 10 +- .../diagnostics/probes/ws-rpc-probe.ts | 146 ++++----- headless-rust/frontend/src/lib/rpc.ts | 228 +++++--------- headless-rust/scripts/test-live-events.ts | 147 +++++++++ headless-rust/scripts/test-server.ts | 143 +++++---- headless-rust/scripts/verify-ws.ts | 70 ++--- headless-rust/src/main.rs | 15 +- headless-rust/src/web/embedded.rs | 60 ++-- headless-rust/src/web/mod.rs | 112 ++++--- headless-rust/src/web/routes.rs | 118 +++---- headless-rust/src/web/rpc.rs | 1 + headless-rust/src/web/socketio.rs | 164 ++++++++++ headless-rust/src/web/ws.rs | 289 ------------------ headless-rust/vite.config.ts | 4 +- 14 files changed, 729 insertions(+), 778 deletions(-) create mode 100644 headless-rust/scripts/test-live-events.ts create mode 100644 headless-rust/src/web/socketio.rs delete mode 100644 headless-rust/src/web/ws.rs diff --git a/headless-rust/README.md b/headless-rust/README.md index 24d2de4..beaaee1 100644 --- a/headless-rust/README.md +++ b/headless-rust/README.md @@ -1,6 +1,6 @@ -# Speedcamera Headless (Rust & Rocket) +# Speedcamera Headless (Rust & Axum / Socket.io) -A lightweight, high-performance, single-binary speedcamera daemon and responsive web controller written in **Rust** using **Rocket 0.5**, **native Aravis C FFI**, **SQLite**, and an embedded **React + Vite** frontend. +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. Creates a standalone Wi-Fi hotspot for laptops, tablets, and phones to connect and manage the system via web browser while communicating with industrial GigE cameras on a dedicated Ethernet subnet. @@ -16,8 +16,8 @@ Engineered specifically for **Raspberry Pi 5 with Raspberry Pi OS Lite** (zero d │ • wlan0 (Hotspot AP): 192.168.4.1/24 <── Web UI Browser Clients │ │ │ │ • speedcamera-rust Daemon (Single Standalone Binary) │ -│ ├── Rocket 0.5 HTTP Server (REST API & Embedded Static Frontend) │ -│ ├── Rocket WS (/ws/rpc JSON-RPC Server & Event Broadcaster) │ +│ ├── 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)│ @@ -304,7 +304,7 @@ bun run test:server - **Web UI:** `http://localhost:3000` - **Health Endpoint:** `http://localhost:3000/api/health` - **Network Endpoint:** `http://localhost:3000/api/network` -- **WebSocket RPC:** `ws://localhost:3000/ws/rpc` +- **Socket.io RPC & Events:** `http://localhost:3000/socket.io/` --- diff --git a/headless-rust/diagnostics/probes/ws-rpc-probe.ts b/headless-rust/diagnostics/probes/ws-rpc-probe.ts index fb68b7b..ec77640 100644 --- a/headless-rust/diagnostics/probes/ws-rpc-probe.ts +++ b/headless-rust/diagnostics/probes/ws-rpc-probe.ts @@ -1,4 +1,5 @@ import type { DiagConfig } from "../config"; +import { io, Socket } from "socket.io-client"; export interface RpcCallRecord { id: number; @@ -34,10 +35,9 @@ export interface WsRpcStats { export class WsRpcProbe { private config: DiagConfig; - private ws: WebSocket | null = null; + private socket: Socket | null = null; private isRunning = false; private reqIdCounter = 1000; - private pendingCalls = new Map(); private completedCalls: RpcCallRecord[] = []; private pushEvents: PushEventRecord[] = []; private lastPushTimestamp = 0; @@ -70,7 +70,7 @@ export class WsRpcProbe { const rpcLoop = async () => { if (!this.isRunning) return; - if (this.ws && this.ws.readyState === WebSocket.OPEN) { + if (this.socket && this.socket.connected) { const method = rpcMethods[methodIdx % rpcMethods.length]; methodIdx++; const params = method === "getViolations" ? { page: 1, limit: 5 } : {}; @@ -91,26 +91,22 @@ export class WsRpcProbe { clearTimeout(this.loopTimer); this.loopTimer = null; } - for (const [, pending] of this.pendingCalls) { - clearTimeout(pending.timeoutTimer); - } - this.pendingCalls.clear(); - if (this.ws) { + if (this.socket) { try { - this.ws.close(); + this.socket.disconnect(); } catch (_) {} - this.ws = null; + this.socket = null; } } public getStats(): WsRpcStats { - const totalCalls = this.completedCalls.length + this.pendingCalls.size; + 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) + .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; @@ -125,7 +121,7 @@ export class WsRpcProbe { const burstEventsCount = this.pushEvents.filter((e) => e.isBurst).length; return { - connected: this.ws !== null && this.ws.readyState === WebSocket.OPEN, + connected: this.socket !== null && this.socket.connected, connectAttempts: this.connectAttempts, disconnects: this.disconnects, totalCalls, @@ -152,8 +148,14 @@ export class WsRpcProbe { return new Promise((resolve) => { this.connectAttempts++; try { - const ws = new WebSocket(this.config.wsUrl); - this.ws = ws; + 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(() => { @@ -163,44 +165,56 @@ export class WsRpcProbe { } }, 4000); - ws.onopen = () => { + socket.on("connect", () => { if (!resolved) { resolved = true; clearTimeout(connectTimer); resolve(true); } if (this.onUpdateCallback) this.onUpdateCallback(); - }; + }); - ws.onmessage = (event) => { - this.handleMessage(event.data); + 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(); }; - ws.onerror = () => { + 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); } - }; + }); - ws.onclose = () => { + socket.on("disconnect", () => { this.disconnects++; - if (this.isRunning) { - // Auto reconnect after 1s - setTimeout(() => { - if (this.isRunning) void this.connect(); - }, 1000); - } if (this.onUpdateCallback) this.onUpdateCallback(); - }; + }); } catch (_) { resolve(false); } }); } - private sendRpc(method: string, params: any): number { + private async sendRpc(method: string, params: any) { const id = ++this.reqIdCounter; const now = Date.now(); @@ -211,67 +225,31 @@ export class WsRpcProbe { timedOut: false, }; - // RPC timeout after 5000ms - const timeoutTimer = setTimeout(() => { - if (this.pendingCalls.has(id)) { - const pending = this.pendingCalls.get(id)!; - this.pendingCalls.delete(id); - pending.record.timedOut = true; - pending.record.rttMs = 5000; - this.completedCalls.push(pending.record); - if (this.onUpdateCallback) this.onUpdateCallback(); - } - }, 5000); - - this.pendingCalls.set(id, { record, timeoutTimer }); - - try { - this.ws?.send(JSON.stringify({ id, method, params })); - } catch (err: any) { - clearTimeout(timeoutTimer); - this.pendingCalls.delete(id); - record.error = err.message; + if (!this.socket || !this.socket.connected) { + record.error = "Not connected"; this.completedCalls.push(record); + if (this.onUpdateCallback) this.onUpdateCallback(); + return; } - return id; - } - - private handleMessage(data: any) { - const now = Date.now(); try { - const msg = typeof data === "string" ? JSON.parse(data) : JSON.parse(data.toString()); - - // Case 1: RPC Response - if (msg.id !== undefined && this.pendingCalls.has(msg.id)) { - const pending = this.pendingCalls.get(msg.id)!; - this.pendingCalls.delete(msg.id); - clearTimeout(pending.timeoutTimer); - - pending.record.receivedAt = now; - pending.record.rttMs = Math.max(0, now - pending.record.sentAt); - if (msg.error) { - pending.record.error = String(msg.error); - } - this.completedCalls.push(pending.record); + 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; } - - // Case 2: Server Push Event - if (msg.event) { - const delta = this.lastPushTimestamp > 0 ? now - this.lastPushTimestamp : 0; - // If delta < 40ms and previous event had a gap > 1500ms, mark as burst! - const isBurst = delta < 40 && this.pushEvents.length > 0 && (this.pushEvents[this.pushEvents.length - 1].deltaFromPrevMs > 1500); - - this.pushEvents.push({ - event: msg.event, - timestamp: now, - deltaFromPrevMs: delta, - isBurst, - }); - this.lastPushTimestamp = now; + } catch (err: any) { + if (err?.name === "TimeoutError" || err?.message?.includes("timeout")) { + record.timedOut = true; + record.rttMs = 5000; + } else { + record.error = err.message; } - } catch (_) {} + } + this.completedCalls.push(record); if (this.onUpdateCallback) this.onUpdateCallback(); } } diff --git a/headless-rust/frontend/src/lib/rpc.ts b/headless-rust/frontend/src/lib/rpc.ts index 429727f..8f5a7a3 100644 --- a/headless-rust/frontend/src/lib/rpc.ts +++ b/headless-rust/frontend/src/lib/rpc.ts @@ -1,5 +1,6 @@ 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"]; @@ -15,53 +16,85 @@ export type SpeedcameraClientRPC = { type EventCallback = (payload: T) => void; -class WebSocketRpcClient { - private ws: WebSocket | null = null; - private reqIdCounter = 0; - private pendingRequests = new Map< - string | number, - { - resolve: (val: any) => void; - reject: (err: any) => void; - timer: ReturnType; - method: string; - } - >(); - private messageQueue: string[] = []; - private reconnectTimeout: ReturnType | null = null; - private reconnectDelay = 500; - private maxReconnectDelay = 5000; - private isConnecting = false; - private isExplicitlyClosed = false; - +class SocketIoRpcClient { + private socket: Socket; private listeners = new Map>(); - private heartbeatInterval: ReturnType | null = null; - private lastLatencyMs: number | null = null; private missedHeartbeats = 0; constructor() { - this.connect(); + const socketUrl = this.getSocketUrl(); + this.socket = io(socketUrl, { + transports: ["websocket", "polling"], + reconnection: true, + reconnectionAttempts: Infinity, + reconnectionDelay: 500, + reconnectionDelayMax: 5000, + timeout: 10000, + }); + + this.setupListeners(); } - private getWebSocketUrl(): string { - if (typeof window === "undefined") return "ws://127.0.0.1:3000/ws/rpc"; - const protocol = window.location.protocol === "https:" ? "wss:" : "ws:"; - const host = window.location.host; // includes port (e.g. localhost:5173 or 192.168.4.1:3000) - return `${protocol}//${host}/ws/rpc`; + 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] Connected to speedcamera daemon via Socket.io"); + this.missedHeartbeats = 0; + this.emit("connectionChange", true); + this.startHeartbeat(); + }); + + this.socket.on("disconnect", (reason) => { + console.log(`[rpc-client] Disconnected from daemon (reason: ${reason})`); + this.stopHeartbeat(); + this.emit("connectionChange", false); + this.emit("heartbeat" as any, { connected: false, latencyMs: null, degraded: true }); + }); + + 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); + }); } private startHeartbeat() { this.stopHeartbeat(); - // 1000ms active heartbeat forces the client Wi-Fi chipset out of 802.11 power-save sleep - // and continuously drains any buffered packets in the AP DTIM queue. + // 1000ms active heartbeat measures RTT and keeps Wi-Fi chipset active this.heartbeatInterval = setInterval(async () => { - if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return; + if (!this.socket.connected) return; const start = performance.now(); try { - await this.call("ping", {}); + await this.socket.timeout(2000).emitWithAck("ping"); const rtt = Math.round(performance.now() - start); - this.lastLatencyMs = rtt; this.missedHeartbeats = 0; this.emit("heartbeat" as any, { connected: true, latencyMs: rtt, degraded: rtt > 250 }); } catch (_) { @@ -80,96 +113,6 @@ class WebSocketRpcClient { } } - public connect() { - if (typeof window === "undefined" || this.isConnecting) return; - if (this.ws && (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING)) return; - - this.isConnecting = true; - - try { - const url = this.getWebSocketUrl(); - const ws = new WebSocket(url); - this.ws = ws; - - ws.onopen = () => { - console.log("[rpc-client] Connected to speedcamera daemon"); - this.isConnecting = false; - this.reconnectDelay = 500; - this.missedHeartbeats = 0; - this.emit("connectionChange", true); - this.startHeartbeat(); - - // Flush any queued messages - while (this.messageQueue.length > 0) { - const queued = this.messageQueue.shift(); - if (queued && ws.readyState === WebSocket.OPEN) { - ws.send(queued); - } - } - }; - - ws.onmessage = (event) => { - try { - const data = JSON.parse(event.data); - - // Case 1: Response to a pending RPC request - if (data.id !== undefined && this.pendingRequests.has(data.id)) { - const pending = this.pendingRequests.get(data.id)!; - this.pendingRequests.delete(data.id); - clearTimeout(pending.timer); - - if (data.error) { - pending.reject(new Error(data.error)); - } else { - pending.resolve(data.result); - } - return; - } - - // Case 2: Server push broadcast event - if (data.event) { - this.handlePushEvent(data.event as keyof PushMessageMap, data.payload); - return; - } - } catch (err) { - console.error("[rpc-client] Error handling message:", err); - } - }; - - ws.onerror = (err) => { - console.warn("[rpc-client] WebSocket transport error:", err); - this.isConnecting = false; - }; - - ws.onclose = (event) => { - console.log(`[rpc-client] Disconnected (code: ${event.code}). Reconnecting in ${this.reconnectDelay}ms...`); - this.isConnecting = false; - this.stopHeartbeat(); - this.ws = null; - this.emit("connectionChange", false); - this.emit("heartbeat" as any, { connected: false, latencyMs: null, degraded: true }); - - if (!this.isExplicitlyClosed && !this.reconnectTimeout) { - this.reconnectTimeout = setTimeout(() => { - this.reconnectTimeout = null; - this.reconnectDelay = Math.min(this.reconnectDelay * 1.5, this.maxReconnectDelay); - this.connect(); - }, this.reconnectDelay); - } - }; - } catch (err) { - this.isConnecting = false; - this.stopHeartbeat(); - console.error("[rpc-client] Failed to create WebSocket connection:", err); - if (!this.reconnectTimeout) { - this.reconnectTimeout = setTimeout(() => { - this.reconnectTimeout = null; - this.connect(); - }, this.reconnectDelay); - } - } - } - public on( event: K, callback: EventCallback @@ -273,33 +216,27 @@ class WebSocketRpcClient { this.emit(event, payload); } - public call(method: string, params: any): Promise { - return new Promise((resolve, reject) => { - const id = ++this.reqIdCounter; - const timer = setTimeout(() => { - if (this.pendingRequests.has(id)) { - this.pendingRequests.delete(id); - reject(new Error(`RPC request '${method}' timed out after 10000ms`)); - } - }, 10000); - - this.pendingRequests.set(id, { resolve, reject, timer, method }); - const payloadStr = JSON.stringify({ id, method, params }); - - if (this.ws && this.ws.readyState === WebSocket.OPEN) { - this.ws.send(payloadStr); - } else { - // Queue message and ensure connection is active - this.messageQueue.push(payloadStr); - if (!this.ws || this.ws.readyState === WebSocket.CLOSED) { - this.connect(); - } + 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 WebSocketRpcClient(); +export const rpcClient = new SocketIoRpcClient(); // Proxy accessor so `getRpc().request.someMethod(params)` works transparently const rpcProxy: SpeedcameraClientRPC = { @@ -313,4 +250,3 @@ const rpcProxy: SpeedcameraClientRPC = { export function getRpc(): SpeedcameraClientRPC { return rpcProxy; } - 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 index cb8754e..87edfc1 100755 --- a/headless-rust/scripts/test-server.ts +++ b/headless-rust/scripts/test-server.ts @@ -1,14 +1,23 @@ #!/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..."); -const binaryPath = existsSync("./target/release/headless-rust") - ? "./target/release/headless-rust" - : existsSync("./target/debug/headless-rust") - ? "./target/debug/headless-rust" - : "cargo"; +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"] @@ -64,81 +73,87 @@ try { } console.log("SPA index.html served correctly! Length:", indexHtml.length); - // 4. Test WebSocket RPC - console.log("Testing WebSocket RPC on ws://127.0.0.1:3099/ws/rpc ..."); - const ws = new WebSocket("ws://127.0.0.1:3099/ws/rpc"); + // 4. Test Socket.io RPC and initial broadcasts + console.log("Testing Socket.io on http://127.0.0.1:3099 ..."); + const socket = io("http://127.0.0.1:3099", { + transports: ["websocket", "polling"], + timeout: 5000, + }); await new Promise((resolve, reject) => { - let settingsOk = false; - let violationsOk = false; - let armedOk = false; - - ws.onopen = () => { - console.log("WebSocket connected successfully!"); - // Send RPC request for getSettings - ws.send(JSON.stringify({ id: 1, method: "getSettings", params: {} })); - // Send RPC request for getViolations - ws.send(JSON.stringify({ id: 2, method: "getViolations", params: { page: 1, limit: 10 } })); - // Send RPC request for getArmedState - ws.send(JSON.stringify({ id: 3, method: "getArmedState", params: {} })); - }; - - ws.onmessage = (event) => { - console.log("WS message received:", event.data); - const data = JSON.parse(event.data); - - if (data.id === 1) { - console.log("RPC getSettings result:", data.result); - if (data.result && typeof data.result.maxSpeed === "number") { - settingsOk = true; - console.log("SUCCESS: Settings RPC validated!"); - } else { - reject(new Error("Unexpected getSettings response")); + 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!"); - if (data.id === 2) { - console.log("RPC getViolations result:", data.result); - if (data.result && Array.isArray(data.result.violations)) { - violationsOk = true; - console.log("SUCCESS: Violations RPC validated!"); - } else { - reject(new Error("Unexpected getViolations response")); + // 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!"); - if (data.id === 3) { - console.log("RPC getArmedState result:", data.result); - if (data.result && typeof data.result.armed === "boolean") { - // Now test setArmed - ws.send(JSON.stringify({ id: 4, method: "setArmed", params: { armed: true } })); - } else { - reject(new Error("Unexpected getArmedState response")); + // 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"); } - } - if (data.id === 4) { - console.log("RPC setArmed result:", data.result); - if (data.result && data.result.armed === true) { - armedOk = true; - console.log("SUCCESS: Armed RPC validated!"); - } else { - reject(new Error("Unexpected setArmed response")); + // 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!"); - if (settingsOk && violationsOk && armedOk) { - ws.close(); + clearTimeout(timer); + socket.disconnect(); resolve(); + } catch (err) { + clearTimeout(timer); + socket.disconnect(); + reject(err); } - }; + }); - ws.onerror = (err) => reject(err); - setTimeout(() => reject(new Error("WS Timeout")), 8000); + socket.on("connect_error", (err) => { + clearTimeout(timer); + reject(err); + }); }); console.log("\n========================================================="); - console.log(" ALL INTEGRATION TESTS PASSED SUCCESSFULLY!"); + console.log(" ALL SOCKET.IO INTEGRATION TESTS PASSED SUCCESSFULLY!"); console.log("========================================================="); } finally { proc.kill(); diff --git a/headless-rust/scripts/verify-ws.ts b/headless-rust/scripts/verify-ws.ts index 39b2025..2776fdf 100755 --- a/headless-rust/scripts/verify-ws.ts +++ b/headless-rust/scripts/verify-ws.ts @@ -1,53 +1,55 @@ #!/usr/bin/env bun -console.log("Connecting to WebSocket on ws://127.0.0.1:3000/ws/rpc ..."); -const ws = new WebSocket("ws://127.0.0.1:3000/ws/rpc"); +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; -ws.onopen = () => { - console.log("[WS] Connected to Speedcamera Headless Rust Daemon!"); - // 1. Request getSettings - ws.send(JSON.stringify({ id: 101, method: "getSettings", params: {} })); - // 2. Request getViolations - ws.send(JSON.stringify({ id: 102, method: "getViolations", params: { page: 1, limit: 10 } })); -}; - -ws.onmessage = (event) => { - console.log("[WS] Message received:", event.data); - const data = JSON.parse(event.data); - - if (data.event === "cameraStatus") { - receivedCameraPush = true; - console.log("-> Push message 'cameraStatus' verified!"); - } +socket.on("connect", async () => { + console.log("[Socket.io] Connected to Speedcamera Headless Rust Daemon! Socket ID:", socket.id); - if (data.id === 101) { - if (data.result && typeof data.result.maxSpeed === "number") { + 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:", data.result.maxSpeed); + console.log("-> RPC 'getSettings' verified! Max speed:", settingsResp.result.maxSpeed); } - } - if (data.id === 102) { - if (data.result && Array.isArray(data.result.violations)) { + // 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:", data.result.total); + console.log("-> RPC 'getViolations' verified! Total violations:", violationsResp.result.total); } - } - if (receivedSettingsResponse && receivedViolationsResponse) { - console.log("\n>>> ALL WEBSOCKET RPC CHECKS PASSED PERFECTLY! <<<"); - ws.close(); - process.exit(0); + 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); +}); -ws.onerror = (err) => { - console.error("WS error:", err); +socket.on("connect_error", (err) => { + console.error("Socket.io error:", err.message); process.exit(1); -}; +}); setTimeout(() => { console.error("Test timeout after 5s"); diff --git a/headless-rust/src/main.rs b/headless-rust/src/main.rs index fd1619d..ae5c083 100644 --- a/headless-rust/src/main.rs +++ b/headless-rust/src/main.rs @@ -30,8 +30,8 @@ struct Args { host: Option, } -#[rocket::main] -async fn main() -> Result<(), rocket::Error> { +#[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()); @@ -48,7 +48,7 @@ async fn main() -> Result<(), rocket::Error> { let config = AppConfig::new(args.mock, args.port, args.host); tracing::info!("─────────────────────────────────────────────────────────────────"); - tracing::info!(" ⚡ Speedcamera Headless Daemon (Rust & Rocket)"); + 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); @@ -153,9 +153,12 @@ async fn main() -> Result<(), rocket::Error> { } }); - // Build and launch Rocket web server - let server = web::build_rocket(config, db, store, camera, serial, violation_tx, armed, armed_tx); - server.launch().await?; + // 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/web/embedded.rs b/headless-rust/src/web/embedded.rs index df47365..e1fcd17 100644 --- a/headless-rust/src/web/embedded.rs +++ b/headless-rust/src/web/embedded.rs @@ -1,28 +1,12 @@ -use rocket::http::ContentType; -use rocket::response::{self, Responder, Response}; -use rocket::Request; +use axum::body::Body; +use axum::http::{header, Response, StatusCode}; use rust_embed::RustEmbed; -use std::io::Cursor; #[derive(RustEmbed)] #[folder = "dist/"] pub struct Asset; -pub struct EmbeddedFile { - pub data: Vec, - pub content_type: ContentType, -} - -impl<'r> Responder<'r, 'static> for EmbeddedFile { - fn respond_to(self, _: &'r Request<'_>) -> response::Result<'static> { - Response::build() - .header(self.content_type) - .sized_body(self.data.len(), Cursor::new(self.data)) - .ok() - } -} - -pub fn get_asset(path: &str) -> Option { +pub fn serve_embedded_asset(path: &str) -> Response { let clean_path = path.trim_start_matches('/'); let target = if clean_path.is_empty() { "index.html" @@ -31,22 +15,30 @@ pub fn get_asset(path: &str) -> Option { }; if let Some(file) = Asset::get(target) { - let ext = std::path::Path::new(target) - .extension() - .and_then(|e| e.to_str()) - .unwrap_or(""); - let content_type = ContentType::from_extension(ext).unwrap_or(ContentType::Bytes); - Some(EmbeddedFile { - data: file.data.into_owned(), - content_type, - }) + 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 only for client-side navigation routes (routes without file extensions) - Asset::get("index.html").map(|index| EmbeddedFile { - data: index.data.into_owned(), - content_type: ContentType::HTML, - }) + // 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 { - None + 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 index 6dabe64..cfc6398 100644 --- a/headless-rust/src/web/mod.rs +++ b/headless-rust/src/web/mod.rs @@ -1,45 +1,27 @@ pub mod embedded; pub mod routes; pub mod rpc; -pub mod ws; +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 rocket::fairing::{Fairing, Info, Kind}; -use rocket::http::Header; -use rocket::{Build, Request, Response, Rocket}; +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 struct Cors; - -#[rocket::async_trait] -impl Fairing for Cors { - fn info(&self) -> Info { - Info { - name: "Add CORS Headers", - kind: Kind::Response, - } - } - - async fn on_response<'r>(&self, _request: &'r Request<'_>, response: &mut Response<'r>) { - response.set_header(Header::new("Access-Control-Allow-Origin", "*")); - response.set_header(Header::new( - "Access-Control-Allow-Methods", - "GET, POST, PUT, DELETE, OPTIONS, HEAD", - )); - response.set_header(Header::new("Access-Control-Allow-Headers", "*")); - response.set_header(Header::new("Access-Control-Allow-Credentials", "true")); - } -} - -use std::sync::atomic::AtomicBool; - -pub fn build_rocket( +pub fn build_app( config: AppConfig, db: Database, store: FileStore, @@ -48,35 +30,51 @@ pub fn build_rocket( violation_tx: broadcast::Sender, armed: Arc, armed_tx: broadcast::Sender, -) -> Rocket { +) -> Router { let (flash_tx, _) = broadcast::channel::(32); - let figment = rocket::Config::figment() - .merge(("address", config.host.as_str())) - .merge(("port", config.port)); + let ctx = Arc::new(RpcContext { + config, + db, + store, + camera, + serial, + teable: TeableClient::new(), + flash_tx, + violation_tx, + armed, + armed_tx, + }); + + // 10 MB payload capacity for live JPEG frames and violation base64 payloads + let (layer, io) = SocketIo::builder() + .max_payload(10_000_000) + .max_buffer_size(2048) + .ping_interval(Duration::from_secs(10)) + .ping_timeout(Duration::from_secs(5)) + .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); - rocket::custom(figment) - .attach(Cors) - .manage(config) - .manage(db) - .manage(store) - .manage(camera) - .manage(serial) - .manage(flash_tx) - .manage(violation_tx) - .manage(armed) - .manage(armed_tx) - .mount( - "/", - rocket::routes![ - routes::health, - routes::network, - routes::get_image, - routes::get_skinned_image, - ws::ws_rpc, - ws::ws_alias, - routes::index, - routes::static_assets, - ], - ) + 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)) + .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 index 1b10f3e..799d920 100644 --- a/headless-rust/src/web/routes.rs +++ b/headless-rust/src/web/routes.rs @@ -1,94 +1,98 @@ -use crate::camera::CameraService; -use crate::config::AppConfig; -use crate::db::Database; use crate::network::get_system_network_summary; use crate::storage::skin::render_poliscan_skin; -use crate::storage::FileStore; -use crate::web::embedded::{get_asset, EmbeddedFile}; -use rocket::http::{ContentType, Status}; -use rocket::serde::json::Json; -use rocket::State; +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, 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; -use std::sync::atomic::{AtomicBool, Ordering}; - -#[rocket::get("/api/health")] -pub fn health( - config: &State, - camera: &State>, - armed: &State>, -) -> Json { +pub async fn health(State(ctx): State>) -> impl IntoResponse { Json(json!({ "status": "ok", "platform": std::env::consts::OS, - "camera": camera.get_status(), + "camera": ctx.camera.get_status(), "network": get_system_network_summary(), - "mockMode": config.mock_mode, - "armed": armed.load(Ordering::SeqCst), + "mockMode": ctx.config.mock_mode, + "armed": ctx.armed.load(Ordering::SeqCst), })) } -#[rocket::get("/api/network")] -pub fn network() -> Json { +pub async fn network() -> impl IntoResponse { Json(get_system_network_summary()) } -#[rocket::get("/image?")] -pub fn get_image( - path: Option, - store: &State, -) -> Result<(ContentType, Vec), Status> { - let p = path.ok_or(Status::BadRequest)?; - let bytes = store.read_image(&p).ok_or(Status::NotFound)?; +#[derive(Deserialize)] +pub struct ImageQuery { + pub path: Option, +} + +pub async fn get_image( + State(ctx): State>, + Query(query): Query, +) -> Result, StatusCode> { + let path = query.path.ok_or(StatusCode::BAD_REQUEST)?; + let bytes = ctx.store.read_image(&path).ok_or(StatusCode::NOT_FOUND)?; let content_type = if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) { - ContentType::JPEG + "image/jpeg" } else { - ContentType::PNG + "image/png" }; - Ok((content_type, bytes)) + + Response::builder() + .status(StatusCode::OK) + .header(header::CONTENT_TYPE, content_type) + .body(Body::from(bytes)) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR) } -#[rocket::get("/skinned-image?")] -pub fn get_skinned_image( - #[allow(non_snake_case)] violationId: Option, - db: &State, - store: &State, -) -> Result<(ContentType, Vec), Status> { - let id = violationId.ok_or(Status::BadRequest)?; - let conn = db.lock(); +#[derive(Deserialize)] +pub struct SkinnedImageQuery { + #[serde(rename = "violationId")] + pub violation_id: Option, +} + +pub async fn get_skinned_image( + State(ctx): State>, + Query(query): Query, +) -> Result, StatusCode> { + let id = query.violation_id.ok_or(StatusCode::BAD_REQUEST)?; + let conn = ctx.db.lock(); let violation = crate::db::violations::get_violation_by_id(&conn, id) - .map_err(|_| Status::InternalServerError)? - .ok_or(Status::NotFound)?; + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? + .ok_or(StatusCode::NOT_FOUND)?; - let settings = crate::db::settings::get_settings(&conn).map_err(|_| Status::InternalServerError)?; - let image_bytes = store.read_image(&violation.image_path).ok_or(Status::NotFound)?; + let settings = crate::db::settings::get_settings(&conn) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + let image_bytes = ctx.store.read_image(&violation.image_path).ok_or(StatusCode::NOT_FOUND)?; let rendered = render_poliscan_skin( &image_bytes, &violation, &settings.skin_measuring_location, ) - .ok_or(Status::InternalServerError)?; + .ok_or(StatusCode::INTERNAL_SERVER_ERROR)?; let content_type = if rendered.starts_with(&[0xFF, 0xD8, 0xFF]) { - ContentType::JPEG + "image/jpeg" } else { - ContentType::PNG + "image/png" }; - Ok((content_type, rendered)) -} - - -#[rocket::get("/", rank = 20)] -pub fn static_assets(file: std::path::PathBuf) -> Result { - let path_str = file.to_string_lossy().to_string(); - get_asset(&path_str).ok_or(Status::NotFound) + Response::builder() + .status(StatusCode::OK) + .header(header::CONTENT_TYPE, content_type) + .body(Body::from(rendered)) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR) } -#[rocket::get("/", rank = 10)] -pub fn index() -> Result { - get_asset("index.html").ok_or(Status::NotFound) +pub async fn static_handler(uri: Uri) -> impl IntoResponse { + let path = uri.path(); + serve_embedded_asset(path) } diff --git a/headless-rust/src/web/rpc.rs b/headless-rust/src/web/rpc.rs index 5397b5b..1cb0452 100644 --- a/headless-rust/src/web/rpc.rs +++ b/headless-rust/src/web/rpc.rs @@ -32,6 +32,7 @@ pub struct RpcResponse { } pub struct RpcContext { + pub config: crate::config::AppConfig, pub db: Database, pub store: FileStore, pub camera: Arc, 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/src/web/ws.rs b/headless-rust/src/web/ws.rs deleted file mode 100644 index cd89184..0000000 --- a/headless-rust/src/web/ws.rs +++ /dev/null @@ -1,289 +0,0 @@ -use crate::camera::CameraService; -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::{handle_rpc, RpcContext, RpcRequest}; -use futures::{SinkExt, StreamExt}; -use rocket::State; -use rocket_ws::stream::DuplexStream; -use rocket_ws::{Channel, Message, WebSocket}; -use serde_json::json; -use std::sync::Arc; -use std::time::Duration; -use std::sync::atomic::{AtomicBool, Ordering}; -use tokio::sync::{broadcast, mpsc}; - -#[rocket::get("/ws/rpc")] -pub fn ws_rpc( - ws: WebSocket, - db: &State, - store: &State, - camera: &State>, - serial: &State>, - flash_tx: &State>, - violation_tx: &State>, - armed: &State>, - armed_tx: &State>, -) -> Channel<'static> { - let ctx = Arc::new(RpcContext { - db: (*db).clone(), - store: (*store).clone(), - camera: (*camera).clone(), - serial: (*serial).clone(), - teable: TeableClient::new(), - flash_tx: (*flash_tx).clone(), - violation_tx: (*violation_tx).clone(), - armed: (*armed).clone(), - armed_tx: (*armed_tx).clone(), - }); - - ws.channel(move |stream: DuplexStream| { - let ctx = ctx.clone(); - Box::pin(async move { - tracing::info!("[ws] Client connected"); - - let (mut ws_sink, mut ws_stream) = stream.split(); - - // MPSC channel for multiplexing outgoing messages onto the WebSocket sink - let (out_tx, mut out_rx) = mpsc::channel::(128); - - // Dedicated Writer Task - let writer_handle = tokio::spawn(async move { - while let Some(msg) = out_rx.recv().await { - if let Err(e) = ws_sink.send(msg).await { - tracing::warn!("[ws-writer] Send error or client disconnected: {}", e); - break; - } - } - let _ = ws_sink.close().await; - }); - - // Push initial camera status immediately (with isStreaming state) - let init_camera = json!({ - "event": "cameraStatus", - "payload": ctx.camera.get_status() - }); - let _ = out_tx.send(Message::Text(init_camera.to_string())).await; - - // Push initial serial status immediately - let init_serial = json!({ - "event": "serialStatus", - "payload": ctx.serial.get_status_payload() - }); - let _ = out_tx.send(Message::Text(init_serial.to_string())).await; - - // Push initial armed status immediately - let init_armed = json!({ - "event": "armedStatus", - "payload": { "armed": ctx.armed.load(Ordering::SeqCst) } - }); - let _ = out_tx.send(Message::Text(init_armed.to_string())).await; - - // Subscribe to all backend event channels - 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(); - - // Heartbeat ping interval - let mut ping_interval = tokio::time::interval(Duration::from_secs(15)); - ping_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); - - loop { - tokio::select! { - // Incoming message from client - incoming = ws_stream.next() => { - match incoming { - Some(Ok(Message::Text(text))) => { - if let Ok(req) = serde_json::from_str::(&text) { - if req.method == "ping" || req.method == "heartbeat" { - let resp = json!({ - "id": req.id, - "result": { "pong": true, "timestamp": chrono::Utc::now().timestamp_millis() } - }); - let _ = out_tx.send(Message::Text(resp.to_string())).await; - continue; - } - - let ctx_clone = ctx.clone(); - let out_tx_clone = out_tx.clone(); - // Handle RPC asynchronously in independent task to prevent blocking the select loop - tokio::spawn(async move { - let resp = handle_rpc(&ctx_clone, req).await; - if let Ok(resp_json) = serde_json::to_string(&resp) { - let _ = out_tx_clone.send(Message::Text(resp_json)).await; - } - }); - } - } - Some(Ok(Message::Ping(payload))) => { - let _ = out_tx.send(Message::Pong(payload)).await; - } - Some(Ok(Message::Pong(_))) => {} - Some(Ok(Message::Close(_))) | None => { - tracing::info!("[ws] Client disconnected cleanly"); - break; - } - Some(Err(e)) => { - tracing::warn!("[ws] Error reading from stream: {}", e); - break; - } - _ => {} - } - } - - // Periodic Ping keepalive - _ = ping_interval.tick() => { - if out_tx.send(Message::Ping(Vec::new())).await.is_err() { - break; - } - } - - // Serial telemetry broadcast (drop on slow client — next update follows soon) - res = serial_rx.recv() => { - match res { - Ok(payload) => { - let msg = json!({ - "event": "serialStatus", - "payload": payload - }); - let _ = out_tx.try_send(Message::Text(msg.to_string())); - } - Err(broadcast::error::RecvError::Lagged(n)) => { - tracing::debug!("[ws] Serial broadcast lagged by {} messages", n); - } - Err(broadcast::error::RecvError::Closed) => break, - } - } - - // Camera status broadcast (drop on slow client — status is re-sent on change) - res = camera_status_rx.recv() => { - match res { - Ok(payload) => { - let msg = json!({ - "event": "cameraStatus", - "payload": payload - }); - let _ = out_tx.try_send(Message::Text(msg.to_string())); - } - Err(broadcast::error::RecvError::Lagged(n)) => { - tracing::debug!("[ws] Camera status broadcast lagged by {} messages", n); - } - Err(broadcast::error::RecvError::Closed) => break, - } - } - - // Live frame broadcast (conflated: drop frame if channel is busy to prevent backpressure stalls) - res = live_frame_rx.recv() => { - match res { - Ok(b64_frame) => { - let msg = json!({ - "event": "liveFrame", - "payload": b64_frame - }); - // Use try_send so slow WebSocket consumers never stall critical telemetry or RPCs - let _ = out_tx.try_send(Message::Text(msg.to_string())); - } - Err(broadcast::error::RecvError::Lagged(_)) => { - // Frame skipping is normal when preview rate exceeds network bandwidth - } - Err(broadcast::error::RecvError::Closed) => break, - } - } - - // Violation broadcast (high priority — retry briefly, then drop rather than stall) - res = violation_rx.recv() => { - match res { - Ok(v) => { - tracing::info!("[ws] Broadcasting violation #{} to client", v.id); - let msg = json!({ - "event": "violation", - "payload": v - }); - let text = Message::Text(msg.to_string()); - // Try a few times with tiny yields; never block the select loop - let mut sent = false; - for _ in 0..10 { - match out_tx.try_send(text.clone()) { - Ok(_) => { sent = true; break; } - Err(mpsc::error::TrySendError::Full(_)) => { - tokio::time::sleep(Duration::from_millis(20)).await; - } - Err(_) => break, - } - } - if !sent { - tracing::warn!("[ws] Dropped violation #{} — client too slow", v.id); - } - } - Err(broadcast::error::RecvError::Lagged(n)) => { - tracing::debug!("[ws] Violation broadcast lagged by {} messages", n); - } - Err(broadcast::error::RecvError::Closed) => break, - } - } - - // Flash progress broadcast (drop on slow client) - res = flash_rx.recv() => { - match res { - Ok(payload) => { - let msg = json!({ - "event": "flashProgress", - "payload": payload - }); - let _ = out_tx.try_send(Message::Text(msg.to_string())); - } - Err(broadcast::error::RecvError::Lagged(n)) => { - tracing::debug!("[ws] Flash progress broadcast lagged by {} messages", n); - } - Err(broadcast::error::RecvError::Closed) => break, - } - } - - // Armed status broadcast (drop on slow client) - res = armed_rx.recv() => { - match res { - Ok(is_armed) => { - let msg = json!({ - "event": "armedStatus", - "payload": { "armed": is_armed } - }); - let _ = out_tx.try_send(Message::Text(msg.to_string())); - } - Err(broadcast::error::RecvError::Lagged(n)) => { - tracing::debug!("[ws] Armed status broadcast lagged by {} messages", n); - } - Err(broadcast::error::RecvError::Closed) => break, - } - } - } - } - - // Drop out_tx so writer task finishes - drop(out_tx); - let _ = writer_handle.await; - - tracing::info!("[ws] Client session ended"); - Ok(()) - }) - }) -} - -#[rocket::get("/ws")] -pub fn ws_alias( - ws: WebSocket, - db: &State, - store: &State, - camera: &State>, - serial: &State>, - flash_tx: &State>, - violation_tx: &State>, - armed: &State>, - armed_tx: &State>, -) -> Channel<'static> { - ws_rpc(ws, db, store, camera, serial, flash_tx, violation_tx, armed, armed_tx) -} diff --git a/headless-rust/vite.config.ts b/headless-rust/vite.config.ts index ebfaf0b..ddc3c25 100644 --- a/headless-rust/vite.config.ts +++ b/headless-rust/vite.config.ts @@ -21,8 +21,8 @@ export default defineConfig({ "/image": "http://127.0.0.1:3000", "/skinned-image": "http://127.0.0.1:3000", "/api": "http://127.0.0.1:3000", - "/ws": { - target: "ws://127.0.0.1:3000", + "/socket.io": { + target: "http://127.0.0.1:3000", ws: true, }, }, From 612ce899122f5469ab14fe9be8a76804304ed468 Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Mon, 17 Aug 2026 23:16:51 +0200 Subject: [PATCH 50/65] feat: Enhance Socket.io client with lifecycle event handling and improved reconnection logic --- headless-rust/frontend/src/lib/rpc.ts | 97 +++++++++++++++++++++++++-- headless-rust/src/web/mod.rs | 12 ++-- 2 files changed, 98 insertions(+), 11 deletions(-) diff --git a/headless-rust/frontend/src/lib/rpc.ts b/headless-rust/frontend/src/lib/rpc.ts index 8f5a7a3..3302b93 100644 --- a/headless-rust/frontend/src/lib/rpc.ts +++ b/headless-rust/frontend/src/lib/rpc.ts @@ -21,19 +21,24 @@ class SocketIoRpcClient { 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, - timeout: 10000, + reconnectionDelay: 300, + reconnectionDelayMax: 2500, + randomizationFactor: 0.2, + timeout: 5000, + autoConnect: true, }); this.setupListeners(); + this.setupLifecycleListeners(); } private getSocketUrl(): string { @@ -43,17 +48,28 @@ class SocketIoRpcClient { private setupListeners() { this.socket.on("connect", () => { - console.log("[rpc-client] Connected to speedcamera daemon via Socket.io"); + 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] Disconnected from daemon (reason: ${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) => { @@ -86,14 +102,79 @@ class SocketIoRpcClient { }); } + /** + * 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(1200).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(); - // 1000ms active heartbeat measures RTT and keeps Wi-Fi chipset active + // 1000ms active heartbeat: + // 1. Sends continuous micro-packets to prevent 802.11 Wi-Fi DTIM sleep + // 2. Real-time RTT latency telemetry + // 3. Instant recovery on 2 missed heartbeats (detects dead connections in 2s) this.heartbeatInterval = setInterval(async () => { if (!this.socket.connected) return; const start = performance.now(); try { - await this.socket.timeout(2000).emitWithAck("ping"); + await this.socket.timeout(1500).emitWithAck("ping"); const rtt = Math.round(performance.now() - start); this.missedHeartbeats = 0; this.emit("heartbeat" as any, { connected: true, latencyMs: rtt, degraded: rtt > 250 }); @@ -101,6 +182,8 @@ class SocketIoRpcClient { this.missedHeartbeats++; if (this.missedHeartbeats >= 2) { this.emit("heartbeat" as any, { connected: false, latencyMs: null, degraded: true }); + console.warn("[rpc-client] Missed 2 heartbeats (silent Wi-Fi stall) — resetting socket transport"); + this.socket.disconnect().connect(); } } }, 1000); diff --git a/headless-rust/src/web/mod.rs b/headless-rust/src/web/mod.rs index cfc6398..fd455c0 100644 --- a/headless-rust/src/web/mod.rs +++ b/headless-rust/src/web/mod.rs @@ -46,12 +46,16 @@ pub fn build_app( armed_tx, }); - // 10 MB payload capacity for live JPEG frames and violation base64 payloads + // 10 MB payload capacity, fast 5s keepalive ping interval to keep Wi-Fi sleep-disabled, + // short 4s timeout for zombie detection, and large 4096 buffer size for live stream bursts. let (layer, io) = SocketIo::builder() .max_payload(10_000_000) - .max_buffer_size(2048) - .ping_interval(Duration::from_secs(10)) - .ping_timeout(Duration::from_secs(5)) + .max_buffer_size(4096) + .ping_interval(Duration::from_secs(5)) + .ping_timeout(Duration::from_secs(4)) + .connect_timeout(Duration::from_secs(5)) + .upgrade_timeout(Duration::from_secs(5)) + .ack_timeout(Duration::from_secs(10)) .build_layer(); let ctx_connect = ctx.clone(); From 73ef306ac4498202cc7890db13e461835d04cc82 Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Mon, 17 Aug 2026 23:40:51 +0200 Subject: [PATCH 51/65] feat: Add new dependencies for image processing and document features --- headless-rust/Cargo.lock | 32 ++++++++++++++++++++++++++++++++ headless-rust/Cargo.toml | 4 +++- 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/headless-rust/Cargo.lock b/headless-rust/Cargo.lock index a303b05..06a02fa 100644 --- a/headless-rust/Cargo.lock +++ b/headless-rust/Cargo.lock @@ -627,6 +627,15 @@ dependencies = [ "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" @@ -738,6 +747,21 @@ 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" @@ -963,12 +987,14 @@ dependencies = [ "base64", "chrono", "clap", + "fast_image_resize", "futures", "image", "imageproc", "mime_guess", "nix 0.29.0", "pkg-config", + "rayon", "reqwest", "rusqlite", "rust-embed", @@ -1441,6 +1467,12 @@ 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" diff --git a/headless-rust/Cargo.toml b/headless-rust/Cargo.toml index 03d7a2c..71b7e3f 100644 --- a/headless-rust/Cargo.toml +++ b/headless-rust/Cargo.toml @@ -12,7 +12,9 @@ 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"] } +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"] } From 0e8b086ab14412121d39a8f0f2fd8a31df764f30 Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Mon, 17 Aug 2026 23:41:47 +0200 Subject: [PATCH 52/65] feat: Optimize image loading with compressed thumbnails and full-resolution support --- .../src/components/LapImageThumbnails.tsx | 17 +++---- .../src/components/LastCapturedImage.tsx | 44 +++++++++++++++---- .../frontend/src/components/ViolationCard.tsx | 7 ++- .../frontend/src/routes/violations.tsx | 12 ++--- .../routes/violations/ViolationGridTile.tsx | 9 +++- .../src/routes/violations/ViolationRow.tsx | 11 +++-- .../routes/violations/useViolationImage.ts | 28 +++++++++--- headless-rust/frontend/src/shared/types.ts | 16 ++++++- 8 files changed, 107 insertions(+), 37 deletions(-) diff --git a/headless-rust/frontend/src/components/LapImageThumbnails.tsx b/headless-rust/frontend/src/components/LapImageThumbnails.tsx index 04f2b89..33f3069 100644 --- a/headless-rust/frontend/src/components/LapImageThumbnails.tsx +++ b/headless-rust/frontend/src/components/LapImageThumbnails.tsx @@ -11,7 +11,7 @@ interface LapImageThumbnailsProps { /** * Renders start/end lap capture thumbnails with a shared lightbox. - * Fetches image data lazily via the RPC and cancels pending fetches on unmount. + * Uses 120px compressed thumbnails over the network, opening full-resolution on click. */ export function LapImageThumbnails({ startImagePath, @@ -26,15 +26,16 @@ export function LapImageThumbnails({ let cancelled = false; setStartImageUrl(null); setEndImageUrl(null); + // ponytail: 120px mini-thumbnails for lap icons if (startImagePath) { getRpc() - .request.getImageData({ imagePath: startImagePath }) + .request.getImageData({ imagePath: startImagePath, width: 120, quality: 75 }) .then((data) => { if (!cancelled) setStartImageUrl(data); }) .catch(() => {}); } if (endImagePath) { getRpc() - .request.getImageData({ imagePath: endImagePath }) + .request.getImageData({ imagePath: endImagePath, width: 120, quality: 75 }) .then((data) => { if (!cancelled) setEndImageUrl(data); }) .catch(() => {}); } @@ -49,8 +50,8 @@ export function LapImageThumbnails({ {startImageUrl && (
diff --git a/headless-rust/frontend/src/routes/violations/ViolationGridTile.tsx b/headless-rust/frontend/src/routes/violations/ViolationGridTile.tsx index b1dc7e6..9030713 100644 --- a/headless-rust/frontend/src/routes/violations/ViolationGridTile.tsx +++ b/headless-rust/frontend/src/routes/violations/ViolationGridTile.tsx @@ -28,7 +28,8 @@ export function ViolationGridTile({ onDelete, onImageClick, }: ViolationGridTileProps) { - const { imageData, imageLoading } = useViolationImage(violation, skinEnabled); + // 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); @@ -41,6 +42,10 @@ export function ViolationGridTile({ 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); @@ -60,7 +65,7 @@ export function ViolationGridTile({ >
imageData && onImageClick(imageData)} + onClick={() => onImageClick(fullResUrl)} >
{ setDeleting(true); try { @@ -61,8 +66,8 @@ export function ViolationRow({ +

+ Network Architecture +

+ {activeMode === "field" ? ( + + ⚡ Field AP Mode + + ) : activeMode === "wifi-client" ? ( + + 📶 Wi-Fi Client Mode + + ) : ( + + 🌐 Standard DHCP + + )} +
+
+ + +
{/* Camera LAN */}
- Camera LAN (eth0) + + Camera LAN (eth0) + {network.cameraLan.status === "ok" ? ( - 192.168.1.100 OK + + 192.168.1.100 OK + ) : network.cameraLan.status === "ip_mismatch" ? ( - {network.cameraLan.ip || "Mismatch"} + + {network.cameraLan.ip || "Mismatch"} + ) : ( - Not Found + + Not Found + )}
IP: {network.cameraLan.ip || "Unassigned"}
-
Subnet: {network.cameraLan.subnet}
+
Subnet: {network.cameraLan.subnet} (MTU 9000)

- Dedicated interface for GigE Vision camera streaming. + Dedicated high-throughput interface for GigE Vision camera streaming.

- {/* Wi-Fi Hotspot */} + {/* Wi-Fi Interface */}
- Hotspot AP (wlan0) - {network.hotspotAp.status === "ok" ? ( - 192.168.4.1 OK + + {network.wifiClient ? "Wi-Fi Client (wlan0)" : "Hotspot AP (wlan0)"} + + {network.wifiClient ? ( + + STA Connected + + ) : network.hotspotAp.status === "ok" ? ( + + 192.168.4.1 AP + ) : network.hotspotAp.status === "ip_mismatch" ? ( - {network.hotspotAp.ip} + + {network.hotspotAp.ip} + ) : ( - Inactive + + Inactive + )}
-
IP: {network.hotspotAp.ip || "Unassigned"}
-
Web UI: :3000
+ {network.wifiClient ? ( + <> +
SSID: {network.wifiClient.ssid || "Connected"}
+
IP: {network.wifiClient.ip || "Waiting DHCP"}
+ {network.wifiClient.gateway &&
Gateway: {network.wifiClient.gateway}
} + + ) : ( + <> +
SSID: speedcamera (5GHz)
+
IP: {network.hotspotAp.ip || "192.168.4.1"}
+
Web UI: :3000
+ + )}

- Wi-Fi access point for remote browser controller. + {network.wifiClient + ? "Pi connected to home/lab router in Station mode (avoids AP firmware drops)." + : "Wi-Fi access point for remote browser controller."}

+ + {/* Mode Switcher Collapsible */} + + +
+

Switch Network Mode

+

+ Select an operating mode. Wi-Fi Client Mode connects the Pi to your external Wi-Fi router while keeping Camera LAN active on 192.168.1.100. +

+ +
+ + + +
+ + {targetMode === "wifi-client" && ( +
+
+ + +
+ + {scannedNetworks.length > 0 ? ( + + ) : ( + setManualSsid(e.target.value)} + /> + )} + + {selectedSsid === "__manual__" && ( + setManualSsid(e.target.value)} + /> + )} + +
+ + setWifiPassword(e.target.value)} + /> +
+
+ )} + + {targetMode === "field" && ( +
+
• Creates 5GHz Wi-Fi Hotspot: speedcamera
+
• Static Hotspot IP: 192.168.4.1
+
• Camera LAN Static IP: 192.168.1.100 (Jumbo MTU 9000)
+
+ )} + + {targetMode === "dhcp" && ( +
+ Resets both Ethernet and Wi-Fi interfaces to standard DHCP. +
+ )} + +
+ + +
+
+
+
); } diff --git a/headless-rust/frontend/src/shared/types.ts b/headless-rust/frontend/src/shared/types.ts index 32f31d6..f9b06de 100644 --- a/headless-rust/frontend/src/shared/types.ts +++ b/headless-rust/frontend/src/shared/types.ts @@ -2,7 +2,7 @@ export interface NetworkInterfaceDetail { name: string; - role: "camera-lan" | "hotspot-ap" | "other" | "loopback"; + role: "camera-lan" | "hotspot-ap" | "wifi-client" | "other" | "loopback"; address: string; family: string; netmask: string; @@ -11,26 +11,60 @@ export interface NetworkInterfaceDetail { 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: "field" | "wifi-client" | "dhcp" | "custom"; cameraLan: { interfaceName: string | null; ip: string | null; - expectedIp: "192.168.1.100"; - subnet: "192.168.1.0/24"; - status: "ok" | "ip_mismatch" | "missing"; + expectedIp: string; + subnet: string; + status: "ok" | "ip_mismatch" | "missing" | "inactive"; description: string; }; hotspotAp: { interfaceName: string | null; ip: string | null; - expectedIp: "192.168.4.1"; - subnet: "192.168.4.0/24"; - status: "ok" | "ip_mismatch" | "missing"; + expectedIp: string; + subnet: string; + status: "ok" | "ip_mismatch" | "missing" | "inactive"; description: string; }; + wifiClient?: WifiClientInfo | null; interfaces: NetworkInterfaceDetail[]; } +export interface WifiScanResult { + ssid: string; + signal: number; + security: string; + inUse: boolean; +} + +export interface ApplyNetworkModeInput { + mode: "field" | "wifi-client" | "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 @@ -464,6 +498,14 @@ export type SpeedcameraRPC = { params: Record; response: SystemNetworkSummary; }; + scanWifiNetworks: { + params: Record; + response: WifiScanResult[]; + }; + applyNetworkMode: { + params: ApplyNetworkModeInput; + response: NetworkOperationResult; + }; // Teable integration testTeableConnection: { diff --git a/headless-rust/src/main.rs b/headless-rust/src/main.rs index 6648fd5..f7a3be1 100644 --- a/headless-rust/src/main.rs +++ b/headless-rust/src/main.rs @@ -55,16 +55,26 @@ async fn main() -> Result<(), Box> { 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() ); - 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() - ); + 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 diff --git a/headless-rust/src/models.rs b/headless-rust/src/models.rs index 56a572c..ce2b97f 100644 --- a/headless-rust/src/models.rs +++ b/headless-rust/src/models.rs @@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize}; #[serde(rename_all = "camelCase")] pub struct NetworkInterfaceDetail { pub name: string_or_empty::StringOrEmpty, - pub role: String, // "camera-lan" | "hotspot-ap" | "other" | "loopback" + pub role: String, // "camera-lan" | "hotspot-ap" | "wifi-client" | "other" | "loopback" pub address: String, pub family: String, pub netmask: String, @@ -27,18 +27,71 @@ pub struct SubnetInfo { pub ip: Option, pub expected_ip: String, pub subnet: String, - pub status: String, // "ok" | "ip_mismatch" | "missing" + 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, // "field" | "wifi-client" | "dhcp" | "custom" 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 { + "field".to_string() +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WifiScanResult { + pub ssid: String, + 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, // "field" | "wifi-client" | "client" | "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 { diff --git a/headless-rust/src/network/mod.rs b/headless-rust/src/network/mod.rs index f95e57e..0822d56 100644 --- a/headless-rust/src/network/mod.rs +++ b/headless-rust/src/network/mod.rs @@ -1,10 +1,17 @@ -use crate::models::{NetworkInterfaceDetail, SubnetInfo, SystemNetworkSummary}; +use crate::models::{ + ApplyNetworkModeInput, NetworkInterfaceDetail, NetworkOperationResult, SubnetInfo, + SystemNetworkSummary, WifiClientInfo, WifiScanResult, +}; use std::collections::HashMap; +use std::path::Path; +use std::process::Command; 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; // Use nix getifaddrs to inspect active IPv4 network interfaces if let Ok(ifaddrs) = nix::ifaddrs::getifaddrs() { @@ -27,16 +34,22 @@ pub fn get_system_network_summary() -> SystemNetworkSummary { 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" || ip.starts_with("192.168.4."); + 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()); + } + let role = if is_loopback { "loopback" } else if is_camera_ip || is_eth_name { "camera-lan" - } else if is_hotspot_ip || is_wifi_name { + } else if is_hotspot_ip { "hotspot-ap" + } else if is_wifi_name { + "wifi-client" } else { "other" }; @@ -69,8 +82,10 @@ pub fn get_system_network_summary() -> SystemNetworkSummary { camera_lan_iface = Some(detail.clone()); } - if role == "hotspot-ap" && (hotspot_ap_iface.is_none() || ip == "192.168.4.1") { + if role == "hotspot-ap" { hotspot_ap_iface = Some(detail.clone()); + } else if role == "wifi-client" { + wifi_client_iface = Some(detail.clone()); } interfaces.push(detail); @@ -83,13 +98,45 @@ pub fn get_system_network_summary() -> SystemNetworkSummary { Some(_) => "ip_mismatch", }; - let hotspot_status = match &hotspot_ap_iface { - None => "missing", - Some(iface) if iface.address == "192.168.4.1" => "ok", - Some(_) => "ip_mismatch", + // Determine Wi-Fi active connection mode & details + let (active_ssid, signal_dbm, power_save_status, default_gateway) = query_wifi_runtime_info( + detected_wifi_name.as_deref().unwrap_or("wlan0") + ); + + let (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" }; + ( + "field".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(), + }; + ( + "wifi-client".to_string(), + "inactive".to_string(), + Some(client_info), + ) + } else { + ( + "dhcp".to_string(), + "missing".to_string(), + None, + ) }; SystemNetworkSummary { + mode, 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()), @@ -99,13 +146,234 @@ pub fn get_system_network_summary() -> SystemNetworkSummary { 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()), + interface_name: hotspot_ap_iface.as_ref().map(|i| i.name.clone()).or_else(|| detected_wifi_name.clone()), 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.to_string(), + status: hotspot_status, description: "Wi-Fi Access Point & Remote Web UI Control (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); + // Example: default via 192.168.178.1 dev wlan0 proto dhcp src 192.168.178.50 metric 600 + 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 results: Vec = Vec::new(); + let mut seen_ssids: HashMap = HashMap::new(); + + if let Ok(output) = Command::new("nmcli") + .args(["-t", "-f", "SSID,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() { + let parts: Vec<&str> = line.split(':').collect(); + if parts.len() >= 4 { + let ssid = parts[0].trim().to_string(); + if ssid.is_empty() || ssid == "--" { + continue; + } + let signal = parts[1].parse::().unwrap_or(0); + let security = parts[2].trim().to_string(); + let in_use = parts[3].trim().eq_ignore_ascii_case("yes") || parts[3].trim() == "*"; + + let item = WifiScanResult { + ssid: ssid.clone(), + 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; + } + } else { + seen_ssids.insert(ssid, item); + } + } + } + } + } + + results = 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 (Field AP, Wi-Fi Client, or 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() { + "field" | "ap" => { + cmd.arg("field"); + } + "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); + } + } + } + "dhcp" | "reset" => { + cmd.arg("dhcp"); + } + other => { + return NetworkOperationResult { + success: false, + mode: input.mode.clone(), + message: format!("Unknown network mode '{}'. Use 'field', 'wifi-client', or 'dhcp'.", 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/web/rpc.rs b/headless-rust/src/web/rpc.rs index 0d63ddb..5f614b3 100644 --- a/headless-rust/src/web/rpc.rs +++ b/headless-rust/src/web/rpc.rs @@ -630,6 +630,22 @@ async fn dispatch_method(ctx: &RpcContext, method: &str, params: Value) -> Resul 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()) + } + // ─── Teable ─────────────────────────────────────────────────────────── "testTeableConnection" => { let url = params["url"].as_str().ok_or("Missing url")?; From 17917822ac62d3f83206cf40e19aee3823d935d7 Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Tue, 25 Aug 2026 23:56:29 +0200 Subject: [PATCH 60/65] feat: Update README for headless-rust module with enhanced Wi-Fi operation mode details and improved deployment instructions --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 977c77a..c1d0645 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ An end-to-end vehicle speed measurement, GigE Vision camera capture, and remote | Directory | Description | | --------- | ----------- | -| [**`headless-rust`**](./headless-rust) | **(Recommended)** High-performance single-binary headless daemon and responsive Web UI controller for Raspberry Pi 5 built with Rust (Rocket 0.5, native Aravis C FFI, SQLite) and embedded React + Vite frontend. Creates standalone Wi-Fi hotspot (`192.168.4.1`) & GigE Vision Camera LAN (`192.168.1.100`). | +| [**`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. | @@ -25,13 +25,13 @@ 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 Field Hotspot Mode or Home LAN) +# 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 in the field: +# 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 modes, offline field use, dependencies, and local mock testing, see the [**Headless Rust Documentation**](./headless-rust/README.md). +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). From 2fcd855646784894572478ffce94c945ae02cb29 Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Tue, 25 Aug 2026 23:56:39 +0200 Subject: [PATCH 61/65] feat: Update README with enhanced network operation modes and onboarding flow details --- headless-rust/README.md | 294 +++++++++++++++++++--------------------- 1 file changed, 139 insertions(+), 155 deletions(-) diff --git a/headless-rust/README.md b/headless-rust/README.md index 020bf47..cc09f50 100644 --- a/headless-rust/README.md +++ b/headless-rust/README.md @@ -2,18 +2,21 @@ 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. Creates a standalone Wi-Fi hotspot for laptops, tablets, and phones to connect and manage the system via web browser while communicating with industrial GigE cameras on a dedicated Ethernet subnet. +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 & Dual-Subnet Network Setup +## Architecture & Network Operation Modes ``` ┌────────────────────────────────────────────────────────────────────────┐ │ Raspberry Pi 5 (Raspberry Pi OS Lite ARM64) │ │ │ -│ • eth0 (Camera LAN): 192.168.1.100/24 <── GigE Vision HIKROBOT │ -│ • wlan0 (Hotspot AP): 192.168.4.1/24 <── Web UI Browser Clients │ +│ • 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) │ @@ -24,19 +27,56 @@ Engineered specifically for **Raspberry Pi 5 with Raspberry Pi OS Lite** (zero d │ ├── SQLite Database (rusqlite WAL mode @ ~/.speedcamera) │ │ └── Pure Rust Poliscan Overlay Renderer (image + imageproc) │ └───────────────────────┬─────────────────────────────▲──────────────────┘ - │ Wi-Fi AP │ Ethernet Cable + │ Wi-Fi (AP or Client) │ Ethernet Cable ▼ │ ┌──────────────────────────────────────────┐ ┌──────────────────────────┐ │ Client Device (Phone / Tablet / Laptop) │ │ Industrial GigE Camera │ │ │ │ │ -│ • Wi-Fi SSID: speedcamera │ │ • Subnet: 192.168.1.0/24 │ -│ • Open: http://192.168.4.1:3000 │ │ • GenICam / Aravis 0.8 │ -│ • Live Radar, Live View, Settings, Laps │ │ • Direct link to eth0 │ +│ • 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`)** | @@ -47,20 +87,84 @@ Engineered specifically for **Raspberry Pi 5 with Raspberry Pi OS Lite** (zero d | **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 following tools and packages are required. +To set up a fresh Raspberry Pi OS image (recommended: **Raspberry Pi OS Lite 64-bit**), the automated installer handles all steps: -> [!TIP] -> The automated installer `bun run install:pi` (or `./scripts/install-rpi.sh` directly on the Pi) automatically checks and installs all of these dependencies for you. +```bash +cd headless-rust +bun run install:pi pi@raspberrypi.local +``` -### 1. System Packages (APT) +### Manual Dependency Reference +#### 1. System Packages (APT) ```bash sudo apt-get update sudo apt-get install -y \ @@ -73,6 +177,8 @@ sudo apt-get install -y \ build-essential \ esptool \ network-manager \ + dnsmasq \ + iptables \ curl \ unzip \ git \ @@ -81,28 +187,19 @@ sudo apt-get install -y \ libsqlite3-dev ``` -### 2. Rust Toolchain (`rustup`) - -Required for building and compiling the native daemon on ARM64: - +#### 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`) - -Required on your developer laptop (and optional on the Pi) for building the React/Vite frontend bundle and running automation/test scripts: - +#### 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 - -Industrial GigE Vision cameras stream high-throughput packet bursts. Increase Linux UDP socket buffer limits while enabling FQ-CoDel smart queueing to prevent Wi-Fi bufferbloat: - +#### 4. GigE Vision Network Socket Buffer & FQ-CoDel Tuning ```bash sudo bash -c 'cat > /etc/sysctl.d/60-gige-camera.conf < [!IMPORTANT] -> **Internet Requirement for Build/Deploy**: Because the Pi compiles dependencies and pulls from Git, `bun run install:pi` and `bun run deploy:pi` must be executed while the Pi is in **Home LAN / DHCP** or **Client Wi-Fi Mode** (with internet access). -> If your Pi is currently in standalone **Field Mode** (`192.168.4.1` hotspot), connect the Pi to your Wi-Fi router first via SSH: -> ```bash -> ssh pi@192.168.4.1 '~/speedcamera/headless-rust/scripts/setup-network.sh internet "MyHomeWiFi" "MyPassword"' -> ``` -> Or plug in an Ethernet cable and run: -> ```bash -> ssh pi@192.168.4.1 '~/speedcamera/headless-rust/scripts/setup-network.sh dhcp' -> ``` - -``` -┌────────────────────────────────────────────────────────────────────────┐ -│ Command │ Purpose │ -├──────────────────────────────┼─────────────────────────────────────────┤ -│ bun run install:pi [target] │ Fresh Pi install on Home LAN / DHCP │ -│ bun run deploy:pi [target] │ Upgrade existing Pi (in Internet Mode) │ -│ bun run cleanup:pi [target] │ Complete teardown & restore DHCP network│ -└──────────────────────────────┴─────────────────────────────────────────┘ -``` - ---- - -### Scenario 1: Fresh Pi Setup (Home LAN / Wi-Fi with DHCP) - -Use this scenario when you have a freshly flashed Raspberry Pi connected to your home router / Wi-Fi via DHCP and want to provision the complete speedcamera suite. - -#### Run from your laptop: -```bash -cd headless-rust - -# Standard fresh installation (SSH key auth): -bun run install:pi pi@raspberrypi.local - -# With password prompt (if SSH keys are not configured): -bun run install:pi pi@raspberrypi.local --password - -# Using direct IP and automatically switching to Field Mode at the very end: -bun run install:pi pi@192.168.1.50 --field - -# Stay in Home LAN mode (skip field network setup): -bun run install:pi pi@raspberrypi.local --lan - -# Deploy a specific branch: -bun run install:pi pi@raspberrypi.local --branch feature/headless -``` - -#### What this command does: -1. Connects to the Raspberry Pi over SSH and verifies internet reachability. -2. Clones or pulls the `speedcamera` git repository directly to `~/speedcamera` on the Pi. -3. Updates Pi system packages (`libaravis-0.8-0`, `libaravis-dev`, `libglib2.0-dev`, `libudev-dev`, `build-essential`, `esptool`, `network-manager`, etc.). -4. Installs the Rust toolchain (`rustup`) and Bun runtime on the Pi. -5. Builds the frontend assets (`bun run build`) and compiles the release binary (`cargo build --release`) natively on Pi 5. -6. Registers, enables, and starts the `speedcamera.service` systemd daemon. -7. **Only after all software and builds succeed**: Transitions network mode to Field Mode if requested (`--field`). - ---- - -### Scenario 2: Upgrading an Existing Installation - -Use this scenario to push code updates to an already configured Pi while connected to your **Home LAN** or **Client Wi-Fi**. - -#### Run from your laptop: -```bash -cd headless-rust - -# Deploy to Pi on Home LAN: -bun run deploy:pi pi@raspberrypi.local - -# With password authentication: -bun run deploy:pi pi@raspberrypi.local --password - -# Force rebuild frontend & Rust binary: -bun run deploy:pi pi@raspberrypi.local --build -``` - -#### What this command does: -1. Connects to the Pi via SSH and verifies active internet connectivity. -2. Runs `git pull` in `~/speedcamera` to fetch and apply the latest commits. -3. Automatically rebuilds the frontend bundle on the Pi if frontend files changed. -4. Automatically recompiles the native Rust release binary on the Pi if Rust code or frontend bundle changed. -5. Restarts `speedcamera.service` and verifies that the daemon is active and running. -6. Preserves existing network configuration without causing unexpected disconnections. - ---- - -### Scenario 3: Complete Cleanup & Network Reset - -Use this scenario to completely uninstall Speedcamera, remove systemd services, delete application files, and restore standard DHCP networking on Ethernet and Wi-Fi. - -#### Option A: Remote cleanup from your laptop ```bash -cd headless-rust +# 1. Start Open AP Setup Hotspot (192.168.4.1, no password, captive portal active) +sudo ~/speedcamera/headless-rust/scripts/setup-network.sh ap -# Clean up speedcamera and restore DHCP network: -bun run cleanup:pi pi@raspberrypi.local +# 2. Connect to Wi-Fi network in Client Mode (normal operation) +sudo ~/speedcamera/headless-rust/scripts/setup-network.sh client "MyHomeWiFi" "SecretPassword123" -# Clean up in Field Mode and purge all SQLite databases/images: -bun run cleanup:pi pi@192.168.4.1 --password --purge +# 3. Boot auto-mode (reconnects saved client Wi-Fi, falls back to AP if unreachable) +sudo ~/speedcamera/headless-rust/scripts/setup-network.sh auto -# Non-interactive cleanup: -bun run cleanup:pi pi@raspberrypi.local --yes --purge -``` - -#### Option B: Direct cleanup on the Raspberry Pi -```bash -# SSH into Pi -ssh pi@raspberrypi.local - -# Run cleanup script -~/speedcamera/headless-rust/scripts/cleanup-pi.sh - -# Or with complete data purge (database & images): -~/speedcamera/headless-rust/scripts/cleanup-pi.sh --purge --yes -``` +# 4. Forget saved Wi-Fi credentials and return to Open AP Setup mode +sudo ~/speedcamera/headless-rust/scripts/setup-network.sh forget ---- - -## Network Mode Management (`setup-network.sh`) - -You can switch the Pi's networking mode at any time via the Web UI Settings (**Camera** tab) or via the network management script: +# 5. Set Ethernet interface to dedicated Camera LAN (Static 192.168.1.100, MTU 9000) +sudo ~/speedcamera/headless-rust/scripts/setup-network.sh lan-camera -```bash -# 1. Wi-Fi Client Mode (External Wi-Fi + Direct GigE Camera LAN 192.168.1.100) -# Connects Pi as Wi-Fi client (avoids Broadcom AP radio drops) while preserving isolated Camera LAN: -~/speedcamera/headless-rust/scripts/setup-network.sh client "MyHomeWiFi" "SecretPassword123" - -# 2. Standalone Field Mode (Camera LAN 192.168.1.100 + Standalone 5GHz Hotspot AP 192.168.4.1) -~/speedcamera/headless-rust/scripts/setup-network.sh field +# 6. Set Ethernet interface to standard DHCP (for wired internet/updates) +sudo ~/speedcamera/headless-rust/scripts/setup-network.sh lan-dhcp -# 3. Scan nearby Wi-Fi networks (SSIDs, signal quality, security) +# 7. Scan nearby visible Wi-Fi networks (SSID, BSSID, channel, signal, security) ~/speedcamera/headless-rust/scripts/setup-network.sh scan -# 4. Revert Ethernet and Wi-Fi to standard DHCP -~/speedcamera/headless-rust/scripts/setup-network.sh dhcp +# 8. Revert both Ethernet and Wi-Fi to standard DHCP +sudo ~/speedcamera/headless-rust/scripts/setup-network.sh dhcp -# 5. Check active network mode, IP addresses, power management, and internet reachability +# 9. Check active network status, IP addresses, power management, and internet reachability ~/speedcamera/headless-rust/scripts/setup-network.sh status ``` @@ -292,8 +278,6 @@ sudo systemctl start speedcamera ## Local Development & Testing -You can develop and test the entire system on your local laptop without physical hardware using mock mode: - ```bash cd headless-rust From 4b16d46b617cd897eafccc60b820fecca5d96ef2 Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Tue, 25 Aug 2026 23:56:45 +0200 Subject: [PATCH 62/65] feat: Add qrcode.react dependency for QR code generation support --- headless-rust/bun.lock | 3 +++ headless-rust/package.json | 1 + 2 files changed, 4 insertions(+) diff --git a/headless-rust/bun.lock b/headless-rust/bun.lock index 6d99dbb..5a3efd5 100644 --- a/headless-rust/bun.lock +++ b/headless-rust/bun.lock @@ -15,6 +15,7 @@ "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", @@ -879,6 +880,8 @@ "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=="], diff --git a/headless-rust/package.json b/headless-rust/package.json index beb839b..43484ae 100644 --- a/headless-rust/package.json +++ b/headless-rust/package.json @@ -33,6 +33,7 @@ "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", From cf0e1ac5b917344dbad69b821d2f317b0cdb6ab9 Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Tue, 25 Aug 2026 23:57:07 +0200 Subject: [PATCH 63/65] feat: Enhance network modes and configurations - Updated SystemNetworkSummary to include new modes: "ap", "client", and additional properties for MAC addresses. - Modified install-rpi.sh and setup-network.sh scripts to reflect changes in network modes, including Open AP Setup Mode. - Added functions for applying Ethernet DHCP and forgetting saved Wi-Fi credentials. - Improved handling of network modes in models and network modules, including auto-connection logic. - Updated web routes to redirect captive portal probes to the new setup page. - Introduced new RPC methods for forgetting Wi-Fi and setting Ethernet modes. --- .../src/components/WifiConnectDialog.tsx | 194 ++++++ .../frontend/src/routes/settings.tsx | 8 +- .../src/routes/settings/CameraTab.tsx | 323 +-------- .../src/routes/settings/NetworkTab.tsx | 652 ++++++++++++++++++ headless-rust/frontend/src/shared/types.ts | 18 +- headless-rust/scripts/install-rpi.sh | 25 +- headless-rust/scripts/setup-network.sh | 169 +++-- headless-rust/src/models.rs | 26 +- headless-rust/src/network/mod.rs | 117 +++- headless-rust/src/web/routes.rs | 32 +- headless-rust/src/web/rpc.rs | 25 + 11 files changed, 1161 insertions(+), 428 deletions(-) create mode 100644 headless-rust/frontend/src/components/WifiConnectDialog.tsx create mode 100644 headless-rust/frontend/src/routes/settings/NetworkTab.tsx 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/routes/settings.tsx b/headless-rust/frontend/src/routes/settings.tsx index 1efef51..7a08e12 100644 --- a/headless-rust/frontend/src/routes/settings.tsx +++ b/headless-rust/frontend/src/routes/settings.tsx @@ -3,6 +3,7 @@ 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"; @@ -18,7 +19,7 @@ function SettingsPage() {
- {(["device", "camera", "speed-camera", "lap-timer"] as const).map((tab) => ( + {(["device", "network", "camera", "speed-camera", "lap-timer"] as const).map((tab) => ( {tab === "device" ? "Device" + : tab === "network" + ? "Network" : tab === "camera" ? "Camera" : tab === "speed-camera" @@ -43,6 +46,9 @@ function SettingsPage() { + + + diff --git a/headless-rust/frontend/src/routes/settings/CameraTab.tsx b/headless-rust/frontend/src/routes/settings/CameraTab.tsx index e08817e..7606c21 100644 --- a/headless-rust/frontend/src/routes/settings/CameraTab.tsx +++ b/headless-rust/frontend/src/routes/settings/CameraTab.tsx @@ -1,18 +1,16 @@ -import { useState, useEffect } from "react"; +import { useState } from "react"; import type { ChangeEvent } from "react"; import { toast } from "sonner"; import { useAppStore } from "@/stores/useAppStore"; -import type { HwControl, SystemNetworkSummary, WifiScanResult } from "@/shared/types"; -import { getRpc } from "@/lib/rpc"; +import type { HwControl } from "@/shared/types"; import { Button } from "@/components/ui/button"; -import { Input } from "@/components/ui/input"; 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, Network } from "lucide-react"; +import { Upload, CheckCircle2, XCircle, ChevronDown } from "lucide-react"; export function CameraTab() { const connected = useAppStore((s) => s.cameraConnected); @@ -83,8 +81,6 @@ export function CameraTab() {
- -

Load .mfs Config

@@ -344,316 +340,3 @@ function HwControlRow({ control, currentValue, saving, onChange }: HwControlRowP
); } - -function NetworkStatusSection() { - const [network, setNetwork] = useState(null); - const [loading, setLoading] = useState(false); - const [showConfig, setShowConfig] = useState(false); - - // Network Switcher State - const [targetMode, setTargetMode] = useState<"field" | "wifi-client" | "dhcp">("wifi-client"); - const [scannedNetworks, setScannedNetworks] = useState([]); - const [scanning, setScanning] = useState(false); - const [selectedSsid, setSelectedSsid] = useState(""); - const [manualSsid, setManualSsid] = useState(""); - const [wifiPassword, setWifiPassword] = useState(""); - const [applying, setApplying] = useState(false); - - const fetchNetwork = () => { - setLoading(true); - getRpc() - .request.getNetworkInfo({}) - .then(setNetwork) - .catch(() => {}) - .finally(() => setLoading(false)); - }; - - const handleScanWifi = async () => { - setScanning(true); - try { - const list = await getRpc().request.scanWifiNetworks({}); - setScannedNetworks(list); - if (list.length > 0 && !selectedSsid) { - setSelectedSsid(list[0].ssid); - } - toast.success(`Found ${list.length} Wi-Fi networks`); - } catch { - toast.error("Failed to scan Wi-Fi networks"); - } finally { - setScanning(false); - } - }; - - const handleApplyMode = async () => { - setApplying(true); - const effectiveSsid = selectedSsid === "__manual__" ? manualSsid : selectedSsid; - - if (targetMode === "wifi-client" && !effectiveSsid.trim()) { - toast.error("Please select or enter a Wi-Fi SSID to connect."); - setApplying(false); - return; - } - - try { - const res = await getRpc().request.applyNetworkMode({ - mode: targetMode, - ssid: effectiveSsid, - password: wifiPassword, - }); - - if (res.success) { - toast.success(res.message); - if (targetMode === "field") { - toast.info("Switched to Field Mode: Connect Wi-Fi to 'speedcamera' at http://192.168.4.1:3000"); - } else if (targetMode === "wifi-client") { - toast.info(`Switched to Wi-Fi Client: Connected to '${effectiveSsid}'. Check router for assigned IP.`); - } - setTimeout(fetchNetwork, 3000); - } else { - toast.error(res.message); - } - } catch (err: any) { - toast.error(err?.message || "Failed to switch network mode"); - } finally { - setApplying(false); - } - }; - - useEffect(() => { - fetchNetwork(); - }, []); - - if (!network) return null; - - const activeMode = network.mode || (network.wifiClient ? "wifi-client" : "field"); - - return ( -
-
-
- -

- Network Architecture -

- {activeMode === "field" ? ( - - ⚡ Field AP Mode - - ) : activeMode === "wifi-client" ? ( - - 📶 Wi-Fi Client Mode - - ) : ( - - 🌐 Standard DHCP - - )} -
-
- - -
-
- -
- {/* Camera LAN */} -
-
- - Camera LAN (eth0) - - {network.cameraLan.status === "ok" ? ( - - 192.168.1.100 OK - - ) : network.cameraLan.status === "ip_mismatch" ? ( - - {network.cameraLan.ip || "Mismatch"} - - ) : ( - - Not Found - - )} -
-
-
IP: {network.cameraLan.ip || "Unassigned"}
-
Subnet: {network.cameraLan.subnet} (MTU 9000)
-
-

- Dedicated high-throughput interface for GigE Vision camera streaming. -

-
- - {/* Wi-Fi Interface */} -
-
- - {network.wifiClient ? "Wi-Fi Client (wlan0)" : "Hotspot AP (wlan0)"} - - {network.wifiClient ? ( - - STA Connected - - ) : network.hotspotAp.status === "ok" ? ( - - 192.168.4.1 AP - - ) : network.hotspotAp.status === "ip_mismatch" ? ( - - {network.hotspotAp.ip} - - ) : ( - - Inactive - - )} -
-
- {network.wifiClient ? ( - <> -
SSID: {network.wifiClient.ssid || "Connected"}
-
IP: {network.wifiClient.ip || "Waiting DHCP"}
- {network.wifiClient.gateway &&
Gateway: {network.wifiClient.gateway}
} - - ) : ( - <> -
SSID: speedcamera (5GHz)
-
IP: {network.hotspotAp.ip || "192.168.4.1"}
-
Web UI: :3000
- - )} -
-

- {network.wifiClient - ? "Pi connected to home/lab router in Station mode (avoids AP firmware drops)." - : "Wi-Fi access point for remote browser controller."} -

-
-
- - {/* Mode Switcher Collapsible */} - - -
-

Switch Network Mode

-

- Select an operating mode. Wi-Fi Client Mode connects the Pi to your external Wi-Fi router while keeping Camera LAN active on 192.168.1.100. -

- -
- - - -
- - {targetMode === "wifi-client" && ( -
-
- - -
- - {scannedNetworks.length > 0 ? ( - - ) : ( - setManualSsid(e.target.value)} - /> - )} - - {selectedSsid === "__manual__" && ( - setManualSsid(e.target.value)} - /> - )} - -
- - setWifiPassword(e.target.value)} - /> -
-
- )} - - {targetMode === "field" && ( -
-
• Creates 5GHz Wi-Fi Hotspot: speedcamera
-
• Static Hotspot IP: 192.168.4.1
-
• Camera LAN Static IP: 192.168.1.100 (Jumbo MTU 9000)
-
- )} - - {targetMode === "dhcp" && ( -
- Resets both Ethernet and Wi-Fi interfaces to standard DHCP. -
- )} - -
- - -
-
-
-
-
- ); -} 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/shared/types.ts b/headless-rust/frontend/src/shared/types.ts index f9b06de..015831a 100644 --- a/headless-rust/frontend/src/shared/types.ts +++ b/headless-rust/frontend/src/shared/types.ts @@ -24,7 +24,11 @@ export interface WifiClientInfo { } export interface SystemNetworkSummary { - mode: "field" | "wifi-client" | "dhcp" | "custom"; + 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; @@ -47,13 +51,15 @@ export interface SystemNetworkSummary { export interface WifiScanResult { ssid: string; + bssid?: string; + channel?: number; signal: number; security: string; inUse: boolean; } export interface ApplyNetworkModeInput { - mode: "field" | "wifi-client" | "client" | "dhcp"; + mode: "ap" | "client" | "forget" | "lan-camera" | "lan-dhcp" | "field" | "wifi-client" | "dhcp"; ssid?: string; password?: string; } @@ -506,6 +512,14 @@ export type SpeedcameraRPC = { params: ApplyNetworkModeInput; response: NetworkOperationResult; }; + forgetWifi: { + params: Record; + response: NetworkOperationResult; + }; + setEthernetMode: { + params: { mode: "camera-lan" | "lan-dhcp" }; + response: NetworkOperationResult; + }; // Teable integration testTeableConnection: { diff --git a/headless-rust/scripts/install-rpi.sh b/headless-rust/scripts/install-rpi.sh index b2aa231..bde83bc 100755 --- a/headless-rust/scripts/install-rpi.sh +++ b/headless-rust/scripts/install-rpi.sh @@ -264,16 +264,16 @@ if [ -n "$CLIENT_SSID" ]; then fi if [ "$AUTO_FIELD" = true ]; then - echo "[*] Switching network to Standalone Field Mode (Camera LAN + Hotspot AP)..." + 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" field + "${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 field deployment, run:" - echo " ~/speedcamera/headless-rust/scripts/setup-network.sh field" + 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 @@ -283,26 +283,27 @@ fi if [ -t 0 ]; then echo "" echo "=========================================================================" - echo " FIELD NETWORK CONFIGURATION (Camera LAN + Hotspot AP)" + 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 Standalone Field Mode:" + 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) -> Standalone Hotspot AP 192.168.4.1 (SSID: speedcamera)" + 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 Standalone Field Mode now? (y/N) " -n 1 -r + 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" - "${PROJECT_DIR}/scripts/setup-network.sh" field + "${PROJECT_DIR}/scripts/setup-network.sh" ap else - echo "Skipping Field Mode network switch for now." - echo "Run anytime later: ~/speedcamera/headless-rust/scripts/setup-network.sh field" + 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 field mode when ready: ~/speedcamera/headless-rust/scripts/setup-network.sh field" + 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 index 2bd9d7c..f3f5606 100755 --- a/headless-rust/scripts/setup-network.sh +++ b/headless-rust/scripts/setup-network.sh @@ -61,6 +61,18 @@ EOF' 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 @@ -87,20 +99,21 @@ EOF" 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_field_mode() { - echo ">>> Applying FIELD MODE (Standalone Offline Dual-Subnet):" - echo " 1. Camera LAN (${ETH_IFACE}) -> Static IP 192.168.1.100/24" - echo " 2. Hotspot AP (${WIFI_IFACE}) -> Static IP 192.168.4.1/24 (SSID: speedcamera)" - echo " NOTE: In this mode, Pi operates standalone/offline." +apply_ap_mode() { + echo ">>> Applying SETUP / AP MODE (Open Hotspot + Captive Portal):" + echo " 1. Wi-Fi Hotspot (${WIFI_IFACE}) -> Open AP (SSID: speedcamera, 5GHz, 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. Configure Camera LAN - apply_camera_lan_config + # 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 - # 2. Configure Wi-Fi Hotspot AP (5GHz Band A, Channel 36 to avoid 2.4GHz congestion) - echo "[*] Configuring 5GHz Wi-Fi Hotspot AP on ${WIFI_IFACE}..." + # Configure Open 5GHz Wi-Fi Hotspot AP (Band A, Channel 36, NO password) + echo "[*] Configuring Open 5GHz Wi-Fi Hotspot AP on ${WIFI_IFACE}..." SSID="speedcamera" - PASS="speedcamerapass" enforce_wifi_powersave_off @@ -116,9 +129,7 @@ apply_field_mode() { 802-11-wireless.channel 36 \ 802-11-wireless.powersave 2 \ ipv4.method shared \ - ipv4.addresses 192.168.4.1/24 \ - wifi-sec.key-mgmt wpa-psk \ - wifi-sec.psk "${PASS}" + ipv4.addresses 192.168.4.1/24 # Disable MAC randomization which can trigger background radio resets sudo nmcli connection modify "Speedcamera-Hotspot" 802-11-wireless.mac-address-randomization 1 2>/dev/null || true @@ -126,8 +137,8 @@ apply_field_mode() { sudo nmcli connection up "Speedcamera-Hotspot" 2>/dev/null || echo "Note: Hotspot initialized." - # Configure DNS interception for OS connectivity checks (Windows NCSI, Fedora hotspot, Linux ping) - echo "[*] Configuring DNS interception for OS internet probes (192.168.4.1)..." + # 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 Rust daemon + # 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 for Wi-Fi + # 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 echo "" echo "=========================================================" - echo " Field Mode Active!" - echo " • 5GHz Wi-Fi Hotspot: SSID '${SSID}' (Password: '${PASS}')" + echo " AP / Setup Mode Active!" + echo " • Open 5GHz Hotspot: SSID '${SSID}' (No password)" echo " • Web UI: http://192.168.4.1:3000" echo " • Camera LAN: http://192.168.1.100:3000" echo "=========================================================" @@ -168,29 +179,30 @@ apply_client_mode() { exit 1 fi - echo ">>> Applying WI-FI CLIENT + CAMERA LAN MODE:" - echo " 1. Camera LAN (${ETH_IFACE}) -> Static IP 192.168.1.100/24 (Direct GigE Camera link)" - echo " 2. Wi-Fi Client (${WIFI_IFACE}) -> Connecting to SSID: '${WIFI_SSID}' (DHCP)" - echo " NOTE: Allows testing if AP mode was root cause of connectivity issues." + 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 "" - # 1. Configure Camera LAN (isolated static 192.168.1.100) - apply_camera_lan_config + # 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 - # 2. Enforce Wi-Fi Power-Save OFF + # Enforce Wi-Fi Power-Save OFF enforce_wifi_powersave_off - # 3. Clean up fake-internet DNS interception and port 80 redirect so real internet/DNS works + # 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 - # 4. Tear down Hotspot AP profile + # 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 - # 5. Scan and connect to external Wi-Fi network + # Scan and connect to external Wi-Fi network sudo nmcli dev wifi rescan 2>/dev/null || true sleep 1 @@ -208,10 +220,12 @@ apply_client_mode() { 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 + # 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 @@ -225,7 +239,7 @@ apply_client_mode() { echo "" echo "=========================================================" - echo " Wi-Fi Client + Camera LAN Mode Active!" + 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}" @@ -238,6 +252,39 @@ apply_client_mode() { 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..." @@ -257,7 +304,7 @@ apply_dhcp_mode() { scan_wifi_networks() { echo "--- Scanning Visible Wi-Fi Networks ---" sudo nmcli dev wifi rescan 2>/dev/null || true - nmcli -f IN-USE,SSID,MODE,CHAN,RATE,SIGNAL,BARS,SECURITY dev wifi list || true + nmcli -f IN-USE,SSID,BSSID,CHAN,SIGNAL,SECURITY dev wifi list || true } show_status() { @@ -265,6 +312,7 @@ show_status() { 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 @@ -275,19 +323,24 @@ show_status() { 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 ] && [ "$HAS_CAM_LAN" -eq 1 ]; then - echo "Mode: FIELD MODE (Hotspot AP 192.168.4.1 + Camera LAN 192.168.1.100)" - elif [ "$HAS_CLIENT" -eq 1 ] && [ "$HAS_CAM_LAN" -eq 1 ]; then - echo "Mode: WI-FI CLIENT MODE (External Wi-Fi + Camera LAN 192.168.1.100)" - elif [ "$HAS_HOTSPOT" -eq 1 ]; then - echo "Mode: HOTSPOT AP ONLY" + 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 "Mode: WI-FI CLIENT ONLY" - elif nmcli -t -f NAME connection show --active 2>/dev/null | grep -qx "Speedcamera-Ethernet-DHCP"; then - echo "Mode: STANDARD DHCP" + echo "Wi-Fi Mode: CLIENT (Connected to external router)" else - echo "Mode: CUSTOM / DYNAMIC" + 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 "" @@ -311,19 +364,35 @@ show_status() { if ping -c 1 -W 2 1.1.1.1 &>/dev/null; then echo "Status: ONLINE (Internet reachable)" else - echo "Status: OFFLINE (Isolated field mode or no default route)" + echo "Status: OFFLINE (Isolated AP setup mode or no default route)" fi } case "$MODE" in - field|ap) - apply_field_mode + 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 ;; @@ -337,11 +406,15 @@ case "$MODE" in ;; *) - echo "Usage: $0 {field|client [PASS]|scan|dhcp|status}" + echo "Usage: $0 {ap|client [PASS]|auto|forget|lan-camera|lan-dhcp|scan|dhcp|status}" echo "" echo "Commands:" - echo " field Set Camera LAN (192.168.1.100) + Hotspot AP (192.168.4.1) [Standalone/Field]" - echo " client [PASS] Set Camera LAN (192.168.1.100) + Connect Wi-Fi Client to router [Client Mode]" + 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" diff --git a/headless-rust/src/models.rs b/headless-rust/src/models.rs index ce2b97f..07aaca5 100644 --- a/headless-rust/src/models.rs +++ b/headless-rust/src/models.rs @@ -51,7 +51,15 @@ pub struct WifiClientInfo { #[serde(rename_all = "camelCase")] pub struct SystemNetworkSummary { #[serde(default = "default_network_mode")] - pub mode: String, // "field" | "wifi-client" | "dhcp" | "custom" + 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")] @@ -60,13 +68,25 @@ pub struct SystemNetworkSummary { } fn default_network_mode() -> String { - "field".to_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, @@ -75,7 +95,7 @@ pub struct WifiScanResult { #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplyNetworkModeInput { - pub mode: String, // "field" | "wifi-client" | "client" | "dhcp" + pub mode: String, // "ap" | "client" | "forget" | "lan-camera" | "lan-dhcp" | "dhcp" #[serde(default)] pub ssid: Option, #[serde(default)] diff --git a/headless-rust/src/network/mod.rs b/headless-rust/src/network/mod.rs index 0822d56..6af2356 100644 --- a/headless-rust/src/network/mod.rs +++ b/headless-rust/src/network/mod.rs @@ -6,12 +6,21 @@ 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() { @@ -41,6 +50,9 @@ pub fn get_system_network_summary() -> SystemNetworkSummary { 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" @@ -67,13 +79,15 @@ pub fn get_system_network_summary() -> SystemNetworkSummary { 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: String::new(), + mac, expected_ip, is_configured, }; @@ -92,21 +106,44 @@ pub fn get_system_network_summary() -> SystemNetworkSummary { } } + 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( - detected_wifi_name.as_deref().unwrap_or("wlan0") - ); + let (active_ssid, signal_dbm, power_save_status, default_gateway) = query_wifi_runtime_info(&wifi_iface_name); - let (mode, hotspot_status, wifi_client_info) = if let Some(ref hs) = hotspot_ap_iface { + 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" }; ( - "field".to_string(), + "ap".to_string(), + "ap".to_string(), status.to_string(), None, ) @@ -123,13 +160,15 @@ pub fn get_system_network_summary() -> SystemNetworkSummary { description: "Wi-Fi Client connected to external router (Station mode)".to_string(), }; ( - "wifi-client".to_string(), + "client".to_string(), + "client".to_string(), "inactive".to_string(), Some(client_info), ) } else { ( - "dhcp".to_string(), + "ap".to_string(), + "disconnected".to_string(), "missing".to_string(), None, ) @@ -137,6 +176,10 @@ pub fn get_system_network_summary() -> SystemNetworkSummary { 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()), @@ -146,12 +189,12 @@ pub fn get_system_network_summary() -> SystemNetworkSummary { 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_else(|| detected_wifi_name.clone()), + 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: "Wi-Fi Access Point & Remote Web UI Control (wlan0/wifi0)".to_string(), + description: "Open Wi-Fi Hotspot AP & Web Setup (wlan0/wifi0)".to_string(), }, wifi_client: wifi_client_info, interfaces, @@ -214,7 +257,6 @@ fn query_wifi_runtime_info(wifi_iface: &str) -> (Option, Option, Op if let Ok(output) = Command::new("ip").args(["route", "show", "default"]).output() { if output.status.success() { let text = String::from_utf8_lossy(&output.stdout); - // Example: default via 192.168.178.1 dev wlan0 proto dhcp src 192.168.178.50 metric 600 let parts: Vec<&str> = text.split_whitespace().collect(); if parts.len() >= 3 && parts[0] == "default" && parts[1] == "via" { gateway = Some(parts[2].to_string()); @@ -227,28 +269,45 @@ fn query_wifi_runtime_info(wifi_iface: &str) -> (Option, Option, Op /// Scans for visible 2.4GHz & 5GHz Wi-Fi networks pub fn scan_wifi_networks() -> Vec { - let mut results: Vec = Vec::new(); let mut seen_ssids: HashMap = HashMap::new(); if let Ok(output) = Command::new("nmcli") - .args(["-t", "-f", "SSID,SIGNAL,SECURITY,IN-USE", "dev", "wifi", "list", "--rescan", "auto"]) + .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 { - let ssid = parts[0].trim().to_string(); + // 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 signal = parts[1].parse::().unwrap_or(0); - let security = parts[2].trim().to_string(); - let in_use = parts[3].trim().eq_ignore_ascii_case("yes") || parts[3].trim() == "*"; let item = WifiScanResult { ssid: ssid.clone(), + bssid, + channel, signal, security: if security.is_empty() { "Open".to_string() } else { security }, in_use, @@ -260,6 +319,8 @@ pub fn scan_wifi_networks() -> Vec { } if item.signal > existing.signal { existing.signal = item.signal; + existing.bssid = item.bssid; + existing.channel = item.channel; } } else { seen_ssids.insert(ssid, item); @@ -269,7 +330,7 @@ pub fn scan_wifi_networks() -> Vec { } } - results = seen_ssids.into_values().collect(); + 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) @@ -281,7 +342,7 @@ pub fn scan_wifi_networks() -> Vec { results } -/// Applies a network mode switch (Field AP, Wi-Fi Client, or DHCP) +/// 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"), @@ -301,8 +362,8 @@ pub fn apply_network_mode(input: &ApplyNetworkModeInput) -> NetworkOperationResu cmd.arg(&script); match normalized_mode.as_str() { - "field" | "ap" => { - cmd.arg("field"); + "ap" | "field" | "hotspot" => { + cmd.arg("ap"); } "client" | "wifi-client" | "internet" | "wifi" => { let ssid = match &input.ssid { @@ -323,6 +384,18 @@ pub fn apply_network_mode(input: &ApplyNetworkModeInput) -> NetworkOperationResu } } } + "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"); } @@ -330,7 +403,7 @@ pub fn apply_network_mode(input: &ApplyNetworkModeInput) -> NetworkOperationResu return NetworkOperationResult { success: false, mode: input.mode.clone(), - message: format!("Unknown network mode '{}'. Use 'field', 'wifi-client', or 'dhcp'.", other), + message: format!("Unknown network mode '{}'.", other), details: None, }; } diff --git a/headless-rust/src/web/routes.rs b/headless-rust/src/web/routes.rs index f876998..969306e 100644 --- a/headless-rust/src/web/routes.rs +++ b/headless-rust/src/web/routes.rs @@ -200,28 +200,21 @@ pub async fn get_skinned_image( .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR) } -// ─── Fake Internet / Captive Portal Connectivity Probes ──────────────────────── -// Pacify Windows, Fedora, Debian, Arch, Android, and macOS network managers -// so client laptops don't background-scan or drop connection thinking there's no internet. +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 { - ( - [(header::CONTENT_TYPE, "text/plain")], - "Microsoft NCSI", - ) + Redirect::temporary("http://192.168.4.1:3000/") } pub async fn connecttest_handler() -> impl IntoResponse { - ( - [(header::CONTENT_TYPE, "text/plain")], - "Microsoft Connect Test", - ) + Redirect::temporary("http://192.168.4.1:3000/") } pub async fn hotspot_txt_handler() -> impl IntoResponse { - ( - [(header::CONTENT_TYPE, "text/plain")], - "OK\n", - ) + Redirect::temporary("http://192.168.4.1:3000/") } pub async fn ping_txt_handler() -> impl IntoResponse { @@ -232,14 +225,13 @@ pub async fn ping_txt_handler() -> impl IntoResponse { } pub async fn generate_204_handler() -> impl IntoResponse { - StatusCode::NO_CONTENT + // 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 { - ( - [(header::CONTENT_TYPE, "text/html; charset=utf-8")], - "SuccessSuccess", - ) + // 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 { diff --git a/headless-rust/src/web/rpc.rs b/headless-rust/src/web/rpc.rs index 5f614b3..94833a7 100644 --- a/headless-rust/src/web/rpc.rs +++ b/headless-rust/src/web/rpc.rs @@ -646,6 +646,31 @@ async fn dispatch_method(ctx: &RpcContext, method: &str, params: Value) -> Resul 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")?; From c37097ce9985e5c64324502e412e2dfa2c71a4ea Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Wed, 26 Aug 2026 00:17:43 +0200 Subject: [PATCH 64/65] feat: Enhance Open AP setup mode with background execution and improved logging --- headless-rust/scripts/install-rpi.sh | 11 +++- headless-rust/scripts/setup-network.sh | 71 ++++++++++++++++++-------- 2 files changed, 61 insertions(+), 21 deletions(-) diff --git a/headless-rust/scripts/install-rpi.sh b/headless-rust/scripts/install-rpi.sh index bde83bc..583a8c0 100755 --- a/headless-rust/scripts/install-rpi.sh +++ b/headless-rust/scripts/install-rpi.sh @@ -298,7 +298,16 @@ if [ -t 0 ]; then if [[ $REPLY =~ ^[Yy]$ ]]; then chmod +x "${PROJECT_DIR}/scripts/setup-network.sh" - "${PROJECT_DIR}/scripts/setup-network.sh" ap + 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" diff --git a/headless-rust/scripts/setup-network.sh b/headless-rust/scripts/setup-network.sh index f3f5606..ae71779 100755 --- a/headless-rust/scripts/setup-network.sh +++ b/headless-rust/scripts/setup-network.sh @@ -1,6 +1,6 @@ #!/usr/bin/env bash set -e -trap '' HUP +trap '' HUP PIPE INT TERM MODE="${1:-status}" @@ -57,7 +57,7 @@ EOF' ipv4.method manual \ ipv4.addresses 192.168.1.100/24 \ ipv4.never-default yes \ - 802-3-ethernet.mtu 9000 + 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." } @@ -101,25 +101,30 @@ EOF" apply_ap_mode() { echo ">>> Applying SETUP / AP MODE (Open Hotspot + Captive Portal):" - echo " 1. Wi-Fi Hotspot (${WIFI_IFACE}) -> Open AP (SSID: speedcamera, 5GHz, No password)" + 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 "" - # 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 + # 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 - # Configure Open 5GHz Wi-Fi Hotspot AP (Band A, Channel 36, NO password) - echo "[*] Configuring Open 5GHz Wi-Fi Hotspot AP on ${WIFI_IFACE}..." + # 2. Configure Open Wi-Fi Hotspot AP + echo "[*] Configuring Open Wi-Fi Hotspot AP on ${WIFI_IFACE}..." SSID="speedcamera" - enforce_wifi_powersave_off + # 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 - sudo nmcli connection add type wifi \ + + # 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 \ @@ -128,16 +133,37 @@ apply_ap_mode() { 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 - - # Disable MAC randomization which can trigger background radio resets - sudo nmcli connection modify "Speedcamera-Hotspot" 802-11-wireless.mac-address-randomization 1 2>/dev/null || true - sudo nmcli connection modify "Speedcamera-Hotspot" ipv4.never-default yes 2>/dev/null || true - - sudo nmcli connection up "Speedcamera-Hotspot" 2>/dev/null || echo "Note: Hotspot initialized." + 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 - # Configure DNS interception for captive portal (192.168.4.1) + # 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 + # 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 5GHz Hotspot: SSID '${SSID}' (No password)" + 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 "=========================================================" From f57147b042749e1f25a7580d215ec54e2035276a Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Wed, 26 Aug 2026 00:29:15 +0200 Subject: [PATCH 65/65] feat: Import useEffect for managing side effects in CameraTab component --- headless-rust/frontend/src/routes/settings/CameraTab.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/headless-rust/frontend/src/routes/settings/CameraTab.tsx b/headless-rust/frontend/src/routes/settings/CameraTab.tsx index 7606c21..803937c 100644 --- a/headless-rust/frontend/src/routes/settings/CameraTab.tsx +++ b/headless-rust/frontend/src/routes/settings/CameraTab.tsx @@ -1,4 +1,4 @@ -import { useState } from "react"; +import { useState, useEffect } from "react"; import type { ChangeEvent } from "react"; import { toast } from "sonner"; import { useAppStore } from "@/stores/useAppStore";