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