Skip to main content

crabshell_services/
bluetooth.rs

1//! Bluetooth adapters and devices from BlueZ, on the system bus, and the
2//! shell's own pairing agent.
3
4pub(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
26/// The most adapters shown: one per radio.
27const MAX_ADAPTERS: usize = 16;
28/// The most devices shown: discovery adds every device in range.
29const MAX_DEVICES: usize = 256;
30/// The most objects kept, so a flood can't take the memory.
31const MAX_OBJECTS: usize = 4096;
32/// How long `Pair` and `Connect` may take: BlueZ answers a pairing only
33/// once the user confirmed it in the agent's prompt.
34const SLOW_CALL: std::time::Duration = std::time::Duration::from_secs(90);
35
36/// The properties this service reads, by interface: a change to any
37/// other, such as a device's signal strength during discovery, shows
38/// nothing new.
39fn 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/// Whether an adapter is on, from BlueZ's `PowerState`.
55#[derive(Clone, Copy, Debug, PartialEq, Eq)]
56pub enum BluetoothAdapterState {
57  /// On.
58  Enabled,
59  /// Off.
60  Disabled,
61  /// Turning on.
62  Enabling,
63  /// Turning off.
64  Disabling,
65  /// Off, and held off by rfkill, as by a laptop's airplane mode.
66  Blocked,
67}
68
69/// Whether a device is connected, from BlueZ's `Connected` and the calls
70/// made through [`Bluetooth`].
71#[derive(Clone, Copy, Debug, PartialEq, Eq)]
72pub enum BluetoothDeviceState {
73  /// Not connected.
74  Disconnected,
75  /// A [`Bluetooth::connect`] call is out.
76  Connecting,
77  /// Connected.
78  Connected,
79  /// A [`Bluetooth::disconnect`] call is out.
80  Disconnecting,
81}
82
83/// A Bluetooth radio BlueZ knows.
84#[derive(Clone, Debug, PartialEq)]
85pub struct BluetoothAdapter {
86  /// BlueZ's object path for it, such as `/org/bluez/hci0`.
87  pub path: String,
88  /// Its name, BlueZ's `Alias`.
89  pub name: String,
90  /// Its address, such as `00:1A:7D:DA:71:13`.
91  pub address: String,
92  /// Whether it is on.
93  pub powered: bool,
94  /// Whether it is on, off or on the way. An older BlueZ, without
95  /// `PowerState`, says only `Enabled` or `Disabled`, from
96  /// [`powered`](Self::powered).
97  pub state: BluetoothAdapterState,
98  /// Whether it is looking for devices.
99  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/// A device BlueZ knows: one paired before, or one discovery found.
138#[derive(Clone, Debug, PartialEq)]
139pub struct BluetoothDevice {
140  /// BlueZ's object path for it, which names it while it exists.
141  pub path: String,
142  /// The path of the adapter it is reached through.
143  pub adapter: String,
144  /// Its address, such as `AA:BB:CC:DD:EE:01`.
145  pub address: String,
146  /// Its `Alias`, else its `Name`, else its address.
147  pub name: String,
148  /// The icon BlueZ suggests, such as `audio-headset`, or `""`.
149  pub icon: String,
150  /// Whether it is connected.
151  pub connected: bool,
152  /// Whether it is connected, or on the way while a call made through
153  /// [`Bluetooth`] is out.
154  pub state: BluetoothDeviceState,
155  /// Whether it is paired.
156  pub paired: bool,
157  /// Whether it may connect without asking.
158  pub trusted: bool,
159  /// How full its battery is, from 0 to 100, if it says.
160  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/// Bluetooth from BlueZ, from `cx.bluetooth()`. Cloning it is cheap.
200#[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  /// Every adapter, in path order. Empty while BlueZ isn't running.
209  pub fn adapters(&self) -> ReadSignal<Vec<BluetoothAdapter>> {
210    self.adapters
211  }
212
213  /// Every device BlueZ knows, in path order. Empty while BlueZ isn't
214  /// running.
215  pub fn devices(&self) -> ReadSignal<Vec<BluetoothDevice>> {
216    self.devices
217  }
218
219  /// Turns the adapter at `adapter`, its path, on or off.
220  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  /// Starts looking for devices. Found ones join [`devices`] until BlueZ
226  /// forgets them, a while after [`stop_discovery`].
227  ///
228  /// [`devices`]: Self::devices
229  /// [`stop_discovery`]: Self::stop_discovery
230  pub fn start_discovery(&self, adapter: &str) {
231    self.call(adapter, ADAPTER, "StartDiscovery", ());
232  }
233
234  /// Stops looking for devices.
235  pub fn stop_discovery(&self, adapter: &str) {
236    self.call(adapter, ADAPTER, "StopDiscovery", ());
237  }
238
239  /// Connects the device at `device`, its path. Its state is
240  /// [`Connecting`](BluetoothDeviceState::Connecting) until BlueZ answers
241  /// or says it connected or disconnected.
242  pub fn connect(&self, device: &str) {
243    self.call(device, DEVICE, "Connect", ());
244  }
245
246  /// Disconnects the device at `device`, which is
247  /// [`Disconnecting`](BluetoothDeviceState::Disconnecting) as
248  /// [`connect`](Self::connect) is connecting.
249  pub fn disconnect(&self, device: &str) {
250    self.call(device, DEVICE, "Disconnect", ());
251  }
252
253  /// Pairs with the device at `device`. BlueZ asks the agent of whoever
254  /// called, so while `cx.bluetooth_agent()` is registered the call goes
255  /// out on the agent's connection, and a device that asks for a PIN, a
256  /// passkey or a confirmation asks the shell. Without it, BlueZ asks its
257  /// default agent, and with none a device that asks fails, which is
258  /// logged.
259  pub fn pair(&self, device: &str) {
260    self.call(device, DEVICE, "Pair", ());
261  }
262
263  /// Lets the device at `device` connect without asking, or not.
264  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  /// Unpairs the device at `device` and has its adapter forget it.
270  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  /// Calls `method` on BlueZ's object at `path`, and logs a refusal.
283  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    // BlueZ asks the agent of whoever called `Pair`.
291    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
322/// `cx.bluetooth()`.
323pub(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
338/// BlueZ for one shell, followed from the first ask.
339pub(crate) struct BluetoothService {
340  shared: Rc<Shared>,
341  /// The shell's pairing agent, whose connection `Pair` goes out on.
342  agent: Rc<agent::Service>,
343  state: RefCell<Option<BluetoothState>>,
344}
345
346struct BluetoothState {
347  adapters: Signal<Vec<BluetoothAdapter>>,
348  devices: Signal<Vec<BluetoothDevice>>,
349  /// BlueZ's adapters and devices, by path.
350  objects: BTreeMap<String, Object>,
351  /// The bus, while BlueZ runs, for the methods.
352  connection: Option<Connection>,
353  generation: u64,
354  /// The devices a connect or disconnect call is out for, by path, with
355  /// the call's number, so the answer to one that another replaced
356  /// changes nothing.
357  calls: HashMap<String, (BluetoothDeviceState, u64)>,
358  /// The number the next such call gets.
359  next_call: u64,
360}
361
362/// The interfaces this service reads on one of BlueZ's objects. An
363/// object is kept while it is an adapter or a device.
364#[derive(Default)]
365struct Object {
366  adapter: Option<Props>,
367  device: Option<Props>,
368  battery: Option<Props>,
369}
370
371impl Object {
372  /// Where `interface`'s properties go, or `None` for one this service
373  /// doesn't read.
374  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
384/// Gives the object at `path` `interfaces`. Past [`MAX_OBJECTS`] a new
385/// one is left out; which are shown is decided as they are.
386fn 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  /// Shows the adapters and devices as they are now.
444  fn publish(&self) {
445    // Set apart from the borrow, since effects may ask for more.
446    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      // Past the cap, connected and paired ones first, so the devices a
472      // person uses never hide behind strangers discovery found.
473      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  /// Shows `device` in `state` while a call is out for it. The call's
487  /// number.
488  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  /// Ends call `number` for `device`, which BlueZ answered, unless another
505  /// call or a change of `Connected` ended it already.
506  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  /// Only what adapters and devices are: BlueZ also broadcasts media,
525  /// GATT values and other programs' notifications, which would each
526  /// wake the shell for nothing.
527  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    // In path order, so the caps keep the same objects every time.
582    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        // Reaching where a call was headed ends it, as that can come before
611        // the answer. A change the other way waits for the answer.
612        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}