subscribe.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package packets
  2. import (
  3. "bytes"
  4. "fmt"
  5. "github.com/pborman/uuid"
  6. "io"
  7. )
  8. //SubscribePacket is an internal representation of the fields of the
  9. //Subscribe MQTT packet
  10. type SubscribePacket struct {
  11. FixedHeader
  12. MessageID uint16
  13. Topics []string
  14. Qoss []byte
  15. uuid uuid.UUID
  16. }
  17. func (s *SubscribePacket) String() string {
  18. str := fmt.Sprintf("%s\n", s.FixedHeader)
  19. str += fmt.Sprintf("MessageID: %d topics: %s", s.MessageID, s.Topics)
  20. return str
  21. }
  22. func (s *SubscribePacket) Write(w io.Writer) error {
  23. var body bytes.Buffer
  24. var err error
  25. body.Write(encodeUint16(s.MessageID))
  26. for i, topic := range s.Topics {
  27. body.Write(encodeString(topic))
  28. body.WriteByte(s.Qoss[i])
  29. }
  30. s.FixedHeader.RemainingLength = body.Len()
  31. packet := s.FixedHeader.pack()
  32. packet.Write(body.Bytes())
  33. _, err = packet.WriteTo(w)
  34. return err
  35. }
  36. //Unpack decodes the details of a ControlPacket after the fixed
  37. //header has been read
  38. func (s *SubscribePacket) Unpack(b io.Reader) {
  39. s.MessageID = decodeUint16(b)
  40. payloadLength := s.FixedHeader.RemainingLength - 2
  41. for payloadLength > 0 {
  42. topic := decodeString(b)
  43. s.Topics = append(s.Topics, topic)
  44. qos := decodeByte(b)
  45. s.Qoss = append(s.Qoss, qos)
  46. payloadLength -= 2 + len(topic) + 1 //2 bytes of string length, plus string, plus 1 byte for Qos
  47. }
  48. }
  49. //Details returns a Details struct containing the Qos and
  50. //MessageID of this ControlPacket
  51. func (s *SubscribePacket) Details() Details {
  52. return Details{Qos: 1, MessageID: s.MessageID}
  53. }
  54. //UUID returns the unique ID assigned to the ControlPacket when
  55. //it was originally received. Note: this is not related to the
  56. //MessageID field for MQTT packets
  57. func (s *SubscribePacket) UUID() uuid.UUID {
  58. return s.uuid
  59. }