webbluetooth-android 0.0.5

Android BLE from pure Rust — JNI spoken directly, callback classes generated at runtime
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
//! Calling the Android BLE APIs.
//!
//! Methods are resolved by name and signature at each call rather than cached.
//! BLE operates at human speed — a scan result every few hundred milliseconds,
//! a GATT read now and then — so the lookup costs nothing measurable, and it
//! removes a whole class of bug where a cached `jmethodID` outlives the class
//! it came from.

// As in `jni`: JNI references are raw pointers passed to the VM, not
// dereferenced here.
#![allow(clippy::not_unsafe_ptr_arg_deref)]

use crate::bluetooth::{Event, EventSink, Ref};
use crate::jni::{Env, JObject, JValue};
use crate::runtime::{Error, Runtime};
use std::sync::Arc;

type Result<T> = std::result::Result<T, Error>;

/// `BluetoothDevice.TRANSPORT_LE`.
const TRANSPORT_LE: i32 = 2;
/// `BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT` / `_NO_RESPONSE`.
pub const WRITE_TYPE_DEFAULT: i32 = 2;
pub const WRITE_TYPE_NO_RESPONSE: i32 = 1;
/// `BluetoothGatt.GATT_SUCCESS`.
pub const GATT_SUCCESS: i32 = 0;

// ── Call helpers ────────────────────────────────────────────────────────────

fn missing(what: &str) -> Error {
    Error::MissingMethod(what.into())
}

pub fn call_object(
    env: Env,
    object: JObject,
    name: &str,
    signature: &str,
    args: &[JValue],
) -> Result<JObject> {
    let method = env
        .method_id(env.get_object_class(object), name, signature)
        .ok_or_else(|| missing(name))?;
    Ok(env.call_object(object, method, args))
}

pub fn call_bool(
    env: Env,
    object: JObject,
    name: &str,
    signature: &str,
    args: &[JValue],
) -> Result<bool> {
    let method = env
        .method_id(env.get_object_class(object), name, signature)
        .ok_or_else(|| missing(name))?;
    Ok(env.call_bool(object, method, args))
}

pub fn call_int(
    env: Env,
    object: JObject,
    name: &str,
    signature: &str,
    args: &[JValue],
) -> Result<i32> {
    let method = env
        .method_id(env.get_object_class(object), name, signature)
        .ok_or_else(|| missing(name))?;
    Ok(env.call_int(object, method, args))
}

pub fn call_void(
    env: Env,
    object: JObject,
    name: &str,
    signature: &str,
    args: &[JValue],
) -> Result<()> {
    let method = env
        .method_id(env.get_object_class(object), name, signature)
        .ok_or_else(|| missing(name))?;
    env.call_void(object, method, args);
    Ok(())
}

/// `java.util.UUID.fromString`.
pub fn uuid(env: Env, canonical: &str) -> Result<JObject> {
    let class = env
        .find_class("java/util/UUID")
        .ok_or_else(|| Error::MissingClass("java.util.UUID".into()))?;
    let from_string = env
        .static_method_id(class, "fromString", "(Ljava/lang/String;)Ljava/util/UUID;")
        .ok_or_else(|| missing("UUID.fromString"))?;
    let s = env.new_string(canonical);
    Ok(env.call_static_object(class, from_string, &[JValue::object(s)]))
}

/// The canonical string of a `java.util.UUID`, lowercase as the spec wants.
pub fn uuid_string(env: Env, object: JObject) -> Option<String> {
    if object.is_null() {
        return None;
    }
    let s = call_object(env, object, "toString", "()Ljava/lang/String;", &[]).ok()?;
    env.get_string(s).map(|s| s.to_ascii_lowercase())
}

/// Wrap a `java.util.UUID` in a `ParcelUuid`, which the scan APIs take.
fn parcel_uuid(env: Env, canonical: &str) -> Result<JObject> {
    let class = env
        .find_class("android/os/ParcelUuid")
        .ok_or_else(|| Error::MissingClass("android.os.ParcelUuid".into()))?;
    let ctor = env
        .method_id(class, "<init>", "(Ljava/util/UUID;)V")
        .ok_or_else(|| missing("ParcelUuid.<init>"))?;
    let inner = uuid(env, canonical)?;
    Ok(env.new_object(class, ctor, &[JValue::object(inner)]))
}

/// Walk a `java.util.List`, applying `f` to each element.
pub fn for_each(env: Env, list: JObject, mut f: impl FnMut(JObject)) {
    if list.is_null() {
        return;
    }
    let Ok(size) = call_int(env, list, "size", "()I", &[]) else {
        return;
    };
    for i in 0..size {
        if let Ok(item) = call_object(env, list, "get", "(I)Ljava/lang/Object;", &[JValue::int(i)])
        {
            f(item);
        }
    }
}

// ── Adapter ─────────────────────────────────────────────────────────────────

/// The Bluetooth adapter and its scanner.
pub struct Adapter {
    adapter: Ref,
}

impl Adapter {
    /// `((BluetoothManager) context.getSystemService(BLUETOOTH_SERVICE)).getAdapter()`.
    pub fn open(runtime: &Runtime) -> Result<Self> {
        let env = runtime.env()?;

        let context_class = env
            .find_class("android/content/Context")
            .ok_or_else(|| Error::MissingClass("android.content.Context".into()))?;
        let field = env
            .static_field_id(context_class, "BLUETOOTH_SERVICE", "Ljava/lang/String;")
            .ok_or_else(|| missing("Context.BLUETOOTH_SERVICE"))?;
        let name = env.static_object_field(context_class, field);

        let manager = call_object(
            env,
            runtime.context(),
            "getSystemService",
            "(Ljava/lang/String;)Ljava/lang/Object;",
            &[JValue::object(name)],
        )?;
        if manager.is_null() {
            return Err(Error::MissingClass(
                "BluetoothManager (no Bluetooth on this device)".into(),
            ));
        }

        let adapter = call_object(
            env,
            manager,
            "getAdapter",
            "()Landroid/bluetooth/BluetoothAdapter;",
            &[],
        )?;
        let adapter = Ref::new(env, adapter)
            .ok_or_else(|| Error::MissingClass("BluetoothAdapter (none present)".into()))?;
        Ok(Self { adapter })
    }

