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.

ManagedMqttClient.cs 15 KiB

il y a 7 ans
il y a 7 ans
il y a 7 ans
il y a 6 ans
il y a 6 ans
il y a 6 ans
il y a 6 ans
il y a 6 ans
il y a 6 ans
il y a 7 ans
il y a 7 ans
il y a 7 ans
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. using MQTTnet.Client;
  7. using MQTTnet.Diagnostics;
  8. using MQTTnet.Exceptions;
  9. using MQTTnet.Internal;
  10. using MQTTnet.Protocol;
  11. using MQTTnet.Server;
  12. using MqttClientConnectedEventArgs = MQTTnet.Client.MqttClientConnectedEventArgs;
  13. using MqttClientDisconnectedEventArgs = MQTTnet.Client.MqttClientDisconnectedEventArgs;
  14. namespace MQTTnet.Extensions.ManagedClient
  15. {
  16. public class ManagedMqttClient : IManagedMqttClient
  17. {
  18. private readonly BlockingQueue<ManagedMqttApplicationMessage> _messageQueue = new BlockingQueue<ManagedMqttApplicationMessage>();
  19. private readonly Dictionary<string, MqttQualityOfServiceLevel> _subscriptions = new Dictionary<string, MqttQualityOfServiceLevel>();
  20. private readonly HashSet<string> _unsubscriptions = new HashSet<string>();
  21. private readonly IMqttClient _mqttClient;
  22. private readonly IMqttNetChildLogger _logger;
  23. private CancellationTokenSource _connectionCancellationToken;
  24. private CancellationTokenSource _publishingCancellationToken;
  25. private ManagedMqttClientStorageManager _storageManager;
  26. private IManagedMqttClientOptions _options;
  27. private bool _subscriptionsNotPushed;
  28. public ManagedMqttClient(IMqttClient mqttClient, IMqttNetChildLogger logger)
  29. {
  30. if (logger == null) throw new ArgumentNullException(nameof(logger));
  31. _mqttClient = mqttClient ?? throw new ArgumentNullException(nameof(mqttClient));
  32. _mqttClient.Connected += OnConnected;
  33. _mqttClient.Disconnected += OnDisconnected;
  34. _mqttClient.ApplicationMessageReceived += OnApplicationMessageReceived;
  35. _logger = logger.CreateChildLogger(nameof(ManagedMqttClient));
  36. }
  37. public bool IsConnected => _mqttClient.IsConnected;
  38. public bool IsStarted => _connectionCancellationToken != null;
  39. public int PendingApplicationMessagesCount => _messageQueue.Count;
  40. public event EventHandler<MqttClientConnectedEventArgs> Connected;
  41. public event EventHandler<MqttClientDisconnectedEventArgs> Disconnected;
  42. public event EventHandler<MqttApplicationMessageReceivedEventArgs> ApplicationMessageReceived;
  43. public event EventHandler<ApplicationMessageProcessedEventArgs> ApplicationMessageProcessed;
  44. public event EventHandler<ApplicationMessageSkippedEventArgs> ApplicationMessageSkipped;
  45. public event EventHandler<MqttManagedProcessFailedEventArgs> ConnectingFailed;
  46. public event EventHandler<MqttManagedProcessFailedEventArgs> SynchronizingSubscriptionsFailed;
  47. public async Task StartAsync(IManagedMqttClientOptions options)
  48. {
  49. if (options == null) throw new ArgumentNullException(nameof(options));
  50. if (options.ClientOptions == null) throw new ArgumentException("The client options are not set.", nameof(options));
  51. if (!options.ClientOptions.CleanSession)
  52. {
  53. throw new NotSupportedException("The managed client does not support existing sessions.");
  54. }
  55. if (_connectionCancellationToken != null) throw new InvalidOperationException("The managed client is already started.");
  56. _options = options;
  57. if (_options.Storage != null)
  58. {
  59. _storageManager = new ManagedMqttClientStorageManager(_options.Storage);
  60. var messages = await _storageManager.LoadQueuedMessagesAsync().ConfigureAwait(false);
  61. foreach (var message in messages)
  62. {
  63. _messageQueue.Enqueue(message);
  64. }
  65. }
  66. _connectionCancellationToken = new CancellationTokenSource();
  67. #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
  68. Task.Run(() => MaintainConnectionAsync(_connectionCancellationToken.Token), _connectionCancellationToken.Token);
  69. #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
  70. _logger.Info("Started");
  71. }
  72. public Task StopAsync()
  73. {
  74. StopPublishing();
  75. StopMaintainingConnection();
  76. _messageQueue.Clear();
  77. return Task.FromResult(0);
  78. }
  79. public Task PublishAsync(MqttApplicationMessage applicationMessage)
  80. {
  81. if (applicationMessage == null) throw new ArgumentNullException(nameof(applicationMessage));
  82. return PublishAsync(new ManagedMqttApplicationMessageBuilder().WithApplicationMessage(applicationMessage).Build());
  83. }
  84. public async Task PublishAsync(ManagedMqttApplicationMessage applicationMessage)
  85. {
  86. if (applicationMessage == null) throw new ArgumentNullException(nameof(applicationMessage));
  87. ManagedMqttApplicationMessage removedMessage = null;
  88. lock (_messageQueue)
  89. {
  90. if (_messageQueue.Count >= _options.MaxPendingMessages)
  91. {
  92. if (_options.PendingMessagesOverflowStrategy == MqttPendingMessagesOverflowStrategy.DropNewMessage)
  93. {
  94. _logger.Verbose("Skipping publish of new application message because internal queue is full.");
  95. ApplicationMessageSkipped?.Invoke(this, new ApplicationMessageSkippedEventArgs(applicationMessage));
  96. return;
  97. }
  98. if (_options.PendingMessagesOverflowStrategy == MqttPendingMessagesOverflowStrategy.DropOldestQueuedMessage)
  99. {
  100. removedMessage = _messageQueue.RemoveFirst();
  101. _logger.Verbose("Removed oldest application message from internal queue because it is full.");
  102. ApplicationMessageSkipped?.Invoke(this, new ApplicationMessageSkippedEventArgs(removedMessage));
  103. }
  104. }
  105. _messageQueue.Enqueue(applicationMessage);
  106. }
  107. if (_storageManager != null)
  108. {
  109. if (removedMessage != null)
  110. {
  111. await _storageManager.RemoveAsync(removedMessage).ConfigureAwait(false);
  112. }
  113. await _storageManager.AddAsync(applicationMessage).ConfigureAwait(false);
  114. }
  115. }
  116. public Task SubscribeAsync(IEnumerable<TopicFilter> topicFilters)
  117. {
  118. if (topicFilters == null) throw new ArgumentNullException(nameof(topicFilters));
  119. lock (_subscriptions)
  120. {
  121. foreach (var topicFilter in topicFilters)
  122. {
  123. _subscriptions[topicFilter.Topic] = topicFilter.QualityOfServiceLevel;
  124. _subscriptionsNotPushed = true;
  125. }
  126. }
  127. return Task.FromResult(0);
  128. }
  129. public Task UnsubscribeAsync(IEnumerable<string> topics)
  130. {
  131. if (topics == null) throw new ArgumentNullException(nameof(topics));
  132. lock (_subscriptions)
  133. {
  134. foreach (var topic in topics)
  135. {
  136. if (_subscriptions.Remove(topic))
  137. {
  138. _unsubscriptions.Add(topic);
  139. _subscriptionsNotPushed = true;
  140. }
  141. }
  142. }
  143. return Task.FromResult(0);
  144. }
  145. public void Dispose()
  146. {
  147. _connectionCancellationToken?.Dispose();
  148. _publishingCancellationToken?.Dispose();
  149. }
  150. private async Task MaintainConnectionAsync(CancellationToken cancellationToken)
  151. {
  152. try
  153. {
  154. while (!cancellationToken.IsCancellationRequested)
  155. {
  156. await TryMaintainConnectionAsync(cancellationToken).ConfigureAwait(false);
  157. }
  158. }
  159. catch (OperationCanceledException)
  160. {
  161. }
  162. catch (Exception exception)
  163. {
  164. _logger.Error(exception, "Unhandled exception while maintaining connection.");
  165. }
  166. finally
  167. {
  168. await _mqttClient.DisconnectAsync().ConfigureAwait(false);
  169. _logger.Info("Stopped");
  170. }
  171. }
  172. private async Task TryMaintainConnectionAsync(CancellationToken cancellationToken)
  173. {
  174. try
  175. {
  176. var connectionState = await ReconnectIfRequiredAsync().ConfigureAwait(false);
  177. if (connectionState == ReconnectionResult.NotConnected)
  178. {
  179. StopPublishing();
  180. await Task.Delay(_options.AutoReconnectDelay, cancellationToken).ConfigureAwait(false);
  181. return;
  182. }
  183. if (connectionState == ReconnectionResult.Reconnected || _subscriptionsNotPushed)
  184. {
  185. await SynchronizeSubscriptionsAsync().ConfigureAwait(false);
  186. StartPublishing();
  187. return;
  188. }
  189. if (connectionState == ReconnectionResult.StillConnected)
  190. {
  191. await Task.Delay(_options.ConnectionCheckInterval, cancellationToken).ConfigureAwait(false);
  192. }
  193. }
  194. catch (OperationCanceledException)
  195. {
  196. }
  197. catch (MqttCommunicationException exception)
  198. {
  199. _logger.Warning(exception, "Communication exception while maintaining connection.");
  200. }
  201. catch (Exception exception)
  202. {
  203. _logger.Error(exception, "Unhandled exception while maintaining connection.");
  204. }
  205. }
  206. private void PublishQueuedMessages(CancellationToken cancellationToken)
  207. {
  208. try
  209. {
  210. while (!cancellationToken.IsCancellationRequested && _mqttClient.IsConnected)
  211. {
  212. var message = _messageQueue.Dequeue();
  213. if (message == null)
  214. {
  215. continue;
  216. }
  217. cancellationToken.ThrowIfCancellationRequested();
  218. TryPublishQueuedMessage(message);
  219. }
  220. }
  221. catch (OperationCanceledException)
  222. {
  223. }
  224. catch (Exception exception)
  225. {
  226. _logger.Error(exception, "Unhandled exception while publishing queued application messages.");
  227. }
  228. finally
  229. {
  230. _logger.Verbose("Stopped publishing messages.");
  231. }
  232. }
  233. private void TryPublishQueuedMessage(ManagedMqttApplicationMessage message)
  234. {
  235. Exception transmitException = null;
  236. try
  237. {
  238. _mqttClient.PublishAsync(message.ApplicationMessage).GetAwaiter().GetResult();
  239. _storageManager?.RemoveAsync(message).GetAwaiter().GetResult();
  240. }
  241. catch (MqttCommunicationException exception)
  242. {
  243. transmitException = exception;
  244. _logger.Warning(exception, $"Publishing application ({message.Id}) message failed.");
  245. if (message.ApplicationMessage.QualityOfServiceLevel > MqttQualityOfServiceLevel.AtMostOnce)
  246. {
  247. _messageQueue.Enqueue(message);
  248. }
  249. }
  250. catch (Exception exception)
  251. {
  252. transmitException = exception;
  253. _logger.Error(exception, $"Unhandled exception while publishing application message ({message.Id}).");
  254. }
  255. finally
  256. {
  257. ApplicationMessageProcessed?.Invoke(this, new ApplicationMessageProcessedEventArgs(message, transmitException));
  258. }
  259. }
  260. private async Task SynchronizeSubscriptionsAsync()
  261. {
  262. _logger.Info(nameof(ManagedMqttClient), "Synchronizing subscriptions");
  263. List<TopicFilter> subscriptions;
  264. HashSet<string> unsubscriptions;
  265. lock (_subscriptions)
  266. {
  267. subscriptions = _subscriptions.Select(i => new TopicFilter(i.Key, i.Value)).ToList();
  268. unsubscriptions = new HashSet<string>(_unsubscriptions);
  269. _unsubscriptions.Clear();
  270. _subscriptionsNotPushed = false;
  271. }
  272. if (!subscriptions.Any() && !unsubscriptions.Any())
  273. {
  274. return;
  275. }
  276. try
  277. {
  278. if (unsubscriptions.Any())
  279. {
  280. await _mqttClient.UnsubscribeAsync(unsubscriptions).ConfigureAwait(false);
  281. }
  282. if (subscriptions.Any())
  283. {
  284. await _mqttClient.SubscribeAsync(subscriptions).ConfigureAwait(false);
  285. }
  286. }
  287. catch (Exception exception)
  288. {
  289. _logger.Warning(exception, "Synchronizing subscriptions failed.");
  290. _subscriptionsNotPushed = true;
  291. SynchronizingSubscriptionsFailed?.Invoke(this, new MqttManagedProcessFailedEventArgs(exception));
  292. }
  293. }
  294. private async Task<ReconnectionResult> ReconnectIfRequiredAsync()
  295. {
  296. if (_mqttClient.IsConnected)
  297. {
  298. return ReconnectionResult.StillConnected;
  299. }
  300. try
  301. {
  302. await _mqttClient.ConnectAsync(_options.ClientOptions).ConfigureAwait(false);
  303. return ReconnectionResult.Reconnected;
  304. }
  305. catch (Exception exception)
  306. {
  307. ConnectingFailed?.Invoke(this, new MqttManagedProcessFailedEventArgs(exception));
  308. return ReconnectionResult.NotConnected;
  309. }
  310. }
  311. private void OnApplicationMessageReceived(object sender, MqttApplicationMessageReceivedEventArgs eventArgs)
  312. {
  313. ApplicationMessageReceived?.Invoke(this, eventArgs);
  314. }
  315. private void OnDisconnected(object sender, MqttClientDisconnectedEventArgs eventArgs)
  316. {
  317. Disconnected?.Invoke(this, eventArgs);
  318. }
  319. private void OnConnected(object sender, MqttClientConnectedEventArgs eventArgs)
  320. {
  321. Connected?.Invoke(this, eventArgs);
  322. }
  323. private void StartPublishing()
  324. {
  325. if (_publishingCancellationToken != null)
  326. {
  327. StopPublishing();
  328. }
  329. var cts = new CancellationTokenSource();
  330. _publishingCancellationToken = cts;
  331. Task.Factory.StartNew(() => PublishQueuedMessages(cts.Token), cts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
  332. }
  333. private void StopPublishing()
  334. {
  335. _publishingCancellationToken?.Cancel(false);
  336. _publishingCancellationToken?.Dispose();
  337. _publishingCancellationToken = null;
  338. }
  339. private void StopMaintainingConnection()
  340. {
  341. _connectionCancellationToken?.Cancel(false);
  342. _connectionCancellationToken?.Dispose();
  343. _connectionCancellationToken = null;
  344. }
  345. }
  346. }