webbluetooth 0.0.5

The Web Bluetooth API in Rust — Apple platforms, Linux, Android, Windows and the browser
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
//! `BluetoothDevice` — a device this process has been granted access to.

use crate::address::is_bluetooth_address;
use crate::error::Result;
use crate::gatt::RemoteGattServer;
use futures_channel::mpsc;
use futures_core::Stream;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};

/// The ATT MTU every LE link carries before any negotiation.
const ATT_DEFAULT_MTU: u16 = 23;

/// A device returned by [`crate::Bluetooth::request_device`].
///
/// Holding one grants access to the services that were requested, and nothing
/// else — the allowlist is fixed at the moment of the grant, exactly as a
/// browser fixes it when the user picks a device.
#[derive(Clone)]
pub struct BluetoothDevice {
    pub(crate) inner: Arc<crate::session::Session>,
    pub(crate) id: String,
}

impl BluetoothDevice {
    /// The per-host device identifier — `BluetoothDevice.id`.
    ///
    /// Stable for this machine and this peripheral across reboots. It is *not*
    /// the Bluetooth address: Apple never exposes that, and rotates this value
    /// per host, so two machines will not agree on it.
    pub fn id(&self) -> &str {
        &self.id
    }

    /// The device's name, if it advertised one.
    pub fn name(&self) -> Option<String> {
        self.inner.device_name(&self.id)
    }

    /// Watch this device's advertisements — `watchAdvertisements()`.
    ///
    /// The returned stream reports every packet from *this* device and nothing
    /// else, for as long as it is held. Useful for a peripheral whose payload
    /// lives in the advertisement rather than in a characteristic, and for
    /// noticing that a device has come back into range without connecting.
    ///
    /// The radio scan is shared, so this runs alongside a `request_device` and
    /// alongside any number of other watches.
    pub async fn watch_advertisements(&self) -> Result<crate::Advertisements> {
        self.inner.require_powered_on().await?;
        let (watcher, stream, restart) = self.inner.scan_hub().add(crate::scan::Want::Device {
            id: self.id.clone(),
            grant: self.inner.grant(&self.id),
        });
        if restart {
            if let Err(e) = self.inner.backend().set_radio_scanning(true) {
                self.inner.scan_hub().remove(watcher);
                return Err(e);
            }
        }
        // The web has no radio-wide scan to reference-count: advertisements
        // come from `watchAdvertisements` on one device, so the watch is
        // started here rather than by the hub.
        #[cfg(target_arch = "wasm32")]
        if let Err(e) = self.inner.watch_advertisements(&self.id, true).await {
            self.inner.scan_hub().remove(watcher);
            return Err(e);
        }
        Ok(crate::Advertisements {
            inner: self.inner.clone(),
            watcher,
            stream,
            device_id: self.id.clone(),
        })
    }

    /// Ask for a different connection interval.
    ///
    /// **Not part of Web Bluetooth.** Two platforms can ask —
    /// `BluetoothGatt.requestConnectionPriority` on Android, and
    /// `RequestPreferredConnectionParameters` on Windows 10 2004 or newer —
    /// and the rest return [`crate::Error::NotSupported`] with the reason:
    /// CoreBluetooth does not expose connection parameters at all, and BlueZ
    /// has no D-Bus API for them.
    ///
    /// Even where it works it is a request. The peripheral decides the
    /// interval, and neither platform reports what was agreed, so success here
    /// means the ask was made and nothing more.
    pub async fn request_connection_priority(
        &self,
        priority: crate::ConnectionPriority,
    ) -> Result<()> {
        self.inner
            .request_connection_priority(&self.id, priority)
            .await
    }

    /// Whether [`Self::watch_advertisements`] is running for this device —
    /// `BluetoothDevice.watchingAdvertisements`.
    ///
    /// True while the [`crate::Advertisements`] stream is alive, and false once
    /// it is dropped, since dropping it is what stops the watch.
    pub fn watching_advertisements(&self) -> bool {
        self.inner.scan_hub().is_watching_device(&self.id)
    }

    /// The GATT server on this device.
    pub fn gatt(&self) -> RemoteGattServer {
        RemoteGattServer {
            inner: self.inner.clone(),
            id: self.id.clone(),
        }
    }

