MQTT is designed for situations with less-than-perfect networks and finicky clients, so there should be a way to send a notification when a client abruptly disconnects. This is what the Last Will and Testament (LWT) feature is all about.
What do we mean by an abrupt or unexpected disconnection? This is when the client disconnects without sending the DISCONNECT command message. For example, if the clients are battery-operated sensors, a sensor would abruptly disconnect when the battery dies.
When a client connects to a broker, there is the option to specify that a message be sent to a specific topic when that client ungracefully disconnects. Using mosquitto_pub and mosquitto_sub, the LWT message is set with the flag --will-payload
, and the topic to which it will be sent is specified with the --will-topic
flag. It is also possible to specify the QoS level of the message when it gets sent to the LWT topic. This is controlled with the --will-qos
flag, which defaults to QoS 0.
Suppose a client connects to the broker and specifies a LWT topic and message (payload). Should that client unexpectedly go offline, then the LWT message is published to the LWT topic by the broker. The client cannot send that message since it has disconnected!
If the client does indeed send a DISCONNECT message, the broker will close the connection and discard that client's LWT message and will not send a message to the LWT topic.
Here is a good way to use LWT:
- Create a special client that is subscribed to a topic named like "home/sensor-problems".
- All new clients, when they connect to the broker, specify "home/sensor-problems" as their LWT topic, and set the LWT to be that client's ID.
- By monitoring the "home/sensor-problems" topic, we will be alerted to when a sensor has problems.
We can test LWT by opening four Terminal windows and run the following commands:
Window #1:mosquitto -v
Window #2:mosquitto_sub -d -h localhost -t home/sensor-problems
Window #3:mosquitto_sub -d -i Subscriber123 -h localhost -t home/living-room/temperature --will-topic home/sensor-problems --will-payload "Problem with Subscriber123"
Then press Control-C to stop the client running in Window #3. This will generate an unexpected disconnection, and the message "Problem with Subscriber123" will be published to the client running in Window #2.
No comments:
Post a Comment