Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
309 changes: 309 additions & 0 deletions src/drivers/bluetooth.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,309 @@
//! Battery of Bluetooth LE mice that have no vendor HID channel, read from the
//! standard Battery Service the operating system already keeps.
//!
//! Mice with a vendor channel over Bluetooth (Logitech HID++, GearHub, …) are
//! read by their HID driver like any other. Some, like the 8BitDo Retro R8 in
//! Bluetooth mode, only expose the standard HID and Battery services, so no
//! driver can reach them; the system still knows their charge.
//!
//! Linux reads BlueZ's `org.bluez.Battery1`. Other platforms list nothing yet.

use super::{DetectedMouse, NativeBattery, NativeStatus};
use anyhow::Result;

/// Device id prefix: `Bluetooth:<address>`.
pub(crate) const BRAND: &str = "Bluetooth";

/// A connected Bluetooth device as the system reports it. Only the BlueZ
/// reader builds one, so it is unused off Linux until a platform reader lands.
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
#[derive(Clone, Debug, Default, PartialEq, Eq)]
struct SystemDevice {
address: String,
name: String,
/// The freedesktop icon name BlueZ derives from the device's appearance.
icon: Option<String>,
connected: bool,
/// `bluetooth:v2DC8p5205d0000` (or `usb:…`): vendor and product ids.
modalias: Option<String>,
battery_percent: Option<u8>,
}

/// A battery-only Bluetooth mouse, listed by discovery.
#[derive(Clone, Debug, PartialEq, Eq)]
struct BatteryMouse {
device: DetectedMouse,
percent: u8,
}

fn device_id(address: &str) -> String {
format!("{BRAND}:{address}")
}

/// `(vendor id, product id)` from a modalias such as `bluetooth:v2DC8p5205d0000`.
fn parse_modalias(modalias: &str) -> Option<(u16, u16)> {
let (_, ids) = modalias.split_once(':')?;
let ids = ids.strip_prefix('v')?;
let (vendor, rest) = ids.split_once('p')?;
let product = rest.get(..4)?;
Some((
u16::from_str_radix(vendor, 16).ok()?,
u16::from_str_radix(product, 16).ok()?,
))
}

/// The connected mice that report a battery level.
fn battery_mice(devices: &[SystemDevice]) -> Vec<BatteryMouse> {
devices
.iter()
.filter(|device| device.connected && device.icon.as_deref() == Some("input-mouse"))
.filter_map(|device| {
let percent = device.battery_percent?.min(100);
let (vendor_id, product_id) = device
.modalias
.as_deref()
.and_then(parse_modalias)
.unwrap_or_default();
Some(BatteryMouse {
device: DetectedMouse {
device_id: device_id(&device.address),
name: device.name.clone(),
vendor_id,
product_id,
},
percent,
})
})
.collect()
}

/// Adds the Bluetooth mice only the system can read to `mice`. A mouse the HID
/// scan already found under the same vendor and product id is left to its
/// driver, so it is not listed twice.
pub(super) fn add_battery_only_mice(mice: &mut Vec<DetectedMouse>) {
merge_battery_mice(mice, battery_mice(&system_devices()));
}

