#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) !!")); } }