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.
 
 
 
 

237 linhas
8.0 KiB

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