Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

MqttClientSession.cs 16 KiB

před 7 roky
před 7 roky
před 7 roky
před 7 roky
před 7 roky
před 7 roky
před 7 roky
před 7 roky
před 7 roky
před 7 roky
před 7 roky
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. using MQTTnet.Adapter;
  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 Stopwatch _lastPacketReceivedTracker = Stopwatch.StartNew();
  18. private readonly Stopwatch _lastNonKeepAlivePacketReceivedTracker = Stopwatch.StartNew();
  19. private readonly IMqttServerOptions _options;
  20. private readonly IMqttNetLogger _logger;
  21. private readonly MqttRetainedMessagesManager _retainedMessagesManager;
  22. private IMqttChannelAdapter _adapter;
  23. private CancellationTokenSource _cancellationTokenSource;
  24. private MqttApplicationMessage _willMessage;
  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. SubscriptionsManager = new MqttClientSubscriptionsManager(_options, clientId);
  36. PendingMessagesQueue = new MqttClientPendingMessagesQueue(_options, this, _logger);
  37. }
  38. public Func<MqttClientSession, MqttApplicationMessage, Task> ApplicationMessageReceivedCallback { get; set; }
  39. public MqttClientSubscriptionsManager SubscriptionsManager { get; }
  40. public MqttClientPendingMessagesQueue PendingMessagesQueue { get; }
  41. public string ClientId { get; }
  42. public MqttProtocolVersion? ProtocolVersion => _adapter?.PacketSerializer.ProtocolVersion;
  43. public TimeSpan LastPacketReceived => _lastPacketReceivedTracker.Elapsed;
  44. public TimeSpan LastNonKeepAlivePacketReceived => _lastNonKeepAlivePacketReceivedTracker.Elapsed;
  45. public bool IsConnected => _adapter != null;
  46. public async Task 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. _willMessage = connectPacket.WillMessage;
  54. _adapter = adapter;
  55. _cancellationTokenSource = cancellationTokenSource;
  56. PendingMessagesQueue.Start(adapter, cancellationTokenSource.Token);
  57. _lastPacketReceivedTracker.Restart();
  58. _lastNonKeepAlivePacketReceivedTracker.Restart();
  59. if (connectPacket.KeepAlivePeriod > 0)
  60. {
  61. StartCheckingKeepAliveTimeout(TimeSpan.FromSeconds(connectPacket.KeepAlivePeriod), cancellationTokenSource.Token);
  62. }
  63. await ReceivePacketsAsync(adapter, cancellationTokenSource.Token).ConfigureAwait(false);
  64. }
  65. catch (OperationCanceledException)
  66. {
  67. }
  68. catch (MqttCommunicationException exception)
  69. {
  70. _logger.Warning<MqttClientSession>(exception, "Client '{0}': Communication exception while processing client packets.", ClientId);
  71. }
  72. catch (Exception exception)
  73. {
  74. _logger.Error<MqttClientSession>(exception, "Client '{0}': Unhandled exception while processing client packets.", ClientId);
  75. }
  76. }
  77. public async Task StopAsync()
  78. {
  79. try
  80. {
  81. if (_cancellationTokenSource == null)
  82. {
  83. return;
  84. }
  85. _cancellationTokenSource?.Cancel(false);
  86. _cancellationTokenSource?.Dispose();
  87. _cancellationTokenSource = null;
  88. if (_adapter != null)
  89. {
  90. await _adapter.DisconnectAsync(_options.DefaultCommunicationTimeout).ConfigureAwait(false);
  91. _adapter = null;
  92. }
  93. _logger.Info<MqttClientSession>("Client '{0}': Session stopped.", ClientId);
  94. }
  95. finally
  96. {
  97. var willMessage = _willMessage;
  98. if (willMessage != null)
  99. {
  100. _willMessage = null; //clear willmessage so it is send just once
  101. await ApplicationMessageReceivedCallback(this, willMessage).ConfigureAwait(false);
  102. }
  103. }
  104. }
  105. public async Task EnqueueApplicationMessageAsync(MqttApplicationMessage applicationMessage)
  106. {
  107. if (applicationMessage == null) throw new ArgumentNullException(nameof(applicationMessage));
  108. var result = await SubscriptionsManager.CheckSubscriptionsAsync(applicationMessage);
  109. if (!result.IsSubscribed)
  110. {
  111. return;
  112. }
  113. var publishPacket = applicationMessage.ToPublishPacket();
  114. publishPacket.QualityOfServiceLevel = result.QualityOfServiceLevel;
  115. PendingMessagesQueue.Enqueue(publishPacket);
  116. }
  117. public Task SubscribeAsync(IList<TopicFilter> topicFilters)
  118. {
  119. if (topicFilters == null) throw new ArgumentNullException(nameof(topicFilters));
  120. var response = SubscriptionsManager.SubscribeAsync(new MqttSubscribePacket
  121. {
  122. TopicFilters = topicFilters
  123. });
  124. return response;
  125. }
  126. public Task UnsubscribeAsync(IList<string> topicFilters)
  127. {
  128. if (topicFilters == null) throw new ArgumentNullException(nameof(topicFilters));
  129. var response = SubscriptionsManager.UnsubscribeAsync(new MqttUnsubscribePacket
  130. {
  131. TopicFilters = topicFilters
  132. });
  133. return response;
  134. }
  135. public void Dispose()
  136. {
  137. ApplicationMessageReceivedCallback = null;
  138. SubscriptionsManager?.Dispose();
  139. PendingMessagesQueue?.Dispose();
  140. _cancellationTokenSource?.Dispose();
  141. }
  142. private async Task ReceivePacketsAsync(IMqttChannelAdapter adapter, CancellationToken cancellationToken)
  143. {
  144. try
  145. {
  146. while (!cancellationToken.IsCancellationRequested)
  147. {
  148. var packet = await adapter.ReceivePacketAsync(TimeSpan.Zero, cancellationToken).ConfigureAwait(false);
  149. _lastPacketReceivedTracker.Restart();
  150. if (!(packet is MqttPingReqPacket))
  151. {
  152. _lastNonKeepAlivePacketReceivedTracker.Restart();
  153. }
  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 MqttPingRespPacket());
  180. }
  181. if (packet is MqttPubRelPacket pubRelPacket)
  182. {
  183. return HandleIncomingPubRelPacketAsync(adapter, pubRelPacket, cancellationToken);
  184. }
  185. if (packet is MqttPubRecPacket pubRecPacket)
  186. {
  187. return adapter.SendPacketsAsync(_options.DefaultCommunicationTimeout, cancellationToken, pubRecPacket.CreateResponse<MqttPubRelPacket>());
  188. }
  189. if (packet is MqttPubAckPacket || packet is MqttPubCompPacket)
  190. {
  191. // Discard message.
  192. return Task.FromResult(0);
  193. }
  194. if (packet is MqttSubscribePacket subscribePacket)
  195. {
  196. return HandleIncomingSubscribePacketAsync(adapter, subscribePacket, cancellationToken);
  197. }
  198. if (packet is MqttUnsubscribePacket unsubscribePacket)
  199. {
  200. return HandleIncomingUnsubscribePacketAsync(adapter, unsubscribePacket, cancellationToken);
  201. }
  202. if (packet is MqttDisconnectPacket || packet is MqttConnectPacket)
  203. {
  204. return StopAsync();
  205. }
  206. _logger.Warning<MqttClientSession>("Client '{0}': Received not supported packet ({1}). Closing connection.", ClientId, packet);
  207. return StopAsync();
  208. }
  209. private async Task HandleIncomingSubscribePacketAsync(IMqttChannelAdapter adapter, MqttSubscribePacket subscribePacket, CancellationToken cancellationToken)
  210. {
  211. var subscribeResult = await SubscriptionsManager.SubscribeAsync(subscribePacket).ConfigureAwait(false);
  212. await adapter.SendPacketsAsync(_options.DefaultCommunicationTimeout, cancellationToken, subscribeResult.ResponsePacket).ConfigureAwait(false);
  213. if (subscribeResult.CloseConnection)
  214. {
  215. await adapter.SendPacketsAsync(_options.DefaultCommunicationTimeout, cancellationToken, new MqttDisconnectPacket()).ConfigureAwait(false);
  216. await StopAsync().ConfigureAwait(false);
  217. }
  218. await EnqueueSubscribedRetainedMessagesAsync(subscribePacket).ConfigureAwait(false);
  219. }
  220. private async Task HandleIncomingUnsubscribePacketAsync(IMqttChannelAdapter adapter, MqttUnsubscribePacket unsubscribePacket, CancellationToken cancellationToken)
  221. {
  222. var unsubscribeResult = await SubscriptionsManager.UnsubscribeAsync(unsubscribePacket).ConfigureAwait(false);
  223. await adapter.SendPacketsAsync(_options.DefaultCommunicationTimeout, cancellationToken, unsubscribeResult);
  224. }
  225. private async Task EnqueueSubscribedRetainedMessagesAsync(MqttSubscribePacket subscribePacket)
  226. {
  227. var retainedMessages = await _retainedMessagesManager.GetSubscribedMessagesAsync(subscribePacket);
  228. foreach (var publishPacket in retainedMessages)
  229. {
  230. await EnqueueApplicationMessageAsync(publishPacket);
  231. }
  232. }
  233. private Task HandleIncomingPublishPacketAsync(IMqttChannelAdapter adapter, MqttPublishPacket publishPacket, CancellationToken cancellationToken)
  234. {
  235. var applicationMessage = publishPacket.ToApplicationMessage();
  236. switch (applicationMessage.QualityOfServiceLevel)
  237. {
  238. case MqttQualityOfServiceLevel.AtMostOnce:
  239. {
  240. return ApplicationMessageReceivedCallback?.Invoke(this, applicationMessage);
  241. }
  242. case MqttQualityOfServiceLevel.AtLeastOnce:
  243. {
  244. return HandleIncomingPublishPacketWithQoS1(adapter, applicationMessage, publishPacket, cancellationToken);
  245. }
  246. case MqttQualityOfServiceLevel.ExactlyOnce:
  247. {
  248. return HandleIncomingPublishPacketWithQoS2(adapter, applicationMessage, publishPacket, cancellationToken);
  249. }
  250. default:
  251. {
  252. throw new MqttCommunicationException("Received a not supported QoS level.");
  253. }
  254. }
  255. }
  256. private async Task HandleIncomingPublishPacketWithQoS1(IMqttChannelAdapter adapter, MqttApplicationMessage applicationMessage, MqttPublishPacket publishPacket, CancellationToken cancellationToken)
  257. {
  258. await ApplicationMessageReceivedCallback(this, applicationMessage).ConfigureAwait(false);
  259. var response = new MqttPubAckPacket { PacketIdentifier = publishPacket.PacketIdentifier };
  260. await adapter.SendPacketsAsync(_options.DefaultCommunicationTimeout, cancellationToken, response).ConfigureAwait(false);
  261. }
  262. private async Task HandleIncomingPublishPacketWithQoS2(IMqttChannelAdapter adapter, MqttApplicationMessage applicationMessage, MqttPublishPacket publishPacket, CancellationToken cancellationToken)
  263. {
  264. // QoS 2 is implement as method "B" [4.3.3 QoS 2: Exactly once delivery]
  265. await ApplicationMessageReceivedCallback(this, applicationMessage).ConfigureAwait(false);
  266. var response = new MqttPubRecPacket { PacketIdentifier = publishPacket.PacketIdentifier };
  267. await adapter.SendPacketsAsync(_options.DefaultCommunicationTimeout, cancellationToken, response).ConfigureAwait(false);
  268. }
  269. private Task HandleIncomingPubRelPacketAsync(IMqttChannelAdapter adapter, MqttPubRelPacket pubRelPacket, CancellationToken cancellationToken)
  270. {
  271. var response = new MqttPubCompPacket { PacketIdentifier = pubRelPacket.PacketIdentifier };
  272. return adapter.SendPacketsAsync(_options.DefaultCommunicationTimeout, cancellationToken, response);
  273. }
  274. private void StartCheckingKeepAliveTimeout(TimeSpan keepAlivePeriod, CancellationToken cancellationToken)
  275. {
  276. Task.Run(
  277. async () => await CheckKeepAliveTimeoutAsync(keepAlivePeriod, cancellationToken).ConfigureAwait(false)
  278. , cancellationToken);
  279. }
  280. private async Task CheckKeepAliveTimeoutAsync(TimeSpan keepAlivePeriod, CancellationToken cancellationToken)
  281. {
  282. try
  283. {
  284. while (!cancellationToken.IsCancellationRequested)
  285. {
  286. // Values described here: [MQTT-3.1.2-24].
  287. if (_lastPacketReceivedTracker.Elapsed.TotalSeconds > keepAlivePeriod.TotalSeconds * 1.5D)
  288. {
  289. _logger.Warning<MqttClientSession>("Client '{0}': Did not receive any packet or keep alive signal.", ClientId);
  290. await StopAsync();
  291. return;
  292. }
  293. await Task.Delay(keepAlivePeriod, cancellationToken);
  294. }
  295. }
  296. catch (OperationCanceledException)
  297. {
  298. }
  299. catch (Exception exception)
  300. {
  301. _logger.Error<MqttClientSession>(exception, "Client '{0}': Unhandled exception while checking keep alive timeouts.", ClientId);
  302. }
  303. finally
  304. {
  305. _logger.Trace<MqttClientSession>("Client {0}: Stopped checking keep alive timeout.", ClientId);
  306. }
  307. }
  308. }
  309. }