simx00x 0.1.0

A no-std and no-alloc driver for SIM800L GSM modules (and probably similar modules)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
//! Inner module that implements a state machine.

use crate::{
    SimX00X,
    at_commands::{
        BEGIN_SEND_MESSAGE, BEGIN_SEND_USSD, CHECK_REGISTERED, CTRL_Z, DISABLE_ECHO, ENABLE_CLI,
        ENABLE_CME_ERROR_VERBOSE, ENABLE_CREG, ENTER_PIN, GET_SIGNAL_STRENGTH, LIST_CURRENT_CALLS,
        SET_TEXT_MODE, SETUP_OUTGOING_CALL,
    },
    call_state::CallState,
    errors::SimError,
    log::{debug, info, warning},
};

/// States of the internal state machine.
#[derive(PartialEq, Debug, Copy, Clone)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum State {
    /// Idle state — the module has not yet been initialised.
    StateIdle,
    /// The module is being powered down gracefully.
    StatePoweringDown,
    /// The module is fully powered down and will not accept commands.
    StatePoweredDown,
    /// Main initialisation / idle loop — checks for pending work and advances the state machine.
    StateInit,
    /// Checking whether the SIM card requires a PIN code.
    StateCheckPin,
    /// Setting SMS text mode (`AT+CMGF=1`).
    StateSetupCmgf,
    /// Enabling caller line identification (`AT+CLIP=1`).
    StateSetupClip,
    /// Requesting network registration status (`AT+CREG?`).
    StateCreg,
    /// Waiting for the network registration response.
    StateCregWait,
    /// Requesting signal strength (`AT+CSQ`).
    StateCsq,
    /// Processing the signal strength response.
    StateCsqResponse,
    /// Sending SMS (phase 1) — sending the `AT+CMGS` command with the recipient number.
    StateSendingSms1,
    /// Sending SMS (phase 2) — waiting for the `>` prompt, then sending the message body.
    StateSendingSms2,
    /// Sending SMS (phase 3) — waiting for the `+CMGS:` send confirmation.
    StateSendingSms3,
    /// Checking for stored SMS messages in the module.
    StateCheckSms,
    /// Parsing a `+CMGL:` SMS listing response to extract sender and message metadata.
    StateParseSmsResponse,
    /// Receiving the full SMS message body.
    StateReceiveSms,
    /// SMS has been received and the callback invoked; pending deletion from the module.
    StateSmsReceived,
    /// Disabling command echo (`ATE0`).
    StateDisableEcho,
    /// Dialling (phase 1) — sending the `ATD` command with the recipient number.
    StateDialing1,
    /// Dialling (phase 2) — waiting for the call to connect.
    StateDialing2,
    /// Parsing an incoming call notification (`+CLIP:`).
    StateParseClip,
    /// Answering an incoming call — `ATA` has been sent, awaiting connection.
    StateAtaSent,
    /// Checking the current call status (`AT+CLCC`).
    StateCheckCall,
    /// Sending a USSD code (phase 1) — sending the `AT+CUSD` command.
    StateSendUssd1,
    /// Sending a USSD code (phase 2) — waiting for the network response.
    StateSendUssd2,
    /// Checking for the USSD response (`+CUSD:`).
    StateCheckUssd,
    /// USSD response has been received and the callback invoked.
    StateReceivedUssd,
}

pub(crate) fn parse_cmd<
    'a,
    U: embedded_io::Write + embedded_io::WriteReady + embedded_io::Read + embedded_io::ReadReady,
    const QUEUE_LEN: usize,
