選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

MqttClientQueued.cs 7.0 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  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.Core.Adapter;
  8. using MQTTnet.Core.Diagnostics;
  9. using MQTTnet.Core.Exceptions;
  10. using MQTTnet.Core.Packets;
  11. using MQTTnet.Core.Protocol;
  12. using MQTTnet.Core.Internal;
  13. namespace MQTTnet.Core.Client
  14. {
  15. public class MqttClientQueued : MqttClient, IMqttClientQueued
  16. {
  17. private MqttClientQueuedOptions _options;
  18. private int _latestPacketIdentifier;
  19. private readonly ConcurrentQueue<MqttApplicationMessage> _inflightQueue;
  20. private bool _usePersistance = false;
  21. private MqttClientQueuedPersistentMessagesManager _persistentMessagesManager;
  22. public MqttClientQueued(IMqttCommunicationAdapterFactory communicationChannelFactory) : base(communicationChannelFactory)
  23. {
  24. _inflightQueue = new ConcurrentQueue<MqttApplicationMessage>();
  25. }
  26. public async Task ConnectAsync(MqttClientQueuedOptions options)
  27. {
  28. try
  29. {
  30. _options = options;
  31. this._usePersistance = _options.UsePersistence;
  32. await base.ConnectAsync(options);
  33. SetupOutgoingPacketProcessingAsync();
  34. //load persistentMessages
  35. if (_usePersistance)
  36. {
  37. if (_persistentMessagesManager == null)
  38. _persistentMessagesManager = new MqttClientQueuedPersistentMessagesManager(_options);
  39. await _persistentMessagesManager.LoadMessagesAsync();
  40. await InternalPublishAsync(_persistentMessagesManager.GetMessages(), false);
  41. }
  42. }
  43. catch (Exception)
  44. {
  45. await DisconnectAsync().ConfigureAwait(false);
  46. throw;
  47. }
  48. }
  49. public new async Task PublishAsync(IEnumerable<MqttApplicationMessage> applicationMessages)
  50. {
  51. await InternalPublishAsync(applicationMessages, true);
  52. }
  53. private async Task InternalPublishAsync(IEnumerable<MqttApplicationMessage> applicationMessages, bool appendIfUsePersistance)
  54. {
  55. ThrowIfNotConnected();
  56. foreach (var applicationMessage in applicationMessages)
  57. {
  58. if (_usePersistance && appendIfUsePersistance)
  59. await _persistentMessagesManager.SaveMessageAsync(applicationMessage);
  60. _inflightQueue.Enqueue(applicationMessage);
  61. }
  62. }
  63. public new async Task<IList<MqttSubscribeResult>> SubscribeAsync(IEnumerable<TopicFilter> topicFilters)
  64. {
  65. return await base.SubscribeAsync(topicFilters);
  66. }
  67. private void ThrowIfNotConnected()
  68. {
  69. if (!IsConnected) throw new MqttCommunicationException("The client is not connected.");
  70. }
  71. private ushort GetNewPacketIdentifier()
  72. {
  73. return (ushort)Interlocked.Increment(ref _latestPacketIdentifier);
  74. }
  75. private void SetupOutgoingPacketProcessingAsync()
  76. {
  77. #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
  78. Task.Factory.StartNew(
  79. () => SendPackets(base._cancellationTokenSource.Token),
  80. base._cancellationTokenSource.Token,
  81. TaskCreationOptions.LongRunning,
  82. TaskScheduler.Default).ConfigureAwait(false);
  83. #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
  84. }
  85. private async Task SendPackets(CancellationToken cancellationToken)
  86. {
  87. MqttNetTrace.Information(nameof(MqttClient), "Start sending packets.");
  88. MqttApplicationMessage messageToSend = null;
  89. try
  90. {
  91. while (!cancellationToken.IsCancellationRequested)
  92. {
  93. while (_inflightQueue.TryDequeue(out messageToSend))
  94. {
  95. MqttQualityOfServiceLevel qosGroup = messageToSend.QualityOfServiceLevel;
  96. MqttPublishPacket publishPacket = messageToSend.ToPublishPacket();
  97. switch (qosGroup)
  98. {
  99. case MqttQualityOfServiceLevel.AtMostOnce:
  100. {
  101. // No packet identifier is used for QoS 0 [3.3.2.2 Packet Identifier]
  102. await base._adapter.SendPacketsAsync(_options.DefaultCommunicationTimeout, base._cancellationTokenSource.Token, publishPacket);
  103. break;
  104. }
  105. case MqttQualityOfServiceLevel.AtLeastOnce:
  106. {
  107. publishPacket.PacketIdentifier = GetNewPacketIdentifier();
  108. await base.SendAndReceiveAsync<MqttPubAckPacket>(publishPacket);
  109. break;
  110. }
  111. case MqttQualityOfServiceLevel.ExactlyOnce:
  112. {
  113. publishPacket.PacketIdentifier = GetNewPacketIdentifier();
  114. var pubRecPacket = await base.SendAndReceiveAsync<MqttPubRecPacket>(publishPacket).ConfigureAwait(false);
  115. await base.SendAndReceiveAsync<MqttPubCompPacket>(pubRecPacket.CreateResponse<MqttPubRelPacket>()).ConfigureAwait(false);
  116. break;
  117. }
  118. default:
  119. {
  120. throw new InvalidOperationException();
  121. }
  122. }
  123. //delete from persistence
  124. if (_usePersistance)
  125. await _persistentMessagesManager.Remove(messageToSend);
  126. }
  127. };
  128. }
  129. catch (OperationCanceledException)
  130. {
  131. }
  132. catch (MqttCommunicationException exception)
  133. {
  134. MqttNetTrace.Warning(nameof(MqttClient), exception, "MQTT communication exception while sending packets.");
  135. //message not send, equeued again
  136. if (messageToSend != null)
  137. _inflightQueue.Enqueue(messageToSend);
  138. }
  139. catch (Exception exception)
  140. {
  141. MqttNetTrace.Error(nameof(MqttClient), exception, "Unhandled exception while sending packets.");
  142. await DisconnectAsync().ConfigureAwait(false);
  143. }
  144. finally
  145. {
  146. MqttNetTrace.Information(nameof(MqttClient), "Stopped sending packets.");
  147. }
  148. }
  149. }
  150. }