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.
 
 
 
 

91 lines
2.4 KiB

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