use crate::controller::ControlSource; use crate::engine::EngineControlHandle; use crate::nomad_elrs::{CRSF_CHANNEL_MAX, CRSF_CHANNEL_MID, CRSF_CHANNEL_MIN}; use crate::telemetry_osd::{TelemetryReceiver, TelemetryState}; use anyhow::Result; use parking_lot::Mutex; use std::net::UdpSocket; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::thread; use std::time::{Duration, Instant}; const G29_TIMEOUT_MS: u64 = 1500; const TOAST_DURATION_MS: u64 = 1500; /// État temps réel reçu depuis le volant G29 (RP2350 -> ESP32-C3 -> UDP) #[derive(Debug, Clone)] pub struct G29State { pub connected: bool, pub failsafe: bool, pub armed: bool, pub gear: i8, pub steering_pct: i8, pub throttle_pct: u8, pub brake_pct: u8, pub clutch_pct: u8, pub steer_crsf: u16, pub throttle_crsf: u16, pub brake_crsf: u16, pub clutch_crsf: u16, pub ffb_raw: u8, pub ffb_pct: u8, pub vib_pct: u8, pub remote_source: ControlSource, pub packets_received: u64, pub last_packet: Option, pub last_button: String, pub last_button_at: Option, pub toast_text: String, pub toast_until: Option, } impl Default for G29State { fn default() -> Self { Self { connected: false, failsafe: false, armed: false, gear: 0, steering_pct: 0, throttle_pct: 0, brake_pct: 0, clutch_pct: 0, steer_crsf: CRSF_CHANNEL_MID, throttle_crsf: CRSF_CHANNEL_MID, brake_crsf: CRSF_CHANNEL_MID, clutch_crsf: CRSF_CHANNEL_MID, ffb_raw: 140, ffb_pct: 55, vib_pct: 50, remote_source: ControlSource::G29, packets_received: 0, last_packet: None, last_button: String::new(), last_button_at: None, toast_text: String::new(), toast_until: None, } } } impl G29State { pub fn is_live(&self) -> bool { self.connected && self .last_packet .map(|t| t.elapsed() <= Duration::from_millis(G29_TIMEOUT_MS)) .unwrap_or(false) } pub fn set_toast(&mut self, msg: impl Into) { self.toast_text = msg.into(); self.toast_until = Some(Instant::now() + Duration::from_millis(TOAST_DURATION_MS)); } pub fn active_toast(&self) -> Option<&str> { match self.toast_until { Some(until) if Instant::now() < until && !self.toast_text.is_empty() => { Some(&self.toast_text) } _ => None, } } pub fn gear_label(&self) -> &'static str { match self.gear { -1 => "R", 0 => "N", 1 => "1", 2 => "2", 3 => "3", _ => "?", } } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum G29ButtonEvent { Cross, Circle, Square, Triangle, Share, Options, Ps, L3, R3, DpadUp, DpadDown, DpadLeft, DpadRight, } impl G29ButtonEvent { pub fn from_name(name: &str) -> Option { match name.trim() { "CROSS" => Some(Self::Cross), "CIRCLE" => Some(Self::Circle), "SQUARE" => Some(Self::Square), "TRIANGLE" => Some(Self::Triangle), "SHARE" => Some(Self::Share), "OPTIONS" => Some(Self::Options), "PS" => Some(Self::Ps), "L3" => Some(Self::L3), "R3" => Some(Self::R3), "DPAD_UP" => Some(Self::DpadUp), "DPAD_DOWN" => Some(Self::DpadDown), "DPAD_LEFT" => Some(Self::DpadLeft), "DPAD_RIGHT" => Some(Self::DpadRight), _ => None, } } } /// Récepteur UDP non-bloquant pour la passerelle Wi-Fi G29 pub struct G29BridgeReceiver { state: Arc>, stop_flag: Arc, worker: Option>, } impl G29BridgeReceiver { pub fn start( bind_ip: &str, port: u16, control: EngineControlHandle, telemetry: Option>>, allowed_peers: Vec, ) -> Result { let addr = format!("{}:{}", bind_ip, port); let socket = UdpSocket::bind(&addr)?; socket.set_read_timeout(Some(Duration::from_millis(100)))?; log::info!( "[G29 Bridge] En écoute UDP unifiée sur {} (pairs autorisés: {:?})", addr, allowed_peers ); let state = Arc::new(Mutex::new(G29State::default())); let state_clone = Arc::clone(&state); let stop_flag = Arc::new(AtomicBool::new(false)); let stop_clone = Arc::clone(&stop_flag); let worker = thread::Builder::new() .name("g29-udp-rx".into()) .spawn(move || { let mut buf = [0u8; 2048]; let mut last_reject_log: Option = None; while !stop_clone.load(Ordering::Acquire) { if let Ok((len, src)) = socket.recv_from(&mut buf) { if !Self::is_peer_allowed(src.ip(), &allowed_peers) { if last_reject_log .is_none_or(|t| t.elapsed() >= Duration::from_secs(5)) { log::warn!( "[G29 Bridge] Paquet UDP rejeté depuis IP non autorisée : {}", src ); last_reject_log = Some(Instant::now()); } continue; } if let Ok(text) = std::str::from_utf8(&buf[..len]) { for line in text.lines() { Self::process_line( line, &state_clone, Some(&control), telemetry.as_ref(), ); } } } // Vérifier le timeout G29 à chaque itération (même si des trames $CRSF continuent d'arriver) { let mut st = state_clone.lock(); if st.connected && !st.is_live() { st.connected = false; st.armed = false; st.failsafe = true; st.gear = 0; st.throttle_pct = 0; st.brake_pct = 0; st.clutch_pct = 0; log::warn!("[G29 Bridge] Perte de liaison avec le volant G29."); } } } log::info!("[G29 Bridge] Thread d'écoute UDP arrêté."); })?; Ok(Self { state, stop_flag, worker: Some(worker), }) } #[allow(dead_code)] pub fn send_command(target_ip: &str, target_port: u16, cmd: &str) -> Result<()> { let socket = UdpSocket::bind("0.0.0.0:0")?; let target = format!("{}:{}", target_ip.trim(), target_port); let trimmed = cmd.trim(); let payload = if trimmed.starts_with('$') && !trimmed.contains('*') { crate::nomad_elrs::NomadHeadTracker::append_nmea_crc8(trimmed) } else { format!("{}\n", trimmed) }; socket.send_to(payload.as_bytes(), target)?; Ok(()) } /// Ping applicatif UDP vers le relais Radxa Zero 3W (`$PING,` -> `$PONG,,`). /// Retourne `(rtt_ms, rp2350_uart_connected)`. pub fn ping_radxa_relay(target_ip: &str, target_port: u16) -> Result<(f32, bool)> { let socket = UdpSocket::bind("0.0.0.0:0")?; socket.set_read_timeout(Some(Duration::from_millis(450)))?; let target = format!("{}:{}", target_ip.trim(), target_port); let seq: u64 = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map(|d| d.as_millis() as u64 % 1_000_000) .unwrap_or(1); let payload = format!("$PING,{}\n", seq); let t0 = Instant::now(); socket.send_to(payload.as_bytes(), &target)?; let mut buf = [0u8; 128]; let (len, _) = socket.recv_from(&mut buf)?; let rtt_ms = t0.elapsed().as_secs_f32() * 1000.0; let reply = std::str::from_utf8(&buf[..len])?.trim(); let rest = reply .strip_prefix("$PONG,") .ok_or_else(|| anyhow::anyhow!("Réponse inattendue : {}", reply))?; let mut parts = rest.split(','); let rx_seq = parts .next() .and_then(|s| s.parse::().ok()) .ok_or_else(|| anyhow::anyhow!("Séquence PONG invalide : {}", reply))?; if rx_seq != seq { anyhow::bail!("Séquence PONG discordante ({} != {})", rx_seq, seq); } let uart_ok = parts.next().map(|s| s.trim() == "1").unwrap_or(false); Ok((rtt_ms, uart_ok)) } pub fn is_peer_allowed(src_ip: std::net::IpAddr, allowed_peers: &[std::net::IpAddr]) -> bool { src_ip.is_loopback() || allowed_peers.is_empty() || allowed_peers.contains(&src_ip) } pub fn state(&self) -> Arc> { Arc::clone(&self.state) } /// Vérifie et retire le suffixe CRC-8 `*XX` optionnel sur les trames `$G29` / `$G29_EVT`. /// Si `*` est présent, le CRC-8 DVB-S2 doit être valide (sinon la trame est rejetée). fn verify_optional_crc8(line: &str) -> Option<&str> { if let Some((body, crc_hex)) = line.rsplit_once('*') { if crc_hex.len() != 2 { return None; } let expected = u8::from_str_radix(crc_hex, 16).ok()?; let calc = crate::nomad_elrs::NomadHeadTracker::crc8_dvb_s2(body.as_bytes()); if calc == expected { Some(body) } else { None } } else { Some(line) } } pub fn process_line( raw_line: &str, state: &Arc>, control: Option<&EngineControlHandle>, telemetry: Option<&Arc>>, ) { let line = raw_line.trim(); if line.starts_with("$G29,") { if let Some(verified) = Self::verify_optional_crc8(line) { if let Some(rest) = verified.strip_prefix("$G29,") { Self::parse_status_fields(rest, state); } } } else if line.starts_with("$G29_EVT,") { if let Some(verified) = Self::verify_optional_crc8(line) { if let Some(rest) = verified.strip_prefix("$G29_EVT,") { Self::parse_button_event(rest, state, control); } } } else if let Some(hex) = line.strip_prefix("$CRSF,") { if let Some(telem) = telemetry { Self::parse_crsf_hex(hex, telem); } } } fn parse_crsf_hex(hex: &str, telemetry: &Arc>) { let bytes = hex.trim().as_bytes(); if bytes.len() < 8 || !bytes.len().is_multiple_of(2) || bytes.len() > 128 { return; } let mut raw = [0u8; 64]; let mut out_len = 0; for chunk in bytes.as_chunks::<2>().0 { let Some(hi) = Self::hex_nibble(chunk[0]) else { return; }; let Some(lo) = Self::hex_nibble(chunk[1]) else { return; }; raw[out_len] = (hi << 4) | lo; out_len += 1; } TelemetryReceiver::parse_datagram(&raw[..out_len], telemetry); } #[inline] fn hex_nibble(b: u8) -> Option { match b { b'0'..=b'9' => Some(b - b'0'), b'a'..=b'f' => Some(b - b'a' + 10), b'A'..=b'F' => Some(b - b'A' + 10), _ => None, } } fn parse_status_fields(fields: &str, state: &Arc>) { let mut st = state.lock(); let had_packets = st.packets_received > 0; let prev_ffb_pct = st.ffb_pct; let prev_vib_pct = st.vib_pct; for pair in fields.split(',') { let Some((k, v)) = pair.split_once('=') else { continue; }; match k.trim() { "ARM" => { if let Ok(val) = v.trim().parse::() { st.armed = val != 0; } } "GEAR" => { if let Ok(val) = v.trim().parse::() { st.gear = val.clamp(-1, 3); } } "THROT" => { if let Ok(val) = v.trim().parse::() { st.throttle_pct = val.min(100); } } "BRAKE" => { if let Ok(val) = v.trim().parse::() { st.brake_pct = val.min(100); } } "CLUTCH" => { if let Ok(val) = v.trim().parse::() { st.clutch_pct = val.min(100); } } "STEER" => { if let Ok(val) = v.trim().parse::() { st.steering_pct = val.clamp(-100, 100); } } "CH1" => { if let Ok(val) = v.trim().parse::() { st.steer_crsf = val.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX); } } "CH2" => { if let Ok(val) = v.trim().parse::() { st.throttle_crsf = val.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX); } } "CH3" => { if let Ok(val) = v.trim().parse::() { st.brake_crsf = val.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX); } } "CH4" => { if let Ok(val) = v.trim().parse::() { st.clutch_crsf = val.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX); } } "FFB" => { if let Ok(val) = v.trim().parse::() { st.ffb_raw = val; st.ffb_pct = ((val as u16 * 100) / 255) as u8; } } "VIB" => { if let Ok(val) = v.trim().parse::() { st.vib_pct = val.min(100); } } "FAIL" => { if let Ok(val) = v.trim().parse::() { st.failsafe = val != 0; } } "SRC" => { st.remote_source = ControlSource::from_str(v); } _ => {} } } if !st.connected { log::info!("[G29 Bridge] Volant G29 connecté en Wi-Fi UDP."); } st.connected = true; st.packets_received = st.packets_received.wrapping_add(1); st.last_packet = Some(Instant::now()); if had_packets && st.ffb_pct != prev_ffb_pct { let pct = st.ffb_pct; st.set_toast(format!("FFB {}%", pct)); } else if had_packets && st.vib_pct != prev_vib_pct { let pct = st.vib_pct; st.set_toast(format!("VIB {}%", pct)); } } fn parse_button_event( fields: &str, state: &Arc>, control: Option<&EngineControlHandle>, ) { let Some((_, btn_name)) = fields.split_once("BTN=") else { return; }; let Some(btn) = G29ButtonEvent::from_name(btn_name) else { return; }; log::info!("[G29 Bridge] Bouton volant reçu : {:?}", btn); let menu_open = control.map(|c| c.is_vr_menu_open()).unwrap_or(false); let toast = match btn { G29ButtonEvent::Options | G29ButtonEvent::L3 => { if let Some(ctrl) = control { let open = ctrl.toggle_vr_menu(); Some(if open { "MENU VR ON".to_string() } else { "MENU VR OFF".to_string() }) } else { Some("MENU VR".to_string()) } } G29ButtonEvent::Cross if menu_open => { if let Some(ctrl) = control { ctrl.vr_menu_activate(); } None } G29ButtonEvent::Circle if menu_open => { let closed = control.map(|ctrl| ctrl.close_vr_menu()).unwrap_or(true); Some(if closed { "MENU VR OFF" } else { "RETOUR MENU" }.to_string()) } G29ButtonEvent::DpadUp if menu_open => { if let Some(ctrl) = control { ctrl.vr_menu_move(-1); } None } G29ButtonEvent::DpadDown if menu_open => { if let Some(ctrl) = control { ctrl.vr_menu_move(1); } None } G29ButtonEvent::DpadLeft if menu_open => { if let Some(ctrl) = control { ctrl.vr_menu_adjust(-1); } None } G29ButtonEvent::DpadRight if menu_open => { if let Some(ctrl) = control { ctrl.vr_menu_adjust(1); } None } G29ButtonEvent::Cross | G29ButtonEvent::Ps | G29ButtonEvent::R3 => { if let Some(ctrl) = control { ctrl.request_recenter(); } Some("TARE HT OK".to_string()) } G29ButtonEvent::Share | G29ButtonEvent::Circle => { if let Some(ctrl) = control { let now_rec = ctrl.toggle_dvr(); Some(if now_rec { "DVR REC".to_string() } else { "DVR STOP".to_string() }) } else { Some("DVR TOGGLE".to_string()) } } G29ButtonEvent::Triangle => { if let Some(ctrl) = control { let now_on = ctrl.toggle_telemetry(); Some(if now_on { "OSD ON".to_string() } else { "OSD OFF".to_string() }) } else { Some("OSD TOGGLE".to_string()) } } G29ButtonEvent::Square => { if let Some(ctrl) = control { let mode_lbl = ctrl.cycle_projection_mode(); Some(format!("PROJ: {}", mode_lbl)) } else { Some("PROJ CYCLE".to_string()) } } G29ButtonEvent::DpadUp => { if let Some(ctrl) = control { ctrl.adjust_head_trim(0.0, 1.0); } Some("TILT +1".to_string()) } G29ButtonEvent::DpadDown => { if let Some(ctrl) = control { ctrl.adjust_head_trim(0.0, -1.0); } Some("TILT -1".to_string()) } G29ButtonEvent::DpadLeft => { if let Some(ctrl) = control { ctrl.adjust_head_trim(-1.0, 0.0); } Some("PAN -1".to_string()) } G29ButtonEvent::DpadRight => { if let Some(ctrl) = control { ctrl.adjust_head_trim(1.0, 0.0); } Some("PAN +1".to_string()) } }; { let mut st = state.lock(); st.connected = true; st.last_packet = Some(Instant::now()); st.last_button = btn_name.trim().to_string(); st.last_button_at = Some(Instant::now()); if let Some(msg) = toast { st.set_toast(msg); } } } } impl Drop for G29BridgeReceiver { fn drop(&mut self) { self.stop_flag.store(true, Ordering::Release); if let Some(handle) = self.worker.take() { let _ = handle.join(); } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_parse_g29_status_and_toast() { let state = Arc::new(Mutex::new(G29State::default())); G29BridgeReceiver::process_line( "$G29,ARM=1,GEAR=2,THROT=64,BRAKE=12,FFB=140,VIB=50,FAIL=0", &state, None, None, ); { let st = state.lock(); assert!(st.connected); assert!(st.armed); assert_eq!(st.gear, 2); assert_eq!(st.gear_label(), "2"); assert_eq!(st.throttle_pct, 64); assert_eq!(st.brake_pct, 12); assert_eq!(st.ffb_raw, 140); assert_eq!(st.vib_pct, 50); assert!(!st.failsafe); } G29BridgeReceiver::process_line( "$G29,ARM=1,GEAR=-1,THROT=0,BRAKE=80,CLUTCH=45,STEER=-35,CH1=1280,CH2=890,CH3=1640,CH4=1360,FFB=200,VIB=50,FAIL=0,SRC=EXT", &state, None, None, ); { let st = state.lock(); assert_eq!(st.gear_label(), "R"); assert_eq!(st.brake_pct, 80); assert_eq!(st.clutch_pct, 45); assert_eq!(st.steering_pct, -35); assert_eq!(st.steer_crsf, 1280); assert_eq!(st.throttle_crsf, 890); assert_eq!(st.brake_crsf, 1640); assert_eq!(st.clutch_crsf, 1360); assert_eq!(st.remote_source, ControlSource::SteamController); assert_eq!(st.active_toast(), Some("FFB 78%")); } } #[test] fn test_parse_g29_button_event() { let state = Arc::new(Mutex::new(G29State::default())); G29BridgeReceiver::process_line("$G29_EVT,BTN=CROSS", &state, None, None); let st = state.lock(); assert_eq!(st.last_button, "CROSS"); assert_eq!(st.active_toast(), Some("TARE HT OK")); } #[test] fn test_parse_crsf_telemetry_hex() { // Trame CRSF Battery Sensor (0x08) : 16.8V (168 = 0x00A8), 12.5A (125 = 0x007D), 1200 mAh, 75% let mut frame = [0u8; 12]; frame[0] = 0xEA; frame[1] = 10; frame[2] = 0x08; frame[3] = 0x00; frame[4] = 0xA8; // 16.8V frame[5] = 0x00; frame[6] = 0x7D; // 12.5A frame[7] = 0x00; frame[8] = 0x04; frame[9] = 0xB0; // 1200 mAh frame[10] = 75; // 75% frame[11] = crate::nomad_elrs::NomadHeadTracker::crc8_dvb_s2(&frame[2..11]); let hex: String = frame.iter().map(|b| format!("{:02X}", b)).collect(); let line = format!("$CRSF,{}", hex); let g29_state = Arc::new(Mutex::new(G29State::default())); let telem_state = Arc::new(Mutex::new(TelemetryState::default())); G29BridgeReceiver::process_line(&line, &g29_state, None, Some(&telem_state)); let ts = telem_state.lock(); assert_eq!(ts.packets_received, 1); assert!((ts.battery_voltage_v - 16.8).abs() < 0.01); assert!((ts.battery_current_a - 12.5).abs() < 0.01); assert_eq!(ts.battery_remaining_pct, 75); } #[test] fn test_udp_peer_allowlist() { use std::net::{IpAddr, Ipv4Addr}; let allowed = vec![IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1))]; assert!(G29BridgeReceiver::is_peer_allowed( IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1)), &allowed )); assert!(G29BridgeReceiver::is_peer_allowed( IpAddr::V4(Ipv4Addr::LOCALHOST), &allowed )); assert!(!G29BridgeReceiver::is_peer_allowed( IpAddr::V4(Ipv4Addr::new(10, 0, 0, 99)), &allowed )); assert!(G29BridgeReceiver::is_peer_allowed( IpAddr::V4(Ipv4Addr::new(10, 0, 0, 99)), &[] )); } #[test] fn test_vr_menu_g29_navigation() { let engine = crate::engine::FpvEngineController::new(true, true); let ctrl = engine.control_handle(); let state = Arc::new(Mutex::new(G29State::default())); assert!(!ctrl.is_vr_menu_open()); G29BridgeReceiver::process_line("$G29_EVT,BTN=OPTIONS", &state, Some(&ctrl), None); assert!(ctrl.is_vr_menu_open()); // Descendre 2 fois (0 -> 2 : PROJECTION VR) puis flèche droite (DOME 140 -> CYL 140) for _ in 0..2 { G29BridgeReceiver::process_line("$G29_EVT,BTN=DPAD_DOWN", &state, Some(&ctrl), None); } G29BridgeReceiver::process_line("$G29_EVT,BTN=DPAD_RIGHT", &state, Some(&ctrl), None); let data = ctrl.vr_menu_render_data().unwrap(); assert_eq!(data.page, crate::telemetry_osd::VrMenuPage::Main); assert_eq!(data.selected_idx, 2); assert_eq!(data.projection_label, "CYL 140"); // Entrer dans le sous-menu Avancé (index 6) puis revenir au menu principal avec Circle for _ in 0..4 { G29BridgeReceiver::process_line("$G29_EVT,BTN=DPAD_DOWN", &state, Some(&ctrl), None); } G29BridgeReceiver::process_line("$G29_EVT,BTN=CROSS", &state, Some(&ctrl), None); assert_eq!( ctrl.vr_menu_render_data().unwrap().page, crate::telemetry_osd::VrMenuPage::Advanced ); G29BridgeReceiver::process_line("$G29_EVT,BTN=CIRCLE", &state, Some(&ctrl), None); assert!(ctrl.is_vr_menu_open()); assert_eq!( ctrl.vr_menu_render_data().unwrap().page, crate::telemetry_osd::VrMenuPage::Main ); // Double confirmation sur Quitter l'App (index 7) G29BridgeReceiver::process_line("$G29_EVT,BTN=DPAD_DOWN", &state, Some(&ctrl), None); G29BridgeReceiver::process_line("$G29_EVT,BTN=CROSS", &state, Some(&ctrl), None); assert!(!ctrl.is_exit_requested()); assert!(ctrl.vr_menu_render_data().unwrap().quit_confirm_pending); G29BridgeReceiver::process_line("$G29_EVT,BTN=CROSS", &state, Some(&ctrl), None); assert!(ctrl.is_exit_requested()); assert!(!ctrl.is_vr_menu_open()); } #[test] fn test_ping_radxa_relay_roundtrip() { let server = UdpSocket::bind("127.0.0.1:0").expect("bind loopback"); let port = server.local_addr().unwrap().port(); let handle = thread::spawn(move || { let mut buf = [0u8; 64]; let (len, src) = server.recv_from(&mut buf).unwrap(); let req = std::str::from_utf8(&buf[..len]).unwrap().trim(); let seq = req.strip_prefix("$PING,").unwrap(); let pong = format!("$PONG,{},1\n", seq); server.send_to(pong.as_bytes(), src).unwrap(); }); let (rtt_ms, uart_ok) = G29BridgeReceiver::ping_radxa_relay("127.0.0.1", port) .expect("ping should succeed"); handle.join().unwrap(); assert!(rtt_ms >= 0.0 && rtt_ms < 250.0); assert!(uart_ok); } }