android-bluetooth-serial 0.1.1

Android API wrapper handling Bluetooth classic RFCOMM/SPP connection.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
//! Android API wrapper handling Bluetooth classic RFCOMM/SPP connection.
//!
//! This crate is looking for maintainers!
//!
//! TODO:
//! - Add a function and an enum for checking the bluetooth state.
//! - Add functions for permission request and enabling bluetooth.
//!   <https://developer.android.com/develop/connectivity/bluetooth/setup>
//! - Add functions for device discovery and pairing.
//! - Provide an asynchronous interface.

use std::io::Error;

use jni::{
    objects::JObject,
    sys::{jint, jvalue},
};
use jni_min_helper::*;
use std::{
    collections::VecDeque,
    io::{ErrorKind, Read, Write},
    sync::{Arc, Mutex},
    thread::JoinHandle,
    time::{Duration, SystemTime},
};

const BLUETOOTH_SERVICE: &str = "bluetooth";

/// The UUID for the well-known SPP profile.
pub const SPP_UUID: &str = "00001101-0000-1000-8000-00805F9B34FB";

/// Maps unexpected JNI errors to `std::io::Error`.
/// (`From<jni::errors::Error>` cannot be implemented for `std::io::Error`
/// here because of the orphan rule). Side effect: `jni_last_cleared_ex()`.
#[inline(always)]
pub(crate) fn jerr(err: jni::errors::Error) -> Error {
    use jni::errors::Error::*;
    if let JavaException = err {
        let err = jni_clear_ex(err);
        let Some(ex) = jni_last_cleared_ex() else {
            return Error::other(JavaException);
        };
        jni_with_env(|env| Ok((ex.get_class_name(env)?, ex.get_throwable_msg(env)?)))
            .map(|(cls, msg)| {
                if cls.contains("SecurityException") {
                    Error::new(ErrorKind::PermissionDenied, msg)
                } else if cls.contains("IllegalArgumentException") {
                    Error::new(ErrorKind::InvalidInput, msg)
                } else {
                    Error::other(format!("{cls}: {msg}"))
                }
            })
            .unwrap_or(Error::other(err))
    } else {
        Error::other(err)
    }
}

/// Returns the global reference of the thread safe `android.bluetooth.BluetoothAdapter`,
/// created for once in this crate.
#[inline(always)]
pub(crate) fn bluetooth_adapter() -> Result<&'static JObject<'static>, Error> {
    use std::sync::OnceLock;
    static BT_ADAPTER: OnceLock<jni::objects::GlobalRef> = OnceLock::new();
    if let Some(ref_adapter) = BT_ADAPTER.get() {
        Ok(ref_adapter.as_obj())
    } else {
        let adapter = get_bluetooth_adapter()?;
        let _ = BT_ADAPTER.set(adapter.clone());
        Ok(BT_ADAPTER.get().unwrap().as_obj())
    }
}

fn get_bluetooth_adapter() -> Result<jni::objects::GlobalRef, Error> {
    jni_with_env(|env| {
        let context = android_context();

        let bluetooth_service = BLUETOOTH_SERVICE.new_jobject(env)?;
        let manager = env
            .call_method(
                context,
                "getSystemService",
                "(Ljava/lang/String;)Ljava/lang/Object;",
                &[(&bluetooth_service).into()],
            )
            .get_object(env)?;
        if manager.is_null() {
            return Ok(Err(Error::new(
                ErrorKind::Unsupported,
                "Cannot get BLUETOOTH_SERVICE",
            )));
        }
        let adapter = env
            .call_method(
                manager,
                "getAdapter",
                "()Landroid/bluetooth/BluetoothAdapter;",
                &[],
            )
            .get_object(env)
            .globalize(env)?;
        if !adapter.is_null() {
            Ok(Ok(adapter))
        } else {
            Ok(Err(Error::new(
                ErrorKind::Unsupported,
                "`getAdapter` returned null",
            )))
        }
    })
    .map_err(jerr)?
}

