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
//! Inner main module.

use core::{
    array,
    cell::{Cell, UnsafeCell},
    str::FromStr,
};

use heapless::{String, format};

use crate::{
    Config,
    at_commands::{
        ANSWER_CALL, AT, CHECK_PIN_PROTECTED, CTRL_Z, DELETE_MESSAGE, ENABLE_GSM_CHARSET,
        HANG_UP_CALL, LIST_ALL_MESSAGES, LIST_CURRENT_CALLS,
    },
    buffer::RingBuffer,
    call_state::CallState,
    errors::SimError,
    log::{debug, error, info, trace},
    state_machine::{self, State},
};

const ASCII_CR: u8 = '\r' as u8;
const ASCII_LF: u8 = '\n' as u8;
const SIM800L_READ_BUFFER_LENGTH: usize = 1024;

const PHONE_NUMBER_MAX_LEN: usize = 24;
const MESSAGE_MAX_LEN: usize = 1024;

/// Main module.
pub struct SimX00X<
    'a,
    U: embedded_io::Write + embedded_io::WriteReady + embedded_io::Read + embedded_io::ReadReady,
    const QUEUE_LEN: usize,
> {
    /// UART instance
    pub(crate) uart: UnsafeCell<U>,
    /// Internal buffer used to store bytes read from the UART.
    pub(crate) uart_buffer: [u8; 1024],
    /// Index of the last read byte.
    pub(crate) uart_buffer_idx: usize,

    /// State of the state machine
    pub(crate) state: State,

    /// Component configuration
    pub(crate) config: Config<'a, QUEUE_LEN>,

    /// The SIM is locked with a PIN code
    pub(crate) pin_locked: bool,

    /// The device is currently registered to a network
    pub(crate) registered: bool,

    /// An operation which requires an ack has been completed
    pub(crate) expect_ack: bool,
    /// Watchdog to detect stalled component
    pub(crate) watchdog: Cell<u8>,
    pub(crate) parse_index: u8,

    /// A USSD is waiting to be sent
    pub(crate) send_ussd_pending: bool,
    /// Received USSD
    pub(crate) ussd: String<64>,

    /// An incoming call is waiting to be answered
    pub(crate) connect_pending: bool,
    /// An ongoing call is waiting to be hung up
    pub(crate) disconnect_pending: bool,

    // COMM
    /// SMS/call sender
    pub(crate) sender: String<PHONE_NUMBER_MAX_LEN>,

    // DIAL
    /// Call recipient
    pub(crate) recipient: String<PHONE_NUMBER_MAX_LEN>,
    /// A call is waiting to be performed
    pub(crate) dial_pending: bool,
    /// State of the call
    pub(crate) call_state: CallState,

    // SMS
    /// An SMS is waiting to be sent
    pub(crate) send_pending: bool,
    /// Received message
    pub(crate) message: String<MESSAGE_MAX_LEN>,
    /// Messages waiting to be sent
    pub(crate) outgoing_smses:
        RingBuffer<(String<PHONE_NUMBER_MAX_LEN>, String<MESSAGE_MAX_LEN>), QUEUE_LEN>,
}

impl<
    'a,
    U: embedded_io::Write + embedded_io::WriteReady + embedded_io::Read + embedded_io::ReadReady,
    const QUEUE_LEN: usize,
