When designing reliable systems using MQTT (Message Queuing Telemetry Transport), it’s important to know whether your devices are online.
Birth and Death messages are special messages that help communicate the state of a device to other clients in a MQTT network.
The MQTT protocol has provision for death messages known as last will and testament but not birth messages.
Birth messages are part of the Sparkplug specification and are sent by the MQTT client and are normal MQTT messages with a specific format.
Birth and Death Message Formats
Birth Messages are sent by a client when it connects (or reconnects) to an MQTT broker, signalling that it’s alive and ready to communicate.
Death Messages are published by the broker on behalf of the client when the client unexpectedly disconnects (e.g., due to a crash or power failure).
A last will and testament message requires:
- a Topic
- A message
- A QOS level (quality of service)
- A message Retain setting.
Birth messages follow the same format.
Example
Birth messages
Topic=topic_base/connection
Message=online
QOS=0
Retain=true
Death messages
Topic=topic_base/connection
Message=offline
QOS=0
Retain=true
Example Implementation Using Python
It can easily be added to existing code in the on_connect callback. Here is my code with the addition.
def on_connect(client, userdata, flags, rc): logging.debug("Connected flags"+str(flags)+"result code "\ +str(rc)+"client1_id") if rc==0: client.connected_flag=True client.publish(connection_topic,"online",0,retain=True) else: client.bad_connection_flag=True
We also need to Set the last will message.Payload is 0 and we use the retain flag.
client.will_set(connected_topic,"offline",0, retain=True) #set will
The last will will take care of an abnormal disconnect. For a normal disconnect we need to remember to update the status before we disconnect as follows:
client.publish(connection_topic,0,retain=True) client.disconnect()
Note: The retain flag should be set in both messages to ensure new subscribers get the current state.
Example implementation including Python Code.
The checking active connections tutorial has an example and also suggestions on making the message more useful.
Related Tutorials
- Using The Mosquitto_pub and Mosquitto_sub MQTT Client Tools- Examples
- MQTT Retained Messages Explained
- MQTT Last Will and Testament Examples
- Understanding MQTT Topic Naming and Design Notes
- Introduction to MQTT +Sparkplug For IIOT