您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

ManagedMqttClient.cs 14 KiB

6 年前
6 年前
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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. }