Skip to main content

serialplugin_core/at/
session.rs

1//! AT session defaults and per-command option merging (native queue).
2
3use crate::events::{AtResultFormat, ExchangeCompletionMode, ExchangeOptions, RxPrepareMode};
4use serde::{Deserialize, Serialize};
5
6/// Session-level defaults for native `at` jobs.
7#[derive(Debug, Clone, Default, Serialize, Deserialize)]
8#[serde(rename_all = "camelCase")]
9pub struct AtSessionConfig {
10    pub default_timeout_ms: Option<u64>,
11    pub default_terminators: Option<Vec<String>>,
12    pub default_idle_ms: Option<u64>,
13    pub default_rx_prepare: Option<RxPrepareMode>,
14    pub default_solicited_prefixes: Option<Vec<String>>,
15    pub stop_on_error: Option<bool>,
16    pub expect_ok: Option<bool>,
17    pub append_cr: Option<bool>,
18    pub result_format: Option<AtResultFormat>,
19}
20
21/// Per-command overrides for native `at`.
22#[derive(Debug, Clone, Default, Serialize, Deserialize)]
23#[serde(rename_all = "camelCase")]
24pub struct AtCommandOptions {
25    pub timeout_ms: Option<u64>,
26    pub terminators: Option<Vec<String>>,
27    pub idle_ms: Option<u64>,
28    pub rx_prepare: Option<RxPrepareMode>,
29    pub completion_mode: Option<ExchangeCompletionMode>,
30    pub result_format: Option<AtResultFormat>,
31    pub solicited_prefixes: Option<Vec<String>>,
32    pub append_cr: Option<bool>,
33}
34
35/// One step in a multi-phase AT flow (e.g. CMGS).
36#[derive(Debug, Clone, Serialize, Deserialize)]
37#[serde(rename_all = "camelCase")]
38pub struct AtPhase {
39    /// UTF-8 command or raw bytes (array of u8).
40    pub write: AtPhaseWrite,
41    pub completion_mode: Option<ExchangeCompletionMode>,
42    pub result_format: Option<AtResultFormat>,
43    pub timeout_ms: Option<u64>,
44    pub command: Option<String>,
45    pub rx_prepare: Option<RxPrepareMode>,
46}
47
48#[derive(Debug, Clone, Serialize, Deserialize)]
49#[serde(untagged)]
50pub enum AtPhaseWrite {
51    Text(String),
52    Binary(Vec<u8>),
53}
54
55#[derive(Debug, Clone, Serialize, Deserialize)]
56#[serde(rename_all = "camelCase")]
57pub struct SendSmsPduOptions {
58    pub timeout_ms: Option<u64>,
59    pub result_format: Option<AtResultFormat>,
60}
61
62impl AtSessionConfig {
63    pub fn stop_on_error(&self) -> bool {
64        self.stop_on_error.unwrap_or(true)
65    }
66
67    pub fn expect_ok(&self) -> bool {
68        self.expect_ok.unwrap_or(false)
69    }
70
71    pub fn append_cr(&self) -> bool {
72        self.append_cr.unwrap_or(true)
73    }
74
75    pub fn merge_exchange(&self, command: &str, per: Option<&AtCommandOptions>) -> ExchangeOptions {
76        let per = per.cloned().unwrap_or_default();
77        ExchangeOptions {
78            timeout_ms: per.timeout_ms.or(self.default_timeout_ms),
79            terminators: per.terminators.or_else(|| self.default_terminators.clone()),
80            idle_ms: per.idle_ms.or(self.default_idle_ms),
81            rx_prepare: per
82                .rx_prepare
83                .or_else(|| self.default_rx_prepare.clone())
84                .or(Some(RxPrepareMode::Drain)),
85            completion_mode: per
86                .completion_mode
87                .clone()
88                .or(Some(ExchangeCompletionMode::AtFinalLine)),
89            result_format: per.result_format.or(self.result_format),
90            command: Some(command.to_string()),
91            solicited_prefixes: per
92                .solicited_prefixes
93                .or_else(|| self.default_solicited_prefixes.clone()),
94            ..Default::default()
95        }
96    }
97
98    pub fn merge_phase(&self, phase: &AtPhase, command: &str) -> ExchangeOptions {
99        ExchangeOptions {
100            timeout_ms: phase.timeout_ms.or(self.default_timeout_ms),
101            terminators: self.default_terminators.clone(),
102            idle_ms: self.default_idle_ms,
103            rx_prepare: phase
104                .rx_prepare
105                .clone()
106                .or_else(|| self.default_rx_prepare.clone())
107                .or(Some(RxPrepareMode::Drain)),
108            completion_mode: phase
109                .completion_mode
110                .clone()
111                .or(Some(ExchangeCompletionMode::AtFinalLine)),
112            result_format: phase.result_format.or(self.result_format),
113            command: Some(command.to_string()),
114            solicited_prefixes: self.default_solicited_prefixes.clone(),
115            ..Default::default()
116        }
117    }
118}
119
120/// Terminate `command` with CR unless the caller already did (or opted out).
121pub fn normalize_at_command(command: &str, append_cr: bool) -> String {
122    if !append_cr || command.ends_with(['\r', '\n']) {
123        command.to_string()
124    } else {
125        format!("{}\r", command.trim())
126    }
127}
128
129pub fn check_expect_ok(
130    session: &AtSessionConfig,
131    status: crate::at::parse::AtParseStatus,
132    response_preview: &str,
133) -> Result<(), crate::error::Error> {
134    if session.expect_ok() && status != crate::at::parse::AtParseStatus::Ok {
135        return Err(crate::error::Error::String(format!(
136            "AT command failed with status {:?}: {}",
137            status, response_preview
138        )));
139    }
140    Ok(())
141}
142
143#[cfg(test)]
144mod tests {
145    use super::*;
146
147    #[test]
148    fn append_cr_adds_cr() {
149        assert_eq!(normalize_at_command("AT", true), "AT\r");
150        // A terminator the caller already supplied must survive.
151        assert_eq!(normalize_at_command("AT\r", true), "AT\r");
152        assert_eq!(normalize_at_command("AT\r\n", true), "AT\r\n");
153        assert_eq!(normalize_at_command("AT\r", false), "AT\r");
154    }
155}