Skip to main content

serialplugin_core/port/
ble_rx.rs

1//! Pieces shared by the btleplug BLE port (desktop/iOS) and the Android GATT port:
2//! the `ble://` scheme and the notification โ†’ `Read` queue.
3
4use std::io;
5use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
6use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender};
7use std::sync::Arc;
8use std::time::Duration;
9
10pub const BLE_SCHEME: &str = "ble://";
11
12/// Notification bytes a [`rx_channel`] port keeps queued but unread. Past this the
13/// newest chunks are dropped (with one warning per overflow run): a port that is open
14/// but not read must not grow without bound. The hub normally reads all the time.
15pub(crate) const RX_QUEUE_CAP: usize = 1 << 20;
16
17/// Largest attribute value (Core spec Vol 3 Part F ยง3.2.9): a write longer than this
18/// fails or is cut, whatever the MTU.
19const MAX_ATTRIBUTE_LEN: usize = 512;
20
21/// Bytes per ATT write: MTU minus the 3-byte ATT header (default MTU 23), at most 512.
22#[cfg_attr(target_os = "android", allow(dead_code))] // Android chunks in Kotlin
23pub(crate) fn chunk_size(mtu: u16) -> usize {
24    (usize::from(mtu.max(23)) - 3).min(MAX_ATTRIBUTE_LEN)
25}
26
27/// Every Nth chunk is written with response when RX allows both write types, so the
28/// peripheral can push back before its buffer overflows (as Adafruit's UART apps do).
29pub(crate) const WRITE_PACE_EVERY: usize = 8;
30
31/// Chooses the write type per chunk (see [`WRITE_PACE_EVERY`]).
32#[derive(Debug, Default)]
33#[cfg_attr(target_os = "android", allow(dead_code))]
34pub(crate) struct WritePacer {
35    sent: usize,
36}
37
38#[cfg_attr(target_os = "android", allow(dead_code))]
39impl WritePacer {
40    /// Whether the next chunk is written with response.
41    pub(crate) fn with_response(&mut self, can_with: bool, can_without: bool) -> bool {
42        self.sent += 1;
43        match (can_with, can_without) {
44            (true, true) => self.sent.is_multiple_of(WRITE_PACE_EVERY),
45            (_, false) => true,
46            (false, true) => false,
47        }
48    }
49}
50
51/// `ble://<target>` names this device: its platform id (case-insensitive), its MAC
52/// (case-insensitive; Apple hides it as all zeros) or its advertised name (exact).
53#[cfg_attr(target_os = "android", allow(dead_code))]
54pub(crate) fn target_matches(id: &str, address: &str, name: Option<&str>, target: &str) -> bool {
55    id.eq_ignore_ascii_case(target)
56        || (address != "00:00:00:00:00:00" && address.eq_ignore_ascii_case(target))
57        || name == Some(target)
58}
59
60/// `ble://<id>` โ†’ `<id>`, or `None` for other paths.
61pub fn ble_target(path: &str) -> Option<&str> {
62    path.strip_prefix(BLE_SCHEME)
63}
64
65/// Sender half of [`rx_channel`]: never blocks (it runs on a Bluetooth binder thread).
66pub(crate) struct RxFeed {
67    tx: Sender<Vec<u8>>,
68    queued: Arc<AtomicUsize>,
69    cap: usize,
70    dropping: AtomicBool,
71}
72
73impl RxFeed {
74    /// Queue `chunk`; `false` when it was dropped because the queue is at its cap.
75    pub(crate) fn push(&self, chunk: Vec<u8>) -> bool {
76        let n = chunk.len();
77        if self.queued.load(Ordering::Acquire) + n > self.cap {
78            // Warn once per overflow run.
79            if self.dropping.swap(true, Ordering::Relaxed) {
80                return false;
81            }
82            crate::log_warn!(
83                "[BLE] RX queue full ({} bytes unread): dropping notifications until it is read",
84                self.cap
85            );
86            return false;
87        }
88        self.dropping.store(false, Ordering::Relaxed);
89        self.queued.fetch_add(n, Ordering::AcqRel);
90        if self.tx.send(chunk).is_err() {
91            self.queued.fetch_sub(n, Ordering::AcqRel);
92        }
93        true
94    }
95}
96
97/// A byte-capped notification queue; [`RxQueue::buffered`] counts queued chunks too.
98pub(crate) fn rx_channel(cap: usize) -> (RxFeed, RxQueue) {
99    let (tx, rx) = mpsc::channel();
100    let queued = Arc::new(AtomicUsize::new(0));
101    let feed = RxFeed {
102        tx,
103        queued: queued.clone(),
104        cap,
105        dropping: AtomicBool::new(false),
106    };
107    let mut q = RxQueue::new(rx);
108    q.queued = Some(queued);
109    (feed, q)
110}
111
112/// Notification chunks โ†’ `Read` with the serial timeout semantics the hub expects.
113/// Dropping the sender (device gone) turns the next read into `UnexpectedEof`,
114/// which the hub reports as `Disconnect`.
115pub(crate) struct RxQueue {
116    rx: Receiver<Vec<u8>>,
117    pending: Vec<u8>,
118    /// Bytes sent but not yet received (only for [`rx_channel`] queues).
119    queued: Option<Arc<AtomicUsize>>,
120}
121
122impl RxQueue {
123    pub(crate) fn new(rx: Receiver<Vec<u8>>) -> Self {
124        Self {
125            rx,
126            pending: Vec::new(),
127            queued: None,
128        }
129    }
130
131    fn took(&self, chunk: &[u8]) {
132        if let Some(q) = &self.queued {
133            q.fetch_sub(chunk.len(), Ordering::AcqRel);
134        }
135    }
136
137    pub(crate) fn read(&mut self, buf: &mut [u8], timeout: Duration) -> io::Result<usize> {
138        if self.pending.is_empty() {
139            match self.rx.recv_timeout(timeout.max(Duration::from_millis(1))) {
140                Ok(chunk) => {
141                    self.took(&chunk);
142                    if chunk.is_empty() {
143                        // An empty notification: no data, never `Ok(0)` (that is EOF).
144                        return Err(io::Error::new(io::ErrorKind::TimedOut, "BLE read timeout"));
145                    }
146                    self.pending = chunk;
147                }
148                Err(RecvTimeoutError::Timeout) => {
149                    return Err(io::Error::new(io::ErrorKind::TimedOut, "BLE read timeout"))
150                }
151                Err(RecvTimeoutError::Disconnected) => {
152                    return Err(io::Error::new(
153                        io::ErrorKind::UnexpectedEof,
154                        "BLE device disconnected",
155                    ))
156                }
157            }
158        }
159        let n = buf.len().min(self.pending.len());
160        buf[..n].copy_from_slice(&self.pending[..n]);
161        self.pending.drain(..n);
162        Ok(n)
163    }
164
165    pub(crate) fn clear(&mut self) {
166        self.pending.clear();
167        while let Ok(chunk) = self.rx.try_recv() {
168            self.took(&chunk);
169        }
170    }
171
172    /// Unread bytes: the split chunk plus, for [`rx_channel`] queues, the queued ones.
173    pub(crate) fn buffered(&self) -> usize {
174        self.pending.len()
175            + self
176                .queued
177                .as_ref()
178                .map_or(0, |q| q.load(Ordering::Acquire))
179    }
180}
181
182#[cfg(test)]
183mod tests {
184    //! In `src/`: the link's queue and write rules are private; the port needs Bluetooth hardware.
185    use super::*;
186    use std::sync::mpsc;
187
188    #[test]
189    fn rx_queue_splits_chunks_and_reports_timeout_and_disconnect() {
190        let (tx, rx) = mpsc::channel();
191        let mut q = RxQueue::new(rx);
192        tx.send(b"hello".to_vec()).unwrap();
193        let mut buf = [0u8; 3];
194        assert_eq!(q.read(&mut buf, Duration::from_millis(10)).unwrap(), 3);
195        assert_eq!(&buf, b"hel");
196        assert_eq!(q.buffered(), 2);
197        assert_eq!(q.read(&mut buf, Duration::from_millis(10)).unwrap(), 2);
198        assert_eq!(&buf[..2], b"lo");
199        let e = q.read(&mut buf, Duration::from_millis(5)).unwrap_err();
200        assert_eq!(e.kind(), io::ErrorKind::TimedOut);
201        drop(tx);
202        let e = q.read(&mut buf, Duration::from_millis(5)).unwrap_err();
203        assert_eq!(e.kind(), io::ErrorKind::UnexpectedEof);
204        q.clear();
205    }
206
207    /// An empty notification is no data, not `Ok(0)` (the hub reads that as EOF).
208    #[test]
209    fn empty_notification_is_a_timeout_not_eof() {
210        let (tx, rx) = mpsc::channel();
211        let mut q = RxQueue::new(rx);
212        tx.send(Vec::new()).unwrap();
213        let mut buf = [0u8; 4];
214        let e = q.read(&mut buf, Duration::from_millis(10)).unwrap_err();
215        assert_eq!(e.kind(), io::ErrorKind::TimedOut);
216    }
217
218    #[test]
219    fn rx_channel_counts_queued_bytes_and_drops_over_cap() {
220        let (feed, mut q) = rx_channel(8);
221        assert!(feed.push(b"hello".to_vec()));
222        assert_eq!(q.buffered(), 5, "queued chunk counts before any read");
223        assert!(!feed.push(b"world".to_vec()), "5 + 5 > cap 8: dropped");
224        assert!(feed.push(b"abc".to_vec()));
225        assert_eq!(q.buffered(), 8);
226        let mut buf = [0u8; 2];
227        assert_eq!(q.read(&mut buf, Duration::from_millis(10)).unwrap(), 2);
228        assert_eq!(q.buffered(), 6, "3 pending + 3 queued");
229        assert!(feed.push(b"xy".to_vec()), "room again after a read");
230        q.clear();
231        assert_eq!(q.buffered(), 0);
232        let mut all = [0u8; 8];
233        let e = q.read(&mut all, Duration::from_millis(5)).unwrap_err();
234        assert_eq!(e.kind(), io::ErrorKind::TimedOut);
235        drop(feed);
236        let e = q.read(&mut all, Duration::from_millis(5)).unwrap_err();
237        assert_eq!(e.kind(), io::ErrorKind::UnexpectedEof);
238    }
239
240    #[test]
241    fn chunks_follow_mtu_capped_at_the_attribute_size() {
242        assert_eq!(chunk_size(23), 20);
243        assert_eq!(chunk_size(0), 20);
244        assert_eq!(chunk_size(247), 244);
245        // Android 14+ always negotiates 517; Linux / Windows report up to 527.
246        assert_eq!(chunk_size(517), 512);
247        assert_eq!(chunk_size(527), 512);
248    }
249
250    #[test]
251    fn every_eighth_chunk_waits_for_a_response_when_rx_allows_both() {
252        let mut p = WritePacer::default();
253        let got: Vec<bool> = (0..16).map(|_| p.with_response(true, true)).collect();
254        let want: Vec<bool> = (1..=16_usize)
255            .map(|i| i.is_multiple_of(WRITE_PACE_EVERY))
256            .collect();
257        assert_eq!(got, want);
258        let mut p = WritePacer::default();
259        assert!(
260            (0..9).all(|_| p.with_response(true, false)),
261            "no write-without-response"
262        );
263        let mut p = WritePacer::default();
264        assert!(
265            (0..9).all(|_| !p.with_response(false, true)),
266            "no write-with-response"
267        );
268    }
269
270    #[test]
271    fn target_matches_id_mac_in_any_case_or_name() {
272        let m = |t| target_matches("hci0/dev_AA_BB", "AA:BB:CC:DD:EE:FF", Some("Nus Board"), t);
273        assert!(m("hci0/dev_AA_BB"));
274        assert!(m("aa:bb:cc:dd:ee:ff"));
275        assert!(m("AA:BB:CC:DD:EE:FF"));
276        assert!(m("Nus Board"));
277        assert!(!m("nus board"), "names are exact");
278        assert!(!m("AA:BB"));
279        // Apple hides the MAC (all zero): never matches by address.
280        assert!(!target_matches(
281            "uuid",
282            "00:00:00:00:00:00",
283            None,
284            "00:00:00:00:00:00"
285        ));
286        assert!(target_matches(
287            "5D2A-UUID",
288            "00:00:00:00:00:00",
289            None,
290            "5d2a-uuid"
291        ));
292    }
293
294    #[test]
295    fn ble_target_strips_scheme() {
296        assert_eq!(ble_target("ble://AA:BB"), Some("AA:BB"));
297        assert_eq!(ble_target("/dev/ttyUSB0"), None);
298    }
299}