13#ifdef USE_API_HOMEASSISTANT_SERVICES
26static const char *
const TAG =
"api";
32static constexpr uint32_t NOISE_PSK_PREF_HASH = 88491486UL;
35#if defined(USE_API_NOISE) && defined(USE_OTA_ENCRYPTION_PROVISIONED)
38#ifdef USE_PREFERENCE_KEY_LOOKUP
57 ESP_LOGW(TAG,
"Socket %s: errno %d", LOG_STR_ARG(msg), errno);
59#ifdef USE_API_OUTGOING_CONNECTION
72#ifndef USE_API_NOISE_PSK_FROM_YAML
75 ESP_LOGD(TAG,
"Loaded saved Noise PSK");
83 this, [](
void *self, uint8_t level,
const char *tag,
const char *
message,
size_t message_len) {
97#if defined(USE_PROVISIONING) && defined(USE_API_NOISE)
113 if (!c->send_message(req)) {
114 API_LOG_MSG_DROPPED(TAG,
"Disconnect request");
125#ifdef USE_API_OUTGOING_CONNECTION
132 if (this->
socket_ ==
nullptr) {
137 int err = this->
socket_->
setsockopt(SOL_SOCKET, SO_REUSEADDR, &enable,
sizeof(
int));
139 ESP_LOGW(TAG,
"Socket reuseaddr: errno %d", errno);
171 this->accept_new_connections_();
175#ifdef USE_NOISE_SPARE_EPHEMERAL
181#ifdef USE_API_OUTGOING_CONNECTION
195 ESP_LOGE(TAG,
"No clients; rebooting");
206 client->on_fatal_error();
207 client->log_client_(ESPHOME_LOG_LEVEL_WARN, LOG_STR(
"Network down; disconnect"));
212 uint8_t client_index = 0;
214 auto &client = this->
clients_[client_index];
217 if (!client->flags_.remove) {
222 if (client->flags_.remove) {
224 this->remove_client_(client_index);
231#ifdef USE_NOISE_SPARE_EPHEMERAL
236 if (client->is_still_connecting(now)) {
244void APIServer::remove_client_(uint8_t client_index) {
245 auto &client = this->
clients_[client_index];
247#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES
250 ESP_LOGV(TAG,
"Remove connection %s", client->get_name());
252#ifdef USE_API_CLIENT_DISCONNECTED_TRIGGER
254 char peername_buf[socket::SOCKADDR_STR_LEN];
255 std::string client_name(client->get_name());
256 std::string client_peername(client->get_peername_to(peername_buf));
260 const bool was_authenticated = client->is_authenticated();
261#ifdef USE_API_OUTGOING_CONNECTION
262 if (client->flags_.outgoing_connection_target) {
269 client->helper_->close();
274 if (client_index < last_index) {
290 if (was_authenticated) {
297#ifdef USE_API_CLIENT_DISCONNECTED_TRIGGER
312 char peername[socket::SOCKADDR_STR_LEN];
313 sock->getpeername_to(peername);
317 ESP_LOGW(TAG,
"Max connections (%d), rejecting %s", MAX_API_CONNECTIONS, peername);
323 ESP_LOGD(TAG,
"Accept %s", peername);
343#ifdef USE_API_OUTGOING_CONNECTION
350 ESP_LOGW(TAG,
"Dropping outgoing connection (%s)",
351 at_limit ? LOG_STR_LITERAL(
"max connections") : LOG_STR_LITERAL(
"no key"));
356 conn->mark_outgoing();
367 char addr_buf[network::USE_ADDRESS_BUFFER_SIZE];
371 " Listen backlog: %u\n"
372 " Max connections: %u",
377 ESP_LOGCONFIG(TAG,
" Supports encryption: YES");
380 ESP_LOGCONFIG(TAG,
" Noise encryption: NO");
382#ifdef USE_API_OUTGOING_CONNECTION
390#define API_DISPATCH_UPDATE(entity_type, entity_name) \
391 void APIServer::on_##entity_name##_update(entity_type *obj) { \
392 if (obj->is_internal()) \
394 for (auto &c : this->active_clients()) { \
395 if (c->flags_.state_subscription) \
396 c->send_##entity_name##_state(obj); \
400#ifdef USE_BINARY_SENSOR
424#ifdef USE_TEXT_SENSOR
436#ifdef USE_DATETIME_DATE
440#ifdef USE_DATETIME_TIME
444#ifdef USE_DATETIME_DATETIME
464#ifdef USE_MEDIA_PLAYER
468#ifdef USE_WATER_HEATER
477 if (c->flags_.state_subscription)
489 if (c->flags_.state_subscription)
490 c->send_update_state(obj);
495#ifdef USE_ZWAVE_PROXY
500 if (!c->send_message(msg)) {
501 API_LOG_MSG_DROPPED(TAG,
"Home ID notification");
507#ifdef USE_SERIAL_PROXY_USB_IDENTITY
510 if (c->flags_.serial_proxy_identity_subscription)
511 c->send_serial_proxy_identity(msg);
518 const std::vector<int32_t> *timings) {
524 resp.timings = timings;
527 c->send_infrared_rf_receive_event(resp);
532#ifdef USE_ALARM_CONTROL_PANEL
536#ifdef USE_API_HOMEASSISTANT_SERVICES
538 bool has_subscriber =
false;
540 has_subscriber |= client->send_homeassistant_action(
call);
542 if (!has_subscriber) {
546 ESP_LOGW(TAG,
"Home Assistant %s '%.*s' dropped; %s",
547 call.is_event ? LOG_STR_LITERAL(
"event") : LOG_STR_LITERAL(
"action"),
548 static_cast<int>(
call.service.size()),
call.service.empty() ?
"" :
call.service.c_str(),
549 this->is_connected() ? LOG_STR_LITERAL(
"client has not subscribed to actions (yet)")
550 : LOG_STR_LITERAL(
"no client connected"));
553#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES
560 if (it->call_id == call_id) {
561 auto callback = std::move(it->callback);
569#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES_JSON
571 const uint8_t *response_data,
size_t response_data_len) {
573 if (it->call_id == call_id) {
574 auto callback = std::move(it->callback);
576 ActionResponse response(success, error_message, response_data, response_data_len);
586#ifdef USE_API_HOMEASSISTANT_STATES
589 std::function<
void(
StringRef)> &&f,
bool once) {
591 .entity_id = entity_id, .attribute = attribute, .callback = std::move(f), .once = once,
598 std::function<
void(
StringRef)> &&f,
bool once) {
604 if (attribute.has_value()) {
640 std::function<
void(
const std::string &)> &&f,
bool once) {
649 std::function<
void(
const std::string &)> &&f) {
654 std::function<
void(
const std::string &)> &&f) {
664#ifndef USE_API_NOISE_PSK_FROM_YAML
666 const LogString *fail_log_msg,
bool make_active) {
668 ESP_LOGW(TAG,
"%s", LOG_STR_ARG(fail_log_msg));
673 ESP_LOGW(TAG,
"Failed to sync preferences");
676 ESP_LOGD(TAG,
"%s", LOG_STR_ARG(save_log_msg));
682 ESP_LOGW(TAG,
"Failed to load saved PSK for activation");
685 ESP_LOGW(TAG,
"Disconnecting all clients to reset PSK");
688 if (!c->send_message(req)) {
689 API_LOG_MSG_DROPPED(TAG,
"Disconnect request");
692 c->flags_.next_close =
true;
713 ESP_LOGW(TAG,
"New PSK matches old");
718 bool result = this->
update_noise_psk_(new_saved_psk, LOG_STR(
"Noise PSK saved"), LOG_STR(
"Failed to save Noise PSK"),
720#ifdef USE_PROVISIONING
731 bool result = this->
update_noise_psk_(empty_psk, LOG_STR(
"Noise PSK cleared"), LOG_STR(
"Failed to clear Noise PSK"),
733#ifdef USE_PROVISIONING
745#ifdef USE_HOMEASSISTANT_TIME
748 if (!client->flags_.remove && client->is_authenticated()) {
749 client->send_time_request();
758 if (this->
clients_[i]->flags_.state_subscription) {
774 if (!c->flags_.remove && c->get_log_subscription_level() >= level)
775 c->try_send_log_message(level, tag,
message, message_len);
783 if (!c->flags_.remove)
784 c->set_camera_state(image);
794#ifdef USE_API_OUTGOING_CONNECTION
804 if (!c->send_message(req)) {
823#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES
826#ifndef USE_API_ACTION_CALL_TIMEOUT_MS
827#define USE_API_ACTION_CALL_TIMEOUT_MS 30000
840 this->
set_timeout(action_call_id, USE_API_ACTION_CALL_TIMEOUT_MS, [
this, action_call_id]() {
841 ESP_LOGD(TAG,
"Action call %" PRIu32
" timed out", action_call_id);
845 return action_call_id;
880 if (
call.action_call_id == action_call_id) {
881 call.connection->send_execute_service_response(
call.client_call_id, success, error_message);
885 ESP_LOGW(TAG,
"Cannot send response: no active call found for action_call_id %" PRIu32, action_call_id);
887#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES_JSON
889 const uint8_t *response_data,
size_t response_data_len) {
891 if (
call.action_call_id == action_call_id) {
892 call.connection->send_execute_service_response(
call.client_call_id, success, error_message, response_data,
897 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()
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.
void refill_spare_ephemeral_()
void on_log(uint8_t level, const char *tag, const char *message, size_t message_len)
bool is_connected_with_state_subscription() const
OutgoingConnectionManager outgoing_conn_
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 on_update(update::UpdateEntity *obj)
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)
bool at_client_limit_() const
void on_camera_image(const std::shared_ptr< camera::CameraImage > &image) override
void socket_failed_(const LogString *msg)
Log the failure, drop the listen socket, and mark the component failed unless this build can still di...
bool load_and_apply_noise_psk_()
void dump_config() override
void unregister_active_action_calls_for_connection(APIConnection *conn)
void handle_disconnect(APIConnection *conn)
void send_action_response(uint32_t action_call_id, bool success, StringRef error_message)
uint8_t api_connection_count_
void unregister_active_action_call(uint32_t action_call_id)
void send_homeassistant_action(const HomeassistantActionRequest &call)
socket::ListenSocket * socket_
uint32_t next_action_call_id_
std::vector< PendingActionResponse > action_response_callbacks_
const std::vector< HomeAssistantStateSubscription > & get_state_subs() const
void send_serial_proxy_identity(const SerialProxyIdentity &msg)
Tell every subscribed client that a serial proxy port's identity changed.
uint8_t provisioning_source_
uint8_t outgoing_target_count_
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
void on_event(event::Event *obj)
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
void on_outgoing_target_client(APIConnection *conn)
bool save_noise_psk(noise::psk_t psk, bool make_active=true)
APIConnection * add_client_(std::unique_ptr< socket::Socket > sock)
Takes the socket into a new connection and starts it; callers must have checked at_client_limit_() fi...
std::vector< ActiveActionCall > active_action_calls_
APIConnection * add_outgoing_client_(std::unique_ptr< socket::Socket > sock)
uint32_t register_active_action_call(uint32_t client_call_id, APIConnection *conn)
noise::NoiseContext noise_ctx_
void on_shutdown() override
void on_zwave_proxy_request(const ZWaveProxyRequest &msg)
static constexpr uint16_t MESSAGE_TYPE
static constexpr uint8_t ESTIMATED_SIZE
enums::DisconnectReason reason
void on_client_removed(APIConnection *conn, bool was_authenticated)
Clears the dialed-connection gate; dying unauthenticated escalates the backoff.
void loop(APIServer *server)
void on_target_client(APIConnection *conn)
A key-verified client declared itself a dial-back target; last one wins.
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.
void set_psk(const uint8_t *psk)
psk points at 32 bytes that outlive the context (PROGMEM or caller owned RAM); nullptr means no key.
static bool is_all_zeros(const psk_t &psk)
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
std::vector< uint8_t > & out
@ DISCONNECT_REASON_PROVISIONING_CLOSED
APIServer * global_api_server
API_DISPATCH_UPDATE(binary_sensor::BinarySensor, binary_sensor) API_DISPATCH_UPDATE(cover
bool load_saved_noise_psk(noise::psk_t &out)
One-shot read of the provisioned key for a boot without an api server (safe mode); false when there i...
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.
std::array< uint8_t, 32 > psk_t
bool has_spare_ephemeral()
void prepare_spare_ephemeral()
Fill the slot; blocks for the base point multiply.
ProvisioningManager * global_provisioning_manager
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 load_from_key(uint32_t, uint8_t *, size_t)
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