终端一体化运控平台
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 

259 行
7.5 KiB

  1. //using BPA.MQTTClient;
  2. //using Microsoft.Extensions.Configuration;
  3. //using MQTTnet.Client;
  4. //using MQTTnet.Client;
  5. //using MQTTnet;
  6. //using MQTTnet.Client;
  7. //using MQTTnet.Client.Options;
  8. //using MQTTnet.Client.Receiving;
  9. using BPASmartClient.Helper;
  10. using BPASmartClient.Message;
  11. using MQTTnet;
  12. using MQTTnet.Client;
  13. using MQTTnet.Client.Options;
  14. using System;
  15. using System.Collections.Generic;
  16. using System.IO;
  17. using System.Linq;
  18. using System.Text;
  19. using System.Threading;
  20. using System.Threading.Tasks;
  21. namespace BPASmartClient.MQTT
  22. {
  23. public class MQTTProxy
  24. {
  25. private IMqttClient client;
  26. IMqttClientOptions options;
  27. public Action<string> MessageRecive { get; set; }
  28. public Action Connected { get; set; }
  29. public Action LostConnect { get; set; }
  30. public bool IsConnected { get; set; }
  31. Action UseDisconnectedAction;
  32. public async void Connect(string UserName, string pass, string IP, int port, string clientID)
  33. {
  34. options = new MqttClientOptionsBuilder().WithTcpServer(IP, port).WithClientId(clientID).WithCredentials(UserName, pass).Build();
  35. client = new MqttFactory().CreateMqttClient();
  36. client.UseDisconnectedHandler(c =>
  37. {
  38. if (UseDisconnectedAction == null)
  39. {
  40. Reconnect();//注册UseDisconnectedAction委托
  41. UseDisconnectedAction();//执行委托
  42. }
  43. }).UseApplicationMessageReceivedHandler(c =>
  44. {
  45. MessageRecive?.Invoke(Encoding.UTF8.GetString(c.ApplicationMessage.Payload));
  46. }).UseConnectedHandler((e) =>
  47. {
  48. //MessageLog.GetInstance.Show($"连接成功");
  49. });
  50. try
  51. {
  52. await client.ConnectAsync(options);
  53. }
  54. catch (Exception ex)
  55. {
  56. MessageLog.GetInstance.ShowEx(ex.Message);
  57. MessageLog.GetInstance.Show("mqtt连接失败!重连执行中");
  58. }
  59. if (client.IsConnected)
  60. {
  61. MessageLog.GetInstance.Show("MQTT连接成功!");
  62. Connected?.Invoke();
  63. }
  64. }
  65. private void Reconnect()
  66. {
  67. UseDisconnectedAction = new Action(() =>
  68. {
  69. MessageLog.GetInstance.ShowEx("MQTT 断开连接");
  70. Thread.Sleep(2000);
  71. while (!UniversalHelper.GetInstance().GetNetworkState())
  72. {
  73. Thread.Sleep(2000);
  74. }
  75. bool ErrorFlag = false;
  76. while (!client.IsConnected)
  77. {
  78. try
  79. {
  80. MessageLog.GetInstance.Show($"重连中");
  81. client.ConnectAsync(options).Wait();
  82. }
  83. catch (Exception ex)
  84. {
  85. if (!ErrorFlag)
  86. {
  87. MessageLog.GetInstance.ShowEx(ex.ToString());
  88. ErrorFlag = true;
  89. }
  90. }
  91. Thread.Sleep(3000);
  92. }
  93. if (client.IsConnected)
  94. {
  95. MessageLog.GetInstance.Show("MQTT重连成功!");
  96. LostConnect?.Invoke();
  97. }
  98. UseDisconnectedAction = null;
  99. });
  100. }
  101. /// <summary>
  102. /// Mqtt 订阅
  103. /// </summary>
  104. /// <param name="topic">需要订阅的主题</param>
  105. public async void MqttSubscriptionAsync(string topic)
  106. {
  107. if (client != null && client.IsConnected)
  108. {
  109. try
  110. {
  111. var result = await client.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic(topic).WithExactlyOnceQoS().Build());
  112. }
  113. catch { }
  114. }
  115. }
  116. /// <summary>
  117. /// Mqtt 订阅
  118. /// </summary>
  119. /// <param name="topic">需要订阅的主题</param>
  120. public async void Subscrib(params string[] topic)
  121. {
  122. if (client != null && client.IsConnected)
  123. {
  124. try
  125. {
  126. foreach (var item in topic)
  127. {
  128. var result = await client.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic(item).WithExactlyOnceQoS().Build());
  129. }
  130. }
  131. catch { }
  132. }
  133. }
  134. /// <summary>
  135. /// Mqtt 发布
  136. /// </summary>
  137. /// <param name="topic">需要发布的主题</param>
  138. /// <param name="content">需要发布的内容</param>
  139. public async void Publish(string topic, string content)
  140. {
  141. if (client != null && client.IsConnected)
  142. {
  143. var msg = new MqttApplicationMessageBuilder().WithTopic(topic).WithPayload(content).WithExactlyOnceQoS().Build();
  144. try
  145. {
  146. var result = await client.PublishAsync(msg);
  147. }
  148. catch { }
  149. }
  150. }
  151. //public Action<string> MessageRecive { get; set; }
  152. //public Action Connected { get; set; }
  153. //public Action LostConnect { get; set; }
  154. //public bool IsConnected { get; set; }
  155. //private IMqttClient client;
  156. //public void Connect(string userName, string Password, string ip, int port, string clientId)
  157. //{
  158. // IConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
  159. // configurationBuilder.AddMqttClientHostedService(p =>
  160. // {
  161. // p.Server = ip;
  162. // p.Port = port;
  163. // //p.UserName = "rafiul";
  164. // //p.Password = "12345678";
  165. // p.UserName = userName;
  166. // p.Password = Password;
  167. // p.mqttClientConnectedHandlerDelegate = new MQTTnet.Client.Connecting.MqttClientConnectedHandlerDelegate(e =>
  168. // {
  169. // IsConnected = true;
  170. // Connected?.Invoke();
  171. // });
  172. // //p.mqttClientDisconnectedHandlerDelegate = new MQTTnet.Client.Disconnecting.MqttClientDisconnectedHandlerDelegate(e =>
  173. // //{
  174. // // IsConnected = false;
  175. // // LostConnect?.Invoke();
  176. // //});
  177. // p.ConnectedResult += (s, e) =>
  178. // {
  179. // client = e;
  180. // };
  181. // p.MqttApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(e =>
  182. // {
  183. // MessageRecive?.Invoke(Encoding.Default.GetString(e.ApplicationMessage.Payload));
  184. // });
  185. // });
  186. //}
  187. public void CloseConnect()
  188. {
  189. client.Dispose();
  190. }
  191. //public async void Publish(string topic, string content)
  192. //{
  193. // if (client.IsConnected)
  194. // await client.PublishAsync(topic, content);
  195. //}
  196. //public async void Subscrib(params string[] topics)
  197. //{
  198. // foreach (var topic in topics)
  199. // {
  200. // await client.SubscribeAsync(new MqttTopicFilter() { Topic = topic, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce });
  201. // }
  202. //}
  203. }
  204. }