What Last Will and Testament?
So, this is built in into the protocol and this is really unique.
The client creates its last will and testament which means the actual message that should be sent by the broker on behalf of the client is defined on connection establishment by a specific client and if this client disconnects unrestful for any reason. The broker would notice and would then publish a MQTT packet on the specified topic. So, other MQTT clients get the chance to understand that this specific client is offline.
Let’s look at the connect packet,
So, the connect packet has four different properties. You can set for last will and testament. Last will testament is an optional feature you don’t need to do this but if you want to use it. It’s a really great feature for error detection. So, if you want to use it, then you need to set in the MQTT connect packet. The will topic which is the topic of the MQTT message. The broker should send on behalf of the client. The will payload which is the actual content of the message and then you can set the quality of service level. So, this is a quality of service zero one or two message and you can set the retained flag also for disconnect packet.
When to use last will and testament?
For example, you could implement an online/offline mechanism to understand if a client is online. So, let’s assume directly after connection establishment. A MQTT client would send the MQTT publish packet which says online for the topic which is named after the device with a retained message to true. So, every subscriber would then see that this client is currently online and you could then also add a offline packet to the will. Which means you put on the same topic. You put the payload offline also with the will retain to true into the connect packet and then as soon as your client disconnects ungraceful. The broker would send it to the topic and everybody who’s interested in it would directly notify.
The great thing is the broker pushes this information. This means as soon as the connection breaks between one of your devices you will get an instant notification and so you have a reliable online offline mechanism.
Also Read: Features of MQTT