suback.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package packets
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. )
  7. // SubackPacket is an internal representation of the fields of the
  8. // Suback MQTT packet
  9. type SubackPacket struct {
  10. FixedHeader
  11. MessageID uint16
  12. ReturnCodes []byte
  13. }
  14. func (sa *SubackPacket) String() string {
  15. return fmt.Sprintf("%s MessageID: %d", sa.FixedHeader, sa.MessageID)
  16. }
  17. func (sa *SubackPacket) Write(w io.Writer) error {
  18. var body bytes.Buffer
  19. var err error
  20. body.Write(encodeUint16(sa.MessageID))
  21. body.Write(sa.ReturnCodes)
  22. sa.FixedHeader.RemainingLength = body.Len()
  23. packet := sa.FixedHeader.pack()
  24. packet.Write(body.Bytes())
  25. _, err = packet.WriteTo(w)
  26. return err
  27. }
  28. // Unpack decodes the details of a ControlPacket after the fixed
  29. // header has been read
  30. func (sa *SubackPacket) Unpack(b io.Reader) error {
  31. var qosBuffer bytes.Buffer
  32. var err error
  33. sa.MessageID, err = decodeUint16(b)
  34. if err != nil {
  35. return err
  36. }
  37. _, err = qosBuffer.ReadFrom(b)
  38. if err != nil {
  39. return err
  40. }
  41. sa.ReturnCodes = qosBuffer.Bytes()
  42. return nil
  43. }
  44. // Details returns a Details struct containing the Qos and
  45. // MessageID of this ControlPacket
  46. func (sa *SubackPacket) Details() Details {
  47. return Details{Qos: 0, MessageID: sa.MessageID}
  48. }