Repository navigation
feat(battery): read bluetooth mice through bluez #140
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
higorhgon
wants to merge
2
commits into
OpenMouse-Project:main
Choose a base branch
from
higorhgon:feat/bluetooth-battery
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| }); | ||
| 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]); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.