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