ESPHome  2024.4.0
api_connection.cpp
Go to the documentation of this file.
1 #include "api_connection.h"
2 #include <cerrno>
3 #include <cinttypes>
4 #include <utility>
7 #include "esphome/core/hal.h"
8 #include "esphome/core/log.h"
9 #include "esphome/core/version.h"
10 
11 #ifdef USE_DEEP_SLEEP
13 #endif
14 #ifdef USE_HOMEASSISTANT_TIME
16 #endif
17 #ifdef USE_BLUETOOTH_PROXY
19 #endif
20 #ifdef USE_VOICE_ASSISTANT
22 #endif
23 
24 namespace esphome {
25 namespace api {
26 
27 static const char *const TAG = "api.connection";
28 static const int ESP32_CAMERA_STOP_STREAM = 5000;
29 
30 APIConnection::APIConnection(std::unique_ptr<socket::Socket> sock, APIServer *parent)
31  : parent_(parent), initial_state_iterator_(this), list_entities_iterator_(this) {
32  this->proto_write_buffer_.reserve(64);
33 
34 #if defined(USE_API_PLAINTEXT)
35  this->helper_ = std::unique_ptr<APIFrameHelper>{new APIPlaintextFrameHelper(std::move(sock))};
36 #elif defined(USE_API_NOISE)
37  this->helper_ = std::unique_ptr<APIFrameHelper>{new APINoiseFrameHelper(std::move(sock), parent->get_noise_ctx())};
38 #else
39 #error "No frame helper defined"
40 #endif
41 }
43  this->last_traffic_ = millis();
44 
45  APIError err = this->helper_->init();
46  if (err != APIError::OK) {
48  ESP_LOGW(TAG, "%s: Helper init failed: %s errno=%d", this->client_combined_info_.c_str(), api_error_to_str(err),
49  errno);
50  return;
51  }
52  this->client_info_ = helper_->getpeername();
53  this->client_peername_ = this->client_info_;
54  this->helper_->set_log_info(this->client_info_);
55 }
56 
58 #ifdef USE_BLUETOOTH_PROXY
59  if (bluetooth_proxy::global_bluetooth_proxy->get_api_connection() == this) {
61  }
62 #endif
63 #ifdef USE_VOICE_ASSISTANT
64  if (voice_assistant::global_voice_assistant->get_api_connection() == this) {
66  }
67 #endif
68 }
69 
71  if (this->remove_)
72  return;
73 
74  if (!network::is_connected()) {
75  // when network is disconnected force disconnect immediately
76  // don't wait for timeout
77  this->on_fatal_error();
78  ESP_LOGW(TAG, "%s: Network unavailable, disconnecting", this->client_combined_info_.c_str());
79  return;
80  }
81  if (this->next_close_) {
82  // requested a disconnect
83  this->helper_->close();
84  this->remove_ = true;
85  return;
86  }
87 
88  APIError err = this->helper_->loop();
89  if (err != APIError::OK) {
91  ESP_LOGW(TAG, "%s: Socket operation failed: %s errno=%d", this->client_combined_info_.c_str(),
92  api_error_to_str(err), errno);
93  return;
94  }
95  ReadPacketBuffer buffer;
96  err = this->helper_->read_packet(&buffer);
97  if (err == APIError::WOULD_BLOCK) {
98  // pass
99  } else if (err != APIError::OK) {
100  on_fatal_error();
101  if (err == APIError::SOCKET_READ_FAILED && errno == ECONNRESET) {
102  ESP_LOGW(TAG, "%s: Connection reset", this->client_combined_info_.c_str());
103  } else if (err == APIError::CONNECTION_CLOSED) {
104  ESP_LOGW(TAG, "%s: Connection closed", this->client_combined_info_.c_str());
105  } else {
106  ESP_LOGW(TAG, "%s: Reading failed: %s errno=%d", this->client_combined_info_.c_str(), api_error_to_str(err),
107  errno);
108  }
109  return;
110  } else {
111  this->last_traffic_ = millis();
112  // read a packet
113  this->read_message(buffer.data_len, buffer.type, &buffer.container[buffer.data_offset]);
114  if (this->remove_)
115  return;
116  }
117 
120 
121  static uint32_t keepalive = 60000;
122  static uint8_t max_ping_retries = 60;
123  static uint16_t ping_retry_interval = 1000;
124  const uint32_t now = millis();
125  if (this->sent_ping_) {
126  // Disconnect if not responded within 2.5*keepalive
127  if (now - this->last_traffic_ > (keepalive * 5) / 2) {
128  on_fatal_error();
129  ESP_LOGW(TAG, "%s didn't respond to ping request in time. Disconnecting...", this->client_combined_info_.c_str());
130  }
131  } else if (now - this->last_traffic_ > keepalive && now > this->next_ping_retry_) {
132  ESP_LOGVV(TAG, "Sending keepalive PING...");
133  this->sent_ping_ = this->send_ping_request(PingRequest());
134  if (!this->sent_ping_) {
135  this->next_ping_retry_ = now + ping_retry_interval;
136  this->ping_retries_++;
137  if (this->ping_retries_ >= max_ping_retries) {
138  on_fatal_error();
139  ESP_LOGE(TAG, "%s: Sending keepalive failed %d time(s). Disconnecting...", this->client_combined_info_.c_str(),
140  this->ping_retries_);
141  } else if (this->ping_retries_ >= 10) {
142  ESP_LOGW(TAG, "%s: Sending keepalive failed %d time(s), will retry in %d ms",
143  this->client_combined_info_.c_str(), this->ping_retries_, ping_retry_interval);
144  } else {
145  ESP_LOGD(TAG, "%s: Sending keepalive failed %d time(s), will retry in %d ms",
146  this->client_combined_info_.c_str(), this->ping_retries_, ping_retry_interval);
147  }
148  }
149  }
150 
151 #ifdef USE_ESP32_CAMERA
152  if (this->image_reader_.available() && this->helper_->can_write_without_blocking()) {
153  uint32_t to_send = std::min((size_t) 1024, this->image_reader_.available());
154  auto buffer = this->create_buffer();
155  // fixed32 key = 1;
156  buffer.encode_fixed32(1, esp32_camera::global_esp32_camera->get_object_id_hash());
157  // bytes data = 2;
158  buffer.encode_bytes(2, this->image_reader_.peek_data_buffer(), to_send);
159  // bool done = 3;
160  bool done = this->image_reader_.available() == to_send;
161  buffer.encode_bool(3, done);
162  bool success = this->send_buffer(buffer, 44);
163 
164  if (success) {
165  this->image_reader_.consume_data(to_send);
166  }
167  if (success && done) {
168  this->image_reader_.return_image();
169  }
170  }
171 #endif
172 
173  if (state_subs_at_ != -1) {
174  const auto &subs = this->parent_->get_state_subs();
175  if (state_subs_at_ >= (int) subs.size()) {
176  state_subs_at_ = -1;
177  } else {
178  auto &it = subs[state_subs_at_];
180  resp.entity_id = it.entity_id;
181  resp.attribute = it.attribute.value();
183  state_subs_at_++;
184  }
185  }
186  }
187 }
188 
189 std::string get_default_unique_id(const std::string &component_type, EntityBase *entity) {
190  return App.get_name() + component_type + entity->get_object_id();
191 }
192 
194  // remote initiated disconnect_client
195  // don't close yet, we still need to send the disconnect response
196  // close will happen on next loop
197  ESP_LOGD(TAG, "%s requested disconnected", this->client_combined_info_.c_str());
198  this->next_close_ = true;
199  DisconnectResponse resp;
200  return resp;
201 }
203  // pass
204 }
205 
206 #ifdef USE_BINARY_SENSOR
208  if (!this->state_subscription_)
209  return false;
210 
212  resp.key = binary_sensor->get_object_id_hash();
213  resp.state = state;
214  resp.missing_state = !binary_sensor->has_state();
215  return this->send_binary_sensor_state_response(resp);
216 }
219  msg.object_id = binary_sensor->get_object_id();
220  msg.key = binary_sensor->get_object_id_hash();
221  if (binary_sensor->has_own_name())
222  msg.name = binary_sensor->get_name();
223  msg.unique_id = get_default_unique_id("binary_sensor", binary_sensor);
224  msg.device_class = binary_sensor->get_device_class();
225  msg.is_status_binary_sensor = binary_sensor->is_status_binary_sensor();
226  msg.disabled_by_default = binary_sensor->is_disabled_by_default();
227  msg.icon = binary_sensor->get_icon();
228  msg.entity_category = static_cast<enums::EntityCategory>(binary_sensor->get_entity_category());
230 }
231 #endif
232 
233 #ifdef USE_COVER
235  if (!this->state_subscription_)
236  return false;
237 
238  auto traits = cover->get_traits();
239  CoverStateResponse resp{};
240  resp.key = cover->get_object_id_hash();
241  resp.legacy_state =
243  resp.position = cover->position;
244  if (traits.get_supports_tilt())
245  resp.tilt = cover->tilt;
246  resp.current_operation = static_cast<enums::CoverOperation>(cover->current_operation);
247  return this->send_cover_state_response(resp);
248 }
250  auto traits = cover->get_traits();
252  msg.key = cover->get_object_id_hash();
253  msg.object_id = cover->get_object_id();
254  if (cover->has_own_name())
255  msg.name = cover->get_name();
256  msg.unique_id = get_default_unique_id("cover", cover);
257  msg.assumed_state = traits.get_is_assumed_state();
258  msg.supports_position = traits.get_supports_position();
259  msg.supports_tilt = traits.get_supports_tilt();
260  msg.supports_stop = traits.get_supports_stop();
261  msg.device_class = cover->get_device_class();
263  msg.icon = cover->get_icon();
264  msg.entity_category = static_cast<enums::EntityCategory>(cover->get_entity_category());
265  return this->send_list_entities_cover_response(msg);
266 }
268  cover::Cover *cover = App.get_cover_by_key(msg.key);
269  if (cover == nullptr)
270  return;
271 
272  auto call = cover->make_call();
273  if (msg.has_legacy_command) {
274  switch (msg.legacy_command) {
276  call.set_command_open();
277  break;
279  call.set_command_close();
280  break;
282  call.set_command_stop();
283  break;
284  }
285  }
286  if (msg.has_position)
287  call.set_position(msg.position);
288  if (msg.has_tilt)
289  call.set_tilt(msg.tilt);
290  if (msg.stop)
291  call.set_command_stop();
292  call.perform();
293 }
294 #endif
295 
296 #ifdef USE_FAN
298  if (!this->state_subscription_)
299  return false;
300 
301  auto traits = fan->get_traits();
302  FanStateResponse resp{};
303  resp.key = fan->get_object_id_hash();
304  resp.state = fan->state;
305  if (traits.supports_oscillation())
306  resp.oscillating = fan->oscillating;
307  if (traits.supports_speed()) {
308  resp.speed_level = fan->speed;
309  }
310  if (traits.supports_direction())
311  resp.direction = static_cast<enums::FanDirection>(fan->direction);
312  if (traits.supports_preset_modes())
313  resp.preset_mode = fan->preset_mode;
314  return this->send_fan_state_response(resp);
315 }
317  auto traits = fan->get_traits();
319  msg.key = fan->get_object_id_hash();
320  msg.object_id = fan->get_object_id();
321  if (fan->has_own_name())
322  msg.name = fan->get_name();
323  msg.unique_id = get_default_unique_id("fan", fan);
324  msg.supports_oscillation = traits.supports_oscillation();
325  msg.supports_speed = traits.supports_speed();
326  msg.supports_direction = traits.supports_direction();
327  msg.supported_speed_count = traits.supported_speed_count();
328  for (auto const &preset : traits.supported_preset_modes())
329  msg.supported_preset_modes.push_back(preset);
331  msg.icon = fan->get_icon();
332  msg.entity_category = static_cast<enums::EntityCategory>(fan->get_entity_category());
333  return this->send_list_entities_fan_response(msg);
334 }
336  fan::Fan *fan = App.get_fan_by_key(msg.key);
337  if (fan == nullptr)
338  return;
339 
340  auto call = fan->make_call();
341  if (msg.has_state)
342  call.set_state(msg.state);
343  if (msg.has_oscillating)
344  call.set_oscillating(msg.oscillating);
345  if (msg.has_speed_level) {
346  // Prefer level
347  call.set_speed(msg.speed_level);
348  }
349  if (msg.has_direction)
350  call.set_direction(static_cast<fan::FanDirection>(msg.direction));
351  if (msg.has_preset_mode)
352  call.set_preset_mode(msg.preset_mode);
353  call.perform();
354 }
355 #endif
356 
357 #ifdef USE_LIGHT
359  if (!this->state_subscription_)
360  return false;
361 
362  auto traits = light->get_traits();
363  auto values = light->remote_values;
364  auto color_mode = values.get_color_mode();
365  LightStateResponse resp{};
366 
367  resp.key = light->get_object_id_hash();
368  resp.state = values.is_on();
369  resp.color_mode = static_cast<enums::ColorMode>(color_mode);
370  resp.brightness = values.get_brightness();
371  resp.color_brightness = values.get_color_brightness();
372  resp.red = values.get_red();
373  resp.green = values.get_green();
374  resp.blue = values.get_blue();
375  resp.white = values.get_white();
376  resp.color_temperature = values.get_color_temperature();
377  resp.cold_white = values.get_cold_white();
378  resp.warm_white = values.get_warm_white();
379  if (light->supports_effects())
380  resp.effect = light->get_effect_name();
381  return this->send_light_state_response(resp);
382 }
384  auto traits = light->get_traits();
386  msg.key = light->get_object_id_hash();
387  msg.object_id = light->get_object_id();
388  if (light->has_own_name())
389  msg.name = light->get_name();
390  msg.unique_id = get_default_unique_id("light", light);
391 
393  msg.icon = light->get_icon();
394  msg.entity_category = static_cast<enums::EntityCategory>(light->get_entity_category());
395 
396  for (auto mode : traits.get_supported_color_modes())
397  msg.supported_color_modes.push_back(static_cast<enums::ColorMode>(mode));
398 
399  msg.legacy_supports_brightness = traits.supports_color_capability(light::ColorCapability::BRIGHTNESS);
400  msg.legacy_supports_rgb = traits.supports_color_capability(light::ColorCapability::RGB);
402  msg.legacy_supports_rgb && (traits.supports_color_capability(light::ColorCapability::WHITE) ||
403  traits.supports_color_capability(light::ColorCapability::COLD_WARM_WHITE));
404  msg.legacy_supports_color_temperature = traits.supports_color_capability(light::ColorCapability::COLOR_TEMPERATURE) ||
405  traits.supports_color_capability(light::ColorCapability::COLD_WARM_WHITE);
406 
408  msg.min_mireds = traits.get_min_mireds();
409  msg.max_mireds = traits.get_max_mireds();
410  }
411  if (light->supports_effects()) {
412  msg.effects.emplace_back("None");
413  for (auto *effect : light->get_effects())
414  msg.effects.push_back(effect->get_name());
415  }
416  return this->send_list_entities_light_response(msg);
417 }
420  if (light == nullptr)
421  return;
422 
423  auto call = light->make_call();
424  if (msg.has_state)
425  call.set_state(msg.state);
426  if (msg.has_brightness)
427  call.set_brightness(msg.brightness);
428  if (msg.has_color_mode)
429  call.set_color_mode(static_cast<light::ColorMode>(msg.color_mode));
430  if (msg.has_color_brightness)
432  if (msg.has_rgb) {
433  call.set_red(msg.red);
434  call.set_green(msg.green);
435  call.set_blue(msg.blue);
436  }
437  if (msg.has_white)
438  call.set_white(msg.white);
439  if (msg.has_color_temperature)
441  if (msg.has_cold_white)
442  call.set_cold_white(msg.cold_white);
443  if (msg.has_warm_white)
444  call.set_warm_white(msg.warm_white);
445  if (msg.has_transition_length)
447  if (msg.has_flash_length)
448  call.set_flash_length(msg.flash_length);
449  if (msg.has_effect)
450  call.set_effect(msg.effect);
451  call.perform();
452 }
453 #endif
454 
455 #ifdef USE_SENSOR
457  if (!this->state_subscription_)
458  return false;
459 
460  SensorStateResponse resp{};
461  resp.key = sensor->get_object_id_hash();
462  resp.state = state;
463  resp.missing_state = !sensor->has_state();
464  return this->send_sensor_state_response(resp);
465 }
468  msg.key = sensor->get_object_id_hash();
469  msg.object_id = sensor->get_object_id();
470  if (sensor->has_own_name())
471  msg.name = sensor->get_name();
472  msg.unique_id = sensor->unique_id();
473  if (msg.unique_id.empty())
474  msg.unique_id = get_default_unique_id("sensor", sensor);
475  msg.icon = sensor->get_icon();
478  msg.force_update = sensor->get_force_update();
479  msg.device_class = sensor->get_device_class();
480  msg.state_class = static_cast<enums::SensorStateClass>(sensor->get_state_class());
482  msg.entity_category = static_cast<enums::EntityCategory>(sensor->get_entity_category());
483  return this->send_list_entities_sensor_response(msg);
484 }
485 #endif
486 
487 #ifdef USE_SWITCH
489  if (!this->state_subscription_)
490  return false;
491 
492  SwitchStateResponse resp{};
493  resp.key = a_switch->get_object_id_hash();
494  resp.state = state;
495  return this->send_switch_state_response(resp);
496 }
499  msg.key = a_switch->get_object_id_hash();
500  msg.object_id = a_switch->get_object_id();
501  if (a_switch->has_own_name())
502  msg.name = a_switch->get_name();
503  msg.unique_id = get_default_unique_id("switch", a_switch);
504  msg.icon = a_switch->get_icon();
505  msg.assumed_state = a_switch->assumed_state();
507  msg.entity_category = static_cast<enums::EntityCategory>(a_switch->get_entity_category());
508  msg.device_class = a_switch->get_device_class();
509  return this->send_list_entities_switch_response(msg);
510 }
512  switch_::Switch *a_switch = App.get_switch_by_key(msg.key);
513  if (a_switch == nullptr)
514  return;
515 
516  if (msg.state) {
517  a_switch->turn_on();
518  } else {
519  a_switch->turn_off();
520  }
521 }
522 #endif
523 
524 #ifdef USE_TEXT_SENSOR
526  if (!this->state_subscription_)
527  return false;
528 
530  resp.key = text_sensor->get_object_id_hash();
531  resp.state = std::move(state);
532  resp.missing_state = !text_sensor->has_state();
533  return this->send_text_sensor_state_response(resp);
534 }
537  msg.key = text_sensor->get_object_id_hash();
538  msg.object_id = text_sensor->get_object_id();
539  msg.name = text_sensor->get_name();
540  msg.unique_id = text_sensor->unique_id();
541  if (msg.unique_id.empty())
542  msg.unique_id = get_default_unique_id("text_sensor", text_sensor);
543  msg.icon = text_sensor->get_icon();
544  msg.disabled_by_default = text_sensor->is_disabled_by_default();
545  msg.entity_category = static_cast<enums::EntityCategory>(text_sensor->get_entity_category());
546  msg.device_class = text_sensor->get_device_class();
547  return this->send_list_entities_text_sensor_response(msg);
548 }
549 #endif
550 
551 #ifdef USE_CLIMATE
553  if (!this->state_subscription_)
554  return false;
555 
556  auto traits = climate->get_traits();
557  ClimateStateResponse resp{};
558  resp.key = climate->get_object_id_hash();
559  resp.mode = static_cast<enums::ClimateMode>(climate->mode);
560  resp.action = static_cast<enums::ClimateAction>(climate->action);
561  if (traits.get_supports_current_temperature())
562  resp.current_temperature = climate->current_temperature;
563  if (traits.get_supports_two_point_target_temperature()) {
564  resp.target_temperature_low = climate->target_temperature_low;
565  resp.target_temperature_high = climate->target_temperature_high;
566  } else {
567  resp.target_temperature = climate->target_temperature;
568  }
569  if (traits.get_supports_fan_modes() && climate->fan_mode.has_value())
570  resp.fan_mode = static_cast<enums::ClimateFanMode>(climate->fan_mode.value());
571  if (!traits.get_supported_custom_fan_modes().empty() && climate->custom_fan_mode.has_value())
572  resp.custom_fan_mode = climate->custom_fan_mode.value();
573  if (traits.get_supports_presets() && climate->preset.has_value()) {
574  resp.preset = static_cast<enums::ClimatePreset>(climate->preset.value());
575  }
576  if (!traits.get_supported_custom_presets().empty() && climate->custom_preset.has_value())
577  resp.custom_preset = climate->custom_preset.value();
578  if (traits.get_supports_swing_modes())
579  resp.swing_mode = static_cast<enums::ClimateSwingMode>(climate->swing_mode);
580  if (traits.get_supports_current_humidity())
581  resp.current_humidity = climate->current_humidity;
582  if (traits.get_supports_target_humidity())
583  resp.target_humidity = climate->target_humidity;
584  return this->send_climate_state_response(resp);
585 }
587  auto traits = climate->get_traits();
589  msg.key = climate->get_object_id_hash();
590  msg.object_id = climate->get_object_id();
591  if (climate->has_own_name())
592  msg.name = climate->get_name();
593  msg.unique_id = get_default_unique_id("climate", climate);
594 
596  msg.icon = climate->get_icon();
597  msg.entity_category = static_cast<enums::EntityCategory>(climate->get_entity_category());
598 
599  msg.supports_current_temperature = traits.get_supports_current_temperature();
600  msg.supports_current_humidity = traits.get_supports_current_humidity();
601  msg.supports_two_point_target_temperature = traits.get_supports_two_point_target_temperature();
602  msg.supports_target_humidity = traits.get_supports_target_humidity();
603 
604  for (auto mode : traits.get_supported_modes())
605  msg.supported_modes.push_back(static_cast<enums::ClimateMode>(mode));
606 
607  msg.visual_min_temperature = traits.get_visual_min_temperature();
608  msg.visual_max_temperature = traits.get_visual_max_temperature();
609  msg.visual_target_temperature_step = traits.get_visual_target_temperature_step();
610  msg.visual_current_temperature_step = traits.get_visual_current_temperature_step();
611  msg.visual_min_humidity = traits.get_visual_min_humidity();
612  msg.visual_max_humidity = traits.get_visual_max_humidity();
613 
614  msg.legacy_supports_away = traits.supports_preset(climate::CLIMATE_PRESET_AWAY);
615  msg.supports_action = traits.get_supports_action();
616 
617  for (auto fan_mode : traits.get_supported_fan_modes())
618  msg.supported_fan_modes.push_back(static_cast<enums::ClimateFanMode>(fan_mode));
619  for (auto const &custom_fan_mode : traits.get_supported_custom_fan_modes())
621  for (auto preset : traits.get_supported_presets())
622  msg.supported_presets.push_back(static_cast<enums::ClimatePreset>(preset));
623  for (auto const &custom_preset : traits.get_supported_custom_presets())
625  for (auto swing_mode : traits.get_supported_swing_modes())
626  msg.supported_swing_modes.push_back(static_cast<enums::ClimateSwingMode>(swing_mode));
627  return this->send_list_entities_climate_response(msg);
628 }
630  climate::Climate *climate = App.get_climate_by_key(msg.key);
631  if (climate == nullptr)
632  return;
633 
634  auto call = climate->make_call();
635  if (msg.has_mode)
636  call.set_mode(static_cast<climate::ClimateMode>(msg.mode));
637  if (msg.has_target_temperature)
643  if (msg.has_target_humidity)
645  if (msg.has_fan_mode)
646  call.set_fan_mode(static_cast<climate::ClimateFanMode>(msg.fan_mode));
647  if (msg.has_custom_fan_mode)
648  call.set_fan_mode(msg.custom_fan_mode);
649  if (msg.has_preset)
650  call.set_preset(static_cast<climate::ClimatePreset>(msg.preset));
651  if (msg.has_custom_preset)
652  call.set_preset(msg.custom_preset);
653  if (msg.has_swing_mode)
654  call.set_swing_mode(static_cast<climate::ClimateSwingMode>(msg.swing_mode));
655  call.perform();
656 }
657 #endif
658 
659 #ifdef USE_NUMBER
661  if (!this->state_subscription_)
662  return false;
663 
664  NumberStateResponse resp{};
665  resp.key = number->get_object_id_hash();
666  resp.state = state;
667  resp.missing_state = !number->has_state();
668  return this->send_number_state_response(resp);
669 }
672  msg.key = number->get_object_id_hash();
673  msg.object_id = number->get_object_id();
674  if (number->has_own_name())
675  msg.name = number->get_name();
676  msg.unique_id = get_default_unique_id("number", number);
677  msg.icon = number->get_icon();
679  msg.entity_category = static_cast<enums::EntityCategory>(number->get_entity_category());
681  msg.mode = static_cast<enums::NumberMode>(number->traits.get_mode());
682  msg.device_class = number->traits.get_device_class();
683 
684  msg.min_value = number->traits.get_min_value();
685  msg.max_value = number->traits.get_max_value();
686  msg.step = number->traits.get_step();
687 
688  return this->send_list_entities_number_response(msg);
689 }
691  number::Number *number = App.get_number_by_key(msg.key);
692  if (number == nullptr)
693  return;
694 
695  auto call = number->make_call();
696  call.set_value(msg.state);
697  call.perform();
698 }
699 #endif
700 
701 #ifdef USE_DATETIME_DATE
703  if (!this->state_subscription_)
704  return false;
705 
706  DateStateResponse resp{};
707  resp.key = date->get_object_id_hash();
708  resp.missing_state = !date->has_state();
709  resp.year = date->year;
710  resp.month = date->month;
711  resp.day = date->day;
712  return this->send_date_state_response(resp);
713 }
716  msg.key = date->get_object_id_hash();
717  msg.object_id = date->get_object_id();
718  if (date->has_own_name())
719  msg.name = date->get_name();
720  msg.unique_id = get_default_unique_id("date", date);
721  msg.icon = date->get_icon();
723  msg.entity_category = static_cast<enums::EntityCategory>(date->get_entity_category());
724 
725  return this->send_list_entities_date_response(msg);
726 }
729  if (date == nullptr)
730  return;
731 
732  auto call = date->make_call();
733  call.set_date(msg.year, msg.month, msg.day);
734  call.perform();
735 }
736 #endif
737 
738 #ifdef USE_DATETIME_TIME
740  if (!this->state_subscription_)
741  return false;
742 
743  TimeStateResponse resp{};
744  resp.key = time->get_object_id_hash();
745  resp.missing_state = !time->has_state();
746  resp.hour = time->hour;
747  resp.minute = time->minute;
748  resp.second = time->second;
749  return this->send_time_state_response(resp);
750 }
753  msg.key = time->get_object_id_hash();
754  msg.object_id = time->get_object_id();
755  if (time->has_own_name())
756  msg.name = time->get_name();
757  msg.unique_id = get_default_unique_id("time", time);
758  msg.icon = time->get_icon();
760  msg.entity_category = static_cast<enums::EntityCategory>(time->get_entity_category());
761 
762  return this->send_list_entities_time_response(msg);
763 }
766  if (time == nullptr)
767  return;
768 
769  auto call = time->make_call();
770  call.set_time(msg.hour, msg.minute, msg.second);
771  call.perform();
772 }
773 #endif
774 
775 #ifdef USE_TEXT
777  if (!this->state_subscription_)
778  return false;
779 
780  TextStateResponse resp{};
781  resp.key = text->get_object_id_hash();
782  resp.state = std::move(state);
783  resp.missing_state = !text->has_state();
784  return this->send_text_state_response(resp);
785 }
788  msg.key = text->get_object_id_hash();
789  msg.object_id = text->get_object_id();
790  msg.name = text->get_name();
791  msg.icon = text->get_icon();
793  msg.entity_category = static_cast<enums::EntityCategory>(text->get_entity_category());
794  msg.mode = static_cast<enums::TextMode>(text->traits.get_mode());
795 
796  msg.min_length = text->traits.get_min_length();
797  msg.max_length = text->traits.get_max_length();
798  msg.pattern = text->traits.get_pattern();
799 
800  return this->send_list_entities_text_response(msg);
801 }
803  text::Text *text = App.get_text_by_key(msg.key);
804  if (text == nullptr)
805  return;
806 
807  auto call = text->make_call();
808  call.set_value(msg.state);
809  call.perform();
810 }
811 #endif
812 
813 #ifdef USE_SELECT
815  if (!this->state_subscription_)
816  return false;
817 
818  SelectStateResponse resp{};
819  resp.key = select->get_object_id_hash();
820  resp.state = std::move(state);
821  resp.missing_state = !select->has_state();
822  return this->send_select_state_response(resp);
823 }
826  msg.key = select->get_object_id_hash();
827  msg.object_id = select->get_object_id();
828  if (select->has_own_name())
829  msg.name = select->get_name();
830  msg.unique_id = get_default_unique_id("select", select);
831  msg.icon = select->get_icon();
833  msg.entity_category = static_cast<enums::EntityCategory>(select->get_entity_category());
834 
835  for (const auto &option : select->traits.get_options())
836  msg.options.push_back(option);
837 
838  return this->send_list_entities_select_response(msg);
839 }
841  select::Select *select = App.get_select_by_key(msg.key);
842  if (select == nullptr)
843  return;
844 
845  auto call = select->make_call();
846  call.set_option(msg.state);
847  call.perform();
848 }
849 #endif
850 
851 #ifdef USE_BUTTON
854  msg.key = button->get_object_id_hash();
855  msg.object_id = button->get_object_id();
856  if (button->has_own_name())
857  msg.name = button->get_name();
858  msg.unique_id = get_default_unique_id("button", button);
859  msg.icon = button->get_icon();
861  msg.entity_category = static_cast<enums::EntityCategory>(button->get_entity_category());
862  msg.device_class = button->get_device_class();
863  return this->send_list_entities_button_response(msg);
864 }
866  button::Button *button = App.get_button_by_key(msg.key);
867  if (button == nullptr)
868  return;
869 
870  button->press();
871 }
872 #endif
873 
874 #ifdef USE_LOCK
876  if (!this->state_subscription_)
877  return false;
878 
879  LockStateResponse resp{};
880  resp.key = a_lock->get_object_id_hash();
881  resp.state = static_cast<enums::LockState>(state);
882  return this->send_lock_state_response(resp);
883 }
886  msg.key = a_lock->get_object_id_hash();
887  msg.object_id = a_lock->get_object_id();
888  if (a_lock->has_own_name())
889  msg.name = a_lock->get_name();
890  msg.unique_id = get_default_unique_id("lock", a_lock);
891  msg.icon = a_lock->get_icon();
892  msg.assumed_state = a_lock->traits.get_assumed_state();
894  msg.entity_category = static_cast<enums::EntityCategory>(a_lock->get_entity_category());
895  msg.supports_open = a_lock->traits.get_supports_open();
896  msg.requires_code = a_lock->traits.get_requires_code();
897  return this->send_list_entities_lock_response(msg);
898 }
900  lock::Lock *a_lock = App.get_lock_by_key(msg.key);
901  if (a_lock == nullptr)
902  return;
903 
904  switch (msg.command) {
905  case enums::LOCK_UNLOCK:
906  a_lock->unlock();
907  break;
908  case enums::LOCK_LOCK:
909  a_lock->lock();
910  break;
911  case enums::LOCK_OPEN:
912  a_lock->open();
913  break;
914  }
915 }
916 #endif
917 
918 #ifdef USE_MEDIA_PLAYER
920  if (!this->state_subscription_)
921  return false;
922 
924  resp.key = media_player->get_object_id_hash();
925  resp.state = static_cast<enums::MediaPlayerState>(media_player->state);
926  resp.volume = media_player->volume;
927  resp.muted = media_player->is_muted();
928  return this->send_media_player_state_response(resp);
929 }
932  msg.key = media_player->get_object_id_hash();
933  msg.object_id = media_player->get_object_id();
934  if (media_player->has_own_name())
935  msg.name = media_player->get_name();
936  msg.unique_id = get_default_unique_id("media_player", media_player);
937  msg.icon = media_player->get_icon();
938  msg.disabled_by_default = media_player->is_disabled_by_default();
939  msg.entity_category = static_cast<enums::EntityCategory>(media_player->get_entity_category());
940 
941  auto traits = media_player->get_traits();
942  msg.supports_pause = traits.get_supports_pause();
943 
945 }
948  if (media_player == nullptr)
949  return;
950 
951  auto call = media_player->make_call();
952  if (msg.has_command) {
953  call.set_command(static_cast<media_player::MediaPlayerCommand>(msg.command));
954  }
955  if (msg.has_volume) {
956  call.set_volume(msg.volume);
957  }
958  if (msg.has_media_url) {
959  call.set_media_url(msg.media_url);
960  }
961  call.perform();
962 }
963 #endif
964 
965 #ifdef USE_ESP32_CAMERA
966 void APIConnection::send_camera_state(std::shared_ptr<esp32_camera::CameraImage> image) {
967  if (!this->state_subscription_)
968  return;
969  if (this->image_reader_.available())
970  return;
971  if (image->was_requested_by(esphome::esp32_camera::API_REQUESTER) ||
972  image->was_requested_by(esphome::esp32_camera::IDLE))
973  this->image_reader_.set_image(std::move(image));
974 }
977  msg.key = camera->get_object_id_hash();
978  msg.object_id = camera->get_object_id();
979  if (camera->has_own_name())
980  msg.name = camera->get_name();
981  msg.unique_id = get_default_unique_id("camera", camera);
983  msg.icon = camera->get_icon();
984  msg.entity_category = static_cast<enums::EntityCategory>(camera->get_entity_category());
985  return this->send_list_entities_camera_response(msg);
986 }
988  if (esp32_camera::global_esp32_camera == nullptr)
989  return;
990 
991  if (msg.single)
993  if (msg.stream) {
995 
996  App.scheduler.set_timeout(this->parent_, "api_esp32_camera_stop_stream", ESP32_CAMERA_STOP_STREAM, []() {
998  });
999  }
1000 }
1001 #endif
1002 
1003 #ifdef USE_HOMEASSISTANT_TIME
1007 }
1008 #endif
1009 
1010 #ifdef USE_BLUETOOTH_PROXY
1013 }
1016 }
1018  if (this->client_api_version_major_ < 1 || this->client_api_version_minor_ < 7) {
1020  for (auto &service : resp.service_data) {
1021  service.legacy_data.assign(service.data.begin(), service.data.end());
1022  service.data.clear();
1023  }
1024  for (auto &manufacturer_data : resp.manufacturer_data) {
1025  manufacturer_data.legacy_data.assign(manufacturer_data.data.begin(), manufacturer_data.data.end());
1026  manufacturer_data.data.clear();
1027  }
1028  return this->send_bluetooth_le_advertisement_response(resp);
1029  }
1030  return this->send_bluetooth_le_advertisement_response(msg);
1031 }
1034 }
1037 }
1040 }
1043 }
1046 }
1049 }
1050 
1053 }
1054 
1060  return resp;
1061 }
1062 #endif
1063 
1064 #ifdef USE_VOICE_ASSISTANT
1066  if (voice_assistant::global_voice_assistant != nullptr) {
1068  }
1069 }
1071  if (voice_assistant::global_voice_assistant != nullptr) {
1072  if (voice_assistant::global_voice_assistant->get_api_connection() != this) {
1073  return;
1074  }
1075 
1076  if (msg.error) {
1078  return;
1079  }
1080  if (msg.port == 0) {
1081  // Use API Audio
1083  } else {
1084  struct sockaddr_storage storage;
1085  socklen_t len = sizeof(storage);
1086  this->helper_->getpeername((struct sockaddr *) &storage, &len);
1088  }
1089  }
1090 };
1092  if (voice_assistant::global_voice_assistant != nullptr) {
1093  if (voice_assistant::global_voice_assistant->get_api_connection() != this) {
1094  return;
1095  }
1096 
1098  }
1099 }
1101  if (voice_assistant::global_voice_assistant != nullptr) {
1102  if (voice_assistant::global_voice_assistant->get_api_connection() != this) {
1103  return;
1104  }
1105 
1107  }
1108 };
1109 
1110 #endif
1111 
1112 #ifdef USE_ALARM_CONTROL_PANEL
1114  if (!this->state_subscription_)
1115  return false;
1116 
1118  resp.key = a_alarm_control_panel->get_object_id_hash();
1119  resp.state = static_cast<enums::AlarmControlPanelState>(a_alarm_control_panel->get_state());
1120  return this->send_alarm_control_panel_state_response(resp);
1121 }
1124  msg.key = a_alarm_control_panel->get_object_id_hash();
1125  msg.object_id = a_alarm_control_panel->get_object_id();
1126  msg.name = a_alarm_control_panel->get_name();
1127  msg.unique_id = get_default_unique_id("alarm_control_panel", a_alarm_control_panel);
1128  msg.icon = a_alarm_control_panel->get_icon();
1129  msg.disabled_by_default = a_alarm_control_panel->is_disabled_by_default();
1130  msg.entity_category = static_cast<enums::EntityCategory>(a_alarm_control_panel->get_entity_category());
1131  msg.supported_features = a_alarm_control_panel->get_supported_features();
1132  msg.requires_code = a_alarm_control_panel->get_requires_code();
1133  msg.requires_code_to_arm = a_alarm_control_panel->get_requires_code_to_arm();
1135 }
1138  if (a_alarm_control_panel == nullptr)
1139  return;
1140 
1141  auto call = a_alarm_control_panel->make_call();
1142  switch (msg.command) {
1144  call.disarm();
1145  break;
1147  call.arm_away();
1148  break;
1150  call.arm_home();
1151  break;
1153  call.arm_night();
1154  break;
1156  call.arm_vacation();
1157  break;
1159  call.arm_custom_bypass();
1160  break;
1162  call.pending();
1163  break;
1164  }
1165  call.set_code(msg.code);
1166  call.perform();
1167 }
1168 #endif
1169 
1170 bool APIConnection::send_log_message(int level, const char *tag, const char *line) {
1171  if (this->log_subscription_ < level)
1172  return false;
1173 
1174  // Send raw so that we don't copy too much
1175  auto buffer = this->create_buffer();
1176  // LogLevel level = 1;
1177  buffer.encode_uint32(1, static_cast<uint32_t>(level));
1178  // string message = 3;
1179  buffer.encode_string(3, line, strlen(line));
1180  // SubscribeLogsResponse - 29
1181  return this->send_buffer(buffer, 29);
1182 }
1183 
1185  this->client_info_ = msg.client_info;
1186  this->client_peername_ = this->helper_->getpeername();
1187  this->client_combined_info_ = this->client_info_ + " (" + this->client_peername_ + ")";
1188  this->helper_->set_log_info(this->client_combined_info_);
1191  ESP_LOGV(TAG, "Hello from client: '%s' | %s | API Version %" PRIu32 ".%" PRIu32, this->client_info_.c_str(),
1192  this->client_peername_.c_str(), this->client_api_version_major_, this->client_api_version_minor_);
1193 
1194  HelloResponse resp;
1195  resp.api_version_major = 1;
1196  resp.api_version_minor = 10;
1197  resp.server_info = App.get_name() + " (esphome v" ESPHOME_VERSION ")";
1198  resp.name = App.get_name();
1199 
1200  this->connection_state_ = ConnectionState::CONNECTED;
1201  return resp;
1202 }
1204  bool correct = this->parent_->check_password(msg.password);
1205 
1206  ConnectResponse resp;
1207  // bool invalid_password = 1;
1208  resp.invalid_password = !correct;
1209  if (correct) {
1210  ESP_LOGD(TAG, "%s: Connected successfully", this->client_combined_info_.c_str());
1211  this->connection_state_ = ConnectionState::AUTHENTICATED;
1213 #ifdef USE_HOMEASSISTANT_TIME
1215  this->send_time_request();
1216  }
1217 #endif
1218  }
1219  return resp;
1220 }
1222  DeviceInfoResponse resp{};
1223  resp.uses_password = this->parent_->uses_password();
1224  resp.name = App.get_name();
1225  resp.friendly_name = App.get_friendly_name();
1226  resp.suggested_area = App.get_area();
1227  resp.mac_address = get_mac_address_pretty();
1228  resp.esphome_version = ESPHOME_VERSION;
1229  resp.compilation_time = App.get_compilation_time();
1230 #if defined(USE_ESP8266) || defined(USE_ESP32)
1231  resp.manufacturer = "Espressif";
1232 #elif defined(USE_RP2040)
1233  resp.manufacturer = "Raspberry Pi";
1234 #elif defined(USE_BK72XX)
1235  resp.manufacturer = "Beken";
1236 #elif defined(USE_RTL87XX)
1237  resp.manufacturer = "Realtek";
1238 #elif defined(USE_HOST)
1239  resp.manufacturer = "Host";
1240 #endif
1241  resp.model = ESPHOME_BOARD;
1242 #ifdef USE_DEEP_SLEEP
1243  resp.has_deep_sleep = deep_sleep::global_has_deep_sleep;
1244 #endif
1245 #ifdef ESPHOME_PROJECT_NAME
1246  resp.project_name = ESPHOME_PROJECT_NAME;
1247  resp.project_version = ESPHOME_PROJECT_VERSION;
1248 #endif
1249 #ifdef USE_WEBSERVER
1250  resp.webserver_port = USE_WEBSERVER_PORT;
1251 #endif
1252 #ifdef USE_BLUETOOTH_PROXY
1253  resp.legacy_bluetooth_proxy_version = bluetooth_proxy::global_bluetooth_proxy->get_legacy_version();
1254  resp.bluetooth_proxy_feature_flags = bluetooth_proxy::global_bluetooth_proxy->get_feature_flags();
1255 #endif
1256 #ifdef USE_VOICE_ASSISTANT
1257  resp.legacy_voice_assistant_version = voice_assistant::global_voice_assistant->get_legacy_version();
1258  resp.voice_assistant_feature_flags = voice_assistant::global_voice_assistant->get_feature_flags();
1259 #endif
1260  return resp;
1261 }
1263  for (auto &it : this->parent_->get_state_subs()) {
1264  if (it.entity_id == msg.entity_id && it.attribute.value() == msg.attribute) {
1265  it.callback(msg.state);
1266  }
1267  }
1268 }
1270  bool found = false;
1271  for (auto *service : this->parent_->get_user_services()) {
1272  if (service->execute_service(msg)) {
1273  found = true;
1274  }
1275  }
1276  if (!found) {
1277  ESP_LOGV(TAG, "Could not find matching service!");
1278  }
1279 }
1281  state_subs_at_ = 0;
1282 }
1283 bool APIConnection::send_buffer(ProtoWriteBuffer buffer, uint32_t message_type) {
1284  if (this->remove_)
1285  return false;
1286  if (!this->helper_->can_write_without_blocking()) {
1287  delay(0);
1288  APIError err = this->helper_->loop();
1289  if (err != APIError::OK) {
1290  on_fatal_error();
1291  ESP_LOGW(TAG, "%s: Socket operation failed: %s errno=%d", this->client_combined_info_.c_str(),
1292  api_error_to_str(err), errno);
1293  return false;
1294  }
1295  if (!this->helper_->can_write_without_blocking()) {
1296  // SubscribeLogsResponse
1297  if (message_type != 29) {
1298  ESP_LOGV(TAG, "Cannot send message because of TCP buffer space");
1299  }
1300  delay(0);
1301  return false;
1302  }
1303  }
1304 
1305  APIError err = this->helper_->write_packet(message_type, buffer.get_buffer()->data(), buffer.get_buffer()->size());
1306  if (err == APIError::WOULD_BLOCK)
1307  return false;
1308  if (err != APIError::OK) {
1309  on_fatal_error();
1310  if (err == APIError::SOCKET_WRITE_FAILED && errno == ECONNRESET) {
1311  ESP_LOGW(TAG, "%s: Connection reset", this->client_combined_info_.c_str());
1312  } else {
1313  ESP_LOGW(TAG, "%s: Packet write failed %s errno=%d", this->client_combined_info_.c_str(), api_error_to_str(err),
1314  errno);
1315  }
1316  return false;
1317  }
1318  // Do not set last_traffic_ on send
1319  return true;
1320 }
1322  this->on_fatal_error();
1323  ESP_LOGD(TAG, "%s: tried to access without authentication.", this->client_combined_info_.c_str());
1324 }
1326  this->on_fatal_error();
1327  ESP_LOGD(TAG, "%s: tried to access without full connection.", this->client_combined_info_.c_str());
1328 }
1330  this->helper_->close();
1331  this->remove_ = true;
1332 }
1333 
1334 } // namespace api
1335 } // namespace esphome
bool get_force_update() const
Get whether force update mode is enabled.
Definition: sensor.h:78
Base class for all switches.
Definition: switch.h:39
value_type const & value() const
Definition: optional.h:89
float current_humidity
The current humidity of the climate device, as reported from the integration.
Definition: climate.h:182
bool send_list_entities_binary_sensor_response(const ListEntitiesBinarySensorResponse &msg)
bool state
The current on/off state of the fan.
Definition: fan.h:110
bool send_text_sensor_state(text_sensor::TextSensor *text_sensor, std::string state)
ClimateSwingMode swing_mode
The active swing mode of the climate device.
Definition: climate.h:202
bool send_alarm_control_panel_state(alarm_control_panel::AlarmControlPanel *a_alarm_control_panel)
bool has_own_name() const
Definition: entity_base.h:23
bool send_date_state_response(const DateStateResponse &msg)
bool send_time_info(datetime::TimeEntity *time)
AlarmControlPanelState get_state() const
Get the state.
enums::EntityCategory entity_category
Definition: api_pb2.h:640
This class represents the communication layer between the front-end MQTT layer and the hardware outpu...
Definition: light_state.h:34
std::vector< std::string > supported_preset_modes
Definition: api_pb2.h:480
LightCall & set_color_brightness(optional< float > brightness)
Set the color brightness of the light from 0.0 (no color) to 1.0 (fully on)
Definition: light_call.cpp:593
bool oscillating
The current oscillation state of the fan.
Definition: fan.h:112
bool has_state() const
Return whether this number has gotten a full state yet.
Definition: number.h:52
std::vector< uint8_t > * get_buffer() const
Definition: proto.h:268
void request_image(CameraRequester requester)
media_player::MediaPlayer * get_media_player_by_key(uint32_t key, bool include_internal=false)
Definition: application.h:353
bool send_text_info(text::Text *text)
bool send_climate_info(climate::Climate *climate)
MediaPlayerCall & set_command(MediaPlayerCommand command)
FanDirection direction
The current direction of the fan.
Definition: fan.h:116
Base class for all cover devices.
Definition: cover.h:111
const std::vector< UserServiceDescriptor * > & get_user_services() const
Definition: api_server.h:108
LightCall & set_red(optional< float > red)
Set the red RGB value of the light from 0.0 to 1.0.
Definition: light_call.cpp:601
void start_stream(CameraRequester requester)
enums::EntityCategory entity_category
Definition: api_pb2.h:1177
LightCall & set_color_temperature(optional< float > color_temperature)
Set the color temperature of the light in mireds for CWWW or RGBWW lights.
Definition: light_call.cpp:633
void on_voice_assistant_audio(const VoiceAssistantAudio &msg) override
void bluetooth_gatt_notify(const BluetoothGATTNotifyRequest &msg) override
TextMode get_mode() const
Definition: text_traits.h:29
bool send_cover_info(cover::Cover *cover)
bool send_text_state_response(const TextStateResponse &msg)
enums::EntityCategory entity_category
Definition: api_pb2.h:1229
bool send_ping_request(const PingRequest &msg)
LightCall & set_cold_white(optional< float > cold_white)
Set the cold white value of the light from 0.0 to 1.0.
Definition: light_call.cpp:641
bool send_switch_state(switch_::Switch *a_switch, bool state)
TimeCall & set_time(uint8_t hour, uint8_t minute, uint8_t second)
Definition: time_entity.cpp:66
float target_temperature
The target temperature of the climate device.
Definition: climate.h:186
VoiceAssistant * global_voice_assistant
std::string get_effect_name()
Return the name of the current effect, or if no effect is active "None".
climate::Climate * get_climate_by_key(uint32_t key, bool include_internal=false)
Definition: application.h:290
std::string get_device_class()
Get the device class, using the manual override if set.
Definition: entity_base.cpp:78
select::Select * get_select_by_key(uint32_t key, bool include_internal=false)
Definition: application.h:335
CoverCall make_call()
Construct a new cover call used to control the cover.
Definition: cover.cpp:149
void alarm_control_panel_command(const AlarmControlPanelCommandRequest &msg) override
void on_voice_assistant_response(const VoiceAssistantResponse &msg) override
TextTraits traits
Definition: text.h:27
BluetoothConnectionsFreeResponse subscribe_bluetooth_connections_free(const SubscribeBluetoothConnectionsFreeRequest &msg) override
std::string get_default_unique_id(const std::string &component_type, EntityBase *entity)
InitialStateIterator initial_state_iterator_
const char * api_error_to_str(APIError err)
virtual std::string unique_id()
Override this method to set the unique ID of this sensor.
Definition: text_sensor.cpp:68
TextCall & set_value(const std::string &value)
Definition: text_call.cpp:10
CoverOperation current_operation
The current operation of the cover (idle, opening, closing).
Definition: cover.h:116
std::vector< enums::ClimatePreset > supported_presets
Definition: api_pb2.h:988
Base class for all buttons.
Definition: button.h:29
enums::EntityCategory entity_category
Definition: api_pb2.h:1130
bool send_camera_info(esp32_camera::ESP32Camera *camera)
std::vector< std::string > options
Definition: api_pb2.h:1128
bool send_fan_state(fan::Fan *fan)
virtual FanTraits get_traits()=0
enums::EntityCategory entity_category
Definition: api_pb2.h:674
enums::EntityCategory entity_category
Definition: api_pb2.h:1829
lock::Lock * get_lock_by_key(uint32_t key, bool include_internal=false)
Definition: application.h:344
bool send_binary_sensor_state_response(const BinarySensorStateResponse &msg)
bool check_password(const std::string &password) const
Definition: api_server.cpp:148
bool supports_effects()
Return whether the light has any effects that meet the trait requirements.
bool send_climate_state(climate::Climate *climate)
ClimateMode mode
The active mode of the climate device.
Definition: climate.h:173
virtual bool get_requires_code() const =0
Returns if the alarm_control_panel has a code.
bool send_button_info(button::Button *button)
button::Button * get_button_by_key(uint32_t key, bool include_internal=false)
Definition: application.h:236
virtual bool assumed_state()
Return whether this switch uses an assumed state - i.e.
Definition: switch.cpp:58
uint32_t socklen_t
Definition: headers.h:97
bool send_list_entities_fan_response(const ListEntitiesFanResponse &msg)
DisconnectResponse disconnect(const DisconnectRequest &msg) override
virtual bool is_status_binary_sensor() const
bool send_number_state_response(const NumberStateResponse &msg)
bool send_lock_state(lock::Lock *a_lock, lock::LockState state)
bool send_text_state(text::Text *text, std::string state)
const std::string & get_area() const
Get the area of this Application set by pre_setup().
Definition: application.h:180
const std::string & get_friendly_name() const
Get the friendly name of this Application set by pre_setup().
Definition: application.h:177
std::unique_ptr< APIFrameHelper > helper_
SelectTraits traits
Definition: select.h:34
enums::ClimateSwingMode swing_mode
Definition: api_pb2.h:1051
float target_temperature_high
The maximum target temperature of the climate device, for climate devices with split target temperatu...
Definition: climate.h:191
void media_player_command(const MediaPlayerCommandRequest &msg) override
float current_temperature
The current temperature of the climate device, as reported from the integration.
Definition: climate.h:179
bool send_list_entities_select_response(const ListEntitiesSelectResponse &msg)
Color temperature can be controlled.
void client_subscription(api::APIConnection *client, bool subscribe)
HomeassistantTime * global_homeassistant_time
LightCall & set_color_mode(optional< ColorMode > color_mode)
Set the color mode of the light.
Definition: light_call.cpp:585
enums::ColorMode color_mode
Definition: api_pb2.h:595
void send_camera_state(std::shared_ptr< esp32_camera::CameraImage > image)
bool send_date_info(datetime::DateEntity *date)
std::vector< BluetoothServiceData > service_data
Definition: api_pb2.h:1337
NumberCall & set_value(float value)
Definition: number_call.cpp:10
bool has_value() const
Definition: optional.h:87
void execute_service(const ExecuteServiceRequest &msg) override
std::vector< std::string > supported_custom_presets
Definition: api_pb2.h:989
int get_max_length() const
Definition: text_traits.h:21
Base-class for all text inputs.
Definition: text.h:24
TextCall make_call()
Instantiate a TextCall object to modify this text component&#39;s state.
Definition: text.h:35
void subscribe_voice_assistant(const SubscribeVoiceAssistantRequest &msg) override
LightCall & set_transition_length(optional< uint32_t > transition_length)
Set the transition length of this call in milliseconds.
Definition: light_call.cpp:561
float target_humidity
The target humidity of the climate device.
Definition: climate.h:196
virtual bool is_muted() const
Definition: media_player.h:80
ClimateCall & set_swing_mode(ClimateSwingMode swing_mode)
Set the swing mode of the climate device.
Definition: climate.cpp:237
AlarmControlPanelCall make_call()
Make a AlarmControlPanelCall.
bool send_number_info(number::Number *number)
void subscribe_bluetooth_le_advertisements(const SubscribeBluetoothLEAdvertisementsRequest &msg) override
float tilt
The current tilt value of the cover from 0.0 to 1.0.
Definition: cover.h:124
bool is_connected()
Return whether the node is connected to the network (through wifi, eth, ...)
Definition: util.cpp:15
void stop_stream(CameraRequester requester)
std::string get_object_id() const
Definition: entity_base.cpp:43
uint32_t IRAM_ATTR HOT millis()
Definition: core.cpp:25
virtual MediaPlayerTraits get_traits()=0
ClimateSwingMode swing_mode
Definition: climate.h:581
void on_no_setup_connection() override
void trigger(Ts... x)
Inform the parent automation that the event has triggered.
Definition: automation.h:95
alarm_control_panel::AlarmControlPanel * get_alarm_control_panel_by_key(uint32_t key, bool include_internal=false)
Definition: application.h:365
bool send_binary_sensor_info(binary_sensor::BinarySensor *binary_sensor)
enums::ClimateFanMode fan_mode
Definition: api_pb2.h:1049
LockTraits traits
Definition: lock.h:124
optional< std::string > custom_fan_mode
The active custom fan mode of the climate device.
Definition: climate.h:205
cover::Cover * get_cover_by_key(uint32_t key, bool include_internal=false)
Definition: application.h:272
virtual CoverTraits get_traits()=0
void bluetooth_device_request(const api::BluetoothDeviceRequest &msg)
BluetoothProxy * global_bluetooth_proxy
Device is in away preset.
Definition: climate_mode.h:88
ClimateCall & set_target_temperature_low(float target_temperature_low)
Set the low point target temperature of the climate device.
Definition: climate.cpp:260
bool send_select_info(select::Select *select)
virtual std::string unique_id()
Override this method to set the unique ID of this sensor.
Definition: sensor.cpp:88
bool send_bluetooth_le_advertisement_response(const BluetoothLEAdvertisementResponse &msg)
ClimateCall make_call()
Make a climate device control call, this is used to control the climate device, see the ClimateCall d...
Definition: climate.cpp:479
fan::Fan * get_fan_by_key(uint32_t key, bool include_internal=false)
Definition: application.h:263
void lock()
Turn this lock on.
Definition: lock.cpp:30
enums::EntityCategory entity_category
Definition: api_pb2.h:933
std::string get_icon() const
Definition: entity_base.cpp:30
std::shared_ptr< APINoiseContext > get_noise_ctx()
Definition: api_server.h:38
ClimateCall & set_target_temperature(float target_temperature)
Set the target temperature of the climate device.
Definition: climate.cpp:256
enums::ClimatePreset preset
Definition: api_pb2.h:1055
void time_command(const TimeCommandRequest &msg) override
void date_command(const DateCommandRequest &msg) override
enums::EntityCategory entity_category
Definition: api_pb2.h:1880
Trigger< std::string, std::string > * get_client_connected_trigger() const
Definition: api_server.h:110
bool send_list_entities_text_sensor_response(const ListEntitiesTextSensorResponse &msg)
FanCall & set_speed(int speed)
Definition: fan.h:59
bool send_sensor_state(sensor::Sensor *sensor, float state)
Brightness of cold and warm white output can be controlled.
void bluetooth_gatt_read(const api::BluetoothGATTReadRequest &msg)
void press()
Press this button.
Definition: button.cpp:9
bool send_select_state(select::Select *select, std::string state)
std::vector< std::string > get_options() const
bool send_list_entities_light_response(const ListEntitiesLightResponse &msg)
std::string preset_mode
Definition: fan.h:118
DateCall & set_date(uint16_t year, uint8_t month, uint8_t day)
Definition: date_entity.cpp:83
enums::EntityCategory entity_category
Definition: api_pb2.h:420
ESP32Camera * global_esp32_camera
optional< ClimatePreset > preset
The active preset of the climate device.
Definition: climate.h:208
enums::FanDirection direction
Definition: api_pb2.h:520
std::vector< std::string > effects
Definition: api_pb2.h:548
bool send_text_sensor_state_response(const TextSensorStateResponse &msg)
virtual bool has_state() const
Return whether this binary sensor has outputted a state.
uint8_t custom_preset
Definition: climate.h:579
std::vector< uint8_t > proto_write_buffer_
bool send_list_entities_cover_response(const ListEntitiesCoverResponse &msg)
bool send_log_message(int level, const char *tag, const char *line)
Base-class for all numbers.
Definition: number.h:39
bool send_time_state(datetime::TimeEntity *time)
Brightness of white channel can be controlled separately from other channels.
int speed
The current fan speed level.
Definition: fan.h:114
bool send_list_entities_camera_response(const ListEntitiesCameraResponse &msg)
ClimateCall & set_preset(ClimatePreset preset)
Set the preset of the climate device.
Definition: climate.cpp:199
bool has_state() const
Return whether this text input has gotten a full state yet.
Definition: text.h:32
std::vector< std::string > supported_custom_fan_modes
Definition: api_pb2.h:987
BedjetMode mode
BedJet operating mode.
Definition: bedjet_codec.h:151
enums::LockCommand command
Definition: api_pb2.h:1208
bool send_list_entities_button_response(const ListEntitiesButtonResponse &msg)
bool has_state() const
Return whether this Datetime has gotten a full state yet.
Definition: datetime_base.h:14
ClimateCall & set_fan_mode(ClimateFanMode fan_mode)
Set the fan mode of the climate device.
Definition: climate.cpp:157
const float COVER_OPEN
Definition: cover.cpp:9
bool send_media_player_info(media_player::MediaPlayer *media_player)
bool send_list_entities_media_player_response(const ListEntitiesMediaPlayerResponse &msg)
void bluetooth_gatt_write(const BluetoothGATTWriteRequest &msg) override
ClimateTraits get_traits()
Get the traits of this climate device with all overrides applied.
Definition: climate.cpp:440
void turn_on()
Turn this switch on.
Definition: switch.cpp:11
bool send_alarm_control_panel_info(alarm_control_panel::AlarmControlPanel *a_alarm_control_panel)
SelectCall make_call()
Instantiate a SelectCall object to modify this select component&#39;s state.
Definition: select.h:42
std::string get_unit_of_measurement()
Get the unit of measurement, using the manual override if set.
Definition: entity_base.cpp:87
bool send_binary_sensor_state(binary_sensor::BinarySensor *binary_sensor, bool state)
void bluetooth_device_request(const BluetoothDeviceRequest &msg) override
bool send_fan_info(fan::Fan *fan)
enums::AlarmControlPanelStateCommand command
Definition: api_pb2.h:1809
FanCall & set_oscillating(bool oscillating)
Definition: fan.h:50
Application App
Global storage of Application pointer - only one Application can exist.
void bluetooth_gatt_write(const api::BluetoothGATTWriteRequest &msg)
StateClass get_state_class()
Get the state class, using the manual override if set.
Definition: sensor.cpp:33
enums::EntityCategory entity_category
Definition: api_pb2.h:1081
const std::vector< LightEffect * > & get_effects() const
Get all effects for this light state.
ColorMode get_color_mode() const
Get the color mode of these light color values.
LightCall & set_state(optional< bool > state)
Set the binary ON/OFF state of the light.
Definition: light_call.cpp:553
void on_disconnect_response(const DisconnectResponse &value) override
light::LightState * get_light_by_key(uint32_t key, bool include_internal=false)
Definition: application.h:281
void on_get_time_response(const GetTimeResponse &value) override
bool get_assumed_state() const
Definition: lock.h:44
void button_command(const ButtonCommandRequest &msg) override
void bluetooth_gatt_write_descriptor(const api::BluetoothGATTWriteDescriptorRequest &msg)
Master brightness of the light can be controlled.
void bluetooth_gatt_read_descriptor(const BluetoothGATTReadDescriptorRequest &msg) override
const std::string & get_name() const
Get the name of this Application set by pre_setup().
Definition: application.h:174
bool send_list_entities_number_response(const ListEntitiesNumberResponse &msg)
bool send_switch_state_response(const SwitchStateResponse &msg)
bool send_cover_state(cover::Cover *cover)
bool read_message(uint32_t msg_size, uint32_t msg_type, uint8_t *msg_data) override
LightCall & set_warm_white(optional< float > warm_white)
Set the warm white value of the light from 0.0 to 1.0.
Definition: light_call.cpp:649
void subscribe_home_assistant_states(const SubscribeHomeAssistantStatesRequest &msg) override
switch_::Switch * get_switch_by_key(uint32_t key, bool include_internal=false)
Definition: application.h:227
bool send_list_entities_lock_response(const ListEntitiesLockResponse &msg)
ClimateCall & set_target_humidity(float target_humidity)
Set the target humidity of the climate device.
Definition: climate.cpp:268
void unsubscribe_api_connection(api::APIConnection *api_connection)
ClimateFanMode fan_mode
Definition: climate.h:573
bool send_buffer(ProtoWriteBuffer buffer, uint32_t message_type) override
NumberTraits traits
Definition: number.h:49
void bluetooth_gatt_write_descriptor(const BluetoothGATTWriteDescriptorRequest &msg) override
std::string client_info
Definition: api_pb2.h:224
void unsubscribe_bluetooth_le_advertisements(const UnsubscribeBluetoothLEAdvertisementsRequest &msg) override
void bluetooth_gatt_get_services(const BluetoothGATTGetServicesRequest &msg) override
bool send_list_entities_sensor_response(const ListEntitiesSensorResponse &msg)
std::vector< enums::ClimateFanMode > supported_fan_modes
Definition: api_pb2.h:985
void on_audio(const api::VoiceAssistantAudio &msg)
optional< std::string > custom_preset
The active custom preset mode of the climate device.
Definition: climate.h:211
LightCall & set_effect(optional< std::string > effect)
Set the effect of the light by its name.
Definition: light_call.cpp:657
bool send_list_entities_alarm_control_panel_response(const ListEntitiesAlarmControlPanelResponse &msg)
ClimateCall & set_target_temperature_high(float target_temperature_high)
Set the high point target temperature of the climate device.
Definition: climate.cpp:264
esp32_camera::CameraImageReader image_reader_
void bluetooth_gatt_notify(const api::BluetoothGATTNotifyRequest &msg)
void set_image(std::shared_ptr< CameraImage > image)
bool send_select_state_response(const SelectStateResponse &msg)
optional< ClimateFanMode > fan_mode
The active fan mode of the climate device.
Definition: climate.h:199
float position
The position of the cover from 0.0 (fully closed) to 1.0 (fully open).
Definition: cover.h:122
void switch_command(const SwitchCommandRequest &msg) override
ConnectResponse connect(const ConnectRequest &msg) override
bool send_light_info(light::LightState *light)
EntityCategory get_entity_category() const
Definition: entity_base.cpp:39
datetime::DateEntity * get_date_by_key(uint32_t key, bool include_internal=false)
Definition: application.h:308
NumberCall make_call()
Definition: number.h:45
FanCall & set_state(bool binary_state)
Definition: fan.h:41
void select_command(const SelectCommandRequest &msg) override
bool send_light_state_response(const LightStateResponse &msg)
bool send_sensor_info(sensor::Sensor *sensor)
std::string size_t len
Definition: helpers.h:292
FanCall & set_preset_mode(const std::string &preset_mode)
Definition: fan.h:75
void open()
Open (unlatch) this lock.
Definition: lock.cpp:40
DeviceInfoResponse device_info(const DeviceInfoRequest &msg) override
bool send_date_state(datetime::DateEntity *date)
bool send_media_player_state_response(const MediaPlayerStateResponse &msg)
text::Text * get_text_by_key(uint32_t key, bool include_internal=false)
Definition: application.h:326
bool send_subscribe_home_assistant_state_response(const SubscribeHomeAssistantStateResponse &msg)
ClimateCall & set_mode(ClimateMode mode)
Set the mode of the climate device.
Definition: climate.cpp:133
const std::vector< HomeAssistantStateSubscription > & get_state_subs() const
Definition: api_server.cpp:332
number::Number * get_number_by_key(uint32_t key, bool include_internal=false)
Definition: application.h:299
enums::EntityCategory entity_category
Definition: api_pb2.h:479
bool send_list_entities_switch_response(const ListEntitiesSwitchResponse &msg)
FanCall make_call()
Definition: fan.cpp:114
LightCall & set_flash_length(optional< uint32_t > flash_length)
Start and set the flash length of this call in milliseconds.
Definition: light_call.cpp:569
bool send_list_entities_date_response(const ListEntitiesDateResponse &msg)
bool get_requires_code() const
Definition: lock.h:42
LightCall & set_green(optional< float > green)
Set the green RGB value of the light from 0.0 to 1.0.
Definition: light_call.cpp:609
bool uses_password() const
Definition: api_server.cpp:147
Base-class for all selects.
Definition: select.h:31
bool send_light_state(light::LightState *light)
std::vector< enums::ColorMode > supported_color_modes
Definition: api_pb2.h:541
void set_timeout(Component *component, const std::string &name, uint32_t timeout, std::function< void()> func)
Definition: scheduler.cpp:22
This is a workaround until we can figure out a way to get the tflite-micro idf component code availab...
Definition: a01nyub.cpp:7
void on_unauthenticated_access() override
bool has_state() const
Return whether this sensor has gotten a full state (that passed through all filters) yet...
Definition: sensor.cpp:97
void bluetooth_gatt_read_descriptor(const api::BluetoothGATTReadDescriptorRequest &msg)
void text_command(const TextCommandRequest &msg) override
bool has_state() const
Return whether this select component has gotten a full state yet.
Definition: select.h:39
void lock_command(const LockCommandRequest &msg) override
std::vector< BluetoothServiceData > manufacturer_data
Definition: api_pb2.h:1338
void unlock()
Turn this lock off.
Definition: lock.cpp:35
bool send_media_player_state(media_player::MediaPlayer *media_player)
bool send_sensor_state_response(const SensorStateResponse &msg)
bool send_cover_state_response(const CoverStateResponse &msg)
bool send_list_entities_text_response(const ListEntitiesTextResponse &msg)
Base class for all binary_sensor-type classes.
Definition: binary_sensor.h:37
Color can be controlled using RGB format (includes a brightness control for the color).
LightColorValues remote_values
The remote color values reported to the frontend.
Definition: light_state.h:77
LockState
Enum for all states a lock can be in.
Definition: lock.h:26
void light_command(const LightCommandRequest &msg) override
bool send_lock_info(lock::Lock *a_lock)
bool send_list_entities_time_response(const ListEntitiesTimeResponse &msg)
NumberMode get_mode() const
Definition: number_traits.h:29
bool send_alarm_control_panel_state_response(const AlarmControlPanelStateResponse &msg)
bool send_list_entities_climate_response(const ListEntitiesClimateResponse &msg)
int8_t get_accuracy_decimals()
Get the accuracy in decimals, using the manual override if set.
Definition: sensor.cpp:25
LightCall & set_white(optional< float > white)
Set the white value value of the light from 0.0 to 1.0 for RGBW[W] lights.
Definition: light_call.cpp:625
LightCall & set_brightness(optional< float > brightness)
Set the target brightness of the light from 0.0 (fully off) to 1.0 (fully on)
Definition: light_call.cpp:577
void number_command(const NumberCommandRequest &msg) override
ListEntitiesIterator list_entities_iterator_
void subscribe_api_connection(api::APIConnection *api_connection, uint32_t flags)
int get_min_length() const
Definition: text_traits.h:19
bool send_switch_info(switch_::Switch *a_switch)
bool send_text_sensor_info(text_sensor::TextSensor *text_sensor)
enums::LegacyCoverCommand legacy_command
Definition: api_pb2.h:452
Base-class for all sensors.
Definition: sensor.h:57
std::string get_mac_address_pretty()
Get the device MAC address as a string, in colon-separated uppercase hex notation.
Definition: helpers.cpp:592
datetime::TimeEntity * get_time_by_key(uint32_t key, bool include_internal=false)
Definition: application.h:317
bool send_lock_state_response(const LockStateResponse &msg)
void on_home_assistant_state_response(const HomeAssistantStateResponse &msg) override
virtual uint32_t get_supported_features() const =0
A numeric representation of the supported features as per HomeAssistant.
LightCall & set_blue(optional< float > blue)
Set the blue RGB value of the light from 0.0 to 1.0.
Definition: light_call.cpp:617
std::vector< enums::ClimateSwingMode > supported_swing_modes
Definition: api_pb2.h:986
void on_voice_assistant_event_response(const VoiceAssistantEventResponse &msg) override
enums::SensorStateClass state_class
Definition: api_pb2.h:637
HelloResponse hello(const HelloRequest &msg) override
std::string get_compilation_time() const
Definition: application.h:187
bool send_bluetooth_le_advertisement(const BluetoothLEAdvertisementResponse &msg)
enums::EntityCategory entity_category
Definition: api_pb2.h:551
bool send_time_state_response(const TimeStateResponse &msg)
enums::EntityCategory entity_category
Definition: api_pb2.h:992
std::vector< uint8_t > container
enums::MediaPlayerCommand command
Definition: api_pb2.h:1291
MediaPlayerCall & set_media_url(const std::string &url)
bool is_disabled_by_default() const
Definition: entity_base.cpp:26
void climate_command(const ClimateCommandRequest &msg) override
bool send_number_state(number::Number *number, float state)
APIConnection(std::unique_ptr< socket::Socket > socket, APIServer *parent)
ProtoWriteBuffer create_buffer() override
uint8_t custom_fan_mode
Definition: climate.h:574
bool get_supports_open() const
Definition: lock.h:40
uint32_t get_object_id_hash()
Definition: entity_base.cpp:76
std::string get_pattern() const
Definition: text_traits.h:25
float target_temperature_low
The minimum target temperature of the climate device, for climate devices with split target temperatu...
Definition: climate.h:189
SelectCall & set_option(const std::string &option)
Definition: select_call.cpp:10
void cover_command(const CoverCommandRequest &msg) override
void bluetooth_gatt_send_services(const api::BluetoothGATTGetServicesRequest &msg)
std::vector< enums::ClimateMode > supported_modes
Definition: api_pb2.h:979
const StringRef & get_name() const
Definition: entity_base.cpp:10
void bluetooth_gatt_read(const BluetoothGATTReadRequest &msg) override
void camera_image(const CameraImageRequest &msg) override
FanCall & set_direction(FanDirection direction)
Definition: fan.h:66
ClimatePreset preset
Definition: climate.h:578
MediaPlayerCall & set_volume(float volume)
Base class for all locks.
Definition: lock.h:103
ClimateAction action
The active state of the climate device.
Definition: climate.h:176
ClimateDevice - This is the base class for all climate integrations.
Definition: climate.h:168
void on_event(const api::VoiceAssistantEventResponse &msg)
bool state
Definition: fan.h:34
void turn_off()
Turn this switch off.
Definition: switch.cpp:15
void IRAM_ATTR HOT delay(uint32_t ms)
Definition: core.cpp:26
virtual bool get_requires_code_to_arm() const =0
Returns if the alarm_control_panel requires a code to arm.
void fan_command(const FanCommandRequest &msg) override
enums::EntityCategory entity_category
Definition: api_pb2.h:1930