MQTT switches and lights are not persistence

Hey,

I use Hass.io on the raspberry pi 3 with the Mosquito broker add on.
The switchtes and lights are working like a charm (use a lot of sonoff with tasmota).

But I have one problem:
If Home Assistant does a restart, the state of either the switch or the lights is not persistent. Meaning they are still “on” but Home Assistant does not know the state. I thougt the “retain” flag would solve this problem.

I looked at the add on Mosquito Broker Add On Repo and the persistence setting is enabled.

Also I am using the retain flag for the components:

light:

# Sonoff Basic
platform: mqtt
name: Star
command_topic: "cmnd/living-room/star/power"
state_topic: "stat/living-room/star/POWER"
payload_on: "ON"
payload_off: "OFF"
qos: "1"
retain: true

switch:

# Sonoff S20
platform: mqtt
name: 'Bathroom Socket'
command_topic: "cmnd/bathroom/socket/power"
state_topic: "stat/bathroom/socket/POWER"
payload_on: "ON"
payload_off: "OFF"
qos: "1"
retain: true

I don’t know about Tasmota but I use the Espurna firmware and inside the configs I have an option that sets what should be done by the Sonoff: turn on, turn off or remember last state.

Does Tasmota have the same config?

I think I got it.

I looked again into the Tasmota Wiki and found this info:

The power state message can be sent with the retain flag set. Enable this with cmnd/sonoff/PowerRetain on.

I think this did the trick. Just tested it with one sonoff.
Want to test the rest tomorrow.

Thanks @j.assuncao for heading me to the right direction!

1 Like

Is that the issue? I though that pertained to if the sonoff loses power, when the power is restored to the sonoff, it will turn the relay on. If HA restarts, the sonoff doesn’t lose power or see a change in mqtt command, its just HA doesn’t know which state the sonoff is in. I thought HA would ask mqtt on restart what the state is and adjust its state.

That’s exactly what HA does.

I thought HA would ask mqtt on restart what the state is and adjust its state.

I thought that too!
I testet it with one sonoff switch which got the “cmnd/sonoff/PowerRetain on” message.
Home Assistant got the right state after restarting.

The other switch, which did not get the message and Home Assistant did not get the right state.

I added this automation to get the state of sonoff switches when Home Assistant loads up:

- alias: "Power state on start-up"
  trigger:
    platform: homeassistant
    event: start
  action:
    - service: mqtt.publish
      data:
        topic: "cmnd/lamp/POWER"
        payload: ""
    - service: mqtt.publish
      data:
        topic: "cmnd/porchlight/POWER"
        payload: ""

Now when I restart HA, it knows the state of the switches from the MQTT request for an update.

2 Likes