How to tell HA not to change sensor value (use old value)

Hello. I use this sensor in order to convert pressure from hPa to mmHg:

- platform: template
sensors:
  pressure_cal:
  value_template: '{{ "%.1f" | format(states("sensor.0x00158d000349c2f8_pressure") | float * 0.75006375541921) }}'
  unit_of_measurement: mmHg

The data of 0x00158d000349c2f8_pressure sensor is provided by zigbee2mqtt. But when the zigbee2mqtt is restarting, the sensor 0x00158d000349c2f8_pressure have the undefined state. At the same time pressure_cal sensor obtains value 0.

So the pressure_cal plot looks like this:

Is it possible to tell HA not to change value of pressure_cal to zero if the 0x00158d000349c2f8_pressure state equals “undefined”?

Use an availability template. This will leave gaps in your graph where there is no data rather than zeros.

- platform: template
  sensors:
    pressure_cal:
      value_template: "{{ '%.1f' | format(states('sensor.0x00158d000349c2f8_pressure') | float * 0.75006375541921) }}"
      unit_of_measurement: mmHg
      availability_template: "{{ states('sensor.0x00158d000349c2f8_pressure') not in ['unavailable', 'unknown', 'none'] }}"

The other alternative is to keep the previous state. This is not recommended as you may be unaware of ongoing issues with the sensor but I’ll include it here for completeness:

- platform: template
  sensors:
    pressure_cal:
      value_template: >
        {% if states('sensor.0x00158d000349c2f8_pressure') not in ['unavailable', 'unknown', 'none'] %}
          {{ '%.1f' | format(states('sensor.0x00158d000349c2f8_pressure') | float * 0.75006375541921) }}
        {% else %}
          {{ states('sensor.pressure_cal') }}
        {% endif %}
      unit_of_measurement: mmHg
3 Likes