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
//! The GATT tree: server, service, characteristic, descriptor.
//!
//! Each type is a handle into a device's attribute table, valid only while the
//! connection that produced it lasts. A handle records the generation it was
//! minted in; a disconnect or a `didModifyServices:` bumps that generation and
//! every stale handle then fails rather than messaging a freed `CBService`.
//! Which failure depends on what went wrong: `NetworkError` while the device
//! is still disconnected, and `InvalidStateError` once it is back, because
//! reconnecting fixes the first and only rediscovery fixes the second.

use crate::backend::attribute_uuid;
use crate::backend::Handle;
use crate::blocklist;
use crate::error::{Error, Result};
use crate::uuid::{BluetoothUuid, IntoUuid};
use futures_core::Stream;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
pub use webbluetooth_core::gatt::{CharacteristicProperties, WriteType};

/// The largest value the spec permits in a single write.
const MAX_ATTRIBUTE_LENGTH: usize = 512;

fn descriptor_suffix(value: &[u8], offset: usize) -> Result<Vec<u8>> {
    if offset > value.len() {
        return Err(Error::InvalidModification(format!(
            "descriptor offset {offset} exceeds its {}-byte value",
            value.len()
        )));
    }
    Ok(value[offset..].to_vec())
}

fn descriptor_patch(mut current: Vec<u8>, offset: usize, value: &[u8]) -> Result<Vec<u8>> {
    if offset > current.len() {
        return Err(Error::InvalidModification(format!(
            "descriptor offset {offset} exceeds its {}-byte value",
            current.len()
        )));
    }
    let end = offset
        .checked_add(value.len())
        .ok_or_else(|| Error::InvalidModification("descriptor value is too large".into()))?;
    if end > MAX_ATTRIBUTE_LENGTH {
        return Err(Error::InvalidModification(format!(
            "value is {end} bytes; a GATT attribute holds at most {MAX_ATTRIBUTE_LENGTH}"
        )));
    }
    if current.len() < end {
        current.resize(end, 0);
    }
    current[offset..end].copy_from_slice(value);
    Ok(current)
}

/// `BluetoothRemoteGATTServer`.
#[derive(Clone)]
pub struct RemoteGattServer {
    pub(crate) inner: Arc<crate::session::Session>,
    pub(crate) id: String,
}

impl RemoteGattServer {
    /// Watch for the service set changing — the specification's
    /// `serviceadded`, `servicechanged` and `serviceremoved`.
    ///
    /// Yields once per change. Every handle obtained before the change is
    /// stale afterwards — `Network` until the device is back, `InvalidState`
    /// after that — so a caller should re-discover rather than retry.
    ///
    /// One stream rather than three events: the platforms report *that* the
    /// set changed, not which service, so splitting it would mean inventing
    /// detail. Reported where the platform says so — CoreBluetooth's
    /// `didModifyServices:` and Android's `onServiceChanged`.
    pub fn watch_services_changed(&self) -> crate::ServiceEvents {
        crate::ServiceEvents {
            rx: self.inner.watch_services_changed(&self.id),
        }
    }

    /// The device this server belongs to — `BluetoothRemoteGATTServer.device`.
    pub fn device(&self) -> crate::BluetoothDevice {
        crate::BluetoothDevice {
            inner: self.inner.clone(),
            id: self.id.clone(),
        }
    }

    /// Whether the link is currently up.
    pub fn connected(&self) -> bool {
        self.inner.is_connected(&self.id)
    }

    /// Open a connection. Resolves once CoreBluetooth reports the link is up.
    ///
    /// Unlike a socket connect there is no built-in timeout: CoreBluetooth will
    /// wait indefinitely for a peripheral to come into range. Wrap this in
    /// [`crate::timeout`] if that is not what you want.
    /// # Example
    ///
    /// ```no_run
    /// # use webbluetooth::uuid::services;
    /// # async fn example(device: webbluetooth::BluetoothDevice) -> webbluetooth::Result<()> {
    /// let gatt = device.gatt();
    /// gatt.connect().await?;
    ///
    /// let service = gatt.get_primary_service(services::BATTERY_SERVICE).await?;
    /// # let _ = service;
    /// # Ok(()) }
    /// ```
    pub async fn connect(&self) -> Result<()> {
        self.inner.backend().connect(&self.id).await
    }

    /// Close the connection. Every handle into this device becomes stale.
    pub fn disconnect(&self) {
        self.inner.disconnect(&self.id);
    }

    /// Close the connection and wait until the link is actually down.
    ///
    /// [`disconnect`](Self::disconnect) only asks: it returns at once and the
    /// platform reports the link gone some time later. That is all the
    /// specification offers, and it is not enough for a caller whose next step
    /// depends on the link being down — a device that will not accept a
    /// Bluetooth Classic connection while its LE one is up, or a reconnect
    /// that must not race the teardown it follows.
    ///
    /// Returns immediately if the device is not connected. There is no
    /// timeout, for the same reason [`connect`](Self::connect) has none; wrap
    /// it in [`crate::timeout`] if the platform cannot be trusted to answer.
    ///
    /// Not part of Web Bluetooth.
    ///
    /// ```no_run
    /// # async fn example(gatt: webbluetooth::RemoteGattServer) {
    /// gatt.disconnect_and_wait().await;
    /// assert!(!gatt.connected());
    /// # }
    /// ```
    pub async fn disconnect_and_wait(&self) {
        use futures_util::StreamExt;

        // Watching before asking, so a platform that reports the disconnect
        // from inside the call cannot be missed.
        let mut disconnects = self.inner.watch_disconnect(&self.id);
        self.inner.disconnect(&self.id);
        if self.connected() {
            disconnects.next().await;
        }
    }

