您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 

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