How to implement AWS IoT core communication in .NET Framework application using MQTT?
How to implement AWS IoT core communication in .NET Framework application using MQTT?
11 March 2021
We can publish and subscribe messages on AWS IoT core by establishing a connection to it. In .Net Framework we have multiple options for connecting to AWS IoT core.
Below are the multiple protocols and the ports they support for communicating with AWS IoT core.
Here, we will use MQTT with WebSocket protocol for handshake with AWS IoT core using Signv4 authentication. We will use MQTTnet library for the publishing and subscribing messages on AWS IoT core.
Benefits of using MQTTnet Library
- It is a high performance .Net library for MQTT based communication.
- Provides both MQTT client and a MQTT broker (server).
- It provides an auto-reconnect facility if the connection is aborted with MQTT Broker.
- Has an improved behavior incase of multiple connections over a session.
Steps for Implementation
- Download MQTTnet Library from Nuget Package Manager in visual studio IDE. Also can download from https://www.nuget.org/packages/MQTTnet/.
- Creating an MQTT client instance and then allowing connection through MOTT client to the MQTT server.
- Referring to above code, for creating an instance of MQTT client, CreateMqttClient() function is invoked using MqttFactory object.
- Inorder to connect to broker the MQTT client needs the signedRequestUrl.
- This signedRequestUrl is generated using 4 things: Host (Iot Host Url), Region, AccessKey and Secret Key.
- Code for generating signedRequest Url:
- Using signedRequestUrl and the clientId the MqttClient is connected to the Mqtt Broker on port 443.
- After connecting, we can publish messages to Mqtt Broker. Code for publishing messages to Mqtt Broker:
For publishing the message, we need the topic on which the message is to be published. Here payload is the message. - We can also subscribe to messages from the Mqtt Broker. Code used for subscribing messages:
- Handle Events for MqttClients: