webbluetooth-linux 0.0.5

Linux BLE from pure Rust — D-Bus and the kernel's Bluetooth sockets, spoken directly
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
//! The Linux engine: BlueZ over D-Bus.
//!
//! Structurally simpler than its CoreBluetooth counterpart, because BlueZ is
//! request/reply where CoreBluetooth is delegate-driven:
//!
//! * `ReadValue` **returns the bytes in its method reply**, so there is no
//!   read-versus-notification ambiguity and none of the per-attribute FIFO
//!   correlation the Apple backend needs.
//! * Services are not discovered explicitly. Connecting resolves them, BlueZ
//!   sets `ServicesResolved`, and the objects appear in the tree — so
//!   "discovery" here is a wait followed by a tree walk.
//! * Notifications are `PropertiesChanged` on a characteristic's `Value`.
//!
//! What stays the same is everything above this file: the allowlist, the
//! blocklist, UUID canonicalisation, filters and the chooser are shared.
//!
//! # One visible platform difference
//!
//! `BluetoothDevice::id` is the peer's Bluetooth address here. BlueZ exposes it
//! and keys its object paths on it; Apple never does. Code that treats the id as
//! opaque works on both, but a Linux id is personally identifying in a way a
//! macOS one is not.

use crate::bluez::{self, interfaces, Bluez, Event as BluezEvent, Object};
use crate::dbus::Value;
use futures_channel::oneshot;
use std::collections::{BTreeSet, HashMap, HashSet};
use std::sync::{Arc, Mutex, Weak};
use std::time::Duration;
use webbluetooth_core::chooser::DeviceChooser;
use webbluetooth_core::error::{Availability, Error, Result};
use webbluetooth_core::filter::{Advertisement, RequestDeviceOptions};
use webbluetooth_core::gatt::{CharacteristicProperties, WriteType};
use webbluetooth_core::registry::DeviceRegistry;
use webbluetooth_core::scan::{self, ScanHub};
use webbluetooth_core::state::ManagerState;
use webbluetooth_core::timer;
use webbluetooth_core::uuid::BluetoothUuid;

/// A handle into a device's attribute table.
///
/// A D-Bus object path plus the UUID it was resolved as. Carrying the UUID
/// makes the handle self-describing, matching the Apple backend where the same
/// question is answered by messaging the object.
#[derive(Clone, Debug)]
pub struct Handle(Arc<HandleData>);

#[derive(Debug)]
struct HandleData {
    path: String,
    uuid: BluetoothUuid,
}

impl Handle {
    fn new(path: &str, uuid: BluetoothUuid) -> Self {
        Self(Arc::new(HandleData {
            path: path.to_owned(),
            uuid,
        }))
    }
    fn path(&self) -> &str {
        &self.0.path
    }
}

/// The canonical UUID of an attribute handle.
pub fn attribute_uuid(handle: &Handle) -> Result<BluetoothUuid> {
    Ok(handle.0.uuid)
}

/// The scan a restored session was running. Never populated on Linux — BlueZ
/// has no state-restoration concept — but the shape is shared.
#[derive(Debug, Default, Clone)]
pub struct RestoredScan {
    pub device_ids: Vec<String>,
    pub scan_services: Vec<BluetoothUuid>,
    pub scan_allow_duplicates: bool,
}

/// What the BlueZ backend needs to reach a device: its object path.
/// Everything else about a grant lives in [`webbluetooth_core::registry`].
type DeviceData = String;

pub struct Inner {
    bluez: Mutex<Option<Bluez>>,
    /// Why BlueZ could not be reached, if it could not.
    unavailable: Mutex<Option<Availability>>,
    /// Everyone watching the scan. The radio is shared, so the scan is
    /// reference-counted rather than owned by whoever started it.
    hub: ScanHub,
    /// Bluetooth address to D-Bus object path, for every device seen this
    /// session. Kept outside the watchers so a finished `requestDevice` can
    /// still resolve the device its chooser picked.
    sightings: Mutex<HashMap<String, String>>,
    devices: DeviceRegistry<DeviceData>,
    notifications: Mutex<HashMap<String, Vec<webbluetooth_core::backlog::Sender<Vec<u8>>>>>,
    /// Resolved when a device's `ServicesResolved` becomes true.
    services_resolved: Mutex<HashMap<String, Vec<oneshot::Sender<()>>>>,
    /// Resolved when `Connected` becomes true.
    connected_waiters: Mutex<HashMap<String, Vec<oneshot::Sender<()>>>>,
    /// Sockets `AcquireWrite` handed over, by characteristic path.
    ///
    /// Held for the life of the connection: acquiring is itself a D-Bus round
    /// trip, so doing it per write would cost exactly what it saves.
    write_sockets: Mutex<HashMap<String, Arc<WriteSocket>>>,
    /// Devices whose GATT tree has finished resolving at least once.
    ///
    /// Services appearing is only a *change* after that: during the first
    /// discovery they are appearing for the first time, and treating that as a
    /// change would invalidate the handles the caller is in the middle of
    /// being given.
    resolved_once: Mutex<HashSet<String>>,
}

/// A socket BlueZ handed over for unacknowledged writes.
///
/// `SOCK_SEQPACKET`, so one write is one ATT PDU — there is no partial write
/// to loop over and no framing to add. The kernel's send buffer provides the
/// flow control that `WriteValue` gets from waiting for a D-Bus reply.
struct WriteSocket {
    fd: std::os::fd::RawFd,
    /// The largest payload this socket accepts, as BlueZ reported it.
    mtu: u16,
}

impl WriteSocket {
    fn write(&self, value: &[u8]) -> std::io::Result<()> {
        // SAFETY: the descriptor is owned by this struct and closed only in
        // its `Drop`.
        let n = unsafe { crate::sys::write(self.fd, value.as_ptr(), value.len()) };
        if n < 0 {
            return Err(std::io::Error::last_os_error());
        }
        if n as usize != value.len() {
            // A sequenced-packet socket does not do partial writes; if it
            // somehow did, the peer received a truncated value and the caller
            // must know.
            return Err(std::io::Error::other(format!(
                "wrote {n} of {} bytes",
                value.len()
            )));
        }
        Ok(())
    }
}

impl Drop for WriteSocket {
    fn drop(&mut self) {
        unsafe { crate::sys::close(self.fd) };
    }
}

// `write` and `close` are declared once, in `sys` — this adapter used to
// declare its own because it was in another crate, and the two disagreed about
// whether the buffer was `*const u8` or `*const c_void`.

