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
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
//! # The Web Bluetooth API, in Rust, on macOS and iOS
//!
//! A faithful port of [Web Bluetooth](https://webbluetoothcg.github.io/web-bluetooth/)
//! — `requestDevice`, `gatt.connect()`, `getPrimaryService`, `readValue`,
//! `startNotifications` — over CoreBluetooth. The JavaScript API's promises
//! become `async fn`s and its events become `Stream`s; everything else keeps
//! its name, so a port reads like the original.
//!
//! ```no_run
//! use webbluetooth::prelude::*;
//! use webbluetooth::uuid::{characteristics, services};
//!
//! # async fn example() -> webbluetooth::Result<()> {
//! let bluetooth = Bluetooth::new();
//!
//! let device = bluetooth
//!     .request_device(
//!         RequestDeviceOptions::new()
//!             .filter(DeviceFilter::new().service(services::HEART_RATE)?)
//!             .optional_service(services::BATTERY_SERVICE)?,
//!     )
//!     .await?;
//!
//! println!("connecting to {}", device.name().unwrap_or_else(|| device.id().into()));
//! let gatt = device.gatt();
//! gatt.connect().await?;
//!
//! let service = gatt.get_primary_service(services::HEART_RATE).await?;
//! let measurement = service
//!     .get_characteristic(characteristics::HEART_RATE_MEASUREMENT)
//!     .await?;
//!
//! let mut beats = measurement.start_notifications().await?;
//! while let Some(value) = beats.next().await {
//!     println!("{} bpm", value[1]);
//! }
//! # Ok(())
//! # }
//! ```
//!
//! # What is different from a browser
//!
//! **The chooser is yours.** `requestDevice()` is defined around a user gesture
//! and a picker dialog, and that consent step is the reason the API is safe to
//! expose. A library has no chrome, so it is a trait: see [`DeviceChooser`].
//! The default, [`chooser::FirstMatch`], takes the first match automatically —
//! convenient, and a deliberate removal of that consent step. Use
//! `chooser::TerminalChooser` (feature `terminal-chooser`) or your own
//! implementation for anything user-facing.
//!
//! **Everything else about the security model is kept.** The
//! [GATT blocklist](blocklist) is vendored from the Web Bluetooth Community
//! Group registry and enforced; the per-device service allowlist from
//! `filters` + `optional_services` is enforced on every
//! `get_primary_service`; blocklisted attributes are filtered out of discovery
//! rather than reported and refused.
//!
//! **No device addresses.** [`BluetoothDevice::id`] is CoreBluetooth's per-host
//! identifier, not a BD_ADDR — Apple does not expose hardware addresses, and
//! the value differs between machines for the same peripheral.
//!
//! # Authorization
//!
//! Bluetooth is TCC-gated. A process with no `NSBluetoothAlwaysUsageDescription`
//! is reported [`Availability::Unauthorized`] and **is not prompted**, so a bare
//! `cargo run` binary silently sees no adapter. See the README for how to embed
//! an `Info.plist` in a CLI binary and what an app bundle needs.
//!
//! # How it works
//!
//! There is no Swift, no Objective-C source, and no build-time code generation:
//! CoreBluetooth is an Objective-C framework, so `webbluetooth-apple` synthesises
//! the `CBCentralManagerDelegate` class at *run time* with
//! `objc_allocateClassPair`, installing Rust `extern "C"` functions as its
//! method implementations. Callbacks are delivered on a private
//! `dispatch_queue`, so this works in a plain `fn main()` with no `NSRunLoop`.
//!
//! ## License
//! MIT — Copyright © 2025 [Eugene Hauptmann](https://github.com/eugenehp)

// Every public item carries documentation. This is the crate people read, and
// an undocumented method on it is one whose contract lives in somebody's head
// — the same failure the surface tests exist to prevent, one level up.
#![warn(missing_docs)]

// The portable model lives in `webbluetooth-core`, which the backends share.
// Re-exported here under the names it always had, so `webbluetooth::uuid` and
// `webbluetooth::filter` mean what they meant before there was a second crate.
pub use webbluetooth_core::{
    adapter, backlog, blocklist, chooser, error, filter, grants, timer, uuid,
};
#[cfg(feature = "profiles")]
pub use webbluetooth_core::{
    negotiate_a2dp, negotiate_sbc_parameters, A2dpCapability, A2dpCodec, A2dpConfiguration,
    A2dpNegotiationError, SbcAllocation, SbcChannelMode, SbcConfiguration,
};
#[cfg(feature = "profiles")]
pub use webbluetooth_core::{
    parse_obex_header, DunState, ObexError, ObexHeader, ObexOperation, ObexPacket, PanRole,
};
#[cfg(feature = "profiles")]
pub use webbluetooth_core::{PanControlMessage, PanError, PanFrame, PanPacketType};
// Not public, and not previously: a backend and the GATT tree both need these,
// a caller does not.
use webbluetooth_core::{address, restoration, scan};
/// Bluetooth Classic L2CAP channels.
#[cfg(all(
    feature = "classic-l2cap",
    any(target_os = "linux", target_os = "android")
))]
pub mod classic_l2cap;
#[cfg(all(feature = "classic-l2cap", target_os = "windows"))]
pub mod classic_l2cap_windows;
/// L2CAP connection-oriented channels.
///
/// Absent on Windows, which exposes no such API. Branch on [`L2CAP`].
#[cfg(l2cap)]
pub mod l2cap;
/// Publishing a GATT server.
///
/// Absent where the platform cannot do it: the CoreBluetooth initialisers this
/// needs are `API_UNAVAILABLE` on watchOS, tvOS and visionOS, and no Linux
/// backend implements it. Branch on [`PERIPHERAL_ROLE`].
#[cfg(peripheral_role)]
pub mod peripheral;
/// Linux raw HCI ACL/SCO transport.
#[cfg(all(
    target_os = "linux",
    any(feature = "raw-acl", feature = "raw-sco", feature = "le-audio")
))]
pub mod raw_hci;
/// Bluetooth Classic RFCOMM byte streams.
#[cfg(feature = "rfcomm")]
pub mod rfcomm;

#[cfg(target_os = "android")]
use webbluetooth_android::backend;
/// The platform engine. Exactly one of these compiles.
///
/// All of them provide the same inherent methods, so everything above — the
/// GATT objects, the allowlist, the blocklist, the chooser — is shared
/// verbatim.
/// They are deliberately *not* a trait: only one ever exists in a build, so a
/// trait would buy dynamic dispatch nobody needs.
/// The platform adapter. Exactly one of these is linked.
///
/// Each lives in its platform's own crate, beside the FFI it is written
/// against: `webbluetooth-apple`'s `backend` is CoreBluetooth expressed as the
/// portable model, and so on for the other five. What is left here is the
/// choice between them.
///
/// They are deliberately not a trait: only one exists in a build, so a trait
/// would buy dynamic dispatch nobody needs, and three of these methods take
/// `self: &Arc<Self>`, which a trait cannot declare. What makes "the same
/// surface" checkable instead is `webbluetooth-core`'s `backend_surface` test,
/// which reads all six and compares them — including the five this build is
/// not compiling.
#[cfg(target_vendor = "apple")]
use webbluetooth_apple::backend;
#[cfg(all(target_os = "linux", not(feature = "linux-hci")))]
use webbluetooth_linux::backend;
#[cfg(all(target_os = "linux", feature = "linux-hci"))]
use webbluetooth_linux::backend_hci as backend;
#[cfg(target_arch = "wasm32")]
use webbluetooth_wasm::backend;
#[cfg(target_os = "windows")]
use webbluetooth_windows::backend;
mod device;
mod gatt;
mod session;
#[cfg(not(target_arch = "wasm32"))]
mod run_loop;
#[cfg(not(target_arch = "wasm32"))]
pub use run_loop::run_with_main_run_loop;

use std::sync::Arc;

