1pub(crate) mod agent;
5#[cfg(test)]
6mod tests;
7
8use std::cell::RefCell;
9use std::collections::{BTreeMap, HashMap};
10use std::rc::Rc;
11use std::sync::Once;
12
13use crabshell_reactive::{ReadSignal, Signal};
14use crabshell_ui::Cx;
15use zbus::{Connection, Message, ObjectPath, OwnedObjectPath, Variant};
16
17pub use self::agent::{BluetoothAgent, PairingKind, PairingRequest};
18use crate::Shared;
19use crate::dbus::{self, CALL_TIMEOUT, Daemon, OBJECT_MANAGER, PROPERTIES, Props, set_changed};
20
21const BLUEZ: &str = "org.bluez";
22const ADAPTER: &str = "org.bluez.Adapter1";
23const DEVICE: &str = "org.bluez.Device1";
24const BATTERY: &str = "org.bluez.Battery1";
25
26const MAX_ADAPTERS: usize = 16;
28const MAX_DEVICES: usize = 256;
30const MAX_OBJECTS: usize = 4096;
32const SLOW_CALL: std::time::Duration = std::time::Duration::from_secs(90);
35
36fn read(interface: &str, name: &str) -> bool {
40 match interface {
41 ADAPTER => matches!(
42 name,
43 "Alias" | "Address" | "Powered" | "PowerState" | "Discovering"
44 ),
45 DEVICE => matches!(
46 name,
47 "Address" | "Alias" | "Name" | "Icon" | "Connected" | "Paired" | "Trusted" | "Adapter"
48 ),
49 BATTERY => name == "Percentage",
50 _ => false,
51 }
52}
53
54#[derive(Clone, Copy, Debug, PartialEq, Eq)]
56pub enum BluetoothAdapterState {
57 Enabled,
59 Disabled,
61 Enabling,
63 Disabling,
65 Blocked,
67}
68
69#[derive(Clone, Copy, Debug, PartialEq, Eq)]
72pub enum BluetoothDeviceState {
73 Disconnected,
75 Connecting,
77 Connected,
79 Disconnecting,
81}
82
83#[derive(Clone, Debug, PartialEq)]
85pub struct BluetoothAdapter {
86 pub path: String,
88 pub name: String,
90 pub address: String,
92 pub powered: bool,
94 pub state: BluetoothAdapterState,
98 pub discovering: bool,
100}
101
102impl BluetoothAdapter {
103 fn from_props(path: String, props: &Props) -> BluetoothAdapter {
104 let powered = dbus::get(props, "Powered").unwrap_or(false);
105 let state = match dbus::get::<&str>(props, "PowerState") {
106 Some("on") => BluetoothAdapterState::Enabled,
107 Some("off") => BluetoothAdapterState::Disabled,
108 Some("off-enabling") => BluetoothAdapterState::Enabling,
109 Some("on-disabling") => BluetoothAdapterState::Disabling,
110 Some("off-blocked") => BluetoothAdapterState::Blocked,
111 unknown => {
112 if let Some(unknown) = unknown {
113 tracing::debug!(
114 path,
115 state = unknown,
116 "an unknown power state; read from Powered"
117 );
118 }
119 if powered {
120 BluetoothAdapterState::Enabled
121 } else {
122 BluetoothAdapterState::Disabled
123 }
124 }
125 };
126 BluetoothAdapter {
127 name: dbus::text(props, "Alias"),
128 address: dbus::text(props, "Address"),
129 powered,
130 state,
131 discovering: dbus::get(props, "Discovering").unwrap_or(false),
132 path,
133 }
134 }
135}
136
137#[derive(Clone, Debug, PartialEq)]
139pub struct BluetoothDevice {
140 pub path: String,
142 pub adapter: String,
144 pub address: String,
146 pub name: String,
148 pub icon: String,
150 pub connected: bool,
152 pub state: BluetoothDeviceState,
155 pub paired: bool,
157 pub trusted: bool,
159 pub battery: Option<u8>,
161}
162
163impl BluetoothDevice {
164 fn from_props(
165 path: String,
166 props: &Props,
167 battery: Option<&Props>,
168 call: Option<BluetoothDeviceState>,
169 ) -> BluetoothDevice {
170 let address = dbus::text(props, "Address");
171 let connected = dbus::get(props, "Connected").unwrap_or(false);
172 let state = match (call, connected) {
173 (Some(call), _) => call,
174 (None, true) => BluetoothDeviceState::Connected,
175 (None, false) => BluetoothDeviceState::Disconnected,
176 };
177 let name = [dbus::text(props, "Alias"), dbus::text(props, "Name")]
178 .into_iter()
179 .find(|name| !name.is_empty())
180 .unwrap_or_else(|| address.clone());
181 BluetoothDevice {
182 path,
183 adapter: dbus::get::<&ObjectPath>(props, "Adapter")
184 .map_or(String::new(), |at| at.to_string()),
185 address,
186 name,
187 icon: dbus::text(props, "Icon"),
188 connected,
189 state,
190 paired: dbus::get(props, "Paired").unwrap_or(false),
191 trusted: dbus::get(props, "Trusted").unwrap_or(false),
192 battery: battery
193 .and_then(|props| dbus::get::<u8>(props, "Percentage"))
194 .map(|percent| percent.min(100)),
195 }
196 }
197}
198
199#[derive(Clone)]
201pub struct Bluetooth {
202 service: Option<Rc<BluetoothService>>,
203 adapters: ReadSignal<Vec<BluetoothAdapter>>,
204 devices: ReadSignal<Vec<BluetoothDevice>>,
205}
206
207impl Bluetooth {
208 pub fn adapters(&self) -> ReadSignal<Vec<BluetoothAdapter>> {
210 self.adapters
211 }
212
213 pub fn devices(&self) -> ReadSignal<Vec<BluetoothDevice>> {
216 self.devices
217 }
218
219 pub fn set_powered(&self, adapter: &str, powered: bool) {
221 let body = (ADAPTER, "Powered", Variant::from(powered));
222 self.call(adapter, PROPERTIES, "Set", body);
223 }
224
225 pub fn start_discovery(&self, adapter: &str) {
231 self.call(adapter, ADAPTER, "StartDiscovery", ());
232 }
233
234 pub fn stop_discovery(&self, adapter: &str) {
236 self.call(adapter, ADAPTER, "StopDiscovery", ());
237 }
238
239 pub fn connect(&self, device: &str) {
243 self.call(device, DEVICE, "Connect", ());
244 }
245
246 pub fn disconnect(&self, device: &str) {
250 self.call(device, DEVICE, "Disconnect", ());
251 }
252
253 pub fn pair(&self, device: &str) {
260 self.call(device, DEVICE, "Pair", ());
261 }
262
263 pub fn set_trusted(&self, device: &str, trusted: bool) {
265 let body = (DEVICE, "Trusted", Variant::from(trusted));
266 self.call(device, PROPERTIES, "Set", body);
267 }
268
269 pub fn forget(&self, device: &str) {
271 let adapter = self.service.as_ref().and_then(|service| {
272 let state = service.state.borrow();
273 let object = state.as_ref()?.objects.get(device)?;
274 dbus::get::<&ObjectPath>(object.device.as_ref()?, "Adapter").map(|at| at.to_string())
275 });
276 let (Some(adapter), Ok(path)) = (adapter, ObjectPath::try_from(device.to_owned())) else {
277 return tracing::info!(device, "no such Bluetooth device; nothing forgotten");
278 };
279 self.call(&adapter, ADAPTER, "RemoveDevice", path);
280 }
281
282 fn call<B>(&self, path: &str, interface: &'static str, method: &'static str, body: B)
284 where
285 B: serde::Serialize + zbus::DynamicType + 'static,
286 {
287 let Some(service) = &self.service else {
288 return;
289 };
290 let agent = (method == "Pair").then(|| service.agent.connection());
292 let Some(connection) = agent.flatten().or_else(|| {
293 let state = service.state.borrow();
294 state.as_ref().and_then(|state| state.connection.clone())
295 }) else {
296 return tracing::info!(method, "BlueZ isn't running; nothing sent");
297 };
298 let marked = match method {
299 "Connect" => Some(service.mark(path, BluetoothDeviceState::Connecting)),
300 "Disconnect" => Some(service.mark(path, BluetoothDeviceState::Disconnecting)),
301 _ => None,
302 };
303 let (shared, service, path) = (&service.shared, Rc::clone(service), path.to_owned());
304 shared.spawn(async move {
305 let call = connection.call_method(Some(BLUEZ), path.as_str(), Some(interface), method, &body);
306 let limit = if matches!(method, "Pair" | "Connect") {
307 SLOW_CALL
308 } else {
309 CALL_TIMEOUT
310 };
311 let answer = service.shared.timeout(limit, call).await;
312 if let Some(number) = marked {
313 service.unmark(&path, number);
314 }
315 if let Err(error) = answer {
316 tracing::warn!(%error, path, method, "BlueZ refused it");
317 }
318 });
319 }
320}
321
322pub(crate) fn bluetooth(cx: &Cx) -> Bluetooth {
324 let Some(service) = cx.service::<BluetoothService>() else {
325 static LOGGED: Once = Once::new();
326 LOGGED.call_once(|| {
327 tracing::warn!("cx.bluetooth() needs the services the shell provides; it stays empty");
328 });
329 return Bluetooth {
330 service: None,
331 adapters: cx.signal(Vec::new()).read_only(),
332 devices: cx.signal(Vec::new()).read_only(),
333 };
334 };
335 service.start()
336}
337
338pub(crate) struct BluetoothService {
340 shared: Rc<Shared>,
341 agent: Rc<agent::Service>,
343 state: RefCell<Option<BluetoothState>>,
344}
345
346struct BluetoothState {
347 adapters: Signal<Vec<BluetoothAdapter>>,
348 devices: Signal<Vec<BluetoothDevice>>,
349 objects: BTreeMap<String, Object>,
351 connection: Option<Connection>,
353 generation: u64,
354 calls: HashMap<String, (BluetoothDeviceState, u64)>,
358 next_call: u64,
360}
361
362#[derive(Default)]
365struct Object {
366 adapter: Option<Props>,
367 device: Option<Props>,
368 battery: Option<Props>,
369}
370
371impl Object {
372 fn slot(&mut self, interface: &str) -> Option<&mut Option<Props>> {
375 match interface {
376 ADAPTER => Some(&mut self.adapter),
377 DEVICE => Some(&mut self.device),
378 BATTERY => Some(&mut self.battery),
379 _ => None,
380 }
381 }
382}
383
384fn add(objects: &mut BTreeMap<String, Object>, path: String, interfaces: HashMap<String, Props>) {
387 if objects.len() >= MAX_OBJECTS && !objects.contains_key(&path) {
388 return tracing::debug!(path, "too many Bluetooth objects; leaving one out");
389 }
390 let mut object = objects.remove(&path).unwrap_or_default();
391 for (interface, props) in interfaces {
392 if let Some(slot) = object.slot(&interface) {
393 *slot = Some(props);
394 }
395 }
396 if object.adapter.is_some() || object.device.is_some() {
397 objects.insert(path, object);
398 }
399}
400
401impl BluetoothService {
402 pub(crate) fn new(shared: Rc<Shared>, agent: Rc<agent::Service>) -> BluetoothService {
403 BluetoothService {
404 shared,
405 agent,
406 state: RefCell::new(None),
407 }
408 }
409
410 fn start(self: &Rc<Self>) -> Bluetooth {
411 if let Some(state) = &*self.state.borrow() {
412 return Bluetooth {
413 service: Some(Rc::clone(self)),
414 adapters: state.adapters.read_only(),
415 devices: state.devices.read_only(),
416 };
417 }
418 let root = &self.shared.root;
419 let (adapters, devices) = (root.signal(Vec::new()), root.signal(Vec::new()));
420 *self.state.borrow_mut() = Some(BluetoothState {
421 adapters,
422 devices,
423 objects: BTreeMap::new(),
424 connection: None,
425 generation: 0,
426 calls: HashMap::new(),
427 next_call: 0,
428 });
429 match self.shared.config.system_bus.clone() {
430 Some(address) => {
431 let follow = dbus::follow(Rc::clone(&self.shared), Rc::clone(self), address);
432 self.shared.spawn(follow);
433 }
434 None => tracing::info!("no system bus, so there is no Bluetooth"),
435 }
436 Bluetooth {
437 service: Some(Rc::clone(self)),
438 adapters: adapters.read_only(),
439 devices: devices.read_only(),
440 }
441 }
442
443 fn publish(&self) {
445 let shown = self.state.borrow().as_ref().map(|state| {
447 let objects = || {
448 state
449 .objects
450 .iter()
451 .map(|(path, object)| (path.clone(), object))
452 };
453 let adapters = objects()
454 .filter_map(|(path, object)| {
455 Some(BluetoothAdapter::from_props(path, object.adapter.as_ref()?))
456 })
457 .take(MAX_ADAPTERS)
458 .collect::<Vec<_>>();
459 let mut devices = objects()
460 .filter_map(|(path, object)| {
461 let device = object.device.as_ref()?;
462 let call = state.calls.get(&path).map(|(call, _)| *call);
463 Some(BluetoothDevice::from_props(
464 path,
465 device,
466 object.battery.as_ref(),
467 call,
468 ))
469 })
470 .collect::<Vec<_>>();
471 if devices.len() > MAX_DEVICES {
474 devices.sort_by_key(|device| (!device.connected, !device.paired));
475 devices.truncate(MAX_DEVICES);
476 devices.sort_by(|a, b| a.path.cmp(&b.path));
477 }
478 (state.adapters, adapters, state.devices, devices)
479 });
480 if let Some((adapters_signal, adapters, devices_signal, devices)) = shown {
481 set_changed(adapters_signal, adapters);
482 set_changed(devices_signal, devices);
483 }
484 }
485
486 fn mark(&self, device: &str, state: BluetoothDeviceState) -> u64 {
489 let number = {
490 let mut held = self.state.borrow_mut();
491 let Some(held) = held.as_mut() else {
492 return 0;
493 };
494 held.next_call += 1;
495 held
496 .calls
497 .insert(device.to_owned(), (state, held.next_call));
498 held.next_call
499 };
500 self.publish();
501 number
502 }
503
504 fn unmark(&self, device: &str, number: u64) {
507 let ended = {
508 let mut state = self.state.borrow_mut();
509 let Some(calls) = state.as_mut().map(|state| &mut state.calls) else {
510 return;
511 };
512 let current = calls.get(device).is_some_and(|(_, at)| *at == number);
513 current && calls.remove(device).is_some()
514 };
515 if ended {
516 self.publish();
517 }
518 }
519}
520
521impl Daemon for BluetoothService {
522 const NAME: &'static str = BLUEZ;
523
524 fn rules() -> Vec<String> {
528 let mut rules = vec![format!(
529 "type='signal',sender='{BLUEZ}',interface='{OBJECT_MANAGER}'"
530 )];
531 rules.extend([ADAPTER, DEVICE, BATTERY].map(|interface| {
532 format!(
533 "type='signal',sender='{BLUEZ}',interface='{PROPERTIES}',member='PropertiesChanged',\
534 arg0='{interface}'"
535 )
536 }));
537 rules
538 }
539
540 fn alive(&self) -> bool {
541 let state = self.state.borrow();
542 state
543 .as_ref()
544 .is_some_and(|state| state.adapters.try_with(|_| ()).is_some())
545 }
546
547 fn clear(&self) -> u64 {
548 let generation = {
549 let mut state = self.state.borrow_mut();
550 let Some(state) = state.as_mut() else {
551 return 0;
552 };
553 state.objects.clear();
554 state.calls.clear();
555 state.connection = None;
556 state.generation += 1;
557 state.generation
558 };
559 self.publish();
560 generation
561 }
562
563 async fn read(self: Rc<Self>, connection: Connection, generation: u64) {
564 let call = connection.call_method(
565 Some(BLUEZ),
566 "/",
567 Some(OBJECT_MANAGER),
568 "GetManagedObjects",
569 &(),
570 );
571 let read = async {
572 let reply = self.shared.timeout(CALL_TIMEOUT, call).await?;
573 reply
574 .body()
575 .deserialize::<HashMap<OwnedObjectPath, HashMap<String, Props>>>()
576 };
577 let managed = match read.await {
578 Ok(managed) => managed,
579 Err(error) => return tracing::warn!(%error, "couldn't read BlueZ"),
580 };
581 let managed = managed
583 .into_iter()
584 .map(|(path, interfaces)| (path.as_str().to_owned(), interfaces))
585 .collect::<BTreeMap<_, _>>();
586 {
587 let mut state = self.state.borrow_mut();
588 let Some(state) = state
589 .as_mut()
590 .filter(|state| state.generation == generation)
591 else {
592 return;
593 };
594 state.objects.clear();
595 for (path, interfaces) in managed {
596 add(&mut state.objects, path, interfaces);
597 }
598 state.connection = Some(connection);
599 }
600 self.publish();
601 }
602
603 fn signal(self: &Rc<Self>, _: &Connection, message: &Message) {
604 if let Some((path, interface, changed, dropped)) = dbus::properties_changed(message) {
605 {
606 let mut state = self.state.borrow_mut();
607 let Some(state) = state.as_mut() else {
608 return;
609 };
610 let reached = match dbus::get::<bool>(&changed, "Connected") {
613 Some(true) => Some(BluetoothDeviceState::Connecting),
614 Some(false) => Some(BluetoothDeviceState::Disconnecting),
615 None => None,
616 };
617 let headed = state.calls.get(&path).map(|(call, _)| *call);
618 if interface == DEVICE && reached.is_some() && headed == reached {
619 state.calls.remove(&path);
620 }
621 let props = state
622 .objects
623 .get_mut(&path)
624 .and_then(|object| object.slot(&interface)?.as_mut());
625 let Some(props) = props else {
626 return;
627 };
628 let shown = changed
629 .keys()
630 .chain(&dropped)
631 .any(|name| read(&interface, name));
632 dbus::apply(props, changed, dropped);
633 if !shown {
634 return;
635 }
636 }
637 return self.publish();
638 }
639 let header = message.header();
640 if header.interface().map(|interface| interface.as_str()) != Some(OBJECT_MANAGER) {
641 return;
642 }
643 let body = message.body();
644 {
645 let mut state = self.state.borrow_mut();
646 let Some(state) = state.as_mut() else {
647 return;
648 };
649 match header.member().map(|member| member.as_str()) {
650 Some("InterfacesAdded") => {
651 let Ok((path, interfaces)) =
652 body.deserialize::<(OwnedObjectPath, HashMap<String, Props>)>()
653 else {
654 return;
655 };
656 add(&mut state.objects, path.as_str().to_owned(), interfaces);
657 }
658 Some("InterfacesRemoved") => {
659 let Ok((path, interfaces)) = body.deserialize::<(OwnedObjectPath, Vec<String>)>() else {
660 return;
661 };
662 let Some(object) = state.objects.get_mut(path.as_str()) else {
663 return;
664 };
665 for interface in interfaces {
666 if let Some(slot) = object.slot(&interface) {
667 *slot = None;
668 }
669 }
670 if object.adapter.is_none() && object.device.is_none() {
671 state.objects.remove(path.as_str());
672 }
673 }
674 _ => return,
675 }
676 }
677 self.publish();
678 }
679}