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 self.pending = chunk;
141 }
142 Err(RecvTimeoutError::Timeout) => {
143 return Err(io::Error::new(io::ErrorKind::TimedOut, "BLE read timeout"))
144 }
145 Err(RecvTimeoutError::Disconnected) => {
146 return Err(io::Error::new(
147 io::ErrorKind::UnexpectedEof,
148 "BLE device disconnected",
149 ))
150 }
151 }
152 }
153 let n = buf.len().min(self.pending.len());
154 buf[..n].copy_from_slice(&self.pending[..n]);
155 self.pending.drain(..n);
156 Ok(n)
157 }
158
159 pub(crate) fn clear(&mut self) {
160 self.pending.clear();
161 while let Ok(chunk) = self.rx.try_recv() {
162 self.took(&chunk);
163 }
164 }
165
166 pub(crate) fn buffered(&self) -> usize {
168 self.pending.len()
169 + self
170 .queued
171 .as_ref()
172 .map_or(0, |q| q.load(Ordering::Acquire))
173 }
174}
175
176#[cfg(test)]
177mod tests {
178 use super::*;
179 use std::sync::mpsc;
180
181 #[test]
182 fn rx_queue_splits_chunks_and_reports_timeout_and_disconnect() {
183 let (tx, rx) = mpsc::channel();
184 let mut q = RxQueue::new(rx);
185 tx.send(b"hello".to_vec()).unwrap();
186 let mut buf = [0u8; 3];
187 assert_eq!(q.read(&mut buf, Duration::from_millis(10)).unwrap(), 3);
188 assert_eq!(&buf, b"hel");
189 assert_eq!(q.buffered(), 2);
190 assert_eq!(q.read(&mut buf, Duration::from_millis(10)).unwrap(), 2);
191 assert_eq!(&buf[..2], b"lo");
192 let e = q.read(&mut buf, Duration::from_millis(5)).unwrap_err();
193 assert_eq!(e.kind(), io::ErrorKind::TimedOut);
194 drop(tx);
195 let e = q.read(&mut buf, Duration::from_millis(5)).unwrap_err();
196 assert_eq!(e.kind(), io::ErrorKind::UnexpectedEof);
197 q.clear();
198 }
199
200 #[test]
201 fn rx_channel_counts_queued_bytes_and_drops_over_cap() {
202 let (feed, mut q) = rx_channel(8);
203 assert!(feed.push(b"hello".to_vec()));
204 assert_eq!(q.buffered(), 5, "queued chunk counts before any read");
205 assert!(!feed.push(b"world".to_vec()), "5 + 5 > cap 8: dropped");
206 assert!(feed.push(b"abc".to_vec()));
207 assert_eq!(q.buffered(), 8);
208 let mut buf = [0u8; 2];
209 assert_eq!(q.read(&mut buf, Duration::from_millis(10)).unwrap(), 2);
210 assert_eq!(q.buffered(), 6, "3 pending + 3 queued");
211 assert!(feed.push(b"xy".to_vec()), "room again after a read");
212 q.clear();
213 assert_eq!(q.buffered(), 0);
214 let mut all = [0u8; 8];
215 let e = q.read(&mut all, Duration::from_millis(5)).unwrap_err();
216 assert_eq!(e.kind(), io::ErrorKind::TimedOut);
217 drop(feed);
218 let e = q.read(&mut all, Duration::from_millis(5)).unwrap_err();
219 assert_eq!(e.kind(), io::ErrorKind::UnexpectedEof);
220 }
221
222 #[test]
223 fn chunks_follow_mtu_capped_at_the_attribute_size() {
224 assert_eq!(chunk_size(23), 20);
225 assert_eq!(chunk_size(0), 20);
226 assert_eq!(chunk_size(247), 244);
227 assert_eq!(chunk_size(517), 512);
229 assert_eq!(chunk_size(527), 512);
230 }
231
232 #[test]
233 fn every_eighth_chunk_waits_for_a_response_when_rx_allows_both() {
234 let mut p = WritePacer::default();
235 let got: Vec<bool> = (0..16).map(|_| p.with_response(true, true)).collect();
236 let want: Vec<bool> = (1..=16_usize)
237 .map(|i| i.is_multiple_of(WRITE_PACE_EVERY))
238 .collect();
239 assert_eq!(got, want);
240 let mut p = WritePacer::default();
241 assert!(
242 (0..9).all(|_| p.with_response(true, false)),
243 "no write-without-response"
244 );
245 let mut p = WritePacer::default();
246 assert!(
247 (0..9).all(|_| !p.with_response(false, true)),
248 "no write-with-response"
249 );
250 }
251
252 #[test]
253 fn target_matches_id_mac_in_any_case_or_name() {
254 let m = |t| target_matches("hci0/dev_AA_BB", "AA:BB:CC:DD:EE:FF", Some("Nus Board"), t);
255 assert!(m("hci0/dev_AA_BB"));
256 assert!(m("aa:bb:cc:dd:ee:ff"));
257 assert!(m("AA:BB:CC:DD:EE:FF"));
258 assert!(m("Nus Board"));
259 assert!(!m("nus board"), "names are exact");
260 assert!(!m("AA:BB"));
261 assert!(!target_matches(
263 "uuid",
264 "00:00:00:00:00:00",
265 None,
266 "00:00:00:00:00:00"
267 ));
268 assert!(target_matches(
269 "5D2A-UUID",
270 "00:00:00:00:00:00",
271 None,
272 "5d2a-uuid"
273 ));
274 }
275
276 #[test]
277 fn ble_target_strips_scheme() {
278 assert_eq!(ble_target("ble://AA:BB"), Some("AA:BB"));
279 assert_eq!(ble_target("/dev/ttyUSB0"), None);
280 }
281}