pub use adapter::{
    AdapterInfo, ConnectionParameters, ConnectionPhy, ConnectionPriority, Pairing, Phy,
};
pub use chooser::{Candidate, Candidates, DeviceChooser};
pub use device::{BluetoothDevice, DisconnectEvents};
pub use error::{Authorization, Availability, Error, Result};
pub use filter::{Advertisement, DataPrefix, DeviceFilter, RequestDeviceOptions};
pub use gatt::{
    CharacteristicProperties, Notifications, RemoteGattCharacteristic, RemoteGattDescriptor,
    RemoteGattServer, RemoteGattService, Tagged, WriteType,
};
#[cfg(all(
    target_os = "linux",
    any(feature = "raw-acl", feature = "raw-sco", feature = "le-audio")
))]
pub use raw_hci::RawHciSocket;
#[cfg(feature = "classic")]
pub use webbluetooth_core::classic::{
    BluetoothAddress, ClassOfDevice, ClassicAddressError, ClassicPsm, ClassicSecurity,
    RfcommChannel as ClassicRfcommChannel,
};
#[cfg(feature = "classic")]
pub use webbluetooth_core::sdp::{SdpDataElement, SdpError, SdpServiceRecord};
#[cfg(feature = "raw-acl")]
pub use webbluetooth_core::AclPacket;
#[cfg(any(
    all(feature = "classic", any(target_os = "windows", target_os = "android", all(target_os = "linux", not(feature = "linux-hci")))),
    all(feature = "apple-classic", target_os = "macos")
))]
pub use webbluetooth_core::ClassicDevice;
#[cfg(feature = "le-audio")]
pub use webbluetooth_core::IsoPacket;
#[cfg(feature = "raw-sco")]
pub use webbluetooth_core::ScoPacket;
#[cfg(feature = "profiles")]
pub use webbluetooth_core::{
    absolute_volume, negotiate_sbc_capabilities, playback_status, AvrcpCommand, AvrcpEvent,
    AvrcpMetadata, AvrcpPassThrough, PlaybackStatus,
};
#[cfg(feature = "profiles")]
pub use webbluetooth_core::{
    encode_command, AtError, AtLine, AtParser, CallCommand, CallInfo, CallState,
};
#[cfg(feature = "profiles")]
pub use webbluetooth_core::{
    AvdtpCapabilitiesError, AvdtpDiscoverError, AvdtpEndpointType, AvdtpError, AvdtpMediaType,
    AvdtpMessageType, AvdtpPacketType, AvdtpResponse, AvdtpResponseResult, AvdtpSbcCapability,
    AvdtpServiceCategory, AvdtpSignalIdentifier, AvdtpSignalingPacket,
    AvdtpStreamEndpointDescriptor, AvdtpStreamEndpointId,
};
#[cfg(feature = "le-audio")]
pub use webbluetooth_core::{
    CodecError, IsoConfiguration, IsoMetadata, IsoStream, Lc3Codec, Lc3Frame,
};
#[cfg(feature = "profiles")]
pub use webbluetooth_core::{
    HidError, HidPacket, InputValue, ReportDescriptor, ReportField, TransactionType,
};
#[cfg(feature = "mesh")]
pub use webbluetooth_core::{
    MeshAddress, MeshNetworkPdu, NetworkHeader, ProvisioningEvent, ProvisioningFailure,
    ProvisioningSession, ProvisioningState,
};
#[cfg(feature = "profiles")]
pub use webbluetooth_core::{Profile, ProfileRequest, ProfileRole};
pub use webbluetooth_core::{Protocol, ProtocolCapabilities};
#[cfg(feature = "profiles")]
pub use webbluetooth_core::{SbcFrame, SbcMediaError, SbcMediaPacket};

/// Streams, and the pieces needed to work with several at once.
///
/// Every event source in this crate is a [`Stream`](futures_core::Stream), and
/// a device with more than one interesting characteristic gives you several —
/// so merging them is not an exotic requirement, it is the ordinary case. The
/// tool for that is `select_all`, which lives in `futures-util`, and requiring
/// a caller to depend on `futures-util` to combine streams this crate handed
/// them is the same gap that left `BoxFuture` unreachable for
/// [`DeviceChooser`] implementors.
///
/// ```no_run
/// # use webbluetooth::stream::{select_all, StreamExt};
/// # async fn example(cs: Vec<webbluetooth::RemoteGattCharacteristic>)
/// # -> webbluetooth::Result<()> {
/// let mut subscriptions = Vec::new();
/// for characteristic in cs {
///     subscriptions.push(characteristic.start_notifications().await?.tagged());
/// }
///
/// let mut values = select_all(subscriptions);
/// while let Some((uuid, value)) = values.next().await {
///     println!("{uuid}: {} bytes", value.len());
/// }
///
/// // And the merged set can still say which subscription dropped anything.
/// for subscription in values.iter() {
///     if subscription.lost() > 0 {
///         println!("{}: lost {}", subscription.uuid(), subscription.lost());
///     }
/// }
/// # Ok(()) }
/// ```
pub mod stream {
    pub use futures_core::Stream;
    pub use futures_util::stream::{select_all, BoxStream, SelectAll};
    pub use futures_util::StreamExt;
}

/// Futures, and the combinators these APIs are used with.
///
/// The same reasoning as [`stream`]: "stop when the device disconnects" is the
/// correct shape for almost every read loop here, and it is written with
/// `select` over the notification stream and
/// [`watch_disconnect`](BluetoothDevice::watch_disconnect). Every example in
/// this repository had to reach into `futures-util` for that, which is a
/// dependency a caller should not need in order to use two things this crate
/// handed them.
///
/// ```no_run
/// # use webbluetooth::future::{select, Either};
/// # use webbluetooth::stream::StreamExt;
/// # async fn example(
/// #     device: webbluetooth::BluetoothDevice,
/// #     characteristic: webbluetooth::RemoteGattCharacteristic,
/// # ) -> webbluetooth::Result<()> {
/// let mut values = characteristic.start_notifications().await?;
/// let mut disconnected = device.watch_disconnect();
///
/// loop {
///     let next_value = std::pin::pin!(values.next());
///     let next_drop = std::pin::pin!(disconnected.next());
///     match select(next_value, next_drop).await {
///         Either::Left((Some(value), _)) => println!("{value:02x?}"),
///         // The stream ended, or the link dropped first.
///         Either::Left((None, _)) | Either::Right(_) => break,
///     }
/// }
/// # Ok(()) }
/// ```
pub mod future {
    pub use futures_util::future::{join, select, BoxFuture, Either};
}

/// The Web Bluetooth-compatible portion of this crate's API.
///
/// Enable the `public` feature and import from this module when an application
/// wants its dependency boundary to advertise the standard surface explicitly.
/// Native extensions remain available from the root crate when desired.
#[cfg(feature = "public")]
pub mod public {
    pub use crate::stream::{Stream, StreamExt};
    pub use crate::uuid::{BluetoothUuid, IntoUuid};
    pub use crate::{
        Availability, Bluetooth, BluetoothDevice, DataPrefix, DeviceFilter, Error, Grant,
        LeScanOptions, Notifications, RemoteGattCharacteristic, RemoteGattDescriptor,
        RemoteGattServer, RemoteGattService, RequestDeviceOptions, Result, Tagged,
    };
}
#[cfg(l2cap)]
pub use l2cap::{L2capChannel, Psm};
/// What a device has been granted access to.
///
/// Re-exported because it is reachable from this crate's own surface —
/// [`Bluetooth::remembered_grant`] returns one and [`grants::Stored`] holds
/// one — and a type a caller can be handed but cannot name is a type they
/// cannot put in a variable, a struct field or a function signature.
pub use webbluetooth_core::registry::Grant;

/// A PSM. Defined even where channels are not, so signatures stay portable.
#[cfg(not(l2cap))]
pub type Psm = u16;

/// Whether L2CAP channels are available on the platform this was built for.
///
/// `false` only on Windows.
pub const L2CAP: bool = cfg!(l2cap);

/// Whether Bluetooth Classic APIs were enabled for this build.
pub const CLASSIC: bool = cfg!(feature = "classic");

/// Whether RFCOMM APIs were enabled for this build.
pub const RFCOMM: bool = cfg!(feature = "rfcomm");

/// Whether profile APIs were enabled for this build.
pub const PROFILES: bool = cfg!(feature = "profiles");

/// Whether Bluetooth Mesh APIs were enabled for this build.
pub const MESH: bool = cfg!(feature = "mesh");

/// Whether raw ACL transport APIs were enabled for this build.
pub const RAW_ACL: bool = cfg!(feature = "raw-acl");

/// Whether raw SCO transport APIs were enabled for this build.
pub const RAW_SCO: bool = cfg!(feature = "raw-sco");

/// Whether LE Audio APIs were enabled for this build.
pub const LE_AUDIO: bool = cfg!(feature = "le-audio");

