How to keep old sensor value during "unknown" state/

Hi,
I am using seven segment OCR sensor.
Sometimes it retrurns “unknown” state, in such cases I would like to keep previous value of sensor.

Here is how I tried to solve this issue, but without sucess (sensor value goes to 0 in case of “unknown” state):

sensor:
  - platform: template
    sensors:
      energy:
        value_template: >-
          {% if not is_state("image_processing.sevensegment_ocr_seven_segments", "unknown") -%}
            {{ states('image_processing.sevensegment_ocr_seven_segments')|float / 100 }}
          {% else %}
            {{states('sensor.energy')}}
          {%- endif %}
        friendly_name: "Joule"
        unit_of_measurement: "GJ"

Here is how looks my sensor history:
Joule

Could you help me to solve this problem?

Thanks!

Try this:

sensor:
  - platform: template
    sensors:
      energy:
        value_template: >
          {% set energy = states('image_processing.sevensegment_ocr_seven_segments')|float(none) %}
          {{ energy if energy != none else states('sensor.energy') }}
        friendly_name: "Joule"
        unit_of_measurement: "GJ"

This will still be ‘unknown’ after a restart until the first valid OCR measurement.

3 Likes