MqttMsgPingReq.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. Copyright (c) 2013, 2014 Paolo Patierno
  3. All rights reserved. This program and the accompanying materials
  4. are made available under the terms of the Eclipse Public License v1.0
  5. and Eclipse Distribution License v1.0 which accompany this distribution.
  6. The Eclipse Public License is available at
  7. http://www.eclipse.org/legal/epl-v10.html
  8. and the Eclipse Distribution License is available at
  9. http://www.eclipse.org/org/documents/edl-v10.php.
  10. Contributors:
  11. Paolo Patierno - initial API and implementation and/or initial documentation
  12. */
  13. using uPLibrary.Networking.M2Mqtt.Exceptions;
  14. namespace uPLibrary.Networking.M2Mqtt.Messages
  15. {
  16. /// <summary>
  17. /// Class for PINGREQ message from client to broker
  18. /// </summary>
  19. public class MqttMsgPingReq : MqttMsgBase
  20. {
  21. /// <summary>
  22. /// Constructor
  23. /// </summary>
  24. public MqttMsgPingReq()
  25. {
  26. this.type = MQTT_MSG_PINGREQ_TYPE;
  27. }
  28. public override byte[] GetBytes(byte protocolVersion)
  29. {
  30. byte[] buffer = new byte[2];
  31. int index = 0;
  32. // first fixed header byte
  33. if (protocolVersion == MqttMsgConnect.PROTOCOL_VERSION_V3_1_1)
  34. buffer[index++] = (MQTT_MSG_PINGREQ_TYPE << MSG_TYPE_OFFSET) | MQTT_MSG_PINGREQ_FLAG_BITS; // [v.3.1.1]
  35. else
  36. buffer[index++] = (MQTT_MSG_PINGREQ_TYPE << MSG_TYPE_OFFSET);
  37. buffer[index++] = 0x00;
  38. return buffer;
  39. }
  40. /// <summary>
  41. /// Parse bytes for a PINGREQ message
  42. /// </summary>
  43. /// <param name="fixedHeaderFirstByte">First fixed header byte</param>
  44. /// <param name="protocolVersion">Protocol Version</param>
  45. /// <param name="channel">Channel connected to the broker</param>
  46. /// <returns>PINGREQ message instance</returns>
  47. public static MqttMsgPingReq Parse(byte fixedHeaderFirstByte, byte protocolVersion, IMqttNetworkChannel channel)
  48. {
  49. MqttMsgPingReq msg = new MqttMsgPingReq();
  50. if (protocolVersion == MqttMsgConnect.PROTOCOL_VERSION_V3_1_1)
  51. {
  52. // [v3.1.1] check flag bits
  53. if ((fixedHeaderFirstByte & MSG_FLAG_BITS_MASK) != MQTT_MSG_PINGREQ_FLAG_BITS)
  54. throw new MqttClientException(MqttClientErrorCode.InvalidFlagBits);
  55. }
  56. // already know remaininglength is zero (MQTT specification),
  57. // so it isn't necessary to read other data from socket
  58. int remainingLength = MqttMsgBase.decodeRemainingLength(channel);
  59. return msg;
  60. }
  61. public override string ToString()
  62. {
  63. #if TRACE
  64. return this.GetTraceString(
  65. "PINGREQ",
  66. null,
  67. null);
  68. #else
  69. return base.ToString();
  70. #endif
  71. }
  72. }
  73. }