6#ifdef USE_API_PLAINTEXT
24#ifdef USE_HOMEASSISTANT_TIME
27#ifdef USE_BLUETOOTH_PROXY
33#ifdef USE_VOICE_ASSISTANT
46static constexpr uint8_t MAX_MESSAGES_PER_LOOP = 5;
47static constexpr uint8_t MAX_PING_RETRIES = 60;
48static constexpr uint16_t PING_RETRY_INTERVAL = 1000;
49static constexpr uint32_t KEEPALIVE_DISCONNECT_TIMEOUT = (KEEPALIVE_TIMEOUT_MS * 5) / 2;
53static const char *
const TAG =
"api.connection";
55static const int CAMERA_STOP_STREAM = 5000;
61#define ENTITY_COMMAND_MAKE_CALL(entity_type, entity_var, getter_name) \
62 entity_type *entity_var = App.get_##getter_name##_by_key(msg.key, msg.device_id); \
63 if ((entity_var) == nullptr) \
65 auto call = (entity_var)->make_call();
69#define ENTITY_COMMAND_GET(entity_type, entity_var, getter_name) \
70 entity_type *entity_var = App.get_##getter_name##_by_key(msg.key, msg.device_id); \
71 if ((entity_var) == nullptr) \
76#define ENTITY_COMMAND_MAKE_CALL(entity_type, entity_var, getter_name) \
77 entity_type *entity_var = App.get_##getter_name##_by_key(msg.key); \
78 if ((entity_var) == nullptr) \
80 auto call = (entity_var)->make_call();
84#define ENTITY_COMMAND_GET(entity_type, entity_var, getter_name) \
85 entity_type *entity_var = App.get_##getter_name##_by_key(msg.key); \
86 if ((entity_var) == nullptr) \
91 : parent_(parent), initial_state_iterator_(this), list_entities_iterator_(this) {
92#if defined(USE_API_PLAINTEXT) && defined(USE_API_NOISE)
94 if (noise_ctx->has_psk()) {
96 std::unique_ptr<APIFrameHelper>{new APINoiseFrameHelper(std::move(sock), noise_ctx, &this->client_info_)};
98 this->helper_ = std::unique_ptr<APIFrameHelper>{
new APIPlaintextFrameHelper(std::move(sock), &this->client_info_)};
100#elif defined(USE_API_PLAINTEXT)
101 this->helper_ = std::unique_ptr<APIFrameHelper>{
new APIPlaintextFrameHelper(std::move(sock), &this->client_info_)};
102#elif defined(USE_API_NOISE)
103 this->helper_ = std::unique_ptr<APIFrameHelper>{
104 new APINoiseFrameHelper(std::move(sock), parent->get_noise_ctx(), &this->client_info_)};
106#error "No frame helper defined"
115uint32_t APIConnection::get_batch_delay_ms_()
const {
return this->parent_->get_batch_delay(); }
117void APIConnection::start() {
120 APIError err = this->helper_->init();
121 if (err != APIError::OK) {
122 this->fatal_error_with_log_(LOG_STR(
"Helper init failed"), err);
125 this->client_info_.peername = helper_->getpeername();
126 this->client_info_.name = this->client_info_.peername;
129APIConnection::~APIConnection() {
130#ifdef USE_BLUETOOTH_PROXY
135#ifdef USE_VOICE_ASSISTANT
142void APIConnection::loop() {
143 if (this->flags_.next_close) {
145 this->helper_->close();
146 this->flags_.remove =
true;
150 APIError err = this->helper_->loop();
151 if (err != APIError::OK) {
152 this->fatal_error_with_log_(LOG_STR(
"Socket operation failed"), err);
158 if (this->helper_->is_socket_ready()) {
160 for (uint8_t message_count = 0; message_count < MAX_MESSAGES_PER_LOOP; message_count++) {
162 err = this->helper_->read_packet(&buffer);
163 if (err == APIError::WOULD_BLOCK) {
166 }
else if (err != APIError::OK) {
167 this->fatal_error_with_log_(LOG_STR(
"Reading failed"), err);
170 this->last_traffic_ = now;
174 if (this->flags_.remove)
181 if (this->flags_.batch_scheduled && now - this->deferred_batch_.batch_start_time >= this->get_batch_delay_ms_()) {
182 this->process_batch_();
185 if (!this->list_entities_iterator_.completed()) {
186 this->process_iterator_batch_(this->list_entities_iterator_);
187 }
else if (!this->initial_state_iterator_.completed()) {
188 this->process_iterator_batch_(this->initial_state_iterator_);
191 if (this->initial_state_iterator_.completed()) {
193 if (!this->deferred_batch_.empty()) {
194 this->process_batch_();
197 this->flags_.should_try_send_immediately =
true;
201 if (this->flags_.sent_ping) {
203 if (now - this->last_traffic_ > KEEPALIVE_DISCONNECT_TIMEOUT) {
205 ESP_LOGW(TAG,
"%s (%s) is unresponsive; disconnecting", this->client_info_.name.c_str(),
206 this->client_info_.peername.c_str());
208 }
else if (now - this->last_traffic_ > KEEPALIVE_TIMEOUT_MS && !this->flags_.remove) {
210 ESP_LOGVV(TAG,
"Sending keepalive PING");
212 this->flags_.sent_ping = this->send_message(req, PingRequest::MESSAGE_TYPE);
213 if (!this->flags_.sent_ping) {
216 ESP_LOGW(TAG,
"Buffer full, ping queued");
217 this->schedule_message_front_(
nullptr, &APIConnection::try_send_ping_request, PingRequest::MESSAGE_TYPE,
218 PingRequest::ESTIMATED_SIZE);
219 this->flags_.sent_ping =
true;
224 if (this->image_reader_ && this->image_reader_->available() && this->helper_->can_write_without_blocking()) {
225 uint32_t to_send = std::min((
size_t) MAX_BATCH_PACKET_SIZE, this->image_reader_->available());
226 bool done = this->image_reader_->available() == to_send;
230 msg.
set_data(this->image_reader_->peek_data_buffer(), to_send);
236 if (this->send_message_(msg, CameraImageResponse::MESSAGE_TYPE)) {
237 this->image_reader_->consume_data(to_send);
239 this->image_reader_->return_image();
245#ifdef USE_API_HOMEASSISTANT_STATES
246 if (state_subs_at_ >= 0) {
247 this->process_state_subscriptions_();
256 ESP_LOGD(TAG,
"%s (%s) disconnected", this->client_info_.name.c_str(), this->client_info_.peername.c_str());
257 this->flags_.next_close =
true;
259 return this->send_message(resp, DisconnectResponse::MESSAGE_TYPE);
262 this->helper_->close();
263 this->flags_.remove =
true;
269 uint32_t remaining_size,
bool is_single) {
270#ifdef HAS_PROTO_MESSAGE_DUMP
281 uint32_t calculated_size = size_calc.
get_size();
284 const uint8_t header_padding = conn->
helper_->frame_header_padding();
285 const uint8_t footer_size = conn->
helper_->frame_footer_size();
288 size_t total_calculated_size = calculated_size + header_padding + footer_size;
291 if (total_calculated_size > remaining_size) {
307 size_t current_size = shared_buf.size();
308 shared_buf.reserve(current_size + total_calculated_size);
309 shared_buf.resize(current_size + footer_size + header_padding);
313 size_t size_before_encode = shared_buf.size();
314 msg.
encode({&shared_buf});
317 size_t actual_payload_size = shared_buf.size() - size_before_encode;
320 size_t actual_total_size = header_padding + actual_payload_size + footer_size;
323 assert(calculated_size == actual_payload_size);
324 return static_cast<uint16_t
>(actual_total_size);
327#ifdef USE_BINARY_SENSOR
329 return this->send_message_smart_(binary_sensor, &APIConnection::try_send_binary_sensor_state,
330 BinarySensorStateResponse::MESSAGE_TYPE, BinarySensorStateResponse::ESTIMATED_SIZE);
337 resp.
state = binary_sensor->state;
339 return fill_and_encode_entity_state(binary_sensor, resp, BinarySensorStateResponse::MESSAGE_TYPE, conn,
340 remaining_size, is_single);
349 return fill_and_encode_entity_info(binary_sensor, msg, ListEntitiesBinarySensorResponse::MESSAGE_TYPE, conn,
350 remaining_size, is_single);
356 return this->send_message_smart_(cover, &APIConnection::try_send_cover_state, CoverStateResponse::MESSAGE_TYPE,
357 CoverStateResponse::ESTIMATED_SIZE);
363 auto traits = cover->get_traits();
365 if (traits.get_supports_tilt())
366 msg.
tilt = cover->tilt;
368 return fill_and_encode_entity_state(cover, msg, CoverStateResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
374 auto traits = cover->get_traits();
380 return fill_and_encode_entity_info(cover, msg, ListEntitiesCoverResponse::MESSAGE_TYPE, conn, remaining_size,
388 call.set_tilt(msg.
tilt);
390 call.set_command_stop();
397 return this->send_message_smart_(fan, &APIConnection::try_send_fan_state, FanStateResponse::MESSAGE_TYPE,
398 FanStateResponse::ESTIMATED_SIZE);
402 auto *fan =
static_cast<fan::Fan *
>(entity);
404 auto traits = fan->get_traits();
405 msg.
state = fan->state;
406 if (traits.supports_oscillation())
408 if (traits.supports_speed()) {
411 if (traits.supports_direction())
413 if (traits.supports_preset_modes() && fan->has_preset_mode())
415 return fill_and_encode_entity_state(fan, msg, FanStateResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
419 auto *fan =
static_cast<fan::Fan *
>(entity);
421 auto traits = fan->get_traits();
427 return fill_and_encode_entity_info(fan, msg, ListEntitiesFanResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
430 ENTITY_COMMAND_MAKE_CALL(
fan::Fan, fan, fan)
432 call.set_state(msg.
state);
449 return this->send_message_smart_(light, &APIConnection::try_send_light_state, LightStateResponse::MESSAGE_TYPE,
450 LightStateResponse::ESTIMATED_SIZE);
456 auto values = light->remote_values;
457 auto color_mode = values.get_color_mode();
458 resp.
state = values.is_on();
462 resp.
red = values.get_red();
463 resp.
green = values.get_green();
464 resp.
blue = values.get_blue();
465 resp.
white = values.get_white();
469 if (light->supports_effects()) {
470 resp.
set_effect(light->get_effect_name_ref());
472 return fill_and_encode_entity_state(light, resp, LightStateResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
478 auto traits = light->get_traits();
479 auto supported_modes = traits.get_supported_color_modes();
487 if (light->supports_effects()) {
488 msg.
effects.emplace_back(
"None");
489 for (
auto *effect : light->get_effects()) {
490 msg.
effects.emplace_back(effect->get_name());
493 return fill_and_encode_entity_info(light, msg, ListEntitiesLightResponse::MESSAGE_TYPE, conn, remaining_size,
499 call.set_state(msg.
state);
507 call.set_red(msg.
red);
508 call.set_green(msg.
green);
509 call.set_blue(msg.
blue);
512 call.set_white(msg.
white);
524 call.set_effect(msg.
effect);
531 return this->send_message_smart_(sensor, &APIConnection::try_send_sensor_state, SensorStateResponse::MESSAGE_TYPE,
532 SensorStateResponse::ESTIMATED_SIZE);
539 resp.
state = sensor->state;
541 return fill_and_encode_entity_state(sensor, resp, SensorStateResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
553 return fill_and_encode_entity_info(sensor, msg, ListEntitiesSensorResponse::MESSAGE_TYPE, conn, remaining_size,
560 return this->send_message_smart_(a_switch, &APIConnection::try_send_switch_state, SwitchStateResponse::MESSAGE_TYPE,
561 SwitchStateResponse::ESTIMATED_SIZE);
568 resp.
state = a_switch->state;
569 return fill_and_encode_entity_state(a_switch, resp, SwitchStateResponse::MESSAGE_TYPE, conn, remaining_size,
579 return fill_and_encode_entity_info(a_switch, msg, ListEntitiesSwitchResponse::MESSAGE_TYPE, conn, remaining_size,
588 a_switch->turn_off();
593#ifdef USE_TEXT_SENSOR
595 return this->send_message_smart_(text_sensor, &APIConnection::try_send_text_sensor_state,
596 TextSensorStateResponse::MESSAGE_TYPE, TextSensorStateResponse::ESTIMATED_SIZE);
605 return fill_and_encode_entity_state(text_sensor, resp, TextSensorStateResponse::MESSAGE_TYPE, conn, remaining_size,
613 return fill_and_encode_entity_info(text_sensor, msg, ListEntitiesTextSensorResponse::MESSAGE_TYPE, conn,
614 remaining_size, is_single);
620 return this->send_message_smart_(climate, &APIConnection::try_send_climate_state, ClimateStateResponse::MESSAGE_TYPE,
621 ClimateStateResponse::ESTIMATED_SIZE);
627 auto traits = climate->get_traits();
639 if (traits.get_supports_fan_modes() && climate->fan_mode.has_value())
641 if (!traits.get_supported_custom_fan_modes().empty() && climate->has_custom_fan_mode()) {
644 if (traits.get_supports_presets() && climate->preset.has_value()) {
647 if (!traits.get_supported_custom_presets().empty() && climate->has_custom_preset()) {
650 if (traits.get_supports_swing_modes())
656 return fill_and_encode_entity_state(climate, resp, ClimateStateResponse::MESSAGE_TYPE, conn, remaining_size,
663 auto traits = climate->get_traits();
685 return fill_and_encode_entity_info(climate, msg, ListEntitiesClimateResponse::MESSAGE_TYPE, conn, remaining_size,
716 return this->send_message_smart_(number, &APIConnection::try_send_number_state, NumberStateResponse::MESSAGE_TYPE,
717 NumberStateResponse::ESTIMATED_SIZE);
724 resp.
state = number->state;
726 return fill_and_encode_entity_state(number, resp, NumberStateResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
736 msg.
min_value = number->traits.get_min_value();
737 msg.
max_value = number->traits.get_max_value();
738 msg.
step = number->traits.get_step();
739 return fill_and_encode_entity_info(number, msg, ListEntitiesNumberResponse::MESSAGE_TYPE, conn, remaining_size,
744 call.set_value(msg.
state);
749#ifdef USE_DATETIME_DATE
751 return this->send_message_smart_(date, &APIConnection::try_send_date_state, DateStateResponse::MESSAGE_TYPE,
752 DateStateResponse::ESTIMATED_SIZE);
759 resp.
year = date->year;
760 resp.
month = date->month;
761 resp.
day = date->day;
762 return fill_and_encode_entity_state(date, resp, DateStateResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
768 return fill_and_encode_entity_info(date, msg, ListEntitiesDateResponse::MESSAGE_TYPE, conn, remaining_size,
778#ifdef USE_DATETIME_TIME
780 return this->send_message_smart_(time, &APIConnection::try_send_time_state, TimeStateResponse::MESSAGE_TYPE,
781 TimeStateResponse::ESTIMATED_SIZE);
788 resp.
hour = time->hour;
789 resp.
minute = time->minute;
790 resp.
second = time->second;
791 return fill_and_encode_entity_state(time, resp, TimeStateResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
797 return fill_and_encode_entity_info(time, msg, ListEntitiesTimeResponse::MESSAGE_TYPE, conn, remaining_size,
807#ifdef USE_DATETIME_DATETIME
809 return this->send_message_smart_(datetime, &APIConnection::try_send_datetime_state,
810 DateTimeStateResponse::MESSAGE_TYPE, DateTimeStateResponse::ESTIMATED_SIZE);
817 if (datetime->has_state()) {
821 return fill_and_encode_entity_state(datetime, resp, DateTimeStateResponse::MESSAGE_TYPE, conn, remaining_size,
828 return fill_and_encode_entity_info(datetime, msg, ListEntitiesDateTimeResponse::MESSAGE_TYPE, conn, remaining_size,
840 return this->send_message_smart_(text, &APIConnection::try_send_text_state, TextStateResponse::MESSAGE_TYPE,
841 TextStateResponse::ESTIMATED_SIZE);
846 auto *text =
static_cast<text::Text *
>(entity);
850 return fill_and_encode_entity_state(text, resp, TextStateResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
855 auto *text =
static_cast<text::Text *
>(entity);
858 msg.
min_length = text->traits.get_min_length();
859 msg.
max_length = text->traits.get_max_length();
861 return fill_and_encode_entity_info(text, msg, ListEntitiesTextResponse::MESSAGE_TYPE, conn, remaining_size,
865 ENTITY_COMMAND_MAKE_CALL(
text::Text, text, text)
866 call.set_value(msg.
state);
873 return this->send_message_smart_(select, &APIConnection::try_send_select_state, SelectStateResponse::MESSAGE_TYPE,
874 SelectStateResponse::ESTIMATED_SIZE);
883 return fill_and_encode_entity_state(select, resp, SelectStateResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
890 msg.
options = &select->traits.get_options();
891 return fill_and_encode_entity_info(select, msg, ListEntitiesSelectResponse::MESSAGE_TYPE, conn, remaining_size,
896 call.set_option(msg.
state);
907 return fill_and_encode_entity_info(button, msg, ListEntitiesButtonResponse::MESSAGE_TYPE, conn, remaining_size,
918 return this->send_message_smart_(a_lock, &APIConnection::try_send_lock_state, LockStateResponse::MESSAGE_TYPE,
919 LockStateResponse::ESTIMATED_SIZE);
924 auto *a_lock =
static_cast<lock::Lock *
>(entity);
927 return fill_and_encode_entity_state(a_lock, resp, LockStateResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
932 auto *a_lock =
static_cast<lock::Lock *
>(entity);
937 return fill_and_encode_entity_info(a_lock, msg, ListEntitiesLockResponse::MESSAGE_TYPE, conn, remaining_size,
944 case enums::LOCK_UNLOCK:
947 case enums::LOCK_LOCK:
950 case enums::LOCK_OPEN:
959 return this->send_message_smart_(valve, &APIConnection::try_send_valve_state, ValveStateResponse::MESSAGE_TYPE,
960 ValveStateResponse::ESTIMATED_SIZE);
968 return fill_and_encode_entity_state(valve, resp, ValveStateResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
974 auto traits = valve->get_traits();
979 return fill_and_encode_entity_info(valve, msg, ListEntitiesValveResponse::MESSAGE_TYPE, conn, remaining_size,
987 call.set_command_stop();
992#ifdef USE_MEDIA_PLAYER
994 return this->send_message_smart_(media_player, &APIConnection::try_send_media_player_state,
995 MediaPlayerStateResponse::MESSAGE_TYPE, MediaPlayerStateResponse::ESTIMATED_SIZE);
1003 : media_player->state;
1005 resp.
volume = media_player->volume;
1006 resp.
muted = media_player->is_muted();
1007 return fill_and_encode_entity_state(media_player, resp, MediaPlayerStateResponse::MESSAGE_TYPE, conn, remaining_size,
1014 auto traits = media_player->get_traits();
1017 for (
auto &supported_format : traits.get_supported_formats()) {
1020 media_format.set_format(
StringRef(supported_format.format));
1021 media_format.sample_rate = supported_format.sample_rate;
1022 media_format.num_channels = supported_format.num_channels;
1024 media_format.sample_bytes = supported_format.sample_bytes;
1026 return fill_and_encode_entity_info(media_player, msg, ListEntitiesMediaPlayerResponse::MESSAGE_TYPE, conn,
1027 remaining_size, is_single);
1035 call.set_volume(msg.
volume);
1048void APIConnection::set_camera_state(std::shared_ptr<camera::CameraImage> image) {
1049 if (!this->flags_.state_subscription)
1051 if (!this->image_reader_)
1053 if (this->image_reader_->available())
1056 this->image_reader_->set_image(std::move(image));
1062 return fill_and_encode_entity_info(camera, msg, ListEntitiesCameraResponse::MESSAGE_TYPE, conn, remaining_size,
1074 App.scheduler.set_timeout(this->parent_,
"api_camera_stop_stream", CAMERA_STOP_STREAM,
1080#ifdef USE_HOMEASSISTANT_TIME
1084#ifdef USE_TIME_TIMEZONE
1094#ifdef USE_BLUETOOTH_PROXY
1124bool APIConnection::send_subscribe_bluetooth_connections_free_response(
1132 msg.
mode == enums::BluetoothScannerMode::BLUETOOTH_SCANNER_MODE_ACTIVE);
1136#ifdef USE_VOICE_ASSISTANT
1137bool APIConnection::check_voice_assistant_api_connection_()
const {
1148 if (!this->check_voice_assistant_api_connection_()) {
1156 if (msg.
port == 0) {
1162 this->helper_->getpeername((
struct sockaddr *) &storage, &
len);
1167 if (this->check_voice_assistant_api_connection_()) {
1172 if (this->check_voice_assistant_api_connection_()) {
1177 if (this->check_voice_assistant_api_connection_()) {
1183 if (this->check_voice_assistant_api_connection_()) {
1190 if (!this->check_voice_assistant_api_connection_()) {
1191 return this->send_message(resp, VoiceAssistantConfigurationResponse::MESSAGE_TYPE);
1195 for (
auto &wake_word : config.available_wake_words) {
1198 resp_wake_word.set_id(
StringRef(wake_word.id));
1199 resp_wake_word.set_wake_word(
StringRef(wake_word.wake_word));
1200 for (
const auto &lang : wake_word.trained_languages) {
1201 resp_wake_word.trained_languages.push_back(lang);
1207 if (wake_word.model_type !=
"micro") {
1214 resp_wake_word.set_id(
StringRef(wake_word.id));
1215 resp_wake_word.set_wake_word(
StringRef(wake_word.wake_word));
1216 for (
const auto &lang : wake_word.trained_languages) {
1217 resp_wake_word.trained_languages.push_back(lang);
1223 return this->send_message(resp, VoiceAssistantConfigurationResponse::MESSAGE_TYPE);
1227 if (this->check_voice_assistant_api_connection_()) {
1233#ifdef USE_ZWAVE_PROXY
1243#ifdef USE_ALARM_CONTROL_PANEL
1245 return this->send_message_smart_(a_alarm_control_panel, &APIConnection::try_send_alarm_control_panel_state,
1246 AlarmControlPanelStateResponse::MESSAGE_TYPE,
1247 AlarmControlPanelStateResponse::ESTIMATED_SIZE);
1250 uint32_t remaining_size,
bool is_single) {
1254 return fill_and_encode_entity_state(a_alarm_control_panel, resp, AlarmControlPanelStateResponse::MESSAGE_TYPE, conn,
1255 remaining_size, is_single);
1258 uint32_t remaining_size,
bool is_single) {
1262 msg.
requires_code = a_alarm_control_panel->get_requires_code();
1264 return fill_and_encode_entity_info(a_alarm_control_panel, msg, ListEntitiesAlarmControlPanelResponse::MESSAGE_TYPE,
1265 conn, remaining_size, is_single);
1270 case enums::ALARM_CONTROL_PANEL_DISARM:
1273 case enums::ALARM_CONTROL_PANEL_ARM_AWAY:
1276 case enums::ALARM_CONTROL_PANEL_ARM_HOME:
1279 case enums::ALARM_CONTROL_PANEL_ARM_NIGHT:
1282 case enums::ALARM_CONTROL_PANEL_ARM_VACATION:
1283 call.arm_vacation();
1285 case enums::ALARM_CONTROL_PANEL_ARM_CUSTOM_BYPASS:
1286 call.arm_custom_bypass();
1288 case enums::ALARM_CONTROL_PANEL_TRIGGER:
1292 call.set_code(msg.
code);
1298void APIConnection::send_event(
event::Event *event,
const char *event_type) {
1299 this->send_message_smart_(event,
MessageCreator(event_type), EventResponse::MESSAGE_TYPE,
1300 EventResponse::ESTIMATED_SIZE);
1303 uint32_t remaining_size,
bool is_single) {
1306 return fill_and_encode_entity_state(event, resp, EventResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
1315 return fill_and_encode_entity_info(event, msg, ListEntitiesEventResponse::MESSAGE_TYPE, conn, remaining_size,
1322 return this->send_message_smart_(update, &APIConnection::try_send_update_state, UpdateStateResponse::MESSAGE_TYPE,
1323 UpdateStateResponse::ESTIMATED_SIZE);
1330 if (update->has_state()) {
1332 if (update->update_info.has_progress) {
1334 resp.
progress = update->update_info.progress;
1342 return fill_and_encode_entity_state(update, resp, UpdateStateResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
1349 return fill_and_encode_entity_info(update, msg, ListEntitiesUpdateResponse::MESSAGE_TYPE, conn, remaining_size,
1356 case enums::UPDATE_COMMAND_UPDATE:
1359 case enums::UPDATE_COMMAND_CHECK:
1362 case enums::UPDATE_COMMAND_NONE:
1363 ESP_LOGE(TAG,
"UPDATE_COMMAND_NONE not handled; confirm command is correct");
1366 ESP_LOGW(TAG,
"Unknown update command: %" PRIu32, msg.
command);
1372bool APIConnection::try_send_log_message(
int level,
const char *tag,
const char *line,
size_t message_len) {
1375 msg.
set_message(
reinterpret_cast<const uint8_t *
>(line), message_len);
1376 return this->send_message_(msg, SubscribeLogsResponse::MESSAGE_TYPE);
1379void APIConnection::complete_authentication_() {
1381 if (this->flags_.connection_state ==
static_cast<uint8_t
>(ConnectionState::AUTHENTICATED)) {
1385 this->flags_.connection_state =
static_cast<uint8_t
>(ConnectionState::AUTHENTICATED);
1386 ESP_LOGD(TAG,
"%s (%s) connected", this->client_info_.name.c_str(), this->client_info_.peername.c_str());
1387#ifdef USE_API_CLIENT_CONNECTED_TRIGGER
1388 this->parent_->get_client_connected_trigger()->trigger(this->client_info_.name, this->client_info_.peername);
1390#ifdef USE_HOMEASSISTANT_TIME
1392 this->send_time_request();
1395#ifdef USE_ZWAVE_PROXY
1404 this->client_info_.peername = this->helper_->getpeername();
1407 ESP_LOGV(TAG,
"Hello from client: '%s' | %s | API Version %" PRIu32
".%" PRIu32, this->client_info_.name.c_str(),
1408 this->client_info_.peername.c_str(), this->client_api_version_major_, this->client_api_version_minor_);
1417#ifdef USE_API_PASSWORD
1419 this->flags_.connection_state =
static_cast<uint8_t
>(ConnectionState::CONNECTED);
1422 this->complete_authentication_();
1425 return this->send_message(resp, HelloResponse::MESSAGE_TYPE);
1427#ifdef USE_API_PASSWORD
1433 this->complete_authentication_();
1435 return this->send_message(resp, AuthenticationResponse::MESSAGE_TYPE);
1441 return this->send_message(resp, PingResponse::MESSAGE_TYPE);
1446#ifdef USE_API_PASSWORD
1456 resp.set_mac_address(
StringRef(mac_address));
1458 resp.set_esphome_version(ESPHOME_VERSION_REF);
1463#if defined(USE_ESP8266) || defined(USE_ESP32)
1465#elif defined(USE_RP2040)
1467#elif defined(USE_BK72XX)
1469#elif defined(USE_LN882X)
1471#elif defined(USE_NRF52)
1473#elif defined(USE_RTL87XX)
1475#elif defined(USE_HOST)
1478 resp.set_manufacturer(MANUFACTURER);
1481 resp.set_model(MODEL);
1482#ifdef USE_DEEP_SLEEP
1485#ifdef ESPHOME_PROJECT_NAME
1488 resp.set_project_name(PROJECT_NAME);
1489 resp.set_project_version(PROJECT_VERSION);
1492 resp.webserver_port = USE_WEBSERVER_PORT;
1494#ifdef USE_BLUETOOTH_PROXY
1498 resp.set_bluetooth_mac_address(
StringRef(bluetooth_mac));
1500#ifdef USE_VOICE_ASSISTANT
1503#ifdef USE_ZWAVE_PROXY
1508 resp.api_encryption_supported =
true;
1511 size_t device_index = 0;
1513 if (device_index >= ESPHOME_DEVICE_COUNT)
1515 auto &device_info = resp.devices[device_index++];
1516 device_info.device_id = device->get_device_id();
1517 device_info.set_name(
StringRef(device->get_name()));
1518 device_info.area_id = device->get_area_id();
1522 size_t area_index = 0;
1524 if (area_index >= ESPHOME_AREA_COUNT)
1526 auto &area_info = resp.areas[area_index++];
1527 area_info.area_id = area->get_area_id();
1528 area_info.set_name(
StringRef(area->get_name()));
1532 return this->send_message(resp, DeviceInfoResponse::MESSAGE_TYPE);
1535#ifdef USE_API_HOMEASSISTANT_STATES
1537 for (
auto &it : this->parent_->get_state_subs()) {
1539 it.callback(msg.
state);
1544#ifdef USE_API_SERVICES
1547 for (
auto *service : this->parent_->get_user_services()) {
1548 if (service->execute_service(msg)) {
1553 ESP_LOGV(TAG,
"Could not find service");
1558#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES
1560#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES_JSON
1577 if (msg.
key.empty()) {
1578 if (this->parent_->clear_noise_psk(
true)) {
1581 ESP_LOGW(TAG,
"Failed to clear encryption key");
1584 ESP_LOGW(TAG,
"Invalid encryption key length");
1585 }
else if (!this->parent_->save_noise_psk(psk,
true)) {
1586 ESP_LOGW(TAG,
"Failed to save encryption key");
1591 return this->send_message(resp, NoiseEncryptionSetKeyResponse::MESSAGE_TYPE);
1594#ifdef USE_API_HOMEASSISTANT_STATES
1599bool APIConnection::try_to_clear_buffer(
bool log_out_of_space) {
1600 if (this->flags_.remove)
1602 if (this->helper_->can_write_without_blocking())
1605 APIError err = this->helper_->loop();
1606 if (err != APIError::OK) {
1607 this->fatal_error_with_log_(LOG_STR(
"Socket operation failed"), err);
1610 if (this->helper_->can_write_without_blocking())
1612 if (log_out_of_space) {
1613 ESP_LOGV(TAG,
"Cannot send message because of TCP buffer space");
1618 if (!this->try_to_clear_buffer(message_type != SubscribeLogsResponse::MESSAGE_TYPE)) {
1622 APIError err = this->helper_->write_protobuf_packet(message_type, buffer);
1623 if (err == APIError::WOULD_BLOCK)
1625 if (err != APIError::OK) {
1626 this->fatal_error_with_log_(LOG_STR(
"Packet write failed"), err);
1632#ifdef USE_API_PASSWORD
1633void APIConnection::on_unauthenticated_access() {
1634 this->on_fatal_error();
1635 ESP_LOGD(TAG,
"%s (%s) no authentication", this->client_info_.name.c_str(), this->client_info_.peername.c_str());
1638void APIConnection::on_no_setup_connection() {
1639 this->on_fatal_error();
1640 ESP_LOGD(TAG,
"%s (%s) no connection setup", this->client_info_.name.c_str(), this->client_info_.peername.c_str());
1642void APIConnection::on_fatal_error() {
1643 this->helper_->close();
1644 this->flags_.remove =
true;
1648 uint8_t estimated_size) {
1652 for (
auto &item : items) {
1653 if (item.entity == entity && item.message_type == message_type) {
1655 item.creator = std::move(creator);
1661 items.emplace_back(entity, std::move(creator), message_type, estimated_size);
1665 uint8_t estimated_size) {
1670 items.emplace_back(entity, std::move(creator), message_type, estimated_size);
1671 if (items.size() > 1) {
1673 std::swap(items.front(), items.back());
1677bool APIConnection::schedule_batch_() {
1678 if (!this->flags_.batch_scheduled) {
1679 this->flags_.batch_scheduled =
true;
1685void APIConnection::process_batch_() {
1687 static_assert(std::is_trivially_destructible<PacketInfo>::value,
1688 "PacketInfo must remain trivially destructible with this placement-new approach");
1690 if (this->deferred_batch_.empty()) {
1691 this->flags_.batch_scheduled =
false;
1696 if (!this->try_to_clear_buffer(
true)) {
1702 auto &shared_buf = this->parent_->get_shared_buffer_ref();
1703 size_t num_items = this->deferred_batch_.size();
1706 if (num_items == 1) {
1707 const auto &item = this->deferred_batch_[0];
1711 item.creator(item.entity,
this, std::numeric_limits<uint16_t>::max(),
true, item.message_type);
1714#ifdef HAS_PROTO_MESSAGE_DUMP
1717 this->log_batch_item_(item);
1719 this->clear_batch_();
1722 ESP_LOGW(TAG,
"Message too large to send: type=%u", item.message_type);
1723 this->clear_batch_();
1728 size_t packets_to_process = std::min(num_items, MAX_PACKETS_PER_BATCH);
1733 size_t packet_count = 0;
1736 const uint8_t header_padding = this->helper_->frame_header_padding();
1737 const uint8_t footer_size = this->helper_->frame_footer_size();
1743 uint32_t total_estimated_size = num_items * (header_padding + footer_size);
1744 for (
size_t i = 0; i < this->deferred_batch_.size(); i++) {
1745 const auto &item = this->deferred_batch_[i];
1746 total_estimated_size += item.estimated_size;
1751 shared_buf.reserve(total_estimated_size);
1752 this->flags_.batch_first_message =
true;
1754 size_t items_processed = 0;
1755 uint16_t remaining_size = std::numeric_limits<uint16_t>::max();
1761 uint32_t current_offset = 0;
1764 for (
size_t i = 0; i < packets_to_process; i++) {
1765 const auto &item = this->deferred_batch_[i];
1768 uint16_t
payload_size = item.creator(item.entity,
this, remaining_size,
false, item.message_type);
1777 uint16_t proto_payload_size =
payload_size - header_padding - footer_size;
1782 new (&packet_info[packet_count++])
PacketInfo(item.message_type, current_offset, proto_payload_size);
1787 if (items_processed == 1) {
1788 remaining_size = MAX_BATCH_PACKET_SIZE;
1793 current_offset = shared_buf.size() + footer_size;
1796 if (items_processed == 0) {
1797 this->deferred_batch_.clear();
1802 if (footer_size > 0) {
1803 shared_buf.resize(shared_buf.size() + footer_size);
1808 std::span<const PacketInfo>(packet_info, packet_count));
1809 if (err != APIError::OK && err != APIError::WOULD_BLOCK) {
1810 this->fatal_error_with_log_(LOG_STR(
"Batch write failed"), err);
1813#ifdef HAS_PROTO_MESSAGE_DUMP
1816 for (
size_t i = 0; i < items_processed; i++) {
1817 const auto &item = this->deferred_batch_[i];
1818 this->log_batch_item_(item);
1823 if (items_processed < this->deferred_batch_.size()) {
1825 this->deferred_batch_.remove_front(items_processed);
1827 this->schedule_batch_();
1830 this->clear_batch_();
1835 bool is_single, uint8_t message_type)
const {
1838 if (message_type == EventResponse::MESSAGE_TYPE) {
1840 return APIConnection::try_send_event_response(e, data_.const_char_ptr, conn, remaining_size, is_single);
1845 return data_.function_ptr(entity, conn, remaining_size, is_single);
1851 return encode_message_to_buffer(resp, ListEntitiesDoneResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
1857 return encode_message_to_buffer(req, DisconnectRequest::MESSAGE_TYPE, conn, remaining_size, is_single);
1863 return encode_message_to_buffer(req, PingRequest::MESSAGE_TYPE, conn, remaining_size, is_single);
1866#ifdef USE_API_HOMEASSISTANT_STATES
1867void APIConnection::process_state_subscriptions_() {
1868 const auto &subs = this->parent_->get_state_subs();
1869 if (this->state_subs_at_ >=
static_cast<int>(subs.size())) {
1870 this->state_subs_at_ = -1;
1874 const auto &it = subs[this->state_subs_at_];
1881 resp.
once = it.once;
1882 if (this->send_message(resp, SubscribeHomeAssistantStateResponse::MESSAGE_TYPE)) {
1883 this->state_subs_at_++;
1889 ESP_LOGW(TAG,
"%s (%s): %s %s errno=%d", this->client_info_.name.c_str(), this->client_info_.peername.c_str(),
const std::string & get_friendly_name() const
Get the friendly name of this Application set by pre_setup().
const char * get_area() const
Get the area of this Application set by pre_setup().
const auto & get_devices()
const std::string & get_name() const
Get the name of this Application set by pre_setup().
StringRef get_compilation_time_ref() const
Get the compilation time as StringRef (for API usage)
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.
uint32_t get_object_id_hash()
uint32_t get_device_id() const
StringRef is a reference to a string owned by something else.
static constexpr StringRef from_lit(const CharT(&s)[N])
struct esphome::api::APIConnection::APIFlags flags_
void prepare_first_message_buffer(std::vector< uint8_t > &shared_buf, size_t header_padding, size_t total_size)
std::unique_ptr< APIFrameHelper > helper_
APIConnection(std::unique_ptr< socket::Socket > socket, APIServer *parent)
void button_command(const ButtonCommandRequest &msg) override
void log_send_message_(const char *name, const std::string &dump)
std::shared_ptr< APINoiseContext > get_noise_ctx()
std::vector< uint8_t > & get_shared_buffer_ref()
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
float target_temperature_high
enums::ClimateSwingMode swing_mode
enums::ClimateFanMode fan_mode
bool has_target_temperature
std::string custom_fan_mode
enums::ClimatePreset preset
std::string custom_preset
enums::ClimateFanMode fan_mode
float target_temperature_low
enums::ClimateSwingMode swing_mode
void set_custom_fan_mode(const StringRef &ref)
void set_custom_preset(const StringRef &ref)
enums::ClimateAction action
enums::ClimatePreset preset
float current_temperature
float target_temperature_high
enums::CoverOperation current_operation
void set_event_type(const StringRef &ref)
enums::FanDirection direction
enums::FanDirection direction
void set_preset_mode(const StringRef &ref)
const uint8_t * client_info
uint32_t api_version_major
uint32_t api_version_minor
uint32_t api_version_minor
void set_name(const StringRef &ref)
void set_server_info(const StringRef &ref)
uint32_t api_version_major
const uint8_t * response_data
std::string error_message
uint16_t response_data_len
bool has_color_temperature
enums::ColorMode color_mode
bool has_transition_length
uint32_t transition_length
bool has_color_brightness
void set_effect(const StringRef &ref)
enums::ColorMode color_mode
bool requires_code_to_arm
uint32_t supported_features
bool is_status_binary_sensor
void set_device_class(const StringRef &ref)
const std::vector< const char * > * supported_custom_presets
const climate::ClimateSwingModeMask * supported_swing_modes
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
void set_device_class(const StringRef &ref)
const FixedVector< const char * > * event_types
void set_device_class(const StringRef &ref)
const std::vector< const char * > * supported_preset_modes
int32_t supported_speed_count
bool supports_oscillation
const light::ColorModeMask * supported_color_modes
std::vector< std::string > effects
void set_unit_of_measurement(const StringRef &ref)
void set_device_class(const StringRef &ref)
const FixedVector< const char * > * options
int32_t accuracy_decimals
void set_unit_of_measurement(const StringRef &ref)
void set_device_class(const StringRef &ref)
enums::SensorStateClass state_class
void set_device_class(const StringRef &ref)
void set_pattern(const StringRef &ref)
void set_device_class(const StringRef &ref)
void set_device_class(const StringRef &ref)
void set_device_class(const StringRef &ref)
enums::LockCommand command
virtual void encode(ProtoWriteBuffer buffer) const
virtual const char * message_name() const
virtual void calculate_size(ProtoSize &size) const
uint32_t get_size() const
void set_state(const StringRef &ref)
void set_entity_id(const StringRef &ref)
void set_attribute(const StringRef &ref)
void set_message(const uint8_t *data, size_t len)
void set_state(const StringRef &ref)
void set_state(const StringRef &ref)
enums::UpdateCommand command
void set_current_version(const StringRef &ref)
void set_latest_version(const StringRef &ref)
void set_release_summary(const StringRef &ref)
void set_title(const StringRef &ref)
void set_release_url(const StringRef &ref)
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
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 bluetooth_gatt_read_descriptor(const api::BluetoothGATTReadDescriptorRequest &msg)
void bluetooth_gatt_write(const api::BluetoothGATTWriteRequest &msg)
void bluetooth_gatt_notify(const api::BluetoothGATTNotifyRequest &msg)
std::string get_bluetooth_mac_address_pretty()
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.
void set_epoch_time(uint32_t epoch)
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.
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 std::string &tz)
Set the time zone.
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)
void send_frame(const uint8_t *data, size_t length)
uint32_t get_feature_flags() const
void api_connection_authenticated(api::APIConnection *conn)
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.
@ UPDATE_STATE_INSTALLING
VoiceAssistant * global_voice_assistant
ZWaveProxy * global_zwave_proxy
std::string get_mac_address_pretty()
Get the device MAC address as a string, in colon-separated uppercase hex notation.
void IRAM_ATTR HOT delay(uint32_t ms)
Application App
Global storage of Application pointer - only one Application can exist.
size_t base64_decode(const std::string &encoded_string, uint8_t *buf, size_t buf_len)
A more user-friendly version of struct tm from time.h.
uint8_t batch_first_message
std::vector< uint8_t > container