Using UNIQO as an MQTT client

MQTT (MQ Telemetry Transport o Message Queue Telemetry Transport) è un protocollo standard ISO di messaggistica leggero di tipo publish-subscribe basato su un message broker, che è responsabile della distribuzione dei messaggi ai client destinatari.

In questo tutorial viene spiegato come configurare UNIQO come client MQTT.

Installazione MQTT su UNIQO

Tramite la libreria M2MQtt è possibile utilizzare un progetto UNIQO come client MQTT. Per l’utilizzo di librerie di terze parti su UNIQO fare riferimento a Use third party .NET libraries.

Configurazione IP del message broker

Per la configurazione del message broker creare una nuova variabile di modello sotto Model chiamata BrokerIpAddress di tipo String e come valore inserire l’indirizzo IP del message broker.

Configurazione publisher

Creare un NetLogic sotto la MainWindow chiamato PublisherLogic, quindi aprire il progetto con Visual Studio e inserire il seguente codice:

#region StandardUsing
using System;
using QPlatform.CoreBase;
using QPlatform.HMIProject;
using UAManagedCore;
using OpcUa = UAManagedCore.OpcUa;
using QPlatform.NetLogic;
using QPlatform.UI;
using QPlatform.OPCUAServer;
#endregion
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;

public class PublisherLogic : BaseNetLogic
{
    public override void Start()
    {
        var brokerIpAddressVariable = Project.Current.GetVariable("Model/BrokerIpAddress");

        // Create a client connecting to the broker (default port is 1883)
        publishClient = new MqttClient(brokerIpAddressVariable.Value);
        // Connect to the broker
        publishClient.Connect("UNIQOPublishClient");
        // Assign a callback to be executed when a message is published to the broker
        publishClient.MqttMsgPublished += PublishClientMqttMsgPublished;
    }

    public override void Stop()
    {
        publishClient.Disconnect();
        publishClient.MqttMsgPublished -= PublishClientMqttMsgPublished;
    }

    private void PublishClientMqttMsgPublished(object sender, MqttMsgPublishedEventArgs e)
    {
        Log.Info("Message " + e.MessageId + " - published = " + e.IsPublished);
    }

    [ExportMethod]
    public void PublishMessage()
    {
        var variable1 = Project.Current.GetVariable("Model/Variable1");
        variable1.Value = new Random().Next(0, 101);

        // Publish a message
        ushort msgId = publishClient.Publish("/my_topic", // topic
            System.Text.Encoding.UTF8.GetBytes(((int)variable1.Value).ToString()), // message body
            MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, // QoS level
            false); // retained
    }

    private MqttClient publishClient;
}

Il codice riportato preleva il valore da pubblicare da una variabile di modello, pertanto è necessario creare sotto la cartella Model una variabile di nome Variable1 di tipo Int32.

Per effettuare il publish del messagio, creare un pulsante chiamato PublishButton nella MainWindow ed istanziare su di esso un MouseClickEvent con il metodo PublishMessage di PublisherLogic.

Configurazione subscriber

Creare un NetLogic sotto la MainWindow chiamato SubscriberLogic, quindi aprire il progetto con Visual Studio e inserire il seguente codice:

#region StandardUsing
using System;
using QPlatform.CoreBase;
using QPlatform.HMIProject;
using UAManagedCore;
using OpcUa = UAManagedCore.OpcUa;
using QPlatform.NetLogic;
using QPlatform.UI;
using QPlatform.OPCUAServer;
#endregion
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;

public class SubscriberLogic : BaseNetLogic
{
    public override void Start()
    {
        var brokerIpAddressVariable = Project.Current.GetVariable("Model/BrokerIpAddress");

        // Create a client connecting to the broker (default port is 1883)
        subscribeClient = new MqttClient(brokerIpAddressVariable.Value);
        // Connect to the broker
        subscribeClient.Connect("UNIQOSubscribeClient");
        // Assign a callback to be executed when a message is received from the broker
        subscribeClient.MqttMsgPublishReceived += SubscribeClientMqttMsgPublishReceived;
        // Subscribe to the "my_topic" topic with QoS 2
        ushort msgId = subscribeClient.Subscribe(new string[] { "/my_topic" }, // topic
            new byte[] { MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE }); // QoS level

        messageVariable = Project.Current.GetVariable("Model/Message");
    }

    public override void Stop()
    {
        subscribeClient.Unsubscribe(new string[] { "/my_topic" });
        subscribeClient.Disconnect();
    }

    private void SubscribeClientMqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
    {
        messageVariable.Value = "Message received: " + System.Text.Encoding.UTF8.GetString(e.Message);
    }

    private MqttClient subscribeClient;
    private IUAVariable messageVariable;
}

Creare una nuova variabile di modello nella cartella Model chiamata Message di tipo stringa. Infine creare un’etichetta chiamata SubscribeLabel e un collegamento dinamico della sua proprietà Testo con la variabile Message precedentemente creata.

Scarica il progetto di esempio da qui.