This topic describes how to use the C# library of Paho MQTT to connect to Alibaba
Cloud IoT Platform and perform Thing Specification Language (TSL) data communication.
Background information
The MQTT C# open-source code provided by Paho contains the Visual Studio solutions.
Each project of a solution can generate corresponding class libraries for different
.NET platforms.
In this example, a console project is created in the solution and the project calls
the MQTT class library of Paho to connect to Alibaba Cloud IoT Platform.
Prepare the development environment
The operating system and development tools used in this example are as follows:
- Operating system: Window 10
- Integrated development environment: Visual Studio 2019
Install the development environment:
- Download Visual Studio 2019 Community Edition, and decompress the package.
- Run the Visual Studio Installer. Select .NET desktop development and click Installation.
Download the Paho client
Visit Eclipse Paho and download Paho MQTT for C# from the GitHub page for .Net(C #).
The demo code uses the master branch. The commit id is b2e64bc4485721a0bd5ae805d9f4917e8d040e81
.
The source code provided by Paho contains the Visual Studio solution file M2MMqtt.sln. You can use it to develop your own device.
Connect to IoT Platform
- Click MqttSign.cs to view and download the code provided by Alibaba Cloud to calculate the MQTT connection
parameters.
The MqttSign.cs file defines the MqttSign
class.
- Open Visual Studio. Import the Visual Studio solution file M2Mqtt.sln from the source code of Paho, and create a project.
- Import the MqttSign.cs file to the project.
- In the application project, add a program file that enables devices to access IoT
Platform.
You must write a program which can call the MqttSign class in the MqttSign.cs file to calculate the MQTT connection parameters.
The instructions for development and sample code are as follows.
- 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());
- Call 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");
Note Replace cn-shanghai in the code with the region ID of your IoT Platform device. For
more information about region IDs, see
Regions and zones.
- Publish messages.
The following sample code is used to report the value of the property LightSwitch.
// Paho MQTT publishes a message
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.
If you want to use custom topics for communication, see What is a topic?.
- Subscribe to topics to receive data sent from IoT Platform.
In the following example, the topic subscribed is used for receiving response messages
from IoT Platform after property values are reported.
// The topic to which Paho MQTT subscribes for messages
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 Communication methods.
- Compile the project.
Demo
- Download the demo package.
The demo package contains the complete program for devices to access IoT Platform
and report property values.
File |
Description |
MqttSign.cs |
The code for calculating MQTT connection parameters. When you run Program.cs, it calls the MqttSign() function to calculate the connection parameters, such as username, password, and clientId.
|
Program.cs |
This file contains the code for a device to connect to IoT Platform and communicate
with IoT Platform.
|
- Open Visual Studio 2019 Community Edition and select Open Project/Solution.
- Import the aiot-csharp-demo file from the demo package.
- In the Program.cs file, change the device information to your device information.
- Replace the productKey, deviceName, and deviceSecret with your device certificate information.
- Replace cn-shanghai in
String broker = productKey + ".iot-as-mqtt.cn-shanghai.aliyuncs.com";
with the region ID of your IoT Platform device. For more information about region
IDs, see Regions and zones.
- Run the Program.cs program to access IoT Platform.
After the program is connected, you can view the success messages for the 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
...
In the IoT Platform console, you can view the device status and logs.
- Choose . You can view that the status of the device is Online.
- Choose . You can view the Device Activity Analysis and Upstream Analysis logs.