    /// Every characteristic of every primary service the grant reaches.
    ///
    /// [`get_primary_services`](Self::get_primary_services) and then
    /// [`RemoteGattService::get_characteristics`] on each, flattened — which
    /// is the flat set `btleplug`'s `peripheral.characteristics()` returns,
    /// and the loop every program arriving from there writes on its first
    /// day. Each characteristic still knows its service:
    /// [`RemoteGattCharacteristic::service_uuid`].
    ///
    /// A service with no accessible characteristics contributes nothing rather
    /// than failing the call; any other failure is returned. "Every" is still
    /// bounded by the grant and the blocklist, as it is everywhere else.
    ///
    /// Not part of Web Bluetooth.
    ///
    /// ```no_run
    /// # async fn example(gatt: webbluetooth::RemoteGattServer) -> webbluetooth::Result<()> {
    /// for characteristic in gatt.get_characteristics().await? {
    ///     if characteristic.properties().notify() {
    ///         println!("{} notifies", characteristic.uuid());
    ///     }
    /// }
    /// # Ok(()) }
    /// ```
    pub async fn get_characteristics(&self) -> Result<Vec<RemoteGattCharacteristic>> {
        let mut out = Vec::new();
        for service in self.get_primary_services(None).await? {
            match service.get_characteristics(None).await {
                Ok(found) => out.extend(found),
                Err(Error::NotFound(_)) => {}
                Err(e) => return Err(e),
            }
        }
        Ok(out)
    }

    /// The primary service with this UUID.
    ///
    /// `SecurityError` if the service was not listed in the `filters` or
    /// `optional_services` of the request that produced this device — the same
    /// rule a browser applies.
    pub async fn get_primary_service(&self, uuid: impl IntoUuid) -> Result<RemoteGattService> {
        let uuid = uuid.into_uuid()?;
        self.guard_service(&uuid)?;
        let found = self.inner.discover_services(&self.id, Some(&uuid)).await?;
        let handle = found
            .into_iter()
            .next()
            .ok_or_else(|| Error::NotFound(format!("no primary service {uuid} on this device")))?;
        self.service_from(handle, uuid)
    }

    /// Every primary service, or every one matching `uuid`.
    ///
    /// Services outside the grant are omitted rather than reported — a caller
    /// must not learn what else the device offers.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # async fn example(gatt: webbluetooth::RemoteGattServer) -> webbluetooth::Result<()> {
    /// // Every service this device granted access to. Passing a UUID narrows
    /// // it to that one; `None` is "all of them", which is still only the
    /// // ones the request asked for.
    /// for service in gatt.get_primary_services(None).await? {
    ///     println!("{}", service.uuid());
    /// }
    /// # Ok(()) }
    /// ```
    /// `None` means every one of them. Anything [`IntoUuid`] accepts narrows
    /// it — bare, without a `Some`: `get_primary_services("heart_rate")`.
    /// `Some(services::HEART_RATE)` works too, because an assigned number is
    /// a [`BluetoothUuid`].
    ///
    pub async fn get_primary_services(
        &self,
        uuid: impl webbluetooth_core::uuid::IntoOptionalUuid,
    ) -> Result<Vec<RemoteGattService>> {
        let uuid = uuid.into_optional_uuid()?;
        if let Some(u) = &uuid {
            self.guard_service(u)?;
        }
        let allowed = self.inner.allowed_services(&self.id)?;
        let found = self
            .inner
            .discover_services(&self.id, uuid.as_ref())
            .await?;

        let mut out = Vec::new();
        for handle in found {
            let Ok(u) = attribute_uuid(&handle) else {
                continue;
            };
            if !allowed.contains(&u) || blocklist::is_blocked(&u) {
                continue;
            }
            out.push(self.service_from(handle, u)?);
        }
        if out.is_empty() {
            return Err(Error::NotFound(
                "no accessible primary services on this device".into(),
            ));
        }
        Ok(out)
    }

    fn guard_service(&self, uuid: &BluetoothUuid) -> Result<()> {
        if blocklist::is_blocked(uuid) {
            return Err(Error::Security(format!(
                "service {uuid} is on the GATT blocklist"
            )));
        }
        self.inner.check_allowed(&self.id, uuid)
    }

    fn service_from(&self, handle: Handle, uuid: BluetoothUuid) -> Result<RemoteGattService> {
        Ok(RemoteGattService {
            is_primary: self.inner.service_is_primary(&handle),
            inner: self.inner.clone(),
            device_id: self.id.clone(),
            generation: self.inner.generation(&self.id)?,
            handle,
            uuid,
        })
    }
}

/// `BluetoothRemoteGATTService`.
#[derive(Clone)]
pub struct RemoteGattService {
    inner: Arc<crate::session::Session>,
    device_id: String,

    handle: Handle,
    uuid: BluetoothUuid,
    generation: u64,
    is_primary: bool,
}

impl RemoteGattService {
    /// This service's UUID — `BluetoothRemoteGATTService.uuid`.
    pub fn uuid(&self) -> &BluetoothUuid {
        &self.uuid
    }

    /// The device this service is on — `BluetoothRemoteGATTService.device`.
    pub fn device(&self) -> crate::BluetoothDevice {
        crate::BluetoothDevice {
            inner: self.inner.clone(),
            id: self.device_id.clone(),
        }
    }

    /// Whether this is a primary service rather than an included one.
    pub fn is_primary(&self) -> bool {
        self.is_primary
    }

    /// The characteristic with this UUID.
    pub async fn get_characteristic(
        &self,
        uuid: impl IntoUuid,
    ) -> Result<RemoteGattCharacteristic> {
        let uuid = uuid.into_uuid()?;
        self.inner
            .check_generation(&self.device_id, self.generation)?;
        if blocklist::is_blocked(&uuid) {
            return Err(Error::Security(format!(
                "characteristic {uuid} is on the GATT blocklist"
            )));
        }
        let found = self
            .inner
            .discover_characteristics(&self.device_id, &self.handle, Some(&uuid))
            .await?;
        let handle = found.into_iter().next().ok_or_else(|| {
            Error::NotFound(format!("no characteristic {uuid} in service {}", self.uuid))
        })?;
        self.characteristic_from(handle, uuid)
    }

    /// Every characteristic, or every one matching `uuid`.
    /// `None` means every one of them. Anything [`IntoUuid`] accepts narrows
    /// it — bare, without a `Some`: `get_primary_services("heart_rate")`.
    /// `Some(services::HEART_RATE)` works too, because an assigned number is
    /// a [`BluetoothUuid`].
    ///
    pub async fn get_characteristics(
        &self,
        uuid: impl webbluetooth_core::uuid::IntoOptionalUuid,
    ) -> Result<Vec<RemoteGattCharacteristic>> {
        let uuid = uuid.into_optional_uuid()?;
        self.inner
            .check_generation(&self.device_id, self.generation)?;
        let found = self
            .inner
            .discover_characteristics(&self.device_id, &self.handle, uuid.as_ref())
            .await?;
        let mut out = Vec::new();
        for handle in found {
            let Ok(u) = attribute_uuid(&handle) else {
                continue;
            };
            if blocklist::is_blocked(&u) {
                continue;
            }
            out.push(self.characteristic_from(handle, u)?);
        }
        if out.is_empty() {
            return Err(Error::NotFound(format!(
                "no accessible characteristics in service {}",
                self.uuid
            )));
        }
        Ok(out)
    }

    /// The included service with this UUID — `getIncludedService()`.
    ///
    /// An included service is one a primary service points at with an Include
    /// declaration, so that a composite service can reuse a definition rather
    /// than restate it. The access rules are the same as for a primary
    /// service: the allowlist decides, and the blocklist overrides it.
    pub async fn get_included_service(&self, uuid: impl IntoUuid) -> Result<RemoteGattService> {
        let uuid = uuid.into_uuid()?;
        self.inner
            .check_generation(&self.device_id, self.generation)?;
        self.guard_included(&uuid)?;
        let found = self
            .inner
            .discover_included_services(&self.device_id, &self.handle, Some(&uuid))
            .await?;
        let handle = found.into_iter().next().ok_or_else(|| {
            Error::NotFound(format!(
                "no included service {uuid} in service {}",
                self.uuid
            ))
        })?;
        self.included_from(handle, uuid)
    }

    /// Every included service, or every one matching `uuid`.
    ///
    /// Services outside the grant are omitted rather than reported, exactly as
    /// for primary services — being reachable through an Include declaration
    /// does not widen what a caller was granted.
    /// `None` means every one of them. Anything [`IntoUuid`] accepts narrows
    /// it — bare, without a `Some`: `get_primary_services("heart_rate")`.
    /// `Some(services::HEART_RATE)` works too, because an assigned number is
    /// a [`BluetoothUuid`].
    ///
    pub async fn get_included_services(
        &self,
        uuid: impl webbluetooth_core::uuid::IntoOptionalUuid,
    ) -> Result<Vec<RemoteGattService>> {
        let uuid = uuid.into_optional_uuid()?;
        self.inner
            .check_generation(&self.device_id, self.generation)?;
        if let Some(u) = &uuid {
            self.guard_included(u)?;
        }
        let allowed = self.inner.allowed_services(&self.device_id)?;
        let found = self
            .inner
            .discover_included_services(&self.device_id, &self.handle, uuid.as_ref())
            .await?;

        let mut out = Vec::new();
        for handle in found {
            let Ok(u) = attribute_uuid(&handle) else {
                continue;
            };
            if !allowed.contains(&u) || blocklist::is_blocked(&u) {
                continue;
            }
            out.push(self.included_from(handle, u)?);
        }
        if out.is_empty() {
            return Err(Error::NotFound(format!(
                "no accessible included services in service {}",
                self.uuid
            )));
        }
        Ok(out)
    }

