Template Sensor slow to update

I use a template sensor to track a day phase (e.g. morning, evening, etc…) which I use in various automations.

Until recently it’s worked perfectly, but recently it’s seemed slow to respond. This morning I was able to catch it definitely misbehaving. The sensor was reading “night” but when I pasted the template into the dev tools it gave me the correct value of “morning”.

Does anyone have any insight why the sensor might be lagging? I’m running Hassio on a Tinkberboard and when looking at the system stats it doesn’t appear to be under any strain at all.

day_phase:
  friendly_name: "Day Phase"
  value_template: >
    {% set time = now() %}
    {% set isDaylight = states.sun.sun.attributes.elevation > -5 %}
    {% set notHoliday = states.input_boolean.holiday_mode.state == "off" %}
    {% set isWeekday = time.isoweekday() <= 5 %}
    {% set t0000 = time.replace(hour=0).replace(minute=0).replace(second=0) %}
    {% set t0600 = t0000.replace(hour=6) %}
    {% set t0800 = t0000.replace(hour=8) %}
    {% set t1200 = t0000.replace(hour=12) %}
    {% set t1600 = t0000.replace(hour=16) %}
    {% set t1900 = t0000.replace(hour=19) %}
    {% set t2130 = t0000.replace(hour=21).replace(minute=30) %}

    {% if t0600 <= time and time < t0800 and isWeekday %}
      Morning
    {% elif isDaylight 
        or (t0800 <= time and time < t1900 and isWeekday and notHoliday)
        or (t0800 <= time and time < t1600)
    %} 
        Day
    {% elif t1600 <= time and time < t2130 %}
        Evening
    {% else %}
        Night
    {% endif %}

This template will only update as fast as your sun elevation sensor updates, or when the holiday sensor changes state, or when the weekday changes. now() is a function, not a sensor, so it will not cause the template to update.

To ensure the template updates at least every minute add the sensor.time entity, like this:

day_phase:
  entity_id: sensor.time
  friendly_name: "Day Phase"
  value_template: > etc...
1 Like

You need to define an entity_ID. The sensor then gets updated whenever that entity changes state. You can use the time sensor, it updates every minute.

That makes sense, cheers!

1 Like