终端一体化运控平台
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 

262 líneas
7.5 KiB

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