Skip to main content

serialplugin_core/at/
commands.rs

1//! Shared AT command runtime (desktop + mobile).
2
3use crate::at::session::{
4    check_expect_ok, normalize_at_command, AtCommandOptions, AtPhase, AtPhaseWrite,
5    AtSessionConfig, SendSmsPduOptions,
6};
7use crate::error::Error;
8use crate::events::{ExchangeCompletionMode, ExchangeOptions, RxPrepareMode};
9use crate::port::tx_queue::PortTxQueue;
10
11/// Platform exchange entry point used by `at` / `at_phases` (physical or CMUX virtual).
12pub trait ExchangeRunner {
13    fn run_exchange_unqueued(
14        &self,
15        path: String,
16        payload: Vec<u8>,
17        options: ExchangeOptions,
18    ) -> Result<crate::at::parse::ExchangeResponse, Error>;
19}
20
21fn phase_gap_hook(_phase_index: usize) {
22    #[cfg(target_os = "android")]
23    if _phase_index > 0 {
24        // CH340 resets if the next command lands while a large RX is still draining.
25        std::thread::sleep(std::time::Duration::from_millis(250));
26    }
27}
28
29/// Run one AT command with session defaults (caller holds TX queue turn).
30pub fn run_at<R: ExchangeRunner>(
31    runner: &R,
32    session: &AtSessionConfig,
33    path: String,
34    command: String,
35    options: Option<AtCommandOptions>,
36) -> Result<crate::at::parse::AtCommandResult, Error> {
37    let append_cr = options
38        .as_ref()
39        .and_then(|o| o.append_cr)
40        .unwrap_or_else(|| session.append_cr());
41    let payload = normalize_at_command(&command, append_cr);
42    let exchange_opts = session.merge_exchange(&command, options.as_ref());
43    let response = runner.run_exchange_unqueued(path, payload.into_bytes(), exchange_opts)?;
44    check_expect_ok(
45        session,
46        response.status,
47        &String::from_utf8_lossy(&response.raw),
48    )?;
49    Ok(crate::at::parse::AtCommandResult::from_exchange(
50        command, response,
51    ))
52}
53
54/// Multi-phase AT flow (caller holds TX queue turn).
55pub fn run_at_phases<R: ExchangeRunner>(
56    runner: &R,
57    session: &AtSessionConfig,
58    path: String,
59    phases: Vec<AtPhase>,
60) -> Result<Vec<crate::at::parse::AtCommandResult>, Error> {
61    let stop_on_error = session.stop_on_error();
62    let mut results = Vec::with_capacity(phases.len());
63    // A payload phase (PDU + Ctrl-Z after `AT+CMGS=n` / `AT+CMGW=n`) has no AT command
64    // of its own; its reply (`+CMGS: <mr>`) answers the command that opened the prompt.
65    let mut command_prefixes: Vec<String> = Vec::new();
66    for (i, phase) in phases.iter().enumerate() {
67        phase_gap_hook(i);
68        let label = phase.command.clone().unwrap_or_else(|| match &phase.write {
69            AtPhaseWrite::Text(s) => s.clone(),
70            AtPhaseWrite::Binary(b) => format!("<binary {} bytes>", b.len()),
71        });
72        let rx_prepare = if i == 0 {
73            None
74        } else {
75            Some(RxPrepareMode::None)
76        };
77        let mut exchange_opts = session.merge_phase(phase, &label);
78        let own_prefixes = crate::at::parse::derive_solicited_prefixes(&label);
79        if own_prefixes.is_empty() {
80            let prefixes = exchange_opts
81                .solicited_prefixes
82                .get_or_insert_with(Vec::new);
83            for p in &command_prefixes {
84                if !prefixes.contains(p) {
85                    prefixes.push(p.clone());
86                }
87            }
88        } else {
89            command_prefixes = own_prefixes;
90        }
91        if let Some(rp) = rx_prepare {
92            exchange_opts.rx_prepare = Some(rp);
93        }
94        let payload = match &phase.write {
95            AtPhaseWrite::Text(s) => normalize_at_command(s, session.append_cr()).into_bytes(),
96            AtPhaseWrite::Binary(b) => b.clone(),
97        };
98        // `timed_out` comes from the exchange error only. `check_expect_ok`'s error quotes
99        // the modem's reply (`+CME ERROR: network timeout` is an answer, not a timeout).
100        // The runner returns an untyped `Error`; its exchange messages carry no device text.
101        let phase_result = runner
102            .run_exchange_unqueued(path.clone(), payload, exchange_opts)
103            .map_err(|e| {
104                let timed_out = crate::error::ErrorKind::from_message(&e.to_string())
105                    == crate::error::ErrorKind::Timeout;
106                (e, timed_out)
107            })
108            .and_then(|response| {
109                check_expect_ok(
110                    session,
111                    response.status,
112                    &String::from_utf8_lossy(&response.raw),
113                )
114                .map_err(|e| (e, false))?;
115                Ok(crate::at::parse::AtCommandResult::from_exchange(
116                    label.clone(),
117                    response,
118                ))
119            });
120        match phase_result {
121            Ok(r) => results.push(r),
122            Err((e, timed_out)) => {
123                if stop_on_error {
124                    return Err(e);
125                }
126                let mut failed = crate::at::parse::AtCommandResult::failed(label, e.to_string());
127                failed.timed_out = timed_out;
128                results.push(failed);
129            }
130        }
131    }
132    Ok(results)
133}
134
135/// Built-in CMGS phase list.
136pub fn cmgs_phases(
137    session: &AtSessionConfig,
138    length: u32,
139    pdu: Vec<u8>,
140    options: Option<&SendSmsPduOptions>,
141) -> Vec<AtPhase> {
142    let timeout_ms = options
143        .and_then(|o| o.timeout_ms)
144        .or(session.default_timeout_ms);
145    let result_format = options
146        .and_then(|o| o.result_format)
147        .or(session.result_format);
148    let cmd = format!("AT+CMGS={length}");
149    let mut payload = pdu;
150    payload.push(0x1a);
151    vec![
152        AtPhase {
153            write: AtPhaseWrite::Text(cmd.clone()),
154            completion_mode: Some(ExchangeCompletionMode::AtIntermediate),
155            result_format,
156            timeout_ms,
157            command: Some(cmd),
158            rx_prepare: None,
159        },
160        AtPhase {
161            write: AtPhaseWrite::Binary(payload),
162            completion_mode: Some(ExchangeCompletionMode::AtFinalLine),
163            result_format,
164            timeout_ms,
165            command: Some(String::new()),
166            rx_prepare: Some(RxPrepareMode::None),
167        },
168    ]
169}
170
171/// Run CMGS recipe through `run_at_phases` (caller holds TX queue turn).
172pub fn run_send_sms_pdu<R: ExchangeRunner>(
173    runner: &R,
174    session: &AtSessionConfig,
175    path: String,
176    length: u32,
177    pdu: Vec<u8>,
178    options: Option<SendSmsPduOptions>,
179) -> Result<Vec<crate::at::parse::AtCommandResult>, Error> {
180    let phases = cmgs_phases(session, length, pdu, options.as_ref());
181    run_at_phases(runner, session, path, phases)
182}
183
184/// Helper: run AT inside the port TX queue.
185pub fn queue_at<R: ExchangeRunner>(
186    runner: &R,
187    tx_queue: &PortTxQueue,
188    path: String,
189    command: String,
190    options: Option<AtCommandOptions>,
191) -> Result<crate::at::parse::AtCommandResult, Error> {
192    tx_queue.run_serial(|| {
193        let session = tx_queue.at_session();
194        run_at(runner, &session, path, command, options)
195    })
196}
197
198pub fn queue_at_phases<R: ExchangeRunner>(
199    runner: &R,
200    tx_queue: &PortTxQueue,
201    path: String,
202    phases: Vec<AtPhase>,
203) -> Result<Vec<crate::at::parse::AtCommandResult>, Error> {
204    tx_queue.run_serial(|| {
205        let session = tx_queue.at_session();
206        run_at_phases(runner, &session, path, phases)
207    })
208}
209
210pub fn queue_send_sms_pdu<R: ExchangeRunner>(
211    runner: &R,
212    tx_queue: &PortTxQueue,
213    path: String,
214    length: u32,
215    pdu: Vec<u8>,
216    options: Option<SendSmsPduOptions>,
217) -> Result<Vec<crate::at::parse::AtCommandResult>, Error> {
218    tx_queue.run_serial(|| {
219        let session = tx_queue.at_session();
220        run_send_sms_pdu(runner, &session, path, length, pdu, options)
221    })
222}
223
224#[cfg(test)]
225mod tests {
226    use super::*;
227    use crate::at::parse::{AtResultFormat, ExchangeMatch, ExchangeResponse};
228    use std::sync::Mutex;
229
230    /// Replies with canned bytes (or a canned exchange error) and parses them with the
231    /// options it was given.
232    struct FakeRunner {
233        replies: Mutex<Vec<Result<&'static [u8], &'static str>>>,
234        seen: Mutex<Vec<ExchangeOptions>>,
235    }
236
237    impl ExchangeRunner for FakeRunner {
238        fn run_exchange_unqueued(
239            &self,
240            _path: String,
241            _payload: Vec<u8>,
242            options: ExchangeOptions,
243        ) -> Result<ExchangeResponse, Error> {
244            let raw = self.replies.lock().unwrap().remove(0)?.to_vec();
245            let command = options.command.clone().unwrap_or_default();
246            let prefixes = options.solicited_prefixes.clone().unwrap_or_default();
247            self.seen.lock().unwrap().push(options);
248            Ok(ExchangeResponse::from_raw(
249                raw,
250                ExchangeMatch::Ok,
251                &command,
252                &prefixes,
253                AtResultFormat::Verbose,
254            ))
255        }
256    }
257
258    #[test]
259    fn cmgs_reference_is_solicited_in_payload_phase() {
260        let runner = FakeRunner {
261            replies: Mutex::new(vec![
262                Ok(b"AT+CMGS=20\r\r\n> "),
263                Ok(b"\r\n+CMGS: 12\r\n\r\nOK\r\n"),
264            ]),
265            seen: Mutex::new(Vec::new()),
266        };
267        let session = AtSessionConfig::default();
268        let results =
269            run_send_sms_pdu(&runner, &session, "p".into(), 20, b"0011".to_vec(), None).unwrap();
270        assert_eq!(results[1].solicited_body, vec!["+CMGS: 12".to_string()]);
271        assert!(
272            results[1].urc_lines.is_empty(),
273            "{:?}",
274            results[1].urc_lines
275        );
276        // The live demux reads the same options, so `+CMGS:` is not emitted as a URC.
277        let seen = runner.seen.lock().unwrap();
278        assert!(seen[1]
279            .solicited_prefixes
280            .as_ref()
281            .is_some_and(|p| p.iter().any(|x| x == "+CMGS:")));
282    }
283
284    fn runner(replies: Vec<&'static [u8]>) -> FakeRunner {
285        FakeRunner {
286            replies: Mutex::new(replies.into_iter().map(Ok).collect()),
287            seen: Mutex::new(Vec::new()),
288        }
289    }
290
291    fn text(s: &str) -> AtPhase {
292        AtPhase {
293            write: AtPhaseWrite::Text(s.into()),
294            completion_mode: None,
295            result_format: None,
296            timeout_ms: None,
297            command: None,
298            rx_prepare: None,
299        }
300    }
301
302    /// Only the first phase prepares RX (drain by default); later phases must not
303    /// eat the reply to the previous one.
304    #[test]
305    fn only_the_first_phase_prepares_rx() {
306        let r = runner(vec![b"\r\nOK\r\n", b"\r\nOK\r\n"]);
307        let results = run_at_phases(
308            &r,
309            &AtSessionConfig::default(),
310            "p".into(),
311            vec![text("AT"), text("ATE0")],
312        )
313        .unwrap();
314        assert_eq!(results.len(), 2);
315        let seen = r.seen.lock().unwrap();
316        assert_eq!(seen[0].rx_prepare, Some(RxPrepareMode::Drain));
317        assert_eq!(seen[1].rx_prepare, Some(RxPrepareMode::None));
318    }
319
320    #[test]
321    fn queued_phases_and_sms_run_on_the_tx_queue() {
322        let q = PortTxQueue::new();
323        let r = runner(vec![b"\r\nOK\r\n"]);
324        let results = queue_at_phases(&r, &q, "p".into(), vec![text("AT")]).unwrap();
325        assert_eq!(results.len(), 1);
326        assert_eq!(results[0].command, "AT");
327
328        let r = runner(vec![b"AT+CMGS=2\r\r\n> ", b"\r\n+CMGS: 7\r\n\r\nOK\r\n"]);
329        let results = queue_send_sms_pdu(&r, &q, "p".into(), 2, b"00".to_vec(), None).unwrap();
330        assert_eq!(results.len(), 2);
331        assert_eq!(results[1].solicited_body, vec!["+CMGS: 7".to_string()]);
332    }
333
334    /// Given a session with `expectOk` and `stopOnError: false`,
335    /// when one phase gets a modem error that mentions a timeout and the next phase's
336    /// exchange itself times out,
337    /// then only the exchange timeout is reported as `timed_out`; the modem's answer is not.
338    #[test]
339    fn timed_out_comes_from_the_exchange_not_the_modem_reply() {
340        let r = FakeRunner {
341            replies: Mutex::new(vec![
342                Ok(b"\r\n+CME ERROR: network timeout\r\n"),
343                Err("exchange timed out after 10 ms"),
344                Ok(b"\r\nOK\r\n"),
345            ]),
346            seen: Mutex::new(Vec::new()),
347        };
348        let session = AtSessionConfig {
349            expect_ok: Some(true),
350            stop_on_error: Some(false),
351            ..Default::default()
352        };
353        let results = run_at_phases(
354            &r,
355            &session,
356            "p".into(),
357            vec![text("AT+COPS?"), text("AT+CSQ"), text("AT")],
358        )
359        .unwrap();
360        let flags: Vec<(bool, bool)> = results
361            .iter()
362            .map(|x| (x.status == crate::at::parse::AtParseStatus::Ok, x.timed_out))
363            .collect();
364        assert_eq!(flags, vec![(false, false), (false, true), (true, false)]);
365    }
366}