[cover] Fold ControlAction/CoverPublishAction fields into stateless lambdas

This commit is contained in:
J. Nick Koston
2026-04-29 06:37:52 -05:00
parent 6f79312fa7
commit d0f4e89ef3
3 changed files with 77 additions and 115 deletions
+30 -27
View File
@@ -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<uint16_t>({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(
+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 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<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 &, 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 *, 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:
+32 -26
View File
@@ -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<uint16_t>({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)