letscontrolit / ESPEasy

Easy MultiSensor device based on ESP8266/ESP32
http://www.espeasy.com
Other
3.26k stars 2.21k forks source link

Workaround to recover states after reset or power cycle with MQTT #3029

Open svmac opened 4 years ago

svmac commented 4 years ago

This is not really an issue but a proposal for improvement.

Through the MQTT retention flag we can send a command and when the module restarts and reconnects to MQTT it will receive the same command again:

mqtt_pub -r myEspEasy/in/cmd event,LIGHT1_ON

The problem is that the retention only retains one value per topic, and in this case the topic is always the same (.../in/cmd). It would be necessary to be able to send different command topics.

An easy solution is to have EspEasy process any topic that starts with 'cmd', making this simple change in controller 005 (file _C005.ino):

Change the line: if (lastPartTopic == F("cmd")) { For this: if (lastPartTopic.startsWith(F("cmd"))) {

In this way we can send commands with different topics and with retention activated:

mqtt_pub -r myEspEasy/in/cmdL1 event,LIGHT1_ON mqtt_pub -r myEspEasy/in/cmdL2 event,LIGHT2_OFF

I use openHAB and I have 2 brokers configured pointing to the same server, one with retain=false and the other with retail=true. Then in the items I use a broker or another depending on what I need.

uzi18 commented 4 years ago

Or use topic with espbackup prefix as save state?

svmac commented 4 years ago

Or use topic with espbackup prefix as save state?

@uzi18 sorry I have searched about espbackup and found nothing, can you give an example?

uzi18 commented 4 years ago

it is proposal like yours :) to save/restore all into topics like: espbackup/%hostname%/%tasknum%/%valnum% or .... implement json-like string to get/set all tasks+valnumber+value at once (so less overhead)

svmac commented 4 years ago

I see ... I think my idea is simpler

GravityRZ commented 4 years ago

does the MQTT server retain a message when it also looses power. i have had that last week (total power failure) .

so if you loose the last message in case of a total power failure then i would rather opt for a cache controller solution(which works in any situation)

TD-er commented 4 years ago

If the MQTT broker is also rebooted, then it all depends on the configuration and implementation of that broker whether the retained messages are... retained.

I guess a broker running on a Raspberry Pi (on SD card) will try not to save the retained messages as it will cause a lot of writes and thus wear out the flash quite fast.

svmac commented 4 years ago

I have a linux pc server with mosquitto MQTT broker and yes, it retains all retained messages after power failure.

TD-er commented 4 years ago

Like I said it may be a disabled feature on a Pi, but good to know it is at least a setting that can be enabled if needed.