/// Return true if Bluetooth is currently enabled and ready for use.
/// It may return an error of `std::io::ErrorKind::PermissionDenied`, or some other error.
pub fn is_enabled() -> Result<bool, Error> {
    let adapter = bluetooth_adapter()?;
    jni_with_env(|env| {
        env.call_method(adapter, "isEnabled", "()Z", &[])
            .get_boolean()
    })
    .map_err(jerr)
}

/// Gets a list of `BluetoothDevice` objects that are bonded (paired) to the adapter.
/// `is_enabled()` is checked at first; returns an empty list if it is not enabled.
pub fn get_bonded_devices() -> Result<Vec<BluetoothDevice>, Error> {
    if !is_enabled()? {
        return Ok(Vec::new());
    }
    let adapter = bluetooth_adapter()?;
    jni_with_env(|env| {
        let dev_set = env
            .call_method(adapter, "getBondedDevices", "()Ljava/util/Set;", &[])
            .get_object(env)?;
        if dev_set.is_null() {
            return Ok(Err(Error::from(ErrorKind::PermissionDenied)));
        }
        let jarr = env
            .call_method(&dev_set, "toArray", "()[Ljava/lang/Object;", &[])
            .get_object(env)?;
        let jarr: &jni::objects::JObjectArray = jarr.as_ref().into();
        let len = env.get_array_length(jarr).map_err(jni_clear_ex)?;
        let mut vec = Vec::with_capacity(len as usize);
        for i in 0..len {
            vec.push(BluetoothDevice {
                internal: env.get_object_array_element(jarr, i).global_ref(env)?,
            });
        }
        Ok(Ok(vec))
    })
    .map_err(jerr)?
}

/// Corresponds to `android.bluetooth.BluetoothDevice`.
#[derive(Clone, Debug)]
pub struct BluetoothDevice {
    pub(crate) internal: jni::objects::GlobalRef,
}

impl BluetoothDevice {
    /// Returns the hardware address of this BluetoothDevice.
    /// TODO: return some MAC address type instead of `String`.
    pub fn get_address(&self) -> Result<String, Error> {
        jni_with_env(|env| {
            env.call_method(&self.internal, "getAddress", "()Ljava/lang/String;", &[])
                .get_object(env)?
                .get_string(env)
        })
        .map_err(jerr)
    }

    /// Gets the friendly Bluetooth name of the remote device.
    pub fn get_name(&self) -> Result<String, Error> {
        jni_with_env(|env| {
            let dev_name = env
                .call_method(&self.internal, "getName", "()Ljava/lang/String;", &[])
                .get_object(env)?;
            if dev_name.is_null() {
                return Ok(Err(Error::from(ErrorKind::PermissionDenied)));
            }
            dev_name.get_string(env).map(Ok)
        })
        .map_err(jerr)?
    }

    /// Creates the Android Bluetooth API socket object for RFCOMM communication.
    /// `SPP_UUID` can be used. Note that `connect` is not called automatically.
    pub fn build_rfcomm_socket(
        &self,
        uuid: &str,
        is_secure: bool,
    ) -> Result<BluetoothSocket, Error> {
        let socket = jni_with_env(|env| {
            let uuid = uuid.new_jobject(env)?;
            let uuid = env
                .call_static_method(
                    "java/util/UUID",
                    "fromString",
                    "(Ljava/lang/String;)Ljava/util/UUID;",
                    &[(&uuid).into()],
                )
                .get_object(env)?;

            let method_name = if is_secure {
                "createRfcommSocketToServiceRecord"
            } else {
                "createInsecureRfcommSocketToServiceRecord"
            };
            env.call_method(
                &self.internal,
                method_name,
                "(Ljava/util/UUID;)Landroid/bluetooth/BluetoothSocket;",
                &[(&uuid).into()],
            )
            .get_object(env)
            .globalize(env)
        })
        .map_err(jerr)?; // TODO: distinguish `IOException` and other unexpected exceptions
        BluetoothSocket::build(socket)
    }
}

