1#[cfg(target_os = "ios")]
11use crate::serialport;
12use btleplug::api::{
13 Central, CentralEvent, CentralState, CharPropFlags, Characteristic, Manager as _,
14 Peripheral as _, ScanFilter, WriteType,
15};
16use btleplug::platform::{Adapter, Manager, Peripheral};
17use futures::StreamExt;
18use serialport::{ClearBuffer, DataBits, FlowControl, Parity, SerialPort, StopBits};
19use std::collections::HashMap;
20use std::io::{self, Read, Write};
21use std::sync::atomic::{AtomicBool, Ordering};
22use std::sync::{Arc, Mutex, OnceLock};
23use std::time::{Duration, Instant};
24use uuid::Uuid;
25
26pub use super::ble_rx::{ble_target, BLE_SCHEME};
27use super::ble_rx::{chunk_size, rx_channel, target_matches, RxQueue, WritePacer, RX_QUEUE_CAP};
28pub const NUS_SERVICE: Uuid = Uuid::from_u128(0x6E400001_B5A3_F393_E0A9_E50E24DCCA9E);
29pub const NUS_RX: Uuid = Uuid::from_u128(0x6E400002_B5A3_F393_E0A9_E50E24DCCA9E);
31pub const NUS_TX: Uuid = Uuid::from_u128(0x6E400003_B5A3_F393_E0A9_E50E24DCCA9E);
33
34fn runtime() -> &'static tokio::runtime::Runtime {
37 static RT: OnceLock<tokio::runtime::Runtime> = OnceLock::new();
38 RT.get_or_init(|| {
39 tokio::runtime::Builder::new_multi_thread()
40 .worker_threads(1)
41 .thread_name("serialplugin-ble")
42 .enable_all()
43 .build()
44 .expect("BLE runtime")
45 })
46}
47
48fn ble_err(e: impl std::fmt::Display) -> io::Error {
49 io::Error::other(format!("BLE: {e}"))
50}
51
52const CONNECT_TIMEOUT: Duration = Duration::from_secs(20);
55
56const WRITE_TIMEOUT: Duration = Duration::from_secs(5);
60
61const POWER_ON_WAIT: Duration = Duration::from_secs(2);
63
64async fn adapter() -> io::Result<Adapter> {
67 static ADAPTER: OnceLock<Adapter> = OnceLock::new();
68 let adapter = match ADAPTER.get() {
69 Some(a) => a.clone(),
70 None => {
71 let manager = Manager::new().await.map_err(ble_err)?;
72 let first = manager
73 .adapters()
74 .await
75 .map_err(ble_err)?
76 .into_iter()
77 .next()
78 .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no Bluetooth adapter"))?;
79 ADAPTER.get_or_init(|| first).clone()
81 }
82 };
83 let deadline = Instant::now() + POWER_ON_WAIT;
84 loop {
85 let state = adapter.adapter_state().await.map_err(ble_err)?;
86 match power_state(state, Instant::now() >= deadline) {
87 Some(ready) => return ready.map(|()| adapter),
88 None => tokio::time::sleep(Duration::from_millis(50)).await,
89 }
90 }
91}
92
93fn power_state(state: CentralState, waited_enough: bool) -> Option<io::Result<()>> {
96 match state {
97 CentralState::PoweredOn => Some(Ok(())),
98 CentralState::PoweredOff => Some(Err(io::Error::new(
99 io::ErrorKind::NotConnected,
100 "Bluetooth is off",
101 ))),
102 CentralState::Unknown if !waited_enough => None,
103 CentralState::Unknown => Some(Err(io::Error::new(
104 io::ErrorKind::PermissionDenied,
105 "Bluetooth is not available (off, or the app is not authorized to use it)",
106 ))),
107 }
108}
109
110fn port_id(p: &Peripheral) -> String {
113 if cfg!(target_os = "linux") {
114 p.address().to_string()
115 } else {
116 p.id().to_string()
117 }
118}
119
120pub fn scan(duration: Duration) -> io::Result<HashMap<String, HashMap<String, String>>> {
123 runtime().block_on(async {
124 let adapter = adapter().await?;
125 adapter
126 .start_scan(ScanFilter {
127 services: vec![NUS_SERVICE],
128 })
129 .await
130 .map_err(ble_err)?;
131 tokio::time::sleep(duration).await;
132 let _ = adapter.stop_scan().await;
133 let mut out = HashMap::new();
134 for p in adapter.peripherals().await.map_err(ble_err)? {
135 let Ok(Some(props)) = p.properties().await else {
136 continue;
137 };
138 out.extend(scan_entry(
139 &port_id(&p),
140 &props.services,
141 props.local_name,
142 props.rssi,
143 ));
144 }
145 Ok(out)
146 })
147}
148
149fn scan_entry(
152 id: &str,
153 services: &[Uuid],
154 local_name: Option<String>,
155 rssi: Option<i16>,
156) -> Option<(String, HashMap<String, String>)> {
157 if !services.contains(&NUS_SERVICE) {
158 return None;
159 }
160 let unknown = || crate::state::UNKNOWN.to_string();
161 let info = HashMap::from([
162 ("type".to_string(), "BLE".to_string()),
163 ("product".to_string(), local_name.unwrap_or_else(unknown)),
164 ("manufacturer".to_string(), unknown()),
165 ("serial_number".to_string(), id.to_string()),
166 ("vid".to_string(), unknown()),
167 ("pid".to_string(), unknown()),
168 (
169 "rssi".to_string(),
170 rssi.map(|r| r.to_string()).unwrap_or_default(),
171 ),
172 ]);
173 Some((format!("{BLE_SCHEME}{id}"), info))
174}
175
176pub struct BleSerialPort {
177 path: String,
178 peripheral: Peripheral,
179 rx_char: Characteristic,
180 tx_char: Characteristic,
181 pacer: WritePacer,
182 rx: Mutex<RxQueue>,
183 connected: Arc<AtomicBool>,
184 baud_rate: u32,
185 data_bits: DataBits,
186 flow_control: FlowControl,
187 parity: Parity,
188 stop_bits: StopBits,
189 timeout: Duration,
190}
191
192impl BleSerialPort {
193 #[allow(clippy::too_many_arguments)]
194 pub fn connect(
195 path: &str,
196 baud_rate: u32,
197 data_bits: DataBits,
198 flow_control: FlowControl,
199 parity: Parity,
200 stop_bits: StopBits,
201 timeout: Duration,
202 ) -> io::Result<Self> {
203 let target = ble_target(path)
204 .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "not a ble:// path"))?
205 .to_string();
206 runtime().block_on(async {
207 let adapter = adapter().await?;
208 let peripheral = find_peripheral(&adapter, &target, Duration::from_secs(10)).await?;
209 let opened =
210 tokio::time::timeout(CONNECT_TIMEOUT, open_nus(&adapter, &peripheral, &target))
211 .await;
212 let (rx_char, tx_char, rx, connected) = match opened {
213 Ok(Ok(v)) => v,
214 Ok(Err(e)) => {
215 let _ = peripheral.disconnect().await;
216 return Err(e);
217 }
218 Err(_) => {
219 let _ = peripheral.disconnect().await;
221 return Err(io::Error::new(
222 io::ErrorKind::TimedOut,
223 format!(
224 "BLE open of {target} timed out after {} s",
225 CONNECT_TIMEOUT.as_secs()
226 ),
227 ));
228 }
229 };
230 Ok(Self {
231 path: path.to_string(),
232 peripheral,
233 rx_char,
234 tx_char,
235 pacer: WritePacer::default(),
236 rx: Mutex::new(rx),
237 connected,
238 baud_rate,
239 data_bits,
240 flow_control,
241 parity,
242 stop_bits,
243 timeout,
244 })
245 })
246 }
247}
248
249async fn open_nus(
253 adapter: &Adapter,
254 peripheral: &Peripheral,
255 target: &str,
256) -> io::Result<(Characteristic, Characteristic, RxQueue, Arc<AtomicBool>)> {
257 peripheral.connect().await.map_err(ble_err)?;
258 peripheral.discover_services().await.map_err(ble_err)?;
259 let chars = peripheral.characteristics();
260 let find = |uuid| {
261 chars
262 .iter()
263 .find(|c| c.uuid == uuid)
264 .cloned()
265 .ok_or_else(|| {
266 io::Error::new(
267 io::ErrorKind::NotFound,
268 format!("{target} has no Nordic UART characteristic {uuid}"),
269 )
270 })
271 };
272 let rx_char = find(NUS_RX)?;
273 let tx_char = find(NUS_TX)?;
274 let mut notes = peripheral.notifications().await.map_err(ble_err)?;
275 let mut events = adapter.events().await.map_err(ble_err)?;
276 peripheral.subscribe(&tx_char).await.map_err(ble_err)?;
278
279 let (feed, rx) = rx_channel(RX_QUEUE_CAP);
280 let connected = Arc::new(AtomicBool::new(true));
281 let id = peripheral.id();
282 let alive = connected.clone();
283 tokio::spawn(async move {
286 loop {
287 tokio::select! {
288 n = notes.next() => match n {
289 Some(n) if n.uuid == NUS_TX => { feed.push(n.value); }
290 Some(_) => {}
291 None => break,
292 },
293 e = events.next() => match e {
294 Some(CentralEvent::DeviceDisconnected(d)) if d == id => break,
295 Some(_) => {}
296 None => break,
297 },
298 }
299 }
300 alive.store(false, Ordering::SeqCst);
301 });
302 Ok((rx_char, tx_char, rx, connected))
303}
304
305async fn find_peripheral(
306 adapter: &Adapter,
307 target: &str,
308 limit: Duration,
309) -> io::Result<Peripheral> {
310 adapter
313 .start_scan(ScanFilter::default())
314 .await
315 .map_err(ble_err)?;
316 let deadline = Instant::now() + limit;
317 let mut name_seen = None;
318 let found = loop {
319 let peripherals = adapter.peripherals().await.map_err(ble_err)?;
320 let mut seen = Vec::with_capacity(peripherals.len());
321 for p in &peripherals {
322 let name = match p.properties().await {
323 Ok(Some(props)) => props.local_name,
324 _ => None,
325 };
326 seen.push(Candidate {
327 id: p.id().to_string(),
328 address: p.address().to_string(),
329 name,
330 });
331 }
332 match scan_step(&seen, target, &mut name_seen, Instant::now(), deadline) {
333 None => {}
334 Some(Ok(Some(i))) => break Ok(Some(peripherals[i].clone())),
335 Some(other) => break other.map(|_| None),
336 }
337 tokio::time::sleep(Duration::from_millis(200)).await;
338 };
339 let _ = adapter.stop_scan().await;
340 found
341 .map_err(|msg| io::Error::new(io::ErrorKind::InvalidInput, msg))?
342 .ok_or_else(|| {
343 io::Error::new(
344 io::ErrorKind::NotFound,
345 format!("no BLE device '{target}' found (id, MAC or advertised name)"),
346 )
347 })
348}
349
350const NAME_SETTLE: Duration = Duration::from_millis(1500);
353
354fn scan_step(
359 seen: &[Candidate],
360 target: &str,
361 name_seen: &mut Option<Instant>,
362 now: Instant,
363 deadline: Instant,
364) -> Option<Result<Option<usize>, String>> {
365 match pick_peripheral(seen, target) {
366 Err(e) => Some(Err(e)),
367 Ok(Some(i)) if target_matches(&seen[i].id, &seen[i].address, None, target) => {
368 Some(Ok(Some(i)))
369 }
370 Ok(Some(i)) => {
371 let first = *name_seen.get_or_insert(now);
372 (now >= first + NAME_SETTLE || now >= deadline).then_some(Ok(Some(i)))
373 }
374 Ok(None) => (now >= deadline).then_some(Ok(None)),
375 }
376}
377
378#[derive(Debug, Clone, PartialEq, Eq)]
380struct Candidate {
381 id: String,
382 address: String,
383 name: Option<String>,
384}
385
386fn pick_peripheral(seen: &[Candidate], target: &str) -> Result<Option<usize>, String> {
392 if let Some(i) = seen
393 .iter()
394 .position(|c| target_matches(&c.id, &c.address, None, target))
395 {
396 return Ok(Some(i));
397 }
398 let named: Vec<&Candidate> = seen
399 .iter()
400 .filter(|c| c.name.as_deref() == Some(target))
401 .collect();
402 match named[..] {
403 [] => Ok(None),
404 [_] => Ok(seen.iter().position(|c| c.name.as_deref() == Some(target))),
405 _ => Err(format!(
406 "{} BLE devices are named '{target}'; open one by id: {}",
407 named.len(),
408 named
409 .iter()
410 .map(|c| {
411 let id = if c.address == "00:00:00:00:00:00" {
412 &c.id
413 } else {
414 &c.address
415 };
416 format!("{BLE_SCHEME}{id}")
417 })
418 .collect::<Vec<_>>()
419 .join(", ")
420 )),
421 }
422}
423
424fn block_on_write(
428 write: impl std::future::Future<Output = btleplug::Result<()>>,
429 limit: Duration,
430 on_timeout: impl FnOnce(),
431) -> io::Result<()> {
432 match runtime().block_on(async { tokio::time::timeout(limit, write).await }) {
434 Ok(r) => r.map_err(ble_err),
435 Err(_) => {
436 on_timeout();
437 Err(io::Error::new(
438 io::ErrorKind::TimedOut,
439 format!("BLE write timed out after {} ms", limit.as_millis()),
440 ))
441 }
442 }
443}
444
445impl Drop for BleSerialPort {
446 fn drop(&mut self) {
447 let (p, tx) = (self.peripheral.clone(), self.tx_char.clone());
448 runtime().spawn(async move {
451 let _ = p.unsubscribe(&tx).await;
452 let _ = p.disconnect().await;
453 });
454 }
455}
456
457impl Read for BleSerialPort {
458 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
459 let timeout = self.timeout;
460 crate::sync_util::lock_or_recover(&self.rx).read(buf, timeout)
461 }
462}
463
464impl Write for BleSerialPort {
465 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
466 if !self.connected.load(Ordering::SeqCst) {
467 return Err(io::Error::new(
468 io::ErrorKind::BrokenPipe,
469 "BLE device disconnected",
470 ));
471 }
472 let n = buf.len().min(chunk_size(self.peripheral.mtu()));
473 let props = self.rx_char.properties;
474 let t = if self.pacer.with_response(
475 props.contains(CharPropFlags::WRITE),
476 props.contains(CharPropFlags::WRITE_WITHOUT_RESPONSE),
477 ) {
478 WriteType::WithResponse
479 } else {
480 WriteType::WithoutResponse
481 };
482 let (p, c) = (&self.peripheral, &self.rx_char);
483 block_on_write(p.write(c, &buf[..n], t), WRITE_TIMEOUT, || {
484 self.connected.store(false, Ordering::SeqCst);
487 let p = self.peripheral.clone();
488 runtime().spawn(async move {
489 let _ = p.disconnect().await;
490 });
491 })?;
492 Ok(n)
493 }
494
495 fn flush(&mut self) -> io::Result<()> {
496 Ok(())
497 }
498}
499
500impl SerialPort for BleSerialPort {
501 fn name(&self) -> Option<String> {
502 Some(self.path.clone())
503 }
504 fn baud_rate(&self) -> serialport::Result<u32> {
505 Ok(self.baud_rate)
506 }
507 fn data_bits(&self) -> serialport::Result<DataBits> {
508 Ok(self.data_bits)
509 }
510 fn flow_control(&self) -> serialport::Result<FlowControl> {
511 Ok(self.flow_control)
512 }
513 fn parity(&self) -> serialport::Result<Parity> {
514 Ok(self.parity)
515 }
516 fn stop_bits(&self) -> serialport::Result<StopBits> {
517 Ok(self.stop_bits)
518 }
519 fn timeout(&self) -> Duration {
520 self.timeout
521 }
522 fn set_baud_rate(&mut self, v: u32) -> serialport::Result<()> {
523 self.baud_rate = v;
524 Ok(())
525 }
526 fn set_data_bits(&mut self, v: DataBits) -> serialport::Result<()> {
527 self.data_bits = v;
528 Ok(())
529 }
530 fn set_flow_control(&mut self, v: FlowControl) -> serialport::Result<()> {
531 self.flow_control = v;
532 Ok(())
533 }
534 fn set_parity(&mut self, v: Parity) -> serialport::Result<()> {
535 self.parity = v;
536 Ok(())
537 }
538 fn set_stop_bits(&mut self, v: StopBits) -> serialport::Result<()> {
539 self.stop_bits = v;
540 Ok(())
541 }
542 fn set_timeout(&mut self, v: Duration) -> serialport::Result<()> {
543 self.timeout = v;
544 Ok(())
545 }
546 fn write_request_to_send(&mut self, _: bool) -> serialport::Result<()> {
547 Ok(())
548 }
549 fn write_data_terminal_ready(&mut self, _: bool) -> serialport::Result<()> {
550 Ok(())
551 }
552 fn read_clear_to_send(&mut self) -> serialport::Result<bool> {
553 Ok(true)
554 }
555 fn read_data_set_ready(&mut self) -> serialport::Result<bool> {
556 Ok(self.connected.load(Ordering::SeqCst))
557 }
558 fn read_ring_indicator(&mut self) -> serialport::Result<bool> {
559 Ok(false)
560 }
561 fn read_carrier_detect(&mut self) -> serialport::Result<bool> {
562 Ok(self.connected.load(Ordering::SeqCst))
563 }
564 fn bytes_to_read(&self) -> serialport::Result<u32> {
565 Ok(crate::sync_util::lock_or_recover(&self.rx).buffered() as u32)
566 }
567 fn bytes_to_write(&self) -> serialport::Result<u32> {
568 Ok(0)
569 }
570 fn clear(&self, which: ClearBuffer) -> serialport::Result<()> {
571 if !matches!(which, ClearBuffer::Output) {
572 crate::sync_util::lock_or_recover(&self.rx).clear();
573 }
574 Ok(())
575 }
576 fn try_clone(&self) -> serialport::Result<Box<dyn SerialPort>> {
577 Err(serialport::Error::new(
578 serialport::ErrorKind::Unknown,
579 "a BLE port cannot be cloned",
580 ))
581 }
582 fn set_break(&self) -> serialport::Result<()> {
583 Ok(())
584 }
585 fn clear_break(&self) -> serialport::Result<()> {
586 Ok(())
587 }
588}
589
590#[cfg(test)]
591mod adapter_tests {
592 use super::*;
594
595 #[test]
596 fn power_states() {
597 assert!(matches!(
598 power_state(CentralState::PoweredOn, false),
599 Some(Ok(()))
600 ));
601 assert!(matches!(
602 power_state(CentralState::PoweredOn, true),
603 Some(Ok(()))
604 ));
605 for waited in [false, true] {
606 let off = power_state(CentralState::PoweredOff, waited)
607 .unwrap()
608 .unwrap_err();
609 assert_eq!(off.kind(), io::ErrorKind::NotConnected);
610 }
611 assert!(power_state(CentralState::Unknown, false).is_none());
612 let unknown = power_state(CentralState::Unknown, true)
613 .unwrap()
614 .unwrap_err();
615 assert_eq!(unknown.kind(), io::ErrorKind::PermissionDenied);
616 }
617
618 #[test]
619 fn scan_lists_nus_devices_only() {
620 let other = Uuid::from_u128(0x180D);
621 assert_eq!(scan_entry("id-1", &[other], Some("hr".into()), None), None);
622 let (path, info) = scan_entry(
623 "id-2",
624 &[other, NUS_SERVICE],
625 Some("board".into()),
626 Some(-60),
627 )
628 .unwrap();
629 assert_eq!(path, "ble://id-2");
630 let get = |k: &str| info.get(k).cloned().unwrap();
631 assert_eq!(get("type"), "BLE");
632 assert_eq!(get("product"), "board");
633 assert_eq!(get("serial_number"), "id-2");
634 assert_eq!(get("rssi"), "-60");
635 for k in ["manufacturer", "vid", "pid"] {
636 assert_eq!(get(k), crate::state::UNKNOWN);
637 }
638 assert_eq!(info.len(), 7);
639 let (_, bare) = scan_entry("id-3", &[NUS_SERVICE], None, None).unwrap();
640 assert_eq!(bare["product"], crate::state::UNKNOWN);
641 assert_eq!(bare["rssi"], "");
642 }
643}
644
645#[cfg(test)]
646mod selection_tests {
647 use super::*;
649
650 fn dev(id: &str, mac: &str, name: Option<&str>) -> Candidate {
651 Candidate {
652 id: id.into(),
653 address: mac.into(),
654 name: name.map(Into::into),
655 }
656 }
657
658 #[test]
659 fn id_or_mac_wins_over_a_name() {
660 let found = [
661 dev("uuid-1", "00:00:00:00:00:00", Some("AA:BB:CC:DD:EE:FF")),
662 dev("uuid-2", "AA:BB:CC:DD:EE:FF", Some("board")),
663 ];
664 assert_eq!(pick_peripheral(&found, "aa:bb:cc:dd:ee:ff"), Ok(Some(1)));
665 assert_eq!(pick_peripheral(&found, "UUID-1"), Ok(Some(0)));
666 }
667
668 #[test]
669 fn a_unique_name_is_used() {
670 let found = [
671 dev("uuid-1", "00:00:00:00:00:00", Some("left")),
672 dev("uuid-2", "00:00:00:00:00:00", Some("right")),
673 ];
674 assert_eq!(pick_peripheral(&found, "right"), Ok(Some(1)));
675 assert_eq!(pick_peripheral(&found, "nothing"), Ok(None));
676 }
677
678 #[test]
679 fn a_shared_name_is_an_error_listing_the_candidates() {
680 let found = [
681 dev("uuid-1", "00:00:00:00:00:00", Some("NUS")),
682 dev("uuid-2", "00:00:00:00:00:00", Some("other")),
683 dev("uuid-3", "00:00:00:00:00:00", Some("NUS")),
684 ];
685 let err = pick_peripheral(&found, "NUS").unwrap_err();
686 assert!(err.contains("ble://uuid-1"), "{err}");
687 assert!(err.contains("ble://uuid-3"), "{err}");
688 assert!(!err.contains("uuid-2"), "{err}");
689 }
690
691 #[test]
692 fn a_stuck_write_times_out_and_drops_the_link() {
693 let dropped = std::cell::Cell::new(0);
694 let err = block_on_write(
695 std::future::pending::<btleplug::Result<()>>(),
696 Duration::from_millis(5),
697 || dropped.set(dropped.get() + 1),
698 )
699 .unwrap_err();
700 assert_eq!(err.kind(), io::ErrorKind::TimedOut);
701 assert_eq!(dropped.get(), 1, "a timed-out write must reset the link");
702 assert!(
703 block_on_write(async { Ok(()) }, Duration::from_secs(10), || {
704 dropped.set(dropped.get() + 1)
705 })
706 .is_ok()
707 );
708 assert_eq!(dropped.get(), 1);
709 }
710
711 #[test]
714 fn a_name_waits_for_the_scan_window() {
715 let t0 = Instant::now();
716 let deadline = t0 + Duration::from_secs(10);
717 let one = [dev("uuid-1", "00:00:00:00:00:00", Some("NUS"))];
718 let two = [
719 dev("uuid-1", "00:00:00:00:00:00", Some("NUS")),
720 dev("uuid-2", "00:00:00:00:00:00", Some("NUS")),
721 ];
722 let mut first = None;
723 assert_eq!(scan_step(&one, "NUS", &mut first, t0, deadline), None);
724 let later = t0 + Duration::from_millis(400);
725 assert!(matches!(
726 scan_step(&two, "NUS", &mut first, later, deadline),
727 Some(Err(_))
728 ));
729 let mut first = None;
730 assert_eq!(scan_step(&one, "NUS", &mut first, t0, deadline), None);
731 let settled = t0 + NAME_SETTLE;
732 assert_eq!(
733 scan_step(&one, "NUS", &mut first, settled, deadline),
734 Some(Ok(Some(0)))
735 );
736 let mut first = None;
738 assert_eq!(
739 scan_step(&one, "uuid-1", &mut first, t0, deadline),
740 Some(Ok(Some(0)))
741 );
742 let mut first = None;
744 assert_eq!(scan_step(&[], "NUS", &mut first, t0, deadline), None);
745 assert_eq!(
746 scan_step(&[], "NUS", &mut first, deadline, deadline),
747 Some(Ok(None))
748 );
749 let mut first = None;
751 assert_eq!(
752 scan_step(&one, "NUS", &mut first, deadline, deadline),
753 Some(Ok(Some(0)))
754 );
755 }
756}