Template sensor randomly stops calculating and updating

I have a couple of template sensors that sum up power, energy consumption, … over various devices. The configuration has been working for months now and has not been touched. Honestly!

Since a couple of days now, the sensors just stop recalculating for no obvious reason although new values are coming in from the underlying sensors.

what I observed / tried:

  • template sensors keep their last calculated values, do not go to unknown or so
  • as far as I have seen, all template sensors summing up the energy values fail at the same time
  • other template sensors do still work when this occurs (I tried a simple one displaying local time)
  • to get them restarted, I need to reload the YAML configuration for template entities or restart HA
  • no obvious pattern when this occurs (time, events, values, …)
  • nothing to be seen in the logs
  • when I copy the code for state into the template editor in developer tools, the value is being correctly summed up there

here is an example of a sensor configuration:


template:
  - sensor:
      - name: "Gesamtleistung"
        unique_id: power_total
        unit_of_measurement: "W"
        device_class: power
        state_class: measurement
        state: >
          {{ states.sensor 
            | selectattr('entity_id', 'in', state_attr('group.power_sensors','entity_id'))
            | selectattr('state', 'is_number')
            | map(attribute='state') | map('float') | default (0.0) | sum }}
        icon: mdi:home-lightning-bolt-outline

I’m kind of clueless at the moment and have not even a good idea how to debug that behaviour. Any ideas around?

Try this version. It isn’t subject to rate limiting like your version

template:
  - sensor:
      - name: "Gesamtleistung"
        unique_id: power_total
        unit_of_measurement: "W"
        device_class: power
        state_class: measurement
        state: >
          {{ expand('group.power_sensors')
            | selectattr('state', 'is_number')
            | map(attribute='state') | map('float', 0) | sum }}
        icon: mdi:home-lightning-bolt-outline

I’ll give it a try, thanks!

I have it running now for some time and this seems to do the trick (although I did not fully understand why). @123 thanks for your help!

For this particular case, I just realized that it could be done even easier. Sensor groups can have type: sum and can calculate the result without the need for an additional template sensor.

1 Like