    fn guard_included(&self, uuid: &BluetoothUuid) -> Result<()> {
        if blocklist::is_blocked(uuid) {
            return Err(Error::Security(format!(
                "service {uuid} is on the GATT blocklist"
            )));
        }
        self.inner.check_allowed(&self.device_id, uuid)
    }

    fn included_from(&self, handle: Handle, uuid: BluetoothUuid) -> Result<RemoteGattService> {
        Ok(RemoteGattService {
            // An included service is by definition not primary, whatever the
            // platform reports for the handle.
            is_primary: false,
            inner: self.inner.clone(),
            device_id: self.device_id.clone(),
            generation: self.generation,
            handle,
            uuid,
        })
    }

    fn characteristic_from(
        &self,
        handle: Handle,
        uuid: BluetoothUuid,
    ) -> Result<RemoteGattCharacteristic> {
        Ok(RemoteGattCharacteristic {
            properties: self.inner.characteristic_properties(&handle),
            inner: self.inner.clone(),
            device_id: self.device_id.clone(),
            service_uuid: self.uuid,
            service_handle: self.handle.clone(),
            generation: self.generation,
            handle,
            uuid,
        })
    }
}

impl std::fmt::Debug for RemoteGattService {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RemoteGattService")
            .field("uuid", &self.uuid.as_str())
            .field("is_primary", &self.is_primary)
            .finish()
    }
}

/// `BluetoothRemoteGATTCharacteristic`.
#[derive(Clone)]
pub struct RemoteGattCharacteristic {
    inner: Arc<crate::session::Session>,
    device_id: String,
    service_uuid: BluetoothUuid,
    /// The service's own handle, so [`Self::service`] can hand back the
    /// service rather than just its UUID — which is what the specification's
    /// `.service` is.
    service_handle: Handle,
    handle: Handle,
    uuid: BluetoothUuid,
    generation: u64,
    properties: CharacteristicProperties,
}

impl RemoteGattCharacteristic {
    /// The service this characteristic belongs to —
    /// `BluetoothRemoteGATTCharacteristic.service`.
    pub fn service(&self) -> RemoteGattService {
        RemoteGattService {
            is_primary: self.inner.service_is_primary(&self.service_handle),
            inner: self.inner.clone(),
            device_id: self.device_id.clone(),
            generation: self.generation,
            handle: self.service_handle.clone(),
            uuid: self.service_uuid,
        }
    }

    /// This characteristic's UUID — `BluetoothRemoteGATTCharacteristic.uuid`.
    pub fn uuid(&self) -> &BluetoothUuid {
        &self.uuid
    }

    /// The UUID of the service this characteristic belongs to.
    pub fn service_uuid(&self) -> &BluetoothUuid {
        &self.service_uuid
    }

    /// What the peer says this characteristic supports.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # async fn example(c: webbluetooth::RemoteGattCharacteristic) -> webbluetooth::Result<()> {
    /// if c.properties().notify() {
    ///     let _stream = c.start_notifications().await?;
    /// } else if c.properties().read() {
    ///     let _value = c.read_value().await?;
    /// }
    /// # Ok(()) }
    /// ```
    pub fn properties(&self) -> CharacteristicProperties {
        self.properties
    }

    /// The last value read or notified, without going to the device.
    pub fn value(&self) -> Option<Vec<u8>> {
        self.inner.cached_value(&self.handle)
    }

    /// Read the current value from the device.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use webbluetooth::uuid::characteristics;
    /// # async fn example(service: webbluetooth::RemoteGattService) -> webbluetooth::Result<()> {
    /// let level = service.get_characteristic(characteristics::BATTERY_LEVEL).await?;
    /// let value = level.read_value().await?;
    /// println!("{}%", value[0]);
    /// # Ok(()) }
    /// ```
    pub async fn read_value(&self) -> Result<Vec<u8>> {
        self.inner
            .check_generation(&self.device_id, self.generation)?;
        if blocklist::reads_blocked(&self.uuid) {
            return Err(Error::Security(format!(
                "reading {} is blocklisted",
                self.uuid
            )));
        }
        if !self.properties.read() {
            return Err(Error::NotSupported(format!(
                "characteristic {} does not support reading",
                self.uuid
            )));
        }
        self.inner
            .read_characteristic(&self.device_id, &self.handle)
            .await
    }

    /// Read the descriptor and return the bytes beginning at `offset`.
    ///
    /// Descriptor values are bounded by the ATT attribute limit. The portable
    /// API reads the complete value first because several platform APIs do not
    /// expose ATT's long-read offset directly.
    pub async fn read_value_at_offset(&self, offset: usize) -> Result<Vec<u8>> {
        descriptor_suffix(&self.read_value().await?, offset)
    }