    pub fn as_ptr(&self) -> JObject {
        self.adapter.as_ptr()
    }

    /// Whether the adapter is on.
    pub fn is_enabled(&self, env: Env) -> bool {
        call_bool(env, self.as_ptr(), "isEnabled", "()Z", &[]).unwrap_or(false)
    }

    /// `adapter.getName()` — what this device advertises itself as.
    pub fn name(&self, env: Env) -> Option<String> {
        let name = call_object(env, self.as_ptr(), "getName", "()Ljava/lang/String;", &[]).ok()?;
        env.get_string(name)
    }

    /// `adapter.getAddress()` — the controller's own address.
    ///
    /// Since Android 6 this returns a fixed `02:00:00:00:00:00` to any app
    /// without `LOCAL_MAC_ADDRESS_PERMISSION`, which is a system permission an
    /// ordinary app cannot hold. The caller is expected to recognise that and
    /// report nothing rather than a placeholder every device shares.
    pub fn address(&self, env: Env) -> Option<String> {
        let address = call_object(
            env,
            self.as_ptr(),
            "getAddress",
            "()Ljava/lang/String;",
            &[],
        )
        .ok()?;
        env.get_string(address)
    }

    /// `adapter.getBluetoothLeScanner()` — null while Bluetooth is off.
    pub fn scanner(&self, env: Env) -> Result<JObject> {
        call_object(
            env,
            self.as_ptr(),
            "getBluetoothLeScanner",
            "()Landroid/bluetooth/le/BluetoothLeScanner;",
            &[],
        )
    }

    /// `adapter.getRemoteDevice(address)`.
    pub fn remote_device(&self, env: Env, address: &str) -> Result<JObject> {
        let address = env.new_string(address);
        call_object(
            env,
            self.as_ptr(),
            "getRemoteDevice",
            "(Ljava/lang/String;)Landroid/bluetooth/BluetoothDevice;",
            &[JValue::object(address)],
        )
    }

    /// Return addresses of devices in `BluetoothAdapter.getBondedDevices()`.
    pub fn bonded_device_addresses(&self, env: Env) -> Result<Vec<String>> {
        let bonded = call_object(
            env,
            self.as_ptr(),
            "getBondedDevices",
            "()Ljava/util/Set;",
            &[],
        )?;
        let iterator = call_object(env, bonded, "iterator", "()Ljava/util/Iterator;", &[])?;
        let iterator_class = env.get_object_class(iterator);
        let has_next = env
            .method_id(iterator_class, "hasNext", "()Z")
            .ok_or_else(|| Error::MissingMethod("Iterator.hasNext".into()))?;
        let next = env
            .method_id(iterator_class, "next", "()Ljava/lang/Object;")
            .ok_or_else(|| Error::MissingMethod("Iterator.next".into()))?;
        let mut addresses = Vec::new();
        while env.call_bool(iterator, has_next, &[]) {
            let device = env.call_object(iterator, next, &[]);
            if let Some(address) = device_address(env, device) {
                addresses.push(address);
            }
        }
        Ok(addresses)
    }

    /// Read service UUIDs reported by `BluetoothDevice.getUuids()`.
    pub fn device_service_uuids(&self, env: Env, device: JObject) -> Result<Vec<String>> {
        let uuids = call_object(env, device, "getUuids", "()[Landroid/os/ParcelUuid;", &[])?;
        if uuids.is_null() {
            return Ok(Vec::new());
        }
        let mut result = Vec::new();
        let array = uuids as crate::jni::JArray;
        for index in 0..env.array_length(array) {
            let parcel = env.object_array_element(array, index);
            let uuid = call_object(env, parcel, "getUuid", "()Ljava/util/UUID;", &[])?;
            if let Some(value) = uuid_string(env, uuid) {
                result.push(value);
            }
        }
        Ok(result)
    }

    /// `adapter.getBluetoothLeAdvertiser()` — null where advertising is
    /// unsupported, which is common on older or cheaper hardware.
    pub fn advertiser(&self, env: Env) -> Result<JObject> {
        call_object(
            env,
            self.as_ptr(),
            "getBluetoothLeAdvertiser",
            "()Landroid/bluetooth/le/BluetoothLeAdvertiser;",
            &[],
        )
    }
}

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

/// Start a scan, filtering on service UUIDs where possible.
///
/// Android's filters run in the controller, so a filtered scan also survives
/// the background restrictions an unfiltered one does not.
pub fn start_scan(
    env: Env,
    scanner: JObject,
    callback: JObject,
    service_uuids: &[String],
) -> Result<()> {
    let filters = build_scan_filters(env, service_uuids)?;
    let settings = build_scan_settings(env)?;
    call_void(
        env,
        scanner,
        "startScan",
        "(Ljava/util/List;Landroid/bluetooth/le/ScanSettings;Landroid/bluetooth/le/ScanCallback;)V",
        &[
            JValue::object(filters),
            JValue::object(settings),
            JValue::object(callback),
        ],
    )
}

pub fn stop_scan(env: Env, scanner: JObject, callback: JObject) -> Result<()> {
    call_void(
        env,
        scanner,
        "stopScan",
        "(Landroid/bluetooth/le/ScanCallback;)V",
        &[JValue::object(callback)],
    )
}

