Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 
 

347 Zeilen
14 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. using MQTTnet.Adapter;
  6. using MQTTnet.Client;
  7. using MQTTnet.Diagnostics;
  8. using MQTTnet.Exceptions;
  9. using MQTTnet.Internal;
  10. using MQTTnet.Packets;
  11. using MQTTnet.Protocol;
  12. using MQTTnet.Serializer;
  13. namespace MQTTnet.Server
  14. {
  15. public sealed class MqttClientSession : IDisposable
  16. {
  17. private readonly MqttPacketIdentifierProvider _packetIdentifierProvider = new MqttPacketIdentifierProvider();
  18. private readonly IMqttServerOptions _options;
  19. private readonly IMqttNetLogger _logger;
  20. private readonly MqttRetainedMessagesManager _retainedMessagesManager;
  21. private IMqttChannelAdapter _adapter;
  22. private CancellationTokenSource _cancellationTokenSource;
  23. private MqttApplicationMessage _willMessage;
  24. private bool _wasCleanDisconnect;
  25. public MqttClientSession(
  26. string clientId,
  27. IMqttServerOptions options,
  28. MqttRetainedMessagesManager retainedMessagesManager,
  29. IMqttNetLogger logger)
  30. {
  31. _options = options ?? throw new ArgumentNullException(nameof(options));
  32. _retainedMessagesManager = retainedMessagesManager ?? throw new ArgumentNullException(nameof(retainedMessagesManager));
  33. _logger = logger ?? throw new ArgumentNullException(nameof(logger));
  34. ClientId = clientId;
  35. KeepAliveMonitor = new MqttClientKeepAliveMonitor(clientId, StopDueToKeepAliveTimeoutAsync, _logger);
  36. SubscriptionsManager = new MqttClientSubscriptionsManager(_options, clientId);
  37. PendingMessagesQueue = new MqttClientPendingMessagesQueue(_options, this, _logger);
  38. }
  39. public Func<MqttClientSession, MqttApplicationMessage, Task> ApplicationMessageReceivedCallback { get; set; }
  40. public MqttClientSubscriptionsManager SubscriptionsManager { get; }
  41. public MqttClientPendingMessagesQueue PendingMessagesQueue { get; }
  42. public MqttClientKeepAliveMonitor KeepAliveMonitor { get; }
  43. public string ClientId { get; }
  44. public MqttProtocolVersion? ProtocolVersion => _adapter?.PacketSerializer.ProtocolVersion;
  45. public bool IsConnected => _adapter != null;
  46. public async Task<bool> RunAsync(MqttConnectPacket connectPacket, IMqttChannelAdapter adapter)
  47. {
  48. if (connectPacket == null) throw new ArgumentNullException(nameof(connectPacket));
  49. if (adapter == null) throw new ArgumentNullException(nameof(adapter));
  50. try
  51. {
  52. var cancellationTokenSource = new CancellationTokenSource();
  53. _wasCleanDisconnect = false;
  54. _willMessage = connectPacket.WillMessage;
  55. _adapter = adapter;
  56. _cancellationTokenSource = cancellationTokenSource;
  57. PendingMessagesQueue.Start(adapter, cancellationTokenSource.Token);
  58. KeepAliveMonitor.Start(connectPacket.KeepAlivePeriod, cancellationTokenSource.Token);
  59. await ReceivePacketsAsync(adapter, cancellationTokenSource.Token).ConfigureAwait(false);
  60. }
  61. catch (OperationCanceledException)
  62. {
  63. }
  64. catch (MqttCommunicationException exception)
  65. {
  66. _logger.Warning<MqttClientSession>(exception, "Client '{0}': Communication exception while processing client packets.", ClientId);
  67. }
  68. catch (Exception exception)
  69. {
  70. _logger.Error<MqttClientSession>(exception, "Client '{0}': Unhandled exception while processing client packets.", ClientId);
  71. }
  72. return _wasCleanDisconnect;
  73. }
  74. public async Task StopAsync(bool wasCleanDisconnect = false)
  75. {
  76. try
  77. {
  78. if (_cancellationTokenSource == null)
  79. {
  80. return;
  81. }
  82. _wasCleanDisconnect = wasCleanDisconnect;
  83. _cancellationTokenSource?.Cancel(false);
  84. PendingMessagesQueue.WaitForCompletion();
  85. KeepAliveMonitor.WaitForCompletion();
  86. _cancellationTokenSource?.Dispose();
  87. _cancellationTokenSource = null;
  88. _adapter = null;
  89. _logger.Info<MqttClientSession>("Client '{0}': Session stopped.", ClientId);
  90. }
  91. finally
  92. {
  93. var willMessage = _willMessage;
  94. _willMessage = null; // clear willmessage so it is send just once
  95. if (willMessage != null && !wasCleanDisconnect)
  96. {
  97. await ApplicationMessageReceivedCallback(this, willMessage).ConfigureAwait(false);
  98. }
  99. }
  100. }
  101. public async Task EnqueueApplicationMessageAsync(MqttApplicationMessage applicationMessage)
  102. {
  103. if (applicationMessage == null) throw new ArgumentNullException(nameof(applicationMessage));
  104. var result = await SubscriptionsManager.CheckSubscriptionsAsync(applicationMessage);
  105. if (!result.IsSubscribed)
  106. {
  107. return;
  108. }
  109. var publishPacket = applicationMessage.ToPublishPacket();
  110. publishPacket.QualityOfServiceLevel = result.QualityOfServiceLevel;
  111. if (publishPacket.QualityOfServiceLevel > 0)
  112. {
  113. publishPacket.PacketIdentifier = _packetIdentifierProvider.GetNewPacketIdentifier();
  114. }
  115. PendingMessagesQueue.Enqueue(publishPacket);
  116. }
  117. public async Task SubscribeAsync(IList<TopicFilter> topicFilters)
  118. {
  119. if (topicFilters == null) throw new ArgumentNullException(nameof(topicFilters));
  120. await SubscriptionsManager.SubscribeAsync(new MqttSubscribePacket
  121. {
  122. TopicFilters = topicFilters
  123. }).ConfigureAwait(false);
  124. await EnqueueSubscribedRetainedMessagesAsync(topicFilters).ConfigureAwait(false);
  125. }
  126. public Task UnsubscribeAsync(IList<string> topicFilters)
  127. {
  128. if (topicFilters == null) throw new ArgumentNullException(nameof(topicFilters));
  129. return SubscriptionsManager.UnsubscribeAsync(new MqttUnsubscribePacket
  130. {
  131. TopicFilters = topicFilters
  132. });
  133. }
  134. public void Dispose()
  135. {
  136. ApplicationMessageReceivedCallback = null;
  137. SubscriptionsManager?.Dispose();
  138. PendingMessagesQueue?.Dispose();
  139. _cancellationTokenSource?.Dispose();
  140. }
  141. private Task StopDueToKeepAliveTimeoutAsync()
  142. {
  143. _logger.Info<MqttClientSession>("Client '{0}': Timeout while waiting for KeepAlive packet.", ClientId);
  144. return StopAsync();
  145. }
  146. private async Task ReceivePacketsAsync(IMqttChannelAdapter adapter, CancellationToken cancellationToken)
  147. {
  148. try
  149. {
  150. while (!cancellationToken.IsCancellationRequested)
  151. {
  152. var packet = await adapter.ReceivePacketAsync(TimeSpan.Zero, cancellationToken).ConfigureAwait(false);
  153. KeepAliveMonitor.PacketReceived(packet);
  154. await ProcessReceivedPacketAsync(adapter, packet, cancellationToken).ConfigureAwait(false);
  155. }
  156. }
  157. catch (OperationCanceledException)
  158. {
  159. }
  160. catch (MqttCommunicationException exception)
  161. {
  162. _logger.Warning<MqttClientSession>(exception, "Client '{0}': Communication exception while processing client packets.", ClientId);
  163. await StopAsync().ConfigureAwait(false);
  164. }
  165. catch (Exception exception)
  166. {
  167. _logger.Error<MqttClientSession>(exception, "Client '{0}': Unhandled exception while processing client packets.", ClientId);
  168. await StopAsync().ConfigureAwait(false);
  169. }
  170. }
  171. private Task ProcessReceivedPacketAsync(IMqttChannelAdapter adapter, MqttBasePacket packet, CancellationToken cancellationToken)
  172. {
  173. if (packet is MqttPublishPacket publishPacket)
  174. {
  175. return HandleIncomingPublishPacketAsync(adapter, publishPacket, cancellationToken);
  176. }
  177. if (packet is MqttPingReqPacket)
  178. {
  179. return adapter.SendPacketsAsync(_options.DefaultCommunicationTimeout, cancellationToken, new[] { new MqttPingRespPacket() });
  180. }
  181. if (packet is MqttPubRelPacket pubRelPacket)
  182. {
  183. return HandleIncomingPubRelPacketAsync(adapter, pubRelPacket, cancellationToken);
  184. }
  185. if (packet is MqttPubRecPacket pubRecPacket)
  186. {
  187. var responsePacket = new MqttPubRelPacket
  188. {
  189. PacketIdentifier = pubRecPacket.PacketIdentifier
  190. };
  191. return adapter.SendPacketsAsync(_options.DefaultCommunicationTimeout, cancellationToken, new[] { responsePacket });
  192. }
  193. if (packet is MqttPubAckPacket || packet is MqttPubCompPacket)
  194. {
  195. // Discard message.
  196. return Task.FromResult(0);
  197. }
  198. if (packet is MqttSubscribePacket subscribePacket)
  199. {
  200. return HandleIncomingSubscribePacketAsync(adapter, subscribePacket, cancellationToken);
  201. }
  202. if (packet is MqttUnsubscribePacket unsubscribePacket)
  203. {
  204. return HandleIncomingUnsubscribePacketAsync(adapter, unsubscribePacket, cancellationToken);
  205. }
  206. if (packet is MqttDisconnectPacket)
  207. {
  208. return StopAsync(true);
  209. }
  210. if (packet is MqttConnectPacket)
  211. {
  212. return StopAsync();
  213. }
  214. _logger.Warning<MqttClientSession>("Client '{0}': Received not supported packet ({1}). Closing connection.", ClientId, packet);
  215. return StopAsync();
  216. }
  217. private async Task HandleIncomingSubscribePacketAsync(IMqttChannelAdapter adapter, MqttSubscribePacket subscribePacket, CancellationToken cancellationToken)
  218. {
  219. var subscribeResult = await SubscriptionsManager.SubscribeAsync(subscribePacket).ConfigureAwait(false);
  220. await adapter.SendPacketsAsync(_options.DefaultCommunicationTimeout, cancellationToken, new[] { subscribeResult.ResponsePacket }).ConfigureAwait(false);
  221. if (subscribeResult.CloseConnection)
  222. {
  223. await StopAsync().ConfigureAwait(false);
  224. }
  225. await EnqueueSubscribedRetainedMessagesAsync(subscribePacket.TopicFilters).ConfigureAwait(false);
  226. }
  227. private async Task HandleIncomingUnsubscribePacketAsync(IMqttChannelAdapter adapter, MqttUnsubscribePacket unsubscribePacket, CancellationToken cancellationToken)
  228. {
  229. var unsubscribeResult = await SubscriptionsManager.UnsubscribeAsync(unsubscribePacket).ConfigureAwait(false);
  230. await adapter.SendPacketsAsync(_options.DefaultCommunicationTimeout, cancellationToken, new[] { unsubscribeResult });
  231. }
  232. private async Task EnqueueSubscribedRetainedMessagesAsync(ICollection<TopicFilter> topicFilters)
  233. {
  234. var retainedMessages = await _retainedMessagesManager.GetSubscribedMessagesAsync(topicFilters);
  235. foreach (var applicationMessage in retainedMessages)
  236. {
  237. await EnqueueApplicationMessageAsync(applicationMessage).ConfigureAwait(false);
  238. }
  239. }
  240. private Task HandleIncomingPublishPacketAsync(IMqttChannelAdapter adapter, MqttPublishPacket publishPacket, CancellationToken cancellationToken)
  241. {
  242. var applicationMessage = publishPacket.ToApplicationMessage();
  243. switch (applicationMessage.QualityOfServiceLevel)
  244. {
  245. case MqttQualityOfServiceLevel.AtMostOnce:
  246. {
  247. return ApplicationMessageReceivedCallback?.Invoke(this, applicationMessage);
  248. }
  249. case MqttQualityOfServiceLevel.AtLeastOnce:
  250. {
  251. return HandleIncomingPublishPacketWithQoS1(adapter, applicationMessage, publishPacket, cancellationToken);
  252. }
  253. case MqttQualityOfServiceLevel.ExactlyOnce:
  254. {
  255. return HandleIncomingPublishPacketWithQoS2(adapter, applicationMessage, publishPacket, cancellationToken);
  256. }
  257. default:
  258. {
  259. throw new MqttCommunicationException("Received a not supported QoS level.");
  260. }
  261. }
  262. }
  263. private async Task HandleIncomingPublishPacketWithQoS1(IMqttChannelAdapter adapter, MqttApplicationMessage applicationMessage, MqttPublishPacket publishPacket, CancellationToken cancellationToken)
  264. {
  265. await ApplicationMessageReceivedCallback(this, applicationMessage).ConfigureAwait(false);
  266. var response = new MqttPubAckPacket { PacketIdentifier = publishPacket.PacketIdentifier };
  267. await adapter.SendPacketsAsync(_options.DefaultCommunicationTimeout, cancellationToken, new[] { response }).ConfigureAwait(false);
  268. }
  269. private async Task HandleIncomingPublishPacketWithQoS2(IMqttChannelAdapter adapter, MqttApplicationMessage applicationMessage, MqttPublishPacket publishPacket, CancellationToken cancellationToken)
  270. {
  271. // QoS 2 is implement as method "B" [4.3.3 QoS 2: Exactly once delivery]
  272. await ApplicationMessageReceivedCallback(this, applicationMessage).ConfigureAwait(false);
  273. var response = new MqttPubRecPacket { PacketIdentifier = publishPacket.PacketIdentifier };
  274. await adapter.SendPacketsAsync(_options.DefaultCommunicationTimeout, cancellationToken, new[] { response }).ConfigureAwait(false);
  275. }
  276. private Task HandleIncomingPubRelPacketAsync(IMqttChannelAdapter adapter, MqttPubRelPacket pubRelPacket, CancellationToken cancellationToken)
  277. {
  278. var response = new MqttPubCompPacket { PacketIdentifier = pubRelPacket.PacketIdentifier };
  279. return adapter.SendPacketsAsync(_options.DefaultCommunicationTimeout, cancellationToken, new[] { response });
  280. }
  281. }
  282. }