1use serde::{Deserialize, Serialize};
4
5#[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#[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#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
37#[serde(rename_all = "camelCase")]
38pub enum ExchangeMatch {
39 Ok,
40 Error,
41 CmeError {
44 code: Option<i32>,
45 },
46 CmsError {
48 code: Option<i32>,
49 },
50 NoCarrier,
51 Busy,
52 NoAnswer,
53 NoDialtone,
54 SendOk,
56 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#[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#[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
165pub 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
177pub 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
195fn 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
226fn 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
245const MAX_CUSD_SPAN: usize = 2_048;
247
248pub 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
264fn 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 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 Line(usize),
318 Cut,
320 Open,
322}
323
324fn 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
358fn glued_final_head(line: &str) -> Option<&str> {
360 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
366fn 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
384fn 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
398pub 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
409pub 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
415pub fn classify_intermediate_line(line: &str) -> bool {
417 let t = line.trim();
418 t == "CONNECT" || t == ">" || t.starts_with("CONNECT ")
419}
420
421pub fn classify_intermediate_line_with_format(line: &str, format: AtResultFormat) -> bool {
423 classify_intermediate_line(line) || (format == AtResultFormat::Numeric && line.trim() == "1")
424}
425
426pub 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
462fn 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
471pub fn at_final_line_complete(buf: &[u8], result_format: AtResultFormat) -> Option<ExchangeMatch> {
478 scan_completion(buf, result_format, false)
479}
480
481fn scan_completion(
483 buf: &[u8],
484 format: AtResultFormat,
485 intermediate: bool,
486) -> Option<ExchangeMatch> {
487 AtCompletion::new(intermediate, format).push(buf)
488}
489
490#[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 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 pub fn push(&mut self, chunk: &[u8]) -> Option<ExchangeMatch> {
517 for line in self.lines.push(chunk) {
518 self.judge(&line);
519 }
520 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 _ 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 _ if line.get(..2).is_some_and(|p| p.eq_ignore_ascii_case("AT")) => self.last = None,
541 _ => {}
542 }
543 }
544}
545
546pub fn at_intermediate_line_complete(
553 buf: &[u8],
554 result_format: AtResultFormat,
555) -> Option<ExchangeMatch> {
556 scan_completion(buf, result_format, true)
557}
558
559pub 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 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
598const 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 ("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
686const 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
718fn 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
729fn 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#[derive(Debug, Clone, PartialEq, Eq)]
749enum LineKind {
750 Echo,
751 Body,
752 Urc,
753 Final(ExchangeMatch),
754}
755
756#[derive(Debug)]
759struct LineClassifier {
760 command: String,
761 prefixes: Vec<String>,
762 format: AtResultFormat,
763 echo_seen: bool,
764 pending: Option<(LineKind, bool)>,
767 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 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 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 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
827pub 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 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 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 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
913pub enum ExchangePhase {
914 AwaitingFirstLine,
916 CollectingSolicited,
918}
919
920pub const MAX_DEMUX_LINE: usize = 65_536;
923
924#[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#[derive(Debug)]
942struct LineAssembler {
943 numeric: bool,
944 partial: Vec<u8>,
946 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 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 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 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 pub fn new(command: &str, solicited_prefixes: &[String]) -> Self {
1025 Self::with_format(command, solicited_prefixes, AtResultFormat::Verbose)
1026 }
1027
1028 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 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 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
1075pub 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}