diff --git a/src/controller.rs b/src/controller.rs index f393b3a..4e9fe6e 100644 --- a/src/controller.rs +++ b/src/controller.rs @@ -61,6 +61,9 @@ const TOAST_DURATION_MS: u64 = 1500; const RC_SEND_INTERVAL_MS: u64 = 10; // 100 Hz vers RP2350 const SRC_RESYNC_INTERVAL_MS: u64 = 500; const DEVICE_RESCAN_INTERVAL_MS: u64 = 1000; +const IBEX_HIDRAW_TIMEOUT_MS: u64 = 1500; +const IBEX_REPORT_ID: u8 = 0x42; +const IBEX_REPORT_LEN: usize = 54; extern "C" { fn ioctl(fd: std::ffi::c_int, request: std::ffi::c_ulong, ...) -> std::ffi::c_int; @@ -720,6 +723,323 @@ impl OpenEvdevGamepad { } } +// ========================================================================= +// LECTEUR NATIF HIDRAW STEAM CONTROLLER 2 (IBEX / PUCK 28DE:1302..1305) +// Contourne automatiquement le Lizard Mode (mode souris/bureau) de hid-steam +// sans nécessiter d'appui long sur Menu ni que Steam soit lancé. +// ========================================================================= + +const IBEX_BUTTON_MAP: &[(usize, u8, u16)] = &[ + // Byte 2 + (2, 0x01, BTN_SOUTH), // A (Tare HT) + (2, 0x02, BTN_EAST), // B (DVR) + (2, 0x04, BTN_NORTH), // Y (OSD) + (2, 0x08, BTN_WEST), // X (Proj VR) + (2, 0x20, BTN_THUMBR), // R3 (Tare HT) + (2, 0x40, BTN_START), // Menu / Start (ARM) + (2, 0x80, BTN_GRIPR), // R4 Grip (Rapport +) + // Byte 3 + (3, 0x02, BTN_TR), // RB (Rapport +) + (3, 0x04, BTN_DPAD_DOWN), // D-Pad Bas + (3, 0x08, BTN_DPAD_RIGHT), // D-Pad Droite + (3, 0x10, BTN_DPAD_LEFT), // D-Pad Gauche + (3, 0x20, BTN_DPAD_UP), // D-Pad Haut + (3, 0x40, BTN_SELECT), // View / Select (DVR) + // Byte 4 + (4, 0x01, BTN_MODE), // Steam (Tare HT) + (4, 0x02, BTN_GRIPL), // L4 Grip (Rapport -) + (4, 0x08, BTN_TL), // LB (Rapport -) +]; + +struct IbexParsedReport { + steer_raw: i32, // -32767..=32767 + throttle_raw: i32, // 0..=32767 + brake_raw: i32, // 0..=32767 + clutch_pressed: bool, + btn_bytes: [u8; 4], // report[2..6] +} + +fn parse_ibex_hidraw_report(data: &[u8]) -> Option { + if data.len() < IBEX_REPORT_LEN || data[0] != IBEX_REPORT_ID { + return None; + } + let brake_raw = i16::from_le_bytes([data[6], data[7]]).max(0) as i32; + let throttle_raw = i16::from_le_bytes([data[8], data[9]]).max(0) as i32; + let steer_raw = (i16::from_le_bytes([data[10], data[11]]) as i32).max(-32767); + let btn_bytes = [data[2], data[3], data[4], data[5]]; + let clutch_pressed = (data[4] & 0x04) != 0; // BTN_GRIPL2 (L5) + + Some(IbexParsedReport { + steer_raw, + throttle_raw, + brake_raw, + clutch_pressed, + btn_bytes, + }) +} + +struct OpenIbexHidraw { + file: File, + name: String, + path: String, + vendor: u16, + product: u16, + steer_axis: AxisRange, + throttle_axis: AxisRange, + brake_axis: AxisRange, + clutch_pressed: bool, + prev_btn_bytes: [u8; 4], + last_report_at: Instant, +} + +impl OpenIbexHidraw { + fn is_ibex_pid(pid: u16) -> bool { + matches!(pid, 0x1302 | 0x1303 | 0x1304 | 0x1305) + } + + fn parse_hid_id(uevent: &str) -> Option<(u16, u16, String)> { + let mut vid = None; + let mut pid = None; + let mut name = String::new(); + for line in uevent.lines() { + if let Some(rest) = line.strip_prefix("HID_ID=") { + let parts: Vec<&str> = rest.split(':').collect(); + if parts.len() == 3 { + vid = u16::from_str_radix(parts[1].trim(), 16).ok(); + pid = u16::from_str_radix(parts[2].trim(), 16).ok(); + } + } else if let Some(rest) = line.strip_prefix("HID_NAME=") { + name = rest.trim().to_string(); + } + } + Some((vid?, pid?, name)) + } + + fn probe_single(path: &str, name: String, vendor: u16, product: u16) -> Option { + let mut file = OpenOptions::new() + .read(true) + .custom_flags(O_NONBLOCK_FLAG) + .open(path) + .ok()?; + + let mut buf = [0u8; 64]; + // Sonde brève (jusqu'à 45 ms) : seule l'interface active du Puck diffuse les trames 0x42 (54 o) + for attempt in 0..5 { + match file.read(&mut buf) { + Ok(n) => { + if let Some(parsed) = parse_ibex_hidraw_report(&buf[..n]) { + return Some(Self { + file, + name: if name.is_empty() { + "Steam Controller (HIDRAW)".to_string() + } else { + name + }, + path: path.to_string(), + vendor, + product, + steer_axis: AxisRange::centered(-32767, 32767, parsed.steer_raw), + throttle_axis: AxisRange::centered(0, 32767, parsed.throttle_raw), + brake_axis: AxisRange::centered(0, 32767, parsed.brake_raw), + clutch_pressed: parsed.clutch_pressed, + prev_btn_bytes: parsed.btn_bytes, + last_report_at: Instant::now(), + }); + } + } + Err(e) if e.kind() == ErrorKind::WouldBlock => { + if attempt < 4 { + thread::sleep(Duration::from_millis(10)); + } + } + Err(_) => return None, + } + } + None + } + + fn find_and_open(override_path: Option<&str>) -> Option { + if let Some(path) = override_path { + let trimmed = path.trim(); + if trimmed.contains("hidraw") { + return Self::probe_single( + trimmed, + format!("Steam Controller ({})", trimmed), + VALVE_VENDOR_ID, + 0x1304, + ); + } + if !trimmed.is_empty() { + return None; + } + } + + let entries = fs::read_dir("/sys/class/hidraw").ok()?; + let mut candidates: Vec<(u32, String, String, u16, u16)> = Vec::new(); + + for entry in entries.flatten() { + let fname = entry.file_name(); + let Some(name_str) = fname.to_str() else { + continue; + }; + let Some(num_str) = name_str.strip_prefix("hidraw") else { + continue; + }; + let idx = num_str.parse::().unwrap_or(u32::MAX); + let uevent_path = format!("/sys/class/hidraw/{}/device/uevent", name_str); + let Ok(uevent) = fs::read_to_string(&uevent_path) else { + continue; + }; + let Some((vid, pid, hid_name)) = Self::parse_hid_id(&uevent) else { + continue; + }; + if vid == VALVE_VENDOR_ID && Self::is_ibex_pid(pid) { + candidates.push((idx, format!("/dev/{}", name_str), hid_name, vid, pid)); + } + } + + // Trier par numéro (hidraw9 / input2 en premier) + candidates.sort_by_key(|c| c.0); + + for (_, dev_path, hid_name, vid, pid) in candidates { + if let Some(opened) = Self::probe_single(&dev_path, hid_name, vid, pid) { + return Some(opened); + } + } + None + } + + fn poll_events(&mut self, out_pressed_keys: &mut Vec) -> Result<()> { + let mut buf = [0u8; 64]; + loop { + match self.file.read(&mut buf) { + Ok(0) => return Err(anyhow!("EOF hidraw (manette déconnectée)")), + Ok(n) => { + if let Some(parsed) = parse_ibex_hidraw_report(&buf[..n]) { + self.last_report_at = Instant::now(); + self.steer_axis.current = parsed.steer_raw; + self.throttle_axis.current = parsed.throttle_raw; + self.brake_axis.current = parsed.brake_raw; + self.clutch_pressed = parsed.clutch_pressed; + + for &(byte_idx, mask, btn_code) in IBEX_BUTTON_MAP { + let arr_idx = byte_idx - 2; + let now_down = (parsed.btn_bytes[arr_idx] & mask) != 0; + let prev_down = (self.prev_btn_bytes[arr_idx] & mask) != 0; + if now_down && !prev_down { + out_pressed_keys.push(btn_code); + } + } + self.prev_btn_bytes = parsed.btn_bytes; + } + } + Err(e) if e.kind() == ErrorKind::WouldBlock => break, + Err(e) => return Err(anyhow!("Erreur lecture hidraw : {}", e)), + } + } + + if self.last_report_at.elapsed() > Duration::from_millis(IBEX_HIDRAW_TIMEOUT_MS) { + return Err(anyhow!( + "Timeout HIDRAW ({} ms sans trame 0x42 — manette en veille ou éteinte)", + IBEX_HIDRAW_TIMEOUT_MS + )); + } + Ok(()) + } +} + +enum OpenGamepad { + IbexHidraw(OpenIbexHidraw), + Evdev(OpenEvdevGamepad), +} + +impl OpenGamepad { + fn open_best(override_path: Option<&str>) -> Option { + if let Some(ibex) = OpenIbexHidraw::find_and_open(override_path) { + return Some(Self::IbexHidraw(ibex)); + } + if let Some(dev_info) = find_steam_controller_device(override_path) { + match OpenEvdevGamepad::open(dev_info) { + Ok(ev) => return Some(Self::Evdev(ev)), + Err(e) => { + log::warn!("[Steam Controller] Impossible d'ouvrir evdev : {}", e); + } + } + } + None + } + + fn name(&self) -> &str { + match self { + Self::IbexHidraw(h) => &h.name, + Self::Evdev(e) => &e.info.name, + } + } + + fn path(&self) -> &str { + match self { + Self::IbexHidraw(h) => &h.path, + Self::Evdev(e) => &e.info.path, + } + } + + fn summary_log(&self) -> String { + match self { + Self::IbexHidraw(h) => format!( + "'{}' sur {} (VID={:04X}, PID={:04X}, mode=HIDRAW Ibex 0x42 natif)", + h.name, h.path, h.vendor, h.product + ), + Self::Evdev(e) => format!( + "'{}' sur {} (VID={:04X}, PID={:04X}, mode=evdev {})", + e.info.name, + e.info.path, + e.info.vendor, + e.info.product, + if e.info.has_hat2_triggers { + "hid-steam HAT2X/Y" + } else { + "standard RZ/Z" + } + ), + } + } + + fn poll_events(&mut self, out_pressed_keys: &mut Vec) -> Result<()> { + match self { + Self::IbexHidraw(h) => h.poll_events(out_pressed_keys), + Self::Evdev(e) => e.poll_events(out_pressed_keys), + } + } + + fn steer_norm(&self) -> f32 { + match self { + Self::IbexHidraw(h) => h.steer_axis.normalized_signed(), + Self::Evdev(e) => e.steer_axis.normalized_signed(), + } + } + + fn throttle_norm(&self) -> f32 { + match self { + Self::IbexHidraw(h) => h.throttle_axis.normalized_unsigned(), + Self::Evdev(e) => e.throttle_axis.normalized_unsigned(), + } + } + + fn brake_norm(&self) -> f32 { + match self { + Self::IbexHidraw(h) => h.brake_axis.normalized_unsigned(), + Self::Evdev(e) => e.brake_axis.normalized_unsigned(), + } + } + + fn clutch_pressed(&self) -> bool { + match self { + Self::IbexHidraw(h) => h.clutch_pressed, + Self::Evdev(e) => e.clutch_pressed, + } + } +} + // ========================================================================= // WORKER TEMPS RÉEL STEAM CONTROLLER -> UDP :14552 -> RADXA -> RP2350 // ========================================================================= @@ -798,7 +1118,7 @@ impl SteamControllerWorker { state: Arc>, stop_flag: Arc, ) { - let mut gamepad: Option = None; + let mut gamepad: Option = None; let mut last_scan = Instant::now() - Duration::from_secs(10); let mut last_src_sync = Instant::now() - Duration::from_secs(10); let mut last_source = ControlSource::from_u8(active_source.load(Ordering::Acquire)); @@ -850,39 +1170,20 @@ impl SteamControllerWorker { last_src_sync = Instant::now(); } - // 2. Découverte / reconnexion à chaud du Steam Controller (evdev) + // 2. Découverte / reconnexion à chaud du Steam Controller (HIDRAW Ibex natif ou evdev) if gamepad.is_none() && last_scan.elapsed() >= Duration::from_millis(DEVICE_RESCAN_INTERVAL_MS) { last_scan = Instant::now(); - if let Some(dev_info) = find_steam_controller_device(cfg.device_override.as_deref()) - { - match OpenEvdevGamepad::open(dev_info) { - Ok(opened) => { - log::info!( - "[Steam Controller] Connecté : '{}' sur {} (VID={:04X}, PID={:04X}, triggers={})", - opened.info.name, - opened.info.path, - opened.info.vendor, - opened.info.product, - if opened.info.has_hat2_triggers { - "hid-steam HAT2X/Y" - } else { - "standard RZ/Z" - } - ); - let mut st = state.lock(); - st.connected = true; - st.device_name = opened.info.name.clone(); - st.device_path = opened.info.path.clone(); - st.armed = false; - st.gear = 0; - gamepad = Some(opened); - } - Err(e) => { - log::warn!("[Steam Controller] Impossible d'ouvrir le périphérique : {}", e); - } - } + if let Some(opened) = OpenGamepad::open_best(cfg.device_override.as_deref()) { + log::info!("[Steam Controller] Connecté : {}", opened.summary_log()); + let mut st = state.lock(); + st.connected = true; + st.device_name = opened.name().to_string(); + st.device_path = opened.path().to_string(); + st.armed = false; + st.gear = 0; + gamepad = Some(opened); } } @@ -914,10 +1215,10 @@ impl SteamControllerWorker { // 4. Traitement axes, boîte séquentielle, boutons cockpit & émission $RC à 100 Hz if let Some(ref gp) = gamepad { - let steer_norm = gp.steer_axis.normalized_signed(); - let throttle_norm = gp.throttle_axis.normalized_unsigned(); - let brake_norm = gp.brake_axis.normalized_unsigned(); - let clutch_pressed = gp.clutch_pressed; + let steer_norm = gp.steer_norm(); + let throttle_norm = gp.throttle_norm(); + let brake_norm = gp.brake_norm(); + let clutch_pressed = gp.clutch_pressed(); let steer_crsf = steering_to_crsf( steer_norm, @@ -1202,4 +1503,26 @@ mod tests { "$RC,992,1150,992,992,1,2\n" ); } + + #[test] + fn test_parse_ibex_hidraw_report() { + let mut raw = [0u8; IBEX_REPORT_LEN]; + raw[0] = IBEX_REPORT_ID; + raw[2] = 0x41; // A (0x01) + Menu/Start (0x40) + raw[3] = 0x02; // RB + raw[4] = 0x04; // L5 clutch + // Brake (L2) at 6..8 = 16384 + raw[6..8].copy_from_slice(&16384i16.to_le_bytes()); + // Throttle (R2) at 8..10 = 32767 + raw[8..10].copy_from_slice(&32767i16.to_le_bytes()); + // Left stick X at 10..12 = -16384 + raw[10..12].copy_from_slice(&(-16384i16).to_le_bytes()); + + let parsed = parse_ibex_hidraw_report(&raw).expect("rapport 0x42 valide"); + assert_eq!(parsed.brake_raw, 16384); + assert_eq!(parsed.throttle_raw, 32767); + assert_eq!(parsed.steer_raw, -16384); + assert!(parsed.clutch_pressed); + assert_eq!(parsed.btn_bytes, [0x41, 0x02, 0x04, 0x00]); + } } diff --git a/src/gui_gpui.rs b/src/gui_gpui.rs index f657827..ce61b97 100644 --- a/src/gui_gpui.rs +++ b/src/gui_gpui.rs @@ -2878,9 +2878,16 @@ impl SteamFrameGpuiApp { } fn render_controller_monitor(&self, cx: &mut Context) -> impl IntoElement { - let viewed_source = self - .monitor_source_override - .unwrap_or(self.active_control_source); + let viewed_source = self.monitor_source_override.unwrap_or_else(|| { + if self.active_control_source == ControlSource::G29 + && !self.latest_g29.is_live() + && self.latest_controller.connected + { + ControlSource::SteamController + } else { + self.active_control_source + } + }); let is_steam_view = viewed_source == ControlSource::SteamController; let ( @@ -3172,14 +3179,12 @@ impl SteamFrameGpuiApp { clutch_crsf, COLOR_CYAN, )) - // Pied du moniteur : dernier bouton & détails liaison + // Pied du moniteur : dernier bouton & détails liaison (sur 2 lignes pour éviter toute troncature) .child( div() .flex() - .flex_wrap() - .justify_between() - .items_center() - .gap_2() + .flex_col() + .gap_1() .pt_1() .border_t_1() .border_color(rgb(COLOR_BORDER_SUBTLE))