6#ifdef USE_API_PLAINTEXT
24#ifdef USE_HOMEASSISTANT_TIME
27#ifdef USE_BLUETOOTH_PROXY
30#ifdef USE_VOICE_ASSISTANT
40static constexpr uint8_t MAX_MESSAGES_PER_LOOP = 5;
41static constexpr uint8_t MAX_PING_RETRIES = 60;
42static constexpr uint16_t PING_RETRY_INTERVAL = 1000;
43static constexpr uint32_t KEEPALIVE_DISCONNECT_TIMEOUT = (KEEPALIVE_TIMEOUT_MS * 5) / 2;
47static const char *
const TAG =
"api.connection";
49static const int CAMERA_STOP_STREAM = 5000;
55#define ENTITY_COMMAND_MAKE_CALL(entity_type, entity_var, getter_name) \
56 entity_type *entity_var = App.get_##getter_name##_by_key(msg.key, msg.device_id); \
57 if ((entity_var) == nullptr) \
59 auto call = (entity_var)->make_call();
63#define ENTITY_COMMAND_GET(entity_type, entity_var, getter_name) \
64 entity_type *entity_var = App.get_##getter_name##_by_key(msg.key, msg.device_id); \
65 if ((entity_var) == nullptr) \
70#define ENTITY_COMMAND_MAKE_CALL(entity_type, entity_var, getter_name) \
71 entity_type *entity_var = App.get_##getter_name##_by_key(msg.key); \
72 if ((entity_var) == nullptr) \
74 auto call = (entity_var)->make_call();
78#define ENTITY_COMMAND_GET(entity_type, entity_var, getter_name) \
79 entity_type *entity_var = App.get_##getter_name##_by_key(msg.key); \
80 if ((entity_var) == nullptr) \
85 : parent_(parent), initial_state_iterator_(this), list_entities_iterator_(this) {
86#if defined(USE_API_PLAINTEXT) && defined(USE_API_NOISE)
88 if (noise_ctx->has_psk()) {
90 std::unique_ptr<APIFrameHelper>{new APINoiseFrameHelper(std::move(sock), noise_ctx, &this->client_info_)};
92 this->helper_ = std::unique_ptr<APIFrameHelper>{
new APIPlaintextFrameHelper(std::move(sock), &this->client_info_)};
94#elif defined(USE_API_PLAINTEXT)
95 this->helper_ = std::unique_ptr<APIFrameHelper>{
new APIPlaintextFrameHelper(std::move(sock), &this->client_info_)};
96#elif defined(USE_API_NOISE)
97 this->helper_ = std::unique_ptr<APIFrameHelper>{
98 new APINoiseFrameHelper(std::move(sock), parent->get_noise_ctx(), &this->client_info_)};
100#error "No frame helper defined"
109uint32_t APIConnection::get_batch_delay_ms_()
const {
return this->parent_->get_batch_delay(); }
111void APIConnection::start() {
114 APIError err = this->helper_->init();
115 if (err != APIError::OK) {
117 this->log_warning_(LOG_STR(
"Helper init failed"), err);
120 this->client_info_.peername = helper_->getpeername();
121 this->client_info_.name = this->client_info_.peername;
124APIConnection::~APIConnection() {
125#ifdef USE_BLUETOOTH_PROXY
130#ifdef USE_VOICE_ASSISTANT
137void APIConnection::loop() {
138 if (this->flags_.next_close) {
140 this->helper_->close();
141 this->flags_.remove =
true;
145 APIError err = this->helper_->loop();
146 if (err != APIError::OK) {
148 this->log_socket_operation_failed_(err);
154 if (this->helper_->is_socket_ready()) {
156 for (uint8_t message_count = 0; message_count < MAX_MESSAGES_PER_LOOP; message_count++) {
158 err = this->helper_->read_packet(&buffer);
159 if (err == APIError::WOULD_BLOCK) {
162 }
else if (err != APIError::OK) {
164 this->log_warning_(LOG_STR(
"Reading failed"), err);
167 this->last_traffic_ = now;
172 this->read_message(0, buffer.
type,
nullptr);
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 is unresponsive; disconnecting", this->get_client_combined_info().c_str());
207 }
else if (now - this->last_traffic_ > KEEPALIVE_TIMEOUT_MS && !this->flags_.remove) {
209 ESP_LOGVV(TAG,
"Sending keepalive PING");
211 this->flags_.sent_ping = this->send_message(req, PingRequest::MESSAGE_TYPE);
212 if (!this->flags_.sent_ping) {
215 ESP_LOGW(TAG,
"Buffer full, ping queued");
216 this->schedule_message_front_(
nullptr, &APIConnection::try_send_ping_request, PingRequest::MESSAGE_TYPE,
217 PingRequest::ESTIMATED_SIZE);
218 this->flags_.sent_ping =
true;
223 if (this->image_reader_ && this->image_reader_->available() && this->helper_->can_write_without_blocking()) {
224 uint32_t to_send = std::min((
size_t) MAX_BATCH_PACKET_SIZE, this->image_reader_->available());
225 bool done = this->image_reader_->available() == to_send;
229 msg.
set_data(this->image_reader_->peek_data_buffer(), to_send);
235 if (this->send_message_(msg, CameraImageResponse::MESSAGE_TYPE)) {
236 this->image_reader_->consume_data(to_send);
238 this->image_reader_->return_image();
244#ifdef USE_API_HOMEASSISTANT_STATES
245 if (state_subs_at_ >= 0) {
246 this->process_state_subscriptions_();
255 ESP_LOGD(TAG,
"%s disconnected", this->get_client_combined_info().c_str());
256 this->flags_.next_close =
true;
258 return this->send_message(resp, DisconnectResponse::MESSAGE_TYPE);
261 this->helper_->close();
262 this->flags_.remove =
true;
268 uint32_t remaining_size,
bool is_single) {
269#ifdef HAS_PROTO_MESSAGE_DUMP
280 uint32_t calculated_size = size_calc.
get_size();
283 const uint8_t header_padding = conn->
helper_->frame_header_padding();
284 const uint8_t footer_size = conn->
helper_->frame_footer_size();
287 size_t total_calculated_size = calculated_size + header_padding + footer_size;
290 if (total_calculated_size > remaining_size) {
306 size_t current_size = shared_buf.size();
307 shared_buf.reserve(current_size + total_calculated_size);
308 shared_buf.resize(current_size + footer_size + header_padding);
312 size_t size_before_encode = shared_buf.size();
313 msg.
encode({&shared_buf});
316 size_t actual_payload_size = shared_buf.size() - size_before_encode;
319 size_t actual_total_size = header_padding + actual_payload_size + footer_size;
322 assert(calculated_size == actual_payload_size);
323 return static_cast<uint16_t
>(actual_total_size);
326#ifdef USE_BINARY_SENSOR
328 return this->send_message_smart_(binary_sensor, &APIConnection::try_send_binary_sensor_state,
329 BinarySensorStateResponse::MESSAGE_TYPE, BinarySensorStateResponse::ESTIMATED_SIZE);
336 resp.
state = binary_sensor->state;
338 return fill_and_encode_entity_state(binary_sensor, resp, BinarySensorStateResponse::MESSAGE_TYPE, conn,
339 remaining_size, is_single);
348 return fill_and_encode_entity_info(binary_sensor, msg, ListEntitiesBinarySensorResponse::MESSAGE_TYPE, conn,
349 remaining_size, is_single);
355 return this->send_message_smart_(cover, &APIConnection::try_send_cover_state, CoverStateResponse::MESSAGE_TYPE,
356 CoverStateResponse::ESTIMATED_SIZE);
362 auto traits = cover->get_traits();
364 if (traits.get_supports_tilt())
365 msg.
tilt = cover->tilt;
367 return fill_and_encode_entity_state(cover, msg, CoverStateResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
373 auto traits = cover->get_traits();
379 return fill_and_encode_entity_info(cover, msg, ListEntitiesCoverResponse::MESSAGE_TYPE, conn, remaining_size,
387 call.set_tilt(msg.
tilt);
389 call.set_command_stop();
396 return this->send_message_smart_(fan, &APIConnection::try_send_fan_state, FanStateResponse::MESSAGE_TYPE,
397 FanStateResponse::ESTIMATED_SIZE);
401 auto *fan =
static_cast<fan::Fan *
>(entity);
403 auto traits = fan->get_traits();
404 msg.
state = fan->state;
405 if (traits.supports_oscillation())
407 if (traits.supports_speed()) {
410 if (traits.supports_direction())
412 if (traits.supports_preset_modes())
414 return fill_and_encode_entity_state(fan, msg, FanStateResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
418 auto *fan =
static_cast<fan::Fan *
>(entity);
420 auto traits = fan->get_traits();
426 return fill_and_encode_entity_info(fan, msg, ListEntitiesFanResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
429 ENTITY_COMMAND_MAKE_CALL(
fan::Fan, fan, fan)
431 call.set_state(msg.
state);
448 return this->send_message_smart_(light, &APIConnection::try_send_light_state, LightStateResponse::MESSAGE_TYPE,
449 LightStateResponse::ESTIMATED_SIZE);
455 auto traits = light->get_traits();
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();
485 if (light->supports_effects()) {
486 msg.
effects.emplace_back(
"None");
487 for (
auto *effect : light->get_effects()) {
488 msg.
effects.push_back(effect->get_name());
491 return fill_and_encode_entity_info(light, msg, ListEntitiesLightResponse::MESSAGE_TYPE, conn, remaining_size,
497 call.set_state(msg.
state);
505 call.set_red(msg.
red);
506 call.set_green(msg.
green);
507 call.set_blue(msg.
blue);
510 call.set_white(msg.
white);
522 call.set_effect(msg.
effect);
529 return this->send_message_smart_(sensor, &APIConnection::try_send_sensor_state, SensorStateResponse::MESSAGE_TYPE,
530 SensorStateResponse::ESTIMATED_SIZE);
537 resp.
state = sensor->state;
539 return fill_and_encode_entity_state(sensor, resp, SensorStateResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
551 return fill_and_encode_entity_info(sensor, msg, ListEntitiesSensorResponse::MESSAGE_TYPE, conn, remaining_size,
558 return this->send_message_smart_(a_switch, &APIConnection::try_send_switch_state, SwitchStateResponse::MESSAGE_TYPE,
559 SwitchStateResponse::ESTIMATED_SIZE);
566 resp.
state = a_switch->state;
567 return fill_and_encode_entity_state(a_switch, resp, SwitchStateResponse::MESSAGE_TYPE, conn, remaining_size,
577 return fill_and_encode_entity_info(a_switch, msg, ListEntitiesSwitchResponse::MESSAGE_TYPE, conn, remaining_size,
586 a_switch->turn_off();
591#ifdef USE_TEXT_SENSOR
593 return this->send_message_smart_(text_sensor, &APIConnection::try_send_text_sensor_state,
594 TextSensorStateResponse::MESSAGE_TYPE, TextSensorStateResponse::ESTIMATED_SIZE);
603 return fill_and_encode_entity_state(text_sensor, resp, TextSensorStateResponse::MESSAGE_TYPE, conn, remaining_size,
611 return fill_and_encode_entity_info(text_sensor, msg, ListEntitiesTextSensorResponse::MESSAGE_TYPE, conn,
612 remaining_size, is_single);
618 return this->send_message_smart_(climate, &APIConnection::try_send_climate_state, ClimateStateResponse::MESSAGE_TYPE,
619 ClimateStateResponse::ESTIMATED_SIZE);
625 auto traits = climate->get_traits();
628 if (traits.get_supports_current_temperature())
630 if (traits.get_supports_two_point_target_temperature()) {
636 if (traits.get_supports_fan_modes() && climate->fan_mode.has_value())
638 if (!traits.get_supported_custom_fan_modes().empty() && climate->custom_fan_mode.has_value()) {
641 if (traits.get_supports_presets() && climate->preset.has_value()) {
644 if (!traits.get_supported_custom_presets().empty() && climate->custom_preset.has_value()) {
647 if (traits.get_supports_swing_modes())
649 if (traits.get_supports_current_humidity())
651 if (traits.get_supports_target_humidity())
653 return fill_and_encode_entity_state(climate, resp, ClimateStateResponse::MESSAGE_TYPE, conn, remaining_size,
660 auto traits = climate->get_traits();
678 return fill_and_encode_entity_info(climate, msg, ListEntitiesClimateResponse::MESSAGE_TYPE, conn, remaining_size,
709 return this->send_message_smart_(number, &APIConnection::try_send_number_state, NumberStateResponse::MESSAGE_TYPE,
710 NumberStateResponse::ESTIMATED_SIZE);
717 resp.
state = number->state;
719 return fill_and_encode_entity_state(number, resp, NumberStateResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
729 msg.
min_value = number->traits.get_min_value();
730 msg.
max_value = number->traits.get_max_value();
731 msg.
step = number->traits.get_step();
732 return fill_and_encode_entity_info(number, msg, ListEntitiesNumberResponse::MESSAGE_TYPE, conn, remaining_size,
737 call.set_value(msg.
state);
742#ifdef USE_DATETIME_DATE
744 return this->send_message_smart_(date, &APIConnection::try_send_date_state, DateStateResponse::MESSAGE_TYPE,
745 DateStateResponse::ESTIMATED_SIZE);
752 resp.
year = date->year;
753 resp.
month = date->month;
754 resp.
day = date->day;
755 return fill_and_encode_entity_state(date, resp, DateStateResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
761 return fill_and_encode_entity_info(date, msg, ListEntitiesDateResponse::MESSAGE_TYPE, conn, remaining_size,
771#ifdef USE_DATETIME_TIME
773 return this->send_message_smart_(time, &APIConnection::try_send_time_state, TimeStateResponse::MESSAGE_TYPE,
774 TimeStateResponse::ESTIMATED_SIZE);
781 resp.
hour = time->hour;
782 resp.
minute = time->minute;
783 resp.
second = time->second;
784 return fill_and_encode_entity_state(time, resp, TimeStateResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
790 return fill_and_encode_entity_info(time, msg, ListEntitiesTimeResponse::MESSAGE_TYPE, conn, remaining_size,
800#ifdef USE_DATETIME_DATETIME
802 return this->send_message_smart_(datetime, &APIConnection::try_send_datetime_state,
803 DateTimeStateResponse::MESSAGE_TYPE, DateTimeStateResponse::ESTIMATED_SIZE);
810 if (datetime->has_state()) {
814 return fill_and_encode_entity_state(datetime, resp, DateTimeStateResponse::MESSAGE_TYPE, conn, remaining_size,
821 return fill_and_encode_entity_info(datetime, msg, ListEntitiesDateTimeResponse::MESSAGE_TYPE, conn, remaining_size,
833 return this->send_message_smart_(text, &APIConnection::try_send_text_state, TextStateResponse::MESSAGE_TYPE,
834 TextStateResponse::ESTIMATED_SIZE);
839 auto *text =
static_cast<text::Text *
>(entity);
843 return fill_and_encode_entity_state(text, resp, TextStateResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
848 auto *text =
static_cast<text::Text *
>(entity);
851 msg.
min_length = text->traits.get_min_length();
852 msg.
max_length = text->traits.get_max_length();
854 return fill_and_encode_entity_info(text, msg, ListEntitiesTextResponse::MESSAGE_TYPE, conn, remaining_size,
858 ENTITY_COMMAND_MAKE_CALL(
text::Text, text, text)
859 call.set_value(msg.
state);
866 return this->send_message_smart_(select, &APIConnection::try_send_select_state, SelectStateResponse::MESSAGE_TYPE,
867 SelectStateResponse::ESTIMATED_SIZE);
876 return fill_and_encode_entity_state(select, resp, SelectStateResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
883 msg.
options = &select->traits.get_options();
884 return fill_and_encode_entity_info(select, msg, ListEntitiesSelectResponse::MESSAGE_TYPE, conn, remaining_size,
889 call.set_option(msg.
state);
900 return fill_and_encode_entity_info(button, msg, ListEntitiesButtonResponse::MESSAGE_TYPE, conn, remaining_size,
911 return this->send_message_smart_(a_lock, &APIConnection::try_send_lock_state, LockStateResponse::MESSAGE_TYPE,
912 LockStateResponse::ESTIMATED_SIZE);
917 auto *a_lock =
static_cast<lock::Lock *
>(entity);
920 return fill_and_encode_entity_state(a_lock, resp, LockStateResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
925 auto *a_lock =
static_cast<lock::Lock *
>(entity);
930 return fill_and_encode_entity_info(a_lock, msg, ListEntitiesLockResponse::MESSAGE_TYPE, conn, remaining_size,
937 case enums::LOCK_UNLOCK:
940 case enums::LOCK_LOCK:
943 case enums::LOCK_OPEN:
952 return this->send_message_smart_(valve, &APIConnection::try_send_valve_state, ValveStateResponse::MESSAGE_TYPE,
953 ValveStateResponse::ESTIMATED_SIZE);
961 return fill_and_encode_entity_state(valve, resp, ValveStateResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
967 auto traits = valve->get_traits();
972 return fill_and_encode_entity_info(valve, msg, ListEntitiesValveResponse::MESSAGE_TYPE, conn, remaining_size,
980 call.set_command_stop();
985#ifdef USE_MEDIA_PLAYER
987 return this->send_message_smart_(media_player, &APIConnection::try_send_media_player_state,
988 MediaPlayerStateResponse::MESSAGE_TYPE, MediaPlayerStateResponse::ESTIMATED_SIZE);
996 : media_player->state;
998 resp.
volume = media_player->volume;
999 resp.
muted = media_player->is_muted();
1000 return fill_and_encode_entity_state(media_player, resp, MediaPlayerStateResponse::MESSAGE_TYPE, conn, remaining_size,
1007 auto traits = media_player->get_traits();
1010 for (
auto &supported_format : traits.get_supported_formats()) {
1013 media_format.set_format(
StringRef(supported_format.format));
1014 media_format.sample_rate = supported_format.sample_rate;
1015 media_format.num_channels = supported_format.num_channels;
1017 media_format.sample_bytes = supported_format.sample_bytes;
1019 return fill_and_encode_entity_info(media_player, msg, ListEntitiesMediaPlayerResponse::MESSAGE_TYPE, conn,
1020 remaining_size, is_single);
1028 call.set_volume(msg.
volume);
1041void APIConnection::set_camera_state(std::shared_ptr<camera::CameraImage> image) {
1042 if (!this->flags_.state_subscription)
1044 if (!this->image_reader_)
1046 if (this->image_reader_->available())
1049 this->image_reader_->set_image(std::move(image));
1055 return fill_and_encode_entity_info(camera, msg, ListEntitiesCameraResponse::MESSAGE_TYPE, conn, remaining_size,
1067 App.scheduler.set_timeout(this->parent_,
"api_camera_stop_stream", CAMERA_STOP_STREAM,
1073#ifdef USE_HOMEASSISTANT_TIME
1077#ifdef USE_TIME_TIMEZONE
1086#ifdef USE_BLUETOOTH_PROXY
1116bool APIConnection::send_subscribe_bluetooth_connections_free_response(
1124 msg.
mode == enums::BluetoothScannerMode::BLUETOOTH_SCANNER_MODE_ACTIVE);
1128#ifdef USE_VOICE_ASSISTANT
1129bool APIConnection::check_voice_assistant_api_connection_()
const {
1140 if (!this->check_voice_assistant_api_connection_()) {
1148 if (msg.
port == 0) {
1154 this->helper_->getpeername((
struct sockaddr *) &storage, &
len);
1159 if (this->check_voice_assistant_api_connection_()) {
1164 if (this->check_voice_assistant_api_connection_()) {
1169 if (this->check_voice_assistant_api_connection_()) {
1175 if (this->check_voice_assistant_api_connection_()) {
1182 if (!this->check_voice_assistant_api_connection_()) {
1183 return this->send_message(resp, VoiceAssistantConfigurationResponse::MESSAGE_TYPE);
1187 for (
auto &wake_word : config.available_wake_words) {
1190 resp_wake_word.set_id(
StringRef(wake_word.id));
1191 resp_wake_word.set_wake_word(
StringRef(wake_word.wake_word));
1192 for (
const auto &lang : wake_word.trained_languages) {
1193 resp_wake_word.trained_languages.push_back(lang);
1198 return this->send_message(resp, VoiceAssistantConfigurationResponse::MESSAGE_TYPE);
1202 if (this->check_voice_assistant_api_connection_()) {
1209#ifdef USE_ALARM_CONTROL_PANEL
1211 return this->send_message_smart_(a_alarm_control_panel, &APIConnection::try_send_alarm_control_panel_state,
1212 AlarmControlPanelStateResponse::MESSAGE_TYPE,
1213 AlarmControlPanelStateResponse::ESTIMATED_SIZE);
1216 uint32_t remaining_size,
bool is_single) {
1220 return fill_and_encode_entity_state(a_alarm_control_panel, resp, AlarmControlPanelStateResponse::MESSAGE_TYPE, conn,
1221 remaining_size, is_single);
1224 uint32_t remaining_size,
bool is_single) {
1228 msg.
requires_code = a_alarm_control_panel->get_requires_code();
1230 return fill_and_encode_entity_info(a_alarm_control_panel, msg, ListEntitiesAlarmControlPanelResponse::MESSAGE_TYPE,
1231 conn, remaining_size, is_single);
1236 case enums::ALARM_CONTROL_PANEL_DISARM:
1239 case enums::ALARM_CONTROL_PANEL_ARM_AWAY:
1242 case enums::ALARM_CONTROL_PANEL_ARM_HOME:
1245 case enums::ALARM_CONTROL_PANEL_ARM_NIGHT:
1248 case enums::ALARM_CONTROL_PANEL_ARM_VACATION:
1249 call.arm_vacation();
1251 case enums::ALARM_CONTROL_PANEL_ARM_CUSTOM_BYPASS:
1252 call.arm_custom_bypass();
1254 case enums::ALARM_CONTROL_PANEL_TRIGGER:
1258 call.set_code(msg.
code);
1264void APIConnection::send_event(
event::Event *event,
const std::string &event_type) {
1265 this->schedule_message_(event,
MessageCreator(event_type), EventResponse::MESSAGE_TYPE,
1266 EventResponse::ESTIMATED_SIZE);
1269 uint32_t remaining_size,
bool is_single) {
1272 return fill_and_encode_entity_state(event, resp, EventResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
1280 for (
const auto &event_type : event->get_event_types())
1282 return fill_and_encode_entity_info(event, msg, ListEntitiesEventResponse::MESSAGE_TYPE, conn, remaining_size,
1289 return this->send_message_smart_(update, &APIConnection::try_send_update_state, UpdateStateResponse::MESSAGE_TYPE,
1290 UpdateStateResponse::ESTIMATED_SIZE);
1297 if (update->has_state()) {
1299 if (update->update_info.has_progress) {
1301 resp.
progress = update->update_info.progress;
1309 return fill_and_encode_entity_state(update, resp, UpdateStateResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
1316 return fill_and_encode_entity_info(update, msg, ListEntitiesUpdateResponse::MESSAGE_TYPE, conn, remaining_size,
1323 case enums::UPDATE_COMMAND_UPDATE:
1326 case enums::UPDATE_COMMAND_CHECK:
1329 case enums::UPDATE_COMMAND_NONE:
1330 ESP_LOGE(TAG,
"UPDATE_COMMAND_NONE not handled; confirm command is correct");
1333 ESP_LOGW(TAG,
"Unknown update command: %" PRIu32, msg.
command);
1339bool APIConnection::try_send_log_message(
int level,
const char *tag,
const char *line,
size_t message_len) {
1342 msg.
set_message(
reinterpret_cast<const uint8_t *
>(line), message_len);
1343 return this->send_message_(msg, SubscribeLogsResponse::MESSAGE_TYPE);
1346void APIConnection::complete_authentication_() {
1348 if (this->flags_.connection_state ==
static_cast<uint8_t
>(ConnectionState::AUTHENTICATED)) {
1352 this->flags_.connection_state =
static_cast<uint8_t
>(ConnectionState::AUTHENTICATED);
1353 ESP_LOGD(TAG,
"%s connected", this->get_client_combined_info().c_str());
1354#ifdef USE_API_CLIENT_CONNECTED_TRIGGER
1355 this->parent_->get_client_connected_trigger()->trigger(this->client_info_.name, this->client_info_.peername);
1357#ifdef USE_HOMEASSISTANT_TIME
1359 this->send_time_request();
1366 this->client_info_.peername = this->helper_->getpeername();
1369 ESP_LOGV(TAG,
"Hello from client: '%s' | %s | API Version %" PRIu32
".%" PRIu32, this->client_info_.name.c_str(),
1370 this->client_info_.peername.c_str(), this->client_api_version_major_, this->client_api_version_minor_);
1379#ifdef USE_API_PASSWORD
1381 this->flags_.connection_state =
static_cast<uint8_t
>(ConnectionState::CONNECTED);
1384 this->complete_authentication_();
1387 return this->send_message(resp, HelloResponse::MESSAGE_TYPE);
1390 bool correct =
true;
1391#ifdef USE_API_PASSWORD
1392 correct = this->parent_->check_password(msg.
password);
1399 this->complete_authentication_();
1401 return this->send_message(resp, ConnectResponse::MESSAGE_TYPE);
1406 return this->send_message(resp, PingResponse::MESSAGE_TYPE);
1411#ifdef USE_API_PASSWORD
1421 resp.set_mac_address(
StringRef(mac_address));
1423 resp.set_esphome_version(ESPHOME_VERSION_REF);
1428#if defined(USE_ESP8266) || defined(USE_ESP32)
1430#elif defined(USE_RP2040)
1432#elif defined(USE_BK72XX)
1434#elif defined(USE_LN882X)
1436#elif defined(USE_RTL87XX)
1438#elif defined(USE_HOST)
1441 resp.set_manufacturer(MANUFACTURER);
1444 resp.set_model(MODEL);
1445#ifdef USE_DEEP_SLEEP
1448#ifdef ESPHOME_PROJECT_NAME
1451 resp.set_project_name(PROJECT_NAME);
1452 resp.set_project_version(PROJECT_VERSION);
1455 resp.webserver_port = USE_WEBSERVER_PORT;
1457#ifdef USE_BLUETOOTH_PROXY
1461 resp.set_bluetooth_mac_address(
StringRef(bluetooth_mac));
1463#ifdef USE_VOICE_ASSISTANT
1467 resp.api_encryption_supported =
true;
1470 size_t device_index = 0;
1472 if (device_index >= ESPHOME_DEVICE_COUNT)
1474 auto &device_info = resp.devices[device_index++];
1475 device_info.device_id = device->get_device_id();
1476 device_info.set_name(
StringRef(device->get_name()));
1477 device_info.area_id = device->get_area_id();
1481 size_t area_index = 0;
1483 if (area_index >= ESPHOME_AREA_COUNT)
1485 auto &area_info = resp.areas[area_index++];
1486 area_info.area_id = area->get_area_id();
1487 area_info.set_name(
StringRef(area->get_name()));
1491 return this->send_message(resp, DeviceInfoResponse::MESSAGE_TYPE);
1494#ifdef USE_API_HOMEASSISTANT_STATES
1496 for (
auto &it : this->parent_->get_state_subs()) {
1498 it.callback(msg.
state);
1503#ifdef USE_API_SERVICES
1506 for (
auto *service : this->parent_->get_user_services()) {
1507 if (service->execute_service(msg)) {
1512 ESP_LOGV(TAG,
"Could not find service");
1523 ESP_LOGW(TAG,
"Invalid encryption key length");
1524 }
else if (!this->parent_->save_noise_psk(psk,
true)) {
1525 ESP_LOGW(TAG,
"Failed to save encryption key");
1530 return this->send_message(resp, NoiseEncryptionSetKeyResponse::MESSAGE_TYPE);
1533#ifdef USE_API_HOMEASSISTANT_STATES
1538bool APIConnection::try_to_clear_buffer(
bool log_out_of_space) {
1539 if (this->flags_.remove)
1541 if (this->helper_->can_write_without_blocking())
1544 APIError err = this->helper_->loop();
1545 if (err != APIError::OK) {
1547 this->log_socket_operation_failed_(err);
1550 if (this->helper_->can_write_without_blocking())
1552 if (log_out_of_space) {
1553 ESP_LOGV(TAG,
"Cannot send message because of TCP buffer space");
1558 if (!this->try_to_clear_buffer(message_type != SubscribeLogsResponse::MESSAGE_TYPE)) {
1562 APIError err = this->helper_->write_protobuf_packet(message_type, buffer);
1563 if (err == APIError::WOULD_BLOCK)
1565 if (err != APIError::OK) {
1567 this->log_warning_(LOG_STR(
"Packet write failed"), err);
1573#ifdef USE_API_PASSWORD
1574void APIConnection::on_unauthenticated_access() {
1575 this->on_fatal_error();
1576 ESP_LOGD(TAG,
"%s access without authentication", this->get_client_combined_info().c_str());
1579void APIConnection::on_no_setup_connection() {
1580 this->on_fatal_error();
1581 ESP_LOGD(TAG,
"%s access without full connection", this->get_client_combined_info().c_str());
1583void APIConnection::on_fatal_error() {
1584 this->helper_->close();
1585 this->flags_.remove =
true;
1589 uint8_t estimated_size) {
1593 for (
auto &item : items) {
1594 if (item.entity == entity && item.message_type == message_type) {
1596 item.creator.cleanup(message_type);
1598 item.creator = std::move(creator);
1604 items.emplace_back(entity, std::move(creator), message_type, estimated_size);
1608 uint8_t estimated_size) {
1613 items.emplace_back(entity, std::move(creator), message_type, estimated_size);
1614 if (items.size() > 1) {
1616 std::swap(items.front(), items.back());
1620bool APIConnection::schedule_batch_() {
1621 if (!this->flags_.batch_scheduled) {
1622 this->flags_.batch_scheduled =
true;
1628void APIConnection::process_batch_() {
1630 static_assert(std::is_trivially_destructible<PacketInfo>::value,
1631 "PacketInfo must remain trivially destructible with this placement-new approach");
1633 if (this->deferred_batch_.empty()) {
1634 this->flags_.batch_scheduled =
false;
1639 if (!this->try_to_clear_buffer(
true)) {
1645 auto &shared_buf = this->parent_->get_shared_buffer_ref();
1646 size_t num_items = this->deferred_batch_.size();
1649 if (num_items == 1) {
1650 const auto &item = this->deferred_batch_[0];
1654 item.creator(item.entity,
this, std::numeric_limits<uint16_t>::max(),
true, item.message_type);
1657#ifdef HAS_PROTO_MESSAGE_DUMP
1660 this->log_batch_item_(item);
1662 this->clear_batch_();
1665 ESP_LOGW(TAG,
"Message too large to send: type=%u", item.message_type);
1666 this->clear_batch_();
1671 size_t packets_to_process = std::min(num_items, MAX_PACKETS_PER_BATCH);
1676 size_t packet_count = 0;
1679 const uint8_t header_padding = this->helper_->frame_header_padding();
1680 const uint8_t footer_size = this->helper_->frame_footer_size();
1686 uint32_t total_estimated_size = num_items * (header_padding + footer_size);
1687 for (
size_t i = 0; i < this->deferred_batch_.size(); i++) {
1688 const auto &item = this->deferred_batch_[i];
1689 total_estimated_size += item.estimated_size;
1694 shared_buf.reserve(total_estimated_size);
1695 this->flags_.batch_first_message =
true;
1697 size_t items_processed = 0;
1698 uint16_t remaining_size = std::numeric_limits<uint16_t>::max();
1704 uint32_t current_offset = 0;
1707 for (
size_t i = 0; i < packets_to_process; i++) {
1708 const auto &item = this->deferred_batch_[i];
1711 uint16_t
payload_size = item.creator(item.entity,
this, remaining_size,
false, item.message_type);
1720 uint16_t proto_payload_size =
payload_size - header_padding - footer_size;
1725 new (&packet_info[packet_count++])
PacketInfo(item.message_type, current_offset, proto_payload_size);
1730 if (items_processed == 1) {
1731 remaining_size = MAX_BATCH_PACKET_SIZE;
1736 current_offset = shared_buf.size() + footer_size;
1739 if (items_processed == 0) {
1740 this->deferred_batch_.clear();
1745 if (footer_size > 0) {
1746 shared_buf.resize(shared_buf.size() + footer_size);
1751 std::span<const PacketInfo>(packet_info, packet_count));
1752 if (err != APIError::OK && err != APIError::WOULD_BLOCK) {
1754 this->log_warning_(LOG_STR(
"Batch write failed"), err);
1757#ifdef HAS_PROTO_MESSAGE_DUMP
1760 for (
size_t i = 0; i < items_processed; i++) {
1761 const auto &item = this->deferred_batch_[i];
1762 this->log_batch_item_(item);
1767 if (items_processed < this->deferred_batch_.size()) {
1769 this->deferred_batch_.remove_front(items_processed);
1771 this->schedule_batch_();
1774 this->clear_batch_();
1779 bool is_single, uint8_t message_type)
const {
1782 if (message_type == EventResponse::MESSAGE_TYPE) {
1784 return APIConnection::try_send_event_response(e, *data_.string_ptr, conn, remaining_size, is_single);
1789 return data_.function_ptr(entity, conn, remaining_size, is_single);
1795 return encode_message_to_buffer(resp, ListEntitiesDoneResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
1801 return encode_message_to_buffer(req, DisconnectRequest::MESSAGE_TYPE, conn, remaining_size, is_single);
1807 return encode_message_to_buffer(req, PingRequest::MESSAGE_TYPE, conn, remaining_size, is_single);
1810#ifdef USE_API_HOMEASSISTANT_STATES
1811void APIConnection::process_state_subscriptions_() {
1812 const auto &subs = this->parent_->get_state_subs();
1813 if (this->state_subs_at_ >=
static_cast<int>(subs.size())) {
1814 this->state_subs_at_ = -1;
1818 const auto &it = subs[this->state_subs_at_];
1825 resp.
once = it.once;
1826 if (this->send_message(resp, SubscribeHomeAssistantStateResponse::MESSAGE_TYPE)) {
1827 this->state_subs_at_++;
1832void APIConnection::log_warning_(
const LogString *message,
APIError err) {
1833 ESP_LOGW(TAG,
"%s: %s %s errno=%d", this->get_client_combined_info().c_str(), LOG_STR_ARG(message),
1837void APIConnection::log_socket_operation_failed_(
APIError err) {
1838 this->log_warning_(LOG_STR(
"Socket operation failed"), err);
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)
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
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)
float visual_max_humidity
const std::set< std::string > * supported_custom_presets
bool supports_current_temperature
bool supports_current_humidity
bool supports_target_humidity
float visual_min_humidity
float visual_max_temperature
const std::set< climate::ClimateSwingMode > * supported_swing_modes
float visual_target_temperature_step
bool supports_two_point_target_temperature
const std::set< std::string > * supported_custom_fan_modes
float visual_min_temperature
const std::set< climate::ClimateFanMode > * supported_fan_modes
float visual_current_temperature_step
const std::set< climate::ClimatePreset > * supported_presets
const std::set< climate::ClimateMode > * supported_modes
void set_device_class(const StringRef &ref)
std::vector< std::string > event_types
void set_device_class(const StringRef &ref)
const std::set< std::string > * supported_preset_modes
int32_t supported_speed_count
bool supports_oscillation
const std::set< light::ColorMode > * supported_color_modes
std::vector< std::string > effects
void set_unit_of_measurement(const StringRef &ref)
void set_device_class(const StringRef &ref)
const std::vector< std::string > * 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< 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
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.
std::string get_timezone()
Get the time zone currently in use.
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)
const LogString * api_error_to_logstr(APIError err)
std::array< uint8_t, 32 > psk_t
BluetoothProxy * global_bluetooth_proxy
ClimatePreset
Enum for all preset modes.
ClimateSwingMode
Enum for all modes a climate swing can be in.
ClimateMode
Enum for all modes a climate device can be in.
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
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