    /// Write and wait for the peer to acknowledge —
    /// `writeValueWithResponse()`.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # async fn example(c: webbluetooth::RemoteGattCharacteristic) -> webbluetooth::Result<()> {
    /// // Fails if the peer refuses it. The unacknowledged form would not.
    /// c.write_value_with_response(&[0x01]).await?;
    /// # Ok(()) }
    /// ```
    pub async fn write_value_with_response(&self, value: &[u8]) -> Result<()> {
        self.guard_write(value)?;
        if !self.properties.write() {
            return Err(Error::NotSupported(format!(
                "characteristic {} does not support acknowledged writes",
                self.uuid
            )));
        }
        self.inner
            .write_characteristic(
                &self.device_id,
                &self.handle,
                value,
                WriteType::WithResponse,
            )
            .await
    }

    /// Write without waiting for acknowledgement —
    /// `writeValueWithoutResponse()`.
    ///
    /// Returns as soon as the write is handed to CoreBluetooth. There is no
    /// delivery confirmation and no flow control: a burst can be dropped
    /// silently. Check [`RemoteGattCharacteristic::max_write_length`] and pace
    /// large transfers.
    pub async fn write_value_without_response(&self, value: &[u8]) -> Result<()> {
        self.guard_write(value)?;
        if !self.properties.write_without_response() {
            return Err(Error::NotSupported(format!(
                "characteristic {} does not support unacknowledged writes",
                self.uuid
            )));
        }
        self.inner
            .write_characteristic(
                &self.device_id,
                &self.handle,
                value,
                WriteType::WithoutResponse,
            )
            .await
    }

    /// The most bytes one write can carry, given the negotiated ATT MTU.
    pub fn max_write_length(&self, with_response: bool) -> Result<usize> {
        let t = if with_response {
            WriteType::WithResponse
        } else {
            WriteType::WithoutResponse
        };
        self.inner.max_write_len(&self.device_id, t)
    }

    /// Subscribe to notifications or indications.
    ///
    /// Returns a stream of values. The stream ends when the device disconnects.
    /// Dropping it does not stop the subscription on the peer — call
    /// [`RemoteGattCharacteristic::stop_notifications`] for that.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use futures_util::StreamExt;
    /// # use webbluetooth::uuid::characteristics;
    /// # async fn example(service: webbluetooth::RemoteGattService) -> webbluetooth::Result<()> {
    /// 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]);
    /// }
    /// // Dropping the stream is what stops the subscription.
    /// # Ok(()) }
    /// ```
    pub async fn start_notifications(&self) -> Result<Notifications> {
        self.inner
            .check_generation(&self.device_id, self.generation)?;
        if !self.properties.notify() && !self.properties.indicate() {
            return Err(Error::NotSupported(format!(
                "characteristic {} supports neither notifications nor indications",
                self.uuid
            )));
        }
        // Subscribe before enabling, so a notification that races the
        // acknowledgement is not lost.
        let rx = self.inner.subscribe(&self.handle);
        // Taken before the subscription is enabled, for the same reason: a
        // link that drops while the request is in flight is still seen.
        let disconnects = self.inner.watch_disconnect(&self.device_id);
        self.inner
            .set_notify(&self.device_id, &self.handle, true)
            .await?;
        Ok(Notifications {
            rx,
            disconnects,
            ended: false,
            characteristic: self.clone(),
        })
    }

    /// Stop notifications on the peer.
    pub async fn stop_notifications(&self) -> Result<()> {
        self.inner
            .check_generation(&self.device_id, self.generation)?;
        self.inner
            .set_notify(&self.device_id, &self.handle, false)
            .await?;
        Ok(())
    }

    /// Whether the peer currently has notifications enabled.
    pub fn is_notifying(&self) -> bool {
        self.inner.is_notifying(&self.handle)
    }

    /// The descriptor with this UUID.
    pub async fn get_descriptor(&self, uuid: impl IntoUuid) -> Result<RemoteGattDescriptor> {
        let uuid = uuid.into_uuid()?;
        self.inner
            .check_generation(&self.device_id, self.generation)?;
        let found = self
            .inner
            .discover_descriptors(&self.device_id, &self.handle, Some(&uuid))
            .await?;
        let handle = found.into_iter().next().ok_or_else(|| {
            Error::NotFound(format!(
                "no descriptor {uuid} on characteristic {}",
                self.uuid
            ))
        })?;
        Ok(self.descriptor_from(handle, uuid))
    }

    /// Every descriptor on this characteristic.
    pub async fn get_descriptors(&self) -> Result<Vec<RemoteGattDescriptor>> {
        self.inner
            .check_generation(&self.device_id, self.generation)?;
        let found = self
            .inner
            .discover_descriptors(&self.device_id, &self.handle, None)
            .await?;
        Ok(found
            .into_iter()
            .filter_map(|h| {
                let u = attribute_uuid(&h).ok()?;
                Some(self.descriptor_from(h, u))
            })
            .collect())
    }

    fn descriptor_from(&self, handle: Handle, uuid: BluetoothUuid) -> RemoteGattDescriptor {
        RemoteGattDescriptor {
            inner: self.inner.clone(),
            device_id: self.device_id.clone(),
            characteristic_uuid: self.uuid,
            characteristic_handle: self.handle.clone(),
            service_uuid: self.service_uuid,
            service_handle: self.service_handle.clone(),
            generation: self.generation,
            handle,
            uuid,
        }
    }

