6#ifdef USE_API_PLAINTEXT
24#ifdef USE_HOMEASSISTANT_TIME
27#ifdef USE_BLUETOOTH_PROXY
30#ifdef USE_VOICE_ASSISTANT
43static constexpr uint8_t MAX_MESSAGES_PER_LOOP = 5;
44static constexpr uint8_t MAX_PING_RETRIES = 60;
45static constexpr uint16_t PING_RETRY_INTERVAL = 1000;
46static constexpr uint32_t KEEPALIVE_DISCONNECT_TIMEOUT = (KEEPALIVE_TIMEOUT_MS * 5) / 2;
50static const char *
const TAG =
"api.connection";
52static const int CAMERA_STOP_STREAM = 5000;
58#define ENTITY_COMMAND_MAKE_CALL(entity_type, entity_var, getter_name) \
59 entity_type *entity_var = App.get_##getter_name##_by_key(msg.key, msg.device_id); \
60 if ((entity_var) == nullptr) \
62 auto call = (entity_var)->make_call();
66#define ENTITY_COMMAND_GET(entity_type, entity_var, getter_name) \
67 entity_type *entity_var = App.get_##getter_name##_by_key(msg.key, msg.device_id); \
68 if ((entity_var) == nullptr) \
73#define ENTITY_COMMAND_MAKE_CALL(entity_type, entity_var, getter_name) \
74 entity_type *entity_var = App.get_##getter_name##_by_key(msg.key); \
75 if ((entity_var) == nullptr) \
77 auto call = (entity_var)->make_call();
81#define ENTITY_COMMAND_GET(entity_type, entity_var, getter_name) \
82 entity_type *entity_var = App.get_##getter_name##_by_key(msg.key); \
83 if ((entity_var) == nullptr) \
88 : parent_(parent), initial_state_iterator_(this), list_entities_iterator_(this) {
89#if defined(USE_API_PLAINTEXT) && defined(USE_API_NOISE)
91 if (noise_ctx->has_psk()) {
93 std::unique_ptr<APIFrameHelper>{new APINoiseFrameHelper(std::move(sock), noise_ctx, &this->client_info_)};
95 this->helper_ = std::unique_ptr<APIFrameHelper>{
new APIPlaintextFrameHelper(std::move(sock), &this->client_info_)};
97#elif defined(USE_API_PLAINTEXT)
98 this->helper_ = std::unique_ptr<APIFrameHelper>{
new APIPlaintextFrameHelper(std::move(sock), &this->client_info_)};
99#elif defined(USE_API_NOISE)
100 this->helper_ = std::unique_ptr<APIFrameHelper>{
101 new APINoiseFrameHelper(std::move(sock), parent->get_noise_ctx(), &this->client_info_)};
103#error "No frame helper defined"
112uint32_t APIConnection::get_batch_delay_ms_()
const {
return this->parent_->get_batch_delay(); }
114void APIConnection::start() {
117 APIError err = this->helper_->init();
118 if (err != APIError::OK) {
120 this->log_warning_(LOG_STR(
"Helper init failed"), err);
123 this->client_info_.peername = helper_->getpeername();
124 this->client_info_.name = this->client_info_.peername;
127APIConnection::~APIConnection() {
128#ifdef USE_BLUETOOTH_PROXY
133#ifdef USE_VOICE_ASSISTANT
140void APIConnection::loop() {
141 if (this->flags_.next_close) {
143 this->helper_->close();
144 this->flags_.remove =
true;
148 APIError err = this->helper_->loop();
149 if (err != APIError::OK) {
151 this->log_socket_operation_failed_(err);
157 if (this->helper_->is_socket_ready()) {
159 for (uint8_t message_count = 0; message_count < MAX_MESSAGES_PER_LOOP; message_count++) {
161 err = this->helper_->read_packet(&buffer);
162 if (err == APIError::WOULD_BLOCK) {
165 }
else if (err != APIError::OK) {
167 this->log_warning_(LOG_STR(
"Reading failed"), err);
170 this->last_traffic_ = now;
175 this->read_message(0, buffer.
type,
nullptr);
177 if (this->flags_.remove)
184 if (this->flags_.batch_scheduled && now - this->deferred_batch_.batch_start_time >= this->get_batch_delay_ms_()) {
185 this->process_batch_();
188 if (!this->list_entities_iterator_.completed()) {
189 this->process_iterator_batch_(this->list_entities_iterator_);
190 }
else if (!this->initial_state_iterator_.completed()) {
191 this->process_iterator_batch_(this->initial_state_iterator_);
194 if (this->initial_state_iterator_.completed()) {
196 if (!this->deferred_batch_.empty()) {
197 this->process_batch_();
200 this->flags_.should_try_send_immediately =
true;
204 if (this->flags_.sent_ping) {
206 if (now - this->last_traffic_ > KEEPALIVE_DISCONNECT_TIMEOUT) {
208 ESP_LOGW(TAG,
"%s is unresponsive; disconnecting", this->get_client_combined_info().c_str());
210 }
else if (now - this->last_traffic_ > KEEPALIVE_TIMEOUT_MS && !this->flags_.remove) {
212 ESP_LOGVV(TAG,
"Sending keepalive PING");
214 this->flags_.sent_ping = this->send_message(req, PingRequest::MESSAGE_TYPE);
215 if (!this->flags_.sent_ping) {
218 ESP_LOGW(TAG,
"Buffer full, ping queued");
219 this->schedule_message_front_(
nullptr, &APIConnection::try_send_ping_request, PingRequest::MESSAGE_TYPE,
220 PingRequest::ESTIMATED_SIZE);
221 this->flags_.sent_ping =
true;
226 if (this->image_reader_ && this->image_reader_->available() && this->helper_->can_write_without_blocking()) {
227 uint32_t to_send = std::min((
size_t) MAX_BATCH_PACKET_SIZE, this->image_reader_->available());
228 bool done = this->image_reader_->available() == to_send;
232 msg.
set_data(this->image_reader_->peek_data_buffer(), to_send);
238 if (this->send_message_(msg, CameraImageResponse::MESSAGE_TYPE)) {
239 this->image_reader_->consume_data(to_send);
241 this->image_reader_->return_image();
247#ifdef USE_API_HOMEASSISTANT_STATES
248 if (state_subs_at_ >= 0) {
249 this->process_state_subscriptions_();
258 ESP_LOGD(TAG,
"%s disconnected", this->get_client_combined_info().c_str());
259 this->flags_.next_close =
true;
261 return this->send_message(resp, DisconnectResponse::MESSAGE_TYPE);
264 this->helper_->close();
265 this->flags_.remove =
true;
271 uint32_t remaining_size,
bool is_single) {
272#ifdef HAS_PROTO_MESSAGE_DUMP
283 uint32_t calculated_size = size_calc.
get_size();
286 const uint8_t header_padding = conn->
helper_->frame_header_padding();
287 const uint8_t footer_size = conn->
helper_->frame_footer_size();
290 size_t total_calculated_size = calculated_size + header_padding + footer_size;
293 if (total_calculated_size > remaining_size) {
309 size_t current_size = shared_buf.size();
310 shared_buf.reserve(current_size + total_calculated_size);
311 shared_buf.resize(current_size + footer_size + header_padding);
315 size_t size_before_encode = shared_buf.size();
316 msg.
encode({&shared_buf});
319 size_t actual_payload_size = shared_buf.size() - size_before_encode;
322 size_t actual_total_size = header_padding + actual_payload_size + footer_size;
325 assert(calculated_size == actual_payload_size);
326 return static_cast<uint16_t
>(actual_total_size);
329#ifdef USE_BINARY_SENSOR
331 return this->send_message_smart_(binary_sensor, &APIConnection::try_send_binary_sensor_state,
332 BinarySensorStateResponse::MESSAGE_TYPE, BinarySensorStateResponse::ESTIMATED_SIZE);
339 resp.
state = binary_sensor->state;
341 return fill_and_encode_entity_state(binary_sensor, resp, BinarySensorStateResponse::MESSAGE_TYPE, conn,
342 remaining_size, is_single);
351 return fill_and_encode_entity_info(binary_sensor, msg, ListEntitiesBinarySensorResponse::MESSAGE_TYPE, conn,
352 remaining_size, is_single);
358 return this->send_message_smart_(cover, &APIConnection::try_send_cover_state, CoverStateResponse::MESSAGE_TYPE,
359 CoverStateResponse::ESTIMATED_SIZE);
365 auto traits = cover->get_traits();
367 if (traits.get_supports_tilt())
368 msg.
tilt = cover->tilt;
370 return fill_and_encode_entity_state(cover, msg, CoverStateResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
376 auto traits = cover->get_traits();
382 return fill_and_encode_entity_info(cover, msg, ListEntitiesCoverResponse::MESSAGE_TYPE, conn, remaining_size,
390 call.set_tilt(msg.
tilt);
392 call.set_command_stop();
399 return this->send_message_smart_(fan, &APIConnection::try_send_fan_state, FanStateResponse::MESSAGE_TYPE,
400 FanStateResponse::ESTIMATED_SIZE);
404 auto *fan =
static_cast<fan::Fan *
>(entity);
406 auto traits = fan->get_traits();
407 msg.
state = fan->state;
408 if (traits.supports_oscillation())
410 if (traits.supports_speed()) {
413 if (traits.supports_direction())
415 if (traits.supports_preset_modes())
417 return fill_and_encode_entity_state(fan, msg, FanStateResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
421 auto *fan =
static_cast<fan::Fan *
>(entity);
423 auto traits = fan->get_traits();
429 return fill_and_encode_entity_info(fan, msg, ListEntitiesFanResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
432 ENTITY_COMMAND_MAKE_CALL(
fan::Fan, fan, fan)
434 call.set_state(msg.
state);
451 return this->send_message_smart_(light, &APIConnection::try_send_light_state, LightStateResponse::MESSAGE_TYPE,
452 LightStateResponse::ESTIMATED_SIZE);
458 auto traits = light->get_traits();
459 auto values = light->remote_values;
460 auto color_mode = values.get_color_mode();
461 resp.
state = values.is_on();
465 resp.
red = values.get_red();
466 resp.
green = values.get_green();
467 resp.
blue = values.get_blue();
468 resp.
white = values.get_white();
472 if (light->supports_effects()) {
473 resp.
set_effect(light->get_effect_name_ref());
475 return fill_and_encode_entity_state(light, resp, LightStateResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
481 auto traits = light->get_traits();
488 if (light->supports_effects()) {
489 msg.
effects.emplace_back(
"None");
490 for (
auto *effect : light->get_effects()) {
491 msg.
effects.push_back(effect->get_name());
494 return fill_and_encode_entity_info(light, msg, ListEntitiesLightResponse::MESSAGE_TYPE, conn, remaining_size,
500 call.set_state(msg.
state);
508 call.set_red(msg.
red);
509 call.set_green(msg.
green);
510 call.set_blue(msg.
blue);
513 call.set_white(msg.
white);
525 call.set_effect(msg.
effect);
532 return this->send_message_smart_(sensor, &APIConnection::try_send_sensor_state, SensorStateResponse::MESSAGE_TYPE,
533 SensorStateResponse::ESTIMATED_SIZE);
540 resp.
state = sensor->state;
542 return fill_and_encode_entity_state(sensor, resp, SensorStateResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
554 return fill_and_encode_entity_info(sensor, msg, ListEntitiesSensorResponse::MESSAGE_TYPE, conn, remaining_size,
561 return this->send_message_smart_(a_switch, &APIConnection::try_send_switch_state, SwitchStateResponse::MESSAGE_TYPE,
562 SwitchStateResponse::ESTIMATED_SIZE);
569 resp.
state = a_switch->state;
570 return fill_and_encode_entity_state(a_switch, resp, SwitchStateResponse::MESSAGE_TYPE, conn, remaining_size,
580 return fill_and_encode_entity_info(a_switch, msg, ListEntitiesSwitchResponse::MESSAGE_TYPE, conn, remaining_size,
589 a_switch->turn_off();
594#ifdef USE_TEXT_SENSOR
596 return this->send_message_smart_(text_sensor, &APIConnection::try_send_text_sensor_state,
597 TextSensorStateResponse::MESSAGE_TYPE, TextSensorStateResponse::ESTIMATED_SIZE);
606 return fill_and_encode_entity_state(text_sensor, resp, TextSensorStateResponse::MESSAGE_TYPE, conn, remaining_size,
614 return fill_and_encode_entity_info(text_sensor, msg, ListEntitiesTextSensorResponse::MESSAGE_TYPE, conn,
615 remaining_size, is_single);
621 return this->send_message_smart_(climate, &APIConnection::try_send_climate_state, ClimateStateResponse::MESSAGE_TYPE,
622 ClimateStateResponse::ESTIMATED_SIZE);
628 auto traits = climate->get_traits();
631 if (traits.get_supports_current_temperature())
633 if (traits.get_supports_two_point_target_temperature()) {
639 if (traits.get_supports_fan_modes() && climate->fan_mode.has_value())
641 if (!traits.get_supported_custom_fan_modes().empty() && climate->custom_fan_mode.has_value()) {
644 if (traits.get_supports_presets() && climate->preset.has_value()) {
647 if (!traits.get_supported_custom_presets().empty() && climate->custom_preset.has_value()) {
650 if (traits.get_supports_swing_modes())
652 if (traits.get_supports_current_humidity())
654 if (traits.get_supports_target_humidity())
656 return fill_and_encode_entity_state(climate, resp, ClimateStateResponse::MESSAGE_TYPE, conn, remaining_size,
663 auto traits = climate->get_traits();
681 return fill_and_encode_entity_info(climate, msg, ListEntitiesClimateResponse::MESSAGE_TYPE, conn, remaining_size,
712 return this->send_message_smart_(number, &APIConnection::try_send_number_state, NumberStateResponse::MESSAGE_TYPE,
713 NumberStateResponse::ESTIMATED_SIZE);
720 resp.
state = number->state;
722 return fill_and_encode_entity_state(number, resp, NumberStateResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
732 msg.
min_value = number->traits.get_min_value();
733 msg.
max_value = number->traits.get_max_value();
734 msg.
step = number->traits.get_step();
735 return fill_and_encode_entity_info(number, msg, ListEntitiesNumberResponse::MESSAGE_TYPE, conn, remaining_size,
740 call.set_value(msg.
state);
745#ifdef USE_DATETIME_DATE
747 return this->send_message_smart_(date, &APIConnection::try_send_date_state, DateStateResponse::MESSAGE_TYPE,
748 DateStateResponse::ESTIMATED_SIZE);
755 resp.
year = date->year;
756 resp.
month = date->month;
757 resp.
day = date->day;
758 return fill_and_encode_entity_state(date, resp, DateStateResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
764 return fill_and_encode_entity_info(date, msg, ListEntitiesDateResponse::MESSAGE_TYPE, conn, remaining_size,
774#ifdef USE_DATETIME_TIME
776 return this->send_message_smart_(time, &APIConnection::try_send_time_state, TimeStateResponse::MESSAGE_TYPE,
777 TimeStateResponse::ESTIMATED_SIZE);
784 resp.
hour = time->hour;
785 resp.
minute = time->minute;
786 resp.
second = time->second;
787 return fill_and_encode_entity_state(time, resp, TimeStateResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
793 return fill_and_encode_entity_info(time, msg, ListEntitiesTimeResponse::MESSAGE_TYPE, conn, remaining_size,
803#ifdef USE_DATETIME_DATETIME
805 return this->send_message_smart_(datetime, &APIConnection::try_send_datetime_state,
806 DateTimeStateResponse::MESSAGE_TYPE, DateTimeStateResponse::ESTIMATED_SIZE);
813 if (datetime->has_state()) {
817 return fill_and_encode_entity_state(datetime, resp, DateTimeStateResponse::MESSAGE_TYPE, conn, remaining_size,
824 return fill_and_encode_entity_info(datetime, msg, ListEntitiesDateTimeResponse::MESSAGE_TYPE, conn, remaining_size,
836 return this->send_message_smart_(text, &APIConnection::try_send_text_state, TextStateResponse::MESSAGE_TYPE,
837 TextStateResponse::ESTIMATED_SIZE);
842 auto *text =
static_cast<text::Text *
>(entity);
846 return fill_and_encode_entity_state(text, resp, TextStateResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
851 auto *text =
static_cast<text::Text *
>(entity);
854 msg.
min_length = text->traits.get_min_length();
855 msg.
max_length = text->traits.get_max_length();
857 return fill_and_encode_entity_info(text, msg, ListEntitiesTextResponse::MESSAGE_TYPE, conn, remaining_size,
861 ENTITY_COMMAND_MAKE_CALL(
text::Text, text, text)
862 call.set_value(msg.
state);
869 return this->send_message_smart_(select, &APIConnection::try_send_select_state, SelectStateResponse::MESSAGE_TYPE,
870 SelectStateResponse::ESTIMATED_SIZE);
879 return fill_and_encode_entity_state(select, resp, SelectStateResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
886 msg.
options = &select->traits.get_options();
887 return fill_and_encode_entity_info(select, msg, ListEntitiesSelectResponse::MESSAGE_TYPE, conn, remaining_size,
892 call.set_option(msg.
state);
903 return fill_and_encode_entity_info(button, msg, ListEntitiesButtonResponse::MESSAGE_TYPE, conn, remaining_size,
914 return this->send_message_smart_(a_lock, &APIConnection::try_send_lock_state, LockStateResponse::MESSAGE_TYPE,
915 LockStateResponse::ESTIMATED_SIZE);
920 auto *a_lock =
static_cast<lock::Lock *
>(entity);
923 return fill_and_encode_entity_state(a_lock, resp, LockStateResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
928 auto *a_lock =
static_cast<lock::Lock *
>(entity);
933 return fill_and_encode_entity_info(a_lock, msg, ListEntitiesLockResponse::MESSAGE_TYPE, conn, remaining_size,
940 case enums::LOCK_UNLOCK:
943 case enums::LOCK_LOCK:
946 case enums::LOCK_OPEN:
955 return this->send_message_smart_(valve, &APIConnection::try_send_valve_state, ValveStateResponse::MESSAGE_TYPE,
956 ValveStateResponse::ESTIMATED_SIZE);
964 return fill_and_encode_entity_state(valve, resp, ValveStateResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
970 auto traits = valve->get_traits();
975 return fill_and_encode_entity_info(valve, msg, ListEntitiesValveResponse::MESSAGE_TYPE, conn, remaining_size,
983 call.set_command_stop();
988#ifdef USE_MEDIA_PLAYER
990 return this->send_message_smart_(media_player, &APIConnection::try_send_media_player_state,
991 MediaPlayerStateResponse::MESSAGE_TYPE, MediaPlayerStateResponse::ESTIMATED_SIZE);
999 : media_player->state;
1001 resp.
volume = media_player->volume;
1002 resp.
muted = media_player->is_muted();
1003 return fill_and_encode_entity_state(media_player, resp, MediaPlayerStateResponse::MESSAGE_TYPE, conn, remaining_size,
1010 auto traits = media_player->get_traits();
1013 for (
auto &supported_format : traits.get_supported_formats()) {
1016 media_format.set_format(
StringRef(supported_format.format));
1017 media_format.sample_rate = supported_format.sample_rate;
1018 media_format.num_channels = supported_format.num_channels;
1020 media_format.sample_bytes = supported_format.sample_bytes;
1022 return fill_and_encode_entity_info(media_player, msg, ListEntitiesMediaPlayerResponse::MESSAGE_TYPE, conn,
1023 remaining_size, is_single);
1031 call.set_volume(msg.
volume);
1044void APIConnection::set_camera_state(std::shared_ptr<camera::CameraImage> image) {
1045 if (!this->flags_.state_subscription)
1047 if (!this->image_reader_)
1049 if (this->image_reader_->available())
1052 this->image_reader_->set_image(std::move(image));
1058 return fill_and_encode_entity_info(camera, msg, ListEntitiesCameraResponse::MESSAGE_TYPE, conn, remaining_size,
1070 App.scheduler.set_timeout(this->parent_,
"api_camera_stop_stream", CAMERA_STOP_STREAM,
1076#ifdef USE_HOMEASSISTANT_TIME
1080#ifdef USE_TIME_TIMEZONE
1095#ifdef USE_BLUETOOTH_PROXY
1125bool APIConnection::send_subscribe_bluetooth_connections_free_response(
1133 msg.
mode == enums::BluetoothScannerMode::BLUETOOTH_SCANNER_MODE_ACTIVE);
1137#ifdef USE_VOICE_ASSISTANT
1138bool APIConnection::check_voice_assistant_api_connection_()
const {
1149 if (!this->check_voice_assistant_api_connection_()) {
1157 if (msg.
port == 0) {
1163 this->helper_->getpeername((
struct sockaddr *) &storage, &
len);
1168 if (this->check_voice_assistant_api_connection_()) {
1173 if (this->check_voice_assistant_api_connection_()) {
1178 if (this->check_voice_assistant_api_connection_()) {
1184 if (this->check_voice_assistant_api_connection_()) {
1191 if (!this->check_voice_assistant_api_connection_()) {
1192 return this->send_message(resp, VoiceAssistantConfigurationResponse::MESSAGE_TYPE);
1196 for (
auto &wake_word : config.available_wake_words) {
1199 resp_wake_word.set_id(
StringRef(wake_word.id));
1200 resp_wake_word.set_wake_word(
StringRef(wake_word.wake_word));
1201 for (
const auto &lang : wake_word.trained_languages) {
1202 resp_wake_word.trained_languages.push_back(lang);
1208 if (wake_word.model_type !=
"micro") {
1215 resp_wake_word.set_id(
StringRef(wake_word.id));
1216 resp_wake_word.set_wake_word(
StringRef(wake_word.wake_word));
1217 for (
const auto &lang : wake_word.trained_languages) {
1218 resp_wake_word.trained_languages.push_back(lang);
1224 return this->send_message(resp, VoiceAssistantConfigurationResponse::MESSAGE_TYPE);
1228 if (this->check_voice_assistant_api_connection_()) {
1234#ifdef USE_ZWAVE_PROXY
1244#ifdef USE_ALARM_CONTROL_PANEL
1246 return this->send_message_smart_(a_alarm_control_panel, &APIConnection::try_send_alarm_control_panel_state,
1247 AlarmControlPanelStateResponse::MESSAGE_TYPE,
1248 AlarmControlPanelStateResponse::ESTIMATED_SIZE);
1251 uint32_t remaining_size,
bool is_single) {
1255 return fill_and_encode_entity_state(a_alarm_control_panel, resp, AlarmControlPanelStateResponse::MESSAGE_TYPE, conn,
1256 remaining_size, is_single);
1259 uint32_t remaining_size,
bool is_single) {
1263 msg.
requires_code = a_alarm_control_panel->get_requires_code();
1265 return fill_and_encode_entity_info(a_alarm_control_panel, msg, ListEntitiesAlarmControlPanelResponse::MESSAGE_TYPE,
1266 conn, remaining_size, is_single);
1271 case enums::ALARM_CONTROL_PANEL_DISARM:
1274 case enums::ALARM_CONTROL_PANEL_ARM_AWAY:
1277 case enums::ALARM_CONTROL_PANEL_ARM_HOME:
1280 case enums::ALARM_CONTROL_PANEL_ARM_NIGHT:
1283 case enums::ALARM_CONTROL_PANEL_ARM_VACATION:
1284 call.arm_vacation();
1286 case enums::ALARM_CONTROL_PANEL_ARM_CUSTOM_BYPASS:
1287 call.arm_custom_bypass();
1289 case enums::ALARM_CONTROL_PANEL_TRIGGER:
1293 call.set_code(msg.
code);
1299void APIConnection::send_event(
event::Event *event,
const std::string &event_type) {
1300 this->schedule_message_(event,
MessageCreator(event_type), EventResponse::MESSAGE_TYPE,
1301 EventResponse::ESTIMATED_SIZE);
1304 uint32_t remaining_size,
bool is_single) {
1307 return fill_and_encode_entity_state(event, resp, EventResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
1315 for (
const auto &event_type : event->get_event_types())
1317 return fill_and_encode_entity_info(event, msg, ListEntitiesEventResponse::MESSAGE_TYPE, conn, remaining_size,
1324 return this->send_message_smart_(update, &APIConnection::try_send_update_state, UpdateStateResponse::MESSAGE_TYPE,
1325 UpdateStateResponse::ESTIMATED_SIZE);
1332 if (update->has_state()) {
1334 if (update->update_info.has_progress) {
1336 resp.
progress = update->update_info.progress;
1344 return fill_and_encode_entity_state(update, resp, UpdateStateResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
1351 return fill_and_encode_entity_info(update, msg, ListEntitiesUpdateResponse::MESSAGE_TYPE, conn, remaining_size,
1358 case enums::UPDATE_COMMAND_UPDATE:
1361 case enums::UPDATE_COMMAND_CHECK:
1364 case enums::UPDATE_COMMAND_NONE:
1365 ESP_LOGE(TAG,
"UPDATE_COMMAND_NONE not handled; confirm command is correct");
1368 ESP_LOGW(TAG,
"Unknown update command: %" PRIu32, msg.
command);
1374bool APIConnection::try_send_log_message(
int level,
const char *tag,
const char *line,
size_t message_len) {
1377 msg.
set_message(
reinterpret_cast<const uint8_t *
>(line), message_len);
1378 return this->send_message_(msg, SubscribeLogsResponse::MESSAGE_TYPE);
1381void APIConnection::complete_authentication_() {
1383 if (this->flags_.connection_state ==
static_cast<uint8_t
>(ConnectionState::AUTHENTICATED)) {
1387 this->flags_.connection_state =
static_cast<uint8_t
>(ConnectionState::AUTHENTICATED);
1388 ESP_LOGD(TAG,
"%s connected", this->get_client_combined_info().c_str());
1389#ifdef USE_API_CLIENT_CONNECTED_TRIGGER
1390 this->parent_->get_client_connected_trigger()->trigger(this->client_info_.name, this->client_info_.peername);
1392#ifdef USE_HOMEASSISTANT_TIME
1394 this->send_time_request();
1401 this->client_info_.peername = this->helper_->getpeername();
1404 ESP_LOGV(TAG,
"Hello from client: '%s' | %s | API Version %" PRIu32
".%" PRIu32, this->client_info_.name.c_str(),
1405 this->client_info_.peername.c_str(), this->client_api_version_major_, this->client_api_version_minor_);
1414#ifdef USE_API_PASSWORD
1416 this->flags_.connection_state =
static_cast<uint8_t
>(ConnectionState::CONNECTED);
1419 this->complete_authentication_();
1422 return this->send_message(resp, HelloResponse::MESSAGE_TYPE);
1424#ifdef USE_API_PASSWORD
1430 this->complete_authentication_();
1432 return this->send_message(resp, AuthenticationResponse::MESSAGE_TYPE);
1438 return this->send_message(resp, PingResponse::MESSAGE_TYPE);
1443#ifdef USE_API_PASSWORD
1453 resp.set_mac_address(
StringRef(mac_address));
1455 resp.set_esphome_version(ESPHOME_VERSION_REF);
1460#if defined(USE_ESP8266) || defined(USE_ESP32)
1462#elif defined(USE_RP2040)
1464#elif defined(USE_BK72XX)
1466#elif defined(USE_LN882X)
1468#elif defined(USE_RTL87XX)
1470#elif defined(USE_HOST)
1473 resp.set_manufacturer(MANUFACTURER);
1476 resp.set_model(MODEL);
1477#ifdef USE_DEEP_SLEEP
1480#ifdef ESPHOME_PROJECT_NAME
1483 resp.set_project_name(PROJECT_NAME);
1484 resp.set_project_version(PROJECT_VERSION);
1487 resp.webserver_port = USE_WEBSERVER_PORT;
1489#ifdef USE_BLUETOOTH_PROXY
1493 resp.set_bluetooth_mac_address(
StringRef(bluetooth_mac));
1495#ifdef USE_VOICE_ASSISTANT
1498#ifdef USE_ZWAVE_PROXY
1503 resp.api_encryption_supported =
true;
1506 size_t device_index = 0;
1508 if (device_index >= ESPHOME_DEVICE_COUNT)
1510 auto &device_info = resp.devices[device_index++];
1511 device_info.device_id = device->get_device_id();
1512 device_info.set_name(
StringRef(device->get_name()));
1513 device_info.area_id = device->get_area_id();
1517 size_t area_index = 0;
1519 if (area_index >= ESPHOME_AREA_COUNT)
1521 auto &area_info = resp.areas[area_index++];
1522 area_info.area_id = area->get_area_id();
1523 area_info.set_name(
StringRef(area->get_name()));
1527 return this->send_message(resp, DeviceInfoResponse::MESSAGE_TYPE);
1530#ifdef USE_API_HOMEASSISTANT_STATES
1532 for (
auto &it : this->parent_->get_state_subs()) {
1534 it.callback(msg.
state);
1539#ifdef USE_API_SERVICES
1542 for (
auto *service : this->parent_->get_user_services()) {
1543 if (service->execute_service(msg)) {
1548 ESP_LOGV(TAG,
"Could not find service");
1559 ESP_LOGW(TAG,
"Invalid encryption key length");
1560 }
else if (!this->parent_->save_noise_psk(psk,
true)) {
1561 ESP_LOGW(TAG,
"Failed to save encryption key");
1566 return this->send_message(resp, NoiseEncryptionSetKeyResponse::MESSAGE_TYPE);
1569#ifdef USE_API_HOMEASSISTANT_STATES
1574bool APIConnection::try_to_clear_buffer(
bool log_out_of_space) {
1575 if (this->flags_.remove)
1577 if (this->helper_->can_write_without_blocking())
1580 APIError err = this->helper_->loop();
1581 if (err != APIError::OK) {
1583 this->log_socket_operation_failed_(err);
1586 if (this->helper_->can_write_without_blocking())
1588 if (log_out_of_space) {
1589 ESP_LOGV(TAG,
"Cannot send message because of TCP buffer space");
1594 if (!this->try_to_clear_buffer(message_type != SubscribeLogsResponse::MESSAGE_TYPE)) {
1598 APIError err = this->helper_->write_protobuf_packet(message_type, buffer);
1599 if (err == APIError::WOULD_BLOCK)
1601 if (err != APIError::OK) {
1603 this->log_warning_(LOG_STR(
"Packet write failed"), err);
1609#ifdef USE_API_PASSWORD
1610void APIConnection::on_unauthenticated_access() {
1611 this->on_fatal_error();
1612 ESP_LOGD(TAG,
"%s access without authentication", this->get_client_combined_info().c_str());
1615void APIConnection::on_no_setup_connection() {
1616 this->on_fatal_error();
1617 ESP_LOGD(TAG,
"%s access without full connection", this->get_client_combined_info().c_str());
1619void APIConnection::on_fatal_error() {
1620 this->helper_->close();
1621 this->flags_.remove =
true;
1625 uint8_t estimated_size) {
1629 for (
auto &item : items) {
1630 if (item.entity == entity && item.message_type == message_type) {
1632 item.creator.cleanup(message_type);
1634 item.creator = std::move(creator);
1640 items.emplace_back(entity, std::move(creator), message_type, estimated_size);
1644 uint8_t estimated_size) {
1649 items.emplace_back(entity, std::move(creator), message_type, estimated_size);
1650 if (items.size() > 1) {
1652 std::swap(items.front(), items.back());
1656bool APIConnection::schedule_batch_() {
1657 if (!this->flags_.batch_scheduled) {
1658 this->flags_.batch_scheduled =
true;
1664void APIConnection::process_batch_() {
1666 static_assert(std::is_trivially_destructible<PacketInfo>::value,
1667 "PacketInfo must remain trivially destructible with this placement-new approach");
1669 if (this->deferred_batch_.empty()) {
1670 this->flags_.batch_scheduled =
false;
1675 if (!this->try_to_clear_buffer(
true)) {
1681 auto &shared_buf = this->parent_->get_shared_buffer_ref();
1682 size_t num_items = this->deferred_batch_.size();
1685 if (num_items == 1) {
1686 const auto &item = this->deferred_batch_[0];
1690 item.creator(item.entity,
this, std::numeric_limits<uint16_t>::max(),
true, item.message_type);
1693#ifdef HAS_PROTO_MESSAGE_DUMP
1696 this->log_batch_item_(item);
1698 this->clear_batch_();
1701 ESP_LOGW(TAG,
"Message too large to send: type=%u", item.message_type);
1702 this->clear_batch_();
1707 size_t packets_to_process = std::min(num_items, MAX_PACKETS_PER_BATCH);
1712 size_t packet_count = 0;
1715 const uint8_t header_padding = this->helper_->frame_header_padding();
1716 const uint8_t footer_size = this->helper_->frame_footer_size();
1722 uint32_t total_estimated_size = num_items * (header_padding + footer_size);
1723 for (
size_t i = 0; i < this->deferred_batch_.size(); i++) {
1724 const auto &item = this->deferred_batch_[i];
1725 total_estimated_size += item.estimated_size;
1730 shared_buf.reserve(total_estimated_size);
1731 this->flags_.batch_first_message =
true;
1733 size_t items_processed = 0;
1734 uint16_t remaining_size = std::numeric_limits<uint16_t>::max();
1740 uint32_t current_offset = 0;
1743 for (
size_t i = 0; i < packets_to_process; i++) {
1744 const auto &item = this->deferred_batch_[i];
1747 uint16_t
payload_size = item.creator(item.entity,
this, remaining_size,
false, item.message_type);
1756 uint16_t proto_payload_size =
payload_size - header_padding - footer_size;
1761 new (&packet_info[packet_count++])
PacketInfo(item.message_type, current_offset, proto_payload_size);
1766 if (items_processed == 1) {
1767 remaining_size = MAX_BATCH_PACKET_SIZE;
1772 current_offset = shared_buf.size() + footer_size;
1775 if (items_processed == 0) {
1776 this->deferred_batch_.clear();
1781 if (footer_size > 0) {
1782 shared_buf.resize(shared_buf.size() + footer_size);
1787 std::span<const PacketInfo>(packet_info, packet_count));
1788 if (err != APIError::OK && err != APIError::WOULD_BLOCK) {
1790 this->log_warning_(LOG_STR(
"Batch write failed"), err);
1793#ifdef HAS_PROTO_MESSAGE_DUMP
1796 for (
size_t i = 0; i < items_processed; i++) {
1797 const auto &item = this->deferred_batch_[i];
1798 this->log_batch_item_(item);
1803 if (items_processed < this->deferred_batch_.size()) {
1805 this->deferred_batch_.remove_front(items_processed);
1807 this->schedule_batch_();
1810 this->clear_batch_();
1815 bool is_single, uint8_t message_type)
const {
1818 if (message_type == EventResponse::MESSAGE_TYPE) {
1820 return APIConnection::try_send_event_response(e, *data_.string_ptr, conn, remaining_size, is_single);
1825 return data_.function_ptr(entity, conn, remaining_size, is_single);
1831 return encode_message_to_buffer(resp, ListEntitiesDoneResponse::MESSAGE_TYPE, conn, remaining_size, is_single);
1837 return encode_message_to_buffer(req, DisconnectRequest::MESSAGE_TYPE, conn, remaining_size, is_single);
1843 return encode_message_to_buffer(req, PingRequest::MESSAGE_TYPE, conn, remaining_size, is_single);
1846#ifdef USE_API_HOMEASSISTANT_STATES
1847void APIConnection::process_state_subscriptions_() {
1848 const auto &subs = this->parent_->get_state_subs();
1849 if (this->state_subs_at_ >=
static_cast<int>(subs.size())) {
1850 this->state_subs_at_ = -1;
1854 const auto &it = subs[this->state_subs_at_];
1861 resp.
once = it.once;
1862 if (this->send_message(resp, SubscribeHomeAssistantStateResponse::MESSAGE_TYPE)) {
1863 this->state_subs_at_++;
1868void APIConnection::log_warning_(
const LogString *message,
APIError err) {
1869 ESP_LOGW(TAG,
"%s: %s %s errno=%d", this->get_client_combined_info().c_str(), LOG_STR_ARG(message),
1873void APIConnection::log_socket_operation_failed_(
APIError err) {
1874 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)
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
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< 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.
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)
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
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
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