diff --git a/scripts/setup_radxa_usb_gadget.sh b/scripts/setup_radxa_usb_gadget.sh index d14ebcf..5bdb6ff 100755 --- a/scripts/setup_radxa_usb_gadget.sh +++ b/scripts/setup_radxa_usb_gadget.sh @@ -19,14 +19,20 @@ if ! grep -q "rk3568-dwc3-peripheral.dtbo" "${EXTLINUX}"; then sed -i '/fdtdir/a \ fdtoverlays /boot/dtbo/rk3568-dwc3-peripheral.dtbo' "${EXTLINUX}" fi +# 1b. Forcer l'activation de la sortie HDMI en mode headless (sans écran physique) +echo "[1b/5] Forçage de la sortie HDMI virtuelle (headless) dans extlinux.conf..." +if ! grep -q "video=HDMI-A-1" "${EXTLINUX}"; then + sed -i '/append/ s/$/ video=HDMI-A-1:1920x1080@60e/' "${EXTLINUX}" +fi + # 2. Charger le module g_cdc au boot -echo "[2/4] Ajout du module g_cdc dans /etc/modules..." +echo "[2/5] Ajout du module g_cdc dans /etc/modules..." if ! grep -q "g_cdc" "${ROOTFS}/etc/modules"; then echo "g_cdc" >> "${ROOTFS}/etc/modules" fi # 3. Configurer l'IP statique 192.168.1.1 sur usb0 -echo "[3/4] Configuration réseau de usb0 (192.168.1.1/24)..." +echo "[3/5] Configuration réseau de usb0 (192.168.1.1/24)..." cat << 'EOF' > "${ROOTFS}/etc/network/interfaces.d/usb0" auto usb0 allow-hotplug usb0 @@ -53,10 +59,12 @@ mkdir -p "${ROOTFS}/etc/systemd/system/multi-user.target.wants" ln -sf /etc/systemd/system/usb0-setup.service "${ROOTFS}/etc/systemd/system/multi-user.target.wants/usb0-setup.service" # 4. Ajuster le port vidéo dans controller_settings.cfg vers 5600 -echo "[4/4] Configuration du port vidéo Ruby vers 5600..." +echo "[4/5] Configuration du port vidéo Ruby vers 5600..." if [ -f "${ROOTFS}/home/radxa/ruby/config/controller_settings.cfg" ]; then sed -i 's/video_usb: 1 [0-9]\+ 1024/video_usb: 1 5600 1024/g' "${ROOTFS}/home/radxa/ruby/config/controller_settings.cfg" fi +echo "[5/5] Synchronisation des fichiers..." + sync echo "[+] Configuration terminée avec succès !" diff --git a/src/engine.rs b/src/engine.rs index 1ca6dcf..4a099e0 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -285,7 +285,7 @@ fn run_engine_worker( ); // 1. Démarrage Vidéo USB (Mode OTG/RNDIS ou Mode Mini-HDMI UVC) - let video_rx_opt = match UsbVideoReceiver::start( + let mut video_rx_opt = match UsbVideoReceiver::start( &cfg.usb_video_mode, &cfg.uvc_device, &cfg.usb_bind_ip, @@ -343,28 +343,30 @@ fn run_engine_worker( &recenter_flag, &telem_enabled_flag, &ht_enabled_flag, - video_rx_opt.as_ref(), + &mut video_rx_opt, &mut telem_rx_opt, &mut head_tracker_opt, ) { - log::warn!( - "[OpenXR] Session VR indisponible ({}). Bascule automatique en mode Monitoring Bureau / Simulation.", - xr_err - ); - monitor.lock().openxr_status = - SubsystemStatus::Warning(format!("Mode Bureau (OpenXR inactif : {})", xr_err)); + if !stop_flag.load(Ordering::Relaxed) { + log::warn!( + "[OpenXR] Session VR indisponible ({}). Bascule automatique en mode Monitoring Bureau / Simulation.", + xr_err + ); + monitor.lock().openxr_status = + SubsystemStatus::Warning(format!("Mode Bureau (OpenXR inactif : {})", xr_err)); - run_desktop_fallback_loop( - &cfg, - &monitor, - &stop_flag, - &recenter_flag, - &telem_enabled_flag, - &ht_enabled_flag, - video_rx_opt.as_ref(), - &mut telem_rx_opt, - &mut head_tracker_opt, - ); + run_desktop_fallback_loop( + &cfg, + &monitor, + &stop_flag, + &recenter_flag, + &telem_enabled_flag, + &ht_enabled_flag, + &mut video_rx_opt, + &mut telem_rx_opt, + &mut head_tracker_opt, + ); + } } log::info!("[Moteur FPV] Tous les sous-systèmes ont été arrêtés."); @@ -378,7 +380,7 @@ fn try_run_openxr_session( recenter_flag: &Arc, telem_enabled_flag: &Arc, ht_enabled_flag: &Arc, - video_rx: Option<&UsbVideoReceiver>, + video_rx_opt: &mut Option, telem_rx_opt: &mut Option, head_tracker_opt: &mut Option, ) -> Result<()> { @@ -485,6 +487,7 @@ fn try_run_openxr_session( let mut fps_counter: u32 = 0; let mut fps_timer = Instant::now(); let mut last_frame_id: u64 = 0; + let mut last_rx_retry = Instant::now(); while !stop_flag.load(Ordering::Relaxed) { let telem_on = telem_enabled_flag.load(Ordering::Relaxed); @@ -564,15 +567,17 @@ fn try_run_openxr_session( let mut new_raw_frame: Option> = None; let mut has_video_stream = false; - if let Some(rx) = video_rx { + if let Some(rx) = video_rx_opt.as_mut() { let lock = rx.latest_frame(); let guard = lock.lock(); if let Some(ref vf) = *guard { - has_video_stream = true; - if vf.frame_id != last_frame_id { - last_frame_id = vf.frame_id; - fps_counter += 1; - new_raw_frame = Some(vf.rgba_data.clone()); + if vf.received_at.elapsed() < Duration::from_millis(600) { + has_video_stream = true; + if vf.frame_id != last_frame_id { + last_frame_id = vf.frame_id; + fps_counter += 1; + new_raw_frame = Some(vf.rgba_data.clone()); + } } } } @@ -587,6 +592,48 @@ fn try_run_openxr_session( standby_tick, &mut composited_rgba, ); + OsdOverlay::draw_text( + &mut composited_rgba, + cfg.video_width, + cfg.video_height, + (cfg.video_width as i32 / 2) - 230, + (cfg.video_height as i32 / 2) + 70, + "SIGNAL VRX PERDU - RECHERCHE FLUX UDP 5600...", + (cfg.video_height / 360).max(2), + [255, 180, 40, 255], + ); + + // Réarmement / reconnexion automatique du pipeline GStreamer toutes les 2 secondes + if last_rx_retry.elapsed() > Duration::from_millis(2000) { + last_rx_retry = Instant::now(); + if let Some(rx) = video_rx_opt.as_mut() { + log::info!("[USB Vidéo] Flux vidéo inactif, réarmement automatique du pipeline..."); + if rx.restart().is_err() || rx.is_broken() { + log::warn!("[USB Vidéo] Échec redémarrage doux, reconstruction complète du pipeline..."); + *video_rx_opt = UsbVideoReceiver::start( + &cfg.usb_video_mode, + &cfg.uvc_device, + &cfg.usb_bind_ip, + cfg.video_udp_port, + &cfg.codec, + &cfg.stream_transport, + cfg.video_width, + cfg.video_height, + ).ok(); + } + } else { + *video_rx_opt = UsbVideoReceiver::start( + &cfg.usb_video_mode, + &cfg.uvc_device, + &cfg.usb_bind_ip, + cfg.video_udp_port, + &cfg.codec, + &cfg.stream_transport, + cfg.video_width, + cfg.video_height, + ).ok(); + } + } } let telem_snapshot = telem_rx_opt @@ -614,7 +661,11 @@ fn try_run_openxr_session( if standby_tick % 2 == 0 || last_frame_id % 2 == 0 { let mut mon = monitor.lock(); if fps_timer.elapsed() >= Duration::from_secs(1) { - mon.video_fps = fps_counter as f32 / fps_timer.elapsed().as_secs_f32(); + if has_video_stream { + mon.video_fps = fps_counter as f32 / fps_timer.elapsed().as_secs_f32(); + } else { + mon.video_fps = 0.0; + } fps_counter = 0; fps_timer = Instant::now(); } @@ -712,7 +763,7 @@ fn run_desktop_fallback_loop( recenter_flag: &Arc, telem_enabled_flag: &Arc, ht_enabled_flag: &Arc, - video_rx: Option<&UsbVideoReceiver>, + video_rx_opt: &mut Option, telem_rx_opt: &mut Option, head_tracker_opt: &mut Option, ) { @@ -729,6 +780,7 @@ fn run_desktop_fallback_loop( let mut last_frame_id: u64 = 0; let mut fps_counter: u32 = 0; let mut fps_timer = Instant::now(); + let mut last_rx_retry = Instant::now(); while !stop_flag.load(Ordering::Relaxed) { let loop_start = Instant::now(); @@ -768,15 +820,17 @@ fn run_desktop_fallback_loop( let mut new_raw_frame: Option> = None; let mut has_video_stream = false; - if let Some(rx) = video_rx { + if let Some(rx) = video_rx_opt.as_mut() { let lock = rx.latest_frame(); let guard = lock.lock(); if let Some(ref vf) = *guard { - has_video_stream = true; - if vf.frame_id != last_frame_id { - last_frame_id = vf.frame_id; - fps_counter += 1; - new_raw_frame = Some(vf.rgba_data.clone()); + if vf.received_at.elapsed() < Duration::from_millis(600) { + has_video_stream = true; + if vf.frame_id != last_frame_id { + last_frame_id = vf.frame_id; + fps_counter += 1; + new_raw_frame = Some(vf.rgba_data.clone()); + } } } } @@ -791,6 +845,48 @@ fn run_desktop_fallback_loop( standby_tick, &mut composited_rgba, ); + OsdOverlay::draw_text( + &mut composited_rgba, + cfg.video_width, + cfg.video_height, + (cfg.video_width as i32 / 2) - 230, + (cfg.video_height as i32 / 2) + 70, + "SIGNAL VRX PERDU - RECHERCHE FLUX UDP 5600...", + (cfg.video_height / 360).max(2), + [255, 180, 40, 255], + ); + + // Réarmement / reconnexion automatique du pipeline GStreamer toutes les 2 secondes + if last_rx_retry.elapsed() > Duration::from_millis(2000) { + last_rx_retry = Instant::now(); + if let Some(rx) = video_rx_opt.as_mut() { + log::info!("[USB Vidéo] Flux vidéo inactif, réarmement automatique du pipeline..."); + if rx.restart().is_err() || rx.is_broken() { + log::warn!("[USB Vidéo] Échec redémarrage doux, reconstruction complète du pipeline..."); + *video_rx_opt = UsbVideoReceiver::start( + &cfg.usb_video_mode, + &cfg.uvc_device, + &cfg.usb_bind_ip, + cfg.video_udp_port, + &cfg.codec, + &cfg.stream_transport, + cfg.video_width, + cfg.video_height, + ).ok(); + } + } else { + *video_rx_opt = UsbVideoReceiver::start( + &cfg.usb_video_mode, + &cfg.uvc_device, + &cfg.usb_bind_ip, + cfg.video_udp_port, + &cfg.codec, + &cfg.stream_transport, + cfg.video_width, + cfg.video_height, + ).ok(); + } + } } let telem_snapshot = telem_rx_opt @@ -816,7 +912,11 @@ fn run_desktop_fallback_loop( { let mut mon = monitor.lock(); if fps_timer.elapsed() >= Duration::from_secs(1) { - mon.video_fps = fps_counter as f32 / fps_timer.elapsed().as_secs_f32(); + if has_video_stream { + mon.video_fps = fps_counter as f32 / fps_timer.elapsed().as_secs_f32(); + } else { + mon.video_fps = 0.0; + } fps_counter = 0; fps_timer = Instant::now(); } diff --git a/src/gui_gpui.rs b/src/gui_gpui.rs index 8e3ff59..c2f8437 100644 --- a/src/gui_gpui.rs +++ b/src/gui_gpui.rs @@ -1,5 +1,5 @@ use crate::config::AppConfig; -use crate::engine::{FpvEngineController, SubsystemStatus}; +use crate::engine::{FpvEngineController, RuntimeMonitor, SubsystemStatus}; use crate::logger::{LogBuffer, LogEntry, LogFilter}; use crate::nomad_elrs::{HeadPoseSample, NomadHeadTracker}; use crate::telemetry_osd::TelemetryState; @@ -12,16 +12,18 @@ use image::{Frame, RgbaImage}; use parking_lot::Mutex; use smallvec::smallvec; use std::process::Command; +use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; use std::time::Duration; // ========================================================================= // Palette Cyberpunk / Aeronautic FPV // ========================================================================= -const COLOR_BG_DARK: u32 = 0x090b10; -const COLOR_SURFACE_CARD: u32 = 0x11151f; -const COLOR_SURFACE_ELEVATED: u32 = 0x181e2b; -const COLOR_BORDER_SUBTLE: u32 = 0x1f293d; +const COLOR_BG_DARK: u32 = 0x07090e; +const COLOR_SURFACE_CARD: u32 = 0x0f131c; +const COLOR_SURFACE_ELEVATED: u32 = 0x161c28; +const COLOR_BORDER_SUBTLE: u32 = 0x1d2636; +const COLOR_BORDER_ACTIVE: u32 = 0x00e5ff; const COLOR_CYAN: u32 = 0x00e5ff; const COLOR_GREEN: u32 = 0x10b981; @@ -30,14 +32,26 @@ const COLOR_RED: u32 = 0xef4444; const COLOR_TEXT_MUTED: u32 = 0x64748b; const COLOR_TEXT_MAIN: u32 = 0xe2e8f0; +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ActiveTab { + Cockpit, + Settings, + Telemetry, + Logs, +} + pub struct SteamFrameGpuiApp { cfg: AppConfig, - engine: FpvEngineController, + engine: Arc>, + engine_monitor: Arc>, log_buffer: Arc>, + log_revision: Arc, log_filter: LogFilter, current_render_image: Option>, images_to_drop: Vec>, last_frame_seq: u64, + active_tab: ActiveTab, + show_hud_overlay: bool, // Snapshots pour l'affichage réactif usb_status: SubsystemStatus, xr_status: SubsystemStatus, @@ -55,18 +69,25 @@ pub struct SteamFrameGpuiApp { impl SteamFrameGpuiApp { pub fn new(cfg: AppConfig, log_buffer: Arc>) -> Self { + let log_revision = log_buffer.lock().revision.clone(); let mut engine = FpvEngineController::new(cfg.telemetry_enabled, cfg.head_tracking_enabled); engine.start(cfg.clone()); + let engine_monitor = Arc::clone(&engine.monitor); + let engine = Arc::new(Mutex::new(engine)); Self { cfg, engine, + engine_monitor, log_buffer, + log_revision, log_filter: LogFilter::All, current_render_image: None, images_to_drop: Vec::new(), last_frame_seq: 0, + active_tab: ActiveTab::Cockpit, + show_hud_overlay: true, usb_status: SubsystemStatus::Starting, xr_status: SubsystemStatus::Starting, nomad_status: SubsystemStatus::Disabled, @@ -82,25 +103,62 @@ impl SteamFrameGpuiApp { } } - /// Synchronise l'état IHM avec le moteur FPV en tâche de fond - fn sync_from_engine(&mut self, window: &mut Window) { - let mon = self.engine.monitor.lock(); + /// Synchronise l'état IHM avec le moteur FPV en minimisant au maximum la contention des verrous + fn sync_from_engine(&mut self, window: &mut Window) -> bool { + let mut changed = false; - // 1. Mise à jour de la texture vidéo si une nouvelle trame est arrivée - if mon.preview_frame_seq != self.last_frame_seq - && !mon.preview_rgba.is_empty() - && mon.preview_width > 0 - && mon.preview_height > 0 - { - if let Some(mut img_buf) = RgbaImage::from_raw( - mon.preview_width, - mon.preview_height, - mon.preview_rgba.clone(), - ) { - // Conversion RGBA -> BGRA requise par l'atlas polychrome GPUI / Vulkan - for pixel in img_buf.chunks_exact_mut(4) { - pixel.swap(0, 2); - } + // 1. Snapshot rapide avec maintien minimal du verrou monitor + let (preview_frame_seq, new_frame_data) = { + let mon = self.engine_monitor.lock(); + + if self.usb_status != mon.usb_video_status { + self.usb_status = mon.usb_video_status.clone(); + changed = true; + } + if self.xr_status != mon.openxr_status { + self.xr_status = mon.openxr_status.clone(); + changed = true; + } + if self.nomad_status != mon.nomad_wifi_status { + self.nomad_status = mon.nomad_wifi_status.clone(); + changed = true; + } + if self.telem_status != mon.telemetry_status { + self.telem_status = mon.telemetry_status.clone(); + changed = true; + } + if (self.video_fps - mon.video_fps).abs() > 0.1 { + self.video_fps = mon.video_fps; + changed = true; + } + if self.video_frames_total != mon.video_frames_total { + self.video_frames_total = mon.video_frames_total; + changed = true; + } + self.latest_pose = mon.latest_head_pose; + self.latest_telem = mon.latest_telemetry.clone(); + + // Ne cloner et décoder la trame QUE si l'onglet Cockpit est actif ! + let frame_data: Option<(u32, u32, Vec)> = if self.active_tab == ActiveTab::Cockpit + && mon.preview_frame_seq != self.last_frame_seq + && !mon.preview_rgba.is_empty() + && mon.preview_width > 0 + && mon.preview_height > 0 + { + Some((mon.preview_width, mon.preview_height, mon.preview_rgba.clone())) + } else { + None + }; + + (mon.preview_frame_seq, frame_data) + }; // Verrou `engine_monitor` immédiatement libéré ! + + // 2. Conversion BGRA et allocation GPU hors du verrou monitor + if let Some((w, h, mut raw_buf)) = new_frame_data { + for pixel in raw_buf.chunks_exact_mut(4) { + pixel.swap(0, 2); + } + if let Some(img_buf) = RgbaImage::from_raw(w, h, raw_buf) { let frame = Frame::new(img_buf); let new_render_image = Arc::new(RenderImage::new(smallvec![frame])); @@ -108,11 +166,9 @@ impl SteamFrameGpuiApp { self.images_to_drop.push(old); } self.current_render_image = Some(new_render_image); - self.last_frame_seq = mon.preview_frame_seq; + self.last_frame_seq = preview_frame_seq; + changed = true; - // Nettoyage de l'atlas texture GPU pour empêcher l'accumulation de VRAM. - // On conserve les 2 dernières trames pour garantir que le GPU a fini - // de les projeter à l'écran avant destruction de la texture. while self.images_to_drop.len() > 2 { let old_img = self.images_to_drop.remove(0); let _ = window.drop_image(old_img); @@ -120,35 +176,48 @@ impl SteamFrameGpuiApp { } } - self.usb_status = mon.usb_video_status.clone(); - self.xr_status = mon.openxr_status.clone(); - self.nomad_status = mon.nomad_wifi_status.clone(); - self.telem_status = mon.telemetry_status.clone(); - self.video_fps = mon.video_fps; - self.video_frames_total = mon.video_frames_total; - self.latest_pose = mon.latest_head_pose; - self.latest_telem = mon.latest_telemetry.clone(); - - // 2. Synchronisation sélective des logs (uniquement sur nouvelle révision) - let lb = self.log_buffer.lock(); - if lb.revision != self.last_log_revision { - self.last_log_revision = lb.revision; + // 3. Synchronisation lock-free des logs via AtomicU64 + let current_log_rev = self.log_revision.load(Ordering::Acquire); + if current_log_rev != self.last_log_revision { + let lb = self.log_buffer.lock(); + self.last_log_revision = current_log_rev; self.log_err_count = lb.error_count; self.log_warn_count = lb.warn_count; - self.log_entries = lb.entries.iter().rev().take(50).cloned().collect(); + self.log_entries = lb.entries.iter().rev().take(60).cloned().collect(); + changed = true; } + + changed } fn run_usb_rndis_setup(&self) { log::info!("[USB RNDIS] Exécution du script de configuration réseau..."); - let script_path = concat!(env!("CARGO_MANIFEST_DIR"), "/scripts/setup_usb_rndis.sh").to_string(); + let script_path = std::env::current_exe() + .ok() + .and_then(|p| p.parent().map(|d| d.join("scripts/setup_usb_rndis.sh"))) + .filter(|p| p.exists()) + .unwrap_or_else(|| { + let candidate = std::path::PathBuf::from("scripts/setup_usb_rndis.sh"); + if candidate.exists() { + candidate + } else { + std::path::PathBuf::from(concat!( + env!("CARGO_MANIFEST_DIR"), + "/scripts/setup_usb_rndis.sh" + )) + } + }); std::thread::spawn(move || { match Command::new("bash").arg(&script_path).output() { Ok(out) => { let stdout = String::from_utf8_lossy(&out.stdout); - log::info!("[USB RNDIS] Résultat (exit={}) :\n{}", out.status, stdout.trim()); + log::info!( + "[USB RNDIS] Résultat (exit={}) :\n{}", + out.status, + stdout.trim() + ); } - Err(e) => log::error!("[USB RNDIS] Échec d'exécution du script : {}", e), + Err(e) => log::error!("[USB RNDIS] Échec d'exécution du script {:?} : {}", script_path, e), } }); } @@ -172,6 +241,7 @@ impl SteamFrameGpuiApp { "ConnectTimeout=2", "-o", "StrictHostKeyChecking=no", + "--", &format!("root@{}", ip), &remote_cmd, ]) @@ -222,29 +292,29 @@ impl Render for SteamFrameGpuiApp { .text_color(rgb(COLOR_TEXT_MAIN)) .p_3() .gap_3() - // 1. HEADER COCKPIT BAR + .overflow_hidden() + // 1. HEADER COCKPIT BAR AVEC MENU D'ONGLETS .child(self.render_header(cx)) - // 2. MAIN LAYOUT: SIDEBAR + CENTRAL COCKPIT + // 2. VUE ACTIVE (Cockpit plein format, Réglages, Télémétrie, Logs) .child( div() .flex() - .flex_row() + .flex_col() .flex_1() - .gap_3() .overflow_hidden() - // Sidebar (340px) - .child(self.render_sidebar(cx)) - // Dashboard central (Aperçu Vidéo + HUD) - .child(self.render_cockpit()), + .child(match self.active_tab { + ActiveTab::Cockpit => self.render_cockpit_view(cx).into_any_element(), + ActiveTab::Settings => self.render_settings_view(cx).into_any_element(), + ActiveTab::Telemetry => self.render_telemetry_view().into_any_element(), + ActiveTab::Logs => self.render_logs_view(cx).into_any_element(), + }), ) - // 3. LOG CONSOLE (DRAWER INFERIEUR) - .child(self.render_logs_drawer(cx)) } } impl SteamFrameGpuiApp { // ------------------------------------------------------------------------- - // 1. Barre Supérieure (Header & Cockpit Quick Actions) + // 1. Barre Supérieure (Header & Navigation par Onglets) // ------------------------------------------------------------------------- fn render_header(&self, cx: &mut Context) -> impl IntoElement { div() @@ -256,76 +326,93 @@ impl SteamFrameGpuiApp { .border_1() .border_color(rgb(COLOR_BORDER_SUBTLE)) .rounded_xl() - .px_4() + .px_3() .py_2() + .gap_2() + // GAUCHE : Identité & Badges Statut .child( div() .flex() .items_center() - .gap_3() + .gap_2p5() .child( div() - .text_xl() + .text_base() .font_weight(gpui::FontWeight::BOLD) .text_color(rgb(COLOR_CYAN)) .child("🥽 SteamFrame FPV"), ) - .child( - div() - .text_xs() - .text_color(rgb(COLOR_TEXT_MUTED)) - .child("Eachine Sphere Link • RadioMaster Nomad • OpenXR 140°"), - ), + .child(self.render_status_badge("VRX", &self.usb_status)) + .child(self.render_status_badge("VR", &self.xr_status)), ) + // CENTRE : Barre d'onglets épurée + .child( + div() + .flex() + .items_center() + .gap_1() + .bg(rgb(COLOR_SURFACE_ELEVATED)) + .p_1() + .rounded_lg() + .border_1() + .border_color(rgb(COLOR_BORDER_SUBTLE)) + .child(self.render_nav_tab("📹 Cockpit", ActiveTab::Cockpit, cx)) + .child(self.render_nav_tab("⚙️ Réglages", ActiveTab::Settings, cx)) + .child(self.render_nav_tab("📊 Télémétrie", ActiveTab::Telemetry, cx)) + .child(self.render_nav_tab( + &if self.log_err_count > 0 { + format!("📜 Logs ({})", self.log_err_count) + } else { + "📜 Logs".to_string() + }, + ActiveTab::Logs, + cx, + )), + ) + // DROITE : Quick Actions & Tare .child( div() .flex() .items_center() .gap_2() - .child(self.render_status_badge("VRX", &self.usb_status)) - .child(self.render_status_badge("VR Casque", &self.xr_status)) .child( div() - .id("toggle_ht") + .id("toggle_ht_quick") .cursor_pointer() .on_click(cx.listener(|this, _, _, cx| { this.cfg.head_tracking_enabled = !this.cfg.head_tracking_enabled; this.engine + .lock() .set_head_tracking_enabled(this.cfg.head_tracking_enabled); cx.notify(); })) .child(self.render_toggle_pill( - "🎯 Suivi Tête", + "🎯 Suivi", self.cfg.head_tracking_enabled, rgb(COLOR_GREEN), )), ) .child( div() - .id("toggle_telem") + .id("toggle_telem_quick") .cursor_pointer() .on_click(cx.listener(|this, _, _, cx| { this.cfg.telemetry_enabled = !this.cfg.telemetry_enabled; this.engine + .lock() .set_telemetry_enabled(this.cfg.telemetry_enabled); cx.notify(); })) .child(self.render_toggle_pill( - "📶 Télémétrie OSD", + "📶 OSD", self.cfg.telemetry_enabled, rgb(COLOR_CYAN), )), - ), - ) - .child( - div() - .flex() - .items_center() - .gap_2() + ) .child( div() - .id("btn_tare") - .px_3() + .id("btn_tare_quick") + .px_2p5() .py_1() .bg(rgb(COLOR_SURFACE_ELEVATED)) .border_1() @@ -335,16 +422,331 @@ impl SteamFrameGpuiApp { .font_weight(gpui::FontWeight::SEMIBOLD) .cursor_pointer() .on_click(cx.listener(|this, _, _, cx| { - this.engine.request_recenter(); + this.engine.lock().request_recenter(); cx.notify(); })) - .child("🎯 Tare (Recentrer)"), + .child("🎯 Tare"), + ), + ) + } + + fn render_nav_tab(&self, label: &str, tab: ActiveTab, cx: &mut Context) -> impl IntoElement { + let is_active = self.active_tab == tab; + let tab_id = match tab { + ActiveTab::Cockpit => "tab_btn_cockpit", + ActiveTab::Settings => "tab_btn_settings", + ActiveTab::Telemetry => "tab_btn_telemetry", + ActiveTab::Logs => "tab_btn_logs", + }; + div() + .id(tab_id) + .px_3() + .py_1() + .rounded_md() + .text_xs() + .font_weight(if is_active { + gpui::FontWeight::BOLD + } else { + gpui::FontWeight::NORMAL + }) + .bg(if is_active { + rgb(0x1a2638) + } else { + rgba(0x00000000) + }) + .border_1() + .border_color(if is_active { + rgb(COLOR_BORDER_ACTIVE) + } else { + rgba(0x00000000) + }) + .text_color(if is_active { + rgb(COLOR_CYAN) + } else { + rgb(COLOR_TEXT_MUTED) + }) + .cursor_pointer() + .on_click(cx.listener(move |this, _, _, cx| { + this.active_tab = tab; + cx.notify(); + })) + .child(label.to_string()) + } + + // ------------------------------------------------------------------------- + // 2. Vue Cockpit : Plein Format Vidéo + Overlay HUD Discret + // ------------------------------------------------------------------------- + fn render_cockpit_view(&self, cx: &mut Context) -> impl IntoElement { + div() + .flex() + .flex_col() + .size_full() + .relative() + .bg(rgb(0x030508)) + .border_1() + .border_color(rgb(COLOR_BORDER_SUBTLE)) + .rounded_xl() + .overflow_hidden() + .items_center() + .justify_center() + // 2.1 Flux Vidéo + .child(if let Some(ref img_src) = self.current_render_image { + div().size_full().child(img(img_src.clone()).size_full()) + } else { + div() + .flex() + .flex_col() + .items_center() + .gap_3() + .child( + div() + .text_xl() + .font_weight(gpui::FontWeight::BOLD) + .text_color(rgb(COLOR_CYAN)) + .child("🥽 En attente du flux Eachine Sphere Link..."), ) .child( div() - .id("btn_apply") - .px_3() + .text_xs() + .text_color(rgb(COLOR_TEXT_MUTED)) + .child("Réception active sur UDP 0.0.0.0:5600 (H.264 Raw direct)"), + ) + .child( + div() + .flex() + .gap_2() + .pt_2() + .child( + div() + .px_3() + .py_1p5() + .bg(rgb(COLOR_SURFACE_CARD)) + .border_1() + .border_color(rgb(COLOR_BORDER_SUBTLE)) + .rounded_lg() + .text_xs() + .child("1. Branchez le câble USB-C OTG ou Mini-HDMI"), + ) + .child( + div() + .px_3() + .py_1p5() + .bg(rgb(COLOR_SURFACE_CARD)) + .border_1() + .border_color(rgb(COLOR_BORDER_SUBTLE)) + .rounded_lg() + .text_xs() + .child("2. Vérifiez le canal 5.8 GHz (Canal 161)"), + ), + ) + }) + // 2.2 Overlay Supérieur Gauche (FPS & Trames) + .child( + div() + .absolute() + .top_3() + .left_3() + .flex() + .gap_2() + .child( + div() + .px_2p5() .py_1() + .bg(rgba(0x0a101abb)) + .border_1() + .border_color(if self.video_fps > 0.1 { + rgb(COLOR_GREEN) + } else { + rgb(COLOR_ORANGE) + }) + .rounded_md() + .text_xs() + .font_weight(gpui::FontWeight::BOLD) + .text_color(if self.video_fps > 0.1 { + rgb(COLOR_GREEN) + } else { + rgb(COLOR_ORANGE) + }) + .child(if self.video_fps > 0.1 { + format!("{:.1} FPS", self.video_fps) + } else { + "⚠️ RECHERCHE SIGNAL".to_string() + }), + ) + .child( + div() + .px_2p5() + .py_1() + .bg(rgba(0x0a101abb)) + .border_1() + .border_color(rgb(COLOR_BORDER_SUBTLE)) + .rounded_md() + .text_xs() + .text_color(rgb(COLOR_TEXT_MUTED)) + .child(format!("{} trames", self.video_frames_total)), + ), + ) + // 2.3 Overlay Supérieur Droit (VR & Format) + .child( + div() + .absolute() + .top_3() + .right_3() + .flex() + .gap_2() + .child( + div() + .px_2p5() + .py_1() + .bg(rgba(0x0a101abb)) + .border_1() + .border_color(rgb(COLOR_BORDER_SUBTLE)) + .rounded_md() + .text_xs() + .text_color(rgb(COLOR_CYAN)) + .child(format!( + "{} • {}", + self.cfg.vrx_video_profile, + self.cfg.projection_mode.to_uppercase() + )), + ) + .child( + div() + .id("btn_toggle_hud") + .px_2p5() + .py_1() + .bg(rgba(0x0a101abb)) + .border_1() + .border_color(rgb(COLOR_BORDER_SUBTLE)) + .rounded_md() + .text_xs() + .text_color(rgb(COLOR_TEXT_MUTED)) + .cursor_pointer() + .on_click(cx.listener(|this, _, _, cx| { + this.show_hud_overlay = !this.show_hud_overlay; + cx.notify(); + })) + .child(if self.show_hud_overlay { + "👁️ HUD ON" + } else { + "👁️ HUD OFF" + }), + ), + ) + // 2.4 Bandeau Flottant Inférieur (HUD Télémetrie & Suivi Tête discret) + .child(if self.show_hud_overlay { + div() + .absolute() + .bottom_3() + .flex() + .items_center() + .gap_3() + .px_4() + .py_1p5() + .bg(rgba(0x090e18ee)) + .border_1() + .border_color(rgb(COLOR_BORDER_SUBTLE)) + .rounded_full() + .text_xs() + .child( + div() + .text_color(rgb(COLOR_GREEN)) + .child(format!("🔋 {:.1} V", self.latest_telem.battery_voltage_v)), + ) + .child( + div() + .text_color(rgb(COLOR_TEXT_MUTED)) + .child("•"), + ) + .child( + div() + .text_color(rgb(COLOR_CYAN)) + .child(format!("📶 LQ {}%", self.latest_telem.link_quality_pct)), + ) + .child( + div() + .text_color(rgb(COLOR_TEXT_MUTED)) + .child("•"), + ) + .child( + div() + .text_color(rgb(COLOR_TEXT_MAIN)) + .child(format!( + "🚀 {:.0} km/h • ⛰️ {:.0} m", + self.latest_telem.groundspeed_ms * 3.6, + self.latest_telem.altitude_m + )), + ) + .child( + div() + .text_color(rgb(COLOR_TEXT_MUTED)) + .child("•"), + ) + .child( + div() + .text_color(rgb(COLOR_ORANGE)) + .child(format!( + "🎯 P:{:+.0}° T:{:+.0}° R:{:+.0}°", + self.latest_pose.pan_deg, + self.latest_pose.tilt_deg, + self.latest_pose.roll_deg + )), + ) + .into_any_element() + } else { + div().into_any_element() + }) + } + + // ------------------------------------------------------------------------- + // 3. Vue Réglages (Menus Déroulants & Paramètres Configurables) + // ------------------------------------------------------------------------- + fn render_settings_view(&self, cx: &mut Context) -> impl IntoElement { + div() + .flex() + .flex_col() + .size_full() + .id("settings_view_scroll") + .overflow_y_scroll() + .bg(rgb(COLOR_SURFACE_CARD)) + .border_1() + .border_color(rgb(COLOR_BORDER_SUBTLE)) + .rounded_xl() + .p_4() + .gap_4() + // Titre & En-tête + .child( + div() + .flex() + .justify_between() + .items_center() + .border_b_1() + .border_color(rgb(COLOR_BORDER_SUBTLE)) + .pb_3() + .child( + div() + .flex() + .flex_col() + .gap_0p5() + .child( + div() + .text_base() + .font_weight(gpui::FontWeight::BOLD) + .text_color(rgb(COLOR_CYAN)) + .child("⚙️ Paramètres et Réglages FPV"), + ) + .child( + div() + .text_xs() + .text_color(rgb(COLOR_TEXT_MUTED)) + .child("Configurez le récepteur VRX, le Wi-Fi Nomad, la projection VR et l'OSD."), + ), + ) + .child( + div() + .id("btn_apply_settings") + .px_4() + .py_1p5() .bg(rgb(COLOR_GREEN)) .text_color(rgb(0x000000)) .rounded_md() @@ -352,334 +754,534 @@ impl SteamFrameGpuiApp { .font_weight(gpui::FontWeight::BOLD) .cursor_pointer() .on_click(cx.listener(|this, _, _, cx| { - this.engine.start(this.cfg.clone()); + log::info!("[Réglages] Application et redémarrage asynchrone du moteur FPV..."); + let engine_clone = Arc::clone(&this.engine); + let cfg_clone = this.cfg.clone(); + std::thread::spawn(move || { + let mut eng = engine_clone.lock(); + eng.start(cfg_clone); + }); cx.notify(); })) - .child("🔄 Appliquer"), + .child("🔄 Appliquer & Redémarrer"), ), ) - } - - // ------------------------------------------------------------------------- - // 2. Panneau Gauche (Sidebar Matérielle & Options) - // ------------------------------------------------------------------------- - fn render_sidebar(&self, cx: &mut Context) -> impl IntoElement { - div() - .flex() - .flex_col() - .w(px(340.0)) - .bg(rgb(COLOR_SURFACE_CARD)) - .border_1() - .border_color(rgb(COLOR_BORDER_SUBTLE)) - .rounded_xl() - .p_3() - .gap_3() - .id("sidebar_scroll") - .overflow_scroll() - // Section 1 : VRX Eachine Sphere Link - .child( - div() - .flex() - .flex_col() - .gap_2() - .child( - div() - .text_sm() - .font_weight(gpui::FontWeight::BOLD) - .text_color(rgb(COLOR_CYAN)) - .child("🔌 1. VRX Sphere Link (Radxa 3W)"), - ) - .child( - div() - .flex() - .justify_between() - .text_xs() - .child("Mode USB :") - .child( - div() - .text_color(rgb(COLOR_GREEN)) - .child(self.cfg.usb_video_mode.to_uppercase()), - ), - ) - .child( - div() - .flex() - .justify_between() - .text_xs() - .child("Canal 5.8 GHz :") - .child( - div() - .text_color(rgb(COLOR_ORANGE)) - .child(format!("Canal {}", self.cfg.wifi_channel)), - ), - ) - .child( - div() - .flex() - .justify_between() - .text_xs() - .child("Résolution Cible :") - .child(format!("{} @ 60 FPS", self.cfg.vrx_video_profile)), - ) - .child( - div() - .flex() - .gap_2() - .pt_1() - .child( - div() - .id("btn_rndis") - .flex_1() - .py_1() - .bg(rgb(COLOR_SURFACE_ELEVATED)) - .border_1() - .border_color(rgb(COLOR_BORDER_SUBTLE)) - .rounded_md() - .text_xs() - .cursor_pointer() - .on_click(cx.listener(|this, _, _, _| { - this.run_usb_rndis_setup(); - })) - .child("⚡ Config RNDIS"), - ) - .child( - div() - .id("btn_ssh") - .flex_1() - .py_1() - .bg(rgb(COLOR_SURFACE_ELEVATED)) - .border_1() - .border_color(rgb(COLOR_BORDER_SUBTLE)) - .rounded_md() - .text_xs() - .cursor_pointer() - .on_click(cx.listener(|this, _, _, _| { - this.configure_radxa_ssh(); - })) - .child("🔧 Config SSH"), - ), - ), - ) - // Section 2 : Wi-Fi RadioMaster Nomad - .child( - div() - .flex() - .flex_col() - .gap_2() - .pt_2() - .border_t_1() - .border_color(rgb(COLOR_BORDER_SUBTLE)) - .child( - div() - .text_sm() - .font_weight(gpui::FontWeight::BOLD) - .text_color(rgb(COLOR_ORANGE)) - .child("📡 2. Wi-Fi Nomad (ELRS)"), - ) - .child( - div() - .flex() - .justify_between() - .text_xs() - .child("Cible UDP :") - .child(format!("{}:{}", self.cfg.nomad_ip, self.cfg.nomad_port)), - ) - .child( - div() - .flex() - .justify_between() - .text_xs() - .child("Protocole :") - .child(self.cfg.ht_protocol.to_uppercase()), - ) - .child( - div() - .flex() - .justify_between() - .text_xs() - .child("Courses Max :") - .child(format!( - "P:{}° T:{}° R:{}°", - self.cfg.max_pan_deg, self.cfg.max_tilt_deg, self.cfg.max_roll_deg - )), - ) - .child( - div() - .id("btn_nomad_test") - .w_full() - .py_1() - .bg(rgb(COLOR_SURFACE_ELEVATED)) - .border_1() - .border_color(rgb(COLOR_BORDER_SUBTLE)) - .rounded_md() - .text_xs() - .cursor_pointer() - .on_click(cx.listener(|this, _, _, _| { - this.test_nomad_packet(); - })) - .child("📡 Envoyer paquet test"), - ), - ) - // Section 3 : Projection OpenXR 140° - .child( - div() - .flex() - .flex_col() - .gap_2() - .pt_2() - .border_t_1() - .border_color(rgb(COLOR_BORDER_SUBTLE)) - .child( - div() - .text_sm() - .font_weight(gpui::FontWeight::BOLD) - .text_color(rgb(COLOR_CYAN)) - .child("🥽 3. Projection VR & Optique"), - ) - .child( - div() - .flex() - .justify_between() - .text_xs() - .child("Mode Projection :") - .child(self.cfg.projection_mode.to_uppercase()), - ) - .child( - div() - .flex() - .justify_between() - .text_xs() - .child("FOV Caméra :") - .child(format!("{}°", self.cfg.camera_fov_deg)), - ) - .child( - div() - .flex() - .justify_between() - .text_xs() - .child("Distorsion Lentille :") - .child(format!("k1={:.2} k2={:.2}", self.cfg.lens_k1, self.cfg.lens_k2)), - ) - .child( - div() - .flex() - .justify_between() - .text_xs() - .child("Rayon Dôme :") - .child(format!("{:.1} m", self.cfg.screen_distance_m)), - ), - ) - } - - // ------------------------------------------------------------------------- - // 3. Cockpit Central (Vidéo Haute Fréquence + Jauges Télémetrie) - // ------------------------------------------------------------------------- - fn render_cockpit(&self) -> impl IntoElement { - div() - .flex() - .flex_col() - .flex_1() - .gap_3() - .overflow_hidden() - // 3.1 VIEWPORT VIDEO 16:9 - .child( - div() - .flex() - .flex_1() - .bg(rgb(0x05070a)) - .border_1() - .border_color(rgb(COLOR_BORDER_SUBTLE)) - .rounded_xl() - .relative() - .overflow_hidden() - .items_center() - .justify_center() - .child(if let Some(ref img_src) = self.current_render_image { - div().size_full().child(img(img_src.clone()).size_full()) - } else { - div() - .flex() - .flex_col() - .items_center() - .gap_2() - .child( - div() - .text_lg() - .font_weight(gpui::FontWeight::BOLD) - .text_color(rgb(COLOR_CYAN)) - .child("En attente du flux vidéo 720p60..."), - ) - .child( - div() - .text_xs() - .text_color(rgb(COLOR_TEXT_MUTED)) - .child("Port UDP 0.0.0.0:5600 (H.264 Raw NAL direct)"), - ) - }) - // Overlay FPS & Compteur de trames en haut à droite - .child( - div() - .absolute() - .top_3() - .right_3() - .flex() - .gap_2() - .child( - div() - .px_2() - .py_0p5() - .bg(rgba(0x000000bb)) - .border_1() - .border_color(rgb(COLOR_GREEN)) - .rounded_md() - .text_xs() - .font_weight(gpui::FontWeight::BOLD) - .text_color(rgb(COLOR_GREEN)) - .child(format!("{:.1} FPS", self.video_fps)), - ) - .child( - div() - .px_2() - .py_0p5() - .bg(rgba(0x000000bb)) - .border_1() - .border_color(rgb(COLOR_BORDER_SUBTLE)) - .rounded_md() - .text_xs() - .text_color(rgb(COLOR_TEXT_MUTED)) - .child(format!("{} trames", self.video_frames_total)), - ), - ), - ) - // 3.2 DOUBLE CARTE DE MONITORING : SUIVI TÊTE & TELEMETRIE + // Grille des réglages (Cartes thématiques) .child( div() .flex() .flex_row() - .h(px(160.0)) + .flex_wrap() .gap_3() - // Carte Suivi de Tête Nomad + // 3.1 Carte VRX Eachine Sphere Link + .child(self.render_settings_card( + "🔌 1. Récepteur VRX Sphere Link (Radxa Zero 3W)", + COLOR_CYAN, + div() + .flex() + .flex_col() + .gap_3() + // Mode d'acquisition + .child(self.render_setting_row( + "Mode Acquisition Vidéo", + div() + .flex() + .gap_2() + .child(self.render_selectable_pill( + "pill_mode_rndis", + "USB OTG (RNDIS)", + self.cfg.usb_video_mode.eq_ignore_ascii_case("rndis"), + cx.listener(|this, _, _, cx| { + this.cfg.usb_video_mode = "rndis".into(); + cx.notify(); + }), + )) + .child(self.render_selectable_pill( + "pill_mode_uvc", + "Mini-HDMI (UVC)", + self.cfg.usb_video_mode.eq_ignore_ascii_case("uvc"), + cx.listener(|this, _, _, cx| { + this.cfg.usb_video_mode = "uvc".into(); + cx.notify(); + }), + )), + )) + // Canal 5.8 GHz + .child(self.render_setting_row( + "Canal 5.8 GHz (RTL8812EU)", + div() + .flex() + .gap_1p5() + .child(self.render_channel_button(149, 5745, cx)) + .child(self.render_channel_button(153, 5765, cx)) + .child(self.render_channel_button(157, 5785, cx)) + .child(self.render_channel_button(161, 5805, cx)), + )) + // Codec & Transport + .child(self.render_setting_row( + "Codec Décodage", + div() + .flex() + .gap_2() + .child(self.render_selectable_pill( + "pill_codec_h264", + "H.264 (Faible Latence)", + self.cfg.codec.eq_ignore_ascii_case("h264"), + cx.listener(|this, _, _, cx| { + this.cfg.codec = "h264".into(); + cx.notify(); + }), + )) + .child(self.render_selectable_pill( + "pill_codec_h265", + "H.265 (HEVC)", + self.cfg.codec.eq_ignore_ascii_case("h265"), + cx.listener(|this, _, _, cx| { + this.cfg.codec = "h265".into(); + cx.notify(); + }), + )), + )) + // Actions matérielles + .child( + div() + .flex() + .gap_2() + .pt_2() + .child( + div() + .id("btn_rndis_setup") + .flex_1() + .py_1p5() + .bg(rgb(COLOR_SURFACE_ELEVATED)) + .border_1() + .border_color(rgb(COLOR_BORDER_SUBTLE)) + .rounded_md() + .text_xs() + .font_weight(gpui::FontWeight::SEMIBOLD) + .cursor_pointer() + .on_click(cx.listener(|this, _, _, _| { + this.run_usb_rndis_setup(); + })) + .child("⚡ Lancer setup_usb_rndis.sh"), + ) + .child( + div() + .id("btn_ssh_setup") + .flex_1() + .py_1p5() + .bg(rgb(COLOR_SURFACE_ELEVATED)) + .border_1() + .border_color(rgb(COLOR_BORDER_SUBTLE)) + .rounded_md() + .text_xs() + .font_weight(gpui::FontWeight::SEMIBOLD) + .cursor_pointer() + .on_click(cx.listener(|this, _, _, _| { + this.configure_radxa_ssh(); + })) + .child("🔧 Config Canal par SSH"), + ), + ), + )) + // 3.2 Carte Wi-Fi RadioMaster Nomad (ELRS) + .child(self.render_settings_card( + "📡 2. Suivi de Tête & Radio (Nomad ELRS)", + COLOR_ORANGE, + div() + .flex() + .flex_col() + .gap_3() + // Protocole + .child(self.render_setting_row( + "Protocole Wi-Fi", + div() + .flex() + .gap_2() + .child(self.render_selectable_pill( + "pill_proto_msp", + "MSPv2 0x0383 (ELRS Backpack)", + self.cfg.ht_protocol.eq_ignore_ascii_case("msp"), + cx.listener(|this, _, _, cx| { + this.cfg.ht_protocol = "msp".into(); + cx.notify(); + }), + )) + .child(self.render_selectable_pill( + "pill_proto_crsf", + "CRSF 0x16 (RC Channels)", + self.cfg.ht_protocol.eq_ignore_ascii_case("crsf"), + cx.listener(|this, _, _, cx| { + this.cfg.ht_protocol = "crsf".into(); + cx.notify(); + }), + )), + )) + // Cible UDP + .child(self.render_setting_row( + "Cible Réseau", + div() + .text_xs() + .text_color(rgb(COLOR_TEXT_MAIN)) + .child(format!("{}:{} (Backpack AP)", self.cfg.nomad_ip, self.cfg.nomad_port)), + )) + // Courses maximales + .child(self.render_setting_row( + "Débattements Max", + div() + .text_xs() + .text_color(rgb(COLOR_TEXT_MAIN)) + .child(format!( + "Pan : {}° | Tilt : {}° | Roll : {}°", + self.cfg.max_pan_deg, self.cfg.max_tilt_deg, self.cfg.max_roll_deg + )), + )) + // Actions Nomad + .child( + div() + .flex() + .gap_2() + .pt_2() + .child( + div() + .id("btn_test_packet_settings") + .flex_1() + .py_1p5() + .bg(rgb(COLOR_SURFACE_ELEVATED)) + .border_1() + .border_color(rgb(COLOR_BORDER_SUBTLE)) + .rounded_md() + .text_xs() + .font_weight(gpui::FontWeight::SEMIBOLD) + .cursor_pointer() + .on_click(cx.listener(|this, _, _, _| { + this.test_nomad_packet(); + })) + .child("📡 Envoyer paquet test"), + ) + .child( + div() + .id("btn_tare_settings") + .flex_1() + .py_1p5() + .bg(rgb(COLOR_SURFACE_ELEVATED)) + .border_1() + .border_color(rgb(COLOR_BORDER_SUBTLE)) + .rounded_md() + .text_xs() + .font_weight(gpui::FontWeight::SEMIBOLD) + .cursor_pointer() + .on_click(cx.listener(|this, _, _, cx| { + this.engine.lock().request_recenter(); + cx.notify(); + })) + .child("🎯 Réinitialiser Zéro (Tare)"), + ), + ), + )) + // 3.3 Carte Projection VR Steam Frame & Optique + .child(self.render_settings_card( + "🥽 3. Projection VR & Correction Optique 140°", + COLOR_CYAN, + div() + .flex() + .flex_col() + .gap_3() + // Mode de projection + .child(self.render_setting_row( + "Mode de Projection VR", + div() + .flex() + .gap_2() + .child(self.render_selectable_pill( + "pill_proj_dome", + "Dôme 140° (Equirect2)", + self.cfg.projection_mode.eq_ignore_ascii_case("dome"), + cx.listener(|this, _, _, cx| { + this.cfg.projection_mode = "dome".into(); + cx.notify(); + }), + )) + .child(self.render_selectable_pill( + "pill_proj_cyl", + "Cylindre 140°", + self.cfg.projection_mode.eq_ignore_ascii_case("cylinder"), + cx.listener(|this, _, _, cx| { + this.cfg.projection_mode = "cylinder".into(); + cx.notify(); + }), + )) + .child(self.render_selectable_pill( + "pill_proj_flat", + "Quad Plat", + self.cfg.projection_mode.eq_ignore_ascii_case("flat"), + cx.listener(|this, _, _, cx| { + this.cfg.projection_mode = "flat".into(); + cx.notify(); + }), + )), + )) + // Lentille et FOV + .child(self.render_setting_row( + "Champ de Vision & Optique", + div() + .text_xs() + .text_color(rgb(COLOR_TEXT_MAIN)) + .child(format!( + "FOV : {}° | Lentille : k1={:.2}, k2={:.2}", + self.cfg.camera_fov_deg, self.cfg.lens_k1, self.cfg.lens_k2 + )), + )) + // Distance virtuelle + .child(self.render_setting_row( + "Distance Virtuelle Écran", + div() + .text_xs() + .text_color(rgb(COLOR_TEXT_MAIN)) + .child(format!("{:.1} mètres", self.cfg.screen_distance_m)), + )), + )) + // 3.4 Carte Télémétrie OSD & MAVLink + .child(self.render_settings_card( + "📊 4. Télémétrie OSD & MAVLink", + COLOR_GREEN, + div() + .flex() + .flex_col() + .gap_3() + .child(self.render_setting_row( + "État Télémétrie & OSD", + div() + .flex() + .gap_2() + .child(self.render_selectable_pill( + "pill_telem_on", + "Activé (ON)", + self.cfg.telemetry_enabled, + cx.listener(|this, _, _, cx| { + this.cfg.telemetry_enabled = true; + this.engine.lock().set_telemetry_enabled(true); + cx.notify(); + }), + )) + .child(self.render_selectable_pill( + "pill_telem_off", + "Désactivé (OFF)", + !self.cfg.telemetry_enabled, + cx.listener(|this, _, _, cx| { + this.cfg.telemetry_enabled = false; + this.engine.lock().set_telemetry_enabled(false); + cx.notify(); + }), + )), + )) + .child(self.render_setting_row( + "Port UDP Écoute MAVLink", + div() + .text_xs() + .text_color(rgb(COLOR_TEXT_MAIN)) + .child(format!("0.0.0.0:{}", self.cfg.telemetry_udp_port)), + )), + )), + ) + } + + fn render_settings_card(&self, title: &str, accent_color: u32, content: impl IntoElement) -> impl IntoElement { + div() + .flex() + .flex_col() + .min_w(px(380.0)) + .flex_1() + .bg(rgb(COLOR_SURFACE_ELEVATED)) + .border_1() + .border_color(rgb(COLOR_BORDER_SUBTLE)) + .rounded_xl() + .p_4() + .gap_3() + .child( + div() + .text_sm() + .font_weight(gpui::FontWeight::BOLD) + .text_color(rgb(accent_color)) + .child(title.to_string()), + ) + .child(content) + } + + fn render_setting_row(&self, label: &str, control: impl IntoElement) -> impl IntoElement { + div() + .flex() + .flex_col() + .gap_1p5() + .child( + div() + .text_xs() + .font_weight(gpui::FontWeight::SEMIBOLD) + .text_color(rgb(COLOR_TEXT_MUTED)) + .child(label.to_string()), + ) + .child(control) + } + + fn render_selectable_pill( + &self, + id: &'static str, + label: &str, + is_selected: bool, + on_click: impl Fn(&gpui::ClickEvent, &mut Window, &mut App) + 'static, + ) -> impl IntoElement { + div() + .id(id) + .px_3() + .py_1() + .bg(if is_selected { + rgb(0x132738) + } else { + rgb(COLOR_SURFACE_CARD) + }) + .border_1() + .border_color(if is_selected { + rgb(COLOR_CYAN) + } else { + rgb(COLOR_BORDER_SUBTLE) + }) + .rounded_md() + .text_xs() + .font_weight(if is_selected { + gpui::FontWeight::BOLD + } else { + gpui::FontWeight::NORMAL + }) + .text_color(if is_selected { + rgb(COLOR_CYAN) + } else { + rgb(COLOR_TEXT_MUTED) + }) + .cursor_pointer() + .on_click(on_click) + .child(label.to_string()) + } + + fn render_channel_button(&self, ch: u16, freq_mhz: u32, cx: &mut Context) -> impl IntoElement { + let is_selected = self.cfg.wifi_channel == ch; + let btn_id = match ch { + 149 => "btn_ch_149", + 153 => "btn_ch_153", + 157 => "btn_ch_157", + _ => "btn_ch_161", + }; + div() + .id(btn_id) + .flex_1() + .px_2() + .py_1() + .bg(if is_selected { + rgb(0x28190d) + } else { + rgb(COLOR_SURFACE_CARD) + }) + .border_1() + .border_color(if is_selected { + rgb(COLOR_ORANGE) + } else { + rgb(COLOR_BORDER_SUBTLE) + }) + .rounded_md() + .text_xs() + .text_center() + .font_weight(if is_selected { + gpui::FontWeight::BOLD + } else { + gpui::FontWeight::NORMAL + }) + .text_color(if is_selected { + rgb(COLOR_ORANGE) + } else { + rgb(COLOR_TEXT_MUTED) + }) + .cursor_pointer() + .on_click(cx.listener(move |this, _, _, cx| { + this.cfg.wifi_channel = ch; + cx.notify(); + })) + .child(format!("CH {} ({}MHz)", ch, freq_mhz)) + } + + // ------------------------------------------------------------------------- + // 4. Vue Télémétrie Détaillée & Jauges Vol + // ------------------------------------------------------------------------- + fn render_telemetry_view(&self) -> impl IntoElement { + div() + .flex() + .flex_col() + .size_full() + .id("telemetry_view_scroll") + .overflow_y_scroll() + .bg(rgb(COLOR_SURFACE_CARD)) + .border_1() + .border_color(rgb(COLOR_BORDER_SUBTLE)) + .rounded_xl() + .p_4() + .gap_4() + // Bandeau supérieur des données batterie et signal + .child( + div() + .flex() + .flex_wrap() + .gap_3() + .child(self.render_stat_box( + "🔋 BATTERIE DRONE", + &format!("{:.2} V", self.latest_telem.battery_voltage_v), + &format!("{:.1} A débit", self.latest_telem.battery_current_a), + COLOR_GREEN, + )) + .child(self.render_stat_box( + "📶 QUALITÉ DU LIEN", + &format!("{} %", self.latest_telem.link_quality_pct), + &format!("{} dBm (RSSI)", self.latest_telem.rssi_dbm), + COLOR_CYAN, + )) + .child(self.render_stat_box( + "🚀 VITESSE SOL", + &format!("{:.1} km/h", self.latest_telem.groundspeed_ms * 3.6), + &format!("Gaz : {}%", self.latest_telem.throttle_pct), + COLOR_ORANGE, + )) + .child(self.render_stat_box( + "⛰️ ALTITUDE & CAP", + &format!("{:.1} m", self.latest_telem.altitude_m), + &format!("Cap : {:.0}°", self.latest_telem.drone_heading_deg), + COLOR_CYAN, + )), + ) + // Double Panneau : Suivi de Tête & Radio + .child( + div() + .flex() + .gap_4() + // Panneau Jauges Suivi de Tête .child( div() .flex() .flex_col() .flex_1() - .bg(rgb(COLOR_SURFACE_CARD)) + .bg(rgb(COLOR_SURFACE_ELEVATED)) .border_1() .border_color(rgb(COLOR_BORDER_SUBTLE)) .rounded_xl() - .p_3() - .gap_2() + .p_4() + .gap_3() .child( div() .flex() .justify_between() + .items_center() .child( div() - .text_xs() + .text_sm() .font_weight(gpui::FontWeight::BOLD) .text_color(rgb(COLOR_ORANGE)) - .child("🎯 Suivi de Tête -> Nomad (CRSF 172..1811)"), + .child("🎯 Canaux CRSF Suivi de Tête (172..1811)"), ) .child( div() @@ -693,120 +1295,139 @@ impl SteamFrameGpuiApp { ), ) .child(self.render_crsf_gauge( - "PAN (Lacet)", + "PAN (Lacet / Direction)", self.latest_pose.pan_deg, self.latest_pose.pan_crsf, self.cfg.max_pan_deg, )) .child(self.render_crsf_gauge( - "TILT (Tangage)", + "TILT (Tangage / Élévation)", self.latest_pose.tilt_deg, self.latest_pose.tilt_crsf, self.cfg.max_tilt_deg, )) .child(self.render_crsf_gauge( - "ROLL (Roulis)", + "ROLL (Roulis / Inclinaison)", self.latest_pose.roll_deg, self.latest_pose.roll_crsf, self.cfg.max_roll_deg, )), ) - // Carte Télémétrie OSD + // Panneau État Liaison Nomad .child( div() .flex() .flex_col() - .flex_1() - .bg(rgb(COLOR_SURFACE_CARD)) + .w(px(340.0)) + .bg(rgb(COLOR_SURFACE_ELEVATED)) .border_1() .border_color(rgb(COLOR_BORDER_SUBTLE)) .rounded_xl() - .p_3() - .gap_2() + .p_4() + .gap_3() .child( div() - .text_xs() + .text_sm() .font_weight(gpui::FontWeight::BOLD) .text_color(rgb(COLOR_CYAN)) - .child("📊 Télémétrie Drone & OSD"), + .child("📡 État RadioMaster Nomad"), ) - .child( - div() - .flex() - .justify_between() - .text_xs() - .child(format!( - "🔋 Batterie : {:.1} V ({:.1} A)", - self.latest_telem.battery_voltage_v, - self.latest_telem.battery_current_a - )) - .child(format!( - "📶 Signal : LQ {}% | {} dBm", - self.latest_telem.link_quality_pct, - self.latest_telem.rssi_dbm - )), - ) - .child( - div() - .flex() - .justify_between() - .text_xs() - .child(format!( - "🧭 Altitude : {:.1} m", - self.latest_telem.altitude_m - )) - .child(format!( - "🚀 Vitesse : {:.1} km/h (Gaz {}%)", - self.latest_telem.groundspeed_ms * 3.6, - self.latest_telem.throttle_pct - )), - ) - .child( - div() - .text_xs() - .text_color(rgb(COLOR_TEXT_MUTED)) - .child(format!( - "Attitude : R{:+.1}° | P{:+.1}° | Cap {:.0}° ({} trames OSD)", - self.latest_telem.drone_roll_rad.to_degrees(), - self.latest_telem.drone_pitch_rad.to_degrees(), - self.latest_telem.drone_heading_deg, - self.latest_telem.packets_received - )), - ), + .child(self.render_stat_row("Statut Réseau :", &format!("{:?}", self.nomad_status))) + .child(self.render_stat_row("Cible UDP :", &format!("{}:{}", self.cfg.nomad_ip, self.cfg.nomad_port))) + .child(self.render_stat_row("Protocole :", &self.cfg.ht_protocol.to_uppercase())) + .child(self.render_stat_row("Fréquence d'Émission :", "60 Hz (Sync OpenXR)")) + .child(self.render_stat_row("Dernière émission :", if self.latest_pose.last_send_ok { "Succès (OK)" } else { "En attente" })), ), ) } - // ------------------------------------------------------------------------- - // 4. Console de Logs & Diagnostic - // ------------------------------------------------------------------------- - fn render_logs_drawer(&self, cx: &mut Context) -> impl IntoElement { + fn render_stat_box(&self, title: &str, value: &str, sub: &str, color: u32) -> impl IntoElement { div() .flex() .flex_col() - .h(px(140.0)) + .flex_1() + .min_w(px(200.0)) + .bg(rgb(COLOR_SURFACE_ELEVATED)) + .border_1() + .border_color(rgb(COLOR_BORDER_SUBTLE)) + .rounded_xl() + .p_3() + .gap_1() + .child( + div() + .text_xs() + .font_weight(gpui::FontWeight::SEMIBOLD) + .text_color(rgb(COLOR_TEXT_MUTED)) + .child(title.to_string()), + ) + .child( + div() + .text_xl() + .font_weight(gpui::FontWeight::BOLD) + .text_color(rgb(color)) + .child(value.to_string()), + ) + .child( + div() + .text_xs() + .text_color(rgb(COLOR_TEXT_MUTED)) + .child(sub.to_string()), + ) + } + + fn render_stat_row(&self, label: &str, val: &str) -> impl IntoElement { + div() + .flex() + .justify_between() + .text_xs() + .child( + div() + .text_color(rgb(COLOR_TEXT_MUTED)) + .child(label.to_string()), + ) + .child( + div() + .font_weight(gpui::FontWeight::SEMIBOLD) + .text_color(rgb(COLOR_TEXT_MAIN)) + .child(val.to_string()), + ) + } + + // ------------------------------------------------------------------------- + // 5. Vue Console de Logs Complète + // ------------------------------------------------------------------------- + fn render_logs_view(&self, cx: &mut Context) -> impl IntoElement { + div() + .flex() + .flex_col() + .size_full() .bg(rgb(COLOR_SURFACE_CARD)) .border_1() .border_color(rgb(COLOR_BORDER_SUBTLE)) .rounded_xl() - .p_2() - .gap_1() + .p_4() + .gap_3() + .overflow_hidden() + // Barre d'outils .child( div() .flex() .justify_between() .items_center() - .px_2() + .border_b_1() + .border_color(rgb(COLOR_BORDER_SUBTLE)) + .pb_3() .child( div() .flex() - .gap_3() .items_center() + .gap_3() .child( div() - .text_xs() + .text_sm() .font_weight(gpui::FontWeight::BOLD) - .child("📋 Journal de Diagnostic"), + .text_color(rgb(COLOR_CYAN)) + .child("📜 Console de Diagnostic et Journal Système"), ) .child( div() @@ -814,7 +1435,7 @@ impl SteamFrameGpuiApp { .text_color(if self.log_err_count > 0 { rgb(COLOR_RED) } else { - rgb(COLOR_GREEN) + rgb(COLOR_TEXT_MUTED) }) .child(format!("{} Erreurs", self.log_err_count)), ) @@ -835,14 +1456,20 @@ impl SteamFrameGpuiApp { .gap_2() .child( div() - .id("filter_all") - .px_2() - .py_0p5() + .id("filter_all_tab") + .px_3() + .py_1() .bg(if self.log_filter == LogFilter::All { rgb(0x1e3a5f) } else { rgb(COLOR_SURFACE_ELEVATED) }) + .border_1() + .border_color(if self.log_filter == LogFilter::All { + rgb(COLOR_CYAN) + } else { + rgb(COLOR_BORDER_SUBTLE) + }) .rounded_md() .text_xs() .cursor_pointer() @@ -850,18 +1477,24 @@ impl SteamFrameGpuiApp { this.log_filter = LogFilter::All; cx.notify(); })) - .child("Tous"), + .child("Tous les logs"), ) .child( div() - .id("filter_warn") - .px_2() - .py_0p5() + .id("filter_warn_tab") + .px_3() + .py_1() .bg(if self.log_filter == LogFilter::WarningsAndErrors { rgb(0x1e3a5f) } else { rgb(COLOR_SURFACE_ELEVATED) }) + .border_1() + .border_color(if self.log_filter == LogFilter::WarningsAndErrors { + rgb(COLOR_ORANGE) + } else { + rgb(COLOR_BORDER_SUBTLE) + }) .rounded_md() .text_xs() .cursor_pointer() @@ -869,18 +1502,24 @@ impl SteamFrameGpuiApp { this.log_filter = LogFilter::WarningsAndErrors; cx.notify(); })) - .child("Warn/Err"), + .child("Warn / Erreurs"), ) .child( div() - .id("filter_err") - .px_2() - .py_0p5() + .id("filter_err_tab") + .px_3() + .py_1() .bg(if self.log_filter == LogFilter::ErrorsOnly { rgb(0x1e3a5f) } else { rgb(COLOR_SURFACE_ELEVATED) }) + .border_1() + .border_color(if self.log_filter == LogFilter::ErrorsOnly { + rgb(COLOR_RED) + } else { + rgb(COLOR_BORDER_SUBTLE) + }) .rounded_md() .text_xs() .cursor_pointer() @@ -888,14 +1527,16 @@ impl SteamFrameGpuiApp { this.log_filter = LogFilter::ErrorsOnly; cx.notify(); })) - .child("Err"), + .child("Erreurs seules"), ) .child( div() - .id("btn_clear_logs") - .px_2() - .py_0p5() + .id("btn_clear_logs_tab") + .px_3() + .py_1() .bg(rgb(COLOR_SURFACE_ELEVATED)) + .border_1() + .border_color(rgb(COLOR_BORDER_SUBTLE)) .rounded_md() .text_xs() .cursor_pointer() @@ -909,23 +1550,23 @@ impl SteamFrameGpuiApp { this.log_warn_count = 0; cx.notify(); })) - .child("Effacer"), + .child("🗑️ Effacer"), ), ), ) + // Liste scrollable des messages .child( div() .flex() .flex_col() .flex_1() - .id("logs_scroll") - .overflow_scroll() + .id("logs_scroll_tab") + .overflow_y_scroll() .px_2() - .gap_0p5() + .gap_1() .children( self.log_entries .iter() - .rev() .filter(|e| match self.log_filter { LogFilter::All => true, LogFilter::WarningsAndErrors => { @@ -933,34 +1574,34 @@ impl SteamFrameGpuiApp { } LogFilter::ErrorsOnly => matches!(e.level, log::Level::Error), }) - .take(40) .map(|e| { - let badge_color = match e.level { - log::Level::Error => COLOR_RED, - log::Level::Warn => COLOR_ORANGE, - _ => COLOR_CYAN, - }; - div() - .flex() - .gap_2() - .text_xs() - .child( + let badge_color = match e.level { + log::Level::Error => COLOR_RED, + log::Level::Warn => COLOR_ORANGE, + _ => COLOR_CYAN, + }; div() - .text_color(rgb(COLOR_TEXT_MUTED)) - .child(e.timestamp.clone()), - ) - .child( - div() - .font_weight(gpui::FontWeight::BOLD) - .text_color(rgb(badge_color)) - .child(format!("[{}]", e.level)), - ) - .child( - div() - .text_color(rgb(COLOR_TEXT_MAIN)) - .child(e.message.clone()), - ) - })), + .flex() + .gap_2() + .text_xs() + .child( + div() + .text_color(rgb(COLOR_TEXT_MUTED)) + .child(e.timestamp.clone()), + ) + .child( + div() + .font_weight(gpui::FontWeight::BOLD) + .text_color(rgb(badge_color)) + .child(format!("[{:<5}]", e.level)), + ) + .child( + div() + .text_color(rgb(COLOR_TEXT_MAIN)) + .child(e.message.clone()), + ) + }), + ), ) } @@ -1044,7 +1685,9 @@ impl SteamFrameGpuiApp { div() .w_full() .h(px(6.0)) - .bg(rgb(COLOR_SURFACE_ELEVATED)) + .bg(rgb(COLOR_SURFACE_CARD)) + .border_1() + .border_color(rgb(COLOR_BORDER_SUBTLE)) .rounded_full() .overflow_hidden() .child( @@ -1059,7 +1702,7 @@ impl SteamFrameGpuiApp { pub fn run_gpui_app(cfg: AppConfig, log_buffer: Arc>) -> Result<()> { Application::new().run(move |cx: &mut App| { - let bounds = Bounds::centered(None, size(px(1240.0), px(840.0)), cx); + let bounds = Bounds::centered(None, size(px(1240.0), px(820.0)), cx); let window_res = cx.open_window( WindowOptions { @@ -1081,8 +1724,9 @@ pub fn run_gpui_app(cfg: AppConfig, log_buffer: Arc>) -> Result .update(|window, cx| { if let Some(view) = weak_view.upgrade() { view.update(cx, |this, cx| { - this.sync_from_engine(window); - cx.notify(); + if this.sync_from_engine(window) { + cx.notify(); + } }); true } else { diff --git a/src/logger.rs b/src/logger.rs index d0d34ae..e85be59 100644 --- a/src/logger.rs +++ b/src/logger.rs @@ -4,6 +4,7 @@ use parking_lot::Mutex; use std::collections::VecDeque; use std::fs::OpenOptions; use std::io::Write; +use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Arc; const MAX_LOG_ENTRIES: usize = 1000; @@ -23,12 +24,22 @@ pub struct LogEntry { pub message: String, } -#[derive(Default)] pub struct LogBuffer { pub entries: VecDeque, pub error_count: usize, pub warn_count: usize, - pub revision: u64, + pub revision: Arc, +} + +impl Default for LogBuffer { + fn default() -> Self { + Self { + entries: VecDeque::new(), + error_count: 0, + warn_count: 0, + revision: Arc::new(AtomicU64::new(0)), + } + } } /// Logger centralisé capturant tous les événements et erreurs pour l'interface graphique @@ -110,10 +121,16 @@ impl Log for GuiLogger { } if lock.entries.len() >= MAX_LOG_ENTRIES { - lock.entries.pop_front(); + if let Some(old) = lock.entries.pop_front() { + match old.level { + Level::Error => lock.error_count = lock.error_count.saturating_sub(1), + Level::Warn => lock.warn_count = lock.warn_count.saturating_sub(1), + _ => {} + } + } } lock.entries.push_back(entry); - lock.revision = lock.revision.wrapping_add(1); + lock.revision.fetch_add(1, Ordering::Release); } fn flush(&self) {} diff --git a/src/nomad_elrs.rs b/src/nomad_elrs.rs index 1dfde61..7246b2f 100644 --- a/src/nomad_elrs.rs +++ b/src/nomad_elrs.rs @@ -171,7 +171,7 @@ impl NomadHeadTracker { #[inline] pub fn deg_to_crsf(angle_deg: f32, max_deg: f32) -> u16 { - if angle_deg.is_nan() || max_deg <= 0.0 { + if angle_deg.is_nan() || !(max_deg > 0.0) { return CRSF_CHANNEL_MID; } let norm = (angle_deg / max_deg).clamp(-1.0, 1.0); @@ -254,6 +254,9 @@ mod tests { 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] diff --git a/src/video_usb.rs b/src/video_usb.rs index 25c4141..70747fb 100644 --- a/src/video_usb.rs +++ b/src/video_usb.rs @@ -23,6 +23,7 @@ pub struct UsbVideoReceiver { pipeline: gst::Pipeline, latest_frame: Arc>>, stop_flag: Arc, + has_error: Arc, } impl UsbVideoReceiver { @@ -159,6 +160,9 @@ impl UsbVideoReceiver { ); let stop_flag = Arc::new(AtomicBool::new(false)); + let has_error = Arc::new(AtomicBool::new(false)); + let error_clone = Arc::clone(&has_error); + if let Some(bus) = pipeline.bus() { let stop_bus = Arc::clone(&stop_flag); let _ = thread::Builder::new() @@ -179,6 +183,11 @@ impl UsbVideoReceiver { err.error(), err.debug() ); + error_clone.store(true, Ordering::Release); + } + MessageView::Eos(..) => { + log::warn!("[GStreamer] Fin de flux vidéo (EOS) reçu."); + error_clone.store(true, Ordering::Release); } MessageView::Warning(warn) => { log::warn!( @@ -207,6 +216,7 @@ impl UsbVideoReceiver { pipeline, latest_frame, stop_flag, + has_error, }) } @@ -214,6 +224,30 @@ impl UsbVideoReceiver { Arc::clone(&self.latest_frame) } + pub fn is_broken(&self) -> bool { + self.has_error.load(Ordering::Acquire) + } + + #[allow(dead_code)] + pub fn is_stream_live(&self, timeout: std::time::Duration) -> bool { + let lock = self.latest_frame.lock(); + if let Some(ref vf) = *lock { + vf.received_at.elapsed() < timeout + } else { + false + } + } + + pub fn restart(&mut self) -> Result<()> { + log::info!("[USB Vidéo] Réarmement du pipeline GStreamer (State: NULL -> PLAYING)..."); + let _ = self.pipeline.set_state(gst::State::Null); + std::thread::sleep(std::time::Duration::from_millis(60)); + self.latest_frame.lock().take(); + self.has_error.store(false, Ordering::Release); + self.pipeline.set_state(gst::State::Playing)?; + Ok(()) + } + pub fn render_standby_pattern(width: u32, height: u32, tick: u32, data: &mut [u8]) { let expected_len = (width * height * 4) as usize; if data.len() < expected_len {