fn build_scan_filters(env: Env, service_uuids: &[String]) -> Result<JObject> {
    let list_class = env
        .find_class("java/util/ArrayList")
        .ok_or_else(|| Error::MissingClass("java.util.ArrayList".into()))?;
    let ctor = env
        .method_id(list_class, "<init>", "()V")
        .ok_or_else(|| missing("ArrayList"))?;
    let list = env.new_object(list_class, ctor, &[]);

    let filter_builder_class = env
        .find_class("android/bluetooth/le/ScanFilter$Builder")
        .ok_or_else(|| Error::MissingClass("ScanFilter.Builder".into()))?;
    let builder_ctor = env
        .method_id(filter_builder_class, "<init>", "()V")
        .ok_or_else(|| missing("ScanFilter.Builder.<init>"))?;

    for canonical in service_uuids {
        let builder = env.new_object(filter_builder_class, builder_ctor, &[]);
        let parcel = parcel_uuid(env, canonical)?;
        call_object(
            env,
            builder,
            "setServiceUuid",
            "(Landroid/os/ParcelUuid;)Landroid/bluetooth/le/ScanFilter$Builder;",
            &[JValue::object(parcel)],
        )?;
        let filter = call_object(
            env,
            builder,
            "build",
            "()Landroid/bluetooth/le/ScanFilter;",
            &[],
        )?;
        call_bool(
            env,
            list,
            "add",
            "(Ljava/lang/Object;)Z",
            &[JValue::object(filter)],
        )?;
    }
    Ok(list)
}

fn build_scan_settings(env: Env) -> Result<JObject> {
    let class = env
        .find_class("android/bluetooth/le/ScanSettings$Builder")
        .ok_or_else(|| Error::MissingClass("ScanSettings.Builder".into()))?;
    let ctor = env
        .method_id(class, "<init>", "()V")
        .ok_or_else(|| missing("ScanSettings.Builder.<init>"))?;
    let builder = env.new_object(class, ctor, &[]);

    // SCAN_MODE_LOW_LATENCY = 2. A chooser is waiting on this, so latency
    // matters more than power for the seconds it runs.
    call_object(
        env,
        builder,
        "setScanMode",
        "(I)Landroid/bluetooth/le/ScanSettings$Builder;",
        &[JValue::int(2)],
    )?;
    call_object(
        env,
        builder,
        "build",
        "()Landroid/bluetooth/le/ScanSettings;",
        &[],
    )
}

// ── GATT client ─────────────────────────────────────────────────────────────

/// `device.connectGatt(context, false, callback, TRANSPORT_LE)`.
///
/// `autoConnect = false` connects now and fails if the peer is not there;
/// `true` waits indefinitely, which is not what `connect()` promises.
/// `device.createBond()` — start the pairing ceremony.
///
/// `false` means it did not start at all; `true` means it started, which is
/// not the same as finished. Android reports the outcome later, through a
/// broadcast.
/// `gatt.setPreferredPhy(txMask, rxMask, options)`.
///
/// Masks rather than values: a caller states which PHYs it will accept and the
/// controller picks. `options` is the coded-PHY preference and is ignored
/// unless coded is in the mask.
pub fn set_preferred_phy(env: Env, gatt: JObject, tx: i32, rx: i32, options: i32) -> Result<()> {
    call_void(
        env,
        gatt,
        "setPreferredPhy",
        "(III)V",
        &[JValue::int(tx), JValue::int(rx), JValue::int(options)],
    )
}

/// `gatt.readPhy()` — the answer arrives in `onPhyRead`.
pub fn read_phy(env: Env, gatt: JObject) -> Result<()> {
    call_void(env, gatt, "readPhy", "()V", &[])
}

pub fn create_bond(env: Env, device: JObject) -> Result<bool> {
    call_bool(env, device, "createBond", "()Z", &[])
}

/// `device.getBondState()` — `BOND_NONE`, `BOND_BONDING` or `BOND_BONDED`.
pub fn bond_state(env: Env, device: JObject) -> Result<i32> {
    call_int(env, device, "getBondState", "()I", &[])
}

pub fn connect_gatt(
    env: Env,
    runtime: &Runtime,
    device: JObject,
    callback: JObject,
) -> Result<JObject> {
    call_object(
        env,
        device,
        "connectGatt",
        "(Landroid/content/Context;ZLandroid/bluetooth/BluetoothGattCallback;I)Landroid/bluetooth/BluetoothGatt;",
        &[
            JValue::object(runtime.context()),
            JValue::bool(false),
            JValue::object(callback),
            JValue::int(TRANSPORT_LE),
        ],
    )
}

pub fn discover_services(env: Env, gatt: JObject) -> Result<bool> {
    call_bool(env, gatt, "discoverServices", "()Z", &[])
}

pub fn services(env: Env, gatt: JObject) -> Result<JObject> {
    call_object(env, gatt, "getServices", "()Ljava/util/List;", &[])
}

pub fn service_characteristics(env: Env, service: JObject) -> Result<JObject> {
    call_object(
        env,
        service,
        "getCharacteristics",
        "()Ljava/util/List;",
        &[],
    )
}

/// `BluetoothGattService.getIncludedServices()`.
///
/// Android populates this from the Include declarations it read during service
/// discovery, so no extra round trip is needed — unlike CoreBluetooth, which
/// has to be asked.
pub fn service_included_services(env: Env, service: JObject) -> Result<JObject> {
    call_object(
        env,
        service,
        "getIncludedServices",
        "()Ljava/util/List;",
        &[],
    )
}

pub fn characteristic_descriptors(env: Env, characteristic: JObject) -> Result<JObject> {
    call_object(
        env,
        characteristic,
        "getDescriptors",
        "()Ljava/util/List;",
        &[],
    )
}

