From 34aa608de84dbc8bceef7f1c80d7ca26f1f1cfbf Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Wed, 9 Sep 2026 19:57:33 +0200 Subject: [PATCH 1/4] feat: implement state machine for operating modes and update JSON output accordingly --- arduino/src/json_output.cpp | 3 +++ arduino/src/main.cpp | 24 ++++++++++++++----- arduino/src/serial_io.cpp | 47 +++++++++++++++++++++++++++++++++---- arduino/src/state.cpp | 5 ++++ arduino/src/state.h | 6 +++++ arduino/src/types.h | 4 ++++ 6 files changed, 78 insertions(+), 11 deletions(-) diff --git a/arduino/src/json_output.cpp b/arduino/src/json_output.cpp index f02e8a5..e0a06c6 100644 --- a/arduino/src/json_output.cpp +++ b/arduino/src/json_output.cpp @@ -61,8 +61,11 @@ void sendJsonPong() { cfg["maxSpeed"] = maxSpeedKmH; cfg["sensorDistance"] = sensorDistance; cfg["debugEnabled"] = debugEnabled; + cfg["operatingMode"] = (currentOpMode == OperatingMode::ALIGNMENT) ? "alignment" + : (currentOpMode == OperatingMode::LAPTIMER) ? "laptimer" : "speedcamera"; LapTimer::populatePongConfig(cfg); Alignment::populatePongConfig(cfg); + String out; serializeJson(doc, out); out += '\n'; diff --git a/arduino/src/main.cpp b/arduino/src/main.cpp index fd92066..4e3c74c 100644 --- a/arduino/src/main.cpp +++ b/arduino/src/main.cpp @@ -26,15 +26,23 @@ void setup() { // ─── Main Loop ─────────────────────────────────────────────────────────────── void loop() { - LapTimer::update(); - Alignment::update(); - - // Process incoming serial commands every iteration + // Process incoming serial commands first every iteration handleSerial(); if (stringComplete) { decodeJson(inputString); } + // ponytail: mutually exclusive execution based on operating mode state machine + if (currentOpMode == OperatingMode::ALIGNMENT) { + Alignment::update(); + yield(); + return; // Do not process speed passes while actively aligning light barriers + } + + if (currentOpMode == OperatingMode::LAPTIMER) { + LapTimer::update(); + } + // ── IDLE: wait for either sensor to trigger ────────────────────────────── if (measState == MeasurementState::IDLE) { if (millis() - lastMeasurementEndMs < (unsigned long)cooldownMs) { @@ -43,6 +51,7 @@ void loop() { } if (digitalRead(sensor1) == HIGH) { + firstTriggerUs = micros(); firstSensor = FirstSensor::SENSOR_ONE; measurementStartMs = millis(); @@ -118,8 +127,11 @@ void loop() { sendJsonStatus("legal", speedInKmH, speedTolerance, direction); } - // ponytail: notify active modules with zero heap allocation or dynamic dispatch - LapTimer::onMeasurement(event); + // ponytail: notify lap timer ONLY if operating in LAPTIMER mode + if (currentOpMode == OperatingMode::LAPTIMER) { + LapTimer::onMeasurement(event); + } + } else { sendJsonStatus("timeout"); // Speed out of valid range — discard diff --git a/arduino/src/serial_io.cpp b/arduino/src/serial_io.cpp index a6a6c0f..ca1755f 100644 --- a/arduino/src/serial_io.cpp +++ b/arduino/src/serial_io.cpp @@ -73,14 +73,51 @@ void handleCommand(JsonDocument &doc) { } else if (strcmp(command, "getCapabilities") == 0) { sendJsonCapabilities(); - // ponytail: route module-specific commands without bloated registry abstractions - } else if (LapTimer::handleCommand(command, doc)) { - return; + } else if (strcmp(command, "setMode") == 0) { + const char *modeStr = doc["mode"] | "speedcamera"; + if (strcmp(modeStr, "alignment") == 0) { + LapTimer::reset(); + currentOpMode = OperatingMode::ALIGNMENT; + resetMeasurement(); + Alignment::handleCommand("startAlignment", doc); + } else if (strcmp(modeStr, "laptimer") == 0) { + Alignment::reset(); + currentOpMode = OperatingMode::LAPTIMER; + resetMeasurement(); + LapTimer::handleCommand("startLapSession", doc); + } else { + Alignment::reset(); + LapTimer::reset(); + currentOpMode = OperatingMode::SPEEDCAMERA; + resetMeasurement(); + sendJsonStatus("modeSpeedcamera"); + } - } else if (Alignment::handleCommand(command, doc)) { - return; + // ponytail: route module commands with strict operating mode mutual exclusion + } else if (strcmp(command, "startAlignment") == 0) { + LapTimer::reset(); + currentOpMode = OperatingMode::ALIGNMENT; + resetMeasurement(); + Alignment::handleCommand(command, doc); + + } else if (strcmp(command, "stopAlignment") == 0) { + Alignment::handleCommand(command, doc); + currentOpMode = OperatingMode::SPEEDCAMERA; + resetMeasurement(); + + } else if (strcmp(command, "startLapSession") == 0) { + Alignment::reset(); + currentOpMode = OperatingMode::LAPTIMER; + resetMeasurement(); + LapTimer::handleCommand(command, doc); + + } else if (strcmp(command, "stopLapSession") == 0) { + LapTimer::handleCommand(command, doc); + currentOpMode = OperatingMode::SPEEDCAMERA; + resetMeasurement(); } else { sendJsonStatus("jsonError"); } } + diff --git a/arduino/src/state.cpp b/arduino/src/state.cpp index 0b75504..3d6f727 100644 --- a/arduino/src/state.cpp +++ b/arduino/src/state.cpp @@ -18,3 +18,8 @@ unsigned long lastMeasurementEndMs = 0; // ─── Speed Measurement Results ──────────────────────────────────────────────── float speedInKmH = 0.0f; float speedTolerance = 0.0f; + +// ─── Operating Mode State ───────────────────────────────────────────────────── +// ponytail: default to SPEEDCAMERA, mutually exclusive with LAPTIMER and ALIGNMENT +OperatingMode currentOpMode = OperatingMode::SPEEDCAMERA; + diff --git a/arduino/src/state.h b/arduino/src/state.h index ec8cfb0..553e825 100644 --- a/arduino/src/state.h +++ b/arduino/src/state.h @@ -21,3 +21,9 @@ extern unsigned long lastMeasurementEndMs; // ─── Speed Measurement Results ──────────────────────────────────────────────── extern float speedInKmH; extern float speedTolerance; + +// ─── Operating Mode State ───────────────────────────────────────────────────── +extern OperatingMode currentOpMode; +void resetMeasurement(); + + diff --git a/arduino/src/types.h b/arduino/src/types.h index fad1dd8..038b53d 100644 --- a/arduino/src/types.h +++ b/arduino/src/types.h @@ -7,6 +7,9 @@ enum class MeasurementState : uint8_t { IDLE, WAITING_FOR_SECOND }; enum class FirstSensor : uint8_t { NONE, SENSOR_ONE, SENSOR_TWO }; +// ─── Operating Mode State Machine ───────────────────────────────────────────── +enum class OperatingMode : uint8_t { SPEEDCAMERA, LAPTIMER, ALIGNMENT }; + // ─── Measurement Event ──────────────────────────────────────────────────────── // Emitted when a passing vehicle triggers both sensors within valid window. struct MeasurementEvent { @@ -15,3 +18,4 @@ struct MeasurementEvent { const char *direction; // "forward" | "reverse" unsigned long boundaryUs; // µs timestamp of first beam break }; + From 9598d78136b9767cdc2ab006471f989c67f90f10 Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Wed, 9 Sep 2026 19:57:49 +0200 Subject: [PATCH 2/4] feat: implement state machine for managing operating modes and plugin availability --- headless-rust/src/config.rs | 23 +- headless-rust/src/main.rs | 64 +++- headless-rust/src/plugins/alignment/mod.rs | 23 ++ headless-rust/src/plugins/display/mod.rs | 14 +- headless-rust/src/plugins/laptimer/mod.rs | 34 ++ headless-rust/src/plugins/mod.rs | 45 +++ headless-rust/src/state_machine.rs | 370 +++++++++++++++++++++ headless-rust/src/web/mod.rs | 3 + headless-rust/src/web/rpc.rs | 36 ++ headless-rust/src/web/socketio.rs | 21 ++ 10 files changed, 618 insertions(+), 15 deletions(-) create mode 100644 headless-rust/src/state_machine.rs diff --git a/headless-rust/src/config.rs b/headless-rust/src/config.rs index d1b1e7d..fbb96d6 100644 --- a/headless-rust/src/config.rs +++ b/headless-rust/src/config.rs @@ -8,10 +8,16 @@ pub struct AppConfig { pub images_dir: PathBuf, pub db_path: PathBuf, pub mock_mode: bool, + pub disabled_plugins: Vec, } impl AppConfig { - pub fn new(mock: bool, port_override: Option, host_override: Option) -> Self { + pub fn new( + mock: bool, + port_override: Option, + host_override: Option, + disable_plugins_override: Option, + ) -> Self { let host = host_override .or_else(|| std::env::var("HOST").ok()) .unwrap_or_else(|| "0.0.0.0".to_string()); @@ -41,6 +47,16 @@ impl AppConfig { || 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); + let disabled_plugins: Vec = disable_plugins_override + .or_else(|| std::env::var("DISABLED_PLUGINS").ok()) + .map(|s| { + s.split(',') + .map(|p| p.trim().to_lowercase()) + .filter(|p| !p.is_empty()) + .collect() + }) + .unwrap_or_default(); + Self { host, port, @@ -48,6 +64,11 @@ impl AppConfig { images_dir, db_path, mock_mode, + disabled_plugins, } } + + pub fn is_plugin_disabled(&self, name: &str) -> bool { + self.disabled_plugins.iter().any(|p| p == name) + } } diff --git a/headless-rust/src/main.rs b/headless-rust/src/main.rs index 7d9006b..d017ee3 100644 --- a/headless-rust/src/main.rs +++ b/headless-rust/src/main.rs @@ -6,9 +6,11 @@ mod models; mod network; mod plugins; mod serial; +mod state_machine; mod storage; mod web; + use camera::CameraService; use clap::Parser; use config::AppConfig; @@ -29,6 +31,9 @@ struct Args { #[arg(short = 'H', long, help = "HTTP server bind address (default: 0.0.0.0)")] host: Option, + + #[arg(long, help = "Comma-separated list of plugins to disable (e.g. laptimer,alignment)")] + disable_plugins: Option, } #[tokio::main] @@ -46,7 +51,7 @@ async fn main() -> Result<(), Box> { .init(); let args = Args::parse(); - let config = AppConfig::new(args.mock, args.port, args.host); + let config = AppConfig::new(args.mock, args.port, args.host, args.disable_plugins); tracing::info!("─────────────────────────────────────────────────────────────────"); tracing::info!(" ⚡ Speedcamera Headless Daemon (Rust & Axum / Socket.io)"); @@ -101,10 +106,12 @@ async fn main() -> Result<(), Box> { } } - // ─── Armed System State ────────────────────────────────────────────────── + // ─── Armed System State & State Machine Synchronization ────────────────── 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(); + let operating_mode = std::sync::Arc::new(std::sync::RwLock::new("speedcamera".to_string())); + let notify_display = std::sync::Arc::new(tokio::sync::Notify::new()); // ─── Plugin System Initialization ──────────────────────────────────────── let plugin_ctx = plugins::PluginContext { @@ -115,17 +122,48 @@ async fn main() -> Result<(), Box> { serial: serial.clone(), armed: armed.clone(), armed_tx: armed_tx.clone(), + operating_mode: operating_mode.clone(), + notify_display: notify_display.clone(), }; let mut plugin_reg = plugins::PluginRegistry::new(); - // ponytail: modular plugins isolated from core daemon - plugin_reg.register(Box::new(plugins::laptimer::LapTimerPlugin::new())); - plugin_reg.register(Box::new(plugins::alignment::AlignmentPlugin::new())); - plugin_reg.register(Box::new(plugins::display::DisplayPlugin::new())); + // ponytail: modular plugins isolated from core daemon, respects disabled_plugins config + if !config.is_plugin_disabled("laptimer") { + plugin_reg.register(Box::new(plugins::laptimer::LapTimerPlugin::new())); + } else { + tracing::info!("[plugins] LapTimerPlugin disabled by configuration"); + } + + if !config.is_plugin_disabled("alignment") { + plugin_reg.register(Box::new(plugins::alignment::AlignmentPlugin::new())); + } else { + tracing::info!("[plugins] AlignmentPlugin disabled by configuration"); + } + + if !config.is_plugin_disabled("display") { + plugin_reg.register(Box::new(plugins::display::DisplayPlugin::new())); + } else { + tracing::info!("[plugins] DisplayPlugin disabled by configuration"); + } + plugin_reg.init(plugin_ctx)?; let plugin_registry = std::sync::Arc::new(plugin_reg); let pipeline_plugins = plugin_registry.clone(); + // ─── Central State Machine Initialization ──────────────────────────────── + let state_machine = std::sync::Arc::new(state_machine::SystemStateMachine::new( + config.clone(), + db.clone(), + camera.clone(), + serial.clone(), + armed.clone(), + armed_tx.clone(), + plugin_registry.clone(), + operating_mode.clone(), + notify_display.clone(), + )); + // ─── Instant Shutter Trigger Pipeline (<10ms latency) ───────────────────── + let (violation_tx, _) = tokio::sync::broadcast::channel::(32); let pipeline_violation_tx = violation_tx.clone(); let pipeline_cam = camera.clone(); @@ -197,8 +235,20 @@ async fn main() -> Result<(), Box> { // 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, plugin_registry); + let app = web::build_app( + config, + db, + store, + camera, + serial, + violation_tx, + armed, + armed_tx, + plugin_registry, + state_machine, + ); let listener = tokio::net::TcpListener::bind(&bind_addr).await?; + tracing::info!(" 🚀 Server listening on http://{}", bind_addr); axum::serve(listener, app).await?; diff --git a/headless-rust/src/plugins/alignment/mod.rs b/headless-rust/src/plugins/alignment/mod.rs index dfa67c2..ececfec 100644 --- a/headless-rust/src/plugins/alignment/mod.rs +++ b/headless-rust/src/plugins/alignment/mod.rs @@ -56,6 +56,29 @@ impl Plugin for AlignmentPlugin { tracing::info!("[plugin:alignment] Registered RPC methods"); } + fn mode_id(&self) -> Option<&'static str> { + Some("alignment") + } + + fn is_available(&self, ctx: &PluginContext) -> Result<(), String> { + if ctx.config.mock_mode || ctx.serial.get_status().connected { + Ok(()) + } else { + Err("Serial radar connection required for sensor alignment".to_string()) + } + } + + fn on_leave_mode(&self, ctx: &PluginContext, _force: bool) -> Result<(), String> { + { + let mut s = self.state.lock().unwrap(); + s.active = false; + } + ctx.serial.send_command(r#"{"command":"stopAlignment"}"#); + tracing::info!("[plugin:alignment] Sent stopAlignment on mode leave"); + Ok(()) + } + + fn on_serial_event(&self, msg: &SerialStatusPayload, _ctx: &PluginContext) { if let SerialStatusPayload::BarrierStatus { sensor1_interrupted, diff --git a/headless-rust/src/plugins/display/mod.rs b/headless-rust/src/plugins/display/mod.rs index 8f54f49..5c28c0d 100644 --- a/headless-rust/src/plugins/display/mod.rs +++ b/headless-rust/src/plugins/display/mod.rs @@ -89,6 +89,7 @@ impl Plugin for DisplayPlugin { let serial_svc = ctx.serial.clone(); let is_conn_thread = self.is_connected.clone(); let last_err_thread = self.last_error.clone(); + let op_mode_thread = ctx.operating_mode.clone(); // Spawn dedicated background render thread (non-blocking for main server) std::thread::Builder::new() @@ -151,14 +152,13 @@ impl Plugin for DisplayPlugin { *shared_fb = local_fb.clone(); } } else { - // Determine active mode + // Determine active mode: ponytail: mirror central state machine when in auto mode let mode = if cfg.mode == "auto" { - if telem.lap_state == "timing" || telem.lap_state == "waiting" { - "laptimer" - } else if telem.sensor1_interrupted || telem.sensor2_interrupted { - "alignment" - } else { - "speedcamera" + let sm = op_mode_thread.read().unwrap(); + match sm.as_str() { + "alignment" | "setup" => "alignment", + "laptimer" => "laptimer", + _ => "speedcamera", } } else { cfg.mode.as_str() diff --git a/headless-rust/src/plugins/laptimer/mod.rs b/headless-rust/src/plugins/laptimer/mod.rs index f05edd6..414860e 100644 --- a/headless-rust/src/plugins/laptimer/mod.rs +++ b/headless-rust/src/plugins/laptimer/mod.rs @@ -86,6 +86,40 @@ impl Plugin for LapTimerPlugin { tracing::info!("[plugin:laptimer] Registered RPC methods"); } + fn mode_id(&self) -> Option<&'static str> { + Some("laptimer") + } + + fn is_available(&self, ctx: &PluginContext) -> Result<(), String> { + if ctx.config.mock_mode || ctx.serial.get_status().connected { + Ok(()) + } else { + Err("Serial radar connection required for lap timer".to_string()) + } + } + + fn on_leave_mode(&self, ctx: &PluginContext, _force: bool) -> Result<(), String> { + let active_id = { + let mut s = self.state.lock().unwrap(); + let id = s.active_session.as_ref().map(|sess| sess.id); + s.active_session = None; + s.lap_state = "idle".to_string(); + s.lap_timing_started_at = None; + s.start_image_path = None; + id + }; + + if let Some(id) = active_id { + let conn = ctx.db.lock(); + let _ = db::close_lap_session(&conn, id); + tracing::info!("[plugin:laptimer] Closed active session #{} on mode leave", id); + } + + ctx.serial.send_command(r#"{"command":"stopLapSession"}"#); + Ok(()) + } + + // ponytail: instant sub-10ms hardware camera capture right from serial pipeline fn on_serial_event(&self, msg: &SerialStatusPayload, ctx: &PluginContext) { match msg { diff --git a/headless-rust/src/plugins/mod.rs b/headless-rust/src/plugins/mod.rs index ddf6946..41a115c 100644 --- a/headless-rust/src/plugins/mod.rs +++ b/headless-rust/src/plugins/mod.rs @@ -28,8 +28,11 @@ pub struct PluginContext { pub serial: Arc, pub armed: Arc, pub armed_tx: broadcast::Sender, + pub operating_mode: Arc>, + pub notify_display: Arc, } + pub type BoxFuture<'a, T> = Pin + Send + 'a>>; pub type RpcHandler = Box BoxFuture<'static, Result> + Send + Sync>; @@ -85,6 +88,18 @@ pub trait Plugin: Send + Sync + 'static { router } fn on_serial_event(&self, _msg: &SerialStatusPayload, _ctx: &PluginContext) {} + fn mode_id(&self) -> Option<&'static str> { + None + } + fn is_available(&self, _ctx: &PluginContext) -> Result<(), String> { + Ok(()) + } + fn on_enter_mode(&self, _ctx: &PluginContext) -> Result<(), String> { + Ok(()) + } + fn on_leave_mode(&self, _ctx: &PluginContext, _force: bool) -> Result<(), String> { + Ok(()) + } } pub struct PluginRegistry { @@ -127,6 +142,35 @@ impl PluginRegistry { router } + #[allow(dead_code)] + pub fn has_plugin(&self, id: &str) -> bool { + self.plugins.iter().any(|p| p.id() == id) + } + + pub fn check_mode_available(&self, mode: &str, ctx: &PluginContext) -> Result<(), String> { + if let Some(plugin) = self.plugins.iter().find(|p| p.mode_id() == Some(mode)) { + plugin.is_available(ctx) + } else { + Err(format!("Plugin for mode '{}' not registered", mode)) + } + } + + pub fn on_enter_mode(&self, mode: &str, ctx: &PluginContext) -> Result<(), String> { + if let Some(plugin) = self.plugins.iter().find(|p| p.mode_id() == Some(mode)) { + plugin.on_enter_mode(ctx) + } else { + Ok(()) + } + } + + pub fn on_leave_mode(&self, mode: &str, ctx: &PluginContext, force: bool) -> Result<(), String> { + if let Some(plugin) = self.plugins.iter().find(|p| p.mode_id() == Some(mode)) { + plugin.on_leave_mode(ctx, force) + } else { + Ok(()) + } + } + pub fn list_plugins(&self) -> Vec { self.plugins .iter() @@ -156,3 +200,4 @@ impl PluginRegistry { } } } + diff --git a/headless-rust/src/state_machine.rs b/headless-rust/src/state_machine.rs new file mode 100644 index 0000000..d7b01d6 --- /dev/null +++ b/headless-rust/src/state_machine.rs @@ -0,0 +1,370 @@ +use crate::camera::CameraService; +use crate::config::AppConfig; +use crate::db::Database; +use crate::plugins::{PluginContext, PluginRegistry}; +use crate::serial::SerialService; +use serde::{Deserialize, Serialize}; +use std::collections::HashMap; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, RwLock}; +use tokio::sync::broadcast; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum OperatingMode { + SpeedCamera, + LapTimer, + Alignment, + CameraSetup, +} + +impl OperatingMode { + pub fn as_str(&self) -> &'static str { + match self { + Self::SpeedCamera => "speedcamera", + Self::LapTimer => "laptimer", + Self::Alignment => "alignment", + Self::CameraSetup => "setup", + } + } + + pub fn from_str(s: &str) -> Option { + match s.to_lowercase().as_str() { + "speedcamera" | "speed_camera" | "speed" => Some(Self::SpeedCamera), + "laptimer" | "lap_timer" | "laps" => Some(Self::LapTimer), + "alignment" | "align" => Some(Self::Alignment), + "setup" | "camera_setup" | "camerasetup" => Some(Self::CameraSetup), + _ => None, + } + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ModeAvailability { + pub available: bool, + #[serde(skip_serializing_if = "Option::is_none")] + pub reason: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct OperatingModeStatus { + pub current_mode: String, + pub previous_mode: Option, + pub available_modes: HashMap, + pub armed: bool, + pub timestamp_ms: i64, +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SafeguardRejection { + pub safeguard: String, // "ARMED" | "NOT_READY" | "SESSION_ACTIVE" | "INVALID_MODE" + pub message: String, +} + +pub struct SystemStateMachine { + current_mode: Arc>, + previous_mode: Arc>>, + tx: broadcast::Sender, + config: AppConfig, + db: Database, + camera: Arc, + serial: Arc, + armed: Arc, + armed_tx: broadcast::Sender, + plugins: Arc, + operating_mode: Arc>, + notify_display: Arc, +} + +impl SystemStateMachine { + pub fn new( + config: AppConfig, + db: Database, + camera: Arc, + serial: Arc, + armed: Arc, + armed_tx: broadcast::Sender, + plugins: Arc, + operating_mode: Arc>, + notify_display: Arc, + ) -> Self { + let (tx, _) = broadcast::channel(32); + Self { + current_mode: Arc::new(RwLock::new(OperatingMode::SpeedCamera)), + previous_mode: Arc::new(RwLock::new(None)), + tx, + config, + db, + camera, + serial, + armed, + armed_tx, + plugins, + operating_mode, + notify_display, + } + } + + + pub fn current_mode(&self) -> OperatingMode { + *self.current_mode.read().unwrap() + } + + pub fn subscribe(&self) -> broadcast::Receiver { + self.tx.subscribe() + } + + fn plugin_context(&self) -> PluginContext { + PluginContext { + config: self.config.clone(), + db: self.db.clone(), + store: crate::storage::FileStore::new(&self.config.images_dir), + camera: self.camera.clone(), + serial: self.serial.clone(), + armed: self.armed.clone(), + armed_tx: self.armed_tx.clone(), + operating_mode: self.operating_mode.clone(), + notify_display: self.notify_display.clone(), + } + } + + pub fn get_available_modes(&self) -> HashMap { + let mut map = HashMap::new(); + let camera_ok = self.config.mock_mode || self.camera.get_status().connected; + let ctx = self.plugin_context(); + + // 1. speedcamera (core) + map.insert( + "speedcamera".to_string(), + ModeAvailability { + available: true, + reason: None, + }, + ); + + // 2. setup (core) + map.insert( + "setup".to_string(), + if camera_ok { + ModeAvailability { + available: true, + reason: None, + } + } else { + ModeAvailability { + available: false, + reason: Some("Camera not connected".to_string()), + } + }, + ); + + // 3. laptimer (plugin) + map.insert( + "laptimer".to_string(), + match self.plugins.check_mode_available("laptimer", &ctx) { + Ok(_) => ModeAvailability { + available: true, + reason: None, + }, + Err(err) => ModeAvailability { + available: false, + reason: Some(err), + }, + }, + ); + + // 4. alignment (plugin) + map.insert( + "alignment".to_string(), + match self.plugins.check_mode_available("alignment", &ctx) { + Ok(_) => ModeAvailability { + available: true, + reason: None, + }, + Err(err) => ModeAvailability { + available: false, + reason: Some(err), + }, + }, + ); + + map + } + + pub fn get_status(&self) -> OperatingModeStatus { + let curr = *self.current_mode.read().unwrap(); + let prev = *self.previous_mode.read().unwrap(); + let armed = self.armed.load(Ordering::SeqCst); + OperatingModeStatus { + current_mode: curr.as_str().to_string(), + previous_mode: prev.map(|p| p.as_str().to_string()), + available_modes: self.get_available_modes(), + armed, + timestamp_ms: chrono::Utc::now().timestamp_millis(), + } + } + + pub fn check_transition( + &self, + target: OperatingMode, + force: bool, + ) -> Result<(), SafeguardRejection> { + let current = self.current_mode(); + if current == target { + return Ok(()); + } + + // Safeguard 1: Leaving SpeedCamera while system is ARMED + if current == OperatingMode::SpeedCamera && self.armed.load(Ordering::SeqCst) && !force { + return Err(SafeguardRejection { + safeguard: "ARMED".to_string(), + message: "System is currently armed. Disarm before switching operating mode." + .to_string(), + }); + } + + // Safeguard 2: Target mode availability (plugins and hardware requirements) + let availabilities = self.get_available_modes(); + if let Some(avail) = availabilities.get(target.as_str()) { + if !avail.available { + return Err(SafeguardRejection { + safeguard: "NOT_READY".to_string(), + message: avail + .reason + .clone() + .unwrap_or_else(|| "Target mode unavailable".to_string()), + }); + } + } else { + return Err(SafeguardRejection { + safeguard: "INVALID_MODE".to_string(), + message: format!("Unknown target mode '{}'", target.as_str()), + }); + } + + Ok(()) + } + + pub fn transition_to( + &self, + target: OperatingMode, + force: bool, + ) -> Result { + self.check_transition(target, force)?; + + let current = self.current_mode(); + if current == target { + return Ok(self.get_status()); + } + + tracing::info!( + "[state-machine] Transitioning: {} -> {} (force: {})", + current.as_str(), + target.as_str(), + force + ); + + // ─── 1. Teardown Leaving Mode ────────────────────────────────────────── + match current { + OperatingMode::SpeedCamera => { + if self.armed.load(Ordering::SeqCst) { + tracing::info!("[state-machine] Auto-disarming system on leaving SpeedCamera mode"); + self.armed.store(false, Ordering::SeqCst); + let _ = self.armed_tx.send(false); + } + } + OperatingMode::CameraSetup => { + tracing::info!("[state-machine] Stopping camera setup stream on mode exit"); + let cam = self.camera.clone(); + let db = self.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); + }); + } + OperatingMode::Alignment => { + tracing::info!("[state-machine] Stopping sensor alignment on mode exit"); + let cmd = serde_json::json!({ "command": "stopAlignment" }); + self.serial.send_command(&cmd.to_string()); + } + OperatingMode::LapTimer => { + tracing::info!("[state-machine] Stopping lap timer session on mode exit"); + let cmd = serde_json::json!({ "command": "stopLapSession" }); + self.serial.send_command(&cmd.to_string()); + } + } + + // Notify plugin lifecycle hooks + let ctx = self.plugin_context(); + let _ = self.plugins.on_leave_mode(current.as_str(), &ctx, force); + + // ─── 2. Enter New Mode ──────────────────────────────────────────────── + match target { + OperatingMode::SpeedCamera => { + // Ensure serial hardware resets back to default speed measurement + let cmd = serde_json::json!({ "command": "setMode", "mode": "speedcamera" }); + self.serial.send_command(&cmd.to_string()); + } + OperatingMode::CameraSetup => { + tracing::info!("[state-machine] Starting camera preview stream for setup mode"); + let cam = self.camera.clone(); + tokio::task::spawn_blocking(move || { + cam.start_setup_stream(); + }); + } + OperatingMode::Alignment => { + tracing::info!("[state-machine] Command serial to start alignment"); + let cmd = serde_json::json!({ "command": "startAlignment" }); + self.serial.send_command(&cmd.to_string()); + } + OperatingMode::LapTimer => { + tracing::info!("[state-machine] Entering lap timer mode"); + let cmd = serde_json::json!({ "command": "setMode", "mode": "laptimer" }); + self.serial.send_command(&cmd.to_string()); + } + } + + let _ = self.plugins.on_enter_mode(target.as_str(), &ctx); + + // ─── 3. Commit State Machine Update & Broadcast ─────────────────────── + { + let mut prev = self.previous_mode.write().unwrap(); + *prev = Some(current); + let mut curr = self.current_mode.write().unwrap(); + *curr = target; + } + + // Synchronize shared string and wake up physical OLED render thread + { + let mut om = self.operating_mode.write().unwrap(); + *om = target.as_str().to_string(); + } + self.notify_display.notify_waiters(); + + let status = self.get_status(); + let _ = self.tx.send(status.clone()); + tracing::info!("[state-machine] Active operating mode is now: {}", status.current_mode); + + Ok(status) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_mode_from_str() { + assert_eq!(OperatingMode::from_str("speedcamera"), Some(OperatingMode::SpeedCamera)); + assert_eq!(OperatingMode::from_str("laptimer"), Some(OperatingMode::LapTimer)); + assert_eq!(OperatingMode::from_str("alignment"), Some(OperatingMode::Alignment)); + assert_eq!(OperatingMode::from_str("setup"), Some(OperatingMode::CameraSetup)); + assert_eq!(OperatingMode::from_str("unknown"), None); + } +} + + diff --git a/headless-rust/src/web/mod.rs b/headless-rust/src/web/mod.rs index e581992..560fbe3 100644 --- a/headless-rust/src/web/mod.rs +++ b/headless-rust/src/web/mod.rs @@ -31,6 +31,7 @@ pub fn build_app( armed: Arc, armed_tx: broadcast::Sender, plugins: Arc, + state_machine: Arc, ) -> Router { let (flash_tx, _) = broadcast::channel::(32); @@ -46,8 +47,10 @@ pub fn build_app( armed, armed_tx, plugins: plugins.clone(), + state_machine, }); + // 10 MB payload capacity, 5s keepalive ping interval to keep Wi-Fi sleep-disabled, // widened 20s ping timeout to tolerate Wi-Fi jitter, and large 4096 buffer size for live stream bursts. let (layer, io) = SocketIo::builder() diff --git a/headless-rust/src/web/rpc.rs b/headless-rust/src/web/rpc.rs index 1865287..3674f3c 100644 --- a/headless-rust/src/web/rpc.rs +++ b/headless-rust/src/web/rpc.rs @@ -43,8 +43,10 @@ pub struct RpcContext { pub armed: Arc, pub armed_tx: broadcast::Sender, pub plugins: Arc, + pub state_machine: Arc, } + pub async fn handle_rpc(ctx: &RpcContext, req: RpcRequest) -> RpcResponse { let id = req.id; let res = dispatch_method(ctx, &req.method, req.params).await; @@ -279,12 +281,46 @@ async fn dispatch_method(ctx: &RpcContext, method: &str, params: Value) -> Resul let is_armed = params["armed"] .as_bool() .ok_or("Missing armed parameter")?; + if is_armed && ctx.state_machine.current_mode() != crate::state_machine::OperatingMode::SpeedCamera { + let _ = ctx.state_machine.transition_to(crate::state_machine::OperatingMode::SpeedCamera, true); + } 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 })) } + // ─── Operating Mode State Machine ────────────────────────────────────── + "getOperatingMode" => { + let status = ctx.state_machine.get_status(); + Ok(serde_json::to_value(status).unwrap()) + } + + "setOperatingMode" => { + let mode_str = params["targetMode"] + .as_str() + .or_else(|| params["mode"].as_str()) + .ok_or("Missing targetMode parameter")?; + let force = params["force"].as_bool().unwrap_or(false); + + let target = crate::state_machine::OperatingMode::from_str(mode_str) + .ok_or_else(|| format!("Unknown operating mode '{}'", mode_str))?; + + match ctx.state_machine.transition_to(target, force) { + Ok(status) => Ok(json!({ + "success": true, + "status": status, + "mode": status.current_mode + })), + Err(rejection) => Ok(json!({ + "success": false, + "safeguard": rejection.safeguard, + "message": rejection.message + })), + } + } + + // ─── Settings ───────────────────────────────────────────────────────── "getSettings" => { let db = ctx.db.clone(); diff --git a/headless-rust/src/web/socketio.rs b/headless-rust/src/web/socketio.rs index 0af0754..49b2490 100644 --- a/headless-rust/src/web/socketio.rs +++ b/headless-rust/src/web/socketio.rs @@ -14,6 +14,8 @@ pub async fn on_connect(s: SocketRef, ctx: Arc) { 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) })); + let _ = s.emit("operatingMode", &ctx.state_machine.get_status()); + // Register RPC handler with AckSender for request-response RPC over Socket.io let ctx_rpc = ctx.clone(); @@ -50,10 +52,29 @@ pub fn spawn_event_broadcaster(io: SocketIo, ctx: Arc) { let mut flash_rx = ctx.flash_tx.subscribe(); let mut violation_rx = ctx.violation_tx.subscribe(); let mut armed_rx = ctx.armed_tx.subscribe(); + let mut mode_rx = ctx.state_machine.subscribe(); loop { tokio::select! { + res = mode_rx.recv() => { + match res { + Ok(mode_status) => { + if let Err(e) = io.emit("operatingModeChanged", &mode_status).await { + tracing::debug!("[socketio] Emit operatingModeChanged error: {:?}", e); + } + } + Err(broadcast::error::RecvError::Lagged(n)) => { + tracing::debug!("[socketio] Mode broadcast lagged by {} messages", n); + } + Err(broadcast::error::RecvError::Closed) => { + tracing::warn!("[socketio] Mode broadcast channel closed"); + break; + } + } + } + res = serial_rx.recv() => { + match res { Ok(payload) => { if let Err(e) = io.emit("serialStatus", &payload).await { From 3bb0baa036bd320d6d2a07e066d222c94dec5735 Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Wed, 9 Sep 2026 19:58:02 +0200 Subject: [PATCH 3/4] feat: Implement operating mode management and alignment setup - Added support for operating mode state management in the RPC client and store. - Introduced new events for operating mode changes and status updates. - Updated the alignment plugin to handle mode changes and integrate with the new operating mode system. - Refactored the AlignmentPage to remove legacy code and streamline the setup process. - Enhanced the SetupRoute to manage transitions between alignment and camera setup with appropriate safeguards. - Implemented a dialog for mode change confirmation when the system is armed. - Updated types to include operating mode status and availability. - Improved UI components to reflect the current operating mode and provide feedback during setup. --- .../src/components/MobileMenuSheet.tsx | 59 ++- .../src/components/ModeChangeGuardDialog.tsx | 86 ++++ .../src/components/NavigationMenu.tsx | 36 +- headless-rust/frontend/src/lib/rpc.ts | 18 + .../frontend/src/plugins/alignment/index.ts | 10 +- .../alignment/routes/AlignmentPage.tsx | 276 +---------- headless-rust/frontend/src/routes/index.tsx | 63 ++- headless-rust/frontend/src/routes/setup.tsx | 454 ++++++++++++++---- headless-rust/frontend/src/shared/types.ts | 36 ++ .../frontend/src/stores/slices/systemSlice.ts | 70 ++- 10 files changed, 725 insertions(+), 383 deletions(-) create mode 100644 headless-rust/frontend/src/components/ModeChangeGuardDialog.tsx diff --git a/headless-rust/frontend/src/components/MobileMenuSheet.tsx b/headless-rust/frontend/src/components/MobileMenuSheet.tsx index 2c77aab..e2d9f7e 100644 --- a/headless-rust/frontend/src/components/MobileMenuSheet.tsx +++ b/headless-rust/frontend/src/components/MobileMenuSheet.tsx @@ -36,10 +36,35 @@ const CORE_NAV_LINKS = [ { label: "About & Updates", to: "/about", icon: Info }, ] as const; +const MODE_META: Record = { + speedcamera: { + label: "Speed Camera", + badgeClass: "bg-blue-500/10 text-blue-400 border-blue-500/25", + }, + laptimer: { + label: "Lap Timer", + badgeClass: "bg-emerald-500/10 text-emerald-400 border-emerald-500/25", + }, + alignment: { + label: "Alignment", + badgeClass: "bg-amber-500/10 text-amber-400 border-amber-500/25", + }, + setup: { + label: "Setup", + badgeClass: "bg-purple-500/10 text-purple-400 border-purple-500/25", + }, +}; + export function MobileMenuSheet({ open, onOpenChange }: MobileMenuSheetProps) { const connectedPort = useAppStore((s) => s.connectedPort); const cameraConnected = useAppStore((s) => s.cameraConnected); const systemState = useAppStore((s) => s.systemState); + const operatingMode = useAppStore((s) => s.operatingMode); + + const currentModeMeta = MODE_META[operatingMode] ?? { + label: operatingMode, + badgeClass: "bg-muted text-muted-foreground border-border", + }; const pluginNavItems = pluginRegistry.getNavItems(); @@ -54,18 +79,28 @@ export function MobileMenuSheet({ open, onOpenChange }: MobileMenuSheetProps) {
Speedcamera - - {systemState} - +
+ + {currentModeMeta.label} + + + {systemState} + +
Mobile Navigation Menu diff --git a/headless-rust/frontend/src/components/ModeChangeGuardDialog.tsx b/headless-rust/frontend/src/components/ModeChangeGuardDialog.tsx new file mode 100644 index 0000000..7a00467 --- /dev/null +++ b/headless-rust/frontend/src/components/ModeChangeGuardDialog.tsx @@ -0,0 +1,86 @@ +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog"; +import { Button } from "@/components/ui/button"; +import { HugeiconsIcon } from "@hugeicons/react"; +import { Alert02Icon, SecurityCheckIcon } from "@hugeicons/core-free-icons"; + +interface ModeChangeGuardDialogProps { + open: boolean; + onOpenChange: (open: boolean) => void; + targetMode: string; + onConfirm: () => void; + onCancel: () => void; + message?: string; + isArmed?: boolean; +} + +export function ModeChangeGuardDialog({ + open, + onOpenChange, + targetMode, + onConfirm, + onCancel, + message, + isArmed = true, +}: ModeChangeGuardDialogProps) { + const modeLabels: Record = { + speedcamera: "Speed Camera", + laptimer: "Lap Timer", + alignment: "Sensor Alignment", + setup: "Setup Wizard", + }; + + const targetLabel = modeLabels[targetMode] || targetMode; + + return ( + + + +
+
+ +
+
+ + {isArmed ? "System Is Currently Armed" : "Safeguard Confirmation"} + + + Mode transition safeguard triggered + +
+
+
+ +
+

+ {message || + `The speed camera is currently active and armed. To switch to ${targetLabel}, the system must disarm.`} +

+

+ Violations will not be captured while in {targetLabel} mode. +

+
+ + + + + +
+
+ ); +} diff --git a/headless-rust/frontend/src/components/NavigationMenu.tsx b/headless-rust/frontend/src/components/NavigationMenu.tsx index f4caa64..bfa2643 100644 --- a/headless-rust/frontend/src/components/NavigationMenu.tsx +++ b/headless-rust/frontend/src/components/NavigationMenu.tsx @@ -1,6 +1,7 @@ import { Link } from "@tanstack/react-router"; import { cn } from "@/lib/utils"; import { pluginRegistry } from "@/plugins"; +import { useAppStore } from "@/stores/useAppStore"; import { ConnectionIndicator } from "./ConnectionIndicator"; const CORE_NAV_ITEMS = [ @@ -12,12 +13,36 @@ const CORE_NAV_ITEMS = [ { label: "About", to: "/about" }, ] as const; +const MODE_META: Record = { + speedcamera: { + label: "Speed Camera", + badgeClass: "bg-blue-500/10 text-blue-400 border-blue-500/25", + }, + laptimer: { + label: "Lap Timer", + badgeClass: "bg-emerald-500/10 text-emerald-400 border-emerald-500/25", + }, + alignment: { + label: "Alignment", + badgeClass: "bg-amber-500/10 text-amber-400 border-amber-500/25", + }, + setup: { + label: "Setup", + badgeClass: "bg-purple-500/10 text-purple-400 border-purple-500/25", + }, +}; + interface NavigationMenuProps { className?: string; } export function NavigationMenu({ className }: NavigationMenuProps) { const pluginNavItems = pluginRegistry.getNavItems(); + const operatingMode = useAppStore((s) => s.operatingMode); + const currentModeMeta = MODE_META[operatingMode] ?? { + label: operatingMode, + badgeClass: "bg-muted text-muted-foreground border-border", + }; const allNavItems = [ CORE_NAV_ITEMS[0], // Home @@ -41,7 +66,16 @@ export function NavigationMenu({ className }: NavigationMenuProps) { ))} -
+
+ + {currentModeMeta.label} +
diff --git a/headless-rust/frontend/src/lib/rpc.ts b/headless-rust/frontend/src/lib/rpc.ts index c4575c3..6d5d31a 100644 --- a/headless-rust/frontend/src/lib/rpc.ts +++ b/headless-rust/frontend/src/lib/rpc.ts @@ -58,8 +58,10 @@ class SocketIoRpcClient { void store.refreshCameraStatus?.(); void store.refreshSerialStatus?.(); void store.refreshArmedStatus?.(); + void store.refreshOperatingMode?.(); }); + this.socket.on("disconnect", (reason) => { console.log(`[rpc-client] Socket.io disconnected (reason: ${reason})`); this.stopHeartbeat(); @@ -100,8 +102,17 @@ class SocketIoRpcClient { this.socket.on("armedStatus", (payload: { armed: boolean }) => { this.handlePushEvent("armedStatus", payload); }); + + this.socket.on("operatingMode", (payload: any) => { + this.handlePushEvent("operatingMode", payload); + }); + + this.socket.on("operatingModeChanged", (payload: any) => { + this.handlePushEvent("operatingModeChanged", payload); + }); } + /** * Monitor browser lifecycle events (tab switching, screen sleep/wake, Wi-Fi reconnect) * to immediately wake and verify the socket instead of waiting for OS TCP timeouts. @@ -284,7 +295,14 @@ class SocketIoRpcClient { store.handleArmedStatus(armedPayload.armed); break; } + case "operatingMode": + case "operatingModeChanged": { + const modePayload = payload as any; + store.handleOperatingModeStatus?.(modePayload); + break; + } case "updateAvailable": + store.setUpdateVersion((payload as any).version); store.setUpdatePhase("ready"); break; diff --git a/headless-rust/frontend/src/plugins/alignment/index.ts b/headless-rust/frontend/src/plugins/alignment/index.ts index 3bb56df..100617b 100644 --- a/headless-rust/frontend/src/plugins/alignment/index.ts +++ b/headless-rust/frontend/src/plugins/alignment/index.ts @@ -9,11 +9,8 @@ export const alignmentPlugin: UiPlugin = { id: "alignment", name: "Sensor Alignment", - navItems: [ - { label: "Alignment", to: "/alignment" }, - ], - mode: { + id: "alignment", label: "Alignment", icon: Crosshair, @@ -36,4 +33,9 @@ export const alignmentPlugin: UiPlugin = { } return false; }, + + onModeChange: (mode: string) => { + useAlignmentStore.setState({ active: mode === "alignment" }); + }, }; + diff --git a/headless-rust/frontend/src/plugins/alignment/routes/AlignmentPage.tsx b/headless-rust/frontend/src/plugins/alignment/routes/AlignmentPage.tsx index d221656..5372733 100644 --- a/headless-rust/frontend/src/plugins/alignment/routes/AlignmentPage.tsx +++ b/headless-rust/frontend/src/plugins/alignment/routes/AlignmentPage.tsx @@ -1,275 +1,13 @@ -import { useEffect, useState } from "react"; -import { useAlignmentStore } from "../store"; -import { SickSensorVisualizer } from "../components/SickSensorVisualizer"; -import { Button } from "@/components/ui/button"; -import { Badge } from "@/components/ui/badge"; -import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; -import { - Collapsible, - CollapsibleContent, - CollapsibleTrigger, -} from "@/components/ui/collapsible"; -import { Link } from "@tanstack/react-router"; -import { - Play, - Square, - Volume2, - VolumeX, - CheckCircle2, - ChevronRight, - ChevronDown, - Camera, - Sparkles, - Activity, -} from "lucide-react"; -import { cn } from "@/lib/utils"; +import { useEffect } from "react"; +import { useNavigate } from "@tanstack/react-router"; +// ponytail: alignment merged into unified /setup hardware wizard export function AlignmentPage() { - const { - active, - loading, - startAlignment, - stopAlignment, - sensor1Interrupted, - sensor2Interrupted, - audioFeedbackEnabled, - toggleAudio, - lastUpdate, - } = useAlignmentStore(); + const navigate = useNavigate(); - const [activeTab, setActiveTab] = useState<"align" | "test">("align"); - const [tipsOpen, setTipsOpen] = useState(false); - const [testEvents, setTestEvents] = useState< - { id: number; text: string; time: string; ok: boolean }[] - >([]); - - // Start monitoring automatically on mount, stop on unmount - useEffect(() => { - void startAlignment(); - return () => { - void stopAlignment(); - }; - }, [startAlignment, stopAlignment]); - - // Track pass events during test mode useEffect(() => { - if (!active) return; - const nowStr = new Date().toLocaleTimeString(); - if (sensor1Interrupted && !sensor2Interrupted) { - setTestEvents((prev) => [ - { id: Date.now(), text: "Sensor 1 (Entry) beam broken", time: nowStr, ok: true }, - ...prev.slice(0, 5), - ]); - } else if (!sensor1Interrupted && sensor2Interrupted) { - setTestEvents((prev) => [ - { id: Date.now(), text: "Sensor 2 (Exit) beam broken", time: nowStr, ok: true }, - ...prev.slice(0, 5), - ]); - } - }, [sensor1Interrupted, sensor2Interrupted, active]); - - const bothAligned = !sensor1Interrupted && !sensor2Interrupted; - - return ( -
- {/* ── Wizard Header ────────────────────────────────────────── */} -
-
-
-

Sensor Alignment

- - Hardware Setup - -
-

- Dual Sick light barriers optical alignment & physical verification. -

-
- - {/* Action Controls */} -
- - - {!active ? ( - - ) : ( - - )} -
-
- - {/* ── Stepper Navigation — Always Horizontal Grid ───────────── */} -
- - - - - - - 3 - - Camera - - -
- - {/* ── Tab 1: Optical Alignment ──────────────────────────────── */} - {activeTab === "align" && ( -
- {/* Unified Physical Assembly Card */} - - - - Dual Barrier Assembly (Side-by-Side) - {lastUpdate && ( - - - 20 Hz Stream - - )} - - - - - - - - {/* Daylight Alignment Tips Accordion (Collapsible for zero clutter on mobile) */} - - - - - -
- 1. Coarse Aiming: Point light barrier head towards roadside reflector center. -
-
- 2. Micrometer Adjustment: Turn bracket screws until both sensors show ALIGNED. -
-
- 3. Flutter Correction: If FLUTTER flashes, reflector is on edge. Re-center until solid. -
-
- 4. Audio Assist: Listen for tone pitch shifts without staring at screen. -
-
-
-
- )} - - {/* ── Tab 2: Walk-Through Trigger Test ───────────────────────── */} - {activeTab === "test" && ( -
- - - - Beam Walk-Through Test - - - -

- Walk through beam: Sensor 1 (Entry) must trigger first, then Sensor 2 (Exit). -

- - - - {/* Event Log */} -
-
- Recent Beam Events -
- {testEvents.length === 0 ? ( -

- Break light barrier to record triggers. -

- ) : ( -
- {testEvents.map((evt) => ( -
- {evt.text} - {evt.time} -
- ))} -
- )} -
+ navigate({ to: "/setup" }); + }, [navigate]); - - - -
-
-
- )} -
- ); + return null; } diff --git a/headless-rust/frontend/src/routes/index.tsx b/headless-rust/frontend/src/routes/index.tsx index 407ef6d..1910f46 100644 --- a/headless-rust/frontend/src/routes/index.tsx +++ b/headless-rust/frontend/src/routes/index.tsx @@ -6,7 +6,9 @@ import { LastCapturedImage } from "@/components/LastCapturedImage"; import { StatusBadge } from "@/components/StatusBadge"; import { ViolationCard } from "@/components/ViolationCard"; import { ArmingButton } from "@/components/ArmingButton"; +import { ModeChangeGuardDialog } from "@/components/ModeChangeGuardDialog"; import { useAppStore } from "@/stores/useAppStore"; + import { useLapStore } from "@/plugins/laptimer/store"; import { pluginRegistry } from "@/plugins"; import { getRpc } from "@/lib/rpc"; @@ -28,7 +30,13 @@ function HomePage() { const lastViolation = useAppStore((s) => s.lastViolation); const setMaxSpeed = useAppStore((s) => s.setMaxSpeed); const appMode = useAppStore((s) => s.appMode); - const setAppMode = useAppStore((s) => s.setAppMode); + const isArmed = useAppStore((s) => s.isArmed); + const availableModes = useAppStore((s) => s.availableModes); + const requestModeChange = useAppStore((s) => s.requestModeChange); + + const [guardDialogOpen, setGuardDialogOpen] = useState(false); + const [pendingTargetMode, setPendingTargetMode] = useState(null); + const [guardMessage, setGuardMessage] = useState(undefined); const lapState = useLapStore((s) => s.lapState); const isLapActive = lapState !== "idle"; @@ -38,6 +46,31 @@ function HomePage() { const serialStatus = connectedPort ? "connected" : "disconnected"; const cameraStatus = cameraConnected ? "connected" : "unknown"; + const handleModeClick = async (targetMode: string) => { + if (appMode === targetMode) return; + const res = await requestModeChange(targetMode); + if (!res.success) { + if (res.safeguard === "ARMED") { + setPendingTargetMode(targetMode); + setGuardMessage(res.message); + setGuardDialogOpen(true); + } else { + toast.error(res.message || `Cannot switch to ${targetMode}`); + } + } + }; + + const handleConfirmDisarmAndSwitch = async () => { + if (!pendingTargetMode) return; + setGuardDialogOpen(false); + const res = await requestModeChange(pendingTargetMode, true); + if (!res.success) { + toast.error(res.message || "Failed to switch mode"); + } + setPendingTargetMode(null); + }; + + // Load relevant settings into the store on mount useEffect(() => { getRpc() @@ -67,7 +100,7 @@ function HomePage() {
+
{/* Main workspace */} @@ -178,6 +219,20 @@ function HomePage() { )} + + { + setGuardDialogOpen(false); + setPendingTargetMode(null); + }} + /> ); } + diff --git a/headless-rust/frontend/src/routes/setup.tsx b/headless-rust/frontend/src/routes/setup.tsx index 2893c3a..d8a4c85 100644 --- a/headless-rust/frontend/src/routes/setup.tsx +++ b/headless-rust/frontend/src/routes/setup.tsx @@ -1,140 +1,420 @@ import { useEffect, useState, useRef } from "react"; -import { createRoute } from "@tanstack/react-router"; +import { createRoute, useNavigate } from "@tanstack/react-router"; import { RootRoute } from "./__root"; import { useAppStore } from "@/stores/useAppStore"; +import { useAlignmentStore } from "@/plugins/alignment/store"; +import { SickSensorVisualizer } from "@/plugins/alignment/components/SickSensorVisualizer"; +import { ModeChangeGuardDialog } from "@/components/ModeChangeGuardDialog"; import { useBackendEvent } from "@/hooks/useBackendEvent"; import { Button } from "@/components/ui/button"; import { Badge } from "@/components/ui/badge"; -import { PlayIcon, SquareIcon, AlertCircleIcon, Loader2Icon } from "lucide-react"; +import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; +import { + PlayIcon, + SquareIcon, + AlertCircleIcon, + Loader2Icon, + Volume2, + VolumeX, + CheckCircle2, + Sparkles, + Activity, + ArrowRight, + Sliders, + Check, +} from "lucide-react"; import { toast } from "sonner"; +import { cn } from "@/lib/utils"; export const SetupRoute = createRoute({ getParentRoute: () => RootRoute, path: "/setup", - component: SetupPage, + component: UnifiedSetupPage, }); -function SetupPage() { - const connected = useAppStore((s) => s.cameraConnected); - const setupStreamActive = useAppStore((s) => s.setupStreamActive); - const startSetupStream = useAppStore((s) => s.startSetupStream); - const stopSetupStream = useAppStore((s) => s.stopSetupStream); +function UnifiedSetupPage() { + const navigate = useNavigate(); + + // Operating mode & store + const operatingMode = useAppStore((s) => s.operatingMode); + const isArmed = useAppStore((s) => s.isArmed); + const requestModeChange = useAppStore((s) => s.requestModeChange); + const cameraConnected = useAppStore((s) => s.cameraConnected); + const connectedPort = useAppStore((s) => s.connectedPort); const refreshCameraStatus = useAppStore((s) => s.refreshCameraStatus); + const liveFrame = useAppStore((s) => s.liveFrame); - const [frame, setFrame] = useState(null); - const [isToggling, setIsToggling] = useState(false); + // Alignment store + const { + active: alignmentActive, + sensor1Interrupted, + sensor2Interrupted, + audioFeedbackEnabled, + toggleAudio, + lastUpdate, + } = useAlignmentStore(); - const setupStreamActiveRef = useRef(setupStreamActive); - setupStreamActiveRef.current = setupStreamActive; + // Local state + const [activeStep, setActiveStep] = useState<"alignment" | "camera">( + operatingMode === "alignment" ? "alignment" : "camera" + ); + const [isChangingMode, setIsChangingMode] = useState(false); + const [guardDialogOpen, setGuardDialogOpen] = useState(false); + const [pendingTargetMode, setPendingTargetMode] = useState(null); + const [testEvents, setTestEvents] = useState< + { id: number; text: string; time: string; ok: boolean }[] + >([]); - // Real-time frame listener - useBackendEvent("liveFrame", (newFrame) => { - setFrame(newFrame as string); - }); + // Reflect external mode changes (e.g. from another client) into wizard tab + useEffect(() => { + if (operatingMode === "alignment") { + setActiveStep("alignment"); + } else if (operatingMode === "setup") { + setActiveStep("camera"); + } + }, [operatingMode]); - // Refresh hardware status on mount + // Ensure initial mode is set on entry useEffect(() => { void refreshCameraStatus(); - }, [refreshCameraStatus]); + if (operatingMode !== "alignment" && operatingMode !== "setup") { + // Default entering wizard to alignment step + void requestModeChange("alignment"); + } + }, []); - // Clean unmount: Stop stream only if it was active + // Cleanup on unmount: return to speedcamera mode + const operatingModeRef = useRef(operatingMode); + operatingModeRef.current = operatingMode; useEffect(() => { return () => { - if (setupStreamActiveRef.current) { - stopSetupStream().catch(console.error); + if (operatingModeRef.current === "alignment" || operatingModeRef.current === "setup") { + void useAppStore.getState().requestModeChange("speedcamera"); } }; - }, [stopSetupStream]); + }, []); - const handleStart = async () => { - if (!connected) { - toast.error("Camera is not connected!"); - return; + // Track beam breaks during alignment + useEffect(() => { + if (operatingMode !== "alignment") return; + const nowStr = new Date().toLocaleTimeString(); + if (sensor1Interrupted && !sensor2Interrupted) { + setTestEvents((prev) => [ + { id: Date.now(), text: "Sensor 1 (Entry) beam broken", time: nowStr, ok: true }, + ...prev.slice(0, 4), + ]); + } else if (!sensor1Interrupted && sensor2Interrupted) { + setTestEvents((prev) => [ + { id: Date.now(), text: "Sensor 2 (Exit) beam broken", time: nowStr, ok: true }, + ...prev.slice(0, 4), + ]); } - setIsToggling(true); + }, [sensor1Interrupted, sensor2Interrupted, operatingMode]); + + const handleStepSwitch = async (targetStep: "alignment" | "camera") => { + const targetMode = targetStep === "alignment" ? "alignment" : "setup"; + if (operatingMode === targetMode) return; + + setIsChangingMode(true); try { - await startSetupStream(); - toast.success("Preview stream started"); - } catch { - toast.error("Failed to start setup stream"); + const res = await requestModeChange(targetMode); + if (!res.success) { + if (res.safeguard === "ARMED") { + setPendingTargetMode(targetMode); + setGuardDialogOpen(true); + } else { + toast.error(res.message || "Failed to switch setup mode"); + } + } else { + setActiveStep(targetStep); + } } finally { - setIsToggling(false); + setIsChangingMode(false); } }; - const handleStop = async () => { - setIsToggling(true); + const handleConfirmDisarmAndSwitch = async () => { + if (!pendingTargetMode) return; + setGuardDialogOpen(false); + setIsChangingMode(true); try { - await stopSetupStream(); - setFrame(null); - toast.info("Preview stream stopped"); - } catch { - toast.error("Failed to stop setup stream"); + const res = await requestModeChange(pendingTargetMode, true); + if (res.success) { + setActiveStep(pendingTargetMode === "alignment" ? "alignment" : "camera"); + } else { + toast.error(res.message || "Failed to switch mode"); + } } finally { - setIsToggling(false); + setIsChangingMode(false); + setPendingTargetMode(null); } }; + const handleFinishSetup = async () => { + setIsChangingMode(true); + try { + await requestModeChange("speedcamera"); + toast.success("Setup complete. Switched to Speed Camera mode."); + navigate({ to: "/" }); + } finally { + setIsChangingMode(false); + } + }; + + const bothAligned = !sensor1Interrupted && !sensor2Interrupted; + return ( -
-
+
+ {/* ── Top Header ────────────────────────────────────────────── */} +
-

Camera Setup

-

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

+

Hardware Setup Wizard

+ + Multi-Client Synced + +
+

+ Step-by-step optical barrier alignment and industrial camera preview.

-
- - {setupStreamActive ? "Streaming" : "Stopped"} - - {!setupStreamActive ? ( - +
+
+ + {/* ── Stepper Header ────────────────────────────────────────── */} +
+
+ + +
-
- {setupStreamActive ? ( - frame ? ( - Camera Livestream - ) : ( -
- Waiting for frame from camera... + {/* ── Wizard Content ────────────────────────────────────────── */} +
+ {activeStep === "alignment" && ( +
+ {/* Alignment Controls Bar */} +
+
+ + {alignmentActive ? "Alignment Active" : "Dormant"} + + {lastUpdate && ( + + + Live 20Hz + + )} +
+ +
+ +
+
+ + {/* Visualizer */} + + + + Optical Light Barrier Status + + {connectedPort ? `Port: ${connectedPort}` : "Serial disconnected"} + + + + + + + + + {/* Walk Test Events */} + + + + Beam Break Test Log + + + + {testEvents.length === 0 ? ( +

+ Wave hand or object through sensors to verify sequence. +

+ ) : ( +
+ {testEvents.map((ev) => ( +
+ + + {ev.text} + + {ev.time} +
+ ))} +
+ )} +
+
+ + {/* Next Step Button */} +
+ +
+
+ )} + + {activeStep === "camera" && ( +
+ {/* Camera Setup Preview Box */} + + +
+ Live Camera Stream +

+ Flash strobe disabled during preview. Real-time auto-exposure active. +

+
+ + {operatingMode === "setup" ? "Streaming (10 FPS)" : "Standby"} + +
+ +
+ {operatingMode === "setup" ? ( + liveFrame ? ( + Camera Preview + ) : ( +
+ + Receiving frames from GigE camera... +
+ ) + ) : ( +
+

{cameraConnected ? "Preview stream paused" : "Camera disconnected"}

+

+ Switching to this step activates the live setup stream. +

+
+ )} +
+
+ + {/* Finish Button */} +
+ +
- ) - ) : ( -
-

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

- {connected && ( -

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

- )}
)}
+ + {/* Safeguard Modal Dialog */} + { + setGuardDialogOpen(false); + setPendingTargetMode(null); + }} + />
); } diff --git a/headless-rust/frontend/src/shared/types.ts b/headless-rust/frontend/src/shared/types.ts index 2a743a1..590c4a3 100644 --- a/headless-rust/frontend/src/shared/types.ts +++ b/headless-rust/frontend/src/shared/types.ts @@ -634,6 +634,17 @@ export type SpeedcameraRPC = { params: { token: string }; response: { valid: boolean; login?: string; error?: string }; }; + + // Operating mode state machine + getOperatingMode: { + params: Record; + response: OperatingModeStatus; + }; + setOperatingMode: { + params: { targetMode: string; force?: boolean }; + response: SetOperatingModeResult; + }; + }, Record>; webview: RPCDefinition, { @@ -657,5 +668,30 @@ export type SpeedcameraRPC = { armedStatus: { armed: boolean }; // Violation notification violation: Violation; + // Operating mode notifications + operatingMode: OperatingModeStatus; + operatingModeChanged: OperatingModeStatus; }>; }; + +export interface ModeAvailability { + available: boolean; + reason?: string; +} + +export interface OperatingModeStatus { + currentMode: string; + previousMode: string | null; + availableModes: Record; + armed: boolean; + timestampMs: number; +} + +export interface SetOperatingModeResult { + success: boolean; + mode?: string; + safeguard?: string; + message?: string; + status?: OperatingModeStatus; +} + diff --git a/headless-rust/frontend/src/stores/slices/systemSlice.ts b/headless-rust/frontend/src/stores/slices/systemSlice.ts index 03b3e20..04e222f 100644 --- a/headless-rust/frontend/src/stores/slices/systemSlice.ts +++ b/headless-rust/frontend/src/stores/slices/systemSlice.ts @@ -3,10 +3,11 @@ import { getRpc } from "@/lib/rpc"; import type { SerialSlice } from "./serialSlice"; import type { CameraSlice } from "./cameraSlice"; import type { MeasurementSlice } from "./measurementSlice"; +import type { ModeAvailability, OperatingModeStatus, SetOperatingModeResult } from "@/shared/types"; import { pluginRegistry } from "@/plugins"; export type SystemState = "PASSIVE" | "DISARMED" | "ARMED"; -export type AppMode = "speedcamera" | string; +export type AppMode = "speedcamera" | "laptimer" | "alignment" | "setup" | string; export interface SystemSlice { /** Underlying daemon armed state */ @@ -17,9 +18,18 @@ export interface SystemSlice { setArmed: (armed: boolean) => Promise; handleArmedStatus: (armed: boolean) => void; refreshArmedStatus: () => Promise; - /** Active mode — routes serial events to violation or plugin handler */ + + /** Centralized synchronized operating mode */ + operatingMode: AppMode; + previousMode: string | null; + availableModes: Record; + handleOperatingModeStatus: (status: OperatingModeStatus) => void; + refreshOperatingMode: () => Promise; + requestModeChange: (targetMode: string, force?: boolean) => Promise; + + /** Backwards-compatible alias for UI components */ appMode: AppMode; - setAppMode: (mode: AppMode) => void; + setAppMode: (mode: AppMode) => Promise; } export const createSystemSlice: StateCreator< @@ -55,10 +65,58 @@ export const createSystemSlice: StateCreator< console.warn("[systemSlice] Failed to get armed status:", e); } }, + + operatingMode: "speedcamera", + previousMode: null, + availableModes: {}, appMode: "speedcamera", - setAppMode: (mode) => { - pluginRegistry.dispatchModeChange(mode); - set({ appMode: mode }); + + handleOperatingModeStatus: (status: OperatingModeStatus) => { + pluginRegistry.dispatchModeChange(status.currentMode); + const isSetup = status.currentMode === "setup"; + set({ + operatingMode: status.currentMode, + previousMode: status.previousMode, + availableModes: status.availableModes || {}, + appMode: status.currentMode, + isArmed: status.armed, + setupStreamActive: isSetup, + liveFrame: isSetup ? get().liveFrame : null, + }); + get().handleArmedStatus(status.armed); + }, + + + refreshOperatingMode: async () => { + try { + const res = await getRpc().request.getOperatingMode({}); + if (res) { + get().handleOperatingModeStatus(res); + } + } catch (e) { + console.warn("[systemSlice] Failed to get operating mode:", e); + } + }, + + requestModeChange: async (targetMode: string, force?: boolean) => { + try { + const res = await getRpc().request.setOperatingMode({ targetMode, force }); + if (res.success && res.status) { + get().handleOperatingModeStatus(res.status); + } + return res; + } catch (e: any) { + console.error("[systemSlice] Error setting operating mode:", e); + return { + success: false, + message: e?.message || "Failed to switch operating mode", + }; + } + }, + + setAppMode: async (mode: AppMode) => { + return get().requestModeChange(mode); }, }); + From fdf060bf31fdcddca5f701ded08673818ade7e2e Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Wed, 9 Sep 2026 20:30:00 +0200 Subject: [PATCH 4/4] fix: TypeScript errors --- headless-rust/frontend/src/lib/rpc.ts | 2 +- headless-rust/frontend/src/plugins/types.ts | 2 +- headless-rust/frontend/src/routes/index.tsx | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/headless-rust/frontend/src/lib/rpc.ts b/headless-rust/frontend/src/lib/rpc.ts index 6d5d31a..50a113d 100644 --- a/headless-rust/frontend/src/lib/rpc.ts +++ b/headless-rust/frontend/src/lib/rpc.ts @@ -314,7 +314,7 @@ class SocketIoRpcClient { } // 2. Dispatch to custom pub-sub event listeners - this.emit(event, payload); + this.emit(event as any, payload as any); } public async call(method: string, params: any): Promise { diff --git a/headless-rust/frontend/src/plugins/types.ts b/headless-rust/frontend/src/plugins/types.ts index 3e53bff..1cae63a 100644 --- a/headless-rust/frontend/src/plugins/types.ts +++ b/headless-rust/frontend/src/plugins/types.ts @@ -5,7 +5,7 @@ import type { SerialStatusPayload } from "@/shared/types"; export interface PluginMode { id: string; label: string; - icon: ComponentType<{ className?: string; strokeWidth?: number; size?: number }>; + icon: ComponentType | any; } export interface PluginNavItem { diff --git a/headless-rust/frontend/src/routes/index.tsx b/headless-rust/frontend/src/routes/index.tsx index 1910f46..f8c245d 100644 --- a/headless-rust/frontend/src/routes/index.tsx +++ b/headless-rust/frontend/src/routes/index.tsx @@ -1,4 +1,4 @@ -import { useEffect } from "react"; +import { useEffect, useState } from "react"; import { createRoute } from "@tanstack/react-router"; import { toast } from "sonner"; import { RootRoute } from "./__root";