13#ifdef USE_API_HOMEASSISTANT_SERVICES
26static const char *
const TAG =
"api";
41 uint32_t hash = 88491486UL;
45#ifndef USE_API_NOISE_PSK_FROM_YAML
49 ESP_LOGD(TAG,
"Loaded saved Noise PSK");
57 ESP_LOGW(TAG,
"Could not create socket");
62 int err = this->
socket_->setsockopt(SOL_SOCKET, SO_REUSEADDR, &enable,
sizeof(
int));
64 ESP_LOGW(TAG,
"Socket unable to set reuseaddr: errno %d", err);
67 err = this->
socket_->setblocking(
false);
69 ESP_LOGW(TAG,
"Socket unable to set nonblocking mode: errno %d", err);
78 ESP_LOGW(TAG,
"Socket unable to set sockaddr: errno %d", errno);
85 ESP_LOGW(TAG,
"Socket unable to bind: errno %d", errno);
92 ESP_LOGW(TAG,
"Socket unable to listen: errno %d", errno);
120 this->accept_new_connections_();
129 ESP_LOGE(TAG,
"No clients; rebooting");
140 for (
auto &client : this->
clients_) {
141 client->on_fatal_error();
142 client->log_client_(ESPHOME_LOG_LEVEL_WARN, LOG_STR(
"Network down; disconnect"));
147 size_t client_index = 0;
148 while (client_index < this->
clients_.size()) {
149 auto &client = this->
clients_[client_index];
152 if (!client->flags_.remove) {
157 if (client->flags_.remove) {
159 this->remove_client_(client_index);
166void APIServer::remove_client_(
size_t client_index) {
167 auto &client = this->
clients_[client_index];
169#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES
172 ESP_LOGV(TAG,
"Remove connection %s", client->get_name());
174#ifdef USE_API_CLIENT_DISCONNECTED_TRIGGER
176 char peername_buf[socket::SOCKADDR_STR_LEN];
177 std::string client_name(client->get_name());
178 std::string client_peername(client->get_peername_to(peername_buf));
182 client->helper_->close();
185 if (client_index < this->
clients_.size() - 1) {
191 if (this->
clients_.empty() && this->reboot_timeout_ != 0) {
196#ifdef USE_API_CLIENT_DISCONNECTED_TRIGGER
202void APIServer::accept_new_connections_() {
211 char peername[socket::SOCKADDR_STR_LEN];
212 sock->getpeername_to(peername);
215 if (this->
clients_.size() >= this->max_connections_) {
216 ESP_LOGW(TAG,
"Max connections (%d), rejecting %s", this->
max_connections_, peername);
222 ESP_LOGD(TAG,
"Accept %s", peername);
224 auto *conn =
new APIConnection(std::move(sock),
this);
229 if (this->
clients_.size() == 1 && this->reboot_timeout_ != 0) {
240 " Listen backlog: %u\n"
241 " Max connections: %u",
246 ESP_LOGCONFIG(TAG,
" Supports encryption: YES");
249 ESP_LOGCONFIG(TAG,
" Noise encryption: NO");
256#define API_DISPATCH_UPDATE(entity_type, entity_name) \
257 void APIServer::on_##entity_name##_update(entity_type *obj) { \
258 if (obj->is_internal()) \
260 for (auto &c : this->clients_) { \
261 if (c->flags_.state_subscription) \
262 c->send_##entity_name##_state(obj); \
266#ifdef USE_BINARY_SENSOR
290#ifdef USE_TEXT_SENSOR
302#ifdef USE_DATETIME_DATE
306#ifdef USE_DATETIME_TIME
310#ifdef USE_DATETIME_DATETIME
330#ifdef USE_MEDIA_PLAYER
334#ifdef USE_WATER_HEATER
343 if (c->flags_.state_subscription)
355 if (c->flags_.state_subscription)
356 c->send_update_state(obj);
361#ifdef USE_ZWAVE_PROXY
372 const std::vector<int32_t> *timings) {
378 resp.timings = timings;
381 c->send_infrared_rf_receive_event(resp);
385#ifdef USE_ALARM_CONTROL_PANEL
395#ifdef USE_API_HOMEASSISTANT_SERVICES
397 for (
auto &client : this->
clients_) {
398 client->send_homeassistant_action(
call);
401#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES
408 if (it->call_id == call_id) {
409 auto callback = std::move(it->callback);
417#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES_JSON
419 const uint8_t *response_data,
size_t response_data_len) {
421 if (it->call_id == call_id) {
422 auto callback = std::move(it->callback);
424 ActionResponse response(success, error_message, response_data, response_data_len);
434#ifdef USE_API_HOMEASSISTANT_STATES
439 .entity_id = entity_id, .attribute = attribute, .callback = std::move(
f), .once = once,
446 std::function<
void(
StringRef)> f,
bool once) {
488 std::function<
void(
const std::string &)> f,
bool once) {
497 std::function<
void(
const std::string &)> f) {
502 std::function<
void(
const std::string &)> f) {
517 const LogString *fail_log_msg,
const psk_t &active_psk,
bool make_active) {
519 ESP_LOGW(TAG,
"%s", LOG_STR_ARG(fail_log_msg));
524 ESP_LOGW(TAG,
"Failed to sync preferences");
527 ESP_LOGD(TAG,
"%s", LOG_STR_ARG(save_log_msg));
530 ESP_LOGW(TAG,
"Disconnecting all clients to reset PSK");
542#ifdef USE_API_NOISE_PSK_FROM_YAML
545 ESP_LOGW(TAG,
"Key set in YAML");
549 if (std::equal(old_psk.begin(), old_psk.end(), psk.begin())) {
550 ESP_LOGW(TAG,
"New PSK matches old");
555 return this->
update_noise_psk_(new_saved_psk, LOG_STR(
"Noise PSK saved"), LOG_STR(
"Failed to save Noise PSK"), psk,
560#ifdef USE_API_NOISE_PSK_FROM_YAML
563 ESP_LOGW(TAG,
"Key set in YAML");
568 return this->
update_noise_psk_(empty_psk, LOG_STR(
"Noise PSK cleared"), LOG_STR(
"Failed to clear Noise PSK"), empty,
574#ifdef USE_HOMEASSISTANT_TIME
576 for (
auto &client : this->
clients_) {
577 if (!client->flags_.remove && client->is_authenticated()) {
578 client->send_time_request();
586 if (!state_subscription_only) {
590 for (
const auto &client : this->
clients_) {
591 if (client->flags_.state_subscription) {
607 if (!c->flags_.remove && c->get_log_subscription_level() >= level)
608 c->try_send_log_message(level, tag,
message, message_len);
616 if (!c->flags_.remove)
617 c->set_camera_state(image);
656#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES
659#ifndef USE_API_ACTION_CALL_TIMEOUT_MS
660#define USE_API_ACTION_CALL_TIMEOUT_MS 30000
673 this->
set_timeout(action_call_id, USE_API_ACTION_CALL_TIMEOUT_MS, [
this, action_call_id]() {
674 ESP_LOGD(TAG,
"Action call %u timed out", action_call_id);
678 return action_call_id;
713 if (
call.action_call_id == action_call_id) {
714 call.connection->send_execute_service_response(
call.client_call_id, success, error_message);
718 ESP_LOGW(TAG,
"Cannot send response: no active call found for action_call_id %u", action_call_id);
720#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES_JSON
722 const uint8_t *response_data,
size_t response_data_len) {
724 if (
call.action_call_id == action_call_id) {
725 call.connection->send_execute_service_response(
call.client_call_id, success, error_message, response_data,
730 ESP_LOGW(TAG,
"Cannot send response: no active call found for action_call_id %u", action_call_id);
uint32_t IRAM_ATTR HOT get_loop_component_start_time() const
Get the cached time in milliseconds from when the current component started its loop execution.
virtual void mark_failed()
Mark this component as failed.
void status_set_warning(const char *message=nullptr)
ESPDEPRECATED("Use const char* or uint32_t overload instead. Removed in 2026.7.0", "2026.1.0") void set_timeout(const std voi set_timeout)(const char *name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a unique name.
ESPDEPRECATED("Use const char* or uint32_t overload instead. Removed in 2026.7.0", "2026.1.0") bool cancel_timeout(const std boo cancel_timeout)(const char *name)
Cancel a timeout function.
ESPDEPRECATED("set_retry is deprecated and will be removed in 2026.8.0. Use set_timeout or set_interval instead.", "2026.2.0") void set_retry(const std uint32_t uint8_t std::function< RetryResult(uint8_t)> && f
void status_clear_warning()
static void register_controller(Controller *controller)
Register a controller to receive entity state updates.
virtual bool sync()=0
Commit pending writes to flash.
virtual ESPPreferenceObject make_preference(size_t length, uint32_t type, bool in_flash)=0
StringRef is a reference to a string owned by something else.
void trigger(const Ts &...x)
Inform the parent automation that the event has triggered.
const psk_t & get_psk() const
void register_action_response_callback(uint32_t call_id, ActionResponseCallback callback)
std::vector< std::unique_ptr< APIConnection > > clients_
void send_infrared_rf_receive_event(uint32_t device_id, uint32_t key, const std::vector< int32_t > *timings)
void on_camera_image(const std::shared_ptr< camera::CameraImage > &image) override
void set_port(uint16_t port)
void dump_config() override
void unregister_active_action_calls_for_connection(APIConnection *conn)
void handle_disconnect(APIConnection *conn)
void set_batch_delay(uint16_t batch_delay)
void set_reboot_timeout(uint32_t reboot_timeout)
void add_state_subscription_(const char *entity_id, const char *attribute, std::function< void(StringRef)> f, bool once)
void send_action_response(uint32_t action_call_id, bool success, StringRef error_message)
bool save_noise_psk(psk_t psk, bool make_active=true)
APINoiseContext noise_ctx_
void unregister_active_action_call(uint32_t action_call_id)
void send_homeassistant_action(const HomeassistantActionRequest &call)
void on_event(event::Event *obj) override
void on_update(update::UpdateEntity *obj) override
uint32_t next_action_call_id_
std::vector< PendingActionResponse > action_response_callbacks_
const std::vector< HomeAssistantStateSubscription > & get_state_subs() const
void subscribe_home_assistant_state(const char *entity_id, const char *attribute, std::function< void(StringRef)> f)
std::vector< uint8_t > shared_write_buffer_
void handle_action_response(uint32_t call_id, bool success, StringRef error_message)
std::function< void(const class ActionResponse &)> ActionResponseCallback
bool update_noise_psk_(const SavedNoisePsk &new_psk, const LogString *save_log_msg, const LogString *fail_log_msg, const psk_t &active_psk, bool make_active)
bool is_connected(bool state_subscription_only=false) const
ESPPreferenceObject noise_pref_
Trigger< std::string, std::string > client_disconnected_trigger_
std::vector< HomeAssistantStateSubscription > state_subs_
void on_zwave_proxy_request(const esphome::api::ProtoMessage &msg)
bool clear_noise_psk(bool make_active=true)
uint16_t get_port() const
std::vector< ActiveActionCall > active_action_calls_
void set_noise_psk(psk_t psk)
void get_home_assistant_state(const char *entity_id, const char *attribute, std::function< void(StringRef)> f)
float get_setup_priority() const override
std::unique_ptr< socket::Socket > socket_
uint32_t register_active_action_call(uint32_t client_call_id, APIConnection *conn)
void on_shutdown() override
void on_log(uint8_t level, const char *tag, const char *message, size_t message_len) override
static constexpr uint8_t MESSAGE_TYPE
static constexpr uint8_t ESTIMATED_SIZE
static constexpr uint8_t MESSAGE_TYPE
Base class for all binary_sensor-type classes.
virtual void add_listener(CameraListener *listener)=0
Add a listener to receive camera events.
static Camera * instance()
The singleton instance of the camera implementation.
ClimateDevice - This is the base class for all climate integrations.
Base class for all cover devices.
This class represents the communication layer between the front-end MQTT layer and the hardware outpu...
Base class for all locks.
void add_log_listener(LogListener *listener)
Register a log listener to receive log messages.
Base-class for all numbers.
value_type const & value() const
Base-class for all selects.
Base-class for all sensors.
Base class for all switches.
Base-class for all text inputs.
Base class for all valve devices.
APIServer * global_api_server
API_DISPATCH_UPDATE(binary_sensor::BinarySensor, binary_sensor) API_DISPATCH_UPDATE(cover
std::array< uint8_t, 32 > psk_t
const char * get_use_address()
Get the active network hostname.
bool is_connected()
Return whether the node is connected to the network (through wifi, eth, ...)
const float AFTER_WIFI
For components that should be initialized after WiFi is connected.
std::unique_ptr< Socket > socket_ip_loop_monitored(int type, int protocol)
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().
ESPPreferences * global_preferences
Application App
Global storage of Application pointer - only one Application can exist.
std::unique_ptr< std::string > entity_id_dynamic_storage
std::function< void(StringRef)> callback
std::unique_ptr< std::string > attribute_dynamic_storage