From e18a9ea2b766bb24cc3db333b4411f454d0b524c Mon Sep 17 00:00:00 2001 From: bleackstorm <49142331+bleackstorm@users.noreply.github.com> Date: Thu, 12 Nov 2026 22:52:27 +0100 Subject: [PATCH] fix(security): durcissement inter-coeurs, failsafe arme et robustesse USB/CRSF --- g29_crsf.ino | 85 +++++++++++++++++++++++++++++++++------------------- 1 file changed, 55 insertions(+), 30 deletions(-) diff --git a/g29_crsf.ino b/g29_crsf.ino index e327b16..ba1503b 100644 --- a/g29_crsf.ino +++ b/g29_crsf.ino @@ -79,7 +79,7 @@ volatile uint16_t crsf_channels[16] = { CRSF_VAL_MID, CRSF_VAL_MID, CRSF_VAL_MID, CRSF_VAL_MID }; -struct ConfigG29 { +struct __attribute__((packed)) ConfigG29 { uint8_t volant; uint8_t accel; uint8_t frein; @@ -96,9 +96,9 @@ 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. - // Pour les plages réduites (< 900°), la butée logicielle démarre à ~96,4% de la demi-course (31600 points). - // À 900° complets, on utilise la course mécanique intégrale (32768) pour s'appuyer sur la butée physique. - maxDeltaVolant = (configSysteme.angleSouhaiteTotal >= 900) ? 32768 : DELTA_MAX_VOLANT_BRUT; + // 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 @@ -123,6 +123,7 @@ 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) // Failsafe et diagnostic volatile bool failsafeActif = true; // Écrit uniquement par le cœur 0 @@ -197,7 +198,6 @@ void sauvegarderConfiguration() { rp2040.wdt_reset(); // Note : EEPROM.commit() gère déjà automatiquement idleOtherCore() / resumeOtherCore() - memcpy(&cfgActuelle, (const void*)&configSysteme, sizeof(ConfigG29)); EEPROM.put(0, cfgActuelle); EEPROM.commit(); Serial.println(">> Configuration sauvegardée en mémoire Flash !"); @@ -367,9 +367,7 @@ void traiterLigneSerie(char* commande) { } else if (periph == 'D' || periph == 'd') { int val = atoi(&commande[2]); if (val >= 0 && val <= 255) { - rp2040.idleOtherCore(); - configSysteme.forceRessort = (uint8_t)val; - rp2040.resumeOtherCore(); + configSysteme.forceRessort = (uint8_t)val; // Atomique sur ARM Cortex-M33 majRessortRequise = true; demanderOuExecuterSauvegarde(); afficherConfiguration(); @@ -411,9 +409,7 @@ void traiterLigneSerie(char* commande) { } else if (periph == 'T' || periph == 't') { int val = atoi(&commande[2]); if (val >= 0 && val <= 100) { - rp2040.idleOtherCore(); - configSysteme.intensiteVibration = (uint8_t)val; - rp2040.resumeOtherCore(); + configSysteme.intensiteVibration = (uint8_t)val; // Atomique sur ARM Cortex-M33 demanderOuExecuterSauvegarde(); afficherConfiguration(); } else { @@ -548,6 +544,18 @@ void setup() { // Évalue le failsafe (cœur 0). Retourne true si les canaux doivent être forcés au neutre. bool evaluerFailsafe() { + uint32_t now = millis(); + + // 1. Surveillance de la santé du Cœur 1 (Watchdog logique inter-cœur) + if (heartbeatCore1_ms > 0 && (now - heartbeatCore1_ms > TIMEOUT_FAILSAFE_MS)) { + if (!failsafeActif) { + failsafeActif = true; + majLedRequise = true; + Serial.println(F("!! [FAILSAFE] Perte de reponse du Coeur 1 (Watchdog) !!")); + } + return true; + } + if (!volant_est_pret) { if (!failsafeActif) { failsafeActif = true; @@ -557,18 +565,18 @@ bool evaluerFailsafe() { return true; } - uint32_t age = millis() - dernierRapportUSB_ms; + uint32_t age = now - dernierRapportUSB_ms; // Sécurité intelligente : - // 1. En accélération (gaz enfoncés) : coupure d'urgence si aucun rapport depuis > 500 ms. - // 2. Au repos (gaz relâchés) : le G29 n'émet que sur mouvement d'axe (idle_rate = 0). - // La voiture est déjà à l'arrêt complet (gaz au neutre), aucun risque de perte de contrôle. - bool stale = (dernierAccelPct > 0.0f) && (age > TIMEOUT_FAILSAFE_MS); + // - En conduite armée (estArme == true) : tout silence USB > 500 ms est une anomalie critique (décélération en virage, déconnexion du volant). + // - Au repos désarmé (!estArme) : tolérance au silence du G29 si accélérateur et frein sont relâchés (idle_rate = 0 au repos). + bool stale = estArme ? (age > TIMEOUT_FAILSAFE_MS) + : ((dernierAccelPct > 0.0f || dernierFreinPct > 0.0f) && (age > TIMEOUT_FAILSAFE_MS)); if (stale && !failsafeActif) { failsafeActif = true; majLedRequise = true; - Serial.printf("!! [FAILSAFE] ACTIF (age=%lu ms, accel=%.1f%%) !!\n", (unsigned long)age, dernierAccelPct); + Serial.printf("!! [FAILSAFE] ACTIF (age=%lu ms, arme=%d) !!\n", (unsigned long)age, estArme ? 1 : 0); } else if (!stale && failsafeActif) { failsafeActif = false; majLedRequise = true; @@ -588,13 +596,21 @@ void traiterTelemetrieCRSF() { 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, etc.) - if (b == 0xC8 || b == 0xEE || b == 0xEA) { + // 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; @@ -627,8 +643,12 @@ void traiterTelemetrieCRSF() { prevRoll = roll; attitudeInitialisee = true; } else { - int32_t deltaPitch = abs((int32_t)pitch - (int32_t)prevPitch); - int32_t deltaRoll = abs((int32_t)roll - (int32_t)prevRoll); + 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; @@ -665,7 +685,10 @@ void traiterTelemetrieCRSF() { } void loop() { - rp2040.wdt_reset(); + // Watchdog dual-core : ne réarmer le watchdog matériel que si le Cœur 1 est également vivant + if (heartbeatCore1_ms == 0 || (millis() - heartbeatCore1_ms <= TIMEOUT_FAILSAFE_MS)) { + rp2040.wdt_reset(); + } verifierCommandesSerie(); traiterTelemetrieCRSF(); @@ -760,7 +783,7 @@ void loop() { // ========================================================================= // CŒUR 1 : PILE PIO-USB, AUTO-CENTER ET LEDS G29 // ========================================================================= -int32_t obtenirDeltaMaxVolant() { +static inline int32_t obtenirDeltaMaxVolant() { return (maxDeltaVolant > 0) ? maxDeltaVolant : DELTA_MAX_VOLANT_BRUT; } @@ -938,6 +961,8 @@ void gererVibrationHaptique() { envoyerForceG29(forceByte); } return; + } else { + directionDernierChocRapport = 0; } // Silence complet en marche arrière (-1) ou au point mort désarmé (0 && !estArme) @@ -995,6 +1020,7 @@ void setup1() { } void loop1() { + heartbeatCore1_ms = millis(); USBHost.task(); if (!volant_est_pret) return; @@ -1071,17 +1097,17 @@ void reinitialiserEtatVolant() { rugositeTerrainExterne = 0; } -// ========================================================================= -// CALLBACKS HID USB HOST (Exécutés sur Core 1) -// ========================================================================= -extern "C" { - -void assignerCanalCRSF(uint8_t numeroCh, uint16_t valeur11bits) { +static inline void assignerCanalCRSF(uint8_t numeroCh, uint16_t valeur11bits) { if (numeroCh >= 1 && numeroCh <= 16 && numeroCh != CANAL_ARM) { crsf_channels[numeroCh - 1] = valeur11bits; } } +// ========================================================================= +// CALLBACKS HID USB HOST (Exécutés sur Core 1) +// ========================================================================= +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; @@ -1137,7 +1163,6 @@ void __not_in_flash_func(tuh_hid_report_received_cb)(uint8_t dev_addr, uint8_t i compteurRapportsRejetes++; dernierRejetLen = len; dernierRejetId = (len > 0) ? report[0] : 0; - if (len > 0) dernierRapportUSB_ms = millis(); // Ne pas marquer comme actif sur erreur de transfert (len == 0) tuh_hid_receive_report(dev_addr, instance); return; }