mqtt

package
v0.2.3 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2015 License: EPL-1.0, MIT Imports: 18 Imported by: 0

README

Eclipse Paho MQTT Go client

This repository contains the source code for the Eclipse Paho MQTT Go client library.

This code builds a library which enable applications to connect to an MQTT broker to publish messages, and to subscribe to topics and receive published messages.

This library supports a fully asynchronous mode of operation.

Installation and Build

This client is designed to work with the standard Go tools, so installation is as easy as:

go get git.eclipse.org/gitroot/paho/org.eclipse.paho.mqtt.golang.git

The client depends on Google's websockets package, also easily installed with the command:

go get code.google.com/p/go.net/websocket

Usage and API

Detailed API documentation is available by using to godoc tool, or can be browsed online using the godoc.org service.

Make use of the library by importing it in your Go client source code. For example,

import MQTT "git.eclipse.org/gitroot/paho/org.eclipse.paho.mqtt.golang.git"

Samples are available in the /samples directory for reference.

Runtime tracing

Tracing is enabled by assigning logs (from the Go log package) to the logging endpoints, ERROR, CRITICAL, WARN and DEBUG

Reporting bugs

Please report bugs under the "MQTT-Go" Component in Eclipse Bugzilla for the Paho Technology project. This is a very new library as of Q1 2014, so there are sure to be bugs.

More information

Discussion of the Paho clients takes place on the Eclipse paho-dev mailing list.

General questions about the MQTT protocol are discussed in the MQTT Google Group.

There is much more information available via the MQTT community site.

Documentation

Overview

Package mqtt provides an MQTT v3.1.1 client library.

Index

Constants

View Source
const (
	NET component = "[net]     "
	PNG component = "[pinger]  "
	CLI component = "[client]  "
	DEC component = "[decode]  "
	MES component = "[message] "
	STR component = "[store]   "
	MID component = "[msgids]  "
	TST component = "[test]    "
	STA component = "[state]   "
	ERR component = "[error]   "
)

Component names for debug output

Variables

View Source
var (
	ERROR    *log.Logger
	CRITICAL *log.Logger
	WARN     *log.Logger
	DEBUG    *log.Logger
)

Internal levels of library output that are initialised to not print anything but can be overridden by programmer

View Source
var ErrInvalidQos = errors.New("Invalid QoS")

InvalidQos is the error returned when an packet is to be sent with an invalid Qos value

View Source
var ErrInvalidTopicEmptyString = errors.New("Invalid Topic; empty string")

InvalidTopicEmptyString is the error returned when a topic string is passed in that is 0 length

View Source
var ErrInvalidTopicMultilevel = errors.New("Invalid Topic; multi-level wildcard must be last level")

InvalidTopicMultilevel is the error returned when a topic string is passed in that has the multi level wildcard in any position but the last

View Source
var ErrNotConnected = errors.New("Not Connected")

ErrNotConnected is the error returned from function calls that are made when the client is not connected to a broker

Functions

func DefaultConnectionLostHandler

func DefaultConnectionLostHandler(client *Client, reason error)

DefaultConnectionLostHandler is a definition of a function that simply reports to the DEBUG log the reason for the client losing a connection.

Types

type Client

type Client struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

Client is an MQTT v3.1.1 client for communicating with an MQTT server using non-blocking methods that allow work to be done in the background. An application may connect to an MQTT server using:

A plain TCP socket
A secure SSL/TLS socket
A websocket

To enable ensured message delivery at Quality of Service (QoS) levels described in the MQTT spec, a message persistence mechanism must be used. This is done by providing a type which implements the Store interface. For convenience, FileStore and MemoryStore are provided implementations that should be sufficient for most use cases. More information can be found in their respective documentation. Numerous connection options may be specified by configuring a and then supplying a ClientOptions type.

func NewClient

func NewClient(o *ClientOptions) *Client

NewClient will create an MQTT v3.1.1 client with all of the options specified in the provided ClientOptions. The client must have the Start method called on it before it may be used. This is to make sure resources (such as a net connection) are created before the application is actually ready.

func (*Client) Connect

func (c *Client) Connect() Token

Connect will create a connection to the message broker If clean session is false, then a slice will be returned containing Receipts for all messages that were in-flight at the last disconnect. If clean session is true, then any existing client state will be removed.

func (*Client) Disconnect

