ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
sim800l.cpp
Go to the documentation of this file.
1#include "sim800l.h"
3#include "esphome/core/log.h"
4#include <cstring>
5
6namespace esphome::sim800l {
7
8ESPHOME_LOG_TAG(TAG, "sim800l");
9
10const char ASCII_CR = 0x0D;
11const char ASCII_LF = 0x0A;
12
14 if (this->watch_dog_++ == 2) {
15 this->state_ = STATE_INIT;
16 this->write(26);
17 // The module may have restarted, enable DTMF detection again
18 this->dtmf_ready_ = false;
19 }
20
21 if (this->expect_ack_)
22 return;
23
24 if (state_ == STATE_INIT) {
25 if (this->registered_ && this->send_pending_) {
26 this->send_cmd_("AT+CSCS=\"GSM\"");
28 } else if (this->registered_ && this->dial_pending_) {
29 this->send_cmd_("AT+CSCS=\"GSM\"");
30 this->state_ = STATE_DIALING1;
31 } else if (this->registered_ && this->connect_pending_) {
32 this->connect_pending_ = false;
33 ESP_LOGI(TAG, "Connecting");
34 this->send_cmd_("ATA");
35 this->state_ = STATE_ATA_SENT;
36 } else if (this->registered_ && this->send_ussd_pending_) {
37 this->send_cmd_("AT+CSCS=\"GSM\"");
39 } else if (this->registered_ && this->disconnect_pending_) {
40 this->disconnect_pending_ = false;
41 ESP_LOGI(TAG, "Disconnecting");
42 this->send_cmd_("ATH");
43 } else if (this->registered_ && this->call_state_ != 6) {
44 send_cmd_("AT+CLCC");
46 return;
47 } else {
48 this->send_cmd_("AT");
50 }
51 this->expect_ack_ = true;
52 } else if (state_ == STATE_RECEIVED_SMS) {
53 // Serial Buffer should have flushed.
54 // Send cmd to delete received sms
55 char delete_cmd[20]; // "AT+CMGD=" (8) + uint8_t (max 3) + null = 12 <= 20
56 buf_append_printf(delete_cmd, sizeof(delete_cmd), 0, "AT+CMGD=%d", this->parse_index_);
57 this->send_cmd_(delete_cmd);
58 this->state_ = STATE_CHECK_SMS;
59 this->expect_ack_ = true;
60 }
61}
62
63void Sim800LComponent::send_cmd_(const std::string &message) {
64 ESP_LOGV(TAG, "S: %s - %d", message.c_str(), this->state_);
65 this->watch_dog_ = 0;
66 this->write_str(message.c_str());
67 this->write_byte(ASCII_CR);
68 this->write_byte(ASCII_LF);
69}
70
72 if (message.empty())
73 return;
74
75 ESP_LOGV(TAG, "R: %s - %d", message.c_str(), this->state_);
76
77 if (this->state_ != STATE_RECEIVE_SMS) {
78 if (message == "RING") {
79 // Incoming call...
81 this->expect_ack_ = false;
82 } else if (message == "NO CARRIER") {
83 if (this->call_state_ != 6) {
84 this->call_state_ = 6;
85 this->call_disconnected_callback_.call();
86 }
87 } else if (message.starts_with("+DTMF:")) {
88 // Unsolicited DTMF key report: "+DTMF: <key>[,<duration>]"
89 size_t start = message.find_first_not_of(' ', 6);
90 if (start != std::string::npos) {
91 std::string key = message.substr(start, message.find(',', start) - start);
92 ESP_LOGD(TAG, "DTMF received: %s", key.c_str());
93 this->dtmf_received_callback_.call(key);
94 }
95 return;
96 }
97 }
98
99 bool ok = message == "OK";
100 if (this->expect_ack_) {
101 this->expect_ack_ = false;
102 if (!ok) {
103 if (this->state_ == STATE_SETUP_CMGF && message == "AT") {
104 // Expected ack but AT echo received
106 this->expect_ack_ = true;
107 } else if (this->state_ == STATE_DDET_SENT) {
108 if (message != "ERROR" && !message.starts_with("+CME ERROR:")) {
109 // Unrelated unsolicited line, keep waiting for the DDET response
110 this->expect_ack_ = true;
111 return;
112 }
113 // Module firmware without DTMF support, carry on with the setup sequence
114 ESP_LOGW(TAG, "DTMF detection not supported by the module: %s", message.c_str());
115 } else {
116 ESP_LOGW(TAG, "Not ack. %d %s", this->state_, message.c_str());
117 this->state_ = STATE_IDLE; // Let it timeout
118 return;
119 }
120 }
121 } else if (ok && (this->state_ != STATE_PARSE_SMS_RESPONSE && this->state_ != STATE_CHECK_CALL &&
122 this->state_ != STATE_RECEIVE_SMS && this->state_ != STATE_DIALING2)) {
123 ESP_LOGW(TAG, "Received unexpected OK. Ignoring");
124 return;
125 }
126
127 switch (this->state_) {
128 case STATE_INIT: {
129 // While we were waiting for update to check for messages, this notifies a message
130 // is available.
131 bool message_available = message.starts_with("+CMTI:");
132 if (!message_available) {
133 if (message == "RING") {
134 // Incoming call...
135 this->state_ = STATE_PARSE_CLIP;
136 } else if (message == "NO CARRIER") {
137 if (this->call_state_ != 6) {
138 this->call_state_ = 6;
139 this->call_disconnected_callback_.call();
140 }
141 } else if (message.starts_with("+CUSD:")) {
142 // Incoming USSD MESSAGE
143 this->state_ = STATE_CHECK_USSD;
144 }
145 break;
146 }
147
148 [[fallthrough]];
149 }
150 case STATE_CHECK_SMS:
151 send_cmd_("AT+CMGL=\"ALL\"");
153 this->parse_index_ = 0;
154 break;
156 send_cmd_("ATE0");
157 this->state_ = STATE_SETUP_CMGF;
158 this->expect_ack_ = true;
159 break;
160 case STATE_SETUP_CMGF:
161 send_cmd_("AT+CMGF=1");
162 this->state_ = STATE_SETUP_CLIP;
163 this->expect_ack_ = true;
164 break;
165 case STATE_SETUP_CLIP:
166 send_cmd_("AT+CLIP=1");
167 this->state_ = this->dtmf_enabled_ && !this->dtmf_ready_ ? STATE_SETUP_DDET : STATE_CREG;
168 this->expect_ack_ = true;
169 break;
170 case STATE_SETUP_DDET:
171 send_cmd_("AT+DDET=1");
172 this->state_ = STATE_DDET_SENT;
173 this->expect_ack_ = true;
174 break;
175 case STATE_SETUP_USSD:
176 send_cmd_("AT+CUSD=1");
177 this->state_ = STATE_CREG;
178 this->expect_ack_ = true;
179 break;
180 case STATE_SEND_USSD1:
181 this->send_cmd_("AT+CUSD=1, \"" + this->ussd_ + "\"");
182 this->state_ = STATE_SEND_USSD2;
183 this->expect_ack_ = true;
184 break;
185 case STATE_SEND_USSD2:
186 ESP_LOGD(TAG, "SendUssd2: '%s'", message.c_str());
187 if (message == "OK") {
188 // Dialing
189 ESP_LOGD(TAG, "Dialing ussd code: '%s' done.", this->ussd_.c_str());
190 this->state_ = STATE_CHECK_USSD;
191 this->send_ussd_pending_ = false;
192 } else {
193 this->set_registered_(false);
194 this->state_ = STATE_INIT;
195 this->send_cmd_("AT+CMEE=2");
196 this->write(26);
197 }
198 break;
199 case STATE_CHECK_USSD:
200 ESP_LOGD(TAG, "Check ussd code: '%s'", message.c_str());
201 if (message.starts_with("+CUSD:")) {
203 size_t start = 10;
204 size_t end = message.find_last_of(',');
205 if (end > start) {
206 // Not stored in ussd_: send_ussd() from a listener would overwrite the text the others receive
207 this->ussd_received_callback_.call(message.substr(start + 1, end - start - 2));
208 }
209 }
210 // Otherwise we receive another OK, we do nothing just wait polling to continuously check for SMS
211 if (message == "OK")
212 this->state_ = STATE_INIT;
213 break;
214 case STATE_DDET_SENT:
215 // Tried once per module reset; firmware without DDET only logs a warning, and a passing error is retried
216 // after the next reset
217 this->dtmf_ready_ = true;
218 [[fallthrough]];
219 case STATE_CREG:
220 send_cmd_("AT+CREG?");
221 this->state_ = STATE_CREG_WAIT;
222 break;
223 case STATE_CREG_WAIT: {
224 // Response: "+CREG: 0,1" -- the one there means registered ok
225 // "+CREG: -,-" means not registered ok
226 bool registered = message.size() > 9 && message.starts_with("+CREG:") && (message[9] == '1' || message[9] == '5');
227 if (registered) {
228 if (!this->registered_) {
229 ESP_LOGD(TAG, "Registered OK");
230 }
231 this->state_ = STATE_CSQ;
232 this->expect_ack_ = true;
233 } else {
234 ESP_LOGW(TAG, "Registration Fail");
235 if (message.size() > 7 && message[7] == '0') { // Network registration is disabled, enable it
236 send_cmd_("AT+CREG=1");
237 this->expect_ack_ = true;
238 this->state_ = STATE_SETUP_CMGF;
239 } else {
240 // Keep waiting registration
241 this->state_ = STATE_INIT;
242 }
243 }
244 set_registered_(registered);
245 break;
246 }
247 case STATE_CSQ:
248 send_cmd_("AT+CSQ");
250 break;
252 if (message.starts_with("+CSQ:")) {
253 size_t comma = message.find(',', 6);
254 if (comma != 6) {
255 int rssi = parse_number<int>(message.substr(6, comma - 6)).value_or(0);
256
257#ifdef USE_SENSOR
258 if (this->rssi_sensor_ != nullptr) {
259 this->rssi_sensor_->publish_state(rssi);
260 } else {
261 ESP_LOGD(TAG, "RSSI: %d", rssi);
262 }
263#else
264 ESP_LOGD(TAG, "RSSI: %d", rssi);
265#endif
266 }
267 }
268 this->expect_ack_ = true;
269 this->state_ = STATE_CHECK_SMS;
270 break;
272 if (message.starts_with("+CMGL:") && this->parse_index_ == 0) {
273 size_t start = 7;
274 size_t end = message.find(',', start);
275 uint8_t item = 0;
276 while (end != start) {
277 item++;
278 if (item == 1) { // Slot Index
279 this->parse_index_ = parse_number<uint8_t>(message.substr(start, end - start)).value_or(0);
280 }
281 // item 2 = STATUS, usually "REC UNREAD"
282 if (item == 3) { // recipient
283 // Add 1 and remove 2 from substring to get rid of "quotes"
284 this->sender_ = message.substr(start + 1, end - start - 2);
285 this->message_.clear();
286 break;
287 }
288 // item 4 = ""
289 // item 5 = Received timestamp
290 start = end + 1;
291 end = message.find(',', start);
292 }
293
294 if (item < 2) {
295 ESP_LOGD(TAG, "Invalid message %d %s", this->state_, message.c_str());
296 return;
297 }
299 }
300 // Otherwise we receive another OK
301 if (ok) {
302 send_cmd_("AT+CLCC");
303 this->state_ = STATE_CHECK_CALL;
304 }
305 break;
306 case STATE_CHECK_CALL:
307 if (message.starts_with("+CLCC:") && this->parse_index_ == 0) {
308 this->expect_ack_ = true;
309 size_t start = 7;
310 size_t end = message.find(',', start);
311 uint8_t item = 0;
312 while (end != start) {
313 item++;
314 // item 1 call index for +CHLD
315 // item 2 dir 0 Mobile originated; 1 Mobile terminated
316 if (item == 3) { // stat
317 uint8_t current_call_state = parse_number<uint8_t>(message.substr(start, end - start)).value_or(6);
318 if (current_call_state != this->call_state_) {
319 if (current_call_state == 4) {
320 ESP_LOGV(TAG, "Premature call state '4'. Ignoring, waiting for RING");
321 } else {
322 this->call_state_ = current_call_state;
323 ESP_LOGD(TAG, "Call state is now: %d", current_call_state);
324 if (current_call_state == 0)
325 this->call_connected_callback_.call();
326 }
327 }
328 break;
329 }
330 // item 4 = ""
331 // item 5 = Received timestamp
332 start = end + 1;
333 end = message.find(',', start);
334 }
335
336 if (item < 2) {
337 ESP_LOGD(TAG, "Invalid message %d %s", this->state_, message.c_str());
338 return;
339 }
340 } else if (ok) {
341 if (this->call_state_ != 6) {
342 // no call in progress
343 this->call_state_ = 6; // Disconnect
344 this->call_disconnected_callback_.call();
345 }
346 }
347 this->state_ = STATE_INIT;
348 break;
350 /* Our recipient is set and the message body is in message
351 kick ESPHome callback now
352 */
353 if (ok || message.starts_with("+CMGL:")) {
354 ESP_LOGD(TAG,
355 "Received SMS from: %s\n"
356 " %s",
357 this->sender_.c_str(), this->message_.c_str());
358 this->sms_received_callback_.call(this->message_, this->sender_);
360 } else {
361 if (!this->message_.empty())
362 this->message_ += '\n';
363 this->message_ += message;
364 }
365 break;
368 // Let the buffer flush. Next poll will request to delete the parsed index message.
369 break;
371 this->send_cmd_("AT+CMGS=\"" + this->recipient_ + "\"");
373 break;
375 if (message == ">") {
376 // Send sms body
377 ESP_LOGI(TAG, "Sending to %s message: '%s'", this->recipient_.c_str(), this->outgoing_message_.c_str());
378 this->write_str(this->outgoing_message_.c_str());
379 this->write(26);
381 } else {
382 set_registered_(false);
383 this->state_ = STATE_INIT;
384 this->send_cmd_("AT+CMEE=2");
385 this->write(26);
386 }
387 break;
389 if (message.starts_with("+CMGS:")) {
390 ESP_LOGD(TAG, "SMS Sent OK: %s", message.c_str());
391 this->send_pending_ = false;
392 this->state_ = STATE_CHECK_SMS;
393 this->expect_ack_ = true;
394 }
395 break;
396 case STATE_DIALING1:
397 this->send_cmd_("ATD" + this->recipient_ + ';');
398 this->state_ = STATE_DIALING2;
399 break;
400 case STATE_DIALING2:
401 if (ok) {
402 ESP_LOGI(TAG, "Dialing: '%s'", this->recipient_.c_str());
403 this->dial_pending_ = false;
404 } else {
405 this->set_registered_(false);
406 this->send_cmd_("AT+CMEE=2");
407 this->write(26);
408 }
409 this->state_ = STATE_INIT;
410 break;
411 case STATE_PARSE_CLIP:
412 if (message.starts_with("+CLIP:")) {
413 std::string caller_id;
414 size_t start = 7;
415 size_t end = message.find(',', start);
416 uint8_t item = 0;
417 while (end != start) {
418 item++;
419 if (item == 1) { // Slot Index
420 // Add 1 and remove 2 from substring to get rid of "quotes"
421 caller_id = message.substr(start + 1, end - start - 2);
422 break;
423 }
424 // item 4 = ""
425 // item 5 = Received timestamp
426 start = end + 1;
427 end = message.find(',', start);
428 }
429 if (this->call_state_ != 4) {
430 this->call_state_ = 4;
431 ESP_LOGI(TAG, "Incoming call from %s", caller_id.c_str());
432 incoming_call_callback_.call(caller_id);
433 }
434 this->state_ = STATE_INIT;
435 }
436 break;
437 case STATE_ATA_SENT:
438 ESP_LOGI(TAG, "Call connected");
439 if (this->call_state_ != 0) {
440 this->call_state_ = 0;
441 this->call_connected_callback_.call();
442 }
443 this->state_ = STATE_INIT;
444 break;
445 default:
446 ESP_LOGW(TAG, "Unhandled: %s - %d", message.c_str(), this->state_);
447 break;
448 }
449} // namespace sim800l
450
451void Sim800LComponent::loop() {
452 // Read message
453 this->read_available([this](uint8_t byte) {
454 ESP_LOGVV(TAG, "Buffer pos: %u %d", this->line_reader_.length(), byte); // NOLINT
455
456 if (byte >= 0x7F)
457 byte = '?'; // need to be valid utf8 string for log functions.
458 const char *line = this->line_reader_.feed(byte);
459 if (line == nullptr && this->state_ == STATE_SENDING_SMS_2 && byte == '>' && this->line_reader_.length() == 1) {
460 // The send prompt has no line end
461 line = this->line_reader_.partial();
462 this->line_reader_.reset();
463 }
464 if (line != nullptr) {
465 this->parse_cmd_(line);
466 } else {
468 }
469 });
470 if (state_ == STATE_INIT && this->registered_ &&
471 (this->call_state_ != 6 // A call is in progress
472 || this->send_pending_ || this->dial_pending_ || this->connect_pending_ || this->disconnect_pending_)) {
473 this->update();
474 }
475}
476
477void Sim800LComponent::send_sms(const std::string &recipient, const std::string &message) {
478 this->recipient_ = recipient;
480 this->send_pending_ = true;
481}
482
483void Sim800LComponent::send_ussd(const std::string &ussd_code) {
484 ESP_LOGD(TAG, "Sending USSD code: %s", ussd_code.c_str());
485 this->ussd_ = ussd_code;
486 this->send_ussd_pending_ = true;
487 this->update();
488}
489void Sim800LComponent::dump_config() {
490 ESP_LOGCONFIG(TAG, "SIM800L:");
491#ifdef USE_BINARY_SENSOR
492 LOG_BINARY_SENSOR(" ", "Registered", this->registered_binary_sensor_);
493#endif
494#ifdef USE_SENSOR
495 LOG_SENSOR(" ", "Rssi", this->rssi_sensor_);
496#endif
497}
498void Sim800LComponent::dial(const std::string &recipient) {
499 this->recipient_ = recipient;
500 this->dial_pending_ = true;
501}
502void Sim800LComponent::connect() { this->connect_pending_ = true; }
503void Sim800LComponent::disconnect() { this->disconnect_pending_ = true; }
504
506 this->registered_ = registered;
507#ifdef USE_BINARY_SENSOR
508 PUBLISH_STATE(this->registered_binary_sensor_, registered);
509#endif
510}
511
512} // namespace esphome::sim800l
const char * partial()
The partial line, NUL terminated, for prompts with no line end; the first N - 1 characters on the byt...
Definition line_reader.h:60
size_t length() const
Length of the partial line; 0 after a line is returned and while an overlong line is dropped.
Definition line_reader.h:56
char * feed(uint8_t c)
Feed one byte; returns the completed line (empty lines included), valid until the next call,...
Definition line_reader.h:23
void reset()
Forget the partial line and start a new one with the next byte.
Definition line_reader.h:76
void log_if_overflowed(const char *tag) const
Log the shared "line dropped" warning when the last feed() overflowed.
Definition line_reader.h:69
virtual void update()=0
void send_cmd_(const std::string &message)
Definition sim800l.cpp:63
CallbackManager< void(const std::string &)> ussd_received_callback_
Definition sim800l.h:121
CallbackManager< void()> call_connected_callback_
Definition sim800l.h:119
void set_registered_(bool registered)
Definition sim800l.cpp:505
CallbackManager< void(const std::string &)> incoming_call_callback_
Definition sim800l.h:118
void parse_cmd_(std::string message)
Definition sim800l.cpp:71
CallbackManager< void()> call_disconnected_callback_
Definition sim800l.h:120
LineReader< SIM800L_READ_BUFFER_LENGTH > line_reader_
Definition sim800l.h:98
CallbackManager< void(const std::string &)> dtmf_received_callback_
Definition sim800l.h:122
CallbackManager< void(const std::string &, const std::string &)> sms_received_callback_
Definition sim800l.h:117
void write_str(const char *str)
Definition uart.h:37
void write_byte(uint8_t data)
Definition uart.h:22
bool read_available(F &&on_byte)
Same as read_available_chunks(), calling on_byte(uint8_t) once per byte.
Definition uart.h:77
size_t write(uint8_t data)
Definition uart.h:105
const LogString * message
Definition component.cpp:35
const char * key
@ STATE_PARSE_SMS_RESPONSE
Definition sim800l.h:34
ESPHOME_LOG_TAG(TAG, "sim800l")
const char ASCII_LF
Definition sim800l.cpp:11
const char ASCII_CR
Definition sim800l.cpp:10
optional< T > parse_number(const char *str)
Parse an unsigned decimal number from a null-terminated string.
Definition helpers.h:1430
uint8_t end[39]
Definition sun_gtil2.cpp:17