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.

MqttClient.cs 20 KiB

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