/// Whether the macOS IOBluetooth Classic backend was explicitly requested.
///
/// `rfcomm` turns it on, since RFCOMM on a Mac is IOBluetooth's; on its own it
/// provides `Bluetooth::paired_classic_devices` (macOS builds only, so not a
/// link: the docs are built for other targets too).
///
/// The backend is not available on non-macOS Apple targets or browsers.
pub const APPLE_CLASSIC: bool = cfg!(all(feature = "apple-classic", target_os = "macos"));

/// Starting the Android backend.
///
/// Android has no ambient way to reach a `Context`, so one must be supplied
/// before any Bluetooth call — from `JNI_OnLoad`, or from an Activity.
#[cfg(target_os = "android")]
pub mod android {
    pub use crate::backend::init;
    pub use webbluetooth_android::jni::{JObject, Vm};
}
#[cfg(all(feature = "classic-l2cap", target_os = "linux"))]
pub use classic_l2cap::ClassicL2capChannel;
#[cfg(all(feature = "classic-l2cap", target_os = "linux"))]
pub use classic_l2cap::ClassicL2capListener;
#[cfg(all(feature = "classic-l2cap", target_os = "android"))]
pub use classic_l2cap::{ClassicL2capChannel, ClassicL2capListener};
#[cfg(all(feature = "classic-l2cap", target_os = "windows"))]
pub use classic_l2cap_windows::ClassicL2capChannel;
#[cfg(all(feature = "classic-l2cap", target_os = "windows"))]
pub use classic_l2cap_windows::ClassicL2capListener;
#[cfg(peripheral_role)]
pub use peripheral::Peripheral;
pub use restoration::Restoration;
#[cfg(all(
    feature = "rfcomm",
    any(
        target_os = "linux",
        target_os = "android",
        target_os = "windows",
        target_os = "macos"
    )
))]
pub use rfcomm::RfcommChannel;
#[cfg(all(feature = "rfcomm", target_os = "linux"))]
pub use rfcomm::RfcommListener;
#[cfg(all(feature = "rfcomm", target_os = "android"))]
pub use rfcomm::RfcommListener;
#[cfg(all(feature = "rfcomm", target_os = "windows"))]
pub use rfcomm::RfcommListener;
pub use timer::{sleep, timeout};
#[cfg(all(feature = "profiles", feature = "classic-l2cap", target_os = "linux"))]
pub use webbluetooth_linux::a2dp::A2dpSession;

/// Everything a program needs in scope, in one import.
///
/// The reason this exists is `StreamExt`. Notifications, advertisements and
/// disconnects are all [`Stream`](futures_core::Stream)s, and a stream has no
/// `.next()` without that
/// trait in scope — which, before this module, meant a caller had to add
/// `futures-util` to their own `Cargo.toml` to use the first example in the
/// README. It is re-exported here so that `webbluetooth` on its own is enough.
///
/// ```no_run
/// use webbluetooth::prelude::*;
///
/// # async fn example(c: webbluetooth::RemoteGattCharacteristic) -> webbluetooth::Result<()> {
/// let mut values = c.start_notifications().await?;
/// while let Some(value) = values.next().await {
///     println!("{value:?}");
/// }
/// # Ok(()) }
/// ```
///
/// [`Error`] and [`Result`] are deliberately **not** here. A glob-imported
/// `Result` alias shadows `std::result::Result`, so one `Result<T, E>`
/// anywhere else in the file stops compiling — which happened to this
/// workspace's own iOS harness within minutes of the first attempt. Name them:
/// `webbluetooth::Result<()>`.
///
/// You still need an executor — this crate does not bring one, so that it
/// works with whichever you already have.
pub mod prelude {
    // Writing a chooser needs all three: the trait, the stream it is handed,
    // and the `BoxFuture` its one method returns. Leaving the last two out
    // meant implementing the crate's own extension point pulled `futures-util`
    // into the caller's Cargo.toml — the same thing the paragraph above says
    // this module exists to prevent.
    pub use crate::chooser::{BoxFuture, Candidate, Candidates, DeviceChooser};
    pub use crate::uuid::{BluetoothUuid, IntoUuid};
    pub use crate::{
        Availability, Bluetooth, BluetoothDevice, DataPrefix, DeviceFilter, Grant, LeScanOptions,
        RequestDeviceOptions,
    };
    pub use crate::{
        RemoteGattCharacteristic, RemoteGattDescriptor, RemoteGattServer, RemoteGattService,
    };
    pub use futures_core::Stream;
    pub use futures_util::StreamExt;
}
pub use uuid::{BluetoothUuid, IntoUuid};

use backend::Inner;

/// The entry point — `navigator.bluetooth`.
///
/// Owns one `CBCentralManager`. Cheap to clone; every clone shares the same
/// adapter, device grants and connections.
#[derive(Clone)]
pub struct Bluetooth {
    inner: Arc<session::Session>,
    chooser: Arc<dyn DeviceChooser>,
}

impl Bluetooth {
    /// Query full SDP service records from a Linux Classic peer.
    #[cfg(all(feature = "rfcomm", target_os = "linux", not(feature = "linux-hci")))]
    pub async fn query_sdp(
        &self,
        address: &str,
        service: BluetoothUuid,
    ) -> Result<Vec<SdpServiceRecord>> {
        webbluetooth_linux::sdp::query(address, service).map_err(Error::Network)
    }

    /// The Bluetooth Classic devices paired with this Mac.
    ///
    /// Answered by IOBluetooth from what the system already knows: no inquiry
    /// runs, and a device is listed whether or not it is in range. This is
    /// where the address [`Self::open_rfcomm_channel`] takes comes from —
    /// CoreBluetooth, and so everything else on this type, never reveals one.
    #[cfg(all(feature = "apple-classic", target_os = "macos"))]
    pub async fn paired_classic_devices(&self) -> Result<Vec<ClassicDevice>> {
        webbluetooth_apple::classic::paired_devices()
    }

    /// Open an RFCOMM stream to a Bluetooth address on macOS.
    ///
    /// On this type rather than on [`BluetoothDevice`] because a Mac has no
    /// `BluetoothDevice` with an address: those come from CoreBluetooth, which
    /// hides it. The device must already be paired, and the binary signed
    /// with the `com.apple.security.device.bluetooth` entitlement.
    ///
    /// For a dual-mode device already held as a [`BluetoothDevice`], see
    /// [`BluetoothDevice::open_rfcomm_channel`], which finds it by name.
    ///
    /// ```no_run
    /// # use webbluetooth::stream::StreamExt;
    /// # async fn example(bluetooth: webbluetooth::Bluetooth) -> webbluetooth::Result<()> {
    /// let channel = bluetooth.open_rfcomm_channel("AA:BB:CC:DD:EE:FF", 1).await?;
    /// let mut incoming = channel.take_incoming().expect("first take");
    /// while let Some(bytes) = incoming.next().await {
    ///     println!("{} bytes", bytes.len());
    /// }
    /// # Ok(()) }
    /// ```
    #[cfg(all(feature = "rfcomm", target_os = "macos"))]
    pub async fn open_rfcomm_channel(&self, address: &str, channel: u8) -> Result<RfcommChannel> {
        rfcomm::open_macos_address(address, channel).await
    }

    /// Open an RFCOMM stream to a Bluetooth address (`"AA:BB:CC:DD:EE:FF"`) on a server
    /// channel without a [`BluetoothDevice`], for a Classic-only peer that never appears in
    /// an LE scan. The socket connects directly; BlueZ handles any pairing.
    #[cfg(all(feature = "rfcomm", target_os = "linux"))]
    pub async fn open_rfcomm_channel(&self, address: &str, channel: u8) -> Result<RfcommChannel> {
        rfcomm::open(address, channel)
    }

    /// Open an RFCOMM stream to a Bluetooth address on a server channel through Winsock
    /// `AF_BTH`, without a [`BluetoothDevice`].
    #[cfg(all(feature = "rfcomm", target_os = "windows"))]
    pub async fn open_rfcomm_channel(&self, address: &str, channel: u8) -> Result<RfcommChannel> {
        rfcomm::open_windows(address, channel)
    }

