1#[cfg(target_os = "ios")]
3use crate::serialport;
4
5mod io_errors {
6 pub(super) fn is_benign_read_error(err: &std::io::Error) -> bool {
8 matches!(
9 err.kind(),
10 std::io::ErrorKind::TimedOut
11 | std::io::ErrorKind::WouldBlock
12 | std::io::ErrorKind::Interrupted
13 )
14 }
15
16 pub(super) fn is_disconnect_read_error(err: &std::io::Error) -> bool {
18 matches!(
19 err.kind(),
20 std::io::ErrorKind::BrokenPipe
21 | std::io::ErrorKind::NotConnected
22 | std::io::ErrorKind::ConnectionAborted
23 | std::io::ErrorKind::ConnectionReset
24 | std::io::ErrorKind::UnexpectedEof
25 )
26 }
27
28 #[cfg(test)]
29 mod tests {
30 use super::*;
31
32 #[cfg(not(target_os = "android"))]
34 #[test]
35 fn persistent_read_error_ends_in_disconnect_event() {
36 use crate::events::SerialEvent;
37 use crate::mock_serial::MockSerialPort;
38 use std::sync::{Arc, Mutex};
39 use std::time::Duration;
40
41 let mut mock = MockSerialPort::new();
42 mock.sticky_read_error = Some(std::io::ErrorKind::PermissionDenied);
43 let port: Arc<Mutex<Box<dyn serialport::SerialPort>>> =
44 Arc::new(Mutex::new(Box::new(mock)));
45 let (tx, rx) = std::sync::mpsc::channel();
46 let tx = Mutex::new(tx);
47 let channel: crate::events::EventSink = Arc::new(move |event: SerialEvent| {
48 if matches!(event, SerialEvent::Disconnect { .. }) {
49 let _ = tx.lock().unwrap().send(());
50 }
51 true
52 });
53 let hub = super::super::PortRxHub::start(port, "unplugged".into());
54 hub.attach_watch_with(channel, 10, 64, false, None);
55 rx.recv_timeout(Duration::from_secs(3))
56 .expect("no Disconnect after persistent read errors");
57 hub.stop();
58 }
59
60 #[test]
61 fn eintr_is_benign() {
62 let err = std::io::Error::new(std::io::ErrorKind::Interrupted, "EINTR");
63 assert!(is_benign_read_error(&err));
64 }
65
66 #[test]
67 fn read_timeout_is_benign_not_disconnect() {
68 let err = std::io::Error::new(std::io::ErrorKind::TimedOut, "timeout");
69 assert!(is_benign_read_error(&err));
70 assert!(!is_disconnect_read_error(&err));
71 }
72
73 #[test]
74 fn broken_pipe_is_disconnect() {
75 let err = std::io::Error::new(std::io::ErrorKind::BrokenPipe, "broken");
76 assert!(!is_benign_read_error(&err));
77 assert!(is_disconnect_read_error(&err));
78 }
79
80 #[test]
81 fn permission_denied_is_neither_benign_nor_disconnect() {
82 let err = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "denied");
83 assert!(!is_benign_read_error(&err));
84 assert!(!is_disconnect_read_error(&err));
85 }
86 }
87}
88
89use io_errors::{is_benign_read_error, is_disconnect_read_error};
90
91use crate::cmux::CmuxSession;
92use crate::events::SerialEvent;
93use crate::hub::shared::{
94 finish_drain, try_complete_drain, ExchangeWaiter, HubRoutingState, RxHubShared,
95};
96use serial_codec::framing::Framer;
97use serialport::SerialPort;
98use std::io::Read;
99use std::sync::atomic::AtomicBool;
100use std::sync::mpsc::{self, Receiver, Sender, TryRecvError};
101use std::sync::{Arc, Mutex};
102use std::thread::{self, JoinHandle};
103use std::time::{Duration, Instant};
104
105const POLL_TIMEOUT: Duration = Duration::from_millis(10);
106
107fn poll_read_port(
109 port: &Arc<Mutex<Box<dyn SerialPort>>>,
110 buf: &mut [u8],
111 stop_rx: &Receiver<()>,
112 timeout: Duration,
113) -> std::io::Result<Option<usize>> {
114 loop {
115 if matches!(stop_rx.try_recv(), Ok(_) | Err(TryRecvError::Disconnected)) {
116 return Ok(None);
117 }
118 let mut p = match port.try_lock() {
119 Ok(g) => g,
120 Err(_) => {
121 thread::sleep(Duration::from_millis(1));
122 continue;
123 }
124 };
125 let _ = p.set_timeout(timeout);
126 match p.read(buf) {
127 Ok(n) => return Ok(Some(n)),
128 Err(e) if is_benign_read_error(&e) => {
129 drop(p);
130 return Ok(Some(0));
132 }
133 Err(e) => return Err(e),
134 }
135 }
136}
137
138const MAX_CONSECUTIVE_READ_ERRORS: u32 = 5;
142
143fn shutdown_hub_state(shared: &RxHubShared, routing: &mut HubRoutingState) {
144 shared.fail_all_waiters("port closed");
145 shared.finish_watch_stream(routing);
146 shared.dispatch_queued_events(std::mem::take(&mut routing.pending_events));
147}
148
149pub struct PortRxHub {
151 shared: Arc<RxHubShared>,
152 stop_tx: Sender<()>,
153 thread: Option<JoinHandle<()>>,
154}
155
156impl PortRxHub {
157 pub fn start(port: Arc<Mutex<Box<dyn SerialPort>>>, path: String) -> Self {
158 let shared = Arc::new(RxHubShared::for_path(path.clone()));
159 let (stop_tx, stop_rx) = mpsc::channel();
160 let shared_clone = shared.clone();
161 let thread = thread::spawn(move || hub_loop(port, path, shared_clone, stop_rx));
162 Self {
163 shared,
164 stop_tx,
165 thread: Some(thread),
166 }
167 }
168
169 pub fn shared(&self) -> Arc<RxHubShared> {
170 self.shared.clone()
171 }
172
173 pub fn is_finished(&self) -> bool {
174 self.thread
175 .as_ref()
176 .map(JoinHandle::is_finished)
177 .unwrap_or(true)
178 }
179
180 #[cfg(feature = "tauri")]
182 pub fn attach_watch(
183 &self,
184 channel: tauri::ipc::Channel<SerialEvent>,
185 batch_timeout_ms: u64,
186 read_size: usize,
187 route_urc: bool,
188 ) {
189 self.shared
190 .attach_watch(channel, batch_timeout_ms, read_size, route_urc);
191 }
192
193 pub fn attach_watch_with(
194 &self,
195 channel: crate::events::EventSink,
196 batch_timeout_ms: u64,
197 read_size: usize,
198 route_urc: bool,
199 framer: Option<Box<dyn Framer>>,
200 ) {
201 self.shared
202 .attach_watch_with(channel, batch_timeout_ms, read_size, route_urc, framer);
203 }
204
205 pub fn detach_watch(&self) {
206 self.shared.detach_watch();
207 }
208
209 pub fn set_exchange_waiter(&self, waiter: Arc<ExchangeWaiter>) {
210 self.shared.set_exchange_waiter(waiter);
211 }
212
213 pub fn clear_exchange_waiter(&self) {
214 self.shared.clear_exchange_waiter();
215 }
216
217 pub fn cancel_active_exchange(&self) {
218 self.shared.cancel_active_exchange();
219 }
220
221 pub fn attach_cmux(&self, session: Arc<CmuxSession>) {
222 self.shared.attach_cmux(session);
223 }
224
225 pub fn detach_cmux(&self) {
226 self.shared.detach_cmux();
227 }
228
229 pub fn drain(
231 &self,
232 idle_ms: u64,
233 max_ms: u64,
234 cancel: Arc<AtomicBool>,
235 solicited_prefixes: Vec<String>,
236 ) -> Result<Vec<u8>, String> {
237 self.shared
238 .drain(idle_ms, max_ms, cancel, solicited_prefixes)
239 }
240
241 pub fn request_stop(&self) {
242 let _ = self.stop_tx.send(());
243 }
244
245 pub fn stop(mut self) {
246 let _ = self.stop_tx.send(());
247 if let Some(h) = self.thread.take() {
248 let _ = h.join();
249 }
250 }
251}
252
253impl crate::hub::handle::RxHubHandle for PortRxHub {
254 fn shared(&self) -> Arc<RxHubShared> {
255 self.shared()
256 }
257 fn set_exchange_waiter(&self, waiter: Arc<ExchangeWaiter>) {
258 self.set_exchange_waiter(waiter);
259 }
260 fn clear_exchange_waiter(&self) {
261 self.clear_exchange_waiter();
262 }
263 fn cancel_active_exchange(&self) {
264 self.cancel_active_exchange();
265 }
266 fn attach_watch_with(
267 &self,
268 channel: crate::events::EventSink,
269 batch_timeout_ms: u64,
270 read_size: usize,
271 route_urc: bool,
272 framer: Option<Box<dyn Framer>>,
273 ) {
274 self.attach_watch_with(channel, batch_timeout_ms, read_size, route_urc, framer);
275 }
276 fn detach_watch(&self) {
277 self.detach_watch();
278 }
279 fn attach_cmux(&self, session: Arc<CmuxSession>) {
280 self.attach_cmux(session);
281 }
282 fn detach_cmux(&self) {
283 self.detach_cmux();
284 }
285 fn shutdown_hub(&self) {
286 self.request_stop();
287 }
288}
289
290fn hub_loop(
291 port: Arc<Mutex<Box<dyn SerialPort>>>,
292 path: String,
293 shared: Arc<RxHubShared>,
294 stop_rx: Receiver<()>,
295) {
296 let mut routing = HubRoutingState::new(path.clone());
297 let mut read_size = 1024usize;
298 let mut last_error_emit = Instant::now() - Duration::from_secs(1);
299 let mut consecutive_errors = 0u32;
300
301 loop {
302 if matches!(stop_rx.try_recv(), Ok(_) | Err(TryRecvError::Disconnected)) {
303 shutdown_hub_state(&shared, &mut routing);
304 break;
305 }
306
307 if crate::sync_util::lock_or_recover(&shared.drain).is_some() {
308 try_complete_drain(&shared);
309 if crate::sync_util::lock_or_recover(&shared.drain).is_none() {
310 continue;
311 }
312
313 let mut buf = vec![0u8; 1024];
314 let n = match poll_read_port(&port, &mut buf, &stop_rx, POLL_TIMEOUT) {
315 Ok(Some(n)) => n,
316 Ok(None) => {
317 shutdown_hub_state(&shared, &mut routing);
318 break;
319 }
320 Err(e) => {
321 finish_drain(&shared, Err(format!("drain read failed: {}", e)));
322 continue;
323 }
324 };
325
326 if n > 0 {
327 shared.feed_bytes(&buf[..n], &mut routing);
330 shared.dispatch_queued_events(std::mem::take(&mut routing.pending_events));
331 }
332 shared.tick(&path, &mut routing);
335 shared.dispatch_queued_events(std::mem::take(&mut routing.pending_events));
336 continue;
337 }
338
339 let mut timeout = POLL_TIMEOUT;
342 if let Some(watch) = crate::sync_util::lock_or_recover(&shared.watch).as_ref() {
343 read_size = watch.read_size;
344 if let Some(d) = watch.framer.as_ref().and_then(|f| f.deadline()) {
345 timeout = d
346 .saturating_duration_since(Instant::now())
347 .clamp(Duration::from_millis(1), POLL_TIMEOUT);
348 }
349 }
350
351 let mut buf = vec![0u8; read_size];
352 let read_result = poll_read_port(&port, &mut buf, &stop_rx, timeout);
353
354 if read_result.is_ok() {
355 consecutive_errors = 0;
356 }
357 match read_result {
358 Ok(None) => {
359 shutdown_hub_state(&shared, &mut routing);
360 break;
361 }
362 Ok(Some(n)) if n > 0 => {
363 shared.feed_bytes(&buf[..n], &mut routing);
364 shared.dispatch_queued_events(std::mem::take(&mut routing.pending_events));
365 }
366 Ok(Some(_)) => {
367 thread::sleep(Duration::from_millis(1));
368 }
369 Err(e) => {
370 consecutive_errors += 1;
371 shared.flush_watch_now(&mut routing);
372 shared.dispatch_queued_events(std::mem::take(&mut routing.pending_events));
373 if is_disconnect_read_error(&e) || consecutive_errors >= MAX_CONSECUTIVE_READ_ERRORS
374 {
375 let reason = format!("Serial port disconnected: {}", e);
376 shared.fail_all_waiters(&reason);
377 shared.emit_disconnect(&path, &reason);
378 #[cfg(target_os = "android")]
381 {
382 crate::android::registry::on_usb_error(&path, &reason);
383 let _ = crate::android::driver_host::global_host().close(Some(&path));
384 }
385 break;
386 }
387 if last_error_emit.elapsed() >= Duration::from_secs(1) {
388 last_error_emit = Instant::now();
389 shared.emit(SerialEvent::Error {
390 path: path.clone(),
391 message: format!("Serial read error: {}", e),
392 });
393 }
394 thread::sleep(Duration::from_millis(50));
395 }
396 }
397
398 shared.tick(&path, &mut routing);
399 shared.dispatch_queued_events(std::mem::take(&mut routing.pending_events));
400 }
401}
402
403#[cfg(all(test, unix, not(any(target_os = "android", target_os = "ios"))))]
404mod tests {
405 use super::*;
406 use std::io::Write;
407
408 #[test]
411 fn parser_timer_fires_during_drain() {
412 let (_guard, mut master, slave) = crate::sync_util::pty_pair_locked();
413 let port: Arc<Mutex<Box<dyn SerialPort>>> = Arc::new(Mutex::new(Box::new(slave)));
414 let hub = PortRxHub::start(port, "pty".into());
415 let (tx, rx) = mpsc::channel();
416 let tx = Mutex::new(tx);
417 let channel: crate::events::EventSink = Arc::new(move |event: SerialEvent| {
418 if let SerialEvent::Data { data, .. } = event {
419 let _ = tx.lock().unwrap().send(data);
420 }
421 true
422 });
423 let cfg: serial_codec::framing::FramerConfig = serde_json::from_value(
424 serde_json::json!({"type": "interByteTimeout", "interval": 150}),
425 )
426 .unwrap();
427 hub.attach_watch_with(channel, 10_000, 64, false, Some(cfg.build().unwrap()));
428 master.write_all(&[1, 2]).unwrap();
429 thread::sleep(Duration::from_millis(50)); let shared = hub.shared();
431 let drainer = thread::spawn(move || {
432 shared.drain(2_000, 3_000, Arc::new(AtomicBool::new(false)), vec![])
433 });
434 let frame = rx
435 .recv_timeout(Duration::from_millis(1_000))
436 .expect("parser frame held back by the drain");
437 assert_eq!(frame, vec![1, 2]);
438 assert!(!drainer.is_finished(), "drain should still be running");
439 let _ = drainer.join();
440 hub.stop();
441 }
442}