[lock] Filter on_lock and on_unlock with when (#20858)

This commit is contained in:
J. Nick Koston
2026-10-17 16:33:05 -10:00
committed by GitHub
parent 968d57c56b
commit a8ab035b59
2 changed files with 6 additions and 26 deletions
+6 -4
View File
@@ -32,8 +32,6 @@ LockCall = lock_ns.class_("LockCall")
LockPublishAction = lock_ns.class_("LockPublishAction", automation.Action)
LockStateForwarder = lock_ns.class_("LockStateForwarder")
LockState = lock_ns.enum("LockState")
LOCK_STATES = LockState.options(
@@ -90,12 +88,16 @@ _CALLBACK_AUTOMATIONS = (
automation.CallbackAutomation(
CONF_ON_LOCK,
"add_on_state_callback",
forwarder=LockStateForwarder.template(LockState.LOCK_STATE_LOCKED),
params=[(LockState, "state")],
forward=[],
when="state == lock::LOCK_STATE_LOCKED",
),
automation.CallbackAutomation(
CONF_ON_UNLOCK,
"add_on_state_callback",
forwarder=LockStateForwarder.template(LockState.LOCK_STATE_UNLOCKED),
params=[(LockState, "state")],
forward=[],
when="state == lock::LOCK_STATE_UNLOCKED",
),
)
-22
View File
@@ -1,22 +0,0 @@
#pragma once
#include "esphome/components/lock/lock.h"
#include "esphome/core/automation.h"
#include "esphome/core/component.h"
namespace esphome::lock {
/// Callback forwarder that triggers an Automation<> only when a specific lock state is entered.
/// Pointer-sized (single Automation* field) to fit inline in Callback::ctx_.
template<LockState State> struct LockStateForwarder {
Automation<> *automation;
void operator()(LockState state) const {
if (state == State)
this->automation->trigger();
}
};
static_assert(sizeof(LockStateForwarder<LockState::LOCK_STATE_LOCKED>) <= sizeof(void *));
static_assert(std::is_trivially_copyable_v<LockStateForwarder<LockState::LOCK_STATE_LOCKED>>);
} // namespace esphome::lock