C# Client Library for Subscribing/Publishing MQTT

Introduction

MQTT (Message Queue Telemetry Transport) is a lightweight, publish-subscribe network protocol that is designed for use in constrained environments, such as IoT devices and mobile applications. It is an ideal solution for communicating between devices that need to exchange data over unreliable networks.
This article will guide you on using the C# client library for subscribing and publishing messages using MQTT.

C# MQTT Client Libraries

There are several C# client libraries available for interacting with MQTT brokers. Some popular options include:

  • MQTTnet
  • Paho.MQTT
  • uMQTT

MQTTnet Library

MQTTnet is a mature and feature-rich MQTT client library for .NET. It offers comprehensive functionality, including:

  • Publish/Subscribe
  • QoS support
  • Will messages
  • Last Will and Testament (LWT)
  • Secure connections (TLS/SSL)
  • MQTT 3.1.1 and 5.0 support

Installation

To use MQTTnet in your C# project, install the NuGet package:

Install-Package MQTTnet

Publishing Messages

The following code demonstrates how to publish a message using MQTTnet:

“`C#
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Client.Options;
using MQTTnet.Extensions.ManagedClient;

public class MqttPublisher
{
public async Task PublishAsync()
{
// Create an MQTT client
var mqttClient = new MqttFactory().CreateMqttClient();

// Create client options
var options = new MqttClientOptionsBuilder()
.WithClientId(“MyClientId”)
.WithTcpServer(“mqtt.example.com”, 1883)
.Build();

// Connect to the broker
await mqttClient.ConnectAsync(options);

// Create a message to publish
var message = new MqttApplicationMessageBuilder()
.WithTopic(“my/topic”)
.WithPayload(“Hello from C#”)
.WithQualityOfServiceLevel(MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce)
.Build();

// Publish the message
await mqttClient.PublishAsync(message);

// Disconnect from the broker
await mqttClient.DisconnectAsync();
}
}
“`

Subscribing to Messages

The following code demonstrates how to subscribe to a topic and receive messages using MQTTnet:

“`C#
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Client.Options;
using MQTTnet.Extensions.ManagedClient;

public class MqttSubscriber
{
public async Task SubscribeAsync()
{
// Create an MQTT client
var mqttClient = new MqttFactory().CreateMqttClient();

// Create client options
var options = new MqttClientOptionsBuilder()
.WithClientId(“MyClientId”)
.WithTcpServer(“mqtt.example.com”, 1883)
.Build();

// Connect to the broker
await mqttClient.ConnectAsync(options);

// Subscribe to a topic
var topicFilter = new MqttTopicFilterBuilder()
.WithTopic(“my/topic”)
.Build();

await mqttClient.SubscribeAsync(topicFilter);

// Handle incoming messages
mqttClient.ApplicationMessageReceived += async (s, e) =>
{
Console.WriteLine($”Received message on topic: {e.ApplicationMessage.Topic}”);
Console.WriteLine($”Payload: {e.ApplicationMessage.Payload}”);
};

// Wait for a while to receive messages
await Task.Delay(TimeSpan.FromSeconds(10));

// Disconnect from the broker
await mqttClient.DisconnectAsync();
}
}
“`

Paho.MQTT

The Paho.MQTT library is a popular and well-maintained option for MQTT communication in C#. It is also widely used for its reliability and performance.

uMQTT

uMQTT is a lightweight and efficient MQTT client library for .NET. It is suitable for applications with limited resources.

Comparison of Libraries

Here is a table that compares the different C# MQTT client libraries discussed:

Feature MQTTnet Paho.MQTT uMQTT
Functionality Comprehensive Well-rounded Lightweight
MQTT Versions 3.1.1, 5.0 3.1.1, 5.0 3.1.1
Security TLS/SSL TLS/SSL Basic authentication
Performance High High Efficient

Choosing the Right Library

When choosing an MQTT client library for your C# project, consider the following factors:

  • **Required features:** Do you need advanced features like QoS, Last Will and Testament, or secure connections?
  • **Performance requirements:** How critical is performance for your application?
  • **Resource constraints:** Are you working with a constrained environment?
  • **Community support:** Is there an active community around the library to provide assistance?

Conclusion

By using a C# MQTT client library, you can easily integrate your C# application with MQTT brokers to exchange messages in real-time, making it an efficient and flexible solution for various use cases, such as IoT applications, mobile apps, and more. This guide has provided a basic understanding of how to subscribe and publish messages using MQTT. Make sure to explore the documentation of the selected client library for comprehensive features and advanced usage patterns.

Leave a Reply

Your email address will not be published. Required fields are marked *