    /// A stream that yields once per disconnection —
    /// `ongattserverdisconnected`.
    ///
    /// BLE links drop routinely, so treat this as expected rather than
    /// exceptional. Every service and characteristic handle taken before the
    /// disconnect is stale afterwards and will fail with `InvalidStateError`;
    /// reconnect and re-resolve them.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use webbluetooth::stream::StreamExt;
    /// # async fn example(device: webbluetooth::BluetoothDevice) -> webbluetooth::Result<()> {
    /// let mut disconnects = device.watch_disconnect();
    /// while disconnects.next().await.is_some() {
    ///     // Handles minted before the drop are stale; rediscover after
    ///     // reconnecting rather than reusing them.
    ///     device.gatt().connect().await?;
    /// }
    /// # Ok(()) }
    /// ```
    pub fn watch_disconnect(&self) -> DisconnectEvents {
        DisconnectEvents {
            rx: self.inner.watch_disconnect(&self.id),
        }
    }

    /// Signal strength in dBm. Requires an active connection.
    ///
    /// Not part of the Web Bluetooth API — CoreBluetooth offers it and it is
    /// useful, so it is here.
    pub async fn rssi(&self) -> Result<i32> {
        self.inner.read_rssi(&self.id).await
    }

    /// What the link actually negotiated — interval, latency and timeout.
    ///
    /// The counterpart to [`Self::request_connection_priority`], which asks;
    /// this reports what came back. Requires an active connection.
    ///
    /// `NotSupported` on every platform but Windows, which is the only one
    /// that hands the negotiated values to an application — and there only on
    /// Windows 10 2004 or newer, where `IBluetoothLEDevice6` exists.
    /// CoreBluetooth, BlueZ and Android all keep them inside the stack, and
    /// even `linux-hci` cannot see them: the kernel owns the link, and the
    /// values appear only in the HCI event that reports it coming up.
    pub async fn connection_parameters(&self) -> Result<crate::ConnectionParameters> {
        self.inner.connection_parameters(&self.id).await
    }

    /// Pair with this device, so encrypted attributes become readable.
    ///
    /// Not part of Web Bluetooth, and the omission is deliberate there: a
    /// browser pairs on the user's behalf when a peer demands it, and a page
    /// is never told. A library's caller *is* the application, so it gets to
    /// ask.
    ///
    /// This matters more than its absence from the standard suggests. A great
    /// many real devices — heart-rate straps, glucose meters, anything with a
    /// privacy requirement — mark their interesting characteristics as
    /// requiring encryption. Reading one without a bond fails with
    /// `insufficient authentication`, and no amount of retrying fixes it.
    ///
    /// What actually happens is the platform's business, and they differ more
    /// than usual:
    ///
    /// | platform | what `pair()` does |
    /// |---|---|
    /// | BlueZ | `org.bluez.Device1.Pair` — the daemon runs the ceremony |
    /// | Android | `createBond`, then waits for the bond to settle |
    /// | Windows | `DeviceInformationPairing.PairAsync` |
    /// | Apple | nothing: [`crate::Pairing::Implicit`], see below |
    /// | `linux-hci` | fails: there is no Security Manager without a daemon |
    ///
    /// On Apple this returns [`crate::Pairing::Implicit`] without doing anything,
    /// because there is nothing to do — CoreBluetooth exposes no pairing API
    /// at all. The system pairs when an encrypted attribute is touched and
    /// shows its own dialog. Reporting success would be a lie and reporting
    /// failure would be worse, since the caller's next read is exactly what
    /// they should do.
    ///
    /// A ceremony needing a passkey or a confirmation is the platform's to
    /// present. On BlueZ that means an agent must be registered — usually the
    /// desktop's — and without one, pairing a device that wants input fails.
    pub async fn pair(&self) -> Result<crate::Pairing> {
        self.inner.pair(&self.id).await
    }

    /// Whether this device is already bonded.
    ///
    /// `false` on platforms that do not say — Apple keeps bonding entirely to
    /// itself, so there is nothing to report and nothing a caller could do
    /// with it.
    pub async fn is_paired(&self) -> Result<bool> {
        self.inner.is_paired(&self.id).await
    }

