终端一体化运控平台
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

184 lines
5.4 KiB

  1. using BPASmartClient.Helper;
  2. using HBLConsole.Service;
  3. using MQTTnet;
  4. using MQTTnet.Client;
  5. using MQTTnet.Client.Options;
  6. using System;
  7. using System.Threading;
  8. namespace HBLConsole.Communication
  9. {
  10. public class MqttHelper
  11. {
  12. private volatile static MqttHelper _Instance;
  13. public static MqttHelper GetInstance => _Instance ?? (_Instance = new MqttHelper());
  14. private MqttHelper() { }
  15. private IMqttClient client;
  16. IMqttClientOptions options;
  17. /// <summary>
  18. /// MQTT 接收消息
  19. /// </summary>
  20. public Action<MqttApplicationMessageReceivedEventArgs> MqttReceive { get; set; }
  21. /// <summary>
  22. /// MQTT 连接成功
  23. /// </summary>
  24. public Action ConnectOk { get; set; }
  25. /// <summary>
  26. /// 重连成功
  27. /// </summary>
  28. public Action Reconnection { get; set; }
  29. Action UseDisconnectedAction;
  30. public async void MqttInitAsync(string UserName, string pass, string IP, int port, string clientID)
  31. {
  32. options = new MqttClientOptionsBuilder().WithTcpServer(IP, port).WithClientId(clientID).WithCredentials(UserName, pass).Build();
  33. client = new MqttFactory().CreateMqttClient();
  34. client.UseDisconnectedHandler(c =>
  35. {
  36. if (UseDisconnectedAction == null)
  37. {
  38. Reconnect();
  39. UseDisconnectedAction();
  40. }
  41. }).UseApplicationMessageReceivedHandler(c =>
  42. {
  43. MqttReceive(c);
  44. }).UseConnectedHandler((e) =>
  45. {
  46. MessageLog.GetInstance.Show($"连接成功");
  47. });
  48. try
  49. {
  50. await client.ConnectAsync(options);
  51. }
  52. catch (Exception ex)
  53. {
  54. MessageLog.GetInstance.ShowEx(ex.Message);
  55. MessageLog.GetInstance.Show("mqtt连接失败!重连执行中");
  56. }
  57. if (client.IsConnected)
  58. {
  59. MessageLog.GetInstance.Show("MQTT连接成功!");
  60. if (ConnectOk != null) ConnectOk();
  61. }
  62. }
  63. private void Reconnect()
  64. {
  65. UseDisconnectedAction = new Action(() =>
  66. {
  67. Thread.Sleep(2000);
  68. while (!UniversalHelper.GetInstance().GetNetworkState())
  69. {
  70. Thread.Sleep(2000);
  71. }
  72. MessageLog.GetInstance.Show($"断开连接");
  73. bool ErrorFlag = false;
  74. while (!client.IsConnected)
  75. {
  76. try
  77. {
  78. MessageLog.GetInstance.Show($"重连中");
  79. client.ConnectAsync(options).Wait();
  80. }
  81. catch (Exception ex)
  82. {
  83. if (!ErrorFlag)
  84. {
  85. MessageLog.GetInstance.ShowEx(ex.ToString());
  86. ErrorFlag = true;
  87. }
  88. }
  89. Thread.Sleep(3000);
  90. }
  91. if (client.IsConnected)
  92. {
  93. MessageLog.GetInstance.Show("MQTT重连成功!");
  94. if (Reconnection != null) Reconnection();
  95. }
  96. UseDisconnectedAction = null;
  97. });
  98. }
  99. /// <summary>
  100. /// Mqtt 订阅
  101. /// </summary>
  102. /// <param name="topic">需要订阅的主题</param>
  103. public async void MqttSubscriptionAsync(string topic)
  104. {
  105. if (client != null)
  106. {
  107. if (client.IsConnected)
  108. {
  109. try
  110. {
  111. var result = await client.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic(topic).WithExactlyOnceQoS().Build());
  112. }
  113. catch { }
  114. }
  115. }
  116. }
  117. /// <summary>
  118. /// Mqtt 订阅
  119. /// </summary>
  120. /// <param name="topic">需要订阅的主题</param>
  121. public async void MqttSubscriptionAsync(string[] topic)
  122. {
  123. if (client != null)
  124. {
  125. if (client.IsConnected)
  126. {
  127. try
  128. {
  129. foreach (var item in topic)
  130. {
  131. var result = await client.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic(item).WithExactlyOnceQoS().Build());
  132. }
  133. }
  134. catch { }
  135. }
  136. }
  137. }
  138. /// <summary>
  139. /// Mqtt 发布
  140. /// </summary>
  141. /// <param name="topic">需要发布的主题</param>
  142. /// <param name="content">需要发布的内容</param>
  143. public async void MqttPublishAsync(string topic, string content)
  144. {
  145. if (client != null)
  146. {
  147. if (client.IsConnected)
  148. {
  149. var msg = new MqttApplicationMessageBuilder().WithTopic(topic).WithPayload(content).WithExactlyOnceQoS().Build();
  150. try
  151. {
  152. var result = await client.PublishAsync(msg);
  153. }
  154. catch { }
  155. }
  156. }
  157. }
  158. }
  159. }