Sum-Template of lazy entities is always unavailable/unknown

Hello community!

I’m currently dealing with a problem when I want to add a template, that sums up other entities. My template looks like this:

-  name: Victron grid
   unit_of_measurement: W
   state: >
       {% set ns = namespace(states=[]) %}
       {% for s in states.sensor %}
           {% if s.object_id.startswith('victron_grid') %}
               {% set ns.states = ns.states + [ s.state | float ] %}
           {% endif %}
       {% endfor %}
       {{ ns.states | sum | round(1) }}

The problem is: the three victron grid entites are retrieved using modbus tcp and are not existing until 5-10 seconds after homeassistent start. The result: unavailable. This stays even if the values are available some seconds after.

I tried to add an “available” option for the template checking one of the entities if it is available:

availability: "{{ state('sensors.victron_grid_l1') is number }}"

The template itself producing an unknown all the time.

What I have to do? Thanks!

The template is not loading because you have not defined a default value for your float filter. So it fails when trying to convert an unknown state to a floating point number. Try this:

-  name: Victron grid
   unit_of_measurement: W
   state: >
       {% set ns = namespace(states=[]) %}
       {% for s in states.sensor %}
           {% if s.object_id.startswith('victron_grid') %}
               {% set ns.states = ns.states + [ s.state | float(0) ] %}
           {% endif %}
       {% endfor %}
       {{ ns.states | sum | round(1) }}

That should be:

availability: "{{ state('sensors.victron_grid_l1') is_number }}"
                                                     ^
                                                     |
1 Like

Thanks, that worked!