struct Sink(Weak<Inner>);

impl bluez::EventSink for Sink {
    fn emit(&self, event: BluezEvent) {
        if let Some(inner) = self.0.upgrade() {
            inner.handle(event);
        }
    }
}

/// `/org/bluez/hci0` shortened to `hci0`.
///
/// The object path is what BlueZ uses internally, but `hci0` is what
/// `hciconfig`, `bluetoothctl` and `WEBBLUETOOTH_ADAPTER` all use, so that is
/// what a caller is shown. `select_adapter` takes either.
fn short_adapter_name(path: &str) -> String {
    path.rsplit('/').next().unwrap_or(path).to_owned()
}

impl Inner {
    pub fn new(show_power_alert: bool) -> Arc<Self> {
        Self::with_restoration(show_power_alert, None, BTreeSet::new())
    }

    /// `restore_identifier` is accepted and ignored: BlueZ has no state
    /// preservation, and nothing on Linux relaunches a process for Bluetooth.
    pub fn with_restoration(
        _show_power_alert: bool,
        _restore_identifier: Option<&str>,
        _restore_allowed: BTreeSet<BluetoothUuid>,
    ) -> Arc<Self> {
        Arc::new_cyclic(|weak: &Weak<Inner>| {
            let inner = Inner {
                bluez: Mutex::new(None),
                unavailable: Mutex::new(None),
                hub: ScanHub::new(),
                sightings: Mutex::new(HashMap::new()),
                devices: DeviceRegistry::default(),
                notifications: Mutex::new(HashMap::new()),
                services_resolved: Mutex::new(HashMap::new()),
                connected_waiters: Mutex::new(HashMap::new()),
                write_sockets: Mutex::new(HashMap::new()),
                resolved_once: Mutex::new(HashSet::new()),
            };
            match Bluez::new(Arc::new(Sink(weak.clone()))) {
                Ok(bluez) => {
                    if bluez.adapter().is_none() {
                        *inner.unavailable.lock().unwrap() = Some(Availability::Unsupported);
                    }
                    *inner.bluez.lock().unwrap() = Some(bluez);
                }
                // A missing bus or a refused connection is the Linux shape of
                // "not authorised": bluetoothd is not reachable from here.
                Err(_) => {
                    *inner.unavailable.lock().unwrap() = Some(Availability::Unauthorized);
                }
            }
            inner
        })
    }

    fn with_bluez<T>(&self, f: impl FnOnce(&Bluez) -> T) -> Result<T> {
        let guard = self.bluez.lock().unwrap();
        let bluez = guard
            .as_ref()
            .ok_or(Error::NotAvailable(Availability::Unauthorized))?;
        Ok(f(bluez))
    }

    // ── Controllers ─────────────────────────────────────────────────────────
    //
    // BlueZ is the platform that genuinely has several: every controller is an
    // `org.bluez.Adapter1` object in the tree this backend already mirrors, so
    // enumerating is a filter over a map that is always up to date.

    pub async fn adapters(&self) -> Result<Vec<webbluetooth_core::AdapterInfo>> {
        self.with_bluez(|b| {
            let current = b.adapter();
            b.adapters()
                .into_iter()
                .map(|path| {
                    let object = b.object(&path);
                    webbluetooth_core::AdapterInfo {
                        // `hci0` rather than the full object path: it is what
                        // `hciconfig` and `bluetoothctl` call it, and
                        // `select_adapter` accepts either.
                        name: object
                            .as_ref()
                            .and_then(|o| o.string(interfaces::ADAPTER, "Alias")),
                        address: object
                            .as_ref()
                            .and_then(|o| o.string(interfaces::ADAPTER, "Address")),
                        powered: object
                            .as_ref()
                            .and_then(|o| o.bool(interfaces::ADAPTER, "Powered"))
                            .unwrap_or(false),
                        is_default: current.as_deref() == Some(path.as_str()),
                        id: short_adapter_name(&path),
                    }
                })
                .collect()
        })
    }

    pub async fn adapter(&self) -> Result<webbluetooth_core::AdapterInfo> {
        let adapters = self.adapters().await?;
        adapters
            .into_iter()
            .find(webbluetooth_core::AdapterInfo::is_default)
            .ok_or(Error::NotAvailable(Availability::Unsupported))
    }

    pub async fn select_adapter(&self, id: &str) -> Result<()> {
        self.with_bluez(|b| b.select_adapter(id))?
            .map_err(|e| Error::NotFound(e.to_string()))
    }

    // ── Events ──────────────────────────────────────────────────────────────

    fn handle(&self, event: BluezEvent) {
        match event {
            BluezEvent::DeviceSeen { path, properties } => self.on_device_seen(&path, &properties),

            BluezEvent::Connected { path } => {
                if let Some(id) = self.id_for_path(&path) {
                    self.devices.update(&id, |d| d.connected = true);
                    for tx in self
                        .connected_waiters
                        .lock()
                        .unwrap()
                        .remove(&id)
                        .into_iter()
                        .flatten()
                    {
                        let _ = tx.send(());
                    }
                }
            }

            BluezEvent::Disconnected { path } => {
                let Some(id) = self.id_for_path(&path) else {
                    return;
                };
                // Waiters would otherwise hang until their own timeout.
                for tx in self
                    .connected_waiters
                    .lock()
                    .unwrap()
                    .remove(&id)
                    .into_iter()
                    .flatten()
                {
                    drop(tx);
                }
                for tx in self
                    .services_resolved
                    .lock()
                    .unwrap()
                    .remove(&id)
                    .into_iter()
                    .flatten()
                {
                    drop(tx);
                }
                // The next resolve is a first discovery again, not a change.
                self.resolved_once.lock().unwrap().remove(&id);
                // The sockets belong to the connection that just ended. Kept,
                // they would be stale descriptors for characteristics that no
                // longer exist — and a reconnect would write into them.
                self.write_sockets
                    .lock()
                    .unwrap()
                    .retain(|characteristic, _| !characteristic.starts_with(&*path));
                self.devices.mark_disconnected(&id);
            }

            BluezEvent::ServicesResolved { path } => {
                let Some(id) = self.id_for_path(&path) else {
                    return;
                };
                // Resolving a second time means BlueZ rebuilt the tree, which
                // it does after a Service Changed indication.
                if !self.resolved_once.lock().unwrap().insert(id.clone()) {
                    self.devices.mark_services_changed(&id);
                }
                for tx in self
                    .services_resolved
                    .lock()
                    .unwrap()
                    .remove(&id)
                    .into_iter()
                    .flatten()
                {
                    let _ = tx.send(());
                }
            }

            BluezEvent::ServicesChanged { path } => {
                let Some(id) = self.id_for_path(&path) else {
                    return;
                };
                if self.resolved_once.lock().unwrap().contains(&id) {
                    self.devices.mark_services_changed(&id);
                }
            }

            BluezEvent::CharacteristicValue { path, value } => {
                let mut subscribers = self.notifications.lock().unwrap();
                if let Some(list) = subscribers.get_mut(&*path) {
                    list.retain(|tx| tx.send(value.clone()).is_ok());
                    if list.is_empty() {
                        subscribers.remove(&*path);
                    }
                }
            }

            BluezEvent::DeviceRemoved { .. }
            | BluezEvent::AdapterChanged { .. }
            | BluezEvent::Disconnected_ => {}
        }
    }

    fn on_device_seen(&self, path: &str, properties: &HashMap<String, Value>) {
        if !self.hub.is_watching() {
            return;
        }

        // A PropertiesChanged sighting carries only what changed, so merge it
        // over the cached object rather than trusting it alone.
        let cached = self
            .bluez
            .lock()
            .unwrap()
            .as_ref()
            .and_then(|b| b.object(path));
        let mut merged: HashMap<String, Value> = cached
            .as_ref()
            .and_then(|o| o.interfaces.get(interfaces::DEVICE).cloned())
            .unwrap_or_default();
        for (k, v) in properties {
            merged.insert(k.clone(), v.clone());
        }

        let Some(address) = merged
            .get("Address")
            .and_then(Value::as_str)
            .map(str::to_owned)
        else {
            return;
        };
        let name = merged
            .get("Name")
            .or_else(|| merged.get("Alias"))
            .and_then(Value::as_str)
            .map(str::to_owned);
        let advertisement = advertisement_from(&merged);

        self.sightings
            .lock()
            .unwrap()
            .insert(address.clone(), path.to_owned());
        // Each watcher applies its own filter; this one just reports.
        self.hub.publish(&address, name.as_deref(), &advertisement);
    }

    pub fn scan_hub(&self) -> &ScanHub {
        &self.hub
    }

    /// Start or stop the adapter's discovery.
    ///
    /// Starting is idempotent and re-applies the filter, because a new watcher
    /// can widen it and BlueZ only accepts a filter change while discovery is
    /// stopped.
    pub fn set_radio_scanning(&self, on: bool) -> Result<()> {
        let adapter = self
            .with_bluez(|b| b.adapter())?
            .ok_or(Error::NotAvailable(Availability::Unsupported))?;

        if !on {
            let _ =
                self.with_bluez(|b| b.call(&adapter, interfaces::ADAPTER, "StopDiscovery", vec![]));
            return Ok(());
        }

        // A discovery filter narrows what bluetoothd reports and, with
        // Transport=le, keeps classic devices out of the results entirely.
        let mut filter = vec![("Transport".to_string(), Value::Str("le".into()))];
        let services = self.hub.scan_services();
        if !services.is_empty() {
            filter.push((
                "UUIDs".to_string(),
                Value::string_array(services.iter().map(|u| u.as_str().to_owned())),
            ));
        }
        filter.push((
            "DuplicateData".to_string(),
            Value::Bool(self.hub.wants_duplicates()),
        ));

        let result = self.with_bluez(|b| {
            let _ = b.call(&adapter, interfaces::ADAPTER, "StopDiscovery", vec![]);
            let _ = b.call(
                &adapter,
                interfaces::ADAPTER,
                "SetDiscoveryFilter",
                vec![Value::dict(filter)],
            );
            b.call(&adapter, interfaces::ADAPTER, "StartDiscovery", vec![])
        })?;
        result.map_err(|e| Error::Network(format!("could not start discovery: {e}")))?;

        // Devices BlueZ already knows about do not re-announce themselves, so
        // replay the cache rather than waiting on signals that will not come.
        self.replay_known_devices();
        Ok(())
    }

    fn id_for_path(&self, path: &str) -> Option<String> {
        self.devices.find(|d| d.inner == path)
    }

    // ── Availability ────────────────────────────────────────────────────────

    pub fn state(&self) -> ManagerState {
        if let Some(a) = *self.unavailable.lock().unwrap() {
            return match a {
                Availability::Unsupported => ManagerState::Unsupported,
                Availability::Unauthorized => ManagerState::Unauthorized,
                _ => ManagerState::Unknown,
            };
        }
        match self.with_bluez(|b| b.is_powered()) {
            Ok(true) => ManagerState::PoweredOn,
            Ok(false) => ManagerState::PoweredOff,
            Err(_) => ManagerState::Unauthorized,
        }
    }

    /// BlueZ answers synchronously, so there is nothing to settle — unlike
    /// CoreBluetooth, which reports `Unknown` until its first callback.
    pub async fn settled_state(&self) -> ManagerState {
        self.state()
    }

    pub async fn require_powered_on(&self) -> Result<()> {
        self.state().require_powered_on()
    }

    pub fn restored(&self) -> Option<RestoredScan> {
        None
    }

    // ── Scanning ────────────────────────────────────────────────────────────

    pub async fn request_device(
        self: &Arc<Self>,
        options: RequestDeviceOptions,
        chooser: &dyn DeviceChooser,
    ) -> Result<String> {
        options.validate()?;
        self.require_powered_on().await?;

        let allowed = options.grant();
        let id = scan::choose(
            &self.hub,
            options,
            chooser,
            |on| self.set_radio_scanning(on),
            || self.replay_known_devices(),
        )
        .await?;
        let Some(path) = self.sightings.lock().unwrap().get(&id).cloned() else {
            return Err(Error::NotFound(format!(
                "the chooser returned {id:?}, which was not among the devices it was offered"
            )));
        };

        let object = self.with_bluez(|b| b.object(&path))?;
        let name = object.as_ref().and_then(|o| {
            o.string(interfaces::DEVICE, "Name")
                .or_else(|| o.string(interfaces::DEVICE, "Alias"))
        });
        let connected = object
            .as_ref()
            .and_then(|o| o.bool(interfaces::DEVICE, "Connected"))
            .unwrap_or(false);

        self.devices.insert(&id, name, allowed, connected, path);
        Ok(id)
    }

    /// Write down the socket `AcquireWrite` gives us, if there is one.
    ///
    /// `Ok(None)` means there is no socket and the caller should fall back to
    /// `WriteValue`: BlueZ only offers this when nothing else holds the
    /// characteristic, and older versions do not offer it at all. That is a
    /// slower path, not a broken one, so it is not an error.
    ///
    /// The gain is the round trip: `WriteValue` is a D-Bus method call, so
    /// every packet crosses into `bluetoothd` and back. This socket is the
    /// same one `bluetoothd` would write to, handed over directly, with the
    /// kernel's own send buffer for flow control.
    async fn write_over_socket(
        &self,
        id: &str,
        handle: &Handle,
        value: &[u8],
    ) -> Result<Option<()>> {
        let Some(socket) = self.acquire_write(id, handle).await else {
            return Ok(None);
        };
        // The socket is `SOCK_SEQPACKET`: one write is one PDU, so a value
        // larger than the MTU it reported cannot be split and must go the
        // other way rather than be silently truncated.
        if value.len() > socket.mtu as usize {
            return Ok(None);
        }
        match socket.write(value) {
            Ok(()) => Ok(Some(())),
            // The peer went away or the socket was revoked — BlueZ takes it
            // back when someone else acquires the characteristic. Forget it
            // and let the caller use `WriteValue`.
            Err(e) => {
                self.write_sockets.lock().unwrap().remove(handle.path());
                Err(Error::Network(format!("the write socket failed: {e}")))
            }
        }
    }

    /// The socket for this characteristic, acquiring one if needed.
    async fn acquire_write(&self, id: &str, handle: &Handle) -> Option<Arc<WriteSocket>> {
        if let Some(socket) = self.write_sockets.lock().unwrap().get(handle.path()) {
            return Some(socket.clone());
        }
        if !self.is_connected(id) {
            return None;
        }

        // An empty options dictionary: no offset, no MTU preference.
        let acquired = self
            .call_with_fds(
                handle.path(),
                interfaces::CHARACTERISTIC,
                "AcquireWrite",
                vec![Value::dict([])],
            )
            .await
            .ok()?;

        let (body, fds) = acquired;
        let mtu = body.get(1).and_then(Value::as_u64)? as u16;
        let fd = fds.into_iter().next()?;
        // Three bytes of ATT header are already accounted for by BlueZ: the
        // MTU it reports is the payload this socket carries.
        let socket = Arc::new(WriteSocket { fd, mtu });
        self.write_sockets
            .lock()
            .unwrap()
            .insert(handle.path().to_owned(), socket.clone());
        Some(socket)
    }

    /// Adopt a device by address.
    ///
    /// BlueZ keeps an object for every device it has ever paired with or seen
    /// recently, so the usual case is that one already exists. Its path is
    /// derived from the address rather than searched for — BlueZ names them
    /// `dev_AA_BB_CC_DD_EE_FF` under the adapter — and the path is checked
    /// against the tree rather than assumed, so an unknown device is a
    /// `NotFound` and not a handle that fails later.
    pub async fn adopt_device(
        &self,
        id: &str,
        allowed: webbluetooth_core::registry::Grant,
    ) -> Result<String> {
        if !webbluetooth_core::address::is_bluetooth_address(id) {
            return Err(Error::NotFound(format!(
                "{id:?} is not a Bluetooth address"
            )));
        }
        let adapter = self
            .with_bluez(|b| b.adapter())?
            .ok_or(Error::NotAvailable(Availability::Unsupported))?;
        let path = format!("{adapter}/dev_{}", id.to_uppercase().replace(':', "_"));

        let object = self.with_bluez(|b| b.object(&path))?;
        let Some(object) = object.filter(|o| o.has(interfaces::DEVICE)) else {
            return Err(Error::NotFound(format!(
                "BlueZ has no device object for {id}; it has to have been seen or \
                 paired at least once"
            )));
        };

        let name = object
            .string(interfaces::DEVICE, "Name")
            .or_else(|| object.string(interfaces::DEVICE, "Alias"));
        let connected = object
            .bool(interfaces::DEVICE, "Connected")
            .unwrap_or(false);

        self.sightings
            .lock()
            .unwrap()
            .insert(id.to_owned(), path.clone());
        self.devices.insert(id, name, allowed, connected, path);
        Ok(id.to_owned())
    }

    /// Feed already-known devices to an in-progress scan.
    fn replay_known_devices(&self) {
        let Ok(paths) = self.with_bluez(|b| b.paths_with(interfaces::DEVICE)) else {
            return;
        };
        for path in paths {
            let Ok(Some(object)) = self.with_bluez(|b| b.object(&path)) else {
                continue;
            };
            let Some(props) = object.interfaces.get(interfaces::DEVICE) else {
                continue;
            };
            self.on_device_seen(&path, props);
        }
    }

    // ── Device access ───────────────────────────────────────────────────────

    // The registry owns grants, generations and the GATT lock; these forward.
    fn device_path(&self, id: &str) -> Result<String> {
        self.devices.get(id, |d| d.inner.clone())
    }

    // The registry answers these identically for every backend.
    webbluetooth_core::registry::forward_to_registry!();

    // ── PHY ─────────────────────────────────────────────────────────────────

    /// BlueZ has no D-Bus API for the PHY. The kernel knows, and `btmgmt` can
    /// be made to say, but nothing on the bus carries it.
    pub async fn phy(&self, id: &str) -> Result<webbluetooth_core::ConnectionPhy> {
        let _ = self.is_connected(id);
        Err(Error::NotSupported(
            "BlueZ does not expose the connection PHY over D-Bus".into(),
        ))
    }

    /// Asking is not possible where even reading is not.
    pub async fn set_preferred_phy(
        &self,
        id: &str,
        _tx: webbluetooth_core::Phy,
        _rx: webbluetooth_core::Phy,
    ) -> Result<webbluetooth_core::ConnectionPhy> {
        let _ = self.is_connected(id);
        Err(Error::NotSupported(
            "BlueZ does not expose the connection PHY over D-Bus".into(),
        ))
    }

    // ── Pairing ─────────────────────────────────────────────────────────────

