unsubscribe.go 1.2 KB

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