feat(ffb): integrer le moteur de vibration haptique double-couche et telemetrie terrain

- Moteur de vibration haptique cadencé à 125 Hz sur le Cœur 1 (Slot 0x11 FFB Logitech)
- Superposition haptique validée : grondement / secousses 12 Hz et texture de vitesse 60 Hz
- Simulation d'à-coup mécanique aux palettes de vitesse et vibration ABS au freinage fort
- Réception de la télémétrie CRSF sur GP1 (Serial1 RX) pour moduler les vibrations selon la rugosité du terrain mesurée par la FC
- Ajout de la commande série T=val (0..100%) et sauvegarde en Flash EEPROM
- Ajout du script de calibration et simulateur interactif test_vibration.py
This commit is contained in:
bleackstorm committed 2026-11-12 09:06:03 +01:00
1 parent 6373ed4371
commit aabd72a41f
2 files changed
+521 -7

No files matched your search

+179 -7
View File
@@ -58,6 +58,8 @@ const uint16_t GAZ_AVANT_MAX_PAR_VITESSE[3] = {
#define FORCE_RESSORT_DEFAUT 140 // Force du retour au centre : 0 à 255
#define PENTE_RESSORT_G29 7 // Raideur autour du centre : 1 à 7
#define ETAPES_INIT_FFB_TOTAL 2 // Nombre d'étapes d'init FFB (0=Range, 1=Spring)
#define VIBRATION_DEFAUT 100 // Intensité par défaut des vibrations (0 à 100%)
#define MAGIC_NUMBER_CONFIG 0x48 // Identifiant de validité en EEPROM
Adafruit_NeoPixel rgb_led(NUM_PIXELS, PIN_LED_RGB, NEO_GRB + NEO_KHZ800);
Adafruit_USBH_Host USBHost;
@@ -77,7 +79,8 @@ struct ConfigG29 {
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 magicNumber; // Identifiant de validité en EEPROM (0x47)
uint8_t intensiteVibration; // Intensité globale des vibrations : 0 à 100%
uint8_t magicNumber; // Identifiant de validité en EEPROM (0x48)
};
volatile ConfigG29 configSysteme;
@@ -133,6 +136,14 @@ volatile uint32_t momentDernierChangementDurete_ms = 0;
volatile bool logDureteRequis = false;
volatile bool demandeSauvegardeEEPROM = false;
// 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;
char serialBuffer[32];
uint8_t serialBufferIdx = 0;
@@ -152,7 +163,8 @@ void reinitialiserConfigurationDefaut() {
configSysteme.forceRessort = FORCE_RESSORT_DEFAUT;
configSysteme.angleSouhaiteTotal = ANGLE_DEFAUT_TOTAL;
configSysteme.expoVolant = EXPO_DEFAUT;
configSysteme.magicNumber = 0x47;
configSysteme.intensiteVibration = VIBRATION_DEFAUT;
configSysteme.magicNumber = MAGIC_NUMBER_CONFIG;
recalculerParametresVolant();
}
@@ -187,7 +199,8 @@ void afficherConfiguration() {
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.println("Commandes : V=ch, A=ch, F=ch, E=ch, D=val, P=val, X=val, S(save), R(reset), ?");
Serial.printf("Vibrations (T) : %d%% [T=0..100] (Mix 12Hz/60Hz + Telemetrie)\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), ?");
}
void chargerConfiguration() {
@@ -217,10 +230,12 @@ void chargerConfiguration() {
bool angleValide = (configSysteme.angleSouhaiteTotal >= 40) &&
(configSysteme.angleSouhaiteTotal <= 900);
if (configSysteme.magicNumber != 0x47 || conflitArm || !canauxValides || !canauxDistincts || !expoValide || !angleValide) {
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) Serial.println("!! Valeur d'angle ou d'expo 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();
@@ -329,6 +344,17 @@ void traiterLigneSerie(char* commande) {
} 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) {
rp2040.idleOtherCore();
configSysteme.intensiteVibration = (uint8_t)val;
rp2040.resumeOtherCore();
sauvegarderConfiguration();
afficherConfiguration();
} else {
Serial.println("!! Vibrations (T) doit etre entre 0 et 100% !!");
}
}
}
}
@@ -474,9 +500,81 @@ bool evaluerFailsafe() {
return stale;
}
// -------------------------------------------------------------------------
// 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 uint32_t dernierPaquetTelemetrie_ms = 0;
while (Serial1.available() > 0) {
uint8_t b = Serial1.read();
if (crsfRxIdx == 0) {
// Les trames CRSF débutent par une adresse connue (0xC8, 0xEE, 0xEA, etc.)
if (b == 0xC8 || b == 0xEE || b == 0xEA) {
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)) {
dernierPaquetTelemetrie_ms = millis();
uint8_t frameType = crsfRxBuffer[2];
// Trame d'attitude (0x1E) : Pitch (int16), Roll (int16), Yaw (int16)
if (frameType == 0x1E && paquetLongueurAttendue >= 8) {
int16_t pitch = (int16_t)((crsfRxBuffer[3] << 8) | crsfRxBuffer[4]);
int16_t roll = (int16_t)((crsfRxBuffer[5] << 8) | crsfRxBuffer[6]);
int16_t deltaPitch = abs(pitch - prevPitch);
int16_t deltaRoll = abs(roll - prevRoll);
prevPitch = pitch;
prevRoll = roll;
uint16_t secousses = deltaPitch + deltaRoll;
rugositeTerrainExterne = (uint8_t)constrain(map(secousses, 15, 250, 0, 255), 0, 255);
}
// Trame personnalisée (0x7F ou 0x2A pour accéléromètre brut / rugosité)
else if ((frameType == 0x7F || frameType == 0x2A) && paquetLongueurAttendue >= 3) {
rugositeTerrainExterne = crsfRxBuffer[3];
}
crsfRxIdx = 0;
}
if (crsfRxIdx >= sizeof(crsfRxBuffer)) {
crsfRxIdx = 0;
}
}
}
// 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 loop() {
rp2040.wdt_reset();
verifierCommandesSerie();
traiterTelemetrieCRSF();
static int8_t dernierRapportLog = 0xFF;
if (majLedRequise) {
@@ -542,8 +640,9 @@ void loop() {
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 | Plage=%d deg | Rapport=%d | Arme=%d | Statut_LED=%d | USB=%lu rap/s | Rejetes=%lu | Failsafe=%d\n",
volant_est_pret, g29_pid, etapeInitMoteur, ETAPES_INIT_FFB_TOTAL, configSysteme.forceRessort, configSysteme.angleSouhaiteTotal,
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 | 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, failsafeActif);
}
@@ -615,6 +714,60 @@ void envoyerLedsG29(uint8_t masque5bits) {
}
}
void gererVibrationHaptique() {
if (!volant_est_pret || etapeInitMoteur < ETAPES_INIT_FFB_TOTAL) return;
if (etapeEnvoiLed != 0 || majRangeRequise || majRessortRequise) return;
if (!tuh_hid_send_ready(g29_dev_addr, g29_instance)) return;
uint8_t intensite = configSysteme.intensiteVibration;
if (intensite == 0 || !estArme) {
if (!forceEstAuNeutre) {
const uint8_t cmdNeutre[7] = {0x11, 0x00, 128, 0x00, 0x00, 0x00, 0x00};
if (envoyerTrameG29_0x30(cmdNeutre)) {
forceEstAuNeutre = true;
}
}
return;
}
forceEstAuNeutre = false;
float gainGlobal = (float)intensite / 100.0f;
float t = (float)millis() * 0.001f;
float forceCalc = 128.0f;
uint32_t now = millis();
uint32_t dtChoc = now - momentDernierChocRapport_ms;
// Cas A : À-coup sec au passage de rapport (durée 70 ms)
if (dtChoc < 70) {
forceCalc = 128.0f + (float)directionDernierChocRapport * 85.0f * gainGlobal;
}
// Cas B : Freinage violent (> 70%) -> vibration ABS à 45 Hz
else if (dernierFreinPct > 70.0f) {
float absAmp = (dernierFreinPct - 70.0f) * 2.5f * gainGlobal;
forceCalc = 128.0f + absAmp * sinf(2.0f * 3.14159265f * 45.0f * t);
}
// 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.45f) * gainGlobal;
float v12 = (ampMoteur12 + ampTerrain12) * sinf(2.0f * 3.14159265f * freq12 * t);
// 60 Hz : Grain de roulement lié à la vitesse (rapport engagé) et aux gaz
float ampVitesse60 = (dernierAccelPct * 0.30f) * (1.0f + (float)rapportEngage * 0.25f) * gainGlobal;
float ampTerrain60 = ((float)rugositeTerrainExterne * 0.20f) * gainGlobal;
float v60 = (ampVitesse60 + ampTerrain60) * sinf(2.0f * 3.14159265f * 60.0f * t);
forceCalc = 128.0f + v12 + v60;
}
uint8_t forceByte = (uint8_t)constrain((int)forceCalc, 0, 255);
const uint8_t cmdForce[7] = {0x11, 0x00, forceByte, 0x00, 0x00, 0x00, 0x00};
envoyerTrameG29_0x30(cmdForce);
}
void setup1() {
sleep_ms(100);
pio_usb_configuration_t pio_cfg = PIO_USB_DEFAULT_CONFIG;
@@ -674,6 +827,13 @@ void loop1() {
}
envoyerLedsG29(masqueCible);
}
// Moteur de vibration haptique (Mix 12 Hz + 60 Hz cadencé à ~125 Hz, toutes les 8 ms)
static uint32_t dernierTickVib = 0;
if (volant_est_pret && etapeInitMoteur >= ETAPES_INIT_FFB_TOTAL && (millis() - dernierTickVib >= 8)) {
dernierTickVib = millis();
gererVibrationHaptique();
}
}
// =========================================================================
@@ -711,6 +871,8 @@ void tuh_hid_mount_cb(uint8_t dev_addr, uint8_t instance, uint8_t const* desc_re
rapportEngage = 0;
demandeRetourNeutre = false;
estArme = false;
forceEstAuNeutre = false;
rugositeTerrainExterne = 0;
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;
@@ -736,6 +898,8 @@ void tuh_hid_umount_cb(uint8_t dev_addr, uint8_t instance) {
etapeInitMoteur = 0;
rapportEngage = 0;
estArme = false;
forceEstAuNeutre = false;
rugositeTerrainExterne = 0;
reinitialiserCanauxCRSF();
majLedRequise = true;
}
@@ -774,6 +938,10 @@ void __not_in_flash_func(tuh_hid_report_received_cb)(uint8_t dev_addr, uint8_t i
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);
@@ -801,6 +969,8 @@ void __not_in_flash_func(tuh_hid_report_received_cb)(uint8_t dev_addr, uint8_t i
if (rapportEngage < 3 && !(rapportEngage < 0 && accelRaw > DEADZONE_PEDALE)) {
rapportEngage++;
majLedRequise = true;
momentDernierChocRapport_ms = millis();
directionDernierChocRapport = 1; // À-coup sec vers la droite
}
palettePlusDejaEnfoncee = true;
} else if (!pPlusActuel && palettePlusDejaEnfoncee) {
@@ -811,6 +981,8 @@ void __not_in_flash_func(tuh_hid_report_received_cb)(uint8_t dev_addr, uint8_t i
if (rapportEngage > -1 && !(rapportEngage <= 0 && accelRaw > DEADZONE_PEDALE)) {
rapportEngage--;
majLedRequise = true;
momentDernierChocRapport_ms = millis();
directionDernierChocRapport = -1; // À-coup sec vers la gauche
}
paletteMoinsDejaEnfoncee = true;
} else if (!pMoinsActuel && paletteMoinsDejaEnfoncee) {
+342
View File
@@ -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()