How to Build .Net IoT Apps Using C# MQTT Client

How to Build .Net IoT Apps Using C# MQTT Client

author Kudzai Manditereza

Written by Kudzai Manditereza

Category: MQTT IoT Dot Net MQTT Client for C Sharp

Published: May 18, 2023

In this article, I’ll guide you through building a .Net IoT application using a C# MQTT Client library. With a focus on technical details, we’ll provide step-by-step instructions for creating a .Net Console application, generating telemetry data, converting it into JSON, and utilizing the HiveMQ MQTT Client library for C#.

I’ll start by discussing the key components of the .Net Console application and how they interact with MQTT Brokers. Then, we’ll dive into generating temperature and humidity telemetry data, emphasizing accuracy and precision.

Next, I’ll explore the conversion of telemetry data into a JSON object and its significance in data exchange protocols. You’ll gain a solid understanding of the process and its benefits for MQTT communication.

We’ll then introduce the HiveMQ MQTT Client library for C#, showcasing its features for publishing data to a HiveMQ Cloud MQTT Broker. With code snippets and explanations, we’ll help you leverage its capabilities for optimal performance and reliability.

Finally, I’ll cover the MQTT topic structure and demonstrate the process of subscribing to a topic on the MQTT Broker, enabling bidirectional communication in the cloud.

By providing concise instructions, code examples, and a deep exploration of the technologies involved, I aim to equip you with the knowledge and skills to develop robust IoT solutions using .Net and the HiveMQ MQTT Client library for C#.

Setting up a HiveMQ Cloud MQTT Broker

To begin, you’ll need to set up a HiveMQ Cloud MQTT broker to handle messages to and from your C# IoT application. Go to the HiveMQ website and select ‘Cloud’ on the menu. 

A free HiveMQ Cloud account allows you to create two MQTT broker clusters and connect up to 100 devices. On the HiveMQ Cloud page, click  ‘Try out for free’ button. 

If you are accessing the HiveMQ Cloud portal for the first time, you must provide an email address and password and follow the simple steps to confirm your email and create your account.

An MQTT broker cluster will automatically be created when you complete your account setup. Establish your credentials to allow devices to connect to your MQTT broker. 

You can do that by specifying the username and password and clicking on ADD

Next, clicking on ‘Overview’ will provide the connection settings needed to connect your C# application to the HiveMQ Cloud MQTT broker cluster. So you need to copy the cluster URL, the port number, and take note of your username and password for use in your C# code. 

If you wish to update your connection credentials, you can always log in to your portal, click  ‘MANAGE CLUSTER,’ and select ‘ACCESS MANAGEMENT’.

And that’s it; your MQTT broker is set up and ready to coordinate messaging for your IoT application.

Now you can start building your C# application to act as an MQTT Client, publishing and receiving messages from the HiveMQ Cloud MQTT broker.

Creating C# .Net Console Application

You’ll require a development platform to build your code to get started. While Visual Studio Code can serve this purpose, I will utilize Visual Studio IDE for demonstration. If you don’t have Visual Studio installed on your computer, you can easily obtain it from the Visual Studio website. Simply download the free-to-use Community edition and follow the installation instructions.

Now, open your Visual Studio IDE, and select Console App to create a new project. Under project types, select C# Console App.

Give your project a name and click on ‘Next.’ On the next page, you may continue .Net 6.0, selected under Framework.

You’ve successfully created an empty C# Console application. 

To develop this application and enable communication with other IoT devices and applications using MQTT, your first step is to install the HiveMQ MQTT client library. This library will empower your application with the necessary capabilities for seamless MQTT integration.

Installing and Configuring HiveMQtt C# MQTT Client Library

The HiveMQtt MQTT client for C# is open source (available on Github) and licensed under the permissive Apache 2.0 License. The client features full MQTT 5.0 support and is compatible with all major MQTT brokers.

The good news is that this package is also available on NuGet.org, which means you can easily install it using the .Net NuGet Package Manager. The NuGet Package Manager simplifies managing dependencies in your .Net projects, allowing for convenient installation and updates. This ensures a smooth and streamlined experience, enabling you to integrate the HiveMQ MQTT client library effortlessly into your application, and you install it with .Net Nuget Package Manager as I’ll demonstrate next.

To add the HiveMQ MQTT client to your C# application, right-click on your project in Solution Explorer and select ‘Manage Nuget Packages.

Next, click on the Browse tab and search for HiveMQtt. Select the client from the results and then install it.

You’ve successfully installed the HiveMQ MQTT client for C#. Now you can begin developing your IoT application.

Publishing and Subscribing to MQTT Messages 

Let’s look at the complete C# code for publishing and subscribing to messages from your HiveMQ Cloud MQTT broker using the HiveMQtt MQTT client library. Go to your empty Program.cs file and perform the following steps. 

