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