Skip to main content

serial_codec/
at.rs

1//! AT response line parsing and solicited vs URC classification.
2
3use serde::{Deserialize, Serialize};
4
5/// AT result line format (V.250 verbose vs numeric `ATV0`).
6#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
7#[serde(rename_all = "camelCase")]
8pub enum AtResultFormat {
9    #[default]
10    Verbose,
11    Numeric,
12}
13
14/// Parsed outcome of an AT exchange response.
15#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
16#[serde(rename_all = "camelCase")]
17pub struct ParsedAtResponse {
18    pub status: AtParseStatus,
19    pub lines: Vec<String>,
20    pub solicited_body: Vec<String>,
21    pub urc_lines: Vec<String>,
22    pub final_line: Option<String>,
23}
24
25#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
26#[serde(rename_all = "lowercase")]
27pub enum AtParseStatus {
28    Ok,
29    Error,
30    Cme,
31    Cms,
32    Unknown,
33}
34
35/// How the read loop decided the exchange finished.
36#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
37#[serde(rename_all = "camelCase")]
38pub enum ExchangeMatch {
39    Ok,
40    Error,
41    /// `+CME ERROR:` (27.007 §9.2); a verbose text (`AT+CMEE=2`) is mapped to its code
42    /// (`None` for text the parser does not know).
43    CmeError {
44        code: Option<i32>,
45    },
46    /// `+CMS ERROR:` (27.005 §3.2.5), mapped like [`ExchangeMatch::CmeError`].
47    CmsError {
48        code: Option<i32>,
49    },
50    NoCarrier,
51    Busy,
52    NoAnswer,
53    NoDialtone,
54    /// `SEND OK`: not V.250, the final of module TCP stacks (`AT+CIPSEND`).
55    SendOk,
56    /// `SEND FAIL`: not V.250, see [`ExchangeMatch::SendOk`].
57    SendFail,
58    Intermediate {
59        line: String,
60    },
61    Substring {
62        term: String,
63    },
64    Idle,
65}
66
67impl ExchangeMatch {
68    pub fn to_parse_status(&self) -> AtParseStatus {
69        match self {
70            ExchangeMatch::Ok | ExchangeMatch::SendOk => AtParseStatus::Ok,
71            ExchangeMatch::Error
72            | ExchangeMatch::NoCarrier
73            | ExchangeMatch::Busy
74            | ExchangeMatch::NoAnswer
75            | ExchangeMatch::NoDialtone
76            | ExchangeMatch::SendFail => AtParseStatus::Error,
77            ExchangeMatch::CmeError { .. } => AtParseStatus::Cme,
78            ExchangeMatch::CmsError { .. } => AtParseStatus::Cms,
79            ExchangeMatch::Intermediate { .. }
80            | ExchangeMatch::Substring { .. }
81            | ExchangeMatch::Idle => AtParseStatus::Unknown,
82        }
83    }
84}
85
86/// Structured exchange result returned to the frontend.
87#[derive(Debug, Clone, Serialize, Deserialize)]
88#[serde(rename_all = "camelCase")]
89pub struct ExchangeResponse {
90    pub raw: Vec<u8>,
91    pub matched: ExchangeMatch,
92    pub lines: Vec<String>,
93    pub status: AtParseStatus,
94    pub solicited_body: Vec<String>,
95    pub urc_lines: Vec<String>,
96}
97
98/// AT command result returned by native `at` / `at_phases` / `send_sms_pdu`.
99#[derive(Debug, Clone, Serialize, Deserialize)]
100#[serde(rename_all = "camelCase")]
101pub struct AtCommandResult {
102    pub command: String,
103    pub response: String,
104    pub raw: Vec<u8>,
105    pub matched: ExchangeMatch,
106    pub lines: Vec<String>,
107    pub status: AtParseStatus,
108    pub solicited_body: Vec<String>,
109    pub urc_lines: Vec<String>,
110    pub timed_out: bool,
111}
112
113impl AtCommandResult {
114    pub fn from_exchange(command: String, exchange: ExchangeResponse) -> Self {
115        let response = String::from_utf8_lossy(&exchange.raw).into_owned();
116        Self {
117            command,
118            response,
119            raw: exchange.raw,
120            matched: exchange.matched,
121            lines: exchange.lines,
122            status: exchange.status,
123            solicited_body: exchange.solicited_body,
124            urc_lines: exchange.urc_lines,
125            timed_out: false,
126        }
127    }
128
129    pub fn failed(command: String, reason: String) -> Self {
130        Self {
131            command,
132            response: reason.clone(),
133            raw: reason.into_bytes(),
134            matched: ExchangeMatch::Error,
135            lines: Vec::new(),
136            status: AtParseStatus::Error,
137            solicited_body: Vec::new(),
138            urc_lines: Vec::new(),
139            timed_out: false,
140        }
141    }
142}
143
144impl ExchangeResponse {
145    pub fn from_raw(
146        raw: Vec<u8>,
147        matched: ExchangeMatch,
148        command: &str,
149        solicited_prefixes: &[String],
150        result_format: AtResultFormat,
151    ) -> Self {
152        let merged = merge_solicited_prefixes(command, solicited_prefixes);
153        let parsed = parse_at_response(&raw, command, &merged, result_format);
154        Self {
155            status: parsed.status,
156            lines: parsed.lines,
157            solicited_body: parsed.solicited_body,
158            urc_lines: parsed.urc_lines,
159            matched,
160            raw,
161        }
162    }
163}
164
165/// Merge user-provided prefixes with auto-derived ones from the command string.
166pub fn merge_solicited_prefixes(command: &str, user: &[String]) -> Vec<String> {
167    let mut out: Vec<String> = derive_solicited_prefixes(command);
168    for p in user {
169        let t = p.trim().to_string();
170        if !t.is_empty() && !out.iter().any(|x| x == &t) {
171            out.push(t);
172        }
173    }
174    out
175}
176
177/// Derive expected solicited response headers from an AT command (e.g. `AT+CSQ` →
178/// `+CSQ:`); a composite command gets one per part (`AT+CSQ;+CREG?` → `+CSQ:`, `+CREG:`).
179/// V.250 basic commands in front of an extended one are skipped (`ATE0V1+CSQ`,
180/// `AT&F+CSQ` → `+CSQ:`).
181pub fn derive_solicited_prefixes(command: &str) -> Vec<String> {
182    let cmd = normalize_command(command);
183    if !cmd.get(..2).is_some_and(|at| at.eq_ignore_ascii_case("AT")) {
184        return Vec::new();
185    }
186    let mut out: Vec<String> = Vec::new();
187    for header in cmd[2..].split(';').filter_map(part_header) {
188        if !out.contains(&header) {
189            out.push(header);
190        }
191    }
192    out
193}
194
195/// Header of one `;`-separated part: its extended command after any leading V.250
196/// basic commands (§5.2.1: `E1`, `V0`, `&F`, `&C1`, `S0=1`, `S3?`), else the part's
197/// own name (`I` → `I:`). `D` takes the rest of the part as its dial string.
198fn part_header(part: &str) -> Option<String> {
199    let part = part.trim();
200    let b = part.as_bytes();
201    let digits = |i: usize| i + b[i..].iter().take_while(|c| c.is_ascii_digit()).count();
202    let mut i = 0;
203    while let Some(&c) = b.get(i) {
204        i = match c.to_ascii_uppercase() {
205            b' ' => i + 1,
206            b'&' if b.get(i + 1).is_some_and(u8::is_ascii_alphabetic) => digits(i + 2),
207            b'D' => break,
208            b'S' if b.get(i + 1).is_some_and(u8::is_ascii_digit) => {
209                let j = digits(i + 1);
210                match b.get(j) {
211                    Some(b'=') => digits(j + 1),
212                    Some(b'?') => j + 1,
213                    _ => j,
214                }
215            }
216            c if c.is_ascii_alphabetic() => digits(i + 1),
217            _ => break,
218        };
219    }
220    match b.get(i) {
221        Some(c) if b"+^#$%*".contains(c) => command_header(&part[i..]),
222        _ => command_header(part),
223    }
224}
225
226/// `+CSQ` → `+CSQ:`, `^SYSCFG?` → `^SYSCFG:`, `I` → `I:`.
227fn command_header(part: &str) -> Option<String> {
228    let part = part.trim();
229    let prefix_char = part.chars().next().filter(|c| "+^#$%*&".contains(*c));
230    let name: String = part
231        .trim_start_matches(['+', '^', '#', '$', '%', '*', '&'])
232        .chars()
233        .take_while(|c| c.is_ascii_alphanumeric())
234        .collect::<String>()
235        .to_ascii_uppercase();
236    if name.is_empty() {
237        return None;
238    }
239    Some(match prefix_char {
240        Some(ch) => format!("{ch}{name}:"),
241        None => format!("{name}:"),
242    })
243}
244
245/// Longest quoted `+CUSD` text kept open across embedded CR/LF (UCS2 hex of 182 chars + slack).
246const MAX_CUSD_SPAN: usize = 2_048;
247
248/// Split buffer into non-empty trimmed lines (handles `\r\n`, `\n` and a lone `\r`:
249/// V.250 §5.7.1 ends a numeric `ATV0` result code, and the echo, with `S3` only).
250///
251/// Two modem quirks are undone here, so every caller sees the same lines:
252/// - a final result glued to the next URC without CRLF (`OK+CUSD: …`) becomes two lines;
253/// - the quoted text of a `+CUSD:` may carry raw `\r`/`\n` (USSD menus): the line stays
254///   open until the quote closes. A result code, another `+XXX:` line or 2 KiB end an
255///   unclosed quote early (truncated `+CUSD`). Inside a `+CUSD` line CR/LF are kept.
256pub fn split_lines(text: &str) -> Vec<String> {
257    group_lines(text, false, false).0
258}
259
260fn is_line_end(b: u8) -> bool {
261    b == b'\n' || b == b'\r'
262}
263
264/// Group text into logical lines: every CR or LF ends a line, except inside a `+CUSD`
265/// quote. With `wait_for_quote`, a `+CUSD` quote still open at the end stops the scan;
266/// the second value is then where the rest starts (always right after a line end, or
267/// 0): it must be fed again with more bytes. Judging piece by piece (a piece ends at
268/// any CR or LF) gives the same lines whether the text arrives at once or line by line.
269/// `numeric` (`ATV0`): a numeric result code also ends an open `+CUSD` quote.
270fn group_lines(text: &str, wait_for_quote: bool, numeric: bool) -> (Vec<String>, Option<usize>) {
271    let b = text.as_bytes();
272    let mut out = Vec::new();
273    let mut pos = 0;
274    while pos < b.len() {
275        let piece_start = pos;
276        let emitted = out.len();
277        let end = b[pos..]
278            .iter()
279            .position(|&c| is_line_end(c))
280            .map_or(b.len(), |e| pos + e);
281        let piece = &text[pos..end];
282        let mut start = pos + (piece.len() - piece.trim_start().len());
283        if let Some(head) = glued_final_head(text[start..end].trim_end()) {
284            out.push(head.to_string());
285            start += head.len();
286        }
287        if !text[start..].starts_with("+CUSD:") {
288            let line = text[start..end].trim();
289            if !line.is_empty() {
290                out.push(line.to_string());
291            }
292            pos = end + 1;
293            continue;
294        }
295        match cusd_line_end(text, start, numeric) {
296            CusdEnd::Line(e) => {
297                out.push(text[start..e].trim_end().to_string());
298                pos = e + 1;
299            }
300            CusdEnd::Open if wait_for_quote => {
301                out.truncate(emitted);
302                return (out, Some(piece_start));
303            }
304            // Cut by a result code, a URC line or the span cap, or still open at the
305            // end: the first piece is a truncated line, the rest is judged on its own.
306            CusdEnd::Cut | CusdEnd::Open => {
307                out.push(text[start..end].trim_end().to_string());
308                pos = end + 1;
309            }
310        }
311    }
312    (out, None)
313}
314
315enum CusdEnd {
316    /// The line ends at this index (a line end outside the quote, or the text end).
317    Line(usize),
318    /// Ended early by a modem line / size cap.
319    Cut,
320    /// The quote is still open at the end of the text.
321    Open,
322}
323
324/// Where the `+CUSD` line starting at `start` ends: line ends inside its quote are
325/// text, unless the piece after one is a result code (with `numeric`, `ATV0` codes
326/// too), a URC line, or the line has grown past [`MAX_CUSD_SPAN`].
327fn cusd_line_end(text: &str, start: usize, numeric: bool) -> CusdEnd {
328    let b = text.as_bytes();
329    let mut quoted = false;
330    for i in start..b.len() {
331        match b[i] {
332            b'"' => quoted = !quoted,
333            c if is_line_end(c) && !quoted => return CusdEnd::Line(i),
334            c if is_line_end(c) => {
335                let next = b[i + 1..]
336                    .iter()
337                    .position(|&c| is_line_end(c))
338                    .map_or(b.len(), |e| i + 1 + e);
339                let piece = text[i + 1..next].trim();
340                if next - start > MAX_CUSD_SPAN
341                    || classify_final_line(piece).is_some()
342                    || (numeric && classify_numeric_final_line(piece).is_some())
343                    || is_urc_shape(piece)
344                {
345                    return CusdEnd::Cut;
346                }
347            }
348            _ => {}
349        }
350    }
351    if quoted {
352        CusdEnd::Open
353    } else {
354        CusdEnd::Line(b.len())
355    }
356}
357
358/// `OK+CUSD: …` → `Some("OK")`: a verbose final result glued to a URC line.
359fn glued_final_head(line: &str) -> Option<&str> {
360    // A leading `+` gives an empty head, which is no final result.
361    let idx = line.find('+')?;
362    let (head, rest) = line.split_at(idx);
363    (classify_final_line(head).is_some() && is_urc_shape(rest)).then_some(head)
364}
365
366/// Strict shape of an unsolicited line: `RING`, or `+NAME:` / `^NAME:` / `#NAME:` … with
367/// an upper-case name. SMS text such as `*100#`, `+7 900 …` or `#tag` does not match.
368fn is_urc_shape(line: &str) -> bool {
369    let t = line.trim();
370    if t == "RING" {
371        return true;
372    }
373    let Some(body) = t.strip_prefix(['+', '^', '#', '$', '%', '*']) else {
374        return false;
375    };
376    body.split_once(':').is_some_and(|(name, _)| {
377        name.starts_with(|c: char| c.is_ascii_uppercase())
378            && name
379                .chars()
380                .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit())
381    })
382}
383
384/// Header whose next line is data (27.005): `Some(true)` when more text lines may
385/// follow (text-mode `+CMGR`/`+CMGL` bodies), `Some(false)` for exactly one data line
386/// (`+CMT`, `+CBM`, PDU-mode `+CDS: <length>`).
387fn two_line_header(line: &str) -> Option<bool> {
388    if line.starts_with("+CMGR:") || line.starts_with("+CMGL:") {
389        return Some(true);
390    }
391    if line.starts_with("+CMT:") || line.starts_with("+CBM:") {
392        return Some(false);
393    }
394    let len = line.strip_prefix("+CDS:")?.trim();
395    (!len.is_empty() && len.chars().all(|c| c.is_ascii_digit())).then_some(false)
396}
397
398/// Vendor extended information line (`+CSQ:`, `^SYSCFG:`, `#SGACT:`, …).
399pub fn is_ext_info_line(line: &str) -> bool {
400    let t = line.trim();
401    t.starts_with('+')
402        || t.starts_with('^')
403        || t.starts_with('#')
404        || t.starts_with('$')
405        || t.starts_with('%')
406        || t.starts_with('*')
407}
408
409/// True when the line is a strict V.250 numeric code (`0`…`99`).
410pub fn is_numeric_result_line(line: &str) -> bool {
411    let t = line.trim();
412    !t.is_empty() && t.len() <= 2 && t.chars().all(|c| c.is_ascii_digit())
413}
414
415/// Intermediate result codes that must not complete an exchange (V.250 verbose).
416pub fn classify_intermediate_line(line: &str) -> bool {
417    let t = line.trim();
418    t == "CONNECT" || t == ">" || t.starts_with("CONNECT ")
419}
420
421/// Intermediate lines including numeric `1` (CONNECT) when `ATV0` is active.
422pub fn classify_intermediate_line_with_format(line: &str, format: AtResultFormat) -> bool {
423    classify_intermediate_line(line) || (format == AtResultFormat::Numeric && line.trim() == "1")
424}
425
426/// V.250 numeric final result codes (`ATV0`): `0` OK, `3` NO CARRIER, `4` ERROR,
427/// `6` NO DIALTONE, `7` BUSY, `8` NO ANSWER. `1` (CONNECT) is intermediate, `2` (RING)
428/// unsolicited, `5` is unassigned.
429///
430/// In numeric mode a one-digit SMS body (`0`, `4`, …) in a `+CMGR`/`+CMGL` reply is
431/// indistinguishable from a result code and ends the exchange early; read SMS in
432/// verbose mode (`ATV1`).
433pub fn classify_numeric_final_line(line: &str) -> Option<ExchangeMatch> {
434    if !is_numeric_result_line(line) {
435        return None;
436    }
437    match line.trim() {
438        "0" => Some(ExchangeMatch::Ok),
439        "3" => Some(ExchangeMatch::NoCarrier),
440        "4" => Some(ExchangeMatch::Error),
441        "6" => Some(ExchangeMatch::NoDialtone),
442        "7" => Some(ExchangeMatch::Busy),
443        "8" => Some(ExchangeMatch::NoAnswer),
444        _ => None,
445    }
446}
447
448fn classify_final_line_with_format(
449    line: &str,
450    format: AtResultFormat,
451    ignore_case: bool,
452) -> Option<ExchangeMatch> {
453    classify_final_line_cased(line, ignore_case).or_else(|| {
454        if format == AtResultFormat::Numeric {
455            classify_numeric_final_line(line)
456        } else {
457            None
458        }
459    })
460}
461
462/// End (inclusive) of the complete lines in `buf`: the last LF, or in numeric mode
463/// also the last CR (V.250 §5.7.1: `ATV0` result codes end with `S3` alone). Bytes
464/// after it may already belong to what comes next (e.g. CMUX flags right after
465/// `AT+CMUX=0` → `OK`, in the same read).
466fn complete_end(buf: &[u8], format: AtResultFormat) -> Option<usize> {
467    buf.iter()
468        .rposition(|&b| b == b'\n' || (b == b'\r' && format == AtResultFormat::Numeric))
469}
470
471/// Returns `Some(match)` when the buffer holds a complete AT final line.
472///
473/// The last final result after the echo wins; whatever follows it in the same read
474/// (`RING`, a two-line `+CMT` with its PDU, `RDY` / `Call Ready`, the rest of a USSD
475/// menu) is trailing unsolicited output and does not hide it. Bytes are decoded
476/// lossily so line noise or a Latin-1 phonebook entry cannot stall the exchange.
477pub fn at_final_line_complete(buf: &[u8], result_format: AtResultFormat) -> Option<ExchangeMatch> {
478    scan_completion(buf, result_format, false)
479}
480
481/// Shared by both completion checks: one pass of an [`AtCompletion`] over `buf`.
482fn scan_completion(
483    buf: &[u8],
484    format: AtResultFormat,
485    intermediate: bool,
486) -> Option<ExchangeMatch> {
487    AtCompletion::new(intermediate, format).push(buf)
488}
489
490/// Incremental form of [`at_final_line_complete`] / [`at_intermediate_line_complete`]:
491/// feed the reply chunk by chunk; each line is judged once, so a long reply costs
492/// time linear in its size. After each [`push`](Self::push) the answer is the one the
493/// one-shot check gives for all bytes pushed so far.
494#[derive(Debug)]
495pub struct AtCompletion {
496    lines: LineAssembler,
497    classifier: LineClassifier,
498    format: AtResultFormat,
499    intermediate: bool,
500    last: Option<ExchangeMatch>,
501}
502
503impl AtCompletion {
504    /// `intermediate`: also complete on `CONNECT` / `1` / the `> ` prompt.
505    pub fn new(intermediate: bool, format: AtResultFormat) -> Self {
506        Self {
507            lines: LineAssembler::new(format),
508            classifier: LineClassifier::new("", &[], format),
509            format,
510            intermediate,
511            last: None,
512        }
513    }
514
515    /// Feed the next bytes; returns the completion state for everything fed so far.
516    pub fn push(&mut self, chunk: &[u8]) -> Option<ExchangeMatch> {
517        for line in self.lines.push(chunk) {
518            self.judge(&line);
519        }
520        // 27.005 sends the SMS prompt as `\r\n> ` with no line feed after it.
521        if self.intermediate && String::from_utf8_lossy(self.lines.tail()).trim() == ">" {
522            return Some(ExchangeMatch::Intermediate { line: ">".into() });
523        }
524        self.last.clone()
525    }
526
527    fn judge(&mut self, line: &str) {
528        let in_data = self.classifier.in_data();
529        match self.classifier.feed(line) {
530            LineKind::Final(m) => self.last = Some(m),
531            // The data line of a two-line URC (`+CMT` text) is never an echo.
532            _ if in_data => {}
533            _ if self.intermediate && classify_intermediate_line_with_format(line, self.format) => {
534                self.last = Some(ExchangeMatch::Intermediate {
535                    line: line.to_string(),
536                })
537            }
538            // Without the command, an echo is any `AT…` line: it starts a new reply,
539            // so an earlier final (late reply to a previous command) is stale.
540            _ if line.get(..2).is_some_and(|p| p.eq_ignore_ascii_case("AT")) => self.last = None,
541            _ => {}
542        }
543    }
544}
545
546/// Completion for prompt-style commands (`AT+CMGS=…` → `> `, `ATD` → `CONNECT`).
547///
548/// 27.005 sends the SMS prompt as `\r\n> ` with no line feed after it, so the last
549/// unterminated line counts too. A final result (`+CMS ERROR: …`, `ERROR`) also
550/// completes, otherwise a rejected command would wait out the whole timeout. Data
551/// after `CONNECT` in the same read (PPP frames, CMUX flags) does not hide it.
552pub fn at_intermediate_line_complete(
553    buf: &[u8],
554    result_format: AtResultFormat,
555) -> Option<ExchangeMatch> {
556    scan_completion(buf, result_format, true)
557}
558
559/// Final result line, case-insensitive (`OK`, `ok`, …): the V.250 verbose codes,
560/// `+CME ERROR:` (27.007) and `+CMS ERROR:` (27.005). `SEND OK` / `SEND FAIL` are
561/// not V.250: they are the finals of the TCP/IP stacks of many modules
562/// (`AT+CIPSEND`) and stay for compatibility.
563pub fn classify_final_line(line: &str) -> Option<ExchangeMatch> {
564    classify_final_line_cased(line, true)
565}
566
567fn classify_final_line_cased(line: &str, ignore_case: bool) -> Option<ExchangeMatch> {
568    let trimmed = line.trim();
569    let upper;
570    let key = if ignore_case {
571        upper = trimmed.to_ascii_uppercase();
572        upper.as_str()
573    } else {
574        trimmed
575    };
576    // ASCII upper-casing keeps byte offsets, so `trimmed[11..]` is the original detail.
577    match key {
578        "OK" => Some(ExchangeMatch::Ok),
579        "ERROR" => Some(ExchangeMatch::Error),
580        "NO CARRIER" => Some(ExchangeMatch::NoCarrier),
581        "BUSY" => Some(ExchangeMatch::Busy),
582        "NO ANSWER" => Some(ExchangeMatch::NoAnswer),
583        "NO DIALTONE" => Some(ExchangeMatch::NoDialtone),
584        "SEND OK" => Some(ExchangeMatch::SendOk),
585        "SEND FAIL" => Some(ExchangeMatch::SendFail),
586        s if s.starts_with("+CME ERROR:") => {
587            let code = parse_error_detail(&trimmed[11..], CME_TEXT_CODES);
588            Some(ExchangeMatch::CmeError { code })
589        }
590        s if s.starts_with("+CMS ERROR:") => {
591            let code = parse_error_detail(&trimmed[11..], CMS_TEXT_CODES);
592            Some(ExchangeMatch::CmsError { code })
593        }
594        _ => None,
595    }
596}
597
598/// Verbose `+CME ERROR:` texts (`AT+CMEE=2`) → numeric codes (27.007 §9.2). Texts are
599/// compared loosely (see [`text_key`]); a code may have several spellings.
600const CME_TEXT_CODES: &[(&str, i32)] = &[
601    ("phone failure", 0),
602    ("no connection to phone", 1),
603    ("no connection", 1),
604    ("phone-adaptor link reserved", 2),
605    ("link reserved", 2),
606    ("operation not allowed", 3),
607    ("operation not supported", 4),
608    ("PH-SIM PIN required", 5),
609    ("PH-FSIM PIN required", 6),
610    ("PH-FSIM PUK required", 7),
611    ("SIM not inserted", 10),
612    ("SIM PIN required", 11),
613    ("SIM PUK required", 12),
614    ("SIM failure", 13),
615    ("SIM busy", 14),
616    ("SIM wrong", 15),
617    ("incorrect password", 16),
618    ("SIM PIN2 required", 17),
619    ("SIM PUK2 required", 18),
620    ("memory full", 20),
621    ("invalid index", 21),
622    ("not found", 22),
623    ("memory failure", 23),
624    ("text string too long", 24),
625    ("invalid characters in text string", 25),
626    ("dial string too long", 26),
627    ("invalid characters in dial string", 27),
628    ("no network service", 30),
629    ("no network", 30),
630    ("network timeout", 31),
631    ("timeout", 31),
632    ("network not allowed - emergency calls only", 32),
633    ("network personalization PIN required", 40),
634    ("network personalization PUK required", 41),
635    ("network subset personalization PIN required", 42),
636    ("network subset personalization PUK required", 43),
637    ("service provider personalization PIN required", 44),
638    ("service provider personalization PUK required", 45),
639    ("corporate personalization PIN required", 46),
640    ("corporate personalization PUK required", 47),
641    ("hidden key required", 48),
642    ("EAP method not supported", 49),
643    ("incorrect parameters", 50),
644    ("command implemented but currently disabled", 51),
645    ("command aborted by user", 52),
646    (
647        "not attached to network due to MT functionality restrictions",
648        53,
649    ),
650    (
651        "modem not allowed - MT restricted to emergency calls only",
652        54,
653    ),
654    (
655        "operation not allowed because of MT functionality restrictions",
656        55,
657    ),
658    (
659        "fixed dial number only allowed - called number is not a fixed dial number",
660        56,
661    ),
662    ("temporarily out of service due to other MT usage", 57),
663    ("language/alphabet not supported", 58),
664    ("language or alphabet not supported", 58),
665    ("unexpected data value", 59),
666    ("system failure", 60),
667    ("data missing", 61),
668    ("call barred", 62),
669    ("message waiting indication subscription failure", 63),
670    ("unknown", 100),
671    // 27.007 §9.2.2 packet domain
672    ("illegal MS", 103),
673    ("illegal ME", 106),
674    ("GPRS services not allowed", 107),
675    ("PLMN not allowed", 111),
676    ("location area not allowed", 112),
677    ("roaming not allowed in this location area", 113),
678    ("service option not supported", 132),
679    ("requested service option not subscribed", 133),
680    ("service option temporarily out of order", 134),
681    ("unspecified GPRS error", 148),
682    ("PDP authentication failure", 149),
683    ("invalid mobile class", 150),
684];
685
686/// Verbose `+CMS ERROR:` texts → numeric codes (27.005 §3.2.5).
687const CMS_TEXT_CODES: &[(&str, i32)] = &[
688    ("ME failure", 300),
689    ("SMS service of ME reserved", 301),
690    ("SMS service reserved", 301),
691    ("operation not allowed", 302),
692    ("operation not supported", 303),
693    ("invalid PDU mode parameter", 304),
694    ("invalid PDU parameter", 304),
695    ("invalid text mode parameter", 305),
696    ("invalid text parameter", 305),
697    ("SIM not inserted", 310),
698    ("SIM PIN required", 311),
699    ("PH-SIM PIN required", 312),
700    ("SIM failure", 313),
701    ("SIM busy", 314),
702    ("SIM wrong", 315),
703    ("SIM PUK required", 316),
704    ("SIM PIN2 required", 317),
705    ("SIM PUK2 required", 318),
706    ("memory failure", 320),
707    ("invalid memory index", 321),
708    ("invalid index", 321),
709    ("memory full", 322),
710    ("SMSC address unknown", 330),
711    ("no network service", 331),
712    ("no network", 331),
713    ("network timeout", 332),
714    ("no +CNMA acknowledgement expected", 340),
715    ("unknown error", 500),
716];
717
718/// Comparison key for error texts: letters and digits only, lower case, British
719/// `-isation` folded to `-ization`, so `SIM-PIN required`, `simpinrequired` and
720/// `Network personalisation PIN required.` find their table row.
721fn text_key(text: &str) -> String {
722    text.chars()
723        .filter(char::is_ascii_alphanumeric)
724        .collect::<String>()
725        .to_ascii_lowercase()
726        .replace("isation", "ization")
727}
728
729/// `14` → 14; `10: SIM not inserted` → 10; `SIM busy` → the table code (14).
730fn parse_error_detail(detail: &str, table: &[(&str, i32)]) -> Option<i32> {
731    let detail = detail.trim();
732    if let Ok(code) = detail.parse() {
733        return Some(code);
734    }
735    if let Some((code, _)) = detail.split_once(':') {
736        if let Ok(code) = code.trim().parse() {
737            return Some(code);
738        }
739    }
740    let key = text_key(detail.trim_matches('"').trim());
741    table
742        .iter()
743        .find(|(message, _)| text_key(message) == key)
744        .map(|(_, code)| *code)
745}
746
747/// What a reply line is, judged in order (see [`LineClassifier::feed`]).
748#[derive(Debug, Clone, PartialEq, Eq)]
749enum LineKind {
750    Echo,
751    Body,
752    Urc,
753    Final(ExchangeMatch),
754}
755
756/// Line-by-line solicited / URC classification shared by the one-shot parser, the
757/// completion check and the live demux, so they never disagree about a line.
758#[derive(Debug)]
759struct LineClassifier {
760    command: String,
761    prefixes: Vec<String>,
762    format: AtResultFormat,
763    echo_seen: bool,
764    /// Kind of the next line: the data line of a two-line header (`+CMT`, `+CMGR`, …),
765    /// plus whether more text-body lines may follow it.
766    pending: Option<(LineKind, bool)>,
767    /// Inside a text-mode `+CMGR`/`+CMGL` body: only strict URC shapes are URCs.
768    in_text_body: bool,
769}
770
771impl LineClassifier {
772    fn new(command: &str, prefixes: &[String], format: AtResultFormat) -> Self {
773        Self {
774            command: normalize_command(command),
775            prefixes: prefixes.to_vec(),
776            format,
777            echo_seen: false,
778            pending: None,
779            in_text_body: false,
780        }
781    }
782
783    /// The next line is SMS data (a two-line header's payload or a text body).
784    fn in_data(&self) -> bool {
785        self.pending.is_some() || self.in_text_body
786    }
787
788    fn feed(&mut self, line: &str) -> LineKind {
789        // SMS text is often lower-case (`ok`): inside a body only exact codes end it.
790        let in_data = self.in_data();
791        if let Some(m) = classify_final_line_with_format(line, self.format, !in_data) {
792            self.pending = None;
793            self.in_text_body = false;
794            return LineKind::Final(m);
795        }
796        if let Some((kind, text_body)) = self.pending.take() {
797            self.in_text_body = text_body;
798            return kind;
799        }
800        if !self.echo_seen && !self.command.is_empty() && lines_equivalent(line, &self.command) {
801            self.echo_seen = true;
802            return LineKind::Echo;
803        }
804        // Inside the reply (after the echo, or in an SMS text body), and whenever the
805        // command is known (`ATE0` sends no echo), only a strict URC shape with a
806        // foreign header is a URC: `+IFC (0,1,2)`, a garbled `+CSCSERROR` or the
807        // `+CGMI` of an `AT+CLAC` list stay reply text, `+CMTI: "SM",3` does not.
808        let strict = self.in_text_body || self.echo_seen || !self.command.is_empty();
809        let kind = if strict {
810            if is_urc_shape(line) && is_likely_urc(line, &self.prefixes) {
811                LineKind::Urc
812            } else {
813                LineKind::Body
814            }
815        } else if is_likely_urc(line, &self.prefixes) {
816            LineKind::Urc
817        } else {
818            LineKind::Body
819        };
820        if let Some(text_body) = two_line_header(line) {
821            self.pending = Some((kind.clone(), text_body));
822        }
823        kind
824    }
825}
826
827/// Classify lines into solicited body vs URC using echo / solicited prefixes.
828///
829/// The data line after `+CMGR:`/`+CMGL:`/`+CMT:`/`+CBM:`/`+CDS: <len>` belongs to its
830/// header (body or URC, kept adjacent). Lines after the final result are URCs.
831pub fn parse_at_response(
832    raw: &[u8],
833    command: &str,
834    solicited_prefixes: &[String],
835    result_format: AtResultFormat,
836) -> ParsedAtResponse {
837    let merged = merge_solicited_prefixes(command, solicited_prefixes);
838    // Same view as completion: complete lines only, and the final result code may be
839    // followed by URC lines (or CMUX flags) that arrived in the same read.
840    let complete = match complete_end(raw, result_format) {
841        Some(end) => &raw[..=end],
842        None => raw,
843    };
844    let numeric = result_format == AtResultFormat::Numeric;
845    let lines = group_lines(&String::from_utf8_lossy(complete), false, numeric).0;
846    let mut classifier = LineClassifier::new(command, &merged, result_format);
847    let kinds: Vec<LineKind> = lines.iter().map(|l| classifier.feed(l)).collect();
848    // Only a final result after the echo ends the reply (the echo line itself is no
849    // final, so the search may start on it).
850    let from = kinds.iter().position(|k| *k == LineKind::Echo).unwrap_or(0);
851    let final_idx = kinds[from..]
852        .iter()
853        .rposition(|k| matches!(k, LineKind::Final(_)))
854        .map(|i| i + from);
855    // Without a final result (substring / idle completion, a prompt, a timeout) every
856    // line is body or URC.
857    let final_pos = final_idx.unwrap_or(lines.len());
858    let final_line = lines.get(final_pos).cloned();
859    let status = match final_idx.map(|i| &kinds[i]) {
860        Some(LineKind::Final(m)) => m.to_parse_status(),
861        _ => AtParseStatus::Unknown,
862    };
863
864    let mut urc_lines = Vec::new();
865    let mut solicited_body = Vec::new();
866    for (line, kind) in lines.iter().zip(&kinds).take(final_pos) {
867        match kind {
868            LineKind::Echo => {}
869            LineKind::Urc => urc_lines.push(line.clone()),
870            LineKind::Body => solicited_body.push(line.clone()),
871            // An earlier result-like line: `NO CARRIER` before the echo is a URC.
872            LineKind::Final(_) if is_likely_urc(line, &merged) => urc_lines.push(line.clone()),
873            LineKind::Final(_) => solicited_body.push(line.clone()),
874        }
875    }
876    if let Some(i) = final_idx {
877        urc_lines.extend(lines.iter().skip(i + 1).cloned());
878    }
879
880    ParsedAtResponse {
881        status,
882        lines,
883        solicited_body,
884        urc_lines,
885        final_line,
886    }
887}
888
889fn normalize_command(command: &str) -> String {
890    command
891        .trim()
892        .trim_end_matches('\r')
893        .trim_end_matches('\n')
894        .to_string()
895}
896
897fn lines_equivalent(line: &str, command: &str) -> bool {
898    line.trim().eq_ignore_ascii_case(command)
899}
900
901pub fn is_likely_urc(line: &str, solicited_prefixes: &[String]) -> bool {
902    let trimmed = line.trim();
903    if !is_ext_info_line(trimmed) {
904        return matches!(trimmed, "RING" | "NO CARRIER" | "BUSY" | "NO ANSWER");
905    }
906    !solicited_prefixes
907        .iter()
908        .any(|p| trimmed.starts_with(p.trim()))
909}
910
911/// Exchange demux phase, see [`ExchangeDemux::phase`].
912#[derive(Debug, Clone, Copy, PartialEq, Eq)]
913pub enum ExchangePhase {
914    /// The echo of the command has not been seen (yet, or ever with `ATE0`).
915    AwaitingFirstLine,
916    /// The echo was seen: the reply is being collected.
917    CollectingSolicited,
918}
919
920/// Longest unterminated line [`ExchangeDemux`] keeps; longer runs without a line
921/// feed (data after `CONNECT`, binary noise) cannot be a URC and are dropped.
922pub const MAX_DEMUX_LINE: usize = 65_536;
923
924/// Routes bytes during an exchange: URC lines are emitted live, the rest is the reply.
925///
926/// Each line is judged once, when it completes, so every URC occurrence (two `RING`s
927/// in one exchange) is emitted exactly once.
928#[derive(Debug)]
929pub struct ExchangeDemux {
930    phase: ExchangePhase,
931    command: String,
932    solicited_prefixes: Vec<String>,
933    format: AtResultFormat,
934    lines: LineAssembler,
935    classifier: LineClassifier,
936}
937
938/// Turns chunks into logical lines (the [`split_lines`] rules) as they complete. A
939/// line ends at LF, in numeric mode also at CR (V.250 §5.7.1); an open `+CUSD` quote
940/// waits for more bytes. Only new bytes are searched for a line end.
941#[derive(Debug)]
942struct LineAssembler {
943    numeric: bool,
944    /// Bytes of an unfinished line (kept raw so a split UTF-8 char survives).
945    partial: Vec<u8>,
946    /// Dropping an overlong line until its line end.
947    skipping: bool,
948}
949
950impl LineAssembler {
951    fn new(format: AtResultFormat) -> Self {
952        Self {
953            numeric: format == AtResultFormat::Numeric,
954            partial: Vec::new(),
955            skipping: false,
956        }
957    }
958
959    fn is_end(&self, b: u8) -> bool {
960        b == b'\n' || (self.numeric && b == b'\r')
961    }
962
963    /// Bytes after the last complete line.
964    fn tail(&self) -> &[u8] {
965        &self.partial
966    }
967
968    fn clear(&mut self) {
969        self.partial.clear();
970        self.skipping = false;
971    }
972
973    fn push(&mut self, mut chunk: &[u8]) -> Vec<String> {
974        if self.skipping {
975            let Some(e) = chunk.iter().position(|&b| self.is_end(b)) else {
976                return Vec::new();
977            };
978            self.skipping = false;
979            // Keep the line end: it only adds an empty line, which is dropped.
980            chunk = &chunk[e..];
981        }
982        let Some(e) = chunk.iter().rposition(|&b| self.is_end(b)) else {
983            self.partial.extend_from_slice(chunk);
984            if self.partial.len() > MAX_DEMUX_LINE {
985                self.partial.clear();
986                self.skipping = true;
987            }
988            return Vec::new();
989        };
990        let end = self.partial.len() + e;
991        self.partial.extend_from_slice(chunk);
992        let text = String::from_utf8_lossy(&self.partial[..end]).into_owned();
993        let (lines, rest) = group_lines(&text, true, self.numeric);
994        // CR and LF are never part of a multi-byte sequence, so counting them in the
995        // raw bytes maps the consumed text back to a byte offset.
996        let cut = match rest {
997            None => end + 1,
998            Some(off) => match text.as_bytes()[..off]
999                .iter()
1000                .filter(|&&b| is_line_end(b))
1001                .count()
1002            {
1003                0 => 0,
1004                n => self
1005                    .partial
1006                    .iter()
1007                    .enumerate()
1008                    .filter(|(_, &b)| is_line_end(b))
1009                    .nth(n - 1)
1010                    .map_or(0, |(i, _)| i + 1),
1011            },
1012        };
1013        self.partial.drain(..cut);
1014        if self.partial.len() > MAX_DEMUX_LINE {
1015            self.skipping = !self.partial.last().is_some_and(|&b| self.is_end(b));
1016            self.partial.clear();
1017        }
1018        lines
1019    }
1020}
1021
1022impl ExchangeDemux {
1023    /// Demux for a verbose (`ATV1`) modem.
1024    pub fn new(command: &str, solicited_prefixes: &[String]) -> Self {
1025        Self::with_format(command, solicited_prefixes, AtResultFormat::Verbose)
1026    }
1027
1028    /// Demux that judges result codes like the completion check with `format`.
1029    pub fn with_format(
1030        command: &str,
1031        solicited_prefixes: &[String],
1032        format: AtResultFormat,
1033    ) -> Self {
1034        let command = normalize_command(command);
1035        let solicited_prefixes = merge_solicited_prefixes(&command, solicited_prefixes);
1036        Self {
1037            phase: ExchangePhase::AwaitingFirstLine,
1038            classifier: LineClassifier::new(&command, &solicited_prefixes, format),
1039            command,
1040            solicited_prefixes,
1041            format,
1042            lines: LineAssembler::new(format),
1043        }
1044    }
1045
1046    /// Whether the echo of the command has been seen.
1047    pub fn phase(&self) -> ExchangePhase {
1048        self.phase
1049    }
1050
1051    pub fn reset(&mut self) {
1052        self.phase = ExchangePhase::AwaitingFirstLine;
1053        self.lines.clear();
1054        self.classifier = LineClassifier::new(&self.command, &self.solicited_prefixes, self.format);
1055    }
1056
1057    /// Process complete lines from a chunk; returns new URC lines to emit live.
1058    ///
1059    /// Cost is linear in the chunk: only the new bytes are searched for a line end,
1060    /// and an unterminated line is capped at [`MAX_DEMUX_LINE`].
1061    pub fn process_chunk(&mut self, chunk: &[u8]) -> Vec<String> {
1062        let lines = self.lines.push(chunk);
1063        let mut live_urc = Vec::new();
1064        for line in lines {
1065            match self.classifier.feed(&line) {
1066                LineKind::Echo => self.phase = ExchangePhase::CollectingSolicited,
1067                LineKind::Urc => live_urc.push(line),
1068                LineKind::Body | LineKind::Final(_) => {}
1069            }
1070        }
1071        live_urc
1072    }
1073}
1074
1075/// Extract URC lines from drained bytes (for drainRx forwarding). The data line of a
1076/// two-line URC (`+CMT: ,23` + PDU) comes right after its header.
1077pub fn urc_lines_from_drain(bytes: &[u8], solicited_prefixes: &[String]) -> Vec<String> {
1078    let mut classifier = LineClassifier::new("", solicited_prefixes, AtResultFormat::Verbose);
1079    split_lines(&String::from_utf8_lossy(bytes))
1080        .into_iter()
1081        .filter(|l| match classifier.feed(l) {
1082            LineKind::Urc => true,
1083            LineKind::Final(_) => is_likely_urc(l, solicited_prefixes),
1084            LineKind::Echo | LineKind::Body => false,
1085        })
1086        .collect()
1087}