    /// What the link is running at, in each direction.
    ///
    /// `NotSupported` where the platform does not say — which is most of them.
    /// Android reports it through `readPhy`, and Windows exposes it on
    /// `BluetoothLEDevice`; CoreBluetooth, BlueZ and the web all keep it
    /// inside the stack.
    pub async fn phy(&self) -> Result<crate::ConnectionPhy> {
        self.inner.phy(&self.id).await
    }

    /// Ask for a different physical layer, and report what the link settled
    /// on.
    ///
    /// The largest throughput lever on a connection: [`crate::Phy::Le2M`] doubles the
    /// symbol rate, so roughly twice as much fits in a connection event. Worth
    /// asking for before a firmware upload or a log download.
    ///
    /// A *request*, not a setting. Both ends and both controllers have to
    /// agree, and any of them may decline — 2M and coded are optional even in
    /// Bluetooth 5. The returned value is what the link actually runs at,
    /// which may be exactly what it was before; that is not an error, and
    /// checking it is the only way to know whether the ask took.
    ///
    /// Only Android can do this. Windows exposes the PHY but no way to choose
    /// one, CoreBluetooth exposes neither, and BlueZ has no D-Bus API for it.
    pub async fn set_preferred_phy(
        &self,
        tx: crate::Phy,
        rx: crate::Phy,
    ) -> Result<crate::ConnectionPhy> {
        self.inner.set_preferred_phy(&self.id, tx, rx).await
    }

    /// The negotiated ATT MTU, in bytes.
    ///
    /// Not part of Web Bluetooth, which hides the number and lets the
    /// implementation split long writes. It is exposed because sizing a
    /// payload to one PDU is the difference between one round trip and five,
    /// and because there is no way to work it out from the outside.
    ///
    /// Requires an active connection. Before negotiation — and on a platform
    /// that will not say — this is 23, the minimum every LE link guarantees.
    ///
    /// For the largest value that fits in a single write, prefer
    /// [`crate::RemoteGattCharacteristic::max_write_length`]: it is this minus
    /// the three-byte ATT header, and on Apple it is what CoreBluetooth
    /// reports directly rather than something derived.
    pub async fn mtu(&self) -> Result<u16> {
        // Derived from the write-without-response limit rather than the
        // with-response one: `withResponse` on Apple reports the 512-byte
        // attribute ceiling, which is a different number and not the MTU.
        let payload = self
            .inner
            .max_write_len(&self.id, crate::gatt::WriteType::WithoutResponse)?;
        Ok((payload as u16).saturating_add(3).max(ATT_DEFAULT_MTU))
    }

    /// Request a different ATT MTU and return the value currently known.
    ///
    /// The request is advisory: the peer and controller may choose a smaller
    /// value. Platforms that do not expose an MTU request return
    /// [`crate::Error::NotSupported`]. Call [`Self::mtu`] after the link has
    /// settled to observe the negotiated value.
    pub async fn request_mtu(&self, mtu: u16) -> Result<u16> {
        if !(23..=517).contains(&mtu) {
            return Err(crate::Error::InvalidModification(
                "ATT MTU must be between 23 and 517 bytes".into(),
            ));
        }
        self.inner.request_mtu(&self.id, mtu).await?;
        self.mtu().await
    }

    /// The device's Bluetooth address, where the platform reveals one.
    ///
    /// `None` on Apple, and only there: CoreBluetooth never exposes a
    /// peripheral's address, giving each one a system-generated UUID instead —
    /// which is what [`Self::id`] returns there. Everywhere else the id *is*
    /// the address and this returns it parsed back out.
    ///
    /// Not part of Web Bluetooth, which deliberately has no address: an
    /// address is a stable identifier for a physical thing, which is the
    /// tracking vector the UUID indirection exists to remove.
    pub fn address(&self) -> Option<String> {
        is_bluetooth_address(&self.id).then(|| self.id.to_uppercase())
    }

    /// Open an L2CAP connection-oriented channel to this device.
    ///
    /// Absent on Windows, which has no such API — see [`crate::L2CAP`].
    #[cfg(l2cap)]
    ///
    /// A byte pipe with no attribute-size ceiling and no ATT round trip per
    /// write — the right tool for a firmware image or a stream. Not part of
    /// Web Bluetooth. Requires an active connection, and a peer that has
    /// published the PSM.
    pub async fn open_l2cap_channel(&self, psm: crate::Psm) -> Result<crate::L2capChannel> {
        let target = self.inner.l2cap_target(&self.id, psm).await?;
        crate::l2cap::from_target(target, psm)
    }

