1#![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
20const TRANSPORT_LE: i32 = 2;
22pub const WRITE_TYPE_DEFAULT: i32 = 2;
24pub const WRITE_TYPE_NO_RESPONSE: i32 = 1;
25pub const GATT_SUCCESS: i32 = 0;
27
28fn 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
87pub 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
99pub 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
108fn 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
120pub 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
136pub struct Adapter {
140 adapter: Ref,
141}
142
143impl Adapter {
144 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 pub fn is_enabled(&self, env: Env) -> bool {
187 call_bool(env, self.as_ptr(), "isEnabled", "()Z", &[]).unwrap_or(false)
188 }
189
190 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 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 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 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 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 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 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
295pub 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 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
403pub 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
429pub 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
438pub 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
481pub 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
530pub 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 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 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
587pub 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 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 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
684pub 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
704pub fn close(env: Env, gatt: JObject) -> Result<()> {
710 call_void(env, gatt, "close", "()V", &[])
711}
712
713pub 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#[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#[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
779pub 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
797pub struct Callback {
801 object: Ref,
802}
803
804impl Callback {
805 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
833pub struct Discard;
835
836impl EventSink for Discard {
837 fn emit(&self, _: Event) {}
838}
839
840const SERVICE_TYPE_PRIMARY: i32 = 0;
844const SERVICE_TYPE_SECONDARY: i32 = 1;
845
846pub const ATT_SUCCESS: i32 = 0;
848
849pub 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; }
863 if permissions & READ_ENCRYPTED != 0 {
864 out |= 2; }
866 if permissions & WRITEABLE != 0 {
867 out |= 16; }
869 if permissions & WRITE_ENCRYPTED != 0 {
870 out |= 32; }
872 out
873}
874
875pub 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
900pub 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
917pub 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 JValue::int(properties as i32),
939 JValue::int(permissions_to_android(permissions)),
940 ],
941 ))
942}
943
944pub 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
1030pub 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
1059pub 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
1105pub 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 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
1201pub fn start_advertising(
1213 env: Env,
1214 advertiser: JObject,
1215 callback: JObject,
1216 include_name: bool,
1217 service_uuids: &[String],
1218 connectable: bool,
1219) -> Result<()> {
1220 let settings = build_advertise_settings(env, connectable)?;
1221 let data = build_advertise_data(env, include_name, service_uuids)?;
1222 call_void(
1223 env,
1224 advertiser,
1225 "startAdvertising",
1226 concat!(
1227 "(Landroid/bluetooth/le/AdvertiseSettings;",
1228 "Landroid/bluetooth/le/AdvertiseData;",
1229 "Landroid/bluetooth/le/AdvertiseCallback;)V"
1230 ),
1231 &[
1232 JValue::object(settings),
1233 JValue::object(data),
1234 JValue::object(callback),
1235 ],
1236 )
1237}
1238
1239pub fn stop_advertising(env: Env, advertiser: JObject, callback: JObject) -> Result<()> {
1240 call_void(
1241 env,
1242 advertiser,
1243 "stopAdvertising",
1244 "(Landroid/bluetooth/le/AdvertiseCallback;)V",
1245 &[JValue::object(callback)],
1246 )
1247}
1248
1249fn build_advertise_settings(env: Env, connectable: bool) -> Result<JObject> {
1250 let class = env
1251 .find_class("android/bluetooth/le/AdvertiseSettings$Builder")
1252 .ok_or_else(|| Error::MissingClass("AdvertiseSettings.Builder".into()))?;
1253 let ctor = env
1254 .method_id(class, "<init>", "()V")
1255 .ok_or_else(|| missing("AdvertiseSettings.Builder.<init>"))?;
1256 let builder = env.new_object(class, ctor, &[]);
1257
1258 call_object(
1260 env,
1261 builder,
1262 "setAdvertiseMode",
1263 "(I)Landroid/bluetooth/le/AdvertiseSettings$Builder;",
1264 &[JValue::int(2)],
1265 )?;
1266 call_object(
1267 env,
1268 builder,
1269 "setConnectable",
1270 "(Z)Landroid/bluetooth/le/AdvertiseSettings$Builder;",
1271 &[JValue::bool(connectable)],
1272 )?;
1273 call_object(
1274 env,
1275 builder,
1276 "build",
1277 "()Landroid/bluetooth/le/AdvertiseSettings;",
1278 &[],
1279 )
1280}
1281
1282fn build_advertise_data(env: Env, include_name: bool, service_uuids: &[String]) -> Result<JObject> {
1283 let class = env
1284 .find_class("android/bluetooth/le/AdvertiseData$Builder")
1285 .ok_or_else(|| Error::MissingClass("AdvertiseData.Builder".into()))?;
1286 let ctor = env
1287 .method_id(class, "<init>", "()V")
1288 .ok_or_else(|| missing("AdvertiseData.Builder.<init>"))?;
1289 let builder = env.new_object(class, ctor, &[]);
1290
1291 call_object(
1292 env,
1293 builder,
1294 "setIncludeDeviceName",
1295 "(Z)Landroid/bluetooth/le/AdvertiseData$Builder;",
1296 &[JValue::bool(include_name)],
1297 )?;
1298 for canonical in service_uuids {
1299 let parcel = parcel_uuid(env, canonical)?;
1300 call_object(
1301 env,
1302 builder,
1303 "addServiceUuid",
1304 "(Landroid/os/ParcelUuid;)Landroid/bluetooth/le/AdvertiseData$Builder;",
1305 &[JValue::object(parcel)],
1306 )?;
1307 }
1308 call_object(
1309 env,
1310 builder,
1311 "build",
1312 "()Landroid/bluetooth/le/AdvertiseData;",
1313 &[],
1314 )
1315}
1316
1317pub fn listen_rfcomm(
1321 env: Env,
1322 adapter: JObject,
1323 name: &str,
1324 service_uuid: &str,
1325) -> Result<JObject> {
1326 let service_uuid = uuid(env, service_uuid)?;
1327 let name = env.new_string(name);
1328 call_object(
1329 env,
1330 adapter,
1331 "listenUsingRfcommWithServiceRecord",
1332 "(Ljava/lang/String;Ljava/util/UUID;)Landroid/bluetooth/BluetoothServerSocket;",
1333 &[JValue::object(name), JValue::object(service_uuid)],
1334 )
1335}
1336
1337pub fn listen_l2cap(env: Env, adapter: JObject, secure: bool) -> Result<JObject> {
1342 let name = if secure {
1343 "listenUsingL2capChannel"
1344 } else {
1345 "listenUsingInsecureL2capChannel"
1346 };
1347 call_object(
1348 env,
1349 adapter,
1350 name,
1351 "()Landroid/bluetooth/BluetoothServerSocket;",
1352 &[],
1353 )
1354}
1355
1356pub fn server_socket_psm(env: Env, socket: JObject) -> Result<i32> {
1357 call_int(env, socket, "getPsm", "()I", &[])
1358}
1359
1360pub fn server_socket_accept(env: Env, socket: JObject) -> Result<JObject> {
1362 call_object(
1363 env,
1364 socket,
1365 "accept",
1366 "()Landroid/bluetooth/BluetoothSocket;",
1367 &[],
1368 )
1369}
1370
1371pub fn server_socket_close(env: Env, socket: JObject) -> Result<()> {
1372 call_void(env, socket, "close", "()V", &[])
1373}