mqtt

package module
v0.0.0-...-d25d63c Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 7, 2020 License: Apache-2.0 Imports: 7 Imported by: 0

README

MQTT

Apache-2.0 License GitHub stars GitHub forks GitHub release Go reference

Package htdvisser.dev/mqtt implements MQTT 3.1.1 and MQTT 5.0 packet types as well as a reader and a writer.

Background

MQTT is a publish/subscribe messaging transport protocol often used in Internet of Things communication. The MQTT specifications are maintained by OASIS.

Goals and Non-Goals

The goal of this library is to provide basic MQTT packet types, as well as implementations for reading and writing those packets. This library aims to implement version 3.1.1 and version 5.0 of the specification, with limited support for version 3.1.

This library does not -- and will not -- implement a client or server (broker), but it can be used by client or server implementations.

Install

go get -u htdvisser.dev/mqtt

Usage

See the examples on pkg.go.dev.

Contributing

See CONTRIBUTING.md and CODE_OF_CONDUCT.md.

License

Apache-2.0 © Hylke Visser

Documentation

Overview

Package mqtt implements MQTT 3.1.1 and MQTT 5.0 packet types as well as a reader and a writer.

Example (Client)
package main

import (
	"log"
	"net"
	"time"

	"htdvisser.dev/mqtt"
)

func main() {
	conn, err := net.Dial("tcp", "localhost:1883")
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()

	reader, writer := mqtt.NewReader(conn), mqtt.NewWriter(conn)

	connect := new(mqtt.ConnectPacket)
	connect.SetCleanSession(true)
	connect.SetUsername([]byte("username"))
	connect.SetPassword([]byte("password"))

	if err = writer.WritePacket(connect); err != nil {
		log.Fatal(err)
	}

	packet, err := reader.ReadPacket()
	if err != nil {
		log.Fatal(err)
	}
	if packet.PacketType() != mqtt.CONNACK {
		log.Fatal("first packet was not CONNACK")
	}
	connack := packet.(*mqtt.ConnackPacket)

	if connack.ReasonCode != mqtt.Success {
		// TODO: Check actual reason code
		log.Fatal("connect failed")
	}

	go func() {
		subscribe := new(mqtt.SubscribePacket)
		subscribe.PacketIdentifier = 1 // TODO: Keep track of these.
		subscribe.SubscribePayload = append(subscribe.SubscribePayload, mqtt.Subscription{
			TopicFilter: []byte("time/+"),
			QoS:         1,
		})
		if err := writer.WritePacket(subscribe); err != nil {
			log.Fatal(err)
		}

		for t := range time.Tick(time.Second) {
			publish := new(mqtt.PublishPacket)
			publish.SetRetain(true)
			publish.TopicName = []byte("time/now")
			publish.PublishPayload = []byte(t.Format(time.RFC3339))
			if err = writer.WritePacket(publish); err != nil {
				log.Fatal(err)
			}
		}
	}()

	for {
		packet, err := reader.ReadPacket()
		if err != nil {
			log.Fatal(err)
		}

		switch packet.PacketType() {
		case mqtt.PUBLISH:
			publish := packet.(*mqtt.PublishPacket)
			switch publish.QoS() {
			case mqtt.QoS1:
				puback := publish.Puback()
				// TODO: Handle QoS 1 publish
				err = writer.WritePacket(puback)
			case mqtt.QoS2:
				pubrec := publish.Pubrec()
				// TODO: Handle QoS 2 publish
				err = writer.WritePacket(pubrec)
			}
		case mqtt.PUBACK:
			puback := packet.(*mqtt.PubackPacket)
			// TODO: Handle QoS 1 publish
			_ = puback.PacketIdentifier
		case mqtt.PUBREC:
			pubrec := packet.(*mqtt.PubrecPacket)
			pubrel := pubrec.Pubrel()
			// TODO: Handle QoS 2 publish
			err = writer.WritePacket(pubrel)
		case mqtt.PUBREL:
			pubrel := packet.(*mqtt.PubrelPacket)
			pubcomp := pubrel.Pubcomp()
			// TODO: Handle QoS 2 publish
			err = writer.WritePacket(pubcomp)
		case mqtt.PUBCOMP:
			pubcomp := packet.(*mqtt.PubcompPacket)
			// TODO: Handle QoS 2 publish
			_ = pubcomp.PacketIdentifier
		case mqtt.SUBACK:
			suback := packet.(*mqtt.SubackPacket)
			// TODO: Find subscribe by ID
			_ = suback.PacketIdentifier
			// TODO: Handle reason codes for subscribes
			_ = suback.SubackPayload
		case mqtt.UNSUBACK:
			unsuback := packet.(*mqtt.UnsubackPacket)
			// TODO: Find unsubscribe by ID
			_ = unsuback.PacketIdentifier
			// TODO: Handle reason codes for unsubscribes
			_ = unsuback.UnsubackPayload
		case mqtt.PINGRESP:
			// TODO: Handle pingresp
		case mqtt.DISCONNECT:
			disconnect := packet.(*mqtt.DisconnectPacket)
			_ = disconnect.ReasonCode
			// TODO: Handle disconnect
			return
		case mqtt.AUTH:
			auth := packet.(*mqtt.AuthPacket)
			if auth.ReasonCode != mqtt.ContinueAuthentication {
				log.Fatal("received auth packet with invalid reason code")
			}
			// TODO: Handle auth
		}
		if err != nil {
			log.Fatal(err)
		}
	}
}
Output:

