MQTT : How to Retain Sonoff Switch Setting across Restarts of HA

I also have this retain problem. But after typing the ip of my sonoff into my browser, I get: “This site can’t be reached. xxx refused to connect”. I am running hass.io with the mosquitto broker. Any ideas?

Unfortunately that doesn’t work for me. The command mosquitto_sub -t "#" -v is not available to me because I run hass.io. I tried PowerRetain 1 in the sonoff tasmota console and retain: true in my yaml file without effect. Any ideas as to what it could be?

Are you using the add-on or the built in mqtt server. If it’s the built in one, ditch it and use the add-on as there are known issues with the other.

You don’t have to run mosquitto_sub on the same computer. You can do it on any windows, mac or linux computer where you can access your pi from. You just have to install mosquitto_clients.

Alternatively, there are MQTT client programs you can run on a smartphone that will do the same thing.

What you need to establish is what your sonoff is sending, and when.

The post by @ladaowner worked when I set this up a month or so ago. Also had no problems with the inbuilt hassio MQTT addon even though it’s widely disparaged here in the forums. I think there might be issues with the Hassbian MQTT component built into HA but I’m not aware of specific issues with the Hassio addon - other than general comments that the inbuilt server is shit. It’s worked without missing a beat for me here.

Thanks, the problem went away with the Hass.io add-on.

I’m not sure if I had this problem before or if something in one of the recent upgrades changed something but I’ve noticed some of my Sonoffs don’t retain their previous setting during a restart. I’ve been playing around with the various retains and such but on two of them I now did the opposite, I restarted HA and now the switched turned on instead.

So what’s the magical setting? It seems I have 3 different places for retaining a power state:

  1. Configuration.yaml has the retain: true or false flag
  2. MQTT broker configuration has the persistence true or false flag
  3. Tasmota itself has the Powerretain option to send the retain flag false or true to the MQTT broker.

I’m hoping to sit down with a spare Sonoff setup and development MQTT/HA install this weekend and try all the various configs and scenarios of switching it manually, through HA, etc with the different configs. If anyone has a setup of the three they use and works well feel free to share, going to dig back through this large thread and pick out some info.

This is what i’ve got and it works.

From what i understand, MQTT broker is a middle man, states are just passed from one end to another - no config as such for retaining power state on the broker.

My sonoffs were flashed with the below power retain flag, if you missed this…it can also be entered via sonoff console by entering the below command

PowerRetain 1

15%20PM

Switches.yaml or switch: is setup as below.

- platform: mqtt
  name: "Switch"
  command_topic: "cmnd/sonoff1/power"
  state_topic: "stat/sonoff1/POWER"
  availability_topic: "tele/sonoff1/LWT"
  qos: 1
  payload_on: "ON"
  payload_off: "OFF"
  payload_available: "Online"
  payload_not_available: "Offline"
  retain: true

FYI Im on hassio with a MQTT broker addon. Hope this helps…

1 Like

Thanks, I’ll make a few of those changes and see what happens. I read back through the thread and saw where folks were changing an option in MQTT to “listen” to the retain flag. I assume it has to do with the same persistence true/false flag in the MQTT configuration file.

"
persistence [ true | false ]
If true, connection, subscription and message data will be written to the disk in mosquitto.db at the location dictated by persistence_location. When mosquitto is restarted, it will reload the information stored in mosquitto.db. The data will be written to disk when mosquitto closes and also at periodic intervals as defined by autosave_interval. Writing of the persistence database may also be forced by sending mosquitto the SIGUSR1 signal. If false, the data will be stored in memory only. Defaults to false.

Reloaded on reload signal.

"

Just to clarify, if you haven’t got it already, the retain flag is set by the sender of a message. So if you set retain: true in configuration.yaml, messages sent from HA will have the retain flag set. Setting to option in the sonoff will ensure the state messages sent from the sonoff will have the retain flag set.

Ahh…that makes sense now that I think of it in the way you explained. So I have to set persistence on MQTT otherwise a cycle of it will cause the states to go away, so that’s the foundation. Then Tasmota has to speak back saying “Hey, retain my power state”. So MQTT saves it and when HA restarts it picks it back up upon sub to the state topic. HA then sends the command with a retain flag as well which should in theory keep the light on during any restarts.

