How to get on/off based on a sensor value

Hi All,

I’m trying to get a binary_sensor to report either ‘on’ or ‘off’ based on the value of another sensor.

I would like to binary_sensor to report ‘off’ if the other sensor value is below 5 and ‘on’ if it is above 5. So far my attempt below has not worked… Any tips?

binary_sensor:
  - platform: template
    sensors:
      onyko_amp_power:
        friendly_name: "Onyko Amp Power"
        value_template: "{{ 'off' if states('sensor.washing_machine_power_power_2') | float < 5 else 'on' }}"

(disregard the mismatch between the devices ‘onkyo amp’ and ‘washing machine’, I’m using a portable power measuring switched outlet for testing)

If someone has the solution that would be awesome as I couldn’t find it when searching earlier today.

Binary sensors report on/off by default so all you need is a true/false test, like so:

binary_sensor:
  - platform: template
    sensors:
      onyko_amp_power:
        friendly_name: "Onyko Amp Power"
        value_template: "{{ states('sensor.washing_machine_power_power_2')  | float > 5 }}"

This will report off if <= 5, and on if > 5.

2 Likes

Thanks Tom, that worked perfectly

2 Likes

I see too many questions like the OP and perhaps the main reason is the way it’s described in documentation:

Defines a template to set the state of the sensor.

It should be more explicit and descriptive, something like

The sensor is on if the template evaluates as True and off otherwise.
The actual appearance in UI (Open/Closed, Detected/Clear etc) depends on the sensor’s device_class value.

I agree. Also when I originally put the template in the development tool, I was getting ‘True’… But I don’t think I had binary_sensor in front of it… Can’t remember

I don’t quite understand your issue, could you elaborate?

That’s because the template evaluates to True or False. The binary sensor takes this information and maps it to on and off respectively. Even if you change the device class so the front end shows something different (detected / clear for a movement sensor for example) the binary sensor still reports on or off to the back end for triggers and templates.

Thanks for the clarification

Tom answered it with his explanation. It was just a lack of my understanding with how the template system works.