mirror of
https://github.com/bleackstorm/SteamFrame-FPV-Control-Center.git
synced 2026-12-03 07:31:57 +01:00
911 lines
35 KiB
Rust
911 lines
35 KiB
Rust
use anyhow::{Context, Result};
|
|
use clap::{parser::ValueSource, CommandFactory, FromArgMatches, Parser};
|
|
use std::collections::HashMap;
|
|
use std::fs;
|
|
use std::path::{Path, PathBuf};
|
|
|
|
#[derive(Parser, Debug, Clone)]
|
|
#[command(author, version, about)]
|
|
pub struct AppConfig {
|
|
/// Mode d'acquisition vidéo USB depuis le VRX Radxa Zero 3W :
|
|
/// "rndis" (Câble USB-C OTG direct -> flux RTP UDP :5600) ou "uvc" (Mini-HDMI -> Carte capture USB /dev/video0)
|
|
#[arg(long, default_value = "rndis")]
|
|
pub usb_video_mode: String,
|
|
|
|
/// Périphérique V4L2 si usb_video_mode = "uvc" (carte d'acquisition Mini-HDMI vers USB-C)
|
|
#[arg(long, default_value = "/dev/video0")]
|
|
pub uvc_device: String,
|
|
|
|
/// Adresse IP d'écoute de l'interface USB RNDIS (0.0.0.0 écoute sur usb0 et toutes les interfaces)
|
|
#[arg(long, default_value = "0.0.0.0")]
|
|
pub usb_bind_ip: String,
|
|
|
|
/// Adresse IP de la carte Radxa Zero 3W (VRX OpenIPC) sur le réseau USB OTG
|
|
#[arg(long, default_value = "192.168.1.1")]
|
|
pub radxa_vrx_ip: String,
|
|
|
|
/// Canal 5.8 GHz du récepteur RTL8812EU (Défaut usine Sphere Link : 161)
|
|
#[arg(long, default_value_t = 161)]
|
|
pub wifi_channel: u16,
|
|
|
|
/// Profil de résolution/FPS du VRX Sphere Link ("720p60", "1080p60", "1080p90", "720p120")
|
|
#[arg(long, default_value = "720p60")]
|
|
pub vrx_video_profile: String,
|
|
|
|
/// Port UDP du flux RTP OpenIPC envoyé par le VRX Eachine Sphere Link
|
|
#[arg(long, default_value_t = 5600)]
|
|
pub video_udp_port: u16,
|
|
|
|
/// Activer ou désactiver la réception de télémétrie UDP et l'incrustation OSD (ON/OFF)
|
|
#[arg(long, default_value_t = false)]
|
|
pub telemetry_enabled: bool,
|
|
|
|
/// Port UDP d'écoute pour la télémétrie MAVLink / CRSF (OSD)
|
|
#[arg(long, default_value_t = 14551)]
|
|
pub telemetry_udp_port: u16,
|
|
|
|
/// Activer la passerelle Wi-Fi UDP du volant Logitech G29 (g29_crsf)
|
|
#[arg(long, default_value_t = true)]
|
|
pub g29_enabled: bool,
|
|
|
|
/// Port UDP d'écoute pour la télémétrie et les boutons du volant G29
|
|
#[arg(long, default_value_t = 14552)]
|
|
pub g29_udp_port: u16,
|
|
|
|
/// Source active de pilotage : "g29" (Volant Logitech G29) ou "steam" (Steam Controller via PC/Steam Frame)
|
|
#[arg(long, default_value = "g29")]
|
|
pub control_source: String,
|
|
|
|
/// Périphérique evdev explicite pour le Steam Controller (vide = détection automatique)
|
|
#[arg(long, default_value = "")]
|
|
pub controller_device: String,
|
|
|
|
/// Expo de direction du Steam Controller (0.0 = linéaire, 0.25 = doux au centre, max 0.8)
|
|
#[arg(long, default_value_t = 0.25)]
|
|
pub controller_expo: f32,
|
|
|
|
/// Zone morte du stick gauche du Steam Controller (0.0..0.45)
|
|
#[arg(long, default_value_t = 0.08)]
|
|
pub controller_deadzone: f32,
|
|
|
|
/// Inverser le sens de direction du Steam Controller
|
|
#[arg(long, default_value_t = false)]
|
|
pub controller_invert_steering: bool,
|
|
|
|
/// Courbe exponentielle de la gâchette de gaz Steam Controller (0.0 = linéaire, 0.5 = crawler doux, max 0.8)
|
|
#[arg(long, default_value_t = 0.0)]
|
|
pub controller_throttle_expo: f32,
|
|
|
|
/// Mode Précision / Rampant (plafonne la course des gaz à 50 % pour les franchissements techniques)
|
|
#[arg(long, default_value_t = false)]
|
|
pub controller_crawl_mode: bool,
|
|
|
|
/// Intensité des vibrations haptiques du Steam Controller (0 = désactivé, 1..=100%)
|
|
#[arg(long, default_value_t = 100)]
|
|
pub controller_vibration: u8,
|
|
|
|
/// Seuil CRSF de démarrage des gaz en marche avant (1ère, 2ème, 3ème)
|
|
#[arg(long, default_value_t = 1065)]
|
|
pub gaz_avant_min: u16,
|
|
|
|
/// Plafond CRSF de la 1ère vitesse (Manœuvre)
|
|
#[arg(long, default_value_t = 1100)]
|
|
pub gear_1_max: u16,
|
|
|
|
/// Plafond CRSF de la 2ème vitesse (Normale)
|
|
#[arg(long, default_value_t = 1150)]
|
|
pub gear_2_max: u16,
|
|
|
|
/// Plafond CRSF de la 3ème vitesse (Rapide)
|
|
#[arg(long, default_value_t = 1220)]
|
|
pub gear_3_max: u16,
|
|
|
|
/// Seuil CRSF de démarrage des gaz en marche arrière (R)
|
|
#[arg(long, default_value_t = 905)]
|
|
pub gaz_arriere_min: u16,
|
|
|
|
/// Plafond CRSF de la marche arrière (R)
|
|
#[arg(long, default_value_t = 800)]
|
|
pub gear_reverse_max: u16,
|
|
|
|
/// Codec vidéo reçu depuis le VRX OpenIPC / Ruby ("h264" ou "h265")
|
|
#[arg(long, default_value = "h264")]
|
|
pub codec: String,
|
|
|
|
/// Format de transport du flux vidéo UDP : "raw" (flux NAL direct Ruby FPV / OpenIPC) ou "rtp" (flux RTP standard)
|
|
#[arg(long, default_value = "raw")]
|
|
pub stream_transport: String,
|
|
|
|
/// Mode de projection VR : "dome" (Sphérique 140° Equirect2), "cylinder" (Incurvé 140°), ou "flat" (Quad plat)
|
|
#[arg(long, default_value = "dome")]
|
|
pub projection_mode: String,
|
|
|
|
/// Champ de vision horizontal (FOV en degrés) de la caméra Eachine Sphere Link
|
|
#[arg(long, default_value_t = 140.0)]
|
|
pub camera_fov_deg: f32,
|
|
|
|
/// Coefficient de correction radiale k1 de la lentille M12 140° (0.0 = désactivé, ex: -0.14)
|
|
#[arg(long, default_value_t = -0.14, allow_hyphen_values = true)]
|
|
pub lens_k1: f32,
|
|
|
|
/// Coefficient de correction radiale k2 de la lentille M12 140°
|
|
#[arg(long, default_value_t = 0.03, allow_hyphen_values = true)]
|
|
pub lens_k2: f32,
|
|
|
|
/// Largeur de la texture swapchain OpenXR (résolution vidéo cible)
|
|
#[arg(long, default_value_t = 1280)]
|
|
pub video_width: u32,
|
|
|
|
/// Hauteur de la texture swapchain OpenXR (résolution vidéo cible)
|
|
#[arg(long, default_value_t = 720)]
|
|
pub video_height: u32,
|
|
|
|
/// Rayon du dôme / cylindre ou distance virtuelle de l'écran FPV devant les yeux en mètres
|
|
#[arg(long, default_value_t = 1.6)]
|
|
pub screen_distance_m: f32,
|
|
|
|
/// Largeur virtuelle de l'écran FPV en mètres (utilisé en mode flat/quad)
|
|
#[arg(long, default_value_t = 3.2)]
|
|
pub screen_width_m: f32,
|
|
|
|
/// Activer ou désactiver l'émetteur Head-Tracking vers le RadioMaster Nomad (ON/OFF)
|
|
#[arg(long, default_value_t = false)]
|
|
pub head_tracking_enabled: bool,
|
|
|
|
/// Adresse IP du pont unifié G29/Radxa (192.168.1.1) ou du Backpack Wi-Fi Nomad (10.0.0.1)
|
|
#[arg(long, default_value = "192.168.1.1")]
|
|
pub nomad_ip: String,
|
|
|
|
/// Port UDP cible du Head-Tracking (14552 = pont unifié Radxa/G29, 14550 = Backpack Nomad)
|
|
#[arg(long, default_value_t = 14552)]
|
|
pub nomad_port: u16,
|
|
|
|
/// Protocole Head-Tracking / Données : "g29" (pont unifié $HT), "msp", "crsf" ou "mavlink"
|
|
#[arg(long, default_value = "g29")]
|
|
pub ht_protocol: String,
|
|
|
|
/// Angle maximal Pan (Lacet/Yaw) en degrés correspondant à la course complète servo (172..1811 CRSF)
|
|
#[arg(long, default_value_t = 90.0)]
|
|
pub max_pan_deg: f32,
|
|
|
|
/// Angle maximal Tilt (Tangage/Pitch) en degrés
|
|
#[arg(long, default_value_t = 60.0)]
|
|
pub max_tilt_deg: f32,
|
|
|
|
/// Angle maximal Roll (Roulis) en degrés
|
|
#[arg(long, default_value_t = 45.0)]
|
|
pub max_roll_deg: f32,
|
|
|
|
/// Forcer le mode sans affichage VR (Headless) uniquement pour tester le Head-Tracking
|
|
#[arg(long, default_value_t = false)]
|
|
pub headless: bool,
|
|
|
|
/// Dossier d'enregistrement des vidéos DVR (ex: "recordings/")
|
|
#[arg(long, default_value = "recordings")]
|
|
pub dvr_dir: String,
|
|
|
|
/// Format de conteneur DVR : "mkv" (Matroska résistant aux coupures) ou "mp4"
|
|
#[arg(long, default_value = "mkv")]
|
|
pub dvr_format: String,
|
|
|
|
/// Mode d'enregistrement DVR : "copy" (flux H.264/H.265 direct 0% CPU) ou "composited" (avec OSD incrusté)
|
|
#[arg(long, default_value = "copy")]
|
|
pub dvr_mode: String,
|
|
|
|
/// Désactiver l'interface graphique de monitoring (lancer directement en ligne de commande)
|
|
#[arg(long, default_value_t = false)]
|
|
pub no_gui: bool,
|
|
|
|
/// Mode VR natif direct sans fenêtre 2D GPUI (idéal pour le Mode Gaming SteamOS sur Steam Frame)
|
|
#[arg(long, default_value_t = false)]
|
|
pub vr_only: bool,
|
|
|
|
/// Nombre de cellules LiPo (0 = auto-détection 2S..6S selon tension initiale, sinon 2..=6)
|
|
#[arg(long, default_value_t = 0)]
|
|
pub battery_cells: u8,
|
|
|
|
/// Seuil d'avertissement batterie par cellule en Volts (jaune)
|
|
#[arg(long, default_value_t = 3.5)]
|
|
pub battery_warn_cell_v: f32,
|
|
|
|
/// Seuil critique batterie par cellule en Volts (rouge + alerte haptique)
|
|
#[arg(long, default_value_t = 3.3)]
|
|
pub battery_crit_cell_v: f32,
|
|
|
|
/// Afficher les métriques de lien vidéo (FPS, Jitter, Drops) dans l'OSD VR
|
|
#[arg(long, default_value_t = true)]
|
|
pub osd_show_video_stats: bool,
|
|
|
|
/// Afficher les informations GPS / Mode de vol CRSF dans l'OSD VR
|
|
#[arg(long, default_value_t = true)]
|
|
pub osd_show_gps: bool,
|
|
|
|
/// Nom du profil véhicule actif (vide = personnalisé)
|
|
#[arg(long, default_value = "")]
|
|
pub active_profile: String,
|
|
|
|
/// Luminosité image GPU temps réel (-0.5..=0.5)
|
|
#[arg(long, default_value_t = 0.0, allow_hyphen_values = true)]
|
|
pub video_brightness: f32,
|
|
|
|
/// Contraste image GPU temps réel (0.5..=2.0)
|
|
#[arg(long, default_value_t = 1.0)]
|
|
pub video_contrast: f32,
|
|
|
|
/// Correction gamma image GPU temps réel (0.5..=2.2)
|
|
#[arg(long, default_value_t = 1.0)]
|
|
pub video_gamma: f32,
|
|
|
|
/// Netteté adaptative CAS-lite sur GPU (0.0..=1.0)
|
|
#[arg(long, default_value_t = 0.0)]
|
|
pub video_sharpness: f32,
|
|
|
|
/// Stabilisation horizon 2D sur GPU pilotée par le roulis télémétrie CRSF
|
|
#[arg(long, default_value_t = false)]
|
|
pub horizon_stabilization: bool,
|
|
|
|
/// Mode Caméra 3D Stéréo Side-by-Side (œil gauche / œil droit séparés en OpenXR)
|
|
#[arg(long, default_value_t = false)]
|
|
pub stereo_sbs: bool,
|
|
|
|
/// Active la négociation zéro-copie DMA-BUF entre décodeur matériel GStreamer et Vulkan
|
|
#[arg(long, default_value_t = false)]
|
|
pub zero_copy_dmabuf: bool,
|
|
|
|
/// Active le traceur de latence GStreamer natif (`GST_TRACERS=latency`) dans les logs
|
|
#[arg(long, default_value_t = false)]
|
|
pub gst_latency_trace: bool,
|
|
|
|
/// Chemin du fichier journal d'erreurs et de diagnostic
|
|
#[arg(long, default_value = "steamframe_fpv.log")]
|
|
pub log_file: String,
|
|
}
|
|
|
|
/// Profil véhicule regroupant vitesses CRSF, direction, optique VR, batterie et contrôleur.
|
|
#[derive(Debug, Clone, PartialEq)]
|
|
pub struct VehicleProfile {
|
|
pub name: String,
|
|
pub control_source: String,
|
|
pub controller_expo: f32,
|
|
pub controller_deadzone: f32,
|
|
pub controller_invert_steering: bool,
|
|
pub gaz_avant_min: u16,
|
|
pub gear_1_max: u16,
|
|
pub gear_2_max: u16,
|
|
pub gear_3_max: u16,
|
|
pub gaz_arriere_min: u16,
|
|
pub gear_reverse_max: u16,
|
|
pub projection_mode: String,
|
|
pub camera_fov_deg: f32,
|
|
pub lens_k1: f32,
|
|
pub screen_distance_m: f32,
|
|
pub battery_cells: u8,
|
|
}
|
|
|
|
impl VehicleProfile {
|
|
pub fn builtin_presets() -> Vec<Self> {
|
|
vec![
|
|
Self {
|
|
name: "Crawler 3S".to_string(),
|
|
control_source: "g29".to_string(),
|
|
controller_expo: 0.35,
|
|
controller_deadzone: 0.08,
|
|
controller_invert_steering: false,
|
|
gaz_avant_min: 1055,
|
|
gear_1_max: 1090,
|
|
gear_2_max: 1130,
|
|
gear_3_max: 1180,
|
|
gaz_arriere_min: 915,
|
|
gear_reverse_max: 840,
|
|
projection_mode: "dome".to_string(),
|
|
camera_fov_deg: 140.0,
|
|
lens_k1: -0.14,
|
|
screen_distance_m: 1.6,
|
|
battery_cells: 3,
|
|
},
|
|
Self {
|
|
name: "Buggy 4S".to_string(),
|
|
control_source: "steam".to_string(),
|
|
controller_expo: 0.25,
|
|
controller_deadzone: 0.06,
|
|
controller_invert_steering: false,
|
|
gaz_avant_min: 1065,
|
|
gear_1_max: 1120,
|
|
gear_2_max: 1200,
|
|
gear_3_max: 1320,
|
|
gaz_arriere_min: 905,
|
|
gear_reverse_max: 780,
|
|
projection_mode: "dome".to_string(),
|
|
camera_fov_deg: 140.0,
|
|
lens_k1: -0.14,
|
|
screen_distance_m: 1.6,
|
|
battery_cells: 4,
|
|
},
|
|
Self {
|
|
name: "Aile FPV".to_string(),
|
|
control_source: "steam".to_string(),
|
|
controller_expo: 0.15,
|
|
controller_deadzone: 0.05,
|
|
controller_invert_steering: false,
|
|
gaz_avant_min: 1065,
|
|
gear_1_max: 1180,
|
|
gear_2_max: 1350,
|
|
gear_3_max: 1650,
|
|
gaz_arriere_min: 905,
|
|
gear_reverse_max: 800,
|
|
projection_mode: "cylinder".to_string(),
|
|
camera_fov_deg: 150.0,
|
|
lens_k1: -0.10,
|
|
screen_distance_m: 1.8,
|
|
battery_cells: 0, // Auto 3S..6S
|
|
},
|
|
]
|
|
}
|
|
|
|
pub fn from_config(name: impl Into<String>, cfg: &AppConfig) -> Self {
|
|
Self {
|
|
name: name.into(),
|
|
control_source: cfg.control_source.clone(),
|
|
controller_expo: cfg.controller_expo,
|
|
controller_deadzone: cfg.controller_deadzone,
|
|
controller_invert_steering: cfg.controller_invert_steering,
|
|
gaz_avant_min: cfg.gaz_avant_min,
|
|
gear_1_max: cfg.gear_1_max,
|
|
gear_2_max: cfg.gear_2_max,
|
|
gear_3_max: cfg.gear_3_max,
|
|
gaz_arriere_min: cfg.gaz_arriere_min,
|
|
gear_reverse_max: cfg.gear_reverse_max,
|
|
projection_mode: cfg.projection_mode.clone(),
|
|
camera_fov_deg: cfg.camera_fov_deg,
|
|
lens_k1: cfg.lens_k1,
|
|
screen_distance_m: cfg.screen_distance_m,
|
|
battery_cells: cfg.battery_cells,
|
|
}
|
|
}
|
|
|
|
pub fn apply_to(&self, cfg: &mut AppConfig) {
|
|
cfg.active_profile = self.name.clone();
|
|
cfg.control_source = self.control_source.clone();
|
|
cfg.controller_expo = self.controller_expo;
|
|
cfg.controller_deadzone = self.controller_deadzone;
|
|
cfg.controller_invert_steering = self.controller_invert_steering;
|
|
cfg.gaz_avant_min = self.gaz_avant_min;
|
|
cfg.gear_1_max = self.gear_1_max;
|
|
cfg.gear_2_max = self.gear_2_max;
|
|
cfg.gear_3_max = self.gear_3_max;
|
|
cfg.gaz_arriere_min = self.gaz_arriere_min;
|
|
cfg.gear_reverse_max = self.gear_reverse_max;
|
|
cfg.projection_mode = self.projection_mode.clone();
|
|
cfg.camera_fov_deg = self.camera_fov_deg;
|
|
cfg.lens_k1 = self.lens_k1;
|
|
cfg.screen_distance_m = self.screen_distance_m;
|
|
cfg.battery_cells = self.battery_cells;
|
|
}
|
|
|
|
pub fn profiles_dir() -> Option<PathBuf> {
|
|
AppConfig::default_config_path()
|
|
.and_then(|p| p.parent().map(|d| d.join("profiles")))
|
|
}
|
|
|
|
pub fn sanitize_filename(name: &str) -> String {
|
|
let s: String = name
|
|
.chars()
|
|
.map(|c| {
|
|
if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
|
|
c.to_ascii_lowercase()
|
|
} else {
|
|
'_'
|
|
}
|
|
})
|
|
.collect();
|
|
let trimmed = s.trim_matches('_');
|
|
if trimmed.is_empty() {
|
|
"custom".to_string()
|
|
} else {
|
|
trimmed.to_string()
|
|
}
|
|
}
|
|
|
|
pub fn to_toml_string(&self) -> String {
|
|
format!(
|
|
"name = \"{}\"\n\
|
|
control_source = \"{}\"\n\
|
|
controller_expo = {:.3}\n\
|
|
controller_deadzone = {:.3}\n\
|
|
controller_invert_steering = {}\n\
|
|
gaz_avant_min = {}\n\
|
|
gear_1_max = {}\n\
|
|
gear_2_max = {}\n\
|
|
gear_3_max = {}\n\
|
|
gaz_arriere_min = {}\n\
|
|
gear_reverse_max = {}\n\
|
|
projection_mode = \"{}\"\n\
|
|
camera_fov_deg = {:.2}\n\
|
|
lens_k1 = {:.4}\n\
|
|
screen_distance_m = {:.3}\n\
|
|
battery_cells = {}\n",
|
|
self.name.replace('"', "\\\""),
|
|
self.control_source,
|
|
self.controller_expo,
|
|
self.controller_deadzone,
|
|
self.controller_invert_steering,
|
|
self.gaz_avant_min,
|
|
self.gear_1_max,
|
|
self.gear_2_max,
|
|
self.gear_3_max,
|
|
self.gaz_arriere_min,
|
|
self.gear_reverse_max,
|
|
self.projection_mode,
|
|
self.camera_fov_deg,
|
|
self.lens_k1,
|
|
self.screen_distance_m,
|
|
self.battery_cells,
|
|
)
|
|
}
|
|
|
|
pub fn parse_toml(raw: &str) -> Option<Self> {
|
|
let map = AppConfig::parse_toml_kv(raw);
|
|
let name = map.get("name")?.clone();
|
|
let mut base = Self::builtin_presets()[0].clone();
|
|
base.name = name;
|
|
if let Some(v) = map.get("control_source") { base.control_source = v.clone(); }
|
|
if let Some(v) = map.get("controller_expo").and_then(|s| s.parse().ok()) { base.controller_expo = v; }
|
|
if let Some(v) = map.get("controller_deadzone").and_then(|s| s.parse().ok()) { base.controller_deadzone = v; }
|
|
if let Some(v) = map.get("controller_invert_steering").and_then(|s| s.parse().ok()) { base.controller_invert_steering = v; }
|
|
if let Some(v) = map.get("gaz_avant_min").and_then(|s| s.parse().ok()) { base.gaz_avant_min = v; }
|
|
if let Some(v) = map.get("gear_1_max").and_then(|s| s.parse().ok()) { base.gear_1_max = v; }
|
|
if let Some(v) = map.get("gear_2_max").and_then(|s| s.parse().ok()) { base.gear_2_max = v; }
|
|
if let Some(v) = map.get("gear_3_max").and_then(|s| s.parse().ok()) { base.gear_3_max = v; }
|
|
if let Some(v) = map.get("gaz_arriere_min").and_then(|s| s.parse().ok()) { base.gaz_arriere_min = v; }
|
|
if let Some(v) = map.get("gear_reverse_max").and_then(|s| s.parse().ok()) { base.gear_reverse_max = v; }
|
|
if let Some(v) = map.get("projection_mode") { base.projection_mode = v.clone(); }
|
|
if let Some(v) = map.get("camera_fov_deg").and_then(|s| s.parse().ok()) { base.camera_fov_deg = v; }
|
|
if let Some(v) = map.get("lens_k1").and_then(|s| s.parse().ok()) { base.lens_k1 = v; }
|
|
if let Some(v) = map.get("screen_distance_m").and_then(|s| s.parse().ok()) { base.screen_distance_m = v; }
|
|
if let Some(v) = map.get("battery_cells").and_then(|s| s.parse().ok()) { base.battery_cells = v; }
|
|
Some(base)
|
|
}
|
|
|
|
pub fn save_to_disk(&self) -> Result<PathBuf> {
|
|
let dir = Self::profiles_dir()
|
|
.ok_or_else(|| anyhow::anyhow!("Impossible de déterminer le dossier des profils"))?;
|
|
fs::create_dir_all(&dir)?;
|
|
let path = dir.join(format!("{}.toml", Self::sanitize_filename(&self.name)));
|
|
let content = self.to_toml_string();
|
|
let tmp = path.with_extension("toml.tmp");
|
|
fs::write(&tmp, content)?;
|
|
fs::rename(&tmp, &path)?;
|
|
Ok(path)
|
|
}
|
|
|
|
/// Retourne les profils intégrés fusionnés avec les profils personnalisés de `~/.config/steamframe-fpv/profiles/`.
|
|
pub fn list_all() -> Vec<Self> {
|
|
let mut profiles = Self::builtin_presets();
|
|
if let Some(dir) = Self::profiles_dir() {
|
|
if let Ok(entries) = fs::read_dir(dir) {
|
|
for entry in entries.flatten() {
|
|
let path = entry.path();
|
|
if path.extension().and_then(|e| e.to_str()) == Some("toml") {
|
|
if let Ok(raw) = fs::read_to_string(&path) {
|
|
if let Some(parsed) = Self::parse_toml(&raw) {
|
|
if let Some(existing) = profiles
|
|
.iter_mut()
|
|
.find(|p| p.name.eq_ignore_ascii_case(&parsed.name))
|
|
{
|
|
*existing = parsed;
|
|
} else {
|
|
profiles.push(parsed);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
profiles
|
|
}
|
|
}
|
|
|
|
impl AppConfig {
|
|
/// Retourne le chemin XDG du fichier de configuration persistant (`~/.config/steamframe-fpv/config.toml`).
|
|
pub fn default_config_path() -> Option<PathBuf> {
|
|
if let Ok(xdg) = std::env::var("XDG_CONFIG_HOME") {
|
|
let trimmed = xdg.trim();
|
|
if !trimmed.is_empty() {
|
|
return Some(PathBuf::from(trimmed).join("steamframe-fpv/config.toml"));
|
|
}
|
|
}
|
|
std::env::var("HOME")
|
|
.ok()
|
|
.filter(|h| !h.trim().is_empty())
|
|
.map(|h| PathBuf::from(h).join(".config/steamframe-fpv/config.toml"))
|
|
}
|
|
|
|
/// Parse les arguments CLI en appliquant les réglages persistés de `config.toml`
|
|
/// uniquement pour les options non explicitement fournies en ligne de commande.
|
|
pub fn parse_with_saved() -> Self {
|
|
let matches = Self::command().get_matches();
|
|
let mut cfg = Self::from_arg_matches(&matches).unwrap_or_else(|e| e.exit());
|
|
if let Some(path) = Self::default_config_path() {
|
|
if path.exists() {
|
|
if let Ok(raw) = fs::read_to_string(&path) {
|
|
let map = Self::parse_toml_kv(&raw);
|
|
cfg.apply_saved_map(&map, |id| {
|
|
matches.value_source(id) == Some(ValueSource::CommandLine)
|
|
});
|
|
}
|
|
}
|
|
}
|
|
// Si --vrx-video-profile est fourni sans --video-width/--video-height explicites, aligner la résolution cible
|
|
if matches.value_source("video_width") != Some(ValueSource::CommandLine)
|
|
&& matches.value_source("video_height") != Some(ValueSource::CommandLine)
|
|
&& matches.value_source("vrx_video_profile") == Some(ValueSource::CommandLine)
|
|
{
|
|
if let Some((w, h)) = Self::profile_dimensions(&cfg.vrx_video_profile) {
|
|
cfg.video_width = w;
|
|
cfg.video_height = h;
|
|
}
|
|
}
|
|
cfg
|
|
}
|
|
|
|
pub fn profile_dimensions(profile: &str) -> Option<(u32, u32)> {
|
|
match profile.trim().to_ascii_lowercase().as_str() {
|
|
"720p60" | "720p120" => Some((1280, 720)),
|
|
"1080p60" | "1080p90" => Some((1920, 1080)),
|
|
_ => None,
|
|
}
|
|
}
|
|
|
|
/// Sérialise les réglages pilote au format TOML propre et lisible.
|
|
pub fn to_toml_string(&self) -> String {
|
|
fn esc(s: &str) -> String {
|
|
s.replace('\\', "\\\\").replace('"', "\\\"")
|
|
}
|
|
format!(
|
|
"# SteamFrame FPV — Configuration persistante (auto-générée)\n\
|
|
# Les arguments en ligne de commande ont toujours priorité sur ce fichier.\n\n\
|
|
usb_video_mode = \"{}\"\n\
|
|
uvc_device = \"{}\"\n\
|
|
usb_bind_ip = \"{}\"\n\
|
|
radxa_vrx_ip = \"{}\"\n\
|
|
wifi_channel = {}\n\
|
|
vrx_video_profile = \"{}\"\n\
|
|
video_udp_port = {}\n\
|
|
codec = \"{}\"\n\
|
|
stream_transport = \"{}\"\n\
|
|
video_width = {}\n\
|
|
video_height = {}\n\n\
|
|
projection_mode = \"{}\"\n\
|
|
camera_fov_deg = {:.2}\n\
|
|
lens_k1 = {:.4}\n\
|
|
lens_k2 = {:.4}\n\
|
|
screen_distance_m = {:.3}\n\
|
|
screen_width_m = {:.3}\n\n\
|
|
telemetry_enabled = {}\n\
|
|
telemetry_udp_port = {}\n\
|
|
head_tracking_enabled = {}\n\
|
|
nomad_ip = \"{}\"\n\
|
|
nomad_port = {}\n\
|
|
ht_protocol = \"{}\"\n\
|
|
max_pan_deg = {:.2}\n\
|
|
max_tilt_deg = {:.2}\n\
|
|
max_roll_deg = {:.2}\n\n\
|
|
g29_enabled = {}\n\
|
|
g29_udp_port = {}\n\
|
|
control_source = \"{}\"\n\
|
|
controller_device = \"{}\"\n\
|
|
controller_expo = {:.3}\n\
|
|
controller_deadzone = {:.3}\n\
|
|
controller_invert_steering = {}\n\
|
|
controller_throttle_expo = {:.3}\n\
|
|
controller_crawl_mode = {}\n\
|
|
controller_vibration = {}\n\
|
|
gaz_avant_min = {}\n\
|
|
gear_1_max = {}\n\
|
|
gear_2_max = {}\n\
|
|
gear_3_max = {}\n\
|
|
gaz_arriere_min = {}\n\
|
|
gear_reverse_max = {}\n\n\
|
|
dvr_dir = \"{}\"\n\
|
|
dvr_format = \"{}\"\n\
|
|
dvr_mode = \"{}\"\n\n\
|
|
battery_cells = {}\n\
|
|
battery_warn_cell_v = {:.2}\n\
|
|
battery_crit_cell_v = {:.2}\n\
|
|
osd_show_video_stats = {}\n\
|
|
osd_show_gps = {}\n\
|
|
active_profile = \"{}\"\n\n\
|
|
video_brightness = {:.3}\n\
|
|
video_contrast = {:.3}\n\
|
|
video_gamma = {:.3}\n\
|
|
video_sharpness = {:.3}\n\
|
|
horizon_stabilization = {}\n\
|
|
stereo_sbs = {}\n\
|
|
zero_copy_dmabuf = {}\n",
|
|
esc(&self.usb_video_mode),
|
|
esc(&self.uvc_device),
|
|
esc(&self.usb_bind_ip),
|
|
esc(&self.radxa_vrx_ip),
|
|
self.wifi_channel,
|
|
esc(&self.vrx_video_profile),
|
|
self.video_udp_port,
|
|
esc(&self.codec),
|
|
esc(&self.stream_transport),
|
|
self.video_width,
|
|
self.video_height,
|
|
esc(&self.projection_mode),
|
|
self.camera_fov_deg,
|
|
self.lens_k1,
|
|
self.lens_k2,
|
|
self.screen_distance_m,
|
|
self.screen_width_m,
|
|
self.telemetry_enabled,
|
|
self.telemetry_udp_port,
|
|
self.head_tracking_enabled,
|
|
esc(&self.nomad_ip),
|
|
self.nomad_port,
|
|
esc(&self.ht_protocol),
|
|
self.max_pan_deg,
|
|
self.max_tilt_deg,
|
|
self.max_roll_deg,
|
|
self.g29_enabled,
|
|
self.g29_udp_port,
|
|
esc(&self.control_source),
|
|
esc(&self.controller_device),
|
|
self.controller_expo,
|
|
self.controller_deadzone,
|
|
self.controller_invert_steering,
|
|
self.controller_throttle_expo,
|
|
self.controller_crawl_mode,
|
|
self.controller_vibration,
|
|
self.gaz_avant_min,
|
|
self.gear_1_max,
|
|
self.gear_2_max,
|
|
self.gear_3_max,
|
|
self.gaz_arriere_min,
|
|
self.gear_reverse_max,
|
|
esc(&self.dvr_dir),
|
|
esc(&self.dvr_format),
|
|
esc(&self.dvr_mode),
|
|
self.battery_cells,
|
|
self.battery_warn_cell_v,
|
|
self.battery_crit_cell_v,
|
|
self.osd_show_video_stats,
|
|
self.osd_show_gps,
|
|
esc(&self.active_profile),
|
|
self.video_brightness,
|
|
self.video_contrast,
|
|
self.video_gamma,
|
|
self.video_sharpness,
|
|
self.horizon_stabilization,
|
|
self.stereo_sbs,
|
|
self.zero_copy_dmabuf,
|
|
)
|
|
}
|
|
|
|
/// Sauvegarde atomique dans `~/.config/steamframe-fpv/config.toml` (fichier temporaire + rename).
|
|
pub fn save_to_disk(&self) -> Result<PathBuf> {
|
|
let path = Self::default_config_path()
|
|
.ok_or_else(|| anyhow::anyhow!("Impossible de déterminer XDG_CONFIG_HOME / HOME"))?;
|
|
self.save_to_path(&path)?;
|
|
Ok(path)
|
|
}
|
|
|
|
pub fn save_to_path(&self, path: &Path) -> Result<()> {
|
|
if let Some(parent) = path.parent() {
|
|
fs::create_dir_all(parent).with_context(|| {
|
|
format!("Impossible de créer le dossier de config {:?}", parent)
|
|
})?;
|
|
}
|
|
let tmp_path = path.with_extension("toml.tmp");
|
|
fs::write(&tmp_path, self.to_toml_string())
|
|
.with_context(|| format!("Échec écriture config temporaire {:?}", tmp_path))?;
|
|
fs::rename(&tmp_path, path)
|
|
.with_context(|| format!("Échec remplacement config {:?}", path))?;
|
|
Ok(())
|
|
}
|
|
|
|
/// Met à jour uniquement un sous-ensemble de clés dans `config.toml` existant (ou crée le fichier)
|
|
/// — utilisé par le Menu VR pour persister les réglages en vol sans écraser les autres options.
|
|
pub fn patch_saved_fields(&self) {
|
|
if let Err(e) = self.save_to_disk() {
|
|
log::warn!("[Config] Impossible de sauvegarder config.toml : {}", e);
|
|
}
|
|
}
|
|
|
|
fn parse_toml_kv(raw: &str) -> HashMap<String, String> {
|
|
let mut map = HashMap::new();
|
|
for line in raw.lines() {
|
|
let trimmed = line.trim();
|
|
if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with('[') {
|
|
continue;
|
|
}
|
|
if let Some((k, v)) = trimmed.split_once('=') {
|
|
let key = k.trim().to_string();
|
|
let mut val = v.trim();
|
|
// Retirer éventuel commentaire en fin de ligne hors guillemets
|
|
if !val.starts_with('"') {
|
|
if let Some((before, _)) = val.split_once('#') {
|
|
val = before.trim();
|
|
}
|
|
map.insert(key, val.to_string());
|
|
} else if let Some(inner) = val.strip_prefix('"').and_then(|s| s.strip_suffix('"'))
|
|
{
|
|
let unescaped = inner.replace("\\\"", "\"").replace("\\\\", "\\");
|
|
map.insert(key, unescaped);
|
|
}
|
|
}
|
|
}
|
|
map
|
|
}
|
|
|
|
fn apply_saved_map<F>(&mut self, map: &HashMap<String, String>, is_cli_set: F)
|
|
where
|
|
F: Fn(&str) -> bool,
|
|
{
|
|
macro_rules! load_str {
|
|
($field:ident) => {
|
|
if !is_cli_set(stringify!($field)) {
|
|
if let Some(v) = map.get(stringify!($field)) {
|
|
self.$field = v.clone();
|
|
}
|
|
}
|
|
};
|
|
}
|
|
macro_rules! load_parse {
|
|
($field:ident) => {
|
|
if !is_cli_set(stringify!($field)) {
|
|
if let Some(v) = map.get(stringify!($field)) {
|
|
if let Ok(parsed) = v.parse() {
|
|
self.$field = parsed;
|
|
}
|
|
}
|
|
}
|
|
};
|
|
}
|
|
|
|
load_str!(usb_video_mode);
|
|
load_str!(uvc_device);
|
|
load_str!(usb_bind_ip);
|
|
load_str!(radxa_vrx_ip);
|
|
load_parse!(wifi_channel);
|
|
load_str!(vrx_video_profile);
|
|
load_parse!(video_udp_port);
|
|
load_str!(codec);
|
|
load_str!(stream_transport);
|
|
load_parse!(video_width);
|
|
load_parse!(video_height);
|
|
|
|
load_str!(projection_mode);
|
|
load_parse!(camera_fov_deg);
|
|
load_parse!(lens_k1);
|
|
load_parse!(lens_k2);
|
|
load_parse!(screen_distance_m);
|
|
load_parse!(screen_width_m);
|
|
|
|
load_parse!(telemetry_enabled);
|
|
load_parse!(telemetry_udp_port);
|
|
load_parse!(head_tracking_enabled);
|
|
load_str!(nomad_ip);
|
|
load_parse!(nomad_port);
|
|
load_str!(ht_protocol);
|
|
load_parse!(max_pan_deg);
|
|
load_parse!(max_tilt_deg);
|
|
load_parse!(max_roll_deg);
|
|
|
|
load_parse!(g29_enabled);
|
|
load_parse!(g29_udp_port);
|
|
load_str!(control_source);
|
|
load_str!(controller_device);
|
|
load_parse!(controller_expo);
|
|
load_parse!(controller_deadzone);
|
|
load_parse!(controller_invert_steering);
|
|
load_parse!(controller_throttle_expo);
|
|
load_parse!(controller_crawl_mode);
|
|
load_parse!(controller_vibration);
|
|
load_parse!(gaz_avant_min);
|
|
load_parse!(gear_1_max);
|
|
load_parse!(gear_2_max);
|
|
load_parse!(gear_3_max);
|
|
load_parse!(gaz_arriere_min);
|
|
load_parse!(gear_reverse_max);
|
|
|
|
load_str!(dvr_dir);
|
|
load_str!(dvr_format);
|
|
load_str!(dvr_mode);
|
|
|
|
load_parse!(battery_cells);
|
|
load_parse!(battery_warn_cell_v);
|
|
load_parse!(battery_crit_cell_v);
|
|
load_parse!(osd_show_video_stats);
|
|
load_parse!(osd_show_gps);
|
|
load_str!(active_profile);
|
|
load_parse!(video_brightness);
|
|
load_parse!(video_contrast);
|
|
load_parse!(video_gamma);
|
|
load_parse!(video_sharpness);
|
|
load_parse!(horizon_stabilization);
|
|
load_parse!(stereo_sbs);
|
|
load_parse!(zero_copy_dmabuf);
|
|
|
|
// Sécurité bornes numériques
|
|
self.video_width = self.video_width.clamp(320, 3840);
|
|
self.video_height = self.video_height.clamp(240, 2160);
|
|
self.camera_fov_deg = self.camera_fov_deg.clamp(60.0, 180.0);
|
|
self.lens_k1 = self.lens_k1.clamp(-0.50, 0.25);
|
|
self.screen_distance_m = self.screen_distance_m.clamp(0.5, 5.0);
|
|
self.controller_vibration = self.controller_vibration.min(100);
|
|
self.controller_throttle_expo = self.controller_throttle_expo.clamp(0.0, 0.8);
|
|
self.battery_cells = self.battery_cells.min(6);
|
|
self.battery_warn_cell_v = self.battery_warn_cell_v.clamp(3.0, 4.2);
|
|
self.battery_crit_cell_v = self.battery_crit_cell_v.clamp(2.8, self.battery_warn_cell_v);
|
|
self.video_brightness = self.video_brightness.clamp(-0.5, 0.5);
|
|
self.video_contrast = self.video_contrast.clamp(0.5, 2.0);
|
|
self.video_gamma = self.video_gamma.clamp(0.5, 2.2);
|
|
self.video_sharpness = self.video_sharpness.clamp(0.0, 1.0);
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn test_config_toml_roundtrip_and_cli_override() {
|
|
let mut cfg = AppConfig::parse_from(["steamframe-fpv"]);
|
|
cfg.projection_mode = "cylinder".to_string();
|
|
cfg.screen_distance_m = 2.2;
|
|
cfg.lens_k1 = -0.22;
|
|
cfg.camera_fov_deg = 120.0;
|
|
cfg.control_source = "steam".to_string();
|
|
cfg.controller_invert_steering = true;
|
|
cfg.gear_3_max = 1350;
|
|
cfg.wifi_channel = 157;
|
|
cfg.telemetry_enabled = true;
|
|
|
|
let toml_text = cfg.to_toml_string();
|
|
let map = AppConfig::parse_toml_kv(&toml_text);
|
|
|
|
let mut loaded = AppConfig::parse_from(["steamframe-fpv", "--wifi-channel", "149"]);
|
|
loaded.apply_saved_map(&map, |id| id == "wifi_channel");
|
|
|
|
assert_eq!(loaded.projection_mode, "cylinder");
|
|
assert!((loaded.screen_distance_m - 2.2).abs() < 0.01);
|
|
assert!((loaded.lens_k1 - (-0.22)).abs() < 0.001);
|
|
assert!((loaded.camera_fov_deg - 120.0).abs() < 0.01);
|
|
assert_eq!(loaded.control_source, "steam");
|
|
assert!(loaded.controller_invert_steering);
|
|
assert_eq!(loaded.gear_3_max, 1350);
|
|
assert!(loaded.telemetry_enabled);
|
|
// L'argument CLI explicite doit garder priorité sur config.toml
|
|
assert_eq!(loaded.wifi_channel, 149);
|
|
}
|
|
|
|
#[test]
|
|
fn test_vehicle_profile_presets_and_apply_roundtrip() {
|
|
let presets = VehicleProfile::builtin_presets();
|
|
assert_eq!(presets.len(), 3);
|
|
let buggy = presets
|
|
.iter()
|
|
.find(|p| p.name.contains("Buggy"))
|
|
.expect("Preset Buggy 4S présent");
|
|
assert_eq!(buggy.battery_cells, 4);
|
|
|
|
let mut cfg = AppConfig::parse_from(["steamframe-fpv"]);
|
|
buggy.apply_to(&mut cfg);
|
|
assert_eq!(cfg.active_profile, buggy.name);
|
|
assert_eq!(cfg.battery_cells, 4);
|
|
assert_eq!(cfg.gear_3_max, buggy.gear_3_max);
|
|
assert!((cfg.lens_k1 - buggy.lens_k1).abs() < 0.001);
|
|
|
|
let extracted = VehicleProfile::from_config("Test Profile", &cfg);
|
|
let toml_text = extracted.to_toml_string();
|
|
let parsed = VehicleProfile::parse_toml(&toml_text).expect("TOML profil valide");
|
|
assert_eq!(parsed.name, "Test Profile");
|
|
assert_eq!(parsed.battery_cells, 4);
|
|
assert_eq!(parsed.gear_3_max, buggy.gear_3_max);
|
|
assert!((parsed.camera_fov_deg - buggy.camera_fov_deg).abs() < 0.01);
|
|
}
|
|
}
|