MqttHelper.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. using ivf_tl_Entity.GlobalEnums;
  2. using MQTTnet;
  3. using MQTTnet.Client;
  4. using MQTTnet.Protocol;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. namespace ivf_tl_Services
  12. {
  13. public class MqttHelper
  14. {
  15. public event Action<string> MessEvent;
  16. public event Action<string, LogEnum> ErrorLogEvent;
  17. public event Action<Exception, string, LogEnum> ExceptionLogEvent;
  18. private string _ip;
  19. private int _port;
  20. private string _username;
  21. private string _password;
  22. private string _clientId;
  23. private string _topicName;
  24. private IMqttClient _mqttClient;
  25. private MqttClientOptions clientOptions;
  26. public bool IsConnect = false;
  27. public MqttHelper(string ip, int port, string username, string password, string clientId, string topicName)
  28. {
  29. this._ip = ip;
  30. this._port = port;
  31. this._username = username;
  32. this._password = password;
  33. this._clientId = clientId;
  34. this._topicName = topicName;
  35. }
  36. public void DisPoseMqtt()
  37. {
  38. _mqttClient.Dispose();
  39. _mqttClient = null;
  40. }
  41. public void StartMqtt()
  42. {
  43. try
  44. {
  45. var mqttClientOptionsBuilder = new MqttClientOptionsBuilder()
  46. .WithTcpServer(_ip, _port)
  47. .WithCredentials(_username, _password)
  48. .WithClientId(_clientId)
  49. .WithCleanSession()
  50. .WithoutPacketFragmentation()
  51. .WithTls(new MqttClientOptionsBuilderTlsParameters()
  52. {
  53. UseTls = false,
  54. });
  55. clientOptions = mqttClientOptionsBuilder.Build();
  56. _mqttClient = new MqttFactory().CreateMqttClient();
  57. _mqttClient.ConnectedAsync -= _mqttClient_ConnectedAsync;
  58. _mqttClient.DisconnectedAsync -= _mqttClient_DisconnectedAsync;
  59. _mqttClient.ApplicationMessageReceivedAsync -= _mqttClient_ApplicationMessageReceivedAsync;
  60. _mqttClient.ConnectedAsync += _mqttClient_ConnectedAsync;
  61. _mqttClient.DisconnectedAsync += _mqttClient_DisconnectedAsync;
  62. _mqttClient.ApplicationMessageReceivedAsync += _mqttClient_ApplicationMessageReceivedAsync;
  63. Task.Run(() => ClientMqtt());
  64. //Task.Factory.StartNew(async () =>
  65. //{
  66. // while (true)
  67. // {
  68. // try
  69. // {
  70. // if (IsDispose)
  71. // {
  72. // ErrorLogEvent?.Invoke($"[clientId:{_clientId}][_topicName:{_topicName}][_ip:{_ip}][_port:{_port}] 主动关闭客户端", LogEnum.MqttClient);
  73. // await _mqttClient.DisconnectAsync();
  74. // _mqttClient.Dispose();
  75. // _mqttClient = null;
  76. // return;
  77. // }
  78. // else
  79. // {
  80. // if (!await _mqttClient.TryPingAsync())
  81. // {
  82. // ErrorLogEvent?.Invoke($"[clientId:{_clientId}][_topicName:{_topicName}][_ip:{_ip}][_port:{_port}] 客户端尝试连接服务器", LogEnum.MqttClient);
  83. // }
  84. // }
  85. // }
  86. // catch (Exception ex)
  87. // {
  88. // ExceptionLogEvent?.Invoke(ex, $"[clientId:{_clientId}][_topicName:{_topicName}][_ip:{_ip}][_port:{_port}] MQTT连接服务器", LogEnum.RunException);
  89. // }
  90. // finally
  91. // {
  92. // await Task.Delay(10000);
  93. // }
  94. // }
  95. //}, TaskCreationOptions.LongRunning);
  96. }
  97. catch (Exception ex)
  98. {
  99. ExceptionLogEvent?.Invoke(ex, "MQTT初始化", LogEnum.RunException);
  100. }
  101. }
  102. public void ClientMqtt()
  103. {
  104. bool b = false;
  105. for (int i = 1; i <= 3; i++)
  106. {
  107. ErrorLogEvent?.Invoke($"[clientId:{_clientId}][_topicName:{_topicName}][_ip:{_ip}][_port:{_port}] 第{i}次连接服务器", LogEnum.MqttClient);
  108. try
  109. {
  110. var a = _mqttClient.ConnectAsync(clientOptions).GetAwaiter().GetResult();
  111. if (a == null)
  112. {
  113. ErrorLogEvent?.Invoke($"[clientId:{_clientId}][_topicName:{_topicName}][_ip:{_ip}][_port:{_port}] 第{i}次连接服务器失败,返回空", LogEnum.RunError);
  114. Thread.Sleep(1000);
  115. continue;
  116. }
  117. if (a.ResultCode == MqttClientConnectResultCode.Success)
  118. {
  119. IsConnect = true;
  120. b = true;
  121. break;
  122. }
  123. else
  124. {
  125. ErrorLogEvent?.Invoke($"[clientId:{_clientId}][_topicName:{_topicName}][_ip:{_ip}][_port:{_port}] 第{i}次连接服务器失败{a.ResultCode}", LogEnum.RunError);
  126. Thread.Sleep(1000);
  127. }
  128. }
  129. catch (Exception ex)
  130. {
  131. ExceptionLogEvent?.Invoke(ex, $"[clientId:{_clientId}][_topicName:{_topicName}][_ip:{_ip}][_port:{_port}] 第{i}次连接MQTT服务器", LogEnum.RunException);
  132. Thread.Sleep(1000);
  133. }
  134. }
  135. if (!b)
  136. {
  137. Thread.Sleep(10000);
  138. ClientMqtt();
  139. }
  140. }
  141. /// <summary>
  142. /// 接收消息
  143. /// </summary>
  144. /// <param name="arg"></param>
  145. /// <returns></returns>
  146. /// <exception cref="NotImplementedException"></exception>
  147. private Task _mqttClient_ApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs arg)
  148. {
  149. try
  150. {
  151. //ErrorLogEvent?.Invoke($"ApplicationMessageReceivedAsync:客户端ID=【{arg.ClientId}】接收到消息。 Topic主题=【{arg.ApplicationMessage.Topic}】 消息=【{Encoding.UTF8.GetString(arg.ApplicationMessage.PayloadSegment)}】 qos等级=【{arg.ApplicationMessage.QualityOfServiceLevel}】", LogEnum.MqttClient);
  152. MessEvent?.Invoke(Encoding.UTF8.GetString(arg.ApplicationMessage.PayloadSegment));
  153. return Task.CompletedTask;
  154. }
  155. catch (Exception ex)
  156. {
  157. ExceptionLogEvent?.Invoke(ex, "MQTT消息处理", LogEnum.RunException);
  158. return Task.CompletedTask;
  159. }
  160. }
  161. /// <summary>
  162. /// 客户端连接关闭
  163. /// </summary>
  164. /// <param name="arg"></param>
  165. /// <returns></returns>
  166. /// <exception cref="NotImplementedException"></exception>
  167. private Task _mqttClient_DisconnectedAsync(MqttClientDisconnectedEventArgs arg)
  168. {
  169. try
  170. {
  171. if (!IsConnect) return Task.CompletedTask;
  172. ErrorLogEvent?.Invoke($"[clientId:{_clientId}][_topicName:{_topicName}][_ip:{_ip}][_port:{_port}]客户端已断开与服务端的连接……", LogEnum.MqttClient);
  173. ErrorLogEvent?.Invoke($"[clientId:{_clientId}][_topicName:{_topicName}][_ip:{_ip}][_port:{_port}]客户端已断开与服务端的连接……", LogEnum.RunError);
  174. IsConnect = false;
  175. ClientMqtt();
  176. return Task.CompletedTask;
  177. }
  178. catch (Exception ex)
  179. {
  180. ExceptionLogEvent?.Invoke(ex, "MQTT客户端连接关闭", LogEnum.RunException);
  181. return Task.CompletedTask;
  182. }
  183. }
  184. /// <summary>
  185. /// 客户端连接成功
  186. /// </summary>
  187. /// <param name="arg"></param>
  188. /// <returns></returns>
  189. /// <exception cref="NotImplementedException"></exception>
  190. private Task _mqttClient_ConnectedAsync(MqttClientConnectedEventArgs arg)
  191. {
  192. // 订阅消息主题 MqttQualityOfServiceLevel: (QoS):
  193. // 0 最多一次,接收者不确认收到消息,并且消息不被发送者存储和重新发送提供与底层 TCP 协议相同的保证。
  194. // 1: 保证一条消息至少有一次会传递给接收方。发送方存储消息,直到它从接收方收到确认收到消息的数据包。一条消息可以多次发送或传递。
  195. // 2: 保证每条消息仅由预期的收件人接收一次。级别2是最安全和最慢的服务质量级别,保证由发送方和接收方之间的至少两个请求/响应(四次握手)。
  196. try
  197. {
  198. ErrorLogEvent?.Invoke($"[clientId:{_clientId}][_topicName:{_topicName}][_ip:{_ip}][_port:{_port}]客户端连接服务器成功", LogEnum.MqttClient);
  199. _mqttClient.SubscribeAsync(_topicName, MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce);
  200. return Task.CompletedTask;
  201. }
  202. catch (Exception ex)
  203. {
  204. ExceptionLogEvent?.Invoke(ex, $"MQTT订阅{_topicName}", LogEnum.RunException);
  205. return Task.CompletedTask;
  206. }
  207. }
  208. public async Task PublishAsync(string data)
  209. {
  210. try
  211. {
  212. var message = new MqttApplicationMessage
  213. {
  214. Topic = "TL/House/collecting-data",
  215. PayloadSegment = Encoding.UTF8.GetBytes(data),
  216. QualityOfServiceLevel = MqttQualityOfServiceLevel.ExactlyOnce,
  217. Retain = false,
  218. // 服务端是否保留消息。true为保留,如果有新的订阅者连接,就会立马收到该消息。
  219. };
  220. await _mqttClient.PublishAsync(message);
  221. }
  222. catch (Exception ex)
  223. {
  224. ExceptionLogEvent?.Invoke(ex, $"MQTT发送消息", LogEnum.RunException);
  225. }
  226. }
  227. }
  228. }