Merge pull request #12 from bleackstorm/feat/gpu-dvr-telemetry-ci

feat(gpu,dvr,ci): image enhance/SBS/DMA-BUF, DVR .srt + Replay 30s, GPS Home arrow, CI & modular split
This commit is contained in:
bleackstorm authored and GitHub committed 2026-11-26 11:47:47 +01:00
commit c83f90570f
59 files changed
+16219 -9785

No files matched your search

+85
View File
@@ -0,0 +1,85 @@
name: CI
on:
push:
branches: [main]
pull_request:
branches: [main]
concurrency:
group: ci-${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
env:
CARGO_TERM_COLOR: always
jobs:
rust:
name: Rust (Clippy & Unit Tests)
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Install native Linux dependencies
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends \
build-essential pkg-config \
libglib2.0-dev libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev \
gstreamer1.0-plugins-base gstreamer1.0-plugins-good \
gstreamer1.0-plugins-bad gstreamer1.0-plugins-ugly gstreamer1.0-libav \
libxkbcommon-dev libxkbcommon-x11-dev libwayland-dev \
libvulkan-dev libopenxr-dev libgl1-mesa-dev libfontconfig1-dev
- name: Setup Rust toolchain
uses: dtolnay/rust-toolchain@stable
with:
components: clippy
- name: Cache Cargo registry & build artifacts
uses: Swatinem/rust-cache@v2
- name: Run cargo clippy (strict)
run: cargo clippy --no-deps --all-targets -- -D warnings
- name: Run cargo test
run: cargo test
scripts-and-python:
name: Shell & Python Validation
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Validate shell scripts syntax (bash -n)
run: bash -n launch.sh launch_vr.sh scripts/*.sh
- name: Validate Python relay syntax (py_compile)
run: python3 -m py_compile scripts/radxa_g29_relay.py
firmware-rp2350:
name: Firmware RP2350 (g29_crsf.ino)
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Install arduino-cli, rp2040 core and firmware libraries
run: |
mkdir -p "$HOME/.local/bin"
curl -fsSL https://raw.githubusercontent.com/arduino/arduino-cli/master/install.sh | BINDIR="$HOME/.local/bin" sh
echo "$HOME/.local/bin" >> "$GITHUB_PATH"
"$HOME/.local/bin/arduino-cli" config init
"$HOME/.local/bin/arduino-cli" config set board_manager.additional_urls \
https://github.com/earlephilhower/arduino-pico/releases/download/global/package_rp2040_index.json
"$HOME/.local/bin/arduino-cli" core update-index
"$HOME/.local/bin/arduino-cli" core install rp2040:rp2040
"$HOME/.local/bin/arduino-cli" lib install "Pico PIO USB" "Adafruit NeoPixel"
- name: Compile g29_crsf firmware for Waveshare RP2350 Plus
run: |
arduino-cli compile \
--fqbn rp2040:rp2040:waveshare_rp2350_plus:usbstack=tinyusb \
firmware/g29_crsf
+2
View File
@@ -6,3 +6,5 @@ steamframe_fpv.log
dist/
recordings/
.DS_Store
__pycache__/
*.pyc
Generated
+2 -1
View File
@@ -5421,7 +5421,7 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
[[package]]
name = "steamframe-fpv"
version = "0.3.0"
version = "0.4.0"
dependencies = [
"anyhow",
"ash",
@@ -5434,6 +5434,7 @@ dependencies = [
"gstreamer-video",
"image",
"log",
"naga",
"openxr",
"parking_lot",
"smallvec",
+2 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "steamframe-fpv"
version = "0.3.0"
version = "0.4.0"
edition = "2021"
description = "Application graphique et VR native Steam Frame (OpenXR + Vulkan + GPUI) pour Eachine Sphere Link (USB RNDIS) et Head-Tracking RadioMaster Nomad (ELRS Wi-Fi)"
@@ -16,6 +16,7 @@ gstreamer-app = "0.23"
gstreamer-video = "0.23"
image = "0.25"
log = "0.4"
naga = { version = "25.0.1", default-features = false, features = ["wgsl-in", "spv-out"] }
openxr = { version = "0.19", features = ["loaded"] }
parking_lot = "0.12"
smallvec = "1.16"
+36 -22
View File
@@ -1,4 +1,4 @@
# SteamFrame FPV (`steamframe-fpv` v0.3.0)
# SteamFrame FPV (`steamframe-fpv` v0.4.0)
Application graphique et VR native **Linux / SteamOS (ARM64 & x86_64)** en **Rust**, conçue pour le casque **Steam Frame** avec :
@@ -8,12 +8,12 @@ Application graphique et VR native **Linux / SteamOS (ARM64 & x86_64)** en **Rus
---
## Architecture & Fonctionnalités (v0.3)
## Architecture & Fonctionnalités (v0.4)
- **Acquisition Vidéo Résiliente (`src/video_usb.rs`)** : Superviseur GStreamer dédié avec reconnexion automatique (backoff exponentiel), gestion de perte de signal et mire de veille animée si le VRX est hors ligne.
- **Rendu OpenXR + Vulkan (`src/vulkan_xr.rs`, `src/dome_projection.rs`)** :
- Support natif `XR_KHR_vulkan_enable2` avec 3 modes de projection VR : **Dôme 140°** (`Equirect2`), **Cylindre 140°** (`Cylinder`) et **Écran Plat** (`Quad`).
- Correction radiale en barillet temps réel (`k1`, `k2`, FOV) par table LUT 32-bit précalculée (`DomeWarpLut`).
- **Acquisition Vidéo Résiliente & Décodage Matériel (`src/video_usb.rs`)** : Superviseur GStreamer dédié avec sondage matériel automatique (`v4l2h264dec` / `vah264dec` / `vaapih264dec`, idem H.265, repli automatique logiciel `avdec_*`), handoff triple-buffer O(1) (`FrameMailbox`), négociation **DMA-BUF zéro-copie** optionnelle (`--zero-copy-dmabuf`), reconnexion automatique et métriques live (`FPS`, `Jitter`, `Drops`).
- **Rendu OpenXR + Vulkan GPU Compute (`src/vulkan_xr.rs`, `src/vulkan_warp.rs`, `src/engine/xr_session.rs`)** :
- Support natif `XR_KHR_vulkan_enable2` avec double-buffering asynchrone (fences) et **Compute Shader Vulkan GPU** (WGSL → SPIR-V via `naga`) assurant en une passe : conversion **BT.709 NV12→RGBA/BGRA**, dé-distorsion radiale bilinéaire (`k1`, `k2`, FOV), **amélioration d'image temps réel** (luminosité, contraste, gamma, netteté CAS-lite), **stabilisation horizon 2D CRSF** et support **Caméra 3D Stéréo Side-by-Side (`--stereo-sbs`, `EyeVisibility::LEFT` / `RIGHT`)**.
- **Double couche OpenXR** : couche 0 vidéo (3 modes : **Dôme 140°** `Equirect2`, **Cylindre 140°** `Cylinder`, **Écran Plat** `Quad`) + couche 1 **OSD / Menu VR dédiée** (`CompositionLayerQuad` transparente, ≤ 20 Hz, texte parfaitement net hors distorsion optique).
- Bascule à chaud **Mode VR ON / OFF** et repli automatique en **Mode Bureau / Simulation** si aucun runtime OpenXR (Monado / SteamVR) n'est actif.
- **Suivi de Tête & Hub G29 Unifié (`src/nomad_elrs.rs`, `src/g29_bridge.rs`)** :
- **`g29`** *(défaut)* : Envoi `$HT,<pan>,<tilt>,<roll>` vers `192.168.1.1:14552` (relais Radxa Zero 3W ➔ RP2350 `g29_crsf` sur **CH6–CH8**, avec recentrage auto à `500 ms` et zéro Wi-Fi).
@@ -21,22 +21,24 @@ Application graphique et VR native **Linux / SteamOS (ARM64 & x86_64)** en **Rus
- **`crsf`** : Trames `RC_CHANNELS_PACKED (0x16)` (11 bits `172..1811`).
- **`mavlink`** : `MAVLink v1 RC_CHANNELS_OVERRIDE` + `HEARTBEAT` (ex. `elrs_txbp.local:14555`).
- **Commandes volant G29 (`$G29` / `$G29_EVT`)** : Tare Head-Tracking (`Cross`/`PS`/`R3`), DVR (`Share`/`Circle`), OSD (`Triangle`), Projection VR (`Square`), Trim Pan/Tilt (`D-Pad`) et affichage rapport engagé / armement / pédales dans le HUD.
- **Support Steam Controller & Haptique 25 Hz (`src/controller.rs`, bascule à chaud G29 ⇄ Steam Controller)** : Lecture Linux **HIDRAW Ibex `0x42` natif** (`28de:1302..1305` / Puck, contournant le Lizard Mode) avec repli `evdev`, boîte séquentielle `R/N/1/2/3`, sécurité d'armement, mêmes raccourcis cockpit, injection `$SRC,EXT` / `$RC,...` à `100 Hz` vers la RP2350 et **retours haptiques natifs Output Report `0x80`** (armement, passages de rapports gauche/droite, ABS > 70 %, grondement moteur, grain de roulement & rugosité terrain CRSF `0x1E` / MAVLink).
- **Télémétrie & OSD Vectoriel (`src/telemetry_osd.rs`)** :
- Décodage unifié depuis le port UDP `14552` (`$CRSF,<HEX>` remonté par `g29_crsf` via la Radxa) **et/ou** le port UDP `14551` (MAVLink v1/v2 & CRSF) avec validation **CRC-16 / CRC-8 DVB-S2**.
- Incrustation OSD zéro-allocation (`StackStr`) : horizon artificiel, ruban de cap, radar gimbal Pan/Tilt, tension/courant batterie, LQ/RSSI, vitesse, altitude/VSI, mode de projection et indicateur `REC`.
- **Enregistreur DVR Intégré (`src/dvr.rs`)** :
- Conteneurs **`mkv`** (Matroska résistant aux coupures) ou **`mp4`** fragmenté, sans écrasement de fichier existant.
- Mode **`copy`** (flux natif H.264/H.265 direct 0 % CPU en RNDIS) ou **`composited`** / **`osd`** (ré-encodage x264 avec OSD et correction optique incrustés).
- **Support Steam Controller & Haptique 25 Hz (`src/controller/`, bascule à chaud G29 ⇄ Steam Controller)** : Lecture Linux **HIDRAW Ibex `0x42` natif** (`28de:1302..1305` / Puck, contournant le Lizard Mode) avec repli `evdev`, boîte séquentielle `R/N/1/2/3`, sécurité d'armement, injection `$SRC,EXT` / `$RC,...` à `100 Hz` vers la RP2350 et **retours haptiques natifs Output Report `0x80`** (armement, passages de rapports, ABS > 70 %, moteur/rugosité terrain CRSF `0x1E` + **alertes batterie critique & LQ < 50 %**).
- **Télémétrie, Auto-LiPo, GPS Home & OSD Vectoriel (`src/telemetry_osd/`)** :
- Décodage unifié depuis UDP `14552` (`$CRSF,<HEX>`) **et/ou** UDP `14551` (MAVLink v1/v2 & CRSF avec CRC-16 / CRC-8 DVB-S2, GPS `0x02`, Flight Mode `0x21`).
- **Auto-détection LiPo (`2S`–`6S`)** avec seuils par cellule, **verrouillage automatique du point Home GPS** au premier armement (≥ 6 sats) et **flèche directionnelle + distance Home** sur l'OSD.
- **Enregistreur DVR, Sous-titres `.srt` & Instant Replay 30 s (`src/dvr.rs`)** :
- Conteneurs **`mkv`** ou **`mp4`** fragmenté, modes **`copy`** (flux natif H.264/H.265 0 % CPU) ou **`composited`** (encodeur matériel `v4l2h264enc`/`vah264enc` puis `x264enc`).
- **Sous-titres télémétrie `.srt` automatiques** synchronisés à côté de chaque vidéo (VLC/MPV, 0 % coût d'encodage).
- **Blackbox / Instant Replay 30 s** : pré-buffer circulaire RAM des 30 dernières secondes H.264/H.265 (calé sur image-clé IDR/IRAP) exportable en 1 clic (`⏮ Replay 30s`) avec son `.srt`.
- **Profils Véhicules & Persistance (`src/config.rs`)** : Préréglages intégrés (**Crawler 3S**, **Buggy 4S**, **Aile FPV**) + sauvegarde TOML dans `~/.config/steamframe-fpv/profiles/*.toml` et persistance atomique `config.toml`.
---
## Interfaces Graphiques & Mode CLI
1. **GPUI (Interface unique GPU-accélérée)** (`src/gui_gpui.rs`) : Interface GPU-accélérée organisée en 4 onglets :
- **`📹 Cockpit`** : Retour vidéo plein écran + bandeau HUD flottant activable/désactivable.
- **`⚙️ Réglages`** : Configuration VRX/UVC, presets réseau Nomad, édition IP/Port, **Mock Manuel Pan/Tilt/Roll** (envoi unitaire ou continu 50 Hz), projection VR & optique temps réel, vitesses CRSF et DVR.
- **`📊 Télémétrie`** : Jauges CRSF Pan/Tilt/Roll et métriques de vol/lien radio.
1. **GPUI (Interface unique GPU-accélérée)** (`src/ui/`) : Interface GPU-accélérée organisée en 4 onglets :
- **`📹 Cockpit`** : Retour vidéo plein écran + bouton **`⏮ Replay 30s`** + bandeau HUD flottant activable/désactivable.
- **`⚙️ Réglages`** : Profils véhicules & LiPo (`Auto 2S–6S`), VRX/UVC, presets réseau Nomad, Mock Manuel Pan/Tilt/Roll, projection VR & optique, **Image GPU / Horizon CRSF / 3D SBS / DMA-BUF**, vitesses CRSF et DVR.
- **`📊 Télémétrie`** : Jauges CRSF Pan/Tilt/Roll, tension/cellule LiPo, GPS + distance/cap Home, métriques lien vidéo (`FPS`, `Jitter`, `Drops`, décodeur, DMA-BUF, Replay RAM).
- **`📜 Logs`** : Console filtrable (`Tous`, `Warn / Erreurs`, `Erreurs seules`) synchronisée sans verrou avec `steamframe_fpv.log`.
2. **Menu Minimaliste VR dans le casque (OpenXR / Mode Gaming `--vr-only`)** :
- Lancez `./launch_vr.sh` (ou ajoutez `steamframe-fpv-vr.desktop` en jeu non-Steam en Mode Gaming) pour démarrer directement en immersion OpenXR sans fenêtre 2D.
@@ -73,7 +75,7 @@ sudo apt update && sudo apt install -y \
build-essential pkg-config \
libglib2.0-dev libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev \
gstreamer1.0-plugins-base gstreamer1.0-plugins-good \
gstreamer1.0-plugins-bad gstreamer1.0-libav \
gstreamer1.0-plugins-bad gstreamer1.0-plugins-ugly gstreamer1.0-libav \
libxkbcommon-dev libxkbcommon-x11-dev libwayland-dev libgl1-mesa-dev v4l-utils
```
@@ -118,18 +120,30 @@ Le script [launch.sh](launch.sh) prépare `libxkbcommon-x11.so` si besoin, compi
| `--controller-invert-steering` | `false` | Inverse le sens de direction du Steam Controller |
| `--controller-vibration` | `100` | Intensité des vibrations haptiques du Steam Controller (`0` = OFF, `1..=100%`, réglable à chaud dans l'IHM) |
| `--telemetry-enabled` / `--telemetry-udp-port` | `false` / `14551` | Active l'OSD et écoute MAVLink / CRSF |
| `--dvr-dir` / `--dvr-format` / `--dvr-mode` | `recordings` / `mkv` / `copy` | Dossier, conteneur (`mkv`, `mp4`) et mode (`copy`, `composited`) |
| `--dvr-dir` / `--dvr-format` / `--dvr-mode` | `recordings` / `mkv` / `copy` | Dossier, conteneur (`mkv`, `mp4`) et mode (`copy`, `composited`) avec `.srt` auto |
| `--video-brightness` / `--video-contrast` / `--video-gamma` / `--video-sharpness` | `0.0` / `1.0` / `1.0` / `0.0` | Amélioration image temps réel sur Compute Shader GPU (CAS-lite) |
| `--horizon-stabilization` / `--stereo-sbs` / `--zero-copy-dmabuf` | `false` | Stabilisation roulis CRSF, caméra 3D Side-by-Side et import DMA-BUF zéro-copie |
| `--log-file` | `steamframe_fpv.log` | Fichier de journalisation persistant |
---
## Tests & Validation
## Tests, CI & Validation
Le dépôt intègre un pipeline **GitHub Actions** ([.github/workflows/ci.yml](.github/workflows/ci.yml)) vérifiant à chaque PR : `cargo clippy -- -D warnings`, `cargo test`, la syntaxe des scripts `bash`/`python` et la compilation `arduino-cli` du firmware RP2350.
```bash
# Tests unitaires (projection optique, protocoles Nomad, CRC télémétrie, pipeline GStreamer, DVR)
# Analyse statique stricte + tests unitaires (51 tests)
cargo clippy --no-deps --all-targets -- -D warnings
cargo test
# Banc de validation complet OpenXR + Vulkan + Head-Tracking (avec Monado simulé)
# Banc de validation complet OpenXR + Vulkan Compute + Head-Tracking (avec Monado simulé)
./scripts/test_openxr_pipeline.sh
./scripts/autonomous_openxr_test.sh
```
---
## Feuille de Route & Évolutions Futures
Le plan des prochaines évolutions dédiées à l'**expérience de pilotage VR & terrain** (profils véhicules dans le Menu VR, ancrage spatial `LOCAL`/amortissement, alertes audio et monitoring `wfb_rx` / thermique Radxa live) est documenté dans :
- [evolution/plan_experience_vr_terrain.md](evolution/plan_experience_vr_terrain.md)
File renamed without changes.
+80
View File
@@ -0,0 +1,80 @@
# Plan d'Évolution Futur — Expérience de Pilotage VR & Terrain
Ce document détaille la feuille de route technique pour le prochain chantier **Expérience VR & Terrain** de `steamframe-fpv`.
---
## 1. Changement de Profil Véhicule dans le Menu VR
### Objectif
Permettre au pilote de basculer entre ses profils véhicules (**Crawler 3S**, **Buggy 4S**, **Aile FPV**, ou profils personnalisés de `~/.config/steamframe-fpv/profiles/*.toml`) directement dans le casque (mode `--vr-only` sur SteamOS), sans retirer le casque ni passer par la fenêtre GPUI.
### Conception technique
- **Modules impactés** :
- `src/engine/vr_menu.rs` : ajouter une entrée `Profil Véhicule` dans `VrMenuPage::Main` (ou en tête de `VrMenuPage::Advanced`) et un champ `profile_names: Vec<String>` / `profile_idx: usize` rafraîchi à l'ouverture du menu via `VehicleProfile::list_all()`.
- `src/engine/control_handle.rs` / `src/engine/mod.rs` : brancher l'action gauche/droite (sélection) et `Confirm` (application à chaud) sur `EngineControlHandle::apply_vehicle_profile(&profile)`, qui met à jour de façon atomique : source de contrôle, boîte séquentielle (`gaz_avant_min`, `gear_1..3_max`, `gear_reverse_max`), optique (`projection_mode`, `camera_fov_deg`, `lens_k1`, `screen_distance_m`), nombre de cellules LiPo (`battery_cells`) et persiste `config.toml`.
- `src/telemetry_osd/osd.rs` : afficher le nom du profil courant dans le rendu du menu VR et déclencher un toast vert (`PROFIL : BUGGY 4S`).
- **Sécurité** : bloquer le changement de profil si le véhicule est **armé** (`armed == true`), avec message toast `DÉSARMER AVANT PROFIL` et retour haptique d'avertissement.
---
## 2. Mode Head-Locked (`VIEW`) vs World-Locked (`LOCAL`) avec Recentrage & Amortissement
### Objectif
Offrir le choix entre :
- **`VIEW` (Head-Locked, défaut actuel)** : l'écran vidéo et l'OSD suivent instantanément la tête (idéal en pilotage dynamique).
- **`LOCAL` (World-Locked / Ancrage spatial)** : l'écran vidéo reste ancré dans l'espace face au pilote à l'instant de la tare/recentrage, avec une **inertie douce (SLERP / amortissement anti-cinétose)** optionnelle sur la couche OSD afin d'éviter la fatigue visuelle sur terrain cassant.
### Conception technique
- **Modules impactés** :
- `src/config.rs` : ajouter `vr_lock_mode: String` (`"head"` | `"world"` | `"smooth"`) et `vr_hud_smoothing: f32` (`0.0..=1.0`), persistés dans `config.toml`.
- `src/engine/xr_session.rs` :
- En mode `world` : soumettre la couche vidéo dans `vk_xr.local_space` avec la pose capturée lors du dernier `Tare / Recentrage` (yaw uniquement, pour garder l'horizon de niveau).
- En mode `smooth` : appliquer un filtre passe-bas quaternion (`Quat::slerp`) entre la pose courante et la pose filtrée sur la couche vidéo ou OSD.
- `src/engine/vr_menu.rs` & `src/ui/settings/` : raccourci de bascule + bouton `Recentrage Espace` lié au bouton `Tare HT`.
---
## 3. Audio Retour, Bips d'Alerte & Synthèse Vocale dans le Casque
### Objectif
Compléter l'OSD visuel et les vibrations haptiques du Steam Controller par un retour audio non intrusif dans le casque Steam Frame (PipeWire / PulseAudio), afin que le pilote garde les yeux sur la trajectoire lors des événements critiques.
### Événements sonores prioritaires
| Événement | Signal audio recommandé | Anti-spam (cooldown) |
| --- | --- | --- |
| Batterie critique (`< crit_cell_v`) | Double bip grave (440 Hz → 330 Hz) ou voix *"Batterie critique"* | 5 s |
| Batterie faible (`< warn_cell_v`) | Bip simple doux (660 Hz) | 15 s |
| Perte / dégradation lien radio (`LQ < 50%`) | Triple tic aigu rapide (1200 Hz) | 3 s |
| Armement / Désarmement | Mélodie montante / descendante 2 tons | immédiat |
| Démarrage / Arrêt DVR ou Instant Replay | Clic obturateur synthétisé | immédiat |
| Changement de rapport (`R/N/1/2/3`) | Bip court optionnel (désactivé par défaut) | immédiat |
### Conception technique
- **Approche légère recommandée (zéro dépendance lourde)** :
- Synthétiseur PCM sinusoïdal/enveloppe ADSR en Rust pur (~120 lignes dans `src/audio_alerts.rs`) poussé sur un mini pipeline GStreamer `appsrc ! audio/x-raw,format=S16LE,rate=44100,channels=1 ! autoaudiosink` (GStreamer est déjà lié !).
- Option voix : lecture de courts échantillons `.wav` embarqués ou génération optionnelle via `espeak-ng` / `piper` en tâche de fond non bloquante.
- Contrôle volume (`audio_alerts_enabled`, `audio_volume_pct`) dans `AppConfig`, GPUI et Menu VR.
---
## 4. Monitoring Radxa VRX Live (`wfb_rx` & Température SoC)
### Objectif
Afficher en temps réel la santé de la liaison vidéo radio WFB-ng et du récepteur Radxa Zero 3W (RSSI par antenne RTL8812EU, paquets FEC réparés/perdus, débit vidéo, température CPU/Wi-Fi du SoC) directement dans l'onglet **Télémétrie** et en bandeau compact sur l'OSD VR.
### Conception technique
- **Côté Radxa Zero 3W** (`scripts/radxa_g29_relay.py` ou démon dédié) :
- Consommer le flux JSON/msgpack de `wfb_rx` (port API stats local `8003` sur OpenIPC/RubyFPV) et lire `/sys/class/thermal/thermal_zone0/temp`.
- Publier un paquet UDP compact (`$VRX,<temp_c>,<rssi_a>,<rssi_b>,<fec_rec>,<fec_lost>,<kbps>\n`) à 2 Hz vers le Steam Frame sur le port unifié `14552` (aucun nouveau port à ouvrir, compatible tunnel USB RNDIS).
- **Côté SteamFrame FPV** :
- Étendre `src/g29_bridge.rs` pour parser `$VRX,...` dans une structure `VrxLinkStats` partagée dans `EngineSharedState`.
- Afficher une carte **VRX Radxa / WFB-ng** dans `src/ui/telemetry.rs` (température avec seuil d'alerte ≥ 75 °C, RSSI antenne 1/2, compteur FEC perdu) et ajouter une ligne optionnelle sur l'OSD VR.
---
## Ordre d'implémentation suggéré
1. **Lot 5A** : Profils véhicules dans le Menu VR + Mode Head/World-Locked (`VIEW`/`LOCAL`).
2. **Lot 5B** : Bips d'alerte audio via GStreamer `appsrc ! autoaudiosink` (sans nouvelle dépendance Cargo).
3. **Lot 5C** : Télémétrie `$VRX` temps réel depuis la Radxa Zero 3W (`wfb_rx` + thermique SoC).
+205 -103
View File
@@ -177,6 +177,8 @@ volatile uint32_t momentConnexionUSB_ms = 0;
volatile bool logMountRequis = false;
volatile int8_t statutEnvoiLed = 0;
volatile uint32_t heartbeatCore1_ms = 0; // Surveillance santé Cœur 1 (Watchdog dual-core)
volatile bool core1Demarre = false; // Passe à true dès le premier tour de loop1()
uint32_t momentDemarrageCore0_ms = 0; // Grâce de démarrage Cœur 1 (5 s max)
// Failsafe et diagnostic
volatile bool failsafeActif = true; // Écrit uniquement par le cœur 0
@@ -229,7 +231,7 @@ volatile uint16_t etatBoutonsCockpitPrec = 0xFFFF; // Ignore tout bouton mainten
volatile uint8_t etatDpadPrec = 0xFF;
bool cockpitEchoUSB = true; // Actif par défaut pour liaison directe USB-C (/dev/ttyACM0)
uint32_t dernierPaquetHT_ms = 0;
bool htActif = false;
volatile bool htActif = false;
// Pilotage externe (Steam Controller via SteamFrame FPV -> Radxa -> RP2350)
volatile uint8_t sourceActive = SRC_G29;
@@ -270,14 +272,21 @@ static inline void assignerCanalCRSF(uint8_t numeroCh, uint16_t valeur11bits) {
}
}
char serialBuffer[64];
char serialBuffer[96];
uint8_t serialBufferIdx = 0;
char serial2Buffer[64];
bool serialBufferOverflow = false;
char serial2Buffer[96];
uint8_t serial2BufferIdx = 0;
bool serial2BufferOverflow = false;
static inline bool estCanalReserve(uint8_t ch) {
return (ch == CANAL_ARM) || (ch == CANAL_HT_PAN) || (ch == CANAL_HT_TILT) || (ch == CANAL_HT_ROLL);
}
void reinitialiserCanauxCRSF() {
bool ht = __atomic_load_n(&htActif, __ATOMIC_ACQUIRE);
for (int i = 0; i < 16; i++) {
if (htActif && (i == (CANAL_HT_PAN - 1) || i == (CANAL_HT_TILT - 1) || i == (CANAL_HT_ROLL - 1))) {
if (ht && (i == (CANAL_HT_PAN - 1) || i == (CANAL_HT_TILT - 1) || i == (CANAL_HT_ROLL - 1))) {
continue;
}
crsfChannelStore((uint8_t)i, CRSF_VAL_MID);
@@ -355,8 +364,8 @@ void chargerConfiguration() {
EEPROM.get(0, cfgStockee);
memcpy((void*)&configSysteme, &cfgStockee, sizeof(ConfigG29));
bool conflitArm = configSysteme.volant == CANAL_ARM || configSysteme.accel == CANAL_ARM ||
configSysteme.frein == CANAL_ARM || configSysteme.embrayage == CANAL_ARM;
bool conflitReserve = estCanalReserve(configSysteme.volant) || estCanalReserve(configSysteme.accel) ||
estCanalReserve(configSysteme.frein) || estCanalReserve(configSysteme.embrayage);
bool canauxValides = (configSysteme.volant >= 1 && configSysteme.volant <= 16) &&
(configSysteme.accel >= 1 && configSysteme.accel <= 16) &&
@@ -379,15 +388,15 @@ void chargerConfiguration() {
bool vibValide = (configSysteme.intensiteVibration <= 100);
bool vitessesValides = (configSysteme.gazAvantMin >= CRSF_VAL_MID && configSysteme.gazAvantMin <= CRSF_VAL_MAX) &&
(configSysteme.gazAvantMax[0] >= configSysteme.gazAvantMin && configSysteme.gazAvantMax[0] <= CRSF_VAL_MAX) &&
(configSysteme.gazAvantMax[1] >= configSysteme.gazAvantMin && configSysteme.gazAvantMax[1] <= CRSF_VAL_MAX) &&
(configSysteme.gazAvantMax[2] >= configSysteme.gazAvantMin && configSysteme.gazAvantMax[2] <= CRSF_VAL_MAX) &&
(configSysteme.gazArriereMin >= CRSF_VAL_MIN && configSysteme.gazArriereMin <= CRSF_VAL_MID) &&
(configSysteme.gazArriereMax >= CRSF_VAL_MIN && configSysteme.gazArriereMax <= configSysteme.gazArriereMin);
bool vitessesValides = (configSysteme.gazAvantMin >= CRSF_VAL_MID && configSysteme.gazAvantMin < CRSF_VAL_MAX) &&
(configSysteme.gazAvantMax[0] > configSysteme.gazAvantMin && configSysteme.gazAvantMax[0] <= CRSF_VAL_MAX) &&
(configSysteme.gazAvantMax[1] > configSysteme.gazAvantMin && configSysteme.gazAvantMax[1] <= CRSF_VAL_MAX) &&
(configSysteme.gazAvantMax[2] > configSysteme.gazAvantMin && configSysteme.gazAvantMax[2] <= CRSF_VAL_MAX) &&
(configSysteme.gazArriereMin > CRSF_VAL_MIN && configSysteme.gazArriereMin <= CRSF_VAL_MID) &&
(configSysteme.gazArriereMax >= CRSF_VAL_MIN && configSysteme.gazArriereMax < configSysteme.gazArriereMin);
if (configSysteme.magicNumber != MAGIC_NUMBER_CONFIG || conflitArm || !canauxValides || !canauxDistincts || !expoValide || !angleValide || !vibValide || !vitessesValides) {
if (conflitArm) Serial.println("!! Un axe etait mappe sur le canal ARM : configuration reinitialisee !!");
if (configSysteme.magicNumber != MAGIC_NUMBER_CONFIG || conflitReserve || !canauxValides || !canauxDistincts || !expoValide || !angleValide || !vibValide || !vitessesValides) {
if (conflitReserve) Serial.println("!! Un axe etait mappe sur un canal reserve (ARM/HT) : configuration reinitialisee !!");
else if (!canauxValides || !canauxDistincts) Serial.println("!! Conflit ou canal invalide en EEPROM : configuration reinitialisee !!");
else if (!expoValide || !angleValide || !vibValide || !vitessesValides) Serial.println("!! Valeur invalide en EEPROM : configuration reinitialisee !!");
else Serial.println(">> Initialisation configuration d'usine par defaut...");
@@ -412,7 +421,33 @@ void demanderOuExecuterSauvegarde() {
}
}
void traiterLigneSerie(char* commande) {
static bool parseStrictInt(const char* s, int& outVal) {
if (!s || *s == '\0') return false;
char* endPtr = nullptr;
long v = strtol(s, &endPtr, 10);
if (endPtr == s || *endPtr != '\0') return false;
outVal = (int)v;
return true;
}
static bool parseStrictFloat(const char* s, float& outVal) {
if (!s || *s == '\0') return false;
char* endPtr = nullptr;
float v = strtof(s, &endPtr);
if (endPtr == s || *endPtr != '\0' || isnan(v) || isinf(v)) return false;
outVal = v;
return true;
}
uint8_t calculerCrc8Crsf(const uint8_t* data, size_t len);
void traiterLigneSerie(char* commande, bool depuisUsb) {
// Sécurité : les commandes CLI sans CRC (B=BOOTSEL, R=Reset, V=/A=/F=/E=...) ne sont
// acceptées QUE sur l'USB local (Serial), jamais sur l'UART Radxa / UDP (Serial2).
if (!depuisUsb && commande[0] != '$') {
return;
}
if (commande[0] == '?') {
afficherConfiguration();
return;
@@ -454,14 +489,14 @@ void traiterLigneSerie(char* commande) {
extEmbrayagePct = 0;
extVolantPct = 0;
extRcActif = false;
sourceActive = SRC_G29;
majLedRequise = true;
cockpitEtatModifie = true;
__atomic_store_n(&sourceActive, SRC_G29, __ATOMIC_RELEASE);
__atomic_store_n(&majLedRequise, true, __ATOMIC_RELEASE);
__atomic_store_n(&cockpitEtatModifie, true, __ATOMIC_RELEASE);
momentDernierChangementDurete_ms = 0;
sauvegardeDifferee = false;
rp2040.resumeOtherCore();
majRangeRequise = true;
majRessortRequise = true;
__atomic_store_n(&majRangeRequise, true, __ATOMIC_RELEASE);
__atomic_store_n(&majRessortRequise, true, __ATOMIC_RELEASE);
sauvegarderConfiguration();
afficherConfiguration();
return;
@@ -474,13 +509,14 @@ void traiterLigneSerie(char* commande) {
Serial.println("!! Remappage des canaux refuse pendant la conduite (desarmer d'abord) !!");
return;
}
int nouveauCanal = atoi(&commande[2]);
if (nouveauCanal < 1 || nouveauCanal > 16) {
Serial.println("!! Canal invalide : doit etre entre 1 et 16 !!");
int nouveauCanal = 0;
if (!parseStrictInt(&commande[2], nouveauCanal) || nouveauCanal < 1 || nouveauCanal > 16) {
Serial.println("!! Canal invalide : doit etre un entier entre 1 et 16 !!");
return;
}
if (nouveauCanal == CANAL_ARM) {
Serial.printf("!! Canal %d reserve a l'armement (R2) !!\n", CANAL_ARM);
if (estCanalReserve((uint8_t)nouveauCanal)) {
Serial.printf("!! Canal %d reserve (ARM=CH%d, HT=CH%d..CH%d) !!\n",
nouveauCanal, CANAL_ARM, CANAL_HT_PAN, CANAL_HT_ROLL);
return;
}
@@ -512,60 +548,63 @@ void traiterLigneSerie(char* commande) {
sauvegarderConfiguration();
afficherConfiguration();
} else if (periph == 'D' || periph == 'd') {
int val = atoi(&commande[2]);
if (val >= 0 && val <= 255) {
int val = 0;
if (parseStrictInt(&commande[2], val) && val >= 0 && val <= 255) {
configSysteme.forceRessort = (uint8_t)val; // Atomique sur ARM Cortex-M33
majRessortRequise = true;
__atomic_store_n(&majRessortRequise, true, __ATOMIC_RELEASE);
demanderOuExecuterSauvegarde();
afficherConfiguration();
} else {
Serial.println("!! Durete (D) doit etre entre 0 et 255 !!");
Serial.println("!! Durete (D) doit etre un entier entre 0 et 255 !!");
}
} else if (periph == 'P' || periph == 'p') {
if (estActuellementArme()) {
Serial.println("!! Reglage de plage (P) refuse pendant la conduite (desarmer d'abord) !!");
return;
}
int val = atoi(&commande[2]);
if (val >= 40 && val <= 900) {
int val = 0;
if (parseStrictInt(&commande[2], val) && val >= 40 && val <= 900) {
rp2040.idleOtherCore();
configSysteme.angleSouhaiteTotal = (uint16_t)val;
recalculerParametresVolant();
rp2040.resumeOtherCore();
majRangeRequise = true;
__atomic_store_n(&majRangeRequise, true, __ATOMIC_RELEASE);
sauvegarderConfiguration();
afficherConfiguration();
} else {
Serial.println("!! Plage d'angle (P) doit etre entre 40 et 900 degres !!");
Serial.println("!! Plage d'angle (P) doit etre un entier entre 40 et 900 degres !!");
}
} else if (periph == 'X' || periph == 'x') {
if (estActuellementArme()) {
Serial.println("!! Reglage d'expo (X) refuse pendant la conduite (desarmer d'abord) !!");
return;
}
float val = atof(&commande[2]);
if (val >= 0.0f && val <= 0.8f) {
float val = 0.0f;
if (parseStrictFloat(&commande[2], val) && val >= 0.0f && val <= 0.8f) {
rp2040.idleOtherCore();
configSysteme.expoVolant = val;
rp2040.resumeOtherCore();
sauvegarderConfiguration();
afficherConfiguration();
} else {
Serial.println("!! Expo volant (X) doit etre entre 0.0 et 0.8 !!");
Serial.println("!! Expo volant (X) doit etre un nombre entre 0.0 et 0.8 !!");
}
} else if (periph == 'T' || periph == 't') {
int val = atoi(&commande[2]);
if (val >= 0 && val <= 100) {
int val = 0;
if (parseStrictInt(&commande[2], val) && val >= 0 && val <= 100) {
configSysteme.intensiteVibration = (uint8_t)val; // Atomique sur ARM Cortex-M33
cockpitEtatModifie = true;
__atomic_store_n(&cockpitEtatModifie, true, __ATOMIC_RELEASE);
demanderOuExecuterSauvegarde();
afficherConfiguration();
} else {
Serial.println("!! Vibrations (T) doit etre entre 0 et 100% !!");
Serial.println("!! Vibrations (T) doit etre un entier entre 0 et 100% !!");
}
} else if (periph == 'W' || periph == 'w') {
cockpitEchoUSB = (atoi(&commande[2]) != 0);
Serial.printf(">> [COCKPIT] Echo trames $G29 sur USB : %s\n", cockpitEchoUSB ? "ON" : "OFF");
int val = 0;
if (parseStrictInt(&commande[2], val)) {
cockpitEchoUSB = (val != 0);
Serial.printf(">> [COCKPIT] Echo trames $G29 sur USB : %s\n", cockpitEchoUSB ? "ON" : "OFF");
}
}
return;
}
@@ -624,22 +663,24 @@ void traiterLigneSerie(char* commande) {
return;
}
rp2040.idleOtherCore();
sourceActive = cible;
__atomic_store_n(&sourceActive, cible, __ATOMIC_RELEASE);
extRcActif = false;
extArme = false;
extRapport = 0;
__atomic_store_n(&extArme, false, __ATOMIC_RELEASE);
__atomic_store_n(&extRapport, 0, __ATOMIC_RELEASE);
extAccelPct = 0;
extFreinPct = 0;
estArme = false;
rapportEngage = 0;
extEmbrayagePct = 0;
extVolantPct = 0;
__atomic_store_n(&estArme, false, __ATOMIC_RELEASE);
__atomic_store_n(&rapportEngage, 0, __ATOMIC_RELEASE);
boutonArmDejaEnfonce = true;
palettePlusDejaEnfoncee = true;
paletteMoinsDejaEnfoncee = true;
etatBoutonsCockpitPrec = 0xFFFF;
reinitialiserCanauxCRSF();
rp2040.resumeOtherCore();
majLedRequise = true;
cockpitEtatModifie = true;
__atomic_store_n(&majLedRequise, true, __ATOMIC_RELEASE);
__atomic_store_n(&cockpitEtatModifie, true, __ATOMIC_RELEASE);
Serial.printf(">> [SRC] Source active basculee sur : %s\n",
(sourceActive == SRC_EXT) ? "EXT (Steam Controller)" : "G29 (Volant)");
return;
@@ -650,12 +691,13 @@ void traiterLigneSerie(char* commande) {
if (strncmp(commande, "$GEARS,", 7) == 0) {
int fMin = 0, g1 = 0, g2 = 0, g3 = 0, rMin = 0, rMax = 0;
if (sscanf(commande + 7, "%d,%d,%d,%d,%d,%d", &fMin, &g1, &g2, &g3, &rMin, &rMax) == 6) {
uint16_t vFMin = (uint16_t)constrain(fMin, CRSF_VAL_MID, CRSF_VAL_MAX);
uint16_t vG1 = (uint16_t)constrain(g1, (int)vFMin, CRSF_VAL_MAX);
uint16_t vG2 = (uint16_t)constrain(g2, (int)vFMin, CRSF_VAL_MAX);
uint16_t vG3 = (uint16_t)constrain(g3, (int)vFMin, CRSF_VAL_MAX);
uint16_t vRMin = (uint16_t)constrain(rMin, CRSF_VAL_MIN, CRSF_VAL_MID);
uint16_t vRMax = (uint16_t)constrain(rMax, CRSF_VAL_MIN, (int)vRMin);
// Bornes strictes (max > min en AV, max < min en AR) pour éliminer toute division par zéro dans map().
uint16_t vFMin = (uint16_t)constrain(fMin, CRSF_VAL_MID, CRSF_VAL_MAX - 1);
uint16_t vG1 = (uint16_t)constrain(g1, (int)vFMin + 1, CRSF_VAL_MAX);
uint16_t vG2 = (uint16_t)constrain(g2, (int)vFMin + 1, CRSF_VAL_MAX);
uint16_t vG3 = (uint16_t)constrain(g3, (int)vFMin + 1, CRSF_VAL_MAX);
uint16_t vRMin = (uint16_t)constrain(rMin, CRSF_VAL_MIN + 1, CRSF_VAL_MID);
uint16_t vRMax = (uint16_t)constrain(rMax, CRSF_VAL_MIN, (int)vRMin - 1);
bool modifie = (configSysteme.gazAvantMin != vFMin) ||
(configSysteme.gazAvantMax[0] != vG1) ||
@@ -664,17 +706,32 @@ void traiterLigneSerie(char* commande) {
(configSysteme.gazArriereMin != vRMin) ||
(configSysteme.gazArriereMax != vRMax);
configSysteme.gazAvantMin = vFMin;
configSysteme.gazAvantMax[0] = vG1;
configSysteme.gazAvantMax[1] = vG2;
configSysteme.gazAvantMax[2] = vG3;
configSysteme.gazArriereMin = vRMin;
configSysteme.gazArriereMax = vRMax;
if (modifie) {
sauvegarderConfiguration();
Serial.printf(">> [VITESSES] AV_MIN=%u | 1=%u | 2=%u | 3=%u | AR_MIN=%u | AR_MAX=%u\n",
vFMin, vG1, vG2, vG3, vRMin, vRMax);
if (estActuellementArme()) {
// Sécurité : jamais d'idleOtherCore / EEPROM.commit() en conduite armée (gel Flash 50-100 ms).
// On applique les plafonds en RAM et on diffère l'écriture Flash au désarmement.
configSysteme.gazAvantMin = vFMin;
configSysteme.gazAvantMax[0] = vG1;
configSysteme.gazAvantMax[1] = vG2;
configSysteme.gazAvantMax[2] = vG3;
configSysteme.gazArriereMin = vRMin;
configSysteme.gazArriereMax = vRMax;
sauvegardeDifferee = true;
Serial.printf(">> [VITESSES] Maj RAM (Flash differee au desarmement) : AV_MIN=%u | 1=%u | 2=%u | 3=%u | AR_MIN=%u | AR_MAX=%u\n",
vFMin, vG1, vG2, vG3, vRMin, vRMax);
} else {
rp2040.idleOtherCore();
configSysteme.gazAvantMin = vFMin;
configSysteme.gazAvantMax[0] = vG1;
configSysteme.gazAvantMax[1] = vG2;
configSysteme.gazAvantMax[2] = vG3;
configSysteme.gazArriereMin = vRMin;
configSysteme.gazArriereMax = vRMax;
rp2040.resumeOtherCore();
sauvegarderConfiguration();
Serial.printf(">> [VITESSES] AV_MIN=%u | 1=%u | 2=%u | 3=%u | AR_MIN=%u | AR_MAX=%u\n",
vFMin, vG1, vG2, vG3, vRMin, vRMax);
}
}
}
return;
@@ -683,7 +740,7 @@ void traiterLigneSerie(char* commande) {
// Injection conduite externe (Steam Controller via SteamFrame FPV) :
// $RC,<steer>,<accel>,<brake>,<clutch>,<arm>,<gear>
if (strncmp(commande, "$RC,", 4) == 0) {
if (sourceActive != SRC_EXT) {
if (__atomic_load_n(&sourceActive, __ATOMIC_ACQUIRE) != SRC_EXT) {
return;
}
int steer = CRSF_VAL_MID, accel = CRSF_VAL_MID, brake = CRSF_VAL_MID, clutch = CRSF_VAL_MID;
@@ -699,38 +756,48 @@ void traiterLigneSerie(char* commande) {
// Sécurité : refuser un armement (0 -> 1) si rapport != N ou gaz non neutres
if (demandeArm && !extArme) {
if (vGear == 0 && vAccel == CRSF_VAL_MID) {
extArme = true;
__atomic_store_n(&extArme, true, __ATOMIC_RELEASE);
momentArmement_ms = millis();
momentDesarmement_ms = 0;
majLedRequise = true;
cockpitEtatModifie = true;
__atomic_store_n(&majLedRequise, true, __ATOMIC_RELEASE);
__atomic_store_n(&cockpitEtatModifie, true, __ATOMIC_RELEASE);
Serial.println(">> [ARM EXT] ARME (Steam Controller)");
}
} else if (!demandeArm && extArme) {
extArme = false;
__atomic_store_n(&extArme, false, __ATOMIC_RELEASE);
momentDesarmement_ms = millis();
momentArmement_ms = 0;
majLedRequise = true;
cockpitEtatModifie = true;
__atomic_store_n(&majLedRequise, true, __ATOMIC_RELEASE);
__atomic_store_n(&cockpitEtatModifie, true, __ATOMIC_RELEASE);
Serial.println(">> [ARM EXT] DESARME (Steam Controller)");
}
if (vGear != extRapport) {
extRapport = vGear;
majLedRequise = true;
cockpitEtatModifie = true;
__atomic_store_n(&extRapport, vGear, __ATOMIC_RELEASE);
__atomic_store_n(&majLedRequise, true, __ATOMIC_RELEASE);
__atomic_store_n(&cockpitEtatModifie, true, __ATOMIC_RELEASE);
}
// Défense en profondeur : appliquer aussi les plafonds CRSF par rapport côté RP2350
if (!extArme || extRapport == 0) {
vAccel = CRSF_VAL_MID;
} else if (extRapport >= 1 && extRapport <= 3) {
uint16_t maxV = configSysteme.gazAvantMax[extRapport - 1];
vAccel = (uint16_t)constrain((int)vAccel, CRSF_VAL_MID, (int)maxV);
} else if (extRapport == -1) {
vAccel = (uint16_t)constrain((int)vAccel, (int)configSysteme.gazArriereMax, CRSF_VAL_MID);
}
uint8_t accelPct = 0;
if (extArme && extRapport >= 1 && extRapport <= 3 && vAccel >= configSysteme.gazAvantMin) {
uint16_t maxV = configSysteme.gazAvantMax[extRapport - 1];
accelPct = (uint8_t)constrain(map(vAccel, configSysteme.gazAvantMin, maxV, 0, 100), 0, 100);
if (maxV > configSysteme.gazAvantMin) {
accelPct = (uint8_t)constrain(map(vAccel, configSysteme.gazAvantMin, maxV, 0, 100), 0, 100);
}
} else if (extArme && extRapport == -1 && vAccel <= configSysteme.gazArriereMin) {
accelPct = (uint8_t)constrain(map(vAccel, configSysteme.gazArriereMin, configSysteme.gazArriereMax, 0, 100), 0, 100);
if (configSysteme.gazArriereMin > configSysteme.gazArriereMax) {
accelPct = (uint8_t)constrain(map(vAccel, configSysteme.gazArriereMin, configSysteme.gazArriereMax, 0, 100), 0, 100);
}
}
uint8_t brakePct = (vBrake > CRSF_VAL_MID)
? (uint8_t)constrain(map(vBrake, CRSF_VAL_MID, CRSF_VAL_MAX, 0, 100), 0, 100)
@@ -756,34 +823,39 @@ void traiterLigneSerie(char* commande) {
dernierPaquetRC_ms = millis();
if (!extRcActif) {
extRcActif = true;
majLedRequise = true;
cockpitEtatModifie = true;
__atomic_store_n(&majLedRequise, true, __ATOMIC_RELEASE);
__atomic_store_n(&cockpitEtatModifie, true, __ATOMIC_RELEASE);
}
}
return;
}
}
void lireFluxSerie(Stream& port, char* buf, uint8_t& idx, size_t maxLen) {
while (port.available() > 0) {
void lireFluxSerie(Stream& port, char* buf, uint8_t& idx, bool& overflow, size_t maxLen, bool depuisUsb) {
int budget = 96; // Borner le temps passé dans loop() pour préserver la cadence CRSF 166 Hz
while (port.available() > 0 && budget-- > 0) {
char c = (char)port.read();
if (c == '\n' || c == '\r') {
if (idx > 0) {
if (!overflow && idx > 0) {
buf[idx] = '\0';
traiterLigneSerie(buf);
idx = 0;
traiterLigneSerie(buf, depuisUsb);
}
idx = 0;
overflow = false;
} else if (overflow) {
// Ignorer le reste de la ligne trop longue jusqu'au prochain retour à la ligne
} else if (idx < maxLen - 1) {
buf[idx++] = c;
} else {
idx = 0; // Ligne trop longue, reset
idx = 0;
overflow = true;
}
}
}
void verifierCommandesSerie() {
lireFluxSerie(Serial, serialBuffer, serialBufferIdx, sizeof(serialBuffer));
lireFluxSerie(Serial2, serial2Buffer, serial2BufferIdx, sizeof(serial2Buffer));
lireFluxSerie(Serial, serialBuffer, serialBufferIdx, serialBufferOverflow, sizeof(serialBuffer), true);
lireFluxSerie(Serial2, serial2Buffer, serial2BufferIdx, serial2BufferOverflow, sizeof(serial2Buffer), false);
}
// -------------------------------------------------------------------------
@@ -896,15 +968,19 @@ void setup() {
Serial1.setTX(0);
Serial1.setRX(1);
Serial1.setFIFOSize(256);
Serial1.begin(420000);
Serial2.setTX(PIN_UART_BRIDGE_TX);
Serial2.setRX(PIN_UART_BRIDGE_RX);
Serial2.setFIFOSize(512);
Serial2.begin(UART_BRIDGE_BAUD);
Serial.println("\n--- WAVESHARE RP2350-USB-A PRETE ---");
afficherConfiguration();
momentDemarrageCore0_ms = millis();
// Watchdog matériel : reboot si loop() ne le nourrit plus pendant WATCHDOG_TIMEOUT_MS
if (watchdog_caused_reboot()) {
Serial.println("!! [WATCHDOG] Redemarrage suite a un blocage !!");
@@ -912,15 +988,24 @@ void setup() {
rp2040.wdt_begin(WATCHDOG_TIMEOUT_MS);
}
static inline bool coeur1EstSain(uint32_t now) {
if (__atomic_load_n(&core1Demarre, __ATOMIC_ACQUIRE)) {
uint32_t hb = __atomic_load_n(&heartbeatCore1_ms, __ATOMIC_ACQUIRE);
return (now - hb) <= TIMEOUT_FAILSAFE_MS;
}
// Grâce de démarrage de 5 s pour laisser setup1() initialiser PIO-USB ; au-delà, faute Core 1.
return (now - momentDemarrageCore0_ms) <= 5000UL;
}
// Évalue le failsafe (cœur 0). Retourne true si les canaux doivent être forcés au neutre.
bool evaluerFailsafe() {
uint32_t now = millis();
// 1. Surveillance de la santé du Cœur 1 (Watchdog logique inter-cœur)
if (heartbeatCore1_ms > 0 && (now - heartbeatCore1_ms > TIMEOUT_FAILSAFE_MS)) {
if (!coeur1EstSain(now)) {
if (!failsafeActif) {
failsafeActif = true;
majLedRequise = true;
__atomic_store_n(&majLedRequise, true, __ATOMIC_RELEASE);
Serial.println(F("!! [FAILSAFE] Perte de reponse du Coeur 1 (Watchdog) !!"));
}
return true;
@@ -1089,10 +1174,24 @@ void traiterTelemetrieCRSF() {
}
void emettreLigneCockpit(const char* ligne) {
Serial2.println(ligne);
int needed = (int)strlen(ligne) + 2;
char framed[192];
const char* toSend = ligne;
// Ajouter un CRC-8 DVB-S2 (*XX) sur les trames $G29 et $G29_EVT (protège la liaison UART 460k)
if (strncmp(ligne, "$G29,", 5) == 0 || strncmp(ligne, "$G29_EVT,", 9) == 0) {
size_t len = strlen(ligne);
if (len + 4 < sizeof(framed)) {
uint8_t crc = calculerCrc8Crsf((const uint8_t*)ligne, len);
snprintf(framed, sizeof(framed), "%s*%02X", ligne, crc);
toSend = framed;
}
}
int needed = (int)strlen(toSend) + 2;
// SerialUART::availableForWrite() sur arduino-pico renvoie >= 1 si de la place est libre en FIFO
if (Serial2.availableForWrite() > 0) {
Serial2.println(toSend);
}
if (cockpitEchoUSB && Serial && Serial.availableForWrite() >= needed) {
Serial.println(ligne);
Serial.println(toSend);
}
}
@@ -1198,8 +1297,8 @@ void gererTimeoutRcExterne() {
}
void loop() {
// Watchdog dual-core : ne réarmer le watchdog matériel que si le Cœur 1 est également vivant
if (heartbeatCore1_ms == 0 || (millis() - heartbeatCore1_ms <= TIMEOUT_FAILSAFE_MS)) {
// Watchdog dual-core : ne réarmer le watchdog matériel que si le Cœur 1 est vivant (ou dans la grâce boot 5 s)
if (coeur1EstSain(millis())) {
rp2040.wdt_reset();
}
verifierCommandesSerie();
@@ -1213,8 +1312,8 @@ void loop() {
bool enAnimationArm = (momentArmement_ms > 0 && (millis() - momentArmement_ms < 850)) ||
(momentDesarmement_ms > 0 && (millis() - momentDesarmement_ms < 250));
if (majLedRequise || (enAnimationArm && (millis() - dernierTickAnimNeo_ms >= 50))) {
majLedRequise = false;
if (__atomic_exchange_n(&majLedRequise, false, __ATOMIC_ACQ_REL)
|| (enAnimationArm && (millis() - dernierTickAnimNeo_ms >= 50))) {
dernierTickAnimNeo_ms = millis();
actualiserLED();
int8_t rap = rapportActuel();
@@ -1596,7 +1695,8 @@ void setup1() {
}
void loop1() {
heartbeatCore1_ms = millis();
__atomic_store_n(&heartbeatCore1_ms, millis(), __ATOMIC_RELEASE);
__atomic_store_n(&core1Demarre, true, __ATOMIC_RELEASE);
USBHost.task();
if (!volant_est_pret) return;
@@ -1638,20 +1738,22 @@ void loop1() {
}
// 4. Envoi immédiat des trames prioritaires dès que le pipe USB est libre (sans bloquer loop1)
if (majRangeRequise) {
if (__atomic_load_n(&majRangeRequise, __ATOMIC_ACQUIRE)) {
if (envoyerPlageG29(configSysteme.angleSouhaiteTotal)) {
majRangeRequise = false;
__atomic_store_n(&majRangeRequise, false, __ATOMIC_RELEASE);
}
}
if (majRessortRequise) {
if (__atomic_load_n(&majRessortRequise, __ATOMIC_ACQUIRE)) {
if (envoyerRessortG29(configSysteme.forceRessort)) {
majRessortRequise = false;
__atomic_store_n(&majRessortRequise, false, __ATOMIC_RELEASE);
}
}
// Arrêt prioritaire du moteur de vibration dès le désarmement (ou si source externe active)
if ((sourceActive != SRC_G29 || !estArme) && !forceEstAuNeutre) {
// Arrêt prioritaire du moteur de vibration dès le désarmement (ou si source externe active),
// sauf si une butée logicielle (900°) est activement en cours pour éviter le battement à 25 Hz.
if ((__atomic_load_n(&sourceActive, __ATOMIC_ACQUIRE) != SRC_G29 || !estArme)
&& !murActifDroite && !murActifGauche && !forceEstAuNeutre) {
if (arreterForceG29()) {
forceEstAuNeutre = true;
return;
+17 -9
View File
@@ -1,22 +1,30 @@
#!/usr/bin/env bash
# SteamFrame FPV Launcher
set -e
set -euo pipefail
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"
cd "$DIR"
# S'assurer que cargo est dans PATH même sous session non-login (SteamOS / raccourci bureau)
if [ -d "$HOME/.cargo/bin" ]; then
export PATH="$HOME/.cargo/bin:$PATH"
fi
# Vérifier les dépendances locales de linkage (libxkbcommon-x11)
mkdir -p "$HOME/.local/lib"
if [ ! -f "$HOME/.local/lib/libxkbcommon-x11.so" ]; then
if [ -f "/usr/lib/x86_64-linux-gnu/libxkbcommon-x11.so.0" ]; then
ln -sf /usr/lib/x86_64-linux-gnu/libxkbcommon-x11.so.0 "$HOME/.local/lib/libxkbcommon-x11.so"
elif [ -f "/usr/lib/libxkbcommon-x11.so.0" ]; then
ln -sf /usr/lib/libxkbcommon-x11.so.0 "$HOME/.local/lib/libxkbcommon-x11.so"
elif [ -f "/usr/lib/libxkbcommon-x11.so" ]; then
ln -sf /usr/lib/libxkbcommon-x11.so "$HOME/.local/lib/libxkbcommon-x11.so"
fi
for candidate in \
"/usr/lib/x86_64-linux-gnu/libxkbcommon-x11.so.0" \
"/usr/lib/aarch64-linux-gnu/libxkbcommon-x11.so.0" \
"/usr/lib/libxkbcommon-x11.so.0" \
"/usr/lib/libxkbcommon-x11.so"; do
if [ -f "$candidate" ]; then
ln -sf "$candidate" "$HOME/.local/lib/libxkbcommon-x11.so"
break
fi
done
fi
export LD_LIBRARY_PATH="$HOME/.local/lib:${LD_LIBRARY_PATH:-}"
export LD_LIBRARY_PATH="$HOME/.local/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
# Vérifier si le binaire release existe, sinon le compiler
if [ ! -f "$DIR/target/release/steamframe-fpv" ]; then
+19 -4
View File
@@ -1,15 +1,30 @@
#!/usr/bin/env bash
# SteamFrame FPV — Lanceur VR Natif (Mode Gaming SteamOS / OpenXR Direct sans fenêtre 2D)
set -e
set -euo pipefail
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"
cd "$DIR"
# Bibliothèques locales éventuelles
if [ -d "$HOME/.local/lib" ]; then
export LD_LIBRARY_PATH="$HOME/.local/lib:${LD_LIBRARY_PATH:-}"
if [ -d "$HOME/.cargo/bin" ]; then
export PATH="$HOME/.cargo/bin:$PATH"
fi
# Bibliothèques locales éventuelles (sans ':' final qui ajouterait CWD à LD_LIBRARY_PATH)
mkdir -p "$HOME/.local/lib"
if [ ! -f "$HOME/.local/lib/libxkbcommon-x11.so" ]; then
for candidate in \
"/usr/lib/aarch64-linux-gnu/libxkbcommon-x11.so.0" \
"/usr/lib/x86_64-linux-gnu/libxkbcommon-x11.so.0" \
"/usr/lib/libxkbcommon-x11.so.0" \
"/usr/lib/libxkbcommon-x11.so"; do
if [ -f "$candidate" ]; then
ln -sf "$candidate" "$HOME/.local/lib/libxkbcommon-x11.so"
break
fi
done
fi
export LD_LIBRARY_PATH="$HOME/.local/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
# Compiler en Release si le binaire n'est pas encore présent
if [ ! -f "$DIR/target/release/steamframe-fpv" ]; then
echo "Compilation initiale de SteamFrame FPV en mode Release..."
+5 -4
View File
@@ -1,8 +1,9 @@
# Règle Udev pour le récepteur Eachine Sphere Link (Radxa Zero 3W / Rockchip RV1106 / RNDIS)
# Déclenche l'attribution de l'IP 192.168.1.10/24 dès que le câble USB-C est branché sur le Steam Frame ou PC
ACTION=="add", SUBSYSTEM=="net", KERNEL=="usb*|enx*", ATTRS{idVendor}=="1d6b|2207|0525", RUN+="/usr/bin/ip addr add 192.168.1.10/24 dev %k", RUN+="/usr/bin/ip link set dev %k up"
# Règle Udev pour le récepteur Eachine Sphere Link (Radxa Zero 3W / Rockchip RV1106 / Linux Gadget RNDIS)
# IMPORTANT : ne JAMAIS inclure 1d6b (Linux Foundation USB Root Hub) dans ATTRS{idVendor},
# sinon TOUS les adaptateurs Ethernet USB Linux seraient détournés vers 192.168.1.10/24.
# On marque aussi NM_UNMANAGED=1 pour éviter que NetworkManager n'écrase l'IP statique par DHCP.
ACTION=="add", SUBSYSTEM=="net", KERNEL=="usb*|enx*", ATTRS{idVendor}=="2207|0525", ENV{NM_UNMANAGED}="1", RUN+="/bin/sh -c 'ip addr replace 192.168.1.10/24 dev %k && ip link set dev %k up'"
# Accès HIDRAW non-root (uaccess) pour le Steam Controller (Ibex 28de:1302..1305) en Mode Gaming SteamOS
# Permet la lecture directe des rapports 0x42 et les retours haptiques 0x80 sans sudo ni conflit Lizard Mode
KERNEL=="hidraw*", ATTRS{idVendor}=="28de", ATTRS{idProduct}=="1302|1303|1304|1305", MODE="0660", TAG+="uaccess"
SUBSYSTEM=="hidraw", ATTRS{idVendor}=="28de", ATTRS{idProduct}=="1302|1303|1304|1305", MODE="0660", TAG+="uaccess"
+12 -7
View File
@@ -28,12 +28,13 @@ if [ "$ARCH" = "aarch64" ]; then
echo "[3/3] Installation locale des lanceurs .desktop (Bureau GPUI + Mode VR Gaming)..."
mkdir -p ~/.local/share/applications
chmod +x "$DIR/launch.sh" "$DIR/launch_vr.sh"
ESCAPED_DIR=$(printf '%s\n' "$DIR" | sed -e 's/[&|\\]/\\&/g')
for desktop_file in steamframe-fpv.desktop steamframe-fpv-vr.desktop; do
cp "$desktop_file" ~/.local/share/applications/
sed -i -E \
-e "s|^Exec=.*/(launch(_vr)?\.sh)|Exec=$DIR/\1|g" \
-e "s|^Path=.*|Path=$DIR|g" \
-e "s|^Icon=.*/assets/|Icon=$DIR/assets/|g" \
-e "s|^Exec=.*/(launch(_vr)?\.sh)|Exec=${ESCAPED_DIR}/\1|g" \
-e "s|^Path=.*|Path=${ESCAPED_DIR}|g" \
-e "s|^Icon=.*/assets/|Icon=${ESCAPED_DIR}/assets/|g" \
"$HOME/.local/share/applications/$desktop_file"
done
@@ -41,13 +42,17 @@ if [ "$ARCH" = "aarch64" ]; then
echo " Mode Gaming : ajoutez 'SteamFrame FPV (Mode VR)' (launch_vr.sh) en jeu non-Steam."
else
echo "[!] Exécution sur hôte ${ARCH} (Ubuntu / PC de développement)."
echo "[2/3] Compilation Release hôte standard..."
cargo build --release
if [ "${1:-}" != "--package-only" ]; then
echo "[2/3] Compilation Release hôte standard..."
cargo build --release
else
echo "[2/3] Mode --package-only : compilation hôte ignorée."
fi
echo "[3/3] Création de l'archive de déploiement pour le Steam Frame..."
mkdir -p dist
tar --exclude="target" --exclude=".git" -czf dist/steamframe-fpv-deploy.tar.gz \
Cargo.toml Cargo.lock src scripts assets README.md launch.sh launch_vr.sh steamframe-fpv.desktop steamframe-fpv-vr.desktop
tar --exclude="target" --exclude=".git" --exclude="__pycache__" -czf dist/steamframe-fpv-deploy.tar.gz \
Cargo.toml Cargo.lock src patches scripts assets README.md launch.sh launch_vr.sh steamframe-fpv.desktop steamframe-fpv-vr.desktop
echo "=== SUCCÈS : Archive de déploiement créée dans $DIR/dist/steamframe-fpv-deploy.tar.gz ==="
echo "Pour déployer sur le casque, lancez : ./scripts/deploy_to_steamframe.sh [ip_steamframe]"
+6 -6
View File
@@ -5,7 +5,7 @@ set -euo pipefail
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." >/dev/null 2>&1 && pwd)"
cd "$DIR"
TARGET_HOST="${1:-deck@192.168.1.15}"
TARGET_HOST="${1:-deck@192.168.1.10}"
echo "=== Déploiement de SteamFrame FPV vers le casque : ${TARGET_HOST} ==="
@@ -18,16 +18,16 @@ if ! ssh -o ConnectTimeout=3 -o BatchMode=yes "${TARGET_HOST}" "echo 'Connexion
fi
echo "[2/5] Préparation du paquet de déploiement..."
./scripts/build_steamframe_arm64.sh
./scripts/build_steamframe_arm64.sh --package-only
echo "[3/5] Transfert des fichiers du projet sur le Steam Frame..."
ssh "${TARGET_HOST}" "mkdir -p ~/projects/steamframe_fpv"
scp dist/steamframe-fpv-deploy.tar.gz "${TARGET_HOST}:~/projects/steamframe_fpv/"
ssh "${TARGET_HOST}" "cd ~/projects/steamframe_fpv && tar -xzf steamframe-fpv-deploy.tar.gz && chmod +x scripts/*.sh launch.sh launch_vr.sh"
ssh "${TARGET_HOST}" "cd ~/projects/steamframe_fpv && tar -xzf steamframe-fpv-deploy.tar.gz && rm -f steamframe-fpv-deploy.tar.gz && chmod +x scripts/*.sh launch.sh launch_vr.sh"
echo "[4/5] Installation de la règle udev USB RNDIS (auto-attribution 192.168.1.10/24)..."
scp scripts/99-radxa-vrx-rndis.rules "${TARGET_HOST}:/tmp/"
ssh "${TARGET_HOST}" "sudo cp /tmp/99-radxa-vrx-rndis.rules /etc/udev/rules.d/ && sudo udevadm control --reload-rules"
echo "[4/5] Installation de la règle udev USB RNDIS & HIDRAW..."
scp scripts/99-radxa-vrx-rndis.rules "${TARGET_HOST}:/tmp/99-radxa-vrx-rndis.rules"
ssh -t "${TARGET_HOST}" "sudo cp /tmp/99-radxa-vrx-rndis.rules /etc/udev/rules.d/ && rm -f /tmp/99-radxa-vrx-rndis.rules && sudo udevadm control --reload-rules && sudo udevadm trigger --subsystem-match=hidraw --subsystem-match=net"
echo "[5/5] Compilation Release native ARM64 sur le casque..."
ssh "${TARGET_HOST}" "cd ~/projects/steamframe_fpv && ./scripts/build_steamframe_arm64.sh"
View File
File mode changed.
+133 -59
View File
@@ -5,6 +5,8 @@ Relie la Waveshare RP2350 (g29_crsf) au casque Steam Frame (192.168.1.10:14552)
via l'interface USB Gadget RNDIS (usb0) sans aucune dépendance externe (stdlib seule).
"""
import errno
import fcntl
import glob
import os
import select
@@ -18,13 +20,20 @@ BAUD_RATE = termios.B460800
BIND_IP = os.environ.get("STEAMFRAME_BIND_IP", "192.168.1.1")
CASQUE_IP = os.environ.get("STEAMFRAME_CASQUE_IP", "192.168.1.10")
UDP_PORT = int(os.environ.get("STEAMFRAME_G29_PORT", "14552"))
MAX_SERIAL_RX_BUF = 4096
MAX_SERIAL_TX_BUF = 4096
# Préfixes autorisés du casque vers la RP2350 (bloque toute commande CLI brute comme B=BOOTSEL ou R=Reset)
ALLOWED_INBOUND_PREFIXES = (b"$HT,", b"$RC,", b"$SRC,", b"$GEARS,")
# Ordre de détection : USB CDC direct puis UART9_M1 (/dev/ttyS9, brochage Radxa Zero 3W documenté)
SERIAL_CANDIDATES = (
"/dev/ttyACM0",
"/dev/ttyACM1",
"/dev/ttyS9",
"/dev/ttyS4",
"/dev/ttyS5",
"/dev/ttyS3",
"/dev/ttyS9",
"/dev/ttyS0",
"/dev/ttyAMA0",
)
@@ -32,24 +41,33 @@ SERIAL_CANDIDATES = (
def open_serial(dev_path: str) -> int:
fd = os.open(dev_path, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
attrs = termios.tcgetattr(fd)
# Mode raw 8N1 sans contrôle de flux
attrs[0] = 0 # iflag
attrs[1] = 0 # oflag
attrs[2] = termios.CS8 | termios.CREAD | termios.CLOCAL # cflag
attrs[3] = 0 # lflag
attrs[4] = BAUD_RATE
attrs[5] = BAUD_RATE
attrs[6][termios.VMIN] = 0
attrs[6][termios.VTIME] = 0
termios.tcsetattr(fd, termios.TCSANOW, attrs)
try:
try:
fcntl.ioctl(fd, termios.TIOCEXCL)
except OSError:
pass
attrs = termios.tcgetattr(fd)
# Mode raw 8N1 sans contrôle de flux
attrs[0] = 0 # iflag
attrs[1] = 0 # oflag
attrs[2] = termios.CS8 | termios.CREAD | termios.CLOCAL # cflag
attrs[3] = 0 # lflag
attrs[4] = BAUD_RATE
attrs[5] = BAUD_RATE
attrs[6][termios.VMIN] = 0
attrs[6][termios.VTIME] = 0
termios.tcsetattr(fd, termios.TCSANOW, attrs)
termios.tcflush(fd, termios.TCIOFLUSH)
except Exception:
os.close(fd)
raise
return fd
def find_serial_device() -> Optional[str]:
forced = os.environ.get("G29_SERIAL_DEV")
if forced and os.path.exists(forced):
return forced
if forced:
return forced if os.path.exists(forced) else None
for pattern in SERIAL_CANDIDATES:
for path in sorted(glob.glob(pattern)):
if os.path.exists(path):
@@ -57,28 +75,49 @@ def find_serial_device() -> Optional[str]:
return None
def main() -> None:
def bind_udp_socket() -> tuple[socket.socket, str]:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
sock.bind((BIND_IP, UDP_PORT))
bound_ip = BIND_IP
except OSError as exc:
print(
f"[radxa_g29_relay] Bind {BIND_IP}:{UDP_PORT} impossible ({exc}), fallback 0.0.0.0",
file=sys.stderr,
flush=True,
)
sock.bind(("0.0.0.0", UDP_PORT))
bound_ip = "0.0.0.0"
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# Attendre brièvement au démarrage que usb0 (192.168.1.1) soit configurée avant fallback
for attempt in range(5):
try:
sock.bind((BIND_IP, UDP_PORT))
sock.setblocking(False)
return sock, BIND_IP
except OSError as exc:
if attempt < 4:
time.sleep(0.5)
else:
print(
f"[radxa_g29_relay] Bind {BIND_IP}:{UDP_PORT} impossible ({exc}), fallback 0.0.0.0",
file=sys.stderr,
flush=True,
)
sock.bind(("0.0.0.0", UDP_PORT))
sock.setblocking(False)
return sock, "0.0.0.0"
def close_serial(serial_fd: Optional[int]) -> None:
if serial_fd is not None:
try:
os.close(serial_fd)
except OSError:
pass
def main() -> None:
sock, bound_ip = bind_udp_socket()
print(
f"[radxa_g29_relay] UDP {bound_ip}:{UDP_PORT} <-> {CASQUE_IP}:{UDP_PORT} (filtre IP actif)",
f"[radxa_g29_relay] UDP {bound_ip}:{UDP_PORT} <-> {CASQUE_IP}:{UDP_PORT} (filtre IP + protocole $ actif)",
flush=True,
)
serial_fd: Optional[int] = None
serial_buf = bytearray()
serial_rx_buf = bytearray()
serial_tx_buf = bytearray()
last_casque_addr = (CASQUE_IP, UDP_PORT)
last_udp_err_log = 0.0
while True:
if serial_fd is None:
@@ -86,7 +125,8 @@ def main() -> None:
if dev is not None:
try:
serial_fd = open_serial(dev)
serial_buf.clear()
serial_rx_buf.clear()
serial_tx_buf.clear()
print(f"[radxa_g29_relay] Connecté à la RP2350 sur {dev}", flush=True)
except OSError as exc:
print(f"[radxa_g29_relay] Erreur ouverture {dev}: {exc}", file=sys.stderr, flush=True)
@@ -98,51 +138,85 @@ def main() -> None:
continue
rlist = [sock.fileno(), serial_fd]
wlist = [serial_fd] if serial_tx_buf else []
try:
readable, _, _ = select.select(rlist, [], [], 0.25)
readable, writable, _ = select.select(rlist, wlist, [], 0.25)
except (OSError, ValueError):
try:
os.close(serial_fd)
except OSError:
pass
close_serial(serial_fd)
serial_fd = None
continue
# 1. Réception UDP depuis le casque -> file d'émission UART (filtrée et non-bloquante)
if sock.fileno() in readable:
try:
data, addr = sock.recvfrom(512)
while True:
try:
data, addr = sock.recvfrom(1024)
except BlockingIOError:
break
except OSError:
break
if addr[0] not in (CASQUE_IP, "127.0.0.1"):
continue
last_casque_addr = (addr[0], UDP_PORT)
if data:
os.write(serial_fd, data)
except OSError:
try:
os.close(serial_fd)
except OSError:
pass
serial_fd = None
continue
for raw_line in data.splitlines():
line = raw_line.strip()
if not line or not line.startswith(ALLOWED_INBOUND_PREFIXES):
continue
payload = line + b"\n"
if len(serial_tx_buf) + len(payload) > MAX_SERIAL_TX_BUF:
# Préférer la trame la plus récente en cas de saturation UART
serial_tx_buf.clear()
serial_tx_buf.extend(payload)
if serial_fd in readable:
# 2. Vidange non-bloquante de la file TX vers la RP2350 (gère écritures partielles et EAGAIN)
if serial_tx_buf and (serial_fd in writable or sock.fileno() in readable):
try:
written = os.write(serial_fd, serial_tx_buf)
if written > 0:
del serial_tx_buf[:written]
except BlockingIOError:
pass
except OSError as exc:
if exc.errno not in (errno.EAGAIN, errno.EWOULDBLOCK):
close_serial(serial_fd)
serial_fd = None
print(f"[radxa_g29_relay] Erreur écriture RP2350 ({exc}), reconnexion...", flush=True)
continue
# 3. Lecture non-bloquante depuis la RP2350 -> émission UDP vers le casque
if serial_fd is not None and serial_fd in readable:
try:
chunk = os.read(serial_fd, 512)
if not chunk:
raise OSError("EOF série")
serial_buf.extend(chunk)
while b"\n" in serial_buf:
nl_idx = serial_buf.index(b"\n")
line = bytes(serial_buf[: nl_idx + 1]).strip()
del serial_buf[: nl_idx + 1]
serial_rx_buf.extend(chunk)
if len(serial_rx_buf) > MAX_SERIAL_RX_BUF:
# Protection anti-OOM si bruit série sans retour à la ligne
del serial_rx_buf[:-512]
while b"\n" in serial_rx_buf:
nl_idx = serial_rx_buf.index(b"\n")
line = bytes(serial_rx_buf[: nl_idx + 1]).strip()
del serial_rx_buf[: nl_idx + 1]
if line.startswith((b"$G29", b"$CRSF")):
sock.sendto(line + b"\n", last_casque_addr)
except OSError:
try:
os.close(serial_fd)
except OSError:
pass
serial_fd = None
print("[radxa_g29_relay] Liaison RP2350 perdue, attente reconnexion...", flush=True)
try:
sock.sendto(line + b"\n", last_casque_addr)
except OSError as exc:
# Une panne réseau usb0 (casque débranché) ne doit JAMAIS fermer le port série RP2350
now = time.monotonic()
if now - last_udp_err_log >= 5.0:
last_udp_err_log = now
print(
f"[radxa_g29_relay] Casque {last_casque_addr[0]} injoignable ({exc})",
file=sys.stderr,
flush=True,
)
except BlockingIOError:
pass
except OSError as exc:
if exc.errno not in (errno.EAGAIN, errno.EWOULDBLOCK):
close_serial(serial_fd)
serial_fd = None
print("[radxa_g29_relay] Liaison RP2350 perdue, attente reconnexion...", flush=True)
if __name__ == "__main__":
+11 -3
View File
@@ -21,18 +21,26 @@ if [ -f /boot/dtbo/rk3568-uart9-m1.dtbo.disabled ] && [ ! -f /boot/dtbo/rk3568-u
fi
if [ -f /boot/dtbo/rk3568-uart9-m1.dtbo ] && [ -f /boot/extlinux/extlinux.conf ]; then
if ! grep -q "rk3568-uart9-m1.dtbo" /boot/extlinux/extlinux.conf; then
sed -i 's|fdtoverlays \(.*\)|fdtoverlays \1 /boot/dtbo/rk3568-uart9-m1.dtbo|' /boot/extlinux/extlinux.conf
echo "[*] Overlay rk3568-uart9-m1.dtbo ajouté dans extlinux.conf (un reboot activera /dev/ttyS9)"
cp /boot/extlinux/extlinux.conf /boot/extlinux/extlinux.conf.bak
if grep -q "fdtoverlays" /boot/extlinux/extlinux.conf; then
sed -i 's|fdtoverlays \(.*\)|fdtoverlays \1 /boot/dtbo/rk3568-uart9-m1.dtbo|' /boot/extlinux/extlinux.conf
echo "[*] Overlay rk3568-uart9-m1.dtbo ajouté dans extlinux.conf (sauvegarde .bak créée, reboot requis)"
else
echo "[!] Aucune directive fdtoverlays trouvée dans /boot/extlinux/extlinux.conf — ajoutez rk3568-uart9-m1.dtbo manuellement."
fi
fi
fi
cat << 'UNIT' > /etc/systemd/system/steamframe-g29-relay.service
[Unit]
Description=SteamFrame FPV Unified G29/CRSF <-> USB0 UDP Relay
After=network.target
After=network-online.target
Wants=network-online.target
StartLimitIntervalSec=0
[Service]
Type=simple
Environment=G29_SERIAL_DEV=/dev/ttyS9
ExecStart=/usr/bin/python3 /usr/local/bin/radxa_g29_relay.py
Restart=always
RestartSec=1
+39 -19
View File
@@ -1,6 +1,6 @@
#!/usr/bin/env bash
# Script de validation automatique de la chaîne OpenXR & des Modes de Projection
set -e
set -euo pipefail
RED='\033[0;31m'
GREEN='\033[0;32m'
@@ -18,16 +18,33 @@ echo -e "${BLUE}======================================================${NC}"
# 1. Vérification du service Monado
echo -n "Vérification du service Monado... "
STARTED_MONADO=0
if pgrep monado-service >/dev/null 2>&1; then
MONADO_FIFO=""
MONADO_KEEPALIVE_PID=""
MONADO_WRAPPER_PID=""
cleanup() {
if [ "$STARTED_MONADO" -eq 1 ]; then
[ -n "$MONADO_KEEPALIVE_PID" ] && kill "$MONADO_KEEPALIVE_PID" 2>/dev/null || true
[ -n "$MONADO_WRAPPER_PID" ] && kill "$MONADO_WRAPPER_PID" 2>/dev/null || true
pkill -x monado-service 2>/dev/null || true
[ -n "$MONADO_FIFO" ] && rm -f "$MONADO_FIFO"
fi
}
trap cleanup EXIT
if pgrep -x monado-service >/dev/null 2>&1; then
echo -e "${GREEN}[OK - Monado est actif]${NC}"
else
echo -e "${YELLOW}[Démarrage de Monado en arrière-plan...]${NC}"
tail -f /dev/null | ./scripts/start_monado_simulated.sh >/tmp/monado_test.log 2>&1 &
MONADO_FIFO=$(mktemp -u /tmp/monado_stdin_XXXXXX.fifo)
mkfifo "$MONADO_FIFO"
sleep infinity > "$MONADO_FIFO" &
MONADO_KEEPALIVE_PID=$!
./scripts/start_monado_simulated.sh < "$MONADO_FIFO" >/tmp/monado_test.log 2>&1 &
MONADO_WRAPPER_PID=$!
STARTED_MONADO=1
trap 'if [ "$STARTED_MONADO" -eq 1 ]; then pkill -f monado-service 2>/dev/null || true; kill "$MONADO_WRAPPER_PID" 2>/dev/null || true; fi' EXIT
sleep 2
if pgrep monado-service >/dev/null 2>&1; then
if pgrep -x monado-service >/dev/null 2>&1; then
echo -e "${GREEN}[OK - Monado démarré]${NC}"
else
echo -e "${RED}[ERREUR] Impossible de contacter Monado.${NC}"
@@ -36,23 +53,25 @@ else
fi
fi
# 2. Test unitaire Rust
echo -e "\n${BLUE}--- Étape 1 : Tests unitaires Rust (Maths & Dé-distorsion) ---${NC}"
# 2. Test unitaire Rust + compilation du binaire release à jour
echo -e "\n${BLUE}--- Étape 1 : Tests unitaires Rust & Compilation Release ---${NC}"
cargo test --quiet
echo -e "${GREEN}✔ Tous les tests unitaires (DomeWarpLut, ProjectionMode, CRSF/MSP) sont validés.${NC}"
cargo build --release --quiet
echo -e "${GREEN}✔ Tous les tests unitaires et la compilation Release sont validés.${NC}"
# Fonction d'exécution d'un test OpenXR
run_mode_test() {
local mode="$1"
local desc="$2"
local extra_args="$3"
echo -e "\n${BLUE}--- Test Mode : ${desc} (--projection-mode ${mode} ${extra_args}) ---${NC}"
local log_tag="$3"
shift 3
echo -e "\n${BLUE}--- Test Mode : ${desc} (--projection-mode ${mode} $*) ---${NC}"
local log_file="/tmp/openxr_test_${mode}.log"
local log_file="/tmp/openxr_test_${log_tag}.log"
rm -f "$log_file"
# Exécution pendant 3.5 secondes
timeout 3.5 ./target/release/steamframe-fpv --no-gui --projection-mode "$mode" $extra_args > "$log_file" 2>&1 || true
timeout 3.5 ./target/release/steamframe-fpv --no-gui --projection-mode "$mode" "$@" > "$log_file" 2>&1 || true
# Vérification des étapes clés dans les logs
local has_device=false
@@ -62,7 +81,7 @@ run_mode_test() {
if grep -q "Casque connecté : Monado" "$log_file"; then
has_device=true
fi
if grep -q "Creation of VkDevice:.*result: VK_SUCCESS" "$log_file" || grep -q "result: VK_SUCCESS" "$log_file"; then
if grep -q "Creation of VkDevice:.*result: VK_SUCCESS" "$log_file" || grep -q "Session OpenXR Vulkan" "$log_file"; then
has_vulkan=true
fi
if grep -q "Changement d'état session : FOCUSED" "$log_file"; then
@@ -83,12 +102,12 @@ run_mode_test() {
}
# 3. Tests des 3 modes de projection
run_mode_test "dome" "Dôme 140° (Equirect2 avec dé-distorsion)" "--lens-k1 -0.14 --lens-k2 0.03"
run_mode_test "cylinder" "Cylindre Incurvé 140° (Cylinder layer)" ""
run_mode_test "flat" "Quad Plat Virtuel (Quad layer)" ""
run_mode_test "dome" "Dôme 140° (Equirect2 avec dé-distorsion)" "dome" --lens-k1 -0.14 --lens-k2 0.03
run_mode_test "cylinder" "Cylindre Incurvé 140° (Cylinder layer)" "cylinder"
run_mode_test "flat" "Quad Plat Virtuel (Quad layer)" "flat"
# 4. Test du Mode VR Natif (--vr-only, Mode Gaming SteamOS)
run_mode_test "dome" "Mode VR Natif Gaming (--vr-only)" "--vr-only"
run_mode_test "dome" "Mode VR Natif Gaming (--vr-only)" "vr_only" --vr-only
# 5. Test d'initialisation de l'interface graphique GPUI avec OpenXR
echo -e "\n${BLUE}--- Étape 2 : Test d'intégration IHM moderne (GPUI + OpenXR) ---${NC}"
@@ -98,8 +117,9 @@ timeout 3 ./target/release/steamframe-fpv > "$gpui_log" 2>&1 || true
if grep -q "Changement d'état session : FOCUSED" "$gpui_log"; then
echo -e "${GREEN}✔ L'interface GPUI se synchronise et alimente parfaitement la session OpenXR FOCUSED.${NC}"
else
echo -e "${YELLOW}Avertissement GPUI :${NC}"
tail -n 10 "$gpui_log"
echo -e "${RED}✘ Échec intégration GPUI + OpenXR :${NC}"
tail -n 15 "$gpui_log"
exit 1
fi
echo -e "\n${GREEN}======================================================${NC}"
+698 -1
View File
@@ -1,4 +1,8 @@
use clap::Parser;
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)]
@@ -188,7 +192,700 @@ pub struct AppConfig {
#[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,
/// 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_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_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_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.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);
}
}
-2227
View File
File diff suppressed because it is too large. Load diff
+328
View File
@@ -0,0 +1,328 @@
use super::types::*;
use anyhow::{anyhow, Result};
use std::fs::{self, File, OpenOptions};
use std::io::{ErrorKind, Read};
use std::os::unix::fs::OpenOptionsExt;
use std::os::unix::io::AsRawFd;
#[derive(Debug, Clone)]
pub(super) struct DetectedEvdevDevice {
pub(super) path: String,
pub(super) name: String,
pub(super) vendor: u16,
pub(super) product: u16,
pub(super) has_hat2_triggers: bool,
pub(super) priority: u8,
}
pub(super) fn sysfs_bitmap_has_bit(text: &str, bit: usize) -> bool {
let bits_per_word = usize::BITS as usize;
let word_idx = bit / bits_per_word;
let bit_in_word = bit % bits_per_word;
let words: Vec<&str> = text.split_whitespace().collect();
if word_idx >= words.len() {
return false;
}
let rev_idx = words.len() - 1 - word_idx;
usize::from_str_radix(words[rev_idx], 16)
.map(|w| ((w >> bit_in_word) & 1) != 0)
.unwrap_or(false)
}
pub(super) fn inspect_sysfs_event_node(event_name: &str) -> Option<DetectedEvdevDevice> {
let sys_dev = format!("/sys/class/input/{}/device", event_name);
let name = fs::read_to_string(format!("{}/name", sys_dev))
.ok()?
.trim()
.to_string();
let key_caps = fs::read_to_string(format!("{}/capabilities/key", sys_dev)).unwrap_or_default();
let abs_caps = fs::read_to_string(format!("{}/capabilities/abs", sys_dev)).unwrap_or_default();
let prop_caps = fs::read_to_string(format!("{}/properties", sys_dev)).unwrap_or_default();
// Exclure les périphériques purement IMU / accéléromètres ("Steam Controller Motion Sensors")
if sysfs_bitmap_has_bit(&prop_caps, INPUT_PROP_ACCELEROMETER)
|| name.to_ascii_lowercase().contains("motion sensor")
{
return None;
}
// Exiger un vrai gamepad (BTN_SOUTH + ABS_X)
let has_btn_south = sysfs_bitmap_has_bit(&key_caps, BTN_SOUTH as usize);
let has_abs_x = sysfs_bitmap_has_bit(&abs_caps, ABS_X as usize);
if !has_btn_south || !has_abs_x {
return None;
}
let vendor = fs::read_to_string(format!("{}/id/vendor", sys_dev))
.ok()
.and_then(|s| u16::from_str_radix(s.trim(), 16).ok())
.unwrap_or(0);
let product = fs::read_to_string(format!("{}/id/product", sys_dev))
.ok()
.and_then(|s| u16::from_str_radix(s.trim(), 16).ok())
.unwrap_or(0);
let has_hat2_triggers = sysfs_bitmap_has_bit(&abs_caps, ABS_HAT2X as usize)
&& sysfs_bitmap_has_bit(&abs_caps, ABS_HAT2Y as usize);
let lower = name.to_ascii_lowercase();
let priority = if vendor == VALVE_VENDOR_ID && lower.contains("steam controller") {
3
} else if vendor == VALVE_VENDOR_ID {
2
} else {
1
};
Some(DetectedEvdevDevice {
path: format!("/dev/input/{}", event_name),
name,
vendor,
product,
has_hat2_triggers,
priority,
})
}
pub(super) fn find_steam_controller_device(override_path: Option<&str>) -> Option<DetectedEvdevDevice> {
if let Some(path) = override_path {
let trimmed = path.trim();
if !trimmed.is_empty() {
if let Some(file_name) = std::path::Path::new(trimmed)
.file_name()
.and_then(|s| s.to_str())
{
if let Some(info) = inspect_sysfs_event_node(file_name) {
return Some(info);
}
}
// Fallback direct si le chemin est fourni explicitement
if std::path::Path::new(trimmed).exists() {
return Some(DetectedEvdevDevice {
path: trimmed.to_string(),
name: format!("Contrôleur ({})", trimmed),
vendor: 0,
product: 0,
has_hat2_triggers: true,
priority: 3,
});
}
return None;
}
}
let entries = fs::read_dir("/sys/class/input").ok()?;
let mut best: Option<DetectedEvdevDevice> = None;
for entry in entries.flatten() {
let fname = entry.file_name();
let Some(name_str) = fname.to_str() else {
continue;
};
if !name_str.starts_with("event") {
continue;
}
let Some(candidate) = inspect_sysfs_event_node(name_str) else {
continue;
};
// Vérifier que le nœud est réellement ouvrable en lecture
if OpenOptions::new()
.read(true)
.custom_flags(O_NONBLOCK_FLAG)
.open(&candidate.path)
.is_err()
{
continue;
}
let replace = match &best {
None => true,
Some(prev) => candidate.priority > prev.priority,
};
if replace {
best = Some(candidate);
}
}
best
}
pub(super) struct AxisRange {
min: i32,
max: i32,
pub(super) current: i32,
}
impl AxisRange {
pub(super) fn centered(min: i32, max: i32, val: i32) -> Self {
Self {
min,
max,
current: val,
}
}
pub(super) fn normalized_signed(&self) -> f32 {
let span = self.max as f64 - self.min as f64;
if span <= 0.0 {
return 0.0;
}
let mid = (self.max as f64 + self.min as f64) * 0.5;
(((self.current as f64 - mid) / (span * 0.5)) as f32).clamp(-1.0, 1.0)
}
pub(super) fn normalized_unsigned(&self) -> f32 {
let span = self.max as f64 - self.min as f64;
if span <= 0.0 {
return 0.0;
}
(((self.current as f64 - self.min as f64) / span) as f32).clamp(0.0, 1.0)
}
}
pub(super) struct OpenEvdevGamepad {
file: File,
pub(super) info: DetectedEvdevDevice,
throttle_code: u16,
brake_code: u16,
pub(super) steer_axis: AxisRange,
pub(super) throttle_axis: AxisRange,
pub(super) brake_axis: AxisRange,
pub(super) clutch_pressed: bool,
}
impl OpenEvdevGamepad {
pub(super) fn open(info: DetectedEvdevDevice) -> Result<Self> {
let file = OpenOptions::new()
.read(true)
.custom_flags(O_NONBLOCK_FLAG)
.open(&info.path)?;
let steer_info = Self::query_abs(&file, ABS_X).unwrap_or(LinuxInputAbsInfo {
value: 0,
minimum: -32767,
maximum: 32767,
..Default::default()
});
let (throttle_code, brake_code) = if info.has_hat2_triggers {
(ABS_HAT2X, ABS_HAT2Y)
} else {
(ABS_RZ, ABS_Z)
};
let throttle_info = Self::query_abs(&file, throttle_code).unwrap_or(LinuxInputAbsInfo {
value: 0,
minimum: 0,
maximum: 32767,
..Default::default()
});
let brake_info = Self::query_abs(&file, brake_code).unwrap_or(LinuxInputAbsInfo {
value: 0,
minimum: 0,
maximum: 32767,
..Default::default()
});
// Sécurité evdev : certaines manettes exposent les gâchettes en plage signée (-32767..32767)
// avec `absinfo.value == 0` avant le premier appui, ce qui donnerait 50% de gaz/frein au repos.
let initial_throttle_val = if throttle_info.minimum < 0 && throttle_info.value == 0 {
throttle_info.minimum
} else {
throttle_info.value
};
let initial_brake_val = if brake_info.minimum < 0 && brake_info.value == 0 {
brake_info.minimum
} else {
brake_info.value
};
Ok(Self {
file,
info,
throttle_code,
brake_code,
steer_axis: AxisRange::centered(
steer_info.minimum,
steer_info.maximum,
steer_info.value,
),
throttle_axis: AxisRange::centered(
throttle_info.minimum,
throttle_info.maximum,
initial_throttle_val,
),
brake_axis: AxisRange::centered(
brake_info.minimum,
brake_info.maximum,
initial_brake_val,
),
clutch_pressed: false,
})
}
pub(super) fn query_abs(file: &File, code: u16) -> Option<LinuxInputAbsInfo> {
let mut info = LinuxInputAbsInfo::default();
// SAFETY: `file` est un fd evdev valide ouvert, `eviocgabs(code)` encode `struct input_absinfo` (24 octets)
// et `info` est un `LinuxInputAbsInfo` #[repr(C)] de même taille passé par pointeur mutable valide.
let ret = unsafe {
ioctl(
file.as_raw_fd(),
eviocgabs(code),
&mut info as *mut LinuxInputAbsInfo,
)
};
if ret >= 0 && info.maximum > info.minimum {
Some(info)
} else {
None
}
}
/// Lit tous les événements en attente de manière non-bloquante.
/// Retourne `Err` si le périphérique a été débranché / éteint.
pub(super) fn poll_events(&mut self, out_pressed_keys: &mut Vec<u16>) -> Result<()> {
const EV_SIZE: usize = std::mem::size_of::<LinuxInputEvent>();
let mut buf = [0u8; EV_SIZE * 64];
loop {
match self.file.read(&mut buf) {
Ok(0) => return Err(anyhow!("EOF evdev (manette déconnectée)")),
Ok(n) => {
let count = n / EV_SIZE;
for i in 0..count {
// SAFETY: `i < n / EV_SIZE` garantit que `i * EV_SIZE + EV_SIZE <= n <= buf.len()`.
let ev = unsafe {
std::ptr::read_unaligned(
buf.as_ptr().add(i * EV_SIZE) as *const LinuxInputEvent
)
};
match ev.ev_type {
EV_ABS => {
if ev.code == ABS_X {
self.steer_axis.current = ev.value;
} else if ev.code == self.throttle_code {
self.throttle_axis.current = ev.value;
} else if ev.code == self.brake_code {
self.brake_axis.current = ev.value;
}
}
EV_KEY => {
if ev.code == BTN_GRIPL2 {
self.clutch_pressed = ev.value != 0;
} else if ev.value == 1 {
out_pressed_keys.push(ev.code);
}
}
_ => {}
}
}
}
Err(e) if e.kind() == ErrorKind::WouldBlock => break,
Err(e) => return Err(anyhow!("Erreur lecture evdev : {}", e)),
}
}
Ok(())
}
}
+144
View File
@@ -0,0 +1,144 @@
use super::types::{ControlSource, GearSpeedLimits};
use crate::nomad_elrs::{CRSF_CHANNEL_MAX, CRSF_CHANNEL_MID, CRSF_CHANNEL_MIN};
pub fn steering_to_crsf(raw_norm: f32, deadzone: f32, expo: f32, invert: bool) -> u16 {
if !raw_norm.is_finite() {
return CRSF_CHANNEL_MID;
}
let clamped = raw_norm.clamp(-1.0, 1.0);
let dz = if deadzone.is_finite() {
deadzone.clamp(0.0, 0.45)
} else {
0.0
};
let abs_v = clamped.abs();
let scaled = if abs_v <= dz {
0.0
} else {
let mag = ((abs_v - dz) / (1.0 - dz)).clamp(0.0, 1.0);
mag.copysign(clamped)
};
let e = if expo.is_finite() {
expo.clamp(0.0, 0.8)
} else {
0.0
};
let curved = scaled * (1.0 - e + e * (scaled * scaled));
let directed = if invert { -curved } else { curved };
let crsf = if directed >= 0.0 {
CRSF_CHANNEL_MID as f32 - directed * (CRSF_CHANNEL_MID - CRSF_CHANNEL_MIN) as f32
} else {
CRSF_CHANNEL_MID as f32 - directed * (CRSF_CHANNEL_MAX - CRSF_CHANNEL_MID) as f32
};
if !crsf.is_finite() {
return CRSF_CHANNEL_MID;
}
(crsf.round() as u16).clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX)
}
/// Normalise une gâchette [0.0..1.0] avec zone morte et calcule le canal gaz CRSF selon la boîte séquentielle.
pub fn throttle_to_crsf(
throttle_norm: f32,
deadzone: f32,
armed: bool,
gear: i8,
limits: GearSpeedLimits,
) -> (u8, u16) {
if !throttle_norm.is_finite() {
return (0, CRSF_CHANNEL_MID);
}
let dz = if deadzone.is_finite() {
deadzone.clamp(0.0, 0.45)
} else {
0.0
};
let clamped = throttle_norm.clamp(0.0, 1.0);
let active = if clamped <= dz {
0.0
} else {
((clamped - dz) / (1.0 - dz)).clamp(0.0, 1.0)
};
let pct = (active * 100.0).round() as u8;
if !armed || active <= 0.0 || gear == 0 {
return (pct, CRSF_CHANNEL_MID);
}
let s = limits.sanitized();
let crsf = if gear == -1 {
let span = s.reverse_min as f32 - s.reverse_max as f32;
(s.reverse_min as f32 - active * span).round() as u16
} else if (1..=3).contains(&gear) {
let max_v = s.forward_max[(gear - 1) as usize];
let span = max_v as f32 - s.forward_min as f32;
(s.forward_min as f32 + active * span).round() as u16
} else {
CRSF_CHANNEL_MID
};
(pct, crsf.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX))
}
/// Normalise la gâchette frein [0.0..1.0] et convertit en CRSF (992..1811).
pub fn brake_to_crsf(brake_norm: f32, deadzone: f32) -> (u8, u16) {
if !brake_norm.is_finite() {
return (0, CRSF_CHANNEL_MID);
}
let dz = if deadzone.is_finite() {
deadzone.clamp(0.0, 0.45)
} else {
0.0
};
let clamped = brake_norm.clamp(0.0, 1.0);
let active = if clamped <= dz {
0.0
} else {
((clamped - dz) / (1.0 - dz)).clamp(0.0, 1.0)
};
let pct = (active * 100.0).round() as u8;
let crsf = if active <= 0.0 {
CRSF_CHANNEL_MID
} else {
let span = (CRSF_CHANNEL_MAX - CRSF_CHANNEL_MID) as f32;
(CRSF_CHANNEL_MID as f32 + active * span).round() as u16
};
(pct, crsf.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX))
}
pub fn encode_src_command(source: ControlSource) -> String {
crate::nomad_elrs::NomadHeadTracker::append_nmea_crc8(&format!("$SRC,{}", source.wire_tag()))
}
pub fn encode_gears_command(limits: GearSpeedLimits) -> String {
let s = limits.sanitized();
crate::nomad_elrs::NomadHeadTracker::append_nmea_crc8(&format!(
"$GEARS,{},{},{},{},{},{}",
s.forward_min,
s.forward_max[0],
s.forward_max[1],
s.forward_max[2],
s.reverse_min,
s.reverse_max,
))
}
pub fn encode_rc_frame(
steer: u16,
accel: u16,
brake: u16,
clutch: u16,
armed: bool,
gear: i8,
) -> String {
crate::nomad_elrs::NomadHeadTracker::append_nmea_crc8(&format!(
"$RC,{},{},{},{},{},{}",
steer.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX),
accel.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX),
brake.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX),
clutch.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX),
if armed { 1 } else { 0 },
gear.clamp(-1, 3),
))
}
+272
View File
@@ -0,0 +1,272 @@
use super::types::IBEX_RUMBLE_REPORT_ID;
use std::time::Instant;
pub fn encode_ibex_rumble_report(left: u16, right: u16) -> [u8; 10] {
let [s_lo, s_hi] = left.to_le_bytes();
let [w_lo, w_hi] = right.to_le_bytes();
[
IBEX_RUMBLE_REPORT_ID,
0x00,
0x00,
0x00,
s_lo,
s_hi,
0x02,
w_lo,
w_hi,
0x00,
]
}
#[inline]
fn scale_rumble_u16(norm: f32) -> u16 {
(norm.clamp(0.0, 1.0) * u16::MAX as f32).round() as u16
}
/// Synthétiseur haptique temps réel cadencé à 25 Hz (40 ms).
#[derive(Debug, Clone)]
pub struct SteamHapticsSynthesizer {
pub(super) origin: Instant,
test_started_at: Option<Instant>,
arm_started_at: Option<Instant>,
disarm_started_at: Option<Instant>,
shift_started_at: Option<Instant>,
shift_dir: i8, // +1 montée (droite), -1 rétrogradage (gauche)
}
impl Default for SteamHapticsSynthesizer {
fn default() -> Self {
Self::new()
}
}
impl SteamHapticsSynthesizer {
pub fn new() -> Self {
Self {
origin: Instant::now(),
test_started_at: None,
arm_started_at: None,
disarm_started_at: None,
shift_started_at: None,
shift_dir: 0,
}
}
pub fn reset(&mut self) {
self.test_started_at = None;
self.arm_started_at = None;
self.disarm_started_at = None;
self.shift_started_at = None;
self.shift_dir = 0;
}
pub fn trigger_test_at(&mut self, now: Instant) {
self.test_started_at = Some(now);
}
pub fn trigger_test(&mut self) {
self.trigger_test_at(Instant::now());
}
pub fn on_arm_at(&mut self, now: Instant) {
self.disarm_started_at = None;
self.arm_started_at = Some(now);
}
pub fn on_arm(&mut self) {
self.on_arm_at(Instant::now());
}
pub fn on_disarm_at(&mut self, now: Instant) {
self.arm_started_at = None;
self.shift_started_at = None;
self.disarm_started_at = Some(now);
}
pub fn on_disarm(&mut self) {
self.on_disarm_at(Instant::now());
}
pub fn on_shift_at(&mut self, dir: i8, now: Instant) {
if dir != 0 {
self.shift_dir = dir.signum();
self.shift_started_at = Some(now);
}
}
pub fn on_shift(&mut self, dir: i8) {
self.on_shift_at(dir, Instant::now());
}
/// Calcule les consignes `(left_strong, right_weak)` dans `0..=65535` selon l'ordre de priorité :
/// 1. Test manuel UI (250 ms gauche puis 250 ms droite, fonctionne même désarmé)
/// 2. Animation Armement (double pulse 2×70 ms) / Désarmement (pulse grave 120 ms)
/// 3. Garde silence (inactif, déconnecté, désarmé, vibration 0% ou rapport <= 0)
/// 4. À-coup passage de rapport (70 ms : droite en montée, gauche en rétrogradage)
/// 5. Freinage violent ABS (`brake_pct > 70%`, pulsation ~12 Hz sur les deux moteurs)
/// 6. Double couche conduite (rapports 1..3) : gauche = moteur + chocs terrain, droite = roulement + terrain
#[allow(clippy::too_many_arguments)]
pub fn compute(
&mut self,
now: Instant,
active_is_steam: bool,
connected: bool,
armed: bool,
gear: i8,
throttle_pct: u8,
brake_pct: u8,
terrain_roughness: u8,
vibration_pct: u8,
) -> (u16, u16) {
if !connected {
self.reset();
return (0, 0);
}
// 1. Test manuel UI (fonctionne même désarmé / hors RP2350)
if let Some(started) = self.test_started_at {
let ms = now.saturating_duration_since(started).as_millis() as u64;
let test_gain = if vibration_pct == 0 {
0.40
} else {
(vibration_pct.min(100) as f32) / 100.0
};
if ms < 250 {
return (scale_rumble_u16(0.75 * test_gain), 0);
} else if ms < 500 {
return (0, scale_rumble_u16(0.75 * test_gain));
} else {
self.test_started_at = None;
}
}
let gain = (vibration_pct.min(100) as f32) / 100.0;
if !active_is_steam || vibration_pct == 0 {
self.arm_started_at = None;
self.disarm_started_at = None;
self.shift_started_at = None;
return (0, 0);
}
// 2. Animations tactiles Armement / Désarmement
if let Some(started) = self.arm_started_at {
let ms = now.saturating_duration_since(started).as_millis() as u64;
if ms < 70 || (130..200).contains(&ms) {
let amp = scale_rumble_u16(0.75 * gain);
return (amp, amp);
} else if ms < 130 {
return (0, 0);
} else {
self.arm_started_at = None;
}
}
if let Some(started) = self.disarm_started_at {
let ms = now.saturating_duration_since(started).as_millis() as u64;
if ms < 120 {
return (scale_rumble_u16(0.65 * gain), 0);
} else {
self.disarm_started_at = None;
}
}
// 3. Silence garanti hors conduite avant armée
if !armed || gear <= 0 {
self.shift_started_at = None;
return (0, 0);
}
// 4. À-coup passage de rapport (70 ms)
if let Some(started) = self.shift_started_at {
let ms = now.saturating_duration_since(started).as_millis() as u64;
if ms < 70 {
let kick = scale_rumble_u16(0.85 * gain);
return if self.shift_dir > 0 {
(0, kick)
} else {
(kick, 0)
};
} else {
self.shift_started_at = None;
}
}
// 5. Freinage violent ABS (> 70%) : pulsation ~12.5 Hz (40 ms crête / 40 ms creux)
if brake_pct > 70 {
let abs_norm = ((brake_pct.min(100) - 70) as f32 / 30.0).clamp(0.0, 1.0);
let crest = (now.saturating_duration_since(self.origin).as_millis() / 40).is_multiple_of(2);
if crest {
let left = scale_rumble_u16((0.35 + 0.55 * abs_norm) * gain);
let right = scale_rumble_u16((0.45 + 0.50 * abs_norm) * gain);
return (left, right);
} else {
let left = scale_rumble_u16(0.10 * abs_norm * gain);
let right = scale_rumble_u16(0.12 * abs_norm * gain);
return (left, right);
}
}
// 6. Double couche conduite (rapports 1, 2, 3)
let throttle_norm = (throttle_pct.min(100) as f32) / 100.0;
let rough_norm = (terrain_roughness as f32) / 255.0;
let gear_factor = match gear {
1 => 0.35,
2 => 0.65,
3 => 1.0,
_ => 0.0,
};
let engine_left = if throttle_pct > 0 {
0.14 + 0.46 * throttle_norm
} else {
0.0
};
let terrain_left = 0.55 * rough_norm;
let left_norm = (engine_left + terrain_left).clamp(0.0, 1.0);
let rolling_right = if throttle_pct > 0 {
(0.10 + 0.35 * throttle_norm) * gear_factor
} else {
0.0
};
let terrain_right = 0.65 * rough_norm;
let right_norm = (rolling_right + terrain_right).clamp(0.0, 1.0);
(
scale_rumble_u16(left_norm * gain),
scale_rumble_u16(right_norm * gain),
)
}
/// Superpose une alerte haptique distincte en cas de batterie critique (double-battement grave 1 Hz)
/// ou de liaison radio LQ < 50% (impulsion rapide droite).
#[allow(clippy::too_many_arguments)]
pub fn apply_telemetry_alert(
&self,
base: (u16, u16),
now: Instant,
active_is_steam: bool,
connected: bool,
armed: bool,
battery_crit: bool,
link_crit: bool,
vibration_pct: u8,
) -> (u16, u16) {
if !active_is_steam || !connected || !armed || vibration_pct == 0 {
return base;
}
let scale = vibration_pct.min(100) as f32 / 100.0;
let phase_ms = now.saturating_duration_since(self.origin).as_millis() as u64 % 1000;
let (mut left, mut right) = base;
if battery_crit && (phase_ms < 90 || (160..250).contains(&phase_ms)) {
let alert_l = (46000.0 * scale) as u16;
left = left.max(alert_l);
}
if link_crit && (phase_ms % 250 < 60) {
let alert_r = (42000.0 * scale) as u16;
right = right.max(alert_r);
}
(left, right)
}
}
+371
View File
@@ -0,0 +1,371 @@
use super::evdev_reader::{find_steam_controller_device, AxisRange, OpenEvdevGamepad};
use super::haptics::encode_ibex_rumble_report;
use super::types::*;
use anyhow::{anyhow, Result};
use std::fs::{self, File, OpenOptions};
use std::io::{ErrorKind, Read, Write};
use std::os::unix::fs::OpenOptionsExt;
use std::thread;
use std::time::{Duration, Instant};
// =========================================================================
// LECTEUR NATIF HIDRAW STEAM CONTROLLER 2 (IBEX / PUCK 28DE:1302..1305)
// Contourne automatiquement le Lizard Mode (mode souris/bureau) de hid-steam
// sans nécessiter d'appui long sur Menu ni que Steam soit lancé.
// =========================================================================
const IBEX_BUTTON_MAP: &[(usize, u8, u16)] = &[
// Byte 2
(2, 0x01, BTN_SOUTH), // A (Tare HT)
(2, 0x02, BTN_EAST), // B (DVR)
(2, 0x04, BTN_NORTH), // Y (OSD)
(2, 0x08, BTN_WEST), // X (Proj VR)
(2, 0x20, BTN_THUMBR), // R3 (Tare HT)
(2, 0x40, BTN_START), // Menu / Start (ARM)
(2, 0x80, BTN_GRIPR), // R4 Grip (Rapport +)
// Byte 3
(3, 0x02, BTN_TR), // RB (Rapport +)
(3, 0x04, BTN_DPAD_DOWN), // D-Pad Bas
(3, 0x08, BTN_DPAD_RIGHT), // D-Pad Droite
(3, 0x10, BTN_DPAD_LEFT), // D-Pad Gauche
(3, 0x20, BTN_DPAD_UP), // D-Pad Haut
(3, 0x40, BTN_SELECT), // View / Select (DVR)
// Byte 4
(4, 0x01, BTN_MODE), // Steam (Tare HT)
(4, 0x02, BTN_GRIPL), // L4 Grip (Rapport -)
(4, 0x08, BTN_TL), // LB (Rapport -)
];
pub(super) struct IbexParsedReport {
pub(super) steer_raw: i32, // -32767..=32767
pub(super) throttle_raw: i32, // 0..=32767
pub(super) brake_raw: i32, // 0..=32767
pub(super) clutch_pressed: bool,
pub(super) btn_bytes: [u8; 4], // report[2..6]
}
pub(super) fn parse_ibex_hidraw_report(data: &[u8]) -> Option<IbexParsedReport> {
if data.len() < IBEX_REPORT_LEN || data[0] != IBEX_REPORT_ID {
return None;
}
let brake_raw = i16::from_le_bytes([data[6], data[7]]).max(0) as i32;
let throttle_raw = i16::from_le_bytes([data[8], data[9]]).max(0) as i32;
let steer_raw = (i16::from_le_bytes([data[10], data[11]]) as i32).max(-32767);
let btn_bytes = [data[2], data[3], data[4], data[5]];
let clutch_pressed = (data[4] & 0x04) != 0; // BTN_GRIPL2 (L5)
Some(IbexParsedReport {
steer_raw,
throttle_raw,
brake_raw,
clutch_pressed,
btn_bytes,
})
}
pub(super) struct OpenIbexHidraw {
file: File,
writable: bool,
name: String,
path: String,
vendor: u16,
product: u16,
steer_axis: AxisRange,
throttle_axis: AxisRange,
brake_axis: AxisRange,
clutch_pressed: bool,
prev_btn_bytes: [u8; 4],
last_report_at: Instant,
}
impl OpenIbexHidraw {
pub(super) fn is_ibex_pid(pid: u16) -> bool {
matches!(pid, 0x1302..=0x1305)
}
pub(super) fn parse_hid_id(uevent: &str) -> Option<(u16, u16, String)> {
let mut vid = None;
let mut pid = None;
let mut name = String::new();
for line in uevent.lines() {
if let Some(rest) = line.strip_prefix("HID_ID=") {
let parts: Vec<&str> = rest.split(':').collect();
if parts.len() == 3 {
vid = u16::from_str_radix(parts[1].trim(), 16).ok();
pid = u16::from_str_radix(parts[2].trim(), 16).ok();
}
} else if let Some(rest) = line.strip_prefix("HID_NAME=") {
name = rest.trim().to_string();
}
}
Some((vid?, pid?, name))
}
pub(super) fn probe_single(path: &str, name: String, vendor: u16, product: u16) -> Option<Self> {
let (mut file, writable) = match OpenOptions::new()
.read(true)
.write(true)
.custom_flags(O_NONBLOCK_FLAG)
.open(path)
{
Ok(f) => (f, true),
Err(_) => {
let f = OpenOptions::new()
.read(true)
.custom_flags(O_NONBLOCK_FLAG)
.open(path)
.ok()?;
(f, false)
}
};
let mut buf = [0u8; 64];
// Sonde brève (jusqu'à 45 ms) : seule l'interface active du Puck diffuse les trames 0x42 (54 o)
for attempt in 0..5 {
match file.read(&mut buf) {
Ok(n) => {
if let Some(parsed) = parse_ibex_hidraw_report(&buf[..n]) {
return Some(Self {
file,
writable,
name: if name.is_empty() {
"Steam Controller (HIDRAW)".to_string()
} else {
name
},
path: path.to_string(),
vendor,
product,
steer_axis: AxisRange::centered(-32767, 32767, parsed.steer_raw),
throttle_axis: AxisRange::centered(0, 32767, parsed.throttle_raw),
brake_axis: AxisRange::centered(0, 32767, parsed.brake_raw),
clutch_pressed: parsed.clutch_pressed,
prev_btn_bytes: parsed.btn_bytes,
last_report_at: Instant::now(),
});
}
}
Err(e) if e.kind() == ErrorKind::WouldBlock => {
if attempt < 4 {
thread::sleep(Duration::from_millis(10));
}
}
Err(_) => return None,
}
}
None
}
pub(super) fn set_rumble(&mut self, left: u16, right: u16) {
if !self.writable {
return;
}
let report = encode_ibex_rumble_report(left, right);
let _ = self.file.write(&report);
}
pub(super) fn find_and_open(override_path: Option<&str>) -> Option<Self> {
if let Some(path) = override_path {
let trimmed = path.trim();
if trimmed.contains("hidraw") {
return Self::probe_single(
trimmed,
format!("Steam Controller ({})", trimmed),
VALVE_VENDOR_ID,
0x1304,
);
}
if !trimmed.is_empty() {
return None;
}
}
let entries = fs::read_dir("/sys/class/hidraw").ok()?;
let mut candidates: Vec<(u32, String, String, u16, u16)> = Vec::new();
for entry in entries.flatten() {
let fname = entry.file_name();
let Some(name_str) = fname.to_str() else {
continue;
};
let Some(num_str) = name_str.strip_prefix("hidraw") else {
continue;
};
let idx = num_str.parse::<u32>().unwrap_or(u32::MAX);
let uevent_path = format!("/sys/class/hidraw/{}/device/uevent", name_str);
let Ok(uevent) = fs::read_to_string(&uevent_path) else {
continue;
};
let Some((vid, pid, hid_name)) = Self::parse_hid_id(&uevent) else {
continue;
};
if vid == VALVE_VENDOR_ID && Self::is_ibex_pid(pid) {
candidates.push((idx, format!("/dev/{}", name_str), hid_name, vid, pid));
}
}
// Trier par numéro (hidraw9 / input2 en premier)
candidates.sort_by_key(|c| c.0);
for (_, dev_path, hid_name, vid, pid) in candidates {
if let Some(opened) = Self::probe_single(&dev_path, hid_name, vid, pid) {
return Some(opened);
}
}
None
}
pub(super) fn poll_events(&mut self, out_pressed_keys: &mut Vec<u16>) -> Result<()> {
let mut buf = [0u8; 64];
loop {
match self.file.read(&mut buf) {
Ok(0) => return Err(anyhow!("EOF hidraw (manette déconnectée)")),
Ok(n) => {
if let Some(parsed) = parse_ibex_hidraw_report(&buf[..n]) {
self.last_report_at = Instant::now();
self.steer_axis.current = parsed.steer_raw;
self.throttle_axis.current = parsed.throttle_raw;
self.brake_axis.current = parsed.brake_raw;
self.clutch_pressed = parsed.clutch_pressed;
for &(byte_idx, mask, btn_code) in IBEX_BUTTON_MAP {
let arr_idx = byte_idx - 2;
let now_down = (parsed.btn_bytes[arr_idx] & mask) != 0;
let prev_down = (self.prev_btn_bytes[arr_idx] & mask) != 0;
if now_down && !prev_down {
out_pressed_keys.push(btn_code);
}
}
self.prev_btn_bytes = parsed.btn_bytes;
}
}
Err(e) if e.kind() == ErrorKind::WouldBlock => break,
Err(e) => return Err(anyhow!("Erreur lecture hidraw : {}", e)),
}
}
if self.last_report_at.elapsed() > Duration::from_millis(IBEX_HIDRAW_TIMEOUT_MS) {
return Err(anyhow!(
"Timeout HIDRAW ({} ms sans trame 0x42 — manette en veille ou éteinte)",
IBEX_HIDRAW_TIMEOUT_MS
));
}
Ok(())
}
}
pub(super) enum OpenGamepad {
IbexHidraw(OpenIbexHidraw),
Evdev(OpenEvdevGamepad),
}
impl OpenGamepad {
pub(super) fn open_best(override_path: Option<&str>) -> Option<Self> {
if let Some(ibex) = OpenIbexHidraw::find_and_open(override_path) {
return Some(Self::IbexHidraw(ibex));
}
if let Some(dev_info) = find_steam_controller_device(override_path) {
match OpenEvdevGamepad::open(dev_info) {
Ok(ev) => return Some(Self::Evdev(ev)),
Err(e) => {
log::warn!("[Steam Controller] Impossible d'ouvrir evdev : {}", e);
}
}
}
None
}
pub(super) fn name(&self) -> &str {
match self {
Self::IbexHidraw(h) => &h.name,
Self::Evdev(e) => &e.info.name,
}
}
pub(super) fn path(&self) -> &str {
match self {
Self::IbexHidraw(h) => &h.path,
Self::Evdev(e) => &e.info.path,
}
}
pub(super) fn summary_log(&self) -> String {
match self {
Self::IbexHidraw(h) => format!(
"'{}' sur {} (VID={:04X}, PID={:04X}, mode=HIDRAW Ibex 0x42 natif, haptique={})",
h.name,
h.path,
h.vendor,
h.product,
if h.writable { "ON (0x80)" } else { "RO" }
),
Self::Evdev(e) => format!(
"'{}' sur {} (VID={:04X}, PID={:04X}, mode=evdev {})",
e.info.name,
e.info.path,
e.info.vendor,
e.info.product,
if e.info.has_hat2_triggers {
"hid-steam HAT2X/Y"
} else {
"standard RZ/Z"
}
),
}
}
pub(super) fn set_rumble(&mut self, left: u16, right: u16) {
if let Self::IbexHidraw(h) = self {
h.set_rumble(left, right);
}
}
pub(super) fn poll_events(&mut self, out_pressed_keys: &mut Vec<u16>) -> Result<()> {
match self {
Self::IbexHidraw(h) => h.poll_events(out_pressed_keys),
Self::Evdev(e) => e.poll_events(out_pressed_keys),
}
}
pub(super) fn steer_norm(&self) -> f32 {
match self {
Self::IbexHidraw(h) => h.steer_axis.normalized_signed(),
Self::Evdev(e) => e.steer_axis.normalized_signed(),
}
}
pub(super) fn throttle_norm(&self) -> f32 {
match self {
Self::IbexHidraw(h) => h.throttle_axis.normalized_unsigned(),
Self::Evdev(e) => e.throttle_axis.normalized_unsigned(),
}
}
pub(super) fn brake_norm(&self) -> f32 {
match self {
Self::IbexHidraw(h) => h.brake_axis.normalized_unsigned(),
Self::Evdev(e) => e.brake_axis.normalized_unsigned(),
}
}
pub(super) fn clutch_pressed(&self) -> bool {
match self {
Self::IbexHidraw(h) => h.clutch_pressed,
Self::Evdev(e) => e.clutch_pressed,
}
}
pub(super) fn is_input_stale(&self) -> bool {
match self {
Self::IbexHidraw(h) => {
h.last_report_at.elapsed() > Duration::from_millis(IBEX_STALE_RC_STOP_MS)
}
Self::Evdev(_) => false,
}
}
}
// =========================================================================
// WORKER TEMPS RÉEL STEAM CONTROLLER -> UDP :14552 -> RADXA -> RP2350
// =========================================================================
File diff suppressed because it is too large. Load diff
+352
View File
@@ -0,0 +1,352 @@
use crate::g29_bridge::G29State;
use crate::nomad_elrs::{CRSF_CHANNEL_MAX, CRSF_CHANNEL_MID, CRSF_CHANNEL_MIN};
use std::time::{Duration, Instant};
// =========================================================================
// CONSTANTES EVDEV LINUX (identiques sur x86_64 et aarch64)
// =========================================================================
pub(super) const EV_KEY: u16 = 0x01;
pub(super) const EV_ABS: u16 = 0x03;
pub(super) const ABS_X: u16 = 0x00;
pub(super) const ABS_Z: u16 = 0x02;
pub(super) const ABS_RZ: u16 = 0x05;
pub(super) const ABS_HAT2X: u16 = 0x14; // 20 : Gâchette droite (R2) sur hid-steam (Steam Controller / Deck)
pub(super) const ABS_HAT2Y: u16 = 0x15; // 21 : Gâchette gauche (L2) sur hid-steam (Steam Controller / Deck)
pub(super) const BTN_SOUTH: u16 = 304; // A
pub(super) const BTN_EAST: u16 = 305; // B
pub(super) const BTN_NORTH: u16 = 307; // Y
pub(super) const BTN_WEST: u16 = 308; // X
pub(super) const BTN_TL: u16 = 310; // LB (Rétrograder)
pub(super) const BTN_TR: u16 = 311; // RB (Monter un rapport)
pub(super) const BTN_SELECT: u16 = 314; // View / Back
pub(super) const BTN_START: u16 = 315; // Menu / Start (Armement / Désarmement)
pub(super) const BTN_MODE: u16 = 316; // Bouton Steam
pub(super) const BTN_THUMBR: u16 = 318; // R3
pub(super) const BTN_DPAD_UP: u16 = 544;
pub(super) const BTN_DPAD_DOWN: u16 = 545;
pub(super) const BTN_DPAD_LEFT: u16 = 546;
pub(super) const BTN_DPAD_RIGHT: u16 = 547;
pub(super) const BTN_GRIPL: u16 = 548; // Palette arrière gauche L4 (Rétrograder)
pub(super) const BTN_GRIPR: u16 = 549; // Palette arrière droite R4 (Monter un rapport)
pub(super) const BTN_GRIPL2: u16 = 550; // Palette arrière basse gauche L5 (Embrayage)
pub(super) const INPUT_PROP_ACCELEROMETER: usize = 6;
pub(super) const VALVE_VENDOR_ID: u16 = 0x28de;
pub(super) const O_NONBLOCK_FLAG: i32 = 0x800; // O_NONBLOCK sur Linux x86_64 et aarch64
// Plages de gaz progressives identiques au firmware RP2350 (g29_crsf.ino)
pub(super) const GAZ_AVANT_MIN: u16 = 1065;
pub(super) const GAZ_AVANT_MAX_PAR_VITESSE: [u16; 3] = [
1100, // 1ère vitesse (Manœuvre)
1150, // 2ème vitesse (Normale)
1220, // 3ème vitesse (Rapide)
];
pub(super) const GAZ_ARRIERE_MIN: u16 = 905;
pub(super) const GAZ_ARRIERE_MAX: u16 = 800;
/// Bornes CRSF configurables de la boîte séquentielle (marche avant 1/2/3 et marche arrière R).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct GearSpeedLimits {
pub forward_min: u16,
pub forward_max: [u16; 3],
pub reverse_min: u16,
pub reverse_max: u16,
}
impl Default for GearSpeedLimits {
fn default() -> Self {
Self {
forward_min: GAZ_AVANT_MIN,
forward_max: GAZ_AVANT_MAX_PAR_VITESSE,
reverse_min: GAZ_ARRIERE_MIN,
reverse_max: GAZ_ARRIERE_MAX,
}
}
}
impl GearSpeedLimits {
/// Contraint chaque valeur dans les bornes CRSF valides et cohérentes.
pub fn sanitized(self) -> Self {
let forward_min = self.forward_min.clamp(CRSF_CHANNEL_MID, CRSF_CHANNEL_MAX);
let forward_max = [
self.forward_max[0].clamp(forward_min, CRSF_CHANNEL_MAX),
self.forward_max[1].clamp(forward_min, CRSF_CHANNEL_MAX),
self.forward_max[2].clamp(forward_min, CRSF_CHANNEL_MAX),
];
let reverse_min = self.reverse_min.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MID);
let reverse_max = self.reverse_max.clamp(CRSF_CHANNEL_MIN, reverse_min);
Self {
forward_min,
forward_max,
reverse_min,
reverse_max,
}
}
}
pub(super) const TOAST_DURATION_MS: u64 = 1500;
pub(super) const RC_SEND_INTERVAL_MS: u64 = 10; // 100 Hz vers RP2350
pub(super) const HAPTICS_INTERVAL_MS: u64 = 40; // 25 Hz (identique au G29)
pub(super) const SRC_RESYNC_INTERVAL_MS: u64 = 500;
pub(super) const GEARS_RESYNC_INTERVAL_MS: u64 = 2000;
pub(super) const DEVICE_RESCAN_INTERVAL_MS: u64 = 1000;
pub(super) const IBEX_HIDRAW_TIMEOUT_MS: u64 = 300;
pub(super) const IBEX_STALE_RC_STOP_MS: u64 = 120;
pub(super) const CONSECUTIVE_SEND_ERR_DISARM: u32 = 10;
pub(super) const IBEX_REPORT_ID: u8 = 0x42;
pub(super) const IBEX_REPORT_LEN: usize = 54;
pub(super) const IBEX_RUMBLE_REPORT_ID: u8 = 0x80;
extern "C" {
pub(super) fn ioctl(fd: std::ffi::c_int, request: std::ffi::c_ulong, ...) -> std::ffi::c_int;
}
#[repr(C)]
#[derive(Clone, Copy, Default)]
pub(super) struct LinuxInputEvent {
pub(super) tv_sec: std::ffi::c_long,
pub(super) tv_usec: std::ffi::c_long,
pub(super) ev_type: u16,
pub(super) code: u16,
pub(super) value: i32,
}
#[repr(C)]
#[derive(Clone, Copy, Default, Debug)]
pub(super) struct LinuxInputAbsInfo {
pub(super) value: i32,
pub(super) minimum: i32,
pub(super) maximum: i32,
pub(super) fuzz: i32,
pub(super) flat: i32,
pub(super) resolution: i32,
}
pub(super) fn eviocgabs(abs_code: u16) -> std::ffi::c_ulong {
// _IOR('E', 0x40 + abs_code, struct input_absinfo) = 0x8018_4540 + abs_code
(0x8018_4540u64 + abs_code as u64) as std::ffi::c_ulong
}
// =========================================================================
// TYPES PUBLICS : SOURCE DE CONTRÔLE & ÉTAT STEAM CONTROLLER
// =========================================================================
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[repr(u8)]
pub enum ControlSource {
#[default]
G29 = 0,
SteamController = 1,
}
impl ControlSource {
pub fn from_str(s: &str) -> Self {
let lower = s.trim().to_ascii_lowercase();
if lower == "steam"
|| lower == "steam_controller"
|| lower == "steam-controller"
|| lower == "controller"
|| lower == "gamepad"
|| lower == "ext"
{
Self::SteamController
} else {
Self::G29
}
}
pub fn from_u8(v: u8) -> Self {
match v {
1 => Self::SteamController,
_ => Self::G29,
}
}
pub fn as_u8(self) -> u8 {
self as u8
}
pub fn as_str(self) -> &'static str {
match self {
Self::G29 => "g29",
Self::SteamController => "steam",
}
}
pub fn wire_tag(self) -> &'static str {
match self {
Self::G29 => "G29",
Self::SteamController => "EXT",
}
}
pub fn label(self) -> &'static str {
match self {
Self::G29 => "Volant G29",
Self::SteamController => "Steam Controller",
}
}
}
#[derive(Debug, Clone)]
pub struct SteamControllerConfig {
pub device_override: Option<String>,
pub steering_deadzone: f32,
pub steering_expo: f32,
pub trigger_deadzone: f32,
#[allow(dead_code)]
pub invert_steering: bool,
}
impl Default for SteamControllerConfig {
fn default() -> Self {
Self {
device_override: None,
steering_deadzone: 0.08,
steering_expo: 0.25,
trigger_deadzone: 0.05,
invert_steering: false,
}
}
}
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub struct SteamControllerState {
pub connected: bool,
pub device_name: String,
pub device_path: String,
pub armed: bool,
pub gear: i8,
pub steering_norm: f32,
pub throttle_pct: u8,
pub brake_pct: u8,
pub clutch_pct: u8,
pub steer_crsf: u16,
pub throttle_crsf: u16,
pub brake_crsf: u16,
pub clutch_crsf: u16,
pub vibration_pct: u8,
pub rumble_left_pct: u8,
pub rumble_right_pct: u8,
pub packets_sent: u64,
pub send_errors: u64,
pub last_button: String,
pub last_button_at: Option<Instant>,
pub toast_text: String,
pub toast_until: Option<Instant>,
}
impl Default for SteamControllerState {
fn default() -> Self {
Self {
connected: false,
device_name: String::new(),
device_path: String::new(),
armed: false,
gear: 0,
steering_norm: 0.0,
throttle_pct: 0,
brake_pct: 0,
clutch_pct: 0,
steer_crsf: CRSF_CHANNEL_MID,
throttle_crsf: CRSF_CHANNEL_MID,
brake_crsf: CRSF_CHANNEL_MID,
clutch_crsf: CRSF_CHANNEL_MID,
vibration_pct: 100,
rumble_left_pct: 0,
rumble_right_pct: 0,
packets_sent: 0,
send_errors: 0,
last_button: String::new(),
last_button_at: None,
toast_text: String::new(),
toast_until: None,
}
}
}
impl SteamControllerState {
pub fn gear_label(&self) -> &'static str {
match self.gear {
-1 => "R",
0 => "N",
1 => "1",
2 => "2",
3 => "3",
_ => "?",
}
}
pub fn set_toast(&mut self, msg: impl Into<String>) {
self.toast_text = msg.into();
self.toast_until = Some(Instant::now() + Duration::from_millis(TOAST_DURATION_MS));
}
#[allow(dead_code)]
pub fn active_toast(&self) -> Option<&str> {
match self.toast_until {
Some(until) if Instant::now() < until && !self.toast_text.is_empty() => {
Some(&self.toast_text)
}
_ => None,
}
}
/// Construit un état compatible OSD pour afficher le HUD Steam Controller sans allocation supplémentaire.
pub fn to_hud_g29_state(&self, hub_failsafe: bool) -> G29State {
G29State {
connected: self.connected,
failsafe: !self.connected || hub_failsafe,
armed: self.armed,
gear: self.gear,
steering_pct: (self.steering_norm * 100.0).round().clamp(-100.0, 100.0) as i8,
throttle_pct: self.throttle_pct,
brake_pct: self.brake_pct,
clutch_pct: self.clutch_pct,
steer_crsf: self.steer_crsf,
throttle_crsf: self.throttle_crsf,
brake_crsf: self.brake_crsf,
clutch_crsf: self.clutch_crsf,
ffb_raw: 0,
ffb_pct: 0,
vib_pct: self.rumble_left_pct.max(self.rumble_right_pct),
remote_source: ControlSource::SteamController,
packets_received: self.packets_sent.max(u64::from(self.connected)),
last_packet: if self.connected {
Some(Instant::now())
} else {
None
},
last_button: self.last_button.clone(),
last_button_at: self.last_button_at,
toast_text: self.toast_text.clone(),
toast_until: self.toast_until,
}
}
}
pub fn key_code_label(key: u16) -> String {
match key {
BTN_START => "Menu / Start (ARM)".to_string(),
BTN_SELECT => "View / Select (DVR)".to_string(),
BTN_MODE => "Steam (Tare HT)".to_string(),
BTN_SOUTH => "A (Tare HT)".to_string(),
BTN_EAST => "B (DVR)".to_string(),
BTN_NORTH => "Y (OSD)".to_string(),
BTN_WEST => "X (Proj VR)".to_string(),
BTN_TR => "RB (Rapport +)".to_string(),
BTN_TL => "LB (Rapport -)".to_string(),
BTN_GRIPR => "R4 Grip (Rapport +)".to_string(),
BTN_GRIPL => "L4 Grip (Rapport -)".to_string(),
BTN_GRIPL2 => "L5 Grip (Embrayage)".to_string(),
BTN_THUMBR => "R3 (Tare HT)".to_string(),
BTN_DPAD_UP => "D-Pad Haut (Tilt +1)".to_string(),
BTN_DPAD_DOWN => "D-Pad Bas (Tilt -1)".to_string(),
BTN_DPAD_LEFT => "D-Pad Gauche (Pan -1)".to_string(),
BTN_DPAD_RIGHT => "D-Pad Droite (Pan +1)".to_string(),
other => format!("KEY_{}", other),
}
}
+31 -11
View File
@@ -41,30 +41,50 @@ pub struct DomeWarpLut {
impl DomeWarpLut {
pub fn new(width: u32, height: u32, fov_deg: f32, k1: f32, k2: f32) -> Self {
let enabled = k1.abs() > 1e-4 || k2.abs() > 1e-4;
let total_pixels = (width * height) as usize;
let enabled = width > 0 && height > 0 && (k1.abs() > 1e-4 || k2.abs() > 1e-4);
if !enabled {
return Self {
width,
height,
fov_deg,
k1,
k2,
src_pixel_offsets: Vec::new(),
enabled: false,
};
}
let total_pixels = (width as usize).saturating_mul(height as usize);
let mut src_pixel_offsets = Vec::with_capacity(total_pixels);
let aspect = width as f32 / height as f32;
let half_fov_rad = (fov_deg.to_radians() * 0.5).max(0.1);
let max_tan = (half_fov_rad * 0.65).tan().max(0.1);
// Normalisation douce liée au FOV : à 140° le facteur de référence vaut 1.0
// (évite le recadrage/étirement des bords lorsque fov_deg < 140°).
let fov_scale = (fov_deg.clamp(60.0, 180.0) / 140.0).clamp(0.75, 1.15);
for y in 0..height {
let ny = ((y as f32 + 0.5) / height as f32) * 2.0 - 1.0;
for x in 0..width {
let nx = ((x as f32 + 0.5) / width as f32) * 2.0 - 1.0;
let rx = nx * aspect;
let ry = ny;
let r2 = rx * rx + ry * ry;
// Rayon normalisé dans [0..1] aux bords pour éviter tout repliement polynomial
// même avec k1 = -0.50 dans les coins 16:9.
let rx = nx * (aspect / aspect.max(1.0));
let ry = ny / aspect.max(1.0);
let r2 = (rx * rx + ry * ry).min(1.5);
let r4 = r2 * r2;
let factor = (1.0 + k1 * r2 + k2 * r4) / max_tan.min(1.15);
let poly = (1.0 + k1 * r2 + k2 * r4).clamp(0.25, 2.5);
let factor = poly / fov_scale;
let src_nx = (nx * factor + 1.0) * 0.5;
let src_ny = (ny * factor + 1.0) * 0.5;
let sx = (src_nx * (width as f32 - 1.0)).round().clamp(0.0, (width - 1) as f32) as u32;
let sy = (src_ny * (height as f32 - 1.0)).round().clamp(0.0, (height - 1) as f32) as u32;
let sx = (src_nx * (width as f32 - 1.0))
.round()
.clamp(0.0, (width - 1) as f32) as u32;
let sy = (src_ny * (height as f32 - 1.0))
.round()
.clamp(0.0, (height - 1) as f32) as u32;
let pixel_offset = sy * width + sx;
src_pixel_offsets.push(pixel_offset);
@@ -78,7 +98,7 @@ impl DomeWarpLut {
k1,
k2,
src_pixel_offsets,
enabled,
enabled: true,
}
}
+512 -37
View File
@@ -1,16 +1,23 @@
use anyhow::{Context, Result};
use anyhow::{anyhow, Context, Result};
use chrono::Local;
use gstreamer as gst;
use gstreamer::prelude::*;
use gstreamer_app as gst_app;
use std::fs;
use parking_lot::Mutex;
use std::collections::VecDeque;
use std::fs::{self, File};
use std::io::{BufWriter, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;
use std::time::Instant;
use std::time::{Duration, Instant};
/// Plafond mémoire de la file `appsrc` DVR (32 Mo) pour empêcher tout OOM si le stockage ralentit.
const DVR_MAX_QUEUE_BYTES: u64 = 32 * 1024 * 1024;
/// Fenêtre du pré-buffer Instant Replay (30 s) et plafond RAM (48 Mo).
pub const REPLAY_WINDOW_SECS: u64 = 30;
const REPLAY_MAX_BYTES: usize = 48 * 1024 * 1024;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DvrContainer {
Mkv,
@@ -36,7 +43,8 @@ impl DvrContainer {
pub fn muxer_element(&self) -> &'static str {
match self {
Self::Mkv => "matroskamux",
Self::Mp4 => "mp4mux fragment-duration=2000 faststart=true",
// fMP4 (fragment-duration=2000) est déjà résistant aux coupures sans réécriture `faststart` à l'EOS
Self::Mp4 => "mp4mux fragment-duration=2000",
}
}
}
@@ -68,7 +76,344 @@ impl DvrMode {
}
}
/// Enregistreur vidéo DVR asynchrone basé sur GStreamer
/// Formate un décalage en millisecondes au format SubRip (`HH:MM:SS,mmm`).
pub fn format_srt_timestamp(ms: u64) -> String {
let hours = ms / 3_600_000;
let mins = (ms % 3_600_000) / 60_000;
let secs = (ms % 60_000) / 1_000;
let millis = ms % 1_000;
format!("{hours:02}:{mins:02}:{secs:02},{millis:03}")
}
/// Écrivain de sous-titres télémétrie `.srt` synchronisés avec le fichier DVR (0 % coût encodage vidéo).
struct SrtWriterState {
writer: Option<BufWriter<File>>,
path: PathBuf,
seq: u32,
last_emit_ms: Option<u64>,
pending_text: Option<(u64, String)>,
}
impl SrtWriterState {
fn open_for_video(video_path: &Path) -> Self {
let srt_path = video_path.with_extension("srt");
let writer = File::create(&srt_path).ok().map(BufWriter::new);
Self {
writer,
path: srt_path,
seq: 0,
last_emit_ms: None,
pending_text: None,
}
}
fn push_caption(&mut self, elapsed_ms: u64, text: &str) {
if let Some(last) = self.last_emit_ms {
if elapsed_ms.saturating_sub(last) < 950 {
return;
}
}
self.last_emit_ms = Some(elapsed_ms);
// Fermer le bloc précédent jusqu'à `elapsed_ms`
if let Some((prev_start, prev_text)) = self.pending_text.take() {
let end_ms = elapsed_ms.max(prev_start + 500);
self.write_block(prev_start, end_ms, &prev_text);
}
self.pending_text = Some((elapsed_ms, text.to_string()));
}
fn write_block(&mut self, start_ms: u64, end_ms: u64, text: &str) {
let Some(ref mut w) = self.writer else {
return;
};
self.seq = self.seq.saturating_add(1);
let _ = writeln!(
w,
"{}\n{} --> {}\n{}\n",
self.seq,
format_srt_timestamp(start_ms),
format_srt_timestamp(end_ms),
text.trim()
);
}
fn finish(&mut self, end_ms: u64) {
if let Some((prev_start, prev_text)) = self.pending_text.take() {
let final_end = end_ms.max(prev_start + 1000);
self.write_block(prev_start, final_end, &prev_text);
}
if let Some(ref mut w) = self.writer {
let _ = w.flush();
}
self.writer = None;
// Supprimer le .srt si aucune télémétrie n'a été écrite
if self.seq == 0 {
let _ = fs::remove_file(&self.path);
}
}
}
/// Détecte si un paquet bitstream H.264 ou H.265 contient une image clé (IDR / SPS / IRAP / VPS).
pub fn detect_keyframe(bytes: &[u8], codec: &str, gst_is_delta: bool) -> bool {
if !gst_is_delta {
return true;
}
let is_h265 = codec.eq_ignore_ascii_case("h265") || codec.eq_ignore_ascii_case("hevc");
let mut i = 0usize;
while i + 4 < bytes.len() {
let sc_len = if bytes[i] == 0 && bytes[i + 1] == 0 && bytes[i + 2] == 1 {
3
} else if bytes[i] == 0 && bytes[i + 1] == 0 && bytes[i + 2] == 0 && bytes[i + 3] == 1 {
4
} else {
i += 1;
continue;
};
let nal_idx = i + sc_len;
if nal_idx < bytes.len() {
let hdr = bytes[nal_idx];
if is_h265 {
let nal_type = (hdr >> 1) & 0x3F;
if matches!(nal_type, 19..=21 | 32 | 33) {
return true;
}
} else {
let nal_type = hdr & 0x1F;
if matches!(nal_type, 5 | 7) {
return true;
}
}
}
i = nal_idx + 1;
}
false
}
#[derive(Clone)]
struct ReplayPacket {
data: Vec<u8>,
received_at: Instant,
is_keyframe: bool,
}
#[derive(Clone)]
struct ReplayCaption {
text: String,
received_at: Instant,
}
/// Pré-buffer circulaire en RAM (Blackbox 30 s) pour Instant Replay zéro-CPU en flux H.264/H.265.
pub struct ReplayRingBuffer {
packets: Mutex<VecDeque<ReplayPacket>>,
captions: Mutex<VecDeque<ReplayCaption>>,
total_bytes: AtomicU64,
window: Duration,
max_bytes: usize,
}
impl Default for ReplayRingBuffer {
fn default() -> Self {
Self::new(Duration::from_secs(REPLAY_WINDOW_SECS), REPLAY_MAX_BYTES)
}
}
impl ReplayRingBuffer {
pub fn new(window: Duration, max_bytes: usize) -> Self {
Self {
packets: Mutex::new(VecDeque::with_capacity(1800)),
captions: Mutex::new(VecDeque::with_capacity(64)),
total_bytes: AtomicU64::new(0),
window,
max_bytes,
}
}
/// Empile un paquet compressé H.264/H.265 dans le pré-buffer circulaire.
pub fn push_encoded_packet(&self, data: &[u8], codec: &str, gst_is_delta: bool) {
if data.is_empty() || data.len() > self.max_bytes / 2 {
return;
}
let now = Instant::now();
let is_keyframe = detect_keyframe(data, codec, gst_is_delta);
let pkt_len = data.len();
let mut q = self.packets.lock();
q.push_back(ReplayPacket {
data: data.to_vec(),
received_at: now,
is_keyframe,
});
let mut cur_bytes = self.total_bytes.load(Ordering::Relaxed) as usize + pkt_len;
while let Some(front) = q.front() {
let expired = now.saturating_duration_since(front.received_at) > self.window;
let over_cap = cur_bytes > self.max_bytes;
if (expired || over_cap) && q.len() > 1 {
let removed = q.pop_front().unwrap();
cur_bytes = cur_bytes.saturating_sub(removed.data.len());
} else {
break;
}
}
self.total_bytes.store(cur_bytes as u64, Ordering::Relaxed);
}
/// Empile un sous-titre télémétrie horodaté (1 Hz) pour accompagner l'Instant Replay.
pub fn push_caption(&self, text: String) {
let now = Instant::now();
let mut q = self.captions.lock();
if let Some(back) = q.back() {
if now.saturating_duration_since(back.received_at) < Duration::from_millis(950) {
return;
}
}
q.push_back(ReplayCaption {
text,
received_at: now,
});
while let Some(front) = q.front() {
if now.saturating_duration_since(front.received_at) > self.window + Duration::from_secs(2)
{
q.pop_front();
} else {
break;
}
}
}
pub fn buffered_bytes(&self) -> u64 {
self.total_bytes.load(Ordering::Relaxed)
}
pub fn clear(&self) {
self.packets.lock().clear();
self.captions.lock().clear();
self.total_bytes.store(0, Ordering::Relaxed);
}
/// Exporte les 30 dernières secondes (à partir de la plus ancienne image-clé) vers `replay_YYYYMMDD_HHMMSS.<ext>` + `.srt`.
pub fn save_instant_replay(
&self,
dir: &str,
container: DvrContainer,
codec: &str,
) -> Result<(PathBuf, usize, f32)> {
let snapshot: Vec<ReplayPacket> = {
let q = self.packets.lock();
if q.is_empty() {
return Err(anyhow!(
"Pré-buffer Replay vide (aucun flux H.264/H.265 reçu récemment)"
));
}
let start_idx = q.iter().position(|p| p.is_keyframe).unwrap_or(0);
q.iter().skip(start_idx).cloned().collect()
};
if snapshot.is_empty() {
return Err(anyhow!("Aucune trame exploitable dans le pré-buffer Replay"));
}
let t0 = snapshot.first().unwrap().received_at;
let t_end = snapshot.last().unwrap().received_at;
let duration_s = t_end.saturating_duration_since(t0).as_secs_f32();
let captions: Vec<ReplayCaption> = {
let c = self.captions.lock();
let min_t = t0.checked_sub(Duration::from_secs(1)).unwrap_or(t0);
c.iter().filter(|cap| cap.received_at >= min_t).cloned().collect()
};
gst::init().context("Échec d'initialisation GStreamer pour Instant Replay")?;
fs::create_dir_all(dir)
.with_context(|| format!("Impossible de créer le répertoire DVR '{}'", dir))?;
let file_path = DvrRecorder::generate_prefixed_filepath(dir, "replay", container);
let codec_lower = codec.to_lowercase();
let is_h264 = codec_lower == "h264";
let parser = if is_h264 { "h264parse" } else { "h265parse" };
let caps = if is_h264 {
"video/x-h264,stream-format=byte-stream"
} else {
"video/x-h265,stream-format=byte-stream"
};
let muxer = container.muxer_element();
let pipeline_str = format!(
"appsrc name=rep_src format=time caps={caps} ! \
{parser} config-interval=-1 ! \
{muxer} ! \
filesink name=rep_sink sync=false"
);
let element = gst::parse::launch(&pipeline_str)
.map_err(|e| anyhow!("Erreur pipeline Replay : {}", e))?;
let pipeline = element
.dynamic_cast::<gst::Pipeline>()
.map_err(|_| anyhow!("L'élément Replay n'est pas un Pipeline"))?;
let appsrc = pipeline
.by_name("rep_src")
.context("rep_src introuvable")?
.dynamic_cast::<gst_app::AppSrc>()
.map_err(|_| anyhow!("Conversion rep_src -> AppSrc échouée"))?;
let filesink = pipeline.by_name("rep_sink").context("rep_sink introuvable")?;
filesink.set_property(
"location",
file_path
.to_str()
.ok_or_else(|| anyhow!("Chemin Replay invalide"))?,
);
pipeline
.set_state(gst::State::Playing)
.map_err(|e| anyhow!("Démarrage pipeline Replay échoué : {}", e))?;
let pkt_count = snapshot.len();
for pkt in snapshot {
let pts_ns = pkt.received_at.saturating_duration_since(t0).as_nanos() as u64;
let mut buf = gst::Buffer::from_slice(pkt.data);
if let Some(bref) = buf.get_mut() {
bref.set_pts(gst::ClockTime::from_nseconds(pts_ns));
}
if let Err(err) = appsrc.push_buffer(buf) {
log::warn!("[Replay] Arrêt anticipé push_buffer : {:?}", err);
break;
}
}
let _ = appsrc.end_of_stream();
if let Some(bus) = pipeline.bus() {
let deadline = Instant::now() + Duration::from_millis(3000);
while Instant::now() < deadline {
if let Some(msg) = bus.timed_pop(gst::ClockTime::from_mseconds(50)) {
use gst::MessageView;
match msg.view() {
MessageView::Eos(..) | MessageView::Error(..) => break,
_ => {}
}
}
}
}
let _ = pipeline.set_state(gst::State::Null);
// Écrire le fichier sous-titres .srt synchronisé avec l'Instant Replay
if !captions.is_empty() {
let mut srt = SrtWriterState::open_for_video(&file_path);
for cap in &captions {
let rel_ms = cap.received_at.saturating_duration_since(t0).as_millis() as u64;
srt.push_caption(rel_ms, &cap.text);
}
srt.finish((duration_s * 1000.0) as u64);
}
log::info!(
"[Replay] Instant Replay sauvegardé : {:?} ({} paquets, {:.1} s)",
file_path,
pkt_count,
duration_s
);
Ok((file_path, pkt_count, duration_s))
}
}
/// Enregistreur vidéo DVR asynchrone basé sur GStreamer avec sous-titres télémétrie `.srt` synchronisés.
pub struct DvrRecorder {
pipeline: gst::Pipeline,
appsrc: gst_app::AppSrc,
@@ -78,6 +423,7 @@ pub struct DvrRecorder {
bytes_written: Arc<AtomicU64>,
frames_recorded: Arc<AtomicU64>,
is_recording: Arc<AtomicBool>,
srt_writer: Mutex<SrtWriterState>,
}
impl DvrRecorder {
@@ -112,7 +458,7 @@ impl DvrRecorder {
);
log::info!(
"[DVR] Démarrage enregistrement StreamCopy ({}) -> {:?}",
"[DVR] Démarrage enregistrement StreamCopy ({}) -> {:?} (+ .srt télémétrie)",
codec.to_uppercase(),
file_path
);
@@ -120,7 +466,7 @@ impl DvrRecorder {
Self::launch(pipeline_str, file_path, DvrMode::StreamCopy)
}
/// Démarre un enregistrement en mode incrustation OSD (re-encodage rapide x264enc)
/// Démarre un enregistrement en mode incrustation OSD (sonde encodeur H.264 matériel puis repli x264enc)
pub fn start_composited_osd(
dir: &str,
container: DvrContainer,
@@ -135,18 +481,43 @@ impl DvrRecorder {
let file_path = Self::generate_filepath(dir, container);
let muxer = container.muxer_element();
let pipeline_str = format!(
"appsrc name=dvr_src is-live=true format=time do-timestamp=true max-bytes={DVR_MAX_QUEUE_BYTES} \
caps=video/x-raw,format=RGBA,width={width},height={height},framerate=60/1 ! \
videoconvert ! \
x264enc tune=zerolatency speed-preset=ultrafast bitrate=8000 key-int-max=60 ! \
h264parse config-interval=-1 ! \
{muxer} ! \
filesink name=dvr_sink sync=false"
let make_pipeline = |encoder: &str| {
format!(
"appsrc name=dvr_src is-live=true format=time do-timestamp=true max-bytes={DVR_MAX_QUEUE_BYTES} \
caps=video/x-raw,format=RGBA,width={width},height={height},framerate=0/1 ! \
videoconvert ! \
{encoder} ! \
h264parse config-interval=-1 ! \
{muxer} ! \
filesink name=dvr_sink sync=false"
)
};
// En production, tenter un encodeur matériel (v4l2h264enc / vah264enc) avant x264enc CPU
#[cfg(not(test))]
for &(factory, desc) in &[
("v4l2h264enc", "v4l2h264enc"),
("vah264enc", "vah264enc bitrate=8000"),
] {
if gst::ElementFactory::find(factory).is_some() {
if let Ok(rec) =
Self::launch(make_pipeline(desc), file_path.clone(), DvrMode::CompositedOsd)
{
log::info!(
"[DVR] Démarrage enregistrement OSD HW ({factory}, {width}x{height} VFR) -> {:?}",
file_path
);
return Ok(rec);
}
}
}
let pipeline_str = make_pipeline(
"x264enc tune=zerolatency speed-preset=ultrafast bitrate=8000 key-int-max=60",
);
log::info!(
"[DVR] Démarrage enregistrement OSD ({width}x{height} @ 60 FPS) -> {:?}",
"[DVR] Démarrage enregistrement OSD ({width}x{height} VFR) -> {:?}",
file_path
);
@@ -155,31 +526,37 @@ impl DvrRecorder {
fn launch(pipeline_str: String, file_path: PathBuf, mode: DvrMode) -> Result<Arc<Self>> {
let element = gst::parse::launch(&pipeline_str).map_err(|e| {
log::error!("[DVR] Erreur pipeline GStreamer : {} (Cmd: {})", e, pipeline_str);
anyhow::anyhow!("Erreur pipeline DVR : {}", e)
log::error!(
"[DVR] Erreur pipeline GStreamer : {} (Cmd: {})",
e,
pipeline_str
);
anyhow!("Erreur pipeline DVR : {}", e)
})?;
let pipeline = element
.dynamic_cast::<gst::Pipeline>()
.map_err(|_| anyhow::anyhow!("L'élément DVR n'est pas un Pipeline"))?;
.map_err(|_| anyhow!("L'élément DVR n'est pas un Pipeline"))?;
let appsrc = pipeline
.by_name("dvr_src")
.context("Appsrc 'dvr_src' introuvable dans le pipeline DVR")?
.dynamic_cast::<gst_app::AppSrc>()
.map_err(|_| anyhow::anyhow!("Impossible de convertir dvr_src en AppSrc"))?;
.map_err(|_| anyhow!("Impossible de convertir dvr_src en AppSrc"))?;
let filesink = pipeline
.by_name("dvr_sink")
.context("Filesink 'dvr_sink' introuvable dans le pipeline DVR")?;
let path_str = file_path
.to_str()
.ok_or_else(|| anyhow::anyhow!("Chemin DVR invalide"))?;
.ok_or_else(|| anyhow!("Chemin DVR invalide"))?;
filesink.set_property("location", path_str);
pipeline
.set_state(gst::State::Playing)
.map_err(|e| anyhow::anyhow!("Impossible de démarrer le pipeline DVR : {}", e))?;
.map_err(|e| anyhow!("Impossible de démarrer le pipeline DVR : {}", e))?;
let srt_writer = Mutex::new(SrtWriterState::open_for_video(&file_path));
Ok(Arc::new(Self {
pipeline,
@@ -190,21 +567,26 @@ impl DvrRecorder {
bytes_written: Arc::new(AtomicU64::new(0)),
frames_recorded: Arc::new(AtomicU64::new(0)),
is_recording: Arc::new(AtomicBool::new(true)),
srt_writer,
}))
}
/// Génère un nom de fichier horodaté `fpv_YYYYMMDD_HHMMSS.<ext>` sans écrasement
pub fn generate_filepath(dir: &str, container: DvrContainer) -> PathBuf {
Self::generate_prefixed_filepath(dir, "fpv", container)
}
pub fn generate_prefixed_filepath(dir: &str, prefix: &str, container: DvrContainer) -> PathBuf {
let now = Local::now();
let stamp = now.format("%Y%m%d_%H%M%S");
let ext = container.extension();
let base_dir = Path::new(dir);
let candidate = base_dir.join(format!("fpv_{}.{}", stamp, ext));
let candidate = base_dir.join(format!("{}_{}.{}", prefix, stamp, ext));
if !candidate.exists() {
return candidate;
}
for n in 1..1000 {
let numbered = base_dir.join(format!("fpv_{}_{}.{}", stamp, n, ext));
let numbered = base_dir.join(format!("{}_{}_{}.{}", prefix, stamp, n, ext));
if !numbered.exists() {
return numbered;
}
@@ -237,31 +619,83 @@ impl DvrRecorder {
self.is_recording.load(Ordering::Relaxed)
}
/// Enregistre une entrée télémétrie dans le fichier sous-titres `.srt` compagnon (throttlé ~1 Hz).
pub fn push_telemetry_caption(&self, caption: &str) {
if !self.is_recording.load(Ordering::Acquire) || caption.trim().is_empty() {
return;
}
let elapsed_ms = self.start_time.elapsed().as_millis() as u64;
self.srt_writer.lock().push_caption(elapsed_ms, caption);
}
/// Sonde le bus GStreamer (non-bloquant) et rafraîchit la taille réelle du fichier sur disque.
fn poll_health_and_size(&self) {
if let Some(bus) = self.pipeline.bus() {
while let Some(msg) = bus.pop() {
use gst::MessageView;
match msg.view() {
MessageView::Error(err) => {
log::error!(
"[DVR] Erreur pipeline en cours d'enregistrement ({:?}) : {} — arrêt DVR.",
self.file_path,
err.error()
);
self.is_recording.store(false, Ordering::Release);
break;
}
MessageView::Eos(..) => {
log::warn!("[DVR] EOS inattendu reçu pendant l'enregistrement.");
self.is_recording.store(false, Ordering::Release);
break;
}
_ => {}
}
}
}
if let Ok(meta) = fs::metadata(&self.file_path) {
self.bytes_written.store(meta.len(), Ordering::Relaxed);
}
}
/// Pousse un buffer GStreamer existant (zéro-copie de pointeur GstBuffer, avec garde-fou anti-OOM)
pub fn push_buffer(&self, buffer: gst::Buffer) {
if !self.is_recording.load(Ordering::Relaxed) {
if !self.is_recording.load(Ordering::Acquire) {
return;
}
if self.appsrc.current_level_bytes() >= DVR_MAX_QUEUE_BYTES {
// File saturée (stockage lent) : abandonner la trame plutôt que saturer la RAM en vol.
return;
}
self.bytes_written
.fetch_add(buffer.size() as u64, Ordering::Relaxed);
self.frames_recorded.fetch_add(1, Ordering::Relaxed);
let _ = self.appsrc.push_buffer(buffer);
let buf_len = buffer.size() as u64;
if let Err(flow_err) = self.appsrc.push_buffer(buffer) {
log::error!(
"[DVR] Échec push_buffer ({:?}) : arrêt de l'enregistrement.",
flow_err
);
self.is_recording.store(false, Ordering::Release);
return;
}
let frame_num = self.frames_recorded.fetch_add(1, Ordering::Relaxed) + 1;
if self.mode == DvrMode::StreamCopy {
self.bytes_written.fetch_add(buf_len, Ordering::Relaxed);
}
if frame_num.is_multiple_of(30) {
self.poll_health_and_size();
}
}
/// Pousse un bloc d'octets mémoire (ex: trame RGBA compositée)
pub fn push_slice(&self, slice: &[u8]) {
if !self.is_recording.load(Ordering::Relaxed) {
if !self.is_recording.load(Ordering::Acquire) {
return;
}
if self.appsrc.current_level_bytes() >= DVR_MAX_QUEUE_BYTES {
return;
}
let buffer = gst::Buffer::from_slice(slice.to_vec());
self.push_buffer(buffer);
}
/// Arrête proprement l'enregistrement en envoyant un signal EOS pour finaliser les en-têtes
/// Arrête proprement l'enregistrement en envoyant un signal EOS pour finaliser les en-têtes + `.srt`.
pub fn stop(&self) {
if !self.is_recording.swap(false, Ordering::SeqCst) {
return;
@@ -272,10 +706,13 @@ impl DvrRecorder {
self.file_path
);
let end_ms = self.start_time.elapsed().as_millis() as u64;
self.srt_writer.lock().finish(end_ms);
let _ = self.appsrc.end_of_stream();
if let Some(bus) = self.pipeline.bus() {
let deadline = Instant::now() + std::time::Duration::from_millis(1500);
let deadline = Instant::now() + Duration::from_millis(2500);
while Instant::now() < deadline {
if let Some(msg) = bus.timed_pop(gst::ClockTime::from_mseconds(100)) {
use gst::MessageView;
@@ -298,6 +735,9 @@ impl DvrRecorder {
}
let _ = self.pipeline.set_state(gst::State::Null);
if let Ok(meta) = fs::metadata(&self.file_path) {
self.bytes_written.store(meta.len(), Ordering::Relaxed);
}
log::info!(
"[DVR] Fichier sauvegardé : {:?} ({} trames, {:.2} Mo)",
self.file_path,
@@ -336,20 +776,55 @@ mod tests {
}
#[test]
fn test_dvr_recording_mkv_and_stop() {
fn test_srt_timestamp_and_keyframe_detection() {
assert_eq!(format_srt_timestamp(0), "00:00:00,000");
assert_eq!(format_srt_timestamp(3_723_456), "01:02:03,456");
// H.264 IDR (NAL type 5 = 0x65) et SPS (NAL type 7 = 0x67)
assert!(detect_keyframe(&[0, 0, 0, 1, 0x65, 0x88], "h264", true));
assert!(detect_keyframe(&[0, 0, 1, 0x67, 0x42], "h264", true));
// H.264 P-frame (NAL type 1 = 0x41)
assert!(!detect_keyframe(&[0, 0, 0, 1, 0x41, 0x9A], "h264", true));
// H.265 IDR_W_RADL (NAL type 19 -> (19 << 1) = 0x26)
assert!(detect_keyframe(&[0, 0, 0, 1, 0x26, 0x01], "h265", true));
// Non-delta GStreamer flag -> toujours keyframe
assert!(detect_keyframe(&[0, 0, 0, 1, 0x41], "h264", false));
}
#[test]
fn test_replay_ring_buffer_cap_and_eviction() {
let rb = ReplayRingBuffer::new(Duration::from_secs(30), 2048);
let idr = vec![0u8, 0, 0, 1, 0x65, 1, 2, 3];
let pframe = vec![0u8; 600];
rb.push_encoded_packet(&idr, "h264", true);
for _ in 0..5 {
rb.push_encoded_packet(&pframe, "h264", true);
}
assert!(rb.buffered_bytes() <= 2048);
assert!(rb.buffered_bytes() >= 600);
}
#[test]
fn test_dvr_recording_mkv_srt_and_stop() {
let dir = format!("/tmp/test_dvr_run_{}", std::process::id());
let dvr = DvrRecorder::start_composited_osd(&dir, DvrContainer::Mkv, 320, 240)
.expect("start dvr failed");
dvr.push_telemetry_caption("BAT 15.2V (3.80V/c) | LQ 99% | G2 | 24 km/h");
let fake_rgba = vec![0u8; 320 * 240 * 4];
for _ in 0..10 {
dvr.push_slice(&fake_rgba);
std::thread::sleep(std::time::Duration::from_millis(10));
std::thread::sleep(Duration::from_millis(10));
}
let path = dvr.file_path().to_path_buf();
let srt_path = path.with_extension("srt");
dvr.stop();
assert!(path.exists());
let meta = std::fs::metadata(&path).expect("file metadata");
assert!(srt_path.exists());
let srt_content = fs::read_to_string(&srt_path).expect("read srt");
assert!(srt_content.contains("BAT 15.2V"));
assert!(srt_content.contains("-->"));
let meta = fs::metadata(&path).expect("file metadata");
assert!(meta.len() > 0);
let _ = std::fs::remove_dir_all(&dir);
let _ = fs::remove_dir_all(&dir);
}
}
-2487
View File
File diff suppressed because it is too large. Load diff
+696
View File
@@ -0,0 +1,696 @@
use super::radxa_ssh::spawn_apply_radxa_channel;
use super::types::{DvrConfig, EngineSharedState, LiveOpticalParams};
use crate::config::{AppConfig, VehicleProfile};
use crate::controller::{ControlSource, GearSpeedLimits};
use crate::dome_projection::ProjectionMode;
use crate::dvr::{DvrContainer, DvrMode};
use crate::telemetry_osd::{VrMenuPage, VrMenuRenderData};
use std::sync::atomic::Ordering;
use std::sync::Arc;
use std::thread::JoinHandle;
use std::time::{Duration, Instant};
/// Poignée légère (`Arc::clone` unique) permettant à l'UI, au G29, au Steam Controller et à OpenXR
/// de piloter le moteur temps réel sans jamais bloquer sur `start()` / `stop()`.
#[derive(Clone)]
pub struct EngineControlHandle {
pub(super) shared: Arc<EngineSharedState>,
}
impl EngineControlHandle {
fn persist_live_config(&self) {
let maybe_snapshot = {
let mut guard = self.shared.persisted_cfg.lock();
if let Some(ref mut cfg) = *guard {
let opt = self.shared.optical_params.lock().clone();
let limits = *self.shared.gear_speed_limits.lock();
let wifi_ch = self.shared.vr_menu_state.lock().wifi_channel;
let (bat_cells, bat_warn, bat_crit) = *self.shared.battery_params.lock();
cfg.telemetry_enabled = self.shared.telemetry_enabled_flag.load(Ordering::Acquire);
cfg.head_tracking_enabled =
self.shared.head_tracking_enabled_flag.load(Ordering::Acquire);
cfg.control_source = match self.active_control_source() {
ControlSource::G29 => "g29".to_string(),
ControlSource::SteamController => "steam".to_string(),
};
cfg.controller_vibration = self
.shared
.controller_vibration_pct
.load(Ordering::Acquire)
.min(100);
cfg.controller_invert_steering = self
.shared
.controller_invert_steering
.load(Ordering::Acquire);
cfg.gaz_avant_min = limits.forward_min;
cfg.gear_1_max = limits.forward_max[0];
cfg.gear_2_max = limits.forward_max[1];
cfg.gear_3_max = limits.forward_max[2];
cfg.gaz_arriere_min = limits.reverse_min;
cfg.gear_reverse_max = limits.reverse_max;
cfg.projection_mode = match opt.projection_mode {
ProjectionMode::Dome140 => "dome".to_string(),
ProjectionMode::Cylinder140 => "cylinder".to_string(),
ProjectionMode::FlatQuad => "flat".to_string(),
};
cfg.camera_fov_deg = opt.camera_fov_deg;
cfg.lens_k1 = opt.lens_k1;
cfg.lens_k2 = opt.lens_k2;
cfg.screen_distance_m = opt.screen_distance_m;
cfg.screen_width_m = opt.screen_width_m;
cfg.video_brightness = opt.brightness;
cfg.video_contrast = opt.contrast;
cfg.video_gamma = opt.gamma;
cfg.video_sharpness = opt.sharpness;
cfg.horizon_stabilization = opt.horizon_stabilization;
cfg.stereo_sbs = opt.stereo_sbs;
cfg.wifi_channel = wifi_ch;
cfg.battery_cells = bat_cells;
cfg.battery_warn_cell_v = bat_warn;
cfg.battery_crit_cell_v = bat_crit;
Some(cfg.clone())
} else {
None
}
};
self.shared.config_revision.fetch_add(1, Ordering::Release);
if let Some(cfg) = maybe_snapshot {
cfg.patch_saved_fields();
}
}
pub fn config_revision(&self) -> u64 {
self.shared.config_revision.load(Ordering::Acquire)
}
pub fn snapshot_live_config(&self) -> Option<AppConfig> {
self.shared.persisted_cfg.lock().clone()
}
pub fn save_full_config(&self, cfg: &AppConfig) {
*self.shared.persisted_cfg.lock() = Some(cfg.clone());
*self.shared.battery_params.lock() = (
cfg.battery_cells,
cfg.battery_warn_cell_v,
cfg.battery_crit_cell_v,
);
self.shared.config_revision.fetch_add(1, Ordering::Release);
cfg.patch_saved_fields();
}
/// Applique un profil véhicule à chaud (refusé si le véhicule est armé).
pub fn apply_vehicle_profile(&self, profile: &VehicleProfile) -> Result<(), String> {
if self.is_vehicle_armed_now() {
return Err("Changement de profil refusé : désarmez d'abord le véhicule !".to_string());
}
let target_src = ControlSource::from_str(&profile.control_source);
self.set_control_source(target_src)?;
self.set_invert_steering(profile.controller_invert_steering);
self.set_gear_speed_limits(GearSpeedLimits {
forward_min: profile.gaz_avant_min,
forward_max: [profile.gear_1_max, profile.gear_2_max, profile.gear_3_max],
reverse_min: profile.gaz_arriere_min,
reverse_max: profile.gear_reverse_max,
});
{
let mut opt = self.shared.optical_params.lock();
opt.projection_mode = ProjectionMode::from_str(&profile.projection_mode);
opt.camera_fov_deg = profile.camera_fov_deg;
opt.lens_k1 = profile.lens_k1;
opt.screen_distance_m = profile.screen_distance_m;
}
{
let mut bat = self.shared.battery_params.lock();
bat.0 = profile.battery_cells;
}
{
let mut guard = self.shared.persisted_cfg.lock();
if let Some(ref mut cfg) = *guard {
profile.apply_to(cfg);
}
}
self.persist_live_config();
log::info!("[Profil Véhicule] Profil '{}' appliqué.", profile.name);
Ok(())
}
pub fn battery_alert_params(&self) -> (u8, f32) {
let (cells, _, crit) = *self.shared.battery_params.lock();
(cells, crit)
}
pub fn set_battery_cells(&self, cells: u8) {
self.shared.battery_params.lock().0 = cells.min(6);
self.persist_live_config();
}
pub fn track_dvr_finalizer(&self, handle: JoinHandle<()>) {
let mut guard = self.shared.dvr_finalize_handles.lock();
guard.retain(|h| !h.is_finished());
guard.push(handle);
}
pub fn join_dvr_finalizers(&self) {
let handles: Vec<JoinHandle<()>> = {
let mut guard = self.shared.dvr_finalize_handles.lock();
std::mem::take(&mut *guard)
};
for h in handles {
let _ = h.join();
}
}
pub fn invert_steering(&self) -> bool {
self.shared
.controller_invert_steering
.load(Ordering::Acquire)
}
pub fn set_invert_steering(&self, invert: bool) {
let prev = self
.shared
.controller_invert_steering
.swap(invert, Ordering::AcqRel);
if prev != invert {
log::info!(
"[Action Utilisateur] Inversion direction Steam Controller : {}",
if invert { "Inversée" } else { "Normale" }
);
self.persist_live_config();
}
}
pub fn request_recenter(&self) {
*self.shared.head_trim_deg.lock() = (0.0, 0.0);
self.shared.recenter_flag.store(true, Ordering::Release);
}
pub fn set_telemetry_enabled(&self, enabled: bool) {
let prev = self
.shared
.telemetry_enabled_flag
.swap(enabled, Ordering::AcqRel);
if prev != enabled {
log::info!(
"[Action Utilisateur] Télémétrie & OSD basculés sur : {}",
if enabled { "ON (Activé)" } else { "OFF (Désactivé)" }
);
self.persist_live_config();
}
}
pub fn toggle_telemetry(&self) -> bool {
let prev = self
.shared
.telemetry_enabled_flag
.fetch_xor(true, Ordering::AcqRel);
let now_on = !prev;
log::info!(
"[Action Volant] Télémétrie & OSD basculés sur : {}",
if now_on { "ON" } else { "OFF" }
);
self.persist_live_config();
now_on
}
pub fn set_head_tracking_enabled(&self, enabled: bool) {
let prev = self
.shared
.head_tracking_enabled_flag
.swap(enabled, Ordering::AcqRel);
if prev != enabled {
if enabled {
self.shared.recenter_flag.store(true, Ordering::Release);
}
log::info!(
"[Action Utilisateur] Suivi de Tête (RadioMaster Nomad) basculé sur : {}",
if enabled { "ON (Activé)" } else { "OFF (Désactivé)" }
);
self.persist_live_config();
}
}
pub fn update_optical_params(&self, opt: LiveOpticalParams) {
*self.shared.optical_params.lock() = opt;
self.persist_live_config();
}
pub fn cycle_projection_mode(&self) -> &'static str {
let mut opt = self.shared.optical_params.lock();
opt.projection_mode = match opt.projection_mode {
ProjectionMode::Dome140 => ProjectionMode::Cylinder140,
ProjectionMode::Cylinder140 => ProjectionMode::FlatQuad,
ProjectionMode::FlatQuad => ProjectionMode::Dome140,
};
let lbl = opt.projection_mode.label();
drop(opt);
log::info!("[Action Volant] Mode de projection VR : {}", lbl);
self.persist_live_config();
lbl
}
pub fn adjust_head_trim(&self, delta_pan_deg: f32, delta_tilt_deg: f32) {
let mut trim = self.shared.head_trim_deg.lock();
trim.0 = (trim.0 + delta_pan_deg).clamp(-30.0, 30.0);
trim.1 = (trim.1 + delta_tilt_deg).clamp(-30.0, 30.0);
}
pub fn update_dvr_config(&self, dir: String, container: DvrContainer, mode: DvrMode) {
*self.shared.dvr_config.lock() = DvrConfig {
dir,
container,
mode,
};
}
pub fn start_dvr(&self) {
*self.shared.dvr_toggle_cmd.lock() = Some(true);
}
pub fn stop_dvr(&self) {
*self.shared.dvr_toggle_cmd.lock() = Some(false);
}
pub fn toggle_dvr(&self) -> bool {
let is_rec = self.shared.dvr_recording_flag.load(Ordering::Acquire);
let next = !is_rec;
*self.shared.dvr_toggle_cmd.lock() = Some(next);
next
}
pub fn active_control_source(&self) -> ControlSource {
ControlSource::from_u8(self.shared.control_source_flag.load(Ordering::Acquire))
}
pub fn set_control_source(&self, target: ControlSource) -> Result<(), String> {
let current = self.active_control_source();
if current == target {
return Ok(());
}
let mut mon = self.shared.monitor.lock();
let armed_now = match current {
ControlSource::G29 => mon.latest_g29.is_live() && mon.latest_g29.armed,
ControlSource::SteamController => mon.latest_controller.armed,
};
if armed_now {
let msg = format!(
"Bascule vers {} refusée : désarmez d'abord le véhicule !",
target.label()
);
log::warn!("[Contrôleur] {}", msg);
return Err(msg);
}
self.shared
.control_source_flag
.store(target.as_u8(), Ordering::Release);
mon.active_control_source = target;
drop(mon);
log::info!(
"[Action Utilisateur] Source de conduite basculée sur : {}",
target.label()
);
self.persist_live_config();
Ok(())
}
#[allow(dead_code)]
pub fn controller_vibration_pct(&self) -> u8 {
self.shared
.controller_vibration_pct
.load(Ordering::Acquire)
.min(100)
}
pub fn set_controller_vibration_pct(&self, pct: u8) {
let clamped = pct.min(100);
let prev = self
.shared
.controller_vibration_pct
.swap(clamped, Ordering::AcqRel);
if prev != clamped {
self.shared.monitor.lock().latest_controller.vibration_pct = clamped;
log::info!(
"[Action Utilisateur] Vibrations Steam Controller réglées sur : {}%",
clamped
);
self.persist_live_config();
}
}
pub fn trigger_controller_rumble_test(&self) {
self.shared
.controller_rumble_test
.store(true, Ordering::Release);
log::info!("[Action Utilisateur] Test haptique Steam Controller déclenché.");
}
pub fn set_gear_speed_limits(&self, limits: GearSpeedLimits) {
let sanitized = limits.sanitized();
let changed = {
let mut guard = self.shared.gear_speed_limits.lock();
if *guard != sanitized {
*guard = sanitized;
true
} else {
false
}
};
if changed {
log::info!(
"[Action Utilisateur] Vitesses CRSF réglées : AV_MIN={} | 1ère={} | 2ème={} | 3ème={} | AR_MIN={} | AR_MAX={}",
sanitized.forward_min,
sanitized.forward_max[0],
sanitized.forward_max[1],
sanitized.forward_max[2],
sanitized.reverse_min,
sanitized.reverse_max
);
self.persist_live_config();
}
}
pub fn set_preview_active(&self, active: bool) {
self.shared
.preview_active_flag
.store(active, Ordering::Relaxed);
}
pub fn is_preview_active(&self) -> bool {
self.shared.preview_active_flag.load(Ordering::Relaxed)
}
pub fn is_exit_requested(&self) -> bool {
self.shared.exit_requested_flag.load(Ordering::Acquire)
}
pub fn request_exit(&self) {
self.shared
.exit_requested_flag
.store(true, Ordering::Release);
log::info!("[Menu VR] Demande de fermeture propre de l'application.");
}
pub fn is_vr_menu_open(&self) -> bool {
self.shared.vr_menu_state.lock().open
}
pub fn toggle_vr_menu(&self) -> bool {
let open = self.shared.vr_menu_state.lock().toggle();
log::info!(
"[Menu VR] {}",
if open { "Ouvert dans le casque" } else { "Fermé" }
);
open
}
pub fn vr_menu_back(&self) -> bool {
let still_open = self.shared.vr_menu_state.lock().back();
if !still_open {
log::info!("[Menu VR] Fermé");
}
still_open
}
/// Retourne `true` si le menu a été fermé, `false` s'il est simplement revenu du sous-menu Avancé.
pub fn close_vr_menu(&self) -> bool {
!self.vr_menu_back()
}
pub fn vr_menu_move(&self, delta: isize) {
self.shared.vr_menu_state.lock().move_selection(delta);
}
pub fn vr_menu_activate(&self) {
self.vr_menu_action(1, true);
}
pub fn vr_menu_adjust(&self, delta: i32) {
self.vr_menu_action(delta, false);
}
fn is_vehicle_armed_now(&self) -> bool {
let current = self.active_control_source();
let mon = self.shared.monitor.lock();
match current {
ControlSource::G29 => mon.latest_g29.is_live() && mon.latest_g29.armed,
ControlSource::SteamController => mon.latest_controller.armed,
}
}
fn vr_menu_action(&self, delta: i32, is_activate: bool) {
let (page, idx) = {
let st = self.shared.vr_menu_state.lock();
if !st.open {
return;
}
(st.page, st.selected_idx % st.page.item_count())
};
let step: i32 = if delta >= 0 { 1 } else { -1 };
match (page, idx) {
(VrMenuPage::Main, 0) => {
let target = match self.active_control_source() {
ControlSource::G29 => ControlSource::SteamController,
ControlSource::SteamController => ControlSource::G29,
};
match self.set_control_source(target) {
Ok(()) => self
.shared
.vr_menu_state
.lock()
.set_feedback("SOURCE CHANGEE", false),
Err(_) => self
.shared
.vr_menu_state
.lock()
.set_feedback("DESARMER D'ABORD!", true),
}
}
(VrMenuPage::Main, 1) => {
if !is_activate {
return;
}
self.request_recenter();
self.shared
.vr_menu_state
.lock()
.set_feedback("TARE HT OK", false);
}
(VrMenuPage::Main, 2) => {
let mut opt = self.shared.optical_params.lock();
opt.projection_mode = match (opt.projection_mode, step > 0) {
(ProjectionMode::Dome140, true) | (ProjectionMode::FlatQuad, false) => {
ProjectionMode::Cylinder140
}
(ProjectionMode::Cylinder140, true) | (ProjectionMode::Dome140, false) => {
ProjectionMode::FlatQuad
}
_ => ProjectionMode::Dome140,
};
let lbl = opt.projection_mode.label();
drop(opt);
log::info!("[Menu VR] Mode de projection VR : {}", lbl);
self.persist_live_config();
self.shared
.vr_menu_state
.lock()
.set_feedback("PROJECTION MAJ", false);
}
(VrMenuPage::Main, 3) => {
{
let mut opt = self.shared.optical_params.lock();
opt.screen_distance_m =
((opt.screen_distance_m + step as f32 * 0.2) * 10.0).round() / 10.0;
opt.screen_distance_m = opt.screen_distance_m.clamp(0.8, 4.0);
}
self.persist_live_config();
}
(VrMenuPage::Main, 4) => {
let next = self.toggle_telemetry();
self.shared
.vr_menu_state
.lock()
.set_feedback(if next { "OSD: ON" } else { "OSD: OFF" }, false);
}
(VrMenuPage::Main, 5) => {
if !is_activate {
return;
}
let rec = self.toggle_dvr();
self.shared
.vr_menu_state
.lock()
.set_feedback(if rec { "DVR DEMARRE" } else { "DVR ARRETE" }, false);
}
(VrMenuPage::Main, 6) => {
if !is_activate {
return;
}
let mut st = self.shared.vr_menu_state.lock();
st.page = VrMenuPage::Advanced;
st.selected_idx = 0;
st.quit_confirm_until = None;
st.feedback = None;
}
(VrMenuPage::Main, _) => {
if !is_activate {
return;
}
if self.is_vehicle_armed_now() {
self.shared
.vr_menu_state
.lock()
.set_feedback("DESARMER D'ABORD!", true);
return;
}
let confirmed = {
let mut st = self.shared.vr_menu_state.lock();
if st.quit_confirm_pending() {
st.open = false;
st.quit_confirm_until = None;
true
} else {
st.quit_confirm_until = Some(Instant::now() + Duration::from_secs(3));
st.set_feedback("REAPPUYER POUR QUITTER", true);
false
}
};
if confirmed {
self.request_exit();
}
}
(VrMenuPage::Advanced, 0) => {
if !is_activate {
return;
}
let mut st = self.shared.vr_menu_state.lock();
st.page = VrMenuPage::Main;
st.selected_idx = 6;
st.feedback = None;
}
(VrMenuPage::Advanced, 1) => {
let next = !self.shared.head_tracking_enabled_flag.load(Ordering::Acquire);
self.set_head_tracking_enabled(next);
self.shared
.vr_menu_state
.lock()
.set_feedback(if next { "SUIVI HT: ON" } else { "SUIVI HT: OFF" }, false);
}
(VrMenuPage::Advanced, 2) => {
{
let mut opt = self.shared.optical_params.lock();
opt.lens_k1 = ((opt.lens_k1 + step as f32 * 0.02) * 100.0).round() / 100.0;
opt.lens_k1 = opt.lens_k1.clamp(-0.50, 0.50);
}
self.persist_live_config();
}
(VrMenuPage::Advanced, 3) => {
{
let mut opt = self.shared.optical_params.lock();
opt.camera_fov_deg =
(opt.camera_fov_deg + step as f32 * 5.0).clamp(70.0, 180.0);
}
self.persist_live_config();
}
(VrMenuPage::Advanced, 4) => {
let mut limits = *self.shared.gear_speed_limits.lock();
limits.forward_max[2] =
limits.forward_max[2].saturating_add_signed((step * 10) as i16);
self.set_gear_speed_limits(limits);
}
(VrMenuPage::Advanced, 5) => {
let cur = self.shared.controller_vibration_pct.load(Ordering::Acquire) as i32;
let next = (cur + step * 10).clamp(0, 100) as u8;
self.set_controller_vibration_pct(next);
}
(VrMenuPage::Advanced, _) => {
if is_activate {
let (ch, ip_str) = {
let st = self.shared.vr_menu_state.lock();
(st.wifi_channel, st.radxa_vrx_ip.clone())
};
self.persist_live_config();
spawn_apply_radxa_channel(
ch,
ip_str,
Arc::clone(&self.shared.vr_menu_state),
Arc::clone(&self.shared.radxa_ssh_busy),
);
} else {
self.shared.vr_menu_state.lock().cycle_wifi_channel(step);
self.persist_live_config();
}
}
}
}
pub fn vr_menu_render_data(&self) -> Option<VrMenuRenderData> {
let st = self.shared.vr_menu_state.lock();
if !st.open {
return None;
}
let page = st.page;
let selected_idx = st.selected_idx % page.item_count();
let wifi_channel = st.wifi_channel;
let quit_confirm_pending = st.quit_confirm_pending();
let feedback_msg = st.active_feedback();
drop(st);
let opt = self.shared.optical_params.lock().clone();
let limits = *self.shared.gear_speed_limits.lock();
Some(VrMenuRenderData {
page,
selected_idx,
control_source: self.active_control_source(),
head_tracking_on: self
.shared
.head_tracking_enabled_flag
.load(Ordering::Relaxed),
telemetry_osd_on: self.shared.telemetry_enabled_flag.load(Ordering::Relaxed),
projection_label: opt.projection_mode.label(),
screen_distance_m: opt.screen_distance_m,
lens_k1: opt.lens_k1,
camera_fov_deg: opt.camera_fov_deg,
dvr_recording: self.shared.dvr_recording_flag.load(Ordering::Relaxed),
gear_3_max: limits.forward_max[2],
vibration_pct: self
.shared
.controller_vibration_pct
.load(Ordering::Relaxed)
.min(100),
wifi_channel,
quit_confirm_pending,
feedback_msg,
})
}
/// Met à jour à chaud les réglages d'amélioration image du Compute Shader GPU.
pub fn set_image_enhance(
&self,
brightness: f32,
contrast: f32,
gamma: f32,
sharpness: f32,
horizon_stabilization: bool,
stereo_sbs: bool,
) {
{
let mut opt = self.shared.optical_params.lock();
opt.brightness = brightness.clamp(-0.5, 0.5);
opt.contrast = contrast.clamp(0.5, 2.0);
opt.gamma = gamma.clamp(0.5, 2.2);
opt.sharpness = sharpness.clamp(0.0, 1.0);
opt.horizon_stabilization = horizon_stabilization;
opt.stereo_sbs = stereo_sbs;
}
self.persist_live_config();
}
/// Demande la sauvegarde asynchrone du pré-buffer Instant Replay 30 s (`.mkv`/`.mp4` + `.srt`).
pub fn request_instant_replay(&self) {
self.shared
.replay_save_requested
.store(true, Ordering::Release);
}
}
+183
View File
@@ -0,0 +1,183 @@
use crate::dome_projection::DomeWarpLut;
use crate::engine::{
compose_osd_and_publish, handle_dvr_lifecycle, sync_head_tracker, sync_telemetry_receiver,
EngineWorkerRefs,
};
use crate::nomad_elrs::HeadPoseSample;
use crate::telemetry_osd::OsdOverlay;
use crate::video_usb::{nv12_to_rgba_or_bgra, PixelFormat, UsbVideoReceiver};
use glam::{EulerRot, Quat};
use std::sync::atomic::Ordering;
use std::thread;
use std::time::{Duration, Instant};
pub fn run_desktop_fallback_loop(ctx: &mut EngineWorkerRefs<'_>) {
let mut dome_lut = DomeWarpLut::new(
ctx.cfg.video_width,
ctx.cfg.video_height,
ctx.cfg.camera_fov_deg,
ctx.cfg.lens_k1,
ctx.cfg.lens_k2,
);
let frame_bytes = (ctx.cfg.video_width * ctx.cfg.video_height * 4) as usize;
let mut raw_frame_buf: Vec<u8> = Vec::with_capacity(frame_bytes);
let mut cpu_rgba_buf: Vec<u8> = vec![0u8; frame_bytes];
let mut warped_rgba = vec![0u8; frame_bytes];
let mut composited_rgba = vec![0u8; frame_bytes];
let mut last_preview_push: Option<Instant> = None;
let mut standby_tick: u32 = 0;
let mut last_standby_draw: Option<Instant> = None;
let mut last_frame_id: u64 = 0;
let mut fps_counter: u32 = 0;
let mut fps_timer = Instant::now();
while !ctx.shared.stop_flag.load(Ordering::Relaxed) && !ctx.control.is_exit_requested() {
let loop_start = Instant::now();
let cur_opt = ctx.shared.optical_params.lock().clone();
if !dome_lut.matches_params(
ctx.cfg.video_width,
ctx.cfg.video_height,
cur_opt.camera_fov_deg,
cur_opt.lens_k1,
cur_opt.lens_k2,
) {
dome_lut = DomeWarpLut::new(
ctx.cfg.video_width,
ctx.cfg.video_height,
cur_opt.camera_fov_deg,
cur_opt.lens_k1,
cur_opt.lens_k2,
);
}
let active_proj = cur_opt.projection_mode;
handle_dvr_lifecycle(ctx);
let telem_on = ctx.shared.telemetry_enabled_flag.load(Ordering::Relaxed);
sync_telemetry_receiver(
ctx.cfg,
telem_on,
ctx.telem_rx_opt,
ctx.shared_telem_state,
&ctx.shared.monitor,
);
let ht_on = ctx.shared.head_tracking_enabled_flag.load(Ordering::Relaxed);
sync_head_tracker(ctx.cfg, ht_on, ctx.head_tracker_opt, &ctx.shared.monitor);
let (manual_pan, manual_tilt, manual_roll) = {
let mut mon = ctx.shared.monitor.lock();
if ctx.shared.recenter_flag.swap(false, Ordering::Relaxed) {
mon.manual_pan_deg = 0.0;
mon.manual_tilt_deg = 0.0;
mon.manual_roll_deg = 0.0;
if let Some(ref mut ht) = ctx.head_tracker_opt.inner {
ht.recenter(Quat::IDENTITY);
}
}
(mon.manual_pan_deg, mon.manual_tilt_deg, mon.manual_roll_deg)
};
let mut current_pose = HeadPoseSample::default();
if let Some(ref mut ht) = ctx.head_tracker_opt.inner {
let (trim_pan, trim_tilt) = *ctx.shared.head_trim_deg.lock();
let sim_quat = Quat::from_euler(
EulerRot::YXZ,
(-(manual_pan + trim_pan)).to_radians(),
(manual_tilt + trim_tilt).to_radians(),
(-manual_roll).to_radians(),
);
if let Ok(sample) = ht.send_pose(sim_quat) {
current_pose = sample;
}
}
let mut has_new_raw_frame = false;
let mut has_video_stream = false;
let mut frame_fmt = PixelFormat::Rgba;
if let Some(rx) = ctx.video_rx_opt {
let (live, taken) = rx.take_latest_frame(
&mut raw_frame_buf,
last_frame_id,
Duration::from_millis(1000),
);
has_video_stream = live;
if let Some(meta) = taken {
if meta.width == ctx.cfg.video_width && meta.height == ctx.cfg.video_height {
last_frame_id = meta.frame_id;
frame_fmt = meta.format;
fps_counter += 1;
has_new_raw_frame = true;
}
}
}
if has_new_raw_frame {
match frame_fmt {
PixelFormat::Nv12 => {
nv12_to_rgba_or_bgra(
&raw_frame_buf,
ctx.cfg.video_width,
ctx.cfg.video_height,
false,
&mut cpu_rgba_buf,
);
dome_lut.apply(&cpu_rgba_buf, &mut warped_rgba);
}
PixelFormat::Rgba => {
dome_lut.apply(&raw_frame_buf, &mut warped_rgba);
}
}
} else if !has_video_stream
&& last_standby_draw.is_none_or(|t| t.elapsed() >= Duration::from_millis(50))
{
last_standby_draw = Some(Instant::now());
standby_tick = standby_tick.wrapping_add(1);
UsbVideoReceiver::render_standby_pattern(
ctx.cfg.video_width,
ctx.cfg.video_height,
standby_tick,
&mut warped_rgba,
);
let standby_msg = if ctx.cfg.usb_video_mode.eq_ignore_ascii_case("uvc") {
"SIGNAL UVC PERDU - VERIFIER CAPTURE HDMI..."
} else {
"SIGNAL VRX PERDU - RECHERCHE FLUX UDP..."
};
OsdOverlay::draw_text(
&mut warped_rgba,
ctx.cfg.video_width,
ctx.cfg.video_height,
(ctx.cfg.video_width as i32 / 2) - 220,
(ctx.cfg.video_height as i32 / 2) + 70,
standby_msg,
(ctx.cfg.video_height / 360).max(2),
[255, 180, 40, 255],
);
}
let _ = compose_osd_and_publish(
ctx,
telem_on,
active_proj.label(),
current_pose,
has_new_raw_frame,
has_video_stream,
last_frame_id,
&mut fps_counter,
&mut fps_timer,
&mut last_preview_push,
&warped_rgba,
&mut composited_rgba,
true,
);
let elapsed = loop_start.elapsed();
let target_dt = Duration::from_millis(8); // Jusqu'à 120 Hz sur les flux 90/120 FPS
if elapsed < target_dt {
thread::sleep(target_dt - elapsed);
}
}
}
+1084
View File
File diff suppressed because it is too large. Load diff
+69
View File
@@ -0,0 +1,69 @@
use crate::engine::vr_menu::VrMenuState;
use parking_lot::Mutex;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::thread;
/// Lance en arrière-plan la mise à jour du canal 5.8 GHz sur la Radxa Zero 3W via SSH sécurisé.
/// Protégé par un verrou atomique `ssh_busy` pour empêcher les exécutions concurrentes.
pub fn spawn_apply_radxa_channel(
ch: u16,
ip_str: String,
menu_ref: Arc<Mutex<VrMenuState>>,
ssh_busy: Arc<AtomicBool>,
) {
if ssh_busy.swap(true, Ordering::AcqRel) {
menu_ref.lock().set_feedback("SSH DEJA EN COURS", true);
return;
}
let Ok(ip) = ip_str.trim().parse::<std::net::IpAddr>() else {
ssh_busy.store(false, Ordering::Release);
menu_ref.lock().set_feedback("IP RADXA INVALIDE", true);
return;
};
menu_ref.lock().set_feedback("ENVOI CANAL SSH...", false);
// Vérifie qu'au moins la mise à jour config ou `iw` réussit (exit != 0 si tout échoue)
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 ]"
);
thread::spawn(move || {
let res = std::process::Command::new("ssh")
.args([
"-o",
"BatchMode=yes",
"-o",
"ConnectTimeout=2",
"-o",
"StrictHostKeyChecking=accept-new",
"--",
&format!("root@{}", ip),
&remote_cmd,
])
.output();
ssh_busy.store(false, Ordering::Release);
match res {
Ok(out) if out.status.success() => {
log::info!("[Menu VR] Canal 5.8GHz {} appliqué sur Radxa {}", ch, ip);
menu_ref.lock().set_feedback("CANAL RADXA OK", false);
}
Ok(out) => {
log::warn!(
"[Menu VR] Échec SSH canal Radxa (exit={}): {}",
out.status,
String::from_utf8_lossy(&out.stderr).trim()
);
menu_ref.lock().set_feedback("ECHEC SSH RADXA", true);
}
Err(e) => {
log::error!("[Menu VR] Erreur SSH Radxa : {}", e);
menu_ref.lock().set_feedback("ERREUR SSH", true);
}
}
});
}
+188
View File
@@ -0,0 +1,188 @@
use super::vr_menu::VrMenuState;
use crate::config::AppConfig;
use crate::controller::{ControlSource, GearSpeedLimits, SteamControllerState};
use crate::dome_projection::ProjectionMode;
use crate::dvr::{DvrContainer, DvrMode, ReplayRingBuffer};
use crate::g29_bridge::G29State;
use crate::nomad_elrs::HeadPoseSample;
use crate::telemetry_osd::TelemetryState;
use parking_lot::Mutex;
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicU8};
use std::sync::Arc;
use std::thread::JoinHandle;
use std::time::{Duration, Instant};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SubsystemStatus {
Stopped,
Disabled,
Starting,
Running(String),
Warning(String),
Error(String),
}
#[derive(Debug, Clone)]
pub struct LiveOpticalParams {
pub camera_fov_deg: f32,
pub lens_k1: f32,
pub lens_k2: f32,
pub screen_distance_m: f32,
pub screen_width_m: f32,
pub projection_mode: ProjectionMode,
pub brightness: f32,
pub contrast: f32,
pub gamma: f32,
pub sharpness: f32,
pub horizon_stabilization: bool,
pub stereo_sbs: bool,
}
#[derive(Debug, Clone)]
pub struct DvrConfig {
pub dir: String,
pub container: DvrContainer,
pub mode: DvrMode,
}
pub struct RuntimeMonitor {
pub usb_video_status: SubsystemStatus,
pub openxr_status: SubsystemStatus,
pub nomad_wifi_status: SubsystemStatus,
pub telemetry_status: SubsystemStatus,
pub g29_status: SubsystemStatus,
pub controller_status: SubsystemStatus,
pub active_control_source: ControlSource,
pub dvr_status: SubsystemStatus,
pub dvr_recording: bool,
pub dvr_elapsed_secs: u64,
pub dvr_file_size_bytes: u64,
pub dvr_frames_recorded: u64,
pub dvr_filename: String,
pub dvr_file_path: String,
pub replay_buffered_bytes: u64,
pub replay_status_text: String,
pub dmabuf_active: bool,
pub video_fps: f32,
pub video_jitter_ms: f32,
pub video_dropped_frames: u64,
pub video_decoder_name: String,
pub video_frames_total: u64,
pub latest_head_pose: HeadPoseSample,
pub latest_telemetry: TelemetryState,
pub latest_g29: G29State,
pub latest_controller: SteamControllerState,
/// Tampon BGRA prêt pour GPUI (évite le double-clone + swizzle RGBA->BGRA sur le thread UI).
pub preview_bgra: Arc<Vec<u8>>,
pub preview_width: u32,
pub preview_height: u32,
pub preview_frame_seq: u64,
pub manual_pan_deg: f32,
pub manual_tilt_deg: f32,
pub manual_roll_deg: f32,
}
impl Default for RuntimeMonitor {
fn default() -> Self {
Self {
usb_video_status: SubsystemStatus::Stopped,
openxr_status: SubsystemStatus::Stopped,
nomad_wifi_status: SubsystemStatus::Stopped,
telemetry_status: SubsystemStatus::Disabled,
g29_status: SubsystemStatus::Disabled,
controller_status: SubsystemStatus::Disabled,
active_control_source: ControlSource::G29,
dvr_status: SubsystemStatus::Stopped,
dvr_recording: false,
dvr_elapsed_secs: 0,
dvr_file_size_bytes: 0,
dvr_frames_recorded: 0,
dvr_filename: String::new(),
dvr_file_path: String::new(),
replay_buffered_bytes: 0,
replay_status_text: String::new(),
dmabuf_active: false,
video_fps: 0.0,
video_jitter_ms: 0.0,
video_dropped_frames: 0,
video_decoder_name: "auto".to_string(),
video_frames_total: 0,
latest_head_pose: HeadPoseSample::default(),
latest_telemetry: TelemetryState::default(),
latest_g29: G29State::default(),
latest_controller: SteamControllerState::default(),
preview_bgra: Arc::new(Vec::new()),
preview_width: 0,
preview_height: 0,
preview_frame_seq: 0,
manual_pan_deg: 0.0,
manual_tilt_deg: 0.0,
manual_roll_deg: 0.0,
}
}
}
/// État partagé centralisé du moteur FPV (supprime le passage de 20 `Arc` individuels).
pub struct EngineSharedState {
pub monitor: Arc<Mutex<RuntimeMonitor>>,
pub optical_params: Arc<Mutex<LiveOpticalParams>>,
pub dvr_toggle_cmd: Arc<Mutex<Option<bool>>>,
pub dvr_config: Arc<Mutex<DvrConfig>>,
pub dvr_recording_flag: Arc<AtomicBool>,
pub head_trim_deg: Arc<Mutex<(f32, f32)>>,
pub stop_flag: Arc<AtomicBool>,
pub recenter_flag: Arc<AtomicBool>,
pub telemetry_enabled_flag: Arc<AtomicBool>,
pub head_tracking_enabled_flag: Arc<AtomicBool>,
pub control_source_flag: Arc<AtomicU8>,
pub controller_vibration_pct: Arc<AtomicU8>,
pub controller_invert_steering: Arc<AtomicBool>,
pub controller_rumble_test: Arc<AtomicBool>,
pub gear_speed_limits: Arc<Mutex<GearSpeedLimits>>,
pub preview_active_flag: Arc<AtomicBool>,
pub exit_requested_flag: Arc<AtomicBool>,
pub vr_menu_state: Arc<Mutex<VrMenuState>>,
pub radxa_ssh_busy: Arc<AtomicBool>,
pub persisted_cfg: Arc<Mutex<Option<AppConfig>>>,
pub config_revision: Arc<AtomicU64>,
pub dvr_finalize_handles: Arc<Mutex<Vec<JoinHandle<()>>>>,
/// Pré-buffer Instant Replay 30 s en RAM + déclencheur de sauvegarde
pub replay_buffer: Arc<ReplayRingBuffer>,
pub replay_save_requested: Arc<AtomicBool>,
/// Paramètres batterie live : `(cells, warn_cell_v, crit_cell_v)`
pub battery_params: Arc<Mutex<(u8, f32, f32)>>,
}
pub struct RetrySlot<T> {
pub inner: Option<T>,
last_fail: Option<Instant>,
}
impl<T> RetrySlot<T> {
const RETRY_COOLDOWN: Duration = Duration::from_secs(3);
pub fn new() -> Self {
Self {
inner: None,
last_fail: None,
}
}
pub fn clear(&mut self) {
self.inner = None;
self.last_fail = None;
}
pub fn ready_to_try(&self) -> bool {
self.inner.is_none()
&& self
.last_fail
.map(|t| t.elapsed() >= Self::RETRY_COOLDOWN)
.unwrap_or(true)
}
pub fn record_failure(&mut self) {
self.last_fail = Some(Instant::now());
}
}
+139
View File
@@ -0,0 +1,139 @@
use crate::telemetry_osd::VrMenuPage;
use std::time::{Duration, Instant};
pub const RADXA_WIFI_CHANNELS: &[u16] = &[36, 40, 44, 48, 149, 153, 157, 161, 165];
#[derive(Debug, Clone)]
pub struct VrMenuState {
pub open: bool,
pub page: VrMenuPage,
pub selected_idx: usize,
pub wifi_channel: u16,
pub radxa_vrx_ip: String,
pub quit_confirm_until: Option<Instant>,
pub feedback: Option<(&'static str, bool, Instant)>,
}
impl Default for VrMenuState {
fn default() -> Self {
Self {
open: false,
page: VrMenuPage::Main,
selected_idx: 0,
wifi_channel: 161,
radxa_vrx_ip: "192.168.1.1".to_string(),
quit_confirm_until: None,
feedback: None,
}
}
}
impl VrMenuState {
pub fn set_feedback(&mut self, msg: &'static str, is_err: bool) {
self.feedback = Some((msg, is_err, Instant::now() + Duration::from_millis(2000)));
}
pub fn active_feedback(&self) -> Option<(&'static str, bool)> {
match self.feedback {
Some((msg, is_err, until)) if Instant::now() < until => Some((msg, is_err)),
_ => None,
}
}
pub fn quit_confirm_pending(&self) -> bool {
self.quit_confirm_until
.map(|u| Instant::now() < u)
.unwrap_or(false)
}
pub fn toggle(&mut self) -> bool {
self.open = !self.open;
self.page = VrMenuPage::Main;
self.selected_idx = 0;
self.quit_confirm_until = None;
if self.open {
self.feedback = None;
}
self.open
}
/// Retourne `true` si le menu reste ouvert, `false` s'il a été fermé.
pub fn back(&mut self) -> bool {
if !self.open {
return false;
}
self.quit_confirm_until = None;
if self.page == VrMenuPage::Advanced {
self.page = VrMenuPage::Main;
self.selected_idx = 6;
self.feedback = None;
true
} else {
self.open = false;
false
}
}
pub fn move_selection(&mut self, delta: isize) {
if !self.open {
return;
}
self.quit_confirm_until = None;
let count = self.page.item_count() as isize;
self.selected_idx = (self.selected_idx as isize + delta).rem_euclid(count) as usize;
}
pub fn cycle_wifi_channel(&mut self, step: i32) {
let cur_pos = RADXA_WIFI_CHANNELS
.iter()
.position(|&c| c == self.wifi_channel)
.unwrap_or(RADXA_WIFI_CHANNELS.len() - 2);
let next_pos = (cur_pos as isize + step as isize)
.rem_euclid(RADXA_WIFI_CHANNELS.len() as isize) as usize;
self.wifi_channel = RADXA_WIFI_CHANNELS[next_pos];
self.set_feedback("A/CROIX POUR APPLIQUER", false);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_vr_menu_state_navigation_and_back() {
let mut st = VrMenuState::default();
assert!(!st.open);
assert!(st.toggle());
assert_eq!(st.selected_idx, 0);
// Wrap-around vers le bas / le haut
st.move_selection(-1);
assert_eq!(st.selected_idx, VrMenuPage::Main.item_count() - 1);
st.move_selection(1);
assert_eq!(st.selected_idx, 0);
// Sous-menu Avancé -> Retour revient sur Main(6) sans fermer
st.page = VrMenuPage::Advanced;
st.selected_idx = 2;
assert!(st.back());
assert!(st.open);
assert_eq!(st.page, VrMenuPage::Main);
assert_eq!(st.selected_idx, 6);
// Second back ferme le menu
assert!(!st.back());
assert!(!st.open);
}
#[test]
fn test_vr_menu_wifi_channel_cycle() {
let mut st = VrMenuState::default();
assert_eq!(st.wifi_channel, 161);
st.cycle_wifi_channel(1);
assert_eq!(st.wifi_channel, 165);
st.cycle_wifi_channel(1);
assert_eq!(st.wifi_channel, 36);
st.cycle_wifi_channel(-1);
assert_eq!(st.wifi_channel, 165);
}
}
File diff suppressed because it is too large. Load diff
+54 -18
View File
@@ -174,17 +174,19 @@ impl G29BridgeReceiver {
let worker = thread::Builder::new()
.name("g29-udp-rx".into())
.spawn(move || {
let mut buf = [0u8; 512];
let mut last_reject_log = Instant::now() - Duration::from_secs(10);
let mut buf = [0u8; 2048];
let mut last_reject_log: Option<Instant> = None;
while !stop_clone.load(Ordering::Acquire) {
if let Ok((len, src)) = socket.recv_from(&mut buf) {
if !Self::is_peer_allowed(src.ip(), &allowed_peers) {
if last_reject_log.elapsed() >= Duration::from_secs(5) {
if last_reject_log
.is_none_or(|t| t.elapsed() >= Duration::from_secs(5))
{
log::warn!(
"[G29 Bridge] Paquet UDP rejeté depuis IP non autorisée : {}",
src
);
last_reject_log = Instant::now();
last_reject_log = Some(Instant::now());
}
continue;
}
@@ -198,10 +200,18 @@ impl G29BridgeReceiver {
);
}
}
} else {
}
// Vérifier le timeout G29 à chaque itération (même si des trames $CRSF continuent d'arriver)
{
let mut st = state_clone.lock();
if st.connected && !st.is_live() {
st.connected = false;
st.armed = false;
st.failsafe = true;
st.gear = 0;
st.throttle_pct = 0;
st.brake_pct = 0;
st.clutch_pct = 0;
log::warn!("[G29 Bridge] Perte de liaison avec le volant G29.");
}
}
@@ -220,10 +230,11 @@ impl G29BridgeReceiver {
pub fn send_command(target_ip: &str, target_port: u16, cmd: &str) -> Result<()> {
let socket = UdpSocket::bind("0.0.0.0:0")?;
let target = format!("{}:{}", target_ip.trim(), target_port);
let payload = if cmd.ends_with('\n') {
cmd.to_string()
let trimmed = cmd.trim();
let payload = if trimmed.starts_with('$') && !trimmed.contains('*') {
crate::nomad_elrs::NomadHeadTracker::append_nmea_crc8(trimmed)
} else {
format!("{}\n", cmd)
format!("{}\n", trimmed)
};
socket.send_to(payload.as_bytes(), target)?;
Ok(())
@@ -237,6 +248,25 @@ impl G29BridgeReceiver {
Arc::clone(&self.state)
}
/// Vérifie et retire le suffixe CRC-8 `*XX` optionnel sur les trames `$G29` / `$G29_EVT`.
/// Si `*` est présent, le CRC-8 DVB-S2 doit être valide (sinon la trame est rejetée).
fn verify_optional_crc8(line: &str) -> Option<&str> {
if let Some((body, crc_hex)) = line.rsplit_once('*') {
if crc_hex.len() != 2 {
return None;
}
let expected = u8::from_str_radix(crc_hex, 16).ok()?;
let calc = crate::nomad_elrs::NomadHeadTracker::crc8_dvb_s2(body.as_bytes());
if calc == expected {
Some(body)
} else {
None
}
} else {
Some(line)
}
}
pub fn process_line(
raw_line: &str,
state: &Arc<Mutex<G29State>>,
@@ -244,10 +274,18 @@ impl G29BridgeReceiver {
telemetry: Option<&Arc<Mutex<TelemetryState>>>,
) {
let line = raw_line.trim();
if let Some(rest) = line.strip_prefix("$G29,") {
Self::parse_status_fields(rest, state);
} else if let Some(rest) = line.strip_prefix("$G29_EVT,") {
Self::parse_button_event(rest, state, control);
if line.starts_with("$G29,") {
if let Some(verified) = Self::verify_optional_crc8(line) {
if let Some(rest) = verified.strip_prefix("$G29,") {
Self::parse_status_fields(rest, state);
}
}
} else if line.starts_with("$G29_EVT,") {
if let Some(verified) = Self::verify_optional_crc8(line) {
if let Some(rest) = verified.strip_prefix("$G29_EVT,") {
Self::parse_button_event(rest, state, control);
}
}
} else if let Some(hex) = line.strip_prefix("$CRSF,") {
if let Some(telem) = telemetry {
Self::parse_crsf_hex(hex, telem);
@@ -257,12 +295,12 @@ impl G29BridgeReceiver {
fn parse_crsf_hex(hex: &str, telemetry: &Arc<Mutex<TelemetryState>>) {
let bytes = hex.trim().as_bytes();
if bytes.len() < 8 || bytes.len() % 2 != 0 || bytes.len() > 128 {
if bytes.len() < 8 || !bytes.len().is_multiple_of(2) || bytes.len() > 128 {
return;
}
let mut raw = [0u8; 64];
let mut out_len = 0;
for chunk in bytes.chunks_exact(2) {
for chunk in bytes.as_chunks::<2>().0 {
let Some(hi) = Self::hex_nibble(chunk[0]) else {
return;
};
@@ -420,10 +458,8 @@ impl G29BridgeReceiver {
None
}
G29ButtonEvent::Circle if menu_open => {
if let Some(ctrl) = control {
ctrl.close_vr_menu();
}
Some("MENU VR OFF".to_string())
let closed = control.map(|ctrl| ctrl.close_vr_menu()).unwrap_or(true);
Some(if closed { "MENU VR OFF" } else { "RETOUR MENU" }.to_string())
}
G29ButtonEvent::DpadUp if menu_open => {
if let Some(ctrl) = control {
-3846
View File
File diff suppressed because it is too large. Load diff
+56 -30
View File
@@ -47,10 +47,13 @@ impl Default for LogBuffer {
enum FileLogCmd {
Line { text: String, flush: bool },
Flush,
FlushSync(mpsc::SyncSender<()>),
}
static GLOBAL_LOG_TX: std::sync::OnceLock<SyncSender<FileLogCmd>> = std::sync::OnceLock::new();
/// Logger centralisé capturant tous les événements et erreurs pour l'interface graphique
/// et les enregistrant sur un thread I/O dédié sans jamais bloquer les boucles temps réel.
/// et les enregistrant sur un thread I/O dédié (stderr + fichier) sans jamais bloquer les boucles temps réel.
pub struct GuiLogger {
buffer: Arc<Mutex<LogBuffer>>,
file_tx: Option<SyncSender<FileLogCmd>>,
@@ -60,34 +63,53 @@ impl GuiLogger {
pub fn init(log_file_path: &str) -> Arc<Mutex<LogBuffer>> {
let buffer = Arc::new(Mutex::new(LogBuffer::default()));
let file_tx = OpenOptions::new()
let file_opt = OpenOptions::new()
.create(true)
.append(true)
.open(log_file_path)
.ok()
.and_then(|file| {
let (tx, rx) = mpsc::sync_channel::<FileLogCmd>(512);
thread::Builder::new()
.name("fpv-log-writer".into())
.spawn(move || {
let mut writer = BufWriter::new(file);
while let Ok(cmd) = rx.recv() {
match cmd {
FileLogCmd::Line { text, flush } => {
let _ = writer.write_all(text.as_bytes());
if flush {
let _ = writer.flush();
}
}
FileLogCmd::Flush => {
let _ = writer.flush();
.ok();
let (tx, rx) = mpsc::sync_channel::<FileLogCmd>(512);
let file_tx = thread::Builder::new()
.name("fpv-log-writer".into())
.spawn(move || {
let mut writer = file_opt.map(BufWriter::new);
let mut stderr = std::io::stderr();
while let Ok(cmd) = rx.recv() {
match cmd {
FileLogCmd::Line { text, flush } => {
let _ = stderr.write_all(text.as_bytes());
if let Some(ref mut w) = writer {
let _ = w.write_all(text.as_bytes());
if flush {
let _ = w.flush();
}
}
}
let _ = writer.flush();
})
.ok()
.map(|_| tx)
FileLogCmd::Flush => {
let _ = stderr.flush();
if let Some(ref mut w) = writer {
let _ = w.flush();
}
}
FileLogCmd::FlushSync(ack) => {
let _ = stderr.flush();
if let Some(ref mut w) = writer {
let _ = w.flush();
}
let _ = ack.send(());
}
}
}
let _ = stderr.flush();
if let Some(ref mut w) = writer {
let _ = w.flush();
}
})
.ok()
.map(|_| {
let _ = GLOBAL_LOG_TX.set(tx.clone());
tx
});
let logger = Box::new(Self {
@@ -101,6 +123,16 @@ impl GuiLogger {
buffer
}
/// Attend la vidange complète du fichier journal et de `stderr` avant la fin du processus.
pub fn flush_blocking() {
if let Some(tx) = GLOBAL_LOG_TX.get() {
let (ack_tx, ack_rx) = mpsc::sync_channel::<()>(1);
if tx.send(FileLogCmd::FlushSync(ack_tx)).is_ok() {
let _ = ack_rx.recv_timeout(std::time::Duration::from_millis(500));
}
}
}
}
impl Log for GuiLogger {
@@ -131,13 +163,7 @@ impl Log for GuiLogger {
message: format!("{}", record.args()),
};
// Affichage console standard
eprintln!(
"[{}] [{:<5}] ({}) {}",
entry.timestamp, entry.level, entry.target, entry.message
);
// Envoi non-bloquant vers le thread d'écriture disque (jamais d'I/O sur thread temps réel)
// Envoi non-bloquant vers le thread I/O dédié (stderr + fichier, jamais de syscall bloquant ici)
if let Some(ref tx) = self.file_tx {
let line = format!(
"[{}] [{:<5}] ({}) {}\n",
+13 -6
View File
@@ -4,15 +4,15 @@ mod dome_projection;
mod dvr;
mod engine;
mod g29_bridge;
mod gui_gpui;
mod logger;
mod nomad_elrs;
mod telemetry_osd;
mod ui;
mod video_usb;
mod vulkan_warp;
mod vulkan_xr;
use anyhow::Result;
use clap::Parser;
use config::AppConfig;
use engine::FpvEngineController;
use logger::GuiLogger;
@@ -21,6 +21,10 @@ use std::time::Duration;
static SHUTDOWN_REQUESTED: AtomicBool = AtomicBool::new(false);
pub fn is_shutdown_requested() -> bool {
SHUTDOWN_REQUESTED.load(Ordering::Acquire)
}
extern "C" fn on_termination_signal(_sig: std::ffi::c_int) {
SHUTDOWN_REQUESTED.store(true, Ordering::Release);
}
@@ -39,7 +43,8 @@ fn install_signal_handlers() {
}
fn main() -> Result<()> {
let mut cfg = AppConfig::parse();
install_signal_handlers();
let mut cfg = AppConfig::parse_with_saved();
let log_buffer = GuiLogger::init(&cfg.log_file);
let mode_label = if cfg.vr_only {
@@ -57,7 +62,6 @@ fn main() -> Result<()> {
);
if cfg.no_gui || cfg.vr_only {
install_signal_handlers();
if cfg.vr_only {
cfg.headless = false;
log::info!("Mode VR natif direct (--vr-only) activé : session OpenXR plein casque sans fenêtre 2D.");
@@ -69,7 +73,7 @@ fn main() -> Result<()> {
control.set_preview_active(false);
engine.start(cfg);
while !SHUTDOWN_REQUESTED.load(Ordering::Acquire)
while !is_shutdown_requested()
&& !control.is_exit_requested()
&& engine.is_running()
{
@@ -77,8 +81,11 @@ fn main() -> Result<()> {
}
log::info!("[FPV] Arrêt demandé, fermeture sécurisée du moteur FPV...");
engine.stop();
GuiLogger::flush_blocking();
return Ok(());
}
gui_gpui::run_gpui_app(cfg, log_buffer)
let res = ui::run_gpui_app(cfg, log_buffer);
GuiLogger::flush_blocking();
res
}
+29 -16
View File
@@ -102,15 +102,6 @@ impl NomadHeadTracker {
max_roll_deg: f32,
protocol: NomadProtocol,
) -> Result<Self> {
let socket = UdpSocket::bind("0.0.0.0:0").map_err(|e| {
log::error!(
"[Wi-Fi Nomad] Impossible de créer le socket UDP sortant : {}",
e
);
e
})?;
socket.set_nonblocking(true)?;
let trimmed_ip = nomad_ip.trim();
let host_port = format!("{}:{}", trimmed_ip, nomad_port);
let target = if let Ok(ip) = trimmed_ip.parse::<std::net::IpAddr>() {
@@ -135,6 +126,16 @@ impl NomadHeadTracker {
.ok_or_else(|| anyhow!("Aucune adresse IP résolue pour {}", host_port))?
};
let bind_addr = if target.is_ipv6() { "[::]:0" } else { "0.0.0.0:0" };
let socket = UdpSocket::bind(bind_addr).map_err(|e| {
log::error!(
"[Wi-Fi Nomad] Impossible de créer le socket UDP sortant : {}",
e
);
e
})?;
socket.set_nonblocking(true)?;
log::info!(
"[Wi-Fi Nomad] Émetteur prêt vers {} ({}) (Protocole: {})",
host_port,
@@ -160,13 +161,25 @@ impl NomadHeadTracker {
/// Réinitialise le centre du suivi de tête (Tare) sur la posture actuelle du casque
pub fn recenter(&mut self, current_orientation: Quat) {
self.zero_quat_inv = current_orientation.inverse();
let safe_q = if current_orientation.is_finite()
&& current_orientation.length_squared() > 1e-8
{
current_orientation.normalize()
} else {
Quat::IDENTITY
};
self.zero_quat_inv = safe_q.inverse();
log::info!("[Head-Tracker] Centre (Tare) réinitialisé sur la position actuelle du casque.");
}
/// Calcule Pan/Tilt/Roll depuis le quaternion OpenXR et envoie la trame UDP au Nomad
pub fn send_pose(&mut self, current_orientation: Quat) -> Result<HeadPoseSample> {
let relative = (self.zero_quat_inv * current_orientation).normalize();
let raw_rel = self.zero_quat_inv * current_orientation;
let relative = if raw_rel.is_finite() && raw_rel.length_squared() > 1e-8 {
raw_rel.normalize()
} else {
Quat::IDENTITY
};
let (yaw_rad, pitch_rad, roll_rad) = relative.to_euler(EulerRot::YXZ);
@@ -200,7 +213,7 @@ impl NomadHeadTracker {
NomadProtocol::Mavlink => {
if self
.last_mav_heartbeat
.map_or(true, |t| t.elapsed() >= Duration::from_secs(1))
.is_none_or(|t| t.elapsed() >= Duration::from_secs(1))
{
let hb = Self::encode_mavlink_heartbeat(self.mav_seq);
self.mav_seq = self.mav_seq.wrapping_add(1);
@@ -260,7 +273,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_finite() || !max_deg.is_finite() || max_deg <= 0.0 {
return CRSF_CHANNEL_MID;
}
let norm = (angle_deg / max_deg).clamp(-1.0, 1.0);
@@ -299,9 +312,9 @@ impl NomadHeadTracker {
pub fn encode_crsf_rc_channels(pan: u16, tilt: u16, roll: u16) -> [u8; 26] {
let mut ch = [CRSF_CHANNEL_MID; 16];
ch[0] = pan;
ch[1] = tilt;
ch[2] = roll;
ch[0] = pan.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX);
ch[1] = tilt.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX);
ch[2] = roll.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX);
let mut frame = [0u8; 26];
frame[0] = 0xEE;
+298
View File
@@ -0,0 +1,298 @@
mod osd;
mod parser;
mod state;
pub use osd::{OsdExtraOptions, OsdOverlay, VrMenuPage, VrMenuRenderData};
pub use parser::TelemetryReceiver;
pub use state::TelemetryState;
/// Tampon de formatage rapide sur la pile pour éliminer toute allocation sur le tas dans l'OSD
pub(super) struct StackStr<const N: usize> {
buf: [u8; N],
len: usize,
}
impl<const N: usize> StackStr<N> {
#[inline]
pub(super) fn new() -> Self {
Self { buf: [0u8; N], len: 0 }
}
#[inline]
pub(super) fn as_str(&self) -> &str {
std::str::from_utf8(&self.buf[..self.len]).unwrap_or("")
}
}
impl<const N: usize> std::fmt::Write for StackStr<N> {
#[inline]
fn write_str(&mut self, s: &str) -> std::fmt::Result {
let avail = N.saturating_sub(self.len);
let mut to_copy = s.len().min(avail);
while to_copy > 0 && !s.is_char_boundary(to_copy) {
to_copy -= 1;
}
self.buf[self.len..self.len + to_copy].copy_from_slice(&s.as_bytes()[..to_copy]);
self.len += to_copy;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::controller::ControlSource;
use parking_lot::Mutex;
use std::fmt::Write as FmtWrite;
use std::sync::Arc;
#[test]
fn test_stack_str_utf8_boundary_truncation() {
let mut s = StackStr::<3>::new();
let _ = write!(s, "12°");
assert_eq!(s.as_str(), "12");
let mut s4 = StackStr::<4>::new();
let _ = write!(s4, "12°");
assert_eq!(s4.as_str(), "12°");
}
#[test]
fn test_render_vr_menu_bounds_and_output() {
let mut rgba = vec![100u8; 1280 * 720 * 4];
let mut menu = VrMenuRenderData {
page: VrMenuPage::Main,
selected_idx: 0,
control_source: ControlSource::SteamController,
head_tracking_on: true,
telemetry_osd_on: true,
projection_label: "DOME 140",
screen_distance_m: 1.6,
lens_k1: -0.14,
camera_fov_deg: 140.0,
dvr_recording: false,
gear_3_max: 1220,
vibration_pct: 100,
wifi_channel: 161,
quit_confirm_pending: false,
feedback_msg: Some(("TARE HT OK", false)),
};
OsdOverlay::render_vr_menu(&mut rgba, 1280, 720, &menu);
let center_idx = ((720 / 2) * 1280 + (1280 / 2)) * 4;
assert_ne!(&rgba[center_idx..center_idx + 3], &[100, 100, 100]);
menu.page = VrMenuPage::Advanced;
menu.selected_idx = 6;
OsdOverlay::render_vr_menu(&mut rgba, 1280, 720, &menu);
OsdOverlay::render_vr_standby_bar(
&mut rgba,
1280,
720,
false,
ControlSource::G29,
false,
);
}
#[test]
fn test_parse_datagram_crsf_crc_validation() {
let state = Arc::new(Mutex::new(TelemetryState::default()));
// Trame CRSF Battery Sensor (0x08) : 16.8V (168 = 0x00A8), 12.5A (125 = 0x007D), remaining = 75%
let mut frame = [0u8; 12];
frame[0] = 0xC8;
frame[1] = 10; // type(1) + payload(8) + crc(1)
frame[2] = 0x08;
frame[3..5].copy_from_slice(&168u16.to_be_bytes());
frame[5..7].copy_from_slice(&125u16.to_be_bytes());
frame[10] = 75;
frame[11] = crate::nomad_elrs::NomadHeadTracker::crc8_dvb_s2(&frame[2..11]);
// Trame au CRC corrompu : doit être ignorée
let mut bad_frame = frame;
bad_frame[11] ^= 0xFF;
TelemetryReceiver::parse_datagram(&bad_frame, &state);
assert_eq!(state.lock().packets_received, 0);
// Trame valide : doit être acceptée et décodée
TelemetryReceiver::parse_datagram(&frame, &state);
let st = state.lock();
assert_eq!(st.packets_received, 1);
assert!((st.battery_voltage_v - 16.8).abs() < 0.01);
assert!((st.battery_current_a - 12.5).abs() < 0.01);
assert_eq!(st.battery_remaining_pct, 75);
}
#[test]
fn test_crsf_attitude_terrain_roughness() {
let state = Arc::new(Mutex::new(TelemetryState::default()));
let make_att_frame = |pitch_10000: i16, roll_10000: i16| -> [u8; 10] {
let mut f = [0u8; 10];
f[0] = 0xEA;
f[1] = 8; // type(1) + payload(6) + crc(1)
f[2] = 0x1E;
f[3..5].copy_from_slice(&pitch_10000.to_be_bytes());
f[5..7].copy_from_slice(&roll_10000.to_be_bytes());
f[7..9].copy_from_slice(&0i16.to_be_bytes());
f[9] = crate::nomad_elrs::NomadHeadTracker::crc8_dvb_s2(&f[2..9]);
f
};
// Première trame : initialise la référence -> rugosité 0
TelemetryReceiver::parse_datagram(&make_att_frame(0, 0), &state);
assert_eq!(state.lock().effective_terrain_roughness(), 0);
// Micro-bruit sous le seuil de 60 (0.006 rad) -> filtré à 0
TelemetryReceiver::parse_datagram(&make_att_frame(20, 20), &state);
assert_eq!(state.lock().effective_terrain_roughness(), 0);
// Grosse secousse (> 450 -> saturation à 255)
TelemetryReceiver::parse_datagram(&make_att_frame(300, 300), &state);
assert_eq!(state.lock().effective_terrain_roughness(), 255);
}
#[test]
fn test_crsf_link_stats_rssi_128_no_overflow_and_defaults() {
let state = Arc::new(Mutex::new(TelemetryState::default()));
{
let st = state.lock();
assert!(!st.is_live());
assert_eq!(st.link_quality_pct, 0);
assert_eq!(st.rssi_dbm, -127);
}
// Trame CRSF LINK_STATISTICS (0x14) avec RSSI1 = 128 (0x80, i8::MIN!) et LQ = 98
let mut frame = [0u8; 14];
frame[0] = 0xC8;
frame[1] = 12; // type(1) + payload(10) + crc(1)
frame[2] = 0x14;
frame[3] = 0x80; // 128 dBm
frame[4] = 95;
frame[5] = 98; // LQ
frame[7] = 0; // active antenna = 0
frame[13] = crate::nomad_elrs::NomadHeadTracker::crc8_dvb_s2(&frame[2..13]);
TelemetryReceiver::parse_datagram(&frame, &state);
let st = state.lock();
assert!(st.is_live());
assert_eq!(st.rssi_dbm, -127);
assert_eq!(st.link_quality_pct, 98);
}
#[test]
fn test_mavlink_v2_zero_truncated_sys_status() {
let state = Arc::new(Mutex::new(TelemetryState::default()));
// MAVLink v2 SYS_STATUS (msgid 1) tronqué à 18 octets (battery_remaining = 0 tronqué)
let mut payload = [0u8; 18];
payload[14..16].copy_from_slice(&15200u16.to_le_bytes()); // 15.2 V
payload[16..18].copy_from_slice(&450i16.to_le_bytes()); // 4.5 A
let mut pkt = vec![
0xFD,
payload.len() as u8,
0, // incompat_flags
0, // compat_flags
1, // seq
1, // sysid
1, // compid
1, // msgid = 1 (SYS_STATUS)
0,
0,
];
pkt.extend_from_slice(&payload);
let crc = crate::nomad_elrs::NomadHeadTracker::mavlink_crc16(&pkt[1..], 124);
pkt.extend_from_slice(&crc.to_le_bytes());
TelemetryReceiver::parse_datagram(&pkt, &state);
let st = state.lock();
assert_eq!(st.packets_received, 1);
assert!((st.battery_voltage_v - 15.2).abs() < 0.01);
assert!((st.battery_current_a - 4.5).abs() < 0.01);
assert_eq!(st.battery_remaining_pct, 0);
// Auto-détection 4S sur 15.2 V (3.80 V/cell)
assert_eq!(st.effective_cells(0), 4);
assert!((st.cell_voltage_v(0).unwrap() - 3.8).abs() < 0.01);
}
#[test]
fn test_crsf_gps_and_flight_mode_and_lipo_autodetect() {
let state = Arc::new(Mutex::new(TelemetryState::default()));
// CRSF GPS (0x02) : lat=48.8566, lon=2.3522, speed=36.0 km/h (360), hdg=90.0° (9000), alt=1150 (150m), sats=11
let mut gps = [0u8; 19];
gps[0] = 0xC8;
gps[1] = 17; // type(1) + payload(15) + crc(1)
gps[2] = 0x02;
gps[3..7].copy_from_slice(&488_566_000i32.to_be_bytes());
gps[7..11].copy_from_slice(&23_522_000i32.to_be_bytes());
gps[11..13].copy_from_slice(&360u16.to_be_bytes());
gps[13..15].copy_from_slice(&9000u16.to_be_bytes());
gps[15..17].copy_from_slice(&1150u16.to_be_bytes());
gps[17] = 11;
gps[18] = crate::nomad_elrs::NomadHeadTracker::crc8_dvb_s2(&gps[2..18]);
TelemetryReceiver::parse_datagram(&gps, &state);
// CRSF FLIGHT_MODE (0x21) : "ACRO\0"
let mut fm = [0u8; 9];
fm[0] = 0xC8;
fm[1] = 7; // type(1) + payload(5) + crc(1)
fm[2] = 0x21;
fm[3..8].copy_from_slice(b"ACRO\0");
fm[8] = crate::nomad_elrs::NomadHeadTracker::crc8_dvb_s2(&fm[2..8]);
TelemetryReceiver::parse_datagram(&fm, &state);
let mut st = state.lock();
assert!(st.gps_fix_valid);
assert_eq!(st.gps_sats, 11);
assert!((st.gps_lat_deg - 48.8566).abs() < 1e-4);
assert!((st.groundspeed_ms - 10.0).abs() < 0.05);
assert!((st.altitude_m - 150.0).abs() < 0.1);
assert_eq!(st.flight_mode, "ACRO");
// LiPo 3S critique (9.6 V -> 3.20 V/cell < 3.30)
st.battery_cells_detected = 0;
st.update_battery_voltage(12.2);
assert_eq!(st.effective_cells(0), 3);
st.update_battery_voltage(9.6);
assert!(st.is_battery_critical(0, 3.3));
}
#[test]
fn test_gps_home_lock_haversine_bearing_and_srt_caption() {
let mut st = TelemetryState {
packets_received: 1,
last_update: Some(std::time::Instant::now()),
link_quality_pct: 98,
rssi_dbm: -58,
gps_lat_deg: 48.8566,
gps_lon_deg: 2.3522,
gps_sats: 10,
gps_fix_valid: true,
..Default::default()
};
st.update_battery_voltage(15.6);
// Ne verrouille pas tant que désarmé
st.maybe_lock_home(false);
assert!(st.home_lat_deg.is_none());
// Verrouille au premier armement avec fix >= 6 sats
st.maybe_lock_home(true);
assert_eq!(st.home_lat_deg, Some(48.8566));
// Déplacement d'environ 111m vers le Sud -> Home doit être au Nord (cap ~0°)
st.gps_lat_deg = 48.8556;
st.drone_heading_deg = 90.0; // Cap Est -> Home est à gauche (-90°)
let (dist_m, rel_deg) = st.home_vector().expect("home_vector valide");
assert!((dist_m - 111.2).abs() < 3.0, "dist_m={dist_m}");
assert!((rel_deg - (-90.0)).abs() < 2.0, "rel_deg={rel_deg}");
let cap = st.format_dvr_srt_caption(0, "G2", 60.0, 1.2);
assert!(cap.contains("BAT 15.6V (4S 3.90V/c)"));
assert!(cap.contains("LQ 98%"));
assert!(cap.contains("HOME "));
assert!(cap.contains("VID 60fps"));
}
}
+255 -549
View File
@@ -1,401 +1,8 @@
use super::state::TelemetryState;
use super::StackStr;
use crate::controller::ControlSource;
use crate::g29_bridge::G29State;
use anyhow::Result;
use parking_lot::Mutex;
use std::fmt::Write as FmtWrite;
use std::net::UdpSocket;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::thread;
use std::time::{Duration, Instant};
/// Tampon de formatage rapide sur la pile pour éliminer toute allocation sur le tas dans l'OSD
struct StackStr<const N: usize> {
buf: [u8; N],
len: usize,
}
impl<const N: usize> StackStr<N> {
#[inline]
fn new() -> Self {
Self { buf: [0u8; N], len: 0 }
}
#[inline]
fn as_str(&self) -> &str {
std::str::from_utf8(&self.buf[..self.len]).unwrap_or("")
}
}
impl<const N: usize> std::fmt::Write for StackStr<N> {
#[inline]
fn write_str(&mut self, s: &str) -> std::fmt::Result {
let avail = N.saturating_sub(self.len);
let mut to_copy = s.len().min(avail);
while to_copy > 0 && !s.is_char_boundary(to_copy) {
to_copy -= 1;
}
self.buf[self.len..self.len + to_copy].copy_from_slice(&s.as_bytes()[..to_copy]);
self.len += to_copy;
Ok(())
}
}
/// É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,
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,
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,
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: 100,
rssi_dbm: -50,
packets_received: 0,
last_update: None,
terrain_roughness: 0,
prev_pitch_rad: None,
prev_roll_rad: None,
last_attitude_update: None,
}
}
}
impl TelemetryState {
/// 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
}
}
}
/// Récepteur UDP non-bloquant décodant les trames MAVLink v1/v2 (OpenIPC) et CRSF (ELRS)
pub struct TelemetryReceiver {
state: Arc<Mutex<TelemetryState>>,
stop_flag: Arc<AtomicBool>,
worker: Option<thread::JoinHandle<()>>,
}
impl TelemetryReceiver {
#[allow(dead_code)]
pub fn start(bind_ip: &str, port: u16) -> Result<Self> {
Self::start_with_state(
bind_ip,
port,
Arc::new(Mutex::new(TelemetryState::default())),
Vec::new(),
)
}
pub fn start_with_state(
bind_ip: &str,
port: u16,
state: Arc<Mutex<TelemetryState>>,
allowed_peers: Vec<std::net::IpAddr>,
) -> Result<Self> {
let addr = format!("{}:{}", bind_ip, port);
let socket = UdpSocket::bind(&addr).map_err(|e| {
log::error!(
"[Télémétrie OSD] Impossible d'écouter sur UDP {} (port déjà utilisé ou IP invalide) : {}",
addr,
e
);
e
})?;
socket.set_read_timeout(Some(Duration::from_millis(100)))?;
log::info!(
"[Télémétrie OSD] Récepteur MAVLink / CRSF en écoute sur UDP {} (pairs autorisés: {:?})",
addr,
allowed_peers
);
let state_clone = Arc::clone(&state);
let stop_flag = Arc::new(AtomicBool::new(false));
let stop_clone = Arc::clone(&stop_flag);
let worker = thread::Builder::new()
.name("telemetry-udp-rx".into())
.spawn(move || {
let mut buf = [0u8; 1024];
let mut last_reject_log = Instant::now() - Duration::from_secs(10);
while !stop_clone.load(Ordering::Acquire) {
if let Ok((len, src)) = socket.recv_from(&mut buf) {
if !src.ip().is_loopback()
&& !allowed_peers.is_empty()
&& !allowed_peers.contains(&src.ip())
{
if last_reject_log.elapsed() >= Duration::from_secs(5) {
log::warn!(
"[Télémétrie OSD] Paquet UDP rejeté depuis IP non autorisée : {}",
src
);
last_reject_log = Instant::now();
}
continue;
}
Self::parse_datagram(&buf[..len], &state_clone);
}
}
log::info!("[Télémétrie OSD] Thread d'écoute UDP arrêté.");
})?;
Ok(Self {
state,
stop_flag,
worker: Some(worker),
})
}
pub fn state(&self) -> Arc<Mutex<TelemetryState>> {
Arc::clone(&self.state)
}
fn mavlink_crc_extra(msg_id: u32) -> Option<u8> {
match msg_id {
0 => Some(50),
1 => Some(124),
30 => Some(39),
74 => Some(20),
109 => Some(185),
_ => None,
}
}
pub fn parse_datagram(data: &[u8], state: &Arc<Mutex<TelemetryState>>) {
let mut i = 0;
while i < data.len() {
match data[i] {
0xFE if i + 8 <= data.len() => {
let payload_len = data[i + 1] as usize;
let total_len = 6 + payload_len + 2;
if i + total_len <= data.len() {
let msg_id = data[i + 5] as u32;
if let Some(extra) = Self::mavlink_crc_extra(msg_id) {
let crc_calc = crate::nomad_elrs::NomadHeadTracker::mavlink_crc16(
&data[i + 1..i + 6 + payload_len],
extra,
);
let crc_pkt = u16::from_le_bytes([
data[i + 6 + payload_len],
data[i + 7 + payload_len],
]);
if crc_calc == crc_pkt {
let payload = &data[i + 6..i + 6 + payload_len];
Self::handle_mavlink_payload(msg_id, payload, state);
i += total_len;
continue;
}
}
}
}
0xFD if i + 12 <= data.len() => {
let payload_len = data[i + 1] as usize;
let incompat_flags = data[i + 2];
let sig_len = if (incompat_flags & 0x01) != 0 { 13 } else { 0 };
let total_len = 10 + payload_len + 2 + sig_len;
if i + total_len <= data.len() {
let msg_id = (data[i + 7] as u32)
| ((data[i + 8] as u32) << 8)
| ((data[i + 9] as u32) << 16);
if let Some(extra) = Self::mavlink_crc_extra(msg_id) {
let crc_calc = crate::nomad_elrs::NomadHeadTracker::mavlink_crc16(
&data[i + 1..i + 10 + payload_len],
extra,
);
let crc_pkt = u16::from_le_bytes([
data[i + 10 + payload_len],
data[i + 11 + payload_len],
]);
if crc_calc == crc_pkt {
let payload = &data[i + 10..i + 10 + payload_len];
Self::handle_mavlink_payload(msg_id, payload, state);
i += total_len;
continue;
}
}
}
}
0xC8 | 0xEA | 0xEE if i + 4 <= data.len() => {
let frame_len = data[i + 1] as usize;
if frame_len >= 2 && frame_len <= 62 && i + 2 + frame_len <= data.len() {
let crc_idx = i + 2 + frame_len - 1;
let expected_crc = crate::nomad_elrs::NomadHeadTracker::crc8_dvb_s2(
&data[i + 2..crc_idx],
);
if data[crc_idx] == expected_crc {
let frame_type = data[i + 2];
let payload = &data[i + 3..crc_idx];
Self::handle_crsf_payload(frame_type, payload, state);
i += 2 + frame_len;
continue;
}
}
}
_ => {}
}
i += 1;
}
}
fn handle_mavlink_payload(msg_id: u32, payload: &[u8], state: &Arc<Mutex<TelemetryState>>) {
let mut st = state.lock();
st.packets_received = st.packets_received.wrapping_add(1);
st.last_update = Some(Instant::now());
match msg_id {
1 if payload.len() >= 31 => {
let voltage_mv = u16::from_le_bytes([payload[14], payload[15]]);
let current_ca = i16::from_le_bytes([payload[16], payload[17]]);
let remaining = payload[30] as i8;
if voltage_mv != u16::MAX {
st.battery_voltage_v = voltage_mv as f32 / 1000.0;
}
if current_ca != -1 {
st.battery_current_a = current_ca as f32 / 100.0;
}
st.battery_remaining_pct = remaining;
}
30 if payload.len() >= 16 => {
st.drone_roll_rad = f32::from_le_bytes([payload[4], payload[5], payload[6], payload[7]]);
st.drone_pitch_rad = f32::from_le_bytes([payload[8], payload[9], payload[10], payload[11]]);
let yaw_rad = f32::from_le_bytes([payload[12], payload[13], payload[14], payload[15]]);
st.drone_heading_deg = yaw_rad.to_degrees().rem_euclid(360.0);
let pitch = st.drone_pitch_rad;
let roll = st.drone_roll_rad;
st.update_attitude_roughness(pitch, roll);
}
74 if payload.len() >= 20 => {
st.groundspeed_ms = f32::from_le_bytes([payload[4], payload[5], payload[6], payload[7]]);
st.altitude_m = f32::from_le_bytes([payload[8], payload[9], payload[10], payload[11]]);
st.climb_ms = f32::from_le_bytes([payload[12], payload[13], payload[14], payload[15]]);
let heading = i16::from_le_bytes([payload[16], payload[17]]);
st.throttle_pct = u16::from_le_bytes([payload[18], payload[19]]);
if (0..=360).contains(&heading) {
st.drone_heading_deg = heading as f32;
}
}
109 if payload.len() >= 9 => {
let rssi = payload[4];
st.link_quality_pct = rssi.min(100);
st.rssi_dbm = (payload[5] as i8).min(-10);
}
_ => {}
}
}
fn handle_crsf_payload(frame_type: u8, payload: &[u8], state: &Arc<Mutex<TelemetryState>>) {
let mut st = state.lock();
st.packets_received = st.packets_received.wrapping_add(1);
st.last_update = Some(Instant::now());
match frame_type {
0x08 if payload.len() >= 8 => {
let mv_div_100 = u16::from_be_bytes([payload[0], payload[1]]);
let ma_div_100 = u16::from_be_bytes([payload[2], payload[3]]);
st.battery_voltage_v = mv_div_100 as f32 / 10.0;
st.battery_current_a = ma_div_100 as f32 / 10.0;
st.battery_remaining_pct = payload[7] as i8;
}
0x14 if payload.len() >= 10 => {
let uplink_rssi_1 = payload[0] as i8;
let uplink_lq = payload[2];
st.rssi_dbm = -uplink_rssi_1.abs();
st.link_quality_pct = uplink_lq;
}
0x1E if payload.len() >= 6 => {
let pitch_10000 = i16::from_be_bytes([payload[0], payload[1]]);
let roll_10000 = i16::from_be_bytes([payload[2], payload[3]]);
let yaw_10000 = i16::from_be_bytes([payload[4], payload[5]]);
st.drone_pitch_rad = pitch_10000 as f32 / 10000.0;
st.drone_roll_rad = roll_10000 as f32 / 10000.0;
st.drone_heading_deg = (yaw_10000 as f32 / 10000.0).to_degrees().rem_euclid(360.0);
let pitch = st.drone_pitch_rad;
let roll = st.drone_roll_rad;
st.update_attitude_roughness(pitch, roll);
}
_ => {}
}
}
}
impl Drop for TelemetryReceiver {
fn drop(&mut self) {
self.stop_flag.store(true, Ordering::Release);
if let Some(handle) = self.worker.take() {
let _ = handle.join();
}
}
}
/// Pages du Menu Minimaliste VR intégré à l'OSD OpenXR.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
@@ -439,14 +46,52 @@ pub struct VrMenuRenderData {
pub feedback_msg: Option<(&'static str, bool)>,
}
/// Options d'affichage avancées pour le moteur OSD (cellules LiPo, stats vidéo, GPS/Mode).
#[derive(Debug, Clone, Copy)]
pub struct OsdExtraOptions {
pub battery_cells: u8,
pub battery_warn_cell_v: f32,
pub battery_crit_cell_v: f32,
pub show_video_stats: bool,
pub show_gps: bool,
pub video_fps: f32,
pub video_jitter_ms: f32,
pub video_dropped: u64,
}
impl Default for OsdExtraOptions {
fn default() -> Self {
Self {
battery_cells: 0,
battery_warn_cell_v: 3.5,
battery_crit_cell_v: 3.3,
show_video_stats: true,
show_gps: true,
video_fps: 0.0,
video_jitter_ms: 0.0,
video_dropped: 0,
}
}
}
/// Moteur d'incrustation graphique OSD (HUD vectoriel + police bitmap 5x7 avec contour)
pub struct OsdOverlay;
impl OsdOverlay {
fn draw_heading_ribbon(rgba: &mut [u8], width: u32, height: u32, heading_deg: f32, scale: u32) {
fn draw_heading_ribbon(
rgba: &mut [u8],
width: u32,
height: u32,
heading_deg: f32,
y: i32,
scale: u32,
) {
let cx = width as i32 / 2;
let y = 14;
let norm_hdg = heading_deg.rem_euclid(360.0);
let norm_hdg = if heading_deg.is_finite() {
heading_deg.rem_euclid(360.0)
} else {
0.0
};
let card_label = match norm_hdg.round() as i32 {
338..=360 | 0..=22 => "N",
23..=67 => "NE",
@@ -460,7 +105,8 @@ impl OsdOverlay {
};
let mut hdg_buf = StackStr::<32>::new();
let _ = write!(hdg_buf, "{:03}° {}", norm_hdg.round() as i32, card_label);
let hx = cx - ((hdg_buf.as_str().len() as i32 * 6 * scale as i32) / 2);
let char_count = hdg_buf.as_str().chars().count() as i32;
let hx = cx - ((char_count * 6 * scale as i32) / 2);
Self::draw_text(rgba, width, height, hx, y, hdg_buf.as_str(), scale, [210, 230, 255, 240]);
}
@@ -479,6 +125,7 @@ impl OsdOverlay {
projection_label: &str,
dvr_recording: bool,
dvr_elapsed_secs: u64,
extra: &OsdExtraOptions,
) {
let scale = (height / 360).max(2);
@@ -491,30 +138,80 @@ impl OsdOverlay {
Self::draw_text(rgba, width, height, 32, 12, rec_buf.as_str(), scale, [255, 45, 45, 255]);
}
// État de la connexion télémétrie (Attente ou Perte de signal)
// État de la connexion télémétrie (Attente / Perte) OU Ruban de Cap en haut-centre (sans superposition)
let top_center_y = 10;
let top_center_bottom = top_center_y + (7 * scale as i32);
if telem.packets_received == 0 {
let wait_text = "WAIT TELEM";
let wx = (width as i32 / 2) - ((wait_text.len() as i32 * 6 * scale as i32) / 2);
Self::draw_text(rgba, width, height, wx, 8, wait_text, scale, [255, 210, 50, 255]);
} else if let Some(last) = telem.last_update {
if last.elapsed() > Duration::from_millis(2500) {
let lost_text = "! TELEM LOST !";
let lx = (width as i32 / 2) - ((lost_text.len() as i32 * 6 * scale as i32) / 2);
Self::draw_text(rgba, width, height, lx, 8, lost_text, scale, [255, 60, 60, 255]);
}
let wx = (width as i32 / 2) - ((wait_text.chars().count() as i32 * 6 * scale as i32) / 2);
Self::draw_text(
rgba,
width,
height,
wx,
top_center_y,
wait_text,
scale,
[255, 210, 50, 255],
);
} else if !telem.is_live() {
let lost_text = "! TELEM LOST !";
let lx = (width as i32 / 2) - ((lost_text.chars().count() as i32 * 6 * scale as i32) / 2);
Self::draw_text(
rgba,
width,
height,
lx,
top_center_y,
lost_text,
scale,
[255, 60, 60, 255],
);
} else {
Self::draw_heading_ribbon(
rgba,
width,
height,
telem.drone_heading_deg,
top_center_y,
scale,
);
}
// Ruban de Cap / Boussole en haut
Self::draw_heading_ribbon(rgba, width, height, telem.drone_heading_deg, scale);
let bat_color = if telem.battery_voltage_v > 0.1 && telem.battery_voltage_v < 14.0 {
[255, 65, 65, 255]
let cell_v_opt = telem.cell_voltage_v(extra.battery_cells);
let eff_cells = telem.effective_cells(extra.battery_cells);
let bat_color = if let Some(cv) = cell_v_opt {
if cv < extra.battery_crit_cell_v {
[255, 65, 65, 255]
} else if cv < extra.battery_warn_cell_v {
[255, 200, 45, 255]
} else {
[90, 255, 130, 255]
}
} else {
[90, 255, 130, 255]
[170, 190, 210, 255]
};
let mut bat_buf = StackStr::<48>::new();
if telem.battery_remaining_pct >= 0 {
let mut bat_buf = StackStr::<64>::new();
if let Some(cv) = cell_v_opt {
if telem.battery_remaining_pct >= 0 {
let _ = write!(
bat_buf,
"BAT {:4.1}V ({}S {:3.2}V/C) {:4.1}A {:3}%",
telem.battery_voltage_v,
eff_cells,
cv,
telem.battery_current_a,
telem.battery_remaining_pct
);
} else {
let _ = write!(
bat_buf,
"BAT {:4.1}V ({}S {:3.2}V/C) {:4.1}A",
telem.battery_voltage_v, eff_cells, cv, telem.battery_current_a
);
}
} else if telem.battery_remaining_pct >= 0 {
let _ = write!(
bat_buf,
"BAT {:4.1}V {:4.1}A {:3}%",
@@ -529,17 +226,75 @@ impl OsdOverlay {
}
Self::draw_text(rgba, width, height, 32, 28, bat_buf.as_str(), scale, bat_color);
let lq_color = if telem.link_quality_pct < 70 {
// Ligne GPS / Mode de vol CRSF + Flèche Home & distance (si activée et disponible)
if extra.show_gps && (!telem.flight_mode.is_empty() || telem.gps_sats > 0) {
let mut gps_buf = StackStr::<64>::new();
if !telem.flight_mode.is_empty() && telem.gps_sats > 0 {
let _ = write!(gps_buf, "MODE {} SAT {}", telem.flight_mode, telem.gps_sats);
} else if !telem.flight_mode.is_empty() {
let _ = write!(gps_buf, "MODE {}", telem.flight_mode);
} else {
let _ = write!(gps_buf, "GPS SAT {}", telem.gps_sats);
}
let gps_y = 28 + (9 * scale as i32);
Self::draw_text(rgba, width, height, 32, gps_y, gps_buf.as_str(), scale, [190, 225, 255, 245]);
if let Some((dist_m, rel_deg)) = telem.home_vector() {
let home_y = gps_y + (9 * scale as i32);
let arrow_cx = 32 + 6 * scale as i32;
let arrow_cy = home_y + 4 * scale as i32;
Self::draw_home_arrow(rgba, width, height, arrow_cx, arrow_cy, rel_deg, scale);
let mut home_buf = StackStr::<32>::new();
if dist_m >= 1000.0 {
let _ = write!(home_buf, "HOME {:4.2}KM", dist_m / 1000.0);
} else {
let _ = write!(home_buf, "HOME {:4.0}M", dist_m);
}
Self::draw_text(
rgba,
width,
height,
arrow_cx + 10 * scale as i32,
home_y,
home_buf.as_str(),
scale,
[120, 255, 190, 250],
);
}
}
let lq_color = if !telem.is_live() || telem.link_quality_pct < 50 {
[255, 65, 65, 255]
} else if telem.link_quality_pct < 70 {
[255, 180, 40, 255]
} else {
[100, 225, 255, 255]
};
let mut link_buf = StackStr::<48>::new();
let _ = write!(link_buf, "LQ {:3}% RSSI {:3}DBM", telem.link_quality_pct, telem.rssi_dbm);
let right_x = width.saturating_sub((link_buf.as_str().len() as u32) * 6 * scale + 32) as i32;
let right_x = width.saturating_sub((link_buf.as_str().chars().count() as u32) * 6 * scale + 32) as i32;
Self::draw_text(rgba, width, height, right_x, 28, link_buf.as_str(), scale, lq_color);
Self::draw_gimbal_radar(
// Ligne compacte de métriques lien vidéo (FPS / Jitter / Drops)
if extra.show_video_stats && extra.video_fps > 0.5 {
let mut vid_buf = StackStr::<48>::new();
let _ = write!(
vid_buf,
"VID {:2.0}FPS JIT {:3.1}MS DRP {}",
extra.video_fps, extra.video_jitter_ms, extra.video_dropped
);
let vx = width.saturating_sub((vid_buf.as_str().chars().count() as u32) * 6 * scale + 32) as i32;
let vy = 28 + (9 * scale as i32);
let vid_col = if extra.video_jitter_ms > 8.0 {
[255, 190, 60, 245]
} else {
[150, 220, 200, 240]
};
Self::draw_text(rgba, width, height, vx, vy, vid_buf.as_str(), scale, vid_col);
}
let radar_top = top_center_bottom + 6;
let radar_bottom = Self::draw_gimbal_radar(
rgba,
width,
height,
@@ -547,6 +302,7 @@ impl OsdOverlay {
head_tilt_deg,
max_pan_deg,
max_tilt_deg,
radar_top,
scale,
);
let mut ht_buf = StackStr::<64>::new();
@@ -555,13 +311,13 @@ impl OsdOverlay {
"HT PAN {:+4.0} TILT {:+4.0} ROLL {:+4.0}",
head_pan_deg, head_tilt_deg, head_roll_deg
);
let ht_x = (width as i32 / 2) - ((ht_buf.as_str().len() as i32 * 6 * scale as i32) / 2);
let ht_x = (width as i32 / 2) - ((ht_buf.as_str().chars().count() as i32 * 6 * scale as i32) / 2);
Self::draw_text(
rgba,
width,
height,
ht_x,
28 + 46 * scale as i32 / 2,
radar_bottom + 6,
ht_buf.as_str(),
scale,
[230, 240, 255, 255],
@@ -960,6 +716,7 @@ impl OsdOverlay {
}
}
#[allow(clippy::too_many_arguments)]
fn darken_rect(
rgba: &mut [u8],
width: u32,
@@ -978,16 +735,25 @@ impl OsdOverlay {
let row_start = (row * width + x0) as usize * 4;
let row_end = (row * width + x1) as usize * 4;
if row_end <= rgba.len() {
for px in rgba[row_start..row_end].chunks_exact_mut(4) {
px[0] = (px[0] >> 2).saturating_add(tint[0]);
px[1] = (px[1] >> 2).saturating_add(tint[1]);
px[2] = (px[2] >> 2).saturating_add(tint[2]);
px[3] = 255;
for px in rgba[row_start..row_end].as_chunks_mut::<4>().0 {
if px[3] == 0 {
// Sur couche OpenXR transparente dédiée : fond verre fumé semi-transparent
px[0] = tint[0];
px[1] = tint[1];
px[2] = tint[2];
px[3] = 215;
} else {
px[0] = (px[0] >> 2).saturating_add(tint[0]);
px[1] = (px[1] >> 2).saturating_add(tint[1]);
px[2] = (px[2] >> 2).saturating_add(tint[2]);
px[3] = 255;
}
}
}
}
}
#[allow(clippy::too_many_arguments)]
fn fill_rect(
rgba: &mut [u8],
width: u32,
@@ -1006,7 +772,7 @@ impl OsdOverlay {
let row_start = (row * width + x0) as usize * 4;
let row_end = (row * width + x1) as usize * 4;
if row_end <= rgba.len() {
for px in rgba[row_start..row_end].chunks_exact_mut(4) {
for px in rgba[row_start..row_end].as_chunks_mut::<4>().0 {
px.copy_from_slice(&color);
}
}
@@ -1073,6 +839,39 @@ impl OsdOverlay {
Self::draw_text(rgba, width, height, pedal_x, gear_y, pedal_buf.as_str(), scale, [230, 235, 245, 255]);
}
/// Dessine une flèche vectorielle directionnelle vers le point Home (0° = haut, +90° = droite).
fn draw_home_arrow(
rgba: &mut [u8],
width: u32,
height: u32,
cx: i32,
cy: i32,
rel_deg: f32,
scale: u32,
) {
let r = (5 * scale as i32) as f32;
let rad = rel_deg.to_radians();
let sin_a = rad.sin();
let cos_a = rad.cos();
// Pointe de flèche (0° = vers le haut -> dx=sin, dy=-cos)
let tip_x = cx + (sin_a * r).round() as i32;
let tip_y = cy - (cos_a * r).round() as i32;
let tail_x = cx - (sin_a * r * 0.8).round() as i32;
let tail_y = cy + (cos_a * r * 0.8).round() as i32;
// Deux ailettes à ±140°
let wing_l = (rel_deg - 140.0).to_radians();
let wing_r = (rel_deg + 140.0).to_radians();
let lx = cx + (wing_l.sin() * r * 0.75).round() as i32;
let ly = cy - (wing_l.cos() * r * 0.75).round() as i32;
let rx = cx + (wing_r.sin() * r * 0.75).round() as i32;
let ry = cy - (wing_r.cos() * r * 0.75).round() as i32;
let col = [100, 255, 180, 255];
Self::draw_line(rgba, width, height, tail_x, tail_y, tip_x, tip_y, col);
Self::draw_line(rgba, width, height, tip_x, tip_y, lx, ly, col);
Self::draw_line(rgba, width, height, tip_x, tip_y, rx, ry, col);
}
#[allow(clippy::too_many_arguments)]
fn draw_gimbal_radar(
rgba: &mut [u8],
@@ -1082,12 +881,13 @@ impl OsdOverlay {
tilt_deg: f32,
max_pan: f32,
max_tilt: f32,
top_y: i32,
scale: u32,
) {
) -> i32 {
let box_w = (44 * scale) as i32;
let box_h = (24 * scale) as i32;
let cx = width as i32 / 2;
let cy = 22 + box_h / 2;
let cy = top_y + box_h / 2;
Self::draw_rect_outline(
rgba,
@@ -1134,6 +934,7 @@ impl OsdOverlay {
}
}
}
top_y + box_h
}
fn draw_artificial_horizon(
@@ -1143,9 +944,14 @@ impl OsdOverlay {
roll_rad: f32,
pitch_rad: f32,
) {
if !roll_rad.is_finite() || !pitch_rad.is_finite() {
return;
}
let cx = width as i32 / 2;
let cy = height as i32 / 2;
let pitch_offset = (pitch_rad.to_degrees() * (height as f32 / 70.0)) as i32;
let max_offset = height as i32;
let pitch_offset = ((pitch_rad.to_degrees() * (height as f32 / 70.0)) as i32)
.clamp(-max_offset, max_offset);
let cos_r = (-roll_rad).cos();
let sin_r = (-roll_rad).sin();
@@ -1162,6 +968,7 @@ impl OsdOverlay {
}
}
#[allow(clippy::too_many_arguments)]
fn draw_rect_outline(
rgba: &mut [u8],
width: u32,
@@ -1178,6 +985,7 @@ impl OsdOverlay {
Self::draw_line(rgba, width, height, x + w, y, x + w, y + h, color);
}
#[allow(clippy::too_many_arguments)]
fn draw_line(
rgba: &mut [u8],
width: u32,
@@ -1188,25 +996,33 @@ impl OsdOverlay {
y1: i32,
color: [u8; 4],
) {
let dx = (x1 - x0).abs();
let w = width as i32;
let h = height as i32;
// Rejet rapide hors-cadre (évite toute boucle longue sur coordonnées extrêmes)
if (x0 < 0 && x1 < 0) || (x0 >= w && x1 >= w) || (y0 < 0 && y1 < 0) || (y0 >= h && y1 >= h)
{
return;
}
let dx = x1.saturating_sub(x0).saturating_abs();
let sx = if x0 < x1 { 1 } else { -1 };
let dy = -(y1 - y0).abs();
let dy = -y1.saturating_sub(y0).saturating_abs();
let sy = if y0 < y1 { 1 } else { -1 };
let mut err = dx + dy;
let mut err = dx.saturating_add(dy);
let max_steps = (w + h).saturating_mul(2).max(16) as u32;
loop {
for _ in 0..max_steps {
Self::put_pixel(rgba, width, height, x0, y0, color);
if x0 == x1 && y0 == y1 {
break;
}
let e2 = 2 * err;
let e2 = err.saturating_mul(2);
if e2 >= dy {
err += dy;
x0 += sx;
err = err.saturating_add(dy);
x0 = x0.saturating_add(sx);
}
if e2 <= dx {
err += dx;
y0 += sy;
err = err.saturating_add(dx);
y0 = y0.saturating_add(sy);
}
}
}
@@ -1326,113 +1142,3 @@ impl OsdOverlay {
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_stack_str_utf8_boundary_truncation() {
let mut s = StackStr::<3>::new();
let _ = write!(s, "12°");
assert_eq!(s.as_str(), "12");
let mut s4 = StackStr::<4>::new();
let _ = write!(s4, "12°");
assert_eq!(s4.as_str(), "12°");
}
#[test]
fn test_render_vr_menu_bounds_and_output() {
let mut rgba = vec![100u8; 1280 * 720 * 4];
let mut menu = VrMenuRenderData {
page: VrMenuPage::Main,
selected_idx: 0,
control_source: ControlSource::SteamController,
head_tracking_on: true,
telemetry_osd_on: true,
projection_label: "DOME 140",
screen_distance_m: 1.6,
lens_k1: -0.14,
camera_fov_deg: 140.0,
dvr_recording: false,
gear_3_max: 1220,
vibration_pct: 100,
wifi_channel: 161,
quit_confirm_pending: false,
feedback_msg: Some(("TARE HT OK", false)),
};
OsdOverlay::render_vr_menu(&mut rgba, 1280, 720, &menu);
let center_idx = ((720 / 2) * 1280 + (1280 / 2)) * 4;
assert_ne!(&rgba[center_idx..center_idx + 3], &[100, 100, 100]);
menu.page = VrMenuPage::Advanced;
menu.selected_idx = 6;
OsdOverlay::render_vr_menu(&mut rgba, 1280, 720, &menu);
OsdOverlay::render_vr_standby_bar(
&mut rgba,
1280,
720,
false,
ControlSource::G29,
false,
);
}
#[test]
fn test_parse_datagram_crsf_crc_validation() {
let state = Arc::new(Mutex::new(TelemetryState::default()));
// Trame CRSF Battery Sensor (0x08) : 16.8V (168 = 0x00A8), 12.5A (125 = 0x007D), remaining = 75%
let mut frame = [0u8; 12];
frame[0] = 0xC8;
frame[1] = 10; // type(1) + payload(8) + crc(1)
frame[2] = 0x08;
frame[3..5].copy_from_slice(&168u16.to_be_bytes());
frame[5..7].copy_from_slice(&125u16.to_be_bytes());
frame[10] = 75;
frame[11] = crate::nomad_elrs::NomadHeadTracker::crc8_dvb_s2(&frame[2..11]);
// Trame au CRC corrompu : doit être ignorée
let mut bad_frame = frame;
bad_frame[11] ^= 0xFF;
TelemetryReceiver::parse_datagram(&bad_frame, &state);
assert_eq!(state.lock().packets_received, 0);
// Trame valide : doit être acceptée et décodée
TelemetryReceiver::parse_datagram(&frame, &state);
let st = state.lock();
assert_eq!(st.packets_received, 1);
assert!((st.battery_voltage_v - 16.8).abs() < 0.01);
assert!((st.battery_current_a - 12.5).abs() < 0.01);
assert_eq!(st.battery_remaining_pct, 75);
}
#[test]
fn test_crsf_attitude_terrain_roughness() {
let state = Arc::new(Mutex::new(TelemetryState::default()));
let make_att_frame = |pitch_10000: i16, roll_10000: i16| -> [u8; 10] {
let mut f = [0u8; 10];
f[0] = 0xEA;
f[1] = 8; // type(1) + payload(6) + crc(1)
f[2] = 0x1E;
f[3..5].copy_from_slice(&pitch_10000.to_be_bytes());
f[5..7].copy_from_slice(&roll_10000.to_be_bytes());
f[7..9].copy_from_slice(&0i16.to_be_bytes());
f[9] = crate::nomad_elrs::NomadHeadTracker::crc8_dvb_s2(&f[2..9]);
f
};
// Première trame : initialise la référence -> rugosité 0
TelemetryReceiver::parse_datagram(&make_att_frame(0, 0), &state);
assert_eq!(state.lock().effective_terrain_roughness(), 0);
// Micro-bruit sous le seuil de 60 (0.006 rad) -> filtré à 0
TelemetryReceiver::parse_datagram(&make_att_frame(20, 20), &state);
assert_eq!(state.lock().effective_terrain_roughness(), 0);
// Grosse secousse (> 450 -> saturation à 255)
TelemetryReceiver::parse_datagram(&make_att_frame(300, 300), &state);
assert_eq!(state.lock().effective_terrain_roughness(), 255);
}
}
+349
View File
@@ -0,0 +1,349 @@
use super::state::TelemetryState;
use anyhow::Result;
use parking_lot::Mutex;
use std::net::UdpSocket;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::thread;
use std::time::{Duration, Instant};
/// Récepteur UDP non-bloquant décodant les trames MAVLink v1/v2 (OpenIPC) et CRSF (ELRS)
pub struct TelemetryReceiver {
state: Arc<Mutex<TelemetryState>>,
stop_flag: Arc<AtomicBool>,
worker: Option<thread::JoinHandle<()>>,
}
impl TelemetryReceiver {
#[allow(dead_code)]
pub fn start(bind_ip: &str, port: u16) -> Result<Self> {
Self::start_with_state(
bind_ip,
port,
Arc::new(Mutex::new(TelemetryState::default())),
Vec::new(),
)
}
pub fn start_with_state(
bind_ip: &str,
port: u16,
state: Arc<Mutex<TelemetryState>>,
allowed_peers: Vec<std::net::IpAddr>,
) -> Result<Self> {
let addr = format!("{}:{}", bind_ip, port);
let socket = UdpSocket::bind(&addr).map_err(|e| {
log::error!(
"[Télémétrie OSD] Impossible d'écouter sur UDP {} (port déjà utilisé ou IP invalide) : {}",
addr,
e
);
e
})?;
socket.set_read_timeout(Some(Duration::from_millis(100)))?;
log::info!(
"[Télémétrie OSD] Récepteur MAVLink / CRSF en écoute sur UDP {} (pairs autorisés: {:?})",
addr,
allowed_peers
);
let state_clone = Arc::clone(&state);
let stop_flag = Arc::new(AtomicBool::new(false));
let stop_clone = Arc::clone(&stop_flag);
let worker = thread::Builder::new()
.name("telemetry-udp-rx".into())
.spawn(move || {
let mut buf = [0u8; 1024];
let mut last_reject_log: Option<Instant> = None;
while !stop_clone.load(Ordering::Acquire) {
if let Ok((len, src)) = socket.recv_from(&mut buf) {
if !src.ip().is_loopback()
&& !allowed_peers.is_empty()
&& !allowed_peers.contains(&src.ip())
{
if last_reject_log
.is_none_or(|t| t.elapsed() >= Duration::from_secs(5))
{
log::warn!(
"[Télémétrie OSD] Paquet UDP rejeté depuis IP non autorisée : {}",
src
);
last_reject_log = Some(Instant::now());
}
continue;
}
Self::parse_datagram(&buf[..len], &state_clone);
}
}
log::info!("[Télémétrie OSD] Thread d'écoute UDP arrêté.");
})?;
Ok(Self {
state,
stop_flag,
worker: Some(worker),
})
}
pub fn state(&self) -> Arc<Mutex<TelemetryState>> {
Arc::clone(&self.state)
}
fn mavlink_crc_extra(msg_id: u32) -> Option<u8> {
match msg_id {
0 => Some(50),
1 => Some(124),
30 => Some(39),
74 => Some(20),
109 => Some(185),
_ => None,
}
}
pub fn parse_datagram(data: &[u8], state: &Arc<Mutex<TelemetryState>>) {
let mut i = 0;
while i < data.len() {
match data[i] {
0xFE if i + 8 <= data.len() => {
let payload_len = data[i + 1] as usize;
let total_len = 6 + payload_len + 2;
if i + total_len <= data.len() {
let msg_id = data[i + 5] as u32;
if let Some(extra) = Self::mavlink_crc_extra(msg_id) {
let crc_calc = crate::nomad_elrs::NomadHeadTracker::mavlink_crc16(
&data[i + 1..i + 6 + payload_len],
extra,
);
let crc_pkt = u16::from_le_bytes([
data[i + 6 + payload_len],
data[i + 7 + payload_len],
]);
if crc_calc == crc_pkt {
let payload = &data[i + 6..i + 6 + payload_len];
Self::handle_mavlink_payload(msg_id, payload, state);
i += total_len;
continue;
}
} else if i + total_len == data.len()
|| matches!(data[i + total_len], 0xFE | 0xFD | 0xC8 | 0xEA | 0xEE)
{
// Sauter la trame MAVLink v1 non gérée sans scanner son payload pour des faux positifs CRSF
i += total_len;
continue;
}
}
}
0xFD if i + 12 <= data.len() => {
let payload_len = data[i + 1] as usize;
let incompat_flags = data[i + 2];
let sig_len = if (incompat_flags & 0x01) != 0 { 13 } else { 0 };
let total_len = 10 + payload_len + 2 + sig_len;
if i + total_len <= data.len() {
let msg_id = (data[i + 7] as u32)
| ((data[i + 8] as u32) << 8)
| ((data[i + 9] as u32) << 16);
if let Some(extra) = Self::mavlink_crc_extra(msg_id) {
let crc_calc = crate::nomad_elrs::NomadHeadTracker::mavlink_crc16(
&data[i + 1..i + 10 + payload_len],
extra,
);
let crc_pkt = u16::from_le_bytes([
data[i + 10 + payload_len],
data[i + 11 + payload_len],
]);
if crc_calc == crc_pkt {
let payload = &data[i + 10..i + 10 + payload_len];
Self::handle_mavlink_payload(msg_id, payload, state);
i += total_len;
continue;
}
} else if i + total_len == data.len()
|| matches!(data[i + total_len], 0xFE | 0xFD | 0xC8 | 0xEA | 0xEE)
{
// Sauter la trame MAVLink v2 non gérée sans scanner son payload pour des faux positifs CRSF
i += total_len;
continue;
}
}
}
0xC8 | 0xEA | 0xEE if i + 4 <= data.len() => {
let frame_len = data[i + 1] as usize;
if (2..=62).contains(&frame_len) && i + 2 + frame_len <= data.len() {
let crc_idx = i + 2 + frame_len - 1;
let expected_crc = crate::nomad_elrs::NomadHeadTracker::crc8_dvb_s2(
&data[i + 2..crc_idx],
);
if data[crc_idx] == expected_crc {
let frame_type = data[i + 2];
let payload = &data[i + 3..crc_idx];
Self::handle_crsf_payload(frame_type, payload, state);
i += 2 + frame_len;
continue;
}
}
}
_ => {}
}
i += 1;
}
}
fn handle_mavlink_payload(msg_id: u32, payload: &[u8], state: &Arc<Mutex<TelemetryState>>) {
// MAVLink v2 tronque les octets nuls de fin : zero-padding dans un buffer fixe avant décodage.
let mut padded = [0u8; 255];
let copy_len = payload.len().min(padded.len());
padded[..copy_len].copy_from_slice(&payload[..copy_len]);
let mut st = state.lock();
st.packets_received = st.packets_received.wrapping_add(1);
st.last_update = Some(Instant::now());
match msg_id {
1 => {
let voltage_mv = u16::from_le_bytes([padded[14], padded[15]]);
let current_ca = i16::from_le_bytes([padded[16], padded[17]]);
let remaining = padded[30] as i8;
if voltage_mv != u16::MAX {
st.update_battery_voltage(voltage_mv as f32 / 1000.0);
}
if current_ca != -1 {
st.battery_current_a = current_ca as f32 / 100.0;
}
st.battery_remaining_pct = remaining;
}
30 => {
let roll = f32::from_le_bytes([padded[4], padded[5], padded[6], padded[7]]);
let pitch = f32::from_le_bytes([padded[8], padded[9], padded[10], padded[11]]);
let yaw_rad = f32::from_le_bytes([padded[12], padded[13], padded[14], padded[15]]);
if roll.is_finite() && pitch.is_finite() {
let safe_roll = roll.clamp(-std::f32::consts::PI, std::f32::consts::PI);
let safe_pitch = pitch.clamp(-std::f32::consts::PI, std::f32::consts::PI);
st.drone_roll_rad = safe_roll;
st.drone_pitch_rad = safe_pitch;
st.update_attitude_roughness(safe_pitch, safe_roll);
}
if yaw_rad.is_finite() {
st.drone_heading_deg = yaw_rad.to_degrees().rem_euclid(360.0);
}
}
74 => {
let gs = f32::from_le_bytes([padded[4], padded[5], padded[6], padded[7]]);
let alt = f32::from_le_bytes([padded[8], padded[9], padded[10], padded[11]]);
let climb = f32::from_le_bytes([padded[12], padded[13], padded[14], padded[15]]);
let heading = i16::from_le_bytes([padded[16], padded[17]]);
st.throttle_pct = u16::from_le_bytes([padded[18], padded[19]]);
if gs.is_finite() {
st.groundspeed_ms = gs;
}
if alt.is_finite() {
st.altitude_m = alt;
}
if climb.is_finite() {
st.climb_ms = climb;
}
if (0..=360).contains(&heading) {
st.drone_heading_deg = heading as f32;
}
}
109 => {
// MAVLink RADIO_STATUS: 255 = valeur inconnue
let rssi = padded[4];
if rssi != u8::MAX {
st.link_quality_pct = rssi.min(100);
}
let remrssi = padded[5];
if remrssi != u8::MAX {
// Échelle SiK/MAVLink standard (0..254 -> approx dBm) ou magnitude négative
st.rssi_dbm = if remrssi == 0 {
-127
} else {
-((remrssi / 2).min(127) as i8)
};
}
}
_ => {}
}
}
fn handle_crsf_payload(frame_type: u8, payload: &[u8], state: &Arc<Mutex<TelemetryState>>) {
let mut st = state.lock();
st.packets_received = st.packets_received.wrapping_add(1);
st.last_update = Some(Instant::now());
match frame_type {
0x02 if payload.len() >= 15 => {
// CRSF GPS : lat/lon (i32 * 1e-7), groundspeed (u16 * 0.1 km/h), heading (u16 * 0.01 deg),
// altitude (u16 - 1000 m), satellites (u8)
let lat_raw = i32::from_be_bytes([payload[0], payload[1], payload[2], payload[3]]);
let lon_raw = i32::from_be_bytes([payload[4], payload[5], payload[6], payload[7]]);
let gs_10kmh = u16::from_be_bytes([payload[8], payload[9]]);
let hdg_100 = u16::from_be_bytes([payload[10], payload[11]]);
let alt_off = u16::from_be_bytes([payload[12], payload[13]]);
let sats = payload[14];
st.gps_lat_deg = lat_raw as f64 / 1e7;
st.gps_lon_deg = lon_raw as f64 / 1e7;
st.gps_sats = sats;
st.gps_alt_m = alt_off as f32 - 1000.0;
st.gps_fix_valid = sats >= 4 && (lat_raw != 0 || lon_raw != 0);
st.groundspeed_ms = (gs_10kmh as f32 * 0.1) / 3.6;
st.altitude_m = st.gps_alt_m;
if hdg_100 <= 36000 {
st.drone_heading_deg = hdg_100 as f32 / 100.0;
}
}
0x08 if payload.len() >= 8 => {
let mv_div_100 = u16::from_be_bytes([payload[0], payload[1]]);
let ma_div_100 = u16::from_be_bytes([payload[2], payload[3]]);
st.update_battery_voltage(mv_div_100 as f32 / 10.0);
st.battery_current_a = ma_div_100 as f32 / 10.0;
st.battery_remaining_pct = payload[7] as i8;
}
0x14 if payload.len() >= 10 => {
// CRSF LINK_STATISTICS : payload[0]=RSSI1 (u8 magnitude), payload[1]=RSSI2,
// payload[2]=LQ (0..100), payload[4]=active_antenna (0 ou 1).
// Évite le panic overflow `i8::MIN.abs()` lorsque RSSI == 128 dBm (0x80).
let active_ant = payload[4];
let raw_rssi = if active_ant == 1 && payload[1] > 0 {
payload[1]
} else {
payload[0]
};
st.rssi_dbm = -(raw_rssi.min(127) as i8);
st.link_quality_pct = payload[2].min(100);
}
0x1E if payload.len() >= 6 => {
let pitch_10000 = i16::from_be_bytes([payload[0], payload[1]]);
let roll_10000 = i16::from_be_bytes([payload[2], payload[3]]);
let yaw_10000 = i16::from_be_bytes([payload[4], payload[5]]);
st.drone_pitch_rad = pitch_10000 as f32 / 10000.0;
st.drone_roll_rad = roll_10000 as f32 / 10000.0;
st.drone_heading_deg = (yaw_10000 as f32 / 10000.0).to_degrees().rem_euclid(360.0);
let pitch = st.drone_pitch_rad;
let roll = st.drone_roll_rad;
st.update_attitude_roughness(pitch, roll);
}
0x21 if !payload.is_empty() => {
// CRSF FLIGHT_MODE : chaîne ASCII terminée par '\0'
let end = payload.iter().position(|&b| b == 0).unwrap_or(payload.len());
if let Ok(mode_str) = std::str::from_utf8(&payload[..end]) {
let trimmed = mode_str.trim();
if !trimmed.is_empty() && trimmed.len() <= 24 {
st.flight_mode = trimmed.to_string();
}
}
}
_ => {}
}
}
}
impl Drop for TelemetryReceiver {
fn drop(&mut self) {
self.stop_flag.store(true, Ordering::Release);
if let Some(handle) = self.worker.take() {
let _ = handle.join();
}
}
}
+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
}
+279
View File
@@ -0,0 +1,279 @@
use super::theme::*;
use super::SteamFrameGpuiApp;
use gpui::{div, img, prelude::*, rgb, rgba, Context, IntoElement};
impl SteamFrameGpuiApp {
pub(super) fn render_cockpit_view(&self, cx: &mut Context<Self>) -> impl IntoElement {
div()
.flex()
.flex_col()
.size_full()
.min_h_0()
.min_w_0()
.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 (cadrage proportionnel intégral sans rognage)
.child(if let Some(ref img_src) = self.current_render_image {
div()
.flex()
.items_center()
.justify_center()
.size_full()
.min_h_0()
.min_w_0()
.child(
img(img_src.clone())
.size_full()
.object_fit(gpui::ObjectFit::Contain),
)
} 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()
.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()
.flex_wrap()
.justify_center()
.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_instant_replay")
.px_2p5()
.py_1()
.bg(rgba(0x0a101abb))
.border_1()
.border_color(if self.replay_buffered_bytes > 0 {
rgb(COLOR_ORANGE)
} else {
rgb(COLOR_BORDER_SUBTLE)
})
.rounded_md()
.text_xs()
.text_color(if self.replay_buffered_bytes > 0 {
rgb(COLOR_ORANGE)
} else {
rgb(COLOR_TEXT_MUTED)
})
.cursor_pointer()
.on_click(cx.listener(|this, _, _, cx| {
this.controls.request_instant_replay();
cx.notify();
}))
.child(if self.replay_buffered_bytes > 0 {
format!(
"⏮ Replay 30s ({:.1} Mo)",
self.replay_buffered_bytes as f64 / (1024.0 * 1024.0)
)
} else {
"⏮ Replay 30s".to_string()
}),
)
.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)
// -------------------------------------------------------------------------
}
+334
View File
@@ -0,0 +1,334 @@
use super::theme::*;
use super::SteamFrameGpuiApp;
use crate::controller::ControlSource;
use gpui::{div, prelude::*, rgb, Context, IntoElement};
impl SteamFrameGpuiApp {
pub(super) fn render_controller_monitor(&self, cx: &mut Context<Self>) -> impl IntoElement {
let viewed_source = self.monitor_source_override.unwrap_or_else(|| {
if self.active_control_source == ControlSource::G29
&& !self.latest_g29.is_live()
&& self.latest_controller.connected
{
ControlSource::SteamController
} else {
self.active_control_source
}
});
let is_steam_view = viewed_source == ControlSource::SteamController;
let (
is_online,
is_failsafe,
is_armed,
gear,
gear_lbl,
steer_pct,
steer_crsf,
throttle_pct,
throttle_crsf,
brake_pct,
brake_crsf,
clutch_pct,
clutch_crsf,
last_btn,
detail_line,
) = if is_steam_view {
let sc = &self.latest_controller;
let detail = if sc.connected {
format!(
"Périphérique : {} ({}) • Vib {}% (G:{}% / D:{}%) • Trames $RC : {} (Err : {})",
sc.device_name,
sc.device_path,
sc.vibration_pct,
sc.rumble_left_pct,
sc.rumble_right_pct,
sc.packets_sent,
sc.send_errors
)
} else {
"En attente d'un Steam Controller / Gamepad Linux (/dev/hidraw* ou /dev/input/event*)".to_string()
};
(
sc.connected,
!sc.connected,
sc.armed,
sc.gear,
sc.gear_label(),
sc.steering_norm * 100.0,
sc.steer_crsf,
sc.throttle_pct,
sc.throttle_crsf,
sc.brake_pct,
sc.brake_crsf,
sc.clutch_pct,
sc.clutch_crsf,
if sc.last_button.is_empty() {
"Aucun".to_string()
} else {
sc.last_button.clone()
},
detail,
)
} else {
let g = &self.latest_g29;
let live = g.is_live();
let detail = if live {
format!(
"FFB Ressort : {}% • Vibrations : {}% • Paquets UDP reçus : {}",
g.ffb_pct, g.vib_pct, g.packets_received
)
} else {
format!(
"En attente du pont G29 sur UDP :{} (Paquets reçus : {})",
self.cfg.g29_udp_port, g.packets_received
)
};
(
live,
!live || g.failsafe,
g.armed,
g.gear,
g.gear_label(),
g.steering_pct as f32,
g.steer_crsf,
g.throttle_pct,
g.throttle_crsf,
g.brake_pct,
g.brake_crsf,
g.clutch_pct,
g.clutch_crsf,
if g.last_button.is_empty() {
"Aucun".to_string()
} else {
g.last_button.clone()
},
detail,
)
};
let gear_color = match gear {
-1 => COLOR_RED,
0 => COLOR_ORANGE,
1 => COLOR_CYAN,
2 => COLOR_GREEN,
3 => 0xc084fc,
_ => COLOR_TEXT_MUTED,
};
let arm_color = if is_failsafe {
COLOR_RED
} else if is_armed {
COLOR_GREEN
} else {
COLOR_ORANGE
};
let arm_text = if is_failsafe {
"FAILSAFE (CH5: 172)"
} else if is_armed {
"ARMED (CH5: 1811)"
} else {
"SAFE (CH5: 172)"
};
let throttle_color = if gear == -1 {
COLOR_RED
} else if is_armed && gear > 0 {
COLOR_GREEN
} else {
COLOR_ORANGE
};
let rp2350_sync_text = if self.latest_g29.is_live() {
format!("RP2350 : {}", self.latest_g29.remote_source.wire_tag())
} else {
"RP2350 : hors ligne".to_string()
};
let rp2350_sync_color = if !self.latest_g29.is_live() {
COLOR_TEXT_MUTED
} else if self.latest_g29.remote_source == self.active_control_source {
COLOR_GREEN
} else {
COLOR_ORANGE
};
div()
.flex()
.flex_col()
.gap_2()
.p_3()
.rounded_lg()
.bg(rgb(COLOR_BG_DARK))
.border_1()
.border_color(if is_online {
rgb(COLOR_BORDER_ACTIVE)
} else {
rgb(COLOR_BORDER_SUBTLE)
})
// En-tête du moniteur + sélecteur de vue (Auto / G29 / Steam)
.child(
div()
.flex()
.flex_wrap()
.justify_between()
.items_center()
.gap_2()
.child(
div()
.text_xs()
.font_weight(gpui::FontWeight::BOLD)
.text_color(rgb(COLOR_CYAN))
.child(format!(
"📊 Moniteur Temps Réel — {}",
viewed_source.label()
)),
)
.child(
div()
.flex()
.gap_1()
.child(self.render_selectable_pill(
"pill_mon_auto",
"Auto (actif)",
self.monitor_source_override.is_none(),
cx.listener(|this, _, _, cx| {
this.monitor_source_override = None;
cx.notify();
}),
))
.child(self.render_selectable_pill(
"pill_mon_g29",
"🏎️ G29",
self.monitor_source_override == Some(ControlSource::G29),
cx.listener(|this, _, _, cx| {
this.monitor_source_override = Some(ControlSource::G29);
cx.notify();
}),
))
.child(self.render_selectable_pill(
"pill_mon_steam",
"🎮 Steam",
self.monitor_source_override
== Some(ControlSource::SteamController),
cx.listener(|this, _, _, cx| {
this.monitor_source_override =
Some(ControlSource::SteamController);
cx.notify();
}),
)),
),
)
// Badges d'état (En ligne, Rapport, ARM/CH5, Sync RP2350)
.child(
div()
.flex()
.flex_wrap()
.items_center()
.gap_2()
.child(
div()
.px_2()
.py_0p5()
.rounded_md()
.bg(rgb(COLOR_SURFACE_ELEVATED))
.border_1()
.border_color(if is_online {
rgb(COLOR_GREEN)
} else {
rgb(COLOR_BORDER_SUBTLE)
})
.text_xs()
.font_weight(gpui::FontWeight::BOLD)
.text_color(if is_online {
rgb(COLOR_GREEN)
} else {
rgb(COLOR_TEXT_MUTED)
})
.child(if is_online {
"● CONNECTÉ"
} else {
"○ HORS LIGNE"
}),
)
.child(
div()
.px_2()
.py_0p5()
.rounded_md()
.bg(rgb(COLOR_SURFACE_ELEVATED))
.border_1()
.border_color(rgb(gear_color))
.text_xs()
.font_weight(gpui::FontWeight::BOLD)
.text_color(rgb(gear_color))
.child(format!("BOÎTE [{}]", gear_lbl)),
)
.child(
div()
.px_2()
.py_0p5()
.rounded_md()
.bg(rgb(COLOR_SURFACE_ELEVATED))
.border_1()
.border_color(rgb(arm_color))
.text_xs()
.font_weight(gpui::FontWeight::BOLD)
.text_color(rgb(arm_color))
.child(arm_text),
)
.child(
div()
.px_2()
.py_0p5()
.rounded_md()
.bg(rgb(COLOR_SURFACE_ELEVATED))
.border_1()
.border_color(rgb(rp2350_sync_color))
.text_xs()
.text_color(rgb(rp2350_sync_color))
.child(rp2350_sync_text),
),
)
// Jauges axes temps réel (CH1..CH4)
.child(self.render_monitor_bipolar_bar(
"Direction (CH1)",
steer_pct,
steer_crsf,
COLOR_CYAN,
))
.child(self.render_monitor_progress_bar(
"Accélérateur (CH2)",
throttle_pct,
throttle_crsf,
throttle_color,
))
.child(self.render_monitor_progress_bar(
"Frein (CH3)",
brake_pct,
brake_crsf,
COLOR_RED,
))
.child(self.render_monitor_progress_bar(
"Embrayage (CH4)",
clutch_pct,
clutch_crsf,
COLOR_CYAN,
))
// Pied du moniteur : dernier bouton & détails liaison (sur 2 lignes pour éviter toute troncature)
.child(
div()
.flex()
.flex_col()
.gap_1()
.pt_1()
.border_t_1()
.border_color(rgb(COLOR_BORDER_SUBTLE))
.text_xs()
.child(
div()
.text_color(rgb(COLOR_ORANGE))
.child(format!("🔘 Dernier bouton : {}", last_btn)),
)
.child(div().text_color(rgb(COLOR_TEXT_MUTED)).child(detail_line)),
)
}
}
+221
View File
@@ -0,0 +1,221 @@
use super::theme::*;
use super::SteamFrameGpuiApp;
use crate::logger::LogFilter;
use gpui::{div, prelude::*, rgb, Context, IntoElement};
impl SteamFrameGpuiApp {
pub(super) fn render_logs_view(&self, cx: &mut Context<Self>) -> impl IntoElement {
div()
.flex()
.flex_col()
.size_full()
.bg(rgb(COLOR_SURFACE_CARD))
.border_1()
.border_color(rgb(COLOR_BORDER_SUBTLE))
.rounded_xl()
.p_4()
.gap_3()
.overflow_hidden()
// Barre d'outils
.child(
div()
.flex()
.justify_between()
.items_center()
.border_b_1()
.border_color(rgb(COLOR_BORDER_SUBTLE))
.pb_3()
.child(
div()
.flex()
.items_center()
.gap_3()
.child(
div()
.text_sm()
.font_weight(gpui::FontWeight::BOLD)
.text_color(rgb(COLOR_CYAN))
.child("📜 Console de Diagnostic et Journal Système"),
)
.child(
div()
.text_xs()
.text_color(if self.log_err_count > 0 {
rgb(COLOR_RED)
} else {
rgb(COLOR_TEXT_MUTED)
})
.child(format!("{} Erreurs", self.log_err_count)),
)
.child(
div()
.text_xs()
.text_color(if self.log_warn_count > 0 {
rgb(COLOR_ORANGE)
} else {
rgb(COLOR_TEXT_MUTED)
})
.child(format!("{} Avertissements", self.log_warn_count)),
),
)
.child(
div()
.flex()
.gap_2()
.child(
div()
.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()
.on_click(cx.listener(|this, _, _, cx| {
this.log_filter = LogFilter::All;
cx.notify();
}))
.child("Tous les logs"),
)
.child(
div()
.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()
.on_click(cx.listener(|this, _, _, cx| {
this.log_filter = LogFilter::WarningsAndErrors;
cx.notify();
}))
.child("Warn / Erreurs"),
)
.child(
div()
.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()
.on_click(cx.listener(|this, _, _, cx| {
this.log_filter = LogFilter::ErrorsOnly;
cx.notify();
}))
.child("Erreurs seules"),
)
.child(
div()
.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()
.on_click(cx.listener(|this, _, _, cx| {
let mut lb = this.log_buffer.lock();
lb.entries.clear();
lb.error_count = 0;
lb.warn_count = 0;
this.log_entries.clear();
this.log_err_count = 0;
this.log_warn_count = 0;
cx.notify();
}))
.child("🗑️ Effacer"),
),
),
)
// Liste scrollable des messages
.child(
div()
.flex()
.flex_col()
.flex_1()
.min_h_0()
.min_w_0()
.id("logs_scroll_tab")
.overflow_y_scroll()
.px_2()
.gap_1()
.children(
self.log_entries
.iter()
.filter(|e| match self.log_filter {
LogFilter::All => true,
LogFilter::WarningsAndErrors => {
matches!(e.level, log::Level::Warn | log::Level::Error)
}
LogFilter::ErrorsOnly => matches!(e.level, log::Level::Error),
})
.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(
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()),
)
}),
),
)
}
// -------------------------------------------------------------------------
// Helpers Composants Graphiques
// -------------------------------------------------------------------------
}
+1153
View File
File diff suppressed because it is too large. Load diff
+466
View File
@@ -0,0 +1,466 @@
use super::super::theme::*;
use super::super::SteamFrameGpuiApp;
use crate::config::VehicleProfile;
use crate::controller::ControlSource;
use gpui::{div, prelude::*, rgb, rgba, Context, IntoElement, SharedString};
impl SteamFrameGpuiApp {
pub(super) fn render_profiles_battery_card(&self, cx: &mut Context<Self>) -> impl IntoElement {
let profiles = VehicleProfile::list_all();
self.render_settings_card(
"🚗 Profils Véhicules & Batterie LiPo",
COLOR_GREEN,
div()
.flex()
.flex_col()
.gap_2()
.child(
div()
.flex()
.flex_wrap()
.items_center()
.gap_2()
.children(profiles.into_iter().enumerate().map(|(idx, prof)| {
let is_active = self.cfg.active_profile.eq_ignore_ascii_case(&prof.name);
let label = format!("{} (V3:{})", prof.name, prof.gear_3_max);
let prof_clone = prof.clone();
self.render_selectable_pill(
SharedString::from(format!("pill_profile_{}", idx)),
&label,
is_active,
cx.listener(move |this, _, _, cx| {
match this.controls.apply_vehicle_profile(&prof_clone) {
Ok(()) => {
prof_clone.apply_to(&mut this.cfg);
this.profile_feedback = format!("Profil '{}' appliqué.", prof_clone.name);
}
Err(err) => {
this.profile_feedback = err;
}
}
cx.notify();
}),
)
}))
.child(
div()
.id("btn_save_custom_profile")
.px_2p5()
.py_1()
.rounded_md()
.bg(rgba(0x10b98122))
.border_1()
.border_color(rgb(COLOR_GREEN))
.text_xs()
.text_color(rgb(COLOR_GREEN))
.cursor_pointer()
.on_click(cx.listener(|this, _, _, cx| {
let name = if this.cfg.active_profile.trim().is_empty() {
"Custom".to_string()
} else {
this.cfg.active_profile.clone()
};
let p = VehicleProfile::from_config(name.clone(), &this.cfg);
match p.save_to_disk() {
Ok(path) => {
this.cfg.active_profile = name;
this.controls.save_full_config(&this.cfg);
this.profile_feedback = format!(
"Profil sauvegardé : {:?}",
path.file_name().unwrap_or_default()
);
}
Err(e) => {
this.profile_feedback = format!("Erreur sauvegarde : {}", e);
}
}
cx.notify();
}))
.child("💾 Sauvegarder profil"),
),
)
.child(
div()
.flex()
.flex_wrap()
.items_center()
.gap_2()
.child(
div()
.text_xs()
.text_color(rgb(COLOR_TEXT_MUTED))
.child("Cellules LiPo :"),
)
.children(
[
(0u8, "Auto 2S-6S"),
(2, "2S"),
(3, "3S"),
(4, "4S"),
(5, "5S"),
(6, "6S"),
]
.into_iter()
.map(|(cells, lbl)| {
self.render_selectable_pill(
SharedString::from(format!("pill_lipo_{}s", cells)),
lbl,
self.cfg.battery_cells == cells,
cx.listener(move |this, _, _, cx| {
this.cfg.battery_cells = cells;
this.controls.set_battery_cells(cells);
cx.notify();
}),
)
}),
),
)
.when(!self.profile_feedback.is_empty(), |el| {
el.child(
div()
.text_xs()
.text_color(rgb(COLOR_CYAN))
.child(self.profile_feedback.clone()),
)
}),
)
}
pub(super) fn render_controller_card(&self, cx: &mut Context<Self>) -> impl IntoElement {
self.render_settings_card(
"🎮 2b. Contrôleur de Conduite (Volant G29 / Steam Controller)",
COLOR_GREEN,
div()
.flex()
.flex_col()
.gap_3()
.child(self.render_setting_row(
"Source Active (bascule à chaud)",
div()
.flex()
.flex_wrap()
.gap_2()
.child(self.render_selectable_pill(
"pill_ctrl_g29",
"🏎️ Volant Logitech G29",
self.active_control_source == ControlSource::G29,
cx.listener(|this, _, _, cx| {
this.switch_control_source(ControlSource::G29);
cx.notify();
}),
))
.child(self.render_selectable_pill(
"pill_ctrl_steam",
"🎮 Steam Controller (Boîte séq.)",
self.active_control_source == ControlSource::SteamController,
cx.listener(|this, _, _, cx| {
this.switch_control_source(
ControlSource::SteamController,
);
cx.notify();
}),
)),
))
.when(!self.control_switch_error.is_empty(), |d| {
d.child(
div()
.px_2p5()
.py_1()
.rounded_md()
.bg(rgb(0x2a1215))
.border_1()
.border_color(rgb(COLOR_RED))
.text_xs()
.text_color(rgb(COLOR_RED))
.child(format!("⚠️ {}", self.control_switch_error)),
)
})
.child(self.render_setting_row(
"État Steam Controller",
div()
.text_xs()
.text_color(if self.latest_controller.connected {
rgb(COLOR_GREEN)
} else {
rgb(COLOR_TEXT_MUTED)
})
.child(if self.latest_controller.connected {
format!(
"● {} ({}) — [{}] {} • Gaz {}% • Frn {}% • Dir {:+.0}%",
self.latest_controller.device_name,
self.latest_controller.device_path,
self.latest_controller.gear_label(),
if self.latest_controller.armed {
"ARMED"
} else {
"SAFE"
},
self.latest_controller.throttle_pct,
self.latest_controller.brake_pct,
self.latest_controller.steering_norm * 100.0
)
} else {
"○ Non détecté (branchez le dongle ou allumez la manette)"
.to_string()
}),
))
.child(self.render_setting_row(
"Sens Direction Steam Controller",
div()
.flex()
.flex_wrap()
.items_center()
.gap_2()
.child(self.render_selectable_pill(
"pill_sc_steer_normal",
"Normal (identique G29)",
!self.cfg.controller_invert_steering,
cx.listener(|this, _, _, cx| {
this.cfg.controller_invert_steering = false;
this.controls.set_invert_steering(false);
cx.notify();
}),
))
.child(self.render_selectable_pill(
"pill_sc_steer_inv",
"Inversée",
self.cfg.controller_invert_steering,
cx.listener(|this, _, _, cx| {
this.cfg.controller_invert_steering = true;
this.controls.set_invert_steering(true);
cx.notify();
}),
))
.child(
div()
.text_xs()
.text_color(rgb(COLOR_TEXT_MUTED))
.child(format!(
"(Expo {:.2} • Deadzone {:.2})",
self.cfg.controller_expo,
self.cfg.controller_deadzone
)),
),
))
.child(self.render_setting_row(
"Vibrations Haptiques SC (25 Hz)",
div()
.flex()
.flex_wrap()
.items_center()
.gap_2()
.child(self.render_selectable_pill(
"pill_sc_vib_0",
"OFF",
self.cfg.controller_vibration == 0,
cx.listener(|this, _, _, cx| {
this.cfg.controller_vibration = 0;
this.controls.set_controller_vibration_pct(0);
cx.notify();
}),
))
.child(
div()
.id("btn_sc_vib_dec")
.px_2()
.py_1()
.rounded_md()
.bg(rgb(COLOR_SURFACE_ELEVATED))
.border_1()
.border_color(rgb(COLOR_BORDER_SUBTLE))
.text_xs()
.font_weight(gpui::FontWeight::BOLD)
.cursor_pointer()
.on_click(cx.listener(|this, _, _, cx| {
let next = this.cfg.controller_vibration.saturating_sub(10);
this.cfg.controller_vibration = next;
this.controls.set_controller_vibration_pct(next);
cx.notify();
}))
.child("−10%"),
)
.child(
div()
.px_2p5()
.py_1()
.rounded_md()
.bg(rgb(COLOR_BG_DARK))
.border_1()
.border_color(if self.cfg.controller_vibration > 0 {
rgb(COLOR_CYAN)
} else {
rgb(COLOR_BORDER_SUBTLE)
})
.text_xs()
.font_weight(gpui::FontWeight::BOLD)
.text_color(if self.cfg.controller_vibration > 0 {
rgb(COLOR_CYAN)
} else {
rgb(COLOR_TEXT_MUTED)
})
.child(if self.cfg.controller_vibration == 0 {
"0% (OFF)".to_string()
} else {
format!("{}%", self.cfg.controller_vibration)
}),
)
.child(
div()
.id("btn_sc_vib_inc")
.px_2()
.py_1()
.rounded_md()
.bg(rgb(COLOR_SURFACE_ELEVATED))
.border_1()
.border_color(rgb(COLOR_BORDER_SUBTLE))
.text_xs()
.font_weight(gpui::FontWeight::BOLD)
.cursor_pointer()
.on_click(cx.listener(|this, _, _, cx| {
let next = (this.cfg.controller_vibration + 10).min(100);
this.cfg.controller_vibration = next;
this.controls.set_controller_vibration_pct(next);
cx.notify();
}))
.child("+10%"),
)
.child(self.render_selectable_pill(
"pill_sc_vib_50",
"50%",
self.cfg.controller_vibration == 50,
cx.listener(|this, _, _, cx| {
this.cfg.controller_vibration = 50;
this.controls.set_controller_vibration_pct(50);
cx.notify();
}),
))
.child(self.render_selectable_pill(
"pill_sc_vib_100",
"100%",
self.cfg.controller_vibration == 100,
cx.listener(|this, _, _, cx| {
this.cfg.controller_vibration = 100;
this.controls.set_controller_vibration_pct(100);
cx.notify();
}),
))
.child(
div()
.id("btn_sc_vib_test")
.px_2p5()
.py_1()
.rounded_md()
.bg(rgb(COLOR_SURFACE_ELEVATED))
.border_1()
.border_color(rgb(COLOR_ORANGE))
.text_xs()
.font_weight(gpui::FontWeight::SEMIBOLD)
.text_color(rgb(COLOR_ORANGE))
.cursor_pointer()
.on_click(cx.listener(|this, _, _, cx| {
this.controls.trigger_controller_rumble_test();
cx.notify();
}))
.child("📳 Tester Vibrations"),
),
))
.child(self.render_setting_row(
"Réglage des Vitesses CRSF (G29 + Steam Controller)",
div()
.flex()
.flex_col()
.gap_2()
.p_2p5()
.rounded_md()
.bg(rgb(COLOR_BG_DARK))
.border_1()
.border_color(rgb(COLOR_BORDER_SUBTLE))
.child(self.render_gear_stepper_row(
"av_min",
"Seuil Gaz Avant (Min)",
self.cfg.gaz_avant_min,
COLOR_TEXT_MAIN,
|cfg, d| cfg.gaz_avant_min = cfg.gaz_avant_min.saturating_add_signed(d),
cx,
))
.child(self.render_gear_stepper_row(
"g1",
"1ère Vitesse (Manœuvre)",
self.cfg.gear_1_max,
COLOR_CYAN,
|cfg, d| cfg.gear_1_max = cfg.gear_1_max.saturating_add_signed(d),
cx,
))
.child(self.render_gear_stepper_row(
"g2",
"2ème Vitesse (Normale)",
self.cfg.gear_2_max,
COLOR_GREEN,
|cfg, d| cfg.gear_2_max = cfg.gear_2_max.saturating_add_signed(d),
cx,
))
.child(self.render_gear_stepper_row(
"g3",
"3ème Vitesse (Rapide)",
self.cfg.gear_3_max,
COLOR_ORANGE,
|cfg, d| cfg.gear_3_max = cfg.gear_3_max.saturating_add_signed(d),
cx,
))
.child(self.render_gear_stepper_row(
"ar_min",
"Seuil Gaz Arrière (Min)",
self.cfg.gaz_arriere_min,
COLOR_TEXT_MAIN,
|cfg, d| cfg.gaz_arriere_min = cfg.gaz_arriere_min.saturating_add_signed(d),
cx,
))
.child(self.render_gear_stepper_row(
"ar_max",
"Plafond Marche Arrière (R)",
self.cfg.gear_reverse_max,
COLOR_RED,
|cfg, d| cfg.gear_reverse_max = cfg.gear_reverse_max.saturating_add_signed(d),
cx,
))
.child(
div()
.flex()
.justify_end()
.pt_1()
.child(
div()
.id("btn_gears_reset_default")
.px_2p5()
.py_1()
.rounded_md()
.bg(rgb(COLOR_SURFACE_ELEVATED))
.border_1()
.border_color(rgb(COLOR_BORDER_SUBTLE))
.text_xs()
.font_weight(gpui::FontWeight::SEMIBOLD)
.text_color(rgb(COLOR_TEXT_MAIN))
.cursor_pointer()
.on_click(cx.listener(|this, _, _, cx| {
this.reset_gear_speed_limits();
cx.notify();
}))
.child("↺ Valeurs par défaut (1065 / 1100-1150-1220 / 905-800)"),
),
),
))
.child(self.render_controller_monitor(cx))
.child(
div()
.p_2()
.rounded_md()
.bg(rgb(COLOR_BG_DARK))
.border_1()
.border_color(rgb(COLOR_BORDER_SUBTLE))
.text_xs()
.text_color(rgb(COLOR_TEXT_MUTED))
.child("Stick G : Direction | R2 : Gaz | L2 : Frein | RB/LB ou R4/L4 : Boîte R-N-1-2-3 | Menu : Armer (au N) | A : Tare | B : DVR | Y : OSD | X : Proj VR | D-Pad : Trim"),
),
)
}
}
+401
View File
@@ -0,0 +1,401 @@
use super::super::theme::*;
use super::super::SteamFrameGpuiApp;
use crate::config::AppConfig;
use crate::controller::GearSpeedLimits;
use crate::dome_projection::ProjectionMode;
use crate::engine::LiveOpticalParams;
use crate::nomad_elrs::NomadHeadTracker;
use gpui::{div, prelude::*, px, rgb, App, Context, ElementId, IntoElement, Window};
impl SteamFrameGpuiApp {
pub(super) fn render_settings_card(&self, title: &str, accent_color: u32, content: impl IntoElement) -> impl IntoElement {
div()
.flex()
.flex_col()
.min_w(px(300.0))
.flex_1()
.overflow_hidden()
.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)
}
pub(super) fn render_mock_axis_row(
&self,
axis: &'static str,
label: &str,
value_deg: f32,
max_deg: f32,
cx: &mut Context<Self>,
) -> impl IntoElement {
let crsf = NomadHeadTracker::deg_to_crsf(value_deg, max_deg);
let pwm = NomadHeadTracker::crsf_to_pwm_us(crsf);
let step_btn = |suffix: &'static str, text: &'static str, delta: f32, reset: bool| {
let id = match (axis, suffix) {
("pan", "m10") => "mock_pan_m10",
("pan", "m1") => "mock_pan_m1",
("pan", "0") => "mock_pan_0",
("pan", "p1") => "mock_pan_p1",
("pan", "p10") => "mock_pan_p10",
("tilt", "m10") => "mock_tilt_m10",
("tilt", "m1") => "mock_tilt_m1",
("tilt", "0") => "mock_tilt_0",
("tilt", "p1") => "mock_tilt_p1",
("tilt", "p10") => "mock_tilt_p10",
("roll", "m10") => "mock_roll_m10",
("roll", "m1") => "mock_roll_m1",
("roll", "0") => "mock_roll_0",
("roll", "p1") => "mock_roll_p1",
_ => "mock_roll_p10",
};
div()
.id(id)
.px_2()
.py_0p5()
.bg(rgb(COLOR_SURFACE_ELEVATED))
.border_1()
.border_color(rgb(COLOR_BORDER_SUBTLE))
.rounded_md()
.text_xs()
.text_color(rgb(COLOR_TEXT_MAIN))
.cursor_pointer()
.on_click(cx.listener(move |this, _, _, cx| {
let (target, max_val) = match axis {
"pan" => (&mut this.mock_pan_deg, this.cfg.max_pan_deg),
"tilt" => (&mut this.mock_tilt_deg, this.cfg.max_tilt_deg),
_ => (&mut this.mock_roll_deg, this.cfg.max_roll_deg),
};
if reset {
*target = 0.0;
} else {
*target = (*target + delta).clamp(-max_val, max_val);
}
cx.notify();
}))
.child(text)
};
div()
.flex()
.flex_wrap()
.items_center()
.justify_between()
.gap_2()
.child(
div()
.text_xs()
.text_color(rgb(COLOR_TEXT_MAIN))
.child(format!(
"{} : {:+.0}° (CRSF {} / {}µs)",
label, value_deg, crsf, pwm
)),
)
.child(
div()
.flex()
.gap_1()
.child(step_btn("m10", "-10°", -10.0, false))
.child(step_btn("m1", "-1°", -1.0, false))
.child(step_btn("0", "0°", 0.0, true))
.child(step_btn("p1", "+1°", 1.0, false))
.child(step_btn("p10", "+10°", 10.0, false)),
)
}
pub(super) fn apply_gear_speed_limits(&mut self) {
let sanitized = GearSpeedLimits {
forward_min: self.cfg.gaz_avant_min,
forward_max: [
self.cfg.gear_1_max,
self.cfg.gear_2_max,
self.cfg.gear_3_max,
],
reverse_min: self.cfg.gaz_arriere_min,
reverse_max: self.cfg.gear_reverse_max,
}
.sanitized();
self.cfg.gaz_avant_min = sanitized.forward_min;
self.cfg.gear_1_max = sanitized.forward_max[0];
self.cfg.gear_2_max = sanitized.forward_max[1];
self.cfg.gear_3_max = sanitized.forward_max[2];
self.cfg.gaz_arriere_min = sanitized.reverse_min;
self.cfg.gear_reverse_max = sanitized.reverse_max;
self.controls.set_gear_speed_limits(sanitized);
}
pub(super) fn reset_gear_speed_limits(&mut self) {
let def = GearSpeedLimits::default();
self.cfg.gaz_avant_min = def.forward_min;
self.cfg.gear_1_max = def.forward_max[0];
self.cfg.gear_2_max = def.forward_max[1];
self.cfg.gear_3_max = def.forward_max[2];
self.cfg.gaz_arriere_min = def.reverse_min;
self.cfg.gear_reverse_max = def.reverse_max;
self.controls.set_gear_speed_limits(def);
}
pub(super) fn sync_optical_params(&self) {
self.controls.update_optical_params(LiveOpticalParams {
projection_mode: ProjectionMode::from_str(&self.cfg.projection_mode),
camera_fov_deg: self.cfg.camera_fov_deg,
lens_k1: self.cfg.lens_k1,
lens_k2: self.cfg.lens_k2,
screen_distance_m: self.cfg.screen_distance_m,
screen_width_m: self.cfg.screen_width_m,
brightness: self.cfg.video_brightness,
contrast: self.cfg.video_contrast,
gamma: self.cfg.video_gamma,
sharpness: self.cfg.video_sharpness,
horizon_stabilization: self.cfg.horizon_stabilization,
stereo_sbs: self.cfg.stereo_sbs,
});
}
pub(super) fn render_optical_stepper_row(
&self,
id_prefix: &'static str,
label: &'static str,
value_text: String,
mutator: fn(&mut AppConfig, f32),
cx: &mut Context<Self>,
) -> impl IntoElement {
let step_btn = |suffix: &'static str, txt: &'static str, step: f32| {
let btn_id = gpui::SharedString::from(format!("btn_opt_{}_{}", id_prefix, suffix));
div()
.id(btn_id)
.px_2p5()
.py_1()
.rounded_md()
.bg(rgb(COLOR_SURFACE_ELEVATED))
.border_1()
.border_color(rgb(COLOR_BORDER_SUBTLE))
.text_xs()
.font_weight(gpui::FontWeight::BOLD)
.cursor_pointer()
.on_click(cx.listener(move |this, _, _, cx| {
mutator(&mut this.cfg, step);
this.sync_optical_params();
cx.notify();
}))
.child(txt)
};
div()
.flex()
.flex_wrap()
.items_center()
.justify_between()
.gap_2()
.child(
div()
.text_xs()
.text_color(rgb(COLOR_TEXT_MAIN))
.child(label),
)
.child(
div()
.flex()
.items_center()
.gap_1p5()
.child(step_btn("m2", "−−", -2.0))
.child(step_btn("m1", "−", -1.0))
.child(
div()
.w(px(64.0))
.py_0p5()
.rounded_md()
.bg(rgb(COLOR_SURFACE_CARD))
.border_1()
.border_color(rgb(COLOR_CYAN))
.text_xs()
.font_weight(gpui::FontWeight::BOLD)
.text_color(rgb(COLOR_CYAN))
.flex()
.justify_center()
.child(value_text),
)
.child(step_btn("p1", "+", 1.0))
.child(step_btn("p2", "++", 2.0)),
)
}
pub(super) fn render_gear_stepper_row(
&self,
id_prefix: &'static str,
label: &'static str,
value: u16,
accent_color: u32,
mutator: fn(&mut AppConfig, i16),
cx: &mut Context<Self>,
) -> impl IntoElement {
let step_btn = |suffix: &'static str, txt: &'static str, delta: i16| {
let btn_id = gpui::SharedString::from(format!("btn_gear_{}_{}", id_prefix, suffix));
div()
.id(btn_id)
.px_2()
.py_0p5()
.rounded_md()
.bg(rgb(COLOR_SURFACE_ELEVATED))
.border_1()
.border_color(rgb(COLOR_BORDER_SUBTLE))
.text_xs()
.font_weight(gpui::FontWeight::BOLD)
.cursor_pointer()
.on_click(cx.listener(move |this, _, _, cx| {
mutator(&mut this.cfg, delta);
this.apply_gear_speed_limits();
cx.notify();
}))
.child(txt)
};
div()
.flex()
.flex_wrap()
.items_center()
.justify_between()
.gap_2()
.child(
div()
.text_xs()
.text_color(rgb(COLOR_TEXT_MAIN))
.child(label),
)
.child(
div()
.flex()
.items_center()
.gap_1p5()
.child(step_btn("m10", "−10", -10))
.child(step_btn("m5", "−5", -5))
.child(
div()
.w(px(56.0))
.py_0p5()
.rounded_md()
.bg(rgb(COLOR_SURFACE_CARD))
.border_1()
.border_color(rgb(accent_color))
.text_xs()
.font_weight(gpui::FontWeight::BOLD)
.text_color(rgb(accent_color))
.flex()
.justify_center()
.child(format!("{}", value)),
)
.child(step_btn("p5", "+5", 5))
.child(step_btn("p10", "+10", 10)),
)
}
pub(super) 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)
}
pub(in super::super) fn render_selectable_pill(
&self,
id: impl Into<ElementId>,
label: &str,
is_selected: bool,
on_click: impl Fn(&gpui::ClickEvent, &mut Window, &mut App) + 'static,
) -> impl IntoElement {
div()
.id(id.into())
.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())
}
pub(super) fn render_channel_button(&self, ch: u16, freq_mhz: u32, cx: &mut Context<Self>) -> 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))
}
}
+90
View File
@@ -0,0 +1,90 @@
mod controls_profiles;
mod helpers;
mod network_system;
mod video_vr;
use super::theme::*;
use super::SteamFrameGpuiApp;
use gpui::{div, prelude::*, rgb, Context, IntoElement};
impl SteamFrameGpuiApp {
pub(super) fn render_settings_view(&self, cx: &mut Context<Self>) -> impl IntoElement {
div()
.flex()
.flex_col()
.size_full()
.min_h_0()
.min_w_0()
.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()
.flex_wrap()
.justify_between()
.items_center()
.gap_2()
.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("Profils véhicules, batterie LiPo, VRX, Wi-Fi Nomad, projection VR et OSD (auto-sauvegardés)."),
),
)
.child(
div()
.id("btn_apply_settings")
.px_4()
.py_1p5()
.bg(rgb(COLOR_GREEN))
.text_color(rgb(0x000000))
.rounded_md()
.text_xs()
.font_weight(gpui::FontWeight::BOLD)
.cursor_pointer()
.on_click(cx.listener(|this, _, _, cx| {
this.restart_engine_async("[Réglages] Application et redémarrage asynchrone du moteur FPV...");
cx.notify();
}))
.child("🔄 Appliquer & Redémarrer"),
),
)
.child(self.render_profiles_battery_card(cx))
.child(
div()
.flex()
.flex_row()
.flex_wrap()
.gap_3()
.child(self.render_vrx_card(cx))
.child(self.render_nomad_card(cx))
.child(self.render_controller_card(cx))
.child(self.render_projection_optical_card(cx))
.child(self.render_gpu_image_enhance_card(cx))
.child(self.render_telemetry_card(cx))
.child(self.render_dvr_card(cx)),
)
}
}
+456
View File
@@ -0,0 +1,456 @@
use super::super::theme::*;
use super::super::{SteamFrameGpuiApp, TargetEditField};
use gpui::{div, prelude::*, rgb, Context, IntoElement, KeyDownEvent};
impl SteamFrameGpuiApp {
pub(super) fn render_vrx_card(&self, cx: &mut Context<Self>) -> impl IntoElement {
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()
.flex_wrap()
.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()
.flex_wrap()
.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()
.flex_wrap()
.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()
.flex_wrap()
.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"),
),
),
)
}
pub(super) fn render_nomad_card(&self, cx: &mut Context<Self>) -> impl IntoElement {
self.render_settings_card(
"📡 2. Suivi de Tête & Radio (Nomad ELRS)",
COLOR_ORANGE,
div()
.flex()
.flex_col()
.gap_3()
.when_some(self.target_focus_handle.as_ref(), |d, fh| {
d.track_focus(fh).on_key_down(cx.listener(|this, ev: &KeyDownEvent, _, cx| {
this.handle_target_key_down(ev);
cx.notify();
}))
})
// Protocole
.child(self.render_setting_row(
"Protocole Wi-Fi",
div()
.flex()
.flex_wrap()
.gap_2()
.child(self.render_selectable_pill(
"pill_proto_g29",
"G29 Hub ($HT)",
self.cfg.ht_protocol.eq_ignore_ascii_case("g29")
|| self.cfg.ht_protocol.eq_ignore_ascii_case("g29_bridge")
|| self.cfg.ht_protocol.eq_ignore_ascii_case("radxa"),
cx.listener(|this, _, _, cx| {
this.cfg.ht_protocol = "g29".into();
this.mock_tracker = None;
cx.notify();
}),
))
.child(self.render_selectable_pill(
"pill_proto_msp",
"MSPv2 0x0383",
self.cfg.ht_protocol.eq_ignore_ascii_case("msp"),
cx.listener(|this, _, _, cx| {
this.cfg.ht_protocol = "msp".into();
this.mock_tracker = None;
cx.notify();
}),
))
.child(self.render_selectable_pill(
"pill_proto_crsf",
"CRSF 0x16",
self.cfg.ht_protocol.eq_ignore_ascii_case("crsf"),
cx.listener(|this, _, _, cx| {
this.cfg.ht_protocol = "crsf".into();
this.mock_tracker = None;
cx.notify();
}),
))
.child(self.render_selectable_pill(
"pill_proto_mavlink",
"MAVLink v1 (14555)",
self.cfg.ht_protocol.eq_ignore_ascii_case("mavlink"),
cx.listener(|this, _, _, cx| {
this.cfg.ht_protocol = "mavlink".into();
this.mock_tracker = None;
cx.notify();
}),
)),
))
// Cible UDP éditable (clic pour taper IP/hostname ou port)
.child(self.render_setting_row(
"Cible Réseau (clic pour éditer)",
div()
.flex()
.flex_wrap()
.items_center()
.gap_1()
.child(
div()
.id("input_nomad_ip")
.px_2()
.py_1()
.rounded_md()
.bg(rgb(COLOR_SURFACE_ELEVATED))
.border_1()
.border_color(if self.target_edit_field == Some(TargetEditField::Ip) {
rgb(COLOR_BORDER_ACTIVE)
} else {
rgb(COLOR_BORDER_SUBTLE)
})
.text_xs()
.text_color(rgb(COLOR_TEXT_MAIN))
.cursor_pointer()
.on_click(cx.listener(|this, _, window, cx| {
if this.target_edit_field == Some(TargetEditField::Port) {
this.commit_port_buf();
}
this.target_edit_field = Some(TargetEditField::Ip);
if let Some(fh) = &this.target_focus_handle {
window.focus(fh);
}
cx.notify();
}))
.child(if self.target_edit_field == Some(TargetEditField::Ip) {
format!("{}|", self.cfg.nomad_ip)
} else {
self.cfg.nomad_ip.clone()
}),
)
.child(div().text_xs().text_color(rgb(COLOR_TEXT_MUTED)).child(":"))
.child(
div()
.id("input_nomad_port")
.px_2()
.py_1()
.rounded_md()
.bg(rgb(COLOR_SURFACE_ELEVATED))
.border_1()
.border_color(if self.target_edit_field == Some(TargetEditField::Port) {
rgb(COLOR_BORDER_ACTIVE)
} else {
rgb(COLOR_BORDER_SUBTLE)
})
.text_xs()
.text_color(rgb(COLOR_TEXT_MAIN))
.cursor_pointer()
.on_click(cx.listener(|this, _, window, cx| {
this.target_port_buf = this.cfg.nomad_port.to_string();
this.target_edit_field = Some(TargetEditField::Port);
if let Some(fh) = &this.target_focus_handle {
window.focus(fh);
}
cx.notify();
}))
.child(if self.target_edit_field == Some(TargetEditField::Port) {
format!("{}|", self.target_port_buf)
} else {
self.cfg.nomad_port.to_string()
}),
),
))
// Presets réseau rapides
.child(self.render_setting_row(
"Presets Cible",
div()
.flex()
.flex_wrap()
.gap_2()
.child(self.render_selectable_pill(
"preset_radxa_g29_unified",
"Tout-en-un Radxa usb0 (192.168.1.1:14552)",
self.cfg.nomad_ip == "192.168.1.1" && self.cfg.nomad_port == 14552,
cx.listener(|this, _, _, cx| {
this.set_nomad_target("192.168.1.1", 14552, Some("g29"));
cx.notify();
}),
))
.child(self.render_selectable_pill(
"preset_ap_default",
"AP Défaut (10.0.0.1:14550)",
self.cfg.nomad_ip == "10.0.0.1" && self.cfg.nomad_port == 14550,
cx.listener(|this, _, _, cx| {
this.set_nomad_target("10.0.0.1", 14550, Some("msp"));
cx.notify();
}),
))
.child(self.render_selectable_pill(
"preset_local_bp",
"Backpack LAN (elrs_txbp.local:14555)",
self.cfg.nomad_ip == "elrs_txbp.local" && self.cfg.nomad_port == 14555,
cx.listener(|this, _, _, cx| {
this.set_nomad_target("elrs_txbp.local", 14555, Some("mavlink"));
cx.notify();
}),
))
.child(self.render_selectable_pill(
"preset_localhost",
"Test Local (127.0.0.1:14550)",
self.cfg.nomad_ip == "127.0.0.1" && self.cfg.nomad_port == 14550,
cx.listener(|this, _, _, cx| {
this.set_nomad_target("127.0.0.1", 14550, None);
cx.notify();
}),
)),
))
// 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
)),
))
// Mock Manuel Pan/Tilt/Roll
.child(
div()
.flex()
.flex_col()
.gap_2()
.p_2()
.rounded_md()
.bg(rgb(COLOR_BG_DARK))
.border_1()
.border_color(rgb(COLOR_BORDER_SUBTLE))
.child(
div()
.text_xs()
.font_weight(gpui::FontWeight::SEMIBOLD)
.text_color(rgb(COLOR_ORANGE))
.child("🎛️ Mock Manuel (Envoi direct vers Nomad / Backpack)"),
)
.child(self.render_mock_axis_row(
"pan",
"Pan (Yaw)",
self.mock_pan_deg,
self.cfg.max_pan_deg,
cx,
))
.child(self.render_mock_axis_row(
"tilt",
"Tilt (Pitch)",
self.mock_tilt_deg,
self.cfg.max_tilt_deg,
cx,
))
.child(self.render_mock_axis_row(
"roll",
"Roll",
self.mock_roll_deg,
self.cfg.max_roll_deg,
cx,
))
.child(
div()
.flex()
.flex_wrap()
.gap_2()
.pt_1()
.child(
div()
.id("btn_send_mock_manual")
.flex_1()
.py_1p5()
.px_2()
.bg(rgb(COLOR_SURFACE_ELEVATED))
.border_1()
.border_color(rgb(COLOR_ORANGE))
.rounded_md()
.text_xs()
.font_weight(gpui::FontWeight::SEMIBOLD)
.cursor_pointer()
.on_click(cx.listener(|this, _, _, cx| {
this.send_mock_manual();
cx.notify();
}))
.child("📤 Envoyer Mock Manuel"),
)
.child(self.render_selectable_pill(
"pill_mock_continuous",
if self.mock_continuous {
"🔄 Continu 50 Hz : ON"
} else {
"🔄 Continu 50 Hz : OFF"
},
self.mock_continuous,
cx.listener(|this, _, _, cx| {
if this.target_edit_field == Some(TargetEditField::Port) {
this.commit_port_buf();
this.target_edit_field = None;
}
this.mock_continuous = !this.mock_continuous;
this.mock_last_send = None;
if this.mock_continuous && this.cfg.head_tracking_enabled {
this.cfg.head_tracking_enabled = false;
this.controls.set_head_tracking_enabled(false);
log::info!("[Mock Manuel] Suivi de tête moteur désactivé automatiquement pour éviter une collision UDP.");
}
cx.notify();
}),
)),
)
.when(!self.mock_status_text.is_empty(), |d| {
d.child(
div()
.text_xs()
.text_color(rgb(COLOR_GREEN))
.child(self.mock_status_text.clone()),
)
}),
)
// Actions Nomad
.child(
div()
.flex()
.flex_wrap()
.gap_2()
.pt_1()
.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 neutre"),
)
.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.controls.request_recenter();
cx.notify();
}))
.child("🎯 Réinitialiser Zéro (Tare)"),
),
),
)
}
}
+443
View File
@@ -0,0 +1,443 @@
use super::super::theme::*;
use super::super::SteamFrameGpuiApp;
use crate::dvr::{DvrContainer, DvrMode};
use gpui::{div, prelude::*, rgb, Context, IntoElement};
impl SteamFrameGpuiApp {
pub(super) fn render_projection_optical_card(&self, cx: &mut Context<Self>) -> impl IntoElement {
self.render_settings_card(
"🥽 3. Projection VR & Correction Optique 140°",
COLOR_CYAN,
div()
.flex()
.flex_col()
.gap_3()
// Activation / Désactivation du mode VR OpenXR
.child(self.render_setting_row(
"Affichage Casque VR (OpenXR)",
div()
.flex()
.flex_wrap()
.gap_2()
.child(self.render_selectable_pill(
"pill_vr_on",
"🥽 Activé (Casque VR)",
!self.cfg.headless,
cx.listener(|this, _, _, cx| {
this.set_vr_enabled(true);
cx.notify();
}),
))
.child(self.render_selectable_pill(
"pill_vr_off",
"🖥️ Désactivé (Mode Bureau léger)",
self.cfg.headless,
cx.listener(|this, _, _, cx| {
this.set_vr_enabled(false);
cx.notify();
}),
)),
))
// Mode de projection
.child(self.render_setting_row(
"Mode de Projection VR",
div()
.flex()
.flex_wrap()
.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();
this.sync_optical_params();
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();
this.sync_optical_params();
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();
this.sync_optical_params();
cx.notify();
}),
)),
))
// Champ de vision, Lentille k1/k2 et Distance virtuelle (réglables à chaud en VR)
.child(self.render_setting_row(
"Optique & Écran VR (Réglage à chaud)",
div()
.flex()
.flex_col()
.gap_2()
.p_2p5()
.rounded_md()
.bg(rgb(COLOR_BG_DARK))
.border_1()
.border_color(rgb(COLOR_BORDER_SUBTLE))
.child(self.render_optical_stepper_row(
"opt_fov",
"FOV Caméra",
format!("{:.0}°", self.cfg.camera_fov_deg),
|cfg, step| {
cfg.camera_fov_deg =
(cfg.camera_fov_deg + step * 5.0).clamp(70.0, 180.0);
},
cx,
))
.child(self.render_optical_stepper_row(
"opt_k1",
"Distorsion k1",
format!("{:+.2}", self.cfg.lens_k1),
|cfg, step| {
cfg.lens_k1 = (((cfg.lens_k1 + step * 0.02) * 100.0)
.round()
/ 100.0)
.clamp(-0.50, 0.50);
},
cx,
))
.child(self.render_optical_stepper_row(
"opt_k2",
"Distorsion k2",
format!("{:+.2}", self.cfg.lens_k2),
|cfg, step| {
cfg.lens_k2 = (((cfg.lens_k2 + step * 0.01) * 100.0)
.round()
/ 100.0)
.clamp(-0.25, 0.25);
},
cx,
))
.child(self.render_optical_stepper_row(
"opt_dist",
"Distance Écran",
format!("{:.1} m", self.cfg.screen_distance_m),
|cfg, step| {
cfg.screen_distance_m = (((cfg.screen_distance_m
+ step * 0.2)
* 10.0)
.round()
/ 10.0)
.clamp(0.8, 4.0);
},
cx,
)),
)),
)
}
pub(super) fn render_gpu_image_enhance_card(&self, cx: &mut Context<Self>) -> impl IntoElement {
self.render_settings_card(
"✨ 3b. Image GPU, Horizon CRSF, 3D SBS & DMA-BUF",
COLOR_ORANGE,
div()
.flex()
.flex_col()
.gap_2p5()
.child(self.render_optical_stepper_row(
"gpu_bright",
"Luminosité",
format!("{:+.2}", self.cfg.video_brightness),
|c, d| c.video_brightness = (c.video_brightness + d * 0.05).clamp(-0.5, 0.5),
cx,
))
.child(self.render_optical_stepper_row(
"gpu_contrast",
"Contraste",
format!("{:.2}x", self.cfg.video_contrast),
|c, d| c.video_contrast = (c.video_contrast + d * 0.1).clamp(0.5, 2.0),
cx,
))
.child(self.render_optical_stepper_row(
"gpu_gamma",
"Gamma",
format!("{:.2}", self.cfg.video_gamma),
|c, d| c.video_gamma = (c.video_gamma + d * 0.1).clamp(0.5, 2.2),
cx,
))
.child(self.render_optical_stepper_row(
"gpu_sharp",
"Netteté CAS",
format!("{:.0}%", self.cfg.video_sharpness * 100.0),
|c, d| c.video_sharpness = (c.video_sharpness + d * 0.1).clamp(0.0, 1.0),
cx,
))
.child(
div()
.flex()
.flex_wrap()
.gap_2()
.child(self.render_selectable_pill(
"pill_horizon_stab",
if self.cfg.horizon_stabilization {
"🧭 Horizon CRSF : ON"
} else {
"🧭 Horizon CRSF : OFF"
},
self.cfg.horizon_stabilization,
cx.listener(|this, _, _, cx| {
this.cfg.horizon_stabilization = !this.cfg.horizon_stabilization;
this.controls.set_image_enhance(
this.cfg.video_brightness,
this.cfg.video_contrast,
this.cfg.video_gamma,
this.cfg.video_sharpness,
this.cfg.horizon_stabilization,
this.cfg.stereo_sbs,
);
cx.notify();
}),
))
.child(self.render_selectable_pill(
"pill_stereo_sbs",
if self.cfg.stereo_sbs {
"🥽 3D Stéréo SBS : ON"
} else {
"🥽 3D Stéréo SBS : OFF"
},
self.cfg.stereo_sbs,
cx.listener(|this, _, _, cx| {
this.cfg.stereo_sbs = !this.cfg.stereo_sbs;
this.controls.set_image_enhance(
this.cfg.video_brightness,
this.cfg.video_contrast,
this.cfg.video_gamma,
this.cfg.video_sharpness,
this.cfg.horizon_stabilization,
this.cfg.stereo_sbs,
);
cx.notify();
}),
))
.child(self.render_selectable_pill(
"pill_dmabuf",
if self.cfg.zero_copy_dmabuf {
"⚡ DMA-BUF Zéro-Copie : ON"
} else {
"⚡ DMA-BUF Zéro-Copie : OFF"
},
self.cfg.zero_copy_dmabuf,
cx.listener(|this, _, _, cx| {
this.cfg.zero_copy_dmabuf = !this.cfg.zero_copy_dmabuf;
this.restart_engine_async("Bascule DMA-BUF zéro-copie");
cx.notify();
}),
)),
)
.child(
div()
.id("btn_reset_gpu_enhance")
.px_2p5()
.py_1()
.rounded_md()
.bg(rgb(COLOR_SURFACE_CARD))
.border_1()
.border_color(rgb(COLOR_BORDER_SUBTLE))
.text_xs()
.text_color(rgb(COLOR_TEXT_MUTED))
.cursor_pointer()
.on_click(cx.listener(|this, _, _, cx| {
this.cfg.video_brightness = 0.0;
this.cfg.video_contrast = 1.0;
this.cfg.video_gamma = 1.0;
this.cfg.video_sharpness = 0.0;
this.cfg.horizon_stabilization = false;
this.cfg.stereo_sbs = false;
this.controls
.set_image_enhance(0.0, 1.0, 1.0, 0.0, false, false);
cx.notify();
}))
.child("↺ Réinitialiser réglages image GPU"),
),
)
}
pub(super) fn render_telemetry_card(&self, cx: &mut Context<Self>) -> impl IntoElement {
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()
.flex_wrap()
.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.controls.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.controls.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)),
)),
)
}
pub(super) fn render_dvr_card(&self, cx: &mut Context<Self>) -> impl IntoElement {
self.render_settings_card(
"🎥 5. Enregistreur Vidéo DVR",
COLOR_RED,
div()
.flex()
.flex_col()
.gap_3()
// Format de conteneur
.child(self.render_setting_row(
"Format Conteneur",
div()
.flex()
.flex_wrap()
.gap_2()
.child(self.render_selectable_pill(
"pill_dvr_mkv",
"MKV (Résistant)",
self.cfg.dvr_format.eq_ignore_ascii_case("mkv"),
cx.listener(|this, _, _, cx| {
this.cfg.dvr_format = "mkv".into();
this.controls.update_dvr_config(
this.cfg.dvr_dir.clone(),
DvrContainer::Mkv,
DvrMode::from_str(&this.cfg.dvr_mode),
);
cx.notify();
}),
))
.child(self.render_selectable_pill(
"pill_dvr_mp4",
"MP4 (Standard)",
self.cfg.dvr_format.eq_ignore_ascii_case("mp4"),
cx.listener(|this, _, _, cx| {
this.cfg.dvr_format = "mp4".into();
this.controls.update_dvr_config(
this.cfg.dvr_dir.clone(),
DvrContainer::Mp4,
DvrMode::from_str(&this.cfg.dvr_mode),
);
cx.notify();
}),
)),
))
// Mode d'enregistrement
.child(self.render_setting_row(
"Mode Enregistrement",
div()
.flex()
.flex_wrap()
.gap_2()
.child(self.render_selectable_pill(
"pill_dvr_copy",
"Direct 0% CPU",
self.cfg.dvr_mode.eq_ignore_ascii_case("copy"),
cx.listener(|this, _, _, cx| {
this.cfg.dvr_mode = "copy".into();
this.controls.update_dvr_config(
this.cfg.dvr_dir.clone(),
DvrContainer::from_str(&this.cfg.dvr_format),
DvrMode::StreamCopy,
);
cx.notify();
}),
))
.child(self.render_selectable_pill(
"pill_dvr_osd",
"Avec OSD incrusté",
self.cfg.dvr_mode.eq_ignore_ascii_case("composited") || self.cfg.dvr_mode.eq_ignore_ascii_case("osd"),
cx.listener(|this, _, _, cx| {
this.cfg.dvr_mode = "composited".into();
this.controls.update_dvr_config(
this.cfg.dvr_dir.clone(),
DvrContainer::from_str(&this.cfg.dvr_format),
DvrMode::CompositedOsd,
);
cx.notify();
}),
)),
))
// Statut & Action
.child(self.render_setting_row(
"Statut DVR",
div()
.text_xs()
.text_color(if self.dvr_recording { rgb(COLOR_RED) } else { rgb(COLOR_TEXT_MUTED) })
.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!("● ACTIF : {:02}:{:02} ({} frames, {:.1} Mo)", mins, secs, self.dvr_frames_recorded, mb)
} else {
"Inactif (Prêt à enregistrer)".to_string()
}),
))
.child(
div()
.flex()
.pt_1()
.child(
div()
.id("btn_toggle_dvr_card")
.flex_1()
.py_1p5()
.bg(if self.dvr_recording { rgb(COLOR_RED) } else { rgb(COLOR_SURFACE_CARD) })
.border_1()
.border_color(if self.dvr_recording { rgb(COLOR_RED) } else { rgb(COLOR_BORDER_SUBTLE) })
.rounded_md()
.text_xs()
.font_weight(gpui::FontWeight::BOLD)
.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 {
"⏹ Arrêter l'enregistrement DVR"
} else {
"🔴 Démarrer l'enregistrement DVR"
}),
),
),
)
}
}
+360
View File
@@ -0,0 +1,360 @@
use super::theme::*;
use super::SteamFrameGpuiApp;
use crate::controller::ControlSource;
use crate::engine::SubsystemStatus;
use gpui::{div, prelude::*, px, rgb, IntoElement};
impl SteamFrameGpuiApp {
pub(super) fn render_telemetry_view(&self) -> impl IntoElement {
let telem_live = self.latest_telem.is_live();
let eff_cells = self.latest_telem.effective_cells(self.cfg.battery_cells);
let cell_v_opt = self.latest_telem.cell_voltage_v(self.cfg.battery_cells);
let (bat_val, bat_sub, bat_color) = if !telem_live {
(
"HORS LIGNE".to_string(),
"En attente télémétrie...".to_string(),
COLOR_TEXT_MUTED,
)
} else if let Some(cv) = cell_v_opt {
let col = if cv < self.cfg.battery_crit_cell_v {
COLOR_RED
} else if cv < self.cfg.battery_warn_cell_v {
COLOR_ORANGE
} else {
COLOR_GREEN
};
(
format!("{:.2} V ({}S)", self.latest_telem.battery_voltage_v, eff_cells),
format!("{:.2} V/cell • {:.1} A", cv, self.latest_telem.battery_current_a),
col,
)
} else {
(
format!("{:.2} V", self.latest_telem.battery_voltage_v),
format!("{:.1} A débit", self.latest_telem.battery_current_a),
COLOR_GREEN,
)
};
let (lq_val, lq_sub, lq_color) = if !telem_live {
(
"HORS LIGNE".to_string(),
"Aucun paquet CRSF/MAVLink".to_string(),
COLOR_TEXT_MUTED,
)
} else {
let col = if self.latest_telem.link_quality_pct < 50 {
COLOR_RED
} else if self.latest_telem.link_quality_pct < 70 {
COLOR_ORANGE
} else {
COLOR_CYAN
};
(
format!("{} %", self.latest_telem.link_quality_pct),
format!("{} dBm (RSSI)", self.latest_telem.rssi_dbm),
col,
)
};
let nomad_status_str = match &self.nomad_status {
SubsystemStatus::Running(s) => s.clone(),
SubsystemStatus::Warning(s) => format!("Alerte : {}", s),
SubsystemStatus::Error(s) => format!("Erreur : {}", s),
SubsystemStatus::Disabled => "Désactivé".to_string(),
SubsystemStatus::Starting => "Démarrage...".to_string(),
SubsystemStatus::Stopped => "Arrêté".to_string(),
};
let gps_summary = if self.latest_telem.gps_fix_valid {
let home_suffix = self
.latest_telem
.home_vector()
.map(|(dist_m, rel_deg)| {
if dist_m >= 1000.0 {
format!(" • HOME {:.2}km ({:+.0}°)", dist_m / 1000.0, rel_deg)
} else {
format!(" • HOME {:.0}m ({:+.0}°)", dist_m, rel_deg)
}
})
.unwrap_or_default();
format!(
"{} sats ({:.4}, {:.4}){}",
self.latest_telem.gps_sats,
self.latest_telem.gps_lat_deg,
self.latest_telem.gps_lon_deg,
home_suffix
)
} else if self.latest_telem.gps_sats > 0 {
format!("{} sats (pas de fix)", self.latest_telem.gps_sats)
} else {
"Aucun fix GPS".to_string()
};
div()
.flex()
.flex_col()
.size_full()
.min_h_0()
.min_w_0()
.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, signal, vidéo et GPS
.child(
div()
.flex()
.flex_wrap()
.gap_3()
.child(self.render_stat_box("🔋 BATTERIE VÉHICULE", &bat_val, &bat_sub, bat_color))
.child(self.render_stat_box("📶 QUALITÉ DU LIEN", &lq_val, &lq_sub, lq_color))
.child(self.render_stat_box(
"🎥 LIEN VIDÉO",
&format!("{:.1} FPS", self.video_fps),
&format!(
"Jitter {:.1} ms • Drop {} • {}",
self.video_jitter_ms, self.video_dropped_frames, self.video_decoder_name
),
if self.video_fps > 1.0 { COLOR_CYAN } else { COLOR_TEXT_MUTED },
))
.child(self.render_stat_box(
"🚀 VITESSE & MODE",
&format!("{:.1} km/h", self.latest_telem.groundspeed_ms * 3.6),
&format!(
"Gaz {}%{}",
self.latest_telem.throttle_pct,
if self.latest_telem.flight_mode.is_empty() {
String::new()
} else {
format!(" • {}", self.latest_telem.flight_mode)
}
),
COLOR_ORANGE,
))
.child(self.render_stat_box(
"🛰️ ALTITUDE & GPS",
&format!("{:.1} m • {:.0}°", self.latest_telem.altitude_m, self.latest_telem.drone_heading_deg),
&gps_summary,
COLOR_CYAN,
))
.child(if self.active_control_source == ControlSource::SteamController {
self.render_stat_box(
"🎮 STEAM CONTROLLER",
&if !self.latest_controller.connected {
"NON DÉTECTÉ".to_string()
} else {
format!(
"[{}] {}",
self.latest_controller.gear_label(),
if self.latest_controller.armed {
"ARMED"
} else {
"SAFE"
}
)
},
&format!(
"Gaz {}% | Frn {}% | Dir {:+.0}%",
self.latest_controller.throttle_pct,
self.latest_controller.brake_pct,
self.latest_controller.steering_norm * 100.0
),
if !self.latest_controller.connected {
COLOR_TEXT_MUTED
} else if self.latest_controller.armed {
COLOR_GREEN
} else {
COLOR_ORANGE
},
)
} else {
self.render_stat_box(
"🏎️ VOLANT G29",
&if !self.latest_g29.is_live() {
"HORS LIGNE".to_string()
} else {
format!(
"[{}] {}",
self.latest_g29.gear_label(),
if self.latest_g29.armed { "ARMED" } else { "SAFE" }
)
},
&format!(
"Gaz {}% | Frn {}% | FFB {}%",
self.latest_g29.throttle_pct,
self.latest_g29.brake_pct,
self.latest_g29.ffb_pct
),
if !self.latest_g29.is_live() {
COLOR_TEXT_MUTED
} else if self.latest_g29.armed {
COLOR_GREEN
} else {
COLOR_ORANGE
},
)
}),
)
// 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_ELEVATED))
.border_1()
.border_color(rgb(COLOR_BORDER_SUBTLE))
.rounded_xl()
.p_4()
.gap_3()
.child(
div()
.flex()
.justify_between()
.items_center()
.child(
div()
.text_sm()
.font_weight(gpui::FontWeight::BOLD)
.text_color(rgb(COLOR_ORANGE))
.child("🎯 Canaux CRSF Suivi de Tête (172..1811)"),
)
.child(
div()
.text_xs()
.text_color(rgb(COLOR_TEXT_MUTED))
.child(format!(
"Paquets: {} | Erreurs: {}",
self.latest_pose.packets_sent,
self.latest_pose.send_errors
)),
),
)
.child(self.render_crsf_gauge(
"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 / Élévation)",
self.latest_pose.tilt_deg,
self.latest_pose.tilt_crsf,
self.cfg.max_tilt_deg,
))
.child(self.render_crsf_gauge(
"ROLL (Roulis / Inclinaison)",
self.latest_pose.roll_deg,
self.latest_pose.roll_crsf,
self.cfg.max_roll_deg,
)),
)
// Panneau État Liaison Nomad
.child(
div()
.flex()
.flex_col()
.w(px(340.0))
.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(COLOR_CYAN))
.child("📡 État RadioMaster Nomad"),
)
.child(self.render_stat_row("Statut Réseau :", &nomad_status_str))
.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(
"Décodeur Vidéo :",
&if self.dmabuf_active {
format!("{} (DMA-BUF)", self.video_decoder_name)
} else {
self.video_decoder_name.clone()
},
))
.child(self.render_stat_row(
"Replay 30s RAM :",
&if !self.replay_status_text.is_empty() {
self.replay_status_text.clone()
} else {
format!("{:.1} Mo", self.replay_buffered_bytes as f64 / (1024.0 * 1024.0))
},
))
.child(self.render_stat_row("Dernière émission :", if self.latest_pose.last_send_ok { "Succès (OK)" } else { "En attente" })),
),
)
}
fn render_stat_box(&self, title: &str, value: &str, sub: &str, color: u32) -> impl IntoElement {
div()
.flex()
.flex_col()
.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
// -------------------------------------------------------------------------
}
+13
View File
@@ -0,0 +1,13 @@
// Palette de couleurs moderne — SteamFrame FPV Control Center
pub const COLOR_BG_DARK: u32 = 0x07090e;
pub const COLOR_SURFACE_CARD: u32 = 0x0f131c;
pub const COLOR_SURFACE_ELEVATED: u32 = 0x161c28;
pub const COLOR_BORDER_SUBTLE: u32 = 0x1d2636;
pub const COLOR_BORDER_ACTIVE: u32 = 0x00e5ff;
pub const COLOR_CYAN: u32 = 0x00e5ff;
pub const COLOR_GREEN: u32 = 0x10b981;
pub const COLOR_ORANGE: u32 = 0xf97316;
pub const COLOR_RED: u32 = 0xef4444;
pub const COLOR_TEXT_MUTED: u32 = 0x64748b;
pub const COLOR_TEXT_MAIN: u32 = 0xe2e8f0;
+221
View File
@@ -0,0 +1,221 @@
use super::theme::*;
use super::SteamFrameGpuiApp;
use crate::engine::SubsystemStatus;
use gpui::{div, prelude::*, px, rgb, DefiniteLength, IntoElement};
impl SteamFrameGpuiApp {
pub(super) fn render_status_badge(&self, label: &str, status: &SubsystemStatus) -> impl IntoElement {
let (color, text) = match status {
SubsystemStatus::Stopped => (COLOR_TEXT_MUTED, "Arrêté"),
SubsystemStatus::Disabled => (COLOR_TEXT_MUTED, "OFF"),
SubsystemStatus::Starting => (COLOR_ORANGE, "Démarrage..."),
SubsystemStatus::Running(_) => (COLOR_GREEN, "Actif"),
SubsystemStatus::Warning(_) => (COLOR_ORANGE, "Attention"),
SubsystemStatus::Error(_) => (COLOR_RED, "Erreur"),
};
div()
.flex()
.items_center()
.gap_1p5()
.px_2()
.py_0p5()
.bg(rgb(COLOR_SURFACE_ELEVATED))
.border_1()
.border_color(rgb(COLOR_BORDER_SUBTLE))
.rounded_md()
.child(
div()
.w(px(6.0))
.h(px(6.0))
.rounded_full()
.bg(rgb(color)),
)
.child(
div()
.text_xs()
.font_weight(gpui::FontWeight::SEMIBOLD)
.child(label.to_string()),
)
.child(
div()
.text_xs()
.text_color(rgb(color))
.child(text.to_string()),
)
}
pub(super) fn render_toggle_pill(&self, label: &str, is_on: bool, on_color: gpui::Rgba) -> impl IntoElement {
div()
.flex()
.items_center()
.gap_1p5()
.px_2()
.py_0p5()
.bg(if is_on { rgb(0x132320) } else { rgb(COLOR_SURFACE_ELEVATED) })
.border_1()
.border_color(if is_on { on_color } else { rgb(COLOR_BORDER_SUBTLE) })
.rounded_md()
.text_xs()
.font_weight(gpui::FontWeight::SEMIBOLD)
.text_color(if is_on { on_color } else { rgb(COLOR_TEXT_MUTED) })
.child(format!("{} : {}", label, if is_on { "ON" } else { "OFF" }))
}
pub(super) fn render_monitor_progress_bar(
&self,
label: &str,
pct: u8,
crsf: u16,
bar_color: u32,
) -> impl IntoElement {
let frac = (pct as f32 / 100.0).clamp(0.0, 1.0);
div()
.flex()
.flex_col()
.gap_0p5()
.child(
div()
.flex()
.justify_between()
.text_xs()
.child(div().text_color(rgb(COLOR_TEXT_MAIN)).child(label.to_string()))
.child(
div()
.text_color(rgb(COLOR_TEXT_MUTED))
.child(format!("{:3}% | CRSF {}", pct, crsf)),
),
)
.child(
div()
.w_full()
.h(px(7.0))
.bg(rgb(COLOR_SURFACE_CARD))
.border_1()
.border_color(rgb(COLOR_BORDER_SUBTLE))
.rounded_full()
.overflow_hidden()
.child(
div()
.h_full()
.w(DefiniteLength::Fraction(frac))
.bg(rgb(bar_color)),
),
)
}
pub(super) fn render_monitor_bipolar_bar(
&self,
label: &str,
pct_signed: f32,
crsf: u16,
bar_color: u32,
) -> impl IntoElement {
let clamped = pct_signed.clamp(-100.0, 100.0);
let left_frac = if clamped < 0.0 {
(-clamped / 100.0).clamp(0.0, 1.0)
} else {
0.0
};
let right_frac = if clamped > 0.0 {
(clamped / 100.0).clamp(0.0, 1.0)
} else {
0.0
};
div()
.flex()
.flex_col()
.gap_0p5()
.child(
div()
.flex()
.justify_between()
.text_xs()
.child(div().text_color(rgb(COLOR_TEXT_MAIN)).child(label.to_string()))
.child(
div()
.text_color(rgb(COLOR_TEXT_MUTED))
.child(format!("{:+.0}% | CRSF {}", clamped, crsf)),
),
)
.child(
div()
.flex()
.items_center()
.w_full()
.h(px(8.0))
.bg(rgb(COLOR_SURFACE_CARD))
.border_1()
.border_color(rgb(COLOR_BORDER_SUBTLE))
.rounded_full()
.overflow_hidden()
// Moitié gauche (remplissage depuis le centre vers la gauche)
.child(
div()
.flex()
.justify_end()
.w(DefiniteLength::Fraction(0.5))
.h_full()
.child(
div()
.h_full()
.w(DefiniteLength::Fraction(left_frac))
.bg(rgb(bar_color)),
),
)
// Repère central
.child(div().w(px(2.0)).h_full().bg(rgb(COLOR_TEXT_MUTED)))
// Moitié droite (remplissage depuis le centre vers la droite)
.child(
div()
.flex()
.justify_start()
.w(DefiniteLength::Fraction(0.5))
.h_full()
.child(
div()
.h_full()
.w(DefiniteLength::Fraction(right_frac))
.bg(rgb(bar_color)),
),
),
)
}
pub(super) fn render_crsf_gauge(&self, label: &str, deg: f32, crsf: u16, max_deg: f32) -> impl IntoElement {
let safe_max = max_deg.max(1.0);
let safe_deg = if deg.is_finite() { deg } else { 0.0 };
let norm = ((safe_deg / safe_max) * 0.5 + 0.5).clamp(0.0, 1.0);
div()
.flex()
.flex_col()
.gap_0p5()
.child(
div()
.flex()
.justify_between()
.text_xs()
.child(label.to_string())
.child(format!("{:+.1}° (CRSF: {})", safe_deg, crsf)),
)
.child(
div()
.w_full()
.h(px(6.0))
.bg(rgb(COLOR_SURFACE_CARD))
.border_1()
.border_color(rgb(COLOR_BORDER_SUBTLE))
.rounded_full()
.overflow_hidden()
.child(
div()
.h_full()
.w(DefiniteLength::Fraction(norm))
.bg(rgb(COLOR_ORANGE)),
),
)
}
}
+736 -120
View File
File diff suppressed because it is too large. Load diff
+864
View File
@@ -0,0 +1,864 @@
use anyhow::{anyhow, Context, Result};
use ash::vk;
use naga::back::spv;
use naga::front::wgsl;
use naga::valid::{Capabilities, ValidationFlags, Validator};
/// Réglages d'amélioration d'image temps réel + stabilisation horizon + Stéréo 3D SBS sur GPU.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GpuImageEnhanceParams {
/// Décalage luminosité (`-0.5..=0.5`, défaut `0.0`).
pub brightness: f32,
/// Multiplicateur contraste (`0.5..=2.0`, défaut `1.0`).
pub contrast: f32,
/// Correction gamma (`0.5..=2.2`, défaut `1.0`).
pub gamma: f32,
/// Netteté adaptative CAS-lite (`0.0..=1.0`, défaut `0.0`).
pub sharpness: f32,
/// Angle de compensation de roulis horizon en radians (0.0 = désactivé).
pub horizon_roll_rad: f32,
/// Mode Caméra 3D Stéréo Side-by-Side (warp optique & horizon appliqués par moitié G/D).
pub stereo_sbs: bool,
}
impl Default for GpuImageEnhanceParams {
fn default() -> Self {
Self {
brightness: 0.0,
contrast: 1.0,
gamma: 1.0,
sharpness: 0.0,
horizon_roll_rad: 0.0,
stereo_sbs: false,
}
}
}
/// Paramètres uniformes poussés au compute shader Vulkan via push constants (64 octets).
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct GpuWarpPushConstants {
pub width: u32,
pub height: u32,
/// Bit 0 : NV12 ; Bit 1 : swap R/B ; Bit 2 : warp optique ; Bit 3 : Stereo SBS ; Bit 4 : CAS sharpness
pub format_flags: u32,
/// Stride plan Y (ou RGBA) en octets (0 = compact `width` pour NV12 ou `width*4` pour RGBA)
pub src_stride_y: u32,
pub k1: f32,
pub k2: f32,
pub fov_scale: f32,
pub aspect: f32,
pub brightness: f32,
pub contrast: f32,
pub gamma: f32,
pub sharpness: f32,
pub horizon_roll_rad: f32,
/// Offset en octets du plan UV pour NV12 (0 = `width * height`)
pub uv_offset_bytes: u32,
/// Stride plan UV en octets pour NV12 (0 = `width`)
pub src_stride_uv: u32,
pub _pad3: u32,
}
impl GpuWarpPushConstants {
#[allow(clippy::too_many_arguments)]
pub fn new(
width: u32,
height: u32,
is_nv12: bool,
swap_rb: bool,
k1: f32,
k2: f32,
fov_deg: f32,
enhance: GpuImageEnhanceParams,
) -> Self {
Self::with_strides(
width, height, is_nv12, swap_rb, k1, k2, fov_deg, enhance, 0, 0, 0,
)
}
#[allow(clippy::too_many_arguments)]
pub fn with_strides(
width: u32,
height: u32,
is_nv12: bool,
swap_rb: bool,
k1: f32,
k2: f32,
fov_deg: f32,
enhance: GpuImageEnhanceParams,
src_stride_y: u32,
uv_offset_bytes: u32,
src_stride_uv: u32,
) -> Self {
let warp_enabled =
k1.abs() > 1e-4 || k2.abs() > 1e-4 || enhance.horizon_roll_rad.abs() > 1e-4;
let sharp_enabled = enhance.sharpness > 1e-3;
let mut flags = 0u32;
if is_nv12 {
flags |= 1;
}
if swap_rb {
flags |= 2;
}
if warp_enabled {
flags |= 4;
}
if enhance.stereo_sbs {
flags |= 8;
}
if sharp_enabled {
flags |= 16;
}
let effective_w = if enhance.stereo_sbs {
(width / 2).max(1)
} else {
width.max(1)
};
let aspect = if height > 0 {
effective_w as f32 / height as f32
} else {
16.0 / 9.0
};
let fov_scale = (fov_deg.clamp(60.0, 180.0) / 140.0).clamp(0.75, 1.15);
Self {
width,
height,
format_flags: flags,
src_stride_y,
k1,
k2,
fov_scale,
aspect,
brightness: enhance.brightness.clamp(-0.5, 0.5),
contrast: enhance.contrast.clamp(0.5, 2.0),
gamma: enhance.gamma.clamp(0.5, 2.2),
sharpness: enhance.sharpness.clamp(0.0, 1.0),
horizon_roll_rad: enhance.horizon_roll_rad.clamp(-0.8, 0.8),
uv_offset_bytes,
src_stride_uv,
_pad3: 0,
}
}
pub fn as_bytes(&self) -> &[u8] {
// SAFETY: `GpuWarpPushConstants` est `#[repr(C)]` composé uniquement de u32/f32 sans padding non initialisé.
unsafe {
std::slice::from_raw_parts(
(self as *const Self) as *const u8,
std::mem::size_of::<Self>(),
)
}
}
}
/// Shader WGSL de conversion NV12/RGBA -> RGBA/BGRA avec :
/// - Lecture stride-aware compatible buffers staging et DMA-BUF linéaires,
/// - Dé-distorsion optique radiale bilinéaire (`k1`, `k2`, FOV),
/// - Compensation de roulis horizon CRSF (rotation 2D),
/// - Support Stéréo 3D Side-by-Side (warp indépendant par moitié G/D sans fuite de bord),
/// - Amélioration d'image temps réel (CAS-lite netteté, luminosité, contraste, gamma).
const NV12_WARP_WGSL: &str = r#"
struct WarpParams {
width: u32,
height: u32,
format_flags: u32,
src_stride_y: u32,
k1: f32,
k2: f32,
fov_scale: f32,
aspect: f32,
brightness: f32,
contrast: f32,
gamma: f32,
sharpness: f32,
horizon_roll_rad: f32,
uv_offset_bytes: u32,
src_stride_uv: u32,
_pad3: u32,
};
var<push_constant> params: WarpParams;
@group(0) @binding(0)
var<storage, read> src_words: array<u32>;
@group(0) @binding(1)
var dst_img: texture_storage_2d<rgba8unorm, write>;
fn read_byte(byte_idx: u32) -> f32 {
let w = src_words[byte_idx >> 2u];
let shift = (byte_idx & 3u) * 8u;
return f32((w >> shift) & 0xFFu) / 255.0;
}
fn fetch_rgba(x: u32, y: u32) -> vec4<f32> {
let stride = select(params.width * 4u, params.src_stride_y, params.src_stride_y > 0u);
let byte_idx = y * stride + x * 4u;
let w = src_words[byte_idx >> 2u];
let r = f32(w & 0xFFu) / 255.0;
let g = f32((w >> 8u) & 0xFFu) / 255.0;
let b = f32((w >> 16u) & 0xFFu) / 255.0;
let a = f32((w >> 24u) & 0xFFu) / 255.0;
return vec4<f32>(r, g, b, a);
}
fn fetch_nv12(x: u32, y: u32) -> vec4<f32> {
let stride_y = select(params.width, params.src_stride_y, params.src_stride_y > 0u);
let uv_off = select(params.width * params.height, params.uv_offset_bytes, params.uv_offset_bytes > 0u);
let stride_uv = select(params.width, params.src_stride_uv, params.src_stride_uv > 0u);
let y_idx = y * stride_y + x;
let y_val = read_byte(y_idx);
let uv_base = uv_off + (y >> 1u) * stride_uv + ((x >> 1u) << 1u);
let u_val = read_byte(uv_base) - 0.5;
let v_val = read_byte(uv_base + 1u) - 0.5;
// Conversion BT.709 (standard HD 720p/1080p OpenIPC / H.264 / H.265)
let y_scaled = max(y_val - 0.062745, 0.0) * 1.164383;
let r = clamp(y_scaled + 1.792741 * v_val, 0.0, 1.0);
let g = clamp(y_scaled - 0.213249 * u_val - 0.532909 * v_val, 0.0, 1.0);
let b = clamp(y_scaled + 2.112402 * u_val, 0.0, 1.0);
return vec4<f32>(r, g, b, 1.0);
}
fn sample_pixel(x: u32, y: u32, is_nv12: bool) -> vec4<f32> {
if (is_nv12) {
return fetch_nv12(x, y);
}
return fetch_rgba(x, y);
}
fn sample_clamped_bilinear(src_u: f32, src_v: f32, min_x: u32, max_x: u32, is_nv12: bool) -> vec4<f32> {
let u_clamped = clamp(src_u, f32(min_x), f32(max_x));
let v_clamped = clamp(src_v, 0.0, f32(params.height - 1u));
let x0 = u32(floor(u_clamped));
let y0 = u32(floor(v_clamped));
let x1 = min(x0 + 1u, max_x);
let y1 = min(y0 + 1u, params.height - 1u);
let fx = u_clamped - f32(x0);
let fy = v_clamped - f32(y0);
let c00 = sample_pixel(x0, y0, is_nv12);
let c10 = sample_pixel(x1, y0, is_nv12);
let c01 = sample_pixel(x0, y1, is_nv12);
let c11 = sample_pixel(x1, y1, is_nv12);
let top = mix(c00, c10, fx);
let bot = mix(c01, c11, fx);
return mix(top, bot, fy);
}
@compute @workgroup_size(16, 16, 1)
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
if (gid.x >= params.width || gid.y >= params.height) {
return;
}
let is_nv12 = (params.format_flags & 1u) != 0u;
let swap_rb = (params.format_flags & 2u) != 0u;
let warp_on = (params.format_flags & 4u) != 0u;
let is_sbs = (params.format_flags & 8u) != 0u;
let sharp_on = (params.format_flags & 16u) != 0u;
// Domaine horizontal effectif (image entière ou moitié gauche/droite en Stéréo SBS)
var min_x: u32 = 0u;
var max_x: u32 = params.width - 1u;
var region_w: u32 = params.width;
if (is_sbs && params.width >= 2u) {
let half_w = params.width >> 1u;
if (gid.x < half_w) {
min_x = 0u;
max_x = half_w - 1u;
region_w = half_w;
} else {
min_x = half_w;
max_x = params.width - 1u;
region_w = params.width - half_w;
}
}
var color: vec4<f32>;
var sample_x: u32 = gid.x;
var sample_y: u32 = gid.y;
if (!warp_on) {
color = sample_pixel(gid.x, gid.y, is_nv12);
} else {
let fw = f32(region_w);
let fh = f32(params.height);
let local_x = f32(gid.x - min_x);
var nx = ((local_x + 0.5) / fw) * 2.0 - 1.0;
var ny = ((f32(gid.y) + 0.5) / fh) * 2.0 - 1.0;
// Compensation de roulis horizon CRSF (rotation 2D compensée par l'aspect)
if (abs(params.horizon_roll_rad) > 0.0001) {
let ca = cos(params.horizon_roll_rad);
let sa = sin(params.horizon_roll_rad);
let ax = nx * params.aspect;
let ay = ny;
nx = (ax * ca - ay * sa) / max(params.aspect, 0.01);
ny = ax * sa + ay * ca;
}
let max_a = max(params.aspect, 1.0);
let rx = nx * (params.aspect / max_a);
let ry = ny / max_a;
let r2 = min(rx * rx + ry * ry, 1.5);
let r4 = r2 * r2;
let poly = clamp(1.0 + params.k1 * r2 + params.k2 * r4, 0.25, 2.5);
let factor = poly / params.fov_scale;
let src_u = f32(min_x) + clamp((nx * factor + 1.0) * 0.5, 0.0, 1.0) * (fw - 1.0);
let src_v = clamp((ny * factor + 1.0) * 0.5, 0.0, 1.0) * (fh - 1.0);
sample_x = u32(clamp(round(src_u), f32(min_x), f32(max_x)));
sample_y = u32(clamp(round(src_v), 0.0, fh - 1.0));
color = sample_clamped_bilinear(src_u, src_v, min_x, max_x, is_nv12);
}
// Netteté adaptative CAS-lite (unsharp mask 5-taps avec clamping anti-halo)
if (sharp_on) {
let xl = select(sample_x - 1u, min_x, sample_x <= min_x);
let xr = min(sample_x + 1u, max_x);
let yu = select(sample_y - 1u, 0u, sample_y == 0u);
let yd = min(sample_y + 1u, params.height - 1u);
let n_l = sample_pixel(xl, sample_y, is_nv12).rgb;
let n_r = sample_pixel(xr, sample_y, is_nv12).rgb;
let n_u = sample_pixel(sample_x, yu, is_nv12).rgb;
let n_d = sample_pixel(sample_x, yd, is_nv12).rgb;
let blur = (n_l + n_r + n_u + n_d) * 0.25;
let lo = min(color.rgb, min(min(n_l, n_r), min(n_u, n_d)));
let hi = max(color.rgb, max(max(n_l, n_r), max(n_u, n_d)));
let sharp_rgb = color.rgb + (color.rgb - blur) * (params.sharpness * 1.4);
// Borne anti-ringing proche du voisinage local
let clamped = clamp(sharp_rgb, lo - vec3<f32>(0.08), hi + vec3<f32>(0.08));
color = vec4<f32>(clamp(clamped, vec3<f32>(0.0), vec3<f32>(1.0)), color.a);
}
// Luminosité, contraste & correction gamma temps réel
if (abs(params.brightness) > 0.001 || abs(params.contrast - 1.0) > 0.001 || abs(params.gamma - 1.0) > 0.001) {
var rgb = (color.rgb - vec3<f32>(0.5)) * params.contrast + vec3<f32>(0.5 + params.brightness);
rgb = clamp(rgb, vec3<f32>(0.0), vec3<f32>(1.0));
if (abs(params.gamma - 1.0) > 0.001) {
let inv_g = 1.0 / max(params.gamma, 0.1);
rgb = pow(rgb, vec3<f32>(inv_g));
}
color = vec4<f32>(rgb, color.a);
}
if (swap_rb) {
color = vec4<f32>(color.b, color.g, color.r, color.a);
}
textureStore(dst_img, vec2<i32>(i32(gid.x), i32(gid.y)), color);
}
"#;
/// Compile le shader WGSL en mots SPIR-V (Vulkan 1.1) via `naga` (0 outil externe requis).
pub fn compile_warp_shader_spirv() -> Result<Vec<u32>> {
let module = wgsl::parse_str(NV12_WARP_WGSL).map_err(|e| {
anyhow!(
"Erreur parsing WGSL shader warp : {}",
e.emit_to_string(NV12_WARP_WGSL)
)
})?;
let mut validator = Validator::new(ValidationFlags::all(), Capabilities::PUSH_CONSTANT);
let info = validator
.validate(&module)
.context("Échec validation Naga du shader compute NV12/Warp")?;
let options = spv::Options {
lang_version: (1, 3),
flags: spv::WriterFlags::empty(),
..Default::default()
};
let words = spv::write_vec(&module, &info, &options, None)
.context("Échec génération SPIR-V du shader compute NV12/Warp")?;
Ok(words)
}
/// Pipeline Vulkan Compute autonome : conversion NV12/RGBA + dé-distorsion bilinéaire +
/// amélioration d'image (CAS/luminosité/contraste/gamma/horizon/SBS) vers une image `DEVICE_LOCAL`.
/// Possède 2 descriptor sets permanents (slots staging) + 1 descriptor set dynamique pour DMA-BUF.
pub struct VulkanWarpPipeline {
pub descriptor_set_layout: vk::DescriptorSetLayout,
pub pipeline_layout: vk::PipelineLayout,
pub pipeline: vk::Pipeline,
pub descriptor_pool: vk::DescriptorPool,
pub descriptor_sets: [vk::DescriptorSet; 2],
pub external_descriptor_set: vk::DescriptorSet,
pub output_image: vk::Image,
pub output_memory: vk::DeviceMemory,
pub output_view: vk::ImageView,
pub width: u32,
pub height: u32,
}
impl VulkanWarpPipeline {
pub fn new(
vk_instance: &ash::Instance,
phys_device: vk::PhysicalDevice,
vk_device: &ash::Device,
staging_buffers: [vk::Buffer; 2],
staging_size: u64,
width: u32,
height: u32,
) -> Result<Self> {
let spirv = compile_warp_shader_spirv()?;
let img_info = vk::ImageCreateInfo::default()
.image_type(vk::ImageType::TYPE_2D)
.format(vk::Format::R8G8B8A8_UNORM)
.extent(vk::Extent3D {
width,
height,
depth: 1,
})
.mip_levels(1)
.array_layers(1)
.samples(vk::SampleCountFlags::TYPE_1)
.tiling(vk::ImageTiling::OPTIMAL)
.usage(vk::ImageUsageFlags::STORAGE | vk::ImageUsageFlags::TRANSFER_SRC)
.sharing_mode(vk::SharingMode::EXCLUSIVE)
.initial_layout(vk::ImageLayout::UNDEFINED);
let output_image = unsafe { vk_device.create_image(&img_info, None)? };
let mem_reqs = unsafe { vk_device.get_image_memory_requirements(output_image) };
let mem_props = unsafe { vk_instance.get_physical_device_memory_properties(phys_device) };
let mem_type = (0..mem_props.memory_type_count)
.find(|&i| {
(mem_reqs.memory_type_bits & (1 << i)) != 0
&& mem_props.memory_types[i as usize]
.property_flags
.contains(vk::MemoryPropertyFlags::DEVICE_LOCAL)
})
.or_else(|| {
(0..mem_props.memory_type_count)
.find(|&i| (mem_reqs.memory_type_bits & (1 << i)) != 0)
})
.ok_or_else(|| anyhow!("Aucune mémoire Vulkan disponible pour l'image warp GPU"))?;
let alloc = vk::MemoryAllocateInfo::default()
.allocation_size(mem_reqs.size)
.memory_type_index(mem_type);
let output_memory = unsafe {
match vk_device.allocate_memory(&alloc, None) {
Ok(m) => m,
Err(e) => {
vk_device.destroy_image(output_image, None);
return Err(e.into());
}
}
};
if let Err(e) = unsafe { vk_device.bind_image_memory(output_image, output_memory, 0) } {
unsafe {
vk_device.destroy_image(output_image, None);
vk_device.free_memory(output_memory, None);
}
return Err(e.into());
}
let view_info = vk::ImageViewCreateInfo::default()
.image(output_image)
.view_type(vk::ImageViewType::TYPE_2D)
.format(vk::Format::R8G8B8A8_UNORM)
.subresource_range(vk::ImageSubresourceRange {
aspect_mask: vk::ImageAspectFlags::COLOR,
base_mip_level: 0,
level_count: 1,
base_array_layer: 0,
layer_count: 1,
});
let output_view = unsafe {
match vk_device.create_image_view(&view_info, None) {
Ok(v) => v,
Err(e) => {
vk_device.destroy_image(output_image, None);
vk_device.free_memory(output_memory, None);
return Err(e.into());
}
}
};
let bindings = [
vk::DescriptorSetLayoutBinding::default()
.binding(0)
.descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
.descriptor_count(1)
.stage_flags(vk::ShaderStageFlags::COMPUTE),
vk::DescriptorSetLayoutBinding::default()
.binding(1)
.descriptor_type(vk::DescriptorType::STORAGE_IMAGE)
.descriptor_count(1)
.stage_flags(vk::ShaderStageFlags::COMPUTE),
];
let ds_layout_info = vk::DescriptorSetLayoutCreateInfo::default().bindings(&bindings);
let descriptor_set_layout =
unsafe { vk_device.create_descriptor_set_layout(&ds_layout_info, None)? };
let push_range = [vk::PushConstantRange {
stage_flags: vk::ShaderStageFlags::COMPUTE,
offset: 0,
size: std::mem::size_of::<GpuWarpPushConstants>() as u32,
}];
let layouts = [descriptor_set_layout];
let pl_info = vk::PipelineLayoutCreateInfo::default()
.set_layouts(&layouts)
.push_constant_ranges(&push_range);
let pipeline_layout = unsafe { vk_device.create_pipeline_layout(&pl_info, None)? };
let shader_info = vk::ShaderModuleCreateInfo::default().code(&spirv);
let shader_module = unsafe { vk_device.create_shader_module(&shader_info, None)? };
let entry_name = std::ffi::CString::new("main")?;
let stage_info = vk::PipelineShaderStageCreateInfo::default()
.stage(vk::ShaderStageFlags::COMPUTE)
.module(shader_module)
.name(&entry_name);
let cp_info = [vk::ComputePipelineCreateInfo::default()
.stage(stage_info)
.layout(pipeline_layout)];
let pipeline_res = unsafe {
vk_device.create_compute_pipelines(vk::PipelineCache::null(), &cp_info, None)
};
unsafe { vk_device.destroy_shader_module(shader_module, None) };
let pipeline = match pipeline_res {
Ok(mut pipes) => pipes.remove(0),
Err((_, e)) => {
unsafe {
vk_device.destroy_pipeline_layout(pipeline_layout, None);
vk_device.destroy_descriptor_set_layout(descriptor_set_layout, None);
vk_device.destroy_image_view(output_view, None);
vk_device.destroy_image(output_image, None);
vk_device.free_memory(output_memory, None);
}
return Err(anyhow!("Échec création ComputePipeline Vulkan warp : {}", e));
}
};
let pool_sizes = [
vk::DescriptorPoolSize {
ty: vk::DescriptorType::STORAGE_BUFFER,
descriptor_count: 3,
},
vk::DescriptorPoolSize {
ty: vk::DescriptorType::STORAGE_IMAGE,
descriptor_count: 3,
},
];
let pool_info = vk::DescriptorPoolCreateInfo::default()
.max_sets(3)
.pool_sizes(&pool_sizes);
let descriptor_pool = unsafe { vk_device.create_descriptor_pool(&pool_info, None)? };
let set_layouts = [
descriptor_set_layout,
descriptor_set_layout,
descriptor_set_layout,
];
let alloc_sets = vk::DescriptorSetAllocateInfo::default()
.descriptor_pool(descriptor_pool)
.set_layouts(&set_layouts);
let sets_vec = unsafe { vk_device.allocate_descriptor_sets(&alloc_sets)? };
let descriptor_sets = [sets_vec[0], sets_vec[1]];
let external_descriptor_set = sets_vec[2];
for (i, &ds) in descriptor_sets.iter().enumerate() {
let buf_info = [vk::DescriptorBufferInfo {
buffer: staging_buffers[i],
offset: 0,
range: staging_size,
}];
let img_desc = [vk::DescriptorImageInfo {
sampler: vk::Sampler::null(),
image_view: output_view,
image_layout: vk::ImageLayout::GENERAL,
}];
let writes = [
vk::WriteDescriptorSet::default()
.dst_set(ds)
.dst_binding(0)
.descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
.buffer_info(&buf_info),
vk::WriteDescriptorSet::default()
.dst_set(ds)
.dst_binding(1)
.descriptor_type(vk::DescriptorType::STORAGE_IMAGE)
.image_info(&img_desc),
];
unsafe { vk_device.update_descriptor_sets(&writes, &[]) };
}
// Initialise le binding image de sortie sur le 3e descriptor set (DMA-BUF)
let ext_img_desc = [vk::DescriptorImageInfo {
sampler: vk::Sampler::null(),
image_view: output_view,
image_layout: vk::ImageLayout::GENERAL,
}];
let ext_write = [vk::WriteDescriptorSet::default()
.dst_set(external_descriptor_set)
.dst_binding(1)
.descriptor_type(vk::DescriptorType::STORAGE_IMAGE)
.image_info(&ext_img_desc)];
unsafe { vk_device.update_descriptor_sets(&ext_write, &[]) };
log::info!(
"[VulkanWarp] Compute shader GPU initialisé ({}x{}, SPIR-V {} mots, CAS/Horizon/SBS/DMA-BUF prêts).",
width,
height,
spirv.len()
);
Ok(Self {
descriptor_set_layout,
pipeline_layout,
pipeline,
descriptor_pool,
descriptor_sets,
external_descriptor_set,
output_image,
output_memory,
output_view,
width,
height,
})
}
/// Lie un `VkBuffer` externe (import DMA-BUF) sur le 3e descriptor set avant dispatch.
///
/// # Safety
/// Le buffer doit rester vivant jusqu'à complétion de la fence du command buffer.
pub unsafe fn bind_external_buffer(
&self,
vk_device: &ash::Device,
external_buffer: vk::Buffer,
size: u64,
) {
let buf_info = [vk::DescriptorBufferInfo {
buffer: external_buffer,
offset: 0,
range: size,
}];
let writes = [vk::WriteDescriptorSet::default()
.dst_set(self.external_descriptor_set)
.dst_binding(0)
.descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
.buffer_info(&buf_info)];
vk_device.update_descriptor_sets(&writes, &[]);
}
/// Enregistre la passe Compute (NV12/RGBA + Warp bilinéaire + Enhance) sur le slot staging `slot_idx`.
///
/// # Safety
/// `cmd` doit être en état recording et `target_image` doit être une image Swapchain valide de taille `width x height`.
pub unsafe fn record_warp_and_copy(
&self,
vk_device: &ash::Device,
cmd: vk::CommandBuffer,
slot_idx: usize,
target_image: vk::Image,
push: &GpuWarpPushConstants,
) {
self.record_warp_and_copy_with_ds(
vk_device,
cmd,
self.descriptor_sets[slot_idx % 2],
target_image,
push,
);
}
/// Enregistre la passe Compute à partir d'un descriptor set externe (ex. DMA-BUF zéro-copie).
///
/// # Safety
/// `cmd` doit être en état recording et `external_descriptor_set` doit pointer vers un buffer valide.
pub unsafe fn record_warp_and_copy_external(
&self,
vk_device: &ash::Device,
cmd: vk::CommandBuffer,
target_image: vk::Image,
push: &GpuWarpPushConstants,
) {
self.record_warp_and_copy_with_ds(
vk_device,
cmd,
self.external_descriptor_set,
target_image,
push,
);
}
unsafe fn record_warp_and_copy_with_ds(
&self,
vk_device: &ash::Device,
cmd: vk::CommandBuffer,
descriptor_set: vk::DescriptorSet,
target_image: vk::Image,
push: &GpuWarpPushConstants,
) {
let subresource = vk::ImageSubresourceRange {
aspect_mask: vk::ImageAspectFlags::COLOR,
base_mip_level: 0,
level_count: 1,
base_array_layer: 0,
layer_count: 1,
};
// 1. Transition output_image -> GENERAL (pour écriture Compute Storage)
let barrier_out_general = vk::ImageMemoryBarrier::default()
.old_layout(vk::ImageLayout::UNDEFINED)
.new_layout(vk::ImageLayout::GENERAL)
.src_access_mask(vk::AccessFlags::empty())
.dst_access_mask(vk::AccessFlags::SHADER_WRITE)
.image(self.output_image)
.subresource_range(subresource);
vk_device.cmd_pipeline_barrier(
cmd,
vk::PipelineStageFlags::TOP_OF_PIPE,
vk::PipelineStageFlags::COMPUTE_SHADER,
vk::DependencyFlags::empty(),
&[],
&[],
&[barrier_out_general],
);
// 2. Exécution Compute Shader (groupes 16x16)
vk_device.cmd_bind_pipeline(cmd, vk::PipelineBindPoint::COMPUTE, self.pipeline);
vk_device.cmd_bind_descriptor_sets(
cmd,
vk::PipelineBindPoint::COMPUTE,
self.pipeline_layout,
0,
&[descriptor_set],
&[],
);
vk_device.cmd_push_constants(
cmd,
self.pipeline_layout,
vk::ShaderStageFlags::COMPUTE,
0,
push.as_bytes(),
);
vk_device.cmd_dispatch(cmd, self.width.div_ceil(16), self.height.div_ceil(16), 1);
// 3. Barrières : output_image -> TRANSFER_SRC_OPTIMAL, target_image -> TRANSFER_DST_OPTIMAL
let barriers_copy = [
vk::ImageMemoryBarrier::default()
.old_layout(vk::ImageLayout::GENERAL)
.new_layout(vk::ImageLayout::TRANSFER_SRC_OPTIMAL)
.src_access_mask(vk::AccessFlags::SHADER_WRITE)
.dst_access_mask(vk::AccessFlags::TRANSFER_READ)
.image(self.output_image)
.subresource_range(subresource),
vk::ImageMemoryBarrier::default()
.old_layout(vk::ImageLayout::UNDEFINED)
.new_layout(vk::ImageLayout::TRANSFER_DST_OPTIMAL)
.src_access_mask(vk::AccessFlags::empty())
.dst_access_mask(vk::AccessFlags::TRANSFER_WRITE)
.image(target_image)
.subresource_range(subresource),
];
vk_device.cmd_pipeline_barrier(
cmd,
vk::PipelineStageFlags::COMPUTE_SHADER,
vk::PipelineStageFlags::TRANSFER,
vk::DependencyFlags::empty(),
&[],
&[],
&barriers_copy,
);
// 4. Copie GPU -> GPU vers l'image Swapchain OpenXR
let region = vk::ImageCopy {
src_subresource: vk::ImageSubresourceLayers {
aspect_mask: vk::ImageAspectFlags::COLOR,
mip_level: 0,
base_array_layer: 0,
layer_count: 1,
},
src_offset: vk::Offset3D { x: 0, y: 0, z: 0 },
dst_subresource: vk::ImageSubresourceLayers {
aspect_mask: vk::ImageAspectFlags::COLOR,
mip_level: 0,
base_array_layer: 0,
layer_count: 1,
},
dst_offset: vk::Offset3D { x: 0, y: 0, z: 0 },
extent: vk::Extent3D {
width: self.width,
height: self.height,
depth: 1,
},
};
vk_device.cmd_copy_image(
cmd,
self.output_image,
vk::ImageLayout::TRANSFER_SRC_OPTIMAL,
target_image,
vk::ImageLayout::TRANSFER_DST_OPTIMAL,
&[region],
);
// 5. Transition target_image -> COLOR_ATTACHMENT_OPTIMAL pour le compositeur OpenXR
let barrier_present = vk::ImageMemoryBarrier::default()
.old_layout(vk::ImageLayout::TRANSFER_DST_OPTIMAL)
.new_layout(vk::ImageLayout::COLOR_ATTACHMENT_OPTIMAL)
.src_access_mask(vk::AccessFlags::TRANSFER_WRITE)
.dst_access_mask(vk::AccessFlags::COLOR_ATTACHMENT_READ)
.image(target_image)
.subresource_range(subresource);
vk_device.cmd_pipeline_barrier(
cmd,
vk::PipelineStageFlags::TRANSFER,
vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT,
vk::DependencyFlags::empty(),
&[],
&[],
&[barrier_present],
);
}
pub unsafe fn destroy(&self, vk_device: &ash::Device) {
vk_device.destroy_descriptor_pool(self.descriptor_pool, None);
vk_device.destroy_pipeline(self.pipeline, None);
vk_device.destroy_pipeline_layout(self.pipeline_layout, None);
vk_device.destroy_descriptor_set_layout(self.descriptor_set_layout, None);
vk_device.destroy_image_view(self.output_view, None);
vk_device.destroy_image(self.output_image, None);
vk_device.free_memory(self.output_memory, None);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_compile_nv12_warp_wgsl_to_spirv() {
let words = compile_warp_shader_spirv().expect("Compilation WGSL -> SPIR-V échouée");
assert!(words.len() > 64, "SPIR-V trop court");
// Magic SPIR-V = 0x07230203
assert_eq!(words[0], 0x0723_0203);
}
#[test]
fn test_push_constants_flags_and_layout() {
let enhance = GpuImageEnhanceParams {
brightness: 0.1,
contrast: 1.2,
gamma: 0.9,
sharpness: 0.5,
horizon_roll_rad: 0.15,
stereo_sbs: true,
};
let pc = GpuWarpPushConstants::new(1280, 720, true, true, -0.14, 0.03, 140.0, enhance);
assert_eq!(pc.format_flags, 0b1_1111);
assert_eq!(pc.as_bytes().len(), 64);
// En mode Stereo SBS, l'aspect par œil vaut (1280/2)/720
assert!((pc.aspect - (640.0 / 720.0)).abs() < 0.001);
}
}
+849 -199
View File
File diff suppressed because it is too large. Load diff