ESPHome 2025.6.3
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Modules Pages
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/srp_client.h>
12#include <openthread/srp_client_buffers.h>
13#include <openthread/tasklet.h>
14
15#include <cstring>
16
19#include "esphome/core/log.h"
20
21static const char *const TAG = "openthread";
22
23namespace esphome {
24namespace openthread {
25
26OpenThreadComponent *global_openthread_component = // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
27 nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
28
30
32 auto lock = InstanceLock::try_acquire(100);
33 if (!lock) {
34 ESP_LOGW(TAG, "Failed to acquire OpenThread lock in destructor, leaking memory");
35 return;
36 }
37 otInstance *instance = lock->get_instance();
38 otSrpClientClearHostAndServices(instance);
39 otSrpClientBuffersFreeAllServices(instance);
41}
42
44 auto lock = InstanceLock::try_acquire(100);
45 if (!lock) {
46 ESP_LOGW(TAG, "Failed to acquire OpenThread lock in is_connected");
47 return false;
48 }
49
50 otInstance *instance = lock->get_instance();
51 if (instance == nullptr) {
52 return false;
53 }
54
55 otDeviceRole role = otThreadGetDeviceRole(instance);
56
57 // TODO: If we're a leader, check that there is at least 1 known peer
58 return role >= OT_DEVICE_ROLE_CHILD;
59}
60
61// Gets the off-mesh routable address
62std::optional<otIp6Address> OpenThreadComponent::get_omr_address() {
64 return this->get_omr_address_(lock);
65}
66
67std::optional<otIp6Address> OpenThreadComponent::get_omr_address_(InstanceLock &lock) {
68 otNetworkDataIterator iterator = OT_NETWORK_DATA_ITERATOR_INIT;
69 otInstance *instance = nullptr;
70
71 instance = lock.get_instance();
72
73 otBorderRouterConfig config;
74 if (otNetDataGetNextOnMeshPrefix(instance, &iterator, &config) != OT_ERROR_NONE) {
75 return std::nullopt;
76 }
77
78 const otIp6Prefix *omr_prefix = &config.mPrefix;
79 const otNetifAddress *unicast_addresses = otIp6GetUnicastAddresses(instance);
80 for (const otNetifAddress *addr = unicast_addresses; addr; addr = addr->mNext) {
81 const otIp6Address *local_ip = &addr->mAddress;
82 if (otIp6PrefixMatch(&omr_prefix->mPrefix, local_ip)) {
83 return *local_ip;
84 }
85 }
86 return {};
87}
88
89void srp_callback(otError err, const otSrpClientHostInfo *host_info, const otSrpClientService *services,
90 const otSrpClientService *removed_services, void *context) {
91 if (err != 0) {
92 ESP_LOGW(TAG, "SRP client reported an error: %s", otThreadErrorToString(err));
93 for (const otSrpClientHostInfo *host = host_info; host; host = nullptr) {
94 ESP_LOGW(TAG, " Host: %s", host->mName);
95 }
96 for (const otSrpClientService *service = services; service; service = service->mNext) {
97 ESP_LOGW(TAG, " Service: %s", service->mName);
98 }
99 }
100}
101
102void srp_start_callback(const otSockAddr *server_socket_address, void *context) {
103 ESP_LOGI(TAG, "SRP client has started");
104}
105
107 otError error;
109 otInstance *instance = lock.get_instance();
110
111 otSrpClientSetCallback(instance, srp_callback, nullptr);
112
113 // set the host name
114 uint16_t size;
115 char *existing_host_name = otSrpClientBuffersGetHostNameString(instance, &size);
116 const std::string &host_name = App.get_name();
117 uint16_t host_name_len = host_name.size();
118 if (host_name_len > size) {
119 ESP_LOGW(TAG, "Hostname is too long, choose a shorter project name");
120 return;
121 }
122 memset(existing_host_name, 0, size);
123 memcpy(existing_host_name, host_name.c_str(), host_name_len);
124
125 error = otSrpClientSetHostName(instance, existing_host_name);
126 if (error != 0) {
127 ESP_LOGW(TAG, "Could not set host name");
128 return;
129 }
130
131 error = otSrpClientEnableAutoHostAddress(instance);
132 if (error != 0) {
133 ESP_LOGW(TAG, "Could not enable auto host address");
134 return;
135 }
136
137 // Copy the mdns services to our local instance so that the c_str pointers remain valid for the lifetime of this
138 // component
139 this->mdns_services_ = this->mdns_->get_services();
140 ESP_LOGD(TAG, "Setting up SRP services. count = %d\n", this->mdns_services_.size());
141 for (const auto &service : this->mdns_services_) {
142 otSrpClientBuffersServiceEntry *entry = otSrpClientBuffersAllocateService(instance);
143 if (!entry) {
144 ESP_LOGW(TAG, "Failed to allocate service entry");
145 continue;
146 }
147
148 // Set service name
149 char *string = otSrpClientBuffersGetServiceEntryServiceNameString(entry, &size);
150 std::string full_service = service.service_type + "." + service.proto;
151 if (full_service.size() > size) {
152 ESP_LOGW(TAG, "Service name too long: %s", full_service.c_str());
153 continue;
154 }
155 memcpy(string, full_service.c_str(), full_service.size() + 1);
156
157 // Set instance name (using host_name)
158 string = otSrpClientBuffersGetServiceEntryInstanceNameString(entry, &size);
159 if (host_name_len > size) {
160 ESP_LOGW(TAG, "Instance name too long: %s", host_name.c_str());
161 continue;
162 }
163 memset(string, 0, size);
164 memcpy(string, host_name.c_str(), host_name_len);
165
166 // Set port
167 entry->mService.mPort = const_cast<TemplatableValue<uint16_t> &>(service.port).value();
168
169 otDnsTxtEntry *txt_entries =
170 reinterpret_cast<otDnsTxtEntry *>(this->pool_alloc_(sizeof(otDnsTxtEntry) * service.txt_records.size()));
171 // Set TXT records
172 entry->mService.mNumTxtEntries = service.txt_records.size();
173 for (size_t i = 0; i < service.txt_records.size(); i++) {
174 const auto &txt = service.txt_records[i];
175 auto value = const_cast<TemplatableValue<std::string> &>(txt.value).value();
176 txt_entries[i].mKey = strdup(txt.key.c_str());
177 txt_entries[i].mValue = reinterpret_cast<const uint8_t *>(strdup(value.c_str()));
178 txt_entries[i].mValueLength = value.size();
179 }
180 entry->mService.mTxtEntries = txt_entries;
181 entry->mService.mNumTxtEntries = service.txt_records.size();
182
183 // Add service
184 error = otSrpClientAddService(instance, &entry->mService);
185 if (error != OT_ERROR_NONE) {
186 ESP_LOGW(TAG, "Failed to add service: %s", otThreadErrorToString(error));
187 }
188 ESP_LOGD(TAG, "Added service: %s", full_service.c_str());
189 }
190
191 otSrpClientEnableAutoStartMode(instance, srp_start_callback, nullptr);
192 ESP_LOGD(TAG, "Finished SRP setup");
193}
194
196 uint8_t *ptr = new uint8_t[size];
197 this->memory_pool_.emplace_back(std::unique_ptr<uint8_t[]>(ptr));
198 return ptr;
199}
200
202
203} // namespace openthread
204} // namespace esphome
205
206#endif
const std::string & get_name() const
Get the name of this Application set by pre_setup().
std::vector< MDNSService > get_services()
static std::optional< InstanceLock > try_acquire(int delay)
std::optional< otIp6Address > get_omr_address_(InstanceLock &lock)
std::optional< otIp6Address > get_omr_address()
std::vector< std::unique_ptr< uint8_t[]> > memory_pool_
Definition openthread.h:47
void set_mdns(esphome::mdns::MDNSComponent *mdns)
std::vector< esphome::mdns::MDNSService > mdns_services_
Definition openthread.h:46
esphome::mdns::MDNSComponent * mdns_
Definition openthread.h:45
OpenThreadComponent * global_openthread_component
void srp_callback(otError err, const otSrpClientHostInfo *host_info, const otSrpClientService *services, const otSrpClientService *removed_services, void *context)
void srp_start_callback(const otSockAddr *server_socket_address, void *context)
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
Application App
Global storage of Application pointer - only one Application can exist.