func (c *Client) Disconnect(quiesce uint)

Disconnect will end the connection with the server, but not before waiting the specified number of milliseconds to wait for existing work to be completed.

func (*Client) IsConnected

func (c *Client) IsConnected() bool

IsConnected returns a bool signifying whether the client is connected or not.

func (*Client) Publish

func (c *Client) Publish(topic string, qos byte, retained bool, payload interface{}) Token

Publish will publish a message with the specified QoS and content to the specified topic. Returns a read only channel used to track the delivery of the message.

func (*Client) Subscribe

func (c *Client) Subscribe(topic string, qos byte, callback MessageHandler) Token

Subscribe starts a new subscription. Provide a MessageHandler to be executed when a message is published on the topic provided.

func (*Client) SubscribeMultiple

func (c *Client) SubscribeMultiple(filters map[string]byte, callback MessageHandler) Token

SubscribeMultiple starts a new subscription for multiple topics. Provide a MessageHandler to be executed when a message is published on one of the topics provided.

func (*Client) Unsubscribe

func (c *Client) Unsubscribe(topics ...string) Token

Unsubscribe will end the subscription from each of the topics provided. Messages published to those topics from other clients will no longer be received.

type ClientInt

type ClientInt interface {
	IsConnected() bool
	Connect() Token
	Disconnect(uint)

	Publish(string, byte, bool, interface{}) Token
	Subscribe(string, byte, MessageHandler) Token
	SubscribeMultiple(map[string]byte, MessageHandler) Token
	Unsubscribe(...string) Token
	// contains filtered or unexported methods
}

ClientInt is the interface definition for a Client as used by this library, the interface is primarily to allow mocking tests.

type ClientOptions

type ClientOptions struct {
	Servers         []*url.URL
	ClientID        string
	Username        string
	Password        string
	CleanSession    bool
	Order           bool
	WillEnabled     bool
	WillTopic       string
	WillPayload     []byte
	WillQos         byte
	WillRetained    bool
	ProtocolVersion uint

	TLSConfig            tls.Config
	KeepAlive            time.Duration
	ConnectTimeout       time.Duration
	MaxReconnectInterval time.Duration
	AutoReconnect        bool
	Store                Store
	DefaultPublishHander MessageHandler
	OnConnect            OnConnectHandler
	OnConnectionLost     ConnectionLostHandler
	WriteTimeout         time.Duration
	// contains filtered or unexported fields
}

ClientOptions contains configurable options for an Client.

func NewClientOptions

func NewClientOptions() *ClientOptions

NewClientOptions will create a new ClientClientOptions type with some default values.

Port: 1883
CleanSession: True
Order: True
KeepAlive: 30 (seconds)
ConnectTimeout: 30 (seconds)
MaxReconnectInterval 10 (minutes)
AutoReconnect: True

func (*ClientOptions) AddBroker

func (o *ClientOptions) AddBroker(server string) *ClientOptions

AddBroker adds a broker URI to the list of brokers to be used. The format should be scheme://host:port Where "scheme" is one of "tcp", "ssl", or "ws", "host" is the ip-address (or hostname) and "port" is the port on which the broker is accepting connections.

func (*ClientOptions) SetAutoReconnect

func (o *ClientOptions) SetAutoReconnect(a bool) *ClientOptions

SetAutoReconnect sets whether the automatic reconnection logic should be used when the connection is lost, even if disabled the ConnectionLostHandler is still called

func (*ClientOptions) SetBinaryWill

func (o *ClientOptions) SetBinaryWill(topic string, payload []byte, qos byte, retained bool) *ClientOptions

SetBinaryWill accepts a []byte will message to be set. When the client connects, it will give this will message to the broker, which will then publish the provided payload (the will) to any clients that are subscribed to the provided topic.

func (*ClientOptions) SetCleanSession

func (o *ClientOptions) SetCleanSession(clean bool) *ClientOptions

SetCleanSession will set the "clean session" flag in the connect message when this client connects to an MQTT broker. By setting this flag, you are indicating that no messages saved by the broker for this client should be delivered. Any messages that were going to be sent by this client before diconnecting previously but didn't will not be sent upon connecting to the broker.

func (*ClientOptions) SetClientID

func (o *ClientOptions) SetClientID(id string) *ClientOptions

SetClientID will set the client id to be used by this client when connecting to the MQTT broker. According to the MQTT v3.1 specification, a client id mus be no longer than 23 characters.

func (*ClientOptions) SetConnectTimeout

func (o *ClientOptions) SetConnectTimeout(t time.Duration) *ClientOptions

SetConnectTimeout limits how long the client will wait when trying to open a connection to an MQTT server before timeing out and erroring the attempt. A duration of 0 never times out. Default 30 seconds. Currently only operational on TCP/TLS connections.

func (*ClientOptions) SetConnectionLostHandler

func (o *ClientOptions) SetConnectionLostHandler(onLost ConnectionLostHandler) *ClientOptions

SetConnectionLostHandler will set the OnConnectionLost callback to be executed in the case where the client unexpectedly loses connection with the MQTT broker.

func (*ClientOptions) SetDefaultPublishHandler

func (o *ClientOptions) SetDefaultPublishHandler(defaultHandler MessageHandler) *ClientOptions

SetDefaultPublishHandler sets the MessageHandler that will be called when a message is received that does not match any known subscriptions.

func (*ClientOptions) SetKeepAlive

func (o *ClientOptions) SetKeepAlive(k time.Duration) *ClientOptions

SetKeepAlive will set the amount of time (in seconds) that the client should wait before sending a PING request to the broker. This will allow the client to know that a connection has not been lost with the server.

func (*ClientOptions) SetMaxReconnectInterval

func (o *ClientOptions) SetMaxReconnectInterval(t time.Duration) *ClientOptions

SetMaxReconnectInterval sets the maximum time that will be waited between reconnection attempts when connection is lost

func (*ClientOptions) SetOnConnectHandler

func (o *ClientOptions) SetOnConnectHandler(onConn OnConnectHandler) *ClientOptions

SetOnConnectHandler sets the function to be called when the client is connected. Both at initial connection time and upon automatic reconnect.

func (*ClientOptions) SetOrderMatters

func (o *ClientOptions) SetOrderMatters(order bool) *ClientOptions

SetOrderMatters will set the message routing to guarantee order within each QoS level. By default, this value is true. If set to false, this flag indicates that messages can be delivered asynchronously from the client to the application and possibly arrive out of order.

func (*ClientOptions) SetPassword

func (o *ClientOptions) SetPassword(p string) *ClientOptions

SetPassword will set the password to be used by this client when connecting to the MQTT broker. Note: without the use of SSL/TLS, this information will be sent in plaintext accross the wire.

func (*ClientOptions) SetProtocolVersion

func (o *ClientOptions) SetProtocolVersion(pv uint) *ClientOptions

SetProtocolVersion sets the MQTT version to be used to connect to the broker. Legitimate values are currently 3 - MQTT 3.1 or 4 - MQTT 3.1.1

func (*ClientOptions) SetStore

func (o *ClientOptions) SetStore(s Store) *ClientOptions

SetStore will set the implementation of the Store interface used to provide message persistence in cases where QoS levels QoS_ONE or QoS_TWO are used. If no store is provided, then the client will use MemoryStore by default.

func (*ClientOptions) SetTLSConfig

func (o *ClientOptions) SetTLSConfig(t *tls.Config) *ClientOptions

SetTLSConfig will set an SSL/TLS configuration to be used when connecting to an MQTT broker. Please read the official Go documentation for more information.

func (*ClientOptions) SetUsername

func (o *ClientOptions) SetUsername(u string) *ClientOptions

SetUsername will set the username to be used by this client when connecting to the MQTT broker. Note: without the use of SSL/TLS, this information will be sent in plaintext accross the wire.

func (*ClientOptions) SetWill

func (o *ClientOptions) SetWill(topic string, payload string, qos byte, retained bool) *ClientOptions

SetWill accepts a string will message to be set. When the client connects, it will give this will message to the broker, which will then publish the provided payload (the will) to any clients that are subscribed to the provided topic.

func (*ClientOptions) SetWriteTimeout

func (o *ClientOptions) SetWriteTimeout(t time.Duration) *ClientOptions

SetWriteTimeout puts a limit on how long a mqtt publish should block until it unblocks with a timeout error. A duration of 0 never times out. Default 30 seconds

func (*ClientOptions) UnsetWill

func (o *ClientOptions) UnsetWill() *ClientOptions

UnsetWill will cause any set will message to be disregarded.

type ConnectToken

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

ConnectToken is an extension of Token containing the extra fields required to provide information about calls to Connect()

func (*ConnectToken) Error

func (b *ConnectToken) Error() error

func (*ConnectToken) ReturnCode

func (c *ConnectToken) ReturnCode() byte

ReturnCode returns the acknowlegement code in the connack sent in response to a Connect()

func (*ConnectToken) Wait

func (b *ConnectToken) Wait() bool

Wait will wait indefinitely for the Token to complete, ie the Publish to be sent and confirmed receipt from the broker

func (*ConnectToken) WaitTimeout

func (b *ConnectToken) WaitTimeout(d time.Duration) bool

WaitTimeout takes a time in ms to wait for the flow associated with the Token to complete, returns true if it returned before the timeout or returns false if the timeout occurred. In the case of a timeout the Token does not have an error set in case the caller wishes to wait again

type ConnectionLostHandler

type ConnectionLostHandler func(*Client, error)

ConnectionLostHandler is a callback type which can be set to be executed upon an unintended disconnection from the MQTT broker. Disconnects caused by calling Disconnect or ForceDisconnect will not cause an OnConnectionLost callback to execute.

type DisconnectToken

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

DisconnectToken is an extension of Token containing the extra fields required to provide information about calls to Disconnect()

func (*DisconnectToken) Error

func (b *DisconnectToken) Error() error

func (*DisconnectToken) Wait

func (b *DisconnectToken) Wait() bool

Wait will wait indefinitely for the Token to complete, ie the Publish to be sent and confirmed receipt from the broker

func (*DisconnectToken) WaitTimeout

func (b *DisconnectToken) WaitTimeout(d time.Duration) bool

WaitTimeout takes a time in ms to wait for the flow associated with the Token to complete, returns true if it returned before the timeout or returns false if the timeout occurred. In the case of a timeout the Token does not have an error set in case the caller wishes to wait again

type FileStore

type FileStore struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

FileStore implements the store interface using the filesystem to provide true persistence, even across client failure. This is designed to use a single directory per running client. If you are running multiple clients on the same filesystem, you will need to be careful to specify unique store directories for each.

func NewFileStore

func NewFileStore(directory string) *FileStore

NewFileStore will create a new FileStore which stores its messages in the directory provided.

func (*FileStore) All

func (store *FileStore) All() []string

All will provide a list of all of the keys associated with messages currenly residing in the FileStore.

func (*FileStore) Close

func (store *FileStore) Close()

Close will disallow the FileStore from being used.

func (*FileStore) Del

func (store *FileStore) Del(key string)

Del will remove the persisted message associated with the provided key from the FileStore.

func (*FileStore) Get

func (store *FileStore) Get(key string) packets.ControlPacket

Get will retrieve a message from the store, the one associated with the provided key value.

func (*FileStore) Open

func (store *FileStore) Open()

Open will allow the FileStore to be used.

func (*FileStore) Put

func (store *FileStore) Put(key string, m packets.ControlPacket)

Put will put a message into the store, associated with the provided key value.

func (*FileStore) Reset

func (store *FileStore) Reset()

Reset will remove all persisted messages from the FileStore.

type MId

type MId uint16

MId is 16 bit message id as specified by the MQTT spec. In general, these values should not be depended upon by the client application.

type MemoryStore

type MemoryStore struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

MemoryStore implements the store interface to provide a "persistence" mechanism wholly stored in memory. This is only useful for as long as the client instance exists.

func NewMemoryStore

func NewMemoryStore() *MemoryStore

NewMemoryStore returns a pointer to a new instance of MemoryStore, the instance is not initialized and ready to use until Open() has been called on it.

func (*MemoryStore) All

func (store *MemoryStore) All() []string

All returns a slice of strings containing all the keys currently in the MemoryStore.

func (*MemoryStore) Close

func (store *MemoryStore) Close()

Close will disallow modifications to the state of the store.

func (*MemoryStore) Del

func (store *MemoryStore) Del(key string)

Del takes a key, searches the MemoryStore and if the key is found deletes the Message pointer associated with it.

func (*MemoryStore) Get

func (store *MemoryStore) Get(key string) packets.ControlPacket

Get takes a key and looks in the store for a matching Message returning either the Message pointer or nil.

func (*MemoryStore) Open

