ESPHome 2026.1.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}
47
49 auto lock = InstanceLock::try_acquire(100);
50 if (!lock) {
51 ESP_LOGW(TAG, "Failed to acquire OpenThread lock in is_connected");
52 return false;
53 }
54
55 otInstance *instance = lock->get_instance();
56 if (instance == nullptr) {
57 return false;
58 }
59
60 otDeviceRole role = otThreadGetDeviceRole(instance);
61
62 // TODO: If we're a leader, check that there is at least 1 known peer
63 return role >= OT_DEVICE_ROLE_CHILD;
64}
65
66// Gets the off-mesh routable address
67std::optional<otIp6Address> OpenThreadComponent::get_omr_address() {
69 return this->get_omr_address_(lock);
70}
71
72std::optional<otIp6Address> OpenThreadComponent::get_omr_address_(InstanceLock &lock) {
73 otNetworkDataIterator iterator = OT_NETWORK_DATA_ITERATOR_INIT;
74 otInstance *instance = nullptr;
75
76 instance = lock.get_instance();
77
78 otBorderRouterConfig config;
79 if (otNetDataGetNextOnMeshPrefix(instance, &iterator, &config) != OT_ERROR_NONE) {
80 return std::nullopt;
81 }
82
83 const otIp6Prefix *omr_prefix = &config.mPrefix;
84 const otNetifAddress *unicast_addresses = otIp6GetUnicastAddresses(instance);
85 for (const otNetifAddress *addr = unicast_addresses; addr; addr = addr->mNext) {
86 const otIp6Address *local_ip = &addr->mAddress;
87 if (otIp6PrefixMatch(&omr_prefix->mPrefix, local_ip)) {
88 return *local_ip;
89 }
90 }
91 return {};
92}
93
95 ESP_LOGD(TAG, "Defer factory_reset_external_callback_");
96 this->defer([this]() { this->factory_reset_external_callback_(); });
97}
98
99void OpenThreadSrpComponent::srp_callback(otError err, const otSrpClientHostInfo *host_info,
100 const otSrpClientService *services,
101 const otSrpClientService *removed_services, void *context) {
102 if (err != 0) {
103 ESP_LOGW(TAG, "SRP client reported an error: %s", otThreadErrorToString(err));
104 for (const otSrpClientHostInfo *host = host_info; host; host = nullptr) {
105 ESP_LOGW(TAG, " Host: %s", host->mName);
106 }
107 for (const otSrpClientService *service = services; service; service = service->mNext) {
108 ESP_LOGW(TAG, " Service: %s", service->mName);
109 }
110 }
111}
112
113void OpenThreadSrpComponent::srp_start_callback(const otSockAddr *server_socket_address, void *context) {
114 ESP_LOGI(TAG, "SRP client has started");
115}
116
117void OpenThreadSrpComponent::srp_factory_reset_callback(otError err, const otSrpClientHostInfo *host_info,
118 const otSrpClientService *services,
119 const otSrpClientService *removed_services, void *context) {
120 OpenThreadComponent *obj = (OpenThreadComponent *) context;
121 if (err == OT_ERROR_NONE && removed_services != NULL && host_info != NULL &&
122 host_info->mState == OT_SRP_CLIENT_ITEM_STATE_REMOVED) {
123 ESP_LOGD(TAG, "Successful Removal SRP Host and Services");
124 } else if (err != OT_ERROR_NONE) {
125 // Handle other SRP client events or errors
126 ESP_LOGW(TAG, "SRP client event/error: %s", otThreadErrorToString(err));
127 }
129}
130
132 otError error;
134 otInstance *instance = lock.get_instance();
135
136 otSrpClientSetCallback(instance, OpenThreadSrpComponent::srp_callback, nullptr);
137
138 // set the host name
139 uint16_t size;
140 char *existing_host_name = otSrpClientBuffersGetHostNameString(instance, &size);
141 const std::string &host_name = App.get_name();
142 uint16_t host_name_len = host_name.size();
143 if (host_name_len > size) {
144 ESP_LOGW(TAG, "Hostname is too long, choose a shorter project name");
145 return;
146 }
147 memset(existing_host_name, 0, size);
148 memcpy(existing_host_name, host_name.c_str(), host_name_len);
149
150 error = otSrpClientSetHostName(instance, existing_host_name);
151 if (error != 0) {
152 ESP_LOGW(TAG, "Could not set host name");
153 return;
154 }
155
156 error = otSrpClientEnableAutoHostAddress(instance);
157 if (error != 0) {
158 ESP_LOGW(TAG, "Could not enable auto host address");
159 return;
160 }
161
162 // Get mdns services and copy their data (strings are copied with strdup below)
163 const auto &mdns_services = this->mdns_->get_services();
164 ESP_LOGD(TAG, "Setting up SRP services. count = %d\n", mdns_services.size());
165 for (const auto &service : mdns_services) {
166 otSrpClientBuffersServiceEntry *entry = otSrpClientBuffersAllocateService(instance);
167 if (!entry) {
168 ESP_LOGW(TAG, "Failed to allocate service entry");
169 continue;
170 }
171
172 // Set service name
173 char *string = otSrpClientBuffersGetServiceEntryServiceNameString(entry, &size);
174 std::string full_service = std::string(MDNS_STR_ARG(service.service_type)) + "." + MDNS_STR_ARG(service.proto);
175 if (full_service.size() > size) {
176 ESP_LOGW(TAG, "Service name too long: %s", full_service.c_str());
177 continue;
178 }
179 memcpy(string, full_service.c_str(), full_service.size() + 1);
180
181 // Set instance name (using host_name)
182 string = otSrpClientBuffersGetServiceEntryInstanceNameString(entry, &size);
183 if (host_name_len > size) {
184 ESP_LOGW(TAG, "Instance name too long: %s", host_name.c_str());
185 continue;
186 }
187 memset(string, 0, size);
188 memcpy(string, host_name.c_str(), host_name_len);
189
190 // Set port
191 entry->mService.mPort = const_cast<TemplatableValue<uint16_t> &>(service.port).value();
192
193 otDnsTxtEntry *txt_entries =
194 reinterpret_cast<otDnsTxtEntry *>(this->pool_alloc_(sizeof(otDnsTxtEntry) * service.txt_records.size()));
195 // Set TXT records
196 entry->mService.mNumTxtEntries = service.txt_records.size();
197 for (size_t i = 0; i < service.txt_records.size(); i++) {
198 const auto &txt = service.txt_records[i];
199 // Value is either a compile-time string literal in flash or a pointer to dynamic_txt_values_
200 // OpenThread SRP client expects the data to persist, so we strdup it
201 const char *value_str = MDNS_STR_ARG(txt.value);
202 txt_entries[i].mKey = MDNS_STR_ARG(txt.key);
203 txt_entries[i].mValue = reinterpret_cast<const uint8_t *>(strdup(value_str));
204 txt_entries[i].mValueLength = strlen(value_str);
205 }
206 entry->mService.mTxtEntries = txt_entries;
207 entry->mService.mNumTxtEntries = service.txt_records.size();
208
209 // Add service
210 error = otSrpClientAddService(instance, &entry->mService);
211 if (error != OT_ERROR_NONE) {
212 ESP_LOGW(TAG, "Failed to add service: %s", otThreadErrorToString(error));
213 }
214 ESP_LOGD(TAG, "Added service: %s", full_service.c_str());
215 }
216
217 otSrpClientEnableAutoStartMode(instance, OpenThreadSrpComponent::srp_start_callback, nullptr);
218 ESP_LOGD(TAG, "Finished SRP setup");
219}
220
222 uint8_t *ptr = new uint8_t[size];
223 this->memory_pool_.emplace_back(std::unique_ptr<uint8_t[]>(ptr));
224 return ptr;
225}
226
228
230 if (!this->teardown_started_) {
231 this->teardown_started_ = true;
232 ESP_LOGD(TAG, "Clear Srp");
233 auto lock = InstanceLock::try_acquire(100);
234 if (!lock) {
235 ESP_LOGW(TAG, "Failed to acquire OpenThread lock during teardown, leaking memory");
236 return true;
237 }
238 otInstance *instance = lock->get_instance();
239 otSrpClientClearHostAndServices(instance);
240 otSrpClientBuffersFreeAllServices(instance);
242#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 5, 0)
243 ESP_LOGD(TAG, "Exit main loop ");
244 int error = esp_openthread_mainloop_exit();
245 if (error != ESP_OK) {
246 ESP_LOGW(TAG, "Failed attempt to stop main loop %d", error);
247 this->teardown_complete_ = true;
248 }
249#else
250 this->teardown_complete_ = true;
251#endif
252 }
253 return this->teardown_complete_;
254}
255
256void OpenThreadComponent::on_factory_reset(std::function<void()> callback) {
258 ESP_LOGD(TAG, "Start Removal SRP Host and Services");
259 otError error;
261 otInstance *instance = lock.get_instance();
262 otSrpClientSetCallback(instance, OpenThreadSrpComponent::srp_factory_reset_callback, this);
263 error = otSrpClientRemoveHostAndServices(instance, true, true);
264 if (error != OT_ERROR_NONE) {
265 ESP_LOGW(TAG, "Failed to Remove SRP Host and Services");
266 return;
267 }
268 ESP_LOGD(TAG, "Waiting on Confirmation Removal SRP Host and Services");
269}
270
271// set_use_address() is guaranteed to be called during component setup by Python code generation,
272// so use_address_ will always be valid when get_use_address() is called - no fallback needed.
273const char *OpenThreadComponent::get_use_address() const { return this->use_address_; }
274
275void OpenThreadComponent::set_use_address(const char *use_address) { this->use_address_ = use_address; }
276
277} // namespace esphome::openthread
278#endif
const std::string & get_name() const
Get the name of this Application set by pre_setup().
void defer(const std::string &name, std::function< void()> &&f)
Defer a callback to the next loop() call.
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::function< void()> factory_reset_external_callback_
Definition openthread.h:46
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:74
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:73
uint8_t duration
Definition msa3xx.h:0
OpenThreadComponent * global_openthread_component
Application App
Global storage of Application pointer - only one Application can exist.