mirror of
https://github.com/esphome/esphome.git
synced 2024-11-21 22:48:10 +01:00
[template/binary_sensor] Implement condition:
option as alternative to lambda. (#7561)
This commit is contained in:
parent
fc97a6d1e3
commit
66f500e594
2 changed files with 26 additions and 6 deletions
|
@ -1,8 +1,10 @@
|
|||
import esphome.codegen as cg
|
||||
import esphome.config_validation as cv
|
||||
from esphome import automation
|
||||
import esphome.codegen as cg
|
||||
from esphome.components import binary_sensor
|
||||
from esphome.const import CONF_ID, CONF_LAMBDA, CONF_STATE
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_CONDITION, CONF_ID, CONF_LAMBDA, CONF_STATE
|
||||
from esphome.cpp_generator import LambdaExpression
|
||||
|
||||
from .. import template_ns
|
||||
|
||||
TemplateBinarySensor = template_ns.class_(
|
||||
|
@ -13,7 +15,10 @@ CONFIG_SCHEMA = (
|
|||
binary_sensor.binary_sensor_schema(TemplateBinarySensor)
|
||||
.extend(
|
||||
{
|
||||
cv.Optional(CONF_LAMBDA): cv.returning_lambda,
|
||||
cv.Exclusive(CONF_LAMBDA, CONF_CONDITION): cv.returning_lambda,
|
||||
cv.Exclusive(
|
||||
CONF_CONDITION, CONF_CONDITION
|
||||
): automation.validate_potentially_and_condition,
|
||||
}
|
||||
)
|
||||
.extend(cv.COMPONENT_SCHEMA)
|
||||
|
@ -24,9 +29,17 @@ async def to_code(config):
|
|||
var = await binary_sensor.new_binary_sensor(config)
|
||||
await cg.register_component(var, config)
|
||||
|
||||
if CONF_LAMBDA in config:
|
||||
if lamb := config.get(CONF_LAMBDA):
|
||||
template_ = await cg.process_lambda(
|
||||
config[CONF_LAMBDA], [], return_type=cg.optional.template(bool)
|
||||
lamb, [], return_type=cg.optional.template(bool)
|
||||
)
|
||||
cg.add(var.set_template(template_))
|
||||
if condition := config.get(CONF_CONDITION):
|
||||
condition = await automation.build_condition(
|
||||
condition, cg.TemplateArguments(), []
|
||||
)
|
||||
template_ = LambdaExpression(
|
||||
f"return {condition.check()};", [], return_type=cg.optional.template(bool)
|
||||
)
|
||||
cg.add(var.set_template(template_))
|
||||
|
||||
|
|
|
@ -46,6 +46,13 @@ binary_sensor:
|
|||
// Garage Door is closed.
|
||||
return false;
|
||||
}
|
||||
- platform: template
|
||||
id: other_binary_sensor
|
||||
name: "Garage Door Closed"
|
||||
condition:
|
||||
sensor.in_range:
|
||||
id: template_sens
|
||||
below: 30.0
|
||||
|
||||
output:
|
||||
- platform: template
|
||||
|
|
Loading…
Reference in a new issue