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ů.
 
 
 
 

98 řádky
2.8 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.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 void Dispose()
  17. {
  18. }
  19. public Task ConnectAsync(TimeSpan timeout, CancellationToken cancellationToken)
  20. {
  21. return Task.FromResult(0);
  22. }
  23. public Task DisconnectAsync(TimeSpan timeout, CancellationToken cancellationToken)
  24. {
  25. return Task.FromResult(0);
  26. }
  27. public Task SendPacketsAsync(TimeSpan timeout, IEnumerable<MqttBasePacket> packets, CancellationToken cancellationToken)
  28. {
  29. ThrowIfPartnerIsNull();
  30. foreach (var packet in packets)
  31. {
  32. Partner.EnqueuePacketInternal(packet);
  33. }
  34. return Task.FromResult(0);
  35. }
  36. public async Task<MqttBasePacket> ReceivePacketAsync(TimeSpan timeout, CancellationToken cancellationToken)
  37. {
  38. ThrowIfPartnerIsNull();
  39. if (timeout > TimeSpan.Zero)
  40. {
  41. using (var timeoutCts = new CancellationTokenSource(timeout))
  42. using (var cts = CancellationTokenSource.CreateLinkedTokenSource(timeoutCts.Token, cancellationToken))
  43. {
  44. return await Task.Run(() =>
  45. {
  46. try
  47. {
  48. return _incomingPackets.Take(cts.Token);
  49. }
  50. catch
  51. {
  52. return null;
  53. }
  54. }, cts.Token);
  55. }
  56. }
  57. return await Task.Run(() =>
  58. {
  59. try
  60. {
  61. return _incomingPackets.Take(cancellationToken);
  62. }
  63. catch
  64. {
  65. return null;
  66. }
  67. }, cancellationToken);
  68. }
  69. private void EnqueuePacketInternal(MqttBasePacket packet)
  70. {
  71. if (packet == null) throw new ArgumentNullException(nameof(packet));
  72. _incomingPackets.Add(packet);
  73. }
  74. private void ThrowIfPartnerIsNull()
  75. {
  76. if (Partner == null)
  77. {
  78. throw new InvalidOperationException("Partner is not set.");
  79. }
  80. }
  81. }
  82. }