mirror of
https://github.com/bleackstorm/SteamFrame-FPV-Control-Center.git
synced 2026-12-03 07:31:57 +01:00
feat: initial commit of SteamFrame FPV Control Center
This commit is contained in:
commit
4459f5ffa4
18 files changed
+8571
No files matched your search
@@ -0,0 +1,6 @@
|
|||||||
|
/target
|
||||||
|
target/
|
||||||
|
*.log
|
||||||
|
steamframe_fpv.log
|
||||||
|
*.bin
|
||||||
|
.DS_Store
|
||||||
Generated
+4663
File diff suppressed because it is too large.
Load diff
+19
@@ -0,0 +1,19 @@
|
|||||||
|
[package]
|
||||||
|
name = "steamframe-fpv"
|
||||||
|
version = "0.2.0"
|
||||||
|
edition = "2021"
|
||||||
|
description = "Application graphique et VR native Steam Frame (OpenXR + Vulkan + egui) pour Eachine Sphere Link (USB RNDIS) et Head-Tracking RadioMaster Nomad (ELRS Wi-Fi)"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
anyhow = "1.0"
|
||||||
|
ash = "0.38"
|
||||||
|
chrono = "0.4"
|
||||||
|
clap = { version = "4.5", features = ["derive"] }
|
||||||
|
eframe = { version = "0.29", default-features = true }
|
||||||
|
glam = "0.29"
|
||||||
|
gstreamer = "0.23"
|
||||||
|
gstreamer-app = "0.23"
|
||||||
|
gstreamer-video = "0.23"
|
||||||
|
log = "0.4"
|
||||||
|
openxr = { version = "0.19", features = ["loaded"] }
|
||||||
|
parking_lot = "0.12"
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
# SteamFrame FPV (`steamframe-fpv`)
|
||||||
|
|
||||||
|
Application graphique et VR native **SteamOS (Linux ARM64)** pour le casque **Steam Frame**, conçue spécifiquement pour :
|
||||||
|
- **Récepteur Eachine Sphere Link VRX** : Carte **Radxa Zero 3W** (1 Go RAM + 32 Go MicroSD, image `runcam_wifilink_sdcard.img` / `OpenIPC sbc-groundstations` ou `RubyFPV`) avec adaptateur **RTL8812EU** (`5.8 GHz`, canal par défaut **`161`**, modes **`1080P@60FPS`**, **`1080P@90FPS`** et **`720P@120FPS`**).
|
||||||
|
- **Module RadioMaster Nomad** : Envoi du suivi de tête (**Head-Tracking Pan / Tilt / Roll**) à 120 Hz par **Wi-Fi UDP** au **Backpack ExpressLRS** du Nomad.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Deux modes de branchement USB au choix (sélectionnables dans l'interface)
|
||||||
|
|
||||||
|
Comme le récepteur Eachine Sphere Link (Radxa Zero 3W) dispose d'une sortie **Mini-HDMI** et d'un port **USB-C OTG (5V)**, l'application supporte nativement les **deux méthodes** dans le panneau **`🔌 1. VRX Sphere Link (Radxa Zero 3W + 8812EU)`** :
|
||||||
|
|
||||||
|
### Option A : Via le port USB-C OTG de la Radxa Zero 3W (`Mode USB-C OTG RNDIS`)
|
||||||
|
- **Câblage** : Un simple câble USB-C entre le port **USB OTG** du VRX Sphere Link et le **Steam Frame** (alimente aussi la Radxa en 5V / 3.5W, ou utilisez une batterie 3S sur la prise DC 5.5x2.1mm).
|
||||||
|
- **Configuration en 2 clics dans l'interface** :
|
||||||
|
1. Cliquez sur **`⚡ 1. Configurer l'interface usb0 (RNDIS)`** (attribue `192.168.1.10/24` au Steam Frame).
|
||||||
|
2. Choisissez votre **Canal 5.8 GHz** (par défaut **`Canal 161`**) et votre profil (**`1080P@60`**, **`1080P@90`** ou **`720P@120`**) puis cliquez sur **`🔧 2. Appliquer Canal 161 sur la Radxa Zero 3W (SSH)`**.
|
||||||
|
|
||||||
|
### Option B : Via la sortie Mini-HDMI du VRX (`Mode Mini-HDMI -> Carte Capture USB-C UVC`)
|
||||||
|
- **Câblage** : Branchez le câble **Mini-HDMI** fourni avec le VRX sur une petite clé d'acquisition **HDMI vers USB-C UVC** (ex: MS2130 USB 3.0 1080p60 / 720p120) connectée au Steam Frame, et alimentez le VRX en 3S (prise DC 5.5x2.1mm).
|
||||||
|
- **Avantage** : **100 % Plug-and-Play** avec la carte MicroSD 32 Go préinstallée (`runcam_wifilink_sdcard.img` ou `RubyFPV`) sans aucune configuration réseau ! Sélectionnez simplement **`Mini-HDMI -> Carte Capture USB-C UVC (/dev/video0)`** dans le menu déroulant **`Mode Entrée USB`**.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Compilation et Lancement (PC Ubuntu/Debian ou SteamOS)
|
||||||
|
|
||||||
|
### 1A. Installer les paquets requis sur votre PC actuel (Ubuntu / Debian)
|
||||||
|
```bash
|
||||||
|
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 \
|
||||||
|
libxkbcommon-dev libwayland-dev libgl1-mesa-dev v4l-utils
|
||||||
|
```
|
||||||
|
|
||||||
|
### 1B. Installer les paquets requis sur le Steam Frame (SteamOS / Arch Linux)
|
||||||
|
```bash
|
||||||
|
sudo steamos-readonly disable
|
||||||
|
sudo pacman -Sy --needed base-devel pkgconf rust cargo \
|
||||||
|
gst-plugins-base gst-plugins-good gst-plugins-bad gst-libav v4l-utils \
|
||||||
|
openxr vulkan-icd-loader libxkbcommon wayland
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. Compiler le projet
|
||||||
|
```bash
|
||||||
|
cd /home/bleack/projects/steamframe_fpv
|
||||||
|
cargo build --release
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. Lancer le Centre de Contrôle Graphique
|
||||||
|
```bash
|
||||||
|
./target/release/steamframe-fpv
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Contrôles disponibles dans l'interface graphique
|
||||||
|
|
||||||
|
- **`📶 Télémétrie & OSD : OFF / ON`** : Active ou coupe à chaud la télémétrie UDP (`14551`) et l'incrustation OSD (désactivée par défaut).
|
||||||
|
- **`Canal 5.8GHz (8812EU)`** : Préconfiguré sur le **Canal 161** (5805 MHz, défaut usine du Sphere Link), avec sélection rapide des canaux `149`, `153`, `157`, `165`, `36`, `40`, `44`, `48`.
|
||||||
|
- **`Profil Résolution VRX`** : Bascule rapide entre `1080P @ 60 FPS` (défaut usine), `1080P @ 90 FPS` et `720P @ 120 FPS` (latence 40–50 ms).
|
||||||
|
- **`🎯 Recentrer la tête (Tare)`** : Réinitialise le centre des servos Pan/Tilt/Roll envoyés en Wi-Fi au **RadioMaster Nomad**.
|
||||||
|
- **`📋 Journal de Diagnostic & Erreurs`** : Affiche et enregistre dans `steamframe_fpv.log` toutes les actions et erreurs éventuelles (GStreamer, USB, Wi-Fi Nomad, OpenXR).
|
||||||
|
- **`❌ Quitter l'application`** : Arrête proprement tous les threads et ferme l'application.
|
||||||
+126
@@ -0,0 +1,126 @@
|
|||||||
|
# Rapport d'Avancement & Contexte Technique — Projet `steamframe-fpv`
|
||||||
|
|
||||||
|
> **Emplacement du projet :** `/home/bleack/projects/steamframe_fpv/`
|
||||||
|
> **Usage de ce fichier :** Fournissez ce fichier (`rapport.md`) au début d'une nouvelle conversation pour reprendre immédiatement le développement avec tout le contexte matériel et logiciel.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Objectif du Projet
|
||||||
|
|
||||||
|
Développer une application native en **Rust** (avec interface graphique de monitoring et moteur VR OpenXR/Vulkan) permettant de :
|
||||||
|
1. **Recevoir le flux vidéo en USB** depuis le récepteur **Eachine Sphere Link VRX** et l'afficher en basse latence dans le casque **Steam Frame** (ou dans la fenêtre de monitoring sur PC).
|
||||||
|
2. **Lire les mouvements de la tête (Head-Tracking Pan / Tilt / Roll)** sur l'IMU du casque Steam Frame via **OpenXR** (ou les simuler depuis l'interface sur PC) et les envoyer par **Wi-Fi UDP** au module **RadioMaster Nomad** (Backpack ExpressLRS) pour piloter une nacelle 3 axes sur le drone/avion.
|
||||||
|
3. **Monitorer, configurer et diagnostiquer les erreurs** depuis une interface graphique complète (`egui` / `eframe`) avec journalisation persistante (`steamframe_fpv.log`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Caractéristiques du Matériel Utilisé
|
||||||
|
|
||||||
|
### A. Casque VR : Valve Steam Frame
|
||||||
|
- **OS** : SteamOS (Arch Linux ARM64, KDE Plasma, Wayland).
|
||||||
|
- **SoC** : Qualcomm Snapdragon 8 Gen 3 (ARM64), 16 Go RAM.
|
||||||
|
- **Affichage** : Dual LCD `2160 × 2160` par œil, 72–120 Hz (144 Hz expérimental), lentilles Pancake (~110° FOV).
|
||||||
|
- **API VR** : OpenXR natif + Vulkan (`XR_KHR_vulkan_enable2`, `XR_KHR_composition_layer_equirect2`, `XR_KHR_composition_layer_cylinder`).
|
||||||
|
|
||||||
|
### B. Récepteur Vidéo (VRX) : Eachine Sphere Link
|
||||||
|
- **Carte SBC** : **Radxa Zero 3W** (1 Go RAM + carte MicroSD 32 Go).
|
||||||
|
- **Puce radio 5.8 GHz** : **RTL8812EU** (jusqu'à 800 mW, protocole `wfb-ng`).
|
||||||
|
- **Firmware** : `OpenIPC/sbc-groundstations` (`runcam_wifilink_sdcard.img`) et compatible `RubyFPV`.
|
||||||
|
- **Paramètres par défaut d'usine** : **Canal `161` (5805 MHz)**, résolution **`1080P @ 60 FPS`**.
|
||||||
|
- **Modes supportés** : `1080P @ 60 FPS`, `1080P @ 90 FPS`, `720P @ 120 FPS` (latence 40 à 50 ms).
|
||||||
|
- **Connectique** : Sortie `Mini-HDMI`, port `USB-C OTG (5V / ~3.5W)`, alimentation `DC 5.5×2.1 mm` (7–26V, 3S recommandé).
|
||||||
|
|
||||||
|
### C. Module Radio Émetteur : RadioMaster Nomad
|
||||||
|
- **Architecture** : Module ExpressLRS Gemini Xrossband (Double bande 2.4 GHz / 868–900 MHz).
|
||||||
|
- **Backpack Wi-Fi** : Puce secondaire **ESP32-C3** dédiée au **TX Backpack ExpressLRS** (Point d'accès Wi-Fi `10.0.0.1` par défaut).
|
||||||
|
- **Protocoles Head-Tracking supportés** :
|
||||||
|
- **MSPv2 `MSP_ELRS_BACKPACK_SET_PTR` (`0x0383`)** : Envoie 3 entiers `u16` (`Pan`, `Tilt`, `Roll` aux bornes CRSF `172..1811`, neutre `992`) avec CRC8 DVB-S2 (`0xD5`).
|
||||||
|
- **CRSF `RC_CHANNELS_PACKED` (`0x16`)** : Trame CRSF 26 octets empaquetant 16 canaux de 11 bits.
|
||||||
|
|
||||||
|
### D. Poste de Développement / Test Actuel
|
||||||
|
- **OS** : **Ubuntu 26.04.1 LTS (x86_64)** utilisé pour compiler et tester le récepteur VRX en USB et l'envoi Wi-Fi vers le Nomad avant déploiement sur le Steam Frame.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Historique de ce qui a été réalisé dans cette conversation
|
||||||
|
|
||||||
|
1. **Moteur VR OpenXR + Vulkan (`src/vulkan_xr.rs`)** :
|
||||||
|
- Initialisation dynamique d'OpenXR (`features = ["loaded"]` dans `Cargo.toml` pour compiler et tourner sur PC même sans SteamVR installé).
|
||||||
|
- Création du `XrSwapchain` Vulkan et transfert DMA haute vitesse via un *Staging Buffer* (`HOST_VISIBLE | HOST_COHERENT`).
|
||||||
|
2. **Projection Dôme 140° & Dé-distorsion Optique (`src/dome_projection.rs`)** :
|
||||||
|
- Support des couches OpenXR **`Dome140` (`XrCompositionLayerEquirect2KHR`)**, **`Cylinder140` (`XrCompositionLayerCylinderKHR`)** et **`FlatQuad` (`XrCompositionLayerQuad`)** verrouillées sur `view_space`.
|
||||||
|
- Précalcul d'une table de correspondance (`DomeWarpLut`, paramètres `lens_k1 = -0.14`, `lens_k2 = 0.03`, `camera_fov_deg = 140.0`) pour corriger la distorsion en barillet de la lentille M12 140° du Sphere Link.
|
||||||
|
3. **Réception Vidéo USB Bimode pour la Radxa Zero 3W (`src/video_usb.rs`)** :
|
||||||
|
- **Mode 1 (`rndis`)** : Réception du flux RTP H.265/H.264 via le port USB-C OTG (`udpsrc port=5600`).
|
||||||
|
- **Mode 2 (`uvc`)** : Réception directe depuis la sortie Mini-HDMI de la Radxa via une carte de capture HDMI $\rightarrow$ USB-C UVC (`v4l2src device=/dev/video0`), 100 % Plug-and-Play avec la carte SD d'origine.
|
||||||
|
- Surveillance active du Bus GStreamer pour capturer et logger toutes les erreurs de décodage ou de réseau.
|
||||||
|
- Génération d'une mire d'attente FPV animée tant qu'aucun flux vidéo n'est reçu.
|
||||||
|
4. **Suivi de Tête Wi-Fi vers RadioMaster Nomad (`src/nomad_elrs.rs`)** :
|
||||||
|
- Lecture du quaternion absolu de la tête dans `local_space`, calcul des angles relatifs (Tare / Recentrage), conversion en valeurs CRSF 11 bits (`172..1811`) et envoi UDP non-bloquant (port `14550`).
|
||||||
|
5. **Télémétrie & OSD Optionnels avec Bouton ON/OFF à Chaud (`src/telemetry_osd.rs` & `src/engine.rs`)** :
|
||||||
|
- Décodeur automatique UDP (`port 14551`) reconnaissant **MAVLink v1 (`0xFE`)**, **MAVLink v2 (`0xFD`)** et **CRSF (`0xC8`/`0xEA`/`0xEE`)**.
|
||||||
|
- Rendu HUD OSD : Tension/Courant/`%` Batterie, `LQ %` & `RSSI dBm`, Vitesse, Altitude, Vario, **Horizon Artificiel** et **Radar Nacelle Pan/Tilt**.
|
||||||
|
- **Optionnel (OFF par défaut)** : Pilotable en temps réel via un bouton **`📶 Télémétrie & OSD : ON / OFF`** dans l'interface qui ouvre ou ferme dynamiquement le socket UDP `14551`.
|
||||||
|
6. **Interface Graphique de Monitoring & Diagnostic (`src/gui.rs`, `src/engine.rs`, `src/logger.rs`)** :
|
||||||
|
- **Bascule automatique en Mode Bureau** si aucun casque OpenXR n'est actif (permet de tester la vidéo USB et les servos du Nomad avec des curseurs sur le PC Ubuntu).
|
||||||
|
- **Réglages dédiés Radxa Zero 3W (`8812EU`)** : Choix du canal 5.8 GHz (`Canal 161` par défaut), du profil vidéo (`1080p60`, `1080p90`, `720p120`), bouton de configuration `usb0` et bouton d'application du canal en SSH.
|
||||||
|
- **Panneau de logs d'erreurs** en bas de la fenêtre + sauvegarde dans `steamframe_fpv.log`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Arborescence des Fichiers (`/home/bleack/projects/steamframe_fpv/`)
|
||||||
|
|
||||||
|
```text
|
||||||
|
/home/bleack/projects/steamframe_fpv/
|
||||||
|
├── Cargo.toml # Dépendances Rust (eframe, openxr loaded, ash, gstreamer, glam, clap, chrono)
|
||||||
|
├── README.md # Documentation utilisateur et guide d'installation
|
||||||
|
├── rapport.md # Ce rapport d'historique et de contexte
|
||||||
|
├── scripts/
|
||||||
|
│ ├── setup_usb_rndis.sh # Diagnostic lsusb et configuration de l'interface usb0 / enx* en 192.168.1.10/24
|
||||||
|
│ └── enable_radxa_sdcard_usb_rtp.sh # Script à lancer sur la carte MicroSD 32 Go de la Radxa pour activer USB RNDIS + RTP
|
||||||
|
└── src/
|
||||||
|
├── main.rs # Point d'entrée (lance la GUI eframe ou le mode --no-gui)
|
||||||
|
├── config.rs # Structure AppConfig (arguments CLI et valeurs par défaut)
|
||||||
|
├── logger.rs # Logger thread-safe GuiLogger + écriture dans steamframe_fpv.log
|
||||||
|
├── engine.rs # Superviseur FpvEngineController (threads Vidéo, Télémétrie ON/OFF, OpenXR & Mode Bureau)
|
||||||
|
├── gui.rs # Interface graphique SteamFrameGuiApp (contrôles, aperçu vidéo, jauges, logs)
|
||||||
|
├── video_usb.rs # Pipelines GStreamer (Mode RNDIS RTP H.265/H.264 & Mode UVC /dev/video0)
|
||||||
|
├── dome_projection.rs # Modes Dome140/Cylinder140/FlatQuad & LUT de dé-distorsion optique (DomeWarpLut)
|
||||||
|
├── telemetry_osd.rs # Récepteur UDP MAVLink/CRSF & moteur de dessin OSD (OsdOverlay)
|
||||||
|
├── nomad_elrs.rs # Encodage Head-Tracking MSPv2 (0x0383) & CRSF (0x16) vers RadioMaster Nomad
|
||||||
|
└── vulkan_xr.rs # Contexte Vulkan + Swapchain OpenXR (VulkanXrContext)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Commandes Rapides pour Reprendre
|
||||||
|
|
||||||
|
### Compiler et lancer l'interface sur le PC Ubuntu actuel :
|
||||||
|
```bash
|
||||||
|
cd /home/bleack/projects/steamframe_fpv
|
||||||
|
cargo run --release
|
||||||
|
```
|
||||||
|
|
||||||
|
### Liaison USB-C OTG Directe avec la Radxa Zero 3W (Ruby FPV v11.8) :
|
||||||
|
1. **Liaison physique & réseau :** Câble USB-C branché sur le port OTG de la Radxa. Interface PC configurée en `192.168.1.10/24`, Radxa en `192.168.1.1/24` (ping < 0.6 ms, SSH sans mot de passe).
|
||||||
|
2. **Découverte de l'architecture Ruby FPV :**
|
||||||
|
- Le transfert vidéo vers l'hôte USB (`video_usb: 1 5600 1024`) n'est **PAS du RTP**, mais un flux **H.264 Annex-B brut** (unités NAL `00 00 01` découpées en paquets UDP de 1024 octets).
|
||||||
|
- Le profil caméra (Eachine Sphere Link IMX415) émet en **H.264 1280x720 @ 60 FPS**.
|
||||||
|
- `video_eth` était initialement actif sur le même port 5600 en mode RTS (trames radio chiffrées/fragmentées), provoquant un entrelacement corrompant le flux. Il a été désactivé (`video_eth: 0 5601 1024`).
|
||||||
|
3. **Pipeline GStreamer Ultra-Basse Latence (Zéro-Lag FPV) :**
|
||||||
|
- Élimination de `decodebin` / `vah264dec` qui provoquait des erreurs `invalid video buffer received` et accumulait plusieurs trames de buffer de référence (DPB).
|
||||||
|
- Utilisation du décodeur direct `avdec_h264 max-threads=1 discard-corrupted-frames=true` (décodage par tranche sans retard de bufferisation de trames).
|
||||||
|
- Réduction du buffer de socket UDP de 4 Mo à 512 Ko (`buffer-size=524288`) pour éliminer tout arriéré historique de paquets (fini les secondes de retard !).
|
||||||
|
- Passage de la résolution cible au format natif de la caméra **1280×720** (suppression de l'upscaling CPU `videoscale` et division par plus de 2 des transferts mémoire RGBA).
|
||||||
|
- Rafraîchissement graphique réactif dans l'UI (`ctx.request_repaint()` immédiat dès l'arrivée d'une nouvelle trame).
|
||||||
|
4. **Validation :**
|
||||||
|
- Aucune erreur GStreamer, flux fluide et synchrone en temps réel (`[USB Vidéo] Première image reçue depuis le VRX Sphere Link (1280x720) !`).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Prochaines Étapes Possibles
|
||||||
|
|
||||||
|
- Observer le flux vidéo en direct dans la fenêtre de monitoring (`cargo run --release`).
|
||||||
|
- Tester l'envoi des trames `MSP_ELRS_BACKPACK_SET_PTR` (`0x0383`) vers le module **RadioMaster Nomad** avec les curseurs de simulation de l'interface graphique.
|
||||||
|
- Ajouter l'enregistrement vidéo DVR (`.mp4` / `.mkv`) en un clic dans l'interface graphique.
|
||||||
|
- Compiler le binaire ARM64 final sur le **Steam Frame** et ajuster le profil de dé-distorsion (`lens_k1`, `lens_k2`) dans le casque.
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Script à exécuter sur votre PC en insérant la carte MicroSD 32 Go du VRX Eachine Sphere Link
|
||||||
|
# (image runcam_wifilink_sdcard.img / OpenIPC sbc-groundstations).
|
||||||
|
# Il active le réseau USB OTG (RNDIS 192.168.1.1) sur la Radxa Zero 3W et redirige
|
||||||
|
# le flux vidéo RTP (port 5600) vers votre PC / Steam Frame (192.168.1.10:5600).
|
||||||
|
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
SD_MOUNT="${1:-}"
|
||||||
|
|
||||||
|
if [[ -z "${SD_MOUNT}" || ! -d "${SD_MOUNT}/etc" ]]; then
|
||||||
|
echo "Usage : sudo $0 /media/$USER/rootfs (chemin où la carte MicroSD de la Radxa est montée)"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "[*] Configuration de la carte MicroSD Radxa Zero 3W montée dans : ${SD_MOUNT}"
|
||||||
|
|
||||||
|
# 1. Script d'initialisation USB Gadget RNDIS + Redirection RTP au démarrage de la Radxa
|
||||||
|
INIT_SCRIPT="${SD_MOUNT}/etc/init.d/S98usb_steamframe"
|
||||||
|
cat << 'EOF' | sudo tee "${INIT_SCRIPT}" >/dev/null
|
||||||
|
#!/bin/sh
|
||||||
|
# Active le mode réseau USB OTG (RNDIS/ECM) sur le port USB-C de la Radxa Zero 3W
|
||||||
|
# et duplique/redirige le flux RTP WFB-ng vers le Steam Frame / PC (192.168.1.10:5600)
|
||||||
|
|
||||||
|
case "$1" in
|
||||||
|
start)
|
||||||
|
modprobe libcomposite 2>/dev/null || true
|
||||||
|
modprobe g_ether host_addr=12:34:56:78:9a:bc dev_addr=12:34:56:78:9a:bd 2>/dev/null || true
|
||||||
|
|
||||||
|
sleep 2
|
||||||
|
if ip link show usb0 >/dev/null 2>&1; then
|
||||||
|
ip link set usb0 up
|
||||||
|
ip addr add 192.168.1.1/24 dev usb0 2>/dev/null || true
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Redirection du flux RTP WFB-ng vers 192.168.1.10:5600 (PC / Steam Frame)
|
||||||
|
if [ -f /etc/wifibroadcast.cfg ]; then
|
||||||
|
sed -i 's|127.0.0.1:5600|192.168.1.10:5600|g' /etc/wifibroadcast.cfg
|
||||||
|
fi
|
||||||
|
;;
|
||||||
|
stop)
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
exit 0
|
||||||
|
EOF
|
||||||
|
|
||||||
|
sudo chmod +x "${INIT_SCRIPT}"
|
||||||
|
sync
|
||||||
|
echo "[+] Configuration terminée ! Remettez la carte MicroSD dans le VRX Eachine Sphere Link et branchez-le en USB-C."
|
||||||
Executable
+62
@@ -0,0 +1,62 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
ROOTFS="/run/media/bleack/rootfs"
|
||||||
|
|
||||||
|
if [ ! -d "${ROOTFS}/etc" ]; then
|
||||||
|
echo "Erreur : La partition rootfs n'est pas montée dans ${ROOTFS}"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "=== Configuration du mode USB Gadget (RNDIS / CDC) sur la Radxa Zero 3W ==="
|
||||||
|
|
||||||
|
# 1. Activer l'overlay device-tree rk3568-dwc3-peripheral
|
||||||
|
echo "[1/4] Activation de l'overlay DWC3 Peripheral mode..."
|
||||||
|
cp "${ROOTFS}/boot/dtbo/rk3568-dwc3-peripheral.dtbo.disabled" "${ROOTFS}/boot/dtbo/rk3568-dwc3-peripheral.dtbo"
|
||||||
|
|
||||||
|
EXTLINUX="${ROOTFS}/boot/extlinux/extlinux.conf"
|
||||||
|
if ! grep -q "rk3568-dwc3-peripheral.dtbo" "${EXTLINUX}"; then
|
||||||
|
sed -i '/fdtdir/a \ fdtoverlays /boot/dtbo/rk3568-dwc3-peripheral.dtbo' "${EXTLINUX}"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 2. Charger le module g_cdc au boot
|
||||||
|
echo "[2/4] Ajout du module g_cdc dans /etc/modules..."
|
||||||
|
if ! grep -q "g_cdc" "${ROOTFS}/etc/modules"; then
|
||||||
|
echo "g_cdc" >> "${ROOTFS}/etc/modules"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 3. Configurer l'IP statique 192.168.1.1 sur usb0
|
||||||
|
echo "[3/4] Configuration réseau de usb0 (192.168.1.1/24)..."
|
||||||
|
cat << 'EOF' > "${ROOTFS}/etc/network/interfaces.d/usb0"
|
||||||
|
auto usb0
|
||||||
|
allow-hotplug usb0
|
||||||
|
iface usb0 inet static
|
||||||
|
address 192.168.1.1
|
||||||
|
netmask 255.255.255.0
|
||||||
|
EOF
|
||||||
|
|
||||||
|
cat << 'EOF' > "${ROOTFS}/etc/systemd/system/usb0-setup.service"
|
||||||
|
[Unit]
|
||||||
|
Description=SteamFrame FPV USB0 IP Setup
|
||||||
|
After=network.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=oneshot
|
||||||
|
ExecStart=/bin/sh -c 'sleep 2; ip link set usb0 up && ip addr add 192.168.1.1/24 dev usb0 || true'
|
||||||
|
RemainAfterExit=yes
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
EOF
|
||||||
|
|
||||||
|
mkdir -p "${ROOTFS}/etc/systemd/system/multi-user.target.wants"
|
||||||
|
ln -sf /etc/systemd/system/usb0-setup.service "${ROOTFS}/etc/systemd/system/multi-user.target.wants/usb0-setup.service"
|
||||||
|
|
||||||
|
# 4. Ajuster le port vidéo dans controller_settings.cfg vers 5600
|
||||||
|
echo "[4/4] Configuration du port vidéo Ruby vers 5600..."
|
||||||
|
if [ -f "${ROOTFS}/home/radxa/ruby/config/controller_settings.cfg" ]; then
|
||||||
|
sed -i 's/video_usb: 1 [0-9]\+ 1024/video_usb: 1 5600 1024/g' "${ROOTFS}/home/radxa/ruby/config/controller_settings.cfg"
|
||||||
|
fi
|
||||||
|
|
||||||
|
sync
|
||||||
|
echo "[+] Configuration terminée avec succès !"
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Script de détection et configuration automatique de l'interface USB OTG / RNDIS
|
||||||
|
# sur votre PC Linux actuel ou sur le Steam Frame pour le VRX Radxa Zero 3W (Sphere Link).
|
||||||
|
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
echo "=== Diagnostic USB du récepteur Eachine Sphere Link (Radxa Zero 3W) ==="
|
||||||
|
|
||||||
|
echo "[1/4] Vérification des périphériques USB branchés (lsusb)..."
|
||||||
|
lsusb | grep -iE "2207|0525|1d6b:0104|radxa|rockchip|gadget|rndis|ether|adb" || echo " -> Info : Aucun identifiant USB Gadget Rockchip/RNDIS standard détecté dans lsusb."
|
||||||
|
|
||||||
|
# Détection automatique de l'interface réseau USB (usb0 ou enx...)
|
||||||
|
DETECTED_IFACE=$(ip -o link show | awk -F': ' '{print $2}' | grep -E '^(usb[0-9]+|enx[0-9a-fA-F]+)$' | head -n 1 || true)
|
||||||
|
USB_IFACE="${1:-${DETECTED_IFACE:-usb0}}"
|
||||||
|
HOST_USB_IP="${2:-192.168.1.10/24}"
|
||||||
|
|
||||||
|
echo "[2/4] Interface réseau USB cible : ${USB_IFACE}"
|
||||||
|
if ! ip link show "${USB_IFACE}" >/dev/null 2>&1; then
|
||||||
|
echo "ERREUR : L'interface réseau '${USB_IFACE}' n'existe pas encore sur votre PC."
|
||||||
|
echo "Causes possibles :"
|
||||||
|
echo " 1. Le câble USB-C utilisé est un câble de charge uniquement (sans fils de données D+/D-)."
|
||||||
|
echo " 2. L'image d'usine 'runcam_wifilink_sdcard.img' sur la carte SD de la Radxa Zero 3W"
|
||||||
|
echo " sort la vidéo uniquement sur le port Mini-HDMI par défaut."
|
||||||
|
echo " -> Solution : Insérez la carte MicroSD 32 Go de la Radxa dans votre PC et lancez :"
|
||||||
|
echo " sudo ./scripts/enable_radxa_sdcard_usb_rtp.sh /chemin/vers/partition_rootfs_sdcard"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "[3/4] Attribution de l'adresse IP ${HOST_USB_IP} sur ${USB_IFACE}..."
|
||||||
|
sudo ip link set dev "${USB_IFACE}" up
|
||||||
|
sudo ip addr flush dev "${USB_IFACE}"
|
||||||
|
sudo ip addr add "${HOST_USB_IP}" dev "${USB_IFACE}"
|
||||||
|
|
||||||
|
sudo sysctl -w net.core.rmem_max=8388608 >/dev/null
|
||||||
|
sudo sysctl -w net.core.rmem_default=4194304 >/dev/null
|
||||||
|
|
||||||
|
echo "[4/4] Test de communication avec la Radxa Zero 3W (192.168.1.1)..."
|
||||||
|
if ping -c 1 -W 1 192.168.1.1 >/dev/null 2>&1; then
|
||||||
|
echo "[+] SUCCÈS : La Radxa Zero 3W répond sur 192.168.1.1 via ${USB_IFACE} !"
|
||||||
|
else
|
||||||
|
echo "[!] Interface ${USB_IFACE} active (${HOST_USB_IP}), mais 192.168.1.1 ne répond pas au ping."
|
||||||
|
fi
|
||||||
+118
@@ -0,0 +1,118 @@
|
|||||||
|
use clap::Parser;
|
||||||
|
|
||||||
|
#[derive(Parser, Debug, Clone)]
|
||||||
|
#[command(author, version, about)]
|
||||||
|
pub struct AppConfig {
|
||||||
|
/// Mode d'acquisition vidéo USB depuis le VRX Radxa Zero 3W :
|
||||||
|
/// "rndis" (Câble USB-C OTG direct -> flux RTP UDP :5600) ou "uvc" (Mini-HDMI -> Carte capture USB /dev/video0)
|
||||||
|
#[arg(long, default_value = "rndis")]
|
||||||
|
pub usb_video_mode: String,
|
||||||
|
|
||||||
|
/// Périphérique V4L2 si usb_video_mode = "uvc" (carte d'acquisition Mini-HDMI vers USB-C)
|
||||||
|
#[arg(long, default_value = "/dev/video0")]
|
||||||
|
pub uvc_device: String,
|
||||||
|
|
||||||
|
/// Adresse IP d'écoute de l'interface USB RNDIS (0.0.0.0 écoute sur usb0 et toutes les interfaces)
|
||||||
|
#[arg(long, default_value = "0.0.0.0")]
|
||||||
|
pub usb_bind_ip: String,
|
||||||
|
|
||||||
|
/// Adresse IP de la carte Radxa Zero 3W (VRX OpenIPC) sur le réseau USB OTG
|
||||||
|
#[arg(long, default_value = "192.168.1.1")]
|
||||||
|
pub radxa_vrx_ip: String,
|
||||||
|
|
||||||
|
/// Canal 5.8 GHz du récepteur RTL8812EU (Défaut usine Sphere Link : 161)
|
||||||
|
#[arg(long, default_value_t = 161)]
|
||||||
|
pub wifi_channel: u16,
|
||||||
|
|
||||||
|
/// Profil de résolution/FPS du VRX Sphere Link ("720p60", "1080p60", "1080p90", "720p120")
|
||||||
|
#[arg(long, default_value = "720p60")]
|
||||||
|
pub vrx_video_profile: String,
|
||||||
|
|
||||||
|
/// Port UDP du flux RTP OpenIPC envoyé par le VRX Eachine Sphere Link
|
||||||
|
#[arg(long, default_value_t = 5600)]
|
||||||
|
pub video_udp_port: u16,
|
||||||
|
|
||||||
|
/// Activer ou désactiver la réception de télémétrie UDP et l'incrustation OSD (ON/OFF)
|
||||||
|
#[arg(long, default_value_t = false)]
|
||||||
|
pub telemetry_enabled: bool,
|
||||||
|
|
||||||
|
/// Port UDP d'écoute pour la télémétrie MAVLink / CRSF (OSD)
|
||||||
|
#[arg(long, default_value_t = 14551)]
|
||||||
|
pub telemetry_udp_port: u16,
|
||||||
|
|
||||||
|
/// Codec vidéo reçu depuis le VRX OpenIPC / Ruby ("h264" ou "h265")
|
||||||
|
#[arg(long, default_value = "h264")]
|
||||||
|
pub codec: String,
|
||||||
|
|
||||||
|
/// Format de transport du flux vidéo UDP : "raw" (flux NAL direct Ruby FPV / OpenIPC) ou "rtp" (flux RTP standard)
|
||||||
|
#[arg(long, default_value = "raw")]
|
||||||
|
pub stream_transport: String,
|
||||||
|
|
||||||
|
/// Mode de projection VR : "dome" (Sphérique 140° Equirect2), "cylinder" (Incurvé 140°), ou "flat" (Quad plat)
|
||||||
|
#[arg(long, default_value = "dome")]
|
||||||
|
pub projection_mode: String,
|
||||||
|
|
||||||
|
/// Champ de vision horizontal (FOV en degrés) de la caméra Eachine Sphere Link
|
||||||
|
#[arg(long, default_value_t = 140.0)]
|
||||||
|
pub camera_fov_deg: f32,
|
||||||
|
|
||||||
|
/// Coefficient de correction radiale k1 de la lentille M12 140° (0.0 = désactivé, ex: -0.14)
|
||||||
|
#[arg(long, default_value_t = -0.14)]
|
||||||
|
pub lens_k1: f32,
|
||||||
|
|
||||||
|
/// Coefficient de correction radiale k2 de la lentille M12 140°
|
||||||
|
#[arg(long, default_value_t = 0.03)]
|
||||||
|
pub lens_k2: f32,
|
||||||
|
|
||||||
|
/// Largeur de la texture swapchain OpenXR (résolution vidéo cible)
|
||||||
|
#[arg(long, default_value_t = 1280)]
|
||||||
|
pub video_width: u32,
|
||||||
|
|
||||||
|
/// Hauteur de la texture swapchain OpenXR (résolution vidéo cible)
|
||||||
|
#[arg(long, default_value_t = 720)]
|
||||||
|
pub video_height: u32,
|
||||||
|
|
||||||
|
/// Rayon du dôme / cylindre ou distance virtuelle de l'écran FPV devant les yeux en mètres
|
||||||
|
#[arg(long, default_value_t = 1.6)]
|
||||||
|
pub screen_distance_m: f32,
|
||||||
|
|
||||||
|
/// Largeur virtuelle de l'écran FPV en mètres (utilisé en mode flat/quad)
|
||||||
|
#[arg(long, default_value_t = 3.2)]
|
||||||
|
pub screen_width_m: f32,
|
||||||
|
|
||||||
|
/// Adresse IP du Backpack Wi-Fi du module RadioMaster Nomad (en mode AP ELRS : 10.0.0.1)
|
||||||
|
#[arg(long, default_value = "10.0.0.1")]
|
||||||
|
pub nomad_ip: String,
|
||||||
|
|
||||||
|
/// Port UDP du Backpack ELRS du RadioMaster Nomad
|
||||||
|
#[arg(long, default_value_t = 14550)]
|
||||||
|
pub nomad_port: u16,
|
||||||
|
|
||||||
|
/// Protocole Head-Tracking vers le Nomad : "msp" (MSP_ELRS_BACKPACK_SET_PTR 0x0383) ou "crsf"
|
||||||
|
#[arg(long, default_value = "msp")]
|
||||||
|
pub ht_protocol: String,
|
||||||
|
|
||||||
|
/// Angle maximal Pan (Lacet/Yaw) en degrés correspondant à la course complète servo (172..1811 CRSF)
|
||||||
|
#[arg(long, default_value_t = 90.0)]
|
||||||
|
pub max_pan_deg: f32,
|
||||||
|
|
||||||
|
/// Angle maximal Tilt (Tangage/Pitch) en degrés
|
||||||
|
#[arg(long, default_value_t = 60.0)]
|
||||||
|
pub max_tilt_deg: f32,
|
||||||
|
|
||||||
|
/// Angle maximal Roll (Roulis) en degrés
|
||||||
|
#[arg(long, default_value_t = 45.0)]
|
||||||
|
pub max_roll_deg: f32,
|
||||||
|
|
||||||
|
/// Forcer le mode sans affichage VR (Headless) uniquement pour tester le Head-Tracking
|
||||||
|
#[arg(long, default_value_t = false)]
|
||||||
|
pub headless: bool,
|
||||||
|
|
||||||
|
/// Désactiver l'interface graphique de monitoring (lancer directement en ligne de commande)
|
||||||
|
#[arg(long, default_value_t = false)]
|
||||||
|
pub no_gui: bool,
|
||||||
|
|
||||||
|
/// Chemin du fichier journal d'erreurs et de diagnostic
|
||||||
|
#[arg(long, default_value = "steamframe_fpv.log")]
|
||||||
|
pub log_file: String,
|
||||||
|
}
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
/// Modes de projection VR pour l'affichage du flux Eachine Sphere Link (140° FOV)
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum ProjectionMode {
|
||||||
|
/// Dôme sphérique 140° (`XR_KHR_composition_layer_equirect2` + correction optique grand-angle)
|
||||||
|
Dome140,
|
||||||
|
/// Écran incurvé cylindrique 140° (`XR_KHR_composition_layer_cylinder`)
|
||||||
|
Cylinder140,
|
||||||
|
/// Écran plat verrouillé sur la tête (`XrCompositionLayerQuad`)
|
||||||
|
FlatQuad,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ProjectionMode {
|
||||||
|
pub fn from_str(s: &str) -> Self {
|
||||||
|
match s.to_lowercase().as_str() {
|
||||||
|
"cylinder" | "cyl" => Self::Cylinder140,
|
||||||
|
"flat" | "quad" => Self::FlatQuad,
|
||||||
|
_ => Self::Dome140,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn label(&self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Self::Dome140 => "DOME 140",
|
||||||
|
Self::Cylinder140 => "CYL 140",
|
||||||
|
Self::FlatQuad => "QUAD",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Table de correspondance (LUT) précalculée pour corriger la distorsion en barillet
|
||||||
|
/// de la lentille M12 140° de l'Eachine Sphere Link et la projeter sur le dôme VR.
|
||||||
|
pub struct DomeWarpLut {
|
||||||
|
pub width: u32,
|
||||||
|
pub height: u32,
|
||||||
|
pub src_byte_offsets: Vec<usize>,
|
||||||
|
pub enabled: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
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 mut src_byte_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);
|
||||||
|
|
||||||
|
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;
|
||||||
|
let r4 = r2 * r2;
|
||||||
|
|
||||||
|
let factor = (1.0 + k1 * r2 + k2 * r4) / max_tan.min(1.15);
|
||||||
|
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 byte_offset = ((sy * width + sx) * 4) as usize;
|
||||||
|
src_byte_offsets.push(byte_offset);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Self {
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
src_byte_offsets,
|
||||||
|
enabled,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn apply(&self, input_rgba: &[u8], output_rgba: &mut [u8]) {
|
||||||
|
if !self.enabled || input_rgba.len() < (self.width * self.height * 4) as usize {
|
||||||
|
output_rgba.copy_from_slice(input_rgba);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (dst_pixel_idx, &src_byte_idx) in self.src_byte_offsets.iter().enumerate() {
|
||||||
|
let dst_byte_idx = dst_pixel_idx * 4;
|
||||||
|
output_rgba[dst_byte_idx..dst_byte_idx + 4]
|
||||||
|
.copy_from_slice(&input_rgba[src_byte_idx..src_byte_idx + 4]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+779
@@ -0,0 +1,779 @@
|
|||||||
|
use crate::config::AppConfig;
|
||||||
|
use crate::dome_projection::{DomeWarpLut, ProjectionMode};
|
||||||
|
use crate::nomad_elrs::{HeadPoseSample, NomadHeadTracker};
|
||||||
|
use crate::telemetry_osd::{OsdOverlay, TelemetryReceiver, TelemetryState};
|
||||||
|
use crate::video_usb::UsbVideoReceiver;
|
||||||
|
use crate::vulkan_xr::VulkanXrContext;
|
||||||
|
use anyhow::{Context, Result};
|
||||||
|
use glam::{EulerRot, Quat};
|
||||||
|
use openxr as xr;
|
||||||
|
use parking_lot::Mutex;
|
||||||
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::thread::{self, JoinHandle};
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum SubsystemStatus {
|
||||||
|
Stopped,
|
||||||
|
Disabled,
|
||||||
|
Starting,
|
||||||
|
Running(String),
|
||||||
|
Warning(String),
|
||||||
|
Error(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct RuntimeMonitor {
|
||||||
|
pub usb_video_status: SubsystemStatus,
|
||||||
|
pub openxr_status: SubsystemStatus,
|
||||||
|
pub nomad_wifi_status: SubsystemStatus,
|
||||||
|
pub telemetry_status: SubsystemStatus,
|
||||||
|
pub video_fps: f32,
|
||||||
|
pub video_frames_total: u64,
|
||||||
|
pub latest_head_pose: HeadPoseSample,
|
||||||
|
pub latest_telemetry: TelemetryState,
|
||||||
|
pub preview_rgba: Vec<u8>,
|
||||||
|
pub preview_width: u32,
|
||||||
|
pub preview_height: u32,
|
||||||
|
pub preview_frame_seq: u64,
|
||||||
|
pub manual_override_enabled: bool,
|
||||||
|
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,
|
||||||
|
video_fps: 0.0,
|
||||||
|
video_frames_total: 0,
|
||||||
|
latest_head_pose: HeadPoseSample::default(),
|
||||||
|
latest_telemetry: TelemetryState::default(),
|
||||||
|
preview_rgba: Vec::new(),
|
||||||
|
preview_width: 0,
|
||||||
|
preview_height: 0,
|
||||||
|
preview_frame_seq: 0,
|
||||||
|
manual_override_enabled: false,
|
||||||
|
manual_pan_deg: 0.0,
|
||||||
|
manual_tilt_deg: 0.0,
|
||||||
|
manual_roll_deg: 0.0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct FpvEngineController {
|
||||||
|
pub monitor: Arc<Mutex<RuntimeMonitor>>,
|
||||||
|
stop_flag: Arc<AtomicBool>,
|
||||||
|
recenter_flag: Arc<AtomicBool>,
|
||||||
|
telemetry_enabled_flag: Arc<AtomicBool>,
|
||||||
|
worker_handle: Option<JoinHandle<()>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FpvEngineController {
|
||||||
|
pub fn new(initial_telemetry_enabled: bool) -> Self {
|
||||||
|
Self {
|
||||||
|
monitor: Arc::new(Mutex::new(RuntimeMonitor::default())),
|
||||||
|
stop_flag: Arc::new(AtomicBool::new(false)),
|
||||||
|
recenter_flag: Arc::new(AtomicBool::new(false)),
|
||||||
|
telemetry_enabled_flag: Arc::new(AtomicBool::new(initial_telemetry_enabled)),
|
||||||
|
worker_handle: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_running(&self) -> bool {
|
||||||
|
self.worker_handle
|
||||||
|
.as_ref()
|
||||||
|
.map(|h| !h.is_finished())
|
||||||
|
.unwrap_or(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn request_recenter(&self) {
|
||||||
|
self.recenter_flag.store(true, Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_telemetry_enabled(&self) -> bool {
|
||||||
|
self.telemetry_enabled_flag.load(Ordering::Relaxed)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_telemetry_enabled(&self, enabled: bool) {
|
||||||
|
let prev = self.telemetry_enabled_flag.swap(enabled, Ordering::Relaxed);
|
||||||
|
if prev != enabled {
|
||||||
|
log::info!(
|
||||||
|
"[Action Utilisateur] Télémétrie & OSD basculés sur : {}",
|
||||||
|
if enabled { "ON (Activé)" } else { "OFF (Désactivé)" }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn stop(&mut self) {
|
||||||
|
if self.is_running() {
|
||||||
|
log::info!("[Moteur FPV] Arrêt des services demandé par l'utilisateur...");
|
||||||
|
self.stop_flag.store(true, Ordering::Relaxed);
|
||||||
|
if let Some(handle) = self.worker_handle.take() {
|
||||||
|
let _ = handle.join();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut mon = self.monitor.lock();
|
||||||
|
mon.usb_video_status = SubsystemStatus::Stopped;
|
||||||
|
mon.openxr_status = SubsystemStatus::Stopped;
|
||||||
|
mon.nomad_wifi_status = SubsystemStatus::Stopped;
|
||||||
|
mon.telemetry_status = if self.is_telemetry_enabled() {
|
||||||
|
SubsystemStatus::Stopped
|
||||||
|
} else {
|
||||||
|
SubsystemStatus::Disabled
|
||||||
|
};
|
||||||
|
mon.video_fps = 0.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn start(&mut self, cfg: AppConfig) {
|
||||||
|
self.stop();
|
||||||
|
self.stop_flag.store(false, Ordering::Relaxed);
|
||||||
|
self.recenter_flag.store(false, Ordering::Relaxed);
|
||||||
|
self.telemetry_enabled_flag
|
||||||
|
.store(cfg.telemetry_enabled, Ordering::Relaxed);
|
||||||
|
|
||||||
|
{
|
||||||
|
let mut mon = self.monitor.lock();
|
||||||
|
mon.usb_video_status = SubsystemStatus::Starting;
|
||||||
|
mon.openxr_status = SubsystemStatus::Starting;
|
||||||
|
mon.nomad_wifi_status = SubsystemStatus::Starting;
|
||||||
|
mon.telemetry_status = if cfg.telemetry_enabled {
|
||||||
|
SubsystemStatus::Starting
|
||||||
|
} else {
|
||||||
|
SubsystemStatus::Disabled
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
let monitor_clone = Arc::clone(&self.monitor);
|
||||||
|
let stop_clone = Arc::clone(&self.stop_flag);
|
||||||
|
let recenter_clone = Arc::clone(&self.recenter_flag);
|
||||||
|
let telem_flag_clone = Arc::clone(&self.telemetry_enabled_flag);
|
||||||
|
|
||||||
|
let handle = thread::Builder::new()
|
||||||
|
.name("fpv-engine-worker".into())
|
||||||
|
.spawn(move || {
|
||||||
|
run_engine_worker(
|
||||||
|
cfg,
|
||||||
|
monitor_clone,
|
||||||
|
stop_clone,
|
||||||
|
recenter_clone,
|
||||||
|
telem_flag_clone,
|
||||||
|
);
|
||||||
|
})
|
||||||
|
.expect("Impossible de créer le thread fpv-engine-worker");
|
||||||
|
|
||||||
|
self.worker_handle = Some(handle);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for FpvEngineController {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.stop();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sync_telemetry_receiver(
|
||||||
|
cfg: &AppConfig,
|
||||||
|
telem_enabled: bool,
|
||||||
|
telem_rx_opt: &mut Option<TelemetryReceiver>,
|
||||||
|
monitor: &Arc<Mutex<RuntimeMonitor>>,
|
||||||
|
) {
|
||||||
|
if telem_enabled && telem_rx_opt.is_none() {
|
||||||
|
match TelemetryReceiver::start(&cfg.usb_bind_ip, cfg.telemetry_udp_port) {
|
||||||
|
Ok(rx) => {
|
||||||
|
monitor.lock().telemetry_status = SubsystemStatus::Running(format!(
|
||||||
|
"ON - UDP {}:{}",
|
||||||
|
cfg.usb_bind_ip, cfg.telemetry_udp_port
|
||||||
|
));
|
||||||
|
*telem_rx_opt = Some(rx);
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
log::error!(
|
||||||
|
"[Télémétrie OSD] Échec d'activation sur le port {} : {}",
|
||||||
|
cfg.telemetry_udp_port,
|
||||||
|
e
|
||||||
|
);
|
||||||
|
monitor.lock().telemetry_status = SubsystemStatus::Error(format!("{}", e));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if !telem_enabled && telem_rx_opt.is_some() {
|
||||||
|
*telem_rx_opt = None;
|
||||||
|
monitor.lock().telemetry_status = SubsystemStatus::Disabled;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run_engine_worker(
|
||||||
|
cfg: AppConfig,
|
||||||
|
monitor: Arc<Mutex<RuntimeMonitor>>,
|
||||||
|
stop_flag: Arc<AtomicBool>,
|
||||||
|
recenter_flag: Arc<AtomicBool>,
|
||||||
|
telem_enabled_flag: Arc<AtomicBool>,
|
||||||
|
) {
|
||||||
|
log::info!(
|
||||||
|
"[Moteur FPV] Initialisation (VRX Radxa Zero 3W + 8812EU, Canal {}, Profil {}, Mode USB={})...",
|
||||||
|
cfg.wifi_channel,
|
||||||
|
cfg.vrx_video_profile,
|
||||||
|
cfg.usb_video_mode
|
||||||
|
);
|
||||||
|
|
||||||
|
// 1. Démarrage Vidéo USB (Mode OTG/RNDIS ou Mode Mini-HDMI UVC)
|
||||||
|
let video_rx_opt = match UsbVideoReceiver::start(
|
||||||
|
&cfg.usb_video_mode,
|
||||||
|
&cfg.uvc_device,
|
||||||
|
&cfg.usb_bind_ip,
|
||||||
|
cfg.video_udp_port,
|
||||||
|
&cfg.codec,
|
||||||
|
&cfg.stream_transport,
|
||||||
|
cfg.video_width,
|
||||||
|
cfg.video_height,
|
||||||
|
) {
|
||||||
|
Ok(rx) => {
|
||||||
|
let status_desc = if cfg.usb_video_mode.eq_ignore_ascii_case("uvc") {
|
||||||
|
format!("Mini-HDMI UVC ({})", cfg.uvc_device)
|
||||||
|
} else {
|
||||||
|
format!(
|
||||||
|
"USB OTG RNDIS {}:{} ({}/{})",
|
||||||
|
cfg.usb_bind_ip,
|
||||||
|
cfg.video_udp_port,
|
||||||
|
cfg.codec.to_uppercase(),
|
||||||
|
cfg.stream_transport.to_uppercase()
|
||||||
|
)
|
||||||
|
};
|
||||||
|
monitor.lock().usb_video_status = SubsystemStatus::Running(status_desc);
|
||||||
|
Some(rx)
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
log::error!("[Moteur FPV] Erreur initialisation USB Vidéo : {}", e);
|
||||||
|
monitor.lock().usb_video_status = SubsystemStatus::Error(format!("{}", e));
|
||||||
|
None
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 2. Démarrage optionnel Télémétrie OSD
|
||||||
|
let mut telem_rx_opt: Option<TelemetryReceiver> = None;
|
||||||
|
sync_telemetry_receiver(
|
||||||
|
&cfg,
|
||||||
|
telem_enabled_flag.load(Ordering::Relaxed),
|
||||||
|
&mut telem_rx_opt,
|
||||||
|
&monitor,
|
||||||
|
);
|
||||||
|
|
||||||
|
// 3. Démarrage Émetteur Wi-Fi RadioMaster Nomad
|
||||||
|
let use_crsf = cfg.ht_protocol.eq_ignore_ascii_case("crsf");
|
||||||
|
let mut head_tracker_opt = match NomadHeadTracker::new(
|
||||||
|
&cfg.nomad_ip,
|
||||||
|
cfg.nomad_port,
|
||||||
|
cfg.max_pan_deg,
|
||||||
|
cfg.max_tilt_deg,
|
||||||
|
cfg.max_roll_deg,
|
||||||
|
use_crsf,
|
||||||
|
) {
|
||||||
|
Ok(ht) => {
|
||||||
|
monitor.lock().nomad_wifi_status = SubsystemStatus::Running(format!(
|
||||||
|
"Cible {}:{} ({})",
|
||||||
|
cfg.nomad_ip,
|
||||||
|
cfg.nomad_port,
|
||||||
|
if use_crsf { "CRSF" } else { "MSPv2 0x0383" }
|
||||||
|
));
|
||||||
|
Some(ht)
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
log::error!("[Moteur FPV] Erreur initialisation RadioMaster Nomad : {}", e);
|
||||||
|
monitor.lock().nomad_wifi_status = SubsystemStatus::Error(format!("{}", e));
|
||||||
|
None
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 4. Tentative d'initialisation OpenXR sur le Steam Frame
|
||||||
|
if let Err(xr_err) = try_run_openxr_session(
|
||||||
|
&cfg,
|
||||||
|
&monitor,
|
||||||
|
&stop_flag,
|
||||||
|
&recenter_flag,
|
||||||
|
&telem_enabled_flag,
|
||||||
|
video_rx_opt.as_ref(),
|
||||||
|
&mut telem_rx_opt,
|
||||||
|
head_tracker_opt.as_mut(),
|
||||||
|
) {
|
||||||
|
log::warn!(
|
||||||
|
"[OpenXR] Session VR indisponible ({}). Bascule automatique en mode Monitoring Bureau / Simulation.",
|
||||||
|
xr_err
|
||||||
|
);
|
||||||
|
monitor.lock().openxr_status =
|
||||||
|
SubsystemStatus::Warning(format!("Mode Bureau (OpenXR inactif : {})", xr_err));
|
||||||
|
|
||||||
|
run_desktop_fallback_loop(
|
||||||
|
&cfg,
|
||||||
|
&monitor,
|
||||||
|
&stop_flag,
|
||||||
|
&recenter_flag,
|
||||||
|
&telem_enabled_flag,
|
||||||
|
video_rx_opt.as_ref(),
|
||||||
|
&mut telem_rx_opt,
|
||||||
|
head_tracker_opt.as_mut(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
log::info!("[Moteur FPV] Tous les sous-systèmes ont été arrêtés.");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
fn try_run_openxr_session(
|
||||||
|
cfg: &AppConfig,
|
||||||
|
monitor: &Arc<Mutex<RuntimeMonitor>>,
|
||||||
|
stop_flag: &Arc<AtomicBool>,
|
||||||
|
recenter_flag: &Arc<AtomicBool>,
|
||||||
|
telem_enabled_flag: &Arc<AtomicBool>,
|
||||||
|
video_rx: Option<&UsbVideoReceiver>,
|
||||||
|
telem_rx_opt: &mut Option<TelemetryReceiver>,
|
||||||
|
mut head_tracker: Option<&mut NomadHeadTracker>,
|
||||||
|
) -> Result<()> {
|
||||||
|
let entry = unsafe {
|
||||||
|
xr::Entry::load().context("libopenxr_loader.so introuvable sur ce système (normal sur PC sans SteamVR)")?
|
||||||
|
};
|
||||||
|
let available_extensions = entry
|
||||||
|
.enumerate_extensions()
|
||||||
|
.context("Impossible d'énumérer les extensions OpenXR")?;
|
||||||
|
|
||||||
|
let mut enabled_extensions = xr::ExtensionSet::default();
|
||||||
|
let use_vulkan = !cfg.headless && available_extensions.khr_vulkan_enable2;
|
||||||
|
|
||||||
|
if use_vulkan {
|
||||||
|
enabled_extensions.khr_vulkan_enable2 = true;
|
||||||
|
if available_extensions.khr_composition_layer_equirect2 {
|
||||||
|
enabled_extensions.khr_composition_layer_equirect2 = true;
|
||||||
|
}
|
||||||
|
if available_extensions.khr_composition_layer_cylinder {
|
||||||
|
enabled_extensions.khr_composition_layer_cylinder = true;
|
||||||
|
}
|
||||||
|
} else if available_extensions.mnd_headless {
|
||||||
|
enabled_extensions.mnd_headless = true;
|
||||||
|
} else {
|
||||||
|
anyhow::bail!("Runtime OpenXR sans support Vulkan ni Headless");
|
||||||
|
}
|
||||||
|
|
||||||
|
let instance = entry
|
||||||
|
.create_instance(
|
||||||
|
&xr::ApplicationInfo {
|
||||||
|
application_name: "SteamFrameFPV",
|
||||||
|
application_version: 1,
|
||||||
|
engine_name: "SteamFrameNative",
|
||||||
|
engine_version: 1,
|
||||||
|
api_version: xr::Version::new(1, 0, 0),
|
||||||
|
},
|
||||||
|
&enabled_extensions,
|
||||||
|
&[],
|
||||||
|
)
|
||||||
|
.context("Échec xrCreateInstance (SteamVR ou Monado n'est pas lancé)")?;
|
||||||
|
|
||||||
|
let system = instance
|
||||||
|
.system(xr::FormFactor::HEAD_MOUNTED_DISPLAY)
|
||||||
|
.context("Aucun casque VR détecté par le runtime OpenXR")?;
|
||||||
|
|
||||||
|
let props = instance.system_properties(system)?;
|
||||||
|
log::info!(
|
||||||
|
"[OpenXR] Casque connecté : {} (Vendor ID: {})",
|
||||||
|
props.system_name,
|
||||||
|
props.vendor_id
|
||||||
|
);
|
||||||
|
|
||||||
|
if !use_vulkan {
|
||||||
|
anyhow::bail!("Mode Headless sélectionné");
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut vk_xr = VulkanXrContext::new(&instance, system, cfg.video_width, cfg.video_height)?;
|
||||||
|
|
||||||
|
let requested_proj = ProjectionMode::from_str(&cfg.projection_mode);
|
||||||
|
let active_proj = match requested_proj {
|
||||||
|
ProjectionMode::Dome140 if enabled_extensions.khr_composition_layer_equirect2 => {
|
||||||
|
ProjectionMode::Dome140
|
||||||
|
}
|
||||||
|
ProjectionMode::Dome140 if enabled_extensions.khr_composition_layer_cylinder => {
|
||||||
|
ProjectionMode::Cylinder140
|
||||||
|
}
|
||||||
|
ProjectionMode::Cylinder140 if enabled_extensions.khr_composition_layer_cylinder => {
|
||||||
|
ProjectionMode::Cylinder140
|
||||||
|
}
|
||||||
|
_ => ProjectionMode::FlatQuad,
|
||||||
|
};
|
||||||
|
|
||||||
|
monitor.lock().openxr_status = SubsystemStatus::Running(format!(
|
||||||
|
"{} ({})",
|
||||||
|
props.system_name,
|
||||||
|
active_proj.label()
|
||||||
|
));
|
||||||
|
|
||||||
|
let dome_lut = DomeWarpLut::new(
|
||||||
|
cfg.video_width,
|
||||||
|
cfg.video_height,
|
||||||
|
cfg.camera_fov_deg,
|
||||||
|
cfg.lens_k1,
|
||||||
|
cfg.lens_k2,
|
||||||
|
);
|
||||||
|
let mut composited_rgba = vec![0u8; (cfg.video_width * cfg.video_height * 4) as usize];
|
||||||
|
|
||||||
|
let local_space = vk_xr
|
||||||
|
.session
|
||||||
|
.create_reference_space(xr::ReferenceSpaceType::LOCAL, xr::Posef::IDENTITY)?;
|
||||||
|
let view_space = vk_xr
|
||||||
|
.session
|
||||||
|
.create_reference_space(xr::ReferenceSpaceType::VIEW, xr::Posef::IDENTITY)?;
|
||||||
|
|
||||||
|
let aspect = cfg.video_width as f32 / cfg.video_height as f32;
|
||||||
|
let screen_height_m = cfg.screen_width_m / aspect;
|
||||||
|
let horizontal_fov_rad = cfg.camera_fov_deg.to_radians();
|
||||||
|
let half_vert_fov_rad = (horizontal_fov_rad / aspect) * 0.5;
|
||||||
|
|
||||||
|
let mut event_storage = xr::EventDataBuffer::new();
|
||||||
|
let mut session_running = false;
|
||||||
|
let mut first_pose = true;
|
||||||
|
let mut standby_tick: u32 = 0;
|
||||||
|
let mut fps_counter: u32 = 0;
|
||||||
|
let mut fps_timer = Instant::now();
|
||||||
|
let mut last_frame_id: u64 = 0;
|
||||||
|
|
||||||
|
while !stop_flag.load(Ordering::Relaxed) {
|
||||||
|
let telem_on = telem_enabled_flag.load(Ordering::Relaxed);
|
||||||
|
sync_telemetry_receiver(cfg, telem_on, telem_rx_opt, monitor);
|
||||||
|
|
||||||
|
while let Some(event) = instance.poll_event(&mut event_storage)? {
|
||||||
|
use xr::Event::*;
|
||||||
|
match event {
|
||||||
|
SessionStateChanged(e) => {
|
||||||
|
log::info!("[OpenXR] Changement d'état session : {:?}", e.state());
|
||||||
|
match e.state() {
|
||||||
|
xr::SessionState::READY => {
|
||||||
|
vk_xr
|
||||||
|
.session
|
||||||
|
.begin(xr::ViewConfigurationType::PRIMARY_STEREO)?;
|
||||||
|
session_running = true;
|
||||||
|
}
|
||||||
|
xr::SessionState::STOPPING => {
|
||||||
|
vk_xr.session.end()?;
|
||||||
|
session_running = false;
|
||||||
|
}
|
||||||
|
xr::SessionState::EXITING | xr::SessionState::LOSS_PENDING => {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ReferenceSpaceChangePending(_) => {
|
||||||
|
first_pose = true;
|
||||||
|
}
|
||||||
|
InstanceLossPending(_) => return Ok(()),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !session_running {
|
||||||
|
thread::sleep(Duration::from_millis(10));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let xr_frame_state = vk_xr.frame_wait.wait()?;
|
||||||
|
vk_xr.frame_stream.begin()?;
|
||||||
|
|
||||||
|
let location = view_space.locate(&local_space, xr_frame_state.predicted_display_time)?;
|
||||||
|
let mut current_pose = HeadPoseSample::default();
|
||||||
|
|
||||||
|
if location
|
||||||
|
.location_flags
|
||||||
|
.contains(xr::SpaceLocationFlags::ORIENTATION_VALID)
|
||||||
|
{
|
||||||
|
let q = location.pose.orientation;
|
||||||
|
let quat = Quat::from_xyzw(q.x, q.y, q.z, q.w);
|
||||||
|
|
||||||
|
if let Some(ht) = head_tracker.as_deref_mut() {
|
||||||
|
if first_pose || recenter_flag.swap(false, Ordering::Relaxed) {
|
||||||
|
ht.recenter(quat);
|
||||||
|
first_pose = false;
|
||||||
|
}
|
||||||
|
if let Ok(sample) = ht.send_pose(quat) {
|
||||||
|
current_pose = sample;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !xr_frame_state.should_render {
|
||||||
|
vk_xr.frame_stream.end(
|
||||||
|
xr_frame_state.predicted_display_time,
|
||||||
|
xr::EnvironmentBlendMode::OPAQUE,
|
||||||
|
&[],
|
||||||
|
)?;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(rx) = video_rx {
|
||||||
|
let lock = rx.latest_frame();
|
||||||
|
let guard = lock.lock();
|
||||||
|
if let Some(ref vf) = *guard {
|
||||||
|
if vf.frame_id != last_frame_id {
|
||||||
|
last_frame_id = vf.frame_id;
|
||||||
|
fps_counter += 1;
|
||||||
|
}
|
||||||
|
dome_lut.apply(&vf.rgba_data, &mut composited_rgba);
|
||||||
|
} else {
|
||||||
|
standby_tick = standby_tick.wrapping_add(1);
|
||||||
|
let pattern = UsbVideoReceiver::generate_standby_pattern(
|
||||||
|
cfg.video_width,
|
||||||
|
cfg.video_height,
|
||||||
|
standby_tick,
|
||||||
|
);
|
||||||
|
composited_rgba.copy_from_slice(&pattern);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let telem_snapshot = telem_rx_opt
|
||||||
|
.as_ref()
|
||||||
|
.map(|t| t.state().lock().clone())
|
||||||
|
.unwrap_or_default();
|
||||||
|
|
||||||
|
if telem_on {
|
||||||
|
OsdOverlay::render(
|
||||||
|
&mut composited_rgba,
|
||||||
|
cfg.video_width,
|
||||||
|
cfg.video_height,
|
||||||
|
&telem_snapshot,
|
||||||
|
current_pose.pan_deg,
|
||||||
|
current_pose.tilt_deg,
|
||||||
|
current_pose.roll_deg,
|
||||||
|
cfg.max_pan_deg,
|
||||||
|
cfg.max_tilt_deg,
|
||||||
|
active_proj.label(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
vk_xr.upload_rgba_to_swapchain(&composited_rgba)?;
|
||||||
|
|
||||||
|
if standby_tick % 2 == 0 || last_frame_id % 2 == 0 {
|
||||||
|
let mut mon = monitor.lock();
|
||||||
|
if fps_timer.elapsed() >= Duration::from_secs(1) {
|
||||||
|
mon.video_fps = fps_counter as f32 / fps_timer.elapsed().as_secs_f32();
|
||||||
|
fps_counter = 0;
|
||||||
|
fps_timer = Instant::now();
|
||||||
|
}
|
||||||
|
mon.video_frames_total = last_frame_id;
|
||||||
|
mon.latest_head_pose = current_pose;
|
||||||
|
mon.latest_telemetry = telem_snapshot;
|
||||||
|
mon.preview_width = cfg.video_width;
|
||||||
|
mon.preview_height = cfg.video_height;
|
||||||
|
mon.preview_rgba.clone_from(&composited_rgba);
|
||||||
|
mon.preview_frame_seq = mon.preview_frame_seq.wrapping_add(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
let sub_image = xr::SwapchainSubImage::new()
|
||||||
|
.swapchain(&vk_xr.swapchain)
|
||||||
|
.image_array_index(0)
|
||||||
|
.image_rect(xr::Rect2Di {
|
||||||
|
offset: xr::Offset2Di { x: 0, y: 0 },
|
||||||
|
extent: xr::Extent2Di {
|
||||||
|
width: cfg.video_width as i32,
|
||||||
|
height: cfg.video_height as i32,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
match active_proj {
|
||||||
|
ProjectionMode::Dome140 => {
|
||||||
|
let equirect_layer = xr::CompositionLayerEquirect2KHR::new()
|
||||||
|
.space(&view_space)
|
||||||
|
.eye_visibility(xr::EyeVisibility::BOTH)
|
||||||
|
.sub_image(sub_image)
|
||||||
|
.pose(xr::Posef::IDENTITY)
|
||||||
|
.radius(cfg.screen_distance_m)
|
||||||
|
.central_horizontal_angle(horizontal_fov_rad)
|
||||||
|
.upper_vertical_angle(half_vert_fov_rad)
|
||||||
|
.lower_vertical_angle(-half_vert_fov_rad);
|
||||||
|
|
||||||
|
vk_xr.frame_stream.end(
|
||||||
|
xr_frame_state.predicted_display_time,
|
||||||
|
xr::EnvironmentBlendMode::OPAQUE,
|
||||||
|
&[&equirect_layer],
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
ProjectionMode::Cylinder140 => {
|
||||||
|
let cylinder_layer = xr::CompositionLayerCylinderKHR::new()
|
||||||
|
.space(&view_space)
|
||||||
|
.eye_visibility(xr::EyeVisibility::BOTH)
|
||||||
|
.sub_image(sub_image)
|
||||||
|
.pose(xr::Posef::IDENTITY)
|
||||||
|
.radius(cfg.screen_distance_m)
|
||||||
|
.central_angle(horizontal_fov_rad)
|
||||||
|
.aspect_ratio(aspect);
|
||||||
|
|
||||||
|
vk_xr.frame_stream.end(
|
||||||
|
xr_frame_state.predicted_display_time,
|
||||||
|
xr::EnvironmentBlendMode::OPAQUE,
|
||||||
|
&[&cylinder_layer],
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
ProjectionMode::FlatQuad => {
|
||||||
|
let quad_pose = xr::Posef {
|
||||||
|
orientation: xr::Quaternionf::IDENTITY,
|
||||||
|
position: xr::Vector3f {
|
||||||
|
x: 0.0,
|
||||||
|
y: 0.0,
|
||||||
|
z: -cfg.screen_distance_m,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
let quad_layer = xr::CompositionLayerQuad::new()
|
||||||
|
.space(&view_space)
|
||||||
|
.eye_visibility(xr::EyeVisibility::BOTH)
|
||||||
|
.sub_image(sub_image)
|
||||||
|
.pose(quad_pose)
|
||||||
|
.size(xr::Extent2Df {
|
||||||
|
width: cfg.screen_width_m,
|
||||||
|
height: screen_height_m,
|
||||||
|
});
|
||||||
|
|
||||||
|
vk_xr.frame_stream.end(
|
||||||
|
xr_frame_state.predicted_display_time,
|
||||||
|
xr::EnvironmentBlendMode::OPAQUE,
|
||||||
|
&[&quad_layer],
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
fn run_desktop_fallback_loop(
|
||||||
|
cfg: &AppConfig,
|
||||||
|
monitor: &Arc<Mutex<RuntimeMonitor>>,
|
||||||
|
stop_flag: &Arc<AtomicBool>,
|
||||||
|
recenter_flag: &Arc<AtomicBool>,
|
||||||
|
telem_enabled_flag: &Arc<AtomicBool>,
|
||||||
|
video_rx: Option<&UsbVideoReceiver>,
|
||||||
|
telem_rx_opt: &mut Option<TelemetryReceiver>,
|
||||||
|
mut head_tracker: Option<&mut NomadHeadTracker>,
|
||||||
|
) {
|
||||||
|
let proj_mode = ProjectionMode::from_str(&cfg.projection_mode);
|
||||||
|
let dome_lut = DomeWarpLut::new(
|
||||||
|
cfg.video_width,
|
||||||
|
cfg.video_height,
|
||||||
|
cfg.camera_fov_deg,
|
||||||
|
cfg.lens_k1,
|
||||||
|
cfg.lens_k2,
|
||||||
|
);
|
||||||
|
let mut composited_rgba = vec![0u8; (cfg.video_width * cfg.video_height * 4) as usize];
|
||||||
|
let mut standby_tick: u32 = 0;
|
||||||
|
let mut last_frame_id: u64 = 0;
|
||||||
|
let mut fps_counter: u32 = 0;
|
||||||
|
let mut fps_timer = Instant::now();
|
||||||
|
|
||||||
|
while !stop_flag.load(Ordering::Relaxed) {
|
||||||
|
let loop_start = Instant::now();
|
||||||
|
|
||||||
|
let telem_on = telem_enabled_flag.load(Ordering::Relaxed);
|
||||||
|
sync_telemetry_receiver(cfg, telem_on, telem_rx_opt, monitor);
|
||||||
|
|
||||||
|
let (manual_pan, manual_tilt, manual_roll) = {
|
||||||
|
let mut mon = monitor.lock();
|
||||||
|
if 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(ht) = head_tracker.as_deref_mut() {
|
||||||
|
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(ht) = head_tracker.as_deref_mut() {
|
||||||
|
let sim_quat = Quat::from_euler(
|
||||||
|
EulerRot::YXZ,
|
||||||
|
(-manual_pan).to_radians(),
|
||||||
|
manual_tilt.to_radians(),
|
||||||
|
(-manual_roll).to_radians(),
|
||||||
|
);
|
||||||
|
if let Ok(sample) = ht.send_pose(sim_quat) {
|
||||||
|
current_pose = sample;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(rx) = video_rx {
|
||||||
|
let lock = rx.latest_frame();
|
||||||
|
let guard = lock.lock();
|
||||||
|
if let Some(ref vf) = *guard {
|
||||||
|
if vf.frame_id != last_frame_id {
|
||||||
|
last_frame_id = vf.frame_id;
|
||||||
|
fps_counter += 1;
|
||||||
|
}
|
||||||
|
dome_lut.apply(&vf.rgba_data, &mut composited_rgba);
|
||||||
|
} else {
|
||||||
|
standby_tick = standby_tick.wrapping_add(1);
|
||||||
|
let pattern = UsbVideoReceiver::generate_standby_pattern(
|
||||||
|
cfg.video_width,
|
||||||
|
cfg.video_height,
|
||||||
|
standby_tick,
|
||||||
|
);
|
||||||
|
composited_rgba.copy_from_slice(&pattern);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
standby_tick = standby_tick.wrapping_add(1);
|
||||||
|
let pattern = UsbVideoReceiver::generate_standby_pattern(
|
||||||
|
cfg.video_width,
|
||||||
|
cfg.video_height,
|
||||||
|
standby_tick,
|
||||||
|
);
|
||||||
|
composited_rgba.copy_from_slice(&pattern);
|
||||||
|
}
|
||||||
|
|
||||||
|
let telem_snapshot = telem_rx_opt
|
||||||
|
.as_ref()
|
||||||
|
.map(|t| t.state().lock().clone())
|
||||||
|
.unwrap_or_default();
|
||||||
|
|
||||||
|
if telem_on {
|
||||||
|
OsdOverlay::render(
|
||||||
|
&mut composited_rgba,
|
||||||
|
cfg.video_width,
|
||||||
|
cfg.video_height,
|
||||||
|
&telem_snapshot,
|
||||||
|
current_pose.pan_deg,
|
||||||
|
current_pose.tilt_deg,
|
||||||
|
current_pose.roll_deg,
|
||||||
|
cfg.max_pan_deg,
|
||||||
|
cfg.max_tilt_deg,
|
||||||
|
proj_mode.label(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
let mut mon = monitor.lock();
|
||||||
|
if fps_timer.elapsed() >= Duration::from_secs(1) {
|
||||||
|
mon.video_fps = fps_counter as f32 / fps_timer.elapsed().as_secs_f32();
|
||||||
|
fps_counter = 0;
|
||||||
|
fps_timer = Instant::now();
|
||||||
|
}
|
||||||
|
if current_pose.send_errors > 0 {
|
||||||
|
mon.nomad_wifi_status = SubsystemStatus::Error(format!(
|
||||||
|
"Erreur d'envoi UDP vers {}:{} ({} échecs)",
|
||||||
|
cfg.nomad_ip, cfg.nomad_port, current_pose.send_errors
|
||||||
|
));
|
||||||
|
}
|
||||||
|
mon.video_frames_total = last_frame_id;
|
||||||
|
mon.latest_head_pose = current_pose;
|
||||||
|
mon.latest_telemetry = telem_snapshot;
|
||||||
|
mon.preview_width = cfg.video_width;
|
||||||
|
mon.preview_height = cfg.video_height;
|
||||||
|
mon.preview_rgba.clone_from(&composited_rgba);
|
||||||
|
mon.preview_frame_seq = mon.preview_frame_seq.wrapping_add(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
let elapsed = loop_start.elapsed();
|
||||||
|
let target_dt = Duration::from_millis(16);
|
||||||
|
if elapsed < target_dt {
|
||||||
|
thread::sleep(target_dt - elapsed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+947
@@ -0,0 +1,947 @@
|
|||||||
|
use crate::config::AppConfig;
|
||||||
|
use crate::engine::{FpvEngineController, SubsystemStatus};
|
||||||
|
use crate::logger::LogBuffer;
|
||||||
|
use crate::nomad_elrs::NomadHeadTracker;
|
||||||
|
use eframe::egui::{self, Color32, RichText, TextureHandle, TextureOptions};
|
||||||
|
use log::Level;
|
||||||
|
use parking_lot::Mutex;
|
||||||
|
use std::process::Command;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
enum LogFilter {
|
||||||
|
All,
|
||||||
|
WarningsAndErrors,
|
||||||
|
ErrorsOnly,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct SteamFrameGuiApp {
|
||||||
|
cfg: AppConfig,
|
||||||
|
engine: FpvEngineController,
|
||||||
|
log_buffer: Arc<Mutex<LogBuffer>>,
|
||||||
|
log_filter: LogFilter,
|
||||||
|
auto_scroll_logs: bool,
|
||||||
|
video_texture: Option<TextureHandle>,
|
||||||
|
last_displayed_frame_seq: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SteamFrameGuiApp {
|
||||||
|
pub fn new(
|
||||||
|
cc: &eframe::CreationContext<'_>,
|
||||||
|
cfg: AppConfig,
|
||||||
|
log_buffer: Arc<Mutex<LogBuffer>>,
|
||||||
|
) -> Self {
|
||||||
|
cc.egui_ctx.set_visuals(egui::Visuals::dark());
|
||||||
|
|
||||||
|
let mut engine = FpvEngineController::new(cfg.telemetry_enabled);
|
||||||
|
engine.start(cfg.clone());
|
||||||
|
|
||||||
|
Self {
|
||||||
|
cfg,
|
||||||
|
engine,
|
||||||
|
log_buffer,
|
||||||
|
log_filter: LogFilter::All,
|
||||||
|
auto_scroll_logs: true,
|
||||||
|
video_texture: None,
|
||||||
|
last_displayed_frame_seq: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn status_badge(ui: &mut egui::Ui, title: &str, status: &SubsystemStatus) {
|
||||||
|
let (color, text) = match status {
|
||||||
|
SubsystemStatus::Stopped => (Color32::from_rgb(130, 130, 140), "Arrêté".to_string()),
|
||||||
|
SubsystemStatus::Disabled => (
|
||||||
|
Color32::from_rgb(110, 115, 125),
|
||||||
|
"OFF (Désactivée)".to_string(),
|
||||||
|
),
|
||||||
|
SubsystemStatus::Starting => (
|
||||||
|
Color32::from_rgb(255, 200, 60),
|
||||||
|
"Démarrage...".to_string(),
|
||||||
|
),
|
||||||
|
SubsystemStatus::Running(msg) => (Color32::from_rgb(70, 230, 120), msg.clone()),
|
||||||
|
SubsystemStatus::Warning(msg) => (Color32::from_rgb(255, 180, 50), msg.clone()),
|
||||||
|
SubsystemStatus::Error(msg) => (Color32::from_rgb(255, 75, 75), msg.clone()),
|
||||||
|
};
|
||||||
|
|
||||||
|
egui::Frame::group(ui.style())
|
||||||
|
.fill(Color32::from_rgb(24, 28, 36))
|
||||||
|
.stroke(egui::Stroke::new(1.0, color))
|
||||||
|
.inner_margin(egui::Margin::symmetric(8.0, 4.0))
|
||||||
|
.show(ui, |ui| {
|
||||||
|
ui.horizontal(|ui| {
|
||||||
|
ui.colored_label(color, "●");
|
||||||
|
ui.label(RichText::new(title).strong());
|
||||||
|
ui.label(RichText::new(text).color(color).small());
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run_usb_rndis_setup_script(&self) {
|
||||||
|
log::info!("[Action Utilisateur] Exécution du script de configuration USB RNDIS (scripts/setup_usb_rndis.sh)...");
|
||||||
|
match Command::new("bash")
|
||||||
|
.arg("scripts/setup_usb_rndis.sh")
|
||||||
|
.output()
|
||||||
|
{
|
||||||
|
Ok(output) => {
|
||||||
|
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||||
|
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||||
|
if output.status.success() {
|
||||||
|
log::info!(
|
||||||
|
"[USB RNDIS] Interface configurée avec succès : {}",
|
||||||
|
stdout.trim()
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
log::error!(
|
||||||
|
"[USB RNDIS] Échec du script (code {:?}) : {}",
|
||||||
|
output.status.code(),
|
||||||
|
stderr.trim()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
log::error!(
|
||||||
|
"[USB RNDIS] Impossible de lancer scripts/setup_usb_rndis.sh : {}",
|
||||||
|
e
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Configure à distance la carte Radxa Zero 3W (OpenIPC `runcam_wifilink_sdcard.img`) via SSH sur le lien USB OTG
|
||||||
|
fn configure_radxa_vrx_over_usb(&self) {
|
||||||
|
let ch = self.cfg.wifi_channel;
|
||||||
|
let ip = &self.cfg.radxa_vrx_ip;
|
||||||
|
let port = self.cfg.video_udp_port;
|
||||||
|
log::info!(
|
||||||
|
"[Radxa Zero 3W] Envoi de la configuration OpenIPC (Canal 5.8GHz={} / Redirection RTP -> 192.168.1.10:{}) vers root@{}...",
|
||||||
|
ch,
|
||||||
|
port,
|
||||||
|
ip
|
||||||
|
);
|
||||||
|
|
||||||
|
let remote_cmd = format!(
|
||||||
|
"sed -i 's/^wifi_channel.*/wifi_channel = {ch}/' /etc/wifibroadcast.cfg 2>/dev/null || true; \
|
||||||
|
iw dev wlan0 set channel {ch} HT20 2>/dev/null || true; \
|
||||||
|
echo 'Radxa Zero 3W 8812EU configurée sur le canal {ch}'"
|
||||||
|
);
|
||||||
|
|
||||||
|
match Command::new("ssh")
|
||||||
|
.args([
|
||||||
|
"-o",
|
||||||
|
"ConnectTimeout=2",
|
||||||
|
"-o",
|
||||||
|
"StrictHostKeyChecking=no",
|
||||||
|
&format!("root@{}", ip),
|
||||||
|
&remote_cmd,
|
||||||
|
])
|
||||||
|
.output()
|
||||||
|
{
|
||||||
|
Ok(output) => {
|
||||||
|
if output.status.success() {
|
||||||
|
log::info!(
|
||||||
|
"[Radxa Zero 3W] Succès : {}",
|
||||||
|
String::from_utf8_lossy(&output.stdout).trim()
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
log::error!(
|
||||||
|
"[Radxa Zero 3W] Échec SSH vers root@{} : {}",
|
||||||
|
ip,
|
||||||
|
String::from_utf8_lossy(&output.stderr).trim()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
log::error!("[Radxa Zero 3W] Erreur exécution SSH : {}", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn test_nomad_udp_packet(&self) {
|
||||||
|
log::info!(
|
||||||
|
"[Test Nomad] Envoi d'un paquet de test Head-Tracking (neutre 992) vers {}:{}...",
|
||||||
|
self.cfg.nomad_ip,
|
||||||
|
self.cfg.nomad_port
|
||||||
|
);
|
||||||
|
let use_crsf = self.cfg.ht_protocol.eq_ignore_ascii_case("crsf");
|
||||||
|
match NomadHeadTracker::new(
|
||||||
|
&self.cfg.nomad_ip,
|
||||||
|
self.cfg.nomad_port,
|
||||||
|
self.cfg.max_pan_deg,
|
||||||
|
self.cfg.max_tilt_deg,
|
||||||
|
self.cfg.max_roll_deg,
|
||||||
|
use_crsf,
|
||||||
|
) {
|
||||||
|
Ok(mut ht) => match ht.send_pose(glam::Quat::IDENTITY) {
|
||||||
|
Ok(sample) => {
|
||||||
|
if sample.send_errors == 0 {
|
||||||
|
log::info!(
|
||||||
|
"[Test Nomad] Paquet UDP envoyé avec succès vers {}:{} (Pan={}, Tilt={}, Roll={})",
|
||||||
|
self.cfg.nomad_ip,
|
||||||
|
self.cfg.nomad_port,
|
||||||
|
sample.pan_crsf,
|
||||||
|
sample.tilt_crsf,
|
||||||
|
sample.roll_crsf
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => log::error!("[Test Nomad] Erreur lors de l'envoi : {}", e),
|
||||||
|
},
|
||||||
|
Err(e) => log::error!("[Test Nomad] Configuration invalide : {}", e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl eframe::App for SteamFrameGuiApp {
|
||||||
|
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
|
||||||
|
ctx.request_repaint_after(Duration::from_millis(16));
|
||||||
|
|
||||||
|
let (
|
||||||
|
usb_status,
|
||||||
|
xr_status,
|
||||||
|
nomad_status,
|
||||||
|
telem_status,
|
||||||
|
fps,
|
||||||
|
total_frames,
|
||||||
|
pose,
|
||||||
|
telem,
|
||||||
|
) = {
|
||||||
|
let mon = self.engine.monitor.lock();
|
||||||
|
if mon.preview_frame_seq != self.last_displayed_frame_seq
|
||||||
|
&& !mon.preview_rgba.is_empty()
|
||||||
|
&& mon.preview_width > 0
|
||||||
|
&& mon.preview_height > 0
|
||||||
|
{
|
||||||
|
self.last_displayed_frame_seq = mon.preview_frame_seq;
|
||||||
|
let image = egui::ColorImage::from_rgba_unmultiplied(
|
||||||
|
[mon.preview_width as usize, mon.preview_height as usize],
|
||||||
|
&mon.preview_rgba,
|
||||||
|
);
|
||||||
|
if let Some(ref mut tex) = self.video_texture {
|
||||||
|
tex.set(image, TextureOptions::LINEAR);
|
||||||
|
} else {
|
||||||
|
self.video_texture =
|
||||||
|
Some(ctx.load_texture("fpv_preview", image, TextureOptions::LINEAR));
|
||||||
|
}
|
||||||
|
ctx.request_repaint();
|
||||||
|
}
|
||||||
|
|
||||||
|
(
|
||||||
|
mon.usb_video_status.clone(),
|
||||||
|
mon.openxr_status.clone(),
|
||||||
|
mon.nomad_wifi_status.clone(),
|
||||||
|
mon.telemetry_status.clone(),
|
||||||
|
mon.video_fps,
|
||||||
|
mon.video_frames_total,
|
||||||
|
mon.latest_head_pose,
|
||||||
|
mon.latest_telemetry.clone(),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// 1. BARRE SUPÉRIEURE : ÉTAT DES SYSTÈMES + BOUTON TÉLÉMÉTRIE ON/OFF
|
||||||
|
// =========================================================================
|
||||||
|
egui::TopBottomPanel::top("top_status_bar")
|
||||||
|
.show(ctx, |ui| {
|
||||||
|
ui.horizontal_wrapped(|ui| {
|
||||||
|
ui.heading(RichText::new("🥽 SteamFrame FPV Control Center").strong());
|
||||||
|
ui.separator();
|
||||||
|
|
||||||
|
let is_running = self.engine.is_running();
|
||||||
|
if is_running {
|
||||||
|
if ui
|
||||||
|
.button(
|
||||||
|
RichText::new("🔄 Appliquer & Redémarrer")
|
||||||
|
.color(Color32::from_rgb(100, 230, 140)),
|
||||||
|
)
|
||||||
|
.clicked()
|
||||||
|
{
|
||||||
|
log::info!("[Action Utilisateur] Redémarrage des services avec la nouvelle configuration...");
|
||||||
|
self.engine.start(self.cfg.clone());
|
||||||
|
}
|
||||||
|
if ui
|
||||||
|
.button(
|
||||||
|
RichText::new("⏹ Arrêter les services")
|
||||||
|
.color(Color32::from_rgb(255, 180, 70)),
|
||||||
|
)
|
||||||
|
.clicked()
|
||||||
|
{
|
||||||
|
self.engine.stop();
|
||||||
|
}
|
||||||
|
} else if ui
|
||||||
|
.button(
|
||||||
|
RichText::new("▶ Démarrer les services")
|
||||||
|
.color(Color32::from_rgb(80, 240, 130))
|
||||||
|
.strong(),
|
||||||
|
)
|
||||||
|
.clicked()
|
||||||
|
{
|
||||||
|
log::info!("[Action Utilisateur] Démarrage manuel des services...");
|
||||||
|
self.engine.start(self.cfg.clone());
|
||||||
|
}
|
||||||
|
|
||||||
|
if ui.button("🎯 Recentrer la tête (Tare)").clicked() {
|
||||||
|
self.engine.request_recenter();
|
||||||
|
}
|
||||||
|
|
||||||
|
ui.separator();
|
||||||
|
|
||||||
|
let telem_btn_label = if self.cfg.telemetry_enabled {
|
||||||
|
RichText::new("📶 Télémétrie & OSD : ON")
|
||||||
|
.color(Color32::from_rgb(70, 245, 130))
|
||||||
|
.strong()
|
||||||
|
} else {
|
||||||
|
RichText::new("📶 Télémétrie & OSD : OFF")
|
||||||
|
.color(Color32::from_rgb(180, 180, 190))
|
||||||
|
};
|
||||||
|
|
||||||
|
if ui
|
||||||
|
.button(telem_btn_label)
|
||||||
|
.on_hover_text("Activer ou désactiver à chaud l'écoute UDP Télémétrie (14551) et l'affichage OSD")
|
||||||
|
.clicked()
|
||||||
|
{
|
||||||
|
self.cfg.telemetry_enabled = !self.cfg.telemetry_enabled;
|
||||||
|
self.engine.set_telemetry_enabled(self.cfg.telemetry_enabled);
|
||||||
|
}
|
||||||
|
|
||||||
|
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||||
|
if ui
|
||||||
|
.button(
|
||||||
|
RichText::new("❌ Quitter l'application")
|
||||||
|
.color(Color32::from_rgb(255, 90, 90))
|
||||||
|
.strong(),
|
||||||
|
)
|
||||||
|
.clicked()
|
||||||
|
{
|
||||||
|
log::info!("[Action Utilisateur] Fermeture de l'application demandée.");
|
||||||
|
self.engine.stop();
|
||||||
|
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
ui.add_space(6.0);
|
||||||
|
ui.horizontal_wrapped(|ui| {
|
||||||
|
Self::status_badge(ui, "VRX Radxa Zero 3W", &usb_status);
|
||||||
|
Self::status_badge(ui, "Casque OpenXR", &xr_status);
|
||||||
|
Self::status_badge(ui, "Wi-Fi Nomad ELRS", &nomad_status);
|
||||||
|
Self::status_badge(ui, "Télémétrie OSD", &telem_status);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// 2. PANNEAU INFÉRIEUR : JOURNAL D'ÉVÉNEMENTS & DIAGNOSTIC DES ERREURS
|
||||||
|
// =========================================================================
|
||||||
|
egui::TopBottomPanel::bottom("bottom_logs_panel")
|
||||||
|
.resizable(true)
|
||||||
|
.default_height(210.0)
|
||||||
|
.min_height(120.0)
|
||||||
|
.show(ctx, |ui| {
|
||||||
|
let (err_count, warn_count) = {
|
||||||
|
let lb = self.log_buffer.lock();
|
||||||
|
(lb.error_count, lb.warn_count)
|
||||||
|
};
|
||||||
|
|
||||||
|
ui.horizontal(|ui| {
|
||||||
|
ui.label(RichText::new("📋 Journal de Diagnostic & Erreurs").strong());
|
||||||
|
ui.separator();
|
||||||
|
|
||||||
|
ui.colored_label(
|
||||||
|
if err_count > 0 {
|
||||||
|
Color32::from_rgb(255, 80, 80)
|
||||||
|
} else {
|
||||||
|
Color32::GRAY
|
||||||
|
},
|
||||||
|
format!("Erreurs : {}", err_count),
|
||||||
|
);
|
||||||
|
ui.colored_label(
|
||||||
|
if warn_count > 0 {
|
||||||
|
Color32::from_rgb(255, 190, 60)
|
||||||
|
} else {
|
||||||
|
Color32::GRAY
|
||||||
|
},
|
||||||
|
format!("Avertissements : {}", warn_count),
|
||||||
|
);
|
||||||
|
|
||||||
|
ui.separator();
|
||||||
|
ui.selectable_value(&mut self.log_filter, LogFilter::All, "Tout afficher");
|
||||||
|
ui.selectable_value(
|
||||||
|
&mut self.log_filter,
|
||||||
|
LogFilter::WarningsAndErrors,
|
||||||
|
"Warn + Erreurs",
|
||||||
|
);
|
||||||
|
ui.selectable_value(
|
||||||
|
&mut self.log_filter,
|
||||||
|
LogFilter::ErrorsOnly,
|
||||||
|
"Erreurs seules",
|
||||||
|
);
|
||||||
|
|
||||||
|
ui.separator();
|
||||||
|
ui.checkbox(&mut self.auto_scroll_logs, "Défilement auto");
|
||||||
|
|
||||||
|
if ui.button("🧹 Effacer").clicked() {
|
||||||
|
let mut lb = self.log_buffer.lock();
|
||||||
|
lb.entries.clear();
|
||||||
|
lb.error_count = 0;
|
||||||
|
lb.warn_count = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ui.button("📎 Copier les logs").clicked() {
|
||||||
|
let lb = self.log_buffer.lock();
|
||||||
|
let dump: String = lb
|
||||||
|
.entries
|
||||||
|
.iter()
|
||||||
|
.map(|e| {
|
||||||
|
format!("[{}] [{}] ({}) {}", e.timestamp, e.level, e.target, e.message)
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join("\n");
|
||||||
|
ctx.copy_text(dump);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
ui.separator();
|
||||||
|
|
||||||
|
egui::ScrollArea::vertical()
|
||||||
|
.auto_shrink([false, false])
|
||||||
|
.stick_to_bottom(self.auto_scroll_logs)
|
||||||
|
.show(ui, |ui| {
|
||||||
|
let lb = self.log_buffer.lock();
|
||||||
|
for entry in lb.entries.iter() {
|
||||||
|
match self.log_filter {
|
||||||
|
LogFilter::All => {}
|
||||||
|
LogFilter::WarningsAndErrors => {
|
||||||
|
if entry.level > Level::Warn {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
LogFilter::ErrorsOnly => {
|
||||||
|
if entry.level != Level::Error {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let (lvl_color, badge) = match entry.level {
|
||||||
|
Level::Error => (Color32::from_rgb(255, 85, 85), "[ERREUR]"),
|
||||||
|
Level::Warn => (Color32::from_rgb(255, 195, 65), "[WARN] "),
|
||||||
|
_ => (Color32::from_rgb(130, 200, 255), "[INFO] "),
|
||||||
|
};
|
||||||
|
|
||||||
|
ui.horizontal_wrapped(|ui| {
|
||||||
|
ui.label(
|
||||||
|
RichText::new(&entry.timestamp)
|
||||||
|
.monospace()
|
||||||
|
.color(Color32::GRAY),
|
||||||
|
);
|
||||||
|
ui.label(RichText::new(badge).monospace().strong().color(lvl_color));
|
||||||
|
ui.label(
|
||||||
|
RichText::new(&entry.message)
|
||||||
|
.monospace()
|
||||||
|
.color(if entry.level == Level::Error {
|
||||||
|
Color32::from_rgb(255, 160, 160)
|
||||||
|
} else {
|
||||||
|
Color32::LIGHT_GRAY
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// 3. PANNEAU GAUCHE : CONFIGURATION RADXA ZERO 3W, WI-FI NOMAD & VR
|
||||||
|
// =========================================================================
|
||||||
|
egui::SidePanel::left("left_config_panel")
|
||||||
|
.resizable(true)
|
||||||
|
.default_width(360.0)
|
||||||
|
.show(ctx, |ui| {
|
||||||
|
egui::ScrollArea::vertical().show(ui, |ui| {
|
||||||
|
ui.heading("⚙ Configuration Matérielle");
|
||||||
|
ui.add_space(6.0);
|
||||||
|
|
||||||
|
// --- Section 1 : VRX Eachine Sphere Link (Radxa Zero 3W + 8812EU) ---
|
||||||
|
egui::CollapsingHeader::new(
|
||||||
|
RichText::new("🔌 1. VRX Sphere Link (Radxa Zero 3W + 8812EU)").strong(),
|
||||||
|
)
|
||||||
|
.default_open(true)
|
||||||
|
.show(ui, |ui| {
|
||||||
|
egui::Grid::new("usb_cfg_grid")
|
||||||
|
.num_columns(2)
|
||||||
|
.spacing([8.0, 6.0])
|
||||||
|
.show(ui, |ui| {
|
||||||
|
ui.label("Mode Entrée USB :");
|
||||||
|
egui::ComboBox::from_id_salt("usb_mode_combo")
|
||||||
|
.selected_text(if self.cfg.usb_video_mode == "uvc" {
|
||||||
|
"Mini-HDMI -> USB UVC"
|
||||||
|
} else {
|
||||||
|
"USB-C OTG RNDIS (RTP)"
|
||||||
|
})
|
||||||
|
.show_ui(ui, |ui| {
|
||||||
|
ui.selectable_value(
|
||||||
|
&mut self.cfg.usb_video_mode,
|
||||||
|
"rndis".to_string(),
|
||||||
|
"USB-C OTG RNDIS (Flux RTP direct :5600)",
|
||||||
|
);
|
||||||
|
ui.selectable_value(
|
||||||
|
&mut self.cfg.usb_video_mode,
|
||||||
|
"uvc".to_string(),
|
||||||
|
"Mini-HDMI -> Carte Capture USB-C UVC (/dev/video0)",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
ui.end_row();
|
||||||
|
|
||||||
|
if self.cfg.usb_video_mode == "uvc" {
|
||||||
|
ui.label("Périphérique V4L2 :");
|
||||||
|
ui.text_edit_singleline(&mut self.cfg.uvc_device);
|
||||||
|
ui.end_row();
|
||||||
|
} else {
|
||||||
|
ui.label("IP Écoute SteamFrame :");
|
||||||
|
ui.text_edit_singleline(&mut self.cfg.usb_bind_ip);
|
||||||
|
ui.end_row();
|
||||||
|
|
||||||
|
ui.label("IP Radxa Zero 3W :");
|
||||||
|
ui.text_edit_singleline(&mut self.cfg.radxa_vrx_ip);
|
||||||
|
ui.end_row();
|
||||||
|
|
||||||
|
ui.label("Port UDP Vidéo RTP :");
|
||||||
|
ui.add(
|
||||||
|
egui::DragValue::new(&mut self.cfg.video_udp_port)
|
||||||
|
.range(1024..=65535),
|
||||||
|
);
|
||||||
|
ui.end_row();
|
||||||
|
|
||||||
|
ui.label("Format Transport UDP :");
|
||||||
|
egui::ComboBox::from_id_salt("transport_combo")
|
||||||
|
.selected_text(if self.cfg.stream_transport == "rtp" {
|
||||||
|
"RTP (OpenIPC / WFB)"
|
||||||
|
} else {
|
||||||
|
"Raw NAL (Ruby FPV direct)"
|
||||||
|
})
|
||||||
|
.show_ui(ui, |ui| {
|
||||||
|
ui.selectable_value(
|
||||||
|
&mut self.cfg.stream_transport,
|
||||||
|
"raw".to_string(),
|
||||||
|
"Raw NAL (Ruby FPV direct)",
|
||||||
|
);
|
||||||
|
ui.selectable_value(
|
||||||
|
&mut self.cfg.stream_transport,
|
||||||
|
"rtp".to_string(),
|
||||||
|
"RTP (OpenIPC / WFB-ng)",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
ui.end_row();
|
||||||
|
|
||||||
|
ui.label("Codec Vidéo :");
|
||||||
|
egui::ComboBox::from_id_salt("codec_combo")
|
||||||
|
.selected_text(self.cfg.codec.to_uppercase())
|
||||||
|
.show_ui(ui, |ui| {
|
||||||
|
ui.selectable_value(
|
||||||
|
&mut self.cfg.codec,
|
||||||
|
"h264".to_string(),
|
||||||
|
"H.264 (AVC - Défaut Ruby)",
|
||||||
|
);
|
||||||
|
ui.selectable_value(
|
||||||
|
&mut self.cfg.codec,
|
||||||
|
"h265".to_string(),
|
||||||
|
"H.265 (HEVC)",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
ui.end_row();
|
||||||
|
}
|
||||||
|
|
||||||
|
ui.label("Canal 5.8GHz (8812EU) :");
|
||||||
|
egui::ComboBox::from_id_salt("ch_combo")
|
||||||
|
.selected_text(format!("Canal {}", self.cfg.wifi_channel))
|
||||||
|
.show_ui(ui, |ui| {
|
||||||
|
for &(ch, desc) in &[
|
||||||
|
(161, "Canal 161 (5805 MHz - Défaut usine)"),
|
||||||
|
(149, "Canal 149 (5745 MHz)"),
|
||||||
|
(153, "Canal 153 (5765 MHz)"),
|
||||||
|
(157, "Canal 157 (5785 MHz)"),
|
||||||
|
(165, "Canal 165 (5825 MHz)"),
|
||||||
|
(36, "Canal 36 (5180 MHz)"),
|
||||||
|
(40, "Canal 40 (5200 MHz)"),
|
||||||
|
(44, "Canal 44 (5220 MHz)"),
|
||||||
|
(48, "Canal 48 (5240 MHz)"),
|
||||||
|
] {
|
||||||
|
ui.selectable_value(
|
||||||
|
&mut self.cfg.wifi_channel,
|
||||||
|
ch,
|
||||||
|
desc,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
ui.end_row();
|
||||||
|
|
||||||
|
ui.label("Profil Résolution VRX :");
|
||||||
|
egui::ComboBox::from_id_salt("res_profile_combo")
|
||||||
|
.selected_text(&self.cfg.vrx_video_profile)
|
||||||
|
.show_ui(ui, |ui| {
|
||||||
|
if ui
|
||||||
|
.selectable_value(
|
||||||
|
&mut self.cfg.vrx_video_profile,
|
||||||
|
"1080p60".to_string(),
|
||||||
|
"1080P @ 60 FPS (Défaut usine)",
|
||||||
|
)
|
||||||
|
.clicked()
|
||||||
|
{
|
||||||
|
self.cfg.video_width = 1920;
|
||||||
|
self.cfg.video_height = 1080;
|
||||||
|
}
|
||||||
|
if ui
|
||||||
|
.selectable_value(
|
||||||
|
&mut self.cfg.vrx_video_profile,
|
||||||
|
"1080p90".to_string(),
|
||||||
|
"1080P @ 90 FPS (Basse latence)",
|
||||||
|
)
|
||||||
|
.clicked()
|
||||||
|
{
|
||||||
|
self.cfg.video_width = 1920;
|
||||||
|
self.cfg.video_height = 1080;
|
||||||
|
}
|
||||||
|
if ui
|
||||||
|
.selectable_value(
|
||||||
|
&mut self.cfg.vrx_video_profile,
|
||||||
|
"720p120".to_string(),
|
||||||
|
"720P @ 120 FPS (Latence 40-50 ms)",
|
||||||
|
)
|
||||||
|
.clicked()
|
||||||
|
{
|
||||||
|
self.cfg.video_width = 1280;
|
||||||
|
self.cfg.video_height = 720;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
ui.end_row();
|
||||||
|
});
|
||||||
|
|
||||||
|
if self.cfg.usb_video_mode != "uvc" {
|
||||||
|
ui.add_space(4.0);
|
||||||
|
if ui
|
||||||
|
.button("⚡ 1. Configurer l'interface usb0 (RNDIS)")
|
||||||
|
.clicked()
|
||||||
|
{
|
||||||
|
self.run_usb_rndis_setup_script();
|
||||||
|
}
|
||||||
|
if ui
|
||||||
|
.button(format!(
|
||||||
|
"🔧 2. Appliquer Canal {} sur la Radxa Zero 3W (SSH)",
|
||||||
|
self.cfg.wifi_channel
|
||||||
|
))
|
||||||
|
.clicked()
|
||||||
|
{
|
||||||
|
self.configure_radxa_vrx_over_usb();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
ui.add_space(8.0);
|
||||||
|
|
||||||
|
// --- Section 2 : Wi-Fi RadioMaster Nomad (ELRS Backpack) ---
|
||||||
|
egui::CollapsingHeader::new(
|
||||||
|
RichText::new("📡 2. Wi-Fi RadioMaster Nomad (ELRS)").strong(),
|
||||||
|
)
|
||||||
|
.default_open(true)
|
||||||
|
.show(ui, |ui| {
|
||||||
|
egui::Grid::new("nomad_cfg_grid")
|
||||||
|
.num_columns(2)
|
||||||
|
.spacing([8.0, 6.0])
|
||||||
|
.show(ui, |ui| {
|
||||||
|
ui.label("IP Backpack Nomad :");
|
||||||
|
ui.text_edit_singleline(&mut self.cfg.nomad_ip);
|
||||||
|
ui.end_row();
|
||||||
|
|
||||||
|
ui.label("Port UDP Nomad :");
|
||||||
|
ui.add(
|
||||||
|
egui::DragValue::new(&mut self.cfg.nomad_port)
|
||||||
|
.range(1024..=65535),
|
||||||
|
);
|
||||||
|
ui.end_row();
|
||||||
|
|
||||||
|
ui.label("Protocole Head-Track :");
|
||||||
|
egui::ComboBox::from_id_salt("ht_proto_combo")
|
||||||
|
.selected_text(if self.cfg.ht_protocol == "crsf" {
|
||||||
|
"CRSF (0x16)"
|
||||||
|
} else {
|
||||||
|
"MSPv2 PTR (0x0383)"
|
||||||
|
})
|
||||||
|
.show_ui(ui, |ui| {
|
||||||
|
ui.selectable_value(
|
||||||
|
&mut self.cfg.ht_protocol,
|
||||||
|
"msp".to_string(),
|
||||||
|
"MSPv2 PTR (0x0383 - Recommandé)",
|
||||||
|
);
|
||||||
|
ui.selectable_value(
|
||||||
|
&mut self.cfg.ht_protocol,
|
||||||
|
"crsf".to_string(),
|
||||||
|
"CRSF RC_CHANNELS_PACKED (0x16)",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
ui.end_row();
|
||||||
|
|
||||||
|
ui.label("Course Max Pan (°) :");
|
||||||
|
ui.add(
|
||||||
|
egui::Slider::new(&mut self.cfg.max_pan_deg, 15.0..=180.0)
|
||||||
|
.suffix("°"),
|
||||||
|
);
|
||||||
|
ui.end_row();
|
||||||
|
|
||||||
|
ui.label("Course Max Tilt (°) :");
|
||||||
|
ui.add(
|
||||||
|
egui::Slider::new(&mut self.cfg.max_tilt_deg, 15.0..=120.0)
|
||||||
|
.suffix("°"),
|
||||||
|
);
|
||||||
|
ui.end_row();
|
||||||
|
|
||||||
|
ui.label("Course Max Roll (°) :");
|
||||||
|
ui.add(
|
||||||
|
egui::Slider::new(&mut self.cfg.max_roll_deg, 15.0..=90.0)
|
||||||
|
.suffix("°"),
|
||||||
|
);
|
||||||
|
ui.end_row();
|
||||||
|
});
|
||||||
|
|
||||||
|
ui.add_space(4.0);
|
||||||
|
if ui.button("📡 Envoyer un paquet de test au Nomad").clicked() {
|
||||||
|
self.test_nomad_udp_packet();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
ui.add_space(8.0);
|
||||||
|
|
||||||
|
// --- Section 3 : Télémétrie (Optionnelle ON/OFF) & Projection VR ---
|
||||||
|
egui::CollapsingHeader::new(
|
||||||
|
RichText::new("🥽 3. Projection VR 140° & Télémétrie (Optionnelle)")
|
||||||
|
.strong(),
|
||||||
|
)
|
||||||
|
.default_open(true)
|
||||||
|
.show(ui, |ui| {
|
||||||
|
ui.horizontal(|ui| {
|
||||||
|
ui.label(RichText::new("Télémétrie & OSD :").strong());
|
||||||
|
let btn_text = if self.cfg.telemetry_enabled {
|
||||||
|
RichText::new("🟢 ON (Activée)")
|
||||||
|
.color(Color32::from_rgb(80, 240, 120))
|
||||||
|
.strong()
|
||||||
|
} else {
|
||||||
|
RichText::new("⚪ OFF (Désactivée)")
|
||||||
|
.color(Color32::from_rgb(170, 170, 180))
|
||||||
|
};
|
||||||
|
if ui.button(btn_text).clicked() {
|
||||||
|
self.cfg.telemetry_enabled = !self.cfg.telemetry_enabled;
|
||||||
|
self.engine.set_telemetry_enabled(self.cfg.telemetry_enabled);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if self.cfg.telemetry_enabled {
|
||||||
|
ui.horizontal(|ui| {
|
||||||
|
ui.label("Port UDP Télémétrie :");
|
||||||
|
ui.add(
|
||||||
|
egui::DragValue::new(&mut self.cfg.telemetry_udp_port)
|
||||||
|
.range(1024..=65535),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
ui.separator();
|
||||||
|
|
||||||
|
egui::Grid::new("vr_cfg_grid")
|
||||||
|
.num_columns(2)
|
||||||
|
.spacing([8.0, 6.0])
|
||||||
|
.show(ui, |ui| {
|
||||||
|
ui.label("Mode Projection :");
|
||||||
|
egui::ComboBox::from_id_salt("proj_combo")
|
||||||
|
.selected_text(&self.cfg.projection_mode)
|
||||||
|
.show_ui(ui, |ui| {
|
||||||
|
ui.selectable_value(
|
||||||
|
&mut self.cfg.projection_mode,
|
||||||
|
"dome".to_string(),
|
||||||
|
"Dôme Sphérique 140° (Equirect2)",
|
||||||
|
);
|
||||||
|
ui.selectable_value(
|
||||||
|
&mut self.cfg.projection_mode,
|
||||||
|
"cylinder".to_string(),
|
||||||
|
"Cylindre Incurvé 140°",
|
||||||
|
);
|
||||||
|
ui.selectable_value(
|
||||||
|
&mut self.cfg.projection_mode,
|
||||||
|
"flat".to_string(),
|
||||||
|
"Écran Plat (Quad)",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
ui.end_row();
|
||||||
|
|
||||||
|
ui.label("FOV Caméra (°) :");
|
||||||
|
ui.add(
|
||||||
|
egui::Slider::new(&mut self.cfg.camera_fov_deg, 70.0..=180.0)
|
||||||
|
.suffix("°"),
|
||||||
|
);
|
||||||
|
ui.end_row();
|
||||||
|
|
||||||
|
ui.label("Correction Lentille k1 :");
|
||||||
|
ui.add(egui::Slider::new(&mut self.cfg.lens_k1, -0.50..=0.50));
|
||||||
|
ui.end_row();
|
||||||
|
|
||||||
|
ui.label("Correction Lentille k2 :");
|
||||||
|
ui.add(egui::Slider::new(&mut self.cfg.lens_k2, -0.25..=0.25));
|
||||||
|
ui.end_row();
|
||||||
|
|
||||||
|
ui.label("Rayon / Distance (m) :");
|
||||||
|
ui.add(
|
||||||
|
egui::Slider::new(&mut self.cfg.screen_distance_m, 0.8..=4.0)
|
||||||
|
.suffix(" m"),
|
||||||
|
);
|
||||||
|
ui.end_row();
|
||||||
|
});
|
||||||
|
|
||||||
|
ui.add_space(6.0);
|
||||||
|
if ui
|
||||||
|
.button(RichText::new("✔ Appliquer les changements").strong())
|
||||||
|
.clicked()
|
||||||
|
{
|
||||||
|
self.engine.start(self.cfg.clone());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// =========================================================================
|
||||||
|
// 4. PANNEAU CENTRAL : APERÇU VIDÉO TEMPS RÉEL + JAUGES HEAD-TRACKING & DRONE
|
||||||
|
// =========================================================================
|
||||||
|
egui::CentralPanel::default().show(ctx, |ui| {
|
||||||
|
egui::ScrollArea::vertical().show(ui, |ui| {
|
||||||
|
ui.columns(2, |cols| {
|
||||||
|
egui::Frame::group(cols[0].style()).show(&mut cols[0], |ui| {
|
||||||
|
ui.label(
|
||||||
|
RichText::new("🎯 Suivi de Tête -> RadioMaster Nomad (172..1811 CRSF)")
|
||||||
|
.strong(),
|
||||||
|
);
|
||||||
|
ui.add_space(4.0);
|
||||||
|
|
||||||
|
let pan_norm = (pose.pan_crsf as f32 - 172.0) / (1811.0 - 172.0);
|
||||||
|
ui.add(
|
||||||
|
egui::ProgressBar::new(pan_norm.clamp(0.0, 1.0)).text(format!(
|
||||||
|
"PAN (Lacet) : {:+5.1}° | CRSF = {}",
|
||||||
|
pose.pan_deg, pose.pan_crsf
|
||||||
|
)),
|
||||||
|
);
|
||||||
|
|
||||||
|
let tilt_norm = (pose.tilt_crsf as f32 - 172.0) / (1811.0 - 172.0);
|
||||||
|
ui.add(
|
||||||
|
egui::ProgressBar::new(tilt_norm.clamp(0.0, 1.0)).text(format!(
|
||||||
|
"TILT (Tangage) : {:+5.1}° | CRSF = {}",
|
||||||
|
pose.tilt_deg, pose.tilt_crsf
|
||||||
|
)),
|
||||||
|
);
|
||||||
|
|
||||||
|
let roll_norm = (pose.roll_crsf as f32 - 172.0) / (1811.0 - 172.0);
|
||||||
|
ui.add(
|
||||||
|
egui::ProgressBar::new(roll_norm.clamp(0.0, 1.0)).text(format!(
|
||||||
|
"ROLL (Roulis) : {:+5.1}° | CRSF = {}",
|
||||||
|
pose.roll_deg, pose.roll_crsf
|
||||||
|
)),
|
||||||
|
);
|
||||||
|
|
||||||
|
ui.add_space(4.0);
|
||||||
|
ui.label(format!(
|
||||||
|
"Paquets Wi-Fi UDP envoyés : {} | Erreurs d'envoi : {}",
|
||||||
|
pose.packets_sent, pose.send_errors
|
||||||
|
));
|
||||||
|
|
||||||
|
ui.collapsing("🕹 Simuler les mouvements de tête (Test Bureau)", |ui| {
|
||||||
|
let mut mon = self.engine.monitor.lock();
|
||||||
|
ui.add(
|
||||||
|
egui::Slider::new(
|
||||||
|
&mut mon.manual_pan_deg,
|
||||||
|
-self.cfg.max_pan_deg..=self.cfg.max_pan_deg,
|
||||||
|
)
|
||||||
|
.text("Simuler Pan (°)"),
|
||||||
|
);
|
||||||
|
ui.add(
|
||||||
|
egui::Slider::new(
|
||||||
|
&mut mon.manual_tilt_deg,
|
||||||
|
-self.cfg.max_tilt_deg..=self.cfg.max_tilt_deg,
|
||||||
|
)
|
||||||
|
.text("Simuler Tilt (°)"),
|
||||||
|
);
|
||||||
|
ui.add(
|
||||||
|
egui::Slider::new(
|
||||||
|
&mut mon.manual_roll_deg,
|
||||||
|
-self.cfg.max_roll_deg..=self.cfg.max_roll_deg,
|
||||||
|
)
|
||||||
|
.text("Simuler Roll (°)"),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
egui::Frame::group(cols[1].style()).show(&mut cols[1], |ui| {
|
||||||
|
ui.label(
|
||||||
|
RichText::new("📊 VRX Radxa Zero 3W (8812EU) & Télémétrie").strong(),
|
||||||
|
);
|
||||||
|
ui.add_space(4.0);
|
||||||
|
|
||||||
|
ui.label(format!(
|
||||||
|
"🎞 Vidéo USB ({}) : {:.1} FPS | Frames : {} | Canal 5.8GHz : {}",
|
||||||
|
self.cfg.vrx_video_profile,
|
||||||
|
fps,
|
||||||
|
total_frames,
|
||||||
|
self.cfg.wifi_channel
|
||||||
|
));
|
||||||
|
ui.separator();
|
||||||
|
|
||||||
|
if self.cfg.telemetry_enabled {
|
||||||
|
ui.horizontal(|ui| {
|
||||||
|
ui.label(format!(
|
||||||
|
"🔋 Batterie : {:.1} V ({:.1} A)",
|
||||||
|
telem.battery_voltage_v, telem.battery_current_a
|
||||||
|
));
|
||||||
|
ui.separator();
|
||||||
|
ui.label(format!(
|
||||||
|
"📶 Lien : LQ {}% | RSSI {} dBm",
|
||||||
|
telem.link_quality_pct, telem.rssi_dbm
|
||||||
|
));
|
||||||
|
});
|
||||||
|
|
||||||
|
ui.horizontal(|ui| {
|
||||||
|
ui.label(format!("🧭 Altitude : {:.1} m", telem.altitude_m));
|
||||||
|
ui.separator();
|
||||||
|
ui.label(format!(
|
||||||
|
"🚀 Vitesse : {:.1} km/h (Gaz {}%)",
|
||||||
|
telem.groundspeed_ms * 3.6,
|
||||||
|
telem.throttle_pct
|
||||||
|
));
|
||||||
|
});
|
||||||
|
|
||||||
|
ui.label(format!(
|
||||||
|
"📐 Attitude Drone : Roll {:+.1}° | Pitch {:+.1}° | Cap {:.0}° ({} trames)",
|
||||||
|
telem.drone_roll_rad.to_degrees(),
|
||||||
|
telem.drone_pitch_rad.to_degrees(),
|
||||||
|
telem.drone_heading_deg,
|
||||||
|
telem.packets_received
|
||||||
|
));
|
||||||
|
} else {
|
||||||
|
ui.colored_label(
|
||||||
|
Color32::GRAY,
|
||||||
|
"Télémétrie & OSD désactivés (OFF). Cliquez sur « 📶 Télémétrie & OSD : OFF » pour l'activer.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
ui.add_space(8.0);
|
||||||
|
|
||||||
|
ui.label(
|
||||||
|
RichText::new("🖥 Retour Vidéo Temps Réel (Dôme 140°)").strong(),
|
||||||
|
);
|
||||||
|
if let Some(ref tex) = self.video_texture {
|
||||||
|
let avail = ui.available_size();
|
||||||
|
let aspect = 16.0 / 9.0;
|
||||||
|
let w = avail.x.min(820.0);
|
||||||
|
let h = w / aspect;
|
||||||
|
ui.image((tex.id(), egui::vec2(w, h)));
|
||||||
|
} else {
|
||||||
|
ui.label("Initialisation de l'aperçu vidéo...");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
+101
@@ -0,0 +1,101 @@
|
|||||||
|
use chrono::Local;
|
||||||
|
use log::{Level, LevelFilter, Log, Metadata, Record};
|
||||||
|
use parking_lot::Mutex;
|
||||||
|
use std::collections::VecDeque;
|
||||||
|
use std::fs::OpenOptions;
|
||||||
|
use std::io::Write;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
const MAX_LOG_ENTRIES: usize = 1000;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct LogEntry {
|
||||||
|
pub timestamp: String,
|
||||||
|
pub level: Level,
|
||||||
|
pub target: String,
|
||||||
|
pub message: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
pub struct LogBuffer {
|
||||||
|
pub entries: VecDeque<LogEntry>,
|
||||||
|
pub error_count: usize,
|
||||||
|
pub warn_count: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Logger centralisé capturant tous les événements et erreurs pour l'interface graphique
|
||||||
|
/// et les enregistrant simultanément dans `steamframe_fpv.log`.
|
||||||
|
pub struct GuiLogger {
|
||||||
|
buffer: Arc<Mutex<LogBuffer>>,
|
||||||
|
log_file_path: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GuiLogger {
|
||||||
|
pub fn init(log_file_path: &str) -> Arc<Mutex<LogBuffer>> {
|
||||||
|
let buffer = Arc::new(Mutex::new(LogBuffer::default()));
|
||||||
|
let logger = Box::new(Self {
|
||||||
|
buffer: Arc::clone(&buffer),
|
||||||
|
log_file_path: log_file_path.to_string(),
|
||||||
|
});
|
||||||
|
|
||||||
|
if log::set_boxed_logger(logger).is_ok() {
|
||||||
|
log::set_max_level(LevelFilter::Info);
|
||||||
|
}
|
||||||
|
|
||||||
|
buffer
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Log for GuiLogger {
|
||||||
|
fn enabled(&self, metadata: &Metadata) -> bool {
|
||||||
|
metadata.level() <= Level::Info
|
||||||
|
}
|
||||||
|
|
||||||
|
fn log(&self, record: &Record) {
|
||||||
|
if !self.enabled(record.metadata()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let now = Local::now().format("%H:%M:%S%.3f").to_string();
|
||||||
|
let entry = LogEntry {
|
||||||
|
timestamp: now.clone(),
|
||||||
|
level: record.level(),
|
||||||
|
target: record.target().to_string(),
|
||||||
|
message: format!("{}", record.args()),
|
||||||
|
};
|
||||||
|
|
||||||
|
// Affichage console standard
|
||||||
|
eprintln!(
|
||||||
|
"[{}] [{:<5}] ({}) {}",
|
||||||
|
entry.timestamp, entry.level, entry.target, entry.message
|
||||||
|
);
|
||||||
|
|
||||||
|
// Écriture persistante sur disque pour diagnostic après crash éventuel
|
||||||
|
if let Ok(mut file) = OpenOptions::new()
|
||||||
|
.create(true)
|
||||||
|
.append(true)
|
||||||
|
.open(&self.log_file_path)
|
||||||
|
{
|
||||||
|
let _ = writeln!(
|
||||||
|
file,
|
||||||
|
"[{}] [{:<5}] ({}) {}",
|
||||||
|
entry.timestamp, entry.level, entry.target, entry.message
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ajout dans le tampon de l'interface graphique
|
||||||
|
let mut lock = self.buffer.lock();
|
||||||
|
if record.level() == Level::Error {
|
||||||
|
lock.error_count += 1;
|
||||||
|
} else if record.level() == Level::Warn {
|
||||||
|
lock.warn_count += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if lock.entries.len() >= MAX_LOG_ENTRIES {
|
||||||
|
lock.entries.pop_front();
|
||||||
|
}
|
||||||
|
lock.entries.push_back(entry);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn flush(&self) {}
|
||||||
|
}
|
||||||
+58
@@ -0,0 +1,58 @@
|
|||||||
|
mod config;
|
||||||
|
mod dome_projection;
|
||||||
|
mod engine;
|
||||||
|
mod gui;
|
||||||
|
mod logger;
|
||||||
|
mod nomad_elrs;
|
||||||
|
mod telemetry_osd;
|
||||||
|
mod video_usb;
|
||||||
|
mod vulkan_xr;
|
||||||
|
|
||||||
|
use anyhow::Result;
|
||||||
|
use clap::Parser;
|
||||||
|
use config::AppConfig;
|
||||||
|
use engine::FpvEngineController;
|
||||||
|
use gui::SteamFrameGuiApp;
|
||||||
|
use logger::GuiLogger;
|
||||||
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
fn main() -> Result<()> {
|
||||||
|
let cfg = AppConfig::parse();
|
||||||
|
let log_buffer = GuiLogger::init(&cfg.log_file);
|
||||||
|
|
||||||
|
log::info!(
|
||||||
|
"=== Démarrage de SteamFrame FPV v0.2 (Fichier journal : {}) ===",
|
||||||
|
cfg.log_file
|
||||||
|
);
|
||||||
|
|
||||||
|
if cfg.no_gui {
|
||||||
|
log::info!("Mode ligne de commande (--no-gui) activé.");
|
||||||
|
let mut engine = FpvEngineController::new(cfg.telemetry_enabled);
|
||||||
|
engine.start(cfg);
|
||||||
|
|
||||||
|
let running = Arc::new(AtomicBool::new(true));
|
||||||
|
while running.load(Ordering::Relaxed) && engine.is_running() {
|
||||||
|
std::thread::sleep(Duration::from_millis(200));
|
||||||
|
}
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
let native_options = eframe::NativeOptions {
|
||||||
|
viewport: eframe::egui::ViewportBuilder::default()
|
||||||
|
.with_title("SteamFrame FPV - Eachine Sphere Link & RadioMaster Nomad")
|
||||||
|
.with_inner_size([1220.0, 820.0])
|
||||||
|
.with_min_inner_size([920.0, 620.0]),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
eframe::run_native(
|
||||||
|
"SteamFrame FPV",
|
||||||
|
native_options,
|
||||||
|
Box::new(move |cc| Ok(Box::new(SteamFrameGuiApp::new(cc, cfg, log_buffer)))),
|
||||||
|
)
|
||||||
|
.map_err(|e| anyhow::anyhow!("Erreur interface graphique eframe : {}", e))?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,253 @@
|
|||||||
|
use anyhow::Result;
|
||||||
|
use glam::{EulerRot, Quat};
|
||||||
|
use std::net::{SocketAddr, UdpSocket};
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
/// Opcode MSPv2 officiel ExpressLRS Backpack pour le Head Tracking (Pan, Tilt, Roll)
|
||||||
|
pub const MSP_ELRS_BACKPACK_SET_PTR: u16 = 0x0383;
|
||||||
|
|
||||||
|
/// Bornes CRSF standard (11 bits : 172 = 988µs, 992 = 1500µs, 1811 = 2012µs)
|
||||||
|
pub const CRSF_CHANNEL_MIN: u16 = 172;
|
||||||
|
pub const CRSF_CHANNEL_MID: u16 = 992;
|
||||||
|
pub const CRSF_CHANNEL_MAX: u16 = 1811;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy)]
|
||||||
|
pub struct HeadPoseSample {
|
||||||
|
pub pan_deg: f32,
|
||||||
|
pub tilt_deg: f32,
|
||||||
|
pub roll_deg: f32,
|
||||||
|
pub pan_crsf: u16,
|
||||||
|
pub tilt_crsf: u16,
|
||||||
|
pub roll_crsf: u16,
|
||||||
|
pub packets_sent: u64,
|
||||||
|
pub send_errors: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for HeadPoseSample {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
pan_deg: 0.0,
|
||||||
|
tilt_deg: 0.0,
|
||||||
|
roll_deg: 0.0,
|
||||||
|
pan_crsf: CRSF_CHANNEL_MID,
|
||||||
|
tilt_crsf: CRSF_CHANNEL_MID,
|
||||||
|
roll_crsf: CRSF_CHANNEL_MID,
|
||||||
|
packets_sent: 0,
|
||||||
|
send_errors: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct NomadHeadTracker {
|
||||||
|
socket: UdpSocket,
|
||||||
|
target: SocketAddr,
|
||||||
|
zero_quat_inv: Quat,
|
||||||
|
max_pan_deg: f32,
|
||||||
|
max_tilt_deg: f32,
|
||||||
|
max_roll_deg: f32,
|
||||||
|
use_crsf: bool,
|
||||||
|
packets_sent: u64,
|
||||||
|
send_errors: u64,
|
||||||
|
last_error_log: Option<Instant>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl NomadHeadTracker {
|
||||||
|
pub fn new(
|
||||||
|
nomad_ip: &str,
|
||||||
|
nomad_port: u16,
|
||||||
|
max_pan_deg: f32,
|
||||||
|
max_tilt_deg: f32,
|
||||||
|
max_roll_deg: f32,
|
||||||
|
use_crsf: bool,
|
||||||
|
) -> 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 target: SocketAddr = format!("{}:{}", nomad_ip, nomad_port).parse().map_err(|e| {
|
||||||
|
log::error!(
|
||||||
|
"[Wi-Fi Nomad] Adresse IP ou port invalide ({}:{}) : {}",
|
||||||
|
nomad_ip,
|
||||||
|
nomad_port,
|
||||||
|
e
|
||||||
|
);
|
||||||
|
e
|
||||||
|
})?;
|
||||||
|
|
||||||
|
log::info!(
|
||||||
|
"[Wi-Fi Nomad] Émetteur Head-Tracking prêt vers {} (Protocole: {})",
|
||||||
|
target,
|
||||||
|
if use_crsf {
|
||||||
|
"CRSF RC_CHANNELS_PACKED (0x16)"
|
||||||
|
} else {
|
||||||
|
"MSPv2 ELRS_BACKPACK_SET_PTR (0x0383)"
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
Ok(Self {
|
||||||
|
socket,
|
||||||
|
target,
|
||||||
|
zero_quat_inv: Quat::IDENTITY,
|
||||||
|
max_pan_deg,
|
||||||
|
max_tilt_deg,
|
||||||
|
max_roll_deg,
|
||||||
|
use_crsf,
|
||||||
|
packets_sent: 0,
|
||||||
|
send_errors: 0,
|
||||||
|
last_error_log: None,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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();
|
||||||
|
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 (yaw_rad, pitch_rad, roll_rad) = relative.to_euler(EulerRot::YXZ);
|
||||||
|
|
||||||
|
let pan_deg = -yaw_rad.to_degrees();
|
||||||
|
let tilt_deg = pitch_rad.to_degrees();
|
||||||
|
let roll_deg = -roll_rad.to_degrees();
|
||||||
|
|
||||||
|
let pan_crsf = Self::deg_to_crsf(pan_deg, self.max_pan_deg);
|
||||||
|
let tilt_crsf = Self::deg_to_crsf(tilt_deg, self.max_tilt_deg);
|
||||||
|
let roll_crsf = Self::deg_to_crsf(roll_deg, self.max_roll_deg);
|
||||||
|
|
||||||
|
let send_res = if self.use_crsf {
|
||||||
|
let packet = Self::encode_crsf_rc_channels(pan_crsf, tilt_crsf, roll_crsf);
|
||||||
|
self.socket.send_to(&packet, self.target)
|
||||||
|
} else {
|
||||||
|
let packet = Self::encode_mspv2_ptr(pan_crsf, tilt_crsf, roll_crsf);
|
||||||
|
self.socket.send_to(&packet, self.target)
|
||||||
|
};
|
||||||
|
|
||||||
|
match send_res {
|
||||||
|
Ok(_) => {
|
||||||
|
self.packets_sent = self.packets_sent.wrapping_add(1);
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
self.send_errors = self.send_errors.wrapping_add(1);
|
||||||
|
let should_log = self
|
||||||
|
.last_error_log
|
||||||
|
.map(|t| t.elapsed() >= Duration::from_secs(3))
|
||||||
|
.unwrap_or(true);
|
||||||
|
if should_log {
|
||||||
|
log::error!(
|
||||||
|
"[Wi-Fi Nomad] Échec d'envoi UDP vers {} : {} (Vérifiez la connexion Wi-Fi au Backpack du RadioMaster Nomad)",
|
||||||
|
self.target,
|
||||||
|
e
|
||||||
|
);
|
||||||
|
self.last_error_log = Some(Instant::now());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(HeadPoseSample {
|
||||||
|
pan_deg,
|
||||||
|
tilt_deg,
|
||||||
|
roll_deg,
|
||||||
|
pan_crsf,
|
||||||
|
tilt_crsf,
|
||||||
|
roll_crsf,
|
||||||
|
packets_sent: self.packets_sent,
|
||||||
|
send_errors: self.send_errors,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn deg_to_crsf(angle_deg: f32, max_deg: f32) -> u16 {
|
||||||
|
let norm = (angle_deg / max_deg).clamp(-1.0, 1.0);
|
||||||
|
let span = (CRSF_CHANNEL_MAX - CRSF_CHANNEL_MIN) as f32 / 2.0;
|
||||||
|
(CRSF_CHANNEL_MID as f32 + norm * span).round() as u16
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn encode_mspv2_ptr(pan: u16, tilt: u16, roll: u16) -> [u8; 15] {
|
||||||
|
let mut buf = [0u8; 15];
|
||||||
|
buf[0] = b'$';
|
||||||
|
buf[1] = b'X';
|
||||||
|
buf[2] = b'<';
|
||||||
|
buf[3] = 0x00;
|
||||||
|
buf[4..6].copy_from_slice(&MSP_ELRS_BACKPACK_SET_PTR.to_le_bytes());
|
||||||
|
buf[6..8].copy_from_slice(&6u16.to_le_bytes());
|
||||||
|
buf[8..10].copy_from_slice(&pan.to_le_bytes());
|
||||||
|
buf[10..12].copy_from_slice(&tilt.to_le_bytes());
|
||||||
|
buf[12..14].copy_from_slice(&roll.to_le_bytes());
|
||||||
|
buf[14] = Self::crc8_dvb_s2(&buf[3..14]);
|
||||||
|
buf
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
|
||||||
|
let mut frame = [0u8; 26];
|
||||||
|
frame[0] = 0xEE;
|
||||||
|
frame[1] = 24;
|
||||||
|
frame[2] = 0x16;
|
||||||
|
|
||||||
|
let mut bit_buf: u32 = 0;
|
||||||
|
let mut bits_in_buf: u8 = 0;
|
||||||
|
let mut byte_idx = 3;
|
||||||
|
|
||||||
|
for &val in &ch {
|
||||||
|
bit_buf |= ((val & 0x07FF) as u32) << bits_in_buf;
|
||||||
|
bits_in_buf += 11;
|
||||||
|
while bits_in_buf >= 8 {
|
||||||
|
frame[byte_idx] = (bit_buf & 0xFF) as u8;
|
||||||
|
byte_idx += 1;
|
||||||
|
bit_buf >>= 8;
|
||||||
|
bits_in_buf -= 8;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
frame[25] = Self::crc8_dvb_s2(&frame[2..25]);
|
||||||
|
frame
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn crc8_dvb_s2(data: &[u8]) -> u8 {
|
||||||
|
let mut crc: u8 = 0;
|
||||||
|
for &byte in data {
|
||||||
|
crc ^= byte;
|
||||||
|
for _ in 0..8 {
|
||||||
|
if (crc & 0x80) != 0 {
|
||||||
|
crc = (crc << 1) ^ 0xD5;
|
||||||
|
} else {
|
||||||
|
crc <<= 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
crc
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_deg_to_crsf_bounds() {
|
||||||
|
assert_eq!(NomadHeadTracker::deg_to_crsf(0.0, 90.0), CRSF_CHANNEL_MID);
|
||||||
|
assert_eq!(NomadHeadTracker::deg_to_crsf(90.0, 90.0), CRSF_CHANNEL_MAX);
|
||||||
|
assert_eq!(NomadHeadTracker::deg_to_crsf(-90.0, 90.0), CRSF_CHANNEL_MIN);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_mspv2_ptr_packet_header() {
|
||||||
|
let pkt = NomadHeadTracker::encode_mspv2_ptr(992, 992, 992);
|
||||||
|
assert_eq!(&pkt[0..3], b"$X<");
|
||||||
|
assert_eq!(u16::from_le_bytes([pkt[4], pkt[5]]), MSP_ELRS_BACKPACK_SET_PTR);
|
||||||
|
assert_eq!(u16::from_le_bytes([pkt[6], pkt[7]]), 6);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,571 @@
|
|||||||
|
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};
|
||||||
|
|
||||||
|
/// É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>,
|
||||||
|
}
|
||||||
|
|
||||||
|
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,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TelemetryReceiver {
|
||||||
|
pub fn start(bind_ip: &str, port: u16) -> 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 {}",
|
||||||
|
addr
|
||||||
|
);
|
||||||
|
|
||||||
|
let state = Arc::new(Mutex::new(TelemetryState::default()));
|
||||||
|
let state_clone = Arc::clone(&state);
|
||||||
|
let stop_flag = Arc::new(AtomicBool::new(false));
|
||||||
|
let stop_clone = Arc::clone(&stop_flag);
|
||||||
|
|
||||||
|
thread::Builder::new()
|
||||||
|
.name("telemetry-udp-rx".into())
|
||||||
|
.spawn(move || {
|
||||||
|
let mut buf = [0u8; 1024];
|
||||||
|
while !stop_clone.load(Ordering::Relaxed) {
|
||||||
|
if let Ok((len, _src)) = socket.recv_from(&mut buf) {
|
||||||
|
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 })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn state(&self) -> Arc<Mutex<TelemetryState>> {
|
||||||
|
Arc::clone(&self.state)
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
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);
|
||||||
|
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 frame_type = data[i + 2];
|
||||||
|
let payload = &data[i + 3..i + 2 + frame_len - 1];
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for TelemetryReceiver {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.stop_flag.store(true, Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Moteur d'incrustation graphique OSD (HUD vectoriel + police bitmap 5x7 avec contour)
|
||||||
|
pub struct OsdOverlay;
|
||||||
|
|
||||||
|
impl OsdOverlay {
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
pub fn render(
|
||||||
|
rgba: &mut [u8],
|
||||||
|
width: u32,
|
||||||
|
height: u32,
|
||||||
|
telem: &TelemetryState,
|
||||||
|
head_pan_deg: f32,
|
||||||
|
head_tilt_deg: f32,
|
||||||
|
head_roll_deg: f32,
|
||||||
|
max_pan_deg: f32,
|
||||||
|
max_tilt_deg: f32,
|
||||||
|
projection_label: &str,
|
||||||
|
) {
|
||||||
|
let scale = (height / 360).max(2);
|
||||||
|
|
||||||
|
let bat_color = if telem.battery_voltage_v > 0.1 && telem.battery_voltage_v < 14.0 {
|
||||||
|
[255, 65, 65, 255]
|
||||||
|
} else {
|
||||||
|
[90, 255, 130, 255]
|
||||||
|
};
|
||||||
|
|
||||||
|
let bat_text = if telem.battery_remaining_pct >= 0 {
|
||||||
|
format!(
|
||||||
|
"BAT {:4.1}V {:4.1}A {:3}%",
|
||||||
|
telem.battery_voltage_v, telem.battery_current_a, telem.battery_remaining_pct
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
format!(
|
||||||
|
"BAT {:4.1}V {:4.1}A",
|
||||||
|
telem.battery_voltage_v, telem.battery_current_a
|
||||||
|
)
|
||||||
|
};
|
||||||
|
Self::draw_text(rgba, width, height, 32, 28, &bat_text, scale, bat_color);
|
||||||
|
|
||||||
|
let lq_color = if telem.link_quality_pct < 70 {
|
||||||
|
[255, 180, 40, 255]
|
||||||
|
} else {
|
||||||
|
[100, 225, 255, 255]
|
||||||
|
};
|
||||||
|
let link_text = format!("LQ {:3}% RSSI {:3}DBM", telem.link_quality_pct, telem.rssi_dbm);
|
||||||
|
let right_x = width.saturating_sub((link_text.len() as u32) * 6 * scale + 32) as i32;
|
||||||
|
Self::draw_text(rgba, width, height, right_x, 28, &link_text, scale, lq_color);
|
||||||
|
|
||||||
|
Self::draw_gimbal_radar(
|
||||||
|
rgba,
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
head_pan_deg,
|
||||||
|
head_tilt_deg,
|
||||||
|
max_pan_deg,
|
||||||
|
max_tilt_deg,
|
||||||
|
scale,
|
||||||
|
);
|
||||||
|
let ht_text = format!(
|
||||||
|
"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_text.len() as i32 * 6 * scale as i32) / 2);
|
||||||
|
Self::draw_text(
|
||||||
|
rgba,
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
ht_x,
|
||||||
|
28 + 46 * scale as i32 / 2,
|
||||||
|
&ht_text,
|
||||||
|
scale,
|
||||||
|
[230, 240, 255, 255],
|
||||||
|
);
|
||||||
|
|
||||||
|
Self::draw_artificial_horizon(
|
||||||
|
rgba,
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
telem.drone_roll_rad,
|
||||||
|
telem.drone_pitch_rad,
|
||||||
|
);
|
||||||
|
|
||||||
|
let bottom_y = height.saturating_sub(28 + 8 * scale) as i32;
|
||||||
|
let spd_kmh = telem.groundspeed_ms * 3.6;
|
||||||
|
let left_bottom_text = format!("SPD {:4.1}KM/H THR {:3}%", spd_kmh, telem.throttle_pct);
|
||||||
|
Self::draw_text(
|
||||||
|
rgba,
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
32,
|
||||||
|
bottom_y,
|
||||||
|
&left_bottom_text,
|
||||||
|
scale,
|
||||||
|
[240, 240, 240, 255],
|
||||||
|
);
|
||||||
|
|
||||||
|
let right_bottom_text = format!(
|
||||||
|
"ALT {:5.1}M VSI {:+4.1}M/S [{}]",
|
||||||
|
telem.altitude_m, telem.climb_ms, projection_label
|
||||||
|
);
|
||||||
|
let rb_x = width.saturating_sub((right_bottom_text.len() as u32) * 6 * scale + 32) as i32;
|
||||||
|
Self::draw_text(
|
||||||
|
rgba,
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
rb_x,
|
||||||
|
bottom_y,
|
||||||
|
&right_bottom_text,
|
||||||
|
scale,
|
||||||
|
[240, 240, 240, 255],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
fn draw_gimbal_radar(
|
||||||
|
rgba: &mut [u8],
|
||||||
|
width: u32,
|
||||||
|
height: u32,
|
||||||
|
pan_deg: f32,
|
||||||
|
tilt_deg: f32,
|
||||||
|
max_pan: f32,
|
||||||
|
max_tilt: f32,
|
||||||
|
scale: u32,
|
||||||
|
) {
|
||||||
|
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;
|
||||||
|
|
||||||
|
Self::draw_rect_outline(
|
||||||
|
rgba,
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
cx - box_w / 2,
|
||||||
|
cy - box_h / 2,
|
||||||
|
box_w,
|
||||||
|
box_h,
|
||||||
|
[160, 190, 220, 220],
|
||||||
|
);
|
||||||
|
|
||||||
|
Self::draw_line(
|
||||||
|
rgba,
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
cx - 4,
|
||||||
|
cy,
|
||||||
|
cx + 4,
|
||||||
|
cy,
|
||||||
|
[100, 120, 140, 200],
|
||||||
|
);
|
||||||
|
Self::draw_line(
|
||||||
|
rgba,
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
cx,
|
||||||
|
cy - 4,
|
||||||
|
cx,
|
||||||
|
cy + 4,
|
||||||
|
[100, 120, 140, 200],
|
||||||
|
);
|
||||||
|
|
||||||
|
let norm_x = (pan_deg / max_pan.max(1.0)).clamp(-1.0, 1.0);
|
||||||
|
let norm_y = (-tilt_deg / max_tilt.max(1.0)).clamp(-1.0, 1.0);
|
||||||
|
let dot_x = cx + (norm_x * (box_w as f32 * 0.44)) as i32;
|
||||||
|
let dot_y = cy + (norm_y * (box_h as f32 * 0.42)) as i32;
|
||||||
|
|
||||||
|
let r = (2 * scale as i32).max(3);
|
||||||
|
for dy in -r..=r {
|
||||||
|
for dx in -r..=r {
|
||||||
|
if dx * dx + dy * dy <= r * r {
|
||||||
|
Self::put_pixel(rgba, width, height, dot_x + dx, dot_y + dy, [0, 255, 180, 255]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw_artificial_horizon(
|
||||||
|
rgba: &mut [u8],
|
||||||
|
width: u32,
|
||||||
|
height: u32,
|
||||||
|
roll_rad: f32,
|
||||||
|
pitch_rad: f32,
|
||||||
|
) {
|
||||||
|
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 cos_r = (-roll_rad).cos();
|
||||||
|
let sin_r = (-roll_rad).sin();
|
||||||
|
let half_span = (width as f32 * 0.14) as i32;
|
||||||
|
let gap = (width as f32 * 0.03) as i32;
|
||||||
|
|
||||||
|
for &(r0, r1) in &[(-half_span, -gap), (gap, half_span)] {
|
||||||
|
let x0 = cx + (r0 as f32 * cos_r) as i32;
|
||||||
|
let y0 = cy + pitch_offset + (r0 as f32 * sin_r) as i32;
|
||||||
|
let x1 = cx + (r1 as f32 * cos_r) as i32;
|
||||||
|
let y1 = cy + pitch_offset + (r1 as f32 * sin_r) as i32;
|
||||||
|
Self::draw_line(rgba, width, height, x0, y0, x1, y1, [0, 255, 160, 220]);
|
||||||
|
Self::draw_line(rgba, width, height, x0, y0 + 1, x1, y1 + 1, [0, 80, 50, 200]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw_rect_outline(
|
||||||
|
rgba: &mut [u8],
|
||||||
|
width: u32,
|
||||||
|
height: u32,
|
||||||
|
x: i32,
|
||||||
|
y: i32,
|
||||||
|
w: i32,
|
||||||
|
h: i32,
|
||||||
|
color: [u8; 4],
|
||||||
|
) {
|
||||||
|
Self::draw_line(rgba, width, height, x, y, x + w, y, color);
|
||||||
|
Self::draw_line(rgba, width, height, x, y + h, x + w, y + h, color);
|
||||||
|
Self::draw_line(rgba, width, height, x, y, x, y + h, color);
|
||||||
|
Self::draw_line(rgba, width, height, x + w, y, x + w, y + h, color);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw_line(
|
||||||
|
rgba: &mut [u8],
|
||||||
|
width: u32,
|
||||||
|
height: u32,
|
||||||
|
mut x0: i32,
|
||||||
|
mut y0: i32,
|
||||||
|
x1: i32,
|
||||||
|
y1: i32,
|
||||||
|
color: [u8; 4],
|
||||||
|
) {
|
||||||
|
let dx = (x1 - x0).abs();
|
||||||
|
let sx = if x0 < x1 { 1 } else { -1 };
|
||||||
|
let dy = -(y1 - y0).abs();
|
||||||
|
let sy = if y0 < y1 { 1 } else { -1 };
|
||||||
|
let mut err = dx + dy;
|
||||||
|
|
||||||
|
loop {
|
||||||
|
Self::put_pixel(rgba, width, height, x0, y0, color);
|
||||||
|
if x0 == x1 && y0 == y1 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
let e2 = 2 * err;
|
||||||
|
if e2 >= dy {
|
||||||
|
err += dy;
|
||||||
|
x0 += sx;
|
||||||
|
}
|
||||||
|
if e2 <= dx {
|
||||||
|
err += dx;
|
||||||
|
y0 += sy;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn put_pixel(rgba: &mut [u8], width: u32, height: u32, x: i32, y: i32, color: [u8; 4]) {
|
||||||
|
if x >= 0 && y >= 0 && (x as u32) < width && (y as u32) < height {
|
||||||
|
let idx = ((y as u32 * width + x as u32) * 4) as usize;
|
||||||
|
if idx + 3 < rgba.len() {
|
||||||
|
rgba[idx] = color[0];
|
||||||
|
rgba[idx + 1] = color[1];
|
||||||
|
rgba[idx + 2] = color[2];
|
||||||
|
rgba[idx + 3] = color[3];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
pub fn draw_text(
|
||||||
|
rgba: &mut [u8],
|
||||||
|
width: u32,
|
||||||
|
height: u32,
|
||||||
|
x: i32,
|
||||||
|
y: i32,
|
||||||
|
text: &str,
|
||||||
|
scale: u32,
|
||||||
|
color: [u8; 4],
|
||||||
|
) {
|
||||||
|
let s = scale.max(1) as i32;
|
||||||
|
for (i, ch) in text.chars().enumerate() {
|
||||||
|
let glyph = Self::glyph_5x7(ch);
|
||||||
|
let gx = x + (i as i32) * 6 * s;
|
||||||
|
for (row_idx, &row_bits) in glyph.iter().enumerate() {
|
||||||
|
for col_idx in 0..5 {
|
||||||
|
if (row_bits & (1 << (4 - col_idx))) != 0 {
|
||||||
|
let px = gx + col_idx * s;
|
||||||
|
let py = y + (row_idx as i32) * s;
|
||||||
|
for sy in 0..s {
|
||||||
|
for sx in 0..s {
|
||||||
|
Self::put_pixel(
|
||||||
|
rgba,
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
px + sx + 2,
|
||||||
|
py + sy + 2,
|
||||||
|
[0, 0, 0, 220],
|
||||||
|
);
|
||||||
|
Self::put_pixel(rgba, width, height, px + sx, py + sy, color);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn glyph_5x7(c: char) -> [u8; 7] {
|
||||||
|
match c.to_ascii_uppercase() {
|
||||||
|
'0' => [0b01110, 0b10001, 0b10011, 0b10101, 0b11001, 0b10001, 0b01110],
|
||||||
|
'1' => [0b00100, 0b01100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110],
|
||||||
|
'2' => [0b01110, 0b10001, 0b00001, 0b00110, 0b01000, 0b10000, 0b11111],
|
||||||
|
'3' => [0b11110, 0b00001, 0b00001, 0b01110, 0b00001, 0b00001, 0b11110],
|
||||||
|
'4' => [0b00010, 0b00110, 0b01010, 0b10010, 0b11111, 0b00010, 0b00010],
|
||||||
|
'5' => [0b11111, 0b10000, 0b11110, 0b00001, 0b00001, 0b10001, 0b01110],
|
||||||
|
'6' => [0b00110, 0b01000, 0b10000, 0b11110, 0b10001, 0b10001, 0b01110],
|
||||||
|
'7' => [0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b01000, 0b01000],
|
||||||
|
'8' => [0b01110, 0b10001, 0b10001, 0b01110, 0b10001, 0b10001, 0b01110],
|
||||||
|
'9' => [0b01110, 0b10001, 0b10001, 0b01111, 0b00001, 0b00010, 0b01100],
|
||||||
|
'A' => [0b01110, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001],
|
||||||
|
'B' => [0b11110, 0b10001, 0b10001, 0b11110, 0b10001, 0b10001, 0b11110],
|
||||||
|
'C' => [0b01110, 0b10001, 0b10000, 0b10000, 0b10000, 0b10001, 0b01110],
|
||||||
|
'D' => [0b11100, 0b10010, 0b10001, 0b10001, 0b10001, 0b10010, 0b11100],
|
||||||
|
'E' => [0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b11111],
|
||||||
|
'F' => [0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b10000],
|
||||||
|
'G' => [0b01110, 0b10001, 0b10000, 0b10111, 0b10001, 0b10001, 0b01110],
|
||||||
|
'H' => [0b10001, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001],
|
||||||
|
'I' => [0b01110, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110],
|
||||||
|
'K' => [0b10001, 0b10010, 0b10100, 0b11000, 0b10100, 0b10010, 0b10001],
|
||||||
|
'L' => [0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b11111],
|
||||||
|
'M' => [0b10001, 0b11011, 0b10101, 0b10101, 0b10001, 0b10001, 0b10001],
|
||||||
|
'N' => [0b10001, 0b11001, 0b10101, 0b10011, 0b10001, 0b10001, 0b10001],
|
||||||
|
'O' => [0b01110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110],
|
||||||
|
'P' => [0b11110, 0b10001, 0b10001, 0b11110, 0b10000, 0b10000, 0b10000],
|
||||||
|
'Q' => [0b01110, 0b10001, 0b10001, 0b10001, 0b10101, 0b10010, 0b01101],
|
||||||
|
'R' => [0b11110, 0b10001, 0b10001, 0b11110, 0b10100, 0b10010, 0b10001],
|
||||||
|
'S' => [0b01111, 0b10000, 0b10000, 0b01110, 0b00001, 0b00001, 0b11110],
|
||||||
|
'T' => [0b11111, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100],
|
||||||
|
'U' => [0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110],
|
||||||
|
'V' => [0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01010, 0b00100],
|
||||||
|
'W' => [0b10001, 0b10001, 0b10001, 0b10101, 0b10101, 0b11011, 0b10001],
|
||||||
|
'Y' => [0b10001, 0b10001, 0b01010, 0b00100, 0b00100, 0b00100, 0b00100],
|
||||||
|
'.' => [0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b01100, 0b01100],
|
||||||
|
':' => [0b00000, 0b01100, 0b01100, 0b00000, 0b01100, 0b01100, 0b00000],
|
||||||
|
'-' => [0b00000, 0b00000, 0b00000, 0b11111, 0b00000, 0b00000, 0b00000],
|
||||||
|
'+' => [0b00000, 0b00100, 0b00100, 0b11111, 0b00100, 0b00100, 0b00000],
|
||||||
|
'%' => [0b11001, 0b11010, 0b00010, 0b00100, 0b01000, 0b01011, 0b10011],
|
||||||
|
'/' => [0b00001, 0b00010, 0b00010, 0b00100, 0b01000, 0b01000, 0b10000],
|
||||||
|
'[' => [0b01110, 0b01000, 0b01000, 0b01000, 0b01000, 0b01000, 0b01110],
|
||||||
|
']' => [0b01110, 0b00010, 0b00010, 0b00010, 0b00010, 0b00010, 0b01110],
|
||||||
|
_ => [0b00000; 7],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,246 @@
|
|||||||
|
use anyhow::{Context, Result};
|
||||||
|
use gstreamer as gst;
|
||||||
|
use gstreamer::prelude::*;
|
||||||
|
use gstreamer_app as gst_app;
|
||||||
|
use gstreamer_video as gst_video;
|
||||||
|
use parking_lot::Mutex;
|
||||||
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::thread;
|
||||||
|
use std::time::Instant;
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct VideoFrame {
|
||||||
|
pub width: u32,
|
||||||
|
pub height: u32,
|
||||||
|
pub rgba_data: Vec<u8>,
|
||||||
|
pub frame_id: u64,
|
||||||
|
pub received_at: Instant,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct UsbVideoReceiver {
|
||||||
|
pipeline: gst::Pipeline,
|
||||||
|
latest_frame: Arc<Mutex<Option<VideoFrame>>>,
|
||||||
|
stop_flag: Arc<AtomicBool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl UsbVideoReceiver {
|
||||||
|
/// Démarre l'acquisition vidéo USB depuis le VRX Radxa Zero 3W (Sphere Link) :
|
||||||
|
/// - Mode `"rndis"` : Réception du flux RTP H.265/H.264 via le port USB OTG (`usb0`, UDP :5600)
|
||||||
|
/// - Mode `"uvc"` : Réception directe depuis la sortie Mini-HDMI du VRX via une carte d'acquisition USB-C UVC (`/dev/video0`)
|
||||||
|
pub fn start(
|
||||||
|
usb_video_mode: &str,
|
||||||
|
uvc_device: &str,
|
||||||
|
bind_ip: &str,
|
||||||
|
port: u16,
|
||||||
|
codec: &str,
|
||||||
|
stream_transport: &str,
|
||||||
|
target_width: u32,
|
||||||
|
target_height: u32,
|
||||||
|
) -> Result<Self> {
|
||||||
|
gst::init().context(
|
||||||
|
"Impossible d'initialiser GStreamer (vérifiez l'installation de gst-plugins-base/good/bad)",
|
||||||
|
)?;
|
||||||
|
|
||||||
|
let pipeline_str = if usb_video_mode.eq_ignore_ascii_case("uvc") {
|
||||||
|
log::info!(
|
||||||
|
"[USB Vidéo UVC] Acquisition depuis la sortie Mini-HDMI de la Radxa Zero 3W via {}",
|
||||||
|
uvc_device
|
||||||
|
);
|
||||||
|
format!(
|
||||||
|
"v4l2src device={uvc_device} do-timestamp=true ! \
|
||||||
|
decodebin ! \
|
||||||
|
videoconvert ! videoscale ! \
|
||||||
|
video/x-raw,format=RGBA,width={target_width},height={target_height} ! \
|
||||||
|
appsink name=fpv_sink sync=false max-buffers=1 drop=true emit-signals=true"
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
let codec_lower = codec.to_lowercase();
|
||||||
|
let is_h264 = codec_lower == "h264";
|
||||||
|
let parser = if is_h264 { "h264parse" } else { "h265parse" };
|
||||||
|
let codec_name = if is_h264 { "H264" } else { "H265" };
|
||||||
|
let depay = if is_h264 { "rtph264depay" } else { "rtph265depay" };
|
||||||
|
let decoder = if is_h264 {
|
||||||
|
"avdec_h264 max-threads=1 discard-corrupted-frames=true"
|
||||||
|
} else {
|
||||||
|
"avdec_h265 max-threads=1 discard-corrupted-frames=true"
|
||||||
|
};
|
||||||
|
|
||||||
|
let depay_and_parse = if stream_transport.eq_ignore_ascii_case("rtp") {
|
||||||
|
format!(
|
||||||
|
"application/x-rtp,media=video,clock-rate=90000,encoding-name={codec_name},payload=96 ! \
|
||||||
|
{depay} ! {parser} config-interval=-1"
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
format!("{parser} config-interval=-1")
|
||||||
|
};
|
||||||
|
|
||||||
|
log::info!(
|
||||||
|
"[USB Vidéo OTG/RNDIS] Écoute du flux {transport} ({codec_name} faible latence) sur {bind_ip}:{port}",
|
||||||
|
transport = if stream_transport.eq_ignore_ascii_case("rtp") { "RTP" } else { "Raw NAL direct" },
|
||||||
|
);
|
||||||
|
|
||||||
|
format!(
|
||||||
|
"udpsrc address={bind_ip} port={port} buffer-size=524288 retrieve-sender-address=false ! \
|
||||||
|
{depay_and_parse} ! \
|
||||||
|
{decoder} ! \
|
||||||
|
videoconvert n-threads=2 ! videoscale method=1 ! \
|
||||||
|
video/x-raw,format=RGBA,width={target_width},height={target_height} ! \
|
||||||
|
appsink name=fpv_sink sync=false max-buffers=1 drop=true emit-signals=true"
|
||||||
|
)
|
||||||
|
};
|
||||||
|
|
||||||
|
let element = gst::parse::launch(&pipeline_str).map_err(|e| {
|
||||||
|
log::error!(
|
||||||
|
"[USB Vidéo] Échec de construction du pipeline GStreamer : {} (Pipeline: {})",
|
||||||
|
e,
|
||||||
|
pipeline_str
|
||||||
|
);
|
||||||
|
anyhow::anyhow!("Erreur pipeline GStreamer : {}", e)
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let pipeline = element
|
||||||
|
.dynamic_cast::<gst::Pipeline>()
|
||||||
|
.map_err(|_| anyhow::anyhow!("L'élément GStreamer n'est pas un Pipeline"))?;
|
||||||
|
|
||||||
|
let appsink = pipeline
|
||||||
|
.by_name("fpv_sink")
|
||||||
|
.context("Appsink 'fpv_sink' introuvable dans le pipeline")?
|
||||||
|
.dynamic_cast::<gst_app::AppSink>()
|
||||||
|
.map_err(|_| anyhow::anyhow!("Impossible de convertir fpv_sink en AppSink"))?;
|
||||||
|
|
||||||
|
let latest_frame: Arc<Mutex<Option<VideoFrame>>> = Arc::new(Mutex::new(None));
|
||||||
|
let frame_store = Arc::clone(&latest_frame);
|
||||||
|
let mut sequence: u64 = 0;
|
||||||
|
|
||||||
|
appsink.set_callbacks(
|
||||||
|
gst_app::AppSinkCallbacks::builder()
|
||||||
|
.new_sample(move |sink| {
|
||||||
|
let sample = sink.pull_sample().map_err(|_| gst::FlowError::Eos)?;
|
||||||
|
let buffer = sample.buffer().ok_or(gst::FlowError::Error)?;
|
||||||
|
let caps = sample.caps().ok_or(gst::FlowError::Error)?;
|
||||||
|
let video_info = gst_video::VideoInfo::from_caps(caps)
|
||||||
|
.map_err(|_| gst::FlowError::Error)?;
|
||||||
|
|
||||||
|
let map = buffer.map_readable().map_err(|_| gst::FlowError::Error)?;
|
||||||
|
sequence = sequence.wrapping_add(1);
|
||||||
|
|
||||||
|
if sequence == 1 {
|
||||||
|
log::info!(
|
||||||
|
"[USB Vidéo] Première image reçue depuis le VRX Sphere Link ({}x{}) !",
|
||||||
|
video_info.width(),
|
||||||
|
video_info.height()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut lock = frame_store.lock();
|
||||||
|
*lock = Some(VideoFrame {
|
||||||
|
width: video_info.width(),
|
||||||
|
height: video_info.height(),
|
||||||
|
rgba_data: map.as_slice().to_vec(),
|
||||||
|
frame_id: sequence,
|
||||||
|
received_at: Instant::now(),
|
||||||
|
});
|
||||||
|
|
||||||
|
Ok(gst::FlowSuccess::Ok)
|
||||||
|
})
|
||||||
|
.build(),
|
||||||
|
);
|
||||||
|
|
||||||
|
let stop_flag = Arc::new(AtomicBool::new(false));
|
||||||
|
if let Some(bus) = pipeline.bus() {
|
||||||
|
let stop_bus = Arc::clone(&stop_flag);
|
||||||
|
let _ = thread::Builder::new()
|
||||||
|
.name("gst-bus-monitor".into())
|
||||||
|
.spawn(move || {
|
||||||
|
while !stop_bus.load(Ordering::Relaxed) {
|
||||||
|
if let Some(msg) = bus.timed_pop(gst::ClockTime::from_mseconds(100)) {
|
||||||
|
use gst::MessageView;
|
||||||
|
match msg.view() {
|
||||||
|
MessageView::Error(err) => {
|
||||||
|
let src_name = err
|
||||||
|
.src()
|
||||||
|
.map(|s| s.path_string().to_string())
|
||||||
|
.unwrap_or_else(|| "inconnu".into());
|
||||||
|
log::error!(
|
||||||
|
"[GStreamer ERREUR] Source={} : {} (Détail debug: {:?})",
|
||||||
|
src_name,
|
||||||
|
err.error(),
|
||||||
|
err.debug()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
MessageView::Warning(warn) => {
|
||||||
|
log::warn!(
|
||||||
|
"[GStreamer WARN] {} (Détail: {:?})",
|
||||||
|
warn.error(),
|
||||||
|
warn.debug()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Err(e) = pipeline.set_state(gst::State::Playing) {
|
||||||
|
log::error!(
|
||||||
|
"[USB Vidéo] Impossible de démarrer le pipeline GStreamer (mode={}) : {}",
|
||||||
|
usb_video_mode,
|
||||||
|
e
|
||||||
|
);
|
||||||
|
anyhow::bail!("Échec démarrage GStreamer ({}) : {}", usb_video_mode, e);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(Self {
|
||||||
|
pipeline,
|
||||||
|
latest_frame,
|
||||||
|
stop_flag,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn latest_frame(&self) -> Arc<Mutex<Option<VideoFrame>>> {
|
||||||
|
Arc::clone(&self.latest_frame)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn generate_standby_pattern(width: u32, height: u32, tick: u32) -> Vec<u8> {
|
||||||
|
let mut data = vec![0u8; (width * height * 4) as usize];
|
||||||
|
let cx = (width / 2) as i32;
|
||||||
|
let cy = (height / 2) as i32;
|
||||||
|
let pulse = ((tick % 120) as f32 / 120.0 * std::f32::consts::TAU).sin() * 0.5 + 0.5;
|
||||||
|
let accent = (80.0 + pulse * 140.0) as u8;
|
||||||
|
|
||||||
|
for y in 0..height as i32 {
|
||||||
|
for x in 0..width as i32 {
|
||||||
|
let idx = ((y as u32 * width + x as u32) * 4) as usize;
|
||||||
|
let dx = (x - cx).abs();
|
||||||
|
let dy = (y - cy).abs();
|
||||||
|
|
||||||
|
let dist_sq = (x - cx) * (x - cx) + (y - cy) * (y - cy);
|
||||||
|
let on_crosshair = (dx < 2 && dy < 40) || (dy < 2 && dx < 60);
|
||||||
|
let on_ring = (dist_sq - 120 * 120).abs() < 350;
|
||||||
|
|
||||||
|
if on_crosshair || on_ring {
|
||||||
|
data[idx] = 0;
|
||||||
|
data[idx + 1] = accent;
|
||||||
|
data[idx + 2] = 255;
|
||||||
|
data[idx + 3] = 255;
|
||||||
|
} else {
|
||||||
|
data[idx] = 14;
|
||||||
|
data[idx + 1] = 18;
|
||||||
|
data[idx + 2] = 26;
|
||||||
|
data[idx + 3] = 255;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
data
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for UsbVideoReceiver {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.stop_flag.store(true, Ordering::Relaxed);
|
||||||
|
let _ = self.pipeline.set_state(gst::State::Null);
|
||||||
|
log::info!("[USB Vidéo] Pipeline GStreamer arrêté proprement.");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,375 @@
|
|||||||
|
use anyhow::{anyhow, Context, Result};
|
||||||
|
use ash::vk::{self, Handle};
|
||||||
|
use openxr as xr;
|
||||||
|
use std::ffi::CString;
|
||||||
|
|
||||||
|
/// Moteur de rendu OpenXR + Vulkan pour afficher le flux vidéo USB Sphere Link
|
||||||
|
/// dans les couches de composition OpenXR (`Equirect2`, `Cylinder`, ou `Quad`).
|
||||||
|
pub struct VulkanXrContext {
|
||||||
|
pub vk_entry: ash::Entry,
|
||||||
|
pub vk_instance: ash::Instance,
|
||||||
|
pub vk_device: ash::Device,
|
||||||
|
pub queue: vk::Queue,
|
||||||
|
pub queue_family_index: u32,
|
||||||
|
pub command_pool: vk::CommandPool,
|
||||||
|
pub command_buffer: vk::CommandBuffer,
|
||||||
|
pub upload_fence: vk::Fence,
|
||||||
|
pub staging_buffer: vk::Buffer,
|
||||||
|
pub staging_memory: vk::DeviceMemory,
|
||||||
|
pub staging_mapped_ptr: *mut u8,
|
||||||
|
pub staging_size: usize,
|
||||||
|
pub session: xr::Session<xr::Vulkan>,
|
||||||
|
pub frame_wait: xr::FrameWaiter,
|
||||||
|
pub frame_stream: xr::FrameStream<xr::Vulkan>,
|
||||||
|
pub swapchain: xr::Swapchain<xr::Vulkan>,
|
||||||
|
pub swapchain_images: Vec<vk::Image>,
|
||||||
|
pub width: u32,
|
||||||
|
pub height: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe impl Send for VulkanXrContext {}
|
||||||
|
|
||||||
|
impl VulkanXrContext {
|
||||||
|
pub fn new(
|
||||||
|
xr_instance: &xr::Instance,
|
||||||
|
system: xr::SystemId,
|
||||||
|
width: u32,
|
||||||
|
height: u32,
|
||||||
|
) -> Result<Self> {
|
||||||
|
let reqs = xr_instance
|
||||||
|
.graphics_requirements::<xr::Vulkan>(system)
|
||||||
|
.context("Impossible de récupérer les prérequis Vulkan OpenXR")?;
|
||||||
|
|
||||||
|
let target_vk_version = vk::make_api_version(0, 1, 1, 0);
|
||||||
|
if reqs.min_api_version_supported > xr::Version::new(1, 1, 0) {
|
||||||
|
log::warn!(
|
||||||
|
"Version Vulkan minimale requise par le runtime : {:?}",
|
||||||
|
reqs.min_api_version_supported
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
let vk_entry = unsafe { ash::Entry::load().context("Impossible de charger libvulkan.so")? };
|
||||||
|
let app_name = CString::new("SphereFrameFPV")?;
|
||||||
|
let engine_name = CString::new("SphereFrameVulkan")?;
|
||||||
|
|
||||||
|
let app_info = vk::ApplicationInfo::default()
|
||||||
|
.application_name(&app_name)
|
||||||
|
.application_version(1)
|
||||||
|
.engine_name(&engine_name)
|
||||||
|
.engine_version(1)
|
||||||
|
.api_version(target_vk_version);
|
||||||
|
|
||||||
|
let vk_instance_create_info = vk::InstanceCreateInfo::default().application_info(&app_info);
|
||||||
|
|
||||||
|
let vk_instance_raw = unsafe {
|
||||||
|
xr_instance
|
||||||
|
.create_vulkan_instance(
|
||||||
|
system,
|
||||||
|
std::mem::transmute(vk_entry.static_fn().get_instance_proc_addr),
|
||||||
|
&vk_instance_create_info as *const _ as *const _,
|
||||||
|
)
|
||||||
|
.context("Échec de xrCreateVulkanInstanceKHR")?
|
||||||
|
.map_err(vk::Result::from_raw)
|
||||||
|
.context("Erreur Vulkan lors de la création de VkInstance")?
|
||||||
|
};
|
||||||
|
|
||||||
|
let vk_instance = unsafe {
|
||||||
|
ash::Instance::load(
|
||||||
|
vk_entry.static_fn(),
|
||||||
|
vk::Instance::from_raw(vk_instance_raw as u64),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
|
||||||
|
let phys_device_raw = unsafe {
|
||||||
|
xr_instance
|
||||||
|
.vulkan_graphics_device(system, vk_instance.handle().as_raw() as _)
|
||||||
|
.context("Impossible d'obtenir le VkPhysicalDevice pour le Steam Frame")?
|
||||||
|
};
|
||||||
|
let phys_device = vk::PhysicalDevice::from_raw(phys_device_raw as u64);
|
||||||
|
|
||||||
|
let queue_props =
|
||||||
|
unsafe { vk_instance.get_physical_device_queue_family_properties(phys_device) };
|
||||||
|
let queue_family_index = queue_props
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.find_map(|(idx, info)| {
|
||||||
|
if info.queue_flags.contains(vk::QueueFlags::GRAPHICS)
|
||||||
|
&& info.queue_flags.contains(vk::QueueFlags::TRANSFER)
|
||||||
|
{
|
||||||
|
Some(idx as u32)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.ok_or_else(|| anyhow!("Aucune file Vulkan GRAPHICS + TRANSFER trouvée"))?;
|
||||||
|
|
||||||
|
let queue_priorities = [1.0f32];
|
||||||
|
let queue_create_info = [vk::DeviceQueueCreateInfo::default()
|
||||||
|
.queue_family_index(queue_family_index)
|
||||||
|
.queue_priorities(&queue_priorities)];
|
||||||
|
|
||||||
|
let device_create_info =
|
||||||
|
vk::DeviceCreateInfo::default().queue_create_infos(&queue_create_info);
|
||||||
|
|
||||||
|
let vk_device_raw = unsafe {
|
||||||
|
xr_instance
|
||||||
|
.create_vulkan_device(
|
||||||
|
system,
|
||||||
|
std::mem::transmute(vk_entry.static_fn().get_instance_proc_addr),
|
||||||
|
phys_device.as_raw() as _,
|
||||||
|
&device_create_info as *const _ as *const _,
|
||||||
|
)
|
||||||
|
.context("Échec de xrCreateVulkanDeviceKHR")?
|
||||||
|
.map_err(vk::Result::from_raw)
|
||||||
|
.context("Erreur Vulkan lors de la création de VkDevice")?
|
||||||
|
};
|
||||||
|
|
||||||
|
let vk_device = unsafe {
|
||||||
|
ash::Device::load(
|
||||||
|
vk_instance.fp_v1_0(),
|
||||||
|
vk::Device::from_raw(vk_device_raw as u64),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
|
||||||
|
let queue = unsafe { vk_device.get_device_queue(queue_family_index, 0) };
|
||||||
|
|
||||||
|
let (session, frame_wait, frame_stream) = unsafe {
|
||||||
|
xr_instance
|
||||||
|
.create_session::<xr::Vulkan>(
|
||||||
|
system,
|
||||||
|
&xr::vulkan::SessionCreateInfo {
|
||||||
|
instance: vk_instance.handle().as_raw() as _,
|
||||||
|
physical_device: phys_device.as_raw() as _,
|
||||||
|
device: vk_device.handle().as_raw() as _,
|
||||||
|
queue_family_index,
|
||||||
|
queue_index: 0,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.context("Impossible de créer la session OpenXR Vulkan")?
|
||||||
|
};
|
||||||
|
|
||||||
|
let formats = session.enumerate_swapchain_formats()?;
|
||||||
|
let format = if formats.contains(&(vk::Format::R8G8B8A8_SRGB.as_raw() as u32)) {
|
||||||
|
vk::Format::R8G8B8A8_SRGB.as_raw() as u32
|
||||||
|
} else if formats.contains(&(vk::Format::R8G8B8A8_UNORM.as_raw() as u32)) {
|
||||||
|
vk::Format::R8G8B8A8_UNORM.as_raw() as u32
|
||||||
|
} else {
|
||||||
|
*formats
|
||||||
|
.first()
|
||||||
|
.ok_or_else(|| anyhow!("Aucun format de Swapchain supporté"))?
|
||||||
|
};
|
||||||
|
|
||||||
|
let swapchain = session.create_swapchain(&xr::SwapchainCreateInfo {
|
||||||
|
create_flags: xr::SwapchainCreateFlags::EMPTY,
|
||||||
|
usage_flags: xr::SwapchainUsageFlags::COLOR_ATTACHMENT
|
||||||
|
| xr::SwapchainUsageFlags::SAMPLED
|
||||||
|
| xr::SwapchainUsageFlags::TRANSFER_DST,
|
||||||
|
format,
|
||||||
|
sample_count: 1,
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
face_count: 1,
|
||||||
|
array_size: 1,
|
||||||
|
mip_count: 1,
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let swapchain_images: Vec<vk::Image> = swapchain
|
||||||
|
.enumerate_images()?
|
||||||
|
.into_iter()
|
||||||
|
.map(|raw| vk::Image::from_raw(raw))
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let pool_info = vk::CommandPoolCreateInfo::default()
|
||||||
|
.queue_family_index(queue_family_index)
|
||||||
|
.flags(vk::CommandPoolCreateFlags::RESET_COMMAND_BUFFER);
|
||||||
|
let command_pool = unsafe { vk_device.create_command_pool(&pool_info, None)? };
|
||||||
|
|
||||||
|
let alloc_info = vk::CommandBufferAllocateInfo::default()
|
||||||
|
.command_pool(command_pool)
|
||||||
|
.level(vk::CommandBufferLevel::PRIMARY)
|
||||||
|
.command_buffer_count(1);
|
||||||
|
let command_buffer = unsafe { vk_device.allocate_command_buffers(&alloc_info)?[0] };
|
||||||
|
|
||||||
|
let fence_info = vk::FenceCreateInfo::default();
|
||||||
|
let upload_fence = unsafe { vk_device.create_fence(&fence_info, None)? };
|
||||||
|
|
||||||
|
let staging_size = (width * height * 4) as usize;
|
||||||
|
let buffer_info = vk::BufferCreateInfo::default()
|
||||||
|
.size(staging_size as u64)
|
||||||
|
.usage(vk::BufferUsageFlags::TRANSFER_SRC)
|
||||||
|
.sharing_mode(vk::SharingMode::EXCLUSIVE);
|
||||||
|
let staging_buffer = unsafe { vk_device.create_buffer(&buffer_info, None)? };
|
||||||
|
let mem_reqs = unsafe { vk_device.get_buffer_memory_requirements(staging_buffer) };
|
||||||
|
let mem_props =
|
||||||
|
unsafe { vk_instance.get_physical_device_memory_properties(phys_device) };
|
||||||
|
|
||||||
|
let memory_type_index = (0..mem_props.memory_type_count)
|
||||||
|
.find(|&i| {
|
||||||
|
let suitable = (mem_reqs.memory_type_bits & (1 << i)) != 0;
|
||||||
|
let flags = mem_props.memory_types[i as usize].property_flags;
|
||||||
|
suitable
|
||||||
|
&& flags.contains(
|
||||||
|
vk::MemoryPropertyFlags::HOST_VISIBLE
|
||||||
|
| vk::MemoryPropertyFlags::HOST_COHERENT,
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.ok_or_else(|| anyhow!("Aucune mémoire Vulkan HOST_VISIBLE | HOST_COHERENT trouvée"))?;
|
||||||
|
|
||||||
|
let mem_alloc = vk::MemoryAllocateInfo::default()
|
||||||
|
.allocation_size(mem_reqs.size)
|
||||||
|
.memory_type_index(memory_type_index);
|
||||||
|
let staging_memory = unsafe { vk_device.allocate_memory(&mem_alloc, None)? };
|
||||||
|
unsafe { vk_device.bind_buffer_memory(staging_buffer, staging_memory, 0)? };
|
||||||
|
|
||||||
|
let staging_mapped_ptr = unsafe {
|
||||||
|
vk_device.map_memory(
|
||||||
|
staging_memory,
|
||||||
|
0,
|
||||||
|
staging_size as u64,
|
||||||
|
vk::MemoryMapFlags::empty(),
|
||||||
|
)? as *mut u8
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(Self {
|
||||||
|
vk_entry,
|
||||||
|
vk_instance,
|
||||||
|
vk_device,
|
||||||
|
queue,
|
||||||
|
queue_family_index,
|
||||||
|
command_pool,
|
||||||
|
command_buffer,
|
||||||
|
upload_fence,
|
||||||
|
staging_buffer,
|
||||||
|
staging_memory,
|
||||||
|
staging_mapped_ptr,
|
||||||
|
staging_size,
|
||||||
|
session,
|
||||||
|
frame_wait,
|
||||||
|
frame_stream,
|
||||||
|
swapchain,
|
||||||
|
swapchain_images,
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Copie les pixels RGBA de la frame vidéo dans l'image active du Swapchain OpenXR
|
||||||
|
pub fn upload_rgba_to_swapchain(&mut self, rgba_bytes: &[u8]) -> Result<()> {
|
||||||
|
let img_idx = self.swapchain.acquire_image()?;
|
||||||
|
self.swapchain.wait_image(xr::Duration::INFINITE)?;
|
||||||
|
|
||||||
|
let copy_len = rgba_bytes.len().min(self.staging_size);
|
||||||
|
unsafe {
|
||||||
|
std::ptr::copy_nonoverlapping(rgba_bytes.as_ptr(), self.staging_mapped_ptr, copy_len);
|
||||||
|
}
|
||||||
|
|
||||||
|
let target_image = self.swapchain_images[img_idx as usize];
|
||||||
|
|
||||||
|
unsafe {
|
||||||
|
self.vk_device
|
||||||
|
.reset_command_buffer(self.command_buffer, vk::CommandBufferResetFlags::empty())?;
|
||||||
|
|
||||||
|
let begin_info = vk::CommandBufferBeginInfo::default()
|
||||||
|
.flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT);
|
||||||
|
self.vk_device
|
||||||
|
.begin_command_buffer(self.command_buffer, &begin_info)?;
|
||||||
|
|
||||||
|
let subresource_range = vk::ImageSubresourceRange {
|
||||||
|
aspect_mask: vk::ImageAspectFlags::COLOR,
|
||||||
|
base_mip_level: 0,
|
||||||
|
level_count: 1,
|
||||||
|
base_array_layer: 0,
|
||||||
|
layer_count: 1,
|
||||||
|
};
|
||||||
|
|
||||||
|
let barrier_to_dst = 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_range);
|
||||||
|
|
||||||
|
self.vk_device.cmd_pipeline_barrier(
|
||||||
|
self.command_buffer,
|
||||||
|
vk::PipelineStageFlags::TOP_OF_PIPE,
|
||||||
|
vk::PipelineStageFlags::TRANSFER,
|
||||||
|
vk::DependencyFlags::empty(),
|
||||||
|
&[],
|
||||||
|
&[],
|
||||||
|
&[barrier_to_dst],
|
||||||
|
);
|
||||||
|
|
||||||
|
let region = vk::BufferImageCopy {
|
||||||
|
buffer_offset: 0,
|
||||||
|
buffer_row_length: 0,
|
||||||
|
buffer_image_height: 0,
|
||||||
|
image_subresource: vk::ImageSubresourceLayers {
|
||||||
|
aspect_mask: vk::ImageAspectFlags::COLOR,
|
||||||
|
mip_level: 0,
|
||||||
|
base_array_layer: 0,
|
||||||
|
layer_count: 1,
|
||||||
|
},
|
||||||
|
image_offset: vk::Offset3D { x: 0, y: 0, z: 0 },
|
||||||
|
image_extent: vk::Extent3D {
|
||||||
|
width: self.width,
|
||||||
|
height: self.height,
|
||||||
|
depth: 1,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
self.vk_device.cmd_copy_buffer_to_image(
|
||||||
|
self.command_buffer,
|
||||||
|
self.staging_buffer,
|
||||||
|
target_image,
|
||||||
|
vk::ImageLayout::TRANSFER_DST_OPTIMAL,
|
||||||
|
&[region],
|
||||||
|
);
|
||||||
|
|
||||||
|
let barrier_to_color = 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_range);
|
||||||
|
|
||||||
|
self.vk_device.cmd_pipeline_barrier(
|
||||||
|
self.command_buffer,
|
||||||
|
vk::PipelineStageFlags::TRANSFER,
|
||||||
|
vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT,
|
||||||
|
vk::DependencyFlags::empty(),
|
||||||
|
&[],
|
||||||
|
&[],
|
||||||
|
&[barrier_to_color],
|
||||||
|
);
|
||||||
|
|
||||||
|
self.vk_device.end_command_buffer(self.command_buffer)?;
|
||||||
|
|
||||||
|
let cmd_buffers = [self.command_buffer];
|
||||||
|
let submit_info = [vk::SubmitInfo::default().command_buffers(&cmd_buffers)];
|
||||||
|
self.vk_device
|
||||||
|
.reset_fences(&[self.upload_fence])?;
|
||||||
|
self.vk_device
|
||||||
|
.queue_submit(self.queue, &submit_info, self.upload_fence)?;
|
||||||
|
self.vk_device
|
||||||
|
.wait_for_fences(&[self.upload_fence], true, u64::MAX)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
self.swapchain.release_image()?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for VulkanXrContext {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
unsafe {
|
||||||
|
let _ = self.vk_device.device_wait_idle();
|
||||||
|
self.vk_device.unmap_memory(self.staging_memory);
|
||||||
|
self.vk_device.destroy_buffer(self.staging_buffer, None);
|
||||||
|
self.vk_device.free_memory(self.staging_memory, None);
|
||||||
|
self.vk_device.destroy_fence(self.upload_fence, None);
|
||||||
|
self.vk_device.destroy_command_pool(self.command_pool, None);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user