环境
VS:.NET Framework 4.8
NuGet:MQTTnet 4.2.1.781
背景
MCU加4G模组要测试MQTT通讯,和功能开发,为方便自己调试,写了个小工具做简单命令首发
MQTT连接
MCU肯定是作为客户端client,项目中已经搭建好了MQTT Broker 服务器。
第一步需要先连接自己的服务器。
csharp
//定义一个mqtt客户端句柄
public static IMqttClient _mqttClient = null;
private void MqttConnectAsync()
{
//若已连接,则断开原来的连接,防止占用资源
if (_mqttClient != null && _mqttClient.IsConnected == true)
{
_mqttClient.DisconnectAsync();
}
var optionsBuilder = new MqttClientOptionsBuilder()
.WithTcpServer("mqtt-test.com", 1883) //服务器IP或域名 服务器端口号
.WithCredentials("", "") //凭据 忽略
.WithClientId("test_client") //客户端ID 如果写死则相同ID的同时客户端连接服务器时,会挤掉其他客户端 | 这里也跟可以生成随机数转成字符串
.WithCleanSession() //清理会话
.WithTls(new MqttClientOptionsBuilderTlsParameters
{
UseTls = false
});
var clientOptions = optionsBuilder.Build();
_mqttClient = new MqttFactory().CreateMqttClient();//创建客户端
//连接成功的回调函数
_mqttClient.ConnectedAsync += _mqttClient_ConnectedAsync;
//连接断开的回调函数
_mqttClient.DisconnectedAsync += _mqttClient_DisconnectedAsync;
//数据接收的回调函数
_mqttClient.ApplicationMessageReceivedAsync += _mqttClient_ApplicationMessageReceivedAsync;
//执行异步方式连接
_mqttClient.ConnectAsync(clientOptions);
}
private Task _mqttClient_ConnectedAsync(MqttClientConnectedEventArgs arg)
{
//连接成功一般做2件事:一、告知上层已连接成功,二、订阅Topic来接收数据
string topic2 = "/C2S/" + IMEI + "/UP";
string topic3 = "/C2S/Public";
_mqttClient.SubscribeAsync(topic3, MqttQualityOfServiceLevel.AtMostOnce);
return Task.CompletedTask;
}
private Task _mqttClient_DisconnectedAsync(MqttClientDisconnectedEventArgs arg)
{
//连接断开:告知上层连接已断开
return Task.CompletedTask;
}
MQTT数据发送
csharp
void _mqttClient_Publish(byte[] cmd)
{
string topic = "S2C/" + IMEI + "/DOWN";
//MQTT数据发送 即 publish 发布,需要2个参数:一、发布主题,二、发布数据(有效载荷)
//发布主题,可以根据自己的规则定义,比如以设备4G模组的IMEI号组成
_mqttClient.PublishBinaryAsync(topic, cmd);
}
MQTT数据接收
csharp
private Task _mqttClient_ApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs arg)
{
byte[] bytes = arg.ApplicationMessage.Payload;
if (bytes[0] == 0x01
&& bytes[1] == 0x98
&& bytes[2] == 0x76)
{
byte[] byte_tmp = new byte[bytes.Length - 9];
for (int i = 5; i < bytes.Length - 4; i++)
{
byte_tmp[i - 5] = bytes[i];
}
//数据定义中,上行数据添加固定头,其后跟字符串数据
//每次接收时,判断固定头,提取后面的字符串数据进行打印
textBox1.AppendText(System.Text.Encoding.UTF8.GetString(byte_tmp) + "\r\n");
}
else
{
textBox1.AppendText("收到非法消息\r\n");
}
return Task.CompletedTask;
}