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.
 
 
 
 

540 lines
22 KiB

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