Template binary sensor with gap

I would like to create a binary sensor that indicates if the light level has reached a certain daytime brightness or fallen below a sunset level.

If the light level is above 200 the sensor is turned on.
if the light level is below 10 the sensor is turned off.

I’m not sure how to template this. Would this work?

(bianary_sensors.yaml)

- platform: template
  sensors:
    lounge_auto_lights_enable:
      friendly_name: "Lounge Auto Lights Enable"
      value_template: >-
        {% if states('sensor.aeotec_lounge_light_level') > 200 %}
          'on'
        {% elif states('sensor.aeotec_lounge_light_level') < 10 %}
          'off'
        {% else %}
           {{ states('lounge_auto_lights_enable') }} # stay the same state
        {% endif %}

This sensor will be used to prevent my lights automatically turning on in the morning if I have not woken up and opened the blinds and there is a dim light level in the room (as happens at sunset when I do want the lights to turn on).

If the max_age of the statisitcs sensor worked I would not need this work around as I could just test for light_level > 200 in the last 8 hours.

I ended up not using or testing this.
I used an mqtt binary sensor and a couple of automations to set it at the required light values instead.

I’m pretty sure that would work. I haven’t used it myself but that would be how I code it.

1 Like

So I agree the design should work, but the actual implementation has some problems. E.g., you have to convert the state strings to float or int before comparing them to numbers. Also the quotes around on and off should probably be removed.

But, for this case, you should probably just use a Threshold Binary Sensor instead. E.g.:

binary_sensor:
  - platform: threshold
    entity_id: sensor.aeotec_lounge_light_level
    upper: 105
    hysteresis: 95

This binary_sensor will turn on whenever the numeric value of sensor.aeotec_lounge_light_level goes above upper + hysteresis (i.e., 105 + 95 = 200), and will turn off whenever it goes below upper - hysteresis (i.e., 105 - 95 = 10.)

1 Like

That’s a great suggestion. Thanks Phil.