pub fn attribute_uuid(env: Env, attribute: JObject) -> Option<String> {
    let uuid = call_object(env, attribute, "getUuid", "()Ljava/util/UUID;", &[]).ok()?;
    uuid_string(env, uuid)
}

pub fn characteristic_properties(env: Env, characteristic: JObject) -> i32 {
    call_int(env, characteristic, "getProperties", "()I", &[]).unwrap_or(0)
}

pub fn characteristic_value(env: Env, characteristic: JObject) -> Option<Vec<u8>> {
    let array = call_object(env, characteristic, "getValue", "()[B", &[]).ok()?;
    env.byte_array(array)
}

pub fn read_characteristic(env: Env, gatt: JObject, characteristic: JObject) -> Result<bool> {
    call_bool(
        env,
        gatt,
        "readCharacteristic",
        "(Landroid/bluetooth/BluetoothGattCharacteristic;)Z",
        &[JValue::object(characteristic)],
    )
}

/// Write a characteristic, using whichever API this device has.
///
/// API 33 replaced the set-then-write pair with a single call, and deprecated
/// the old one. Both are tried, newest first, because a library cannot pick at
/// build time what the device will offer at run time.
pub fn write_characteristic(
    env: Env,
    gatt: JObject,
    characteristic: JObject,
    value: &[u8],
    write_type: i32,
) -> Result<bool> {
    let bytes = env.new_byte_array(value);

    // API 33+: writeCharacteristic(characteristic, byte[], int) -> int status
    if let Some(method) = env.method_id(
        env.get_object_class(gatt),
        "writeCharacteristic",
        "(Landroid/bluetooth/BluetoothGattCharacteristic;[BI)I",
    ) {
        let status = env.call_int(
            gatt,
            method,
            &[
                JValue::object(characteristic),
                JValue::object(bytes),
                JValue::int(write_type),
            ],
        );
        return Ok(status == GATT_SUCCESS);
    }

    // Older: set the value on the characteristic, then write it.
    call_int(
        env,
        characteristic,
        "setWriteType",
        "(I)V",
        &[JValue::int(write_type)],
    )
    .ok();
    call_bool(
        env,
        characteristic,
        "setValue",
        "([B)Z",
        &[JValue::object(bytes)],
    )?;
    call_bool(
        env,
        gatt,
        "writeCharacteristic",
        "(Landroid/bluetooth/BluetoothGattCharacteristic;)Z",
        &[JValue::object(characteristic)],
    )
}

/// Subscribe.
///
/// Two steps, and missing the second is the most common Android BLE bug: local
/// delivery has to be enabled *and* the peer has to be told, by writing its
/// Client Characteristic Configuration descriptor.
pub fn set_notify(
    env: Env,
    gatt: JObject,
    characteristic: JObject,
    enable: bool,
    indicate: bool,
) -> Result<bool> {
    call_bool(
        env,
        gatt,
        "setCharacteristicNotification",
        "(Landroid/bluetooth/BluetoothGattCharacteristic;Z)Z",
        &[JValue::object(characteristic), JValue::bool(enable)],
    )?;

    let cccd = uuid(env, "00002902-0000-1000-8000-00805f9b34fb")?;
    let descriptor = call_object(
        env,
        characteristic,
        "getDescriptor",
        "(Ljava/util/UUID;)Landroid/bluetooth/BluetoothGattDescriptor;",
        &[JValue::object(cccd)],
    )?;
    if descriptor.is_null() {
        // No CCCD: local delivery is on, but the peer will send nothing.
        return Ok(false);
    }

    let value: &[u8] = match (enable, indicate) {
        (false, _) => &[0x00, 0x00],
        (true, false) => &[0x01, 0x00],
        (true, true) => &[0x02, 0x00],
    };
    write_descriptor(env, gatt, descriptor, value)
}

pub fn read_descriptor(env: Env, gatt: JObject, descriptor: JObject) -> Result<bool> {
    call_bool(
        env,
        gatt,
        "readDescriptor",
        "(Landroid/bluetooth/BluetoothGattDescriptor;)Z",
        &[JValue::object(descriptor)],
    )
}

pub fn write_descriptor(
    env: Env,
    gatt: JObject,
    descriptor: JObject,
    value: &[u8],
) -> Result<bool> {
    let bytes = env.new_byte_array(value);

    // API 33+ takes the value directly.
    if let Some(method) = env.method_id(
        env.get_object_class(gatt),
        "writeDescriptor",
        "(Landroid/bluetooth/BluetoothGattDescriptor;[B)I",
    ) {
        let status = env.call_int(
            gatt,
            method,
            &[JValue::object(descriptor), JValue::object(bytes)],
        );
        return Ok(status == GATT_SUCCESS);
    }

    call_bool(
        env,
        descriptor,
        "setValue",
        "([B)Z",
        &[JValue::object(bytes)],
    )?;
    call_bool(
        env,
        gatt,
        "writeDescriptor",
        "(Landroid/bluetooth/BluetoothGattDescriptor;)Z",
        &[JValue::object(descriptor)],
    )
}

pub fn request_mtu(env: Env, gatt: JObject, mtu: i32) -> Result<bool> {
    call_bool(env, gatt, "requestMtu", "(I)Z", &[JValue::int(mtu)])
}

pub fn read_remote_rssi(env: Env, gatt: JObject) -> Result<bool> {
    call_bool(env, gatt, "readRemoteRssi", "()Z", &[])
}

/// `BluetoothGatt.requestConnectionPriority(int)`.
///
/// A hint: Android asks the controller to re-negotiate the connection
/// interval, and the peripheral has the final say. `false` means the request
/// was not even sent — usually because the argument was out of range or the
/// link is gone.
pub fn request_connection_priority(env: Env, gatt: JObject, priority: i32) -> Result<bool> {
    call_bool(
        env,
        gatt,
        "requestConnectionPriority",
        "(I)Z",
        &[JValue::int(priority)],
    )
}

