4#include "soc/soc_caps.h"
5#include <driver/uart.h>
16#include <esp_netif_ppp.h>
26using esp_modem::command_result;
27using esp_modem::create_uart_dte;
29using esp_modem::modem_mode;
34static constexpr int HP_UART_COUNT = SOC_UART_HP_NUM;
36static constexpr int HP_UART_COUNT = UART_NUM_MAX;
41static constexpr uint32_t WAIT_IP_TIMEOUT_MS = 50000;
42static constexpr uint32_t PROBE_TIMEOUT_MS = 100;
44static constexpr uint32_t PROBE_RETRY_DELAY_MS = 5000;
45static constexpr uint32_t PROBE_RETRY_MAX_MS = 60000;
47static constexpr uint32_t ECHO_OFF_TIMEOUT_MS = 100;
49static constexpr uint32_t ESCAPE_GUARD_MS = 1100;
52static constexpr size_t CMUX_FLUSH_BYTES = 4096;
53static constexpr uint32_t CMUX_FLUSH_SETTLE_MS = 3000;
55static constexpr uint32_t SYNC_ACK_TIMEOUT_MS = 5000;
57static constexpr uint32_t TASK_STACK_SIZE = 5120;
58#ifdef USE_MODEM_PIN_CODE
60static constexpr uint32_t PIN_TIMEOUT_MS = 5000;
61static constexpr uint32_t PIN_UNLOCK_WAIT_MS = 10000;
63static constexpr uint8_t PIN_MAX_UNCONFIRMED_SENDS = 2;
66static constexpr uint32_t ATTACH_POLL_MS = 4000;
67static constexpr uint8_t ATTACH_DIAG_EVERY = 4;
68static constexpr uint8_t ATTACH_UNKNOWN_POLLS = 15;
70static constexpr uint32_t ATTACH_TIMEOUT_MS = 150000;
72static constexpr uint8_t SIM_WARN_AFTER = 10;
73static constexpr uint8_t SIM_WARN_EVERY = 60;
74static constexpr int RADIO_STATE_MINIMUM = 0;
75static constexpr int RADIO_STATE_RF_OFF = 4;
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;
82PROGMEM_STRING_TABLE(ModemStateStrings,
"DISABLED",
"ENABLING",
"SYNCED",
"CONNECTING",
"WAIT_IP",
"CONNECTED",
83 "DISCONNECTING",
"UNKNOWN");
85 return ModemStateStrings::get_log_str(
static_cast<uint8_t
>(
state), ModemStateStrings::LAST_INDEX);
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");
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");
102 if (registration < 0) {
103 return LOG_STR(
"not reported");
105 return RegistrationStrings::get_log_str(
static_cast<uint8_t
>(registration), RegistrationStrings::LAST_INDEX);
110static const LogString *result_to_str(command_result result) {
111 return CommandResultStrings::get_log_str(
static_cast<uint8_t
>(result), CommandResultStrings::LAST_INDEX);
116 : tx_pin_(tx_pin), rx_pin_(rx_pin), model_(model), dce_factory_(factory), apn_(apn) {
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);
125 if (this->component_state_.load() != ModemState::MODEM_STATE_CONNECTED) {
126 this->arm_connect_timeout_();
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_();
138void ModemComponent::wake_task_() {
139 if (this->task_.is_created()) {
140 xTaskNotifyGive(this->task_.get_handle());
145void ModemComponent::arm_connect_timeout_() {
147 if (this->timeout_ == 0 || this->connect_timeout_armed_) {
150 this->connect_timeout_armed_ =
true;
151 App.
scheduler.set_timeout(
this, this->timeout_, [
this]() {
153 this->connect_timeout_armed_ =
false;
157 ESP_LOGE(TAG,
"Modem was not able to connect (timeout), rebooting");
162void ModemComponent::cancel_connect_timeout_() {
163 this->connect_timeout_armed_ =
false;
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);
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_();
188void ModemComponent::hand_over_(
uint32_t pending) {
189 this->pending_.fetch_or(pending, std::memory_order_release);
190 this->enable_loop_soon_any_context();
194void ModemComponent::set_fault_(ModemFault fault) {
196 if (fault == ModemFault::MODEM_FAULT_BAUD || fault == ModemFault::MODEM_FAULT_INIT_AT) {
197 this->config_fault_.store(fault, std::memory_order_relaxed);
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);
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);
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);
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;
226 if (fault == ModemFault::MODEM_FAULT_NONE) {
227 fault = this->config_fault_.load(std::memory_order_relaxed);
229 if (fault == ModemFault::MODEM_FAULT_NONE) {
230 this->status_clear_warning();
231 this->status_clear_error();
234 const LogString *
message = ModemFaultStrings::get_log_str(
static_cast<uint8_t
>(fault), ModemFaultStrings::LAST_INDEX);
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);
241 this->status_clear_error();
242 this->status_set_warning(
message);
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)) {
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);
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);
261 if (pending & PENDING_ON_CONNECT) {
262 this->dump_connect_params_();
263 this->on_state_callback_.call(ModemState::MODEM_STATE_CONNECTED);
265 if ((pending & PENDING_ON_DISCONNECT) && !disconnect_first) {
266 this->on_state_callback_.call(ModemState::MODEM_STATE_DISCONNECTING);
269 if (pending & PENDING_STATUS) {
270 this->publish_status_();
272 if (pending & PENDING_CONNECT_TIMEOUT) {
273 if (this->target_state_.load() == ModemState::MODEM_STATE_CONNECTED && !this->is_connected()) {
274 this->arm_connect_timeout_();
276 this->cancel_connect_timeout_();
279 if ((pending & PENDING_SAVE_BAUD) && !this->pref_.save(&this->restored_baud_)) {
280 ESP_LOGW(TAG,
"Failed to save the baud rate");
282#ifdef USE_MODEM_PIN_CODE
284 if (pending & PENDING_SAVE_PIN) {
288 ESP_LOGE(TAG,
"Failed to save the PIN record");
291 if (this->pin_record_unsaved_ != !saved) {
292 this->pin_record_unsaved_ = !saved;
293 this->publish_status_();
295 this->pin_save_state_.store(saved ? PinSave::PIN_SAVE_DONE : PinSave::PIN_SAVE_FAILED, std::memory_order_release);
300 if (pending & PENDING_ON_DISCONNECT) {
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);
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);
316 if (this->pending_.load(std::memory_order_acquire) == 0) {
317 this->disable_loop();
321void ModemComponent::setup() {
323 this->pref_.
load(&this->restored_baud_);
324#ifdef USE_MODEM_PIN_CODE
326 if (!this->pin_pref_.load(&this->pin_record_)) {
328 ESP_LOGD(TAG,
"No PIN record stored");
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");
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");
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;
360 if (this->uart_port_ == UART_NUM_MAX) {
361 this->mark_failed(LOG_STR(
"No free UART port for modem"));
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"));
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) {
378 ESP_LOGD(TAG,
"PPP IP event: Got IP " IPSTR, IP2STR(&
static_cast<ip_event_got_ip_t *
>(event_data)->ip_info.ip));
380 ESP_LOGD(TAG,
"PPP IP event: Lost IP");
382 auto *self =
static_cast<ModemComponent *
>(arg);
383 self->got_ip_.store(got_ip, std::memory_order_release);
388 auto ppp_status = [](
void *arg, esp_event_base_t, int32_t
event_id,
void *) {
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);
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"));
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_);
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;
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;
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_);
427 this->dce_ = this->dce_factory_(&dce_config, this->dte_, this->ppp_netif_);
430 this->fail_setup_(LOG_STR(
"Modem DTE/DCE creation failed"));
435 if (this->tx_pin_->is_inverted()) {
436 invert |= UART_SIGNAL_TXD_INV;
438 if (this->rx_pin_->is_inverted()) {
439 invert |= UART_SIGNAL_RXD_INV;
441 if (this->rts_pin_ !=
nullptr) {
442 if (this->rts_pin_->is_inverted()) {
443 invert |= UART_SIGNAL_RTS_INV;
445 if (this->cts_pin_->is_inverted()) {
446 invert |= UART_SIGNAL_CTS_INV;
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"));
456 this->dce_->set_enhanced_urc([
this](
const DTE::UrcBufferInfo &buffer_info) {
459 if (buffer_info.is_command_active) {
460 this->urc_reader_.reset();
461 return DTE::UrcConsumeInfo{DTE::UrcConsumeResult::CONSUME_NONE, 0};
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)) {
468 dropped |= c !=
'\r' && c !=
'\n';
469 this->urc_reader_.discard_line();
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();
480 ESP_LOGW(TAG,
"URC dropped; the previous one is not published yet");
482 return DTE::UrcConsumeInfo{DTE::UrcConsumeResult::CONSUME_ALL, 0};
485 if (!this->task_.create(ModemComponent::task_entry,
"modem", TASK_STACK_SIZE,
this, 1,
false)) {
486 this->fail_setup_(LOG_STR(
"Task creation failed"));
490void ModemComponent::dump_config() {
491#ifdef USE_MODEM_PIN_CODE
492 const char *pin_code = LOG_STR_LITERAL(
"Yes (not shown)");
494 const char *pin_code = LOG_STR_LITERAL(
"No");
505 " TX buffer size: %u\n"
506 " RX buffer size: %u\n"
507 " DTE buffer size: %u\n"
508 " Reboot timeout: %" PRIu32
" ms\n"
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()));
514 ESP_LOGCONFIG(TAG,
" Update interval: %" PRIu32
" ms", this->update_interval_);
516#ifdef USE_MODEM_SIGNAL
517 LOG_SENSOR(
" ",
"RSSI", this->rssi_sensor_);
518 LOG_SENSOR(
" ",
"BER", this->ber_sensor_);
520#ifdef USE_MODEM_NETWORK_TYPE
521 LOG_TEXT_SENSOR(
" ",
"Network type", this->network_type_text_sensor_);
523 this->dump_connect_params_();
526void ModemComponent::task_entry(
void *arg) {
static_cast<ModemComponent *
>(arg)->run_task_(); }
528void ModemComponent::run_task_() {
530#ifdef USE_MODEM_SEND_AT
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);
537 this->step_delay_ms_ = 0;
538 this->transition_to_(this->compute_next_state_());
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_);
545 int32_t remaining =
static_cast<int32_t
>(this->next_poll_ms_ -
millis());
546 if (remaining <= 0) {
548 if (!this->poll_unpublished_.load(std::memory_order_acquire)) {
550 this->poll_unpublished_.store(1, std::memory_order_release);
551 this->enable_loop_soon_any_context();
553 this->next_poll_ms_ =
millis() + this->update_interval_;
554 remaining =
static_cast<int32_t
>(this->update_interval_);
556 wait = pdMS_TO_TICKS(remaining);
559 ulTaskNotifyTake(pdTRUE, wait);
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);
573 this->step_delay_ms_ = delay_ms;
577ModemState ModemComponent::compute_next_state_() {
579 if (this->target_state_.load() == ModemState::MODEM_STATE_DISABLED) {
580 if (
state == ModemState::MODEM_STATE_DISABLED) {
581 return ModemState::MODEM_STATE_DISABLED;
583 if (
state != ModemState::MODEM_STATE_DISCONNECTING) {
584 return ModemState::MODEM_STATE_DISCONNECTING;
589 case ModemState::MODEM_STATE_DISABLED:
590#ifdef USE_MODEM_PIN_CODE
592 if (this->pin_step_ == PinStep::PIN_STEP_SENT) {
593 this->pin_step_ = PinStep::PIN_STEP_IDLE;
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;
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_();
619ModemState ModemComponent::handle_state_enabling_() {
622 this->at_reply_(
"ATE0", ECHO_OFF_TIMEOUT_MS);
624 if (!this->dce_->set_mode(modem_mode::AUTODETECT)) {
626 this->dce_->set_mode(modem_mode::UNDEF);
628 auto mode = this->dce_->get_mode();
629 ESP_LOGD(TAG,
"Autodetect mode: %d",
static_cast<int>(
mode));
634 case modem_mode::CMUX_MANUAL_MODE:
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");
642 case modem_mode::UNDEF: {
644 const int detected = this->current_baud_rate_;
646 const int bauds[] = {this->restored_baud_, this->baud_rate_, FALLBACK_BAUD_RATE};
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) {
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);
661 found = this->dce_->at(
"AT", output, PROBE_TIMEOUT_MS) == command_result::OK;
663 this->not_responding_(baud);
669 if (this->current_baud_rate_ != detected) {
670 const esp_err_t err = this->set_uart_baud_(detected);
672 ESP_LOGW(TAG,
"UART rejected baud rate %d (%s); data mode and CMUX recovery skipped", detected,
674 this->set_fault_(ModemFault::MODEM_FAULT_BAUD);
679 if (this->current_baud_rate_ == detected && (this->escape_data_mode_() || this->flush_cmux_())) {
685 this->not_responding_(detected);
687 const uint32_t delay_ms = this->next_probe_delay_();
688 if (delay_ms == PROBE_RETRY_MAX_MS) {
689 this->answered_ =
false;
691 return this->retry_(ModemState::MODEM_STATE_ENABLING, delay_ms);
693 ESP_LOGD(TAG,
"Modem responded at baud %d", this->current_baud_rate_);
697 case modem_mode::COMMAND_MODE:
701 case modem_mode::DATA_MODE:
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");
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");
714 this->dce_->set_mode(modem_mode::UNDEF);
718 if (exited && this->dce_->sync() != command_result::OK) {
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_());
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");
731 if (this->dce_->set_echo(
false) != command_result::OK) {
732 ESP_LOGW(TAG,
"Failed to disable command echo");
735 if (this->dce_->config_mobile_termination_error(2) != command_result::OK) {
736 ESP_LOGW(TAG,
"Modem refused verbose errors (AT+CMEE=2)");
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");
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;
753 this->answered_ =
true;
754 return this->retry_(ModemState::MODEM_STATE_ENABLING, this->next_probe_delay_());
756 this->probe_backoff_.store(0, std::memory_order_relaxed);
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) {
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;
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;
772 ESP_LOGI(TAG,
"Modem synced at baud rate %d.", this->current_baud_rate_);
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);
781 if (this->baud_rate_ == 0 || this->baud_rate_ == this->current_baud_rate_) {
782 this->clear_config_fault_(ModemFault::MODEM_FAULT_BAUD);
784 if (this->restored_baud_ != this->current_baud_rate_) {
785 this->restored_baud_ = this->current_baud_rate_;
786 this->hand_over_(PENDING_SAVE_BAUD);
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");
793 this->modem_synced_ =
true;
794 this->answered_ =
true;
795 return ModemState::MODEM_STATE_SYNCED;
798ModemState ModemComponent::handle_state_synced_() {
801 for (uint8_t i = 0; i != this->init_at_count_; i++) {
802 failed |= this->at_(this->init_at_commands_[i]) != command_result::OK;
805 this->set_fault_(ModemFault::MODEM_FAULT_INIT_AT);
807 this->clear_config_fault_(ModemFault::MODEM_FAULT_INIT_AT);
809 this->connect_step_ = ConnectStep::CONNECT_STEP_START;
810 this->sim_polls_ = 0;
811 return ModemState::MODEM_STATE_CONNECTING;
814ModemState ModemComponent::handle_state_connecting_() {
815 if (this->connect_step_ == ConnectStep::CONNECT_STEP_START) {
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;
825 switch (this->prepare_sim_()) {
826 case SimResult::SIM_RESULT_READY:
828 case SimResult::SIM_RESULT_RETRY:
829 return this->retry_(ModemState::MODEM_STATE_CONNECTING);
830 case SimResult::SIM_RESULT_LOCKED:
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:
838 this->target_state_.store(ModemState::MODEM_STATE_DISABLED);
839 return ModemState::MODEM_STATE_DISCONNECTING;
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);
848 this->apn_pending_ =
false;
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);
855 this->connect_step_ = ConnectStep::CONNECT_STEP_RADIO_ON;
856 this->attach_polls_ = 0;
857 this->idle_polls_ = 0;
858 this->unknown_polls_ = 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);
869 const int registration = this->read_registration_();
870 if (registration == REGISTRATION_NO_ANSWER) {
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);
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;
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;
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);
901 if (attach != command_result::OK) {
902 ESP_LOGW(TAG,
"Network attachment request refused: %s", this->reply_);
904 this->connect_step_ = ConnectStep::CONNECT_STEP_ATTACH_REQUESTED;
905 return this->retry_(ModemState::MODEM_STATE_CONNECTING);
907 if (this->attach_polls_++ % ATTACH_DIAG_EVERY == 0) {
908 int rssi = 99, ber = 99,
mode = -1;
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);
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);
917 if (registration == REGISTRATION_DENIED) {
919 const command_result reason_read = this->at_reply_(
"AT+CEER");
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_);
925 this->connect_step_ = ConnectStep::CONNECT_STEP_RADIO_ON;
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);
932 ESP_LOGI(TAG,
"Modem initialized and ready, starting PPP");
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;
941 this->state_started_ms_ =
millis();
942 return ModemState::MODEM_STATE_WAIT_IP;
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;
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;
957 if (elapsed < WAIT_IP_TIMEOUT_MS) {
959 return this->retry_(ModemState::MODEM_STATE_WAIT_IP, WAIT_IP_TIMEOUT_MS - elapsed);
961 ESP_LOGE(TAG,
"Unable to get IP address");
962 this->set_fault_(ModemFault::MODEM_FAULT_PPP);
963 return ModemState::MODEM_STATE_DISCONNECTING;
966ModemState ModemComponent::handle_state_disconnecting_() {
968 if (!this->modem_synced_) {
969 return ModemState::MODEM_STATE_DISABLED;
971 this->modem_synced_ =
false;
973 if (this->dce_->get_mode() != modem_mode::COMMAND_MODE && !this->dce_->set_mode(modem_mode::COMMAND_MODE)) {
975 ESP_LOGW(TAG,
"Failed to leave data mode");
976 this->set_teardown_fault_();
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");
985 ESP_LOGW(TAG,
"Radio off failed");
986 this->set_teardown_fault_();
988 return ModemState::MODEM_STATE_DISABLED;
991void ModemComponent::transition_to_(ModemState next_state) {
993 if (next_state ==
state) {
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);
1000 if (next_state == ModemState::MODEM_STATE_SYNCED) {
1003 this->sync_acked_.store(0, std::memory_order_release);
1004 this->hand_over_(PENDING_ON_SYNC);
1006 while (this->sync_acked_.load(std::memory_order_acquire) == 0) {
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));
1012 ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(SYNC_ACK_TIMEOUT_MS - elapsed));
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();
1019 }
else if (next_state == ModemState::MODEM_STATE_DISCONNECTING) {
1021 this->got_ip_.store(0, std::memory_order_release);
1022 this->step_delay_ms_ = COMMAND_TIMEOUT_MS;
1026 this->hand_over_(PENDING_ON_DISCONNECT | PENDING_CONNECT_TIMEOUT);
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;
1039bool ModemComponent::escape_data_mode_() {
1040 delay(ESCAPE_GUARD_MS);
1041 if (this->dce_->set_command_mode() != command_result::OK) {
1042 ESP_LOGD(TAG,
"No answer after the data mode escape");
1045 ESP_LOGW(TAG,
"Modem was left in data mode; escaped to command mode");
1049bool ModemComponent::flush_cmux_() {
1051 if (this->rts_pin_ !=
nullptr) {
1052 ESP_LOGW(TAG,
"CMUX recovery is not available with RTS/CTS flow control");
1055 static constexpr uint8_t CMUX_FLAG = 0xF9;
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));
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));
1071 delay(CMUX_FLUSH_SETTLE_MS);
1072 if (this->dce_->sync() != command_result::OK) {
1073 ESP_LOGD(TAG,
"No answer after the CMUX flush");
1076 ESP_LOGW(TAG,
"Modem was stuck in CMUX; reset it to command mode");
1081void ModemComponent::request_resync_() {
1082 this->connect_step_ = ConnectStep::CONNECT_STEP_START;
1083 this->resync_ =
true;
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;
1093 return REGISTRATION_UNSUPPORTED;
1095 const int stat = result == command_result::OK ?
registration_from_reply(this->reply_, prefix) : REGISTRATION_UNKNOWN;
1096 if (stat == REGISTRATION_UNKNOWN) {
1098 if (result == command_result::FAIL && this->attach_polls_ % ATTACH_DIAG_EVERY == 0) {
1099 ESP_LOGW(TAG,
"%s failed: %s", cmd, this->reply_);
1101 ESP_LOGD(TAG,
"%s gave no state: %s", cmd, this->reply_);
1109int ModemComponent::read_registration_() {
1110 const int lte = this->read_stat_(
"AT+CEREG?",
"+CEREG:");
1117void ModemComponent::not_responding_(
int baud) {
1118 if (this->answered_) {
1120 ESP_LOGW(TAG,
"Modem not responding at %d baud; it may be busy or restarting", baud);
1122 ESP_LOGW(TAG,
"Modem not responding at %d baud. Check power, PWRKEY and TX/RX wiring.", baud);
1124 this->set_fault_(ModemFault::MODEM_FAULT_NO_RESPONSE);
1127void ModemComponent::sim_not_ready_(
const char *reason) {
1129 if (++this->sim_polls_ == SIM_WARN_AFTER + SIM_WARN_EVERY) {
1130 this->sim_polls_ = SIM_WARN_AFTER;
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"));
1136 this->set_fault_(ModemFault::MODEM_FAULT_SIM_NOT_READY);
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); }
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);
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);
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));
1156 memcpy(this->at_command_, cmd,
len + 1);
1157 this->at_timeout_ = timeout;
1158 this->at_pending_.store(1, std::memory_order_release);
1166command_result ModemComponent::at_reply_(
const char *cmd,
uint32_t timeout) {
1167 std::string line = cmd;
1169 this->reply_len_ = 0;
1170 this->reply_[0] =
'\0';
1171#ifdef CONFIG_ESP_MODEM_USE_INFLATABLE_BUFFER_IF_NEEDED
1173 const bool whole =
true;
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;
1183 }
state{whole,
false};
1184 const command_result result = this->dce_->command(
1186 [
this, &
state](
const uint8_t *data,
size_t len) {
1189 reinterpret_cast<const char *
>(data),
len,
state.whole);
1191 case ReplyEnd::REPLY_END_OK:
1192 return command_result::OK;
1193 case ReplyEnd::REPLY_END_ERROR:
1194 return command_result::FAIL;
1196 return command_result::TIMEOUT;
1200 this->reply_len_ =
flatten_reply(this->reply_, this->reply_len_);
1201 this->reply_cut_ =
state.cut;
1205command_result ModemComponent::at_(
const char *cmd,
uint32_t timeout) {
1206 const command_result result = this->at_reply_(cmd, timeout);
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_);
1212 ESP_LOGW(TAG,
"AT '%s' -> %s: %s%s", cmd, LOG_STR_ARG(result_to_str(result)), cut, this->reply_);
1218SimResult ModemComponent::prepare_sim_() {
1219#ifdef USE_MODEM_PIN_CODE
1221 if (this->pin_save_state_.load(std::memory_order_acquire) == PinSave::PIN_SAVE_PENDING) {
1222 return SimResult::SIM_RESULT_RETRY;
1226 const command_result result = this->at_reply_(
"AT+CPIN?");
1227 if (result == command_result::TIMEOUT) {
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;
1234 if (result != command_result::OK) {
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;
1241 const char *found =
sim_status(this->reply_);
1242 const StringRef
status = found !=
nullptr ? StringRef(found) : StringRef();
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;
1248 ESP_LOGD(TAG,
"SIM: %s",
status.c_str());
1252#ifdef USE_MODEM_PIN_CODE
1253 this->pin_step_ = PinStep::PIN_STEP_IDLE;
1254 if (this->pin_record_.sends != 0) {
1255 this->pin_record_.sends = 0;
1256 this->save_pin_record_();
1259 return SimResult::SIM_RESULT_READY;
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;
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;
1273 ESP_LOGD(TAG,
"SIM not ready: %s",
status.c_str());
1274 this->sim_not_ready_(
status.c_str());
1275 return SimResult::SIM_RESULT_RETRY;
1277#ifdef USE_MODEM_PIN_CODE
1278 return this->send_pin_();
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;
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);
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;
1302 this->pin_record_.sends++;
1303 this->pin_step_ = PinStep::PIN_STEP_SAVING;
1304 this->save_pin_record_();
1305 return SimResult::SIM_RESULT_RETRY;
1307 case PinStep::PIN_STEP_SAVING: {
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;
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_;
1321 if (this->at_(cmd.c_str(), PIN_TIMEOUT_MS) == command_result::FAIL) {
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;
1329 return SimResult::SIM_RESULT_RETRY;
1332 case PinStep::PIN_STEP_SENT:
1334 if (
millis() - this->state_started_ms_ < PIN_UNLOCK_WAIT_MS) {
1335 return SimResult::SIM_RESULT_RETRY;
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;
1343 this->set_fault_(ModemFault::MODEM_FAULT_SIM_LOCKED);
1344 return SimResult::SIM_RESULT_HALT;
1346 return SimResult::SIM_RESULT_RETRY;
1350#ifdef USE_MODEM_POLL
1352#ifdef USE_MODEM_SIGNAL
1354static constexpr float BER_PERCENT[] = {0.14f, 0.28f, 0.57f, 1.13f, 2.26f, 4.53f, 9.05f, 18.10f};
1357void ModemComponent::poll_() {
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);
1365#ifdef USE_MODEM_NETWORK_TYPE
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);
1372#ifdef USE_MODEM_NETWORK_TYPE
1374PROGMEM_STRING_TABLE(NetworkModeStrings,
"No service",
"GSM",
"GPRS",
"EDGE",
"WCDMA",
"HSDPA",
"HSUPA",
"HSPA",
"LTE",
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);
1385#ifdef USE_MODEM_NETWORK_TYPE
1386 PUBLISH_STATE(this->network_type_text_sensor_,
1387 NetworkModeStrings::get_progmem_str(
mode, NetworkModeStrings::LAST_INDEX));
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");
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");
1403 return network::IPAddress(&dns.ip.u_addr.ip4).str_to(buf);
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];
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));
BedjetMode mode
BedJet operating mode.
const StringRef & get_name() const
Get the name of this Application set by pre_setup().
constexpr const char * c_str() const
const LogString * message
unsigned long millis(void)
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.
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),...
ReplyEnd reply_end(const char *data, size_t len, bool skip_first)
How the reply ends.
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.
bool reply_names_unsupported(const char *reply)
Whether an error reply says the command is not supported (+CME ERROR: 4 or its verbose text)
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.
const char * sim_status(char *reply)
The SIM status in a flattened AT+CPIN? reply, cut before any following line, or nullptr.
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).
std::array< IPAddress, 5 > IPAddresses
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.
ESPHOME_ALWAYS_INLINE bool is_connected()
Return whether the node is connected to the network (through wifi, eth, ...)
ESPPreferences * global_preferences
uint32_t fnv1_hash(const char *str)
Calculate a FNV-1 hash of str.
void HOT delay(uint32_t ms)
uint32_t IRAM_ATTR HOT millis()
Application App
Global storage of Application pointer - only one Application can exist.
ESPPreferenceObject make_preference(size_t, uint32_t, bool)
bool sync()
Commit pending writes to flash.