MqttMsgDisconnect.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 DISCONNECT message from client to broker
  18. /// </summary>
  19. public class MqttMsgDisconnect : MqttMsgBase
  20. {
  21. /// <summary>
  22. /// Constructor
  23. /// </summary>
  24. public MqttMsgDisconnect()
  25. {
  26. this.type = MQTT_MSG_DISCONNECT_TYPE;
  27. }
  28. /// <summary>
  29. /// Parse bytes for a DISCONNECT message
  30. /// </summary>
  31. /// <param name="fixedHeaderFirstByte">First fixed header byte</param>
  32. /// <param name="protocolVersion">Protocol Version</param>
  33. /// <param name="channel">Channel connected to the broker</param>
  34. /// <returns>DISCONNECT message instance</returns>
  35. public static MqttMsgDisconnect Parse(byte fixedHeaderFirstByte, byte protocolVersion, IMqttNetworkChannel channel)
  36. {
  37. MqttMsgDisconnect msg = new MqttMsgDisconnect();
  38. if (protocolVersion == MqttMsgConnect.PROTOCOL_VERSION_V3_1_1)
  39. {
  40. // [v3.1.1] check flag bits
  41. if ((fixedHeaderFirstByte & MSG_FLAG_BITS_MASK) != MQTT_MSG_DISCONNECT_FLAG_BITS)
  42. throw new MqttClientException(MqttClientErrorCode.InvalidFlagBits);
  43. }
  44. // get remaining length and allocate buffer
  45. int remainingLength = MqttMsgBase.decodeRemainingLength(channel);
  46. // NOTE : remainingLength must be 0
  47. return msg;
  48. }
  49. public override byte[] GetBytes(byte protocolVersion)
  50. {
  51. byte[] buffer = new byte[2];
  52. int index = 0;
  53. // first fixed header byte
  54. if (protocolVersion == MqttMsgConnect.PROTOCOL_VERSION_V3_1_1)
  55. buffer[index++] = (MQTT_MSG_DISCONNECT_TYPE << MSG_TYPE_OFFSET) | MQTT_MSG_DISCONNECT_FLAG_BITS; // [v.3.1.1]
  56. else
  57. buffer[index++] = (MQTT_MSG_DISCONNECT_TYPE << MSG_TYPE_OFFSET);
  58. buffer[index++] = 0x00;
  59. return buffer;
  60. }
  61. public override string ToString()
  62. {
  63. #if TRACE
  64. return this.GetTraceString(
  65. "DISCONNECT",
  66. null,
  67. null);
  68. #else
  69. return base.ToString();
  70. #endif
  71. }
  72. }
  73. }