    /// `org.bluez.Device1.Pair`.
    ///
    /// The call returns when the ceremony finishes, so there is nothing to
    /// poll. If the peer wants a passkey or a confirmation, BlueZ asks the
    /// registered agent — usually the desktop's — and without one the call
    /// fails rather than hanging, which is the right way round.
    pub async fn pair(&self, id: &str) -> Result<webbluetooth_core::Pairing> {
        if self.is_paired(id).await? {
            return Ok(webbluetooth_core::Pairing::AlreadyPaired);
        }
        let Some(path) = self.sightings.lock().unwrap().get(id).cloned() else {
            return Err(Error::NotFound(format!(
                "BlueZ has no device object for {id}"
            )));
        };
        self.call(&path, interfaces::DEVICE, "Pair", vec![]).await?;
        Ok(webbluetooth_core::Pairing::Paired)
    }

    pub async fn is_paired(&self, id: &str) -> Result<bool> {
        let Some(path) = self.sightings.lock().unwrap().get(id).cloned() else {
            return Ok(false);
        };
        Ok(self
            .with_bluez(|b| b.object(&path))?
            .and_then(|o| o.bool(interfaces::DEVICE, "Paired"))
            .unwrap_or(false))
    }

    #[cfg(feature = "classic")]
    pub async fn bonded_classic_devices(&self) -> Result<Vec<String>> {
        let mut addresses = Vec::new();
        for path in self.with_bluez(|bluez| bluez.paths_with(interfaces::DEVICE))? {
            let Some(object) = self.with_bluez(|bluez| bluez.object(&path))? else {
                continue;
            };
            if object.bool(interfaces::DEVICE, "Paired").unwrap_or(false) {
                if let Some(address) = object.string(interfaces::DEVICE, "Address") {
                    addresses.push(address);
                }
            }
        }
        addresses.sort();
        addresses.dedup();
        Ok(addresses)
    }

    #[cfg(feature = "rfcomm")]
    pub async fn register_classic_profile(
        &self,
        service: BluetoothUuid,
        security: webbluetooth_core::ClassicSecurity,
    ) -> Result<crate::classic_profile::ProfileRegistration> {
        let guard = self.bluez.lock().unwrap();
        let bluez = guard
            .as_ref()
            .ok_or(Error::NotAvailable(Availability::Unauthorized))?;
        crate::classic_profile::ProfileRegistration::register(bluez, service, security)
    }

    #[cfg(feature = "rfcomm")]
    pub async fn register_classic_profile_channel(
        &self,
        service: BluetoothUuid,
        channel: u8,
        security: webbluetooth_core::ClassicSecurity,
    ) -> Result<crate::classic_profile::ProfileRegistration> {
        let guard = self.bluez.lock().unwrap();
        let bluez = guard
            .as_ref()
            .ok_or(Error::NotAvailable(Availability::Unauthorized))?;
        crate::classic_profile::ProfileRegistration::register_rfcomm_channel(
            bluez, service, channel, security,
        )
    }

    #[cfg(feature = "classic-l2cap")]
    pub async fn register_classic_l2cap_profile(
        &self,
        service: BluetoothUuid,
        psm: webbluetooth_core::ClassicPsm,
        security: webbluetooth_core::ClassicSecurity,
    ) -> Result<crate::classic_profile::ProfileRegistration> {
        let guard = self.bluez.lock().unwrap();
        let bluez = guard
            .as_ref()
            .ok_or(Error::NotAvailable(Availability::Unauthorized))?;
        crate::classic_profile::ProfileRegistration::register_l2cap(bluez, service, psm, security)
    }

    #[cfg(feature = "classic")]
    pub async fn classic_service_uuids(&self, id: &str) -> Result<Vec<BluetoothUuid>> {
        let path = self.device_path(id)?;
        let object = self
            .with_bluez(|bluez| bluez.object(&path))?
            .ok_or_else(|| Error::NotFound(format!("BlueZ has no device object for {id}")))?;
        let values = object
            .property(interfaces::DEVICE, "UUIDs")
            .and_then(Value::as_array)
            .unwrap_or_default();
        Ok(values
            .iter()
            .filter_map(Value::as_str)
            .filter_map(|uuid| BluetoothUuid::parse(uuid).ok())
            .collect())
    }

    /// Not reachable from an application on this platform.
    ///
    /// BlueZ keeps the negotiated parameters in the kernel; no D-Bus property
    /// carries them.
    pub async fn connection_parameters(
        &self,
        id: &str,
    ) -> Result<webbluetooth_core::ConnectionParameters> {
        let _ = self.is_connected(id);
        Err(Error::NotSupported(
            "BlueZ does not expose negotiated connection parameters over D-Bus".into(),
        ))
    }

    async fn gatt_lock(&self, id: &str) -> Result<futures_util::lock::OwnedMutexGuard<()>> {
        self.devices.gatt_lock(id).await
    }

    /// Revoke a grant, dropping the link with it.
    pub fn forget(&self, id: &str) {
        if let Some(device) = self.sightings.lock().unwrap().get(id).cloned() {
            self.write_sockets
                .lock()
                .unwrap()
                .retain(|characteristic, _| !characteristic.starts_with(&device));
        }
        if let Some(device) = self.devices.remove(id) {
            if device.connected {
                let _ = self.with_bluez(|b| {
                    b.call(&device.inner, interfaces::DEVICE, "Disconnect", vec![])
                });
            }
        }
    }

    // ── Attribute accessors, answered from the cached tree ──────────────────

    fn object(&self, path: &str) -> Option<Object> {
        self.with_bluez(|b| b.object(path)).ok().flatten()
    }

    pub fn service_is_primary(&self, handle: &Handle) -> bool {
        self.object(handle.path())
            .and_then(|o| o.bool(interfaces::SERVICE, "Primary"))
            .unwrap_or(true)
    }

    pub fn characteristic_properties(&self, handle: &Handle) -> CharacteristicProperties {
        // BlueZ reports properties as flag strings rather than a bitmask.
        let flags = self
            .object(handle.path())
            .and_then(|o| o.property(interfaces::CHARACTERISTIC, "Flags").cloned())
            .map(|v| v.as_strings())
            .unwrap_or_default();
        CharacteristicProperties(flags.iter().fold(0, |bits, flag| {
            bits | match flag.as_str() {
                "broadcast" => CharacteristicProperties::BROADCAST,
                "read" => CharacteristicProperties::READ,
                "write-without-response" => CharacteristicProperties::WRITE_WITHOUT_RESPONSE,
                "write" => CharacteristicProperties::WRITE,
                "notify" => CharacteristicProperties::NOTIFY,
                "indicate" => CharacteristicProperties::INDICATE,
                "authenticated-signed-writes" => {
                    CharacteristicProperties::AUTHENTICATED_SIGNED_WRITES
                }
                // BlueZ lists these separately, so keep them separate: the
                // presence of the descriptor and what it says are different
                // questions.
                "extended-properties" => CharacteristicProperties::EXTENDED_PROPERTIES,
                "reliable-write" => CharacteristicProperties::RELIABLE_WRITE,
                "writable-auxiliaries" => CharacteristicProperties::WRITABLE_AUXILIARIES,
                "encrypt-notify" | "encrypt-authenticated-notify" => {
                    CharacteristicProperties::NOTIFY_ENCRYPTION_REQUIRED
                }
                "encrypt-indicate" | "encrypt-authenticated-indicate" => {
                    CharacteristicProperties::INDICATE_ENCRYPTION_REQUIRED
                }
                _ => 0,
            }
        }))
    }

