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    /// Return addresses of devices in `BluetoothAdapter.getBondedDevices()`.
238    pub fn bonded_device_addresses(&self, env: Env) -> Result<Vec<String>> {
239        let bonded = call_object(
240            env,
241            self.as_ptr(),
242            "getBondedDevices",
243            "()Ljava/util/Set;",
244            &[],
245        )?;
246        let iterator = call_object(env, bonded, "iterator", "()Ljava/util/Iterator;", &[])?;
247        let iterator_class = env.get_object_class(iterator);
248        let has_next = env
249            .method_id(iterator_class, "hasNext", "()Z")
250            .ok_or_else(|| Error::MissingMethod("Iterator.hasNext".into()))?;
251        let next = env
252            .method_id(iterator_class, "next", "()Ljava/lang/Object;")
253            .ok_or_else(|| Error::MissingMethod("Iterator.next".into()))?;
254        let mut addresses = Vec::new();
255        while env.call_bool(iterator, has_next, &[]) {
256            let device = env.call_object(iterator, next, &[]);
257            if let Some(address) = device_address(env, device) {
258                addresses.push(address);
259            }
260        }
261        Ok(addresses)
262    }
263
264    /// Read service UUIDs reported by `BluetoothDevice.getUuids()`.
265    pub fn device_service_uuids(&self, env: Env, device: JObject) -> Result<Vec<String>> {
266        let uuids = call_object(env, device, "getUuids", "()[Landroid/os/ParcelUuid;", &[])?;
267        if uuids.is_null() {
268            return Ok(Vec::new());
269        }
270        let mut result = Vec::new();
271        let array = uuids as crate::jni::JArray;
272        for index in 0..env.array_length(array) {
273            let parcel = env.object_array_element(array, index);
274            let uuid = call_object(env, parcel, "getUuid", "()Ljava/util/UUID;", &[])?;
275            if let Some(value) = uuid_string(env, uuid) {
276                result.push(value);
277            }
278        }
279        Ok(result)
280    }
281
282    /// `adapter.getBluetoothLeAdvertiser()` — null where advertising is
283    /// unsupported, which is common on older or cheaper hardware.
284    pub fn advertiser(&self, env: Env) -> Result<JObject> {
285        call_object(
286            env,
287            self.as_ptr(),
288            "getBluetoothLeAdvertiser",
289            "()Landroid/bluetooth/le/BluetoothLeAdvertiser;",
290            &[],
291        )
292    }
293}
294
295// ── Scanning ────────────────────────────────────────────────────────────────
296
297/// Start a scan, filtering on service UUIDs where possible.
298///
299/// Android's filters run in the controller, so a filtered scan also survives
300/// the background restrictions an unfiltered one does not.
301pub fn start_scan(
302    env: Env,
303    scanner: JObject,
304    callback: JObject,
305    service_uuids: &[String],
306) -> Result<()> {
307    let filters = build_scan_filters(env, service_uuids)?;
308    let settings = build_scan_settings(env)?;
309    call_void(
310        env,
311        scanner,
312        "startScan",
313        "(Ljava/util/List;Landroid/bluetooth/le/ScanSettings;Landroid/bluetooth/le/ScanCallback;)V",
314        &[
315            JValue::object(filters),
316            JValue::object(settings),
317            JValue::object(callback),
318        ],
319    )
320}
321
322pub fn stop_scan(env: Env, scanner: JObject, callback: JObject) -> Result<()> {
323    call_void(
324        env,
325        scanner,
326        "stopScan",
327        "(Landroid/bluetooth/le/ScanCallback;)V",
328        &[JValue::object(callback)],
329    )
330}
331
332fn build_scan_filters(env: Env, service_uuids: &[String]) -> Result<JObject> {
333    let list_class = env
334        .find_class("java/util/ArrayList")
335        .ok_or_else(|| Error::MissingClass("java.util.ArrayList".into()))?;
336    let ctor = env
337        .method_id(list_class, "<init>", "()V")
338        .ok_or_else(|| missing("ArrayList"))?;
339    let list = env.new_object(list_class, ctor, &[]);
340
341    let filter_builder_class = env
342        .find_class("android/bluetooth/le/ScanFilter$Builder")
343        .ok_or_else(|| Error::MissingClass("ScanFilter.Builder".into()))?;
344    let builder_ctor = env
345        .method_id(filter_builder_class, "<init>", "()V")
346        .ok_or_else(|| missing("ScanFilter.Builder.<init>"))?;
347
348    for canonical in service_uuids {
349        let builder = env.new_object(filter_builder_class, builder_ctor, &[]);
350        let parcel = parcel_uuid(env, canonical)?;
351        call_object(
352            env,
353            builder,
354            "setServiceUuid",
355            "(Landroid/os/ParcelUuid;)Landroid/bluetooth/le/ScanFilter$Builder;",
356            &[JValue::object(parcel)],
357        )?;
358        let filter = call_object(
359            env,
360            builder,
361            "build",
362            "()Landroid/bluetooth/le/ScanFilter;",
363            &[],
364        )?;
365        call_bool(
366            env,
367            list,
368            "add",
369            "(Ljava/lang/Object;)Z",
370            &[JValue::object(filter)],
371        )?;
372    }
373    Ok(list)
374}
375
376fn build_scan_settings(env: Env) -> Result<JObject> {
377    let class = env
378        .find_class("android/bluetooth/le/ScanSettings$Builder")
379        .ok_or_else(|| Error::MissingClass("ScanSettings.Builder".into()))?;
380    let ctor = env
381        .method_id(class, "<init>", "()V")
382        .ok_or_else(|| missing("ScanSettings.Builder.<init>"))?;
383    let builder = env.new_object(class, ctor, &[]);
384
385    // SCAN_MODE_LOW_LATENCY = 2. A chooser is waiting on this, so latency
386    // matters more than power for the seconds it runs.
387    call_object(
388        env,
389        builder,
390        "setScanMode",
391        "(I)Landroid/bluetooth/le/ScanSettings$Builder;",
392        &[JValue::int(2)],
393    )?;
394    call_object(
395        env,
396        builder,
397        "build",
398        "()Landroid/bluetooth/le/ScanSettings;",
399        &[],
400    )
401}
402
403// ── GATT client ─────────────────────────────────────────────────────────────
404
405/// `device.connectGatt(context, false, callback, TRANSPORT_LE)`.
406///
407/// `autoConnect = false` connects now and fails if the peer is not there;
408/// `true` waits indefinitely, which is not what `connect()` promises.
409/// `device.createBond()` — start the pairing ceremony.
410///
411/// `false` means it did not start at all; `true` means it started, which is
412/// not the same as finished. Android reports the outcome later, through a
413/// broadcast.
414/// `gatt.setPreferredPhy(txMask, rxMask, options)`.
415///
416/// Masks rather than values: a caller states which PHYs it will accept and the
417/// controller picks. `options` is the coded-PHY preference and is ignored
418/// unless coded is in the mask.
419pub fn set_preferred_phy(env: Env, gatt: JObject, tx: i32, rx: i32, options: i32) -> Result<()> {
420    call_void(
421        env,
422        gatt,
423        "setPreferredPhy",
424        "(III)V",
425        &[JValue::int(tx), JValue::int(rx), JValue::int(options)],
426    )
427}
428
429/// `gatt.readPhy()` — the answer arrives in `onPhyRead`.
430pub fn read_phy(env: Env, gatt: JObject) -> Result<()> {
431    call_void(env, gatt, "readPhy", "()V", &[])
432}
433
434pub fn create_bond(env: Env, device: JObject) -> Result<bool> {
435    call_bool(env, device, "createBond", "()Z", &[])
436}
437
438/// `device.getBondState()` — `BOND_NONE`, `BOND_BONDING` or `BOND_BONDED`.
439pub fn bond_state(env: Env, device: JObject) -> Result<i32> {
440    call_int(env, device, "getBondState", "()I", &[])
441}
442
443pub fn connect_gatt(
444    env: Env,
445    runtime: &Runtime,
446    device: JObject,
447    callback: JObject,
448) -> Result<JObject> {
449    call_object(
450        env,
451        device,
452        "connectGatt",
453        "(Landroid/content/Context;ZLandroid/bluetooth/BluetoothGattCallback;I)Landroid/bluetooth/BluetoothGatt;",
454        &[
455            JValue::object(runtime.context()),
456            JValue::bool(false),
457            JValue::object(callback),
458            JValue::int(TRANSPORT_LE),
459        ],
460    )
461}
462
463pub fn discover_services(env: Env, gatt: JObject) -> Result<bool> {
464    call_bool(env, gatt, "discoverServices", "()Z", &[])
465}
466
467pub fn services(env: Env, gatt: JObject) -> Result<JObject> {
468    call_object(env, gatt, "getServices", "()Ljava/util/List;", &[])
469}
470
471pub fn service_characteristics(env: Env, service: JObject) -> Result<JObject> {
472    call_object(
473        env,
474        service,
475        "getCharacteristics",
476        "()Ljava/util/List;",
477        &[],
478    )
479}
480
481/// `BluetoothGattService.getIncludedServices()`.
482///
483/// Android populates this from the Include declarations it read during service
484/// discovery, so no extra round trip is needed — unlike CoreBluetooth, which
485/// has to be asked.
486pub fn service_included_services(env: Env, service: JObject) -> Result<JObject> {
487    call_object(
488        env,
489        service,
490        "getIncludedServices",
491        "()Ljava/util/List;",
492        &[],
493    )
494}
495
496pub fn characteristic_descriptors(env: Env, characteristic: JObject) -> Result<JObject> {
497    call_object(
498        env,
499        characteristic,
500        "getDescriptors",
501        "()Ljava/util/List;",
502        &[],
503    )
504}
505
506pub fn attribute_uuid(env: Env, attribute: JObject) -> Option<String> {
507    let uuid = call_object(env, attribute, "getUuid", "()Ljava/util/UUID;", &[]).ok()?;
508    uuid_string(env, uuid)
509}
510
511pub fn characteristic_properties(env: Env, characteristic: JObject) -> i32 {
512    call_int(env, characteristic, "getProperties", "()I", &[]).unwrap_or(0)
513}
514
515pub fn characteristic_value(env: Env, characteristic: JObject) -> Option<Vec<u8>> {
516    let array = call_object(env, characteristic, "getValue", "()[B", &[]).ok()?;
517    env.byte_array(array)
518}
519
520pub fn read_characteristic(env: Env, gatt: JObject, characteristic: JObject) -> Result<bool> {
521    call_bool(
522        env,
523        gatt,
524        "readCharacteristic",
525        "(Landroid/bluetooth/BluetoothGattCharacteristic;)Z",
526        &[JValue::object(characteristic)],
527    )
528}
529
530/// Write a characteristic, using whichever API this device has.
531///
532/// API 33 replaced the set-then-write pair with a single call, and deprecated
533/// the old one. Both are tried, newest first, because a library cannot pick at
534/// build time what the device will offer at run time.
535pub fn write_characteristic(
536    env: Env,
537    gatt: JObject,
538    characteristic: JObject,
539    value: &[u8],
540    write_type: i32,
541) -> Result<bool> {
542    let bytes = env.new_byte_array(value);
543
544    // API 33+: writeCharacteristic(characteristic, byte[], int) -> int status
545    if let Some(method) = env.method_id(
546        env.get_object_class(gatt),
547        "writeCharacteristic",
548        "(Landroid/bluetooth/BluetoothGattCharacteristic;[BI)I",
549    ) {
550        let status = env.call_int(
551            gatt,
552            method,
553            &[
554                JValue::object(characteristic),
555                JValue::object(bytes),
556                JValue::int(write_type),
557            ],
558        );
559        return Ok(status == GATT_SUCCESS);
560    }
561
562    // Older: set the value on the characteristic, then write it.
563    call_int(
564        env,
565        characteristic,
566        "setWriteType",
567        "(I)V",
568        &[JValue::int(write_type)],
569    )
570    .ok();
571    call_bool(
572        env,
573        characteristic,
574        "setValue",
575        "([B)Z",
576        &[JValue::object(bytes)],
577    )?;
578    call_bool(
579        env,
580        gatt,
581        "writeCharacteristic",
582        "(Landroid/bluetooth/BluetoothGattCharacteristic;)Z",
583        &[JValue::object(characteristic)],
584    )
585}
586
587/// Subscribe.
588///
589/// Two steps, and missing the second is the most common Android BLE bug: local
590/// delivery has to be enabled *and* the peer has to be told, by writing its
591/// Client Characteristic Configuration descriptor.
592pub fn set_notify(
593    env: Env,
594    gatt: JObject,
595    characteristic: JObject,
596    enable: bool,
597    indicate: bool,
598) -> Result<bool> {
599    call_bool(
600        env,
601        gatt,
602        "setCharacteristicNotification",
603        "(Landroid/bluetooth/BluetoothGattCharacteristic;Z)Z",
604        &[JValue::object(characteristic), JValue::bool(enable)],
605    )?;
606
607    let cccd = uuid(env, "00002902-0000-1000-8000-00805f9b34fb")?;
608    let descriptor = call_object(
609        env,
610        characteristic,
611        "getDescriptor",
612        "(Ljava/util/UUID;)Landroid/bluetooth/BluetoothGattDescriptor;",
613        &[JValue::object(cccd)],
614    )?;
615    if descriptor.is_null() {
616        // No CCCD: local delivery is on, but the peer will send nothing.
617        return Ok(false);
618    }
619
620    let value: &[u8] = match (enable, indicate) {
621        (false, _) => &[0x00, 0x00],
622        (true, false) => &[0x01, 0x00],
623        (true, true) => &[0x02, 0x00],
624    };
625    write_descriptor(env, gatt, descriptor, value)
626}
627
628pub fn read_descriptor(env: Env, gatt: JObject, descriptor: JObject) -> Result<bool> {
629    call_bool(
630        env,
631        gatt,
632        "readDescriptor",
633        "(Landroid/bluetooth/BluetoothGattDescriptor;)Z",
634        &[JValue::object(descriptor)],
635    )
636}
637
638pub fn write_descriptor(
639    env: Env,
640    gatt: JObject,
641    descriptor: JObject,
642    value: &[u8],
643) -> Result<bool> {
644    let bytes = env.new_byte_array(value);
645
646    // API 33+ takes the value directly.
647    if let Some(method) = env.method_id(
648        env.get_object_class(gatt),
649        "writeDescriptor",
650        "(Landroid/bluetooth/BluetoothGattDescriptor;[B)I",
651    ) {
652        let status = env.call_int(
653            gatt,
654            method,
655            &[JValue::object(descriptor), JValue::object(bytes)],
656        );
657        return Ok(status == GATT_SUCCESS);
658    }
659
660    call_bool(
661        env,
662        descriptor,
663        "setValue",
664        "([B)Z",
665        &[JValue::object(bytes)],
666    )?;
667    call_bool(
668        env,
669        gatt,
670        "writeDescriptor",
671        "(Landroid/bluetooth/BluetoothGattDescriptor;)Z",
672        &[JValue::object(descriptor)],
673    )
674}
675
676pub fn request_mtu(env: Env, gatt: JObject, mtu: i32) -> Result<bool> {
677    call_bool(env, gatt, "requestMtu", "(I)Z", &[JValue::int(mtu)])
678}
679
680pub fn read_remote_rssi(env: Env, gatt: JObject) -> Result<bool> {
681    call_bool(env, gatt, "readRemoteRssi", "()Z", &[])
682}
683
684/// `BluetoothGatt.requestConnectionPriority(int)`.
685///
686/// A hint: Android asks the controller to re-negotiate the connection
687/// interval, and the peripheral has the final say. `false` means the request
688/// was not even sent — usually because the argument was out of range or the
689/// link is gone.
690pub fn request_connection_priority(env: Env, gatt: JObject, priority: i32) -> Result<bool> {
691    call_bool(
692        env,
693        gatt,
694        "requestConnectionPriority",
695        "(I)Z",
696        &[JValue::int(priority)],
697    )
698}
699
700pub fn disconnect(env: Env, gatt: JObject) -> Result<()> {
701    call_void(env, gatt, "disconnect", "()V", &[])
702}
703
704/// Release the connection's resources.
705///
706/// Android allows a small number of concurrent GATT clients — historically 32,
707/// far fewer in practice — and leaking them is how an app stops being able to
708/// connect at all until it is restarted.
709pub fn close(env: Env, gatt: JObject) -> Result<()> {
710    call_void(env, gatt, "close", "()V", &[])
711}
712
713// ── L2CAP ───────────────────────────────────────────────────────────────────
714
715/// `device.createL2capChannel(psm)` — API 29+.
716pub fn create_l2cap_channel(env: Env, device: JObject, psm: i32) -> Result<JObject> {
717    call_object(
718        env,
719        device,
720        "createL2capChannel",
721        "(I)Landroid/bluetooth/BluetoothSocket;",
722        &[JValue::int(psm)],
723    )
724}
725
726/// `device.createL2capSocket(psm)` for a Bluetooth Classic L2CAP socket.
727#[cfg(feature = "classic-l2cap")]
728pub fn create_classic_l2cap_socket(env: Env, device: JObject, psm: i32) -> Result<JObject> {
729    call_object(
730        env,
731        device,
732        "createL2capSocket",
733        "(I)Landroid/bluetooth/BluetoothSocket;",
734        &[JValue::int(psm)],
735    )
736}
737
738/// `device.createRfcommSocketToServiceRecord(uuid)`.
739#[cfg(feature = "rfcomm")]
740pub fn create_rfcomm_socket(env: Env, device: JObject, service_uuid: &str) -> Result<JObject> {
741    let service_uuid = uuid(env, service_uuid)?;
742    call_object(
743        env,
744        device,
745        "createRfcommSocketToServiceRecord",
746        "(Ljava/util/UUID;)Landroid/bluetooth/BluetoothSocket;",
747        &[JValue::object(service_uuid)],
748    )
749}
750
751pub fn socket_connect(env: Env, socket: JObject) -> Result<()> {
752    call_void(env, socket, "connect", "()V", &[])
753}
754
755pub fn socket_close(env: Env, socket: JObject) -> Result<()> {
756    call_void(env, socket, "close", "()V", &[])
757}
758
759pub fn socket_input_stream(env: Env, socket: JObject) -> Result<JObject> {
760    call_object(
761        env,
762        socket,
763        "getInputStream",
764        "()Ljava/io/InputStream;",
765        &[],
766    )
767}
768
769pub fn socket_output_stream(env: Env, socket: JObject) -> Result<JObject> {
770    call_object(
771        env,
772        socket,
773        "getOutputStream",
774        "()Ljava/io/OutputStream;",
775        &[],
776    )
777}
778
779/// Read once from a `java.io.InputStream`. `Ok(None)` at end of stream.
780pub fn stream_read(env: Env, stream: JObject, buffer: usize) -> Result<Option<Vec<u8>>> {
781    let array = env.new_byte_array(&vec![0u8; buffer]);
782    let n = call_int(env, stream, "read", "([B)I", &[JValue::object(array)])?;
783    if n < 0 {
784        return Ok(None);
785    }
786    let mut bytes = env.byte_array(array).unwrap_or_default();
787    bytes.truncate(n as usize);
788    Ok(Some(bytes))
789}
790
791pub fn stream_write(env: Env, stream: JObject, data: &[u8]) -> Result<()> {
792    let array = env.new_byte_array(data);
793    call_void(env, stream, "write", "([B)V", &[JValue::object(array)])?;
794    call_void(env, stream, "flush", "()V", &[])
795}
796
797// ── Callback objects ────────────────────────────────────────────────────────
798
799/// A generated callback class, instantiated and bound to a sink.
800pub struct Callback {
801    object: Ref,
802}
803
804impl Callback {
805    /// Define the class if needed, make one, and route its events to `sink`.
806    pub fn new(
807        runtime: &Runtime,
808        binary_name: &str,
809        dex: Vec<u8>,
810        natives: &[(&str, &str, *const std::ffi::c_void)],
811        sink: Arc<dyn EventSink>,
812    ) -> Result<Self> {
813        let class = runtime.define_class(binary_name, dex, natives)?;
814        let object = runtime.new_instance(class)?;
815        let env = runtime.env()?;
816        let object = Ref::new(env, object)
817            .ok_or_else(|| Error::ClassLoad(format!("{binary_name} produced a null instance")))?;
818        crate::bluetooth::bind_sink(&object, sink);
819        Ok(Self { object })
820    }
821
822    pub fn as_ptr(&self) -> JObject {
823        self.object.as_ptr()
824    }
825}
826
827impl Drop for Callback {
828    fn drop(&mut self) {
829        crate::bluetooth::unbind_sink(&self.object);
830    }
831}
832
833/// Discard events — useful where a callback is required but nothing listens.
834pub struct Discard;
835
836impl EventSink for Discard {
837    fn emit(&self, _: Event) {}
838}
839
840// ── Peripheral role ─────────────────────────────────────────────────────────
841
842/// `BluetoothGattService.SERVICE_TYPE_PRIMARY` / `_SECONDARY`.
843const SERVICE_TYPE_PRIMARY: i32 = 0;
844const SERVICE_TYPE_SECONDARY: i32 = 1;
845
846/// `BluetoothGattServer.GATT_SUCCESS` and the ATT codes it forwards.
847pub const ATT_SUCCESS: i32 = 0;
848
849/// Map the shared permission bits onto Android's.
850///
851/// Android's constants are not the Bluetooth ones: read is `1` but write is
852/// `16`, with the encrypted variants interleaved between them.
853pub fn permissions_to_android(permissions: u32) -> i32 {
854    const READABLE: u32 = 0x01;
855    const WRITEABLE: u32 = 0x02;
856    const READ_ENCRYPTED: u32 = 0x04;
857    const WRITE_ENCRYPTED: u32 = 0x08;
858
859    let mut out = 0;
860    if permissions & READABLE != 0 {
861        out |= 1; // PERMISSION_READ
862    }
863    if permissions & READ_ENCRYPTED != 0 {
864        out |= 2; // PERMISSION_READ_ENCRYPTED
865    }
866    if permissions & WRITEABLE != 0 {
867        out |= 16; // PERMISSION_WRITE
868    }
869    if permissions & WRITE_ENCRYPTED != 0 {
870        out |= 32; // PERMISSION_WRITE_ENCRYPTED
871    }
872    out
873}
874
875/// `manager.openGattServer(context, callback)`.
876pub fn open_gatt_server(env: Env, runtime: &Runtime, callback: JObject) -> Result<JObject> {
877    let context_class = env
878        .find_class("android/content/Context")
879        .ok_or_else(|| Error::MissingClass("android.content.Context".into()))?;
880    let field = env
881        .static_field_id(context_class, "BLUETOOTH_SERVICE", "Ljava/lang/String;")
882        .ok_or_else(|| missing("Context.BLUETOOTH_SERVICE"))?;
883    let name = env.static_object_field(context_class, field);
884    let manager = call_object(
885        env,
886        runtime.context(),
887        "getSystemService",
888        "(Ljava/lang/String;)Ljava/lang/Object;",
889        &[JValue::object(name)],
890    )?;
891    call_object(
892        env,
893        manager,
894        "openGattServer",
895        "(Landroid/content/Context;Landroid/bluetooth/BluetoothGattServerCallback;)Landroid/bluetooth/BluetoothGattServer;",
896        &[JValue::object(runtime.context()), JValue::object(callback)],
897    )
898}
899
900/// `new BluetoothGattService(uuid, primary ? PRIMARY : SECONDARY)`.
901pub fn new_service(env: Env, canonical: &str, primary: bool) -> Result<JObject> {
902    let class = env
903        .find_class("android/bluetooth/BluetoothGattService")
904        .ok_or_else(|| Error::MissingClass("BluetoothGattService".into()))?;
905    let ctor = env
906        .method_id(class, "<init>", "(Ljava/util/UUID;I)V")
907        .ok_or_else(|| missing("BluetoothGattService.<init>"))?;
908    let uuid = uuid(env, canonical)?;
909    let kind = if primary {
910        SERVICE_TYPE_PRIMARY
911    } else {
912        SERVICE_TYPE_SECONDARY
913    };
914    Ok(env.new_object(class, ctor, &[JValue::object(uuid), JValue::int(kind)]))
915}
916
917/// `new BluetoothGattCharacteristic(uuid, properties, permissions)`.
918pub fn new_characteristic(
919    env: Env,
920    canonical: &str,
921    properties: u32,
922    permissions: u32,
923) -> Result<JObject> {
924    let class = env
925        .find_class("android/bluetooth/BluetoothGattCharacteristic")
926        .ok_or_else(|| Error::MissingClass("BluetoothGattCharacteristic".into()))?;
927    let ctor = env
928        .method_id(class, "<init>", "(Ljava/util/UUID;II)V")
929        .ok_or_else(|| missing("BluetoothGattCharacteristic.<init>"))?;
930    let uuid = uuid(env, canonical)?;
931    Ok(env.new_object(
932        class,
933        ctor,
934        &[
935            JValue::object(uuid),
936            // Android's PROPERTY_* are the Bluetooth bits, unlike its
937            // permissions.
938            JValue::int(properties as i32),
939            JValue::int(permissions_to_android(permissions)),
940        ],
941    ))
942}
943
944/// `new BluetoothGattDescriptor(uuid, permissions)`.
945pub fn new_descriptor(env: Env, canonical: &str, permissions: u32) -> Result<JObject> {
946    let class = env
947        .find_class("android/bluetooth/BluetoothGattDescriptor")
948        .ok_or_else(|| Error::MissingClass("BluetoothGattDescriptor".into()))?;
949    let ctor = env
950        .method_id(class, "<init>", "(Ljava/util/UUID;I)V")
951        .ok_or_else(|| missing("BluetoothGattDescriptor.<init>"))?;
952    let uuid = uuid(env, canonical)?;
953    Ok(env.new_object(
954        class,
955        ctor,
956        &[
957            JValue::object(uuid),
958            JValue::int(permissions_to_android(permissions)),
959        ],
960    ))
961}
962
963pub fn service_add_characteristic(
964    env: Env,
965    service: JObject,
966    characteristic: JObject,
967) -> Result<bool> {
968    call_bool(
969        env,
970        service,
971        "addCharacteristic",
972        "(Landroid/bluetooth/BluetoothGattCharacteristic;)Z",
973        &[JValue::object(characteristic)],
974    )
975}
976
977pub fn characteristic_add_descriptor(
978    env: Env,
979    characteristic: JObject,
980    descriptor: JObject,
981) -> Result<bool> {
982    call_bool(
983        env,
984        characteristic,
985        "addDescriptor",
986        "(Landroid/bluetooth/BluetoothGattDescriptor;)Z",
987        &[JValue::object(descriptor)],
988    )
989}
990
991pub fn set_value(env: Env, attribute: JObject, value: &[u8]) -> Result<bool> {
992    let bytes = env.new_byte_array(value);
993    call_bool(
994        env,
995        attribute,
996        "setValue",
997        "([B)Z",
998        &[JValue::object(bytes)],
999    )
1000}
1001
1002pub fn server_add_service(env: Env, server: JObject, service: JObject) -> Result<bool> {
1003    call_bool(
1004        env,
1005        server,
1006        "addService",
1007        "(Landroid/bluetooth/BluetoothGattService;)Z",
1008        &[JValue::object(service)],
1009    )
1010}
1011
1012pub fn server_remove_service(env: Env, server: JObject, service: JObject) -> Result<bool> {
1013    call_bool(
1014        env,
1015        server,
1016        "removeService",
1017        "(Landroid/bluetooth/BluetoothGattService;)Z",
1018        &[JValue::object(service)],
1019    )
1020}
1021
1022pub fn server_clear_services(env: Env, server: JObject) -> Result<()> {
1023    call_void(env, server, "clearServices", "()V", &[])
1024}
1025
1026pub fn server_close(env: Env, server: JObject) -> Result<()> {
1027    call_void(env, server, "close", "()V", &[])
1028}
1029
1030/// `server.sendResponse(device, requestId, status, offset, value)`.
1031///
1032/// Every request that asked for a response must get exactly one, or the central
1033/// stalls until the ATT timeout.
1034pub fn server_send_response(
1035    env: Env,
1036    server: JObject,
1037    device: JObject,
1038    request_id: i32,
1039    status: i32,
1040    offset: i32,
1041    value: &[u8],
1042) -> Result<bool> {
1043    let bytes = env.new_byte_array(value);
1044    call_bool(
1045        env,
1046        server,
1047        "sendResponse",
1048        "(Landroid/bluetooth/BluetoothDevice;III[B)Z",
1049        &[
1050            JValue::object(device),
1051            JValue::int(request_id),
1052            JValue::int(status),
1053            JValue::int(offset),
1054            JValue::object(bytes),
1055        ],
1056    )
1057}
1058
1059/// Push a value to one subscriber.
1060///
1061/// API 33 takes the bytes directly and returns a status; older releases want
1062/// the value set on the characteristic first. Both are tried, newest first.
1063pub fn server_notify(
1064    env: Env,
1065    server: JObject,
1066    device: JObject,
1067    characteristic: JObject,
1068    confirm: bool,
1069    value: &[u8],
1070) -> Result<bool> {
1071    let bytes = env.new_byte_array(value);
1072
1073    if let Some(method) = env.method_id(
1074        env.get_object_class(server),
1075        "notifyCharacteristicChanged",
1076        "(Landroid/bluetooth/BluetoothDevice;Landroid/bluetooth/BluetoothGattCharacteristic;Z[B)I",
1077    ) {
1078        let status = env.call_int(
1079            server,
1080            method,
1081            &[
1082                JValue::object(device),
1083                JValue::object(characteristic),
1084                JValue::bool(confirm),
1085                JValue::object(bytes),
1086            ],
1087        );
1088        return Ok(status == ATT_SUCCESS);
1089    }
1090
1091    set_value(env, characteristic, value)?;
1092    call_bool(
1093        env,
1094        server,
1095        "notifyCharacteristicChanged",
1096        "(Landroid/bluetooth/BluetoothDevice;Landroid/bluetooth/BluetoothGattCharacteristic;Z)Z",
1097        &[
1098            JValue::object(device),
1099            JValue::object(characteristic),
1100            JValue::bool(confirm),
1101        ],
1102    )
1103}
1104
1105/// The centrals connected to the GATT server.
1106pub fn server_connected_devices(env: Env, runtime: &Runtime) -> Result<JObject> {
1107    let context_class = env
1108        .find_class("android/content/Context")
1109        .ok_or_else(|| Error::MissingClass("android.content.Context".into()))?;
1110    let field = env
1111        .static_field_id(context_class, "BLUETOOTH_SERVICE", "Ljava/lang/String;")
1112        .ok_or_else(|| missing("Context.BLUETOOTH_SERVICE"))?;
1113    let name = env.static_object_field(context_class, field);
1114    let manager = call_object(
1115        env,
1116        runtime.context(),
1117        "getSystemService",
1118        "(Ljava/lang/String;)Ljava/lang/Object;",
1119        &[JValue::object(name)],
1120    )?;
1121    // BluetoothProfile.GATT_SERVER == 8
1122    call_object(
1123        env,
1124        manager,
1125        "getConnectedDevices",
1126        "(I)Ljava/util/List;",
1127        &[JValue::int(8)],
1128    )
1129}
1130
1131pub fn device_address(env: Env, device: JObject) -> Option<String> {
1132    let s = call_object(env, device, "getAddress", "()Ljava/lang/String;", &[]).ok()?;
1133    env.get_string(s)
1134}
1135
1136#[cfg(feature = "classic")]
1137pub fn start_classic_discovery(env: Env, adapter: JObject) -> Result<()> {
1138    if call_bool(env, adapter, "startDiscovery", "()Z", &[])? {
1139        Ok(())
1140    } else {
1141        Err(Error::MissingMethod(
1142            "BluetoothAdapter.startDiscovery returned false".into(),
1143        ))
1144    }
1145}
1146
1147#[cfg(feature = "classic")]
1148pub fn cancel_classic_discovery(env: Env, adapter: JObject) -> Result<()> {
1149    call_bool(env, adapter, "cancelDiscovery", "()Z", &[]).map(|_| ())
1150}
1151
1152#[cfg(feature = "classic")]
1153pub fn classic_discovery_filter(env: Env) -> Result<JObject> {
1154    let class = env
1155        .find_class("android/content/IntentFilter")
1156        .ok_or_else(|| Error::MissingClass("android.content.IntentFilter".into()))?;
1157    let ctor = env
1158        .method_id(class, "<init>", "()V")
1159        .ok_or_else(|| missing("IntentFilter.<init>"))?;
1160    let filter = env.new_object(class, ctor, &[]);
1161    for action in [
1162        "android.bluetooth.device.action.FOUND",
1163        "android.bluetooth.adapter.action.DISCOVERY_STARTED",
1164        "android.bluetooth.adapter.action.DISCOVERY_FINISHED",
1165    ] {
1166        let action = env.new_string(action);
1167        call_void(
1168            env,
1169            filter,
1170            "addAction",
1171            "(Ljava/lang/String;)V",
1172            &[JValue::object(action)],
1173        )?;
1174    }
1175    Ok(filter)
1176}
1177
1178#[cfg(feature = "classic")]
1179pub fn register_classic_receiver(env: Env, receiver: JObject, filter: JObject) -> Result<()> {
1180    call_object(
1181        env,
1182        Runtime::get().ok_or(Error::NoContext)?.context(),
1183        "registerReceiver",
1184        "(Landroid/content/BroadcastReceiver;Landroid/content/IntentFilter;)Landroid/content/Intent;",
1185        &[JValue::object(receiver), JValue::object(filter)],
1186    )
1187    .map(|_| ())
1188}
1189
1190#[cfg(feature = "classic")]
1191pub fn unregister_classic_receiver(env: Env, receiver: JObject) -> Result<()> {
1192    call_void(
1193        env,
1194        Runtime::get().ok_or(Error::NoContext)?.context(),
1195        "unregisterReceiver",
1196        "(Landroid/content/BroadcastReceiver;)V",
1197        &[JValue::object(receiver)],
1198    )
1199}
1200
1201// ── Advertising ─────────────────────────────────────────────────────────────
1202
1203/// Start advertising.
1204///
1205/// Android will not put an arbitrary name in the payload: `AdvertiseData` only
1206/// offers `setIncludeDeviceName`, which uses the *adapter's* name. Changing
1207/// that means `BluetoothAdapter.setName`, which is global to the device — so
1208/// [`Advertising::local_name`] is honoured by including the device name, not by
1209/// overriding it.
1210///
1211/// [`Advertising::local_name`]: crate::ble
1212pub fn start_advertising(
1213    env: Env,
1214    advertiser: JObject,
1215    callback: JObject,
1216    include_name: bool,
1217    service_uuids: &[String],
1218    connectable: bool,
1219    mode: i32,
1220) -> Result<()> {
1221    let settings = build_advertise_settings(env, connectable, mode)?;
1222    let data = build_advertise_data(env, include_name, service_uuids)?;
1223    call_void(
1224        env,
1225        advertiser,
1226        "startAdvertising",
1227        concat!(
1228            "(Landroid/bluetooth/le/AdvertiseSettings;",
1229            "Landroid/bluetooth/le/AdvertiseData;",
1230            "Landroid/bluetooth/le/AdvertiseCallback;)V"
1231        ),
1232        &[
1233            JValue::object(settings),
1234            JValue::object(data),
1235            JValue::object(callback),
1236        ],
1237    )
1238}
1239
1240pub fn stop_advertising(env: Env, advertiser: JObject, callback: JObject) -> Result<()> {
1241    call_void(
1242        env,
1243        advertiser,
1244        "stopAdvertising",
1245        "(Landroid/bluetooth/le/AdvertiseCallback;)V",
1246        &[JValue::object(callback)],
1247    )
1248}
1249
1250/// `AdvertiseSettings` mode for a preferred maximum interval: low latency
1251/// (~100 ms), balanced (~250 ms) or low power (~1 s).
1252pub fn advertise_mode(max_interval: Option<std::time::Duration>) -> i32 {
1253    match max_interval.map(|d| d.as_millis()) {
1254        None => 2,
1255        Some(ms) if ms <= 175 => 2,
1256        Some(ms) if ms <= 500 => 1,
1257        Some(_) => 0,
1258    }
1259}
1260
1261fn build_advertise_settings(env: Env, connectable: bool, mode: i32) -> Result<JObject> {
1262    let class = env
1263        .find_class("android/bluetooth/le/AdvertiseSettings$Builder")
1264        .ok_or_else(|| Error::MissingClass("AdvertiseSettings.Builder".into()))?;
1265    let ctor = env
1266        .method_id(class, "<init>", "()V")
1267        .ok_or_else(|| missing("AdvertiseSettings.Builder.<init>"))?;
1268    let builder = env.new_object(class, ctor, &[]);
1269
1270    // ADVERTISE_MODE_LOW_LATENCY = 2 by default: a peripheral is meant to be
1271    // found. See `advertise_mode`.
1272    call_object(
1273        env,
1274        builder,
1275        "setAdvertiseMode",
1276        "(I)Landroid/bluetooth/le/AdvertiseSettings$Builder;",
1277        &[JValue::int(mode)],
1278    )?;
1279    call_object(
1280        env,
1281        builder,
1282        "setConnectable",
1283        "(Z)Landroid/bluetooth/le/AdvertiseSettings$Builder;",
1284        &[JValue::bool(connectable)],
1285    )?;
1286    call_object(
1287        env,
1288        builder,
1289        "build",
1290        "()Landroid/bluetooth/le/AdvertiseSettings;",
1291        &[],
1292    )
1293}
1294
1295fn build_advertise_data(env: Env, include_name: bool, service_uuids: &[String]) -> Result<JObject> {
1296    let class = env
1297        .find_class("android/bluetooth/le/AdvertiseData$Builder")
1298        .ok_or_else(|| Error::MissingClass("AdvertiseData.Builder".into()))?;
1299    let ctor = env
1300        .method_id(class, "<init>", "()V")
1301        .ok_or_else(|| missing("AdvertiseData.Builder.<init>"))?;
1302    let builder = env.new_object(class, ctor, &[]);
1303
1304    call_object(
1305        env,
1306        builder,
1307        "setIncludeDeviceName",
1308        "(Z)Landroid/bluetooth/le/AdvertiseData$Builder;",
1309        &[JValue::bool(include_name)],
1310    )?;
1311    for canonical in service_uuids {
1312        let parcel = parcel_uuid(env, canonical)?;
1313        call_object(
1314            env,
1315            builder,
1316            "addServiceUuid",
1317            "(Landroid/os/ParcelUuid;)Landroid/bluetooth/le/AdvertiseData$Builder;",
1318            &[JValue::object(parcel)],
1319        )?;
1320    }
1321    call_object(
1322        env,
1323        builder,
1324        "build",
1325        "()Landroid/bluetooth/le/AdvertiseData;",
1326        &[],
1327    )
1328}
1329
1330// ── L2CAP, listening side ───────────────────────────────────────────────────
1331
1332/// `adapter.listenUsingRfcommWithServiceRecord(name, uuid)`.
1333pub fn listen_rfcomm(
1334    env: Env,
1335    adapter: JObject,
1336    name: &str,
1337    service_uuid: &str,
1338) -> Result<JObject> {
1339    let service_uuid = uuid(env, service_uuid)?;
1340    let name = env.new_string(name);
1341    call_object(
1342        env,
1343        adapter,
1344        "listenUsingRfcommWithServiceRecord",
1345        "(Ljava/lang/String;Ljava/util/UUID;)Landroid/bluetooth/BluetoothServerSocket;",
1346        &[JValue::object(name), JValue::object(service_uuid)],
1347    )
1348}
1349
1350/// `adapter.listenUsingInsecureL2capChannel()` — API 29+.
1351///
1352/// Returns a `BluetoothServerSocket`; its PSM is assigned by the system and
1353/// read back with `getPsm()`.
1354pub fn listen_l2cap(env: Env, adapter: JObject, secure: bool) -> Result<JObject> {
1355    let name = if secure {
1356        "listenUsingL2capChannel"
1357    } else {
1358        "listenUsingInsecureL2capChannel"
1359    };
1360    call_object(
1361        env,
1362        adapter,
1363        name,
1364        "()Landroid/bluetooth/BluetoothServerSocket;",
1365        &[],
1366    )
1367}
1368
1369pub fn server_socket_psm(env: Env, socket: JObject) -> Result<i32> {
1370    call_int(env, socket, "getPsm", "()I", &[])
1371}
1372
1373/// Block until a central connects, then return the accepted socket.
1374pub fn server_socket_accept(env: Env, socket: JObject) -> Result<JObject> {
1375    call_object(
1376        env,
1377        socket,
1378        "accept",
1379        "()Landroid/bluetooth/BluetoothSocket;",
1380        &[],
1381    )
1382}
1383
1384pub fn server_socket_close(env: Env, socket: JObject) -> Result<()> {
1385    call_void(env, socket, "close", "()V", &[])
1386}