The only other thing in play would be the state of the relay when the switch is rebooted. Whether it goes to the last state, ON, or OFF. Think I had it on the last state and one time I was pushing new firmware to my AP and the wife was asking why her lamp was blinking. I think it was due to the Tasmota rebooting after enough Wifi failures and she was seeing the relay cycle during reboot.

Will definitely give this a shot and see what all works out. Now if only Zigbee bulbs would always retain their status :slight_smile:

1 Like

Hallo,

I’m using this from https://github.com/arendst/Sonoff-Tasmota/wiki/Home-Assistant
This one simple code is for all sonoff devices and really find out the current status after restarting HA.

Power state on start-up without retain option
Edit automations.yaml and add:

- alias: "Power state on HA start-up"
  trigger:
    platform: homeassistant
    event: start
  action:
    - service: mqtt.publish
      data:
        topic: "cmnd/sonoffs/power1"
        payload: ""
    - service: mqtt.publish
      data:
        topic: "cmnd/sonoffs/power2"
        payload: ""
    - service: mqtt.publish
      data:
        topic: "cmnd/sonoffs/Power3"
        payload: "" 
    - service: mqtt.publish
      data:
        topic: "cmnd/sonoffs/power4"
        payload: ""

with no “PowerRetain” on tasmota and no retain in configuration.yaml
Function perfect!

8 Likes

This is just great. Works perfectly fine so far for my 15 or so sonoffs around the house

How can i send you a beer?
PS i’m sending on “sync” topic to the specific switch after hassio starts up. Then the switch sends back his status, so hassio knows the current status of the switch.
If the switch restarts, the “retain” flag will action the switch again, then it will send back his updated status to hassio. By doing this way, they are perfectly in sync now.

I don’t know why but for me was a little bit different. I had to put the group first then the prefix. Like this:

  • alias: “Power state on HA start-up”
    trigger:
    platform: homeassistant
    event: start
    action:
    • service: mqtt.publish
      data:
      topic: “sonoffs/cmnd/state”
      payload: “”
    • service: mqtt.publish
      data:
      topic: sonoffs/cmnd/POWER
1 Like

Tasmota changes the order of the topic depending on whether or not home assistant auto discovery is enabled or not. Noticed that in the wiki one day after being confused about it for a long time.

Hi, It is crazy how to fix it.

I have a blind switch loratap SW500, it is configured as sonoff dual, everything works fine but during night when HA restart my blind go up and wake up us, I can create the same scenario to check all possibilities but nothing works.
Now I’m testing powerretain OFF, HA blind configuration retain= OFF, and I included an automation to start up HA mqtt.
I checked it with everything to ON but with the same result after restart blind goes up.
How have you fix it?
@gabrielmiranda with your sketch in automation give me the same result.
@Daveee I checked out also your script but with the same results.

I put also the tasmota original sketch but the same…

- alias: "Power state on HA start-up"
  trigger:
    platform: homeassistant
    event: start
  action:
    - service: mqtt.publish
      data:
        topic: "cmnd/%shutters grouptopic%/shutterposition"
        payload: ""       
