I have a templated binary_sensor which decide if we are at night (or not). The template return is based on the sun elevation and the outside illuminance. The metered outside lux is not a stricly decreasing function for various reason. So, around the trigger value, the state of the binary_sensor may wobble.
My idea was to forbid the sensor to change its state for at least 4h. So I wrote something like this.
binary_sensor:
- platform: template
sensors:
night:
value_template: >-
{% set last_state = states.binary_sensor.night %}
{% if last_state is not none and now()-last_state.last_changed < timedelta(hours=4) %}
{{ last_state.state }}
{% elif states("sensor.balcony_illuminance") != "unknown" %}
{{ state_attr("sun.sun", "elevation")|float < -2.0 and states("sensor.balcony_illuminance")|float <= 2 }}
{% else %}
{{ state_attr("sun.sun", "elevation")|float < -2.0 }}
{% endif %}
This is triggering Template loop detected errors like this:
2020-10-25 20:00:48 WARNING (MainThread) [homeassistant.components.template.template_entity] Template loop detected while processing event: <Event state_changed[L]: entity_id=binary_sensor.night, old_state=<state binary_sensor.night=on; friendly_name=The night, icon=mdi:weather-night, device_class=light @ 2020-10-25T19:59:46.104737+01:00>, new_state=<state binary_sensor.night=off; friendly_name=The night, icon=mdi:weather-night, device_class=light @ 2020-10-25T20:00:48.083852+01:00>>, skipping template render for Template[{% set last_state = states.binary_sensor.night %} {% if last_state is not none and now()-last_state.last_changed < timedelta(hours=4) %} {{ last_state.state }} {% elif states("sensor.balcony_illuminance") != "unknown" %} {{ state_attr("sun.sun", "elevation")|float < -2.0 and states("sensor.balcony_illuminance")|float <= 2 }} {% else %} {{ state_attr("sun.sun", "elevation")|float < -2.0 }} {% endif %}]
I imagine this kind of unstable inputs and detecting the night is something very common for home automation. Do you have suggestion to improve a templated binary_sensor stability without triggering loop protection?