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