    fn guard_write(&self, value: &[u8]) -> Result<()> {
        self.inner
            .check_generation(&self.device_id, self.generation)?;
        if blocklist::writes_blocked(&self.uuid) {
            return Err(Error::Security(format!(
                "writing {} is blocklisted",
                self.uuid
            )));
        }
        if value.len() > MAX_ATTRIBUTE_LENGTH {
            return Err(Error::InvalidModification(format!(
                "value is {} bytes; a GATT attribute holds at most {MAX_ATTRIBUTE_LENGTH}",
                value.len()
            )));
        }
        Ok(())
    }
}

impl std::fmt::Debug for RemoteGattCharacteristic {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RemoteGattCharacteristic")
            .field("uuid", &self.uuid.as_str())
            .field("properties", &self.properties)
            .finish()
    }
}

/// `BluetoothRemoteGATTDescriptor`.
#[derive(Clone)]
pub struct RemoteGattDescriptor {
    inner: Arc<crate::session::Session>,
    device_id: String,
    characteristic_uuid: BluetoothUuid,
    /// Enough of the parent to rebuild it for [`Self::characteristic`].
    characteristic_handle: Handle,
    service_uuid: BluetoothUuid,
    service_handle: Handle,
    handle: Handle,
    uuid: BluetoothUuid,
    generation: u64,
}

impl RemoteGattDescriptor {
    /// The characteristic this descriptor belongs to —
    /// `BluetoothRemoteGATTDescriptor.characteristic`.
    pub fn characteristic(&self) -> RemoteGattCharacteristic {
        RemoteGattCharacteristic {
            properties: self
                .inner
                .characteristic_properties(&self.characteristic_handle),
            inner: self.inner.clone(),
            device_id: self.device_id.clone(),
            service_uuid: self.service_uuid,
            service_handle: self.service_handle.clone(),
            generation: self.generation,
            handle: self.characteristic_handle.clone(),
            uuid: self.characteristic_uuid,
        }
    }

    /// This descriptor's UUID — `BluetoothRemoteGATTDescriptor.uuid`.
    pub fn uuid(&self) -> &BluetoothUuid {
        &self.uuid
    }

    /// The UUID of the characteristic this descriptor belongs to.
    pub fn characteristic_uuid(&self) -> &BluetoothUuid {
        &self.characteristic_uuid
    }

    /// Read the descriptor's value.
    pub async fn read_value(&self) -> Result<Vec<u8>> {
        self.inner
            .check_generation(&self.device_id, self.generation)?;
        if blocklist::reads_blocked(&self.uuid) {
            return Err(Error::Security(format!(
                "reading {} is blocklisted",
                self.uuid
            )));
        }
        self.inner
            .read_descriptor(&self.device_id, &self.handle)
            .await
    }

    /// Read the descriptor's value beginning at `offset`.
    ///
    /// The complete value is read first because the platform descriptor APIs
    /// do not expose a portable ATT long-read offset parameter.
    pub async fn read_value_at_offset(&self, offset: usize) -> Result<Vec<u8>> {
        let value = self.read_value().await?;
        if offset > value.len() {
            return Err(Error::InvalidModification(format!(
                "descriptor offset {offset} exceeds its {}-byte value",
                value.len()
            )));
        }
        Ok(value[offset..].to_vec())
    }

    /// Write the descriptor's value.
    ///
    /// Note that the Client Characteristic Configuration descriptor is
    /// write-blocklisted: enabling notifications by writing it directly would
    /// bypass [`RemoteGattCharacteristic::start_notifications`], so use that
    /// instead.
    pub async fn write_value(&self, value: &[u8]) -> Result<()> {
        self.inner
            .check_generation(&self.device_id, self.generation)?;
        if blocklist::writes_blocked(&self.uuid) {
            return Err(Error::Security(format!(
                "writing {} is blocklisted — use start_notifications() to subscribe",
                self.uuid
            )));
        }
        if value.len() > MAX_ATTRIBUTE_LENGTH {
            return Err(Error::InvalidModification(format!(
                "value is {} bytes; a GATT attribute holds at most {MAX_ATTRIBUTE_LENGTH}",
                value.len()
            )));
        }
        self.inner
            .write_descriptor(&self.device_id, &self.handle, value)
            .await
    }

    /// Replace part of the descriptor value starting at `offset`.
    ///
    /// This uses a read-modify-write sequence so it works on platforms whose
    /// descriptor APIs only expose whole-value writes. The operation fails if
    /// the existing value cannot be read or the resulting value exceeds the
    /// ATT attribute limit.
    pub async fn write_value_at_offset(&self, offset: usize, value: &[u8]) -> Result<()> {
        let current = descriptor_patch(self.read_value().await?, offset, value)?;
        self.write_value(&current).await
    }
}

impl std::fmt::Debug for RemoteGattDescriptor {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RemoteGattDescriptor")
            .field("uuid", &self.uuid.as_str())
            .finish()
    }
}

