MqttHelper.cs 9.9 KB

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