    /// Open an RFCOMM stream on a Bluetooth Classic server channel.
    #[cfg(all(feature = "rfcomm", target_os = "linux"))]
    pub async fn open_rfcomm_channel(&self, channel: u8) -> Result<crate::RfcommChannel> {
        let address = self.address().ok_or_else(|| {
            crate::Error::NotSupported("RFCOMM requires a platform Bluetooth address".into())
        })?;
        crate::rfcomm::open(&address, channel)
    }

    /// Open Linux RFCOMM with an explicit Classic security requirement.
    #[cfg(all(feature = "rfcomm", target_os = "linux"))]
    pub async fn open_rfcomm_channel_with_security(
        &self,
        channel: u8,
        security: crate::ClassicSecurity,
    ) -> Result<crate::RfcommChannel> {
        let address = self.address().ok_or_else(|| {
            crate::Error::NotSupported("RFCOMM requires a platform Bluetooth address".into())
        })?;
        crate::rfcomm::open_with_security(&address, channel, security)
    }

    /// Open an Android RFCOMM service by its 128-bit service UUID.
    #[cfg(all(feature = "rfcomm", target_os = "android"))]
    pub async fn open_rfcomm_service(&self, service_uuid: &str) -> Result<crate::RfcommChannel> {
        let (socket, peer) = self.inner.rfcomm_target(&self.id, service_uuid).await?;
        crate::rfcomm::open_android(socket, peer)
    }

    /// Open an Android RFCOMM connection for a profile's SIG service UUID.
    ///
    /// This opens the profile transport only. Profile-specific negotiation,
    /// codecs, and state machines remain the responsibility of the caller.
    #[cfg(all(feature = "profiles", feature = "rfcomm", target_os = "android"))]
    pub async fn open_profile_rfcomm(
        &self,
        profile: crate::Profile,
    ) -> Result<crate::RfcommChannel> {
        let uuid = profile.service_uuid().ok_or_else(|| {
            crate::Error::NotSupported("this profile has no RFCOMM service UUID".into())
        })?;
        self.open_rfcomm_service(uuid.as_str()).await
    }

