diff --git a/firmware/g29_crsf/cli_serial.h b/firmware/g29_crsf/cli_serial.h new file mode 100644 index 0000000..4e5fc6b --- /dev/null +++ b/firmware/g29_crsf/cli_serial.h @@ -0,0 +1,461 @@ +#pragma once + +// Forward declarations (fonctions définies dans crsf_protocol.h et g29_hid.h) +void actualiserLED(); +bool envoyerPlageG29(uint16_t angle); +bool envoyerRessortG29(uint8_t force); +bool envoyerForceG29(uint8_t forceByte); +bool arreterForceG29(); +void gererInitMoteurG29(); + +// ------------------------------------------------------------------------- +// GESTION SÉRIE NON BLOQUANTE +// ------------------------------------------------------------------------- +void demanderOuExecuterSauvegarde() { + if (estActuellementArme()) { + sauvegardeDifferee = true; + Serial.println(">> Modification appliquee (sauvegarde Flash differee au desarmement)."); + } else { + momentDernierChangementDurete_ms = 0; + sauvegardeDifferee = false; + sauvegarderConfiguration(); + } +} + +static bool parseStrictInt(const char* s, int& outVal) { + if (!s || *s == '\0') return false; + char* endPtr = nullptr; + long v = strtol(s, &endPtr, 10); + if (endPtr == s || *endPtr != '\0') return false; + outVal = (int)v; + return true; +} + +static bool parseStrictFloat(const char* s, float& outVal) { + if (!s || *s == '\0') return false; + char* endPtr = nullptr; + float v = strtof(s, &endPtr); + if (endPtr == s || *endPtr != '\0' || isnan(v) || isinf(v)) return false; + outVal = v; + return true; +} + +uint8_t calculerCrc8Crsf(const uint8_t* data, size_t len); + +void traiterLigneSerie(char* commande, bool depuisUsb) { + // Sécurité : les commandes CLI sans CRC (B=BOOTSEL, R=Reset, V=/A=/F=/E=...) ne sont + // acceptées QUE sur l'USB local (Serial), jamais sur l'UART Radxa / UDP (Serial2). + if (!depuisUsb && commande[0] != '$') { + return; + } + + if (commande[0] == '?') { + afficherConfiguration(); + return; + } + if (commande[0] == 'B' || commande[0] == 'b') { + if (estActuellementArme()) { + Serial.println("!! Redemarrage BOOTSEL refuse pendant la conduite (desarmer d'abord) !!"); + return; + } + Serial.println(">> Redemarrage en mode BOOTSEL..."); + Serial.flush(); + rp2040.rebootToBootloader(); + return; + } + if (commande[0] == 'S' || commande[0] == 's') { + if (estActuellementArme()) { + Serial.println("!! Sauvegarde Flash refusee pendant la conduite (desarmer d'abord) !!"); + return; + } + momentDernierChangementDurete_ms = 0; + sauvegardeDifferee = false; + sauvegarderConfiguration(); + return; + } + if (commande[0] == 'R' || commande[0] == 'r') { + if (estActuellementArme()) { + Serial.println("!! Reinitialisation refusee pendant la conduite (desarmer d'abord) !!"); + return; + } + rp2040.idleOtherCore(); + reinitialiserConfigurationDefaut(); + reinitialiserCanauxCRSF(); + rapportEngage = 0; + estArme = false; + extArme = false; + extRapport = 0; + extAccelPct = 0; + extFreinPct = 0; + extEmbrayagePct = 0; + extVolantPct = 0; + extRcActif = false; + __atomic_store_n(&sourceActive, SRC_G29, __ATOMIC_RELEASE); + __atomic_store_n(&majLedRequise, true, __ATOMIC_RELEASE); + __atomic_store_n(&cockpitEtatModifie, true, __ATOMIC_RELEASE); + momentDernierChangementDurete_ms = 0; + sauvegardeDifferee = false; + rp2040.resumeOtherCore(); + __atomic_store_n(&majRangeRequise, true, __ATOMIC_RELEASE); + __atomic_store_n(&majRessortRequise, true, __ATOMIC_RELEASE); + sauvegarderConfiguration(); + afficherConfiguration(); + return; + } + if (strlen(commande) >= 3 && commande[1] == '=') { + char periph = commande[0]; + if (periph == 'V' || periph == 'v' || periph == 'A' || periph == 'a' || + periph == 'F' || periph == 'f' || periph == 'E' || periph == 'e') { + if (estActuellementArme()) { + Serial.println("!! Remappage des canaux refuse pendant la conduite (desarmer d'abord) !!"); + return; + } + int nouveauCanal = 0; + if (!parseStrictInt(&commande[2], nouveauCanal) || nouveauCanal < 1 || nouveauCanal > 16) { + Serial.println("!! Canal invalide : doit etre un entier entre 1 et 16 !!"); + return; + } + if (estCanalReserve((uint8_t)nouveauCanal)) { + Serial.printf("!! Canal %d reserve (ARM=CH%d, HT=CH%d..CH%d) !!\n", + nouveauCanal, CANAL_ARM, CANAL_HT_PAN, CANAL_HT_ROLL); + return; + } + + uint8_t cV = configSysteme.volant; + uint8_t cA = configSysteme.accel; + uint8_t cF = configSysteme.frein; + uint8_t cE = configSysteme.embrayage; + bool conflit = false; + switch (periph) { + case 'V': case 'v': if (nouveauCanal == cA || nouveauCanal == cF || nouveauCanal == cE) conflit = true; break; + case 'A': case 'a': if (nouveauCanal == cV || nouveauCanal == cF || nouveauCanal == cE) conflit = true; break; + case 'F': case 'f': if (nouveauCanal == cV || nouveauCanal == cA || nouveauCanal == cE) conflit = true; break; + case 'E': case 'e': if (nouveauCanal == cV || nouveauCanal == cA || nouveauCanal == cF) conflit = true; break; + } + if (conflit) { + Serial.printf("!! Conflit : le canal %d est deja utilise par un autre axe !!\n", nouveauCanal); + return; + } + + rp2040.idleOtherCore(); + switch (periph) { + case 'V': case 'v': configSysteme.volant = nouveauCanal; break; + case 'A': case 'a': configSysteme.accel = nouveauCanal; break; + case 'F': case 'f': configSysteme.frein = nouveauCanal; break; + case 'E': case 'e': configSysteme.embrayage = nouveauCanal; break; + } + reinitialiserCanauxCRSF(); + rp2040.resumeOtherCore(); + sauvegarderConfiguration(); + afficherConfiguration(); + } else if (periph == 'D' || periph == 'd') { + int val = 0; + if (parseStrictInt(&commande[2], val) && val >= 0 && val <= 255) { + configSysteme.forceRessort = (uint8_t)val; // Atomique sur ARM Cortex-M33 + __atomic_store_n(&majRessortRequise, true, __ATOMIC_RELEASE); + demanderOuExecuterSauvegarde(); + afficherConfiguration(); + } else { + Serial.println("!! Durete (D) doit etre un entier entre 0 et 255 !!"); + } + } else if (periph == 'P' || periph == 'p') { + if (estActuellementArme()) { + Serial.println("!! Reglage de plage (P) refuse pendant la conduite (desarmer d'abord) !!"); + return; + } + int val = 0; + if (parseStrictInt(&commande[2], val) && val >= 40 && val <= 900) { + rp2040.idleOtherCore(); + configSysteme.angleSouhaiteTotal = (uint16_t)val; + recalculerParametresVolant(); + rp2040.resumeOtherCore(); + __atomic_store_n(&majRangeRequise, true, __ATOMIC_RELEASE); + sauvegarderConfiguration(); + afficherConfiguration(); + } else { + Serial.println("!! Plage d'angle (P) doit etre un entier entre 40 et 900 degres !!"); + } + } else if (periph == 'X' || periph == 'x') { + if (estActuellementArme()) { + Serial.println("!! Reglage d'expo (X) refuse pendant la conduite (desarmer d'abord) !!"); + return; + } + float val = 0.0f; + if (parseStrictFloat(&commande[2], val) && val >= 0.0f && val <= 0.8f) { + rp2040.idleOtherCore(); + configSysteme.expoVolant = val; + rp2040.resumeOtherCore(); + sauvegarderConfiguration(); + afficherConfiguration(); + } else { + Serial.println("!! Expo volant (X) doit etre un nombre entre 0.0 et 0.8 !!"); + } + } else if (periph == 'T' || periph == 't') { + int val = 0; + if (parseStrictInt(&commande[2], val) && val >= 0 && val <= 100) { + configSysteme.intensiteVibration = (uint8_t)val; // Atomique sur ARM Cortex-M33 + __atomic_store_n(&cockpitEtatModifie, true, __ATOMIC_RELEASE); + demanderOuExecuterSauvegarde(); + afficherConfiguration(); + } else { + Serial.println("!! Vibrations (T) doit etre un entier entre 0 et 100% !!"); + } + } else if (periph == 'W' || periph == 'w') { + int val = 0; + if (parseStrictInt(&commande[2], val)) { + cockpitEchoUSB = (val != 0); + Serial.printf(">> [COCKPIT] Echo trames $G29 sur USB : %s\n", cockpitEchoUSB ? "ON" : "OFF"); + } + } + return; + } + + // Validation CRC-8 DVB-S2 (*XX) obligatoire sur toutes les trames $... (anti-corruption UART) + if (commande[0] == '$') { + char* star = strrchr(commande, '*'); + if (!star || strlen(star + 1) != 2) { + return; + } + char* endPtr = nullptr; + unsigned long crcRecu = strtoul(star + 1, &endPtr, 16); + if (endPtr != star + 3) { + return; + } + size_t bodyLen = (size_t)(star - commande); + uint8_t crcCalc = calculerCrc8Crsf((const uint8_t*)commande, bodyLen); + if ((uint8_t)crcRecu != crcCalc) { + return; + } + *star = '\0'; + } + + // Injection Head-Tracking depuis SteamFrame FPV : $HT,,, (172..1811) + if (strncmp(commande, "$HT,", 4) == 0) { + int pan = CRSF_VAL_MID, tilt = CRSF_VAL_MID, roll = CRSF_VAL_MID; + if (sscanf(commande + 4, "%d,%d,%d", &pan, &tilt, &roll) == 3) { + crsfChannelStore(CANAL_HT_PAN - 1, (uint16_t)constrain(pan, CRSF_VAL_MIN, CRSF_VAL_MAX)); + crsfChannelStore(CANAL_HT_TILT - 1, (uint16_t)constrain(tilt, CRSF_VAL_MIN, CRSF_VAL_MAX)); + crsfChannelStore(CANAL_HT_ROLL - 1, (uint16_t)constrain(roll, CRSF_VAL_MIN, CRSF_VAL_MAX)); + 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(); + __atomic_store_n(&sourceActive, cible, __ATOMIC_RELEASE); + extRcActif = false; + __atomic_store_n(&extArme, false, __ATOMIC_RELEASE); + __atomic_store_n(&extRapport, 0, __ATOMIC_RELEASE); + extAccelPct = 0; + extFreinPct = 0; + extEmbrayagePct = 0; + extVolantPct = 0; + __atomic_store_n(&estArme, false, __ATOMIC_RELEASE); + __atomic_store_n(&rapportEngage, 0, __ATOMIC_RELEASE); + boutonArmDejaEnfonce = true; + palettePlusDejaEnfoncee = true; + paletteMoinsDejaEnfoncee = true; + etatBoutonsCockpitPrec = 0xFFFF; + reinitialiserCanauxCRSF(); + rp2040.resumeOtherCore(); + __atomic_store_n(&majLedRequise, true, __ATOMIC_RELEASE); + __atomic_store_n(&cockpitEtatModifie, true, __ATOMIC_RELEASE); + Serial.printf(">> [SRC] Source active basculee sur : %s\n", + (sourceActive == SRC_EXT) ? "EXT (Steam Controller)" : "G29 (Volant)"); + return; + } + + // Synchronisation des plages de vitesses CRSF depuis SteamFrame FPV : + // $GEARS,,,,,, + if (strncmp(commande, "$GEARS,", 7) == 0) { + int fMin = 0, g1 = 0, g2 = 0, g3 = 0, rMin = 0, rMax = 0; + if (sscanf(commande + 7, "%d,%d,%d,%d,%d,%d", &fMin, &g1, &g2, &g3, &rMin, &rMax) == 6) { + // Bornes strictes (max > min en AV, max < min en AR) pour éliminer toute division par zéro dans map(). + uint16_t vFMin = (uint16_t)constrain(fMin, CRSF_VAL_MID, CRSF_VAL_MAX - 1); + uint16_t vG1 = (uint16_t)constrain(g1, (int)vFMin + 1, CRSF_VAL_MAX); + uint16_t vG2 = (uint16_t)constrain(g2, (int)vFMin + 1, CRSF_VAL_MAX); + uint16_t vG3 = (uint16_t)constrain(g3, (int)vFMin + 1, CRSF_VAL_MAX); + uint16_t vRMin = (uint16_t)constrain(rMin, CRSF_VAL_MIN + 1, CRSF_VAL_MID); + uint16_t vRMax = (uint16_t)constrain(rMax, CRSF_VAL_MIN, (int)vRMin - 1); + + bool modifie = (configSysteme.gazAvantMin != vFMin) || + (configSysteme.gazAvantMax[0] != vG1) || + (configSysteme.gazAvantMax[1] != vG2) || + (configSysteme.gazAvantMax[2] != vG3) || + (configSysteme.gazArriereMin != vRMin) || + (configSysteme.gazArriereMax != vRMax); + + if (modifie) { + if (estActuellementArme()) { + // Sécurité : jamais d'idleOtherCore / EEPROM.commit() en conduite armée (gel Flash 50-100 ms). + // On applique les plafonds en RAM et on diffère l'écriture Flash au désarmement. + configSysteme.gazAvantMin = vFMin; + configSysteme.gazAvantMax[0] = vG1; + configSysteme.gazAvantMax[1] = vG2; + configSysteme.gazAvantMax[2] = vG3; + configSysteme.gazArriereMin = vRMin; + configSysteme.gazArriereMax = vRMax; + sauvegardeDifferee = true; + Serial.printf(">> [VITESSES] Maj RAM (Flash differee au desarmement) : AV_MIN=%u | 1=%u | 2=%u | 3=%u | AR_MIN=%u | AR_MAX=%u\n", + vFMin, vG1, vG2, vG3, vRMin, vRMax); + } else { + rp2040.idleOtherCore(); + configSysteme.gazAvantMin = vFMin; + configSysteme.gazAvantMax[0] = vG1; + configSysteme.gazAvantMax[1] = vG2; + configSysteme.gazAvantMax[2] = vG3; + configSysteme.gazArriereMin = vRMin; + configSysteme.gazArriereMax = vRMax; + rp2040.resumeOtherCore(); + sauvegarderConfiguration(); + Serial.printf(">> [VITESSES] AV_MIN=%u | 1=%u | 2=%u | 3=%u | AR_MIN=%u | AR_MAX=%u\n", + vFMin, vG1, vG2, vG3, vRMin, vRMax); + } + } + } + return; + } + + // Injection conduite externe (Steam Controller via SteamFrame FPV) : + // $RC,,,,,, + if (strncmp(commande, "$RC,", 4) == 0) { + if (__atomic_load_n(&sourceActive, __ATOMIC_ACQUIRE) != SRC_EXT) { + return; + } + int steer = CRSF_VAL_MID, accel = CRSF_VAL_MID, brake = CRSF_VAL_MID, clutch = CRSF_VAL_MID; + 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) { + __atomic_store_n(&extArme, true, __ATOMIC_RELEASE); + momentArmement_ms = millis(); + momentDesarmement_ms = 0; + __atomic_store_n(&majLedRequise, true, __ATOMIC_RELEASE); + __atomic_store_n(&cockpitEtatModifie, true, __ATOMIC_RELEASE); + Serial.println(">> [ARM EXT] ARME (Steam Controller)"); + } + } else if (!demandeArm && extArme) { + __atomic_store_n(&extArme, false, __ATOMIC_RELEASE); + momentDesarmement_ms = millis(); + momentArmement_ms = 0; + __atomic_store_n(&majLedRequise, true, __ATOMIC_RELEASE); + __atomic_store_n(&cockpitEtatModifie, true, __ATOMIC_RELEASE); + Serial.println(">> [ARM EXT] DESARME (Steam Controller)"); + } + + if (vGear != extRapport) { + __atomic_store_n(&extRapport, vGear, __ATOMIC_RELEASE); + __atomic_store_n(&majLedRequise, true, __ATOMIC_RELEASE); + __atomic_store_n(&cockpitEtatModifie, true, __ATOMIC_RELEASE); + } + + // Défense en profondeur : appliquer aussi les plafonds CRSF par rapport côté RP2350 + if (!extArme || extRapport == 0) { + vAccel = CRSF_VAL_MID; + } else if (extRapport >= 1 && extRapport <= 3) { + uint16_t maxV = configSysteme.gazAvantMax[extRapport - 1]; + vAccel = (uint16_t)constrain((int)vAccel, CRSF_VAL_MID, (int)maxV); + } else if (extRapport == -1) { + vAccel = (uint16_t)constrain((int)vAccel, (int)configSysteme.gazArriereMax, CRSF_VAL_MID); + } + + uint8_t accelPct = 0; + if (extArme && extRapport >= 1 && extRapport <= 3 && vAccel >= configSysteme.gazAvantMin) { + uint16_t maxV = configSysteme.gazAvantMax[extRapport - 1]; + if (maxV > configSysteme.gazAvantMin) { + accelPct = (uint8_t)constrain(map(vAccel, configSysteme.gazAvantMin, maxV, 0, 100), 0, 100); + } + } else if (extArme && extRapport == -1 && vAccel <= configSysteme.gazArriereMin) { + if (configSysteme.gazArriereMin > configSysteme.gazArriereMax) { + accelPct = (uint8_t)constrain(map(vAccel, configSysteme.gazArriereMin, configSysteme.gazArriereMax, 0, 100), 0, 100); + } + } + uint8_t brakePct = (vBrake > CRSF_VAL_MID) + ? (uint8_t)constrain(map(vBrake, CRSF_VAL_MID, CRSF_VAL_MAX, 0, 100), 0, 100) + : 0; + uint8_t clutchPct = (vClutch > CRSF_VAL_MID) + ? (uint8_t)constrain(map(vClutch, CRSF_VAL_MID, CRSF_VAL_MAX, 0, 100), 0, 100) + : 0; + int8_t steerPct = (int8_t)constrain( + (int)(((float)((int)CRSF_VAL_MID - (int)vSteer) / (float)(CRSF_VAL_MID - CRSF_VAL_MIN)) * 100.0f), + -100, 100 + ); + extAccelPct = accelPct; + extFreinPct = brakePct; + extEmbrayagePct = clutchPct; + extVolantPct = steerPct; + + assignerCanalCRSF(configSysteme.volant, vSteer); + assignerCanalCRSF(configSysteme.accel, vAccel); + assignerCanalCRSF(configSysteme.frein, vBrake); + assignerCanalCRSF(configSysteme.embrayage, vClutch); + crsfChannelStore(CANAL_ARM - 1, extArme ? CRSF_VAL_MAX : CRSF_VAL_MIN); + + dernierPaquetRC_ms = millis(); + if (!extRcActif) { + extRcActif = true; + __atomic_store_n(&majLedRequise, true, __ATOMIC_RELEASE); + __atomic_store_n(&cockpitEtatModifie, true, __ATOMIC_RELEASE); + } + } + return; + } +} + +void lireFluxSerie(Stream& port, char* buf, uint8_t& idx, bool& overflow, size_t maxLen, bool depuisUsb) { + int budget = 96; // Borner le temps passé dans loop() pour préserver la cadence CRSF 166 Hz + while (port.available() > 0 && budget-- > 0) { + char c = (char)port.read(); + if (c == '\n' || c == '\r') { + if (!overflow && idx > 0) { + buf[idx] = '\0'; + traiterLigneSerie(buf, depuisUsb); + } + idx = 0; + overflow = false; + } else if (overflow) { + // Ignorer le reste de la ligne trop longue jusqu'au prochain retour à la ligne + } else if (idx < maxLen - 1) { + buf[idx++] = c; + } else { + idx = 0; + overflow = true; + } + } +} + +void verifierCommandesSerie() { + lireFluxSerie(Serial, serialBuffer, serialBufferIdx, serialBufferOverflow, sizeof(serialBuffer), true); + lireFluxSerie(Serial2, serial2Buffer, serial2BufferIdx, serial2BufferOverflow, sizeof(serial2Buffer), false); +} + diff --git a/firmware/g29_crsf/config_state.h b/firmware/g29_crsf/config_state.h new file mode 100644 index 0000000..6856234 --- /dev/null +++ b/firmware/g29_crsf/config_state.h @@ -0,0 +1,411 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +// Brochage natif de la Waveshare RP2350-USB-A +#define HOST_PIN_DP 12 // USB-A D+ (D- est automatiquement sur GP13) +#define NUM_PIXELS 1 +#define PIN_LED_RGB 16 // LED RGB WS2812 intégrée +#define EEPROM_SIZE 32 + +// Sécurité : failsafe, watchdog et identification du volant +#define TIMEOUT_FAILSAFE_MS 1000 // Watchdog inter-coeur : alerte si le coeur 1 ne repond plus depuis X ms +#define WATCHDOG_TIMEOUT_MS 1000 // Reboot materiel si le coeur 0 se fige +#define G29_VID 0x046D +#define G29_PID_PS4 0xC260 // G29 en mode PS4 (le mode PS3 = 0xC24F a un autre format de rapport) +#define G29_REPORT_ID 0x01 + +// Masques additionnels dans report[5] (D-Pad et boutons façade en mode PS4) +#define DPAD_MASK_B5 0x0F // Quartet bas : 0=Haut, 2=Droite, 4=Bas, 6=Gauche, 8=Neutre +#define BOUTON_CARRE_MASK 0x10 // Carré [□] +#define BOUTON_CROIX_MASK 0x20 // Croix [✕] +#define BOUTON_ROND_MASK 0x40 // Rond [○] +#define BOUTON_TRIANGLE_MASK 0x80 // Triangle [△] + +// Masques des palettes et boutons dans report[6] +#define PALETTE_MOINS_MASK 0x01 // L1 (Palette gauche : Rétrograder) +#define PALETTE_PLUS_MASK 0x02 // R1 (Palette droite : Monter un rapport) +#define BOUTON_L2_MASK 0x04 // L2 +#define BOUTON_ARM_MASK 0x08 // R2 (Bascule Armé / Désarmé) +#define BOUTON_SHARE_MASK 0x10 // Share +#define BOUTON_OPTIONS_MASK 0x20 // Options +#define BOUTON_L3_MASK 0x40 // L3 +#define BOUTON_R3_MASK 0x80 // R3 + +// Masques additionnels dans report[54] (Molette et boutons + / - / Enter en mode PS4 PID 0xC260) +#define DIAL_ENTER_MASK_B54 0x01 // Bouton central de la molette +#define DIAL_CCW_MASK_B54 0x02 // Molette sens anti-horaire (Dureté -) +#define DIAL_CW_MASK_B54 0x04 // Molette sens horaire (Dureté +) +#define BOUTON_MOINS_MASK_B54 0x08 // Bouton [-] (Dureté -) +#define BOUTON_PLUS_MASK_B54 0x10 // Bouton [+] (Dureté +) + +// Masques de secours dans report[7] (Mode PC / rapport court + bouton PS) +#define BOUTON_PS_MASK_B7 0x01 // Bouton PS +#define BOUTON_PLUS_MASK_B7 0x04 // Bouton [+] +#define BOUTON_MOINS_MASK_B7 0x08 // Bouton [-] +#define DIAL_CW_MASK_B7 0x10 // Molette sens horaire +#define DIAL_CCW_MASK_B7 0x20 // Molette sens anti-horaire +#define DIAL_ENTER_MASK_B7 0x40 // Bouton central de la molette + +// Liaison série bidirectionnelle vers le pont Radxa Zero 3W / SteamFrame FPV Cockpit +#define PIN_UART_BRIDGE_TX 4 +#define PIN_UART_BRIDGE_RX 5 +#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 { + EVT_BTN_CROSS = (1 << 0), + EVT_BTN_CIRCLE = (1 << 1), + EVT_BTN_SQUARE = (1 << 2), + EVT_BTN_TRIANGLE = (1 << 3), + EVT_BTN_SHARE = (1 << 4), + EVT_BTN_OPTIONS = (1 << 5), + EVT_BTN_PS = (1 << 6), + EVT_BTN_L3 = (1 << 7), + EVT_BTN_R3 = (1 << 8), + EVT_BTN_DPAD_UP = (1 << 9), + EVT_BTN_DPAD_DOWN = (1 << 10), + EVT_BTN_DPAD_LEFT = (1 << 11), + EVT_BTN_DPAD_RIGHT = (1 << 12), +}; + +// Armement ELRS : AUX1 = canal 5 (réservé, ne peut pas être mappé ailleurs) +#define CANAL_ARM 5 + +// Head-Tracking Steam Frame : AUX2..AUX4 = canaux 6, 7, 8 (Pan, Tilt, Roll) +#define CANAL_HT_PAN 6 +#define CANAL_HT_TILT 7 +#define CANAL_HT_ROLL 8 + +// Bornes officielles CRSF +#define CRSF_VAL_MIN 172 // ~988 us +#define CRSF_VAL_MID 992 // 1500 us (Neutre) +#define CRSF_VAL_MAX 1811 // ~2012 us + +// Plages de gaz progressives (Marche avant : rapports 1, 2, 3) +#define GAZ_AVANT_MIN 1065 +const uint16_t GAZ_AVANT_MAX_PAR_VITESSE[3] = { + 1100, // 1ère vitesse (Manœuvre) + 1150, // 2ème vitesse (Normale) + 1220 // 3ème vitesse (Rapide) +}; + +#define GAZ_ARRIERE_MIN 905 +#define GAZ_ARRIERE_MAX 800 +#define DEADZONE_PEDALE 800 + +// Configuration par défaut du volant G29 +#define CENTRE_VOLANT_BRUT 32768 +#define DELTA_MAX_VOLANT_BRUT 31600 // ~96,4% de la demi-course (début de la butée logicielle) +#define HYSTERESIS_MUR_BRUT 450 // ~1,6° de marge pour repousser franchement sans osciller +#define ANGLE_DEFAUT_TOTAL 240.0f // Plage totale par defaut : 240 degres (+/- 120 degres) +#define EXPO_DEFAUT 0.25f // 0.0f = Lineaire, 0.25f = Doux au centre (FPU RP2350) +#define FORCE_RESSORT_DEFAUT 140 // Force du retour au centre : 0 a 255 +#define PENTE_RESSORT_G29 7 // Raideur autour du centre : 1 a 7 +#define ETAPES_INIT_FFB_TOTAL 2 // Nombre d'etapes d'init FFB initiales (0=Range, 1=Spring) +#define VIBRATION_DEFAUT 50 // Intensite par defaut des vibrations (0 a 100%) +#define MAGIC_NUMBER_CONFIG 0x4B // Identifiant de validite en EEPROM (mis a jour pour vitesses CRSF) + +Adafruit_NeoPixel rgb_led(NUM_PIXELS, PIN_LED_RGB, NEO_GRB + NEO_KHZ800); +Adafruit_USBH_Host USBHost; + +volatile uint16_t crsf_channels[16] = { + CRSF_VAL_MID, CRSF_VAL_MID, CRSF_VAL_MID, CRSF_VAL_MID, + CRSF_VAL_MIN, CRSF_VAL_MID, CRSF_VAL_MID, CRSF_VAL_MID, // Canal 5 (ARM) : désarmé + CRSF_VAL_MID, CRSF_VAL_MID, CRSF_VAL_MID, CRSF_VAL_MID, + CRSF_VAL_MID, CRSF_VAL_MID, CRSF_VAL_MID, CRSF_VAL_MID +}; + +struct __attribute__((packed)) ConfigG29 { + uint8_t volant; + uint8_t accel; + uint8_t frein; + uint8_t embrayage; + uint8_t forceRessort; // Force du retour au centre : 0 à 255 + uint16_t angleSouhaiteTotal; // Plage totale en degrés : 40 à 900 + float expoVolant; // Expo volant : 0.0f à 0.8f + uint8_t intensiteVibration; // Intensité globale des vibrations : 0 à 100% + uint16_t gazAvantMin; // Seuil de démarrage marche avant (défaut 1065) + uint16_t gazAvantMax[3]; // Plafonds 1ère, 2ème, 3ème vitesse + uint16_t gazArriereMin; // Seuil de démarrage marche arrière (défaut 905) + uint16_t gazArriereMax; // Plafond marche arrière (défaut 800) + uint8_t magicNumber; // Identifiant de validité en EEPROM (MAGIC_NUMBER_CONFIG) +}; + +volatile ConfigG29 configSysteme; +volatile int32_t maxDeltaVolant = 0; + +void recalculerParametresVolant() { + // Le G29 en mode PS4 redistribue ses 65535 points (16-bit) sur la plage configurée par cmdRange. + // La butée démarre à DELTA_MAX_VOLANT_BRUT (31600 points, ~96,4% de demi-course) + // pour permettre l'allumage franc des 5 LEDs RPM en butée extrême. + maxDeltaVolant = DELTA_MAX_VOLANT_BRUT; +} + +// Boîte séquentielle : -1 = R, 0 = N (Point Mort), 1 = 1ère, 2 = 2ème, 3 = 3ème +volatile int8_t rapportEngage = 0; +volatile bool palettePlusDejaEnfoncee = false; +volatile bool paletteMoinsDejaEnfoncee = false; +volatile bool majLedRequise = true; + +// Armement (bascule par R2) : écrit uniquement par le cœur 1 +volatile bool estArme = false; +volatile bool boutonArmDejaEnfonce = false; +volatile int8_t logArmRequis = 0; // 1 = armé, -1 = désarmé, 2 = armement refusé + +// État USB Host et diagnostic inter-cœurs +volatile uint8_t g29_dev_addr = 0; +volatile uint8_t g29_instance = 0; +volatile uint16_t g29_desc_len = 0; +volatile uint16_t g29_vid = 0; +volatile uint16_t g29_pid = 0; +volatile bool volant_est_pret = false; +volatile uint32_t dernierRapportUSB_ms = 0; +volatile uint32_t momentConnexionUSB_ms = 0; +volatile bool logMountRequis = false; +volatile int8_t statutEnvoiLed = 0; +volatile uint32_t heartbeatCore1_ms = 0; // Surveillance santé Cœur 1 (Watchdog dual-core) +volatile bool core1Demarre = false; // Passe à true dès le premier tour de loop1() +uint32_t momentDemarrageCore0_ms = 0; // Grâce de démarrage Cœur 1 (5 s max) + +// Failsafe et diagnostic +volatile bool failsafeActif = true; // Écrit uniquement par le cœur 0 +volatile uint32_t compteurRapportsOK = 0; // Écrit uniquement par le cœur 1 +volatile uint32_t compteurRapportsRejetes = 0; +volatile uint16_t dernierRejetLen = 0; +volatile uint8_t dernierRejetId = 0; +volatile bool logRejetRequis = false; +volatile uint16_t rejet_vid = 0; +volatile uint16_t rejet_pid = 0; + +volatile uint8_t dernierMasqueLedG29 = 0xFF; +volatile uint8_t etapeEnvoiLed = 0; +volatile uint8_t etapeInitMoteur = 0; +volatile bool reinitPlageTardiveFaite = false; + +// Variables pour le réglage FFB à la volée (Molette / Boutons +/- et Série) +volatile bool majRessortRequise = false; +volatile bool majRangeRequise = false; +volatile bool dialPlusDejaEnfonce = false; +volatile bool dialMoinsDejaEnfonce = false; +volatile bool dialEnterDejaEnfonce = false; +volatile bool btnPlusDejaEnfonce = false; +volatile bool btnMoinsDejaEnfonce = false; +volatile uint32_t momentDernierChangementDurete_ms = 0; +volatile uint32_t momentDernierChangementVib_ms = 0; +volatile bool logDureteRequis = false; +volatile bool logVibrationRequis = false; +volatile bool demandeSauvegardeEEPROM = false; +volatile bool sauvegardeDifferee = false; +volatile uint32_t momentArmement_ms = 0; +volatile uint32_t momentDesarmement_ms = 0; + +// Variables pour les vibrations haptiques et la télémétrie +volatile uint8_t rugositeTerrainExterne = 0; // 0 à 255 (pilotable via CRSF télémétrie / FC) +volatile float dernierAccelPct = 0.0f; // 0.0 à 100.0% +volatile float dernierFreinPct = 0.0f; // 0.0 à 100.0% +volatile float dernierEmbrayagePct = 0.0f; // 0.0 à 100.0% +volatile uint32_t momentDernierChocRapport_ms = 0; // Horodatage du passage de vitesse +volatile int8_t directionDernierChocRapport = 0; // -1 gauche, +1 droite +volatile bool forceEstAuNeutre = false; +volatile int32_t dernierVolantCentre = 0; // Position mesurée du volant par rapport au centre +volatile bool murActifDroite = false; +volatile bool murActifGauche = false; + +// Variables de télémétrie, Head-Tracking & événements boutons vers SteamFrame FPV (Radxa / USB) +volatile uint16_t evtBoutonsMasque = 0; +volatile bool cockpitEtatModifie = true; +volatile uint16_t etatBoutonsCockpitPrec = 0xFFFF; // Ignore tout bouton maintenu au branchement +volatile uint8_t etatDpadPrec = 0xFF; +bool cockpitEchoUSB = true; // Actif par défaut pour liaison directe USB-C (/dev/ttyACM0) +uint32_t dernierPaquetHT_ms = 0; +volatile 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 uint8_t extEmbrayagePct = 0; +volatile int8_t extVolantPct = 0; +volatile uint32_t dernierPaquetRC_ms = 0; + +static inline uint16_t crsfChannelLoad(uint8_t idx) { + return __atomic_load_n(&crsf_channels[idx], __ATOMIC_RELAXED); +} + +static inline void crsfChannelStore(uint8_t idx, uint16_t val) { + __atomic_store_n(&crsf_channels[idx], val, __ATOMIC_RELAXED); +} + +static inline bool estActuellementArme() { + uint8_t src = __atomic_load_n(&sourceActive, __ATOMIC_ACQUIRE); + return (src == SRC_EXT) + ? __atomic_load_n(&extArme, __ATOMIC_ACQUIRE) + : __atomic_load_n(&estArme, __ATOMIC_ACQUIRE); +} + +static inline int8_t rapportActuel() { + uint8_t src = __atomic_load_n(&sourceActive, __ATOMIC_ACQUIRE); + return (src == SRC_EXT) + ? __atomic_load_n(&extRapport, __ATOMIC_ACQUIRE) + : __atomic_load_n(&rapportEngage, __ATOMIC_ACQUIRE); +} + +static inline void assignerCanalCRSF(uint8_t numeroCh, uint16_t valeur11bits) { + if (numeroCh >= 1 && numeroCh <= 16 && numeroCh != CANAL_ARM) { + crsfChannelStore(numeroCh - 1, valeur11bits); + } +} + +char serialBuffer[96]; +uint8_t serialBufferIdx = 0; +bool serialBufferOverflow = false; +char serial2Buffer[96]; +uint8_t serial2BufferIdx = 0; +bool serial2BufferOverflow = false; + +static inline bool estCanalReserve(uint8_t ch) { + return (ch == CANAL_ARM) || (ch == CANAL_HT_PAN) || (ch == CANAL_HT_TILT) || (ch == CANAL_HT_ROLL); +} + +void reinitialiserCanauxCRSF() { + bool ht = __atomic_load_n(&htActif, __ATOMIC_ACQUIRE); + for (int i = 0; i < 16; i++) { + if (ht && (i == (CANAL_HT_PAN - 1) || i == (CANAL_HT_TILT - 1) || i == (CANAL_HT_ROLL - 1))) { + continue; + } + crsfChannelStore((uint8_t)i, CRSF_VAL_MID); + } + crsfChannelStore(CANAL_ARM - 1, CRSF_VAL_MIN); // Toujours désarmé par défaut +} + +void reinitialiserConfigurationDefaut() { + memset((void*)&configSysteme, 0, sizeof(ConfigG29)); + configSysteme.volant = 1; + configSysteme.accel = 3; // AETR : CH3 = Gaz / ESC + configSysteme.frein = 2; // AETR : CH2 = Frein + configSysteme.embrayage = 4; + configSysteme.forceRessort = FORCE_RESSORT_DEFAUT; + configSysteme.angleSouhaiteTotal = ANGLE_DEFAUT_TOTAL; + configSysteme.expoVolant = EXPO_DEFAUT; + configSysteme.intensiteVibration = VIBRATION_DEFAUT; + configSysteme.gazAvantMin = GAZ_AVANT_MIN; + configSysteme.gazAvantMax[0] = GAZ_AVANT_MAX_PAR_VITESSE[0]; + configSysteme.gazAvantMax[1] = GAZ_AVANT_MAX_PAR_VITESSE[1]; + configSysteme.gazAvantMax[2] = GAZ_AVANT_MAX_PAR_VITESSE[2]; + configSysteme.gazArriereMin = GAZ_ARRIERE_MIN; + configSysteme.gazArriereMax = GAZ_ARRIERE_MAX; + configSysteme.magicNumber = MAGIC_NUMBER_CONFIG; + recalculerParametresVolant(); +} + +void sauvegarderConfiguration() { + ConfigG29 cfgActuelle; + // Geler brièvement le Cœur 1 pour garantir un instantané cohérent de configSysteme. + rp2040.idleOtherCore(); + memcpy(&cfgActuelle, (const void*)&configSysteme, sizeof(ConfigG29)); + rp2040.resumeOtherCore(); + + ConfigG29 cfgStockee; + EEPROM.get(0, cfgStockee); + + if (memcmp(&cfgActuelle, &cfgStockee, sizeof(ConfigG29)) == 0) { + return; // Déjà synchronisé : évite un gel du Cœur 1 et préserve les cycles Flash + } + + rp2040.wdt_reset(); + // Note : EEPROM.commit() gère déjà automatiquement idleOtherCore() / resumeOtherCore() + EEPROM.put(0, cfgActuelle); + EEPROM.commit(); + Serial.println(">> Configuration sauvegardée en mémoire Flash !"); +} + +void afficherConfiguration() { + Serial.println("\n--- Configuration G29-CRSF (Waveshare RP2350-USB-A) ---"); + Serial.printf("Volant (V) : Canal %d\n", configSysteme.volant); + Serial.printf("Accel (A) : Canal %d\n", configSysteme.accel); + Serial.printf("Frein (F) : Canal %d\n", configSysteme.frein); + Serial.printf("Embrayage (E) : Canal %d\n", configSysteme.embrayage); + Serial.printf("ARM (R2) : Canal %d (reserve)\n", CANAL_ARM); + Serial.printf("Durete FFB (D) : %d / 255 (%d%%) [Molette rouge ou D=xxx]\n", + 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.printf("Vitesses CRSF : AV_MIN=%u | 1=%u | 2=%u | 3=%u | AR_MIN=%u | AR_MAX=%u\n", + configSysteme.gazAvantMin, + configSysteme.gazAvantMax[0], + configSysteme.gazAvantMax[1], + configSysteme.gazAvantMax[2], + configSysteme.gazArriereMin, + configSysteme.gazArriereMax); + Serial.println("Commandes : V=ch, A=ch, F=ch, E=ch, D=val, P=val, X=val, T=val, $SRC,G29|EXT, $GEARS,..., $RC,..., $HT,..., S(save), R(reset), B(bootsel), ?"); +} + +void chargerConfiguration() { + ConfigG29 cfgStockee; + EEPROM.get(0, cfgStockee); + memcpy((void*)&configSysteme, &cfgStockee, sizeof(ConfigG29)); + + bool conflitReserve = estCanalReserve(configSysteme.volant) || estCanalReserve(configSysteme.accel) || + estCanalReserve(configSysteme.frein) || estCanalReserve(configSysteme.embrayage); + + bool canauxValides = (configSysteme.volant >= 1 && configSysteme.volant <= 16) && + (configSysteme.accel >= 1 && configSysteme.accel <= 16) && + (configSysteme.frein >= 1 && configSysteme.frein <= 16) && + (configSysteme.embrayage >= 1 && configSysteme.embrayage <= 16); + + bool canauxDistincts = (configSysteme.volant != configSysteme.accel) && + (configSysteme.volant != configSysteme.frein) && + (configSysteme.volant != configSysteme.embrayage) && + (configSysteme.accel != configSysteme.frein) && + (configSysteme.accel != configSysteme.embrayage) && + (configSysteme.frein != configSysteme.embrayage); + + bool expoValide = !isnan(configSysteme.expoVolant) && + (configSysteme.expoVolant >= 0.0f) && + (configSysteme.expoVolant <= 0.8f); + + bool angleValide = (configSysteme.angleSouhaiteTotal >= 40) && + (configSysteme.angleSouhaiteTotal <= 900); + + bool vibValide = (configSysteme.intensiteVibration <= 100); + + bool vitessesValides = (configSysteme.gazAvantMin >= CRSF_VAL_MID && configSysteme.gazAvantMin < CRSF_VAL_MAX) && + (configSysteme.gazAvantMax[0] > configSysteme.gazAvantMin && configSysteme.gazAvantMax[0] <= CRSF_VAL_MAX) && + (configSysteme.gazAvantMax[1] > configSysteme.gazAvantMin && configSysteme.gazAvantMax[1] <= CRSF_VAL_MAX) && + (configSysteme.gazAvantMax[2] > configSysteme.gazAvantMin && configSysteme.gazAvantMax[2] <= CRSF_VAL_MAX) && + (configSysteme.gazArriereMin > CRSF_VAL_MIN && configSysteme.gazArriereMin <= CRSF_VAL_MID) && + (configSysteme.gazArriereMax >= CRSF_VAL_MIN && configSysteme.gazArriereMax < configSysteme.gazArriereMin); + + if (configSysteme.magicNumber != MAGIC_NUMBER_CONFIG || conflitReserve || !canauxValides || !canauxDistincts || !expoValide || !angleValide || !vibValide || !vitessesValides) { + if (conflitReserve) Serial.println("!! Un axe etait mappe sur un canal reserve (ARM/HT) : configuration reinitialisee !!"); + else if (!canauxValides || !canauxDistincts) Serial.println("!! Conflit ou canal invalide en EEPROM : configuration reinitialisee !!"); + else if (!expoValide || !angleValide || !vibValide || !vitessesValides) Serial.println("!! Valeur invalide en EEPROM : configuration reinitialisee !!"); + else Serial.println(">> Initialisation configuration d'usine par defaut..."); + reinitialiserConfigurationDefaut(); + sauvegarderConfiguration(); + } else { + recalculerParametresVolant(); + } +} + diff --git a/firmware/g29_crsf/crsf_protocol.h b/firmware/g29_crsf/crsf_protocol.h new file mode 100644 index 0000000..02c7434 --- /dev/null +++ b/firmware/g29_crsf/crsf_protocol.h @@ -0,0 +1,408 @@ +#pragma once + +void emettreLigneCockpit(const char* ligne); + +// ------------------------------------------------------------------------- +// GESTION LED RGB SUR GP16 +// ------------------------------------------------------------------------- +void actualiserLED() { + uint8_t r = 0, g = 0, b = 0; + uint32_t now = millis(); + uint32_t dtArm = now - momentArmement_ms; + uint32_t dtDesarm = now - momentDesarmement_ms; + + if (momentArmement_ms > 0 && dtArm < 850) { + // Animation NeoPixel a l'armement : alternance vert lumineux et flash blanc + if ((dtArm / 90) % 2 == 0) { + r = 0; g = 255; b = 120; // Vert emeraude + } else { + r = 255; g = 255; b = 255; // Eclat blanc + } + } else if (momentDesarmement_ms > 0 && dtDesarm < 250) { + // Animation NeoPixel au desarmement : flash rouge d'arret + r = 255; g = 20; b = 0; + } 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 + } else { + 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 (!estActuellementArme()) { // Désarmé : couleur du rapport très atténuée + r /= 10; g /= 10; b /= 10; + } + } + rgb_led.setPixelColor(0, rgb_led.Color(r, g, b)); + rgb_led.show(); +} + +// ------------------------------------------------------------------------- +// ENVOI CRSF DEPUIS LA SRAM DU RP2350 +// ------------------------------------------------------------------------- +uint8_t __not_in_flash_func(calculerCrc8Crsf)(const uint8_t* data, size_t len) { + uint8_t crc = 0; + for (size_t i = 0; i < len; i++) { + crc ^= data[i]; + for (int j = 0; j < 8; j++) { + if (crc & 0x80) crc = (crc << 1) ^ 0xD5; + else crc <<= 1; + } + } + return crc; +} + +void __not_in_flash_func(envoyer_paquet_crsf)(bool neutre) { + uint8_t packet[26]; + uint16_t ch[16]; + + for (int i = 0; i < 16; i++) { + ch[i] = neutre ? CRSF_VAL_MID : crsfChannelLoad((uint8_t)i); + } + if (neutre) ch[CANAL_ARM - 1] = CRSF_VAL_MIN; // Failsafe : toujours désarmé + + packet[0] = 0xC8; + packet[1] = 24; + packet[2] = 0x16; + + packet[3] = (uint8_t)(ch[0]); + packet[4] = (uint8_t)((ch[0] >> 8) | (ch[1] << 3)); + packet[5] = (uint8_t)((ch[1] >> 5) | (ch[2] << 6)); + packet[6] = (uint8_t)(ch[2] >> 2); + packet[7] = (uint8_t)((ch[2] >> 10) | (ch[3] << 1)); + packet[8] = (uint8_t)((ch[3] >> 7) | (ch[4] << 4)); + packet[9] = (uint8_t)((ch[4] >> 4) | (ch[5] << 7)); + packet[10] = (uint8_t)(ch[5] >> 1); + packet[11] = (uint8_t)((ch[5] >> 9) | (ch[6] << 2)); + packet[12] = (uint8_t)((ch[6] >> 6) | (ch[7] << 5)); + packet[13] = (uint8_t)(ch[7] >> 3); + packet[14] = (uint8_t)(ch[8]); + packet[15] = (uint8_t)((ch[8] >> 8) | (ch[9] << 3)); + packet[16] = (uint8_t)((ch[9] >> 5) | (ch[10] << 6)); + packet[17] = (uint8_t)(ch[10] >> 2); + packet[18] = (uint8_t)((ch[10] >> 10) | (ch[11] << 1)); + packet[19] = (uint8_t)((ch[11] >> 7) | (ch[12] << 4)); + packet[20] = (uint8_t)((ch[12] >> 4) | (ch[13] << 7)); + packet[21] = (uint8_t)(ch[13] >> 1); + packet[22] = (uint8_t)((ch[13] >> 9) | (ch[14] << 2)); + packet[23] = (uint8_t)((ch[14] >> 6) | (ch[15] << 5)); + packet[24] = (uint8_t)(ch[15] >> 3); + packet[25] = calculerCrc8Crsf(&packet[2], 23); + + Serial1.write(packet, 26); +} + + + +static inline bool coeur1EstSain(uint32_t now) { + if (__atomic_load_n(&core1Demarre, __ATOMIC_ACQUIRE)) { + uint32_t hb = __atomic_load_n(&heartbeatCore1_ms, __ATOMIC_ACQUIRE); + return (now - hb) <= TIMEOUT_FAILSAFE_MS; + } + // Grâce de démarrage de 5 s pour laisser setup1() initialiser PIO-USB ; au-delà, faute Core 1. + return (now - momentDemarrageCore0_ms) <= 5000UL; +} + +// Évalue le failsafe (cœur 0). Retourne true si les canaux doivent être forcés au neutre. +bool evaluerFailsafe() { + uint32_t now = millis(); + + // 1. Surveillance de la santé du Cœur 1 (Watchdog logique inter-cœur) + if (!coeur1EstSain(now)) { + if (!failsafeActif) { + failsafeActif = true; + __atomic_store_n(&majLedRequise, true, __ATOMIC_RELEASE); + Serial.println(F("!! [FAILSAFE] Perte de reponse du Coeur 1 (Watchdog) !!")); + } + return true; + } + + // 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; + } + } + + // Volant branché et Cœur 1 fonctionnel : liaison valide (pas de faux failsafe quand le volant est immobile) + if (failsafeActif) { + failsafeActif = false; + majLedRequise = true; + Serial.println(F("[FAILSAFE] Signal retabli")); + } + return false; +} + +// ------------------------------------------------------------------------- +// RÉCEPTION TÉLÉMÉTRIE CRSF SUR GP1 (Serial1 RX) +// ------------------------------------------------------------------------- +void traiterTelemetrieCRSF() { + static uint8_t crsfRxBuffer[64]; + static uint8_t crsfRxIdx = 0; + static uint8_t paquetLongueurAttendue = 0; + static int16_t prevPitch = 0; + static int16_t prevRoll = 0; + static bool attitudeInitialisee = false; + static uint32_t dernierPaquetTelemetrie_ms = 0; + static uint32_t dernierOctetRx_ms = 0; + + while (Serial1.available() > 0) { + uint32_t now = millis(); + // Timeout inter-octets : réinitialiser l'index si une trame a été interrompue ou parasitée (> 2 ms) + if (crsfRxIdx > 0 && (now - dernierOctetRx_ms > 2)) { + crsfRxIdx = 0; + } + dernierOctetRx_ms = now; + + uint8_t b = Serial1.read(); + + if (crsfRxIdx == 0) { + // Les trames CRSF débutent par une adresse connue (0xC8, 0xEE, 0xEA, 0xEC standard) + if (b == 0xC8 || b == 0xEE || b == 0xEA || b == 0xEC) { + crsfRxBuffer[0] = b; + crsfRxIdx = 1; + paquetLongueurAttendue = 0; + } + } else if (crsfRxIdx == 1) { + paquetLongueurAttendue = b; + if (paquetLongueurAttendue < 2 || paquetLongueurAttendue > 62) { + crsfRxIdx = 0; // Trame invalide, rejet + } else { + crsfRxBuffer[1] = b; + crsfRxIdx = 2; + } + } else { + crsfRxBuffer[crsfRxIdx++] = b; + // Trame complète reçue : taille totale = 2 octets d'en-tête + longueur indiquée + if (crsfRxIdx >= (paquetLongueurAttendue + 2)) { + uint8_t crcAttendu = crsfRxBuffer[paquetLongueurAttendue + 1]; + uint8_t crcCalcule = calculerCrc8Crsf(&crsfRxBuffer[2], paquetLongueurAttendue - 1); + + if (crcCalcule == crcAttendu) { + dernierPaquetTelemetrie_ms = millis(); + uint8_t frameType = crsfRxBuffer[2]; + + if (!estArme || sourceActive != SRC_G29) { + rugositeTerrainExterne = 0; + attitudeInitialisee = false; + } else if (frameType == 0x1E && paquetLongueurAttendue >= 8) { + // Trame d'attitude (0x1E) : Pitch (int16), Roll (int16), Yaw (int16) + int16_t pitch = (int16_t)((crsfRxBuffer[3] << 8) | crsfRxBuffer[4]); + int16_t roll = (int16_t)((crsfRxBuffer[5] << 8) | crsfRxBuffer[6]); + if (!attitudeInitialisee) { + prevPitch = pitch; + prevRoll = roll; + attitudeInitialisee = true; + } else { + int32_t diffP = (int32_t)pitch - (int32_t)prevPitch; + int32_t diffR = (int32_t)roll - (int32_t)prevRoll; + if (diffP > 32767) diffP -= 65536; else if (diffP < -32768) diffP += 65536; + if (diffR > 32767) diffR -= 65536; else if (diffR < -32768) diffR += 65536; + int32_t deltaPitch = abs(diffP); + int32_t deltaRoll = abs(diffR); + prevPitch = pitch; + prevRoll = roll; + + int32_t secousses = deltaPitch + deltaRoll; + // Filtrage des micro-vibrations du FC : seuil mort de 60 (~0.35°) pour ignorer le bruit gyroscopique + if (secousses > 60) { + rugositeTerrainExterne = (uint8_t)constrain(map(secousses, 60, 450, 0, 255), 0, 255); + } else { + rugositeTerrainExterne = 0; + } + } + } + // Trame personnalisée (0x7F ou 0x2A pour accéléromètre brut / rugosité) + else if ((frameType == 0x7F || frameType == 0x2A) && paquetLongueurAttendue >= 3) { + rugositeTerrainExterne = crsfRxBuffer[3]; + } + + // Relais de la télémétrie CRSF valide vers SteamFrame FPV (OSD via Radxa/USB) + // Ne jamais relayer 0x16 (RC_CHANNELS_PACKED) si GP1 reçoit un écho des trames émises + if (frameType != 0x16) { + size_t totalLen = (size_t)paquetLongueurAttendue + 2; + if (totalLen <= 64) { + char bufCrsf[140]; + memcpy(bufCrsf, "$CRSF,", 6); + static const char HEX_DIGITS[] = "0123456789ABCDEF"; + for (size_t i = 0; i < totalLen; i++) { + uint8_t byteVal = crsfRxBuffer[i]; + bufCrsf[6 + i * 2] = HEX_DIGITS[(byteVal >> 4) & 0x0F]; + bufCrsf[6 + i * 2 + 1] = HEX_DIGITS[byteVal & 0x0F]; + } + bufCrsf[6 + totalLen * 2] = '\0'; + emettreLigneCockpit(bufCrsf); + } + } + } + + crsfRxIdx = 0; + } + if (crsfRxIdx >= sizeof(crsfRxBuffer)) { + crsfRxIdx = 0; + } + } + } + + if (!estArme || sourceActive != SRC_G29) { + rugositeTerrainExterne = 0; + attitudeInitialisee = false; + return; + } + + if (dernierPaquetTelemetrie_ms > 0 && (millis() - dernierPaquetTelemetrie_ms > 500)) { + attitudeInitialisee = false; + } + + // Décroissance douce de la rugosité si la télémétrie ne transmet plus depuis > 200 ms + if (rugositeTerrainExterne > 0 && (millis() - dernierPaquetTelemetrie_ms > 200)) { + static uint32_t dernierDecul = 0; + if (millis() - dernierDecul >= 50) { + dernierDecul = millis(); + rugositeTerrainExterne = (rugositeTerrainExterne > 10) ? (rugositeTerrainExterne - 10) : 0; + } + } +} + +void emettreLigneCockpit(const char* ligne) { + char framed[192]; + const char* toSend = ligne; + // Ajouter un CRC-8 DVB-S2 (*XX) sur les trames $G29 et $G29_EVT (protège la liaison UART 460k) + if (strncmp(ligne, "$G29,", 5) == 0 || strncmp(ligne, "$G29_EVT,", 9) == 0) { + size_t len = strlen(ligne); + if (len + 4 < sizeof(framed)) { + uint8_t crc = calculerCrc8Crsf((const uint8_t*)ligne, len); + snprintf(framed, sizeof(framed), "%s*%02X", ligne, crc); + toSend = framed; + } + } + int needed = (int)strlen(toSend) + 2; + // SerialUART::availableForWrite() sur arduino-pico renvoie >= 1 si de la place est libre en FIFO + if (Serial2.availableForWrite() > 0) { + Serial2.println(toSend); + } + if (cockpitEchoUSB && Serial && Serial.availableForWrite() >= needed) { + Serial.println(toSend); + } +} + +void gererSortieCockpit() { + static uint32_t dernierEnvoiCockpit_ms = 0; + + // 1. Émission immédiate des événements boutons (consommation atomique inter-cœurs) + uint16_t evts = __atomic_exchange_n(&evtBoutonsMasque, 0, __ATOMIC_ACQ_REL); + if (evts != 0) { + struct BoutonNom { uint16_t bit; const char* nom; }; + static const BoutonNom TABLE_BOUTONS[] = { + { EVT_BTN_CROSS, "CROSS" }, + { EVT_BTN_CIRCLE, "CIRCLE" }, + { EVT_BTN_SQUARE, "SQUARE" }, + { EVT_BTN_TRIANGLE, "TRIANGLE" }, + { EVT_BTN_SHARE, "SHARE" }, + { EVT_BTN_OPTIONS, "OPTIONS" }, + { EVT_BTN_PS, "PS" }, + { EVT_BTN_L3, "L3" }, + { EVT_BTN_R3, "R3" }, + { EVT_BTN_DPAD_UP, "DPAD_UP" }, + { EVT_BTN_DPAD_DOWN, "DPAD_DOWN" }, + { EVT_BTN_DPAD_LEFT, "DPAD_LEFT" }, + { EVT_BTN_DPAD_RIGHT, "DPAD_RIGHT" }, + }; + char bufEvt[32]; + for (size_t i = 0; i < sizeof(TABLE_BOUTONS) / sizeof(TABLE_BOUTONS[0]); i++) { + if (evts & TABLE_BOUTONS[i].bit) { + snprintf(bufEvt, sizeof(bufEvt), "$G29_EVT,BTN=%s", TABLE_BOUTONS[i].nom); + emettreLigneCockpit(bufEvt); + } + } + } + + // 2. Trame d'état cockpit à 20 Hz ou immédiatement sur changement critique + uint32_t now = millis(); + bool modif = __atomic_exchange_n(&cockpitEtatModifie, false, __ATOMIC_ACQ_REL); + if (modif || (now - dernierEnvoiCockpit_ms >= INTERVALLE_COCKPIT_MS)) { + dernierEnvoiCockpit_ms = now; + 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); + int clutch = (sourceActive == SRC_EXT) + ? (int)extEmbrayagePct + : (int)constrain(dernierEmbrayagePct + 0.5f, 0.0f, 100.0f); + int32_t dMax = (maxDeltaVolant > 0) ? maxDeltaVolant : DELTA_MAX_VOLANT_BRUT; + int steer = (sourceActive == SRC_EXT) + ? (int)extVolantPct + : (int)constrain(((float)dernierVolantCentre / (float)dMax) * 100.0f, -100.0f, 100.0f); + uint16_t ch1 = failsafeActif ? CRSF_VAL_MID : crsfChannelLoad(configSysteme.volant - 1); + uint16_t ch2 = failsafeActif ? CRSF_VAL_MID : crsfChannelLoad(configSysteme.accel - 1); + uint16_t ch3 = failsafeActif ? CRSF_VAL_MID : crsfChannelLoad(configSysteme.frein - 1); + uint16_t ch4 = failsafeActif ? CRSF_VAL_MID : crsfChannelLoad(configSysteme.embrayage - 1); + const char* srcStr = (sourceActive == SRC_EXT) ? "EXT" : "G29"; + char bufEtat[176]; + snprintf(bufEtat, sizeof(bufEtat), + "$G29,ARM=%d,GEAR=%d,THROT=%d,BRAKE=%d,CLUTCH=%d,STEER=%d,CH1=%u,CH2=%u,CH3=%u,CH4=%u,FFB=%d,VIB=%d,FAIL=%d,SRC=%s", + armeOut ? 1 : 0, + (int)rapportOut, + throt, + brake, + clutch, + steer, + (unsigned int)ch1, + (unsigned int)ch2, + (unsigned int)ch3, + (unsigned int)ch4, + (int)configSysteme.forceRessort, + (int)configSysteme.intensiteVibration, + failsafeActif ? 1 : 0, + srcStr); + emettreLigneCockpit(bufEtat); + } +} + +void gererTimeoutHeadTracking() { + if (htActif && (millis() - dernierPaquetHT_ms > TIMEOUT_HT_MS)) { + htActif = false; + crsfChannelStore(CANAL_HT_PAN - 1, CRSF_VAL_MID); + crsfChannelStore(CANAL_HT_TILT - 1, CRSF_VAL_MID); + crsfChannelStore(CANAL_HT_ROLL - 1, CRSF_VAL_MID); + } +} + +void gererTimeoutRcExterne() { + if (sourceActive == SRC_EXT && extRcActif && (millis() - dernierPaquetRC_ms > TIMEOUT_RC_EXT_MS)) { + extRcActif = false; + extArme = false; + extAccelPct = 0; + extFreinPct = 0; + extEmbrayagePct = 0; + extVolantPct = 0; + reinitialiserCanauxCRSF(); + majLedRequise = true; + cockpitEtatModifie = true; + Serial.println(F("!! [FAILSAFE] Perte de liaison Steam Controller ($RC timeout) !!")); + } +} + diff --git a/firmware/g29_crsf/g29_crsf.ino b/firmware/g29_crsf/g29_crsf.ino index bb65810..c2c043e 100644 --- a/firmware/g29_crsf/g29_crsf.ino +++ b/firmware/g29_crsf/g29_crsf.ino @@ -1,956 +1,7 @@ -#include -#include -#include -#include -#include -#include - -// Brochage natif de la Waveshare RP2350-USB-A -#define HOST_PIN_DP 12 // USB-A D+ (D- est automatiquement sur GP13) -#define NUM_PIXELS 1 -#define PIN_LED_RGB 16 // LED RGB WS2812 intégrée -#define EEPROM_SIZE 32 - -// Sécurité : failsafe, watchdog et identification du volant -#define TIMEOUT_FAILSAFE_MS 1000 // Watchdog inter-coeur : alerte si le coeur 1 ne repond plus depuis X ms -#define WATCHDOG_TIMEOUT_MS 1000 // Reboot materiel si le coeur 0 se fige -#define G29_VID 0x046D -#define G29_PID_PS4 0xC260 // G29 en mode PS4 (le mode PS3 = 0xC24F a un autre format de rapport) -#define G29_REPORT_ID 0x01 - -// Masques additionnels dans report[5] (D-Pad et boutons façade en mode PS4) -#define DPAD_MASK_B5 0x0F // Quartet bas : 0=Haut, 2=Droite, 4=Bas, 6=Gauche, 8=Neutre -#define BOUTON_CARRE_MASK 0x10 // Carré [□] -#define BOUTON_CROIX_MASK 0x20 // Croix [✕] -#define BOUTON_ROND_MASK 0x40 // Rond [○] -#define BOUTON_TRIANGLE_MASK 0x80 // Triangle [△] - -// Masques des palettes et boutons dans report[6] -#define PALETTE_MOINS_MASK 0x01 // L1 (Palette gauche : Rétrograder) -#define PALETTE_PLUS_MASK 0x02 // R1 (Palette droite : Monter un rapport) -#define BOUTON_L2_MASK 0x04 // L2 -#define BOUTON_ARM_MASK 0x08 // R2 (Bascule Armé / Désarmé) -#define BOUTON_SHARE_MASK 0x10 // Share -#define BOUTON_OPTIONS_MASK 0x20 // Options -#define BOUTON_L3_MASK 0x40 // L3 -#define BOUTON_R3_MASK 0x80 // R3 - -// Masques additionnels dans report[54] (Molette et boutons + / - / Enter en mode PS4 PID 0xC260) -#define DIAL_ENTER_MASK_B54 0x01 // Bouton central de la molette -#define DIAL_CCW_MASK_B54 0x02 // Molette sens anti-horaire (Dureté -) -#define DIAL_CW_MASK_B54 0x04 // Molette sens horaire (Dureté +) -#define BOUTON_MOINS_MASK_B54 0x08 // Bouton [-] (Dureté -) -#define BOUTON_PLUS_MASK_B54 0x10 // Bouton [+] (Dureté +) - -// Masques de secours dans report[7] (Mode PC / rapport court + bouton PS) -#define BOUTON_PS_MASK_B7 0x01 // Bouton PS -#define BOUTON_PLUS_MASK_B7 0x04 // Bouton [+] -#define BOUTON_MOINS_MASK_B7 0x08 // Bouton [-] -#define DIAL_CW_MASK_B7 0x10 // Molette sens horaire -#define DIAL_CCW_MASK_B7 0x20 // Molette sens anti-horaire -#define DIAL_ENTER_MASK_B7 0x40 // Bouton central de la molette - -// Liaison série bidirectionnelle vers le pont Radxa Zero 3W / SteamFrame FPV Cockpit -#define PIN_UART_BRIDGE_TX 4 -#define PIN_UART_BRIDGE_RX 5 -#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 { - EVT_BTN_CROSS = (1 << 0), - EVT_BTN_CIRCLE = (1 << 1), - EVT_BTN_SQUARE = (1 << 2), - EVT_BTN_TRIANGLE = (1 << 3), - EVT_BTN_SHARE = (1 << 4), - EVT_BTN_OPTIONS = (1 << 5), - EVT_BTN_PS = (1 << 6), - EVT_BTN_L3 = (1 << 7), - EVT_BTN_R3 = (1 << 8), - EVT_BTN_DPAD_UP = (1 << 9), - EVT_BTN_DPAD_DOWN = (1 << 10), - EVT_BTN_DPAD_LEFT = (1 << 11), - EVT_BTN_DPAD_RIGHT = (1 << 12), -}; - -// Armement ELRS : AUX1 = canal 5 (réservé, ne peut pas être mappé ailleurs) -#define CANAL_ARM 5 - -// Head-Tracking Steam Frame : AUX2..AUX4 = canaux 6, 7, 8 (Pan, Tilt, Roll) -#define CANAL_HT_PAN 6 -#define CANAL_HT_TILT 7 -#define CANAL_HT_ROLL 8 - -// Bornes officielles CRSF -#define CRSF_VAL_MIN 172 // ~988 us -#define CRSF_VAL_MID 992 // 1500 us (Neutre) -#define CRSF_VAL_MAX 1811 // ~2012 us - -// Plages de gaz progressives (Marche avant : rapports 1, 2, 3) -#define GAZ_AVANT_MIN 1065 -const uint16_t GAZ_AVANT_MAX_PAR_VITESSE[3] = { - 1100, // 1ère vitesse (Manœuvre) - 1150, // 2ème vitesse (Normale) - 1220 // 3ème vitesse (Rapide) -}; - -#define GAZ_ARRIERE_MIN 905 -#define GAZ_ARRIERE_MAX 800 -#define DEADZONE_PEDALE 800 - -// Configuration par défaut du volant G29 -#define CENTRE_VOLANT_BRUT 32768 -#define DELTA_MAX_VOLANT_BRUT 31600 // ~96,4% de la demi-course (début de la butée logicielle) -#define HYSTERESIS_MUR_BRUT 450 // ~1,6° de marge pour repousser franchement sans osciller -#define ANGLE_DEFAUT_TOTAL 240.0f // Plage totale par defaut : 240 degres (+/- 120 degres) -#define EXPO_DEFAUT 0.25f // 0.0f = Lineaire, 0.25f = Doux au centre (FPU RP2350) -#define FORCE_RESSORT_DEFAUT 140 // Force du retour au centre : 0 a 255 -#define PENTE_RESSORT_G29 7 // Raideur autour du centre : 1 a 7 -#define ETAPES_INIT_FFB_TOTAL 2 // Nombre d'etapes d'init FFB initiales (0=Range, 1=Spring) -#define VIBRATION_DEFAUT 50 // Intensite par defaut des vibrations (0 a 100%) -#define MAGIC_NUMBER_CONFIG 0x4B // Identifiant de validite en EEPROM (mis a jour pour vitesses CRSF) - -Adafruit_NeoPixel rgb_led(NUM_PIXELS, PIN_LED_RGB, NEO_GRB + NEO_KHZ800); -Adafruit_USBH_Host USBHost; - -volatile uint16_t crsf_channels[16] = { - CRSF_VAL_MID, CRSF_VAL_MID, CRSF_VAL_MID, CRSF_VAL_MID, - CRSF_VAL_MIN, CRSF_VAL_MID, CRSF_VAL_MID, CRSF_VAL_MID, // Canal 5 (ARM) : désarmé - CRSF_VAL_MID, CRSF_VAL_MID, CRSF_VAL_MID, CRSF_VAL_MID, - CRSF_VAL_MID, CRSF_VAL_MID, CRSF_VAL_MID, CRSF_VAL_MID -}; - -struct __attribute__((packed)) ConfigG29 { - uint8_t volant; - uint8_t accel; - uint8_t frein; - uint8_t embrayage; - uint8_t forceRessort; // Force du retour au centre : 0 à 255 - uint16_t angleSouhaiteTotal; // Plage totale en degrés : 40 à 900 - float expoVolant; // Expo volant : 0.0f à 0.8f - uint8_t intensiteVibration; // Intensité globale des vibrations : 0 à 100% - uint16_t gazAvantMin; // Seuil de démarrage marche avant (défaut 1065) - uint16_t gazAvantMax[3]; // Plafonds 1ère, 2ème, 3ème vitesse - uint16_t gazArriereMin; // Seuil de démarrage marche arrière (défaut 905) - uint16_t gazArriereMax; // Plafond marche arrière (défaut 800) - uint8_t magicNumber; // Identifiant de validité en EEPROM (MAGIC_NUMBER_CONFIG) -}; - -volatile ConfigG29 configSysteme; -volatile int32_t maxDeltaVolant = 0; - -void recalculerParametresVolant() { - // Le G29 en mode PS4 redistribue ses 65535 points (16-bit) sur la plage configurée par cmdRange. - // La butée démarre à DELTA_MAX_VOLANT_BRUT (31600 points, ~96,4% de demi-course) - // pour permettre l'allumage franc des 5 LEDs RPM en butée extrême. - maxDeltaVolant = DELTA_MAX_VOLANT_BRUT; -} - -// Boîte séquentielle : -1 = R, 0 = N (Point Mort), 1 = 1ère, 2 = 2ème, 3 = 3ème -volatile int8_t rapportEngage = 0; -volatile bool palettePlusDejaEnfoncee = false; -volatile bool paletteMoinsDejaEnfoncee = false; -volatile bool majLedRequise = true; - -// Armement (bascule par R2) : écrit uniquement par le cœur 1 -volatile bool estArme = false; -volatile bool boutonArmDejaEnfonce = false; -volatile int8_t logArmRequis = 0; // 1 = armé, -1 = désarmé, 2 = armement refusé - -// État USB Host et diagnostic inter-cœurs -volatile uint8_t g29_dev_addr = 0; -volatile uint8_t g29_instance = 0; -volatile uint16_t g29_desc_len = 0; -volatile uint16_t g29_vid = 0; -volatile uint16_t g29_pid = 0; -volatile bool volant_est_pret = false; -volatile uint32_t dernierRapportUSB_ms = 0; -volatile uint32_t momentConnexionUSB_ms = 0; -volatile bool logMountRequis = false; -volatile int8_t statutEnvoiLed = 0; -volatile uint32_t heartbeatCore1_ms = 0; // Surveillance santé Cœur 1 (Watchdog dual-core) -volatile bool core1Demarre = false; // Passe à true dès le premier tour de loop1() -uint32_t momentDemarrageCore0_ms = 0; // Grâce de démarrage Cœur 1 (5 s max) - -// Failsafe et diagnostic -volatile bool failsafeActif = true; // Écrit uniquement par le cœur 0 -volatile uint32_t compteurRapportsOK = 0; // Écrit uniquement par le cœur 1 -volatile uint32_t compteurRapportsRejetes = 0; -volatile uint16_t dernierRejetLen = 0; -volatile uint8_t dernierRejetId = 0; -volatile bool logRejetRequis = false; -volatile uint16_t rejet_vid = 0; -volatile uint16_t rejet_pid = 0; - -volatile uint8_t dernierMasqueLedG29 = 0xFF; -volatile uint8_t etapeEnvoiLed = 0; -volatile uint8_t etapeInitMoteur = 0; -volatile bool reinitPlageTardiveFaite = false; - -// Variables pour le réglage FFB à la volée (Molette / Boutons +/- et Série) -volatile bool majRessortRequise = false; -volatile bool majRangeRequise = false; -volatile bool dialPlusDejaEnfonce = false; -volatile bool dialMoinsDejaEnfonce = false; -volatile bool dialEnterDejaEnfonce = false; -volatile bool btnPlusDejaEnfonce = false; -volatile bool btnMoinsDejaEnfonce = false; -volatile uint32_t momentDernierChangementDurete_ms = 0; -volatile uint32_t momentDernierChangementVib_ms = 0; -volatile bool logDureteRequis = false; -volatile bool logVibrationRequis = false; -volatile bool demandeSauvegardeEEPROM = false; -volatile bool sauvegardeDifferee = false; -volatile uint32_t momentArmement_ms = 0; -volatile uint32_t momentDesarmement_ms = 0; - -// Variables pour les vibrations haptiques et la télémétrie -volatile uint8_t rugositeTerrainExterne = 0; // 0 à 255 (pilotable via CRSF télémétrie / FC) -volatile float dernierAccelPct = 0.0f; // 0.0 à 100.0% -volatile float dernierFreinPct = 0.0f; // 0.0 à 100.0% -volatile float dernierEmbrayagePct = 0.0f; // 0.0 à 100.0% -volatile uint32_t momentDernierChocRapport_ms = 0; // Horodatage du passage de vitesse -volatile int8_t directionDernierChocRapport = 0; // -1 gauche, +1 droite -volatile bool forceEstAuNeutre = false; -volatile int32_t dernierVolantCentre = 0; // Position mesurée du volant par rapport au centre -volatile bool murActifDroite = false; -volatile bool murActifGauche = false; - -// Variables de télémétrie, Head-Tracking & événements boutons vers SteamFrame FPV (Radxa / USB) -volatile uint16_t evtBoutonsMasque = 0; -volatile bool cockpitEtatModifie = true; -volatile uint16_t etatBoutonsCockpitPrec = 0xFFFF; // Ignore tout bouton maintenu au branchement -volatile uint8_t etatDpadPrec = 0xFF; -bool cockpitEchoUSB = true; // Actif par défaut pour liaison directe USB-C (/dev/ttyACM0) -uint32_t dernierPaquetHT_ms = 0; -volatile 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 uint8_t extEmbrayagePct = 0; -volatile int8_t extVolantPct = 0; -volatile uint32_t dernierPaquetRC_ms = 0; - -static inline uint16_t crsfChannelLoad(uint8_t idx) { - return __atomic_load_n(&crsf_channels[idx], __ATOMIC_RELAXED); -} - -static inline void crsfChannelStore(uint8_t idx, uint16_t val) { - __atomic_store_n(&crsf_channels[idx], val, __ATOMIC_RELAXED); -} - -static inline bool estActuellementArme() { - uint8_t src = __atomic_load_n(&sourceActive, __ATOMIC_ACQUIRE); - return (src == SRC_EXT) - ? __atomic_load_n(&extArme, __ATOMIC_ACQUIRE) - : __atomic_load_n(&estArme, __ATOMIC_ACQUIRE); -} - -static inline int8_t rapportActuel() { - uint8_t src = __atomic_load_n(&sourceActive, __ATOMIC_ACQUIRE); - return (src == SRC_EXT) - ? __atomic_load_n(&extRapport, __ATOMIC_ACQUIRE) - : __atomic_load_n(&rapportEngage, __ATOMIC_ACQUIRE); -} - -static inline void assignerCanalCRSF(uint8_t numeroCh, uint16_t valeur11bits) { - if (numeroCh >= 1 && numeroCh <= 16 && numeroCh != CANAL_ARM) { - crsfChannelStore(numeroCh - 1, valeur11bits); - } -} - -char serialBuffer[96]; -uint8_t serialBufferIdx = 0; -bool serialBufferOverflow = false; -char serial2Buffer[96]; -uint8_t serial2BufferIdx = 0; -bool serial2BufferOverflow = false; - -static inline bool estCanalReserve(uint8_t ch) { - return (ch == CANAL_ARM) || (ch == CANAL_HT_PAN) || (ch == CANAL_HT_TILT) || (ch == CANAL_HT_ROLL); -} - -void reinitialiserCanauxCRSF() { - bool ht = __atomic_load_n(&htActif, __ATOMIC_ACQUIRE); - for (int i = 0; i < 16; i++) { - if (ht && (i == (CANAL_HT_PAN - 1) || i == (CANAL_HT_TILT - 1) || i == (CANAL_HT_ROLL - 1))) { - continue; - } - crsfChannelStore((uint8_t)i, CRSF_VAL_MID); - } - crsfChannelStore(CANAL_ARM - 1, CRSF_VAL_MIN); // Toujours désarmé par défaut -} - -void reinitialiserConfigurationDefaut() { - memset((void*)&configSysteme, 0, sizeof(ConfigG29)); - configSysteme.volant = 1; - configSysteme.accel = 3; // AETR : CH3 = Gaz / ESC - configSysteme.frein = 2; // AETR : CH2 = Frein - configSysteme.embrayage = 4; - configSysteme.forceRessort = FORCE_RESSORT_DEFAUT; - configSysteme.angleSouhaiteTotal = ANGLE_DEFAUT_TOTAL; - configSysteme.expoVolant = EXPO_DEFAUT; - configSysteme.intensiteVibration = VIBRATION_DEFAUT; - configSysteme.gazAvantMin = GAZ_AVANT_MIN; - configSysteme.gazAvantMax[0] = GAZ_AVANT_MAX_PAR_VITESSE[0]; - configSysteme.gazAvantMax[1] = GAZ_AVANT_MAX_PAR_VITESSE[1]; - configSysteme.gazAvantMax[2] = GAZ_AVANT_MAX_PAR_VITESSE[2]; - configSysteme.gazArriereMin = GAZ_ARRIERE_MIN; - configSysteme.gazArriereMax = GAZ_ARRIERE_MAX; - configSysteme.magicNumber = MAGIC_NUMBER_CONFIG; - recalculerParametresVolant(); -} - -void sauvegarderConfiguration() { - ConfigG29 cfgActuelle; - // Geler brièvement le Cœur 1 pour garantir un instantané cohérent de configSysteme. - rp2040.idleOtherCore(); - memcpy(&cfgActuelle, (const void*)&configSysteme, sizeof(ConfigG29)); - rp2040.resumeOtherCore(); - - ConfigG29 cfgStockee; - EEPROM.get(0, cfgStockee); - - if (memcmp(&cfgActuelle, &cfgStockee, sizeof(ConfigG29)) == 0) { - return; // Déjà synchronisé : évite un gel du Cœur 1 et préserve les cycles Flash - } - - rp2040.wdt_reset(); - // Note : EEPROM.commit() gère déjà automatiquement idleOtherCore() / resumeOtherCore() - EEPROM.put(0, cfgActuelle); - EEPROM.commit(); - Serial.println(">> Configuration sauvegardée en mémoire Flash !"); -} - -void afficherConfiguration() { - Serial.println("\n--- Configuration G29-CRSF (Waveshare RP2350-USB-A) ---"); - Serial.printf("Volant (V) : Canal %d\n", configSysteme.volant); - Serial.printf("Accel (A) : Canal %d\n", configSysteme.accel); - Serial.printf("Frein (F) : Canal %d\n", configSysteme.frein); - Serial.printf("Embrayage (E) : Canal %d\n", configSysteme.embrayage); - Serial.printf("ARM (R2) : Canal %d (reserve)\n", CANAL_ARM); - Serial.printf("Durete FFB (D) : %d / 255 (%d%%) [Molette rouge ou D=xxx]\n", - 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.printf("Vitesses CRSF : AV_MIN=%u | 1=%u | 2=%u | 3=%u | AR_MIN=%u | AR_MAX=%u\n", - configSysteme.gazAvantMin, - configSysteme.gazAvantMax[0], - configSysteme.gazAvantMax[1], - configSysteme.gazAvantMax[2], - configSysteme.gazArriereMin, - configSysteme.gazArriereMax); - Serial.println("Commandes : V=ch, A=ch, F=ch, E=ch, D=val, P=val, X=val, T=val, $SRC,G29|EXT, $GEARS,..., $RC,..., $HT,..., S(save), R(reset), B(bootsel), ?"); -} - -void chargerConfiguration() { - ConfigG29 cfgStockee; - EEPROM.get(0, cfgStockee); - memcpy((void*)&configSysteme, &cfgStockee, sizeof(ConfigG29)); - - bool conflitReserve = estCanalReserve(configSysteme.volant) || estCanalReserve(configSysteme.accel) || - estCanalReserve(configSysteme.frein) || estCanalReserve(configSysteme.embrayage); - - bool canauxValides = (configSysteme.volant >= 1 && configSysteme.volant <= 16) && - (configSysteme.accel >= 1 && configSysteme.accel <= 16) && - (configSysteme.frein >= 1 && configSysteme.frein <= 16) && - (configSysteme.embrayage >= 1 && configSysteme.embrayage <= 16); - - bool canauxDistincts = (configSysteme.volant != configSysteme.accel) && - (configSysteme.volant != configSysteme.frein) && - (configSysteme.volant != configSysteme.embrayage) && - (configSysteme.accel != configSysteme.frein) && - (configSysteme.accel != configSysteme.embrayage) && - (configSysteme.frein != configSysteme.embrayage); - - bool expoValide = !isnan(configSysteme.expoVolant) && - (configSysteme.expoVolant >= 0.0f) && - (configSysteme.expoVolant <= 0.8f); - - bool angleValide = (configSysteme.angleSouhaiteTotal >= 40) && - (configSysteme.angleSouhaiteTotal <= 900); - - bool vibValide = (configSysteme.intensiteVibration <= 100); - - bool vitessesValides = (configSysteme.gazAvantMin >= CRSF_VAL_MID && configSysteme.gazAvantMin < CRSF_VAL_MAX) && - (configSysteme.gazAvantMax[0] > configSysteme.gazAvantMin && configSysteme.gazAvantMax[0] <= CRSF_VAL_MAX) && - (configSysteme.gazAvantMax[1] > configSysteme.gazAvantMin && configSysteme.gazAvantMax[1] <= CRSF_VAL_MAX) && - (configSysteme.gazAvantMax[2] > configSysteme.gazAvantMin && configSysteme.gazAvantMax[2] <= CRSF_VAL_MAX) && - (configSysteme.gazArriereMin > CRSF_VAL_MIN && configSysteme.gazArriereMin <= CRSF_VAL_MID) && - (configSysteme.gazArriereMax >= CRSF_VAL_MIN && configSysteme.gazArriereMax < configSysteme.gazArriereMin); - - if (configSysteme.magicNumber != MAGIC_NUMBER_CONFIG || conflitReserve || !canauxValides || !canauxDistincts || !expoValide || !angleValide || !vibValide || !vitessesValides) { - if (conflitReserve) Serial.println("!! Un axe etait mappe sur un canal reserve (ARM/HT) : configuration reinitialisee !!"); - else if (!canauxValides || !canauxDistincts) Serial.println("!! Conflit ou canal invalide en EEPROM : configuration reinitialisee !!"); - else if (!expoValide || !angleValide || !vibValide || !vitessesValides) Serial.println("!! Valeur invalide en EEPROM : configuration reinitialisee !!"); - else Serial.println(">> Initialisation configuration d'usine par defaut..."); - reinitialiserConfigurationDefaut(); - sauvegarderConfiguration(); - } else { - recalculerParametresVolant(); - } -} - -// ------------------------------------------------------------------------- -// GESTION SÉRIE NON BLOQUANTE -// ------------------------------------------------------------------------- -void demanderOuExecuterSauvegarde() { - if (estActuellementArme()) { - sauvegardeDifferee = true; - Serial.println(">> Modification appliquee (sauvegarde Flash differee au desarmement)."); - } else { - momentDernierChangementDurete_ms = 0; - sauvegardeDifferee = false; - sauvegarderConfiguration(); - } -} - -static bool parseStrictInt(const char* s, int& outVal) { - if (!s || *s == '\0') return false; - char* endPtr = nullptr; - long v = strtol(s, &endPtr, 10); - if (endPtr == s || *endPtr != '\0') return false; - outVal = (int)v; - return true; -} - -static bool parseStrictFloat(const char* s, float& outVal) { - if (!s || *s == '\0') return false; - char* endPtr = nullptr; - float v = strtof(s, &endPtr); - if (endPtr == s || *endPtr != '\0' || isnan(v) || isinf(v)) return false; - outVal = v; - return true; -} - -uint8_t calculerCrc8Crsf(const uint8_t* data, size_t len); - -void traiterLigneSerie(char* commande, bool depuisUsb) { - // Sécurité : les commandes CLI sans CRC (B=BOOTSEL, R=Reset, V=/A=/F=/E=...) ne sont - // acceptées QUE sur l'USB local (Serial), jamais sur l'UART Radxa / UDP (Serial2). - if (!depuisUsb && commande[0] != '$') { - return; - } - - if (commande[0] == '?') { - afficherConfiguration(); - return; - } - if (commande[0] == 'B' || commande[0] == 'b') { - if (estActuellementArme()) { - Serial.println("!! Redemarrage BOOTSEL refuse pendant la conduite (desarmer d'abord) !!"); - return; - } - Serial.println(">> Redemarrage en mode BOOTSEL..."); - Serial.flush(); - rp2040.rebootToBootloader(); - return; - } - if (commande[0] == 'S' || commande[0] == 's') { - if (estActuellementArme()) { - Serial.println("!! Sauvegarde Flash refusee pendant la conduite (desarmer d'abord) !!"); - return; - } - momentDernierChangementDurete_ms = 0; - sauvegardeDifferee = false; - sauvegarderConfiguration(); - return; - } - if (commande[0] == 'R' || commande[0] == 'r') { - if (estActuellementArme()) { - Serial.println("!! Reinitialisation refusee pendant la conduite (desarmer d'abord) !!"); - return; - } - rp2040.idleOtherCore(); - reinitialiserConfigurationDefaut(); - reinitialiserCanauxCRSF(); - rapportEngage = 0; - estArme = false; - extArme = false; - extRapport = 0; - extAccelPct = 0; - extFreinPct = 0; - extEmbrayagePct = 0; - extVolantPct = 0; - extRcActif = false; - __atomic_store_n(&sourceActive, SRC_G29, __ATOMIC_RELEASE); - __atomic_store_n(&majLedRequise, true, __ATOMIC_RELEASE); - __atomic_store_n(&cockpitEtatModifie, true, __ATOMIC_RELEASE); - momentDernierChangementDurete_ms = 0; - sauvegardeDifferee = false; - rp2040.resumeOtherCore(); - __atomic_store_n(&majRangeRequise, true, __ATOMIC_RELEASE); - __atomic_store_n(&majRessortRequise, true, __ATOMIC_RELEASE); - sauvegarderConfiguration(); - afficherConfiguration(); - return; - } - if (strlen(commande) >= 3 && commande[1] == '=') { - char periph = commande[0]; - if (periph == 'V' || periph == 'v' || periph == 'A' || periph == 'a' || - periph == 'F' || periph == 'f' || periph == 'E' || periph == 'e') { - if (estActuellementArme()) { - Serial.println("!! Remappage des canaux refuse pendant la conduite (desarmer d'abord) !!"); - return; - } - int nouveauCanal = 0; - if (!parseStrictInt(&commande[2], nouveauCanal) || nouveauCanal < 1 || nouveauCanal > 16) { - Serial.println("!! Canal invalide : doit etre un entier entre 1 et 16 !!"); - return; - } - if (estCanalReserve((uint8_t)nouveauCanal)) { - Serial.printf("!! Canal %d reserve (ARM=CH%d, HT=CH%d..CH%d) !!\n", - nouveauCanal, CANAL_ARM, CANAL_HT_PAN, CANAL_HT_ROLL); - return; - } - - uint8_t cV = configSysteme.volant; - uint8_t cA = configSysteme.accel; - uint8_t cF = configSysteme.frein; - uint8_t cE = configSysteme.embrayage; - bool conflit = false; - switch (periph) { - case 'V': case 'v': if (nouveauCanal == cA || nouveauCanal == cF || nouveauCanal == cE) conflit = true; break; - case 'A': case 'a': if (nouveauCanal == cV || nouveauCanal == cF || nouveauCanal == cE) conflit = true; break; - case 'F': case 'f': if (nouveauCanal == cV || nouveauCanal == cA || nouveauCanal == cE) conflit = true; break; - case 'E': case 'e': if (nouveauCanal == cV || nouveauCanal == cA || nouveauCanal == cF) conflit = true; break; - } - if (conflit) { - Serial.printf("!! Conflit : le canal %d est deja utilise par un autre axe !!\n", nouveauCanal); - return; - } - - rp2040.idleOtherCore(); - switch (periph) { - case 'V': case 'v': configSysteme.volant = nouveauCanal; break; - case 'A': case 'a': configSysteme.accel = nouveauCanal; break; - case 'F': case 'f': configSysteme.frein = nouveauCanal; break; - case 'E': case 'e': configSysteme.embrayage = nouveauCanal; break; - } - reinitialiserCanauxCRSF(); - rp2040.resumeOtherCore(); - sauvegarderConfiguration(); - afficherConfiguration(); - } else if (periph == 'D' || periph == 'd') { - int val = 0; - if (parseStrictInt(&commande[2], val) && val >= 0 && val <= 255) { - configSysteme.forceRessort = (uint8_t)val; // Atomique sur ARM Cortex-M33 - __atomic_store_n(&majRessortRequise, true, __ATOMIC_RELEASE); - demanderOuExecuterSauvegarde(); - afficherConfiguration(); - } else { - Serial.println("!! Durete (D) doit etre un entier entre 0 et 255 !!"); - } - } else if (periph == 'P' || periph == 'p') { - if (estActuellementArme()) { - Serial.println("!! Reglage de plage (P) refuse pendant la conduite (desarmer d'abord) !!"); - return; - } - int val = 0; - if (parseStrictInt(&commande[2], val) && val >= 40 && val <= 900) { - rp2040.idleOtherCore(); - configSysteme.angleSouhaiteTotal = (uint16_t)val; - recalculerParametresVolant(); - rp2040.resumeOtherCore(); - __atomic_store_n(&majRangeRequise, true, __ATOMIC_RELEASE); - sauvegarderConfiguration(); - afficherConfiguration(); - } else { - Serial.println("!! Plage d'angle (P) doit etre un entier entre 40 et 900 degres !!"); - } - } else if (periph == 'X' || periph == 'x') { - if (estActuellementArme()) { - Serial.println("!! Reglage d'expo (X) refuse pendant la conduite (desarmer d'abord) !!"); - return; - } - float val = 0.0f; - if (parseStrictFloat(&commande[2], val) && val >= 0.0f && val <= 0.8f) { - rp2040.idleOtherCore(); - configSysteme.expoVolant = val; - rp2040.resumeOtherCore(); - sauvegarderConfiguration(); - afficherConfiguration(); - } else { - Serial.println("!! Expo volant (X) doit etre un nombre entre 0.0 et 0.8 !!"); - } - } else if (periph == 'T' || periph == 't') { - int val = 0; - if (parseStrictInt(&commande[2], val) && val >= 0 && val <= 100) { - configSysteme.intensiteVibration = (uint8_t)val; // Atomique sur ARM Cortex-M33 - __atomic_store_n(&cockpitEtatModifie, true, __ATOMIC_RELEASE); - demanderOuExecuterSauvegarde(); - afficherConfiguration(); - } else { - Serial.println("!! Vibrations (T) doit etre un entier entre 0 et 100% !!"); - } - } else if (periph == 'W' || periph == 'w') { - int val = 0; - if (parseStrictInt(&commande[2], val)) { - cockpitEchoUSB = (val != 0); - Serial.printf(">> [COCKPIT] Echo trames $G29 sur USB : %s\n", cockpitEchoUSB ? "ON" : "OFF"); - } - } - return; - } - - // Validation CRC-8 DVB-S2 (*XX) obligatoire sur toutes les trames $... (anti-corruption UART) - if (commande[0] == '$') { - char* star = strrchr(commande, '*'); - if (!star || strlen(star + 1) != 2) { - return; - } - char* endPtr = nullptr; - unsigned long crcRecu = strtoul(star + 1, &endPtr, 16); - if (endPtr != star + 3) { - return; - } - size_t bodyLen = (size_t)(star - commande); - uint8_t crcCalc = calculerCrc8Crsf((const uint8_t*)commande, bodyLen); - if ((uint8_t)crcRecu != crcCalc) { - return; - } - *star = '\0'; - } - - // Injection Head-Tracking depuis SteamFrame FPV : $HT,,, (172..1811) - if (strncmp(commande, "$HT,", 4) == 0) { - int pan = CRSF_VAL_MID, tilt = CRSF_VAL_MID, roll = CRSF_VAL_MID; - if (sscanf(commande + 4, "%d,%d,%d", &pan, &tilt, &roll) == 3) { - crsfChannelStore(CANAL_HT_PAN - 1, (uint16_t)constrain(pan, CRSF_VAL_MIN, CRSF_VAL_MAX)); - crsfChannelStore(CANAL_HT_TILT - 1, (uint16_t)constrain(tilt, CRSF_VAL_MIN, CRSF_VAL_MAX)); - crsfChannelStore(CANAL_HT_ROLL - 1, (uint16_t)constrain(roll, CRSF_VAL_MIN, CRSF_VAL_MAX)); - 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(); - __atomic_store_n(&sourceActive, cible, __ATOMIC_RELEASE); - extRcActif = false; - __atomic_store_n(&extArme, false, __ATOMIC_RELEASE); - __atomic_store_n(&extRapport, 0, __ATOMIC_RELEASE); - extAccelPct = 0; - extFreinPct = 0; - extEmbrayagePct = 0; - extVolantPct = 0; - __atomic_store_n(&estArme, false, __ATOMIC_RELEASE); - __atomic_store_n(&rapportEngage, 0, __ATOMIC_RELEASE); - boutonArmDejaEnfonce = true; - palettePlusDejaEnfoncee = true; - paletteMoinsDejaEnfoncee = true; - etatBoutonsCockpitPrec = 0xFFFF; - reinitialiserCanauxCRSF(); - rp2040.resumeOtherCore(); - __atomic_store_n(&majLedRequise, true, __ATOMIC_RELEASE); - __atomic_store_n(&cockpitEtatModifie, true, __ATOMIC_RELEASE); - Serial.printf(">> [SRC] Source active basculee sur : %s\n", - (sourceActive == SRC_EXT) ? "EXT (Steam Controller)" : "G29 (Volant)"); - return; - } - - // Synchronisation des plages de vitesses CRSF depuis SteamFrame FPV : - // $GEARS,,,,,, - if (strncmp(commande, "$GEARS,", 7) == 0) { - int fMin = 0, g1 = 0, g2 = 0, g3 = 0, rMin = 0, rMax = 0; - if (sscanf(commande + 7, "%d,%d,%d,%d,%d,%d", &fMin, &g1, &g2, &g3, &rMin, &rMax) == 6) { - // Bornes strictes (max > min en AV, max < min en AR) pour éliminer toute division par zéro dans map(). - uint16_t vFMin = (uint16_t)constrain(fMin, CRSF_VAL_MID, CRSF_VAL_MAX - 1); - uint16_t vG1 = (uint16_t)constrain(g1, (int)vFMin + 1, CRSF_VAL_MAX); - uint16_t vG2 = (uint16_t)constrain(g2, (int)vFMin + 1, CRSF_VAL_MAX); - uint16_t vG3 = (uint16_t)constrain(g3, (int)vFMin + 1, CRSF_VAL_MAX); - uint16_t vRMin = (uint16_t)constrain(rMin, CRSF_VAL_MIN + 1, CRSF_VAL_MID); - uint16_t vRMax = (uint16_t)constrain(rMax, CRSF_VAL_MIN, (int)vRMin - 1); - - bool modifie = (configSysteme.gazAvantMin != vFMin) || - (configSysteme.gazAvantMax[0] != vG1) || - (configSysteme.gazAvantMax[1] != vG2) || - (configSysteme.gazAvantMax[2] != vG3) || - (configSysteme.gazArriereMin != vRMin) || - (configSysteme.gazArriereMax != vRMax); - - if (modifie) { - if (estActuellementArme()) { - // Sécurité : jamais d'idleOtherCore / EEPROM.commit() en conduite armée (gel Flash 50-100 ms). - // On applique les plafonds en RAM et on diffère l'écriture Flash au désarmement. - configSysteme.gazAvantMin = vFMin; - configSysteme.gazAvantMax[0] = vG1; - configSysteme.gazAvantMax[1] = vG2; - configSysteme.gazAvantMax[2] = vG3; - configSysteme.gazArriereMin = vRMin; - configSysteme.gazArriereMax = vRMax; - sauvegardeDifferee = true; - Serial.printf(">> [VITESSES] Maj RAM (Flash differee au desarmement) : AV_MIN=%u | 1=%u | 2=%u | 3=%u | AR_MIN=%u | AR_MAX=%u\n", - vFMin, vG1, vG2, vG3, vRMin, vRMax); - } else { - rp2040.idleOtherCore(); - configSysteme.gazAvantMin = vFMin; - configSysteme.gazAvantMax[0] = vG1; - configSysteme.gazAvantMax[1] = vG2; - configSysteme.gazAvantMax[2] = vG3; - configSysteme.gazArriereMin = vRMin; - configSysteme.gazArriereMax = vRMax; - rp2040.resumeOtherCore(); - sauvegarderConfiguration(); - Serial.printf(">> [VITESSES] AV_MIN=%u | 1=%u | 2=%u | 3=%u | AR_MIN=%u | AR_MAX=%u\n", - vFMin, vG1, vG2, vG3, vRMin, vRMax); - } - } - } - return; - } - - // Injection conduite externe (Steam Controller via SteamFrame FPV) : - // $RC,,,,,, - if (strncmp(commande, "$RC,", 4) == 0) { - if (__atomic_load_n(&sourceActive, __ATOMIC_ACQUIRE) != SRC_EXT) { - return; - } - int steer = CRSF_VAL_MID, accel = CRSF_VAL_MID, brake = CRSF_VAL_MID, clutch = CRSF_VAL_MID; - 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) { - __atomic_store_n(&extArme, true, __ATOMIC_RELEASE); - momentArmement_ms = millis(); - momentDesarmement_ms = 0; - __atomic_store_n(&majLedRequise, true, __ATOMIC_RELEASE); - __atomic_store_n(&cockpitEtatModifie, true, __ATOMIC_RELEASE); - Serial.println(">> [ARM EXT] ARME (Steam Controller)"); - } - } else if (!demandeArm && extArme) { - __atomic_store_n(&extArme, false, __ATOMIC_RELEASE); - momentDesarmement_ms = millis(); - momentArmement_ms = 0; - __atomic_store_n(&majLedRequise, true, __ATOMIC_RELEASE); - __atomic_store_n(&cockpitEtatModifie, true, __ATOMIC_RELEASE); - Serial.println(">> [ARM EXT] DESARME (Steam Controller)"); - } - - if (vGear != extRapport) { - __atomic_store_n(&extRapport, vGear, __ATOMIC_RELEASE); - __atomic_store_n(&majLedRequise, true, __ATOMIC_RELEASE); - __atomic_store_n(&cockpitEtatModifie, true, __ATOMIC_RELEASE); - } - - // Défense en profondeur : appliquer aussi les plafonds CRSF par rapport côté RP2350 - if (!extArme || extRapport == 0) { - vAccel = CRSF_VAL_MID; - } else if (extRapport >= 1 && extRapport <= 3) { - uint16_t maxV = configSysteme.gazAvantMax[extRapport - 1]; - vAccel = (uint16_t)constrain((int)vAccel, CRSF_VAL_MID, (int)maxV); - } else if (extRapport == -1) { - vAccel = (uint16_t)constrain((int)vAccel, (int)configSysteme.gazArriereMax, CRSF_VAL_MID); - } - - uint8_t accelPct = 0; - if (extArme && extRapport >= 1 && extRapport <= 3 && vAccel >= configSysteme.gazAvantMin) { - uint16_t maxV = configSysteme.gazAvantMax[extRapport - 1]; - if (maxV > configSysteme.gazAvantMin) { - accelPct = (uint8_t)constrain(map(vAccel, configSysteme.gazAvantMin, maxV, 0, 100), 0, 100); - } - } else if (extArme && extRapport == -1 && vAccel <= configSysteme.gazArriereMin) { - if (configSysteme.gazArriereMin > configSysteme.gazArriereMax) { - accelPct = (uint8_t)constrain(map(vAccel, configSysteme.gazArriereMin, configSysteme.gazArriereMax, 0, 100), 0, 100); - } - } - uint8_t brakePct = (vBrake > CRSF_VAL_MID) - ? (uint8_t)constrain(map(vBrake, CRSF_VAL_MID, CRSF_VAL_MAX, 0, 100), 0, 100) - : 0; - uint8_t clutchPct = (vClutch > CRSF_VAL_MID) - ? (uint8_t)constrain(map(vClutch, CRSF_VAL_MID, CRSF_VAL_MAX, 0, 100), 0, 100) - : 0; - int8_t steerPct = (int8_t)constrain( - (int)(((float)((int)CRSF_VAL_MID - (int)vSteer) / (float)(CRSF_VAL_MID - CRSF_VAL_MIN)) * 100.0f), - -100, 100 - ); - extAccelPct = accelPct; - extFreinPct = brakePct; - extEmbrayagePct = clutchPct; - extVolantPct = steerPct; - - assignerCanalCRSF(configSysteme.volant, vSteer); - assignerCanalCRSF(configSysteme.accel, vAccel); - assignerCanalCRSF(configSysteme.frein, vBrake); - assignerCanalCRSF(configSysteme.embrayage, vClutch); - crsfChannelStore(CANAL_ARM - 1, extArme ? CRSF_VAL_MAX : CRSF_VAL_MIN); - - dernierPaquetRC_ms = millis(); - if (!extRcActif) { - extRcActif = true; - __atomic_store_n(&majLedRequise, true, __ATOMIC_RELEASE); - __atomic_store_n(&cockpitEtatModifie, true, __ATOMIC_RELEASE); - } - } - return; - } -} - -void lireFluxSerie(Stream& port, char* buf, uint8_t& idx, bool& overflow, size_t maxLen, bool depuisUsb) { - int budget = 96; // Borner le temps passé dans loop() pour préserver la cadence CRSF 166 Hz - while (port.available() > 0 && budget-- > 0) { - char c = (char)port.read(); - if (c == '\n' || c == '\r') { - if (!overflow && idx > 0) { - buf[idx] = '\0'; - traiterLigneSerie(buf, depuisUsb); - } - idx = 0; - overflow = false; - } else if (overflow) { - // Ignorer le reste de la ligne trop longue jusqu'au prochain retour à la ligne - } else if (idx < maxLen - 1) { - buf[idx++] = c; - } else { - idx = 0; - overflow = true; - } - } -} - -void verifierCommandesSerie() { - lireFluxSerie(Serial, serialBuffer, serialBufferIdx, serialBufferOverflow, sizeof(serialBuffer), true); - lireFluxSerie(Serial2, serial2Buffer, serial2BufferIdx, serial2BufferOverflow, sizeof(serial2Buffer), false); -} - -// ------------------------------------------------------------------------- -// GESTION LED RGB SUR GP16 -// ------------------------------------------------------------------------- -void actualiserLED() { - uint8_t r = 0, g = 0, b = 0; - uint32_t now = millis(); - uint32_t dtArm = now - momentArmement_ms; - uint32_t dtDesarm = now - momentDesarmement_ms; - - if (momentArmement_ms > 0 && dtArm < 850) { - // Animation NeoPixel a l'armement : alternance vert lumineux et flash blanc - if ((dtArm / 90) % 2 == 0) { - r = 0; g = 255; b = 120; // Vert emeraude - } else { - r = 255; g = 255; b = 255; // Eclat blanc - } - } else if (momentDesarmement_ms > 0 && dtDesarm < 250) { - // Animation NeoPixel au desarmement : flash rouge d'arret - r = 255; g = 20; b = 0; - } 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 - } else { - 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 (!estActuellementArme()) { // Désarmé : couleur du rapport très atténuée - r /= 10; g /= 10; b /= 10; - } - } - rgb_led.setPixelColor(0, rgb_led.Color(r, g, b)); - rgb_led.show(); -} - -// ------------------------------------------------------------------------- -// ENVOI CRSF DEPUIS LA SRAM DU RP2350 -// ------------------------------------------------------------------------- -uint8_t __not_in_flash_func(calculerCrc8Crsf)(const uint8_t* data, size_t len) { - uint8_t crc = 0; - for (size_t i = 0; i < len; i++) { - crc ^= data[i]; - for (int j = 0; j < 8; j++) { - if (crc & 0x80) crc = (crc << 1) ^ 0xD5; - else crc <<= 1; - } - } - return crc; -} - -void __not_in_flash_func(envoyer_paquet_crsf)(bool neutre) { - uint8_t packet[26]; - uint16_t ch[16]; - - for (int i = 0; i < 16; i++) { - ch[i] = neutre ? CRSF_VAL_MID : crsfChannelLoad((uint8_t)i); - } - if (neutre) ch[CANAL_ARM - 1] = CRSF_VAL_MIN; // Failsafe : toujours désarmé - - packet[0] = 0xC8; - packet[1] = 24; - packet[2] = 0x16; - - packet[3] = (uint8_t)(ch[0]); - packet[4] = (uint8_t)((ch[0] >> 8) | (ch[1] << 3)); - packet[5] = (uint8_t)((ch[1] >> 5) | (ch[2] << 6)); - packet[6] = (uint8_t)(ch[2] >> 2); - packet[7] = (uint8_t)((ch[2] >> 10) | (ch[3] << 1)); - packet[8] = (uint8_t)((ch[3] >> 7) | (ch[4] << 4)); - packet[9] = (uint8_t)((ch[4] >> 4) | (ch[5] << 7)); - packet[10] = (uint8_t)(ch[5] >> 1); - packet[11] = (uint8_t)((ch[5] >> 9) | (ch[6] << 2)); - packet[12] = (uint8_t)((ch[6] >> 6) | (ch[7] << 5)); - packet[13] = (uint8_t)(ch[7] >> 3); - packet[14] = (uint8_t)(ch[8]); - packet[15] = (uint8_t)((ch[8] >> 8) | (ch[9] << 3)); - packet[16] = (uint8_t)((ch[9] >> 5) | (ch[10] << 6)); - packet[17] = (uint8_t)(ch[10] >> 2); - packet[18] = (uint8_t)((ch[10] >> 10) | (ch[11] << 1)); - packet[19] = (uint8_t)((ch[11] >> 7) | (ch[12] << 4)); - packet[20] = (uint8_t)((ch[12] >> 4) | (ch[13] << 7)); - packet[21] = (uint8_t)(ch[13] >> 1); - packet[22] = (uint8_t)((ch[13] >> 9) | (ch[14] << 2)); - packet[23] = (uint8_t)((ch[14] >> 6) | (ch[15] << 5)); - packet[24] = (uint8_t)(ch[15] >> 3); - packet[25] = calculerCrc8Crsf(&packet[2], 23); - - Serial1.write(packet, 26); -} +#include "config_state.h" +#include "cli_serial.h" +#include "crsf_protocol.h" +#include "g29_hid.h" // ========================================================================= // CŒUR 0 : Initialisation, CRSF 166Hz, Série, EEPROM et LED RGB @@ -988,314 +39,6 @@ void setup() { rp2040.wdt_begin(WATCHDOG_TIMEOUT_MS); } -static inline bool coeur1EstSain(uint32_t now) { - if (__atomic_load_n(&core1Demarre, __ATOMIC_ACQUIRE)) { - uint32_t hb = __atomic_load_n(&heartbeatCore1_ms, __ATOMIC_ACQUIRE); - return (now - hb) <= TIMEOUT_FAILSAFE_MS; - } - // Grâce de démarrage de 5 s pour laisser setup1() initialiser PIO-USB ; au-delà, faute Core 1. - return (now - momentDemarrageCore0_ms) <= 5000UL; -} - -// Évalue le failsafe (cœur 0). Retourne true si les canaux doivent être forcés au neutre. -bool evaluerFailsafe() { - uint32_t now = millis(); - - // 1. Surveillance de la santé du Cœur 1 (Watchdog logique inter-cœur) - if (!coeur1EstSain(now)) { - if (!failsafeActif) { - failsafeActif = true; - __atomic_store_n(&majLedRequise, true, __ATOMIC_RELEASE); - Serial.println(F("!! [FAILSAFE] Perte de reponse du Coeur 1 (Watchdog) !!")); - } - return true; - } - - // 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; - } - } - - // Volant branché et Cœur 1 fonctionnel : liaison valide (pas de faux failsafe quand le volant est immobile) - if (failsafeActif) { - failsafeActif = false; - majLedRequise = true; - Serial.println(F("[FAILSAFE] Signal retabli")); - } - return false; -} - -// ------------------------------------------------------------------------- -// RÉCEPTION TÉLÉMÉTRIE CRSF SUR GP1 (Serial1 RX) -// ------------------------------------------------------------------------- -void traiterTelemetrieCRSF() { - static uint8_t crsfRxBuffer[64]; - static uint8_t crsfRxIdx = 0; - static uint8_t paquetLongueurAttendue = 0; - static int16_t prevPitch = 0; - static int16_t prevRoll = 0; - static bool attitudeInitialisee = false; - static uint32_t dernierPaquetTelemetrie_ms = 0; - static uint32_t dernierOctetRx_ms = 0; - - while (Serial1.available() > 0) { - uint32_t now = millis(); - // Timeout inter-octets : réinitialiser l'index si une trame a été interrompue ou parasitée (> 2 ms) - if (crsfRxIdx > 0 && (now - dernierOctetRx_ms > 2)) { - crsfRxIdx = 0; - } - dernierOctetRx_ms = now; - - uint8_t b = Serial1.read(); - - if (crsfRxIdx == 0) { - // Les trames CRSF débutent par une adresse connue (0xC8, 0xEE, 0xEA, 0xEC standard) - if (b == 0xC8 || b == 0xEE || b == 0xEA || b == 0xEC) { - crsfRxBuffer[0] = b; - crsfRxIdx = 1; - paquetLongueurAttendue = 0; - } - } else if (crsfRxIdx == 1) { - paquetLongueurAttendue = b; - if (paquetLongueurAttendue < 2 || paquetLongueurAttendue > 62) { - crsfRxIdx = 0; // Trame invalide, rejet - } else { - crsfRxBuffer[1] = b; - crsfRxIdx = 2; - } - } else { - crsfRxBuffer[crsfRxIdx++] = b; - // Trame complète reçue : taille totale = 2 octets d'en-tête + longueur indiquée - if (crsfRxIdx >= (paquetLongueurAttendue + 2)) { - uint8_t crcAttendu = crsfRxBuffer[paquetLongueurAttendue + 1]; - uint8_t crcCalcule = calculerCrc8Crsf(&crsfRxBuffer[2], paquetLongueurAttendue - 1); - - if (crcCalcule == crcAttendu) { - dernierPaquetTelemetrie_ms = millis(); - uint8_t frameType = crsfRxBuffer[2]; - - if (!estArme || sourceActive != SRC_G29) { - rugositeTerrainExterne = 0; - attitudeInitialisee = false; - } else if (frameType == 0x1E && paquetLongueurAttendue >= 8) { - // Trame d'attitude (0x1E) : Pitch (int16), Roll (int16), Yaw (int16) - int16_t pitch = (int16_t)((crsfRxBuffer[3] << 8) | crsfRxBuffer[4]); - int16_t roll = (int16_t)((crsfRxBuffer[5] << 8) | crsfRxBuffer[6]); - if (!attitudeInitialisee) { - prevPitch = pitch; - prevRoll = roll; - attitudeInitialisee = true; - } else { - int32_t diffP = (int32_t)pitch - (int32_t)prevPitch; - int32_t diffR = (int32_t)roll - (int32_t)prevRoll; - if (diffP > 32767) diffP -= 65536; else if (diffP < -32768) diffP += 65536; - if (diffR > 32767) diffR -= 65536; else if (diffR < -32768) diffR += 65536; - int32_t deltaPitch = abs(diffP); - int32_t deltaRoll = abs(diffR); - prevPitch = pitch; - prevRoll = roll; - - int32_t secousses = deltaPitch + deltaRoll; - // Filtrage des micro-vibrations du FC : seuil mort de 60 (~0.35°) pour ignorer le bruit gyroscopique - if (secousses > 60) { - rugositeTerrainExterne = (uint8_t)constrain(map(secousses, 60, 450, 0, 255), 0, 255); - } else { - rugositeTerrainExterne = 0; - } - } - } - // Trame personnalisée (0x7F ou 0x2A pour accéléromètre brut / rugosité) - else if ((frameType == 0x7F || frameType == 0x2A) && paquetLongueurAttendue >= 3) { - rugositeTerrainExterne = crsfRxBuffer[3]; - } - - // Relais de la télémétrie CRSF valide vers SteamFrame FPV (OSD via Radxa/USB) - // Ne jamais relayer 0x16 (RC_CHANNELS_PACKED) si GP1 reçoit un écho des trames émises - if (frameType != 0x16) { - size_t totalLen = (size_t)paquetLongueurAttendue + 2; - if (totalLen <= 64) { - char bufCrsf[140]; - memcpy(bufCrsf, "$CRSF,", 6); - static const char HEX_DIGITS[] = "0123456789ABCDEF"; - for (size_t i = 0; i < totalLen; i++) { - uint8_t byteVal = crsfRxBuffer[i]; - bufCrsf[6 + i * 2] = HEX_DIGITS[(byteVal >> 4) & 0x0F]; - bufCrsf[6 + i * 2 + 1] = HEX_DIGITS[byteVal & 0x0F]; - } - bufCrsf[6 + totalLen * 2] = '\0'; - emettreLigneCockpit(bufCrsf); - } - } - } - - crsfRxIdx = 0; - } - if (crsfRxIdx >= sizeof(crsfRxBuffer)) { - crsfRxIdx = 0; - } - } - } - - if (!estArme || sourceActive != SRC_G29) { - rugositeTerrainExterne = 0; - attitudeInitialisee = false; - return; - } - - if (dernierPaquetTelemetrie_ms > 0 && (millis() - dernierPaquetTelemetrie_ms > 500)) { - attitudeInitialisee = false; - } - - // Décroissance douce de la rugosité si la télémétrie ne transmet plus depuis > 200 ms - if (rugositeTerrainExterne > 0 && (millis() - dernierPaquetTelemetrie_ms > 200)) { - static uint32_t dernierDecul = 0; - if (millis() - dernierDecul >= 50) { - dernierDecul = millis(); - rugositeTerrainExterne = (rugositeTerrainExterne > 10) ? (rugositeTerrainExterne - 10) : 0; - } - } -} - -void emettreLigneCockpit(const char* ligne) { - char framed[192]; - const char* toSend = ligne; - // Ajouter un CRC-8 DVB-S2 (*XX) sur les trames $G29 et $G29_EVT (protège la liaison UART 460k) - if (strncmp(ligne, "$G29,", 5) == 0 || strncmp(ligne, "$G29_EVT,", 9) == 0) { - size_t len = strlen(ligne); - if (len + 4 < sizeof(framed)) { - uint8_t crc = calculerCrc8Crsf((const uint8_t*)ligne, len); - snprintf(framed, sizeof(framed), "%s*%02X", ligne, crc); - toSend = framed; - } - } - int needed = (int)strlen(toSend) + 2; - // SerialUART::availableForWrite() sur arduino-pico renvoie >= 1 si de la place est libre en FIFO - if (Serial2.availableForWrite() > 0) { - Serial2.println(toSend); - } - if (cockpitEchoUSB && Serial && Serial.availableForWrite() >= needed) { - Serial.println(toSend); - } -} - -void gererSortieCockpit() { - static uint32_t dernierEnvoiCockpit_ms = 0; - - // 1. Émission immédiate des événements boutons (consommation atomique inter-cœurs) - uint16_t evts = __atomic_exchange_n(&evtBoutonsMasque, 0, __ATOMIC_ACQ_REL); - if (evts != 0) { - struct BoutonNom { uint16_t bit; const char* nom; }; - static const BoutonNom TABLE_BOUTONS[] = { - { EVT_BTN_CROSS, "CROSS" }, - { EVT_BTN_CIRCLE, "CIRCLE" }, - { EVT_BTN_SQUARE, "SQUARE" }, - { EVT_BTN_TRIANGLE, "TRIANGLE" }, - { EVT_BTN_SHARE, "SHARE" }, - { EVT_BTN_OPTIONS, "OPTIONS" }, - { EVT_BTN_PS, "PS" }, - { EVT_BTN_L3, "L3" }, - { EVT_BTN_R3, "R3" }, - { EVT_BTN_DPAD_UP, "DPAD_UP" }, - { EVT_BTN_DPAD_DOWN, "DPAD_DOWN" }, - { EVT_BTN_DPAD_LEFT, "DPAD_LEFT" }, - { EVT_BTN_DPAD_RIGHT, "DPAD_RIGHT" }, - }; - char bufEvt[32]; - for (size_t i = 0; i < sizeof(TABLE_BOUTONS) / sizeof(TABLE_BOUTONS[0]); i++) { - if (evts & TABLE_BOUTONS[i].bit) { - snprintf(bufEvt, sizeof(bufEvt), "$G29_EVT,BTN=%s", TABLE_BOUTONS[i].nom); - emettreLigneCockpit(bufEvt); - } - } - } - - // 2. Trame d'état cockpit à 20 Hz ou immédiatement sur changement critique - uint32_t now = millis(); - bool modif = __atomic_exchange_n(&cockpitEtatModifie, false, __ATOMIC_ACQ_REL); - if (modif || (now - dernierEnvoiCockpit_ms >= INTERVALLE_COCKPIT_MS)) { - dernierEnvoiCockpit_ms = now; - 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); - int clutch = (sourceActive == SRC_EXT) - ? (int)extEmbrayagePct - : (int)constrain(dernierEmbrayagePct + 0.5f, 0.0f, 100.0f); - int32_t dMax = (maxDeltaVolant > 0) ? maxDeltaVolant : DELTA_MAX_VOLANT_BRUT; - int steer = (sourceActive == SRC_EXT) - ? (int)extVolantPct - : (int)constrain(((float)dernierVolantCentre / (float)dMax) * 100.0f, -100.0f, 100.0f); - uint16_t ch1 = failsafeActif ? CRSF_VAL_MID : crsfChannelLoad(configSysteme.volant - 1); - uint16_t ch2 = failsafeActif ? CRSF_VAL_MID : crsfChannelLoad(configSysteme.accel - 1); - uint16_t ch3 = failsafeActif ? CRSF_VAL_MID : crsfChannelLoad(configSysteme.frein - 1); - uint16_t ch4 = failsafeActif ? CRSF_VAL_MID : crsfChannelLoad(configSysteme.embrayage - 1); - const char* srcStr = (sourceActive == SRC_EXT) ? "EXT" : "G29"; - char bufEtat[176]; - snprintf(bufEtat, sizeof(bufEtat), - "$G29,ARM=%d,GEAR=%d,THROT=%d,BRAKE=%d,CLUTCH=%d,STEER=%d,CH1=%u,CH2=%u,CH3=%u,CH4=%u,FFB=%d,VIB=%d,FAIL=%d,SRC=%s", - armeOut ? 1 : 0, - (int)rapportOut, - throt, - brake, - clutch, - steer, - (unsigned int)ch1, - (unsigned int)ch2, - (unsigned int)ch3, - (unsigned int)ch4, - (int)configSysteme.forceRessort, - (int)configSysteme.intensiteVibration, - failsafeActif ? 1 : 0, - srcStr); - emettreLigneCockpit(bufEtat); - } -} - -void gererTimeoutHeadTracking() { - if (htActif && (millis() - dernierPaquetHT_ms > TIMEOUT_HT_MS)) { - htActif = false; - crsfChannelStore(CANAL_HT_PAN - 1, CRSF_VAL_MID); - crsfChannelStore(CANAL_HT_TILT - 1, CRSF_VAL_MID); - crsfChannelStore(CANAL_HT_ROLL - 1, CRSF_VAL_MID); - } -} - -void gererTimeoutRcExterne() { - if (sourceActive == SRC_EXT && extRcActif && (millis() - dernierPaquetRC_ms > TIMEOUT_RC_EXT_MS)) { - extRcActif = false; - extArme = false; - extAccelPct = 0; - extFreinPct = 0; - extEmbrayagePct = 0; - extVolantPct = 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 vivant (ou dans la grâce boot 5 s) if (coeur1EstSain(millis())) { @@ -1411,694 +154,3 @@ void loop() { } } -// ========================================================================= -// CŒUR 1 : PILE PIO-USB, AUTO-CENTER ET LEDS G29 -// ========================================================================= -static inline int32_t obtenirDeltaMaxVolant() { - return (maxDeltaVolant > 0) ? maxDeltaVolant : DELTA_MAX_VOLANT_BRUT; -} - -bool envoyerTrameG29_0x30(const uint8_t cmd7[7]) { - if (!tuh_hid_send_ready(g29_dev_addr, g29_instance)) return false; - static uint8_t payload63[63]; - memset(payload63, 0, sizeof(payload63)); - memcpy(payload63, cmd7, 7); - return tuh_hid_send_report(g29_dev_addr, g29_instance, 0x30, payload63, sizeof(payload63)); -} - -bool envoyerPlageG29(uint16_t angle) { - const uint8_t cmdRange[7] = {0xF8, 0x81, (uint8_t)(angle & 0xFF), (uint8_t)(angle >> 8), 0x00, 0x00, 0x00}; - return envoyerTrameG29_0x30(cmdRange); -} - -bool envoyerRessortG29(uint8_t force) { - const uint8_t cmdSpring[7] = {0xFE, 0x0D, (uint8_t)(PENTE_RESSORT_G29 & 0x07), (uint8_t)(PENTE_RESSORT_G29 & 0x07), force, 0x00, 0x00}; - return envoyerTrameG29_0x30(cmdSpring); -} - -bool envoyerForceG29(uint8_t forceByte) { - const uint8_t cmdForce[7] = {0x11, 0x00, forceByte, 0x00, 0x00, 0x00, 0x00}; - return envoyerTrameG29_0x30(cmdForce); -} - -bool arreterForceG29() { - const uint8_t cmdStop[7] = {0x13, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; - return envoyerTrameG29_0x30(cmdStop); -} - -void gererInitMoteurG29() { - if (!volant_est_pret || etapeInitMoteur >= ETAPES_INIT_FFB_TOTAL) return; - // Attendre 6s après la connexion USB pour que le G29 ait terminé son calibrage matériel - if (millis() - momentConnexionUSB_ms < 6000) return; - - switch (etapeInitMoteur) { - case 0: if (envoyerPlageG29(configSysteme.angleSouhaiteTotal)) etapeInitMoteur++; break; - case 1: if (envoyerRessortG29(configSysteme.forceRessort)) etapeInitMoteur = ETAPES_INIT_FFB_TOTAL; break; - } -} - -uint8_t calculerMasqueLedG29() { - uint8_t masqueCible = 0x00; - uint32_t now = millis(); - - // 1. Animation dynamique lors de l'Armement du véhicule (~850 ms) - // Montée progressive des 5 LEDs (rev-up) puis double flash de confirmation - uint32_t dtArm = now - momentArmement_ms; - if (momentArmement_ms > 0 && dtArm < 850) { - if (dtArm < 80) masqueCible = 0x01; // 1 LED (Vert 1) - else if (dtArm < 160) masqueCible = 0x03; // 2 LEDs (Vert 1+2) - else if (dtArm < 240) masqueCible = 0x07; // 3 LEDs (Jaune 1) - else if (dtArm < 320) masqueCible = 0x0F; // 4 LEDs (Jaune 2) - else if (dtArm < 420) masqueCible = 0x1F; // 5 LEDs (Rouge max) - else if (dtArm < 520) masqueCible = 0x00; // Flash Off - else if (dtArm < 620) masqueCible = 0x1F; // Flash On (1) - else if (dtArm < 720) masqueCible = 0x00; // Flash Off - else masqueCible = 0x1F; // Flash On (2) - return masqueCible; - } - - // 2. Animation rapide lors du Désarmement du véhicule (~250 ms) - uint32_t dtDesarm = now - momentDesarmement_ms; - if (momentDesarmement_ms > 0 && dtDesarm < 250) { - if (dtDesarm < 70) masqueCible = 0x1F; // 5 LEDs - else if (dtDesarm < 140) masqueCible = 0x07; // 3 LEDs - else if (dtDesarm < 200) masqueCible = 0x01; // 1 LED - else masqueCible = 0x00; // Éteint - return masqueCible; - } - - // 3. Priorité aux jauges de réglage temporaires (1.5s) - uint32_t momentVib = momentDernierChangementVib_ms; - if (momentVib > 0 && (now - momentVib < 1500)) { - uint8_t v = configSysteme.intensiteVibration; - if (v >= 90) masqueCible = 0x1F; // 5 LEDs (90-100%) - else if (v >= 70) masqueCible = 0x0F; // 4 LEDs (70-80%) - else if (v >= 50) masqueCible = 0x07; // 3 LEDs (50-60%) - else if (v >= 30) masqueCible = 0x03; // 2 LEDs (30-40%) - else if (v >= 10) masqueCible = 0x01; // 1 LED (10-20%) - else masqueCible = 0x00; // 0 LED (0% / coupé) - } - else if (momentDernierChangementDurete_ms > 0 && (now - momentDernierChangementDurete_ms < 1500)) { - uint8_t f = configSysteme.forceRessort; - if (f >= 240) masqueCible = 0x1F; // 5 LEDs (Rouge) - else if (f >= 180) masqueCible = 0x0F; // 4 LEDs (Jaune haut) - else if (f >= 120) masqueCible = 0x07; // 3 LEDs (Jaune bas) - else if (f >= 60) masqueCible = 0x03; // 2 LEDs (Vert haut) - else if (f > 0) masqueCible = 0x01; // 1 LED (Vert bas) - else masqueCible = 0x00; // 0 LED (libre) - } else { - switch (rapportEngage) { - case -1: masqueCible = 0x1F; break; // 5 LEDs fixes en marche arriere (pas de spam USB cyclique) - case 0: masqueCible = 0x00; break; - case 1: masqueCible = 0x01; break; - case 2: masqueCible = 0x03; break; - case 3: masqueCible = 0x07; break; - } - } - if (murActifDroite || murActifGauche) { - masqueCible = 0x1F; // Allumer les 5 LEDs du volant dès qu'on touche la butée FFB ! - } - return masqueCible; -} - -bool envoyerLedsPendingG29() { - if (!volant_est_pret || etapeEnvoiLed == 0) return false; - if (millis() - momentConnexionUSB_ms < 500) return false; - - // Format validé sur G29 PS4 physique : - // Report ID = 0x30, payload 63 octets débutant par F8 12 suivi de zéros - const uint8_t cmdLed[7] = {0xF8, 0x12, (uint8_t)(dernierMasqueLedG29 & 0x1F), 0x00, 0x00, 0x00, 0x00}; - if (envoyerTrameG29_0x30(cmdLed)) { - statutEnvoiLed = 1; - etapeEnvoiLed = 0; - return true; - } - return false; -} - -void actualiserEtatButee() { - int32_t posCentre = dernierVolantCentre; - int32_t deltaMax = obtenirDeltaMaxVolant(); - - if (!murActifDroite) { - if (posCentre > deltaMax) { - murActifDroite = true; - } - } else if (posCentre <= deltaMax - HYSTERESIS_MUR_BRUT) { - murActifDroite = false; - } - - if (!murActifGauche) { - if (posCentre < -deltaMax) { - murActifGauche = true; - } - } else if (posCentre >= -deltaMax + HYSTERESIS_MUR_BRUT) { - murActifGauche = false; - } -} - -float calculerForceButee(int32_t posCentre, int32_t deltaMax) { - // Le G29 en mode PS4 gère matériellement la butée virtuelle via cmdRange pour les plages < 900°. - // L'injection d'une contre-force constante logicielle entre en conflit direct avec le microcontrôleur du G29. - if (configSysteme.angleSouhaiteTotal < 900) return 0.0f; - if (!murActifDroite && !murActifGauche) return 0.0f; - - int32_t depassement = murActifDroite ? (posCentre - deltaMax) : (-deltaMax - posCentre); - float f = 0.0f; - if (depassement >= 0) { - // Dans le mur strict : contre-force ultra-ferme immédiate (115 à 127, soit 90% à 100% du couple max) - f = constrain(115.0f + (float)depassement * 0.60f, 115.0f, 127.0f); - } else { - // Zone d'hystérésis : éjection ferme continue puis décroissance vers 0 - int32_t surplus = HYSTERESIS_MUR_BRUT + depassement; - f = constrain((float)surplus * (115.0f / (float)HYSTERESIS_MUR_BRUT), 0.0f, 115.0f); - } - return murActifDroite ? f : -f; -} - -float avancerPhaseSinus(float& phase, float freqHz, float dt_s) { - constexpr float DEUX_PI = 6.28318530718f; - phase += DEUX_PI * freqHz * dt_s; - if (phase >= DEUX_PI) { - phase = fmodf(phase, DEUX_PI); - } - return sinf(phase); -} - -void gererVibrationHaptique() { - if (!volant_est_pret || etapeInitMoteur < ETAPES_INIT_FFB_TOTAL) return; - if (majRangeRequise || majRessortRequise) return; - if (etapeEnvoiLed != 0 && (estArme || forceEstAuNeutre)) return; - if (!tuh_hid_send_ready(g29_dev_addr, g29_instance)) return; - - static uint32_t dernierCalculPhase_us = 0; - static float phase12 = 0.0f; - static float phase60 = 0.0f; - static float phase45 = 0.0f; - - // 1. Si on est dans le mur : le mur actif de blocage est prioritaire absolu - float forceButee = calculerForceButee(dernierVolantCentre, obtenirDeltaMaxVolant()); - if (forceButee != 0.0f) { - dernierCalculPhase_us = 0; - forceEstAuNeutre = false; - uint8_t forceByte = (uint8_t)constrain((int)(128.0f + forceButee), 0, 255); - envoyerForceG29(forceByte); - return; - } - - // 2. Gestion des vibrations haptiques et retours mécaniques - uint8_t intensite = configSysteme.intensiteVibration; - if (sourceActive != SRC_G29 || !estArme || intensite == 0) { - dernierCalculPhase_us = 0; - directionDernierChocRapport = 0; - if (!forceEstAuNeutre) { - if (arreterForceG29()) { - forceEstAuNeutre = true; - } - } - return; - } - - float gainGlobal = (float)intensite / 100.0f; - uint32_t now = millis(); - uint32_t dtChoc = now - momentDernierChocRapport_ms; - - // Cas A : À-coup sec au passage de rapport (durée 70 ms) - // Toujours actif lors du changement vers un rapport avant, pour un ressenti mécanique direct aux palettes ! - if (dtChoc < 70 && directionDernierChocRapport != 0) { - dernierCalculPhase_us = 0; - forceEstAuNeutre = false; - static uint32_t dernierMomentChocEnvoye = 0; - if (momentDernierChocRapport_ms != dernierMomentChocEnvoye) { - dernierMomentChocEnvoye = momentDernierChocRapport_ms; - float forceCalc = 128.0f + (float)directionDernierChocRapport * 85.0f * gainGlobal; - uint8_t forceByte = (uint8_t)constrain((int)forceCalc, 0, 255); - envoyerForceG29(forceByte); - } - return; - } else { - directionDernierChocRapport = 0; - } - - // Silence complet au point mort (0) ou en marche arrière (-1) - if (rapportEngage <= 0) { - dernierCalculPhase_us = 0; - if (!forceEstAuNeutre) { - if (arreterForceG29()) { - forceEstAuNeutre = true; - } - } - return; - } - forceEstAuNeutre = false; - - uint32_t now_us = micros(); - float dt_s = (dernierCalculPhase_us == 0) ? 0.040f : (float)(now_us - dernierCalculPhase_us) * 1e-6f; - if (dt_s > 0.08f) dt_s = 0.040f; - dernierCalculPhase_us = now_us; - - float forceCalc = 128.0f; - - // Cas B : Freinage violent (> 70%) -> vibration ABS à 45 Hz - if (dernierFreinPct > 70.0f) { - float absAmp = (dernierFreinPct - 70.0f) * 2.5f * gainGlobal; - forceCalc = 128.0f + absAmp * avancerPhaseSinus(phase45, 45.0f, dt_s); - } - // Cas C : Double-couche haptique (12 Hz grondement/terrain + 60 Hz roulement/vitesse) - else { - // 12 Hz : Grondement moteur au ralenti / régime + secousses terrain - float freq12 = 12.0f + (dernierAccelPct * 0.15f); - float ampMoteur12 = (14.0f + dernierAccelPct * 0.40f) * gainGlobal; - float ampTerrain12 = ((float)rugositeTerrainExterne * 0.25f) * gainGlobal; - float v12 = (ampMoteur12 + ampTerrain12) * avancerPhaseSinus(phase12, freq12, dt_s); - - // 60 Hz : Grain de roulement lié à la vitesse (rapport engagé) et aux gaz - // Baseline de 8.0f sur les rapports avant pour un retour haptique franc dès le rapport engagé - float baseVitesse = (rapportEngage > 0) ? 8.0f : 0.0f; - float ampVitesse60 = (baseVitesse + dernierAccelPct * 0.30f) * (1.0f + (float)rapportEngage * 0.25f) * gainGlobal; - float ampTerrain60 = ((float)rugositeTerrainExterne * 0.12f) * gainGlobal; - float v60 = (ampVitesse60 + ampTerrain60) * avancerPhaseSinus(phase60, 60.0f, dt_s); - - forceCalc = 128.0f + v12 + v60; - } - - uint8_t forceByte = (uint8_t)constrain((int)forceCalc, 0, 255); - envoyerForceG29(forceByte); -} - -void setup1() { - sleep_ms(100); - pio_usb_configuration_t pio_cfg = PIO_USB_DEFAULT_CONFIG; - pio_cfg.pin_dp = HOST_PIN_DP; - USBHost.configure_pio_usb(0, &pio_cfg); - USBHost.begin(0); -} - -void loop1() { - __atomic_store_n(&heartbeatCore1_ms, millis(), __ATOMIC_RELEASE); - __atomic_store_n(&core1Demarre, true, __ATOMIC_RELEASE); - USBHost.task(); - - if (!volant_est_pret) return; - - // Watchdog USB-Host : réarmer la réception dès que l'endpoint IN est disponible - if (tuh_hid_receive_ready(g29_dev_addr, g29_instance)) { - tuh_hid_receive_report(g29_dev_addr, g29_instance); - } - - // 1. Séquence d'initialisation FFB (6s après connexion USB, espacée de 50 ms) - static uint32_t dernierTickInit = 0; - if (etapeInitMoteur < ETAPES_INIT_FFB_TOTAL) { - if (millis() - dernierTickInit >= 50) { - dernierTickInit = millis(); - gererInitMoteurG29(); - } - return; - } - - // 1b. Confirmation tardive à 10 s (si le calibrage mécanique du G29 a dépassé 6 s) - if (!reinitPlageTardiveFaite && !estArme && (millis() - momentConnexionUSB_ms >= 10000)) { - reinitPlageTardiveFaite = true; - majRangeRequise = true; - majRessortRequise = true; - } - - // 2. Mise à jour continue de l'état de la butée active (avant LEDs et FFB) - actualiserEtatButee(); - - // 3. Rafraîchissement périodique de la cible LED (40 ms pour fluidité des animations) - static uint32_t dernierTickLed = 0; - if (millis() - dernierTickLed >= 40) { - dernierTickLed = millis(); - uint8_t masqueCible = calculerMasqueLedG29(); - if (masqueCible != dernierMasqueLedG29) { - dernierMasqueLedG29 = masqueCible; - etapeEnvoiLed = 1; - } - } - - // 4. Envoi immédiat des trames prioritaires dès que le pipe USB est libre (sans bloquer loop1) - if (__atomic_load_n(&majRangeRequise, __ATOMIC_ACQUIRE)) { - if (envoyerPlageG29(configSysteme.angleSouhaiteTotal)) { - __atomic_store_n(&majRangeRequise, false, __ATOMIC_RELEASE); - } - } - - if (__atomic_load_n(&majRessortRequise, __ATOMIC_ACQUIRE)) { - if (envoyerRessortG29(configSysteme.forceRessort)) { - __atomic_store_n(&majRessortRequise, false, __ATOMIC_RELEASE); - } - } - - // Arrêt prioritaire du moteur de vibration dès le désarmement (ou si source externe active), - // sauf si une butée logicielle (900°) est activement en cours pour éviter le battement à 25 Hz. - if ((__atomic_load_n(&sourceActive, __ATOMIC_ACQUIRE) != SRC_G29 || !estArme) - && !murActifDroite && !murActifGauche && !forceEstAuNeutre) { - if (arreterForceG29()) { - forceEstAuNeutre = true; - return; - } - } - - if (etapeEnvoiLed != 0) { - if (envoyerLedsPendingG29()) { - return; // Laisse 20 ms au G29 pour digérer la commande LED avant le prochain envoi FFB - } - } - - // 5. Moteur de vibration haptique & butée active (cadencé à 25 Hz / 40 ms pour préserver la bande passante PIO-USB) - static uint32_t dernierTickVib = 0; - if ((millis() - dernierTickVib >= 40) && tuh_hid_send_ready(g29_dev_addr, g29_instance)) { - dernierTickVib = millis(); - gererVibrationHaptique(); - } -} - -void reinitialiserEtatVolant() { - dernierMasqueLedG29 = 0xFF; - etapeEnvoiLed = 0; - etapeInitMoteur = 0; - reinitPlageTardiveFaite = false; - statutEnvoiLed = 0; - rapportEngage = 0; - estArme = false; - forceEstAuNeutre = true; - directionDernierChocRapport = 0; - murActifDroite = false; - murActifGauche = false; - dernierVolantCentre = 0; - dernierAccelPct = 0.0f; - dernierFreinPct = 0.0f; - dernierEmbrayagePct = 0.0f; - rugositeTerrainExterne = 0; -} - -// ========================================================================= -// CALLBACKS HID USB HOST (Exécutés sur Core 1) -// ========================================================================= -extern "C" { - -void tuh_hid_mount_cb(uint8_t dev_addr, uint8_t instance, uint8_t const* desc_report, uint16_t desc_len) { - (void)desc_report; - - // Filtrage : n'accepter que le G29 en mode PS4, et une seule interface à la fois - uint16_t vid = 0, pid = 0; - tuh_vid_pid_get(dev_addr, &vid, &pid); - if (vid != G29_VID || pid != G29_PID_PS4 || volant_est_pret) { - rejet_vid = vid; - rejet_pid = pid; - logRejetRequis = true; - return; // Pas de tuh_hid_receive_report() : on ignore ce périphérique - } - - g29_vid = vid; - g29_pid = pid; - g29_dev_addr = dev_addr; - g29_instance = instance; - g29_desc_len = desc_len; - reinitialiserEtatVolant(); - boutonArmDejaEnfonce = true; // Ignorer R2 s'il est déjà enfoncé au branchement - palettePlusDejaEnfoncee = true; // Exiger relâchement des palettes et molette au boot - paletteMoinsDejaEnfoncee= true; - dialPlusDejaEnfonce = true; - dialMoinsDejaEnfonce = true; - dialEnterDejaEnfonce = true; - etatBoutonsCockpitPrec = 0xFFFF; - etatDpadPrec = 0xFF; - evtBoutonsMasque = 0; - cockpitEtatModifie = true; - momentConnexionUSB_ms = millis(); - dernierRapportUSB_ms = millis(); - volant_est_pret = true; - majLedRequise = true; - logMountRequis = true; - - tuh_hid_receive_report(dev_addr, instance); -} - -void tuh_hid_umount_cb(uint8_t dev_addr, uint8_t instance) { - // Ignorer la déconnexion d'un autre périphérique que le G29 - if (!volant_est_pret || dev_addr != g29_dev_addr || instance != g29_instance) return; - - volant_est_pret = false; - g29_vid = 0; - g29_pid = 0; - reinitialiserEtatVolant(); - if (sourceActive == SRC_G29) { - reinitialiserCanauxCRSF(); - } - majLedRequise = true; -} - -void __not_in_flash_func(tuh_hid_report_received_cb)(uint8_t dev_addr, uint8_t instance, uint8_t const* report, uint16_t len) { - // Ignorer tout rapport ne venant pas du G29, ou n'ayant pas le bon format - if (dev_addr != g29_dev_addr || instance != g29_instance) { - return; // Ne pas réarmer la réception d'un périphérique étranger - } - if (len < 51 || report[0] != G29_REPORT_ID) { - compteurRapportsRejetes++; - dernierRejetLen = len; - dernierRejetId = (len > 0) ? report[0] : 0; - tuh_hid_receive_report(dev_addr, instance); - return; - } - - { - 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]); - uint16_t embrayageRaw = 65535 - ((report[50] << 8) | report[49]); - - // Pourcentages des pédales pour la synthèse haptique et le moniteur cockpit (0.0 à 100.0%) - dernierAccelPct = (accelRaw > DEADZONE_PEDALE) ? (((float)(accelRaw - DEADZONE_PEDALE) / (float)(65535 - DEADZONE_PEDALE)) * 100.0f) : 0.0f; - dernierFreinPct = (freinRaw > DEADZONE_PEDALE) ? (((float)(freinRaw - DEADZONE_PEDALE) / (float)(65535 - DEADZONE_PEDALE)) * 100.0f) : 0.0f; - dernierEmbrayagePct = (embrayageRaw > DEADZONE_PEDALE) ? (((float)(embrayageRaw - DEADZONE_PEDALE) / (float)(65535 - DEADZONE_PEDALE)) * 100.0f) : 0.0f; - - uint8_t boutonsEpaule = report[6]; - bool pPlusActuel = (boutonsEpaule & PALETTE_PLUS_MASK); - bool pMoinsActuel = (boutonsEpaule & PALETTE_MOINS_MASK); - bool armActuel = (boutonsEpaule & BOUTON_ARM_MASK); - - // Bascule ARM / DÉSARMÉ sur front montant de R2. - // Armement autorisé uniquement après l'init FFB, au point mort et accélérateur relâché. - if (armActuel && !boutonArmDejaEnfonce) { - if (estArme) { - estArme = false; - logArmRequis = -1; - directionDernierChocRapport = 0; - rugositeTerrainExterne = 0; - momentDesarmement_ms = millis(); - momentArmement_ms = 0; - cockpitEtatModifie = true; - } else if (etapeInitMoteur < ETAPES_INIT_FFB_TOTAL) { - logArmRequis = 3; - } else if (rapportEngage == 0 && accelRaw <= DEADZONE_PEDALE) { - estArme = true; - logArmRequis = 1; - momentArmement_ms = millis(); - momentDesarmement_ms = 0; - cockpitEtatModifie = true; - } else { - logArmRequis = 2; - } - majLedRequise = true; - boutonArmDejaEnfonce = true; - } else if (!armActuel && boutonArmDejaEnfonce) { - boutonArmDejaEnfonce = false; - } - - if (pPlusActuel && !palettePlusDejaEnfoncee) { - if (rapportEngage < 3 && !(rapportEngage < 0 && accelRaw > DEADZONE_PEDALE)) { - int8_t ancienRapport = rapportEngage; - rapportEngage++; - majLedRequise = true; - cockpitEtatModifie = true; - if (estArme && ancienRapport >= 0) { - momentDernierChocRapport_ms = millis(); - directionDernierChocRapport = 1; // À-coup sec vers la droite - } - } - palettePlusDejaEnfoncee = true; - } else if (!pPlusActuel && palettePlusDejaEnfoncee) { - palettePlusDejaEnfoncee = false; - } - - if (pMoinsActuel && !paletteMoinsDejaEnfoncee) { - if (rapportEngage > -1 && !(rapportEngage <= 0 && accelRaw > DEADZONE_PEDALE)) { - rapportEngage--; - majLedRequise = true; - cockpitEtatModifie = true; - if (estArme && rapportEngage >= 0) { - momentDernierChocRapport_ms = millis(); - directionDernierChocRapport = -1; // À-coup sec vers la gauche - } - } - paletteMoinsDejaEnfoncee = true; - } else if (!pMoinsActuel && paletteMoinsDejaEnfoncee) { - paletteMoinsDejaEnfoncee = false; - } - - // Réglage FFB à la volée : - // - Molette rouge (CW/CCW) : Dureté du ressort de centrage (0 à 255) - // - Boutons [+] / [-] : Intensité des vibrations haptiques (0 à 100%, 0 = désactivé) - // Sur G29 en mode PS4 (PID 0xC260), la molette et les boutons +/- sont situés dans report[54]. - // On conserve également report[7] comme solution de secours universelle. - uint8_t b54 = (len > 54) ? report[54] : 0; - uint8_t b7 = (len > 7) ? report[7] : 0; - - bool dialPlusActuel = (b54 & DIAL_CW_MASK_B54) || (b7 & DIAL_CW_MASK_B7); - bool dialMoinsActuel = (b54 & DIAL_CCW_MASK_B54) || (b7 & DIAL_CCW_MASK_B7); - bool dialEnterActuel = (b54 & DIAL_ENTER_MASK_B54) || (b7 & DIAL_ENTER_MASK_B7); - - bool btnPlusActuel = (b54 & BOUTON_PLUS_MASK_B54) || (b7 & BOUTON_PLUS_MASK_B7); - bool btnMoinsActuel = (b54 & BOUTON_MOINS_MASK_B54) || (b7 & BOUTON_MOINS_MASK_B7); - - // Molette : Dureté du ressort de rappel (FFB) - if (dialPlusActuel && !dialPlusDejaEnfonce) { - if (configSysteme.forceRessort <= 245) configSysteme.forceRessort += 10; - else configSysteme.forceRessort = 255; - majRessortRequise = true; - logDureteRequis = true; - majLedRequise = true; - cockpitEtatModifie = true; - momentDernierChangementDurete_ms = millis(); - dialPlusDejaEnfonce = true; - } else if (!dialPlusActuel && dialPlusDejaEnfonce) { - dialPlusDejaEnfonce = false; - } - - if (dialMoinsActuel && !dialMoinsDejaEnfonce) { - if (configSysteme.forceRessort >= 10) configSysteme.forceRessort -= 10; - else configSysteme.forceRessort = 0; - majRessortRequise = true; - logDureteRequis = true; - majLedRequise = true; - cockpitEtatModifie = true; - momentDernierChangementDurete_ms = millis(); - dialMoinsDejaEnfonce = true; - } else if (!dialMoinsActuel && dialMoinsDejaEnfonce) { - dialMoinsDejaEnfonce = false; - } - - // Bouton [+] : Augmenter les vibrations (+10%) - if (btnPlusActuel && !btnPlusDejaEnfonce) { - if (configSysteme.intensiteVibration <= 90) configSysteme.intensiteVibration += 10; - else configSysteme.intensiteVibration = 100; - logVibrationRequis = true; - majLedRequise = true; - cockpitEtatModifie = true; - momentDernierChangementVib_ms = millis(); - btnPlusDejaEnfonce = true; - } else if (!btnPlusActuel && btnPlusDejaEnfonce) { - btnPlusDejaEnfonce = false; - } - - // Bouton [-] : Diminuer les vibrations (-10%, jusqu'à 0% = coupé) - if (btnMoinsActuel && !btnMoinsDejaEnfonce) { - if (configSysteme.intensiteVibration >= 10) configSysteme.intensiteVibration -= 10; - else configSysteme.intensiteVibration = 0; - logVibrationRequis = true; - majLedRequise = true; - cockpitEtatModifie = true; - momentDernierChangementVib_ms = millis(); - btnMoinsDejaEnfonce = true; - } else if (!btnMoinsActuel && btnMoinsDejaEnfonce) { - btnMoinsDejaEnfonce = false; - } - - // Détection des boutons libres du G29 pour piloter le casque SteamFrame FPV - uint8_t b5 = report[5]; - uint16_t btnsActuels = 0; - if (b5 & BOUTON_CROIX_MASK) btnsActuels |= EVT_BTN_CROSS; - if (b5 & BOUTON_ROND_MASK) btnsActuels |= EVT_BTN_CIRCLE; - if (b5 & BOUTON_CARRE_MASK) btnsActuels |= EVT_BTN_SQUARE; - if (b5 & BOUTON_TRIANGLE_MASK) btnsActuels |= EVT_BTN_TRIANGLE; - if (boutonsEpaule & BOUTON_SHARE_MASK) btnsActuels |= EVT_BTN_SHARE; - if (boutonsEpaule & BOUTON_OPTIONS_MASK) btnsActuels |= EVT_BTN_OPTIONS; - if (b7 & BOUTON_PS_MASK_B7) btnsActuels |= EVT_BTN_PS; - if (boutonsEpaule & BOUTON_L3_MASK) btnsActuels |= EVT_BTN_L3; - if (boutonsEpaule & BOUTON_R3_MASK) btnsActuels |= EVT_BTN_R3; - - uint8_t dpadActuel = (b5 & DPAD_MASK_B5); - if (etatDpadPrec != 0xFF && dpadActuel != etatDpadPrec) { - if (dpadActuel == 0) btnsActuels |= EVT_BTN_DPAD_UP; - else if (dpadActuel == 4) btnsActuels |= EVT_BTN_DPAD_DOWN; - else if (dpadActuel == 6) btnsActuels |= EVT_BTN_DPAD_LEFT; - else if (dpadActuel == 2) btnsActuels |= EVT_BTN_DPAD_RIGHT; - } - etatDpadPrec = dpadActuel; - - uint16_t frontsMontants = btnsActuels & ~etatBoutonsCockpitPrec; - if (frontsMontants != 0) { - __atomic_fetch_or(&evtBoutonsMasque, frontsMontants, __ATOMIC_ACQ_REL); - } - etatBoutonsCockpitPrec = btnsActuels & 0x01FF; // Mémorise uniquement les boutons (pas le D-Pad) - - // Sauvegarde en Flash protégée : nécessite un appui continu de 2 secondes sur Enter - // véhicule à l'arrêt et désarmé, pour interdire tout gel Flash intempestif en manipulant la molette. - static uint32_t debutAppuiEnter_ms = 0; - if (dialEnterActuel) { - if (debutAppuiEnter_ms == 0) { - debutAppuiEnter_ms = millis(); - } else if (!estArme && accelRaw <= DEADZONE_PEDALE && (millis() - debutAppuiEnter_ms >= 2000) && !dialEnterDejaEnfonce) { - demandeSauvegardeEEPROM = true; - dialEnterDejaEnfonce = true; - } - } else { - debutAppuiEnter_ms = 0; - dialEnterDejaEnfonce = false; - } - - int32_t volantCentre = (int32_t)volantRaw - CENTRE_VOLANT_BRUT; - dernierVolantCentre = volantCentre; - int32_t deltaMax = obtenirDeltaMaxVolant(); - int32_t volantBorne = constrain(volantCentre, -deltaMax, deltaMax); - - float x = (float)volantBorne / (float)deltaMax; - float expo = configSysteme.expoVolant; - float y = x * (1.0f - expo + expo * (x * x)); - uint16_t vVolant = constrain((int32_t)(CRSF_VAL_MID - y * (CRSF_VAL_MAX - CRSF_VAL_MID)), CRSF_VAL_MIN, CRSF_VAL_MAX); - - uint16_t vAccel = CRSF_VAL_MID; - if (estArme && accelRaw > DEADZONE_PEDALE) { // Désarmé : gaz coupés quoi qu'il arrive - if (rapportEngage == -1) { - vAccel = constrain(map(accelRaw, DEADZONE_PEDALE, 65535, configSysteme.gazArriereMin, configSysteme.gazArriereMax), CRSF_VAL_MIN, CRSF_VAL_MAX); - } else if (rapportEngage >= 1 && rapportEngage <= 3) { - uint16_t maxVitesse = configSysteme.gazAvantMax[rapportEngage - 1]; - vAccel = constrain(map(accelRaw, DEADZONE_PEDALE, 65535, configSysteme.gazAvantMin, maxVitesse), CRSF_VAL_MIN, CRSF_VAL_MAX); - } - } - - uint16_t vFrein = (freinRaw > DEADZONE_PEDALE) - ? constrain(map(freinRaw, DEADZONE_PEDALE, 65535, CRSF_VAL_MID, CRSF_VAL_MAX), CRSF_VAL_MIN, CRSF_VAL_MAX) - : CRSF_VAL_MID; - - uint16_t vEmbrayage = (embrayageRaw > DEADZONE_PEDALE) - ? constrain(map(embrayageRaw, DEADZONE_PEDALE, 65535, CRSF_VAL_MID, CRSF_VAL_MAX), CRSF_VAL_MIN, CRSF_VAL_MAX) - : CRSF_VAL_MID; - - assignerCanalCRSF(configSysteme.volant, vVolant); - assignerCanalCRSF(configSysteme.accel, vAccel); - assignerCanalCRSF(configSysteme.frein, vFrein); - assignerCanalCRSF(configSysteme.embrayage, vEmbrayage); - crsfChannelStore(CANAL_ARM - 1, __atomic_load_n(&estArme, __ATOMIC_ACQUIRE) ? CRSF_VAL_MAX : CRSF_VAL_MIN); - - // Horodatage APRÈS l'écriture des canaux : à la sortie d'un failsafe, le cœur 0 - // ne peut pas renvoyer d'anciennes valeurs (d'avant la coupure) pendant un paquet. - dernierRapportUSB_ms = millis(); - } - - tuh_hid_receive_report(dev_addr, instance); -} - -} // extern "C" diff --git a/firmware/g29_crsf/g29_hid.h b/firmware/g29_crsf/g29_hid.h new file mode 100644 index 0000000..50dabf8 --- /dev/null +++ b/firmware/g29_crsf/g29_hid.h @@ -0,0 +1,693 @@ +#pragma once + +// ========================================================================= +// CŒUR 1 : PILE PIO-USB, AUTO-CENTER ET LEDS G29 +// ========================================================================= +static inline int32_t obtenirDeltaMaxVolant() { + return (maxDeltaVolant > 0) ? maxDeltaVolant : DELTA_MAX_VOLANT_BRUT; +} + +bool envoyerTrameG29_0x30(const uint8_t cmd7[7]) { + if (!tuh_hid_send_ready(g29_dev_addr, g29_instance)) return false; + static uint8_t payload63[63]; + memset(payload63, 0, sizeof(payload63)); + memcpy(payload63, cmd7, 7); + return tuh_hid_send_report(g29_dev_addr, g29_instance, 0x30, payload63, sizeof(payload63)); +} + +bool envoyerPlageG29(uint16_t angle) { + const uint8_t cmdRange[7] = {0xF8, 0x81, (uint8_t)(angle & 0xFF), (uint8_t)(angle >> 8), 0x00, 0x00, 0x00}; + return envoyerTrameG29_0x30(cmdRange); +} + +bool envoyerRessortG29(uint8_t force) { + const uint8_t cmdSpring[7] = {0xFE, 0x0D, (uint8_t)(PENTE_RESSORT_G29 & 0x07), (uint8_t)(PENTE_RESSORT_G29 & 0x07), force, 0x00, 0x00}; + return envoyerTrameG29_0x30(cmdSpring); +} + +bool envoyerForceG29(uint8_t forceByte) { + const uint8_t cmdForce[7] = {0x11, 0x00, forceByte, 0x00, 0x00, 0x00, 0x00}; + return envoyerTrameG29_0x30(cmdForce); +} + +bool arreterForceG29() { + const uint8_t cmdStop[7] = {0x13, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + return envoyerTrameG29_0x30(cmdStop); +} + +void gererInitMoteurG29() { + if (!volant_est_pret || etapeInitMoteur >= ETAPES_INIT_FFB_TOTAL) return; + // Attendre 6s après la connexion USB pour que le G29 ait terminé son calibrage matériel + if (millis() - momentConnexionUSB_ms < 6000) return; + + switch (etapeInitMoteur) { + case 0: if (envoyerPlageG29(configSysteme.angleSouhaiteTotal)) etapeInitMoteur++; break; + case 1: if (envoyerRessortG29(configSysteme.forceRessort)) etapeInitMoteur = ETAPES_INIT_FFB_TOTAL; break; + } +} + +uint8_t calculerMasqueLedG29() { + uint8_t masqueCible = 0x00; + uint32_t now = millis(); + + // 1. Animation dynamique lors de l'Armement du véhicule (~850 ms) + // Montée progressive des 5 LEDs (rev-up) puis double flash de confirmation + uint32_t dtArm = now - momentArmement_ms; + if (momentArmement_ms > 0 && dtArm < 850) { + if (dtArm < 80) masqueCible = 0x01; // 1 LED (Vert 1) + else if (dtArm < 160) masqueCible = 0x03; // 2 LEDs (Vert 1+2) + else if (dtArm < 240) masqueCible = 0x07; // 3 LEDs (Jaune 1) + else if (dtArm < 320) masqueCible = 0x0F; // 4 LEDs (Jaune 2) + else if (dtArm < 420) masqueCible = 0x1F; // 5 LEDs (Rouge max) + else if (dtArm < 520) masqueCible = 0x00; // Flash Off + else if (dtArm < 620) masqueCible = 0x1F; // Flash On (1) + else if (dtArm < 720) masqueCible = 0x00; // Flash Off + else masqueCible = 0x1F; // Flash On (2) + return masqueCible; + } + + // 2. Animation rapide lors du Désarmement du véhicule (~250 ms) + uint32_t dtDesarm = now - momentDesarmement_ms; + if (momentDesarmement_ms > 0 && dtDesarm < 250) { + if (dtDesarm < 70) masqueCible = 0x1F; // 5 LEDs + else if (dtDesarm < 140) masqueCible = 0x07; // 3 LEDs + else if (dtDesarm < 200) masqueCible = 0x01; // 1 LED + else masqueCible = 0x00; // Éteint + return masqueCible; + } + + // 3. Priorité aux jauges de réglage temporaires (1.5s) + uint32_t momentVib = momentDernierChangementVib_ms; + if (momentVib > 0 && (now - momentVib < 1500)) { + uint8_t v = configSysteme.intensiteVibration; + if (v >= 90) masqueCible = 0x1F; // 5 LEDs (90-100%) + else if (v >= 70) masqueCible = 0x0F; // 4 LEDs (70-80%) + else if (v >= 50) masqueCible = 0x07; // 3 LEDs (50-60%) + else if (v >= 30) masqueCible = 0x03; // 2 LEDs (30-40%) + else if (v >= 10) masqueCible = 0x01; // 1 LED (10-20%) + else masqueCible = 0x00; // 0 LED (0% / coupé) + } + else if (momentDernierChangementDurete_ms > 0 && (now - momentDernierChangementDurete_ms < 1500)) { + uint8_t f = configSysteme.forceRessort; + if (f >= 240) masqueCible = 0x1F; // 5 LEDs (Rouge) + else if (f >= 180) masqueCible = 0x0F; // 4 LEDs (Jaune haut) + else if (f >= 120) masqueCible = 0x07; // 3 LEDs (Jaune bas) + else if (f >= 60) masqueCible = 0x03; // 2 LEDs (Vert haut) + else if (f > 0) masqueCible = 0x01; // 1 LED (Vert bas) + else masqueCible = 0x00; // 0 LED (libre) + } else { + switch (rapportEngage) { + case -1: masqueCible = 0x1F; break; // 5 LEDs fixes en marche arriere (pas de spam USB cyclique) + case 0: masqueCible = 0x00; break; + case 1: masqueCible = 0x01; break; + case 2: masqueCible = 0x03; break; + case 3: masqueCible = 0x07; break; + } + } + if (murActifDroite || murActifGauche) { + masqueCible = 0x1F; // Allumer les 5 LEDs du volant dès qu'on touche la butée FFB ! + } + return masqueCible; +} + +bool envoyerLedsPendingG29() { + if (!volant_est_pret || etapeEnvoiLed == 0) return false; + if (millis() - momentConnexionUSB_ms < 500) return false; + + // Format validé sur G29 PS4 physique : + // Report ID = 0x30, payload 63 octets débutant par F8 12 suivi de zéros + const uint8_t cmdLed[7] = {0xF8, 0x12, (uint8_t)(dernierMasqueLedG29 & 0x1F), 0x00, 0x00, 0x00, 0x00}; + if (envoyerTrameG29_0x30(cmdLed)) { + statutEnvoiLed = 1; + etapeEnvoiLed = 0; + return true; + } + return false; +} + +void actualiserEtatButee() { + int32_t posCentre = dernierVolantCentre; + int32_t deltaMax = obtenirDeltaMaxVolant(); + + if (!murActifDroite) { + if (posCentre > deltaMax) { + murActifDroite = true; + } + } else if (posCentre <= deltaMax - HYSTERESIS_MUR_BRUT) { + murActifDroite = false; + } + + if (!murActifGauche) { + if (posCentre < -deltaMax) { + murActifGauche = true; + } + } else if (posCentre >= -deltaMax + HYSTERESIS_MUR_BRUT) { + murActifGauche = false; + } +} + +float calculerForceButee(int32_t posCentre, int32_t deltaMax) { + // Le G29 en mode PS4 gère matériellement la butée virtuelle via cmdRange pour les plages < 900°. + // L'injection d'une contre-force constante logicielle entre en conflit direct avec le microcontrôleur du G29. + if (configSysteme.angleSouhaiteTotal < 900) return 0.0f; + if (!murActifDroite && !murActifGauche) return 0.0f; + + int32_t depassement = murActifDroite ? (posCentre - deltaMax) : (-deltaMax - posCentre); + float f = 0.0f; + if (depassement >= 0) { + // Dans le mur strict : contre-force ultra-ferme immédiate (115 à 127, soit 90% à 100% du couple max) + f = constrain(115.0f + (float)depassement * 0.60f, 115.0f, 127.0f); + } else { + // Zone d'hystérésis : éjection ferme continue puis décroissance vers 0 + int32_t surplus = HYSTERESIS_MUR_BRUT + depassement; + f = constrain((float)surplus * (115.0f / (float)HYSTERESIS_MUR_BRUT), 0.0f, 115.0f); + } + return murActifDroite ? f : -f; +} + +float avancerPhaseSinus(float& phase, float freqHz, float dt_s) { + constexpr float DEUX_PI = 6.28318530718f; + phase += DEUX_PI * freqHz * dt_s; + if (phase >= DEUX_PI) { + phase = fmodf(phase, DEUX_PI); + } + return sinf(phase); +} + +void gererVibrationHaptique() { + if (!volant_est_pret || etapeInitMoteur < ETAPES_INIT_FFB_TOTAL) return; + if (majRangeRequise || majRessortRequise) return; + if (etapeEnvoiLed != 0 && (estArme || forceEstAuNeutre)) return; + if (!tuh_hid_send_ready(g29_dev_addr, g29_instance)) return; + + static uint32_t dernierCalculPhase_us = 0; + static float phase12 = 0.0f; + static float phase60 = 0.0f; + static float phase45 = 0.0f; + + // 1. Si on est dans le mur : le mur actif de blocage est prioritaire absolu + float forceButee = calculerForceButee(dernierVolantCentre, obtenirDeltaMaxVolant()); + if (forceButee != 0.0f) { + dernierCalculPhase_us = 0; + forceEstAuNeutre = false; + uint8_t forceByte = (uint8_t)constrain((int)(128.0f + forceButee), 0, 255); + envoyerForceG29(forceByte); + return; + } + + // 2. Gestion des vibrations haptiques et retours mécaniques + uint8_t intensite = configSysteme.intensiteVibration; + if (sourceActive != SRC_G29 || !estArme || intensite == 0) { + dernierCalculPhase_us = 0; + directionDernierChocRapport = 0; + if (!forceEstAuNeutre) { + if (arreterForceG29()) { + forceEstAuNeutre = true; + } + } + return; + } + + float gainGlobal = (float)intensite / 100.0f; + uint32_t now = millis(); + uint32_t dtChoc = now - momentDernierChocRapport_ms; + + // Cas A : À-coup sec au passage de rapport (durée 70 ms) + // Toujours actif lors du changement vers un rapport avant, pour un ressenti mécanique direct aux palettes ! + if (dtChoc < 70 && directionDernierChocRapport != 0) { + dernierCalculPhase_us = 0; + forceEstAuNeutre = false; + static uint32_t dernierMomentChocEnvoye = 0; + if (momentDernierChocRapport_ms != dernierMomentChocEnvoye) { + dernierMomentChocEnvoye = momentDernierChocRapport_ms; + float forceCalc = 128.0f + (float)directionDernierChocRapport * 85.0f * gainGlobal; + uint8_t forceByte = (uint8_t)constrain((int)forceCalc, 0, 255); + envoyerForceG29(forceByte); + } + return; + } else { + directionDernierChocRapport = 0; + } + + // Silence complet au point mort (0) ou en marche arrière (-1) + if (rapportEngage <= 0) { + dernierCalculPhase_us = 0; + if (!forceEstAuNeutre) { + if (arreterForceG29()) { + forceEstAuNeutre = true; + } + } + return; + } + forceEstAuNeutre = false; + + uint32_t now_us = micros(); + float dt_s = (dernierCalculPhase_us == 0) ? 0.040f : (float)(now_us - dernierCalculPhase_us) * 1e-6f; + if (dt_s > 0.08f) dt_s = 0.040f; + dernierCalculPhase_us = now_us; + + float forceCalc = 128.0f; + + // Cas B : Freinage violent (> 70%) -> vibration ABS à 45 Hz + if (dernierFreinPct > 70.0f) { + float absAmp = (dernierFreinPct - 70.0f) * 2.5f * gainGlobal; + forceCalc = 128.0f + absAmp * avancerPhaseSinus(phase45, 45.0f, dt_s); + } + // Cas C : Double-couche haptique (12 Hz grondement/terrain + 60 Hz roulement/vitesse) + else { + // 12 Hz : Grondement moteur au ralenti / régime + secousses terrain + float freq12 = 12.0f + (dernierAccelPct * 0.15f); + float ampMoteur12 = (14.0f + dernierAccelPct * 0.40f) * gainGlobal; + float ampTerrain12 = ((float)rugositeTerrainExterne * 0.25f) * gainGlobal; + float v12 = (ampMoteur12 + ampTerrain12) * avancerPhaseSinus(phase12, freq12, dt_s); + + // 60 Hz : Grain de roulement lié à la vitesse (rapport engagé) et aux gaz + // Baseline de 8.0f sur les rapports avant pour un retour haptique franc dès le rapport engagé + float baseVitesse = (rapportEngage > 0) ? 8.0f : 0.0f; + float ampVitesse60 = (baseVitesse + dernierAccelPct * 0.30f) * (1.0f + (float)rapportEngage * 0.25f) * gainGlobal; + float ampTerrain60 = ((float)rugositeTerrainExterne * 0.12f) * gainGlobal; + float v60 = (ampVitesse60 + ampTerrain60) * avancerPhaseSinus(phase60, 60.0f, dt_s); + + forceCalc = 128.0f + v12 + v60; + } + + uint8_t forceByte = (uint8_t)constrain((int)forceCalc, 0, 255); + envoyerForceG29(forceByte); +} + +void setup1() { + sleep_ms(100); + pio_usb_configuration_t pio_cfg = PIO_USB_DEFAULT_CONFIG; + pio_cfg.pin_dp = HOST_PIN_DP; + USBHost.configure_pio_usb(0, &pio_cfg); + USBHost.begin(0); +} + +void loop1() { + __atomic_store_n(&heartbeatCore1_ms, millis(), __ATOMIC_RELEASE); + __atomic_store_n(&core1Demarre, true, __ATOMIC_RELEASE); + USBHost.task(); + + if (!volant_est_pret) return; + + // Watchdog USB-Host : réarmer la réception dès que l'endpoint IN est disponible + if (tuh_hid_receive_ready(g29_dev_addr, g29_instance)) { + tuh_hid_receive_report(g29_dev_addr, g29_instance); + } + + // 1. Séquence d'initialisation FFB (6s après connexion USB, espacée de 50 ms) + static uint32_t dernierTickInit = 0; + if (etapeInitMoteur < ETAPES_INIT_FFB_TOTAL) { + if (millis() - dernierTickInit >= 50) { + dernierTickInit = millis(); + gererInitMoteurG29(); + } + return; + } + + // 1b. Confirmation tardive à 10 s (si le calibrage mécanique du G29 a dépassé 6 s) + if (!reinitPlageTardiveFaite && !estArme && (millis() - momentConnexionUSB_ms >= 10000)) { + reinitPlageTardiveFaite = true; + majRangeRequise = true; + majRessortRequise = true; + } + + // 2. Mise à jour continue de l'état de la butée active (avant LEDs et FFB) + actualiserEtatButee(); + + // 3. Rafraîchissement périodique de la cible LED (40 ms pour fluidité des animations) + static uint32_t dernierTickLed = 0; + if (millis() - dernierTickLed >= 40) { + dernierTickLed = millis(); + uint8_t masqueCible = calculerMasqueLedG29(); + if (masqueCible != dernierMasqueLedG29) { + dernierMasqueLedG29 = masqueCible; + etapeEnvoiLed = 1; + } + } + + // 4. Envoi immédiat des trames prioritaires dès que le pipe USB est libre (sans bloquer loop1) + if (__atomic_load_n(&majRangeRequise, __ATOMIC_ACQUIRE)) { + if (envoyerPlageG29(configSysteme.angleSouhaiteTotal)) { + __atomic_store_n(&majRangeRequise, false, __ATOMIC_RELEASE); + } + } + + if (__atomic_load_n(&majRessortRequise, __ATOMIC_ACQUIRE)) { + if (envoyerRessortG29(configSysteme.forceRessort)) { + __atomic_store_n(&majRessortRequise, false, __ATOMIC_RELEASE); + } + } + + // Arrêt prioritaire du moteur de vibration dès le désarmement (ou si source externe active), + // sauf si une butée logicielle (900°) est activement en cours pour éviter le battement à 25 Hz. + if ((__atomic_load_n(&sourceActive, __ATOMIC_ACQUIRE) != SRC_G29 || !estArme) + && !murActifDroite && !murActifGauche && !forceEstAuNeutre) { + if (arreterForceG29()) { + forceEstAuNeutre = true; + return; + } + } + + if (etapeEnvoiLed != 0) { + if (envoyerLedsPendingG29()) { + return; // Laisse 20 ms au G29 pour digérer la commande LED avant le prochain envoi FFB + } + } + + // 5. Moteur de vibration haptique & butée active (cadencé à 25 Hz / 40 ms pour préserver la bande passante PIO-USB) + static uint32_t dernierTickVib = 0; + if ((millis() - dernierTickVib >= 40) && tuh_hid_send_ready(g29_dev_addr, g29_instance)) { + dernierTickVib = millis(); + gererVibrationHaptique(); + } +} + +void reinitialiserEtatVolant() { + dernierMasqueLedG29 = 0xFF; + etapeEnvoiLed = 0; + etapeInitMoteur = 0; + reinitPlageTardiveFaite = false; + statutEnvoiLed = 0; + rapportEngage = 0; + estArme = false; + forceEstAuNeutre = true; + directionDernierChocRapport = 0; + murActifDroite = false; + murActifGauche = false; + dernierVolantCentre = 0; + dernierAccelPct = 0.0f; + dernierFreinPct = 0.0f; + dernierEmbrayagePct = 0.0f; + rugositeTerrainExterne = 0; +} + +// ========================================================================= +// CALLBACKS HID USB HOST (Exécutés sur Core 1) +// ========================================================================= +extern "C" { + +void tuh_hid_mount_cb(uint8_t dev_addr, uint8_t instance, uint8_t const* desc_report, uint16_t desc_len) { + (void)desc_report; + + // Filtrage : n'accepter que le G29 en mode PS4, et une seule interface à la fois + uint16_t vid = 0, pid = 0; + tuh_vid_pid_get(dev_addr, &vid, &pid); + if (vid != G29_VID || pid != G29_PID_PS4 || volant_est_pret) { + rejet_vid = vid; + rejet_pid = pid; + logRejetRequis = true; + return; // Pas de tuh_hid_receive_report() : on ignore ce périphérique + } + + g29_vid = vid; + g29_pid = pid; + g29_dev_addr = dev_addr; + g29_instance = instance; + g29_desc_len = desc_len; + reinitialiserEtatVolant(); + boutonArmDejaEnfonce = true; // Ignorer R2 s'il est déjà enfoncé au branchement + palettePlusDejaEnfoncee = true; // Exiger relâchement des palettes et molette au boot + paletteMoinsDejaEnfoncee= true; + dialPlusDejaEnfonce = true; + dialMoinsDejaEnfonce = true; + dialEnterDejaEnfonce = true; + etatBoutonsCockpitPrec = 0xFFFF; + etatDpadPrec = 0xFF; + evtBoutonsMasque = 0; + cockpitEtatModifie = true; + momentConnexionUSB_ms = millis(); + dernierRapportUSB_ms = millis(); + volant_est_pret = true; + majLedRequise = true; + logMountRequis = true; + + tuh_hid_receive_report(dev_addr, instance); +} + +void tuh_hid_umount_cb(uint8_t dev_addr, uint8_t instance) { + // Ignorer la déconnexion d'un autre périphérique que le G29 + if (!volant_est_pret || dev_addr != g29_dev_addr || instance != g29_instance) return; + + volant_est_pret = false; + g29_vid = 0; + g29_pid = 0; + reinitialiserEtatVolant(); + if (sourceActive == SRC_G29) { + reinitialiserCanauxCRSF(); + } + majLedRequise = true; +} + +void __not_in_flash_func(tuh_hid_report_received_cb)(uint8_t dev_addr, uint8_t instance, uint8_t const* report, uint16_t len) { + // Ignorer tout rapport ne venant pas du G29, ou n'ayant pas le bon format + if (dev_addr != g29_dev_addr || instance != g29_instance) { + return; // Ne pas réarmer la réception d'un périphérique étranger + } + if (len < 51 || report[0] != G29_REPORT_ID) { + compteurRapportsRejetes++; + dernierRejetLen = len; + dernierRejetId = (len > 0) ? report[0] : 0; + tuh_hid_receive_report(dev_addr, instance); + return; + } + + { + 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]); + uint16_t embrayageRaw = 65535 - ((report[50] << 8) | report[49]); + + // Pourcentages des pédales pour la synthèse haptique et le moniteur cockpit (0.0 à 100.0%) + dernierAccelPct = (accelRaw > DEADZONE_PEDALE) ? (((float)(accelRaw - DEADZONE_PEDALE) / (float)(65535 - DEADZONE_PEDALE)) * 100.0f) : 0.0f; + dernierFreinPct = (freinRaw > DEADZONE_PEDALE) ? (((float)(freinRaw - DEADZONE_PEDALE) / (float)(65535 - DEADZONE_PEDALE)) * 100.0f) : 0.0f; + dernierEmbrayagePct = (embrayageRaw > DEADZONE_PEDALE) ? (((float)(embrayageRaw - DEADZONE_PEDALE) / (float)(65535 - DEADZONE_PEDALE)) * 100.0f) : 0.0f; + + uint8_t boutonsEpaule = report[6]; + bool pPlusActuel = (boutonsEpaule & PALETTE_PLUS_MASK); + bool pMoinsActuel = (boutonsEpaule & PALETTE_MOINS_MASK); + bool armActuel = (boutonsEpaule & BOUTON_ARM_MASK); + + // Bascule ARM / DÉSARMÉ sur front montant de R2. + // Armement autorisé uniquement après l'init FFB, au point mort et accélérateur relâché. + if (armActuel && !boutonArmDejaEnfonce) { + if (estArme) { + estArme = false; + logArmRequis = -1; + directionDernierChocRapport = 0; + rugositeTerrainExterne = 0; + momentDesarmement_ms = millis(); + momentArmement_ms = 0; + cockpitEtatModifie = true; + } else if (etapeInitMoteur < ETAPES_INIT_FFB_TOTAL) { + logArmRequis = 3; + } else if (rapportEngage == 0 && accelRaw <= DEADZONE_PEDALE) { + estArme = true; + logArmRequis = 1; + momentArmement_ms = millis(); + momentDesarmement_ms = 0; + cockpitEtatModifie = true; + } else { + logArmRequis = 2; + } + majLedRequise = true; + boutonArmDejaEnfonce = true; + } else if (!armActuel && boutonArmDejaEnfonce) { + boutonArmDejaEnfonce = false; + } + + if (pPlusActuel && !palettePlusDejaEnfoncee) { + if (rapportEngage < 3 && !(rapportEngage < 0 && accelRaw > DEADZONE_PEDALE)) { + int8_t ancienRapport = rapportEngage; + rapportEngage++; + majLedRequise = true; + cockpitEtatModifie = true; + if (estArme && ancienRapport >= 0) { + momentDernierChocRapport_ms = millis(); + directionDernierChocRapport = 1; // À-coup sec vers la droite + } + } + palettePlusDejaEnfoncee = true; + } else if (!pPlusActuel && palettePlusDejaEnfoncee) { + palettePlusDejaEnfoncee = false; + } + + if (pMoinsActuel && !paletteMoinsDejaEnfoncee) { + if (rapportEngage > -1 && !(rapportEngage <= 0 && accelRaw > DEADZONE_PEDALE)) { + rapportEngage--; + majLedRequise = true; + cockpitEtatModifie = true; + if (estArme && rapportEngage >= 0) { + momentDernierChocRapport_ms = millis(); + directionDernierChocRapport = -1; // À-coup sec vers la gauche + } + } + paletteMoinsDejaEnfoncee = true; + } else if (!pMoinsActuel && paletteMoinsDejaEnfoncee) { + paletteMoinsDejaEnfoncee = false; + } + + // Réglage FFB à la volée : + // - Molette rouge (CW/CCW) : Dureté du ressort de centrage (0 à 255) + // - Boutons [+] / [-] : Intensité des vibrations haptiques (0 à 100%, 0 = désactivé) + // Sur G29 en mode PS4 (PID 0xC260), la molette et les boutons +/- sont situés dans report[54]. + // On conserve également report[7] comme solution de secours universelle. + uint8_t b54 = (len > 54) ? report[54] : 0; + uint8_t b7 = (len > 7) ? report[7] : 0; + + bool dialPlusActuel = (b54 & DIAL_CW_MASK_B54) || (b7 & DIAL_CW_MASK_B7); + bool dialMoinsActuel = (b54 & DIAL_CCW_MASK_B54) || (b7 & DIAL_CCW_MASK_B7); + bool dialEnterActuel = (b54 & DIAL_ENTER_MASK_B54) || (b7 & DIAL_ENTER_MASK_B7); + + bool btnPlusActuel = (b54 & BOUTON_PLUS_MASK_B54) || (b7 & BOUTON_PLUS_MASK_B7); + bool btnMoinsActuel = (b54 & BOUTON_MOINS_MASK_B54) || (b7 & BOUTON_MOINS_MASK_B7); + + // Molette : Dureté du ressort de rappel (FFB) + if (dialPlusActuel && !dialPlusDejaEnfonce) { + if (configSysteme.forceRessort <= 245) configSysteme.forceRessort += 10; + else configSysteme.forceRessort = 255; + majRessortRequise = true; + logDureteRequis = true; + majLedRequise = true; + cockpitEtatModifie = true; + momentDernierChangementDurete_ms = millis(); + dialPlusDejaEnfonce = true; + } else if (!dialPlusActuel && dialPlusDejaEnfonce) { + dialPlusDejaEnfonce = false; + } + + if (dialMoinsActuel && !dialMoinsDejaEnfonce) { + if (configSysteme.forceRessort >= 10) configSysteme.forceRessort -= 10; + else configSysteme.forceRessort = 0; + majRessortRequise = true; + logDureteRequis = true; + majLedRequise = true; + cockpitEtatModifie = true; + momentDernierChangementDurete_ms = millis(); + dialMoinsDejaEnfonce = true; + } else if (!dialMoinsActuel && dialMoinsDejaEnfonce) { + dialMoinsDejaEnfonce = false; + } + + // Bouton [+] : Augmenter les vibrations (+10%) + if (btnPlusActuel && !btnPlusDejaEnfonce) { + if (configSysteme.intensiteVibration <= 90) configSysteme.intensiteVibration += 10; + else configSysteme.intensiteVibration = 100; + logVibrationRequis = true; + majLedRequise = true; + cockpitEtatModifie = true; + momentDernierChangementVib_ms = millis(); + btnPlusDejaEnfonce = true; + } else if (!btnPlusActuel && btnPlusDejaEnfonce) { + btnPlusDejaEnfonce = false; + } + + // Bouton [-] : Diminuer les vibrations (-10%, jusqu'à 0% = coupé) + if (btnMoinsActuel && !btnMoinsDejaEnfonce) { + if (configSysteme.intensiteVibration >= 10) configSysteme.intensiteVibration -= 10; + else configSysteme.intensiteVibration = 0; + logVibrationRequis = true; + majLedRequise = true; + cockpitEtatModifie = true; + momentDernierChangementVib_ms = millis(); + btnMoinsDejaEnfonce = true; + } else if (!btnMoinsActuel && btnMoinsDejaEnfonce) { + btnMoinsDejaEnfonce = false; + } + + // Détection des boutons libres du G29 pour piloter le casque SteamFrame FPV + uint8_t b5 = report[5]; + uint16_t btnsActuels = 0; + if (b5 & BOUTON_CROIX_MASK) btnsActuels |= EVT_BTN_CROSS; + if (b5 & BOUTON_ROND_MASK) btnsActuels |= EVT_BTN_CIRCLE; + if (b5 & BOUTON_CARRE_MASK) btnsActuels |= EVT_BTN_SQUARE; + if (b5 & BOUTON_TRIANGLE_MASK) btnsActuels |= EVT_BTN_TRIANGLE; + if (boutonsEpaule & BOUTON_SHARE_MASK) btnsActuels |= EVT_BTN_SHARE; + if (boutonsEpaule & BOUTON_OPTIONS_MASK) btnsActuels |= EVT_BTN_OPTIONS; + if (b7 & BOUTON_PS_MASK_B7) btnsActuels |= EVT_BTN_PS; + if (boutonsEpaule & BOUTON_L3_MASK) btnsActuels |= EVT_BTN_L3; + if (boutonsEpaule & BOUTON_R3_MASK) btnsActuels |= EVT_BTN_R3; + + uint8_t dpadActuel = (b5 & DPAD_MASK_B5); + if (etatDpadPrec != 0xFF && dpadActuel != etatDpadPrec) { + if (dpadActuel == 0) btnsActuels |= EVT_BTN_DPAD_UP; + else if (dpadActuel == 4) btnsActuels |= EVT_BTN_DPAD_DOWN; + else if (dpadActuel == 6) btnsActuels |= EVT_BTN_DPAD_LEFT; + else if (dpadActuel == 2) btnsActuels |= EVT_BTN_DPAD_RIGHT; + } + etatDpadPrec = dpadActuel; + + uint16_t frontsMontants = btnsActuels & ~etatBoutonsCockpitPrec; + if (frontsMontants != 0) { + __atomic_fetch_or(&evtBoutonsMasque, frontsMontants, __ATOMIC_ACQ_REL); + } + etatBoutonsCockpitPrec = btnsActuels & 0x01FF; // Mémorise uniquement les boutons (pas le D-Pad) + + // Sauvegarde en Flash protégée : nécessite un appui continu de 2 secondes sur Enter + // véhicule à l'arrêt et désarmé, pour interdire tout gel Flash intempestif en manipulant la molette. + static uint32_t debutAppuiEnter_ms = 0; + if (dialEnterActuel) { + if (debutAppuiEnter_ms == 0) { + debutAppuiEnter_ms = millis(); + } else if (!estArme && accelRaw <= DEADZONE_PEDALE && (millis() - debutAppuiEnter_ms >= 2000) && !dialEnterDejaEnfonce) { + demandeSauvegardeEEPROM = true; + dialEnterDejaEnfonce = true; + } + } else { + debutAppuiEnter_ms = 0; + dialEnterDejaEnfonce = false; + } + + int32_t volantCentre = (int32_t)volantRaw - CENTRE_VOLANT_BRUT; + dernierVolantCentre = volantCentre; + int32_t deltaMax = obtenirDeltaMaxVolant(); + int32_t volantBorne = constrain(volantCentre, -deltaMax, deltaMax); + + float x = (float)volantBorne / (float)deltaMax; + float expo = configSysteme.expoVolant; + float y = x * (1.0f - expo + expo * (x * x)); + uint16_t vVolant = constrain((int32_t)(CRSF_VAL_MID - y * (CRSF_VAL_MAX - CRSF_VAL_MID)), CRSF_VAL_MIN, CRSF_VAL_MAX); + + uint16_t vAccel = CRSF_VAL_MID; + if (estArme && accelRaw > DEADZONE_PEDALE) { // Désarmé : gaz coupés quoi qu'il arrive + if (rapportEngage == -1) { + vAccel = constrain(map(accelRaw, DEADZONE_PEDALE, 65535, configSysteme.gazArriereMin, configSysteme.gazArriereMax), CRSF_VAL_MIN, CRSF_VAL_MAX); + } else if (rapportEngage >= 1 && rapportEngage <= 3) { + uint16_t maxVitesse = configSysteme.gazAvantMax[rapportEngage - 1]; + vAccel = constrain(map(accelRaw, DEADZONE_PEDALE, 65535, configSysteme.gazAvantMin, maxVitesse), CRSF_VAL_MIN, CRSF_VAL_MAX); + } + } + + uint16_t vFrein = (freinRaw > DEADZONE_PEDALE) + ? constrain(map(freinRaw, DEADZONE_PEDALE, 65535, CRSF_VAL_MID, CRSF_VAL_MAX), CRSF_VAL_MIN, CRSF_VAL_MAX) + : CRSF_VAL_MID; + + uint16_t vEmbrayage = (embrayageRaw > DEADZONE_PEDALE) + ? constrain(map(embrayageRaw, DEADZONE_PEDALE, 65535, CRSF_VAL_MID, CRSF_VAL_MAX), CRSF_VAL_MIN, CRSF_VAL_MAX) + : CRSF_VAL_MID; + + assignerCanalCRSF(configSysteme.volant, vVolant); + assignerCanalCRSF(configSysteme.accel, vAccel); + assignerCanalCRSF(configSysteme.frein, vFrein); + assignerCanalCRSF(configSysteme.embrayage, vEmbrayage); + crsfChannelStore(CANAL_ARM - 1, __atomic_load_n(&estArme, __ATOMIC_ACQUIRE) ? CRSF_VAL_MAX : CRSF_VAL_MIN); + + // Horodatage APRÈS l'écriture des canaux : à la sortie d'un failsafe, le cœur 0 + // ne peut pas renvoyer d'anciennes valeurs (d'avant la coupure) pendant un paquet. + dernierRapportUSB_ms = millis(); + } + + tuh_hid_receive_report(dev_addr, instance); +} + +} // extern "C" diff --git a/src/engine/mod.rs b/src/engine/mod.rs index 5d2680d..7511bab 100644 --- a/src/engine/mod.rs +++ b/src/engine/mod.rs @@ -6,6 +6,7 @@ pub mod vr_menu; mod xr_session; pub use control_handle::EngineControlHandle; +pub use radxa_ssh::apply_radxa_wifi_channel_ssh; pub use types::{ DvrConfig, EngineSharedState, LiveOpticalParams, RetrySlot, RuntimeMonitor, SubsystemStatus, }; diff --git a/src/engine/radxa_ssh.rs b/src/engine/radxa_ssh.rs index 518bc4a..c5415af 100644 --- a/src/engine/radxa_ssh.rs +++ b/src/engine/radxa_ssh.rs @@ -4,6 +4,41 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use std::thread; +/// Exécute de façon synchrone la mise à jour du canal 5.8 GHz sur la Radxa Zero 3W via SSH sécurisé. +pub fn apply_radxa_wifi_channel_ssh(ch: u16, ip: std::net::IpAddr) -> std::result::Result<(), String> { + // Vérifie qu'au moins la mise à jour config ou `iw` réussit (exit != 0 si tout échoue) + let remote_cmd = format!( + "ok=0; \ + if [ -f /etc/wifibroadcast.cfg ]; then sed -i 's/^wifi_channel.*/wifi_channel = {ch}/' /etc/wifibroadcast.cfg && ok=1; fi; \ + for iface in wlan0 wlx*; do if [ -d \"/sys/class/net/$iface\" ]; then iw dev \"$iface\" set channel {ch} HT20 2>/dev/null && ok=1; fi; done; \ + [ \"$ok\" -eq 1 ]" + ); + + let res = std::process::Command::new("ssh") + .args([ + "-o", + "BatchMode=yes", + "-o", + "ConnectTimeout=2", + "-o", + "StrictHostKeyChecking=accept-new", + "--", + &format!("root@{}", ip), + &remote_cmd, + ]) + .output(); + + match res { + Ok(out) if out.status.success() => Ok(()), + Ok(out) => Err(format!( + "exit={}: {}", + out.status, + String::from_utf8_lossy(&out.stderr).trim() + )), + Err(e) => Err(format!("erreur exécution ssh: {}", e)), + } +} + /// Lance en arrière-plan la mise à jour du canal 5.8 GHz sur la Radxa Zero 3W via SSH sécurisé. /// Protégé par un verrou atomique `ssh_busy` pour empêcher les exécutions concurrentes. pub fn spawn_apply_radxa_channel( @@ -24,46 +59,19 @@ pub fn spawn_apply_radxa_channel( }; menu_ref.lock().set_feedback("ENVOI CANAL SSH...", false); - // Vérifie qu'au moins la mise à jour config ou `iw` réussit (exit != 0 si tout échoue) - let remote_cmd = format!( - "ok=0; \ - if [ -f /etc/wifibroadcast.cfg ]; then sed -i 's/^wifi_channel.*/wifi_channel = {ch}/' /etc/wifibroadcast.cfg && ok=1; fi; \ - for iface in wlan0 wlx*; do if [ -d \"/sys/class/net/$iface\" ]; then iw dev \"$iface\" set channel {ch} HT20 2>/dev/null && ok=1; fi; done; \ - [ \"$ok\" -eq 1 ]" - ); thread::spawn(move || { - let res = std::process::Command::new("ssh") - .args([ - "-o", - "BatchMode=yes", - "-o", - "ConnectTimeout=2", - "-o", - "StrictHostKeyChecking=accept-new", - "--", - &format!("root@{}", ip), - &remote_cmd, - ]) - .output(); + let res = apply_radxa_wifi_channel_ssh(ch, ip); ssh_busy.store(false, Ordering::Release); match res { - Ok(out) if out.status.success() => { + Ok(()) => { log::info!("[Menu VR] Canal 5.8GHz {} appliqué sur Radxa {}", ch, ip); menu_ref.lock().set_feedback("CANAL RADXA OK", false); } - Ok(out) => { - log::warn!( - "[Menu VR] Échec SSH canal Radxa (exit={}): {}", - out.status, - String::from_utf8_lossy(&out.stderr).trim() - ); + Err(err_msg) => { + log::warn!("[Menu VR] Échec SSH canal Radxa ({})", err_msg); menu_ref.lock().set_feedback("ECHEC SSH RADXA", true); } - Err(e) => { - log::error!("[Menu VR] Erreur SSH Radxa : {}", e); - menu_ref.lock().set_feedback("ERREUR SSH", true); - } } }); } diff --git a/src/ui/mod.rs b/src/ui/mod.rs index e3ffd6a..255584b 100644 --- a/src/ui/mod.rs +++ b/src/ui/mod.rs @@ -484,40 +484,17 @@ impl SteamFrameGpuiApp { ch, ip ); - let remote_cmd = format!( - "ok=0; \ - if [ -f /etc/wifibroadcast.cfg ]; then sed -i 's/^wifi_channel.*/wifi_channel = {ch}/' /etc/wifibroadcast.cfg && ok=1; fi; \ - for iface in wlan0 wlx*; do if [ -d \"/sys/class/net/$iface\" ]; then iw dev \"$iface\" set channel {ch} HT20 2>/dev/null && ok=1; fi; done; \ - [ \"$ok\" -eq 1 ]" - ); let busy = Arc::clone(&self.subprocess_busy); std::thread::spawn(move || { - let res = Command::new("ssh") - .args([ - "-o", - "BatchMode=yes", - "-o", - "ConnectTimeout=2", - "-o", - "StrictHostKeyChecking=accept-new", - "--", - &format!("root@{}", ip), - &remote_cmd, - ]) - .output(); + let res = crate::engine::apply_radxa_wifi_channel_ssh(ch, ip); busy.store(false, Ordering::Release); match res { - Ok(out) if out.status.success() => { + Ok(()) => { log::info!("[Radxa Zero 3W] Canal 5.8GHz configuré avec succès sur {}", ip); } - Ok(out) => { - log::warn!( - "[Radxa Zero 3W] SSH retour exit={} : {}", - out.status, - String::from_utf8_lossy(&out.stderr).trim() - ); + Err(err_msg) => { + log::warn!("[Radxa Zero 3W] Échec commande SSH ({})", err_msg); } - Err(e) => log::error!("[Radxa Zero 3W] Échec commande SSH : {}", e), } }); } diff --git a/src/video_usb.rs b/src/video_usb.rs index 0ea9b57..1b48f3a 100644 --- a/src/video_usb.rs +++ b/src/video_usb.rs @@ -667,12 +667,24 @@ fn extract_dmabuf_frame( } }; - let min_needed = uv_offset as usize + (uv_stride as usize) * (info.height() as usize / 2); - let total_size = mem.size().max(min_needed); + let min_y_bytes = (y_stride as usize).saturating_mul(info.height() as usize); + let min_uv_bytes = (uv_stride as usize).saturating_mul(info.height() as usize / 2); + let min_needed = (uv_offset as usize).saturating_add(min_uv_bytes); + let mem_size = mem.size(); + + // Garde de linéarité et de bornes : rejeter vers le repli CPU si le DMA-BUF est plus petit + // que le plan NV12 linéaire attendu (ex. buffer compressé/tuilé ou métadonnées incohérentes). + if y_stride < info.width() + || uv_stride < info.width() + || (uv_offset as usize) < min_y_bytes + || mem_size < min_needed + { + return None; + } Some(DmaBufFrame { fd, - size: total_size, + size: mem_size, width: info.width(), height: info.height(), y_stride, @@ -1015,7 +1027,9 @@ fn supervisor_loop( } } - let p = pipeline.as_ref().unwrap(); + let Some(p) = pipeline.as_ref() else { + continue; + }; let mut needs_rebuild = false; if let Some(bus) = p.bus() {