[SOLVED] How to „secure“ a template against failures?

Dear,
using AI on the edge, I am reading my gasmeter. Since this is done based on cubic metres, I am using a template to calculate kWh from it.
The (very simple) template looks like this

{{ states('sensor.gasuhr_per_ai_on_the_edge_value') | float(0) * states('input_number.gas_brennwert') | float(0) * states('input_number.gas_zustandszahl') | float(0) | round(2) }}

So I simply multiply the gasmeter value with the gas condition and the calorific value.
This template is placed in my energy dashboard, which generally works quite well. However, at certain times, the gasmeter value becomes unavailable. As soon as it comes back to life, it „increases“ to the old value - which means that it counts the complete meter value.
So the sensor looks like this:

With the energy dashboard looking like this

I know that I can correct the value manually, however, I would like to secure my template so that this cannot happen again.

Could anyone of you please guide me on how to do this?
Thank you,
regards

Philip

If you are using YAML you can use an availability template. If you are using the UI you can do this:

{% if has_value('sensor.gasuhr_per_ai_on_the_edge_value') %}
  {{ states('sensor.gasuhr_per_ai_on_the_edge_value') | float() * states('input_number.gas_brennwert') | float() * states('input_number.gas_zustandszahl') | float() | round(2) }}
{% else %}
  this.state
{% endif %}

this.state is the previous state. If your template source sensor is unavailable or unknown this is what the value stays at.

Normally you would check all the entities have a valid value however you shouldn’t have to do this for the input_numbers.

Also why are you using input numbers for constants rather than just numbers?

e.g. the calorific value is just a number that should not change.

1 Like

Great, thank you for your support. I really need to get used to Jinja…

In terms of your remarks: I have prepared caloric value and condition number as input number, as they are changing from year to year. Therefore, I am always updating the input numbers to the latest information on the gas invoice.