> SimX00X<'a, U, QUEUE_LEN>
{
    pub fn reset(&mut self) {
        self.uart_buffer_idx = 0;
        self.state = State::StateIdle;
        self.pin_locked = true;
        self.registered = false;
        self.send_ussd_pending = false;
        self.expect_ack = false;
        self.watchdog.set(0);
        self.parse_index = 0;
        self.ussd = String::new();
        self.connect_pending = false;
        self.disconnect_pending = false;
        self.sender = String::new();
        self.recipient = String::new();
        self.dial_pending = false;
        self.call_state = CallState::Disconnect;
        self.send_pending = false;
        self.message = String::new();
        self.outgoing_smses.reset();

        let uart = unsafe { &mut *self.uart.get() };
        let _ = uart.flush();
        if uart.read_ready().is_ok_and(|x| x) {
            let _ = uart.read(&mut self.uart_buffer);
        }
    }

    /// Create a new `Sim800L` component.
    /// Parameters:
    /// * `uart`: UART peripheral
    /// * `config`: Configuration component
    pub fn new(uart: U, config: Config<'a, QUEUE_LEN>) -> Self {
        Self {
            uart: UnsafeCell::new(uart),
            uart_buffer: [0; 1024],
            uart_buffer_idx: 0,
            state: State::StateIdle,
            config,
            pin_locked: true,
            registered: false,
            send_ussd_pending: false,
            expect_ack: false,
            watchdog: Cell::new(0),
            parse_index: 0,
            ussd: String::new(),
            connect_pending: false,
            disconnect_pending: false,
            sender: String::new(),
            recipient: String::new(),
            dial_pending: false,
            call_state: CallState::Disconnect,
            send_pending: false,
            message: String::new(),
            outgoing_smses: RingBuffer::new(array::repeat((String::new(), String::new()))),
        }
    }

    pub(crate) fn push_cmd(&self, cmd: &str) -> Result<(), SimError<U>> {
        self.watchdog.set(0);

        if self.state == State::StatePoweringDown {
            return Err(SimError::PoweringDown);
        }

        unsafe { &mut *self.uart.get() }
            .write_all(cmd.as_bytes())
            .map_err(SimError::IOError)
    }
    pub(crate) fn confirm_cmd(&self) -> Result<(), SimError<U>> {
        self.watchdog.set(0);

        if self.state == State::StatePoweringDown {
            return Err(SimError::PoweringDown);
        }

        let uart = unsafe { &mut *self.uart.get() };
        uart.write_all(&[ASCII_CR]).map_err(SimError::IOError)?;
        uart.write_all(&[ASCII_LF]).map_err(SimError::IOError)
    }

    pub(crate) fn send_cmd(&self, cmd: &str) -> Result<(), SimError<U>> {
        self.watchdog.set(0);

        if self.state == State::StatePoweringDown {
            return Err(SimError::PoweringDown);
        }

        let uart = unsafe { &mut *self.uart.get() };

        uart.write_all(cmd.as_bytes()).map_err(SimError::IOError)?;
        uart.write_all(&[ASCII_CR]).map_err(SimError::IOError)?;
        uart.write_all(&[ASCII_LF]).map_err(SimError::IOError)
    }

    pub(crate) fn check_sms(&mut self) -> Result<(), SimError<U>> {
        self.send_cmd(LIST_ALL_MESSAGES)?;
        self.state = State::StateParseSmsResponse;
        self.parse_index = 0;
        Ok(())
    }

    pub fn update(&mut self) -> Result<(), SimError<U>> {
        if self.state == State::StatePoweredDown {
            return Err(SimError::PoweredDown);
        }

        self.watchdog.update(|x| x + 1);

        info!("WATCHDOG: {}", self.watchdog.get()); // TODO: remove me
        if self.watchdog.get() >= 10 {
            if let Some(f) = self.config.module_stalled_callback.as_mut() {
                if f() {
                    error!("[Sim800L] Module stalled. Resetting...");
                    self.reset();
                    debug!("[Sim800L] Reset OK.");
                } else {
                    error!(
                        "[Sim800L] Module stalled but the callback returned false. Not resetting."
                    );
                }
            } else {
                error!("[Sim800L] Module stalled but the callback is not set. Not resetting.");
            }
            return Err(SimError::ModuleStalled);
        }

        if self.watchdog.get() == 3 {
            self.state = State::StateInit;
            unsafe { &mut *self.uart.get() }
                .write_all(&[CTRL_Z])
                .map_err(SimError::IOError)?;
        }

        if self.expect_ack {
            return Ok(());
        }

        if self.state == State::StateInit {
            if self.registered && self.send_pending && self.outgoing_smses.cons_avail() {
                self.send_cmd(ENABLE_GSM_CHARSET)?;
                self.state = State::StateSendingSms1;
            } else if self.registered && self.dial_pending {
                self.send_cmd(ENABLE_GSM_CHARSET)?;
                self.state = State::StateDialing1;
            } else if self.registered && self.connect_pending {
                self.connect_pending = false;
                info!("[Sim800L] Answering call...");
                self.send_cmd(ANSWER_CALL)?;
                self.state = State::StateAtaSent;
            } else if self.registered && self.send_ussd_pending {
                self.send_cmd(ENABLE_GSM_CHARSET)?;
                self.state = State::StateSendUssd1;
            } else if self.registered && self.disconnect_pending {
                self.disconnect_pending = false;
                info!("[Sim800L] Disconnecting");
                self.send_cmd(HANG_UP_CALL)?;
            } else if self.registered && self.call_state != CallState::Disconnect {
                self.send_cmd(LIST_CURRENT_CALLS)?;
                self.state = State::StateCheckCall;
                return Ok(());
            } else if self.pin_locked {
                self.send_cmd(CHECK_PIN_PROTECTED)?;
                self.state = State::StateCheckPin;
                return Ok(());
            } else {
                self.send_cmd(AT)?;
                self.state = State::StateSetupCmgf;
            }

            self.expect_ack = true;
        } else if self.state == State::StateSmsReceived {
            // Serial Buffer should have been flushed.
            // Send cmd to delete received sms
            self.push_cmd(DELETE_MESSAGE)?;
            self.push_cmd(format!(12; "{}", self.parse_index)?.as_str())?;
            self.confirm_cmd()?;

            self.state = State::StateCheckSms;
            self.expect_ack = true;
        }

        Ok(())
    }

    /// Attempts to read a byte from the UART RX channel, acting accordingly when a full response is found.
    /// This method has to be run multiple times in a second, ideally, in the application's main loop.
    pub fn tick(&mut self) -> Result<(), SimError<U>> {
        if self.state == State::StatePoweredDown {
            return Err(SimError::PoweredDown);
        }

        let mut byte = [0];
        let uart = unsafe { &mut *self.uart.get() };

        // Read message
        while uart.read_ready().is_ok_and(|r| r)
            && uart.read(&mut byte).map_err(SimError::IOError)? > 0
        {
            let mut byte = byte[0];

            if self.uart_buffer_idx == SIM800L_READ_BUFFER_LENGTH {
                self.uart_buffer_idx = 0;
            }

            if byte == ASCII_CR as u8 {
                continue;
            }

            if byte >= 0x7F {
                byte = '?' as u8; // need to be valid utf8 string for log functions.
            }
            self.uart_buffer[self.uart_buffer_idx] = byte;

            if self.state == State::StateSendingSms2
                && self.uart_buffer_idx == 0
                && byte == '>' as u8
            {
                self.uart_buffer_idx += 1;
                self.uart_buffer[self.uart_buffer_idx] = ASCII_LF as u8;
            }

            if self.uart_buffer[self.uart_buffer_idx] == ASCII_LF as u8 {
                trace!(
                    "End of response: {} - {}",
                    &self.uart_buffer[..self.uart_buffer_idx],
                    unsafe { str::from_utf8_unchecked(&self.uart_buffer[..self.uart_buffer_idx]) }
                );

                state_machine::parse_cmd(self)?;

                self.uart_buffer_idx = 0;
            } else {
                self.uart_buffer_idx += 1;
            }
        }

        if self.state == State::StateInit
            && self.registered
            && (self.call_state != CallState::Disconnect  // A call is in progress
               || self.send_pending || self.dial_pending || self.connect_pending || self.disconnect_pending)
        {
            self.update()?;
        }

        Ok(())
    }

    // ############################################## ACTIONS ##############################################

    /// Powers down the SIM in a safe way.
    /// See `AT+CPOWD=1` in the SIM datasheet.
    pub fn power_off_normally(&mut self) -> Result<(), SimError<U>> {
        self.send_cmd("AT+CPOWD=1")?;
        self.state = State::StatePoweringDown;
        Ok(())
    }

    /// Powers down the SIM without waiting for a response.
    /// See `AT+CPOWD=0` in the SIM datasheet.
    ///
    /// # Safety
    /// This method attempts to fully reset the module, but it is up to the user to check that it is
    /// actually reset when the SIM is powered up again.
    pub unsafe fn power_off_urgently(&mut self) -> Result<(), SimError<U>> {
        self.send_cmd("AT+CPOWD=0")?;
        self.reset();
        Ok(())
    }

    /// Enables SIM's full functionality mode.
    ///
    /// For SIM800L/SIM800H, the datasheet reports a current consumption of 1.04 mA.
    pub fn enable_full_functionality_mode(&mut self) -> Result<(), SimError<U>> {
        self.send_cmd("AT+CFUN=1")
    }

    /// Enables SIM's minimum functionality mode (disables RF function and SIM card function).
    ///
    /// For SIM800L/SIM800H, the datasheet reports a current consumption of 0.83 mA.
    pub fn enable_minimum_functionality_mode(&mut self) -> Result<(), SimError<U>> {
        self.send_cmd("AT+CFUN=0")
    }

    /// Enables SIM's flight mode (disables RF function).
    ///
    /// For SIM800L/SIM800H, the datasheet reports a current consumption of 0.92 mA.
    pub fn enable_flight_mode(&mut self) -> Result<(), SimError<U>> {
        self.send_cmd("AT+CFUN=4")
    }

    /// Send an SMS with content `sms` to a recipient `recipient`.
    pub fn enqueue_sms(&mut self, recipient: &str, sms: &'a str) -> Result<(), SimError<U>> {
        if !self.outgoing_smses.push((
            String::from_str(recipient).unwrap(),
            String::from_str(sms).unwrap(),
        )) {
            return Err(SimError::SmsQueueLimitReached);
        }

        self.send_pending = true;
        Ok(())
    }

    /// Send a USSD.
    pub fn send_ussd(&mut self, ussd: &str) -> Result<(), SimError<U>> {
        self.ussd.clear();
        self.ussd.push_str(ussd)?;
        self.send_ussd_pending = true;
        self.update()
    }

    /// Dial a number.
    pub fn dial(&mut self, number: &str) -> Result<(), SimError<U>> {
        self.recipient.clear();
        self.recipient.push_str(number)?;
        self.dial_pending = true;
        Ok(())
    }

    /// Answer an incoming call.
    pub(crate) fn answer_call(&mut self) {
        self.connect_pending = true;
    }

    /// Hang up an ongoing call.
    pub fn hang_up_call(&mut self) {
        self.disconnect_pending = true;
    }
}