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