Skip to main content

webbluetooth_android/
ble.rs

1//! Calling the Android BLE APIs.
2//!
3//! Methods are resolved by name and signature at each call rather than cached.
4//! BLE operates at human speed — a scan result every few hundred milliseconds,
5//! a GATT read now and then — so the lookup costs nothing measurable, and it
6//! removes a whole class of bug where a cached `jmethodID` outlives the class
7//! it came from.
8
9// As in `jni`: JNI references are raw pointers passed to the VM, not
10// dereferenced here.
11#![allow(clippy::not_unsafe_ptr_arg_deref)]
12
13use crate::bluetooth::{Event, EventSink, Ref};
14use crate::jni::{Env, JObject, JValue};
15use crate::runtime::{Error, Runtime};
16use std::sync::Arc;
17
18type Result<T> = std::result::Result<T, Error>;
19
20/// `BluetoothDevice.TRANSPORT_LE`.
21const TRANSPORT_LE: i32 = 2;
22/// `BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT` / `_NO_RESPONSE`.
23pub const WRITE_TYPE_DEFAULT: i32 = 2;
24pub const WRITE_TYPE_NO_RESPONSE: i32 = 1;
25/// `BluetoothGatt.GATT_SUCCESS`.
26pub const GATT_SUCCESS: i32 = 0;
27
28// ── Call helpers ────────────────────────────────────────────────────────────
29
30fn missing(what: &str) -> Error {
31    Error::MissingMethod(what.into())
32}
33
34pub fn call_object(
35    env: Env,
36    object: JObject,
37    name: &str,
38    signature: &str,
39    args: &[JValue],
40) -> Result<JObject> {
41    let method = env
42        .method_id(env.get_object_class(object), name, signature)
43        .ok_or_else(|| missing(name))?;
44    Ok(env.call_object(object, method, args))
45}
46
47pub fn call_bool(
48    env: Env,
49    object: JObject,
50    name: &str,
51    signature: &str,
52    args: &[JValue],
53) -> Result<bool> {
54    let method = env
55        .method_id(env.get_object_class(object), name, signature)
56        .ok_or_else(|| missing(name))?;
57    Ok(env.call_bool(object, method, args))
58}
59
60pub fn call_int(
61    env: Env,
62    object: JObject,
63    name: &str,
64    signature: &str,
65    args: &[JValue],
66) -> Result<i32> {
67    let method = env
68        .method_id(env.get_object_class(object), name, signature)
69        .ok_or_else(|| missing(name))?;
70    Ok(env.call_int(object, method, args))
71}
72
73pub fn call_void(
74    env: Env,
75    object: JObject,
76    name: &str,
77    signature: &str,
78    args: &[JValue],
79) -> Result<()> {
80    let method = env
81        .method_id(env.get_object_class(object), name, signature)
82        .ok_or_else(|| missing(name))?;
83    env.call_void(object, method, args);
84    Ok(())
85}
86
87/// `java.util.UUID.fromString`.
88pub fn uuid(env: Env, canonical: &str) -> Result<JObject> {
89    let class = env
90        .find_class("java/util/UUID")
91        .ok_or_else(|| Error::MissingClass("java.util.UUID".into()))?;
92    let from_string = env
93        .static_method_id(class, "fromString", "(Ljava/lang/String;)Ljava/util/UUID;")
94        .ok_or_else(|| missing("UUID.fromString"))?;
95    let s = env.new_string(canonical);
96    Ok(env.call_static_object(class, from_string, &[JValue::object(s)]))
97}
98
99/// The canonical string of a `java.util.UUID`, lowercase as the spec wants.
100pub fn uuid_string(env: Env, object: JObject) -> Option<String> {
101    if object.is_null() {
102        return None;
103    }
104    let s = call_object(env, object, "toString", "()Ljava/lang/String;", &[]).ok()?;
105    env.get_string(s).map(|s| s.to_ascii_lowercase())
106}
107
108/// Wrap a `java.util.UUID` in a `ParcelUuid`, which the scan APIs take.
109fn parcel_uuid(env: Env, canonical: &str) -> Result<JObject> {
110    let class = env
111        .find_class("android/os/ParcelUuid")
112        .ok_or_else(|| Error::MissingClass("android.os.ParcelUuid".into()))?;
113    let ctor = env
114        .method_id(class, "<init>", "(Ljava/util/UUID;)V")
115        .ok_or_else(|| missing("ParcelUuid.<init>"))?;
116    let inner = uuid(env, canonical)?;
117    Ok(env.new_object(class, ctor, &[JValue::object(inner)]))
118}
119
120/// Walk a `java.util.List`, applying `f` to each element.
121pub fn for_each(env: Env, list: JObject, mut f: impl FnMut(JObject)) {
122    if list.is_null() {
123        return;
124    }
125    let Ok(size) = call_int(env, list, "size", "()I", &[]) else {
126        return;
127    };
128    for i in 0..size {
129        if let Ok(item) = call_object(env, list, "get", "(I)Ljava/lang/Object;", &[JValue::int(i)])
130        {
131            f(item);
132        }
133    }
134}
135
136// ── Adapter ─────────────────────────────────────────────────────────────────
137
138/// The Bluetooth adapter and its scanner.
139pub struct Adapter {
140    adapter: Ref,
141}
142
143impl Adapter {
144    /// `((BluetoothManager) context.getSystemService(BLUETOOTH_SERVICE)).getAdapter()`.
145    pub fn open(runtime: &Runtime) -> Result<Self> {
146        let env = runtime.env()?;
147
148        let context_class = env
149            .find_class("android/content/Context")
150            .ok_or_else(|| Error::MissingClass("android.content.Context".into()))?;
151        let field = env
152            .static_field_id(context_class, "BLUETOOTH_SERVICE", "Ljava/lang/String;")
153            .ok_or_else(|| missing("Context.BLUETOOTH_SERVICE"))?;
154        let name = env.static_object_field(context_class, field);
155
156        let manager = call_object(
157            env,
158            runtime.context(),
159            "getSystemService",
160            "(Ljava/lang/String;)Ljava/lang/Object;",
161            &[JValue::object(name)],
162        )?;
163        if manager.is_null() {
164            return Err(Error::MissingClass(
165                "BluetoothManager (no Bluetooth on this device)".into(),
166            ));
167        }
168
169        let adapter = call_object(
170            env,
171            manager,
172            "getAdapter",
173            "()Landroid/bluetooth/BluetoothAdapter;",
174            &[],
175        )?;
176        let adapter = Ref::new(env, adapter)
177            .ok_or_else(|| Error::MissingClass("BluetoothAdapter (none present)".into()))?;
178        Ok(Self { adapter })
179    }
180
181    pub fn as_ptr(&self) -> JObject {
182        self.adapter.as_ptr()
183    }
184
185    /// Whether the adapter is on.
186    pub fn is_enabled(&self, env: Env) -> bool {
187        call_bool(env, self.as_ptr(), "isEnabled", "()Z", &[]).unwrap_or(false)
188    }
189
190    /// `adapter.getName()` — what this device advertises itself as.
191    pub fn name(&self, env: Env) -> Option<String> {
192        let name = call_object(env, self.as_ptr(), "getName", "()Ljava/lang/String;", &[]).ok()?;
193        env.get_string(name)
194    }
195
196    /// `adapter.getAddress()` — the controller's own address.
197    ///
198    /// Since Android 6 this returns a fixed `02:00:00:00:00:00` to any app
199    /// without `LOCAL_MAC_ADDRESS_PERMISSION`, which is a system permission an
200    /// ordinary app cannot hold. The caller is expected to recognise that and
201    /// report nothing rather than a placeholder every device shares.
202    pub fn address(&self, env: Env) -> Option<String> {
203        let address = call_object(
204            env,
205            self.as_ptr(),
206            "getAddress",
207            "()Ljava/lang/String;",
208            &[],
209        )
210        .ok()?;
211        env.get_string(address)
212    }
213
214    /// `adapter.getBluetoothLeScanner()` — null while Bluetooth is off.
215    pub fn scanner(&self, env: Env) -> Result<JObject> {
216        call_object(
217            env,
218            self.as_ptr(),
219            "getBluetoothLeScanner",
220            "()Landroid/bluetooth/le/BluetoothLeScanner;",
221            &[],
222        )
223    }
224
225    /// `adapter.getRemoteDevice(address)`.
226    pub fn remote_device(&self, env: Env, address: &str) -> Result<JObject> {
227        let address = env.new_string(address);
228        call_object(
229            env,
230            self.as_ptr(),
231            "getRemoteDevice",
232            "(Ljava/lang/String;)Landroid/bluetooth/BluetoothDevice;",
233            &[JValue::object(address)],
234        )
235    }
236
237    /// `adapter.getBluetoothLeAdvertiser()` — null where advertising is
238    /// unsupported, which is common on older or cheaper hardware.
239    pub fn advertiser(&self, env: Env) -> Result<JObject> {
240        call_object(
241            env,
242            self.as_ptr(),
243            "getBluetoothLeAdvertiser",
244            "()Landroid/bluetooth/le/BluetoothLeAdvertiser;",
245            &[],
246        )
247    }
248}
249
250// ── Scanning ────────────────────────────────────────────────────────────────
251
252/// Start a scan, filtering on service UUIDs where possible.
253///
254/// Android's filters run in the controller, so a filtered scan also survives
255/// the background restrictions an unfiltered one does not.
256pub fn start_scan(
257    env: Env,
258    scanner: JObject,
259    callback: JObject,
260    service_uuids: &[String],
261) -> Result<()> {
262    let filters = build_scan_filters(env, service_uuids)?;
263    let settings = build_scan_settings(env)?;
264    call_void(
265        env,
266        scanner,
267        "startScan",
268        "(Ljava/util/List;Landroid/bluetooth/le/ScanSettings;Landroid/bluetooth/le/ScanCallback;)V",
269        &[
270            JValue::object(filters),
271            JValue::object(settings),
272            JValue::object(callback),
273        ],
274    )
275}
276
277pub fn stop_scan(env: Env, scanner: JObject, callback: JObject) -> Result<()> {
278    call_void(
279        env,
280        scanner,
281        "stopScan",
282        "(Landroid/bluetooth/le/ScanCallback;)V",
283        &[JValue::object(callback)],
284    )
285}
286
287fn build_scan_filters(env: Env, service_uuids: &[String]) -> Result<JObject> {
288    let list_class = env
289        .find_class("java/util/ArrayList")
290        .ok_or_else(|| Error::MissingClass("java.util.ArrayList".into()))?;
291    let ctor = env
292        .method_id(list_class, "<init>", "()V")
293        .ok_or_else(|| missing("ArrayList"))?;
294    let list = env.new_object(list_class, ctor, &[]);
295
296    let filter_builder_class = env
297        .find_class("android/bluetooth/le/ScanFilter$Builder")
298        .ok_or_else(|| Error::MissingClass("ScanFilter.Builder".into()))?;
299    let builder_ctor = env
300        .method_id(filter_builder_class, "<init>", "()V")
301        .ok_or_else(|| missing("ScanFilter.Builder.<init>"))?;
302
303    for canonical in service_uuids {
304        let builder = env.new_object(filter_builder_class, builder_ctor, &[]);
305        let parcel = parcel_uuid(env, canonical)?;
306        call_object(
307            env,
308            builder,
309            "setServiceUuid",
310            "(Landroid/os/ParcelUuid;)Landroid/bluetooth/le/ScanFilter$Builder;",
311            &[JValue::object(parcel)],
312        )?;
313        let filter = call_object(
314            env,
315            builder,
316            "build",
317            "()Landroid/bluetooth/le/ScanFilter;",
318            &[],
319        )?;
320        call_bool(
321            env,
322            list,
323            "add",
324            "(Ljava/lang/Object;)Z",
325            &[JValue::object(filter)],
326        )?;
327    }
328    Ok(list)
329}
330
331fn build_scan_settings(env: Env) -> Result<JObject> {
332    let class = env
333        .find_class("android/bluetooth/le/ScanSettings$Builder")
334        .ok_or_else(|| Error::MissingClass("ScanSettings.Builder".into()))?;
335    let ctor = env
336        .method_id(class, "<init>", "()V")
337        .ok_or_else(|| missing("ScanSettings.Builder.<init>"))?;
338    let builder = env.new_object(class, ctor, &[]);
339
340    // SCAN_MODE_LOW_LATENCY = 2. A chooser is waiting on this, so latency
341    // matters more than power for the seconds it runs.
342    call_object(
343        env,
344        builder,
345        "setScanMode",
346        "(I)Landroid/bluetooth/le/ScanSettings$Builder;",
347        &[JValue::int(2)],
348    )?;
349    call_object(
350        env,
351        builder,
352        "build",
353        "()Landroid/bluetooth/le/ScanSettings;",
354        &[],
355    )
356}
357
358// ── GATT client ─────────────────────────────────────────────────────────────
359
360/// `device.connectGatt(context, false, callback, TRANSPORT_LE)`.
361///
362/// `autoConnect = false` connects now and fails if the peer is not there;
363/// `true` waits indefinitely, which is not what `connect()` promises.
364/// `device.createBond()` — start the pairing ceremony.
365///
366/// `false` means it did not start at all; `true` means it started, which is
367/// not the same as finished. Android reports the outcome later, through a
368/// broadcast.
369/// `gatt.setPreferredPhy(txMask, rxMask, options)`.
370///
371/// Masks rather than values: a caller states which PHYs it will accept and the
372/// controller picks. `options` is the coded-PHY preference and is ignored
373/// unless coded is in the mask.
374pub fn set_preferred_phy(env: Env, gatt: JObject, tx: i32, rx: i32, options: i32) -> Result<()> {
375    call_void(
376        env,
377        gatt,
378        "setPreferredPhy",
379        "(III)V",
380        &[JValue::int(tx), JValue::int(rx), JValue::int(options)],
381    )
382}
383
384/// `gatt.readPhy()` — the answer arrives in `onPhyRead`.
385pub fn read_phy(env: Env, gatt: JObject) -> Result<()> {
386    call_void(env, gatt, "readPhy", "()V", &[])
387}
388
389pub fn create_bond(env: Env, device: JObject) -> Result<bool> {
390    call_bool(env, device, "createBond", "()Z", &[])
391}
392
393/// `device.getBondState()` — `BOND_NONE`, `BOND_BONDING` or `BOND_BONDED`.
394pub fn bond_state(env: Env, device: JObject) -> Result<i32> {
395    call_int(env, device, "getBondState", "()I", &[])
396}
397
398pub fn connect_gatt(
399    env: Env,
400    runtime: &Runtime,
401    device: JObject,
402    callback: JObject,
403) -> Result<JObject> {
404    call_object(
405        env,
406        device,
407        "connectGatt",
408        "(Landroid/content/Context;ZLandroid/bluetooth/BluetoothGattCallback;I)Landroid/bluetooth/BluetoothGatt;",
409        &[
410            JValue::object(runtime.context()),
411            JValue::bool(false),
412            JValue::object(callback),
413            JValue::int(TRANSPORT_LE),
414        ],
415    )
416}
417
418pub fn discover_services(env: Env, gatt: JObject) -> Result<bool> {
419    call_bool(env, gatt, "discoverServices", "()Z", &[])
420}
421
422pub fn services(env: Env, gatt: JObject) -> Result<JObject> {
423    call_object(env, gatt, "getServices", "()Ljava/util/List;", &[])
424}
425
426pub fn service_characteristics(env: Env, service: JObject) -> Result<JObject> {
427    call_object(
428        env,
429        service,
430        "getCharacteristics",
431        "()Ljava/util/List;",
432        &[],
433    )
434}
435
436/// `BluetoothGattService.getIncludedServices()`.
437///
438/// Android populates this from the Include declarations it read during service
439/// discovery, so no extra round trip is needed — unlike CoreBluetooth, which
440/// has to be asked.
441pub fn service_included_services(env: Env, service: JObject) -> Result<JObject> {
442    call_object(
443        env,
444        service,
445        "getIncludedServices",
446        "()Ljava/util/List;",
447        &[],
448    )
449}
450
451pub fn characteristic_descriptors(env: Env, characteristic: JObject) -> Result<JObject> {
452    call_object(
453        env,
454        characteristic,
455        "getDescriptors",
456        "()Ljava/util/List;",
457        &[],
458    )
459}
460
461pub fn attribute_uuid(env: Env, attribute: JObject) -> Option<String> {
462    let uuid = call_object(env, attribute, "getUuid", "()Ljava/util/UUID;", &[]).ok()?;
463    uuid_string(env, uuid)
464}
465
466pub fn characteristic_properties(env: Env, characteristic: JObject) -> i32 {
467    call_int(env, characteristic, "getProperties", "()I", &[]).unwrap_or(0)
468}
469
470pub fn characteristic_value(env: Env, characteristic: JObject) -> Option<Vec<u8>> {
471    let array = call_object(env, characteristic, "getValue", "()[B", &[]).ok()?;
472    env.byte_array(array)
473}
474
475pub fn read_characteristic(env: Env, gatt: JObject, characteristic: JObject) -> Result<bool> {
476    call_bool(
477        env,
478        gatt,
479        "readCharacteristic",
480        "(Landroid/bluetooth/BluetoothGattCharacteristic;)Z",
481        &[JValue::object(characteristic)],
482    )
483}
484
485/// Write a characteristic, using whichever API this device has.
486///
487/// API 33 replaced the set-then-write pair with a single call, and deprecated
488/// the old one. Both are tried, newest first, because a library cannot pick at
489/// build time what the device will offer at run time.
490pub fn write_characteristic(
491    env: Env,
492    gatt: JObject,
493    characteristic: JObject,
494    value: &[u8],
495    write_type: i32,
496) -> Result<bool> {
497    let bytes = env.new_byte_array(value);
498
499    // API 33+: writeCharacteristic(characteristic, byte[], int) -> int status
500    if let Some(method) = env.method_id(
501        env.get_object_class(gatt),
502        "writeCharacteristic",
503        "(Landroid/bluetooth/BluetoothGattCharacteristic;[BI)I",
504    ) {
505        let status = env.call_int(
506            gatt,
507            method,
508            &[
509                JValue::object(characteristic),
510                JValue::object(bytes),
511                JValue::int(write_type),
512            ],
513        );
514        return Ok(status == GATT_SUCCESS);
515    }
516
517    // Older: set the value on the characteristic, then write it.
518    call_int(
519        env,
520        characteristic,
521        "setWriteType",
522        "(I)V",
523        &[JValue::int(write_type)],
524    )
525    .ok();
526    call_bool(
527        env,
528        characteristic,
529        "setValue",
530        "([B)Z",
531        &[JValue::object(bytes)],
532    )?;
533    call_bool(
534        env,
535        gatt,
536        "writeCharacteristic",
537        "(Landroid/bluetooth/BluetoothGattCharacteristic;)Z",
538        &[JValue::object(characteristic)],
539    )
540}
541
542/// Subscribe.
543///
544/// Two steps, and missing the second is the most common Android BLE bug: local
545/// delivery has to be enabled *and* the peer has to be told, by writing its
546/// Client Characteristic Configuration descriptor.
547pub fn set_notify(
548    env: Env,
549    gatt: JObject,
550    characteristic: JObject,
551    enable: bool,
552    indicate: bool,
553) -> Result<bool> {
554    call_bool(
555        env,
556        gatt,
557        "setCharacteristicNotification",
558        "(Landroid/bluetooth/BluetoothGattCharacteristic;Z)Z",
559        &[JValue::object(characteristic), JValue::bool(enable)],
560    )?;
561
562    let cccd = uuid(env, "00002902-0000-1000-8000-00805f9b34fb")?;
563    let descriptor = call_object(
564        env,
565        characteristic,
566        "getDescriptor",
567        "(Ljava/util/UUID;)Landroid/bluetooth/BluetoothGattDescriptor;",
568        &[JValue::object(cccd)],
569    )?;
570    if descriptor.is_null() {
571        // No CCCD: local delivery is on, but the peer will send nothing.
572        return Ok(false);
573    }
574
575    let value: &[u8] = match (enable, indicate) {
576        (false, _) => &[0x00, 0x00],
577        (true, false) => &[0x01, 0x00],
578        (true, true) => &[0x02, 0x00],
579    };
580    write_descriptor(env, gatt, descriptor, value)
581}
582
583pub fn read_descriptor(env: Env, gatt: JObject, descriptor: JObject) -> Result<bool> {
584    call_bool(
585        env,
586        gatt,
587        "readDescriptor",
588        "(Landroid/bluetooth/BluetoothGattDescriptor;)Z",
589        &[JValue::object(descriptor)],
590    )
591}
592
593pub fn write_descriptor(
594    env: Env,
595    gatt: JObject,
596    descriptor: JObject,
597    value: &[u8],
598) -> Result<bool> {
599    let bytes = env.new_byte_array(value);
600
601    // API 33+ takes the value directly.
602    if let Some(method) = env.method_id(
603        env.get_object_class(gatt),
604        "writeDescriptor",
605        "(Landroid/bluetooth/BluetoothGattDescriptor;[B)I",
606    ) {
607        let status = env.call_int(
608            gatt,
609            method,
610            &[JValue::object(descriptor), JValue::object(bytes)],
611        );
612        return Ok(status == GATT_SUCCESS);
613    }
614
615    call_bool(
616        env,
617        descriptor,
618        "setValue",
619        "([B)Z",
620        &[JValue::object(bytes)],
621    )?;
622    call_bool(
623        env,
624        gatt,
625        "writeDescriptor",
626        "(Landroid/bluetooth/BluetoothGattDescriptor;)Z",
627        &[JValue::object(descriptor)],
628    )
629}
630
631pub fn request_mtu(env: Env, gatt: JObject, mtu: i32) -> Result<bool> {
632    call_bool(env, gatt, "requestMtu", "(I)Z", &[JValue::int(mtu)])
633}
634
635pub fn read_remote_rssi(env: Env, gatt: JObject) -> Result<bool> {
636    call_bool(env, gatt, "readRemoteRssi", "()Z", &[])
637}
638
639/// `BluetoothGatt.requestConnectionPriority(int)`.
640///
641/// A hint: Android asks the controller to re-negotiate the connection
642/// interval, and the peripheral has the final say. `false` means the request
643/// was not even sent — usually because the argument was out of range or the
644/// link is gone.
645pub fn request_connection_priority(env: Env, gatt: JObject, priority: i32) -> Result<bool> {
646    call_bool(
647        env,
648        gatt,
649        "requestConnectionPriority",
650        "(I)Z",
651        &[JValue::int(priority)],
652    )
653}
654
655pub fn disconnect(env: Env, gatt: JObject) -> Result<()> {
656    call_void(env, gatt, "disconnect", "()V", &[])
657}
658
659/// Release the connection's resources.
660///
661/// Android allows a small number of concurrent GATT clients — historically 32,
662/// far fewer in practice — and leaking them is how an app stops being able to
663/// connect at all until it is restarted.
664pub fn close(env: Env, gatt: JObject) -> Result<()> {
665    call_void(env, gatt, "close", "()V", &[])
666}
667
668// ── L2CAP ───────────────────────────────────────────────────────────────────
669
670/// `device.createL2capChannel(psm)` — API 29+.
671pub fn create_l2cap_channel(env: Env, device: JObject, psm: i32) -> Result<JObject> {
672    call_object(
673        env,
674        device,
675        "createL2capChannel",
676        "(I)Landroid/bluetooth/BluetoothSocket;",
677        &[JValue::int(psm)],
678    )
679}
680
681pub fn socket_connect(env: Env, socket: JObject) -> Result<()> {
682    call_void(env, socket, "connect", "()V", &[])
683}
684
685pub fn socket_close(env: Env, socket: JObject) -> Result<()> {
686    call_void(env, socket, "close", "()V", &[])
687}
688
689pub fn socket_input_stream(env: Env, socket: JObject) -> Result<JObject> {
690    call_object(
691        env,
692        socket,
693        "getInputStream",
694        "()Ljava/io/InputStream;",
695        &[],
696    )
697}
698
699pub fn socket_output_stream(env: Env, socket: JObject) -> Result<JObject> {
700    call_object(
701        env,
702        socket,
703        "getOutputStream",
704        "()Ljava/io/OutputStream;",
705        &[],
706    )
707}
708
709/// Read once from a `java.io.InputStream`. `Ok(None)` at end of stream.
710pub fn stream_read(env: Env, stream: JObject, buffer: usize) -> Result<Option<Vec<u8>>> {
711    let array = env.new_byte_array(&vec![0u8; buffer]);
712    let n = call_int(env, stream, "read", "([B)I", &[JValue::object(array)])?;
713    if n < 0 {
714        return Ok(None);
715    }
716    let mut bytes = env.byte_array(array).unwrap_or_default();
717    bytes.truncate(n as usize);
718    Ok(Some(bytes))
719}
720
721pub fn stream_write(env: Env, stream: JObject, data: &[u8]) -> Result<()> {
722    let array = env.new_byte_array(data);
723    call_void(env, stream, "write", "([B)V", &[JValue::object(array)])?;
724    call_void(env, stream, "flush", "()V", &[])
725}
726
727// ── Callback objects ────────────────────────────────────────────────────────
728
729/// A generated callback class, instantiated and bound to a sink.
730pub struct Callback {
731    object: Ref,
732}
733
734impl Callback {
735    /// Define the class if needed, make one, and route its events to `sink`.
736    pub fn new(
737        runtime: &Runtime,
738        binary_name: &str,
739        dex: Vec<u8>,
740        natives: &[(&str, &str, *const std::ffi::c_void)],
741        sink: Arc<dyn EventSink>,
742    ) -> Result<Self> {
743        let class = runtime.define_class(binary_name, dex, natives)?;
744        let object = runtime.new_instance(class)?;
745        let env = runtime.env()?;
746        let object = Ref::new(env, object)
747            .ok_or_else(|| Error::ClassLoad(format!("{binary_name} produced a null instance")))?;
748        crate::bluetooth::bind_sink(&object, sink);
749        Ok(Self { object })
750    }
751
752    pub fn as_ptr(&self) -> JObject {
753        self.object.as_ptr()
754    }
755}
756
757impl Drop for Callback {
758    fn drop(&mut self) {
759        crate::bluetooth::unbind_sink(&self.object);
760    }
761}
762
763/// Discard events — useful where a callback is required but nothing listens.
764pub struct Discard;
765
766impl EventSink for Discard {
767    fn emit(&self, _: Event) {}
768}
769
770// ── Peripheral role ─────────────────────────────────────────────────────────
771
772/// `BluetoothGattService.SERVICE_TYPE_PRIMARY` / `_SECONDARY`.
773const SERVICE_TYPE_PRIMARY: i32 = 0;
774const SERVICE_TYPE_SECONDARY: i32 = 1;
775
776/// `BluetoothGattServer.GATT_SUCCESS` and the ATT codes it forwards.
777pub const ATT_SUCCESS: i32 = 0;
778
779/// Map the shared permission bits onto Android's.
780///
781/// Android's constants are not the Bluetooth ones: read is `1` but write is
782/// `16`, with the encrypted variants interleaved between them.
783pub fn permissions_to_android(permissions: u32) -> i32 {
784    const READABLE: u32 = 0x01;
785    const WRITEABLE: u32 = 0x02;
786    const READ_ENCRYPTED: u32 = 0x04;
787    const WRITE_ENCRYPTED: u32 = 0x08;
788
789    let mut out = 0;
790    if permissions & READABLE != 0 {
791        out |= 1; // PERMISSION_READ
792    }
793    if permissions & READ_ENCRYPTED != 0 {
794        out |= 2; // PERMISSION_READ_ENCRYPTED
795    }
796    if permissions & WRITEABLE != 0 {
797        out |= 16; // PERMISSION_WRITE
798    }
799    if permissions & WRITE_ENCRYPTED != 0 {
800        out |= 32; // PERMISSION_WRITE_ENCRYPTED
801    }
802    out
803}
804
805/// `manager.openGattServer(context, callback)`.
806pub fn open_gatt_server(env: Env, runtime: &Runtime, callback: JObject) -> Result<JObject> {
807    let context_class = env
808        .find_class("android/content/Context")
809        .ok_or_else(|| Error::MissingClass("android.content.Context".into()))?;
810    let field = env
811        .static_field_id(context_class, "BLUETOOTH_SERVICE", "Ljava/lang/String;")
812        .ok_or_else(|| missing("Context.BLUETOOTH_SERVICE"))?;
813    let name = env.static_object_field(context_class, field);
814    let manager = call_object(
815        env,
816        runtime.context(),
817        "getSystemService",
818        "(Ljava/lang/String;)Ljava/lang/Object;",
819        &[JValue::object(name)],
820    )?;
821    call_object(
822        env,
823        manager,
824        "openGattServer",
825        "(Landroid/content/Context;Landroid/bluetooth/BluetoothGattServerCallback;)Landroid/bluetooth/BluetoothGattServer;",
826        &[JValue::object(runtime.context()), JValue::object(callback)],
827    )
828}
829
830/// `new BluetoothGattService(uuid, primary ? PRIMARY : SECONDARY)`.
831pub fn new_service(env: Env, canonical: &str, primary: bool) -> Result<JObject> {
832    let class = env
833        .find_class("android/bluetooth/BluetoothGattService")
834        .ok_or_else(|| Error::MissingClass("BluetoothGattService".into()))?;
835    let ctor = env
836        .method_id(class, "<init>", "(Ljava/util/UUID;I)V")
837        .ok_or_else(|| missing("BluetoothGattService.<init>"))?;
838    let uuid = uuid(env, canonical)?;
839    let kind = if primary {
840        SERVICE_TYPE_PRIMARY
841    } else {
842        SERVICE_TYPE_SECONDARY
843    };
844    Ok(env.new_object(class, ctor, &[JValue::object(uuid), JValue::int(kind)]))
845}
846
847/// `new BluetoothGattCharacteristic(uuid, properties, permissions)`.
848pub fn new_characteristic(
849    env: Env,
850    canonical: &str,
851    properties: u32,
852    permissions: u32,
853) -> Result<JObject> {
854    let class = env
855        .find_class("android/bluetooth/BluetoothGattCharacteristic")
856        .ok_or_else(|| Error::MissingClass("BluetoothGattCharacteristic".into()))?;
857    let ctor = env
858        .method_id(class, "<init>", "(Ljava/util/UUID;II)V")
859        .ok_or_else(|| missing("BluetoothGattCharacteristic.<init>"))?;
860    let uuid = uuid(env, canonical)?;
861    Ok(env.new_object(
862        class,
863        ctor,
864        &[
865            JValue::object(uuid),
866            // Android's PROPERTY_* are the Bluetooth bits, unlike its
867            // permissions.
868            JValue::int(properties as i32),
869            JValue::int(permissions_to_android(permissions)),
870        ],
871    ))
872}
873
874/// `new BluetoothGattDescriptor(uuid, permissions)`.
875pub fn new_descriptor(env: Env, canonical: &str, permissions: u32) -> Result<JObject> {
876    let class = env
877        .find_class("android/bluetooth/BluetoothGattDescriptor")
878        .ok_or_else(|| Error::MissingClass("BluetoothGattDescriptor".into()))?;
879    let ctor = env
880        .method_id(class, "<init>", "(Ljava/util/UUID;I)V")
881        .ok_or_else(|| missing("BluetoothGattDescriptor.<init>"))?;
882    let uuid = uuid(env, canonical)?;
883    Ok(env.new_object(
884        class,
885        ctor,
886        &[
887            JValue::object(uuid),
888            JValue::int(permissions_to_android(permissions)),
889        ],
890    ))
891}
892
893pub fn service_add_characteristic(
894    env: Env,
895    service: JObject,
896    characteristic: JObject,
897) -> Result<bool> {
898    call_bool(
899        env,
900        service,
901        "addCharacteristic",
902        "(Landroid/bluetooth/BluetoothGattCharacteristic;)Z",
903        &[JValue::object(characteristic)],
904    )
905}
906
907pub fn characteristic_add_descriptor(
908    env: Env,
909    characteristic: JObject,
910    descriptor: JObject,
911) -> Result<bool> {
912    call_bool(
913        env,
914        characteristic,
915        "addDescriptor",
916        "(Landroid/bluetooth/BluetoothGattDescriptor;)Z",
917        &[JValue::object(descriptor)],
918    )
919}
920
921pub fn set_value(env: Env, attribute: JObject, value: &[u8]) -> Result<bool> {
922    let bytes = env.new_byte_array(value);
923    call_bool(
924        env,
925        attribute,
926        "setValue",
927        "([B)Z",
928        &[JValue::object(bytes)],
929    )
930}
931
932pub fn server_add_service(env: Env, server: JObject, service: JObject) -> Result<bool> {
933    call_bool(
934        env,
935        server,
936        "addService",
937        "(Landroid/bluetooth/BluetoothGattService;)Z",
938        &[JValue::object(service)],
939    )
940}
941
942pub fn server_remove_service(env: Env, server: JObject, service: JObject) -> Result<bool> {
943    call_bool(
944        env,
945        server,
946        "removeService",
947        "(Landroid/bluetooth/BluetoothGattService;)Z",
948        &[JValue::object(service)],
949    )
950}
951
952pub fn server_clear_services(env: Env, server: JObject) -> Result<()> {
953    call_void(env, server, "clearServices", "()V", &[])
954}
955
956pub fn server_close(env: Env, server: JObject) -> Result<()> {
957    call_void(env, server, "close", "()V", &[])
958}
959
960/// `server.sendResponse(device, requestId, status, offset, value)`.
961///
962/// Every request that asked for a response must get exactly one, or the central
963/// stalls until the ATT timeout.
964pub fn server_send_response(
965    env: Env,
966    server: JObject,
967    device: JObject,
968    request_id: i32,
969    status: i32,
970    offset: i32,
971    value: &[u8],
972) -> Result<bool> {
973    let bytes = env.new_byte_array(value);
974    call_bool(
975        env,
976        server,
977        "sendResponse",
978        "(Landroid/bluetooth/BluetoothDevice;III[B)Z",
979        &[
980            JValue::object(device),
981            JValue::int(request_id),
982            JValue::int(status),
983            JValue::int(offset),
984            JValue::object(bytes),
985        ],
986    )
987}
988
989/// Push a value to one subscriber.
990///
991/// API 33 takes the bytes directly and returns a status; older releases want
992/// the value set on the characteristic first. Both are tried, newest first.
993pub fn server_notify(
994    env: Env,
995    server: JObject,
996    device: JObject,
997    characteristic: JObject,
998    confirm: bool,
999    value: &[u8],
1000) -> Result<bool> {
1001    let bytes = env.new_byte_array(value);
1002
1003    if let Some(method) = env.method_id(
1004        env.get_object_class(server),
1005        "notifyCharacteristicChanged",
1006        "(Landroid/bluetooth/BluetoothDevice;Landroid/bluetooth/BluetoothGattCharacteristic;Z[B)I",
1007    ) {
1008        let status = env.call_int(
1009            server,
1010            method,
1011            &[
1012                JValue::object(device),
1013                JValue::object(characteristic),
1014                JValue::bool(confirm),
1015                JValue::object(bytes),
1016            ],
1017        );
1018        return Ok(status == ATT_SUCCESS);
1019    }
1020
1021    set_value(env, characteristic, value)?;
1022    call_bool(
1023        env,
1024        server,
1025        "notifyCharacteristicChanged",
1026        "(Landroid/bluetooth/BluetoothDevice;Landroid/bluetooth/BluetoothGattCharacteristic;Z)Z",
1027        &[
1028            JValue::object(device),
1029            JValue::object(characteristic),
1030            JValue::bool(confirm),
1031        ],
1032    )
1033}
1034
1035/// The centrals connected to the GATT server.
1036pub fn server_connected_devices(env: Env, runtime: &Runtime) -> Result<JObject> {
1037    let context_class = env
1038        .find_class("android/content/Context")
1039        .ok_or_else(|| Error::MissingClass("android.content.Context".into()))?;
1040    let field = env
1041        .static_field_id(context_class, "BLUETOOTH_SERVICE", "Ljava/lang/String;")
1042        .ok_or_else(|| missing("Context.BLUETOOTH_SERVICE"))?;
1043    let name = env.static_object_field(context_class, field);
1044    let manager = call_object(
1045        env,
1046        runtime.context(),
1047        "getSystemService",
1048        "(Ljava/lang/String;)Ljava/lang/Object;",
1049        &[JValue::object(name)],
1050    )?;
1051    // BluetoothProfile.GATT_SERVER == 8
1052    call_object(
1053        env,
1054        manager,
1055        "getConnectedDevices",
1056        "(I)Ljava/util/List;",
1057        &[JValue::int(8)],
1058    )
1059}
1060
1061pub fn device_address(env: Env, device: JObject) -> Option<String> {
1062    let s = call_object(env, device, "getAddress", "()Ljava/lang/String;", &[]).ok()?;
1063    env.get_string(s)
1064}
1065
1066// ── Advertising ─────────────────────────────────────────────────────────────
1067
1068/// Start advertising.
1069///
1070/// Android will not put an arbitrary name in the payload: `AdvertiseData` only
1071/// offers `setIncludeDeviceName`, which uses the *adapter's* name. Changing
1072/// that means `BluetoothAdapter.setName`, which is global to the device — so
1073/// [`Advertising::local_name`] is honoured by including the device name, not by
1074/// overriding it.
1075///
1076/// [`Advertising::local_name`]: crate::ble
1077pub fn start_advertising(
1078    env: Env,
1079    advertiser: JObject,
1080    callback: JObject,
1081    include_name: bool,
1082    service_uuids: &[String],
1083    connectable: bool,
1084) -> Result<()> {
1085    let settings = build_advertise_settings(env, connectable)?;
1086    let data = build_advertise_data(env, include_name, service_uuids)?;
1087    call_void(
1088        env,
1089        advertiser,
1090        "startAdvertising",
1091        concat!(
1092            "(Landroid/bluetooth/le/AdvertiseSettings;",
1093            "Landroid/bluetooth/le/AdvertiseData;",
1094            "Landroid/bluetooth/le/AdvertiseCallback;)V"
1095        ),
1096        &[
1097            JValue::object(settings),
1098            JValue::object(data),
1099            JValue::object(callback),
1100        ],
1101    )
1102}
1103
1104pub fn stop_advertising(env: Env, advertiser: JObject, callback: JObject) -> Result<()> {
1105    call_void(
1106        env,
1107        advertiser,
1108        "stopAdvertising",
1109        "(Landroid/bluetooth/le/AdvertiseCallback;)V",
1110        &[JValue::object(callback)],
1111    )
1112}
1113
1114fn build_advertise_settings(env: Env, connectable: bool) -> Result<JObject> {
1115    let class = env
1116        .find_class("android/bluetooth/le/AdvertiseSettings$Builder")
1117        .ok_or_else(|| Error::MissingClass("AdvertiseSettings.Builder".into()))?;
1118    let ctor = env
1119        .method_id(class, "<init>", "()V")
1120        .ok_or_else(|| missing("AdvertiseSettings.Builder.<init>"))?;
1121    let builder = env.new_object(class, ctor, &[]);
1122
1123    // ADVERTISE_MODE_LOW_LATENCY = 2: a peripheral is meant to be found.
1124    call_object(
1125        env,
1126        builder,
1127        "setAdvertiseMode",
1128        "(I)Landroid/bluetooth/le/AdvertiseSettings$Builder;",
1129        &[JValue::int(2)],
1130    )?;
1131    call_object(
1132        env,
1133        builder,
1134        "setConnectable",
1135        "(Z)Landroid/bluetooth/le/AdvertiseSettings$Builder;",
1136        &[JValue::bool(connectable)],
1137    )?;
1138    call_object(
1139        env,
1140        builder,
1141        "build",
1142        "()Landroid/bluetooth/le/AdvertiseSettings;",
1143        &[],
1144    )
1145}
1146
1147fn build_advertise_data(env: Env, include_name: bool, service_uuids: &[String]) -> Result<JObject> {
1148    let class = env
1149        .find_class("android/bluetooth/le/AdvertiseData$Builder")
1150        .ok_or_else(|| Error::MissingClass("AdvertiseData.Builder".into()))?;
1151    let ctor = env
1152        .method_id(class, "<init>", "()V")
1153        .ok_or_else(|| missing("AdvertiseData.Builder.<init>"))?;
1154    let builder = env.new_object(class, ctor, &[]);
1155
1156    call_object(
1157        env,
1158        builder,
1159        "setIncludeDeviceName",
1160        "(Z)Landroid/bluetooth/le/AdvertiseData$Builder;",
1161        &[JValue::bool(include_name)],
1162    )?;
1163    for canonical in service_uuids {
1164        let parcel = parcel_uuid(env, canonical)?;
1165        call_object(
1166            env,
1167            builder,
1168            "addServiceUuid",
1169            "(Landroid/os/ParcelUuid;)Landroid/bluetooth/le/AdvertiseData$Builder;",
1170            &[JValue::object(parcel)],
1171        )?;
1172    }
1173    call_object(
1174        env,
1175        builder,
1176        "build",
1177        "()Landroid/bluetooth/le/AdvertiseData;",
1178        &[],
1179    )
1180}
1181
1182// ── L2CAP, listening side ───────────────────────────────────────────────────
1183
1184/// `adapter.listenUsingInsecureL2capChannel()` — API 29+.
1185///
1186/// Returns a `BluetoothServerSocket`; its PSM is assigned by the system and
1187/// read back with `getPsm()`.
1188pub fn listen_l2cap(env: Env, adapter: JObject, secure: bool) -> Result<JObject> {
1189    let name = if secure {
1190        "listenUsingL2capChannel"
1191    } else {
1192        "listenUsingInsecureL2capChannel"
1193    };
1194    call_object(
1195        env,
1196        adapter,
1197        name,
1198        "()Landroid/bluetooth/BluetoothServerSocket;",
1199        &[],
1200    )
1201}
1202
1203pub fn server_socket_psm(env: Env, socket: JObject) -> Result<i32> {
1204    call_int(env, socket, "getPsm", "()I", &[])
1205}
1206
1207/// Block until a central connects, then return the accepted socket.
1208pub fn server_socket_accept(env: Env, socket: JObject) -> Result<JObject> {
1209    call_object(
1210        env,
1211        socket,
1212        "accept",
1213        "()Landroid/bluetooth/BluetoothSocket;",
1214        &[],
1215    )
1216}
1217
1218pub fn server_socket_close(env: Env, socket: JObject) -> Result<()> {
1219    call_void(env, socket, "close", "()V", &[])
1220}