How to save last MQTT value?

Hi everyone, i have two Sonoff Humidity&Temperature sensors connected to a Sonoff Zigbee Hub flashed with Tasmota. Everything works fine except for the fact that whenever i turn on HomeAssistant after a reboot i get “unknown” status from both sensors until i get a zigbee update.
How can i save the last value received to display a value and not “unknown” ?

The sensors are defined like this:

- name: "Temperatura Camera Christian"
      unit_of_measurement: '°C'
      unique_id: "temperatura_camera_christian" 
      device_class: temperature
      qos: 1
      state_topic: "tele/HUB_Zigbee/SENSOR"
      value_template: > 
       {% if "Temperature" in value_json['ZbReceived']['0xE862'] %} 
          {{ value_json['ZbReceived']['0xE862']['Temperature'] }}
       {% else %}
         {{states('sensor.temperatura_camera_christian') }}
       {% endif %}

I suspect the HASS sensor is only updated when the MQTT data is published, giving undefined between a reboot and the next update.

I think you can also add a default value other than Unknown, but that’s not really a fix.

For template sensors, you can add an extra trigger for reboot, so you could try triggers for start/ reload/ and MQTT change. I’ve not got an exact code example, but here’s a start (update needs to be changed from time_pattern to MQTT data updating):

- trigger:
    - event: start
      platform: homeassistant
    - platform: event
      event_type: event_template_reloaded
    - platform: time_pattern
      # only needs to change once a day
      hours:   05
      minutes: 05
  sensor:
    - name: Date in Text
      #description: "Date in text format suitable for TTS"
      state: >
          {% set dayofweek = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'][now().weekday()] %}
          {% set day = ['1st','2nd','3rd','4th','5th','6th','7th','8th','9th','10th','11th','12th','13th','14th','15th','16th','17th','18th','19th','20th','21th','22th','23th','24th','25th','26th','27th','28th','29th','30th','31th' ][ now().day-1] %}
          {% set month = ['January','February','March','April','May','June','July','August','September','October','November','December'][now().month-1] %}
          {{ dayofweek +', '+ day + ' ' + month + ' '+ now().strftime('%Y') }}
      icon: "mdi:CalendarRange"

So, from what i understand, you are suggesting to trigger a sensor update when HomeAssistant boots, am i right?
But my question is: how does it get the value? The sensors are battery powered so it can’t “ask” them via MQTT their value, and from what i understand MQTT broker loses its values during reboots, so how would your change affect my sensor?

From Tasmota’s documentation:

Telemetry messages can also be sent with the retain flag using SensorRetain.

Configure the Tasmotized hub with SensorRetain 1

The telemetry messages will be retained by the MQTT broker. When Home Assistant restarts and connects to the broker, it will immediately receive the most recent telemetry message that was published.

Seems not to be working, i tried to type it into the console and it seems to be ON now, but still i lose values after rebooting

Use an MQTT client, like MQTT Explorer, to confirm tele/HUB_Zigbee/SENSOR is receiving retained messages.

Yes they are retained

Messaggio 0 ricevuto su tele/HUB_Zigbee/SENSOR alle 18:35:
{
    "ZbReceived": {
        "0xE862": {
            "Device": "0xE862",
            "Name": " Camera Christian",
            "Temperature": 19.29,
            "Endpoint": 1,
            "LinkQuality": 9
        }
    }
}
QoS: 0 - Retain: true

Well seems like it sometimes retains and sometimes not, this is the message i got after that:

Messaggio 1 ricevuto su tele/HUB_Zigbee/SENSOR alle 18:41:
{
    "ZbReceived": {
        "0xE862": {
            "Device": "0xE862",
            "Name": " Camera Christian",
            "Temperature": 20.25,
            "Humidity": 71.86,
            "Endpoint": 1,
            "LinkQuality": 22
        }
    }
}
QoS: 0 - Retain: false

Even if from tasmota console that’s what i see:

18:41:39.648 MQT: tele/HUB_Zigbee/SENSOR = {"ZbReceived":{"0xE862":{"Device":"0xE862","Name":" Camera Christian","Temperature":20.25,"Humidity":71.86,"Endpoint":1,"LinkQuality":22}}} (retained)

If it’s retained then it means the value is stored on the MQTT broker. The moment Home Assistant connects to the broker and subscribes to tele/HUB_Zigbee/SENSOR it will immediately receive the stored value. That’s how retained messages work for any MQTT client.

Perhaps the SensorRetain command doesn’t work as documented when the device is Sonoff Zigbee Bridge flashed with Zigbee2Tasmota.

Upon further examination, even if retained messages are sent, it won’t necessarily fix the problem you reported. The tele/HUB_Zigbee/SENSOR topic is used to report information about all connected Zigbee sensors and not just for sensor 0xE862. So if you have multiple sensors, the last stored message might not even be the one for 0xE862.

1 Like

Hi. I have the same problem, and maybe it could be related to what you are talking about. However, if the option SetOption89 is activated then the topic is individual per devices. But… that doesn’t solve the problem either.
I also can’t find the reason why sometimes (most of the time) messages are not retained by HA MQTT server when it restarts. Most of these options are tested: (except power and switch since I have only sensors): MQTT - Tasmota

1 Like

Just to try to provide some more information, and related to what Taras says.

In my case I have two Sonoff Zbridge with Tasmota. One of them only with two door sensors.

If one sensor (door) is in ‘unknown’ and the other with known state (closed), then on HA restart both sensors start as ‘unknown’. However, if both sensors have a ‘known’ state (open, close…) before restarting HA, then when restarting HA both sensors keep the last state (open, close…).

Maybe the ‘retain’ flag only works if there is no ‘unknown state’ in the devices connected to the Sonoff Zbdridge before restarting HA.