pub fn disconnect(env: Env, gatt: JObject) -> Result<()> {
    call_void(env, gatt, "disconnect", "()V", &[])
}

/// Release the connection's resources.
///
/// Android allows a small number of concurrent GATT clients — historically 32,
/// far fewer in practice — and leaking them is how an app stops being able to
/// connect at all until it is restarted.
pub fn close(env: Env, gatt: JObject) -> Result<()> {
    call_void(env, gatt, "close", "()V", &[])
}

// ── L2CAP ───────────────────────────────────────────────────────────────────

/// `device.createL2capChannel(psm)` — API 29+.
pub fn create_l2cap_channel(env: Env, device: JObject, psm: i32) -> Result<JObject> {
    call_object(
        env,
        device,
        "createL2capChannel",
        "(I)Landroid/bluetooth/BluetoothSocket;",
        &[JValue::int(psm)],
    )
}

/// `device.createL2capSocket(psm)` for a Bluetooth Classic L2CAP socket.
#[cfg(feature = "classic-l2cap")]
pub fn create_classic_l2cap_socket(env: Env, device: JObject, psm: i32) -> Result<JObject> {
    call_object(
        env,
        device,
        "createL2capSocket",
        "(I)Landroid/bluetooth/BluetoothSocket;",
        &[JValue::int(psm)],
    )
}

/// `device.createRfcommSocketToServiceRecord(uuid)`.
#[cfg(feature = "rfcomm")]
pub fn create_rfcomm_socket(env: Env, device: JObject, service_uuid: &str) -> Result<JObject> {
    let service_uuid = uuid(env, service_uuid)?;
    call_object(
        env,
        device,
        "createRfcommSocketToServiceRecord",
        "(Ljava/util/UUID;)Landroid/bluetooth/BluetoothSocket;",
        &[JValue::object(service_uuid)],
    )
}

pub fn socket_connect(env: Env, socket: JObject) -> Result<()> {
    call_void(env, socket, "connect", "()V", &[])
}

pub fn socket_close(env: Env, socket: JObject) -> Result<()> {
    call_void(env, socket, "close", "()V", &[])
}

pub fn socket_input_stream(env: Env, socket: JObject) -> Result<JObject> {
    call_object(
        env,
        socket,
        "getInputStream",
        "()Ljava/io/InputStream;",
        &[],
    )
}

pub fn socket_output_stream(env: Env, socket: JObject) -> Result<JObject> {
    call_object(
        env,
        socket,
        "getOutputStream",
        "()Ljava/io/OutputStream;",
        &[],
    )
}

/// Read once from a `java.io.InputStream`. `Ok(None)` at end of stream.
pub fn stream_read(env: Env, stream: JObject, buffer: usize) -> Result<Option<Vec<u8>>> {
    let array = env.new_byte_array(&vec![0u8; buffer]);
    let n = call_int(env, stream, "read", "([B)I", &[JValue::object(array)])?;
    if n < 0 {
        return Ok(None);
    }
    let mut bytes = env.byte_array(array).unwrap_or_default();
    bytes.truncate(n as usize);
    Ok(Some(bytes))
}

pub fn stream_write(env: Env, stream: JObject, data: &[u8]) -> Result<()> {
    let array = env.new_byte_array(data);
    call_void(env, stream, "write", "([B)V", &[JValue::object(array)])?;
    call_void(env, stream, "flush", "()V", &[])
}

// ── Callback objects ────────────────────────────────────────────────────────

/// A generated callback class, instantiated and bound to a sink.
pub struct Callback {
    object: Ref,
}

impl Callback {
    /// Define the class if needed, make one, and route its events to `sink`.
    pub fn new(
        runtime: &Runtime,
        binary_name: &str,
        dex: Vec<u8>,
        natives: &[(&str, &str, *const std::ffi::c_void)],
        sink: Arc<dyn EventSink>,
    ) -> Result<Self> {
        let class = runtime.define_class(binary_name, dex, natives)?;
        let object = runtime.new_instance(class)?;
        let env = runtime.env()?;
        let object = Ref::new(env, object)
            .ok_or_else(|| Error::ClassLoad(format!("{binary_name} produced a null instance")))?;
        crate::bluetooth::bind_sink(&object, sink);
        Ok(Self { object })
    }

    pub fn as_ptr(&self) -> JObject {
        self.object.as_ptr()
    }
}

impl Drop for Callback {
    fn drop(&mut self) {
        crate::bluetooth::unbind_sink(&self.object);
    }
}

/// Discard events — useful where a callback is required but nothing listens.
pub struct Discard;

impl EventSink for Discard {
    fn emit(&self, _: Event) {}
}

// ── Peripheral role ─────────────────────────────────────────────────────────

/// `BluetoothGattService.SERVICE_TYPE_PRIMARY` / `_SECONDARY`.
const SERVICE_TYPE_PRIMARY: i32 = 0;
const SERVICE_TYPE_SECONDARY: i32 = 1;

/// `BluetoothGattServer.GATT_SUCCESS` and the ATT codes it forwards.
pub const ATT_SUCCESS: i32 = 0;

/// Map the shared permission bits onto Android's.
///
/// Android's constants are not the Bluetooth ones: read is `1` but write is
/// `16`, with the encrypted variants interleaved between them.
pub fn permissions_to_android(permissions: u32) -> i32 {
    const READABLE: u32 = 0x01;
    const WRITEABLE: u32 = 0x02;
    const READ_ENCRYPTED: u32 = 0x04;
    const WRITE_ENCRYPTED: u32 = 0x08;

    let mut out = 0;
    if permissions & READABLE != 0 {
        out |= 1; // PERMISSION_READ
    }
    if permissions & READ_ENCRYPTED != 0 {
        out |= 2; // PERMISSION_READ_ENCRYPTED
    }
    if permissions & WRITEABLE != 0 {
        out |= 16; // PERMISSION_WRITE
    }
    if permissions & WRITE_ENCRYPTED != 0 {
        out |= 32; // PERMISSION_WRITE_ENCRYPTED
    }
    out
}

