ESPHome  2024.9.2
api_server.cpp
Go to the documentation of this file.
1 #include "api_server.h"
2 #include <cerrno>
3 #include "api_connection.h"
6 #include "esphome/core/defines.h"
7 #include "esphome/core/hal.h"
8 #include "esphome/core/log.h"
9 #include "esphome/core/util.h"
10 #include "esphome/core/version.h"
11 
12 #ifdef USE_LOGGER
14 #endif
15 
16 #include <algorithm>
17 
18 namespace esphome {
19 namespace api {
20 
21 static const char *const TAG = "api";
22 
23 // APIServer
25  ESP_LOGCONFIG(TAG, "Setting up Home Assistant API server...");
26  this->setup_controller();
27  socket_ = socket::socket_ip(SOCK_STREAM, 0);
28  if (socket_ == nullptr) {
29  ESP_LOGW(TAG, "Could not create socket.");
30  this->mark_failed();
31  return;
32  }
33  int enable = 1;
34  int err = socket_->setsockopt(SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int));
35  if (err != 0) {
36  ESP_LOGW(TAG, "Socket unable to set reuseaddr: errno %d", err);
37  // we can still continue
38  }
39  err = socket_->setblocking(false);
40  if (err != 0) {
41  ESP_LOGW(TAG, "Socket unable to set nonblocking mode: errno %d", err);
42  this->mark_failed();
43  return;
44  }
45 
46  struct sockaddr_storage server;
47 
48  socklen_t sl = socket::set_sockaddr_any((struct sockaddr *) &server, sizeof(server), this->port_);
49  if (sl == 0) {
50  ESP_LOGW(TAG, "Socket unable to set sockaddr: errno %d", errno);
51  this->mark_failed();
52  return;
53  }
54 
55  err = socket_->bind((struct sockaddr *) &server, sl);
56  if (err != 0) {
57  ESP_LOGW(TAG, "Socket unable to bind: errno %d", errno);
58  this->mark_failed();
59  return;
60  }
61 
62  err = socket_->listen(4);
63  if (err != 0) {
64  ESP_LOGW(TAG, "Socket unable to listen: errno %d", errno);
65  this->mark_failed();
66  return;
67  }
68 
69 #ifdef USE_LOGGER
70  if (logger::global_logger != nullptr) {
71  logger::global_logger->add_on_log_callback([this](int level, const char *tag, const char *message) {
72  for (auto &c : this->clients_) {
73  if (!c->remove_)
74  c->send_log_message(level, tag, message);
75  }
76  });
77  }
78 #endif
79 
80  this->last_connected_ = millis();
81 
82 #ifdef USE_ESP32_CAMERA
83  if (esp32_camera::global_esp32_camera != nullptr && !esp32_camera::global_esp32_camera->is_internal()) {
85  [this](const std::shared_ptr<esp32_camera::CameraImage> &image) {
86  for (auto &c : this->clients_) {
87  if (!c->remove_)
88  c->send_camera_state(image);
89  }
90  });
91  }
92 #endif
93 }
95  // Accept new clients
96  while (true) {
97  struct sockaddr_storage source_addr;
98  socklen_t addr_len = sizeof(source_addr);
99  auto sock = socket_->accept((struct sockaddr *) &source_addr, &addr_len);
100  if (!sock)
101  break;
102  ESP_LOGD(TAG, "Accepted %s", sock->getpeername().c_str());
103 
104  auto *conn = new APIConnection(std::move(sock), this);
105  clients_.emplace_back(conn);
106  conn->start();
107  }
108 
109  // Partition clients into remove and active
110  auto new_end = std::partition(this->clients_.begin(), this->clients_.end(),
111  [](const std::unique_ptr<APIConnection> &conn) { return !conn->remove_; });
112  // print disconnection messages
113  for (auto it = new_end; it != this->clients_.end(); ++it) {
114  this->client_disconnected_trigger_->trigger((*it)->client_info_, (*it)->client_peername_);
115  ESP_LOGV(TAG, "Removing connection to %s", (*it)->client_info_.c_str());
116  }
117  // resize vector
118  this->clients_.erase(new_end, this->clients_.end());
119 
120  for (auto &client : this->clients_) {
121  client->loop();
122  }
123 
124  if (this->reboot_timeout_ != 0) {
125  const uint32_t now = millis();
126  if (!this->is_connected()) {
127  if (now - this->last_connected_ > this->reboot_timeout_) {
128  ESP_LOGE(TAG, "No client connected to API. Rebooting...");
129  App.reboot();
130  }
131  this->status_set_warning();
132  } else {
133  this->last_connected_ = now;
134  this->status_clear_warning();
135  }
136  }
137 }
139  ESP_LOGCONFIG(TAG, "API Server:");
140  ESP_LOGCONFIG(TAG, " Address: %s:%u", network::get_use_address().c_str(), this->port_);
141 #ifdef USE_API_NOISE
142  ESP_LOGCONFIG(TAG, " Using noise encryption: YES");
143 #else
144  ESP_LOGCONFIG(TAG, " Using noise encryption: NO");
145 #endif
146 }
147 bool APIServer::uses_password() const { return !this->password_.empty(); }
148 bool APIServer::check_password(const std::string &password) const {
149  // depend only on input password length
150  const char *a = this->password_.c_str();
151  uint32_t len_a = this->password_.length();
152  const char *b = password.c_str();
153  uint32_t len_b = password.length();
154 
155  // disable optimization with volatile
156  volatile uint32_t length = len_b;
157  volatile const char *left = nullptr;
158  volatile const char *right = b;
159  uint8_t result = 0;
160 
161  if (len_a == length) {
162  left = *((volatile const char **) &a);
163  result = 0;
164  }
165  if (len_a != length) {
166  left = b;
167  result = 1;
168  }
169 
170  for (size_t i = 0; i < length; i++) {
171  result |= *left++ ^ *right++; // NOLINT
172  }
173 
174  return result == 0;
175 }
177 #ifdef USE_BINARY_SENSOR
179  if (obj->is_internal())
180  return;
181  for (auto &c : this->clients_)
182  c->send_binary_sensor_state(obj, state);
183 }
184 #endif
185 
186 #ifdef USE_COVER
188  if (obj->is_internal())
189  return;
190  for (auto &c : this->clients_)
191  c->send_cover_state(obj);
192 }
193 #endif
194 
195 #ifdef USE_FAN
197  if (obj->is_internal())
198  return;
199  for (auto &c : this->clients_)
200  c->send_fan_state(obj);
201 }
202 #endif
203 
204 #ifdef USE_LIGHT
206  if (obj->is_internal())
207  return;
208  for (auto &c : this->clients_)
209  c->send_light_state(obj);
210 }
211 #endif
212 
213 #ifdef USE_SENSOR
215  if (obj->is_internal())
216  return;
217  for (auto &c : this->clients_)
218  c->send_sensor_state(obj, state);
219 }
220 #endif
221 
222 #ifdef USE_SWITCH
224  if (obj->is_internal())
225  return;
226  for (auto &c : this->clients_)
227  c->send_switch_state(obj, state);
228 }
229 #endif
230 
231 #ifdef USE_TEXT_SENSOR
233  if (obj->is_internal())
234  return;
235  for (auto &c : this->clients_)
236  c->send_text_sensor_state(obj, state);
237 }
238 #endif
239 
240 #ifdef USE_CLIMATE
242  if (obj->is_internal())
243  return;
244  for (auto &c : this->clients_)
245  c->send_climate_state(obj);
246 }
247 #endif
248 
249 #ifdef USE_NUMBER
251  if (obj->is_internal())
252  return;
253  for (auto &c : this->clients_)
254  c->send_number_state(obj, state);
255 }
256 #endif
257 
258 #ifdef USE_DATETIME_DATE
260  if (obj->is_internal())
261  return;
262  for (auto &c : this->clients_)
263  c->send_date_state(obj);
264 }
265 #endif
266 
267 #ifdef USE_DATETIME_TIME
269  if (obj->is_internal())
270  return;
271  for (auto &c : this->clients_)
272  c->send_time_state(obj);
273 }
274 #endif
275 
276 #ifdef USE_DATETIME_DATETIME
278  if (obj->is_internal())
279  return;
280  for (auto &c : this->clients_)
281  c->send_datetime_state(obj);
282 }
283 #endif
284 
285 #ifdef USE_TEXT
286 void APIServer::on_text_update(text::Text *obj, const std::string &state) {
287  if (obj->is_internal())
288  return;
289  for (auto &c : this->clients_)
290  c->send_text_state(obj, state);
291 }
292 #endif
293 
294 #ifdef USE_SELECT
295 void APIServer::on_select_update(select::Select *obj, const std::string &state, size_t index) {
296  if (obj->is_internal())
297  return;
298  for (auto &c : this->clients_)
299  c->send_select_state(obj, state);
300 }
301 #endif
302 
303 #ifdef USE_LOCK
305  if (obj->is_internal())
306  return;
307  for (auto &c : this->clients_)
308  c->send_lock_state(obj, obj->state);
309 }
310 #endif
311 
312 #ifdef USE_VALVE
314  if (obj->is_internal())
315  return;
316  for (auto &c : this->clients_)
317  c->send_valve_state(obj);
318 }
319 #endif
320 
321 #ifdef USE_MEDIA_PLAYER
323  if (obj->is_internal())
324  return;
325  for (auto &c : this->clients_)
326  c->send_media_player_state(obj);
327 }
328 #endif
329 
330 #ifdef USE_EVENT
331 void APIServer::on_event(event::Event *obj, const std::string &event_type) {
332  for (auto &c : this->clients_)
333  c->send_event(obj, event_type);
334 }
335 #endif
336 
337 #ifdef USE_UPDATE
339  for (auto &c : this->clients_)
340  c->send_update_state(obj);
341 }
342 #endif
343 
345 void APIServer::set_port(uint16_t port) { this->port_ = port; }
346 APIServer *global_api_server = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
347 
348 void APIServer::set_password(const std::string &password) { this->password_ = password; }
350  for (auto &client : this->clients_) {
351  client->send_homeassistant_service_call(call);
352  }
353 }
354 
355 APIServer::APIServer() { global_api_server = this; }
357  std::function<void(std::string)> f) {
359  .entity_id = std::move(entity_id),
360  .attribute = std::move(attribute),
361  .callback = std::move(f),
362  .once = false,
363  });
364 }
365 void APIServer::get_home_assistant_state(std::string entity_id, optional<std::string> attribute,
366  std::function<void(std::string)> f) {
368  .entity_id = std::move(entity_id),
369  .attribute = std::move(attribute),
370  .callback = std::move(f),
371  .once = true,
372  });
373 };
374 const std::vector<APIServer::HomeAssistantStateSubscription> &APIServer::get_state_subs() const {
375  return this->state_subs_;
376 }
377 uint16_t APIServer::get_port() const { return this->port_; }
378 void APIServer::set_reboot_timeout(uint32_t reboot_timeout) { this->reboot_timeout_ = reboot_timeout; }
379 #ifdef USE_HOMEASSISTANT_TIME
381  for (auto &client : this->clients_) {
382  if (!client->remove_ && client->is_authenticated())
383  client->send_time_request();
384  }
385 }
386 #endif
387 bool APIServer::is_connected() const { return !this->clients_.empty(); }
389  for (auto &c : this->clients_) {
390  c->send_disconnect_request(DisconnectRequest());
391  }
392  delay(10);
393 }
394 
395 #ifdef USE_ALARM_CONTROL_PANEL
397  if (obj->is_internal())
398  return;
399  for (auto &c : this->clients_)
400  c->send_alarm_control_panel_state(obj);
401 }
402 #endif
403 
404 } // namespace api
405 } // namespace esphome
Base class for all switches.
Definition: switch.h:39
std::unique_ptr< Socket > socket_ip(int type, int protocol)
Create a socket in the newest available IP domain (IPv6 or IPv4) of the given type and protocol...
Definition: socket.cpp:13
void handle_disconnect(APIConnection *conn)
Definition: api_server.cpp:176
This class represents the communication layer between the front-end MQTT layer and the hardware outpu...
Definition: light_state.h:34
bool is_connected() const
Definition: api_server.cpp:387
void add_on_log_callback(std::function< void(int, const char *, const char *)> &&callback)
Register a callback that will be called for every log message sent.
Definition: logger.cpp:178
Base class for all cover devices.
Definition: cover.h:111
void on_update(update::UpdateEntity *obj) override
Definition: api_server.cpp:338
const float AFTER_WIFI
For components that should be initialized after WiFi is connected.
Definition: component.cpp:26
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:51
std::string get_use_address()
Get the active network hostname.
Definition: util.cpp:52
void status_set_warning(const char *message="unspecified")
Definition: component.cpp:151
LockState state
The current reported state of the lock.
Definition: lock.h:122
void on_media_player_update(media_player::MediaPlayer *obj) override
Definition: api_server.cpp:322
void on_select_update(select::Select *obj, const std::string &state, size_t index) override
Definition: api_server.cpp:295
bool check_password(const std::string &password) const
Definition: api_server.cpp:148
std::vector< HomeAssistantStateSubscription > state_subs_
Definition: api_server.h:137
void on_light_update(light::LightState *obj) override
Definition: api_server.cpp:205
uint32_t socklen_t
Definition: headers.h:97
void on_lock_update(lock::Lock *obj) override
Definition: api_server.cpp:304
void send_homeassistant_service_call(const HomeassistantServiceResponse &call)
Definition: api_server.cpp:349
void add_image_callback(std::function< void(std::shared_ptr< CameraImage >)> &&callback)
void on_cover_update(cover::Cover *obj) override
Definition: api_server.cpp:187
void on_binary_sensor_update(binary_sensor::BinarySensor *obj, bool state) override
Definition: api_server.cpp:178
Base-class for all text inputs.
Definition: text.h:24
void loop() override
Definition: api_server.cpp:94
Trigger< std::string, std::string > * client_disconnected_trigger_
Definition: api_server.h:140
uint32_t IRAM_ATTR HOT millis()
Definition: core.cpp:25
void on_fan_update(fan::Fan *obj) override
Definition: api_server.cpp:196
void trigger(Ts... x)
Inform the parent automation that the event has triggered.
Definition: automation.h:95
void setup() override
Definition: api_server.cpp:24
void on_alarm_control_panel_update(alarm_control_panel::AlarmControlPanel *obj) override
Definition: api_server.cpp:396
Logger * global_logger
Definition: logger.cpp:198
void on_switch_update(switch_::Switch *obj, bool state) override
Definition: api_server.cpp:223
void dump_config() override
Definition: api_server.cpp:138
void on_date_update(datetime::DateEntity *obj) override
Definition: api_server.cpp:259
void on_datetime_update(datetime::DateTimeEntity *obj) override
Definition: api_server.cpp:277
ESP32Camera * global_esp32_camera
void on_text_update(text::Text *obj, const std::string &state) override
Definition: api_server.cpp:286
void on_number_update(number::Number *obj, float state) override
Definition: api_server.cpp:250
Base-class for all numbers.
Definition: number.h:39
void status_clear_warning()
Definition: component.cpp:166
void set_reboot_timeout(uint32_t reboot_timeout)
Definition: api_server.cpp:378
void on_climate_update(climate::Climate *obj) override
Definition: api_server.cpp:241
bool is_internal() const
Definition: entity_base.cpp:22
void on_text_sensor_update(text_sensor::TextSensor *obj, const std::string &state) override
Definition: api_server.cpp:232
Application App
Global storage of Application pointer - only one Application can exist.
void set_port(uint16_t port)
Definition: api_server.cpp:345
const std::vector< HomeAssistantStateSubscription > & get_state_subs() const
Definition: api_server.cpp:374
virtual void mark_failed()
Mark this component as failed.
Definition: component.cpp:118
void on_sensor_update(sensor::Sensor *obj, float state) override
Definition: api_server.cpp:214
void setup_controller(bool include_internal=false)
Definition: controller.cpp:7
uint16_t length
Definition: tt21100.cpp:12
void on_event(event::Event *obj, const std::string &event_type) override
Definition: api_server.cpp:331
bool uses_password() const
Definition: api_server.cpp:147
Base-class for all selects.
Definition: select.h:31
std::vector< std::unique_ptr< APIConnection > > clients_
Definition: api_server.h:135
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7
Base class for all valve devices.
Definition: valve.h:105
Base class for all binary_sensor-type classes.
Definition: binary_sensor.h:37
float get_setup_priority() const override
Definition: api_server.cpp:344
void subscribe_home_assistant_state(std::string entity_id, optional< std::string > attribute, std::function< void(std::string)> f)
Definition: api_server.cpp:356
void on_shutdown() override
Definition: api_server.cpp:388
Base-class for all sensors.
Definition: sensor.h:57
void get_home_assistant_state(std::string entity_id, optional< std::string > attribute, std::function< void(std::string)> f)
Definition: api_server.cpp:365
uint16_t get_port() const
Definition: api_server.cpp:377
void on_valve_update(valve::Valve *obj) override
Definition: api_server.cpp:313
void set_password(const std::string &password)
Definition: api_server.cpp:348
APIServer * global_api_server
Definition: api_server.cpp:346
std::unique_ptr< socket::Socket > socket_
Definition: api_server.h:131
Base class for all locks.
Definition: lock.h:103
ClimateDevice - This is the base class for all climate integrations.
Definition: climate.h:168
bool state
Definition: fan.h:34
void IRAM_ATTR HOT delay(uint32_t ms)
Definition: core.cpp:26
void on_time_update(datetime::TimeEntity *obj) override
Definition: api_server.cpp:268