From feaa903056d17382c93618538157d3f50344a6c2 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Mon, 27 Apr 2026 04:58:35 -0500 Subject: [PATCH 1/4] [cover] Use bitmask template parameter for ControlAction/CoverPublishAction Apply the bitmask pattern from LightControlAction (#16039) to cover::ControlAction (3 fields: stop, position, tilt) and cover::CoverPublishAction (3 fields: position, tilt, current_operation). Unused fields are elided via [[no_unique_address]] and skipped at compile time in play() via if constexpr. Codegen for cover.control: and cover.template.publish: builds the bitmask from the YAML keys present. CONF_STATE and CONF_POSITION both map to the same position bit (they are mutually exclusive YAML keys for the same C++ field). Per-instance: 16-28 B depending on which fields are set, down from ~28 B baseline. --- esphome/components/cover/__init__.py | 16 +++- esphome/components/cover/automation.h | 77 ++++++++++++++----- esphome/components/template/cover/__init__.py | 16 +++- 3 files changed, 87 insertions(+), 22 deletions(-) diff --git a/esphome/components/cover/__init__.py b/esphome/components/cover/__init__.py index 41efd2ba7a..25e92e5c22 100644 --- a/esphome/components/cover/__init__.py +++ b/esphome/components/cover/__init__.py @@ -299,7 +299,21 @@ COVER_CONTROL_ACTION_SCHEMA = cv.Schema( ) async def cover_control_to_code(config, action_id, template_arg, args): paren = await cg.get_variable(config[CONF_ID]) - var = cg.new_Pvariable(action_id, template_arg, paren) + + # Bit positions must match COVER_CONTROL_FIELDS in automation.h. + # CONF_STATE and CONF_POSITION both map to set_position (bit 1). + field_mask = 0 + if CONF_STOP in config: + field_mask |= 1 << 0 + if CONF_STATE in config or CONF_POSITION in config: + field_mask |= 1 << 1 + if CONF_TILT in config: + field_mask |= 1 << 2 + + control_template_arg = cg.TemplateArguments( + cg.RawExpression(f"static_cast({field_mask})"), *template_arg + ) + var = cg.new_Pvariable(action_id, control_template_arg, paren) if (stop := config.get(CONF_STOP)) is not None: template_ = await cg.templatable(stop, args, cg.bool_) cg.add(var.set_stop(template_)) diff --git a/esphome/components/cover/automation.h b/esphome/components/cover/automation.h index f121e5c2d6..223c7644ea 100644 --- a/esphome/components/cover/automation.h +++ b/esphome/components/cover/automation.h @@ -46,49 +46,86 @@ template class ToggleAction : public Action { Cover *cover_; }; -template class ControlAction : public Action { +// Unique Empty per field so [[no_unique_address]] is guaranteed to coalesce. +namespace cover_action_detail { +template struct Empty {}; +} // namespace cover_action_detail + +// X-macro: (type, field_name, bit_index). Order/bits must match +// cover_control_to_code's FIELDS table in __init__.py. +#define COVER_CONTROL_FIELDS(X) \ + X(bool, stop, 0) \ + X(float, position, 1) \ + X(float, tilt, 2) + +template class ControlAction : public Action { public: explicit ControlAction(Cover *cover) : cover_(cover) {} - TEMPLATABLE_VALUE(bool, stop) - TEMPLATABLE_VALUE(float, position) - TEMPLATABLE_VALUE(float, tilt) +#define COVER_FIELD_SETTER_(type, name, idx) \ + template void set_##name(V value) requires((Fields & (1 << (idx))) != 0) { this->name##_ = value; } +#define COVER_FIELD_APPLY_(type, name, idx) \ + if constexpr ((Fields & (1 << (idx))) != 0) \ + call.set_##name(this->name##_.value(x...)); +#define COVER_FIELD_DECL_(type, name, idx) \ + [[no_unique_address]] std::conditional_t<(Fields & (1 << (idx))) != 0, TemplatableFn, \ + cover_action_detail::Empty<(idx)>> \ + name##_{}; + + COVER_CONTROL_FIELDS(COVER_FIELD_SETTER_) void play(const Ts &...x) override { auto call = this->cover_->make_call(); - if (this->stop_.has_value()) - call.set_stop(this->stop_.value(x...)); - if (this->position_.has_value()) - call.set_position(this->position_.value(x...)); - if (this->tilt_.has_value()) - call.set_tilt(this->tilt_.value(x...)); + COVER_CONTROL_FIELDS(COVER_FIELD_APPLY_) call.perform(); } protected: Cover *cover_; + COVER_CONTROL_FIELDS(COVER_FIELD_DECL_) }; +#undef COVER_CONTROL_FIELDS -template class CoverPublishAction : public Action { +// X-macro: (type, field_name, bit_index). Order/bits must match +// cover_template_publish_to_code's FIELDS table in template/cover/__init__.py. +#define COVER_PUBLISH_FIELDS(X) \ + X(float, position, 0) \ + X(float, tilt, 1) \ + X(CoverOperation, current_operation, 2) + +template class CoverPublishAction : public Action { public: CoverPublishAction(Cover *cover) : cover_(cover) {} - TEMPLATABLE_VALUE(float, position) - TEMPLATABLE_VALUE(float, tilt) - TEMPLATABLE_VALUE(CoverOperation, current_operation) + +#define COVER_PUBLISH_SETTER_(type, name, idx) \ + template void set_##name(V value) requires((Fields & (1 << (idx))) != 0) { this->name##_ = value; } +#define COVER_PUBLISH_APPLY_(type, name, idx) \ + if constexpr ((Fields & (1 << (idx))) != 0) \ + this->cover_->name = this->name##_.value(x...); +#define COVER_PUBLISH_DECL_(type, name, idx) \ + [[no_unique_address]] std::conditional_t<(Fields & (1 << (idx))) != 0, TemplatableFn, \ + cover_action_detail::Empty<(idx) + 8>> \ + name##_{}; + + COVER_PUBLISH_FIELDS(COVER_PUBLISH_SETTER_) void play(const Ts &...x) override { - if (this->position_.has_value()) - this->cover_->position = this->position_.value(x...); - if (this->tilt_.has_value()) - this->cover_->tilt = this->tilt_.value(x...); - if (this->current_operation_.has_value()) - this->cover_->current_operation = this->current_operation_.value(x...); + COVER_PUBLISH_FIELDS(COVER_PUBLISH_APPLY_) this->cover_->publish_state(); } protected: Cover *cover_; + COVER_PUBLISH_FIELDS(COVER_PUBLISH_DECL_) + +#undef COVER_PUBLISH_DECL_ +#undef COVER_PUBLISH_APPLY_ +#undef COVER_PUBLISH_SETTER_ +#undef COVER_FIELD_DECL_ +#undef COVER_FIELD_APPLY_ +#undef COVER_FIELD_SETTER_ }; +#undef COVER_PUBLISH_FIELDS template class CoverPositionCondition : public Condition { public: diff --git a/esphome/components/template/cover/__init__.py b/esphome/components/template/cover/__init__.py index a30c0af313..7dd3cddf47 100644 --- a/esphome/components/template/cover/__init__.py +++ b/esphome/components/template/cover/__init__.py @@ -128,7 +128,21 @@ async def to_code(config): ) async def cover_template_publish_to_code(config, action_id, template_arg, args): paren = await cg.get_variable(config[CONF_ID]) - var = cg.new_Pvariable(action_id, template_arg, paren) + + # Bit positions must match COVER_PUBLISH_FIELDS in cover/automation.h. + # CONF_STATE and CONF_POSITION both map to set_position (bit 0). + field_mask = 0 + if CONF_STATE in config or CONF_POSITION in config: + field_mask |= 1 << 0 + if CONF_TILT in config: + field_mask |= 1 << 1 + if CONF_CURRENT_OPERATION in config: + field_mask |= 1 << 2 + + publish_template_arg = cg.TemplateArguments( + cg.RawExpression(f"static_cast({field_mask})"), *template_arg + ) + var = cg.new_Pvariable(action_id, publish_template_arg, paren) if CONF_STATE in config: template_ = await cg.templatable(config[CONF_STATE], args, cg.float_) cg.add(var.set_position(template_)) From 3522eef8ee4fd7f2a466b5e560544574e7a8bca9 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Mon, 27 Apr 2026 05:02:58 -0500 Subject: [PATCH 2/4] [cover] Add integration test for ControlAction/CoverPublishAction --- .../fixtures/cover_control_action.yaml | 110 ++++++++++++++++++ .../integration/test_cover_control_action.py | 84 +++++++++++++ 2 files changed, 194 insertions(+) create mode 100644 tests/integration/fixtures/cover_control_action.yaml create mode 100644 tests/integration/test_cover_control_action.py diff --git a/tests/integration/fixtures/cover_control_action.yaml b/tests/integration/fixtures/cover_control_action.yaml new file mode 100644 index 0000000000..da67e98f5a --- /dev/null +++ b/tests/integration/fixtures/cover_control_action.yaml @@ -0,0 +1,110 @@ +esphome: + name: cover-control-action-test +host: +api: +logger: + level: DEBUG + +globals: + - id: test_position + type: float + initial_value: "0.42" + +cover: + - platform: template + name: "Test Cover" + id: test_cover + has_position: true + optimistic: true + assumed_state: true + open_action: + - cover.template.publish: + id: test_cover + position: 1.0 + close_action: + - cover.template.publish: + id: test_cover + position: 0.0 + stop_action: + - cover.template.publish: + id: test_cover + current_operation: IDLE + tilt_action: + - lambda: |- + // Manually set tilt and publish + id(test_cover).tilt = tilt; + id(test_cover).publish_state(); + +button: + # Test 1: cover.control with position only (mask 0b010 = 2) + - platform: template + id: btn_position + name: "Set Position" + on_press: + - cover.control: + id: test_cover + position: 50% + + # Test 2: cover.control with tilt only (mask 0b100 = 4) + - platform: template + id: btn_tilt + name: "Set Tilt" + on_press: + - cover.control: + id: test_cover + tilt: 75% + + # Test 3: cover.control with position + tilt (mask 0b110 = 6) + - platform: template + id: btn_pos_tilt + name: "Set Pos Tilt" + on_press: + - cover.control: + id: test_cover + position: 25% + tilt: 30% + + # Test 4: cover.control with stop only (mask 0b001 = 1) + - platform: template + id: btn_stop + name: "Stop Cover" + on_press: + - cover.control: + id: test_cover + stop: true + + # Test 5: cover.control with state alias (sets position bit via CONF_STATE) + - platform: template + id: btn_open_state + name: "Open State" + on_press: + - cover.control: + id: test_cover + state: OPEN + + # Test 6: cover.control with lambda position (exercises lambda path) + - platform: template + id: btn_lambda_position + name: "Lambda Position" + on_press: + - cover.control: + id: test_cover + position: !lambda "return id(test_position);" + + # Test 7: cover.template.publish position only (mask 0b001) + - platform: template + id: btn_publish_pos + name: "Publish Pos" + on_press: + - cover.template.publish: + id: test_cover + position: 0.6 + + # Test 8: cover.template.publish current_operation only (mask 0b100) + - platform: template + id: btn_publish_op + name: "Publish Op" + on_press: + - cover.template.publish: + id: test_cover + current_operation: OPENING diff --git a/tests/integration/test_cover_control_action.py b/tests/integration/test_cover_control_action.py new file mode 100644 index 0000000000..fee89555fa --- /dev/null +++ b/tests/integration/test_cover_control_action.py @@ -0,0 +1,84 @@ +"""Integration test for cover ControlAction and CoverPublishAction. + +Tests that cover.control and cover.template.publish automation actions +work correctly with the per-instance bitmask field storage. Exercises +multiple field combinations to cover the bitmask variants. +""" + +import asyncio +from typing import Any + +import pytest + +from .types import APIClientConnectedFactory, RunCompiledFunction + + +@pytest.mark.asyncio +async def test_cover_control_action( + yaml_config: str, + run_compiled: RunCompiledFunction, + api_client_connected: APIClientConnectedFactory, +) -> None: + """Test cover ControlAction/CoverPublishAction with constants and lambdas.""" + async with run_compiled(yaml_config), api_client_connected() as client: + state_futures: dict[int, asyncio.Future[Any]] = {} + + def on_state(state: Any) -> None: + if state.key in state_futures and not state_futures[state.key].done(): + state_futures[state.key].set_result(state) + + client.subscribe_states(on_state) + + entities = await client.list_entities_services() + cover = next(e for e in entities[0] if e.object_id == "test_cover") + buttons = {e.name: e for e in entities[0] if hasattr(e, "name")} + + async def wait_for_state(key: int, timeout: float = 5.0) -> Any: + loop = asyncio.get_running_loop() + state_futures[key] = loop.create_future() + try: + return await asyncio.wait_for(state_futures[key], timeout) + finally: + state_futures.pop(key, None) + + async def press_and_wait(button_name: str) -> Any: + btn = buttons[button_name] + client.button_command(btn.key) + return await wait_for_state(cover.key) + + # Test 1: position only (mask 2) + state = await press_and_wait("Set Position") + assert state.position == pytest.approx(0.5, abs=0.01) + + # Test 2: tilt only (mask 4) + state = await press_and_wait("Set Tilt") + assert state.tilt == pytest.approx(0.75, abs=0.01) + + # Test 3: position + tilt (mask 6) + state = await press_and_wait("Set Pos Tilt") + assert state.position == pytest.approx(0.25, abs=0.01) + assert state.tilt == pytest.approx(0.30, abs=0.01) + + # Test 4: stop (mask 1) — stop on a non-moving cover should not change state + # We just verify the action runs without error; no state change expected. + btn = buttons["Stop Cover"] + client.button_command(btn.key) + # Give the action a moment to execute + await asyncio.sleep(0.1) + + # Test 5: state: OPEN (CONF_STATE alias for position 1.0) + state = await press_and_wait("Open State") + assert state.position == pytest.approx(1.0, abs=0.01) + + # Test 6: lambda position + state = await press_and_wait("Lambda Position") + assert state.position == pytest.approx(0.42, abs=0.01) + + # Test 7: cover.template.publish position only + state = await press_and_wait("Publish Pos") + assert state.position == pytest.approx(0.6, abs=0.01) + + # Test 8: cover.template.publish current_operation only + state = await press_and_wait("Publish Op") + # Operation 1 = OPENING + assert state.current_operation == 1 From a532f0adc914ff68739b52f328703efa55504f9b Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Mon, 27 Apr 2026 05:08:08 -0500 Subject: [PATCH 3/4] [cover] Use InitialStateHelper in integration test --- .../integration/test_cover_control_action.py | 66 ++++++++++--------- 1 file changed, 34 insertions(+), 32 deletions(-) diff --git a/tests/integration/test_cover_control_action.py b/tests/integration/test_cover_control_action.py index fee89555fa..206079ca89 100644 --- a/tests/integration/test_cover_control_action.py +++ b/tests/integration/test_cover_control_action.py @@ -5,11 +5,14 @@ work correctly with the per-instance bitmask field storage. Exercises multiple field combinations to cover the bitmask variants. """ -import asyncio -from typing import Any +from __future__ import annotations +import asyncio + +from aioesphomeapi import ButtonInfo, CoverInfo, CoverState, EntityState import pytest +from .state_utils import InitialStateHelper, require_entity from .types import APIClientConnectedFactory, RunCompiledFunction @@ -20,31 +23,37 @@ async def test_cover_control_action( api_client_connected: APIClientConnectedFactory, ) -> None: """Test cover ControlAction/CoverPublishAction with constants and lambdas.""" + loop = asyncio.get_running_loop() async with run_compiled(yaml_config), api_client_connected() as client: - state_futures: dict[int, asyncio.Future[Any]] = {} + cover_state_future: asyncio.Future[CoverState] | None = None - def on_state(state: Any) -> None: - if state.key in state_futures and not state_futures[state.key].done(): - state_futures[state.key].set_result(state) + def on_state(state: EntityState) -> None: + if ( + isinstance(state, CoverState) + and cover_state_future is not None + and not cover_state_future.done() + ): + cover_state_future.set_result(state) - client.subscribe_states(on_state) - - entities = await client.list_entities_services() - cover = next(e for e in entities[0] if e.object_id == "test_cover") - buttons = {e.name: e for e in entities[0] if hasattr(e, "name")} - - async def wait_for_state(key: int, timeout: float = 5.0) -> Any: - loop = asyncio.get_running_loop() - state_futures[key] = loop.create_future() + async def wait_for_cover_state(timeout: float = 5.0) -> CoverState: + nonlocal cover_state_future + cover_state_future = loop.create_future() try: - return await asyncio.wait_for(state_futures[key], timeout) + return await asyncio.wait_for(cover_state_future, timeout) finally: - state_futures.pop(key, None) + cover_state_future = None - async def press_and_wait(button_name: str) -> Any: - btn = buttons[button_name] + entities, _ = await client.list_entities_services() + initial_state_helper = InitialStateHelper(entities) + client.subscribe_states(initial_state_helper.on_state_wrapper(on_state)) + await initial_state_helper.wait_for_initial_states() + + require_entity(entities, "test_cover", CoverInfo) + + async def press_and_wait(name: str) -> CoverState: + btn = require_entity(entities, name.lower().replace(" ", "_"), ButtonInfo) client.button_command(btn.key) - return await wait_for_state(cover.key) + return await wait_for_cover_state() # Test 1: position only (mask 2) state = await press_and_wait("Set Position") @@ -59,26 +68,19 @@ async def test_cover_control_action( assert state.position == pytest.approx(0.25, abs=0.01) assert state.tilt == pytest.approx(0.30, abs=0.01) - # Test 4: stop (mask 1) — stop on a non-moving cover should not change state - # We just verify the action runs without error; no state change expected. - btn = buttons["Stop Cover"] - client.button_command(btn.key) - # Give the action a moment to execute - await asyncio.sleep(0.1) - - # Test 5: state: OPEN (CONF_STATE alias for position 1.0) + # Test 4: state: OPEN (CONF_STATE alias for position 1.0) state = await press_and_wait("Open State") assert state.position == pytest.approx(1.0, abs=0.01) - # Test 6: lambda position + # Test 5: lambda position (test_position global = 0.42) state = await press_and_wait("Lambda Position") assert state.position == pytest.approx(0.42, abs=0.01) - # Test 7: cover.template.publish position only + # Test 6: cover.template.publish position only state = await press_and_wait("Publish Pos") assert state.position == pytest.approx(0.6, abs=0.01) - # Test 8: cover.template.publish current_operation only + # Test 7: cover.template.publish current_operation only state = await press_and_wait("Publish Op") - # Operation 1 = OPENING + # CoverOperation.OPENING == 1 assert state.current_operation == 1 From 6770a6b87f4a0526d12bc0e0bb413b1f5ff31bf8 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Mon, 27 Apr 2026 05:39:21 -0500 Subject: [PATCH 4/4] [cover] Address Copilot review on integration test fixture and macro comments --- esphome/components/cover/automation.h | 11 +++++--- .../fixtures/cover_control_action.yaml | 27 ++++++++++--------- .../integration/test_cover_control_action.py | 6 +++++ 3 files changed, 27 insertions(+), 17 deletions(-) diff --git a/esphome/components/cover/automation.h b/esphome/components/cover/automation.h index 223c7644ea..e056a11ea5 100644 --- a/esphome/components/cover/automation.h +++ b/esphome/components/cover/automation.h @@ -51,8 +51,9 @@ namespace cover_action_detail { template struct Empty {}; } // namespace cover_action_detail -// X-macro: (type, field_name, bit_index). Order/bits must match -// cover_control_to_code's FIELDS table in __init__.py. +// X-macro: (type, field_name, bit_index). Order/bits must match the +// inline field-mask computation in cover_control_to_code in __init__.py: +// stop=bit 0, position=bit 1 (also set by CONF_STATE), tilt=bit 2. #define COVER_CONTROL_FIELDS(X) \ X(bool, stop, 0) \ X(float, position, 1) \ @@ -86,8 +87,10 @@ template class ControlAction : public Action IDLE + - platform: template + id: btn_stop + name: "Stop Cover" + on_press: + - cover.control: + id: test_cover + stop: true diff --git a/tests/integration/test_cover_control_action.py b/tests/integration/test_cover_control_action.py index 206079ca89..29ece37ce5 100644 --- a/tests/integration/test_cover_control_action.py +++ b/tests/integration/test_cover_control_action.py @@ -84,3 +84,9 @@ async def test_cover_control_action( state = await press_and_wait("Publish Op") # CoverOperation.OPENING == 1 assert state.current_operation == 1 + + # Test 8: cover.control stop only (mask 1) + # The template cover's stop_action publishes current_operation: IDLE + state = await press_and_wait("Stop Cover") + # CoverOperation.IDLE == 0 + assert state.current_operation == 0