00:00:00 CFG: Loaded from flash at F5, Count 1119
00:00:00 SHT: Shutter 1 (Relay:1): Init. Pos: 52380 [97 %], Open Vel.: 100, Close Vel.: 100 , Max Way: 54000, Opentime 27.0 [s], Closetime 27.0 [s], CoeffCalc: c0: 300, c1 500, c2: 700, c3: 900, c4: 1000, binmask 3, is inverted 0, is locked 0, end stop time enabled 0, webButtons inverted 0, shuttermode 0, motordelay 0
00:00:00 Project tasmota Tasmota Version 8.1.0.11(tasmota)-STAGE
00:00:00 WIF: Connecting to AP1 MiFibra-0B4A in mode 11N as persiana-4269...
00:00:05 WIF: Connected
00:00:05 HTP: Web server active on persiana-4269 with IP address 192.168.1.120
11:13:06 MQT: Attempting connection...
11:13:06 MQT: Connected
11:13:06 MQT: tele/persiana/LWT = Online (retained)
11:13:06 MQT: cmnd/persiana/POWER = 
11:13:06 MQT: tele/persiana/INFO1 = {"Module":"SC500W","Version":"8.1.0.11(tasmota)","FallbackTopic":"cmnd/DVES_B450AD_fb/","GroupTopic":"cmnd/tasmotas/"}
11:13:06 MQT: tele/persiana/INFO2 = {"WebServerMode":"Admin","Hostname":"persiana-4269","IPAddress":"192.168.1.120"}
11:13:06 MQT: tele/persiana/INFO3 = {"RestartReason":"Software/System restart"}
11:13:06 MQT: stat/persiana/RESULT = {"POWER1":"OFF"}
11:13:06 MQT: stat/persiana/POWER1 = OFF
11:13:06 MQT: stat/persiana/RESULT = {"POWER2":"OFF"}
11:13:06 MQT: stat/persiana/POWER2 = OFF
11:13:06 SHT: Start in dir 0
11:13:06 MQT: tele/persiana/STATE = {"Time":"2020-08-25T11:13:06","Uptime":"0T00:00:08","UptimeSec":8,"Heap":27,"SleepMode":"Dynamic","Sleep":50,"LoadAvg":19,"MqttCount":1,"POWER1":"ON","POWER2":"OFF","Wifi":{"AP":1,"SSId":"MiFibra-0B4A","BSSId":"78:DD:12:AB:0B:4C","Channel":11,"RSSI":76,"Signal":-62,"LinkCount":1,"Downtime":"0T00:00:06"}}
11:13:06 MQT: stat/persiana/RESULT = {"POWER1":"ON"}
11:13:06 MQT: stat/persiana/POWER1 = ON
11:13:06 MQT: stat/persiana/RESULT = {"ShutterPosition1":100}
11:13:06 SHT: Shutter1 Real 52480, Start 52380, Stop 54000, Dir 1, Delay 0, Rtc 0.05 [s], Freq 0
11:13:06 MQT: stat/persiana/RESULT = {"Shutter1":{"Position":97,"Direction":1,"Target":100}}
11:13:06 MQT: stat/persiana/RESULT = {"ShutterOpen1":100}

This video saved me and I think that will save you for retain issue

So, I have also problem regarding “unknown” status after HA restart…

slika

When I click on sensor I can manualy set correct status:
slika

After I click on sensor or if automation set ON or OFF, after that status is correct…

Tasmota:

So, probably the problem is:

switch:

  - platform: mqtt
    name: "Zunaj - steber (luč)"
    state_topic: "stat/Sonoff-TH16-Steber/POWER"
    command_topic: "cmnd/Sonoff-TH16-Steber/POWER"
    availability_topic: "tele/Sonoff-TH16-Steber/LWT"
    qos: 1
    payload_on: "ON"
    payload_off: "OFF"
    payload_available: "Online"
    payload_not_available: "Offline"
    retain: false

sensor:

  - platform: mqtt
    name: "Zunaj-T"
    state_topic: "tele/Sonoff-TH16-Steber/SENSOR"
    value_template: '{{ value_json["AM2301"]["Temperature"] }}'
    unit_of_measurement: "°C"
  - platform: mqtt
    name: "Zunaj-V"
    state_topic: "tele/Sonoff-TH16-Steber/SENSOR"
    value_template: '{{ value_json["AM2301"]["Humidity"] }}'
    unit_of_measurement: "%"

What would be correct settings in my configuration…
Probably also enable PowerRetain, but not only this as this do not resolve my “unknown” status problem…

Can anybody help me to get correct sensor mqtt settings… Thank you…

Using the Console did it for me too - thanks!

My set up is for a delayed-stop bathroom air extractor fan. My wife wanted the ability to switch it off remotely (from the bath), but also that it comes on automatically, either all the time or if the humidity is too high (we have a separate Sonoff environment sensor in there, but it’s showing too high currently!). Because the extractor has live, ground and switched-live, the Sonoff is powered by the physical light switch and powers the switched-live of the extractor. The problem was that the Sonoff was retained the power off flag when the light switch was turned off. This posted solution works in this case, though I didn’t realise how the retain flag ended up being set to off, before I changed it.
Screencast from 2024-01-06 14-09-11