unsubscribe.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package packets
  2. import (
  3. "bytes"
  4. "fmt"
  5. "github.com/pborman/uuid"
  6. "io"
  7. )
  8. //UnsubscribePacket is an internal representation of the fields of the
  9. //Unsubscribe MQTT packet
  10. type UnsubscribePacket struct {
  11. FixedHeader
  12. MessageID uint16
  13. Topics []string
  14. uuid uuid.UUID
  15. }
  16. func (u *UnsubscribePacket) String() string {
  17. str := fmt.Sprintf("%s\n", u.FixedHeader)
  18. str += fmt.Sprintf("MessageID: %d", u.MessageID)
  19. return str
  20. }
  21. func (u *UnsubscribePacket) Write(w io.Writer) error {
  22. var body bytes.Buffer
  23. var err error
  24. body.Write(encodeUint16(u.MessageID))
  25. for _, topic := range u.Topics {
  26. body.Write(encodeString(topic))
  27. }
  28. u.FixedHeader.RemainingLength = body.Len()
  29. packet := u.FixedHeader.pack()
  30. packet.Write(body.Bytes())
  31. _, err = packet.WriteTo(w)
  32. return err
  33. }
  34. //Unpack decodes the details of a ControlPacket after the fixed
  35. //header has been read
  36. func (u *UnsubscribePacket) Unpack(b io.Reader) {
  37. u.MessageID = decodeUint16(b)
  38. var topic string
  39. for topic = decodeString(b); topic != ""; topic = decodeString(b) {
  40. u.Topics = append(u.Topics, topic)
  41. }
  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. }
  48. //UUID returns the unique ID assigned to the ControlPacket when
  49. //it was originally received. Note: this is not related to the
  50. //MessageID field for MQTT packets
  51. func (u *UnsubscribePacket) UUID() uuid.UUID {
  52. return u.uuid
  53. }