/// A stream of characteristic values, from
/// [`RemoteGattCharacteristic::start_notifications`].
///
/// Ends when the device disconnects. The characteristic it belongs to is stale
/// from that moment and can never notify again, so a stream that stayed open
/// would be one that simply stopped: a `while let Some(..)` loop over it would
/// wait forever on a link that is already gone. Values that arrived before the
/// disconnect are still delivered first.
pub struct Notifications {
    rx: crate::backlog::Receiver<Vec<u8>>,
    /// Fires when the device this subscription belongs to disconnects.
    disconnects: futures_channel::mpsc::UnboundedReceiver<()>,
    /// Set once the stream has ended, so it stays ended.
    ended: bool,
    /// Where the values come from.
    ///
    /// The specification delivers these as events, and an event carries its
    /// `target` — so in JavaScript `event.target.uuid` is always at hand and
    /// a listener over several characteristics can tell them apart. A bare
    /// stream of `Vec<u8>` lost that, which is only invisible on a device with
    /// one interesting characteristic.
    characteristic: RemoteGattCharacteristic,
}

impl Notifications {
    /// The characteristic these values come from — the specification's
    /// `event.target`.
    pub fn characteristic(&self) -> &RemoteGattCharacteristic {
        &self.characteristic
    }

    /// That characteristic's UUID.
    ///
    /// The reason to reach for this is usually a merged stream: several
    /// subscriptions selected together deliver values that no longer say what
    /// they are, and — since [`lost`](Self::lost) is per subscription — a gap
    /// could not be attributed to a characteristic either.
    pub fn uuid(&self) -> &BluetoothUuid {
        self.characteristic.uuid()
    }

    /// Pair every value with the UUID it came from.
    ///
    /// For merging subscriptions: tag each one, then select over them, and the
    /// result is a single stream that still says which characteristic each
    /// value belongs to.
    ///
    /// ```no_run
    /// # use futures_util::{stream::select_all, StreamExt};
    /// # async fn example(
    /// #     eeg: webbluetooth::RemoteGattCharacteristic,
    /// #     ppg: webbluetooth::RemoteGattCharacteristic,
    /// # ) -> webbluetooth::Result<()> {
    /// let mut sensors = select_all([
    ///     eeg.start_notifications().await?.tagged().boxed(),
    ///     ppg.start_notifications().await?.tagged().boxed(),
    /// ]);
    ///
    /// while let Some((uuid, value)) = sensors.next().await {
    ///     println!("{uuid}: {} bytes", value.len());
    /// }
    /// # Ok(()) }
    /// ```
    pub fn tagged(self) -> Tagged {
        Tagged { inner: self }
    }

    /// How many notifications have been dropped because this stream was not
    /// being read fast enough.
    ///
    /// A peer can notify once per connection interval — every 7.5 ms at the
    /// fastest — and its callback thread cannot be made to wait, so a consumer
    /// that falls behind has to lose something. The queue keeps the newest and
    /// counts the rest here.
    ///
    /// Cumulative, so two readings can be compared: if this has moved between
    /// one value and the next, the difference is exactly the size of the gap
    /// between them. Anything reassembling a sequence — a firmware image, a
    /// log download — should check it rather than trust the bytes to be
    /// contiguous.
    ///
    /// ```no_run
    /// # async fn example(mut notifications: webbluetooth::Notifications) {
    /// use futures_util::StreamExt;
    /// let mut seen = notifications.lost();
    /// while let Some(value) = notifications.next().await {
    ///     if notifications.lost() != seen {
    ///         seen = notifications.lost();
    ///         // A gap: start the transfer again rather than stitch it.
    ///     }
    ///     let _ = value;
    /// }
    /// # }
    /// ```
    pub fn lost(&self) -> u64 {
        self.rx.lost()
    }

    /// How many notifications are queued and unread.
    ///
    /// Sitting near the queue's capacity means a consumer that is not keeping
    /// up — visible before [`lost`](Self::lost) starts moving.
    pub fn depth(&self) -> usize {
        self.rx.depth()
    }
}

/// [`Notifications`] with each value paired with the UUID it came from —
/// [`Notifications::tagged`].
///
/// A named type rather than `impl Stream` on purpose. Tagging exists so that
/// several subscriptions can be merged and still say what each value is, and
/// merging is what takes the stream by value: `select_all` owns what it is
/// given and hands back only what the item type carries. An opaque return type
/// would have taken [`lost`](Self::lost) with it, so the merged set could
/// report that notifications had been dropped but not which characteristic
/// dropped them — which is the position the bare `Vec<u8>` stream was in, one
/// step along.
///
/// `SelectAll::iter()` reaches these, so a merged set stays diagnosable.
pub struct Tagged {
    inner: Notifications,
}

impl Tagged {
    /// The characteristic these values come from.
    pub fn characteristic(&self) -> &RemoteGattCharacteristic {
        self.inner.characteristic()
    }

    /// That characteristic's UUID — the same one each item carries.
    pub fn uuid(&self) -> &BluetoothUuid {
        self.inner.uuid()
    }

    /// How many notifications this subscription has dropped.
    ///
    /// See [`Notifications::lost`]. Per subscription, which is why it is worth
    /// having beside the UUID.
    pub fn lost(&self) -> u64 {
        self.inner.lost()
    }

