mirror of
				https://github.com/esphome/esphome.git
				synced 2025-10-30 22:53:59 +00:00 
			
		
		
		
	[template/binary_sensor] Implement condition: option as alternative to lambda. (#7561)
				
					
				
			This commit is contained in:
		| @@ -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 | ||||
|   | ||||
		Reference in New Issue
	
	Block a user