You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

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