1use crate::mux::{self, Frame, Reader, DISC, DM, PF, SABM, UA, UIH};
4use crate::WAIT;
5use std::collections::{HashMap, HashSet};
6use std::sync::{Arc, Condvar, Mutex, MutexGuard};
7use std::time::Instant;
8
9#[derive(Debug, Clone, PartialEq, Eq)]
11#[non_exhaustive]
12pub struct Command {
13 pub dlci: Option<u8>,
15 pub line: String,
17}
18
19#[derive(Debug, Default)]
20struct Seen {
21 commands: Vec<Command>,
22 frames: Vec<Frame>,
23 pdus: Vec<String>,
24 cld_before_ua: bool,
25}
26
27#[derive(Debug, Clone, Default)]
29pub struct ModemLog(Arc<(Mutex<Seen>, Condvar)>);
30
31impl ModemLog {
32 fn lock(&self) -> MutexGuard<'_, Seen> {
33 self.0 .0.lock().unwrap_or_else(|e| e.into_inner())
34 }
35
36 fn note(&self, f: impl FnOnce(&mut Seen)) {
37 f(&mut self.lock());
38 self.0 .1.notify_all();
39 }
40
41 fn wait<T>(&self, what: &str, found: impl Fn(&Seen) -> Option<T>) -> T {
43 let deadline = Instant::now() + WAIT;
44 let mut seen = self.lock();
45 loop {
46 if let Some(found) = found(&seen) {
47 return found;
48 }
49 let left = deadline.saturating_duration_since(Instant::now());
50 if left.is_zero() {
51 drop(seen);
52 panic!("never: {what}");
53 }
54 let woken = self.0 .1.wait_timeout(seen, left);
55 seen = woken.unwrap_or_else(|e| e.into_inner()).0;
56 }
57 }
58
59 pub fn commands(&self) -> Vec<Command> {
61 self.lock().commands.clone()
62 }
63
64 pub fn wait_command(&self, line: &str) -> Command {
66 self.wait(&format!("the modem read {line}"), |s| {
67 let found = |c: &&Command| c.line.eq_ignore_ascii_case(line);
68 s.commands.iter().find(found).cloned()
69 })
70 }
71
72 pub fn frames(&self) -> Vec<Frame> {
74 self.lock().frames.clone()
75 }
76
77 pub fn wait_frame(&self, what: &str, pred: impl Fn(&Frame) -> bool) -> Frame {
79 self.wait(what, |s| s.frames.iter().find(|f| pred(f)).cloned())
80 }
81
82 pub fn pdus(&self) -> Vec<String> {
84 self.lock().pdus.clone()
85 }
86
87 pub fn cld_before_ua(&self) -> bool {
90 self.lock().cld_before_ua
91 }
92}
93
94#[derive(Debug, Clone)]
103#[non_exhaustive]
104pub struct MuxOptions {
105 pub answer_cld: bool,
107 pub deaf: HashSet<u8>,
109 pub refuse: HashSet<u8>,
111 pub lost_first_frames: usize,
114}
115
116impl Default for MuxOptions {
117 fn default() -> Self {
118 Self {
119 answer_cld: true,
120 deaf: HashSet::new(),
121 refuse: HashSet::new(),
122 lost_first_frames: 0,
123 }
124 }
125}
126
127impl MuxOptions {
128 pub fn answer_cld(mut self, on: bool) -> Self {
130 self.answer_cld = on;
131 self
132 }
133
134 pub fn deaf(mut self, dlcis: impl IntoIterator<Item = u8>) -> Self {
136 self.deaf.extend(dlcis);
137 self
138 }
139
140 pub fn refuse(mut self, dlcis: impl IntoIterator<Item = u8>) -> Self {
142 self.refuse.extend(dlcis);
143 self
144 }
145
146 pub fn lost_first_frames(mut self, n: usize) -> Self {
148 self.lost_first_frames = n;
149 self
150 }
151}
152
153#[derive(Debug, Clone)]
154enum Reply {
155 Lines(Vec<String>, String),
157 Raw(Vec<u8>),
159 Silent,
160}
161
162#[derive(Debug)]
184pub struct Modem {
185 replies: HashMap<String, Reply>,
187 echo: bool,
188 numeric: bool,
189 mux: Option<MuxOptions>,
191 log: ModemLog,
192 session: Option<Session>,
193 lines: HashMap<Option<u8>, Vec<u8>>,
194 prompts: HashSet<Option<u8>>,
196}
197
198#[derive(Debug)]
200struct Session {
201 reader: Reader,
202 lost: usize,
204 open: HashSet<u8>,
206}
207
208impl Default for Modem {
209 fn default() -> Self {
210 Self::new()
211 }
212}
213
214impl Modem {
215 pub fn new() -> Self {
218 let modem = Self {
219 replies: HashMap::new(),
220 echo: false,
221 numeric: false,
222 mux: None,
223 log: ModemLog::default(),
224 session: None,
225 lines: HashMap::new(),
226 prompts: HashSet::new(),
227 };
228 modem.reply("AT", &[]).reply("AT+CSQ", &["+CSQ: 20,99"])
229 }
230
231 fn on(mut self, command: &str, reply: Reply) -> Self {
232 self.replies.insert(command.to_ascii_uppercase(), reply);
233 self
234 }
235
236 pub fn reply(self, command: &str, lines: &[&str]) -> Self {
238 let lines = lines.iter().map(|l| l.to_string()).collect();
239 self.on(command, Reply::Lines(lines, "OK".into()))
240 }
241
242 pub fn fails(self, command: &str, result: &str) -> Self {
244 self.on(command, Reply::Lines(Vec::new(), result.into()))
245 }
246
247 pub fn raw(self, command: &str, bytes: &[u8]) -> Self {
249 self.on(command, Reply::Raw(bytes.to_vec()))
250 }
251
252 pub fn silent(self, command: &str) -> Self {
254 self.on(command, Reply::Silent)
255 }
256
257 pub fn echo(mut self) -> Self {
259 self.echo = true;
260 self
261 }
262
263 pub fn numeric(mut self) -> Self {
265 self.numeric = true;
266 self
267 }
268
269 pub fn mux(mut self, options: MuxOptions) -> Self {
271 self.mux = Some(options);
272 self
273 }
274
275 pub fn log(&self) -> ModemLog {
277 self.log.clone()
278 }
279
280 pub fn feed(&mut self, bytes: &[u8]) -> Vec<u8> {
282 self.feed_with_unread(bytes, 0)
283 }
284
285 pub(crate) fn feed_with_unread(&mut self, bytes: &[u8], unread: usize) -> Vec<u8> {
287 let mut out = Vec::new();
288 let mut rest = bytes.to_vec();
289 while !rest.is_empty() {
292 match &mut self.session {
293 None => {
294 let (reply, taken) = self.terminal(None, &rest);
295 out.extend(reply);
296 rest.drain(..taken);
297 }
298 Some(session) => {
299 let mut reader = std::mem::take(&mut session.reader);
301 reader.push(&std::mem::take(&mut rest));
302 while self.session.is_some() {
303 let Some(frame) = reader.next_frame() else {
304 break;
305 };
306 out.extend(self.frame(frame, unread));
307 }
308 match &mut self.session {
309 Some(session) => session.reader = reader,
310 None => rest = reader.into_rest(),
311 }
312 }
313 }
314 }
315 out
316 }
317
318 fn frame(&mut self, f: Frame, unread: usize) -> Vec<u8> {
319 let (Some(options), Some(session)) = (&self.mux, &mut self.session) else {
320 return Vec::new();
321 };
322 if session.lost > 0 {
323 session.lost -= 1;
324 return Vec::new();
325 }
326 self.log.note(|s| s.frames.push(f.clone()));
327 let ua = mux::frame(f.dlci, true, UA | PF, &[]);
329 let dm = mux::frame(f.dlci, true, DM | PF, &[]);
330 match f.kind {
331 SABM if options.deaf.contains(&f.dlci) => Vec::new(),
332 SABM if options.refuse.contains(&f.dlci) => dm,
333 SABM => {
334 session.open.insert(f.dlci);
335 ua
336 }
337 UA | DM => Vec::new(),
339 _ if !session.open.contains(&f.dlci) => dm,
340 DISC => {
341 session.open.remove(&f.dlci);
342 self.forget_line(f.dlci);
343 if f.dlci == 0 {
344 self.session = None;
345 }
346 ua
347 }
348 UIH if f.dlci == 0 && f.payload.first() == Some(&mux::CLD) => {
349 if unread > 0 {
350 self.log.note(|s| s.cld_before_ua = true);
351 }
352 if !options.answer_cld {
353 return Vec::new();
354 }
355 self.session = None;
356 mux::control(mux::CLD & !2, &[])
357 }
358 UIH if f.dlci != 0 => {
359 let (reply, _) = self.terminal(Some(f.dlci), &f.payload);
360 reply
362 .chunks(31)
363 .flat_map(|c| mux::data(f.dlci, c))
364 .collect()
365 }
366 _ => Vec::new(),
367 }
368 }
369
370 fn forget_line(&mut self, dlci: u8) {
372 self.lines.remove(&Some(dlci));
373 self.prompts.remove(&Some(dlci));
374 }
375
376 fn terminal(&mut self, channel: Option<u8>, bytes: &[u8]) -> (Vec<u8>, usize) {
379 let mut out = Vec::new();
380 for (i, &b) in bytes.iter().enumerate() {
381 if self.prompts.contains(&channel) {
382 match b {
384 0x1A => {
385 self.prompts.remove(&channel);
386 let pdu = std::mem::take(self.lines.entry(channel).or_default());
387 let pdu = String::from_utf8_lossy(&pdu).trim().to_string();
388 self.log.note(|s| s.pdus.push(pdu));
389 out.extend(self.lines_reply(&["+CMGS: 7".into()], "OK"));
390 }
391 0x1B => {
392 self.prompts.remove(&channel);
393 self.lines.remove(&channel);
394 out.extend(self.lines_reply(&[], "OK"));
395 }
396 _ => self.lines.entry(channel).or_default().push(b),
397 }
398 continue;
399 }
400 if b != b'\r' {
401 self.lines.entry(channel).or_default().push(b);
402 continue;
403 }
404 let line = std::mem::take(self.lines.entry(channel).or_default());
405 let command = String::from_utf8_lossy(&line).trim().to_string();
406 if self.echo {
407 out.extend(&line);
408 out.push(b'\r');
409 }
410 self.log.note(|s| {
411 s.commands.push(Command {
412 dlci: channel,
413 line: command.clone(),
414 })
415 });
416 out.extend(self.answer(channel, &command));
417 if channel.is_none() && self.session.is_some() {
418 return (out, i + 1);
419 }
420 }
421 (out, bytes.len())
422 }
423
424 fn answer(&mut self, channel: Option<u8>, command: &str) -> Vec<u8> {
425 let command = command.to_ascii_uppercase();
426 if let Some(reply) = self.replies.get(&command).cloned() {
427 return match reply {
428 Reply::Lines(lines, result) => self.lines_reply(&lines, &result),
429 Reply::Raw(bytes) => bytes,
430 Reply::Silent => Vec::new(),
431 };
432 }
433 if command.starts_with("AT+CMUX=") && channel.is_none() {
434 if let Some(options) = &self.mux {
435 self.lines.retain(|channel, _| channel.is_none());
436 self.prompts.clear();
437 self.session = Some(Session {
438 reader: Reader::default(),
439 lost: options.lost_first_frames,
440 open: HashSet::new(),
441 });
442 return self.lines_reply(&[], "OK");
443 }
444 }
445 if command.starts_with("AT+CMGS=") {
446 self.prompts.insert(channel);
447 return b"\r\n> ".to_vec();
448 }
449 self.lines_reply(&[], "ERROR")
450 }
451
452 fn lines_reply(&self, lines: &[String], result: &str) -> Vec<u8> {
453 let body: String = lines
454 .iter()
455 .map(|l| {
456 if self.numeric {
457 format!("{l}\r\n")
458 } else {
459 format!("\r\n{l}\r\n")
460 }
461 })
462 .collect();
463 let result = match (self.numeric, result) {
464 (true, "OK") => "0\r".to_string(),
465 (true, "ERROR") => "4\r".to_string(),
466 _ => format!("\r\n{result}\r\n"),
467 };
468 (body + &result).into_bytes()
469 }
470}