/// Manages the Bluetooth socket and IO streams. It uses a read buffer and a background thread,
/// because the timeout of the Java `InputStream` from the `BluetoothSocket` cannot be set.
/// The read timeout defaults to 0 (it does not block).
///
/// Reference:
/// <https://developer.android.com/develop/connectivity/bluetooth/transfer-data>
pub struct BluetoothSocket {
    internal: jni::objects::GlobalRef,

    input_stream: jni::objects::GlobalRef,
    buf_read: Arc<Mutex<VecDeque<u8>>>,
    thread_read: Option<JoinHandle<Result<(), Error>>>, // the returned value is unused
    read_callback: Arc<Mutex<Option<ReadCallback>>>,    // None by default
    read_timeout: Duration,                             // set for the standard Read trait

    output_stream: jni::objects::GlobalRef,
    jmethod_write: jni::objects::JMethodID,
    jmethod_flush: jni::objects::JMethodID,
    array_write: jni::objects::GlobalRef,
}

type ReadCallback = Box<dyn Fn(Option<usize>) + 'static + Send>;

impl BluetoothSocket {
    const ARRAY_SIZE: usize = 32 * 1024;

    fn build(obj: jni::objects::GlobalRef) -> Result<Self, Error> {
        jni_with_env(|env| {
            // the streams may (or may NOT) be usable after reconnection (check Android SDK source)
            let input_stream = env
                .call_method(&obj, "getInputStream", "()Ljava/io/InputStream;", &[])
                .get_object(env)
                .globalize(env)?;
            let output_stream = env
                .call_method(&obj, "getOutputStream", "()Ljava/io/OutputStream;", &[])
                .get_object(env)
                .globalize(env)?;

            let jmethod_write = env
                .get_method_id("java/io/OutputStream", "write", "([BII)V")
                .map_err(jni_clear_ex)?;
            let jmethod_flush = env
                .get_method_id("java/io/OutputStream", "flush", "()V")
                .map_err(jni_clear_ex)?;

            let array_size = Self::ARRAY_SIZE as i32;
            let array_write = env.new_byte_array(array_size).global_ref(env)?;

            Ok(Self {
                internal: obj,

                input_stream,
                buf_read: Arc::new(Mutex::new(VecDeque::new())),
                thread_read: None,
                read_callback: Arc::new(Mutex::new(None)),
                read_timeout: Duration::from_millis(0),

                output_stream,
                jmethod_write,
                jmethod_flush,
                array_write,
            })
        })
        .map_err(jerr)
    }

    /// Gets the connection status of this socket.
    #[inline(always)]
    pub fn is_connected(&self) -> Result<bool, Error> {
        jni_with_env(|env| {
            env.call_method(&self.internal, "isConnected", "()Z", &[])
                .get_boolean()
        })
        .map_err(jerr)
    }

    /// Attempts to connect to a remote device. When connected, it creates a
    /// backgrond thread for reading data, which terminates itself on disconnection.
    /// Do not reuse the socket after disconnection, because the underlying OS
    /// implementation is probably incapable of reconnecting the device, just like
    /// `java.net.Socket`.
    pub fn connect(&mut self) -> Result<(), Error> {
        if self.is_connected()? {
            return Ok(());
        }
        let adapter = bluetooth_adapter()?;

        jni_with_env(|env| {
            let _ = env
                .call_method(adapter, "cancelDiscovery", "()Z", &[])
                .map_err(jni_clear_ex);
            env.call_method(&self.internal, "connect", "()V", &[])
                .clear_ex()
        })
        .map_err(jerr)?;

        if self.is_connected()? {
            let socket = self.internal.clone();
            let input_stream = self.input_stream.clone();
            let arc_buf_read = self.buf_read.clone();
            let arc_callback = self.read_callback.clone();
            self.thread_read.replace(std::thread::spawn(move || {
                Self::read_loop(socket, input_stream, arc_buf_read, arc_callback)
            }));
            Ok(())
        } else {
            Err(Error::from(ErrorKind::NotConnected))
        }
    }