func (store *MemoryStore) Open()

Open initializes a MemoryStore instance.

func (*MemoryStore) Put

func (store *MemoryStore) Put(key string, message packets.ControlPacket)

Put takes a key and a pointer to a Message and stores the message.

func (*MemoryStore) Reset

func (store *MemoryStore) Reset()

Reset eliminates all persisted message data in the store.

type Message

type Message interface {
	Duplicate() bool
	Qos() byte
	Retained() bool
	Topic() string
	MessageID() uint16
	Payload() []byte
}

Message defines the externals that a message implementation must support these are received messages that are passed to the callbacks, not internal messages

type MessageHandler

type MessageHandler func(*Client, Message)

MessageHandler is a callback type which can be set to be executed upon the arrival of messages published to topics to which the client is subscribed.

type OnConnectHandler

type OnConnectHandler func(*Client)

OnConnectHandler is a callback that is called when the client state changes from unconnected/disconnected to connected. Both at initial connection and on reconnection

type PacketAndToken

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

PacketAndToken is a struct that contains both a ControlPacket and a Token. This struct is passed via channels between the client interface code and the underlying code responsible for sending and receiving MQTT messages.

type PublishToken

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

PublishToken is an extension of Token containing the extra fields required to provide information about calls to Publish()

func (*PublishToken) Error

func (b *PublishToken) Error() error

func (*PublishToken) MessageID

func (p *PublishToken) MessageID() uint16

MessageID returns the MQTT message ID that was assigned to the Publish packet when it was sent to the broker

func (*PublishToken) Wait

func (b *PublishToken) Wait() bool

Wait will wait indefinitely for the Token to complete, ie the Publish to be sent and confirmed receipt from the broker

func (*PublishToken) WaitTimeout

func (b *PublishToken) WaitTimeout(d time.Duration) bool

WaitTimeout takes a time in ms to wait for the flow associated with the Token to complete, returns true if it returned before the timeout or returns false if the timeout occurred. In the case of a timeout the Token does not have an error set in case the caller wishes to wait again

type Store

type Store interface {
	Open()
	Put(string, packets.ControlPacket)
	Get(string) packets.ControlPacket
	All() []string
	Del(string)
	Close()
	Reset()
}

Store is an interface which can be used to provide implementations for message persistence. Because we may have to store distinct messages with the same message ID, we need a unique key for each message. This is possible by prepending "i." or "o." to each message id

type SubscribeToken

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

SubscribeToken is an extension of Token containing the extra fields required to provide information about calls to Subscribe()

func (*SubscribeToken) Error

func (b *SubscribeToken) Error() error

func (*SubscribeToken) Result

func (s *SubscribeToken) Result() map[string]byte

Result returns a map of topics that were subscribed to along with the matching return code from the broker. This is either the Qos value of the subscription or an error code.

func (*SubscribeToken) Wait

func (b *SubscribeToken) Wait() bool

Wait will wait indefinitely for the Token to complete, ie the Publish to be sent and confirmed receipt from the broker

func (*SubscribeToken) WaitTimeout

func (b *SubscribeToken) WaitTimeout(d time.Duration) bool

WaitTimeout takes a time in ms to wait for the flow associated with the Token to complete, returns true if it returned before the timeout or returns false if the timeout occurred. In the case of a timeout the Token does not have an error set in case the caller wishes to wait again

type Token

type Token interface {
	Wait() bool
	WaitTimeout(time.Duration) bool

	Error() error
	// contains filtered or unexported methods
}

Token defines the interface for the tokens used to indicate when actions have completed.

type UnsubscribeToken

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

UnsubscribeToken is an extension of Token containing the extra fields required to provide information about calls to Unsubscribe()

func (*UnsubscribeToken) Error

func (b *UnsubscribeToken) Error() error

func (*UnsubscribeToken) Wait

func (b *UnsubscribeToken) Wait() bool

Wait will wait indefinitely for the Token to complete, ie the Publish to be sent and confirmed receipt from the broker

func (*UnsubscribeToken) WaitTimeout

func (b *UnsubscribeToken) WaitTimeout(d time.Duration) bool

WaitTimeout takes a time in ms to wait for the flow associated with the Token to complete, returns true if it returned before the timeout or returns false if the timeout occurred. In the case of a timeout the Token does not have an error set in case the caller wishes to wait again

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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