Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

MqttChannelAdapter.cs 7.9 KiB

7 anos atrás
7 anos atrás
7 anos atrás
7 anos atrás
7 anos atrás
7 anos atrás
7 anos atrás
7 anos atrás
7 anos atrás
7 anos atrás
7 anos atrás
7 anos atrás
7 anos atrás
7 anos atrás
7 anos atrás
7 anos atrás
7 anos atrás
7 anos atrás
7 anos atrás
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Net.Sockets;
  5. using System.Runtime.InteropServices;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using MQTTnet.Channel;
  9. using MQTTnet.Diagnostics;
  10. using MQTTnet.Exceptions;
  11. using MQTTnet.Internal;
  12. using MQTTnet.Packets;
  13. using MQTTnet.Serializer;
  14. namespace MQTTnet.Adapter
  15. {
  16. public class MqttChannelAdapter : IMqttChannelAdapter
  17. {
  18. private const uint ErrorOperationAborted = 0x800703E3;
  19. private const int ReadBufferSize = 4096; // TODO: Move buffer size to config
  20. private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);
  21. private readonly IMqttNetLogger _logger;
  22. private readonly IMqttChannel _channel;
  23. public MqttChannelAdapter(IMqttChannel channel, IMqttPacketSerializer serializer, IMqttNetLogger logger)
  24. {
  25. _logger = logger ?? throw new ArgumentNullException(nameof(logger));
  26. _channel = channel ?? throw new ArgumentNullException(nameof(channel));
  27. PacketSerializer = serializer ?? throw new ArgumentNullException(nameof(serializer));
  28. }
  29. public IMqttPacketSerializer PacketSerializer { get; }
  30. public Task ConnectAsync(TimeSpan timeout)
  31. {
  32. _logger.Trace<MqttChannelAdapter>("Connecting [Timeout={0}]", timeout);
  33. return ExecuteAndWrapExceptionAsync(() => _channel.ConnectAsync().TimeoutAfter(timeout));
  34. }
  35. public Task DisconnectAsync(TimeSpan timeout)
  36. {
  37. _logger.Trace<MqttChannelAdapter>("Disconnecting [Timeout={0}]", timeout);
  38. return ExecuteAndWrapExceptionAsync(() => _channel.DisconnectAsync().TimeoutAfter(timeout));
  39. }
  40. public Task SendPacketsAsync(TimeSpan timeout, CancellationToken cancellationToken, IEnumerable<MqttBasePacket> packets)
  41. {
  42. return ExecuteAndWrapExceptionAsync(async () =>
  43. {
  44. await _semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  45. try
  46. {
  47. foreach (var packet in packets)
  48. {
  49. if (packet == null)
  50. {
  51. continue;
  52. }
  53. _logger.Trace<MqttChannelAdapter>("TX >>> {0} [Timeout={1}]", packet, timeout);
  54. var chunks = PacketSerializer.Serialize(packet);
  55. foreach (var chunk in chunks)
  56. {
  57. await _channel.SendStream.WriteAsync(chunk.Array, chunk.Offset, chunk.Count, cancellationToken).ConfigureAwait(false);
  58. }
  59. }
  60. if (timeout > TimeSpan.Zero)
  61. {
  62. await _channel.SendStream.FlushAsync(cancellationToken).TimeoutAfter(timeout).ConfigureAwait(false);
  63. }
  64. else
  65. {
  66. await _channel.SendStream.FlushAsync(cancellationToken).ConfigureAwait(false);
  67. }
  68. }
  69. finally
  70. {
  71. _semaphore.Release();
  72. }
  73. });
  74. }
  75. public async Task<MqttBasePacket> ReceivePacketAsync(TimeSpan timeout, CancellationToken cancellationToken)
  76. {
  77. MqttBasePacket packet = null;
  78. await ExecuteAndWrapExceptionAsync(async () =>
  79. {
  80. ReceivedMqttPacket receivedMqttPacket = null;
  81. try
  82. {
  83. if (timeout > TimeSpan.Zero)
  84. {
  85. receivedMqttPacket = await ReceiveAsync(_channel.ReceiveStream, cancellationToken).TimeoutAfter(timeout).ConfigureAwait(false);
  86. }
  87. else
  88. {
  89. receivedMqttPacket = await ReceiveAsync(_channel.ReceiveStream, cancellationToken).ConfigureAwait(false);
  90. }
  91. if (receivedMqttPacket == null || cancellationToken.IsCancellationRequested)
  92. {
  93. throw new TaskCanceledException();
  94. }
  95. packet = PacketSerializer.Deserialize(receivedMqttPacket.Header, receivedMqttPacket.Body);
  96. if (packet == null)
  97. {
  98. throw new MqttProtocolViolationException("Received malformed packet.");
  99. }
  100. _logger.Trace<MqttChannelAdapter>("RX <<< {0}", packet);
  101. }
  102. finally
  103. {
  104. receivedMqttPacket?.Dispose();
  105. }
  106. }).ConfigureAwait(false);
  107. return packet;
  108. }
  109. private static async Task<ReceivedMqttPacket> ReceiveAsync(Stream stream, CancellationToken cancellationToken)
  110. {
  111. var header = await MqttPacketReader.ReadHeaderAsync(stream, cancellationToken).ConfigureAwait(false);
  112. if (header == null)
  113. {
  114. return null;
  115. }
  116. if (header.BodyLength == 0)
  117. {
  118. return new ReceivedMqttPacket(header, new MemoryStream(new byte[0], false));
  119. }
  120. var body = header.BodyLength <= ReadBufferSize ? new MemoryStream(header.BodyLength) : new MemoryStream();
  121. var buffer = new byte[ReadBufferSize];
  122. while (body.Length < header.BodyLength)
  123. {
  124. var bytesLeft = header.BodyLength - (int)body.Length;
  125. if (bytesLeft > buffer.Length)
  126. {
  127. bytesLeft = buffer.Length;
  128. }
  129. var readBytesCount = await stream.ReadAsync(buffer, 0, bytesLeft, cancellationToken).ConfigureAwait(false);
  130. // Check if the client closed the connection before sending the full body.
  131. if (readBytesCount == 0)
  132. {
  133. throw new MqttCommunicationException("Connection closed while reading remaining packet body.");
  134. }
  135. // Here is no need to await because internally only an array is used and no real I/O operation is made.
  136. // Using async here will only generate overhead.
  137. body.Write(buffer, 0, readBytesCount);
  138. }
  139. body.Seek(0L, SeekOrigin.Begin);
  140. return new ReceivedMqttPacket(header, body);
  141. }
  142. private static async Task ExecuteAndWrapExceptionAsync(Func<Task> action)
  143. {
  144. try
  145. {
  146. await action().ConfigureAwait(false);
  147. }
  148. catch (TaskCanceledException)
  149. {
  150. throw;
  151. }
  152. catch (OperationCanceledException)
  153. {
  154. throw;
  155. }
  156. catch (MqttCommunicationTimedOutException)
  157. {
  158. throw;
  159. }
  160. catch (MqttCommunicationException)
  161. {
  162. throw;
  163. }
  164. catch (COMException comException)
  165. {
  166. if ((uint) comException.HResult == ErrorOperationAborted)
  167. {
  168. throw new OperationCanceledException();
  169. }
  170. throw new MqttCommunicationException(comException);
  171. }
  172. catch (IOException exception)
  173. {
  174. if (exception.InnerException is SocketException socketException)
  175. {
  176. if (socketException.SocketErrorCode == SocketError.ConnectionAborted)
  177. {
  178. throw new OperationCanceledException();
  179. }
  180. }
  181. throw new MqttCommunicationException(exception);
  182. }
  183. catch (Exception exception)
  184. {
  185. throw new MqttCommunicationException(exception);
  186. }
  187. }
  188. }
  189. }