Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 

88 rindas
2.8 KiB

  1. using System;
  2. using System.Threading.Tasks;
  3. using MQTTnet.Core.Channel;
  4. using MQTTnet.Core.Client;
  5. using MQTTnet.Core.Diagnostics;
  6. using MQTTnet.Core.Exceptions;
  7. using MQTTnet.Core.Packets;
  8. using MQTTnet.Core.Serializer;
  9. namespace MQTTnet.Core.Adapter
  10. {
  11. public class MqttChannelCommunicationAdapter : IMqttCommunicationAdapter
  12. {
  13. private readonly IMqttPacketSerializer _serializer;
  14. private readonly IMqttCommunicationChannel _channel;
  15. public MqttChannelCommunicationAdapter(IMqttCommunicationChannel channel, IMqttPacketSerializer serializer)
  16. {
  17. _channel = channel ?? throw new ArgumentNullException(nameof(channel));
  18. _serializer = serializer ?? throw new ArgumentNullException(nameof(serializer));
  19. }
  20. public async Task ConnectAsync(MqttClientOptions options, TimeSpan timeout)
  21. {
  22. var task = _channel.ConnectAsync(options);
  23. if (await Task.WhenAny(Task.Delay(timeout), task) != task)
  24. {
  25. throw new MqttCommunicationTimedOutException();
  26. }
  27. }
  28. public async Task DisconnectAsync()
  29. {
  30. await _channel.DisconnectAsync();
  31. }
  32. public async Task SendPacketAsync(MqttBasePacket packet, TimeSpan timeout)
  33. {
  34. MqttTrace.Information(nameof(MqttChannelCommunicationAdapter), $"TX >>> {packet} [Timeout={timeout}]");
  35. bool hasTimeout;
  36. try
  37. {
  38. var task = _serializer.SerializeAsync(packet, _channel);
  39. hasTimeout = await Task.WhenAny(Task.Delay(timeout), task) != task;
  40. }
  41. catch (Exception exception)
  42. {
  43. throw new MqttCommunicationException(exception);
  44. }
  45. if (hasTimeout)
  46. {
  47. throw new MqttCommunicationTimedOutException();
  48. }
  49. }
  50. public async Task<MqttBasePacket> ReceivePacketAsync(TimeSpan timeout)
  51. {
  52. MqttBasePacket packet;
  53. if (timeout > TimeSpan.Zero)
  54. {
  55. var workerTask = _serializer.DeserializeAsync(_channel);
  56. var timeoutTask = Task.Delay(timeout);
  57. var hasTimeout = Task.WhenAny(timeoutTask, workerTask) == timeoutTask;
  58. if (hasTimeout)
  59. {
  60. throw new MqttCommunicationTimedOutException();
  61. }
  62. packet = workerTask.Result;
  63. }
  64. else
  65. {
  66. packet = await _serializer.DeserializeAsync(_channel);
  67. }
  68. if (packet == null)
  69. {
  70. throw new MqttProtocolViolationException("Received malformed packet.");
  71. }
  72. MqttTrace.Information(nameof(MqttChannelCommunicationAdapter), $"RX <<< {packet}");
  73. return packet;
  74. }
  75. }
  76. }