Skip to main content

serialplugin_testing/
modem.rs

1//! A fake AT modem: 27.005 / 27.007 command lines, 27.010 multiplexer.
2
3use crate::mux::{self, Frame, Reader, DISC, DM, PF, SABM, UA, UIH};
4use crate::WAIT;
5use std::collections::{HashMap, HashSet};
6use std::sync::{Arc, Condvar, Mutex, MutexGuard};
7use std::time::Instant;
8
9/// A command line the modem read, without its CR.
10#[derive(Debug, Clone, PartialEq, Eq)]
11#[non_exhaustive]
12pub struct Command {
13    /// The multiplexer channel it came on; `None` is the port itself.
14    pub dlci: Option<u8>,
15    /// The line as the host wrote it, surrounding spaces trimmed.
16    pub line: String,
17}
18
19#[derive(Debug, Default)]
20struct Seen {
21    commands: Vec<Command>,
22    frames: Vec<Frame>,
23    pdus: Vec<String>,
24    cld_before_ua: bool,
25}
26
27/// What a [`Modem`] saw, in order; stays usable after the modem moved into a device.
28#[derive(Debug, Clone, Default)]
29pub struct ModemLog(Arc<(Mutex<Seen>, Condvar)>);
30
31impl ModemLog {
32    fn lock(&self) -> MutexGuard<'_, Seen> {
33        self.0 .0.lock().unwrap_or_else(|e| e.into_inner())
34    }
35
36    fn note(&self, f: impl FnOnce(&mut Seen)) {
37        f(&mut self.lock());
38        self.0 .1.notify_all();
39    }
40
41    /// Wait until `found` finds something; panics with `what` after [`WAIT`].
42    fn wait<T>(&self, what: &str, found: impl Fn(&Seen) -> Option<T>) -> T {
43        let deadline = Instant::now() + WAIT;
44        let mut seen = self.lock();
45        loop {
46            if let Some(found) = found(&seen) {
47                return found;
48            }
49            let left = deadline.saturating_duration_since(Instant::now());
50            if left.is_zero() {
51                drop(seen);
52                panic!("never: {what}");
53            }
54            let woken = self.0 .1.wait_timeout(seen, left);
55            seen = woken.unwrap_or_else(|e| e.into_inner()).0;
56        }
57    }
58
59    /// Every command line so far.
60    pub fn commands(&self) -> Vec<Command> {
61        self.lock().commands.clone()
62    }
63
64    /// Wait until the modem read `line` (on any channel, in any case).
65    pub fn wait_command(&self, line: &str) -> Command {
66        self.wait(&format!("the modem read {line}"), |s| {
67            let found = |c: &&Command| c.line.eq_ignore_ascii_case(line);
68            s.commands.iter().find(found).cloned()
69        })
70    }
71
72    /// Every frame received while multiplexed.
73    pub fn frames(&self) -> Vec<Frame> {
74        self.lock().frames.clone()
75    }
76
77    /// Wait until a frame satisfies `pred`; returns it.
78    pub fn wait_frame(&self, what: &str, pred: impl Fn(&Frame) -> bool) -> Frame {
79        self.wait(what, |s| s.frames.iter().find(|f| pred(f)).cloned())
80    }
81
82    /// PDUs sent after an `AT+CMGS` prompt and ended by Ctrl-Z.
83    pub fn pdus(&self) -> Vec<String> {
84        self.lock().pdus.clone()
85    }
86
87    /// The host sent CLD before it read the UA to its last DISC. Real modems (Quectel M26)
88    /// answer such a CLD late. Only known on a [`FakeDevice`](crate::FakeDevice).
89    pub fn cld_before_ua(&self) -> bool {
90        self.lock().cld_before_ua
91    }
92}
93
94/// How the multiplexer behaves; the default answers every request.
95///
96/// ```
97/// use serialplugin_testing::MuxOptions;
98///
99/// let options = MuxOptions::default().refuse([4]).lost_first_frames(1);
100/// assert!(options.answer_cld && options.refuse.contains(&4));
101/// ```
102#[derive(Debug, Clone)]
103#[non_exhaustive]
104pub struct MuxOptions {
105    /// Answer CLD and leave the multiplexer; off, CLD gets no answer.
106    pub answer_cld: bool,
107    /// DLCIs whose SABM gets no answer.
108    pub deaf: HashSet<u8>,
109    /// DLCIs whose SABM is refused (DM).
110    pub refuse: HashSet<u8>,
111    /// Frames ignored right after the `AT+CMUX` OK, as a Quectel M26 does when the host
112    /// is too quick.
113    pub lost_first_frames: usize,
114}
115
116impl Default for MuxOptions {
117    fn default() -> Self {
118        Self {
119            answer_cld: true,
120            deaf: HashSet::new(),
121            refuse: HashSet::new(),
122            lost_first_frames: 0,
123        }
124    }
125}
126
127impl MuxOptions {
128    /// Set [`answer_cld`](field@Self::answer_cld).
129    pub fn answer_cld(mut self, on: bool) -> Self {
130        self.answer_cld = on;
131        self
132    }
133
134    /// Add to [`deaf`](field@Self::deaf).
135    pub fn deaf(mut self, dlcis: impl IntoIterator<Item = u8>) -> Self {
136        self.deaf.extend(dlcis);
137        self
138    }
139
140    /// Add to [`refuse`](field@Self::refuse).
141    pub fn refuse(mut self, dlcis: impl IntoIterator<Item = u8>) -> Self {
142        self.refuse.extend(dlcis);
143        self
144    }
145
146    /// Set [`lost_first_frames`](field@Self::lost_first_frames).
147    pub fn lost_first_frames(mut self, n: usize) -> Self {
148        self.lost_first_frames = n;
149        self
150    }
151}
152
153#[derive(Debug, Clone)]
154enum Reply {
155    /// Body lines, then the final result.
156    Lines(Vec<String>, String),
157    /// Sent as is.
158    Raw(Vec<u8>),
159    Silent,
160}
161
162/// The modem as a state machine: [`Modem::feed`] takes what the host wrote and returns what
163/// the modem sends back. Plug it into [`FakeDevice::modem`](crate::FakeDevice::modem) or
164/// [`peer::serve`](crate::peer::serve).
165///
166/// Commands match in any case (V.250: `at` is `AT`).
167///
168/// The multiplexer keeps the state of each DLC, as 27.010 asks: a channel carries data from
169/// its SABM to its DISC, anything else on it is answered with DM. DISC on DLCI 0 and CLD end
170/// the multiplexer: what follows is plain AT again.
171///
172/// ```
173/// use serialplugin_testing::Modem;
174///
175/// let mut modem = Modem::new()
176///     .reply("AT+CPIN?", &["+CPIN: READY"])
177///     .fails("AT+COPS?", "+CME ERROR: 30");
178/// let log = modem.log();
179/// assert_eq!(modem.feed(b"AT+CPIN?\r"), b"\r\n+CPIN: READY\r\n\r\nOK\r\n");
180/// assert_eq!(modem.feed(b"AT+COPS?\r"), b"\r\n+CME ERROR: 30\r\n");
181/// assert_eq!(log.commands()[1].line, "AT+COPS?");
182/// ```
183#[derive(Debug)]
184pub struct Modem {
185    /// By the command in upper case.
186    replies: HashMap<String, Reply>,
187    echo: bool,
188    numeric: bool,
189    /// `None`: no multiplexer (`AT+CMUX` is an error).
190    mux: Option<MuxOptions>,
191    log: ModemLog,
192    session: Option<Session>,
193    lines: HashMap<Option<u8>, Vec<u8>>,
194    /// Channels waiting for the PDU of their `AT+CMGS`.
195    prompts: HashSet<Option<u8>>,
196}
197
198/// A running multiplexer.
199#[derive(Debug)]
200struct Session {
201    reader: Reader,
202    /// Frames still to lose.
203    lost: usize,
204    /// Established DLCs.
205    open: HashSet<u8>,
206}
207
208impl Default for Modem {
209    fn default() -> Self {
210        Self::new()
211    }
212}
213
214impl Modem {
215    /// Answers `AT` with OK, `AT+CSQ` with a reading, `AT+CMGS=…` with the prompt, then
216    /// `+CMGS: 7`; anything else with ERROR.
217    pub fn new() -> Self {
218        let modem = Self {
219            replies: HashMap::new(),
220            echo: false,
221            numeric: false,
222            mux: None,
223            log: ModemLog::default(),
224            session: None,
225            lines: HashMap::new(),
226            prompts: HashSet::new(),
227        };
228        modem.reply("AT", &[]).reply("AT+CSQ", &["+CSQ: 20,99"])
229    }
230
231    fn on(mut self, command: &str, reply: Reply) -> Self {
232        self.replies.insert(command.to_ascii_uppercase(), reply);
233        self
234    }
235
236    /// `command` answers with `lines`, then OK.
237    pub fn reply(self, command: &str, lines: &[&str]) -> Self {
238        let lines = lines.iter().map(|l| l.to_string()).collect();
239        self.on(command, Reply::Lines(lines, "OK".into()))
240    }
241
242    /// `command` answers with the final result `result` (`ERROR`, `+CME ERROR: 10`, …).
243    pub fn fails(self, command: &str, result: &str) -> Self {
244        self.on(command, Reply::Lines(Vec::new(), result.into()))
245    }
246
247    /// `command` answers with exactly `bytes`.
248    pub fn raw(self, command: &str, bytes: &[u8]) -> Self {
249        self.on(command, Reply::Raw(bytes.to_vec()))
250    }
251
252    /// `command` gets no answer.
253    pub fn silent(self, command: &str) -> Self {
254        self.on(command, Reply::Silent)
255    }
256
257    /// Echo command lines (ATE1).
258    pub fn echo(mut self) -> Self {
259        self.echo = true;
260        self
261    }
262
263    /// Numeric result codes (ATV0): `0\r` for OK, `4\r` for ERROR.
264    pub fn numeric(mut self) -> Self {
265        self.numeric = true;
266        self
267    }
268
269    /// `AT+CMUX…` starts a multiplexer.
270    pub fn mux(mut self, options: MuxOptions) -> Self {
271        self.mux = Some(options);
272        self
273    }
274
275    /// The log, also after the modem moved into a device.
276    pub fn log(&self) -> ModemLog {
277        self.log.clone()
278    }
279
280    /// What the modem answers to `bytes` from the host.
281    pub fn feed(&mut self, bytes: &[u8]) -> Vec<u8> {
282        self.feed_with_unread(bytes, 0)
283    }
284
285    /// `unread`: bytes sent earlier that the host has not read yet.
286    pub(crate) fn feed_with_unread(&mut self, bytes: &[u8], unread: usize) -> Vec<u8> {
287        let mut out = Vec::new();
288        let mut rest = bytes.to_vec();
289        // Frames may follow the command that starts the multiplexer, and text the frame
290        // that ends it.
291        while !rest.is_empty() {
292            match &mut self.session {
293                None => {
294                    let (reply, taken) = self.terminal(None, &rest);
295                    out.extend(reply);
296                    rest.drain(..taken);
297                }
298                Some(session) => {
299                    // Out of the session, which a frame may end.
300                    let mut reader = std::mem::take(&mut session.reader);
301                    reader.push(&std::mem::take(&mut rest));
302                    while self.session.is_some() {
303                        let Some(frame) = reader.next_frame() else {
304                            break;
305                        };
306                        out.extend(self.frame(frame, unread));
307                    }
308                    match &mut self.session {
309                        Some(session) => session.reader = reader,
310                        None => rest = reader.into_rest(),
311                    }
312                }
313            }
314        }
315        out
316    }
317
318    fn frame(&mut self, f: Frame, unread: usize) -> Vec<u8> {
319        let (Some(options), Some(session)) = (&self.mux, &mut self.session) else {
320            return Vec::new();
321        };
322        if session.lost > 0 {
323            session.lost -= 1;
324            return Vec::new();
325        }
326        self.log.note(|s| s.frames.push(f.clone()));
327        // Responses of the responder: C/R 1 (27.010 §5.2.1.2).
328        let ua = mux::frame(f.dlci, true, UA | PF, &[]);
329        let dm = mux::frame(f.dlci, true, DM | PF, &[]);
330        match f.kind {
331            SABM if options.deaf.contains(&f.dlci) => Vec::new(),
332            SABM if options.refuse.contains(&f.dlci) => dm,
333            SABM => {
334                session.open.insert(f.dlci);
335                ua
336            }
337            // Responses of the host to what the test sent.
338            UA | DM => Vec::new(),
339            _ if !session.open.contains(&f.dlci) => dm,
340            DISC => {
341                session.open.remove(&f.dlci);
342                self.forget_line(f.dlci);
343                if f.dlci == 0 {
344                    self.session = None;
345                }
346                ua
347            }
348            UIH if f.dlci == 0 && f.payload.first() == Some(&mux::CLD) => {
349                if unread > 0 {
350                    self.log.note(|s| s.cld_before_ua = true);
351                }
352                if !options.answer_cld {
353                    return Vec::new();
354                }
355                self.session = None;
356                mux::control(mux::CLD & !2, &[])
357            }
358            UIH if f.dlci != 0 => {
359                let (reply, _) = self.terminal(Some(f.dlci), &f.payload);
360                // 31 octets per frame: the default N1.
361                reply
362                    .chunks(31)
363                    .flat_map(|c| mux::data(f.dlci, c))
364                    .collect()
365            }
366            _ => Vec::new(),
367        }
368    }
369
370    /// A channel opened again starts with an empty line and no prompt.
371    fn forget_line(&mut self, dlci: u8) {
372        self.lines.remove(&Some(dlci));
373        self.prompts.remove(&Some(dlci));
374    }
375
376    /// Command lines on the port itself (`None`) or on a DLCI: the answer, and how many
377    /// bytes were text (the rest comes after the start of the multiplexer).
378    fn terminal(&mut self, channel: Option<u8>, bytes: &[u8]) -> (Vec<u8>, usize) {
379        let mut out = Vec::new();
380        for (i, &b) in bytes.iter().enumerate() {
381            if self.prompts.contains(&channel) {
382                // Ctrl-Z ends the PDU, ESC drops it.
383                match b {
384                    0x1A => {
385                        self.prompts.remove(&channel);
386                        let pdu = std::mem::take(self.lines.entry(channel).or_default());
387                        let pdu = String::from_utf8_lossy(&pdu).trim().to_string();
388                        self.log.note(|s| s.pdus.push(pdu));
389                        out.extend(self.lines_reply(&["+CMGS: 7".into()], "OK"));
390                    }
391                    0x1B => {
392                        self.prompts.remove(&channel);
393                        self.lines.remove(&channel);
394                        out.extend(self.lines_reply(&[], "OK"));
395                    }
396                    _ => self.lines.entry(channel).or_default().push(b),
397                }
398                continue;
399            }
400            if b != b'\r' {
401                self.lines.entry(channel).or_default().push(b);
402                continue;
403            }
404            let line = std::mem::take(self.lines.entry(channel).or_default());
405            let command = String::from_utf8_lossy(&line).trim().to_string();
406            if self.echo {
407                out.extend(&line);
408                out.push(b'\r');
409            }
410            self.log.note(|s| {
411                s.commands.push(Command {
412                    dlci: channel,
413                    line: command.clone(),
414                })
415            });
416            out.extend(self.answer(channel, &command));
417            if channel.is_none() && self.session.is_some() {
418                return (out, i + 1);
419            }
420        }
421        (out, bytes.len())
422    }
423
424    fn answer(&mut self, channel: Option<u8>, command: &str) -> Vec<u8> {
425        let command = command.to_ascii_uppercase();
426        if let Some(reply) = self.replies.get(&command).cloned() {
427            return match reply {
428                Reply::Lines(lines, result) => self.lines_reply(&lines, &result),
429                Reply::Raw(bytes) => bytes,
430                Reply::Silent => Vec::new(),
431            };
432        }
433        if command.starts_with("AT+CMUX=") && channel.is_none() {
434            if let Some(options) = &self.mux {
435                self.lines.retain(|channel, _| channel.is_none());
436                self.prompts.clear();
437                self.session = Some(Session {
438                    reader: Reader::default(),
439                    lost: options.lost_first_frames,
440                    open: HashSet::new(),
441                });
442                return self.lines_reply(&[], "OK");
443            }
444        }
445        if command.starts_with("AT+CMGS=") {
446            self.prompts.insert(channel);
447            return b"\r\n> ".to_vec();
448        }
449        self.lines_reply(&[], "ERROR")
450    }
451
452    fn lines_reply(&self, lines: &[String], result: &str) -> Vec<u8> {
453        let body: String = lines
454            .iter()
455            .map(|l| {
456                if self.numeric {
457                    format!("{l}\r\n")
458                } else {
459                    format!("\r\n{l}\r\n")
460                }
461            })
462            .collect();
463        let result = match (self.numeric, result) {
464            (true, "OK") => "0\r".to_string(),
465            (true, "ERROR") => "4\r".to_string(),
466            _ => format!("\r\n{result}\r\n"),
467        };
468        (body + &result).into_bytes()
469    }
470}