ESPHome 2025.10.0-dev
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
13#ifdef USE_LOGGER
15#endif
16
17#include <algorithm>
18
19namespace esphome::api {
20
21static const char *const TAG = "api";
22
23// APIServer
24APIServer *global_api_server = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
25
27 global_api_server = this;
28 // Pre-allocate shared write buffer
29 shared_write_buffer_.reserve(64);
30}
31
33 this->setup_controller();
34
35#ifdef USE_API_NOISE
36 uint32_t hash = 88491486UL;
37
39
40#ifndef USE_API_NOISE_PSK_FROM_YAML
41 // Only load saved PSK if not set from YAML
42 SavedNoisePsk noise_pref_saved{};
43 if (this->noise_pref_.load(&noise_pref_saved)) {
44 ESP_LOGD(TAG, "Loaded saved Noise PSK");
45 this->set_noise_psk(noise_pref_saved.psk);
46 }
47#endif
48#endif
49
50 // Schedule reboot if no clients connect within timeout
51 if (this->reboot_timeout_ != 0) {
53 }
54
55 this->socket_ = socket::socket_ip_loop_monitored(SOCK_STREAM, 0); // monitored for incoming connections
56 if (this->socket_ == nullptr) {
57 ESP_LOGW(TAG, "Could not create socket");
58 this->mark_failed();
59 return;
60 }
61 int enable = 1;
62 int err = this->socket_->setsockopt(SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int));
63 if (err != 0) {
64 ESP_LOGW(TAG, "Socket unable to set reuseaddr: errno %d", err);
65 // we can still continue
66 }
67 err = this->socket_->setblocking(false);
68 if (err != 0) {
69 ESP_LOGW(TAG, "Socket unable to set nonblocking mode: errno %d", err);
70 this->mark_failed();
71 return;
72 }
73
74 struct sockaddr_storage server;
75
76 socklen_t sl = socket::set_sockaddr_any((struct sockaddr *) &server, sizeof(server), this->port_);
77 if (sl == 0) {
78 ESP_LOGW(TAG, "Socket unable to set sockaddr: errno %d", errno);
79 this->mark_failed();
80 return;
81 }
82
83 err = this->socket_->bind((struct sockaddr *) &server, sl);
84 if (err != 0) {
85 ESP_LOGW(TAG, "Socket unable to bind: errno %d", errno);
86 this->mark_failed();
87 return;
88 }
89
90 err = this->socket_->listen(this->listen_backlog_);
91 if (err != 0) {
92 ESP_LOGW(TAG, "Socket unable to listen: errno %d", errno);
93 this->mark_failed();
94 return;
95 }
96
97#ifdef USE_LOGGER
98 if (logger::global_logger != nullptr) {
100 [this](int level, const char *tag, const char *message, size_t message_len) {
101 if (this->shutting_down_) {
102 // Don't try to send logs during shutdown
103 // as it could result in a recursion and
104 // we would be filling a buffer we are trying to clear
105 return;
106 }
107 for (auto &c : this->clients_) {
108 if (!c->flags_.remove && c->get_log_subscription_level() >= level)
109 c->try_send_log_message(level, tag, message, message_len);
110 }
111 });
112 }
113#endif
114
115#ifdef USE_CAMERA
116 if (camera::Camera::instance() != nullptr && !camera::Camera::instance()->is_internal()) {
117 camera::Camera::instance()->add_image_callback([this](const std::shared_ptr<camera::CameraImage> &image) {
118 for (auto &c : this->clients_) {
119 if (!c->flags_.remove)
120 c->set_camera_state(image);
121 }
122 });
123 }
124#endif
125}
126
128 this->status_set_warning();
129 this->set_timeout("api_reboot", this->reboot_timeout_, []() {
130 if (!global_api_server->is_connected()) {
131 ESP_LOGE(TAG, "No clients; rebooting");
132 App.reboot();
133 }
134 });
135}
136
138 // Accept new clients only if the socket exists and has incoming connections
139 if (this->socket_ && this->socket_->ready()) {
140 while (true) {
141 struct sockaddr_storage source_addr;
142 socklen_t addr_len = sizeof(source_addr);
143
144 auto sock = this->socket_->accept_loop_monitored((struct sockaddr *) &source_addr, &addr_len);
145 if (!sock)
146 break;
147
148 // Check if we're at the connection limit
149 if (this->clients_.size() >= this->max_connections_) {
150 ESP_LOGW(TAG, "Max connections (%d), rejecting %s", this->max_connections_, sock->getpeername().c_str());
151 // Immediately close - socket destructor will handle cleanup
152 sock.reset();
153 continue;
154 }
155
156 ESP_LOGD(TAG, "Accept %s", sock->getpeername().c_str());
157
158 auto *conn = new APIConnection(std::move(sock), this);
159 this->clients_.emplace_back(conn);
160 conn->start();
161
162 // Clear warning status and cancel reboot when first client connects
163 if (this->clients_.size() == 1 && this->reboot_timeout_ != 0) {
164 this->status_clear_warning();
165 this->cancel_timeout("api_reboot");
166 }
167 }
168 }
169
170 if (this->clients_.empty()) {
171 return;
172 }
173
174 // Process clients and remove disconnected ones in a single pass
175 // Check network connectivity once for all clients
176 if (!network::is_connected()) {
177 // Network is down - disconnect all clients
178 for (auto &client : this->clients_) {
179 client->on_fatal_error();
180 ESP_LOGW(TAG, "%s: Network down; disconnect", client->get_client_combined_info().c_str());
181 }
182 // Continue to process and clean up the clients below
183 }
184
185 size_t client_index = 0;
186 while (client_index < this->clients_.size()) {
187 auto &client = this->clients_[client_index];
188
189 if (!client->flags_.remove) {
190 // Common case: process active client
191 client->loop();
192 client_index++;
193 continue;
194 }
195
196 // Rare case: handle disconnection
197#ifdef USE_API_CLIENT_DISCONNECTED_TRIGGER
198 this->client_disconnected_trigger_->trigger(client->client_info_.name, client->client_info_.peername);
199#endif
200 ESP_LOGV(TAG, "Remove connection %s", client->client_info_.name.c_str());
201
202 // Swap with the last element and pop (avoids expensive vector shifts)
203 if (client_index < this->clients_.size() - 1) {
204 std::swap(this->clients_[client_index], this->clients_.back());
205 }
206 this->clients_.pop_back();
207
208 // Schedule reboot when last client disconnects
209 if (this->clients_.empty() && this->reboot_timeout_ != 0) {
211 }
212 // Don't increment client_index since we need to process the swapped element
213 }
214}
215
217 ESP_LOGCONFIG(TAG,
218 "Server:\n"
219 " Address: %s:%u\n"
220 " Listen backlog: %u\n"
221 " Max connections: %u",
222 network::get_use_address().c_str(), this->port_, this->listen_backlog_, this->max_connections_);
223#ifdef USE_API_NOISE
224 ESP_LOGCONFIG(TAG, " Noise encryption: %s", YESNO(this->noise_ctx_->has_psk()));
225 if (!this->noise_ctx_->has_psk()) {
226 ESP_LOGCONFIG(TAG, " Supports encryption: YES");
227 }
228#else
229 ESP_LOGCONFIG(TAG, " Noise encryption: NO");
230#endif
231}
232
233#ifdef USE_API_PASSWORD
234bool APIServer::check_password(const uint8_t *password_data, size_t password_len) const {
235 // depend only on input password length
236 const char *a = this->password_.c_str();
237 uint32_t len_a = this->password_.length();
238 const char *b = reinterpret_cast<const char *>(password_data);
239 uint32_t len_b = password_len;
240
241 // disable optimization with volatile
242 volatile uint32_t length = len_b;
243 volatile const char *left = nullptr;
244 volatile const char *right = b;
245 uint8_t result = 0;
246
247 if (len_a == length) {
248 left = *((volatile const char **) &a);
249 result = 0;
250 }
251 if (len_a != length) {
252 left = b;
253 result = 1;
254 }
255
256 for (size_t i = 0; i < length; i++) {
257 result |= *left++ ^ *right++; // NOLINT
258 }
259
260 return result == 0;
261}
262
263#endif
264
266
267// Macro for entities without extra parameters
268#define API_DISPATCH_UPDATE(entity_type, entity_name) \
269 void APIServer::on_##entity_name##_update(entity_type *obj) { /* NOLINT(bugprone-macro-parentheses) */ \
270 if (obj->is_internal()) \
271 return; \
272 for (auto &c : this->clients_) \
273 c->send_##entity_name##_state(obj); \
274 }
275
276// Macro for entities with extra parameters (but parameters not used in send)
277#define API_DISPATCH_UPDATE_IGNORE_PARAMS(entity_type, entity_name, ...) \
278 void APIServer::on_##entity_name##_update(entity_type *obj, __VA_ARGS__) { /* NOLINT(bugprone-macro-parentheses) */ \
279 if (obj->is_internal()) \
280 return; \
281 for (auto &c : this->clients_) \
282 c->send_##entity_name##_state(obj); \
283 }
284
285#ifdef USE_BINARY_SENSOR
287#endif
288
289#ifdef USE_COVER
291#endif
292
293#ifdef USE_FAN
295#endif
296
297#ifdef USE_LIGHT
299#endif
300
301#ifdef USE_SENSOR
302API_DISPATCH_UPDATE_IGNORE_PARAMS(sensor::Sensor, sensor, float state)
303#endif
304
305#ifdef USE_SWITCH
306API_DISPATCH_UPDATE_IGNORE_PARAMS(switch_::Switch, switch, bool state)
307#endif
308
309#ifdef USE_TEXT_SENSOR
310API_DISPATCH_UPDATE_IGNORE_PARAMS(text_sensor::TextSensor, text_sensor, const std::string &state)
311#endif
312
313#ifdef USE_CLIMATE
315#endif
316
317#ifdef USE_NUMBER
318API_DISPATCH_UPDATE_IGNORE_PARAMS(number::Number, number, float state)
319#endif
320
321#ifdef USE_DATETIME_DATE
323#endif
324
325#ifdef USE_DATETIME_TIME
327#endif
328
329#ifdef USE_DATETIME_DATETIME
331#endif
332
333#ifdef USE_TEXT
334API_DISPATCH_UPDATE_IGNORE_PARAMS(text::Text, text, const std::string &state)
335#endif
336
337#ifdef USE_SELECT
338API_DISPATCH_UPDATE_IGNORE_PARAMS(select::Select, select, const std::string &state, size_t index)
339#endif
340
341#ifdef USE_LOCK
343#endif
344
345#ifdef USE_VALVE
347#endif
348
349#ifdef USE_MEDIA_PLAYER
351#endif
352
353#ifdef USE_EVENT
354// Event is a special case - it's the only entity that passes extra parameters to the send method
355void APIServer::on_event(event::Event *obj, const std::string &event_type) {
356 if (obj->is_internal())
357 return;
358 for (auto &c : this->clients_)
359 c->send_event(obj, event_type);
360}
361#endif
362
363#ifdef USE_UPDATE
364// Update is a special case - the method is called on_update, not on_update_update
366 if (obj->is_internal())
367 return;
368 for (auto &c : this->clients_)
369 c->send_update_state(obj);
370}
371#endif
372
373#ifdef USE_ZWAVE_PROXY
375 // We could add code to manage a second subscription type, but, since this message type is
376 // very infrequent and small, we simply send it to all clients
377 for (auto &c : this->clients_)
378 c->send_message(msg, api::ZWaveProxyRequest::MESSAGE_TYPE);
379}
380#endif
381
382#ifdef USE_ALARM_CONTROL_PANEL
384#endif
385
387
388void APIServer::set_port(uint16_t port) { this->port_ = port; }
389
390#ifdef USE_API_PASSWORD
391void APIServer::set_password(const std::string &password) { this->password_ = password; }
392#endif
393
394void APIServer::set_batch_delay(uint16_t batch_delay) { this->batch_delay_ = batch_delay; }
395
396#ifdef USE_API_HOMEASSISTANT_SERVICES
398 for (auto &client : this->clients_) {
399 client->send_homeassistant_action(call);
400 }
401}
402#endif
403
404#ifdef USE_API_HOMEASSISTANT_STATES
406 std::function<void(std::string)> f) {
408 .entity_id = std::move(entity_id),
409 .attribute = std::move(attribute),
410 .callback = std::move(f),
411 .once = false,
412 });
413}
414
415void APIServer::get_home_assistant_state(std::string entity_id, optional<std::string> attribute,
416 std::function<void(std::string)> f) {
418 .entity_id = std::move(entity_id),
419 .attribute = std::move(attribute),
420 .callback = std::move(f),
421 .once = true,
422 });
423};
424
425const std::vector<APIServer::HomeAssistantStateSubscription> &APIServer::get_state_subs() const {
426 return this->state_subs_;
427}
428#endif
429
430uint16_t APIServer::get_port() const { return this->port_; }
431
432void APIServer::set_reboot_timeout(uint32_t reboot_timeout) { this->reboot_timeout_ = reboot_timeout; }
433
434#ifdef USE_API_NOISE
435bool APIServer::save_noise_psk(psk_t psk, bool make_active) {
436#ifdef USE_API_NOISE_PSK_FROM_YAML
437 // When PSK is set from YAML, this function should never be called
438 // but if it is, reject the change
439 ESP_LOGW(TAG, "Key set in YAML");
440 return false;
441#else
442 auto &old_psk = this->noise_ctx_->get_psk();
443 if (std::equal(old_psk.begin(), old_psk.end(), psk.begin())) {
444 ESP_LOGW(TAG, "New PSK matches old");
445 return true;
446 }
447
448 SavedNoisePsk new_saved_psk{psk};
449 if (!this->noise_pref_.save(&new_saved_psk)) {
450 ESP_LOGW(TAG, "Failed to save Noise PSK");
451 return false;
452 }
453 // ensure it's written immediately
454 if (!global_preferences->sync()) {
455 ESP_LOGW(TAG, "Failed to sync preferences");
456 return false;
457 }
458 ESP_LOGD(TAG, "Noise PSK saved");
459 if (make_active) {
460 this->set_timeout(100, [this, psk]() {
461 ESP_LOGW(TAG, "Disconnecting all clients to reset PSK");
462 this->set_noise_psk(psk);
463 for (auto &c : this->clients_) {
465 c->send_message(req, DisconnectRequest::MESSAGE_TYPE);
466 }
467 });
468 }
469 return true;
470#endif
471}
472#endif
473
474#ifdef USE_HOMEASSISTANT_TIME
476 for (auto &client : this->clients_) {
477 if (!client->flags_.remove && client->is_authenticated())
478 client->send_time_request();
479 }
480}
481#endif
482
483bool APIServer::is_connected() const { return !this->clients_.empty(); }
484
486 this->shutting_down_ = true;
487
488 // Close the listening socket to prevent new connections
489 if (this->socket_) {
490 this->socket_->close();
491 this->socket_ = nullptr;
492 }
493
494 // Change batch delay to 5ms for quick flushing during shutdown
495 this->batch_delay_ = 5;
496
497 // Send disconnect requests to all connected clients
498 for (auto &c : this->clients_) {
500 if (!c->send_message(req, DisconnectRequest::MESSAGE_TYPE)) {
501 // If we can't send the disconnect request directly (tx_buffer full),
502 // schedule it at the front of the batch so it will be sent with priority
505 }
506 }
507}
508
510 // If network is disconnected, no point trying to flush buffers
511 if (!network::is_connected()) {
512 return true;
513 }
514 this->loop();
515
516 // Return true only when all clients have been torn down
517 return this->clients_.empty();
518}
519
520} // namespace esphome::api
521#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)
std::vector< std::unique_ptr< APIConnection > > clients_
Definition api_server.h:179
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
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
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:202
Trigger< std::string, std::string > * client_disconnected_trigger_
Definition api_server.h:172
std::vector< uint8_t > shared_write_buffer_
Definition api_server.h:183
void subscribe_home_assistant_state(std::string entity_id, optional< std::string > attribute, std::function< void(std::string)> f)
ESPPreferenceObject noise_pref_
Definition api_server.h:203
std::vector< HomeAssistantStateSubscription > state_subs_
Definition api_server.h:185
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:55
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:167
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:2974
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:103
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:229
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
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:288
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:56
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