25using esp_modem::command_result;
26using esp_modem::create_uart_dte;
28using esp_modem::modem_mode;
33static constexpr int HP_UART_COUNT = SOC_UART_HP_NUM;
35static constexpr int HP_UART_COUNT = UART_NUM_MAX;
40static constexpr uint32_t WAIT_IP_TIMEOUT_MS = 50000;
41static constexpr uint32_t PROBE_TIMEOUT_MS = 100;
43static constexpr uint32_t PROBE_RETRY_DELAY_MS = 5000;
44static constexpr uint32_t PROBE_RETRY_MAX_MS = 60000;
46static constexpr uint32_t SYNC_ACK_TIMEOUT_MS = 5000;
48static constexpr uint32_t TASK_STACK_SIZE = 5120;
49#ifdef USE_MODEM_PIN_CODE
51static constexpr uint32_t PIN_TIMEOUT_MS = 5000;
52static constexpr uint32_t PIN_UNLOCK_WAIT_MS = 10000;
54static constexpr uint8_t PIN_MAX_UNCONFIRMED_SENDS = 2;
57static constexpr uint32_t ATTACH_POLL_MS = 4000;
58static constexpr uint8_t ATTACH_DIAG_EVERY = 4;
59static constexpr int RADIO_STATE_MINIMUM = 0;
60static constexpr int RADIO_STATE_RF_OFF = 4;
61static constexpr uint8_t UART_EVENT_QUEUE_SIZE = 10;
62static constexpr uint32_t BAUD_PREF_HASH = 76007670UL;
63static constexpr uint32_t PIN_PREF_HASH = 76007671UL;
64static constexpr int FALLBACK_BAUD_RATE = 115200;
67PROGMEM_STRING_TABLE(ModemStateStrings,
"DISABLED",
"ENABLING",
"SYNCED",
"CONNECTING",
"WAIT_IP",
"CONNECTED",
68 "DISCONNECTING",
"UNKNOWN");
70 return ModemStateStrings::get_log_str(
static_cast<uint8_t
>(
state), ModemStateStrings::LAST_INDEX);
75 "init_at command failed",
"SIM not ready",
"SIM locked",
"SIM PIN not sent; check pin_code",
76 "PIN record not saved",
"APN or radio setup failed",
"No network attachment",
"PPP link failed",
77 "Modem teardown failed");
81static const LogString *result_to_str(command_result result) {
82 return CommandResultStrings::get_log_str(
static_cast<uint8_t
>(result), CommandResultStrings::LAST_INDEX);
87 : tx_pin_(tx_pin), rx_pin_(rx_pin), model_(model), dce_factory_(factory), apn_(apn) {
91void ModemComponent::enable() {
92 ESP_LOGI(TAG,
"Setting modem target state to CONNECTED");
93 this->target_state_.store(ModemState::MODEM_STATE_CONNECTED);
94 this->probe_backoff_.store(0, std::memory_order_relaxed);
96 if (this->component_state_.load() != ModemState::MODEM_STATE_CONNECTED) {
97 this->arm_connect_timeout_();
102void ModemComponent::disable() {
103 ESP_LOGI(TAG,
"Setting modem target state to DISABLED");
104 this->target_state_.store(ModemState::MODEM_STATE_DISABLED);
105 this->cancel_connect_timeout_();
109void ModemComponent::wake_task_() {
110 if (this->task_.is_created()) {
111 xTaskNotifyGive(this->task_.get_handle());
116void ModemComponent::arm_connect_timeout_() {
118 if (this->timeout_ == 0 || this->connect_timeout_armed_) {
121 this->connect_timeout_armed_ =
true;
122 App.
scheduler.set_timeout(
this, this->timeout_, [
this]() {
124 this->connect_timeout_armed_ =
false;
128 ESP_LOGE(TAG,
"Modem was not able to connect (timeout), rebooting");
133void ModemComponent::cancel_connect_timeout_() {
134 this->connect_timeout_armed_ =
false;
140 esp_netif_ip_info_t ip;
141 if (this->
is_connected() && esp_netif_get_ip_info(this->ppp_netif_, &ip) == ESP_OK) {
142 addresses[0] = network::IPAddress(&ip.ip);
150void ModemComponent::fail_setup_(
const LogString *reason) {
151 this->mark_failed(reason);
152 if (this->target_state_.load() == ModemState::MODEM_STATE_CONNECTED) {
153 this->arm_connect_timeout_();
159void ModemComponent::hand_over_(
uint32_t pending) {
160 this->pending_.fetch_or(pending, std::memory_order_release);
161 this->enable_loop_soon_any_context();
165void ModemComponent::set_fault_(ModemFault fault) {
167 if (fault == ModemFault::MODEM_FAULT_BAUD || fault == ModemFault::MODEM_FAULT_INIT_AT) {
168 this->config_fault_.store(fault, std::memory_order_relaxed);
170 if (this->fault_.load(std::memory_order_relaxed) != fault) {
171 this->fault_.store(fault, std::memory_order_relaxed);
172 this->hand_over_(PENDING_STATUS);
177void ModemComponent::set_teardown_fault_() {
178 if (this->fault_.load(std::memory_order_relaxed) == ModemFault::MODEM_FAULT_NONE) {
179 this->set_fault_(ModemFault::MODEM_FAULT_TEARDOWN);
183void ModemComponent::clear_config_fault_(ModemFault fault) {
184 if (this->config_fault_.load(std::memory_order_relaxed) == fault) {
185 this->config_fault_.store(ModemFault::MODEM_FAULT_NONE, std::memory_order_relaxed);
186 this->hand_over_(PENDING_STATUS);
190void ModemComponent::publish_status_() {
191 ModemFault fault = this->fault_.load(std::memory_order_relaxed);
192#ifdef USE_MODEM_PIN_CODE
193 if (this->pin_record_unsaved_) {
194 fault = ModemFault::MODEM_FAULT_PIN_RECORD;
197 if (fault == ModemFault::MODEM_FAULT_NONE) {
198 fault = this->config_fault_.load(std::memory_order_relaxed);
200 if (fault == ModemFault::MODEM_FAULT_NONE) {
201 this->status_clear_warning();
202 this->status_clear_error();
205 const LogString *
message = ModemFaultStrings::get_log_str(
static_cast<uint8_t
>(fault), ModemFaultStrings::LAST_INDEX);
207 if (fault == ModemFault::MODEM_FAULT_SIM_LOCKED || fault == ModemFault::MODEM_FAULT_PIN_NOT_SENT ||
208 fault == ModemFault::MODEM_FAULT_PIN_RECORD) {
209 this->status_clear_warning();
210 this->status_set_error(
message);
212 this->status_clear_error();
213 this->status_set_warning(
message);
217void ModemComponent::loop() {
218 const uint32_t pending = this->pending_.exchange(0, std::memory_order_acquire);
219 if (pending & (PENDING_ON_SYNC | PENDING_ON_CONNECT | PENDING_ON_DISCONNECT)) {
222 const bool disconnect_first =
223 (pending & PENDING_ON_DISCONNECT) && (this->
is_connected() || (pending & PENDING_ON_SYNC));
224 if (disconnect_first) {
225 this->on_state_callback_.call(ModemState::MODEM_STATE_DISCONNECTING);
227 if (pending & PENDING_ON_SYNC) {
228 this->on_state_callback_.call(ModemState::MODEM_STATE_SYNCED);
229 this->sync_acked_.store(1, std::memory_order_release);
232 if (pending & PENDING_ON_CONNECT) {
233 this->dump_connect_params_();
234 this->on_state_callback_.call(ModemState::MODEM_STATE_CONNECTED);
236 if ((pending & PENDING_ON_DISCONNECT) && !disconnect_first) {
237 this->on_state_callback_.call(ModemState::MODEM_STATE_DISCONNECTING);
240 if (pending & PENDING_STATUS) {
241 this->publish_status_();
243 if (pending & PENDING_CONNECT_TIMEOUT) {
244 if (this->target_state_.load() == ModemState::MODEM_STATE_CONNECTED && !this->is_connected()) {
245 this->arm_connect_timeout_();
247 this->cancel_connect_timeout_();
250 if ((pending & PENDING_SAVE_BAUD) && !this->pref_.save(&this->restored_baud_)) {
251 ESP_LOGW(TAG,
"Failed to save the baud rate");
253#ifdef USE_MODEM_PIN_CODE
255 if (pending & PENDING_SAVE_PIN) {
259 ESP_LOGE(TAG,
"Failed to save the PIN record");
262 if (this->pin_record_unsaved_ != !saved) {
263 this->pin_record_unsaved_ = !saved;
264 this->publish_status_();
266 this->pin_save_state_.store(saved ? PinSave::PIN_SAVE_DONE : PinSave::PIN_SAVE_FAILED, std::memory_order_release);
271 if (pending & PENDING_ON_DISCONNECT) {
273 this->poll_unpublished_.store(0, std::memory_order_release);
274 this->publish_readings_(CSQ_UNKNOWN, CSQ_UNKNOWN, NETWORK_MODE_NO_SERVICE);
275 }
else if (this->poll_unpublished_.load(std::memory_order_acquire)) {
276 this->publish_readings_(this->poll_rssi_, this->poll_ber_, this->poll_mode_);
277 this->poll_unpublished_.store(0, std::memory_order_release);
281 if (this->urc_pending_.load(std::memory_order_acquire)) {
282 this->urc_text_sensor_->publish_state(this->urc_line_);
283 this->urc_pending_.store(0, std::memory_order_release);
287 if (this->pending_.load(std::memory_order_acquire) == 0) {
288 this->disable_loop();
292void ModemComponent::setup() {
294 this->pref_.
load(&this->restored_baud_);
295#ifdef USE_MODEM_PIN_CODE
297 if (!this->pin_pref_.load(&this->pin_record_)) {
299 ESP_LOGD(TAG,
"No PIN record stored");
303 if (this->pin_record_.hash != pin_hash) {
304 this->pin_record_ = PinRecord{pin_hash, 0};
305 if (!this->pin_pref_.save(&this->pin_record_)) {
306 ESP_LOGW(TAG,
"Failed to clear the PIN record");
314 if (pin_pref.load(&record) && record.hash != 0) {
315 record = PinRecord{};
316 if (!pin_pref.save(&record)) {
317 ESP_LOGW(TAG,
"Failed to clear the PIN record");
325 for (
int p = HP_UART_COUNT - 1; p > UART_NUM_0; p--) {
326 if (!uart_is_driver_installed(
static_cast<uart_port_t
>(p))) {
327 this->uart_port_ = p;
331 if (this->uart_port_ == UART_NUM_MAX) {
332 this->mark_failed(LOG_STR(
"No free UART port for modem"));
336 esp_netif_config_t netif_ppp_config = ESP_NETIF_DEFAULT_PPP();
337 this->ppp_netif_ = esp_netif_new(&netif_ppp_config);
338 if (this->ppp_netif_ ==
nullptr) {
339 this->fail_setup_(LOG_STR(
"PPP netif creation failed"));
343 auto ip_event = [](
void *arg, esp_event_base_t, int32_t
event_id,
void *event_data) {
344 const bool got_ip =
event_id == IP_EVENT_PPP_GOT_IP;
345 if (!got_ip &&
event_id != IP_EVENT_PPP_LOST_IP) {
349 ESP_LOGD(TAG,
"PPP IP event: Got IP " IPSTR, IP2STR(&
static_cast<ip_event_got_ip_t *
>(event_data)->ip_info.ip));
351 ESP_LOGD(TAG,
"PPP IP event: Lost IP");
353 auto *self =
static_cast<ModemComponent *
>(arg);
354 self->got_ip_.store(got_ip, std::memory_order_release);
359 auto ppp_status = [](
void *arg, esp_event_base_t, int32_t
event_id,
void *) {
361 ESP_LOGW(TAG,
"PPP error %d",
static_cast<int>(
event_id));
362 auto *self =
static_cast<ModemComponent *
>(arg);
363 self->ppp_error_.store(
static_cast<uint8_t
>(
event_id), std::memory_order_release);
364 self->got_ip_.store(0, std::memory_order_release);
368 if (esp_event_handler_register(IP_EVENT, ESP_EVENT_ANY_ID, ip_event,
this) != ESP_OK ||
369 esp_event_handler_register(NETIF_PPP_STATUS, ESP_EVENT_ANY_ID, ppp_status,
this) != ESP_OK) {
370 this->fail_setup_(LOG_STR(
"Event handler register failed"));
375 esp_modem_dte_config_t dte_config = ESP_MODEM_DTE_DEFAULT_CONFIG();
376 dte_config.uart_config.tx_io_num = this->tx_pin_->get_pin();
377 dte_config.uart_config.rx_io_num = this->rx_pin_->get_pin();
378 dte_config.uart_config.rx_buffer_size = this->rx_buffer_size_;
379 dte_config.uart_config.tx_buffer_size = this->tx_buffer_size_;
380 dte_config.uart_config.event_queue_size = UART_EVENT_QUEUE_SIZE;
381 dte_config.uart_config.port_num =
static_cast<uart_port_t
>(this->uart_port_);
384 const int start_baud = this->restored_baud_ != 0 ? this->restored_baud_ : this->baud_rate_;
385 if (start_baud != 0) {
386 dte_config.uart_config.baud_rate = start_baud;
388 if (this->rts_pin_ !=
nullptr) {
389 dte_config.uart_config.rts_io_num = this->rts_pin_->get_pin();
390 dte_config.uart_config.cts_io_num = this->cts_pin_->get_pin();
391 dte_config.uart_config.flow_control = ESP_MODEM_FLOW_CONTROL_HW;
393 dte_config.dte_buffer_size = this->dte_buffer_size_;
394 this->current_baud_rate_ = dte_config.uart_config.baud_rate;
395 this->dte_ = create_uart_dte(&dte_config);
396 esp_modem_dce_config_t dce_config = ESP_MODEM_DCE_DEFAULT_CONFIG(this->apn_);
398 this->dce_ = this->dce_factory_(&dce_config, this->dte_, this->ppp_netif_);
401 this->fail_setup_(LOG_STR(
"Modem DTE/DCE creation failed"));
406 if (this->tx_pin_->is_inverted()) {
407 invert |= UART_SIGNAL_TXD_INV;
409 if (this->rx_pin_->is_inverted()) {
410 invert |= UART_SIGNAL_RXD_INV;
412 if (this->rts_pin_ !=
nullptr) {
413 if (this->rts_pin_->is_inverted()) {
414 invert |= UART_SIGNAL_RTS_INV;
416 if (this->cts_pin_->is_inverted()) {
417 invert |= UART_SIGNAL_CTS_INV;
420 if (invert != 0 && uart_set_line_inverse(
static_cast<uart_port_t
>(this->uart_port_), invert) != ESP_OK) {
421 this->fail_setup_(LOG_STR(
"UART line inversion failed"));
427 this->dce_->set_enhanced_urc([
this](
const DTE::UrcBufferInfo &buffer_info) {
430 if (buffer_info.is_command_active) {
431 this->urc_reader_.reset();
432 return DTE::UrcConsumeInfo{DTE::UrcConsumeResult::CONSUME_NONE, 0};
434 bool dropped =
false;
435 for (
size_t i = 0; i < buffer_info.new_data_size; i++) {
436 const uint8_t c = buffer_info.new_data_start[i];
437 if (this->urc_pending_.load(std::memory_order_acquire)) {
439 dropped |= c !=
'\r' && c !=
'\n';
440 this->urc_reader_.discard_line();
442 const char *line = this->urc_reader_.feed(c);
443 this->urc_reader_.log_if_overflowed(TAG);
444 if (line !=
nullptr && line[0] !=
'\0') {
445 this->urc_line_ = line;
446 this->urc_pending_.store(1, std::memory_order_release);
447 this->enable_loop_soon_any_context();
451 ESP_LOGW(TAG,
"URC dropped; the previous one is not published yet");
453 return DTE::UrcConsumeInfo{DTE::UrcConsumeResult::CONSUME_ALL, 0};
456 if (!this->task_.create(ModemComponent::task_entry,
"modem", TASK_STACK_SIZE,
this, 1,
false)) {
457 this->fail_setup_(LOG_STR(
"Task creation failed"));
461void ModemComponent::dump_config() {
462#ifdef USE_MODEM_PIN_CODE
463 const char *pin_code = LOG_STR_LITERAL(
"Yes (not shown)");
465 const char *pin_code = LOG_STR_LITERAL(
"No");
476 " TX buffer size: %u\n"
477 " RX buffer size: %u\n"
478 " DTE buffer size: %u\n"
479 " Reboot timeout: %" PRIu32
" ms\n"
481 this->model_, this->apn_, pin_code, this->tx_pin_->get_pin(), this->rx_pin_->get_pin(),
482 static_cast<int>(this->uart_port_), this->current_baud_rate_, this->tx_buffer_size_,
483 this->rx_buffer_size_, this->dte_buffer_size_, this->timeout_, YESNO(this->is_enabled()));
485 ESP_LOGCONFIG(TAG,
" Update interval: %" PRIu32
" ms", this->update_interval_);
487#ifdef USE_MODEM_SIGNAL
488 LOG_SENSOR(
" ",
"RSSI", this->rssi_sensor_);
489 LOG_SENSOR(
" ",
"BER", this->ber_sensor_);
491#ifdef USE_MODEM_NETWORK_TYPE
492 LOG_TEXT_SENSOR(
" ",
"Network type", this->network_type_text_sensor_);
494 this->dump_connect_params_();
497void ModemComponent::task_entry(
void *arg) {
static_cast<ModemComponent *
>(arg)->run_task_(); }
499void ModemComponent::run_task_() {
501#ifdef USE_MODEM_SEND_AT
503 if (this->at_pending_.load(std::memory_order_acquire)) {
504 this->at_(this->at_command_, this->at_timeout_);
505 this->at_pending_.store(0, std::memory_order_release);
508 this->step_delay_ms_ = 0;
509 this->transition_to_(this->compute_next_state_());
511 const bool parked = this->component_state_.load() == this->target_state_.load();
512 TickType_t wait = parked ? portMAX_DELAY : pdMS_TO_TICKS(this->step_delay_ms_);
516 int32_t remaining =
static_cast<int32_t
>(this->next_poll_ms_ -
millis());
517 if (remaining <= 0) {
519 if (!this->poll_unpublished_.load(std::memory_order_acquire)) {
521 this->poll_unpublished_.store(1, std::memory_order_release);
522 this->enable_loop_soon_any_context();
524 this->next_poll_ms_ =
millis() + this->update_interval_;
525 remaining =
static_cast<int32_t
>(this->update_interval_);
527 wait = pdMS_TO_TICKS(remaining);
530 ulTaskNotifyTake(pdTRUE, wait);
534uint32_t ModemComponent::next_probe_delay_() {
535 const uint8_t backoff = this->probe_backoff_.load(std::memory_order_relaxed);
536 const uint32_t delay_ms = std::min(PROBE_RETRY_DELAY_MS << backoff, PROBE_RETRY_MAX_MS);
537 if (delay_ms < PROBE_RETRY_MAX_MS) {
538 this->probe_backoff_.store(backoff + 1, std::memory_order_relaxed);
544 this->step_delay_ms_ = delay_ms;
548ModemState ModemComponent::compute_next_state_() {
550 if (this->target_state_.load() == ModemState::MODEM_STATE_DISABLED) {
551 if (
state == ModemState::MODEM_STATE_DISABLED) {
552 return ModemState::MODEM_STATE_DISABLED;
554 if (
state != ModemState::MODEM_STATE_DISCONNECTING) {
555 return ModemState::MODEM_STATE_DISCONNECTING;
560 case ModemState::MODEM_STATE_DISABLED:
561#ifdef USE_MODEM_PIN_CODE
563 if (this->pin_step_ == PinStep::PIN_STEP_SENT) {
564 this->pin_step_ = PinStep::PIN_STEP_IDLE;
567 return ModemState::MODEM_STATE_ENABLING;
568 case ModemState::MODEM_STATE_ENABLING:
569 return this->handle_state_enabling_();
570 case ModemState::MODEM_STATE_SYNCED:
571 return this->handle_state_synced_();
572 case ModemState::MODEM_STATE_CONNECTING:
573 return this->handle_state_connecting_();
574 case ModemState::MODEM_STATE_WAIT_IP:
575 return this->handle_state_wait_ip_();
576 case ModemState::MODEM_STATE_CONNECTED:
577 if (this->got_ip_.load(std::memory_order_acquire)) {
578 return ModemState::MODEM_STATE_CONNECTED;
580 ESP_LOGW(TAG,
"Lost IP; PPP error %u", this->ppp_error_.load(std::memory_order_acquire));
581 this->ppp_error_.store(0, std::memory_order_release);
582 this->set_fault_(ModemFault::MODEM_FAULT_PPP);
583 return ModemState::MODEM_STATE_DISCONNECTING;
584 case ModemState::MODEM_STATE_DISCONNECTING:
585 return this->handle_state_disconnecting_();
590ModemState ModemComponent::handle_state_enabling_() {
592 if (!this->dce_->set_mode(modem_mode::AUTODETECT)) {
594 this->dce_->set_mode(modem_mode::UNDEF);
596 auto mode = this->dce_->get_mode();
597 ESP_LOGD(TAG,
"Autodetect mode: %d",
static_cast<int>(
mode));
602 case modem_mode::CMUX_MANUAL_MODE:
604 ESP_LOGD(TAG,
"Modem warm reboot. Exiting CMUX");
605 if (!this->dce_->set_mode(modem_mode::CMUX_MANUAL_EXIT)) {
606 ESP_LOGW(TAG,
"Failed to exit CMUX");
610 case modem_mode::UNDEF: {
612 const int detected = this->current_baud_rate_;
614 const int bauds[] = {this->restored_baud_, this->baud_rate_, FALLBACK_BAUD_RATE};
617 bool rejected =
false;
618 for (
size_t i = 0; i != std::size(bauds) && !found; i++) {
619 const int baud = bauds[i];
620 if (baud == 0 || baud == detected || std::find(bauds, bauds + i, baud) != bauds + i) {
623 if (uart_set_baudrate(
static_cast<uart_port_t
>(this->uart_port_), baud) != ESP_OK) {
624 ESP_LOGW(TAG,
"UART rejected baud rate %d", baud);
625 this->set_fault_(ModemFault::MODEM_FAULT_BAUD);
629 this->current_baud_rate_ = baud;
632 found = this->dce_->at(
"AT", output, PROBE_TIMEOUT_MS) == command_result::OK;
634 this->not_responding_(baud);
639 if (!probed && !rejected) {
640 this->not_responding_(detected);
642 return this->retry_(ModemState::MODEM_STATE_ENABLING, this->next_probe_delay_());
644 ESP_LOGD(TAG,
"Modem responded at baud %d", this->current_baud_rate_);
648 case modem_mode::COMMAND_MODE:
652 case modem_mode::DATA_MODE:
654 ESP_LOGW(TAG,
"Exiting DATA_MODE");
655 if (!this->dce_->set_mode(modem_mode::COMMAND_MODE)) {
656 ESP_LOGW(TAG,
"Failed to leave data mode");
661 ESP_LOGW(TAG,
"Modem in unexpected mode %d. Switching to COMMAND mode.",
static_cast<int>(
mode));
662 if (!this->dce_->set_mode(modem_mode::COMMAND_MODE)) {
663 ESP_LOGW(TAG,
"Failed to switch to command mode");
665 this->dce_->set_mode(modem_mode::UNDEF);
669 if (exited && this->dce_->sync() != command_result::OK) {
672 ESP_LOGW(TAG,
"Modem did not return to command mode");
673 this->set_fault_(ModemFault::MODEM_FAULT_TEARDOWN);
674 return this->retry_(ModemState::MODEM_STATE_ENABLING, this->next_probe_delay_());
677 if (this->dce_->set_echo(
false) != command_result::OK) {
678 ESP_LOGW(TAG,
"Failed to disable command echo");
683 esp_modem::PdpContext pdp(this->apn_);
684 this->apn_pending_ = this->dce_->set_radio_state(RADIO_STATE_MINIMUM) != command_result::OK ||
685 this->dce_->set_pdp_context(pdp) != command_result::OK;
686 if (this->apn_pending_) {
687 ESP_LOGW(TAG,
"Failed to set the APN with the SIM powered down; setting it after the SIM check");
690 if (this->dce_->set_radio_state(RADIO_STATE_RF_OFF) != command_result::OK &&
691 this->dce_->set_radio_state(1) != command_result::OK) {
692 ESP_LOGW(TAG,
"Failed to power the SIM up");
693 this->set_fault_(ModemFault::MODEM_FAULT_SETUP);
694 this->modem_synced_ =
true;
695 return this->retry_(ModemState::MODEM_STATE_ENABLING, this->next_probe_delay_());
697 this->probe_backoff_.store(0, std::memory_order_relaxed);
699 if (this->baud_rate_ != 0 && this->baud_rate_ != this->current_baud_rate_) {
700 ESP_LOGD(TAG,
"Setting baud rate: %d -> %d", this->current_baud_rate_, this->baud_rate_);
701 if (this->dce_->set_baud(this->baud_rate_) == command_result::OK) {
703 if (uart_set_baudrate(
static_cast<uart_port_t
>(this->uart_port_), this->baud_rate_) != ESP_OK) {
704 ESP_LOGE(TAG,
"UART rejected baud rate %d", this->baud_rate_);
705 this->set_fault_(ModemFault::MODEM_FAULT_BAUD);
706 return ModemState::MODEM_STATE_DISCONNECTING;
708 this->current_baud_rate_ = this->baud_rate_;
709 if (this->dce_->sync() != command_result::OK) {
710 ESP_LOGE(TAG,
"Failed to sync modem at baud rate %d.", this->baud_rate_);
711 this->set_fault_(ModemFault::MODEM_FAULT_BAUD);
712 return ModemState::MODEM_STATE_DISCONNECTING;
714 ESP_LOGI(TAG,
"Modem synced at baud rate %d.", this->current_baud_rate_);
717 ESP_LOGW(TAG,
"Modem rejected baud rate %d. Staying at %d.", this->baud_rate_, this->current_baud_rate_);
718 this->set_fault_(ModemFault::MODEM_FAULT_BAUD);
723 if (this->baud_rate_ == 0 || this->baud_rate_ == this->current_baud_rate_) {
724 this->clear_config_fault_(ModemFault::MODEM_FAULT_BAUD);
726 if (this->restored_baud_ != this->current_baud_rate_) {
727 this->restored_baud_ = this->current_baud_rate_;
728 this->hand_over_(PENDING_SAVE_BAUD);
732 if (this->rts_pin_ !=
nullptr && this->dce_->set_flow_control(2, 2) != command_result::OK) {
733 ESP_LOGW(TAG,
"Modem refused hardware flow control; UART overruns are possible");
735 this->modem_synced_ =
true;
736 return ModemState::MODEM_STATE_SYNCED;
739ModemState ModemComponent::handle_state_synced_() {
742 for (uint8_t i = 0; i != this->init_at_count_; i++) {
743 failed |= this->at_(this->init_at_commands_[i]) != command_result::OK;
746 this->set_fault_(ModemFault::MODEM_FAULT_INIT_AT);
748 this->clear_config_fault_(ModemFault::MODEM_FAULT_INIT_AT);
750 this->connect_step_ = ConnectStep::CONNECT_STEP_START;
751 return ModemState::MODEM_STATE_CONNECTING;
754ModemState ModemComponent::handle_state_connecting_() {
755 if (this->connect_step_ == ConnectStep::CONNECT_STEP_START) {
758 this->resync_ =
false;
759 if (this->dce_->sync() != command_result::OK) {
760 ESP_LOGW(TAG,
"Modem not synced during network init");
761 return ModemState::MODEM_STATE_ENABLING;
765 switch (this->prepare_sim_()) {
766 case SimResult::SIM_RESULT_READY:
768 case SimResult::SIM_RESULT_RETRY:
769 return this->retry_(ModemState::MODEM_STATE_CONNECTING);
770 case SimResult::SIM_RESULT_LOCKED:
772 this->target_state_.store(ModemState::MODEM_STATE_DISABLED);
773 this->hand_over_(PENDING_CONNECT_TIMEOUT);
774 return ModemState::MODEM_STATE_DISCONNECTING;
775 case SimResult::SIM_RESULT_HALT:
778 this->target_state_.store(ModemState::MODEM_STATE_DISABLED);
779 return ModemState::MODEM_STATE_DISCONNECTING;
781 if (this->apn_pending_) {
782 esp_modem::PdpContext pdp(this->apn_);
783 if (this->dce_->set_pdp_context(pdp) != command_result::OK) {
784 ESP_LOGW(TAG,
"Failed to set the APN");
785 this->set_fault_(ModemFault::MODEM_FAULT_SETUP);
786 return this->retry_(ModemState::MODEM_STATE_CONNECTING);
788 this->apn_pending_ =
false;
790 if (this->dce_->set_radio_state(1) != command_result::OK) {
791 ESP_LOGW(TAG,
"Failed to turn the radio on");
792 this->set_fault_(ModemFault::MODEM_FAULT_SETUP);
793 return this->retry_(ModemState::MODEM_STATE_CONNECTING);
795 this->connect_step_ = ConnectStep::CONNECT_STEP_RADIO_ON;
796 this->attach_polls_ = 0;
799 if (this->connect_step_ == ConnectStep::CONNECT_STEP_RADIO_ON) {
801 if (this->dce_->set_network_attachment_state(1) != command_result::OK) {
802 ESP_LOGD(TAG,
"Network attachment request refused");
804 this->connect_step_ = ConnectStep::CONNECT_STEP_ATTACH_REQUESTED;
808 if (this->dce_->get_network_attachment_state(attached) != command_result::OK) {
809 ESP_LOGW(TAG,
"Failed to read the network attachment state");
810 this->set_fault_(ModemFault::MODEM_FAULT_NOT_ATTACHED);
811 this->connect_step_ = ConnectStep::CONNECT_STEP_START;
812 this->resync_ =
true;
813 return this->retry_(ModemState::MODEM_STATE_CONNECTING);
816 if (this->attach_polls_++ % ATTACH_DIAG_EVERY == 0) {
817 int rssi = 99, ber = 99, registration = -1,
mode = -1;
818 this->dce_->get_network_registration_state(registration);
819 this->dce_->get_signal_quality(rssi, ber);
820 this->dce_->get_network_system_mode(
mode);
821 ESP_LOGW(TAG,
"Modem not attached yet: registration %d, network type %d, CSQ %d, BER %d", registration,
mode,
823 this->connect_step_ = ConnectStep::CONNECT_STEP_RADIO_ON;
825 this->set_fault_(ModemFault::MODEM_FAULT_NOT_ATTACHED);
826 return this->retry_(ModemState::MODEM_STATE_CONNECTING, ATTACH_POLL_MS);
829 ESP_LOGI(TAG,
"Modem initialized and ready, starting PPP");
831 this->got_ip_.store(0, std::memory_order_release);
832 this->ppp_error_.store(0, std::memory_order_release);
833 if (!this->dce_->set_mode(modem_mode::CMUX_MODE)) {
834 ESP_LOGE(TAG,
"Failed to enter PPP. Resetting modem.");
835 this->set_fault_(ModemFault::MODEM_FAULT_PPP);
836 return ModemState::MODEM_STATE_DISCONNECTING;
838 this->state_started_ms_ =
millis();
839 return ModemState::MODEM_STATE_WAIT_IP;
842ModemState ModemComponent::handle_state_wait_ip_() {
843 if (this->got_ip_.load(std::memory_order_acquire)) {
844 this->set_fault_(ModemFault::MODEM_FAULT_NONE);
845 return ModemState::MODEM_STATE_CONNECTED;
848 if (this->ppp_error_.load(std::memory_order_acquire) != 0) {
849 this->ppp_error_.store(0, std::memory_order_release);
850 this->set_fault_(ModemFault::MODEM_FAULT_PPP);
851 return ModemState::MODEM_STATE_DISCONNECTING;
854 if (elapsed < WAIT_IP_TIMEOUT_MS) {
856 return this->retry_(ModemState::MODEM_STATE_WAIT_IP, WAIT_IP_TIMEOUT_MS - elapsed);
858 ESP_LOGE(TAG,
"Unable to get IP address");
859 this->set_fault_(ModemFault::MODEM_FAULT_PPP);
860 return ModemState::MODEM_STATE_DISCONNECTING;
863ModemState ModemComponent::handle_state_disconnecting_() {
865 if (!this->modem_synced_) {
866 return ModemState::MODEM_STATE_DISABLED;
868 this->modem_synced_ =
false;
870 if (this->dce_->get_mode() != modem_mode::COMMAND_MODE && !this->dce_->set_mode(modem_mode::COMMAND_MODE)) {
872 ESP_LOGW(TAG,
"Failed to leave data mode");
873 this->set_teardown_fault_();
877 if (this->dce_->set_radio_state(RADIO_STATE_MINIMUM) == command_result::OK) {
878 ESP_LOGI(TAG,
"Radio off");
879 }
else if (this->dce_->set_radio_state(RADIO_STATE_RF_OFF) == command_result::OK) {
880 ESP_LOGW(TAG,
"Radio off, but the SIM could not be powered down");
882 ESP_LOGW(TAG,
"Radio off failed");
883 this->set_teardown_fault_();
885 return ModemState::MODEM_STATE_DISABLED;
888void ModemComponent::transition_to_(ModemState next_state) {
890 if (next_state ==
state) {
893 const bool lost = next_state == ModemState::MODEM_STATE_DISCONNECTING &&
state == ModemState::MODEM_STATE_CONNECTED;
894 ESP_LOGD(TAG,
"State change: %s -> %s", LOG_STR_ARG(state_to_str(
state)), LOG_STR_ARG(state_to_str(next_state)));
895 this->component_state_.store(next_state);
897 if (next_state == ModemState::MODEM_STATE_SYNCED) {
900 this->sync_acked_.store(0, std::memory_order_release);
901 this->hand_over_(PENDING_ON_SYNC);
903 while (this->sync_acked_.load(std::memory_order_acquire) == 0) {
905 if (elapsed >= SYNC_ACK_TIMEOUT_MS) {
906 ESP_LOGW(TAG,
"on_sync did not run within %u ms; continuing",
static_cast<unsigned>(SYNC_ACK_TIMEOUT_MS));
909 ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(SYNC_ACK_TIMEOUT_MS - elapsed));
911 }
else if (next_state == ModemState::MODEM_STATE_CONNECTED) {
912 this->hand_over_(PENDING_ON_CONNECT | PENDING_CONNECT_TIMEOUT);
914 this->next_poll_ms_ =
millis();
916 }
else if (next_state == ModemState::MODEM_STATE_DISCONNECTING) {
918 this->got_ip_.store(0, std::memory_order_release);
919 this->step_delay_ms_ = COMMAND_TIMEOUT_MS;
923 this->hand_over_(PENDING_ON_DISCONNECT | PENDING_CONNECT_TIMEOUT);
928void ModemComponent::not_responding_(
int baud) {
929 ESP_LOGW(TAG,
"Modem not responding at %d baud. Check power, PWRKEY and TX/RX wiring.", baud);
930 this->set_fault_(ModemFault::MODEM_FAULT_NO_RESPONSE);
933#ifdef USE_MODEM_SEND_AT
934bool ModemComponent::send_at(
const std::string &cmd,
uint32_t timeout) {
return this->send_at(cmd.c_str(), timeout); }
936bool ModemComponent::send_at(
const char *cmd,
uint32_t timeout) {
937 if (!this->task_.is_created()) {
938 ESP_LOGW(TAG,
"Modem not ready, cannot send AT command: %s", cmd);
941 if (this->at_pending_.load(std::memory_order_acquire)) {
942 ESP_LOGW(TAG,
"AT command '%s' dropped; the previous one is not sent yet", cmd);
945 const size_t len = strlen(cmd);
946 if (
len >=
sizeof(this->at_command_)) {
947 ESP_LOGW(TAG,
"AT command longer than %u bytes dropped",
static_cast<unsigned>(
sizeof(this->at_command_) - 1));
950 memcpy(this->at_command_, cmd,
len + 1);
951 this->at_timeout_ = timeout;
952 this->at_pending_.store(1, std::memory_order_release);
959command_result ModemComponent::at_(
const char *cmd,
uint32_t timeout) {
961 const command_result result = this->dce_->at(cmd, output, timeout);
962 if (result == command_result::OK) {
963 ESP_LOGI(TAG,
"AT '%s' -> OK: %s", cmd, output.c_str());
965 ESP_LOGW(TAG,
"AT '%s' -> %s: %s", cmd, LOG_STR_ARG(result_to_str(result)), output.c_str());
971SimResult ModemComponent::prepare_sim_() {
972#ifdef USE_MODEM_PIN_CODE
974 if (this->pin_save_state_.load(std::memory_order_acquire) == PinSave::PIN_SAVE_PENDING) {
975 return SimResult::SIM_RESULT_RETRY;
979 if (this->dce_->at(
"AT+CPIN?", output, COMMAND_TIMEOUT_MS) != command_result::OK) {
981 ESP_LOGD(TAG,
"SIM status not readable yet: %s", output.c_str());
982 this->set_fault_(ModemFault::MODEM_FAULT_SIM_NOT_READY);
983 return SimResult::SIM_RESULT_RETRY;
986 const char *found = strstr(output.c_str(),
"+CPIN:");
987 if (found !=
nullptr) {
988 found +=
sizeof(
"+CPIN:") - 1;
989 while (*found ==
' ') {
993 const StringRef
status = found !=
nullptr ? StringRef(found) : StringRef();
995 ESP_LOGD(TAG,
"SIM status not reported yet: %s", output.c_str());
996 this->set_fault_(ModemFault::MODEM_FAULT_SIM_NOT_READY);
997 return SimResult::SIM_RESULT_RETRY;
999 ESP_LOGD(TAG,
"SIM: %s",
status.c_str());
1003#ifdef USE_MODEM_PIN_CODE
1004 this->pin_step_ = PinStep::PIN_STEP_IDLE;
1005 if (this->pin_record_.sends != 0) {
1006 this->pin_record_.sends = 0;
1007 this->save_pin_record_();
1010 return SimResult::SIM_RESULT_READY;
1012 if (strstr(
status.c_str(),
"PUK") !=
nullptr) {
1013 ESP_LOGE(TAG,
"SIM is PUK locked; unlock it in a phone");
1014 this->set_fault_(ModemFault::MODEM_FAULT_SIM_LOCKED);
1015 return SimResult::SIM_RESULT_LOCKED;
1018 if (!
status.starts_with(
"SIM PIN") ||
status.starts_with(
"SIM PIN2")) {
1019 if (strstr(status.c_str(),
"PIN") != nullptr) {
1020 ESP_LOGE(TAG,
"SIM lock %s needs a credential pin_code cannot provide", status.c_str());
1021 this->set_fault_(ModemFault::MODEM_FAULT_SIM_LOCKED);
1022 return SimResult::SIM_RESULT_LOCKED;
1024 ESP_LOGW(TAG,
"SIM not ready: %s",
status.c_str());
1025 this->set_fault_(ModemFault::MODEM_FAULT_SIM_NOT_READY);
1026 return SimResult::SIM_RESULT_RETRY;
1028#ifdef USE_MODEM_PIN_CODE
1029 return this->send_pin_();
1031 ESP_LOGE(TAG,
"SIM requires a PIN but pin_code is not set");
1032 this->set_fault_(ModemFault::MODEM_FAULT_SIM_LOCKED);
1033 return SimResult::SIM_RESULT_LOCKED;
1037#ifdef USE_MODEM_PIN_CODE
1038void ModemComponent::save_pin_record_() {
1039 this->pin_save_state_.store(PinSave::PIN_SAVE_PENDING, std::memory_order_release);
1040 this->hand_over_(PENDING_SAVE_PIN);
1046 switch (this->pin_step_) {
1047 case PinStep::PIN_STEP_IDLE:
1048 if (this->pin_record_.sends >= PIN_MAX_UNCONFIRMED_SENDS) {
1049 ESP_LOGE(TAG,
"The SIM never confirmed this pin_code; not sending it again");
1050 this->set_fault_(ModemFault::MODEM_FAULT_PIN_NOT_SENT);
1051 return SimResult::SIM_RESULT_LOCKED;
1053 this->pin_record_.sends++;
1054 this->pin_step_ = PinStep::PIN_STEP_SAVING;
1055 this->save_pin_record_();
1056 return SimResult::SIM_RESULT_RETRY;
1058 case PinStep::PIN_STEP_SAVING: {
1060 if (this->pin_save_state_.load(std::memory_order_acquire) != PinSave::PIN_SAVE_DONE) {
1061 ESP_LOGE(TAG,
"The PIN attempt could not be recorded; not sending it");
1062 this->pin_record_.sends--;
1063 this->pin_step_ = PinStep::PIN_STEP_IDLE;
1064 this->set_fault_(ModemFault::MODEM_FAULT_PIN_RECORD);
1065 return SimResult::SIM_RESULT_HALT;
1067 this->pin_step_ = PinStep::PIN_STEP_SENT;
1068 this->state_started_ms_ =
millis();
1069 std::string cmd =
"AT+CPIN=\"";
1070 cmd += this->pin_code_;
1072 if (this->at_(cmd.c_str(), PIN_TIMEOUT_MS) == command_result::FAIL) {
1074 ESP_LOGE(TAG,
"The SIM refused the PIN; check pin_code");
1075 this->pin_record_.sends = PIN_MAX_UNCONFIRMED_SENDS;
1076 this->save_pin_record_();
1077 this->set_fault_(ModemFault::MODEM_FAULT_PIN_NOT_SENT);
1078 return SimResult::SIM_RESULT_LOCKED;
1080 return SimResult::SIM_RESULT_RETRY;
1083 case PinStep::PIN_STEP_SENT:
1085 if (
millis() - this->state_started_ms_ < PIN_UNLOCK_WAIT_MS) {
1086 return SimResult::SIM_RESULT_RETRY;
1088 ESP_LOGE(TAG,
"SIM still locked after sending the PIN; check the SIM");
1089 if (this->pin_record_.sends >= PIN_MAX_UNCONFIRMED_SENDS) {
1090 this->set_fault_(ModemFault::MODEM_FAULT_PIN_NOT_SENT);
1091 return SimResult::SIM_RESULT_LOCKED;
1094 this->set_fault_(ModemFault::MODEM_FAULT_SIM_LOCKED);
1095 return SimResult::SIM_RESULT_HALT;
1097 return SimResult::SIM_RESULT_RETRY;
1101#ifdef USE_MODEM_POLL
1103#ifdef USE_MODEM_SIGNAL
1105static constexpr float BER_PERCENT[] = {0.14f, 0.28f, 0.57f, 1.13f, 2.26f, 4.53f, 9.05f, 18.10f};
1108void ModemComponent::poll_() {
1110#ifdef USE_MODEM_SIGNAL
1111 int rssi = CSQ_UNKNOWN, ber = CSQ_UNKNOWN;
1112 const bool signal_ok = this->dce_->get_signal_quality(rssi, ber) == command_result::OK;
1113 this->poll_rssi_ =
static_cast<uint8_t
>(signal_ok && rssi >= 0 && rssi < CSQ_UNKNOWN ? rssi : CSQ_UNKNOWN);
1114 this->poll_ber_ =
static_cast<uint8_t
>(signal_ok && ber >= 0 && ber < CSQ_UNKNOWN ? ber : CSQ_UNKNOWN);
1116#ifdef USE_MODEM_NETWORK_TYPE
1118 const bool mode_ok = this->dce_->get_network_system_mode(
mode) == command_result::OK;
1119 this->poll_mode_ =
static_cast<uint8_t
>(mode_ok &&
mode >= 0 &&
mode < NETWORK_MODE_NONE ?
mode : NETWORK_MODE_NONE);
1123#ifdef USE_MODEM_NETWORK_TYPE
1125PROGMEM_STRING_TABLE(NetworkModeStrings,
"No service",
"GSM",
"GPRS",
"EDGE",
"WCDMA",
"HSDPA",
"HSUPA",
"HSPA",
"LTE",
1130void ModemComponent::publish_readings_([[maybe_unused]] uint8_t rssi, [[maybe_unused]] uint8_t ber,
1131 [[maybe_unused]] uint8_t
mode) {
1132#ifdef USE_MODEM_SIGNAL
1133 PUBLISH_STATE(this->rssi_sensor_, rssi <= CSQ_RSSI_MAX ? -113.0f + 2.0f * rssi : NAN);
1134 PUBLISH_STATE(this->ber_sensor_, ber < std::size(BER_PERCENT) ? BER_PERCENT[ber] : NAN);
1136#ifdef USE_MODEM_NETWORK_TYPE
1137 PUBLISH_STATE(this->network_type_text_sensor_,
1138 NetworkModeStrings::get_progmem_str(
mode, NetworkModeStrings::LAST_INDEX));
1143void ModemComponent::dump_connect_params_() {
1144 esp_netif_ip_info_t ip;
1145 if (!this->got_ip_.load(std::memory_order_acquire) || esp_netif_get_ip_info(this->ppp_netif_, &ip) != ESP_OK) {
1146 ESP_LOGCONFIG(TAG,
" Connection: not connected");
1149 auto dns_str = [
this](esp_netif_dns_type_t
type,
char *buf) ->
const char * {
1150 esp_netif_dns_info_t dns{};
1151 if (esp_netif_get_dns_info(this->ppp_netif_,
type, &dns) != ESP_OK) {
1152 return LOG_STR_LITERAL(
"unavailable");
1154 return network::IPAddress(&dns.ip.u_addr.ip4).str_to(buf);
1156 char ip_buf[network::IP_ADDRESS_BUFFER_SIZE];
1157 char netmask_buf[network::IP_ADDRESS_BUFFER_SIZE];
1158 char gw_buf[network::IP_ADDRESS_BUFFER_SIZE];
1159 char dns_main_buf[network::IP_ADDRESS_BUFFER_SIZE];
1160 char dns_backup_buf[network::IP_ADDRESS_BUFFER_SIZE];
1170 network::IPAddress(&ip.netmask).str_to(netmask_buf), network::IPAddress(&ip.gw).str_to(gw_buf),
1171 dns_str(ESP_NETIF_DNS_MAIN, dns_main_buf), dns_str(ESP_NETIF_DNS_BACKUP, dns_backup_buf));