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