Merge remote-tracking branch 'origin/cover-action-bitmask' into integration

This commit is contained in:
J. Nick Koston
2026-04-29 07:41:16 -05:00
5 changed files with 153 additions and 144 deletions
+89 -31
View File
@@ -1,3 +1,5 @@
from collections.abc import Callable
from dataclasses import dataclass
import logging
from esphome import automation
@@ -36,14 +38,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 +70,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
@@ -294,39 +297,94 @@ 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[ApplyField, ...],
prefix_args: list[tuple[object, str]],
statement_fn: Callable[[str, str], str],
) -> 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])
fwd_args = ", ".join(name for _, name in args)
body_lines: list[str] = []
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=field.type_)
value_expr = f"({inner})({fwd_args})"
else:
value_expr = str(cg.safe_exp(value))
body_lines.append(statement_fn(field.target, value_expr))
apply_args = [
*prefix_args,
*((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)
# 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: 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_),
)
@automation.register_action(
"cover.control", ControlAction, COVER_CONTROL_ACTION_SCHEMA, synchronous=True
)
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<uint16_t>({field_mask})"), *template_arg
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});",
)
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_))
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_))
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
COVER_CONDITION_SCHEMA = cv.maybe_simple_value(
+15 -62
View File
@@ -46,89 +46,42 @@ template<typename... Ts> class ToggleAction : public Action<Ts...> {
Cover *cover_;
};
// Unique Empty<Tag> per field so [[no_unique_address]] is guaranteed to coalesce.
namespace cover_action_detail {
template<int Tag> 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 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.
// 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<uint16_t Fields, typename... Ts> class ControlAction : public Action<Ts...> {
template<typename... Ts> class ControlAction : public Action<Ts...> {
public:
explicit ControlAction(Cover *cover) : cover_(cover) {}
#define COVER_FIELD_SETTER_(type, name, idx) \
template<typename V> 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<type, Ts...>, \
cover_action_detail::Empty<(idx)>> \
name##_{};
COVER_CONTROL_FIELDS(COVER_FIELD_SETTER_)
using ApplyFn = void (*)(CoverCall &, const 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<uint16_t Fields, typename... Ts> class CoverPublishAction : public Action<Ts...> {
template<typename... Ts> class CoverPublishAction : public Action<Ts...> {
public:
CoverPublishAction(Cover *cover) : cover_(cover) {}
#define COVER_PUBLISH_SETTER_(type, name, idx) \
template<typename V> 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<type, Ts...>, \
cover_action_detail::Empty<(idx) + 8>> \
name##_{};
COVER_PUBLISH_FIELDS(COVER_PUBLISH_SETTER_)
using ApplyFn = void (*)(Cover *, const 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<bool OPEN, typename... Ts> class CoverPositionCondition : public Condition<Ts...> {
public:
+29 -31
View File
@@ -19,6 +19,9 @@ from esphome.const import (
CONF_TILT_ACTION,
CONF_TILT_LAMBDA,
)
from esphome.core import ID
from esphome.cpp_generator import MockObj
from esphome.types import ConfigType, TemplateArgsType
from .. import template_ns
@@ -110,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: 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),
)
@automation.register_action(
"cover.template.publish",
cover.CoverPublishAction,
@@ -126,35 +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])
# 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<uint16_t>({field_mask})"), *template_arg
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};",
)
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
)
cg.add(var.set_current_operation(template_))
return var
@@ -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"
+11 -11
View File
@@ -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