MQTT sensor and template sensor - how to return value when mqtt sensor is offline

I have an MQTT sensor that is configured like this:

sensor:
  - platform: mqtt
    state_topic: "Temp1/Salon/Temperature"
    name: "salon_temperature"
    unit_of_measurement: "°C"
    expire_after: 180
    availability_topic: "Temp1/status"
    payload_available: "Online"
    payload_not_available: "Offline"

and a template sensor that I use to callibrate readings:

  - platform: template
    sensors:
      temperatura_salon:
        friendly_name: "Salon"
        unit_of_measurement: '°C'
        value_template: >-
          {{ states.sensor.salon_temperature.state | float - 1.9 }}

The MQTT sensor works fine, but I have weird picks on history charts for the template sensor:

image

This is best visible in the history panel:

I’m using Wemos D1 with ESPEasy and DS18B20 to read the temperature. The wifi is stable but I noticed that sometimes I get Offline message on LWT topic, but for a short period of time.

Can I modify the template sensor is such a way that it won’t report -1.9 as the value when the sensor won’t be available?
I’d like to avoid removing the availability_topic from MQTT sensor and do the work in template sensor.

The “dips” in the graph, or “picks” as you called them, represent negative values. This is the template:

{{ states.sensor.salon_temperature.state | float - 1.9 }}

When salon_temperature is an unknown value, the float filter will convert it to 0. The result will 0 - 1.9 = -1.9 and produce a dip/pick in the graph.

I’m aware of that :slightly_smiling_face:
As first I was thinking that sensors are broken and I replaced them with original DS18B20.
Not sure if this is something with ESPEasy or wemos board (I already ordered a couple more to test)

Can I configure the template sensor to return the last value when the state is unknown?
Or maybe I should use expire_after and not use availability_topic?
My sensor will be offline after 180 seconds (will have unknown state/value) and LWT topic will not cause those dips. Should that help?

Try this:

  - platform: template
    sensors:
      temperatura_salon:
        friendly_name: "Salon"
        unit_of_measurement: '°C'
        value_template: >-
          {% set t = states('sensor.salon_temperature') %}
          {{ states('sensor.temperatura_salon') if t == 'unknown' else t | float -1.9 }}