feat: add Steam Controller support with hot-switchable G29/Steam selector

This commit is contained in:
bleack committed 2026-11-21 02:18:22 +01:00
1 parent d5dc1de504
commit 95ad271232
11 files changed
+1979 -81

No files matched your search

+5
View File
@@ -21,6 +21,7 @@ Application graphique et VR native **Linux / SteamOS (ARM64 & x86_64)** en **Rus
- **`crsf`** : Trames `RC_CHANNELS_PACKED (0x16)` (11 bits `172..1811`).
- **`mavlink`** : `MAVLink v1 RC_CHANNELS_OVERRIDE` + `HEARTBEAT` (ex. `elrs_txbp.local:14555`).
- **Commandes volant G29 (`$G29` / `$G29_EVT`)** : Tare Head-Tracking (`Cross`/`PS`/`R3`), DVR (`Share`/`Circle`), OSD (`Triangle`), Projection VR (`Square`), Trim Pan/Tilt (`D-Pad`) et affichage rapport engagé / armement / pédales dans le HUD.
- **Support Steam Controller (`src/controller.rs`, bascule à chaud G29 ⇄ Steam Controller)** : Lecture Linux `evdev` native (dongle sans fil `Steam Controller Puck`, USB ou gamepad standard) avec boîte séquentielle `R/N/1/2/3`, sécurité d'armement, mêmes raccourcis cockpit et injection `$SRC,EXT` / `$RC,...` à `100 Hz` vers la RP2350 via le pont UDP `14552`.
- **Télémétrie & OSD Vectoriel (`src/telemetry_osd.rs`)** :
- Décodage unifié depuis le port UDP `14552` (`$CRSF,<HEX>` remonté par `g29_crsf` via la Radxa) **et/ou** le port UDP `14551` (MAVLink v1/v2 & CRSF) avec validation **CRC-16 / CRC-8 DVB-S2**.
- Incrustation OSD zéro-allocation (`StackStr`) : horizon artificiel, ruban de cap, radar gimbal Pan/Tilt, tension/courant batterie, LQ/RSSI, vitesse, altitude/VSI, mode de projection et indicateur `REC`.
@@ -108,6 +109,10 @@ Le script [launch.sh](launch.sh) prépare `libxkbcommon-x11.so` si besoin, compi
| `--ht-protocol` | `g29` | Protocole Head-Tracking : `g29` (pont unifié `$HT`), `msp`, `crsf`, `mavlink` |
| `--nomad-ip` / `--nomad-port` | `192.168.1.1` / `14552` | Cible UDP du pont unifié Radxa/G29 (`10.0.0.1:14550` pour Backpack AP) |
| `--g29-enabled` / `--g29-udp-port` | `true` / `14552` | Active la passerelle unifiée G29 + boutons + télémétrie `$CRSF` |
| `--control-source` | `g29` | Source de conduite active : `g29` (Volant Logitech G29) ou `steam` (Steam Controller) |
| `--controller-device` | *(auto)* | Chemin `evdev` explicite du Steam Controller (ex. `/dev/input/event28`, auto-détecté par défaut) |
| `--controller-expo` / `--controller-deadzone` | `0.25` / `0.08` | Expo cubique et zone morte du stick gauche du Steam Controller |
| `--controller-invert-steering` | `false` | Inverse le sens de direction du Steam Controller |
| `--telemetry-enabled` / `--telemetry-udp-port` | `false` / `14551` | Active l'OSD et écoute MAVLink / CRSF |
| `--dvr-dir` / `--dvr-format` / `--dvr-mode` | `recordings` / `mkv` / `copy` | Dossier, conteneur (`mkv`, `mp4`) et mode (`copy`, `composited`) |
| `--log-file` | `steamframe_fpv.log` | Fichier de journalisation persistant |
+4 -2
View File
@@ -21,10 +21,10 @@ Firmware dual-core pour **Waveshare RP2350-USB-A** transformant un volant **Logi
```
### Ce qui est centralisé sur la RP2350 :
1. **Pilotage G29 (`CH1..CH5`)** : Volant (`CH1`), Accélérateur avec boîte séquentielle R/N/1/2/3 (`CH2`), Frein (`CH3`), Embrayage (`CH4`), Armement R2 (`CH5`).
1. **Pilotage G29 (`CH1..CH5`) ou Steam Controller externe (`$SRC,EXT` + `$RC,...`)** : Volant/Stick (`CH1`), Accélérateur avec boîte séquentielle R/N/1/2/3 (`CH2`), Frein (`CH3`), Embrayage (`CH4`), Armement (`CH5`). En mode `EXT`, la RP2350 applique un **watchdog failsafe de `400 ms`** sur `$RC` et fonctionne même si le G29 est débranché.
2. **Mixage Head-Tracking (`CH6..CH8`)** : Réception des trames `$HT,<pan>,<tilt>,<roll>` (valeurs CRSF `172..1811`, neutre `992`) depuis le casque via la Radxa Zero 3W (`Serial2` à `460 800 bauds` ou `Serial` USB-C), avec **watchdog de recentrage automatique à `500 ms`**.
3. **Relais Télémétrie & État Cockpit** :
- État G29 à 20 Hz (`$G29,ARM=...,GEAR=...,THROT=...,BRAKE=...,FFB=...,VIB=...,FAIL=...`).
- État actif à 20 Hz (`$G29,ARM=...,GEAR=...,THROT=...,BRAKE=...,FFB=...,VIB=...,FAIL=...,SRC=G29|EXT`).
- Événements boutons immédiats (`$G29_EVT,BTN=...`) pour piloter l'OSD, le DVR, le mode de projection VR et la Tare Head-Tracking depuis le volant.
- Relais complet des trames CRSF valides reçues sur `GP1` (`$CRSF,<HEX>`) vers l'OSD de `steamframe-fpv`, tout en conservant le calcul local de rugosité (`0x1E`) pour le retour de force haptique du volant.
@@ -76,6 +76,8 @@ Firmware dual-core pour **Waveshare RP2350-USB-A** transformant un volant **Logi
| Commande | Description |
| :--- | :--- |
| `$SRC,G29` / `$SRC,EXT` | Bascule la source de conduite active (Volant G29 ou Steam Controller externe, désarmé uniquement) |
| `$RC,<dir>,<gaz>,<frn>,<emb>,<arm>,<gear>` | Injecte la conduite externe (`CH1..CH5`, valeurs CRSF `172..1811`, watchdog `400 ms`) en mode `EXT` |
| `$HT,<pan>,<tilt>,<roll>` | Injecte le Head-Tracking sur `CH6, CH7, CH8` (`172..1811`) |
| `D=<0..255>` | Règle la dureté du ressort FFB (sauvegarde différée si armé) |
| `T=<0..100>` | Règle l'intensité des vibrations haptiques (`0` = désactivé) |
+244 -47
View File
@@ -56,6 +56,13 @@
#define UART_BRIDGE_BAUD 460800
#define INTERVALLE_COCKPIT_MS 50 // 20 Hz
#define TIMEOUT_HT_MS 500 // Retour au centre si le casque ne répond plus
#define TIMEOUT_RC_EXT_MS 400 // Watchdog failsafe si la manette externe (Steam Controller) ne répond plus
// Source active de pilotage (bascule via $SRC,G29 ou $SRC,EXT)
enum SourceControle : uint8_t {
SRC_G29 = 0,
SRC_EXT = 1,
};
// Bits d'événements boutons (Cœur 1 -> Cœur 0)
enum CockpitBoutonBit : uint16_t {
@@ -218,6 +225,29 @@ bool cockpitEchoUSB = true; // Actif par défaut pour lia
uint32_t dernierPaquetHT_ms = 0;
bool htActif = false;
// Pilotage externe (Steam Controller via SteamFrame FPV -> Radxa -> RP2350)
volatile uint8_t sourceActive = SRC_G29;
volatile bool extRcActif = false;
volatile bool extArme = false;
volatile int8_t extRapport = 0;
volatile uint8_t extAccelPct = 0;
volatile uint8_t extFreinPct = 0;
volatile uint32_t dernierPaquetRC_ms = 0;
static inline bool estActuellementArme() {
return (sourceActive == SRC_EXT) ? extArme : estArme;
}
static inline int8_t rapportActuel() {
return (sourceActive == SRC_EXT) ? extRapport : rapportEngage;
}
static inline void assignerCanalCRSF(uint8_t numeroCh, uint16_t valeur11bits) {
if (numeroCh >= 1 && numeroCh <= 16 && numeroCh != CANAL_ARM) {
crsf_channels[numeroCh - 1] = valeur11bits;
}
}
char serialBuffer[64];
uint8_t serialBufferIdx = 0;
char serial2Buffer[64];
@@ -276,8 +306,10 @@ void afficherConfiguration() {
configSysteme.forceRessort, (configSysteme.forceRessort * 100) / 255);
Serial.printf("Plage Volant(P): %d degres [P=40..900]\n", configSysteme.angleSouhaiteTotal);
Serial.printf("Expo Volant(X) : %.2f [X=0.00..0.80]\n", configSysteme.expoVolant);
Serial.printf("Source active : %s [$SRC,G29 | $SRC,EXT]\n",
(sourceActive == SRC_EXT) ? "EXT (Steam Controller)" : "G29 (Volant)");
Serial.printf("Vibrations (T) : %d%% [Boutons +/- ou T=0..100] (0 = desactive)\n", configSysteme.intensiteVibration);
Serial.println("Commandes : V=ch, A=ch, F=ch, E=ch, D=val, P=val, X=val, T=val, S(save), R(reset), B(bootsel), ?");
Serial.println("Commandes : V=ch, A=ch, F=ch, E=ch, D=val, P=val, X=val, T=val, $SRC,G29|EXT, $RC,..., $HT,..., S(save), R(reset), B(bootsel), ?");
}
void chargerConfiguration() {
@@ -325,7 +357,7 @@ void chargerConfiguration() {
// GESTION SÉRIE NON BLOQUANTE
// -------------------------------------------------------------------------
void demanderOuExecuterSauvegarde() {
if (estArme) {
if (estActuellementArme()) {
sauvegardeDifferee = true;
Serial.println(">> Modification appliquee (sauvegarde Flash differee au desarmement).");
} else {
@@ -341,7 +373,7 @@ void traiterLigneSerie(char* commande) {
return;
}
if (commande[0] == 'B' || commande[0] == 'b') {
if (estArme) {
if (estActuellementArme()) {
Serial.println("!! Redemarrage BOOTSEL refuse pendant la conduite (desarmer d'abord) !!");
return;
}
@@ -351,7 +383,7 @@ void traiterLigneSerie(char* commande) {
return;
}
if (commande[0] == 'S' || commande[0] == 's') {
if (estArme) {
if (estActuellementArme()) {
Serial.println("!! Sauvegarde Flash refusee pendant la conduite (desarmer d'abord) !!");
return;
}
@@ -361,7 +393,7 @@ void traiterLigneSerie(char* commande) {
return;
}
if (commande[0] == 'R' || commande[0] == 'r') {
if (estArme) {
if (estActuellementArme()) {
Serial.println("!! Reinitialisation refusee pendant la conduite (desarmer d'abord) !!");
return;
}
@@ -370,7 +402,14 @@ void traiterLigneSerie(char* commande) {
reinitialiserCanauxCRSF();
rapportEngage = 0;
estArme = false;
extArme = false;
extRapport = 0;
extAccelPct = 0;
extFreinPct = 0;
extRcActif = false;
sourceActive = SRC_G29;
majLedRequise = true;
cockpitEtatModifie = true;
momentDernierChangementDurete_ms = 0;
sauvegardeDifferee = false;
rp2040.resumeOtherCore();
@@ -384,7 +423,7 @@ void traiterLigneSerie(char* commande) {
char periph = commande[0];
if (periph == 'V' || periph == 'v' || periph == 'A' || periph == 'a' ||
periph == 'F' || periph == 'f' || periph == 'E' || periph == 'e') {
if (estArme) {
if (estActuellementArme()) {
Serial.println("!! Remappage des canaux refuse pendant la conduite (desarmer d'abord) !!");
return;
}
@@ -436,7 +475,7 @@ void traiterLigneSerie(char* commande) {
Serial.println("!! Durete (D) doit etre entre 0 et 255 !!");
}
} else if (periph == 'P' || periph == 'p') {
if (estArme) {
if (estActuellementArme()) {
Serial.println("!! Reglage de plage (P) refuse pendant la conduite (desarmer d'abord) !!");
return;
}
@@ -453,7 +492,7 @@ void traiterLigneSerie(char* commande) {
Serial.println("!! Plage d'angle (P) doit etre entre 40 et 900 degres !!");
}
} else if (periph == 'X' || periph == 'x') {
if (estArme) {
if (estActuellementArme()) {
Serial.println("!! Reglage d'expo (X) refuse pendant la conduite (desarmer d'abord) !!");
return;
}
@@ -494,6 +533,124 @@ void traiterLigneSerie(char* commande) {
dernierPaquetHT_ms = millis();
htActif = true;
}
return;
}
// Sélection de la source de pilotage : $SRC,G29 ou $SRC,EXT (Steam Controller)
if (strncmp(commande, "$SRC,", 5) == 0) {
const char* mode = commande + 5;
uint8_t cible = sourceActive;
if (strcmp(mode, "G29") == 0 || strcmp(mode, "g29") == 0) {
cible = SRC_G29;
} else if (strcmp(mode, "EXT") == 0 || strcmp(mode, "ext") == 0 || strcmp(mode, "STEAM") == 0) {
cible = SRC_EXT;
} else {
Serial.printf("!! [SRC] Source inconnue : %s (attendu G29 ou EXT) !!\n", mode);
return;
}
if (cible == sourceActive) {
cockpitEtatModifie = true;
return;
}
if (estActuellementArme()) {
Serial.println("!! [SRC] Changement de controleur refuse : desarmer d'abord !!");
cockpitEtatModifie = true;
return;
}
rp2040.idleOtherCore();
sourceActive = cible;
extRcActif = false;
extArme = false;
extRapport = 0;
extAccelPct = 0;
extFreinPct = 0;
estArme = false;
rapportEngage = 0;
boutonArmDejaEnfonce = true;
palettePlusDejaEnfoncee = true;
paletteMoinsDejaEnfoncee = true;
etatBoutonsCockpitPrec = 0xFFFF;
reinitialiserCanauxCRSF();
rp2040.resumeOtherCore();
majLedRequise = true;
cockpitEtatModifie = true;
Serial.printf(">> [SRC] Source active basculee sur : %s\n",
(sourceActive == SRC_EXT) ? "EXT (Steam Controller)" : "G29 (Volant)");
return;
}
// Injection conduite externe (Steam Controller via SteamFrame FPV) :
// $RC,<steer>,<accel>,<brake>,<clutch>,<arm>,<gear>
if (strncmp(commande, "$RC,", 4) == 0) {
if (sourceActive != SRC_EXT) {
return;
}
int steer = CRSF_VAL_MID, accel = CRSF_VAL_MID, brake = CRSF_VAL_MID, clutch = CRSF_VAL_MID;
int arm = 0, gear = 0;
if (sscanf(commande + 4, "%d,%d,%d,%d,%d,%d", &steer, &accel, &brake, &clutch, &arm, &gear) == 6) {
uint16_t vSteer = (uint16_t)constrain(steer, CRSF_VAL_MIN, CRSF_VAL_MAX);
uint16_t vAccel = (uint16_t)constrain(accel, CRSF_VAL_MIN, CRSF_VAL_MAX);
uint16_t vBrake = (uint16_t)constrain(brake, CRSF_VAL_MIN, CRSF_VAL_MAX);
uint16_t vClutch = (uint16_t)constrain(clutch, CRSF_VAL_MIN, CRSF_VAL_MAX);
int8_t vGear = (int8_t)constrain(gear, -1, 3);
bool demandeArm = (arm != 0);
// Sécurité : refuser un armement (0 -> 1) si rapport != N ou gaz non neutres
if (demandeArm && !extArme) {
if (vGear == 0 && vAccel == CRSF_VAL_MID) {
extArme = true;
momentArmement_ms = millis();
momentDesarmement_ms = 0;
majLedRequise = true;
cockpitEtatModifie = true;
Serial.println(">> [ARM EXT] ARME (Steam Controller)");
}
} else if (!demandeArm && extArme) {
extArme = false;
momentDesarmement_ms = millis();
momentArmement_ms = 0;
majLedRequise = true;
cockpitEtatModifie = true;
Serial.println(">> [ARM EXT] DESARME (Steam Controller)");
}
if (vGear != extRapport) {
extRapport = vGear;
majLedRequise = true;
cockpitEtatModifie = true;
}
if (!extArme || extRapport == 0) {
vAccel = CRSF_VAL_MID;
}
uint8_t accelPct = 0;
if (extArme && extRapport >= 1 && extRapport <= 3 && vAccel >= GAZ_AVANT_MIN) {
uint16_t maxV = GAZ_AVANT_MAX_PAR_VITESSE[extRapport - 1];
accelPct = (uint8_t)constrain(map(vAccel, GAZ_AVANT_MIN, maxV, 0, 100), 0, 100);
} else if (extArme && extRapport == -1 && vAccel <= GAZ_ARRIERE_MIN) {
accelPct = (uint8_t)constrain(map(vAccel, GAZ_ARRIERE_MIN, GAZ_ARRIERE_MAX, 0, 100), 0, 100);
}
uint8_t brakePct = (vBrake > CRSF_VAL_MID)
? (uint8_t)constrain(map(vBrake, CRSF_VAL_MID, CRSF_VAL_MAX, 0, 100), 0, 100)
: 0;
extAccelPct = accelPct;
extFreinPct = brakePct;
assignerCanalCRSF(configSysteme.volant, vSteer);
assignerCanalCRSF(configSysteme.accel, vAccel);
assignerCanalCRSF(configSysteme.frein, vBrake);
assignerCanalCRSF(configSysteme.embrayage, vClutch);
crsf_channels[CANAL_ARM - 1] = extArme ? CRSF_VAL_MAX : CRSF_VAL_MIN;
dernierPaquetRC_ms = millis();
if (!extRcActif) {
extRcActif = true;
majLedRequise = true;
cockpitEtatModifie = true;
}
}
return;
}
}
@@ -538,19 +695,19 @@ void actualiserLED() {
} else if (momentDesarmement_ms > 0 && dtDesarm < 250) {
// Animation NeoPixel au desarmement : flash rouge d'arret
r = 255; g = 20; b = 0;
} else if (!volant_est_pret) {
b = 255; // Bleu : Attente G29
} else if ((sourceActive == SRC_G29 && !volant_est_pret) || (sourceActive == SRC_EXT && !extRcActif)) {
b = 255; // Bleu : Attente contrôleur actif (G29 ou Steam Controller)
} else if (failsafeActif) {
r = 255; g = 255; b = 255; // Blanc : Failsafe (G29 muet)
r = 255; g = 255; b = 255; // Blanc : Failsafe
} else {
switch (rapportEngage) {
switch (rapportActuel()) {
case -1: r = 255; g = 0; b = 0; break; // Rouge : R
case 0: r = 255; g = 100; b = 0; break; // Orange : N
case 1: r = 0; g = 255; b = 255; break; // Cyan : 1ère
case 2: r = 0; g = 255; b = 0; break; // Vert : 2ème
case 3: r = 180; g = 0; b = 255; break; // Violet : 3ème
}
if (!estArme) { // Désarmé : couleur du rapport très atténuée
if (!estActuellementArme()) { // Désarmé : couleur du rapport très atténuée
r /= 10; g /= 10; b /= 10;
}
}
@@ -659,14 +816,26 @@ bool evaluerFailsafe() {
return true;
}
// 2. Déconnexion matérielle du volant G29 (câble USB arraché ou hors tension)
if (!volant_est_pret) {
if (!failsafeActif) {
failsafeActif = true;
majLedRequise = true;
Serial.println(F("!! [FAILSAFE] Volant G29 non detecte ou debranche !!"));
// 2. Surveillance de la source active (Steam Controller externe ou Volant G29)
if (sourceActive == SRC_EXT) {
if (!extRcActif || (now - dernierPaquetRC_ms > TIMEOUT_RC_EXT_MS)) {
if (!failsafeActif) {
failsafeActif = true;
majLedRequise = true;
Serial.println(F("!! [FAILSAFE] Steam Controller inactif ou deconnecte !!"));
}
return true;
}
} else {
// Déconnexion matérielle du volant G29 (câble USB arraché ou hors tension)
if (!volant_est_pret) {
if (!failsafeActif) {
failsafeActif = true;
majLedRequise = true;
Serial.println(F("!! [FAILSAFE] Volant G29 non detecte ou debranche !!"));
}
return true;
}
return true;
}
// Volant branché et Cœur 1 fonctionnel : liaison valide (pas de faux failsafe quand le volant est immobile)
@@ -727,7 +896,7 @@ void traiterTelemetrieCRSF() {
dernierPaquetTelemetrie_ms = millis();
uint8_t frameType = crsfRxBuffer[2];
if (!estArme) {
if (!estArme || sourceActive != SRC_G29) {
rugositeTerrainExterne = 0;
attitudeInitialisee = false;
} else if (frameType == 0x1E && paquetLongueurAttendue >= 8) {
@@ -789,7 +958,7 @@ void traiterTelemetrieCRSF() {
}
}
if (!estArme) {
if (!estArme || sourceActive != SRC_G29) {
rugositeTerrainExterne = 0;
attitudeInitialisee = false;
return;
@@ -853,18 +1022,26 @@ void gererSortieCockpit() {
bool modif = __atomic_exchange_n(&cockpitEtatModifie, false, __ATOMIC_ACQ_REL);
if (modif || (now - dernierEnvoiCockpit_ms >= INTERVALLE_COCKPIT_MS)) {
dernierEnvoiCockpit_ms = now;
int throt = (int)constrain(dernierAccelPct + 0.5f, 0.0f, 100.0f);
int brake = (int)constrain(dernierFreinPct + 0.5f, 0.0f, 100.0f);
char bufEtat[96];
bool armeOut = estActuellementArme();
int8_t rapportOut = rapportActuel();
int throt = (sourceActive == SRC_EXT)
? (int)extAccelPct
: (int)constrain(dernierAccelPct + 0.5f, 0.0f, 100.0f);
int brake = (sourceActive == SRC_EXT)
? (int)extFreinPct
: (int)constrain(dernierFreinPct + 0.5f, 0.0f, 100.0f);
const char* srcStr = (sourceActive == SRC_EXT) ? "EXT" : "G29";
char bufEtat[112];
snprintf(bufEtat, sizeof(bufEtat),
"$G29,ARM=%d,GEAR=%d,THROT=%d,BRAKE=%d,FFB=%d,VIB=%d,FAIL=%d",
estArme ? 1 : 0,
(int)rapportEngage,
"$G29,ARM=%d,GEAR=%d,THROT=%d,BRAKE=%d,FFB=%d,VIB=%d,FAIL=%d,SRC=%s",
armeOut ? 1 : 0,
(int)rapportOut,
throt,
brake,
(int)configSysteme.forceRessort,
(int)configSysteme.intensiteVibration,
failsafeActif ? 1 : 0);
failsafeActif ? 1 : 0,
srcStr);
emettreLigneCockpit(bufEtat);
}
}
@@ -878,6 +1055,19 @@ void gererTimeoutHeadTracking() {
}
}
void gererTimeoutRcExterne() {
if (sourceActive == SRC_EXT && extRcActif && (millis() - dernierPaquetRC_ms > TIMEOUT_RC_EXT_MS)) {
extRcActif = false;
extArme = false;
extAccelPct = 0;
extFreinPct = 0;
reinitialiserCanauxCRSF();
majLedRequise = true;
cockpitEtatModifie = true;
Serial.println(F("!! [FAILSAFE] Perte de liaison Steam Controller ($RC timeout) !!"));
}
}
void loop() {
// Watchdog dual-core : ne réarmer le watchdog matériel que si le Cœur 1 est également vivant
if (heartbeatCore1_ms == 0 || (millis() - heartbeatCore1_ms <= TIMEOUT_FAILSAFE_MS)) {
@@ -885,6 +1075,7 @@ void loop() {
}
verifierCommandesSerie();
gererTimeoutHeadTracking();
gererTimeoutRcExterne();
traiterTelemetrieCRSF();
gererSortieCockpit();
@@ -897,9 +1088,10 @@ void loop() {
majLedRequise = false;
dernierTickAnimNeo_ms = millis();
actualiserLED();
if (rapportEngage != dernierRapportLog) {
dernierRapportLog = rapportEngage;
Serial.printf("[BOITE] Rapport engage : %d\n", rapportEngage);
int8_t rap = rapportActuel();
if (rap != dernierRapportLog) {
dernierRapportLog = rap;
Serial.printf("[BOITE] Rapport engage : %d (%s)\n", rap, (sourceActive == SRC_EXT) ? "EXT" : "G29");
}
}
@@ -940,7 +1132,7 @@ void loop() {
}
// Sauvegarde différée suite à une commande série (D= / T=) passée pendant la conduite
if (!estArme && sauvegardeDifferee) {
if (!estActuellementArme() && sauvegardeDifferee) {
sauvegardeDifferee = false;
sauvegarderConfiguration();
}
@@ -949,7 +1141,7 @@ void loop() {
// (interdite en conduite armée pour éviter un gel Flash)
if (demandeSauvegardeEEPROM) {
demandeSauvegardeEEPROM = false;
if (estArme) {
if (estActuellementArme()) {
Serial.println(F("!! Sauvegarde Flash refusee pendant la conduite (desarmer d'abord) !!"));
} else {
momentDernierChangementDurete_ms = 0;
@@ -966,10 +1158,11 @@ void loop() {
uint32_t compteOK = compteurRapportsOK;
uint32_t rapportsParSec = ((compteOK - dernierCompteOK) * 1000UL) / (dt ? dt : 1);
dernierCompteOK = compteOK;
Serial.printf("[ETAT] G29_Pret=%d (PID=%04X) | InitFFB=%d/%d | Durete=%d/255 | Vib=%d%% | Rugosite=%d | Plage=%d deg | Rapport=%d | Arme=%d | Statut_LED=%d | USB=%lu rap/s | Rejetes=%lu (L=%d,ID=%02X) | Failsafe=%d\n",
volant_est_pret, g29_pid, etapeInitMoteur, ETAPES_INIT_FFB_TOTAL, configSysteme.forceRessort,
Serial.printf("[ETAT] SRC=%s | G29_Pret=%d (PID=%04X) | ExtRC=%d | InitFFB=%d/%d | Durete=%d/255 | Vib=%d%% | Rugosite=%d | Plage=%d deg | Rapport=%d | Arme=%d | Statut_LED=%d | USB=%lu rap/s | Rejetes=%lu (L=%d,ID=%02X) | Failsafe=%d\n",
(sourceActive == SRC_EXT) ? "EXT" : "G29",
volant_est_pret, g29_pid, extRcActif, etapeInitMoteur, ETAPES_INIT_FFB_TOTAL, configSysteme.forceRessort,
configSysteme.intensiteVibration, rugositeTerrainExterne, configSysteme.angleSouhaiteTotal,
rapportEngage, estArme, statutEnvoiLed,
rapportActuel(), estActuellementArme(), statutEnvoiLed,
(unsigned long)rapportsParSec, (unsigned long)compteurRapportsRejetes,
dernierRejetLen, dernierRejetId, failsafeActif);
}
@@ -1187,7 +1380,7 @@ void gererVibrationHaptique() {
// 2. Gestion des vibrations haptiques et retours mécaniques
uint8_t intensite = configSysteme.intensiteVibration;
if (!estArme || intensite == 0) {
if (sourceActive != SRC_G29 || !estArme || intensite == 0) {
dernierCalculPhase_us = 0;
directionDernierChocRapport = 0;
if (!forceEstAuNeutre) {
@@ -1321,8 +1514,8 @@ void loop1() {
}
}
// Arrêt prioritaire du moteur de vibration dès le désarmement (avant l'animation LED)
if (!estArme && !forceEstAuNeutre) {
// Arrêt prioritaire du moteur de vibration dès le désarmement (ou si source externe active)
if ((sourceActive != SRC_G29 || !estArme) && !forceEstAuNeutre) {
if (arreterForceG29()) {
forceEstAuNeutre = true;
return;
@@ -1360,12 +1553,6 @@ void reinitialiserEtatVolant() {
rugositeTerrainExterne = 0;
}
static inline void assignerCanalCRSF(uint8_t numeroCh, uint16_t valeur11bits) {
if (numeroCh >= 1 && numeroCh <= 16 && numeroCh != CANAL_ARM) {
crsf_channels[numeroCh - 1] = valeur11bits;
}
}
// =========================================================================
// CALLBACKS HID USB HOST (Exécutés sur Core 1)
// =========================================================================
@@ -1417,7 +1604,9 @@ void tuh_hid_umount_cb(uint8_t dev_addr, uint8_t instance) {
g29_vid = 0;
g29_pid = 0;
reinitialiserEtatVolant();
reinitialiserCanauxCRSF();
if (sourceActive == SRC_G29) {
reinitialiserCanauxCRSF();
}
majLedRequise = true;
}
@@ -1437,6 +1626,14 @@ void __not_in_flash_func(tuh_hid_report_received_cb)(uint8_t dev_addr, uint8_t i
{
compteurRapportsOK++;
// Si la source active est la manette externe (Steam Controller), on maintient la liaison USB
// mais on ignore les axes/boutons G29 pour éviter toute interférence.
if (sourceActive != SRC_G29) {
dernierRapportUSB_ms = millis();
tuh_hid_receive_report(dev_addr, instance);
return;
}
uint16_t volantRaw = (report[44] << 8) | report[43];
uint16_t accelRaw = 65535 - ((report[46] << 8) | report[45]);
uint16_t freinRaw = 65535 - ((report[48] << 8) | report[47]);
+20
View File
@@ -48,6 +48,26 @@ pub struct AppConfig {
#[arg(long, default_value_t = 14552)]
pub g29_udp_port: u16,
/// Source active de pilotage : "g29" (Volant Logitech G29) ou "steam" (Steam Controller via PC/Steam Frame)
#[arg(long, default_value = "g29")]
pub control_source: String,
/// Périphérique evdev explicite pour le Steam Controller (vide = détection automatique)
#[arg(long, default_value = "")]
pub controller_device: String,
/// Expo de direction du Steam Controller (0.0 = linéaire, 0.25 = doux au centre, max 0.8)
#[arg(long, default_value_t = 0.25)]
pub controller_expo: f32,
/// Zone morte du stick gauche du Steam Controller (0.0..0.45)
#[arg(long, default_value_t = 0.08)]
pub controller_deadzone: f32,
/// Inverser le sens de direction du Steam Controller
#[arg(long, default_value_t = false)]
pub controller_invert_steering: bool,
/// Codec vidéo reçu depuis le VRX OpenIPC / Ruby ("h264" ou "h265")
#[arg(long, default_value = "h264")]
pub codec: String,
+1140
View File
File diff suppressed because it is too large. Load diff
+160 -3
View File
@@ -1,4 +1,7 @@
use crate::config::AppConfig;
use crate::controller::{
ControlSource, SteamControllerConfig, SteamControllerState, SteamControllerWorker,
};
use crate::dome_projection::{DomeWarpLut, ProjectionMode};
use crate::dvr::{DvrContainer, DvrMode, DvrRecorder};
use crate::g29_bridge::{G29BridgeReceiver, G29State};
@@ -10,7 +13,7 @@ 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::atomic::{AtomicBool, AtomicU8, Ordering};
use std::sync::Arc;
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};
@@ -48,6 +51,8 @@ pub struct RuntimeMonitor {
pub nomad_wifi_status: SubsystemStatus,
pub telemetry_status: SubsystemStatus,
pub g29_status: SubsystemStatus,
pub controller_status: SubsystemStatus,
pub active_control_source: ControlSource,
pub dvr_status: SubsystemStatus,
pub dvr_recording: bool,
pub dvr_elapsed_secs: u64,
@@ -60,6 +65,7 @@ pub struct RuntimeMonitor {
pub latest_head_pose: HeadPoseSample,
pub latest_telemetry: TelemetryState,
pub latest_g29: G29State,
pub latest_controller: SteamControllerState,
pub preview_rgba: Vec<u8>,
pub preview_width: u32,
pub preview_height: u32,
@@ -77,6 +83,8 @@ impl Default for RuntimeMonitor {
nomad_wifi_status: SubsystemStatus::Stopped,
telemetry_status: SubsystemStatus::Disabled,
g29_status: SubsystemStatus::Disabled,
controller_status: SubsystemStatus::Disabled,
active_control_source: ControlSource::G29,
dvr_status: SubsystemStatus::Stopped,
dvr_recording: false,
dvr_elapsed_secs: 0,
@@ -89,6 +97,7 @@ impl Default for RuntimeMonitor {
latest_head_pose: HeadPoseSample::default(),
latest_telemetry: TelemetryState::default(),
latest_g29: G29State::default(),
latest_controller: SteamControllerState::default(),
preview_rgba: Vec::new(),
preview_width: 0,
preview_height: 0,
@@ -108,6 +117,8 @@ pub struct EngineControlHandle {
recenter_flag: Arc<AtomicBool>,
telemetry_enabled_flag: Arc<AtomicBool>,
head_tracking_enabled_flag: Arc<AtomicBool>,
control_source_flag: Arc<AtomicU8>,
monitor_ref: Arc<Mutex<RuntimeMonitor>>,
optical_params: Arc<Mutex<LiveOpticalParams>>,
dvr_toggle_cmd: Arc<Mutex<Option<bool>>>,
dvr_config: Arc<Mutex<DvrConfig>>,
@@ -191,6 +202,42 @@ impl EngineControlHandle {
*self.dvr_toggle_cmd.lock() = Some(next);
next
}
pub fn active_control_source(&self) -> ControlSource {
ControlSource::from_u8(self.control_source_flag.load(Ordering::Acquire))
}
/// Bascule la source de conduite (Volant G29 <-> Steam Controller).
/// Refusé par sécurité tant que le véhicule est armé.
pub fn set_control_source(&self, target: ControlSource) -> Result<(), String> {
let current = self.active_control_source();
if current == target {
return Ok(());
}
{
let mon = self.monitor_ref.lock();
let armed_now = match current {
ControlSource::G29 => mon.latest_g29.is_live() && mon.latest_g29.armed,
ControlSource::SteamController => mon.latest_controller.armed,
};
if armed_now {
let msg = format!(
"Bascule vers {} refusée : désarmez d'abord le véhicule !",
target.label()
);
log::warn!("[Contrôleur] {}", msg);
return Err(msg);
}
}
self.control_source_flag
.store(target.as_u8(), Ordering::Release);
self.monitor_ref.lock().active_control_source = target;
log::info!(
"[Action Utilisateur] Source de conduite basculée sur : {}",
target.label()
);
Ok(())
}
}
pub struct FpvEngineController {
@@ -204,6 +251,7 @@ pub struct FpvEngineController {
recenter_flag: Arc<AtomicBool>,
telemetry_enabled_flag: Arc<AtomicBool>,
head_tracking_enabled_flag: Arc<AtomicBool>,
control_source_flag: Arc<AtomicU8>,
worker_handle: Option<JoinHandle<()>>,
}
@@ -234,6 +282,7 @@ impl FpvEngineController {
recenter_flag: Arc::new(AtomicBool::new(false)),
telemetry_enabled_flag: Arc::new(AtomicBool::new(initial_telemetry_enabled)),
head_tracking_enabled_flag: Arc::new(AtomicBool::new(initial_head_tracking_enabled)),
control_source_flag: Arc::new(AtomicU8::new(ControlSource::G29.as_u8())),
worker_handle: None,
}
}
@@ -243,6 +292,8 @@ impl FpvEngineController {
recenter_flag: Arc::clone(&self.recenter_flag),
telemetry_enabled_flag: Arc::clone(&self.telemetry_enabled_flag),
head_tracking_enabled_flag: Arc::clone(&self.head_tracking_enabled_flag),
control_source_flag: Arc::clone(&self.control_source_flag),
monitor_ref: Arc::clone(&self.monitor),
optical_params: Arc::clone(&self.optical_params),
dvr_toggle_cmd: Arc::clone(&self.dvr_toggle_cmd),
dvr_config: Arc::clone(&self.dvr_config),
@@ -300,6 +351,9 @@ impl FpvEngineController {
.store(cfg.telemetry_enabled, Ordering::Relaxed);
self.head_tracking_enabled_flag
.store(cfg.head_tracking_enabled, Ordering::Relaxed);
let initial_src = ControlSource::from_str(&cfg.control_source);
self.control_source_flag
.store(initial_src.as_u8(), Ordering::Relaxed);
*self.optical_params.lock() = LiveOpticalParams {
camera_fov_deg: cfg.camera_fov_deg,
@@ -338,9 +392,12 @@ impl FpvEngineController {
} else {
SubsystemStatus::Disabled
};
mon.active_control_source = initial_src;
mon.controller_status = SubsystemStatus::Starting;
}
let control_for_g29 = self.control_handle();
let control_for_ctrl = self.control_handle();
let monitor_clone = Arc::clone(&self.monitor);
let optical_clone = Arc::clone(&self.optical_params);
let dvr_cmd_clone = Arc::clone(&self.dvr_toggle_cmd);
@@ -351,6 +408,7 @@ impl FpvEngineController {
let recenter_clone = Arc::clone(&self.recenter_flag);
let telem_flag_clone = Arc::clone(&self.telemetry_enabled_flag);
let ht_flag_clone = Arc::clone(&self.head_tracking_enabled_flag);
let control_source_clone = Arc::clone(&self.control_source_flag);
let handle = thread::Builder::new()
.name("fpv-engine-worker".into())
@@ -364,10 +422,12 @@ impl FpvEngineController {
dvr_rec_flag_clone,
head_trim_clone,
control_for_g29,
control_for_ctrl,
stop_clone,
recenter_clone,
telem_flag_clone,
ht_flag_clone,
control_source_clone,
);
})
.expect("Impossible de créer le thread fpv-engine-worker");
@@ -628,6 +688,53 @@ fn sync_g29_status(
st
}
fn sync_controller_status(
control_source_flag: &Arc<AtomicU8>,
ctrl_worker_opt: Option<&SteamControllerWorker>,
g29_snapshot: &G29State,
monitor: &Arc<Mutex<RuntimeMonitor>>,
) -> G29State {
let active_src = ControlSource::from_u8(control_source_flag.load(Ordering::Acquire));
let ctrl_state = ctrl_worker_opt
.map(|w| w.state().lock().clone())
.unwrap_or_default();
let status = match active_src {
ControlSource::SteamController => {
if ctrl_state.connected {
SubsystemStatus::Running(format!(
"{} ([{}], {})",
ctrl_state.device_name,
ctrl_state.gear_label(),
if ctrl_state.armed { "ARMED" } else { "SAFE" }
))
} else {
SubsystemStatus::Warning("Steam Controller non détecté".to_string())
}
}
ControlSource::G29 => {
if ctrl_state.connected {
SubsystemStatus::Stopped
} else {
SubsystemStatus::Disabled
}
}
};
{
let mut mon = monitor.lock();
mon.active_control_source = active_src;
mon.controller_status = status;
mon.latest_controller = ctrl_state.clone();
}
if active_src == ControlSource::SteamController {
ctrl_state.to_hud_g29_state(g29_snapshot.is_live() && g29_snapshot.failsafe)
} else {
g29_snapshot.clone()
}
}
#[allow(clippy::too_many_arguments)]
fn run_engine_worker(
cfg: AppConfig,
@@ -638,10 +745,12 @@ fn run_engine_worker(
dvr_rec_flag: Arc<AtomicBool>,
head_trim_deg: Arc<Mutex<(f32, f32)>>,
control_for_g29: EngineControlHandle,
control_for_ctrl: EngineControlHandle,
stop_flag: Arc<AtomicBool>,
recenter_flag: Arc<AtomicBool>,
telem_enabled_flag: Arc<AtomicBool>,
ht_enabled_flag: Arc<AtomicBool>,
control_source_flag: Arc<AtomicU8>,
) {
let mut active_dvr: Option<Arc<DvrRecorder>> = None;
log::info!(
@@ -715,6 +824,34 @@ fn run_engine_worker(
None
};
// 3c. Démarrage du gestionnaire Steam Controller (evdev -> $SRC / $RC sur le même pont UDP)
let ctrl_cfg = SteamControllerConfig {
device_override: if cfg.controller_device.trim().is_empty() {
None
} else {
Some(cfg.controller_device.clone())
},
steering_deadzone: cfg.controller_deadzone,
steering_expo: cfg.controller_expo,
trigger_deadzone: 0.05,
invert_steering: cfg.controller_invert_steering,
};
let ctrl_worker_opt = match SteamControllerWorker::start(
&cfg.nomad_ip,
cfg.nomad_port,
ctrl_cfg,
Arc::clone(&control_source_flag),
control_for_ctrl,
g29_rx_opt.as_ref().map(|rx| rx.state()),
) {
Ok(worker) => Some(worker),
Err(e) => {
log::error!("[Steam Controller] Erreur démarrage worker : {}", e);
monitor.lock().controller_status = SubsystemStatus::Error(format!("{}", e));
None
}
};
// 4. Tentative d'initialisation OpenXR sur le Steam Frame (sauf si mode VR désactivé / headless)
let fallback_needed = if cfg.headless {
log::info!("[OpenXR] Mode VR désactivé (Mode Bureau léger actif).");
@@ -734,11 +871,13 @@ fn run_engine_worker(
&recenter_flag,
&telem_enabled_flag,
&ht_enabled_flag,
&control_source_flag,
video_rx_opt.as_ref(),
&mut telem_rx_opt,
&shared_telem_state,
&mut head_tracker_opt,
g29_rx_opt.as_ref(),
ctrl_worker_opt.as_ref(),
);
if !stop_flag.load(Ordering::Acquire) {
@@ -779,11 +918,13 @@ fn run_engine_worker(
&recenter_flag,
&telem_enabled_flag,
&ht_enabled_flag,
&control_source_flag,
video_rx_opt.as_ref(),
&mut telem_rx_opt,
&shared_telem_state,
&mut head_tracker_opt,
g29_rx_opt.as_ref(),
ctrl_worker_opt.as_ref(),
);
}
@@ -811,11 +952,13 @@ fn try_run_openxr_session(
recenter_flag: &Arc<AtomicBool>,
telem_enabled_flag: &Arc<AtomicBool>,
ht_enabled_flag: &Arc<AtomicBool>,
control_source_flag: &Arc<AtomicU8>,
video_rx_opt: Option<&UsbVideoReceiver>,
telem_rx_opt: &mut RetrySlot<TelemetryReceiver>,
shared_telem_state: &Arc<Mutex<TelemetryState>>,
head_tracker_opt: &mut RetrySlot<NomadHeadTracker>,
g29_rx_opt: Option<&G29BridgeReceiver>,
ctrl_worker_opt: Option<&SteamControllerWorker>,
) -> Result<()> {
let entry = unsafe {
xr::Entry::load().context("libopenxr_loader.so introuvable sur ce système (normal sur PC sans SteamVR)")?
@@ -1148,6 +1291,12 @@ fn try_run_openxr_session(
dvr_rec_flag.store(active_dvr.is_some(), Ordering::Release);
let g29_snapshot = sync_g29_status(cfg, g29_rx_opt, monitor);
let hud_ctrl_snapshot = sync_controller_status(
control_source_flag,
ctrl_worker_opt,
&g29_snapshot,
monitor,
);
let mut telem_snapshot = telem_rx_opt
.inner
@@ -1172,7 +1321,7 @@ fn try_run_openxr_session(
cfg.video_width,
cfg.video_height,
&telem_snapshot,
&g29_snapshot,
&hud_ctrl_snapshot,
current_pose.pan_deg,
current_pose.tilt_deg,
current_pose.roll_deg,
@@ -1341,11 +1490,13 @@ fn run_desktop_fallback_loop(
recenter_flag: &Arc<AtomicBool>,
telem_enabled_flag: &Arc<AtomicBool>,
ht_enabled_flag: &Arc<AtomicBool>,
control_source_flag: &Arc<AtomicU8>,
video_rx_opt: Option<&UsbVideoReceiver>,
telem_rx_opt: &mut RetrySlot<TelemetryReceiver>,
shared_telem_state: &Arc<Mutex<TelemetryState>>,
head_tracker_opt: &mut RetrySlot<NomadHeadTracker>,
g29_rx_opt: Option<&G29BridgeReceiver>,
ctrl_worker_opt: Option<&SteamControllerWorker>,
) {
let mut dome_lut = DomeWarpLut::new(
cfg.video_width,
@@ -1469,6 +1620,12 @@ fn run_desktop_fallback_loop(
dvr_rec_flag.store(active_dvr.is_some(), Ordering::Release);
let g29_snapshot = sync_g29_status(cfg, g29_rx_opt, monitor);
let hud_ctrl_snapshot = sync_controller_status(
control_source_flag,
ctrl_worker_opt,
&g29_snapshot,
monitor,
);
let mut telem_snapshot = telem_rx_opt
.inner
@@ -1493,7 +1650,7 @@ fn run_desktop_fallback_loop(
cfg.video_width,
cfg.video_height,
&telem_snapshot,
&g29_snapshot,
&hud_ctrl_snapshot,
current_pose.pan_deg,
current_pose.tilt_deg,
current_pose.roll_deg,
+8 -1
View File
@@ -1,3 +1,4 @@
use crate::controller::ControlSource;
use crate::engine::EngineControlHandle;
use crate::telemetry_osd::{TelemetryReceiver, TelemetryState};
use anyhow::Result;
@@ -23,6 +24,7 @@ pub struct G29State {
pub ffb_raw: u8,
pub ffb_pct: u8,
pub vib_pct: u8,
pub remote_source: ControlSource,
pub packets_received: u64,
pub last_packet: Option<Instant>,
pub toast_text: String,
@@ -41,6 +43,7 @@ impl Default for G29State {
ffb_raw: 140,
ffb_pct: 55,
vib_pct: 50,
remote_source: ControlSource::G29,
packets_received: 0,
last_packet: None,
toast_text: String::new(),
@@ -292,6 +295,9 @@ impl G29BridgeReceiver {
st.failsafe = val != 0;
}
}
"SRC" => {
st.remote_source = ControlSource::from_str(v);
}
_ => {}
}
}
@@ -437,7 +443,7 @@ mod tests {
}
G29BridgeReceiver::process_line(
"$G29,ARM=1,GEAR=-1,THROT=0,BRAKE=80,FFB=200,VIB=50,FAIL=0",
"$G29,ARM=1,GEAR=-1,THROT=0,BRAKE=80,FFB=200,VIB=50,FAIL=0,SRC=EXT",
&state,
None,
None,
@@ -446,6 +452,7 @@ mod tests {
let st = state.lock();
assert_eq!(st.gear_label(), "R");
assert_eq!(st.brake_pct, 80);
assert_eq!(st.remote_source, ControlSource::SteamController);
assert_eq!(st.active_toast(), Some("FFB 78%"));
}
}
+120
View File
@@ -1,4 +1,5 @@
use crate::config::AppConfig;
use crate::controller::ControlSource;
use crate::dome_projection::ProjectionMode;
use crate::dvr::{DvrContainer, DvrMode};
use crate::engine::{EngineControlHandle, FpvEngineController, LiveOpticalParams, RuntimeMonitor, SubsystemStatus};
@@ -24,6 +25,7 @@ pub struct SteamFrameGuiApp {
auto_scroll_logs: bool,
video_texture: Option<TextureHandle>,
last_displayed_frame_seq: u64,
control_switch_error: String,
}
impl SteamFrameGuiApp {
@@ -51,6 +53,7 @@ impl SteamFrameGuiApp {
auto_scroll_logs: true,
video_texture: None,
last_displayed_frame_seq: 0,
control_switch_error: String::new(),
}
}
@@ -283,6 +286,10 @@ impl eframe::App for SteamFrameGuiApp {
xr_status,
nomad_status,
telem_status,
g29_status,
controller_status,
active_ctrl_source,
latest_ctrl,
dvr_status,
dvr_recording,
dvr_secs,
@@ -318,6 +325,10 @@ impl eframe::App for SteamFrameGuiApp {
mon.openxr_status.clone(),
mon.nomad_wifi_status.clone(),
mon.telemetry_status.clone(),
mon.g29_status.clone(),
mon.controller_status.clone(),
mon.active_control_source,
mon.latest_controller.clone(),
mon.dvr_status.clone(),
mon.dvr_recording,
mon.dvr_elapsed_secs,
@@ -488,6 +499,11 @@ impl eframe::App for SteamFrameGuiApp {
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);
if active_ctrl_source == ControlSource::SteamController {
Self::status_badge(ui, "Steam Controller", &controller_status);
} else {
Self::status_badge(ui, "Volant G29", &g29_status);
}
Self::status_badge(ui, "Télémétrie OSD", &telem_status);
Self::status_badge(ui, "DVR Vidéo", &dvr_status);
});
@@ -854,6 +870,11 @@ impl eframe::App for SteamFrameGuiApp {
egui::ComboBox::from_id_salt("ht_proto_combo")
.selected_text(NomadProtocol::from_str(&self.cfg.ht_protocol).label())
.show_ui(ui, |ui| {
ui.selectable_value(
&mut self.cfg.ht_protocol,
"g29".to_string(),
"G29 Hub unifié ($HT - UDP 14552)",
);
ui.selectable_value(
&mut self.cfg.ht_protocol,
"msp".to_string(),
@@ -902,6 +923,105 @@ impl eframe::App for SteamFrameGuiApp {
ui.add_space(8.0);
// --- Section 2b : Contrôleur de Conduite (Volant G29 / Steam Controller) ---
egui::CollapsingHeader::new(
RichText::new("🎮 2b. Contrôleur de Conduite (Volant G29 / Steam Controller)")
.strong(),
)
.default_open(true)
.show(ui, |ui| {
ui.horizontal(|ui| {
ui.label(RichText::new("Source active :").strong());
if ui
.selectable_label(
active_ctrl_source == ControlSource::G29,
"🏎️ Volant G29",
)
.clicked()
{
match self.controls.set_control_source(ControlSource::G29) {
Ok(()) => {
self.cfg.control_source = "g29".to_string();
self.control_switch_error.clear();
}
Err(msg) => self.control_switch_error = msg,
}
}
if ui
.selectable_label(
active_ctrl_source == ControlSource::SteamController,
"🎮 Steam Controller",
)
.clicked()
{
match self
.controls
.set_control_source(ControlSource::SteamController)
{
Ok(()) => {
self.cfg.control_source = "steam".to_string();
self.control_switch_error.clear();
}
Err(msg) => self.control_switch_error = msg,
}
}
});
if !self.control_switch_error.is_empty() {
ui.colored_label(
Color32::from_rgb(255, 85, 85),
format!("⚠ {}", self.control_switch_error),
);
}
ui.add_space(4.0);
if latest_ctrl.connected {
ui.colored_label(
Color32::from_rgb(80, 235, 130),
format!(
"● {} ({}) — [{}] {} | Gaz {}% | Frn {}% | Dir {:+.0}%",
latest_ctrl.device_name,
latest_ctrl.device_path,
latest_ctrl.gear_label(),
if latest_ctrl.armed { "ARMED" } else { "SAFE" },
latest_ctrl.throttle_pct,
latest_ctrl.brake_pct,
latest_ctrl.steering_norm * 100.0
),
);
} else {
ui.colored_label(
Color32::GRAY,
"○ Steam Controller non détecté (dongle / USB)",
);
}
ui.add_space(4.0);
egui::Grid::new("ctrl_cfg_grid")
.num_columns(2)
.spacing([8.0, 6.0])
.show(ui, |ui| {
ui.label("Expo direction SC :");
ui.add(egui::Slider::new(&mut self.cfg.controller_expo, 0.0..=0.8));
ui.end_row();
ui.label("Zone morte stick :");
ui.add(egui::Slider::new(
&mut self.cfg.controller_deadzone,
0.0..=0.4,
));
ui.end_row();
ui.label("Inverser direction :");
ui.checkbox(&mut self.cfg.controller_invert_steering, "Inversée");
ui.end_row();
});
ui.small("Stick G: Dir | R2: Gaz | L2: Frein | RB/LB ou R4/L4: Boîte R/N/1/2/3 | Menu: Armer (au N)");
});
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)")
+263 -25
View File
@@ -1,4 +1,5 @@
use crate::config::AppConfig;
use crate::controller::{ControlSource, SteamControllerState};
use crate::dome_projection::ProjectionMode;
use crate::dvr::{DvrContainer, DvrMode};
use crate::engine::{
@@ -70,6 +71,8 @@ pub struct SteamFrameGpuiApp {
nomad_status: SubsystemStatus,
telem_status: SubsystemStatus,
g29_status: SubsystemStatus,
controller_status: SubsystemStatus,
active_control_source: ControlSource,
dvr_status: SubsystemStatus,
dvr_recording: bool,
dvr_elapsed_secs: u64,
@@ -81,6 +84,8 @@ pub struct SteamFrameGpuiApp {
latest_pose: HeadPoseSample,
latest_telem: TelemetryState,
latest_g29: G29State,
latest_controller: SteamControllerState,
control_switch_error: String,
log_entries: Vec<LogEntry>,
log_err_count: usize,
log_warn_count: usize,
@@ -111,6 +116,7 @@ impl SteamFrameGpuiApp {
) -> Self {
let log_revision = log_buffer.lock().revision.clone();
let target_port_buf = cfg.nomad_port.to_string();
let initial_control_source = ControlSource::from_str(&cfg.control_source);
Self {
cfg,
@@ -130,6 +136,8 @@ impl SteamFrameGpuiApp {
nomad_status: SubsystemStatus::Disabled,
telem_status: SubsystemStatus::Disabled,
g29_status: SubsystemStatus::Disabled,
controller_status: SubsystemStatus::Disabled,
active_control_source: initial_control_source,
dvr_status: SubsystemStatus::Stopped,
dvr_recording: false,
dvr_elapsed_secs: 0,
@@ -141,6 +149,8 @@ impl SteamFrameGpuiApp {
latest_pose: HeadPoseSample::default(),
latest_telem: TelemetryState::default(),
latest_g29: G29State::default(),
latest_controller: SteamControllerState::default(),
control_switch_error: String::new(),
log_entries: Vec::new(),
log_err_count: 0,
log_warn_count: 0,
@@ -188,6 +198,14 @@ impl SteamFrameGpuiApp {
self.g29_status = mon.g29_status.clone();
changed = true;
}
if self.controller_status != mon.controller_status {
self.controller_status = mon.controller_status.clone();
changed = true;
}
if self.active_control_source != mon.active_control_source {
self.active_control_source = mon.active_control_source;
changed = true;
}
if self.dvr_recording != mon.dvr_recording
|| self.dvr_elapsed_secs != mon.dvr_elapsed_secs
|| self.dvr_status != mon.dvr_status
@@ -217,6 +235,18 @@ impl SteamFrameGpuiApp {
}
self.latest_g29 = mon.latest_g29.clone();
if self.latest_controller.connected != mon.latest_controller.connected
|| self.latest_controller.armed != mon.latest_controller.armed
|| self.latest_controller.gear != mon.latest_controller.gear
|| self.latest_controller.throttle_pct != mon.latest_controller.throttle_pct
|| self.latest_controller.brake_pct != mon.latest_controller.brake_pct
|| (self.latest_controller.steering_norm - mon.latest_controller.steering_norm).abs()
> 0.02
{
changed = true;
}
self.latest_controller = mon.latest_controller.clone();
// Ne cloner et décoder la trame QUE si l'onglet Cockpit est actif !
let frame_data: Option<(u32, u32, Vec<u8>)> = if self.active_tab == ActiveTab::Cockpit
&& mon.preview_frame_seq != self.last_frame_seq
@@ -667,6 +697,44 @@ impl SteamFrameGpuiApp {
.flex()
.items_center()
.gap_2()
.child(
div()
.id("toggle_ctrl_source_quick")
.px_2()
.py_0p5()
.bg(if self.active_control_source == ControlSource::SteamController {
rgb(0x132738)
} else {
rgb(COLOR_SURFACE_ELEVATED)
})
.border_1()
.border_color(if self.active_control_source == ControlSource::SteamController {
rgb(COLOR_CYAN)
} else {
rgb(COLOR_ORANGE)
})
.rounded_md()
.text_xs()
.font_weight(gpui::FontWeight::SEMIBOLD)
.text_color(if self.active_control_source == ControlSource::SteamController {
rgb(COLOR_CYAN)
} else {
rgb(COLOR_ORANGE)
})
.cursor_pointer()
.on_click(cx.listener(|this, _, _, cx| {
let next = match this.active_control_source {
ControlSource::G29 => ControlSource::SteamController,
ControlSource::SteamController => ControlSource::G29,
};
this.switch_control_source(next);
cx.notify();
}))
.child(match self.active_control_source {
ControlSource::G29 => "🏎️ G29",
ControlSource::SteamController => "🎮 Steam",
}),
)
.child(
div()
.id("toggle_vr_quick")
@@ -765,6 +833,19 @@ impl SteamFrameGpuiApp {
)
}
fn switch_control_source(&mut self, target: ControlSource) {
match self.controls.set_control_source(target) {
Ok(()) => {
self.active_control_source = target;
self.cfg.control_source = target.as_str().to_string();
self.control_switch_error.clear();
}
Err(msg) => {
self.control_switch_error = msg;
}
}
}
fn render_nav_tab(&self, label: &str, tab: ActiveTab, cx: &mut Context<Self>) -> impl IntoElement {
let is_active = self.active_tab == tab;
let tab_id = match tab {
@@ -1542,6 +1623,131 @@ impl SteamFrameGpuiApp {
),
),
))
// 3.2b Carte Contrôleur de Conduite (Volant G29 / Steam Controller)
.child(self.render_settings_card(
"🎮 2b. Contrôleur de Conduite (Volant G29 / Steam Controller)",
COLOR_GREEN,
div()
.flex()
.flex_col()
.gap_3()
.child(self.render_setting_row(
"Source Active (bascule à chaud)",
div()
.flex()
.flex_wrap()
.gap_2()
.child(self.render_selectable_pill(
"pill_ctrl_g29",
"🏎️ Volant Logitech G29",
self.active_control_source == ControlSource::G29,
cx.listener(|this, _, _, cx| {
this.switch_control_source(ControlSource::G29);
cx.notify();
}),
))
.child(self.render_selectable_pill(
"pill_ctrl_steam",
"🎮 Steam Controller (Boîte séq.)",
self.active_control_source == ControlSource::SteamController,
cx.listener(|this, _, _, cx| {
this.switch_control_source(
ControlSource::SteamController,
);
cx.notify();
}),
)),
))
.when(!self.control_switch_error.is_empty(), |d| {
d.child(
div()
.px_2p5()
.py_1()
.rounded_md()
.bg(rgb(0x2a1215))
.border_1()
.border_color(rgb(COLOR_RED))
.text_xs()
.text_color(rgb(COLOR_RED))
.child(format!("⚠️ {}", self.control_switch_error)),
)
})
.child(self.render_setting_row(
"État Steam Controller",
div()
.text_xs()
.text_color(if self.latest_controller.connected {
rgb(COLOR_GREEN)
} else {
rgb(COLOR_TEXT_MUTED)
})
.child(if self.latest_controller.connected {
format!(
"● {} ({}) — [{}] {} • Gaz {}% • Frn {}% • Dir {:+.0}%",
self.latest_controller.device_name,
self.latest_controller.device_path,
self.latest_controller.gear_label(),
if self.latest_controller.armed {
"ARMED"
} else {
"SAFE"
},
self.latest_controller.throttle_pct,
self.latest_controller.brake_pct,
self.latest_controller.steering_norm * 100.0
)
} else {
"○ Non détecté (branchez le dongle ou allumez la manette)"
.to_string()
}),
))
.child(self.render_setting_row(
"Sens Direction Steam Controller",
div()
.flex()
.items_center()
.gap_2()
.child(self.render_selectable_pill(
"pill_sc_steer_normal",
"Normal (identique G29)",
!self.cfg.controller_invert_steering,
cx.listener(|this, _, _, cx| {
this.cfg.controller_invert_steering = false;
cx.notify();
}),
))
.child(self.render_selectable_pill(
"pill_sc_steer_inv",
"Inversée",
self.cfg.controller_invert_steering,
cx.listener(|this, _, _, cx| {
this.cfg.controller_invert_steering = true;
cx.notify();
}),
))
.child(
div()
.text_xs()
.text_color(rgb(COLOR_TEXT_MUTED))
.child(format!(
"(Expo {:.2} • Deadzone {:.2})",
self.cfg.controller_expo,
self.cfg.controller_deadzone
)),
),
))
.child(
div()
.p_2()
.rounded_md()
.bg(rgb(COLOR_BG_DARK))
.border_1()
.border_color(rgb(COLOR_BORDER_SUBTLE))
.text_xs()
.text_color(rgb(COLOR_TEXT_MUTED))
.child("Stick G : Direction | R2 : Gaz | L2 : Frein | RB/LB ou R4/L4 : Boîte R-N-1-2-3 | Menu : Armer (au N) | A : Tare | B : DVR | Y : OSD | X : Proj VR | D-Pad : Trim"),
),
))
// 3.3 Carte Projection VR Steam Frame & Optique
.child(self.render_settings_card(
"🥽 3. Projection VR & Correction Optique 140°",
@@ -2072,31 +2278,63 @@ impl SteamFrameGpuiApp {
&format!("Cap : {:.0}°", self.latest_telem.drone_heading_deg),
COLOR_CYAN,
))
.child(self.render_stat_box(
"🎮 VOLANT G29",
&if !self.latest_g29.is_live() {
"HORS LIGNE".to_string()
} else {
format!(
"[{}] {}",
self.latest_g29.gear_label(),
if self.latest_g29.armed { "ARMED" } else { "SAFE" }
)
},
&format!(
"Gaz {}% | Frn {}% | FFB {}%",
self.latest_g29.throttle_pct,
self.latest_g29.brake_pct,
self.latest_g29.ffb_pct
),
if !self.latest_g29.is_live() {
COLOR_TEXT_MUTED
} else if self.latest_g29.armed {
COLOR_GREEN
} else {
COLOR_ORANGE
},
)),
.child(if self.active_control_source == ControlSource::SteamController {
self.render_stat_box(
"🎮 STEAM CONTROLLER",
&if !self.latest_controller.connected {
"NON DÉTECTÉ".to_string()
} else {
format!(
"[{}] {}",
self.latest_controller.gear_label(),
if self.latest_controller.armed {
"ARMED"
} else {
"SAFE"
}
)
},
&format!(
"Gaz {}% | Frn {}% | Dir {:+.0}%",
self.latest_controller.throttle_pct,
self.latest_controller.brake_pct,
self.latest_controller.steering_norm * 100.0
),
if !self.latest_controller.connected {
COLOR_TEXT_MUTED
} else if self.latest_controller.armed {
COLOR_GREEN
} else {
COLOR_ORANGE
},
)
} else {
self.render_stat_box(
"🏎️ VOLANT G29",
&if !self.latest_g29.is_live() {
"HORS LIGNE".to_string()
} else {
format!(
"[{}] {}",
self.latest_g29.gear_label(),
if self.latest_g29.armed { "ARMED" } else { "SAFE" }
)
},
&format!(
"Gaz {}% | Frn {}% | FFB {}%",
self.latest_g29.throttle_pct,
self.latest_g29.brake_pct,
self.latest_g29.ffb_pct
),
if !self.latest_g29.is_live() {
COLOR_TEXT_MUTED
} else if self.latest_g29.armed {
COLOR_GREEN
} else {
COLOR_ORANGE
},
)
}),
)
// Double Panneau : Suivi de Tête & Radio
.child(
+1
View File
@@ -1,4 +1,5 @@
mod config;
mod controller;
mod dome_projection;
mod dvr;
mod engine;
+14 -3
View File
@@ -1,3 +1,4 @@
use crate::controller::ControlSource;
use crate::g29_bridge::G29State;
use anyhow::Result;
use parking_lot::Mutex;
@@ -516,12 +517,22 @@ impl OsdOverlay {
let _ = write!(gear_buf, "[{}]", g29.gear_label());
Self::draw_text(rgba, width, height, 32, gear_y, gear_buf.as_str(), scale, gear_color);
let is_steam = g29.remote_source == ControlSource::SteamController;
let (arm_lbl, arm_color) = if !g29.is_live() || g29.failsafe {
("G29 FAIL", [255, 65, 65, 255])
(
if is_steam { "SC FAIL" } else { "G29 FAIL" },
[255, 65, 65, 255],
)
} else if g29.armed {
("ARMED", [90, 255, 120, 255])
(
if is_steam { "SC ARMED" } else { "ARMED" },
[90, 255, 120, 255],
)
} else {
("SAFE", [255, 180, 50, 255])
(
if is_steam { "SC SAFE" } else { "SAFE" },
[255, 180, 50, 255],
)
};
let arm_x = 32 + (4 * 6 * scale as i32);
Self::draw_text(rgba, width, height, arm_x, gear_y, arm_lbl, scale, arm_color);