Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.

TestMqttCommunicationAdapter.cs 1.8 KiB

7 anni fa
7 anni fa
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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.Adapter;
  7. using MQTTnet.Packets;
  8. using MQTTnet.Serializer;
  9. namespace MQTTnet.Core.Tests
  10. {
  11. public class TestMqttCommunicationAdapter : IMqttChannelAdapter
  12. {
  13. private readonly BlockingCollection<MqttBasePacket> _incomingPackets = new BlockingCollection<MqttBasePacket>();
  14. public TestMqttCommunicationAdapter Partner { get; set; }
  15. public IMqttPacketSerializer PacketSerializer { get; } = new MqttPacketSerializer();
  16. public Task ConnectAsync(TimeSpan timeout)
  17. {
  18. return Task.FromResult(0);
  19. }
  20. public Task DisconnectAsync(TimeSpan timeout)
  21. {
  22. return Task.FromResult(0);
  23. }
  24. public Task SendPacketsAsync(TimeSpan timeout, CancellationToken cancellationToken, IEnumerable<MqttBasePacket> packets)
  25. {
  26. ThrowIfPartnerIsNull();
  27. foreach (var packet in packets)
  28. {
  29. Partner.EnqueuePacketInternal(packet);
  30. }
  31. return Task.FromResult(0);
  32. }
  33. public Task<MqttBasePacket> ReceivePacketAsync(TimeSpan timeout, CancellationToken cancellationToken)
  34. {
  35. ThrowIfPartnerIsNull();
  36. return Task.Run(() => _incomingPackets.Take(), cancellationToken);
  37. }
  38. private void EnqueuePacketInternal(MqttBasePacket packet)
  39. {
  40. if (packet == null) throw new ArgumentNullException(nameof(packet));
  41. _incomingPackets.Add(packet);
  42. }
  43. private void ThrowIfPartnerIsNull()
  44. {
  45. if (Partner == null)
  46. {
  47. throw new InvalidOperationException("Partner is not set.");
  48. }
  49. }
  50. }
  51. }