/// `manager.openGattServer(context, callback)`.
pub fn open_gatt_server(env: Env, runtime: &Runtime, callback: JObject) -> Result<JObject> {
    let context_class = env
        .find_class("android/content/Context")
        .ok_or_else(|| Error::MissingClass("android.content.Context".into()))?;
    let field = env
        .static_field_id(context_class, "BLUETOOTH_SERVICE", "Ljava/lang/String;")
        .ok_or_else(|| missing("Context.BLUETOOTH_SERVICE"))?;
    let name = env.static_object_field(context_class, field);
    let manager = call_object(
        env,
        runtime.context(),
        "getSystemService",
        "(Ljava/lang/String;)Ljava/lang/Object;",
        &[JValue::object(name)],
    )?;
    call_object(
        env,
        manager,
        "openGattServer",
        "(Landroid/content/Context;Landroid/bluetooth/BluetoothGattServerCallback;)Landroid/bluetooth/BluetoothGattServer;",
        &[JValue::object(runtime.context()), JValue::object(callback)],
    )
}

/// `new BluetoothGattService(uuid, primary ? PRIMARY : SECONDARY)`.
pub fn new_service(env: Env, canonical: &str, primary: bool) -> Result<JObject> {
    let class = env
        .find_class("android/bluetooth/BluetoothGattService")
        .ok_or_else(|| Error::MissingClass("BluetoothGattService".into()))?;
    let ctor = env
        .method_id(class, "<init>", "(Ljava/util/UUID;I)V")
        .ok_or_else(|| missing("BluetoothGattService.<init>"))?;
    let uuid = uuid(env, canonical)?;
    let kind = if primary {
        SERVICE_TYPE_PRIMARY
    } else {
        SERVICE_TYPE_SECONDARY
    };
    Ok(env.new_object(class, ctor, &[JValue::object(uuid), JValue::int(kind)]))
}

/// `new BluetoothGattCharacteristic(uuid, properties, permissions)`.
pub fn new_characteristic(
    env: Env,
    canonical: &str,
    properties: u32,
    permissions: u32,
) -> Result<JObject> {
    let class = env
        .find_class("android/bluetooth/BluetoothGattCharacteristic")
        .ok_or_else(|| Error::MissingClass("BluetoothGattCharacteristic".into()))?;
    let ctor = env
        .method_id(class, "<init>", "(Ljava/util/UUID;II)V")
        .ok_or_else(|| missing("BluetoothGattCharacteristic.<init>"))?;
    let uuid = uuid(env, canonical)?;
    Ok(env.new_object(
        class,
        ctor,
        &[
            JValue::object(uuid),
            // Android's PROPERTY_* are the Bluetooth bits, unlike its
            // permissions.
            JValue::int(properties as i32),
            JValue::int(permissions_to_android(permissions)),
        ],
    ))
}

/// `new BluetoothGattDescriptor(uuid, permissions)`.
pub fn new_descriptor(env: Env, canonical: &str, permissions: u32) -> Result<JObject> {
    let class = env
        .find_class("android/bluetooth/BluetoothGattDescriptor")
        .ok_or_else(|| Error::MissingClass("BluetoothGattDescriptor".into()))?;
    let ctor = env
        .method_id(class, "<init>", "(Ljava/util/UUID;I)V")
        .ok_or_else(|| missing("BluetoothGattDescriptor.<init>"))?;
    let uuid = uuid(env, canonical)?;
    Ok(env.new_object(
        class,
        ctor,
        &[
            JValue::object(uuid),
            JValue::int(permissions_to_android(permissions)),
        ],
    ))
}

pub fn service_add_characteristic(
    env: Env,
    service: JObject,
    characteristic: JObject,
) -> Result<bool> {
    call_bool(
        env,
        service,
        "addCharacteristic",
        "(Landroid/bluetooth/BluetoothGattCharacteristic;)Z",
        &[JValue::object(characteristic)],
    )
}

pub fn characteristic_add_descriptor(
    env: Env,
    characteristic: JObject,
    descriptor: JObject,
) -> Result<bool> {
    call_bool(
        env,
        characteristic,
        "addDescriptor",
        "(Landroid/bluetooth/BluetoothGattDescriptor;)Z",
        &[JValue::object(descriptor)],
    )
}

pub fn set_value(env: Env, attribute: JObject, value: &[u8]) -> Result<bool> {
    let bytes = env.new_byte_array(value);
    call_bool(
        env,
        attribute,
        "setValue",
        "([B)Z",
        &[JValue::object(bytes)],
    )
}

pub fn server_add_service(env: Env, server: JObject, service: JObject) -> Result<bool> {
    call_bool(
        env,
        server,
        "addService",
        "(Landroid/bluetooth/BluetoothGattService;)Z",
        &[JValue::object(service)],
    )
}

pub fn server_remove_service(env: Env, server: JObject, service: JObject) -> Result<bool> {
    call_bool(
        env,
        server,
        "removeService",
        "(Landroid/bluetooth/BluetoothGattService;)Z",
        &[JValue::object(service)],
    )
}

pub fn server_clear_services(env: Env, server: JObject) -> Result<()> {
    call_void(env, server, "clearServices", "()V", &[])
}

pub fn server_close(env: Env, server: JObject) -> Result<()> {
    call_void(env, server, "close", "()V", &[])
}