    /// The paired (bonded) Bluetooth Classic devices, the same way on every platform that has a list: IOBluetooth's
    /// paired devices on macOS (needs `apple-classic`, which `rfcomm` turns on), BlueZ's on Linux, Android's bonded
    /// devices, and the remembered ones of the Windows device list. One entry per address. Where a platform reports
    /// only addresses (Linux, Android) the rest of each entry is unknown: no name, not connected.
    ///
    /// The addresses are what [`Self::open_rfcomm_channel`] takes.
    #[cfg(any(
        all(feature = "apple-classic", target_os = "macos"),
        all(feature = "classic", any(target_os = "windows", target_os = "android", all(target_os = "linux", not(feature = "linux-hci"))))
    ))]
    pub async fn paired_devices(&self) -> Result<Vec<ClassicDevice>> {
        #[cfg(target_os = "macos")]
        {
            self.paired_classic_devices().await
        }
        #[cfg(target_os = "windows")]
        {
            Ok(self.classic_devices().await?.into_iter().filter(|d| d.bonded).collect())
        }
        #[cfg(any(target_os = "linux", target_os = "android"))]
        {
            let mut out: Vec<ClassicDevice> = Vec::new();
            for a in self.bonded_classic_devices().await? {
                let address = a.parse().ok();
                if address.is_some() && out.iter().any(|d| d.address == address) {
                    continue;
                }
                out.push(ClassicDevice { address, name: None, class_of_device: None, bonded: true, authenticated: false, connected: false });
            }
            Ok(out)
        }
    }

    /// Discover Bluetooth Classic devices through the Windows native API.
    #[cfg(all(feature = "classic", target_os = "windows"))]
    pub async fn classic_devices(&self) -> Result<Vec<ClassicDevice>> {
        self.inner.backend().classic_devices().await
    }

    /// List paired Bluetooth Classic device addresses from BlueZ.
    #[cfg(all(feature = "classic", target_os = "linux", not(feature = "linux-hci")))]
    pub async fn bonded_classic_devices(&self) -> Result<Vec<String>> {
        self.inner.require_powered_on().await?;
        self.inner.backend().bonded_classic_devices().await
    }

    /// Register an RFCOMM Classic profile with BlueZ.
    #[cfg(all(feature = "rfcomm", target_os = "linux", not(feature = "linux-hci")))]
    pub async fn register_classic_profile(
        &self,
        service: BluetoothUuid,
        security: ClassicSecurity,
    ) -> Result<webbluetooth_linux::classic_profile::ProfileRegistration> {
        self.inner
            .backend()
            .register_classic_profile(service, security)
            .await
    }

    /// Register an RFCOMM Classic profile on a specific BlueZ server channel.
    #[cfg(all(feature = "rfcomm", target_os = "linux", not(feature = "linux-hci")))]
    pub async fn register_classic_profile_channel(
        &self,
        service: BluetoothUuid,
        channel: u8,
        security: ClassicSecurity,
    ) -> Result<webbluetooth_linux::classic_profile::ProfileRegistration> {
        self.inner
            .backend()
            .register_classic_profile_channel(service, channel, security)
            .await
    }

    /// Register a SIG profile over RFCOMM with Linux BlueZ.
    ///
    /// This registers the transport/profile endpoint only. A2DP, HFP, HID,
    /// and other profile state machines remain platform-specific.
    #[cfg(all(
        feature = "profiles",
        feature = "rfcomm",
        target_os = "linux",
        not(feature = "linux-hci")
    ))]
    pub async fn register_profile(
        &self,
        profile: Profile,
        security: ClassicSecurity,
    ) -> Result<webbluetooth_linux::classic_profile::ProfileRegistration> {
        let service = profile
            .service_uuid()
            .ok_or_else(|| Error::NotSupported("this profile has no RFCOMM service UUID".into()))?;
        self.register_classic_profile(service, security).await
    }

    /// Register a Classic L2CAP profile with BlueZ.
    #[cfg(all(
        feature = "classic-l2cap",
        target_os = "linux",
        not(feature = "linux-hci")
    ))]
    pub async fn register_classic_l2cap_profile(
        &self,
        service: BluetoothUuid,
        psm: ClassicPsm,
        security: ClassicSecurity,
    ) -> Result<webbluetooth_linux::classic_profile::ProfileRegistration> {
        self.inner
            .backend()
            .register_classic_l2cap_profile(service, psm, security)
            .await
    }

    /// Read Classic/LE service UUIDs reported by an Android device.
    #[cfg(all(feature = "classic", target_os = "android"))]
    pub async fn classic_service_uuids(&self, id: &str) -> Result<Vec<BluetoothUuid>> {
        self.inner.backend().classic_service_uuids(id).await
    }

    /// Read Classic service UUIDs reported by a BlueZ device object.
    #[cfg(all(feature = "classic", target_os = "linux", not(feature = "linux-hci")))]
    pub async fn classic_service_uuids(&self, id: &str) -> Result<Vec<BluetoothUuid>> {
        self.inner.backend().classic_service_uuids(id).await
    }

    /// List paired Android Bluetooth Classic device addresses.
    #[cfg(all(feature = "classic", target_os = "android"))]
    pub async fn bonded_classic_devices(&self) -> Result<Vec<String>> {
        self.inner.require_powered_on().await?;
        self.inner.backend().bonded_classic_devices().await
    }

    /// Listen for Windows Bluetooth Classic L2CAP connections on a PSM.
    #[cfg(all(feature = "classic-l2cap", target_os = "windows"))]
    pub fn listen_classic_l2cap(&self, psm: ClassicPsm) -> Result<ClassicL2capListener> {
        classic_l2cap_windows::listen(psm)
    }

    /// Listen for Windows RFCOMM connections on a server channel.
    #[cfg(all(feature = "rfcomm", target_os = "windows"))]
    pub fn listen_rfcomm(&self, channel: u8) -> Result<RfcommListener> {
        rfcomm::listen_windows(channel)
    }

    /// Listen for Android Bluetooth Classic L2CAP connections.
    #[cfg(all(feature = "classic-l2cap", target_os = "android"))]
    pub async fn listen_classic_l2cap(&self, secure: bool) -> Result<ClassicL2capListener> {
        self.inner.require_powered_on().await?;
        classic_l2cap::listen_android(self, secure).await
    }

    /// Listen for Android RFCOMM connections registered under a service UUID.
    #[cfg(all(feature = "rfcomm", target_os = "android"))]
    pub async fn listen_rfcomm_service(
        &self,
        name: &str,
        service_uuid: &str,
    ) -> Result<RfcommListener> {
        self.inner.require_powered_on().await?;
        rfcomm::listen_android(self, name, service_uuid).await
    }

    /// Open a Linux raw ACL HCI socket for controller `device`.
    #[cfg(all(target_os = "linux", feature = "raw-acl"))]
    pub fn open_raw_acl(&self, device: u16) -> Result<RawHciSocket> {
        raw_hci::open_acl(device)
    }

    /// Open a Linux raw SCO/eSCO HCI socket for controller `device`.
    #[cfg(all(target_os = "linux", feature = "raw-sco"))]
    pub fn open_raw_sco(&self, device: u16) -> Result<RawHciSocket> {
        raw_hci::open_sco(device)
    }

    /// Open a Linux raw ISO HCI socket for LE Audio CIS/BIS packets.
    #[cfg(all(target_os = "linux", feature = "le-audio"))]
    pub fn open_raw_iso(&self, device: u16) -> Result<RawHciSocket> {
        raw_hci::open_iso(device)
    }

    /// Protocol capabilities compiled for this target and feature set.
    pub const fn protocol_capabilities() -> ProtocolCapabilities {
        ProtocolCapabilities::current()
    }
    /// Listen for Linux Bluetooth Classic L2CAP connections on a PSM.
    #[cfg(all(feature = "classic-l2cap", target_os = "linux"))]
    pub fn listen_classic_l2cap(&self, psm: ClassicPsm) -> Result<ClassicL2capListener> {
        classic_l2cap::listen(psm)
    }

    /// Listen for Linux RFCOMM connections on a server channel.
    #[cfg(all(feature = "rfcomm", target_os = "linux"))]
    pub fn listen_rfcomm(&self, channel: u8) -> Result<RfcommListener> {
        rfcomm::listen(channel)
    }

    /// Open the default adapter, choosing devices with
    /// [`chooser::FirstMatch`].
    ///
    /// Returns immediately; the adapter settles asynchronously, and every
    /// operation waits for it. Use [`Bluetooth::availability`] to find out
    /// whether Bluetooth is actually usable.
    ///
    /// # Call this once and clone it
    ///
    /// Each call opens a *separate* adapter session: its own
    /// `CBCentralManager`, its own grants, its own connections. A
    /// [`BluetoothDevice`] carries the session it was found through, so a
    /// device discovered by one `Bluetooth` cannot be connected by another —
    /// two `new()` calls in one program is the shape of that bug, and it
    /// looks like a device that simply will not connect.
    ///
    /// A browser has exactly one `navigator.bluetooth` and no way to ask for
    /// a second, which is the model to follow: make one, clone it. Cloning
    /// shares everything; `new()` shares nothing. [`Bluetooth::shared`] is
    /// that model already done.
    ///
    /// ```no_run
    /// # use webbluetooth::Bluetooth;
    /// let bluetooth = Bluetooth::new();
    /// let elsewhere = bluetooth.clone(); // same radio, same grants
    /// # let _ = elsewhere;
    /// ```
    pub fn new() -> Self {
        Self::with_chooser(chooser::FirstMatch::default())
    }

    /// The process-wide adapter session — the analogue of
    /// `navigator.bluetooth`.
    ///
    /// A browser exposes exactly one `Bluetooth` and gives a page no way to
    /// ask for a second. This is that: the first call opens an adapter, every
    /// call after it hands back a clone of the same one, and they all share
    /// the radio, the grants and the connections.
    ///
    /// Prefer it to [`new`](Self::new) unless you have a reason not to.
    /// Devices are only usable through the session that found them, so two
    /// sessions in one program is a bug that presents as a device which
    /// simply will not connect — and reaching for a global is exactly what a
    /// caller ends up writing by hand instead.
    ///
    /// It chooses devices with [`chooser::FirstMatch`], because a shared
    /// session cannot ask each caller which chooser it wanted. For anything
    /// user-facing, build one with [`with_chooser`](Self::with_chooser) and
    /// clone *that* around your program.
    ///
    /// ```no_run
    /// # use webbluetooth::Bluetooth;
    /// // Anywhere in the program, without threading a handle through.
    /// let bluetooth = Bluetooth::shared();
    /// # let _ = bluetooth;
    /// ```
    pub fn shared() -> Self {
        static SHARED: std::sync::OnceLock<Bluetooth> = std::sync::OnceLock::new();
        SHARED.get_or_init(Self::new).clone()
    }

    /// Open the default adapter with a specific chooser.
    pub fn with_chooser(chooser: impl DeviceChooser) -> Self {
        Self {
            inner: session::Session::new(Inner::new(false), None),
            chooser: Arc::new(chooser),
        }
    }

    /// Open the default adapter, keeping grants in a file.
    ///
    /// The specification models permissions as *storage*: `getDevices()` reads
    /// it and `requestDevice` adds to it, which is what lets a page reconnect
    /// to something the user chose last week without asking again. Without
    /// this, grants live for the run and go with it.
    ///
    /// Opting in has a consequence worth being deliberate about: the file is
    /// the permission. A later run — or anything else that can read it —
    /// reaches those devices and those services with no chooser and nobody
    /// present. It is written `0600`, and where you put it is part of the
    /// decision. See [`grants`].
    ///
    /// Losing the file costs a trip through the chooser and nothing else.
    pub fn with_grants(store: grants::GrantStore, chooser: impl DeviceChooser) -> Self {
        Self {
            inner: session::Session::new(Inner::new(false), Some(Arc::new(store))),
            chooser: Arc::new(chooser),
        }
    }

    /// What was granted to a device in an earlier run, if anything.
    ///
    /// Held apart from the registry on purpose. The registry holds *devices* —
    /// each with whatever handle its backend needs to reach one — and a
    /// remembered permission has no handle yet, because nothing has found the
    /// device. The specification draws the same line: storage holds
    /// `allowedDevices`, and a `BluetoothDevice` appears when the device does.
    ///
    /// [`Self::adopt_device`] is what turns one back into a usable device.
    pub fn remembered_grant(&self, id: &str) -> Option<Grant> {
        let store = self.inner.grants.as_ref()?;
        store.load().get(id).map(|stored| stored.grant.clone())
    }

    /// Every device this instance has been granted in any run.
    ///
    /// `navigator.bluetooth.getDevices()` is defined against the permission
    /// store, so with one configured this is the union of what is live now and
    /// what was remembered. Being listed does not mean a device is in range,
    /// connected, or even still exists — the specification says as much.
    pub fn remembered_devices(&self) -> Vec<String> {
        let mut ids = self.inner.granted_devices();
        if let Some(store) = &self.inner.grants {
            for id in store.load().into_keys() {
                if !ids.contains(&id) {
                    ids.push(id);
                }
            }
        }
        ids.sort();
        ids
    }

    /// Open the adapter with state preservation and restoration.
    ///
    /// See [`Restoration`] — and read its platform note before relying on this.
    pub fn with_restoration(restoration: Restoration, chooser: impl DeviceChooser) -> Self {
        Self {
            inner: session::Session::new(
                Inner::with_restoration(
                    false,
                    Some(&restoration.identifier),
                    restoration.allowed_services.into_iter().collect(),
                ),
                None,
            ),
            chooser: Arc::new(chooser),
        }
    }

    /// What the system preserved across a relaunch, if this adapter was created
    /// with [`Bluetooth::with_restoration`] and was in fact restored.
    ///
    /// Waits for the adapter to settle first, because
    /// `centralManager:willRestoreState:` is delivered before the first state
    /// report — checking too early would always see `None`.
    pub async fn restored_session(&self) -> Option<RestoredSession> {
        let _ = self.inner.settled_state().await;
        let restored = self.inner.restored()?;
        Some(RestoredSession {
            devices: restored
                .device_ids
                .into_iter()
                .map(|id| BluetoothDevice {
                    inner: self.inner.clone(),
                    id,
                })
                .collect(),
            scan_services: restored.scan_services,
            scan_allow_duplicates: restored.scan_allow_duplicates,
        })
    }

    /// Ask the system to offer to turn Bluetooth on if it is off
    /// (`CBCentralManagerOptionShowPowerAlertKey`).
    ///
    /// Off by default, because a browser never raises that dialog.
    pub fn with_power_alert(chooser: impl DeviceChooser) -> Self {
        Self {
            inner: session::Session::new(Inner::new(true), None),
            chooser: Arc::new(chooser),
        }
    }

    /// `navigator.bluetooth.getAvailability()` — is there a usable radio?
    pub async fn get_availability(&self) -> bool {
        self.availability().await.is_ok()
    }

    /// Why Bluetooth is not usable, if it is not.
    ///
    /// Waits for the adapter's first state report, so this is the right thing
    /// to call at startup to distinguish "no radio" from "not yet known".
    /// # Example
    ///
    /// ```no_run
    /// # use webbluetooth::{Availability, Bluetooth};
    /// # async fn example() {
    /// match Bluetooth::new().availability().await {
    ///     Ok(()) => println!("usable"),
    ///     Err(Availability::PoweredOff) => println!("turn Bluetooth on"),
    ///     Err(Availability::Unauthorized) => println!("this process may not use it"),
    ///     Err(why) => println!("unusable: {why:?}"),
    /// }
    /// # }
    /// ```
    pub async fn availability(&self) -> std::result::Result<(), Availability> {
        match self.inner.require_powered_on().await {
            Ok(()) => Ok(()),
            Err(Error::NotAvailable(a)) => Err(a),
            Err(_) => Err(Availability::Unknown),
        }
    }

    // ── Controllers ─────────────────────────────────────────────────────
    //
    // Outside the standard: a browser has one Bluetooth and no way to ask for
    // another. See the [`adapter`] module for what each platform can say.

    /// Every Bluetooth controller this system is managing.
    ///
    /// Platforms that cannot enumerate report exactly one, named
    /// [`adapter::DEFAULT_ADAPTER`], rather than an empty list — so a caller
    /// that iterates gets the same shape everywhere.
    pub async fn adapters(&self) -> Result<Vec<AdapterInfo>> {
        self.inner.adapters().await
    }

    /// The controller this instance is using.
    pub async fn adapter(&self) -> Result<AdapterInfo> {
        self.inner.adapter().await
    }

    /// Use a different controller from here on.
    ///
    /// Takes an [`AdapterInfo::id`]. Fails with `NotFound` if no such
    /// controller exists, and `NotSupported` on a platform that has no way to
    /// choose — rather than silently carrying on with the wrong radio, which
    /// is the failure worth preventing: a two-adapter test rig that quietly
    /// puts both ends on the same controller passes while testing nothing.
    ///
    /// Anything already connected stays on the controller it was connected
    /// through; this changes what later scans and connections use.
    pub async fn select_adapter(&self, id: &str) -> Result<()> {
        self.inner.select_adapter(id).await
    }

    /// Grant access to a device you already know, without scanning or asking.
    ///
    /// Outside the standard, and deliberately so: Web Bluetooth has no such
    /// call because a web page must not be able to reach a device the user did
    /// not pick. This crate is not a web page — a headless bridge with a
    /// device address in its config has nobody to ask — so the capability
    /// exists, under a name that says it is a grant rather than a lookup.
    ///
    /// `id` is what [`BluetoothDevice::id`] would return: a Bluetooth address
    /// everywhere except Apple, where it is the system-assigned UUID. The
    /// grant is taken from `options` exactly as [`Self::request_device`] takes
    /// it, so `optional_services` is what decides which services become
    /// reachable; the filters are not used, since nothing is being matched.
    ///
    /// This does not connect, and does not require the device to be in range
    /// or advertising — call [`BluetoothDevice::gatt`] and connect as usual.
    /// It fails with `NotFound` if the platform cannot resolve the identifier
    /// at all.
    pub async fn adopt_device(&self, id: &str, grant: impl Into<Grant>) -> Result<BluetoothDevice> {
        let mut grant = grant.into();
        grant.validate()?;
        // Anything remembered for this device is merged in, so adopting with
        // a narrow grant does not silently discard a wider one the user
        // already gave — the same rule `insert` follows for a re-grant.
        if let Some(store) = &self.inner.grants {
            if let Some(stored) = store.load().get(id) {
                grant = stored.grant.union(&grant);
            }
        }
        let id = self.inner.backend().adopt_device(id, grant).await?;
        self.inner.persist_grants();
        Ok(BluetoothDevice {
            inner: self.inner.clone(),
            id,
        })
    }

    /// Grant access to a device a scan just reported.
    ///
    /// [`Bluetooth::request_le_scan`] reports advertisements and grants
    /// nothing, by design — it is `requestLEScan`, not `requestDevice`. This
    /// is how a sighting becomes something connectable without going back
    /// through a chooser: the same grant [`Self::adopt_device`] takes, applied
    /// to a [`Candidate`] rather than to an identifier copied out of one.
    ///
    /// Outside the standard for the same reason `adopt_device` is, and subject
    /// to the same caveat: adopting re-resolves the device through the
    /// platform, which can fail for something the scan reported a moment ago.
    /// # Example
    ///
    /// ```no_run
    /// # use futures_util::StreamExt;
    /// # use webbluetooth::{Bluetooth, Grant, LeScanOptions};
    /// # use webbluetooth::uuid::services;
    /// # async fn example() -> webbluetooth::Result<()> {
    /// let bluetooth = Bluetooth::new();
    /// let mut scan = bluetooth
    ///     .request_le_scan(LeScanOptions::accept_all_advertisements())
    ///     .await?;
    ///
    /// while let Some(sighting) = scan.next().await {
    ///     if sighting.name.as_deref() == Some("the one") {
    ///         let grant = Grant::new().service(services::HEART_RATE)?;
    ///         let device = bluetooth.adopt_candidate(&sighting, grant).await?;
    ///         device.gatt().connect().await?;
    ///         break;
    ///     }
    /// }
    /// # Ok(()) }
    /// ```
    pub async fn adopt_candidate(
        &self,
        candidate: &Candidate,
        grant: impl Into<Grant>,
    ) -> Result<BluetoothDevice> {
        self.adopt_device(&candidate.id, grant).await
    }

    /// `navigator.bluetooth.requestDevice()` — scan, choose, and grant.
    ///
    /// Scans with the request's filters, hands matches to this instance's
    /// chooser, and grants access to whichever it returns. The grant covers
    /// exactly the services named in `filters` and `optional_services`.
    /// # Example
    ///
    /// ```no_run
    /// # use webbluetooth::{Bluetooth, DeviceFilter, RequestDeviceOptions};
    /// # use webbluetooth::uuid::services;
    /// # async fn example() -> webbluetooth::Result<()> {
    /// let bluetooth = Bluetooth::new();
    /// let device = bluetooth
    ///     .request_device(
    ///         RequestDeviceOptions::new()
    ///             .filter(DeviceFilter::new().service(services::HEART_RATE)?)
    ///             // Reachable afterwards, but not filtered on.
    ///             .optional_service(services::BATTERY_SERVICE)?,
    ///     )
    ///     .await?;
    ///
    /// println!("{}", device.name().unwrap_or_else(|| "(unnamed)".into()));
    /// # Ok(()) }
    /// ```
    pub async fn request_device(&self, options: RequestDeviceOptions) -> Result<BluetoothDevice> {
        self.request_device_with(options, self.chooser.as_ref())
            .await
    }

    /// As [`Bluetooth::request_device`], with a chooser for this call only.
    pub async fn request_device_with(
        &self,
        options: RequestDeviceOptions,
        chooser: &dyn DeviceChooser,
    ) -> Result<BluetoothDevice> {
        let id = self
            .inner
            .backend()
            .request_device(options, chooser)
            .await?;
        // "Add device to storage", which is where the specification puts it:
        // a grant is a permission, and a permission outlives the call that
        // created it. Both request paths end here, so both record it.
        self.inner.persist_grants();
        Ok(BluetoothDevice {
            inner: self.inner.clone(),
            id,
        })
    }

    /// `navigator.bluetooth.getDevices()` — devices already granted.
    ///
    /// The grant lives as long as this `Bluetooth` does. Unlike a browser,
    /// nothing is persisted across process restarts, so this is empty at
    /// startup.
    /// Watch advertisements without asking for a device — `requestLEScan()`.
    ///
    /// Unlike [`Bluetooth::request_device`] this grants nothing: it reports
    /// advertisements and hands back no [`BluetoothDevice`]. Filters here
    /// choose what is *reported*, and a scan runs until the returned
    /// [`LeScan`] is stopped or dropped.
    ///
    /// The radio scan is shared, so this coexists with a `request_device` in
    /// flight and with any number of [`BluetoothDevice::watch_advertisements`].
    /// # Example
    ///
    /// ```no_run
    /// # use futures_util::StreamExt;
    /// # use webbluetooth::{Bluetooth, LeScanOptions};
    /// # async fn example() -> webbluetooth::Result<()> {
    /// let bluetooth = Bluetooth::new();
    /// let mut scan = bluetooth.request_le_scan(LeScanOptions::accept_all_advertisements()).await?;
    ///
    /// while let Some(sighting) = scan.next().await {
    ///     match sighting.rssi() {
    ///         Some(dbm) => println!("{} at {dbm} dBm", sighting.id),
    ///         None => println!("{}, no signal strength reported", sighting.id),
    ///     }
    /// }
    /// # Ok(()) }
    /// ```
    pub async fn request_le_scan(&self, options: LeScanOptions) -> Result<LeScan> {
        options.validate()?;
        self.inner.require_powered_on().await?;

        let (watcher, stream, restart) = self.inner.scan_hub().add(scan::Want::Scan {
            options: options.as_request(),
            keep_repeated: options.keep_repeated_devices,
        });
        if restart {
            if let Err(e) = self.inner.backend().set_radio_scanning(true) {
                self.inner.scan_hub().remove(watcher);
                return Err(e);
            }
        }
        Ok(LeScan {
            inner: self.inner.clone(),
            watcher,
            stream,
            options,
        })
    }

    /// Watch for availability changing — `Bluetooth.onavailabilitychanged`.
    ///
    /// The first value is the state at the time of the call, so a caller does
    /// not have to ask separately and then race the first change. See
    /// [`AvailabilityEvents`] for why this is polled.
    /// # Example
    ///
    /// ```no_run
    /// # use futures_util::StreamExt;
    /// # use webbluetooth::Bluetooth;
    /// # async fn example() {
    /// let bluetooth = Bluetooth::new();
    /// let mut changes = bluetooth.watch_availability();
    ///
    /// // Each item is the new answer to `availability()`, reported when it
    /// // changes rather than polled by the caller.
    /// while let Some(state) = changes.next().await {
    ///     match state {
    ///         Ok(()) => println!("radio up"),
    ///         Err(why) => println!("radio down: {why:?}"),
    ///     }
    /// }
    /// # }
    /// ```
    pub fn watch_availability(&self) -> AvailabilityEvents {
        const INTERVAL: std::time::Duration = std::time::Duration::from_millis(750);

        let (tx, rx) = futures_channel::mpsc::unbounded();
        let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
        let inner = self.inner.clone();
        let flag = stop.clone();

        std::thread::Builder::new()
            .name("webbluetooth-availability".into())
            .spawn(move || {
                let mut last: Option<std::result::Result<(), Availability>> = None;
                while !flag.load(std::sync::atomic::Ordering::Acquire) {
                    let now = inner.state().availability();
                    if last.as_ref() != Some(&now) {
                        last = Some(now);
                        if tx.unbounded_send(now).is_err() {
                            return;
                        }
                    }
                    std::thread::sleep(INTERVAL);
                }
            })
            .ok();

        AvailabilityEvents { rx, stop }
    }

    /// The devices this session has been granted — `Bluetooth.getDevices()`.
    ///
    /// A browser answers this from a permission store that outlives the page.
    /// There is no such store here unless you provide one with
    /// [`Bluetooth::with_grants`], so by default this is what the *process*
    /// has been granted: whatever `request_device` has returned so far, minus
    /// anything [`BluetoothDevice::forget`] has revoked.
    /// # Example
    ///
    /// ```no_run
    /// # use webbluetooth::Bluetooth;
    /// # async fn example() -> webbluetooth::Result<()> {
    /// let bluetooth = Bluetooth::new();
    /// for device in bluetooth.get_devices() {
    ///     // Already granted, so this needs no chooser and no user gesture.
    ///     device.gatt().connect().await?;
    /// }
    /// # Ok(()) }
    /// ```
    pub fn get_devices(&self) -> Vec<BluetoothDevice> {
        self.inner
            .granted_devices()
            .into_iter()
            .map(|id| BluetoothDevice {
                inner: self.inner.clone(),
                id,
            })
            .collect()
    }
}

impl Default for Bluetooth {
    fn default() -> Self {
        Self::new()
    }
}

impl std::fmt::Debug for Bluetooth {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Bluetooth")
            .field("state", &self.inner.state())
            .field("granted_devices", &self.inner.granted_devices().len())
            .finish()
    }
}

/// What [`Bluetooth::with_restoration`] recovered.
#[derive(Debug)]
pub struct RestoredSession {
    /// Peripherals that were connected or connecting when the process ended.
    /// Already granted the services declared on [`Restoration`].
    pub devices: Vec<BluetoothDevice>,
    /// The services the interrupted scan was filtering on.
    pub scan_services: Vec<BluetoothUuid>,
    /// Whether that scan allowed duplicate advertisements.
    pub scan_allow_duplicates: bool,
}

/// Whether the peripheral role is available on the platform this was built for.
///
/// `true` on macOS, iOS, Android, Windows and Linux. `false` on watchOS, tvOS
/// and visionOS, where CoreBluetooth's `CBPeripheralManager` and
/// mutable-attribute initialisers are `API_UNAVAILABLE`, and on the web, which
/// has no peripheral role at all. The `peripheral` module does not exist where
/// this is `false`, so it is the value to branch on in cross-platform code.
///
/// This said "`false` … on Linux, where no backend implements it" until a
/// backend implemented it; `build.rs` is what decides, and it is the thing to
/// read if this ever disagrees with a build again.
pub const PERIPHERAL_ROLE: bool = cfg!(peripheral_role);

/// Whether this process is permitted to use Bluetooth at all.
///
/// Distinct from [`Bluetooth::availability`], which also reports on the radio.
/// `NotDetermined` here with no prompt appearing means the process has no
/// `NSBluetoothAlwaysUsageDescription`.
pub fn authorization() -> Authorization {
    backend::authorization()
}

// ── Scanning without a grant ────────────────────────────────────────────────

/// What a sighting reports — `BluetoothAdvertisingEvent`.
///
/// The same shape the chooser is offered, because it is the same information:
/// which device, what it called itself, and what the packet contained.
pub type AdvertisementEvent = chooser::Candidate;

/// Options for [`Bluetooth::request_le_scan`] — `BluetoothLEScanOptions`.
///
/// The scanning specification defines this as its own dictionary —
/// `{ filters, keepRepeatedDevices, acceptAllAdvertisements }` — and
/// deliberately not as a `RequestDeviceOptions`: a scan reports
/// advertisements and grants nothing, so it has no `optionalServices` and no
/// exclusion filters. Taking the request type here meant accepting fields
/// that silently did nothing, which is a worse way to say "not applicable"
/// than not having them.
#[derive(Debug, Clone, Default)]
pub struct LeScanOptions {
    filters: Vec<DeviceFilter>,
    keep_repeated_devices: bool,
    /// Report every company's manufacturer data, and the raw packet with it.
    #[cfg(feature = "unrestricted")]
    all_manufacturer_data: bool,
    accept_all_advertisements: bool,
}

impl LeScanOptions {
    /// An empty scan request. It needs either a filter or
    /// [`accept_all_advertisements`](Self::accept_all_advertisements).
    pub fn new() -> Self {
        Self::default()
    }

    /// Report every advertisement from every device —
    /// `acceptAllAdvertisements`.
    ///
    /// The reports carry no service UUIDs or service data: an event only tells
    /// a caller about the services its grant covers, and this grant names none
    /// (the spec's *fire an advertisementreceived event*). A device that does
    /// advertise a service still shows up, with an empty
    /// [`service_uuids`](crate::Advertisement::service_uuids). To see a service,
    /// scan with a [`filter`](Self::filter) on it instead.
    pub fn accept_all_advertisements() -> Self {
        Self {
            accept_all_advertisements: true,
            ..Self::default()
        }
    }

    /// Report only advertisements matching this filter.
    ///
    /// A sighting matching any filter is reported. Mutually exclusive with
    /// [`accept_all_advertisements`](Self::accept_all_advertisements).
    /// # Example
    ///
    /// ```no_run
    /// # use webbluetooth::{DeviceFilter, LeScanOptions};
    /// # fn example() -> webbluetooth::Result<()> {
    /// let options = LeScanOptions::new()
    ///     .filter(DeviceFilter::new().name_prefix("Muse"))
    ///     .keep_repeated_devices(true);
    /// # let _ = options;
    /// # Ok(()) }
    /// ```
    pub fn filter(mut self, filter: DeviceFilter) -> Self {
        self.filters.push(filter);
        self
    }

    /// Add several filters at once.
    pub fn filters(mut self, filters: impl IntoIterator<Item = DeviceFilter>) -> Self {
        self.filters.extend(filters);
        self
    }

    /// Report repeat sightings of a device rather than only the first.
    ///
    /// Off by default, as in the specification. Turn it on to track signal
    /// strength or a value carried in service data, both of which change while
    /// the device identity does not.
    pub fn keep_repeated_devices(mut self, keep: bool) -> Self {
        self.keep_repeated_devices = keep;
        self
    }

    /// Report manufacturer data from every company, and the raw advertising
    /// bytes along with it — [`Advertisement::raw`].
    ///
    /// Behind the `unrestricted` feature, and outside the Web Bluetooth model
    /// for the same reason `Grant::all_services` is: a page names the companies
    /// it came for, and a general scanner cannot, because showing what is on
    /// the air is the whole job.
    ///
    /// Without this a scan sees only the company identifiers it asked for, and
    /// no raw bytes at all — the packet carries every company's data, so
    /// handing it over would make the filtering above meaningless.
    ///
    /// The manufacturer blocklist is not part of this and still applies.
    ///
    /// [`Advertisement::raw`]: webbluetooth_core::filter::Advertisement::raw
    #[cfg(feature = "unrestricted")]
    pub fn accept_all_manufacturer_data(mut self) -> Self {
        self.all_manufacturer_data = true;
        self
    }

    /// Check the combination the way the specification's algorithm does,
    /// before the radio is touched.
    pub fn validate(&self) -> Result<()> {
        match (self.accept_all_advertisements, self.filters.is_empty()) {
            (true, false) => {
                return Err(Error::InvalidModification(
                    "accept_all_advertisements() and filter() are mutually exclusive".into(),
                ))
            }
            (false, true) => {
                return Err(Error::InvalidModification(
                    "provide at least one filter(), or call accept_all_advertisements()".into(),
                ))
            }
            _ => {}
        }
        self.as_request().validate()
    }

