ESPHome 2026.3.0-dev
Loading...
Searching...
No Matches
openthread.cpp
Go to the documentation of this file.
2#ifdef USE_OPENTHREAD
3#include "openthread.h"
4#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 5, 0)
5#include "esp_openthread.h"
6#endif
7
8#include <freertos/portmacro.h>
9
10#include <openthread/cli.h>
11#include <openthread/instance.h>
12#include <openthread/logging.h>
13#include <openthread/netdata.h>
14#include <openthread/tasklet.h>
15
16#include <cstring>
17
20#include "esphome/core/log.h"
21
22static const char *const TAG = "openthread";
23
25
26OpenThreadComponent *global_openthread_component = // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
27 nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
28
30
32 ESP_LOGCONFIG(TAG, "Open Thread:");
33#if CONFIG_OPENTHREAD_FTD
34 ESP_LOGCONFIG(TAG, " Device Type: FTD");
35#elif CONFIG_OPENTHREAD_MTD
36 ESP_LOGCONFIG(TAG, " Device Type: MTD");
37 // TBD: Synchronized Sleepy End Device
38 if (this->poll_period_ > 0) {
39 ESP_LOGCONFIG(TAG, " Device is configured as Sleepy End Device (SED)");
40 uint32_t duration = this->poll_period_ / 1000;
41 ESP_LOGCONFIG(TAG, " Poll Period: %" PRIu32 "s", duration);
42 } else {
43 ESP_LOGCONFIG(TAG, " Device is configured as Minimal End Device (MED)");
44 }
45#endif
46 if (this->output_power_.has_value()) {
47 ESP_LOGCONFIG(TAG, " Output power: %" PRId8 "dBm", *this->output_power_);
48 }
49}
50
52 auto lock = InstanceLock::try_acquire(100);
53 if (!lock) {
54 ESP_LOGW(TAG, "Failed to acquire OpenThread lock in is_connected");
55 return false;
56 }
57
58 otInstance *instance = lock->get_instance();
59 if (instance == nullptr) {
60 return false;
61 }
62
63 otDeviceRole role = otThreadGetDeviceRole(instance);
64
65 // TODO: If we're a leader, check that there is at least 1 known peer
66 return role >= OT_DEVICE_ROLE_CHILD;
67}
68
69// Gets the off-mesh routable address
70std::optional<otIp6Address> OpenThreadComponent::get_omr_address() {
72 return this->get_omr_address_(lock);
73}
74
75std::optional<otIp6Address> OpenThreadComponent::get_omr_address_(InstanceLock &lock) {
76 otNetworkDataIterator iterator = OT_NETWORK_DATA_ITERATOR_INIT;
77 otInstance *instance = nullptr;
78
79 instance = lock.get_instance();
80
81 otBorderRouterConfig config;
82 if (otNetDataGetNextOnMeshPrefix(instance, &iterator, &config) != OT_ERROR_NONE) {
83 return std::nullopt;
84 }
85
86 const otIp6Prefix *omr_prefix = &config.mPrefix;
87 const otNetifAddress *unicast_addresses = otIp6GetUnicastAddresses(instance);
88 for (const otNetifAddress *addr = unicast_addresses; addr; addr = addr->mNext) {
89 const otIp6Address *local_ip = &addr->mAddress;
90 if (otIp6PrefixMatch(&omr_prefix->mPrefix, local_ip)) {
91 return *local_ip;
92 }
93 }
94 return {};
95}
96
98 ESP_LOGD(TAG, "Defer factory_reset_external_callback_");
99 this->defer([this]() { this->factory_reset_external_callback_(); });
100}
101
102void OpenThreadSrpComponent::srp_callback(otError err, const otSrpClientHostInfo *host_info,
103 const otSrpClientService *services,
104 const otSrpClientService *removed_services, void *context) {
105 if (err != 0) {
106 ESP_LOGW(TAG, "SRP client reported an error: %s", otThreadErrorToString(err));
107 for (const otSrpClientHostInfo *host = host_info; host; host = nullptr) {
108 ESP_LOGW(TAG, " Host: %s", host->mName);
109 }
110 for (const otSrpClientService *service = services; service; service = service->mNext) {
111 ESP_LOGW(TAG, " Service: %s", service->mName);
112 }
113 }
114}
115
116void OpenThreadSrpComponent::srp_start_callback(const otSockAddr *server_socket_address, void *context) {
117 ESP_LOGI(TAG, "SRP client has started");
118}
119
120void OpenThreadSrpComponent::srp_factory_reset_callback(otError err, const otSrpClientHostInfo *host_info,
121 const otSrpClientService *services,
122 const otSrpClientService *removed_services, void *context) {
123 OpenThreadComponent *obj = (OpenThreadComponent *) context;
124 if (err == OT_ERROR_NONE && removed_services != NULL && host_info != NULL &&
125 host_info->mState == OT_SRP_CLIENT_ITEM_STATE_REMOVED) {
126 ESP_LOGD(TAG, "Successful Removal SRP Host and Services");
127 } else if (err != OT_ERROR_NONE) {
128 // Handle other SRP client events or errors
129 ESP_LOGW(TAG, "SRP client event/error: %s", otThreadErrorToString(err));
130 }
132}
133
135 otError error;
137 otInstance *instance = lock.get_instance();
138
139 otSrpClientSetCallback(instance, OpenThreadSrpComponent::srp_callback, nullptr);
140
141 // set the host name
142 uint16_t size;
143 char *existing_host_name = otSrpClientBuffersGetHostNameString(instance, &size);
144 const std::string &host_name = App.get_name();
145 uint16_t host_name_len = host_name.size();
146 if (host_name_len > size) {
147 ESP_LOGW(TAG, "Hostname is too long, choose a shorter project name");
148 return;
149 }
150 memset(existing_host_name, 0, size);
151 memcpy(existing_host_name, host_name.c_str(), host_name_len);
152
153 error = otSrpClientSetHostName(instance, existing_host_name);
154 if (error != 0) {
155 ESP_LOGW(TAG, "Could not set host name");
156 return;
157 }
158
159 error = otSrpClientEnableAutoHostAddress(instance);
160 if (error != 0) {
161 ESP_LOGW(TAG, "Could not enable auto host address");
162 return;
163 }
164
165 // Get mdns services and copy their data (strings are copied with strdup below)
166 const auto &mdns_services = this->mdns_->get_services();
167 ESP_LOGD(TAG, "Setting up SRP services. count = %d\n", mdns_services.size());
168 for (const auto &service : mdns_services) {
169 otSrpClientBuffersServiceEntry *entry = otSrpClientBuffersAllocateService(instance);
170 if (!entry) {
171 ESP_LOGW(TAG, "Failed to allocate service entry");
172 continue;
173 }
174
175 // Set service name
176 char *string = otSrpClientBuffersGetServiceEntryServiceNameString(entry, &size);
177 std::string full_service = std::string(MDNS_STR_ARG(service.service_type)) + "." + MDNS_STR_ARG(service.proto);
178 if (full_service.size() > size) {
179 ESP_LOGW(TAG, "Service name too long: %s", full_service.c_str());
180 continue;
181 }
182 memcpy(string, full_service.c_str(), full_service.size() + 1);
183
184 // Set instance name (using host_name)
185 string = otSrpClientBuffersGetServiceEntryInstanceNameString(entry, &size);
186 if (host_name_len > size) {
187 ESP_LOGW(TAG, "Instance name too long: %s", host_name.c_str());
188 continue;
189 }
190 memset(string, 0, size);
191 memcpy(string, host_name.c_str(), host_name_len);
192
193 // Set port
194 entry->mService.mPort = const_cast<TemplatableValue<uint16_t> &>(service.port).value();
195
196 otDnsTxtEntry *txt_entries =
197 reinterpret_cast<otDnsTxtEntry *>(this->pool_alloc_(sizeof(otDnsTxtEntry) * service.txt_records.size()));
198 // Set TXT records
199 entry->mService.mNumTxtEntries = service.txt_records.size();
200 for (size_t i = 0; i < service.txt_records.size(); i++) {
201 const auto &txt = service.txt_records[i];
202 // Value is either a compile-time string literal in flash or a pointer to dynamic_txt_values_
203 // OpenThread SRP client expects the data to persist, so we strdup it
204 const char *value_str = MDNS_STR_ARG(txt.value);
205 txt_entries[i].mKey = MDNS_STR_ARG(txt.key);
206 txt_entries[i].mValue = reinterpret_cast<const uint8_t *>(strdup(value_str));
207 txt_entries[i].mValueLength = strlen(value_str);
208 }
209 entry->mService.mTxtEntries = txt_entries;
210 entry->mService.mNumTxtEntries = service.txt_records.size();
211
212 // Add service
213 error = otSrpClientAddService(instance, &entry->mService);
214 if (error != OT_ERROR_NONE) {
215 ESP_LOGW(TAG, "Failed to add service: %s", otThreadErrorToString(error));
216 }
217 ESP_LOGD(TAG, "Added service: %s", full_service.c_str());
218 }
219
220 otSrpClientEnableAutoStartMode(instance, OpenThreadSrpComponent::srp_start_callback, nullptr);
221 ESP_LOGD(TAG, "Finished SRP setup");
222}
223
225 uint8_t *ptr = new uint8_t[size];
226 this->memory_pool_.emplace_back(std::unique_ptr<uint8_t[]>(ptr));
227 return ptr;
228}
229
231
233 if (!this->teardown_started_) {
234 this->teardown_started_ = true;
235 ESP_LOGD(TAG, "Clear Srp");
236 auto lock = InstanceLock::try_acquire(100);
237 if (!lock) {
238 ESP_LOGW(TAG, "Failed to acquire OpenThread lock during teardown, leaking memory");
239 return true;
240 }
241 otInstance *instance = lock->get_instance();
242 otSrpClientClearHostAndServices(instance);
243 otSrpClientBuffersFreeAllServices(instance);
245#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 5, 0)
246 ESP_LOGD(TAG, "Exit main loop ");
247 int error = esp_openthread_mainloop_exit();
248 if (error != ESP_OK) {
249 ESP_LOGW(TAG, "Failed attempt to stop main loop %d", error);
250 this->teardown_complete_ = true;
251 }
252#else
253 this->teardown_complete_ = true;
254#endif
255 }
256 return this->teardown_complete_;
257}
258
259void OpenThreadComponent::on_factory_reset(std::function<void()> callback) {
261 ESP_LOGD(TAG, "Start Removal SRP Host and Services");
262 otError error;
264 otInstance *instance = lock.get_instance();
265 otSrpClientSetCallback(instance, OpenThreadSrpComponent::srp_factory_reset_callback, this);
266 error = otSrpClientRemoveHostAndServices(instance, true, true);
267 if (error != OT_ERROR_NONE) {
268 ESP_LOGW(TAG, "Failed to Remove SRP Host and Services");
269 return;
270 }
271 ESP_LOGD(TAG, "Waiting on Confirmation Removal SRP Host and Services");
272}
273
274// set_use_address() is guaranteed to be called during component setup by Python code generation,
275// so use_address_ will always be valid when get_use_address() is called - no fallback needed.
276const char *OpenThreadComponent::get_use_address() const { return this->use_address_; }
277
278void OpenThreadComponent::set_use_address(const char *use_address) { this->use_address_ = use_address; }
279
280} // namespace esphome::openthread
281#endif
const std::string & get_name() const
Get the name of this Application set by pre_setup().
ESPDEPRECATED("Use const char* overload instead. Removed in 2026.7.0", "2026.1.0") void defer(const std voi defer)(const char *name, std::function< void()> &&f)
Defer a callback to the next loop() call.
Definition component.h:493
const StaticVector< MDNSService, MDNS_SERVICE_COUNT > & get_services() const
static std::optional< InstanceLock > try_acquire(int delay)
void set_use_address(const char *use_address)
std::optional< otIp6Address > get_omr_address_(InstanceLock &lock)
std::optional< int8_t > output_power_
Definition openthread.h:49
std::function< void()> factory_reset_external_callback_
Definition openthread.h:45
std::optional< otIp6Address > get_omr_address()
void on_factory_reset(std::function< void()> callback)
std::vector< std::unique_ptr< uint8_t[]> > memory_pool_
Definition openthread.h:76
static void srp_start_callback(const otSockAddr *server_socket_address, void *context)
void set_mdns(esphome::mdns::MDNSComponent *mdns)
static void srp_factory_reset_callback(otError err, const otSrpClientHostInfo *host_info, const otSrpClientService *services, const otSrpClientService *removed_services, void *context)
static void srp_callback(otError err, const otSrpClientHostInfo *host_info, const otSrpClientService *services, const otSrpClientService *removed_services, void *context)
esphome::mdns::MDNSComponent * mdns_
Definition openthread.h:75
uint8_t duration
Definition msa3xx.h:0
OpenThreadComponent * global_openthread_component
size_t size
Definition helpers.h:854
Application App
Global storage of Application pointer - only one Application can exist.