Skip to content

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

by Kudzai Manditereza
12 min read

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 click on ‘Login’ on the main menu. 

A free HiveMQ Cloud account allows you to create an 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.

HiveMQ Cloud provide an email address and passwordAn 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. 

MQTT broker access credentialsYou 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. 

HiveMQ Cloud Cluster Details OverviewIf 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.

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

Visual Studio IDE Create a New ProjectGive your project a name and click on ‘Next.’ On the next page, you may continue .Net 6.0, selected under Framework.

Visual Studio IDE Configure Your New ProjectYou’ve successfully created an empty C# Console application. 

C# Console applicationTo 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.

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

‘Manage Nuget Packages.’Next, click on the Browse tab and search for HiveMQtt. Select the client from the results and then install it.

HiveMQtt on Visual Studio IDEYou’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. 

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.

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.

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”.

// 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.

//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

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.

C# console app successful connection to your MQTT brokerTo 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.

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

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

Displaying the published dataConclusion

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.

Chapters
  • 00:52 - Setting up a HiveMQ Cloud MQTT Broker
  • 02:57 - Creating C# .Net Console Application
  • 05:15 - Publishing and Subscribing to MQTT Messages

Get started with a complete MQTT platform for testing and small-scale IoT projects. Enjoy a 15-day free trial with exclusive features like unlimited connections, up to 1MB/s data throughput, 99.95% uptime, 24/7 support, client certificate authentication, and more.

Try HiveMQ Cloud Starter

Kudzai Manditereza

Kudzai is a tech influencer and electronic engineer based in Germany. As a Sr. Industry Solutions Advocate at HiveMQ, he helps developers and architects adopt MQTT and HiveMQ for their IIoT projects. Kudzai runs a popular YouTube channel focused on IIoT and Smart Manufacturing technologies and he has been recognized as one of the Top 100 global influencers talking about Industry 4.0 online.

  • Kudzai Manditereza on LinkedIn
  • Contact Kudzai Manditereza via e-mail
HiveMQ logo
Review HiveMQ on G2