ESPHome 2025.12.0-dev
Loading...
Searching...
No Matches
api_server.h
Go to the documentation of this file.
1#pragma once
2
4#ifdef USE_API
5#include "api_noise_context.h"
6#include "api_pb2.h"
7#include "api_pb2_service.h"
12#include "esphome/core/log.h"
13#include "list_entities.h"
14#include "subscribe_state.h"
15#ifdef USE_API_SERVICES
16#include "user_services.h"
17#endif
18
19#include <map>
20#include <vector>
21
22namespace esphome::api {
23
24#ifdef USE_API_NOISE
27} PACKED; // NOLINT
28#endif
29
30class APIServer : public Component, public Controller {
31 public:
32 APIServer();
33 void setup() override;
34 uint16_t get_port() const;
35 float get_setup_priority() const override;
36 void loop() override;
37 void dump_config() override;
38 void on_shutdown() override;
39 bool teardown() override;
40#ifdef USE_API_PASSWORD
41 bool check_password(const uint8_t *password_data, size_t password_len) const;
42 void set_password(const std::string &password);
43#endif
44 void set_port(uint16_t port);
45 void set_reboot_timeout(uint32_t reboot_timeout);
46 void set_batch_delay(uint16_t batch_delay);
47 uint16_t get_batch_delay() const { return batch_delay_; }
48 void set_listen_backlog(uint8_t listen_backlog) { this->listen_backlog_ = listen_backlog; }
49 void set_max_connections(uint8_t max_connections) { this->max_connections_ = max_connections; }
50
51 // Get reference to shared buffer for API connections
52 std::vector<uint8_t> &get_shared_buffer_ref() { return shared_write_buffer_; }
53
54#ifdef USE_API_NOISE
55 bool save_noise_psk(psk_t psk, bool make_active = true);
56 bool clear_noise_psk(bool make_active = true);
57 void set_noise_psk(psk_t psk) { noise_ctx_->set_psk(psk); }
58 std::shared_ptr<APINoiseContext> get_noise_ctx() { return noise_ctx_; }
59#endif // USE_API_NOISE
60
62#ifdef USE_BINARY_SENSOR
64#endif
65#ifdef USE_COVER
66 void on_cover_update(cover::Cover *obj) override;
67#endif
68#ifdef USE_FAN
69 void on_fan_update(fan::Fan *obj) override;
70#endif
71#ifdef USE_LIGHT
73#endif
74#ifdef USE_SENSOR
75 void on_sensor_update(sensor::Sensor *obj) override;
76#endif
77#ifdef USE_SWITCH
78 void on_switch_update(switch_::Switch *obj) override;
79#endif
80#ifdef USE_TEXT_SENSOR
82#endif
83#ifdef USE_CLIMATE
85#endif
86#ifdef USE_NUMBER
87 void on_number_update(number::Number *obj) override;
88#endif
89#ifdef USE_DATETIME_DATE
91#endif
92#ifdef USE_DATETIME_TIME
94#endif
95#ifdef USE_DATETIME_DATETIME
97#endif
98#ifdef USE_TEXT
99 void on_text_update(text::Text *obj) override;
100#endif
101#ifdef USE_SELECT
102 void on_select_update(select::Select *obj) override;
103#endif
104#ifdef USE_LOCK
105 void on_lock_update(lock::Lock *obj) override;
106#endif
107#ifdef USE_VALVE
108 void on_valve_update(valve::Valve *obj) override;
109#endif
110#ifdef USE_MEDIA_PLAYER
112#endif
113#ifdef USE_API_HOMEASSISTANT_SERVICES
115
116#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES
117 // Action response handling
118 using ActionResponseCallback = std::function<void(const class ActionResponse &)>;
119 void register_action_response_callback(uint32_t call_id, ActionResponseCallback callback);
120 void handle_action_response(uint32_t call_id, bool success, const std::string &error_message);
121#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES_JSON
122 void handle_action_response(uint32_t call_id, bool success, const std::string &error_message,
123 const uint8_t *response_data, size_t response_data_len);
124#endif // USE_API_HOMEASSISTANT_ACTION_RESPONSES_JSON
125#endif // USE_API_HOMEASSISTANT_ACTION_RESPONSES
126#endif // USE_API_HOMEASSISTANT_SERVICES
127#ifdef USE_API_SERVICES
128 void initialize_user_services(std::initializer_list<UserServiceDescriptor *> services) {
129 this->user_services_.assign(services);
130 }
131#ifdef USE_API_CUSTOM_SERVICES
132 // Only compile push_back method when custom_services: true (external components)
133 void register_user_service(UserServiceDescriptor *descriptor) { this->user_services_.push_back(descriptor); }
134#endif
135#endif
136#ifdef USE_HOMEASSISTANT_TIME
137 void request_time();
138#endif
139
140#ifdef USE_ALARM_CONTROL_PANEL
142#endif
143#ifdef USE_EVENT
144 void on_event(event::Event *obj) override;
145#endif
146#ifdef USE_UPDATE
147 void on_update(update::UpdateEntity *obj) override;
148#endif
149#ifdef USE_ZWAVE_PROXY
151#endif
152
153 bool is_connected() const;
154
155#ifdef USE_API_HOMEASSISTANT_STATES
157 std::string entity_id;
159 std::function<void(std::string)> callback;
160 bool once;
161 };
162
163 void subscribe_home_assistant_state(std::string entity_id, optional<std::string> attribute,
164 std::function<void(std::string)> f);
165 void get_home_assistant_state(std::string entity_id, optional<std::string> attribute,
166 std::function<void(std::string)> f);
167 const std::vector<HomeAssistantStateSubscription> &get_state_subs() const;
168#endif
169#ifdef USE_API_SERVICES
170 const std::vector<UserServiceDescriptor *> &get_user_services() const { return this->user_services_; }
171#endif
172
173#ifdef USE_API_CLIENT_CONNECTED_TRIGGER
175#endif
176#ifdef USE_API_CLIENT_DISCONNECTED_TRIGGER
180#endif
181
182 protected:
184#ifdef USE_API_NOISE
185 bool update_noise_psk_(const SavedNoisePsk &new_psk, const LogString *save_log_msg, const LogString *fail_log_msg,
186 const psk_t &active_psk, bool make_active);
187#endif // USE_API_NOISE
188 // Pointers and pointer-like types first (4 bytes each)
189 std::unique_ptr<socket::Socket> socket_ = nullptr;
190#ifdef USE_API_CLIENT_CONNECTED_TRIGGER
192#endif
193#ifdef USE_API_CLIENT_DISCONNECTED_TRIGGER
195#endif
196
197 // 4-byte aligned types
198 uint32_t reboot_timeout_{300000};
199
200 // Vectors and strings (12 bytes each on 32-bit)
201 std::vector<std::unique_ptr<APIConnection>> clients_;
202#ifdef USE_API_PASSWORD
203 std::string password_;
204#endif
205 std::vector<uint8_t> shared_write_buffer_; // Shared proto write buffer for all connections
206#ifdef USE_API_HOMEASSISTANT_STATES
207 std::vector<HomeAssistantStateSubscription> state_subs_;
208#endif
209#ifdef USE_API_SERVICES
210 std::vector<UserServiceDescriptor *> user_services_;
211#endif
212#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES
217 std::vector<PendingActionResponse> action_response_callbacks_;
218#endif
219
220 // Group smaller types together
221 uint16_t port_{6053};
222 uint16_t batch_delay_{100};
223 // Connection limits - these defaults will be overridden by config values
224 // from cv.SplitDefault in __init__.py which sets platform-specific defaults
225 uint8_t listen_backlog_{4};
227 bool shutting_down_ = false;
228 // 7 bytes used, 1 byte padding
229
230#ifdef USE_API_NOISE
231 std::shared_ptr<APINoiseContext> noise_ctx_ = std::make_shared<APINoiseContext>();
233#endif // USE_API_NOISE
234};
235
236extern APIServer *global_api_server; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
237
238template<typename... Ts> class APIConnectedCondition : public Condition<Ts...> {
239 public:
240 bool check(const Ts &...x) override { return global_api_server->is_connected(); }
241};
242
243} // namespace esphome::api
244#endif
Base class for all automation conditions.
Definition automation.h:148
bool check(const Ts &...x) override
Definition api_server.h:240
void on_valve_update(valve::Valve *obj) override
uint16_t get_batch_delay() const
Definition api_server.h:47
void on_switch_update(switch_::Switch *obj) override
void register_action_response_callback(uint32_t call_id, ActionResponseCallback callback)
std::shared_ptr< APINoiseContext > get_noise_ctx()
Definition api_server.h:58
std::vector< std::unique_ptr< APIConnection > > clients_
Definition api_server.h:201
void set_password(const std::string &password)
void on_time_update(datetime::TimeEntity *obj) override
void on_cover_update(cover::Cover *obj) override
std::vector< UserServiceDescriptor * > user_services_
Definition api_server.h:210
void on_light_update(light::LightState *obj) override
void on_media_player_update(media_player::MediaPlayer *obj) override
const std::vector< UserServiceDescriptor * > & get_user_services() const
Definition api_server.h:170
void initialize_user_services(std::initializer_list< UserServiceDescriptor * > services)
Definition api_server.h:128
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)
void set_listen_backlog(uint8_t listen_backlog)
Definition api_server.h:48
Trigger< std::string, std::string > * client_connected_trigger_
Definition api_server.h:191
void register_user_service(UserServiceDescriptor *descriptor)
Definition api_server.h:133
bool save_noise_psk(psk_t psk, bool make_active=true)
void on_lock_update(lock::Lock *obj) override
void setup() override
void on_date_update(datetime::DateEntity *obj) override
void handle_action_response(uint32_t call_id, bool success, const std::string &error_message)
bool teardown() override
void on_number_update(number::Number *obj) override
void send_homeassistant_action(const HomeassistantActionRequest &call)
void on_event(event::Event *obj) override
void on_update(update::UpdateEntity *obj) override
bool check_password(const uint8_t *password_data, size_t password_len) const
std::vector< PendingActionResponse > action_response_callbacks_
Definition api_server.h:217
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:231
Trigger< std::string, std::string > * client_disconnected_trigger_
Definition api_server.h:194
std::vector< uint8_t > shared_write_buffer_
Definition api_server.h:205
void subscribe_home_assistant_state(std::string entity_id, optional< std::string > attribute, std::function< void(std::string)> f)
void on_climate_update(climate::Climate *obj) override
std::function< void(const class ActionResponse &)> ActionResponseCallback
Definition api_server.h:118
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)
void set_max_connections(uint8_t max_connections)
Definition api_server.h:49
void on_binary_sensor_update(binary_sensor::BinarySensor *obj) override
ESPPreferenceObject noise_pref_
Definition api_server.h:232
void on_fan_update(fan::Fan *obj) override
std::vector< HomeAssistantStateSubscription > state_subs_
Definition api_server.h:207
void on_zwave_proxy_request(const esphome::api::ProtoMessage &msg)
bool clear_noise_psk(bool make_active=true)
void on_select_update(select::Select *obj) override
uint16_t get_port() const
std::vector< uint8_t > & get_shared_buffer_ref()
Definition api_server.h:52
void on_text_update(text::Text *obj) override
void on_text_sensor_update(text_sensor::TextSensor *obj) override
void set_noise_psk(psk_t psk)
Definition api_server.h:57
void on_datetime_update(datetime::DateTimeEntity *obj) override
Trigger< std::string, std::string > * get_client_disconnected_trigger() const
Definition api_server.h:177
void on_sensor_update(sensor::Sensor *obj) override
float get_setup_priority() const override
std::unique_ptr< socket::Socket > socket_
Definition api_server.h:189
void on_shutdown() override
Trigger< std::string, std::string > * get_client_connected_trigger() const
Definition api_server.h:174
void on_alarm_control_panel_update(alarm_control_panel::AlarmControlPanel *obj) override
Base class for all binary_sensor-type classes.
ClimateDevice - This is the base class for all climate integrations.
Definition climate.h:178
Base class for all cover devices.
Definition cover.h:112
This class represents the communication layer between the front-end MQTT layer and the hardware outpu...
Definition light_state.h:69
Base class for all locks.
Definition lock.h:109
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
APIServer * global_api_server
struct esphome::api::SavedNoisePsk PACKED
std::array< uint8_t, 32 > psk_t
uint16_t x
Definition tt21100.cpp:5