Skip to main content

webbluetooth_android/
bluetooth.rs

1//! The Android BLE APIs, reached through JNI.
2//!
3//! Shaped like the other backends' sys layers: an [`Event`] enum, an
4//! [`EventSink`] to receive it, and a `Central` that owns the adapter. What
5//! differs is where the events come from — Android delivers them to callback
6//! *objects*, which is why [`crate::dex`] and [`crate::runtime`] exist.
7//!
8//! # Threading
9//!
10//! Callbacks arrive on binder threads the VM owns but Rust has never seen, so
11//! every entry point attaches, pushes a local frame, and pops it before
12//! returning. Without the frame, a scan that runs for a minute exhausts the
13//! 512-entry local reference table and aborts the process.
14//!
15//! # Permissions
16//!
17//! `BLUETOOTH_SCAN` and `BLUETOOTH_CONNECT` from API 31, and
18//! `ACCESS_FINE_LOCATION` for scanning on 23–30. A missing permission surfaces
19//! as a `SecurityException` from the framework — caught, cleared and reported
20//! rather than left pending.
21
22#![allow(clippy::not_unsafe_ptr_arg_deref)]
23
24use crate::jni::{Env, JObject, JValue};
25use crate::runtime::Runtime;
26use std::ffi::c_void;
27use std::sync::{Arc, Mutex, OnceLock};
28
29/// A retained Java object.
30///
31/// A global reference, so it survives the callback it arrived in and can cross
32/// threads — the Android counterpart of `Retained` on Apple.
33#[derive(Debug)]
34pub struct Ref(JObject);
35
36impl Ref {
37    /// Promote a local reference. `None` if null.
38    pub fn new(env: Env, object: JObject) -> Option<Self> {
39        (!object.is_null()).then(|| Self(env.new_global_ref(object)))
40    }
41
42    pub fn as_ptr(&self) -> JObject {
43        self.0
44    }
45
46    /// A stable identity key.
47    pub fn key(&self) -> usize {
48        self.0 as usize
49    }
50}
51
52impl Clone for Ref {
53    fn clone(&self) -> Self {
54        match Runtime::get().and_then(|r| r.env().ok()) {
55            Some(env) => Self(env.new_global_ref(self.0)),
56            // Without a VM there is nothing to retain; the copy is inert and
57            // the original still owns the reference.
58            None => Self(self.0),
59        }
60    }
61}
62
63impl Drop for Ref {
64    fn drop(&mut self) {
65        if let Some(env) = Runtime::get().and_then(|r| r.env().ok()) {
66            env.delete_global_ref(self.0);
67        }
68    }
69}
70
71unsafe impl Send for Ref {}
72unsafe impl Sync for Ref {}
73
74/// `BluetoothAdapter.STATE_*`, plus the cases that are not adapter states.
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub enum ManagerState {
77    Unknown,
78    Unsupported,
79    Unauthorized,
80    PoweredOff,
81    PoweredOn,
82}
83
84/// What Android tells us.
85#[derive(Debug)]
86pub enum Event {
87    /// A scan result. `record` is the raw advertising payload when Android
88    /// supplies one.
89    Discovered {
90        address: String,
91        name: Option<String>,
92        rssi: i32,
93        service_uuids: Vec<String>,
94        manufacturer_data: Vec<(u16, Vec<u8>)>,
95        service_data: Vec<(String, Vec<u8>)>,
96        class_of_device: Option<u32>,
97        connectable: bool,
98    },
99    ScanFailed {
100        code: i32,
101    },
102    #[cfg(feature = "classic")]
103    ClassicDiscovered {
104        address: String,
105        name: Option<String>,
106        class_of_device: Option<u32>,
107    },
108    #[cfg(feature = "classic")]
109    ClassicDiscoveryFinished,
110    /// `onConnectionStateChange`. `status` is a `GATT_*` code; 0 is success.
111    ConnectionStateChanged {
112        gatt: Ref,
113        status: i32,
114        connected: bool,
115    },
116    ServicesDiscovered {
117        gatt: Ref,
118        status: i32,
119    },
120    CharacteristicRead {
121        gatt: Ref,
122        characteristic: Ref,
123        value: Vec<u8>,
124        status: i32,
125    },
126    CharacteristicWritten {
127        gatt: Ref,
128        characteristic: Ref,
129        status: i32,
130    },
131    /// A subscription delivering a value.
132    CharacteristicChanged {
133        gatt: Ref,
134        characteristic: Ref,
135        value: Vec<u8>,
136    },
137    DescriptorRead {
138        gatt: Ref,
139        descriptor: Ref,
140        value: Vec<u8>,
141        status: i32,
142    },
143    DescriptorWritten {
144        gatt: Ref,
145        descriptor: Ref,
146        status: i32,
147    },
148    /// The link's PHY, as reported by `onPhyUpdate` or `onPhyRead`.
149    ///
150    /// One event for both because they carry the same thing and a caller only
151    /// ever has one outstanding: the difference is whether it was asked to
152    /// change or merely to report.
153    PhyChanged {
154        gatt: Ref,
155        tx: i32,
156        rx: i32,
157        status: i32,
158    },
159    MtuChanged {
160        gatt: Ref,
161        mtu: i32,
162        status: i32,
163    },
164    RssiRead {
165        gatt: Ref,
166        rssi: i32,
167        status: i32,
168    },
169    /// The peer's attribute table changed; every handle into it is stale.
170    ServicesChanged {
171        gatt: Ref,
172    },
173
174    // ── Peripheral role ─────────────────────────────────────────────────────
175    ServerConnectionStateChanged {
176        device: Ref,
177        connected: bool,
178    },
179    ServiceAdded {
180        status: i32,
181    },
182    ReadRequest {
183        device: Ref,
184        request_id: i32,
185        offset: i32,
186        characteristic: Ref,
187    },
188    WriteRequest {
189        device: Ref,
190        request_id: i32,
191        characteristic: Ref,
192        prepared: bool,
193        response_needed: bool,
194        offset: i32,
195        value: Vec<u8>,
196    },
197    DescriptorReadRequest {
198        device: Ref,
199        request_id: i32,
200        offset: i32,
201        descriptor: Ref,
202    },
203    DescriptorWriteRequest {
204        device: Ref,
205        request_id: i32,
206        descriptor: Ref,
207        response_needed: bool,
208        offset: i32,
209        value: Vec<u8>,
210    },
211    NotificationSent {
212        device: Ref,
213        status: i32,
214    },
215    AdvertisingStarted {
216        error: Option<i32>,
217    },
218}
219
220/// Where events go. Called on a binder thread, one at a time per callback.
221pub trait EventSink: Send + Sync {
222    fn emit(&self, event: Event);
223}
224
225// ── Sink registry, keyed by callback object ─────────────────────────────────
226
227/// Registered sinks, each with the global reference identifying its callback.
228///
229/// **Not a map keyed by pointer.** A JNI reference is a handle, not an
230/// address: the local reference a native method is handed and the global
231/// reference held here denote the same object through different pointers, so
232/// looking one up by the other's value never matches. `IsSameObject` is the
233/// only way to ask whether two references mean the same object, which is why
234/// this is a list that gets walked rather than a `HashMap`. There are a
235/// handful of callbacks per connection, so walking it costs nothing.
236type Sinks = Vec<(Ref, Arc<dyn EventSink>)>;
237
238static SINKS: OnceLock<Mutex<Sinks>> = OnceLock::new();
239
240fn sinks() -> &'static Mutex<Sinks> {
241    SINKS.get_or_init(|| Mutex::new(Vec::new()))
242}
243
244/// Register a sink for a callback object.
245pub fn bind_sink(callback: &Ref, sink: Arc<dyn EventSink>) {
246    let mut sinks = sinks().lock().unwrap();
247    sinks.retain(|(existing, _)| existing.key() != callback.key());
248    sinks.push((callback.clone(), sink));
249}
250
251pub fn unbind_sink(callback: &Ref) {
252    sinks()
253        .lock()
254        .unwrap()
255        .retain(|(existing, _)| existing.key() != callback.key());
256}
257
258/// Deliver an event to whichever sink owns `this`.
259fn emit(env: Env, this: JObject, event: Event) {
260    let sink = sinks().lock().ok().and_then(|sinks| {
261        sinks
262            .iter()
263            .find(|(callback, _)| env.is_same_object(this, callback.as_ptr()))
264            .map(|(_, sink)| sink.clone())
265    });
266    if let Some(sink) = sink {
267        sink.emit(event);
268    }
269}
270
271/// Run a callback body with an attached env and a local frame.
272///
273/// Every native below goes through this: attaching is required because the
274/// thread is the VM's, and the frame is required because the callback may run
275/// thousands of times.
276fn in_callback(env: Env, body: impl FnOnce(Env)) {
277    if !env.push_local_frame(32) {
278        return;
279    }
280    body(env);
281    env.pop_local_frame();
282}
283
284// ── BluetoothGattCallback ───────────────────────────────────────────────────
285
286unsafe extern "C" fn on_connection_state_change(
287    env: Env,
288    this: JObject,
289    gatt: JObject,
290    status: i32,
291    new_state: i32,
292) {
293    in_callback(env, |env| {
294        let Some(gatt) = Ref::new(env, gatt) else {
295            return;
296        };
297        // BluetoothProfile.STATE_CONNECTED == 2
298        emit(
299            env,
300            this,
301            Event::ConnectionStateChanged {
302                gatt,
303                status,
304                connected: new_state == 2,
305            },
306        );
307    });
308}
309
310unsafe extern "C" fn on_services_discovered(env: Env, this: JObject, gatt: JObject, status: i32) {
311    in_callback(env, |env| {
312        let Some(gatt) = Ref::new(env, gatt) else {
313            return;
314        };
315        emit(env, this, Event::ServicesDiscovered { gatt, status });
316    });
317}
318
319unsafe extern "C" fn on_characteristic_read(
320    env: Env,
321    this: JObject,
322    gatt: JObject,
323    characteristic: JObject,
324    value: JObject,
325    status: i32,
326) {
327    in_callback(env, |env| {
328        let (Some(gatt), Some(characteristic)) =
329            (Ref::new(env, gatt), Ref::new(env, characteristic))
330        else {
331            return;
332        };
333        let value = env.byte_array(value).unwrap_or_default();
334        emit(
335            env,
336            this,
337            Event::CharacteristicRead {
338                gatt,
339                characteristic,
340                value,
341                status,
342            },
343        );
344    });
345}
346
347unsafe extern "C" fn on_characteristic_write(
348    env: Env,
349    this: JObject,
350    gatt: JObject,
351    characteristic: JObject,
352    status: i32,
353) {
354    in_callback(env, |env| {
355        let (Some(gatt), Some(characteristic)) =
356            (Ref::new(env, gatt), Ref::new(env, characteristic))
357        else {
358            return;
359        };
360        emit(
361            env,
362            this,
363            Event::CharacteristicWritten {
364                gatt,
365                characteristic,
366                status,
367            },
368        );
369    });
370}
371
372unsafe extern "C" fn on_characteristic_changed(
373    env: Env,
374    this: JObject,
375    gatt: JObject,
376    characteristic: JObject,
377    value: JObject,
378) {
379    in_callback(env, |env| {
380        let (Some(gatt), Some(characteristic)) =
381            (Ref::new(env, gatt), Ref::new(env, characteristic))
382        else {
383            return;
384        };
385        let value = env.byte_array(value).unwrap_or_default();
386        emit(
387            env,
388            this,
389            Event::CharacteristicChanged {
390                gatt,
391                characteristic,
392                value,
393            },
394        );
395    });
396}
397
398unsafe extern "C" fn on_descriptor_read(
399    env: Env,
400    this: JObject,
401    gatt: JObject,
402    descriptor: JObject,
403    status: i32,
404    value: JObject,
405) {
406    in_callback(env, |env| {
407        let (Some(gatt), Some(descriptor)) = (Ref::new(env, gatt), Ref::new(env, descriptor))
408        else {
409            return;
410        };
411        let value = env.byte_array(value).unwrap_or_default();
412        emit(
413            env,
414            this,
415            Event::DescriptorRead {
416                gatt,
417                descriptor,
418                value,
419                status,
420            },
421        );
422    });
423}
424
425unsafe extern "C" fn on_descriptor_write(
426    env: Env,
427    this: JObject,
428    gatt: JObject,
429    descriptor: JObject,
430    status: i32,
431) {
432    in_callback(env, |env| {
433        let (Some(gatt), Some(descriptor)) = (Ref::new(env, gatt), Ref::new(env, descriptor))
434        else {
435            return;
436        };
437        emit(
438            env,
439            this,
440            Event::DescriptorWritten {
441                gatt,
442                descriptor,
443                status,
444            },
445        );
446    });
447}
448
449unsafe extern "C" fn on_mtu_changed(env: Env, this: JObject, gatt: JObject, mtu: i32, status: i32) {
450    in_callback(env, |env| {
451        let Some(gatt) = Ref::new(env, gatt) else {
452            return;
453        };
454        emit(env, this, Event::MtuChanged { gatt, mtu, status });
455    });
456}
457
458unsafe extern "C" fn on_phy_update(
459    env: Env,
460    this: JObject,
461    gatt: JObject,
462    tx: i32,
463    rx: i32,
464    status: i32,
465) {
466    in_callback(env, |env| {
467        let Some(gatt) = Ref::new(env, gatt) else {
468            return;
469        };
470        emit(
471            env,
472            this,
473            Event::PhyChanged {
474                gatt,
475                tx,
476                rx,
477                status,
478            },
479        );
480    });
481}
482
483unsafe extern "C" fn on_phy_read(
484    env: Env,
485    this: JObject,
486    gatt: JObject,
487    tx: i32,
488    rx: i32,
489    status: i32,
490) {
491    in_callback(env, |env| {
492        let Some(gatt) = Ref::new(env, gatt) else {
493            return;
494        };
495        emit(
496            env,
497            this,
498            Event::PhyChanged {
499                gatt,
500                tx,
501                rx,
502                status,
503            },
504        );
505    });
506}
507
508unsafe extern "C" fn on_read_remote_rssi(
509    env: Env,
510    this: JObject,
511    gatt: JObject,
512    rssi: i32,
513    status: i32,
514) {
515    in_callback(env, |env| {
516        let Some(gatt) = Ref::new(env, gatt) else {
517            return;
518        };
519        emit(env, this, Event::RssiRead { gatt, rssi, status });
520    });
521}
522
523unsafe extern "C" fn on_service_changed(env: Env, this: JObject, gatt: JObject) {
524    in_callback(env, |env| {
525        let Some(gatt) = Ref::new(env, gatt) else {
526            return;
527        };
528        emit(env, this, Event::ServicesChanged { gatt });
529    });
530}
531
532/// The `(name, signature, function)` table for `GattCallback`.
533///
534/// These must match [`crate::gatt_callback_dex`] exactly — `RegisterNatives`
535/// checks the name and signature against the class, so a mismatch fails loudly
536/// at registration rather than quietly at the first call.
537pub fn gatt_natives() -> Vec<(&'static str, &'static str, *const c_void)> {
538    const GATT: &str = "Landroid/bluetooth/BluetoothGatt;";
539    const CHAR: &str = "Landroid/bluetooth/BluetoothGattCharacteristic;";
540    const DESC: &str = "Landroid/bluetooth/BluetoothGattDescriptor;";
541    vec![
542        (
543            "onConnectionStateChange",
544            concat!("(", "Landroid/bluetooth/BluetoothGatt;", "II)V"),
545            on_connection_state_change as *const c_void,
546        ),
547        (
548            "onServicesDiscovered",
549            concat!("(", "Landroid/bluetooth/BluetoothGatt;", "I)V"),
550            on_services_discovered as *const c_void,
551        ),
552        (
553            "onCharacteristicRead",
554            concat!(
555                "(Landroid/bluetooth/BluetoothGatt;",
556                "Landroid/bluetooth/BluetoothGattCharacteristic;[BI)V"
557            ),
558            on_characteristic_read as *const c_void,
559        ),
560        (
561            "onCharacteristicWrite",
562            concat!(
563                "(Landroid/bluetooth/BluetoothGatt;",
564                "Landroid/bluetooth/BluetoothGattCharacteristic;I)V"
565            ),
566            on_characteristic_write as *const c_void,
567        ),
568        (
569            "onCharacteristicChanged",
570            concat!(
571                "(Landroid/bluetooth/BluetoothGatt;",
572                "Landroid/bluetooth/BluetoothGattCharacteristic;[B)V"
573            ),
574            on_characteristic_changed as *const c_void,
575        ),
576        (
577            "onDescriptorRead",
578            concat!(
579                "(Landroid/bluetooth/BluetoothGatt;",
580                "Landroid/bluetooth/BluetoothGattDescriptor;I[B)V"
581            ),
582            on_descriptor_read as *const c_void,
583        ),
584        (
585            "onDescriptorWrite",
586            concat!(
587                "(Landroid/bluetooth/BluetoothGatt;",
588                "Landroid/bluetooth/BluetoothGattDescriptor;I)V"
589            ),
590            on_descriptor_write as *const c_void,
591        ),
592        (
593            "onMtuChanged",
594            "(Landroid/bluetooth/BluetoothGatt;II)V",
595            on_mtu_changed as *const c_void,
596        ),
597        (
598            "onPhyUpdate",
599            "(Landroid/bluetooth/BluetoothGatt;III)V",
600            on_phy_update as *const c_void,
601        ),
602        (
603            "onPhyRead",
604            "(Landroid/bluetooth/BluetoothGatt;III)V",
605            on_phy_read as *const c_void,
606        ),
607        (
608            "onReadRemoteRssi",
609            "(Landroid/bluetooth/BluetoothGatt;II)V",
610            on_read_remote_rssi as *const c_void,
611        ),
612        (
613            "onServiceChanged",
614            "(Landroid/bluetooth/BluetoothGatt;)V",
615            on_service_changed as *const c_void,
616        ),
617        // Referencing the constants keeps them beside the signatures above.
618        ("", GATT, std::ptr::null()),
619        ("", CHAR, std::ptr::null()),
620        ("", DESC, std::ptr::null()),
621    ]
622    .into_iter()
623    .filter(|(name, _, _)| !name.is_empty())
624    .collect()
625}
626
627// ── ScanCallback ────────────────────────────────────────────────────────────
628
629unsafe extern "C" fn on_scan_result(env: Env, this: JObject, _type: i32, result: JObject) {
630    in_callback(env, |env| {
631        if let Some(event) = read_scan_result(env, result) {
632            emit(env, this, event);
633        }
634    });
635}
636
637unsafe extern "C" fn on_batch_scan_results(env: Env, this: JObject, results: JObject) {
638    in_callback(env, |env| {
639        // java.util.List, so size()/get(int).
640        let Some(list) = env.find_class("java/util/List") else {
641            return;
642        };
643        let (Some(size), Some(get)) = (
644            env.method_id(list, "size", "()I"),
645            env.method_id(list, "get", "(I)Ljava/lang/Object;"),
646        ) else {
647            return;
648        };
649        let count = env.call_int(results, size, &[]);
650        for i in 0..count {
651            let item = env.call_object(results, get, &[JValue::int(i)]);
652            if let Some(event) = read_scan_result(env, item) {
653                emit(env, this, event);
654            }
655        }
656    });
657}
658
659unsafe extern "C" fn on_scan_failed(env: Env, this: JObject, code: i32) {
660    in_callback(env, |env| emit(env, this, Event::ScanFailed { code }));
661}
662
663#[cfg(feature = "classic")]
664unsafe extern "C" fn on_classic_receive(
665    env: Env,
666    this: JObject,
667    _context: JObject,
668    intent: JObject,
669) {
670    in_callback(env, |env| {
671        let Some(action) =
672            crate::ble::call_object(env, intent, "getAction", "()Ljava/lang/String;", &[])
673                .ok()
674                .and_then(|value| env.get_string(value))
675        else {
676            return;
677        };
678        match action.as_str() {
679            "android.bluetooth.adapter.action.DISCOVERY_FINISHED" => {
680                emit(env, this, Event::ClassicDiscoveryFinished)
681            }
682            "android.bluetooth.device.action.FOUND" => {
683                let key = env.new_string("android.bluetooth.device.extra.DEVICE");
684                let device = crate::ble::call_object(
685                    env,
686                    intent,
687                    "getParcelableExtra",
688                    "(Ljava/lang/String;)Landroid/os/Parcelable;",
689                    &[JValue::object(key)],
690                )
691                .unwrap_or(std::ptr::null_mut());
692                if device.is_null() {
693                    return;
694                }
695                let address = crate::ble::device_address(env, device);
696                let name =
697                    crate::ble::call_object(env, device, "getName", "()Ljava/lang/String;", &[])
698                        .ok()
699                        .and_then(|value| env.get_string(value));
700                let class_of_device = crate::ble::call_object(
701                    env,
702                    device,
703                    "getBluetoothClass",
704                    "()Landroid/bluetooth/BluetoothClass;",
705                    &[],
706                )
707                .ok()
708                .and_then(|class| {
709                    crate::ble::call_int(env, class, "getClassOfDevice", "()I", &[]).ok()
710                })
711                .map(|value| value as u32);
712                if let Some(address) = address {
713                    emit(
714                        env,
715                        this,
716                        Event::ClassicDiscovered {
717                            address,
718                            name,
719                            class_of_device,
720                        },
721                    );
722                }
723            }
724            _ => {}
725        }
726    });
727}
728
729/// Pull an advertisement out of a `ScanResult`.
730fn read_scan_result(env: Env, result: JObject) -> Option<Event> {
731    if result.is_null() {
732        return None;
733    }
734    let result_class = env.get_object_class(result);
735    let get_device = env.method_id(
736        result_class,
737        "getDevice",
738        "()Landroid/bluetooth/BluetoothDevice;",
739    )?;
740    let get_rssi = env.method_id(result_class, "getRssi", "()I")?;
741    let get_record = env.method_id(
742        result_class,
743        "getScanRecord",
744        "()Landroid/bluetooth/le/ScanRecord;",
745    )?;
746
747    let device = env.call_object(result, get_device, &[]);
748    let rssi = env.call_int(result, get_rssi, &[]);
749    let record = env.call_object(result, get_record, &[]);
750
751    let device_class = env.get_object_class(device);
752    let get_address = env.method_id(device_class, "getAddress", "()Ljava/lang/String;")?;
753    let address = env.get_string(env.call_object(device, get_address, &[]))?;
754    let class_of_device = env
755        .method_id(
756            device_class,
757            "getBluetoothClass",
758            "()Landroid/bluetooth/BluetoothClass;",
759        )
760        .and_then(|get_class| {
761            let class = env.call_object(device, get_class, &[]);
762            let class_type = env.get_object_class(class);
763            let value = env.method_id(class_type, "getClassOfDevice", "()I")?;
764            Some(env.call_int(class, value, &[]) as u32)
765        });
766
767    let mut name = None;
768    let mut service_uuids = Vec::new();
769    let mut manufacturer_data = Vec::new();
770    let mut service_data = Vec::new();
771
772    if !record.is_null() {
773        let record_class = env.get_object_class(record);
774        if let Some(get_name) = env.method_id(record_class, "getDeviceName", "()Ljava/lang/String;")
775        {
776            name = env.get_string(env.call_object(record, get_name, &[]));
777        }
778        if let Some(get_uuids) =
779            env.method_id(record_class, "getServiceUuids", "()Ljava/util/List;")
780        {
781            let list = env.call_object(record, get_uuids, &[]);
782            service_uuids = read_uuid_list(env, list);
783        }
784        if let Some(get_manufacturer) = env.method_id(
785            record_class,
786            "getManufacturerSpecificData",
787            "()Landroid/util/SparseArray;",
788        ) {
789            let sparse = env.call_object(record, get_manufacturer, &[]);
790            manufacturer_data = read_sparse_bytes(env, sparse);
791        }
792        if let Some(get_service_data) =
793            env.method_id(record_class, "getServiceData", "()Ljava/util/Map;")
794        {
795            let map = env.call_object(record, get_service_data, &[]);
796            service_data = read_service_data(env, map);
797        }
798    }
799
800    Some(Event::Discovered {
801        address,
802        name,
803        rssi,
804        service_uuids,
805        manufacturer_data,
806        service_data,
807        class_of_device,
808        // Android reports connectability only from API 26 in ScanResult, and
809        // anything reachable through a Device1 handle accepts connections.
810        connectable: true,
811    })
812}
813
814/// A `List<ParcelUuid>` as canonical strings.
815fn read_uuid_list(env: Env, list: JObject) -> Vec<String> {
816    let mut out = Vec::new();
817    if list.is_null() {
818        return out;
819    }
820    let Some(list_class) = env.find_class("java/util/List") else {
821        return out;
822    };
823    let (Some(size), Some(get)) = (
824        env.method_id(list_class, "size", "()I"),
825        env.method_id(list_class, "get", "(I)Ljava/lang/Object;"),
826    ) else {
827        return out;
828    };
829    let count = env.call_int(list, size, &[]);
830    for i in 0..count {
831        let parcel = env.call_object(list, get, &[JValue::int(i)]);
832        if let Some(uuid) = parcel_uuid_to_string(env, parcel) {
833            out.push(uuid);
834        }
835    }
836    out
837}
838
839fn parcel_uuid_to_string(env: Env, parcel: JObject) -> Option<String> {
840    if parcel.is_null() {
841        return None;
842    }
843    let class = env.get_object_class(parcel);
844    let to_string = env.method_id(class, "toString", "()Ljava/lang/String;")?;
845    env.get_string(env.call_object(parcel, to_string, &[]))
846        .map(|s| s.to_ascii_lowercase())
847}
848
849/// A `SparseArray<byte[]>` — manufacturer data, keyed by company identifier.
850fn read_sparse_bytes(env: Env, sparse: JObject) -> Vec<(u16, Vec<u8>)> {
851    let mut out = Vec::new();
852    if sparse.is_null() {
853        return out;
854    }
855    let class = env.get_object_class(sparse);
856    let (Some(size), Some(key_at), Some(value_at)) = (
857        env.method_id(class, "size", "()I"),
858        env.method_id(class, "keyAt", "(I)I"),
859        env.method_id(class, "valueAt", "(I)Ljava/lang/Object;"),
860    ) else {
861        return out;
862    };
863    let count = env.call_int(sparse, size, &[]);
864    for i in 0..count {
865        let key = env.call_int(sparse, key_at, &[JValue::int(i)]);
866        let value = env.call_object(sparse, value_at, &[JValue::int(i)]);
867        if let Some(bytes) = env.byte_array(value) {
868            out.push((key as u16, bytes));
869        }
870    }
871    out
872}
873
874/// A `Map<ParcelUuid, byte[]>`.
875fn read_service_data(env: Env, map: JObject) -> Vec<(String, Vec<u8>)> {
876    let mut out = Vec::new();
877    if map.is_null() {
878        return out;
879    }
880    let Some(map_class) = env.find_class("java/util/Map") else {
881        return out;
882    };
883    let Some(entry_set) = env.method_id(map_class, "entrySet", "()Ljava/util/Set;") else {
884        return out;
885    };
886    let set = env.call_object(map, entry_set, &[]);
887    let Some(set_class) = env.find_class("java/util/Set") else {
888        return out;
889    };
890    let Some(iterator) = env.method_id(set_class, "iterator", "()Ljava/util/Iterator;") else {
891        return out;
892    };
893    let it = env.call_object(set, iterator, &[]);
894    let Some(it_class) = env.find_class("java/util/Iterator") else {
895        return out;
896    };
897    let (Some(has_next), Some(next)) = (
898        env.method_id(it_class, "hasNext", "()Z"),
899        env.method_id(it_class, "next", "()Ljava/lang/Object;"),
900    ) else {
901        return out;
902    };
903    let Some(entry_class) = env.find_class("java/util/Map$Entry") else {
904        return out;
905    };
906    let (Some(get_key), Some(get_value)) = (
907        env.method_id(entry_class, "getKey", "()Ljava/lang/Object;"),
908        env.method_id(entry_class, "getValue", "()Ljava/lang/Object;"),
909    ) else {
910        return out;
911    };
912
913    while env.call_bool(it, has_next, &[]) {
914        let entry = env.call_object(it, next, &[]);
915        let key = env.call_object(entry, get_key, &[]);
916        let value = env.call_object(entry, get_value, &[]);
917        if let (Some(uuid), Some(bytes)) = (parcel_uuid_to_string(env, key), env.byte_array(value))
918        {
919            out.push((uuid, bytes));
920        }
921    }
922    out
923}
924
925// ── BluetoothGattServerCallback ─────────────────────────────────────────────
926
927unsafe extern "C" fn on_server_connection_state_change(
928    env: Env,
929    this: JObject,
930    device: JObject,
931    _status: i32,
932    new_state: i32,
933) {
934    in_callback(env, |env| {
935        let Some(device) = Ref::new(env, device) else {
936            return;
937        };
938        emit(
939            env,
940            this,
941            Event::ServerConnectionStateChanged {
942                device,
943                connected: new_state == 2,
944            },
945        );
946    });
947}
948
949unsafe extern "C" fn on_service_added(env: Env, this: JObject, status: i32, _service: JObject) {
950    in_callback(env, |env| emit(env, this, Event::ServiceAdded { status }));
951}
952
953unsafe extern "C" fn on_characteristic_read_request(
954    env: Env,
955    this: JObject,
956    device: JObject,
957    request_id: i32,
958    offset: i32,
959    characteristic: JObject,
960) {
961    in_callback(env, |env| {
962        let (Some(device), Some(characteristic)) =
963            (Ref::new(env, device), Ref::new(env, characteristic))
964        else {
965            return;
966        };
967        emit(
968            env,
969            this,
970            Event::ReadRequest {
971                device,
972                request_id,
973                offset,
974                characteristic,
975            },
976        );
977    });
978}
979
980unsafe extern "C" fn on_characteristic_write_request(
981    env: Env,
982    this: JObject,
983    device: JObject,
984    request_id: i32,
985    characteristic: JObject,
986    prepared: u8,
987    response_needed: u8,
988    offset: i32,
989    value: JObject,
990) {
991    in_callback(env, |env| {
992        let (Some(device), Some(characteristic)) =
993            (Ref::new(env, device), Ref::new(env, characteristic))
994        else {
995            return;
996        };
997        emit(
998            env,
999            this,
1000            Event::WriteRequest {
1001                device,
1002                request_id,
1003                characteristic,
1004                prepared: prepared != 0,
1005                response_needed: response_needed != 0,
1006                offset,
1007                value: env.byte_array(value).unwrap_or_default(),
1008            },
1009        );
1010    });
1011}
1012
1013unsafe extern "C" fn on_descriptor_read_request(
1014    env: Env,
1015    this: JObject,
1016    device: JObject,
1017    request_id: i32,
1018    offset: i32,
1019    descriptor: JObject,
1020) {
1021    in_callback(env, |env| {
1022        let (Some(device), Some(descriptor)) = (Ref::new(env, device), Ref::new(env, descriptor))
1023        else {
1024            return;
1025        };
1026        emit(
1027            env,
1028            this,
1029            Event::DescriptorReadRequest {
1030                device,
1031                request_id,
1032                offset,
1033                descriptor,
1034            },
1035        );
1036    });
1037}
1038
1039unsafe extern "C" fn on_descriptor_write_request(
1040    env: Env,
1041    this: JObject,
1042    device: JObject,
1043    request_id: i32,
1044    descriptor: JObject,
1045    _prepared: u8,
1046    response_needed: u8,
1047    offset: i32,
1048    value: JObject,
1049) {
1050    in_callback(env, |env| {
1051        let (Some(device), Some(descriptor)) = (Ref::new(env, device), Ref::new(env, descriptor))
1052        else {
1053            return;
1054        };
1055        emit(
1056            env,
1057            this,
1058            Event::DescriptorWriteRequest {
1059                device,
1060                request_id,
1061                descriptor,
1062                response_needed: response_needed != 0,
1063                offset,
1064                value: env.byte_array(value).unwrap_or_default(),
1065            },
1066        );
1067    });
1068}
1069
1070unsafe extern "C" fn on_notification_sent(env: Env, this: JObject, device: JObject, status: i32) {
1071    in_callback(env, |env| {
1072        let Some(device) = Ref::new(env, device) else {
1073            return;
1074        };
1075        emit(env, this, Event::NotificationSent { device, status });
1076    });
1077}
1078
1079unsafe extern "C" fn on_server_mtu_changed(env: Env, this: JObject, _device: JObject, _mtu: i32) {
1080    in_callback(env, |_| {
1081        let _ = this;
1082    });
1083}
1084
1085/// The `(name, signature, function)` table for `BluetoothGattServerCallback`.
1086pub fn server_natives() -> Vec<(&'static str, &'static str, *const c_void)> {
1087    vec![
1088        (
1089            "onConnectionStateChange",
1090            "(Landroid/bluetooth/BluetoothDevice;II)V",
1091            on_server_connection_state_change as *const c_void,
1092        ),
1093        (
1094            "onServiceAdded",
1095            "(ILandroid/bluetooth/BluetoothGattService;)V",
1096            on_service_added as *const c_void,
1097        ),
1098        (
1099            "onCharacteristicReadRequest",
1100            concat!(
1101                "(Landroid/bluetooth/BluetoothDevice;II",
1102                "Landroid/bluetooth/BluetoothGattCharacteristic;)V"
1103            ),
1104            on_characteristic_read_request as *const c_void,
1105        ),
1106        (
1107            "onCharacteristicWriteRequest",
1108            concat!(
1109                "(Landroid/bluetooth/BluetoothDevice;I",
1110                "Landroid/bluetooth/BluetoothGattCharacteristic;ZZI[B)V"
1111            ),
1112            on_characteristic_write_request as *const c_void,
1113        ),
1114        (
1115            "onDescriptorReadRequest",
1116            concat!(
1117                "(Landroid/bluetooth/BluetoothDevice;II",
1118                "Landroid/bluetooth/BluetoothGattDescriptor;)V"
1119            ),
1120            on_descriptor_read_request as *const c_void,
1121        ),
1122        (
1123            "onDescriptorWriteRequest",
1124            concat!(
1125                "(Landroid/bluetooth/BluetoothDevice;I",
1126                "Landroid/bluetooth/BluetoothGattDescriptor;ZZI[B)V"
1127            ),
1128            on_descriptor_write_request as *const c_void,
1129        ),
1130        (
1131            "onNotificationSent",
1132            "(Landroid/bluetooth/BluetoothDevice;I)V",
1133            on_notification_sent as *const c_void,
1134        ),
1135        (
1136            "onMtuChanged",
1137            "(Landroid/bluetooth/BluetoothDevice;I)V",
1138            on_server_mtu_changed as *const c_void,
1139        ),
1140    ]
1141}
1142
1143// ── AdvertiseCallback ───────────────────────────────────────────────────────
1144
1145unsafe extern "C" fn on_start_success(env: Env, this: JObject, _settings: JObject) {
1146    in_callback(env, |env| {
1147        emit(env, this, Event::AdvertisingStarted { error: None })
1148    });
1149}
1150
1151unsafe extern "C" fn on_start_failure(env: Env, this: JObject, code: i32) {
1152    in_callback(env, |env| {
1153        emit(env, this, Event::AdvertisingStarted { error: Some(code) })
1154    });
1155}
1156
1157/// The `(name, signature, function)` table for `AdvertiseCallback`.
1158pub fn advertise_natives() -> Vec<(&'static str, &'static str, *const c_void)> {
1159    vec![
1160        (
1161            "onStartSuccess",
1162            "(Landroid/bluetooth/le/AdvertiseSettings;)V",
1163            on_start_success as *const c_void,
1164        ),
1165        ("onStartFailure", "(I)V", on_start_failure as *const c_void),
1166    ]
1167}
1168
1169/// The `(name, signature, function)` table for `ScanCallback`.
1170pub fn scan_natives() -> Vec<(&'static str, &'static str, *const c_void)> {
1171    vec![
1172        (
1173            "onScanResult",
1174            "(ILandroid/bluetooth/le/ScanResult;)V",
1175            on_scan_result as *const c_void,
1176        ),
1177        (
1178            "onBatchScanResults",
1179            "(Ljava/util/List;)V",
1180            on_batch_scan_results as *const c_void,
1181        ),
1182        ("onScanFailed", "(I)V", on_scan_failed as *const c_void),
1183    ]
1184}
1185
1186#[cfg(feature = "classic")]
1187pub fn classic_discovery_natives() -> Vec<(&'static str, &'static str, *const c_void)> {
1188    vec![(
1189        "onReceive",
1190        "(Landroid/content/Context;Landroid/content/Intent;)V",
1191        on_classic_receive as *const c_void,
1192    )]
1193}
1194
1195#[cfg(test)]
1196mod tests {
1197    use super::*;
1198
1199    /// Every native must match the DEX that declares it, or `RegisterNatives`
1200    /// rejects the whole table.
1201    #[test]
1202    fn native_tables_match_the_generated_dex() {
1203        let gatt = gatt_natives();
1204        // No count here on purpose: the DEX class is generated *from* this
1205        // table, so the two cannot disagree and a number would only be one
1206        // more thing to update. What is still worth asserting is that each
1207        // entry is well formed, because a bad descriptor is what
1208        // `RegisterNatives` actually rejects.
1209        assert!(!gatt.is_empty(), "GattCallback overrides something");
1210        for (name, signature, f) in &gatt {
1211            assert!(!name.is_empty());
1212            assert!(
1213                signature.starts_with('('),
1214                "{name}: {signature} is not a descriptor"
1215            );
1216            assert!(
1217                signature.ends_with(")V"),
1218                "{name}: every callback returns void"
1219            );
1220            assert!(!f.is_null());
1221        }
1222
1223        let scan = scan_natives();
1224        assert_eq!(scan.len(), 3);
1225        for (_, signature, _) in &scan {
1226            assert!(signature.ends_with(")V"));
1227        }
1228
1229        #[cfg(feature = "classic")]
1230        {
1231            let classic = classic_discovery_natives();
1232            assert_eq!(classic.len(), 1);
1233            assert_eq!(classic[0].0, "onReceive");
1234            assert_eq!(
1235                classic[0].1,
1236                "(Landroid/content/Context;Landroid/content/Intent;)V"
1237            );
1238            assert!(!classic[0].2.is_null());
1239        }
1240    }
1241
1242    #[test]
1243    fn the_peripheral_tables_match_their_dex() {
1244        // Eight server overrides and two advertising ones, matching the
1245        // classes `crate::gatt_server_callback_dex` and
1246        // `crate::advertise_callback_dex` declare.
1247        assert_eq!(server_natives().len(), 8);
1248        assert_eq!(advertise_natives().len(), 2);
1249        for (name, signature, f) in server_natives().iter().chain(advertise_natives().iter()) {
1250            assert!(!name.is_empty());
1251            assert!(
1252                signature.starts_with('(') && signature.ends_with(")V"),
1253                "{name}"
1254            );
1255            assert!(!f.is_null());
1256        }
1257    }
1258
1259    #[test]
1260    fn signatures_agree_between_the_dex_and_the_native_table() {
1261        // The DEX declares the methods; this table binds them. They are written
1262        // in two places, so check they say the same thing.
1263        let dex_source = crate::gatt_callback_dex();
1264        assert!(!dex_source.is_empty());
1265        // Names must line up one for one.
1266        let names: Vec<&str> = gatt_natives().into_iter().map(|(n, _, _)| n).collect();
1267        for expected in [
1268            "onConnectionStateChange",
1269            "onServicesDiscovered",
1270            "onCharacteristicRead",
1271            "onCharacteristicWrite",
1272            "onCharacteristicChanged",
1273            "onDescriptorRead",
1274            "onDescriptorWrite",
1275            "onMtuChanged",
1276            "onReadRemoteRssi",
1277            "onServiceChanged",
1278        ] {
1279            assert!(
1280                names.contains(&expected),
1281                "{expected} is missing from the native table"
1282            );
1283        }
1284    }
1285}