Example (Server)
package main

import (
	"context"
	"errors"
	"log"
	"net"
	"sync"
	"time"

	"htdvisser.dev/mqtt"
)

func ListenAndAccept(address string, handle func(net.Conn) error) error {
	lis, err := net.Listen("tcp", address)
	if err != nil {
		log.Fatal(err)
	}
	for {
		conn, err := lis.Accept()
		if err != nil {
			return err
		}
		go func() {
			defer conn.Close()
			handle(conn)
		}()
	}
}

func checkAuth(username, password []byte) error {
	return nil
}

func main() {
	ListenAndAccept("localhost:1883", func(conn net.Conn) error {
		ctx, cancel := context.WithCancel(context.Background())
		var wg sync.WaitGroup
		defer func() {
			cancel()
			wg.Wait()
		}()

		reader, writer := mqtt.NewReader(conn), mqtt.NewWriter(conn)

		timeout := 10 * time.Second

		conn.SetReadDeadline(time.Now().Add(timeout)) // Read deadline for CONNECT.

		packet, err := reader.ReadPacket()
		if err != nil {
			return err
		}
		if packet.PacketType() != mqtt.CONNECT {
			return errors.New("first packet was not CONNECT")
		}
		connect := packet.(*mqtt.ConnectPacket)
		writer.SetProtocol(connect.ProtocolVersion)

		conn.SetWriteDeadline(time.Now().Add(timeout)) // Write deadline for CONNACK.

		connack := connect.Connack()

		if err := checkAuth(connect.Username(), connect.Password()); err != nil {
			connack.ReasonCode = mqtt.BadUsernameOrPassword
			return writer.WritePacket(connack)
		}

		if connect.KeepAlive != 0 {
			timeout = time.Duration(connect.KeepAlive) * 1500 * time.Millisecond
		}

		// TODO: Handle session, will, ...

		if err = writer.WritePacket(connack); err != nil {
			return err
		}

		conn.SetReadDeadline(time.Now().Add(timeout))
		conn.SetWriteDeadline(time.Time{}) // Clear write deadline.

		var (
			controlPackets = make(chan mqtt.Packet)
			publishPackets = make(chan *mqtt.PublishPacket)
		)

		wg.Add(1)
		go func() { // Write routine
			defer wg.Done()
			for {
				select {
				case <-ctx.Done():
					return
				case pkt := <-controlPackets:
					conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
					err = writer.WritePacket(pkt)
				case pkt := <-publishPackets:
					conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
					err = writer.WritePacket(pkt)
				}
				if err != nil {
					// TODO: Handle error
				}
			}
		}()

		for { // Read routine
			conn.SetReadDeadline(time.Now().Add(timeout))
			packet, err := reader.ReadPacket()
			if err != nil {
				return err
			}

			switch packet.PacketType() {
			case mqtt.PUBLISH:
				publish := packet.(*mqtt.PublishPacket)
				switch publish.QoS() {
				case mqtt.QoS1:
					puback := publish.Puback()
					// TODO: Handle QoS 1 publish
					controlPackets <- puback
				case mqtt.QoS2:
					pubrec := publish.Pubrec()
					// TODO: Handle QoS 2 publish
					controlPackets <- pubrec
				}
			case mqtt.PUBACK:
				puback := packet.(*mqtt.PubackPacket)
				// TODO: Handle QoS 1 publish
				_ = puback.PacketIdentifier
			case mqtt.PUBREC:
				pubrec := packet.(*mqtt.PubrecPacket)
				pubrel := pubrec.Pubrel()
				// TODO: Handle QoS 2 publish
				controlPackets <- pubrel
			case mqtt.PUBREL:
				pubrel := packet.(*mqtt.PubrelPacket)
				pubcomp := pubrel.Pubcomp()
				// TODO: Handle QoS 2 publish
				controlPackets <- pubcomp
			case mqtt.PUBCOMP:
				pubcomp := packet.(*mqtt.PubcompPacket)
				// TODO: Handle QoS 2 publish
				_ = pubcomp.PacketIdentifier
			case mqtt.SUBSCRIBE:
				subscribe := packet.(*mqtt.SubscribePacket)
				suback := subscribe.Suback()
				// TODO: Handle subscribe, set reason codes in suback
				controlPackets <- suback
			case mqtt.UNSUBSCRIBE:
				unsubscribe := packet.(*mqtt.UnsubscribePacket)
				unsuback := unsubscribe.Unsuback()
				// TODO: Handle unsubscribe, set reason codes in unsuback
				controlPackets <- unsuback
			case mqtt.PINGREQ:
				pingreq := packet.(*mqtt.PingreqPacket)
				pingresp := pingreq.Pingresp()
				controlPackets <- pingresp
			case mqtt.DISCONNECT:
				disconnect := packet.(*mqtt.DisconnectPacket)
				_ = disconnect.ReasonCode
				// TODO: Handle disconnect
				return nil
			case mqtt.AUTH:
				auth := packet.(*mqtt.AuthPacket)
				if auth.ReasonCode != mqtt.ContinueAuthentication {
					return errors.New("received auth packet with invalid reason code")
				}
				// TODO: Handle auth
			}
			if err != nil {
				return err
			}
		}
	})
}
Output:

Index

Examples

Constants

View Source
const (
	PayloadFormatIndicator          = 1  // Payload Format Indicator
	MessageExpiryInterval           = 2  // Message Expiry Interval
	ContentType                     = 3  // Content Type
	ResponseTopic                   = 8  // Response Topic
	CorrelationData                 = 9  // Correlation Data
	SubscriptionIdentifier          = 11 // Subscription Identifier
	SessionExpiryInterval           = 17 // Session Expiry Interval
	AssignedClientIdentifier        = 18 // Assigned Client Identifier
	ServerKeepAlive                 = 19 // Server Keep Alive
	AuthenticationMethod            = 21 // Authentication Method
	AuthenticationData              = 22 // Authentication Data
	RequestProblemInformation       = 23 // Request Problem Information
	WillDelayInterval               = 24 // Will Delay Interval
	RequestResponseInformation      = 25 // Request Response Information
	ResponseInformation             = 26 // Response Information
	ServerReference                 = 28 // Server Reference
	ReasonString                    = 31 // Reason String
	ReceiveMaximum                  = 33 // Receive Maximum
	TopicAliasMaximum               = 34 // Topic Alias Maximum
	TopicAlias                      = 35 // Topic Alias
	MaximumQoS                      = 36 // Maximum QoS
	RetainAvailable                 = 37 // Retain Available
	UserProperty                    = 38 // User Property
	MaximumPacketSize               = 39 // Maximum Packet Size
	WildcardSubscriptionAvailable   = 40 // Wildcard Subscription Available
	SubscriptionIdentifierAvailable = 41 // Subscription Identifier Available
	SharedSubscriptionAvailable     = 42 // Shared Subscription Available
)

PropertyIdentifier values.

Variables

View Source
var DefaultProtocolVersion byte = 4

DefaultProtocolVersion is the default MQTT protocol version to use.

Functions

func NewReasonCodeError

func NewReasonCodeError(c ReasonCode, message string) error

NewReasonCodeError returns a new error based on the given reason code.

Types

type AuthHeader

type AuthHeader struct {
	ReasonCode
}

AuthHeader is the header of the Auth packet.

type AuthPacket

type AuthPacket struct {
	AuthHeader
	Properties
}

AuthPacket is the Auth packet.

func (*AuthPacket) Auth

func (p *AuthPacket) Auth() *AuthPacket

Auth returns an AuthPacket as response to the AuthPacket.

func (AuthPacket) PacketType

func (AuthPacket) PacketType() PacketType

PacketType returns the packet type of the Auth packet.

func (*AuthPacket) Reply

func (p *AuthPacket) Reply() Packet

Reply returns the appropriate reply to this packet.

type ConnackHeader

type ConnackHeader struct {
	ConnackHeaderFlags
	ReasonCode
}

ConnackHeader is the header of the Connack packet.

type ConnackHeaderFlags

type ConnackHeaderFlags byte

ConnackHeaderFlags are the flags in the header of the Connack packet.

func (ConnackHeaderFlags) SessionPresent

func (f ConnackHeaderFlags) SessionPresent() bool

SessionPresent returns Session Present bit from the connack header flags.

func (*ConnackHeaderFlags) SetSessionPresent

func (f *ConnackHeaderFlags) SetSessionPresent(sessionPresent bool)

SetSessionPresent sets the Session Present bit into the connack header flags.

type ConnackPacket

type ConnackPacket struct {
	ConnackHeader
	Properties
}

ConnackPacket is the Connack packet.

func (ConnackPacket) PacketType

func (ConnackPacket) PacketType() PacketType

PacketType returns the packet type of the Connack packet.

type ConnectHeader

type ConnectHeader struct {
	ProtocolName    []byte
	ProtocolVersion byte
	ConnectHeaderFlags
	KeepAlive uint16
}

ConnectHeader is the header of the Connect packet.

type ConnectHeaderFlags

type ConnectHeaderFlags byte

ConnectHeaderFlags are the flags in the header of the Connect packet.

func (ConnectHeaderFlags) CleanSession

func (f ConnectHeaderFlags) CleanSession() bool

CleanSession is an alias for CleanStart.

func (ConnectHeaderFlags) CleanStart

func (f ConnectHeaderFlags) CleanStart() bool

CleanStart returns the CleanStart bit from the connect header flags.

func (ConnectHeaderFlags) Password

func (f ConnectHeaderFlags) Password() bool

Password returns the Password bit from the connect header flags.

func (*ConnectHeaderFlags) SetCleanSession

func (f *ConnectHeaderFlags) SetCleanSession(cleanSession bool)

SetCleanSession is an alias for SetCleanStart.

func (*ConnectHeaderFlags) SetCleanStart

func (f *ConnectHeaderFlags) SetCleanStart(cleanSession bool)

SetCleanStart sets the CleanStart bit into the connect header flags.

func (*ConnectHeaderFlags) SetPassword

func (f *ConnectHeaderFlags) SetPassword(password bool)

SetPassword sets the Password bit into the connect header flags.

func (*ConnectHeaderFlags) SetUsername

func (f *ConnectHeaderFlags) SetUsername(username bool)

SetUsername sets the Username bit into the connect header flags.

func (*ConnectHeaderFlags) SetWill

func (f *ConnectHeaderFlags) SetWill(will bool)

SetWill sets the Will bit into the connect header flags.

func (*ConnectHeaderFlags) SetWillQoS

func (f *ConnectHeaderFlags) SetWillQoS(qos QoS)

SetWillQoS sets the WillQoS into the connect header flags.

func (*ConnectHeaderFlags) SetWillRetain

func (f *ConnectHeaderFlags) SetWillRetain(willRetain bool)

SetWillRetain sets the WillRetain bit into the connect header flags.

func (ConnectHeaderFlags) Username

func (f ConnectHeaderFlags) Username() bool

Username returns the Username bit from the connect header flags.

func (ConnectHeaderFlags) Will

func (f ConnectHeaderFlags) Will() bool

Will returns the Will bit from the connect header flags.

func (ConnectHeaderFlags) WillQoS

func (f ConnectHeaderFlags) WillQoS() QoS

WillQoS returns the WillQoS from the connect header flags.

func (ConnectHeaderFlags) WillRetain

func (f ConnectHeaderFlags) WillRetain() bool

WillRetain returns the WillRetain bit from the connect header flags.

type ConnectPacket

type ConnectPacket struct {
	ConnectHeader
	ConnectPayload
	Properties
}

ConnectPacket is the Connect packet.

func (*ConnectPacket) Connack

func (p *ConnectPacket) Connack() *ConnackPacket

Connack returns an ConnackPacket as response to the ConnectPacket.

func (ConnectPacket) PacketType

func (ConnectPacket) PacketType() PacketType

PacketType returns the packet type of the Connect packet.

func (ConnectPacket) Password

func (p ConnectPacket) Password() []byte

Password returns the Password from the packet or nil if it doesn't have one.

func (*ConnectPacket) Reply

func (p *ConnectPacket) Reply() Packet

Reply returns the appropriate reply to this packet.

func (*ConnectPacket) SetPassword

func (p *ConnectPacket) SetPassword(password []byte)

SetPassword sets the Password into the packet if non-nil, or unsets it if nil.

func (*ConnectPacket) SetUsername

func (p *ConnectPacket) SetUsername(username []byte)

SetUsername sets the Username into the packet if non-nil, or unsets it if nil.

func (*ConnectPacket) SetWill

func (p *ConnectPacket) SetWill(properties Properties, topic, message []byte)

SetWill sets the Will into the packet if the topic is non-nil, or unsets it if nil.

func (ConnectPacket) Username

func (p ConnectPacket) Username() []byte

Username returns the Username from the packet or nil if it doesn't have one.

func (*ConnectPacket) Will

func (p *ConnectPacket) Will() (properties Properties, topic, message []byte)

Will returns the Will from the packet or nil if it doesn't have one.

type ConnectPayload

type ConnectPayload struct {
	ClientIdentifier []byte
	WillProperties   Properties
	WillTopic        []byte
	WillMessage      []byte
	Username         []byte
	Password         []byte
}

ConnectPayload is the payload of the Connect packet.

type DisconnectHeader

type DisconnectHeader struct {
	ReasonCode
}

DisconnectHeader is the header of the Disconnect packet.

type DisconnectPacket

type DisconnectPacket struct {
	DisconnectHeader
	Properties
}

DisconnectPacket is the Disconnect packet.

func (DisconnectPacket) PacketType

func (DisconnectPacket) PacketType() PacketType

PacketType returns the packet type of the Disconnect packet.

type FixedHeader

type FixedHeader struct {
	// contains filtered or unexported fields
}

FixedHeader is the fixed header of an MQTT packet.

func (FixedHeader) PacketType

func (h FixedHeader) PacketType() PacketType

PacketType returns the packet type from the fixed header.

func (*FixedHeader) SetPacketType

func (h *FixedHeader) SetPacketType(p PacketType)

SetPacketType sets the packet type into the fixed header.

type Packet

type Packet interface {
	PacketType() PacketType
	// contains filtered or unexported methods
}

Packet interface for MQTT packets from this package.

type PacketReader

type PacketReader struct {
	// contains filtered or unexported fields
}

PacketReader reads MQTT packets.

func NewReader

func NewReader(rd io.Reader, opts ...ReaderOption) *PacketReader

NewReader returns a new Reader on top of the given io.Reader.

func (*PacketReader) ReadPacket

func (r *PacketReader) ReadPacket() (Packet, error)

ReadPacket reads the next packet.

func (*PacketReader) SetProtocol

func (r *PacketReader) SetProtocol(protocol byte)

SetProtocol sets the MQTT protocol version.

type PacketType

type PacketType byte

PacketType is the MQTT packet type.

const (
	CONNECT     PacketType = 1  // Client request to connect to Server
	CONNACK     PacketType = 2  // Connect acknowledgment
	PUBLISH     PacketType = 3  // Publish message
	PUBACK      PacketType = 4  // Publish acknowledgment
	PUBREC      PacketType = 5  // Publish received (assured delivery part 1)
	PUBREL      PacketType = 6  // Publish release (assured delivery part 2)
	PUBCOMP     PacketType = 7  // Publish complete (assured delivery part 3)
	SUBSCRIBE   PacketType = 8  // Subscribe request
	SUBACK      PacketType = 9  // Subscribe acknowledgment
	UNSUBSCRIBE PacketType = 10 // Unsubscribe request
	UNSUBACK    PacketType = 11 // Unsubscribe acknowledgment
	PINGREQ     PacketType = 12 // PING request
	PINGRESP    PacketType = 13 // PING response
	DISCONNECT  PacketType = 14 // Client is disconnecting
	AUTH        PacketType = 15 // Authentication exchange
)

PacketType values.

func (PacketType) String

func (t PacketType) String() string

type PacketWriter

type PacketWriter struct {
	// contains filtered or unexported fields
}

PacketWriter writes MQTT packets.

func NewWriter

func NewWriter(wr io.Writer, opts ...WriterOption) *PacketWriter

NewWriter returns a new Writer on top of the given io.Writer.

func (*PacketWriter) SetProtocol

func (w *PacketWriter) SetProtocol(protocol byte)

SetProtocol sets the MQTT protocol version.

func (*PacketWriter) WritePacket

func (w *PacketWriter) WritePacket(packet Packet) error