fn merge_battery_mice(mice: &mut Vec<DetectedMouse>, battery: Vec<BatteryMouse>) {
// Only the HID scan's mice have a driver: two Bluetooth mice of the same
// model must not hide each other.
let hid_count = mice.len();
for mouse in battery {
let has_driver = mouse.device.vendor_id != 0
&& mice[..hid_count].iter().any(|found| {
found.vendor_id == mouse.device.vendor_id
&& found.product_id == mouse.device.product_id
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
if !has_driver
&& !mice
.iter()
.any(|found| found.device_id == mouse.device.device_id)
{
mice.push(mouse.device);
}
}
}

/// The battery of the Bluetooth mouse `device_id` names, `None` when it is no
/// longer connected or reports no battery. The system has no charging state
/// for it, so it always reads as discharging.
pub(super) fn read_status(device_id: &str) -> Result<Option<NativeStatus>> {
let status = battery_mice(&system_devices())
.into_iter()
.find(|mouse| mouse.device.device_id == device_id)
.map(|mouse| NativeStatus {
battery: NativeBattery {
percent: mouse.percent,
charging: false,
reported_name: None,
},
dpi: None,
polling_rate_hz: None,
switch_mode: None,
});
Ok(status)
}

#[cfg(target_os = "linux")]
fn system_devices() -> Vec<SystemDevice> {
match bluez::devices() {
Ok(devices) => devices,
Err(error) => {
// No system bus or no BlueZ: there is simply nothing to list.
tracing::debug!(%error, "Could not list Bluetooth devices from BlueZ");
Vec::new()
}
}
}

#[cfg(not(target_os = "linux"))]
fn system_devices() -> Vec<SystemDevice> {
Vec::new()
}

#[cfg(target_os = "linux")]
mod bluez {
use super::SystemDevice;
use anyhow::Result;
use std::{
collections::HashMap,
sync::{Mutex, PoisonError},
};
use zbus::{
blocking::{Connection, fdo::ObjectManagerProxy},
zvariant::OwnedValue,
};

const DEVICE: &str = "org.bluez.Device1";
const BATTERY: &str = "org.bluez.Battery1";

/// One system-bus connection, reused while it works; discovery asks every
/// few seconds. A failed call drops it so the next one reconnects.
static CONNECTION: Mutex<Option<Connection>> = Mutex::new(None);

fn connection() -> Result<Connection> {
let mut cached = CONNECTION.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(connection) = cached.as_ref() {
return Ok(connection.clone());
}
let connection = Connection::system()?;
*cached = Some(connection.clone());
Ok(connection)
}

pub(super) fn devices() -> Result<Vec<SystemDevice>> {
let devices = read_devices(&connection()?);
if devices.is_err() {
*CONNECTION.lock().unwrap_or_else(PoisonError::into_inner) = None;
}
devices
}

fn read_devices(connection: &Connection) -> Result<Vec<SystemDevice>> {
let manager = ObjectManagerProxy::builder(connection)
.destination("org.bluez")?
.path("/")?
.build()?;
let objects = manager.get_managed_objects()?;
Ok(objects
.values()
.filter_map(|interfaces| {
let device = interfaces
.iter()
.find(|(name, _)| name.as_str() == DEVICE)?
.1;
let battery = interfaces
.iter()
.find(|(name, _)| name.as_str() == BATTERY)
.map(|(_, properties)| properties);
Some(SystemDevice {
address: string(device, "Address")?,
name: string(device, "Alias")
.or_else(|| string(device, "Name"))
.unwrap_or_default(),
icon: string(device, "Icon"),
connected: device
.get("Connected")
.and_then(|value| value.downcast_ref::<bool>().ok())
.unwrap_or(false),
modalias: string(device, "Modalias"),
battery_percent: battery
.and_then(|properties| properties.get("Percentage"))
.and_then(|value| value.downcast_ref::<u8>().ok()),
})
})
.collect())
}

fn string(properties: &HashMap<String, OwnedValue>, key: &str) -> Option<String> {
properties
.get(key)
.and_then(|value| value.downcast_ref::<&str>().ok())
.map(str::to_owned)
}
}

#[cfg(test)]
mod tests {
use super::*;

fn r8(connected: bool, battery_percent: Option<u8>) -> SystemDevice {
SystemDevice {
address: "E4:17:D8:02:8C:85".into(),
name: "8BitDo Retro R8 Mouse".into(),
icon: Some("input-mouse".into()),
connected,
modalias: Some("bluetooth:v2DC8p5205d0000".into()),
battery_percent,
}
}

#[test]
fn reads_vendor_and_product_from_the_modalias() {
assert_eq!(
parse_modalias("bluetooth:v2DC8p5205d0000"),
Some((0x2dc8, 0x5205))
);
assert_eq!(
parse_modalias("usb:v046DpB023d0001"),
Some((0x046d, 0xb023))
);
assert_eq!(
parse_modalias("bluetooth:v05D6p000A"),
Some((0x05d6, 0x000a))
);
assert_eq!(parse_modalias("bluetooth:xyz"), None);
}

#[test]
fn lists_connected_mice_with_a_battery() {
let headset = SystemDevice {
icon: Some("audio-headset".into()),
..r8(true, Some(70))
};
let mice = battery_mice(&[r8(true, Some(75)), headset]);
assert_eq!(
mice,
vec![BatteryMouse {
device: DetectedMouse {
device_id: "Bluetooth:E4:17:D8:02:8C:85".into(),
name: "8BitDo Retro R8 Mouse".into(),
vendor_id: 0x2dc8,
product_id: 0x5205,
},
percent: 75,
}]
);
// Not connected, or no battery level: nothing to show.
assert!(battery_mice(&[r8(false, Some(75))]).is_empty());
assert!(battery_mice(&[r8(true, None)]).is_empty());
}

#[test]
fn two_mice_of_one_model_are_both_listed_unless_a_driver_has_it() {
let mouse = |address: &str| BatteryMouse {
device: DetectedMouse {
device_id: device_id(address),
name: "8BitDo Retro R8 Mouse".into(),
vendor_id: 0x2dc8,
product_id: 0x5205,
},
percent: 75,
};
let mut mice = Vec::new();
merge_battery_mice(&mut mice, vec![mouse("AA"), mouse("BB"), mouse("AA")]);
let ids: Vec<_> = mice.iter().map(|m| m.device_id.as_str()).collect();
assert_eq!(ids, ["Bluetooth:AA", "Bluetooth:BB"]);

// The HID scan found that model: its driver reads it instead.
let hid = DetectedMouse {
device_id: "8BitDo:2dc85205".into(),
name: "8BitDo Retro R8 Mouse".into(),
vendor_id: 0x2dc8,
product_id: 0x5205,
};
let mut mice = vec![hid.clone()];
merge_battery_mice(&mut mice, vec![mouse("AA"), mouse("BB")]);
assert_eq!(mice, vec![hid]);
}
}
26 changes: 19 additions & 7 deletions src/drivers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ use anyhow::Result;
use crate::config::ApplicationProfile;

pub(crate) mod automation;
mod bluetooth;

/// A native automation error with the parts that only mean Bridge has no driver
/// for a mouse removed, or `None` if that was all it said.
Expand All @@ -31,6 +32,7 @@ mod native_hid;
pub mod pulsar;
mod registry;

pub(crate) use bluetooth::BRAND as BLUETOOTH_BRAND;
pub use native_hid::{NativeBattery, NativeStatus, spawn_button_listener};

/// A mouse Bridge discovered by itself, by scanning the HID bus for vendor
Expand Down Expand Up @@ -154,14 +156,20 @@ fn discovered_brand(info: &hidapi::DeviceInfo) -> Option<&'static str> {
/// device when it cannot be reached (no Node.js), come from Bridge's
/// vendor-id table.
pub fn detect_mice() -> Vec<DetectedMouse> {
let Some(devices) = registry::devices() else {
return detect_by_vendor();
let mut mice = match registry::devices() {
Some(devices) => {
let mut mice = mice_from_registry(devices);
// Discovery is additive: a mouse the registry does not claim (or
// whose descriptors could not be read) is still listed by vendor
// id, so it never vanishes from Bridge. Its battery read just
// fails softly.
backfill(&mut mice, detect_by_vendor());
mice
}
None => detect_by_vendor(),
};
let mut mice = mice_from_registry(devices);
// Discovery is additive: a mouse the registry does not claim (or whose
// descriptors could not be read) is still listed by vendor id, so it
// never vanishes from Bridge. Its battery read just fails softly.
backfill(&mut mice, detect_by_vendor());
// Bluetooth mice no HID driver reaches, whose battery the system reads.
bluetooth::add_battery_only_mice(&mut mice);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
mice
}

Expand Down Expand Up @@ -470,6 +478,10 @@ fn write_settings_held(
/// (e.g. asleep or disconnected).
pub fn read_status(device_id: &str) -> Result<Option<NativeStatus>> {
let brand = device_id.split(':').next().unwrap_or_default();
// Read from the system's Bluetooth stack, not the HID bus.
if brand.eq_ignore_ascii_case(bluetooth::BRAND) {
return bluetooth::read_status(device_id);
}
let _access = device_access_within(DEVICE_ACCESS_WAIT)?;
ensure_native_ownership()?;
if brand.eq_ignore_ascii_case(pulsar::BRAND) {
Expand Down
Loading