mirror of
https://github.com/bleackstorm/SteamFrame-FPV-Control-Center.git
synced 2026-12-03 07:31:57 +01:00
fix(core): harden OpenXR/Vulkan lifecycle, DVR composited mode, and telemetry CRC validation
- Accept 'composited' and 'osd' in DvrMode::from_str, set filesink location via GObject property, and avoid overwriting files within the same second - Validate MAVLink v1/v2 CRC-16 and CRSF CRC-8 DVB-S2 in TelemetryReceiver, join UDP worker thread on Drop, and preserve UTF-8 char boundaries in StackStr - Ensure OpenXR swapchain image release and session.end() on error paths, reuse pre-allocated raw frame buffer in render loops, and remove forced monado.service stop - Make egui SSH/RNDIS helper scripts non-blocking and flush log file buffer only on Warn/Error
This commit is contained in:
1 parent
b8f2f00f09
commit
26279836d9
7 files changed
+210
-115
No files matched your search
@@ -30,13 +30,13 @@ impl ProjectionMode {
|
||||
/// Table de correspondance (LUT) précalculée pour corriger la distorsion en barillet
|
||||
/// de la lentille M12 140° de l'Eachine Sphere Link et la projeter sur le dôme VR.
|
||||
pub struct DomeWarpLut {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub fov_deg: f32,
|
||||
pub k1: f32,
|
||||
pub k2: f32,
|
||||
pub src_pixel_offsets: Vec<u32>,
|
||||
pub enabled: bool,
|
||||
width: u32,
|
||||
height: u32,
|
||||
fov_deg: f32,
|
||||
k1: f32,
|
||||
k2: f32,
|
||||
src_pixel_offsets: Vec<u32>,
|
||||
enabled: bool,
|
||||
}
|
||||
|
||||
impl DomeWarpLut {
|
||||
|
||||
+37
-20
@@ -51,7 +51,7 @@ pub enum DvrMode {
|
||||
|
||||
impl DvrMode {
|
||||
pub fn from_str(s: &str) -> Self {
|
||||
if s.eq_ignore_ascii_case("osd") {
|
||||
if s.eq_ignore_ascii_case("osd") || s.eq_ignore_ascii_case("composited") {
|
||||
Self::CompositedOsd
|
||||
} else {
|
||||
Self::StreamCopy
|
||||
@@ -92,9 +92,6 @@ impl DvrRecorder {
|
||||
.with_context(|| format!("Impossible de créer le répertoire DVR '{}'", dir))?;
|
||||
|
||||
let file_path = Self::generate_filepath(dir, container);
|
||||
let path_str = file_path
|
||||
.to_str()
|
||||
.ok_or_else(|| anyhow::anyhow!("Chemin DVR invalide"))?;
|
||||
|
||||
let codec_lower = codec.to_lowercase();
|
||||
let is_h264 = codec_lower == "h264";
|
||||
@@ -110,7 +107,7 @@ impl DvrRecorder {
|
||||
"appsrc name=dvr_src is-live=true format=time do-timestamp=true caps={caps} ! \
|
||||
{parser} config-interval=-1 ! \
|
||||
{muxer} ! \
|
||||
filesink location=\"{path_str}\" sync=false"
|
||||
filesink name=dvr_sink sync=false"
|
||||
);
|
||||
|
||||
log::info!(
|
||||
@@ -135,10 +132,6 @@ impl DvrRecorder {
|
||||
.with_context(|| format!("Impossible de créer le répertoire DVR '{}'", dir))?;
|
||||
|
||||
let file_path = Self::generate_filepath(dir, container);
|
||||
let path_str = file_path
|
||||
.to_str()
|
||||
.ok_or_else(|| anyhow::anyhow!("Chemin DVR invalide"))?;
|
||||
|
||||
let muxer = container.muxer_element();
|
||||
|
||||
let pipeline_str = format!(
|
||||
@@ -148,7 +141,7 @@ impl DvrRecorder {
|
||||
x264enc tune=zerolatency speed-preset=ultrafast bitrate=8000 key-int-max=60 ! \
|
||||
h264parse config-interval=-1 ! \
|
||||
{muxer} ! \
|
||||
filesink location=\"{path_str}\" sync=false"
|
||||
filesink name=dvr_sink sync=false"
|
||||
);
|
||||
|
||||
log::info!(
|
||||
@@ -175,6 +168,14 @@ impl DvrRecorder {
|
||||
.dynamic_cast::<gst_app::AppSrc>()
|
||||
.map_err(|_| anyhow::anyhow!("Impossible de convertir dvr_src en AppSrc"))?;
|
||||
|
||||
let filesink = pipeline
|
||||
.by_name("dvr_sink")
|
||||
.context("Filesink 'dvr_sink' introuvable dans le pipeline DVR")?;
|
||||
let path_str = file_path
|
||||
.to_str()
|
||||
.ok_or_else(|| anyhow::anyhow!("Chemin DVR invalide"))?;
|
||||
filesink.set_property("location", path_str);
|
||||
|
||||
pipeline
|
||||
.set_state(gst::State::Playing)
|
||||
.map_err(|e| anyhow::anyhow!("Impossible de démarrer le pipeline DVR : {}", e))?;
|
||||
@@ -191,15 +192,23 @@ impl DvrRecorder {
|
||||
}))
|
||||
}
|
||||
|
||||
/// Génère un nom de fichier horodaté `fpv_YYYYMMDD_HHMMSS.<ext>`
|
||||
/// Génère un nom de fichier horodaté `fpv_YYYYMMDD_HHMMSS.<ext>` sans écrasement
|
||||
pub fn generate_filepath(dir: &str, container: DvrContainer) -> PathBuf {
|
||||
let now = Local::now();
|
||||
let filename = format!(
|
||||
"fpv_{}.{}",
|
||||
now.format("%Y%m%d_%H%M%S"),
|
||||
container.extension()
|
||||
);
|
||||
Path::new(dir).join(filename)
|
||||
let stamp = now.format("%Y%m%d_%H%M%S");
|
||||
let ext = container.extension();
|
||||
let base_dir = Path::new(dir);
|
||||
let candidate = base_dir.join(format!("fpv_{}.{}", stamp, ext));
|
||||
if !candidate.exists() {
|
||||
return candidate;
|
||||
}
|
||||
for n in 1..1000 {
|
||||
let numbered = base_dir.join(format!("fpv_{}_{}.{}", stamp, n, ext));
|
||||
if !numbered.exists() {
|
||||
return numbered;
|
||||
}
|
||||
}
|
||||
candidate
|
||||
}
|
||||
|
||||
pub fn mode(&self) -> DvrMode {
|
||||
@@ -313,10 +322,18 @@ mod tests {
|
||||
assert!(path_mp4.to_str().unwrap().ends_with(".mp4"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_dvr_mode_parsing() {
|
||||
assert_eq!(DvrMode::from_str("composited"), DvrMode::CompositedOsd);
|
||||
assert_eq!(DvrMode::from_str("COMPOSITED"), DvrMode::CompositedOsd);
|
||||
assert_eq!(DvrMode::from_str("osd"), DvrMode::CompositedOsd);
|
||||
assert_eq!(DvrMode::from_str("copy"), DvrMode::StreamCopy);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_dvr_recording_mkv_and_stop() {
|
||||
let dir = "/tmp/test_dvr_run";
|
||||
let dvr = DvrRecorder::start_composited_osd(dir, DvrContainer::Mkv, 320, 240)
|
||||
let dir = format!("/tmp/test_dvr_run_{}", std::process::id());
|
||||
let dvr = DvrRecorder::start_composited_osd(&dir, DvrContainer::Mkv, 320, 240)
|
||||
.expect("start dvr failed");
|
||||
let fake_rgba = vec![0u8; 320 * 240 * 4];
|
||||
for _ in 0..10 {
|
||||
@@ -328,6 +345,6 @@ mod tests {
|
||||
assert!(path.exists());
|
||||
let meta = std::fs::metadata(&path).expect("file metadata");
|
||||
assert!(meta.len() > 0);
|
||||
let _ = std::fs::remove_file(&path);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
+34
-72
@@ -61,8 +61,6 @@ pub struct RuntimeMonitor {
|
||||
pub preview_width: u32,
|
||||
pub preview_height: u32,
|
||||
pub preview_frame_seq: u64,
|
||||
#[allow(dead_code)]
|
||||
pub manual_override_enabled: bool,
|
||||
pub manual_pan_deg: f32,
|
||||
pub manual_tilt_deg: f32,
|
||||
pub manual_roll_deg: f32,
|
||||
@@ -90,7 +88,6 @@ impl Default for RuntimeMonitor {
|
||||
preview_width: 0,
|
||||
preview_height: 0,
|
||||
preview_frame_seq: 0,
|
||||
manual_override_enabled: false,
|
||||
manual_pan_deg: 0.0,
|
||||
manual_tilt_deg: 0.0,
|
||||
manual_roll_deg: 0.0,
|
||||
@@ -205,27 +202,6 @@ impl FpvEngineController {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update_optical_params(&self, opt: LiveOpticalParams) {
|
||||
*self.optical_params.lock() = opt;
|
||||
}
|
||||
|
||||
pub fn update_dvr_config(&self, dir: String, container: DvrContainer, mode: DvrMode) {
|
||||
*self.dvr_config.lock() = DvrConfig { dir, container, mode };
|
||||
}
|
||||
|
||||
pub fn start_dvr(&self) {
|
||||
*self.dvr_toggle_cmd.lock() = Some(true);
|
||||
}
|
||||
|
||||
pub fn stop_dvr(&self) {
|
||||
*self.dvr_toggle_cmd.lock() = Some(false);
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub fn is_dvr_recording(&self) -> bool {
|
||||
self.monitor.lock().dvr_recording
|
||||
}
|
||||
|
||||
pub fn is_running(&self) -> bool {
|
||||
self.worker_handle
|
||||
.as_ref()
|
||||
@@ -233,38 +209,14 @@ impl FpvEngineController {
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
pub fn request_recenter(&self) {
|
||||
self.recenter_flag.store(true, Ordering::Release);
|
||||
}
|
||||
|
||||
pub fn is_telemetry_enabled(&self) -> bool {
|
||||
self.telemetry_enabled_flag.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
pub fn set_telemetry_enabled(&self, enabled: bool) {
|
||||
let prev = self.telemetry_enabled_flag.swap(enabled, Ordering::AcqRel);
|
||||
if prev != enabled {
|
||||
log::info!(
|
||||
"[Action Utilisateur] Télémétrie & OSD basculés sur : {}",
|
||||
if enabled { "ON (Activé)" } else { "OFF (Désactivé)" }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_head_tracking_enabled(&self) -> bool {
|
||||
self.head_tracking_enabled_flag.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
pub fn set_head_tracking_enabled(&self, enabled: bool) {
|
||||
let prev = self.head_tracking_enabled_flag.swap(enabled, Ordering::AcqRel);
|
||||
if prev != enabled {
|
||||
log::info!(
|
||||
"[Action Utilisateur] Suivi de Tête (RadioMaster Nomad) basculé sur : {}",
|
||||
if enabled { "ON (Activé)" } else { "OFF (Désactivé)" }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn stop(&mut self) {
|
||||
self.stop_flag.store(true, Ordering::Release);
|
||||
if let Some(handle) = self.worker_handle.take() {
|
||||
@@ -272,14 +224,6 @@ impl FpvEngineController {
|
||||
let _ = handle.join();
|
||||
}
|
||||
|
||||
// Sur Linux, s'assurer que la fenêtre de simulation de Monado ne reste pas bloquée
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let _ = std::process::Command::new("systemctl")
|
||||
.args(["--user", "stop", "monado.service"])
|
||||
.output();
|
||||
}
|
||||
|
||||
let mut mon = self.monitor.lock();
|
||||
mon.usb_video_status = SubsystemStatus::Stopped;
|
||||
mon.openxr_status = SubsystemStatus::Stopped;
|
||||
@@ -825,6 +769,8 @@ fn try_run_openxr_session(
|
||||
cfg.lens_k1,
|
||||
cfg.lens_k2,
|
||||
);
|
||||
let mut raw_frame_buf: Vec<u8> =
|
||||
Vec::with_capacity((cfg.video_width * cfg.video_height * 4) as usize);
|
||||
let mut composited_rgba = vec![0u8; (cfg.video_width * cfg.video_height * 4) as usize];
|
||||
|
||||
let session = vk_xr
|
||||
@@ -848,6 +794,7 @@ fn try_run_openxr_session(
|
||||
let mut fps_timer = Instant::now();
|
||||
let mut last_frame_id: u64 = 0;
|
||||
|
||||
let loop_res: Result<()> = (|| {
|
||||
while !stop_flag.load(Ordering::Relaxed) || session_running {
|
||||
let cur_opt = optical_params.lock().clone();
|
||||
if !dome_lut.matches_params(
|
||||
@@ -1012,11 +959,7 @@ fn try_run_openxr_session(
|
||||
}
|
||||
|
||||
if !xr_frame_state.should_render {
|
||||
vk_xr
|
||||
.frame_stream
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.end(
|
||||
frame_stream.end(
|
||||
xr_frame_state.predicted_display_time,
|
||||
xr::EnvironmentBlendMode::OPAQUE,
|
||||
&[],
|
||||
@@ -1024,7 +967,7 @@ fn try_run_openxr_session(
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut new_raw_frame: Option<Vec<u8>> = None;
|
||||
let mut has_new_raw_frame = false;
|
||||
let mut has_video_stream = false;
|
||||
|
||||
if let Some(rx) = video_rx_opt {
|
||||
@@ -1036,14 +979,16 @@ fn try_run_openxr_session(
|
||||
if vf.frame_id != last_frame_id {
|
||||
last_frame_id = vf.frame_id;
|
||||
fps_counter += 1;
|
||||
new_raw_frame = Some(vf.rgba_data.clone());
|
||||
raw_frame_buf.clear();
|
||||
raw_frame_buf.extend_from_slice(&vf.rgba_data);
|
||||
has_new_raw_frame = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(ref raw) = new_raw_frame {
|
||||
dome_lut.apply(&raw, &mut composited_rgba);
|
||||
if has_new_raw_frame {
|
||||
dome_lut.apply(&raw_frame_buf, &mut composited_rgba);
|
||||
} else if !has_video_stream {
|
||||
standby_tick = standby_tick.wrapping_add(1);
|
||||
UsbVideoReceiver::render_standby_pattern(
|
||||
@@ -1093,7 +1038,7 @@ fn try_run_openxr_session(
|
||||
}
|
||||
|
||||
if let Some(ref dvr) = *active_dvr {
|
||||
if dvr.mode() == DvrMode::CompositedOsd && new_raw_frame.is_some() {
|
||||
if dvr.mode() == DvrMode::CompositedOsd && has_new_raw_frame {
|
||||
dvr.push_slice(&composited_rgba);
|
||||
}
|
||||
}
|
||||
@@ -1112,6 +1057,17 @@ fn try_run_openxr_session(
|
||||
fps_counter = 0;
|
||||
fps_timer = Instant::now();
|
||||
}
|
||||
if current_pose.last_send_ok {
|
||||
mon.nomad_wifi_status = SubsystemStatus::Running(format!(
|
||||
"ON - Cible {}:{} ({} paquets)",
|
||||
cfg.nomad_ip, cfg.nomad_port, current_pose.packets_sent
|
||||
));
|
||||
} else if current_pose.send_errors > 0 {
|
||||
mon.nomad_wifi_status = SubsystemStatus::Error(format!(
|
||||
"Erreur d'envoi UDP vers {}:{} ({} échecs)",
|
||||
cfg.nomad_ip, cfg.nomad_port, current_pose.send_errors
|
||||
));
|
||||
}
|
||||
mon.video_frames_total = last_frame_id;
|
||||
mon.latest_head_pose = current_pose;
|
||||
mon.latest_telemetry = telem_snapshot;
|
||||
@@ -1206,6 +1162,8 @@ fn try_run_openxr_session(
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
|
||||
if session_running {
|
||||
log::warn!("[OpenXR] Sortie de boucle avec session encore active, appel de session.end()...");
|
||||
@@ -1219,7 +1177,7 @@ fn try_run_openxr_session(
|
||||
drop(local_space);
|
||||
drop(vk_xr);
|
||||
|
||||
Ok(())
|
||||
loop_res
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
@@ -1245,6 +1203,8 @@ fn run_desktop_fallback_loop(
|
||||
cfg.lens_k1,
|
||||
cfg.lens_k2,
|
||||
);
|
||||
let mut raw_frame_buf: Vec<u8> =
|
||||
Vec::with_capacity((cfg.video_width * cfg.video_height * 4) as usize);
|
||||
let mut composited_rgba = vec![0u8; (cfg.video_width * cfg.video_height * 4) as usize];
|
||||
let mut standby_tick: u32 = 0;
|
||||
let mut last_frame_id: u64 = 0;
|
||||
@@ -1313,7 +1273,7 @@ fn run_desktop_fallback_loop(
|
||||
}
|
||||
}
|
||||
|
||||
let mut new_raw_frame: Option<Vec<u8>> = None;
|
||||
let mut has_new_raw_frame = false;
|
||||
let mut has_video_stream = false;
|
||||
|
||||
if let Some(rx) = video_rx_opt {
|
||||
@@ -1325,14 +1285,16 @@ fn run_desktop_fallback_loop(
|
||||
if vf.frame_id != last_frame_id {
|
||||
last_frame_id = vf.frame_id;
|
||||
fps_counter += 1;
|
||||
new_raw_frame = Some(vf.rgba_data.clone());
|
||||
raw_frame_buf.clear();
|
||||
raw_frame_buf.extend_from_slice(&vf.rgba_data);
|
||||
has_new_raw_frame = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(ref raw) = new_raw_frame {
|
||||
dome_lut.apply(&raw, &mut composited_rgba);
|
||||
if has_new_raw_frame {
|
||||
dome_lut.apply(&raw_frame_buf, &mut composited_rgba);
|
||||
} else if !has_video_stream {
|
||||
standby_tick = standby_tick.wrapping_add(1);
|
||||
UsbVideoReceiver::render_standby_pattern(
|
||||
@@ -1382,7 +1344,7 @@ fn run_desktop_fallback_loop(
|
||||
}
|
||||
|
||||
if let Some(ref dvr) = *active_dvr {
|
||||
if dvr.mode() == DvrMode::CompositedOsd && new_raw_frame.is_some() {
|
||||
if dvr.mode() == DvrMode::CompositedOsd && has_new_raw_frame {
|
||||
dvr.push_slice(&composited_rgba);
|
||||
}
|
||||
}
|
||||
|
||||
+17
-1
@@ -149,6 +149,7 @@ impl SteamFrameGuiApp {
|
||||
|
||||
fn run_usb_rndis_setup_script(&self) {
|
||||
log::info!("[Action Utilisateur] Exécution du script de configuration USB RNDIS (scripts/setup_usb_rndis.sh)...");
|
||||
std::thread::spawn(move || {
|
||||
match Command::new("bash")
|
||||
.arg("scripts/setup_usb_rndis.sh")
|
||||
.output()
|
||||
@@ -176,12 +177,13 @@ impl SteamFrameGuiApp {
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Configure à distance la carte Radxa Zero 3W (OpenIPC `runcam_wifilink_sdcard.img`) via SSH sur le lien USB OTG
|
||||
fn configure_radxa_vrx_over_usb(&self) {
|
||||
let ch = self.cfg.wifi_channel;
|
||||
let ip = &self.cfg.radxa_vrx_ip;
|
||||
let ip = self.cfg.radxa_vrx_ip.clone();
|
||||
let port = self.cfg.video_udp_port;
|
||||
log::info!(
|
||||
"[Radxa Zero 3W] Envoi de la configuration OpenIPC (Canal 5.8GHz={} / Redirection RTP -> 192.168.1.10:{}) vers root@{}...",
|
||||
@@ -196,12 +198,14 @@ impl SteamFrameGuiApp {
|
||||
echo 'Radxa Zero 3W 8812EU configurée sur le canal {ch}'"
|
||||
);
|
||||
|
||||
std::thread::spawn(move || {
|
||||
match Command::new("ssh")
|
||||
.args([
|
||||
"-o",
|
||||
"ConnectTimeout=2",
|
||||
"-o",
|
||||
"StrictHostKeyChecking=no",
|
||||
"--",
|
||||
&format!("root@{}", ip),
|
||||
&remote_cmd,
|
||||
])
|
||||
@@ -225,6 +229,7 @@ impl SteamFrameGuiApp {
|
||||
log::error!("[Radxa Zero 3W] Erreur exécution SSH : {}", e);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn test_nomad_udp_packet(&self) {
|
||||
@@ -734,6 +739,17 @@ impl eframe::App for SteamFrameGuiApp {
|
||||
egui::ComboBox::from_id_salt("res_profile_combo")
|
||||
.selected_text(&self.cfg.vrx_video_profile)
|
||||
.show_ui(ui, |ui| {
|
||||
if ui
|
||||
.selectable_value(
|
||||
&mut self.cfg.vrx_video_profile,
|
||||
"720p60".to_string(),
|
||||
"720P @ 60 FPS (Défaut)",
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
self.cfg.video_width = 1280;
|
||||
self.cfg.video_height = 720;
|
||||
}
|
||||
if ui
|
||||
.selectable_value(
|
||||
&mut self.cfg.vrx_video_profile,
|
||||
|
||||
@@ -116,9 +116,11 @@ impl Log for GuiLogger {
|
||||
"[{}] [{:<5}] ({}) {}",
|
||||
entry.timestamp, entry.level, entry.target, entry.message
|
||||
);
|
||||
if record.level() <= Level::Warn {
|
||||
let _ = writer.flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Ajout dans le tampon de l'interface graphique
|
||||
let mut lock = self.buffer.lock();
|
||||
|
||||
+104
-8
@@ -28,10 +28,12 @@ impl<const N: usize> StackStr<N> {
|
||||
impl<const N: usize> std::fmt::Write for StackStr<N> {
|
||||
#[inline]
|
||||
fn write_str(&mut self, s: &str) -> std::fmt::Result {
|
||||
let bytes = s.as_bytes();
|
||||
let avail = N.saturating_sub(self.len);
|
||||
let to_copy = bytes.len().min(avail);
|
||||
self.buf[self.len..self.len + to_copy].copy_from_slice(&bytes[..to_copy]);
|
||||
let mut to_copy = s.len().min(avail);
|
||||
while to_copy > 0 && !s.is_char_boundary(to_copy) {
|
||||
to_copy -= 1;
|
||||
}
|
||||
self.buf[self.len..self.len + to_copy].copy_from_slice(&s.as_bytes()[..to_copy]);
|
||||
self.len += to_copy;
|
||||
Ok(())
|
||||
}
|
||||
@@ -81,6 +83,7 @@ impl Default for TelemetryState {
|
||||
pub struct TelemetryReceiver {
|
||||
state: Arc<Mutex<TelemetryState>>,
|
||||
stop_flag: Arc<AtomicBool>,
|
||||
worker: Option<thread::JoinHandle<()>>,
|
||||
}
|
||||
|
||||
impl TelemetryReceiver {
|
||||
@@ -105,11 +108,11 @@ impl TelemetryReceiver {
|
||||
let stop_flag = Arc::new(AtomicBool::new(false));
|
||||
let stop_clone = Arc::clone(&stop_flag);
|
||||
|
||||
thread::Builder::new()
|
||||
let worker = thread::Builder::new()
|
||||
.name("telemetry-udp-rx".into())
|
||||
.spawn(move || {
|
||||
let mut buf = [0u8; 1024];
|
||||
while !stop_clone.load(Ordering::Relaxed) {
|
||||
while !stop_clone.load(Ordering::Acquire) {
|
||||
if let Ok((len, _src)) = socket.recv_from(&mut buf) {
|
||||
Self::parse_datagram(&buf[..len], &state_clone);
|
||||
}
|
||||
@@ -117,13 +120,28 @@ impl TelemetryReceiver {
|
||||
log::info!("[Télémétrie OSD] Thread d'écoute UDP arrêté.");
|
||||
})?;
|
||||
|
||||
Ok(Self { state, stop_flag })
|
||||
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() {
|
||||
@@ -133,12 +151,24 @@ impl TelemetryReceiver {
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
0xFD if i + 12 <= data.len() => {
|
||||
let payload_len = data[i + 1] as usize;
|
||||
let incompat_flags = data[i + 2];
|
||||
@@ -148,22 +178,40 @@ impl TelemetryReceiver {
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
0xC8 | 0xEA | 0xEE if i + 4 <= data.len() => {
|
||||
let frame_len = data[i + 1] as usize;
|
||||
if frame_len >= 2 && frame_len <= 62 && 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..i + 2 + frame_len - 1];
|
||||
let payload = &data[i + 3..crc_idx];
|
||||
Self::handle_crsf_payload(frame_type, payload, state);
|
||||
i += 2 + frame_len;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
i += 1;
|
||||
@@ -247,7 +295,10 @@ impl TelemetryReceiver {
|
||||
|
||||
impl Drop for TelemetryReceiver {
|
||||
fn drop(&mut self) {
|
||||
self.stop_flag.store(true, Ordering::Relaxed);
|
||||
self.stop_flag.store(true, Ordering::Release);
|
||||
if let Some(handle) = self.worker.take() {
|
||||
let _ = handle.join();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -667,3 +718,48 @@ impl OsdOverlay {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_stack_str_utf8_boundary_truncation() {
|
||||
let mut s = StackStr::<3>::new();
|
||||
let _ = write!(s, "12°");
|
||||
assert_eq!(s.as_str(), "12");
|
||||
|
||||
let mut s4 = StackStr::<4>::new();
|
||||
let _ = write!(s4, "12°");
|
||||
assert_eq!(s4.as_str(), "12°");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_datagram_crsf_crc_validation() {
|
||||
let state = Arc::new(Mutex::new(TelemetryState::default()));
|
||||
|
||||
// Trame CRSF Battery Sensor (0x08) : 16.8V (168 = 0x00A8), 12.5A (125 = 0x007D), remaining = 75%
|
||||
let mut frame = [0u8; 12];
|
||||
frame[0] = 0xC8;
|
||||
frame[1] = 10; // type(1) + payload(8) + crc(1)
|
||||
frame[2] = 0x08;
|
||||
frame[3..5].copy_from_slice(&168u16.to_be_bytes());
|
||||
frame[5..7].copy_from_slice(&125u16.to_be_bytes());
|
||||
frame[10] = 75;
|
||||
frame[11] = crate::nomad_elrs::NomadHeadTracker::crc8_dvb_s2(&frame[2..11]);
|
||||
|
||||
// Trame au CRC corrompu : doit être ignorée
|
||||
let mut bad_frame = frame;
|
||||
bad_frame[11] ^= 0xFF;
|
||||
TelemetryReceiver::parse_datagram(&bad_frame, &state);
|
||||
assert_eq!(state.lock().packets_received, 0);
|
||||
|
||||
// Trame valide : doit être acceptée et décodée
|
||||
TelemetryReceiver::parse_datagram(&frame, &state);
|
||||
let st = state.lock();
|
||||
assert_eq!(st.packets_received, 1);
|
||||
assert!((st.battery_voltage_v - 16.8).abs() < 0.01);
|
||||
assert!((st.battery_current_a - 12.5).abs() < 0.01);
|
||||
assert_eq!(st.battery_remaining_pct, 75);
|
||||
}
|
||||
}
|
||||
+9
-7
@@ -264,13 +264,11 @@ impl VulkanXrContext {
|
||||
swapchain.wait_image(xr::Duration::INFINITE)?;
|
||||
|
||||
let copy_len = rgba_bytes.len().min(self.staging_size);
|
||||
unsafe {
|
||||
std::ptr::copy_nonoverlapping(rgba_bytes.as_ptr(), self.staging_mapped_ptr, copy_len);
|
||||
}
|
||||
|
||||
let target_image = self.swapchain_images[img_idx as usize];
|
||||
|
||||
unsafe {
|
||||
let vk_res: Result<()> = (|| unsafe {
|
||||
std::ptr::copy_nonoverlapping(rgba_bytes.as_ptr(), self.staging_mapped_ptr, copy_len);
|
||||
|
||||
self.vk_device
|
||||
.reset_command_buffer(self.command_buffer, vk::CommandBufferResetFlags::empty())?;
|
||||
|
||||
@@ -359,9 +357,13 @@ impl VulkanXrContext {
|
||||
.queue_submit(self.queue, &submit_info, self.upload_fence)?;
|
||||
self.vk_device
|
||||
.wait_for_fences(&[self.upload_fence], true, u64::MAX)?;
|
||||
}
|
||||
|
||||
swapchain.release_image()?;
|
||||
Ok(())
|
||||
})();
|
||||
|
||||
let release_res = swapchain.release_image();
|
||||
vk_res?;
|
||||
release_res?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user