Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 
 

66 řádky
1.9 KiB

  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. using MQTTnet.Core.Adapter;
  7. using MQTTnet.Core.Client;
  8. using MQTTnet.Core.Packets;
  9. using MQTTnet.Core.Serializer;
  10. namespace MQTTnet.Core.Tests
  11. {
  12. public class TestMqttCommunicationAdapter : IMqttCommunicationAdapter
  13. {
  14. private readonly BlockingCollection<MqttBasePacket> _incomingPackets = new BlockingCollection<MqttBasePacket>();
  15. public TestMqttCommunicationAdapter Partner { get; set; }
  16. public IMqttPacketSerializer PacketSerializer { get; } = new MqttPacketSerializer();
  17. public Task ConnectAsync(TimeSpan timeout, MqttClientOptions options)
  18. {
  19. return Task.FromResult(0);
  20. }
  21. public Task DisconnectAsync(TimeSpan timeout)
  22. {
  23. return Task.FromResult(0);
  24. }
  25. public Task SendPacketsAsync(TimeSpan timeout, CancellationToken cancellationToken, IEnumerable<MqttBasePacket> packets)
  26. {
  27. ThrowIfPartnerIsNull();
  28. foreach (var packet in packets)
  29. {
  30. Partner.SendPacketInternal(packet);
  31. }
  32. return Task.FromResult(0);
  33. }
  34. public Task<MqttBasePacket> ReceivePacketAsync(TimeSpan timeout, CancellationToken cancellationToken)
  35. {
  36. ThrowIfPartnerIsNull();
  37. return Task.Run(() => _incomingPackets.Take(), cancellationToken);
  38. }
  39. private void SendPacketInternal(MqttBasePacket packet)
  40. {
  41. if (packet == null) throw new ArgumentNullException(nameof(packet));
  42. _incomingPackets.Add(packet);
  43. }
  44. private void ThrowIfPartnerIsNull()
  45. {
  46. if (Partner == null)
  47. {
  48. throw new InvalidOperationException("Partner is not set.");
  49. }
  50. }
  51. }
  52. }