Help with binary_sensor template never evaluated

I am struggling with this template binary sensor:

binary_sensor:
      smartplug2_1_poweron:
        value_template: >-
          "{% if states('sensor.smartplug2_1_energy_power')|float > 5.0 and 
            is_state('switch.smartplug2_1', 'on')%}true{% else %}false{% endif %}"

The template is correct and checks ok in the template editor. Anyway the sensor is never evaluated and it never turns on.

  • You need to declare the platform.
  • You need to declare the entity ids you use in the template so HA knows what to monitor to update the template.
  • Don’t use quotes for multi-line templates (only single line templates).
  • You can simplify your template (the one below will evaluate to True or False without having to use if/else).
binary_sensor:
  platform: template
  sensors:
    smartplug2_1_poweron:
      entity_id:
        - sensor.smartplug2_1_energy_power
        - switch.smartplug2_1
      value_template: >
        {{ ( states('sensor.smartplug2_1_energy_power') | float > 5.0 ) and is_state('switch.smartplug2_1', 'on') }}

Single line template version:

binary_sensor:
  platform: template
  sensors:
    smartplug2_1_poweron:
      entity_id:
        - sensor.smartplug2_1_energy_power
        - switch.smartplug2_1
      value_template:  "{{ ( states('sensor.smartplug2_1_energy_power') | float > 5.0 ) and is_state('switch.smartplug2_1', 'on') }}"

Using double quotes on multiline was the real problem. Single liner worked immediately without adding entities to monitor.
Anyway now it evaluates the state correctly.

The platform was missing only in the config I pasted here, it was in place in the original configuration.

@tom_l thank you for your promptly help, sometimes takes forever to notice errors that are immediately evident to someone more experienced.

Do add the entities though. It was a breaking change a few versions ago and is recommended practice.

Also see this suggestion by 123 to give a default value on float conversion failure to Prevent false triggering if the sensor becomes unavailable. Though in your case a default of 0 wii be ok (not > 5). Just something to keep in mind for future templates.

Ok, I have this now:

binary_sensors:
  - platform: template
    sensors:
      smartplug2_1_poweron:
        device_class: power
        entity_id:
          - sensor.smartplug2_1_energy_power
          - switch.smartplug2_1
        value_template: "{{ ( states('sensor.smartplug2_1_energy_power') | float(default=0.0) > 5.0 ) and is_state('switch.smartplug2_1', 'on') }}"

It works flawlessy :slight_smile: