connack.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. // ConnackPacket is an internal representation of the fields of the
  23. // Connack MQTT packet
  24. type ConnackPacket struct {
  25. FixedHeader
  26. SessionPresent bool
  27. ReturnCode byte
  28. }
  29. func (ca *ConnackPacket) String() string {
  30. return fmt.Sprintf("%s sessionpresent: %t returncode: %d", ca.FixedHeader, ca.SessionPresent, ca.ReturnCode)
  31. }
  32. func (ca *ConnackPacket) Write(w io.Writer) error {
  33. var body bytes.Buffer
  34. var err error
  35. body.WriteByte(boolToByte(ca.SessionPresent))
  36. body.WriteByte(ca.ReturnCode)
  37. ca.FixedHeader.RemainingLength = 2
  38. packet := ca.FixedHeader.pack()
  39. packet.Write(body.Bytes())
  40. _, err = packet.WriteTo(w)
  41. return err
  42. }
  43. // Unpack decodes the details of a ControlPacket after the fixed
  44. // header has been read
  45. func (ca *ConnackPacket) Unpack(b io.Reader) error {
  46. flags, err := decodeByte(b)
  47. if err != nil {
  48. return err
  49. }
  50. ca.SessionPresent = 1&flags > 0
  51. ca.ReturnCode, err = decodeByte(b)
  52. return err
  53. }
  54. // Details returns a Details struct containing the Qos and
  55. // MessageID of this ControlPacket
  56. func (ca *ConnackPacket) Details() Details {
  57. return Details{Qos: 0, MessageID: 0}
  58. }