feat(core,radxa): extract cross-platform fpv-core workspace crate and add usb0 DHCP setup for Android

This commit is contained in:
bleack committed 2026-11-27 00:03:24 +01:00
1 parent 9a8ae95b3f
commit 16d05785fb
18 files changed
+2119 -1298

No files matched your search

+58
View File
@@ -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",
}
}
}
+760
View File
@@ -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<Instant>,
pub last_button: String,
pub last_button_at: Option<Instant>,
pub toast_text: String,
pub toast_until: Option<Instant>,
}
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<String>) {
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<Self> {
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<Mutex<G29State>>,
stop_flag: Arc<AtomicBool>,
worker: Option<thread::JoinHandle<()>>,
}
impl G29BridgeReceiver {
pub fn start(
bind_ip: &str,
port: u16,
control: impl FpvControlTarget,
telemetry: Option<Arc<Mutex<TelemetryState>>>,
allowed_peers: Vec<std::net::IpAddr>,
) -> Result<Self> {
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<Instant> = 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,<seq>` -> `$PONG,<seq>,<uart_ok>`).
/// 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::<u64>().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<Mutex<G29State>> {
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<Mutex<G29State>>,
control: Option<&dyn FpvControlTarget>,
telemetry: Option<&Arc<Mutex<TelemetryState>>>,
) {
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<Mutex<TelemetryState>>) {
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<u8> {
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<Mutex<G29State>>) {
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::<u8>() {
st.armed = val != 0;
}
}
"GEAR" => {
if let Ok(val) = v.trim().parse::<i8>() {
st.gear = val.clamp(-1, 3);
}
}
"THROT" => {
if let Ok(val) = v.trim().parse::<u8>() {
st.throttle_pct = val.min(100);
}
}
"BRAKE" => {
if let Ok(val) = v.trim().parse::<u8>() {
st.brake_pct = val.min(100);
}
}
"CLUTCH" => {
if let Ok(val) = v.trim().parse::<u8>() {
st.clutch_pct = val.min(100);
}
}
"STEER" => {
if let Ok(val) = v.trim().parse::<i8>() {
st.steering_pct = val.clamp(-100, 100);
}
}
"CH1" => {
if let Ok(val) = v.trim().parse::<u16>() {
st.steer_crsf = val.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX);
}
}
"CH2" => {
if let Ok(val) = v.trim().parse::<u16>() {
st.throttle_crsf = val.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX);
}
}
"CH3" => {
if let Ok(val) = v.trim().parse::<u16>() {
st.brake_crsf = val.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX);
}
}
"CH4" => {
if let Ok(val) = v.trim().parse::<u16>() {
st.clutch_crsf = val.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX);
}
}
"FFB" => {
if let Ok(val) = v.trim().parse::<u8>() {
st.ffb_raw = val;
st.ffb_pct = ((val as u16 * 100) / 255) as u8;
}
}
"VIB" => {
if let Ok(val) = v.trim().parse::<u8>() {
st.vib_pct = val.min(100);
}
}
"FAIL" => {
if let Ok(val) = v.trim().parse::<u8>() {
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<Mutex<G29State>>,
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);
}
}
+21
View File
@@ -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,
};
+523
View File
@@ -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,<pan>,<tilt>,<roll>) — 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<Instant>,
packets_sent: u64,
send_errors: u64,
last_error_log: Option<Instant>,
}
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<Self> {
let trimmed_ip = nomad_ip.trim();
let host_port = format!("{}:{}", trimmed_ip, nomad_port);
let target = if let Ok(ip) = trimmed_ip.parse::<std::net::IpAddr>() {
SocketAddr::new(ip, nomad_port)
} else {
let addrs: Vec<SocketAddr> = 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<HeadPoseSample> {
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<HeadPoseSample> {
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<const P: usize, const T: usize>(
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);
}
}
+5
View File
@@ -0,0 +1,5 @@
pub mod parser;
pub mod state;
pub use parser::TelemetryReceiver;
pub use state::TelemetryState;
+353
View File
@@ -0,0 +1,353 @@
use super::state::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};
/// Récepteur UDP non-bloquant décodant les trames MAVLink v1/v2 (OpenIPC) et CRSF (ELRS)
pub struct TelemetryReceiver {
state: Arc<Mutex<TelemetryState>>,
stop_flag: Arc<AtomicBool>,
worker: Option<thread::JoinHandle<()>>,
}
impl TelemetryReceiver {
#[allow(dead_code)]
pub fn start(bind_ip: &str, port: u16) -> Result<Self> {
Self::start_with_state(
bind_ip,
port,
Arc::new(Mutex::new(TelemetryState::default())),
Vec::new(),
)
}
pub fn start_with_state(
bind_ip: &str,
port: u16,
state: Arc<Mutex<TelemetryState>>,
allowed_peers: Vec<std::net::IpAddr>,
) -> Result<Self> {
let addr = format!("{}:{}", bind_ip, port);
let socket = UdpSocket::bind(&addr).map_err(|e| {
log::error!(
"[Télémétrie OSD] Impossible d'écouter sur UDP {} (port déjà utilisé ou IP invalide) : {}",
addr,
e
);
e
})?;
socket.set_read_timeout(Some(Duration::from_millis(100)))?;
log::info!(
"[Télémétrie OSD] Récepteur MAVLink / CRSF en écoute sur UDP {} (pairs autorisés: {:?})",
addr,
allowed_peers
);
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("telemetry-udp-rx".into())
.spawn(move || {
let mut buf = [0u8; 1024];
let mut last_reject_log: Option<Instant> = None;
while !stop_clone.load(Ordering::Acquire) {
if let Ok((len, src)) = socket.recv_from(&mut buf) {
if !src.ip().is_loopback()
&& !allowed_peers.is_empty()
&& !allowed_peers.contains(&src.ip())
{
if last_reject_log
.is_none_or(|t| t.elapsed() >= Duration::from_secs(5))
{
log::warn!(
"[Télémétrie OSD] Paquet UDP rejeté depuis IP non autorisée : {}",
src
);
last_reject_log = Some(Instant::now());
}
continue;
}
Self::parse_datagram(&buf[..len], &state_clone);
}
}
log::info!("[Télémétrie OSD] Thread d'écoute UDP arrêté.");
})?;
Ok(Self {
state,
stop_flag,
worker: Some(worker),
})
}
pub fn state(&self) -> Arc<Mutex<TelemetryState>> {
Arc::clone(&self.state)
}
fn mavlink_crc_extra(msg_id: u32) -> Option<u8> {
match msg_id {
0 => Some(50),
1 => Some(124),
30 => Some(39),
74 => Some(20),
109 => Some(185),
_ => None,
}
}
pub fn parse_datagram(data: &[u8], state: &Arc<Mutex<TelemetryState>>) {
let mut i = 0;
while i < data.len() {
match data[i] {
0xFE if i + 8 <= data.len() => {
let payload_len = data[i + 1] as usize;
let total_len = 6 + payload_len + 2;
if i + total_len <= data.len() {
let msg_id = data[i + 5] as u32;
if let Some(extra) = Self::mavlink_crc_extra(msg_id) {
let crc_calc = crate::nomad_elrs::NomadHeadTracker::mavlink_crc16(
&data[i + 1..i + 6 + payload_len],
extra,
);
let crc_pkt = u16::from_le_bytes([
data[i + 6 + payload_len],
data[i + 7 + payload_len],
]);
if crc_calc == crc_pkt {
let payload = &data[i + 6..i + 6 + payload_len];
Self::handle_mavlink_payload(msg_id, payload, state);
i += total_len;
continue;
}
} else if i + total_len == data.len()
|| matches!(data[i + total_len], 0xFE | 0xFD | 0xC8 | 0xEA | 0xEE)
{
// Sauter la trame MAVLink v1 non gérée sans scanner son payload pour des faux positifs CRSF
i += total_len;
continue;
}
}
}
0xFD if i + 12 <= data.len() => {
let payload_len = data[i + 1] as usize;
let incompat_flags = data[i + 2];
let sig_len = if (incompat_flags & 0x01) != 0 { 13 } else { 0 };
let total_len = 10 + payload_len + 2 + sig_len;
if i + total_len <= data.len() {
let msg_id = (data[i + 7] as u32)
| ((data[i + 8] as u32) << 8)
| ((data[i + 9] as u32) << 16);
if let Some(extra) = Self::mavlink_crc_extra(msg_id) {
let crc_calc = crate::nomad_elrs::NomadHeadTracker::mavlink_crc16(
&data[i + 1..i + 10 + payload_len],
extra,
);
let crc_pkt = u16::from_le_bytes([
data[i + 10 + payload_len],
data[i + 11 + payload_len],
]);
if crc_calc == crc_pkt {
let payload = &data[i + 10..i + 10 + payload_len];
Self::handle_mavlink_payload(msg_id, payload, state);
i += total_len;
continue;
}
} else if i + total_len == data.len()
|| matches!(data[i + total_len], 0xFE | 0xFD | 0xC8 | 0xEA | 0xEE)
{
// Sauter la trame MAVLink v2 non gérée sans scanner son payload pour des faux positifs CRSF
i += total_len;
continue;
}
}
}
0xC8 | 0xEA | 0xEE if i + 4 <= data.len() => {
let frame_len = data[i + 1] as usize;
if (2..=62).contains(&frame_len) && i + 2 + frame_len <= data.len() {
let crc_idx = i + 2 + frame_len - 1;
let expected_crc = crate::nomad_elrs::NomadHeadTracker::crc8_dvb_s2(
&data[i + 2..crc_idx],
);
if data[crc_idx] == expected_crc {
let frame_type = data[i + 2];
let payload = &data[i + 3..crc_idx];
Self::handle_crsf_payload(frame_type, payload, state);
i += 2 + frame_len;
continue;
}
}
}
_ => {}
}
i += 1;
}
}
fn handle_mavlink_payload(msg_id: u32, payload: &[u8], state: &Arc<Mutex<TelemetryState>>) {
// MAVLink v2 tronque les octets nuls de fin : zero-padding dans un buffer fixe avant décodage.
let mut padded = [0u8; 255];
let copy_len = payload.len().min(padded.len());
padded[..copy_len].copy_from_slice(&payload[..copy_len]);
let mut st = state.lock();
st.packets_received = st.packets_received.wrapping_add(1);
st.last_update = Some(Instant::now());
match msg_id {
1 => {
let voltage_mv = u16::from_le_bytes([padded[14], padded[15]]);
let current_ca = i16::from_le_bytes([padded[16], padded[17]]);
let remaining = padded[30] as i8;
if voltage_mv != u16::MAX {
st.update_battery_voltage(voltage_mv as f32 / 1000.0);
}
if current_ca != -1 {
st.battery_current_a = current_ca as f32 / 100.0;
}
st.battery_remaining_pct = remaining;
}
30 => {
let roll = f32::from_le_bytes([padded[4], padded[5], padded[6], padded[7]]);
let pitch = f32::from_le_bytes([padded[8], padded[9], padded[10], padded[11]]);
let yaw_rad = f32::from_le_bytes([padded[12], padded[13], padded[14], padded[15]]);
if roll.is_finite() && pitch.is_finite() {
let safe_roll = roll.clamp(-std::f32::consts::PI, std::f32::consts::PI);
let safe_pitch = pitch.clamp(-std::f32::consts::PI, std::f32::consts::PI);
st.drone_roll_rad = safe_roll;
st.drone_pitch_rad = safe_pitch;
st.update_attitude_roughness(safe_pitch, safe_roll);
}
if yaw_rad.is_finite() {
st.drone_heading_deg = yaw_rad.to_degrees().rem_euclid(360.0);
}
}
74 => {
let gs = f32::from_le_bytes([padded[4], padded[5], padded[6], padded[7]]);
let alt = f32::from_le_bytes([padded[8], padded[9], padded[10], padded[11]]);
let climb = f32::from_le_bytes([padded[12], padded[13], padded[14], padded[15]]);
let heading = i16::from_le_bytes([padded[16], padded[17]]);
st.throttle_pct = u16::from_le_bytes([padded[18], padded[19]]);
if gs.is_finite() {
st.groundspeed_ms = gs;
}
if alt.is_finite() {
st.altitude_m = alt;
}
if climb.is_finite() {
st.climb_ms = climb;
}
if (0..=360).contains(&heading) {
st.drone_heading_deg = heading as f32;
}
}
109 => {
// MAVLink RADIO_STATUS: 255 = valeur inconnue
let rssi = padded[4];
if rssi != u8::MAX {
st.link_quality_pct = rssi.min(100);
}
let remrssi = padded[5];
if remrssi != u8::MAX {
// Échelle SiK/MAVLink standard (0..254 -> approx dBm) ou magnitude négative
st.rssi_dbm = if remrssi == 0 {
-127
} else {
-((remrssi / 2).min(127) as i8)
};
}
}
_ => {}
}
}
fn handle_crsf_payload(frame_type: u8, payload: &[u8], state: &Arc<Mutex<TelemetryState>>) {
let mut st = state.lock();
st.packets_received = st.packets_received.wrapping_add(1);
st.last_update = Some(Instant::now());
match frame_type {
0x02 if payload.len() >= 15 => {
// CRSF GPS : lat/lon (i32 * 1e-7), groundspeed (u16 * 0.1 km/h), heading (u16 * 0.01 deg),
// altitude (u16 - 1000 m), satellites (u8)
let lat_raw = i32::from_be_bytes([payload[0], payload[1], payload[2], payload[3]]);
let lon_raw = i32::from_be_bytes([payload[4], payload[5], payload[6], payload[7]]);
let gs_10kmh = u16::from_be_bytes([payload[8], payload[9]]);
let hdg_100 = u16::from_be_bytes([payload[10], payload[11]]);
let alt_off = u16::from_be_bytes([payload[12], payload[13]]);
let sats = payload[14];
st.gps_lat_deg = lat_raw as f64 / 1e7;
st.gps_lon_deg = lon_raw as f64 / 1e7;
st.gps_sats = sats;
st.gps_alt_m = alt_off as f32 - 1000.0;
st.gps_fix_valid = sats >= 4 && (lat_raw != 0 || lon_raw != 0);
if st.gps_fix_valid {
st.last_valid_gps = Some((st.gps_lat_deg, st.gps_lon_deg, st.gps_alt_m, sats));
st.last_valid_gps_at = Some(Instant::now());
}
st.groundspeed_ms = (gs_10kmh as f32 * 0.1) / 3.6;
st.altitude_m = st.gps_alt_m;
if hdg_100 <= 36000 {
st.drone_heading_deg = hdg_100 as f32 / 100.0;
}
}
0x08 if payload.len() >= 8 => {
let mv_div_100 = u16::from_be_bytes([payload[0], payload[1]]);
let ma_div_100 = u16::from_be_bytes([payload[2], payload[3]]);
st.update_battery_voltage(mv_div_100 as f32 / 10.0);
st.battery_current_a = ma_div_100 as f32 / 10.0;
st.battery_remaining_pct = payload[7] as i8;
}
0x14 if payload.len() >= 10 => {
// CRSF LINK_STATISTICS : payload[0]=RSSI1 (u8 magnitude), payload[1]=RSSI2,
// payload[2]=LQ (0..100), payload[4]=active_antenna (0 ou 1).
// Évite le panic overflow `i8::MIN.abs()` lorsque RSSI == 128 dBm (0x80).
let active_ant = payload[4];
let raw_rssi = if active_ant == 1 && payload[1] > 0 {
payload[1]
} else {
payload[0]
};
st.rssi_dbm = -(raw_rssi.min(127) as i8);
st.link_quality_pct = payload[2].min(100);
}
0x1E if payload.len() >= 6 => {
let pitch_10000 = i16::from_be_bytes([payload[0], payload[1]]);
let roll_10000 = i16::from_be_bytes([payload[2], payload[3]]);
let yaw_10000 = i16::from_be_bytes([payload[4], payload[5]]);
st.drone_pitch_rad = pitch_10000 as f32 / 10000.0;
st.drone_roll_rad = roll_10000 as f32 / 10000.0;
st.drone_heading_deg = (yaw_10000 as f32 / 10000.0).to_degrees().rem_euclid(360.0);
let pitch = st.drone_pitch_rad;
let roll = st.drone_roll_rad;
st.update_attitude_roughness(pitch, roll);
}
0x21 if !payload.is_empty() => {
// CRSF FLIGHT_MODE : chaîne ASCII terminée par '\0'
let end = payload.iter().position(|&b| b == 0).unwrap_or(payload.len());
if let Ok(mode_str) = std::str::from_utf8(&payload[..end]) {
let trimmed = mode_str.trim();
if !trimmed.is_empty() && trimmed.len() <= 24 {
st.flight_mode = trimmed.to_string();
}
}
}
_ => {}
}
}
}
impl Drop for TelemetryReceiver {
fn drop(&mut self) {
self.stop_flag.store(true, Ordering::Release);
if let Some(handle) = self.worker.take() {
let _ = handle.join();
}
}
}
+310
View File
@@ -0,0 +1,310 @@
use std::time::{Duration, Instant};
/// État télémétrique temps réel fusionnant MAVLink (OpenIPC / FC) et CRSF (ELRS Nomad)
#[derive(Debug, Clone)]
pub struct TelemetryState {
pub battery_voltage_v: f32,
pub battery_current_a: f32,
pub battery_remaining_pct: i8,
/// Nombre de cellules LiPo auto-détecté (2..=6) dès réception d'une tension valide >= 6.0 V
pub battery_cells_detected: u8,
pub drone_roll_rad: f32,
pub drone_pitch_rad: f32,
pub drone_heading_deg: f32,
pub altitude_m: f32,
pub groundspeed_ms: f32,
pub climb_ms: f32,
pub throttle_pct: u16,
pub link_quality_pct: u8,
pub rssi_dbm: i8,
/// Données GPS CRSF (0x02) & Mode de vol CRSF (0x21)
pub gps_lat_deg: f64,
pub gps_lon_deg: f64,
pub gps_sats: u8,
pub gps_alt_m: f32,
pub gps_fix_valid: bool,
/// Point Home mémorisé au premier armement avec fix GPS valide (>= 6 sats)
pub home_lat_deg: Option<f64>,
pub home_lon_deg: Option<f64>,
/// Dernière position GPS valide connue (lat, lon, alt_m, sats) — figée en cas de perte liaison (Lost Model)
pub last_valid_gps: Option<(f64, f64, f32, u8)>,
pub last_valid_gps_at: Option<Instant>,
pub flight_mode: String,
pub packets_received: u64,
pub last_update: Option<Instant>,
/// Rugosité terrain dérivée de l'attitude Pitch/Roll (0..255) pour le retour haptique
pub terrain_roughness: u8,
pub prev_pitch_rad: Option<f32>,
pub prev_roll_rad: Option<f32>,
pub last_attitude_update: Option<Instant>,
}
impl Default for TelemetryState {
fn default() -> Self {
Self {
battery_voltage_v: 0.0,
battery_current_a: 0.0,
battery_remaining_pct: -1,
battery_cells_detected: 0,
drone_roll_rad: 0.0,
drone_pitch_rad: 0.0,
drone_heading_deg: 0.0,
altitude_m: 0.0,
groundspeed_ms: 0.0,
climb_ms: 0.0,
throttle_pct: 0,
link_quality_pct: 0,
rssi_dbm: -127,
gps_lat_deg: 0.0,
gps_lon_deg: 0.0,
gps_sats: 0,
gps_alt_m: 0.0,
gps_fix_valid: false,
home_lat_deg: None,
home_lon_deg: None,
last_valid_gps: None,
last_valid_gps_at: None,
flight_mode: String::new(),
packets_received: 0,
last_update: None,
terrain_roughness: 0,
prev_pitch_rad: None,
prev_roll_rad: None,
last_attitude_update: None,
}
}
}
impl TelemetryState {
/// Indique si la télémétrie a reçu au moins une trame valide au cours des 2,5 dernières secondes.
pub fn is_live(&self) -> bool {
self.packets_received > 0
&& self
.last_update
.is_some_and(|t| t.elapsed() <= Duration::from_millis(2500))
}
/// Auto-détecte le nombre de cellules LiPo (2S..6S) sur la tension initiale du pack.
pub fn update_battery_voltage(&mut self, voltage_v: f32) {
if !voltage_v.is_finite() || voltage_v < 0.0 {
return;
}
self.battery_voltage_v = voltage_v;
if self.battery_cells_detected == 0 && (6.0..=26.5).contains(&voltage_v) {
let est = (voltage_v / 4.35).ceil().clamp(2.0, 6.0) as u8;
self.battery_cells_detected = est;
}
}
/// Nombre de cellules effectif (config manuelle prioritaire si >= 2, sinon auto-détecté).
pub fn effective_cells(&self, configured_cells: u8) -> u8 {
if (2..=6).contains(&configured_cells) {
configured_cells
} else if (2..=6).contains(&self.battery_cells_detected) {
self.battery_cells_detected
} else if self.battery_voltage_v >= 6.0 && self.battery_voltage_v <= 26.5 {
(self.battery_voltage_v / 4.35).ceil().clamp(2.0, 6.0) as u8
} else {
0
}
}
pub fn cell_voltage_v(&self, configured_cells: u8) -> Option<f32> {
let cells = self.effective_cells(configured_cells);
if cells >= 2 && self.battery_voltage_v > 0.5 {
Some(self.battery_voltage_v / cells as f32)
} else {
None
}
}
pub fn is_battery_critical(&self, configured_cells: u8, crit_cell_v: f32) -> bool {
self.is_live()
&& self
.cell_voltage_v(configured_cells)
.is_some_and(|cv| cv < crit_cell_v)
}
pub fn is_link_critical(&self) -> bool {
self.is_live() && self.link_quality_pct < 50
}
/// Mémorise automatiquement le point Home lors du premier armement avec fix GPS valide (>= 6 satellites).
pub fn maybe_lock_home(&mut self, armed: bool) {
if self.home_lat_deg.is_some() || !armed {
return;
}
if self.gps_fix_valid
&& self.gps_sats >= 6
&& (self.gps_lat_deg.abs() > 1e-4 || self.gps_lon_deg.abs() > 1e-4)
{
self.home_lat_deg = Some(self.gps_lat_deg);
self.home_lon_deg = Some(self.gps_lon_deg);
log::info!(
"[GPS Home] Point Home mémorisé : {:.6}, {:.6} ({} sats)",
self.gps_lat_deg,
self.gps_lon_deg,
self.gps_sats
);
}
}
#[allow(dead_code)]
pub fn reset_home(&mut self) {
self.home_lat_deg = None;
self.home_lon_deg = None;
}
/// Retourne `(distance_m, angle_relatif_deg)` vers le point Home par rapport au cap courant du véhicule.
/// `0°` = droit devant, `+90°` = à droite, `-90°` = à gauche, `±180°` = derrière.
pub fn home_vector(&self) -> Option<(f32, f32)> {
let (hlat, hlon) = (self.home_lat_deg?, self.home_lon_deg?);
if !self.gps_fix_valid {
return None;
}
let dist_m = haversine_distance_m(self.gps_lat_deg, self.gps_lon_deg, hlat, hlon);
let bearing_home = initial_bearing_deg(self.gps_lat_deg, self.gps_lon_deg, hlat, hlon);
let mut rel = (bearing_home - self.drone_heading_deg) % 360.0;
if rel > 180.0 {
rel -= 360.0;
} else if rel < -180.0 {
rel += 360.0;
}
Some((dist_m, rel))
}
/// Retourne `(distance_m, azimut_depuis_home_deg)` entre le point Home et la dernière position GPS valide connue.
/// Utile en mode « Véhicule Perdu » (Lost Model) pour savoir dans quelle direction marcher.
pub fn last_known_gps_from_home(&self) -> Option<(f32, f32)> {
let (hlat, hlon) = (self.home_lat_deg?, self.home_lon_deg?);
let (lat, lon, _, _) = self.last_valid_gps?;
let dist_m = haversine_distance_m(hlat, hlon, lat, lon);
let bearing = initial_bearing_deg(hlat, hlon, lat, lon);
Some((dist_m, bearing))
}
/// URL Google Maps vers la dernière position GPS valide connue.
pub fn last_known_gps_maps_url(&self) -> Option<String> {
let (lat, lon, _, _) = self.last_valid_gps?;
Some(format!("https://maps.google.com/?q={:.6},{:.6}", lat, lon))
}
/// Formate une ligne compacte de télémétrie pour sous-titres DVR `.srt` (VLC/MPV).
pub fn format_dvr_srt_caption(
&self,
configured_cells: u8,
gear_label: &str,
video_fps: f32,
video_jitter_ms: f32,
) -> String {
let mut parts: Vec<String> = Vec::with_capacity(6);
if let Some(cv) = self.cell_voltage_v(configured_cells) {
parts.push(format!(
"BAT {:.1}V ({}S {:.2}V/c) {:.1}A",
self.battery_voltage_v,
self.effective_cells(configured_cells),
cv,
self.battery_current_a
));
} else if self.battery_voltage_v > 0.1 {
parts.push(format!(
"BAT {:.1}V {:.1}A",
self.battery_voltage_v, self.battery_current_a
));
}
if self.is_live() {
parts.push(format!("LQ {}% RSSI {}dBm", self.link_quality_pct, self.rssi_dbm));
}
if !gear_label.is_empty() {
parts.push(format!("GEAR {}", gear_label));
}
if self.groundspeed_ms > 0.1 {
parts.push(format!("{:.1} km/h", self.groundspeed_ms * 3.6));
}
if self.gps_fix_valid && self.gps_sats > 0 {
let home_part = self
.home_vector()
.map(|(d, _)| format!(" HOME {:.0}m", d))
.unwrap_or_default();
parts.push(format!(
"GPS {:.5},{:.5} ({}sat){}",
self.gps_lat_deg, self.gps_lon_deg, self.gps_sats, home_part
));
}
if video_fps > 0.5 {
parts.push(format!("VID {:.0}fps jit {:.1}ms", video_fps, video_jitter_ms));
}
parts.join(" | ")
}
/// Calcule la rugosité du terrain (0..255) à partir de la dérivée Pitch/Roll,
/// alignée sur l'algorithme du firmware RP2350 (seuil mort 0.006 rad ≈ 0.35°, saturation 0.045 rad).
pub fn update_attitude_roughness(&mut self, pitch_rad: f32, roll_rad: f32) {
const DEADBAND_RAD: f32 = 0.006;
const SATURATION_RAD: f32 = 0.045;
let now = Instant::now();
if let (Some(prev_p), Some(prev_r)) = (self.prev_pitch_rad, self.prev_roll_rad) {
let delta = (pitch_rad - prev_p).abs() + (roll_rad - prev_r).abs();
let instant = if delta <= DEADBAND_RAD {
0u8
} else {
let norm = ((delta - DEADBAND_RAD) / (SATURATION_RAD - DEADBAND_RAD)).clamp(0.0, 1.0);
(norm * 255.0).round() as u8
};
// Attaque instantanée sur choc, décroissance douce entre trames
self.terrain_roughness = if instant >= self.terrain_roughness {
instant
} else {
((self.terrain_roughness as u16 * 3 + instant as u16) / 4) as u8
};
} else {
self.terrain_roughness = 0;
}
self.prev_pitch_rad = Some(pitch_rad);
self.prev_roll_rad = Some(roll_rad);
self.last_attitude_update = Some(now);
}
/// Retourne la rugosité terrain active avec décroissance linéaire entre 200 ms et 500 ms sans nouvelle attitude.
pub fn effective_terrain_roughness(&self) -> u8 {
if self.terrain_roughness == 0 {
return 0;
}
let Some(last) = self.last_attitude_update else {
return 0;
};
let elapsed_ms = Instant::now().saturating_duration_since(last).as_millis() as u64;
if elapsed_ms <= 200 {
self.terrain_roughness
} else if elapsed_ms >= 500 {
0
} else {
((self.terrain_roughness as u64 * (500 - elapsed_ms)) / 300) as u8
}
}
}
/// Distance géodésique Haversine en mètres entre deux points WGS84 (degrés).
pub fn haversine_distance_m(lat1_deg: f64, lon1_deg: f64, lat2_deg: f64, lon2_deg: f64) -> f32 {
const EARTH_R_M: f64 = 6_371_000.0;
let lat1 = lat1_deg.to_radians();
let lat2 = lat2_deg.to_radians();
let dlat = (lat2_deg - lat1_deg).to_radians();
let dlon = (lon2_deg - lon1_deg).to_radians();
let a = (dlat * 0.5).sin().powi(2) + lat1.cos() * lat2.cos() * (dlon * 0.5).sin().powi(2);
let c = 2.0 * a.clamp(0.0, 1.0).sqrt().asin();
(EARTH_R_M * c) as f32
}
/// Cap initial (azimut 0..360°, 0° = Nord, 90° = Est) du point 1 vers le point 2.
pub fn initial_bearing_deg(lat1_deg: f64, lon1_deg: f64, lat2_deg: f64, lon2_deg: f64) -> f32 {
let lat1 = lat1_deg.to_radians();
let lat2 = lat2_deg.to_radians();
let dlon = (lon2_deg - lon1_deg).to_radians();
let y = dlon.sin() * lat2.cos();
let x = lat1.cos() * lat2.sin() - lat1.sin() * lat2.cos() * dlon.cos();
let deg = y.atan2(x).to_degrees();
((deg + 360.0) % 360.0) as f32
}
+591
View File
@@ -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<u8>,
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<u16>,
fu_buf: Vec<u8>,
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<F>(&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<F>(&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<F>(&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<Mutex<UdpVideoMetrics>>,
stop_flag: Arc<AtomicBool>,
worker: Option<thread::JoinHandle<()>>,
}
impl UdpVideoReceiver {
pub fn start<F>(
bind_ip: &str,
port: u16,
codec: VideoCodec,
transport: StreamTransport,
mut on_nal: F,
) -> Result<Self>
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<Instant> = None;
let mut last_frame_at: Option<Instant> = 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<Mutex<UdpVideoMetrics>> {
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<u8> {
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]);
}
}