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/// How long a new adapter may stay in state Unknown before the first scan.
57const POWER_ON_WAIT: Duration = Duration::from_secs(2);
58
59/// One adapter for the process (one long-lived `CBCentralManager` on Apple, as Apple
60/// advises; a fresh one ignores scans until it reports its state).
61async fn adapter() -> io::Result<Adapter> {
62    static ADAPTER: OnceLock<Adapter> = OnceLock::new();
63    let adapter = match ADAPTER.get() {
64        Some(a) => a.clone(),
65        None => {
66            let manager = Manager::new().await.map_err(ble_err)?;
67            let first = manager
68                .adapters()
69                .await
70                .map_err(ble_err)?
71                .into_iter()
72                .next()
73                .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no Bluetooth adapter"))?;
74            // A concurrent first call may have won; keep the stored one.
75            ADAPTER.get_or_init(|| first).clone()
76        }
77    };
78    let deadline = Instant::now() + POWER_ON_WAIT;
79    loop {
80        match adapter.adapter_state().await.map_err(ble_err)? {
81            CentralState::PoweredOn => return Ok(adapter),
82            CentralState::PoweredOff => {
83                return Err(io::Error::new(
84                    io::ErrorKind::NotConnected,
85                    "Bluetooth is off",
86                ))
87            }
88            CentralState::Unknown if Instant::now() < deadline => {
89                tokio::time::sleep(Duration::from_millis(50)).await
90            }
91            CentralState::Unknown => {
92                return Err(io::Error::new(
93                    io::ErrorKind::PermissionDenied,
94                    "Bluetooth is not available (off, or the app is not authorized to use it)",
95                ))
96            }
97        }
98    }
99}
100
101/// Port id of a scanned device: the MAC where the platform has one (Linux's own id is
102/// a D-Bus path), else the platform id (a per-host UUID on Apple).
103fn port_id(p: &Peripheral) -> String {
104    if cfg!(target_os = "linux") {
105        p.address().to_string()
106    } else {
107        p.id().to_string()
108    }
109}
110
111/// Scan for devices advertising the Nordic UART Service.
112/// Returns `ble://<id>` → port-info map (same shape as `available_ports`).
113pub fn scan(duration: Duration) -> io::Result<HashMap<String, HashMap<String, String>>> {
114    runtime().block_on(async {
115        let adapter = adapter().await?;
116        adapter
117            .start_scan(ScanFilter {
118                services: vec![NUS_SERVICE],
119            })
120            .await
121            .map_err(ble_err)?;
122        tokio::time::sleep(duration).await;
123        let _ = adapter.stop_scan().await;
124        let mut out = HashMap::new();
125        for p in adapter.peripherals().await.map_err(ble_err)? {
126            let Ok(Some(props)) = p.properties().await else {
127                continue;
128            };
129            if !props.services.contains(&NUS_SERVICE) {
130                continue;
131            }
132            let name = props
133                .local_name
134                .clone()
135                .unwrap_or_else(|| crate::state::UNKNOWN.to_string());
136            let info = HashMap::from([
137                ("type".to_string(), "BLE".to_string()),
138                ("product".to_string(), name),
139                (
140                    "manufacturer".to_string(),
141                    crate::state::UNKNOWN.to_string(),
142                ),
143                ("serial_number".to_string(), port_id(&p)),
144                ("vid".to_string(), crate::state::UNKNOWN.to_string()),
145                ("pid".to_string(), crate::state::UNKNOWN.to_string()),
146                (
147                    "rssi".to_string(),
148                    props.rssi.map(|r| r.to_string()).unwrap_or_default(),
149                ),
150            ]);
151            out.insert(format!("{BLE_SCHEME}{}", port_id(&p)), info);
152        }
153        Ok(out)
154    })
155}
156
157pub struct BleSerialPort {
158    path: String,
159    peripheral: Peripheral,
160    rx_char: Characteristic,
161    tx_char: Characteristic,
162    pacer: WritePacer,
163    rx: Mutex<RxQueue>,
164    connected: Arc<AtomicBool>,
165    baud_rate: u32,
166    data_bits: DataBits,
167    flow_control: FlowControl,
168    parity: Parity,
169    stop_bits: StopBits,
170    timeout: Duration,
171}
172
173impl BleSerialPort {
174    #[allow(clippy::too_many_arguments)]
175    pub fn connect(
176        path: &str,
177        baud_rate: u32,
178        data_bits: DataBits,
179        flow_control: FlowControl,
180        parity: Parity,
181        stop_bits: StopBits,
182        timeout: Duration,
183    ) -> io::Result<Self> {
184        let target = ble_target(path)
185            .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "not a ble:// path"))?
186            .to_string();
187        runtime().block_on(async {
188            let adapter = adapter().await?;
189            let peripheral = find_peripheral(&adapter, &target, Duration::from_secs(10)).await?;
190            let opened =
191                tokio::time::timeout(CONNECT_TIMEOUT, open_nus(&adapter, &peripheral, &target))
192                    .await;
193            let (rx_char, tx_char, rx, connected) = match opened {
194                Ok(Ok(v)) => v,
195                Ok(Err(e)) => {
196                    let _ = peripheral.disconnect().await;
197                    return Err(e);
198                }
199                Err(_) => {
200                    // Cancels the pending connect (CoreBluetooth keeps trying otherwise).
201                    let _ = peripheral.disconnect().await;
202                    return Err(io::Error::new(
203                        io::ErrorKind::TimedOut,
204                        format!(
205                            "BLE open of {target} timed out after {} s",
206                            CONNECT_TIMEOUT.as_secs()
207                        ),
208                    ));
209                }
210            };
211            Ok(Self {
212                path: path.to_string(),
213                peripheral,
214                rx_char,
215                tx_char,
216                pacer: WritePacer::default(),
217                rx: Mutex::new(rx),
218                connected,
219                baud_rate,
220                data_bits,
221                flow_control,
222                parity,
223                stop_bits,
224                timeout,
225            })
226        })
227    }
228}
229
230/// Connect, find the NUS characteristics and start notifications. The notification
231/// and event streams are taken before subscribing, so nothing sent right after the
232/// CCCD write is lost.
233async fn open_nus(
234    adapter: &Adapter,
235    peripheral: &Peripheral,
236    target: &str,
237) -> io::Result<(Characteristic, Characteristic, RxQueue, Arc<AtomicBool>)> {
238    peripheral.connect().await.map_err(ble_err)?;
239    peripheral.discover_services().await.map_err(ble_err)?;
240    let chars = peripheral.characteristics();
241    let find = |uuid| {
242        chars
243            .iter()
244            .find(|c| c.uuid == uuid)
245            .cloned()
246            .ok_or_else(|| {
247                io::Error::new(
248                    io::ErrorKind::NotFound,
249                    format!("{target} has no Nordic UART characteristic {uuid}"),
250                )
251            })
252    };
253    let rx_char = find(NUS_RX)?;
254    let tx_char = find(NUS_TX)?;
255    let mut notes = peripheral.notifications().await.map_err(ble_err)?;
256    let mut events = adapter.events().await.map_err(ble_err)?;
257    // btleplug enables notify, or indicate when TX only indicates.
258    peripheral.subscribe(&tx_char).await.map_err(ble_err)?;
259
260    let (feed, rx) = rx_channel(RX_QUEUE_CAP);
261    let connected = Arc::new(AtomicBool::new(true));
262    let id = peripheral.id();
263    let alive = connected.clone();
264    // Forward notifications until the device disconnects; dropping `feed` then turns
265    // the next read into UnexpectedEof (→ hub Disconnect).
266    tokio::spawn(async move {
267        loop {
268            tokio::select! {
269                n = notes.next() => match n {
270                    Some(n) if n.uuid == NUS_TX => { feed.push(n.value); }
271                    Some(_) => {}
272                    None => break,
273                },
274                e = events.next() => match e {
275                    Some(CentralEvent::DeviceDisconnected(d)) if d == id => break,
276                    Some(_) => {}
277                    None => break,
278                },
279            }
280        }
281        alive.store(false, Ordering::SeqCst);
282    });
283    Ok((rx_char, tx_char, rx, connected))
284}
285
286async fn find_peripheral(
287    adapter: &Adapter,
288    target: &str,
289    limit: Duration,
290) -> io::Result<Peripheral> {
291    // Unfiltered: many NUS firmwares do not advertise the 128-bit service UUID (the
292    // service is checked after connecting anyway).
293    adapter
294        .start_scan(ScanFilter::default())
295        .await
296        .map_err(ble_err)?;
297    let deadline = Instant::now() + limit;
298    let found = 'scan: loop {
299        for p in adapter.peripherals().await.map_err(ble_err)? {
300            let name = match p.properties().await {
301                Ok(Some(props)) => props.local_name,
302                _ => None,
303            };
304            let (id, address) = (p.id().to_string(), p.address().to_string());
305            if target_matches(&id, &address, name.as_deref(), target) {
306                break 'scan Some(p);
307            }
308        }
309        if Instant::now() >= deadline {
310            break None;
311        }
312        tokio::time::sleep(Duration::from_millis(200)).await;
313    };
314    let _ = adapter.stop_scan().await;
315    found.ok_or_else(|| {
316        io::Error::new(
317            io::ErrorKind::NotFound,
318            format!("no BLE device '{target}' found (id, MAC or advertised name)"),
319        )
320    })
321}
322
323impl Drop for BleSerialPort {
324    fn drop(&mut self) {
325        let (p, tx) = (self.peripheral.clone(), self.tx_char.clone());
326        // Best effort: turn notifications off (BlueZ re-enables them on reconnect
327        // otherwise) and let the device advertise again for the next open.
328        runtime().spawn(async move {
329            let _ = p.unsubscribe(&tx).await;
330            let _ = p.disconnect().await;
331        });
332    }
333}
334
335impl Read for BleSerialPort {
336    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
337        let timeout = self.timeout;
338        crate::sync_util::lock_or_recover(&self.rx).read(buf, timeout)
339    }
340}
341
342impl Write for BleSerialPort {
343    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
344        if !self.connected.load(Ordering::SeqCst) {
345            return Err(io::Error::new(
346                io::ErrorKind::BrokenPipe,
347                "BLE device disconnected",
348            ));
349        }
350        let n = buf.len().min(chunk_size(self.peripheral.mtu()));
351        let props = self.rx_char.properties;
352        let t = if self.pacer.with_response(
353            props.contains(CharPropFlags::WRITE),
354            props.contains(CharPropFlags::WRITE_WITHOUT_RESPONSE),
355        ) {
356            WriteType::WithResponse
357        } else {
358            WriteType::WithoutResponse
359        };
360        let (p, c) = (&self.peripheral, &self.rx_char);
361        runtime()
362            .block_on(p.write(c, &buf[..n], t))
363            .map_err(ble_err)?;
364        Ok(n)
365    }
366
367    fn flush(&mut self) -> io::Result<()> {
368        Ok(())
369    }
370}
371
372impl SerialPort for BleSerialPort {
373    fn name(&self) -> Option<String> {
374        Some(self.path.clone())
375    }
376    fn baud_rate(&self) -> serialport::Result<u32> {
377        Ok(self.baud_rate)
378    }
379    fn data_bits(&self) -> serialport::Result<DataBits> {
380        Ok(self.data_bits)
381    }
382    fn flow_control(&self) -> serialport::Result<FlowControl> {
383        Ok(self.flow_control)
384    }
385    fn parity(&self) -> serialport::Result<Parity> {
386        Ok(self.parity)
387    }
388    fn stop_bits(&self) -> serialport::Result<StopBits> {
389        Ok(self.stop_bits)
390    }
391    fn timeout(&self) -> Duration {
392        self.timeout
393    }
394    fn set_baud_rate(&mut self, v: u32) -> serialport::Result<()> {
395        self.baud_rate = v;
396        Ok(())
397    }
398    fn set_data_bits(&mut self, v: DataBits) -> serialport::Result<()> {
399        self.data_bits = v;
400        Ok(())
401    }
402    fn set_flow_control(&mut self, v: FlowControl) -> serialport::Result<()> {
403        self.flow_control = v;
404        Ok(())
405    }
406    fn set_parity(&mut self, v: Parity) -> serialport::Result<()> {
407        self.parity = v;
408        Ok(())
409    }
410    fn set_stop_bits(&mut self, v: StopBits) -> serialport::Result<()> {
411        self.stop_bits = v;
412        Ok(())
413    }
414    fn set_timeout(&mut self, v: Duration) -> serialport::Result<()> {
415        self.timeout = v;
416        Ok(())
417    }
418    fn write_request_to_send(&mut self, _: bool) -> serialport::Result<()> {
419        Ok(())
420    }
421    fn write_data_terminal_ready(&mut self, _: bool) -> serialport::Result<()> {
422        Ok(())
423    }
424    fn read_clear_to_send(&mut self) -> serialport::Result<bool> {
425        Ok(true)
426    }
427    fn read_data_set_ready(&mut self) -> serialport::Result<bool> {
428        Ok(self.connected.load(Ordering::SeqCst))
429    }
430    fn read_ring_indicator(&mut self) -> serialport::Result<bool> {
431        Ok(false)
432    }
433    fn read_carrier_detect(&mut self) -> serialport::Result<bool> {
434        Ok(self.connected.load(Ordering::SeqCst))
435    }
436    fn bytes_to_read(&self) -> serialport::Result<u32> {
437        Ok(crate::sync_util::lock_or_recover(&self.rx).buffered() as u32)
438    }
439    fn bytes_to_write(&self) -> serialport::Result<u32> {
440        Ok(0)
441    }
442    fn clear(&self, which: ClearBuffer) -> serialport::Result<()> {
443        if !matches!(which, ClearBuffer::Output) {
444            crate::sync_util::lock_or_recover(&self.rx).clear();
445        }
446        Ok(())
447    }
448    fn try_clone(&self) -> serialport::Result<Box<dyn SerialPort>> {
449        Err(serialport::Error::new(
450            serialport::ErrorKind::Unknown,
451            "a BLE port cannot be cloned",
452        ))
453    }
454    fn set_break(&self) -> serialport::Result<()> {
455        Ok(())
456    }
457    fn clear_break(&self) -> serialport::Result<()> {
458        Ok(())
459    }
460}
461
462#[cfg(test)]
463mod tests {
464    use super::*;
465
466    #[test]
467    fn write_chunks_follow_mtu() {
468        assert_eq!(chunk_size(247), 244);
469        assert_eq!(chunk_size(517), 512);
470        assert_eq!(ble_target("ble://AA:BB"), Some("AA:BB"));
471        assert_eq!(ble_target("/dev/ttyUSB0"), None);
472    }
473}