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