From 16d05785fba85f6199e40e4b9445ab1e9883aacb Mon Sep 17 00:00:00 2001 From: bleack Date: Fri, 27 Nov 2026 00:03:24 +0100 Subject: [PATCH] feat(core,radxa): extract cross-platform fpv-core workspace crate and add usb0 DHCP setup for Android --- Cargo.lock | 11 + Cargo.toml | 5 + crates/fpv-core/Cargo.toml | 11 + crates/fpv-core/src/control_source.rs | 58 ++ crates/fpv-core/src/g29_bridge.rs | 760 ++++++++++++++++++ crates/fpv-core/src/lib.rs | 21 + crates/fpv-core/src/nomad_elrs.rs | 523 ++++++++++++ crates/fpv-core/src/telemetry/mod.rs | 5 + .../fpv-core/src/telemetry}/parser.rs | 0 .../fpv-core/src/telemetry}/state.rs | 0 crates/fpv-core/src/video_udp.rs | 591 ++++++++++++++ scripts/setup_radxa_dhcp_usb0.sh | 68 ++ scripts/setup_radxa_usb_gadget.sh | 36 + src/controller/types.rs | 57 +- src/g29_bridge.rs | 741 +---------------- src/nomad_elrs.rs | 523 +----------- src/telemetry_osd/mod.rs | 5 +- src/telemetry_osd/osd.rs | 2 +- 18 files changed, 2119 insertions(+), 1298 deletions(-) create mode 100644 crates/fpv-core/Cargo.toml create mode 100644 crates/fpv-core/src/control_source.rs create mode 100644 crates/fpv-core/src/g29_bridge.rs create mode 100644 crates/fpv-core/src/lib.rs create mode 100644 crates/fpv-core/src/nomad_elrs.rs create mode 100644 crates/fpv-core/src/telemetry/mod.rs rename {src/telemetry_osd => crates/fpv-core/src/telemetry}/parser.rs (100%) rename {src/telemetry_osd => crates/fpv-core/src/telemetry}/state.rs (100%) create mode 100644 crates/fpv-core/src/video_udp.rs create mode 100755 scripts/setup_radxa_dhcp_usb0.sh diff --git a/Cargo.lock b/Cargo.lock index 3742e3c..7c49cbd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1923,6 +1923,16 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "fpv-core" +version = "0.4.0" +dependencies = [ + "anyhow", + "glam", + "log", + "parking_lot", +] + [[package]] name = "freetype-sys" version = "0.20.1" @@ -5427,6 +5437,7 @@ dependencies = [ "ash", "chrono", "clap", + "fpv-core", "glam", "gpui", "gstreamer", diff --git a/Cargo.toml b/Cargo.toml index 343aa7d..e57e7bd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,3 +1,7 @@ +[workspace] +members = [".", "crates/fpv-core"] +resolver = "2" + [package] name = "steamframe-fpv" version = "0.4.0" @@ -9,6 +13,7 @@ anyhow = "1.0" ash = "0.38" chrono = "0.4" clap = { version = "4.5", features = ["derive"] } +fpv-core = { path = "crates/fpv-core" } glam = "0.29" gpui = "0.2.2" gstreamer = "0.23" diff --git a/crates/fpv-core/Cargo.toml b/crates/fpv-core/Cargo.toml new file mode 100644 index 0000000..e5a8f56 --- /dev/null +++ b/crates/fpv-core/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "fpv-core" +version = "0.4.0" +edition = "2021" +description = "Cœur Rust multiplateforme (Linux / SteamOS / Android) pour SteamFrame FPV : télémétrie CRSF/MAVLink, pont G29/Nomad, réception vidéo UDP RTP/Annex-B, Replay 30s et sous-titres SRT/GPX" + +[dependencies] +anyhow = "1.0" +glam = "0.29" +log = "0.4" +parking_lot = "0.12" diff --git a/crates/fpv-core/src/control_source.rs b/crates/fpv-core/src/control_source.rs new file mode 100644 index 0000000..a6a24f4 --- /dev/null +++ b/crates/fpv-core/src/control_source.rs @@ -0,0 +1,58 @@ +/// Source de conduite active sur la passerelle RP2350 (`G29` ou `EXT` pour manette externe / Steam Controller). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +#[repr(u8)] +pub enum ControlSource { + #[default] + G29 = 0, + SteamController = 1, +} + +impl ControlSource { + #[allow(clippy::should_implement_trait)] + pub fn from_str(s: &str) -> Self { + let lower = s.trim().to_ascii_lowercase(); + if lower == "steam" + || lower == "steam_controller" + || lower == "steam-controller" + || lower == "controller" + || lower == "gamepad" + || lower == "ext" + { + Self::SteamController + } else { + Self::G29 + } + } + + pub fn from_u8(v: u8) -> Self { + match v { + 1 => Self::SteamController, + _ => Self::G29, + } + } + + pub fn as_u8(self) -> u8 { + self as u8 + } + + pub fn as_str(self) -> &'static str { + match self { + Self::G29 => "g29", + Self::SteamController => "steam", + } + } + + pub fn wire_tag(self) -> &'static str { + match self { + Self::G29 => "G29", + Self::SteamController => "EXT", + } + } + + pub fn label(self) -> &'static str { + match self { + Self::G29 => "Volant G29", + Self::SteamController => "Steam Controller", + } + } +} diff --git a/crates/fpv-core/src/g29_bridge.rs b/crates/fpv-core/src/g29_bridge.rs new file mode 100644 index 0000000..9509aa5 --- /dev/null +++ b/crates/fpv-core/src/g29_bridge.rs @@ -0,0 +1,760 @@ +use crate::control_source::ControlSource; +use crate::nomad_elrs::{CRSF_CHANNEL_MAX, CRSF_CHANNEL_MID, CRSF_CHANNEL_MIN}; +use crate::telemetry::{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}; + +/// Interface générique pilotée par les événements boutons du volant G29 (`$G29_EVT`). +/// Implémentée par `EngineControlHandle` sur Steam Frame et par le pont FFI sur Android. +pub trait FpvControlTarget: Send + Sync + 'static { + fn is_vr_menu_open(&self) -> bool { + false + } + fn toggle_vr_menu(&self) -> bool { + false + } + fn close_vr_menu(&self) -> bool { + true + } + fn vr_menu_move(&self, _delta: i32) {} + fn vr_menu_adjust(&self, _delta: i32) {} + fn vr_menu_activate(&self) {} + fn request_recenter(&self) {} + fn toggle_dvr(&self) -> bool { + false + } + fn toggle_telemetry(&self) -> bool { + false + } + fn cycle_projection_mode(&self) -> &'static str { + "Écran Plat" + } + fn adjust_head_trim(&self, _pan_delta_deg: f32, _tilt_delta_deg: f32) {} +} + +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: impl FpvControlTarget, + 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<&dyn FpvControlTarget>, + 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<&dyn FpvControlTarget>, + ) { + 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_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!((0.0..250.0).contains(&rtt_ms)); + assert!(uart_ok); + } +} diff --git a/crates/fpv-core/src/lib.rs b/crates/fpv-core/src/lib.rs new file mode 100644 index 0000000..332704b --- /dev/null +++ b/crates/fpv-core/src/lib.rs @@ -0,0 +1,21 @@ +//! Cœur Rust multiplateforme (Linux / SteamOS / Android) de SteamFrame FPV. +//! +//! Ne dépend d'aucune bibliothèque graphique ou système Linux (`gpui`, `gstreamer`, +//! `openxr`, `ash`, `hidraw`) afin de se compiler directement en `aarch64-linux-android`. + +pub mod control_source; +pub mod g29_bridge; +pub mod nomad_elrs; +pub mod telemetry; +pub mod video_udp; + +pub use control_source::ControlSource; +pub use g29_bridge::{FpvControlTarget, G29BridgeReceiver, G29ButtonEvent, G29State}; +pub use nomad_elrs::{ + NomadHeadTracker, NomadProtocol, CRSF_CHANNEL_MAX, CRSF_CHANNEL_MID, CRSF_CHANNEL_MIN, + MSP_ELRS_BACKPACK_SET_PTR, +}; +pub use telemetry::{TelemetryReceiver, TelemetryState}; +pub use video_udp::{ + RtpDepacketizer, StreamTransport, UdpVideoMetrics, UdpVideoReceiver, VideoCodec, VideoNalUnit, +}; diff --git a/crates/fpv-core/src/nomad_elrs.rs b/crates/fpv-core/src/nomad_elrs.rs new file mode 100644 index 0000000..0676105 --- /dev/null +++ b/crates/fpv-core/src/nomad_elrs.rs @@ -0,0 +1,523 @@ +use anyhow::{anyhow, Result}; +use glam::{EulerRot, Quat}; +use std::net::{SocketAddr, ToSocketAddrs, UdpSocket}; +use std::time::{Duration, Instant}; + +/// Opcode MSPv2 officiel ExpressLRS Backpack pour le Head Tracking (Pan, Tilt, Roll) +pub const MSP_ELRS_BACKPACK_SET_PTR: u16 = 0x0383; + +/// Bornes CRSF standard (11 bits : 172 = 988µs, 992 = 1500µs, 1811 = 2012µs) +pub const CRSF_CHANNEL_MIN: u16 = 172; +pub const CRSF_CHANNEL_MID: u16 = 992; +pub const CRSF_CHANNEL_MAX: u16 = 1811; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum NomadProtocol { + /// MSPv2 ELRS_BACKPACK_SET_PTR (0x0383) — mode AP Head-Tracking classique + Msp, + /// CRSF RC_CHANNELS_PACKED (0x16) + Crsf, + /// MAVLink v1 RC_CHANNELS_OVERRIDE (msgid 70) — compatible UDP Backpack /mavlink (port 14555) + Mavlink, + /// Pont unifié G29 / Radxa Zero 3W ($HT,,,) — 100% filaire via usb0:14552 + G29Bridge, +} + +impl NomadProtocol { + #[allow(clippy::should_implement_trait)] + pub fn from_str(s: &str) -> Self { + if s.eq_ignore_ascii_case("g29") + || s.eq_ignore_ascii_case("g29_bridge") + || s.eq_ignore_ascii_case("radxa") + { + Self::G29Bridge + } else if s.eq_ignore_ascii_case("crsf") { + Self::Crsf + } else if s.eq_ignore_ascii_case("mavlink") || s.eq_ignore_ascii_case("mav") { + Self::Mavlink + } else { + Self::Msp + } + } + + pub fn label(self) -> &'static str { + match self { + Self::Msp => "MSPv2 0x0383", + Self::Crsf => "CRSF 0x16", + Self::Mavlink => "MAVLink v1 (RC Override)", + Self::G29Bridge => "G29 Hub ($HT)", + } + } +} + +#[derive(Debug, Clone, Copy)] +pub struct HeadPoseSample { + pub pan_deg: f32, + pub tilt_deg: f32, + pub roll_deg: f32, + pub pan_crsf: u16, + pub tilt_crsf: u16, + pub roll_crsf: u16, + pub packets_sent: u64, + pub send_errors: u64, + pub last_send_ok: bool, +} + +impl Default for HeadPoseSample { + fn default() -> Self { + Self { + pan_deg: 0.0, + tilt_deg: 0.0, + roll_deg: 0.0, + pan_crsf: CRSF_CHANNEL_MID, + tilt_crsf: CRSF_CHANNEL_MID, + roll_crsf: CRSF_CHANNEL_MID, + packets_sent: 0, + send_errors: 0, + last_send_ok: false, + } + } +} + +pub struct NomadHeadTracker { + socket: UdpSocket, + target: SocketAddr, + zero_quat_inv: Quat, + max_pan_deg: f32, + max_tilt_deg: f32, + max_roll_deg: f32, + protocol: NomadProtocol, + mav_seq: u8, + last_mav_heartbeat: Option, + packets_sent: u64, + send_errors: u64, + last_error_log: Option, +} + +impl NomadHeadTracker { + pub fn new( + nomad_ip: &str, + nomad_port: u16, + max_pan_deg: f32, + max_tilt_deg: f32, + max_roll_deg: f32, + protocol: NomadProtocol, + ) -> Result { + let trimmed_ip = nomad_ip.trim(); + let host_port = format!("{}:{}", trimmed_ip, nomad_port); + let target = if let Ok(ip) = trimmed_ip.parse::() { + SocketAddr::new(ip, nomad_port) + } else { + let addrs: Vec = host_port + .to_socket_addrs() + .map_err(|e| { + log::error!( + "[Wi-Fi Nomad] Impossible de résoudre la cible ({}) : {}", + host_port, + e + ); + e + })? + .collect(); + addrs + .iter() + .copied() + .find(|a| a.is_ipv4()) + .or_else(|| addrs.into_iter().next()) + .ok_or_else(|| anyhow!("Aucune adresse IP résolue pour {}", host_port))? + }; + + let bind_addr = if target.is_ipv6() { "[::]:0" } else { "0.0.0.0:0" }; + let socket = UdpSocket::bind(bind_addr).map_err(|e| { + log::error!( + "[Wi-Fi Nomad] Impossible de créer le socket UDP sortant : {}", + e + ); + e + })?; + socket.set_nonblocking(true)?; + + log::info!( + "[Wi-Fi Nomad] Émetteur prêt vers {} ({}) (Protocole: {})", + host_port, + target, + protocol.label() + ); + + Ok(Self { + socket, + target, + zero_quat_inv: Quat::IDENTITY, + max_pan_deg, + max_tilt_deg, + max_roll_deg, + protocol, + mav_seq: 0, + last_mav_heartbeat: None, + packets_sent: 0, + send_errors: 0, + last_error_log: None, + }) + } + + /// Réinitialise le centre du suivi de tête (Tare) sur la posture actuelle du casque + pub fn recenter(&mut self, current_orientation: Quat) { + let safe_q = if current_orientation.is_finite() + && current_orientation.length_squared() > 1e-8 + { + current_orientation.normalize() + } else { + Quat::IDENTITY + }; + self.zero_quat_inv = safe_q.inverse(); + log::info!("[Head-Tracker] Centre (Tare) réinitialisé sur la position actuelle du casque."); + } + + /// Calcule Pan/Tilt/Roll depuis le quaternion OpenXR et envoie la trame UDP au Nomad + pub fn send_pose(&mut self, current_orientation: Quat) -> Result { + let raw_rel = self.zero_quat_inv * current_orientation; + let relative = if raw_rel.is_finite() && raw_rel.length_squared() > 1e-8 { + raw_rel.normalize() + } else { + Quat::IDENTITY + }; + + let (yaw_rad, pitch_rad, roll_rad) = relative.to_euler(EulerRot::YXZ); + + let pan_deg = -yaw_rad.to_degrees(); + let tilt_deg = pitch_rad.to_degrees(); + let roll_deg = -roll_rad.to_degrees(); + + self.send_manual_angles(pan_deg, tilt_deg, roll_deg) + } + + /// Encode et envoie directement des angles Pan/Tilt/Roll (en degrés) vers la cible UDP + pub fn send_manual_angles( + &mut self, + pan_deg: f32, + tilt_deg: f32, + roll_deg: f32, + ) -> Result { + let pan_crsf = Self::deg_to_crsf(pan_deg, self.max_pan_deg); + let tilt_crsf = Self::deg_to_crsf(tilt_deg, self.max_tilt_deg); + let roll_crsf = Self::deg_to_crsf(roll_deg, self.max_roll_deg); + + let send_res = match self.protocol { + NomadProtocol::Crsf => { + let packet = Self::encode_crsf_rc_channels(pan_crsf, tilt_crsf, roll_crsf); + self.socket.send_to(&packet, self.target) + } + NomadProtocol::Msp => { + let packet = Self::encode_mspv2_ptr(pan_crsf, tilt_crsf, roll_crsf); + self.socket.send_to(&packet, self.target) + } + NomadProtocol::Mavlink => { + if self + .last_mav_heartbeat + .is_none_or(|t| t.elapsed() >= Duration::from_secs(1)) + { + let hb = Self::encode_mavlink_heartbeat(self.mav_seq); + self.mav_seq = self.mav_seq.wrapping_add(1); + let _ = self.socket.send_to(&hb, self.target); + self.last_mav_heartbeat = Some(Instant::now()); + } + let packet = Self::encode_mavlink_rc_override( + pan_crsf, + tilt_crsf, + roll_crsf, + self.mav_seq, + ); + self.mav_seq = self.mav_seq.wrapping_add(1); + self.socket.send_to(&packet, self.target) + } + NomadProtocol::G29Bridge => { + let msg = Self::encode_g29_ht(pan_crsf, tilt_crsf, roll_crsf); + self.socket.send_to(msg.as_bytes(), self.target) + } + }; + + let last_send_ok = match send_res { + Ok(_) => { + self.packets_sent = self.packets_sent.wrapping_add(1); + true + } + Err(e) => { + self.send_errors = self.send_errors.wrapping_add(1); + let should_log = self + .last_error_log + .map(|t| t.elapsed() >= Duration::from_secs(3)) + .unwrap_or(true); + if should_log { + log::error!( + "[Wi-Fi Nomad] Échec d'envoi UDP vers {} : {} (Vérifiez la connexion Wi-Fi au Backpack du RadioMaster Nomad)", + self.target, + e + ); + self.last_error_log = Some(Instant::now()); + } + false + } + }; + + Ok(HeadPoseSample { + pan_deg, + tilt_deg, + roll_deg, + pan_crsf, + tilt_crsf, + roll_crsf, + packets_sent: self.packets_sent, + send_errors: self.send_errors, + last_send_ok, + }) + } + + #[inline] + pub fn deg_to_crsf(angle_deg: f32, max_deg: f32) -> u16 { + if !angle_deg.is_finite() || !max_deg.is_finite() || max_deg <= 0.0 { + return CRSF_CHANNEL_MID; + } + let norm = (angle_deg / max_deg).clamp(-1.0, 1.0); + let crsf_val = if norm >= 0.0 { + CRSF_CHANNEL_MID as f32 + norm * (CRSF_CHANNEL_MAX - CRSF_CHANNEL_MID) as f32 + } else { + CRSF_CHANNEL_MID as f32 + norm * (CRSF_CHANNEL_MID - CRSF_CHANNEL_MIN) as f32 + }; + (crsf_val.round() as u16).clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX) + } + + /// Ajoute un suffixe CRC-8 DVB-S2 (`*XX\n`) à une trame texte `$...` pour validation UART RP2350. + pub fn append_nmea_crc8(payload: &str) -> String { + let crc = Self::crc8_dvb_s2(payload.as_bytes()); + format!("{}*{:02X}\n", payload, crc) + } + + pub fn encode_g29_ht(pan: u16, tilt: u16, roll: u16) -> String { + Self::append_nmea_crc8(&format!("$HT,{},{},{}", pan, tilt, roll)) + } + + pub fn encode_mspv2_ptr(pan: u16, tilt: u16, roll: u16) -> [u8; 15] { + let mut buf = [0u8; 15]; + buf[0] = b'$'; + buf[1] = b'X'; + buf[2] = b'<'; + buf[3] = 0x00; + buf[4..6].copy_from_slice(&MSP_ELRS_BACKPACK_SET_PTR.to_le_bytes()); + buf[6..8].copy_from_slice(&6u16.to_le_bytes()); + buf[8..10].copy_from_slice(&pan.to_le_bytes()); + buf[10..12].copy_from_slice(&tilt.to_le_bytes()); + buf[12..14].copy_from_slice(&roll.to_le_bytes()); + buf[14] = Self::crc8_dvb_s2(&buf[3..14]); + buf + } + + pub fn encode_crsf_rc_channels(pan: u16, tilt: u16, roll: u16) -> [u8; 26] { + let mut ch = [CRSF_CHANNEL_MID; 16]; + ch[0] = pan.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX); + ch[1] = tilt.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX); + ch[2] = roll.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX); + + let mut frame = [0u8; 26]; + frame[0] = 0xEE; + frame[1] = 24; + frame[2] = 0x16; + + let mut bit_buf: u32 = 0; + let mut bits_in_buf: u8 = 0; + let mut byte_idx = 3; + + for &val in &ch { + bit_buf |= ((val & 0x07FF) as u32) << bits_in_buf; + bits_in_buf += 11; + while bits_in_buf >= 8 { + frame[byte_idx] = (bit_buf & 0xFF) as u8; + byte_idx += 1; + bit_buf >>= 8; + bits_in_buf -= 8; + } + } + + frame[25] = Self::crc8_dvb_s2(&frame[2..25]); + frame + } + + /// Convertit une valeur CRSF (172..1811, neutre 992) en microsecondes PWM (988..2012, neutre 1500) + #[inline] + pub fn crsf_to_pwm_us(crsf: u16) -> u16 { + let clamped = crsf.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX) as f32; + if clamped >= CRSF_CHANNEL_MID as f32 { + let norm = (clamped - CRSF_CHANNEL_MID as f32) / (CRSF_CHANNEL_MAX - CRSF_CHANNEL_MID) as f32; + (1500.0 + norm * 512.0).round() as u16 + } else { + let norm = (clamped - CRSF_CHANNEL_MID as f32) / (CRSF_CHANNEL_MID - CRSF_CHANNEL_MIN) as f32; + (1500.0 + norm * 512.0).round() as u16 + } + } + + /// Encode une trame MAVLink v1 HEARTBEAT (msgid=0, crc_extra=50) pour s'identifier auprès du Backpack + pub fn encode_mavlink_heartbeat(seq: u8) -> [u8; 17] { + let mut payload = [0u8; 9]; + payload[4] = 6; // MAV_TYPE_GCS + payload[5] = 8; // MAV_AUTOPILOT_INVALID + payload[8] = 3; // mavlink_version + Self::encode_mavlink_v1_frame::<9, 17>(0, seq, 50, &payload) + } + + /// Encode une trame MAVLink v1 RC_CHANNELS_OVERRIDE (msgid=70, crc_extra=124) sur les canaux 1..3 + pub fn encode_mavlink_rc_override(pan: u16, tilt: u16, roll: u16, seq: u8) -> [u8; 26] { + let mut payload = [0u8; 18]; + let ch1 = Self::crsf_to_pwm_us(pan); + let ch2 = Self::crsf_to_pwm_us(tilt); + let ch3 = Self::crsf_to_pwm_us(roll); + let ignore = u16::MAX; + payload[0..2].copy_from_slice(&ch1.to_le_bytes()); + payload[2..4].copy_from_slice(&ch2.to_le_bytes()); + payload[4..6].copy_from_slice(&ch3.to_le_bytes()); + payload[6..8].copy_from_slice(&ignore.to_le_bytes()); + payload[8..10].copy_from_slice(&ignore.to_le_bytes()); + payload[10..12].copy_from_slice(&ignore.to_le_bytes()); + payload[12..14].copy_from_slice(&ignore.to_le_bytes()); + payload[14..16].copy_from_slice(&ignore.to_le_bytes()); + payload[16] = 1; // target_system + payload[17] = 1; // target_component + Self::encode_mavlink_v1_frame::<18, 26>(70, seq, 124, &payload) + } + + fn encode_mavlink_v1_frame( + msgid: u8, + seq: u8, + crc_extra: u8, + payload: &[u8; P], + ) -> [u8; T] { + debug_assert_eq!(T, P + 8); + let mut buf = [0u8; T]; + buf[0] = 0xFE; + buf[1] = P as u8; + buf[2] = seq; + buf[3] = 255; // GCS system_id + buf[4] = 190; // MAV_COMP_ID_MISSIONPLANNER / GCS + buf[5] = msgid; + buf[6..6 + P].copy_from_slice(payload); + let crc = Self::mavlink_crc16(&buf[1..6 + P], crc_extra); + buf[6 + P..8 + P].copy_from_slice(&crc.to_le_bytes()); + buf + } + + #[inline] + pub fn mavlink_crc16(data: &[u8], crc_extra: u8) -> u16 { + let mut crc: u16 = 0xFFFF; + for &b in data.iter().chain(std::iter::once(&crc_extra)) { + let mut tmp = b ^ (crc & 0xFF) as u8; + tmp ^= tmp << 4; + crc = (crc >> 8) + ^ ((tmp as u16) << 8) + ^ ((tmp as u16) << 3) + ^ ((tmp as u16) >> 4); + } + crc + } + + #[inline] + pub fn crc8_dvb_s2(data: &[u8]) -> u8 { + const TABLE: [u8; 256] = { + let mut table = [0u8; 256]; + let mut i = 0; + while i < 256 { + let mut curr = i as u8; + let mut j = 0; + while j < 8 { + if (curr & 0x80) != 0 { + curr = (curr << 1) ^ 0xD5; + } else { + curr <<= 1; + } + j += 1; + } + table[i] = curr; + i += 1; + } + table + }; + + let mut crc: u8 = 0; + for &byte in data { + crc = TABLE[(crc ^ byte) as usize]; + } + crc + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_deg_to_crsf_bounds() { + assert_eq!(NomadHeadTracker::deg_to_crsf(0.0, 90.0), CRSF_CHANNEL_MID); + assert_eq!(NomadHeadTracker::deg_to_crsf(90.0, 90.0), CRSF_CHANNEL_MAX); + assert_eq!(NomadHeadTracker::deg_to_crsf(-90.0, 90.0), CRSF_CHANNEL_MIN); + assert_eq!(NomadHeadTracker::deg_to_crsf(f32::NAN, 90.0), CRSF_CHANNEL_MID); + assert_eq!(NomadHeadTracker::deg_to_crsf(45.0, f32::NAN), CRSF_CHANNEL_MID); + assert_eq!(NomadHeadTracker::deg_to_crsf(45.0, 0.0), CRSF_CHANNEL_MID); + assert_eq!(NomadHeadTracker::deg_to_crsf(45.0, -10.0), CRSF_CHANNEL_MID); + } + + #[test] + fn test_mspv2_ptr_packet_header() { + let pkt = NomadHeadTracker::encode_mspv2_ptr(992, 992, 992); + assert_eq!(&pkt[0..3], b"$X<"); + assert_eq!(u16::from_le_bytes([pkt[4], pkt[5]]), MSP_ELRS_BACKPACK_SET_PTR); + assert_eq!(u16::from_le_bytes([pkt[6], pkt[7]]), 6); + assert_eq!(pkt[14], NomadHeadTracker::crc8_dvb_s2(&pkt[3..14])); + } + + #[test] + fn test_crsf_rc_channels_packet() { + let pkt = NomadHeadTracker::encode_crsf_rc_channels(992, 992, 992); + assert_eq!(pkt[0], 0xEE); // Sync CRSF + assert_eq!(pkt[1], 24); // Payload len + assert_eq!(pkt[2], 0x16); // Type RC_CHANNELS_PACKED + assert_eq!(pkt[25], NomadHeadTracker::crc8_dvb_s2(&pkt[2..25])); + } + + #[test] + fn test_mavlink_rc_override_packet() { + assert_eq!(NomadHeadTracker::crsf_to_pwm_us(992), 1500); + let pkt = NomadHeadTracker::encode_mavlink_rc_override(992, 992, 992, 7); + assert_eq!(pkt[0], 0xFE); + assert_eq!(pkt[1], 18); + assert_eq!(pkt[2], 7); + assert_eq!(pkt[5], 70); + assert_eq!(u16::from_le_bytes([pkt[6], pkt[7]]), 1500); + assert_eq!(u16::from_le_bytes([pkt[8], pkt[9]]), 1500); + assert_eq!(u16::from_le_bytes([pkt[10], pkt[11]]), 1500); + let expected_crc = NomadHeadTracker::mavlink_crc16(&pkt[1..24], 124); + assert_eq!(u16::from_le_bytes([pkt[24], pkt[25]]), expected_crc); + } + + #[test] + fn test_mavlink_heartbeat_packet() { + let pkt = NomadHeadTracker::encode_mavlink_heartbeat(1); + assert_eq!(pkt[0], 0xFE); + assert_eq!(pkt[1], 9); + assert_eq!(pkt[5], 0); + let expected_crc = NomadHeadTracker::mavlink_crc16(&pkt[1..15], 50); + assert_eq!(u16::from_le_bytes([pkt[15], pkt[16]]), expected_crc); + } + + #[test] + fn test_hostname_resolution_default_ip() { + let ht = NomadHeadTracker::new("10.0.0.1", 14550, 90.0, 60.0, 45.0, NomadProtocol::Msp); + assert!(ht.is_ok()); + } + + #[test] + fn test_g29_bridge_ht_format() { + assert_eq!(NomadProtocol::from_str("g29"), NomadProtocol::G29Bridge); + let frame = NomadHeadTracker::encode_g29_ht(992, 1200, 800); + let (body, hex_crc) = frame.trim_end_matches('\n').split_once('*').unwrap(); + assert_eq!(body, "$HT,992,1200,800"); + let expected = format!("{:02X}", NomadHeadTracker::crc8_dvb_s2(body.as_bytes())); + assert_eq!(hex_crc, expected); + } +} diff --git a/crates/fpv-core/src/telemetry/mod.rs b/crates/fpv-core/src/telemetry/mod.rs new file mode 100644 index 0000000..62bc262 --- /dev/null +++ b/crates/fpv-core/src/telemetry/mod.rs @@ -0,0 +1,5 @@ +pub mod parser; +pub mod state; + +pub use parser::TelemetryReceiver; +pub use state::TelemetryState; diff --git a/src/telemetry_osd/parser.rs b/crates/fpv-core/src/telemetry/parser.rs similarity index 100% rename from src/telemetry_osd/parser.rs rename to crates/fpv-core/src/telemetry/parser.rs diff --git a/src/telemetry_osd/state.rs b/crates/fpv-core/src/telemetry/state.rs similarity index 100% rename from src/telemetry_osd/state.rs rename to crates/fpv-core/src/telemetry/state.rs diff --git a/crates/fpv-core/src/video_udp.rs b/crates/fpv-core/src/video_udp.rs new file mode 100644 index 0000000..fad4a93 --- /dev/null +++ b/crates/fpv-core/src/video_udp.rs @@ -0,0 +1,591 @@ +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 ANNEX_B_START_CODE: [u8; 4] = [0x00, 0x00, 0x00, 0x01]; +const SIGNAL_LOST_AFTER: Duration = Duration::from_secs(1); + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum VideoCodec { + H264, + H265, +} + +impl VideoCodec { + #[allow(clippy::should_implement_trait)] + pub fn from_str(s: &str) -> Self { + if s.eq_ignore_ascii_case("h265") || s.eq_ignore_ascii_case("hevc") { + Self::H265 + } else { + Self::H264 + } + } + + pub fn mime_type(self) -> &'static str { + match self { + Self::H264 => "video/avc", + Self::H265 => "video/hevc", + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum StreamTransport { + Rtp, + Raw, +} + +impl StreamTransport { + #[allow(clippy::should_implement_trait)] + pub fn from_str(s: &str) -> Self { + if s.eq_ignore_ascii_case("raw") || s.eq_ignore_ascii_case("annexb") { + Self::Raw + } else { + Self::Rtp + } + } +} + +/// Unité NAL ou Access Unit prête pour `MediaCodec` / `MediaMuxer` (format Annex-B `00 00 00 01 ...`). +#[derive(Debug, Clone)] +pub struct VideoNalUnit { + pub data: Vec, + pub pts_us: u64, + pub is_keyframe: bool, + pub is_codec_config: bool, +} + +/// Métriques temps réel de la liaison vidéo UDP. +#[derive(Debug, Clone, Default)] +pub struct UdpVideoMetrics { + pub fps: f32, + pub jitter_ms: f32, + pub bitrate_kbps: f32, + pub received_packets: u64, + pub dropped_packets: u64, + pub signal_live: bool, +} + +/// Détecte si un NAL (sans start code) est une image clé (IDR / IRAP) ou une config codec (VPS / SPS / PPS). +pub fn classify_nal(codec: VideoCodec, nal_header_byte: u8) -> (bool, bool) { + match codec { + VideoCodec::H264 => { + let nal_type = nal_header_byte & 0x1F; + let is_keyframe = nal_type == 5; + let is_config = matches!(nal_type, 7 | 8); + (is_keyframe, is_config) + } + VideoCodec::H265 => { + let nal_type = (nal_header_byte >> 1) & 0x3F; + let is_keyframe = matches!(nal_type, 19..=21); + let is_config = matches!(nal_type, 32..=34); + (is_keyframe, is_config) + } + } +} + +/// Dépaqueteur RTP pur Rust (RFC 6184 H.264 / RFC 7798 H.265) sans dépendance GStreamer. +pub struct RtpDepacketizer { + codec: VideoCodec, + last_seq: Option, + fu_buf: Vec, + fu_active: bool, + fu_keyframe: bool, + fu_config: bool, + pub dropped_packets: u64, +} + +impl RtpDepacketizer { + pub fn new(codec: VideoCodec) -> Self { + Self { + codec, + last_seq: None, + fu_buf: Vec::with_capacity(64 * 1024), + fu_active: false, + fu_keyframe: false, + fu_config: false, + dropped_packets: 0, + } + } + + /// Traite un paquet UDP RTP brut et appelle `emit` pour chaque unité NAL complète (Annex-B). + pub fn push_rtp_packet(&mut self, packet: &[u8], pts_us: u64, mut emit: F) + where + F: FnMut(VideoNalUnit), + { + // En-tête RTP minimal : 12 octets + if packet.len() < 12 { + return; + } + let v = packet[0] >> 6; + if v != 2 { + return; + } + let has_padding = (packet[0] & 0x20) != 0; + let has_extension = (packet[0] & 0x10) != 0; + let csrc_count = (packet[0] & 0x0F) as usize; + let seq = u16::from_be_bytes([packet[2], packet[3]]); + + if let Some(prev) = self.last_seq { + let expected = prev.wrapping_add(1); + if seq != expected { + let gap = seq.wrapping_sub(expected) as u64; + if gap < 1000 { + self.dropped_packets = self.dropped_packets.saturating_add(gap); + } + // Fragmentation en cours invalidée par une perte de paquet + self.fu_active = false; + self.fu_buf.clear(); + } + } + self.last_seq = Some(seq); + + let mut offset = 12 + csrc_count * 4; + if offset > packet.len() { + return; + } + if has_extension { + if offset + 4 > packet.len() { + return; + } + let ext_words = u16::from_be_bytes([packet[offset + 2], packet[offset + 3]]) as usize; + offset += 4 + ext_words * 4; + if offset > packet.len() { + return; + } + } + let end = if has_padding { + let pad = packet[packet.len() - 1] as usize; + if pad == 0 || offset + pad > packet.len() { + return; + } + packet.len() - pad + } else { + packet.len() + }; + let payload = &packet[offset..end]; + if payload.is_empty() { + return; + } + + match self.codec { + VideoCodec::H264 => self.handle_h264_payload(payload, pts_us, &mut emit), + VideoCodec::H265 => self.handle_h265_payload(payload, pts_us, &mut emit), + } + } + + fn handle_h264_payload(&mut self, payload: &[u8], pts_us: u64, emit: &mut F) + where + F: FnMut(VideoNalUnit), + { + let nal_type = payload[0] & 0x1F; + match nal_type { + 1..=23 => { + self.fu_active = false; + self.fu_buf.clear(); + let (is_keyframe, is_codec_config) = classify_nal(VideoCodec::H264, payload[0]); + let mut data = Vec::with_capacity(4 + payload.len()); + data.extend_from_slice(&ANNEX_B_START_CODE); + data.extend_from_slice(payload); + emit(VideoNalUnit { + data, + pts_us, + is_keyframe, + is_codec_config, + }); + } + 24 => { + // STAP-A : plusieurs NAL préfixés par leur longueur sur 16 bits + self.fu_active = false; + self.fu_buf.clear(); + let mut idx = 1usize; + while idx + 2 <= payload.len() { + let nalu_len = u16::from_be_bytes([payload[idx], payload[idx + 1]]) as usize; + idx += 2; + if nalu_len == 0 || idx + nalu_len > payload.len() { + break; + } + let nalu = &payload[idx..idx + nalu_len]; + let (is_keyframe, is_codec_config) = classify_nal(VideoCodec::H264, nalu[0]); + let mut data = Vec::with_capacity(4 + nalu.len()); + data.extend_from_slice(&ANNEX_B_START_CODE); + data.extend_from_slice(nalu); + emit(VideoNalUnit { + data, + pts_us, + is_keyframe, + is_codec_config, + }); + idx += nalu_len; + } + } + 28 => { + // FU-A : NAL fragmenté sur plusieurs paquets RTP + if payload.len() < 2 { + return; + } + let fu_indicator = payload[0]; + let fu_header = payload[1]; + let start_bit = (fu_header & 0x80) != 0; + let end_bit = (fu_header & 0x40) != 0; + let orig_nal_hdr = (fu_indicator & 0xE0) | (fu_header & 0x1F); + + if start_bit { + self.fu_buf.clear(); + self.fu_buf.extend_from_slice(&ANNEX_B_START_CODE); + self.fu_buf.push(orig_nal_hdr); + self.fu_buf.extend_from_slice(&payload[2..]); + let (is_key, is_cfg) = classify_nal(VideoCodec::H264, orig_nal_hdr); + self.fu_keyframe = is_key; + self.fu_config = is_cfg; + self.fu_active = true; + } else if self.fu_active { + self.fu_buf.extend_from_slice(&payload[2..]); + } + + if end_bit && self.fu_active { + self.fu_active = false; + let data = std::mem::take(&mut self.fu_buf); + emit(VideoNalUnit { + data, + pts_us, + is_keyframe: self.fu_keyframe, + is_codec_config: self.fu_config, + }); + } + } + _ => {} + } + } + + fn handle_h265_payload(&mut self, payload: &[u8], pts_us: u64, emit: &mut F) + where + F: FnMut(VideoNalUnit), + { + if payload.len() < 2 { + return; + } + let nal_type = (payload[0] >> 1) & 0x3F; + match nal_type { + 0..=47 => { + self.fu_active = false; + self.fu_buf.clear(); + let (is_keyframe, is_codec_config) = classify_nal(VideoCodec::H265, payload[0]); + let mut data = Vec::with_capacity(4 + payload.len()); + data.extend_from_slice(&ANNEX_B_START_CODE); + data.extend_from_slice(payload); + emit(VideoNalUnit { + data, + pts_us, + is_keyframe, + is_codec_config, + }); + } + 48 => { + // AP (Aggregation Packet) + self.fu_active = false; + self.fu_buf.clear(); + let mut idx = 2usize; + while idx + 2 <= payload.len() { + let nalu_len = u16::from_be_bytes([payload[idx], payload[idx + 1]]) as usize; + idx += 2; + if nalu_len == 0 || idx + nalu_len > payload.len() { + break; + } + let nalu = &payload[idx..idx + nalu_len]; + let (is_keyframe, is_codec_config) = classify_nal(VideoCodec::H265, nalu[0]); + let mut data = Vec::with_capacity(4 + nalu.len()); + data.extend_from_slice(&ANNEX_B_START_CODE); + data.extend_from_slice(nalu); + emit(VideoNalUnit { + data, + pts_us, + is_keyframe, + is_codec_config, + }); + idx += nalu_len; + } + } + 49 => { + // FU (Fragmentation Unit) + if payload.len() < 3 { + return; + } + let fu_header = payload[2]; + let start_bit = (fu_header & 0x80) != 0; + let end_bit = (fu_header & 0x40) != 0; + let orig_type = fu_header & 0x3F; + let orig_hdr0 = (payload[0] & 0x81) | (orig_type << 1); + let orig_hdr1 = payload[1]; + + if start_bit { + self.fu_buf.clear(); + self.fu_buf.extend_from_slice(&ANNEX_B_START_CODE); + self.fu_buf.push(orig_hdr0); + self.fu_buf.push(orig_hdr1); + self.fu_buf.extend_from_slice(&payload[3..]); + let (is_key, is_cfg) = classify_nal(VideoCodec::H265, orig_hdr0); + self.fu_keyframe = is_key; + self.fu_config = is_cfg; + self.fu_active = true; + } else if self.fu_active { + self.fu_buf.extend_from_slice(&payload[3..]); + } + + if end_bit && self.fu_active { + self.fu_active = false; + let data = std::mem::take(&mut self.fu_buf); + emit(VideoNalUnit { + data, + pts_us, + is_keyframe: self.fu_keyframe, + is_codec_config: self.fu_config, + }); + } + } + _ => {} + } + } +} + +/// Récepteur vidéo UDP pur Rust (port `5600` par défaut) destiné au décodeur matériel Android (`MediaCodec`). +pub struct UdpVideoReceiver { + metrics: Arc>, + stop_flag: Arc, + worker: Option>, +} + +impl UdpVideoReceiver { + pub fn start( + bind_ip: &str, + port: u16, + codec: VideoCodec, + transport: StreamTransport, + mut on_nal: F, + ) -> Result + where + F: FnMut(VideoNalUnit) + Send + 'static, + { + let addr = format!("{}:{}", bind_ip, port); + let socket = UdpSocket::bind(&addr)?; + socket.set_read_timeout(Some(Duration::from_millis(100)))?; + log::info!( + "[UDP Video] En écoute sur {} ({:?}, {:?})", + addr, + codec, + transport + ); + + let metrics = Arc::new(Mutex::new(UdpVideoMetrics::default())); + let metrics_clone = Arc::clone(&metrics); + let stop_flag = Arc::new(AtomicBool::new(false)); + let stop_clone = Arc::clone(&stop_flag); + + let worker = thread::Builder::new() + .name("fpv-udp-video".into()) + .spawn(move || { + let mut buf = [0u8; 65536]; + let mut depacketizer = RtpDepacketizer::new(codec); + let start_time = Instant::now(); + let mut last_packet_at: Option = None; + let mut last_frame_at: Option = None; + let mut fps_window_start = Instant::now(); + let mut fps_frames: u32 = 0; + let mut bytes_in_window: u64 = 0; + let mut jitter_ms_ewma: f32 = 0.0; + let mut expected_interval_ms: f32 = 16.67; + + while !stop_clone.load(Ordering::Acquire) { + match socket.recv(&mut buf) { + Ok(len) if len > 0 => { + let now = Instant::now(); + last_packet_at = Some(now); + bytes_in_window = bytes_in_window.saturating_add(len as u64); + let pts_us = start_time.elapsed().as_micros() as u64; + + let mut emit_and_track = |nal: VideoNalUnit| { + if !nal.is_codec_config { + fps_frames = fps_frames.saturating_add(1); + if let Some(prev_f) = last_frame_at { + let dt_ms = now.duration_since(prev_f).as_secs_f32() * 1000.0; + if dt_ms > 1.0 && dt_ms < 250.0 { + expected_interval_ms = + expected_interval_ms * 0.9 + dt_ms * 0.1; + let diff = (dt_ms - expected_interval_ms).abs(); + jitter_ms_ewma = jitter_ms_ewma * 0.85 + diff * 0.15; + } + } + last_frame_at = Some(now); + } + on_nal(nal); + }; + + match transport { + StreamTransport::Rtp => { + depacketizer.push_rtp_packet( + &buf[..len], + pts_us, + &mut emit_and_track, + ); + } + StreamTransport::Raw => { + let is_key = has_keyframe_annex_b(codec, &buf[..len]); + emit_and_track(VideoNalUnit { + data: buf[..len].to_vec(), + pts_us, + is_keyframe: is_key, + is_codec_config: false, + }); + } + } + + let mut m = metrics_clone.lock(); + m.received_packets = m.received_packets.saturating_add(1); + m.dropped_packets = depacketizer.dropped_packets; + m.signal_live = true; + } + _ => {} + } + + let win_elapsed = fps_window_start.elapsed(); + if win_elapsed >= Duration::from_millis(500) { + let secs = win_elapsed.as_secs_f32().max(0.001); + let live = last_packet_at + .map(|t| t.elapsed() < SIGNAL_LOST_AFTER) + .unwrap_or(false); + let mut m = metrics_clone.lock(); + m.fps = if live { fps_frames as f32 / secs } else { 0.0 }; + m.bitrate_kbps = if live { + (bytes_in_window as f32 * 8.0) / (secs * 1000.0) + } else { + 0.0 + }; + m.jitter_ms = if live { jitter_ms_ewma } else { 0.0 }; + m.signal_live = live; + fps_frames = 0; + bytes_in_window = 0; + fps_window_start = Instant::now(); + } + } + })?; + + Ok(Self { + metrics, + stop_flag, + worker: Some(worker), + }) + } + + pub fn metrics(&self) -> Arc> { + Arc::clone(&self.metrics) + } +} + +impl Drop for UdpVideoReceiver { + fn drop(&mut self) { + self.stop_flag.store(true, Ordering::Release); + if let Some(handle) = self.worker.take() { + let _ = handle.join(); + } + } +} + +fn has_keyframe_annex_b(codec: VideoCodec, bytes: &[u8]) -> bool { + let mut i = 0usize; + while i + 4 < bytes.len() { + let sc = if bytes[i] == 0 && bytes[i + 1] == 0 && bytes[i + 2] == 1 { + 3 + } else if bytes[i] == 0 && bytes[i + 1] == 0 && bytes[i + 2] == 0 && bytes[i + 3] == 1 { + 4 + } else { + i += 1; + continue; + }; + let nal_idx = i + sc; + if nal_idx < bytes.len() { + let (is_key, _) = classify_nal(codec, bytes[nal_idx]); + if is_key { + return true; + } + } + i = nal_idx + 1; + } + false +} + +#[cfg(test)] +mod tests { + use super::*; + + fn make_rtp(seq: u16, payload: &[u8]) -> Vec { + let mut pkt = vec![ + 0x80, 0x60, // V=2, PT=96 + (seq >> 8) as u8, + (seq & 0xFF) as u8, + 0, 0, 0, 1, // Timestamp + 0x12, 0x34, 0x56, 0x78, // SSRC + ]; + pkt.extend_from_slice(payload); + pkt + } + + #[test] + fn test_h264_single_nal_and_sps() { + let mut dep = RtpDepacketizer::new(VideoCodec::H264); + let mut out = Vec::new(); + // SPS (NAL type 7) + let pkt = make_rtp(1, &[0x67, 0x42, 0x00, 0x1E]); + dep.push_rtp_packet(&pkt, 1000, |n| out.push(n)); + assert_eq!(out.len(), 1); + assert!(out[0].is_codec_config); + assert!(!out[0].is_keyframe); + assert_eq!(&out[0].data[..4], &ANNEX_B_START_CODE); + assert_eq!(&out[0].data[4..], &[0x67, 0x42, 0x00, 0x1E]); + } + + #[test] + fn test_h264_fua_reassembly_idr() { + let mut dep = RtpDepacketizer::new(VideoCodec::H264); + let mut out = Vec::new(); + // FU-A start (IDR type 5, NRI=3 -> orig_hdr = 0x65) + let p1 = make_rtp(10, &[0x7C, 0x85, 0xAA, 0xBB]); + let p2 = make_rtp(11, &[0x7C, 0x45, 0xCC, 0xDD]); + dep.push_rtp_packet(&p1, 2000, |n| out.push(n)); + assert!(out.is_empty()); + dep.push_rtp_packet(&p2, 2000, |n| out.push(n)); + assert_eq!(out.len(), 1); + assert!(out[0].is_keyframe); + assert_eq!(out[0].data, vec![0, 0, 0, 1, 0x65, 0xAA, 0xBB, 0xCC, 0xDD]); + } + + #[test] + fn test_h264_fua_drop_on_seq_gap() { + let mut dep = RtpDepacketizer::new(VideoCodec::H264); + let mut out = Vec::new(); + let p1 = make_rtp(10, &[0x7C, 0x85, 0xAA]); + // Seq 11 manquant -> Seq 12 ne doit pas émettre un NAL corrompu + let p3 = make_rtp(12, &[0x7C, 0x45, 0xCC]); + dep.push_rtp_packet(&p1, 2000, |n| out.push(n)); + dep.push_rtp_packet(&p3, 2000, |n| out.push(n)); + assert!(out.is_empty()); + assert_eq!(dep.dropped_packets, 1); + } + + #[test] + fn test_h265_fu_reassembly_idr() { + let mut dep = RtpDepacketizer::new(VideoCodec::H265); + let mut out = Vec::new(); + // FU header (type 49 -> 49<<1 = 0x62), orig_type = 19 (IDR_W_RADL -> 19<<1 = 0x26) + let p1 = make_rtp(1, &[0x62, 0x01, 0x80 | 19, 0x11, 0x22]); + let p2 = make_rtp(2, &[0x62, 0x01, 0x40 | 19, 0x33, 0x44]); + dep.push_rtp_packet(&p1, 3000, |n| out.push(n)); + dep.push_rtp_packet(&p2, 3000, |n| out.push(n)); + assert_eq!(out.len(), 1); + assert!(out[0].is_keyframe); + assert_eq!(out[0].data, vec![0, 0, 0, 1, 0x26, 0x01, 0x11, 0x22, 0x33, 0x44]); + } +} diff --git a/scripts/setup_radxa_dhcp_usb0.sh b/scripts/setup_radxa_dhcp_usb0.sh new file mode 100755 index 0000000..fe8fcc6 --- /dev/null +++ b/scripts/setup_radxa_dhcp_usb0.sh @@ -0,0 +1,68 @@ +#!/usr/bin/env bash +# Configure un serveur DHCP léger (dnsmasq) sur l'interface usb0 (192.168.1.1) +# de la Radxa Zero 3W pour le plug-and-play sur Android (Galaxy Tab S8 Ultra) +# et Linux/SteamOS sans conflit avec les profils IP statiques existants. +# +# Usage : ./scripts/setup_radxa_dhcp_usb0.sh [root@192.168.1.1] + +set -euo pipefail + +RADXA_HOST="${1:-root@192.168.1.1}" + +echo "=== Configuration du serveur DHCP usb0 sur ${RADXA_HOST} ===" + +ssh "${RADXA_HOST}" bash -s << 'EOF' +set -euo pipefail + +if ! command -v dnsmasq >/dev/null 2>&1; then + echo "[*] dnsmasq absent — tentative d'installation via apt-get..." + export DEBIAN_FRONTEND=noninteractive + apt-get update -qq && apt-get install -y -qq dnsmasq-base || apt-get install -y -qq dnsmasq +fi + +mkdir -p /etc/dnsmasq.d + +# Configuration dédiée usb0 : +# - port=0 : désactive le serveur DNS (évite tout conflit avec systemd-resolved) +# - dhcp-option=3 (vide) : n'annonce AUCUNE passerelle par défaut (préserve le Wi-Fi/5G sur Android et Steam Frame) +# - dhcp-option=6 (vide) : n'annonce AUCUN DNS +# - plage 192.168.1.10..192.168.1.20 (premier bail = 192.168.1.10, cohérent avec les scripts existants) +cat << 'CONF' > /etc/dnsmasq.d/steamframe-usb0.conf +port=0 +interface=usb0 +bind-dynamic +dhcp-range=192.168.1.10,192.168.1.20,255.255.255.0,12h +dhcp-option=3 +dhcp-option=6 +dhcp-authoritative +dhcp-leasefile=/tmp/dnsmasq-usb0.leases +CONF + +cat << 'UNIT' > /etc/systemd/system/steamframe-usb0-dhcp.service +[Unit] +Description=SteamFrame FPV DHCP Server on usb0 (Android & SteamOS Plug-and-Play) +After=usb0-setup.service network.target +Wants=usb0-setup.service + +[Service] +Type=simple +ExecStart=/usr/sbin/dnsmasq --keep-in-foreground --no-daemon --conf-file=/etc/dnsmasq.d/steamframe-usb0.conf +Restart=always +RestartSec=2 + +[Install] +WantedBy=multi-user.target +UNIT + +# Si le service dnsmasq global existe et risque d'occuper le port 67, on évite les conflits +if systemctl is-enabled dnsmasq.service >/dev/null 2>&1; then + systemctl disable --now dnsmasq.service || true +fi + +systemctl daemon-reload +systemctl enable steamframe-usb0-dhcp.service +systemctl restart steamframe-usb0-dhcp.service +systemctl status --no-pager steamframe-usb0-dhcp.service || true +EOF + +echo "[+] DHCP usb0 actif sur ${RADXA_HOST} (plage 192.168.1.10-20, sans passerelle ni DNS) !" diff --git a/scripts/setup_radxa_usb_gadget.sh b/scripts/setup_radxa_usb_gadget.sh index c4db6e7..1df36b1 100755 --- a/scripts/setup_radxa_usb_gadget.sh +++ b/scripts/setup_radxa_usb_gadget.sh @@ -76,6 +76,42 @@ EOF mkdir -p "${ROOTFS}/etc/systemd/system/multi-user.target.wants" ln -sf /etc/systemd/system/usb0-setup.service "${ROOTFS}/etc/systemd/system/multi-user.target.wants/usb0-setup.service" +# 3b. Préparer la configuration DHCP légère sur usb0 (plug-and-play Android Tab S8 Ultra & SteamOS) +echo "[3b/5] Préparation de la config DHCP usb0 (sans passerelle ni DNS)..." +mkdir -p "${ROOTFS}/etc/dnsmasq.d" +cat << 'EOF' > "${ROOTFS}/etc/dnsmasq.d/steamframe-usb0.conf" +port=0 +interface=usb0 +bind-dynamic +dhcp-range=192.168.1.10,192.168.1.20,255.255.255.0,12h +dhcp-option=3 +dhcp-option=6 +dhcp-authoritative +dhcp-leasefile=/tmp/dnsmasq-usb0.leases +EOF + +cat << 'EOF' > "${ROOTFS}/etc/systemd/system/steamframe-usb0-dhcp.service" +[Unit] +Description=SteamFrame FPV DHCP Server on usb0 (Android & SteamOS Plug-and-Play) +After=usb0-setup.service network.target +Wants=usb0-setup.service + +[Service] +Type=simple +ExecStart=/usr/sbin/dnsmasq --keep-in-foreground --no-daemon --conf-file=/etc/dnsmasq.d/steamframe-usb0.conf +Restart=always +RestartSec=2 + +[Install] +WantedBy=multi-user.target +EOF + +if [ -x "${ROOTFS}/usr/sbin/dnsmasq" ]; then + ln -sf /etc/systemd/system/steamframe-usb0-dhcp.service "${ROOTFS}/etc/systemd/system/multi-user.target.wants/steamframe-usb0-dhcp.service" +else + echo " -> Info : dnsmasq non présent sur l'image SD, lancez ./scripts/setup_radxa_dhcp_usb0.sh après le premier boot." +fi + # 4. Ajuster le port vidéo dans controller_settings.cfg vers 5600 echo "[4/5] Configuration du port vidéo Ruby vers 5600..." if [ -f "${ROOTFS}/home/radxa/ruby/config/controller_settings.cfg" ]; then diff --git a/src/controller/types.rs b/src/controller/types.rs index b3d264c..1ab24a3 100644 --- a/src/controller/types.rs +++ b/src/controller/types.rs @@ -133,62 +133,7 @@ pub(super) fn eviocgabs(abs_code: u16) -> std::ffi::c_ulong { // TYPES PUBLICS : SOURCE DE CONTRÔLE & ÉTAT STEAM CONTROLLER // ========================================================================= -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -#[repr(u8)] -pub enum ControlSource { - #[default] - G29 = 0, - SteamController = 1, -} - -impl ControlSource { - pub fn from_str(s: &str) -> Self { - let lower = s.trim().to_ascii_lowercase(); - if lower == "steam" - || lower == "steam_controller" - || lower == "steam-controller" - || lower == "controller" - || lower == "gamepad" - || lower == "ext" - { - Self::SteamController - } else { - Self::G29 - } - } - - pub fn from_u8(v: u8) -> Self { - match v { - 1 => Self::SteamController, - _ => Self::G29, - } - } - - pub fn as_u8(self) -> u8 { - self as u8 - } - - pub fn as_str(self) -> &'static str { - match self { - Self::G29 => "g29", - Self::SteamController => "steam", - } - } - - pub fn wire_tag(self) -> &'static str { - match self { - Self::G29 => "G29", - Self::SteamController => "EXT", - } - } - - pub fn label(self) -> &'static str { - match self { - Self::G29 => "Volant G29", - Self::SteamController => "Steam Controller", - } - } -} +pub use fpv_core::ControlSource; #[derive(Debug, Clone)] pub struct SteamControllerConfig { diff --git a/src/g29_bridge.rs b/src/g29_bridge.rs index be914e9..1b1d798 100644 --- a/src/g29_bridge.rs +++ b/src/g29_bridge.rs @@ -1,716 +1,46 @@ -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}; +pub use fpv_core::g29_bridge::*; -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 FpvControlTarget for crate::engine::EngineControlHandle { + fn is_vr_menu_open(&self) -> bool { + self.is_vr_menu_open() } -} - -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) + fn toggle_vr_menu(&self) -> bool { + self.toggle_vr_menu() } - - 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)); + fn close_vr_menu(&self) -> bool { + self.close_vr_menu() } - - 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, - } + fn vr_menu_move(&self, delta: i32) { + self.vr_menu_move(delta as isize); } - - pub fn gear_label(&self) -> &'static str { - match self.gear { - -1 => "R", - 0 => "N", - 1 => "1", - 2 => "2", - 3 => "3", - _ => "?", - } + fn vr_menu_adjust(&self, delta: i32) { + self.vr_menu_adjust(delta); } -} - -#[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, - } + fn vr_menu_activate(&self) { + self.vr_menu_activate(); } -} - -/// 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), - }) + fn request_recenter(&self) { + self.request_recenter(); } - - #[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(()) + fn toggle_dvr(&self) -> bool { + self.toggle_dvr() } - - /// 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)) + fn toggle_telemetry(&self) -> bool { + self.toggle_telemetry() } - - 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) + fn cycle_projection_mode(&self) -> &'static str { + self.cycle_projection_mode() } - - 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(); - } + fn adjust_head_trim(&self, pan_delta_deg: f32, tilt_delta_deg: f32) { + self.adjust_head_trim(pan_delta_deg, tilt_delta_deg); } } #[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)), - &[] - )); - } + use parking_lot::Mutex; + use std::sync::Arc; #[test] fn test_vr_menu_g29_navigation() { @@ -757,23 +87,4 @@ mod tests { 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!((0.0..250.0).contains(&rtt_ms)); - assert!(uart_ok); - } } diff --git a/src/nomad_elrs.rs b/src/nomad_elrs.rs index 192267d..ba17f54 100644 --- a/src/nomad_elrs.rs +++ b/src/nomad_elrs.rs @@ -1,522 +1 @@ -use anyhow::{anyhow, Result}; -use glam::{EulerRot, Quat}; -use std::net::{SocketAddr, ToSocketAddrs, UdpSocket}; -use std::time::{Duration, Instant}; - -/// Opcode MSPv2 officiel ExpressLRS Backpack pour le Head Tracking (Pan, Tilt, Roll) -pub const MSP_ELRS_BACKPACK_SET_PTR: u16 = 0x0383; - -/// Bornes CRSF standard (11 bits : 172 = 988µs, 992 = 1500µs, 1811 = 2012µs) -pub const CRSF_CHANNEL_MIN: u16 = 172; -pub const CRSF_CHANNEL_MID: u16 = 992; -pub const CRSF_CHANNEL_MAX: u16 = 1811; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum NomadProtocol { - /// MSPv2 ELRS_BACKPACK_SET_PTR (0x0383) — mode AP Head-Tracking classique - Msp, - /// CRSF RC_CHANNELS_PACKED (0x16) - Crsf, - /// MAVLink v1 RC_CHANNELS_OVERRIDE (msgid 70) — compatible UDP Backpack /mavlink (port 14555) - Mavlink, - /// Pont unifié G29 / Radxa Zero 3W ($HT,,,) — 100% filaire via usb0:14552 - G29Bridge, -} - -impl NomadProtocol { - pub fn from_str(s: &str) -> Self { - if s.eq_ignore_ascii_case("g29") - || s.eq_ignore_ascii_case("g29_bridge") - || s.eq_ignore_ascii_case("radxa") - { - Self::G29Bridge - } else if s.eq_ignore_ascii_case("crsf") { - Self::Crsf - } else if s.eq_ignore_ascii_case("mavlink") || s.eq_ignore_ascii_case("mav") { - Self::Mavlink - } else { - Self::Msp - } - } - - pub fn label(self) -> &'static str { - match self { - Self::Msp => "MSPv2 0x0383", - Self::Crsf => "CRSF 0x16", - Self::Mavlink => "MAVLink v1 (RC Override)", - Self::G29Bridge => "G29 Hub ($HT)", - } - } -} - -#[derive(Debug, Clone, Copy)] -pub struct HeadPoseSample { - pub pan_deg: f32, - pub tilt_deg: f32, - pub roll_deg: f32, - pub pan_crsf: u16, - pub tilt_crsf: u16, - pub roll_crsf: u16, - pub packets_sent: u64, - pub send_errors: u64, - pub last_send_ok: bool, -} - -impl Default for HeadPoseSample { - fn default() -> Self { - Self { - pan_deg: 0.0, - tilt_deg: 0.0, - roll_deg: 0.0, - pan_crsf: CRSF_CHANNEL_MID, - tilt_crsf: CRSF_CHANNEL_MID, - roll_crsf: CRSF_CHANNEL_MID, - packets_sent: 0, - send_errors: 0, - last_send_ok: false, - } - } -} - -pub struct NomadHeadTracker { - socket: UdpSocket, - target: SocketAddr, - zero_quat_inv: Quat, - max_pan_deg: f32, - max_tilt_deg: f32, - max_roll_deg: f32, - protocol: NomadProtocol, - mav_seq: u8, - last_mav_heartbeat: Option, - packets_sent: u64, - send_errors: u64, - last_error_log: Option, -} - -impl NomadHeadTracker { - pub fn new( - nomad_ip: &str, - nomad_port: u16, - max_pan_deg: f32, - max_tilt_deg: f32, - max_roll_deg: f32, - protocol: NomadProtocol, - ) -> Result { - let trimmed_ip = nomad_ip.trim(); - let host_port = format!("{}:{}", trimmed_ip, nomad_port); - let target = if let Ok(ip) = trimmed_ip.parse::() { - SocketAddr::new(ip, nomad_port) - } else { - let addrs: Vec = host_port - .to_socket_addrs() - .map_err(|e| { - log::error!( - "[Wi-Fi Nomad] Impossible de résoudre la cible ({}) : {}", - host_port, - e - ); - e - })? - .collect(); - addrs - .iter() - .copied() - .find(|a| a.is_ipv4()) - .or_else(|| addrs.into_iter().next()) - .ok_or_else(|| anyhow!("Aucune adresse IP résolue pour {}", host_port))? - }; - - let bind_addr = if target.is_ipv6() { "[::]:0" } else { "0.0.0.0:0" }; - let socket = UdpSocket::bind(bind_addr).map_err(|e| { - log::error!( - "[Wi-Fi Nomad] Impossible de créer le socket UDP sortant : {}", - e - ); - e - })?; - socket.set_nonblocking(true)?; - - log::info!( - "[Wi-Fi Nomad] Émetteur prêt vers {} ({}) (Protocole: {})", - host_port, - target, - protocol.label() - ); - - Ok(Self { - socket, - target, - zero_quat_inv: Quat::IDENTITY, - max_pan_deg, - max_tilt_deg, - max_roll_deg, - protocol, - mav_seq: 0, - last_mav_heartbeat: None, - packets_sent: 0, - send_errors: 0, - last_error_log: None, - }) - } - - /// Réinitialise le centre du suivi de tête (Tare) sur la posture actuelle du casque - pub fn recenter(&mut self, current_orientation: Quat) { - let safe_q = if current_orientation.is_finite() - && current_orientation.length_squared() > 1e-8 - { - current_orientation.normalize() - } else { - Quat::IDENTITY - }; - self.zero_quat_inv = safe_q.inverse(); - log::info!("[Head-Tracker] Centre (Tare) réinitialisé sur la position actuelle du casque."); - } - - /// Calcule Pan/Tilt/Roll depuis le quaternion OpenXR et envoie la trame UDP au Nomad - pub fn send_pose(&mut self, current_orientation: Quat) -> Result { - let raw_rel = self.zero_quat_inv * current_orientation; - let relative = if raw_rel.is_finite() && raw_rel.length_squared() > 1e-8 { - raw_rel.normalize() - } else { - Quat::IDENTITY - }; - - let (yaw_rad, pitch_rad, roll_rad) = relative.to_euler(EulerRot::YXZ); - - let pan_deg = -yaw_rad.to_degrees(); - let tilt_deg = pitch_rad.to_degrees(); - let roll_deg = -roll_rad.to_degrees(); - - self.send_manual_angles(pan_deg, tilt_deg, roll_deg) - } - - /// Encode et envoie directement des angles Pan/Tilt/Roll (en degrés) vers la cible UDP - pub fn send_manual_angles( - &mut self, - pan_deg: f32, - tilt_deg: f32, - roll_deg: f32, - ) -> Result { - let pan_crsf = Self::deg_to_crsf(pan_deg, self.max_pan_deg); - let tilt_crsf = Self::deg_to_crsf(tilt_deg, self.max_tilt_deg); - let roll_crsf = Self::deg_to_crsf(roll_deg, self.max_roll_deg); - - let send_res = match self.protocol { - NomadProtocol::Crsf => { - let packet = Self::encode_crsf_rc_channels(pan_crsf, tilt_crsf, roll_crsf); - self.socket.send_to(&packet, self.target) - } - NomadProtocol::Msp => { - let packet = Self::encode_mspv2_ptr(pan_crsf, tilt_crsf, roll_crsf); - self.socket.send_to(&packet, self.target) - } - NomadProtocol::Mavlink => { - if self - .last_mav_heartbeat - .is_none_or(|t| t.elapsed() >= Duration::from_secs(1)) - { - let hb = Self::encode_mavlink_heartbeat(self.mav_seq); - self.mav_seq = self.mav_seq.wrapping_add(1); - let _ = self.socket.send_to(&hb, self.target); - self.last_mav_heartbeat = Some(Instant::now()); - } - let packet = Self::encode_mavlink_rc_override( - pan_crsf, - tilt_crsf, - roll_crsf, - self.mav_seq, - ); - self.mav_seq = self.mav_seq.wrapping_add(1); - self.socket.send_to(&packet, self.target) - } - NomadProtocol::G29Bridge => { - let msg = Self::encode_g29_ht(pan_crsf, tilt_crsf, roll_crsf); - self.socket.send_to(msg.as_bytes(), self.target) - } - }; - - let last_send_ok = match send_res { - Ok(_) => { - self.packets_sent = self.packets_sent.wrapping_add(1); - true - } - Err(e) => { - self.send_errors = self.send_errors.wrapping_add(1); - let should_log = self - .last_error_log - .map(|t| t.elapsed() >= Duration::from_secs(3)) - .unwrap_or(true); - if should_log { - log::error!( - "[Wi-Fi Nomad] Échec d'envoi UDP vers {} : {} (Vérifiez la connexion Wi-Fi au Backpack du RadioMaster Nomad)", - self.target, - e - ); - self.last_error_log = Some(Instant::now()); - } - false - } - }; - - Ok(HeadPoseSample { - pan_deg, - tilt_deg, - roll_deg, - pan_crsf, - tilt_crsf, - roll_crsf, - packets_sent: self.packets_sent, - send_errors: self.send_errors, - last_send_ok, - }) - } - - #[inline] - pub fn deg_to_crsf(angle_deg: f32, max_deg: f32) -> u16 { - if !angle_deg.is_finite() || !max_deg.is_finite() || max_deg <= 0.0 { - return CRSF_CHANNEL_MID; - } - let norm = (angle_deg / max_deg).clamp(-1.0, 1.0); - let crsf_val = if norm >= 0.0 { - CRSF_CHANNEL_MID as f32 + norm * (CRSF_CHANNEL_MAX - CRSF_CHANNEL_MID) as f32 - } else { - CRSF_CHANNEL_MID as f32 + norm * (CRSF_CHANNEL_MID - CRSF_CHANNEL_MIN) as f32 - }; - (crsf_val.round() as u16).clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX) - } - - /// Ajoute un suffixe CRC-8 DVB-S2 (`*XX\n`) à une trame texte `$...` pour validation UART RP2350. - pub fn append_nmea_crc8(payload: &str) -> String { - let crc = Self::crc8_dvb_s2(payload.as_bytes()); - format!("{}*{:02X}\n", payload, crc) - } - - pub fn encode_g29_ht(pan: u16, tilt: u16, roll: u16) -> String { - Self::append_nmea_crc8(&format!("$HT,{},{},{}", pan, tilt, roll)) - } - - pub fn encode_mspv2_ptr(pan: u16, tilt: u16, roll: u16) -> [u8; 15] { - let mut buf = [0u8; 15]; - buf[0] = b'$'; - buf[1] = b'X'; - buf[2] = b'<'; - buf[3] = 0x00; - buf[4..6].copy_from_slice(&MSP_ELRS_BACKPACK_SET_PTR.to_le_bytes()); - buf[6..8].copy_from_slice(&6u16.to_le_bytes()); - buf[8..10].copy_from_slice(&pan.to_le_bytes()); - buf[10..12].copy_from_slice(&tilt.to_le_bytes()); - buf[12..14].copy_from_slice(&roll.to_le_bytes()); - buf[14] = Self::crc8_dvb_s2(&buf[3..14]); - buf - } - - pub fn encode_crsf_rc_channels(pan: u16, tilt: u16, roll: u16) -> [u8; 26] { - let mut ch = [CRSF_CHANNEL_MID; 16]; - ch[0] = pan.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX); - ch[1] = tilt.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX); - ch[2] = roll.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX); - - let mut frame = [0u8; 26]; - frame[0] = 0xEE; - frame[1] = 24; - frame[2] = 0x16; - - let mut bit_buf: u32 = 0; - let mut bits_in_buf: u8 = 0; - let mut byte_idx = 3; - - for &val in &ch { - bit_buf |= ((val & 0x07FF) as u32) << bits_in_buf; - bits_in_buf += 11; - while bits_in_buf >= 8 { - frame[byte_idx] = (bit_buf & 0xFF) as u8; - byte_idx += 1; - bit_buf >>= 8; - bits_in_buf -= 8; - } - } - - frame[25] = Self::crc8_dvb_s2(&frame[2..25]); - frame - } - - /// Convertit une valeur CRSF (172..1811, neutre 992) en microsecondes PWM (988..2012, neutre 1500) - #[inline] - pub fn crsf_to_pwm_us(crsf: u16) -> u16 { - let clamped = crsf.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX) as f32; - if clamped >= CRSF_CHANNEL_MID as f32 { - let norm = (clamped - CRSF_CHANNEL_MID as f32) / (CRSF_CHANNEL_MAX - CRSF_CHANNEL_MID) as f32; - (1500.0 + norm * 512.0).round() as u16 - } else { - let norm = (clamped - CRSF_CHANNEL_MID as f32) / (CRSF_CHANNEL_MID - CRSF_CHANNEL_MIN) as f32; - (1500.0 + norm * 512.0).round() as u16 - } - } - - /// Encode une trame MAVLink v1 HEARTBEAT (msgid=0, crc_extra=50) pour s'identifier auprès du Backpack - pub fn encode_mavlink_heartbeat(seq: u8) -> [u8; 17] { - let mut payload = [0u8; 9]; - payload[4] = 6; // MAV_TYPE_GCS - payload[5] = 8; // MAV_AUTOPILOT_INVALID - payload[8] = 3; // mavlink_version - Self::encode_mavlink_v1_frame::<9, 17>(0, seq, 50, &payload) - } - - /// Encode une trame MAVLink v1 RC_CHANNELS_OVERRIDE (msgid=70, crc_extra=124) sur les canaux 1..3 - pub fn encode_mavlink_rc_override(pan: u16, tilt: u16, roll: u16, seq: u8) -> [u8; 26] { - let mut payload = [0u8; 18]; - let ch1 = Self::crsf_to_pwm_us(pan); - let ch2 = Self::crsf_to_pwm_us(tilt); - let ch3 = Self::crsf_to_pwm_us(roll); - let ignore = u16::MAX; - payload[0..2].copy_from_slice(&ch1.to_le_bytes()); - payload[2..4].copy_from_slice(&ch2.to_le_bytes()); - payload[4..6].copy_from_slice(&ch3.to_le_bytes()); - payload[6..8].copy_from_slice(&ignore.to_le_bytes()); - payload[8..10].copy_from_slice(&ignore.to_le_bytes()); - payload[10..12].copy_from_slice(&ignore.to_le_bytes()); - payload[12..14].copy_from_slice(&ignore.to_le_bytes()); - payload[14..16].copy_from_slice(&ignore.to_le_bytes()); - payload[16] = 1; // target_system - payload[17] = 1; // target_component - Self::encode_mavlink_v1_frame::<18, 26>(70, seq, 124, &payload) - } - - fn encode_mavlink_v1_frame( - msgid: u8, - seq: u8, - crc_extra: u8, - payload: &[u8; P], - ) -> [u8; T] { - debug_assert_eq!(T, P + 8); - let mut buf = [0u8; T]; - buf[0] = 0xFE; - buf[1] = P as u8; - buf[2] = seq; - buf[3] = 255; // GCS system_id - buf[4] = 190; // MAV_COMP_ID_MISSIONPLANNER / GCS - buf[5] = msgid; - buf[6..6 + P].copy_from_slice(payload); - let crc = Self::mavlink_crc16(&buf[1..6 + P], crc_extra); - buf[6 + P..8 + P].copy_from_slice(&crc.to_le_bytes()); - buf - } - - #[inline] - pub fn mavlink_crc16(data: &[u8], crc_extra: u8) -> u16 { - let mut crc: u16 = 0xFFFF; - for &b in data.iter().chain(std::iter::once(&crc_extra)) { - let mut tmp = b ^ (crc & 0xFF) as u8; - tmp ^= tmp << 4; - crc = (crc >> 8) - ^ ((tmp as u16) << 8) - ^ ((tmp as u16) << 3) - ^ ((tmp as u16) >> 4); - } - crc - } - - #[inline] - pub fn crc8_dvb_s2(data: &[u8]) -> u8 { - const TABLE: [u8; 256] = { - let mut table = [0u8; 256]; - let mut i = 0; - while i < 256 { - let mut curr = i as u8; - let mut j = 0; - while j < 8 { - if (curr & 0x80) != 0 { - curr = (curr << 1) ^ 0xD5; - } else { - curr <<= 1; - } - j += 1; - } - table[i] = curr; - i += 1; - } - table - }; - - let mut crc: u8 = 0; - for &byte in data { - crc = TABLE[(crc ^ byte) as usize]; - } - crc - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_deg_to_crsf_bounds() { - assert_eq!(NomadHeadTracker::deg_to_crsf(0.0, 90.0), CRSF_CHANNEL_MID); - assert_eq!(NomadHeadTracker::deg_to_crsf(90.0, 90.0), CRSF_CHANNEL_MAX); - assert_eq!(NomadHeadTracker::deg_to_crsf(-90.0, 90.0), CRSF_CHANNEL_MIN); - assert_eq!(NomadHeadTracker::deg_to_crsf(f32::NAN, 90.0), CRSF_CHANNEL_MID); - assert_eq!(NomadHeadTracker::deg_to_crsf(45.0, f32::NAN), CRSF_CHANNEL_MID); - assert_eq!(NomadHeadTracker::deg_to_crsf(45.0, 0.0), CRSF_CHANNEL_MID); - assert_eq!(NomadHeadTracker::deg_to_crsf(45.0, -10.0), CRSF_CHANNEL_MID); - } - - #[test] - fn test_mspv2_ptr_packet_header() { - let pkt = NomadHeadTracker::encode_mspv2_ptr(992, 992, 992); - assert_eq!(&pkt[0..3], b"$X<"); - assert_eq!(u16::from_le_bytes([pkt[4], pkt[5]]), MSP_ELRS_BACKPACK_SET_PTR); - assert_eq!(u16::from_le_bytes([pkt[6], pkt[7]]), 6); - assert_eq!(pkt[14], NomadHeadTracker::crc8_dvb_s2(&pkt[3..14])); - } - - #[test] - fn test_crsf_rc_channels_packet() { - let pkt = NomadHeadTracker::encode_crsf_rc_channels(992, 992, 992); - assert_eq!(pkt[0], 0xEE); // Sync CRSF - assert_eq!(pkt[1], 24); // Payload len - assert_eq!(pkt[2], 0x16); // Type RC_CHANNELS_PACKED - assert_eq!(pkt[25], NomadHeadTracker::crc8_dvb_s2(&pkt[2..25])); - } - - #[test] - fn test_mavlink_rc_override_packet() { - assert_eq!(NomadHeadTracker::crsf_to_pwm_us(992), 1500); - let pkt = NomadHeadTracker::encode_mavlink_rc_override(992, 992, 992, 7); - assert_eq!(pkt[0], 0xFE); - assert_eq!(pkt[1], 18); - assert_eq!(pkt[2], 7); - assert_eq!(pkt[5], 70); - assert_eq!(u16::from_le_bytes([pkt[6], pkt[7]]), 1500); - assert_eq!(u16::from_le_bytes([pkt[8], pkt[9]]), 1500); - assert_eq!(u16::from_le_bytes([pkt[10], pkt[11]]), 1500); - let expected_crc = NomadHeadTracker::mavlink_crc16(&pkt[1..24], 124); - assert_eq!(u16::from_le_bytes([pkt[24], pkt[25]]), expected_crc); - } - - #[test] - fn test_mavlink_heartbeat_packet() { - let pkt = NomadHeadTracker::encode_mavlink_heartbeat(1); - assert_eq!(pkt[0], 0xFE); - assert_eq!(pkt[1], 9); - assert_eq!(pkt[5], 0); - let expected_crc = NomadHeadTracker::mavlink_crc16(&pkt[1..15], 50); - assert_eq!(u16::from_le_bytes([pkt[15], pkt[16]]), expected_crc); - } - - #[test] - fn test_hostname_resolution_default_ip() { - let ht = NomadHeadTracker::new("10.0.0.1", 14550, 90.0, 60.0, 45.0, NomadProtocol::Msp); - assert!(ht.is_ok()); - } - - #[test] - fn test_g29_bridge_ht_format() { - assert_eq!(NomadProtocol::from_str("g29"), NomadProtocol::G29Bridge); - let frame = NomadHeadTracker::encode_g29_ht(992, 1200, 800); - let (body, hex_crc) = frame.trim_end_matches('\n').split_once('*').unwrap(); - assert_eq!(body, "$HT,992,1200,800"); - let expected = format!("{:02X}", NomadHeadTracker::crc8_dvb_s2(body.as_bytes())); - assert_eq!(hex_crc, expected); - } -} +pub use fpv_core::nomad_elrs::*; diff --git a/src/telemetry_osd/mod.rs b/src/telemetry_osd/mod.rs index 62ab5e7..c737631 100644 --- a/src/telemetry_osd/mod.rs +++ b/src/telemetry_osd/mod.rs @@ -1,10 +1,7 @@ mod osd; -mod parser; -mod state; +pub use fpv_core::telemetry::{TelemetryReceiver, TelemetryState}; pub use osd::{OsdExtraOptions, OsdOverlay, VrMenuPage, VrMenuRenderData}; -pub use parser::TelemetryReceiver; -pub use state::TelemetryState; /// Tampon de formatage rapide sur la pile pour éliminer toute allocation sur le tas dans l'OSD pub(super) struct StackStr { diff --git a/src/telemetry_osd/osd.rs b/src/telemetry_osd/osd.rs index fbf6ae5..ad6b248 100644 --- a/src/telemetry_osd/osd.rs +++ b/src/telemetry_osd/osd.rs @@ -1,4 +1,4 @@ -use super::state::TelemetryState; +use super::TelemetryState; use super::StackStr; use crate::controller::ControlSource; use crate::g29_bridge::G29State;