Template help for unavailable attributes

I have been screwing around in the template dev tool for quite some time now. Can’t find a working solution.

I currently have a number of template sensors to pull wattage information from some switches.

https://github.com/SilvrrGIT/HomeAssistant/blob/master/sensors.yaml#L219

They work great normally. However at startup HA doesn’t have all the attributes yet (i.e. ‘current_power_w’ is not in the states tab) and they throw an error. Or if there isn’t a KWh reading yet it will show as unknown.

I would like for them to not throw an error when the attribute isn’t available and read 0 until another value is provided. Is this possible?

You can Add | default(0) to your template after attributes["current_power_w"]
Check my file for more details and a better solution
https://github.com/lolouk44/homeassistant/blob/master/sensors/Edimax.yaml

1 Like

Many thanks, that works perfectly.

1 Like

I know this has been solved, but did you try

edimax1_watts:
  value_template: "{{ state_attr('switch.edimax1' , 'current_power_w') }}"
  unit_of_measurement: 'W'

Which should return the value if present and none if it isn’t? Then you could use the same method as above to make it zero if needed, but it’s a shed load less code.

All of this is a random thought btw, might not even work.

I think I used that and it throws an error as ‘current_power_w’ isn’t defined sometimes. Its not a issue of an unknown value, the attribute actually doesn’t exist until you turn the switch on. That works fine for reading the value when the attribute is present.

According to the docs it should work in that format even when the attribute doesn’t exist, hence my question.