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.
 
 
 
 

416 line
15 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.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. }