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::Error;
11use crate::events::{EventSink, ExchangeOptions, PortListSink, WatchOptions};
12#[cfg(target_os = "android")]
13use crate::log_error;
14use crate::port::tx_queue::PortTxQueue;
15use crate::state::{
16    ClearBuffer, ConnectedPort, ConnectedPortHandle, DataBits, FlowControl, Parity, PortState,
17    SerialportInfo, StopBits,
18};
19use crate::{log_debug, log_info};
20use serialport::SerialPort as SerialPortTrait;
21use std::collections::HashMap;
22use std::io::Write;
23use std::sync::atomic::{AtomicU32, Ordering};
24use std::sync::{Arc, Mutex};
25use std::thread;
26use std::time::{Duration, Instant};
27
28/// Ids handed out by [`SerialManager::watch`] / [`SerialManager::watch_ports`].
29/// The Tauri plugin passes its IPC channel ids through the `*_with_id` variants instead;
30/// both share one registry, so an id already taken there is skipped (and `register`
31/// rejects a duplicate id outright).
32fn next_watch_id(taken: impl Fn(u32) -> bool) -> u32 {
33    static NEXT: AtomicU32 = AtomicU32::new(1);
34    loop {
35        let id = NEXT.fetch_add(1, Ordering::Relaxed);
36        if !taken(id) {
37            return id;
38        }
39    }
40}
41
42/// Platform seam: enumerate available ports.
43fn platform_available_ports(
44    single_port_per_device: bool,
45) -> Result<HashMap<String, HashMap<String, String>>, Error> {
46    #[cfg(not(target_os = "android"))]
47    {
48        crate::port::list::enumerate_available_ports(single_port_per_device)
49    }
50    #[cfg(target_os = "android")]
51    {
52        let json = crate::android::fd_bridge::call_enumerate_json()?;
53        log_info!(
54            "[SerialEnumerate] raw json ({} bytes): {}",
55            json.len(),
56            json
57        );
58        #[derive(serde::Deserialize)]
59        struct AvailablePortsResponse {
60            #[serde(default)]
61            ports: HashMap<String, crate::android::enumerate::DeviceEntry>,
62        }
63        let response: AvailablePortsResponse = serde_json::from_str(&json).map_err(|e| {
64            log_error!("[SerialEnumerate] Invalid enumerate JSON: {e}; body={json}");
65            Error::new(format!("Invalid enumerate JSON: {e}"))
66        })?;
67        let filtered =
68            crate::android::enumerate::expand_devices(response.ports, single_port_per_device)?;
69        let keys: Vec<&str> = filtered.keys().map(|s| s.as_str()).collect();
70        log_info!(
71            "[SerialEnumerate] parsed {} port(s) single={} keys={:?}",
72            filtered.len(),
73            single_port_per_device,
74            keys
75        );
76        Ok(filtered)
77    }
78}
79
80/// Platform seam: open physical port as `Box<dyn serialport::SerialPort>`.
81#[allow(clippy::too_many_arguments)]
82fn platform_open(
83    path: &str,
84    baud_rate: u32,
85    data_bits: DataBits,
86    flow_control: FlowControl,
87    parity: Parity,
88    stop_bits: StopBits,
89    timeout: Duration,
90    lines: crate::state::ModemLinesOnOpen,
91) -> Result<(String, Box<dyn SerialPortTrait>), Error> {
92    if path.starts_with("ble://") {
93        #[cfg(feature = "ble")]
94        {
95            #[cfg(not(target_os = "android"))]
96            use crate::port::ble::BleSerialPort as Ble;
97            #[cfg(target_os = "android")]
98            use crate::port::ble_android::AndroidBleSerialPort as Ble;
99            let port = Ble::connect(
100                path,
101                baud_rate,
102                data_bits.into(),
103                flow_control.into(),
104                parity.into(),
105                stop_bits.into(),
106                timeout,
107            )
108            .map_err(|e| Error::String(format!("Failed to open {path}: {e}")))?;
109            return Ok((path.to_string(), Box::new(port)));
110        }
111        #[cfg(not(feature = "ble"))]
112        return Err(Error::String(format!(
113            "{path}: BLE needs the plugin's `ble` cargo feature"
114        )));
115    }
116    if crate::port::tcp::tcp_address(path).is_some() {
117        let port = crate::port::tcp::TcpSerialPort::connect(
118            path,
119            baud_rate,
120            data_bits.into(),
121            flow_control.into(),
122            parity.into(),
123            stop_bits.into(),
124            timeout,
125        )
126        .map_err(|e| Error::String(format!("Failed to open {path}: {e}")))?;
127        return Ok((path.to_string(), Box::new(port)));
128    }
129    // iOS has no local serial devices; serialport's open/enumerate code would also
130    // pull in IOKit, which iOS apps cannot link.
131    #[cfg(target_os = "ios")]
132    {
133        let _ = (
134            baud_rate,
135            data_bits,
136            flow_control,
137            parity,
138            stop_bits,
139            timeout,
140            lines,
141        );
142        Err(Error::String(format!(
143            "{path}: iOS has no local serial ports; use a tcp://host:port bridge"
144        )))
145    }
146    #[cfg(not(any(target_os = "android", target_os = "ios")))]
147    {
148        let mut builder = serialport::new(path, baud_rate)
149            .data_bits(data_bits.into())
150            .flow_control(flow_control.into())
151            .parity(parity.into())
152            .stop_bits(stop_bits.into())
153            .timeout(timeout);
154        if let Some(dtr) = lines.dtr {
155            builder = builder.dtr_on_open(dtr);
156        }
157        let mut port = builder
158            .open()
159            .map_err(|e| Error::String(format!("Failed to open serial port: {}", e)))?;
160        if let Some(rts) = lines.rts {
161            port.write_request_to_send(rts)
162                .map_err(|e| Error::String(format!("Failed to set RTS on open: {}", e)))?;
163        }
164        Ok((path.to_string(), port))
165    }
166    #[cfg(target_os = "android")]
167    {
168        let _ = timeout;
169        crate::android::driver_host::global_host().open(
170            path,
171            baud_rate,
172            data_bits,
173            flow_control,
174            parity,
175            stop_bits,
176            lines,
177        )
178    }
179}
180
181/// Default read/write timeout (ms) when opening a port.
182const DEFAULT_PORT_TIMEOUT_MS: u64 = 1000;
183const PORT_LOCK_TIMEOUT_MS: u64 = 250;
184const PORT_IO_TIMEOUT_MS: u64 = 100;
185/// Watch batch window when the caller sets none: short enough for interactive
186/// terminals, long enough to coalesce a burst into one event.
187const DEFAULT_WATCH_FLUSH_MS: u64 = 20;
188
189/// Acquire the port mutex with a deadline (hub reader uses try_lock; avoid blocking forever).
190fn with_port_try_lock<T, F>(
191    port: &Arc<Mutex<Box<dyn serialport::SerialPort>>>,
192    lock_timeout: Duration,
193    f: F,
194) -> Result<T, Error>
195where
196    F: FnOnce(&mut Box<dyn serialport::SerialPort>) -> Result<T, Error>,
197{
198    let deadline = Instant::now() + lock_timeout;
199    loop {
200        match port.try_lock() {
201            Ok(mut guard) => {
202                let _ = guard.set_timeout(Duration::from_millis(PORT_IO_TIMEOUT_MS));
203                return f(&mut guard);
204            }
205            Err(_) if Instant::now() >= deadline => {
206                return Err(Error::String(format!(
207                    "serial port lock timeout after {} ms",
208                    lock_timeout.as_millis()
209                )));
210            }
211            Err(_) => thread::sleep(Duration::from_millis(1)),
212        }
213    }
214}
215
216/// Write the full buffer, retrying until all bytes are sent or an error occurs.
217fn write_all_port(
218    port: &mut Box<dyn serialport::SerialPort>,
219    buf: &[u8],
220    operation: &str,
221) -> Result<usize, Error> {
222    // The shared 100 ms I/O timeout is too short for big or slow writes (8 KB at
223    // 9600 baud needs ~9 s), so give writes room for the wire time plus a margin.
224    let baud = u64::from(port.baud_rate().unwrap_or(9600).max(1));
225    let wire_ms = (buf.len() as u64).saturating_mul(11_000) / baud;
226    let _ = port.set_timeout(Duration::from_millis(wire_ms.saturating_mul(2) + 1000));
227    let result = port
228        .write_all(buf)
229        .map_err(|e| Error::String(format!("Failed to {}: {}", operation, e)));
230    let _ = port.set_timeout(Duration::from_millis(PORT_IO_TIMEOUT_MS));
231    result.map(|()| buf.len())
232}
233
234/// Tear down resources held by a [`SerialportInfo`] (RX hub + port).
235fn finish_serialport_info(path: &str, info: SerialportInfo) -> Result<(), Error> {
236    #[cfg(not(target_os = "android"))]
237    let _ = path;
238    match info.state {
239        PortState::Connected(cp) => {
240            if let Ok(mut hub_guard) = cp.rx_hub.lock() {
241                if let Some(hub) = hub_guard.take() {
242                    #[cfg(target_os = "android")]
243                    crate::android::registry::global_registry().unregister(path);
244                    match Arc::try_unwrap(hub) {
245                        Ok(hub) => hub.stop(),
246                        Err(hub) => hub.request_stop(),
247                    }
248                }
249            }
250            #[cfg(target_os = "android")]
251            {
252                let _ = crate::android::driver_host::global_host().close(Some(path));
253            }
254            Ok(())
255        }
256        PortState::Opening | PortState::Closed => Ok(()),
257    }
258}
259
260fn register_mobile_hub(path: &str, cp: &ConnectedPortHandle, hub: Arc<crate::hub::PortRxHub>) {
261    #[cfg(target_os = "android")]
262    {
263        let hub_handle: Arc<dyn crate::hub::RxHubHandle> = hub;
264        crate::android::registry::global_registry().register(path, hub_handle, cp.clone());
265    }
266    #[cfg(not(target_os = "android"))]
267    {
268        let _ = (path, cp, hub);
269    }
270}
271
272fn ensure_rx_hub_running(cp: &ConnectedPortHandle, path: &str) -> Result<(), Error> {
273    let mut guard = cp
274        .rx_hub
275        .lock()
276        .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?;
277    let needs_start = match guard.as_ref() {
278        None => true,
279        Some(hub) => hub.is_finished(),
280    };
281    if needs_start {
282        let hub = Arc::new(crate::hub::PortRxHub::start(
283            cp.port.clone(),
284            path.to_string(),
285        ));
286        register_mobile_hub(path, cp, hub.clone());
287        *guard = Some(hub);
288    }
289    Ok(())
290}
291
292fn ensure_rx_hub(cp: &ConnectedPortHandle, path: &str) -> Result<(), Error> {
293    ensure_rx_hub_running(cp, path)
294}
295
296fn ensure_rx_hub_on_physical(serial: &SerialManager, physical_path: &str) -> Result<(), Error> {
297    let cp = serial.resolve_connected_port(physical_path)?;
298    ensure_rx_hub(&cp, physical_path)
299}
300
301/// Owns every open port (desktop serial, `tcp://`, `ble://`, Android USB, CMUX channels).
302///
303/// Cheap to clone (all clones share the same ports). Methods block: call them from a
304/// plain thread or `tokio::task::spawn_blocking`, not straight from an async task.
305///
306/// Lock order: `serialports` before `virtual_ports`; never hold a map lock across
307/// device I/O, thread spawn, or `JoinHandle` join.
308#[derive(Clone, Default)]
309pub struct SerialManager {
310    #[doc(hidden)]
311    pub serialports: Arc<Mutex<HashMap<String, SerialportInfo>>>,
312    #[doc(hidden)]
313    pub virtual_ports: Arc<Mutex<HashMap<String, crate::state::VirtualPortRef>>>,
314}
315
316impl SerialManager {
317    pub fn new() -> Self {
318        Self::default()
319    }
320
321    /// Android only: hook USB detach / port-list callbacks from the Kotlin side into this manager.
322    #[cfg(target_os = "android")]
323    pub fn setup_teardown(&self) {
324        let serialports = self.serialports.clone();
325        let virtual_ports = self.virtual_ports.clone();
326        crate::android::registry::set_rust_state_fail(Box::new(move |path, _reason| {
327            if let Err(e) = Self::rust_fail_port_state(&serialports, &virtual_ports, path) {
328                crate::log_warn!("rust_fail_port_state {}: {}", path, e);
329            }
330        }));
331        crate::port::list_monitor::set_android_enumerator(move |single| {
332            platform_available_ports(single)
333        });
334        crate::android::registry::init_registry();
335    }
336
337    #[cfg(target_os = "android")]
338    fn rust_fail_port_state(
339        ports: &Arc<Mutex<HashMap<String, SerialportInfo>>>,
340        virtual_ports: &Arc<Mutex<HashMap<String, crate::state::VirtualPortRef>>>,
341        path: &str,
342    ) -> Result<(), Error> {
343        if let Ok(mut v) = virtual_ports.lock() {
344            if let Some(vp) = v.remove(path) {
345                vp.tx_queue.cancel_all();
346            }
347        }
348        let mut map = ports
349            .lock()
350            .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?;
351        map.remove(path);
352        Ok(())
353    }
354
355    /// Get serial port list
356    pub fn available_ports(
357        &self,
358        single_port_per_device: bool,
359    ) -> Result<HashMap<String, HashMap<String, String>>, Error> {
360        platform_available_ports(single_port_per_device)
361    }
362
363    /// Subscribe to available-port attach/detach events. `sink` first gets a
364    /// [`Snapshot`](crate::events::PortListEvent::Snapshot), then `added` / `removed`.
365    /// Returns the id for [`Self::unwatch_ports`].
366    pub fn watch_ports(
367        &self,
368        options: crate::events::WatchPortsOptions,
369        sink: PortListSink,
370    ) -> Result<u32, Error> {
371        self.watch_ports_with_id(
372            next_watch_id(crate::port::list_monitor::is_subscribed),
373            options,
374            sink,
375        )
376    }
377
378    /// [`Self::watch_ports`] under a caller-chosen id (the plugin uses its IPC channel id).
379    pub fn watch_ports_with_id(
380        &self,
381        id: u32,
382        options: crate::events::WatchPortsOptions,
383        sink: PortListSink,
384    ) -> Result<u32, Error> {
385        crate::port::list_monitor::subscribe_sink(id, sink, options)?;
386        Ok(id)
387    }
388
389    /// Stop a port-list watch session.
390    pub fn unwatch_ports(&self, channel_id: u32) -> Result<(), Error> {
391        crate::port::list_monitor::unsubscribe(channel_id);
392        Ok(())
393    }
394
395    /// Get a list of managed serial ports.
396    pub fn managed_ports(&self) -> Result<Vec<String>, Error> {
397        // Lock the Mutex to safely access the data inside `self.serialports`.
398        let ports = self
399            .serialports
400            .lock()
401            .map_err(|_| Error::String("Failed to lock serialports mutex".to_string()))?;
402
403        let mut port_list: Vec<String> = ports.keys().cloned().collect();
404        if let Ok(virtuals) = self.virtual_ports.lock() {
405            port_list.extend(virtuals.keys().cloned());
406        }
407        port_list.sort();
408        Ok(port_list)
409    }
410
411    /// Cancel an in-flight poll [`Self::read`] (does not stop an active [`Self::watch`]).
412    pub fn cancel_read(&self, path: String) -> Result<(), Error> {
413        let cp = self.resolve_connected_port(&path)?;
414        if let Ok(guard) = cp.rx_hub.lock() {
415            if let Some(hub) = guard.as_ref() {
416                hub.shared().cancel_pending_read();
417            }
418        }
419        Ok(())
420    }
421
422    /// Close the specified serial port
423    pub fn close(&self, path: String) -> Result<(), Error> {
424        log_debug!("close {}", path);
425
426        for channel_id in crate::port::watch_registry::paths_for_port(&path) {
427            let _ = self.unwatch(channel_id);
428        }
429
430        if let Ok(mut virtuals) = self.virtual_ports.lock() {
431            if let Some(vp) = virtuals.remove(&path) {
432                vp.tx_queue.cancel_all();
433                let physical = vp.physical_path.clone();
434                let dlci = vp.dlci;
435                drop(virtuals);
436                if let Ok(cp) = self.resolve_connected_port(&physical) {
437                    if let Some(session) = crate::sync_util::lock_or_recover(&cp.mux).clone() {
438                        session.unregister_dlci(dlci);
439                    }
440                }
441                return Ok(());
442            }
443        }
444
445        // Physical port: its virtual channels and CMUX session go with it.
446        if self.resolve_connected_port(&path).is_ok() {
447            let _ = self.disable_mux(path.clone());
448        }
449
450        let removed = match self.serialports.lock() {
451            Ok(mut serialports) => serialports.remove(&path),
452            Err(error) => {
453                return Err(Error::String(format!("Failed to acquire lock: {}", error)));
454            }
455        };
456
457        if let Some(port_info) = removed {
458            log_debug!("stop {}", path);
459            finish_serialport_info(&path, port_info)?;
460            log_debug!("end {}", path);
461            Ok(())
462        } else {
463            Err(Error::String(format!("Serial port {} is not open!", path)))
464        }
465    }
466
467    /// Close all open serial ports
468    pub fn close_all(&self) -> Result<(), Error> {
469        let paths = self.managed_ports()?;
470        let mut errors = vec![];
471
472        for path in paths {
473            if let Err(e) = self.close(path) {
474                errors.push(e.to_string());
475            }
476        }
477
478        if errors.is_empty() {
479            Ok(())
480        } else {
481            Err(Error::String(errors.join(", ")))
482        }
483    }
484
485    /// Force close a serial port
486    pub fn force_close(&self, path: String) -> Result<(), Error> {
487        for channel_id in crate::port::watch_registry::paths_for_port(&path) {
488            let _ = self.unwatch(channel_id);
489        }
490        if crate::sync_util::lock_or_recover(&self.virtual_ports).contains_key(&path) {
491            return self.close(path);
492        }
493        self.close_virtual_channels_of(&path);
494        if let Ok(cp) = self.resolve_connected_port(&path) {
495            if let Some(session) = crate::sync_util::lock_or_recover(&cp.mux).take() {
496                session.close_down();
497            }
498        }
499
500        // Remove under the lock, join the hub outside it (lock order, see the struct docs).
501        let removed = match self.serialports.lock() {
502            Ok(mut map) => map.remove(&path),
503            Err(error) => return Err(Error::String(format!("Failed to acquire lock: {}", error))),
504        };
505        if let Some(serial) = removed {
506            finish_serialport_info(&path, serial)?;
507        }
508        Ok(())
509    }
510
511    #[allow(clippy::too_many_arguments)]
512    pub fn open(
513        &self,
514        path: String,
515        baud_rate: u32,
516        data_bits: Option<DataBits>,
517        flow_control: Option<FlowControl>,
518        parity: Option<Parity>,
519        stop_bits: Option<StopBits>,
520        timeout: Option<u64>,
521    ) -> Result<String, Error> {
522        self.open_with_lines(
523            path,
524            baud_rate,
525            data_bits,
526            flow_control,
527            parity,
528            stop_bits,
529            timeout,
530            crate::state::ModemLinesOnOpen::default(),
531        )
532    }
533
534    /// [`Self::open`] with explicit DTR / RTS levels on open.
535    #[allow(clippy::too_many_arguments)]
536    pub fn open_with_lines(
537        &self,
538        path: String,
539        baud_rate: u32,
540        data_bits: Option<DataBits>,
541        flow_control: Option<FlowControl>,
542        parity: Option<Parity>,
543        stop_bits: Option<StopBits>,
544        timeout: Option<u64>,
545        lines: crate::state::ModemLinesOnOpen,
546    ) -> Result<String, Error> {
547        // Re-open (e.g. after a webview reload): tear the old session down the same
548        // way `close` does, so its watches, CMUX channels and hub go with it.
549        let already_open = matches!(
550            crate::sync_util::lock_or_recover(&self.serialports)
551                .get(&path)
552                .map(|i| &i.state),
553            Some(PortState::Connected(_))
554        );
555        if already_open {
556            log_info!("Replacing existing port {}", path);
557            let _ = self.close(path.clone());
558        }
559        let stale = {
560            let mut serialports = self
561                .serialports
562                .lock()
563                .map_err(|e| Error::String(format!("Failed to acquire lock: {}", e)))?;
564            if matches!(
565                serialports.get(&path).map(|i| &i.state),
566                Some(PortState::Opening)
567            ) {
568                return Err(Error::String(format!(
569                    "open already in progress for {}",
570                    path
571                )));
572            }
573            let stale = serialports.remove(&path);
574            serialports.insert(
575                path.clone(),
576                SerialportInfo {
577                    state: PortState::Opening,
578                },
579            );
580            stale
581        };
582
583        if let Some(existing) = stale {
584            log_info!("Replacing existing port {}", path);
585            finish_serialport_info(&path, existing)?;
586        }
587
588        let timeout_ms = timeout.unwrap_or(DEFAULT_PORT_TIMEOUT_MS);
589        let port_result = platform_open(
590            &path,
591            baud_rate,
592            data_bits.unwrap_or(DataBits::Eight),
593            flow_control.unwrap_or(FlowControl::None),
594            parity.unwrap_or(Parity::None),
595            stop_bits.unwrap_or(StopBits::One),
596            Duration::from_millis(timeout_ms),
597            lines,
598        );
599
600        let mut serialports = self
601            .serialports
602            .lock()
603            .map_err(|e| Error::String(format!("Failed to acquire lock: {}", e)))?;
604
605        match port_result {
606            Ok((session_path, port)) => {
607                if session_path != path {
608                    serialports.remove(&path);
609                    if !serialports.contains_key(&session_path) {
610                        serialports.insert(
611                            session_path.clone(),
612                            SerialportInfo {
613                                state: PortState::Opening,
614                            },
615                        );
616                    }
617                }
618
619                let cp = ConnectedPort::new(port);
620                let hub = ensure_rx_hub(&cp.handle(), &session_path);
621                let reserved = matches!(
622                    serialports.get(&session_path).map(|i| &i.state),
623                    Some(PortState::Opening)
624                );
625                if let (Ok(()), true) = (&hub, reserved) {
626                    if let Some(entry) = serialports.get_mut(&session_path) {
627                        entry.state = PortState::Connected(cp);
628                    }
629                    return Ok(session_path);
630                }
631                // Never leave an `Opening` entry or a running hub thread behind.
632                if reserved {
633                    serialports.remove(&session_path);
634                }
635                drop(serialports);
636                let _ = finish_serialport_info(
637                    &session_path,
638                    SerialportInfo {
639                        state: PortState::Connected(cp),
640                    },
641                );
642                hub?;
643                Err(Error::String(format!(
644                    "Port '{}' state changed during open",
645                    session_path
646                )))
647            }
648            Err(e) => {
649                if matches!(
650                    serialports.get(&path).map(|i| &i.state),
651                    Some(PortState::Opening)
652                ) {
653                    serialports.remove(&path);
654                }
655                Err(e)
656            }
657        }
658    }
659
660    /// Stream port events into `sink` (one watch per port). Returns the id for
661    /// [`Self::unwatch`]. `sink` runs on the port's RX thread, keep it short; the last
662    /// events (parser remainder on unwatch / close) may run on the caller's thread. It
663    /// never runs under a manager lock, so it may call back into the manager.
664    pub fn watch(
665        &self,
666        path: String,
667        options: WatchOptions,
668        sink: EventSink,
669    ) -> Result<u32, Error> {
670        self.watch_framed(path, options, None, sink)
671    }
672
673    /// [`Self::watch`] under a caller-chosen id (the plugin uses its IPC channel id).
674    pub fn watch_with_id(
675        &self,
676        channel_id: u32,
677        path: String,
678        options: WatchOptions,
679        sink: EventSink,
680    ) -> Result<u32, Error> {
681        self.watch_framed_with_id(channel_id, path, options, None, sink)
682    }
683
684    /// [`Self::watch`] with a native parser: each complete frame becomes exactly one
685    /// [`SerialEvent::Data`](crate::events::SerialEvent::Data) (the batch timer no longer
686    /// applies). An invalid config fails before the watch starts. With
687    /// [`WatchOptions::route_urc`] the URC split runs first and only non-URC lines reach
688    /// the parser. On unwatch, close or disconnect the parser's buffered remainder is
689    /// sent as a final `data` event (before `disconnect`), like Node serialport emits
690    /// on stream end.
691    pub fn watch_framed(
692        &self,
693        path: String,
694        options: WatchOptions,
695        parser: Option<serial_codec::framing::FramerConfig>,
696        sink: EventSink,
697    ) -> Result<u32, Error> {
698        self.watch_framed_with_id(
699            next_watch_id(crate::port::watch_registry::contains),
700            path,
701            options,
702            parser,
703            sink,
704        )
705    }
706
707    /// [`Self::watch_framed`] under a caller-chosen id.
708    pub fn watch_framed_with_id(
709        &self,
710        channel_id: u32,
711        path: String,
712        options: WatchOptions,
713        parser: Option<serial_codec::framing::FramerConfig>,
714        channel: EventSink,
715    ) -> Result<u32, Error> {
716        // Validate the parser before anything is registered or attached.
717        let mut framer = parser
718            .as_ref()
719            .map(|p| p.build())
720            .transpose()
721            .map_err(|e| Error::String(e.to_string()))?;
722        crate::port::watch_registry::register(channel_id, path.clone())?;
723        log_debug!("Starting watch on port: {} (channel {})", path, channel_id);
724
725        let batch_timeout = options
726            .serial_data_flush_interval_ms
727            .or(options.timeout)
728            .unwrap_or(DEFAULT_WATCH_FLUSH_MS);
729        let read_size = options.size.unwrap_or(1024);
730        let route_urc = options.route_urc;
731
732        if let Ok(virtuals) = self.virtual_ports.lock() {
733            if let Some(vp) = virtuals.get(&path).cloned() {
734                drop(virtuals);
735                let session = {
736                    let cp = self.resolve_connected_port(&vp.physical_path)?;
737                    let mux = cp
738                        .mux
739                        .lock()
740                        .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?
741                        .clone()
742                        .ok_or_else(|| Error::String("CMUX not enabled".into()))?;
743                    mux
744                };
745                ensure_rx_hub_on_physical(self, &vp.physical_path)?;
746                session.set_watch_with(vp.dlci, channel, batch_timeout, framer);
747                return Ok(channel_id);
748            }
749        }
750
751        // A replaced watch's remainder is queued under the locks, delivered after.
752        let mut replaced = None;
753        let attached = self.with_connected_port(path.clone(), |cp| {
754            if cp.virtual_dlci.is_some() {
755                return Err(Error::String("legacy virtual ConnectedPort".into()));
756            }
757            if let Some(shared) = cp
758                .rx_hub
759                .lock()
760                .ok()
761                .and_then(|g| g.as_ref().map(|h| h.shared()))
762                .filter(|s| s.has_watch())
763            {
764                shared.detach_watch_queued();
765                replaced = Some(shared);
766            }
767            ensure_rx_hub(&cp.handle(), &path)?;
768            let guard = cp
769                .rx_hub
770                .lock()
771                .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?;
772            let hub = guard
773                .as_ref()
774                .ok_or_else(|| Error::String("RX hub missing after start".into()))?;
775            hub.attach_watch_with(channel, batch_timeout, read_size, route_urc, framer.take());
776            Ok(())
777        });
778        if let Some(shared) = replaced {
779            shared.deliver_queued();
780        }
781        if let Err(e) = attached {
782            crate::port::watch_registry::unregister(channel_id);
783            return Err(e);
784        }
785
786        Ok(channel_id)
787    }
788
789    pub fn unwatch(&self, channel_id: u32) -> Result<(), Error> {
790        let path = crate::port::watch_registry::unregister(channel_id)
791            .ok_or_else(|| Error::new(format!("No active watch for channel {}", channel_id)))?;
792        log_debug!("Stopping watch on port: {} (channel {})", path, channel_id);
793        self.stop_watch_thread(&path)
794    }
795
796    /// Detach the watch of `path`. The remainder goes to the sink after every lock
797    /// here is released, so a sink calling back into the manager cannot deadlock.
798    fn stop_watch_thread(&self, path: &str) -> Result<(), Error> {
799        let virtual_port = self
800            .virtual_ports
801            .lock()
802            .ok()
803            .and_then(|v| v.get(path).cloned());
804        if let Some(vp) = virtual_port {
805            if let Ok(cp) = self.resolve_connected_port(&vp.physical_path) {
806                let session = crate::sync_util::lock_or_recover(&cp.mux).clone();
807                if let Some(session) = session {
808                    session.clear_watch(vp.dlci);
809                }
810            }
811            return Ok(());
812        }
813        enum Detach {
814            Mux(Arc<CmuxSession>, u8),
815            Hub(Arc<crate::hub::RxHubShared>),
816            Nothing,
817        }
818        let detach = self.with_connected_port(path.to_string(), |cp| {
819            if let Some(dlci) = cp.virtual_dlci {
820                let session = crate::sync_util::lock_or_recover(&cp.mux).clone();
821                return Ok(session.map_or(Detach::Nothing, |s| Detach::Mux(s, dlci)));
822            }
823            let shared = cp
824                .rx_hub
825                .lock()
826                .ok()
827                .and_then(|g| g.as_ref().map(|h| h.shared()));
828            Ok(shared.map_or(Detach::Nothing, Detach::Hub))
829        })?;
830        match detach {
831            Detach::Mux(session, dlci) => session.clear_watch(dlci),
832            Detach::Hub(shared) => shared.detach_watch(),
833            Detach::Nothing => {}
834        }
835        Ok(())
836    }
837
838    pub fn read(
839        &self,
840        path: String,
841        timeout: Option<u64>,
842        size: Option<usize>,
843    ) -> Result<String, Error> {
844        let bytes = self.read_via_hub(path, timeout, size, false)?;
845        Ok(String::from_utf8_lossy(&bytes).to_string())
846    }
847
848    pub fn read_binary(
849        &self,
850        path: String,
851        timeout: Option<u64>,
852        size: Option<usize>,
853    ) -> Result<Vec<u8>, Error> {
854        self.read_via_hub(path, timeout, size, true)
855    }
856
857    fn read_via_hub(
858        &self,
859        path: String,
860        timeout: Option<u64>,
861        size: Option<usize>,
862        fill: bool,
863    ) -> Result<Vec<u8>, Error> {
864        let cp = self.resolve_connected_port(&path)?;
865        ensure_rx_hub_running(&cp, &path)?;
866        let hub_shared = {
867            let guard = cp
868                .rx_hub
869                .lock()
870                .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?;
871            guard
872                .as_ref()
873                .ok_or_else(|| Error::String("RX hub missing".into()))?
874                .shared()
875        };
876        hub_shared
877            .read_request(size.unwrap_or(1024), timeout.unwrap_or(1000), fill)
878            .map_err(Error::String)
879    }
880
881    /// Write data to the serial port
882    pub fn write(&self, path: String, value: String) -> Result<usize, Error> {
883        self.get_serialport(path.clone(), |port| {
884            write_all_port(port, value.as_bytes(), "write data")
885        })
886    }
887
888    /// Write binary data to the serial port
889    pub fn write_binary(&self, path: String, value: Vec<u8>) -> Result<usize, Error> {
890        self.get_serialport(path.clone(), |port| {
891            write_all_port(port, &value, "write binary data")
892        })
893    }
894
895    /// Set the baud rate
896    pub fn set_baud_rate(&self, path: String, baud_rate: u32) -> Result<(), Error> {
897        self.get_serialport(path, |port| {
898            port.set_baud_rate(baud_rate)
899                .map_err(|e| Error::String(format!("Failed to set baud rate: {}", e)))
900        })
901    }
902
903    /// Set the data bits
904    pub fn set_data_bits(&self, path: String, data_bits: DataBits) -> Result<(), Error> {
905        self.get_serialport(path, |port| {
906            port.set_data_bits(data_bits.into()).map_err(Error::from)
907        })
908    }
909
910    /// Set the flow control
911    pub fn set_flow_control(&self, path: String, flow_control: FlowControl) -> Result<(), Error> {
912        self.get_serialport(path, |port| {
913            port.set_flow_control(flow_control.into())
914                .map_err(Error::from)
915        })
916    }
917
918    /// Set the parity
919    pub fn set_parity(&self, path: String, parity: Parity) -> Result<(), Error> {
920        self.get_serialport(path, |port| {
921            port.set_parity(parity.into()).map_err(Error::from)
922        })
923    }
924
925    /// Set the stop bits
926    pub fn set_stop_bits(&self, path: String, stop_bits: StopBits) -> Result<(), Error> {
927        self.get_serialport(path, |port| {
928            port.set_stop_bits(stop_bits.into()).map_err(Error::from)
929        })
930    }
931
932    /// Set the timeout
933    pub fn set_timeout(&self, path: String, timeout: Duration) -> Result<(), Error> {
934        self.get_serialport(path, |port| port.set_timeout(timeout).map_err(Error::from))
935    }
936
937    /// Set the RTS (Request To Send) control signal
938    pub fn write_request_to_send(&self, path: String, level: bool) -> Result<(), Error> {
939        self.get_serialport(path, |port| {
940            port.write_request_to_send(level).map_err(Error::from)
941        })
942    }
943
944    /// Set the DTR (Data Terminal Ready) control signal
945    pub fn write_data_terminal_ready(&self, path: String, level: bool) -> Result<(), Error> {
946        self.get_serialport(path, |port| {
947            port.write_data_terminal_ready(level).map_err(Error::from)
948        })
949    }
950
951    /// Read the CTS (Clear To Send) control signal state
952    pub fn read_clear_to_send(&self, path: String) -> Result<bool, Error> {
953        self.get_serialport(path, |port| port.read_clear_to_send().map_err(Error::from))
954    }
955
956    /// Read the DSR (Data Set Ready) control signal state
957    pub fn read_data_set_ready(&self, path: String) -> Result<bool, Error> {
958        self.get_serialport(path, |port| port.read_data_set_ready().map_err(Error::from))
959    }
960
961    /// Read the RI (Ring Indicator) control signal state
962    pub fn read_ring_indicator(&self, path: String) -> Result<bool, Error> {
963        self.get_serialport(path, |port| port.read_ring_indicator().map_err(Error::from))
964    }
965
966    /// Read the CD (Carrier Detect) control signal state
967    pub fn read_carrier_detect(&self, path: String) -> Result<bool, Error> {
968        self.get_serialport(path, |port| port.read_carrier_detect().map_err(Error::from))
969    }
970
971    /// Get the number of bytes available to read
972    pub fn bytes_to_read(&self, path: String) -> Result<u32, Error> {
973        let hub_buffered = if let Ok(cp) = self.resolve_connected_port(&path) {
974            cp.rx_hub
975                .lock()
976                .ok()
977                .and_then(|guard| guard.as_ref().map(|hub| hub.shared().buffered_len() as u32))
978                .unwrap_or(0)
979        } else {
980            0
981        };
982        let port_buffered = if let Ok(cp) = self.resolve_connected_port(&path) {
983            cp.port
984                .try_lock()
985                .ok()
986                .and_then(|port| port.bytes_to_read().ok())
987                .unwrap_or(0)
988        } else {
989            0
990        };
991        Ok(hub_buffered.saturating_add(port_buffered))
992    }
993
994    /// Get the number of bytes waiting to be written
995    pub fn bytes_to_write(&self, path: String) -> Result<u32, Error> {
996        self.get_serialport(path, |port| port.bytes_to_write().map_err(Error::from))
997    }
998
999    /// Clear input/output buffers
1000    pub fn clear_buffer(&self, path: String, buffer_to_clear: ClearBuffer) -> Result<(), Error> {
1001        self.get_serialport(path, |port| {
1002            port.clear(buffer_to_clear.into()).map_err(Error::from)
1003        })
1004    }
1005
1006    /// Start break signal transmission
1007    pub fn set_break(&self, path: String) -> Result<(), Error> {
1008        self.get_serialport(path, |port| port.set_break().map_err(Error::from))
1009    }
1010
1011    /// Stop break signal transmission
1012    pub fn clear_break(&self, path: String) -> Result<(), Error> {
1013        self.get_serialport(path, |port| port.clear_break().map_err(Error::from))
1014    }
1015
1016    /// Write payload and read until terminators, idle silence, or timeout (AT-style exchange).
1017    pub fn exchange(
1018        &self,
1019        path: String,
1020        value: String,
1021        options: ExchangeOptions,
1022    ) -> Result<crate::at::parse::ExchangeResponse, Error> {
1023        self.exchange_bytes(path, value.into_bytes(), options)
1024    }
1025
1026    /// Binary variant of [`Self::exchange`].
1027    pub fn exchange_binary(
1028        &self,
1029        path: String,
1030        value: Vec<u8>,
1031        options: ExchangeOptions,
1032    ) -> Result<crate::at::parse::ExchangeResponse, Error> {
1033        self.exchange_bytes(path, value, options)
1034    }
1035
1036    fn get_tx_queue(&self, path: &str) -> Result<Arc<PortTxQueue>, Error> {
1037        if let Ok(virtuals) = self.virtual_ports.lock() {
1038            if let Some(vp) = virtuals.get(path) {
1039                return Ok(vp.tx_queue.clone());
1040            }
1041        }
1042        let ports = self
1043            .serialports
1044            .lock()
1045            .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?;
1046        let info = ports
1047            .get(path)
1048            .ok_or_else(|| Error::String(format!("Port '{}' not found", path)))?;
1049        match &info.state {
1050            PortState::Connected(cp) => Ok(cp.tx_queue.clone()),
1051            other => Err(Error::String(other.not_connected_reason())),
1052        }
1053    }
1054
1055    fn exchange_bytes(
1056        &self,
1057        path: String,
1058        payload: Vec<u8>,
1059        options: ExchangeOptions,
1060    ) -> Result<crate::at::parse::ExchangeResponse, Error> {
1061        run_exchange_queued(
1062            path,
1063            options,
1064            |p| self.get_tx_queue(p),
1065            |physical_path,
1066             dlci,
1067             virtual_path,
1068             payload,
1069             options|
1070             -> Result<crate::at::parse::ExchangeResponse, Error> {
1071                self.exchange_bytes_mux_direct(physical_path, dlci, virtual_path, payload, options)
1072            },
1073            |path, payload, options| -> Result<crate::at::parse::ExchangeResponse, Error> {
1074                self.exchange_bytes_direct(path, payload, options)
1075            },
1076            payload,
1077        )
1078    }
1079
1080    fn exchange_bytes_direct(
1081        &self,
1082        path: String,
1083        payload: Vec<u8>,
1084        options: ExchangeOptions,
1085    ) -> Result<crate::at::parse::ExchangeResponse, Error> {
1086        let command = options
1087            .command
1088            .clone()
1089            .unwrap_or_else(|| String::from_utf8_lossy(&payload).into_owned());
1090        let user_solicited = options.solicited_prefixes.clone().unwrap_or_default();
1091        let resolved_timeout = options.resolve().timeout_ms;
1092
1093        let cp = self.resolve_connected_port(&path)?;
1094        ensure_rx_hub(&cp, &path)?;
1095
1096        struct DesktopExchangeIo<'a> {
1097            port: &'a Arc<Mutex<Box<dyn serialport::SerialPort>>>,
1098            timeout_ms: u64,
1099        }
1100        impl crate::exchange::io::ExchangeIo for DesktopExchangeIo<'_> {
1101            fn purge_rx(&self) -> Result<(), Error> {
1102                with_port_try_lock(
1103                    self.port,
1104                    Duration::from_millis(self.timeout_ms.min(5000)),
1105                    |port| port.clear(ClearBuffer::Input.into()).map_err(Error::from),
1106                )
1107            }
1108            fn write_payload(&self, payload: &[u8]) -> Result<(), Error> {
1109                with_port_try_lock(
1110                    self.port,
1111                    Duration::from_millis(self.timeout_ms.min(5000)),
1112                    |port| write_all_port(port, payload, "exchange write").map(|_| ()),
1113                )
1114            }
1115        }
1116
1117        let hub = {
1118            let guard = crate::sync_util::lock_or_recover(&cp.rx_hub);
1119            guard
1120                .as_ref()
1121                .ok_or_else(|| Error::String("RX hub missing".into()))?
1122                .clone()
1123        };
1124
1125        crate::exchange::run::run_physical_exchange(
1126            hub.as_ref(),
1127            &DesktopExchangeIo {
1128                port: &cp.port,
1129                timeout_ms: resolved_timeout,
1130            },
1131            &command,
1132            &user_solicited,
1133            payload,
1134            options,
1135            cp.exchange_cancel.clone(),
1136        )
1137    }
1138
1139    fn exchange_bytes_mux_direct(
1140        &self,
1141        physical_path: String,
1142        _dlci: u8,
1143        virtual_path: String,
1144        payload: Vec<u8>,
1145        options: ExchangeOptions,
1146    ) -> Result<crate::at::parse::ExchangeResponse, Error> {
1147        let vp = self
1148            .virtual_ports
1149            .lock()
1150            .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?
1151            .get(&virtual_path)
1152            .cloned()
1153            .ok_or_else(|| Error::String(format!("Virtual port '{}' not open", virtual_path)))?;
1154        self.exchange_bytes_mux_via_ref(physical_path, &vp, payload, options)
1155    }
1156
1157    fn exchange_bytes_mux_via_ref(
1158        &self,
1159        physical_path: String,
1160        vp: &crate::state::VirtualPortRef,
1161        payload: Vec<u8>,
1162        options: ExchangeOptions,
1163    ) -> Result<crate::at::parse::ExchangeResponse, Error> {
1164        let dlci = vp.dlci;
1165        let command = options
1166            .command
1167            .clone()
1168            .unwrap_or_else(|| String::from_utf8_lossy(&payload).into_owned());
1169        let user_solicited = options.solicited_prefixes.clone().unwrap_or_default();
1170
1171        let session = {
1172            let ports = self
1173                .serialports
1174                .lock()
1175                .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?;
1176            let info = ports.get(&physical_path).ok_or_else(|| {
1177                Error::String(format!("Physical port '{}' not found", physical_path))
1178            })?;
1179            match &info.state {
1180                PortState::Connected(cp) => cp
1181                    .mux
1182                    .lock()
1183                    .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?
1184                    .clone()
1185                    .ok_or_else(|| Error::String("CMUX not enabled on physical port".into()))?,
1186                other => return Err(Error::String(other.not_connected_reason())),
1187            }
1188        };
1189
1190        ensure_rx_hub_on_physical(self, &physical_path)?;
1191
1192        crate::exchange::run::run_mux_exchange(
1193            &session,
1194            dlci,
1195            &command,
1196            &user_solicited,
1197            payload,
1198            options,
1199            vp.exchange_cancel.clone(),
1200        )
1201    }
1202
1203    fn run_exchange_unqueued(
1204        &self,
1205        path: String,
1206        payload: Vec<u8>,
1207        options: ExchangeOptions,
1208    ) -> Result<crate::at::parse::ExchangeResponse, Error> {
1209        if let Some((physical, dlci)) = parse_mux_path(path.as_str()) {
1210            return self.exchange_bytes_mux_direct(
1211                physical.to_string(),
1212                dlci,
1213                path,
1214                payload,
1215                options,
1216            );
1217        }
1218        self.exchange_bytes_direct(path, payload, options)
1219    }
1220
1221    pub fn at(
1222        &self,
1223        path: String,
1224        command: String,
1225        options: Option<AtCommandOptions>,
1226    ) -> Result<crate::at::parse::AtCommandResult, Error> {
1227        let tx_queue = self.get_tx_queue(&path)?;
1228        crate::at::commands::queue_at(self, &tx_queue, path, command, options)
1229    }
1230
1231    /// Multi-phase AT flow (e.g. CMGS) — phases run atomically without interleaving other jobs.
1232    pub fn at_phases(
1233        &self,
1234        path: String,
1235        phases: Vec<AtPhase>,
1236    ) -> Result<Vec<crate::at::parse::AtCommandResult>, Error> {
1237        let tx_queue = self.get_tx_queue(&path)?;
1238        crate::at::commands::queue_at_phases(self, &tx_queue, path, phases)
1239    }
1240
1241    /// Built-in CMGS recipe: `AT+CMGS=n` → `>` → PDU + Ctrl+Z → final line.
1242    pub fn send_sms_pdu(
1243        &self,
1244        path: String,
1245        length: u32,
1246        pdu: Vec<u8>,
1247        options: Option<SendSmsPduOptions>,
1248    ) -> Result<Vec<crate::at::parse::AtCommandResult>, Error> {
1249        let tx_queue = self.get_tx_queue(&path)?;
1250        crate::at::commands::queue_send_sms_pdu(self, &tx_queue, path, length, pdu, options)
1251    }
1252
1253    /// Configure AT session defaults for native `at` jobs on this port.
1254    pub fn configure_at_session(
1255        &self,
1256        path: String,
1257        session: AtSessionConfig,
1258    ) -> Result<(), Error> {
1259        let tx_queue = self
1260            .resolve_connected_port(&path)
1261            .map(|cp| cp.tx_queue.clone())
1262            .ok();
1263        configure_at_session_shared(&self.virtual_ports, tx_queue, &path, session)
1264    }
1265
1266    /// Enter GSM 07.10 CMUX mode (`AT+CMUX=…` then attach deframer to the RX hub).
1267    pub fn enable_mux(&self, path: String, command: String, timeout_ms: u64) -> Result<(), Error> {
1268        let response = self.exchange(
1269            path.clone(),
1270            format!("{command}\r"),
1271            ExchangeOptions {
1272                timeout_ms: Some(timeout_ms),
1273                rx_prepare: Some(crate::events::RxPrepareMode::None),
1274                ..Default::default()
1275            },
1276        )?;
1277        if response.status != crate::at::parse::AtParseStatus::Ok {
1278            return Err(Error::String(format!(
1279                "modem rejected {command}: {}",
1280                String::from_utf8_lossy(&response.raw).trim()
1281            )));
1282        }
1283
1284        let cp = self.resolve_connected_port(&path)?;
1285        if cp.virtual_dlci.is_some() {
1286            return Err(Error::String("enable_mux on virtual port".into()));
1287        }
1288        if crate::sync_util::lock_or_recover(&cp.mux).is_some() {
1289            return Err(Error::String("CMUX already enabled".into()));
1290        }
1291        cp.port
1292            .lock()
1293            .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?
1294            .clear(ClearBuffer::Input.into())
1295            .map_err(Error::from)?;
1296        let session = CmuxSession::with_n1(
1297            path.clone(),
1298            Arc::new(crate::cmux::SerialPortIo(cp.port.clone())),
1299            crate::cmux::cmux_n1(&command),
1300        );
1301        ensure_rx_hub(&cp, &path)?;
1302        if let Some(hub) = crate::sync_util::lock_or_recover(&cp.rx_hub).as_ref() {
1303            hub.attach_cmux(session.clone());
1304        }
1305        // Control channel first; without its UA the modem is not multiplexing.
1306        if let Err(e) = session.open_dlci(0, Duration::from_millis(timeout_ms.max(500))) {
1307            if let Some(hub) = crate::sync_util::lock_or_recover(&cp.rx_hub).as_ref() {
1308                hub.detach_cmux();
1309            }
1310            return Err(Error::String(e));
1311        }
1312        *crate::sync_util::lock_or_recover(&cp.mux) = Some(session);
1313        Ok(())
1314    }
1315
1316    /// Register a virtual DLCI channel on an CMUX-enabled physical port.
1317    pub fn open_mux_channel(&self, physical_path: String, dlci: u8) -> Result<String, Error> {
1318        if !crate::cmux::is_data_dlci(dlci) {
1319            return Err(Error::String(format!(
1320                "invalid CMUX DLCI {dlci}: data channels are 1..=63"
1321            )));
1322        }
1323        let virtual_path = mux_path(&physical_path, dlci);
1324        let session = {
1325            let ports = self
1326                .serialports
1327                .lock()
1328                .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?;
1329            let info = ports
1330                .get(&physical_path)
1331                .ok_or_else(|| Error::String(format!("Port '{}' not found", physical_path)))?;
1332            match &info.state {
1333                PortState::Connected(cp) => cp
1334                    .mux
1335                    .lock()
1336                    .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?
1337                    .clone()
1338                    .ok_or_else(|| Error::String("CMUX not enabled".into())),
1339                other => Err(Error::String(other.not_connected_reason())),
1340            }
1341        }?;
1342
1343        // Already open on *this* session. An entry left from an earlier session (port
1344        // closed and re-opened) is stale and gets replaced below.
1345        let known = self
1346            .virtual_ports
1347            .lock()
1348            .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?
1349            .contains_key(&virtual_path);
1350        if known && session.has_dlci(dlci) {
1351            return Ok(virtual_path);
1352        }
1353
1354        session.register_dlci(dlci, virtual_path.clone());
1355        if let Err(e) = session.open_dlci(dlci, Duration::from_secs(3)) {
1356            session.unregister_dlci(dlci);
1357            return Err(Error::String(e));
1358        }
1359        self.virtual_ports
1360            .lock()
1361            .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?
1362            .insert(virtual_path.clone(), {
1363                let tx_queue = Arc::new(PortTxQueue::new());
1364                crate::state::VirtualPortRef {
1365                    physical_path,
1366                    dlci,
1367                    exchange_cancel: tx_queue.cancel_flag(),
1368                    tx_queue,
1369                }
1370            });
1371        Ok(virtual_path)
1372    }
1373
1374    /// Tear down CMUX: close virtual channels and detach deframer.
1375    pub fn disable_mux(&self, path: String) -> Result<(), Error> {
1376        self.close_virtual_channels_of(&path);
1377        self.with_connected_port(path.clone(), |cp| {
1378            if let Some(session) = crate::sync_util::lock_or_recover(&cp.mux).take() {
1379                session.close_down();
1380            }
1381            if let Some(hub) = crate::sync_util::lock_or_recover(&cp.rx_hub).as_ref() {
1382                hub.detach_cmux();
1383            }
1384            Ok(())
1385        })
1386    }
1387
1388    /// Close every CMUX virtual channel that rides on `physical`.
1389    fn close_virtual_channels_of(&self, physical: &str) {
1390        let virtual_paths: Vec<String> = crate::sync_util::lock_or_recover(&self.virtual_ports)
1391            .iter()
1392            .filter(|(_, vp)| vp.physical_path == physical)
1393            .map(|(p, _)| p.clone())
1394            .collect();
1395        for vp in virtual_paths {
1396            let _ = self.close(vp);
1397        }
1398    }
1399
1400    /// Cancel an in-flight exchange and reject queued waiters on `path`.
1401    pub fn cancel_exchange(&self, path: String) -> Result<(), Error> {
1402        if let Ok(virtuals) = self.virtual_ports.lock() {
1403            if let Some(vp) = virtuals.get(&path).cloned() {
1404                drop(virtuals);
1405                let session = {
1406                    let ports = self
1407                        .serialports
1408                        .lock()
1409                        .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?;
1410                    let info = ports.get(&vp.physical_path).ok_or_else(|| {
1411                        Error::String(format!("Physical port '{}' not found", vp.physical_path))
1412                    })?;
1413                    match &info.state {
1414                        PortState::Connected(cp) => cp
1415                            .mux
1416                            .lock()
1417                            .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?
1418                            .clone(),
1419                        other => return Err(Error::String(other.not_connected_reason())),
1420                    }
1421                };
1422                if let Some(session) = session {
1423                    crate::exchange::cancel::cancel_virtual_exchange(
1424                        &vp.exchange_cancel,
1425                        &vp.tx_queue,
1426                        &session,
1427                        vp.dlci,
1428                    );
1429                } else {
1430                    vp.exchange_cancel.store(true, Ordering::SeqCst);
1431                    vp.tx_queue.cancel_all();
1432                }
1433                return Ok(());
1434            }
1435        }
1436        let cp = self.resolve_connected_port(&path)?;
1437        crate::exchange::cancel::cancel_physical_exchange(
1438            &cp.exchange_cancel,
1439            &cp.tx_queue,
1440            || {
1441                if let Ok(guard) = cp.rx_hub.lock() {
1442                    if let Some(hub) = guard.as_ref() {
1443                        hub.cancel_active_exchange();
1444                    }
1445                }
1446            },
1447        );
1448        Ok(())
1449    }
1450
1451    /// Resolve a connected port's shared handles (brief global lock only).
1452    fn resolve_connected_port(&self, path: &str) -> Result<ConnectedPortHandle, Error> {
1453        let ports = self
1454            .serialports
1455            .lock()
1456            .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?;
1457        let info = ports
1458            .get(path)
1459            .ok_or_else(|| Error::String(format!("Port '{}' not found", path)))?;
1460        match &info.state {
1461            PortState::Connected(cp) => Ok(cp.handle()),
1462            other => Err(Error::String(other.not_connected_reason())),
1463        }
1464    }
1465
1466    /// Run `f` only when the port is [`PortState::Connected`] (holds global lock for `f`).
1467    fn with_connected_port<T, F>(&self, path: String, f: F) -> Result<T, Error>
1468    where
1469        F: FnOnce(&mut ConnectedPort) -> Result<T, Error>,
1470    {
1471        let mut ports = self
1472            .serialports
1473            .lock()
1474            .map_err(|e| Error::String(format!("Mutex lock failed: {}", e)))?;
1475
1476        let info = ports
1477            .get_mut(&path)
1478            .ok_or_else(|| Error::String(format!("Port '{}' not found", path)))?;
1479
1480        match &mut info.state {
1481            PortState::Connected(cp) => f(cp),
1482            other => Err(Error::String(other.not_connected_reason())),
1483        }
1484    }
1485
1486    fn get_serialport<T, F>(&self, path: String, f: F) -> Result<T, Error>
1487    where
1488        F: FnOnce(&mut Box<dyn serialport::SerialPort>) -> Result<T, Error>,
1489    {
1490        let cp = self.resolve_connected_port(&path)?;
1491        with_port_try_lock(&cp.port, Duration::from_millis(PORT_LOCK_TIMEOUT_MS), f)
1492    }
1493}
1494
1495impl crate::at::commands::ExchangeRunner for SerialManager {
1496    fn run_exchange_unqueued(
1497        &self,
1498        path: String,
1499        payload: Vec<u8>,
1500        options: ExchangeOptions,
1501    ) -> Result<crate::at::parse::ExchangeResponse, Error> {
1502        SerialManager::run_exchange_unqueued(self, path, payload, options)
1503    }
1504}