革博士程序V1仓库
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

159 Zeilen
5.3 KiB

  1. using MQTTnet;
  2. using MQTTnet.Client;
  3. using Newtonsoft.Json;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. namespace LeatherApp.Device
  11. {
  12. public class CloudlInfo
  13. {
  14. public string ProductKey = "";
  15. public string DeviceName = "";
  16. public string DeviceSecret = "";
  17. public string clientId = "";
  18. public string username = "";
  19. public string mqttHostUrl = "";
  20. public string passwd = "";
  21. public int port = 0;
  22. }
  23. /// <summary>
  24. /// 云端控制
  25. /// </summary>
  26. public class CloudMgr
  27. {
  28. private IMqttClient mqttClient = null;
  29. private CloudlInfo cloudlInfo = new CloudlInfo();
  30. /// <summary>
  31. /// 连接服务器
  32. /// </summary>
  33. /// <param name="path"></param>
  34. /// <returns></returns>
  35. public bool ConnectCloud(string ip, int port, string username, string password)
  36. {
  37. bool ret = true;
  38. cloudlInfo.mqttHostUrl = ip;
  39. cloudlInfo.port = port;
  40. cloudlInfo.username = username;
  41. cloudlInfo.passwd = password;
  42. cloudlInfo.clientId = username;
  43. //连接
  44. var option = new MqttClientOptions();
  45. option.ClientId = cloudlInfo.clientId;
  46. //设置服务器地址与端口
  47. option.ChannelOptions = new MqttClientTcpOptions()
  48. {
  49. Server = cloudlInfo.mqttHostUrl,
  50. Port = cloudlInfo.port
  51. };
  52. //设置账号与密码
  53. option.Credentials = new MqttClientCredentials(cloudlInfo.username, Encoding.Default.GetBytes(cloudlInfo.passwd));
  54. option.CleanSession = true;
  55. //保持期
  56. option.KeepAlivePeriod = TimeSpan.FromSeconds(100.5);
  57. //构建客户端对象
  58. mqttClient = new MqttFactory().CreateMqttClient() as MqttClient;
  59. try
  60. {
  61. //绑定消息接收方法
  62. mqttClient.ApplicationMessageReceivedAsync += _client_ApplicationMessageReceived;
  63. //绑定连接成功状态接收方法
  64. mqttClient.ConnectedAsync += _client_Connected;
  65. //绑定连接断开状态接收方法
  66. mqttClient.DisconnectedAsync += _client_Disconnected;
  67. //启动连接
  68. mqttClient.ConnectAsync(option);
  69. }
  70. catch
  71. {
  72. Console.WriteLine($"{DateTime.Now.ToString("HH:mm:ss")} 连接失败");
  73. ret = false;
  74. }
  75. return ret;
  76. }
  77. /// <summary>
  78. /// 客户端与服务端断开连接
  79. /// </summary>
  80. /// <param name="sender"></param>
  81. /// <param name="e"></param>
  82. private Task _client_Disconnected(MqttClientDisconnectedEventArgs e)
  83. {
  84. Console.WriteLine($"{DateTime.Now.ToString("HH:mm:ss")} Mqtt客户端连接断开");
  85. if (mqttClient == null || mqttClient.IsConnected == false)
  86. {
  87. Thread.Sleep(25 * 1000);
  88. Console.WriteLine($"{DateTime.Now.ToString("HH:mm:ss")} Mqtt客户端重连...");
  89. mqttClient.ReconnectAsync();
  90. Thread.Sleep(5 * 1000);
  91. }
  92. if (mqttClient.IsConnected)
  93. Console.WriteLine($"{DateTime.Now.ToString("HH:mm:ss")} Mqtt客户端重连成功");
  94. return Task.CompletedTask;
  95. }
  96. /// <summary>
  97. /// 客户端与服务端建立连接
  98. /// </summary>
  99. /// <param name="sender"></param>
  100. /// <param name="e"></param>
  101. private Task _client_Connected(MqttClientConnectedEventArgs e)
  102. {
  103. Console.WriteLine($"{DateTime.Now.ToString("HH:mm:ss")} Mqtt客户端连接成功.");
  104. return Task.CompletedTask;
  105. }
  106. /// <summary>
  107. /// 客户端收到消息
  108. /// </summary>
  109. /// <param name="sender"></param>
  110. /// <param name="e"></param>
  111. private Task _client_ApplicationMessageReceived(MqttApplicationMessageReceivedEventArgs e)
  112. {
  113. Console.WriteLine($"{DateTime.Now.ToString("HH:mm:ss")} Mqtt客户端收到消息:{e.ApplicationMessage}");
  114. return Task.CompletedTask;
  115. }
  116. private class WarningInfo
  117. {
  118. public WarningEnum Warn;
  119. public string WarningString;
  120. }
  121. /// <summary>
  122. /// 发送topic信息
  123. /// </summary>
  124. /// <param name="topic"></param>
  125. /// <param name="payload"></param>
  126. public bool SendTopic(string topic, string payload)
  127. {
  128. try
  129. {
  130. var applicationMessage = new MqttApplicationMessageBuilder()
  131. .WithTopic(topic)
  132. .WithPayload(payload)
  133. .Build();
  134. Task<MqttClientPublishResult> task = mqttClient.PublishAsync(applicationMessage);
  135. task.Wait();
  136. return true;
  137. }
  138. catch
  139. {
  140. //throw new Exception("云端连接错误");
  141. return false;
  142. }
  143. }
  144. }
  145. }