Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 

418 linhas
17 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. using MQTTnet.Core.Adapter;
  7. using MQTTnet.Core.Diagnostics;
  8. using MQTTnet.Core.Exceptions;
  9. using MQTTnet.Core.Internal;
  10. using MQTTnet.Core.Packets;
  11. using MQTTnet.Core.Protocol;
  12. namespace MQTTnet.Core.Client
  13. {
  14. public class MqttClient : IMqttClient
  15. {
  16. private readonly HashSet<ushort> _unacknowledgedPublishPackets = new HashSet<ushort>();
  17. private readonly MqttPacketDispatcher _packetDispatcher = new MqttPacketDispatcher();
  18. private readonly MqttClientOptions _options;
  19. private readonly IMqttCommunicationAdapter _adapter;
  20. private bool _disconnectedEventSuspended;
  21. private int _latestPacketIdentifier;
  22. private CancellationTokenSource _cancellationTokenSource;
  23. public MqttClient(MqttClientOptions options, IMqttCommunicationAdapter adapter)
  24. {
  25. _options = options ?? throw new ArgumentNullException(nameof(options));
  26. _adapter = adapter ?? throw new ArgumentNullException(nameof(adapter));
  27. _adapter.PacketSerializer.ProtocolVersion = options.ProtocolVersion;
  28. }
  29. public event EventHandler Connected;
  30. public event EventHandler Disconnected;
  31. public event EventHandler<MqttApplicationMessageReceivedEventArgs> ApplicationMessageReceived;
  32. public bool IsConnected { get; private set; }
  33. public async Task ConnectAsync(MqttApplicationMessage willApplicationMessage = null)
  34. {
  35. MqttTrace.Verbose(nameof(MqttClient), "Trying to connect.");
  36. if (IsConnected)
  37. {
  38. throw new MqttProtocolViolationException("It is not allowed to connect with a server after the connection is established.");
  39. }
  40. try
  41. {
  42. _disconnectedEventSuspended = false;
  43. await _adapter.ConnectAsync(_options, _options.DefaultCommunicationTimeout).ConfigureAwait(false);
  44. MqttTrace.Verbose(nameof(MqttClient), "Connection with server established.");
  45. var connectPacket = new MqttConnectPacket
  46. {
  47. ClientId = _options.ClientId,
  48. Username = _options.UserName,
  49. Password = _options.Password,
  50. CleanSession = _options.CleanSession,
  51. KeepAlivePeriod = (ushort)_options.KeepAlivePeriod.TotalSeconds,
  52. WillMessage = willApplicationMessage
  53. };
  54. _cancellationTokenSource = new CancellationTokenSource();
  55. _latestPacketIdentifier = 0;
  56. _packetDispatcher.Reset();
  57. StartReceivePackets();
  58. var response = await SendAndReceiveAsync<MqttConnAckPacket>(connectPacket).ConfigureAwait(false);
  59. if (response.ConnectReturnCode != MqttConnectReturnCode.ConnectionAccepted)
  60. {
  61. await DisconnectInternalAsync().ConfigureAwait(false);
  62. throw new MqttConnectingFailedException(response.ConnectReturnCode);
  63. }
  64. if (_options.KeepAlivePeriod != TimeSpan.Zero)
  65. {
  66. StartSendKeepAliveMessages();
  67. }
  68. MqttTrace.Verbose(nameof(MqttClient), "MQTT connection with server established.");
  69. IsConnected = true;
  70. Connected?.Invoke(this, EventArgs.Empty);
  71. }
  72. catch (Exception)
  73. {
  74. await DisconnectInternalAsync().ConfigureAwait(false);
  75. throw;
  76. }
  77. }
  78. public async Task DisconnectAsync()
  79. {
  80. try
  81. {
  82. await SendAsync(new MqttDisconnectPacket()).ConfigureAwait(false);
  83. }
  84. finally
  85. {
  86. await DisconnectInternalAsync().ConfigureAwait(false);
  87. }
  88. }
  89. public Task<IList<MqttSubscribeResult>> SubscribeAsync(params TopicFilter[] topicFilters)
  90. {
  91. if (topicFilters == null) throw new ArgumentNullException(nameof(topicFilters));
  92. return SubscribeAsync(topicFilters.ToList());
  93. }
  94. public async Task<IList<MqttSubscribeResult>> SubscribeAsync(IList<TopicFilter> topicFilters)
  95. {
  96. if (topicFilters == null) throw new ArgumentNullException(nameof(topicFilters));
  97. if (!topicFilters.Any()) throw new MqttProtocolViolationException("At least one topic filter must be set [MQTT-3.8.3-3].");
  98. ThrowIfNotConnected();
  99. var subscribePacket = new MqttSubscribePacket
  100. {
  101. PacketIdentifier = GetNewPacketIdentifier(),
  102. TopicFilters = topicFilters
  103. };
  104. var response = await SendAndReceiveAsync<MqttSubAckPacket>(subscribePacket).ConfigureAwait(false);
  105. if (response.SubscribeReturnCodes.Count != topicFilters.Count)
  106. {
  107. throw new MqttProtocolViolationException("The return codes are not matching the topic filters [MQTT-3.9.3-1].");
  108. }
  109. return topicFilters.Select((t, i) => new MqttSubscribeResult(t, response.SubscribeReturnCodes[i])).ToList();
  110. }
  111. public Task Unsubscribe(params string[] topicFilters)
  112. {
  113. if (topicFilters == null) throw new ArgumentNullException(nameof(topicFilters));
  114. return Unsubscribe(topicFilters.ToList());
  115. }
  116. public Task Unsubscribe(IList<string> topicFilters)
  117. {
  118. if (topicFilters == null) throw new ArgumentNullException(nameof(topicFilters));
  119. if (!topicFilters.Any()) throw new MqttProtocolViolationException("At least one topic filter must be set [MQTT-3.10.3-2].");
  120. ThrowIfNotConnected();
  121. var unsubscribePacket = new MqttUnsubscribePacket
  122. {
  123. PacketIdentifier = GetNewPacketIdentifier(),
  124. TopicFilters = topicFilters
  125. };
  126. return SendAndReceiveAsync<MqttUnsubAckPacket>(unsubscribePacket);
  127. }
  128. public async Task PublishAsync(IEnumerable<MqttApplicationMessage> applicationMessages)
  129. {
  130. ThrowIfNotConnected();
  131. var publishPackets = applicationMessages.Select(m => m.ToPublishPacket());
  132. foreach (var qosGroup in publishPackets.GroupBy(p => p.QualityOfServiceLevel))
  133. {
  134. var qosPackets = qosGroup.ToArray();
  135. switch ( qosGroup.Key )
  136. {
  137. case MqttQualityOfServiceLevel.AtMostOnce:
  138. // No packet identifier is used for QoS 0 [3.3.2.2 Packet Identifier]
  139. await _adapter.SendPacketsAsync(_options.DefaultCommunicationTimeout, qosPackets);
  140. break;
  141. case MqttQualityOfServiceLevel.AtLeastOnce:
  142. {
  143. foreach (var publishPacket in qosPackets)
  144. {
  145. publishPacket.PacketIdentifier = GetNewPacketIdentifier();
  146. await SendAndReceiveAsync<MqttPubAckPacket>(publishPacket);
  147. }
  148. break;
  149. }
  150. case MqttQualityOfServiceLevel.ExactlyOnce:
  151. {
  152. foreach (var publishPacket in qosPackets)
  153. {
  154. publishPacket.PacketIdentifier = GetNewPacketIdentifier();
  155. await PublishExactlyOncePacketAsync( publishPacket );
  156. }
  157. break;
  158. }
  159. default:
  160. throw new InvalidOperationException();
  161. }
  162. }
  163. }
  164. private async Task PublishExactlyOncePacketAsync(MqttBasePacket publishPacket)
  165. {
  166. var pubRecPacket = await SendAndReceiveAsync<MqttPubRecPacket>(publishPacket).ConfigureAwait(false);
  167. await SendAndReceiveAsync<MqttPubCompPacket>(pubRecPacket.CreateResponse<MqttPubRelPacket>()).ConfigureAwait(false);
  168. }
  169. private void ThrowIfNotConnected()
  170. {
  171. if (!IsConnected) throw new MqttCommunicationException("The client is not connected.");
  172. }
  173. private async Task DisconnectInternalAsync()
  174. {
  175. try
  176. {
  177. await _adapter.DisconnectAsync();
  178. }
  179. catch (Exception exception)
  180. {
  181. MqttTrace.Warning(nameof(MqttClient), exception, "Error while disconnecting.");
  182. }
  183. finally
  184. {
  185. _cancellationTokenSource?.Cancel(false);
  186. _cancellationTokenSource?.Dispose();
  187. _cancellationTokenSource = null;
  188. IsConnected = false;
  189. if (!_disconnectedEventSuspended)
  190. {
  191. _disconnectedEventSuspended = true;
  192. Disconnected?.Invoke(this, EventArgs.Empty);
  193. }
  194. }
  195. }
  196. private async Task ProcessReceivedPacketAsync(MqttBasePacket mqttPacket)
  197. {
  198. try
  199. {
  200. if (mqttPacket is MqttPingReqPacket)
  201. {
  202. await SendAsync(new MqttPingRespPacket());
  203. }
  204. if (mqttPacket is MqttDisconnectPacket)
  205. {
  206. await DisconnectAsync();
  207. }
  208. if (mqttPacket is MqttPublishPacket publishPacket)
  209. {
  210. await ProcessReceivedPublishPacket(publishPacket);
  211. }
  212. if (mqttPacket is MqttPubRelPacket pubRelPacket)
  213. {
  214. await ProcessReceivedPubRelPacket(pubRelPacket);
  215. }
  216. _packetDispatcher.Dispatch(mqttPacket);
  217. }
  218. catch (Exception exception)
  219. {
  220. MqttTrace.Error(nameof(MqttClient), exception, "Error while processing received packet.");
  221. }
  222. }
  223. private void FireApplicationMessageReceivedEvent(MqttPublishPacket publishPacket)
  224. {
  225. var applicationMessage = publishPacket.ToApplicationMessage();
  226. try
  227. {
  228. ApplicationMessageReceived?.Invoke(this, new MqttApplicationMessageReceivedEventArgs(applicationMessage));
  229. }
  230. catch (Exception exception)
  231. {
  232. MqttTrace.Error(nameof(MqttClient), exception, "Unhandled exception while handling application message.");
  233. }
  234. }
  235. private async Task ProcessReceivedPublishPacket(MqttPublishPacket publishPacket)
  236. {
  237. if (publishPacket.QualityOfServiceLevel == MqttQualityOfServiceLevel.AtMostOnce)
  238. {
  239. FireApplicationMessageReceivedEvent(publishPacket);
  240. }
  241. if (publishPacket.QualityOfServiceLevel == MqttQualityOfServiceLevel.AtLeastOnce)
  242. {
  243. FireApplicationMessageReceivedEvent(publishPacket);
  244. await SendAsync(new MqttPubAckPacket { PacketIdentifier = publishPacket.PacketIdentifier });
  245. }
  246. if (publishPacket.QualityOfServiceLevel == MqttQualityOfServiceLevel.ExactlyOnce)
  247. {
  248. // QoS 2 is implement as method "B" [4.3.3 QoS 2: Exactly once delivery]
  249. lock (_unacknowledgedPublishPackets)
  250. {
  251. _unacknowledgedPublishPackets.Add(publishPacket.PacketIdentifier);
  252. }
  253. FireApplicationMessageReceivedEvent(publishPacket);
  254. await SendAsync(new MqttPubRecPacket { PacketIdentifier = publishPacket.PacketIdentifier });
  255. }
  256. throw new MqttCommunicationException("Received a not supported QoS level.");
  257. }
  258. private Task ProcessReceivedPubRelPacket(MqttPubRelPacket pubRelPacket)
  259. {
  260. lock (_unacknowledgedPublishPackets)
  261. {
  262. _unacknowledgedPublishPackets.Remove(pubRelPacket.PacketIdentifier);
  263. }
  264. return SendAsync(pubRelPacket.CreateResponse<MqttPubCompPacket>());
  265. }
  266. private Task SendAsync(MqttBasePacket packet)
  267. {
  268. return _adapter.SendPacketsAsync(_options.DefaultCommunicationTimeout, packet);
  269. }
  270. private async Task<TResponsePacket> SendAndReceiveAsync<TResponsePacket>(MqttBasePacket requestPacket) where TResponsePacket : MqttBasePacket
  271. {
  272. await _adapter.SendPacketsAsync( _options.DefaultCommunicationTimeout, requestPacket ).ConfigureAwait(false);
  273. return (TResponsePacket)await _packetDispatcher.WaitForPacketAsync(requestPacket, typeof( TResponsePacket ), _options.DefaultCommunicationTimeout).ConfigureAwait(false);
  274. }
  275. private ushort GetNewPacketIdentifier()
  276. {
  277. return (ushort)Interlocked.Increment(ref _latestPacketIdentifier);
  278. }
  279. private async Task SendKeepAliveMessagesAsync(CancellationToken cancellationToken)
  280. {
  281. MqttTrace.Information(nameof(MqttClient), "Start sending keep alive packets.");
  282. try
  283. {
  284. while (!cancellationToken.IsCancellationRequested)
  285. {
  286. await Task.Delay(_options.KeepAlivePeriod, cancellationToken).ConfigureAwait(false);
  287. await SendAndReceiveAsync<MqttPingRespPacket>(new MqttPingReqPacket()).ConfigureAwait(false);
  288. }
  289. }
  290. catch (MqttCommunicationException exception)
  291. {
  292. MqttTrace.Warning(nameof(MqttClient), exception, "MQTT communication error while receiving packets.");
  293. await DisconnectInternalAsync().ConfigureAwait(false);
  294. }
  295. catch (Exception exception)
  296. {
  297. MqttTrace.Warning(nameof(MqttClient), exception, "Error while sending/receiving keep alive packets.");
  298. await DisconnectInternalAsync().ConfigureAwait(false);
  299. }
  300. finally
  301. {
  302. MqttTrace.Information(nameof(MqttClient), "Stopped sending keep alive packets.");
  303. }
  304. }
  305. private async Task ReceivePackets(CancellationToken cancellationToken)
  306. {
  307. MqttTrace.Information(nameof(MqttClient), "Start receiving packets.");
  308. try
  309. {
  310. while (!cancellationToken.IsCancellationRequested)
  311. {
  312. var packet = await _adapter.ReceivePacketAsync(TimeSpan.Zero).ConfigureAwait(false);
  313. MqttTrace.Information(nameof(MqttClient), "Received <<< {0}", packet);
  314. StartProcessReceivedPacket(packet, cancellationToken);
  315. }
  316. }
  317. catch (MqttCommunicationException exception)
  318. {
  319. MqttTrace.Warning(nameof(MqttClient), exception, "MQTT communication exception while receiving packets.");
  320. await DisconnectInternalAsync().ConfigureAwait(false);
  321. }
  322. catch (Exception exception)
  323. {
  324. MqttTrace.Error(nameof(MqttClient), exception, "Unhandled exception while receiving packets.");
  325. await DisconnectInternalAsync().ConfigureAwait(false);
  326. }
  327. finally
  328. {
  329. MqttTrace.Information(nameof(MqttClient), "Stopped receiving packets.");
  330. }
  331. }
  332. private void StartProcessReceivedPacket(MqttBasePacket packet, CancellationToken cancellationToken)
  333. {
  334. #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
  335. Task.Run(() => ProcessReceivedPacketAsync(packet), cancellationToken);
  336. #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
  337. }
  338. private void StartReceivePackets()
  339. {
  340. #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
  341. Task.Run(() => ReceivePackets(_cancellationTokenSource.Token), _cancellationTokenSource.Token);
  342. #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
  343. }
  344. private void StartSendKeepAliveMessages()
  345. {
  346. #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
  347. Task.Run(() => SendKeepAliveMessagesAsync(_cancellationTokenSource.Token), _cancellationTokenSource.Token);
  348. #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
  349. }
  350. }
  351. }