ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
modem_component.cpp
Go to the documentation of this file.
1#ifdef USE_ESP32
2#include "modem_component.h"
3#include "soc/soc_caps.h"
4#include <driver/uart.h>
5
8#include "esphome/core/log.h"
12
13#include <esp_event.h>
14#include <esp_netif.h>
15#include <esp_netif_ppp.h>
16
17#include <algorithm>
18#include <cinttypes>
19#include <cmath>
20#include <cstring>
21#include <iterator>
22
23namespace esphome::modem {
24
25using esp_modem::command_result;
26using esp_modem::create_uart_dte;
27using esp_modem::DTE;
28using esp_modem::modem_mode;
29
30ESPHOME_LOG_TAG(TAG, "modem");
31
32#ifdef SOC_UART_HP_NUM
33static constexpr int HP_UART_COUNT = SOC_UART_HP_NUM;
34#else
35static constexpr int HP_UART_COUNT = UART_NUM_MAX;
36#endif
37
38ModemComponent *global_modem_component = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
39
40static constexpr uint32_t WAIT_IP_TIMEOUT_MS = 50000;
41static constexpr uint32_t PROBE_TIMEOUT_MS = 100;
42// A silent modem is not going to answer the next second, so its probes are spaced out, doubling up to a minute
43static constexpr uint32_t PROBE_RETRY_DELAY_MS = 5000;
44static constexpr uint32_t PROBE_RETRY_MAX_MS = 60000;
45// How long the task waits for the main loop to run on_sync before attaching
46static constexpr uint32_t SYNC_ACK_TIMEOUT_MS = 5000;
47// esp_modem's command strings and the log lines are built on this stack
48static constexpr uint32_t TASK_STACK_SIZE = 5120;
49#ifdef USE_MODEM_PIN_CODE
50// AT+CPIN= can take a few seconds; the SIM may need longer still before AT+CPIN? says READY
51static constexpr uint32_t PIN_TIMEOUT_MS = 5000;
52static constexpr uint32_t PIN_UNLOCK_WAIT_MS = 10000;
53// Sends of one pin_code the SIM has not confirmed with READY, across reboots, before it is not sent again
54static constexpr uint8_t PIN_MAX_UNCONFIRMED_SENDS = 2;
55#endif
56// The attachment is polled every 4 s; the signal and operator queries only every 4th poll
57static constexpr uint32_t ATTACH_POLL_MS = 4000;
58static constexpr uint8_t ATTACH_DIAG_EVERY = 4;
59static constexpr int RADIO_STATE_MINIMUM = 0; // CFUN=0: radio off and the SIM powered down
60static constexpr int RADIO_STATE_RF_OFF = 4; // CFUN=4: transmit and receive off, SIM still powered
61static constexpr uint8_t UART_EVENT_QUEUE_SIZE = 10;
62static constexpr uint32_t BAUD_PREF_HASH = 76007670UL;
63static constexpr uint32_t PIN_PREF_HASH = 76007671UL;
64static constexpr int FALLBACK_BAUD_RATE = 115200;
65
66// Indexed by ModemState
67PROGMEM_STRING_TABLE(ModemStateStrings, "DISABLED", "ENABLING", "SYNCED", "CONNECTING", "WAIT_IP", "CONNECTED",
68 "DISCONNECTING", "UNKNOWN");
69static const LogString *state_to_str(ModemState state) {
70 return ModemStateStrings::get_log_str(static_cast<uint8_t>(state), ModemStateStrings::LAST_INDEX);
71}
72
73// Indexed by ModemFault
74PROGMEM_STRING_TABLE(ModemFaultStrings, "", "Modem not responding", "Configured baud rate failed",
75 "init_at command failed", "SIM not ready", "SIM locked", "SIM PIN not sent; check pin_code",
76 "PIN record not saved", "APN or radio setup failed", "No network attachment", "PPP link failed",
77 "Modem teardown failed");
78
79// Indexed by esp_modem::command_result
80PROGMEM_STRING_TABLE(CommandResultStrings, "OK", "FAIL", "TIMEOUT");
81static const LogString *result_to_str(command_result result) {
82 return CommandResultStrings::get_log_str(static_cast<uint8_t>(result), CommandResultStrings::LAST_INDEX);
83}
84
85ModemComponent::ModemComponent(InternalGPIOPin *tx_pin, InternalGPIOPin *rx_pin, const char *model, DceFactory factory,
86 const char *apn)
87 : tx_pin_(tx_pin), rx_pin_(rx_pin), model_(model), dce_factory_(factory), apn_(apn) {
89}
90
91void ModemComponent::enable() {
92 ESP_LOGI(TAG, "Setting modem target state to CONNECTED");
93 this->target_state_.store(ModemState::MODEM_STATE_CONNECTED);
94 this->probe_backoff_.store(0, std::memory_order_relaxed);
95 // A link that is already up has nothing to wait for; a lost one re-arms the timer itself
96 if (this->component_state_.load() != ModemState::MODEM_STATE_CONNECTED) {
97 this->arm_connect_timeout_();
98 }
99 this->wake_task_();
100}
101
102void ModemComponent::disable() {
103 ESP_LOGI(TAG, "Setting modem target state to DISABLED");
104 this->target_state_.store(ModemState::MODEM_STATE_DISABLED);
105 this->cancel_connect_timeout_();
106 this->wake_task_();
107}
108
109void ModemComponent::wake_task_() {
110 if (this->task_.is_created()) {
111 xTaskNotifyGive(this->task_.get_handle());
112 }
113}
114
115// Self-keyed so it still fires after a failed setup, where the component's own timers are skipped
116void ModemComponent::arm_connect_timeout_() {
117 // Measures time without a connection, like wifi: neither retry cycles nor a repeated enable() restart it
118 if (this->timeout_ == 0 || this->connect_timeout_armed_) {
119 return;
120 }
121 this->connect_timeout_armed_ = true;
122 App.scheduler.set_timeout(this, this->timeout_, [this]() {
123 // The task may have connected between enable() checking the state and arming this timer
124 this->connect_timeout_armed_ = false;
125 if (this->is_connected()) {
126 return;
127 }
128 ESP_LOGE(TAG, "Modem was not able to connect (timeout), rebooting");
129 App.reboot();
130 });
131}
132
133void ModemComponent::cancel_connect_timeout_() {
134 this->connect_timeout_armed_ = false;
135 App.scheduler.cancel_timeout(this);
136}
137
138network::IPAddresses ModemComponent::get_ip_addresses() {
139 network::IPAddresses addresses;
140 esp_netif_ip_info_t ip;
141 if (this->is_connected() && esp_netif_get_ip_info(this->ppp_netif_, &ip) == ESP_OK) {
142 addresses[0] = network::IPAddress(&ip.ip);
143#if USE_NETWORK_IPV6
144 network::fill_ip6_addresses(this->ppp_netif_, addresses);
145#endif /* USE_NETWORK_IPV6 */
146 }
147 return addresses;
148}
149
150void ModemComponent::fail_setup_(const LogString *reason) {
151 this->mark_failed(reason);
152 if (this->target_state_.load() == ModemState::MODEM_STATE_CONNECTED) {
153 this->arm_connect_timeout_();
154 }
155}
156
157// The status flags, the automations and the preferences belong to the main loop, so the task leaves the
158// work in pending_ and wakes loop()
159void ModemComponent::hand_over_(uint32_t pending) {
160 this->pending_.fetch_or(pending, std::memory_order_release);
161 this->enable_loop_soon_any_context();
162}
163
164// The task is the only writer, so a load and a store do; a byte-sized read-modify-write is a library call on Xtensa
165void ModemComponent::set_fault_(ModemFault fault) {
166 // A wrong baud_rate or init_at is kept apart, so it stays visible once the modem connects
167 if (fault == ModemFault::MODEM_FAULT_BAUD || fault == ModemFault::MODEM_FAULT_INIT_AT) {
168 this->config_fault_.store(fault, std::memory_order_relaxed);
169 }
170 if (this->fault_.load(std::memory_order_relaxed) != fault) {
171 this->fault_.store(fault, std::memory_order_relaxed);
172 this->hand_over_(PENDING_STATUS);
173 }
174}
175
176// The fault that ended the session says more than a failed cleanup after it
177void ModemComponent::set_teardown_fault_() {
178 if (this->fault_.load(std::memory_order_relaxed) == ModemFault::MODEM_FAULT_NONE) {
179 this->set_fault_(ModemFault::MODEM_FAULT_TEARDOWN);
180 }
181}
182
183void ModemComponent::clear_config_fault_(ModemFault fault) {
184 if (this->config_fault_.load(std::memory_order_relaxed) == fault) {
185 this->config_fault_.store(ModemFault::MODEM_FAULT_NONE, std::memory_order_relaxed);
186 this->hand_over_(PENDING_STATUS);
187 }
188}
189
190void ModemComponent::publish_status_() {
191 ModemFault fault = this->fault_.load(std::memory_order_relaxed);
192#ifdef USE_MODEM_PIN_CODE
193 if (this->pin_record_unsaved_) {
194 fault = ModemFault::MODEM_FAULT_PIN_RECORD;
195 }
196#endif
197 if (fault == ModemFault::MODEM_FAULT_NONE) {
198 fault = this->config_fault_.load(std::memory_order_relaxed);
199 }
200 if (fault == ModemFault::MODEM_FAULT_NONE) {
201 this->status_clear_warning();
202 this->status_clear_error();
203 return;
204 }
205 const LogString *message = ModemFaultStrings::get_log_str(static_cast<uint8_t>(fault), ModemFaultStrings::LAST_INDEX);
206 // These stop the modem until the SIM or pin_code is fixed
207 if (fault == ModemFault::MODEM_FAULT_SIM_LOCKED || fault == ModemFault::MODEM_FAULT_PIN_NOT_SENT ||
208 fault == ModemFault::MODEM_FAULT_PIN_RECORD) {
209 this->status_clear_warning();
210 this->status_set_error(message);
211 } else {
212 this->status_clear_error();
213 this->status_set_warning(message);
214 }
215}
216
217void ModemComponent::loop() {
218 const uint32_t pending = this->pending_.exchange(0, std::memory_order_acquire);
219 if (pending & (PENDING_ON_SYNC | PENDING_ON_CONNECT | PENDING_ON_DISCONNECT)) {
220 // The task waits for the sync hand-over, so a pending disconnect came before a pending sync; connected now
221 // means a pending disconnect also came before the pending connect
222 const bool disconnect_first =
223 (pending & PENDING_ON_DISCONNECT) && (this->is_connected() || (pending & PENDING_ON_SYNC));
224 if (disconnect_first) {
225 this->on_state_callback_.call(ModemState::MODEM_STATE_DISCONNECTING);
226 }
227 if (pending & PENDING_ON_SYNC) {
228 this->on_state_callback_.call(ModemState::MODEM_STATE_SYNCED);
229 this->sync_acked_.store(1, std::memory_order_release); // on_sync finished, so the task may attach
230 this->wake_task_();
231 }
232 if (pending & PENDING_ON_CONNECT) {
233 this->dump_connect_params_();
234 this->on_state_callback_.call(ModemState::MODEM_STATE_CONNECTED);
235 }
236 if ((pending & PENDING_ON_DISCONNECT) && !disconnect_first) {
237 this->on_state_callback_.call(ModemState::MODEM_STATE_DISCONNECTING);
238 }
239 }
240 if (pending & PENDING_STATUS) {
241 this->publish_status_();
242 }
243 if (pending & PENDING_CONNECT_TIMEOUT) {
244 if (this->target_state_.load() == ModemState::MODEM_STATE_CONNECTED && !this->is_connected()) {
245 this->arm_connect_timeout_();
246 } else {
247 this->cancel_connect_timeout_();
248 }
249 }
250 if ((pending & PENDING_SAVE_BAUD) && !this->pref_.save(&this->restored_baud_)) {
251 ESP_LOGW(TAG, "Failed to save the baud rate");
252 }
253#ifdef USE_MODEM_PIN_CODE
254 // Written through at once: a power cycle before the periodic flush would send the PIN again
255 if (pending & PENDING_SAVE_PIN) {
256 // The task leaves pin_record_ alone until pin_save_state_ reports the outcome
257 const bool saved = this->pin_pref_.save(&this->pin_record_) && global_preferences->sync();
258 if (!saved) {
259 ESP_LOGE(TAG, "Failed to save the PIN record");
260 }
261 // A power cycle could send a refused PIN again, so a failed save shows until a later one succeeds
262 if (this->pin_record_unsaved_ != !saved) {
263 this->pin_record_unsaved_ = !saved;
264 this->publish_status_();
265 }
266 this->pin_save_state_.store(saved ? PinSave::PIN_SAVE_DONE : PinSave::PIN_SAVE_FAILED, std::memory_order_release);
267 this->wake_task_();
268 }
269#endif
270#ifdef USE_MODEM_POLL
271 if (pending & PENDING_ON_DISCONNECT) {
272 // A lost link must not keep showing the last healthy reading, nor one taken before it dropped
273 this->poll_unpublished_.store(0, std::memory_order_release);
274 this->publish_readings_(CSQ_UNKNOWN, CSQ_UNKNOWN, NETWORK_MODE_NO_SERVICE);
275 } else if (this->poll_unpublished_.load(std::memory_order_acquire)) {
276 this->publish_readings_(this->poll_rssi_, this->poll_ber_, this->poll_mode_);
277 this->poll_unpublished_.store(0, std::memory_order_release);
278 }
279#endif
280#ifdef USE_MODEM_URC
281 if (this->urc_pending_.load(std::memory_order_acquire)) {
282 this->urc_text_sensor_->publish_state(this->urc_line_);
283 this->urc_pending_.store(0, std::memory_order_release);
284 }
285#endif
286 // A hand-over after these checks re-enables the loop through enable_loop_soon_any_context()
287 if (this->pending_.load(std::memory_order_acquire) == 0) {
288 this->disable_loop();
289 }
290}
291
292void ModemComponent::setup() {
293 this->pref_ = global_preferences->make_preference<int>(BAUD_PREF_HASH);
294 this->pref_.load(&this->restored_baud_);
295#ifdef USE_MODEM_PIN_CODE
296 this->pin_pref_ = global_preferences->make_preference<PinRecord>(PIN_PREF_HASH);
297 if (!this->pin_pref_.load(&this->pin_record_)) {
298 // Also the first boot with pin_code; after a flash fault the send count starts over
299 ESP_LOGD(TAG, "No PIN record stored");
300 }
301 // A changed pin_code starts with a clean record and may be sent again
302 const uint32_t pin_hash = fnv1_hash(this->pin_code_);
303 if (this->pin_record_.hash != pin_hash) {
304 this->pin_record_ = PinRecord{pin_hash, 0};
305 if (!this->pin_pref_.save(&this->pin_record_)) {
306 ESP_LOGW(TAG, "Failed to clear the PIN record");
307 }
308 }
309#else
310 // A build without pin_code forgets the count, so flashing once without it clears the record
311 {
312 auto pin_pref = global_preferences->make_preference<PinRecord>(PIN_PREF_HASH);
313 PinRecord record{};
314 if (pin_pref.load(&record) && record.hash != 0) {
315 record = PinRecord{};
316 if (!pin_pref.save(&record)) {
317 ESP_LOGW(TAG, "Failed to clear the PIN record");
318 }
319 }
320 }
321#endif
322
323 // Highest free high-performance port first; UART0 stays with the logger and the low-power UART of the
324 // C6/P4 has restricted pins and clocks
325 for (int p = HP_UART_COUNT - 1; p > UART_NUM_0; p--) {
326 if (!uart_is_driver_installed(static_cast<uart_port_t>(p))) {
327 this->uart_port_ = p;
328 break;
329 }
330 }
331 if (this->uart_port_ == UART_NUM_MAX) {
332 this->mark_failed(LOG_STR("No free UART port for modem"));
333 return;
334 }
335
336 esp_netif_config_t netif_ppp_config = ESP_NETIF_DEFAULT_PPP();
337 this->ppp_netif_ = esp_netif_new(&netif_ppp_config);
338 if (this->ppp_netif_ == nullptr) {
339 this->fail_setup_(LOG_STR("PPP netif creation failed"));
340 return;
341 }
342
343 auto ip_event = [](void *arg, esp_event_base_t, int32_t event_id, void *event_data) {
344 const bool got_ip = event_id == IP_EVENT_PPP_GOT_IP;
345 if (!got_ip && event_id != IP_EVENT_PPP_LOST_IP) {
346 return;
347 }
348 if (got_ip) {
349 ESP_LOGD(TAG, "PPP IP event: Got IP " IPSTR, IP2STR(&static_cast<ip_event_got_ip_t *>(event_data)->ip_info.ip));
350 } else {
351 ESP_LOGD(TAG, "PPP IP event: Lost IP");
352 }
353 auto *self = static_cast<ModemComponent *>(arg);
354 self->got_ip_.store(got_ip, std::memory_order_release);
355 self->wake_task_();
356 };
357 // A dead peer or an LCP failure is reported here, not as a lost IP event; esp_modem enables these
358 // error events itself when it attaches the netif
359 auto ppp_status = [](void *arg, esp_event_base_t, int32_t event_id, void *) {
360 if (event_id < NETIF_PP_PHASE_OFFSET && event_id != NETIF_PPP_ERRORNONE) {
361 ESP_LOGW(TAG, "PPP error %d", static_cast<int>(event_id));
362 auto *self = static_cast<ModemComponent *>(arg);
363 self->ppp_error_.store(static_cast<uint8_t>(event_id), std::memory_order_release);
364 self->got_ip_.store(0, std::memory_order_release);
365 self->wake_task_();
366 }
367 };
368 if (esp_event_handler_register(IP_EVENT, ESP_EVENT_ANY_ID, ip_event, this) != ESP_OK ||
369 esp_event_handler_register(NETIF_PPP_STATUS, ESP_EVENT_ANY_ID, ppp_status, this) != ESP_OK) {
370 this->fail_setup_(LOG_STR("Event handler register failed"));
371 return;
372 }
373
374 // The DTE and DCE live for the life of the program; a baud probe only changes the UART divisor
375 esp_modem_dte_config_t dte_config = ESP_MODEM_DTE_DEFAULT_CONFIG();
376 dte_config.uart_config.tx_io_num = this->tx_pin_->get_pin();
377 dte_config.uart_config.rx_io_num = this->rx_pin_->get_pin();
378 dte_config.uart_config.rx_buffer_size = this->rx_buffer_size_;
379 dte_config.uart_config.tx_buffer_size = this->tx_buffer_size_;
380 dte_config.uart_config.event_queue_size = UART_EVENT_QUEUE_SIZE;
381 dte_config.uart_config.port_num = static_cast<uart_port_t>(this->uart_port_);
382 // The rate the modem answered at last time comes first: after a baud_rate change the modem may still sit in
383 // CMUX at the old rate, which only that rate can detect; the configured rate is applied once synced
384 const int start_baud = this->restored_baud_ != 0 ? this->restored_baud_ : this->baud_rate_;
385 if (start_baud != 0) {
386 dte_config.uart_config.baud_rate = start_baud;
387 }
388 if (this->rts_pin_ != nullptr) {
389 dte_config.uart_config.rts_io_num = this->rts_pin_->get_pin();
390 dte_config.uart_config.cts_io_num = this->cts_pin_->get_pin();
391 dte_config.uart_config.flow_control = ESP_MODEM_FLOW_CONTROL_HW;
392 }
393 dte_config.dte_buffer_size = this->dte_buffer_size_;
394 this->current_baud_rate_ = dte_config.uart_config.baud_rate;
395 this->dte_ = create_uart_dte(&dte_config);
396 esp_modem_dce_config_t dce_config = ESP_MODEM_DCE_DEFAULT_CONFIG(this->apn_);
397 if (this->dte_) {
398 this->dce_ = this->dce_factory_(&dce_config, this->dte_, this->ppp_netif_);
399 }
400 if (!this->dce_) {
401 this->fail_setup_(LOG_STR("Modem DTE/DCE creation failed"));
402 return;
403 }
404 // The pin schema's inverted flag is applied to the UART signals, as the uart component does
405 uint32_t invert = 0;
406 if (this->tx_pin_->is_inverted()) {
407 invert |= UART_SIGNAL_TXD_INV;
408 }
409 if (this->rx_pin_->is_inverted()) {
410 invert |= UART_SIGNAL_RXD_INV;
411 }
412 if (this->rts_pin_ != nullptr) {
413 if (this->rts_pin_->is_inverted()) {
414 invert |= UART_SIGNAL_RTS_INV;
415 }
416 if (this->cts_pin_->is_inverted()) {
417 invert |= UART_SIGNAL_CTS_INV;
418 }
419 }
420 if (invert != 0 && uart_set_line_inverse(static_cast<uart_port_t>(this->uart_port_), invert) != ESP_OK) {
421 this->fail_setup_(LOG_STR("UART line inversion failed"));
422 return;
423 }
424#ifdef USE_MODEM_URC
425 // Runs on the UART task. CMUX hands each frame over on its own, so lines are assembled here; every
426 // chunk is consumed and a complete line is handed to loop() in urc_line_.
427 this->dce_->set_enhanced_urc([this](const DTE::UrcBufferInfo &buffer_info) {
428 // The response parser owns the buffer while a command runs; URCs in that window are best effort,
429 // and a line started before it would otherwise be glued to the next one
430 if (buffer_info.is_command_active) {
431 this->urc_reader_.reset();
432 return DTE::UrcConsumeInfo{DTE::UrcConsumeResult::CONSUME_NONE, 0};
433 }
434 bool dropped = false;
435 for (size_t i = 0; i < buffer_info.new_data_size; i++) {
436 const uint8_t c = buffer_info.new_data_start[i];
437 if (this->urc_pending_.load(std::memory_order_acquire)) {
438 // The line loop() has not published yet lives in the reader's buffer, which a dropped line leaves alone
439 dropped |= c != '\r' && c != '\n';
440 this->urc_reader_.discard_line();
441 }
442 const char *line = this->urc_reader_.feed(c);
443 this->urc_reader_.log_if_overflowed(TAG);
444 if (line != nullptr && line[0] != '\0') {
445 this->urc_line_ = line;
446 this->urc_pending_.store(1, std::memory_order_release);
447 this->enable_loop_soon_any_context();
448 }
449 }
450 if (dropped) {
451 ESP_LOGW(TAG, "URC dropped; the previous one is not published yet");
452 }
453 return DTE::UrcConsumeInfo{DTE::UrcConsumeResult::CONSUME_ALL, 0};
454 });
455#endif
456 if (!this->task_.create(ModemComponent::task_entry, "modem", TASK_STACK_SIZE, this, 1, false)) {
457 this->fail_setup_(LOG_STR("Task creation failed"));
458 }
459}
460
461void ModemComponent::dump_config() {
462#ifdef USE_MODEM_PIN_CODE
463 const char *pin_code = LOG_STR_LITERAL("Yes (not shown)");
464#else
465 const char *pin_code = LOG_STR_LITERAL("No");
466#endif
467 ESP_LOGCONFIG(TAG,
468 "Modem:\n"
469 " Model: %s\n"
470 " APN: %s\n"
471 " PIN code: %s\n"
472 " TX Pin: GPIO%u\n"
473 " RX Pin: GPIO%u\n"
474 " UART port: %d\n"
475 " Baud rate: %d\n"
476 " TX buffer size: %u\n"
477 " RX buffer size: %u\n"
478 " DTE buffer size: %u\n"
479 " Reboot timeout: %" PRIu32 " ms\n"
480 " Enabled: %s",
481 this->model_, this->apn_, pin_code, this->tx_pin_->get_pin(), this->rx_pin_->get_pin(),
482 static_cast<int>(this->uart_port_), this->current_baud_rate_, this->tx_buffer_size_,
483 this->rx_buffer_size_, this->dte_buffer_size_, this->timeout_, YESNO(this->is_enabled()));
484#ifdef USE_MODEM_POLL
485 ESP_LOGCONFIG(TAG, " Update interval: %" PRIu32 " ms", this->update_interval_);
486#endif
487#ifdef USE_MODEM_SIGNAL
488 LOG_SENSOR(" ", "RSSI", this->rssi_sensor_);
489 LOG_SENSOR(" ", "BER", this->ber_sensor_);
490#endif
491#ifdef USE_MODEM_NETWORK_TYPE
492 LOG_TEXT_SENSOR(" ", "Network type", this->network_type_text_sensor_);
493#endif
494 this->dump_connect_params_();
495}
496
497void ModemComponent::task_entry(void *arg) { static_cast<ModemComponent *>(arg)->run_task_(); }
498
499void ModemComponent::run_task_() {
500 while (true) {
501#ifdef USE_MODEM_SEND_AT
502 // A command from send_at() goes out between state steps, never in the middle of a sequence
503 if (this->at_pending_.load(std::memory_order_acquire)) {
504 this->at_(this->at_command_, this->at_timeout_);
505 this->at_pending_.store(0, std::memory_order_release);
506 }
507#endif
508 this->step_delay_ms_ = 0;
509 this->transition_to_(this->compute_next_state_());
510 // Nothing to do while disabled or connected: enable(), disable() and the PPP events wake the task
511 const bool parked = this->component_state_.load() == this->target_state_.load();
512 TickType_t wait = parked ? portMAX_DELAY : pdMS_TO_TICKS(this->step_delay_ms_);
513#ifdef USE_MODEM_POLL
514 // Like send_at(), the poll goes out between state steps; while connected the next poll ends the wait
515 if (parked && this->is_connected()) {
516 int32_t remaining = static_cast<int32_t>(this->next_poll_ms_ - millis());
517 if (remaining <= 0) {
518 // A result loop() has not published yet is not overwritten; that poll is skipped
519 if (!this->poll_unpublished_.load(std::memory_order_acquire)) {
520 this->poll_();
521 this->poll_unpublished_.store(1, std::memory_order_release);
522 this->enable_loop_soon_any_context();
523 }
524 this->next_poll_ms_ = millis() + this->update_interval_;
525 remaining = static_cast<int32_t>(this->update_interval_);
526 }
527 wait = pdMS_TO_TICKS(remaining);
528 }
529#endif
530 ulTaskNotifyTake(pdTRUE, wait);
531 }
532}
533
534uint32_t ModemComponent::next_probe_delay_() {
535 const uint8_t backoff = this->probe_backoff_.load(std::memory_order_relaxed);
536 const uint32_t delay_ms = std::min(PROBE_RETRY_DELAY_MS << backoff, PROBE_RETRY_MAX_MS);
537 if (delay_ms < PROBE_RETRY_MAX_MS) {
538 this->probe_backoff_.store(backoff + 1, std::memory_order_relaxed);
539 }
540 return delay_ms;
541}
542
543ModemState ModemComponent::retry_(ModemState state, uint32_t delay_ms) {
544 this->step_delay_ms_ = delay_ms;
545 return state;
546}
547
548ModemState ModemComponent::compute_next_state_() {
549 const ModemState state = this->component_state_.load();
550 if (this->target_state_.load() == ModemState::MODEM_STATE_DISABLED) {
551 if (state == ModemState::MODEM_STATE_DISABLED) {
552 return ModemState::MODEM_STATE_DISABLED;
553 }
554 if (state != ModemState::MODEM_STATE_DISCONNECTING) {
555 return ModemState::MODEM_STATE_DISCONNECTING;
556 }
557 }
558
559 switch (state) {
560 case ModemState::MODEM_STATE_DISABLED:
561#ifdef USE_MODEM_PIN_CODE
562 // A new attempt may send the PIN again; a counted send that has not gone out yet still does
563 if (this->pin_step_ == PinStep::PIN_STEP_SENT) {
564 this->pin_step_ = PinStep::PIN_STEP_IDLE;
565 }
566#endif
567 return ModemState::MODEM_STATE_ENABLING;
568 case ModemState::MODEM_STATE_ENABLING:
569 return this->handle_state_enabling_();
570 case ModemState::MODEM_STATE_SYNCED:
571 return this->handle_state_synced_();
572 case ModemState::MODEM_STATE_CONNECTING:
573 return this->handle_state_connecting_();
574 case ModemState::MODEM_STATE_WAIT_IP:
575 return this->handle_state_wait_ip_();
576 case ModemState::MODEM_STATE_CONNECTED:
577 if (this->got_ip_.load(std::memory_order_acquire)) {
578 return ModemState::MODEM_STATE_CONNECTED;
579 }
580 ESP_LOGW(TAG, "Lost IP; PPP error %u", this->ppp_error_.load(std::memory_order_acquire));
581 this->ppp_error_.store(0, std::memory_order_release);
582 this->set_fault_(ModemFault::MODEM_FAULT_PPP);
583 return ModemState::MODEM_STATE_DISCONNECTING;
584 case ModemState::MODEM_STATE_DISCONNECTING:
585 return this->handle_state_disconnecting_();
586 }
587 return state;
588}
589
590ModemState ModemComponent::handle_state_enabling_() {
591 // Find the baud rate the modem answers at and leave it in command mode, synced
592 if (!this->dce_->set_mode(modem_mode::AUTODETECT)) {
593 // A failed detection keeps the previous mode, which would skip the baud rate search below
594 this->dce_->set_mode(modem_mode::UNDEF);
595 }
596 auto mode = this->dce_->get_mode();
597 ESP_LOGD(TAG, "Autodetect mode: %d", static_cast<int>(mode));
598
599 // A detection proves the modem answers; leaving CMUX or data mode has to be checked with a sync
600 bool exited = true;
601 switch (mode) {
602 case modem_mode::CMUX_MANUAL_MODE:
603 // A data session survived the ESP reboot; the radio off step below ends it
604 ESP_LOGD(TAG, "Modem warm reboot. Exiting CMUX");
605 if (!this->dce_->set_mode(modem_mode::CMUX_MANUAL_EXIT)) {
606 ESP_LOGW(TAG, "Failed to exit CMUX");
607 }
608 break;
609
610 case modem_mode::UNDEF: {
611 // The detection above probed the current rate; the other known rates are tried in this pass
612 const int detected = this->current_baud_rate_;
613 exited = false;
614 const int bauds[] = {this->restored_baud_, this->baud_rate_, FALLBACK_BAUD_RATE};
615 bool found = false;
616 bool probed = false;
617 bool rejected = false;
618 for (size_t i = 0; i != std::size(bauds) && !found; i++) {
619 const int baud = bauds[i];
620 if (baud == 0 || baud == detected || std::find(bauds, bauds + i, baud) != bauds + i) {
621 continue;
622 }
623 if (uart_set_baudrate(static_cast<uart_port_t>(this->uart_port_), baud) != ESP_OK) {
624 ESP_LOGW(TAG, "UART rejected baud rate %d", baud);
625 this->set_fault_(ModemFault::MODEM_FAULT_BAUD);
626 rejected = true;
627 continue;
628 }
629 this->current_baud_rate_ = baud;
630 probed = true;
631 std::string output;
632 found = this->dce_->at("AT", output, PROBE_TIMEOUT_MS) == command_result::OK;
633 if (!found) {
634 this->not_responding_(baud);
635 }
636 }
637 if (!found) {
638 // The detection at the current rate already failed; a UART that refused every other rate set BAUD
639 if (!probed && !rejected) {
640 this->not_responding_(detected);
641 }
642 return this->retry_(ModemState::MODEM_STATE_ENABLING, this->next_probe_delay_());
643 }
644 ESP_LOGD(TAG, "Modem responded at baud %d", this->current_baud_rate_);
645 break;
646 }
647
648 case modem_mode::COMMAND_MODE:
649 exited = false;
650 break;
651
652 case modem_mode::DATA_MODE:
653 // Can block 20 s; esp_modem offers no shorter exit
654 ESP_LOGW(TAG, "Exiting DATA_MODE");
655 if (!this->dce_->set_mode(modem_mode::COMMAND_MODE)) {
656 ESP_LOGW(TAG, "Failed to leave data mode");
657 }
658 break;
659
660 default:
661 ESP_LOGW(TAG, "Modem in unexpected mode %d. Switching to COMMAND mode.", static_cast<int>(mode));
662 if (!this->dce_->set_mode(modem_mode::COMMAND_MODE)) {
663 ESP_LOGW(TAG, "Failed to switch to command mode");
664 }
665 this->dce_->set_mode(modem_mode::UNDEF);
666 break;
667 }
668
669 if (exited && this->dce_->sync() != command_result::OK) {
670 // The detection proved the modem answers, so the CMUX or data mode exit is what failed; the exit can block
671 // for 20 s, so it backs off like the probe
672 ESP_LOGW(TAG, "Modem did not return to command mode");
673 this->set_fault_(ModemFault::MODEM_FAULT_TEARDOWN);
674 return this->retry_(ModemState::MODEM_STATE_ENABLING, this->next_probe_delay_());
675 }
676 // esp_modem keeps the last line before OK as the reply, which can be the echoed command
677 if (this->dce_->set_echo(false) != command_result::OK) {
678 ESP_LOGW(TAG, "Failed to disable command echo");
679 }
680
681 // The SIM7670G only uses an APN written at CFUN=0 (else the attach fails with an ESM failure); CFUN=0 also drops a
682 // session left by a warm reboot. A modem that refuses gets the APN after the SIM check instead, as before.
683 esp_modem::PdpContext pdp(this->apn_);
684 this->apn_pending_ = this->dce_->set_radio_state(RADIO_STATE_MINIMUM) != command_result::OK ||
685 this->dce_->set_pdp_context(pdp) != command_result::OK;
686 if (this->apn_pending_) {
687 ESP_LOGW(TAG, "Failed to set the APN with the SIM powered down; setting it after the SIM check");
688 }
689 // CFUN=4 powers the SIM up with the radio still off; a modem without it needs CFUN=1 to bring the SIM back
690 if (this->dce_->set_radio_state(RADIO_STATE_RF_OFF) != command_result::OK &&
691 this->dce_->set_radio_state(1) != command_result::OK) {
692 ESP_LOGW(TAG, "Failed to power the SIM up");
693 this->set_fault_(ModemFault::MODEM_FAULT_SETUP);
694 this->modem_synced_ = true; // it answers, so a disable() still tears it down
695 return this->retry_(ModemState::MODEM_STATE_ENABLING, this->next_probe_delay_());
696 }
697 this->probe_backoff_.store(0, std::memory_order_relaxed);
698
699 if (this->baud_rate_ != 0 && this->baud_rate_ != this->current_baud_rate_) {
700 ESP_LOGD(TAG, "Setting baud rate: %d -> %d", this->current_baud_rate_, this->baud_rate_);
701 if (this->dce_->set_baud(this->baud_rate_) == command_result::OK) {
702 delay(200); // NOLINT
703 if (uart_set_baudrate(static_cast<uart_port_t>(this->uart_port_), this->baud_rate_) != ESP_OK) {
704 ESP_LOGE(TAG, "UART rejected baud rate %d", this->baud_rate_);
705 this->set_fault_(ModemFault::MODEM_FAULT_BAUD);
706 return ModemState::MODEM_STATE_DISCONNECTING;
707 }
708 this->current_baud_rate_ = this->baud_rate_;
709 if (this->dce_->sync() != command_result::OK) {
710 ESP_LOGE(TAG, "Failed to sync modem at baud rate %d.", this->baud_rate_);
711 this->set_fault_(ModemFault::MODEM_FAULT_BAUD);
712 return ModemState::MODEM_STATE_DISCONNECTING;
713 }
714 ESP_LOGI(TAG, "Modem synced at baud rate %d.", this->current_baud_rate_);
715 } else {
716 // The modem still answers at the probed rate, so a rejected rate is not worth a retry loop
717 ESP_LOGW(TAG, "Modem rejected baud rate %d. Staying at %d.", this->baud_rate_, this->current_baud_rate_);
718 this->set_fault_(ModemFault::MODEM_FAULT_BAUD);
719 }
720 }
721
722 // The rate in use is the wanted one, so a baud fault from this or an earlier attempt no longer applies
723 if (this->baud_rate_ == 0 || this->baud_rate_ == this->current_baud_rate_) {
724 this->clear_config_fault_(ModemFault::MODEM_FAULT_BAUD);
725 }
726 if (this->restored_baud_ != this->current_baud_rate_) {
727 this->restored_baud_ = this->current_baud_rate_;
728 this->hand_over_(PENDING_SAVE_BAUD);
729 }
730
731 // The DTE side was set up with the UART; the modem side has to be asked for RTS/CTS as well
732 if (this->rts_pin_ != nullptr && this->dce_->set_flow_control(2, 2) != command_result::OK) {
733 ESP_LOGW(TAG, "Modem refused hardware flow control; UART overruns are possible");
734 }
735 this->modem_synced_ = true;
736 return ModemState::MODEM_STATE_SYNCED;
737}
738
739ModemState ModemComponent::handle_state_synced_() {
740 // transition_to_() gave on_sync its head start; a command it queued went out at the top of this pass
741 bool failed = false;
742 for (uint8_t i = 0; i != this->init_at_count_; i++) {
743 failed |= this->at_(this->init_at_commands_[i]) != command_result::OK; // at_() logs the failure
744 }
745 if (failed) {
746 this->set_fault_(ModemFault::MODEM_FAULT_INIT_AT);
747 } else {
748 this->clear_config_fault_(ModemFault::MODEM_FAULT_INIT_AT);
749 }
750 this->connect_step_ = ConnectStep::CONNECT_STEP_START;
751 return ModemState::MODEM_STATE_CONNECTING;
752}
753
754ModemState ModemComponent::handle_state_connecting_() {
755 if (this->connect_step_ == ConnectStep::CONNECT_STEP_START) {
756 // ENABLING just synced; only a failed attachment read comes back here unsure of the modem
757 if (this->resync_) {
758 this->resync_ = false;
759 if (this->dce_->sync() != command_result::OK) {
760 ESP_LOGW(TAG, "Modem not synced during network init");
761 return ModemState::MODEM_STATE_ENABLING;
762 }
763 }
764 // ENABLING powered the SIM up (CFUN=4, or CFUN=1 on a modem without it), so the SIM answers
765 switch (this->prepare_sim_()) {
766 case SimResult::SIM_RESULT_READY:
767 break;
768 case SimResult::SIM_RESULT_RETRY:
769 return this->retry_(ModemState::MODEM_STATE_CONNECTING);
770 case SimResult::SIM_RESULT_LOCKED:
771 // A reboot would send nothing more, so the reboot timer is cancelled
772 this->target_state_.store(ModemState::MODEM_STATE_DISABLED);
773 this->hand_over_(PENDING_CONNECT_TIMEOUT);
774 return ModemState::MODEM_STATE_DISCONNECTING;
775 case SimResult::SIM_RESULT_HALT:
776 // Retrying now could burn the SIM's PIN attempts; the reboot timer stays armed, since a reboot may
777 // still open the SIM
778 this->target_state_.store(ModemState::MODEM_STATE_DISABLED);
779 return ModemState::MODEM_STATE_DISCONNECTING;
780 }
781 if (this->apn_pending_) {
782 esp_modem::PdpContext pdp(this->apn_);
783 if (this->dce_->set_pdp_context(pdp) != command_result::OK) {
784 ESP_LOGW(TAG, "Failed to set the APN");
785 this->set_fault_(ModemFault::MODEM_FAULT_SETUP);
786 return this->retry_(ModemState::MODEM_STATE_CONNECTING);
787 }
788 this->apn_pending_ = false;
789 }
790 if (this->dce_->set_radio_state(1) != command_result::OK) {
791 ESP_LOGW(TAG, "Failed to turn the radio on");
792 this->set_fault_(ModemFault::MODEM_FAULT_SETUP);
793 return this->retry_(ModemState::MODEM_STATE_CONNECTING);
794 }
795 this->connect_step_ = ConnectStep::CONNECT_STEP_RADIO_ON;
796 this->attach_polls_ = 0;
797 }
798
799 if (this->connect_step_ == ConnectStep::CONNECT_STEP_RADIO_ON) {
800 // A modem still searching for a network refuses this; the attachment poll asks again
801 if (this->dce_->set_network_attachment_state(1) != command_result::OK) {
802 ESP_LOGD(TAG, "Network attachment request refused");
803 }
804 this->connect_step_ = ConnectStep::CONNECT_STEP_ATTACH_REQUESTED;
805 }
806
807 int attached = 0;
808 if (this->dce_->get_network_attachment_state(attached) != command_result::OK) {
809 ESP_LOGW(TAG, "Failed to read the network attachment state");
810 this->set_fault_(ModemFault::MODEM_FAULT_NOT_ATTACHED);
811 this->connect_step_ = ConnectStep::CONNECT_STEP_START; // start over with a sync on the next pass
812 this->resync_ = true;
813 return this->retry_(ModemState::MODEM_STATE_CONNECTING);
814 }
815 if (!attached) {
816 if (this->attach_polls_++ % ATTACH_DIAG_EVERY == 0) {
817 int rssi = 99, ber = 99, registration = -1, mode = -1; // -1 stays when the query fails
818 this->dce_->get_network_registration_state(registration);
819 this->dce_->get_signal_quality(rssi, ber);
820 this->dce_->get_network_system_mode(mode);
821 ESP_LOGW(TAG, "Modem not attached yet: registration %d, network type %d, CSQ %d, BER %d", registration, mode,
822 rssi, ber);
823 this->connect_step_ = ConnectStep::CONNECT_STEP_RADIO_ON; // request the attachment again
824 }
825 this->set_fault_(ModemFault::MODEM_FAULT_NOT_ATTACHED);
826 return this->retry_(ModemState::MODEM_STATE_CONNECTING, ATTACH_POLL_MS);
827 }
828
829 ESP_LOGI(TAG, "Modem initialized and ready, starting PPP");
830 // A late event from the last session must not count
831 this->got_ip_.store(0, std::memory_order_release);
832 this->ppp_error_.store(0, std::memory_order_release);
833 if (!this->dce_->set_mode(modem_mode::CMUX_MODE)) {
834 ESP_LOGE(TAG, "Failed to enter PPP. Resetting modem.");
835 this->set_fault_(ModemFault::MODEM_FAULT_PPP);
836 return ModemState::MODEM_STATE_DISCONNECTING;
837 }
838 this->state_started_ms_ = millis();
839 return ModemState::MODEM_STATE_WAIT_IP;
840}
841
842ModemState ModemComponent::handle_state_wait_ip_() {
843 if (this->got_ip_.load(std::memory_order_acquire)) {
844 this->set_fault_(ModemFault::MODEM_FAULT_NONE);
845 return ModemState::MODEM_STATE_CONNECTED;
846 }
847 // A PPP failure (wrong APN, authentication, dead peer) ends the wait at once; the event logged the code
848 if (this->ppp_error_.load(std::memory_order_acquire) != 0) {
849 this->ppp_error_.store(0, std::memory_order_release);
850 this->set_fault_(ModemFault::MODEM_FAULT_PPP);
851 return ModemState::MODEM_STATE_DISCONNECTING;
852 }
853 const uint32_t elapsed = millis() - this->state_started_ms_;
854 if (elapsed < WAIT_IP_TIMEOUT_MS) {
855 // The IP event wakes the task sooner
856 return this->retry_(ModemState::MODEM_STATE_WAIT_IP, WAIT_IP_TIMEOUT_MS - elapsed);
857 }
858 ESP_LOGE(TAG, "Unable to get IP address");
859 this->set_fault_(ModemFault::MODEM_FAULT_PPP);
860 return ModemState::MODEM_STATE_DISCONNECTING;
861}
862
863ModemState ModemComponent::handle_state_disconnecting_() {
864 // Each teardown command holds the task for up to 20 s, so a modem that never answered is skipped
865 if (!this->modem_synced_) {
866 return ModemState::MODEM_STATE_DISABLED;
867 }
868 this->modem_synced_ = false;
869 // COMMAND_MODE stops PPP and leaves CMUX; the manual exit only applies to a warm reboot
870 if (this->dce_->get_mode() != modem_mode::COMMAND_MODE && !this->dce_->set_mode(modem_mode::COMMAND_MODE)) {
871 // The next enable() probes the mode again and retries the exit; the fault keeps this visible
872 ESP_LOGW(TAG, "Failed to leave data mode");
873 this->set_teardown_fault_();
874 }
875 // Turn the radio off; waiting for the lost IP event could take up to 2 min. The SIM is powered down as well, as
876 // ENABLING does anyway on a reconnect.
877 if (this->dce_->set_radio_state(RADIO_STATE_MINIMUM) == command_result::OK) {
878 ESP_LOGI(TAG, "Radio off");
879 } else if (this->dce_->set_radio_state(RADIO_STATE_RF_OFF) == command_result::OK) {
880 ESP_LOGW(TAG, "Radio off, but the SIM could not be powered down");
881 } else {
882 ESP_LOGW(TAG, "Radio off failed");
883 this->set_teardown_fault_();
884 }
885 return ModemState::MODEM_STATE_DISABLED;
886}
887
888void ModemComponent::transition_to_(ModemState next_state) {
889 const ModemState state = this->component_state_.load();
890 if (next_state == state) {
891 return;
892 }
893 const bool lost = next_state == ModemState::MODEM_STATE_DISCONNECTING && state == ModemState::MODEM_STATE_CONNECTED;
894 ESP_LOGD(TAG, "State change: %s -> %s", LOG_STR_ARG(state_to_str(state)), LOG_STR_ARG(state_to_str(next_state)));
895 this->component_state_.store(next_state);
896 // The automations run on the main loop
897 if (next_state == ModemState::MODEM_STATE_SYNCED) {
898 // on_sync may queue an AT command or disable the modem; it gets a bounded head start, and loop() wakes the
899 // task once it ran. An earlier enable() or a send_at() inside on_sync also notifies, so the flag decides.
900 this->sync_acked_.store(0, std::memory_order_release);
901 this->hand_over_(PENDING_ON_SYNC);
902 const uint32_t started = millis();
903 while (this->sync_acked_.load(std::memory_order_acquire) == 0) {
904 const uint32_t elapsed = millis() - started;
905 if (elapsed >= SYNC_ACK_TIMEOUT_MS) {
906 ESP_LOGW(TAG, "on_sync did not run within %u ms; continuing", static_cast<unsigned>(SYNC_ACK_TIMEOUT_MS));
907 break;
908 }
909 ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(SYNC_ACK_TIMEOUT_MS - elapsed));
910 }
911 } else if (next_state == ModemState::MODEM_STATE_CONNECTED) {
912 this->hand_over_(PENDING_ON_CONNECT | PENDING_CONNECT_TIMEOUT);
913#ifdef USE_MODEM_POLL
914 this->next_poll_ms_ = millis(); // the first poll runs right after connecting
915#endif
916 } else if (next_state == ModemState::MODEM_STATE_DISCONNECTING) {
917 // The lost IP event can lag by minutes; a quick re-enable must wait for a fresh address
918 this->got_ip_.store(0, std::memory_order_release);
919 this->step_delay_ms_ = COMMAND_TIMEOUT_MS; // let the link settle before the first pass
920 // on_disconnect pairs with on_connect, so a failed attempt that never connected does not fire it; a lost
921 // connection starts the reconnect watchdog again
922 if (lost) {
923 this->hand_over_(PENDING_ON_DISCONNECT | PENDING_CONNECT_TIMEOUT);
924 }
925 }
926}
927
928void ModemComponent::not_responding_(int baud) {
929 ESP_LOGW(TAG, "Modem not responding at %d baud. Check power, PWRKEY and TX/RX wiring.", baud);
930 this->set_fault_(ModemFault::MODEM_FAULT_NO_RESPONSE);
931}
932
933#ifdef USE_MODEM_SEND_AT
934bool ModemComponent::send_at(const std::string &cmd, uint32_t timeout) { return this->send_at(cmd.c_str(), timeout); }
935
936bool ModemComponent::send_at(const char *cmd, uint32_t timeout) {
937 if (!this->task_.is_created()) {
938 ESP_LOGW(TAG, "Modem not ready, cannot send AT command: %s", cmd);
939 return false;
940 }
941 if (this->at_pending_.load(std::memory_order_acquire)) {
942 ESP_LOGW(TAG, "AT command '%s' dropped; the previous one is not sent yet", cmd);
943 return false;
944 }
945 const size_t len = strlen(cmd);
946 if (len >= sizeof(this->at_command_)) {
947 ESP_LOGW(TAG, "AT command longer than %u bytes dropped", static_cast<unsigned>(sizeof(this->at_command_) - 1));
948 return false;
949 }
950 memcpy(this->at_command_, cmd, len + 1);
951 this->at_timeout_ = timeout;
952 this->at_pending_.store(1, std::memory_order_release);
953 this->wake_task_();
954 return true;
955}
956
957#endif
958
959command_result ModemComponent::at_(const char *cmd, uint32_t timeout) {
960 std::string output;
961 const command_result result = this->dce_->at(cmd, output, timeout);
962 if (result == command_result::OK) {
963 ESP_LOGI(TAG, "AT '%s' -> OK: %s", cmd, output.c_str());
964 } else {
965 ESP_LOGW(TAG, "AT '%s' -> %s: %s", cmd, LOG_STR_ARG(result_to_str(result)), output.c_str());
966 }
967 return result;
968}
969
970// esp_modem's read_pin() takes NOT READY for READY and SIM PIN2 for the SIM PIN, so the status is read here
971SimResult ModemComponent::prepare_sim_() {
972#ifdef USE_MODEM_PIN_CODE
973 // Every write to pin_record_ happens below, so waiting here keeps the task off it while loop() saves it
974 if (this->pin_save_state_.load(std::memory_order_acquire) == PinSave::PIN_SAVE_PENDING) {
975 return SimResult::SIM_RESULT_RETRY; // the save wakes the task
976 }
977#endif
978 std::string output;
979 if (this->dce_->at("AT+CPIN?", output, COMMAND_TIMEOUT_MS) != command_result::OK) {
980 // A SIM that is still starting answers with an error for a second or so
981 ESP_LOGD(TAG, "SIM status not readable yet: %s", output.c_str());
982 this->set_fault_(ModemFault::MODEM_FAULT_SIM_NOT_READY);
983 return SimResult::SIM_RESULT_RETRY;
984 }
985 // Anything else, such as an echoed command, is not a status and must not reach the lock checks below
986 const char *found = strstr(output.c_str(), "+CPIN:");
987 if (found != nullptr) {
988 found += sizeof("+CPIN:") - 1;
989 while (*found == ' ') {
990 found++;
991 }
992 }
993 const StringRef status = found != nullptr ? StringRef(found) : StringRef();
994 if (status.empty()) {
995 ESP_LOGD(TAG, "SIM status not reported yet: %s", output.c_str());
996 this->set_fault_(ModemFault::MODEM_FAULT_SIM_NOT_READY);
997 return SimResult::SIM_RESULT_RETRY;
998 }
999 ESP_LOGD(TAG, "SIM: %s", status.c_str());
1000
1001 // A prefix match: "NOT READY" contains READY but does not start with it
1002 if (status.starts_with("READY")) {
1003#ifdef USE_MODEM_PIN_CODE
1004 this->pin_step_ = PinStep::PIN_STEP_IDLE; // proven correct, so a modem self-reset may send it again
1005 if (this->pin_record_.sends != 0) {
1006 this->pin_record_.sends = 0;
1007 this->save_pin_record_();
1008 }
1009#endif
1010 return SimResult::SIM_RESULT_READY;
1011 }
1012 if (strstr(status.c_str(), "PUK") != nullptr) {
1013 ESP_LOGE(TAG, "SIM is PUK locked; unlock it in a phone");
1014 this->set_fault_(ModemFault::MODEM_FAULT_SIM_LOCKED);
1015 return SimResult::SIM_RESULT_LOCKED;
1016 }
1017 // Only the plain SIM PIN takes pin_code; SIM PIN2 and the PH-* locks need other credentials
1018 if (!status.starts_with("SIM PIN") || status.starts_with("SIM PIN2")) {
1019 if (strstr(status.c_str(), "PIN") != nullptr) {
1020 ESP_LOGE(TAG, "SIM lock %s needs a credential pin_code cannot provide", status.c_str());
1021 this->set_fault_(ModemFault::MODEM_FAULT_SIM_LOCKED);
1022 return SimResult::SIM_RESULT_LOCKED;
1023 }
1024 ESP_LOGW(TAG, "SIM not ready: %s", status.c_str()); // e.g. NOT READY or NOT INSERTED
1025 this->set_fault_(ModemFault::MODEM_FAULT_SIM_NOT_READY);
1026 return SimResult::SIM_RESULT_RETRY;
1027 }
1028#ifdef USE_MODEM_PIN_CODE
1029 return this->send_pin_();
1030#else
1031 ESP_LOGE(TAG, "SIM requires a PIN but pin_code is not set");
1032 this->set_fault_(ModemFault::MODEM_FAULT_SIM_LOCKED);
1033 return SimResult::SIM_RESULT_LOCKED;
1034#endif
1035}
1036
1037#ifdef USE_MODEM_PIN_CODE
1038void ModemComponent::save_pin_record_() {
1039 this->pin_save_state_.store(PinSave::PIN_SAVE_PENDING, std::memory_order_release);
1040 this->hand_over_(PENDING_SAVE_PIN);
1041}
1042
1043// Each send is counted in flash before the PIN goes out, so reboots cannot keep spending the SIM's attempts on a
1044// PIN it never confirmed; READY clears the count and a refused send uses it up
1045SimResult ModemComponent::send_pin_() {
1046 switch (this->pin_step_) {
1047 case PinStep::PIN_STEP_IDLE:
1048 if (this->pin_record_.sends >= PIN_MAX_UNCONFIRMED_SENDS) {
1049 ESP_LOGE(TAG, "The SIM never confirmed this pin_code; not sending it again");
1050 this->set_fault_(ModemFault::MODEM_FAULT_PIN_NOT_SENT);
1051 return SimResult::SIM_RESULT_LOCKED;
1052 }
1053 this->pin_record_.sends++;
1054 this->pin_step_ = PinStep::PIN_STEP_SAVING;
1055 this->save_pin_record_();
1056 return SimResult::SIM_RESULT_RETRY;
1057
1058 case PinStep::PIN_STEP_SAVING: {
1059 // prepare_sim_() waited for the outcome
1060 if (this->pin_save_state_.load(std::memory_order_acquire) != PinSave::PIN_SAVE_DONE) {
1061 ESP_LOGE(TAG, "The PIN attempt could not be recorded; not sending it");
1062 this->pin_record_.sends--;
1063 this->pin_step_ = PinStep::PIN_STEP_IDLE;
1064 this->set_fault_(ModemFault::MODEM_FAULT_PIN_RECORD);
1065 return SimResult::SIM_RESULT_HALT;
1066 }
1067 this->pin_step_ = PinStep::PIN_STEP_SENT;
1068 this->state_started_ms_ = millis();
1069 std::string cmd = "AT+CPIN=\"";
1070 cmd += this->pin_code_;
1071 cmd += '"';
1072 if (this->at_(cmd.c_str(), PIN_TIMEOUT_MS) == command_result::FAIL) {
1073 // A blind resend could PUK-lock the SIM, so a refusal uses up the count until pin_code changes
1074 ESP_LOGE(TAG, "The SIM refused the PIN; check pin_code");
1075 this->pin_record_.sends = PIN_MAX_UNCONFIRMED_SENDS;
1076 this->save_pin_record_();
1077 this->set_fault_(ModemFault::MODEM_FAULT_PIN_NOT_SENT);
1078 return SimResult::SIM_RESULT_LOCKED;
1079 }
1080 return SimResult::SIM_RESULT_RETRY; // AT+CPIN? confirms READY on the next pass
1081 }
1082
1083 case PinStep::PIN_STEP_SENT:
1084 // Some SIMs take seconds to unlock, so AT+CPIN? is asked again for a while
1085 if (millis() - this->state_started_ms_ < PIN_UNLOCK_WAIT_MS) {
1086 return SimResult::SIM_RESULT_RETRY;
1087 }
1088 ESP_LOGE(TAG, "SIM still locked after sending the PIN; check the SIM");
1089 if (this->pin_record_.sends >= PIN_MAX_UNCONFIRMED_SENDS) {
1090 this->set_fault_(ModemFault::MODEM_FAULT_PIN_NOT_SENT);
1091 return SimResult::SIM_RESULT_LOCKED;
1092 }
1093 // This attempt stops rather than sending the PIN blind again; a reboot sends it once more
1094 this->set_fault_(ModemFault::MODEM_FAULT_SIM_LOCKED);
1095 return SimResult::SIM_RESULT_HALT;
1096 }
1097 return SimResult::SIM_RESULT_RETRY;
1098}
1099#endif
1100
1101#ifdef USE_MODEM_POLL
1102
1103#ifdef USE_MODEM_SIGNAL
1104// 3GPP TS 45.008 representative bit error rates for the RXQUAL classes AT+CSQ reports
1105static constexpr float BER_PERCENT[] = {0.14f, 0.28f, 0.57f, 1.13f, 2.26f, 4.53f, 9.05f, 18.10f};
1106#endif
1107
1108void ModemComponent::poll_() {
1109 // The task owns the poll_ answers while poll_unpublished_ is clear
1110#ifdef USE_MODEM_SIGNAL
1111 int rssi = CSQ_UNKNOWN, ber = CSQ_UNKNOWN;
1112 const bool signal_ok = this->dce_->get_signal_quality(rssi, ber) == command_result::OK;
1113 this->poll_rssi_ = static_cast<uint8_t>(signal_ok && rssi >= 0 && rssi < CSQ_UNKNOWN ? rssi : CSQ_UNKNOWN);
1114 this->poll_ber_ = static_cast<uint8_t>(signal_ok && ber >= 0 && ber < CSQ_UNKNOWN ? ber : CSQ_UNKNOWN);
1115#endif
1116#ifdef USE_MODEM_NETWORK_TYPE
1117 int mode = -1;
1118 const bool mode_ok = this->dce_->get_network_system_mode(mode) == command_result::OK;
1119 this->poll_mode_ = static_cast<uint8_t>(mode_ok && mode >= 0 && mode < NETWORK_MODE_NONE ? mode : NETWORK_MODE_NONE);
1120#endif
1121}
1122
1123#ifdef USE_MODEM_NETWORK_TYPE
1124// AT+CNSMOD values 0-8 on the SIM7600 family; anything else shows as Unknown
1125PROGMEM_STRING_TABLE(NetworkModeStrings, "No service", "GSM", "GPRS", "EDGE", "WCDMA", "HSDPA", "HSUPA", "HSPA", "LTE",
1126 "Unknown");
1127#endif
1128
1129// Raw AT answers: CSQ rssi and ber, and the CNSMOD mode (past the table shows as Unknown)
1130void ModemComponent::publish_readings_([[maybe_unused]] uint8_t rssi, [[maybe_unused]] uint8_t ber,
1131 [[maybe_unused]] uint8_t mode) {
1132#ifdef USE_MODEM_SIGNAL
1133 PUBLISH_STATE(this->rssi_sensor_, rssi <= CSQ_RSSI_MAX ? -113.0f + 2.0f * rssi : NAN);
1134 PUBLISH_STATE(this->ber_sensor_, ber < std::size(BER_PERCENT) ? BER_PERCENT[ber] : NAN);
1135#endif
1136#ifdef USE_MODEM_NETWORK_TYPE
1137 PUBLISH_STATE(this->network_type_text_sensor_,
1138 NetworkModeStrings::get_progmem_str(mode, NetworkModeStrings::LAST_INDEX));
1139#endif
1140}
1141#endif
1142
1143void ModemComponent::dump_connect_params_() {
1144 esp_netif_ip_info_t ip;
1145 if (!this->got_ip_.load(std::memory_order_acquire) || esp_netif_get_ip_info(this->ppp_netif_, &ip) != ESP_OK) {
1146 ESP_LOGCONFIG(TAG, " Connection: not connected");
1147 return;
1148 }
1149 auto dns_str = [this](esp_netif_dns_type_t type, char *buf) -> const char * {
1150 esp_netif_dns_info_t dns{};
1151 if (esp_netif_get_dns_info(this->ppp_netif_, type, &dns) != ESP_OK) {
1152 return LOG_STR_LITERAL("unavailable");
1153 }
1154 return network::IPAddress(&dns.ip.u_addr.ip4).str_to(buf);
1155 };
1156 char ip_buf[network::IP_ADDRESS_BUFFER_SIZE];
1157 char netmask_buf[network::IP_ADDRESS_BUFFER_SIZE];
1158 char gw_buf[network::IP_ADDRESS_BUFFER_SIZE];
1159 char dns_main_buf[network::IP_ADDRESS_BUFFER_SIZE];
1160 char dns_backup_buf[network::IP_ADDRESS_BUFFER_SIZE];
1161 ESP_LOGCONFIG(TAG,
1162 " Connection:\n"
1163 " IP Address: %s\n"
1164 " Hostname: '%s'\n"
1165 " Subnet: %s\n"
1166 " Gateway: %s\n"
1167 " DNS main: %s\n"
1168 " DNS backup: %s",
1169 network::IPAddress(&ip.ip).str_to(ip_buf), App.get_name().c_str(),
1170 network::IPAddress(&ip.netmask).str_to(netmask_buf), network::IPAddress(&ip.gw).str_to(gw_buf),
1171 dns_str(ESP_NETIF_DNS_MAIN, dns_main_buf), dns_str(ESP_NETIF_DNS_BACKUP, dns_backup_buf));
1172}
1173
1174} // namespace esphome::modem
1175
1176#endif
BedjetMode mode
BedJet operating mode.
uint8_t status
Definition bl0942.h:8
const StringRef & get_name() const
Get the name of this Application set by pre_setup().
constexpr const char * c_str() const
Definition string_ref.h:78
const LogString * message
Definition component.cpp:35
unsigned long millis(void)
uint8_t type
bool state
Definition fan.h:2
ModemComponent * global_modem_component
PROGMEM_STRING_TABLE(ModemStateStrings, "DISABLED", "ENABLING", "SYNCED", "CONNECTING", "WAIT_IP", "CONNECTED", "DISCONNECTING", "UNKNOWN")
std::unique_ptr< esp_modem::DCE >(*)(const esp_modem::dce_config *, std::shared_ptr< esp_modem::DTE >, esp_netif_t *) DceFactory
ESPHOME_LOG_TAG(TAG, "modem")
std::array< IPAddress, 5 > IPAddresses
Definition ip_address.h:368
void fill_ip6_addresses(esp_netif_t *netif, IPAddresses &addresses)
Copies the IPv6 addresses of an esp_netif into addresses[1..], warning once when some do not fit.
Definition util.cpp:13
ESPHOME_ALWAYS_INLINE bool is_connected()
Return whether the node is connected to the network (through wifi, eth, ...)
Definition util.h:36
const void size_t len
Definition hal.h:68
ESPPreferences * global_preferences
if(written< 0)
Definition helpers.h:1342
uint32_t fnv1_hash(const char *str)
Calculate a FNV-1 hash of str.
Definition helpers.cpp:169
void HOT delay(uint32_t ms)
Definition hal.cpp:85
uint32_t IRAM_ATTR HOT millis()
Definition hal.cpp:25
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t
ESPPreferenceObject make_preference(size_t, uint32_t, bool)
Definition preferences.h:24
bool sync()
Commit pending writes to flash.
Definition preferences.h:33
uint8_t event_id
Definition tt21100.cpp:3