终端一体化运控平台
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

MQTTProxy.cs 7.5 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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. }