    /// How many are queued and unread on this subscription.
    pub fn depth(&self) -> usize {
        self.inner.depth()
    }
}

impl Stream for Tagged {
    type Item = (BluetoothUuid, Vec<u8>);

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        // Copied before the stream is borrowed mutably; a `BluetoothUuid` is
        // 36 bytes of ASCII and `Copy`, so this is not worth avoiding.
        let uuid = *self.inner.uuid();
        Pin::new(&mut self.inner)
            .poll_next(cx)
            .map(|value| value.map(|value| (uuid, value)))
    }
}

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

impl Stream for Notifications {
    type Item = Vec<u8>;
    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Vec<u8>>> {
        let this = &mut *self;
        poll_until_disconnect(&mut this.rx, &mut this.disconnects, &mut this.ended, cx)
    }
}

/// Yield from `values` until `disconnects` fires, then end for good.
///
/// Values are polled first, so everything queued before the link dropped is
/// delivered before the stream ends. No backend closes a subscription when
/// its device disconnects — the senders sit in a map keyed by characteristic,
/// which says nothing about which device they belong to — so this is where
/// the two are tied together, once, for all of them.
fn poll_until_disconnect<V, D>(
    values: &mut V,
    disconnects: &mut D,
    ended: &mut bool,
    cx: &mut Context<'_>,
) -> Poll<Option<Vec<u8>>>
where
    V: Stream<Item = Vec<u8>> + Unpin,
    D: Stream<Item = ()> + Unpin,
{
    if *ended {
        return Poll::Ready(None);
    }
    match Pin::new(values).poll_next(cx) {
        Poll::Ready(Some(value)) => return Poll::Ready(Some(value)),
        Poll::Ready(None) => {}
        Poll::Pending => {
            // `None` here means nothing is left to report a disconnect, which
            // is the session going away: just as final.
            if Pin::new(disconnects).poll_next(cx).is_pending() {
                return Poll::Pending;
            }
        }
    }
    *ended = true;
    Poll::Ready(None)
}

// The other handles in this file print their identity; these two were simply
// missed, which is visible the moment a caller puts one in a struct they want
// to `#[derive(Debug)]`.
impl std::fmt::Debug for RemoteGattServer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RemoteGattServer")
            .field("device", &self.id)
            .finish_non_exhaustive()
    }
}

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

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

    #[test]
    fn descriptor_suffix_validates_offsets() {
        assert_eq!(descriptor_suffix(&[1, 2, 3], 1).unwrap(), vec![2, 3]);
        assert_eq!(descriptor_suffix(&[1, 2, 3], 3).unwrap(), Vec::<u8>::new());
        assert!(descriptor_suffix(&[1, 2, 3], 4).is_err());
    }

    #[test]
    fn descriptor_patch_preserves_and_extends_values() {
        assert_eq!(
            descriptor_patch(vec![1, 2, 3], 1, &[9, 8]).unwrap(),
            vec![1, 9, 8]
        );
        assert_eq!(
            descriptor_patch(vec![1, 2], 2, &[3, 4]).unwrap(),
            vec![1, 2, 3, 4]
        );
        assert!(descriptor_patch(vec![1], 2, &[3]).is_err());
        assert!(descriptor_patch(vec![], 0, &vec![0; MAX_ATTRIBUTE_LENGTH + 1]).is_err());
    }

    /// Drive `poll_until_disconnect` the way `Notifications` does.
    struct Subscription {
        values: futures_channel::mpsc::UnboundedReceiver<Vec<u8>>,
        disconnects: futures_channel::mpsc::UnboundedReceiver<()>,
        ended: bool,
    }

    impl Stream for Subscription {
        type Item = Vec<u8>;
        fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Vec<u8>>> {
            let this = &mut *self;
            poll_until_disconnect(&mut this.values, &mut this.disconnects, &mut this.ended, cx)
        }
    }

    /// The bug this exists for: the link drops, the sender is still held by
    /// the backend, and a consumer awaiting the next value waits forever.
    #[test]
    fn notifications_end_when_the_device_disconnects() {
        use futures_util::StreamExt;

        let (values_tx, values) = futures_channel::mpsc::unbounded();
        let (disconnects_tx, disconnects) = futures_channel::mpsc::unbounded();
        let mut subscription = Subscription {
            values,
            disconnects,
            ended: false,
        };

        values_tx.unbounded_send(vec![1]).unwrap();
        values_tx.unbounded_send(vec![2]).unwrap();
        disconnects_tx.unbounded_send(()).unwrap();

        futures_executor::block_on(async {
            // What arrived before the drop is still delivered, in order.
            assert_eq!(subscription.next().await, Some(vec![1]));
            assert_eq!(subscription.next().await, Some(vec![2]));
            // The sender is alive, as it is in every backend; the stream ends
            // anyway.
            assert_eq!(subscription.next().await, None);

            // And stays ended, even if the stale characteristic says more.
            values_tx.unbounded_send(vec![3]).unwrap();
            assert_eq!(subscription.next().await, None);
        });
    }
}