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 match adapter.adapter_state().await.map_err(ble_err)? {
86 CentralState::PoweredOn => return Ok(adapter),
87 CentralState::PoweredOff => {
88 return Err(io::Error::new(
89 io::ErrorKind::NotConnected,
90 "Bluetooth is off",
91 ))
92 }
93 CentralState::Unknown if Instant::now() < deadline => {
94 tokio::time::sleep(Duration::from_millis(50)).await
95 }
96 CentralState::Unknown => {
97 return Err(io::Error::new(
98 io::ErrorKind::PermissionDenied,
99 "Bluetooth is not available (off, or the app is not authorized to use it)",
100 ))
101 }
102 }
103 }
104}
105
106fn port_id(p: &Peripheral) -> String {
109 if cfg!(target_os = "linux") {
110 p.address().to_string()
111 } else {
112 p.id().to_string()
113 }
114}
115
116pub fn scan(duration: Duration) -> io::Result<HashMap<String, HashMap<String, String>>> {
119 runtime().block_on(async {
120 let adapter = adapter().await?;
121 adapter
122 .start_scan(ScanFilter {
123 services: vec![NUS_SERVICE],
124 })
125 .await
126 .map_err(ble_err)?;
127 tokio::time::sleep(duration).await;
128 let _ = adapter.stop_scan().await;
129 let mut out = HashMap::new();
130 for p in adapter.peripherals().await.map_err(ble_err)? {
131 let Ok(Some(props)) = p.properties().await else {
132 continue;
133 };
134 if !props.services.contains(&NUS_SERVICE) {
135 continue;
136 }
137 let name = props
138 .local_name
139 .clone()
140 .unwrap_or_else(|| crate::state::UNKNOWN.to_string());
141 let info = HashMap::from([
142 ("type".to_string(), "BLE".to_string()),
143 ("product".to_string(), name),
144 (
145 "manufacturer".to_string(),
146 crate::state::UNKNOWN.to_string(),
147 ),
148 ("serial_number".to_string(), port_id(&p)),
149 ("vid".to_string(), crate::state::UNKNOWN.to_string()),
150 ("pid".to_string(), crate::state::UNKNOWN.to_string()),
151 (
152 "rssi".to_string(),
153 props.rssi.map(|r| r.to_string()).unwrap_or_default(),
154 ),
155 ]);
156 out.insert(format!("{BLE_SCHEME}{}", port_id(&p)), info);
157 }
158 Ok(out)
159 })
160}
161
162pub struct BleSerialPort {
163 path: String,
164 peripheral: Peripheral,
165 rx_char: Characteristic,
166 tx_char: Characteristic,
167 pacer: WritePacer,
168 rx: Mutex<RxQueue>,
169 connected: Arc<AtomicBool>,
170 baud_rate: u32,
171 data_bits: DataBits,
172 flow_control: FlowControl,
173 parity: Parity,
174 stop_bits: StopBits,
175 timeout: Duration,
176}
177
178impl BleSerialPort {
179 #[allow(clippy::too_many_arguments)]
180 pub fn connect(
181 path: &str,
182 baud_rate: u32,
183 data_bits: DataBits,
184 flow_control: FlowControl,
185 parity: Parity,
186 stop_bits: StopBits,
187 timeout: Duration,
188 ) -> io::Result<Self> {
189 let target = ble_target(path)
190 .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "not a ble:// path"))?
191 .to_string();
192 runtime().block_on(async {
193 let adapter = adapter().await?;
194 let peripheral = find_peripheral(&adapter, &target, Duration::from_secs(10)).await?;
195 let opened =
196 tokio::time::timeout(CONNECT_TIMEOUT, open_nus(&adapter, &peripheral, &target))
197 .await;
198 let (rx_char, tx_char, rx, connected) = match opened {
199 Ok(Ok(v)) => v,
200 Ok(Err(e)) => {
201 let _ = peripheral.disconnect().await;
202 return Err(e);
203 }
204 Err(_) => {
205 let _ = peripheral.disconnect().await;
207 return Err(io::Error::new(
208 io::ErrorKind::TimedOut,
209 format!(
210 "BLE open of {target} timed out after {} s",
211 CONNECT_TIMEOUT.as_secs()
212 ),
213 ));
214 }
215 };
216 Ok(Self {
217 path: path.to_string(),
218 peripheral,
219 rx_char,
220 tx_char,
221 pacer: WritePacer::default(),
222 rx: Mutex::new(rx),
223 connected,
224 baud_rate,
225 data_bits,
226 flow_control,
227 parity,
228 stop_bits,
229 timeout,
230 })
231 })
232 }
233}
234
235async fn open_nus(
239 adapter: &Adapter,
240 peripheral: &Peripheral,
241 target: &str,
242) -> io::Result<(Characteristic, Characteristic, RxQueue, Arc<AtomicBool>)> {
243 peripheral.connect().await.map_err(ble_err)?;
244 peripheral.discover_services().await.map_err(ble_err)?;
245 let chars = peripheral.characteristics();
246 let find = |uuid| {
247 chars
248 .iter()
249 .find(|c| c.uuid == uuid)
250 .cloned()
251 .ok_or_else(|| {
252 io::Error::new(
253 io::ErrorKind::NotFound,
254 format!("{target} has no Nordic UART characteristic {uuid}"),
255 )
256 })
257 };
258 let rx_char = find(NUS_RX)?;
259 let tx_char = find(NUS_TX)?;
260 let mut notes = peripheral.notifications().await.map_err(ble_err)?;
261 let mut events = adapter.events().await.map_err(ble_err)?;
262 peripheral.subscribe(&tx_char).await.map_err(ble_err)?;
264
265 let (feed, rx) = rx_channel(RX_QUEUE_CAP);
266 let connected = Arc::new(AtomicBool::new(true));
267 let id = peripheral.id();
268 let alive = connected.clone();
269 tokio::spawn(async move {
272 loop {
273 tokio::select! {
274 n = notes.next() => match n {
275 Some(n) if n.uuid == NUS_TX => { feed.push(n.value); }
276 Some(_) => {}
277 None => break,
278 },
279 e = events.next() => match e {
280 Some(CentralEvent::DeviceDisconnected(d)) if d == id => break,
281 Some(_) => {}
282 None => break,
283 },
284 }
285 }
286 alive.store(false, Ordering::SeqCst);
287 });
288 Ok((rx_char, tx_char, rx, connected))
289}
290
291async fn find_peripheral(
292 adapter: &Adapter,
293 target: &str,
294 limit: Duration,
295) -> io::Result<Peripheral> {
296 adapter
299 .start_scan(ScanFilter::default())
300 .await
301 .map_err(ble_err)?;
302 let deadline = Instant::now() + limit;
303 let mut name_seen = None;
304 let found = loop {
305 let peripherals = adapter.peripherals().await.map_err(ble_err)?;
306 let mut seen = Vec::with_capacity(peripherals.len());
307 for p in &peripherals {
308 let name = match p.properties().await {
309 Ok(Some(props)) => props.local_name,
310 _ => None,
311 };
312 seen.push(Candidate {
313 id: p.id().to_string(),
314 address: p.address().to_string(),
315 name,
316 });
317 }
318 match scan_step(&seen, target, &mut name_seen, Instant::now(), deadline) {
319 None => {}
320 Some(Ok(Some(i))) => break Ok(Some(peripherals[i].clone())),
321 Some(other) => break other.map(|_| None),
322 }
323 tokio::time::sleep(Duration::from_millis(200)).await;
324 };
325 let _ = adapter.stop_scan().await;
326 found
327 .map_err(|msg| io::Error::new(io::ErrorKind::InvalidInput, msg))?
328 .ok_or_else(|| {
329 io::Error::new(
330 io::ErrorKind::NotFound,
331 format!("no BLE device '{target}' found (id, MAC or advertised name)"),
332 )
333 })
334}
335
336const NAME_SETTLE: Duration = Duration::from_millis(1500);
339
340fn scan_step(
345 seen: &[Candidate],
346 target: &str,
347 name_seen: &mut Option<Instant>,
348 now: Instant,
349 deadline: Instant,
350) -> Option<Result<Option<usize>, String>> {
351 match pick_peripheral(seen, target) {
352 Err(e) => Some(Err(e)),
353 Ok(Some(i)) if target_matches(&seen[i].id, &seen[i].address, None, target) => {
354 Some(Ok(Some(i)))
355 }
356 Ok(Some(i)) => {
357 let first = *name_seen.get_or_insert(now);
358 (now >= first + NAME_SETTLE || now >= deadline).then_some(Ok(Some(i)))
359 }
360 Ok(None) => (now >= deadline).then_some(Ok(None)),
361 }
362}
363
364#[derive(Debug, Clone, PartialEq, Eq)]
366struct Candidate {
367 id: String,
368 address: String,
369 name: Option<String>,
370}
371
372fn pick_peripheral(seen: &[Candidate], target: &str) -> Result<Option<usize>, String> {
378 if let Some(i) = seen
379 .iter()
380 .position(|c| target_matches(&c.id, &c.address, None, target))
381 {
382 return Ok(Some(i));
383 }
384 let named: Vec<&Candidate> = seen
385 .iter()
386 .filter(|c| c.name.as_deref() == Some(target))
387 .collect();
388 match named[..] {
389 [] => Ok(None),
390 [_] => Ok(seen.iter().position(|c| c.name.as_deref() == Some(target))),
391 _ => Err(format!(
392 "{} BLE devices are named '{target}'; open one by id: {}",
393 named.len(),
394 named
395 .iter()
396 .map(|c| {
397 let id = if c.address == "00:00:00:00:00:00" {
398 &c.id
399 } else {
400 &c.address
401 };
402 format!("{BLE_SCHEME}{id}")
403 })
404 .collect::<Vec<_>>()
405 .join(", ")
406 )),
407 }
408}
409
410fn block_on_write(
414 write: impl std::future::Future<Output = btleplug::Result<()>>,
415 limit: Duration,
416 on_timeout: impl FnOnce(),
417) -> io::Result<()> {
418 match runtime().block_on(async { tokio::time::timeout(limit, write).await }) {
420 Ok(r) => r.map_err(ble_err),
421 Err(_) => {
422 on_timeout();
423 Err(io::Error::new(
424 io::ErrorKind::TimedOut,
425 format!("BLE write timed out after {} ms", limit.as_millis()),
426 ))
427 }
428 }
429}
430
431impl Drop for BleSerialPort {
432 fn drop(&mut self) {
433 let (p, tx) = (self.peripheral.clone(), self.tx_char.clone());
434 runtime().spawn(async move {
437 let _ = p.unsubscribe(&tx).await;
438 let _ = p.disconnect().await;
439 });
440 }
441}
442
443impl Read for BleSerialPort {
444 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
445 let timeout = self.timeout;
446 crate::sync_util::lock_or_recover(&self.rx).read(buf, timeout)
447 }
448}
449
450impl Write for BleSerialPort {
451 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
452 if !self.connected.load(Ordering::SeqCst) {
453 return Err(io::Error::new(
454 io::ErrorKind::BrokenPipe,
455 "BLE device disconnected",
456 ));
457 }
458 let n = buf.len().min(chunk_size(self.peripheral.mtu()));
459 let props = self.rx_char.properties;
460 let t = if self.pacer.with_response(
461 props.contains(CharPropFlags::WRITE),
462 props.contains(CharPropFlags::WRITE_WITHOUT_RESPONSE),
463 ) {
464 WriteType::WithResponse
465 } else {
466 WriteType::WithoutResponse
467 };
468 let (p, c) = (&self.peripheral, &self.rx_char);
469 block_on_write(p.write(c, &buf[..n], t), WRITE_TIMEOUT, || {
470 self.connected.store(false, Ordering::SeqCst);
473 let p = self.peripheral.clone();
474 runtime().spawn(async move {
475 let _ = p.disconnect().await;
476 });
477 })?;
478 Ok(n)
479 }
480
481 fn flush(&mut self) -> io::Result<()> {
482 Ok(())
483 }
484}
485
486impl SerialPort for BleSerialPort {
487 fn name(&self) -> Option<String> {
488 Some(self.path.clone())
489 }
490 fn baud_rate(&self) -> serialport::Result<u32> {
491 Ok(self.baud_rate)
492 }
493 fn data_bits(&self) -> serialport::Result<DataBits> {
494 Ok(self.data_bits)
495 }
496 fn flow_control(&self) -> serialport::Result<FlowControl> {
497 Ok(self.flow_control)
498 }
499 fn parity(&self) -> serialport::Result<Parity> {
500 Ok(self.parity)
501 }
502 fn stop_bits(&self) -> serialport::Result<StopBits> {
503 Ok(self.stop_bits)
504 }
505 fn timeout(&self) -> Duration {
506 self.timeout
507 }
508 fn set_baud_rate(&mut self, v: u32) -> serialport::Result<()> {
509 self.baud_rate = v;
510 Ok(())
511 }
512 fn set_data_bits(&mut self, v: DataBits) -> serialport::Result<()> {
513 self.data_bits = v;
514 Ok(())
515 }
516 fn set_flow_control(&mut self, v: FlowControl) -> serialport::Result<()> {
517 self.flow_control = v;
518 Ok(())
519 }
520 fn set_parity(&mut self, v: Parity) -> serialport::Result<()> {
521 self.parity = v;
522 Ok(())
523 }
524 fn set_stop_bits(&mut self, v: StopBits) -> serialport::Result<()> {
525 self.stop_bits = v;
526 Ok(())
527 }
528 fn set_timeout(&mut self, v: Duration) -> serialport::Result<()> {
529 self.timeout = v;
530 Ok(())
531 }
532 fn write_request_to_send(&mut self, _: bool) -> serialport::Result<()> {
533 Ok(())
534 }
535 fn write_data_terminal_ready(&mut self, _: bool) -> serialport::Result<()> {
536 Ok(())
537 }
538 fn read_clear_to_send(&mut self) -> serialport::Result<bool> {
539 Ok(true)
540 }
541 fn read_data_set_ready(&mut self) -> serialport::Result<bool> {
542 Ok(self.connected.load(Ordering::SeqCst))
543 }
544 fn read_ring_indicator(&mut self) -> serialport::Result<bool> {
545 Ok(false)
546 }
547 fn read_carrier_detect(&mut self) -> serialport::Result<bool> {
548 Ok(self.connected.load(Ordering::SeqCst))
549 }
550 fn bytes_to_read(&self) -> serialport::Result<u32> {
551 Ok(crate::sync_util::lock_or_recover(&self.rx).buffered() as u32)
552 }
553 fn bytes_to_write(&self) -> serialport::Result<u32> {
554 Ok(0)
555 }
556 fn clear(&self, which: ClearBuffer) -> serialport::Result<()> {
557 if !matches!(which, ClearBuffer::Output) {
558 crate::sync_util::lock_or_recover(&self.rx).clear();
559 }
560 Ok(())
561 }
562 fn try_clone(&self) -> serialport::Result<Box<dyn SerialPort>> {
563 Err(serialport::Error::new(
564 serialport::ErrorKind::Unknown,
565 "a BLE port cannot be cloned",
566 ))
567 }
568 fn set_break(&self) -> serialport::Result<()> {
569 Ok(())
570 }
571 fn clear_break(&self) -> serialport::Result<()> {
572 Ok(())
573 }
574}
575
576#[cfg(test)]
577mod tests {
578 use super::*;
579
580 #[test]
581 fn write_chunks_follow_mtu() {
582 assert_eq!(chunk_size(247), 244);
583 assert_eq!(chunk_size(517), 512);
584 assert_eq!(ble_target("ble://AA:BB"), Some("AA:BB"));
585 assert_eq!(ble_target("/dev/ttyUSB0"), None);
586 }
587}
588
589#[cfg(test)]
590mod selection_tests {
591 use super::*;
592
593 fn dev(id: &str, mac: &str, name: Option<&str>) -> Candidate {
594 Candidate {
595 id: id.into(),
596 address: mac.into(),
597 name: name.map(Into::into),
598 }
599 }
600
601 #[test]
602 fn id_or_mac_wins_over_a_name() {
603 let found = [
604 dev("uuid-1", "00:00:00:00:00:00", Some("AA:BB:CC:DD:EE:FF")),
605 dev("uuid-2", "AA:BB:CC:DD:EE:FF", Some("board")),
606 ];
607 assert_eq!(pick_peripheral(&found, "aa:bb:cc:dd:ee:ff"), Ok(Some(1)));
608 assert_eq!(pick_peripheral(&found, "UUID-1"), Ok(Some(0)));
609 }
610
611 #[test]
612 fn a_unique_name_is_used() {
613 let found = [
614 dev("uuid-1", "00:00:00:00:00:00", Some("left")),
615 dev("uuid-2", "00:00:00:00:00:00", Some("right")),
616 ];
617 assert_eq!(pick_peripheral(&found, "right"), Ok(Some(1)));
618 assert_eq!(pick_peripheral(&found, "nothing"), Ok(None));
619 }
620
621 #[test]
622 fn a_shared_name_is_an_error_listing_the_candidates() {
623 let found = [
624 dev("uuid-1", "00:00:00:00:00:00", Some("NUS")),
625 dev("uuid-2", "00:00:00:00:00:00", Some("other")),
626 dev("uuid-3", "00:00:00:00:00:00", Some("NUS")),
627 ];
628 let err = pick_peripheral(&found, "NUS").unwrap_err();
629 assert!(err.contains("ble://uuid-1"), "{err}");
630 assert!(err.contains("ble://uuid-3"), "{err}");
631 assert!(!err.contains("uuid-2"), "{err}");
632 }
633
634 #[test]
635 fn a_stuck_write_times_out_and_drops_the_link() {
636 let started = Instant::now();
637 let dropped = std::cell::Cell::new(0);
638 let err = block_on_write(
639 std::future::pending::<btleplug::Result<()>>(),
640 Duration::from_millis(50),
641 || dropped.set(dropped.get() + 1),
642 )
643 .unwrap_err();
644 assert_eq!(err.kind(), io::ErrorKind::TimedOut);
645 assert!(started.elapsed() < Duration::from_secs(2));
646 assert_eq!(dropped.get(), 1, "a timed-out write must reset the link");
647 assert!(
648 block_on_write(async { Ok(()) }, Duration::from_millis(50), || {
649 dropped.set(dropped.get() + 1)
650 })
651 .is_ok()
652 );
653 assert_eq!(dropped.get(), 1);
654 }
655
656 #[test]
659 fn a_name_waits_for_the_scan_window() {
660 let t0 = Instant::now();
661 let deadline = t0 + Duration::from_secs(10);
662 let one = [dev("uuid-1", "00:00:00:00:00:00", Some("NUS"))];
663 let two = [
664 dev("uuid-1", "00:00:00:00:00:00", Some("NUS")),
665 dev("uuid-2", "00:00:00:00:00:00", Some("NUS")),
666 ];
667 let mut first = None;
668 assert_eq!(scan_step(&one, "NUS", &mut first, t0, deadline), None);
669 let later = t0 + Duration::from_millis(400);
670 assert!(matches!(
671 scan_step(&two, "NUS", &mut first, later, deadline),
672 Some(Err(_))
673 ));
674 let mut first = None;
675 assert_eq!(scan_step(&one, "NUS", &mut first, t0, deadline), None);
676 let settled = t0 + NAME_SETTLE;
677 assert_eq!(
678 scan_step(&one, "NUS", &mut first, settled, deadline),
679 Some(Ok(Some(0)))
680 );
681 let mut first = None;
683 assert_eq!(
684 scan_step(&one, "uuid-1", &mut first, t0, deadline),
685 Some(Ok(Some(0)))
686 );
687 let mut first = None;
689 assert_eq!(
690 scan_step(&one, "NUS", &mut first, deadline, deadline),
691 Some(Ok(Some(0)))
692 );
693 }
694}