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.
 
 
 
 

85 lines
2.4 KiB

  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. using MQTTnet.Adapter;
  6. using MQTTnet.Formatter;
  7. using MQTTnet.Packets;
  8. namespace MQTTnet.Tests.Mockups
  9. {
  10. public class TestMqttCommunicationAdapter : IMqttChannelAdapter
  11. {
  12. private readonly BlockingCollection<MqttBasePacket> _incomingPackets = new BlockingCollection<MqttBasePacket>();
  13. public TestMqttCommunicationAdapter Partner { get; set; }
  14. public string Endpoint { get; } = string.Empty;
  15. public bool IsSecureConnection { get; } = false;
  16. public MqttPacketFormatterAdapter PacketFormatterAdapter { get; } = new MqttPacketFormatterAdapter(MqttProtocolVersion.V311);
  17. public long BytesSent { get; }
  18. public long BytesReceived { get; }
  19. public Action ReadingPacketStartedCallback { get; set; }
  20. public Action ReadingPacketCompletedCallback { get; set; }
  21. public void Dispose()
  22. {
  23. }
  24. public Task ConnectAsync(TimeSpan timeout, CancellationToken cancellationToken)
  25. {
  26. return Task.FromResult(0);
  27. }
  28. public Task DisconnectAsync(TimeSpan timeout, CancellationToken cancellationToken)
  29. {
  30. return Task.FromResult(0);
  31. }
  32. public Task SendPacketAsync(MqttBasePacket packet, TimeSpan timeout, CancellationToken cancellationToken)
  33. {
  34. ThrowIfPartnerIsNull();
  35. Partner.EnqueuePacketInternal(packet);
  36. return Task.FromResult(0);
  37. }
  38. public Task<MqttBasePacket> ReceivePacketAsync(TimeSpan timeout, CancellationToken cancellationToken)
  39. {
  40. ThrowIfPartnerIsNull();
  41. return Task.Run(() =>
  42. {
  43. try
  44. {
  45. return _incomingPackets.Take(cancellationToken);
  46. }
  47. catch
  48. {
  49. return null;
  50. }
  51. }, cancellationToken);
  52. }
  53. private void EnqueuePacketInternal(MqttBasePacket packet)
  54. {
  55. if (packet == null) throw new ArgumentNullException(nameof(packet));
  56. _incomingPackets.Add(packet);
  57. }
  58. private void ThrowIfPartnerIsNull()
  59. {
  60. if (Partner == null)
  61. {
  62. throw new InvalidOperationException("Partner is not set.");
  63. }
  64. }
  65. }
  66. }