Using MQTT and retrieving last published value

Hi all,

I just started playing around with MQTT and it's so amazing. I just wonder if there's a way to use it to remember a devices previous state. Say, you lost connection, power or the device was reset. I'm thinking its best to retrieve the last state and replicate it. So for a ESP8266 that had a light on, once reset, it should subscribe to the "state" topic again and see the last state was "on" and turn the light on again.

Can anyone point me to some resources to learn how to subscribe and retrieve the last item in a topic on boot up?

I'm not even sure if that's a good idea. What do you think? Here are the options I've considered:

  • Default to some factory value every time, regardless of it's previous state
  • Retrieve the last state from the MQTT topic and default back to that
  • Store it's last state in EEPROM and default to that

Or is it better to default to the last command sent to it? And what happens if it's offline, I attempt to turn it on and off several times through a topic, then it comes back online... Is there a best practice concept when it comes to this?

Can anyone point me to some resources to learn how to subscribe and retrieve the last item in a topic on boot up?

I suggest searching for "mqtt retained messages". Another useful mqtt feature is called "last will".

CheeseNWine:
I'm not even sure if that's a good idea. What do you think? Here are the options I've considered:

[/li]

Hi there,
I have same problem that you had.
I must set a switch from retained MQTT message when I power on a NodeMCU

Have you solved please ?

Thanks in advance
Denis