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            if !self.dropping.swap(true, Ordering::Relaxed) {
79                crate::log_warn!(
80                    "[BLE] RX queue full ({} bytes unread): dropping notifications until it is read",
81                    self.cap
82                );
83            }
84            return false;
85        }
86        self.dropping.store(false, Ordering::Relaxed);
87        self.queued.fetch_add(n, Ordering::AcqRel);
88        if self.tx.send(chunk).is_err() {
89            self.queued.fetch_sub(n, Ordering::AcqRel);
90        }
91        true
92    }
93}
94
95/// A byte-capped notification queue; [`RxQueue::buffered`] counts queued chunks too.
96pub(crate) fn rx_channel(cap: usize) -> (RxFeed, RxQueue) {
97    let (tx, rx) = mpsc::channel();
98    let queued = Arc::new(AtomicUsize::new(0));
99    let feed = RxFeed {
100        tx,
101        queued: queued.clone(),
102        cap,
103        dropping: AtomicBool::new(false),
104    };
105    let mut q = RxQueue::new(rx);
106    q.queued = Some(queued);
107    (feed, q)
108}
109
110/// Notification chunks โ†’ `Read` with the serial timeout semantics the hub expects.
111/// Dropping the sender (device gone) turns the next read into `UnexpectedEof`,
112/// which the hub reports as `Disconnect`.
113pub(crate) struct RxQueue {
114    rx: Receiver<Vec<u8>>,
115    pending: Vec<u8>,
116    /// Bytes sent but not yet received (only for [`rx_channel`] queues).
117    queued: Option<Arc<AtomicUsize>>,
118}
119
120impl RxQueue {
121    pub(crate) fn new(rx: Receiver<Vec<u8>>) -> Self {
122        Self {
123            rx,
124            pending: Vec::new(),
125            queued: None,
126        }
127    }
128
129    fn took(&self, chunk: &[u8]) {
130        if let Some(q) = &self.queued {
131            q.fetch_sub(chunk.len(), Ordering::AcqRel);
132        }
133    }
134
135    pub(crate) fn read(&mut self, buf: &mut [u8], timeout: Duration) -> io::Result<usize> {
136        if self.pending.is_empty() {
137            match self.rx.recv_timeout(timeout.max(Duration::from_millis(1))) {
138                Ok(chunk) => {
139                    self.took(&chunk);
140                    if chunk.is_empty() {
141                        // An empty notification: no data, never `Ok(0)` (that is EOF).
142                        return Err(io::Error::new(io::ErrorKind::TimedOut, "BLE read timeout"));
143                    }
144                    self.pending = chunk;
145                }
146                Err(RecvTimeoutError::Timeout) => {
147                    return Err(io::Error::new(io::ErrorKind::TimedOut, "BLE read timeout"))
148                }
149                Err(RecvTimeoutError::Disconnected) => {
150                    return Err(io::Error::new(
151                        io::ErrorKind::UnexpectedEof,
152                        "BLE device disconnected",
153                    ))
154                }
155            }
156        }
157        let n = buf.len().min(self.pending.len());
158        buf[..n].copy_from_slice(&self.pending[..n]);
159        self.pending.drain(..n);
160        Ok(n)
161    }
162
163    pub(crate) fn clear(&mut self) {
164        self.pending.clear();
165        while let Ok(chunk) = self.rx.try_recv() {
166            self.took(&chunk);
167        }
168    }
169
170    /// Unread bytes: the split chunk plus, for [`rx_channel`] queues, the queued ones.
171    pub(crate) fn buffered(&self) -> usize {
172        self.pending.len()
173            + self
174                .queued
175                .as_ref()
176                .map_or(0, |q| q.load(Ordering::Acquire))
177    }
178}
179
180#[cfg(test)]
181mod tests {
182    use super::*;
183    use std::sync::mpsc;
184
185    #[test]
186    fn rx_queue_splits_chunks_and_reports_timeout_and_disconnect() {
187        let (tx, rx) = mpsc::channel();
188        let mut q = RxQueue::new(rx);
189        tx.send(b"hello".to_vec()).unwrap();
190        let mut buf = [0u8; 3];
191        assert_eq!(q.read(&mut buf, Duration::from_millis(10)).unwrap(), 3);
192        assert_eq!(&buf, b"hel");
193        assert_eq!(q.buffered(), 2);
194        assert_eq!(q.read(&mut buf, Duration::from_millis(10)).unwrap(), 2);
195        assert_eq!(&buf[..2], b"lo");
196        let e = q.read(&mut buf, Duration::from_millis(5)).unwrap_err();
197        assert_eq!(e.kind(), io::ErrorKind::TimedOut);
198        drop(tx);
199        let e = q.read(&mut buf, Duration::from_millis(5)).unwrap_err();
200        assert_eq!(e.kind(), io::ErrorKind::UnexpectedEof);
201        q.clear();
202    }
203
204    /// An empty notification is no data, not `Ok(0)` (the hub reads that as EOF).
205    #[test]
206    fn empty_notification_is_a_timeout_not_eof() {
207        let (tx, rx) = mpsc::channel();
208        let mut q = RxQueue::new(rx);
209        tx.send(Vec::new()).unwrap();
210        let mut buf = [0u8; 4];
211        let e = q.read(&mut buf, Duration::from_millis(10)).unwrap_err();
212        assert_eq!(e.kind(), io::ErrorKind::TimedOut);
213    }
214
215    #[test]
216    fn rx_channel_counts_queued_bytes_and_drops_over_cap() {
217        let (feed, mut q) = rx_channel(8);
218        assert!(feed.push(b"hello".to_vec()));
219        assert_eq!(q.buffered(), 5, "queued chunk counts before any read");
220        assert!(!feed.push(b"world".to_vec()), "5 + 5 > cap 8: dropped");
221        assert!(feed.push(b"abc".to_vec()));
222        assert_eq!(q.buffered(), 8);
223        let mut buf = [0u8; 2];
224        assert_eq!(q.read(&mut buf, Duration::from_millis(10)).unwrap(), 2);
225        assert_eq!(q.buffered(), 6, "3 pending + 3 queued");
226        assert!(feed.push(b"xy".to_vec()), "room again after a read");
227        q.clear();
228        assert_eq!(q.buffered(), 0);
229        let mut all = [0u8; 8];
230        let e = q.read(&mut all, Duration::from_millis(5)).unwrap_err();
231        assert_eq!(e.kind(), io::ErrorKind::TimedOut);
232        drop(feed);
233        let e = q.read(&mut all, Duration::from_millis(5)).unwrap_err();
234        assert_eq!(e.kind(), io::ErrorKind::UnexpectedEof);
235    }
236
237    #[test]
238    fn chunks_follow_mtu_capped_at_the_attribute_size() {
239        assert_eq!(chunk_size(23), 20);
240        assert_eq!(chunk_size(0), 20);
241        assert_eq!(chunk_size(247), 244);
242        // Android 14+ always negotiates 517; Linux / Windows report up to 527.
243        assert_eq!(chunk_size(517), 512);
244        assert_eq!(chunk_size(527), 512);
245    }
246
247    #[test]
248    fn every_eighth_chunk_waits_for_a_response_when_rx_allows_both() {
249        let mut p = WritePacer::default();
250        let got: Vec<bool> = (0..16).map(|_| p.with_response(true, true)).collect();
251        let want: Vec<bool> = (1..=16_usize)
252            .map(|i| i.is_multiple_of(WRITE_PACE_EVERY))
253            .collect();
254        assert_eq!(got, want);
255        let mut p = WritePacer::default();
256        assert!(
257            (0..9).all(|_| p.with_response(true, false)),
258            "no write-without-response"
259        );
260        let mut p = WritePacer::default();
261        assert!(
262            (0..9).all(|_| !p.with_response(false, true)),
263            "no write-with-response"
264        );
265    }
266
267    #[test]
268    fn target_matches_id_mac_in_any_case_or_name() {
269        let m = |t| target_matches("hci0/dev_AA_BB", "AA:BB:CC:DD:EE:FF", Some("Nus Board"), t);
270        assert!(m("hci0/dev_AA_BB"));
271        assert!(m("aa:bb:cc:dd:ee:ff"));
272        assert!(m("AA:BB:CC:DD:EE:FF"));
273        assert!(m("Nus Board"));
274        assert!(!m("nus board"), "names are exact");
275        assert!(!m("AA:BB"));
276        // Apple hides the MAC (all zero): never matches by address.
277        assert!(!target_matches(
278            "uuid",
279            "00:00:00:00:00:00",
280            None,
281            "00:00:00:00:00:00"
282        ));
283        assert!(target_matches(
284            "5D2A-UUID",
285            "00:00:00:00:00:00",
286            None,
287            "5d2a-uuid"
288        ));
289    }
290
291    #[test]
292    fn ble_target_strips_scheme() {
293        assert_eq!(ble_target("ble://AA:BB"), Some("AA:BB"));
294        assert_eq!(ble_target("/dev/ttyUSB0"), None);
295    }
296}