ESPHome 2025.10.4
Loading...
Searching...
No Matches
api_server.cpp
Go to the documentation of this file.
1#include "api_server.h"
2#ifdef USE_API
3#include <cerrno>
4#include "api_connection.h"
8#include "esphome/core/hal.h"
9#include "esphome/core/log.h"
10#include "esphome/core/util.h"
12#ifdef USE_API_HOMEASSISTANT_SERVICES
14#endif
15
16#ifdef USE_LOGGER
18#endif
19
20#include <algorithm>
21#include <utility>
22
23namespace esphome::api {
24
25static const char *const TAG = "api";
26
27// APIServer
28APIServer *global_api_server = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
29
31 global_api_server = this;
32 // Pre-allocate shared write buffer
33 shared_write_buffer_.reserve(64);
34}
35
37 this->setup_controller();
38
39#ifdef USE_API_NOISE
40 uint32_t hash = 88491486UL;
41
43
44#ifndef USE_API_NOISE_PSK_FROM_YAML
45 // Only load saved PSK if not set from YAML
46 SavedNoisePsk noise_pref_saved{};
47 if (this->noise_pref_.load(&noise_pref_saved)) {
48 ESP_LOGD(TAG, "Loaded saved Noise PSK");
49 this->set_noise_psk(noise_pref_saved.psk);
50 }
51#endif
52#endif
53
54 // Schedule reboot if no clients connect within timeout
55 if (this->reboot_timeout_ != 0) {
57 }
58
59 this->socket_ = socket::socket_ip_loop_monitored(SOCK_STREAM, 0); // monitored for incoming connections
60 if (this->socket_ == nullptr) {
61 ESP_LOGW(TAG, "Could not create socket");
62 this->mark_failed();
63 return;
64 }
65 int enable = 1;
66 int err = this->socket_->setsockopt(SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int));
67 if (err != 0) {
68 ESP_LOGW(TAG, "Socket unable to set reuseaddr: errno %d", err);
69 // we can still continue
70 }
71 err = this->socket_->setblocking(false);
72 if (err != 0) {
73 ESP_LOGW(TAG, "Socket unable to set nonblocking mode: errno %d", err);
74 this->mark_failed();
75 return;
76 }
77
78 struct sockaddr_storage server;
79
80 socklen_t sl = socket::set_sockaddr_any((struct sockaddr *) &server, sizeof(server), this->port_);
81 if (sl == 0) {
82 ESP_LOGW(TAG, "Socket unable to set sockaddr: errno %d", errno);
83 this->mark_failed();
84 return;
85 }
86
87 err = this->socket_->bind((struct sockaddr *) &server, sl);
88 if (err != 0) {
89 ESP_LOGW(TAG, "Socket unable to bind: errno %d", errno);
90 this->mark_failed();
91 return;
92 }
93
94 err = this->socket_->listen(this->listen_backlog_);
95 if (err != 0) {
96 ESP_LOGW(TAG, "Socket unable to listen: errno %d", errno);
97 this->mark_failed();
98 return;
99 }
100
101#ifdef USE_LOGGER
102 if (logger::global_logger != nullptr) {
104 [this](int level, const char *tag, const char *message, size_t message_len) {
105 if (this->shutting_down_) {
106 // Don't try to send logs during shutdown
107 // as it could result in a recursion and
108 // we would be filling a buffer we are trying to clear
109 return;
110 }
111 for (auto &c : this->clients_) {
112 if (!c->flags_.remove && c->get_log_subscription_level() >= level)
113 c->try_send_log_message(level, tag, message, message_len);
114 }
115 });
116 }
117#endif
118
119#ifdef USE_CAMERA
120 if (camera::Camera::instance() != nullptr && !camera::Camera::instance()->is_internal()) {
121 camera::Camera::instance()->add_image_callback([this](const std::shared_ptr<camera::CameraImage> &image) {
122 for (auto &c : this->clients_) {
123 if (!c->flags_.remove)
124 c->set_camera_state(image);
125 }
126 });
127 }
128#endif
129}
130
132 this->status_set_warning();
133 this->set_timeout("api_reboot", this->reboot_timeout_, []() {
134 if (!global_api_server->is_connected()) {
135 ESP_LOGE(TAG, "No clients; rebooting");
136 App.reboot();
137 }
138 });
139}
140
142 // Accept new clients only if the socket exists and has incoming connections
143 if (this->socket_ && this->socket_->ready()) {
144 while (true) {
145 struct sockaddr_storage source_addr;
146 socklen_t addr_len = sizeof(source_addr);
147
148 auto sock = this->socket_->accept_loop_monitored((struct sockaddr *) &source_addr, &addr_len);
149 if (!sock)
150 break;
151
152 // Check if we're at the connection limit
153 if (this->clients_.size() >= this->max_connections_) {
154 ESP_LOGW(TAG, "Max connections (%d), rejecting %s", this->max_connections_, sock->getpeername().c_str());
155 // Immediately close - socket destructor will handle cleanup
156 sock.reset();
157 continue;
158 }
159
160 ESP_LOGD(TAG, "Accept %s", sock->getpeername().c_str());
161
162 auto *conn = new APIConnection(std::move(sock), this);
163 this->clients_.emplace_back(conn);
164 conn->start();
165
166 // Clear warning status and cancel reboot when first client connects
167 if (this->clients_.size() == 1 && this->reboot_timeout_ != 0) {
168 this->status_clear_warning();
169 this->cancel_timeout("api_reboot");
170 }
171 }
172 }
173
174 if (this->clients_.empty()) {
175 return;
176 }
177
178 // Process clients and remove disconnected ones in a single pass
179 // Check network connectivity once for all clients
180 if (!network::is_connected()) {
181 // Network is down - disconnect all clients
182 for (auto &client : this->clients_) {
183 client->on_fatal_error();
184 ESP_LOGW(TAG, "%s (%s): Network down; disconnect", client->client_info_.name.c_str(),
185 client->client_info_.peername.c_str());
186 }
187 // Continue to process and clean up the clients below
188 }
189
190 size_t client_index = 0;
191 while (client_index < this->clients_.size()) {
192 auto &client = this->clients_[client_index];
193
194 if (!client->flags_.remove) {
195 // Common case: process active client
196 client->loop();
197 client_index++;
198 continue;
199 }
200
201 // Rare case: handle disconnection
202#ifdef USE_API_CLIENT_DISCONNECTED_TRIGGER
203 this->client_disconnected_trigger_->trigger(client->client_info_.name, client->client_info_.peername);
204#endif
205 ESP_LOGV(TAG, "Remove connection %s", client->client_info_.name.c_str());
206
207 // Swap with the last element and pop (avoids expensive vector shifts)
208 if (client_index < this->clients_.size() - 1) {
209 std::swap(this->clients_[client_index], this->clients_.back());
210 }
211 this->clients_.pop_back();
212
213 // Schedule reboot when last client disconnects
214 if (this->clients_.empty() && this->reboot_timeout_ != 0) {
216 }
217 // Don't increment client_index since we need to process the swapped element
218 }
219}
220
222 ESP_LOGCONFIG(TAG,
223 "Server:\n"
224 " Address: %s:%u\n"
225 " Listen backlog: %u\n"
226 " Max connections: %u",
227 network::get_use_address().c_str(), this->port_, this->listen_backlog_, this->max_connections_);
228#ifdef USE_API_NOISE
229 ESP_LOGCONFIG(TAG, " Noise encryption: %s", YESNO(this->noise_ctx_->has_psk()));
230 if (!this->noise_ctx_->has_psk()) {
231 ESP_LOGCONFIG(TAG, " Supports encryption: YES");
232 }
233#else
234 ESP_LOGCONFIG(TAG, " Noise encryption: NO");
235#endif
236}
237
238#ifdef USE_API_PASSWORD
239bool APIServer::check_password(const uint8_t *password_data, size_t password_len) const {
240 // depend only on input password length
241 const char *a = this->password_.c_str();
242 uint32_t len_a = this->password_.length();
243 const char *b = reinterpret_cast<const char *>(password_data);
244 uint32_t len_b = password_len;
245
246 // disable optimization with volatile
247 volatile uint32_t length = len_b;
248 volatile const char *left = nullptr;
249 volatile const char *right = b;
250 uint8_t result = 0;
251
252 if (len_a == length) {
253 left = *((volatile const char **) &a);
254 result = 0;
255 }
256 if (len_a != length) {
257 left = b;
258 result = 1;
259 }
260
261 for (size_t i = 0; i < length; i++) {
262 result |= *left++ ^ *right++; // NOLINT
263 }
264
265 return result == 0;
266}
267
268#endif
269
271
272// Macro for entities without extra parameters
273#define API_DISPATCH_UPDATE(entity_type, entity_name) \
274 void APIServer::on_##entity_name##_update(entity_type *obj) { /* NOLINT(bugprone-macro-parentheses) */ \
275 if (obj->is_internal()) \
276 return; \
277 for (auto &c : this->clients_) \
278 c->send_##entity_name##_state(obj); \
279 }
280
281// Macro for entities with extra parameters (but parameters not used in send)
282#define API_DISPATCH_UPDATE_IGNORE_PARAMS(entity_type, entity_name, ...) \
283 void APIServer::on_##entity_name##_update(entity_type *obj, __VA_ARGS__) { /* NOLINT(bugprone-macro-parentheses) */ \
284 if (obj->is_internal()) \
285 return; \
286 for (auto &c : this->clients_) \
287 c->send_##entity_name##_state(obj); \
288 }
289
290#ifdef USE_BINARY_SENSOR
292#endif
293
294#ifdef USE_COVER
296#endif
297
298#ifdef USE_FAN
300#endif
301
302#ifdef USE_LIGHT
304#endif
305
306#ifdef USE_SENSOR
307API_DISPATCH_UPDATE_IGNORE_PARAMS(sensor::Sensor, sensor, float state)
308#endif
309
310#ifdef USE_SWITCH
311API_DISPATCH_UPDATE_IGNORE_PARAMS(switch_::Switch, switch, bool state)
312#endif
313
314#ifdef USE_TEXT_SENSOR
315API_DISPATCH_UPDATE_IGNORE_PARAMS(text_sensor::TextSensor, text_sensor, const std::string &state)
316#endif
317
318#ifdef USE_CLIMATE
320#endif
321
322#ifdef USE_NUMBER
323API_DISPATCH_UPDATE_IGNORE_PARAMS(number::Number, number, float state)
324#endif
325
326#ifdef USE_DATETIME_DATE
328#endif
329
330#ifdef USE_DATETIME_TIME
332#endif
333
334#ifdef USE_DATETIME_DATETIME
336#endif
337
338#ifdef USE_TEXT
339API_DISPATCH_UPDATE_IGNORE_PARAMS(text::Text, text, const std::string &state)
340#endif
341
342#ifdef USE_SELECT
343API_DISPATCH_UPDATE_IGNORE_PARAMS(select::Select, select, const std::string &state, size_t index)
344#endif
345
346#ifdef USE_LOCK
348#endif
349
350#ifdef USE_VALVE
352#endif
353
354#ifdef USE_MEDIA_PLAYER
356#endif
357
358#ifdef USE_EVENT
359// Event is a special case - it's the only entity that passes extra parameters to the send method
360void APIServer::on_event(event::Event *obj, const std::string &event_type) {
361 if (obj->is_internal())
362 return;
363 for (auto &c : this->clients_)
364 c->send_event(obj, event_type);
365}
366#endif
367
368#ifdef USE_UPDATE
369// Update is a special case - the method is called on_update, not on_update_update
371 if (obj->is_internal())
372 return;
373 for (auto &c : this->clients_)
374 c->send_update_state(obj);
375}
376#endif
377
378#ifdef USE_ZWAVE_PROXY
380 // We could add code to manage a second subscription type, but, since this message type is
381 // very infrequent and small, we simply send it to all clients
382 for (auto &c : this->clients_)
383 c->send_message(msg, api::ZWaveProxyRequest::MESSAGE_TYPE);
384}
385#endif
386
387#ifdef USE_ALARM_CONTROL_PANEL
389#endif
390
392
393void APIServer::set_port(uint16_t port) { this->port_ = port; }
394
395#ifdef USE_API_PASSWORD
396void APIServer::set_password(const std::string &password) { this->password_ = password; }
397#endif
398
399void APIServer::set_batch_delay(uint16_t batch_delay) { this->batch_delay_ = batch_delay; }
400
401#ifdef USE_API_HOMEASSISTANT_SERVICES
403 for (auto &client : this->clients_) {
404 client->send_homeassistant_action(call);
405 }
406}
407#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES
409 this->action_response_callbacks_.push_back({call_id, std::move(callback)});
410}
411
412void APIServer::handle_action_response(uint32_t call_id, bool success, const std::string &error_message) {
413 for (auto it = this->action_response_callbacks_.begin(); it != this->action_response_callbacks_.end(); ++it) {
414 if (it->call_id == call_id) {
415 auto callback = std::move(it->callback);
416 this->action_response_callbacks_.erase(it);
417 ActionResponse response(success, error_message);
418 callback(response);
419 return;
420 }
421 }
422}
423#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES_JSON
424void APIServer::handle_action_response(uint32_t call_id, bool success, const std::string &error_message,
425 const uint8_t *response_data, size_t response_data_len) {
426 for (auto it = this->action_response_callbacks_.begin(); it != this->action_response_callbacks_.end(); ++it) {
427 if (it->call_id == call_id) {
428 auto callback = std::move(it->callback);
429 this->action_response_callbacks_.erase(it);
430 ActionResponse response(success, error_message, response_data, response_data_len);
431 callback(response);
432 return;
433 }
434 }
435}
436#endif // USE_API_HOMEASSISTANT_ACTION_RESPONSES_JSON
437#endif // USE_API_HOMEASSISTANT_ACTION_RESPONSES
438#endif // USE_API_HOMEASSISTANT_SERVICES
439
440#ifdef USE_API_HOMEASSISTANT_STATES
442 std::function<void(std::string)> f) {
444 .entity_id = std::move(entity_id),
445 .attribute = std::move(attribute),
446 .callback = std::move(f),
447 .once = false,
448 });
449}
450
451void APIServer::get_home_assistant_state(std::string entity_id, optional<std::string> attribute,
452 std::function<void(std::string)> f) {
454 .entity_id = std::move(entity_id),
455 .attribute = std::move(attribute),
456 .callback = std::move(f),
457 .once = true,
458 });
459};
460
461const std::vector<APIServer::HomeAssistantStateSubscription> &APIServer::get_state_subs() const {
462 return this->state_subs_;
463}
464#endif
465
466uint16_t APIServer::get_port() const { return this->port_; }
467
468void APIServer::set_reboot_timeout(uint32_t reboot_timeout) { this->reboot_timeout_ = reboot_timeout; }
469
470#ifdef USE_API_NOISE
471bool APIServer::save_noise_psk(psk_t psk, bool make_active) {
472#ifdef USE_API_NOISE_PSK_FROM_YAML
473 // When PSK is set from YAML, this function should never be called
474 // but if it is, reject the change
475 ESP_LOGW(TAG, "Key set in YAML");
476 return false;
477#else
478 auto &old_psk = this->noise_ctx_->get_psk();
479 if (std::equal(old_psk.begin(), old_psk.end(), psk.begin())) {
480 ESP_LOGW(TAG, "New PSK matches old");
481 return true;
482 }
483
484 SavedNoisePsk new_saved_psk{psk};
485 if (!this->noise_pref_.save(&new_saved_psk)) {
486 ESP_LOGW(TAG, "Failed to save Noise PSK");
487 return false;
488 }
489 // ensure it's written immediately
490 if (!global_preferences->sync()) {
491 ESP_LOGW(TAG, "Failed to sync preferences");
492 return false;
493 }
494 ESP_LOGD(TAG, "Noise PSK saved");
495 if (make_active) {
496 this->set_timeout(100, [this, psk]() {
497 ESP_LOGW(TAG, "Disconnecting all clients to reset PSK");
498 this->set_noise_psk(psk);
499 for (auto &c : this->clients_) {
501 c->send_message(req, DisconnectRequest::MESSAGE_TYPE);
502 }
503 });
504 }
505 return true;
506#endif
507}
508#endif
509
510#ifdef USE_HOMEASSISTANT_TIME
512 for (auto &client : this->clients_) {
513 if (!client->flags_.remove && client->is_authenticated())
514 client->send_time_request();
515 }
516}
517#endif
518
519bool APIServer::is_connected() const { return !this->clients_.empty(); }
520
522 this->shutting_down_ = true;
523
524 // Close the listening socket to prevent new connections
525 if (this->socket_) {
526 this->socket_->close();
527 this->socket_ = nullptr;
528 }
529
530 // Change batch delay to 5ms for quick flushing during shutdown
531 this->batch_delay_ = 5;
532
533 // Send disconnect requests to all connected clients
534 for (auto &c : this->clients_) {
536 if (!c->send_message(req, DisconnectRequest::MESSAGE_TYPE)) {
537 // If we can't send the disconnect request directly (tx_buffer full),
538 // schedule it at the front of the batch so it will be sent with priority
541 }
542 }
543}
544
546 // If network is disconnected, no point trying to flush buffers
547 if (!network::is_connected()) {
548 return true;
549 }
550 this->loop();
551
552 // Return true only when all clients have been torn down
553 return this->clients_.empty();
554}
555
556} // namespace esphome::api
557#endif
virtual void mark_failed()
Mark this component as failed.
void status_set_warning(const char *message=nullptr)
bool cancel_timeout(const std::string &name)
Cancel a timeout function.
void status_clear_warning()
void set_timeout(const std::string &name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a unique name.
void setup_controller(bool include_internal=false)
Definition controller.cpp:7
bool save(const T *src)
Definition preferences.h:21
virtual bool sync()=0
Commit pending writes to flash.
virtual ESPPreferenceObject make_preference(size_t length, uint32_t type, bool in_flash)=0
bool is_internal() const
Definition entity_base.h:44
void trigger(Ts... x)
Inform the parent automation that the event has triggered.
Definition automation.h:145
static uint16_t try_send_disconnect_request(EntityBase *entity, APIConnection *conn, uint32_t remaining_size, bool is_single)
void register_action_response_callback(uint32_t call_id, ActionResponseCallback callback)
std::vector< std::unique_ptr< APIConnection > > clients_
Definition api_server.h:190
void set_password(const std::string &password)
void set_port(uint16_t port)
void dump_config() override
void handle_disconnect(APIConnection *conn)
void set_batch_delay(uint16_t batch_delay)
void set_reboot_timeout(uint32_t reboot_timeout)
bool save_noise_psk(psk_t psk, bool make_active=true)
void setup() override
void handle_action_response(uint32_t call_id, bool success, const std::string &error_message)
bool teardown() override
void send_homeassistant_action(const HomeassistantActionRequest &call)
void on_update(update::UpdateEntity *obj) override
bool check_password(const uint8_t *password_data, size_t password_len) const
std::vector< PendingActionResponse > action_response_callbacks_
Definition api_server.h:206
void get_home_assistant_state(std::string entity_id, optional< std::string > attribute, std::function< void(std::string)> f)
const std::vector< HomeAssistantStateSubscription > & get_state_subs() const
std::shared_ptr< APINoiseContext > noise_ctx_
Definition api_server.h:220
Trigger< std::string, std::string > * client_disconnected_trigger_
Definition api_server.h:183
std::vector< uint8_t > shared_write_buffer_
Definition api_server.h:194
void subscribe_home_assistant_state(std::string entity_id, optional< std::string > attribute, std::function< void(std::string)> f)
std::function< void(const class ActionResponse &)> ActionResponseCallback
Definition api_server.h:117
ESPPreferenceObject noise_pref_
Definition api_server.h:221
std::vector< HomeAssistantStateSubscription > state_subs_
Definition api_server.h:196
void on_zwave_proxy_request(const esphome::api::ProtoMessage &msg)
uint16_t get_port() const
void set_noise_psk(psk_t psk)
Definition api_server.h:56
void on_event(event::Event *obj, const std::string &event_type) override
float get_setup_priority() const override
std::unique_ptr< socket::Socket > socket_
Definition api_server.h:178
void on_shutdown() override
static constexpr uint8_t MESSAGE_TYPE
Definition api_pb2.h:407
static constexpr uint8_t ESTIMATED_SIZE
Definition api_pb2.h:408
static constexpr uint8_t MESSAGE_TYPE
Definition api_pb2.h:3007
Base class for all binary_sensor-type classes.
static Camera * instance()
The singleton instance of the camera implementation.
Definition camera.cpp:19
virtual void add_image_callback(std::function< void(std::shared_ptr< CameraImage >)> &&callback)=0
ClimateDevice - This is the base class for all climate integrations.
Definition climate.h:168
Base class for all cover devices.
Definition cover.h:111
This class represents the communication layer between the front-end MQTT layer and the hardware outpu...
Definition light_state.h:68
Base class for all locks.
Definition lock.h:109
void add_on_log_callback(std::function< void(uint8_t, const char *, const char *, size_t)> &&callback)
Register a callback that will be called for every log message sent.
Definition logger.cpp:233
Base-class for all numbers.
Definition number.h:30
Base-class for all selects.
Definition select.h:31
Base-class for all sensors.
Definition sensor.h:42
Base class for all switches.
Definition switch.h:39
Base-class for all text inputs.
Definition text.h:24
Base class for all valve devices.
Definition valve.h:105
const char * message
Definition component.cpp:38
uint16_t addr_len
bool state
Definition fan.h:0
uint32_t socklen_t
Definition headers.h:97
APIServer * global_api_server
API_DISPATCH_UPDATE(binary_sensor::BinarySensor, binary_sensor) API_DISPATCH_UPDATE(cover
std::array< uint8_t, 32 > psk_t
Logger * global_logger
Definition logger.cpp:294
std::string get_use_address()
Get the active network hostname.
Definition util.cpp:88
bool is_connected()
Return whether the node is connected to the network (through wifi, eth, ...)
Definition util.cpp:26
const float AFTER_WIFI
For components that should be initialized after WiFi is connected.
Definition component.cpp:66
std::unique_ptr< Socket > socket_ip_loop_monitored(int type, int protocol)
Definition socket.cpp:44
socklen_t set_sockaddr_any(struct sockaddr *addr, socklen_t addrlen, uint16_t port)
Set a sockaddr to the any address and specified port for the IP version used by socket_ip().
Definition socket.cpp:82
ESPPreferences * global_preferences
Application App
Global storage of Application pointer - only one Application can exist.
uint16_t length
Definition tt21100.cpp:0