mirror of
https://github.com/bleackstorm/SteamFrame-FPV-Control-Center.git
synced 2026-12-03 07:31:57 +01:00
1899 lines
74 KiB
Arduino
1899 lines
74 KiB
Arduino
#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)
|
|
#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 850
|
|
#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 (0=Range, 1=Spring)
|
|
#define VIBRATION_DEFAUT 50 // Intensite par defaut des vibrations (0 a 100%)
|
|
#define MAGIC_NUMBER_CONFIG 0x4A // Identifiant de validite en EEPROM (mis a jour pour 50% vibrations)
|
|
|
|
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%
|
|
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)
|
|
|
|
// 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;
|
|
|
|
// 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;
|
|
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 bool estActuellementArme() {
|
|
return (sourceActive == SRC_EXT) ? extArme : estArme;
|
|
}
|
|
|
|
static inline int8_t rapportActuel() {
|
|
return (sourceActive == SRC_EXT) ? extRapport : rapportEngage;
|
|
}
|
|
|
|
static inline void assignerCanalCRSF(uint8_t numeroCh, uint16_t valeur11bits) {
|
|
if (numeroCh >= 1 && numeroCh <= 16 && numeroCh != CANAL_ARM) {
|
|
crsf_channels[numeroCh - 1] = valeur11bits;
|
|
}
|
|
}
|
|
|
|
char serialBuffer[64];
|
|
uint8_t serialBufferIdx = 0;
|
|
char serial2Buffer[64];
|
|
uint8_t serial2BufferIdx = 0;
|
|
|
|
void reinitialiserCanauxCRSF() {
|
|
for (int i = 0; i < 16; i++) {
|
|
if (htActif && (i == (CANAL_HT_PAN - 1) || i == (CANAL_HT_TILT - 1) || i == (CANAL_HT_ROLL - 1))) {
|
|
continue;
|
|
}
|
|
crsf_channels[i] = CRSF_VAL_MID;
|
|
}
|
|
crsf_channels[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 = 2;
|
|
configSysteme.frein = 3;
|
|
configSysteme.embrayage = 4;
|
|
configSysteme.forceRessort = FORCE_RESSORT_DEFAUT;
|
|
configSysteme.angleSouhaiteTotal = ANGLE_DEFAUT_TOTAL;
|
|
configSysteme.expoVolant = EXPO_DEFAUT;
|
|
configSysteme.intensiteVibration = VIBRATION_DEFAUT;
|
|
configSysteme.magicNumber = MAGIC_NUMBER_CONFIG;
|
|
recalculerParametresVolant();
|
|
}
|
|
|
|
void sauvegarderConfiguration() {
|
|
ConfigG29 cfgActuelle;
|
|
memcpy(&cfgActuelle, (const void*)&configSysteme, sizeof(ConfigG29));
|
|
|
|
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.println("Commandes : V=ch, A=ch, F=ch, E=ch, D=val, P=val, X=val, T=val, $SRC,G29|EXT, $RC,..., $HT,..., S(save), R(reset), B(bootsel), ?");
|
|
}
|
|
|
|
void chargerConfiguration() {
|
|
ConfigG29 cfgStockee;
|
|
EEPROM.get(0, cfgStockee);
|
|
memcpy((void*)&configSysteme, &cfgStockee, sizeof(ConfigG29));
|
|
|
|
bool conflitArm = configSysteme.volant == CANAL_ARM || configSysteme.accel == CANAL_ARM ||
|
|
configSysteme.frein == CANAL_ARM || configSysteme.embrayage == CANAL_ARM;
|
|
|
|
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);
|
|
|
|
if (configSysteme.magicNumber != MAGIC_NUMBER_CONFIG || conflitArm || !canauxValides || !canauxDistincts || !expoValide || !angleValide || !vibValide) {
|
|
if (conflitArm) Serial.println("!! Un axe etait mappe sur le canal ARM : configuration reinitialisee !!");
|
|
else if (!canauxValides || !canauxDistincts) Serial.println("!! Conflit ou canal invalide en EEPROM : configuration reinitialisee !!");
|
|
else if (!expoValide || !angleValide || !vibValide) 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();
|
|
}
|
|
}
|
|
|
|
void traiterLigneSerie(char* commande) {
|
|
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;
|
|
sourceActive = SRC_G29;
|
|
majLedRequise = true;
|
|
cockpitEtatModifie = true;
|
|
momentDernierChangementDurete_ms = 0;
|
|
sauvegardeDifferee = false;
|
|
rp2040.resumeOtherCore();
|
|
majRangeRequise = true;
|
|
majRessortRequise = true;
|
|
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 = atoi(&commande[2]);
|
|
if (nouveauCanal < 1 || nouveauCanal > 16) {
|
|
Serial.println("!! Canal invalide : doit etre entre 1 et 16 !!");
|
|
return;
|
|
}
|
|
if (nouveauCanal == CANAL_ARM) {
|
|
Serial.printf("!! Canal %d reserve a l'armement (R2) !!\n", CANAL_ARM);
|
|
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 = atoi(&commande[2]);
|
|
if (val >= 0 && val <= 255) {
|
|
configSysteme.forceRessort = (uint8_t)val; // Atomique sur ARM Cortex-M33
|
|
majRessortRequise = true;
|
|
demanderOuExecuterSauvegarde();
|
|
afficherConfiguration();
|
|
} else {
|
|
Serial.println("!! Durete (D) doit etre 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 = atoi(&commande[2]);
|
|
if (val >= 40 && val <= 900) {
|
|
rp2040.idleOtherCore();
|
|
configSysteme.angleSouhaiteTotal = (uint16_t)val;
|
|
recalculerParametresVolant();
|
|
rp2040.resumeOtherCore();
|
|
majRangeRequise = true;
|
|
sauvegarderConfiguration();
|
|
afficherConfiguration();
|
|
} else {
|
|
Serial.println("!! Plage d'angle (P) doit etre 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 = atof(&commande[2]);
|
|
if (val >= 0.0f && val <= 0.8f) {
|
|
rp2040.idleOtherCore();
|
|
configSysteme.expoVolant = val;
|
|
rp2040.resumeOtherCore();
|
|
sauvegarderConfiguration();
|
|
afficherConfiguration();
|
|
} else {
|
|
Serial.println("!! Expo volant (X) doit etre entre 0.0 et 0.8 !!");
|
|
}
|
|
} else if (periph == 'T' || periph == 't') {
|
|
int val = atoi(&commande[2]);
|
|
if (val >= 0 && val <= 100) {
|
|
configSysteme.intensiteVibration = (uint8_t)val; // Atomique sur ARM Cortex-M33
|
|
cockpitEtatModifie = true;
|
|
demanderOuExecuterSauvegarde();
|
|
afficherConfiguration();
|
|
} else {
|
|
Serial.println("!! Vibrations (T) doit etre entre 0 et 100% !!");
|
|
}
|
|
} else if (periph == 'W' || periph == 'w') {
|
|
cockpitEchoUSB = (atoi(&commande[2]) != 0);
|
|
Serial.printf(">> [COCKPIT] Echo trames $G29 sur USB : %s\n", cockpitEchoUSB ? "ON" : "OFF");
|
|
}
|
|
return;
|
|
}
|
|
|
|
// Injection Head-Tracking depuis SteamFrame FPV : $HT,<pan>,<tilt>,<roll> (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) {
|
|
crsf_channels[CANAL_HT_PAN - 1] = (uint16_t)constrain(pan, CRSF_VAL_MIN, CRSF_VAL_MAX);
|
|
crsf_channels[CANAL_HT_TILT - 1] = (uint16_t)constrain(tilt, CRSF_VAL_MIN, CRSF_VAL_MAX);
|
|
crsf_channels[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();
|
|
sourceActive = cible;
|
|
extRcActif = false;
|
|
extArme = false;
|
|
extRapport = 0;
|
|
extAccelPct = 0;
|
|
extFreinPct = 0;
|
|
estArme = false;
|
|
rapportEngage = 0;
|
|
boutonArmDejaEnfonce = true;
|
|
palettePlusDejaEnfoncee = true;
|
|
paletteMoinsDejaEnfoncee = true;
|
|
etatBoutonsCockpitPrec = 0xFFFF;
|
|
reinitialiserCanauxCRSF();
|
|
rp2040.resumeOtherCore();
|
|
majLedRequise = true;
|
|
cockpitEtatModifie = true;
|
|
Serial.printf(">> [SRC] Source active basculee sur : %s\n",
|
|
(sourceActive == SRC_EXT) ? "EXT (Steam Controller)" : "G29 (Volant)");
|
|
return;
|
|
}
|
|
|
|
// Injection conduite externe (Steam Controller via SteamFrame FPV) :
|
|
// $RC,<steer>,<accel>,<brake>,<clutch>,<arm>,<gear>
|
|
if (strncmp(commande, "$RC,", 4) == 0) {
|
|
if (sourceActive != SRC_EXT) {
|
|
return;
|
|
}
|
|
int steer = CRSF_VAL_MID, accel = CRSF_VAL_MID, brake = CRSF_VAL_MID, clutch = CRSF_VAL_MID;
|
|
int arm = 0, gear = 0;
|
|
if (sscanf(commande + 4, "%d,%d,%d,%d,%d,%d", &steer, &accel, &brake, &clutch, &arm, &gear) == 6) {
|
|
uint16_t vSteer = (uint16_t)constrain(steer, CRSF_VAL_MIN, CRSF_VAL_MAX);
|
|
uint16_t vAccel = (uint16_t)constrain(accel, CRSF_VAL_MIN, CRSF_VAL_MAX);
|
|
uint16_t vBrake = (uint16_t)constrain(brake, CRSF_VAL_MIN, CRSF_VAL_MAX);
|
|
uint16_t vClutch = (uint16_t)constrain(clutch, CRSF_VAL_MIN, CRSF_VAL_MAX);
|
|
int8_t vGear = (int8_t)constrain(gear, -1, 3);
|
|
bool demandeArm = (arm != 0);
|
|
|
|
// Sécurité : refuser un armement (0 -> 1) si rapport != N ou gaz non neutres
|
|
if (demandeArm && !extArme) {
|
|
if (vGear == 0 && vAccel == CRSF_VAL_MID) {
|
|
extArme = true;
|
|
momentArmement_ms = millis();
|
|
momentDesarmement_ms = 0;
|
|
majLedRequise = true;
|
|
cockpitEtatModifie = true;
|
|
Serial.println(">> [ARM EXT] ARME (Steam Controller)");
|
|
}
|
|
} else if (!demandeArm && extArme) {
|
|
extArme = false;
|
|
momentDesarmement_ms = millis();
|
|
momentArmement_ms = 0;
|
|
majLedRequise = true;
|
|
cockpitEtatModifie = true;
|
|
Serial.println(">> [ARM EXT] DESARME (Steam Controller)");
|
|
}
|
|
|
|
if (vGear != extRapport) {
|
|
extRapport = vGear;
|
|
majLedRequise = true;
|
|
cockpitEtatModifie = true;
|
|
}
|
|
|
|
if (!extArme || extRapport == 0) {
|
|
vAccel = CRSF_VAL_MID;
|
|
}
|
|
|
|
uint8_t accelPct = 0;
|
|
if (extArme && extRapport >= 1 && extRapport <= 3 && vAccel >= GAZ_AVANT_MIN) {
|
|
uint16_t maxV = GAZ_AVANT_MAX_PAR_VITESSE[extRapport - 1];
|
|
accelPct = (uint8_t)constrain(map(vAccel, GAZ_AVANT_MIN, maxV, 0, 100), 0, 100);
|
|
} else if (extArme && extRapport == -1 && vAccel <= GAZ_ARRIERE_MIN) {
|
|
accelPct = (uint8_t)constrain(map(vAccel, GAZ_ARRIERE_MIN, GAZ_ARRIERE_MAX, 0, 100), 0, 100);
|
|
}
|
|
uint8_t brakePct = (vBrake > CRSF_VAL_MID)
|
|
? (uint8_t)constrain(map(vBrake, CRSF_VAL_MID, CRSF_VAL_MAX, 0, 100), 0, 100)
|
|
: 0;
|
|
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);
|
|
crsf_channels[CANAL_ARM - 1] = extArme ? CRSF_VAL_MAX : CRSF_VAL_MIN;
|
|
|
|
dernierPaquetRC_ms = millis();
|
|
if (!extRcActif) {
|
|
extRcActif = true;
|
|
majLedRequise = true;
|
|
cockpitEtatModifie = true;
|
|
}
|
|
}
|
|
return;
|
|
}
|
|
}
|
|
|
|
void lireFluxSerie(Stream& port, char* buf, uint8_t& idx, size_t maxLen) {
|
|
while (port.available() > 0) {
|
|
char c = (char)port.read();
|
|
if (c == '\n' || c == '\r') {
|
|
if (idx > 0) {
|
|
buf[idx] = '\0';
|
|
traiterLigneSerie(buf);
|
|
idx = 0;
|
|
}
|
|
} else if (idx < maxLen - 1) {
|
|
buf[idx++] = c;
|
|
} else {
|
|
idx = 0; // Ligne trop longue, reset
|
|
}
|
|
}
|
|
}
|
|
|
|
void verifierCommandesSerie() {
|
|
lireFluxSerie(Serial, serialBuffer, serialBufferIdx, sizeof(serialBuffer));
|
|
lireFluxSerie(Serial2, serial2Buffer, serial2BufferIdx, sizeof(serial2Buffer));
|
|
}
|
|
|
|
// -------------------------------------------------------------------------
|
|
// 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 : crsf_channels[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);
|
|
}
|
|
|
|
// =========================================================================
|
|
// CŒUR 0 : Initialisation, CRSF 166Hz, Série, EEPROM et LED RGB
|
|
// =========================================================================
|
|
void setup() {
|
|
Serial.begin(115200);
|
|
EEPROM.begin(EEPROM_SIZE);
|
|
|
|
rgb_led.begin();
|
|
rgb_led.setBrightness(50);
|
|
actualiserLED();
|
|
|
|
delay(500);
|
|
chargerConfiguration();
|
|
|
|
Serial1.setTX(0);
|
|
Serial1.setRX(1);
|
|
Serial1.begin(420000);
|
|
|
|
Serial2.setTX(PIN_UART_BRIDGE_TX);
|
|
Serial2.setRX(PIN_UART_BRIDGE_RX);
|
|
Serial2.begin(UART_BRIDGE_BAUD);
|
|
|
|
Serial.println("\n--- WAVESHARE RP2350-USB-A PRETE ---");
|
|
afficherConfiguration();
|
|
|
|
// Watchdog matériel : reboot si loop() ne le nourrit plus pendant WATCHDOG_TIMEOUT_MS
|
|
if (watchdog_caused_reboot()) {
|
|
Serial.println("!! [WATCHDOG] Redemarrage suite a un blocage !!");
|
|
}
|
|
rp2040.wdt_begin(WATCHDOG_TIMEOUT_MS);
|
|
}
|
|
|
|
// É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;
|
|
}
|
|
|
|
// 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) {
|
|
Serial2.println(ligne);
|
|
int needed = (int)strlen(ligne) + 2;
|
|
if (cockpitEchoUSB && Serial && Serial.availableForWrite() >= needed) {
|
|
Serial.println(ligne);
|
|
}
|
|
}
|
|
|
|
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 : crsf_channels[configSysteme.volant - 1];
|
|
uint16_t ch2 = failsafeActif ? CRSF_VAL_MID : crsf_channels[configSysteme.accel - 1];
|
|
uint16_t ch3 = failsafeActif ? CRSF_VAL_MID : crsf_channels[configSysteme.frein - 1];
|
|
uint16_t ch4 = failsafeActif ? CRSF_VAL_MID : crsf_channels[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;
|
|
crsf_channels[CANAL_HT_PAN - 1] = CRSF_VAL_MID;
|
|
crsf_channels[CANAL_HT_TILT - 1] = CRSF_VAL_MID;
|
|
crsf_channels[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 également vivant
|
|
if (heartbeatCore1_ms == 0 || (millis() - heartbeatCore1_ms <= TIMEOUT_FAILSAFE_MS)) {
|
|
rp2040.wdt_reset();
|
|
}
|
|
verifierCommandesSerie();
|
|
gererTimeoutHeadTracking();
|
|
gererTimeoutRcExterne();
|
|
traiterTelemetrieCRSF();
|
|
gererSortieCockpit();
|
|
|
|
static int8_t dernierRapportLog = 0xFF;
|
|
static uint32_t dernierTickAnimNeo_ms = 0;
|
|
bool enAnimationArm = (momentArmement_ms > 0 && (millis() - momentArmement_ms < 850)) ||
|
|
(momentDesarmement_ms > 0 && (millis() - momentDesarmement_ms < 250));
|
|
|
|
if (majLedRequise || (enAnimationArm && (millis() - dernierTickAnimNeo_ms >= 50))) {
|
|
majLedRequise = false;
|
|
dernierTickAnimNeo_ms = millis();
|
|
actualiserLED();
|
|
int8_t rap = rapportActuel();
|
|
if (rap != dernierRapportLog) {
|
|
dernierRapportLog = rap;
|
|
Serial.printf("[BOITE] Rapport engage : %d (%s)\n", rap, (sourceActive == SRC_EXT) ? "EXT" : "G29");
|
|
}
|
|
}
|
|
|
|
if (logMountRequis) {
|
|
logMountRequis = false;
|
|
Serial.printf("[USB HOST] G29 detecte ! VID=%04X, PID=%04X, dev=%d, inst=%d, desc_len=%d\n",
|
|
g29_vid, g29_pid, g29_dev_addr, g29_instance, g29_desc_len);
|
|
}
|
|
|
|
if (logRejetRequis) {
|
|
logRejetRequis = false;
|
|
Serial.printf("[USB HOST] Peripherique ignore (VID=%04X, PID=%04X) : pas un G29 en mode PS4\n",
|
|
rejet_vid, rejet_pid);
|
|
}
|
|
|
|
int8_t evtArm = logArmRequis;
|
|
if (evtArm != 0) {
|
|
logArmRequis = 0;
|
|
if (evtArm == 1) Serial.println(">> [ARM] ARME (R2)");
|
|
else if (evtArm == -1) Serial.println(">> [ARM] DESARME");
|
|
else if (evtArm == 3) Serial.println("!! [ARM] Refuse : initialisation FFB du G29 en cours (patienter) !!");
|
|
else Serial.println("!! [ARM] Refuse : passer au point mort (N) et relacher l'accelerateur !!");
|
|
}
|
|
|
|
if (logDureteRequis) {
|
|
logDureteRequis = false;
|
|
Serial.printf(">> [DURETE G29] Force ressort : %d / 255 (%d%%)\n",
|
|
configSysteme.forceRessort, (configSysteme.forceRessort * 100) / 255);
|
|
}
|
|
|
|
if (logVibrationRequis) {
|
|
logVibrationRequis = false;
|
|
if (configSysteme.intensiteVibration == 0) {
|
|
Serial.println(">> [VIBRATIONS] Desactivees (0%)");
|
|
} else {
|
|
Serial.printf(">> [VIBRATIONS] Intensite reglee a %d%%\n", configSysteme.intensiteVibration);
|
|
}
|
|
}
|
|
|
|
// Sauvegarde différée suite à une commande série (D= / T=) passée pendant la conduite
|
|
if (!estActuellementArme() && sauvegardeDifferee) {
|
|
sauvegardeDifferee = false;
|
|
sauvegarderConfiguration();
|
|
}
|
|
|
|
// Sauvegarde manuelle sur appui du bouton central Enter de la molette
|
|
// (interdite en conduite armée pour éviter un gel Flash)
|
|
if (demandeSauvegardeEEPROM) {
|
|
demandeSauvegardeEEPROM = false;
|
|
if (estActuellementArme()) {
|
|
Serial.println(F("!! Sauvegarde Flash refusee pendant la conduite (desarmer d'abord) !!"));
|
|
} else {
|
|
momentDernierChangementDurete_ms = 0;
|
|
sauvegardeDifferee = false;
|
|
sauvegarderConfiguration();
|
|
}
|
|
}
|
|
|
|
static uint32_t dernierHeartbeat = 0;
|
|
static uint32_t dernierCompteOK = 0;
|
|
if (millis() - dernierHeartbeat >= 2000) {
|
|
uint32_t dt = millis() - dernierHeartbeat;
|
|
dernierHeartbeat = millis();
|
|
uint32_t compteOK = compteurRapportsOK;
|
|
uint32_t rapportsParSec = ((compteOK - dernierCompteOK) * 1000UL) / (dt ? dt : 1);
|
|
dernierCompteOK = compteOK;
|
|
Serial.printf("[ETAT] SRC=%s | G29_Pret=%d (PID=%04X) | ExtRC=%d | InitFFB=%d/%d | Durete=%d/255 | Vib=%d%% | Rugosite=%d | Plage=%d deg | Rapport=%d | Arme=%d | Statut_LED=%d | USB=%lu rap/s | Rejetes=%lu (L=%d,ID=%02X) | Failsafe=%d\n",
|
|
(sourceActive == SRC_EXT) ? "EXT" : "G29",
|
|
volant_est_pret, g29_pid, extRcActif, etapeInitMoteur, ETAPES_INIT_FFB_TOTAL, configSysteme.forceRessort,
|
|
configSysteme.intensiteVibration, rugositeTerrainExterne, configSysteme.angleSouhaiteTotal,
|
|
rapportActuel(), estActuellementArme(), statutEnvoiLed,
|
|
(unsigned long)rapportsParSec, (unsigned long)compteurRapportsRejetes,
|
|
dernierRejetLen, dernierRejetId, failsafeActif);
|
|
}
|
|
|
|
// Transmission CRSF précise à 166.67 Hz (toutes les 6000 µs sans dérive ni burst)
|
|
static uint32_t dernier_envoi_us = 0;
|
|
if (dernier_envoi_us == 0) {
|
|
dernier_envoi_us = micros();
|
|
}
|
|
uint32_t now_us = micros();
|
|
if (now_us - dernier_envoi_us >= 6000) {
|
|
if (now_us - dernier_envoi_us >= 12000) {
|
|
dernier_envoi_us = now_us;
|
|
} else {
|
|
dernier_envoi_us += 6000;
|
|
}
|
|
envoyer_paquet_crsf(evaluerFailsafe());
|
|
}
|
|
}
|
|
|
|
// =========================================================================
|
|
// 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 <masque> 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() {
|
|
heartbeatCore1_ms = millis();
|
|
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;
|
|
}
|
|
|
|
// 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 (majRangeRequise) {
|
|
if (envoyerPlageG29(configSysteme.angleSouhaiteTotal)) {
|
|
majRangeRequise = false;
|
|
}
|
|
}
|
|
|
|
if (majRessortRequise) {
|
|
if (envoyerRessortG29(configSysteme.forceRessort)) {
|
|
majRessortRequise = false;
|
|
}
|
|
}
|
|
|
|
// Arrêt prioritaire du moteur de vibration dès le désarmement (ou si source externe active)
|
|
if ((sourceActive != SRC_G29 || !estArme) && !forceEstAuNeutre) {
|
|
if (arreterForceG29()) {
|
|
forceEstAuNeutre = true;
|
|
return;
|
|
}
|
|
}
|
|
|
|
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;
|
|
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, GAZ_ARRIERE_MIN, GAZ_ARRIERE_MAX), CRSF_VAL_MIN, CRSF_VAL_MAX);
|
|
} else if (rapportEngage >= 1 && rapportEngage <= 3) {
|
|
uint16_t maxVitesse = GAZ_AVANT_MAX_PAR_VITESSE[rapportEngage - 1];
|
|
vAccel = constrain(map(accelRaw, DEADZONE_PEDALE, 65535, GAZ_AVANT_MIN, 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);
|
|
crsf_channels[CANAL_ARM - 1] = estArme ? 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"
|