Some template help appreciated, please

I’m seeing errors like this:


TemplateError('ValueError: Template error: float got invalid input 'unavailable' when rendering template '{{ [ states('sensor.main_house_net_power'), states('sensor.west_wing_power'), states('sensor.tool_store_net_power'), states('sensor.garage_power') ] | map('float') | sum }}' but no default was specified') while processing template 'Template("{{ [ states('sensor.main_house_net_power'), states('sensor.west_wing_power'), states('sensor.tool_store_net_power'), states('sensor.garage_power') ] | map('float') | sum }}")' for attribute '_attr_native_value' in entity 'sensor.total_power'

that relate to template sensors like this:

- sensor:
    - name: "Total Power"
      unit_of_measurement: "kW"
      device_class: power
      state: >
        {{ [ states('sensor.main_house_net_power'), 
              states('sensor.west_wing_power'), 
              states('sensor.tool_store_net_power'), 
              states('sensor.garage_power') ]
              | map('float') | sum }}
      availability: >
        {{ not 'unavailable' in 
           [ states('sensor.main_house_net_power'), 
              states('ssensor.west_wing_power'), 
              states('sensor.tool_store_net_power'), 
              states('sensor.garage_power') ] }}

I think it’s because if one of the sensors becomes unavailable then the template can’t be evaluated as it sees a string instead of an expected float.

Is there a way to catch this and prevent the error?

Your availability has a typo in it “ssensor.west_wing_power”, which is likely keeping it from working properly. That should take care of the issue.

You can also prevent the error by supplying the requested default to float() and use a select filter so you are only summing numeric values.

state: >
    {{ [ states('sensor.main_house_net_power'), 
    states('sensor.west_wing_power'), 
    states('sensor.tool_store_net_power'), 
    states('sensor.garage_power') ]
    | map('float', 'unavailable')
    | select('is_number') | sum }}
1 Like

Thank you. Well spotted with the typo.

So, does that now mean that if a sensor is unavailable it will just sum the remaining three or not sum any?

It depends on how you decide to set it up…

Option 1: Correct the typo and leave the state template as it was. With a properly functioning availability, your sensor will simply return “unavailable” if any of the original sensors are unavailable.

Option 2: Use the state template with the default and get rid of the availability. If any of the sensors have a non-numeric state they will be disregarded and the remaining sensors will be summed.

Option 3: Use the state template with the default and keep the fixed availability. Your sensor will return “unavailable” if any of the original sensors are unavailable. If any of the sensors have a non-numeric state other than “unavailable”, they will be disregarded and the remaining sensors will be summed.

1 Like