package
1.0.3
Repository: https://github.com/mdzio/go-mqtt.git
Documentation: pkg.go.dev

# README

Package message is an encoder/decoder library for MQTT 3.1 and 3.1.1 messages. You can find the MQTT specs at the following locations:

3.1.1 - http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/ 3.1 - http://public.dhe.ibm.com/software/dw/webservices/ws-mqtt/mqtt-v3r1.html

From the spec:

MQTT is a Client Server publish/subscribe messaging transport protocol. It is light weight, open, simple, and designed so as to be easy to implement. These characteristics make it ideal for use in many situations, including constrained environments such as for communication in Machine to Machine (M2M) and Internet of Things (IoT) contexts where a small code footprint is required and/or network bandwidth is at a premium.

The MQTT protocol works by exchanging a series of MQTT messages in a defined way. The protocol runs over TCP/IP, or over other network protocols that provide ordered, lossless, bi-directional connections.

There are two main items to take note in this package. The first is

	type MessageType byte

MessageType is the type representing the MQTT packet types. In the MQTT spec, MQTT control packet type is represented as a 4-bit unsigned value. MessageType receives several methods that returns string representations of the names and descriptions.

Also, one of the methods is New(). It returns a new Message object based on the mtype parameter. For example:

	m, err := CONNECT.New()
	msg := m.(*ConnectMessage)

This would return a PublishMessage struct, but mapped to the Message interface. You can then type assert it back to a *PublishMessage. Another way to create a new PublishMessage is to call

	msg := NewConnectMessage()

Every message type has a New function that returns a new message. The list of available message types are defined as constants below.

As you may have noticed, the second important item is the Message interface. It defines several methods that are common to all messages, including Name(), Desc(), and Type(). Most importantly, it also defines the Encode() and Decode() methods.

	Encode() (io.Reader, int, error)
	Decode(io.Reader) (int, error)

Encode returns an io.Reader in which the encoded bytes can be read. The second return value is the number of bytes encoded, so the caller knows how many bytes there will be. If Encode returns an error, then the first two return values should be considered invalid. Any changes to the message after Encode() is called will invalidate the io.Reader.

Decode reads from the io.Reader parameter until a full message is decoded, or when io.Reader returns EOF or error. The first return value is the number of bytes read from io.Reader. The second is error if Decode encounters any problems.

With these in mind, we can now do:

	// Create a new CONNECT message
	msg := NewConnectMessage()

	// Set the appropriate parameters
	msg.SetWillQos(1)
	msg.SetVersion(4)
	msg.SetCleanSession(true)
	msg.SetClientId([]byte("surgemq"))
	msg.SetKeepAlive(10)
	msg.SetWillTopic([]byte("will"))
	msg.SetWillMessage([]byte("send me home"))
	msg.SetUsername([]byte("surgemq"))
	msg.SetPassword([]byte("verysecret"))

	// Encode the message and get the io.Reader
	r, n, err := msg.Encode()
	if err == nil {
		return err
	}

	// Write n bytes into the connection
	m, err := io.CopyN(conn, r, int64(n))
	if err != nil {
		return err
	}

	fmt.Printf("Sent %d bytes of %s message", m, msg.Name())

To receive a CONNECT message from a connection, we can do:

	// Create a new CONNECT message
	msg := NewConnectMessage()

	// Decode the message by reading from conn
	n, err := msg.Decode(conn)

If you don't know what type of message is coming down the pipe, you can do something like this:

	// Create a buffered IO reader for the connection
	br := bufio.NewReader(conn)

	// Peek at the first byte, which contains the message type
	b, err := br.Peek(1)
	if err != nil {
		return err
	}

	// Extract the type from the first byte
	t := MessageType(b[0] >> 4)

	// Create a new message
	msg, err := t.New()
	if err != nil {
		return err
	}

	// Decode it from the bufio.Reader
	n, err := msg.Decode(br)
	if err != nil {
		return err
	}

# Functions

NewConnackMessage creates a new CONNACK message.
NewConnectMessage creates a new CONNECT message.
NewDisconnectMessage creates a new DISCONNECT message.
NewPingreqMessage creates a new PINGREQ message.
NewPingrespMessage creates a new PINGRESP message.
NewPubackMessage creates a new PUBACK message.
NewPubcompMessage creates a new PUBCOMP message.
NewPublishMessage creates a new PUBLISH message.
NewPubrecMessage creates a new PUBREC message.
NewPubrelMessage creates a new PUBREL message.
NewSubackMessage creates a new SUBACK message.
NewSubscribeMessage creates a new SUBSCRIBE message.
NewUnsubackMessage creates a new UNSUBACK message.
NewUnsubscribeMessage creates a new UNSUBSCRIBE message.
ValidConnackError checks to see if the error is a Connack Error or not.
ValidQos checks the QoS value to see if it's valid.
ValidTopic checks the topic, which is a slice of bytes, to see if it's valid.
ValidVersion checks to see if the version is valid.

# Constants

CONNACK - Server to Client.
CONNECT - Client to Server.
ConnectionAccepted - Connection accepted.
DISCONNECT - Client to Server.
ErrBadUsernameOrPassword - The data in the user name or password is malformed.
ErrIdentifierRejected - The Client identifier is correct UTF-8 but not allowed by the server.
ErrInvalidProtocolVersion - The Server does not support the level of the MQTT protocol requested by the Client.
ErrNotAuthorized - The Client is not authorized to connect.
ErrServerUnavailable - The Network Connection has been made but the MQTT service is unavailable.
PINGREQ - Client to Server.
PINGRESP - Server to Client.
PUBACK - Client to Server, or Server to Client.
PUBCOMP - Client to Server, or Server to Client.
PUBLISH - Client to Server, or Server to Client.
PUBREC - Client to Server, or Server to Client.
PUBREL - Client to Server, or Server to Client.
QosAtLeastOnce (QoS 1: At least once delivery) This quality of service ensures that the message arrives at the receiver at least once.
QosAtMostOnce (QoS 0: At most once delivery) The message is delivered according to the capabilities of the underlying network.
QosExactlyOnce (QoS 2: Exactly once delivery) This is the highest quality of service, for use when neither loss nor duplication of messages are acceptable.
QosFailure is a return value for a subscription if there's a problem while subscribing to a specific topic.
RESERVED is a reserved value and should be considered an invalid message type.
RESERVED2 is a reserved value and should be considered an invalid message type.
SUBACK - Server to Client.
SUBSCRIBE - Client to Server.
UNSUBACK - Server to Client.
UNSUBSCRIBE - Client to Server.

# Variables

SupportedVersions is a map of the version number (0x3 or 0x4) to the version string, "MQIsdp" for 0x3, and "MQTT" for 0x4.

# Structs

ConnackMessage is the packet sent by the Server in response to a CONNECT Packet received from a Client.
ConnectMessage represents a MQTT connect message.
DisconnectMessage represents a MQTT disconnect message.
PingreqMessage is a PINGREQ packet sent from a Client to the Server.
PingrespMessage is a PINGRESP packet is sent by the Server to the Client in response to a PINGREQ Packet.
PubackMessage is a PUBACK packet, the response to a PUBLISH Packet with QoS level 1.
PubcompMessage is a PUBCOMP packet, the response to a PUBREL Packet.
A PublishMessage (PUBLISH Control Packet) is sent from a Client to a Server or from Server to a Client to transport an Application Message.
PubrecMessage is a PUBREC message.
PubrelMessage is a PUBREL packet, the response to a PUBREC Packet.
SubackMessage ia a SUBACK packet, sent by the Server to the Client to confirm receipt and processing of a SUBSCRIBE Packet.
SubscribeMessage is a SUBSCRIBE packet, sent from the Client to the Server to create one or more Subscriptions.
UnsubackMessage is aUNSUBACK packet, sent by the Server to the Client to confirm receipt of an UNSUBSCRIBE Packet.
UnsubscribeMessage is a UNSUBSCRIBE packet, sent by the Client to the Server, to unsubscribe from topics.

# Interfaces

Message is an interface defined for all MQTT message types.

# Type aliases

ConnackCode is the type representing the return code in the CONNACK message, returned after the initial CONNECT message.
Type is the type representing the MQTT packet types.