Sensor states across restarts

I have some sensors defined as below. My question is, why after a restart do they revert to a state of ‘unknown’ even if they had a value before the restart?

  - platform: mqtt
    name: "Sonoff03_firmware"
    state_topic: "stat/sonoff03/STATUS2"
    value_template: >
      {% if value_json.StatusFWR.Version != 'unknown' %}
        {{ value_json.StatusFWR.Version }}
      {% else %}
        {{ states('sensor.sonoff03_firmware') }}
      {% endif %}

Some of my sonoffs don’t stay plugged in so clearly they are technically ‘unknown’ but shouldn’t my value_template stop it changing?


For completeness here is the automation that updates the sensors:

automation:
  - alias: Sonoff Firmware Installed
    initial_state: on
    trigger:
      - platform: time
        at: '00:00:15'

      - platform: homeassistant
        event: start

    action:
      - service: mqtt.publish
        data:
          topic: cmnd/sonoff03/status
          payload: "2"

And here is proof a that there used to be a value!
image

Is the device using the retain flag?

Err, yes but only the power and the power state. There is no way I am aware of to retain the firmware version. In fact to get it you have to publish to its topic.

So why do you care about their firmware version?

Because I can :wink:

I have this, it would just be nice to see the version of each device even if it is not currently available.

1 Like

Your template is looking for ‘unknown’ but your screenshot shows ‘Unknown’

Indeed it is but the Dev tool shows ‘unknown’.

image

EDIT:
For fun I tried ‘Unknown’ and…
…. I think it worked!?!

EDIT:
No it didn’t. I wasn’t concentrating properly, I’m doing several things at once here…

Regarding this code:

    state_topic: "stat/sonoff03/STATUS2"
    value_template: >
      {% if value_json.StatusFWR.Version != 'unknown' %}

It is based on the assumption that the state_topic’s message contains this JSON element:
"Version": "unknown"

Maybe I’ve misunderstood how this works but wouldn’t this topic message contain "Version": "" when there’s no version information available? Faced with no available value, Home Assistant considers the value to be unknown.

The process is that the automation publishes to a topic with a payload that causes the Sonoff to respond with JSON which includes the element "Version": "firmware" where firmware is always a number such as 6.2.1

The sensor detects this and updates accordingly.

So you are absolutely right in that Version can never in fact be “unknown” so will never get to the else.

Thanks. I can’t believe how off my thought process was.