diff --git a/README.md b/README.md index 8ad1d5e..349f095 100644 --- a/README.md +++ b/README.md @@ -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,` 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 | diff --git a/firmware/g29_crsf/README.md b/firmware/g29_crsf/README.md index d094303..5d3b301 100644 --- a/firmware/g29_crsf/README.md +++ b/firmware/g29_crsf/README.md @@ -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,,,` (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,`) 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,,,,,,` | Injecte la conduite externe (`CH1..CH5`, valeurs CRSF `172..1811`, watchdog `400 ms`) en mode `EXT` | | `$HT,,,` | 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é) | diff --git a/firmware/g29_crsf/g29_crsf.ino b/firmware/g29_crsf/g29_crsf.ino index 23419f3..7a99aab 100644 --- a/firmware/g29_crsf/g29_crsf.ino +++ b/firmware/g29_crsf/g29_crsf.ino @@ -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,,,,,, + 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]); diff --git a/src/config.rs b/src/config.rs index be2acdf..13eaf94 100644 --- a/src/config.rs +++ b/src/config.rs @@ -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, diff --git a/src/controller.rs b/src/controller.rs new file mode 100644 index 0000000..4b526d6 --- /dev/null +++ b/src/controller.rs @@ -0,0 +1,1140 @@ +use crate::engine::EngineControlHandle; +use crate::g29_bridge::G29State; +use crate::nomad_elrs::{CRSF_CHANNEL_MAX, CRSF_CHANNEL_MID, CRSF_CHANNEL_MIN}; +use anyhow::{anyhow, Result}; +use parking_lot::Mutex; +use std::fs::{self, File, OpenOptions}; +use std::io::{ErrorKind, Read}; +use std::net::{SocketAddr, ToSocketAddrs, UdpSocket}; +use std::os::unix::fs::OpenOptionsExt; +use std::os::unix::io::AsRawFd; +use std::sync::atomic::{AtomicBool, AtomicU8, Ordering}; +use std::sync::Arc; +use std::thread; +use std::time::{Duration, Instant}; + +// ========================================================================= +// CONSTANTES EVDEV LINUX (identiques sur x86_64 et aarch64) +// ========================================================================= +const EV_KEY: u16 = 0x01; +const EV_ABS: u16 = 0x03; + +const ABS_X: u16 = 0x00; +const ABS_Z: u16 = 0x02; +const ABS_RZ: u16 = 0x05; +const ABS_HAT2X: u16 = 0x14; // 20 : Gâchette droite (R2) sur hid-steam (Steam Controller / Deck) +const ABS_HAT2Y: u16 = 0x15; // 21 : Gâchette gauche (L2) sur hid-steam (Steam Controller / Deck) + +const BTN_SOUTH: u16 = 304; // A +const BTN_EAST: u16 = 305; // B +const BTN_NORTH: u16 = 307; // Y +const BTN_WEST: u16 = 308; // X +const BTN_TL: u16 = 310; // LB (Rétrograder) +const BTN_TR: u16 = 311; // RB (Monter un rapport) +const BTN_SELECT: u16 = 314; // View / Back +const BTN_START: u16 = 315; // Menu / Start (Armement / Désarmement) +const BTN_MODE: u16 = 316; // Bouton Steam +const BTN_THUMBR: u16 = 318; // R3 +const BTN_DPAD_UP: u16 = 544; +const BTN_DPAD_DOWN: u16 = 545; +const BTN_DPAD_LEFT: u16 = 546; +const BTN_DPAD_RIGHT: u16 = 547; +const BTN_GRIPL: u16 = 548; // Palette arrière gauche L4 (Rétrograder) +const BTN_GRIPR: u16 = 549; // Palette arrière droite R4 (Monter un rapport) +const BTN_GRIPL2: u16 = 550; // Palette arrière basse gauche L5 (Embrayage) + +const INPUT_PROP_ACCELEROMETER: usize = 6; +const VALVE_VENDOR_ID: u16 = 0x28de; +const O_NONBLOCK_FLAG: i32 = 0x800; // O_NONBLOCK sur Linux x86_64 et aarch64 + +// Plages de gaz progressives identiques au firmware RP2350 (g29_crsf.ino) +const GAZ_AVANT_MIN: u16 = 1065; +const GAZ_AVANT_MAX_PAR_VITESSE: [u16; 3] = [ + 1100, // 1ère vitesse (Manœuvre) + 1150, // 2ème vitesse (Normale) + 1220, // 3ème vitesse (Rapide) +]; +const GAZ_ARRIERE_MIN: u16 = 905; +const GAZ_ARRIERE_MAX: u16 = 850; + +const TOAST_DURATION_MS: u64 = 1500; +const RC_SEND_INTERVAL_MS: u64 = 10; // 100 Hz vers RP2350 +const SRC_RESYNC_INTERVAL_MS: u64 = 500; +const DEVICE_RESCAN_INTERVAL_MS: u64 = 1000; + +extern "C" { + fn ioctl(fd: std::ffi::c_int, request: std::ffi::c_ulong, ...) -> std::ffi::c_int; +} + +#[repr(C)] +#[derive(Clone, Copy, Default)] +struct LinuxInputEvent { + tv_sec: std::ffi::c_long, + tv_usec: std::ffi::c_long, + ev_type: u16, + code: u16, + value: i32, +} + +#[repr(C)] +#[derive(Clone, Copy, Default, Debug)] +struct LinuxInputAbsInfo { + value: i32, + minimum: i32, + maximum: i32, + fuzz: i32, + flat: i32, + resolution: i32, +} + +fn eviocgabs(abs_code: u16) -> std::ffi::c_ulong { + // _IOR('E', 0x40 + abs_code, struct input_absinfo) = 0x8018_4540 + abs_code + (0x8018_4540u64 + abs_code as u64) as std::ffi::c_ulong +} + +// ========================================================================= +// TYPES PUBLICS : SOURCE DE CONTRÔLE & ÉTAT STEAM CONTROLLER +// ========================================================================= + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u8)] +pub enum ControlSource { + G29 = 0, + SteamController = 1, +} + +impl Default for ControlSource { + fn default() -> Self { + Self::G29 + } +} + +impl ControlSource { + pub fn from_str(s: &str) -> Self { + let lower = s.trim().to_ascii_lowercase(); + if lower == "steam" + || lower == "steam_controller" + || lower == "steam-controller" + || lower == "controller" + || lower == "gamepad" + || lower == "ext" + { + Self::SteamController + } else { + Self::G29 + } + } + + pub fn from_u8(v: u8) -> Self { + match v { + 1 => Self::SteamController, + _ => Self::G29, + } + } + + pub fn as_u8(self) -> u8 { + self as u8 + } + + pub fn as_str(self) -> &'static str { + match self { + Self::G29 => "g29", + Self::SteamController => "steam", + } + } + + pub fn wire_tag(self) -> &'static str { + match self { + Self::G29 => "G29", + Self::SteamController => "EXT", + } + } + + pub fn label(self) -> &'static str { + match self { + Self::G29 => "Volant G29", + Self::SteamController => "Steam Controller", + } + } +} + +#[derive(Debug, Clone)] +pub struct SteamControllerConfig { + pub device_override: Option, + pub steering_deadzone: f32, + pub steering_expo: f32, + pub trigger_deadzone: f32, + pub invert_steering: bool, +} + +impl Default for SteamControllerConfig { + fn default() -> Self { + Self { + device_override: None, + steering_deadzone: 0.08, + steering_expo: 0.25, + trigger_deadzone: 0.05, + invert_steering: false, + } + } +} + +#[allow(dead_code)] +#[derive(Debug, Clone)] +pub struct SteamControllerState { + pub connected: bool, + pub device_name: String, + pub device_path: String, + pub armed: bool, + pub gear: i8, + pub steering_norm: f32, + pub throttle_pct: u8, + pub brake_pct: u8, + pub clutch_pct: u8, + pub steer_crsf: u16, + pub throttle_crsf: u16, + pub brake_crsf: u16, + pub clutch_crsf: u16, + pub packets_sent: u64, + pub send_errors: u64, + pub toast_text: String, + pub toast_until: Option, +} + +impl Default for SteamControllerState { + fn default() -> Self { + Self { + connected: false, + device_name: String::new(), + device_path: String::new(), + armed: false, + gear: 0, + steering_norm: 0.0, + throttle_pct: 0, + brake_pct: 0, + clutch_pct: 0, + steer_crsf: CRSF_CHANNEL_MID, + throttle_crsf: CRSF_CHANNEL_MID, + brake_crsf: CRSF_CHANNEL_MID, + clutch_crsf: CRSF_CHANNEL_MID, + packets_sent: 0, + send_errors: 0, + toast_text: String::new(), + toast_until: None, + } + } +} + +impl SteamControllerState { + pub fn gear_label(&self) -> &'static str { + match self.gear { + -1 => "R", + 0 => "N", + 1 => "1", + 2 => "2", + 3 => "3", + _ => "?", + } + } + + pub fn set_toast(&mut self, msg: impl Into) { + self.toast_text = msg.into(); + self.toast_until = Some(Instant::now() + Duration::from_millis(TOAST_DURATION_MS)); + } + + #[allow(dead_code)] + pub fn active_toast(&self) -> Option<&str> { + match self.toast_until { + Some(until) if Instant::now() < until && !self.toast_text.is_empty() => { + Some(&self.toast_text) + } + _ => None, + } + } + + /// Construit un état compatible OSD pour afficher le HUD Steam Controller sans allocation supplémentaire. + pub fn to_hud_g29_state(&self, hub_failsafe: bool) -> G29State { + G29State { + connected: self.connected, + failsafe: !self.connected || hub_failsafe, + armed: self.armed, + gear: self.gear, + throttle_pct: self.throttle_pct, + brake_pct: self.brake_pct, + ffb_raw: 0, + ffb_pct: 0, + vib_pct: 0, + remote_source: ControlSource::SteamController, + packets_received: self.packets_sent.max(u64::from(self.connected)), + last_packet: if self.connected { + Some(Instant::now()) + } else { + None + }, + toast_text: self.toast_text.clone(), + toast_until: self.toast_until, + } + } +} + +// ========================================================================= +// LOGIQUE DE CALCUL DES CANAUX CRSF & BOÎTE SÉQUENTIELLE +// ========================================================================= + +/// Applique la zone morte, l'expo cubique (identique G29) et convertit en CRSF 11-bit (172..1811). +pub fn steering_to_crsf(raw_norm: f32, deadzone: f32, expo: f32, invert: bool) -> u16 { + let clamped = raw_norm.clamp(-1.0, 1.0); + let dz = deadzone.clamp(0.0, 0.45); + let abs_v = clamped.abs(); + let scaled = if abs_v <= dz { + 0.0 + } else { + let mag = ((abs_v - dz) / (1.0 - dz)).clamp(0.0, 1.0); + mag.copysign(clamped) + }; + + let e = expo.clamp(0.0, 0.8); + let curved = scaled * (1.0 - e + e * (scaled * scaled)); + let directed = if invert { -curved } else { curved }; + + let crsf = CRSF_CHANNEL_MID as f32 - directed * (CRSF_CHANNEL_MAX - CRSF_CHANNEL_MID) as f32; + (crsf.round() as u16).clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX) +} + +/// Normalise une gâchette [0.0..1.0] avec zone morte et calcule le canal gaz CRSF selon la boîte séquentielle. +pub fn throttle_to_crsf(throttle_norm: f32, deadzone: f32, armed: bool, gear: i8) -> (u8, u16) { + let dz = deadzone.clamp(0.0, 0.45); + let clamped = throttle_norm.clamp(0.0, 1.0); + let active = if clamped <= dz { + 0.0 + } else { + ((clamped - dz) / (1.0 - dz)).clamp(0.0, 1.0) + }; + let pct = (active * 100.0).round() as u8; + + if !armed || active <= 0.0 || gear == 0 { + return (pct, CRSF_CHANNEL_MID); + } + + let crsf = if gear == -1 { + let span = GAZ_ARRIERE_MIN as f32 - GAZ_ARRIERE_MAX as f32; + (GAZ_ARRIERE_MIN as f32 - active * span).round() as u16 + } else if (1..=3).contains(&gear) { + let max_v = GAZ_AVANT_MAX_PAR_VITESSE[(gear - 1) as usize]; + let span = max_v as f32 - GAZ_AVANT_MIN as f32; + (GAZ_AVANT_MIN as f32 + active * span).round() as u16 + } else { + CRSF_CHANNEL_MID + }; + + (pct, crsf.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX)) +} + +/// Normalise la gâchette frein [0.0..1.0] et convertit en CRSF (992..1811). +pub fn brake_to_crsf(brake_norm: f32, deadzone: f32) -> (u8, u16) { + let dz = deadzone.clamp(0.0, 0.45); + let clamped = brake_norm.clamp(0.0, 1.0); + let active = if clamped <= dz { + 0.0 + } else { + ((clamped - dz) / (1.0 - dz)).clamp(0.0, 1.0) + }; + let pct = (active * 100.0).round() as u8; + let crsf = if active <= 0.0 { + CRSF_CHANNEL_MID + } else { + let span = (CRSF_CHANNEL_MAX - CRSF_CHANNEL_MID) as f32; + (CRSF_CHANNEL_MID as f32 + active * span).round() as u16 + }; + (pct, crsf.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX)) +} + +pub fn encode_src_command(source: ControlSource) -> String { + format!("$SRC,{}\n", source.wire_tag()) +} + +pub fn encode_rc_frame( + steer: u16, + accel: u16, + brake: u16, + clutch: u16, + armed: bool, + gear: i8, +) -> String { + format!( + "$RC,{},{},{},{},{},{}\n", + steer.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX), + accel.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX), + brake.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX), + clutch.clamp(CRSF_CHANNEL_MIN, CRSF_CHANNEL_MAX), + if armed { 1 } else { 0 }, + gear.clamp(-1, 3), + ) +} + +// ========================================================================= +// DÉCOUVERTE & LECTURE EVDEV LINUX (SANS DÉPENDANCE EXTERNE) +// ========================================================================= + +#[derive(Debug, Clone)] +struct DetectedEvdevDevice { + path: String, + name: String, + vendor: u16, + product: u16, + has_hat2_triggers: bool, + priority: u8, +} + +fn sysfs_bitmap_has_bit(text: &str, bit: usize) -> bool { + let bits_per_word = usize::BITS as usize; + let word_idx = bit / bits_per_word; + let bit_in_word = bit % bits_per_word; + let words: Vec<&str> = text.split_whitespace().collect(); + if word_idx >= words.len() { + return false; + } + let rev_idx = words.len() - 1 - word_idx; + usize::from_str_radix(words[rev_idx], 16) + .map(|w| ((w >> bit_in_word) & 1) != 0) + .unwrap_or(false) +} + +fn inspect_sysfs_event_node(event_name: &str) -> Option { + let sys_dev = format!("/sys/class/input/{}/device", event_name); + let name = fs::read_to_string(format!("{}/name", sys_dev)) + .ok()? + .trim() + .to_string(); + let key_caps = fs::read_to_string(format!("{}/capabilities/key", sys_dev)).unwrap_or_default(); + let abs_caps = fs::read_to_string(format!("{}/capabilities/abs", sys_dev)).unwrap_or_default(); + let prop_caps = fs::read_to_string(format!("{}/properties", sys_dev)).unwrap_or_default(); + + // Exclure les périphériques purement IMU / accéléromètres ("Steam Controller Motion Sensors") + if sysfs_bitmap_has_bit(&prop_caps, INPUT_PROP_ACCELEROMETER) + || name.to_ascii_lowercase().contains("motion sensor") + { + return None; + } + + // Exiger un vrai gamepad (BTN_SOUTH + ABS_X) + let has_btn_south = sysfs_bitmap_has_bit(&key_caps, BTN_SOUTH as usize); + let has_abs_x = sysfs_bitmap_has_bit(&abs_caps, ABS_X as usize); + if !has_btn_south || !has_abs_x { + return None; + } + + let vendor = fs::read_to_string(format!("{}/id/vendor", sys_dev)) + .ok() + .and_then(|s| u16::from_str_radix(s.trim(), 16).ok()) + .unwrap_or(0); + let product = fs::read_to_string(format!("{}/id/product", sys_dev)) + .ok() + .and_then(|s| u16::from_str_radix(s.trim(), 16).ok()) + .unwrap_or(0); + + let has_hat2_triggers = sysfs_bitmap_has_bit(&abs_caps, ABS_HAT2X as usize) + && sysfs_bitmap_has_bit(&abs_caps, ABS_HAT2Y as usize); + + let lower = name.to_ascii_lowercase(); + let priority = if vendor == VALVE_VENDOR_ID && lower.contains("steam controller") { + 3 + } else if vendor == VALVE_VENDOR_ID { + 2 + } else { + 1 + }; + + Some(DetectedEvdevDevice { + path: format!("/dev/input/{}", event_name), + name, + vendor, + product, + has_hat2_triggers, + priority, + }) +} + +fn find_steam_controller_device(override_path: Option<&str>) -> Option { + if let Some(path) = override_path { + let trimmed = path.trim(); + if !trimmed.is_empty() { + if let Some(file_name) = std::path::Path::new(trimmed) + .file_name() + .and_then(|s| s.to_str()) + { + if let Some(info) = inspect_sysfs_event_node(file_name) { + return Some(info); + } + } + // Fallback direct si le chemin est fourni explicitement + if std::path::Path::new(trimmed).exists() { + return Some(DetectedEvdevDevice { + path: trimmed.to_string(), + name: format!("Contrôleur ({})", trimmed), + vendor: 0, + product: 0, + has_hat2_triggers: true, + priority: 3, + }); + } + return None; + } + } + + let entries = fs::read_dir("/sys/class/input").ok()?; + let mut best: Option = None; + + for entry in entries.flatten() { + let fname = entry.file_name(); + let Some(name_str) = fname.to_str() else { + continue; + }; + if !name_str.starts_with("event") { + continue; + } + let Some(candidate) = inspect_sysfs_event_node(name_str) else { + continue; + }; + // Vérifier que le nœud est réellement ouvrable en lecture + if OpenOptions::new() + .read(true) + .custom_flags(O_NONBLOCK_FLAG) + .open(&candidate.path) + .is_err() + { + continue; + } + + let replace = match &best { + None => true, + Some(prev) => candidate.priority > prev.priority, + }; + if replace { + best = Some(candidate); + } + } + + best +} + +struct AxisRange { + min: i32, + max: i32, + current: i32, +} + +impl AxisRange { + fn centered(min: i32, max: i32, val: i32) -> Self { + Self { + min, + max, + current: val, + } + } + + fn normalized_signed(&self) -> f32 { + let span = (self.max - self.min) as f32; + if span <= 0.0 { + return 0.0; + } + let mid = (self.max as f32 + self.min as f32) * 0.5; + ((self.current as f32 - mid) / (span * 0.5)).clamp(-1.0, 1.0) + } + + fn normalized_unsigned(&self) -> f32 { + let span = (self.max - self.min) as f32; + if span <= 0.0 { + return 0.0; + } + ((self.current - self.min) as f32 / span).clamp(0.0, 1.0) + } +} + +struct OpenEvdevGamepad { + file: File, + info: DetectedEvdevDevice, + throttle_code: u16, + brake_code: u16, + steer_axis: AxisRange, + throttle_axis: AxisRange, + brake_axis: AxisRange, + clutch_pressed: bool, +} + +impl OpenEvdevGamepad { + fn open(info: DetectedEvdevDevice) -> Result { + let file = OpenOptions::new() + .read(true) + .custom_flags(O_NONBLOCK_FLAG) + .open(&info.path)?; + + let steer_info = Self::query_abs(&file, ABS_X).unwrap_or(LinuxInputAbsInfo { + value: 0, + minimum: -32767, + maximum: 32767, + ..Default::default() + }); + + let (throttle_code, brake_code) = if info.has_hat2_triggers { + (ABS_HAT2X, ABS_HAT2Y) + } else { + (ABS_RZ, ABS_Z) + }; + + let throttle_info = Self::query_abs(&file, throttle_code).unwrap_or(LinuxInputAbsInfo { + value: 0, + minimum: 0, + maximum: 32767, + ..Default::default() + }); + let brake_info = Self::query_abs(&file, brake_code).unwrap_or(LinuxInputAbsInfo { + value: 0, + minimum: 0, + maximum: 32767, + ..Default::default() + }); + + Ok(Self { + file, + info, + throttle_code, + brake_code, + steer_axis: AxisRange::centered( + steer_info.minimum, + steer_info.maximum, + steer_info.value, + ), + throttle_axis: AxisRange::centered( + throttle_info.minimum, + throttle_info.maximum, + throttle_info.value, + ), + brake_axis: AxisRange::centered( + brake_info.minimum, + brake_info.maximum, + brake_info.value, + ), + clutch_pressed: false, + }) + } + + fn query_abs(file: &File, code: u16) -> Option { + let mut info = LinuxInputAbsInfo::default(); + let ret = unsafe { + ioctl( + file.as_raw_fd(), + eviocgabs(code), + &mut info as *mut LinuxInputAbsInfo, + ) + }; + if ret >= 0 && info.maximum > info.minimum { + Some(info) + } else { + None + } + } + + /// Lit tous les événements en attente de manière non-bloquante. + /// Retourne `Err` si le périphérique a été débranché / éteint. + fn poll_events(&mut self, out_pressed_keys: &mut Vec) -> Result<()> { + const EV_SIZE: usize = std::mem::size_of::(); + let mut buf = [0u8; EV_SIZE * 64]; + + loop { + match self.file.read(&mut buf) { + Ok(0) => return Err(anyhow!("EOF evdev (manette déconnectée)")), + Ok(n) => { + let count = n / EV_SIZE; + for i in 0..count { + let ev = unsafe { + std::ptr::read_unaligned( + buf.as_ptr().add(i * EV_SIZE) as *const LinuxInputEvent + ) + }; + match ev.ev_type { + EV_ABS => { + if ev.code == ABS_X { + self.steer_axis.current = ev.value; + } else if ev.code == self.throttle_code { + self.throttle_axis.current = ev.value; + } else if ev.code == self.brake_code { + self.brake_axis.current = ev.value; + } + } + EV_KEY => { + if ev.code == BTN_GRIPL2 { + self.clutch_pressed = ev.value != 0; + } else if ev.value == 1 { + out_pressed_keys.push(ev.code); + } + } + _ => {} + } + } + } + Err(e) if e.kind() == ErrorKind::WouldBlock => break, + Err(e) => return Err(anyhow!("Erreur lecture evdev : {}", e)), + } + } + Ok(()) + } +} + +// ========================================================================= +// WORKER TEMPS RÉEL STEAM CONTROLLER -> UDP :14552 -> RADXA -> RP2350 +// ========================================================================= + +pub struct SteamControllerWorker { + state: Arc>, + stop_flag: Arc, + worker: Option>, +} + +impl SteamControllerWorker { + pub fn start( + target_ip: &str, + target_port: u16, + cfg: SteamControllerConfig, + active_source: Arc, + control: EngineControlHandle, + g29_state_opt: Option>>, + ) -> Result { + let socket = UdpSocket::bind("0.0.0.0:0")?; + socket.set_nonblocking(true)?; + + let trimmed_ip = target_ip.trim(); + let host_port = format!("{}:{}", trimmed_ip, target_port); + let target: SocketAddr = if let Ok(ip) = trimmed_ip.parse::() { + SocketAddr::new(ip, target_port) + } else { + let addrs: Vec = host_port.to_socket_addrs()?.collect(); + addrs + .iter() + .copied() + .find(|a| a.is_ipv4()) + .or_else(|| addrs.into_iter().next()) + .ok_or_else(|| anyhow!("Impossible de résoudre la cible contrôleur {}", host_port))? + }; + + let state = Arc::new(Mutex::new(SteamControllerState::default())); + let state_clone = Arc::clone(&state); + let stop_flag = Arc::new(AtomicBool::new(false)); + let stop_clone = Arc::clone(&stop_flag); + + let worker = thread::Builder::new() + .name("steam-ctrl-worker".into()) + .spawn(move || { + Self::run_loop( + socket, + target, + cfg, + active_source, + control, + g29_state_opt, + state_clone, + stop_clone, + ); + })?; + + Ok(Self { + state, + stop_flag, + worker: Some(worker), + }) + } + + pub fn state(&self) -> Arc> { + Arc::clone(&self.state) + } + + #[allow(clippy::too_many_arguments)] + fn run_loop( + socket: UdpSocket, + target: SocketAddr, + cfg: SteamControllerConfig, + active_source: Arc, + control: EngineControlHandle, + g29_state_opt: Option>>, + state: Arc>, + stop_flag: Arc, + ) { + let mut gamepad: Option = None; + let mut last_scan = Instant::now() - Duration::from_secs(10); + let mut last_src_sync = Instant::now() - Duration::from_secs(10); + let mut last_source = ControlSource::from_u8(active_source.load(Ordering::Acquire)); + let mut pressed_keys: Vec = Vec::with_capacity(16); + + // Synchronisation initiale de la source souhaitée auprès de la RP2350 + let init_cmd = encode_src_command(last_source); + let _ = socket.send_to(init_cmd.as_bytes(), target); + + while !stop_flag.load(Ordering::Acquire) { + let loop_start = Instant::now(); + let desired_source = ControlSource::from_u8(active_source.load(Ordering::Acquire)); + + // 1. Changement de source actif (G29 <-> Steam Controller) + if desired_source != last_source { + last_source = desired_source; + { + let mut st = state.lock(); + st.armed = false; + st.gear = 0; + st.throttle_pct = 0; + st.brake_pct = 0; + st.steer_crsf = CRSF_CHANNEL_MID; + st.throttle_crsf = CRSF_CHANNEL_MID; + st.brake_crsf = CRSF_CHANNEL_MID; + st.clutch_crsf = CRSF_CHANNEL_MID; + st.set_toast(format!("CTRL: {}", desired_source.label())); + } + let cmd = encode_src_command(desired_source); + let _ = socket.send_to(cmd.as_bytes(), target); + last_src_sync = Instant::now(); + log::info!( + "[Contrôleur] Bascule source envoyée vers {} : {}", + target, + cmd.trim() + ); + } else if last_src_sync.elapsed() >= Duration::from_millis(SRC_RESYNC_INTERVAL_MS) { + // Resynchroniser si la RP2350 (après reboot ou paquet UDP perdu) n'est pas sur la source attendue + let needs_resync = if let Some(ref g29_st) = g29_state_opt { + let g = g29_st.lock(); + g.is_live() && !g.armed && g.remote_source != desired_source + } else { + desired_source == ControlSource::SteamController + }; + if needs_resync { + let cmd = encode_src_command(desired_source); + let _ = socket.send_to(cmd.as_bytes(), target); + } + last_src_sync = Instant::now(); + } + + // 2. Découverte / reconnexion à chaud du Steam Controller (evdev) + if gamepad.is_none() + && last_scan.elapsed() >= Duration::from_millis(DEVICE_RESCAN_INTERVAL_MS) + { + last_scan = Instant::now(); + if let Some(dev_info) = find_steam_controller_device(cfg.device_override.as_deref()) + { + match OpenEvdevGamepad::open(dev_info) { + Ok(opened) => { + log::info!( + "[Steam Controller] Connecté : '{}' sur {} (VID={:04X}, PID={:04X}, triggers={})", + opened.info.name, + opened.info.path, + opened.info.vendor, + opened.info.product, + if opened.info.has_hat2_triggers { + "hid-steam HAT2X/Y" + } else { + "standard RZ/Z" + } + ); + let mut st = state.lock(); + st.connected = true; + st.device_name = opened.info.name.clone(); + st.device_path = opened.info.path.clone(); + st.armed = false; + st.gear = 0; + gamepad = Some(opened); + } + Err(e) => { + log::warn!("[Steam Controller] Impossible d'ouvrir le périphérique : {}", e); + } + } + } + } + + // 3. Lecture non-bloquante des événements evdev + pressed_keys.clear(); + let mut disconnected = false; + if let Some(ref mut gp) = gamepad { + if let Err(e) = gp.poll_events(&mut pressed_keys) { + log::warn!("[Steam Controller] Liaison perdue ({}) : désarmement immédiat.", e); + disconnected = true; + } + } + if disconnected { + gamepad = None; + let mut st = state.lock(); + st.connected = false; + st.armed = false; + st.gear = 0; + st.steering_norm = 0.0; + st.throttle_pct = 0; + st.brake_pct = 0; + st.clutch_pct = 0; + st.steer_crsf = CRSF_CHANNEL_MID; + st.throttle_crsf = CRSF_CHANNEL_MID; + st.brake_crsf = CRSF_CHANNEL_MID; + st.clutch_crsf = CRSF_CHANNEL_MID; + st.set_toast("SC DECONNECTE"); + } + + // 4. Traitement axes, boîte séquentielle, boutons cockpit & émission $RC à 100 Hz + if desired_source == ControlSource::SteamController { + if let Some(ref gp) = gamepad { + let steer_norm = gp.steer_axis.normalized_signed(); + let throttle_norm = gp.throttle_axis.normalized_unsigned(); + let brake_norm = gp.brake_axis.normalized_unsigned(); + let clutch_pressed = gp.clutch_pressed; + + let steer_crsf = steering_to_crsf( + steer_norm, + cfg.steering_deadzone, + cfg.steering_expo, + cfg.invert_steering, + ); + let (brake_pct, brake_crsf) = brake_to_crsf(brake_norm, cfg.trigger_deadzone); + let clutch_pct = if clutch_pressed { 100 } else { 0 }; + let clutch_crsf = if clutch_pressed { + CRSF_CHANNEL_MAX + } else { + CRSF_CHANNEL_MID + }; + + // Évaluer les boutons avant le calcul final des gaz + let (armed, gear, throttle_pct, throttle_crsf) = { + let mut st = state.lock(); + let (pre_throt_pct, _) = throttle_to_crsf( + throttle_norm, + cfg.trigger_deadzone, + st.armed, + st.gear, + ); + let gas_released = pre_throt_pct == 0; + + for &key in &pressed_keys { + Self::handle_key_press(key, gas_released, &mut st, &control); + } + + let (throt_pct, throt_crsf) = throttle_to_crsf( + throttle_norm, + cfg.trigger_deadzone, + st.armed, + st.gear, + ); + st.steering_norm = steer_norm; + st.throttle_pct = throt_pct; + st.brake_pct = brake_pct; + st.clutch_pct = clutch_pct; + st.steer_crsf = steer_crsf; + st.throttle_crsf = throt_crsf; + st.brake_crsf = brake_crsf; + st.clutch_crsf = clutch_crsf; + + (st.armed, st.gear, throt_pct, throt_crsf) + }; + + let _ = throttle_pct; + let frame = encode_rc_frame( + steer_crsf, + throttle_crsf, + brake_crsf, + clutch_crsf, + armed, + gear, + ); + match socket.send_to(frame.as_bytes(), target) { + Ok(_) => { + let mut st = state.lock(); + st.packets_sent = st.packets_sent.wrapping_add(1); + } + Err(_) => { + let mut st = state.lock(); + st.send_errors = st.send_errors.wrapping_add(1); + } + } + } + } + + let elapsed = loop_start.elapsed(); + let interval = Duration::from_millis(RC_SEND_INTERVAL_MS); + if elapsed < interval { + thread::sleep(interval - elapsed); + } + } + + // À l'arrêt propre, envoyer un état désarmé si le Steam Controller était actif + if ControlSource::from_u8(active_source.load(Ordering::Acquire)) + == ControlSource::SteamController + { + let safe_frame = encode_rc_frame( + CRSF_CHANNEL_MID, + CRSF_CHANNEL_MID, + CRSF_CHANNEL_MID, + CRSF_CHANNEL_MID, + false, + 0, + ); + let _ = socket.send_to(safe_frame.as_bytes(), target); + } + log::info!("[Steam Controller] Thread contrôleur arrêté."); + } + + fn handle_key_press( + key: u16, + gas_released: bool, + st: &mut SteamControllerState, + control: &EngineControlHandle, + ) { + match key { + // Armement / Désarmement (Start / Menu) — même règle de sécurité que R2 sur G29 + BTN_START => { + if st.armed { + st.armed = false; + st.set_toast("DESARME"); + log::info!("[Steam Controller] Véhicule DÉSARMÉ (Menu/Start)."); + } else if st.gear == 0 && gas_released { + st.armed = true; + st.set_toast("ARME (SC)"); + log::info!("[Steam Controller] Véhicule ARMÉ (Menu/Start)."); + } else { + st.set_toast("ARM REFUSE (N+GAZ 0)"); + log::warn!( + "[Steam Controller] Armement refusé : passer au point mort (N) et relâcher la gâchette R2 !" + ); + } + } + // Boîte séquentielle : Monter un rapport (RB ou Palette arrière droite R4) + BTN_TR | BTN_GRIPR => { + if st.gear < 3 && !(st.gear < 0 && !gas_released) { + st.gear += 1; + let lbl = st.gear_label(); + st.set_toast(format!("RAPPORT {}", lbl)); + } + } + // Boîte séquentielle : Rétrograder (LB ou Palette arrière gauche L4) + BTN_TL | BTN_GRIPL => { + if st.gear > -1 && !(st.gear <= 0 && !gas_released) { + st.gear -= 1; + let lbl = st.gear_label(); + st.set_toast(format!("RAPPORT {}", lbl)); + } + } + // Actions Cockpit (identiques au mapping G29) + BTN_SOUTH | BTN_THUMBR | BTN_MODE => { + control.request_recenter(); + st.set_toast("TARE HT OK"); + } + BTN_EAST | BTN_SELECT => { + let now_rec = control.toggle_dvr(); + st.set_toast(if now_rec { "DVR REC" } else { "DVR STOP" }); + } + BTN_NORTH => { + let now_on = control.toggle_telemetry(); + st.set_toast(if now_on { "OSD ON" } else { "OSD OFF" }); + } + BTN_WEST => { + let mode_lbl = control.cycle_projection_mode(); + st.set_toast(format!("PROJ: {}", mode_lbl)); + } + BTN_DPAD_UP => { + control.adjust_head_trim(0.0, 1.0); + st.set_toast("TILT +1"); + } + BTN_DPAD_DOWN => { + control.adjust_head_trim(0.0, -1.0); + st.set_toast("TILT -1"); + } + BTN_DPAD_LEFT => { + control.adjust_head_trim(-1.0, 0.0); + st.set_toast("PAN -1"); + } + BTN_DPAD_RIGHT => { + control.adjust_head_trim(1.0, 0.0); + st.set_toast("PAN +1"); + } + _ => {} + } + } +} + +impl Drop for SteamControllerWorker { + fn drop(&mut self) { + self.stop_flag.store(true, Ordering::Release); + if let Some(handle) = self.worker.take() { + let _ = handle.join(); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_control_source_parsing() { + assert_eq!(ControlSource::from_str("g29"), ControlSource::G29); + assert_eq!(ControlSource::from_str("wheel"), ControlSource::G29); + assert_eq!( + ControlSource::from_str("steam"), + ControlSource::SteamController + ); + assert_eq!( + ControlSource::from_str("EXT"), + ControlSource::SteamController + ); + assert_eq!(ControlSource::G29.wire_tag(), "G29"); + assert_eq!(ControlSource::SteamController.wire_tag(), "EXT"); + } + + #[test] + fn test_sysfs_bitmap_has_bit_steam_controller() { + // Capacités réelles d'un Wireless Steam Controller (28de:1304) + let key_caps = "ff00000000 0 0 0 7fdb004600000000 0 0 0 0"; + let abs_caps = "3f001b"; + assert!(sysfs_bitmap_has_bit(key_caps, BTN_SOUTH as usize)); + assert!(sysfs_bitmap_has_bit(key_caps, BTN_START as usize)); + assert!(sysfs_bitmap_has_bit(key_caps, BTN_GRIPR as usize)); + assert!(sysfs_bitmap_has_bit(abs_caps, ABS_X as usize)); + assert!(sysfs_bitmap_has_bit(abs_caps, ABS_HAT2X as usize)); + assert!(sysfs_bitmap_has_bit(abs_caps, ABS_HAT2Y as usize)); + assert!(!sysfs_bitmap_has_bit("40", 0)); + assert!(sysfs_bitmap_has_bit("40", INPUT_PROP_ACCELEROMETER)); + } + + #[test] + fn test_steering_curve_and_polarity() { + // Neutre dans la zone morte + assert_eq!(steering_to_crsf(0.05, 0.08, 0.25, false), CRSF_CHANNEL_MID); + // À droite (+1.0) -> descend vers MIN (172), identique au G29 + assert_eq!(steering_to_crsf(1.0, 0.08, 0.25, false), CRSF_CHANNEL_MIN); + // À gauche (-1.0) -> monte vers MAX (1811), identique au G29 + assert_eq!(steering_to_crsf(-1.0, 0.08, 0.25, false), CRSF_CHANNEL_MAX); + // Inversion + assert_eq!(steering_to_crsf(1.0, 0.08, 0.25, true), CRSF_CHANNEL_MAX); + } + + #[test] + fn test_sequential_gearbox_throttle_and_brake() { + // Désarmé : toujours au neutre + assert_eq!(throttle_to_crsf(1.0, 0.05, false, 2), (100, CRSF_CHANNEL_MID)); + // Point mort N : toujours au neutre + assert_eq!(throttle_to_crsf(1.0, 0.05, true, 0), (100, CRSF_CHANNEL_MID)); + // 1ère vitesse plein gaz -> 1100 + assert_eq!(throttle_to_crsf(1.0, 0.05, true, 1), (100, 1100)); + // 3ème vitesse plein gaz -> 1220 + assert_eq!(throttle_to_crsf(1.0, 0.05, true, 3), (100, 1220)); + // Marche arrière plein gaz -> 850 + assert_eq!(throttle_to_crsf(1.0, 0.05, true, -1), (100, 850)); + // Frein plein -> 1811 + assert_eq!(brake_to_crsf(1.0, 0.05), (100, CRSF_CHANNEL_MAX)); + assert_eq!(brake_to_crsf(0.02, 0.05), (0, CRSF_CHANNEL_MID)); + } + + #[test] + fn test_encode_rc_and_src_frames() { + assert_eq!(encode_src_command(ControlSource::G29), "$SRC,G29\n"); + assert_eq!( + encode_src_command(ControlSource::SteamController), + "$SRC,EXT\n" + ); + assert_eq!( + encode_rc_frame(992, 1150, 992, 992, true, 2), + "$RC,992,1150,992,992,1,2\n" + ); + } +} diff --git a/src/engine.rs b/src/engine.rs index 29e9dea..067c549 100644 --- a/src/engine.rs +++ b/src/engine.rs @@ -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, 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, telemetry_enabled_flag: Arc, head_tracking_enabled_flag: Arc, + control_source_flag: Arc, + monitor_ref: Arc>, optical_params: Arc>, dvr_toggle_cmd: Arc>>, dvr_config: Arc>, @@ -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, telemetry_enabled_flag: Arc, head_tracking_enabled_flag: Arc, + control_source_flag: Arc, worker_handle: Option>, } @@ -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, + ctrl_worker_opt: Option<&SteamControllerWorker>, + g29_snapshot: &G29State, + monitor: &Arc>, +) -> 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, head_trim_deg: Arc>, control_for_g29: EngineControlHandle, + control_for_ctrl: EngineControlHandle, stop_flag: Arc, recenter_flag: Arc, telem_enabled_flag: Arc, ht_enabled_flag: Arc, + control_source_flag: Arc, ) { let mut active_dvr: Option> = 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, telem_enabled_flag: &Arc, ht_enabled_flag: &Arc, + control_source_flag: &Arc, video_rx_opt: Option<&UsbVideoReceiver>, telem_rx_opt: &mut RetrySlot, shared_telem_state: &Arc>, head_tracker_opt: &mut RetrySlot, 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, telem_enabled_flag: &Arc, ht_enabled_flag: &Arc, + control_source_flag: &Arc, video_rx_opt: Option<&UsbVideoReceiver>, telem_rx_opt: &mut RetrySlot, shared_telem_state: &Arc>, head_tracker_opt: &mut RetrySlot, 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, diff --git a/src/g29_bridge.rs b/src/g29_bridge.rs index 3531c82..36ce4b3 100644 --- a/src/g29_bridge.rs +++ b/src/g29_bridge.rs @@ -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, 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%")); } } diff --git a/src/gui.rs b/src/gui.rs index 012b8f0..e1fc0bd 100644 --- a/src/gui.rs +++ b/src/gui.rs @@ -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, 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)") diff --git a/src/gui_gpui.rs b/src/gui_gpui.rs index f1a3cb3..bb69f57 100644 --- a/src/gui_gpui.rs +++ b/src/gui_gpui.rs @@ -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, 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)> = 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) -> 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( diff --git a/src/main.rs b/src/main.rs index 4806f3c..fb62f7f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,4 +1,5 @@ mod config; +mod controller; mod dome_projection; mod dvr; mod engine; diff --git a/src/telemetry_osd.rs b/src/telemetry_osd.rs index 302cbce..77db64c 100644 --- a/src/telemetry_osd.rs +++ b/src/telemetry_osd.rs @@ -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);