Language: EN

como-usar-el-protocolo-mqtt-con-c-y-la-libreria-mqttnet

How to use the MQTT protocol with C# and the MQTTNET library

MQTTNet is a .NET library that allows us to implement communication using the MQTT protocol, acting as both a client and a broker.

The library is one of the most complete available for .NET. It is designed to be lightweight and highly efficient, capable of handling tens of thousands of messages per second.

MQTTNet supports MQTT protocol versions 3.1.0, 3.1.1, and 5.0.0, as well as communication over both TCP and Websockets, in both cases with or without TLS.

It is cross-platform and compatible with .NET Standard 1.3+, .NET Core 1.1+, .NET Framework 4.5.2+, Xamarin.Android 7.5+, Mono 5.2+, among others. Therefore, it can be run on Windows, Linux, and macOS.

Using MQTTNet

We can easily add the library to a .NET project through the corresponding Nuget package.

Install-Package MQTTnet

The library provides extensive documentation on the project’s website, including numerous usage examples in the wiki https://github.com/chkr1011/MQTTnet/wiki.

However, a simple example of usage would be as follows.

public class MqttService
{
    IMqttClient mqttClient;
     
    public async Task Start(string brokerIp, string clientId, Action<string> callback = null)
    {
        var factory = new MqttFactory();

        var options = new MqttClientOptionsBuilder()
        .WithTcpServer(brokerIp)
        .WithClientId(clientId)
        .Build();

        mqttClient = factory.CreateMqttClient();

        mqttClient.ConnectedAsync += (async e =>
        {
            Console.WriteLine("MQTT connected");
            Console.WriteLine("");
            await mqttClient.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic("my/topic/receive").Build());
        });

        mqttClient.ApplicationMessageReceivedAsync += (async e =>
        {
            var payload = Encoding.UTF8.GetString(e.ApplicationMessage.PayloadSegment);

            Console.WriteLine("Received MQTT message");
            Console.WriteLine($" - Topic = {e.ApplicationMessage.Topic}");
            Console.WriteLine($" - Payload = {payload}");
            Console.WriteLine($" - QoS = {e.ApplicationMessage.QualityOfServiceLevel}");
            Console.WriteLine($" - Retain = {e.ApplicationMessage.Retain}");
            Console.WriteLine("");

            callback?.Invoke(payload);
        });

        mqttClient.DisconnectedAsync += (async e =>
        {
            Console.WriteLine("MQTT reconnecting");
            await Task.Delay(TimeSpan.FromSeconds(5));
            await mqttClient.ConnectAsync(options, CancellationToken.None);
        });

        await mqttClient.ConnectAsync(options, CancellationToken.None);
    }

    public async Task SendCode(string message)
    {
        var topic = "my/topic/send";

        Console.WriteLine("Publish MQTT message");
        Console.WriteLine($" - Topic: {topic}");
        Console.WriteLine($" - Payload: {message}");
        Console.WriteLine("");

        var applicationMessage = new MqttApplicationMessageBuilder()
          .WithTopic(topic)
          .WithPayload(message)
          .Build();
        await mqttClient.PublishAsync(applicationMessage);
    }
}

With this example service that we have created, the usage from a console application, for example, would be as simple as this.

MqttService mqttService = new();

string clientId = Guid.NewGuid().ToString();
await mqttService.Start("your_broker_address", clientId, async (m) =>
{
        // do something with the received message
});

Console.ReadLine();

MQQTNet is Open Source under the MIT license and all the documentation and project code can be found at https://github.com/chkr1011/MQTTnet.