This article describes how to use the Paho Message Queuing Telemetry Transport (MQTT) library for C# to connect to IoT Platform and exchange messages with IoT Platform.

Prerequisites

A product and a device are created in the IoT Platform console. The LightSwitch property is defined on the Define Feature tab for the product.

For more information, see Create a product, Create a device, and Add a TSL feature.

Background information

The open source code of Paho MQTT for C# contains a Visual Studio solution. Each project in the solution can be used to generate the library for the specified .NET platform.

In this example, a console application project is created in the solution. The application uses the Paho MQTT library to connect to IoT Platform.

Prepare the development environment

In this example, the development environment consists of the following components:

  • Operating system: Windows 10
  • Integrated development environment (IDE): Visual Studio 2019

To install the IDE, perform the following steps:

  1. Download the installation file of Visual Studio Community 2019.
  2. Double-click the installation file to start Visual Studio Installer. Select .NET desktop development and click Install.

Download the Paho MQTT C# client

Visit paho.mqtt.m2mqtt on GitHub and download the package of the Paho MQTT C# client.

The master branch is used to develop the demo in this example. The commit ID is b2e64bc4485721a0bd5ae805d9f4917e8d040e81.

The source code provided by Paho contains the Visual Studio solution file M2MMqtt.sln. You can use this solution file to develop your own device program.

Connect to IoT Platform

  1. Click MqttSign.cs to obtain the source code provided by Alibaba Cloud to calculate the MQTT connection parameters.

    The MqttSign.cs file defines the MqttSign class.

    • Prototype
      class MqttSign
    • Description

      Calculates the MQTT connection parameters username, password, and clientid.

    • Members
      Type Method
      public bool calculate(String productKey, String deviceName, String deviceSecret)

      You can call this method to calculate the username, password, and clientid parameters based on the productKey, deviceName, and deviceSecret of the device.

      public String getUsername()

      You can call this method to obtain the MQTT connection parameter username.

      public String getPassword()

      You can call this method to obtain the MQTT connection parameter password.

      public String getClientid()

      You can call this method to obtain the MQTT connection parameter clientid.

  2. Open Visual Studio. Import the Visual Studio solution file M2Mqtt.sln and create an application project.
  3. Import the MqttSign.cs file downloaded in Step 1 into the application project.
  4. In the application project, add a program file that can connect a device to IoT Platform.

    You must write a program to use the MqttSign class in the MqttSign.cs file to calculate the parameters that are used to establish an MQTT connection to IoT Platform.

    This section provides the development instructions and sample code.

    • Calculate the MQTT connection parameters.

      Use the MqttSign class in the MqttSign.cs file to calculate the MQTT connection parameters.

      String productKey = "a1X2bEn****";
      String deviceName = "example1";
      String deviceSecret = "ga7XA6KdlEeiPXQPpRbAjOZXwG8y****";
      
      // Calculate the MQTT connection parameters.
      MqttSign sign = new MqttSign();
      sign.calculate(productKey, deviceName, deviceSecret);
      
      Console.WriteLine("username: " + sign.getUsername());
      Console.WriteLine("password: " + sign.getPassword());
      Console.WriteLine("clientid: " + sign.getClientid());
    • Create a Paho MQTT client to connect to IoT Platform.
      // Use the Paho MQTT C# client to connect to IoT Platform.
      int port = 443;
      String broker = productKey + ".iot-as-mqtt.cn-shanghai.aliyuncs.com";
      
      MqttClient mqttClient = new MqttClient(broker, port, true, MqttSslProtocols.TLSv1_2, null, null);
      mqttClient.Connect(sign.getClientid(), sign.getUsername(), sign.getPassword());
      
      Console.WriteLine("Broker: " + broker + " Connected");
      Note

      Replace cn-shanghai in the code with the ID of the region where your device resides. For more information about region IDs, see Regions and zones.

    • Report data to IoT Platform.

      The following sample code is used to report the LightSwitch property of a TSL model.

      // Publish messages by using Paho MQTT.
      String topic = "/sys/" + productKey + "/" + deviceName + "/thing/event/property/post";
      String message = "{\"id\":\"1\",\"version\":\"1.0\",\"params\":{\"LightSwitch\":0}}";
      mqttClient.Publish(topic, Encoding.UTF8.GetBytes(message));

      For more information about the TSL data format, see Device properties, events, and services.

      For more information about how to use custom topics for communication, see What is a topic?

    • Subscribe to a topic to obtain messages from IoT Platform.

      In this example, you subscribe to the topic to which IoT Platform returns response messages after the property values are reported.

      // Subscribe to a message topic by using Paho MQTT.
      String topicReply = "/sys/" + productKey + "/" + deviceName + "/thing/event/property/post_reply";
      
      mqttClient.MqttMsgPublishReceived += MqttPostProperty_MqttMsgPublishReceived;
      mqttClient.Subscribe(new string[] { topicReply }, new byte[] { MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE });
      ...
      private static void MqttPostProperty_MqttMsgPublishReceived(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e)
      {
          Console.WriteLine("reply topic  :" + e.Topic);
          Console.WriteLine("reply payload:" + e.Message.ToString());
      }

    For more information about the communication methods of devices, servers, and IoT Platform, see Overview.

  5. Compile the project.

Demo

The demo code demonstrates how to connect a device to IoT Platform.

  1. Download the demo package and decompress it to the aiot-csharp-demo directory.

    The aiot-csharp-demo\paho.mqtt.m2mqtt-master\aiot-csharp-demo directory contains a complete program that can connect to IoT Platform and report properties of the TSL model.

    File Description
    MqttSign.cs This file contains the code that is used to calculate the parameters for establishing an MQTT connection to IoT Platform. When you run the Program.cs file, the MqttSign() function is called to calculate the connection parameters username, password, and clientId.
    Program.cs This file contains the logic code that connects to IoT Platform and reports properties.
  2. Open the solution file aiot-csharp-demo\paho.mqtt.m2mqtt-master\M2Mqtt.sln in Visual Studio Community 2019.
    The aiot-csharp-demo project is imported into Visual Studio.
  3. In the Program.cs file, replace the device information with your device information.
    • Replace the values of the productKey, deviceName, and deviceSecret parameters with your device certificate information.
      String productKey = "${ProductKey}";
      String deviceName = "${DeviceName}";
      String deviceSecret = "${DeviceSecret}";
    • Modify the domain name in String broker = productKey + ".iot-as-mqtt.cn-shanghai.aliyuncs.com";. For more information, see Step 4 in the "Connect to IoT Platform" section.
  4. Run the aiot-csharp-demo project to connect to IoT Platform.
    Connect to IoT Platform
    After the demo is connected to IoT Platform, you can view the information about successful connection, successful data reporting, and successful message subscription in local logs.
    ...
    broker: a1X2bEn****.iot-as-mqtt.cn-shanghai.aliyuncs.com Connected
    ...
    publish: {"id":"1","version":"1.0","params":{"LightSwitch":0}}
    ...
    subscribe: /sys/a1X2bEn****/example1/thing/event/property/post_reply
    ...

    Log on to the IoT Platform console.View device status and logs.

    • Choose Devices > Devices. You can find that the status of the device is Online.
    • Choose Maintenance > Device Log to view logs on the Cloud run log and Device local log tabs. For more information, see IoT Platform logs and Local device logs.

      If the Mqtt5App program is run, you can view the reported custom properties in the log details.

Error codes

If a device fails to establish an MQTT connection to IoT Platform, you can troubleshoot the issue based on the error code. For more information about the error codes that may be returned by IoT Platform, see Troubleshooting.