unsubscribe.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. * Copyright (c) 2021 IBM Corp and others.
  3. *
  4. * All rights reserved. This program and the accompanying materials
  5. * are made available under the terms of the Eclipse Public License v2.0
  6. * and Eclipse Distribution License v1.0 which accompany this distribution.
  7. *
  8. * The Eclipse Public License is available at
  9. * https://www.eclipse.org/legal/epl-2.0/
  10. * and the Eclipse Distribution License is available at
  11. * http://www.eclipse.org/org/documents/edl-v10.php.
  12. *
  13. * Contributors:
  14. * Allan Stockdill-Mander
  15. */
  16. package packets
  17. import (
  18. "bytes"
  19. "fmt"
  20. "io"
  21. )
  22. // UnsubscribePacket is an internal representation of the fields of the
  23. // Unsubscribe MQTT packet
  24. type UnsubscribePacket struct {
  25. FixedHeader
  26. MessageID uint16
  27. Topics []string
  28. }
  29. func (u *UnsubscribePacket) String() string {
  30. return fmt.Sprintf("%s MessageID: %d", u.FixedHeader, u.MessageID)
  31. }
  32. func (u *UnsubscribePacket) Write(w io.Writer) error {
  33. var body bytes.Buffer
  34. var err error
  35. body.Write(encodeUint16(u.MessageID))
  36. for _, topic := range u.Topics {
  37. body.Write(encodeString(topic))
  38. }
  39. u.FixedHeader.RemainingLength = body.Len()
  40. packet := u.FixedHeader.pack()
  41. packet.Write(body.Bytes())
  42. _, err = packet.WriteTo(w)
  43. return err
  44. }
  45. // Unpack decodes the details of a ControlPacket after the fixed
  46. // header has been read
  47. func (u *UnsubscribePacket) Unpack(b io.Reader) error {
  48. var err error
  49. u.MessageID, err = decodeUint16(b)
  50. if err != nil {
  51. return err
  52. }
  53. for topic, err := decodeString(b); err == nil && topic != ""; topic, err = decodeString(b) {
  54. u.Topics = append(u.Topics, topic)
  55. }
  56. return err
  57. }
  58. // Details returns a Details struct containing the Qos and
  59. // MessageID of this ControlPacket
  60. func (u *UnsubscribePacket) Details() Details {
  61. return Details{Qos: 1, MessageID: u.MessageID}
  62. }