Skip to main content

webbluetooth_core/
adapter.rs

1//! The controllers themselves.
2//!
3//! Web Bluetooth has no concept of choosing a radio: a browser has one
4//! Bluetooth, and `navigator.bluetooth` is it. That is the right model for a
5//! web page and the wrong one for a machine with two dongles, a test rig
6//! driving both ends of a link, or a Raspberry Pi whose built-in controller is
7//! worse than the USB one next to it.
8//!
9//! So this sits alongside the standard rather than inside it. The default is
10//! unchanged — `Bluetooth::new` takes whichever controller the
11//! platform considers first — and nothing here has to be called to use the
12//! rest of the crate.
13//!
14//! What a platform can say about its radios varies more than most things in
15//! this crate, and the honest answer is sometimes "there is one and I cannot
16//! describe it":
17//!
18//! | platform | enumerate | select | address |
19//! |---|---|---|---|
20//! | BlueZ | yes | yes | yes |
21//! | `linux-hci` | yes | yes | yes |
22//! | Windows | yes | yes | yes |
23//! | CoreBluetooth | one | no | no |
24//! | Android | one | no | redacted |
25//!
26//! CoreBluetooth exposes no controller identity at all — a `CBCentralManager`
27//! is the radio, and there is no API to ask which one or to pick another.
28//! Android has `getDefaultAdapter()` and no way to enumerate; since Android 6
29//! `getAddress()` returns a fixed `02:00:00:00:00:00` to every caller that is
30//! not the system, so reporting it would be reporting a placeholder.
31//!
32//! Rather than pretend, those platforms report exactly one adapter and
33//! `Bluetooth::select_adapter` refuses anything else by name.
34
35/// One Bluetooth controller.
36///
37/// Obtained from `Bluetooth::adapters`. The [`id`](Self::id) is what
38/// `Bluetooth::select_adapter` takes, and is whatever the platform
39/// uses to name a radio: `hci0` on Linux, a device interface path on Windows.
40#[derive(Debug, Clone, PartialEq, Eq)]
41pub struct AdapterInfo {
42    /// What `Bluetooth::select_adapter` takes to choose this controller.
43    pub id: String,
44    /// A human-readable name, where the platform has one.
45    pub name: Option<String>,
46    /// The controller's own Bluetooth address, where the platform exposes it.
47    pub address: Option<String>,
48    /// Whether the radio is on.
49    pub powered: bool,
50    /// Whether this is the controller a plain `Bluetooth::new` uses.
51    pub is_default: bool,
52}
53
54impl AdapterInfo {
55    /// What `Bluetooth::select_adapter` takes to choose this one.
56    pub fn id(&self) -> &str {
57        &self.id
58    }
59
60    /// A human-readable name, where the platform has one.
61    ///
62    /// BlueZ reports the adapter's `Alias`, which is what the machine
63    /// advertises as. `None` where the platform does not name its radios.
64    pub fn name(&self) -> Option<&str> {
65        self.name.as_deref()
66    }
67
68    /// The controller's own Bluetooth address.
69    ///
70    /// `None` where the platform withholds it: CoreBluetooth never exposes it,
71    /// and Android returns a fixed placeholder to ordinary apps rather than
72    /// the real address, which is reported as `None` rather than as that
73    /// placeholder.
74    pub fn address(&self) -> Option<&str> {
75        self.address.as_deref()
76    }
77
78    /// Whether the radio is switched on.
79    pub fn is_powered(&self) -> bool {
80        self.powered
81    }
82
83    /// Whether this is the controller a plain `Bluetooth::new` uses.
84    pub fn is_default(&self) -> bool {
85        self.is_default
86    }
87}
88
89/// What a link actually negotiated.
90///
91/// The counterpart to `Bluetooth`'s connection *priority*: priority
92/// asks for a profile, this reports what came back. Not part of Web
93/// Bluetooth, which has neither.
94///
95/// The units are the Bluetooth ones rather than milliseconds, because that is
96/// what the controller reports and converting would lose precision: the
97/// interval is in 1.25 ms steps and the timeout in 10 ms steps.
98#[derive(Debug, Clone, Copy, PartialEq, Eq)]
99pub struct ConnectionParameters {
100    /// Connection interval, in 1.25 ms steps.
101    pub interval: u16,
102    /// Peripheral latency: connection events the peer may skip.
103    pub latency: u16,
104    /// Supervision timeout, in 10 ms steps.
105    pub timeout: u16,
106}
107
108impl ConnectionParameters {
109    /// Connection interval, in units of 1.25 ms.
110    pub fn interval(&self) -> u16 {
111        self.interval
112    }
113
114    /// How many connection events the peripheral may skip.
115    pub fn latency(&self) -> u16 {
116        self.latency
117    }
118
119    /// Supervision timeout, in units of 10 ms.
120    pub fn timeout(&self) -> u16 {
121        self.timeout
122    }
123
124    /// Connection interval in milliseconds.
125    pub fn interval_millis(&self) -> f32 {
126        self.interval as f32 * 1.25
127    }
128
129    /// Supervision timeout in milliseconds.
130    pub fn timeout_millis(&self) -> u32 {
131        self.timeout as u32 * 10
132    }
133}
134
135/// What `BluetoothDevice::pair` did.
136///
137/// Three outcomes rather than a bare `Result<()>`, because "nothing happened"
138/// is a real answer here and it is not a failure: Apple pairs when an
139/// encrypted attribute is touched and offers no way to ask for it in advance.
140/// Collapsing that into `Ok(())` would tell a caller a bond exists when it
141/// does not, and into an error would send them looking for a problem that is
142/// not there.
143#[derive(Debug, Clone, Copy, PartialEq, Eq)]
144pub enum Pairing {
145    /// The ceremony ran and the device is now bonded.
146    Paired,
147    /// It already was, so nothing was asked of the user.
148    AlreadyPaired,
149    /// This platform pairs by itself, when an encrypted attribute is first
150    /// read or written. Nothing was done; carry on and the system will ask the
151    /// user if it needs to.
152    Implicit,
153}
154
155/// A physical layer an LE link can run at.
156///
157/// Not part of Web Bluetooth, which has no notion of one. It is here because
158/// it is the largest single throughput lever available on a connection: 2M
159/// doubles the symbol rate, which roughly doubles what fits in a connection
160/// event. Coded trades the other way, buying range at a quarter or an eighth
161/// of the rate.
162#[derive(Debug, Clone, Copy, PartialEq, Eq)]
163pub enum Phy {
164    /// 1 Msym/s. Every LE device supports this; it is the only one that
165    /// existed before Bluetooth 5.
166    Le1M,
167    /// 2 Msym/s. Bluetooth 5, and optional — a peer may simply not have it,
168    /// in which case asking for it leaves the link where it was.
169    Le2M,
170    /// Long range. Bluetooth 5, optional, and slower by design.
171    LeCoded,
172}
173
174/// What a link is actually running at, in each direction.
175///
176/// The two can differ: a sensor that sends a great deal and receives almost
177/// nothing has no reason to run both ways at the same rate.
178#[derive(Debug, Clone, Copy, PartialEq, Eq)]
179pub struct ConnectionPhy {
180    /// The PHY this side transmits on.
181    pub tx: Phy,
182    /// The PHY this side receives on.
183    pub rx: Phy,
184}
185
186impl ConnectionPhy {
187    /// The PHY this device transmits on.
188    pub fn tx(&self) -> Phy {
189        self.tx
190    }
191
192    /// The PHY it receives on.
193    pub fn rx(&self) -> Phy {
194        self.rx
195    }
196}
197
198/// The single adapter a platform that cannot enumerate reports.
199///
200/// Named rather than empty so that `Bluetooth::adapters` has the same
201/// shape everywhere: one entry, selectable by this id, and refusing any other.
202pub const DEFAULT_ADAPTER: &str = "default";
203
204/// Whether `address` is the placeholder Android hands out instead of the real
205/// controller address.
206///
207/// Since Android 6 `BluetoothAdapter.getAddress()` returns a constant to any
208/// app without `LOCAL_MAC_ADDRESS_PERMISSION`, which is a system permission.
209/// Every device returns the same one, so passing it through would be worse
210/// than saying nothing.
211#[cfg_attr(not(target_os = "android"), allow(dead_code))]
212pub fn is_placeholder_address(address: &str) -> bool {
213    address.eq_ignore_ascii_case("02:00:00:00:00:00")
214}
215
216#[cfg(test)]
217mod tests {
218    use super::*;
219
220    /// Android's placeholder is not an address, and reporting it as one would
221    /// have every Android device claim the same radio.
222    #[test]
223    fn the_android_placeholder_is_not_reported_as_an_address() {
224        assert!(is_placeholder_address("02:00:00:00:00:00"));
225        assert!(is_placeholder_address(
226            "02:00:00:00:00:00".to_uppercase().as_str()
227        ));
228        assert!(!is_placeholder_address("AA:BB:CC:DD:EE:FF"));
229    }
230
231    /// The units are the controller's, and the conversions have to match the
232    /// specification's: 1.25 ms per interval step, 10 ms per timeout step.
233    #[test]
234    fn connection_parameters_convert_in_the_units_the_controller_uses() {
235        // 24 * 1.25 = 30 ms, the interval an iPhone typically settles on.
236        let p = ConnectionParameters {
237            interval: 24,
238            latency: 0,
239            timeout: 500,
240        };
241        assert_eq!(p.interval(), 24);
242        assert_eq!(p.interval_millis(), 30.0);
243        // 500 * 10 = 5 s, the usual supervision timeout.
244        assert_eq!(p.timeout_millis(), 5_000);
245        assert_eq!(p.latency(), 0);
246    }
247
248    #[test]
249    fn an_adapter_reports_what_it_was_given() {
250        let a = AdapterInfo {
251            id: "hci1".into(),
252            name: Some("rig".into()),
253            address: Some("AA:BB:CC:DD:EE:FF".into()),
254            powered: true,
255            is_default: false,
256        };
257        assert_eq!(a.id(), "hci1");
258        assert_eq!(a.name(), Some("rig"));
259        assert_eq!(a.address(), Some("AA:BB:CC:DD:EE:FF"));
260        assert!(a.is_powered());
261        assert!(!a.is_default());
262    }
263}
264
265/// How aggressively to maintain a connection.
266///
267/// **Not part of Web Bluetooth**, and a hint rather than an instruction: the
268/// peripheral has the final say on the connection interval, and only some
269/// platforms can even ask. See
270/// `BluetoothDevice::request_connection_priority`.
271#[derive(Debug, Clone, Copy, PartialEq, Eq)]
272pub enum ConnectionPriority {
273    /// Whatever the platform considers a reasonable default.
274    Balanced,
275    /// A shorter interval: lower latency, more power, and fewer simultaneous
276    /// connections the controller can keep.
277    High,
278    /// A longer interval: less power, higher latency.
279    LowPower,
280}