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.
 
 
 
 

92 lines
2.9 KiB

  1. using System;
  2. using System.IO;
  3. using System.Text;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. using MQTTnet.Core.Adapter;
  7. using MQTTnet.Core.Exceptions;
  8. using MQTTnet.Core.Protocol;
  9. using MQTTnet.Core.Packets;
  10. namespace MQTTnet.Core.Serializer
  11. {
  12. public sealed class MqttPacketReader : BinaryReader
  13. {
  14. private readonly ReceivedMqttPacket _receivedMqttPacket;
  15. public MqttPacketReader(ReceivedMqttPacket receivedMqttPacket)
  16. : base(receivedMqttPacket.Body, Encoding.UTF8, true)
  17. {
  18. _receivedMqttPacket = receivedMqttPacket;
  19. }
  20. public bool EndOfRemainingData => BaseStream.Position == _receivedMqttPacket.Header.BodyLength;
  21. public static MqttPacketHeader ReadHeaderFromSource(Stream stream, CancellationToken cancellationToken)
  22. {
  23. var fixedHeader = (byte)stream.ReadByte();
  24. var controlPacketType = (MqttControlPacketType)(fixedHeader >> 4);
  25. var bodyLength = ReadBodyLengthFromSource(stream, cancellationToken);
  26. return new MqttPacketHeader
  27. {
  28. FixedHeader = fixedHeader,
  29. ControlPacketType = controlPacketType,
  30. BodyLength = bodyLength
  31. };
  32. }
  33. public override ushort ReadUInt16()
  34. {
  35. var buffer = ReadBytes(2);
  36. var temp = buffer[0];
  37. buffer[0] = buffer[1];
  38. buffer[1] = temp;
  39. return BitConverter.ToUInt16(buffer, 0);
  40. }
  41. public string ReadStringWithLengthPrefix()
  42. {
  43. var buffer = ReadWithLengthPrefix();
  44. return Encoding.UTF8.GetString(buffer, 0, buffer.Length);
  45. }
  46. public byte[] ReadWithLengthPrefix()
  47. {
  48. var length = ReadUInt16();
  49. return ReadBytes(length);
  50. }
  51. public byte[] ReadRemainingData()
  52. {
  53. return ReadBytes(_receivedMqttPacket.Header.BodyLength - (int)BaseStream.Position);
  54. }
  55. private static int ReadBodyLengthFromSource(Stream stream, CancellationToken cancellationToken)
  56. {
  57. // Alorithm taken from http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html.
  58. var multiplier = 1;
  59. var value = 0;
  60. byte encodedByte;
  61. do
  62. {
  63. if (cancellationToken.IsCancellationRequested)
  64. {
  65. throw new TaskCanceledException();
  66. }
  67. encodedByte = (byte)stream.ReadByte();
  68. value += (encodedByte & 127) * multiplier;
  69. multiplier *= 128;
  70. if (multiplier > 128 * 128 * 128)
  71. {
  72. throw new MqttProtocolViolationException("Remaining length is invalid.");
  73. }
  74. } while ((encodedByte & 128) != 0);
  75. return value;
  76. }
  77. }
  78. }