Skip to main content

serialplugin_testing/
mux.rs

1//! 3GPP 27.010 basic-option frames, as a modem sends and reads them.
2
3/// Set asynchronous balanced mode: opens a DLCI.
4pub const SABM: u8 = 0x2F;
5/// Unnumbered acknowledgement.
6pub const UA: u8 = 0x63;
7/// Disconnected mode: refuses a DLCI.
8pub const DM: u8 = 0x0F;
9/// Disconnect: closes a DLCI.
10pub const DISC: u8 = 0x43;
11/// Data.
12pub const UIH: u8 = 0xEF;
13/// Poll / final bit of the control octet.
14pub const PF: u8 = 0x10;
15
16/// Multiplexer close down: the control message on DLCI 0 that ends the multiplexer (type
17/// octet, command form, as all of them here).
18pub const CLD: u8 = 0xC3;
19/// Flow control on: channel data may be sent again.
20pub const FCON: u8 = 0xA3;
21/// Flow control off: no channel data until FCON.
22pub const FCOFF: u8 = 0x63;
23/// Modem status command: V.24 signals and flow control of one DLCI.
24pub const MSC: u8 = 0xE3;
25
26const FLAG: u8 = 0xF9;
27
28/// One frame.
29#[derive(Debug, Clone, PartialEq, Eq)]
30#[non_exhaustive]
31pub struct Frame {
32    /// Channel; 0 is control.
33    pub dlci: u8,
34    /// Command / response bit.
35    pub cr: bool,
36    /// Control octet without the P/F bit.
37    pub kind: u8,
38    /// Information field.
39    pub payload: Vec<u8>,
40}
41
42impl Frame {
43    /// A frame; `kind` is the control octet without the P/F bit.
44    pub fn new(dlci: u8, cr: bool, kind: u8, payload: &[u8]) -> Self {
45        Self {
46            dlci,
47            cr,
48            kind,
49            payload: payload.to_vec(),
50        }
51    }
52}
53
54/// 27.010 §5.2.1.6: reflected CRC-8, polynomial x^8 + x^2 + x + 1, ones complement.
55fn fcs(header: &[u8]) -> u8 {
56    let crc = header.iter().fold(0xFFu8, |crc, b| {
57        (0..8).fold(
58            crc ^ b,
59            |c, _| if c & 1 == 1 { (c >> 1) ^ 0xE0 } else { c >> 1 },
60        )
61    });
62    0xFF - crc
63}
64
65/// A frame as sent on the wire; `control` carries the P/F bit when it is set. The modem is
66/// the responder (27.010 §5.2.1.2): `cr` is false in its commands (DISC) and data, true in
67/// its responses (UA, DM).
68pub fn frame(dlci: u8, cr: bool, control: u8, payload: &[u8]) -> Vec<u8> {
69    let mut header = vec![dlci << 2 | u8::from(cr) << 1 | 1, control];
70    match payload.len() {
71        n @ 0..=127 => header.push((n as u8) << 1 | 1),
72        n => header.extend([(n as u8 & 0x7F) << 1, (n >> 7) as u8]),
73    }
74    let check = fcs(&header);
75    let mut out = vec![FLAG];
76    out.extend(header);
77    out.extend(payload);
78    out.extend([check, FLAG]);
79    out
80}
81
82/// Data from the modem on `dlci` (the modem is the responder: C/R 0 in its commands).
83pub fn data(dlci: u8, payload: &[u8]) -> Vec<u8> {
84    frame(dlci, false, UIH, payload)
85}
86
87/// A control message from the modem on DLCI 0.
88pub fn control(kind: u8, value: &[u8]) -> Vec<u8> {
89    let mut message = vec![kind, (value.len() as u8) << 1 | 1];
90    message.extend(value);
91    data(0, &message)
92}
93
94/// Splits a byte stream into frames; bytes that are no frame are dropped.
95#[derive(Debug, Default)]
96pub struct Reader {
97    buf: Vec<u8>,
98}
99
100impl Reader {
101    /// The frames completed by `bytes`.
102    pub fn feed(&mut self, bytes: &[u8]) -> Vec<Frame> {
103        self.push(bytes);
104        std::iter::from_fn(|| self.next_frame()).collect()
105    }
106
107    pub(crate) fn push(&mut self, bytes: &[u8]) {
108        self.buf.extend(bytes);
109    }
110
111    /// What is left behind the last frame.
112    pub(crate) fn into_rest(self) -> Vec<u8> {
113        let start = self.buf.iter().take_while(|b| **b == FLAG).count();
114        self.buf[start..].to_vec()
115    }
116
117    /// The next complete frame.
118    pub(crate) fn next_frame(&mut self) -> Option<Frame> {
119        loop {
120            let Some(start) = self.buf.iter().position(|b| *b == FLAG) else {
121                self.buf.clear();
122                return None;
123            };
124            self.buf.drain(..start);
125            // Flags between frames may be shared or repeated.
126            while self.buf.get(1) == Some(&FLAG) {
127                self.buf.remove(0);
128            }
129            let head = self.buf.get(1..4)?;
130            let (len, header_len) = if head[2] & 1 == 1 {
131                (usize::from(head[2] >> 1), 3)
132            } else {
133                let high = self.buf.get(4)?;
134                (usize::from(head[2] >> 1) | usize::from(*high) << 7, 4)
135            };
136            let end = 1 + header_len + len;
137            let tail = self.buf.get(end..end + 2)?;
138            let header = &self.buf[1..1 + header_len];
139            if tail != [fcs(header), FLAG] {
140                self.buf.remove(0);
141                continue;
142            }
143            let frame = Frame {
144                dlci: header[0] >> 2,
145                cr: header[0] & 2 != 0,
146                kind: header[1] & !PF,
147                payload: self.buf[1 + header_len..end].to_vec(),
148            };
149            // The closing flag may open the next frame.
150            self.buf.drain(..end + 1);
151            return Some(frame);
152        }
153    }
154}