How to Build .Net IoT Apps Using C# MQTT Client
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.
Next, create a new HiveMQClientOptions object to enter the connection details of your HiveMQ Cloud MQTT broker, followed by an instantiation of a HiveMQClient.
Once complete, you can connect to your MQTT broker and display your connection status on the console.
Next, define a message handler method for receiving MQTT messages from the cloud followed by a subscription to the topic “hivemqdemo/commands”.
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.
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”
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.
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.
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 LinkedInContact Kudzai