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.
 
 
 
 

396 lines
14 KiB

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