Files

412 lines
19 KiB
C

#pragma once
#include <Arduino.h>
#include <Adafruit_TinyUSB.h>
#include <pio_usb.h>
#include <Adafruit_NeoPixel.h>
#include <EEPROM.h>
#include <hardware/watchdog.h>
// 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) — WLToys 144010
#define GAZ_AVANT_MIN 1105
const uint16_t GAZ_AVANT_MAX_PAR_VITESSE[3] = {
1160, // 1ère vitesse (Manœuvre)
1250, // 2ème vitesse (Normale)
1400 // 3ème vitesse (Rapide)
};
#define GAZ_ARRIERE_MIN 875
#define GAZ_ARRIERE_MAX 750
#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 0x4C // Identifiant de validite en EEPROM (mis a jour pour vitesses WLToys 144010)
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 1105)
uint16_t gazAvantMax[3]; // Plafonds 1ère, 2ème, 3ème vitesse
uint16_t gazArriereMin; // Seuil de démarrage marche arrière (défaut 875)
uint16_t gazArriereMax; // Plafond marche arrière (défaut 750)
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();
}
}