All Products
Search
Document Center

IoT Platform:Use the Paho MQTT C# client

Last Updated:Dec 28, 2023

This topic describes how to use the Paho Message Queuing Telemetry Transport (MQTT) library for C# to connect to 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, and the Paho MQTT library is used 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 Visual Studio Community 2019 and decompress the package.

  2. Double-click the installation file to start Visual Studio Installer. Select .NET desktop development and 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 M2Mqtt.sln. You can use this file to develop your devices. For more information, see Connect a device to IoT Platform.

For more information about the instructions on the Paho source code, visit GitHub.

In this topic, the master branch is used to develop the sample code. The commit ID is b2e64bc4485721a0bd5ae805d9f4917e8d040e81.

Connect a device to IoT Platform

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

    The MqttSign.cs file specifies the MqttSign class.

    • Syntax

      class MqttSign
    • Description

      You can use this class 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 named M2Mqtt.sln and create an application project.

  3. Import the MqttSign.cs file that you downloaded in Step 1 to 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. This way, you can obtain the parameters that are used to establish an MQTT connection with IoT Platform.

    This section provides the development instructions and sample code of establishing the connection.

    • 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 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

      Modify the endpoint in String broker = productKey + ".iot-as-mqtt.cn-shanghai.aliyuncs.com";.

      For more information about the endpoints of public instances and Enterprise Edition instances and the formats of the endpoints, see View the endpoint of an instance.

    • 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 information about TSL data formats, see Device properties, events, and services.

      For information about how to use custom topics for communication, see Topics.

    • Subscribe to a topic to receive the messages from IoT Platform.

      The following example shows how to subscribe to a topic. IoT Platform returns a response message to the topic 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 information about the communication methods of devices, servers, and IoT Platform, see Overview of communications among devices, IoT platform, and servers.

  5. Compile the project.

Sample code

You can use the sample code to connect a device to IoT Platform.

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

    The aiot-csharp-demo\paho.mqtt.m2mqtt-master\aiot-csharp-demo directory contains a complete program that allows a device to connect to IoT Platform and submit properties.

    File

    Description

    MqttSign.cs

    This file contains the code that you can use 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 allows a device to connect to 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 sample 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 a device to IoT Platform" section in this topic.

  4. Specify the aiot-csharp-demo file as the startup item, and then run the file to connect the device to IoT Platform.

    Connect a device to IoT Platform

    After you connect the device to IoT Platform, 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
    ...

    In the IoT Platform console, you can view the device status and logs.

    • Choose Devices > Devices. The Devices page shows that the device is in Online state.

    • 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.