/// `server.sendResponse(device, requestId, status, offset, value)`.
///
/// Every request that asked for a response must get exactly one, or the central
/// stalls until the ATT timeout.
pub fn server_send_response(
    env: Env,
    server: JObject,
    device: JObject,
    request_id: i32,
    status: i32,
    offset: i32,
    value: &[u8],
) -> Result<bool> {
    let bytes = env.new_byte_array(value);
    call_bool(
        env,
        server,
        "sendResponse",
        "(Landroid/bluetooth/BluetoothDevice;III[B)Z",
        &[
            JValue::object(device),
            JValue::int(request_id),
            JValue::int(status),
            JValue::int(offset),
            JValue::object(bytes),
        ],
    )
}

/// Push a value to one subscriber.
///
/// API 33 takes the bytes directly and returns a status; older releases want
/// the value set on the characteristic first. Both are tried, newest first.
pub fn server_notify(
    env: Env,
    server: JObject,
    device: JObject,
    characteristic: JObject,
    confirm: bool,
    value: &[u8],
) -> Result<bool> {
    let bytes = env.new_byte_array(value);

    if let Some(method) = env.method_id(
        env.get_object_class(server),
        "notifyCharacteristicChanged",
        "(Landroid/bluetooth/BluetoothDevice;Landroid/bluetooth/BluetoothGattCharacteristic;Z[B)I",
    ) {
        let status = env.call_int(
            server,
            method,
            &[
                JValue::object(device),
                JValue::object(characteristic),
                JValue::bool(confirm),
                JValue::object(bytes),
            ],
        );
        return Ok(status == ATT_SUCCESS);
    }

    set_value(env, characteristic, value)?;
    call_bool(
        env,
        server,
        "notifyCharacteristicChanged",
        "(Landroid/bluetooth/BluetoothDevice;Landroid/bluetooth/BluetoothGattCharacteristic;Z)Z",
        &[
            JValue::object(device),
            JValue::object(characteristic),
            JValue::bool(confirm),
        ],
    )
}

/// The centrals connected to the GATT server.
pub fn server_connected_devices(env: Env, runtime: &Runtime) -> Result<JObject> {
    let context_class = env
        .find_class("android/content/Context")
        .ok_or_else(|| Error::MissingClass("android.content.Context".into()))?;
    let field = env
        .static_field_id(context_class, "BLUETOOTH_SERVICE", "Ljava/lang/String;")
        .ok_or_else(|| missing("Context.BLUETOOTH_SERVICE"))?;
    let name = env.static_object_field(context_class, field);
    let manager = call_object(
        env,
        runtime.context(),
        "getSystemService",
        "(Ljava/lang/String;)Ljava/lang/Object;",
        &[JValue::object(name)],
    )?;
    // BluetoothProfile.GATT_SERVER == 8
    call_object(
        env,
        manager,
        "getConnectedDevices",
        "(I)Ljava/util/List;",
        &[JValue::int(8)],
    )
}

pub fn device_address(env: Env, device: JObject) -> Option<String> {
    let s = call_object(env, device, "getAddress", "()Ljava/lang/String;", &[]).ok()?;
    env.get_string(s)
}

#[cfg(feature = "classic")]
pub fn start_classic_discovery(env: Env, adapter: JObject) -> Result<()> {
    if call_bool(env, adapter, "startDiscovery", "()Z", &[])? {
        Ok(())
    } else {
        Err(Error::MissingMethod(
            "BluetoothAdapter.startDiscovery returned false".into(),
        ))
    }
}

#[cfg(feature = "classic")]
pub fn cancel_classic_discovery(env: Env, adapter: JObject) -> Result<()> {
    call_bool(env, adapter, "cancelDiscovery", "()Z", &[]).map(|_| ())
}

#[cfg(feature = "classic")]
pub fn classic_discovery_filter(env: Env) -> Result<JObject> {
    let class = env
        .find_class("android/content/IntentFilter")
        .ok_or_else(|| Error::MissingClass("android.content.IntentFilter".into()))?;
    let ctor = env
        .method_id(class, "<init>", "()V")
        .ok_or_else(|| missing("IntentFilter.<init>"))?;
    let filter = env.new_object(class, ctor, &[]);
    for action in [
        "android.bluetooth.device.action.FOUND",
        "android.bluetooth.adapter.action.DISCOVERY_STARTED",
        "android.bluetooth.adapter.action.DISCOVERY_FINISHED",
    ] {
        let action = env.new_string(action);
        call_void(
            env,
            filter,
            "addAction",
            "(Ljava/lang/String;)V",
            &[JValue::object(action)],
        )?;
    }
    Ok(filter)
}

#[cfg(feature = "classic")]
pub fn register_classic_receiver(env: Env, receiver: JObject, filter: JObject) -> Result<()> {
    call_object(
        env,
        Runtime::get().ok_or(Error::NoContext)?.context(),
        "registerReceiver",
        "(Landroid/content/BroadcastReceiver;Landroid/content/IntentFilter;)Landroid/content/Intent;",
        &[JValue::object(receiver), JValue::object(filter)],
    )
    .map(|_| ())
}

#[cfg(feature = "classic")]
pub fn unregister_classic_receiver(env: Env, receiver: JObject) -> Result<()> {
    call_void(
        env,
        Runtime::get().ok_or(Error::NoContext)?.context(),
        "unregisterReceiver",
        "(Landroid/content/BroadcastReceiver;)V",
        &[JValue::object(receiver)],
    )
}

// ── Advertising ─────────────────────────────────────────────────────────────