First, include assembly references to import the HiveMQtt client library into your code. 

1
2
3
4
5
using HiveMQtt.Client;
using HiveMQtt.Client.Options;
using HiveMQtt.MQTT5.ReasonCodes;
using HiveMQtt.MQTT5.Types;
using System.Text.Json;

Next, create a new HiveMQClientOptions object to enter the connection details of your HiveMQ Cloud MQTT broker, followed by an instantiation of a HiveMQClient.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
var options = new HiveMQClientOptions
{
    Host = "81b8283f2a154f549a4337bd921c5da4.s2.eu.hivemq.cloud",
    Port = 8883,
    UseTLS = true,
    UserName = "admin",
    Password = "password",
};

var client = new HiveMQClient(options);

Once complete, you can connect to your MQTT broker and display your connection status on the console.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
Console.WriteLine($"Connecting to {options.Host} on port {options.Port} ...");

// Connect
HiveMQtt.Client.Results.ConnectResult connectResult;
try
{
    connectResult = await client.ConnectAsync().ConfigureAwait(false);
    if (connectResult.ReasonCode == ConnAckReasonCode.Success)
    {
        Console.WriteLine($"Connect successful: {connectResult}");
    }
    else
    {
        // FIXME: Add ToString
        Console.WriteLine($"Connect failed: {connectResult}");
        Environment.Exit(-1);
    }
}
catch (System.Net.Sockets.SocketException e)
{
    Console.WriteLine($"Error connecting to the MQTT Broker with the following socket error: {e.Message}");
    Environment.Exit(-1);
}
catch (Exception e)
{
    Console.WriteLine($"Error connecting to the MQTT Broker with the following message: {e.Message}");
    Environment.Exit(-1);
}

Next, define a message handler method for receiving MQTT messages from the cloud followed by a subscription to the topic “hivemqdemo/commands”.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// Message Handler
client.OnMessageReceived += (sender, args) =>
{
    string received_message = args.PublishMessage.PayloadAsString;
    Console.WriteLine(received_message);

};

// Subscribe
await client.SubscribeAsync("hivemqdemo/commands").ConfigureAwait(false);

Proceed to create and initialize temperature and humidity variables, which will serve as containers for the telemetry data to be published to the MQTT broker. Additionally, you will instantiate a random number generator that will be utilized for generating the precise telemetry values.

1
2
3
4
//initialise telemetry values
double temperature = 25.1;
double humidity = 77.5;
var rand = new Random();

Finally, create an endless loop that generates random telemetry data for temperature and humidity, converts the data into an object, serializes it into JSON, and then publishes the data to the MQTT broker under the topic “hivemqdemo/telemetry

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
Console.WriteLine("Publishing message...");

while (true)
{
    double currentTemperature = temperature + rand.NextDouble();
    double currentHumidity = humidity + rand.NextDouble();
    var msg = JsonSerializer.Serialize(
        new
        {
            temperature = currentTemperature,
            humidity = currentHumidity,
        });
//Publish MQTT messages
    var result = await client.PublishAsync("hivemqdemo/telemetry", msg, QualityOfService.AtLeastOnceDelivery).ConfigureAwait(false);

}

When you run your C# console app, you should get a successful connection to your MQTT broker.

To check if your application is publishing messages to the cloud you can use an MQTT test application such as MQTT.fx. When you subscribe to the HiveMQ Cloud MQTT broker you should see data published to it.

Next, you can test whether your application can receive MQTT messages by publishing data to the HiveMQ Cloud MQTT broker. 

When you do that your console app should receive and display the published data.

Conclusion

You have now gained a comprehensive understanding of building .Net IoT applications using the C# MQTT Client. We encourage you to download and explore the HiveMQ C# MQTT client. If you have any questions or encounter any issues, our Community Forum and Github repository are available to support you. By applying the knowledge gained from this guide, you are well-equipped to embark on your IoT development journey with confidence.

Watch my video below to get a hands-on view on how to build a .Net IoT application using a C# MQTT Client library. 

author Kudzai Manditereza

About Kudzai Manditereza

Kudzai is an experienced Technology Communicator and Electronic Engineer based in Germany. As a Developer Advocate at HiveMQ, his goals include creating compelling content to help developers and architects adopt MQTT and HiveMQ for their IIoT projects. In addition to his primary job functions, Kudzai runs a popular YouTube channel and Podcast where he teaches and talks about IIoT and Smart Manufacturing technologies. He has since been recognized as one of the Top 100 global influential personas talking about Industry 4.0 online.

Follow Kudzai on LinkedIn

mail icon Contact Kudzai
newer posts The Power of Data Management in Driving Smart Manufacturing Success
The Ultimate Guide on How to Use MQTT with Node.js older posts