Send MQTT command on start/reload

Whenever I restart Home Asisstant or use YAML configuration reloading > Manually configured MQTT entities to reload the MQTT sensor configuration, all the MQTT sensors lose their state until the next state message arrives.

It would be great if I could configure an init_command: for an MQTT sensor which would be sent after a reload, to request the current state.

But I think there is no such option, or I just didn’t see it?

You need to send these mqtt state messages with the retained flag set.

That way when Home Assistant starts it subscribes to the topics and gets pushed an immediate update.

Do not retain command messages for switches, covers and the like. Or you will get all sorts of weird ghost switching when home assistant starts.

1 Like

Hm, retaining these would retain them even after the sensor really disconnects, so the retained message could be long outdated. It would be nicer if HA could fetch an up to date state when starting.

That’s what the LWT message is for.

It can if you use a status command
I have an automation:

  - id: '1532478833428'
    alias: Power State Tasmota on HA Start-Up
    - event: start
      platform: homeassistant
    - service: script.turn_on
        entity_id: script.startupalltasmota

runs this script:

    alias: Tasmota Restore State at Startup
    - data:
        payload: ''
        topic: cmnd/sonoffs/state
      service: mqtt.publish
    - data:
        payload: ''
        topic: cmnd/nodemcu/state
      service: mqtt.publish

I use 2 different group topics, sonoffs and nodemcu

1 Like

If you subscribe to the homeassistant/status topic, HA will send ‘online’ and ‘offline’ messages whenever it (re)starts or goes offline

See MQTT - Home Assistant