Skip to main content

webbluetooth_linux/bluez/
mod.rs

1//! The BlueZ object model.
2//!
3//! BlueZ publishes the whole Bluetooth world as a D-Bus object tree and expects
4//! clients to track it through `ObjectManager`:
5//!
6//! ```text
7//!   /org/bluez                                        org.bluez.AgentManager1
8//!   /org/bluez/hci0                                   org.bluez.Adapter1
9//!                                                     org.bluez.LEAdvertisingManager1
10//!                                                     org.bluez.GattManager1
11//!   /org/bluez/hci0/dev_AA_BB_CC_DD_EE_FF             org.bluez.Device1
12//!   …/dev_AA_BB_CC_DD_EE_FF/service0010               org.bluez.GattService1
13//!   …/service0010/char0011                            org.bluez.GattCharacteristic1
14//!   …/char0011/desc0013                               org.bluez.GattDescriptor1
15//! ```
16//!
17//! So an object *path* is the handle, and the hierarchy is encoded in it: a
18//! characteristic's service is its parent path. That is the opposite of
19//! CoreBluetooth, where handles are opaque pointers and the tree is walked by
20//! asking. It is also why this layer keeps a cached mirror of the tree — every
21//! lookup would otherwise be a round trip.
22//!
23//! # Where this differs from CoreBluetooth
24//!
25//! * **Discovery is not a request/reply.** `StartDiscovery` returns immediately
26//!   and devices appear as `InterfacesAdded` signals. Same as CoreBluetooth.
27//! * **GATT reads are.** `ReadValue` returns the bytes in its method reply, so
28//!   there is no read-versus-notification ambiguity to resolve — the problem
29//!   [`crate::dbus`]'s Apple counterpart needs a FIFO for does not exist here.
30//! * **Notifications are property changes.** `StartNotify` then
31//!   `PropertiesChanged` on `Value`.
32//! * **Services are not discovered explicitly.** Connecting resolves them and
33//!   sets `ServicesResolved`; the objects simply appear in the tree.
34
35use crate::dbus::connection::{Error as DbusError, ObjectHandler};
36use crate::dbus::{Connection, Message, Value};
37use std::collections::HashMap;
38use std::sync::{Arc, Mutex};
39use std::time::Duration;
40
41pub mod interfaces {
42    pub const OBJECT_MANAGER: &str = "org.freedesktop.DBus.ObjectManager";
43    pub const PROPERTIES: &str = "org.freedesktop.DBus.Properties";
44    pub const ADAPTER: &str = "org.bluez.Adapter1";
45    pub const DEVICE: &str = "org.bluez.Device1";
46    pub const SERVICE: &str = "org.bluez.GattService1";
47    pub const CHARACTERISTIC: &str = "org.bluez.GattCharacteristic1";
48    pub const DESCRIPTOR: &str = "org.bluez.GattDescriptor1";
49    pub const GATT_MANAGER: &str = "org.bluez.GattManager1";
50    pub const LE_ADVERTISING_MANAGER: &str = "org.bluez.LEAdvertisingManager1";
51    pub const LE_ADVERTISEMENT: &str = "org.bluez.LEAdvertisement1";
52    pub const PROFILE_MANAGER: &str = "org.bluez.ProfileManager1";
53    pub const PROFILE: &str = "org.bluez.Profile1";
54}
55
56pub const SERVICE_NAME: &str = "org.bluez";
57const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
58
59pub type Result<T> = std::result::Result<T, DbusError>;
60
61/// A D-Bus object path — the Linux equivalent of a CoreBluetooth handle.
62///
63/// Cheap to clone and hash, and unlike a pointer it stays meaningful across a
64/// disconnect, which is why the layer above still needs a generation counter to
65/// know when a path has gone stale.
66pub type Path = Arc<str>;
67
68pub fn path(s: &str) -> Path {
69    Arc::from(s)
70}
71
72/// One object in BlueZ's tree: its interfaces and their properties.
73#[derive(Debug, Clone, Default)]
74pub struct Object {
75    pub interfaces: HashMap<String, HashMap<String, Value>>,
76}
77
78impl Object {
79    pub fn has(&self, interface: &str) -> bool {
80        self.interfaces.contains_key(interface)
81    }
82
83    pub fn property(&self, interface: &str, name: &str) -> Option<&Value> {
84        self.interfaces.get(interface)?.get(name)
85    }
86
87    pub fn string(&self, interface: &str, name: &str) -> Option<String> {
88        self.property(interface, name)?.as_str().map(str::to_owned)
89    }
90
91    pub fn bool(&self, interface: &str, name: &str) -> Option<bool> {
92        self.property(interface, name)?.as_bool()
93    }
94
95    pub fn int(&self, interface: &str, name: &str) -> Option<i64> {
96        self.property(interface, name)?.as_i64()
97    }
98}
99
100/// What the tree tells us happened.
101#[derive(Debug, Clone)]
102pub enum Event {
103    /// The adapter's `Powered` changed, or it appeared/vanished.
104    AdapterChanged { powered: bool, present: bool },
105    /// A device object appeared, or re-advertised with new properties.
106    DeviceSeen {
107        path: Path,
108        properties: HashMap<String, Value>,
109    },
110    /// A device object vanished — BlueZ removes stale ones after a scan.
111    DeviceRemoved { path: Path },
112    /// `Connected` became true.
113    Connected { path: Path },
114    /// `Connected` became false.
115    Disconnected { path: Path },
116    /// `ServicesResolved` became true: the GATT tree is now populated.
117    ServicesResolved { path: Path },
118    /// A characteristic's `Value` changed — a notification or indication.
119    CharacteristicValue { path: Path, value: Vec<u8> },
120    /// A `GattService1` object appeared under or vanished from a device.
121    ///
122    /// This is the tree's account of the Service Changed indication. BlueZ
123    /// subscribes to that characteristic itself and re-discovers, so what
124    /// reaches us is the result rather than the indication: services arriving
125    /// and leaving under the device's path. `path` is the device, not the
126    /// service.
127    ServicesChanged { path: Path },
128    /// The whole bus went away.
129    Disconnected_,
130}
131
132/// Where tree changes are delivered. Called on the D-Bus reader thread.
133pub trait EventSink: Send + Sync {
134    fn emit(&self, event: Event);
135}
136
137/// A connection to BlueZ, with a cached mirror of its object tree.
138pub struct Bluez {
139    connection: Arc<Connection>,
140    tree: Arc<Mutex<HashMap<String, Object>>>,
141    adapter: Mutex<Option<String>>,
142    /// Held so the signal handler's clone is not the only reference.
143    _sink: Arc<dyn EventSink>,
144}
145
146impl Bluez {
147    /// Connect to the system bus, subscribe to the tree, and load it.
148    pub fn new(sink: Arc<dyn EventSink>) -> Result<Self> {
149        let connection = Arc::new(Connection::system()?);
150        let tree = Arc::new(Mutex::new(HashMap::new()));
151
152        let bluez = Self {
153            connection: connection.clone(),
154            tree: tree.clone(),
155            adapter: Mutex::new(None),
156            _sink: sink.clone(),
157        };
158
159        // Subscribe *before* the initial load, so nothing that happens during
160        // it is missed. Duplicate events are harmless; a lost one is not.
161        let handler_tree = tree.clone();
162        let handler_sink = sink.clone();
163        connection.add_match(
164            "type='signal',sender='org.bluez'",
165            Arc::new(move |m: &Message| {
166                on_signal(&handler_tree, &handler_sink, m);
167            }),
168        )?;
169
170        bluez.reload()?;
171        Ok(bluez)
172    }
173
174    /// The underlying bus, for the peripheral role's object exports.
175    pub fn connection(&self) -> &Arc<Connection> {
176        &self.connection
177    }
178
179    /// Re-read the whole tree with `GetManagedObjects`.
180    pub fn reload(&self) -> Result<()> {
181        let reply = self.connection.call_blocking(
182            Message::call(
183                SERVICE_NAME,
184                "/",
185                interfaces::OBJECT_MANAGER,
186                "GetManagedObjects",
187            ),
188            DEFAULT_TIMEOUT,
189        )?;
190
191        let mut tree = HashMap::new();
192        if let Some(objects) = reply.arg(0) {
193            for (object_path, interfaces) in objects.as_map() {
194                tree.insert(
195                    object_path,
196                    Object {
197                        interfaces: to_interfaces(&interfaces),
198                    },
199                );
200            }
201        }
202        *self.tree.lock().unwrap() = tree;
203
204        // Keep whichever adapter was chosen, if it is still there. Re-reading
205        // the tree must not silently move an established session to a
206        // different controller.
207        let adapters = self.adapters();
208        let current = self.adapter.lock().unwrap().clone();
209        let keep = current.filter(|c| adapters.contains(c));
210
211        *self.adapter.lock().unwrap() = keep.or_else(|| {
212            // `WEBBLUETOOTH_ADAPTER` names one explicitly — "hci1" or a full
213            // object path — which is how a machine with several controllers
214            // picks, and how a two-adapter test puts each end on its own.
215            if let Ok(want) = std::env::var("WEBBLUETOOTH_ADAPTER") {
216                let wanted = Self::adapter_path(&want);
217                if let Some(found) = adapters.iter().find(|p| **p == wanted) {
218                    return Some(found.clone());
219                }
220            }
221            // Otherwise the first, which sorts to hci0 — what every other tool
222            // defaults to.
223            adapters.into_iter().next()
224        });
225        Ok(())
226    }
227
228    /// `hci1` or `/org/bluez/hci1` both name the same adapter.
229    fn adapter_path(name: &str) -> String {
230        if name.starts_with('/') {
231            name.to_owned()
232        } else {
233            format!("/org/bluez/{name}")
234        }
235    }
236
237    /// Every adapter BlueZ is managing, sorted, so `hci0` comes first.
238    pub fn adapters(&self) -> Vec<String> {
239        let mut adapters: Vec<String> = self
240            .tree
241            .lock()
242            .unwrap()
243            .iter()
244            .filter(|(_, o)| o.has(interfaces::ADAPTER))
245            .map(|(p, _)| p.clone())
246            .collect();
247        adapters.sort();
248        adapters
249    }
250
251    /// Use a named adapter for everything from here on.
252    ///
253    /// Takes `hci1` or a full object path. Fails if BlueZ is not managing it,
254    /// rather than silently carrying on with a different one.
255    pub fn select_adapter(&self, name: &str) -> Result<()> {
256        let wanted = Self::adapter_path(name);
257        let adapters = self.adapters();
258        if !adapters.contains(&wanted) {
259            return Err(DbusError::Call {
260                name: "org.bluez.Error.NoAdapter".into(),
261                message: format!("no adapter at {wanted}; BlueZ has {}", adapters.join(", ")),
262            });
263        }
264        *self.adapter.lock().unwrap() = Some(wanted);
265        Ok(())
266    }
267
268    /// The local adapter's own Bluetooth address, as BlueZ reports it.
269    pub fn adapter_address(&self) -> Option<String> {
270        let adapter = self.adapter()?;
271        self.object(&adapter)?
272            .string(interfaces::ADAPTER, "Address")
273    }
274
275    /// The adapter object path, if one exists.
276    pub fn adapter(&self) -> Option<String> {
277        self.adapter.lock().unwrap().clone()
278    }
279
280    /// Whether an adapter exists and is powered.
281    pub fn is_powered(&self) -> bool {
282        let Some(adapter) = self.adapter() else {
283            return false;
284        };
285        self.object(&adapter)
286            .and_then(|o| o.bool(interfaces::ADAPTER, "Powered"))
287            .unwrap_or(false)
288    }
289
290    /// Turn the adapter on.
291    pub fn set_powered(&self, on: bool) -> Result<()> {
292        let Some(adapter) = self.adapter() else {
293            return Err(DbusError::Call {
294                name: "org.bluez.Error.NoAdapter".into(),
295                message: "no Bluetooth adapter present".into(),
296            });
297        };
298        self.set_property(&adapter, interfaces::ADAPTER, "Powered", Value::Bool(on))
299    }
300
301    /// A snapshot of one object.
302    pub fn object(&self, path: &str) -> Option<Object> {
303        self.tree.lock().unwrap().get(path).cloned()
304    }
305
306    /// Every object path carrying `interface`.
307    pub fn paths_with(&self, interface: &str) -> Vec<String> {
308        let mut out: Vec<String> = self
309            .tree
310            .lock()
311            .unwrap()
312            .iter()
313            .filter(|(_, o)| o.has(interface))
314            .map(|(p, _)| p.clone())
315            .collect();
316        out.sort();
317        out
318    }
319
320    /// Children of `parent` carrying `interface` — how the GATT tree is walked,
321    /// since BlueZ encodes the hierarchy in the path.
322    pub fn children_with(&self, parent: &str, interface: &str) -> Vec<String> {
323        let prefix = format!("{parent}/");
324        let mut out: Vec<String> = self
325            .tree
326            .lock()
327            .unwrap()
328            .iter()
329            .filter(|(p, o)| p.starts_with(&prefix) && o.has(interface))
330            .map(|(p, _)| p.clone())
331            .collect();
332        out.sort();
333        out
334    }
335
336    /// Read a property live, bypassing the cache.
337    pub fn get_property(&self, path: &str, interface: &str, name: &str) -> Result<Value> {
338        let reply = self.connection.call_blocking(
339            Message::call(SERVICE_NAME, path, interfaces::PROPERTIES, "Get")
340                .with_body(vec![Value::Str(interface.into()), Value::Str(name.into())]),
341            DEFAULT_TIMEOUT,
342        )?;
343        Ok(reply.arg(0).cloned().unwrap_or(Value::Byte(0)))
344    }
345
346    /// Write a property.
347    pub fn set_property(
348        &self,
349        path: &str,
350        interface: &str,
351        name: &str,
352        value: Value,
353    ) -> Result<()> {
354        self.connection.call_blocking(
355            Message::call(SERVICE_NAME, path, interfaces::PROPERTIES, "Set").with_body(vec![
356                Value::Str(interface.into()),
357                Value::Str(name.into()),
358                Value::Variant(Box::new(value)),
359            ]),
360            DEFAULT_TIMEOUT,
361        )?;
362        Ok(())
363    }
364
365    /// Call a BlueZ method, delivering the reply to a callback.
366    ///
367    /// Callback-based rather than blocking, so the async layer can wrap it
368    /// without a thread per request — the same shape as the Apple backend.
369    pub fn call_async(
370        &self,
371        path: &str,
372        interface: &str,
373        member: &str,
374        args: Vec<Value>,
375        then: impl FnOnce(Result<Message>) + Send + 'static,
376    ) {
377        self.connection.call_async(
378            Message::call(SERVICE_NAME, path, interface, member).with_body(args),
379            Box::new(then),
380        );
381    }
382
383    /// As [`Bluez::call_async`], keeping any descriptors the reply carried.
384    ///
385    /// For `AcquireWrite` and `AcquireNotify`, whose answer is a socket. The
386    /// body holds only an index; the descriptor travelled beside the message.
387    pub fn call_async_with_fds(
388        &self,
389        path: &str,
390        interface: &str,
391        member: &str,
392        args: Vec<Value>,
393        then: impl FnOnce(Result<(Vec<Value>, Vec<std::os::fd::RawFd>)>) + Send + 'static,
394    ) {
395        let connection = self.connection.clone();
396        self.connection.call_async(
397            Message::call(SERVICE_NAME, path, interface, member).with_body(args),
398            Box::new(move |reply| {
399                then(reply.map(|m| {
400                    // Claimed by the serial the reply answers, which is what
401                    // the reader filed them under.
402                    let fds = m
403                        .reply_serial
404                        .map(|s| connection.take_fds(s))
405                        .unwrap_or_default();
406                    (m.body.clone(), fds)
407                }))
408            }),
409        );
410    }
411
412    /// Call a BlueZ method and wait.
413    pub fn call(
414        &self,
415        path: &str,
416        interface: &str,
417        member: &str,
418        args: Vec<Value>,
419    ) -> Result<Message> {
420        self.connection.call_blocking(
421            Message::call(SERVICE_NAME, path, interface, member).with_body(args),
422            DEFAULT_TIMEOUT,
423        )
424    }
425
426    /// Export an object so BlueZ can call into it — the peripheral role.
427    pub fn export(&self, path: &str, handler: Arc<dyn ObjectHandler>) {
428        self.connection.export(path, handler);
429    }
430}
431
432/// Convert an `a{sa{sv}}` interfaces dictionary into a plain map.
433fn to_interfaces(value: &Value) -> HashMap<String, HashMap<String, Value>> {
434    value
435        .as_map()
436        .into_iter()
437        .map(|(name, props)| (name, props.as_map()))
438        .collect()
439}
440
441/// The device object path a GATT service hangs off.
442///
443/// BlueZ nests the tree in the path itself — a service is
444/// `/org/bluez/hci0/dev_AA_BB_CC_DD_EE_FF/service001c` — so the owner is the
445/// parent. Returns `None` for a path with no parent rather than guessing.
446fn device_of(service_path: &str) -> Option<&str> {
447    let (device, _) = service_path.rsplit_once('/')?;
448    (!device.is_empty()).then_some(device)
449}
450
451/// Apply a signal to the cached tree and tell the sink what changed.
452fn on_signal(
453    tree: &Arc<Mutex<HashMap<String, Object>>>,
454    sink: &Arc<dyn EventSink>,
455    message: &Message,
456) {
457    match (message.interface.as_deref(), message.member.as_deref()) {
458        (Some(interfaces::OBJECT_MANAGER), Some("InterfacesAdded")) => {
459            let (Some(object_path), Some(interfaces)) = (
460                message.arg(0).and_then(Value::as_str).map(str::to_owned),
461                message.arg(1),
462            ) else {
463                return;
464            };
465            let added = to_interfaces(interfaces);
466            {
467                let mut tree = tree.lock().unwrap();
468                let entry = tree.entry(object_path.clone()).or_default();
469                for (name, props) in &added {
470                    entry.interfaces.insert(name.clone(), props.clone());
471                }
472            }
473            if let Some(props) = added.get(interfaces::DEVICE) {
474                sink.emit(Event::DeviceSeen {
475                    path: path(&object_path),
476                    properties: props.clone(),
477                });
478            }
479            if added.contains_key(interfaces::SERVICE) {
480                if let Some(device) = device_of(&object_path) {
481                    sink.emit(Event::ServicesChanged { path: path(device) });
482                }
483            }
484        }
485
486        (Some(interfaces::OBJECT_MANAGER), Some("InterfacesRemoved")) => {
487            let (Some(object_path), Some(removed)) = (
488                message.arg(0).and_then(Value::as_str).map(str::to_owned),
489                message.arg(1),
490            ) else {
491                return;
492            };
493            let names = removed.as_strings();
494            let now_empty = {
495                let mut tree = tree.lock().unwrap();
496                if let Some(entry) = tree.get_mut(&object_path) {
497                    for n in &names {
498                        entry.interfaces.remove(n);
499                    }
500                    if entry.interfaces.is_empty() {
501                        tree.remove(&object_path);
502                        true
503                    } else {
504                        false
505                    }
506                } else {
507                    false
508                }
509            };
510            if names.iter().any(|n| n == interfaces::SERVICE) {
511                if let Some(device) = device_of(&object_path) {
512                    sink.emit(Event::ServicesChanged { path: path(device) });
513                }
514            }
515            if now_empty || names.iter().any(|n| n == interfaces::DEVICE) {
516                sink.emit(Event::DeviceRemoved {
517                    path: path(&object_path),
518                });
519            }
520        }
521
522        (Some(interfaces::PROPERTIES), Some("PropertiesChanged")) => {
523            let Some(object_path) = message.path.clone() else {
524                return;
525            };
526            let Some(interface) = message.arg(0).and_then(Value::as_str).map(str::to_owned) else {
527                return;
528            };
529            let changed = message.arg(1).map(Value::as_map).unwrap_or_default();
530            let invalidated = message.arg(2).map(Value::as_strings).unwrap_or_default();
531
532            {
533                let mut tree = tree.lock().unwrap();
534                let entry = tree.entry(object_path.clone()).or_default();
535                let props = entry.interfaces.entry(interface.clone()).or_default();
536                for (k, v) in &changed {
537                    props.insert(k.clone(), v.clone());
538                }
539                for k in &invalidated {
540                    props.remove(k);
541                }
542            }
543
544            let handle = path(&object_path);
545            match interface.as_str() {
546                interfaces::DEVICE => {
547                    if let Some(connected) = changed.get("Connected").and_then(Value::as_bool) {
548                        sink.emit(if connected {
549                            Event::Connected {
550                                path: handle.clone(),
551                            }
552                        } else {
553                            Event::Disconnected {
554                                path: handle.clone(),
555                            }
556                        });
557                    }
558                    if changed.get("ServicesResolved").and_then(Value::as_bool) == Some(true) {
559                        sink.emit(Event::ServicesResolved {
560                            path: handle.clone(),
561                        });
562                    }
563                    // RSSI updates are how a scan reports a device it already
564                    // knows, so they count as sightings.
565                    if changed.contains_key("RSSI") || changed.contains_key("ManufacturerData") {
566                        sink.emit(Event::DeviceSeen {
567                            path: handle,
568                            properties: changed,
569                        });
570                    }
571                }
572                interfaces::CHARACTERISTIC => {
573                    if let Some(bytes) = changed.get("Value").and_then(Value::as_bytes) {
574                        sink.emit(Event::CharacteristicValue {
575                            path: handle,
576                            value: bytes,
577                        });
578                    }
579                }
580                interfaces::ADAPTER => {
581                    if let Some(powered) = changed.get("Powered").and_then(Value::as_bool) {
582                        sink.emit(Event::AdapterChanged {
583                            powered,
584                            present: true,
585                        });
586                    }
587                }
588                _ => {}
589            }
590        }
591        _ => {}
592    }
593}
594
595#[cfg(test)]
596mod tests {
597    use super::*;
598
599    #[test]
600    fn a_services_owner_is_its_parent_path() {
601        assert_eq!(
602            device_of("/org/bluez/hci0/dev_AA_BB_CC_DD_EE_FF/service001c"),
603            Some("/org/bluez/hci0/dev_AA_BB_CC_DD_EE_FF")
604        );
605        // A path with no parent is reported as such rather than guessed at,
606        // so a malformed signal cannot be attributed to some other device.
607        assert_eq!(device_of("/service001c"), None);
608        assert_eq!(device_of("service001c"), None);
609        assert_eq!(device_of(""), None);
610    }
611
612    #[test]
613    fn object_paths_encode_the_gatt_hierarchy() {
614        // BlueZ has no "parent" property; the path *is* the relationship.
615        let device = "/org/bluez/hci0/dev_AA_BB_CC_DD_EE_FF";
616        let service = format!("{device}/service0010");
617        let characteristic = format!("{service}/char0011");
618        assert!(characteristic.starts_with(&format!("{service}/")));
619        assert!(service.starts_with(&format!("{device}/")));
620    }
621
622    #[test]
623    fn interfaces_dictionaries_flatten() {
624        let raw = Value::Array {
625            element: "{sa{sv}}".into(),
626            items: vec![Value::DictEntry(
627                Box::new(Value::Str(interfaces::DEVICE.into())),
628                Box::new(Value::dict([
629                    ("Name".into(), Value::Str("Pixel".into())),
630                    ("Connected".into(), Value::Bool(false)),
631                ])),
632            )],
633        };
634        let flat = to_interfaces(&raw);
635        let device = flat.get(interfaces::DEVICE).expect("Device1 missing");
636        assert_eq!(device.get("Name").and_then(Value::as_str), Some("Pixel"));
637        assert_eq!(
638            device.get("Connected").and_then(Value::as_bool),
639            Some(false)
640        );
641    }
642
643    #[test]
644    fn object_accessors_read_typed_properties() {
645        let mut interfaces_map = HashMap::new();
646        interfaces_map.insert(
647            interfaces::DEVICE.to_string(),
648            HashMap::from([
649                (
650                    "Name".to_string(),
651                    Value::Variant(Box::new(Value::Str("Pixel".into()))),
652                ),
653                (
654                    "RSSI".to_string(),
655                    Value::Variant(Box::new(Value::Int16(-55))),
656                ),
657                (
658                    "Connected".to_string(),
659                    Value::Variant(Box::new(Value::Bool(true))),
660                ),
661            ]),
662        );
663        let object = Object {
664            interfaces: interfaces_map,
665        };
666
667        assert!(object.has(interfaces::DEVICE));
668        assert!(!object.has(interfaces::ADAPTER));
669        assert_eq!(
670            object.string(interfaces::DEVICE, "Name").as_deref(),
671            Some("Pixel")
672        );
673        assert_eq!(object.int(interfaces::DEVICE, "RSSI"), Some(-55));
674        assert_eq!(object.bool(interfaces::DEVICE, "Connected"), Some(true));
675        assert_eq!(object.string(interfaces::DEVICE, "Missing"), None);
676    }
677}