    pub fn cached_value(&self, handle: &Handle) -> Option<Vec<u8>> {
        self.object(handle.path())?
            .property(interfaces::CHARACTERISTIC, "Value")?
            .as_bytes()
    }

    pub fn is_notifying(&self, handle: &Handle) -> bool {
        self.object(handle.path())
            .and_then(|o| o.bool(interfaces::CHARACTERISTIC, "Notifying"))
            .unwrap_or(false)
    }

    // ── GATT operations ─────────────────────────────────────────────────────

    /// Wrap BlueZ's callback-based call in a future.
    /// As [`Inner::call`], keeping any descriptors the reply carried.
    async fn call_with_fds(
        &self,
        path: &str,
        interface: &str,
        member: &str,
        args: Vec<Value>,
    ) -> Result<(Vec<Value>, Vec<std::os::fd::RawFd>)> {
        let (tx, rx) = oneshot::channel();
        self.with_bluez(|b| {
            b.call_async_with_fds(path, interface, member, args, move |reply| {
                let _ = tx.send(reply);
            });
        })?;
        rx.await
            .map_err(|_| Error::Network("the D-Bus call was dropped".into()))?
            .map_err(|e| Error::Network(e.to_string()))
    }

    async fn call(
        &self,
        path: &str,
        interface: &str,
        member: &str,
        args: Vec<Value>,
    ) -> Result<Vec<Value>> {
        let (tx, rx) = oneshot::channel();
        self.with_bluez(|b| {
            b.call_async(path, interface, member, args, move |reply| {
                let _ = tx.send(reply.map(|m| m.body.clone()));
            });
        })?;
        match rx.await {
            Ok(Ok(body)) => Ok(body),
            Ok(Err(e)) => Err(map_error(member, e)),
            Err(_) => Err(Error::Aborted(format!("{member} was cancelled"))),
        }
    }

    pub async fn connect(&self, id: &str) -> Result<()> {
        self.require_powered_on().await?;
        if self.is_connected(id) {
            return Ok(());
        }
        let path = self.device_path(id)?;

        // Register interest before calling: `Connected` can change before the
        // reply lands.
        let connected = {
            let (tx, rx) = oneshot::channel();
            self.connected_waiters
                .lock()
                .unwrap()
                .entry(id.into())
                .or_default()
                .push(tx);
            rx
        };
        let resolved = {
            let (tx, rx) = oneshot::channel();
            self.services_resolved
                .lock()
                .unwrap()
                .entry(id.into())
                .or_default()
                .push(tx);
            rx
        };

        // `Device1.Connect` picks the bearer itself, and for a dual-mode
        // device bonded over BR/EDR only — headphones paired for audio — it
        // picks BR/EDR, where there is no GATT to reach. The error BlueZ
        // gives for that names neither cause nor remedy, so it is replaced.
        let result = self
            .call(&path, interfaces::DEVICE, "Connect", vec![])
            .await;
        result.map_err(explain_bredr_choice)?;
        let _ = connected.await;
        self.devices.update(id, |d| d.connected = true);

        // BlueZ populates the GATT tree asynchronously after connecting, so a
        // read issued too early finds no objects at all. Wait for
        // `ServicesResolved`, but do not fail if it is already true.
        if !self.services_are_resolved(&path) {
            let _ = timer::timeout(Duration::from_secs(20), resolved).await;
        }
        Ok(())
    }

    fn services_are_resolved(&self, path: &str) -> bool {
        self.object(path)
            .and_then(|o| o.bool(interfaces::DEVICE, "ServicesResolved"))
            .unwrap_or(false)
    }

    pub fn disconnect(&self, id: &str) {
        if let Ok(path) = self.device_path(id) {
            let _ = self.with_bluez(|b| {
                b.call_async(&path, interfaces::DEVICE, "Disconnect", vec![], |_| {})
            });
        }
    }

    pub async fn discover_services(
        &self,
        id: &str,
        uuid: Option<&BluetoothUuid>,
    ) -> Result<Vec<Handle>> {
        let _guard = self.gatt_lock(id).await?;
        let path = self.device_path(id)?;
        if !self.is_connected(id) {
            return Err(Error::InvalidState("the device is not connected".into()));
        }
        Ok(self.children(&path, interfaces::SERVICE, uuid))
    }

    pub async fn discover_characteristics(
        &self,
        id: &str,
        service: &Handle,
        uuid: Option<&BluetoothUuid>,
    ) -> Result<Vec<Handle>> {
        let _guard = self.gatt_lock(id).await?;
        Ok(self.children(service.path(), interfaces::CHARACTERISTIC, uuid))
    }

    pub async fn discover_descriptors(
        &self,
        id: &str,
        characteristic: &Handle,
        uuid: Option<&BluetoothUuid>,
    ) -> Result<Vec<Handle>> {
        let _guard = self.gatt_lock(id).await?;
        Ok(self.children(characteristic.path(), interfaces::DESCRIPTOR, uuid))
    }