/// Start advertising.
///
/// Android will not put an arbitrary name in the payload: `AdvertiseData` only
/// offers `setIncludeDeviceName`, which uses the *adapter's* name. Changing
/// that means `BluetoothAdapter.setName`, which is global to the device — so
/// [`Advertising::local_name`] is honoured by including the device name, not by
/// overriding it.
///
/// [`Advertising::local_name`]: crate::ble
pub fn start_advertising(
    env: Env,
    advertiser: JObject,
    callback: JObject,
    include_name: bool,
    service_uuids: &[String],
    connectable: bool,
    mode: i32,
) -> Result<()> {
    let settings = build_advertise_settings(env, connectable, mode)?;
    let data = build_advertise_data(env, include_name, service_uuids)?;
    call_void(
        env,
        advertiser,
        "startAdvertising",
        concat!(
            "(Landroid/bluetooth/le/AdvertiseSettings;",
            "Landroid/bluetooth/le/AdvertiseData;",
            "Landroid/bluetooth/le/AdvertiseCallback;)V"
        ),
        &[
            JValue::object(settings),
            JValue::object(data),
            JValue::object(callback),
        ],
    )
}

pub fn stop_advertising(env: Env, advertiser: JObject, callback: JObject) -> Result<()> {
    call_void(
        env,
        advertiser,
        "stopAdvertising",
        "(Landroid/bluetooth/le/AdvertiseCallback;)V",
        &[JValue::object(callback)],
    )
}

/// `AdvertiseSettings` mode for a preferred maximum interval: low latency
/// (~100 ms), balanced (~250 ms) or low power (~1 s).
pub fn advertise_mode(max_interval: Option<std::time::Duration>) -> i32 {
    match max_interval.map(|d| d.as_millis()) {
        None => 2,
        Some(ms) if ms <= 175 => 2,
        Some(ms) if ms <= 500 => 1,
        Some(_) => 0,
    }
}

fn build_advertise_settings(env: Env, connectable: bool, mode: i32) -> Result<JObject> {
    let class = env
        .find_class("android/bluetooth/le/AdvertiseSettings$Builder")
        .ok_or_else(|| Error::MissingClass("AdvertiseSettings.Builder".into()))?;
    let ctor = env
        .method_id(class, "<init>", "()V")
        .ok_or_else(|| missing("AdvertiseSettings.Builder.<init>"))?;
    let builder = env.new_object(class, ctor, &[]);

    // ADVERTISE_MODE_LOW_LATENCY = 2 by default: a peripheral is meant to be
    // found. See `advertise_mode`.
    call_object(
        env,
        builder,
        "setAdvertiseMode",
        "(I)Landroid/bluetooth/le/AdvertiseSettings$Builder;",
        &[JValue::int(mode)],
    )?;
    call_object(
        env,
        builder,
        "setConnectable",
        "(Z)Landroid/bluetooth/le/AdvertiseSettings$Builder;",
        &[JValue::bool(connectable)],
    )?;
    call_object(
        env,
        builder,
        "build",
        "()Landroid/bluetooth/le/AdvertiseSettings;",
        &[],
    )
}

fn build_advertise_data(env: Env, include_name: bool, service_uuids: &[String]) -> Result<JObject> {
    let class = env
        .find_class("android/bluetooth/le/AdvertiseData$Builder")
        .ok_or_else(|| Error::MissingClass("AdvertiseData.Builder".into()))?;
    let ctor = env
        .method_id(class, "<init>", "()V")
        .ok_or_else(|| missing("AdvertiseData.Builder.<init>"))?;
    let builder = env.new_object(class, ctor, &[]);

    call_object(
        env,
        builder,
        "setIncludeDeviceName",
        "(Z)Landroid/bluetooth/le/AdvertiseData$Builder;",
        &[JValue::bool(include_name)],
    )?;
    for canonical in service_uuids {
        let parcel = parcel_uuid(env, canonical)?;
        call_object(
            env,
            builder,
            "addServiceUuid",
            "(Landroid/os/ParcelUuid;)Landroid/bluetooth/le/AdvertiseData$Builder;",
            &[JValue::object(parcel)],
        )?;
    }
    call_object(
        env,
        builder,
        "build",
        "()Landroid/bluetooth/le/AdvertiseData;",
        &[],
    )
}

// ── L2CAP, listening side ───────────────────────────────────────────────────

/// `adapter.listenUsingRfcommWithServiceRecord(name, uuid)`.
pub fn listen_rfcomm(
    env: Env,
    adapter: JObject,
    name: &str,
    service_uuid: &str,
) -> Result<JObject> {
    let service_uuid = uuid(env, service_uuid)?;
    let name = env.new_string(name);
    call_object(
        env,
        adapter,
        "listenUsingRfcommWithServiceRecord",
        "(Ljava/lang/String;Ljava/util/UUID;)Landroid/bluetooth/BluetoothServerSocket;",
        &[JValue::object(name), JValue::object(service_uuid)],
    )
}

/// `adapter.listenUsingInsecureL2capChannel()` — API 29+.
///
/// Returns a `BluetoothServerSocket`; its PSM is assigned by the system and
/// read back with `getPsm()`.
pub fn listen_l2cap(env: Env, adapter: JObject, secure: bool) -> Result<JObject> {
    let name = if secure {
        "listenUsingL2capChannel"
    } else {
        "listenUsingInsecureL2capChannel"
    };
    call_object(
        env,
        adapter,
        name,
        "()Landroid/bluetooth/BluetoothServerSocket;",
        &[],
    )
}

pub fn server_socket_psm(env: Env, socket: JObject) -> Result<i32> {
    call_int(env, socket, "getPsm", "()I", &[])
}

/// Block until a central connects, then return the accepted socket.
pub fn server_socket_accept(env: Env, socket: JObject) -> Result<JObject> {
    call_object(
        env,
        socket,
        "accept",
        "()Landroid/bluetooth/BluetoothSocket;",
        &[],
    )
}

pub fn server_socket_close(env: Env, socket: JObject) -> Result<()> {
    call_void(env, socket, "close", "()V", &[])
}