mirror of
https://github.com/bleackstorm/SteamFrame-FPV-Control-Center.git
synced 2026-12-03 07:31:57 +01:00
1141 lines
46 KiB
Rust
1141 lines
46 KiB
Rust
mod cockpit;
|
|
mod controller_monitor;
|
|
mod logs;
|
|
mod settings;
|
|
mod telemetry;
|
|
mod theme;
|
|
mod widgets;
|
|
|
|
use theme::*;
|
|
use crate::config::AppConfig;
|
|
use crate::controller::{ControlSource, SteamControllerState};
|
|
use crate::engine::{
|
|
EngineControlHandle, FpvEngineController, RuntimeMonitor, SubsystemStatus,
|
|
};
|
|
use crate::g29_bridge::G29State;
|
|
use crate::logger::{LogBuffer, LogEntry, LogFilter};
|
|
use crate::nomad_elrs::{HeadPoseSample, NomadHeadTracker, NomadProtocol};
|
|
use crate::telemetry_osd::TelemetryState;
|
|
use anyhow::Result;
|
|
use gpui::{
|
|
div, prelude::*, px, rgb, rgba, size, App, Application, Bounds, Context,
|
|
FocusHandle, KeyDownEvent, RenderImage, Timer, Window, WindowBounds, WindowOptions,
|
|
};
|
|
use image::{Frame, RgbaImage};
|
|
use parking_lot::Mutex;
|
|
use smallvec::smallvec;
|
|
use std::process::Command;
|
|
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
|
use std::sync::Arc;
|
|
use std::time::{Duration, Instant};
|
|
|
|
// =========================================================================
|
|
// Palette Cyberpunk / Aeronautic FPV
|
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub enum ActiveTab {
|
|
Cockpit,
|
|
Settings,
|
|
Telemetry,
|
|
Logs,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
enum TargetEditField {
|
|
Ip,
|
|
Port,
|
|
}
|
|
|
|
pub struct SteamFrameGpuiApp {
|
|
cfg: AppConfig,
|
|
engine: Arc<Mutex<FpvEngineController>>,
|
|
controls: EngineControlHandle,
|
|
engine_monitor: Arc<Mutex<RuntimeMonitor>>,
|
|
log_buffer: Arc<Mutex<LogBuffer>>,
|
|
log_revision: Arc<AtomicU64>,
|
|
log_filter: LogFilter,
|
|
current_render_image: Option<Arc<RenderImage>>,
|
|
images_to_drop: Vec<Arc<RenderImage>>,
|
|
last_frame_seq: u64,
|
|
active_tab: ActiveTab,
|
|
show_hud_overlay: bool,
|
|
// Snapshots pour l'affichage réactif
|
|
usb_status: SubsystemStatus,
|
|
xr_status: SubsystemStatus,
|
|
nomad_status: SubsystemStatus,
|
|
telem_status: SubsystemStatus,
|
|
g29_status: SubsystemStatus,
|
|
controller_status: SubsystemStatus,
|
|
active_control_source: ControlSource,
|
|
dvr_status: SubsystemStatus,
|
|
dvr_recording: bool,
|
|
dvr_elapsed_secs: u64,
|
|
dvr_file_size_bytes: u64,
|
|
dvr_frames_recorded: u64,
|
|
dvr_filename: String,
|
|
video_fps: f32,
|
|
video_jitter_ms: f32,
|
|
video_dropped_frames: u64,
|
|
video_decoder_name: String,
|
|
video_frames_total: u64,
|
|
latest_pose: HeadPoseSample,
|
|
latest_telem: TelemetryState,
|
|
latest_g29: G29State,
|
|
latest_controller: SteamControllerState,
|
|
control_switch_error: String,
|
|
profile_feedback: String,
|
|
monitor_source_override: Option<ControlSource>,
|
|
log_entries: Vec<LogEntry>,
|
|
log_err_count: usize,
|
|
log_warn_count: usize,
|
|
last_log_revision: u64,
|
|
last_config_revision: u64,
|
|
// Cible réseau éditable & Mock Manuel Nomad
|
|
target_edit_field: Option<TargetEditField>,
|
|
target_port_buf: String,
|
|
target_focus_handle: Option<FocusHandle>,
|
|
mock_pan_deg: f32,
|
|
mock_tilt_deg: f32,
|
|
mock_roll_deg: f32,
|
|
mock_continuous: bool,
|
|
mock_tracker: Option<NomadHeadTracker>,
|
|
mock_resolving: Arc<AtomicBool>,
|
|
mock_resolved: Arc<Mutex<Option<std::result::Result<NomadHeadTracker, String>>>>,
|
|
mock_last_send: Option<Instant>,
|
|
mock_status_text: String,
|
|
is_restarting: Arc<AtomicBool>,
|
|
subprocess_busy: Arc<AtomicBool>,
|
|
is_closing: Arc<AtomicBool>,
|
|
}
|
|
|
|
impl SteamFrameGpuiApp {
|
|
pub fn new(
|
|
cfg: AppConfig,
|
|
log_buffer: Arc<Mutex<LogBuffer>>,
|
|
engine: Arc<Mutex<FpvEngineController>>,
|
|
controls: EngineControlHandle,
|
|
engine_monitor: Arc<Mutex<RuntimeMonitor>>,
|
|
is_closing: Arc<AtomicBool>,
|
|
) -> Self {
|
|
let log_revision = log_buffer.lock().revision.clone();
|
|
let last_config_revision = controls.config_revision();
|
|
let target_port_buf = cfg.nomad_port.to_string();
|
|
let initial_control_source = ControlSource::from_str(&cfg.control_source);
|
|
|
|
Self {
|
|
cfg,
|
|
engine,
|
|
controls,
|
|
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,
|
|
telem_status: SubsystemStatus::Disabled,
|
|
g29_status: SubsystemStatus::Disabled,
|
|
controller_status: SubsystemStatus::Disabled,
|
|
active_control_source: initial_control_source,
|
|
dvr_status: SubsystemStatus::Stopped,
|
|
dvr_recording: false,
|
|
dvr_elapsed_secs: 0,
|
|
dvr_file_size_bytes: 0,
|
|
dvr_frames_recorded: 0,
|
|
dvr_filename: String::new(),
|
|
video_fps: 0.0,
|
|
video_jitter_ms: 0.0,
|
|
video_dropped_frames: 0,
|
|
video_decoder_name: "auto".to_string(),
|
|
video_frames_total: 0,
|
|
latest_pose: HeadPoseSample::default(),
|
|
latest_telem: TelemetryState::default(),
|
|
latest_g29: G29State::default(),
|
|
latest_controller: SteamControllerState::default(),
|
|
control_switch_error: String::new(),
|
|
profile_feedback: String::new(),
|
|
monitor_source_override: None,
|
|
log_entries: Vec::new(),
|
|
log_err_count: 0,
|
|
log_warn_count: 0,
|
|
last_log_revision: 0,
|
|
last_config_revision,
|
|
target_edit_field: None,
|
|
target_port_buf,
|
|
target_focus_handle: None,
|
|
mock_pan_deg: 0.0,
|
|
mock_tilt_deg: 0.0,
|
|
mock_roll_deg: 0.0,
|
|
mock_continuous: false,
|
|
mock_tracker: None,
|
|
mock_resolving: Arc::new(AtomicBool::new(false)),
|
|
mock_resolved: Arc::new(Mutex::new(None)),
|
|
mock_last_send: None,
|
|
mock_status_text: String::new(),
|
|
is_restarting: Arc::new(AtomicBool::new(false)),
|
|
subprocess_busy: Arc::new(AtomicBool::new(false)),
|
|
is_closing,
|
|
}
|
|
}
|
|
|
|
/// 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;
|
|
self.controls
|
|
.set_preview_active(self.active_tab == ActiveTab::Cockpit);
|
|
|
|
// Synchroniser les réglages éventuellement modifiés depuis le Menu VR / G29 / Steam Controller
|
|
let cfg_rev = self.controls.config_revision();
|
|
if cfg_rev != self.last_config_revision {
|
|
self.last_config_revision = cfg_rev;
|
|
if let Some(live_cfg) = self.controls.snapshot_live_config() {
|
|
self.cfg = live_cfg;
|
|
changed = true;
|
|
}
|
|
}
|
|
|
|
// 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.g29_status != mon.g29_status {
|
|
self.g29_status = mon.g29_status.clone();
|
|
changed = true;
|
|
}
|
|
if self.controller_status != mon.controller_status {
|
|
self.controller_status = mon.controller_status.clone();
|
|
changed = true;
|
|
}
|
|
if self.active_control_source != mon.active_control_source {
|
|
self.active_control_source = mon.active_control_source;
|
|
changed = true;
|
|
}
|
|
if self.dvr_recording != mon.dvr_recording
|
|
|| self.dvr_elapsed_secs != mon.dvr_elapsed_secs
|
|
|| self.dvr_status != mon.dvr_status
|
|
{
|
|
self.dvr_recording = mon.dvr_recording;
|
|
self.dvr_elapsed_secs = mon.dvr_elapsed_secs;
|
|
self.dvr_file_size_bytes = mon.dvr_file_size_bytes;
|
|
self.dvr_frames_recorded = mon.dvr_frames_recorded;
|
|
self.dvr_filename = mon.dvr_filename.clone();
|
|
self.dvr_status = mon.dvr_status.clone();
|
|
changed = true;
|
|
}
|
|
if (self.video_fps - mon.video_fps).abs() > 0.1
|
|
|| (self.video_jitter_ms - mon.video_jitter_ms).abs() > 0.1
|
|
|| self.video_dropped_frames != mon.video_dropped_frames
|
|
|| self.video_decoder_name != mon.video_decoder_name
|
|
{
|
|
self.video_fps = mon.video_fps;
|
|
self.video_jitter_ms = mon.video_jitter_ms;
|
|
self.video_dropped_frames = mon.video_dropped_frames;
|
|
self.video_decoder_name = mon.video_decoder_name.clone();
|
|
changed = true;
|
|
}
|
|
if self.video_frames_total != mon.video_frames_total {
|
|
self.video_frames_total = mon.video_frames_total;
|
|
changed = true;
|
|
}
|
|
let pose_changed = (self.latest_pose.pan_deg - mon.latest_head_pose.pan_deg).abs()
|
|
> 0.1
|
|
|| (self.latest_pose.tilt_deg - mon.latest_head_pose.tilt_deg).abs() > 0.1
|
|
|| (self.latest_pose.roll_deg - mon.latest_head_pose.roll_deg).abs() > 0.1
|
|
|| self.latest_pose.pan_crsf != mon.latest_head_pose.pan_crsf;
|
|
let telem_changed =
|
|
self.latest_telem.packets_received != mon.latest_telemetry.packets_received
|
|
|| self.latest_telem.is_live() != mon.latest_telemetry.is_live();
|
|
if (self.active_tab == ActiveTab::Telemetry || self.active_tab == ActiveTab::Cockpit)
|
|
&& (pose_changed || telem_changed)
|
|
{
|
|
changed = true;
|
|
}
|
|
self.latest_pose = mon.latest_head_pose;
|
|
self.latest_telem = mon.latest_telemetry.clone();
|
|
if self.latest_g29.connected != mon.latest_g29.connected
|
|
|| self.latest_g29.last_button != mon.latest_g29.last_button
|
|
|| (self.active_tab == ActiveTab::Settings
|
|
&& self.latest_g29.packets_received != mon.latest_g29.packets_received)
|
|
{
|
|
changed = true;
|
|
}
|
|
self.latest_g29 = mon.latest_g29.clone();
|
|
|
|
if self.latest_controller.connected != mon.latest_controller.connected
|
|
|| self.latest_controller.armed != mon.latest_controller.armed
|
|
|| self.latest_controller.gear != mon.latest_controller.gear
|
|
|| self.latest_controller.throttle_pct != mon.latest_controller.throttle_pct
|
|
|| self.latest_controller.brake_pct != mon.latest_controller.brake_pct
|
|
|| self.latest_controller.clutch_pct != mon.latest_controller.clutch_pct
|
|
|| self.latest_controller.vibration_pct != mon.latest_controller.vibration_pct
|
|
|| self.latest_controller.rumble_left_pct != mon.latest_controller.rumble_left_pct
|
|
|| self.latest_controller.rumble_right_pct != mon.latest_controller.rumble_right_pct
|
|
|| self.latest_controller.last_button != mon.latest_controller.last_button
|
|
|| (self.latest_controller.steering_norm - mon.latest_controller.steering_norm).abs()
|
|
> 0.005
|
|
|| (self.active_tab == ActiveTab::Settings
|
|
&& self.latest_controller.packets_sent != mon.latest_controller.packets_sent)
|
|
{
|
|
changed = true;
|
|
}
|
|
self.latest_controller = mon.latest_controller.clone();
|
|
|
|
// Récupération directe du tampon BGRA pré-converti par le worker (zéro swizzle UI)
|
|
let frame_data: Option<(u32, u32, Arc<Vec<u8>>)> = if self.active_tab == ActiveTab::Cockpit
|
|
&& mon.preview_frame_seq != self.last_frame_seq
|
|
&& !mon.preview_bgra.is_empty()
|
|
&& mon.preview_width > 0
|
|
&& mon.preview_height > 0
|
|
{
|
|
Some((mon.preview_width, mon.preview_height, Arc::clone(&mon.preview_bgra)))
|
|
} else {
|
|
None
|
|
};
|
|
|
|
(mon.preview_frame_seq, frame_data)
|
|
}; // Verrou `engine_monitor` immédiatement libéré !
|
|
|
|
// Libérer immédiatement les textures GPU lorsqu'on quitte l'onglet Cockpit
|
|
if self.active_tab != ActiveTab::Cockpit {
|
|
if let Some(old) = self.current_render_image.take() {
|
|
let _ = window.drop_image(old);
|
|
}
|
|
for old in self.images_to_drop.drain(..) {
|
|
let _ = window.drop_image(old);
|
|
}
|
|
}
|
|
|
|
// 2. Upload RenderImage GPU direct (pixels déjà en BGRA — plus de swizzle CPU sur thread UI)
|
|
if let Some((w, h, bgra_arc)) = new_frame_data {
|
|
let bgra_buf = match Arc::try_unwrap(bgra_arc) {
|
|
Ok(v) => v,
|
|
Err(shared) => (*shared).clone(),
|
|
};
|
|
if let Some(img_buf) = RgbaImage::from_raw(w, h, bgra_buf) {
|
|
let frame = Frame::new(img_buf);
|
|
let new_render_image = Arc::new(RenderImage::new(smallvec![frame]));
|
|
|
|
if let Some(old) = self.current_render_image.take() {
|
|
self.images_to_drop.push(old);
|
|
}
|
|
self.current_render_image = Some(new_render_image);
|
|
self.last_frame_seq = preview_frame_seq;
|
|
changed = true;
|
|
|
|
while self.images_to_drop.len() > 2 {
|
|
let old_img = self.images_to_drop.remove(0);
|
|
let _ = window.drop_image(old_img);
|
|
}
|
|
}
|
|
}
|
|
|
|
// 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(60).cloned().collect();
|
|
changed = true;
|
|
}
|
|
|
|
// 4. Envoi continu du Mock Manuel Nomad à 50 Hz si activé
|
|
if self.mock_continuous {
|
|
let due = self
|
|
.mock_last_send
|
|
.map(|t| t.elapsed() >= Duration::from_millis(20))
|
|
.unwrap_or(true);
|
|
if due {
|
|
self.send_mock_manual();
|
|
self.mock_last_send = Some(Instant::now());
|
|
changed = true;
|
|
}
|
|
}
|
|
|
|
changed
|
|
}
|
|
|
|
fn run_usb_rndis_setup(&self) {
|
|
if self.subprocess_busy.swap(true, Ordering::AcqRel) {
|
|
log::warn!("[USB RNDIS] Une opération système/SSH est déjà en cours.");
|
|
return;
|
|
}
|
|
log::info!("[USB RNDIS] Exécution du script de configuration réseau...");
|
|
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())
|
|
.or_else(|| {
|
|
let installed = std::path::PathBuf::from("/usr/share/steamframe-fpv/scripts/setup_usb_rndis.sh");
|
|
if installed.exists() {
|
|
Some(installed)
|
|
} else {
|
|
let local = std::path::PathBuf::from("scripts/setup_usb_rndis.sh");
|
|
local.exists().then_some(local)
|
|
}
|
|
});
|
|
let Some(script_path) = script_path else {
|
|
self.subprocess_busy.store(false, Ordering::Release);
|
|
log::error!("[USB RNDIS] Script setup_usb_rndis.sh introuvable à côté du binaire ni dans /usr/share/steamframe-fpv/scripts.");
|
|
return;
|
|
};
|
|
let busy = Arc::clone(&self.subprocess_busy);
|
|
std::thread::spawn(move || {
|
|
let res = Command::new("bash").arg(&script_path).output();
|
|
busy.store(false, Ordering::Release);
|
|
match res {
|
|
Ok(out) => {
|
|
let stdout = String::from_utf8_lossy(&out.stdout);
|
|
log::info!(
|
|
"[USB RNDIS] Résultat (exit={}) :\n{}",
|
|
out.status,
|
|
stdout.trim()
|
|
);
|
|
}
|
|
Err(e) => log::error!("[USB RNDIS] Échec d'exécution du script {:?} : {}", script_path, e),
|
|
}
|
|
});
|
|
}
|
|
|
|
fn configure_radxa_ssh(&self) {
|
|
if self.subprocess_busy.swap(true, Ordering::AcqRel) {
|
|
log::warn!("[Radxa Zero 3W] Une opération système/SSH est déjà en cours.");
|
|
return;
|
|
}
|
|
let ch = self.cfg.wifi_channel;
|
|
let Ok(ip) = self.cfg.radxa_vrx_ip.trim().parse::<std::net::IpAddr>() else {
|
|
self.subprocess_busy.store(false, Ordering::Release);
|
|
log::error!(
|
|
"[Radxa Zero 3W] Adresse IP invalide pour SSH : '{}'",
|
|
self.cfg.radxa_vrx_ip
|
|
);
|
|
return;
|
|
};
|
|
log::info!(
|
|
"[Radxa Zero 3W] Configuration du canal 5.8GHz={} sur root@{}...",
|
|
ch,
|
|
ip
|
|
);
|
|
let remote_cmd = format!(
|
|
"ok=0; \
|
|
if [ -f /etc/wifibroadcast.cfg ]; then sed -i 's/^wifi_channel.*/wifi_channel = {ch}/' /etc/wifibroadcast.cfg && ok=1; fi; \
|
|
for iface in wlan0 wlx*; do if [ -d \"/sys/class/net/$iface\" ]; then iw dev \"$iface\" set channel {ch} HT20 2>/dev/null && ok=1; fi; done; \
|
|
[ \"$ok\" -eq 1 ]"
|
|
);
|
|
let busy = Arc::clone(&self.subprocess_busy);
|
|
std::thread::spawn(move || {
|
|
let res = Command::new("ssh")
|
|
.args([
|
|
"-o",
|
|
"BatchMode=yes",
|
|
"-o",
|
|
"ConnectTimeout=2",
|
|
"-o",
|
|
"StrictHostKeyChecking=accept-new",
|
|
"--",
|
|
&format!("root@{}", ip),
|
|
&remote_cmd,
|
|
])
|
|
.output();
|
|
busy.store(false, Ordering::Release);
|
|
match res {
|
|
Ok(out) if out.status.success() => {
|
|
log::info!("[Radxa Zero 3W] Canal 5.8GHz configuré avec succès sur {}", ip);
|
|
}
|
|
Ok(out) => {
|
|
log::warn!(
|
|
"[Radxa Zero 3W] SSH retour exit={} : {}",
|
|
out.status,
|
|
String::from_utf8_lossy(&out.stderr).trim()
|
|
);
|
|
}
|
|
Err(e) => log::error!("[Radxa Zero 3W] Échec commande SSH : {}", e),
|
|
}
|
|
});
|
|
}
|
|
|
|
/// Envoi de paquet test sur un thread séparé (la résolution mDNS/DNS ne bloque jamais le thread UI GPUI).
|
|
fn test_nomad_packet(&self) {
|
|
let protocol = NomadProtocol::from_str(&self.cfg.ht_protocol);
|
|
let ip = self.cfg.nomad_ip.clone();
|
|
let port = self.cfg.nomad_port;
|
|
let max_pan = self.cfg.max_pan_deg;
|
|
let max_tilt = self.cfg.max_tilt_deg;
|
|
let max_roll = self.cfg.max_roll_deg;
|
|
log::info!(
|
|
"[Wi-Fi Nomad] Envoi d'un paquet de test ({}) vers {}:{}...",
|
|
protocol.label(),
|
|
ip,
|
|
port
|
|
);
|
|
std::thread::spawn(move || {
|
|
match NomadHeadTracker::new(&ip, port, max_pan, max_tilt, max_roll, protocol) {
|
|
Ok(mut ht) => {
|
|
let _ = ht.send_pose(glam::Quat::IDENTITY);
|
|
}
|
|
Err(e) => log::error!("[Wi-Fi Nomad] Cible invalide : {}", e),
|
|
}
|
|
});
|
|
}
|
|
|
|
fn set_nomad_target(&mut self, ip: &str, port: u16, proto: Option<&str>) {
|
|
self.cfg.nomad_ip = ip.to_string();
|
|
self.cfg.nomad_port = port;
|
|
self.target_port_buf = port.to_string();
|
|
if let Some(p) = proto {
|
|
self.cfg.ht_protocol = p.to_string();
|
|
}
|
|
self.target_edit_field = None;
|
|
self.mock_tracker = None;
|
|
log::info!(
|
|
"[Wi-Fi Nomad] Cible réseau mise à jour : {}:{} ({})",
|
|
self.cfg.nomad_ip,
|
|
self.cfg.nomad_port,
|
|
NomadProtocol::from_str(&self.cfg.ht_protocol).label()
|
|
);
|
|
}
|
|
|
|
fn commit_port_buf(&mut self) {
|
|
if let Ok(p) = self.target_port_buf.trim().parse::<u16>() {
|
|
if p >= 1 {
|
|
self.cfg.nomad_port = p;
|
|
self.mock_tracker = None;
|
|
}
|
|
}
|
|
self.target_port_buf = self.cfg.nomad_port.to_string();
|
|
}
|
|
|
|
fn handle_target_key_down(&mut self, ev: &KeyDownEvent) {
|
|
let Some(field) = self.target_edit_field else {
|
|
return;
|
|
};
|
|
let key = ev.keystroke.key.as_str();
|
|
match key {
|
|
"escape" => {
|
|
self.target_port_buf = self.cfg.nomad_port.to_string();
|
|
self.target_edit_field = None;
|
|
}
|
|
"enter" => {
|
|
if field == TargetEditField::Port {
|
|
self.commit_port_buf();
|
|
} else {
|
|
self.mock_tracker = None;
|
|
}
|
|
self.target_edit_field = None;
|
|
}
|
|
"backspace" => {
|
|
match field {
|
|
TargetEditField::Ip => {
|
|
self.cfg.nomad_ip.pop();
|
|
self.mock_tracker = None;
|
|
}
|
|
TargetEditField::Port => {
|
|
self.target_port_buf.pop();
|
|
}
|
|
}
|
|
}
|
|
_ => {
|
|
if let Some(ch_str) = &ev.keystroke.key_char {
|
|
for ch in ch_str.chars() {
|
|
match field {
|
|
TargetEditField::Ip => {
|
|
if ch.is_ascii_alphanumeric() || ch == '.' || ch == '-' || ch == '_' {
|
|
self.cfg.nomad_ip.push(ch);
|
|
self.mock_tracker = None;
|
|
}
|
|
}
|
|
TargetEditField::Port => {
|
|
if ch.is_ascii_digit() && self.target_port_buf.len() < 5 {
|
|
self.target_port_buf.push(ch);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
fn send_mock_manual(&mut self) {
|
|
if self.target_edit_field == Some(TargetEditField::Port) {
|
|
self.commit_port_buf();
|
|
self.target_edit_field = None;
|
|
}
|
|
let protocol = NomadProtocol::from_str(&self.cfg.ht_protocol);
|
|
if self.mock_tracker.is_none() {
|
|
if let Some(res) = self.mock_resolved.lock().take() {
|
|
match res {
|
|
Ok(ht) => self.mock_tracker = Some(ht),
|
|
Err(e) => {
|
|
self.mock_status_text = format!("Erreur cible : {}", e);
|
|
self.mock_continuous = false;
|
|
return;
|
|
}
|
|
}
|
|
} else if self.cfg.nomad_ip.parse::<std::net::IpAddr>().is_ok() {
|
|
match NomadHeadTracker::new(
|
|
&self.cfg.nomad_ip,
|
|
self.cfg.nomad_port,
|
|
self.cfg.max_pan_deg,
|
|
self.cfg.max_tilt_deg,
|
|
self.cfg.max_roll_deg,
|
|
protocol,
|
|
) {
|
|
Ok(ht) => self.mock_tracker = Some(ht),
|
|
Err(e) => {
|
|
self.mock_status_text = format!("Erreur cible : {}", e);
|
|
self.mock_continuous = false;
|
|
return;
|
|
}
|
|
}
|
|
} else {
|
|
if !self.mock_resolving.swap(true, Ordering::AcqRel) {
|
|
let ip = self.cfg.nomad_ip.clone();
|
|
let port = self.cfg.nomad_port;
|
|
let max_pan = self.cfg.max_pan_deg;
|
|
let max_tilt = self.cfg.max_tilt_deg;
|
|
let max_roll = self.cfg.max_roll_deg;
|
|
let resolving = Arc::clone(&self.mock_resolving);
|
|
let resolved = Arc::clone(&self.mock_resolved);
|
|
std::thread::spawn(move || {
|
|
let res = NomadHeadTracker::new(
|
|
&ip, port, max_pan, max_tilt, max_roll, protocol,
|
|
)
|
|
.map_err(|e| e.to_string());
|
|
*resolved.lock() = Some(res);
|
|
resolving.store(false, Ordering::Release);
|
|
});
|
|
}
|
|
self.mock_status_text =
|
|
format!("Résolution DNS/mDNS de {}:{}...", self.cfg.nomad_ip, self.cfg.nomad_port);
|
|
return;
|
|
}
|
|
}
|
|
|
|
if let Some(ht) = self.mock_tracker.as_mut() {
|
|
match ht.send_manual_angles(self.mock_pan_deg, self.mock_tilt_deg, self.mock_roll_deg) {
|
|
Ok(sample) => {
|
|
self.latest_pose = sample;
|
|
if sample.last_send_ok {
|
|
self.mock_status_text = format!(
|
|
"OK #{} -> {}:{} | Pan {} ({}µs) | Tilt {} ({}µs) | Roll {} ({}µs)",
|
|
sample.packets_sent,
|
|
self.cfg.nomad_ip,
|
|
self.cfg.nomad_port,
|
|
sample.pan_crsf,
|
|
NomadHeadTracker::crsf_to_pwm_us(sample.pan_crsf),
|
|
sample.tilt_crsf,
|
|
NomadHeadTracker::crsf_to_pwm_us(sample.tilt_crsf),
|
|
sample.roll_crsf,
|
|
NomadHeadTracker::crsf_to_pwm_us(sample.roll_crsf),
|
|
);
|
|
} else {
|
|
self.mock_status_text = format!(
|
|
"Échec envoi UDP ({} erreurs) vers {}:{}",
|
|
sample.send_errors, self.cfg.nomad_ip, self.cfg.nomad_port
|
|
);
|
|
}
|
|
}
|
|
Err(e) => {
|
|
self.mock_status_text = format!("Erreur : {}", e);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
fn restart_engine_async(&mut self, reason: &'static str) {
|
|
if self.target_edit_field == Some(TargetEditField::Port) {
|
|
self.commit_port_buf();
|
|
}
|
|
self.target_edit_field = None;
|
|
|
|
if self.is_closing.load(Ordering::Acquire) {
|
|
return;
|
|
}
|
|
if self
|
|
.is_restarting
|
|
.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
|
|
.is_err()
|
|
{
|
|
log::warn!("[Moteur FPV] Redémarrage déjà en cours, requête ignorée.");
|
|
return;
|
|
}
|
|
|
|
self.controls.save_full_config(&self.cfg);
|
|
self.last_config_revision = self.controls.config_revision();
|
|
|
|
let engine_clone = Arc::clone(&self.engine);
|
|
let cfg_clone = self.cfg.clone();
|
|
let is_restarting = Arc::clone(&self.is_restarting);
|
|
let is_closing = Arc::clone(&self.is_closing);
|
|
std::thread::spawn(move || {
|
|
{
|
|
let mut eng = engine_clone.lock();
|
|
if !is_closing.load(Ordering::Acquire) {
|
|
log::info!("{}", reason);
|
|
eng.start(cfg_clone);
|
|
}
|
|
}
|
|
is_restarting.store(false, Ordering::Release);
|
|
});
|
|
}
|
|
|
|
fn set_vr_enabled(&mut self, enabled: bool) {
|
|
let target_headless = !enabled;
|
|
if self.cfg.headless == target_headless {
|
|
return;
|
|
}
|
|
if self.is_restarting.load(Ordering::Acquire) {
|
|
log::warn!("[Moteur FPV] Bascule VR ignorée pendant un redémarrage en cours.");
|
|
return;
|
|
}
|
|
self.cfg.headless = target_headless;
|
|
if enabled {
|
|
self.restart_engine_async("[Action Utilisateur] Mode VR (OpenXR) réactivé, redémarrage du moteur FPV...");
|
|
} else {
|
|
self.restart_engine_async("[Action Utilisateur] Mode VR désactivé (Mode Bureau léger), redémarrage du moteur FPV...");
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Drop for SteamFrameGpuiApp {
|
|
fn drop(&mut self) {
|
|
self.is_closing.store(true, Ordering::Release);
|
|
log::info!("[SteamFrameGpuiApp] Fermeture de l'interface IHM, arrêt propre du moteur FPV...");
|
|
self.engine.lock().stop();
|
|
}
|
|
}
|
|
|
|
impl Render for SteamFrameGpuiApp {
|
|
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
|
if self.target_focus_handle.is_none() {
|
|
self.target_focus_handle = Some(cx.focus_handle());
|
|
}
|
|
div()
|
|
.flex()
|
|
.flex_col()
|
|
.size_full()
|
|
.bg(rgb(COLOR_BG_DARK))
|
|
.text_color(rgb(COLOR_TEXT_MAIN))
|
|
.p_3()
|
|
.gap_3()
|
|
.overflow_hidden()
|
|
// 1. HEADER COCKPIT BAR AVEC MENU D'ONGLETS
|
|
.child(self.render_header(cx))
|
|
// 2. VUE ACTIVE (Cockpit plein format, Réglages, Télémétrie, Logs)
|
|
.child(
|
|
div()
|
|
.flex()
|
|
.flex_col()
|
|
.flex_1()
|
|
.min_h_0()
|
|
.min_w_0()
|
|
.overflow_hidden()
|
|
.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(),
|
|
}),
|
|
)
|
|
}
|
|
}
|
|
|
|
impl SteamFrameGpuiApp {
|
|
// -------------------------------------------------------------------------
|
|
// 1. Barre Supérieure (Header & Navigation par Onglets)
|
|
// -------------------------------------------------------------------------
|
|
fn render_header(&self, cx: &mut Context<Self>) -> impl IntoElement {
|
|
div()
|
|
.flex()
|
|
.flex_row()
|
|
.flex_wrap()
|
|
.justify_between()
|
|
.items_center()
|
|
.bg(rgb(COLOR_SURFACE_CARD))
|
|
.border_1()
|
|
.border_color(rgb(COLOR_BORDER_SUBTLE))
|
|
.rounded_xl()
|
|
.px_3()
|
|
.py_2()
|
|
.gap_2()
|
|
// GAUCHE : Identité & Badges Statut
|
|
.child(
|
|
div()
|
|
.flex()
|
|
.flex_wrap()
|
|
.items_center()
|
|
.gap_2p5()
|
|
.child(
|
|
div()
|
|
.text_base()
|
|
.font_weight(gpui::FontWeight::BOLD)
|
|
.text_color(rgb(COLOR_CYAN))
|
|
.child(concat!("🥽 SteamFrame FPV v", env!("CARGO_PKG_VERSION"))),
|
|
)
|
|
.child(self.render_status_badge("VRX", &self.usb_status))
|
|
.child(self.render_status_badge("VR", &self.xr_status))
|
|
.child(self.render_status_badge("DVR", &self.dvr_status)),
|
|
)
|
|
// CENTRE : Barre d'onglets épurée
|
|
.child(
|
|
div()
|
|
.flex()
|
|
.flex_wrap()
|
|
.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()
|
|
.flex_wrap()
|
|
.items_center()
|
|
.gap_2()
|
|
.child(
|
|
div()
|
|
.id("toggle_ctrl_source_quick")
|
|
.px_2()
|
|
.py_0p5()
|
|
.bg(if self.active_control_source == ControlSource::SteamController {
|
|
rgb(0x132738)
|
|
} else {
|
|
rgb(COLOR_SURFACE_ELEVATED)
|
|
})
|
|
.border_1()
|
|
.border_color(if self.active_control_source == ControlSource::SteamController {
|
|
rgb(COLOR_CYAN)
|
|
} else {
|
|
rgb(COLOR_ORANGE)
|
|
})
|
|
.rounded_md()
|
|
.text_xs()
|
|
.font_weight(gpui::FontWeight::SEMIBOLD)
|
|
.text_color(if self.active_control_source == ControlSource::SteamController {
|
|
rgb(COLOR_CYAN)
|
|
} else {
|
|
rgb(COLOR_ORANGE)
|
|
})
|
|
.cursor_pointer()
|
|
.on_click(cx.listener(|this, _, _, cx| {
|
|
let next = match this.active_control_source {
|
|
ControlSource::G29 => ControlSource::SteamController,
|
|
ControlSource::SteamController => ControlSource::G29,
|
|
};
|
|
this.switch_control_source(next);
|
|
cx.notify();
|
|
}))
|
|
.child(match self.active_control_source {
|
|
ControlSource::G29 => "🏎️ G29",
|
|
ControlSource::SteamController => "🎮 Steam",
|
|
}),
|
|
)
|
|
.child(
|
|
div()
|
|
.id("toggle_vr_quick")
|
|
.cursor_pointer()
|
|
.on_click(cx.listener(|this, _, _, cx| {
|
|
let vr_on = this.cfg.headless;
|
|
this.set_vr_enabled(vr_on);
|
|
cx.notify();
|
|
}))
|
|
.child(self.render_toggle_pill(
|
|
"🥽 VR",
|
|
!self.cfg.headless,
|
|
rgb(COLOR_CYAN),
|
|
)),
|
|
)
|
|
.child(
|
|
div()
|
|
.id("toggle_ht_quick")
|
|
.cursor_pointer()
|
|
.on_click(cx.listener(|this, _, _, cx| {
|
|
this.cfg.head_tracking_enabled = !this.cfg.head_tracking_enabled;
|
|
this.controls
|
|
.set_head_tracking_enabled(this.cfg.head_tracking_enabled);
|
|
cx.notify();
|
|
}))
|
|
.child(self.render_toggle_pill(
|
|
"🎯 Suivi",
|
|
self.cfg.head_tracking_enabled,
|
|
rgb(COLOR_GREEN),
|
|
)),
|
|
)
|
|
.child(
|
|
div()
|
|
.id("toggle_telem_quick")
|
|
.cursor_pointer()
|
|
.on_click(cx.listener(|this, _, _, cx| {
|
|
this.cfg.telemetry_enabled = !this.cfg.telemetry_enabled;
|
|
this.controls
|
|
.set_telemetry_enabled(this.cfg.telemetry_enabled);
|
|
cx.notify();
|
|
}))
|
|
.child(self.render_toggle_pill(
|
|
"📶 OSD",
|
|
self.cfg.telemetry_enabled,
|
|
rgb(COLOR_CYAN),
|
|
)),
|
|
)
|
|
.child(
|
|
div()
|
|
.id("btn_vr_menu_quick")
|
|
.cursor_pointer()
|
|
.on_click(cx.listener(|this, _, _, cx| {
|
|
this.controls.toggle_vr_menu();
|
|
cx.notify();
|
|
}))
|
|
.child(self.render_toggle_pill(
|
|
"📋 Menu VR",
|
|
self.controls.is_vr_menu_open(),
|
|
rgb(COLOR_ORANGE),
|
|
)),
|
|
)
|
|
.child(
|
|
div()
|
|
.id("btn_tare_quick")
|
|
.px_2p5()
|
|
.py_1()
|
|
.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.controls.request_recenter();
|
|
cx.notify();
|
|
}))
|
|
.child("🎯 Tare"),
|
|
)
|
|
.child(
|
|
div()
|
|
.id("btn_dvr_quick")
|
|
.px_2p5()
|
|
.py_1()
|
|
.bg(if self.dvr_recording { rgb(COLOR_RED) } else { rgb(COLOR_SURFACE_ELEVATED) })
|
|
.border_1()
|
|
.border_color(if self.dvr_recording { rgb(COLOR_RED) } else { rgb(COLOR_BORDER_SUBTLE) })
|
|
.rounded_md()
|
|
.text_xs()
|
|
.font_weight(gpui::FontWeight::SEMIBOLD)
|
|
.text_color(if self.dvr_recording { rgb(0xffffff) } else { rgb(COLOR_TEXT_MAIN) })
|
|
.cursor_pointer()
|
|
.on_click(cx.listener(|this, _, _, cx| {
|
|
if this.dvr_recording {
|
|
this.controls.stop_dvr();
|
|
} else {
|
|
this.controls.start_dvr();
|
|
}
|
|
cx.notify();
|
|
}))
|
|
.child(if self.dvr_recording {
|
|
let mins = self.dvr_elapsed_secs / 60;
|
|
let secs = self.dvr_elapsed_secs % 60;
|
|
let mb = self.dvr_file_size_bytes as f64 / (1024.0 * 1024.0);
|
|
format!("⏹ DVR ({:02}:{:02} - {:.1}Mo)", mins, secs, mb)
|
|
} else {
|
|
"🔴 DVR".to_string()
|
|
}),
|
|
),
|
|
)
|
|
}
|
|
|
|
fn switch_control_source(&mut self, target: ControlSource) {
|
|
match self.controls.set_control_source(target) {
|
|
Ok(()) => {
|
|
self.active_control_source = target;
|
|
self.cfg.control_source = target.as_str().to_string();
|
|
self.control_switch_error.clear();
|
|
}
|
|
Err(msg) => {
|
|
self.control_switch_error = msg;
|
|
}
|
|
}
|
|
}
|
|
|
|
fn render_nav_tab(&self, label: &str, tab: ActiveTab, cx: &mut Context<Self>) -> 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
|
|
// -------------------------------------------------------------------------
|
|
}
|
|
|
|
|
|
pub fn run_gpui_app(cfg: AppConfig, log_buffer: Arc<Mutex<LogBuffer>>) -> Result<()> {
|
|
Application::new().run(move |cx: &mut App| {
|
|
let mut engine =
|
|
FpvEngineController::new(cfg.telemetry_enabled, cfg.head_tracking_enabled);
|
|
engine.start(cfg.clone());
|
|
let controls = engine.control_handle();
|
|
let engine_monitor = Arc::clone(&engine.monitor);
|
|
let engine = Arc::new(Mutex::new(engine));
|
|
let engine_for_close = Arc::clone(&engine);
|
|
let is_closing = Arc::new(AtomicBool::new(false));
|
|
let is_closing_for_window = Arc::clone(&is_closing);
|
|
|
|
cx.on_window_closed(move |cx| {
|
|
if cx.windows().is_empty() {
|
|
log::info!("[GPUI] Dernière fenêtre fermée, arrêt propre et complet du moteur FPV...");
|
|
is_closing_for_window.store(true, Ordering::Release);
|
|
engine_for_close.lock().stop();
|
|
cx.quit();
|
|
}
|
|
})
|
|
.detach();
|
|
|
|
let bounds = Bounds::centered(None, size(px(1240.0), px(820.0)), cx);
|
|
|
|
let window_res = cx.open_window(
|
|
WindowOptions {
|
|
window_bounds: Some(WindowBounds::Windowed(bounds)),
|
|
titlebar: None,
|
|
..Default::default()
|
|
},
|
|
|window, cx| {
|
|
// Création du modèle réactif de l'application
|
|
let app_view = cx.new(|_| {
|
|
SteamFrameGpuiApp::new(
|
|
cfg.clone(),
|
|
log_buffer.clone(),
|
|
engine,
|
|
controls,
|
|
engine_monitor,
|
|
is_closing,
|
|
)
|
|
});
|
|
|
|
// Boucle de rafraîchissement 60 FPS synchronisée avec le moteur FPV
|
|
let weak_view = app_view.downgrade();
|
|
window
|
|
.spawn(cx, async move |cx| {
|
|
loop {
|
|
Timer::after(Duration::from_millis(16)).await;
|
|
let should_continue = cx
|
|
.update(|window, cx| {
|
|
if let Some(view) = weak_view.upgrade() {
|
|
let mut exit_now = false;
|
|
view.update(cx, |this, cx| {
|
|
if this.controls.is_exit_requested()
|
|
|| crate::is_shutdown_requested()
|
|
{
|
|
exit_now = true;
|
|
return;
|
|
}
|
|
if this.sync_from_engine(window) {
|
|
cx.notify();
|
|
}
|
|
});
|
|
if exit_now {
|
|
window.remove_window();
|
|
return false;
|
|
}
|
|
true
|
|
} else {
|
|
false
|
|
}
|
|
})
|
|
.unwrap_or(false);
|
|
|
|
if !should_continue {
|
|
break;
|
|
}
|
|
}
|
|
})
|
|
.detach();
|
|
|
|
app_view
|
|
},
|
|
);
|
|
|
|
if let Err(e) = window_res {
|
|
log::error!("Échec d'ouverture de la fenêtre GPUI : {:?}", e);
|
|
}
|
|
|
|
cx.activate(true);
|
|
});
|
|
|
|
Ok(())
|
|
}
|