Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

69 wiersze
1.7 KiB

  1. package packet
  2. // SUBSCRIBE represents a SUBSCRIBE Packet.
  3. type SUBSCRIBE struct {
  4. base
  5. // PacketID is the Packet Identifier of the variable header.
  6. PacketID uint16
  7. // SubReqs is a slice of the subscription requests.
  8. SubReqs []*SubReq
  9. }
  10. // setFixedHeader sets the fixed header to the Packet.
  11. func (p *SUBSCRIBE) setFixedHeader() {
  12. // Append the first byte to the fixed header.
  13. p.fixedHeader = append(p.fixedHeader, TypeSUBSCRIBE<<4|0x02)
  14. // Append the Remaining Length to the fixed header.
  15. p.appendRemainingLength()
  16. }
  17. // setVariableHeader sets the variable header to the Packet.
  18. func (p *SUBSCRIBE) setVariableHeader() {
  19. // Append the Packet Identifier to the variable header.
  20. p.variableHeader = append(p.variableHeader, encodeUint16(p.PacketID)...)
  21. }
  22. // setPayload sets the payload to the Packet.
  23. func (p *SUBSCRIBE) setPayload() {
  24. // Append each subscription request to the payload.
  25. for _, s := range p.SubReqs {
  26. // Append the Topic Filter to the payload.
  27. p.payload = appendLenStr(p.payload, s.TopicFilter)
  28. // Append the QoS to the payload.
  29. p.payload = append(p.payload, s.QoS)
  30. }
  31. }
  32. // NewSUBSCRIBE creates and returns a SUBSCRIBE Packet.
  33. func NewSUBSCRIBE(opts *SUBSCRIBEOptions) (Packet, error) {
  34. // Initialize the options.
  35. if opts == nil {
  36. opts = &SUBSCRIBEOptions{}
  37. }
  38. // Validate the options.
  39. if err := opts.validate(); err != nil {
  40. return nil, err
  41. }
  42. // Create a SUBSCRIBE Packet.
  43. p := &SUBSCRIBE{
  44. PacketID: opts.PacketID,
  45. SubReqs: opts.SubReqs,
  46. }
  47. // Set the variable header to the Packet.
  48. p.setVariableHeader()
  49. // Set the payload to the Packet.
  50. p.setPayload()
  51. // Set the Fixed header to the Packet.
  52. p.setFixedHeader()
  53. // Return the Packet.
  54. return p, nil
  55. }