1use 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
61pub type Path = Arc<str>;
67
68pub fn path(s: &str) -> Path {
69 Arc::from(s)
70}
71
72#[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#[derive(Debug, Clone)]
102pub enum Event {
103 AdapterChanged { powered: bool, present: bool },
105 DeviceSeen {
107 path: Path,
108 properties: HashMap<String, Value>,
109 },
110 DeviceRemoved { path: Path },
112 Connected { path: Path },
114 Disconnected { path: Path },
116 ServicesResolved { path: Path },
118 CharacteristicValue { path: Path, value: Vec<u8> },
120 ServicesChanged { path: Path },
128 Disconnected_,
130}
131
132pub trait EventSink: Send + Sync {
134 fn emit(&self, event: Event);
135}
136
137pub struct Bluez {
139 connection: Arc<Connection>,
140 tree: Arc<Mutex<HashMap<String, Object>>>,
141 adapter: Mutex<Option<String>>,
142 _sink: Arc<dyn EventSink>,
144}
145
146impl Bluez {
147 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 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 pub fn connection(&self) -> &Arc<Connection> {
176 &self.connection
177 }
178
179 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 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 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 adapters.into_iter().next()
224 });
225 Ok(())
226 }
227
228 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 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 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 pub fn adapter_address(&self) -> Option<String> {
270 let adapter = self.adapter()?;
271 self.object(&adapter)?
272 .string(interfaces::ADAPTER, "Address")
273 }
274
275 pub fn adapter(&self) -> Option<String> {
277 self.adapter.lock().unwrap().clone()
278 }
279
280 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 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 pub fn object(&self, path: &str) -> Option<Object> {
303 self.tree.lock().unwrap().get(path).cloned()
304 }
305
306 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 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 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 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 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 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 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 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 pub fn export(&self, path: &str, handler: Arc<dyn ObjectHandler>) {
428 self.connection.export(path, handler);
429 }
430}
431
432fn 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
441fn device_of(service_path: &str) -> Option<&str> {
447 let (device, _) = service_path.rsplit_once('/')?;
448 (!device.is_empty()).then_some(device)
449}
450
451fn 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 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 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 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}