1use 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
11pub 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 std::thread::sleep(std::time::Duration::from_millis(250));
26 }
27}
28
29pub 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
54pub 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 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 = 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
135pub 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
171pub 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
184pub 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}