MQTT Samples - Retain
Both MQTT and XSockets support the retain flag
. Retain
means the server will store the value of the message as a last know good value
. This is useful for example when a sensor produces data with long intervals between messages.
Scenario without retain:
A sensor sends message every 30 minutes to the server. Just minutes after the last publish form the sensor a new client connects and subscribes to the topic that the sensor use. The client will now have to wait for almost 30 minutes to know the sensor value.
Scenario with retain:
A sensor sends message every 30 minutes to the server. Since the message has the retain flag set to true the server will store the message. Just minutes after the last publish form the sensor a new client connects and subscribes to the topic that the sensor use. The client will instantly get the last known good value
for the topic since the message was stored on the server.
Below we will extend the Publish & Subscribe 2 sample to use the retain flag.
MqttBridge
public class MyMqttBride : MqttBridge
{
private Sensor sensor;
public MyMqttBride()
{
sensor = new Sensor();
}
public override bool OnPublish(MqttClient client, MqttMsgPublishEventArgs e)
{
//Extract the message (we assume that it is JSON being sent in this sample)
var s = System.Text.Encoding.UTF8.GetString(e.Message);
//Create a IMessage
var m = new Message(s, e.Topic){Retain = e.Retain};
//Pusblih to XSockets and MQTT
sensor.PublishToAll(m);
sensor.MqttPublish(e.Topic, s);
// Deny the message to be published to MQTT clients (we already published)
return false;
}
}
XSockets Controller
The sensor controller can of-course have methods and logic, but in this sample it is not needed.
public class Sensor : XSocketController
{
}
Result
First we connect Mqtt.fx
, and subscribe to the topic home/+/temp
.
Then the Mqtt.fx
client publish a message with retain = true
on the topic home/kitchen/temp
and pass some JSON as payload. The Mqtt.fx client get the message back since we subscribe to the topic.
Then we connect Putty and subscribe to the topic home/+/temp
. Since there is a retained message for that topic we get the last know value back instantly.
Note that we did not have to publish to MQTT clients, we could just have been returning true instead of false.