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