Best way to fill gaps in sensor data

I have a rest sensor that has gaps in the data.
I have a filter that consumes the rest sensor and applies time_simple_moving_average to it.
Whenever the rest sensor has gaps in the data, the filter does too.
What’s the best way to get a sensor that fills in these gaps with the last known value before passing it to the filter?

Here’s what I came up with after seeing something similar on the forum: a template sensor that copies its own value whenever there’s a gap in the input sensor. Is this the best way?

template:
  - sensor:
      - name: foo_nogap
        state: >
          {% if states('sensor.foo')|is_number %}
            {{ states('sensor.foo') }}
          {% else %}
            {{ states('sensor.foo_nogap') }}
          {% endif %}
1 Like

That looks ok. The other way is to fill the gap with the previous value:

template:
  - sensor:
      - name: foo_nogap
        state: >
          {% if states('sensor.foo')|is_number %}
            {{ states('sensor.foo') }}
          {% else %}
            {{ this.state }}
          {% endif %}

See: https://www.home-assistant.io/integrations/template/#self-referencing

This could also be done directly in the rest sensor without a template sensor (using the state or value_template in the rest sensor). However I like to see the gaps so I know when there is an issue with my sensor.

1 Like