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    ///
701    /// Opening a path that is already open (or disconnected and not yet closed)
702    /// replaces that session, as `open` does in 4.x: it is closed first, with its
703    /// watches, `watch_core` streams, CMUX channels and RX hub.
704    #[allow(clippy::too_many_arguments)]
705    pub fn open_core(
706        &self,
707        path: String,
708        baud_rate: u32,
709        data_bits: Option<DataBits>,
710        flow_control: Option<FlowControl>,
711        parity: Option<Parity>,
712        stop_bits: Option<StopBits>,
713        timeout: Option<u64>,
714        lines: crate::state::ModemLinesOnOpen,
715    ) -> Result<String, CoreError> {
716        self.open_core_with(
717            path,
718            baud_rate,
719            data_bits,
720            flow_control,
721            parity,
722            stop_bits,
723            timeout,
724            lines,
725            None,
726        )
727    }
728
729    /// [`Self::open_core`] plus a [`Self::watch_core`] stream that exists before the
730    /// port's first read: no byte and no event is lost (a `RDY` / URC sent right after
731    /// open, or a `Disconnect` of a port that dies at once, which still returns `Ok`).
732    /// Returns the session path and the stream's id (for [`Self::unwatch_core`]). An
733    /// invalid `parser` fails before the port is opened.
734    #[allow(clippy::too_many_arguments)]
735    pub fn open_watch_core(
736        &self,
737        path: String,
738        baud_rate: u32,
739        data_bits: Option<DataBits>,
740        flow_control: Option<FlowControl>,
741        parity: Option<Parity>,
742        stop_bits: Option<StopBits>,
743        timeout: Option<u64>,
744        lines: crate::state::ModemLinesOnOpen,
745        options: WatchOptions,
746        parser: Option<serial_codec::framing::FramerConfig>,
747        sink: CoreSink,
748    ) -> Result<(String, SubscriptionId), CoreError> {
749        let (id, queue, slot) = self.first_core_watch(&options, parser, sink)?;
750        match self.open_core_with(
751            path,
752            baud_rate,
753            data_bits,
754            flow_control,
755            parity,
756            stop_bits,
757            timeout,
758            lines,
759            Some(slot),
760        ) {
761            Ok(session) => {
762                crate::sync_util::lock_or_recover(&self.core.core_watches)
763                    .insert(id, session.clone());
764                Ok((session, SubscriptionId(id)))
765            }
766            Err(e) => {
767                queue.close();
768                Err(e)
769            }
770        }
771    }
772
773    /// [`Self::insert_port`] plus a [`Self::watch_core`] stream that exists before the
774    /// port's first read, as [`Self::open_watch_core`].
775    pub fn insert_port_watch_core(
776        &self,
777        path: String,
778        port: Box<dyn SerialPortTrait>,
779        options: WatchOptions,
780        parser: Option<serial_codec::framing::FramerConfig>,
781        sink: CoreSink,
782    ) -> Result<SubscriptionId, CoreError> {
783        let (id, queue, slot) = self.first_core_watch(&options, parser, sink)?;
784        match self.insert_port_with(path.clone(), port, Some(slot)) {
785            Ok(()) => {
786                crate::sync_util::lock_or_recover(&self.core.core_watches).insert(id, path);
787                Ok(SubscriptionId(id))
788            }
789            Err(e) => {
790                queue.close();
791                Err(e)
792            }
793        }
794    }
795
796    /// The stream of `open_watch_core` / `insert_port_watch_core`, not attached yet.
797    fn first_core_watch(
798        &self,
799        options: &WatchOptions,
800        parser: Option<serial_codec::framing::FramerConfig>,
801        sink: CoreSink,
802    ) -> Result<(u64, Arc<CoreQueue>, crate::hub::shared::CoreWatchSlot), CoreError> {
803        let framer = parser
804            .as_ref()
805            .map(|p| p.build())
806            .transpose()
807            .map_err(|e| CoreError::new(ErrorKind::Other, Error::String(e.to_string())))?;
808        let (batch_timeout, read_size, route_urc) = watch_params(options);
809        let id = next_subscription_id();
810        let queue = CoreQueue::spawn(sink, self.core_queue_capacity());
811        let slot = crate::hub::shared::CoreWatchSlot::new(
812            id,
813            queue.event_sink(),
814            queue.alive_flag(),
815            batch_timeout,
816            read_size,
817            route_urc,
818            framer,
819        );
820        Ok((id, queue, slot))
821    }
822
823    #[allow(clippy::too_many_arguments)]
824    fn open_core_with(
825        &self,
826        path: String,
827        baud_rate: u32,
828        data_bits: Option<DataBits>,
829        flow_control: Option<FlowControl>,
830        parity: Option<Parity>,
831        stop_bits: Option<StopBits>,
832        timeout: Option<u64>,
833        lines: crate::state::ModemLinesOnOpen,
834        first_watch: Option<crate::hub::shared::CoreWatchSlot>,
835    ) -> Result<String, CoreError> {
836        // Re-open (e.g. after a webview reload): tear the old session down the same
837        // way `close` does, so its watches, CMUX channels and hub go with it.
838        let already_open = matches!(
839            crate::sync_util::lock_or_recover(&self.serialports)
840                .get(&path)
841                .map(|i| &i.state),
842            Some(PortState::Connected(_))
843        );
844        let released =
845            crate::sync_util::lock_or_recover(&self.core.disconnected).contains_key(&path);
846        if already_open || released {
847            log_info!("Replacing existing port {}", path);
848            let _ = self.close(path.clone());
849        }
850        let stale = {
851            let mut serialports = self
852                .serialports
853                .lock()
854                .map_err(|e| Error::String(format!("Failed to acquire lock: {}", e)))?;
855            if matches!(
856                serialports.get(&path).map(|i| &i.state),
857                Some(PortState::Opening)
858            ) {
859                return Err(Error::String(format!("open already in progress for {}", path)).into());
860            }
861            let stale = serialports.remove(&path);
862            serialports.insert(
863                path.clone(),
864                SerialportInfo {
865                    state: PortState::Opening,
866                },
867            );
868            stale
869        };
870
871        if let Some(existing) = stale {
872            log_info!("Replacing existing port {}", path);
873            finish_serialport_info(&path, existing)?;
874        }
875
876        let timeout = Duration::from_millis(timeout.unwrap_or(DEFAULT_PORT_TIMEOUT_MS));
877        let port_result = platform_open(
878            &path,
879            baud_rate,
880            data_bits.unwrap_or(DataBits::Eight),
881            flow_control.unwrap_or(FlowControl::None),
882            parity.unwrap_or(Parity::None),
883            stop_bits.unwrap_or(StopBits::One),
884            timeout,
885            lines,
886        );
887
888        let mut serialports = self
889            .serialports
890            .lock()
891            .map_err(|e| Error::String(format!("Failed to acquire lock: {}", e)))?;
892
893        match port_result {
894            Ok((session_path, port)) => {
895                if session_path != path {
896                    serialports.remove(&path);
897                    if !serialports.contains_key(&session_path) {
898                        serialports.insert(
899                            session_path.clone(),
900                            SerialportInfo {
901                                state: PortState::Opening,
902                            },
903                        );
904                    }
905                }
906
907                let (cp, hub) = self.connect(&session_path, port, timeout, first_watch);
908                let reserved = matches!(
909                    serialports.get(&session_path).map(|i| &i.state),
910                    Some(PortState::Opening)
911                );
912                if let (Ok(()), true) = (&hub, reserved) {
913                    if let Some(entry) = serialports.get_mut(&session_path) {
914                        entry.state = PortState::Connected(cp);
915                    }
916                    // Under the map lock: a disconnect hook (it waits for the lock)
917                    // reports `Disconnected` after this `Opened`.
918                    self.emit_port_state(&session_path, PortStatus::Opened);
919                    drop(serialports);
920                    return Ok(session_path);
921                }
922                // Never leave an `Opening` entry or a running hub thread behind.
923                if reserved {
924                    serialports.remove(&session_path);
925                }
926                drop(serialports);
927                self.drop_writer(&session_path);
928                let _ = finish_serialport_info(
929                    &session_path,
930                    SerialportInfo {
931                        state: PortState::Connected(cp),
932                    },
933                );
934                hub?;
935                Err(
936                    Error::String(format!("Port '{}' state changed during open", session_path))
937                        .into(),
938                )
939            }
940            Err(e) => {
941                if matches!(
942                    serialports.get(&path).map(|i| &i.state),
943                    Some(PortState::Opening)
944                ) {
945                    serialports.remove(&path);
946                }
947                Err(e)
948            }
949        }
950    }
951
952    /// Manage `port` under `path` as if [`Self::open`] had opened it (tests, custom
953    /// transports, a fake device). An open port under `path` is closed first. Its
954    /// current `timeout()` is the port timeout.
955    ///
956    /// On Unix (not TCP / BLE) writes and control calls go to `port.try_clone()` when
957    /// it succeeds, reads to `port`: a clone must share the device (like a dup'ed fd),
958    /// or `try_clone` must return `Err` to keep one handle for everything.
959    pub fn insert_port(
960        &self,
961        path: String,
962        port: Box<dyn SerialPortTrait>,
963    ) -> Result<(), CoreError> {
964        self.insert_port_with(path, port, None)
965    }
966
967    fn insert_port_with(
968        &self,
969        path: String,
970        port: Box<dyn SerialPortTrait>,
971        first_watch: Option<crate::hub::shared::CoreWatchSlot>,
972    ) -> Result<(), CoreError> {
973        let known = crate::sync_util::lock_or_recover(&self.serialports).contains_key(&path)
974            || crate::sync_util::lock_or_recover(&self.core.disconnected).contains_key(&path);
975        if known {
976            let _ = self.close(path.clone());
977        }
978        let timeout = port.timeout();
979        // Under the map lock (as `open_core`): a device failing at once is reported by
980        // its disconnect hook, which waits for the record.
981        let mut serialports = crate::sync_util::lock_or_recover(&self.serialports);
982        let (cp, hub) = self.connect(&path, port, timeout, first_watch);
983        if let Err(e) = hub {
984            drop(serialports);
985            self.drop_writer(&path);
986            let _ = finish_serialport_info(
987                &path,
988                SerialportInfo {
989                    state: PortState::Connected(cp),
990                },
991            );
992            return Err(e.into());
993        }
994        serialports.insert(
995            path.clone(),
996            SerialportInfo {
997                state: PortState::Connected(cp),
998            },
999        );
1000        self.emit_port_state(&path, PortStatus::Opened);
1001        drop(serialports);
1002        Ok(())
1003    }
1004
1005    /// Stream port events into `sink` (one watch per port and manager). Returns the id
1006    /// for [`Self::unwatch`]. As in 4.x, `sink` runs on the RX side: the port's hub
1007    /// thread, or the caller of `unwatch` / `close` for the tail they deliver. It never
1008    /// runs under a manager lock, but a slow sink holds up RX (keep it short, e.g.
1009    /// forward into a channel), and calling `at()` / `exchange` on the same port from
1010    /// it waits for the RX it blocks. Nothing reaches it after `close()` returns.
1011    /// [`Self::watch_core`] has its own delivery thread instead.
1012    pub fn watch(
1013        &self,
1014        path: String,
1015        options: WatchOptions,
1016        sink: EventSink,
1017    ) -> Result<u32, Error> {
1018        self.watch_framed(path, options, None, sink)
1019    }
1020
1021    /// [`Self::watch`] under a caller-chosen id (the plugin uses its IPC channel id).
1022    pub fn watch_with_id(
1023        &self,
1024        channel_id: u32,
1025        path: String,
1026        options: WatchOptions,
1027        sink: EventSink,
1028    ) -> Result<u32, Error> {
1029        self.watch_framed_with_id(channel_id, path, options, None, sink)
1030    }
1031
1032    /// [`Self::watch`] with a native parser: each complete frame becomes exactly one
1033    /// [`SerialEvent::Data`](crate::events::SerialEvent::Data) (the batch timer no longer
1034    /// applies). An invalid config fails before the watch starts. With
1035    /// [`WatchOptions::route_urc`] the URC split runs first and only non-URC lines reach
1036    /// the parser. On unwatch, close or disconnect the parser's buffered remainder is
1037    /// sent as a final `data` event (before `disconnect`), like Node serialport emits
1038    /// on stream end.
1039    pub fn watch_framed(
1040        &self,
1041        path: String,
1042        options: WatchOptions,
1043        parser: Option<serial_codec::framing::FramerConfig>,
1044        sink: EventSink,
1045    ) -> Result<u32, Error> {
1046        let id = next_watch_id(|id| {
1047            crate::sync_util::lock_or_recover(&self.core.watches).contains_key(&id)
1048                || crate::port::watch_registry::contains(id)
1049        });
1050        self.watch_framed_with_id(id, path, options, parser, sink)
1051    }
1052
1053    /// [`Self::watch_framed`] under a caller-chosen id.
1054    pub fn watch_framed_with_id(
1055        &self,
1056        channel_id: u32,
1057        path: String,
1058        options: WatchOptions,
1059        parser: Option<serial_codec::framing::FramerConfig>,
1060        channel: EventSink,
1061    ) -> Result<u32, Error> {
1062        // Validate the parser before anything is registered or attached.
1063        let mut framer = parser
1064            .as_ref()
1065            .map(|p| p.build())
1066            .transpose()
1067            .map_err(|e| Error::String(e.to_string()))?;
1068        self.register_watch(channel_id, &path)?;
1069        log_debug!("Starting watch on port: {} (channel {})", path, channel_id);
1070
1071        // Released after a disconnect: the late watch gets that `Disconnect` (4.x).
1072        if let Some(reason) = self.released_reason(&path) {
1073            crate::port::watch_registry::send_event_to(
1074                &channel,
1075                SerialEvent::Disconnect { path, reason },
1076            );
1077            return Ok(channel_id);
1078        }
1079
1080        let (batch_timeout, read_size, route_urc) = watch_params(&options);
1081
1082        if let Ok(virtuals) = self.virtual_ports.lock() {
1083            if let Some(vp) = virtuals.get(&path).cloned() {
1084                drop(virtuals);
1085                let session = self
1086                    .resolve_connected_port(&vp.physical_path)
1087                    .and_then(|cp| {
1088                        crate::sync_util::lock_or_recover(&cp.mux)
1089                            .clone()
1090                            .ok_or_else(|| Error::String("CMUX not enabled".into()))
1091                    });
1092                let session = match session {
1093                    Ok(session) => session,
1094                    Err(e) => {
1095                        self.unregister_watch(channel_id);
1096                        return Err(e);
1097                    }
1098                };
1099                if let Err(e) = self.ensure_rx_hub_on_physical(&vp.physical_path) {
1100                    self.unregister_watch(channel_id);
1101                    return Err(e);
1102                }
1103                session.set_watch_with(vp.dlci, channel, batch_timeout, framer);
1104                return Ok(channel_id);
1105            }
1106        }
1107
1108        // A replaced watch's remainder is queued under the locks, delivered after.
1109        let mut replaced = None;
1110        let attached = self.with_connected_port(path.clone(), |cp| {
1111            if cp.virtual_dlci.is_some() {
1112                return Err(Error::String("legacy virtual ConnectedPort".into()));
1113            }
1114            if let Some(shared) = cp
1115                .rx_hub
1116                .lock()
1117                .ok()
1118                .and_then(|g| g.as_ref().map(|h| h.shared()))
1119                .filter(|s| s.has_watch())
1120            {
1121                shared.detach_watch_queued();
1122                replaced = Some(shared);
1123            }
1124            self.ensure_rx_hub(&cp.handle(), &path)?;
1125            let guard = cp
1126                .rx_hub
1127                .lock()
1128                .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?;
1129            let hub = guard
1130                .as_ref()
1131                .ok_or_else(|| Error::String("RX hub missing after start".into()))?;
1132            hub.attach_watch_with(channel, batch_timeout, read_size, route_urc, framer.take());
1133            Ok(())
1134        });
1135        if let Some(shared) = replaced {
1136            shared.deliver_queued();
1137        }
1138        if let Err(e) = attached {
1139            self.unregister_watch(channel_id);
1140            return Err(e);
1141        }
1142
1143        Ok(channel_id)
1144    }
1145
1146    pub fn unwatch(&self, channel_id: u32) -> Result<(), Error> {
1147        let path = self
1148            .unregister_watch(channel_id)
1149            .ok_or_else(|| Error::new(format!("No active watch for channel {}", channel_id)))?;
1150        log_debug!("Stopping watch on port: {} (channel {})", path, channel_id);
1151        self.stop_watch_thread(&path)
1152    }
1153
1154    /// Detach the watch of `path`. The remainder goes to the sink after every lock
1155    /// here is released, so a sink calling back into the manager cannot deadlock.
1156    fn stop_watch_thread(&self, path: &str) -> Result<(), Error> {
1157        let virtual_port = self
1158            .virtual_ports
1159            .lock()
1160            .ok()
1161            .and_then(|v| v.get(path).cloned());
1162        if let Some(vp) = virtual_port {
1163            if let Ok(cp) = self.resolve_connected_port(&vp.physical_path) {
1164                let session = crate::sync_util::lock_or_recover(&cp.mux).clone();
1165                if let Some(session) = session {
1166                    session.clear_watch(vp.dlci);
1167                }
1168            }
1169            return Ok(());
1170        }
1171        enum Detach {
1172            Mux(Arc<CmuxSession>, u8),
1173            Hub(Arc<crate::hub::RxHubShared>),
1174            Nothing,
1175        }
1176        // A port the core already released (disconnect) has nothing left to detach.
1177        let detach = self
1178            .with_connected_port(path.to_string(), |cp| {
1179                if let Some(dlci) = cp.virtual_dlci {
1180                    let session = crate::sync_util::lock_or_recover(&cp.mux).clone();
1181                    return Ok(session.map_or(Detach::Nothing, |s| Detach::Mux(s, dlci)));
1182                }
1183                let shared = cp
1184                    .rx_hub
1185                    .lock()
1186                    .ok()
1187                    .and_then(|g| g.as_ref().map(|h| h.shared()));
1188                Ok(shared.map_or(Detach::Nothing, Detach::Hub))
1189            })
1190            .unwrap_or(Detach::Nothing);
1191        match detach {
1192            Detach::Mux(session, dlci) => session.clear_watch(dlci),
1193            Detach::Hub(shared) => shared.detach_watch(),
1194            Detach::Nothing => {}
1195        }
1196        Ok(())
1197    }
1198
1199    pub fn read(
1200        &self,
1201        path: String,
1202        timeout: Option<u64>,
1203        size: Option<usize>,
1204    ) -> Result<String, Error> {
1205        let bytes = self.read_via_hub(path, timeout, size, false)?;
1206        Ok(String::from_utf8_lossy(&bytes).to_string())
1207    }
1208
1209    pub fn read_binary(
1210        &self,
1211        path: String,
1212        timeout: Option<u64>,
1213        size: Option<usize>,
1214    ) -> Result<Vec<u8>, Error> {
1215        self.read_via_hub(path, timeout, size, true)
1216    }
1217
1218    fn read_via_hub(
1219        &self,
1220        path: String,
1221        timeout: Option<u64>,
1222        size: Option<usize>,
1223        fill: bool,
1224    ) -> Result<Vec<u8>, Error> {
1225        let cp = self.resolve_connected_port(&path)?;
1226        self.ensure_rx_hub(&cp, &path)?;
1227        let hub_shared = {
1228            let guard = cp
1229                .rx_hub
1230                .lock()
1231                .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?;
1232            guard
1233                .as_ref()
1234                .ok_or_else(|| Error::String("RX hub missing".into()))?
1235                .shared()
1236        };
1237        hub_shared
1238            .read_request(size.unwrap_or(1024), timeout.unwrap_or(1000), fill)
1239            .map_err(Error::String)
1240    }
1241
1242    /// Write data to the serial port (or a CMUX channel `path#dlci=N`).
1243    pub fn write(&self, path: String, value: String) -> Result<usize, Error> {
1244        self.write_bytes(&path, value.as_bytes(), "write data")
1245            .map_err(Error::from)
1246    }
1247
1248    /// Write binary data to the serial port (or a CMUX channel `path#dlci=N`).
1249    pub fn write_binary(&self, path: String, value: Vec<u8>) -> Result<usize, Error> {
1250        self.write_bytes(&path, &value, "write binary data")
1251            .map_err(Error::from)
1252    }
1253
1254    /// [`Self::write_binary`] with a [`CoreError`] (the I/O error as its source).
1255    pub fn write_core(&self, path: String, data: Vec<u8>) -> Result<usize, CoreError> {
1256        self.write_bytes(&path, &data, "write binary data")
1257    }
1258
1259    fn write_bytes(&self, path: &str, data: &[u8], operation: &str) -> Result<usize, CoreError> {
1260        let virtual_port = crate::sync_util::lock_or_recover(&self.virtual_ports)
1261            .get(path)
1262            .cloned();
1263        if let Some(vp) = virtual_port {
1264            let cp = self.resolve_connected_port(&vp.physical_path)?;
1265            let session = crate::sync_util::lock_or_recover(&cp.mux)
1266                .clone()
1267                .ok_or_else(|| Error::String("CMUX not enabled".into()))?;
1268            return session
1269                .send_uih(vp.dlci, data)
1270                .map_err(|e| Error::String(format!("Failed to {operation}: {e}")).into());
1271        }
1272        let cp = self.resolve_connected_port(path)?;
1273        match self.writer_of(path, &cp) {
1274            Some(writer) => write_all_split(&writer, data, operation),
1275            None => with_port_try_lock(
1276                &cp.port,
1277                Duration::from_millis(PORT_LOCK_TIMEOUT_MS),
1278                |port| write_all_port(port, data, operation),
1279            ),
1280        }
1281    }
1282
1283    /// Set the baud rate
1284    pub fn set_baud_rate(&self, path: String, baud_rate: u32) -> Result<(), Error> {
1285        self.get_serialport(path, |port| {
1286            port.set_baud_rate(baud_rate)
1287                .map_err(|e| Error::String(format!("Failed to set baud rate: {}", e)))
1288        })
1289    }
1290
1291    /// Set the data bits
1292    pub fn set_data_bits(&self, path: String, data_bits: DataBits) -> Result<(), Error> {
1293        self.get_serialport(path, |port| {
1294            port.set_data_bits(data_bits.into()).map_err(Error::from)
1295        })
1296    }
1297
1298    /// Set the flow control
1299    pub fn set_flow_control(&self, path: String, flow_control: FlowControl) -> Result<(), Error> {
1300        self.get_serialport(path, |port| {
1301            port.set_flow_control(flow_control.into())
1302                .map_err(Error::from)
1303        })
1304    }
1305
1306    /// Set the parity
1307    pub fn set_parity(&self, path: String, parity: Parity) -> Result<(), Error> {
1308        self.get_serialport(path, |port| {
1309            port.set_parity(parity.into()).map_err(Error::from)
1310        })
1311    }
1312
1313    /// Set the stop bits
1314    pub fn set_stop_bits(&self, path: String, stop_bits: StopBits) -> Result<(), Error> {
1315        self.get_serialport(path, |port| {
1316            port.set_stop_bits(stop_bits.into()).map_err(Error::from)
1317        })
1318    }
1319
1320    /// Set the timeout
1321    pub fn set_timeout(&self, path: String, timeout: Duration) -> Result<(), Error> {
1322        self.get_serialport(path, |port| port.set_timeout(timeout).map_err(Error::from))
1323    }
1324
1325    /// Set the RTS (Request To Send) control signal
1326    pub fn write_request_to_send(&self, path: String, level: bool) -> Result<(), Error> {
1327        self.get_serialport(path, |port| {
1328            port.write_request_to_send(level).map_err(Error::from)
1329        })
1330    }
1331
1332    /// Set the DTR (Data Terminal Ready) control signal
1333    pub fn write_data_terminal_ready(&self, path: String, level: bool) -> Result<(), Error> {
1334        self.get_serialport(path, |port| {
1335            port.write_data_terminal_ready(level).map_err(Error::from)
1336        })
1337    }
1338
1339    /// Read the CTS (Clear To Send) control signal state
1340    pub fn read_clear_to_send(&self, path: String) -> Result<bool, Error> {
1341        self.get_serialport(path, |port| port.read_clear_to_send().map_err(Error::from))
1342    }
1343
1344    /// Read the DSR (Data Set Ready) control signal state
1345    pub fn read_data_set_ready(&self, path: String) -> Result<bool, Error> {
1346        self.get_serialport(path, |port| port.read_data_set_ready().map_err(Error::from))
1347    }
1348
1349    /// Read the RI (Ring Indicator) control signal state
1350    pub fn read_ring_indicator(&self, path: String) -> Result<bool, Error> {
1351        self.get_serialport(path, |port| port.read_ring_indicator().map_err(Error::from))
1352    }
1353
1354    /// Read the CD (Carrier Detect) control signal state
1355    pub fn read_carrier_detect(&self, path: String) -> Result<bool, Error> {
1356        self.get_serialport(path, |port| port.read_carrier_detect().map_err(Error::from))
1357    }
1358
1359    /// Get the number of bytes available to read
1360    pub fn bytes_to_read(&self, path: String) -> Result<u32, Error> {
1361        if let Some(reason) = self.released_reason(&path) {
1362            return Err(Error::String(reason));
1363        }
1364        let hub_buffered = if let Ok(cp) = self.resolve_connected_port(&path) {
1365            cp.rx_hub
1366                .lock()
1367                .ok()
1368                .and_then(|guard| guard.as_ref().map(|hub| hub.shared().buffered_len() as u32))
1369                .unwrap_or(0)
1370        } else {
1371            0
1372        };
1373        // Wait for the handle (the hub holds the reader during a poll) instead of
1374        // reporting 0 whenever it is busy.
1375        let port_buffered = if let Ok(cp) = self.resolve_connected_port(&path) {
1376            let port = self.writer_of(&path, &cp).unwrap_or(cp.port);
1377            lock_with_deadline(
1378                &port,
1379                Duration::from_millis(PORT_LOCK_TIMEOUT_MS),
1380                false,
1381                |p| p.bytes_to_read().map_err(Error::from),
1382            )
1383            .unwrap_or(0)
1384        } else {
1385            0
1386        };
1387        Ok(hub_buffered.saturating_add(port_buffered))
1388    }
1389
1390    /// Get the number of bytes waiting to be written
1391    pub fn bytes_to_write(&self, path: String) -> Result<u32, Error> {
1392        self.get_serialport(path, |port| port.bytes_to_write().map_err(Error::from))
1393    }
1394
1395    /// Clear input/output buffers
1396    /// `Input` / `All` also drop what the RX hub holds for no one yet.
1397    pub fn clear_buffer(&self, path: String, buffer_to_clear: ClearBuffer) -> Result<(), Error> {
1398        let input = !matches!(buffer_to_clear, ClearBuffer::Output);
1399        self.get_serialport(path.clone(), |port| {
1400            port.clear(buffer_to_clear.into()).map_err(Error::from)
1401        })?;
1402        if input {
1403            if let Ok(cp) = self.resolve_connected_port(&path) {
1404                if let Some(hub) = crate::sync_util::lock_or_recover(&cp.rx_hub).as_ref() {
1405                    hub.shared().purge_buffers();
1406                }
1407            }
1408        }
1409        Ok(())
1410    }
1411
1412    /// Start break signal transmission
1413    pub fn set_break(&self, path: String) -> Result<(), Error> {
1414        self.get_serialport(path, |port| port.set_break().map_err(Error::from))
1415    }
1416
1417    /// Stop break signal transmission
1418    pub fn clear_break(&self, path: String) -> Result<(), Error> {
1419        self.get_serialport(path, |port| port.clear_break().map_err(Error::from))
1420    }
1421
1422    /// Write payload and read until terminators, idle silence, or timeout (AT-style exchange).
1423    pub fn exchange(
1424        &self,
1425        path: String,
1426        value: String,
1427        options: ExchangeOptions,
1428    ) -> Result<crate::at::parse::ExchangeResponse, Error> {
1429        self.exchange_bytes(path, value.into_bytes(), options)
1430    }
1431
1432    /// Binary variant of [`Self::exchange`].
1433    pub fn exchange_binary(
1434        &self,
1435        path: String,
1436        value: Vec<u8>,
1437        options: ExchangeOptions,
1438    ) -> Result<crate::at::parse::ExchangeResponse, Error> {
1439        self.exchange_bytes(path, value, options)
1440    }
1441
1442    /// [`Self::exchange_binary`] with a [`CoreError`] (`Timeout`, `Cancelled`, …).
1443    pub fn exchange_core(
1444        &self,
1445        path: String,
1446        value: Vec<u8>,
1447        options: ExchangeOptions,
1448    ) -> Result<crate::at::parse::ExchangeResponse, CoreError> {
1449        self.exchange_bytes(path, value, options)
1450            .map_err(CoreError::from)
1451    }
1452
1453    fn get_tx_queue(&self, path: &str) -> Result<Arc<PortTxQueue>, Error> {
1454        if let Ok(virtuals) = self.virtual_ports.lock() {
1455            if let Some(vp) = virtuals.get(path) {
1456                return Ok(vp.tx_queue.clone());
1457            }
1458        }
1459        let ports = self
1460            .serialports
1461            .lock()
1462            .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?;
1463        let info = ports.get(path).ok_or_else(|| self.not_open_error(path))?;
1464        match &info.state {
1465            PortState::Connected(cp) => Ok(cp.tx_queue.clone()),
1466            other => Err(Error::String(other.not_connected_reason())),
1467        }
1468    }
1469
1470    fn exchange_bytes(
1471        &self,
1472        path: String,
1473        payload: Vec<u8>,
1474        options: ExchangeOptions,
1475    ) -> Result<crate::at::parse::ExchangeResponse, Error> {
1476        run_exchange_queued(
1477            path,
1478            options,
1479            |p| self.get_tx_queue(p),
1480            |physical_path,
1481             dlci,
1482             virtual_path,
1483             payload,
1484             options|
1485             -> Result<crate::at::parse::ExchangeResponse, Error> {
1486                self.exchange_bytes_mux_direct(physical_path, dlci, virtual_path, payload, options)
1487            },
1488            |path, payload, options| -> Result<crate::at::parse::ExchangeResponse, Error> {
1489                self.exchange_bytes_direct(path, payload, options)
1490            },
1491            payload,
1492        )
1493    }
1494
1495    fn exchange_bytes_direct(
1496        &self,
1497        path: String,
1498        payload: Vec<u8>,
1499        options: ExchangeOptions,
1500    ) -> Result<crate::at::parse::ExchangeResponse, Error> {
1501        let command = options
1502            .command
1503            .clone()
1504            .unwrap_or_else(|| String::from_utf8_lossy(&payload).into_owned());
1505        let user_solicited = options.solicited_prefixes.clone().unwrap_or_default();
1506        let resolved_timeout = options.resolve().timeout_ms;
1507
1508        let cp = self.resolve_connected_port(&path)?;
1509        self.ensure_rx_hub(&cp, &path)?;
1510
1511        struct DesktopExchangeIo<'a> {
1512            port: &'a PortArc,
1513            writer: Option<PortArc>,
1514            timeout_ms: u64,
1515        }
1516        impl crate::exchange::io::ExchangeIo for DesktopExchangeIo<'_> {
1517            fn purge_rx(&self) -> Result<(), Error> {
1518                let (port, io_timeout) = match &self.writer {
1519                    Some(w) => (w, false),
1520                    None => (self.port, true),
1521                };
1522                lock_with_deadline(
1523                    port,
1524                    Duration::from_millis(self.timeout_ms.min(5000)),
1525                    io_timeout,
1526                    |port| port.clear(ClearBuffer::Input.into()).map_err(Error::from),
1527                )
1528            }
1529            fn write_payload(&self, payload: &[u8]) -> Result<(), Error> {
1530                if let Some(w) = &self.writer {
1531                    return write_all_split(w, payload, "exchange write")
1532                        .map(|_| ())
1533                        .map_err(Error::from);
1534                }
1535                with_port_try_lock(
1536                    self.port,
1537                    Duration::from_millis(self.timeout_ms.min(5000)),
1538                    |port| {
1539                        write_all_port(port, payload, "exchange write")
1540                            .map(|_| ())
1541                            .map_err(Error::from)
1542                    },
1543                )
1544            }
1545        }
1546
1547        let hub = {
1548            let guard = crate::sync_util::lock_or_recover(&cp.rx_hub);
1549            guard
1550                .as_ref()
1551                .ok_or_else(|| Error::String("RX hub missing".into()))?
1552                .clone()
1553        };
1554
1555        crate::exchange::run::run_physical_exchange(
1556            hub.as_ref(),
1557            &DesktopExchangeIo {
1558                port: &cp.port,
1559                writer: self.writer_of(&path, &cp),
1560                timeout_ms: resolved_timeout,
1561            },
1562            &command,
1563            &user_solicited,
1564            payload,
1565            options,
1566            cp.exchange_cancel.clone(),
1567        )
1568    }
1569
1570    fn exchange_bytes_mux_direct(
1571        &self,
1572        physical_path: String,
1573        _dlci: u8,
1574        virtual_path: String,
1575        payload: Vec<u8>,
1576        options: ExchangeOptions,
1577    ) -> Result<crate::at::parse::ExchangeResponse, Error> {
1578        let vp = self
1579            .virtual_ports
1580            .lock()
1581            .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?
1582            .get(&virtual_path)
1583            .cloned()
1584            .ok_or_else(|| Error::String(format!("Virtual port '{}' not open", virtual_path)))?;
1585        self.exchange_bytes_mux_via_ref(physical_path, &vp, payload, options)
1586    }
1587
1588    fn exchange_bytes_mux_via_ref(
1589        &self,
1590        physical_path: String,
1591        vp: &crate::state::VirtualPortRef,
1592        payload: Vec<u8>,
1593        options: ExchangeOptions,
1594    ) -> Result<crate::at::parse::ExchangeResponse, Error> {
1595        let dlci = vp.dlci;
1596        let command = options
1597            .command
1598            .clone()
1599            .unwrap_or_else(|| String::from_utf8_lossy(&payload).into_owned());
1600        let user_solicited = options.solicited_prefixes.clone().unwrap_or_default();
1601
1602        let session = {
1603            let ports = self
1604                .serialports
1605                .lock()
1606                .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?;
1607            let info = ports.get(&physical_path).ok_or_else(|| {
1608                Error::String(format!("Physical port '{}' not found", physical_path))
1609            })?;
1610            match &info.state {
1611                PortState::Connected(cp) => cp
1612                    .mux
1613                    .lock()
1614                    .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?
1615                    .clone()
1616                    .ok_or_else(|| Error::String("CMUX not enabled on physical port".into()))?,
1617                other => return Err(Error::String(other.not_connected_reason())),
1618            }
1619        };
1620
1621        self.ensure_rx_hub_on_physical(&physical_path)?;
1622
1623        crate::exchange::run::run_mux_exchange(
1624            &session,
1625            dlci,
1626            &command,
1627            &user_solicited,
1628            payload,
1629            options,
1630            vp.exchange_cancel.clone(),
1631        )
1632    }
1633
1634    fn run_exchange_unqueued(
1635        &self,
1636        path: String,
1637        payload: Vec<u8>,
1638        options: ExchangeOptions,
1639    ) -> Result<crate::at::parse::ExchangeResponse, Error> {
1640        if let Some((physical, dlci)) = parse_mux_path(path.as_str()) {
1641            return self.exchange_bytes_mux_direct(
1642                physical.to_string(),
1643                dlci,
1644                path,
1645                payload,
1646                options,
1647            );
1648        }
1649        self.exchange_bytes_direct(path, payload, options)
1650    }
1651
1652    pub fn at(
1653        &self,
1654        path: String,
1655        command: String,
1656        options: Option<AtCommandOptions>,
1657    ) -> Result<crate::at::parse::AtCommandResult, Error> {
1658        let tx_queue = self.get_tx_queue(&path)?;
1659        crate::at::commands::queue_at(self, &tx_queue, path, command, options)
1660    }
1661
1662    /// [`Self::at`] with a [`CoreError`].
1663    pub fn at_core(
1664        &self,
1665        path: String,
1666        command: String,
1667        options: Option<AtCommandOptions>,
1668    ) -> Result<crate::at::parse::AtCommandResult, CoreError> {
1669        self.at(path, command, options).map_err(CoreError::from)
1670    }
1671
1672    /// Multi-phase AT flow (e.g. CMGS) — phases run atomically without interleaving other jobs.
1673    pub fn at_phases(
1674        &self,
1675        path: String,
1676        phases: Vec<AtPhase>,
1677    ) -> Result<Vec<crate::at::parse::AtCommandResult>, Error> {
1678        let tx_queue = self.get_tx_queue(&path)?;
1679        crate::at::commands::queue_at_phases(self, &tx_queue, path, phases)
1680    }
1681
1682    /// Built-in CMGS recipe: `AT+CMGS=n` → `>` → PDU + Ctrl+Z → final line.
1683    pub fn send_sms_pdu(
1684        &self,
1685        path: String,
1686        length: u32,
1687        pdu: Vec<u8>,
1688        options: Option<SendSmsPduOptions>,
1689    ) -> Result<Vec<crate::at::parse::AtCommandResult>, Error> {
1690        let tx_queue = self.get_tx_queue(&path)?;
1691        crate::at::commands::queue_send_sms_pdu(self, &tx_queue, path, length, pdu, options)
1692    }
1693
1694    /// Configure AT session defaults for native `at` jobs on this port.
1695    pub fn configure_at_session(
1696        &self,
1697        path: String,
1698        session: AtSessionConfig,
1699    ) -> Result<(), Error> {
1700        let tx_queue = self
1701            .resolve_connected_port(&path)
1702            .map(|cp| cp.tx_queue.clone())
1703            .ok();
1704        configure_at_session_shared(&self.virtual_ports, tx_queue, &path, session)
1705    }
1706
1707    /// Enter GSM 07.10 CMUX mode (`AT+CMUX=…` then attach deframer to the RX hub).
1708    pub fn enable_mux(&self, path: String, command: String, timeout_ms: u64) -> Result<(), Error> {
1709        let response = self.exchange(
1710            path.clone(),
1711            format!("{command}\r"),
1712            ExchangeOptions {
1713                timeout_ms: Some(timeout_ms),
1714                rx_prepare: Some(crate::events::RxPrepareMode::None),
1715                ..Default::default()
1716            },
1717        )?;
1718        if response.status != crate::at::parse::AtParseStatus::Ok {
1719            return Err(Error::String(format!(
1720                "modem rejected {command}: {}",
1721                String::from_utf8_lossy(&response.raw).trim()
1722            )));
1723        }
1724        // The modem switches to multiplexer mode a few ms after its OK. A frame sent
1725        // inside that window is lost, and the Quectel M26 then ignores SABM (retries
1726        // included) for about 2 s: wait the switch out before the first frame.
1727        thread::sleep(CMUX_SWITCH_SETTLE);
1728
1729        let cp = self.resolve_connected_port(&path)?;
1730        if cp.virtual_dlci.is_some() {
1731            return Err(Error::String("enable_mux on virtual port".into()));
1732        }
1733        if crate::sync_util::lock_or_recover(&cp.mux).is_some() {
1734            return Err(Error::String("CMUX already enabled".into()));
1735        }
1736        let io_port = self
1737            .writer_of(&path, &cp)
1738            .unwrap_or_else(|| cp.port.clone());
1739        io_port
1740            .lock()
1741            .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?
1742            .clear(ClearBuffer::Input.into())
1743            .map_err(Error::from)?;
1744        let session = CmuxSession::for_command(
1745            path.clone(),
1746            Arc::new(crate::cmux::SerialPortIo(io_port)),
1747            &command,
1748        );
1749        // The modem closed channels (DISC / DM / CLD): their state goes out, and when it
1750        // left multiplexer mode the session is detached (the port is plain again).
1751        let manager = self.downgrade();
1752        let weak = Arc::downgrade(&session);
1753        let physical = path.clone();
1754        session.set_on_closed(Box::new(move |paths, reason, whole| {
1755            let Some(m) = manager.upgrade() else {
1756                return;
1757            };
1758            for p in paths {
1759                m.emit_port_state(
1760                    p,
1761                    PortStatus::Disconnected {
1762                        kind: ErrorKind::Disconnected,
1763                        reason: reason.to_string(),
1764                    },
1765                );
1766            }
1767            if whole {
1768                m.detach_mux_session(&physical, &weak);
1769            }
1770        }));
1771        self.ensure_rx_hub(&cp, &path)?;
1772        if let Some(hub) = crate::sync_util::lock_or_recover(&cp.rx_hub).as_ref() {
1773            hub.attach_cmux(session.clone());
1774        }
1775        // Control channel first; without its UA the modem is not multiplexing.
1776        if let Err(e) = session.open_dlci(0, Duration::from_millis(timeout_ms.max(500))) {
1777            // The modem said OK to AT+CMUX, so it may be multiplexing with the UA lost:
1778            // CLD takes it back to AT mode.
1779            session.close_down();
1780            if let Some(hub) = crate::sync_util::lock_or_recover(&cp.rx_hub).as_ref() {
1781                hub.detach_cmux();
1782            }
1783            return Err(Error::String(e));
1784        }
1785        *crate::sync_util::lock_or_recover(&cp.mux) = Some(session);
1786        Ok(())
1787    }
1788
1789    /// Register a virtual DLCI channel on an CMUX-enabled physical port.
1790    pub fn open_mux_channel(&self, physical_path: String, dlci: u8) -> Result<String, Error> {
1791        if !crate::cmux::is_data_dlci(dlci) {
1792            return Err(Error::String(format!(
1793                "invalid CMUX DLCI {dlci}: data channels are 1..=63"
1794            )));
1795        }
1796        let virtual_path = mux_path(&physical_path, dlci);
1797        let session = {
1798            let ports = self
1799                .serialports
1800                .lock()
1801                .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?;
1802            let info = ports
1803                .get(&physical_path)
1804                .ok_or_else(|| self.not_open_error(&physical_path))?;
1805            match &info.state {
1806                PortState::Connected(cp) => cp
1807                    .mux
1808                    .lock()
1809                    .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?
1810                    .clone()
1811                    .ok_or_else(|| Error::String("CMUX not enabled".into())),
1812                other => Err(Error::String(other.not_connected_reason())),
1813            }
1814        }?;
1815
1816        // Already open on *this* session. An entry left from an earlier session (port
1817        // closed and re-opened) is stale and gets replaced below.
1818        let known = self
1819            .virtual_ports
1820            .lock()
1821            .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?
1822            .contains_key(&virtual_path);
1823        if known && session.has_dlci(dlci) {
1824            return Ok(virtual_path);
1825        }
1826        // Closed by the modem or left from an earlier session: its watches are dead.
1827        if known {
1828            self.forget_watches(&virtual_path);
1829        }
1830
1831        session.register_dlci(dlci, virtual_path.clone());
1832        if let Err(e) = session.open_dlci(dlci, Duration::from_secs(3)) {
1833            session.unregister_dlci(dlci);
1834            return Err(Error::String(e));
1835        }
1836        self.virtual_ports
1837            .lock()
1838            .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?
1839            .insert(virtual_path.clone(), {
1840                let tx_queue = Arc::new(PortTxQueue::new());
1841                crate::state::VirtualPortRef {
1842                    physical_path,
1843                    dlci,
1844                    exchange_cancel: tx_queue.cancel_flag(),
1845                    tx_queue,
1846                }
1847            });
1848        self.emit_port_state(&virtual_path, PortStatus::Opened);
1849        Ok(virtual_path)
1850    }
1851
1852    /// Tear down CMUX: close virtual channels and detach deframer.
1853    /// The CLD wait (up to T2) runs without the manager's map lock.
1854    pub fn disable_mux(&self, path: String) -> Result<(), Error> {
1855        self.close_virtual_channels_of(&path);
1856        let cp = self.resolve_connected_port(&path)?;
1857        let session = crate::sync_util::lock_or_recover(&cp.mux).take();
1858        if let Some(session) = session {
1859            session.close_down();
1860        }
1861        if let Some(hub) = crate::sync_util::lock_or_recover(&cp.rx_hub).as_ref() {
1862            hub.detach_cmux();
1863        }
1864        Ok(())
1865    }
1866
1867    /// The modem left multiplexer mode: drop `session` from `physical` (if it is still
1868    /// that port's session) and its deframer from the hub.
1869    fn detach_mux_session(&self, physical: &str, session: &Weak<CmuxSession>) {
1870        let Ok(cp) = self.resolve_connected_port(physical) else {
1871            return;
1872        };
1873        let mut mux = crate::sync_util::lock_or_recover(&cp.mux);
1874        let current = mux
1875            .as_ref()
1876            .zip(session.upgrade())
1877            .is_some_and(|(a, b)| Arc::ptr_eq(a, &b));
1878        if !current {
1879            return;
1880        }
1881        mux.take();
1882        drop(mux);
1883        if let Some(hub) = crate::sync_util::lock_or_recover(&cp.rx_hub).as_ref() {
1884            hub.detach_cmux();
1885        };
1886    }
1887
1888    /// Close every CMUX virtual channel that rides on `physical`.
1889    fn close_virtual_channels_of(&self, physical: &str) {
1890        let virtual_paths: Vec<String> = crate::sync_util::lock_or_recover(&self.virtual_ports)
1891            .iter()
1892            .filter(|(_, vp)| vp.physical_path == physical)
1893            .map(|(p, _)| p.clone())
1894            .collect();
1895        for vp in virtual_paths {
1896            let _ = self.close(vp);
1897        }
1898    }
1899
1900    /// Cancel an in-flight exchange and reject queued waiters on `path`.
1901    pub fn cancel_exchange(&self, path: String) -> Result<(), Error> {
1902        if let Ok(virtuals) = self.virtual_ports.lock() {
1903            if let Some(vp) = virtuals.get(&path).cloned() {
1904                drop(virtuals);
1905                let session = {
1906                    let ports = self
1907                        .serialports
1908                        .lock()
1909                        .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?;
1910                    let info = ports.get(&vp.physical_path).ok_or_else(|| {
1911                        Error::String(format!("Physical port '{}' not found", vp.physical_path))
1912                    })?;
1913                    match &info.state {
1914                        PortState::Connected(cp) => cp
1915                            .mux
1916                            .lock()
1917                            .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?
1918                            .clone(),
1919                        other => return Err(Error::String(other.not_connected_reason())),
1920                    }
1921                };
1922                if let Some(session) = session {
1923                    crate::exchange::cancel::cancel_virtual_exchange(
1924                        &vp.exchange_cancel,
1925                        &vp.tx_queue,
1926                        &session,
1927                        vp.dlci,
1928                    );
1929                } else {
1930                    vp.exchange_cancel.store(true, Ordering::SeqCst);
1931                    vp.tx_queue.cancel_all();
1932                }
1933                return Ok(());
1934            }
1935        }
1936        let cp = self.resolve_connected_port(&path)?;
1937        crate::exchange::cancel::cancel_physical_exchange(
1938            &cp.exchange_cancel,
1939            &cp.tx_queue,
1940            || {
1941                if let Ok(guard) = cp.rx_hub.lock() {
1942                    if let Some(hub) = guard.as_ref() {
1943                        hub.cancel_active_exchange();
1944                    }
1945                }
1946            },
1947        );
1948        Ok(())
1949    }
1950
1951    /// Resolve a connected port's shared handles (brief global lock only).
1952    fn resolve_connected_port(&self, path: &str) -> Result<ConnectedPortHandle, Error> {
1953        let ports = self
1954            .serialports
1955            .lock()
1956            .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?;
1957        let info = ports.get(path).ok_or_else(|| self.not_open_error(path))?;
1958        match &info.state {
1959            PortState::Connected(cp) => Ok(cp.handle()),
1960            other => Err(Error::String(other.not_connected_reason())),
1961        }
1962    }
1963
1964    /// Run `f` only when the port is [`PortState::Connected`] (holds global lock for `f`).
1965    fn with_connected_port<T, F>(&self, path: String, f: F) -> Result<T, Error>
1966    where
1967        F: FnOnce(&mut ConnectedPort) -> Result<T, Error>,
1968    {
1969        let mut ports = self
1970            .serialports
1971            .lock()
1972            .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?;
1973
1974        let info = ports
1975            .get_mut(&path)
1976            .ok_or_else(|| self.not_open_error(&path))?;
1977
1978        match &mut info.state {
1979            PortState::Connected(cp) => f(cp),
1980            other => Err(Error::String(other.not_connected_reason())),
1981        }
1982    }
1983
1984    /// The error for a path with no record: the disconnect reason of a port the core
1985    /// released (4.x: calls on a dead port fail with a disconnect error), else
1986    /// "Port 'X' not found".
1987    fn not_open_error(&self, path: &str) -> Error {
1988        Error::String(
1989            self.released_reason(path)
1990                .unwrap_or_else(|| format!("Port '{}' not found", path)),
1991        )
1992    }
1993
1994    fn released_reason(&self, path: &str) -> Option<String> {
1995        crate::sync_util::lock_or_recover(&self.core.disconnected)
1996            .get(path)
1997            .cloned()
1998    }
1999
2000    /// Settings, lines, buffers and `set_timeout` go to the write handle when the port
2001    /// has one (no wait for the hub's read, no timeout override), else to the port.
2002    fn get_serialport<T, F>(&self, path: String, f: F) -> Result<T, Error>
2003    where
2004        F: FnOnce(&mut Box<dyn serialport::SerialPort>) -> Result<T, Error>,
2005    {
2006        let cp = self.resolve_connected_port(&path)?;
2007        let lock = Duration::from_millis(PORT_LOCK_TIMEOUT_MS);
2008        match self.writer_of(&path, &cp) {
2009            Some(writer) => lock_with_deadline(&writer, lock, false, f),
2010            None => with_port_try_lock(&cp.port, lock, f),
2011        }
2012    }
2013}
2014
2015/// Batch window, read size and URC routing of a watch.
2016fn watch_params(options: &WatchOptions) -> (u64, usize, bool) {
2017    let batch_timeout = options
2018        .serial_data_flush_interval_ms
2019        .or(options.timeout)
2020        .unwrap_or(DEFAULT_WATCH_FLUSH_MS);
2021    (
2022        batch_timeout,
2023        options.size.unwrap_or(1024),
2024        options.route_urc,
2025    )
2026}
2027
2028/// The 4.2 core API: [`CoreEvent`] streams, port-state subscriptions, queue limits.
2029impl SerialManager {
2030    /// Stream one port's events into `sink` as [`CoreEvent::Event`] (the final
2031    /// `Disconnect` included). Any number of these may run on a port, beside the old
2032    /// [`Self::watch`]: each gets its own copy of the stream and its own `parser` /
2033    /// `route_urc` state, and URCs caught during `at()` / `exchange` reach every one
2034    /// with `route_urc`. See [`CoreSink`] for threading, the queue and overflow.
2035    pub fn watch_core(
2036        &self,
2037        path: String,
2038        options: WatchOptions,
2039        parser: Option<serial_codec::framing::FramerConfig>,
2040        sink: CoreSink,
2041    ) -> Result<SubscriptionId, CoreError> {
2042        let framer = parser
2043            .as_ref()
2044            .map(|p| p.build())
2045            .transpose()
2046            .map_err(|e| CoreError::new(ErrorKind::Other, Error::String(e.to_string())))?;
2047        let (batch_timeout, read_size, route_urc) = watch_params(&options);
2048        let id = next_subscription_id();
2049        let queue = CoreQueue::spawn(sink, self.core_queue_capacity());
2050        if let Some(reason) = self.released_reason(&path) {
2051            queue.push(CoreEvent::Event(SerialEvent::Disconnect { path, reason }));
2052            queue.close();
2053            return Ok(SubscriptionId(id));
2054        }
2055        let virtual_port = crate::sync_util::lock_or_recover(&self.virtual_ports)
2056            .get(&path)
2057            .cloned();
2058        if let Some(vp) = virtual_port {
2059            let cp = self.resolve_connected_port(&vp.physical_path)?;
2060            let session = crate::sync_util::lock_or_recover(&cp.mux)
2061                .clone()
2062                .ok_or_else(|| Error::String("CMUX not enabled".into()))?;
2063            self.ensure_rx_hub(&cp, &vp.physical_path)?;
2064            if !session.add_core_watch(
2065                vp.dlci,
2066                id,
2067                queue.event_sink(),
2068                queue.alive_flag(),
2069                batch_timeout,
2070                framer,
2071            ) {
2072                return Err(Error::String(format!("Port '{}' not found", path)).into());
2073            }
2074        } else {
2075            let cp = self.resolve_connected_port(&path)?;
2076            self.ensure_rx_hub(&cp, &path)?;
2077            let shared = crate::sync_util::lock_or_recover(&cp.rx_hub)
2078                .as_ref()
2079                .map(|h| h.shared())
2080                .ok_or_else(|| Error::String("RX hub missing after start".into()))?;
2081            shared.attach_core_watch(crate::hub::shared::CoreWatchSlot::new(
2082                id,
2083                queue.event_sink(),
2084                queue.alive_flag(),
2085                batch_timeout,
2086                read_size,
2087                route_urc,
2088                framer,
2089            ));
2090        }
2091        crate::sync_util::lock_or_recover(&self.core.core_watches).insert(id, path);
2092        Ok(SubscriptionId(id))
2093    }
2094
2095    /// Stop a [`Self::watch_core`] stream; its batch and parser remainder arrive last.
2096    /// `NotFound` also for a stream that already ended (overflow, sink returned
2097    /// `false`, port gone).
2098    pub fn unwatch_core(&self, id: SubscriptionId) -> Result<(), CoreError> {
2099        let not_found = || {
2100            CoreError::new(
2101                ErrorKind::NotFound,
2102                Error::new(format!("No active watch for id {}", id.0)),
2103            )
2104        };
2105        let path = crate::sync_util::lock_or_recover(&self.core.core_watches)
2106            .remove(&id.0)
2107            .ok_or_else(not_found)?;
2108        let virtual_port = crate::sync_util::lock_or_recover(&self.virtual_ports)
2109            .get(&path)
2110            .cloned();
2111        let detached = if let Some(vp) = virtual_port {
2112            self.resolve_connected_port(&vp.physical_path)
2113                .ok()
2114                .and_then(|cp| crate::sync_util::lock_or_recover(&cp.mux).clone())
2115                .is_some_and(|session| session.remove_core_watch(vp.dlci, id.0))
2116        } else {
2117            self.resolve_connected_port(&path)
2118                .ok()
2119                .and_then(|cp| {
2120                    crate::sync_util::lock_or_recover(&cp.rx_hub)
2121                        .as_ref()
2122                        .map(|h| h.shared())
2123                })
2124                .is_some_and(|shared| shared.detach_core_watch(id.0))
2125        };
2126        if detached {
2127            Ok(())
2128        } else {
2129            Err(not_found())
2130        }
2131    }
2132
2133    /// Port states of every port of this manager ([`CoreEvent::PortState`]: opened,
2134    /// disconnected with its kind and reason, closed); needs no watch. Same queue and
2135    /// overflow rules as [`Self::watch_core`].
2136    pub fn subscribe_core(&self, sink: CoreSink) -> SubscriptionId {
2137        let id = next_subscription_id();
2138        let queue = CoreQueue::spawn(sink, self.core_queue_capacity());
2139        crate::sync_util::lock_or_recover(&self.core.subscribers).push((id, queue));
2140        SubscriptionId(id)
2141    }
2142
2143    pub fn unsubscribe_core(&self, id: SubscriptionId) -> Result<(), CoreError> {
2144        let mut subs = crate::sync_util::lock_or_recover(&self.core.subscribers);
2145        let i = subs.iter().position(|(s, _)| *s == id.0).ok_or_else(|| {
2146            CoreError::new(
2147                ErrorKind::NotFound,
2148                Error::new(format!("No subscription {}", id.0)),
2149            )
2150        })?;
2151        subs.remove(i).1.close();
2152        Ok(())
2153    }
2154
2155    /// Queue limit (bytes of event data) of core receivers created from now on.
2156    /// Default [`crate::events::DEFAULT_CORE_QUEUE_BYTES`].
2157    pub fn set_core_queue_capacity(&self, bytes: usize) {
2158        self.core.queue_capacity.store(bytes, Ordering::SeqCst);
2159    }
2160
2161    fn core_queue_capacity(&self) -> usize {
2162        match self.core.queue_capacity.load(Ordering::SeqCst) {
2163            0 => crate::events::DEFAULT_CORE_QUEUE_BYTES,
2164            n => n,
2165        }
2166    }
2167
2168    fn emit_port_state(&self, path: &str, state: PortStatus) {
2169        let subs: Vec<Arc<CoreQueue>> = crate::sync_util::lock_or_recover(&self.core.subscribers)
2170            .iter()
2171            .map(|(_, q)| q.clone())
2172            .collect();
2173        for q in subs {
2174            q.push(CoreEvent::PortState {
2175                path: path.to_string(),
2176                state: state.clone(),
2177            });
2178        }
2179        crate::sync_util::lock_or_recover(&self.core.subscribers).retain(|(_, q)| q.alive());
2180    }
2181
2182    fn downgrade(&self) -> WeakManager {
2183        WeakManager {
2184            serialports: Arc::downgrade(&self.serialports),
2185            virtual_ports: Arc::downgrade(&self.virtual_ports),
2186            core: Arc::downgrade(&self.core),
2187        }
2188    }
2189
2190    // --- old watch registry (per manager; mirrored into `port::watch_registry`)
2191
2192    fn register_watch(&self, id: u32, path: &str) -> Result<(), Error> {
2193        let mut watches = crate::sync_util::lock_or_recover(&self.core.watches);
2194        if watches.contains_key(&id) {
2195            return Err(Error::new(format!("watch id {} is already in use", id)));
2196        }
2197        if watches.values().any(|p| p == path) {
2198            return Err(Error::new(format!(
2199                "A watch is already active for port {}",
2200                path
2201            )));
2202        }
2203        // The 4.x global registry is shared by every manager: an id another manager
2204        // holds is taken too (else one manager's watch would vanish from it).
2205        if !crate::port::watch_registry::mirror_insert(id, path) {
2206            return Err(Error::new(format!("watch id {} is already in use", id)));
2207        }
2208        watches.insert(id, path.to_string());
2209        Ok(())
2210    }
2211
2212    fn unregister_watch(&self, id: u32) -> Option<String> {
2213        let path = crate::sync_util::lock_or_recover(&self.core.watches).remove(&id);
2214        if path.is_some() {
2215            crate::port::watch_registry::mirror_remove(id);
2216        }
2217        path
2218    }
2219
2220    fn watch_ids_for(&self, path: &str) -> Vec<u32> {
2221        crate::sync_util::lock_or_recover(&self.core.watches)
2222            .iter()
2223            .filter(|(_, p)| p.as_str() == path)
2224            .map(|(id, _)| *id)
2225            .collect()
2226    }
2227
2228    fn core_watch_ids_for(&self, path: &str) -> Vec<u64> {
2229        crate::sync_util::lock_or_recover(&self.core.core_watches)
2230            .iter()
2231            .filter(|(_, p)| p.as_str() == path)
2232            .map(|(id, _)| *id)
2233            .collect()
2234    }
2235
2236    /// Drop the registry entries of `path` (the port is gone; its hub ended the streams).
2237    fn forget_watches(&self, path: &str) {
2238        for id in self.watch_ids_for(path) {
2239            self.unregister_watch(id);
2240        }
2241        crate::sync_util::lock_or_recover(&self.core.core_watches).retain(|_, p| p != path);
2242    }
2243
2244    // --- port handles and hub
2245
2246    /// Wrap a freshly opened port: write handle (where it can be split) and RX hub.
2247    fn connect(
2248        &self,
2249        path: &str,
2250        port: Box<dyn SerialPortTrait>,
2251        timeout: Duration,
2252        first_watch: Option<crate::hub::shared::CoreWatchSlot>,
2253    ) -> (ConnectedPort, Result<(), Error>) {
2254        let writer = split_writer(path, port.as_ref(), timeout);
2255        let cp = ConnectedPort::new(port);
2256        if let Some(writer) = writer {
2257            crate::sync_util::lock_or_recover(&self.core.writers).insert(
2258                path.to_string(),
2259                Writer {
2260                    reader: Arc::downgrade(&cp.port),
2261                    port: Arc::new(Mutex::new(writer)),
2262                },
2263            );
2264        }
2265        let hub = self.start_rx_hub(&cp.handle(), path, first_watch);
2266        (cp, hub)
2267    }
2268
2269    /// The write handle of `path`, if it was split from this very port.
2270    fn writer_of(&self, path: &str, cp: &ConnectedPortHandle) -> Option<PortArc> {
2271        crate::sync_util::lock_or_recover(&self.core.writers)
2272            .get(path)
2273            .filter(|w| {
2274                w.reader
2275                    .upgrade()
2276                    .is_some_and(|r| Arc::ptr_eq(&r, &cp.port))
2277            })
2278            .map(|w| w.port.clone())
2279    }
2280
2281    fn drop_writer(&self, path: &str) {
2282        crate::sync_util::lock_or_recover(&self.core.writers).remove(path);
2283    }
2284
2285    /// Start the RX hub if it is not running (it is restarted after an intentional
2286    /// stop; after a disconnect the port is gone, so it never restarts on a dead fd).
2287    fn ensure_rx_hub(&self, cp: &ConnectedPortHandle, path: &str) -> Result<(), Error> {
2288        self.start_rx_hub(cp, path, None)
2289    }
2290
2291    /// [`Self::ensure_rx_hub`]; `first_watch` joins the hub before its first read.
2292    fn start_rx_hub(
2293        &self,
2294        cp: &ConnectedPortHandle,
2295        path: &str,
2296        first_watch: Option<crate::hub::shared::CoreWatchSlot>,
2297    ) -> Result<(), Error> {
2298        let mut guard = cp
2299            .rx_hub
2300            .lock()
2301            .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?;
2302        let needs_start = match guard.as_ref() {
2303            None => true,
2304            Some(hub) => hub.is_finished(),
2305        };
2306        if needs_start {
2307            let manager = self.downgrade();
2308            let reader = Arc::downgrade(&cp.port);
2309            let owner = path.to_string();
2310            let hook: crate::hub::desktop::DisconnectHook = Box::new(move |reason| {
2311                if let Some(m) = manager.upgrade() {
2312                    m.on_port_disconnected(&owner, &reader, reason);
2313                }
2314            });
2315            let hub = Arc::new(crate::hub::PortRxHub::start_with(
2316                cp.port.clone(),
2317                path.to_string(),
2318                Some(hook),
2319                first_watch,
2320            ));
2321            register_mobile_hub(path, cp, hub.clone());
2322            *guard = Some(hub);
2323        } else if let (Some(slot), Some(hub)) = (first_watch, guard.as_ref()) {
2324            hub.shared().attach_core_watch(slot);
2325        }
2326        Ok(())
2327    }
2328
2329    fn ensure_rx_hub_on_physical(&self, physical_path: &str) -> Result<(), Error> {
2330        let cp = self.resolve_connected_port(physical_path)?;
2331        self.ensure_rx_hub(&cp, physical_path)
2332    }
2333
2334    /// On the hub thread, after `Disconnect` went out: release the record if it is
2335    /// still this reader's (see [`Self::release`]). Never joins the hub (its thread).
2336    fn on_port_disconnected(
2337        &self,
2338        path: &str,
2339        reader: &Weak<Mutex<Box<dyn SerialPortTrait>>>,
2340        reason: &str,
2341    ) {
2342        let removed = {
2343            let mut map = crate::sync_util::lock_or_recover(&self.serialports);
2344            let same = match map.get(path).map(|i| &i.state) {
2345                Some(PortState::Connected(cp)) => {
2346                    reader.upgrade().is_some_and(|r| Arc::ptr_eq(&r, &cp.port))
2347                }
2348                _ => false,
2349            };
2350            if same {
2351                map.remove(path)
2352            } else {
2353                None
2354            }
2355        };
2356        if let Some(info) = removed {
2357            self.release(path, info, reason);
2358        }
2359    }
2360
2361    /// A port that disconnected (its record already out of the map): drop both handles,
2362    /// the hub and its CMUX channels, keep a tombstone with `reason` for each (listed,
2363    /// a late watch gets `Disconnect`, calls fail with it, `close` removes it), and send
2364    /// `PortState::Disconnected`. Watches stay registered until `close` / `unwatch`.
2365    fn release(&self, path: &str, info: SerialportInfo, reason: &str) {
2366        let channels: Vec<String> = {
2367            let mut virtuals = crate::sync_util::lock_or_recover(&self.virtual_ports);
2368            let keys: Vec<String> = virtuals
2369                .iter()
2370                .filter(|(_, vp)| vp.physical_path == path)
2371                .map(|(k, _)| k.clone())
2372                .collect();
2373            for k in &keys {
2374                if let Some(vp) = virtuals.remove(k) {
2375                    vp.tx_queue.cancel_all();
2376                }
2377            }
2378            keys
2379        };
2380        self.drop_writer(path);
2381        {
2382            let mut released = crate::sync_util::lock_or_recover(&self.core.disconnected);
2383            for p in channels.iter().map(String::as_str).chain([path]) {
2384                released.insert(p.to_string(), reason.to_string());
2385            }
2386        }
2387        if let PortState::Connected(cp) = info.state {
2388            // Dropping the hub handle detaches its (ending) thread; the reader goes with it.
2389            crate::sync_util::lock_or_recover(&cp.rx_hub).take();
2390            #[cfg(target_os = "android")]
2391            crate::android::registry::global_registry().unregister(path);
2392        }
2393        log_info!("{} released after disconnect: {}", path, reason);
2394        // The I/O error kind is in `reason`; an unplug is `Disconnected` on every
2395        // platform (Windows reports it as PermissionDenied).
2396        for p in channels.iter().map(String::as_str).chain([path]) {
2397            self.emit_port_state(
2398                p,
2399                PortStatus::Disconnected {
2400                    kind: ErrorKind::Disconnected,
2401                    reason: reason.to_string(),
2402                },
2403            );
2404        }
2405    }
2406}
2407
2408impl crate::at::commands::ExchangeRunner for SerialManager {
2409    fn run_exchange_unqueued(
2410        &self,
2411        path: String,
2412        payload: Vec<u8>,
2413        options: ExchangeOptions,
2414    ) -> Result<crate::at::parse::ExchangeResponse, Error> {
2415        SerialManager::run_exchange_unqueued(self, path, payload, options)
2416    }
2417}