diff --git a/firmware/g29_crsf/.gitignore b/firmware/g29_crsf/.gitignore new file mode 100644 index 0000000..8cbfc39 --- /dev/null +++ b/firmware/g29_crsf/.gitignore @@ -0,0 +1,3 @@ +__pycache__/ +*.pyc +build/ diff --git a/firmware/g29_crsf/README.md b/firmware/g29_crsf/README.md new file mode 100644 index 0000000..d094303 --- /dev/null +++ b/firmware/g29_crsf/README.md @@ -0,0 +1,94 @@ +# G29-CRSF Hub (`g29_crsf` — Waveshare RP2350-USB-A) + +Firmware dual-core pour **Waveshare RP2350-USB-A** transformant un volant **Logitech G29** (en mode PS4) en **émetteur CRSF 16 canaux @ 166,7 Hz** vers un module **RadioMaster Nomad (ExpressLRS)** et servant de **hub central unifié (100 % filaire, zéro Wi-Fi)** pour le casque **Steam Frame (`steamframe-fpv`)**. + +--- + +## Architecture Unifiée (100 % Filaire) + +```text +[Volant + Pédales G29] + │ (USB-A Host PIO-USB GP12/13) + ▼ +[Waveshare RP2350-USB-A] + ├── GP0 (TX) / GP1 (RX) @ 420 000 bauds ◄═══► [RadioMaster Nomad (ELRS)] + │ • Aller : CRSF 16ch @ 166.7 Hz (CH1-5 = G29, CH6-8 = Head-Tracking) + │ • Retour : Télémétrie CRSF véhicule (Attitude, Batt, GPS, LQ/RSSI) + │ + └── UART GP4/GP5 @ 460 800 bauds (ou USB-C /dev/ttyACM0) + ▼ +[Radxa Zero 3W (VRX)] ◄══► [Splitter USB-C PD] ◄══► [Casque Steam Frame] +``` + +### Ce qui est centralisé sur la RP2350 : +1. **Pilotage G29 (`CH1..CH5`)** : Volant (`CH1`), Accélérateur avec boîte séquentielle R/N/1/2/3 (`CH2`), Frein (`CH3`), Embrayage (`CH4`), Armement R2 (`CH5`). +2. **Mixage Head-Tracking (`CH6..CH8`)** : Réception des trames `$HT,,,` (valeurs CRSF `172..1811`, neutre `992`) depuis le casque via la Radxa Zero 3W (`Serial2` à `460 800 bauds` ou `Serial` USB-C), avec **watchdog de recentrage automatique à `500 ms`**. +3. **Relais Télémétrie & État Cockpit** : + - État G29 à 20 Hz (`$G29,ARM=...,GEAR=...,THROT=...,BRAKE=...,FFB=...,VIB=...,FAIL=...`). + - Événements boutons immédiats (`$G29_EVT,BTN=...`) pour piloter l'OSD, le DVR, le mode de projection VR et la Tare Head-Tracking depuis le volant. + - Relais complet des trames CRSF valides reçues sur `GP1` (`$CRSF,`) vers l'OSD de `steamframe-fpv`, tout en conservant le calcul local de rugosité (`0x1E`) pour le retour de force haptique du volant. + +--- + +## Brochage Waveshare RP2350-USB-A + +| Broche | Fonction | Cible | +| :--- | :--- | :--- | +| **USB-A (GP12/GP13)** | USB Host PIO-USB | Volant Logitech G29 (mode PS4) | +| **GP0 (Serial1 TX)** | CRSF TX `420 000 bauds` | RadioMaster Nomad (Baie JR / RX) | +| **GP1 (Serial1 RX)** | CRSF RX `420 000 bauds` | RadioMaster Nomad (Télémétrie) | +| **GP4 (Serial2 TX)** | Pont Cockpit TX `460 800 bauds` | Radxa Zero 3W RX (`radxa_g29_relay.py`) | +| **GP5 (Serial2 RX)** | Pont Cockpit RX `460 800 bauds` | Radxa Zero 3W TX (`radxa_g29_relay.py`) | +| **USB-C natif** | Série CDC + Flash | Liaison directe alternative ou debug | +| **GP16** | LED RGB WS2812 | État armement / rapport engagé / failsafe | + +--- + +## Mapping Complet des Touches du Logitech G29 + +### 1. Conduite, Radio CRSF & Retour de Force (RP2350) +| Touche / Axe G29 | Action | Canal / Effet | +| :--- | :--- | :--- | +| **Volant** | Direction | `CH1` (plage `40..900°`, expo configurable) | +| **Pédale Accélérateur** | Gaz progressifs selon rapport (`R`, `1`, `2`, `3`) | `CH2` | +| **Pédale Frein** | Frein | `CH3` | +| **Pédale Embrayage** | Embrayage | `CH4` | +| **`R2`** | Bascule **Armé / Désarmé** *(au point mort `N`, gaz relâchés)* | `CH5` (`AUX1`) | +| **Palette droite (`R1`) / gauche (`L1`)** | Monter / rétrograder un rapport (`R ⇄ N ⇄ 1 ⇄ 2 ⇄ 3`) | Boîte séquentielle + LEDs | +| **Molette rouge (`CW` / `CCW`)** | Dureté du ressort de centrage FFB (`0..255`) | Retour de force | +| **Boutons `+` / `-`** | Intensité des vibrations haptiques (`0..100 %`, `0` = coupé) | Haptique volant | +| **Bouton central `Enter`** *(appui 2 s désarmé)* | Sauvegarde des réglages en mémoire Flash (EEPROM) | Persistance | + +### 2. Commandes Cockpit SteamFrame FPV (`$G29_EVT` via Radxa / USB) +| Touche G29 | Action dans `steamframe-fpv` | Toast OSD | +| :--- | :--- | :--- | +| **`Croix (✕)`**, **`PS`** ou **`R3`** | **Tare Head-Tracking** (recentre la vue et la nacelle) | `TARE HT OK` | +| **`Rond (○)`** ou **`Share`** | **Enregistrement DVR** (Démarrer / Arrêter) | `DVR REC` / `DVR STOP` | +| **`Triangle (△)`** | **Incrustation OSD** (Afficher / Masquer) | `OSD ON` / `OSD OFF` | +| **`Carré (□)`** | **Mode de projection VR** (`Dome140` ➔ `Cylinder140` ➔ `FlatQuad`) | `PROJ: ...` | +| **`D-Pad` Haut / Bas** | **Trim Tilt** caméra (`+1°` / `-1°`) | `TILT +1` / `TILT -1` | +| **`D-Pad` Gauche / Droite** | **Trim Pan** caméra (`-1°` / `+1°`) | `PAN -1` / `PAN +1` | +| **`Options`**, **`L3`** | Réservés (libres pour extensions futures) | — | + +--- + +## Commandes Série (`Serial` & `Serial2`) + +| Commande | Description | +| :--- | :--- | +| `$HT,,,` | Injecte le Head-Tracking sur `CH6, CH7, CH8` (`172..1811`) | +| `D=<0..255>` | Règle la dureté du ressort FFB (sauvegarde différée si armé) | +| `T=<0..100>` | Règle l'intensité des vibrations haptiques (`0` = désactivé) | +| `P=<40..900>` | Plage de rotation du volant en degrés (désarmé uniquement) | +| `X=<0.0..0.8>` | Expo volant (désarmé uniquement) | +| `V/A/F/E=` | Remappage des canaux Volant / Accel / Frein / Embrayage | +| `W=<0\|1>` | Active/désactive l'écho des trames `$G29`/`$CRSF` sur USB-C (`1` par défaut) | +| `?` / `S` / `R` / `B` | Afficher config / Sauvegarder EEPROM / Reset usine / BOOTSEL | + +--- + +## Compilation (`arduino-cli`) + +```bash +arduino-cli compile --fqbn rp2040:rp2040:waveshare_rp2350_plus:usbstack=tinyusb --build-path ./build . +``` diff --git a/firmware/g29_crsf/decode_g29.py b/firmware/g29_crsf/decode_g29.py new file mode 100755 index 0000000..c314cfd --- /dev/null +++ b/firmware/g29_crsf/decode_g29.py @@ -0,0 +1,177 @@ +#!/usr/bin/env python3 +""" +G29 HID Frame Sniffer & Decoder +Usage: python3 decode_g29.py [--raw] +""" + +import os +import sys +import glob +import time +import struct +import select + +def find_g29_hidraw(): + for hidraw in sorted(glob.glob('/dev/hidraw*')): + name = os.path.basename(hidraw) + uevent_path = f'/sys/class/hidraw/{name}/device/uevent' + if os.path.exists(uevent_path): + with open(uevent_path, 'r') as f: + content = f.read() + if '046D:0000C260' in content.upper() or '046D:0000C294' in content.upper() or 'LOGITECH' in content.upper(): + return hidraw + return None + +def format_hat(hat_val): + hat_names = { + 0: "↑ (Haut)", + 1: "↗ (Haut-Droite)", + 2: "→ (Droite)", + 3: "↘ (Bas-Droite)", + 4: "↓ (Bas)", + 5: "↙ (Bas-Gauche)", + 6: "← (Gauche)", + 7: "↖ (Haut-Gauche)", + 8: "Neutre" + } + return hat_names.get(hat_val, f"Inconnu({hat_val})") + +def main(): + hid_path = find_g29_hidraw() + if not hid_path: + print("Erreur: Logitech G29 non trouvé dans /dev/hidraw* !") + sys.exit(1) + + print(f"=== Logitech G29 détecté sur {hid_path} ===") + print("En attente de mouvements ou boutons (appuie sur une pédale, tourne le volant ou clique)...") + print("Appuie sur Ctrl+C pour quitter.\n") + + try: + fd = os.open(hid_path, os.O_RDWR) + except PermissionError: + print(f"Erreur de permission sur {hid_path}. Lance avec sudo ou vérifie les ACLs.") + sys.exit(1) + + last_report = None + last_print_time = 0 + + try: + while True: + r, _, _ = select.select([fd], [], [], 0.5) + if not r: + continue + + report = os.read(fd, 128) + now = time.time() + if not report: + continue + + # Check if anything changed compared to last_report + if last_report is not None and report == last_report: + continue + + # Detect differences + diffs = [] + if last_report is not None and len(last_report) == len(report): + for i in range(len(report)): + if report[i] != last_report[i]: + diffs.append(f"B[{i}]: 0x{last_report[i]:02X} -> 0x{report[i]:02X} (déc:{report[i]})") + + last_report = report + + # Decode standard G29 PS4 report + # Length is typically 64 bytes (report[0] is Report ID 0x01) + report_id = report[0] + + # Print decoded info + out_lines = [] + out_lines.append(f"--- [Rapport ID: 0x{report_id:02X} | Longueur: {len(report)} octets] ---") + + if len(report) >= 51 and report_id == 0x01: + # 16-bit axes (from g29_crsf.ino) + wheel_raw = report[43] | (report[44] << 8) + accel_raw = 65535 - (report[45] | (report[46] << 8)) + brake_raw = 65535 - (report[47] | (report[48] << 8)) + clutch_raw = 65535 - (report[49] | (report[50] << 8)) + + # Percentages + wheel_pct = (wheel_raw / 65535.0) * 100.0 + accel_pct = (accel_raw / 65535.0) * 100.0 + brake_pct = (brake_raw / 65535.0) * 100.0 + clutch_pct = (clutch_raw / 65535.0) * 100.0 + + out_lines.append(f"Volant : {wheel_raw:5d} / 65535 ({wheel_pct:5.1f}%) | " + f"Gaz : {accel_raw:5d} ({accel_pct:4.1f}%) | " + f"Frein : {brake_raw:5d} ({brake_pct:4.1f}%) | " + f"Embrayage : {clutch_raw:5d} ({clutch_pct:4.1f}%)") + + # Buttons byte 5 & 6 & 7 + b5 = report[5] + hat = b5 & 0x0F + btn_sq = bool(b5 & 0x10) + btn_cross = bool(b5 & 0x20) + btn_circle = bool(b5 & 0x40) + btn_triangle = bool(b5 & 0x80) + + b6 = report[6] + btn_l1 = bool(b6 & 0x01) # Palette - + btn_r1 = bool(b6 & 0x02) # Palette + + btn_l2 = bool(b6 & 0x04) + btn_r2 = bool(b6 & 0x08) + btn_share = bool(b6 & 0x10) + btn_option = bool(b6 & 0x20) + btn_l3 = bool(b6 & 0x40) + btn_r3 = bool(b6 & 0x80) + + b7 = report[7] if len(report) > 7 else 0 + btn_ps = bool(b7 & 0x01) + btn_plus = bool(b7 & 0x04) + btn_minus = bool(b7 & 0x08) + dial_cw = bool(b7 & 0x10) + dial_ccw = bool(b7 & 0x20) + dial_enter = bool(b7 & 0x40) + + active_buttons = [] + if btn_sq: active_buttons.append("Carré [□]") + if btn_cross: active_buttons.append("Croix [✕]") + if btn_circle: active_buttons.append("Rond [○]") + if btn_triangle: active_buttons.append("Triangle [△]") + if btn_l1: active_buttons.append("L1 (Palette -)") + if btn_r1: active_buttons.append("R1 (Palette +)") + if btn_l2: active_buttons.append("L2") + if btn_r2: active_buttons.append("R2 (Arm)") + if btn_share: active_buttons.append("Share") + if btn_option: active_buttons.append("Options") + if btn_l3: active_buttons.append("L3") + if btn_r3: active_buttons.append("R3") + if btn_ps: active_buttons.append("PS") + if btn_plus: active_buttons.append("Plus [+]") + if btn_minus: active_buttons.append("Moins [-]") + if dial_cw: active_buttons.append("Molette (Sens horaire ↷)") + if dial_ccw: active_buttons.append("Molette (Sens anti-horaire ↶)") + if dial_enter: active_buttons.append("Molette (Enter central)") + + # Check additional bytes for rotary knob and +/- and Enter + # Often in report[7], report[8] or other vendor bytes + out_lines.append(f"D-Pad : {format_hat(hat)}") + out_lines.append(f"Boutons: {', '.join(active_buttons) if active_buttons else 'Aucun'}") + + if diffs: + out_lines.append("Changements détectés : " + " | ".join(diffs)) + + # Raw hex dump (condensed) + hex_view = ' '.join(f'{b:02X}' for b in report[:32]) + if len(report) > 32: + hex_view += ' ... ' + ' '.join(f'{b:02X}' for b in report[32:52]) + out_lines.append(f"Hex: {hex_view}") + + print("\n".join(out_lines)) + print() + + except KeyboardInterrupt: + print("\nArrêt.") + finally: + os.close(fd) + +if __name__ == '__main__': + main() diff --git a/firmware/g29_crsf/g29_crsf.ino b/firmware/g29_crsf/g29_crsf.ino new file mode 100644 index 0000000..23419f3 --- /dev/null +++ b/firmware/g29_crsf/g29_crsf.ino @@ -0,0 +1,1666 @@ +#include +#include +#include +#include +#include +#include + +// Brochage natif de la Waveshare RP2350-USB-A +#define HOST_PIN_DP 12 // USB-A D+ (D- est automatiquement sur GP13) +#define NUM_PIXELS 1 +#define PIN_LED_RGB 16 // LED RGB WS2812 intégrée +#define EEPROM_SIZE 32 + +// Sécurité : failsafe, watchdog et identification du volant +#define TIMEOUT_FAILSAFE_MS 1000 // Watchdog inter-coeur : alerte si le coeur 1 ne repond plus depuis X ms +#define WATCHDOG_TIMEOUT_MS 1000 // Reboot materiel si le coeur 0 se fige +#define G29_VID 0x046D +#define G29_PID_PS4 0xC260 // G29 en mode PS4 (le mode PS3 = 0xC24F a un autre format de rapport) +#define G29_REPORT_ID 0x01 + +// Masques additionnels dans report[5] (D-Pad et boutons façade en mode PS4) +#define DPAD_MASK_B5 0x0F // Quartet bas : 0=Haut, 2=Droite, 4=Bas, 6=Gauche, 8=Neutre +#define BOUTON_CARRE_MASK 0x10 // Carré [□] +#define BOUTON_CROIX_MASK 0x20 // Croix [✕] +#define BOUTON_ROND_MASK 0x40 // Rond [○] +#define BOUTON_TRIANGLE_MASK 0x80 // Triangle [△] + +// Masques des palettes et boutons dans report[6] +#define PALETTE_MOINS_MASK 0x01 // L1 (Palette gauche : Rétrograder) +#define PALETTE_PLUS_MASK 0x02 // R1 (Palette droite : Monter un rapport) +#define BOUTON_L2_MASK 0x04 // L2 +#define BOUTON_ARM_MASK 0x08 // R2 (Bascule Armé / Désarmé) +#define BOUTON_SHARE_MASK 0x10 // Share +#define BOUTON_OPTIONS_MASK 0x20 // Options +#define BOUTON_L3_MASK 0x40 // L3 +#define BOUTON_R3_MASK 0x80 // R3 + +// Masques additionnels dans report[54] (Molette et boutons + / - / Enter en mode PS4 PID 0xC260) +#define DIAL_ENTER_MASK_B54 0x01 // Bouton central de la molette +#define DIAL_CCW_MASK_B54 0x02 // Molette sens anti-horaire (Dureté -) +#define DIAL_CW_MASK_B54 0x04 // Molette sens horaire (Dureté +) +#define BOUTON_MOINS_MASK_B54 0x08 // Bouton [-] (Dureté -) +#define BOUTON_PLUS_MASK_B54 0x10 // Bouton [+] (Dureté +) + +// Masques de secours dans report[7] (Mode PC / rapport court + bouton PS) +#define BOUTON_PS_MASK_B7 0x01 // Bouton PS +#define BOUTON_PLUS_MASK_B7 0x04 // Bouton [+] +#define BOUTON_MOINS_MASK_B7 0x08 // Bouton [-] +#define DIAL_CW_MASK_B7 0x10 // Molette sens horaire +#define DIAL_CCW_MASK_B7 0x20 // Molette sens anti-horaire +#define DIAL_ENTER_MASK_B7 0x40 // Bouton central de la molette + +// Liaison série bidirectionnelle vers le pont Radxa Zero 3W / SteamFrame FPV Cockpit +#define PIN_UART_BRIDGE_TX 4 +#define PIN_UART_BRIDGE_RX 5 +#define UART_BRIDGE_BAUD 460800 +#define INTERVALLE_COCKPIT_MS 50 // 20 Hz +#define TIMEOUT_HT_MS 500 // Retour au centre si le casque ne répond plus + +// 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 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; + +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("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, 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 (estArme) { + 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 (estArme) { + 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 (estArme) { + 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 (estArme) { + Serial.println("!! Reinitialisation refusee pendant la conduite (desarmer d'abord) !!"); + return; + } + rp2040.idleOtherCore(); + reinitialiserConfigurationDefaut(); + reinitialiserCanauxCRSF(); + rapportEngage = 0; + estArme = false; + majLedRequise = 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 (estArme) { + 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 (estArme) { + 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 (estArme) { + 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,,, (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; + } + } +} + +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 (!volant_est_pret) { + b = 255; // Bleu : Attente G29 + } else if (failsafeActif) { + r = 255; g = 255; b = 255; // Blanc : Failsafe (G29 muet) + } else { + switch (rapportEngage) { + 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 (!estArme) { // 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. 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) { + 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) { + 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; + int throt = (int)constrain(dernierAccelPct + 0.5f, 0.0f, 100.0f); + int brake = (int)constrain(dernierFreinPct + 0.5f, 0.0f, 100.0f); + char bufEtat[96]; + snprintf(bufEtat, sizeof(bufEtat), + "$G29,ARM=%d,GEAR=%d,THROT=%d,BRAKE=%d,FFB=%d,VIB=%d,FAIL=%d", + estArme ? 1 : 0, + (int)rapportEngage, + throt, + brake, + (int)configSysteme.forceRessort, + (int)configSysteme.intensiteVibration, + failsafeActif ? 1 : 0); + 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 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(); + 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(); + if (rapportEngage != dernierRapportLog) { + dernierRapportLog = rapportEngage; + Serial.printf("[BOITE] Rapport engage : %d\n", rapportEngage); + } + } + + 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 (!estArme && 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 (estArme) { + 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] G29_Pret=%d (PID=%04X) | 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", + volant_est_pret, g29_pid, etapeInitMoteur, ETAPES_INIT_FFB_TOTAL, configSysteme.forceRessort, + configSysteme.intensiteVibration, rugositeTerrainExterne, configSysteme.angleSouhaiteTotal, + rapportEngage, estArme, 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 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 (!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 (avant l'animation LED) + if (!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; + rugositeTerrainExterne = 0; +} + +static inline void assignerCanalCRSF(uint8_t numeroCh, uint16_t valeur11bits) { + if (numeroCh >= 1 && numeroCh <= 16 && numeroCh != CANAL_ARM) { + crsf_channels[numeroCh - 1] = valeur11bits; + } +} + +// ========================================================================= +// CALLBACKS HID USB HOST (Exécutés sur Core 1) +// ========================================================================= +extern "C" { + +void tuh_hid_mount_cb(uint8_t dev_addr, uint8_t instance, uint8_t const* desc_report, uint16_t desc_len) { + (void)desc_report; + + // 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(); + 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++; + + 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 (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; + + 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" diff --git a/firmware/g29_crsf/isolate_led.py b/firmware/g29_crsf/isolate_led.py new file mode 100644 index 0000000..9cf6337 --- /dev/null +++ b/firmware/g29_crsf/isolate_led.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python3 +""" +Isolate the exact LED command on G29 +""" + +import os +import sys +import glob +import time +import fcntl + +HIDIOCSFEATURE = lambda length: 0xC0004806 | (length << 16) + +def find_g29(): + for h in sorted(glob.glob('/dev/hidraw*')): + uevent = f'/sys/class/hidraw/{os.path.basename(h)}/device/uevent' + if os.path.exists(uevent): + try: + with open(uevent) as f: + c = f.read().upper() + if '046D:0000C260' in c or '046D:0000C24F' in c or 'LOGITECH' in c: + return h + except Exception: + pass + return '/dev/hidraw2' + +def make_cmd(mask): + return bytes([0xF8, 0x12, mask, 0x00, 0x00, 0x00, 0x00]) + +candidates = { + # Key: (name, function(fd, mask)) + "P1": ("P1: Raw 7 bytes on EP OUT (hidraw strip 0x00)", + lambda fd, m: os.write(fd, bytes([0x00]) + make_cmd(m))), + + "P2": ("P2: 8 bytes avec 1-byte offset 0x00 (GIMX format)", + lambda fd, m: os.write(fd, bytes([0x00, 0x00]) + make_cmd(m))), + + "P3": ("P3: Output Report 0x05 standard (32 octets)", + lambda fd, m: os.write(fd, bytes([0x05]) + make_cmd(m) + bytes([0x00]*24))), + + "P4": ("P4: Output Report 0x05 avec offset 0x00 (32 octets)", + lambda fd, m: os.write(fd, bytes([0x05, 0x00]) + make_cmd(m) + bytes([0x00]*23))), + + "P5": ("P5: Output Report 0x05 paddé à 64 octets", + lambda fd, m: os.write(fd, bytes([0x05]) + make_cmd(m) + bytes([0x00]*56))), + + "P6": ("P6: Feature Report 0xF3 (7 octets payload)", + lambda fd, m: fcntl.ioctl(fd, HIDIOCSFEATURE(8), bytearray([0xF3]) + bytearray(make_cmd(m)))), + + "P7": ("P7: Feature Report 0xF3 (offset 0x00)", + lambda fd, m: fcntl.ioctl(fd, HIDIOCSFEATURE(9), bytearray([0xF3, 0x00]) + bytearray(make_cmd(m)))), + + "P8": ("P8: Feature Report 0xF0 (63 octets payload)", + lambda fd, m: fcntl.ioctl(fd, HIDIOCSFEATURE(64), bytearray([0xF0]) + bytearray(make_cmd(m)) + bytearray([0x00]*56))), + + "P10": ("P10: Report 0x30 (64 octets)", + lambda fd, m: os.write(fd, bytes([0x30]) + make_cmd(m) + bytes([0x00]*56))), +} + +if __name__ == '__main__': + if len(sys.argv) < 3: + print("Usage: python3 isolate_led.py ") + sys.exit(1) + + cid = sys.argv[1].upper() + action = sys.argv[2].lower() + + if cid not in candidates: + print(f"Candidat inconnu: {cid}. Choisis parmi {list(candidates.keys())}") + sys.exit(1) + + name, func = candidates[cid] + print(f"Test de {name} -> Action: {action}") + dev = find_g29() + fd = os.open(dev, os.O_RDWR) + + if action == 'off': + func(fd, 0x00) + print("Envoyé: ÉTEINT (0x00)") + elif action == 'on': + func(fd, 0x1F) + print("Envoyé: TOUT ALLUMÉ (0x1F)") + elif action == 'blink': + print("Clignotement 3 fois...") + for _ in range(3): + func(fd, 0x1F) + time.sleep(0.3) + func(fd, 0x00) + time.sleep(0.3) + elif action == 'chase': + print("Chenillard (1 par 1)...") + # 0x01 (2 vertes), 0x03 (4 vertes), 0x07 (2 jaunes), 0x0F (4 jaunes), 0x1F (rouge) + for m in [0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x0F, 0x07, 0x03, 0x01, 0x00]: + func(fd, m) + time.sleep(0.15) + + os.close(fd) diff --git a/firmware/g29_crsf/test_leds.py b/firmware/g29_crsf/test_leds.py new file mode 100644 index 0000000..503b4f4 --- /dev/null +++ b/firmware/g29_crsf/test_leds.py @@ -0,0 +1,199 @@ +#!/usr/bin/env python3 +""" +Interactive LED frame test for Logitech G29 on Linux (/dev/hidraw2) +Tests multiple framing methods for RPM LEDs: + - Output report 0x05 (32 bytes) + - Feature report 0xF3 (7-8 bytes) + - Feature report 0xF0 (64 bytes) + - Raw unnumbered output report (0x00 + 7-8 bytes) + - Raw direct output report (0xF8 + 7 bytes) +""" + +import os +import sys +import fcntl +import time + +HIDIOCSFEATURE = lambda length: 0xC0004806 | (length << 16) + +def find_g29(): + import glob + for h in sorted(glob.glob('/dev/hidraw*')): + uevent = f'/sys/class/hidraw/{os.path.basename(h)}/device/uevent' + if os.path.exists(uevent): + with open(uevent) as f: + c = f.read().upper() + if '046D:0000C260' in c or '046D:0000C24F' in c or 'LOGITECH' in c: + return h + return '/dev/hidraw2' + +def test_method(fd, name, func): + print(f"\n==========================================") + print(f"▶ TEST: {name}") + print(f"==========================================") + # Send all LEDs ON (0x1F = 5 pairs = all 5 LEDs) + func(0x1F) + time.sleep(1.5) + # Send all LEDs OFF (0x00) + func(0x00) + time.sleep(0.5) + +def main(): + dev = find_g29() + print(f"Ouverture de {dev}...") + fd = os.open(dev, os.O_RDWR) + + # Method 1: Output Report 0x05 (32 bytes total: 0x05, 0xF8, 0x12, mask, 0x00...) + def m1(mask): + pkt = bytes([0x05, 0xF8, 0x12, mask] + [0x00] * 28) + try: + res = os.write(fd, pkt) + print(f" [M1 - Output 0x05] write({len(pkt)} bytes) -> {res}") + except Exception as e: + print(f" [M1 - Output 0x05] Erreur: {e}") + + # Method 2: Output Report 0x00 prefix (Unnumbered report 7-8 bytes: 0x00, 0xF8, 0x12, mask, 0, 0, 0, 0) + def m2(mask): + pkt = bytes([0x00, 0xF8, 0x12, mask, 0x00, 0x00, 0x00, 0x00]) + try: + res = os.write(fd, pkt) + print(f" [M2 - Unnumbered Output] write({len(pkt)} bytes) -> {res}") + except Exception as e: + print(f" [M2 - Unnumbered Output] Erreur: {e}") + + # Method 3: Output Report 0xF8 prefix (Report ID 0xF8: 0xF8, 0x12, mask, 0, 0, 0, 0) + def m3(mask): + pkt = bytes([0xF8, 0x12, mask, 0x00, 0x00, 0x00, 0x00]) + try: + res = os.write(fd, pkt) + print(f" [M3 - Output 0xF8] write({len(pkt)} bytes) -> {res}") + except Exception as e: + print(f" [M3 - Output 0xF8] Erreur: {e}") + + # Method 4: Feature Report 0xF3 (8 bytes: 0xF3, 0xF8, 0x12, mask, 0, 0, 0, 0) + def m4(mask): + pkt = bytearray([0xF3, 0xF8, 0x12, mask, 0x00, 0x00, 0x00, 0x00]) + try: + res = fcntl.ioctl(fd, HIDIOCSFEATURE(len(pkt)), pkt) + print(f" [M4 - Feature 0xF3 (F8 12)] ioctl(8 bytes) -> {res}") + except Exception as e: + print(f" [M4 - Feature 0xF3 (F8 12)] Erreur: {e}") + + # Method 5: Feature Report 0xF3 (8 bytes: 0xF3, 0x12, mask, 0, 0, 0, 0, 0) + def m5(mask): + pkt = bytearray([0xF3, 0x12, mask, 0x00, 0x00, 0x00, 0x00, 0x00]) + try: + res = fcntl.ioctl(fd, HIDIOCSFEATURE(len(pkt)), pkt) + print(f" [M5 - Feature 0xF3 (12 mask)] ioctl(8 bytes) -> {res}") + except Exception as e: + print(f" [M5 - Feature 0xF3 (12 mask)] Erreur: {e}") + + # Method 6: Feature Report 0xF0 (64 bytes: 0xF0, 0xF8, 0x12, mask, 0x00...) + def m6(mask): + pkt = bytearray([0xF0, 0xF8, 0x12, mask] + [0x00] * 60) + try: + res = fcntl.ioctl(fd, HIDIOCSFEATURE(len(pkt)), pkt) + print(f" [M6 - Feature 0xF0] ioctl(64 bytes) -> {res}") + except Exception as e: + print(f" [M6 - Feature 0xF0] Erreur: {e}") + + # Method 7: Init sequence first (CMD 4, CMD 3 range 900), then Output 0x05 + def m7(mask): + # f8 04 01 ... + cmd_init = bytes([0x05, 0xF8, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00] + [0x00]*24) + # f8 03 00 ... (900 deg) + cmd_range = bytes([0x05, 0xF8, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00] + [0x00]*24) + # f8 12 mask ... + cmd_led = bytes([0x05, 0xF8, 0x12, mask, 0x00, 0x00, 0x00, 0x00] + [0x00]*24) + try: + os.write(fd, cmd_init) + os.write(fd, cmd_range) + res = os.write(fd, cmd_led) + print(f" [M7 - Init + Output 0x05] write -> {res}") + except Exception as e: + print(f" [M7 - Init + Output 0x05] Erreur: {e}") + + # Method 8: Repeating 7-byte pattern in Output 0x05 (like in g29_crsf.ino) + def m8(mask): + pattern = bytes([0xF8, 0x12, mask, 0x00, 0x00, 0x00, 0x00]) + # 31 bytes payload = 4 x 7 bytes + 3 bytes + payload = pattern * 4 + bytes([0xF8, 0x12, mask]) + pkt = bytes([0x05]) + payload + try: + res = os.write(fd, pkt) + print(f" [M8 - Repeating in 0x05] write -> {res}") + except Exception as e: + print(f" [M8 - Repeating in 0x05] Erreur: {e}") + + tests = [ + ("1", "Output Report 0x05 standard (0x05, 0xF8, 0x12, mask, 0...)", m1), + ("2", "Output Sans ID (0x00, 0xF8, 0x12, mask, 0...)", m2), + ("3", "Output Report 0xF8 direct (0xF8, 0x12, mask...)", m3), + ("4", "Feature Report 0xF3 (0xF3, 0xF8, 0x12, mask...)", m4), + ("5", "Feature Report 0xF3 court (0xF3, 0x12, mask...)", m5), + ("6", "Feature Report 0xF0 (0xF0, 0xF8, 0x12, mask...)", m6), + ("7", "Init PS4 (CMD 4 + Range) puis Output 0x05", m7), + ("8", "Répétition 7-octets dans Output 0x05", m8), + ] + + import argparse + parser = argparse.ArgumentParser() + parser.add_argument('--method', '-m', type=str, default='all', help='Méthode à tester (1 à 8, ou all)') + parser.add_argument('--on', action='store_true', help='Allumer en continu (ne pas éteindre)') + parser.add_argument('--interactive', '-i', action='store_true', help='Mode interactif (touches 1 à 8 pour allumer, 0 pour éteindre)') + args = parser.parse_args() + + if args.interactive: + print("\n=== MODE INTERACTIF TEST LEDS G29 ===") + print("Touches :") + for num, name, _ in tests: + print(f" [{num}] : {name}") + print(" [0] : Éteindre toutes les méthodes") + print(" [q] : Quitter\n") + try: + import tty, termios + old_settings = termios.tcgetattr(sys.stdin) + tty.setcbreak(sys.stdin.fileno()) + while True: + ch = sys.stdin.read(1) + if ch == 'q': + break + if ch == '0': + print("\r-> Éteindre tout...") + for _, _, f in tests: + f(0x00) + else: + for num, name, func in tests: + if ch == num: + print(f"\r-> Test {num} ({name}) : ALLUMÉ (0x1F)") + func(0x1F) + break + finally: + termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings) + print("\nFin.") + os.close(fd) + return + + if args.method != 'all': + chosen = [t for t in tests if t[0] == args.method] + if not chosen: + print(f"Méthode {args.method} inconnue. Choisis entre 1 et 8.") + sys.exit(1) + num, name, func = chosen[0] + print(f"\n▶ Test Méthode {num} : {name}") + func(0x1F) + if not args.on: + time.sleep(2.0) + func(0x00) + print("Éteint.") + else: + print("Démarrage du test séquentiel des méthodes d'allumage des LEDs...") + print("Observe bien le volant : nous testons chaque méthode pendant 1.5s.\n") + for num, name, func in tests: + test_method(fd, f"Méthode {num} : {name}", func) + print("\nFin des tests !") + + os.close(fd) + +if __name__ == '__main__': + main() diff --git a/firmware/g29_crsf/test_matrix.py b/firmware/g29_crsf/test_matrix.py new file mode 100644 index 0000000..a0b6a9c --- /dev/null +++ b/firmware/g29_crsf/test_matrix.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python3 +""" +Deep diagnostic for Logitech G29 (046d:c260) on /dev/hidraw2 +Tests both FFB (force/spring) and LEDs to find which channel the G29 responds to. +""" + +import os +import sys +import glob +import time +import fcntl + +HIDIOCSFEATURE = lambda length: 0xC0004806 | (length << 16) + +def find_g29(): + for h in sorted(glob.glob('/dev/hidraw*')): + uevent = f'/sys/class/hidraw/{os.path.basename(h)}/device/uevent' + if os.path.exists(uevent): + try: + with open(uevent) as f: + c = f.read().upper() + if '046D:0000C260' in c or '046D:0000C24F' in c or 'LOGITECH' in c: + return h + except Exception: + pass + return '/dev/hidraw2' + +def main(): + dev = find_g29() + print(f"=== TEST DIAGNOSTIC G29 PS4 SUR {dev} ===") + fd = os.open(dev, os.O_RDWR) + + # Spring command (centering force 0xFE 0x0D ... or high res spring 0x21 0x0B ...) + # If accepted, the steering wheel immediately resists when turned! + spring_cmd = bytes([0xFE, 0x0D, 0x07, 0x07, 0xFF, 0x00, 0x00]) # 7 bytes + led_cmd = bytes([0xF8, 0x12, 0x1F, 0x00, 0x00, 0x00, 0x00]) # 7 bytes + + patterns = [ + ("P1: Raw 7 bytes on EP OUT (hidraw strip 0x00)", + bytes([0x00]) + led_cmd, 'write'), + + ("P2: 8 bytes with 1-byte offset 0x00 (hidraw strip 0x00)", + bytes([0x00, 0x00]) + led_cmd, 'write'), + + ("P3: Output Report 0x05 + 7 bytes command", + bytes([0x05]) + led_cmd + bytes([0x00]*24), 'write'), + + ("P4: Output Report 0x05 + 1-byte offset 0x00 + 7 bytes command", + bytes([0x05, 0x00]) + led_cmd + bytes([0x00]*23), 'write'), + + ("P5: Output Report 0x05 padded to 64 bytes", + bytes([0x05]) + led_cmd + bytes([0x00]*56), 'write'), + + ("P6: Feature Report 0xF3 (7 bytes payload)", + bytearray([0xF3]) + bytearray(led_cmd), 'feature'), + + ("P7: Feature Report 0xF3 (8 bytes: 0xF3 0x00 F8 12 1F...)", + bytearray([0xF3, 0x00]) + bytearray(led_cmd), 'feature'), + + ("P8: Feature Report 0xF0 (63 bytes)", + bytearray([0xF0]) + bytearray(led_cmd) + bytearray([0x00]*56), 'feature'), + + ("P9: Feature Report 0x03 (47 bytes)", + bytearray([0x03]) + bytearray(led_cmd) + bytearray([0x00]*40), 'feature'), + + ("P10: Report 0x30 padded to 64 bytes", + bytes([0x30]) + led_cmd + bytes([0x00]*56), 'write'), + ] + + print("\n--- Test des LEDs (1 seconde par motif) ---") + for i, (name, pkt, ptype) in enumerate(patterns, 1): + print(f"[{i:2d}/10] Test: {name}") + try: + if ptype == 'write': + os.write(fd, pkt) + else: + fcntl.ioctl(fd, HIDIOCSFEATURE(len(pkt)), pkt) + except Exception as e: + print(f" Erreur: {e}") + time.sleep(1.0) + + # Let's test Spring Force (Resistance) + print("\n--- Test du Retour au Centre (Force / Spring) ---") + print("Essaie de tourner le volant pour voir s'il devient dur / résistant...") + spring_tests = [ + ("S1: Spring via Output 0x05 (32 bytes)", bytes([0x05]) + spring_cmd + bytes([0x00]*24), 'write'), + ("S2: Spring via Output 0x05 avec offset 0x00", bytes([0x05, 0x00]) + spring_cmd + bytes([0x00]*23), 'write'), + ("S3: Spring via Feature 0xF3", bytearray([0xF3]) + bytearray(spring_cmd), 'feature'), + ("S4: Spring via Raw EP OUT", bytes([0x00]) + spring_cmd, 'write'), + ("S5: Spring High-Res PS4 (0x21 0x0B...)", bytes([0x05, 0x21, 0x0B, 0x7F, 0x7F, 0x77, 0xEE, 0xFF] + [0x00]*24), 'write'), + ] + + for name, pkt, ptype in spring_tests: + print(f"Test force: {name}") + try: + if ptype == 'write': + os.write(fd, pkt) + else: + fcntl.ioctl(fd, HIDIOCSFEATURE(len(pkt)), pkt) + except Exception as e: + print(f" Erreur: {e}") + time.sleep(1.5) + + os.close(fd) + print("\nFin des tests diagnostic !") + +if __name__ == '__main__': + main() diff --git a/firmware/g29_crsf/test_spring.py b/firmware/g29_crsf/test_spring.py new file mode 100755 index 0000000..71c1230 --- /dev/null +++ b/firmware/g29_crsf/test_spring.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python3 +""" +Test interactif de Force Feedback / Recentrage (Spring) et Butée (Range) pour Logitech G29 +""" + +import os +import sys +import glob +import time + +def find_g29(): + for h in sorted(glob.glob('/dev/hidraw*')): + uevent = f'/sys/class/hidraw/{os.path.basename(h)}/device/uevent' + if os.path.exists(uevent): + try: + with open(uevent) as f: + c = f.read().upper() + if '046D:0000C260' in c or '046D:0000C24F' in c or 'LOGITECH' in c: + return h + except Exception: + pass + return '/dev/hidraw2' + +CMD_RANGE_180 = bytes([0xF8, 0x81, 0xB4, 0x00, 0x00, 0x00, 0x00]) # 180 deg +CMD_RANGE_900 = bytes([0xF8, 0x81, 0x84, 0x03, 0x00, 0x00, 0x00]) # 900 deg +CMD_SPRING_140 = bytes([0xFE, 0x0D, 0x07, 0x07, 140, 0x00, 0x00]) # Force 140 +CMD_SPRING_MAX = bytes([0xFE, 0x0D, 0x07, 0x07, 0xFF, 0x00, 0x00]) # Force 255 +CMD_SPRING_OFF = bytes([0xFE, 0x0D, 0x00, 0x00, 0x00, 0x00, 0x00]) # Force 0 +CMD_ENABLE_14 = bytes([0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) # 0x14 (Autocenter default) +CMD_DISABLE_F5 = bytes([0xf5, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) # 0xF5 (Deactivate default autocenter) + +def send_r30(fd, cmd7): + payload = bytes([0x30]) + cmd7 + bytes([0x00] * 56) + return os.write(fd, payload) + +def main(): + dev = find_g29() + print(f"=== TEST RECENTRAGE + BUTÉE 180° G29 SUR {dev} ===") + + try: + fd = os.open(dev, os.O_RDWR) + except Exception as e: + print(f"Erreur d'ouverture {dev} : {e}") + sys.exit(1) + + tests = { + "A": ("Range 180° + Spring 140 SANS commande 0x14 (Recommandé)", [ + ("Range 180°", CMD_RANGE_180), + ("Spring 140", CMD_SPRING_140), + ]), + "B": ("Ordre inverse : 0x14 d'abord, PUIS Range 180°, PUIS Spring 140", [ + ("Enable 0x14", CMD_ENABLE_14), + ("Range 180°", CMD_RANGE_180), + ("Spring 140", CMD_SPRING_140), + ]), + "C": ("0xF5 (Désactiver défaut) + Range 180° + Spring 140", [ + ("Disable default 0xF5", CMD_DISABLE_F5), + ("Range 180°", CMD_RANGE_180), + ("Spring 140", CMD_SPRING_140), + ]), + "D": ("Range 180° seul (sans ressort)", [ + ("Range 180°", CMD_RANGE_180), + ("Spring OFF", CMD_SPRING_OFF), + ]), + "0": ("Désactiver force et remettre en 900°", [ + ("Spring OFF", CMD_SPRING_OFF), + ("Range 900°", CMD_RANGE_900), + ]), + } + + if len(sys.argv) > 1: + choice = sys.argv[1].upper() + else: + print("\nOptions à tester :") + for k, (desc, _) in tests.items(): + print(f" [{k}] {desc}") + choice = input("\nTon choix : ").strip().upper() + + if choice in tests: + desc, steps = tests[choice] + print(f"\n▶ Exécution : {desc}") + for name, cmd in steps: + send_r30(fd, cmd) + print(f" -> Envoyé : {name} ({cmd.hex()})") + time.sleep(0.05) + print("\n👉 TOURNE LE VOLANT :") + print(" 1. Est-il dur et revient-il au centre ?") + print(" 2. Bloque-t-il bien en butée à ±90° (180° au total) ?") + else: + print("Choix invalide.") + + os.close(fd) + +if __name__ == '__main__': + main() diff --git a/firmware/g29_crsf/test_vibration.py b/firmware/g29_crsf/test_vibration.py new file mode 100755 index 0000000..ba21506 --- /dev/null +++ b/firmware/g29_crsf/test_vibration.py @@ -0,0 +1,342 @@ +#!/usr/bin/env python3 +""" +Test interactif de Force Feedback : Vibrations, Textures de terrain et Rumble pour Logitech G29 +Permet de tester différentes fréquences, amplitudes et simulations de terrain accidenté. +""" + +import os +import sys +import glob +import time +import math +import select + +def find_g29(): + for h in sorted(glob.glob('/dev/hidraw*')): + uevent = f'/sys/class/hidraw/{os.path.basename(h)}/device/uevent' + if os.path.exists(uevent): + try: + with open(uevent) as f: + c = f.read().upper() + if '046D:0000C260' in c or '046D:0000C24F' in c or 'LOGITECH' in c: + return h + except Exception: + pass + return '/dev/hidraw2' + +def send_r30(fd, cmd7): + """Envoie une trame de 7 octets dans le rapport HID 0x30 (64 octets au total).""" + payload = bytes([0x30]) + bytes(cmd7) + bytes([0x00] * 56) + return os.write(fd, payload) + +def stop_ffb(fd): + """Arrête les forces actives et remet le slot 0 au neutre.""" + send_r30(fd, [0x13, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) # STOP_FORCE slot 0 + send_r30(fd, [0x11, 0x00, 128, 0x00, 0x00, 0x00, 0x00]) # Force neutre (128) + # Réactiver le ressort de rappel par défaut (force 140) + send_r30(fd, [0xFE, 0x0D, 0x07, 0x07, 140, 0x00, 0x00]) + +def play_vibration(fd, freq_hz, amplitude_0_127, duration_sec, desc=""): + """ + Génère une oscillation sinusoïdale de force constante autour du neutre (128). + freq_hz : Fréquence de la vibration en Hertz (ex: 15 à 60 Hz). + amplitude_0_127 : Force de la vibration (1 à 127). + """ + if desc: + print(f" ▶ {desc} (f = {freq_hz} Hz, amplitude = {amplitude_0_127}/127, durée = {duration_sec}s)") + + t_start = time.time() + dt_target = 0.008 # Cadence d'envoi USB à ~125 Hz + + while True: + t = time.time() - t_start + if t >= duration_sec: + break + + # Valeur centrée sur 128 (0 = plein gauche, 128 = neutre, 255 = plein droite) + force = int(128 + amplitude_0_127 * math.sin(2.0 * math.pi * freq_hz * t)) + force = max(0, min(255, force)) + + send_r30(fd, [0x11, 0x00, force, 0x00, 0x00, 0x00, 0x00]) + time.sleep(dt_target) + + stop_ffb(fd) + +def test_frequences(fd): + print("\n=== TEST 1 : COMPARAISON DES FRÉQUENCES DE VIBRATION ===") + print("Pose tes mains sur le volant pour ressentir la texture...") + time.sleep(1) + + samples = [ + (12, 60, 2.0, "12 Hz : Grondement sourd / Régime moteur au ralenti"), + (25, 75, 2.0, "25 Hz : Gravier / Piste en terre battue"), + (40, 80, 2.0, "40 Hz : Pavés / Tôle ondulée / Vibreur de circuit"), + (60, 90, 2.0, "60 Hz : Vibration aiguë / Micro-aspérités du bitume"), + ] + + for freq, amp, dur, desc in samples: + play_vibration(fd, freq, amp, dur, desc) + time.sleep(0.5) + +def test_amplitudes(fd): + print("\n=== TEST 2 : GRADATION D'INTENSITÉ (À 30 Hz) ===") + time.sleep(1) + + intensites = [ + (30, 25, 1.5, "Intensité Faible (20%) : Léger frémissement"), + (30, 60, 1.5, "Intensité Moyenne (50%) : Route accidentée"), + (30, 95, 1.5, "Intensité Forte (75%) : Gros cailloux / Ornières"), + (30, 125, 1.5, "Intensité Maximale(100%): Terrain très cassant"), + ] + + for freq, amp, dur, desc in intensites: + play_vibration(fd, freq, amp, dur, desc) + time.sleep(0.5) + +def test_simulation_terrain(fd): + print("\n=== TEST 3 : PARCOURS DE TERRAIN PROGRESSIF ===") + print("Ce test simule un véhicule qui traverse différents types de sols :") + time.sleep(1) + + sections = [ + ("1. Asphalte lisse", 0, 0, 2.0), + ("2. Transition sur gravier fin", 35, 30, 2.0), + ("3. Piste en terre avec trous et bosses", 22, 85, 3.0), + ("4. Zone de gros franchissement / Cailloux", 15, 120, 2.5), + ("5. Retour sur route goudronnée", 0, 0, 1.5), + ] + + for nom, freq, amp, duree in sections: + print(f" 🚗 Section : {nom}...") + if amp == 0: + stop_ffb(fd) + time.sleep(duree) + else: + play_vibration(fd, freq, amp, duree) + +def test_chocs_ponctuels(fd): + print("\n=== TEST 4 : CHOCS SOUDAINS (Nids-de-poule & Pierres) ===") + print("Simule une roue gauche ou droite qui heurte un obstacle franc...") + time.sleep(1) + + for i in range(3): + # Pause de roulage calme + stop_ffb(fd) + time.sleep(0.8) + + # Choc à gauche ou à droite + direction = "GAUCHE" if i % 2 == 0 else "DROITE" + force_choc = 20 if direction == "GAUCHE" else 235 + print(f" 💥 CHOC ROUE {direction} !") + + # Impulsion très brève et forte (50 ms) + for _ in range(5): + send_r30(fd, [0x11, 0x00, force_choc, 0x00, 0x00, 0x00, 0x00]) + time.sleep(0.01) + + # Rebond opposé amorti (40 ms) + force_rebond = 170 if direction == "GAUCHE" else 85 + for _ in range(4): + send_r30(fd, [0x11, 0x00, force_rebond, 0x00, 0x00, 0x00, 0x00]) + time.sleep(0.01) + + stop_ffb(fd) + +def test_mix_12_60(fd): + print("\n=== TEST 6 : MIX DOUBLE-COUCHE HAPTIQUE (12 Hz + 60 Hz) ===") + print("Compare les deux fréquences isolées puis leur superposition simultanée :") + time.sleep(1) + + print(" 1/4 : 12 Hz seul (Gros grondement / secousses mécaniques)...") + play_vibration(fd, 12, 65, 2.0) + time.sleep(0.5) + + print(" 2/4 : 60 Hz seul (Texture de surface / grain du bitume)...") + play_vibration(fd, 60, 65, 2.0) + time.sleep(0.5) + + print(" 3/4 : SUPERPOSITION 12 Hz + 60 Hz (Double texture simultanée)...") + t_start = time.time() + while time.time() - t_start < 3.0: + t = time.time() - t_start + # 12 Hz donne l'amplitude de fond, 60 Hz superpose le grain de surface + v12 = 45.0 * math.sin(2.0 * math.pi * 12.0 * t) + v60 = 35.0 * math.sin(2.0 * math.pi * 60.0 * t) + force = int(128 + v12 + v60) + force = max(0, min(255, force)) + send_r30(fd, [0x11, 0x00, force, 0x00, 0x00, 0x00, 0x00]) + time.sleep(0.008) + stop_ffb(fd) + time.sleep(0.5) + + print(" 4/4 : SIMULATION TOUT-TERRAIN DYNAMIQUE...") + print(" (Fond de roulement 60 Hz continu + bouffées de 12 Hz sur les ornières)") + t_start = time.time() + while time.time() - t_start < 4.0: + t = time.time() - t_start + # Enveloppe d'ornières toutes les 0.8s + choc_orniere = math.sin(2.0 * math.pi * 1.25 * t) + amp12 = 70.0 if choc_orniere > 0.4 else 15.0 + + v12 = amp12 * math.sin(2.0 * math.pi * 12.0 * t) + v60 = 30.0 * math.sin(2.0 * math.pi * 60.0 * t) + force = int(128 + v12 + v60) + force = max(0, min(255, force)) + send_r30(fd, [0x11, 0x00, force, 0x00, 0x00, 0x00, 0x00]) + time.sleep(0.008) + stop_ffb(fd) + +def test_interactif_pedales(fd): + print("\n=== TEST 5 : SIMULATEUR INTERACTIF EN DIRECT (PÉDALES & VOLANT) ===") + print("Prends le volant et appuie sur les pédales :") + print(" - ACCÉLÉRATEUR : Augmente le régime moteur (fréquence + rumble)") + print(" - FREIN FORT : Déclenche la vibration d'ABS / blocage de roue") + print(" - PALETTES +/- : Secousse mécanique de passage de rapport") + print(" - [Ctrl + C] : Quitter le simulateur") + print("\nInitialisation en cours...") + + # Assurer le recentrage et la butée 180° + send_r30(fd, [0xF8, 0x81, 0xB4, 0x00, 0x00, 0x00, 0x00]) # Range 180° + send_r30(fd, [0xFE, 0x0D, 0x07, 0x07, 130, 0x00, 0x00]) # Ressort + + rapport = 1 + palette_plus_prev = False + palette_moins_prev = False + choc_rapport_timer = 0 + choc_direction = 1 + + t_start = time.time() + + try: + while True: + # 1. Lecture non bloquante des rapports HID du G29 + r, _, _ = select.select([fd], [], [], 0.008) + accel_pct = 0.0 + frein_pct = 0.0 + p_plus = False + p_moins = False + + if r: + data = os.read(fd, 64) + if len(data) >= 51 and data[0] == 0x01: + accel_raw = 65535 - (data[45] | (data[46] << 8)) + frein_raw = 65535 - (data[47] | (data[48] << 8)) + accel_pct = max(0.0, min(100.0, (accel_raw / 65535.0) * 100.0)) + frein_pct = max(0.0, min(100.0, (frein_raw / 65535.0) * 100.0)) + + b6 = data[6] + p_moins = bool(b6 & 0x01) + p_plus = bool(b6 & 0x02) + + # Gestion des passages de vitesses + if p_plus and not palette_plus_prev: + if rapport < 4: rapport += 1 + choc_rapport_timer = time.time() + choc_direction = 1 + if p_moins and not palette_moins_prev: + if rapport > 1: rapport -= 1 + choc_rapport_timer = time.time() + choc_direction = -1 + + palette_plus_prev = p_plus + palette_moins_prev = p_moins + + # 2. Calcul du retour de force (FFB) en fonction de l'état + now = time.time() + force_calc = 128 + + # Cas A : À-coup sec au passage de rapport (durée 70 ms) + if now - choc_rapport_timer < 0.07: + force_calc = 128 + choc_direction * 90 + + # Cas B : Freinage violent (> 70%) -> Vibration ABS rapide + elif frein_pct > 70.0: + abs_amp = int((frein_pct - 70.0) * 3.0) + force_calc = int(128 + abs_amp * math.sin(2.0 * math.pi * 45.0 * now)) + + # Cas C : Régime moteur lié à l'accélérateur et au rapport (Mix 12 Hz + 60 Hz) + else: + # 12 Hz : Grondement moteur qui monte légèrement en fréquence et amplitude avec les gaz + freq_moteur = 12.0 + (accel_pct * 0.15) + amp_moteur = 15.0 + (accel_pct * 0.45) + v_moteur = amp_moteur * math.sin(2.0 * math.pi * freq_moteur * now) + + # 60 Hz : Grain de roulement et vibration mécanique qui augmente avec la vitesse + amp_vitesse = (accel_pct * 0.35) * (1.0 + (rapport - 1) * 0.25) + v_roulement = amp_vitesse * math.sin(2.0 * math.pi * 60.0 * now) + + force_calc = int(128 + v_moteur + v_roulement) + + force_calc = max(0, min(255, force_calc)) + send_r30(fd, [0x11, 0x00, force_calc, 0x00, 0x00, 0x00, 0x00]) + + # Affichage console synthétique toutes les 150 ms + if int(now * 6) != int((now - 0.008) * 6): + barre_gaz = "█" * int(accel_pct / 5) + "-" * (20 - int(accel_pct / 5)) + barre_frein = "█" * int(frein_pct / 5) + "-" * (20 - int(frein_pct / 5)) + sys.stdout.write(f"\r[VITESSE: {rapport}] Gaz: [{barre_gaz}] Frein: [{barre_frein}] FFB: {force_calc:3d} ") + sys.stdout.flush() + + except KeyboardInterrupt: + print("\n\nArrêt du simulateur interactif.") + finally: + stop_ffb(fd) + +def main(): + dev = find_g29() + print(f"============================================================") + print(f" TEST FORCE FEEDBACK : VIBRATIONS & RUGOSITÉ G29 ({dev}) ") + print(f"============================================================") + + try: + fd = os.open(dev, os.O_RDWR) + except Exception as e: + print(f"Erreur d'ouverture du périphérique {dev} : {e}") + print("Vérifie les permissions (ex: sudo ou groupe input/plugdev).") + sys.exit(1) + + menu = { + "1": ("Tester les différentes fréquences (12 Hz à 60 Hz)", test_frequences), + "2": ("Tester les différentes intensités (20% à 100%)", test_amplitudes), + "3": ("Simulation complète de terrain (Asphalte -> Terre -> Cailloux)", test_simulation_terrain), + "4": ("Simulation de chocs soudains (Trous & Cailloux isolés)", test_chocs_ponctuels), + "5": ("SIMULATEUR COMPLET EN DIRECT (Moteur, Pédales, Boîte & ABS)", test_interactif_pedales), + "6": ("TEST DOUBLE-COUCHE HAPTIQUE (Superposition 12 Hz + 60 Hz)", test_mix_12_60), + "0": ("Remettre à zéro (Arrêt FFB et recentrage par défaut)", stop_ffb), + } + + if len(sys.argv) > 1: + choix = sys.argv[1].strip() + if choix in menu: + desc, action = menu[choix] + print(f"\n▶ Exécution : {desc}") + action(fd) + stop_ffb(fd) + os.close(fd) + return + + try: + while True: + print("\nChoisis un test à lancer :") + for k, (desc, _) in menu.items(): + print(f" [{k}] {desc}") + print(" [Q] Quitter") + + choix = input("\nTon choix : ").strip().upper() + if choix in ('Q', 'QUIT'): + break + if choix in menu: + desc, action = menu[choix] + action(fd) + stop_ffb(fd) + else: + print("Choix invalide.") + except KeyboardInterrupt: + print("\nInterruption.") + finally: + stop_ffb(fd) + os.close(fd) + print("Fin du programme. G29 remis au neutre.") + +if __name__ == '__main__': + main()