|
- using MQTTnet;
- using MQTTnet.Client;
- using Newtonsoft.Json;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
-
- namespace LeatherApp.Device
- {
- public class CloudlInfo
- {
- public string ProductKey = "";
- public string DeviceName = "";
- public string DeviceSecret = "";
- public string clientId = "";
- public string username = "";
- public string mqttHostUrl = "";
- public string passwd = "";
- public int port = 0;
- }
-
- /// <summary>
- /// 云端控制
- /// </summary>
- public class CloudMgr
- {
- private IMqttClient mqttClient = null;
- private CloudlInfo cloudlInfo = new CloudlInfo();
- /// <summary>
- /// 连接服务器
- /// </summary>
- /// <param name="path"></param>
- /// <returns></returns>
- public bool ConnectCloud(string ip, int port, string username, string password)
- {
- bool ret = true;
- cloudlInfo.mqttHostUrl = ip;
- cloudlInfo.port = port;
- cloudlInfo.username = username;
- cloudlInfo.passwd = password;
- cloudlInfo.clientId = username;
- //连接
- var option = new MqttClientOptions();
- option.ClientId = cloudlInfo.clientId;
-
- //设置服务器地址与端口
- option.ChannelOptions = new MqttClientTcpOptions()
- {
- Server = cloudlInfo.mqttHostUrl,
- Port = cloudlInfo.port
- };
- //设置账号与密码
- option.Credentials = new MqttClientCredentials(cloudlInfo.username, Encoding.Default.GetBytes(cloudlInfo.passwd));
- option.CleanSession = true;
-
- //保持期
- option.KeepAlivePeriod = TimeSpan.FromSeconds(100.5);
-
- //构建客户端对象
- mqttClient = new MqttFactory().CreateMqttClient() as MqttClient;
- try
- {
- //绑定消息接收方法
- mqttClient.ApplicationMessageReceivedAsync += _client_ApplicationMessageReceived;
- //绑定连接成功状态接收方法
- mqttClient.ConnectedAsync += _client_Connected;
- //绑定连接断开状态接收方法
- mqttClient.DisconnectedAsync += _client_Disconnected;
-
- //启动连接
- mqttClient.ConnectAsync(option);
- }
- catch
- {
- Console.WriteLine($"{DateTime.Now.ToString("HH:mm:ss")} 连接失败");
- ret = false;
- }
- return ret;
- }
- /// <summary>
- /// 客户端与服务端断开连接
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private Task _client_Disconnected(MqttClientDisconnectedEventArgs e)
- {
- Console.WriteLine($"{DateTime.Now.ToString("HH:mm:ss")} Mqtt客户端连接断开");
-
- if (mqttClient == null || mqttClient.IsConnected == false)
- {
- Thread.Sleep(25 * 1000);
- Console.WriteLine($"{DateTime.Now.ToString("HH:mm:ss")} Mqtt客户端重连...");
- mqttClient.ReconnectAsync();
- Thread.Sleep(5 * 1000);
- }
- if (mqttClient.IsConnected)
- Console.WriteLine($"{DateTime.Now.ToString("HH:mm:ss")} Mqtt客户端重连成功");
-
- return Task.CompletedTask;
- }
-
- /// <summary>
- /// 客户端与服务端建立连接
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
-
- private Task _client_Connected(MqttClientConnectedEventArgs e)
- {
- Console.WriteLine($"{DateTime.Now.ToString("HH:mm:ss")} Mqtt客户端连接成功.");
-
- return Task.CompletedTask;
- }
-
- /// <summary>
- /// 客户端收到消息
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private Task _client_ApplicationMessageReceived(MqttApplicationMessageReceivedEventArgs e)
- {
- Console.WriteLine($"{DateTime.Now.ToString("HH:mm:ss")} Mqtt客户端收到消息:{e.ApplicationMessage}");
- return Task.CompletedTask;
- }
-
- private class WarningInfo
- {
- public WarningEnum Warn;
- public string WarningString;
- }
- /// <summary>
- /// 发送topic信息
- /// </summary>
- /// <param name="topic"></param>
- /// <param name="payload"></param>
- public bool SendTopic(string topic, string payload)
- {
- try
- {
- var applicationMessage = new MqttApplicationMessageBuilder()
- .WithTopic(topic)
- .WithPayload(payload)
- .Build();
- Task<MqttClientPublishResult> task = mqttClient.PublishAsync(applicationMessage);
- task.Wait();
- return true;
- }
- catch
- {
- //throw new Exception("云端连接错误");
- return false;
- }
- }
- }
- }
|