suback.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * Copyright (c) 2021 IBM Corp and others.
  3. *
  4. * All rights reserved. This program and the accompanying materials
  5. * are made available under the terms of the Eclipse Public License v2.0
  6. * and Eclipse Distribution License v1.0 which accompany this distribution.
  7. *
  8. * The Eclipse Public License is available at
  9. * https://www.eclipse.org/legal/epl-2.0/
  10. * and the Eclipse Distribution License is available at
  11. * http://www.eclipse.org/org/documents/edl-v10.php.
  12. *
  13. * Contributors:
  14. * Allan Stockdill-Mander
  15. */
  16. package packets
  17. import (
  18. "bytes"
  19. "fmt"
  20. "io"
  21. )
  22. // SubackPacket is an internal representation of the fields of the
  23. // Suback MQTT packet
  24. type SubackPacket struct {
  25. FixedHeader
  26. MessageID uint16
  27. ReturnCodes []byte
  28. }
  29. func (sa *SubackPacket) String() string {
  30. return fmt.Sprintf("%s MessageID: %d", sa.FixedHeader, sa.MessageID)
  31. }
  32. func (sa *SubackPacket) Write(w io.Writer) error {
  33. var body bytes.Buffer
  34. var err error
  35. body.Write(encodeUint16(sa.MessageID))
  36. body.Write(sa.ReturnCodes)
  37. sa.FixedHeader.RemainingLength = body.Len()
  38. packet := sa.FixedHeader.pack()
  39. packet.Write(body.Bytes())
  40. _, err = packet.WriteTo(w)
  41. return err
  42. }
  43. // Unpack decodes the details of a ControlPacket after the fixed
  44. // header has been read
  45. func (sa *SubackPacket) Unpack(b io.Reader) error {
  46. var qosBuffer bytes.Buffer
  47. var err error
  48. sa.MessageID, err = decodeUint16(b)
  49. if err != nil {
  50. return err
  51. }
  52. _, err = qosBuffer.ReadFrom(b)
  53. if err != nil {
  54. return err
  55. }
  56. sa.ReturnCodes = qosBuffer.Bytes()
  57. return nil
  58. }
  59. // Details returns a Details struct containing the Qos and
  60. // MessageID of this ControlPacket
  61. func (sa *SubackPacket) Details() Details {
  62. return Details{Qos: 0, MessageID: sa.MessageID}
  63. }