>(
    module: &mut SimX00X<'a, U, QUEUE_LEN>,
    //    msg: &str,
) -> Result<(), SimError<U>> {
    let msg = unsafe { str::from_utf8_unchecked(&module.uart_buffer[..module.uart_buffer_idx]) };
    let uart = unsafe { &mut *module.uart.get() };

    if msg.is_empty() {
        return Ok(());
    }

    if module.state == State::StatePoweringDown {
        if msg.contains("NORMAL POWER DOWN") {
            info!("[Sim800L] Powered down.");
            module.state = State::StatePoweredDown;
            if let Some(f) = module.config.module_powered_down_callback.as_mut() {
                f();
            }
        }
        return Ok(());
    }

    debug!("[Sim800L] PARSING MSG: {} - {:?}", msg, module.state);

    if module.state != State::StateReceiveSms {
        if msg == "RING" {
            //Incoming call...
            module.state = State::StateParseClip;
            module.expect_ack = false;
        } else if msg == "NO CARRIER" {
            if module.call_state != CallState::Disconnect {
                module.call_state = CallState::Disconnect;
                if let Some(f) = module.config.call_disconnected_callback.as_mut() {
                    f();
                }
            }
        }
    }

    if msg == "ERROR" {
        let err = SimError::AtError(module.state);
        module.state = State::StateIdle;
        return Err(err);
    }

    let ok = msg == "OK";

    if module.expect_ack {
        module.expect_ack = false;

        if !ok {
            if module.state == State::StateSetupCmgf && msg == "AT" {
                // Expected ack but AT echo received
                module.state = State::StateDisableEcho;
                module.expect_ack = true;
            } else {
                //ESP_LOGW(TAG, "Not ack. %d %s", module.state_, message.c_str());
                module.state = State::StateIdle; // Let it timeout
                return Ok(());
            }
        }
    } else if ok
        && (module.state != State::StateParseSmsResponse
            && module.state != State::StateCheckCall
            && module.state != State::StateReceiveSms
            && module.state != State::StateDialing2)
    {
        warning!("Received unexpected OK. Ignoring");
        module.expect_ack = false;
        return Ok(());
    }

    match module.state {
        State::StateInit => {
            // While we were waiting for update to check for messages, this notifies a message
            // is available.
            let message_available = msg.contains("+CMTI:");
            if !message_available {
                if msg == "RING" {
                    // Incoming call...
                    module.state = State::StateParseClip;
                } else if msg == "NO CARRIER" {
                    if module.call_state != CallState::Disconnect {
                        module.call_state = CallState::Disconnect;
                        if let Some(f) = module.config.call_disconnected_callback.as_mut() {
                            f();
                        }
                    }
                } else if msg.contains("+CUSD:") {
                    // Incoming USSD MESSAGE
                    module.state = State::StateCheckUssd;
                } else {
                    warning!("[Sim800L] Unhandled: {} - {:?}", msg, module.state);
                }
            } else {
                module.check_sms()?;
            }
        }
        State::StateCheckPin => {
            if msg.contains("+CPIN:") {
                if msg.contains("READY") {
                    module.pin_locked = false;
                    module.state = State::StateInit;
                    debug!("[Sim800L] SIM unlocked.");
                } else if msg.contains("SIM PIN") {
                    if let Some(pin) = module.config.sim_card_pin {
                        module.push_cmd(ENTER_PIN)?;
                        module.push_cmd(pin)?;
                        module.push_cmd("\"")?;
                        module.confirm_cmd()?;
                    } else {
                        warning!("[Sim800L] PIN needed!");
                        return Err(SimError::PinNeeded);
                    }
                }

                return Ok(());
            }
        }
        State::StateSetupCmgf => {
            module.send_cmd(SET_TEXT_MODE)?;
            module.state = State::StateSetupClip;
            module.expect_ack = true;
        }
        State::StateSetupClip => {
            module.send_cmd(ENABLE_CLI)?;
            module.state = State::StateCreg;
            module.expect_ack = true;
        }
        State::StateCreg => {
            module.send_cmd(CHECK_REGISTERED)?;
            module.state = State::StateCregWait;
        }
        State::StateCregWait => {
            // Response: "+CREG: 0,1" -- the one there means registered ok
            //           "+CREG: -,-" means not registered ok

            if let Some(m) = msg.strip_prefix("+CREG: ") {
                let mut split = m.split(',');
                let (en_status, conn_status) = (split.next(), split.next());

                let registered = conn_status.is_some_and(|n| n == "1" || n == "5");
                if registered {
                    if !module.registered {
                        debug!("[Sim800L] Registered OK");
                    }
                    module.state = State::StateCsq;
                    module.expect_ack = true;
                } else {
                    warning!("[Sim800L] Registration Fail");
                    if en_status.is_some_and(|n| n == "0") {
                        // Network registration is disabled, enable it
                        module.send_cmd(ENABLE_CREG)?;
                        module.expect_ack = true;
                        module.state = State::StateSetupCmgf;
                    } else {
                        debug!("Keep waiting registration...");
                        module.state = State::StateInit;
                    }
                }
                module.registered = registered;
            } else {
                debug!("Incorrect +CREG response. Keep waiting registration...");
                // Keep waiting registration
                module.state = State::StateInit;
            }
        }
        State::StateCsq => {
            module.send_cmd(GET_SIGNAL_STRENGTH)?;
            module.state = State::StateCsqResponse;
        }
        State::StateCsqResponse => {
            if let Some(m) = msg.strip_prefix("+CSQ: ") {
                let val = m.split(',').next();

                if let Some(_val) = val {
                    debug!("[Sim800L] RSSI: {}", _val);
                }
            }
            module.expect_ack = true;
            module.state = State::StateCheckSms;
        }
        State::StateSendingSms1 => {
            module.push_cmd(BEGIN_SEND_MESSAGE)?;
            let (rec, _) = module.outgoing_smses.peek().unwrap();
            uart.write_all(rec.as_bytes()).map_err(SimError::IOError)?;
            module.push_cmd("\"")?;
            module.confirm_cmd()?;

            module.state = State::StateSendingSms2;
        }
        State::StateSendingSms2 => {
            if msg == ">" {
                let (_rec, message) = module.outgoing_smses.peek().unwrap();

                // Send sms body
                info!(
                    "[Sim800L] Sending to {} message: '{}'",
                    _rec.as_str(),
                    message.as_str()
                );
                uart.write_all(message.as_bytes())
                    .map_err(SimError::IOError)?;
                uart.write_all(&[CTRL_Z]).map_err(SimError::IOError)?;
                module.state = State::StateSendingSms3;
            } else {
                module.registered = false;
                module.state = State::StateInit;
                module.send_cmd(ENABLE_CME_ERROR_VERBOSE)?;
                uart.write_all(&[CTRL_Z]).map_err(SimError::IOError)?;
            }
        }
        State::StateSendingSms3 => {
            if msg.contains("+CMGS:") {
                debug!("[Sim800L] SMS Sent OK: {}", msg);
                module.state = State::StateCheckSms;
                module.expect_ack = true;
                module.outgoing_smses.advance_cons();
                module.send_pending = module.outgoing_smses.cons_avail();
            }
        }
        State::StateCheckSms => {
            module.check_sms()?;
        }
        State::StateParseSmsResponse => {
            if msg.contains("+CMGL:") && module.parse_index == 0 {
                if let Some(m) = msg.strip_prefix("+CMGL: ") {
                    let mut split = m.split(',');

                    module.parse_index =
                        u8::from_str_radix(split.next().unwrap_or_default(), 10).unwrap_or(0);
                    split.next();

                    module.sender.clear();
                    module.sender.push_str(split.next().unwrap_or("?"))?;
                    module.message.clear();
                } else {
                    // TODO: CHECK
                    debug!("[Sim800L] Invalid message {:?} {}", module.state, msg);
                    return Ok(());
                }
                module.state = State::StateReceiveSms;
            }
            // Otherwise we receive another OK
            if ok {
                module.send_cmd(LIST_CURRENT_CALLS)?;
                module.state = State::StateCheckCall;
            }
        }
        State::StateReceiveSms => {
            /* Our recipient is set and the message body is in message
              kick ESPHome callback now
            */
            if ok || msg.contains("+CMGL:") {
                debug!(
                    "[Sim800L] Received SMS from: {}\n{}",
                    module.sender, module.message
                );

                if let Some(f) = module.config.received_sms_callback.as_mut() {
                    f(module.message.as_str(), module.sender.as_str());
                }

                module.state = State::StateSmsReceived;
            } else {
                if !module.message.is_empty() {
                    module.message.push_str("\n")?;
                }
                module.message.push_str(msg)?;
            }
        }
        State::StateSmsReceived => {}
        State::StateDisableEcho => {
            module.send_cmd(DISABLE_ECHO)?;
            module.state = State::StateSetupCmgf;
            module.expect_ack = true;
        }
        State::StateDialing1 => {
            module.push_cmd(SETUP_OUTGOING_CALL)?;

            uart.write_all(module.recipient.as_bytes())
                .map_err(SimError::IOError)?;

            module.push_cmd(";")?;
            module.confirm_cmd()?;
            module.state = State::StateDialing2;
        }
        State::StateDialing2 => {
            if ok {
                info!("[Sim800L] Dialing: '{}'", module.recipient.as_str());
                module.dial_pending = false;
            } else {
                module.registered = false;
                module.send_cmd(ENABLE_CME_ERROR_VERBOSE)?;
                uart.write_all(&[CTRL_Z]).map_err(SimError::IOError)?;
            }
            module.state = State::StateInit;
        }
        State::StateParseClip => {
            if msg.contains("+CLIP:") {
                let mut caller_id = "NULL";

                if let Some(m) = msg.strip_prefix("+CLIP: ") {
                    let mut split = m.split(',');

                    caller_id = split.next().unwrap_or("?");
                }

                if module.call_state != CallState::Incoming {
                    module.call_state = CallState::Incoming;
                    info!("[Sim800L] Incoming call from {}", caller_id);
                    if let Some(f) = module.config.received_call_callback.as_mut() {
                        if f(caller_id) {
                            module.answer_call();
                        }
                    }
                }
                module.state = State::StateInit;
            }
        }
        State::StateAtaSent => {
            info!("[Sim800L] Call connected");
            if module.call_state != CallState::Active {
                module.call_state = CallState::Active;
                if let Some(f) = module.config.call_connected_callback.as_mut() {
                    f();
                }
            }
            module.state = State::StateInit;
        }
        State::StateCheckCall => {
            if msg.contains("+CLCC:") && module.parse_index == 0 {
                module.expect_ack = true;

                if let Some(m) = msg.strip_prefix("+CLCC: ") {
                    let mut v = m.split(',').skip(2);

                    let current_call_state = CallState::from(
                        u8::from_str_radix(v.next().unwrap_or_default(), 10).unwrap_or(6),
                    );

                    if current_call_state != module.call_state {
                        if current_call_state == CallState::Incoming {
                            debug!(
                                "[Sim800L] Premature call state '4'. Ignoring, waiting for RING"
                            );
                        } else {
                            debug!("[Sim800L] Call state is now: {:?}", current_call_state);
                            if current_call_state == CallState::Active {
                                if let Some(f) = module.config.call_connected_callback.as_mut() {
                                    f();
                                }
                            }
                            module.call_state = current_call_state;
                        }
                    }
                } else {
                    debug!("[Sim800L] Invalid message {:?} {}", module.state, msg);
                    return Ok(());
                }
            } else if ok {
                if module.call_state != CallState::Disconnect {
                    // no call in progress
                    module.call_state = CallState::Disconnect; // Disconnect
                    if let Some(f) = module.config.call_disconnected_callback.as_mut() {
                        f();
                    }
                }
            }
            module.state = State::StateInit;
        }
        State::StateSendUssd1 => {
            module.push_cmd(BEGIN_SEND_USSD)?;
            uart.write_all(module.ussd.as_bytes())
                .map_err(SimError::IOError)?;
            module.push_cmd("\"")?;
            module.confirm_cmd()?;

            module.state = State::StateSendUssd2;
            module.expect_ack = true;
        }
        State::StateSendUssd2 => {
            debug!("[Sim800L] SendUssd2: '{}'", msg);
            if msg == "OK" {
                // Dialing
                debug!("[Sim800L] Dialing ussd code: '{}' done.", module.ussd);
                module.state = State::StateCheckUssd;
                module.send_ussd_pending = false;
            } else {
                module.registered = false;
                module.state = State::StateInit;
                module.send_cmd(ENABLE_CME_ERROR_VERBOSE)?;
                uart.write_all(&[CTRL_Z]).map_err(SimError::IOError)?;
            }
        }
        State::StateCheckUssd => {
            debug!("[Sim800L] Check ussd code: '{}'", msg);
            if msg.contains("+CUSD:") {
                module.state = State::StateReceivedUssd;
                module.ussd.clear();

                if let Some(m) = msg.strip_prefix("+CUSD: ") {
                    let mut split = m.split(',').skip(1);

                    if let Some(ussd) = split.next() {
                        module.ussd.push_str(ussd.trim_matches('"'))?;
                        if let Some(f) = module.config.received_ussd_callback.as_mut() {
                            f(module.ussd.as_str());
                        }
                    }
                }
            }
            // Otherwise we receive another OK, we do nothing just wait polling to continuously check for SMS
            if msg == "OK" {
                module.state = State::StateInit;
            }
        }
        State::StateReceivedUssd => {
            // Let the buffer flush. Next poll will request to delete the parsed index message.
        }
        _ => {
            warning!("[Sim800L] Unhandled: {} - {:?}", msg, module.state);
        }
    }

    Ok(())
}