    /// Open a Linux BlueZ profile by querying SDP for its RFCOMM channel.
    #[cfg(all(
        feature = "profiles",
        feature = "rfcomm",
        target_os = "linux",
        not(feature = "linux-hci")
    ))]
    pub async fn open_profile_rfcomm(
        &self,
        profile: crate::Profile,
    ) -> Result<crate::RfcommChannel> {
        let service = profile.service_uuid().ok_or_else(|| {
            crate::Error::NotSupported("this profile has no RFCOMM service UUID".into())
        })?;
        let address = self.address().ok_or_else(|| {
            crate::Error::NotSupported("RFCOMM requires a platform Bluetooth address".into())
        })?;
        // A blocking SDP exchange over its own L2CAP socket; BlueZ's backend
        // has no SDP call to route it through.
        let records =
            webbluetooth_linux::sdp::query(&address, service).map_err(crate::Error::Network)?;
        let channel = records
            .iter()
            .find_map(webbluetooth_core::SdpServiceRecord::rfcomm_channel)
            .ok_or_else(|| crate::Error::NotFound("SDP record has no RFCOMM channel".into()))?;
        crate::rfcomm::open(&address, channel)
    }

    /// Open a Linux HFP/HSP AT session over the profile's SDP RFCOMM channel.
    #[cfg(all(
        feature = "profiles",
        feature = "rfcomm",
        target_os = "linux",
        not(feature = "linux-hci")
    ))]
    pub async fn open_hfp_session(&self) -> Result<webbluetooth_linux::hfp::HfpSession> {
        let channel = self.open_profile_rfcomm(crate::Profile::Hfp).await?;
        Ok(webbluetooth_linux::hfp::HfpSession::new(channel))
    }

    /// Open a Linux AVRCP pass-through session over SDP/RFCOMM.
    #[cfg(all(
        feature = "profiles",
        feature = "rfcomm",
        target_os = "linux",
        not(feature = "linux-hci")
    ))]
    pub async fn open_avrcp_session(&self) -> Result<webbluetooth_linux::avrcp::AvrcpSession> {
        let channel = self.open_profile_rfcomm(crate::Profile::Avrcp).await?;
        Ok(webbluetooth_linux::avrcp::AvrcpSession::new(channel))
    }

    /// Open a Linux PAN profile over its SDP Classic L2CAP PSM.
    #[cfg(all(
        feature = "profiles",
        feature = "classic-l2cap",
        target_os = "linux",
        not(feature = "linux-hci")
    ))]
    pub async fn open_pan(&self) -> Result<crate::ClassicL2capChannel> {
        self.open_profile_l2cap(crate::Profile::Pan).await
    }

    /// Open a Linux PAN/BNEP session over SDP-resolved Classic L2CAP.
    #[cfg(all(
        feature = "profiles",
        feature = "classic-l2cap",
        target_os = "linux",
        not(feature = "linux-hci")
    ))]
    pub async fn open_pan_session(&self) -> Result<webbluetooth_linux::pan::PanSession> {
        Ok(webbluetooth_linux::pan::PanSession::new(
            self.open_pan().await?,
        ))
    }

    /// Open a Linux DUN profile over its SDP RFCOMM channel.
    #[cfg(all(
        feature = "profiles",
        feature = "rfcomm",
        target_os = "linux",
        not(feature = "linux-hci")
    ))]
    pub async fn open_dun(&self) -> Result<crate::RfcommChannel> {
        self.open_profile_rfcomm(crate::Profile::Dun).await
    }

    /// Open a Linux DUN AT session over SDP/RFCOMM.
    #[cfg(all(
        feature = "profiles",
        feature = "rfcomm",
        target_os = "linux",
        not(feature = "linux-hci")
    ))]
    pub async fn open_dun_session(&self) -> Result<webbluetooth_linux::dun::DunSession> {
        let channel = self.open_dun().await?;
        Ok(webbluetooth_linux::dun::DunSession::new(channel))
    }

    /// Open a Linux OBEX Object Push profile over its SDP RFCOMM channel.
    #[cfg(all(
        feature = "profiles",
        feature = "rfcomm",
        target_os = "linux",
        not(feature = "linux-hci")
    ))]
    pub async fn open_obex(&self) -> Result<crate::RfcommChannel> {
        self.open_profile_rfcomm(crate::Profile::Obex).await
    }

    /// Open a Linux OBEX FTP profile over its SDP RFCOMM channel.
    #[cfg(all(
        feature = "profiles",
        feature = "rfcomm",
        target_os = "linux",
        not(feature = "linux-hci")
    ))]
    pub async fn open_obex_ftp(&self) -> Result<crate::RfcommChannel> {
        self.open_profile_rfcomm(crate::Profile::Ftp).await
    }

    /// Open a Linux OBEX Object Push session.
    #[cfg(all(
        feature = "profiles",
        feature = "rfcomm",
        target_os = "linux",
        not(feature = "linux-hci")
    ))]
    pub async fn open_obex_session(&self) -> Result<webbluetooth_linux::obex::ObexSession> {
        let channel = self.open_obex().await?;
        Ok(webbluetooth_linux::obex::ObexSession::new(channel))
    }

    /// Open a Linux OBEX FTP session.
    #[cfg(all(
        feature = "profiles",
        feature = "rfcomm",
        target_os = "linux",
        not(feature = "linux-hci")
    ))]
    pub async fn open_obex_ftp_session(&self) -> Result<webbluetooth_linux::obex::ObexSession> {
        let channel = self.open_obex_ftp().await?;
        Ok(webbluetooth_linux::obex::ObexSession::new(channel))
    }

    /// Open a Linux BlueZ profile by querying SDP for its Classic L2CAP PSM.
    #[cfg(all(
        feature = "profiles",
        feature = "classic-l2cap",
        target_os = "linux",
        not(feature = "linux-hci")
    ))]
    pub async fn open_profile_l2cap(
        &self,
        profile: crate::Profile,
    ) -> Result<crate::ClassicL2capChannel> {
        let service = profile.service_uuid().ok_or_else(|| {
            crate::Error::NotSupported("this profile has no Classic service UUID".into())
        })?;
        let address = self.address().ok_or_else(|| {
            crate::Error::NotSupported("Classic L2CAP requires a Bluetooth address".into())
        })?;
        // A blocking SDP exchange over its own L2CAP socket; BlueZ's backend
        // has no SDP call to route it through.
        let records =
            webbluetooth_linux::sdp::query(&address, service).map_err(crate::Error::Network)?;
        let psm = records
            .iter()
            .find_map(webbluetooth_core::SdpServiceRecord::l2cap_psm)
            .and_then(crate::ClassicPsm::new)
            .ok_or_else(|| crate::Error::NotFound("SDP record has no Classic L2CAP PSM".into()))?;
        crate::classic_l2cap::open(&address, psm)
    }

    /// Open a Windows profile transport using its SIG service UUID.
    #[cfg(all(feature = "profiles", feature = "rfcomm", target_os = "windows"))]
    pub async fn open_profile_rfcomm(
        &self,
        profile: crate::Profile,
    ) -> Result<crate::RfcommChannel> {
        let uuid = profile.service_uuid().ok_or_else(|| {
            crate::Error::NotSupported("this profile has no RFCOMM service UUID".into())
        })?;
        self.open_rfcomm_service(uuid.as_str()).await
    }

    /// Open an RFCOMM stream on a Bluetooth Classic server channel, on macOS.
    ///
    /// For a dual-mode device: one reached over LE through CoreBluetooth that
    /// also serves RFCOMM over Classic. CoreBluetooth hides the address and
    /// IOBluetooth, which owns Classic, has never heard of this device's
    /// identifier — so the two are matched by **name**, against the devices
    /// paired with this Mac. That is a heuristic and it is the only bridge
    /// there is: two paired devices with one name are indistinguishable here.
    /// With an address in hand, use [`crate::Bluetooth::open_rfcomm_channel`]
    /// instead, which has no such ambiguity.
    ///
    /// Many dual-mode devices refuse the Classic link while the LE one is up;
    /// [`RemoteGattServer::disconnect_and_wait`] is for that.
    ///
    /// [`RemoteGattServer::disconnect_and_wait`]: crate::RemoteGattServer::disconnect_and_wait
    #[cfg(all(feature = "rfcomm", target_os = "macos"))]
    pub async fn open_rfcomm_channel(&self, channel: u8) -> Result<crate::RfcommChannel> {
        let name = self.name().ok_or_else(|| {
            crate::Error::NotSupported(
                "this device has no name to find its Bluetooth Classic side by".into(),
            )
        })?;
        crate::rfcomm::open_macos_name(&name, channel).await
    }

    /// Open a Windows RFCOMM server channel through Winsock `AF_BTH`.
    #[cfg(all(feature = "rfcomm", target_os = "windows"))]
    pub async fn open_rfcomm_channel(&self, channel: u8) -> Result<crate::RfcommChannel> {
        let address = self.address().ok_or_else(|| {
            crate::Error::NotSupported("RFCOMM requires a Bluetooth address".into())
        })?;
        crate::rfcomm::open_windows(&address, channel)
    }

    /// Open a Windows RFCOMM profile by its SDP service UUID.
    #[cfg(all(feature = "rfcomm", target_os = "windows"))]
    pub async fn open_rfcomm_service(&self, service_uuid: &str) -> Result<crate::RfcommChannel> {
        let address = self.address().ok_or_else(|| {
            crate::Error::NotSupported("RFCOMM requires a platform Bluetooth address".into())
        })?;
        crate::rfcomm::open_windows_service(&address, service_uuid)
    }

    /// Open a Bluetooth Classic L2CAP channel on a Protocol/Service Multiplexer.
    #[cfg(all(feature = "classic-l2cap", target_os = "linux"))]
    pub async fn open_classic_l2cap_channel(
        &self,
        psm: crate::ClassicPsm,
    ) -> Result<crate::ClassicL2capChannel> {
        let address = self.address().ok_or_else(|| {
            crate::Error::NotSupported("Classic L2CAP requires a Bluetooth address".into())
        })?;
        crate::classic_l2cap::open(&address, psm)
    }

    /// Open a Linux Classic HID host connection.
    #[cfg(all(feature = "profiles", feature = "classic-l2cap", target_os = "linux"))]
    pub async fn open_hid_host(&self) -> Result<webbluetooth_linux::hid_host::HidHost> {
        let address = self.address().ok_or_else(|| {
            crate::Error::NotSupported("HID host requires a Bluetooth address".into())
        })?;
        webbluetooth_linux::hid_host::HidHost::connect(&address).await
    }

    /// Open Linux Classic L2CAP with an explicit security requirement.
    #[cfg(all(feature = "classic-l2cap", target_os = "linux"))]
    pub async fn open_classic_l2cap_with_security(
        &self,
        psm: crate::ClassicPsm,
        security: crate::ClassicSecurity,
    ) -> Result<crate::ClassicL2capChannel> {
        let address = self.address().ok_or_else(|| {
            crate::Error::NotSupported("Classic L2CAP requires a Bluetooth address".into())
        })?;
        crate::classic_l2cap::open_with_security(&address, psm, security)
    }

    /// Open an Android Bluetooth Classic L2CAP socket on a PSM.
    #[cfg(all(feature = "classic-l2cap", target_os = "android"))]
    pub async fn open_classic_l2cap_psm(
        &self,
        psm: crate::ClassicPsm,
    ) -> Result<crate::ClassicL2capChannel> {
        let (socket, peer) = self.inner.classic_l2cap_target(&self.id, psm.get()).await?;
        crate::classic_l2cap::open_android(socket, psm, peer)
    }

    /// Open a Windows Bluetooth Classic L2CAP PSM through WinSock `AF_BTH`.
    #[cfg(all(feature = "classic-l2cap", target_os = "windows"))]
    pub async fn open_classic_l2cap_channel(
        &self,
        psm: crate::ClassicPsm,
    ) -> Result<crate::ClassicL2capChannel> {
        let address = self.address().ok_or_else(|| {
            crate::Error::NotSupported("Classic L2CAP requires a Bluetooth address".into())
        })?;
        crate::classic_l2cap_windows::open(&address, psm)
    }

    /// Revoke this process's access — `BluetoothDevice.forget()`.
    ///
    /// Disconnects if connected, and drops the grant, so a later
    /// `request_device` must go through the chooser again.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # fn example(device: webbluetooth::BluetoothDevice) {
    /// // Revokes the grant and consumes the device — `self`, not `&self`,
    /// // because every handle under it is invalid afterwards.
    /// device.forget();
    /// # }
    /// ```
    pub fn forget(self) {
        self.inner.forget(&self.id);
        // "Remove device from storage". Doing only the first half would revoke
        // the grant for this run and hand it straight back on the next one.
        self.inner.persist_grants();
    }
}

