Team XSockets.NET

MQTT Samples - QoS

In MQTT Quality of Service means that you can flag the message to be handled a certain way. There is 3 levels in MQTT.

  • Fire and forget
  • At least once
  • Exactly once

XSockets currently supports the first 2 levels, so you can not pass in Exactly Once into XSockets from the MqttBridge.

Example

In this sample we will send a message from MQTT to XSockets with QoS = At least once and also send a message from XSockets to MQTT with QoS = At least once. XSockets C# and JavaScript implementation supports QoS, but since we use Putty in the sample we will fake QoS support.

We will extend the sample used in previous sections to show this.

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, QoS = (QoS)e.QosLevel };

        //Pusblih to XSockets and MQTT
        sensor.PublishToAll(m);
        sensor.MqttPublish(e.Topic, s);

        // Deny the message to be published to MQTT clients
        return false;
    }    
}

XSockets Controller

The sensor controller just overrides the OnMessage, in real life you will probably have methods with complex objects as parameters. Since we do not have any business logic for the data we can settle for OnMessage

public class Sensor : XSocketController
{
    public override async Task OnMessage(IMessage message)
    {
        // Do this since Putty cant set that flag
        message.QoS = QoS.AtLeastOnce;
        // Publish to XSockets
        await this.PublishToAll(message);        
        // Publish to MQTT
        this.MqttPublish(message.Topic, message.Data, message.QoS, message.Retain);
    }
}

Result

First we connect Mqtt.fx and subscribe to the topic home/+/temp with QoS = 1.

mqtt qos 1

Then the Mqtt.fx client publish a message on the topic home/kitchen/temp with QoS = 1 and retain = true.

The message is received at the MqttBridge. The bridge then publish to both XSockets clients and MQTT clients. No XSockets client is currently connected to only the MQTT client get the message.

mqtt qos 2

Then we connect Putty and tell the connection that QoS is enabled. This will make the server use QoS for the specific connection.

When we subscribe to the topic home/+/temp the server will send back the retained messages for the topic.

mqtt qos 3

Now we send a message from Putty with the topic home/basement/temp. This message will be sent to both MQTT.fx and Putty (since they both subscribe).

mqtt qos 4

results matching ""

    No results matching ""