From d0f4e89ef3a97e93e2ca20b307ddb0e356238280 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Wed, 29 Apr 2026 06:37:52 -0500 Subject: [PATCH 1/5] [cover] Fold ControlAction/CoverPublishAction fields into stateless lambdas --- esphome/components/cover/__init__.py | 57 +++++++------- esphome/components/cover/automation.h | 77 ++++--------------- esphome/components/template/cover/__init__.py | 58 +++++++------- 3 files changed, 77 insertions(+), 115 deletions(-) diff --git a/esphome/components/cover/__init__.py b/esphome/components/cover/__init__.py index 25e92e5c229..30d3e23bf6f 100644 --- a/esphome/components/cover/__init__.py +++ b/esphome/components/cover/__init__.py @@ -36,14 +36,14 @@ from esphome.const import ( DEVICE_CLASS_SHUTTER, DEVICE_CLASS_WINDOW, ) -from esphome.core import CORE, ID, CoroPriority, coroutine_with_priority +from esphome.core import CORE, ID, CoroPriority, Lambda, coroutine_with_priority from esphome.core.entity_helpers import ( entity_duplicate_validator, queue_entity_register, setup_device_class, setup_entity, ) -from esphome.cpp_generator import MockObj, MockObjClass +from esphome.cpp_generator import LambdaExpression, MockObj, MockObjClass from esphome.types import ConfigType, TemplateArgsType IS_PLATFORM_COMPONENT = True @@ -68,6 +68,7 @@ _LOGGER = logging.getLogger(__name__) cover_ns = cg.esphome_ns.namespace("cover") Cover = cover_ns.class_("Cover", cg.EntityBase) +CoverCall = cover_ns.class_("CoverCall") COVER_OPEN = cover_ns.COVER_OPEN COVER_CLOSED = cover_ns.COVER_CLOSED @@ -300,33 +301,35 @@ 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]) - # 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) + # All configured fields are folded into a single stateless lambda whose + # constants live in flash; the action stores only a function pointer. + # CONF_STATE and CONF_POSITION are mutually exclusive in the schema and + # both map to set_position. + fields: list[tuple[object, str, object]] = [] if (stop := config.get(CONF_STOP)) is not None: - template_ = await cg.templatable(stop, args, cg.bool_) - cg.add(var.set_stop(template_)) - if (state := config.get(CONF_STATE)) is not None: - template_ = await cg.templatable(state, args, cg.float_) - cg.add(var.set_position(template_)) - if (position := config.get(CONF_POSITION)) is not None: - template_ = await cg.templatable(position, args, cg.float_) - cg.add(var.set_position(template_)) + fields.append((stop, "set_stop", cg.bool_)) + if (position := config.get(CONF_STATE, config.get(CONF_POSITION))) is not None: + fields.append((position, "set_position", cg.float_)) if (tilt := config.get(CONF_TILT)) is not None: - template_ = await cg.templatable(tilt, args, cg.float_) - cg.add(var.set_tilt(template_)) - return var + fields.append((tilt, "set_tilt", cg.float_)) + + fwd_args = ", ".join(name for _, name in args) + body_lines: list[str] = [] + for value, setter, type_ in fields: + if isinstance(value, Lambda): + inner = await cg.process_lambda(value, args, return_type=type_) + body_lines.append(f"call.{setter}(({inner})({fwd_args}));") + else: + body_lines.append(f"call.{setter}({cg.safe_exp(value)});") + + apply_args = [(CoverCall.operator("ref"), "call"), *args] + apply_lambda = LambdaExpression( + ["\n".join(body_lines)], + apply_args, + capture="", + return_type=cg.void, + ) + return cg.new_Pvariable(action_id, template_arg, paren, apply_lambda) COVER_CONDITION_SCHEMA = cv.maybe_simple_value( diff --git a/esphome/components/cover/automation.h b/esphome/components/cover/automation.h index e056a11ea54..42ca8921428 100644 --- a/esphome/components/cover/automation.h +++ b/esphome/components/cover/automation.h @@ -46,89 +46,42 @@ template class ToggleAction : public Action { Cover *cover_; }; -// Unique Empty per field so [[no_unique_address]] is guaranteed to coalesce. -namespace cover_action_detail { -template struct Empty {}; -} // namespace cover_action_detail +// All configured fields are baked into a single stateless lambda whose +// constants live in flash. Each action stores only a function pointer +// (4 bytes) plus the parent (4 bytes), regardless of how many fields the +// user set. Trigger args are forwarded to the apply function so user +// lambdas (e.g. `position: !lambda "return x;"`) keep working. -// 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) \ - X(float, tilt, 2) - -template class ControlAction : public Action { +template class ControlAction : public Action { public: - explicit ControlAction(Cover *cover) : cover_(cover) {} - -#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_) + using ApplyFn = void (*)(CoverCall &, Ts...); + ControlAction(Cover *cover, ApplyFn apply) : cover_(cover), apply_(apply) {} void play(const Ts &...x) override { auto call = this->cover_->make_call(); - COVER_CONTROL_FIELDS(COVER_FIELD_APPLY_) + this->apply_(call, x...); call.perform(); } protected: Cover *cover_; - COVER_CONTROL_FIELDS(COVER_FIELD_DECL_) + ApplyFn apply_; }; -#undef COVER_CONTROL_FIELDS -// X-macro: (type, field_name, bit_index). Order/bits must match the -// inline bitmask built in cover_template_publish_to_code in -// template/cover/__init__.py: position=bit 0 (also set by CONF_STATE), -// tilt=bit 1, current_operation=bit 2. -#define COVER_PUBLISH_FIELDS(X) \ - X(float, position, 0) \ - X(float, tilt, 1) \ - X(CoverOperation, current_operation, 2) - -template class CoverPublishAction : public Action { +template class CoverPublishAction : public Action { public: - CoverPublishAction(Cover *cover) : cover_(cover) {} - -#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_) + using ApplyFn = void (*)(Cover *, Ts...); + CoverPublishAction(Cover *cover, ApplyFn apply) : cover_(cover), apply_(apply) {} void play(const Ts &...x) override { - COVER_PUBLISH_FIELDS(COVER_PUBLISH_APPLY_) + this->apply_(this->cover_, x...); 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_ + ApplyFn apply_; }; -#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 7dd3cddf473..8b39dc5b631 100644 --- a/esphome/components/template/cover/__init__.py +++ b/esphome/components/template/cover/__init__.py @@ -19,6 +19,8 @@ from esphome.const import ( CONF_TILT_ACTION, CONF_TILT_LAMBDA, ) +from esphome.core import Lambda +from esphome.cpp_generator import LambdaExpression from .. import template_ns @@ -129,32 +131,36 @@ 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]) - # 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 + # All configured fields are folded into a single stateless lambda whose + # constants live in flash; the action stores only a function pointer. + # The lambda mutates Cover fields directly (no CoverCall) since publish + # is a state push, not a control request. + # CONF_STATE and CONF_POSITION both map to position. + fields: list[tuple[object, str, object]] = [] + position_value = config.get(CONF_STATE, config.get(CONF_POSITION)) + if position_value is not None: + fields.append((position_value, "position", cg.float_)) if CONF_TILT in config: - field_mask |= 1 << 1 + fields.append((config[CONF_TILT], "tilt", cg.float_)) 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_)) - if CONF_POSITION in config: - template_ = await cg.templatable(config[CONF_POSITION], args, cg.float_) - cg.add(var.set_position(template_)) - if CONF_TILT in config: - template_ = await cg.templatable(config[CONF_TILT], args, cg.float_) - cg.add(var.set_tilt(template_)) - if CONF_CURRENT_OPERATION in config: - template_ = await cg.templatable( - config[CONF_CURRENT_OPERATION], args, cover.CoverOperation + fields.append( + (config[CONF_CURRENT_OPERATION], "current_operation", cover.CoverOperation) ) - cg.add(var.set_current_operation(template_)) - return var + + fwd_args = ", ".join(name for _, name in args) + body_lines: list[str] = [] + for value, field, type_ in fields: + if isinstance(value, Lambda): + inner = await cg.process_lambda(value, args, return_type=type_) + body_lines.append(f"cover->{field} = ({inner})({fwd_args});") + else: + body_lines.append(f"cover->{field} = {cg.safe_exp(value)};") + + apply_args = [(cover.Cover.operator("ptr"), "cover"), *args] + apply_lambda = LambdaExpression( + ["\n".join(body_lines)], + apply_args, + capture="", + return_type=cg.void, + ) + return cg.new_Pvariable(action_id, template_arg, paren, apply_lambda) From 22a70e3139da695c98bec86f0b87cc3641011c6b Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Wed, 29 Apr 2026 06:40:09 -0500 Subject: [PATCH 2/5] [cover] Use FIELDS table to match light/climate codegen pattern --- esphome/components/cover/__init__.py | 21 +++++++++-------- esphome/components/template/cover/__init__.py | 23 +++++++++---------- 2 files changed, 22 insertions(+), 22 deletions(-) diff --git a/esphome/components/cover/__init__.py b/esphome/components/cover/__init__.py index 30d3e23bf6f..9d5b6ad49ce 100644 --- a/esphome/components/cover/__init__.py +++ b/esphome/components/cover/__init__.py @@ -303,19 +303,20 @@ async def cover_control_to_code(config, action_id, template_arg, args): # All configured fields are folded into a single stateless lambda whose # constants live in flash; the action stores only a function pointer. - # CONF_STATE and CONF_POSITION are mutually exclusive in the schema and - # both map to set_position. - fields: list[tuple[object, str, object]] = [] - if (stop := config.get(CONF_STOP)) is not None: - fields.append((stop, "set_stop", cg.bool_)) - if (position := config.get(CONF_STATE, config.get(CONF_POSITION))) is not None: - fields.append((position, "set_position", cg.float_)) - if (tilt := config.get(CONF_TILT)) is not None: - fields.append((tilt, "set_tilt", cg.float_)) + # CONF_STATE and CONF_POSITION are cv.Exclusive in the schema, so at most + # one is present and both dispatch to set_position. + FIELDS = ( + (CONF_STOP, "set_stop", cg.bool_), + (CONF_STATE, "set_position", cg.float_), + (CONF_POSITION, "set_position", cg.float_), + (CONF_TILT, "set_tilt", cg.float_), + ) fwd_args = ", ".join(name for _, name in args) body_lines: list[str] = [] - for value, setter, type_ in fields: + for conf_key, setter, type_ in FIELDS: + if (value := config.get(conf_key)) is None: + continue if isinstance(value, Lambda): inner = await cg.process_lambda(value, args, return_type=type_) body_lines.append(f"call.{setter}(({inner})({fwd_args}));") diff --git a/esphome/components/template/cover/__init__.py b/esphome/components/template/cover/__init__.py index 8b39dc5b631..1af003d75d6 100644 --- a/esphome/components/template/cover/__init__.py +++ b/esphome/components/template/cover/__init__.py @@ -135,21 +135,20 @@ async def cover_template_publish_to_code(config, action_id, template_arg, args): # constants live in flash; the action stores only a function pointer. # The lambda mutates Cover fields directly (no CoverCall) since publish # is a state push, not a control request. - # CONF_STATE and CONF_POSITION both map to position. - fields: list[tuple[object, str, object]] = [] - position_value = config.get(CONF_STATE, config.get(CONF_POSITION)) - if position_value is not None: - fields.append((position_value, "position", cg.float_)) - if CONF_TILT in config: - fields.append((config[CONF_TILT], "tilt", cg.float_)) - if CONF_CURRENT_OPERATION in config: - fields.append( - (config[CONF_CURRENT_OPERATION], "current_operation", cover.CoverOperation) - ) + # CONF_STATE and CONF_POSITION are cv.Exclusive in the schema, so at most + # one is present and both map to the position field. + FIELDS = ( + (CONF_STATE, "position", cg.float_), + (CONF_POSITION, "position", cg.float_), + (CONF_TILT, "tilt", cg.float_), + (CONF_CURRENT_OPERATION, "current_operation", cover.CoverOperation), + ) fwd_args = ", ".join(name for _, name in args) body_lines: list[str] = [] - for value, field, type_ in fields: + for conf_key, field, type_ in FIELDS: + if (value := config.get(conf_key)) is None: + continue if isinstance(value, Lambda): inner = await cg.process_lambda(value, args, return_type=type_) body_lines.append(f"cover->{field} = ({inner})({fwd_args});") From f7c8df823458f693c2452a33cb66344e53d049a7 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Wed, 29 Apr 2026 06:56:18 -0500 Subject: [PATCH 3/5] [cover] Address review feedback (const ref args, drop mask numbering) --- esphome/components/cover/__init__.py | 6 ++++- esphome/components/cover/automation.h | 12 +++++----- esphome/components/template/cover/__init__.py | 6 ++++- .../fixtures/cover_control_action.yaml | 18 +++++++-------- .../integration/test_cover_control_action.py | 22 +++++++++---------- 5 files changed, 36 insertions(+), 28 deletions(-) diff --git a/esphome/components/cover/__init__.py b/esphome/components/cover/__init__.py index 9d5b6ad49ce..5a27ceb8fa5 100644 --- a/esphome/components/cover/__init__.py +++ b/esphome/components/cover/__init__.py @@ -323,7 +323,11 @@ async def cover_control_to_code(config, action_id, template_arg, args): else: body_lines.append(f"call.{setter}({cg.safe_exp(value)});") - apply_args = [(CoverCall.operator("ref"), "call"), *args] + # Match ControlAction::ApplyFn signature: const Ts &... for trigger args. + apply_args = [ + (CoverCall.operator("ref"), "call"), + *((t.operator("const").operator("ref"), n) for t, n in args), + ] apply_lambda = LambdaExpression( ["\n".join(body_lines)], apply_args, diff --git a/esphome/components/cover/automation.h b/esphome/components/cover/automation.h index 42ca8921428..e2384c23593 100644 --- a/esphome/components/cover/automation.h +++ b/esphome/components/cover/automation.h @@ -47,14 +47,14 @@ template class ToggleAction : public Action { }; // All configured fields are baked into a single stateless lambda whose -// constants live in flash. Each action stores only a function pointer -// (4 bytes) plus the parent (4 bytes), regardless of how many fields the -// user set. Trigger args are forwarded to the apply function so user -// lambdas (e.g. `position: !lambda "return x;"`) keep working. +// constants live in flash. Each action stores only one function pointer +// plus one parent pointer, regardless of how many fields the user set. +// Trigger args are forwarded to the apply function so user lambdas +// (e.g. `position: !lambda "return x;"`) keep working. template class ControlAction : public Action { public: - using ApplyFn = void (*)(CoverCall &, Ts...); + using ApplyFn = void (*)(CoverCall &, const Ts &...); ControlAction(Cover *cover, ApplyFn apply) : cover_(cover), apply_(apply) {} void play(const Ts &...x) override { @@ -70,7 +70,7 @@ template class ControlAction : public Action { template class CoverPublishAction : public Action { public: - using ApplyFn = void (*)(Cover *, Ts...); + using ApplyFn = void (*)(Cover *, const Ts &...); CoverPublishAction(Cover *cover, ApplyFn apply) : cover_(cover), apply_(apply) {} void play(const Ts &...x) override { diff --git a/esphome/components/template/cover/__init__.py b/esphome/components/template/cover/__init__.py index 1af003d75d6..bcf0c54c7f7 100644 --- a/esphome/components/template/cover/__init__.py +++ b/esphome/components/template/cover/__init__.py @@ -155,7 +155,11 @@ async def cover_template_publish_to_code(config, action_id, template_arg, args): else: body_lines.append(f"cover->{field} = {cg.safe_exp(value)};") - apply_args = [(cover.Cover.operator("ptr"), "cover"), *args] + # Match CoverPublishAction::ApplyFn: const Ts &... for trigger args. + apply_args = [ + (cover.Cover.operator("ptr"), "cover"), + *((t.operator("const").operator("ref"), n) for t, n in args), + ] apply_lambda = LambdaExpression( ["\n".join(body_lines)], apply_args, diff --git a/tests/integration/fixtures/cover_control_action.yaml b/tests/integration/fixtures/cover_control_action.yaml index f9eaa2ceee7..085d6327963 100644 --- a/tests/integration/fixtures/cover_control_action.yaml +++ b/tests/integration/fixtures/cover_control_action.yaml @@ -36,7 +36,7 @@ cover: id(test_cover).publish_state(); button: - # Test 1: cover.control with position only (mask 0b010 = 2) + # cover.control: position only - platform: template id: btn_position name: "Set Position" @@ -45,7 +45,7 @@ button: id: test_cover position: 50% - # Test 2: cover.control with tilt only (mask 0b100 = 4) + # cover.control: tilt only - platform: template id: btn_tilt name: "Set Tilt" @@ -54,7 +54,7 @@ button: id: test_cover tilt: 75% - # Test 3: cover.control with position + tilt (mask 0b110 = 6) + # cover.control: position + tilt - platform: template id: btn_pos_tilt name: "Set Pos Tilt" @@ -64,7 +64,7 @@ button: position: 25% tilt: 30% - # Test 4: cover.control with state alias (sets position bit via CONF_STATE) + # cover.control: state alias for position - platform: template id: btn_open_state name: "Open State" @@ -73,7 +73,7 @@ button: id: test_cover state: OPEN - # Test 5: cover.control with lambda position (exercises lambda path) + # cover.control: lambda position (exercises lambda path) - platform: template id: btn_lambda_position name: "Lambda Position" @@ -82,7 +82,7 @@ button: id: test_cover position: !lambda "return id(test_position);" - # Test 6: cover.template.publish position only (mask 0b001) + # cover.template.publish: position only - platform: template id: btn_publish_pos name: "Publish Pos" @@ -91,7 +91,7 @@ button: id: test_cover position: 0.6 - # Test 7: cover.template.publish current_operation only (mask 0b100) + # cover.template.publish: current_operation only - platform: template id: btn_publish_op name: "Publish Op" @@ -100,8 +100,8 @@ button: id: test_cover current_operation: OPENING - # Test 8: cover.control with stop only (mask 0b001 = 1) — runs after - # Publish Op so we can verify current_operation transitions OPENING -> IDLE + # cover.control: stop only — runs after Publish Op so the test can + # verify current_operation transitions OPENING -> IDLE. - platform: template id: btn_stop name: "Stop Cover" diff --git a/tests/integration/test_cover_control_action.py b/tests/integration/test_cover_control_action.py index 29ece37ce51..9c7395371bb 100644 --- a/tests/integration/test_cover_control_action.py +++ b/tests/integration/test_cover_control_action.py @@ -1,8 +1,8 @@ """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. +work correctly with the single stateless apply lambda/function pointer +implementation. Exercises multiple field combinations and the lambda path. """ from __future__ import annotations @@ -55,38 +55,38 @@ async def test_cover_control_action( client.button_command(btn.key) return await wait_for_cover_state() - # Test 1: position only (mask 2) + # cover.control: position only state = await press_and_wait("Set Position") assert state.position == pytest.approx(0.5, abs=0.01) - # Test 2: tilt only (mask 4) + # cover.control: tilt only state = await press_and_wait("Set Tilt") assert state.tilt == pytest.approx(0.75, abs=0.01) - # Test 3: position + tilt (mask 6) + # cover.control: position + tilt 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: state: OPEN (CONF_STATE alias for position 1.0) + # cover.control: state alias for position 1.0 state = await press_and_wait("Open State") assert state.position == pytest.approx(1.0, abs=0.01) - # Test 5: lambda position (test_position global = 0.42) + # cover.control: 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 6: cover.template.publish position only + # cover.template.publish: position only state = await press_and_wait("Publish Pos") assert state.position == pytest.approx(0.6, abs=0.01) - # Test 7: cover.template.publish current_operation only + # cover.template.publish: current_operation only 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 + # cover.control: stop only — template cover's stop_action publishes + # current_operation: IDLE. state = await press_and_wait("Stop Cover") # CoverOperation.IDLE == 0 assert state.current_operation == 0 From 964cfaa73099120f1f4522599cf68a36a476a394 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Wed, 29 Apr 2026 07:06:55 -0500 Subject: [PATCH 4/5] [cover] Extract build_apply_lambda_action helper, add typing, use kwargs --- esphome/components/cover/__init__.py | 73 +++++++++++++------ esphome/components/template/cover/__init__.py | 69 ++++++++---------- 2 files changed, 81 insertions(+), 61 deletions(-) diff --git a/esphome/components/cover/__init__.py b/esphome/components/cover/__init__.py index 5a27ceb8fa5..e6a3c29c1de 100644 --- a/esphome/components/cover/__init__.py +++ b/esphome/components/cover/__init__.py @@ -295,37 +295,38 @@ COVER_CONTROL_ACTION_SCHEMA = cv.Schema( ) -@automation.register_action( - "cover.control", ControlAction, COVER_CONTROL_ACTION_SCHEMA, synchronous=True -) -async def cover_control_to_code(config, action_id, template_arg, args): +async def build_apply_lambda_action( + config: ConfigType, + action_id: ID, + template_arg: cg.TemplateArguments, + args: TemplateArgsType, + fields: tuple[tuple[str, str, object], ...], + prefix_args: list[tuple[object, str]], + statement_fn, +) -> MockObj: + """Fold configured fields into a single stateless apply lambda action. + + Used by both `cover.control` and `cover.template.publish` (and shared + with the template/cover platform). Constants are emitted as flash + immediates; user lambdas are invoked inline so trigger args still flow. + The trigger arg types are wrapped as `const T &` to match the + `void (*)(..., const Ts &...)` ApplyFn signature. + """ paren = await cg.get_variable(config[CONF_ID]) - - # All configured fields are folded into a single stateless lambda whose - # constants live in flash; the action stores only a function pointer. - # CONF_STATE and CONF_POSITION are cv.Exclusive in the schema, so at most - # one is present and both dispatch to set_position. - FIELDS = ( - (CONF_STOP, "set_stop", cg.bool_), - (CONF_STATE, "set_position", cg.float_), - (CONF_POSITION, "set_position", cg.float_), - (CONF_TILT, "set_tilt", cg.float_), - ) - fwd_args = ", ".join(name for _, name in args) body_lines: list[str] = [] - for conf_key, setter, type_ in FIELDS: + for conf_key, target, type_ in fields: if (value := config.get(conf_key)) is None: continue if isinstance(value, Lambda): inner = await cg.process_lambda(value, args, return_type=type_) - body_lines.append(f"call.{setter}(({inner})({fwd_args}));") + value_expr = f"({inner})({fwd_args})" else: - body_lines.append(f"call.{setter}({cg.safe_exp(value)});") + value_expr = str(cg.safe_exp(value)) + body_lines.append(statement_fn(target, value_expr)) - # Match ControlAction::ApplyFn signature: const Ts &... for trigger args. apply_args = [ - (CoverCall.operator("ref"), "call"), + *prefix_args, *((t.operator("const").operator("ref"), n) for t, n in args), ] apply_lambda = LambdaExpression( @@ -337,6 +338,36 @@ async def cover_control_to_code(config, action_id, template_arg, args): return cg.new_Pvariable(action_id, template_arg, paren, apply_lambda) +# CONF_STATE and CONF_POSITION are cv.Exclusive in the schema, so at most +# one is present and both dispatch to set_position. +_COVER_CONTROL_FIELDS = ( + (CONF_STOP, "set_stop", cg.bool_), + (CONF_STATE, "set_position", cg.float_), + (CONF_POSITION, "set_position", cg.float_), + (CONF_TILT, "set_tilt", cg.float_), +) + + +@automation.register_action( + "cover.control", ControlAction, COVER_CONTROL_ACTION_SCHEMA, synchronous=True +) +async def cover_control_to_code( + config: ConfigType, + action_id: ID, + template_arg: cg.TemplateArguments, + args: TemplateArgsType, +) -> MockObj: + return await build_apply_lambda_action( + config=config, + action_id=action_id, + template_arg=template_arg, + args=args, + fields=_COVER_CONTROL_FIELDS, + prefix_args=[(CoverCall.operator("ref"), "call")], + statement_fn=lambda setter, expr: f"call.{setter}({expr});", + ) + + COVER_CONDITION_SCHEMA = cv.maybe_simple_value( {cv.Required(CONF_ID): cv.use_id(Cover)}, key=CONF_ID ) diff --git a/esphome/components/template/cover/__init__.py b/esphome/components/template/cover/__init__.py index bcf0c54c7f7..3cf87798473 100644 --- a/esphome/components/template/cover/__init__.py +++ b/esphome/components/template/cover/__init__.py @@ -19,8 +19,9 @@ from esphome.const import ( CONF_TILT_ACTION, CONF_TILT_LAMBDA, ) -from esphome.core import Lambda -from esphome.cpp_generator import LambdaExpression +from esphome.core import ID +from esphome.cpp_generator import MockObj +from esphome.types import ConfigType, TemplateArgsType from .. import template_ns @@ -112,6 +113,16 @@ async def to_code(config): cg.add(var.set_restore_mode(config[CONF_RESTORE_MODE])) +# CONF_STATE and CONF_POSITION are cv.Exclusive in the schema, so at most +# one is present and both map to the position field. +_COVER_PUBLISH_FIELDS = ( + (CONF_STATE, "position", cg.float_), + (CONF_POSITION, "position", cg.float_), + (CONF_TILT, "tilt", cg.float_), + (CONF_CURRENT_OPERATION, "current_operation", cover.CoverOperation), +) + + @automation.register_action( "cover.template.publish", cover.CoverPublishAction, @@ -128,42 +139,20 @@ async def to_code(config): ), synchronous=True, ) -async def cover_template_publish_to_code(config, action_id, template_arg, args): - paren = await cg.get_variable(config[CONF_ID]) - - # All configured fields are folded into a single stateless lambda whose - # constants live in flash; the action stores only a function pointer. - # The lambda mutates Cover fields directly (no CoverCall) since publish - # is a state push, not a control request. - # CONF_STATE and CONF_POSITION are cv.Exclusive in the schema, so at most - # one is present and both map to the position field. - FIELDS = ( - (CONF_STATE, "position", cg.float_), - (CONF_POSITION, "position", cg.float_), - (CONF_TILT, "tilt", cg.float_), - (CONF_CURRENT_OPERATION, "current_operation", cover.CoverOperation), +async def cover_template_publish_to_code( + config: ConfigType, + action_id: ID, + template_arg: cg.TemplateArguments, + args: TemplateArgsType, +) -> MockObj: + # Mutates Cover fields directly (no CoverCall) since publish is a state + # push, not a control request. + return await cover.build_apply_lambda_action( + config=config, + action_id=action_id, + template_arg=template_arg, + args=args, + fields=_COVER_PUBLISH_FIELDS, + prefix_args=[(cover.Cover.operator("ptr"), "cover")], + statement_fn=lambda field, expr: f"cover->{field} = {expr};", ) - - fwd_args = ", ".join(name for _, name in args) - body_lines: list[str] = [] - for conf_key, field, type_ in FIELDS: - if (value := config.get(conf_key)) is None: - continue - if isinstance(value, Lambda): - inner = await cg.process_lambda(value, args, return_type=type_) - body_lines.append(f"cover->{field} = ({inner})({fwd_args});") - else: - body_lines.append(f"cover->{field} = {cg.safe_exp(value)};") - - # Match CoverPublishAction::ApplyFn: const Ts &... for trigger args. - apply_args = [ - (cover.Cover.operator("ptr"), "cover"), - *((t.operator("const").operator("ref"), n) for t, n in args), - ] - apply_lambda = LambdaExpression( - ["\n".join(body_lines)], - apply_args, - capture="", - return_type=cg.void, - ) - return cg.new_Pvariable(action_id, template_arg, paren, apply_lambda) From 4e921f8127fa60bd1810c3e9ae5cdd5c79f16104 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Wed, 29 Apr 2026 07:09:55 -0500 Subject: [PATCH 5/5] [cover] Use ApplyField dataclass for the apply-lambda field list --- esphome/components/cover/__init__.py | 41 ++++++++++++++----- esphome/components/template/cover/__init__.py | 10 ++--- 2 files changed, 35 insertions(+), 16 deletions(-) diff --git a/esphome/components/cover/__init__.py b/esphome/components/cover/__init__.py index e6a3c29c1de..954ad7a3457 100644 --- a/esphome/components/cover/__init__.py +++ b/esphome/components/cover/__init__.py @@ -1,3 +1,5 @@ +from collections.abc import Callable +from dataclasses import dataclass import logging from esphome import automation @@ -295,14 +297,31 @@ COVER_CONTROL_ACTION_SCHEMA = cv.Schema( ) +@dataclass(frozen=True) +class ApplyField: + """One field in a folded-lambda action. + + `conf_key` is the YAML key looked up in `config`. When present, the + helper emits `statement_fn(target, value_expr)` into the lambda body. + `target` is whatever the statement function needs to identify the + field (typically a setter name like `"set_position"` or a struct + member like `"position"`). `type_` is the C++ return type for + `cg.process_lambda` when the value is a user lambda. + """ + + conf_key: str + target: str + type_: object + + async def build_apply_lambda_action( config: ConfigType, action_id: ID, template_arg: cg.TemplateArguments, args: TemplateArgsType, - fields: tuple[tuple[str, str, object], ...], + fields: tuple[ApplyField, ...], prefix_args: list[tuple[object, str]], - statement_fn, + statement_fn: Callable[[str, str], str], ) -> MockObj: """Fold configured fields into a single stateless apply lambda action. @@ -315,15 +334,15 @@ async def build_apply_lambda_action( paren = await cg.get_variable(config[CONF_ID]) fwd_args = ", ".join(name for _, name in args) body_lines: list[str] = [] - for conf_key, target, type_ in fields: - if (value := config.get(conf_key)) is None: + for field in fields: + if (value := config.get(field.conf_key)) is None: continue if isinstance(value, Lambda): - inner = await cg.process_lambda(value, args, return_type=type_) + inner = await cg.process_lambda(value, args, return_type=field.type_) value_expr = f"({inner})({fwd_args})" else: value_expr = str(cg.safe_exp(value)) - body_lines.append(statement_fn(target, value_expr)) + body_lines.append(statement_fn(field.target, value_expr)) apply_args = [ *prefix_args, @@ -340,11 +359,11 @@ async def build_apply_lambda_action( # CONF_STATE and CONF_POSITION are cv.Exclusive in the schema, so at most # one is present and both dispatch to set_position. -_COVER_CONTROL_FIELDS = ( - (CONF_STOP, "set_stop", cg.bool_), - (CONF_STATE, "set_position", cg.float_), - (CONF_POSITION, "set_position", cg.float_), - (CONF_TILT, "set_tilt", cg.float_), +_COVER_CONTROL_FIELDS: tuple[ApplyField, ...] = ( + ApplyField(CONF_STOP, "set_stop", cg.bool_), + ApplyField(CONF_STATE, "set_position", cg.float_), + ApplyField(CONF_POSITION, "set_position", cg.float_), + ApplyField(CONF_TILT, "set_tilt", cg.float_), ) diff --git a/esphome/components/template/cover/__init__.py b/esphome/components/template/cover/__init__.py index 3cf87798473..7cb50df84c5 100644 --- a/esphome/components/template/cover/__init__.py +++ b/esphome/components/template/cover/__init__.py @@ -115,11 +115,11 @@ async def to_code(config): # CONF_STATE and CONF_POSITION are cv.Exclusive in the schema, so at most # one is present and both map to the position field. -_COVER_PUBLISH_FIELDS = ( - (CONF_STATE, "position", cg.float_), - (CONF_POSITION, "position", cg.float_), - (CONF_TILT, "tilt", cg.float_), - (CONF_CURRENT_OPERATION, "current_operation", cover.CoverOperation), +_COVER_PUBLISH_FIELDS: tuple[cover.ApplyField, ...] = ( + cover.ApplyField(CONF_STATE, "position", cg.float_), + cover.ApplyField(CONF_POSITION, "position", cg.float_), + cover.ApplyField(CONF_TILT, "tilt", cg.float_), + cover.ApplyField(CONF_CURRENT_OPERATION, "current_operation", cover.CoverOperation), )