impl std::fmt::Debug for BluetoothDevice {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BluetoothDevice")
            .field("id", &self.id)
            .field("name", &self.name())
            .field("connected", &self.inner.is_connected(&self.id))
            .finish()
    }
}

/// Yields `()` each time the device disconnects.
pub struct DisconnectEvents {
    rx: mpsc::UnboundedReceiver<()>,
}

impl Stream for DisconnectEvents {
    type Item = ();
    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<()>> {
        Pin::new(&mut self.rx).poll_next(cx)
    }
}

impl std::fmt::Debug for DisconnectEvents {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DisconnectEvents").finish_non_exhaustive()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The distinction [`BluetoothDevice::address`] rests on: everywhere but
    /// Apple the id is an address, and on Apple it is a UUID.
    #[test]
    fn an_address_is_told_apart_from_a_platform_uuid() {
        assert!(is_bluetooth_address("AA:BB:CC:DD:EE:FF"));
        assert!(is_bluetooth_address("00:00:00:00:00:00"));
        assert!(is_bluetooth_address("aa:bb:cc:dd:ee:ff"));

        // CoreBluetooth's identifiers, which must not be reported as addresses.
        assert!(!is_bluetooth_address(
            "6E3C8F1A-2B4D-4E5F-8A9B-0C1D2E3F4A5B"
        ));
        // Near misses.
        assert!(!is_bluetooth_address("AA:BB:CC:DD:EE"));
        assert!(!is_bluetooth_address("AA:BB:CC:DD:EE:FF:00"));
        assert!(!is_bluetooth_address("AA-BB-CC-DD-EE-FF"));
        assert!(!is_bluetooth_address("AA:BB:CC:DD:EE:GG"));
        assert!(!is_bluetooth_address("A:BB:CC:DD:EE:FF"));
        assert!(!is_bluetooth_address(""));
    }
}