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.

MqttClient.cs 17 KiB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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 Task PublishAsync(MqttApplicationMessage applicationMessage)
  129. {
  130. if (applicationMessage == null) throw new ArgumentNullException(nameof(applicationMessage));
  131. ThrowIfNotConnected();
  132. var publishPacket = applicationMessage.ToPublishPacket();
  133. if (publishPacket.QualityOfServiceLevel == MqttQualityOfServiceLevel.AtMostOnce)
  134. {
  135. // No packet identifier is used for QoS 0 [3.3.2.2 Packet Identifier]
  136. return SendAsync(publishPacket);
  137. }
  138. if (publishPacket.QualityOfServiceLevel == MqttQualityOfServiceLevel.AtLeastOnce)
  139. {
  140. publishPacket.PacketIdentifier = GetNewPacketIdentifier();
  141. return SendAndReceiveAsync<MqttPubAckPacket>(publishPacket);
  142. }
  143. if (publishPacket.QualityOfServiceLevel == MqttQualityOfServiceLevel.ExactlyOnce)
  144. {
  145. publishPacket.PacketIdentifier = GetNewPacketIdentifier();
  146. return PublishExactlyOncePacketAsync(publishPacket);
  147. }
  148. throw new InvalidOperationException();
  149. }
  150. private async Task PublishExactlyOncePacketAsync(MqttBasePacket publishPacket)
  151. {
  152. var pubRecPacket = await SendAndReceiveAsync<MqttPubRecPacket>(publishPacket).ConfigureAwait(false);
  153. await SendAndReceiveAsync<MqttPubCompPacket>(pubRecPacket.CreateResponse<MqttPubRelPacket>()).ConfigureAwait(false);
  154. }
  155. private void ThrowIfNotConnected()
  156. {
  157. if (!IsConnected) throw new MqttCommunicationException("The client is not connected.");
  158. }
  159. private Task DisconnectInternalAsync()
  160. {
  161. try
  162. {
  163. return _adapter.DisconnectAsync();
  164. }
  165. catch (Exception exception)
  166. {
  167. MqttTrace.Warning(nameof(MqttClient), exception, "Error while disconnecting.");
  168. return Task.FromResult(0);
  169. }
  170. finally
  171. {
  172. _cancellationTokenSource?.Cancel(false);
  173. _cancellationTokenSource?.Dispose();
  174. _cancellationTokenSource = null;
  175. IsConnected = false;
  176. if (!_disconnectedEventSuspended)
  177. {
  178. _disconnectedEventSuspended = true;
  179. Disconnected?.Invoke(this, EventArgs.Empty);
  180. }
  181. }
  182. }
  183. private Task ProcessReceivedPacketAsync(MqttBasePacket mqttPacket)
  184. {
  185. try
  186. {
  187. if (mqttPacket is MqttPingReqPacket)
  188. {
  189. return SendAsync(new MqttPingRespPacket());
  190. }
  191. if (mqttPacket is MqttDisconnectPacket)
  192. {
  193. return DisconnectAsync();
  194. }
  195. if (mqttPacket is MqttPublishPacket publishPacket)
  196. {
  197. return ProcessReceivedPublishPacket(publishPacket);
  198. }
  199. if (mqttPacket is MqttPubRelPacket pubRelPacket)
  200. {
  201. return ProcessReceivedPubRelPacket(pubRelPacket);
  202. }
  203. _packetDispatcher.Dispatch(mqttPacket);
  204. }
  205. catch (Exception exception)
  206. {
  207. MqttTrace.Error(nameof(MqttClient), exception, "Error while processing received packet.");
  208. }
  209. return Task.FromResult(0);
  210. }
  211. private void FireApplicationMessageReceivedEvent(MqttPublishPacket publishPacket)
  212. {
  213. var applicationMessage = publishPacket.ToApplicationMessage();
  214. try
  215. {
  216. ApplicationMessageReceived?.Invoke(this, new MqttApplicationMessageReceivedEventArgs(applicationMessage));
  217. }
  218. catch (Exception exception)
  219. {
  220. MqttTrace.Error(nameof(MqttClient), exception, "Unhandled exception while handling application message.");
  221. }
  222. }
  223. private Task ProcessReceivedPublishPacket(MqttPublishPacket publishPacket)
  224. {
  225. if (publishPacket.QualityOfServiceLevel == MqttQualityOfServiceLevel.AtMostOnce)
  226. {
  227. FireApplicationMessageReceivedEvent(publishPacket);
  228. return Task.FromResult(0);
  229. }
  230. if (publishPacket.QualityOfServiceLevel == MqttQualityOfServiceLevel.AtLeastOnce)
  231. {
  232. FireApplicationMessageReceivedEvent(publishPacket);
  233. return SendAsync(new MqttPubAckPacket { PacketIdentifier = publishPacket.PacketIdentifier });
  234. }
  235. if (publishPacket.QualityOfServiceLevel == MqttQualityOfServiceLevel.ExactlyOnce)
  236. {
  237. // QoS 2 is implement as method "B" [4.3.3 QoS 2: Exactly once delivery]
  238. lock (_unacknowledgedPublishPackets)
  239. {
  240. _unacknowledgedPublishPackets.Add(publishPacket.PacketIdentifier);
  241. }
  242. FireApplicationMessageReceivedEvent(publishPacket);
  243. return SendAsync(new MqttPubRecPacket { PacketIdentifier = publishPacket.PacketIdentifier });
  244. }
  245. throw new MqttCommunicationException("Received a not supported QoS level.");
  246. }
  247. private Task ProcessReceivedPubRelPacket(MqttPubRelPacket pubRelPacket)
  248. {
  249. lock (_unacknowledgedPublishPackets)
  250. {
  251. _unacknowledgedPublishPackets.Remove(pubRelPacket.PacketIdentifier);
  252. }
  253. return SendAsync(pubRelPacket.CreateResponse<MqttPubCompPacket>());
  254. }
  255. private Task SendAsync(MqttBasePacket packet)
  256. {
  257. return _adapter.SendPacketAsync(packet, _options.DefaultCommunicationTimeout);
  258. }
  259. private async Task<TResponsePacket> SendAndReceiveAsync<TResponsePacket>(MqttBasePacket requestPacket) where TResponsePacket : MqttBasePacket
  260. {
  261. bool ResponsePacketSelector(MqttBasePacket p)
  262. {
  263. if (!(p is TResponsePacket p1))
  264. {
  265. return false;
  266. }
  267. if (!(requestPacket is IMqttPacketWithIdentifier pi1) || !(p is IMqttPacketWithIdentifier pi2))
  268. {
  269. return true;
  270. }
  271. return pi1.PacketIdentifier == pi2.PacketIdentifier;
  272. }
  273. await _adapter.SendPacketAsync(requestPacket, _options.DefaultCommunicationTimeout).ConfigureAwait(false);
  274. return (TResponsePacket)await _packetDispatcher.WaitForPacketAsync(ResponsePacketSelector, _options.DefaultCommunicationTimeout).ConfigureAwait(false);
  275. }
  276. private ushort GetNewPacketIdentifier()
  277. {
  278. return (ushort)Interlocked.Increment(ref _latestPacketIdentifier);
  279. }
  280. private async Task SendKeepAliveMessagesAsync(CancellationToken cancellationToken)
  281. {
  282. MqttTrace.Information(nameof(MqttClient), "Start sending keep alive packets.");
  283. try
  284. {
  285. while (!cancellationToken.IsCancellationRequested)
  286. {
  287. await Task.Delay(_options.KeepAlivePeriod, cancellationToken).ConfigureAwait(false);
  288. await SendAndReceiveAsync<MqttPingRespPacket>(new MqttPingReqPacket()).ConfigureAwait(false);
  289. }
  290. }
  291. catch (MqttCommunicationException exception)
  292. {
  293. MqttTrace.Warning(nameof(MqttClient), exception, "MQTT communication error while receiving packets.");
  294. await DisconnectInternalAsync().ConfigureAwait(false);
  295. }
  296. catch (Exception exception)
  297. {
  298. MqttTrace.Warning(nameof(MqttClient), exception, "Error while sending/receiving keep alive packets.");
  299. await DisconnectInternalAsync().ConfigureAwait(false);
  300. }
  301. finally
  302. {
  303. MqttTrace.Information(nameof(MqttClient), "Stopped sending keep alive packets.");
  304. }
  305. }
  306. private async Task ReceivePackets(CancellationToken cancellationToken)
  307. {
  308. MqttTrace.Information(nameof(MqttClient), "Start receiving packets.");
  309. try
  310. {
  311. while (!cancellationToken.IsCancellationRequested)
  312. {
  313. var packet = await _adapter.ReceivePacketAsync(TimeSpan.Zero).ConfigureAwait(false);
  314. MqttTrace.Information(nameof(MqttClient), "Received <<< {0}", packet);
  315. StartProcessReceivedPacket(packet, cancellationToken);
  316. }
  317. }
  318. catch (MqttCommunicationException exception)
  319. {
  320. MqttTrace.Warning(nameof(MqttClient), exception, "MQTT communication exception while receiving packets.");
  321. await DisconnectInternalAsync().ConfigureAwait(false);
  322. }
  323. catch (Exception exception)
  324. {
  325. MqttTrace.Error(nameof(MqttClient), exception, "Unhandled exception while receiving packets.");
  326. await DisconnectInternalAsync().ConfigureAwait(false);
  327. }
  328. finally
  329. {
  330. MqttTrace.Information(nameof(MqttClient), "Stopped receiving packets.");
  331. }
  332. }
  333. private void StartProcessReceivedPacket(MqttBasePacket packet, CancellationToken cancellationToken)
  334. {
  335. #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
  336. Task.Run(() => ProcessReceivedPacketAsync(packet), cancellationToken);
  337. #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
  338. }
  339. private void StartReceivePackets()
  340. {
  341. #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
  342. Task.Run(() => ReceivePackets(_cancellationTokenSource.Token), _cancellationTokenSource.Token);
  343. #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
  344. }
  345. private void StartSendKeepAliveMessages()
  346. {
  347. #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
  348. Task.Run(() => SendKeepAliveMessagesAsync(_cancellationTokenSource.Token), _cancellationTokenSource.Token);
  349. #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
  350. }
  351. }
  352. }