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.

AWS_IoT_core_communication_in_dotNET_Framework_application_using_MQTT_01

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

  1. Download MQTTnet Library from Nuget Package Manager in visual studio IDE. Also can download from https://www.nuget.org/packages/MQTTnet/.
  2. Creating an MQTT client instance and then allowing connection through MOTT client to the MQTT server.
    AWS_IoT_core_communication_in_dotNET_Framework_application_using_MQTT_02

    1. Referring to above code, for creating an instance of MQTT client, CreateMqttClient() function is invoked using MqttFactory object.
    2. Inorder to connect to broker the MQTT client needs the signedRequestUrl.
    3. This signedRequestUrl is generated using 4 things: Host (Iot Host Url), Region, AccessKey and Secret Key.
    4. Code for generating signedRequest Url:
      AWS_IoT_core_communication_in_dotNET_Framework_application_using_MQTT_03
    5. Using signedRequestUrl and the clientId the MqttClient is connected to the Mqtt Broker on port 443.
  3. After connecting, we can publish messages to Mqtt Broker. Code for publishing messages to Mqtt Broker:
    AWS_IoT_core_communication_in_dotNET_Framework_application_using_MQTT_04 For publishing the message, we need the topic on which the message is to be published. Here payload is the message.
  4. We can also subscribe to messages from the Mqtt Broker. Code used for subscribing messages:
    AWS_IoT_core_communication_in_dotNET_Framework_application_using_MQTT_05
  5. Handle Events for MqttClients:
    1. Connected Handler:
      AWS_IoT_core_communication_in_dotNET_Framework_application_using_MQTT_06
    2. Disconnected Handler:
      AWS_IoT_core_communication_in_dotNET_Framework_application_using_MQTT_07
    3. Handler for message received after subscribing to messages.
      AWS_IoT_core_communication_in_dotNET_Framework_application_using_MQTT_08

search
Blog Categories
Request a quote