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.
 
 
 
 

81 lines
2.2 KiB

  1. using System;
  2. using System.IO;
  3. using System.Text;
  4. using MQTTnet.Protocol;
  5. namespace MQTTnet.Serializer
  6. {
  7. public static class MqttPacketWriter
  8. {
  9. public static byte BuildFixedHeader(MqttControlPacketType packetType, byte flags = 0)
  10. {
  11. var fixedHeader = (int)packetType << 4;
  12. fixedHeader |= flags;
  13. return (byte)fixedHeader;
  14. }
  15. public static void Write(this Stream stream, ushort value)
  16. {
  17. var buffer = BitConverter.GetBytes(value);
  18. stream.WriteByte(buffer[1]);
  19. stream.WriteByte(buffer[0]);
  20. }
  21. public static void Write(this Stream stream, ByteWriter value)
  22. {
  23. if (value == null) throw new ArgumentNullException(nameof(value));
  24. stream.Write(value.Value);
  25. }
  26. public static void WriteWithLengthPrefix(this Stream stream, string value)
  27. {
  28. stream.WriteWithLengthPrefix(Encoding.UTF8.GetBytes(value ?? string.Empty));
  29. }
  30. public static void WriteWithLengthPrefix(this Stream stream, byte[] value)
  31. {
  32. var length = (ushort)value.Length;
  33. stream.Write(length);
  34. stream.Write(value, 0, length);
  35. }
  36. public static int EncodeRemainingLength(int length, MemoryStream stream)
  37. {
  38. // write the encoded remaining length right aligned on the 4 byte buffer
  39. if (length <= 0)
  40. {
  41. stream.Seek(3, SeekOrigin.Current);
  42. stream.WriteByte(0);
  43. return 1;
  44. }
  45. var buffer = new byte[4];
  46. var offset = 0;
  47. // Alorithm taken from http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html.
  48. var x = length;
  49. do
  50. {
  51. var encodedByte = x % 128;
  52. x = x / 128;
  53. if (x > 0)
  54. {
  55. encodedByte = encodedByte | 128;
  56. }
  57. buffer[offset] = (byte)encodedByte;
  58. offset++;
  59. } while (x > 0);
  60. stream.Seek(4 - offset, SeekOrigin.Current);
  61. stream.Write(buffer, 0, offset);
  62. return offset;
  63. }
  64. }
  65. }