mirror of
https://github.com/bleackstorm/SteamFrame-FPV-Control-Center.git
synced 2026-12-03 07:31:57 +01:00
Merge pull request #7 from bleackstorm/feat/merge-g29-monorepo
Feat/merge g29 monorepo
This commit is contained in:
11 files changed
+2783
-2
No files matched your search
@@ -3,7 +3,7 @@
|
||||
Application graphique et VR native **Linux / SteamOS (ARM64 & x86_64)** en **Rust**, conçue pour le casque **Steam Frame** avec :
|
||||
|
||||
- **Récepteur Eachine Sphere Link VRX** : Carte **Radxa Zero 3W** (`OpenIPC` / `RubyFPV` avec adaptateur **RTL8812EU** 5.8 GHz, canal par défaut `161`, profils `720p60`, `1080p60`, `1080p90`, `720p120`), via **USB-C OTG RNDIS** (`usb0` sur `192.168.1.1`) ou **Mini-HDMI + carte capture USB-C UVC**.
|
||||
- **Station Tout-en-un 100 % Filaire (Zéro Wi-Fi) + Charge PD** : Un **Splitter USB-C (Data + Charge PD)** relie le casque Steam Frame à la Radxa Zero 3W (`usb0`) tout en rechargeant le casque en continu. La **Waveshare RP2350 (`g29_crsf`)** centralise le volant **Logitech G29 (`CH1..CH5`)**, le **Head-Tracking (`CH6..CH8` via `$HT`)**, l'émission CRSF 166,7 Hz vers le **RadioMaster Nomad** et la remontée télémétrique (`$G29`, `$G29_EVT`, `$CRSF`) vers l'OSD sur un seul port UDP **`14552`**.
|
||||
- **Station Tout-en-un 100 % Filaire (Zéro Wi-Fi) + Charge PD** : Un **Splitter USB-C (Data + Charge PD)** relie le casque Steam Frame à la Radxa Zero 3W (`usb0`) tout en rechargeant le casque en continu. La **Waveshare RP2350 ([firmware/g29_crsf](firmware/g29_crsf/README.md))** centralise le volant **Logitech G29 (`CH1..CH5`)**, le **Head-Tracking (`CH6..CH8` via `$HT`)**, l'émission CRSF 166,7 Hz vers le **RadioMaster Nomad** et la remontée télémétrique (`$G29`, `$G29_EVT`, `$CRSF`) vers l'OSD sur un seul port UDP **`14552`**.
|
||||
- **Module RadioMaster Nomad (ExpressLRS)** : Piloté directement en CRSF filaire via `g29_crsf` (mode recommandé **`g29`**, Wi-Fi Backpack coupé) ou en Wi-Fi UDP autonome (`MSPv2 0x0383`, `CRSF 0x16`, `MAVLink v1 RC Override`).
|
||||
|
||||
---
|
||||
|
||||
@@ -48,7 +48,7 @@ Ce guide explique comment câbler, configurer et tester sur **PC Ubuntu** (en at
|
||||
Branchez la RP2350 en USB-C sur votre PC (maintenez **BOOT** si elle n'apparaît pas sur `/dev/ttyACM0`) :
|
||||
|
||||
```bash
|
||||
cd /home/bleack/projects/g29_crsf
|
||||
cd firmware/g29_crsf
|
||||
arduino-cli compile --fqbn rp2040:rp2040:waveshare_rp2350_plus:usbstack=tinyusb --build-path ./build .
|
||||
arduino-cli upload --fqbn rp2040:rp2040:waveshare_rp2350_plus:usbstack=tinyusb --input-dir ./build -p /dev/ttyACM0
|
||||
```
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
__pycache__/
|
||||
*.pyc
|
||||
build/
|
||||
@@ -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,<pan>,<tilt>,<roll>` (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,<HEX>`) 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,<pan>,<tilt>,<roll>` | 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=<ch>` | 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 .
|
||||
```
|
||||
Executable
+177
@@ -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()
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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 <candidate P1..P10> <on|off|blink|chase>")
|
||||
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)
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
Executable
+95
@@ -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()
|
||||
Executable
+342
@@ -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()
|
||||
Reference in new issue
Block a user