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.
 
 
 
 

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