connack.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package packets
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. )
  7. // ConnackPacket is an internal representation of the fields of the
  8. // Connack MQTT packet
  9. type ConnackPacket struct {
  10. FixedHeader
  11. SessionPresent bool
  12. ReturnCode byte
  13. }
  14. func (ca *ConnackPacket) String() string {
  15. return fmt.Sprintf("%s sessionpresent: %t returncode: %d", ca.FixedHeader, ca.SessionPresent, ca.ReturnCode)
  16. }
  17. func (ca *ConnackPacket) Write(w io.Writer) error {
  18. var body bytes.Buffer
  19. var err error
  20. body.WriteByte(boolToByte(ca.SessionPresent))
  21. body.WriteByte(ca.ReturnCode)
  22. ca.FixedHeader.RemainingLength = 2
  23. packet := ca.FixedHeader.pack()
  24. packet.Write(body.Bytes())
  25. _, err = packet.WriteTo(w)
  26. return err
  27. }
  28. // Unpack decodes the details of a ControlPacket after the fixed
  29. // header has been read
  30. func (ca *ConnackPacket) Unpack(b io.Reader) error {
  31. flags, err := decodeByte(b)
  32. if err != nil {
  33. return err
  34. }
  35. ca.SessionPresent = 1&flags > 0
  36. ca.ReturnCode, err = decodeByte(b)
  37. return err
  38. }
  39. // Details returns a Details struct containing the Qos and
  40. // MessageID of this ControlPacket
  41. func (ca *ConnackPacket) Details() Details {
  42. return Details{Qos: 0, MessageID: 0}
  43. }