Skip to main content

hap_ble/
bluest_gatt.rs

1//! A [`GattConnection`] backed by the `bluest` crate, with a **reconnect-and-
2//! resume supervisor**: sleepy HAP accessories drop the link every few
3//! operations during the long attribute-database sweep, so each operation
4//! reconnects (re-discovering its characteristic handles by UUID) and retries
5//! on a clean disconnect, resuming where it left off.
6
7use crate::error::{BleError, Result};
8use crate::gatt::{
9    u16_le, AdvertSource, GattCharacteristic, GattConnection, GattService, RawAdvert,
10    HAP_INSTANCE_ID_DESC, HAP_SERVICE_ID_CHAR,
11};
12use crate::scan_gate::ScanGate;
13use async_trait::async_trait;
14use bluest::error::ErrorKind;
15use bluest::{Adapter, Characteristic, Device};
16use std::collections::HashMap;
17use std::sync::atomic::{AtomicU64, Ordering};
18use std::sync::Arc;
19use std::time::Duration;
20use tokio::sync::{mpsc, Mutex};
21
22/// Per-attempt timeout for re-establishing the link (connect + service
23/// discovery). On macOS a `connect_device` attempted while a scan is running can
24/// hang indefinitely; bounding it (as aiohomekit does via `bleak_retry_connector`)
25/// turns a wedged connect into a failed attempt the backstop can retry.
26const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
27
28/// Per-attempt timeout for the pre-connect teardown (disconnect + adapter
29/// wait). On the pause-ack-timeout escape path these run while a scan may
30/// still be live and can hang exactly like the connect; bounding them turns
31/// that into a failed attempt the backstop retries instead of a wedge that
32/// blocks every later operation behind the scan gate's lock.
33const TEARDOWN_TIMEOUT: Duration = Duration::from_secs(5);
34
35/// The HAP Service-Signature characteristic — appears in *every* service. Only
36/// the one in the Protocol Information service is addressable/used; the rest are
37/// dropped during discovery so the (UUID-keyed) handle map doesn't collide and
38/// the generate-broadcast-key write reaches the correct characteristic.
39const SERVICE_SIGNATURE_CHAR: &str = "000000a5-0000-1000-8000-0026bb765291";
40/// The HAP Protocol Information service — the one whose Service-Signature char is
41/// the generate-broadcast-key target (matches aiohomekit's service-scoped lookup).
42const PROTOCOL_INFO_SERVICE: &str = "000000a2-0000-1000-8000-0026bb765291";
43
44/// Consecutive reconnects allowed *within a single operation* before it gives up
45/// (a runaway backstop). This bounds one stuck read/write, not the connection's
46/// lifetime — a sleepy accessory may legitimately drop the link on most
47/// operations, so a healthy long-lived subscription can far exceed this in
48/// aggregate; only a link that will not stay up for one op long enough to make
49/// progress trips it.
50const MAX_OP_RECONNECTS: u32 = 8;
51
52/// Map a bluest error to a [`BleError`], classifying link-loss conditions as
53/// [`BleError::Disconnected`] (so the supervisor reconnects) from bluest's typed
54/// [`ErrorKind`] rather than by string-matching. A [`Timeout`](ErrorKind::Timeout)
55/// is treated as a disconnect: on some platforms a dropped link surfaces as a
56/// read/write timeout, and a reconnect+retry against a merely-slow accessory is
57/// cheap and self-correcting. A [`NotFound`](ErrorKind::NotFound) is too: on
58/// macOS an operation against a slept accessory's stale characteristic handle
59/// reports it, and the reconnect re-discovers the handles.
60// By value for ergonomic `.map_err(be)`.
61#[allow(clippy::needless_pass_by_value)]
62pub(crate) fn be(e: bluest::Error) -> BleError {
63    match e.kind() {
64        ErrorKind::NotConnected
65        | ErrorKind::AdapterUnavailable
66        | ErrorKind::ConnectionFailed
67        | ErrorKind::ServiceChanged
68        | ErrorKind::NotReady
69        | ErrorKind::NotFound
70        | ErrorKind::Timeout => BleError::Disconnected,
71        _ => BleError::Backend(e.to_string()),
72    }
73}
74
75/// Whether an error means the link dropped (so reconnecting may recover).
76fn is_disconnect(e: &BleError) -> bool {
77    matches!(e, BleError::Disconnected)
78}
79
80/// The discovered structure of one service: its UUID and its characteristics'
81/// UUIDs (stable across reconnects, unlike the bluest handles).
82#[derive(Clone)]
83struct ServiceShape {
84    uuid: String,
85    char_uuids: Vec<String>,
86}
87
88/// A `GattConnection` over a connected `bluest` [`Device`] that reconnects and
89/// retries on a dropped link.
90pub struct BluestConnection {
91    adapter: Adapter,
92    device: Device,
93    /// Lowercased characteristic UUID -> the (current) bluest handle.
94    chars: Mutex<HashMap<String, Characteristic>>,
95    /// The service/characteristic UUID structure (stable across reconnects).
96    shape: Vec<ServiceShape>,
97    /// Increments on every reconnect — also the backstop count. A change since a
98    /// secure session was established means the accessory dropped that session.
99    generation: AtomicU64,
100    /// Coordinates the continuous advert scan with connects: on macOS
101    /// CoreBluetooth a connect cannot complete while a scan is running, so
102    /// `reconnect`/`disconnect` pause the scan for their duration.
103    scan_gate: Arc<ScanGate>,
104}
105
106impl BluestConnection {
107    /// Wrap an already-connected device, discovering its services and
108    /// characteristics.
109    ///
110    /// # Errors
111    /// Returns [`BleError::Backend`] on a bluest discovery failure.
112    pub async fn new(adapter: Adapter, device: Device) -> Result<Self> {
113        let (chars, shape) = Self::discover(&device).await?;
114        Ok(Self {
115            adapter,
116            device,
117            chars: Mutex::new(chars),
118            shape,
119            generation: AtomicU64::new(0),
120            scan_gate: ScanGate::new(),
121        })
122    }
123
124    async fn discover(
125        device: &Device,
126    ) -> Result<(HashMap<String, Characteristic>, Vec<ServiceShape>)> {
127        let mut chars = HashMap::new();
128        let mut shape = Vec::new();
129        for svc in device.discover_services().await.map_err(be)? {
130            let svc_uuid = svc.uuid().to_string().to_ascii_lowercase();
131            let is_protocol_info = svc_uuid == PROTOCOL_INFO_SERVICE;
132            let mut char_uuids = Vec::new();
133            for ch in svc.discover_characteristics().await.map_err(be)? {
134                let uuid = ch.uuid().to_string().to_ascii_lowercase();
135                char_uuids.push(uuid.clone());
136                // The Service-Signature char exists in every service and they all
137                // share one UUID; keep only the Protocol Information service's so
138                // the UUID-keyed handle map resolves the generate-broadcast-key
139                // target deterministically (and survives reconnects, unlike an
140                // iid-keyed map that would need a re-sweep).
141                if uuid == SERVICE_SIGNATURE_CHAR && !is_protocol_info {
142                    continue;
143                }
144                chars.insert(uuid, ch);
145            }
146            shape.push(ServiceShape {
147                uuid: svc.uuid().to_string(),
148                char_uuids,
149            });
150        }
151        Ok((chars, shape))
152    }
153
154    /// Re-establish the link and rebuild the characteristic handle map, advancing
155    /// the link [`generation`](Self::generation). The UUID structure
156    /// ([`shape`](Self::shape)) is unchanged.
157    async fn reconnect(&self) -> Result<()> {
158        self.generation.fetch_add(1, Ordering::SeqCst);
159        // Own the radio for the whole teardown + connect: on macOS
160        // CoreBluetooth a connect (or disconnect/wait_available) cannot
161        // complete while a scan is running. The guard resumes the scan when
162        // dropped — on success and on every error path alike.
163        let _scan_pause = self.scan_gate.pause().await;
164        let _ = tokio::time::timeout(TEARDOWN_TIMEOUT, async {
165            let _ = self.adapter.disconnect_device(&self.device).await;
166            let _ = self.adapter.wait_available().await;
167        })
168        .await;
169        // Bound the connect + service discovery: a connect attempted while a scan
170        // is running can wedge on macOS, so a timeout surfaces as a recoverable
171        // disconnect that the per-operation backstop retries rather than hanging.
172        let establish = async {
173            self.adapter
174                .connect_device(&self.device)
175                .await
176                .map_err(be)?;
177            Self::discover(&self.device).await
178        };
179        let (fresh, _shape) = tokio::time::timeout(CONNECT_TIMEOUT, establish)
180            .await
181            .map_err(|_| BleError::Disconnected)??;
182        *self.chars.lock().await = fresh;
183        Ok(())
184    }
185
186    /// Reconnect for one in-flight operation, giving up once a single operation
187    /// has forced [`MAX_OP_RECONNECTS`] reconnects without making progress (the
188    /// link will not stay up long enough to complete it). `attempts` is the
189    /// per-operation reconnect count, owned by the caller's retry loop — it does
190    /// not bound the connection's lifetime.
191    async fn reconnect_bounded(&self, attempts: &mut u32) -> Result<()> {
192        *attempts += 1;
193        if *attempts > MAX_OP_RECONNECTS {
194            return Err(BleError::Disconnected);
195        }
196        self.reconnect().await
197    }
198
199    /// Look up the current handle for a characteristic UUID.
200    async fn handle(&self, char_uuid: &str) -> Result<Characteristic> {
201        self.chars
202            .lock()
203            .await
204            .get(&char_uuid.to_ascii_lowercase())
205            .cloned()
206            .ok_or(BleError::MalformedPdu("gatt characteristic not found"))
207    }
208
209    /// Read a characteristic's HAP instance-id descriptor, reconnecting on drop.
210    async fn read_iid(&self, char_uuid: &str) -> Result<Option<u16>> {
211        let mut attempts = 0;
212        loop {
213            let ch = self.handle(char_uuid).await?;
214            let attempt = async {
215                let descriptors = ch.discover_descriptors().await.map_err(be)?;
216                let Some(desc) = descriptors.iter().find(|d| {
217                    d.uuid()
218                        .to_string()
219                        .eq_ignore_ascii_case(HAP_INSTANCE_ID_DESC)
220                }) else {
221                    return Ok(None);
222                };
223                Ok(u16_le(&desc.read().await.map_err(be)?))
224            }
225            .await;
226            match attempt {
227                Ok(v) => return Ok(v),
228                Err(ref e) if is_disconnect(e) => self.reconnect_bounded(&mut attempts).await?,
229                Err(e) => return Err(e),
230            }
231        }
232    }
233}
234
235#[async_trait]
236impl GattConnection for BluestConnection {
237    async fn instance_id(&self, char_uuid: &str) -> Result<u16> {
238        self.read_iid(char_uuid)
239            .await?
240            .ok_or(BleError::MalformedPdu("no instance id descriptor"))
241    }
242
243    async fn max_write(&self) -> usize {
244        // The MTU is connection-wide, so any characteristic's max write works.
245        let ch = self.chars.lock().await.values().next().cloned();
246        ch.and_then(|c| c.max_write_len().ok())
247            .map_or(crate::gatt::DEFAULT_FRAGMENT_SIZE, |n| n.clamp(20, 512))
248    }
249
250    async fn generation(&self) -> u64 {
251        self.generation.load(Ordering::SeqCst)
252    }
253
254    async fn write(&self, char_uuid: &str, value: &[u8]) -> Result<()> {
255        let mut attempts = 0;
256        loop {
257            let ch = self.handle(char_uuid).await?;
258            match ch.write(value).await.map_err(be) {
259                Ok(()) => return Ok(()),
260                Err(ref e) if is_disconnect(e) => self.reconnect_bounded(&mut attempts).await?,
261                Err(e) => return Err(e),
262            }
263        }
264    }
265
266    async fn read(&self, char_uuid: &str) -> Result<Vec<u8>> {
267        let mut attempts = 0;
268        loop {
269            let ch = self.handle(char_uuid).await?;
270            match ch.read().await.map_err(be) {
271                Ok(v) => return Ok(v),
272                Err(ref e) if is_disconnect(e) => self.reconnect_bounded(&mut attempts).await?,
273                Err(e) => return Err(e),
274            }
275        }
276    }
277
278    // Connected GATT notify is BEST-EFFORT: the spawned task ends when the
279    // notification stream ends (a link drop). It is deliberately NOT re-armed and
280    // does NOT reconnect — a sleepy accessory intentionally drops idle links, so
281    // auto-reconnecting here causes a reconnect storm (validated on hardware).
282    // Durable events come from the advertisement channels (broadcast +
283    // disconnected-event poll); the session re-verifies lazily on the next read.
284    async fn subscribe(&self, char_uuid: &str) -> Result<mpsc::Receiver<Vec<u8>>> {
285        let ch = self.handle(char_uuid).await?;
286        let (tx, rx) = mpsc::channel(16);
287        tokio::spawn(async move {
288            use tokio_stream::StreamExt as _;
289            if let Ok(mut stream) = ch.notify().await {
290                while let Some(item) = stream.next().await {
291                    let Ok(v) = item else { break };
292                    if tx.send(v).await.is_err() {
293                        break;
294                    }
295                }
296            }
297        });
298        Ok(rx)
299    }
300
301    async fn enumerate(&self) -> Result<Vec<GattService>> {
302        let mut services = Vec::new();
303        for svc in &self.shape {
304            let mut characteristics = Vec::new();
305            for char_uuid in &svc.char_uuids {
306                // The Service-Instance-ID characteristic is not a HAP
307                // characteristic; its value would need a paired read.
308                if char_uuid.eq_ignore_ascii_case(HAP_SERVICE_ID_CHAR) {
309                    continue;
310                }
311                // The Service-Signature char is a service-level signature, not a
312                // model characteristic — skip it (it also shares a UUID across
313                // services, so reading it here would yield duplicate iids).
314                if char_uuid.eq_ignore_ascii_case(SERVICE_SIGNATURE_CHAR) {
315                    continue;
316                }
317                // Per-characteristic resilient instance-id read: resumes the
318                // sweep across the device's periodic disconnects.
319                if let Some(iid) = self.read_iid(char_uuid).await? {
320                    characteristics.push(GattCharacteristic {
321                        uuid: char_uuid.clone(),
322                        iid,
323                    });
324                }
325            }
326            services.push(GattService {
327                uuid: svc.uuid.clone(),
328                iid: 0,
329                characteristics,
330            });
331        }
332        Ok(services)
333    }
334
335    async fn disconnect(&self) {
336        // Pause the scan for the teardown: on macOS a disconnect cannot
337        // complete while a scan is running.
338        let _scan_pause = self.scan_gate.pause().await;
339        let _ = tokio::time::timeout(
340            TEARDOWN_TIMEOUT,
341            self.adapter.disconnect_device(&self.device),
342        )
343        .await;
344    }
345}
346
347/// Apple's Bluetooth company identifier; HAP advertisements live under it.
348const APPLE_COMPANY_ID: u16 = 0x004C;
349
350#[async_trait]
351impl AdvertSource for BluestConnection {
352    /// Stream Apple HAP advertisements by running a continuous adapter scan.
353    ///
354    /// Spawns a background task that feeds every Apple (company id `0x004C`)
355    /// manufacturer-data frame into the returned channel. Forwarding is
356    /// best-effort: frames are dropped when the receiver falls behind, not
357    /// queued unboundedly, to ensure the task never blocks on backpressure
358    /// and can always respond to a pause request. While a connect owns the
359    /// radio (the [`ScanGate`] is paused) the task drops its scan stream and
360    /// restarts it on resume. The task stops for good when the receiver is
361    /// dropped or the adapter's scan stream ends.
362    ///
363    /// Intended for a single active watcher per connection: concurrent scan tasks
364    /// would share one scanning flag and corrupt the pause-ack protocol.
365    ///
366    /// # Errors
367    /// Returns [`crate::error::BleError`] on adapter/scan failures.
368    async fn watch_adverts(&self) -> Result<mpsc::Receiver<RawAdvert>> {
369        let adapter = self.adapter.clone();
370        let gate = self.scan_gate.clone();
371        let (tx, rx) = mpsc::channel(32);
372        tokio::spawn(async move {
373            use tokio_stream::StreamExt as _;
374            let mut pause = gate.pause_watch();
375            loop {
376                // Hold off while a connect owns the radio.
377                while *pause.borrow_and_update() {
378                    if pause.changed().await.is_err() {
379                        return;
380                    }
381                }
382                let Ok(mut scan) = adapter.scan(&[]).await else {
383                    return;
384                };
385                gate.set_scanning(true);
386                let stopped_for_pause = loop {
387                    tokio::select! {
388                        changed = pause.changed() => {
389                            match changed {
390                                Ok(()) if *pause.borrow_and_update() => break true,
391                                Ok(()) => {}
392                                Err(_) => break false,
393                            }
394                        }
395                        adv = scan.next() => {
396                            let Some(adv) = adv else { break false };
397                            let Some(md) = adv.adv_data.manufacturer_data else {
398                                continue;
399                            };
400                            if md.company_id != APPLE_COMPANY_ID {
401                                continue;
402                            }
403                            // Non-blocking send: a stalled consumer must not
404                            // wedge this task inside an await where it cannot
405                            // see a pause request. Adverts are a lossy,
406                            // repeating medium — dropping a frame under
407                            // backpressure is safe; holding the radio is not.
408                            match tx.try_send(RawAdvert {
409                                manufacturer_data: md.data,
410                            }) {
411                                Ok(()) | Err(mpsc::error::TrySendError::Full(_)) => {}
412                                Err(mpsc::error::TrySendError::Closed(_)) => {
413                                    break false; // receiver dropped — stop scanning
414                                }
415                            }
416                        }
417                    }
418                };
419                drop(scan);
420                gate.set_scanning(false);
421                if !stopped_for_pause {
422                    return;
423                }
424            }
425        });
426        Ok(rx)
427    }
428}
429
430#[cfg(test)]
431mod tests {
432    use super::*;
433
434    /// A slept accessory's stale handle surfaces as bluest `NotFound` on
435    /// macOS; it must classify as a recoverable disconnect so the supervisor
436    /// reconnects (safe only because reconnect pauses the scan and bounds the
437    /// connect).
438    #[test]
439    fn not_found_maps_to_disconnected() {
440        let e = bluest::Error::from(ErrorKind::NotFound);
441        assert!(matches!(be(e), BleError::Disconnected));
442    }
443}