C#
本文主要介绍如何在 C# 项目中使用 paho.mqtt.m2mqtt 客户端库 ,实现客户端与 SX-IOT物联网设备的连接、订阅、收发消息等功能。
C# 是微软推出的一种基于 .NET框架的、 面向对象 的高级编程语言。 C#是一种由C和C++派生出来的面向对象的编程语言。 它在继承C和C++强大功能的同时去掉了一些它们的复杂特性,使其成为C语言家族中的一种高效强大的编程语言。
前提条件
安装依赖包
1sudo apt remove 'dotnet*' 'aspnet*' 'netstandard*'
2sudo rm /etc/apt/sources.list.d/microsoft-prod.list
3sudo apt update
4sudo apt install dotnet-sdk-6.0
5dotnet --version
6dotnet new console -o mqtt-client-Csharp-paho
7cd mqtt-client-Csharp-paho
8dotnet add package M2Mqtt --version 4.3.0
连接使用
连接设置
本文将使用自定义的接入认证方式,服务器接入信息如下:
Broker: mqtt.geek-smart.cn
TCP Port: 1883
WebSocket Port: 8083
导入依赖包
1 using System;
2 using uPLibrary.Networking.M2Mqtt;
3 using uPLibrary.Networking.M2Mqtt.Messages;
定义连接地址、认证信息以及消息发布主题
设置 MQTT Broker 连接地址,端口以及 topic。
1 string broker = "mqtt.geek-smart.cn";
2 int port = 1883;
3 string pub_topic = "/HYUGHV/lVtAcHuor***/4cebd60bf***/publish";
4 string sub_topic = "/HYUGHV/lVtAcHuor***/4cebd60bf***/subscribe";
5 string clientId = "csharp-client";
6 string username = "************";
7 string password = "************";
定义消息发布函数
1 static void Publish(MqttClient client, string topic)
2 {
3 int msg_count = 0;
4 while (true)
5 {
6 System.Threading.Thread.Sleep(1*1000);
7 string msg = "{'type':'info'}";
8 client.Publish(topic, System.Text.Encoding.UTF8.GetBytes(msg));
9 Console.WriteLine("Send `{0}` to topic `{1}`", msg, topic);
10 msg_count++;
11 }
12 }
定义 subscribe 回调函数,用于打印订阅主题接收的消息内容
1 static void Subscribe(MqttClient client, string topic)
2 {
3 client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
4 client.Subscribe(new string[] { topic }, new byte[] { MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE });
5 }
6 static void client_MqttMsgPublishReceived(object sender,MqttMsgPublishEventArgs e)
7 {
8 string payload = System.Text.Encoding.Default.GetString(e.Message);
9 Console.WriteLine("Received `{0}` from `{1}` topic", payload, e.Topic.ToString());
10 }
初始化 MQTT 客户端并订阅主题
1 static MqttClient ConnectMQTT(string broker, int port, stringclientId, string username, string password)
2 {
3 MqttClient client = new MqttClient(broker, port, false, MqttSslProtocols.None, null, null);
4 client.Connect(clientId, username, password);
5 if (client.IsConnected)
6 {
7 Console.WriteLine("Connected to MQTT Broker");
8 }
9 else
10 {
11 Console.WriteLine("Failed to connect");
12 }
13 return client;
14 }
完整代码
1<Project Sdk="Microsoft.NET.Sdk">
2
3 <PropertyGroup>
4 <OutputType>Exe</OutputType>
5 <TargetFramework>net6.0</TargetFramework>
6 <RootNamespace>mqtt_client_Csharp_paho</RootNamespace>
7 <ImplicitUsings>enable</ImplicitUsings>
8 <Nullable>enable</Nullable>
9 </PropertyGroup>
10
11 <ItemGroup>
12 <PackageReference Include="M2Mqtt" Version="4.3.0" />
13 </ItemGroup>
14
15</Project>
1 using System;
2 using uPLibrary.Networking.M2Mqtt;
3 using uPLibrary.Networking.M2Mqtt.Messages;
4
5 namespace csharpMQTT
6 {
7 class Program
8 {
9 static MqttClient ConnectMQTT(string broker, int port, string clientId, string username, string password)
10 {
11 MqttClient client = new MqttClient(broker, port, false, MqttSslProtocols.None, null, null);
12 client.Connect(clientId, username, password);
13 if (client.IsConnected)
14 {
15 Console.WriteLine("Connected to MQTT Broker");
16 }
17 else
18 {
19 Console.WriteLine("Failed to connect");
20 }
21 return client;
22 }
23
24 static void Publish(MqttClient client, string topic)
25 {
26 int msg_count = 0;
27 while (true)
28 {
29 System.Threading.Thread.Sleep(1*1000);
30 string msg = "{'type':'info'}";
31 client.Publish(topic, System.Text.Encoding.UTF8.GetBytes(msg));
32 Console.WriteLine("Send `{0}` to topic `{1}`", msg, topic);
33 msg_count++;
34 }
35 }
36
37 static void Subscribe(MqttClient client, string topic)
38 {
39 client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
40 client.Subscribe(new string[] { topic }, new byte[] { MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE });
41 }
42 static void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
43 {
44 string payload = System.Text.Encoding.Default.GetString(e.Message);
45 Console.WriteLine("Received `{0}` from `{1}` topic", payload, e.Topic.ToString());
46 }
47
48 static void Main(string[] args)
49 {
50 string broker = "mqtt.geek-smart.cn";
51 int port = 1883;
52 string pub_topic = "/HYUGHV/lVtAcHuor***/4cebd60bf***/publish";
53 string sub_topic = "/HYUGHV/lVtAcHuor***/4cebd60bf***/subscribe";
54 string clientId = "csharp-client";
55 string username = "************";
56 string password = "************";
57 MqttClient client = ConnectMQTT(broker, port, clientId, username, password);
58 Subscribe(client, sub_topic);
59 Publish(client, pub_topic);
60 }
61 }
62 }
测试验证
运行
1dotnet run