14#ifdef USE_API_HOMEASSISTANT_SERVICES
27static const char *
const TAG =
"api";
35 ESP_LOGW(TAG,
"Socket %s: errno %d", LOG_STR_ARG(msg), errno);
48#ifndef USE_API_NOISE_PSK_FROM_YAML
51 ESP_LOGD(TAG,
"Loaded saved Noise PSK");
62 int err = this->
socket_->
setsockopt(SOL_SOCKET, SO_REUSEADDR, &enable,
sizeof(
int));
64 ESP_LOGW(TAG,
"Socket reuseaddr: errno %d", errno);
96 this, [](
void *self, uint8_t level,
const char *
tag,
const char *
message,
size_t message_len) {
110#if defined(USE_PROVISIONING) && defined(USE_API_NOISE)
126 if (!c->send_message(req)) {
127 API_LOG_MSG_DROPPED(TAG,
"Disconnect request");
143 this->accept_new_connections_();
154 ESP_LOGE(TAG,
"No clients; rebooting");
166 client->on_fatal_error();
167 client->log_client_(ESPHOME_LOG_LEVEL_WARN, LOG_STR(
"Network down; disconnect"));
172 uint8_t client_index = 0;
174 auto &client = this->
clients_[client_index];
177 if (!client->flags_.remove) {
182 if (client->flags_.remove) {
184 this->remove_client_(client_index);
191void APIServer::remove_client_(uint8_t client_index) {
192 auto &client = this->
clients_[client_index];
194#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES
197 ESP_LOGV(TAG,
"Remove connection %s", client->get_name());
199#ifdef USE_API_CLIENT_DISCONNECTED_TRIGGER
201 char peername_buf[socket::SOCKADDR_STR_LEN];
202 std::string client_name(client->get_name());
203 std::string client_peername(client->get_peername_to(peername_buf));
207 client->helper_->close();
212 if (client_index < last_index) {
229#ifdef USE_API_CLIENT_DISCONNECTED_TRIGGER
244 char peername[socket::SOCKADDR_STR_LEN];
245 sock->getpeername_to(peername);
249 ESP_LOGW(TAG,
"Max connections (%d), rejecting %s", MAX_API_CONNECTIONS, peername);
255 ESP_LOGD(TAG,
"Accept %s", peername);
270 char addr_buf[network::USE_ADDRESS_BUFFER_SIZE];
274 " Listen backlog: %u\n"
275 " Max connections: %u",
280 ESP_LOGCONFIG(TAG,
" Supports encryption: YES");
283 ESP_LOGCONFIG(TAG,
" Noise encryption: NO");
290#define API_DISPATCH_UPDATE(entity_type, entity_name) \
291 void APIServer::on_##entity_name##_update(entity_type *obj) { \
292 if (obj->is_internal()) \
294 for (auto &c : this->active_clients()) { \
295 if (c->flags_.state_subscription) \
296 c->send_##entity_name##_state(obj); \
300#ifdef USE_BINARY_SENSOR
324#ifdef USE_TEXT_SENSOR
336#ifdef USE_DATETIME_DATE
340#ifdef USE_DATETIME_TIME
344#ifdef USE_DATETIME_DATETIME
364#ifdef USE_MEDIA_PLAYER
368#ifdef USE_WATER_HEATER
377 if (c->flags_.state_subscription)
389 if (c->flags_.state_subscription)
390 c->send_update_state(obj);
395#ifdef USE_ZWAVE_PROXY
400 if (!c->send_message(msg)) {
401 API_LOG_MSG_DROPPED(TAG,
"Home ID notification");
407#if defined(USE_IR_RF) || defined(USE_RADIO_FREQUENCY)
409 const std::vector<int32_t> *timings) {
415 resp.timings = timings;
418 c->send_infrared_rf_receive_event(resp);
422#ifdef USE_ALARM_CONTROL_PANEL
432#ifdef USE_API_HOMEASSISTANT_SERVICES
434 bool has_subscriber =
false;
436 has_subscriber |= client->send_homeassistant_action(
call);
438 if (!has_subscriber) {
442 ESP_LOGW(TAG,
"Home Assistant %s '%s' dropped; %s",
call.is_event ?
"event" :
"action",
call.service.c_str(),
443 this->is_connected() ?
"client has not subscribed to actions (yet)" :
"no client connected");
446#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES
453 if (it->call_id == call_id) {
454 auto callback = std::move(it->callback);
462#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES_JSON
464 const uint8_t *response_data,
size_t response_data_len) {
466 if (it->call_id == call_id) {
467 auto callback = std::move(it->callback);
469 ActionResponse response(success, error_message, response_data, response_data_len);
479#ifdef USE_API_HOMEASSISTANT_STATES
482 std::function<
void(
StringRef)> &&f,
bool once) {
484 .entity_id = entity_id, .attribute = attribute, .callback = std::move(f), .once = once,
491 std::function<
void(
StringRef)> &&f,
bool once) {
497 if (attribute.has_value()) {
533 std::function<
void(
const std::string &)> &&f,
bool once) {
542 std::function<
void(
const std::string &)> &&f) {
547 std::function<
void(
const std::string &)> &&f) {
562 const LogString *fail_log_msg,
bool make_active) {
564 ESP_LOGW(TAG,
"%s", LOG_STR_ARG(fail_log_msg));
569 ESP_LOGW(TAG,
"Failed to sync preferences");
572 ESP_LOGD(TAG,
"%s", LOG_STR_ARG(save_log_msg));
578 ESP_LOGW(TAG,
"Failed to load saved PSK for activation");
581 ESP_LOGW(TAG,
"Disconnecting all clients to reset PSK");
584 if (!c->send_message(req)) {
585 API_LOG_MSG_DROPPED(TAG,
"Disconnect request");
602#ifdef USE_API_NOISE_PSK_FROM_YAML
605 ESP_LOGW(TAG,
"Key set in YAML");
609 if (std::equal(old_psk.begin(), old_psk.end(), psk.begin())) {
610 ESP_LOGW(TAG,
"New PSK matches old");
615 bool result = this->
update_noise_psk_(new_saved_psk, LOG_STR(
"Noise PSK saved"), LOG_STR(
"Failed to save Noise PSK"),
617#ifdef USE_PROVISIONING
628#ifdef USE_API_NOISE_PSK_FROM_YAML
631 ESP_LOGW(TAG,
"Key set in YAML");
635 bool result = this->
update_noise_psk_(empty_psk, LOG_STR(
"Noise PSK cleared"), LOG_STR(
"Failed to clear Noise PSK"),
637#ifdef USE_PROVISIONING
649#ifdef USE_HOMEASSISTANT_TIME
652 if (!client->flags_.remove && client->is_authenticated()) {
653 client->send_time_request();
662 if (this->
clients_[i]->flags_.state_subscription) {
678 if (!c->flags_.remove && c->get_log_subscription_level() >= level)
679 c->try_send_log_message(level,
tag,
message, message_len);
687 if (!c->flags_.remove)
688 c->set_camera_state(image);
705 if (!c->send_message(req)) {
724#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES
727#ifndef USE_API_ACTION_CALL_TIMEOUT_MS
728#define USE_API_ACTION_CALL_TIMEOUT_MS 30000
741 this->
set_timeout(action_call_id, USE_API_ACTION_CALL_TIMEOUT_MS, [
this, action_call_id]() {
742 ESP_LOGD(TAG,
"Action call %" PRIu32
" timed out", action_call_id);
746 return action_call_id;
781 if (
call.action_call_id == action_call_id) {
782 call.connection->send_execute_service_response(
call.client_call_id, success, error_message);
786 ESP_LOGW(TAG,
"Cannot send response: no active call found for action_call_id %" PRIu32, action_call_id);
788#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES_JSON
790 const uint8_t *response_data,
size_t response_data_len) {
792 if (
call.action_call_id == action_call_id) {
793 call.connection->send_execute_service_response(
call.client_call_id, success, error_message, response_data,
798 ESP_LOGW(TAG,
"Cannot send response: no active call found for action_call_id %" PRIu32, 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.
void mark_failed()
Mark this component as failed.
void status_set_warning()
bool cancel_timeout(const char *name)
Cancel a timeout function.
void set_timeout(const char *name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a const char* name.
void status_clear_warning()
static void register_controller(Controller *controller)
Register a controller to receive entity state updates.
StringRef is a reference to a string owned by something else.
void trigger(const Ts &...x) ESPHOME_ALWAYS_INLINE
Inform the parent automation that the event has triggered.
const psk_t & get_psk() const
void on_log(uint8_t level, const char *tag, const char *message, size_t message_len)
bool is_connected_with_state_subscription() const
std::array< APIConnectionPtr, MAX_API_CONNECTIONS > clients_
void register_action_response_callback(uint32_t call_id, ActionResponseCallback callback)
void send_infrared_rf_receive_event(uint32_t device_id, uint32_t key, const std::vector< int32_t > *timings)
void add_state_subscription_(const char *entity_id, const char *attribute, std::function< void(StringRef)> &&f, bool once)
void get_home_assistant_state(const char *entity_id, const char *attribute, std::function< void(StringRef)> &&f)
void on_camera_image(const std::shared_ptr< camera::CameraImage > &image) override
void socket_failed_(const LogString *msg)
bool load_and_apply_noise_psk_()
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 send_action_response(uint32_t action_call_id, bool success, StringRef error_message)
bool save_noise_psk(psk_t psk, bool make_active=true)
uint8_t api_connection_count_
APINoiseContext noise_ctx_
void unregister_active_action_call(uint32_t action_call_id)
void send_homeassistant_action(const HomeassistantActionRequest &call)
socket::ListenSocket * socket_
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
uint8_t provisioning_source_
void subscribe_home_assistant_state(const char *entity_id, const char *attribute, std::function< void(StringRef)> &&f)
void handle_action_response(uint32_t call_id, bool success, StringRef error_message)
std::function< void(const class ActionResponse &)> ActionResponseCallback
bool provisioning_pending_() const
bool update_noise_psk_(const SavedNoisePsk &new_psk, const LogString *save_log_msg, const LogString *fail_log_msg, bool make_active)
ESPPreferenceObject noise_pref_
Trigger< std::string, std::string > client_disconnected_trigger_
std::vector< HomeAssistantStateSubscription > state_subs_
bool clear_noise_psk(bool make_active=true)
ActiveClientsView active_clients() const
uint16_t get_port() const
std::vector< ActiveActionCall > active_action_calls_
void set_noise_psk(psk_t psk)
float get_setup_priority() const override
uint32_t register_active_action_call(uint32_t client_call_id, APIConnection *conn)
void on_shutdown() override
void on_zwave_proxy_request(const ZWaveProxyRequest &msg)
static constexpr uint8_t MESSAGE_TYPE
static constexpr uint8_t ESTIMATED_SIZE
enums::DisconnectReason reason
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_callback(void *instance, void(*fn)(void *, uint8_t, const char *, const char *, size_t))
Register a log callback to receive log messages.
Base-class for all numbers.
void add_on_closed_callback(F &&callback)
uint8_t register_source()
void set_source_provisioned(uint8_t source, bool provisioned)
Base-class for all selects.
Base-class for all sensors.
int setblocking(bool blocking)
bool ready() const
Check if the socket has buffered data ready to read.
int bind(const struct sockaddr *addr, socklen_t addrlen)
int setsockopt(int level, int optname, const void *optval, socklen_t optlen)
std::unique_ptr< BSDSocketImpl > accept_loop_monitored(struct sockaddr *addr, socklen_t *addrlen)
Base class for all switches.
Base-class for all text inputs.
Base class for all valve devices.
struct @66::@67 __attribute__
Wake the main loop task from an ISR. ISR-safe.
const LogString * message
@ DISCONNECT_REASON_PROVISIONING_CLOSED
APIServer * global_api_server
API_DISPATCH_UPDATE(binary_sensor::BinarySensor, binary_sensor) API_DISPATCH_UPDATE(cover
std::array< uint8_t, 32 > psk_t
ESPHOME_ALWAYS_INLINE bool is_connected()
Return whether the node is connected to the network (through wifi, eth, ...)
const char * get_use_address_to(std::span< char, USE_ADDRESS_BUFFER_SIZE > buf)
Get the active network address for logging.
ProvisioningManager * global_provisioning_manager
constexpr float AFTER_WIFI
For components that should be initialized after WiFi is connected.
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().
std::unique_ptr< ListenSocket > socket_ip_loop_monitored(int type, int protocol)
ESPPreferences * global_preferences
Application App
Global storage of Application pointer - only one Application can exist.
ESPPreferenceObject make_preference(size_t, uint32_t, bool)
bool sync()
Commit pending writes to flash.
std::unique_ptr< std::string > entity_id_dynamic_storage
std::function< void(StringRef)> callback
std::unique_ptr< std::string > attribute_dynamic_storage