Skip to main content

serialplugin_core/cmux/
session.rs

1//! CMUX session: deframe physical RX, route per DLCI, encode TX.
2
3use crate::cmux::frame::{
4    encode_frame, encode_uih, DecodedFrame, Deframer, DISC, DM, PF, SABM, UA, UI, UIH,
5};
6use crate::cmux::io::CmuxPhysicalIo;
7use crate::events::SerialEvent;
8use crate::hub::shared::{Outbox, PORT_CLOSED};
9use crate::hub::stream::{EventStream, Target, WatchOwner};
10use crate::hub::ExchangeWaiter;
11use serial_codec::framing::Framer;
12use std::collections::{HashMap, HashSet};
13use std::sync::atomic::{AtomicBool, Ordering};
14use std::sync::mpsc;
15use std::sync::{Arc, Condvar, Mutex, OnceLock};
16use std::time::{Duration, Instant};
17
18/// Per-DLCI routing state (virtual channel).
19pub struct DlciChannel {
20    pub path: String,
21    pub exchange_waiter: Mutex<Option<Arc<ExchangeWaiter>>>,
22    watches: Mutex<DlciWatches>,
23    /// Being closed by the app: exchanges and writes fail at once.
24    closing: AtomicBool,
25    /// The session's outbox: events are queued under `watches`, in production order,
26    /// and delivered by the session once no lock is held.
27    outbox: Arc<Outbox>,
28}
29
30/// The old watch (at most one) and the `watch_core` streams of one channel.
31#[derive(Default)]
32struct DlciWatches {
33    old: Option<DlciWatchSlot>,
34    core: Vec<(u64, DlciWatchSlot)>,
35}
36
37impl DlciWatches {
38    /// The watches whose sink is not gone; the old one is returned if its is (drop it with
39    /// no lock held).
40    fn each(&mut self, mut f: impl FnMut(&mut DlciWatchSlot)) -> Option<DlciWatchSlot> {
41        self.core.retain(|(_, w)| !w.target.gone());
42        self.core.iter_mut().for_each(|(_, w)| f(w));
43        match self.old.as_mut() {
44            Some(old) if !old.target.gone() => {
45                f(old);
46                None
47            }
48            _ => self.old.take(),
49        }
50    }
51}
52
53struct DlciWatchSlot {
54    target: Target,
55    batch_timeout_ms: u64,
56    flush_at: Instant,
57    /// Native parser: each frame is one `Data` event, no batching.
58    framer: Option<Box<dyn Framer>>,
59    buffer: Vec<u8>,
60}
61
62impl DlciWatchSlot {
63    fn new(target: Target, batch_timeout_ms: u64, framer: Option<Box<dyn Framer>>) -> Self {
64        Self {
65            target,
66            batch_timeout_ms,
67            flush_at: Instant::now(),
68            framer,
69            buffer: Vec::new(),
70        }
71    }
72
73    fn take_due(&mut self) -> bool {
74        if self.flush_at.elapsed() >= Duration::from_millis(self.batch_timeout_ms) {
75            self.flush_at = Instant::now();
76            true
77        } else {
78            false
79        }
80    }
81
82    /// Frames ready after `payload` (parser), or the batch once its timer is due.
83    fn push(&mut self, payload: &[u8]) -> Vec<Vec<u8>> {
84        let mut frames = Vec::new();
85        if let Some(f) = self.framer.as_mut() {
86            f.push(payload, Instant::now(), &mut frames);
87            return frames;
88        }
89        self.buffer.extend_from_slice(payload);
90        if self.take_due() {
91            frames.push(std::mem::take(&mut self.buffer));
92        }
93        frames
94    }
95
96    /// Time-based frames, or a batch whose timeout elapsed with no new data.
97    fn poll(&mut self) -> Vec<Vec<u8>> {
98        let mut frames = Vec::new();
99        if let Some(f) = self.framer.as_mut() {
100            f.poll(Instant::now(), &mut frames);
101        } else if self.take_due() && !self.buffer.is_empty() {
102            frames.push(std::mem::take(&mut self.buffer));
103        }
104        frames
105    }
106
107    /// End of stream: the batch, then the parser remainder.
108    fn finish(&mut self) -> Vec<Vec<u8>> {
109        let batch = std::mem::take(&mut self.buffer);
110        let rest = self.framer.as_mut().and_then(|f| f.flush());
111        [batch, rest.unwrap_or_default()]
112            .into_iter()
113            .filter(|d| !d.is_empty())
114            .collect()
115    }
116}
117
118impl DlciChannel {
119    fn new(path: String, outbox: Arc<Outbox>) -> Self {
120        Self {
121            path,
122            exchange_waiter: Mutex::new(None),
123            watches: Mutex::new(DlciWatches::default()),
124            closing: AtomicBool::new(false),
125            outbox,
126        }
127    }
128
129    /// 4.0.0 API (feature `tauri`): [`Self::attach_watch_with`] for a Tauri channel, no parser.
130    #[cfg(feature = "tauri")]
131    pub fn attach_watch(&self, channel: tauri::ipc::Channel<SerialEvent>, batch_timeout_ms: u64) {
132        self.attach_watch_with(crate::events::channel_sink(channel), batch_timeout_ms, None);
133    }
134
135    pub fn attach_watch_with(
136        &self,
137        channel: crate::events::EventSink,
138        batch_timeout_ms: u64,
139        framer: Option<Box<dyn Framer>>,
140    ) {
141        self.attach_stream(channel, batch_timeout_ms, framer);
142    }
143
144    /// [`Self::attach_watch_with`]; the stream is the watch's identity. A watch it replaces
145    /// ends with its tail queued.
146    fn attach_stream(
147        &self,
148        channel: crate::events::EventSink,
149        batch_timeout_ms: u64,
150        framer: Option<Box<dyn Framer>>,
151    ) -> Arc<EventStream> {
152        let stream = self.outbox.stream(channel);
153        let slot = DlciWatchSlot::new(Target::Old(stream.clone()), batch_timeout_ms, framer);
154        let mut guard = crate::sync_util::lock_or_recover(&self.watches);
155        let mut replaced = guard.old.replace(slot);
156        if let Some(old) = replaced.as_mut() {
157            self.end_slot(old, None);
158        }
159        // Unlocked before the replaced watch's sink is dropped.
160        drop(guard);
161        stream
162    }
163
164    /// Take the old watch (if `which` accepts it); its tail is queued.
165    fn take_watch(&self, which: impl Fn(&DlciWatchSlot) -> bool) -> Option<DlciWatchSlot> {
166        let mut guard = crate::sync_util::lock_or_recover(&self.watches);
167        if !guard.old.as_ref().is_some_and(which) {
168            return None;
169        }
170        let mut slot = guard.old.take();
171        if let Some(slot) = slot.as_mut() {
172            self.end_slot(slot, None);
173        }
174        slot
175    }
176
177    /// Stop the watch; its batch and its parser's remainder are queued as the last `Data`
178    /// (after the frames already queued). The session delivers them on its next RX, tick
179    /// or [`CmuxSession::clear_watch`] (which calls this and delivers).
180    pub fn detach_watch(&self) {
181        self.take_watch(|_| true);
182    }
183
184    fn attach_core_watch(&self, id: u64, slot: DlciWatchSlot) {
185        crate::sync_util::lock_or_recover(&self.watches)
186            .core
187            .push((id, slot));
188    }
189
190    /// Remove a `watch_core` stream; its batch and remainder are sent last.
191    fn detach_core_watch(&self, id: u64) -> bool {
192        let mut guard = crate::sync_util::lock_or_recover(&self.watches);
193        let Some(i) = guard.core.iter().position(|(c, _)| *c == id) else {
194            return false;
195        };
196        let (_, mut slot) = guard.core.remove(i);
197        self.end_slot(&mut slot, None);
198        drop(guard);
199        true
200    }
201
202    /// End every watch: its batch and parser remainder, then `last`.
203    fn end_watches(&self, last: Option<&SerialEvent>) {
204        let ended = {
205            let mut guard = crate::sync_util::lock_or_recover(&self.watches);
206            let mut watches = std::mem::take(&mut *guard);
207            let gone = watches.each(|slot| self.end_slot(slot, last));
208            (watches, gone)
209        };
210        // Unlocked: it drops the sinks.
211        drop(ended);
212    }
213
214    /// The slot's remainder, then `last`: nothing more is sent.
215    fn end_slot(&self, slot: &mut DlciWatchSlot, last: Option<&SerialEvent>) {
216        let mut events = self.data_events(slot.finish());
217        events.extend(last.cloned());
218        slot.target.end(&mut events);
219    }
220
221    /// Fail the exchange in flight.
222    fn fail_exchange(&self, reason: &str) {
223        if let Some(waiter) = crate::sync_util::lock_or_recover(&self.exchange_waiter).as_ref() {
224            waiter.fail_with_reason(reason.to_string());
225        }
226    }
227
228    fn is_closing(&self) -> bool {
229        self.closing.load(Ordering::SeqCst)
230    }
231
232    /// The app closes the channel: exchanges and writes on it fail from now on.
233    fn begin_close(&self) {
234        self.closing.store(true, Ordering::SeqCst);
235        self.fail_exchange(PORT_CLOSED);
236    }
237
238    fn set_exchange_waiter(&self, waiter: Arc<ExchangeWaiter>) {
239        *crate::sync_util::lock_or_recover(&self.exchange_waiter) = Some(waiter);
240        if self.is_closing() {
241            self.fail_exchange(PORT_CLOSED);
242        }
243    }
244
245    fn data_events(&self, frames: Vec<Vec<u8>>) -> Vec<SerialEvent> {
246        let event = |data: Vec<u8>| SerialEvent::Data {
247            path: self.path.clone(),
248            size: data.len(),
249            data,
250        };
251        frames.into_iter().map(event).collect()
252    }
253
254    /// Run `f` over the watches; its frames are sent under the `watches` lock, so the order
255    /// is the production order whatever thread sends next.
256    fn each_watch(&self, mut f: impl FnMut(&mut DlciWatchSlot) -> Vec<Vec<u8>>) {
257        let gone = crate::sync_util::lock_or_recover(&self.watches).each(|slot| {
258            let frames = f(slot);
259            slot.target.send(&mut self.data_events(frames));
260        });
261        drop(gone);
262    }
263
264    fn push_stream(&self, payload: &[u8]) {
265        self.each_watch(|slot| slot.push(payload));
266    }
267
268    /// Parser timers and batches whose timeout elapsed with no new frame.
269    fn tick(&self) {
270        self.each_watch(DlciWatchSlot::poll);
271    }
272}
273
274impl WatchOwner for DlciChannel {
275    fn stop(&self, stream: &Arc<EventStream>) {
276        // The slot (and with it the sink) is dropped with no lock held.
277        drop(self.take_watch(|slot| slot.target.is(stream)));
278        self.outbox.settle(stream);
279    }
280}
281
282/// Parameter `index` (0-based) of an `AT+CMUX=` command
283/// (27.007 +CMUX: mode, subset, port_speed, N1, T1, N2, T2, T3, k).
284fn cmux_param(command: &str, index: usize) -> Option<u64> {
285    let upper = command.to_ascii_uppercase();
286    let at = upper.find("+CMUX=")?;
287    upper[at + "+CMUX=".len()..]
288        .split(',')
289        .nth(index)?
290        .trim()
291        .parse()
292        .ok()
293}
294
295/// N1 (maximum info bytes per frame) from an `AT+CMUX=` command: the 4th parameter.
296/// 31 (the basic-option default) when absent or empty.
297pub fn cmux_n1(command: &str) -> usize {
298    cmux_param(command, 3).map_or(31, |n1| n1 as usize)
299}
300
301/// 27.010 link timers, from the `AT+CMUX=` parameters (see [`CmuxTimers::from_command`]).
302#[derive(Debug, Clone, Copy, PartialEq, Eq)]
303pub struct CmuxTimers {
304    /// T1, acknowledgement timer: how long to wait for UA before resending SABM.
305    pub t1: Duration,
306    /// N2, maximum number of retransmissions.
307    pub n2: u32,
308    /// T2, response timer for control-channel commands (CLD).
309    pub t2: Duration,
310}
311
312impl Default for CmuxTimers {
313    /// The 27.010 defaults: T1 100 ms, N2 3, T2 300 ms.
314    fn default() -> Self {
315        Self {
316            t1: Duration::from_millis(100),
317            n2: 3,
318            t2: Duration::from_millis(300),
319        }
320    }
321}
322
323impl CmuxTimers {
324    /// T1, N2 and T2 are the 5th–7th `+CMUX` parameters (T1/T2 in 10 ms units);
325    /// absent, empty or out of the 27.007 range (T1 1..=255, N2 0..=100, T2 2..=255):
326    /// the default. With neither T1 nor N2 in the command SABM is sent once (N2 = 0)
327    /// and its UA gets the whole open timeout, as in 4.x.
328    pub fn from_command(command: &str) -> Self {
329        let d = Self::default();
330        let tens = |i, min, default| {
331            cmux_param(command, i)
332                .filter(|v| (min..=255).contains(v))
333                .map_or(default, |v| Duration::from_millis(v * 10))
334        };
335        let retransmit = cmux_param(command, 4).is_some() || cmux_param(command, 5).is_some();
336        Self {
337            t1: tens(4, 1, d.t1),
338            n2: if retransmit {
339                cmux_param(command, 5)
340                    .filter(|v| *v <= 100)
341                    .map_or(d.n2, |v| v as u32)
342            } else {
343                0
344            },
345            t2: tens(6, 2, d.t2),
346        }
347    }
348}
349
350// Control-channel message type octets (27.010 §5.4.6.3), C/R and EA bits included.
351const CR: u8 = 0x02;
352const PN_CMD: u8 = 0x83;
353const PSC_CMD: u8 = 0x43;
354const TEST_CMD: u8 = 0x23;
355const MSC_CMD: u8 = 0xE3;
356const RPN_CMD: u8 = 0x93;
357const RLS_CMD: u8 = 0x53;
358const FCON_CMD: u8 = 0xA3;
359const FCOFF_CMD: u8 = 0x63;
360const CLD_CMD: u8 = 0xC3;
361const CLD_RSP: u8 = 0xC1;
362/// Non-supported command response (§5.4.6.3.8).
363const NSC_RSP: u8 = 0x11;
364/// Commands answered by echoing them with C/R cleared.
365const ECHOED: [u8; 9] = [
366    PN_CMD, PSC_CMD, TEST_CMD, MSC_CMD, RPN_CMD, RLS_CMD, FCON_CMD, FCOFF_CMD, CLD_CMD,
367];
368/// MSC V.24 signals we send: EA | RTC | RTR | DV.
369const V24_READY: u8 = 0x8D;
370/// MSC V.24 flow control bit: the sender of the MSC cannot accept frames on that DLC.
371const V24_FC: u8 = 0x02;
372
373/// Flow control from the modem: FCoff stops every DLC, MSC with FC=1 one DLC.
374/// Writes wait (on `CmuxSession::tx_cv`) until it ends or their write timeout.
375#[derive(Default)]
376struct TxGate {
377    fc_off: bool,
378    held_dlcis: HashSet<u8>,
379}
380
381/// The modem closed channels: their virtual paths, the reason, and whether it left
382/// multiplexer mode altogether (DISC / DM on DLCI 0, CLD).
383pub(crate) type ClosedHook = Box<dyn Fn(&[String], &str, bool) + Send + Sync>;
384
385/// Active GSM 07.10 multiplexer on a physical serial port.
386pub struct CmuxSession {
387    physical_path: String,
388    io: Arc<dyn CmuxPhysicalIo>,
389    deframer: Mutex<Deframer>,
390    channels: Mutex<HashMap<u8, Arc<DlciChannel>>>,
391    /// SABM or DISC sent, waiting for UA (true) or DM (false).
392    pending_open: Mutex<HashMap<u8, mpsc::Sender<bool>>>,
393    /// CLD sent, waiting for its response.
394    pending_cld: Mutex<Option<mpsc::Sender<()>>>,
395    /// DLCs the modem closed (DISC / DM): writes fail until the DLCI is registered again.
396    closed: Mutex<HashSet<u8>>,
397    tx: Mutex<TxGate>,
398    tx_cv: Condvar,
399    /// Set when the session ended (closed down, or the modem left multiplexer mode).
400    dead: Mutex<Option<String>>,
401    on_closed: OnceLock<ClosedHook>,
402    timers: CmuxTimers,
403    outbox: Arc<Outbox>,
404}
405
406impl CmuxSession {
407    /// Session with the basic-option default N1 (31, the 4.0.0 behaviour);
408    /// [`Self::with_n1`] for the N1 given to `AT+CMUX`.
409    pub fn new(physical_path: String, io: Arc<dyn CmuxPhysicalIo>) -> Arc<Self> {
410        Self::with_n1(physical_path, io, serial_codec::cmux::TX_N1)
411    }
412
413    /// `n1`: the negotiated maximum frame size (`AT+CMUX` N1, see [`cmux_n1`]).
414    /// Frames up to `max(n1, DEFAULT_MAX_RX_INFO)` info bytes are accepted. One SABM
415    /// per open (4.x).
416    pub fn with_n1(physical_path: String, io: Arc<dyn CmuxPhysicalIo>, n1: usize) -> Arc<Self> {
417        let timers = CmuxTimers {
418            n2: 0,
419            ..CmuxTimers::default()
420        };
421        Self::with_timers(physical_path, io, n1, timers)
422    }
423
424    /// Session for the `AT+CMUX=` command that started it: N1 ([`cmux_n1`]) and the
425    /// T1/N2/T2 timers ([`CmuxTimers::from_command`]).
426    pub fn for_command(
427        physical_path: String,
428        io: Arc<dyn CmuxPhysicalIo>,
429        command: &str,
430    ) -> Arc<Self> {
431        Self::with_timers(
432            physical_path,
433            io,
434            cmux_n1(command),
435            CmuxTimers::from_command(command),
436        )
437    }
438
439    fn with_timers(
440        physical_path: String,
441        io: Arc<dyn CmuxPhysicalIo>,
442        n1: usize,
443        timers: CmuxTimers,
444    ) -> Arc<Self> {
445        Arc::new(Self {
446            physical_path,
447            io,
448            deframer: Mutex::new(Deframer::with_max_info(
449                n1.max(crate::cmux::frame::DEFAULT_MAX_RX_INFO),
450            )),
451            channels: Mutex::new(HashMap::new()),
452            pending_open: Mutex::new(HashMap::new()),
453            pending_cld: Mutex::new(None),
454            closed: Mutex::new(HashSet::new()),
455            tx: Mutex::default(),
456            tx_cv: Condvar::new(),
457            dead: Mutex::new(None),
458            on_closed: OnceLock::new(),
459            timers,
460            outbox: Arc::default(),
461        })
462    }
463
464    pub fn physical_path(&self) -> &str {
465        &self.physical_path
466    }
467
468    /// Run `hook` whenever the modem closes channels (set once, by the manager).
469    pub(crate) fn set_on_closed(&self, hook: ClosedHook) {
470        let _ = self.on_closed.set(hook);
471    }
472
473    /// `Err` once the session ended.
474    fn check_alive(&self) -> Result<(), String> {
475        match crate::sync_util::lock_or_recover(&self.dead).as_ref() {
476            Some(why) => Err(why.clone()),
477            None => Ok(()),
478        }
479    }
480
481    fn end(&self, why: &str) {
482        crate::sync_util::lock_or_recover(&self.dead).get_or_insert_with(|| why.to_string());
483        self.wake_writers();
484    }
485
486    /// Wake writers waiting on flow control (state changed: FCon, a channel closed …).
487    fn wake_writers(&self) {
488        drop(crate::sync_util::lock_or_recover(&self.tx));
489        self.tx_cv.notify_all();
490    }
491
492    pub fn register_dlci(&self, dlci: u8, virtual_path: String) -> Arc<DlciChannel> {
493        let ch = Arc::new(DlciChannel::new(virtual_path, self.outbox.clone()));
494        let replaced = crate::sync_util::lock_or_recover(&self.channels).insert(dlci, ch.clone());
495        if let Some(old) = replaced {
496            old.begin_close();
497            old.end_watches(None);
498        }
499        crate::sync_util::lock_or_recover(&self.closed).remove(&dlci);
500        // An MSC FC of the channel's previous life does not hold the new one.
501        crate::sync_util::lock_or_recover(&self.tx)
502            .held_dlcis
503            .remove(&dlci);
504        ch
505    }
506
507    pub fn unregister_dlci(&self, dlci: u8) {
508        crate::sync_util::lock_or_recover(&self.closed).remove(&dlci);
509        crate::sync_util::lock_or_recover(&self.tx)
510            .held_dlcis
511            .remove(&dlci);
512        let removed = crate::sync_util::lock_or_recover(&self.channels).remove(&dlci);
513        self.wake_writers();
514        if let Some(ch) = removed {
515            ch.begin_close();
516            ch.end_watches(None);
517            // Wait (up to T1) for the UA / DM: a CLD sent while the DISC is still in
518            // progress is answered by the M26 only after ~0.5 s, past T2.
519            let (tx, rx) = mpsc::channel();
520            crate::sync_util::lock_or_recover(&self.pending_open).insert(dlci, tx);
521            if self
522                .io
523                .write_all(&encode_frame(dlci, true, DISC | PF, &[]))
524                .is_ok()
525            {
526                let _ = rx.recv_timeout(self.timers.t1);
527            }
528            crate::sync_util::lock_or_recover(&self.pending_open).remove(&dlci);
529        }
530    }
531
532    pub fn has_dlci(&self, dlci: u8) -> bool {
533        crate::sync_util::lock_or_recover(&self.channels).contains_key(&dlci)
534    }
535
536    /// Establish a DLC: send SABM and wait for the modem's UA (DM = refused). SABM is
537    /// resent every T1, at most N2 times; the last try waits out `timeout` (at least T1).
538    /// A data DLC gets an MSC (V.24 signals ready) once established.
539    /// DLCI 0 (the control channel) must be opened first.
540    pub fn open_dlci(&self, dlci: u8, timeout: Duration) -> Result<(), String> {
541        self.check_alive()?;
542        let (tx, rx) = mpsc::channel();
543        crate::sync_util::lock_or_recover(&self.pending_open).insert(dlci, tx);
544        let CmuxTimers { t1, n2, .. } = self.timers;
545        let total = timeout.max(t1 * (n2 + 1));
546        let sabm = encode_frame(dlci, true, SABM | PF, &[]);
547        let start = Instant::now();
548        let mut answer = Ok(None);
549        for attempt in 0..=n2 {
550            if let Err(e) = self.io.write_all(&sabm) {
551                answer = Err(e);
552                break;
553            }
554            let wait = if attempt == n2 {
555                total.saturating_sub(start.elapsed())
556            } else {
557                t1
558            };
559            if let Ok(ua) = rx.recv_timeout(wait) {
560                answer = Ok(Some(ua));
561                break;
562            }
563        }
564        crate::sync_util::lock_or_recover(&self.pending_open).remove(&dlci);
565        match answer? {
566            Some(true) => {
567                if dlci != 0 {
568                    let msc = [MSC_CMD, 0x05, (dlci << 2) | 0x03, V24_READY];
569                    let _ = self.io.write_all(&encode_frame(0, true, UIH, &msc));
570                }
571                Ok(())
572            }
573            Some(false) => Err(format!("modem refused CMUX DLCI {dlci} (DM)")),
574            None => Err(format!(
575                "no UA for CMUX DLCI {dlci} within {} ms",
576                total.as_millis()
577            )),
578        }
579    }
580
581    /// Ask the modem to leave multiplexer mode: CLD on the control channel, then wait
582    /// up to T2 for its response. Channel writes fail from here on.
583    pub fn close_down(&self) {
584        self.end("CMUX multiplexer is closed");
585        let (tx, rx) = mpsc::channel();
586        *crate::sync_util::lock_or_recover(&self.pending_cld) = Some(tx);
587        let cld = encode_frame(0, true, UIH, &[CLD_CMD, 0x01]);
588        if self.io.write_all(&cld).is_ok() {
589            let _ = rx.recv_timeout(self.timers.t2);
590        }
591        *crate::sync_util::lock_or_recover(&self.pending_cld) = None;
592    }
593
594    /// The modem closed `dlci` (DISC / DM; 0: the whole multiplexer): its watches get
595    /// their remainder and `Disconnect`, an exchange in flight fails, held data is dropped.
596    fn closed_by_modem(&self, dlci: u8) {
597        let gone: Vec<(u8, Arc<DlciChannel>)> = {
598            let mut channels = crate::sync_util::lock_or_recover(&self.channels);
599            if dlci == 0 {
600                channels.drain().collect()
601            } else {
602                channels
603                    .remove(&dlci)
604                    .map(|ch| (dlci, ch))
605                    .into_iter()
606                    .collect()
607            }
608        };
609        if dlci == 0 {
610            self.end("CMUX multiplexer closed by the modem");
611        }
612        let mut paths = Vec::new();
613        for (d, ch) in gone {
614            crate::sync_util::lock_or_recover(&self.closed).insert(d);
615            let reason = format!("CMUX DLCI {d} closed by the modem");
616            ch.fail_exchange(&reason);
617            ch.end_watches(Some(&SerialEvent::Disconnect {
618                path: ch.path.clone(),
619                reason,
620            }));
621            paths.push(ch.path.clone());
622        }
623        self.wake_writers();
624        if let Some(hook) = self.on_closed.get() {
625            let reason = if dlci == 0 {
626                "CMUX multiplexer closed by the modem".to_string()
627            } else {
628                format!("CMUX DLCI {dlci} closed by the modem")
629            };
630            hook(&paths, &reason, dlci == 0);
631        }
632    }
633
634    /// Batch-timeout flush for virtual-channel watches (called from the hub tick).
635    pub fn tick(&self) {
636        for ch in self.channels() {
637            ch.tick();
638        }
639        self.outbox.deliver();
640    }
641
642    fn channels(&self) -> Vec<Arc<DlciChannel>> {
643        crate::sync_util::lock_or_recover(&self.channels)
644            .values()
645            .cloned()
646            .collect()
647    }
648
649    fn channel(&self, dlci: u8) -> Option<Arc<DlciChannel>> {
650        crate::sync_util::lock_or_recover(&self.channels)
651            .get(&dlci)
652            .cloned()
653    }
654
655    /// Physical link lost: the session ends (writes waiting on flow control fail), an
656    /// exchange in flight on a channel fails, and every channel watch gets its remainder,
657    /// then `Disconnect` with the channel's virtual path.
658    pub fn emit_disconnect(&self, reason: &str) {
659        self.disconnect_queued(reason);
660        self.deliver_queued();
661    }
662
663    /// [`Self::emit_disconnect`] without running the sinks: their last events are queued.
664    pub(crate) fn disconnect_queued(&self, reason: &str) {
665        self.end(reason);
666        let channels = self.channels();
667        for ch in &channels {
668            ch.fail_exchange(reason);
669        }
670        for ch in channels {
671            ch.end_watches(Some(&SerialEvent::Disconnect {
672                path: ch.path.clone(),
673                reason: reason.to_string(),
674            }));
675        }
676    }
677
678    /// Deliver queued events. Call with no lock held.
679    pub(crate) fn deliver_queued(&self) {
680        self.outbox.deliver();
681    }
682
683    /// The app closes `dlci` (`None`: the port, so every channel): what waits on it fails
684    /// now, so a sink in an exchange does not hold up the close.
685    pub(crate) fn begin_close(&self, dlci: Option<u8>) {
686        let channels = match dlci {
687            Some(dlci) => self.channel(dlci).into_iter().collect(),
688            None => self.channels(),
689        };
690        channels.iter().for_each(|ch| ch.begin_close());
691        self.wake_writers();
692    }
693
694    /// 4.0.0 API (feature `tauri`): [`Self::set_watch_with`] for a Tauri channel, no parser.
695    #[cfg(feature = "tauri")]
696    pub fn set_watch(
697        &self,
698        dlci: u8,
699        channel: tauri::ipc::Channel<SerialEvent>,
700        batch_timeout_ms: u64,
701    ) {
702        self.set_watch_with(
703            dlci,
704            crate::events::channel_sink(channel),
705            batch_timeout_ms,
706            None,
707        );
708    }
709
710    pub fn set_watch_with(
711        &self,
712        dlci: u8,
713        channel: crate::events::EventSink,
714        batch_timeout_ms: u64,
715        framer: Option<Box<dyn Framer>>,
716    ) {
717        self.attach_stream(dlci, channel, batch_timeout_ms, framer);
718    }
719
720    /// [`Self::set_watch_with`]; `None`: no such channel.
721    pub(crate) fn attach_stream(
722        &self,
723        dlci: u8,
724        channel: crate::events::EventSink,
725        batch_timeout_ms: u64,
726        framer: Option<Box<dyn Framer>>,
727    ) -> Option<(Arc<DlciChannel>, Arc<EventStream>)> {
728        let ch = self.channel(dlci)?;
729        let stream = ch.attach_stream(channel, batch_timeout_ms, framer);
730        Some((ch, stream))
731    }
732
733    /// Stop the channel watch; its batch and parser remainder are the last `Data`, before
734    /// this returns (a sink that calls it does not wait for another thread's delivery). The
735    /// sink runs here, so call with no manager lock held.
736    pub fn clear_watch(&self, dlci: u8) {
737        let slot = self.channel(dlci).and_then(|ch| ch.take_watch(|_| true));
738        if let Some(DlciWatchSlot {
739            target: Target::Old(stream),
740            ..
741        }) = slot
742        {
743            self.outbox.settle(&stream);
744        }
745    }
746
747    /// Add a `watch_core` stream on `dlci` (its own batch / parser). `false`: no channel.
748    pub(crate) fn add_core_watch(
749        &self,
750        dlci: u8,
751        id: u64,
752        target: Target,
753        batch_timeout_ms: u64,
754        framer: Option<Box<dyn Framer>>,
755    ) -> bool {
756        let Some(ch) = self.channel(dlci) else {
757            return false;
758        };
759        ch.attach_core_watch(id, DlciWatchSlot::new(target, batch_timeout_ms, framer));
760        true
761    }
762
763    /// Remove a `watch_core` stream; its remainder goes to its queue.
764    pub(crate) fn remove_core_watch(&self, dlci: u8, id: u64) -> bool {
765        self.channel(dlci)
766            .is_some_and(|ch| ch.detach_core_watch(id))
767    }
768
769    pub fn set_exchange_waiter(&self, dlci: u8, waiter: Arc<ExchangeWaiter>) {
770        if let Some(ch) = crate::sync_util::lock_or_recover(&self.channels).get(&dlci) {
771            ch.set_exchange_waiter(waiter);
772        }
773    }
774
775    pub fn clear_exchange_waiter(&self, dlci: u8) {
776        if let Some(ch) = crate::sync_util::lock_or_recover(&self.channels).get(&dlci) {
777            *crate::sync_util::lock_or_recover(&ch.exchange_waiter) = None;
778        }
779    }
780
781    /// Fail the in-flight exchange waiter on `dlci` (used by `cancel_exchange`).
782    pub fn cancel_active_exchange(&self, dlci: u8) {
783        if let Some(ch) = crate::sync_util::lock_or_recover(&self.channels).get(&dlci) {
784            ch.fail_exchange("exchange cancelled");
785        }
786    }
787
788    /// Send `payload` on `dlci` as UIH frames. While the modem holds flow control off
789    /// (FCoff, or MSC with FC=1 for this DLC) the write waits for it to end, at most the
790    /// write timeout of the frames, then fails; nothing is queued to go out later.
791    pub fn send_uih(&self, dlci: u8, payload: &[u8]) -> Result<usize, String> {
792        let frame = encode_uih(dlci, payload);
793        let deadline = Instant::now() + self.io.write_timeout(frame.len());
794        // Written under the gate lock: no data frame follows our FCoff response.
795        let mut gate = crate::sync_util::lock_or_recover(&self.tx);
796        loop {
797            self.check_alive()?;
798            if crate::sync_util::lock_or_recover(&self.closed).contains(&dlci) {
799                return Err(format!("CMUX DLCI {dlci} closed by the modem"));
800            }
801            match self.channel(dlci) {
802                None => return Err(format!("CMUX DLCI {dlci} is closed")),
803                Some(ch) if ch.is_closing() => return Err(PORT_CLOSED.into()),
804                Some(_) => {}
805            }
806            let held = if gate.fc_off {
807                "CMUX flow control off (FCoff)".to_string()
808            } else if gate.held_dlcis.contains(&dlci) {
809                format!("CMUX DLCI {dlci} flow control off (MSC FC)")
810            } else {
811                break;
812            };
813            let left = deadline.saturating_duration_since(Instant::now());
814            if left.is_zero() {
815                return Err(held);
816            }
817            gate = self
818                .tx_cv
819                .wait_timeout(gate, left)
820                .unwrap_or_else(|e| e.into_inner())
821                .0;
822        }
823        self.io.write_all(&frame)?;
824        drop(gate);
825        Ok(payload.len())
826    }
827
828    /// Feed raw bytes from the physical RX hub thread.
829    pub fn feed_physical_rx(&self, chunk: &[u8]) {
830        let frames = crate::sync_util::lock_or_recover(&self.deframer).feed(chunk);
831        for frame in frames {
832            self.dispatch_frame(frame);
833        }
834        self.outbox.deliver();
835    }
836
837    fn dispatch_frame(&self, frame: DecodedFrame) {
838        match frame.kind {
839            UA | DM => {
840                if let Some(tx) =
841                    crate::sync_util::lock_or_recover(&self.pending_open).get(&frame.dlci)
842                {
843                    let _ = tx.send(frame.kind == UA);
844                } else if frame.kind == DM {
845                    // DM on an established DLC: the modem has closed it.
846                    self.closed_by_modem(frame.dlci);
847                }
848                return;
849            }
850            DISC => {
851                // UA when the DLC is open (DLCI 0: the whole multiplexer), else DM.
852                let open = frame.dlci == 0 || self.has_dlci(frame.dlci);
853                let reply = if open { UA } else { DM };
854                let _ = self
855                    .io
856                    .write_all(&encode_frame(frame.dlci, false, reply | PF, &[]));
857                if open {
858                    self.closed_by_modem(frame.dlci);
859                }
860                return;
861            }
862            UIH | UI => {}
863            // SABM from the modem: we are the initiator, nothing to accept.
864            _ => return,
865        }
866        if frame.dlci == 0 {
867            self.handle_control(&frame.payload);
868            return;
869        }
870        let Some(ch) = self.channel(frame.dlci) else {
871            return;
872        };
873        let waiter = crate::sync_util::lock_or_recover(&ch.exchange_waiter).clone();
874        if let Some(waiter) = waiter {
875            waiter.push_bytes(&frame.payload);
876            return;
877        }
878        ch.push_stream(&frame.payload);
879    }
880
881    /// Control-channel message from the modem. The commands we know (PN, PSC, TEST,
882    /// MSC, RPN, RLS, FCon/FCoff, CLD) are acknowledged by echoing them back with the
883    /// type octet's C/R bit cleared, as 27.010 §5.4.6 requires; any other command gets
884    /// NSC (§5.4.6.3.8). FCoff holds UIH data on every DLC until FCon, an MSC with FC
885    /// set holds that DLC until an MSC without it; CLD from the modem closes every
886    /// channel. Of the responses only CLD's is waited for.
887    fn handle_control(&self, payload: &[u8]) {
888        let Some(&type_octet) = payload.first() else {
889            return;
890        };
891        if type_octet & CR == 0 {
892            if type_octet == CLD_RSP {
893                if let Some(tx) = crate::sync_util::lock_or_recover(&self.pending_cld).as_ref() {
894                    let _ = tx.send(());
895                }
896            }
897            return;
898        }
899        // Gate first: no data frame may follow the FCoff response.
900        if type_octet == FCOFF_CMD {
901            crate::sync_util::lock_or_recover(&self.tx).fc_off = true;
902        }
903        if let (MSC_CMD, Some(&address), Some(&v24)) = (type_octet, payload.get(2), payload.get(3))
904        {
905            let dlci = address >> 2;
906            let mut gate = crate::sync_util::lock_or_recover(&self.tx);
907            if v24 & V24_FC != 0 {
908                gate.held_dlcis.insert(dlci);
909            } else {
910                gate.held_dlcis.remove(&dlci);
911            }
912            drop(gate);
913            self.tx_cv.notify_all();
914        }
915        let reply = if ECHOED.contains(&type_octet) {
916            let mut reply = payload.to_vec();
917            reply[0] &= !CR;
918            reply
919        } else {
920            vec![NSC_RSP, 0x03, type_octet]
921        };
922        let _ = self.io.write_all(&encode_frame(0, true, UIH, &reply));
923        match type_octet {
924            FCON_CMD => {
925                crate::sync_util::lock_or_recover(&self.tx).fc_off = false;
926                self.tx_cv.notify_all();
927            }
928            CLD_CMD => self.closed_by_modem(0),
929            _ => {}
930        }
931    }
932}