    /// The services an `Includes` declaration points at.
    ///
    /// Unlike characteristics, an included service is not a child of the
    /// service that includes it: BlueZ lists it as an array of object paths in
    /// the `Includes` property, and the object itself sits beside its includer
    /// under the device. So this resolves paths rather than walking the tree.
    pub async fn discover_included_services(
        &self,
        id: &str,
        service: &Handle,
        uuid: Option<&BluetoothUuid>,
    ) -> Result<Vec<Handle>> {
        let _guard = self.gatt_lock(id).await?;
        if !self.is_connected(id) {
            return Err(Error::InvalidState("the device is not connected".into()));
        }

        // `Includes` is optional, and absent rather than empty when a service
        // includes nothing.
        let included = self
            .object(service.path())
            .and_then(|o| o.property(interfaces::SERVICE, "Includes").cloned());
        let Some(included) = included else {
            return Ok(Vec::new());
        };

        let mut out = Vec::new();
        for entry in included.as_array().unwrap_or(&[]) {
            let Some(path) = entry.peel().as_str() else {
                continue;
            };
            let Some(raw) = self
                .object(path)
                .and_then(|o| o.string(interfaces::SERVICE, "UUID"))
            else {
                continue;
            };
            let Ok(found) = BluetoothUuid::parse(&raw) else {
                continue;
            };
            if uuid.is_some_and(|want| *want != found) {
                continue;
            }
            out.push(Handle::new(path, found));
        }
        Ok(out)
    }

    /// Walk the cached tree for children of `parent` on `interface`.
    fn children(&self, parent: &str, interface: &str, uuid: Option<&BluetoothUuid>) -> Vec<Handle> {
        let Ok(paths) = self.with_bluez(|b| b.children_with(parent, interface)) else {
            return Vec::new();
        };
        paths
            .into_iter()
            .filter_map(|p| {
                let raw = self.object(&p)?.string(interface, "UUID")?;
                let found = BluetoothUuid::parse(&raw).ok()?;
                match uuid {
                    Some(want) if *want != found => None,
                    _ => Some(Handle::new(&p, found)),
                }
            })
            .collect()
    }

    pub async fn read_characteristic(&self, id: &str, handle: &Handle) -> Result<Vec<u8>> {
        let _guard = self.gatt_lock(id).await?;
        let body = self
            .call(
                handle.path(),
                interfaces::CHARACTERISTIC,
                "ReadValue",
                vec![Value::dict([])],
            )
            .await?;
        body.first()
            .and_then(Value::as_bytes)
            .ok_or_else(|| Error::Network("ReadValue returned no bytes".into()))
    }

    pub async fn write_characteristic(
        &self,
        id: &str,
        handle: &Handle,
        value: &[u8],
        write_type: WriteType,
    ) -> Result<()> {
        // An unacknowledged write can go straight down a socket BlueZ hands
        // out, skipping the round trip into `bluetoothd` that `WriteValue`
        // costs on every packet. Tried first, and only for this write type —
        // `AcquireWrite` has no acknowledged form.
        if write_type == WriteType::WithoutResponse {
            if let Some(sent) = self.write_over_socket(id, handle, value).await? {
                return Ok(sent);
            }
        }

        // Only the acknowledged form takes the lock. `WriteValue` with
        // `type: "command"` is an independent D-Bus call that BlueZ turns into
        // an ATT command, which is not subject to the one-outstanding-request
        // rule the lock exists for.
        let _guard = match write_type {
            WriteType::WithResponse => Some(self.gatt_lock(id).await?),
            WriteType::WithoutResponse => None,
        };
        let kind = match write_type {
            WriteType::WithResponse => "request",
            WriteType::WithoutResponse => "command",
        };
        self.call(
            handle.path(),
            interfaces::CHARACTERISTIC,
            "WriteValue",
            vec![
                Value::bytes(value),
                Value::dict([("type".to_string(), Value::Str(kind.into()))]),
            ],
        )
        .await?;
        Ok(())
    }

    pub async fn set_notify(&self, id: &str, handle: &Handle, enabled: bool) -> Result<bool> {
        let _guard = self.gatt_lock(id).await?;
        let member = if enabled { "StartNotify" } else { "StopNotify" };
        self.call(handle.path(), interfaces::CHARACTERISTIC, member, vec![])
            .await?;
        Ok(enabled)
    }

    pub fn subscribe(&self, handle: &Handle) -> webbluetooth_core::backlog::Receiver<Vec<u8>> {
        // Bounded: a notification arrives on a platform callback
        // thread that must return promptly, so there is nobody to
        // apply backpressure to. See `webbluetooth_core::backlog`.
        let (tx, rx) = webbluetooth_core::backlog::channel();
        self.notifications
            .lock()
            .unwrap()
            .entry(handle.path().to_owned())
            .or_default()
            .push(tx);
        rx
    }

    pub async fn read_descriptor(&self, id: &str, handle: &Handle) -> Result<Vec<u8>> {
        let _guard = self.gatt_lock(id).await?;
        let body = self
            .call(
                handle.path(),
                interfaces::DESCRIPTOR,
                "ReadValue",
                vec![Value::dict([])],
            )
            .await?;
        body.first()
            .and_then(Value::as_bytes)
            .ok_or_else(|| Error::Network("ReadValue returned no bytes".into()))
    }

    pub async fn write_descriptor(&self, id: &str, handle: &Handle, value: &[u8]) -> Result<()> {
        let _guard = self.gatt_lock(id).await?;
        self.call(
            handle.path(),
            interfaces::DESCRIPTOR,
            "WriteValue",
            vec![Value::bytes(value), Value::dict([])],
        )
        .await?;
        Ok(())
    }

    pub async fn read_rssi(&self, id: &str) -> Result<i32> {
        let path = self.device_path(id)?;
        // BlueZ keeps RSSI as a property rather than offering a read, and drops
        // the property entirely once a device is no longer being advertised at.
        // 127 is the "no reading" sentinel, which must not be handed back as if
        // it were a measurement.
        self.object(&path)
            .and_then(|o| o.int(interfaces::DEVICE, "RSSI"))
            .map(|v| v as i32)
            .filter(|v| *v != webbluetooth_core::filter::UNAVAILABLE_RSSI)
            .ok_or_else(|| Error::NotSupported("no RSSI is available for this device".into()))
    }

    pub async fn request_connection_priority(
        &self,
        _id: &str,
        _priority: webbluetooth_core::ConnectionPriority,
    ) -> Result<()> {
        Err(Error::NotSupported(
            "BlueZ has no D-Bus API for connection parameters; they are set \
             through the kernel management socket, which bluetoothd owns"
                .into(),
        ))
    }

    pub async fn request_mtu(&self, _id: &str, _mtu: u16) -> Result<()> {
        Err(Error::NotSupported(
            "BlueZ does not expose an ATT MTU request API".into(),
        ))
    }

