ESPHome 2026.3.0-dev
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"
12#include "esphome/core/log.h"
13
14#include "esp_err.h"
15#include "esp_event.h"
16#include "esp_netif.h"
17#include "esp_netif_types.h"
18#include "esp_openthread_cli.h"
19#include "esp_openthread_netif_glue.h"
20#include "esp_vfs_eventfd.h"
21#include "freertos/FreeRTOS.h"
22#include "freertos/task.h"
23#include "nvs_flash.h"
24
25static const char *const TAG = "openthread";
26
27namespace esphome::openthread {
28
30 // Used eventfds:
31 // * netif
32 // * ot task queue
33 // * radio driver
34 esp_vfs_eventfd_config_t eventfd_config = {
35 .max_fds = 3,
36 };
37 ESP_ERROR_CHECK(nvs_flash_init());
38 ESP_ERROR_CHECK(esp_event_loop_create_default());
39 ESP_ERROR_CHECK(esp_netif_init());
40 ESP_ERROR_CHECK(esp_vfs_eventfd_register(&eventfd_config));
41
42 xTaskCreate(
43 [](void *arg) {
44 static_cast<OpenThreadComponent *>(arg)->ot_main();
45 vTaskDelete(nullptr);
46 },
47 "ot_main", 10240, this, 5, nullptr);
48}
49
50static esp_netif_t *init_openthread_netif(const esp_openthread_platform_config_t *config) {
51 esp_netif_config_t cfg = ESP_NETIF_DEFAULT_OPENTHREAD();
52 esp_netif_t *netif = esp_netif_new(&cfg);
53 assert(netif != nullptr);
54 ESP_ERROR_CHECK(esp_netif_attach(netif, esp_openthread_netif_glue_init(config)));
55
56 return netif;
57}
58
60 esp_openthread_platform_config_t config = {
61 .radio_config =
62 {
63 .radio_mode = RADIO_MODE_NATIVE,
64 .radio_uart_config = {},
65 },
66 .host_config =
67 {
68 // There is a conflict between esphome's logger which also
69 // claims the usb serial jtag device.
70 // .host_connection_mode = HOST_CONNECTION_MODE_CLI_USB,
71 // .host_usb_config = USB_SERIAL_JTAG_DRIVER_CONFIG_DEFAULT(),
72 },
73 .port_config =
74 {
75 .storage_partition_name = "nvs",
76 .netif_queue_size = 10,
77 .task_queue_size = 10,
78 },
79 };
80
81 // Initialize the OpenThread stack
82 // otLoggingSetLevel(OT_LOG_LEVEL_DEBG);
83 ESP_ERROR_CHECK(esp_openthread_init(&config));
84 // Fetch OT instance once to avoid repeated call into OT stack
85 otInstance *instance = esp_openthread_get_instance();
86
87#if CONFIG_OPENTHREAD_STATE_INDICATOR_ENABLE
88 ESP_ERROR_CHECK(esp_openthread_state_indicator_init(instance));
89#endif
90
91#if CONFIG_OPENTHREAD_LOG_LEVEL_DYNAMIC
92 // The OpenThread log level directly matches ESP log level
93 (void) otLoggingSetLevel(CONFIG_LOG_DEFAULT_LEVEL);
94#endif
95 // Initialize the OpenThread cli
96#if CONFIG_OPENTHREAD_CLI
97 esp_openthread_cli_init();
98#endif
99
100 esp_netif_t *openthread_netif;
101 // Initialize the esp_netif bindings
102 openthread_netif = init_openthread_netif(&config);
103 esp_netif_set_default_netif(openthread_netif);
104
105#if CONFIG_OPENTHREAD_CLI_ESP_EXTENSION
106 esp_cli_custom_command_init();
107#endif // CONFIG_OPENTHREAD_CLI_ESP_EXTENSION
108
109 ESP_LOGD(TAG, "Thread Version: %" PRIu16, otThreadGetVersion());
110
111 otLinkModeConfig link_mode_config{};
112#if CONFIG_OPENTHREAD_FTD
113 link_mode_config.mRxOnWhenIdle = true;
114 link_mode_config.mDeviceType = true;
115 link_mode_config.mNetworkData = true;
116#elif CONFIG_OPENTHREAD_MTD
117 if (this->poll_period_ > 0) {
118 if (otLinkSetPollPeriod(instance, this->poll_period_) != OT_ERROR_NONE) {
119 ESP_LOGE(TAG, "Failed to set pollperiod");
120 }
121 ESP_LOGD(TAG, "Link Polling Period: %" PRIu32, otLinkGetPollPeriod(instance));
122 }
123 link_mode_config.mRxOnWhenIdle = this->poll_period_ == 0;
124 link_mode_config.mDeviceType = false;
125 link_mode_config.mNetworkData = false;
126#endif
127
128 if (otThreadSetLinkMode(instance, link_mode_config) != OT_ERROR_NONE) {
129 ESP_LOGE(TAG, "Failed to set linkmode");
130 }
131#ifdef ESPHOME_LOG_HAS_DEBUG // Fetch link mode from OT only when DEBUG
132 link_mode_config = otThreadGetLinkMode(instance);
133 ESP_LOGD(TAG, "Link Mode Device Type: %s, Network Data: %s, RX On When Idle: %s",
134 TRUEFALSE(link_mode_config.mDeviceType), TRUEFALSE(link_mode_config.mNetworkData),
135 TRUEFALSE(link_mode_config.mRxOnWhenIdle));
136#endif
137
138 // Run the main loop
139#if CONFIG_OPENTHREAD_CLI
140 esp_openthread_cli_create_task();
141#endif
142 ESP_LOGI(TAG, "Activating dataset...");
143 otOperationalDatasetTlvs dataset = {};
144
145#ifndef USE_OPENTHREAD_FORCE_DATASET
146 // Check if openthread has a valid dataset from a previous execution
147 otError error = otDatasetGetActiveTlvs(instance, &dataset);
148 if (error != OT_ERROR_NONE) {
149 // Make sure the length is 0 so we fallback to the configuration
150 dataset.mLength = 0;
151 } else {
152 ESP_LOGI(TAG, "Found existing dataset, ignoring config (force_dataset: true to override)");
153 }
154#endif
155
156#ifdef USE_OPENTHREAD_TLVS
157 if (dataset.mLength == 0) {
158 // If we didn't have an active dataset, and we have tlvs, parse it and pass it to esp_openthread_auto_start
159 size_t len = (sizeof(USE_OPENTHREAD_TLVS) - 1) / 2;
160 if (len > sizeof(dataset.mTlvs)) {
161 ESP_LOGW(TAG, "TLV buffer too small, truncating");
162 len = sizeof(dataset.mTlvs);
163 }
164 parse_hex(USE_OPENTHREAD_TLVS, sizeof(USE_OPENTHREAD_TLVS) - 1, dataset.mTlvs, len);
165 dataset.mLength = len;
166 }
167#endif
168
169 // Pass the existing dataset, or NULL which will use the preprocessor definitions
170 ESP_ERROR_CHECK(esp_openthread_auto_start(dataset.mLength > 0 ? &dataset : nullptr));
171
172 esp_openthread_launch_mainloop();
173
174 // Clean up
175 esp_openthread_deinit();
176 esp_openthread_netif_glue_deinit();
177 esp_netif_destroy(openthread_netif);
178
179 esp_vfs_eventfd_unregister();
180 this->teardown_complete_ = true;
181 vTaskDelete(NULL);
182}
183
185 network::IPAddresses addresses;
186 struct esp_ip6_addr if_ip6s[CONFIG_LWIP_IPV6_NUM_ADDRESSES];
187 uint8_t count = 0;
188 esp_netif_t *netif = esp_netif_get_default_netif();
189 count = esp_netif_get_all_ip6(netif, if_ip6s);
190 assert(count <= CONFIG_LWIP_IPV6_NUM_ADDRESSES);
191 for (int i = 0; i < count; i++) {
192 addresses[i + 1] = network::IPAddress(&if_ip6s[i]);
193 }
194 return addresses;
195}
196
197std::optional<InstanceLock> InstanceLock::try_acquire(int delay) {
198 if (esp_openthread_lock_acquire(delay)) {
199 return InstanceLock();
200 }
201 return {};
202}
203
205 while (!esp_openthread_lock_acquire(100)) {
206 esp_task_wdt_reset();
207 }
208 return InstanceLock();
209}
210
211otInstance *InstanceLock::get_instance() { return esp_openthread_get_instance(); }
212
213InstanceLock::~InstanceLock() { esp_openthread_lock_release(); }
214
215} // namespace esphome::openthread
216#endif
static std::optional< InstanceLock > try_acquire(int delay)
std::array< IPAddress, 5 > IPAddresses
Definition ip_address.h:187
std::string size_t len
Definition helpers.h:817
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:27