This article describes how to use the Paho Message Queuing Telemetry Transport (MQTT) library for C# to connect to IoT Platform and communicate 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 of the Product Details page.

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# includes 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 with 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 Visual Studio Community 2019 and decompress the package.
  2. Open Visual Studio Installer, click .NET desktop development, and then click Install.

Download the Paho MQTT C# client

Download the Paho MQTT for C# source code. The code includes a Visual Studio solution file named M2MMqtt.sln. You can use this project file to develop your devices. For more information, see Connect the client to IoT Platform.

To view more instructions on the Paho source code, visit the GitHub.

The master branch is used to develop the sample code in this article. The commit ID is b2e64bc4485721a0bd5ae805d9f4917e8d040e81.

Connect the client to IoT Platform

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

    The MqttSign.cs file defines the MqttSign class.

    • Syntax
      class MqttSign
    • Description

      This class is used to obtain the following MQTT connection parameters: username, password, and clientid.

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

      Calculates the username, password, and clientid parameters based on the productKey, deviceName, and deviceSecret parameters.

      public String getUsername()

      Obtains the username parameter.

      public String getPassword()

      Obtains the password parameter.

      public String getClientid()

      Obtains the clientid parameter.

  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 obtain the parameters that are used to establish an MQTT connection with IoT Platform.

    This section provides the development instructions and sample code.

    • Obtain the MQTT connection parameters.

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

      String productKey = "a1X2bEn****";
      String deviceName = "example1";
      String deviceSecret = "ga7XA6KdlEeiPXQPpRbAjOZXwG8y****";
      
      // Obtain 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 with IoT Platform.
      // Use the Paho MQTT C# client to connect with 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.

    • Submit data to IoT Platform.

      The following sample code is used to submit the LightSwitch property.

      // 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 TSL data formats, 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 receive the messages from IoT Platform.

      The following example shows how to subscribe to the topic to which IoT Platform returns a response message after the property is submitted.

      // Subscribe to a 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.

Sample code

You can use the sample code to connect with 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 is used to connect with IoT Platform and submit properties.

    File Description
    MqttSign.cs This file contains the code that is used to obtain the MQTT connection parameters. When you run the Program.cs file, the MqttSign() function is called to obtain the username, password, and clientId parameters.
    Program.cs This file contains the logic code that is used to connect with IoT Platform and submit properties.
  2. Open Visual Studio Community 2019, click Open a project or solution, and then open the aiot-csharp-demo\paho.mqtt.m2mqtt-master\M2Mqtt.sln file.
    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 endpoint in String broker = productKey + ".iot-as-mqtt.cn-shanghai.aliyuncs.com";. For more information, see Step 4 in the "Connect the client to IoT Platform" section.
  4. Set the aiot-csharp-demo file as the startup item, and then run it to connect the client with IoT Platform.
    Connect the client with IoT Platform
    After the connection is established, you can view the information about the connection, data submission, and 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. Then, click the Cloud run log or Device local log tab to view logs. For more information, see IoT Platform logs and Local device logs.

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, see Troubleshooting.