Skip to main content

serialplugin_core/port/
ble.rs

1//! Serial over Bluetooth LE: `ble://<device id, MAC or name>` using the Nordic UART
2//! Service (NUS), the de-facto "BLE serial" profile of nRF, ESP32 and Adafruit/BBC
3//! boards. (HM-10 / CC254x modules use service FFE0 instead and are not supported.)
4//!
5//! Built on `btleplug` behind the `ble` cargo feature (desktop + iOS). Bytes written
6//! go to the NUS RX characteristic in MTU-sized chunks; notifications on the TX
7//! characteristic become read data. Line settings and modem lines are stored only:
8//! a BLE UART has no baud rate or RTS/DTR.
9
10#[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);
29/// Central writes here.
30pub const NUS_RX: Uuid = Uuid::from_u128(0x6E400002_B5A3_F393_E0A9_E50E24DCCA9E);
31/// Peripheral notifies here.
32pub const NUS_TX: Uuid = Uuid::from_u128(0x6E400003_B5A3_F393_E0A9_E50E24DCCA9E);
33
34/// One runtime for all BLE work: btleplug's platform event loops live in it, and
35/// the sync serial API drives it with `block_on`.
36fn 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
52/// The whole `open()` (connect, service discovery, subscribe) must finish in this
53/// time: CoreBluetooth never times out a connect to an absent device by itself.
54const CONNECT_TIMEOUT: Duration = Duration::from_secs(20);
55
56/// One `write` (one MTU chunk) must finish in this time. A write with response to a
57/// device that went out of range otherwise waits for the OS supervision timeout,
58/// with the port lock held by the caller.
59const WRITE_TIMEOUT: Duration = Duration::from_secs(5);
60
61/// How long a new adapter may stay in state Unknown before the first scan.
62const POWER_ON_WAIT: Duration = Duration::from_secs(2);
63
64/// One adapter for the process (one long-lived `CBCentralManager` on Apple, as Apple
65/// advises; a fresh one ignores scans until it reports its state).
66async 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            // A concurrent first call may have won; keep the stored one.
80            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
93/// What an adapter state means for opening: `None` = still Unknown, ask again (until
94/// `waited_enough`).
95fn 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
110/// Port id of a scanned device: the MAC where the platform has one (Linux's own id is
111/// a D-Bus path), else the platform id (a per-host UUID on Apple).
112fn 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
120/// Scan for devices advertising the Nordic UART Service.
121/// Returns `ble://<id>` → port-info map (same shape as `available_ports`).
122pub 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
149/// The `available_ports`-shaped entry of one scanned device, `None` when it does not
150/// advertise the Nordic UART Service.
151fn 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                    // Cancels the pending connect (CoreBluetooth keeps trying otherwise).
220                    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
249/// Connect, find the NUS characteristics and start notifications. The notification
250/// and event streams are taken before subscribing, so nothing sent right after the
251/// CCCD write is lost.
252async 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    // btleplug enables notify, or indicate when TX only indicates.
277    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    // Forward notifications until the device disconnects; dropping `feed` then turns
284    // the next read into UnexpectedEof (→ hub Disconnect).
285    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    // Unfiltered: many NUS firmwares do not advertise the 128-bit service UUID (the
311    // service is checked after connecting anyway).
312    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
350/// How long the scan goes on after a name first matched one device, so a second
351/// device with that name is still seen (and the name refused as ambiguous).
352const NAME_SETTLE: Duration = Duration::from_millis(1500);
353
354/// One scan pass: `None` = keep scanning. An id / MAC match is taken at once; a name
355/// that one device has is taken once it was seen for [`NAME_SETTLE`] (or at the
356/// deadline) and is an error as soon as a second device has it. `Some(Ok(None))`:
357/// nothing found by the deadline.
358fn 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/// A device seen by the scan, for [`pick_peripheral`].
379#[derive(Debug, Clone, PartialEq, Eq)]
380struct Candidate {
381    id: String,
382    address: String,
383    name: Option<String>,
384}
385
386/// Which scanned device `ble://<target>` names. A platform id or MAC match wins (both
387/// are unique). An advertised name is used only when exactly one device seen so far
388/// has it; several devices with that name are an error listing their `ble://` paths
389/// (MAC, or the platform id where the MAC is hidden), never "the first one the scan
390/// returned". `Ok(None)`: not seen (yet).
391fn 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
424/// Run one GATT write on the BLE runtime, bounded by `limit`. On a timeout
425/// `on_timeout` runs: the abandoned write may still complete later and could then be
426/// matched to the next write's future, so the link is dropped instead of reused.
427fn block_on_write(
428    write: impl std::future::Future<Output = btleplug::Result<()>>,
429    limit: Duration,
430    on_timeout: impl FnOnce(),
431) -> io::Result<()> {
432    // The timer must be created inside the runtime (it needs its time driver).
433    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        // Best effort: turn notifications off (BlueZ re-enables them on reconnect
449        // otherwise) and let the device advertise again for the next open.
450        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            // Fail later writes now; the disconnect ends the notification task, so
485            // reads see EOF and the hub reports `Disconnect` (reopen to go on).
486            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 tests {
592    use super::*;
593
594    #[test]
595    fn write_chunks_follow_mtu() {
596        assert_eq!(chunk_size(247), 244);
597        assert_eq!(chunk_size(517), 512);
598        assert_eq!(ble_target("ble://AA:BB"), Some("AA:BB"));
599        assert_eq!(ble_target("/dev/ttyUSB0"), None);
600    }
601}
602
603#[cfg(test)]
604mod adapter_tests {
605    use super::*;
606
607    #[test]
608    fn power_states() {
609        assert!(matches!(
610            power_state(CentralState::PoweredOn, false),
611            Some(Ok(()))
612        ));
613        assert!(matches!(
614            power_state(CentralState::PoweredOn, true),
615            Some(Ok(()))
616        ));
617        for waited in [false, true] {
618            let off = power_state(CentralState::PoweredOff, waited)
619                .unwrap()
620                .unwrap_err();
621            assert_eq!(off.kind(), io::ErrorKind::NotConnected);
622        }
623        assert!(power_state(CentralState::Unknown, false).is_none());
624        let unknown = power_state(CentralState::Unknown, true)
625            .unwrap()
626            .unwrap_err();
627        assert_eq!(unknown.kind(), io::ErrorKind::PermissionDenied);
628    }
629
630    #[test]
631    fn scan_lists_nus_devices_only() {
632        let other = Uuid::from_u128(0x180D);
633        assert_eq!(scan_entry("id-1", &[other], Some("hr".into()), None), None);
634        let (path, info) = scan_entry(
635            "id-2",
636            &[other, NUS_SERVICE],
637            Some("board".into()),
638            Some(-60),
639        )
640        .unwrap();
641        assert_eq!(path, "ble://id-2");
642        let get = |k: &str| info.get(k).cloned().unwrap();
643        assert_eq!(get("type"), "BLE");
644        assert_eq!(get("product"), "board");
645        assert_eq!(get("serial_number"), "id-2");
646        assert_eq!(get("rssi"), "-60");
647        for k in ["manufacturer", "vid", "pid"] {
648            assert_eq!(get(k), crate::state::UNKNOWN);
649        }
650        assert_eq!(info.len(), 7);
651        let (_, bare) = scan_entry("id-3", &[NUS_SERVICE], None, None).unwrap();
652        assert_eq!(bare["product"], crate::state::UNKNOWN);
653        assert_eq!(bare["rssi"], "");
654    }
655}
656
657#[cfg(test)]
658mod selection_tests {
659    use super::*;
660
661    fn dev(id: &str, mac: &str, name: Option<&str>) -> Candidate {
662        Candidate {
663            id: id.into(),
664            address: mac.into(),
665            name: name.map(Into::into),
666        }
667    }
668
669    #[test]
670    fn id_or_mac_wins_over_a_name() {
671        let found = [
672            dev("uuid-1", "00:00:00:00:00:00", Some("AA:BB:CC:DD:EE:FF")),
673            dev("uuid-2", "AA:BB:CC:DD:EE:FF", Some("board")),
674        ];
675        assert_eq!(pick_peripheral(&found, "aa:bb:cc:dd:ee:ff"), Ok(Some(1)));
676        assert_eq!(pick_peripheral(&found, "UUID-1"), Ok(Some(0)));
677    }
678
679    #[test]
680    fn a_unique_name_is_used() {
681        let found = [
682            dev("uuid-1", "00:00:00:00:00:00", Some("left")),
683            dev("uuid-2", "00:00:00:00:00:00", Some("right")),
684        ];
685        assert_eq!(pick_peripheral(&found, "right"), Ok(Some(1)));
686        assert_eq!(pick_peripheral(&found, "nothing"), Ok(None));
687    }
688
689    #[test]
690    fn a_shared_name_is_an_error_listing_the_candidates() {
691        let found = [
692            dev("uuid-1", "00:00:00:00:00:00", Some("NUS")),
693            dev("uuid-2", "00:00:00:00:00:00", Some("other")),
694            dev("uuid-3", "00:00:00:00:00:00", Some("NUS")),
695        ];
696        let err = pick_peripheral(&found, "NUS").unwrap_err();
697        assert!(err.contains("ble://uuid-1"), "{err}");
698        assert!(err.contains("ble://uuid-3"), "{err}");
699        assert!(!err.contains("uuid-2"), "{err}");
700    }
701
702    #[test]
703    fn a_stuck_write_times_out_and_drops_the_link() {
704        let started = Instant::now();
705        let dropped = std::cell::Cell::new(0);
706        let err = block_on_write(
707            std::future::pending::<btleplug::Result<()>>(),
708            Duration::from_millis(50),
709            || dropped.set(dropped.get() + 1),
710        )
711        .unwrap_err();
712        assert_eq!(err.kind(), io::ErrorKind::TimedOut);
713        assert!(started.elapsed() < Duration::from_secs(2));
714        assert_eq!(dropped.get(), 1, "a timed-out write must reset the link");
715        assert!(
716            block_on_write(async { Ok(()) }, Duration::from_millis(50), || {
717                dropped.set(dropped.get() + 1)
718            })
719            .is_ok()
720        );
721        assert_eq!(dropped.get(), 1);
722    }
723
724    /// A unique name is taken only after the settle window, so a second device with
725    /// that name seen later in the scan is still an error.
726    #[test]
727    fn a_name_waits_for_the_scan_window() {
728        let t0 = Instant::now();
729        let deadline = t0 + Duration::from_secs(10);
730        let one = [dev("uuid-1", "00:00:00:00:00:00", Some("NUS"))];
731        let two = [
732            dev("uuid-1", "00:00:00:00:00:00", Some("NUS")),
733            dev("uuid-2", "00:00:00:00:00:00", Some("NUS")),
734        ];
735        let mut first = None;
736        assert_eq!(scan_step(&one, "NUS", &mut first, t0, deadline), None);
737        let later = t0 + Duration::from_millis(400);
738        assert!(matches!(
739            scan_step(&two, "NUS", &mut first, later, deadline),
740            Some(Err(_))
741        ));
742        let mut first = None;
743        assert_eq!(scan_step(&one, "NUS", &mut first, t0, deadline), None);
744        let settled = t0 + NAME_SETTLE;
745        assert_eq!(
746            scan_step(&one, "NUS", &mut first, settled, deadline),
747            Some(Ok(Some(0)))
748        );
749        // An id match does not wait.
750        let mut first = None;
751        assert_eq!(
752            scan_step(&one, "uuid-1", &mut first, t0, deadline),
753            Some(Ok(Some(0)))
754        );
755        // Nothing seen: keep scanning until the deadline, then not found.
756        let mut first = None;
757        assert_eq!(scan_step(&[], "NUS", &mut first, t0, deadline), None);
758        assert_eq!(
759            scan_step(&[], "NUS", &mut first, deadline, deadline),
760            Some(Ok(None))
761        );
762        // The settle window never runs past the deadline.
763        let mut first = None;
764        assert_eq!(
765            scan_step(&one, "NUS", &mut first, deadline, deadline),
766            Some(Ok(Some(0)))
767        );
768    }
769}