It works perfectly except when restarting Home Assistant. The template sensor temporarily gets the state of unavailable during 0.015 seconds. This is the state of the sensor during startup:
I’ve tested to set the state of the template sensor to 0 and it still gives me the state of unavailable during startup of Home Assistant. I guess, this is something related to the initialization process of Home Assistant.
I’ve checked the rest of the template sensors and all the template sensors have the state unavailable at startup during 0.015 seconds.
Does anybody have the same problem with template sensors? Has anybody solved the problem with the unavailable state of the entity configured in the gas consumption of the Energy dashboard?
thank you for your answer. I’ve used your code and the behavior is the same. The state of the template sensor is unavailable at startup during few microseconds:
I think that when the state is unavailable at startup, the code of the template sensor is not executed. Then, it doesn’t matter what I put in the state or the availability parameters of the template sensor. After few microseconds, the template sensor is executed correctly. Am I right?
Every entity is marked unavailable at startup until its integration receives or restores a value. There is nothing you can do about this. It is how home assistant works.
The availability template will prevent this template sensor from rendering as zero (your default for the counter). It will remain unavailable until a valid value is received.
The unavailable state wasn’t messing with your graph, the default zero value was.
0 → some value = add that whole value to the total
Unavailable → some value = do nothing.
I have seen this issue more times than I can count. Trust me the availability template will fix your strange readings after a restart. That’s why I wrote the Community Guide.