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::*;
185 use std::sync::mpsc;
186
187 #[test]
188 fn rx_queue_splits_chunks_and_reports_timeout_and_disconnect() {
189 let (tx, rx) = mpsc::channel();
190 let mut q = RxQueue::new(rx);
191 tx.send(b"hello".to_vec()).unwrap();
192 let mut buf = [0u8; 3];
193 assert_eq!(q.read(&mut buf, Duration::from_millis(10)).unwrap(), 3);
194 assert_eq!(&buf, b"hel");
195 assert_eq!(q.buffered(), 2);
196 assert_eq!(q.read(&mut buf, Duration::from_millis(10)).unwrap(), 2);
197 assert_eq!(&buf[..2], b"lo");
198 let e = q.read(&mut buf, Duration::from_millis(5)).unwrap_err();
199 assert_eq!(e.kind(), io::ErrorKind::TimedOut);
200 drop(tx);
201 let e = q.read(&mut buf, Duration::from_millis(5)).unwrap_err();
202 assert_eq!(e.kind(), io::ErrorKind::UnexpectedEof);
203 q.clear();
204 }
205
206 #[test]
208 fn empty_notification_is_a_timeout_not_eof() {
209 let (tx, rx) = mpsc::channel();
210 let mut q = RxQueue::new(rx);
211 tx.send(Vec::new()).unwrap();
212 let mut buf = [0u8; 4];
213 let e = q.read(&mut buf, Duration::from_millis(10)).unwrap_err();
214 assert_eq!(e.kind(), io::ErrorKind::TimedOut);
215 }
216
217 #[test]
218 fn rx_channel_counts_queued_bytes_and_drops_over_cap() {
219 let (feed, mut q) = rx_channel(8);
220 assert!(feed.push(b"hello".to_vec()));
221 assert_eq!(q.buffered(), 5, "queued chunk counts before any read");
222 assert!(!feed.push(b"world".to_vec()), "5 + 5 > cap 8: dropped");
223 assert!(feed.push(b"abc".to_vec()));
224 assert_eq!(q.buffered(), 8);
225 let mut buf = [0u8; 2];
226 assert_eq!(q.read(&mut buf, Duration::from_millis(10)).unwrap(), 2);
227 assert_eq!(q.buffered(), 6, "3 pending + 3 queued");
228 assert!(feed.push(b"xy".to_vec()), "room again after a read");
229 q.clear();
230 assert_eq!(q.buffered(), 0);
231 let mut all = [0u8; 8];
232 let e = q.read(&mut all, Duration::from_millis(5)).unwrap_err();
233 assert_eq!(e.kind(), io::ErrorKind::TimedOut);
234 drop(feed);
235 let e = q.read(&mut all, Duration::from_millis(5)).unwrap_err();
236 assert_eq!(e.kind(), io::ErrorKind::UnexpectedEof);
237 }
238
239 #[test]
240 fn chunks_follow_mtu_capped_at_the_attribute_size() {
241 assert_eq!(chunk_size(23), 20);
242 assert_eq!(chunk_size(0), 20);
243 assert_eq!(chunk_size(247), 244);
244 assert_eq!(chunk_size(517), 512);
246 assert_eq!(chunk_size(527), 512);
247 }
248
249 #[test]
250 fn every_eighth_chunk_waits_for_a_response_when_rx_allows_both() {
251 let mut p = WritePacer::default();
252 let got: Vec<bool> = (0..16).map(|_| p.with_response(true, true)).collect();
253 let want: Vec<bool> = (1..=16_usize)
254 .map(|i| i.is_multiple_of(WRITE_PACE_EVERY))
255 .collect();
256 assert_eq!(got, want);
257 let mut p = WritePacer::default();
258 assert!(
259 (0..9).all(|_| p.with_response(true, false)),
260 "no write-without-response"
261 );
262 let mut p = WritePacer::default();
263 assert!(
264 (0..9).all(|_| !p.with_response(false, true)),
265 "no write-with-response"
266 );
267 }
268
269 #[test]
270 fn target_matches_id_mac_in_any_case_or_name() {
271 let m = |t| target_matches("hci0/dev_AA_BB", "AA:BB:CC:DD:EE:FF", Some("Nus Board"), t);
272 assert!(m("hci0/dev_AA_BB"));
273 assert!(m("aa:bb:cc:dd:ee:ff"));
274 assert!(m("AA:BB:CC:DD:EE:FF"));
275 assert!(m("Nus Board"));
276 assert!(!m("nus board"), "names are exact");
277 assert!(!m("AA:BB"));
278 assert!(!target_matches(
280 "uuid",
281 "00:00:00:00:00:00",
282 None,
283 "00:00:00:00:00:00"
284 ));
285 assert!(target_matches(
286 "5D2A-UUID",
287 "00:00:00:00:00:00",
288 None,
289 "5d2a-uuid"
290 ));
291 }
292
293 #[test]
294 fn ble_target_strips_scheme() {
295 assert_eq!(ble_target("ble://AA:BB"), Some("AA:BB"));
296 assert_eq!(ble_target("/dev/ttyUSB0"), None);
297 }
298}