    /// Returns number of available bytes that can be read without blocking.
    #[inline(always)]
    pub fn len_available(&self) -> usize {
        self.buf_read.lock().unwrap().len()
    }

    /// Clears the managed read buffer used by the Rust side background thread.
    #[inline(always)]
    pub fn clear_read_buf(&mut self) {
        self.buf_read.lock().unwrap().clear();
    }

    /// Sets timeout for the `std::io::Read` implementation.
    pub fn set_read_timeout(&mut self, timeout: Duration) {
        self.read_timeout = timeout;
    }

    /// Sets or replaces the callback to be invoked from the background thread when
    /// new data becomes available or the socket is disconnected. The length of newly
    /// arrived data instead of the length of available data in the read buffer will
    /// be passed to the callback (or `None` if it is disconnected).
    pub fn set_read_callback(&mut self, f: impl Fn(Option<usize>) + 'static + Send) {
        self.read_callback.lock().unwrap().replace(Box::new(f));
    }

    /// Closes this socket and releases any system resources associated with it.
    /// If the stream is already closed then invoking this method has no effect.
    pub fn close(&mut self) -> Result<(), Error> {
        if !self.is_connected()? {
            return Ok(());
        }
        let _ = self.flush();
        jni_with_env(|env| {
            env.call_method(&self.internal, "close", "()V", &[])?;
            if let Some(th) = self.thread_read.take() {
                let _ = th.join();
            }
            Ok(())
        })
        .map_err(jerr)
    }
}

impl BluetoothSocket {
    fn read_loop(
        socket: jni::objects::GlobalRef,
        input_stream: jni::objects::GlobalRef,
        buf_read: Arc<Mutex<VecDeque<u8>>>,
        read_callback: Arc<Mutex<Option<ReadCallback>>>,
    ) -> Result<(), Error> {
        jni_with_env(|env| {
            let jmethod_read = env.get_method_id("java/io/InputStream", "read", "([BII)I")?;
            let read_size = env
                .call_method(&socket, "getMaxReceivePacketSize", "()I", &[])
                .get_int()
                .map(|i| {
                    if i > 0 {
                        let sz = i as usize;
                        (Self::ARRAY_SIZE / sz) * sz
                    } else {
                        Self::ARRAY_SIZE
                    }
                })
                .unwrap_or(Self::ARRAY_SIZE);

            let mut vec_read = vec![0u8; read_size];
            let array_read = env.new_byte_array(read_size as i32).auto_local(env)?;
            let array_read: &jni::objects::JByteArray<'_> = array_read.as_ref().into();

            loop {
                use jni::signature::*;
                // Safety: arguments passed to `call_method_unchecked` are correct.
                let read_len = unsafe {
                    env.call_method_unchecked(
                        &input_stream,
                        jmethod_read,
                        ReturnType::Primitive(Primitive::Int),
                        &[
                            jvalue {
                                l: array_read.as_raw(),
                            },
                            jvalue { i: 0 as jint },
                            jvalue {
                                i: read_size as jint,
                            },
                        ],
                    )
                }
                .get_int();
                if let Ok(len) = read_len {
                    let len = if len > 0 {
                        len as usize
                    } else {
                        continue;
                    };
                    // Safety: casts `&mut [u8]` to `&mut [i8]` for `get_byte_array_region`,
                    // `input_stream.read(..)` = `len` <= `read_size` = `vec_read.len()`.
                    let tmp_read = unsafe {
                        std::slice::from_raw_parts_mut(vec_read.as_mut_ptr() as *mut i8, len)
                    };
                    env.get_byte_array_region(array_read, 0, tmp_read)
                        .map_err(jni_clear_ex)?;
                    buf_read
                        .lock()
                        .unwrap()
                        .write_all(&vec_read[..len])
                        .unwrap();
                    Self::read_callback(&read_callback, Some(len));
                } else {
                    if let Some(ex) = jni_last_cleared_ex() {
                        let ex_msg = ex.get_throwable_msg(env).unwrap().to_lowercase();
                        if ex_msg.contains("closed") {
                            // Note: will it change in future Android versions?
                            let _ = env
                                .call_method(&socket, "close", "()V", &[])
                                .map_err(jni_clear_ex_ignore);
                            Self::read_callback(&read_callback, None);
                            return Ok(());
                        }
                    }
                    let is_connected = env
                        .call_method(&socket, "isConnected", "()Z", &[])
                        .get_boolean()?;
                    if !is_connected {
                        Self::read_callback(&read_callback, None);
                        return Ok(());
                    }
                }
            }
        })
        .map_err(jerr)
    }

    fn read_callback(cb: impl AsRef<Mutex<Option<ReadCallback>>>, val: Option<usize>) {
        let mut lck = cb.as_ref().lock().unwrap();
        if let Some(callback) = lck.take() {
            drop(lck);
            callback(val);
            let mut lck = cb.as_ref().lock().unwrap();
            if lck.is_none() {
                lck.replace(callback);
            }
        }
    }
}

impl Read for BluetoothSocket {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        if buf.is_empty() {
            return Ok(0);
        }

        let t_timeout = SystemTime::now() + self.read_timeout;

        let mut cnt_read = 0;
        let mut disconnected = false;
        while cnt_read == 0 {
            let mut lck_buf_read = self.buf_read.lock().unwrap();
            if let Ok(cnt) = lck_buf_read.read(&mut buf[cnt_read..]) {
                cnt_read += cnt;
            }
            drop(lck_buf_read);
            if cnt_read > 0 {
                break;
            } else if !self.is_connected()? {
                disconnected = true;
                break;
            } else if let Ok(dur_rem) = t_timeout.duration_since(SystemTime::now()) {
                std::thread::sleep(Duration::from_millis(50).min(dur_rem));
            } else {
                break;
            }
        }

        if cnt_read > 0 {
            Ok(cnt_read)
        } else if !disconnected {
            Err(Error::from(ErrorKind::TimedOut))
        } else {
            Err(Error::from(ErrorKind::NotConnected))
        }
    }
}

impl Write for BluetoothSocket {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        if buf.is_empty() {
            return Ok(0);
        }

        jni_with_env(|env| {
            let array_write: &jni::objects::JByteArray<'_> = self.array_write.as_obj().into();
            if (env.get_array_length(array_write).map_err(jni_clear_ex)? as usize) < buf.len() {
                // replace the prepared reusable Java array with a larger array
                self.array_write = env.byte_array_from_slice(buf).global_ref(env)?;
            } else {
                // Safety: casts `&[u8]` to `&[i8]` for `set_byte_array_region`.
                let buf =
                    unsafe { std::slice::from_raw_parts(buf.as_ptr() as *const i8, buf.len()) };
                env.set_byte_array_region(array_write, 0, buf)
                    .map_err(jni_clear_ex)?;
            }

            use jni::signature::*;
            // Safety: arguments passed to `call_method_unchecked` are correct.
            unsafe {
                env.call_method_unchecked(
                    &self.output_stream,
                    self.jmethod_write,
                    ReturnType::Primitive(Primitive::Void),
                    &[
                        jvalue {
                            l: self.array_write.as_raw(),
                        },
                        jvalue { i: 0 as jint },
                        jvalue {
                            i: buf.len() as jint,
                        },
                    ],
                )
            }
            .clear_ex()
        })
        .map_err(|e| {
            if !self.is_connected().unwrap_or(false) {
                Error::from(ErrorKind::NotConnected)
            } else {
                jerr(e)
            }
        })
        .map(|_| buf.len())
    }

    #[inline]
    fn flush(&mut self) -> std::io::Result<()> {
        jni_with_env(|env| {
            use jni::signature::*;
            unsafe {
                env.call_method_unchecked(
                    &self.output_stream,
                    self.jmethod_flush,
                    ReturnType::Primitive(Primitive::Void),
                    &[],
                )
            }
            .clear_ex()
        })
        .map_err(jerr)
    }
}

impl Drop for BluetoothSocket {
    fn drop(&mut self) {
        let _ = self.close();
    }
}