WritePacket writes the given packet.

type PingreqPacket

type PingreqPacket struct{}

PingreqPacket is the Pingreq packet.

func (PingreqPacket) PacketType

func (PingreqPacket) PacketType() PacketType

PacketType returns the packet type of the Pingreq packet.

func (*PingreqPacket) Pingresp

func (p *PingreqPacket) Pingresp() *PingrespPacket

Pingresp returns an PingrespPacket as response to the PingreqPacket.

func (*PingreqPacket) Reply

func (p *PingreqPacket) Reply() Packet

Reply returns the appropriate reply to this packet.

type PingrespPacket

type PingrespPacket struct{}

PingrespPacket is the Pingresp packet.

func (PingrespPacket) PacketType

func (PingrespPacket) PacketType() PacketType

PacketType returns the packet type of the Pingresp packet.

type Properties

type Properties []Property

Properties is a slice of MQTT Properties.

type Property

type Property struct {
	Identifier      PropertyIdentifier
	UintValue       uint64 // used for all uints
	BytesValue      []byte // used for bytes and strings
	StringPairValue StringPair
	ByteValue       byte
}

Property is a single MQTT Property

type PropertyIdentifier

type PropertyIdentifier uint64

PropertyIdentifier is the identifier for MQTT properties.

type PubackHeader

type PubackHeader struct {
	PacketIdentifier uint16
	ReasonCode
}

PubackHeader is the header of the Puback packet.

type PubackPacket

type PubackPacket struct {
	PubackHeader
	Properties
}

PubackPacket is the Puback packet.

func (PubackPacket) PacketType

func (PubackPacket) PacketType() PacketType

PacketType returns the packet type of the Puback packet.

type PubcompHeader

type PubcompHeader struct {
	PacketIdentifier uint16
	ReasonCode
}

PubcompHeader is the header of the Pubcomp packet.

type PubcompPacket

type PubcompPacket struct {
	PubcompHeader
	Properties
}

PubcompPacket is the Pubcomp packet.

func (PubcompPacket) PacketType

func (PubcompPacket) PacketType() PacketType

PacketType returns the packet type of the Pubcomp packet.

type PublishFlags

type PublishFlags byte

PublishFlags are the fixed header flags for a Publish packet.

func (PublishFlags) Dup

func (f PublishFlags) Dup() bool

Dup returns the Dup bit from the publish flags.

func (PublishFlags) QoS

func (f PublishFlags) QoS() QoS

QoS returns the QoS from the publish flags.

func (PublishFlags) Retain

func (f PublishFlags) Retain() bool

Retain returns the Retain bit from the publish flags.

func (*PublishFlags) SetDup

func (f *PublishFlags) SetDup(dup bool)

SetDup sets the Dup bit into the publish flags.

func (*PublishFlags) SetQoS

func (f *PublishFlags) SetQoS(qos QoS)

SetQoS sets the QoS into the publish flags.

func (*PublishFlags) SetRetain

func (f *PublishFlags) SetRetain(retain bool)

SetRetain sets the Retain bit into the publish flags.

type PublishHeader

type PublishHeader struct {
	TopicName        []byte
	PacketIdentifier uint16
}

PublishHeader is the header of the Publish packet.

type PublishPacket

type PublishPacket struct {
	PublishFlags
	PublishHeader
	Properties
	PublishPayload []byte
}

PublishPacket is the Publish packet.

func (PublishPacket) PacketType

func (PublishPacket) PacketType() PacketType

PacketType returns the packet type of the Publish packet.

func (*PublishPacket) Puback

func (p *PublishPacket) Puback() *PubackPacket

Puback returns an PubackPacket as response to the PublishPacket.

func (*PublishPacket) Pubrec

func (p *PublishPacket) Pubrec() *PubrecPacket

Pubrec returns an PubrecPacket as response to the PublishPacket.

func (*PublishPacket) Reply

func (p *PublishPacket) Reply() Packet

Reply returns the appropriate reply to this packet. If no reply is needed, nil is returned.

type PubrecHeader

type PubrecHeader struct {
	PacketIdentifier uint16
	ReasonCode
}

PubrecHeader is the header of the Pubrec packet.

type PubrecPacket

type PubrecPacket struct {
	PubrecHeader
	Properties
}

PubrecPacket is the Pubrec packet.

func (PubrecPacket) PacketType

func (PubrecPacket) PacketType() PacketType

PacketType returns the packet type of the Pubrec packet.

