1use 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
12pub(crate) const RX_QUEUE_CAP: usize = 1 << 20;
16
17const MAX_ATTRIBUTE_LEN: usize = 512;
20
21#[cfg_attr(target_os = "android", allow(dead_code))] pub(crate) fn chunk_size(mtu: u16) -> usize {
24 (usize::from(mtu.max(23)) - 3).min(MAX_ATTRIBUTE_LEN)
25}
26
27pub(crate) const WRITE_PACE_EVERY: usize = 8;
30
31#[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 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#[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
60pub fn ble_target(path: &str) -> Option<&str> {
62 path.strip_prefix(BLE_SCHEME)
63}
64
65pub(crate) struct RxFeed {
67 tx: Sender<Vec<u8>>,
68 queued: Arc<AtomicUsize>,
69 cap: usize,
70 dropping: AtomicBool,
71}
72
73impl RxFeed {
74 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) {
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
97pub(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
112pub(crate) struct RxQueue {
116 rx: Receiver<Vec<u8>>,
117 pending: Vec<u8>,
118 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 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 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 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 #[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 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 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}