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) {
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
95pub(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
110pub(crate) struct RxQueue {
114 rx: Receiver<Vec<u8>>,
115 pending: Vec<u8>,
116 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 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 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 #[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 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 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}