func (*PubrecPacket) Pubrel

func (p *PubrecPacket) Pubrel() *PubrelPacket

Pubrel returns an PubrelPacket as response to the PubrecPacket.

func (*PubrecPacket) Reply

func (p *PubrecPacket) Reply() Packet

Reply returns the appropriate reply to this packet.

type PubrelHeader

type PubrelHeader struct {
	PacketIdentifier uint16
	ReasonCode
}

PubrelHeader is the header of the Pubrel packet.

type PubrelPacket

type PubrelPacket struct {
	PubrelHeader
	Properties
}

PubrelPacket is the Pubrel packet.

func (PubrelPacket) PacketType

func (PubrelPacket) PacketType() PacketType

PacketType returns the packet type of the Pubrel packet.

func (*PubrelPacket) Pubcomp

func (p *PubrelPacket) Pubcomp() *PubcompPacket

Pubcomp returns an PubcompPacket as response to the PubrelPacket.

func (*PubrelPacket) Reply

func (p *PubrelPacket) Reply() Packet

Reply returns the appropriate reply to this packet.

type QoS

type QoS byte

QoS is the MQTT quality of service of a Publish packet.

const (
	QoS0 QoS = 0 // At Most Once
	QoS1 QoS = 1 // At Least Once
	QoS2 QoS = 2 // Exactly Once
)

QoS values.

type ReaderOption

type ReaderOption interface {
	// contains filtered or unexported methods
}

ReaderOption is an option for the PacketReader.

func WithMaxPacketLength

func WithMaxPacketLength(bytes uint32) ReaderOption

WithMaxPacketLength returns a ReaderOption that configures a maximum packet length on the Reader.

type ReasonCode

type ReasonCode byte

ReasonCode indicates the result of an operation

const (
	Success                             ReasonCode = 0x00 // Success
	NormalDisconnection                 ReasonCode = 0x00 // Normal disconnection
	GrantedQoS0                         ReasonCode = 0x00 // Granted QoS 0
	GrantedQoS1                         ReasonCode = 0x01 // Granted QoS 1
	GrantedQoS2                         ReasonCode = 0x02 // Granted QoS 2
	DisconnectWithWillMessage           ReasonCode = 0x04 // Disconnect with Will Message
	NoMatchingSubscribers               ReasonCode = 0x10 // No matching subscribers
	NoSubscriptionExisted               ReasonCode = 0x11 // No subscription existed
	ContinueAuthentication              ReasonCode = 0x18 // Continue authentication
	ReAuthenticate                      ReasonCode = 0x19 // Re-authenticate
	UnspecifiedError                    ReasonCode = 0x80 // Unspecified error
	MalformedPacket                     ReasonCode = 0x81 // Malformed Packet
	ProtocolError                       ReasonCode = 0x82 // Protocol Error
	ImplementationSpecificError         ReasonCode = 0x83 // Implementation specific error
	UnsupportedProtocolVersion          ReasonCode = 0x84 // Unsupported Protocol Version
	ClientIdentifierNotValid            ReasonCode = 0x85 // Client Identifier not valid
	BadUsernameOrPassword               ReasonCode = 0x86 // Bad User Name or Password
	NotAuthorized                       ReasonCode = 0x87 // Not authorized
	ServerUnavailable                   ReasonCode = 0x88 // Server unavailable
	ServerBusy                          ReasonCode = 0x89 // Server busy
	Banned                              ReasonCode = 0x8A // Banned
	ServerShuttingDown                  ReasonCode = 0x8B // Server shutting down
	BadAuthenticationMethod             ReasonCode = 0x8C // Bad authentication method
	KeepAliveTimeout                    ReasonCode = 0x8D // Keep Alive timeout
	SessionTakenOver                    ReasonCode = 0x8E // Session taken over
	TopicFilterInvalid                  ReasonCode = 0x8F // Topic Filter invalid
	TopicNameInvalid                    ReasonCode = 0x90 // Topic Name invalid
	PacketIdentifierInUse               ReasonCode = 0x91 // Packet Identifier in use
	PacketIdentifierNotFound            ReasonCode = 0x92 // Packet Identifier not found
	ReceiveMaximumExceeded              ReasonCode = 0x93 // Receive Maximum exceeded
	TopicAliasInvalid                   ReasonCode = 0x94 // Topic Alias invalid
	PacketTooLarge                      ReasonCode = 0x95 // Packet too large
	MessageRateTooHigh                  ReasonCode = 0x96 // Message rate too high
	QuotaExceeded                       ReasonCode = 0x97 // Quota exceeded
	AdministrativeAction                ReasonCode = 0x98 // Administrative action
	PayloadFormatInvalid                ReasonCode = 0x99 // Payload format invalid
	RetainNotSupported                  ReasonCode = 0x9A // Retain not supported
	QoSNotSupported                     ReasonCode = 0x9B // QoS not supported
	UseAnotherServer                    ReasonCode = 0x9C // Use another server
	ServerMoved                         ReasonCode = 0x9D // Server moved
	SharedSubscriptionsNotSupported     ReasonCode = 0x9E // Shared Subscriptions not supported
	ConnectionRateExceeded              ReasonCode = 0x9F // Connection rate exceeded
	MaximumConnectTime                  ReasonCode = 0xA0 // Maximum connect time
	SubscriptionIdentifiersNotSupported ReasonCode = 0xA1 // Subscription Identifiers not supported
	WildcardSubscriptionsNotSupported   ReasonCode = 0xA2 // Wildcard Subscriptions not supported
)