    pub fn max_write_len(&self, id: &str, _write_type: WriteType) -> Result<usize> {
        // BlueZ exposes MTU per characteristic; without one, fall back to the
        // smallest an ATT write is guaranteed to carry.
        let path = self.device_path(id)?;
        let mtu = self
            .with_bluez(|b| b.children_with(&path, interfaces::CHARACTERISTIC))?
            .into_iter()
            .find_map(|p| self.object(&p)?.int(interfaces::CHARACTERISTIC, "MTU"));
        Ok(mtu.map(|m| (m as usize).saturating_sub(3)).unwrap_or(20))
    }

    pub async fn l2cap_target(&self, id: &str, _psm: u16) -> Result<(String, String)> {
        let path = self.device_path(id)?;
        let address = self
            .object(&path)
            .and_then(|o| o.string(interfaces::DEVICE, "Address"))
            .ok_or_else(|| Error::InvalidState("the device has no address".into()))?;
        let address_type = self
            .object(&path)
            .and_then(|o| o.string(interfaces::DEVICE, "AddressType"))
            .unwrap_or_else(|| "public".into());
        Ok((address, address_type))
    }
}

/// Turn a BlueZ D-Bus error into the spec's vocabulary.
/// Say why a dual-mode device failed to connect, when BlueZ chose BR/EDR.
///
/// BlueZ reports it as `br-connection-profile-unavailable` and the like, which
/// names neither the cause nor anything a caller can do about it.
fn explain_bredr_choice(error: Error) -> Error {
    match error {
        Error::Network(message) if message.contains("br-connection") => Error::Network(format!(
            "{message}: BlueZ chose Bluetooth Classic (BR/EDR) for this dual-mode \
             device, and GATT needs LE. It does for a device bonded over BR/EDR only, \
             and for some that are not bonded at all — a Mac advertising with its \
             public address, for one. A BlueZ new enough to expose Device1.PreferredBearer, run with \
             experimental interfaces (`bluetoothd -E`), can be told to prefer \"le\" \
             for this device."
        )),
        other => other,
    }
}

fn map_error(member: &str, e: crate::dbus::connection::Error) -> Error {
    use crate::dbus::connection::Error as D;
    match &e {
        D::Call { name, message } => match name.as_str() {
            "org.bluez.Error.NotPermitted" | "org.bluez.Error.NotAuthorized" => {
                Error::Security(format!("{member} refused: {message}"))
            }
            "org.bluez.Error.NotSupported" => Error::NotSupported(message.clone()),
            "org.bluez.Error.InvalidValueLength" => Error::InvalidModification(message.clone()),
            "org.bluez.Error.NotConnected" => Error::InvalidState(message.clone()),
            _ => Error::Network(format!("{member} failed: {message}")),
        },
        D::Timeout => Error::Timeout(format!("{member} timed out")),
        D::Disconnected => Error::InvalidState("the connection to BlueZ was lost".into()),
        other => Error::Network(format!("{member} failed: {other}")),
    }
}

/// Build the shared advertisement view from BlueZ device properties.
fn advertisement_from(props: &HashMap<String, Value>) -> Advertisement {
    let mut manufacturer_data = HashMap::new();
    if let Some(md) = props.get("ManufacturerData") {
        // `a{qv}`: company identifier → bytes.
        for item in md.as_array().unwrap_or(&[]) {
            if let Value::DictEntry(k, v) = item.peel() {
                if let (Some(company), Some(bytes)) = (k.as_u64(), v.as_bytes()) {
                    manufacturer_data.insert(company as u16, bytes);
                }
            }
        }
    }

    let mut service_data = HashMap::new();
    if let Some(sd) = props.get("ServiceData") {
        for (uuid, bytes) in sd.as_map() {
            if let (Ok(uuid), Some(bytes)) = (BluetoothUuid::parse(&uuid), bytes.as_bytes()) {
                service_data.insert(uuid, bytes);
            }
        }
    }

    Advertisement {
        #[cfg(feature = "classic")]
        class_of_device: props
            .get("Class")
            .and_then(Value::as_u64)
            .map(|value| webbluetooth_core::ClassOfDevice::from_raw(value as u32)),
        local_name: props
            .get("Name")
            .or_else(|| props.get("Alias"))
            .and_then(Value::as_str)
            .map(str::to_owned),
        tx_power: props
            .get("TxPower")
            .and_then(Value::as_i64)
            .map(|v| v as i16),
        appearance: props
            .get("Appearance")
            .and_then(Value::as_u64)
            .map(|v| v as u16),
        // BlueZ only surfaces connectable devices through Device1.
        is_connectable: Some(true),
        service_uuids: props
            .get("UUIDs")
            .map(|v| v.as_strings())
            .unwrap_or_default()
            .iter()
            .filter_map(|s| BluetoothUuid::parse(s).ok())
            .collect(),
        // No Apple-style overflow area on Linux.
        overflow_service_uuids: Vec::new(),
        solicited_service_uuids: Vec::new(),
        manufacturer_data,
        service_data,
        rssi: props
            .get("RSSI")
            .and_then(Value::as_i64)
            .map(|v| v as i32)
            .unwrap_or(127),
        // BlueZ hands over D-Bus properties, not the packet they came from.
        // The `linux-hci` backend, which reads the reports itself, does have
        // the bytes.
        raw: None,
    }
}

/// Whether this process may use Bluetooth.
///
/// Linux has no per-application Bluetooth permission. What it does have is
/// D-Bus policy: reaching `org.bluez` at all requires the caller be in a group
/// the system bus configuration allows. So reachability is the honest answer to
/// the same question.
pub fn authorization() -> webbluetooth_core::Authorization {
    match crate::dbus::Connection::system() {
        Ok(_) => webbluetooth_core::Authorization::Allowed,
        Err(_) => webbluetooth_core::Authorization::Denied,
    }
}

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

    /// The error a caller sees when BlueZ connects a dual-mode device over
    /// BR/EDR has to say so; anything else passes through untouched.
    #[test]
    fn a_bredr_connection_failure_is_explained() {
        let explained = explain_bredr_choice(Error::Network(
            "Connect failed: br-connection-profile-unavailable".into(),
        ));
        let Error::Network(message) = explained else {
            panic!("still a NetworkError");
        };
        assert!(
            message.contains("br-connection-profile-unavailable"),
            "{message}"
        );
        assert!(message.contains("PreferredBearer"), "{message}");

        let untouched = explain_bredr_choice(Error::Network("Connect failed: timeout".into()));
        assert!(matches!(untouched, Error::Network(m) if m == "Connect failed: timeout"));
    }
}