Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 

65 linhas
2.1 KiB

  1. using System;
  2. using System.Threading;
  3. using MQTTnet.Adapter;
  4. using MQTTnet.Diagnostics;
  5. using MQTTnet.Formatter;
  6. using MQTTnet.Internal;
  7. using MQTTnet.Packets;
  8. namespace MQTTnet.Tests
  9. {
  10. public sealed class MqttPacketSerializationHelper : IDisposable
  11. {
  12. readonly IMqttPacketFormatter _packetFormatter;
  13. readonly MqttProtocolVersion _protocolVersion;
  14. public MqttPacketSerializationHelper(MqttProtocolVersion protocolVersion = MqttProtocolVersion.V311, MqttBufferWriter bufferWriter = null)
  15. {
  16. _protocolVersion = protocolVersion;
  17. if (bufferWriter == null)
  18. {
  19. bufferWriter = new MqttBufferWriter(4096, 65535);
  20. }
  21. _packetFormatter = MqttPacketFormatterAdapter.GetMqttPacketFormatter(_protocolVersion, bufferWriter);
  22. }
  23. public MqttPacket Decode(MqttPacketBuffer buffer)
  24. {
  25. using (var channel = new TestMqttChannel(buffer.ToArray()))
  26. {
  27. var formatterAdapter = new MqttPacketFormatterAdapter(_protocolVersion, new MqttBufferWriter(4096, 65535));
  28. var adapter = new MqttChannelAdapter(channel, formatterAdapter, null, MqttNetNullLogger.Instance);
  29. return adapter.ReceivePacketAsync(CancellationToken.None).GetAwaiter().GetResult();
  30. }
  31. }
  32. public void Dispose()
  33. {
  34. }
  35. public MqttPacketBuffer Encode(MqttPacket packet)
  36. {
  37. return _packetFormatter.Encode(packet);
  38. }
  39. public static TPacket EncodeAndDecodePacket<TPacket>(TPacket packet, MqttProtocolVersion protocolVersion) where TPacket : MqttPacket
  40. {
  41. using (var helper = new MqttPacketSerializationHelper(protocolVersion))
  42. {
  43. var buffer = helper.Encode(packet);
  44. return (TPacket)helper.Decode(buffer);
  45. }
  46. }
  47. public static byte[] EncodePacket(MqttPacket packet)
  48. {
  49. using (var helper = new MqttPacketSerializationHelper())
  50. {
  51. return helper.Encode(packet).ToArray();
  52. }
  53. }
  54. }
  55. }