So far we have discussed message payload, topic, and QoS. Another property of messages is retention.
When a message is marked for retention (using the -r flag in mosquitto_pub) and sent to a topic, the broker retains that message and the QoS for that topic. When a client then subscribes to that topic, the broker will send that message right away to the new client. The client can then receive the last known value of that topic, instead of waiting for the publisher to publish to that topic.
In summary: MQTT message retention is for when subscribers come late to the party!
Here's how to see this in action using three Terminal windows:
Window #1:mosquitto -v
Window #2:mosquitto_pub -d -h localhost -t home/living-room/temperature -r -m "Living room temperature"
Now, the publishing client has sent a retained message (because of the -r flag) then disconnected. When we subscribe to that same topic:
Window #3: mosquitto_sub -d -h localhost -t home/living-room/temperature
the client receives the "Living room temperature" message even though the publisher has already disconnected!
To change the retained message, just send another retained message on the same topic:
Window #2: mosquitto_pub -d -h localhost -t home/living-room/temperature -r -m "New temperature"
Note: sending a non-retained message will NOT change the retained message.
To delete the retained message, just send a retained message with zero length:
Window #2: mosquitto_pub -d -h localhost -t home/living-room/temperature -r -m ""
After that, new subscribers to that topic will NOT receive a retained message.
No comments:
Post a Comment