Trying to create template sensors without "gaps"

Hello,
I have a sensor which becomes unavailable at certain times, which also creates gaps in the graphs.
I would like to prevent this with a template sensor of the original sensor. So my approach was to make a template sensor which copies the value, except for when it retrieves an error.
Currently I have this:

    pv_gen_meter_edit:
        unit_of_measurement: kWh
        value_template: |
            {% if states('sensor.pv_gen_meter')|float(0) > 0 %}
            {{ states('sensor.pv_gen_meter') }}
            {% endif %}

However, the gaps are still there. How can I fix this?

    pv_gen_meter_edit:
        unit_of_measurement: kWh
        value_template: >
            {% if states('sensor.pv_gen_meter')|is_number %}
              {{ states('sensor.pv_gen_meter') }}
            {% else %}
              {{ states('sensor.pv_gen_meter_edit') }}
            {% endif %}

This should keep the last value if sensor.pv_gen_meter is unknown or unavailable.

My idea was that the _edit version would keep its old value by doing only the if part.
But that’s not the case if I understand this correctly?

What value does your template return if sensor.pv_gen_meter is unknown or unavailable?

You have not defined it.

That is what the (required) else case provides in my version. The current value of sensor.pv_gen_meter_edit. i.e. don’t change.

NOTE: there was an error in my template. I have edited the post and fixed it.

Thanks, I have changed it.
I will check it the next time the original sensor becomes unavailable.

You can manually change the value of sensor.pv_gen_meter to ‘unavailable’ in Developer Tools → States if you want to test it now. It will revert to a number next time the sensor updates.

Click on the entity in the list then up the top of the page:

A bit more compact:

        value_template: >-
            {% set VALUE = states('sensor.pv_gen_meter') -%}
            {%- if VALUE|is_number -%}
              {{ VALUE }}
            {%- else -%}
              {{ this.state }}
            {%- endif %}
1 Like

I keep forgetting about this.

Btw, once I asked if it is same:

this.state
states(this.entity_id).state

then I was told - yes, it is same.
Hope there is no any problems when using “this.state”.