feat(gpu,dvr,ci): image enhance/SBS/DMA-BUF, DVR .srt + Replay 30s, GPS Home arrow, CI & modular split

This commit is contained in:
bleack committed 2026-11-25 23:47:48 +01:00
1 parent 4aa4fc06e7
commit b4642ddc95
33 files changed
+8279 -6092

No files matched your search

+289
View File
@@ -0,0 +1,289 @@
use std::time::{Duration, Instant};
/// État télémétrique temps réel fusionnant MAVLink (OpenIPC / FC) et CRSF (ELRS Nomad)
#[derive(Debug, Clone)]
pub struct TelemetryState {
pub battery_voltage_v: f32,
pub battery_current_a: f32,
pub battery_remaining_pct: i8,
/// Nombre de cellules LiPo auto-détecté (2..=6) dès réception d'une tension valide >= 6.0 V
pub battery_cells_detected: u8,
pub drone_roll_rad: f32,
pub drone_pitch_rad: f32,
pub drone_heading_deg: f32,
pub altitude_m: f32,
pub groundspeed_ms: f32,
pub climb_ms: f32,
pub throttle_pct: u16,
pub link_quality_pct: u8,
pub rssi_dbm: i8,
/// Données GPS CRSF (0x02) & Mode de vol CRSF (0x21)
pub gps_lat_deg: f64,
pub gps_lon_deg: f64,
pub gps_sats: u8,
pub gps_alt_m: f32,
pub gps_fix_valid: bool,
/// Point Home mémorisé au premier armement avec fix GPS valide (>= 6 sats)
pub home_lat_deg: Option<f64>,
pub home_lon_deg: Option<f64>,
pub flight_mode: String,
pub packets_received: u64,
pub last_update: Option<Instant>,
/// Rugosité terrain dérivée de l'attitude Pitch/Roll (0..255) pour le retour haptique
pub terrain_roughness: u8,
pub prev_pitch_rad: Option<f32>,
pub prev_roll_rad: Option<f32>,
pub last_attitude_update: Option<Instant>,
}
impl Default for TelemetryState {
fn default() -> Self {
Self {
battery_voltage_v: 0.0,
battery_current_a: 0.0,
battery_remaining_pct: -1,
battery_cells_detected: 0,
drone_roll_rad: 0.0,
drone_pitch_rad: 0.0,
drone_heading_deg: 0.0,
altitude_m: 0.0,
groundspeed_ms: 0.0,
climb_ms: 0.0,
throttle_pct: 0,
link_quality_pct: 0,
rssi_dbm: -127,
gps_lat_deg: 0.0,
gps_lon_deg: 0.0,
gps_sats: 0,
gps_alt_m: 0.0,
gps_fix_valid: false,
home_lat_deg: None,
home_lon_deg: None,
flight_mode: String::new(),
packets_received: 0,
last_update: None,
terrain_roughness: 0,
prev_pitch_rad: None,
prev_roll_rad: None,
last_attitude_update: None,
}
}
}
impl TelemetryState {
/// Indique si la télémétrie a reçu au moins une trame valide au cours des 2,5 dernières secondes.
pub fn is_live(&self) -> bool {
self.packets_received > 0
&& self
.last_update
.is_some_and(|t| t.elapsed() <= Duration::from_millis(2500))
}
/// Auto-détecte le nombre de cellules LiPo (2S..6S) sur la tension initiale du pack.
pub fn update_battery_voltage(&mut self, voltage_v: f32) {
if !voltage_v.is_finite() || voltage_v < 0.0 {
return;
}
self.battery_voltage_v = voltage_v;
if self.battery_cells_detected == 0 && (6.0..=26.5).contains(&voltage_v) {
let est = (voltage_v / 4.35).ceil().clamp(2.0, 6.0) as u8;
self.battery_cells_detected = est;
}
}
/// Nombre de cellules effectif (config manuelle prioritaire si >= 2, sinon auto-détecté).
pub fn effective_cells(&self, configured_cells: u8) -> u8 {
if (2..=6).contains(&configured_cells) {
configured_cells
} else if (2..=6).contains(&self.battery_cells_detected) {
self.battery_cells_detected
} else if self.battery_voltage_v >= 6.0 && self.battery_voltage_v <= 26.5 {
(self.battery_voltage_v / 4.35).ceil().clamp(2.0, 6.0) as u8
} else {
0
}
}
pub fn cell_voltage_v(&self, configured_cells: u8) -> Option<f32> {
let cells = self.effective_cells(configured_cells);
if cells >= 2 && self.battery_voltage_v > 0.5 {
Some(self.battery_voltage_v / cells as f32)
} else {
None
}
}
pub fn is_battery_critical(&self, configured_cells: u8, crit_cell_v: f32) -> bool {
self.is_live()
&& self
.cell_voltage_v(configured_cells)
.is_some_and(|cv| cv < crit_cell_v)
}
pub fn is_link_critical(&self) -> bool {
self.is_live() && self.link_quality_pct < 50
}
/// Mémorise automatiquement le point Home lors du premier armement avec fix GPS valide (>= 6 satellites).
pub fn maybe_lock_home(&mut self, armed: bool) {
if self.home_lat_deg.is_some() || !armed {
return;
}
if self.gps_fix_valid
&& self.gps_sats >= 6
&& (self.gps_lat_deg.abs() > 1e-4 || self.gps_lon_deg.abs() > 1e-4)
{
self.home_lat_deg = Some(self.gps_lat_deg);
self.home_lon_deg = Some(self.gps_lon_deg);
log::info!(
"[GPS Home] Point Home mémorisé : {:.6}, {:.6} ({} sats)",
self.gps_lat_deg,
self.gps_lon_deg,
self.gps_sats
);
}
}
#[allow(dead_code)]
pub fn reset_home(&mut self) {
self.home_lat_deg = None;
self.home_lon_deg = None;
}
/// Retourne `(distance_m, angle_relatif_deg)` vers le point Home par rapport au cap courant du véhicule.
/// `0°` = droit devant, `+90°` = à droite, `-90°` = à gauche, `±180°` = derrière.
pub fn home_vector(&self) -> Option<(f32, f32)> {
let (hlat, hlon) = (self.home_lat_deg?, self.home_lon_deg?);
if !self.gps_fix_valid {
return None;
}
let dist_m = haversine_distance_m(self.gps_lat_deg, self.gps_lon_deg, hlat, hlon);
let bearing_home = initial_bearing_deg(self.gps_lat_deg, self.gps_lon_deg, hlat, hlon);
let mut rel = (bearing_home - self.drone_heading_deg) % 360.0;
if rel > 180.0 {
rel -= 360.0;
} else if rel < -180.0 {
rel += 360.0;
}
Some((dist_m, rel))
}
/// Formate une ligne compacte de télémétrie pour sous-titres DVR `.srt` (VLC/MPV).
pub fn format_dvr_srt_caption(
&self,
configured_cells: u8,
gear_label: &str,
video_fps: f32,
video_jitter_ms: f32,
) -> String {
let mut parts: Vec<String> = Vec::with_capacity(6);
if let Some(cv) = self.cell_voltage_v(configured_cells) {
parts.push(format!(
"BAT {:.1}V ({}S {:.2}V/c) {:.1}A",
self.battery_voltage_v,
self.effective_cells(configured_cells),
cv,
self.battery_current_a
));
} else if self.battery_voltage_v > 0.1 {
parts.push(format!(
"BAT {:.1}V {:.1}A",
self.battery_voltage_v, self.battery_current_a
));
}
if self.is_live() {
parts.push(format!("LQ {}% RSSI {}dBm", self.link_quality_pct, self.rssi_dbm));
}
if !gear_label.is_empty() {
parts.push(format!("GEAR {}", gear_label));
}
if self.groundspeed_ms > 0.1 {
parts.push(format!("{:.1} km/h", self.groundspeed_ms * 3.6));
}
if self.gps_fix_valid && self.gps_sats > 0 {
let home_part = self
.home_vector()
.map(|(d, _)| format!(" HOME {:.0}m", d))
.unwrap_or_default();
parts.push(format!(
"GPS {:.5},{:.5} ({}sat){}",
self.gps_lat_deg, self.gps_lon_deg, self.gps_sats, home_part
));
}
if video_fps > 0.5 {
parts.push(format!("VID {:.0}fps jit {:.1}ms", video_fps, video_jitter_ms));
}
parts.join(" | ")
}
/// Calcule la rugosité du terrain (0..255) à partir de la dérivée Pitch/Roll,
/// alignée sur l'algorithme du firmware RP2350 (seuil mort 0.006 rad ≈ 0.35°, saturation 0.045 rad).
pub fn update_attitude_roughness(&mut self, pitch_rad: f32, roll_rad: f32) {
const DEADBAND_RAD: f32 = 0.006;
const SATURATION_RAD: f32 = 0.045;
let now = Instant::now();
if let (Some(prev_p), Some(prev_r)) = (self.prev_pitch_rad, self.prev_roll_rad) {
let delta = (pitch_rad - prev_p).abs() + (roll_rad - prev_r).abs();
let instant = if delta <= DEADBAND_RAD {
0u8
} else {
let norm = ((delta - DEADBAND_RAD) / (SATURATION_RAD - DEADBAND_RAD)).clamp(0.0, 1.0);
(norm * 255.0).round() as u8
};
// Attaque instantanée sur choc, décroissance douce entre trames
self.terrain_roughness = if instant >= self.terrain_roughness {
instant
} else {
((self.terrain_roughness as u16 * 3 + instant as u16) / 4) as u8
};
} else {
self.terrain_roughness = 0;
}
self.prev_pitch_rad = Some(pitch_rad);
self.prev_roll_rad = Some(roll_rad);
self.last_attitude_update = Some(now);
}
/// Retourne la rugosité terrain active avec décroissance linéaire entre 200 ms et 500 ms sans nouvelle attitude.
pub fn effective_terrain_roughness(&self) -> u8 {
if self.terrain_roughness == 0 {
return 0;
}
let Some(last) = self.last_attitude_update else {
return 0;
};
let elapsed_ms = Instant::now().saturating_duration_since(last).as_millis() as u64;
if elapsed_ms <= 200 {
self.terrain_roughness
} else if elapsed_ms >= 500 {
0
} else {
((self.terrain_roughness as u64 * (500 - elapsed_ms)) / 300) as u8
}
}
}
/// Distance géodésique Haversine en mètres entre deux points WGS84 (degrés).
pub fn haversine_distance_m(lat1_deg: f64, lon1_deg: f64, lat2_deg: f64, lon2_deg: f64) -> f32 {
const EARTH_R_M: f64 = 6_371_000.0;
let lat1 = lat1_deg.to_radians();
let lat2 = lat2_deg.to_radians();
let dlat = (lat2_deg - lat1_deg).to_radians();
let dlon = (lon2_deg - lon1_deg).to_radians();
let a = (dlat * 0.5).sin().powi(2) + lat1.cos() * lat2.cos() * (dlon * 0.5).sin().powi(2);
let c = 2.0 * a.clamp(0.0, 1.0).sqrt().asin();
(EARTH_R_M * c) as f32
}
/// Cap initial (azimut 0..360°, 0° = Nord, 90° = Est) du point 1 vers le point 2.
pub fn initial_bearing_deg(lat1_deg: f64, lon1_deg: f64, lat2_deg: f64, lon2_deg: f64) -> f32 {
let lat1 = lat1_deg.to_radians();
let lat2 = lat2_deg.to_radians();
let dlon = (lon2_deg - lon1_deg).to_radians();
let y = dlon.sin() * lat2.cos();
let x = lat1.cos() * lat2.sin() - lat1.sin() * lat2.cos() * dlon.cos();
let deg = y.atan2(x).to_degrees();
((deg + 360.0) % 360.0) as f32
}