Use the Paho MQTT library for C# to connect to Alibaba Cloud IoT Platform and exchange data by using a Thing Specification Language (TSL) model.
Prerequisites
You have created a product and a device in IoT Platform and defined a LightSwitch property for the product on the Function Definition tab.
For more information, see Create a product, Create a single device, and Add a TSL model for a single product.
Background information
The open source code for Paho MQTT for C# includes a Visual Studio solution project. Each project in the solution targets a different .NET platform and generates a corresponding class library.
In this example, you create a console application project in the solution that calls the Paho MQTT class library to connect to Alibaba Cloud IoT Platform.
Prepare the development environment
This example uses the following operating system and development tools:
-
Operating system: Windows 10
-
Integrated development environment (IDE): Visual Studio 2019
Install the development environment:
-
Download Visual Studio Community 2019 and decompress the package.
-
Open Visual Studio Installer, select .NET desktop development, and then click Install.
Download the Paho client
Download the Paho MQTT for C# source code. The source code includes the Visual Studio solution project file M2Mqtt.sln. You can use this project file to develop your device client. For more information, see Connect to IoT Platform.
You can also visit Eclipse Paho for more information about the Paho source code.
This demo uses the master branch. The commit ID is b2e64bc4485721a0bd5ae805d9f4917e8d040e81.
Connect to IoT Platform
-
Download MqttSign.cs to obtain the source code that Alibaba Cloud provides for calculating MQTT connection parameters.
The MqttSign.cs file defines the
MqttSignclass:-
Prototype:
class MqttSign -
Function:
Calculates the username, password, and clientID required for connecting a device to IoT Platform over MQTT.
-
Members:
Type definition
Method description
public bool
calculate(String productKey, String deviceName, String deviceSecret)Calculates the MQTT connection parameters username, password, and clientid based on the productKey, deviceName, and deviceSecret of the device.
public String
getUsername()Gets the MQTT connection parameter username.
public String
getPassword()Gets the MQTT connection parameter password.
public String
getClientid()Gets the MQTT connection parameter clientid.
-
-
Open Visual Studio, import the M2Mqtt.sln Visual Studio solution file from the Paho source code, and then create an application project.
-
Import the MqttSign.cs file that you downloaded in Step 1 into the application project.
-
In the application project, add the program file for connecting the device to IoT Platform.
Call the MqttSign class in MqttSign.cs to calculate the MQTT connection parameters for connecting the device to IoT Platform.
The following development instructions and code examples are provided:
-
Calculate MQTT connection parameters.
Call MqttSign in MqttSign.cs 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()); -
Use the Paho MQTT client to connect to IoT Platform.
// Use Paho to connect to Alibaba Cloud 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");NoteIn the code
String broker = productKey + ".iot-as-mqtt.cn-shanghai.aliyuncs.com";, replace the endpoint with the one that corresponds to your device's instance.For more information about the endpoint formats for public and Enterprise instances, see View instance endpoints.
-
Report data from the device to IoT Platform.
The following sample code shows how to report the LightSwitch TSL model property.
// Publish a message using the Paho MQTT client. 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 the data format for TSL model communication, see Device properties, events, and services.
If you want to use a custom topic for communication, see What is a topic?.
-
Subscribe to a topic to receive data from IoT Platform.
In the following example, the device subscribes to the topic that IoT Platform uses to return an acknowledgement message after the device reports a property value.
// Subscribe to a message using the Paho MQTT client. 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()); }
Learn about device-cloud communication patterns in Overview of communications among devices, IoT platform, and servers.
-
-
Compile the project.
Demo
Use the demo code to connect to IoT Platform.
-
Download the demo code package and decompress it to the aiot-csharp-demo folder.
The aiot-csharp-demo\paho.mqtt.m2mqtt-master\aiot-csharp-demo folder contains the complete program for connecting a device to IoT Platform and reporting TSL model properties.
File
Description
MqttSign.cs
Source code provided by Alibaba Cloud for generating MQTT connection parameters. At runtime, Program.cs calls the MqttSign() function defined in this file to calculate the username, password, and clientId parameters.
Program.cs
Contains the logic for connecting the device to IoT Platform and reporting property data.
-
Start Visual Studio Community 2019, select Open a project or solution, and open the aiot-csharp-demo\paho.mqtt.m2mqtt-master\M2Mqtt.sln file.
The aiot-csharp-demo project file is then imported into Visual Studio.
-
In Program.cs, replace the sample device information with your actual device information.
-
In the following code, replace the values of productKey, deviceName, and deviceSecret with your device credentials.
String productKey = "${ProductKey}"; String deviceName = "${DeviceName}"; String deviceSecret = "${DeviceSecret}"; -
Modify the endpoint in the code
String broker = productKey + ".iot-as-mqtt.cn-shanghai.aliyuncs.com";. For more information, see Step 4 in the "Connect to IoT Platform" section.
-
-
Set aiot-csharp-demo as the startup project and run the project to connect the device to IoT Platform.
username: lxxx3 password: E251xxx clientid: g1xxx|timestamp=1606810137987, _v=paho-c#-1.0.0, securemode=2, signmethod=hmacsha256| broker: iotxxxn Connected subscribe: /sys/gxxx/thing/event/property/post_reply publish: {"id":"1","version":"1.0","params":{"LightSwitch":0}} reply topic :/sys/gxxxp/thing/event/property/post_reply reply payload:{"code":200,"data":{},"id":"1","message":"success","method":"thing.event.property.post","version":"1.0"}After the device connects, the on-premises logs show a successful connection, data reporting, and message subscription.
... 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 in to the IoT Platform console to view device status and logs in your instance.
-
In the left-side navigation pane, choose . You can see that the device status is Online.
Choose . You can view IoT Platform logs and on-premises device logs. For more information, see IoT Platform logs and On-premises device logs.
-
Error codes
If the device fails to connect to IoT Platform over MQTT, use the error codes to troubleshoot the issue. For more information about server-side error codes, see Troubleshooting.