ESPHome 2026.3.3
Loading...
Searching...
No Matches
openthread_esp.cpp
Go to the documentation of this file.
2#if defined(USE_OPENTHREAD) && defined(USE_ESP32)
3#include <openthread/logging.h>
4#include "openthread.h"
5
6#include "esp_log.h"
7#include "esp_openthread.h"
8#include "esp_openthread_lock.h"
9
10#include "esp_task_wdt.h"
11#include "esphome/core/hal.h"
13#include "esphome/core/log.h"
14
15#include "esp_err.h"
16#include "esp_event.h"
17#include "esp_netif.h"
18#include "esp_netif_types.h"
19#include "esp_openthread_cli.h"
20#include "esp_openthread_netif_glue.h"
21#include "esp_vfs_eventfd.h"
22#include "freertos/FreeRTOS.h"
23#include "freertos/task.h"
24#include "nvs_flash.h"
25
26static const char *const TAG = "openthread";
27
28namespace esphome::openthread {
29
31 // Used eventfds:
32 // * netif
33 // * ot task queue
34 // * radio driver
35 esp_vfs_eventfd_config_t eventfd_config = {
36 .max_fds = 3,
37 };
38 ESP_ERROR_CHECK(nvs_flash_init());
39 ESP_ERROR_CHECK(esp_event_loop_create_default());
40 ESP_ERROR_CHECK(esp_netif_init());
41 ESP_ERROR_CHECK(esp_vfs_eventfd_register(&eventfd_config));
42
43 xTaskCreate(
44 [](void *arg) {
45 static_cast<OpenThreadComponent *>(arg)->ot_main();
46 vTaskDelete(nullptr);
47 },
48 "ot_main", 10240, this, 5, nullptr);
49}
50
51static esp_netif_t *init_openthread_netif(const esp_openthread_platform_config_t *config) {
52 esp_netif_config_t cfg = ESP_NETIF_DEFAULT_OPENTHREAD();
53 esp_netif_t *netif = esp_netif_new(&cfg);
54 assert(netif != nullptr);
55 ESP_ERROR_CHECK(esp_netif_attach(netif, esp_openthread_netif_glue_init(config)));
56
57 return netif;
58}
59
61 esp_openthread_platform_config_t config = {
62 .radio_config =
63 {
64 .radio_mode = RADIO_MODE_NATIVE,
65 .radio_uart_config = {},
66 },
67 .host_config =
68 {
69 // There is a conflict between esphome's logger which also
70 // claims the usb serial jtag device.
71 // .host_connection_mode = HOST_CONNECTION_MODE_CLI_USB,
72 // .host_usb_config = USB_SERIAL_JTAG_DRIVER_CONFIG_DEFAULT(),
73 },
74 .port_config =
75 {
76 .storage_partition_name = "nvs",
77 .netif_queue_size = 10,
78 .task_queue_size = 10,
79 },
80 };
81
82 // Initialize the OpenThread stack
83 // otLoggingSetLevel(OT_LOG_LEVEL_DEBG);
84 ESP_ERROR_CHECK(esp_openthread_init(&config));
85 // Mark lock as initialized so InstanceLock callers know it's safe to acquire.
86 // Must be set after esp_openthread_init() which creates the internal semaphore.
87 this->lock_initialized_ = true;
88 // Fetch OT instance once to avoid repeated call into OT stack
89 otInstance *instance = esp_openthread_get_instance();
90
91#if CONFIG_OPENTHREAD_STATE_INDICATOR_ENABLE
92 ESP_ERROR_CHECK(esp_openthread_state_indicator_init(instance));
93#endif
94
95#if CONFIG_OPENTHREAD_LOG_LEVEL_DYNAMIC
96 // The OpenThread log level directly matches ESP log level
97 (void) otLoggingSetLevel(CONFIG_LOG_DEFAULT_LEVEL);
98#endif
99 // Initialize the OpenThread cli
100#if CONFIG_OPENTHREAD_CLI
101 esp_openthread_cli_init();
102#endif
103
104 esp_netif_t *openthread_netif;
105 // Initialize the esp_netif bindings
106 openthread_netif = init_openthread_netif(&config);
107 esp_netif_set_default_netif(openthread_netif);
108
109#if CONFIG_OPENTHREAD_CLI_ESP_EXTENSION
110 esp_cli_custom_command_init();
111#endif // CONFIG_OPENTHREAD_CLI_ESP_EXTENSION
112
113 ESP_LOGD(TAG, "Thread Version: %" PRIu16, otThreadGetVersion());
114
115 otLinkModeConfig link_mode_config{};
116#if CONFIG_OPENTHREAD_FTD
117 link_mode_config.mRxOnWhenIdle = true;
118 link_mode_config.mDeviceType = true;
119 link_mode_config.mNetworkData = true;
120#elif CONFIG_OPENTHREAD_MTD
121 if (this->poll_period_ > 0) {
122 if (otLinkSetPollPeriod(instance, this->poll_period_) != OT_ERROR_NONE) {
123 ESP_LOGE(TAG, "Failed to set pollperiod");
124 }
125 ESP_LOGD(TAG, "Link Polling Period: %" PRIu32, otLinkGetPollPeriod(instance));
126 }
127 link_mode_config.mRxOnWhenIdle = this->poll_period_ == 0;
128 link_mode_config.mDeviceType = false;
129 link_mode_config.mNetworkData = false;
130#endif
131
132 if (otThreadSetLinkMode(instance, link_mode_config) != OT_ERROR_NONE) {
133 ESP_LOGE(TAG, "Failed to set linkmode");
134 }
135#ifdef ESPHOME_LOG_HAS_DEBUG // Fetch link mode from OT only when DEBUG
136 link_mode_config = otThreadGetLinkMode(instance);
137 ESP_LOGD(TAG, "Link Mode Device Type: %s, Network Data: %s, RX On When Idle: %s",
138 TRUEFALSE(link_mode_config.mDeviceType), TRUEFALSE(link_mode_config.mNetworkData),
139 TRUEFALSE(link_mode_config.mRxOnWhenIdle));
140#endif
141
142 if (this->output_power_.has_value()) {
143 if (const auto err = otPlatRadioSetTransmitPower(instance, *this->output_power_); err != OT_ERROR_NONE) {
144 ESP_LOGE(TAG, "Failed to set power: %s", otThreadErrorToString(err));
145 }
146 }
147
148 // Run the main loop
149#if CONFIG_OPENTHREAD_CLI
150 esp_openthread_cli_create_task();
151#endif
152 ESP_LOGI(TAG, "Activating dataset...");
153 otOperationalDatasetTlvs dataset = {};
154
155#ifndef USE_OPENTHREAD_FORCE_DATASET
156 // Check if openthread has a valid dataset from a previous execution
157 otError error = otDatasetGetActiveTlvs(instance, &dataset);
158 if (error != OT_ERROR_NONE) {
159 // Make sure the length is 0 so we fallback to the configuration
160 dataset.mLength = 0;
161 } else {
162 ESP_LOGI(TAG, "Found existing dataset, ignoring config (force_dataset: true to override)");
163 }
164#endif
165
166#ifdef USE_OPENTHREAD_TLVS
167 if (dataset.mLength == 0) {
168 // If we didn't have an active dataset, and we have tlvs, parse it and pass it to esp_openthread_auto_start
169 size_t len = (sizeof(USE_OPENTHREAD_TLVS) - 1) / 2;
170 if (len > sizeof(dataset.mTlvs)) {
171 ESP_LOGW(TAG, "TLV buffer too small, truncating");
172 len = sizeof(dataset.mTlvs);
173 }
174 parse_hex(USE_OPENTHREAD_TLVS, sizeof(USE_OPENTHREAD_TLVS) - 1, dataset.mTlvs, len);
175 dataset.mLength = len;
176 }
177#endif
178
179 // Pass the existing dataset, or NULL which will use the preprocessor definitions
180 ESP_ERROR_CHECK(esp_openthread_auto_start(dataset.mLength > 0 ? &dataset : nullptr));
181
182 // Register state change callback to update connected_ reactively instead of polling
183 otSetStateChangedCallback(instance, OpenThreadComponent::on_state_changed_, this);
184
185 esp_openthread_launch_mainloop();
186
187 // Clean up - reset lock flag before deinit destroys the semaphore
188 this->lock_initialized_ = false;
189 esp_openthread_deinit();
190 esp_openthread_netif_glue_deinit();
191 esp_netif_destroy(openthread_netif);
192
193 esp_vfs_eventfd_unregister();
194 this->teardown_complete_ = true;
195 vTaskDelete(NULL);
196}
197
198int OpenThreadComponent::openthread_stop_() { return esp_openthread_mainloop_exit(); }
199
201 network::IPAddresses addresses;
202 struct esp_ip6_addr if_ip6s[CONFIG_LWIP_IPV6_NUM_ADDRESSES];
203 uint8_t count = 0;
204 esp_netif_t *netif = esp_netif_get_default_netif();
205 count = esp_netif_get_all_ip6(netif, if_ip6s);
206 assert(count <= CONFIG_LWIP_IPV6_NUM_ADDRESSES);
207 assert(count < addresses.size());
208 for (int i = 0; i < count; i++) {
209 addresses[i + 1] = network::IPAddress(&if_ip6s[i]);
210 }
211 return addresses;
212}
213
214// not thread safe, only use in read-only use cases
215otInstance *OpenThreadComponent::get_openthread_instance_() { return esp_openthread_get_instance(); }
216
217std::optional<InstanceLock> InstanceLock::try_acquire(int delay) {
219 return {};
220 }
221 if (esp_openthread_lock_acquire(delay)) {
222 return InstanceLock();
223 }
224 return {};
225}
226
228 // Wait for the lock to be created by ot_main() before attempting to acquire it.
229 // esp_openthread_lock_acquire() will assert-crash if called before esp_openthread_init().
230 constexpr uint32_t lock_init_timeout_ms = 10000;
231 uint32_t start = millis();
233 if (millis() - start > lock_init_timeout_ms) {
234 ESP_LOGE(TAG, "OpenThread lock not initialized after %" PRIu32 "ms, aborting", lock_init_timeout_ms);
235 abort();
236 }
237 delay(10);
238 esp_task_wdt_reset();
239 }
240 while (!esp_openthread_lock_acquire(100)) {
241 esp_task_wdt_reset();
242 }
243 return InstanceLock();
244}
245
246otInstance *InstanceLock::get_instance() { return esp_openthread_get_instance(); }
247
248InstanceLock::~InstanceLock() { esp_openthread_lock_release(); }
249
250} // namespace esphome::openthread
251#endif
static std::optional< InstanceLock > try_acquire(int delay)
std::optional< int8_t > output_power_
Definition openthread.h:56
static void on_state_changed_(otChangedFlags flags, void *context)
bool is_lock_initialized() const
Returns true once esp_openthread_init() has completed and the OT lock is usable.
Definition openthread.h:33
std::array< IPAddress, 5 > IPAddresses
Definition ip_address.h:187
OpenThreadComponent * global_openthread_component
std::string size_t len
Definition helpers.h:892
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.
Definition helpers.cpp:294
void HOT delay(uint32_t ms)
Definition core.cpp:28
uint32_t IRAM_ATTR HOT millis()
Definition core.cpp:26
static void uint32_t