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