Wrapping a rest sensor in a template sensor

I have wrapped a rest sensor in a a template sensor because sometimes the data is not available, and rather than showing nothing, it shows the previous state, this works fine:-

- sensor:
    - name: "Main HDD UDMA_CRC_Error_Count"
      unique_id: main_hdd_UDMA_CRC_Error_Count
      state: >
        {% if states('sensor.main_hdd_udma_crc_error_count_rest')|float(-1)>-1 %}
        {{ states('sensor.main_hdd_udma_crc_error_count_rest') }}
        {%else%}
        {{ this.state|float(0) }}
        {%endif%}
      unit_of_measurement: "errors"

Except if the Rest data is not available immediately after a restart. In this case this.state is simply ‘unavailable’.

Is there a way to preserve this value during restarts, or perhaps another way to avoid this ?

I do the same for reading values from a public Air Quality service. Sometimes the service fails to respond, or some other problem occurs, so the combination of REST and Template gives me more control over the final, reported value.

Here’s what I suggest you do to avoid the problem on startup. Create a Trigger-based Template Sensor employing a State Trigger to monitor sensor.main_hdd_udma_crc_error_count_rest.

Configure the State Trigger to avoid triggering when the sensor’s value changes to unavailable or unknown. In other words, it will trigger for any state-changes except to those two.

The state of a Trigger-based Template Sensor is automatically restored on startup (so there’s no need for its template to handle this.state).

template:
  - triggers:
      - trigger: state
        entity_id: sensor.main_hdd_udma_crc_error_count_rest
        not_to:
          - unavailable
          - unknown
    sensor:
      - name: "Main HDD UDMA_CRC_Error_Count"
        unique_id: main_hdd_UDMA_CRC_Error_Count
        state: "{{ trigger.to_state.state }}"
        unit_of_measurement: "errors"

Here’s an alternative example, employing conditions to confirm the sensor’s value is not unknown or unavailable, using has_value(), and the value is a number, using is_number.

template:
  - triggers:
      - trigger: state
        entity_id: sensor.main_hdd_udma_crc_error_count_rest
    conditions:
      - condition: template
        value_template: |
          {{ has_value('sensor.main_hdd_udma_crc_error_count_rest')
             and trigger.to_state.state | is_number }}
    sensor:
      - name: "Main HDD UDMA_CRC_Error_Count"
        unique_id: main_hdd_UDMA_CRC_Error_Count
        state: "{{ trigger.to_state.state }}"
        unit_of_measurement: "errors"

Be advised that the initial value of a Trigger-based Template Sensor is unknown and will change when it is triggered.