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}
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
59pub type Path = Arc<str>;
65
66pub fn path(s: &str) -> Path {
67 Arc::from(s)
68}
69
70#[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#[derive(Debug, Clone)]
100pub enum Event {
101 AdapterChanged { powered: bool, present: bool },
103 DeviceSeen {
105 path: Path,
106 properties: HashMap<String, Value>,
107 },
108 DeviceRemoved { path: Path },
110 Connected { path: Path },
112 Disconnected { path: Path },
114 ServicesResolved { path: Path },
116 CharacteristicValue { path: Path, value: Vec<u8> },
118 ServicesChanged { path: Path },
126 Disconnected_,
128}
129
130pub trait EventSink: Send + Sync {
132 fn emit(&self, event: Event);
133}
134
135pub struct Bluez {
137 connection: Arc<Connection>,
138 tree: Arc<Mutex<HashMap<String, Object>>>,
139 adapter: Mutex<Option<String>>,
140 _sink: Arc<dyn EventSink>,
142}
143
144impl Bluez {
145 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 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 pub fn connection(&self) -> &Arc<Connection> {
174 &self.connection
175 }
176
177 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 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 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 adapters.into_iter().next()
222 });
223 Ok(())
224 }
225
226 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 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 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 pub fn adapter_address(&self) -> Option<String> {
268 let adapter = self.adapter()?;
269 self.object(&adapter)?
270 .string(interfaces::ADAPTER, "Address")
271 }
272
273 pub fn adapter(&self) -> Option<String> {
275 self.adapter.lock().unwrap().clone()
276 }
277
278 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 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 pub fn object(&self, path: &str) -> Option<Object> {
301 self.tree.lock().unwrap().get(path).cloned()
302 }
303
304 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 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 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 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 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 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 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 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 pub fn export(&self, path: &str, handler: Arc<dyn ObjectHandler>) {
426 self.connection.export(path, handler);
427 }
428}
429
430fn 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
439fn device_of(service_path: &str) -> Option<&str> {
445 let (device, _) = service_path.rsplit_once('/')?;
446 (!device.is_empty()).then_some(device)
447}
448
449fn 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 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 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 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}