Overview
In this post, I show how to use the MQTT Retain message to simplify an IoT system.
I will use a Smart Home example to explain this topic.
We have two “smart” light bulbs connected to the MQTT Broker.
Based on the structure of our IoT system, we defined the following general MQTT Topic structure:
OWNER_ID/HOUSE_ID/ROOM_ID/light
So the Topic structure for this specific deployment is following:
owner_abc/house_1/room_a/light
The Owner can use an Application to change the color of light in a specified Room.
We need to ensure that all bulbs in a Room will have the same color.
The Application sends a message to specified Room Topic with Payload defining the color of light:
|
|
Retain Messages
During MQTT publish, the Application set the RETAIN flag. This means that the Broker will keep the MQTT message after sending it to all active Subscribers.
The MQTT message is delivered to all active Subscribers, and also any new Device that subscribes to this MQTT Topic in the future.
⚠️Very important: Only one Retained Message can be saved per Topic! Future Retained Messages sent to this Topic will replace an existing Retained Message.
Publishing a new Retained Message with an empty payload will remove the currently Retained Message from topic.
Going back to our example; all connected bulbs received the MQTT message and turned green.
The User lived happily ever after till… one of the bulbs got broken!
Facing a hardware related issue, the User decided to buy a new bulb and connect it to the IoT system.
By default, the bulb’s light color is white. Do you think that our User should use the App to change the color to green?
Wait a minute, we used the Retained Messages in our IoT system! Our MQTT Broker stored that Message and will send it to any new device subscribed to the specified MQTT Topic!
And the magic happened!
Mosquitto example
Let’s use the Mosquitto MQTT Broker to see Retained Messages in action.
Eclipse Mosquitto is an open source (EPL/EDL licensed) message broker, you can download it from this link.
Start the Mosquitto Broker:
|
|
Subscribe as the Bulb001:
|
|
Set Bulb’s color to green using MQTT Retained Message:
|
|
Subscribe as the new Bulb002 (after the initial MQTT message was sent):
|
|
You should receive the Retained MQTT Message:
Video
Summary
This MQTT feature allows simplifying the logic on the Edge. Devices will receive the MQTT message once they subscribe to the specified topic (even if they were not online when a message was actually sent).
The Cloud/Backend logic can also be simplified - you can send the device configuration once and it will be delivered to every existing and future device.
I hope that my explanation of Retained Messages was interesting for you.
Feel free to reach out in case of any questions!