Last Will and Testament
Overview
Last Will and Testament (LWT) is a powerful feature in MQTT that allows clients to specify a message that will be automatically published by the broker on their behalf, if or when an unexpected disconnection occurs.
It provides a reliable means of communication and ensures that clients can gracefully handle disconnections without leaving topics in an inconsistent state. This feature is particularly valuable when clients must notify others of their unavailability or convey important information upon an unexpected disconnection, reference HiveMQ.
Joule supports a consumer LWT handler feature by providing a dedicated DSL attribute, and lwt handler.
Example
In this example, the lwt handler feature is configured for the MQTT consumer.
It specifies that a MQTT publisher disconnects unexpectedly, a message will be sent to the topic sensors/groundfloor/+/status to notify subscribers of the disconnection.
The custom handler will be called when a message has been received on the LWT topic.
This snippet configures the client to process all ground floor room sensors, using the topic wildcard, LWT messages using the SensorOfflineHandler custom class.
mqttConsumer:
...
lwt handler:
topic: sensors/groundfloor/+/status
handler: com.fractalworks.streams.example.SensorOfflineHandler
properties:
message: "Ground floor sensor status: {}"
qos: 1Simple implementation of a MQTTLastWillTestamentHandler interface which uses passed in properties that provide a custom log message using the MqttMessage as a parameter.
public class SensorOfflineHandler implements MQTTLastWillTestamentHandler {
private final Logger logger = LoggerFactory.getLogger(SensorOfflineHandler.class.getName());
public SensorOfflineHandler() {
// REQUIRED
}
@Override
public void onMessage(String topic, MqttMessage mqttMessage) {
if(properties != null && properties.containsKey("message")) {
logger.info(properties.getProperty("message"), mqttMessage);
} else {
logger.info("Received MQTT LWT message {}", mqttMessage);
}
}
@Override
public void setProperties(Properties properties) {
this.properties = properties;
}
}Handler attributes schema
These attributes provide the configuration parameters to receive and process LWT disconnection notifications.
topic
Topic LWT messages are received on
String
handler
Custom handler which processes the LWT message. This is a fully qualified class string i.e. com.fractalworks.streams.example.SensorOfflineHandler
String
properties
Set of properties required by the handler
Long
Default: 5 seconds
qos
Quality of service
Integer
Default: 1
Last updated
Was this helpful?