    /// The same thing expressed as a request, which is what the scan hub and
    /// the backends match against.
    ///
    /// Private: a scan grants nothing, so handing this out would reintroduce
    /// exactly the `optionalServices`-shaped confusion this type exists to
    /// remove.
    fn as_request(&self) -> RequestDeviceOptions {
        let mut request = RequestDeviceOptions::new();
        if self.accept_all_advertisements {
            request = request.accept_all_devices();
        }
        for filter in &self.filters {
            request = request.filter(filter.clone());
        }
        #[cfg(feature = "unrestricted")]
        if self.all_manufacturer_data {
            request = request.accept_all_manufacturer_data();
        }
        request
    }
}

/// A running scan — `BluetoothLEScan`.
///
/// Yields [`AdvertisementEvent`]s. The scan stops when this is dropped, so a
/// caller who wants it to keep running has to keep it alive.
pub struct LeScan {
    inner: Arc<crate::session::Session>,
    watcher: u64,
    stream: crate::backlog::Receiver<AdvertisementEvent>,
    options: LeScanOptions,
}

impl LeScan {
    /// Whether this scan is still running — `BluetoothLEScan.active`.
    pub fn is_active(&self) -> bool {
        self.inner.scan_hub().contains(self.watcher)
    }

    /// `keepRepeatedDevices`, as asked for.
    pub fn keep_repeated_devices(&self) -> bool {
        self.options.keep_repeated_devices
    }

    /// `acceptAllAdvertisements`, as asked for.
    pub fn accept_all_advertisements(&self) -> bool {
        self.options.accept_all_advertisements
    }

    /// The filters this scan is reporting against — `BluetoothLEScan.filters`.
    ///
    /// Empty when it accepts all advertisements.
    pub fn filters(&self) -> &[DeviceFilter] {
        &self.options.filters
    }

    /// Scan for `duration` and return what was seen, one entry per device.
    ///
    /// The enumerating scan — "show me what is out there" — which is what
    /// `btleplug`'s `start_scan`, sleep, `peripherals()` does and what a
    /// picker needs before it has anything to show. Sightings of the same
    /// device are folded together with [`Candidate::merge`], in the order the
    /// devices were first seen, so a name that arrived in a scan response is
    /// attached to the services that arrived in the advertisement before it.
    ///
    /// Ask for [`keep_repeated_devices`](LeScanOptions::keep_repeated_devices)
    /// when the later packets matter: without it each device is reported once
    /// and there is nothing to fold.
    ///
    /// The scan is still running afterwards — call this again to keep
    /// listening, or [`stop`](Self::stop) it.
    ///
    /// Not part of Web Bluetooth.
    ///
    /// ```no_run
    /// # use std::time::Duration;
    /// # use webbluetooth::{Bluetooth, LeScanOptions};
    /// # async fn example() -> webbluetooth::Result<()> {
    /// let mut scan = Bluetooth::shared()
    ///     .request_le_scan(
    ///         LeScanOptions::accept_all_advertisements().keep_repeated_devices(true),
    ///     )
    ///     .await?;
    ///
    /// for device in scan.collect_for(Duration::from_secs(5)).await {
    ///     println!("{} ({})", device.label(), device.id);
    /// }
    /// # Ok(()) }
    /// ```
    pub async fn collect_for(&mut self, duration: std::time::Duration) -> Vec<AdvertisementEvent> {
        use futures_util::StreamExt;

        let mut seen: Vec<AdvertisementEvent> = Vec::new();
        let _ = timeout(duration, async {
            while let Some(sighting) = self.next().await {
                match seen.iter_mut().find(|known| known.id == sighting.id) {
                    Some(known) => known.merge(sighting),
                    None => seen.push(sighting),
                }
            }
        })
        .await;
        seen
    }

    /// Stop scanning. Dropping does the same thing.
    pub fn stop(self) {}
}

impl futures_core::Stream for LeScan {
    type Item = AdvertisementEvent;

    fn poll_next(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Option<AdvertisementEvent>> {
        std::pin::Pin::new(&mut self.stream).poll_next(cx)
    }
}

impl Drop for LeScan {
    fn drop(&mut self) {
        // Stop the radio only if this was the last one interested in it.
        if self.inner.scan_hub().remove(self.watcher) {
            let _ = self.inner.backend().set_radio_scanning(false);
        }
    }
}

impl std::fmt::Debug for LeScan {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("LeScan")
            .field("active", &self.is_active())
            .field("keep_repeated_devices", &self.keep_repeated_devices())
            .field(
                "accept_all_advertisements",
                &self.accept_all_advertisements(),
            )
            .finish()
    }
}

/// Advertisements from one device — what `watchAdvertisements()` starts.
///
/// Yields [`AdvertisementEvent`]s for that device only. Watching stops when
/// this is dropped.
pub struct Advertisements {
    inner: Arc<crate::session::Session>,
    watcher: u64,
    stream: crate::backlog::Receiver<AdvertisementEvent>,
    device_id: String,
}

impl Advertisements {
    /// How many advertisements were dropped because this stream was not being
    /// read fast enough.
    ///
    /// A busy room produces hundreds a second and the radio's callback cannot
    /// be made to wait, so a consumer that falls behind loses the oldest. That
    /// is the right thing to lose — an advertisement describes a moment, and a
    /// stale one is not worth delivering — but it is worth being able to see,
    /// because a number that climbs steadily means the loop reading this is
    /// too slow for the environment it is in.
    pub fn lost(&self) -> u64 {
        self.stream.lost()
    }

    /// `BluetoothDevice.watchingAdvertisements`.
    pub fn is_watching(&self) -> bool {
        self.inner.scan_hub().contains(self.watcher)
    }

    /// The device being watched.
    pub fn device_id(&self) -> &str {
        &self.device_id
    }

    /// Stop watching. Dropping does the same thing.
    pub fn stop(self) {}
}

impl futures_core::Stream for Advertisements {
    type Item = AdvertisementEvent;

    fn poll_next(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Option<AdvertisementEvent>> {
        std::pin::Pin::new(&mut self.stream).poll_next(cx)
    }
}

impl Drop for Advertisements {
    fn drop(&mut self) {
        if self.inner.scan_hub().remove(self.watcher) {
            let _ = self.inner.backend().set_radio_scanning(false);
        }
        // On the web the watch belongs to the device, so stopping it is a
        // call rather than a reference count reaching zero. Spawned because
        // `drop` cannot await, and the page will abort the watch whether or
        // not anything is still listening.
        #[cfg(target_arch = "wasm32")]
        {
            let inner = self.inner.clone();
            let id = self.device_id.clone();
            webbluetooth_wasm::spawn(async move {
                let _ = inner.watch_advertisements(&id, false).await;
            });
        }
    }
}

impl std::fmt::Debug for Advertisements {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Advertisements")
            .field("device", &self.device_id)
            .field("watching", &self.is_watching())
            .finish()
    }
}

/// The service set changed — see
/// [`RemoteGattServer::watch_services_changed`](crate::gatt::RemoteGattServer::watch_services_changed).
pub struct ServiceEvents {
    pub(crate) rx: futures_channel::mpsc::UnboundedReceiver<()>,
}

impl futures_core::Stream for ServiceEvents {
    type Item = ();

    fn poll_next(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Option<()>> {
        std::pin::Pin::new(&mut self.rx).poll_next(cx)
    }
}

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

// ── Availability changes ────────────────────────────────────────────────────

/// Adapter availability, as it changes — `Bluetooth.onavailabilitychanged`.
///
/// Yields each time the answer to [`Bluetooth::availability`] changes: the
/// radio is switched off, a dongle is unplugged, a permission is revoked.
///
/// **Polled, not pushed.** The platforms disagree about whether they report
/// this at all — CoreBluetooth and BlueZ do, a raw HCI socket does not, and
/// Android needs a `BroadcastReceiver` this crate does not install — so rather
/// than have the event fire promptly on two platforms and never on the others,
/// it is derived by asking. The interval is the latency, not the resolution:
/// a change is reported once, when it is noticed.
pub struct AvailabilityEvents {
    rx: futures_channel::mpsc::UnboundedReceiver<std::result::Result<(), Availability>>,
    /// Dropping the stream stops the poller.
    stop: Arc<std::sync::atomic::AtomicBool>,
}

impl futures_core::Stream for AvailabilityEvents {
    type Item = std::result::Result<(), Availability>;

    fn poll_next(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Option<Self::Item>> {
        std::pin::Pin::new(&mut self.rx).poll_next(cx)
    }
}

impl Drop for AvailabilityEvents {
    fn drop(&mut self) {
        self.stop.store(true, std::sync::atomic::Ordering::Release);
    }
}

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