7#ifdef USE_API_PLAINTEXT
10#ifdef USE_API_USER_DEFINED_ACTIONS
28#ifdef USE_PROVISIONING
35#ifdef USE_HOMEASSISTANT_TIME
38#ifdef USE_BLUETOOTH_PROXY
44#ifdef USE_VOICE_ASSISTANT
50#ifdef USE_WATER_HEATER
56#ifdef USE_RADIO_FREQUENCY
66static constexpr uint8_t MAX_MESSAGES_PER_LOOP = 10;
67static constexpr uint8_t MAX_PING_RETRIES = 60;
68static constexpr uint16_t PING_RETRY_INTERVAL = 1000;
69static constexpr uint32_t KEEPALIVE_DISCONNECT_TIMEOUT = (KEEPALIVE_TIMEOUT_MS * 5) / 2;
78static constexpr uint32_t HANDSHAKE_TIMEOUT_MS = 60000;
83static_assert(MAC_ADDRESS_PRETTY_BUFFER_SIZE - 1 == 17,
84 "Update max_data_length for mac_address/bluetooth_mac_address in api.proto");
86static_assert(
sizeof(ESPHOME_VERSION) - 1 <= 32,
"Update max_data_length for esphome_version in api.proto");
87static_assert(ESPHOME_DEVICE_NAME_MAX_LEN <= 31,
"Update max_data_length for name in api.proto");
88static_assert(ESPHOME_FRIENDLY_NAME_MAX_LEN <= 120,
"Update max_data_length for friendly_name in api.proto");
90static const char *
const TAG =
"api.connection";
92static const int CAMERA_STOP_STREAM = 5000;
98#define ENTITY_COMMAND_MAKE_CALL(entity_type, entity_var, getter_name) \
99 entity_type *entity_var = App.get_##getter_name##_by_key(msg.key, msg.device_id); \
100 if ((entity_var) == nullptr) \
102 auto call = (entity_var)->make_call();
106#define ENTITY_COMMAND_GET(entity_type, entity_var, getter_name) \
107 entity_type *entity_var = App.get_##getter_name##_by_key(msg.key, msg.device_id); \
108 if ((entity_var) == nullptr) \
113#define ENTITY_COMMAND_LOOKUP(entity_type, entity_var, getter_name) \
114 entity_type *entity_var = App.get_##getter_name##_by_key(msg.key, msg.device_id)
119#define ENTITY_COMMAND_MAKE_CALL(entity_type, entity_var, getter_name) \
120 entity_type *entity_var = App.get_##getter_name##_by_key(msg.key); \
121 if ((entity_var) == nullptr) \
123 auto call = (entity_var)->make_call();
127#define ENTITY_COMMAND_GET(entity_type, entity_var, getter_name) \
128 entity_type *entity_var = App.get_##getter_name##_by_key(msg.key); \
129 if ((entity_var) == nullptr) \
134#define ENTITY_COMMAND_LOOKUP(entity_type, entity_var, getter_name) \
135 entity_type *entity_var = App.get_##getter_name##_by_key(msg.key)
140#if defined(USE_API_PLAINTEXT) && defined(USE_API_NOISE)
142 if (noise_ctx.has_psk()) {
143 this->helper_ = std::unique_ptr<APIFrameHelper>{new APINoiseFrameHelper(std::move(sock), noise_ctx)};
147#elif defined(USE_API_PLAINTEXT)
148 this->helper_ = std::unique_ptr<APIPlaintextFrameHelper>{
new APIPlaintextFrameHelper(std::move(sock))};
149#elif defined(USE_API_NOISE)
151 std::unique_ptr<APINoiseFrameHelper>{
new APINoiseFrameHelper(std::move(sock), parent->get_noise_ctx())};
153#error "No frame helper defined"
162void APIConnection::start() {
165 APIError err = this->helper_->init();
166 if (err != APIError::OK) {
167 this->fatal_error_with_log_(LOG_STR(
"Helper init failed"), err);
171 char peername[socket::SOCKADDR_STR_LEN];
172 this->helper_->set_client_name(this->helper_->get_peername_to(peername), strlen(peername));
175APIConnection::~APIConnection() {
176 this->destroy_active_iterator_();
177#ifdef USE_BLUETOOTH_PROXY
182#ifdef USE_VOICE_ASSISTANT
187#ifdef USE_ZWAVE_PROXY
192#ifdef USE_SERIAL_PROXY
194 if (proxy->get_api_connection() ==
this) {
195 proxy->serial_proxy_request(
this, enums::SERIAL_PROXY_REQUEST_TYPE_UNSUBSCRIBE);
201#if defined(USE_API_NOISE) && defined(USE_API_PLAINTEXT)
202void APIConnection::upgrade_helper_to_noise_() {
212 auto *noise =
new APINoiseFrameHelper(plaintext->release_socket_for_switch(), this->parent_->get_noise_ctx());
214 const char *name = plaintext->get_client_name();
215 noise->set_client_name(name, strlen(name));
216 this->helper_.reset(noise);
217 APIError err = noise->init_from_handoff(header, header_len);
218 if (err != APIError::OK) {
219 this->fatal_error_with_log_(LOG_STR(
"Noise handoff failed"), err);
224void APIConnection::destroy_active_iterator_() {
225 switch (this->active_iterator_) {
226 case ActiveIterator::LIST_ENTITIES:
227 this->iterator_storage_.list_entities.~ListEntitiesIterator();
229 case ActiveIterator::INITIAL_STATE:
230 this->iterator_storage_.initial_state.~InitialStateIterator();
232 case ActiveIterator::NONE:
235 this->active_iterator_ = ActiveIterator::NONE;
239 this->destroy_active_iterator_();
240 this->active_iterator_ =
type;
241 if (
type == ActiveIterator::LIST_ENTITIES) {
243 this->iterator_storage_.list_entities.
begin();
246 this->iterator_storage_.initial_state.
begin();
250void APIConnection::loop() {
251 if (this->flags_.next_close) {
254 this->flags_.remove =
true;
258 APIError err = this->helper_->loop();
259 if (err != APIError::OK) {
260 this->fatal_error_with_log_(LOG_STR(
"Socket operation failed"), err);
271 if (this->helper_->is_socket_ready() || this->flags_.may_have_remaining_data) {
272 this->flags_.may_have_remaining_data =
false;
274 uint8_t message_count = 0;
275 for (; message_count < MAX_MESSAGES_PER_LOOP; message_count++) {
277 err = this->helper_->read_packet(&buffer);
278 if (err == APIError::WOULD_BLOCK) {
281 }
else if (err != APIError::OK) {
282#if defined(USE_API_NOISE) && defined(USE_API_PLAINTEXT)
286 if (err == APIError::PROTOCOL_SWITCH_TO_NOISE) {
287 this->upgrade_helper_to_noise_();
291 this->fatal_error_with_log_(LOG_STR(
"Reading failed"), err);
297 if (this->is_authenticated()) {
298 this->last_traffic_ = now;
302 if (this->flags_.remove)
308 if (message_count == MAX_MESSAGES_PER_LOOP) {
309 this->flags_.may_have_remaining_data =
true;
314 if (this->flags_.batch_scheduled && now - this->deferred_batch_.batch_start_time >= this->get_batch_delay_ms_()) {
315 this->process_batch_();
318 if (this->active_iterator_ != ActiveIterator::NONE) {
319 this->process_active_iterator_();
325 if (!this->is_authenticated() && now - this->last_traffic_ > HANDSHAKE_TIMEOUT_MS) {
326 this->on_fatal_error();
327 this->log_client_(ESPHOME_LOG_LEVEL_WARN, LOG_STR(
"handshake timeout; disconnecting"));
334 if (now - this->last_traffic_ > KEEPALIVE_TIMEOUT_MS) {
335 this->check_keepalive_(now);
338#ifdef USE_API_HOMEASSISTANT_STATES
339 if (state_subs_at_ >= 0) {
340 this->process_state_subscriptions_();
347 this->try_send_camera_image_();
351void APIConnection::check_keepalive_(
uint32_t now) {
353 if (this->flags_.sent_ping) {
355 if (now - this->last_traffic_ > KEEPALIVE_DISCONNECT_TIMEOUT) {
357 this->log_client_(ESPHOME_LOG_LEVEL_WARN, LOG_STR(
"is unresponsive; disconnecting"));
359 }
else if (!this->flags_.remove) {
361 ESP_LOGVV(TAG,
"Sending keepalive PING");
363 this->flags_.sent_ping = this->send_message(req);
364 if (!this->flags_.sent_ping) {
367 ESP_LOGW(TAG,
"Buffer full, ping queued");
368 this->schedule_message_front_(
nullptr, PingRequest::MESSAGE_TYPE, PingRequest::ESTIMATED_SIZE);
369 this->flags_.sent_ping =
true;
374void APIConnection::process_active_iterator_() {
376 if (this->active_iterator_ == ActiveIterator::LIST_ENTITIES) {
377 if (this->iterator_storage_.list_entities.completed()) {
378 this->destroy_active_iterator_();
379 if (this->flags_.state_subscription) {
380 this->begin_iterator_(ActiveIterator::INITIAL_STATE);
382 this->finalize_iterator_sync_();
385 this->process_iterator_batch_(this->iterator_storage_.list_entities);
388 if (this->iterator_storage_.initial_state.completed()) {
389 this->destroy_active_iterator_();
390 this->finalize_iterator_sync_();
392 this->process_iterator_batch_(this->iterator_storage_.initial_state);
397void APIConnection::finalize_iterator_sync_() {
401 if (!this->deferred_batch_.empty()) {
402 this->process_batch_();
405 this->flags_.should_try_send_immediately =
true;
407 this->deferred_batch_.release_buffer();
408 this->helper_->release_buffers();
412 size_t initial_size = this->deferred_batch_.size();
413 size_t max_batch = MAX_INITIAL_PER_BATCH;
414 while (!iterator.
completed() && (this->deferred_batch_.size() - initial_size) < max_batch) {
420 if (this->deferred_batch_.size() >= max_batch) {
421 this->process_batch_();
425bool APIConnection::send_disconnect_response_() {
429 this->log_client_(ESPHOME_LOG_LEVEL_DEBUG, LOG_STR(
"disconnected"));
430 this->flags_.next_close =
true;
432 return this->send_message(resp);
434void APIConnection::on_disconnect_response() {
437 this->flags_.remove =
true;
447 return encode_to_buffer(size_fn(&msg), encode_fn, &msg, conn, remaining_size);
461#ifdef USE_ENTITY_ICON
462 char icon_buf[MAX_ICON_LENGTH];
470 return encode_to_buffer_slow(size_fn(&msg), encode_fn, &msg, conn, remaining_size);
478 char dc_buf[MAX_DEVICE_CLASS_LENGTH];
480 return fill_and_encode_entity_info(entity, msg, size_fn, encode_fn, conn, remaining_size);
483#ifdef USE_BINARY_SENSOR
485 return this->send_message_smart_(binary_sensor, BinarySensorStateResponse::MESSAGE_TYPE,
486 BinarySensorStateResponse::ESTIMATED_SIZE);
492 resp.
state = binary_sensor->state;
494 return fill_and_encode_entity_state(binary_sensor, resp, conn, remaining_size);
501 return fill_and_encode_entity_info_with_device_class(binary_sensor, msg, msg.
device_class, conn, remaining_size);
507 return this->send_message_smart_(cover, CoverStateResponse::MESSAGE_TYPE, CoverStateResponse::ESTIMATED_SIZE);
512 auto traits = cover->get_traits();
514 if (traits.get_supports_tilt())
515 msg.
tilt = cover->tilt;
517 return fill_and_encode_entity_state(cover, msg, conn, remaining_size);
522 auto traits = cover->get_traits();
527 return fill_and_encode_entity_info_with_device_class(cover, msg, msg.
device_class, conn, remaining_size);
534 call.set_tilt(msg.
tilt);
536 call.set_command_stop();
543 return this->send_message_smart_(fan, FanStateResponse::MESSAGE_TYPE, FanStateResponse::ESTIMATED_SIZE);
546 auto *fan =
static_cast<fan::Fan *
>(entity);
548 auto traits = fan->get_traits();
549 msg.
state = fan->state;
550 if (traits.supports_oscillation())
552 if (traits.supports_speed()) {
555 if (traits.supports_direction())
557 if (traits.supports_preset_modes() && fan->has_preset_mode())
559 return fill_and_encode_entity_state(fan, msg, conn, remaining_size);
562 auto *fan =
static_cast<fan::Fan *
>(entity);
564 auto traits = fan->get_traits();
570 return fill_and_encode_entity_info(fan, msg, conn, remaining_size);
573 ENTITY_COMMAND_MAKE_CALL(
fan::Fan, fan, fan)
575 call.set_state(msg.
state);
592 return this->send_message_smart_(light, LightStateResponse::MESSAGE_TYPE, LightStateResponse::ESTIMATED_SIZE);
597 auto values = light->remote_values;
598 auto color_mode = values.get_color_mode();
599 resp.
state = values.is_on();
603 resp.
red = values.get_red();
604 resp.
green = values.get_green();
605 resp.
blue = values.get_blue();
606 resp.
white = values.get_white();
610 if (light->supports_effects()) {
611 resp.
effect = light->get_effect_name();
613 return fill_and_encode_entity_state(light, resp, conn, remaining_size);
618 auto traits = light->get_traits();
619 auto supported_modes = traits.get_supported_color_modes();
628 if (light->supports_effects()) {
629 auto &light_effects = light->get_effects();
630 effects_list.
init(light_effects.size() + 1);
632 for (
auto *effect : light_effects) {
634 effects_list.
push_back(effect->get_name().c_str());
638 return fill_and_encode_entity_info(light, msg, conn, remaining_size);
643 call.set_state(msg.
state);
651 call.set_red(msg.
red);
652 call.set_green(msg.
green);
653 call.set_blue(msg.
blue);
656 call.set_white(msg.
white);
675 return this->send_message_smart_(sensor, SensorStateResponse::MESSAGE_TYPE, SensorStateResponse::ESTIMATED_SIZE);
681 resp.
state = sensor->state;
683 return fill_and_encode_entity_state(sensor, resp, conn, remaining_size);
693 return fill_and_encode_entity_info_with_device_class(sensor, msg, msg.
device_class, conn, remaining_size);
699 return this->send_message_smart_(a_switch, SwitchStateResponse::MESSAGE_TYPE, SwitchStateResponse::ESTIMATED_SIZE);
705 resp.
state = a_switch->state;
706 return fill_and_encode_entity_state(a_switch, resp, conn, remaining_size);
713 return fill_and_encode_entity_info_with_device_class(a_switch, msg, msg.
device_class, conn, remaining_size);
721 a_switch->turn_off();
726#ifdef USE_TEXT_SENSOR
728 return this->send_message_smart_(text_sensor, TextSensorStateResponse::MESSAGE_TYPE,
729 TextSensorStateResponse::ESTIMATED_SIZE);
737 return fill_and_encode_entity_state(text_sensor, resp, conn, remaining_size);
742 return fill_and_encode_entity_info_with_device_class(text_sensor, msg, msg.
device_class, conn, remaining_size);
748 return this->send_message_smart_(climate, ClimateStateResponse::MESSAGE_TYPE, ClimateStateResponse::ESTIMATED_SIZE);
753 auto traits = climate->get_traits();
765 if (traits.get_supports_fan_modes() && climate->fan_mode.has_value())
767 if (!traits.get_supported_custom_fan_modes().empty() && climate->has_custom_fan_mode()) {
770 if (traits.get_supports_presets() && climate->preset.has_value()) {
773 if (!traits.get_supported_custom_presets().empty() && climate->has_custom_preset()) {
776 if (traits.get_supports_swing_modes())
782 return fill_and_encode_entity_state(climate, resp, conn, remaining_size);
787 auto traits = climate->get_traits();
810 return fill_and_encode_entity_info(climate, msg, conn, remaining_size);
840 return this->send_message_smart_(number, NumberStateResponse::MESSAGE_TYPE, NumberStateResponse::ESTIMATED_SIZE);
846 resp.
state = number->state;
848 return fill_and_encode_entity_state(number, resp, conn, remaining_size);
856 msg.
min_value = number->traits.get_min_value();
857 msg.
max_value = number->traits.get_max_value();
858 msg.
step = number->traits.get_step();
859 return fill_and_encode_entity_info_with_device_class(number, msg, msg.
device_class, conn, remaining_size);
863 call.set_value(msg.
state);
868#ifdef USE_DATETIME_DATE
870 return this->send_message_smart_(date, DateStateResponse::MESSAGE_TYPE, DateStateResponse::ESTIMATED_SIZE);
876 resp.
year = date->year;
877 resp.
month = date->month;
878 resp.
day = date->day;
879 return fill_and_encode_entity_state(date, resp, conn, remaining_size);
884 return fill_and_encode_entity_info(date, msg, conn, remaining_size);
893#ifdef USE_DATETIME_TIME
895 return this->send_message_smart_(time, TimeStateResponse::MESSAGE_TYPE, TimeStateResponse::ESTIMATED_SIZE);
901 resp.
hour = time->hour;
902 resp.
minute = time->minute;
903 resp.
second = time->second;
904 return fill_and_encode_entity_state(time, resp, conn, remaining_size);
909 return fill_and_encode_entity_info(time, msg, conn, remaining_size);
918#ifdef USE_DATETIME_DATETIME
920 return this->send_message_smart_(datetime, DateTimeStateResponse::MESSAGE_TYPE,
921 DateTimeStateResponse::ESTIMATED_SIZE);
927 if (datetime->has_state()) {
931 return fill_and_encode_entity_state(datetime, resp, conn, remaining_size);
936 return fill_and_encode_entity_info(datetime, msg, conn, remaining_size);
947 return this->send_message_smart_(text, TextStateResponse::MESSAGE_TYPE, TextStateResponse::ESTIMATED_SIZE);
951 auto *text =
static_cast<text::Text *
>(entity);
955 return fill_and_encode_entity_state(text, resp, conn, remaining_size);
959 auto *text =
static_cast<text::Text *
>(entity);
962 msg.
min_length = text->traits.get_min_length();
963 msg.
max_length = text->traits.get_max_length();
964 msg.
pattern = text->traits.get_pattern_ref();
965 return fill_and_encode_entity_info(text, msg, conn, remaining_size);
968 ENTITY_COMMAND_MAKE_CALL(
text::Text, text, text)
976 return this->send_message_smart_(select, SelectStateResponse::MESSAGE_TYPE, SelectStateResponse::ESTIMATED_SIZE);
982 resp.
state = select->current_option();
984 return fill_and_encode_entity_state(select, resp, conn, remaining_size);
990 msg.
options = &select->traits.get_options();
991 return fill_and_encode_entity_info(select, msg, conn, remaining_size);
1004 return fill_and_encode_entity_info_with_device_class(button, msg, msg.
device_class, conn, remaining_size);
1014 return this->send_message_smart_(a_lock, LockStateResponse::MESSAGE_TYPE, LockStateResponse::ESTIMATED_SIZE);
1018 auto *a_lock =
static_cast<lock::Lock *
>(entity);
1021 return fill_and_encode_entity_state(a_lock, resp, conn, remaining_size);
1025 auto *a_lock =
static_cast<lock::Lock *
>(entity);
1030 return fill_and_encode_entity_info(a_lock, msg, conn, remaining_size);
1036 case enums::LOCK_UNLOCK:
1039 case enums::LOCK_LOCK:
1042 case enums::LOCK_OPEN:
1051 return this->send_message_smart_(valve, ValveStateResponse::MESSAGE_TYPE, ValveStateResponse::ESTIMATED_SIZE);
1058 return fill_and_encode_entity_state(valve, resp, conn, remaining_size);
1063 auto traits = valve->get_traits();
1067 return fill_and_encode_entity_info_with_device_class(valve, msg, msg.
device_class, conn, remaining_size);
1074 call.set_command_stop();
1079#ifdef USE_MEDIA_PLAYER
1081 return this->send_message_smart_(media_player, MediaPlayerStateResponse::MESSAGE_TYPE,
1082 MediaPlayerStateResponse::ESTIMATED_SIZE);
1089 : media_player->state;
1091 resp.
volume = media_player->volume;
1092 resp.
muted = media_player->is_muted();
1093 return fill_and_encode_entity_state(media_player, resp, conn, remaining_size);
1098 auto traits = media_player->get_traits();
1101 for (
auto &supported_format : traits.get_supported_formats()) {
1104 media_format.format =
StringRef(supported_format.format);
1105 media_format.sample_rate = supported_format.sample_rate;
1106 media_format.num_channels = supported_format.num_channels;
1108 media_format.sample_bytes = supported_format.sample_bytes;
1110 return fill_and_encode_entity_info(media_player, msg, conn, remaining_size);
1118 call.set_volume(msg.
volume);
1131void APIConnection::try_send_camera_image_() {
1132 if (!this->image_reader_)
1136 while (this->image_reader_->available()) {
1137 if (!this->helper_->can_write_without_blocking())
1140 uint32_t to_send = std::min((
size_t) MAX_BATCH_PACKET_SIZE, this->image_reader_->available());
1141 bool done = this->image_reader_->available() == to_send;
1145 msg.
set_data(this->image_reader_->peek_data_buffer(), to_send);
1151 if (!this->send_message(msg)) {
1154 this->image_reader_->consume_data(to_send);
1156 this->image_reader_->return_image();
1161void APIConnection::set_camera_state(std::shared_ptr<camera::CameraImage> image) {
1162 if (!this->flags_.state_subscription)
1164 if (!this->image_reader_)
1166 if (this->image_reader_->available())
1169 this->image_reader_->set_image(std::move(image));
1171 this->try_send_camera_image_();
1177 return fill_and_encode_entity_info(camera, msg, conn, remaining_size);
1188 App.
scheduler.set_timeout(this->parent_,
"api_camera_stop_stream", CAMERA_STOP_STREAM,
1194#ifdef USE_HOMEASSISTANT_TIME
1198#if defined(USE_HOMEASSISTANT_TIMEZONE) && defined(USE_TIME_TIMEZONE)
1204 if (pt.std_offset_seconds != 0 || pt.dst_start.type != enums::DST_RULE_TYPE_NONE) {
1209 tz.
dst_start.
day =
static_cast<uint16_t
>(pt.dst_start.day);
1212 tz.
dst_start.
week =
static_cast<uint8_t
>(pt.dst_start.week);
1215 tz.
dst_end.
day =
static_cast<uint16_t
>(pt.dst_end.day);
1217 tz.
dst_end.
month =
static_cast<uint8_t
>(pt.dst_end.month);
1218 tz.
dst_end.
week =
static_cast<uint8_t
>(pt.dst_end.week);
1230#ifdef USE_BLUETOOTH_PROXY
1231void APIConnection::on_subscribe_bluetooth_le_advertisements_request(
1235void APIConnection::on_unsubscribe_bluetooth_le_advertisements_request() {
1261bool APIConnection::send_subscribe_bluetooth_connections_free_response_() {
1265void APIConnection::on_subscribe_bluetooth_connections_free_request() {
1266 if (!this->send_subscribe_bluetooth_connections_free_response_()) {
1267 this->on_fatal_error();
1273 msg.
mode == enums::BluetoothScannerMode::BLUETOOTH_SCANNER_MODE_ACTIVE);
1280#ifdef USE_VOICE_ASSISTANT
1281bool APIConnection::check_voice_assistant_api_connection_()
const {
1292 if (!this->check_voice_assistant_api_connection_()) {
1300 if (msg.
port == 0) {
1306 this->helper_->getpeername((
struct sockaddr *) &storage, &
len);
1311 if (this->check_voice_assistant_api_connection_()) {
1316 if (this->check_voice_assistant_api_connection_()) {
1321 if (this->check_voice_assistant_api_connection_()) {
1327 if (this->check_voice_assistant_api_connection_()) {
1334 if (!this->check_voice_assistant_api_connection_()) {
1336 const std::vector<std::string> empty_wake_words;
1338 return this->send_message(resp);
1342 for (
auto &wake_word : config.available_wake_words) {
1345 resp_wake_word.id =
StringRef(wake_word.id);
1346 resp_wake_word.wake_word =
StringRef(wake_word.wake_word);
1347 for (
const auto &lang : wake_word.trained_languages) {
1348 resp_wake_word.trained_languages.push_back(lang);
1354 if (wake_word.model_type !=
"micro") {
1361 resp_wake_word.id =
StringRef(wake_word.id);
1362 resp_wake_word.wake_word =
StringRef(wake_word.wake_word);
1363 for (
const auto &lang : wake_word.trained_languages) {
1364 resp_wake_word.trained_languages.push_back(lang);
1370 return this->send_message(resp);
1373 if (!this->send_voice_assistant_get_configuration_response_(msg)) {
1374 this->on_fatal_error();
1379 if (this->check_voice_assistant_api_connection_()) {
1385#ifdef USE_ZWAVE_PROXY
1395#ifdef USE_ALARM_CONTROL_PANEL
1397 return this->send_message_smart_(a_alarm_control_panel, AlarmControlPanelStateResponse::MESSAGE_TYPE,
1398 AlarmControlPanelStateResponse::ESTIMATED_SIZE);
1405 return fill_and_encode_entity_state(a_alarm_control_panel, resp, conn, remaining_size);
1412 msg.
requires_code = a_alarm_control_panel->get_requires_code();
1414 return fill_and_encode_entity_info(a_alarm_control_panel, msg, conn, remaining_size);
1419 case enums::ALARM_CONTROL_PANEL_DISARM:
1422 case enums::ALARM_CONTROL_PANEL_ARM_AWAY:
1425 case enums::ALARM_CONTROL_PANEL_ARM_HOME:
1428 case enums::ALARM_CONTROL_PANEL_ARM_NIGHT:
1431 case enums::ALARM_CONTROL_PANEL_ARM_VACATION:
1432 call.arm_vacation();
1434 case enums::ALARM_CONTROL_PANEL_ARM_CUSTOM_BYPASS:
1435 call.arm_custom_bypass();
1437 case enums::ALARM_CONTROL_PANEL_TRIGGER:
1446#ifdef USE_WATER_HEATER
1448 return this->send_message_smart_(water_heater, WaterHeaterStateResponse::MESSAGE_TYPE,
1449 WaterHeaterStateResponse::ESTIMATED_SIZE);
1459 resp.
state = wh->get_state();
1461 return fill_and_encode_entity_state(wh, resp, conn, remaining_size);
1466 auto traits = wh->get_traits();
1473 return fill_and_encode_entity_info(wh, msg, conn, remaining_size);
1478 if (msg.
has_fields & enums::WATER_HEATER_COMMAND_HAS_MODE)
1480 if (msg.
has_fields & enums::WATER_HEATER_COMMAND_HAS_TARGET_TEMPERATURE)
1482 if (msg.
has_fields & enums::WATER_HEATER_COMMAND_HAS_TARGET_TEMPERATURE_LOW)
1484 if (msg.
has_fields & enums::WATER_HEATER_COMMAND_HAS_TARGET_TEMPERATURE_HIGH)
1486 if ((msg.
has_fields & enums::WATER_HEATER_COMMAND_HAS_AWAY_STATE) ||
1487 (msg.
has_fields & enums::WATER_HEATER_COMMAND_HAS_STATE)) {
1490 if ((msg.
has_fields & enums::WATER_HEATER_COMMAND_HAS_ON_STATE) ||
1491 (msg.
has_fields & enums::WATER_HEATER_COMMAND_HAS_STATE)) {
1502 this->send_message_smart_(event, EventResponse::MESSAGE_TYPE, EventResponse::ESTIMATED_SIZE,
1509 return fill_and_encode_entity_state(event, resp, conn, remaining_size);
1516 return fill_and_encode_entity_info_with_device_class(event, msg, msg.
device_class, conn, remaining_size);
1520#if defined(USE_IR_RF) || defined(USE_RADIO_FREQUENCY)
1526 if (infrared !=
nullptr) {
1527 auto call = infrared->make_call();
1535#ifdef USE_RADIO_FREQUENCY
1537 if (radio_frequency !=
nullptr) {
1538 auto call = radio_frequency->make_call();
1549#if defined(USE_IR_RF) || defined(USE_RADIO_FREQUENCY)
1553#ifdef USE_SERIAL_PROXY
1556 if (msg.
instance >= proxies.size()) {
1557 ESP_LOGW(TAG,
"Serial proxy instance %" PRIu32
" out of range (max %" PRIu32
")", msg.
instance,
1558 static_cast<uint32_t>(proxies.size()));
1567 if (msg.
instance >= proxies.size()) {
1568 ESP_LOGW(TAG,
"Serial proxy instance %" PRIu32
" out of range", msg.
instance);
1576 if (msg.
instance >= proxies.size()) {
1577 ESP_LOGW(TAG,
"Serial proxy instance %" PRIu32
" out of range", msg.
instance);
1585 if (msg.
instance >= proxies.size()) {
1586 ESP_LOGW(TAG,
"Serial proxy instance %" PRIu32
" out of range", msg.
instance);
1591 resp.line_states = proxies[msg.
instance]->get_modem_pins();
1592 this->send_message(resp);
1597 if (msg.
instance >= proxies.size()) {
1598 ESP_LOGW(TAG,
"Serial proxy instance %" PRIu32
" out of range", msg.
instance);
1602 case enums::SERIAL_PROXY_REQUEST_TYPE_SUBSCRIBE:
1603 case enums::SERIAL_PROXY_REQUEST_TYPE_UNSUBSCRIBE:
1604 proxies[msg.
instance]->serial_proxy_request(
this, msg.
type);
1606 case enums::SERIAL_PROXY_REQUEST_TYPE_FLUSH: {
1609 resp.type = enums::SERIAL_PROXY_REQUEST_TYPE_FLUSH;
1610 switch (proxies[msg.
instance]->flush_port()) {
1612 resp.status = enums::SERIAL_PROXY_STATUS_OK;
1615 resp.status = enums::SERIAL_PROXY_STATUS_ASSUMED_SUCCESS;
1618 resp.status = enums::SERIAL_PROXY_STATUS_TIMEOUT;
1621 resp.status = enums::SERIAL_PROXY_STATUS_ERROR;
1624 this->send_message(resp);
1628 ESP_LOGW(TAG,
"Unknown serial proxy request type: %" PRIu32,
static_cast<uint32_t>(msg.
type));
1642 return fill_and_encode_entity_info(infrared, msg, conn, remaining_size);
1646#ifdef USE_RADIO_FREQUENCY
1652 msg.
frequency_min = rf->get_traits().get_frequency_min_hz();
1653 msg.
frequency_max = rf->get_traits().get_frequency_max_hz();
1655 return fill_and_encode_entity_info(rf, msg, conn, remaining_size);
1661 return this->send_message_smart_(update, UpdateStateResponse::MESSAGE_TYPE, UpdateStateResponse::ESTIMATED_SIZE);
1667 if (update->has_state()) {
1669 if (update->update_info.has_progress) {
1671 resp.
progress = update->update_info.progress;
1679 return fill_and_encode_entity_state(update, resp, conn, remaining_size);
1684 return fill_and_encode_entity_info_with_device_class(update, msg, msg.
device_class, conn, remaining_size);
1690 case enums::UPDATE_COMMAND_UPDATE:
1693 case enums::UPDATE_COMMAND_CHECK:
1696 case enums::UPDATE_COMMAND_NONE:
1697 ESP_LOGE(TAG,
"UPDATE_COMMAND_NONE not handled; confirm command is correct");
1700 ESP_LOGW(TAG,
"Unknown update command: %" PRIu32, msg.
command);
1706bool APIConnection::try_send_log_message(
int level,
const char *
tag,
const char *
line,
size_t message_len) {
1709 msg.
set_message(
reinterpret_cast<const uint8_t *
>(
line), message_len);
1710 return this->send_message(msg);
1713void APIConnection::complete_authentication_() {
1715 if (this->flags_.connection_state ==
static_cast<uint8_t
>(ConnectionState::AUTHENTICATED)) {
1719 this->flags_.connection_state =
static_cast<uint8_t
>(ConnectionState::AUTHENTICATED);
1722 this->log_client_(ESPHOME_LOG_LEVEL_DEBUG, LOG_STR(
"connected"));
1723#ifdef USE_API_CLIENT_CONNECTED_TRIGGER
1725 char peername[socket::SOCKADDR_STR_LEN];
1726 this->parent_->get_client_connected_trigger()->trigger(std::string(this->helper_->get_client_name()),
1727 std::string(this->helper_->get_peername_to(peername)));
1730#ifdef USE_HOMEASSISTANT_TIME
1732 this->send_time_request();
1735#ifdef USE_ZWAVE_PROXY
1747 char peername[socket::SOCKADDR_STR_LEN];
1748 ESP_LOGV(TAG,
"Hello from client: '%s' | %s | API Version %" PRIu16
".%" PRIu16, this->helper_->get_client_name(),
1749 this->helper_->get_peername_to(peername), this->client_api_version_major_, this->client_api_version_minor_);
1758#ifdef USE_PROVISIONING
1763 this->log_client_(ESPHOME_LOG_LEVEL_WARN, LOG_STR(
"Provisioning closed; rejecting connection"));
1764 this->send_message(resp);
1766 req.
reason = enums::DISCONNECT_REASON_PROVISIONING_CLOSED;
1767 return this->send_message(req);
1772 this->complete_authentication_();
1774 return this->send_message(resp);
1777bool APIConnection::send_ping_response_() {
1779 return this->send_message(resp);
1782bool APIConnection::send_device_info_response_() {
1790 char mac_address[18];
1804#if defined(USE_ESP8266) || defined(USE_ESP32)
1805#define ESPHOME_MANUFACTURER "Espressif"
1806#elif defined(USE_RP2)
1807#define ESPHOME_MANUFACTURER "Raspberry Pi"
1808#elif defined(USE_BK72XX)
1809#define ESPHOME_MANUFACTURER "Beken"
1810#elif defined(USE_LN882X)
1811#define ESPHOME_MANUFACTURER "Lightning"
1812#elif defined(USE_NRF52)
1813#define ESPHOME_MANUFACTURER "Nordic Semiconductor"
1814#elif defined(USE_RTL87XX)
1815#define ESPHOME_MANUFACTURER "Realtek"
1816#elif defined(USE_HOST)
1817#define ESPHOME_MANUFACTURER "Host"
1822 static const char MANUFACTURER_PROGMEM[]
PROGMEM = ESPHOME_MANUFACTURER;
1823 char manufacturer_buf[
sizeof(MANUFACTURER_PROGMEM)];
1824 memcpy_P(manufacturer_buf, MANUFACTURER_PROGMEM,
sizeof(MANUFACTURER_PROGMEM));
1830 static_assert(
sizeof(ESPHOME_MANUFACTURER) - 1 <= 20,
"Update max_data_length for manufacturer in api.proto");
1831#undef ESPHOME_MANUFACTURER
1834 static const char MODEL_PROGMEM[]
PROGMEM = ESPHOME_BOARD;
1835 char model_buf[
sizeof(MODEL_PROGMEM)];
1836 memcpy_P(model_buf, MODEL_PROGMEM,
sizeof(MODEL_PROGMEM));
1842#ifdef USE_DEEP_SLEEP
1845#ifdef ESPHOME_PROJECT_NAME
1847 static const char PROJECT_NAME_PROGMEM[]
PROGMEM = ESPHOME_PROJECT_NAME;
1848 static const char PROJECT_VERSION_PROGMEM[]
PROGMEM = ESPHOME_PROJECT_VERSION;
1849 char project_name_buf[
sizeof(PROJECT_NAME_PROGMEM)];
1850 char project_version_buf[
sizeof(PROJECT_VERSION_PROGMEM)];
1851 memcpy_P(project_name_buf, PROJECT_NAME_PROGMEM,
sizeof(PROJECT_NAME_PROGMEM));
1852 memcpy_P(project_version_buf, PROJECT_VERSION_PROGMEM,
sizeof(PROJECT_VERSION_PROGMEM));
1865#ifdef USE_BLUETOOTH_PROXY
1868 char bluetooth_mac[18];
1872#ifdef USE_VOICE_ASSISTANT
1875#ifdef USE_ZWAVE_PROXY
1879#ifdef USE_SERIAL_PROXY
1880 size_t serial_proxy_index = 0;
1882 if (serial_proxy_index >= SERIAL_PROXY_COUNT)
1885 info.name =
StringRef(proxy->get_name());
1886 info.port_type = proxy->get_port_type();
1891#ifndef USE_API_NOISE_PSK_FROM_YAML
1899 size_t device_index = 0;
1901 if (device_index >= ESPHOME_DEVICE_COUNT)
1903 auto &device_info = resp.
devices[device_index++];
1904 device_info.device_id = device->get_device_id();
1905 device_info.name =
StringRef(device->get_name());
1906 device_info.area_id = device->get_area_id();
1910 size_t area_index = 0;
1912 if (area_index >= ESPHOME_AREA_COUNT)
1914 auto &area_info = resp.
areas[area_index++];
1915 area_info.area_id = area->get_area_id();
1916 area_info.name =
StringRef(area->get_name());
1920 return this->send_message(resp);
1923 if (!this->send_hello_response_(msg)) {
1924 this->on_fatal_error();
1929 if (!this->send_disconnect_response_()) {
1930 this->on_fatal_error();
1933void APIConnection::on_ping_request() {
1934 if (!this->send_ping_response_()) {
1935 this->on_fatal_error();
1938void APIConnection::on_device_info_request() {
1939 if (!this->send_device_info_response_()) {
1940 this->on_fatal_error();
1944#ifdef USE_API_HOMEASSISTANT_STATES
1960 for (
auto &it : this->parent_->get_state_subs()) {
1971 it.callback(msg.
state);
1975#ifdef USE_API_USER_DEFINED_ACTIONS
1983 if (!arg.string_.empty()) {
1984 const_cast<char *
>(arg.string_.c_str())[arg.string_.size()] =
'\0';
1988#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES
1993 action_call_id = this->parent_->register_active_action_call(msg.
call_id,
this);
1996 for (
auto *service : this->parent_->get_user_services()) {
1997 if (service->execute_service(msg, action_call_id)) {
2002 for (
auto *service : this->parent_->get_user_services()) {
2003 if (service->execute_service(msg)) {
2009 ESP_LOGV(TAG,
"Could not find service");
2015#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES
2016void APIConnection::send_execute_service_response(
uint32_t call_id,
bool success,
StringRef error_message) {
2021 this->send_message(resp);
2023#ifdef USE_API_USER_DEFINED_ACTION_RESPONSES_JSON
2024void APIConnection::send_execute_service_response(
uint32_t call_id,
bool success,
StringRef error_message,
2025 const uint8_t *response_data,
size_t response_data_len) {
2032 this->send_message(resp);
2038#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES
2040#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES_JSON
2056#ifdef USE_PROVISIONING
2060 ESP_LOGW(TAG,
"Provisioning closed; rejecting key set");
2061 return this->send_message(resp);
2067 if (this->parent_->clear_noise_psk(
true)) {
2070 ESP_LOGW(TAG,
"Failed to clear encryption key");
2073 ESP_LOGW(TAG,
"Invalid encryption key length");
2074 }
else if (APINoiseContext::is_all_zeros(psk)) {
2077 ESP_LOGW(TAG,
"Rejecting all-zero encryption key");
2078 }
else if (!this->parent_->save_noise_psk(psk,
true)) {
2079 ESP_LOGW(TAG,
"Failed to save encryption key");
2082#ifdef USE_API_PLAINTEXT
2083 if (this->helper_->frame_footer_size() == 0) {
2086 ESP_LOGW(TAG,
"Key received over plaintext; deprecated, will be removed in 2027.2.0");
2091 return this->send_message(resp);
2094 if (!this->send_noise_encryption_set_key_response_(msg)) {
2095 this->on_fatal_error();
2099#ifdef USE_API_HOMEASSISTANT_STATES
2100void APIConnection::on_subscribe_home_assistant_states_request() { state_subs_at_ = 0; }
2102bool APIConnection::try_to_clear_buffer_slow_(
bool log_out_of_space) {
2104 APIError err = this->helper_->loop();
2105 if (err != APIError::OK) {
2106 this->fatal_error_with_log_(LOG_STR(
"Socket operation failed"), err);
2109 if (this->helper_->can_write_without_blocking())
2111 if (log_out_of_space) {
2112 ESP_LOGV(TAG,
"Cannot send message because of TCP buffer space");
2118#ifdef HAS_PROTO_MESSAGE_DUMP
2120 if (message_type != SubscribeLogsResponse::MESSAGE_TYPE
2122 && message_type != CameraImageResponse::MESSAGE_TYPE
2125 auto *proto_msg =
static_cast<const ProtoMessage *
>(msg);
2127 this->log_send_message_(proto_msg->message_name(), proto_msg->dump_to(dump_buf));
2130 auto &shared_buf = this->parent_->get_shared_buffer_ref();
2131 this->prepare_first_message_buffer(shared_buf,
payload_size);
2132 size_t write_start = shared_buf.size();
2135 encode_fn(msg, buffer PROTO_ENCODE_DEBUG_INIT(&shared_buf));
2143 return encode_to_buffer(calculated_size, encode_fn, msg, conn, remaining_size);
2146 const bool is_log_message = (message_type == SubscribeLogsResponse::MESSAGE_TYPE);
2148 if (!this->try_to_clear_buffer(!is_log_message)) {
2153 this->helper_->set_nodelay_for_message(is_log_message);
2155 APIError err = this->helper_->write_protobuf_packet(message_type, buffer);
2156 if (err == APIError::WOULD_BLOCK)
2158 if (err != APIError::OK) {
2159 this->fatal_error_with_log_(LOG_STR(
"Packet write failed"), err);
2165void APIConnection::on_no_setup_connection() {
2166 this->on_fatal_error();
2167 this->log_client_(ESPHOME_LOG_LEVEL_DEBUG, LOG_STR(
"no connection setup"));
2169void APIConnection::on_fatal_error() {
2172 this->flags_.remove =
true;
2175bool APIConnection::schedule_message_front_(
EntityBase *entity, uint8_t message_type, uint8_t estimated_size) {
2176 this->deferred_batch_.add_item_front(entity, message_type, estimated_size);
2177 return this->schedule_batch_();
2180bool APIConnection::send_message_smart_(
EntityBase *entity, uint8_t message_type, uint8_t estimated_size,
2181 uint8_t aux_data_index) {
2182 if (this->should_send_immediately_(message_type) && this->helper_->can_write_without_blocking()) {
2183 auto &shared_buf = this->parent_->get_shared_buffer_ref();
2184 this->prepare_first_message_buffer(shared_buf, estimated_size);
2186 if (this->dispatch_message_(item, MAX_BATCH_PACKET_SIZE,
true) &&
2188#ifdef HAS_PROTO_MESSAGE_DUMP
2189 this->log_batch_item_(item);
2194 return this->schedule_message_(entity, message_type, estimated_size, aux_data_index);
2197bool APIConnection::schedule_batch_() {
2198 if (!this->flags_.batch_scheduled) {
2199 this->flags_.batch_scheduled =
true;
2205void APIConnection::process_batch_() {
2206 if (this->deferred_batch_.empty()) {
2207 this->flags_.batch_scheduled =
false;
2216 this->helper_->set_nodelay_for_message(
false);
2219 if (!this->try_to_clear_buffer(
true)) {
2225 auto &shared_buf = this->parent_->get_shared_buffer_ref();
2226 size_t num_items = this->deferred_batch_.size();
2229 const uint8_t header_padding = this->helper_->frame_header_padding();
2230 const uint8_t footer_size = this->helper_->frame_footer_size();
2233 uint32_t total_estimated_size = num_items * (header_padding + footer_size);
2234 for (
size_t i = 0; i < num_items; i++) {
2235 total_estimated_size += this->deferred_batch_[i].estimated_size;
2238 if (total_estimated_size > MAX_BATCH_PACKET_SIZE) {
2239 total_estimated_size = MAX_BATCH_PACKET_SIZE;
2242 this->prepare_first_message_buffer(shared_buf, header_padding, total_estimated_size);
2245 if (num_items == 1) {
2246 const auto &item = this->deferred_batch_[0];
2248 uint16_t
payload_size = this->dispatch_message_(item, std::numeric_limits<uint16_t>::max(),
true);
2251#ifdef HAS_PROTO_MESSAGE_DUMP
2253 this->log_batch_item_(item);
2255 this->clear_batch_();
2258 ESP_LOGW(TAG,
"Message too large to send: type=%u", item.message_type);
2259 this->clear_batch_();
2265 this->process_batch_multi_(shared_buf, num_items, header_padding, footer_size);
2270void APIConnection::process_batch_multi_(
APIBuffer &shared_buf,
size_t num_items, uint8_t header_padding,
2271 uint8_t footer_size) {
2273 static_assert(std::is_trivially_destructible<MessageInfo>::value,
2274 "MessageInfo must remain trivially destructible with this placement-new approach");
2276 const size_t messages_to_process = std::min(num_items, MAX_MESSAGES_PER_BATCH);
2281 size_t items_processed = 0;
2282 uint16_t remaining_size = std::numeric_limits<uint16_t>::max();
2289 for (
size_t i = 0; i < messages_to_process; i++) {
2290 const auto &item = this->deferred_batch_[i];
2293 uint16_t
payload_size = this->dispatch_message_(item, remaining_size, i == 0);
2302 uint16_t proto_payload_size =
payload_size - this->batch_header_size_ - footer_size;
2307 new (&message_info[items_processed++])
2308 MessageInfo(item.message_type, current_offset, proto_payload_size, this->batch_header_size_);
2310 if (items_processed == 1) {
2311 remaining_size = MAX_BATCH_PACKET_SIZE;
2316 current_offset = shared_buf.
size() + footer_size;
2319 if (items_processed > 0) {
2321 if (footer_size > 0) {
2322 shared_buf.
resize(shared_buf.
size() + footer_size);
2327 std::span<const MessageInfo>(message_info, items_processed));
2328 if (err != APIError::OK && err != APIError::WOULD_BLOCK) {
2329 this->fatal_error_with_log_(LOG_STR(
"Batch write failed"), err);
2332#ifdef HAS_PROTO_MESSAGE_DUMP
2335 for (
size_t i = 0; i < items_processed; i++) {
2336 const auto &item = this->deferred_batch_[i];
2337 this->log_batch_item_(item);
2342 if (items_processed < this->deferred_batch_.size()) {
2343 this->deferred_batch_.remove_front(items_processed);
2344 this->schedule_batch_();
2350 this->clear_batch_();
2357 this->flags_.batch_first_message = batch_first;
2361 if (item.
message_type == EventResponse::MESSAGE_TYPE) {
2367 this, remaining_size);
2375#define CASE_STATE_INFO(entity_name, StateResp, InfoResp) \
2376 case StateResp::MESSAGE_TYPE: \
2377 func = &try_send_##entity_name##_state; \
2379 case InfoResp::MESSAGE_TYPE: \
2380 func = &try_send_##entity_name##_info; \
2382#define CASE_INFO_ONLY(entity_name, InfoResp) \
2383 case InfoResp::MESSAGE_TYPE: \
2384 func = &try_send_##entity_name##_info; \
2388#ifdef USE_BINARY_SENSOR
2409#ifdef USE_TEXT_SENSOR
2418#ifdef USE_DATETIME_DATE
2421#ifdef USE_DATETIME_TIME
2424#ifdef USE_DATETIME_DATETIME
2439#ifdef USE_MEDIA_PLAYER
2442#ifdef USE_ALARM_CONTROL_PANEL
2445#ifdef USE_WATER_HEATER
2454#ifdef USE_RADIO_FREQUENCY
2464 case ListEntitiesDoneResponse::MESSAGE_TYPE:
2465 func = &try_send_list_info_done;
2467 case DisconnectRequest::MESSAGE_TYPE:
2468 func = &try_send_disconnect_request;
2470 case PingRequest::MESSAGE_TYPE:
2471 func = &try_send_ping_request;
2477#undef CASE_STATE_INFO
2478#undef CASE_INFO_ONLY
2480 return func(item.
entity,
this, remaining_size);
2485 return encode_message_to_buffer(resp, conn, remaining_size);
2490 return encode_message_to_buffer(req, conn, remaining_size);
2495 return encode_message_to_buffer(req, conn, remaining_size);
2498#ifdef USE_API_HOMEASSISTANT_STATES
2499void APIConnection::process_state_subscriptions_() {
2500 const auto &subs = this->parent_->get_state_subs();
2501 if (this->state_subs_at_ >=
static_cast<int>(subs.size())) {
2502 this->state_subs_at_ = -1;
2506 const auto &it = subs[this->state_subs_at_];
2513 resp.
once = it.once;
2514 if (this->send_message(resp)) {
2515 this->state_subs_at_++;
2520void APIConnection::log_client_(
int level,
const LogString *
message) {
2521 char peername[socket::SOCKADDR_STR_LEN];
2522 esp_log_printf_(level, TAG, __LINE__, ESPHOME_LOG_FORMAT(
"%s (%s): %s"), this->helper_->get_client_name(),
2523 this->helper_->get_peername_to(peername), LOG_STR_ARG(
message));
2527 char peername[socket::SOCKADDR_STR_LEN];
2528 ESP_LOGW(TAG,
"%s (%s): %s %s errno=%d", this->helper_->get_client_name(), this->helper_->get_peername_to(peername),
const StringRef & get_name() const
Get the name of this Application set by pre_setup().
static constexpr size_t BUILD_TIME_STR_SIZE
Size of buffer required for build time string (including null terminator)
const StringRef & get_friendly_name() const
Get the friendly name of this Application set by pre_setup().
void get_build_time_string(std::span< char, BUILD_TIME_STR_SIZE > buffer)
Copy the build time string into the provided buffer Buffer must be BUILD_TIME_STR_SIZE bytes (compile...
const char * get_area() const
Get the area of this Application set by pre_setup().
const auto & get_devices()
auto & get_serial_proxies() const
uint32_t IRAM_ATTR HOT get_loop_component_start_time() const
Get the cached time in milliseconds from when the current component started its loop execution.
void begin(bool include_internal=false)
const char * get_device_class_to(std::span< char, MAX_DEVICE_CLASS_LENGTH > buffer) const
bool has_own_name() const
const StringRef & get_name() const
ESPDEPRECATED("Use get_unit_of_measurement_ref() instead for better performance (avoids string copy). Will be " "removed in ESPHome 2026.9.0", "2026.3.0") std const char * get_icon_to(std::span< char, MAX_ICON_LENGTH > buffer) const
Get the unit of measurement as std::string (deprecated, prefer get_unit_of_measurement_ref())
uint32_t get_object_id_hash() const
ESPDEPRECATED("Use get_icon_to() instead. Will be removed in ESPHome 2026.9.0", "2026.3.0") std uint32_t get_device_id() const
bool is_disabled_by_default() const
EntityCategory get_entity_category() const
Fixed-capacity vector - allocates once at runtime, never reallocates This avoids std::vector template...
void push_back(const T &value)
Add element without bounds checking Caller must ensure sufficient capacity was allocated via init() S...
StringRef is a reference to a string owned by something else.
constexpr const char * c_str() const
constexpr bool empty() const
constexpr size_type size() const
static constexpr StringRef from_lit(const CharT(&s)[N])
static StringRef from_maybe_nullptr(const char *s)
Byte buffer that skips zero-initialization on resize().
void resize(size_t n) ESPHOME_ALWAYS_INLINE
void on_button_command_request(const ButtonCommandRequest &msg)
uint8_t *(*)(const void *, ProtoWriteBuffer &PROTO_ENCODE_DEBUG_PARAM) MessageEncodeFn
APIConnection(std::unique_ptr< socket::Socket > socket, APIServer *parent)
uint16_t(*)(EntityBase *, APIConnection *, uint32_t remaining_size) MessageCreatorPtr
uint32_t(*)(const void *) CalculateSizeFn
uint8_t get_consumed_header(uint8_t out[3]) const
APINoiseContext & get_noise_ctx()
enums::AlarmControlPanelStateCommand command
enums::AlarmControlPanelState state
enums::BluetoothScannerMode mode
void set_data(const uint8_t *data, size_t len)
bool has_target_temperature_high
float target_temperature_low
bool has_target_temperature_low
StringRef custom_fan_mode
float target_temperature_high
enums::ClimateSwingMode swing_mode
enums::ClimateFanMode fan_mode
bool has_target_temperature
enums::ClimatePreset preset
enums::ClimateFanMode fan_mode
float target_temperature_low
enums::ClimateSwingMode swing_mode
enums::ClimateAction action
enums::ClimatePreset preset
StringRef custom_fan_mode
float current_temperature
float target_temperature_high
enums::CoverOperation current_operation
bool api_encryption_provisionable
StringRef project_version
uint32_t zwave_proxy_feature_flags
StringRef esphome_version
std::array< AreaInfo, ESPHOME_AREA_COUNT > areas
StringRef bluetooth_mac_address
uint32_t bluetooth_proxy_feature_flags
StringRef compilation_time
uint32_t voice_assistant_feature_flags
bool api_encryption_supported
std::array< SerialProxyInfo, SERIAL_PROXY_COUNT > serial_proxies
std::array< DeviceInfo, ESPHOME_DEVICE_COUNT > devices
enums::DisconnectReason reason
Fixed-size buffer for message dumps - avoids heap allocation.
uint16_t response_data_len
const uint8_t * response_data
enums::FanDirection direction
enums::FanDirection direction
ParsedTimezone parsed_timezone
uint32_t api_version_major
uint32_t api_version_minor
uint32_t api_version_minor
uint32_t api_version_major
const uint8_t * response_data
uint16_t response_data_len
enums::EntityCategory entity_category
const uint8_t * timings_data_
uint32_t carrier_frequency
bool has_color_temperature
enums::ColorMode color_mode
bool has_transition_length
uint32_t transition_length
bool has_color_brightness
enums::ColorMode color_mode
bool requires_code_to_arm
uint32_t supported_features
bool is_status_binary_sensor
const std::vector< const char * > * supported_custom_presets
const climate::ClimateSwingModeMask * supported_swing_modes
enums::TemperatureUnit temperature_unit
float visual_max_humidity
const std::vector< const char * > * supported_custom_fan_modes
bool supports_current_temperature
bool supports_current_humidity
bool supports_target_humidity
float visual_min_humidity
float visual_max_temperature
float visual_target_temperature_step
bool supports_two_point_target_temperature
const climate::ClimatePresetMask * supported_presets
const climate::ClimateFanModeMask * supported_fan_modes
const climate::ClimateModeMask * supported_modes
float visual_min_temperature
float visual_current_temperature_step
const FixedVector< const char * > * event_types
const std::vector< const char * > * supported_preset_modes
int32_t supported_speed_count
bool supports_oscillation
uint32_t receiver_frequency
const FixedVector< const char * > * effects
const light::ColorModeMask * supported_color_modes
StringRef unit_of_measurement
uint32_t supported_modulations
const FixedVector< const char * > * options
int32_t accuracy_decimals
StringRef unit_of_measurement
enums::SensorStateClass state_class
enums::TemperatureUnit temperature_unit
float target_temperature_step
const water_heater::WaterHeaterModeMask * supported_modes
uint32_t supported_features
enums::LockCommand command
enums::SerialProxyRequestType type
void set_message(const uint8_t *data, size_t len)
enums::UpdateCommand command
StringRef current_version
StringRef release_summary
enums::ValveOperation current_operation
std::vector< VoiceAssistantExternalWakeWord > external_wake_words
std::vector< VoiceAssistantWakeWord > available_wake_words
uint32_t max_active_wake_words
const std::vector< std::string > * active_wake_words
std::vector< std::string > active_wake_words
float target_temperature_low
enums::WaterHeaterMode mode
float target_temperature_high
float current_temperature
float target_temperature_low
float target_temperature_high
enums::WaterHeaterMode mode
enums::ZWaveProxyRequestType type
Base class for all binary_sensor-type classes.
void bluetooth_gatt_read(const api::BluetoothGATTReadRequest &msg)
void bluetooth_gatt_send_services(const api::BluetoothGATTGetServicesRequest &msg)
void bluetooth_device_request(const api::BluetoothDeviceRequest &msg)
void bluetooth_gatt_write_descriptor(const api::BluetoothGATTWriteDescriptorRequest &msg)
void bluetooth_scanner_set_mode(bool active)
void subscribe_api_connection(api::APIConnection *api_connection, uint32_t flags)
uint32_t get_feature_flags() const
void send_connections_free()
void unsubscribe_api_connection(api::APIConnection *api_connection)
void get_bluetooth_mac_address_pretty(std::span< char, 18 > output)
void bluetooth_set_connection_params(const api::BluetoothSetConnectionParamsRequest &msg)
void bluetooth_gatt_read_descriptor(const api::BluetoothGATTReadDescriptorRequest &msg)
void bluetooth_gatt_write(const api::BluetoothGATTWriteRequest &msg)
void bluetooth_gatt_notify(const api::BluetoothGATTNotifyRequest &msg)
Abstract camera base class.
virtual CameraImageReader * create_image_reader()=0
Returns a new camera image reader that keeps track of the JPEG data in the camera image.
virtual void start_stream(CameraRequester requester)=0
virtual void stop_stream(CameraRequester requester)=0
virtual void request_image(CameraRequester requester)=0
static Camera * instance()
The singleton instance of the camera implementation.
ClimateDevice - This is the base class for all climate integrations.
Base class for all cover devices.
uint8_t get_last_event_type_index() const
Return index of last triggered event type, or max uint8_t if no event triggered yet.
void set_epoch_time(uint32_t epoch)
Infrared - Base class for infrared remote control implementations.
This class represents the communication layer between the front-end MQTT layer and the hardware outpu...
Base class for all locks.
Base-class for all numbers.
RadioFrequency - Base class for radio frequency implementations.
Base-class for all selects.
Base-class for all sensors.
Base class for all switches.
Base-class for all text inputs.
void set_timezone(const char *tz)
Set the time zone from a POSIX TZ string.
Base class for all valve devices.
const Configuration & get_configuration()
void on_timer_event(const api::VoiceAssistantTimerEventResponse &msg)
void on_audio(const api::VoiceAssistantAudio &msg)
void client_subscription(api::APIConnection *client, bool subscribe)
void on_event(const api::VoiceAssistantEventResponse &msg)
void on_announce(const api::VoiceAssistantAnnounceRequest &msg)
api::APIConnection * get_api_connection() const
uint32_t get_feature_flags() const
void on_set_configuration(const std::vector< std::string > &active_wake_words)
void zwave_proxy_request(api::APIConnection *api_connection, api::enums::ZWaveProxyRequestType type)
uint32_t get_feature_flags() const
void send_frame(api::APIConnection *api_connection, const uint8_t *data, size_t length)
void api_connection_authenticated(api::APIConnection *conn)
const LogString * message
const LogString * api_error_to_logstr(APIError err)
std::array< uint8_t, 32 > psk_t
BluetoothProxy * global_bluetooth_proxy
@ CLIMATE_SUPPORTS_CURRENT_HUMIDITY
@ CLIMATE_SUPPORTS_TARGET_HUMIDITY
@ CLIMATE_SUPPORTS_TWO_POINT_TARGET_TEMPERATURE
@ CLIMATE_SUPPORTS_CURRENT_TEMPERATURE
@ CLIMATE_SUPPORTS_ACTION
@ CLIMATE_REQUIRES_TWO_POINT_TARGET_TEMPERATURE
ClimatePreset
Enum for all preset modes NOTE: If adding values, update ClimatePresetMask in climate_traits....
ClimateSwingMode
Enum for all modes a climate swing can be in NOTE: If adding values, update ClimateSwingModeMask in c...
ClimateMode
Enum for all modes a climate device can be in.
ClimateFanMode
NOTE: If adding values, update ClimateFanModeMask in climate_traits.h to use the new last value.
bool global_has_deep_sleep
FanDirection
Simple enum to represent the direction of a fan.
HomeassistantTime * global_homeassistant_time
ColorMode
Color modes are a combination of color capabilities that can be used at the same time.
@ COLOR_TEMPERATURE
Color temperature can be controlled.
@ COLD_WARM_WHITE
Brightness of cold and warm white output can be controlled.
ProvisioningManager * global_provisioning_manager
RadioFrequencyModulation
Modulation types supported by radio frequency implementations.
void set_global_tz(const ParsedTimezone &tz)
Set the global timezone used by epoch_to_local_tm() when called without a timezone.
DSTRuleType
Type of DST transition rule.
@ UART_FLUSH_RESULT_ASSUMED_SUCCESS
Platform cannot report result; success is assumed.
@ UART_FLUSH_RESULT_SUCCESS
Confirmed: all bytes left the TX FIFO.
@ UART_FLUSH_RESULT_FAILED
Confirmed: driver or hardware error.
@ UART_FLUSH_RESULT_TIMEOUT
Confirmed: timed out before TX completed.
@ UPDATE_STATE_INSTALLING
VoiceAssistant * global_voice_assistant
@ WATER_HEATER_STATE_ON
Water heater is on (not in standby)
@ WATER_HEATER_STATE_AWAY
Away/vacation mode is currently active.
ZWaveProxy * global_zwave_proxy
const char int const __FlashStringHelper va_list args
void HOT esp_log_printf_(int level, const char *tag, int line, const char *format,...)
std::vector< uint8_t > base64_decode(const std::string &encoded_string)
Decode a base64 string to a byte vector.
void get_mac_address_raw(uint8_t *mac)
Get the device MAC address as raw bytes, written into the provided byte array (6 bytes).
void HOT delay(uint32_t ms)
Application App
Global storage of Application pointer - only one Application can exist.
char * format_mac_addr_upper(const uint8_t *mac, char *output)
Format MAC address as XX:XX:XX:XX:XX:XX (uppercase, colon separators)
A more user-friendly version of struct tm from time.h.
uint16_t day
Day of year (for JULIAN_NO_LEAP and DAY_OF_YEAR)
DSTRuleType type
Type of rule.
uint8_t week
Week 1-5, 5 = last (for MONTH_WEEK_DAY)
int32_t time_seconds
Seconds after midnight (default 7200 = 2:00 AM)
uint8_t day_of_week
Day 0-6, 0 = Sunday (for MONTH_WEEK_DAY)
uint8_t month
Month 1-12 (for MONTH_WEEK_DAY)
Parsed POSIX timezone information (packed for 32-bit: 32 bytes)
DSTRule dst_end
When DST ends.
DSTRule dst_start
When DST starts.
int32_t dst_offset_seconds
DST offset from UTC in seconds.
int32_t std_offset_seconds
Standard time offset from UTC in seconds (positive = west)
const uint8_t ESPHOME_WEBSERVER_INDEX_HTML[] PROGMEM