From ac955934b501a451cc5b0c3c5d244e57a057517c Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 15 Oct 2026 16:35:33 +0200 Subject: [PATCH 1/2] DualSense output over HID: the report, a writer thread, and rumble through it The horizon-dualsense crate builds the DualSense's output report (USB 0x02, Bluetooth 0x31 with its CRC-32 seeded with 0xA2) and writes it with hidapi from a thread. The game sends its rumble pulses through it when the active pad is a DualSense, so vibration now works on macOS too, and falls back to gilrs force feedback when the pad can't be opened. Quitting frees the triggers and stops the motors. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 22 ++ Cargo.toml | 2 +- crates/horizon-client/Cargo.toml | 2 + crates/horizon-client/src/game.rs | 1 + crates/horizon-client/src/game/pad.rs | 47 ++- crates/horizon-dualsense/Cargo.toml | 16 + .../horizon-dualsense/examples/dualsense.rs | 270 ++++++++++++++ crates/horizon-dualsense/src/device.rs | 341 ++++++++++++++++++ crates/horizon-dualsense/src/lib.rs | 290 +++++++++++++++ docs/controllers.md | 73 +++- 10 files changed, 1053 insertions(+), 11 deletions(-) create mode 100644 crates/horizon-dualsense/Cargo.toml create mode 100644 crates/horizon-dualsense/examples/dualsense.rs create mode 100644 crates/horizon-dualsense/src/device.rs create mode 100644 crates/horizon-dualsense/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock index 761e2ddc6..3138764a0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1187,6 +1187,19 @@ version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" +[[package]] +name = "hidapi" +version = "2.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "818c0e1d27887aaf76fe737042e27a66b796a7b099e6d2e1a72d106c2dff3fa6" +dependencies = [ + "cc", + "cfg-if", + "libc", + "pkg-config", + "windows-sys 0.61.2", +] + [[package]] name = "hkdf" version = "0.12.4" @@ -1238,6 +1251,7 @@ dependencies = [ "horizon-assets", "horizon-bench", "horizon-core", + "horizon-dualsense", "horizon-friends", "horizon-protocol", "horizon-telemetry", @@ -1267,6 +1281,14 @@ dependencies = [ "libm", ] +[[package]] +name = "horizon-dualsense" +version = "0.1.0" +dependencies = [ + "hidapi", + "log", +] + [[package]] name = "horizon-friends" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 03b7e1d66..19fbabc55 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] exclude = ["launcher", "crates/horizon-telemetry-server"] -members = ["crates/horizon-core", "crates/horizon-world", "crates/voxel-kernels", "crates/horizon-client", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/cargo-horizon-mod", "crates/horizon-mod-sdk/examples/coords-hud", "xtask"] +members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-world", "crates/voxel-kernels", "crates/horizon-client", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/cargo-horizon-mod", "crates/horizon-mod-sdk/examples/coords-hud", "xtask"] resolver = "2" [workspace.package] diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index ef06335c0..09d24c7f2 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -40,6 +40,8 @@ arboard = { version = "3.6.1", default-features = false, features = ["wayland-da zip = { version = "2", default-features = false, features = ["deflate"] } # Controllers (evdev + libudev on Linux, IOKit on macOS, Windows.Gaming.Input). gilrs = "0.11" +# The DualSense's rumble, adaptive triggers and lights over HID (gilrs only reads it). +horizon-dualsense = { path = "../horizon-dualsense" } # HTTPS to the Minecraft services (online-mode session join). ureq = { version = "2", default-features = false, features = ["tls"] } diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 2f12e5136..12b2519dd 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -9408,6 +9408,7 @@ impl ApplicationHandler for Game<'_> { /// applicationWillTerminate without a CloseRequested; vanilla's GLFW /// window turns it into a window close, so Minecraft.stop saves the world. fn exiting(&mut self, _event_loop: &ActiveEventLoop) { + self.pad_close_output(); if let Err(e) = self.save_for_exit() { log::warn!("Horizon: failed to save the world on exit: {e}"); } diff --git a/crates/horizon-client/src/game/pad.rs b/crates/horizon-client/src/game/pad.rs index a9009db35..ce0633615 100644 --- a/crates/horizon-client/src/game/pad.rs +++ b/crates/horizon-client/src/game/pad.rs @@ -54,6 +54,11 @@ pub(super) struct Pads { last_rumble: Option<(&'static str, gamepad::Pulse)>, /// The player's health between polls (a drop is damage taken). health: HealthWatch, + /// The active pad is a DualSense. + dualsense: bool, + /// Its own output over HID (rumble here; gilrs only reads it), started once this window + /// has the pad in hand; dropped, it releases the pad. + output: Option, } fn gilrs_button(button: Button) -> gilrs::Button { @@ -78,6 +83,11 @@ fn gilrs_button(button: Button) -> gilrs::Button { } } +fn is_dualsense(pad: &gilrs::Gamepad) -> bool { + matches!((pad.vendor_id(), pad.product_id()), + (Some(vendor), Some(product)) if horizon_dualsense::is_dualsense(vendor, product)) +} + impl Pads { /// A new player entity took over (spawn, respawn, a server joined, a /// dimension change): its health is not compared with the old one's. @@ -116,12 +126,18 @@ impl Pads { match event { E::Connected => { log::info!("Controller connected: {}", gilrs.gamepad(id).name()); + if let Some(output) = &self.output { + output.scan(); + } } E::Disconnected => { log::info!("Controller disconnected: {}", gilrs.gamepad(id).name()); if self.active == Some(id) { self.active = None; } + if let Some(output) = &self.output { + output.scan(); + } } E::ButtonPressed(..) => self.active = Some(id), E::AxisChanged(_, value, _) | E::ButtonChanged(_, value, _) @@ -133,9 +149,12 @@ impl Pads { } } let Some(pad) = self.active.and_then(|id| gilrs.connected_gamepad(id)) else { + // Before any pad is touched (the virtual pad playing), a DualSense still shows it. + self.dualsense = gilrs.gamepads().any(|(_, pad)| is_dualsense(&pad)); return PadState::default(); }; self.style = GlyphStyle::of_vendor(pad.vendor_id()); + self.dualsense = is_dualsense(&pad); let mut state = PadState::default(); for button in Button::ALL { if !matches!(button, Button::LeftTrigger | Button::RightTrigger) { @@ -192,6 +211,9 @@ impl Game<'_> { self.pad.in_use = true; } self.pad.state = state; + if self.pad.dualsense && self.pad.in_use && self.focused && self.pad.output.is_none() { + self.pad.output = Some(horizon_dualsense::Link::start()); + } // Damage from any source, here or on a server; nothing counts on // the title screen. let health = self @@ -378,9 +400,22 @@ impl Game<'_> { self.pitch = rotation.x_rot; } + /// The DualSense's HID output, while it is the active pad, open, and this window has focus + /// (another game on the same pad keeps it otherwise). + fn pad_output(&self) -> Option<&horizon_dualsense::Link> { + let output = self.pad.output.as_ref()?; + (self.pad.dualsense && self.focused && output.open().is_some()).then_some(output) + } + + /// Release the DualSense's output (the game is quitting). + pub(super) fn pad_close_output(&mut self) { + self.pad.output = None; + } + /// Vibrate the active pad, when vibration is on and the pad is the one - /// playing (a pad lying idle while the mouse plays stays still). - /// Platforms without force feedback (gilrs on macOS) skip it. + /// playing (a pad lying idle while the mouse plays stays still): a + /// DualSense through its own report, else gilrs' force feedback, which + /// platforms without it (gilrs on macOS) skip. pub(super) fn pad_rumble(&mut self, rumble: Rumble) { let settings = &self.settings.controller; if !settings.enabled || !settings.vibration || !self.pad.in_use { @@ -390,6 +425,12 @@ impl Game<'_> { return; }; self.pad.last_rumble = Some((rumble.name(), pulse)); + let level = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + if let Some(output) = self.pad_output() { + let length = Duration::from_millis(u64::from(pulse.millis)); + output.rumble(vec![([level(pulse.strong), level(pulse.weak)], length)]); + return; + } let (Some(gilrs), Some(id)) = (self.pad.gilrs.as_mut(), self.pad.active) else { return; }; @@ -470,6 +511,8 @@ impl Game<'_> { "backend": self.pad.gilrs.is_some(), "controllers": pads, "glyphs": self.pad.style.name(), + "dualsense_output": self.pad.output.as_ref().and_then(|o| o.open()) + .map(|t| format!("{t:?}")), "last_rumble": self.pad.last_rumble.map(|(why, p)| json!({ "reason": why, "strong": p.strong, "weak": p.weak, "ms": p.millis, })), diff --git a/crates/horizon-dualsense/Cargo.toml b/crates/horizon-dualsense/Cargo.toml new file mode 100644 index 000000000..8e26f2e59 --- /dev/null +++ b/crates/horizon-dualsense/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "horizon-dualsense" +version = "0.1.0" +edition.workspace = true +license.workspace = true +rust-version = "1.85" +description = "The DualSense's output over HID: rumble, adaptive triggers, lightbar and player LEDs" + +[dependencies] +# MIT; bundles the C hidapi under its BSD licence option. hidraw on Linux (libudev, as gilrs), +# IOKit on macOS (opened shared, so gilrs keeps reading the pad), the HID API on Windows. +hidapi = { version = "2.6.7", default-features = false, features = ["linux-static-hidraw", "macos-shared-device"] } +log = "0.4" + +[lints] +workspace = true diff --git a/crates/horizon-dualsense/examples/dualsense.rs b/crates/horizon-dualsense/examples/dualsense.rs new file mode 100644 index 000000000..a6917b6fc --- /dev/null +++ b/crates/horizon-dualsense/examples/dualsense.rs @@ -0,0 +1,270 @@ +//! Plays each output on a real DualSense and reads back what the pad reports, so a change to the +//! reports can be checked without the game: +//! +//! cargo run -p horizon-dualsense --example dualsense -- [status|rumble|lightbar|leds|triggers|link|all|watch] +//! +//! The pad's input report carries the triggers' active effect, and its accelerometer and gyro +//! pick up the motors, so `rumble` measures the shake against the pad lying still. +use horizon_dualsense::device::{DualSense, Link, State}; +use horizon_dualsense::{Output, TRIGGER_OFF, TriggerEffect}; +use std::time::{Duration, Instant}; + +/// Offsets in the input report's data, after the report ID (USB 0x01) or the ID and a tag byte +/// (Bluetooth 0x31). +const GYRO: usize = 0x0f; +const ACCEL: usize = 0x15; +const RIGHT_TRIGGER_STATUS: usize = 0x29; +const LEFT_TRIGGER_STATUS: usize = 0x2a; +const TRIGGER_EFFECTS: usize = 0x2f; +const POWER: usize = 0x34; + +fn main() { + let what = std::env::args().nth(1).unwrap_or_else(|| "all".into()); + let api = hidapi::HidApi::new().expect("hidapi"); + let mut pad = match DualSense::open(&api) { + Some(Ok(pad)) => pad, + Some(Err(e)) => panic!("the DualSense is there but can't be opened: {e}"), + None => panic!("no DualSense found"), + }; + println!("DualSense over {:?}", pad.transport()); + let all = what == "all"; + if all || what == "status" { + status(&pad); + } + if all || what == "rumble" { + rumble(&mut pad); + } + if all || what == "lightbar" { + lightbar(&mut pad); + } + if all || what == "leds" { + leds(&mut pad); + } + if all || what == "triggers" { + triggers(&mut pad); + } + if what == "watch" { + // The shake every 200 ms for 30 s, while something else (the game) drives the pad. + for _ in 0..150 { + let (accel, gyro) = shake(&pad, Duration::from_millis(200)); + if accel > 100.0 { + println!( + " {:?} shaking: accel {accel:7.1} gyro {gyro:7.1}", + std::time::SystemTime::now() + ); + } + } + } + drop(pad); + if all || what == "link" { + link(); + } +} + +/// The data of the next full input report. +fn input(pad: &DualSense) -> Vec { + let mut buf = [0; 80]; + // Skip the reports queued since the last read. + while pad.read(&mut buf, 0).is_ok_and(|n| n > 0) {} + loop { + let n = pad.read(&mut buf, 1000).expect("read"); + match buf[0] { + 0x01 if n >= 64 => return buf[1..n].to_vec(), + 0x31 if n >= 78 => return buf[2..n].to_vec(), + _ => {} + } + } +} + +fn status(pad: &DualSense) { + let d = input(pad); + println!( + " sticks {:?} triggers {:?} battery {}%", + &d[0..4], + &d[4..6], + (d[POWER] & 0x0f).min(10) * 10 + ); + trigger_status(pad); +} + +fn trigger_status(pad: &DualSense) { + let d = input(pad); + println!( + " triggers report: right {:02x} left {:02x} effects {:02x}", + d[RIGHT_TRIGGER_STATUS], d[LEFT_TRIGGER_STATUS], d[TRIGGER_EFFECTS] + ); +} + +/// How much the pad shakes over `time`: the standard deviation of the accelerometer and the +/// gyro, summed over the axes. +fn shake(pad: &DualSense, time: Duration) -> (f64, f64) { + let end = Instant::now() + time; + let mut samples = Vec::new(); + while Instant::now() < end { + let d = input(pad); + let axis = + |at: usize, i: usize| f64::from(i16::from_le_bytes([d[at + 2 * i], d[at + 2 * i + 1]])); + samples.push([0, 1, 2, 3, 4, 5].map(|i| { + if i < 3 { + axis(ACCEL, i) + } else { + axis(GYRO, i - 3) + } + })); + } + let deviation = |range: std::ops::Range| -> f64 { + range + .map(|i| { + let n = samples.len() as f64; + let mean = samples.iter().map(|s| s[i]).sum::() / n; + (samples.iter().map(|s| (s[i] - mean).powi(2)).sum::() / n).sqrt() + }) + .sum() + }; + (deviation(0..3), deviation(3..6)) +} + +fn write(pad: &mut DualSense, out: Output) { + pad.write(&out).expect("write"); +} + +fn rumble(pad: &mut DualSense) { + let still = shake(pad, Duration::from_millis(400)); + println!( + " still: accel {:7.1} gyro {:7.1}", + still.0, still.1 + ); + for (name, motors) in [ + ("left (heavy) 50%", [128, 0]), + ("left (heavy) 100%", [255, 0]), + ("right (light) 50%", [0, 128]), + ("right (light) 100%", [0, 255]), + ("both 100%", [255, 255]), + ] { + write( + pad, + Output { + rumble: Some(motors), + ..Output::default() + }, + ); + let s = shake(pad, Duration::from_millis(400)); + println!(" {name:18} accel {:7.1} gyro {:7.1}", s.0, s.1); + write( + pad, + Output { + rumble: Some([0, 0]), + ..Output::default() + }, + ); + std::thread::sleep(Duration::from_millis(250)); + } + for i in 1..=3 { + let after = shake(pad, Duration::from_millis(300)); + println!( + " stopped ({i}): accel {:7.1} gyro {:7.1}", + after.0, after.1 + ); + } +} + +fn lightbar(pad: &mut DualSense) { + write( + pad, + Output { + release_leds: true, + ..Output::default() + }, + ); + for (name, rgb) in [ + ("red", [255, 0, 0]), + ("green", [0, 255, 0]), + ("blue", [0, 0, 255]), + ("Horizon violet", [0x8b, 0x5c, 0xf6]), + ] { + println!(" lightbar {name}"); + write( + pad, + Output { + lightbar: Some(rgb), + ..Output::default() + }, + ); + std::thread::sleep(Duration::from_millis(800)); + } +} + +fn leds(pad: &mut DualSense) { + for (name, leds) in [ + ("player 1", 0b00100), + ("player 2", 0b01010), + ("player 3", 0b10101), + ("player 4", 0b11011), + ("all", 0b11111), + ("none", 0), + ] { + println!(" player LEDs {name}"); + write( + pad, + Output { + player_leds: Some(leds | horizon_dualsense::PLAYER_LEDS_INSTANT), + ..Output::default() + }, + ); + std::thread::sleep(Duration::from_millis(600)); + } + write( + pad, + Output { + player_leds: Some(0b00100), + ..Output::default() + }, + ); +} + +fn triggers(pad: &mut DualSense) { + // Raw effects in the pad's own encoding (docs/controllers.md): resistance from zone 3 on at + // strength 6, then a weapon click between zones 2 and 6. + let feedback: TriggerEffect = [0x21, 0xf8, 0x03, 0x00, 0xda, 0xb6, 0x2d, 0, 0, 0, 0]; + let weapon: TriggerEffect = [0x25, 0x44, 0x00, 0x05, 0, 0, 0, 0, 0, 0, 0]; + for (name, effect) in [ + ("feedback", feedback), + ("weapon", weapon), + ("off", TRIGGER_OFF), + ] { + write( + pad, + Output { + left_trigger: Some(effect), + right_trigger: Some(effect), + ..Output::default() + }, + ); + std::thread::sleep(Duration::from_millis(100)); + print!(" {name:9}"); + trigger_status(pad); + } +} + +/// The writer thread: a state, a two-step vibration, and the release when it drops. +fn link() { + println!("link:"); + let link = Link::start(); + let start = Instant::now(); + while link.open().is_none() && start.elapsed() < Duration::from_secs(3) { + std::thread::sleep(Duration::from_millis(20)); + } + println!(" open over {:?} after {:?}", link.open(), start.elapsed()); + link.set(State { + triggers: [TRIGGER_OFF, [0x25, 0x44, 0x00, 0x05, 0, 0, 0, 0, 0, 0, 0]], + lightbar: Some([0x8b, 0x5c, 0xf6]), + player_leds: Some(0b00100), + }); + link.rumble(vec![ + ([200, 0], Duration::from_millis(120)), + ([0, 160], Duration::from_millis(200)), + ]); + std::thread::sleep(Duration::from_millis(600)); + drop(link); + println!(" dropped: triggers released"); +} diff --git a/crates/horizon-dualsense/src/device.rs b/crates/horizon-dualsense/src/device.rs new file mode 100644 index 000000000..3591a1598 --- /dev/null +++ b/crates/horizon-dualsense/src/device.rs @@ -0,0 +1,341 @@ +//! The pad over hidapi, and the thread that writes to it: writes block (a Bluetooth report can +//! take milliseconds), so the game only hands over what the pad should do. +use crate::{Output, TRIGGER_OFF, TriggerEffect, Vibration, is_dualsense}; +use hidapi::{BusType, HidApi, HidDevice, HidResult}; +use std::sync::Arc; +use std::sync::atomic::{AtomicU8, Ordering}; +use std::sync::mpsc::{self, RecvTimeoutError, Sender}; +use std::thread::JoinHandle; +use std::time::{Duration, Instant}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Transport { + Usb, + Bluetooth, +} + +/// An open DualSense. +pub struct DualSense { + device: HidDevice, + transport: Transport, + vibration: Vibration, + /// The Bluetooth report's sequence number. + seq: u8, +} + +impl DualSense { + /// The first DualSense hidapi lists; `None` when there is none, an error when it can't be + /// opened (Linux without access to its hidraw node). + pub fn open(api: &HidApi) -> Option> { + let info = api + .device_list() + .find(|d| is_dualsense(d.vendor_id(), d.product_id()))?; + let transport = match info.bus_type() { + BusType::Bluetooth => Transport::Bluetooth, + _ => Transport::Usb, + }; + Some(info.open_device(api).map(|device| { + let mut firmware = [0; 64]; + firmware[0] = 0x20; + // The update version decides how vibration is asked for; without it, the kernel's + // default. + let vibration = match device.get_feature_report(&mut firmware) { + Ok(n) if n >= 46 => { + Vibration::of_update_version(u16::from_le_bytes([firmware[44], firmware[45]])) + } + _ => Vibration::Legacy, + }; + DualSense { + device, + transport, + vibration, + seq: 0, + } + })) + } + + pub fn transport(&self) -> Transport { + self.transport + } + + pub fn write(&mut self, out: &Output) -> HidResult<()> { + match self.transport { + Transport::Usb => self.device.write(&out.usb(self.vibration))?, + Transport::Bluetooth => { + let report = out.bluetooth(self.vibration, self.seq); + self.seq = (self.seq + 1) & 0x0f; + self.device.write(&report)? + } + }; + Ok(()) + } + + /// An input report (USB 0x01, Bluetooth 0x31), waiting up to `millis` (-1: forever). + pub fn read(&self, buf: &mut [u8], millis: i32) -> HidResult { + self.device.read_timeout(buf, millis) + } +} + +/// What the pad should show while nothing else is asked: the triggers' effects (left, right), +/// the lightbar and the player LEDs (`None`: the pad's own). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct State { + pub triggers: [TriggerEffect; 2], + pub lightbar: Option<[u8; 3]>, + pub player_leds: Option, +} + +impl Default for State { + fn default() -> Self { + State { + triggers: [TRIGGER_OFF; 2], + lightbar: None, + player_leds: None, + } + } +} + +/// A vibration: the motors' levels (left, right), each for a while, in order. +pub type Rumble = Vec<([u8; 2], Duration)>; + +enum Message { + State(State), + Rumble(Rumble), + Scan, +} + +/// The writer thread. Dropping it frees the triggers and stops the motors before it ends. +pub struct Link { + tx: Option>, + /// 0: no pad open, else 1 + the transport. + open: Arc, + thread: Option>, +} + +impl Link { + /// Start the thread and look for a DualSense. + pub fn start() -> Link { + let (tx, rx) = mpsc::channel(); + let open = Arc::new(AtomicU8::new(0)); + let shown = open.clone(); + let thread = std::thread::Builder::new() + .name("dualsense".into()) + .spawn(move || Writer::new(shown).run(rx)) + .map_err(|e| log::warn!("Horizon: DualSense output: {e}")) + .ok(); + Link { + tx: Some(tx), + open, + thread, + } + } + + /// The pad's transport while one is open and taking reports. + pub fn open(&self) -> Option { + match self.open.load(Ordering::Relaxed) { + 1 => Some(Transport::Usb), + 2 => Some(Transport::Bluetooth), + _ => None, + } + } + + /// Look for the pad again (a controller connected). + pub fn scan(&self) { + self.send(Message::Scan); + } + + /// What the pad shows from now on; sent again whenever it reconnects. + pub fn set(&self, state: State) { + self.send(Message::State(state)); + } + + /// Play a vibration, replacing the one playing. + pub fn rumble(&self, rumble: Rumble) { + self.send(Message::Rumble(rumble)); + } + + fn send(&self, message: Message) { + if let Some(tx) = &self.tx { + let _ = tx.send(message); + } + } +} + +impl Drop for Link { + fn drop(&mut self) { + // Closing the channel ends the thread, which releases the pad first. + self.tx = None; + if let Some(thread) = self.thread.take() { + let _ = thread.join(); + } + } +} + +/// Looks for the pad this many more times, a second apart, after a scan finds nothing (its +/// hidraw node may appear after the controller does). +const SCAN_TRIES: u32 = 5; + +struct Writer { + api: Option, + pad: Option, + open: Arc, + state: State, + /// What the pad was last sent; `None` after (re)opening. + sent: Option<(State, [u8; 2])>, + rumble: Rumble, + /// When the vibration's current step ends. + step_end: Option, + scans_left: u32, + next_scan: Instant, +} + +impl Writer { + fn new(open: Arc) -> Self { + Writer { + api: None, + pad: None, + open, + state: State::default(), + sent: None, + rumble: Vec::new(), + step_end: None, + scans_left: 1, + next_scan: Instant::now(), + } + } + + fn run(mut self, rx: mpsc::Receiver) { + loop { + let now = Instant::now(); + if self.pad.is_none() && self.scans_left > 0 && now >= self.next_scan { + self.scan(); + } + let wake = [ + self.step_end, + (self.pad.is_none() && self.scans_left > 0).then_some(self.next_scan), + ] + .into_iter() + .flatten() + .min(); + let message = match wake { + Some(at) => rx.recv_timeout(at.saturating_duration_since(now)), + None => rx.recv().map_err(|_| RecvTimeoutError::Disconnected), + }; + match message { + Ok(Message::State(state)) => self.state = state, + Ok(Message::Rumble(rumble)) => { + self.rumble = rumble; + self.rumble.reverse(); + self.step_end = None; + } + Ok(Message::Scan) => { + // A pad that was unplugged while idle fails to read. + let mut buf = [0; 80]; + if self + .pad + .as_ref() + .is_some_and(|pad| pad.read(&mut buf, 0).is_err()) + { + self.lost("unplugged"); + } + if self.pad.is_none() { + self.scans_left = SCAN_TRIES; + self.next_scan = Instant::now(); + } + continue; + } + Err(RecvTimeoutError::Timeout) => {} + Err(RecvTimeoutError::Disconnected) => break, + } + self.advance_rumble(); + self.flush(); + } + if let Some(pad) = self.pad.as_mut() { + let _ = pad.write(&Output::release()); + } + } + + fn scan(&mut self) { + self.scans_left -= 1; + self.next_scan = Instant::now() + Duration::from_secs(1); + let api = match self.api.as_mut() { + Some(api) => api.refresh_devices().map(|()| &*api), + None => HidApi::new().map(|api| &*self.api.insert(api)), + }; + let found = match api { + Ok(api) => DualSense::open(api), + Err(e) => { + log::warn!("Horizon: DualSense output: {e}"); + None + } + }; + match found { + Some(Ok(pad)) => { + log::info!("DualSense output over {:?}", pad.transport()); + self.open + .store(1 + pad.transport() as u8, Ordering::Relaxed); + self.pad = Some(pad); + self.sent = None; + self.scans_left = 0; + self.flush(); + } + Some(Err(e)) => { + // No access (Linux without a udev rule): vibration stays with gilrs. + log::info!("Horizon: the DualSense can't be opened for output: {e}"); + self.scans_left = 0; + } + None => {} + } + } + + /// Move to the vibration's next step once this one is over. + fn advance_rumble(&mut self) { + let now = Instant::now(); + match self.step_end { + Some(end) if end > now => return, + Some(_) => { + self.rumble.pop(); + } + None => {} + } + self.step_end = self.rumble.last().map(|&(_, length)| now + length); + } + + /// Send what changed; a failed write means the pad is gone. + fn flush(&mut self) { + let Some(pad) = self.pad.as_mut() else { + return; + }; + let motors = self.rumble.last().map_or([0, 0], |(m, _)| *m); + let (state, sent) = (self.state, self.sent); + if sent == Some((state, motors)) { + return; + } + let mut out = Output { + rumble: (sent.is_none_or(|(_, m)| m != motors)).then_some(motors), + release_leds: sent.is_none() && state.lightbar.is_some(), + ..Output::default() + }; + let old = sent.map(|(s, _)| s); + if old.is_none_or(|s| s.triggers != state.triggers) { + out.left_trigger = Some(state.triggers[0]); + out.right_trigger = Some(state.triggers[1]); + } + if old.is_none_or(|s| s.lightbar != state.lightbar) { + out.lightbar = state.lightbar; + } + if old.is_none_or(|s| s.player_leds != state.player_leds) { + out.player_leds = state.player_leds; + } + match pad.write(&out) { + Ok(()) => self.sent = Some((state, motors)), + Err(e) => self.lost(&e.to_string()), + } + } + + fn lost(&mut self, why: &str) { + log::info!("DualSense output closed: {why}"); + self.pad = None; + self.open.store(0, Ordering::Relaxed); + } +} diff --git a/crates/horizon-dualsense/src/lib.rs b/crates/horizon-dualsense/src/lib.rs new file mode 100644 index 000000000..46d6627d1 --- /dev/null +++ b/crates/horizon-dualsense/src/lib.rs @@ -0,0 +1,290 @@ +//! The DualSense's output report, built by hand (docs/controllers.md "DualSense output"): the +//! compatible-vibration motors, the adaptive triggers, the lightbar and the player LEDs. Gilrs +//! keeps reading the pad; this crate only writes to it, over hidapi ([`device`]). +//! +//! The byte layout is the one documented by the Linux kernel's `hid-playstation.c` and SDL's +//! `SDL_hidapi_ps5.c`: a 47-byte block shared by both transports, sent as report 0x02 over USB +//! and as report 0x31 over Bluetooth, where a sequence tag leads it and a CRC-32 (seeded with +//! the byte 0xA2) closes it. +pub mod device; + +pub use device::{Link, Transport}; + +/// Sony's vendor ID and the DualSense's product IDs (the plain pad and the Edge). +pub const SONY: u16 = 0x054c; +pub const DUALSENSE: u16 = 0x0ce6; +pub const DUALSENSE_EDGE: u16 = 0x0df2; + +/// Whether a USB vendor / product pair is a DualSense. +pub fn is_dualsense(vendor: u16, product: u16) -> bool { + vendor == SONY && matches!(product, DUALSENSE | DUALSENSE_EDGE) +} + +pub const USB_REPORT_ID: u8 = 0x02; +/// The report ID and the common block; Windows pads a short write to the report's length. +pub const USB_REPORT_LEN: usize = 1 + COMMON_LEN; +pub const BT_REPORT_ID: u8 = 0x31; +pub const BT_REPORT_LEN: usize = 78; +const BT_TAG: u8 = 0x10; +const BT_CRC_SEED: u8 = 0xa2; +const COMMON_LEN: usize = 47; + +// Offsets in the common block. +const FLAGS0: usize = 0; +const FLAGS1: usize = 1; +const MOTOR_RIGHT: usize = 2; +const MOTOR_LEFT: usize = 3; +const RIGHT_TRIGGER: usize = 10; +const LEFT_TRIGGER: usize = 21; +const FLAGS2: usize = 38; +const LIGHTBAR_SETUP: usize = 41; +const PLAYER_LEDS: usize = 43; +const LIGHTBAR: usize = 44; + +// Which parts of the block the pad applies. +const FLAG0_COMPATIBLE_VIBRATION: u8 = 1 << 0; +const FLAG0_HAPTICS_SELECT: u8 = 1 << 1; +const FLAG0_RIGHT_TRIGGER: u8 = 1 << 2; +const FLAG0_LEFT_TRIGGER: u8 = 1 << 3; +const FLAG1_LIGHTBAR: u8 = 1 << 2; +const FLAG1_RELEASE_LEDS: u8 = 1 << 3; +const FLAG1_PLAYER_LEDS: u8 = 1 << 4; +const FLAG2_LIGHTBAR_SETUP: u8 = 1 << 1; +const FLAG2_VIBRATION_V2: u8 = 1 << 2; +/// `lightbar_setup`: fade the firmware's own blue light out, so the host's colour shows. +const LIGHTBAR_LIGHT_OUT: u8 = 1 << 1; +/// Player LEDs: switch at once instead of fading. +pub const PLAYER_LEDS_INSTANT: u8 = 1 << 5; + +/// An adaptive trigger's effect: a mode byte and ten parameters. +pub type TriggerEffect = [u8; 11]; +/// The effect that frees a trigger. +pub const TRIGGER_OFF: TriggerEffect = [0x05, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + +/// What an output report changes; `None` leaves that part of the pad as it is. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Output { + /// The vibration motors, 0..255: the left (heavy, low) and the right (light, high) one. + pub rumble: Option<[u8; 2]>, + pub left_trigger: Option, + pub right_trigger: Option, + /// Red, green, blue. + pub lightbar: Option<[u8; 3]>, + /// The five LEDs under the touchpad, left to right in bits 0..4. + pub player_leds: Option, + /// Hand the lightbar to the host: the firmware's blue light fades out. + pub release_leds: bool, +} + +/// How the pad takes vibration: firmware 2.24 and later has a better rumble emulation, picked +/// with its own flag (`hid-playstation.c`'s `use_vibration_v2`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Vibration { + Legacy, + #[default] + V2, +} + +impl Vibration { + /// From the firmware's update version (feature report 0x20, bytes 44..46). + pub fn of_update_version(version: u16) -> Self { + if version >= 0x0224 { + Vibration::V2 + } else { + Vibration::Legacy + } + } +} + +impl Output { + /// Everything off: triggers free, motors still. + pub fn release() -> Self { + Output { + rumble: Some([0, 0]), + left_trigger: Some(TRIGGER_OFF), + right_trigger: Some(TRIGGER_OFF), + ..Output::default() + } + } + + /// The block both transports carry. + pub fn common(&self, vibration: Vibration) -> [u8; COMMON_LEN] { + let mut c = [0; COMMON_LEN]; + if let Some([left, right]) = self.rumble { + // Classic rumble rather than the audio-driven haptics. + c[FLAGS0] |= FLAG0_HAPTICS_SELECT; + match vibration { + Vibration::V2 => c[FLAGS2] |= FLAG2_VIBRATION_V2, + Vibration::Legacy => c[FLAGS0] |= FLAG0_COMPATIBLE_VIBRATION, + } + c[MOTOR_LEFT] = left; + c[MOTOR_RIGHT] = right; + } + if let Some(effect) = self.right_trigger { + c[FLAGS0] |= FLAG0_RIGHT_TRIGGER; + c[RIGHT_TRIGGER..RIGHT_TRIGGER + 11].copy_from_slice(&effect); + } + if let Some(effect) = self.left_trigger { + c[FLAGS0] |= FLAG0_LEFT_TRIGGER; + c[LEFT_TRIGGER..LEFT_TRIGGER + 11].copy_from_slice(&effect); + } + if self.release_leds { + c[FLAGS1] |= FLAG1_RELEASE_LEDS; + c[FLAGS2] |= FLAG2_LIGHTBAR_SETUP; + c[LIGHTBAR_SETUP] = LIGHTBAR_LIGHT_OUT; + } + if let Some(rgb) = self.lightbar { + c[FLAGS1] |= FLAG1_LIGHTBAR; + c[LIGHTBAR..LIGHTBAR + 3].copy_from_slice(&rgb); + } + if let Some(leds) = self.player_leds { + c[FLAGS1] |= FLAG1_PLAYER_LEDS; + c[PLAYER_LEDS] = leds; + } + c + } + + /// Report 0x02, for a pad on USB. + pub fn usb(&self, vibration: Vibration) -> [u8; USB_REPORT_LEN] { + let mut r = [0; USB_REPORT_LEN]; + r[0] = USB_REPORT_ID; + r[1..].copy_from_slice(&self.common(vibration)); + r + } + + /// Report 0x31, for a pad on Bluetooth: `seq` (0..15, wrapping) in the high nibble of the + /// second byte, then the tag, the block, and the CRC-32 of the seed byte and everything + /// before it, little-endian. + pub fn bluetooth(&self, vibration: Vibration, seq: u8) -> [u8; BT_REPORT_LEN] { + let mut r = [0; BT_REPORT_LEN]; + r[0] = BT_REPORT_ID; + r[1] = (seq & 0x0f) << 4; + r[2] = BT_TAG; + r[3..3 + COMMON_LEN].copy_from_slice(&self.common(vibration)); + let crc = bt_crc(&r[..BT_REPORT_LEN - 4]); + r[BT_REPORT_LEN - 4..].copy_from_slice(&crc.to_le_bytes()); + r + } +} + +/// The CRC a Bluetooth output report ends with: CRC-32 over the seed byte 0xA2 and the report. +pub fn bt_crc(report: &[u8]) -> u32 { + !report.iter().fold(crc32_update(!0, BT_CRC_SEED), |crc, b| { + crc32_update(crc, *b) + }) +} + +/// One byte of the reflected CRC-32 (zlib's, polynomial 0xEDB88320). +fn crc32_update(crc: u32, byte: u8) -> u32 { + let mut crc = crc ^ u32::from(byte); + for _ in 0..8 { + crc = (crc >> 1) ^ (0xedb8_8320 & (crc & 1).wrapping_neg()); + } + crc +} + +#[cfg(test)] +mod tests { + use super::*; + + fn crc32(data: &[u8]) -> u32 { + !data.iter().fold(!0, |crc, b| crc32_update(crc, *b)) + } + + #[test] + fn crc_is_zlibs() { + // The standard check value. + assert_eq!(crc32(b"123456789"), 0xcbf4_3926); + assert_eq!(bt_crc(b"123456789"), crc32(b"\xa2123456789")); + } + + #[test] + fn usb_report_layout() { + let out = Output { + rumble: Some([200, 40]), + right_trigger: Some([0x25, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), + lightbar: Some([255, 128, 0]), + player_leds: Some(0b00100), + ..Output::default() + }; + let r = out.usb(Vibration::V2); + assert_eq!(r.len(), 48); + assert_eq!(r[0], 0x02); + // Classic rumble and the right trigger in flags 0, lightbar and player LEDs in flags 1, + // the newer rumble emulation in flags 2. + assert_eq!(r[1], 0b0000_0110); + assert_eq!(r[2], 0b0001_0100); + // Right motor, then left. + assert_eq!(r[3..5], [40, 200]); + assert_eq!(r[11..22], [0x25, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); + // The left trigger is untouched. + assert_eq!(r[22..33], [0; 11]); + assert_eq!(r[39], FLAG2_VIBRATION_V2); + assert_eq!(r[44], 0b00100); + assert_eq!(r[45..48], [255, 128, 0]); + } + + #[test] + fn legacy_vibration_selects_haptics() { + let out = Output { + rumble: Some([1, 2]), + ..Output::default() + }; + let c = out.common(Vibration::Legacy); + assert_eq!(c[FLAGS0], FLAG0_COMPATIBLE_VIBRATION | FLAG0_HAPTICS_SELECT); + assert_eq!(c[FLAGS2], 0); + assert_eq!(Vibration::of_update_version(0x0223), Vibration::Legacy); + assert_eq!(Vibration::of_update_version(0x0641), Vibration::V2); + } + + #[test] + fn release_frees_both_triggers_and_stops_the_motors() { + let c = Output::release().common(Vibration::V2); + assert_eq!( + c[FLAGS0], + FLAG0_HAPTICS_SELECT | FLAG0_LEFT_TRIGGER | FLAG0_RIGHT_TRIGGER + ); + assert_eq!(c[MOTOR_LEFT..MOTOR_LEFT + 1], [0]); + assert_eq!(c[RIGHT_TRIGGER..RIGHT_TRIGGER + 11], TRIGGER_OFF); + assert_eq!(c[LEFT_TRIGGER..LEFT_TRIGGER + 11], TRIGGER_OFF); + // Nothing else changes. + assert_eq!(c[FLAGS1], 0); + } + + #[test] + fn release_leds_fades_the_firmware_light() { + let out = Output { + release_leds: true, + ..Output::default() + }; + let c = out.common(Vibration::V2); + assert_eq!(c[FLAGS1], FLAG1_RELEASE_LEDS); + assert_eq!(c[FLAGS2], FLAG2_LIGHTBAR_SETUP); + assert_eq!(c[LIGHTBAR_SETUP], LIGHTBAR_LIGHT_OUT); + } + + #[test] + fn bluetooth_report_layout() { + let out = Output { + lightbar: Some([1, 2, 3]), + ..Output::default() + }; + let r = out.bluetooth(Vibration::V2, 0x13); + assert_eq!(r.len(), 78); + assert_eq!(r[..3], [0x31, 0x30, 0x10]); + assert_eq!(r[3..50], out.common(Vibration::V2)); + assert_eq!(r[50..74], [0; 24]); + let crc = u32::from_le_bytes(r[74..].try_into().unwrap()); + assert_eq!(crc, crc32(&[&[0xa2], &r[..74]].concat())); + // The sequence number changes the CRC. + assert_ne!(out.bluetooth(Vibration::V2, 1)[74..], r[74..]); + } + + #[test] + fn dualsense_ids() { + assert!(is_dualsense(0x054c, 0x0ce6)); + assert!(is_dualsense(0x054c, 0x0df2)); + // A DualShock 4. + assert!(!is_dualsense(0x054c, 0x09cc)); + } +} diff --git a/docs/controllers.md b/docs/controllers.md index 6658c8fc9..04133fcdd 100644 --- a/docs/controllers.md +++ b/docs/controllers.md @@ -244,12 +244,68 @@ sensitivity, slower while scoping with a spyglass. ## Rumble -Vibration (on by default, off in the options) through gilrs force feedback: -taking damage (stronger with the damage), a block broken, an explosion nearby -(scaled by distance), a totem of undying, an elytra boost, a fish biting. -Short, low-intensity pulses, as on Bedrock. Linux (evdev force feedback, -including Steam Input's virtual pad) and Windows support it; macOS gilrs has -no force feedback, so it is silently skipped there. +Vibration (on by default, off in the options): taking damage (stronger with +the damage), a block broken, an explosion nearby (scaled by distance), a totem +of undying. Short, low-intensity pulses, as on Bedrock. A DualSense gets them +through its own output report (below), on every OS. Other pads go through +gilrs force feedback: Linux (evdev force feedback, including Steam Input's +virtual pad) and Windows support it; macOS gilrs has no force feedback, so it +is silently skipped there. + +## DualSense output + +Gilrs only reads the pads. A DualSense (054c:0ce6, the Edge 054c:0df2) is also +written to directly, over HID: the `horizon-dualsense` crate builds its output +report and [hidapi](https://crates.io/crates/hidapi) (MIT, bundling the C +hidapi under its BSD option) sends it: hidraw on Linux, IOKit on macOS (opened +shared, so gilrs keeps reading the same pad), the HID API on Windows. + +- **Report.** One 47-byte block carries everything: which parts to apply + (three flag bytes), the two compatible-vibration motors, both adaptive + triggers' effects, the lightbar colour and the player LEDs. Over USB it is + report 0x02; over Bluetooth report 0x31, led by a sequence number and a tag + and closed by a CRC-32 of the seed byte 0xA2 and the report. Firmware with + update version 0x0224 or later (feature report 0x20) takes the newer rumble + emulation flag. Unit tests check the bytes and the CRC. +- **Writer thread.** Writes block (a Bluetooth write can take milliseconds), + so a thread owns the pad: the game hands it the state to show and timed + vibrations, and it sends only what changed, and everything again when the + pad reconnects. It opens the pad once this window has the pad in hand (the + pad is active and the window has focus), and looks again whenever gilrs + sees a controller come or go. +- **Off-safe.** Quitting (and the thread ending any other way) frees the + triggers and stops the motors before the pad is closed. Another game on the + same pad is left alone: nothing is written while this window is unfocused. +- **Fallback.** If the pad can't be opened (Linux without access to its + hidraw node), vibration silently stays with gilrs, as before. +- **Linux access.** `/dev/hidraw*` is root-only by default. Steam's udev rules + (`60-steam-input.rules`, installed with Steam or the `steam-devices` + package) already give the logged-in user the DualSense, over USB and + Bluetooth. Without Steam, this rule does the same (the launcher could + install it): + + ``` + # /etc/udev/rules.d/70-horizon-dualsense.rules + KERNEL=="hidraw*", ATTRS{idVendor}=="054c", ATTRS{idProduct}=="0ce6|0df2", TAG+="uaccess" + KERNEL=="hidraw*", KERNELS=="*054C:0CE6*|*054C:0DF2*", TAG+="uaccess" + ``` + + The kernel's own `hid-playstation` driver keeps working alongside: its + reports set only the parts their flags name. +- **Trying it without the game:** `cargo run -p horizon-dualsense --example + dualsense -- all` plays each output on a connected pad and reads back what + the pad reports: the triggers' active effect, and the accelerometer's + shake while the motors run (`watch` logs the shake while the game drives + the pad). + +Byte layout from public references; no code is copied from them: the Linux +kernel's [`hid-playstation.c`](https://github.com/torvalds/linux/blob/master/drivers/hid/hid-playstation.c) +(report IDs and sizes, valid flags, motor, lightbar and player LED offsets, +the Bluetooth CRC, the firmware's vibration version), SDL's +[`SDL_hidapi_ps5.c`](https://github.com/libsdl-org/SDL/blob/main/src/joystick/hidapi/SDL_hidapi_ps5.c) +(the trigger effect blocks and the input report), and the +[dualsensectl](https://github.com/nowrep/dualsensectl) and DualSenseX +documentation. ## Steam Deck @@ -272,8 +328,9 @@ PRs #120, #129, #145 and #149. The second round, each shippable alone: menu styles, the on-screen keyboard. 2. **Button prompts**: contextual hints with the pad's glyphs in menus and optionally in game, and rebinding from them. -3. **DualSense output**: adaptive triggers, lightbar, player LEDs and richer - rumble over HID, off-safe. +3. **DualSense output** (above): the HID output layer and rumble through it + first, then adaptive triggers, shaped vibration and the lightbar and + player LEDs. 4. **Launcher**: the same focus navigation in the gpui launcher. Each is tested with unit tests (focus steps, prompt contexts, report bytes), From 6086758f94cf1ab813137800d02f773e2c7b1f7c Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 15 Oct 2026 18:32:06 +0200 Subject: [PATCH 2/2] DualSense output: rumble, LEDs and Bluetooth checked against SDL and the kernel - Every report carries the motors; still motors send no rumble flags, as SDL stops rumble (a report without them ends the emulation and re-arms the audio haptics), so a trigger change no longer cuts a vibration. - Legacy vibration at half strength (SDL); the Edge always takes V2; an unreadable firmware version falls back to legacy. - The first report after opening clears the motor/trigger attenuation (flags 1 bit 6, byte 36; dualsensectl, pydualsense). - The LED reset goes in a report of its own before any colour (hid-playstation's dualsense_reset_leds); over Bluetooth the colour waits for the connection animation (SDL's sensor clock check). - Bluetooth output only where gilrs keeps reading the pad (Linux), else with HORIZON_DUALSENSE_BT=1: any output switches the pad to its full report. - USB is preferred when the pad is on both. - Tests pin the reset report and its CRC (zlib), the flags and the clock offset. Co-Authored-By: Claude Opus 5.5 --- .../horizon-dualsense/examples/dualsense.rs | 4 +- crates/horizon-dualsense/src/device.rs | 150 ++++++++++++++++-- crates/horizon-dualsense/src/lib.rs | 124 +++++++++++---- docs/controllers.md | 56 +++++-- 4 files changed, 274 insertions(+), 60 deletions(-) diff --git a/crates/horizon-dualsense/examples/dualsense.rs b/crates/horizon-dualsense/examples/dualsense.rs index a6917b6fc..90d62ebef 100644 --- a/crates/horizon-dualsense/examples/dualsense.rs +++ b/crates/horizon-dualsense/examples/dualsense.rs @@ -144,7 +144,7 @@ fn rumble(pad: &mut DualSense) { write( pad, Output { - rumble: Some(motors), + rumble: motors, ..Output::default() }, ); @@ -153,7 +153,7 @@ fn rumble(pad: &mut DualSense) { write( pad, Output { - rumble: Some([0, 0]), + rumble: [0, 0], ..Output::default() }, ); diff --git a/crates/horizon-dualsense/src/device.rs b/crates/horizon-dualsense/src/device.rs index 3591a1598..2ed168292 100644 --- a/crates/horizon-dualsense/src/device.rs +++ b/crates/horizon-dualsense/src/device.rs @@ -3,7 +3,7 @@ use crate::{Output, TRIGGER_OFF, TriggerEffect, Vibration, is_dualsense}; use hidapi::{BusType, HidApi, HidDevice, HidResult}; use std::sync::Arc; -use std::sync::atomic::{AtomicU8, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU8, Ordering}; use std::sync::mpsc::{self, RecvTimeoutError, Sender}; use std::thread::JoinHandle; use std::time::{Duration, Instant}; @@ -23,13 +23,35 @@ pub struct DualSense { seq: u8, } +/// Whether a pad on Bluetooth may be written to. Any output report, and even reading a feature +/// report, switches it to its full input report (0x31) until it is turned off (SDL_hints.h, +/// `SDL_HINT_JOYSTICK_ENHANCED_REPORTS`; SDL_hidapi_ps5.c). Linux's `hid-playstation` has +/// already switched it and reads that report, but gilrs on macOS and Windows parses the simple +/// report 0x01 and would stop seeing the pad: there it waits for `HORIZON_DUALSENSE_BT=1`. +pub fn bluetooth_allowed() -> bool { + cfg!(target_os = "linux") || std::env::var_os("HORIZON_DUALSENSE_BT").is_some_and(|v| v == "1") +} + impl DualSense { - /// The first DualSense hidapi lists; `None` when there is none, an error when it can't be - /// opened (Linux without access to its hidraw node). + /// The first DualSense hidapi lists, USB before Bluetooth (as SDL); `None` when there is + /// none, an error when it can't be opened (Linux without access to its hidraw node). pub fn open(api: &HidApi) -> Option> { - let info = api + static SKIPPED: AtomicBool = AtomicBool::new(false); + let bluetooth = |d: &&hidapi::DeviceInfo| matches!(d.bus_type(), BusType::Bluetooth); + let pads = api .device_list() - .find(|d| is_dualsense(d.vendor_id(), d.product_id()))?; + .filter(|d| is_dualsense(d.vendor_id(), d.product_id())); + let (wireless, wired): (Vec<_>, Vec<_>) = pads.partition(bluetooth); + let info = match wired.first() { + Some(info) => info, + None if bluetooth_allowed() => wireless.first()?, + None => { + if !wireless.is_empty() && !SKIPPED.swap(true, Ordering::Relaxed) { + log::info!("Horizon: no DualSense output over Bluetooth on this system"); + } + return None; + } + }; let transport = match info.bus_type() { BusType::Bluetooth => Transport::Bluetooth, _ => Transport::Usb, @@ -37,14 +59,11 @@ impl DualSense { Some(info.open_device(api).map(|device| { let mut firmware = [0; 64]; firmware[0] = 0x20; - // The update version decides how vibration is asked for; without it, the kernel's - // default. - let vibration = match device.get_feature_report(&mut firmware) { - Ok(n) if n >= 46 => { - Vibration::of_update_version(u16::from_le_bytes([firmware[44], firmware[45]])) - } - _ => Vibration::Legacy, + let version = match device.get_feature_report(&mut firmware) { + Ok(n) if n >= 46 => Some(u16::from_le_bytes([firmware[44], firmware[45]])), + _ => None, }; + let vibration = Vibration::of(info.product_id(), version); DualSense { device, transport, @@ -182,6 +201,9 @@ struct Writer { state: State, /// What the pad was last sent; `None` after (re)opening. sent: Option<(State, [u8; 2])>, + /// Whether the lights may be set: over Bluetooth, not before the pad's connection + /// animation is over, or it paints over them. + lights: Lights, rumble: Rumble, /// When the vibration's current step ends. step_end: Option, @@ -189,6 +211,32 @@ struct Writer { next_scan: Instant, } +#[derive(Clone, Copy, Debug, PartialEq)] +enum Lights { + /// Over Bluetooth, until the pad's clock says its animation is over (or this long after + /// opening, when it sends no clock). + Waiting(Instant), + /// They may be set, after the reset report that hands them to the host. + Ready, + Reset, +} + +/// The pad's sensor clock once its Bluetooth connection animation is over (SDL_hidapi_ps5.c's +/// `HIDAPI_DriverPS5_CheckPendingLEDReset`). +const ANIMATION_OVER: u32 = 10_200_000; + +/// The sensor clock of a Bluetooth input report 0x31: its state block starts at byte 2 and +/// holds the clock at 27..31, little-endian (SDL's `PS5StatePacketCommon_t`, the kernel's +/// `dualsense_input_report`). +fn bluetooth_clock(report: &[u8]) -> Option { + match report { + [0x31, _, state @ ..] if state.len() >= 31 => { + Some(u32::from_le_bytes(state[27..31].try_into().ok()?)) + } + _ => None, + } +} + impl Writer { fn new(open: Arc) -> Self { Writer { @@ -197,6 +245,7 @@ impl Writer { open, state: State::default(), sent: None, + lights: Lights::Ready, rumble: Vec::new(), step_end: None, scans_left: 1, @@ -210,9 +259,11 @@ impl Writer { if self.pad.is_none() && self.scans_left > 0 && now >= self.next_scan { self.scan(); } + let waiting = matches!(self.lights, Lights::Waiting(_)) && self.pad.is_some(); let wake = [ self.step_end, (self.pad.is_none() && self.scans_left > 0).then_some(self.next_scan), + waiting.then(|| now + Duration::from_millis(250)), ] .into_iter() .flatten() @@ -247,6 +298,7 @@ impl Writer { Err(RecvTimeoutError::Timeout) => {} Err(RecvTimeoutError::Disconnected) => break, } + self.watch_animation(); self.advance_rumble(); self.flush(); } @@ -274,6 +326,12 @@ impl Writer { log::info!("DualSense output over {:?}", pad.transport()); self.open .store(1 + pad.transport() as u8, Ordering::Relaxed); + self.lights = match pad.transport() { + Transport::Usb => Lights::Ready, + Transport::Bluetooth => { + Lights::Waiting(Instant::now() + Duration::from_secs(1)) + } + }; self.pad = Some(pad); self.sent = None; self.scans_left = 0; @@ -288,6 +346,28 @@ impl Writer { } } + /// Over Bluetooth, read the pad's clock until its connection animation is over. + fn watch_animation(&mut self) { + let (Lights::Waiting(deadline), Some(pad)) = (self.lights, self.pad.as_ref()) else { + return; + }; + let mut buf = [0; 80]; + let mut clock = None; + while let Ok(n) = pad.read(&mut buf, 0) + && n > 0 + { + clock = bluetooth_clock(&buf[..n]).or(clock); + } + let over = match clock { + Some(clock) => clock >= ANIMATION_OVER, + // No full report to read the clock from: as SDL, take it as over. + None => Instant::now() >= deadline, + }; + if over { + self.lights = Lights::Ready; + } + } + /// Move to the vibration's next step once this one is over. fn advance_rumble(&mut self) { let now = Instant::now(); @@ -307,13 +387,36 @@ impl Writer { return; }; let motors = self.rumble.last().map_or([0, 0], |(m, _)| *m); - let (state, sent) = (self.state, self.sent); + let mut state = self.state; + if matches!(self.lights, Lights::Waiting(_)) { + state.lightbar = None; + state.player_leds = None; + } + let sent = self.sent; if sent == Some((state, motors)) { return; } + // Every report carries the motors: one without them stops the rumble. + let mut first = Output { + rumble: motors, + ..Output::default() + }; + if sent.is_none() { + first.full_power = true; + } + let lit = state.lightbar.is_some() || state.player_leds.is_some(); + if lit && self.lights == Lights::Ready { + first.release_leds = true; + self.lights = Lights::Reset; + } + // The reset goes alone, before any colour (hid-playstation.c). + if first.full_power || first.release_leds { + if let Err(e) = pad.write(&first) { + return self.lost(&e.to_string()); + } + } let mut out = Output { - rumble: (sent.is_none_or(|(_, m)| m != motors)).then_some(motors), - release_leds: sent.is_none() && state.lightbar.is_some(), + rumble: motors, ..Output::default() }; let old = sent.map(|(s, _)| s); @@ -339,3 +442,20 @@ impl Writer { self.open.store(0, Ordering::Relaxed); } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn bluetooth_clock_offset() { + let mut report = [0; 78]; + report[0] = 0x31; + report[2 + 27..2 + 31].copy_from_slice(&ANIMATION_OVER.to_le_bytes()); + assert_eq!(bluetooth_clock(&report), Some(10_200_000)); + // The simple report, or a USB one, has no clock here. + report[0] = 0x01; + assert_eq!(bluetooth_clock(&report), None); + assert_eq!(bluetooth_clock(&[0x31, 0, 0]), None); + } +} diff --git a/crates/horizon-dualsense/src/lib.rs b/crates/horizon-dualsense/src/lib.rs index 46d6627d1..dd4823b26 100644 --- a/crates/horizon-dualsense/src/lib.rs +++ b/crates/horizon-dualsense/src/lib.rs @@ -36,6 +36,9 @@ const MOTOR_RIGHT: usize = 2; const MOTOR_LEFT: usize = 3; const RIGHT_TRIGGER: usize = 10; const LEFT_TRIGGER: usize = 21; +/// `reduce_motor_power` (dualsensectl): the motors' attenuation in bits 0..2, the triggers' in +/// bits 4..6, 0 (none) to 7. +const ATTENUATION: usize = 36; const FLAGS2: usize = 38; const LIGHTBAR_SETUP: usize = 41; const PLAYER_LEDS: usize = 43; @@ -49,6 +52,7 @@ const FLAG0_LEFT_TRIGGER: u8 = 1 << 3; const FLAG1_LIGHTBAR: u8 = 1 << 2; const FLAG1_RELEASE_LEDS: u8 = 1 << 3; const FLAG1_PLAYER_LEDS: u8 = 1 << 4; +const FLAG1_ATTENUATION: u8 = 1 << 6; const FLAG2_LIGHTBAR_SETUP: u8 = 1 << 1; const FLAG2_VIBRATION_V2: u8 = 1 << 2; /// `lightbar_setup`: fade the firmware's own blue light out, so the host's colour shows. @@ -65,19 +69,27 @@ pub const TRIGGER_OFF: TriggerEffect = [0x05, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; #[derive(Clone, Copy, Debug, Default, PartialEq)] pub struct Output { /// The vibration motors, 0..255: the left (heavy, low) and the right (light, high) one. - pub rumble: Option<[u8; 2]>, + /// Every report carries them: one without the rumble flags ends the motors' emulation and + /// hands the actuators back to the audio haptics (SDL_hidapi_ps5.c: "Leaving emulated + /// rumble bits off will restore audio haptics"), so stopping sends no flags at all. + pub rumble: [u8; 2], pub left_trigger: Option, pub right_trigger: Option, /// Red, green, blue. pub lightbar: Option<[u8; 3]>, /// The five LEDs under the touchpad, left to right in bits 0..4. pub player_leds: Option, - /// Hand the lightbar to the host: the firmware's blue light fades out. + /// Hand the lightbar to the host: the firmware's blue light fades out. Sent alone, before + /// any colour (hid-playstation.c's `dualsense_reset_leds`). pub release_leds: bool, + /// Undo the motor and trigger attenuation another host (a PS5's intensity settings) left in + /// the pad, which would otherwise scale every effect down. + pub full_power: bool, } -/// How the pad takes vibration: firmware 2.24 and later has a better rumble emulation, picked -/// with its own flag (`hid-playstation.c`'s `use_vibration_v2`). +/// How the pad takes vibration: newer firmware has a better rumble emulation, picked with its +/// own flag (`hid-playstation.c`'s `use_vibration_v2`, SDL's `enhanced_rumble`); the legacy one +/// still works on every firmware. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum Vibration { Legacy, @@ -86,9 +98,12 @@ pub enum Vibration { } impl Vibration { - /// From the firmware's update version (feature report 0x20, bytes 44..46). - pub fn of_update_version(version: u16) -> Self { - if version >= 0x0224 { + /// From the product and the firmware's update version (feature report 0x20, bytes 44..46; + /// `None` when it can't be read). The Edge always has it. SDL picks it from 0x0224, the + /// kernel from 0x0215 (`DS_FEATURE_VERSION(2, 21)`): we take SDL's, as both agree from + /// there, and legacy below it and when the version is unknown, as it works everywhere. + pub fn of(product: u16, update_version: Option) -> Self { + if product == DUALSENSE_EDGE || update_version.is_some_and(|v| v >= 0x0224) { Vibration::V2 } else { Vibration::Legacy @@ -100,7 +115,7 @@ impl Output { /// Everything off: triggers free, motors still. pub fn release() -> Self { Output { - rumble: Some([0, 0]), + rumble: [0, 0], left_trigger: Some(TRIGGER_OFF), right_trigger: Some(TRIGGER_OFF), ..Output::default() @@ -110,16 +125,27 @@ impl Output { /// The block both transports carry. pub fn common(&self, vibration: Vibration) -> [u8; COMMON_LEN] { let mut c = [0; COMMON_LEN]; - if let Some([left, right]) = self.rumble { + if self.rumble != [0, 0] { // Classic rumble rather than the audio-driven haptics. c[FLAGS0] |= FLAG0_HAPTICS_SELECT; - match vibration { - Vibration::V2 => c[FLAGS2] |= FLAG2_VIBRATION_V2, - Vibration::Legacy => c[FLAGS0] |= FLAG0_COMPATIBLE_VIBRATION, - } + let [left, right] = match vibration { + Vibration::V2 => { + c[FLAGS2] |= FLAG2_VIBRATION_V2; + self.rumble + } + Vibration::Legacy => { + c[FLAGS0] |= FLAG0_COMPATIBLE_VIBRATION; + // The old emulation shakes about twice as hard: SDL halves it. + self.rumble.map(|m| m >> 1) + } + }; c[MOTOR_LEFT] = left; c[MOTOR_RIGHT] = right; } + if self.full_power { + c[FLAGS1] |= FLAG1_ATTENUATION; + c[ATTENUATION] = 0; + } if let Some(effect) = self.right_trigger { c[FLAGS0] |= FLAG0_RIGHT_TRIGGER; c[RIGHT_TRIGGER..RIGHT_TRIGGER + 11].copy_from_slice(&effect); @@ -201,7 +227,7 @@ mod tests { #[test] fn usb_report_layout() { let out = Output { - rumble: Some([200, 40]), + rumble: [200, 40], right_trigger: Some([0x25, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), lightbar: Some([255, 128, 0]), player_leds: Some(0b00100), @@ -225,42 +251,75 @@ mod tests { } #[test] - fn legacy_vibration_selects_haptics() { - let out = Output { - rumble: Some([1, 2]), + fn legacy_vibration() { + // SDL's pre-2.24 path: rumble emulation (0x01) and audio haptics off (0x02), the + // motors halved, nothing in flags 2. + let c = Output { + rumble: [200, 41], ..Output::default() - }; - let c = out.common(Vibration::Legacy); - assert_eq!(c[FLAGS0], FLAG0_COMPATIBLE_VIBRATION | FLAG0_HAPTICS_SELECT); + } + .common(Vibration::Legacy); + assert_eq!(c[FLAGS0], 0x03); + assert_eq!(c[MOTOR_RIGHT..=MOTOR_LEFT], [20, 100]); assert_eq!(c[FLAGS2], 0); - assert_eq!(Vibration::of_update_version(0x0223), Vibration::Legacy); - assert_eq!(Vibration::of_update_version(0x0641), Vibration::V2); + } + + #[test] + fn vibration_mode_of_the_firmware() { + assert_eq!(Vibration::of(DUALSENSE, Some(0x0223)), Vibration::Legacy); + assert_eq!(Vibration::of(DUALSENSE, Some(0x0224)), Vibration::V2); + assert_eq!(Vibration::of(DUALSENSE, Some(0x0641)), Vibration::V2); + assert_eq!(Vibration::of(DUALSENSE, None), Vibration::Legacy); + assert_eq!(Vibration::of(DUALSENSE_EDGE, None), Vibration::V2); + } + + #[test] + fn still_motors_send_no_rumble_flags() { + // The all-zero report, which also re-arms the audio haptics (nondebug/dualsense). + assert_eq!(Output::default().common(Vibration::V2), [0; COMMON_LEN]); + assert_eq!(Output::default().common(Vibration::Legacy), [0; COMMON_LEN]); } #[test] fn release_frees_both_triggers_and_stops_the_motors() { let c = Output::release().common(Vibration::V2); - assert_eq!( - c[FLAGS0], - FLAG0_HAPTICS_SELECT | FLAG0_LEFT_TRIGGER | FLAG0_RIGHT_TRIGGER - ); - assert_eq!(c[MOTOR_LEFT..MOTOR_LEFT + 1], [0]); + assert_eq!(c[FLAGS0], FLAG0_LEFT_TRIGGER | FLAG0_RIGHT_TRIGGER); + assert_eq!(c[FLAGS0], 0b1100); + assert_eq!(c[MOTOR_RIGHT..=MOTOR_LEFT], [0, 0]); assert_eq!(c[RIGHT_TRIGGER..RIGHT_TRIGGER + 11], TRIGGER_OFF); assert_eq!(c[LEFT_TRIGGER..LEFT_TRIGGER + 11], TRIGGER_OFF); // Nothing else changes. assert_eq!(c[FLAGS1], 0); + assert_eq!(c[FLAGS2], 0); } #[test] - fn release_leds_fades_the_firmware_light() { + fn full_power_clears_the_attenuation() { + let c = Output { + full_power: true, + ..Output::default() + } + .common(Vibration::V2); + // dualsensectl's VIBRATION_ATTENUATION_ENABLE and `reduce_motor_power`. + assert_eq!(c[FLAGS1], 0x40); + assert_eq!(c[36], 0); + } + + #[test] + fn release_leds_resets_the_lights() { + // hid-playstation.c's dualsense_reset_leds (lightbar setup: light out) and SDL's + // "Reset LED state" bit, over Bluetooth with sequence number 5; the CRC is + // zlib.crc32(b"\xa2" + report[:74]). + let mut expected = [0; BT_REPORT_LEN]; + expected[..5].copy_from_slice(&[0x31, 0x50, 0x10, 0x00, 0x08]); + expected[3 + 38] = 0x02; + expected[3 + 41] = 0x02; + expected[74..].copy_from_slice(&0xc72d_0f94u32.to_le_bytes()); let out = Output { release_leds: true, ..Output::default() }; - let c = out.common(Vibration::V2); - assert_eq!(c[FLAGS1], FLAG1_RELEASE_LEDS); - assert_eq!(c[FLAGS2], FLAG2_LIGHTBAR_SETUP); - assert_eq!(c[LIGHTBAR_SETUP], LIGHTBAR_LIGHT_OUT); + assert_eq!(out.bluetooth(Vibration::V2, 5), expected); } #[test] @@ -271,6 +330,7 @@ mod tests { }; let r = out.bluetooth(Vibration::V2, 0x13); assert_eq!(r.len(), 78); + // The sequence number in the high nibble, the tag 0x10 (hid-playstation.c). assert_eq!(r[..3], [0x31, 0x30, 0x10]); assert_eq!(r[3..50], out.common(Vibration::V2)); assert_eq!(r[50..74], [0; 24]); diff --git a/docs/controllers.md b/docs/controllers.md index 04133fcdd..8fd58274c 100644 --- a/docs/controllers.md +++ b/docs/controllers.md @@ -264,9 +264,34 @@ shared, so gilrs keeps reading the same pad), the HID API on Windows. (three flag bytes), the two compatible-vibration motors, both adaptive triggers' effects, the lightbar colour and the player LEDs. Over USB it is report 0x02; over Bluetooth report 0x31, led by a sequence number and a tag - and closed by a CRC-32 of the seed byte 0xA2 and the report. Firmware with - update version 0x0224 or later (feature report 0x20) takes the newer rumble - emulation flag. Unit tests check the bytes and the CRC. + and closed by a CRC-32 of the seed byte 0xA2 and the report. Unit tests pin + the bytes to the references below (the CRC to zlib's, the LED reset to the + kernel's). +- **Rumble.** Every report carries the motors: a report without the rumble + flags ends the motors' emulation and hands the actuators back to the audio + haptics (that is how SDL stops rumble, and how the HD haptics are re-armed), + so a trigger change mid-rumble would otherwise cut it. A pad with update + version 0x0224 or later (feature report 0x20), and every Edge, takes the + newer emulation (flags 2, bit 2); older or unknown firmware the legacy one + (flags 0, bit 0), at half strength as SDL does. The kernel takes the newer + one from 0x0215; between the two, legacy works on every firmware. The first + report after opening clears the motor and trigger attenuation another host + (a PS5's intensity settings) may have left (flags 1, bit 6, byte 36 = 0). +- **Lights.** Before the first colour, a report of its own resets the lights + (flags 1 bit 3, and the lightbar setup "light out"; the kernel does the + same). Over Bluetooth the pad plays a connection animation that paints over + the lightbar: like SDL, the colour waits until the pad's sensor clock + (input report 0x31) passes 10 200 000. +- **Bluetooth.** Any output report, even reading a feature report, switches a + pad on Bluetooth to its full input report (0x31) until it is turned off. On + Linux `hid-playstation` has done that already and gilrs reads its events, + so output goes ahead. Gilrs on macOS and Windows parses the simple report + 0x01 instead and would stop seeing the pad (SDL's + `SDL_HINT_JOYSTICK_ENHANCED_REPORTS`: "break Windows DirectInput for other + applications"), so there a pad on Bluetooth gets no output unless + `HORIZON_DUALSENSE_BT=1`. Doing it for everyone means reading the pad's + input ourselves over HID, as SDL does (a later PR). A pad on both cables is + written over USB. - **Writer thread.** Writes block (a Bluetooth write can take milliseconds), so a thread owns the pad: the game hands it the state to show and timed vibrations, and it sends only what changed, and everything again when the @@ -298,14 +323,23 @@ shared, so gilrs keeps reading the same pad), the HID API on Windows. shake while the motors run (`watch` logs the shake while the game drives the pad). -Byte layout from public references; no code is copied from them: the Linux -kernel's [`hid-playstation.c`](https://github.com/torvalds/linux/blob/master/drivers/hid/hid-playstation.c) -(report IDs and sizes, valid flags, motor, lightbar and player LED offsets, -the Bluetooth CRC, the firmware's vibration version), SDL's -[`SDL_hidapi_ps5.c`](https://github.com/libsdl-org/SDL/blob/main/src/joystick/hidapi/SDL_hidapi_ps5.c) -(the trigger effect blocks and the input report), and the -[dualsensectl](https://github.com/nowrep/dualsensectl) and DualSenseX -documentation. +Byte layout from public references, read for facts; no code is copied from +them (the kernel and dualsensectl are GPL): + +| Reference | Read at | What it settles | +| --- | --- | --- | +| SDL [`SDL_hidapi_ps5.c`](https://github.com/libsdl-org/SDL/blob/6defbc0129b5ba90bab3f6c67bbc1e9329e24ff1/src/joystick/hidapi/SDL_hidapi_ps5.c) and [`SDL_hints.h`](https://github.com/libsdl-org/SDL/blob/6defbc0129b5ba90bab3f6c67bbc1e9329e24ff1/include/SDL3/SDL_hints.h) (zlib) | `6defbc0` | the 47-byte block, rumble flags and stop, 0x0224, legacy at half, LED reset and the Bluetooth animation clock, USB report length 48, the enhanced-mode switch | +| Linux [`hid-playstation.c`](https://github.com/torvalds/linux/blob/045958acaa75205b31578cb22c4345e28dd2e4bf/drivers/hid/hid-playstation.c) (GPL) | `045958a` | valid flags, the Bluetooth sequence and tag 0x10, CRC seed 0xA2, `dualsense_reset_leds`, `use_vibration_v2` from 2.21, player LED patterns, the default blue | +| [dualsensectl](https://github.com/nowrep/dualsensectl/blob/d3ae2fa272e1bf9a5c08a0ded3f374b40f7c73ac/main.c) (GPL) | `d3ae2fa` | trigger valid bits (flags 0 bits 2, 3), `reduce_motor_power` (byte 36) and its flag, the trigger effect packing | +| [pydualsense](https://github.com/flok/pydualsense/blob/01445f5ed6ba/pydualsense/pydualsense.py) (MIT) | `01445f5` | sets the attenuation flag with 0 on every report | +| [nondebug/dualsense](https://github.com/nondebug/dualsense) | `b87450e` | an all-zero report 0x02 leaves rumble emulation for the audio haptics | + +Verified on hardware (USB, dualsense-1, Mac mini): the motors with the V2 +flags (the IMU shook, and settled after a stop that then still sent the +flags), the pad reporting a feedback and a weapon trigger effect as active, +and the writer thread. Verified against the references only: everything +else, the flag-less stop, the attenuation and LED reset reports, and all of +Bluetooth. ## Steam Deck