ReasonCode Values.

func (ReasonCode) IsError

func (c ReasonCode) IsError() bool

IsError returns whether the reason code is an error code.

func (ReasonCode) String

func (c ReasonCode) String() string

type StringPair

type StringPair struct {
	Key   []byte
	Value []byte
}

StringPair is a key-value pair of MQTT strings.

func (StringPair) Strings

func (p StringPair) Strings() (key, value string)

Strings returns the key-value pair as strings.

type SubackHeader

type SubackHeader struct {
	PacketIdentifier uint16
}

SubackHeader is the header of the Suback packet.

type SubackPacket

type SubackPacket struct {
	SubackHeader
	Properties
	SubackPayload []ReasonCode
}

SubackPacket is the Suback packet.

func (SubackPacket) PacketType

func (SubackPacket) PacketType() PacketType

PacketType returns the packet type of the Suback packet.

type SubscribeHeader

type SubscribeHeader struct {
	PacketIdentifier uint16
}

SubscribeHeader is the header of the Subscribe packet.

type SubscribePacket

type SubscribePacket struct {
	SubscribeHeader
	Properties
	SubscribePayload []Subscription
}

SubscribePacket is the Subscribe packet.

func (SubscribePacket) PacketType

func (SubscribePacket) PacketType() PacketType

PacketType returns the packet type of the Subscribe packet.

func (*SubscribePacket) Reply

func (p *SubscribePacket) Reply() Packet

Reply returns the appropriate reply to this packet.

func (*SubscribePacket) Suback

func (p *SubscribePacket) Suback() *SubackPacket

Suback returns an SubackPacket as response to the SubscribePacket.

type Subscription

type Subscription struct {
	TopicFilter TopicFilter
	QoS         QoS
}

Subscription is an MQTT subscription.

type TopicFilter

type TopicFilter []byte

TopicFilter is the topic filter for MQTT subscriptions.

type UnsubackHeader

type UnsubackHeader struct {
	PacketIdentifier uint16
}

UnsubackHeader is the header of the Unsuback packet.

type UnsubackPacket

type UnsubackPacket struct {
	UnsubackHeader
	Properties
	UnsubackPayload []ReasonCode
}

UnsubackPacket is the Unsuback packet.

func (UnsubackPacket) PacketType

func (UnsubackPacket) PacketType() PacketType

PacketType returns the packet type of the Unsuback packet.

type UnsubscribeHeader

type UnsubscribeHeader struct {
	PacketIdentifier uint16
}

UnsubscribeHeader is the header of the Unsubscribe packet.

type UnsubscribePacket

type UnsubscribePacket struct {
	UnsubscribeHeader
	Properties
	UnsubscribePayload []TopicFilter
}

UnsubscribePacket is the Unsubscribe packet.

func (UnsubscribePacket) PacketType

func (UnsubscribePacket) PacketType() PacketType

PacketType returns the packet type of the Unsubscribe packet.

func (*UnsubscribePacket) Reply

func (p *UnsubscribePacket) Reply() Packet

Reply returns the appropriate reply to this packet.

func (*UnsubscribePacket) Unsuback

func (p *UnsubscribePacket) Unsuback() *UnsubackPacket

Unsuback returns an UnsubackPacket as response to the UnsubscribePacket.

type WriterOption

type WriterOption interface {
	// contains filtered or unexported methods
}

WriterOption is an option for the PacketWriter.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL