Using template binary sensors in triggers

I have created a simple sun-based sensor

  - platform: template
        friendly_name: Is light outside
        value_template: "{{ state_attr('sun.sun', 'elevation')|float > -4 }}"
        device_class: illuminance

This works, but not in the way I expected. The documentation for template binary sensors says:

The state of a Template Binary Sensor can only be on or off .

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

However, unlike all other binary sensors I’ve used, my template sensor’s value is actually True or False rather than on or off. In the developer tools:

and in the template viewer for {{ states('sensor.is_light_outside') }}:

So, none of these work (the expression is always false):

{{ is_state('sensor.is_light_outside', 'on') }}
{{ is_state('sensor.is_light_outside', True) }}
{{ is_state('sensor.is_light_outside', true) }}
{{ states('sensor.is_light_outside') == true }}
{{ states('sensor.is_light_outside') is true }}

Similarly, the sensor doesn’t work in a state trigger that checks for a specific value like 'on' or true.

Using the sensor directly as a boolean value in a template trigger does work, but it seems non-intuitive (because it doesn’t work like any other sensor):

{{ states('sensor.is_light_outside') }}

So, I can use the sensor in a state trigger that triggers for any state change, or I can use the sensor in a template trigger as a boolean value, but not in the same way as a normal binary sensor. Is this the expected behavior for template binary sensors?

Where have you defined this sensor?

Is it a binary_sensor or a sensor?

Binary Sensor

  - platform: template


  - platform: template

In configuration.yaml, and it’s a sensor, not a binary_sensor.

Hmmm…I would have sworn that the template binary sensor docs used sensor in the example, which I thought was particularly odd when I was creating the sensor. Apparently not. Let me just try that as a binary_sensor

If it’s a sensor then it’s reporting the correct state value (True/False).

If you define it as a binary_sensor then it will report on/off. However, illuminance is not a valid device_class for a binary_sensor. You’ll have to choose something else.

I actually had the device class as light at first, but of course that didn’t work since I had defined the sensor as a sensor rather than binary_sensor.

Yay, that works much better. Chalk this up to me not being able to read the docs late at night. :grin: