2#if defined(USE_OPENTHREAD) && defined(USE_ESP32)
3#include <openthread/dataset.h>
4#include <openthread/ip6.h>
5#include <openthread/tasklet.h>
6#ifdef USE_OPENTHREAD_BORDER_ROUTER
7#include <openthread/platform/infra_if.h>
11#ifdef USE_OPENTHREAD_BORDER_ROUTER
12#include "esp_openthread_border_router.h"
14#ifndef USE_OPENTHREAD_RCP_UART
15#include "esp_coexist.h"
18#ifdef USE_OPENTHREAD_RCP_UART
19#include "esp_openthread_spinel.h"
22#include "esp_openthread.h"
23#include "esp_openthread_lock.h"
24#include "esp_openthread_types.h"
25#include "esp_task_wdt.h"
34#include "esp_openthread_netif_glue.h"
35#include "esp_vfs_eventfd.h"
36#include "freertos/FreeRTOS.h"
37#include "freertos/task.h"
38#ifndef USE_OPENTHREAD_BORDER_ROUTER
40#include "lwip/ip_addr.h"
47void OpenThreadComponent::setup() {
48#ifdef USE_OPENTHREAD_BORDER_ROUTER
50 if (backbone_netif ==
nullptr) {
51 ESP_LOGE(TAG,
"Wi-Fi STA backbone netif is not initialized");
52 this->teardown_stage_ = TeardownStage::TEARDOWN_STAGE_COMPLETED;
56 esp_openthread_set_backbone_netif(backbone_netif);
62#if defined(USE_OPENTHREAD_BORDER_ROUTER) && !defined(USE_OPENTHREAD_RCP_UART)
63 constexpr size_t max_eventfds = 4;
65 constexpr size_t max_eventfds = 3;
67 esp_vfs_eventfd_config_t eventfd_config = {
68 .max_fds = max_eventfds,
74 ESP_LOGE(TAG,
"NVS unavailable");
75 this->teardown_stage_ = TeardownStage::TEARDOWN_STAGE_COMPLETED;
79 ESP_ERROR_CHECK(esp_vfs_eventfd_register(&eventfd_config));
86 static_cast<OpenThreadComponent *
>(arg)->ot_main_();
89 CONFIG_OPENTHREAD_TASK_NAME, CONFIG_OPENTHREAD_TASK_SIZE,
this, CONFIG_OPENTHREAD_TASK_PRIORITY,
91 ESP_LOGE(TAG,
"Failed to create OpenThread task");
92 esp_vfs_eventfd_unregister();
93 this->teardown_stage_ = TeardownStage::TEARDOWN_STAGE_COMPLETED;
98void OpenThreadComponent::ot_main_() {
99 esp_openthread_platform_config_t config = {
102#ifdef USE_OPENTHREAD_RCP_UART
103 .radio_mode = RADIO_MODE_UART_RCP,
109 .baud_rate =
static_cast<int>(this->rcp_baud_rate_),
110 .data_bits = UART_DATA_8_BITS,
111 .parity = UART_PARITY_DISABLE,
112 .stop_bits = UART_STOP_BITS_1,
113 .flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
114 .rx_flow_ctrl_thresh = 0,
115 .source_clk = UART_SCLK_DEFAULT,
117 .rx_pin =
static_cast<gpio_num_t
>(this->rcp_rx_pin_),
118 .tx_pin =
static_cast<gpio_num_t
>(this->rcp_tx_pin_),
121 .radio_mode = RADIO_MODE_NATIVE,
122 .radio_uart_config = {},
134 .storage_partition_name =
"nvs",
135 .netif_queue_size = 10,
136 .task_queue_size = 10,
140#ifdef USE_OPENTHREAD_RCP_UART
142 if (this->rcp_reset_pin_ !=
nullptr) {
143 this->rcp_reset_pin_->setup();
144 esp_openthread_register_rcp_failure_handler(OpenThreadComponent::rcp_failure_handler);
145 esp_openthread_set_coprocessor_reset_failure_callback(OpenThreadComponent::rcp_failure_handler);
146 this->reset_rcp_(
false);
150 ESP_ERROR_CHECK(esp_openthread_init(&config));
153 esp_netif_config_t netif_config = ESP_NETIF_DEFAULT_OPENTHREAD();
155 assert(netif !=
nullptr);
156 ESP_ERROR_CHECK(esp_netif_attach(netif, esp_openthread_netif_glue_init(&config)));
157#ifndef USE_OPENTHREAD_BORDER_ROUTER
158 esp_netif_set_default_netif(netif);
161 ESP_LOGD(TAG,
"Thread Version: %" PRIu16, otThreadGetVersion());
163 otInstance *instance = esp_openthread_get_instance();
164 bool launch_mainloop =
true;
165#if defined(USE_OPENTHREAD_BORDER_ROUTER) && !defined(USE_OPENTHREAD_RCP_UART)
168 if (
const esp_err_t err = esp_coex_wifi_i154_enable(); err != ESP_OK) {
169 ESP_LOGE(TAG,
"Failed to enable Wi-Fi/802.15.4 coexistence: %s",
esp_err_to_name(err));
170 this->mark_task_failed_(LOG_STR(
"Coexistence could not be enabled"));
171 launch_mainloop =
false;
179 esp_openthread_lock_acquire(portMAX_DELAY);
180 this->lock_initialized_ =
true;
181 InstanceLock
lock = InstanceLock::acquire();
182 esp_openthread_lock_release();
184#ifndef USE_OPENTHREAD_BORDER_ROUTER
185 this->apply_linkmode_(instance);
188 if (this->output_power_.has_value()) {
189 if (
const auto err = otPlatRadioSetTransmitPower(instance, *this->output_power_); err != OT_ERROR_NONE) {
190 ESP_LOGE(TAG,
"Failed to set power: %s", otThreadErrorToString(err));
194 ESP_LOGI(TAG,
"Activating dataset...");
195 otOperationalDatasetTlvs dataset = {};
196 bool stored_dataset =
false;
197#ifndef USE_OPENTHREAD_FORCE_DATASET
199 if (otDatasetGetActiveTlvs(instance, &dataset) != OT_ERROR_NONE) {
203 stored_dataset =
true;
204 ESP_LOGI(TAG,
"Found existing dataset, ignoring config (force_dataset: true to override)");
208#ifdef USE_OPENTHREAD_TLVS
209 if (dataset.mLength == 0) {
211 constexpr size_t len = (
sizeof(USE_OPENTHREAD_TLVS) - 1) / 2;
212 static_assert(
len <=
sizeof(dataset.mTlvs),
"OpenThread dataset TLV is too long");
213 parse_hex(USE_OPENTHREAD_TLVS,
sizeof(USE_OPENTHREAD_TLVS) - 1, dataset.mTlvs,
len);
214 dataset.mLength =
len;
218 if (dataset.mLength > 0 && !otDatasetIsValid(&dataset,
true)) {
219 if (stored_dataset) {
220 ESP_LOGE(TAG,
"Stored OpenThread Active Operational Dataset is invalid; set force_dataset: true to replace it");
222 ESP_LOGE(TAG,
"Configured OpenThread Active Operational Dataset TLV is invalid");
224 this->mark_task_failed_(LOG_STR(
"Invalid dataset"));
225 launch_mainloop =
false;
226 }
else if (launch_mainloop) {
230 if (
const esp_err_t err = esp_openthread_auto_start(dataset.mLength > 0 ? &dataset :
nullptr); err != ESP_OK) {
232 this->mark_task_failed_(LOG_STR(
"Start failed"));
233 launch_mainloop =
false;
237 if (launch_mainloop) {
239 otError ot_err = otSetStateChangedCallback(instance, OpenThreadComponent::on_state_changed,
this);
240 if (ot_err != OT_ERROR_NONE) {
241 ESP_LOGE(TAG,
"Failed to register state change callback: %d", ot_err);
244 this->mark_task_failed_(LOG_STR(
"State callback could not be registered"));
245 launch_mainloop =
false;
250 if (launch_mainloop) {
251#ifdef USE_OPENTHREAD_BORDER_ROUTER
252 this->mainloop_running_ =
true;
254 const esp_err_t err = esp_openthread_launch_mainloop();
255#ifdef USE_OPENTHREAD_BORDER_ROUTER
256 this->mainloop_running_ =
false;
259 ESP_LOGE(TAG,
"OpenThread main loop failed: %s",
esp_err_to_name(err));
260 this->mark_task_failed_(LOG_STR(
"Main loop failed"));
266 esp_openthread_lock_acquire(portMAX_DELAY);
268 otIp6SetAddressCallback(instance,
nullptr,
nullptr);
269#ifdef USE_OPENTHREAD_BORDER_ROUTER
270 if (this->border_router_started_) {
271 (void) esp_openthread_border_router_deinit();
272 this->border_router_started_ =
false;
275 (void) otThreadSetEnabled(instance,
false);
276 (void) otIp6SetEnabled(instance,
false);
279 for (uint8_t i = 0; i < 16 && otTaskletsArePending(instance); i++) {
280 otTaskletsProcess(instance);
282 this->lock_initialized_ =
false;
283 this->connected_ =
false;
284 this->task_exited_ =
true;
285 esp_openthread_lock_release();
286 esp_openthread_netif_glue_deinit();
287 esp_netif_destroy(netif);
290 esp_openthread_lock_acquire(portMAX_DELAY);
291 esp_openthread_deinit();
292 esp_vfs_eventfd_unregister();
293 this->teardown_stage_ = TeardownStage::TEARDOWN_STAGE_COMPLETED;
298void OpenThreadComponent::mark_task_failed_(
const LogString *reason) {
299 this->defer([
this, reason]() {
300 ESP_LOGE(TAG,
"OpenThread task failed: %s", LOG_STR_ARG(reason));
305#ifdef USE_OPENTHREAD_RCP_UART
306void OpenThreadComponent::rcp_failure_handler() {
308 ESP_LOGE(TAG,
"RCP failure reported after OpenThread component was torn down");
314void OpenThreadComponent::reset_rcp_(
bool recovery_attempt) {
315 if (recovery_attempt) {
316 static constexpr uint8_t MAX_RESET_ATTEMPTS = 5;
317 uint8_t attempt = this->rcp_reset_attempts_;
318 if (attempt > MAX_RESET_ATTEMPTS) {
323 if (attempt != 0 && now - this->last_rcp_reset_ms_ > RCP_RESET_FORGET_MS) {
326 this->rcp_reset_attempts_ = ++attempt;
327 if (attempt > MAX_RESET_ATTEMPTS) {
328 ESP_LOGE(TAG,
"RCP failed to recover after %u reset attempts", MAX_RESET_ATTEMPTS);
329 this->mark_task_failed_(LOG_STR(
"RCP does not recover"));
332 ESP_LOGW(TAG,
"RCP failure detected, reset attempt %u of %u", attempt, MAX_RESET_ATTEMPTS);
333 this->last_rcp_reset_ms_ = now;
335 this->rcp_reset_pin_->digital_write(
true);
336 vTaskDelay(pdMS_TO_TICKS(10));
337 this->rcp_reset_pin_->digital_write(
false);
338 vTaskDelay(pdMS_TO_TICKS(30));
342int OpenThreadComponent::openthread_stop_() {
return esp_openthread_mainloop_exit(); }
349 auto lock = InstanceLock::try_acquire(10);
351 ESP_LOGV(TAG,
"Instance lock busy, no addresses this time");
354 if (
esp_netif_t *netif = esp_openthread_get_netif(); netif !=
nullptr) {
361#ifdef USE_OPENTHREAD_BORDER_ROUTER
362static constexpr uint32_t BORDER_ROUTER_RETRY_MS = 10000;
364void OpenThreadComponent::loop() {
369 if (!this->mainloop_running_) {
373 if (backbone_up == this->backbone_up_) {
374 this->disable_loop();
378 auto lock = InstanceLock::try_acquire(0);
382 auto retry_later = [
this](
const LogString *reason) {
383 this->status_set_error(reason);
384 this->disable_loop();
385 this->set_timeout(BORDER_ROUTER_RETRY_MS, [
this]() { this->enable_loop(); });
388 if (this->border_router_started_) {
389 ESP_LOGI(TAG,
"Wi-Fi backbone lost, border routing pauses");
390 esp_netif_t *backbone = esp_openthread_get_backbone_netif();
392 if (otPlatInfraIfStateChanged(
lock.get_instance(), esp_netif_get_netif_impl_index(backbone),
false) !=
394 ESP_LOGW(TAG,
"Stack did not take the backbone loss, routes stay until Wi-Fi returns");
397 this->backbone_up_ =
false;
398 this->disable_loop();
401 if (this->border_router_started_) {
402 ESP_LOGI(TAG,
"Wi-Fi backbone back, border routing restarts");
404 if (
const esp_err_t err = esp_openthread_border_router_deinit(); err != ESP_OK) {
405 ESP_LOGE(TAG,
"Failed to deinitialize OpenThread Border Router: %s",
esp_err_to_name(err));
406 retry_later(LOG_STR(
"Border router deinit failed"));
409 this->border_router_started_ =
false;
411 if (
const esp_err_t err = esp_openthread_border_router_init(); err != ESP_OK) {
412 ESP_LOGE(TAG,
"Failed to initialize OpenThread Border Router: %s",
esp_err_to_name(err));
413 retry_later(LOG_STR(
"Border router init failed"));
416 this->status_clear_error();
417 this->border_router_started_ =
true;
418 this->backbone_up_ =
true;
419 ESP_LOGI(TAG,
"Border routing started");
420 this->disable_loop();
425otInstance *OpenThreadComponent::get_openthread_instance_() {
return esp_openthread_get_instance(); }
427InstanceLock InstanceLock::try_acquire(
int delay) {
429 return InstanceLock(
false);
431 if (!esp_openthread_lock_acquire(
delay)) {
432 return InstanceLock(
false);
436 esp_openthread_lock_release();
437 return InstanceLock(
false);
439 return InstanceLock(
true);
443static void abort_if_task_exited() {
445 ESP_LOGE(TAG,
"OpenThread task has exited, cannot acquire instance lock");
450InstanceLock InstanceLock::acquire() {
454 ESP_LOGE(TAG,
"OpenThread component torn down, cannot acquire instance lock");
459 ESP_LOGE(TAG,
"Setup failed, cannot acquire instance lock");
464 constexpr uint32_t lock_init_timeout_ms = 10000;
467 abort_if_task_exited();
468 if (
millis() - start > lock_init_timeout_ms) {
469 ESP_LOGE(TAG,
"OpenThread lock not initialized after %" PRIu32
"ms, aborting", lock_init_timeout_ms);
473 esp_task_wdt_reset();
475 while (!esp_openthread_lock_acquire(100)) {
476 abort_if_task_exited();
477 esp_task_wdt_reset();
481 esp_openthread_lock_release();
482 abort_if_task_exited();
484 return InstanceLock(
true);
487otInstance *InstanceLock::get_instance() {
return esp_openthread_get_instance(); }
489InstanceLock::~InstanceLock() {
491 esp_openthread_lock_release();
497#ifndef USE_OPENTHREAD_BORDER_ROUTER
507 void *callback_arg, u8_t addrtype, err_t *err);
509 void *callback_arg, u8_t addrtype, err_t *err) {
511 if (ipaddr_aton(name, &literal) && IP_IS_V6_VAL(literal))
void add_connect_state_listener(WiFiConnectStateListener *listener)
Add a listener for WiFi connection state changes.
esp_netif_t * get_esp_netif_sta()
esp_netif handle of the station interface, used by network for default-route arbitration.
bool is_connected() const
const char * esp_err_to_name(esp_err_t err)
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.
OpenThreadComponent * global_openthread_component
WiFiComponent * global_wifi_component
size_t parse_hex(const char *str, size_t length, uint8_t *data, size_t count)
Parse bytes from a hex-encoded string into a byte array.
ESPPreferences * global_preferences
void HOT delay(uint32_t ms)
uint32_t IRAM_ATTR HOT millis()
struct esp_netif_obj esp_netif_t
int __real_lwip_hook_dns_external_resolve(const char *name, ip_addr_t *addr, dns_found_callback found, void *callback_arg, u8_t addrtype, err_t *err)
int __wrap_lwip_hook_dns_external_resolve(const char *name, ip_addr_t *addr, dns_found_callback found, void *callback_arg, u8_t addrtype, err_t *err)
ESPHOME_LOG_TAG(TAG, "openthread")