diff --git a/esphome/components/api/api_connection.cpp b/esphome/components/api/api_connection.cpp index 5c925268aa..7b91dc04f5 100644 --- a/esphome/components/api/api_connection.cpp +++ b/esphome/components/api/api_connection.cpp @@ -252,44 +252,72 @@ void APIConnection::on_disconnect_response(const DisconnectResponse &value) { #ifdef USE_BINARY_SENSOR bool APIConnection::send_binary_sensor_state(binary_sensor::BinarySensor *binary_sensor, bool state) { - BinarySensorStateResponse msg; - msg.state = state; - msg.missing_state = !binary_sensor->has_state(); - msg.key = binary_sensor->get_object_id_hash(); - return this->try_send_entity_state(msg); + // Use lambda to capture the state value + this->deferred_batch_.add_item(binary_sensor, [this, state](EntityBase *entity) -> std::unique_ptr { + auto *bs = static_cast(entity); + auto msg = std::make_unique(); + msg->state = state; + msg->missing_state = !bs->has_state(); + msg->key = bs->get_object_id_hash(); + return msg; + }); + return this->schedule_batch_(); } void APIConnection::send_binary_sensor_info(binary_sensor::BinarySensor *binary_sensor) { - ListEntitiesBinarySensorResponse msg; - msg.device_class = binary_sensor->get_device_class(); - msg.is_status_binary_sensor = binary_sensor->is_status_binary_sensor(); - msg.unique_id = get_default_unique_id("binary_sensor", binary_sensor); - this->try_send_entity_info_(static_cast(binary_sensor), msg); + // For info messages, we can use bind to avoid lambda overhead + this->deferred_batch_.add_item(binary_sensor, + std::bind(&APIConnection::try_send_binary_sensor_info_, this, std::placeholders::_1)); + this->schedule_batch_(); +} +std::unique_ptr APIConnection::try_send_binary_sensor_info_(EntityBase *entity) { + auto *binary_sensor = static_cast(entity); + auto msg = std::make_unique(); + msg->device_class = binary_sensor->get_device_class(); + msg->is_status_binary_sensor = binary_sensor->is_status_binary_sensor(); + msg->unique_id = get_default_unique_id("binary_sensor", binary_sensor); + + // Fill common entity fields + this->fill_entity_info_base_(binary_sensor, *msg); + + return msg; } #endif #ifdef USE_COVER bool APIConnection::send_cover_state(cover::Cover *cover) { - CoverStateResponse msg; - auto traits = cover->get_traits(); - msg.legacy_state = - (cover->position == cover::COVER_OPEN) ? enums::LEGACY_COVER_STATE_OPEN : enums::LEGACY_COVER_STATE_CLOSED; - msg.position = cover->position; - if (traits.get_supports_tilt()) - msg.tilt = cover->tilt; - msg.current_operation = static_cast(cover->current_operation); - msg.key = cover->get_object_id_hash(); - return this->try_send_entity_state(msg); + // Cover state doesn't need to capture extra values, so we can use bind + this->deferred_batch_.add_item(cover, std::bind(&APIConnection::try_send_cover_state_, this, std::placeholders::_1)); + return this->schedule_batch_(); } void APIConnection::send_cover_info(cover::Cover *cover) { - ListEntitiesCoverResponse msg; + this->deferred_batch_.add_item(cover, std::bind(&APIConnection::try_send_cover_info_, this, std::placeholders::_1)); + this->schedule_batch_(); +} +std::unique_ptr APIConnection::try_send_cover_state_(EntityBase *entity) { + auto *cover = static_cast(entity); + auto msg = std::make_unique(); auto traits = cover->get_traits(); - msg.assumed_state = traits.get_is_assumed_state(); - msg.supports_position = traits.get_supports_position(); - msg.supports_tilt = traits.get_supports_tilt(); - msg.supports_stop = traits.get_supports_stop(); - msg.device_class = cover->get_device_class(); - msg.unique_id = get_default_unique_id("cover", cover); - this->try_send_entity_info_(static_cast(cover), msg); + msg->legacy_state = + (cover->position == cover::COVER_OPEN) ? enums::LEGACY_COVER_STATE_OPEN : enums::LEGACY_COVER_STATE_CLOSED; + msg->position = cover->position; + if (traits.get_supports_tilt()) + msg->tilt = cover->tilt; + msg->current_operation = static_cast(cover->current_operation); + msg->key = cover->get_object_id_hash(); + return msg; +} +std::unique_ptr APIConnection::try_send_cover_info_(EntityBase *entity) { + auto *cover = static_cast(entity); + auto msg = std::make_unique(); + auto traits = cover->get_traits(); + msg->assumed_state = traits.get_is_assumed_state(); + msg->supports_position = traits.get_supports_position(); + msg->supports_tilt = traits.get_supports_tilt(); + msg->supports_stop = traits.get_supports_stop(); + msg->device_class = cover->get_device_class(); + msg->unique_id = get_default_unique_id("cover", cover); + this->fill_entity_info_base_(cover, *msg); + return msg; } void APIConnection::cover_command(const CoverCommandRequest &msg) { cover::Cover *cover = App.get_cover_by_key(msg.key); @@ -322,32 +350,43 @@ void APIConnection::cover_command(const CoverCommandRequest &msg) { #ifdef USE_FAN bool APIConnection::send_fan_state(fan::Fan *fan) { - FanStateResponse msg; - auto traits = fan->get_traits(); - msg.state = fan->state; - if (traits.supports_oscillation()) - msg.oscillating = fan->oscillating; - if (traits.supports_speed()) { - msg.speed_level = fan->speed; - } - if (traits.supports_direction()) - msg.direction = static_cast(fan->direction); - if (traits.supports_preset_modes()) - msg.preset_mode = fan->preset_mode; - msg.key = fan->get_object_id_hash(); - return this->try_send_entity_state(msg); + this->deferred_batch_.add_item(fan, std::bind(&APIConnection::try_send_fan_state_, this, std::placeholders::_1)); + return this->schedule_batch_(); } void APIConnection::send_fan_info(fan::Fan *fan) { - ListEntitiesFanResponse msg; + this->deferred_batch_.add_item(fan, std::bind(&APIConnection::try_send_fan_info_, this, std::placeholders::_1)); + this->schedule_batch_(); +} +std::unique_ptr APIConnection::try_send_fan_state_(EntityBase *entity) { + auto *fan = static_cast(entity); + auto msg = std::make_unique(); auto traits = fan->get_traits(); - msg.supports_oscillation = traits.supports_oscillation(); - msg.supports_speed = traits.supports_speed(); - msg.supports_direction = traits.supports_direction(); - msg.supported_speed_count = traits.supported_speed_count(); + msg->state = fan->state; + if (traits.supports_oscillation()) + msg->oscillating = fan->oscillating; + if (traits.supports_speed()) { + msg->speed_level = fan->speed; + } + if (traits.supports_direction()) + msg->direction = static_cast(fan->direction); + if (traits.supports_preset_modes()) + msg->preset_mode = fan->preset_mode; + msg->key = fan->get_object_id_hash(); + return msg; +} +std::unique_ptr APIConnection::try_send_fan_info_(EntityBase *entity) { + auto *fan = static_cast(entity); + auto msg = std::make_unique(); + auto traits = fan->get_traits(); + msg->supports_oscillation = traits.supports_oscillation(); + msg->supports_speed = traits.supports_speed(); + msg->supports_direction = traits.supports_direction(); + msg->supported_speed_count = traits.supported_speed_count(); for (auto const &preset : traits.supported_preset_modes()) - msg.supported_preset_modes.push_back(preset); - msg.unique_id = get_default_unique_id("fan", fan); - this->try_send_entity_info_(static_cast(fan), msg); + msg->supported_preset_modes.push_back(preset); + msg->unique_id = get_default_unique_id("fan", fan); + this->fill_entity_info_base_(fan, *msg); + return msg; } void APIConnection::fan_command(const FanCommandRequest &msg) { fan::Fan *fan = App.get_fan_by_key(msg.key); @@ -373,50 +412,62 @@ void APIConnection::fan_command(const FanCommandRequest &msg) { #ifdef USE_LIGHT bool APIConnection::send_light_state(light::LightState *light) { - LightStateResponse resp; + this->deferred_batch_.add_item(light, std::bind(&APIConnection::try_send_light_state_, this, std::placeholders::_1)); + return this->schedule_batch_(); +} +void APIConnection::send_light_info(light::LightState *light) { + this->deferred_batch_.add_item(light, std::bind(&APIConnection::try_send_light_info_, this, std::placeholders::_1)); + this->schedule_batch_(); +} +std::unique_ptr APIConnection::try_send_light_state_(EntityBase *entity) { + auto *light = static_cast(entity); + auto msg = std::make_unique(); auto traits = light->get_traits(); auto values = light->remote_values; auto color_mode = values.get_color_mode(); - resp.state = values.is_on(); - resp.color_mode = static_cast(color_mode); - resp.brightness = values.get_brightness(); - resp.color_brightness = values.get_color_brightness(); - resp.red = values.get_red(); - resp.green = values.get_green(); - resp.blue = values.get_blue(); - resp.white = values.get_white(); - resp.color_temperature = values.get_color_temperature(); - resp.cold_white = values.get_cold_white(); - resp.warm_white = values.get_warm_white(); + msg->state = values.is_on(); + msg->color_mode = static_cast(color_mode); + msg->brightness = values.get_brightness(); + msg->color_brightness = values.get_color_brightness(); + msg->red = values.get_red(); + msg->green = values.get_green(); + msg->blue = values.get_blue(); + msg->white = values.get_white(); + msg->color_temperature = values.get_color_temperature(); + msg->cold_white = values.get_cold_white(); + msg->warm_white = values.get_warm_white(); if (light->supports_effects()) - resp.effect = light->get_effect_name(); - resp.key = light->get_object_id_hash(); - return this->try_send_entity_state(resp); + msg->effect = light->get_effect_name(); + msg->key = light->get_object_id_hash(); + return msg; } -void APIConnection::send_light_info(light::LightState *light) { - ListEntitiesLightResponse msg; +std::unique_ptr APIConnection::try_send_light_info_(EntityBase *entity) { + auto *light = static_cast(entity); + auto msg = std::make_unique(); auto traits = light->get_traits(); for (auto mode : traits.get_supported_color_modes()) - msg.supported_color_modes.push_back(static_cast(mode)); - msg.legacy_supports_brightness = traits.supports_color_capability(light::ColorCapability::BRIGHTNESS); - msg.legacy_supports_rgb = traits.supports_color_capability(light::ColorCapability::RGB); - msg.legacy_supports_white_value = - msg.legacy_supports_rgb && (traits.supports_color_capability(light::ColorCapability::WHITE) || - traits.supports_color_capability(light::ColorCapability::COLD_WARM_WHITE)); - msg.legacy_supports_color_temperature = traits.supports_color_capability(light::ColorCapability::COLOR_TEMPERATURE) || - traits.supports_color_capability(light::ColorCapability::COLD_WARM_WHITE); - if (msg.legacy_supports_color_temperature) { - msg.min_mireds = traits.get_min_mireds(); - msg.max_mireds = traits.get_max_mireds(); + msg->supported_color_modes.push_back(static_cast(mode)); + msg->legacy_supports_brightness = traits.supports_color_capability(light::ColorCapability::BRIGHTNESS); + msg->legacy_supports_rgb = traits.supports_color_capability(light::ColorCapability::RGB); + msg->legacy_supports_white_value = + msg->legacy_supports_rgb && (traits.supports_color_capability(light::ColorCapability::WHITE) || + traits.supports_color_capability(light::ColorCapability::COLD_WARM_WHITE)); + msg->legacy_supports_color_temperature = + traits.supports_color_capability(light::ColorCapability::COLOR_TEMPERATURE) || + traits.supports_color_capability(light::ColorCapability::COLD_WARM_WHITE); + if (msg->legacy_supports_color_temperature) { + msg->min_mireds = traits.get_min_mireds(); + msg->max_mireds = traits.get_max_mireds(); } if (light->supports_effects()) { - msg.effects.emplace_back("None"); + msg->effects.emplace_back("None"); for (auto *effect : light->get_effects()) { - msg.effects.push_back(effect->get_name()); + msg->effects.push_back(effect->get_name()); } } - msg.unique_id = get_default_unique_id("light", light); - this->try_send_entity_info_(static_cast(light), msg); + msg->unique_id = get_default_unique_id("light", light); + this->fill_entity_info_base_(light, *msg); + return msg; } void APIConnection::light_command(const LightCommandRequest &msg) { light::LightState *light = App.get_light_by_key(msg.key); @@ -457,41 +508,62 @@ void APIConnection::light_command(const LightCommandRequest &msg) { #ifdef USE_SENSOR bool APIConnection::send_sensor_state(sensor::Sensor *sensor, float state) { - SensorStateResponse resp; - resp.state = state; - resp.missing_state = !sensor->has_state(); - - resp.key = sensor->get_object_id_hash(); - return this->try_send_entity_state(resp); + // Use lambda to capture the float state value + this->deferred_batch_.add_item(sensor, [this, state](EntityBase *entity) -> std::unique_ptr { + auto *s = static_cast(entity); + auto msg = std::make_unique(); + msg->state = state; + msg->missing_state = !s->has_state(); + msg->key = s->get_object_id_hash(); + return msg; + }); + return this->schedule_batch_(); } void APIConnection::send_sensor_info(sensor::Sensor *sensor) { - ListEntitiesSensorResponse msg; - msg.unit_of_measurement = sensor->get_unit_of_measurement(); - msg.accuracy_decimals = sensor->get_accuracy_decimals(); - msg.force_update = sensor->get_force_update(); - msg.device_class = sensor->get_device_class(); - msg.state_class = static_cast(sensor->get_state_class()); - msg.unique_id = sensor->unique_id(); - if (msg.unique_id.empty()) - msg.unique_id = get_default_unique_id("sensor", sensor); - this->try_send_entity_info_(static_cast(sensor), msg); + this->deferred_batch_.add_item(sensor, std::bind(&APIConnection::try_send_sensor_info_, this, std::placeholders::_1)); + this->schedule_batch_(); +} +std::unique_ptr APIConnection::try_send_sensor_info_(EntityBase *entity) { + auto *sensor = static_cast(entity); + auto msg = std::make_unique(); + msg->unit_of_measurement = sensor->get_unit_of_measurement(); + msg->accuracy_decimals = sensor->get_accuracy_decimals(); + msg->force_update = sensor->get_force_update(); + msg->device_class = sensor->get_device_class(); + msg->state_class = static_cast(sensor->get_state_class()); + msg->unique_id = sensor->unique_id(); + if (msg->unique_id.empty()) + msg->unique_id = get_default_unique_id("sensor", sensor); + this->fill_entity_info_base_(sensor, *msg); + return msg; } #endif #ifdef USE_SWITCH bool APIConnection::send_switch_state(switch_::Switch *a_switch, bool state) { - SwitchStateResponse resp; - resp.state = state; - - resp.key = a_switch->get_object_id_hash(); - return this->try_send_entity_state(resp); + // Use lambda to capture the bool state value + this->deferred_batch_.add_item(a_switch, [this, state](EntityBase *entity) -> std::unique_ptr { + auto *sw = static_cast(entity); + auto msg = std::make_unique(); + msg->state = state; + msg->key = sw->get_object_id_hash(); + return msg; + }); + return this->schedule_batch_(); } void APIConnection::send_switch_info(switch_::Switch *a_switch) { - ListEntitiesSwitchResponse msg; - msg.assumed_state = a_switch->assumed_state(); - msg.device_class = a_switch->get_device_class(); - msg.unique_id = get_default_unique_id("switch", a_switch); - this->try_send_entity_info_(static_cast(a_switch), msg); + this->deferred_batch_.add_item(a_switch, + std::bind(&APIConnection::try_send_switch_info_, this, std::placeholders::_1)); + this->schedule_batch_(); +} +std::unique_ptr APIConnection::try_send_switch_info_(EntityBase *entity) { + auto *a_switch = static_cast(entity); + auto msg = std::make_unique(); + msg->assumed_state = a_switch->assumed_state(); + msg->device_class = a_switch->get_device_class(); + msg->unique_id = get_default_unique_id("switch", a_switch); + this->fill_entity_info_base_(a_switch, *msg); + return msg; } void APIConnection::switch_command(const SwitchCommandRequest &msg) { switch_::Switch *a_switch = App.get_switch_by_key(msg.key); @@ -508,84 +580,118 @@ void APIConnection::switch_command(const SwitchCommandRequest &msg) { #ifdef USE_TEXT_SENSOR bool APIConnection::send_text_sensor_state(text_sensor::TextSensor *text_sensor, std::string state) { - TextSensorStateResponse resp; - resp.state = std::move(state); - resp.missing_state = !text_sensor->has_state(); - - resp.key = text_sensor->get_object_id_hash(); - return this->try_send_entity_state(resp); + // Use lambda to capture the state value + this->deferred_batch_.add_item(text_sensor, + [this, state = std::move(state)](EntityBase *entity) -> std::unique_ptr { + auto *ts = static_cast(entity); + auto msg = std::make_unique(); + msg->state = std::move(state); + msg->missing_state = !ts->has_state(); + msg->key = ts->get_object_id_hash(); + return msg; + }); + return this->schedule_batch_(); } void APIConnection::send_text_sensor_info(text_sensor::TextSensor *text_sensor) { - ListEntitiesTextSensorResponse msg; - msg.device_class = text_sensor->get_device_class(); - msg.unique_id = text_sensor->unique_id(); - if (msg.unique_id.empty()) - msg.unique_id = get_default_unique_id("text_sensor", text_sensor); - this->try_send_entity_info_(static_cast(text_sensor), msg); + // For info messages, we can use bind to avoid lambda overhead + this->deferred_batch_.add_item(text_sensor, + std::bind(&APIConnection::try_send_text_sensor_info_, this, std::placeholders::_1)); + this->schedule_batch_(); +} +std::unique_ptr APIConnection::try_send_text_sensor_info_(EntityBase *entity) { + auto *text_sensor = static_cast(entity); + auto msg = std::make_unique(); + msg->device_class = text_sensor->get_device_class(); + msg->unique_id = text_sensor->unique_id(); + if (msg->unique_id.empty()) + msg->unique_id = get_default_unique_id("text_sensor", text_sensor); + + // Fill common entity fields + this->fill_entity_info_base_(text_sensor, *msg); + + return msg; } #endif #ifdef USE_CLIMATE bool APIConnection::send_climate_state(climate::Climate *climate) { - ClimateStateResponse resp; - resp.key = climate->get_object_id_hash(); + // Climate state doesn't need to capture extra values, so we can use bind + this->deferred_batch_.add_item(climate, + std::bind(&APIConnection::try_send_climate_state_, this, std::placeholders::_1)); + return this->schedule_batch_(); +} +std::unique_ptr APIConnection::try_send_climate_state_(EntityBase *entity) { + auto *climate = static_cast(entity); + auto msg = std::make_unique(); + msg->key = climate->get_object_id_hash(); auto traits = climate->get_traits(); - resp.mode = static_cast(climate->mode); - resp.action = static_cast(climate->action); + msg->mode = static_cast(climate->mode); + msg->action = static_cast(climate->action); if (traits.get_supports_current_temperature()) - resp.current_temperature = climate->current_temperature; + msg->current_temperature = climate->current_temperature; if (traits.get_supports_two_point_target_temperature()) { - resp.target_temperature_low = climate->target_temperature_low; - resp.target_temperature_high = climate->target_temperature_high; + msg->target_temperature_low = climate->target_temperature_low; + msg->target_temperature_high = climate->target_temperature_high; } else { - resp.target_temperature = climate->target_temperature; + msg->target_temperature = climate->target_temperature; } if (traits.get_supports_fan_modes() && climate->fan_mode.has_value()) - resp.fan_mode = static_cast(climate->fan_mode.value()); + msg->fan_mode = static_cast(climate->fan_mode.value()); if (!traits.get_supported_custom_fan_modes().empty() && climate->custom_fan_mode.has_value()) - resp.custom_fan_mode = climate->custom_fan_mode.value(); + msg->custom_fan_mode = climate->custom_fan_mode.value(); if (traits.get_supports_presets() && climate->preset.has_value()) { - resp.preset = static_cast(climate->preset.value()); + msg->preset = static_cast(climate->preset.value()); } if (!traits.get_supported_custom_presets().empty() && climate->custom_preset.has_value()) - resp.custom_preset = climate->custom_preset.value(); + msg->custom_preset = climate->custom_preset.value(); if (traits.get_supports_swing_modes()) - resp.swing_mode = static_cast(climate->swing_mode); + msg->swing_mode = static_cast(climate->swing_mode); if (traits.get_supports_current_humidity()) - resp.current_humidity = climate->current_humidity; + msg->current_humidity = climate->current_humidity; if (traits.get_supports_target_humidity()) - resp.target_humidity = climate->target_humidity; - return this->try_send_entity_state(resp); + msg->target_humidity = climate->target_humidity; + return msg; } void APIConnection::send_climate_info(climate::Climate *climate) { - ListEntitiesClimateResponse msg; + // For info messages, we can use bind to avoid lambda overhead + this->deferred_batch_.add_item(climate, + std::bind(&APIConnection::try_send_climate_info_, this, std::placeholders::_1)); + this->schedule_batch_(); +} +std::unique_ptr APIConnection::try_send_climate_info_(EntityBase *entity) { + auto *climate = static_cast(entity); + auto msg = std::make_unique(); auto traits = climate->get_traits(); - msg.supports_current_temperature = traits.get_supports_current_temperature(); - msg.supports_current_humidity = traits.get_supports_current_humidity(); - msg.supports_two_point_target_temperature = traits.get_supports_two_point_target_temperature(); - msg.supports_target_humidity = traits.get_supports_target_humidity(); + msg->supports_current_temperature = traits.get_supports_current_temperature(); + msg->supports_current_humidity = traits.get_supports_current_humidity(); + msg->supports_two_point_target_temperature = traits.get_supports_two_point_target_temperature(); + msg->supports_target_humidity = traits.get_supports_target_humidity(); for (auto mode : traits.get_supported_modes()) - msg.supported_modes.push_back(static_cast(mode)); - msg.visual_min_temperature = traits.get_visual_min_temperature(); - msg.visual_max_temperature = traits.get_visual_max_temperature(); - msg.visual_target_temperature_step = traits.get_visual_target_temperature_step(); - msg.visual_current_temperature_step = traits.get_visual_current_temperature_step(); - msg.visual_min_humidity = traits.get_visual_min_humidity(); - msg.visual_max_humidity = traits.get_visual_max_humidity(); - msg.legacy_supports_away = traits.supports_preset(climate::CLIMATE_PRESET_AWAY); - msg.supports_action = traits.get_supports_action(); + msg->supported_modes.push_back(static_cast(mode)); + msg->visual_min_temperature = traits.get_visual_min_temperature(); + msg->visual_max_temperature = traits.get_visual_max_temperature(); + msg->visual_target_temperature_step = traits.get_visual_target_temperature_step(); + msg->visual_current_temperature_step = traits.get_visual_current_temperature_step(); + msg->visual_min_humidity = traits.get_visual_min_humidity(); + msg->visual_max_humidity = traits.get_visual_max_humidity(); + msg->legacy_supports_away = traits.supports_preset(climate::CLIMATE_PRESET_AWAY); + msg->supports_action = traits.get_supports_action(); for (auto fan_mode : traits.get_supported_fan_modes()) - msg.supported_fan_modes.push_back(static_cast(fan_mode)); + msg->supported_fan_modes.push_back(static_cast(fan_mode)); for (auto const &custom_fan_mode : traits.get_supported_custom_fan_modes()) - msg.supported_custom_fan_modes.push_back(custom_fan_mode); + msg->supported_custom_fan_modes.push_back(custom_fan_mode); for (auto preset : traits.get_supported_presets()) - msg.supported_presets.push_back(static_cast(preset)); + msg->supported_presets.push_back(static_cast(preset)); for (auto const &custom_preset : traits.get_supported_custom_presets()) - msg.supported_custom_presets.push_back(custom_preset); + msg->supported_custom_presets.push_back(custom_preset); for (auto swing_mode : traits.get_supported_swing_modes()) - msg.supported_swing_modes.push_back(static_cast(swing_mode)); - msg.unique_id = get_default_unique_id("climate", climate); - this->try_send_entity_info_(static_cast(climate), msg); + msg->supported_swing_modes.push_back(static_cast(swing_mode)); + msg->unique_id = get_default_unique_id("climate", climate); + + // Fill common entity fields + this->fill_entity_info_base_(climate, *msg); + + return msg; } void APIConnection::climate_command(const ClimateCommandRequest &msg) { climate::Climate *climate = App.get_climate_by_key(msg.key); @@ -619,23 +725,37 @@ void APIConnection::climate_command(const ClimateCommandRequest &msg) { #ifdef USE_NUMBER bool APIConnection::send_number_state(number::Number *number, float state) { - NumberStateResponse resp; - resp.state = state; - resp.missing_state = !number->has_state(); - - resp.key = number->get_object_id_hash(); - return this->try_send_entity_state(resp); + // Use lambda to capture the state value + this->deferred_batch_.add_item(number, [this, state](EntityBase *entity) -> std::unique_ptr { + auto *n = static_cast(entity); + auto msg = std::make_unique(); + msg->state = state; + msg->missing_state = !n->has_state(); + msg->key = n->get_object_id_hash(); + return msg; + }); + return this->schedule_batch_(); } void APIConnection::send_number_info(number::Number *number) { - ListEntitiesNumberResponse msg; - msg.unit_of_measurement = number->traits.get_unit_of_measurement(); - msg.mode = static_cast(number->traits.get_mode()); - msg.device_class = number->traits.get_device_class(); - msg.min_value = number->traits.get_min_value(); - msg.max_value = number->traits.get_max_value(); - msg.step = number->traits.get_step(); - msg.unique_id = get_default_unique_id("number", number); - this->try_send_entity_info_(static_cast(number), msg); + // For info messages, we can use bind to avoid lambda overhead + this->deferred_batch_.add_item(number, std::bind(&APIConnection::try_send_number_info_, this, std::placeholders::_1)); + this->schedule_batch_(); +} +std::unique_ptr APIConnection::try_send_number_info_(EntityBase *entity) { + auto *number = static_cast(entity); + auto msg = std::make_unique(); + msg->unit_of_measurement = number->traits.get_unit_of_measurement(); + msg->mode = static_cast(number->traits.get_mode()); + msg->device_class = number->traits.get_device_class(); + msg->min_value = number->traits.get_min_value(); + msg->max_value = number->traits.get_max_value(); + msg->step = number->traits.get_step(); + msg->unique_id = get_default_unique_id("number", number); + + // Fill common entity fields + this->fill_entity_info_base_(number, *msg); + + return msg; } void APIConnection::number_command(const NumberCommandRequest &msg) { number::Number *number = App.get_number_by_key(msg.key); @@ -650,19 +770,34 @@ void APIConnection::number_command(const NumberCommandRequest &msg) { #ifdef USE_DATETIME_DATE bool APIConnection::send_date_state(datetime::DateEntity *date) { - DateStateResponse resp; - resp.missing_state = !date->has_state(); - resp.year = date->year; - resp.month = date->month; - resp.day = date->day; - - resp.key = date->get_object_id_hash(); - return this->try_send_entity_state(resp); + // Date state doesn't need to capture extra values, so we can use bind + this->deferred_batch_.add_item(date, std::bind(&APIConnection::try_send_date_state_, this, std::placeholders::_1)); + return this->schedule_batch_(); +} +std::unique_ptr APIConnection::try_send_date_state_(EntityBase *entity) { + auto *date = static_cast(entity); + auto msg = std::make_unique(); + msg->missing_state = !date->has_state(); + msg->year = date->year; + msg->month = date->month; + msg->day = date->day; + msg->key = date->get_object_id_hash(); + return msg; } void APIConnection::send_date_info(datetime::DateEntity *date) { - ListEntitiesDateResponse msg; - msg.unique_id = get_default_unique_id("date", date); - this->try_send_entity_info_(static_cast(date), msg); + // For info messages, we can use bind to avoid lambda overhead + this->deferred_batch_.add_item(date, std::bind(&APIConnection::try_send_date_info_, this, std::placeholders::_1)); + this->schedule_batch_(); +} +std::unique_ptr APIConnection::try_send_date_info_(EntityBase *entity) { + auto *date = static_cast(entity); + auto msg = std::make_unique(); + msg->unique_id = get_default_unique_id("date", date); + + // Fill common entity fields + this->fill_entity_info_base_(date, *msg); + + return msg; } void APIConnection::date_command(const DateCommandRequest &msg) { datetime::DateEntity *date = App.get_date_by_key(msg.key); @@ -677,19 +812,34 @@ void APIConnection::date_command(const DateCommandRequest &msg) { #ifdef USE_DATETIME_TIME bool APIConnection::send_time_state(datetime::TimeEntity *time) { - TimeStateResponse resp; - resp.missing_state = !time->has_state(); - resp.hour = time->hour; - resp.minute = time->minute; - resp.second = time->second; - - resp.key = time->get_object_id_hash(); - return this->try_send_entity_state(resp); + // Time state doesn't need to capture extra values, so we can use bind + this->deferred_batch_.add_item(time, std::bind(&APIConnection::try_send_time_state_, this, std::placeholders::_1)); + return this->schedule_batch_(); +} +std::unique_ptr APIConnection::try_send_time_state_(EntityBase *entity) { + auto *time = static_cast(entity); + auto msg = std::make_unique(); + msg->missing_state = !time->has_state(); + msg->hour = time->hour; + msg->minute = time->minute; + msg->second = time->second; + msg->key = time->get_object_id_hash(); + return msg; } void APIConnection::send_time_info(datetime::TimeEntity *time) { - ListEntitiesTimeResponse msg; - msg.unique_id = get_default_unique_id("time", time); - this->try_send_entity_info_(static_cast(time), msg); + // For info messages, we can use bind to avoid lambda overhead + this->deferred_batch_.add_item(time, std::bind(&APIConnection::try_send_time_info_, this, std::placeholders::_1)); + this->schedule_batch_(); +} +std::unique_ptr APIConnection::try_send_time_info_(EntityBase *entity) { + auto *time = static_cast(entity); + auto msg = std::make_unique(); + msg->unique_id = get_default_unique_id("time", time); + + // Fill common entity fields + this->fill_entity_info_base_(time, *msg); + + return msg; } void APIConnection::time_command(const TimeCommandRequest &msg) { datetime::TimeEntity *time = App.get_time_by_key(msg.key); @@ -704,20 +854,37 @@ void APIConnection::time_command(const TimeCommandRequest &msg) { #ifdef USE_DATETIME_DATETIME bool APIConnection::send_datetime_state(datetime::DateTimeEntity *datetime) { - DateTimeStateResponse resp; - resp.missing_state = !datetime->has_state(); + // DateTime state doesn't need to capture extra values, so we can use bind + this->deferred_batch_.add_item(datetime, + std::bind(&APIConnection::try_send_datetime_state_, this, std::placeholders::_1)); + return this->schedule_batch_(); +} +std::unique_ptr APIConnection::try_send_datetime_state_(EntityBase *entity) { + auto *datetime = static_cast(entity); + auto msg = std::make_unique(); + msg->missing_state = !datetime->has_state(); if (datetime->has_state()) { ESPTime state = datetime->state_as_esptime(); - resp.epoch_seconds = state.timestamp; + msg->epoch_seconds = state.timestamp; } - - resp.key = datetime->get_object_id_hash(); - return this->try_send_entity_state(resp); + msg->key = datetime->get_object_id_hash(); + return msg; } void APIConnection::send_datetime_info(datetime::DateTimeEntity *datetime) { - ListEntitiesDateTimeResponse msg; - msg.unique_id = get_default_unique_id("datetime", datetime); - this->try_send_entity_info_(static_cast(datetime), msg); + // For info messages, we can use bind to avoid lambda overhead + this->deferred_batch_.add_item(datetime, + std::bind(&APIConnection::try_send_datetime_info_, this, std::placeholders::_1)); + this->schedule_batch_(); +} +std::unique_ptr APIConnection::try_send_datetime_info_(EntityBase *entity) { + auto *datetime = static_cast(entity); + auto msg = std::make_unique(); + msg->unique_id = get_default_unique_id("datetime", datetime); + + // Fill common entity fields + this->fill_entity_info_base_(datetime, *msg); + + return msg; } void APIConnection::datetime_command(const DateTimeCommandRequest &msg) { datetime::DateTimeEntity *datetime = App.get_datetime_by_key(msg.key); @@ -732,21 +899,36 @@ void APIConnection::datetime_command(const DateTimeCommandRequest &msg) { #ifdef USE_TEXT bool APIConnection::send_text_state(text::Text *text, std::string state) { - TextStateResponse resp; - resp.state = std::move(state); - resp.missing_state = !text->has_state(); - - resp.key = text->get_object_id_hash(); - return this->try_send_entity_state(resp); + // Use lambda to capture the state value + this->deferred_batch_.add_item(text, + [this, state = std::move(state)](EntityBase *entity) -> std::unique_ptr { + auto *t = static_cast(entity); + auto msg = std::make_unique(); + msg->state = std::move(state); + msg->missing_state = !t->has_state(); + msg->key = t->get_object_id_hash(); + return msg; + }); + return this->schedule_batch_(); } void APIConnection::send_text_info(text::Text *text) { - ListEntitiesTextResponse msg; - msg.mode = static_cast(text->traits.get_mode()); - msg.min_length = text->traits.get_min_length(); - msg.max_length = text->traits.get_max_length(); - msg.pattern = text->traits.get_pattern(); - msg.unique_id = get_default_unique_id("text", text); - this->try_send_entity_info_(static_cast(text), msg); + // For info messages, we can use bind to avoid lambda overhead + this->deferred_batch_.add_item(text, std::bind(&APIConnection::try_send_text_info_, this, std::placeholders::_1)); + this->schedule_batch_(); +} +std::unique_ptr APIConnection::try_send_text_info_(EntityBase *entity) { + auto *text = static_cast(entity); + auto msg = std::make_unique(); + msg->mode = static_cast(text->traits.get_mode()); + msg->min_length = text->traits.get_min_length(); + msg->max_length = text->traits.get_max_length(); + msg->pattern = text->traits.get_pattern(); + msg->unique_id = get_default_unique_id("text", text); + + // Fill common entity fields + this->fill_entity_info_base_(text, *msg); + + return msg; } void APIConnection::text_command(const TextCommandRequest &msg) { text::Text *text = App.get_text_by_key(msg.key); @@ -761,19 +943,34 @@ void APIConnection::text_command(const TextCommandRequest &msg) { #ifdef USE_SELECT bool APIConnection::send_select_state(select::Select *select, std::string state) { - SelectStateResponse resp; - resp.state = std::move(state); - resp.missing_state = !select->has_state(); - - resp.key = select->get_object_id_hash(); - return this->try_send_entity_state(resp); + // Use lambda to capture the state value + this->deferred_batch_.add_item(select, + [this, state = std::move(state)](EntityBase *entity) -> std::unique_ptr { + auto *s = static_cast(entity); + auto msg = std::make_unique(); + msg->state = std::move(state); + msg->missing_state = !s->has_state(); + msg->key = s->get_object_id_hash(); + return msg; + }); + return this->schedule_batch_(); } void APIConnection::send_select_info(select::Select *select) { - ListEntitiesSelectResponse msg; + // For info messages, we can use bind to avoid lambda overhead + this->deferred_batch_.add_item(select, std::bind(&APIConnection::try_send_select_info_, this, std::placeholders::_1)); + this->schedule_batch_(); +} +std::unique_ptr APIConnection::try_send_select_info_(EntityBase *entity) { + auto *select = static_cast(entity); + auto msg = std::make_unique(); for (const auto &option : select->traits.get_options()) - msg.options.push_back(option); - msg.unique_id = get_default_unique_id("select", select); - this->try_send_entity_info_(static_cast(select), msg); + msg->options.push_back(option); + msg->unique_id = get_default_unique_id("select", select); + + // Fill common entity fields + this->fill_entity_info_base_(select, *msg); + + return msg; } void APIConnection::select_command(const SelectCommandRequest &msg) { select::Select *select = App.get_select_by_key(msg.key); @@ -788,10 +985,20 @@ void APIConnection::select_command(const SelectCommandRequest &msg) { #ifdef USE_BUTTON void esphome::api::APIConnection::send_button_info(button::Button *button) { - ListEntitiesButtonResponse msg; - msg.device_class = button->get_device_class(); - msg.unique_id = get_default_unique_id("button", button); - this->try_send_entity_info_(static_cast(button), msg); + // For info messages, we can use bind to avoid lambda overhead + this->deferred_batch_.add_item(button, std::bind(&APIConnection::try_send_button_info_, this, std::placeholders::_1)); + this->schedule_batch_(); +} +std::unique_ptr APIConnection::try_send_button_info_(EntityBase *entity) { + auto *button = static_cast(entity); + auto msg = std::make_unique(); + msg->device_class = button->get_device_class(); + msg->unique_id = get_default_unique_id("button", button); + + // Fill common entity fields + this->fill_entity_info_base_(button, *msg); + + return msg; } void esphome::api::APIConnection::button_command(const ButtonCommandRequest &msg) { button::Button *button = App.get_button_by_key(msg.key); @@ -804,19 +1011,33 @@ void esphome::api::APIConnection::button_command(const ButtonCommandRequest &msg #ifdef USE_LOCK bool APIConnection::send_lock_state(lock::Lock *a_lock, lock::LockState state) { - LockStateResponse resp; - resp.state = static_cast(state); - - resp.key = a_lock->get_object_id_hash(); - return this->try_send_entity_state(resp); + // Use lambda to capture the state value + this->deferred_batch_.add_item(a_lock, [this, state](EntityBase *entity) -> std::unique_ptr { + auto *l = static_cast(entity); + auto msg = std::make_unique(); + msg->state = static_cast(state); + msg->key = l->get_object_id_hash(); + return msg; + }); + return this->schedule_batch_(); } void APIConnection::send_lock_info(lock::Lock *a_lock) { - ListEntitiesLockResponse msg; - msg.assumed_state = a_lock->traits.get_assumed_state(); - msg.supports_open = a_lock->traits.get_supports_open(); - msg.requires_code = a_lock->traits.get_requires_code(); - msg.unique_id = get_default_unique_id("lock", a_lock); - this->try_send_entity_info_(static_cast(a_lock), msg); + // For info messages, we can use bind to avoid lambda overhead + this->deferred_batch_.add_item(a_lock, std::bind(&APIConnection::try_send_lock_info_, this, std::placeholders::_1)); + this->schedule_batch_(); +} +std::unique_ptr APIConnection::try_send_lock_info_(EntityBase *entity) { + auto *a_lock = static_cast(entity); + auto msg = std::make_unique(); + msg->assumed_state = a_lock->traits.get_assumed_state(); + msg->supports_open = a_lock->traits.get_supports_open(); + msg->requires_code = a_lock->traits.get_requires_code(); + msg->unique_id = get_default_unique_id("lock", a_lock); + + // Fill common entity fields + this->fill_entity_info_base_(a_lock, *msg); + + return msg; } void APIConnection::lock_command(const LockCommandRequest &msg) { lock::Lock *a_lock = App.get_lock_by_key(msg.key); @@ -839,22 +1060,37 @@ void APIConnection::lock_command(const LockCommandRequest &msg) { #ifdef USE_VALVE bool APIConnection::send_valve_state(valve::Valve *valve) { - ValveStateResponse resp; - resp.position = valve->position; - resp.current_operation = static_cast(valve->current_operation); - - resp.key = valve->get_object_id_hash(); - return this->try_send_entity_state(resp); + // Valve state doesn't need to capture extra values, so we can use bind + this->deferred_batch_.add_item(valve, std::bind(&APIConnection::try_send_valve_state_, this, std::placeholders::_1)); + return this->schedule_batch_(); +} +std::unique_ptr APIConnection::try_send_valve_state_(EntityBase *entity) { + auto *valve = static_cast(entity); + auto msg = std::make_unique(); + msg->position = valve->position; + msg->current_operation = static_cast(valve->current_operation); + msg->key = valve->get_object_id_hash(); + return msg; } void APIConnection::send_valve_info(valve::Valve *valve) { - ListEntitiesValveResponse msg; + // For info messages, we can use bind to avoid lambda overhead + this->deferred_batch_.add_item(valve, std::bind(&APIConnection::try_send_valve_info_, this, std::placeholders::_1)); + this->schedule_batch_(); +} +std::unique_ptr APIConnection::try_send_valve_info_(EntityBase *entity) { + auto *valve = static_cast(entity); + auto msg = std::make_unique(); auto traits = valve->get_traits(); - msg.device_class = valve->get_device_class(); - msg.assumed_state = traits.get_is_assumed_state(); - msg.supports_position = traits.get_supports_position(); - msg.supports_stop = traits.get_supports_stop(); - msg.unique_id = get_default_unique_id("valve", valve); - this->try_send_entity_info_(static_cast(valve), msg); + msg->device_class = valve->get_device_class(); + msg->assumed_state = traits.get_is_assumed_state(); + msg->supports_position = traits.get_supports_position(); + msg->supports_stop = traits.get_supports_stop(); + msg->unique_id = get_default_unique_id("valve", valve); + + // Fill common entity fields + this->fill_entity_info_base_(valve, *msg); + + return msg; } void APIConnection::valve_command(const ValveCommandRequest &msg) { valve::Valve *valve = App.get_valve_by_key(msg.key); @@ -872,21 +1108,34 @@ void APIConnection::valve_command(const ValveCommandRequest &msg) { #ifdef USE_MEDIA_PLAYER bool APIConnection::send_media_player_state(media_player::MediaPlayer *media_player) { - MediaPlayerStateResponse resp; + // Media player state doesn't need to capture extra values, so we can use bind + this->deferred_batch_.add_item(media_player, + std::bind(&APIConnection::try_send_media_player_state_, this, std::placeholders::_1)); + return this->schedule_batch_(); +} +std::unique_ptr APIConnection::try_send_media_player_state_(EntityBase *entity) { + auto *media_player = static_cast(entity); + auto msg = std::make_unique(); media_player::MediaPlayerState report_state = media_player->state == media_player::MEDIA_PLAYER_STATE_ANNOUNCING ? media_player::MEDIA_PLAYER_STATE_PLAYING : media_player->state; - resp.state = static_cast(report_state); - resp.volume = media_player->volume; - resp.muted = media_player->is_muted(); - - resp.key = media_player->get_object_id_hash(); - return this->try_send_entity_state(resp); + msg->state = static_cast(report_state); + msg->volume = media_player->volume; + msg->muted = media_player->is_muted(); + msg->key = media_player->get_object_id_hash(); + return msg; } void APIConnection::send_media_player_info(media_player::MediaPlayer *media_player) { - ListEntitiesMediaPlayerResponse msg; + // For info messages, we can use bind to avoid lambda overhead + this->deferred_batch_.add_item(media_player, + std::bind(&APIConnection::try_send_media_player_info_, this, std::placeholders::_1)); + this->schedule_batch_(); +} +std::unique_ptr APIConnection::try_send_media_player_info_(EntityBase *entity) { + auto *media_player = static_cast(entity); + auto msg = std::make_unique(); auto traits = media_player->get_traits(); - msg.supports_pause = traits.get_supports_pause(); + msg->supports_pause = traits.get_supports_pause(); for (auto &supported_format : traits.get_supported_formats()) { MediaPlayerSupportedFormat media_format; media_format.format = supported_format.format; @@ -894,10 +1143,14 @@ void APIConnection::send_media_player_info(media_player::MediaPlayer *media_play media_format.num_channels = supported_format.num_channels; media_format.purpose = static_cast(supported_format.purpose); media_format.sample_bytes = supported_format.sample_bytes; - msg.supported_formats.push_back(media_format); + msg->supported_formats.push_back(media_format); } - msg.unique_id = get_default_unique_id("media_player", media_player); - this->try_send_entity_info_(static_cast(media_player), msg); + msg->unique_id = get_default_unique_id("media_player", media_player); + + // Fill common entity fields + this->fill_entity_info_base_(media_player, *msg); + + return msg; } void APIConnection::media_player_command(const MediaPlayerCommandRequest &msg) { media_player::MediaPlayer *media_player = App.get_media_player_by_key(msg.key); @@ -1441,21 +1694,17 @@ void APIConnection::on_fatal_error() { this->remove_ = true; } -void APIConnection::DeferredBatch::add_item(std::unique_ptr message) { - // Calculate message size - uint32_t size = 0; - message->calculate_size(size); - uint16_t message_size = static_cast(size); - - // Add new item without deduplication - items.push_back({std::move(message), message_size, App.get_loop_component_start_time()}); +void APIConnection::DeferredBatch::add_item(EntityBase *entity, MessageCreator creator) { + // Add new item without deduplication for now + items.push_back({entity, std::move(creator), App.get_loop_component_start_time()}); } -void APIConnection::schedule_batch_() { +bool APIConnection::schedule_batch_() { if (!this->deferred_batch_.batch_scheduled) { this->deferred_batch_.batch_scheduled = true; this->deferred_batch_.batch_start_time = App.get_loop_component_start_time(); } + return true; } void APIConnection::process_batch_() { @@ -1472,19 +1721,47 @@ void APIConnection::process_batch_() { return; } + // First pass: create messages and calculate sizes + struct MessageInfo { + std::unique_ptr message; + uint16_t message_size; + }; + std::vector messages; + messages.reserve(this->deferred_batch_.items.size()); + + for (const auto &item : this->deferred_batch_.items) { + // Call the creator function with the entity to generate the message + auto message = item.creator(item.entity); + if (!message) { + continue; // Skip if creator returned nullptr + } + + // Calculate message size + uint32_t size = 0; + message->calculate_size(size); + uint16_t message_size = static_cast(size); + + messages.push_back({std::move(message), message_size}); + } + + if (messages.empty()) { + this->deferred_batch_.clear(); + return; + } + // Calculate the total size needed and build packet info std::vector> packet_info; - packet_info.reserve(this->deferred_batch_.items.size()); + packet_info.reserve(messages.size()); uint32_t total_buffer_size = 0; size_t messages_to_process = 0; uint32_t current_offset = 0; // Track offset for each packet - for (size_t i = 0; i < this->deferred_batch_.items.size(); i++) { - const auto &item = this->deferred_batch_.items[i]; - uint16_t message_type = item.message->get_message_type(); - uint16_t overhead = this->helper_->calculate_packet_overhead(message_type, item.message_size); - uint32_t packet_size = item.message_size + overhead; + for (size_t i = 0; i < messages.size(); i++) { + const auto &msg_info = messages[i]; + uint16_t message_type = msg_info.message->get_message_type(); + uint16_t overhead = this->helper_->calculate_packet_overhead(message_type, msg_info.message_size); + uint32_t packet_size = msg_info.message_size + overhead; // Check if adding this message would exceed our limit if (messages_to_process > 0 && total_buffer_size + packet_size > MAX_BATCH_SIZE_BYTES) { @@ -1493,11 +1770,11 @@ void APIConnection::process_batch_() { // Add to packet info (type, offset where packet starts, message length) // For the first message, offset is 0; for subsequent messages, it's after previous message + padding - packet_info.push_back(std::make_tuple(message_type, current_offset, item.message_size)); + packet_info.push_back(std::make_tuple(message_type, current_offset, msg_info.message_size)); // Update offset for next message: add header padding for next message if not last - if (i < this->deferred_batch_.items.size() - 1) { - current_offset += item.message_size + this->helper_->frame_header_padding(); + if (i < messages.size() - 1) { + current_offset += msg_info.message_size + this->helper_->frame_header_padding(); } total_buffer_size += packet_size; @@ -1508,15 +1785,15 @@ void APIConnection::process_batch_() { // Encode all messages for (size_t i = 0; i < messages_to_process; i++) { - const auto &item = this->deferred_batch_.items[i]; + const auto &msg_info = messages[i]; // For messages after the first, extend the buffer with padding if (i > 0) { batch_buffer = this->extend_buffer(); } - // Encode the message directly from the stored ProtoMessage - item.message->encode(batch_buffer); + // Encode the message + msg_info.message->encode(batch_buffer); } // Send all collected packets diff --git a/esphome/components/api/api_connection.h b/esphome/components/api/api_connection.h index 4b6c545939..cf5125abb6 100644 --- a/esphome/components/api/api_connection.h +++ b/esphome/components/api/api_connection.h @@ -11,6 +11,7 @@ #include "esphome/core/entity_base.h" #include +#include namespace esphome { namespace api { @@ -333,10 +334,11 @@ class APIConnection : public APIServerConnection { response.disabled_by_default = entity->is_disabled_by_default(); response.entity_category = static_cast(entity->get_entity_category()); - // Add to deferred batch - this->deferred_batch_.add_item(std::make_unique(response)); - this->schedule_batch_(); - return true; + // Add to deferred batch with a lambda that creates the message + this->deferred_batch_.add_item(entity, [response](EntityBase *) -> std::unique_ptr { + return std::make_unique(response); + }); + return this->schedule_batch_(); } /** @@ -346,14 +348,113 @@ class APIConnection : public APIServerConnection { * @return True if the message was sent successfully */ template bool try_send_entity_state(ResponseT &response) { - // Add to deferred batch - this->deferred_batch_.add_item(std::make_unique(response)); + // Add to deferred batch with a lambda that creates the message + this->deferred_batch_.add_item( + [response]() -> std::unique_ptr { return std::make_unique(response); }); this->schedule_batch_(); return true; } bool send_(const void *buf, size_t len, bool force); + protected: + // Helper function to fill common entity fields + template void fill_entity_info_base_(esphome::EntityBase *entity, ResponseT &response) { + // Set common fields that are shared by all entity types + response.key = entity->get_object_id_hash(); + response.object_id = entity->get_object_id(); + + if (entity->has_own_name()) + response.name = entity->get_name(); + + // Set common EntityBase properties + response.icon = entity->get_icon(); + response.disabled_by_default = entity->is_disabled_by_default(); + response.entity_category = static_cast(entity->get_entity_category()); + } +#ifdef USE_BINARY_SENSOR + std::unique_ptr try_send_binary_sensor_state_(EntityBase *binary_sensor); + std::unique_ptr try_send_binary_sensor_info_(EntityBase *binary_sensor); +#endif +#ifdef USE_COVER + std::unique_ptr try_send_cover_state_(EntityBase *cover); + std::unique_ptr try_send_cover_info_(EntityBase *cover); +#endif +#ifdef USE_FAN + std::unique_ptr try_send_fan_state_(EntityBase *fan); + std::unique_ptr try_send_fan_info_(EntityBase *fan); +#endif +#ifdef USE_LIGHT + std::unique_ptr try_send_light_state_(EntityBase *light); + std::unique_ptr try_send_light_info_(EntityBase *light); +#endif +#ifdef USE_SENSOR + std::unique_ptr try_send_sensor_state_(EntityBase *sensor); + std::unique_ptr try_send_sensor_info_(EntityBase *sensor); +#endif +#ifdef USE_SWITCH + std::unique_ptr try_send_switch_state_(EntityBase *a_switch); + std::unique_ptr try_send_switch_info_(EntityBase *a_switch); +#endif +#ifdef USE_TEXT_SENSOR + std::unique_ptr try_send_text_sensor_state_(EntityBase *text_sensor); + std::unique_ptr try_send_text_sensor_info_(EntityBase *text_sensor); +#endif +#ifdef USE_CLIMATE + std::unique_ptr try_send_climate_state_(EntityBase *climate); + std::unique_ptr try_send_climate_info_(EntityBase *climate); +#endif +#ifdef USE_NUMBER + std::unique_ptr try_send_number_state_(EntityBase *number); + std::unique_ptr try_send_number_info_(EntityBase *number); +#endif +#ifdef USE_DATETIME_DATE + std::unique_ptr try_send_date_state_(EntityBase *date); + std::unique_ptr try_send_date_info_(EntityBase *date); +#endif +#ifdef USE_DATETIME_TIME + std::unique_ptr try_send_time_state_(EntityBase *time); + std::unique_ptr try_send_time_info_(EntityBase *time); +#endif +#ifdef USE_DATETIME_DATETIME + std::unique_ptr try_send_datetime_state_(EntityBase *datetime); + std::unique_ptr try_send_datetime_info_(EntityBase *datetime); +#endif +#ifdef USE_TEXT + std::unique_ptr try_send_text_state_(EntityBase *text); + std::unique_ptr try_send_text_info_(EntityBase *text); +#endif +#ifdef USE_SELECT + std::unique_ptr try_send_select_state_(EntityBase *select); + std::unique_ptr try_send_select_info_(EntityBase *select); +#endif +#ifdef USE_BUTTON + std::unique_ptr try_send_button_info_(EntityBase *button); +#endif +#ifdef USE_LOCK + std::unique_ptr try_send_lock_state_(EntityBase *a_lock); + std::unique_ptr try_send_lock_info_(EntityBase *a_lock); +#endif +#ifdef USE_VALVE + std::unique_ptr try_send_valve_state_(EntityBase *valve); + std::unique_ptr try_send_valve_info_(EntityBase *valve); +#endif +#ifdef USE_MEDIA_PLAYER + std::unique_ptr try_send_media_player_state_(EntityBase *media_player); + std::unique_ptr try_send_media_player_info_(EntityBase *media_player); +#endif +#ifdef USE_ALARM_CONTROL_PANEL + std::unique_ptr try_send_alarm_control_panel_state_(EntityBase *a_alarm_control_panel); + std::unique_ptr try_send_alarm_control_panel_info_(EntityBase *a_alarm_control_panel); +#endif +#ifdef USE_EVENT + std::unique_ptr try_send_event_info_(EntityBase *event); +#endif +#ifdef USE_UPDATE + std::unique_ptr try_send_update_state_(EntityBase *update); + std::unique_ptr try_send_update_info_(EntityBase *update); +#endif + enum class ConnectionState { WAITING_FOR_HELLO, CONNECTED, @@ -389,12 +490,15 @@ class APIConnection : public APIServerConnection { ListEntitiesIterator list_entities_iterator_; int state_subs_at_ = -1; + // Function type that creates a ProtoMessage from an entity + using MessageCreator = std::function(EntityBase *)>; + // Generic batching mechanism for both state updates and entity info struct DeferredBatch { struct BatchItem { - std::unique_ptr message; - uint16_t message_size; // Pre-calculated message size - uint32_t timestamp; // When this update was queued + EntityBase *entity; // Entity pointer + MessageCreator creator; // Function that creates the message when needed + uint32_t timestamp; // When this update was queued }; std::vector items; @@ -402,7 +506,7 @@ class APIConnection : public APIServerConnection { bool batch_scheduled{false}; // Add item to the batch - void add_item(std::unique_ptr message); + void add_item(EntityBase *entity, MessageCreator creator); void clear() { items.clear(); batch_scheduled = false; @@ -415,7 +519,7 @@ class APIConnection : public APIServerConnection { static constexpr uint32_t BATCH_DELAY_MS = 100; static constexpr size_t MAX_BATCH_SIZE_BYTES = 1360; // MTU - 100 bytes safety margin - void schedule_batch_(); + bool schedule_batch_(); void process_batch_(); };