Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 

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