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        let phase_result = (|| -> Result<crate::at::parse::AtCommandResult, Error> {
99            let response = runner.run_exchange_unqueued(path.clone(), payload, exchange_opts)?;
100            check_expect_ok(
101                session,
102                response.status,
103                &String::from_utf8_lossy(&response.raw),
104            )?;
105            Ok(crate::at::parse::AtCommandResult::from_exchange(
106                label.clone(),
107                response,
108            ))
109        })();
110        match phase_result {
111            Ok(r) => results.push(r),
112            Err(e) => {
113                if stop_on_error {
114                    return Err(e);
115                }
116                results.push(crate::at::parse::AtCommandResult::failed(
117                    label,
118                    e.to_string(),
119                ));
120            }
121        }
122    }
123    Ok(results)
124}
125
126/// Built-in CMGS phase list.
127pub fn cmgs_phases(
128    session: &AtSessionConfig,
129    length: u32,
130    pdu: Vec<u8>,
131    options: Option<&SendSmsPduOptions>,
132) -> Vec<AtPhase> {
133    let timeout_ms = options
134        .and_then(|o| o.timeout_ms)
135        .or(session.default_timeout_ms);
136    let result_format = options
137        .and_then(|o| o.result_format)
138        .or(session.result_format);
139    let cmd = format!("AT+CMGS={length}");
140    let mut payload = pdu;
141    payload.push(0x1a);
142    vec![
143        AtPhase {
144            write: AtPhaseWrite::Text(cmd.clone()),
145            completion_mode: Some(ExchangeCompletionMode::AtIntermediate),
146            result_format,
147            timeout_ms,
148            command: Some(cmd),
149            rx_prepare: None,
150        },
151        AtPhase {
152            write: AtPhaseWrite::Binary(payload),
153            completion_mode: Some(ExchangeCompletionMode::AtFinalLine),
154            result_format,
155            timeout_ms,
156            command: Some(String::new()),
157            rx_prepare: Some(RxPrepareMode::None),
158        },
159    ]
160}
161
162/// Run CMGS recipe through `run_at_phases` (caller holds TX queue turn).
163pub fn run_send_sms_pdu<R: ExchangeRunner>(
164    runner: &R,
165    session: &AtSessionConfig,
166    path: String,
167    length: u32,
168    pdu: Vec<u8>,
169    options: Option<SendSmsPduOptions>,
170) -> Result<Vec<crate::at::parse::AtCommandResult>, Error> {
171    let phases = cmgs_phases(session, length, pdu, options.as_ref());
172    run_at_phases(runner, session, path, phases)
173}
174
175/// Helper: run AT inside the port TX queue.
176pub fn queue_at<R: ExchangeRunner>(
177    runner: &R,
178    tx_queue: &PortTxQueue,
179    path: String,
180    command: String,
181    options: Option<AtCommandOptions>,
182) -> Result<crate::at::parse::AtCommandResult, Error> {
183    tx_queue.run_serial(|| {
184        let session = tx_queue.at_session();
185        run_at(runner, &session, path, command, options)
186    })
187}
188
189pub fn queue_at_phases<R: ExchangeRunner>(
190    runner: &R,
191    tx_queue: &PortTxQueue,
192    path: String,
193    phases: Vec<AtPhase>,
194) -> Result<Vec<crate::at::parse::AtCommandResult>, Error> {
195    tx_queue.run_serial(|| {
196        let session = tx_queue.at_session();
197        run_at_phases(runner, &session, path, phases)
198    })
199}
200
201pub fn queue_send_sms_pdu<R: ExchangeRunner>(
202    runner: &R,
203    tx_queue: &PortTxQueue,
204    path: String,
205    length: u32,
206    pdu: Vec<u8>,
207    options: Option<SendSmsPduOptions>,
208) -> Result<Vec<crate::at::parse::AtCommandResult>, Error> {
209    tx_queue.run_serial(|| {
210        let session = tx_queue.at_session();
211        run_send_sms_pdu(runner, &session, path, length, pdu, options)
212    })
213}
214
215#[cfg(test)]
216mod tests {
217    use super::*;
218    use crate::at::parse::{AtResultFormat, ExchangeMatch, ExchangeResponse};
219    use std::sync::Mutex;
220
221    /// Replies with canned bytes and parses them with the options it was given.
222    struct FakeRunner {
223        replies: Mutex<Vec<&'static [u8]>>,
224        seen: Mutex<Vec<ExchangeOptions>>,
225    }
226
227    impl ExchangeRunner for FakeRunner {
228        fn run_exchange_unqueued(
229            &self,
230            _path: String,
231            _payload: Vec<u8>,
232            options: ExchangeOptions,
233        ) -> Result<ExchangeResponse, Error> {
234            let raw = self.replies.lock().unwrap().remove(0).to_vec();
235            let command = options.command.clone().unwrap_or_default();
236            let prefixes = options.solicited_prefixes.clone().unwrap_or_default();
237            self.seen.lock().unwrap().push(options);
238            Ok(ExchangeResponse::from_raw(
239                raw,
240                ExchangeMatch::Ok,
241                &command,
242                &prefixes,
243                AtResultFormat::Verbose,
244            ))
245        }
246    }
247
248    #[test]
249    fn cmgs_reference_is_solicited_in_payload_phase() {
250        let runner = FakeRunner {
251            replies: Mutex::new(vec![b"AT+CMGS=20\r\r\n> ", b"\r\n+CMGS: 12\r\n\r\nOK\r\n"]),
252            seen: Mutex::new(Vec::new()),
253        };
254        let session = AtSessionConfig::default();
255        let results =
256            run_send_sms_pdu(&runner, &session, "p".into(), 20, b"0011".to_vec(), None).unwrap();
257        assert_eq!(results[1].solicited_body, vec!["+CMGS: 12".to_string()]);
258        assert!(
259            results[1].urc_lines.is_empty(),
260            "{:?}",
261            results[1].urc_lines
262        );
263        // The live demux reads the same options, so `+CMGS:` is not emitted as a URC.
264        let seen = runner.seen.lock().unwrap();
265        assert!(seen[1]
266            .solicited_prefixes
267            .as_ref()
268            .is_some_and(|p| p.iter().any(|x| x == "+CMGS:")));
269    }
270}