Skip to main content

serialplugin_core/api/
serial.rs

1//! Unified serial API — `Box<dyn serialport::SerialPort>` on desktop and Android.
2#[cfg(target_os = "ios")]
3use crate::serialport;
4
5use crate::api::serial_port::{
6    configure_at_session as configure_at_session_shared, run_exchange_queued,
7};
8use crate::at::session::{AtCommandOptions, AtPhase, AtSessionConfig, SendSmsPduOptions};
9use crate::cmux::{mux_path, parse_mux_path, CmuxSession};
10use crate::error::{CoreError, Error, ErrorKind};
11use crate::events::{
12    CoreEvent, CoreSink, EventSink, ExchangeOptions, PortListSink, PortStatus, SerialEvent,
13    SubscriptionId, WatchOptions,
14};
15use crate::hub::delivery::CoreQueue;
16use crate::hub::shared::CoreWatchSlot;
17use crate::hub::stream::{EventStream, Target, WatchOwner};
18#[cfg(target_os = "android")]
19use crate::log_error;
20use crate::port::tx_queue::PortTxQueue;
21use crate::state::{
22    ClearBuffer, ConnectedPort, ConnectedPortHandle, DataBits, FlowControl, Parity, PortState,
23    SerialportInfo, StopBits,
24};
25use crate::{log_debug, log_info};
26use serialport::SerialPort as SerialPortTrait;
27use std::collections::HashMap;
28use std::io::Write;
29use std::sync::atomic::{AtomicU32, AtomicU64, AtomicUsize, Ordering};
30use std::sync::{Arc, Mutex, Weak};
31use std::thread;
32use std::time::{Duration, Instant};
33
34type PortArc = Arc<Mutex<Box<dyn SerialPortTrait>>>;
35
36/// Ids handed out by [`SerialManager::watch`] / [`SerialManager::watch_ports`].
37/// The Tauri plugin passes its IPC channel ids through the `*_with_id` variants instead;
38/// both share the manager's registry, so an id already taken there is skipped (and
39/// registering a duplicate id is rejected outright).
40fn next_watch_id(taken: impl Fn(u32) -> bool) -> u32 {
41    static NEXT: AtomicU32 = AtomicU32::new(1);
42    loop {
43        let id = NEXT.fetch_add(1, Ordering::Relaxed);
44        if !taken(id) {
45            return id;
46        }
47    }
48}
49
50/// Ids of `watch_core` streams and `subscribe_core` subscriptions.
51fn next_subscription_id() -> u64 {
52    static NEXT: AtomicU64 = AtomicU64::new(1);
53    NEXT.fetch_add(1, Ordering::Relaxed)
54}
55
56/// Platform seam: enumerate available ports.
57fn platform_available_ports(
58    single_port_per_device: bool,
59) -> Result<HashMap<String, HashMap<String, String>>, Error> {
60    #[cfg(not(target_os = "android"))]
61    {
62        crate::port::list::enumerate_available_ports(single_port_per_device)
63    }
64    #[cfg(target_os = "android")]
65    {
66        let json = crate::android::fd_bridge::call_enumerate_json()?;
67        log_info!(
68            "[SerialEnumerate] raw json ({} bytes): {}",
69            json.len(),
70            json
71        );
72        #[derive(serde::Deserialize)]
73        struct AvailablePortsResponse {
74            #[serde(default)]
75            ports: HashMap<String, crate::android::enumerate::DeviceEntry>,
76        }
77        let response: AvailablePortsResponse = serde_json::from_str(&json).map_err(|e| {
78            log_error!("[SerialEnumerate] Invalid enumerate JSON: {e}; body={json}");
79            Error::new(format!("Invalid enumerate JSON: {e}"))
80        })?;
81        let filtered =
82            crate::android::enumerate::expand_devices(response.ports, single_port_per_device)?;
83        let keys: Vec<&str> = filtered.keys().map(|s| s.as_str()).collect();
84        log_info!(
85            "[SerialEnumerate] parsed {} port(s) single={} keys={:?}",
86            filtered.len(),
87            single_port_per_device,
88            keys
89        );
90        Ok(filtered)
91    }
92}
93
94/// Platform seam: open physical port as `Box<dyn serialport::SerialPort>`.
95#[allow(clippy::too_many_arguments)]
96fn platform_open(
97    path: &str,
98    baud_rate: u32,
99    data_bits: DataBits,
100    flow_control: FlowControl,
101    parity: Parity,
102    stop_bits: StopBits,
103    timeout: Duration,
104    lines: crate::state::ModemLinesOnOpen,
105) -> Result<(String, Box<dyn SerialPortTrait>), CoreError> {
106    if path.starts_with("ble://") {
107        #[cfg(feature = "ble")]
108        {
109            #[cfg(not(target_os = "android"))]
110            use crate::port::ble::BleSerialPort as Ble;
111            #[cfg(target_os = "android")]
112            use crate::port::ble_android::AndroidBleSerialPort as Ble;
113            let port = Ble::connect(
114                path,
115                baud_rate,
116                data_bits.into(),
117                flow_control.into(),
118                parity.into(),
119                stop_bits.into(),
120                timeout,
121            )
122            .map_err(|e| CoreError::io(format!("Failed to open {path}"), e))?;
123            return Ok((path.to_string(), Box::new(port)));
124        }
125        #[cfg(not(feature = "ble"))]
126        return Err(CoreError::new(
127            ErrorKind::Other,
128            Error::String(format!(
129                "{path}: BLE needs the plugin's `ble` cargo feature"
130            )),
131        ));
132    }
133    if crate::port::tcp::tcp_address(path).is_some() {
134        let port = crate::port::tcp::TcpSerialPort::connect(
135            path,
136            baud_rate,
137            data_bits.into(),
138            flow_control.into(),
139            parity.into(),
140            stop_bits.into(),
141            timeout,
142        )
143        .map_err(|e| CoreError::io(format!("Failed to open {path}"), e))?;
144        return Ok((path.to_string(), Box::new(port)));
145    }
146    // iOS has no local serial devices; serialport's open/enumerate code would also
147    // pull in IOKit, which iOS apps cannot link.
148    #[cfg(target_os = "ios")]
149    {
150        let _ = (
151            baud_rate,
152            data_bits,
153            flow_control,
154            parity,
155            stop_bits,
156            timeout,
157            lines,
158        );
159        Err(CoreError::new(
160            ErrorKind::NotFound,
161            Error::String(format!(
162                "{path}: iOS has no local serial ports; use a tcp://host:port bridge"
163            )),
164        ))
165    }
166    #[cfg(not(any(target_os = "android", target_os = "ios")))]
167    {
168        let mut builder = serialport::new(path, baud_rate)
169            .data_bits(data_bits.into())
170            .flow_control(flow_control.into())
171            .parity(parity.into())
172            .stop_bits(stop_bits.into())
173            .timeout(timeout);
174        if let Some(dtr) = lines.dtr {
175            builder = builder.dtr_on_open(dtr);
176        }
177        let mut port = builder.open().map_err(|e| {
178            let err = CoreError::serialport("Failed to open serial port".into(), e);
179            // Listed but not openable: in use (Windows says "Access is denied", in the
180            // system language; serialport reports that and flock failures as NoDevice).
181            let listed = || {
182                serialport::available_ports().is_ok_and(|l| l.iter().any(|p| p.port_name == path))
183            };
184            let kind = open_error_kind(err.kind(), listed);
185            err.with_kind(kind)
186        })?;
187        if let Some(rts) = lines.rts {
188            port.write_request_to_send(rts)
189                .map_err(|e| CoreError::serialport("Failed to set RTS on open".into(), e))?;
190        }
191        Ok((path.to_string(), port))
192    }
193    #[cfg(target_os = "android")]
194    {
195        let _ = timeout;
196        crate::android::driver_host::global_host()
197            .open(
198                path,
199                baud_rate,
200                data_bits,
201                flow_control,
202                parity,
203                stop_bits,
204                lines,
205            )
206            .map_err(CoreError::from)
207    }
208}
209
210/// A second handle for writes and control calls, so they never wait for the RX hub's
211/// read (and the hub's poll timeout never touches the write timeout). `timeout` is
212/// the port timeout from `open` / `set_timeout`.
213///
214/// Local serial ports on Unix only. TCP, BLE and Android keep one handle (no real
215/// clone there), and so does Windows: its duplicated handles share one COMMTIMEOUTS,
216/// so the hub's short read timeout would cut writes short.
217fn split_writer(
218    path: &str,
219    port: &dyn SerialPortTrait,
220    timeout: Duration,
221) -> Option<Box<dyn SerialPortTrait>> {
222    if !cfg!(all(
223        unix,
224        not(any(target_os = "android", target_os = "ios"))
225    )) || path.starts_with("ble://")
226        || crate::port::tcp::tcp_address(path).is_some()
227    {
228        return None;
229    }
230    let mut writer = port.try_clone().ok()?;
231    writer.set_timeout(timeout).ok()?;
232    Some(writer)
233}
234
235/// Default read/write timeout (ms) when opening a port.
236const DEFAULT_PORT_TIMEOUT_MS: u64 = 1000;
237const PORT_LOCK_TIMEOUT_MS: u64 = 250;
238const PORT_IO_TIMEOUT_MS: u64 = 100;
239/// Pause between the `AT+CMUX` OK and the first frame (see `enable_mux`). The M26
240/// needs well under 20 ms; 100 ms leaves room for slower modems.
241const CMUX_SWITCH_SETTLE: Duration = Duration::from_millis(100);
242/// Watch batch window when the caller sets none: short enough for interactive
243/// terminals, long enough to coalesce a burst into one event.
244const DEFAULT_WATCH_FLUSH_MS: u64 = 20;
245
246/// Acquire the port mutex with a deadline (hub reader uses try_lock; avoid blocking forever).
247/// `io_timeout`: set the shared 100 ms I/O timeout first (single-handle ports only).
248fn lock_with_deadline<T, E, F>(
249    port: &PortArc,
250    lock_timeout: Duration,
251    io_timeout: bool,
252    f: F,
253) -> Result<T, E>
254where
255    E: From<Error>,
256    F: FnOnce(&mut Box<dyn serialport::SerialPort>) -> Result<T, E>,
257{
258    let deadline = Instant::now() + lock_timeout;
259    loop {
260        match port.try_lock() {
261            Ok(mut guard) => {
262                if io_timeout {
263                    let _ = guard.set_timeout(Duration::from_millis(PORT_IO_TIMEOUT_MS));
264                }
265                return f(&mut guard);
266            }
267            Err(_) if Instant::now() >= deadline => {
268                return Err(Error::String(format!(
269                    "serial port lock timeout after {} ms",
270                    lock_timeout.as_millis()
271                ))
272                .into());
273            }
274            Err(_) => thread::sleep(Duration::from_millis(1)),
275        }
276    }
277}
278
279fn with_port_try_lock<T, E, F>(port: &PortArc, lock_timeout: Duration, f: F) -> Result<T, E>
280where
281    E: From<Error>,
282    F: FnOnce(&mut Box<dyn serialport::SerialPort>) -> Result<T, E>,
283{
284    lock_with_deadline(port, lock_timeout, true, f)
285}
286
287/// Kind of a failed open: a device that is listed but "not found" is in use.
288#[cfg(not(any(target_os = "android", target_os = "ios")))]
289fn open_error_kind(kind: ErrorKind, listed: impl FnOnce() -> bool) -> ErrorKind {
290    if kind == ErrorKind::NotFound && listed() {
291        ErrorKind::Busy
292    } else {
293        kind
294    }
295}
296
297/// Time `len` bytes take on the wire at the port's baud rate (11 bits a character).
298fn wire_ms(port: &dyn SerialPortTrait, len: usize) -> u64 {
299    let baud = u64::from(port.baud_rate().unwrap_or(9600).max(1));
300    (len as u64).saturating_mul(11_000) / baud
301}
302
303/// Write the full buffer, retrying until all bytes are sent or an error occurs
304/// (single-handle ports: the hub shares the handle and its timeout).
305fn write_all_port(
306    port: &mut Box<dyn serialport::SerialPort>,
307    buf: &[u8],
308    operation: &str,
309) -> Result<usize, CoreError> {
310    // The shared 100 ms I/O timeout is too short for big or slow writes (8 KB at
311    // 9600 baud needs ~9 s), so give writes room for the wire time plus a margin.
312    let wire_ms = wire_ms(port.as_ref(), buf.len());
313    let _ = port.set_timeout(Duration::from_millis(wire_ms.saturating_mul(2) + 1000));
314    let result = port
315        .write_all(buf)
316        .map_err(|e| CoreError::io(format!("Failed to {operation}"), e));
317    let _ = port.set_timeout(Duration::from_millis(PORT_IO_TIMEOUT_MS));
318    result.map(|()| buf.len())
319}
320
321/// Write on a split write handle: its own timeout, no lock shared with the hub. A
322/// write that needs longer on the wire than the port timeout gets twice its wire
323/// time (as 4.x writes did), so a big write is not cut short by a short timeout.
324fn write_all_split(port: &PortArc, buf: &[u8], operation: &str) -> Result<usize, CoreError> {
325    lock_with_deadline(
326        port,
327        Duration::from_millis(PORT_LOCK_TIMEOUT_MS),
328        false,
329        |p| {
330            let own = p.timeout();
331            let need = Duration::from_millis(wire_ms(p.as_ref(), buf.len()).saturating_mul(2));
332            let raise = need > own;
333            if raise {
334                let _ = p.set_timeout(need);
335            }
336            let result = p
337                .write_all(buf)
338                .map(|()| buf.len())
339                .map_err(|e| CoreError::io(format!("Failed to {operation}"), e));
340            if raise {
341                let _ = p.set_timeout(own);
342            }
343            result
344        },
345    )
346}
347
348/// Tear down resources held by a [`SerialportInfo`] (RX hub + port).
349fn finish_serialport_info(path: &str, info: SerialportInfo) -> Result<(), Error> {
350    #[cfg(not(target_os = "android"))]
351    let _ = path;
352    match info.state {
353        PortState::Connected(cp) => {
354            // Joined with the slot unlocked: a sink may still be asking for it. The hub
355            // stays in the slot, so a call that still has `cp` starts no new one.
356            let hub = crate::sync_util::lock_or_recover(&cp.rx_hub).clone();
357            if let Some(hub) = hub {
358                #[cfg(target_os = "android")]
359                crate::android::registry::global_registry().unregister(path);
360                // The hub flushes what it holds into the watches; no `Disconnect`.
361                cp.tx_queue.cancel_all();
362                hub.shared().begin_close();
363                hub.stop_and_join();
364            }
365            #[cfg(target_os = "android")]
366            {
367                let _ = crate::android::driver_host::global_host().close(Some(path));
368            }
369            Ok(())
370        }
371        PortState::Opening | PortState::Closed => Ok(()),
372    }
373}
374
375fn register_mobile_hub(path: &str, cp: &ConnectedPortHandle, hub: Arc<crate::hub::PortRxHub>) {
376    #[cfg(target_os = "android")]
377    {
378        let hub_handle: Arc<dyn crate::hub::RxHubHandle> = hub;
379        crate::android::registry::global_registry().register(path, hub_handle, cp.clone());
380    }
381    #[cfg(not(target_os = "android"))]
382    {
383        let _ = (path, cp, hub);
384    }
385}
386
387/// Cloned write handle of a port, tied to the reader it was cloned from.
388struct Writer {
389    reader: Weak<Mutex<Box<dyn SerialPortTrait>>>,
390    port: PortArc,
391}
392
393/// One old watch. It stays here until its tail is delivered, so whoever ends it (or closes
394/// its port) meanwhile waits for that too.
395struct OldWatch {
396    path: String,
397    /// `None` until attached (and for the late watch of a released port).
398    attached: Option<Attached>,
399    /// `unwatch` is at work.
400    stopping: bool,
401}
402
403/// How to end a watch without its port's record, which a close may have removed already.
404#[derive(Clone)]
405struct Attached {
406    owner: Weak<dyn WatchOwner>,
407    stream: Weak<EventStream>,
408}
409
410impl Attached {
411    /// Detach and settle. Whoever still has events to deliver keeps owner and stream alive.
412    fn stop(&self) {
413        let Some(stream) = self.stream.upgrade() else {
414            return;
415        };
416        match self.owner.upgrade() {
417            Some(owner) => owner.stop(&stream),
418            // The hub is gone, and with it everything it held.
419            None => stream.settle(),
420        }
421    }
422}
423
424/// Per-manager state of the 4.2 core (registries, write handles, subscriptions).
425#[derive(Default)]
426struct CoreState {
427    /// Old `watch` ids (one per port).
428    watches: Mutex<HashMap<u32, OldWatch>>,
429    /// `watch_core` ids → path (any number per port).
430    core_watches: Mutex<HashMap<u64, String>>,
431    writers: Mutex<HashMap<String, Writer>>,
432    /// Ports the core released after a disconnect, with the reason (4.x behaviour until
433    /// `close`: still listed, a late watch gets `Disconnect`, calls fail with it).
434    disconnected: Mutex<HashMap<String, String>>,
435    subscribers: Mutex<Vec<(u64, Arc<CoreQueue>)>>,
436    /// Bytes per core receiver queue; 0 = [`crate::events::DEFAULT_CORE_QUEUE_BYTES`].
437    queue_capacity: AtomicUsize,
438}
439
440/// A manager without keeping it alive (the hub threads' disconnect hooks).
441struct WeakManager {
442    serialports: Weak<Mutex<HashMap<String, SerialportInfo>>>,
443    virtual_ports: Weak<Mutex<HashMap<String, crate::state::VirtualPortRef>>>,
444    core: Weak<CoreState>,
445}
446
447impl WeakManager {
448    fn upgrade(&self) -> Option<SerialManager> {
449        Some(SerialManager {
450            serialports: self.serialports.upgrade()?,
451            virtual_ports: self.virtual_ports.upgrade()?,
452            core: self.core.upgrade()?,
453        })
454    }
455}
456
457/// Owns every open port (desktop serial, `tcp://`, `ble://`, Android USB, CMUX channels).
458///
459/// Cheap to clone (all clones share the same ports). Methods block: call them from a
460/// plain thread or `tokio::task::spawn_blocking`, not straight from an async task.
461///
462/// Lock order: `serialports` before `virtual_ports` and the disconnect tombstones;
463/// never hold a map lock across device I/O, thread spawn, or `JoinHandle` join.
464#[derive(Clone, Default)]
465pub struct SerialManager {
466    #[doc(hidden)]
467    pub serialports: Arc<Mutex<HashMap<String, SerialportInfo>>>,
468    #[doc(hidden)]
469    pub virtual_ports: Arc<Mutex<HashMap<String, crate::state::VirtualPortRef>>>,
470    core: Arc<CoreState>,
471}
472
473impl SerialManager {
474    pub fn new() -> Self {
475        Self::default()
476    }
477
478    /// Android only: hook USB detach / port-list callbacks from the Kotlin side into this manager.
479    #[cfg(target_os = "android")]
480    pub fn setup_teardown(&self) {
481        let manager = self.downgrade();
482        // USB failure: released like a desktop disconnect (state event, the path stays
483        // listed until `close`, watches stay registered as on desktop and in 4.x).
484        crate::android::registry::set_rust_state_fail(Box::new(move |path, reason| {
485            if let Some(m) = manager.upgrade() {
486                let removed = {
487                    let mut map = crate::sync_util::lock_or_recover(&m.serialports);
488                    let removed = map.remove(path);
489                    if removed.is_some() {
490                        // As on desktop: the tombstone lands under the map lock.
491                        crate::sync_util::lock_or_recover(&m.core.disconnected)
492                            .insert(path.to_string(), reason.to_string());
493                    }
494                    removed
495                };
496                if let Some(info) = removed {
497                    m.release(path, info, reason);
498                }
499            }
500        }));
501        crate::port::list_monitor::set_android_enumerator(move |single| {
502            platform_available_ports(single)
503        });
504        crate::android::registry::init_registry();
505    }
506
507    /// Get serial port list
508    pub fn available_ports(
509        &self,
510        single_port_per_device: bool,
511    ) -> Result<HashMap<String, HashMap<String, String>>, Error> {
512        platform_available_ports(single_port_per_device)
513    }
514
515    /// Subscribe to available-port attach/detach events. `sink` first gets a
516    /// [`Snapshot`](crate::events::PortListEvent::Snapshot), then `added` / `removed`.
517    /// Returns the id for [`Self::unwatch_ports`].
518    pub fn watch_ports(
519        &self,
520        options: crate::events::WatchPortsOptions,
521        sink: PortListSink,
522    ) -> Result<u32, Error> {
523        self.watch_ports_with_id(
524            next_watch_id(crate::port::list_monitor::is_subscribed),
525            options,
526            sink,
527        )
528    }
529
530    /// [`Self::watch_ports`] under a caller-chosen id (the plugin uses its IPC channel id).
531    pub fn watch_ports_with_id(
532        &self,
533        id: u32,
534        options: crate::events::WatchPortsOptions,
535        sink: PortListSink,
536    ) -> Result<u32, Error> {
537        crate::port::list_monitor::subscribe_sink(id, sink, options)?;
538        Ok(id)
539    }
540
541    /// Stop a port-list watch session.
542    pub fn unwatch_ports(&self, channel_id: u32) -> Result<(), Error> {
543        crate::port::list_monitor::unsubscribe(channel_id);
544        Ok(())
545    }
546
547    /// Get a list of managed serial ports.
548    pub fn managed_ports(&self) -> Result<Vec<String>, Error> {
549        // Lock the Mutex to safely access the data inside `self.serialports`.
550        let ports = self
551            .serialports
552            .lock()
553            .map_err(|_| Error::String("Failed to lock serialports mutex".to_string()))?;
554
555        let mut port_list: Vec<String> = ports.keys().cloned().collect();
556        drop(ports);
557        if let Ok(virtuals) = self.virtual_ports.lock() {
558            port_list.extend(virtuals.keys().cloned());
559        }
560        port_list.extend(
561            crate::sync_util::lock_or_recover(&self.core.disconnected)
562                .keys()
563                .cloned(),
564        );
565        port_list.sort();
566        port_list.dedup();
567        Ok(port_list)
568    }
569
570    /// Cancel an in-flight poll [`Self::read`] (does not stop an active [`Self::watch`]).
571    pub fn cancel_read(&self, path: String) -> Result<(), Error> {
572        let cp = self.resolve_connected_port(&path)?;
573        if let Ok(guard) = cp.rx_hub.lock() {
574            if let Some(hub) = guard.as_ref() {
575                hub.shared().cancel_pending_read();
576            }
577        }
578        Ok(())
579    }
580
581    /// Close the specified serial port. What waits on it (exchanges, reads, queued
582    /// commands) fails; what the hub still holds (the watch batch, a parser's remainder)
583    /// reaches the watches first, in order; no `Disconnect` is sent, and nothing reaches a
584    /// [`Self::watch`] sink after this returned. It waits for a sink call in progress, so do
585    /// not hold a lock that sink takes; called from a sink it waits for no other thread.
586    /// Succeeds once on a port the core already released after a disconnect.
587    pub fn close(&self, path: String) -> Result<(), Error> {
588        self.close_core(path).map_err(Error::from)
589    }
590
591    /// [`Self::close`] with a [`CoreError`].
592    pub fn close_core(&self, path: String) -> Result<(), CoreError> {
593        log_debug!("close {}", path);
594
595        let virtual_port = crate::sync_util::lock_or_recover(&self.virtual_ports)
596            .get(&path)
597            .cloned();
598        if let Some(vp) = virtual_port {
599            let session = self
600                .resolve_connected_port(&vp.physical_path)
601                .ok()
602                .and_then(|cp| crate::sync_util::lock_or_recover(&cp.mux).clone());
603            // First, so a sink that waits in an exchange does not hold up the rest.
604            vp.tx_queue.cancel_all();
605            if let Some(session) = &session {
606                session.begin_close(Some(vp.dlci));
607            }
608            self.forget_old_watches(&path);
609            for id in self.core_watch_ids_for(&path) {
610                let _ = self.unwatch_core(SubscriptionId(id));
611            }
612            let removed = crate::sync_util::lock_or_recover(&self.virtual_ports).remove(&path);
613            if let Some(vp) = removed {
614                vp.tx_queue.cancel_all();
615                if let Some(session) = session {
616                    session.unregister_dlci(vp.dlci);
617                }
618                self.emit_port_state(&path, PortStatus::Closed);
619                return Ok(());
620            }
621        }
622
623        // Physical port: its virtual channels and CMUX session go with it.
624        if let Ok(cp) = self.resolve_connected_port(&path) {
625            self.begin_close(&path, &cp);
626            let _ = self.disable_mux(path.clone());
627        }
628
629        let removed = match self.serialports.lock() {
630            Ok(mut serialports) => serialports.remove(&path),
631            Err(error) => {
632                return Err(Error::String(format!("Failed to acquire lock: {}", error)).into());
633            }
634        };
635
636        if let Some(port_info) = removed {
637            log_debug!("stop {}", path);
638            self.drop_writer(&path);
639            let finished = finish_serialport_info(&path, port_info);
640            self.forget_watches(&path);
641            finished?;
642            self.emit_port_state(&path, PortStatus::Closed);
643            log_debug!("end {}", path);
644            Ok(())
645        } else {
646            self.forget_watches(&path);
647            if crate::sync_util::lock_or_recover(&self.core.disconnected)
648                .remove(&path)
649                .is_some()
650            {
651                return Ok(());
652            }
653            Err(CoreError::new(
654                ErrorKind::NotFound,
655                Error::String(format!("Serial port {} is not open!", path)),
656            ))
657        }
658    }
659
660    /// First step of a close: what waits on `path` or its channels fails, so a sink that
661    /// waits in an exchange does not hold up the rest.
662    fn begin_close(&self, path: &str, cp: &ConnectedPortHandle) {
663        let queues: Vec<_> = crate::sync_util::lock_or_recover(&self.virtual_ports)
664            .values()
665            .filter(|vp| vp.physical_path == path)
666            .map(|vp| vp.tx_queue.clone())
667            .collect();
668        for queue in queues.iter().chain([&cp.tx_queue]) {
669            queue.cancel_all();
670        }
671        if let Some(session) = crate::sync_util::lock_or_recover(&cp.mux).as_ref() {
672            session.begin_close(None);
673        }
674        if let Some(hub) = crate::sync_util::lock_or_recover(&cp.rx_hub).as_ref() {
675            hub.shared().begin_close();
676        }
677    }
678
679    /// Close all open serial ports
680    pub fn close_all(&self) -> Result<(), Error> {
681        let paths = self.managed_ports()?;
682        let mut errors = vec![];
683
684        // CMUX channels first: closing their port closes them too.
685        let (channels, ports): (Vec<_>, Vec<_>) =
686            paths.into_iter().partition(|p| parse_mux_path(p).is_some());
687        for path in channels.into_iter().chain(ports) {
688            if let Err(e) = self.close(path) {
689                errors.push(e.to_string());
690            }
691        }
692
693        if errors.is_empty() {
694            Ok(())
695        } else {
696            Err(Error::String(errors.join(", ")))
697        }
698    }
699
700    /// Force close a serial port
701    pub fn force_close(&self, path: String) -> Result<(), Error> {
702        if crate::sync_util::lock_or_recover(&self.virtual_ports).contains_key(&path) {
703            return self.close(path);
704        }
705        let connected = self.resolve_connected_port(&path);
706        if let Ok(cp) = &connected {
707            self.begin_close(&path, cp);
708        }
709        self.close_virtual_channels_of(&path);
710        if let Ok(cp) = connected {
711            if let Some(session) = crate::sync_util::lock_or_recover(&cp.mux).take() {
712                session.close_down();
713            }
714        }
715
716        // Remove under the lock, join the hub outside it (lock order, see the struct docs).
717        let removed = match self.serialports.lock() {
718            Ok(mut map) => map.remove(&path),
719            Err(error) => return Err(Error::String(format!("Failed to acquire lock: {}", error))),
720        };
721        self.drop_writer(&path);
722        crate::sync_util::lock_or_recover(&self.core.disconnected).remove(&path);
723        if let Some(serial) = removed {
724            let finished = finish_serialport_info(&path, serial);
725            self.forget_watches(&path);
726            finished?;
727            self.emit_port_state(&path, PortStatus::Closed);
728        } else {
729            self.forget_watches(&path);
730        }
731        Ok(())
732    }
733
734    #[allow(clippy::too_many_arguments)]
735    pub fn open(
736        &self,
737        path: String,
738        baud_rate: u32,
739        data_bits: Option<DataBits>,
740        flow_control: Option<FlowControl>,
741        parity: Option<Parity>,
742        stop_bits: Option<StopBits>,
743        timeout: Option<u64>,
744    ) -> Result<String, Error> {
745        self.open_with_lines(
746            path,
747            baud_rate,
748            data_bits,
749            flow_control,
750            parity,
751            stop_bits,
752            timeout,
753            crate::state::ModemLinesOnOpen::default(),
754        )
755    }
756
757    /// [`Self::open`] with explicit DTR / RTS levels on open.
758    #[allow(clippy::too_many_arguments)]
759    pub fn open_with_lines(
760        &self,
761        path: String,
762        baud_rate: u32,
763        data_bits: Option<DataBits>,
764        flow_control: Option<FlowControl>,
765        parity: Option<Parity>,
766        stop_bits: Option<StopBits>,
767        timeout: Option<u64>,
768        lines: crate::state::ModemLinesOnOpen,
769    ) -> Result<String, Error> {
770        self.open_core(
771            path,
772            baud_rate,
773            data_bits,
774            flow_control,
775            parity,
776            stop_bits,
777            timeout,
778            lines,
779        )
780        .map_err(Error::from)
781    }
782
783    /// [`Self::open_with_lines`] with a [`CoreError`] (kind `NotFound`, `PermissionDenied`,
784    /// `Busy`, … and the platform error as its source). `timeout` (ms, default 1000)
785    /// is the port's read / write timeout; [`Self::set_timeout`] changes it later.
786    ///
787    /// Opening a path that is already open (or disconnected and not yet closed)
788    /// replaces that session, as `open` does in 4.x: it is closed first, with its
789    /// watches, `watch_core` streams, CMUX channels and RX hub.
790    #[allow(clippy::too_many_arguments)]
791    pub fn open_core(
792        &self,
793        path: String,
794        baud_rate: u32,
795        data_bits: Option<DataBits>,
796        flow_control: Option<FlowControl>,
797        parity: Option<Parity>,
798        stop_bits: Option<StopBits>,
799        timeout: Option<u64>,
800        lines: crate::state::ModemLinesOnOpen,
801    ) -> Result<String, CoreError> {
802        self.open_core_with(
803            path,
804            baud_rate,
805            data_bits,
806            flow_control,
807            parity,
808            stop_bits,
809            timeout,
810            lines,
811            None,
812        )
813    }
814
815    /// [`Self::open_core`] plus a [`Self::watch_core`] stream that exists before the
816    /// port's first read: no byte and no event is lost (a `RDY` / URC sent right after
817    /// open, or a `Disconnect` of a port that dies at once, which still returns `Ok`).
818    /// Returns the session path and the stream's id (for [`Self::unwatch_core`]). An
819    /// invalid `parser` fails before the port is opened.
820    #[allow(clippy::too_many_arguments)]
821    pub fn open_watch_core(
822        &self,
823        path: String,
824        baud_rate: u32,
825        data_bits: Option<DataBits>,
826        flow_control: Option<FlowControl>,
827        parity: Option<Parity>,
828        stop_bits: Option<StopBits>,
829        timeout: Option<u64>,
830        lines: crate::state::ModemLinesOnOpen,
831        options: WatchOptions,
832        parser: Option<serial_codec::framing::FramerConfig>,
833        sink: CoreSink,
834    ) -> Result<(String, SubscriptionId), CoreError> {
835        let (id, queue, slot) = self.first_core_watch(&options, parser, sink)?;
836        match self.open_core_with(
837            path,
838            baud_rate,
839            data_bits,
840            flow_control,
841            parity,
842            stop_bits,
843            timeout,
844            lines,
845            Some(slot),
846        ) {
847            Ok(session) => {
848                crate::sync_util::lock_or_recover(&self.core.core_watches)
849                    .insert(id, session.clone());
850                Ok((session, SubscriptionId(id)))
851            }
852            Err(e) => {
853                queue.close();
854                Err(e)
855            }
856        }
857    }
858
859    /// [`Self::insert_port`] plus a [`Self::watch_core`] stream that exists before the
860    /// port's first read, as [`Self::open_watch_core`].
861    pub fn insert_port_watch_core(
862        &self,
863        path: String,
864        port: Box<dyn SerialPortTrait>,
865        options: WatchOptions,
866        parser: Option<serial_codec::framing::FramerConfig>,
867        sink: CoreSink,
868    ) -> Result<SubscriptionId, CoreError> {
869        let (id, queue, slot) = self.first_core_watch(&options, parser, sink)?;
870        match self.insert_port_with(path.clone(), port, Some(slot)) {
871            Ok(()) => {
872                crate::sync_util::lock_or_recover(&self.core.core_watches).insert(id, path);
873                Ok(SubscriptionId(id))
874            }
875            Err(e) => {
876                queue.close();
877                Err(e)
878            }
879        }
880    }
881
882    /// The stream of `open_watch_core` / `insert_port_watch_core`, not attached yet.
883    fn first_core_watch(
884        &self,
885        options: &WatchOptions,
886        parser: Option<serial_codec::framing::FramerConfig>,
887        sink: CoreSink,
888    ) -> Result<(u64, Arc<CoreQueue>, CoreWatchSlot), CoreError> {
889        let framer = parser
890            .as_ref()
891            .map(|p| p.build())
892            .transpose()
893            .map_err(|e| CoreError::new(ErrorKind::Other, Error::String(e.to_string())))?;
894        let (batch_timeout, read_size, route_urc) = watch_params(options);
895        let id = next_subscription_id();
896        let queue = CoreQueue::spawn(sink, self.core_queue_capacity());
897        let slot = CoreWatchSlot::new(
898            id,
899            core_target(&queue),
900            batch_timeout,
901            read_size,
902            route_urc,
903            framer,
904        );
905        Ok((id, queue, slot))
906    }
907
908    #[allow(clippy::too_many_arguments)]
909    fn open_core_with(
910        &self,
911        path: String,
912        baud_rate: u32,
913        data_bits: Option<DataBits>,
914        flow_control: Option<FlowControl>,
915        parity: Option<Parity>,
916        stop_bits: Option<StopBits>,
917        timeout: Option<u64>,
918        lines: crate::state::ModemLinesOnOpen,
919        first_watch: Option<CoreWatchSlot>,
920    ) -> Result<String, CoreError> {
921        // Re-open (e.g. after a webview reload): tear the old session down the same
922        // way `close` does, so its watches, CMUX channels and hub go with it.
923        let already_open = matches!(
924            crate::sync_util::lock_or_recover(&self.serialports)
925                .get(&path)
926                .map(|i| &i.state),
927            Some(PortState::Connected(_))
928        );
929        let released =
930            crate::sync_util::lock_or_recover(&self.core.disconnected).contains_key(&path);
931        if already_open || released {
932            log_info!("Replacing existing port {}", path);
933            let _ = self.close(path.clone());
934        }
935        let stale = {
936            let mut serialports = self
937                .serialports
938                .lock()
939                .map_err(|e| Error::String(format!("Failed to acquire lock: {}", e)))?;
940            if matches!(
941                serialports.get(&path).map(|i| &i.state),
942                Some(PortState::Opening)
943            ) {
944                return Err(Error::String(format!("open already in progress for {}", path)).into());
945            }
946            let stale = serialports.remove(&path);
947            serialports.insert(
948                path.clone(),
949                SerialportInfo {
950                    state: PortState::Opening,
951                },
952            );
953            stale
954        };
955
956        if let Some(existing) = stale {
957            log_info!("Replacing existing port {}", path);
958            finish_serialport_info(&path, existing)?;
959        }
960
961        let timeout = Duration::from_millis(timeout.unwrap_or(DEFAULT_PORT_TIMEOUT_MS));
962        let port_result = platform_open(
963            &path,
964            baud_rate,
965            data_bits.unwrap_or(DataBits::Eight),
966            flow_control.unwrap_or(FlowControl::None),
967            parity.unwrap_or(Parity::None),
968            stop_bits.unwrap_or(StopBits::One),
969            timeout,
970            lines,
971        );
972
973        let mut serialports = self
974            .serialports
975            .lock()
976            .map_err(|e| Error::String(format!("Failed to acquire lock: {}", e)))?;
977
978        match port_result {
979            Ok((session_path, port)) => {
980                if session_path != path {
981                    serialports.remove(&path);
982                    if !serialports.contains_key(&session_path) {
983                        serialports.insert(
984                            session_path.clone(),
985                            SerialportInfo {
986                                state: PortState::Opening,
987                            },
988                        );
989                    }
990                }
991
992                let (cp, hub) = self.connect(&session_path, port, timeout, first_watch);
993                let reserved = matches!(
994                    serialports.get(&session_path).map(|i| &i.state),
995                    Some(PortState::Opening)
996                );
997                if let (Ok(()), true) = (&hub, reserved) {
998                    if let Some(entry) = serialports.get_mut(&session_path) {
999                        entry.state = PortState::Connected(cp);
1000                    }
1001                    // Under the map lock: a disconnect hook (it waits for the lock)
1002                    // reports `Disconnected` after this `Opened`.
1003                    self.emit_port_state(&session_path, PortStatus::Opened);
1004                    drop(serialports);
1005                    return Ok(session_path);
1006                }
1007                // Never leave an `Opening` entry or a running hub thread behind.
1008                if reserved {
1009                    serialports.remove(&session_path);
1010                }
1011                drop(serialports);
1012                self.drop_writer(&session_path);
1013                let _ = finish_serialport_info(
1014                    &session_path,
1015                    SerialportInfo {
1016                        state: PortState::Connected(cp),
1017                    },
1018                );
1019                hub?;
1020                Err(
1021                    Error::String(format!("Port '{}' state changed during open", session_path))
1022                        .into(),
1023                )
1024            }
1025            Err(e) => {
1026                if matches!(
1027                    serialports.get(&path).map(|i| &i.state),
1028                    Some(PortState::Opening)
1029                ) {
1030                    serialports.remove(&path);
1031                }
1032                Err(e)
1033            }
1034        }
1035    }
1036
1037    /// Manage `port` under `path` as if [`Self::open`] had opened it (tests, custom
1038    /// transports, a fake device). An open port under `path` is closed first. Its
1039    /// current `timeout()` is the port timeout.
1040    ///
1041    /// On Unix (not TCP / BLE) writes and control calls go to `port.try_clone()` when
1042    /// it succeeds, reads to `port`: a clone must share the device (like a dup'ed fd),
1043    /// or `try_clone` must return `Err` to keep one handle for everything.
1044    pub fn insert_port(
1045        &self,
1046        path: String,
1047        port: Box<dyn SerialPortTrait>,
1048    ) -> Result<(), CoreError> {
1049        self.insert_port_with(path, port, None)
1050    }
1051
1052    fn insert_port_with(
1053        &self,
1054        path: String,
1055        port: Box<dyn SerialPortTrait>,
1056        first_watch: Option<CoreWatchSlot>,
1057    ) -> Result<(), CoreError> {
1058        let known = crate::sync_util::lock_or_recover(&self.serialports).contains_key(&path)
1059            || crate::sync_util::lock_or_recover(&self.core.disconnected).contains_key(&path);
1060        if known {
1061            let _ = self.close(path.clone());
1062        }
1063        let timeout = port.timeout();
1064        // Under the map lock (as `open_core`): a device failing at once is reported by
1065        // its disconnect hook, which waits for the record.
1066        let mut serialports = crate::sync_util::lock_or_recover(&self.serialports);
1067        let (cp, hub) = self.connect(&path, port, timeout, first_watch);
1068        if let Err(e) = hub {
1069            drop(serialports);
1070            self.drop_writer(&path);
1071            let _ = finish_serialport_info(
1072                &path,
1073                SerialportInfo {
1074                    state: PortState::Connected(cp),
1075                },
1076            );
1077            return Err(e.into());
1078        }
1079        serialports.insert(
1080            path.clone(),
1081            SerialportInfo {
1082                state: PortState::Connected(cp),
1083            },
1084        );
1085        self.emit_port_state(&path, PortStatus::Opened);
1086        drop(serialports);
1087        Ok(())
1088    }
1089
1090    /// Stream port events into `sink` (one watch per port and manager). Returns the id
1091    /// for [`Self::unwatch`]. As in 4.x, `sink` runs on the RX side: the port's hub
1092    /// thread, or the caller of `unwatch` / `close` for the tail they deliver. It never
1093    /// runs under a manager lock, but a slow sink holds up RX (keep it short, e.g.
1094    /// forward into a channel), and calling `at()` / `exchange` on the same port from
1095    /// it waits for the RX it blocks. Nothing reaches it after `unwatch()` or `close()`
1096    /// returned (called from a sink they do not wait: what another thread delivers right
1097    /// then, or the tail of the sink's own watch, follows). A panic in it is caught and
1098    /// ends the watch.
1099    /// [`Self::watch_core`] has its own delivery thread instead.
1100    pub fn watch(
1101        &self,
1102        path: String,
1103        options: WatchOptions,
1104        sink: EventSink,
1105    ) -> Result<u32, Error> {
1106        self.watch_framed(path, options, None, sink)
1107    }
1108
1109    /// [`Self::watch`] under a caller-chosen id (the plugin uses its IPC channel id).
1110    pub fn watch_with_id(
1111        &self,
1112        channel_id: u32,
1113        path: String,
1114        options: WatchOptions,
1115        sink: EventSink,
1116    ) -> Result<u32, Error> {
1117        self.watch_framed_with_id(channel_id, path, options, None, sink)
1118    }
1119
1120    /// [`Self::watch`] with a native parser: each complete frame becomes exactly one
1121    /// [`SerialEvent::Data`] (the batch timer no longer
1122    /// applies). An invalid config fails before the watch starts. With
1123    /// [`WatchOptions::route_urc`] the URC split runs first and only non-URC lines reach
1124    /// the parser. On unwatch, close or disconnect the parser's buffered remainder is
1125    /// sent as a final `data` event (before `disconnect`), like Node serialport emits
1126    /// on stream end.
1127    pub fn watch_framed(
1128        &self,
1129        path: String,
1130        options: WatchOptions,
1131        parser: Option<serial_codec::framing::FramerConfig>,
1132        sink: EventSink,
1133    ) -> Result<u32, Error> {
1134        let id = next_watch_id(|id| {
1135            crate::sync_util::lock_or_recover(&self.core.watches).contains_key(&id)
1136                || crate::port::watch_registry::contains(id)
1137        });
1138        self.watch_framed_with_id(id, path, options, parser, sink)
1139    }
1140
1141    /// [`Self::watch_framed`] under a caller-chosen id.
1142    pub fn watch_framed_with_id(
1143        &self,
1144        channel_id: u32,
1145        path: String,
1146        options: WatchOptions,
1147        parser: Option<serial_codec::framing::FramerConfig>,
1148        channel: EventSink,
1149    ) -> Result<u32, Error> {
1150        // Validate the parser before anything is registered or attached.
1151        let mut framer = parser
1152            .as_ref()
1153            .map(|p| p.build())
1154            .transpose()
1155            .map_err(|e| Error::String(e.to_string()))?;
1156        self.register_watch(channel_id, &path)?;
1157        log_debug!("Starting watch on port: {} (channel {})", path, channel_id);
1158
1159        // Released after a disconnect: the late watch gets that `Disconnect` (4.x).
1160        if let Some(reason) = self.released_reason(&path) {
1161            crate::port::watch_registry::send_event_to(
1162                &channel,
1163                SerialEvent::Disconnect { path, reason },
1164            );
1165            return Ok(channel_id);
1166        }
1167
1168        let (batch_timeout, read_size, route_urc) = watch_params(&options);
1169
1170        if let Ok(virtuals) = self.virtual_ports.lock() {
1171            if let Some(vp) = virtuals.get(&path).cloned() {
1172                drop(virtuals);
1173                let session = self
1174                    .resolve_connected_port(&vp.physical_path)
1175                    .and_then(|cp| {
1176                        crate::sync_util::lock_or_recover(&cp.mux)
1177                            .clone()
1178                            .ok_or_else(|| Error::String("CMUX not enabled".into()))
1179                    });
1180                let session = match session {
1181                    Ok(session) => session,
1182                    Err(e) => {
1183                        self.unregister_watch(channel_id);
1184                        return Err(e);
1185                    }
1186                };
1187                if let Err(e) = self.ensure_rx_hub_on_physical(&vp.physical_path) {
1188                    self.unregister_watch(channel_id);
1189                    return Err(e);
1190                }
1191                let attached = session.attach_stream(vp.dlci, channel, batch_timeout, framer);
1192                if let Some((owner, stream)) = attached {
1193                    self.bind_watch(channel_id, owner, &stream);
1194                }
1195                return Ok(channel_id);
1196            }
1197        }
1198
1199        let attached = self.with_connected_port(path.clone(), |cp| {
1200            if cp.virtual_dlci.is_some() {
1201                return Err(Error::String("legacy virtual ConnectedPort".into()));
1202            }
1203            self.ensure_rx_hub(&cp.handle(), &path)?;
1204            let guard = cp
1205                .rx_hub
1206                .lock()
1207                .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?;
1208            let shared = guard
1209                .as_ref()
1210                .ok_or_else(|| Error::String("RX hub missing after start".into()))?
1211                .shared();
1212            let stream =
1213                shared.attach_stream(channel, batch_timeout, read_size, route_urc, framer.take());
1214            Ok((shared, stream))
1215        });
1216        match attached {
1217            Ok((shared, stream)) => self.bind_watch(channel_id, shared, &stream),
1218            Err(e) => {
1219                self.unregister_watch(channel_id);
1220                return Err(e);
1221            }
1222        }
1223
1224        Ok(channel_id)
1225    }
1226
1227    /// Stop a [`Self::watch`]. What it still holds (its batch, an unfinished line, its
1228    /// parser's remainder) is delivered first, in order, and nothing reaches its sink after
1229    /// this returned. If the sink is running on another thread this waits for it, so do not
1230    /// hold a lock the sink takes. Called from a sink it does not wait (two sinks may
1231    /// unwatch each other): the delivery in progress goes on when that sink returns.
1232    pub fn unwatch(&self, channel_id: u32) -> Result<(), Error> {
1233        let (path, attached) = {
1234            let mut watches = crate::sync_util::lock_or_recover(&self.core.watches);
1235            let watch = watches
1236                .get_mut(&channel_id)
1237                .filter(|w| !w.stopping)
1238                .ok_or_else(|| Error::new(format!("No active watch for channel {}", channel_id)))?;
1239            watch.stopping = true;
1240            (watch.path.clone(), watch.attached.clone())
1241        };
1242        log_debug!("Stopping watch on port: {} (channel {})", path, channel_id);
1243        // No lock held: the sink may run here.
1244        if let Some(attached) = attached {
1245            attached.stop();
1246        }
1247        let mut watches = crate::sync_util::lock_or_recover(&self.core.watches);
1248        // Closed meanwhile, the id may be a new watch's.
1249        if watches.get(&channel_id).is_some_and(|w| w.stopping) {
1250            watches.remove(&channel_id);
1251            crate::port::watch_registry::mirror_remove(channel_id);
1252        }
1253        Ok(())
1254    }
1255
1256    pub fn read(
1257        &self,
1258        path: String,
1259        timeout: Option<u64>,
1260        size: Option<usize>,
1261    ) -> Result<String, Error> {
1262        let bytes = self.read_via_hub(path, timeout, size, false)?;
1263        Ok(String::from_utf8_lossy(&bytes).to_string())
1264    }
1265
1266    pub fn read_binary(
1267        &self,
1268        path: String,
1269        timeout: Option<u64>,
1270        size: Option<usize>,
1271    ) -> Result<Vec<u8>, Error> {
1272        self.read_via_hub(path, timeout, size, true)
1273    }
1274
1275    fn read_via_hub(
1276        &self,
1277        path: String,
1278        timeout: Option<u64>,
1279        size: Option<usize>,
1280        fill: bool,
1281    ) -> Result<Vec<u8>, Error> {
1282        let cp = self.resolve_connected_port(&path)?;
1283        self.ensure_rx_hub(&cp, &path)?;
1284        let hub_shared = {
1285            let guard = cp
1286                .rx_hub
1287                .lock()
1288                .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?;
1289            guard
1290                .as_ref()
1291                .ok_or_else(|| Error::String("RX hub missing".into()))?
1292                .shared()
1293        };
1294        hub_shared
1295            .read_request(size.unwrap_or(1024), timeout.unwrap_or(1000), fill)
1296            .map_err(Error::String)
1297    }
1298
1299    /// Write data to the serial port (or a CMUX channel `path#dlci=N`).
1300    pub fn write(&self, path: String, value: String) -> Result<usize, Error> {
1301        self.write_bytes(&path, value.as_bytes(), "write data")
1302            .map_err(Error::from)
1303    }
1304
1305    /// Write binary data to the serial port (or a CMUX channel `path#dlci=N`).
1306    pub fn write_binary(&self, path: String, value: Vec<u8>) -> Result<usize, Error> {
1307        self.write_bytes(&path, &value, "write binary data")
1308            .map_err(Error::from)
1309    }
1310
1311    /// [`Self::write_binary`] with a [`CoreError`] (the I/O error as its source).
1312    pub fn write_core(&self, path: String, data: Vec<u8>) -> Result<usize, CoreError> {
1313        self.write_bytes(&path, &data, "write binary data")
1314    }
1315
1316    fn write_bytes(&self, path: &str, data: &[u8], operation: &str) -> Result<usize, CoreError> {
1317        let virtual_port = crate::sync_util::lock_or_recover(&self.virtual_ports)
1318            .get(path)
1319            .cloned();
1320        if let Some(vp) = virtual_port {
1321            let cp = self.resolve_connected_port(&vp.physical_path)?;
1322            let session = crate::sync_util::lock_or_recover(&cp.mux)
1323                .clone()
1324                .ok_or_else(|| Error::String("CMUX not enabled".into()))?;
1325            return session
1326                .send_uih(vp.dlci, data)
1327                .map_err(|e| Error::String(format!("Failed to {operation}: {e}")).into());
1328        }
1329        let cp = self.resolve_connected_port(path)?;
1330        match self.writer_of(path, &cp) {
1331            Some(writer) => write_all_split(&writer, data, operation),
1332            None => with_port_try_lock(
1333                &cp.port,
1334                Duration::from_millis(PORT_LOCK_TIMEOUT_MS),
1335                |port| write_all_port(port, data, operation),
1336            ),
1337        }
1338    }
1339
1340    /// Set the baud rate
1341    pub fn set_baud_rate(&self, path: String, baud_rate: u32) -> Result<(), Error> {
1342        self.get_serialport(path, |port| {
1343            port.set_baud_rate(baud_rate)
1344                .map_err(|e| Error::String(format!("Failed to set baud rate: {}", e)))
1345        })
1346    }
1347
1348    /// Set the data bits
1349    pub fn set_data_bits(&self, path: String, data_bits: DataBits) -> Result<(), Error> {
1350        self.get_serialport(path, |port| {
1351            port.set_data_bits(data_bits.into()).map_err(Error::from)
1352        })
1353    }
1354
1355    /// Set the flow control
1356    pub fn set_flow_control(&self, path: String, flow_control: FlowControl) -> Result<(), Error> {
1357        self.get_serialport(path, |port| {
1358            port.set_flow_control(flow_control.into())
1359                .map_err(Error::from)
1360        })
1361    }
1362
1363    /// Set the parity
1364    pub fn set_parity(&self, path: String, parity: Parity) -> Result<(), Error> {
1365        self.get_serialport(path, |port| {
1366            port.set_parity(parity.into()).map_err(Error::from)
1367        })
1368    }
1369
1370    /// Set the stop bits
1371    pub fn set_stop_bits(&self, path: String, stop_bits: StopBits) -> Result<(), Error> {
1372        self.get_serialport(path, |port| {
1373            port.set_stop_bits(stop_bits.into()).map_err(Error::from)
1374        })
1375    }
1376
1377    /// Set the timeout
1378    pub fn set_timeout(&self, path: String, timeout: Duration) -> Result<(), Error> {
1379        self.get_serialport(path, |port| port.set_timeout(timeout).map_err(Error::from))
1380    }
1381
1382    /// Set the RTS (Request To Send) control signal
1383    pub fn write_request_to_send(&self, path: String, level: bool) -> Result<(), Error> {
1384        self.get_serialport(path, |port| {
1385            port.write_request_to_send(level).map_err(Error::from)
1386        })
1387    }
1388
1389    /// Set the DTR (Data Terminal Ready) control signal
1390    pub fn write_data_terminal_ready(&self, path: String, level: bool) -> Result<(), Error> {
1391        self.get_serialport(path, |port| {
1392            port.write_data_terminal_ready(level).map_err(Error::from)
1393        })
1394    }
1395
1396    /// Read the CTS (Clear To Send) control signal state
1397    pub fn read_clear_to_send(&self, path: String) -> Result<bool, Error> {
1398        self.get_serialport(path, |port| port.read_clear_to_send().map_err(Error::from))
1399    }
1400
1401    /// Read the DSR (Data Set Ready) control signal state
1402    pub fn read_data_set_ready(&self, path: String) -> Result<bool, Error> {
1403        self.get_serialport(path, |port| port.read_data_set_ready().map_err(Error::from))
1404    }
1405
1406    /// Read the RI (Ring Indicator) control signal state
1407    pub fn read_ring_indicator(&self, path: String) -> Result<bool, Error> {
1408        self.get_serialport(path, |port| port.read_ring_indicator().map_err(Error::from))
1409    }
1410
1411    /// Read the CD (Carrier Detect) control signal state
1412    pub fn read_carrier_detect(&self, path: String) -> Result<bool, Error> {
1413        self.get_serialport(path, |port| port.read_carrier_detect().map_err(Error::from))
1414    }
1415
1416    /// Get the number of bytes available to read
1417    pub fn bytes_to_read(&self, path: String) -> Result<u32, Error> {
1418        if let Some(reason) = self.released_reason(&path) {
1419            return Err(Error::String(reason));
1420        }
1421        let hub_buffered = if let Ok(cp) = self.resolve_connected_port(&path) {
1422            cp.rx_hub
1423                .lock()
1424                .ok()
1425                .and_then(|guard| guard.as_ref().map(|hub| hub.shared().buffered_len() as u32))
1426                .unwrap_or(0)
1427        } else {
1428            0
1429        };
1430        // Wait for the handle (the hub holds the reader during a poll) instead of
1431        // reporting 0 whenever it is busy.
1432        let port_buffered = if let Ok(cp) = self.resolve_connected_port(&path) {
1433            let port = self.writer_of(&path, &cp).unwrap_or(cp.port);
1434            lock_with_deadline(
1435                &port,
1436                Duration::from_millis(PORT_LOCK_TIMEOUT_MS),
1437                false,
1438                |p| p.bytes_to_read().map_err(Error::from),
1439            )
1440            .unwrap_or(0)
1441        } else {
1442            0
1443        };
1444        Ok(hub_buffered.saturating_add(port_buffered))
1445    }
1446
1447    /// Get the number of bytes waiting to be written
1448    pub fn bytes_to_write(&self, path: String) -> Result<u32, Error> {
1449        self.get_serialport(path, |port| port.bytes_to_write().map_err(Error::from))
1450    }
1451
1452    /// Clear input/output buffers
1453    /// `Input` / `All` also drop what the RX hub holds for no one yet.
1454    pub fn clear_buffer(&self, path: String, buffer_to_clear: ClearBuffer) -> Result<(), Error> {
1455        let input = !matches!(buffer_to_clear, ClearBuffer::Output);
1456        self.get_serialport(path.clone(), |port| {
1457            port.clear(buffer_to_clear.into()).map_err(Error::from)
1458        })?;
1459        if input {
1460            if let Ok(cp) = self.resolve_connected_port(&path) {
1461                if let Some(hub) = crate::sync_util::lock_or_recover(&cp.rx_hub).as_ref() {
1462                    hub.shared().purge_buffers();
1463                }
1464            }
1465        }
1466        Ok(())
1467    }
1468
1469    /// Start break signal transmission
1470    pub fn set_break(&self, path: String) -> Result<(), Error> {
1471        self.get_serialport(path, |port| port.set_break().map_err(Error::from))
1472    }
1473
1474    /// Stop break signal transmission
1475    pub fn clear_break(&self, path: String) -> Result<(), Error> {
1476        self.get_serialport(path, |port| port.clear_break().map_err(Error::from))
1477    }
1478
1479    /// Write payload and read until terminators, idle silence, or timeout (AT-style exchange).
1480    pub fn exchange(
1481        &self,
1482        path: String,
1483        value: String,
1484        options: ExchangeOptions,
1485    ) -> Result<crate::at::parse::ExchangeResponse, Error> {
1486        self.exchange_bytes(path, value.into_bytes(), options)
1487    }
1488
1489    /// Binary variant of [`Self::exchange`].
1490    pub fn exchange_binary(
1491        &self,
1492        path: String,
1493        value: Vec<u8>,
1494        options: ExchangeOptions,
1495    ) -> Result<crate::at::parse::ExchangeResponse, Error> {
1496        self.exchange_bytes(path, value, options)
1497    }
1498
1499    /// [`Self::exchange_binary`] with a [`CoreError`] (`Timeout`, `Cancelled`, …).
1500    pub fn exchange_core(
1501        &self,
1502        path: String,
1503        value: Vec<u8>,
1504        options: ExchangeOptions,
1505    ) -> Result<crate::at::parse::ExchangeResponse, CoreError> {
1506        self.exchange_bytes(path, value, options)
1507            .map_err(CoreError::from)
1508    }
1509
1510    fn get_tx_queue(&self, path: &str) -> Result<Arc<PortTxQueue>, Error> {
1511        if let Ok(virtuals) = self.virtual_ports.lock() {
1512            if let Some(vp) = virtuals.get(path) {
1513                return Ok(vp.tx_queue.clone());
1514            }
1515        }
1516        let ports = self
1517            .serialports
1518            .lock()
1519            .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?;
1520        let info = ports.get(path).ok_or_else(|| self.not_open_error(path))?;
1521        match &info.state {
1522            PortState::Connected(cp) => Ok(cp.tx_queue.clone()),
1523            other => Err(Error::String(other.not_connected_reason())),
1524        }
1525    }
1526
1527    fn exchange_bytes(
1528        &self,
1529        path: String,
1530        payload: Vec<u8>,
1531        options: ExchangeOptions,
1532    ) -> Result<crate::at::parse::ExchangeResponse, Error> {
1533        run_exchange_queued(
1534            path,
1535            options,
1536            |p| self.get_tx_queue(p),
1537            |physical_path,
1538             dlci,
1539             virtual_path,
1540             payload,
1541             options|
1542             -> Result<crate::at::parse::ExchangeResponse, Error> {
1543                self.exchange_bytes_mux_direct(physical_path, dlci, virtual_path, payload, options)
1544            },
1545            |path, payload, options| -> Result<crate::at::parse::ExchangeResponse, Error> {
1546                self.exchange_bytes_direct(path, payload, options)
1547            },
1548            payload,
1549        )
1550    }
1551
1552    fn exchange_bytes_direct(
1553        &self,
1554        path: String,
1555        payload: Vec<u8>,
1556        options: ExchangeOptions,
1557    ) -> Result<crate::at::parse::ExchangeResponse, Error> {
1558        let command = options
1559            .command
1560            .clone()
1561            .unwrap_or_else(|| String::from_utf8_lossy(&payload).into_owned());
1562        let user_solicited = options.solicited_prefixes.clone().unwrap_or_default();
1563        let resolved_timeout = options.resolve().timeout_ms;
1564
1565        let cp = self.resolve_connected_port(&path)?;
1566        self.ensure_rx_hub(&cp, &path)?;
1567
1568        struct DesktopExchangeIo<'a> {
1569            port: &'a PortArc,
1570            writer: Option<PortArc>,
1571            /// For the handle, which the hub holds during a read: not less than a plain write
1572            /// waits, however short the exchange's own timeout (it runs from the write on).
1573            lock_timeout: Duration,
1574        }
1575        impl crate::exchange::io::ExchangeIo for DesktopExchangeIo<'_> {
1576            fn purge_rx(&self) -> Result<(), Error> {
1577                let (port, io_timeout) = match &self.writer {
1578                    Some(w) => (w, false),
1579                    None => (self.port, true),
1580                };
1581                lock_with_deadline(port, self.lock_timeout, io_timeout, |port| {
1582                    port.clear(ClearBuffer::Input.into()).map_err(Error::from)
1583                })
1584            }
1585            fn write_payload(&self, payload: &[u8]) -> Result<(), Error> {
1586                if let Some(w) = &self.writer {
1587                    return write_all_split(w, payload, "exchange write")
1588                        .map(|_| ())
1589                        .map_err(Error::from);
1590                }
1591                with_port_try_lock(self.port, self.lock_timeout, |port| {
1592                    write_all_port(port, payload, "exchange write")
1593                        .map(|_| ())
1594                        .map_err(Error::from)
1595                })
1596            }
1597        }
1598
1599        let hub = {
1600            let guard = crate::sync_util::lock_or_recover(&cp.rx_hub);
1601            guard
1602                .as_ref()
1603                .ok_or_else(|| Error::String("RX hub missing".into()))?
1604                .clone()
1605        };
1606
1607        crate::exchange::run::run_physical_exchange(
1608            hub.as_ref(),
1609            &DesktopExchangeIo {
1610                port: &cp.port,
1611                writer: self.writer_of(&path, &cp),
1612                lock_timeout: Duration::from_millis(
1613                    resolved_timeout.clamp(PORT_LOCK_TIMEOUT_MS, 5000),
1614                ),
1615            },
1616            &command,
1617            &user_solicited,
1618            payload,
1619            options,
1620            cp.exchange_cancel.clone(),
1621        )
1622    }
1623
1624    fn exchange_bytes_mux_direct(
1625        &self,
1626        physical_path: String,
1627        _dlci: u8,
1628        virtual_path: String,
1629        payload: Vec<u8>,
1630        options: ExchangeOptions,
1631    ) -> Result<crate::at::parse::ExchangeResponse, Error> {
1632        let vp = self
1633            .virtual_ports
1634            .lock()
1635            .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?
1636            .get(&virtual_path)
1637            .cloned()
1638            .ok_or_else(|| Error::String(format!("Virtual port '{}' not open", virtual_path)))?;
1639        self.exchange_bytes_mux_via_ref(physical_path, &vp, payload, options)
1640    }
1641
1642    fn exchange_bytes_mux_via_ref(
1643        &self,
1644        physical_path: String,
1645        vp: &crate::state::VirtualPortRef,
1646        payload: Vec<u8>,
1647        options: ExchangeOptions,
1648    ) -> Result<crate::at::parse::ExchangeResponse, Error> {
1649        let dlci = vp.dlci;
1650        let command = options
1651            .command
1652            .clone()
1653            .unwrap_or_else(|| String::from_utf8_lossy(&payload).into_owned());
1654        let user_solicited = options.solicited_prefixes.clone().unwrap_or_default();
1655
1656        let session = {
1657            let ports = self
1658                .serialports
1659                .lock()
1660                .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?;
1661            let info = ports.get(&physical_path).ok_or_else(|| {
1662                Error::String(format!("Physical port '{}' not found", physical_path))
1663            })?;
1664            match &info.state {
1665                PortState::Connected(cp) => cp
1666                    .mux
1667                    .lock()
1668                    .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?
1669                    .clone()
1670                    .ok_or_else(|| Error::String("CMUX not enabled on physical port".into()))?,
1671                other => return Err(Error::String(other.not_connected_reason())),
1672            }
1673        };
1674
1675        self.ensure_rx_hub_on_physical(&physical_path)?;
1676
1677        crate::exchange::run::run_mux_exchange(
1678            &session,
1679            dlci,
1680            &command,
1681            &user_solicited,
1682            payload,
1683            options,
1684            vp.exchange_cancel.clone(),
1685        )
1686    }
1687
1688    fn run_exchange_unqueued(
1689        &self,
1690        path: String,
1691        payload: Vec<u8>,
1692        options: ExchangeOptions,
1693    ) -> Result<crate::at::parse::ExchangeResponse, Error> {
1694        if let Some((physical, dlci)) = parse_mux_path(path.as_str()) {
1695            return self.exchange_bytes_mux_direct(
1696                physical.to_string(),
1697                dlci,
1698                path,
1699                payload,
1700                options,
1701            );
1702        }
1703        self.exchange_bytes_direct(path, payload, options)
1704    }
1705
1706    pub fn at(
1707        &self,
1708        path: String,
1709        command: String,
1710        options: Option<AtCommandOptions>,
1711    ) -> Result<crate::at::parse::AtCommandResult, Error> {
1712        let tx_queue = self.get_tx_queue(&path)?;
1713        crate::at::commands::queue_at(self, &tx_queue, path, command, options)
1714    }
1715
1716    /// [`Self::at`] with a [`CoreError`].
1717    pub fn at_core(
1718        &self,
1719        path: String,
1720        command: String,
1721        options: Option<AtCommandOptions>,
1722    ) -> Result<crate::at::parse::AtCommandResult, CoreError> {
1723        self.at(path, command, options).map_err(CoreError::from)
1724    }
1725
1726    /// Multi-phase AT flow (e.g. CMGS) — phases run atomically without interleaving other jobs.
1727    pub fn at_phases(
1728        &self,
1729        path: String,
1730        phases: Vec<AtPhase>,
1731    ) -> Result<Vec<crate::at::parse::AtCommandResult>, Error> {
1732        let tx_queue = self.get_tx_queue(&path)?;
1733        crate::at::commands::queue_at_phases(self, &tx_queue, path, phases)
1734    }
1735
1736    /// Built-in CMGS recipe: `AT+CMGS=n` → `>` → PDU + Ctrl+Z → final line.
1737    pub fn send_sms_pdu(
1738        &self,
1739        path: String,
1740        length: u32,
1741        pdu: Vec<u8>,
1742        options: Option<SendSmsPduOptions>,
1743    ) -> Result<Vec<crate::at::parse::AtCommandResult>, Error> {
1744        let tx_queue = self.get_tx_queue(&path)?;
1745        crate::at::commands::queue_send_sms_pdu(self, &tx_queue, path, length, pdu, options)
1746    }
1747
1748    /// Configure AT session defaults for native `at` jobs on this port.
1749    pub fn configure_at_session(
1750        &self,
1751        path: String,
1752        session: AtSessionConfig,
1753    ) -> Result<(), Error> {
1754        let tx_queue = self
1755            .resolve_connected_port(&path)
1756            .map(|cp| cp.tx_queue.clone())
1757            .ok();
1758        configure_at_session_shared(&self.virtual_ports, tx_queue, &path, session)
1759    }
1760
1761    /// Enter GSM 07.10 CMUX mode (`AT+CMUX=…` then attach deframer to the RX hub).
1762    pub fn enable_mux(&self, path: String, command: String, timeout_ms: u64) -> Result<(), Error> {
1763        let response = self.exchange(
1764            path.clone(),
1765            format!("{command}\r"),
1766            ExchangeOptions {
1767                timeout_ms: Some(timeout_ms),
1768                rx_prepare: Some(crate::events::RxPrepareMode::None),
1769                ..Default::default()
1770            },
1771        )?;
1772        if response.status != crate::at::parse::AtParseStatus::Ok {
1773            return Err(Error::String(format!(
1774                "modem rejected {command}: {}",
1775                String::from_utf8_lossy(&response.raw).trim()
1776            )));
1777        }
1778        // The modem switches to multiplexer mode a few ms after its OK. A frame sent
1779        // inside that window is lost, and the Quectel M26 then ignores SABM (retries
1780        // included) for about 2 s: wait the switch out before the first frame.
1781        thread::sleep(CMUX_SWITCH_SETTLE);
1782
1783        let cp = self.resolve_connected_port(&path)?;
1784        if cp.virtual_dlci.is_some() {
1785            return Err(Error::String("enable_mux on virtual port".into()));
1786        }
1787        if crate::sync_util::lock_or_recover(&cp.mux).is_some() {
1788            return Err(Error::String("CMUX already enabled".into()));
1789        }
1790        let io_port = self
1791            .writer_of(&path, &cp)
1792            .unwrap_or_else(|| cp.port.clone());
1793        io_port
1794            .lock()
1795            .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?
1796            .clear(ClearBuffer::Input.into())
1797            .map_err(Error::from)?;
1798        let session = CmuxSession::for_command(
1799            path.clone(),
1800            Arc::new(crate::cmux::SerialPortIo(io_port)),
1801            &command,
1802        );
1803        // The modem closed channels (DISC / DM / CLD): their state goes out, and when it
1804        // left multiplexer mode the session is detached (the port is plain again).
1805        let manager = self.downgrade();
1806        let weak = Arc::downgrade(&session);
1807        let physical = path.clone();
1808        session.set_on_closed(Box::new(move |paths, reason, whole| {
1809            let Some(m) = manager.upgrade() else {
1810                return;
1811            };
1812            for p in paths {
1813                m.emit_port_state(
1814                    p,
1815                    PortStatus::Disconnected {
1816                        kind: ErrorKind::Disconnected,
1817                        reason: reason.to_string(),
1818                    },
1819                );
1820            }
1821            if whole {
1822                m.detach_mux_session(&physical, &weak);
1823            }
1824        }));
1825        self.ensure_rx_hub(&cp, &path)?;
1826        if let Some(hub) = crate::sync_util::lock_or_recover(&cp.rx_hub).as_ref() {
1827            hub.attach_cmux(session.clone());
1828        }
1829        // Control channel first; without its UA the modem is not multiplexing.
1830        if let Err(e) = session.open_dlci(0, Duration::from_millis(timeout_ms.max(500))) {
1831            // The modem said OK to AT+CMUX, so it may be multiplexing with the UA lost:
1832            // CLD takes it back to AT mode.
1833            session.close_down();
1834            if let Some(hub) = crate::sync_util::lock_or_recover(&cp.rx_hub).as_ref() {
1835                hub.detach_cmux();
1836            }
1837            return Err(Error::String(e));
1838        }
1839        *crate::sync_util::lock_or_recover(&cp.mux) = Some(session);
1840        Ok(())
1841    }
1842
1843    /// Register a virtual DLCI channel on an CMUX-enabled physical port.
1844    pub fn open_mux_channel(&self, physical_path: String, dlci: u8) -> Result<String, Error> {
1845        if !crate::cmux::is_data_dlci(dlci) {
1846            return Err(Error::String(format!(
1847                "invalid CMUX DLCI {dlci}: data channels are 1..=63"
1848            )));
1849        }
1850        let virtual_path = mux_path(&physical_path, dlci);
1851        let session = {
1852            let ports = self
1853                .serialports
1854                .lock()
1855                .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?;
1856            let info = ports
1857                .get(&physical_path)
1858                .ok_or_else(|| self.not_open_error(&physical_path))?;
1859            match &info.state {
1860                PortState::Connected(cp) => cp
1861                    .mux
1862                    .lock()
1863                    .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?
1864                    .clone()
1865                    .ok_or_else(|| Error::String("CMUX not enabled".into())),
1866                other => Err(Error::String(other.not_connected_reason())),
1867            }
1868        }?;
1869
1870        // Already open on *this* session. An entry left from an earlier session (port
1871        // closed and re-opened) is stale and gets replaced below.
1872        let known = self
1873            .virtual_ports
1874            .lock()
1875            .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?
1876            .contains_key(&virtual_path);
1877        if known && session.has_dlci(dlci) {
1878            return Ok(virtual_path);
1879        }
1880        // Closed by the modem or left from an earlier session: its watches are dead.
1881        if known {
1882            self.forget_watches(&virtual_path);
1883        }
1884
1885        session.register_dlci(dlci, virtual_path.clone());
1886        if let Err(e) = session.open_dlci(dlci, Duration::from_secs(3)) {
1887            session.unregister_dlci(dlci);
1888            return Err(Error::String(e));
1889        }
1890        self.virtual_ports
1891            .lock()
1892            .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?
1893            .insert(virtual_path.clone(), {
1894                let tx_queue = Arc::new(PortTxQueue::new());
1895                crate::state::VirtualPortRef {
1896                    physical_path,
1897                    dlci,
1898                    exchange_cancel: tx_queue.cancel_flag(),
1899                    tx_queue,
1900                }
1901            });
1902        self.emit_port_state(&virtual_path, PortStatus::Opened);
1903        Ok(virtual_path)
1904    }
1905
1906    /// Tear down CMUX: close virtual channels and detach deframer.
1907    /// The CLD wait (up to T2) runs without the manager's map lock.
1908    pub fn disable_mux(&self, path: String) -> Result<(), Error> {
1909        self.close_virtual_channels_of(&path);
1910        let cp = self.resolve_connected_port(&path)?;
1911        let session = crate::sync_util::lock_or_recover(&cp.mux).take();
1912        if let Some(session) = session {
1913            session.close_down();
1914        }
1915        if let Some(hub) = crate::sync_util::lock_or_recover(&cp.rx_hub).as_ref() {
1916            hub.detach_cmux();
1917        }
1918        Ok(())
1919    }
1920
1921    /// The modem left multiplexer mode: drop `session` from `physical` (if it is still
1922    /// that port's session) and its deframer from the hub.
1923    fn detach_mux_session(&self, physical: &str, session: &Weak<CmuxSession>) {
1924        let Ok(cp) = self.resolve_connected_port(physical) else {
1925            return;
1926        };
1927        let mut mux = crate::sync_util::lock_or_recover(&cp.mux);
1928        let current = mux
1929            .as_ref()
1930            .zip(session.upgrade())
1931            .is_some_and(|(a, b)| Arc::ptr_eq(a, &b));
1932        if !current {
1933            return;
1934        }
1935        mux.take();
1936        drop(mux);
1937        if let Some(hub) = crate::sync_util::lock_or_recover(&cp.rx_hub).as_ref() {
1938            hub.detach_cmux();
1939        };
1940    }
1941
1942    /// Close every CMUX virtual channel that rides on `physical`.
1943    fn close_virtual_channels_of(&self, physical: &str) {
1944        let virtual_paths: Vec<String> = crate::sync_util::lock_or_recover(&self.virtual_ports)
1945            .iter()
1946            .filter(|(_, vp)| vp.physical_path == physical)
1947            .map(|(p, _)| p.clone())
1948            .collect();
1949        for vp in virtual_paths {
1950            let _ = self.close(vp);
1951        }
1952    }
1953
1954    /// Cancel an in-flight exchange and reject queued waiters on `path`.
1955    pub fn cancel_exchange(&self, path: String) -> Result<(), Error> {
1956        if let Ok(virtuals) = self.virtual_ports.lock() {
1957            if let Some(vp) = virtuals.get(&path).cloned() {
1958                drop(virtuals);
1959                let session = {
1960                    let ports = self
1961                        .serialports
1962                        .lock()
1963                        .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?;
1964                    let info = ports.get(&vp.physical_path).ok_or_else(|| {
1965                        Error::String(format!("Physical port '{}' not found", vp.physical_path))
1966                    })?;
1967                    match &info.state {
1968                        PortState::Connected(cp) => cp
1969                            .mux
1970                            .lock()
1971                            .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?
1972                            .clone(),
1973                        other => return Err(Error::String(other.not_connected_reason())),
1974                    }
1975                };
1976                if let Some(session) = session {
1977                    crate::exchange::cancel::cancel_virtual_exchange(
1978                        &vp.exchange_cancel,
1979                        &vp.tx_queue,
1980                        &session,
1981                        vp.dlci,
1982                    );
1983                } else {
1984                    vp.exchange_cancel.store(true, Ordering::SeqCst);
1985                    vp.tx_queue.cancel_all();
1986                }
1987                return Ok(());
1988            }
1989        }
1990        let cp = self.resolve_connected_port(&path)?;
1991        crate::exchange::cancel::cancel_physical_exchange(
1992            &cp.exchange_cancel,
1993            &cp.tx_queue,
1994            || {
1995                if let Ok(guard) = cp.rx_hub.lock() {
1996                    if let Some(hub) = guard.as_ref() {
1997                        hub.cancel_active_exchange();
1998                    }
1999                }
2000            },
2001        );
2002        Ok(())
2003    }
2004
2005    /// Resolve a connected port's shared handles (brief global lock only).
2006    fn resolve_connected_port(&self, path: &str) -> Result<ConnectedPortHandle, Error> {
2007        let ports = self
2008            .serialports
2009            .lock()
2010            .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?;
2011        let info = ports.get(path).ok_or_else(|| self.not_open_error(path))?;
2012        match &info.state {
2013            PortState::Connected(cp) => Ok(cp.handle()),
2014            other => Err(Error::String(other.not_connected_reason())),
2015        }
2016    }
2017
2018    /// Run `f` only when the port is [`PortState::Connected`] (holds global lock for `f`).
2019    fn with_connected_port<T, F>(&self, path: String, f: F) -> Result<T, Error>
2020    where
2021        F: FnOnce(&mut ConnectedPort) -> Result<T, Error>,
2022    {
2023        let mut ports = self
2024            .serialports
2025            .lock()
2026            .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?;
2027
2028        let info = ports
2029            .get_mut(&path)
2030            .ok_or_else(|| self.not_open_error(&path))?;
2031
2032        match &mut info.state {
2033            PortState::Connected(cp) => f(cp),
2034            other => Err(Error::String(other.not_connected_reason())),
2035        }
2036    }
2037
2038    /// The error for a path with no record: the disconnect reason of a port the core
2039    /// released (4.x: calls on a dead port fail with a disconnect error), else
2040    /// "Port 'X' not found".
2041    fn not_open_error(&self, path: &str) -> Error {
2042        Error::String(
2043            self.released_reason(path)
2044                .unwrap_or_else(|| format!("Port '{}' not found", path)),
2045        )
2046    }
2047
2048    fn released_reason(&self, path: &str) -> Option<String> {
2049        crate::sync_util::lock_or_recover(&self.core.disconnected)
2050            .get(path)
2051            .cloned()
2052    }
2053
2054    /// Settings, lines, buffers and `set_timeout` go to the write handle when the port
2055    /// has one (no wait for the hub's read, no timeout override), else to the port.
2056    fn get_serialport<T, F>(&self, path: String, f: F) -> Result<T, Error>
2057    where
2058        F: FnOnce(&mut Box<dyn serialport::SerialPort>) -> Result<T, Error>,
2059    {
2060        let cp = self.resolve_connected_port(&path)?;
2061        let lock = Duration::from_millis(PORT_LOCK_TIMEOUT_MS);
2062        match self.writer_of(&path, &cp) {
2063            Some(writer) => lock_with_deadline(&writer, lock, false, f),
2064            None => with_port_try_lock(&cp.port, lock, f),
2065        }
2066    }
2067}
2068
2069fn core_target(queue: &Arc<CoreQueue>) -> Target {
2070    Target::Core {
2071        sink: queue.event_sink(),
2072        alive: queue.alive_flag(),
2073    }
2074}
2075
2076/// Batch window, read size and URC routing of a watch.
2077fn watch_params(options: &WatchOptions) -> (u64, usize, bool) {
2078    let batch_timeout = options
2079        .serial_data_flush_interval_ms
2080        .or(options.timeout)
2081        .unwrap_or(DEFAULT_WATCH_FLUSH_MS);
2082    (
2083        batch_timeout,
2084        options.size.unwrap_or(1024),
2085        options.route_urc,
2086    )
2087}
2088
2089/// The 4.2 core API: [`CoreEvent`] streams, port-state subscriptions, queue limits.
2090impl SerialManager {
2091    /// Stream one port's events into `sink` as [`CoreEvent::Event`] (the final
2092    /// `Disconnect` included). Any number of these may run on a port, beside the old
2093    /// [`Self::watch`]: each gets its own copy of the stream and its own `parser` /
2094    /// `route_urc` state, and URCs caught during `at()` / `exchange` reach every one
2095    /// with `route_urc`. See [`CoreSink`] for threading, the queue and overflow.
2096    pub fn watch_core(
2097        &self,
2098        path: String,
2099        options: WatchOptions,
2100        parser: Option<serial_codec::framing::FramerConfig>,
2101        sink: CoreSink,
2102    ) -> Result<SubscriptionId, CoreError> {
2103        let framer = parser
2104            .as_ref()
2105            .map(|p| p.build())
2106            .transpose()
2107            .map_err(|e| CoreError::new(ErrorKind::Other, Error::String(e.to_string())))?;
2108        let (batch_timeout, read_size, route_urc) = watch_params(&options);
2109        let id = next_subscription_id();
2110        let queue = CoreQueue::spawn(sink, self.core_queue_capacity());
2111        if let Some(reason) = self.released_reason(&path) {
2112            queue.push(CoreEvent::Event(SerialEvent::Disconnect { path, reason }));
2113            queue.close();
2114            return Ok(SubscriptionId(id));
2115        }
2116        let virtual_port = crate::sync_util::lock_or_recover(&self.virtual_ports)
2117            .get(&path)
2118            .cloned();
2119        if let Some(vp) = virtual_port {
2120            let cp = self.resolve_connected_port(&vp.physical_path)?;
2121            let session = crate::sync_util::lock_or_recover(&cp.mux)
2122                .clone()
2123                .ok_or_else(|| Error::String("CMUX not enabled".into()))?;
2124            self.ensure_rx_hub(&cp, &vp.physical_path)?;
2125            if !session.add_core_watch(vp.dlci, id, core_target(&queue), batch_timeout, framer) {
2126                return Err(Error::String(format!("Port '{}' not found", path)).into());
2127            }
2128        } else {
2129            let cp = self.resolve_connected_port(&path)?;
2130            self.ensure_rx_hub(&cp, &path)?;
2131            let shared = crate::sync_util::lock_or_recover(&cp.rx_hub)
2132                .as_ref()
2133                .map(|h| h.shared())
2134                .ok_or_else(|| Error::String("RX hub missing after start".into()))?;
2135            shared.attach_core_watch(CoreWatchSlot::new(
2136                id,
2137                core_target(&queue),
2138                batch_timeout,
2139                read_size,
2140                route_urc,
2141                framer,
2142            ));
2143        }
2144        crate::sync_util::lock_or_recover(&self.core.core_watches).insert(id, path);
2145        Ok(SubscriptionId(id))
2146    }
2147
2148    /// Stop a [`Self::watch_core`] stream; its batch and parser remainder arrive last.
2149    /// `NotFound` also for a stream that already ended (overflow, sink returned
2150    /// `false`, port gone).
2151    pub fn unwatch_core(&self, id: SubscriptionId) -> Result<(), CoreError> {
2152        let not_found = || {
2153            CoreError::new(
2154                ErrorKind::NotFound,
2155                Error::new(format!("No active watch for id {}", id.0)),
2156            )
2157        };
2158        let path = crate::sync_util::lock_or_recover(&self.core.core_watches)
2159            .remove(&id.0)
2160            .ok_or_else(not_found)?;
2161        let virtual_port = crate::sync_util::lock_or_recover(&self.virtual_ports)
2162            .get(&path)
2163            .cloned();
2164        let detached = if let Some(vp) = virtual_port {
2165            self.resolve_connected_port(&vp.physical_path)
2166                .ok()
2167                .and_then(|cp| crate::sync_util::lock_or_recover(&cp.mux).clone())
2168                .is_some_and(|session| session.remove_core_watch(vp.dlci, id.0))
2169        } else {
2170            self.resolve_connected_port(&path)
2171                .ok()
2172                .and_then(|cp| {
2173                    crate::sync_util::lock_or_recover(&cp.rx_hub)
2174                        .as_ref()
2175                        .map(|h| h.shared())
2176                })
2177                .is_some_and(|shared| shared.detach_core_watch(id.0))
2178        };
2179        if detached {
2180            Ok(())
2181        } else {
2182            Err(not_found())
2183        }
2184    }
2185
2186    /// Port states of every port of this manager ([`CoreEvent::PortState`]: opened,
2187    /// disconnected with its kind and reason, closed); needs no watch. Same queue and
2188    /// overflow rules as [`Self::watch_core`].
2189    pub fn subscribe_core(&self, sink: CoreSink) -> SubscriptionId {
2190        let id = next_subscription_id();
2191        let queue = CoreQueue::spawn(sink, self.core_queue_capacity());
2192        crate::sync_util::lock_or_recover(&self.core.subscribers).push((id, queue));
2193        SubscriptionId(id)
2194    }
2195
2196    pub fn unsubscribe_core(&self, id: SubscriptionId) -> Result<(), CoreError> {
2197        let mut subs = crate::sync_util::lock_or_recover(&self.core.subscribers);
2198        let i = subs.iter().position(|(s, _)| *s == id.0).ok_or_else(|| {
2199            CoreError::new(
2200                ErrorKind::NotFound,
2201                Error::new(format!("No subscription {}", id.0)),
2202            )
2203        })?;
2204        subs.remove(i).1.close();
2205        Ok(())
2206    }
2207
2208    /// Queue limit (bytes of event data) of core receivers created from now on.
2209    /// Default [`crate::events::DEFAULT_CORE_QUEUE_BYTES`].
2210    pub fn set_core_queue_capacity(&self, bytes: usize) {
2211        self.core.queue_capacity.store(bytes, Ordering::SeqCst);
2212    }
2213
2214    fn core_queue_capacity(&self) -> usize {
2215        match self.core.queue_capacity.load(Ordering::SeqCst) {
2216            0 => crate::events::DEFAULT_CORE_QUEUE_BYTES,
2217            n => n,
2218        }
2219    }
2220
2221    fn emit_port_state(&self, path: &str, state: PortStatus) {
2222        let subs: Vec<Arc<CoreQueue>> = crate::sync_util::lock_or_recover(&self.core.subscribers)
2223            .iter()
2224            .map(|(_, q)| q.clone())
2225            .collect();
2226        for q in subs {
2227            q.push(CoreEvent::PortState {
2228                path: path.to_string(),
2229                state: state.clone(),
2230            });
2231        }
2232        crate::sync_util::lock_or_recover(&self.core.subscribers).retain(|(_, q)| q.alive());
2233    }
2234
2235    fn downgrade(&self) -> WeakManager {
2236        WeakManager {
2237            serialports: Arc::downgrade(&self.serialports),
2238            virtual_ports: Arc::downgrade(&self.virtual_ports),
2239            core: Arc::downgrade(&self.core),
2240        }
2241    }
2242
2243    // --- old watch registry (per manager; mirrored into `port::watch_registry`)
2244
2245    fn register_watch(&self, id: u32, path: &str) -> Result<(), Error> {
2246        let mut watches = crate::sync_util::lock_or_recover(&self.core.watches);
2247        if watches.contains_key(&id) {
2248            return Err(Error::new(format!("watch id {} is already in use", id)));
2249        }
2250        if watches.values().any(|w| w.path == path) {
2251            return Err(Error::new(format!(
2252                "A watch is already active for port {}",
2253                path
2254            )));
2255        }
2256        // The 4.x global registry is shared by every manager: an id another manager
2257        // holds is taken too (else one manager's watch would vanish from it).
2258        if !crate::port::watch_registry::mirror_insert(id, path) {
2259            return Err(Error::new(format!("watch id {} is already in use", id)));
2260        }
2261        let watch = OldWatch {
2262            path: path.to_string(),
2263            attached: None,
2264            stopping: false,
2265        };
2266        watches.insert(id, watch);
2267        Ok(())
2268    }
2269
2270    /// The watch `id` is attached to `owner`; ended meanwhile, it is stopped right away.
2271    fn bind_watch(&self, id: u32, owner: Arc<dyn WatchOwner>, stream: &Arc<EventStream>) {
2272        let attached = Attached {
2273            owner: Arc::downgrade(&owner),
2274            stream: Arc::downgrade(stream),
2275        };
2276        let mut watches = crate::sync_util::lock_or_recover(&self.core.watches);
2277        match watches.get_mut(&id) {
2278            Some(watch) if !watch.stopping => watch.attached = Some(attached),
2279            _ => {
2280                drop(watches);
2281                attached.stop();
2282            }
2283        }
2284    }
2285
2286    fn unregister_watch(&self, id: u32) {
2287        let watch = crate::sync_util::lock_or_recover(&self.core.watches).remove(&id);
2288        if watch.is_some() {
2289            crate::port::watch_registry::mirror_remove(id);
2290        }
2291    }
2292
2293    /// End the old watches of `path` (their tail is delivered) and drop their ids. Call with
2294    /// no lock held.
2295    fn forget_old_watches(&self, path: &str) {
2296        let watches: Vec<(u32, Option<Attached>)> =
2297            crate::sync_util::lock_or_recover(&self.core.watches)
2298                .iter()
2299                .filter(|(_, w)| w.path == path)
2300                .map(|(id, w)| (*id, w.attached.clone()))
2301                .collect();
2302        for (id, attached) in watches {
2303            if let Some(attached) = attached {
2304                attached.stop();
2305            }
2306            self.unregister_watch(id);
2307        }
2308    }
2309
2310    fn core_watch_ids_for(&self, path: &str) -> Vec<u64> {
2311        crate::sync_util::lock_or_recover(&self.core.core_watches)
2312            .iter()
2313            .filter(|(_, p)| p.as_str() == path)
2314            .map(|(id, _)| *id)
2315            .collect()
2316    }
2317
2318    /// Drop the registry entries of `path` (the port is gone; its hub ended the streams).
2319    /// Call with no lock held.
2320    fn forget_watches(&self, path: &str) {
2321        self.forget_old_watches(path);
2322        crate::sync_util::lock_or_recover(&self.core.core_watches).retain(|_, p| p != path);
2323    }
2324
2325    // --- port handles and hub
2326
2327    /// Wrap a freshly opened port: write handle (where it can be split) and RX hub.
2328    fn connect(
2329        &self,
2330        path: &str,
2331        port: Box<dyn SerialPortTrait>,
2332        timeout: Duration,
2333        first_watch: Option<CoreWatchSlot>,
2334    ) -> (ConnectedPort, Result<(), Error>) {
2335        let writer = split_writer(path, port.as_ref(), timeout);
2336        let cp = ConnectedPort::new(port);
2337        if let Some(writer) = writer {
2338            crate::sync_util::lock_or_recover(&self.core.writers).insert(
2339                path.to_string(),
2340                Writer {
2341                    reader: Arc::downgrade(&cp.port),
2342                    port: Arc::new(Mutex::new(writer)),
2343                },
2344            );
2345        }
2346        let hub = self.start_rx_hub(&cp.handle(), path, first_watch);
2347        (cp, hub)
2348    }
2349
2350    /// The write handle of `path`, if it was split from this very port.
2351    fn writer_of(&self, path: &str, cp: &ConnectedPortHandle) -> Option<PortArc> {
2352        crate::sync_util::lock_or_recover(&self.core.writers)
2353            .get(path)
2354            .filter(|w| {
2355                w.reader
2356                    .upgrade()
2357                    .is_some_and(|r| Arc::ptr_eq(&r, &cp.port))
2358            })
2359            .map(|w| w.port.clone())
2360    }
2361
2362    fn drop_writer(&self, path: &str) {
2363        crate::sync_util::lock_or_recover(&self.core.writers).remove(path);
2364    }
2365
2366    /// Start the RX hub if it is not running. An error once the port is being closed or has
2367    /// disconnected (the caller found it just before): no hub runs, and nothing is sent, on
2368    /// a port that is gone.
2369    fn ensure_rx_hub(&self, cp: &ConnectedPortHandle, path: &str) -> Result<(), Error> {
2370        self.start_rx_hub(cp, path, None)
2371    }
2372
2373    /// [`Self::ensure_rx_hub`]; `first_watch` joins the hub before its first read.
2374    fn start_rx_hub(
2375        &self,
2376        cp: &ConnectedPortHandle,
2377        path: &str,
2378        first_watch: Option<CoreWatchSlot>,
2379    ) -> Result<(), Error> {
2380        let mut guard = cp
2381            .rx_hub
2382            .lock()
2383            .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?;
2384        let needs_start = match guard.as_ref() {
2385            None => true,
2386            Some(hub) => {
2387                hub.shared().check_open().map_err(Error::String)?;
2388                hub.is_finished()
2389            }
2390        };
2391        if needs_start {
2392            let manager = self.downgrade();
2393            let reader = Arc::downgrade(&cp.port);
2394            let owner = path.to_string();
2395            let hook: crate::hub::desktop::DisconnectHook = Box::new(move |reason| {
2396                if let Some(m) = manager.upgrade() {
2397                    m.on_port_disconnected(&owner, &reader, reason);
2398                }
2399            });
2400            let hub = Arc::new(crate::hub::PortRxHub::start_with(
2401                cp.port.clone(),
2402                path.to_string(),
2403                Some(hook),
2404                first_watch,
2405            ));
2406            register_mobile_hub(path, cp, hub.clone());
2407            *guard = Some(hub);
2408        } else if let (Some(slot), Some(hub)) = (first_watch, guard.as_ref()) {
2409            hub.shared().attach_core_watch(slot);
2410        }
2411        Ok(())
2412    }
2413
2414    fn ensure_rx_hub_on_physical(&self, physical_path: &str) -> Result<(), Error> {
2415        let cp = self.resolve_connected_port(physical_path)?;
2416        self.ensure_rx_hub(&cp, physical_path)
2417    }
2418
2419    /// On the hub thread, after `Disconnect` went out: release the record if it is
2420    /// still this reader's (see [`Self::release`]). Never joins the hub (its thread).
2421    fn on_port_disconnected(
2422        &self,
2423        path: &str,
2424        reader: &Weak<Mutex<Box<dyn SerialPortTrait>>>,
2425        reason: &str,
2426    ) {
2427        let removed = {
2428            let mut map = crate::sync_util::lock_or_recover(&self.serialports);
2429            let same = match map.get(path).map(|i| &i.state) {
2430                Some(PortState::Connected(cp)) => {
2431                    reader.upgrade().is_some_and(|r| Arc::ptr_eq(&r, &cp.port))
2432                }
2433                _ => false,
2434            };
2435            if same {
2436                // Tombstone before the record leaves the map: a `close` racing the
2437                // release must find one of the two, never neither ("not open").
2438                crate::sync_util::lock_or_recover(&self.core.disconnected)
2439                    .insert(path.to_string(), reason.to_string());
2440                map.remove(path)
2441            } else {
2442                None
2443            }
2444        };
2445        if let Some(info) = removed {
2446            self.release(path, info, reason);
2447        }
2448    }
2449
2450    /// A port that disconnected (its record already out of the map, its tombstone in):
2451    /// drop both handles, the hub and its CMUX channels, give each channel a tombstone
2452    /// with `reason` (listed, a late watch gets `Disconnect`, calls fail with it, `close`
2453    /// removes it), and send `PortState::Disconnected`. The physical path's tombstone
2454    /// is not added here. Watches stay registered until `close` / `unwatch`.
2455    fn release(&self, path: &str, info: SerialportInfo, reason: &str) {
2456        let session = match &info.state {
2457            PortState::Connected(cp) => crate::sync_util::lock_or_recover(&cp.mux).clone(),
2458            _ => None,
2459        };
2460        let channels: Vec<String> = {
2461            let mut virtuals = crate::sync_util::lock_or_recover(&self.virtual_ports);
2462            let keys: Vec<String> = virtuals
2463                .iter()
2464                .filter(|(_, vp)| vp.physical_path == path)
2465                .map(|(k, _)| k.clone())
2466                .collect();
2467            // Each channel's tombstone goes in under the same lock that removes it
2468            // (order virtual_ports -> disconnected): a racing `close("p#dlci=N")` finds
2469            // one of the two, never neither ("not open"). The physical path's tombstone
2470            // went in with the record's removal; adding it again would revive it after
2471            // a racing `close`.
2472            let mut released = crate::sync_util::lock_or_recover(&self.core.disconnected);
2473            // A channel the modem closed has reported its `Disconnected` already.
2474            let mut open = Vec::new();
2475            for k in keys {
2476                if let Some(vp) = virtuals.remove(&k) {
2477                    released.insert(k.clone(), reason.to_string());
2478                    vp.tx_queue.cancel_all();
2479                    if session.as_ref().is_some_and(|s| s.has_dlci(vp.dlci)) {
2480                        open.push(k);
2481                    }
2482                }
2483            }
2484            open
2485        };
2486        self.drop_writer(path);
2487        if let PortState::Connected(cp) = info.state {
2488            // The (ending) hub stays in its slot: a call that still has `cp` starts no new
2489            // one on the dead port.
2490            #[cfg(target_os = "android")]
2491            crate::android::registry::global_registry().unregister(path);
2492            drop(cp);
2493        }
2494        log_info!("{} released after disconnect: {}", path, reason);
2495        // The I/O error kind is in `reason`; an unplug is `Disconnected` on every
2496        // platform (Windows reports it as PermissionDenied).
2497        for p in channels.iter().map(String::as_str).chain([path]) {
2498            self.emit_port_state(
2499                p,
2500                PortStatus::Disconnected {
2501                    kind: ErrorKind::Disconnected,
2502                    reason: reason.to_string(),
2503                },
2504            );
2505        }
2506    }
2507}
2508
2509impl crate::at::commands::ExchangeRunner for SerialManager {
2510    fn run_exchange_unqueued(
2511        &self,
2512        path: String,
2513        payload: Vec<u8>,
2514        options: ExchangeOptions,
2515    ) -> Result<crate::at::parse::ExchangeResponse, Error> {
2516        SerialManager::run_exchange_unqueued(self, path, payload, options)
2517    }
2518}
2519
2520#[cfg(all(test, not(any(target_os = "android", target_os = "ios"))))]
2521mod tests {
2522    //! In `src/`: needs the system to list a port it then fails to open.
2523    use super::*;
2524
2525    #[test]
2526    fn listed_but_not_found_is_busy() {
2527        assert_eq!(
2528            open_error_kind(ErrorKind::NotFound, || true),
2529            ErrorKind::Busy
2530        );
2531        assert_eq!(
2532            open_error_kind(ErrorKind::NotFound, || false),
2533            ErrorKind::NotFound
2534        );
2535        assert_eq!(
2536            open_error_kind(ErrorKind::Other, || panic!("only asked for NotFound")),
2537            ErrorKind::Other
2538        );
2539    }
2540}