English Documentation: https://godoc.org/github.com/eclipse/paho.mqtt.golang
github: https://github.com/eclipse/paho.mqtt.golang
Constants
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 name of debug output
Variables
ErrInvalidQos is an error returned when the Qos value for sending a package is invalid
var ErrInvalidTopicEmptyString = errors.New("Invalid Topic; empty string")
ErrInvalidTopicEmptyString is an error returned when passing a 0-length theme string
var ErrInvalidTopicMultilevel = errors.New("Invalid Topic; multi-level wildcard must be last level")
ErrInvalidTopicMultilevel is an error returned when passing a theme string that has a multilevel wildcard anywhere but the last position
ErrNotConnected is an error returned by a function call executed when the client is not connected to the proxy
func DefaultConnectionLostHandler
func DefaultConnectionLostHandler(client Client, reason error)
DefaultConnectionLostHandler is the definition of a function that simply reports to the debug log the reason the client lost its connection.
type Client
// Determine if the connection was successful IsConnected() bool // Determine if you are connected to an agent IsConnectionOpen() bool // Create a connection to the message agent, and if it fails, reconnect x times by default Connect() Token // Disconnect after waiting for specified milliseconds and for existing work to complete Disconnect(quiesce uint) // Publish a message with a specific Qos identity and content to a specific topic and return a Token to track how the message is delivered to the agent Publish(topic string, qos byte, retained bool, payload interface{}) Token // Subscribe to a topic that executes a message handler when it has messages and defaults if it is nil Subscribe(topic string, qos byte, callback MessageHandler) Token // You can subscribe to multiple topics, and when one of them comes to a message, execute the message handler, or default if it is empty SubscribeMultiple(filters map[string] byte, callback MessageHandler) Token // Unsubscribe will end receiving messages from other client s Unsubscribe(topics ...string) Token // Allow adding a message handler to a topic without a subscription AddRoute(topic string, callback MessageHandler) // Returns an option on the client side being used OptionsReader() ClientOptionsReader }
Client is the interface definition of the client used by this library, which is mainly used to allow impersonation tests.Applications can connect to MQTT servers using the following methods:
A plain TCP socket
A secure SSL/TLS socket
A websocket
To ensure message delivery at the quality of service level described in the MQTT specification, a message persistence mechanism must be used.This is achieved by providing a type that implements the Store interface.For convenience, the implementations provided by FileStore and MooryStore should be sufficient for most use cases.More information can be found in their respective documents.Many connection options can be specified by configuring a and then providing the ClientOptions type.
func NewClient
func NewClient(o *ClientOptions) Client
NewClient will create an MQTT client using all the options specified in the ClientOptions provided.Clients must call the Connect method before using it.This is to ensure that resources (such as network connections) are created before the application is actually ready.
type ClientOptions
type ClientOptions struct { Servers []*url.URL ClientID string Username string Password string CredentialsProvider CredentialsProvider CleanSession bool Order bool WillEnabled bool WillTopic string WillPayload []byte WillQos byte WillRetained bool ProtocolVersion uint TLSConfig *tls.Config KeepAlive int64 PingTimeout time.Duration ConnectTimeout time.Duration MaxReconnectInterval time.Duration AutoReconnect bool Store Store DefaultPublishHandler MessageHandler OnConnect OnConnectHandler OnConnectionLost ConnectionLostHandler WriteTimeout time.Duration MessageChannelDepth uint ResumeSubs bool HTTPHeaders http.Header // contains filtered or unexported fields }
ClientOptions contains configurable options for the client.
func NewClientOptions
func NewClientOptions() *ClientOptions
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 the proxy URI to the list of proxies to use.The format should be scheme://host:port Where scheme is one of "tcp", "ssl" or "ws", "host" is the ip address (or host name), "port" is the port on which the agent accepts connections.The default is tcp://127.0.0.1
func (*ClientOptions) SetAutoReconnect
func (o *ClientOptions) SetAutoReconnect(a bool) *ClientOptions</pre>
SetAutoReconnect sets whether automatic reconnection logic should be used when a connection is lost, even if ConnectionLostHandler is disabled
func (*ClientOptions) SetBinaryWill
func (o *ClientOptions) SetBinaryWill(topic string, payload []byte, qos byte, retained bool) *ClientOptions
SetBinaryWill accepts a will message of [] bytes to be set.When the client connects, it sends this will message to the proxy, which publishes the provided payload (will) to any client that subscribes to the provided topic.
func (*ClientOptions) SetCleanSession
func (o *ClientOptions) SetCleanSession(clean bool) *ClientOptions
Set the clear session flag. When the clear flag is set, the proxy will not store the message you send and will forward it directly to the corresponding topic
func (*ClientOptions) SetClientID
func (o *ClientOptions) SetClientID(id string) *ClientOptions
SetClientID sets the client id to be used by the client when connecting to the MQTT proxy.According to the MQTT specification, the client id must not exceed 23 characters.
func (*ClientOptions) SetConnectTimeout
func (o *ClientOptions) SetConnectTimeout(t time.Duration) *ClientOptions/pre>
SetConnectTimeout limits the amount of time a client waits to attempt to open a connection to an MQTT server before timing out and attempting incorrectly.The duration of 0 will not time out.Default 30 seconds.Currently it can only run on TCP/TLS connections.
func (*ClientOptions) SetConnectionLostHandler
func (o *ClientOptions) SetConnectionLostHandler(onLost ConnectionLostHandler) *ClientOptions</pre>
SetConnectionLostHandler sets the OnConnectionLost callback function to execute when the client unexpectedly loses its connection to the MQTT proxy.
func (*ClientOptions) SetCredentialsProvider
func (o *ClientOptions) SetCredentialsProvider(p CredentialsProvider) *ClientOptions
SetCredentialsProvider sets the method that this client will invoke when connecting to the MQTT proxy that provides the current user name and password.Note: If you do not use SSL/TLS, this information will be sent over the network in clear text.
func (*ClientOptions) SetDefaultPublishHandler
func (o *ClientOptions) SetDefaultPublishHandler(defaultHandler MessageHandler) *ClientOptions
SetDefaultPublishHandler sets the MesageHandler to be called when a message is received that does not match any known subscription.
func (*ClientOptions) SetHTTPHeaders
func (o *ClientOptions) SetHTTPHeaders(h http.Header) *ClientOptions
SetHTTPHeaders sets the additional HTTP headers that will be sent in the WebSocket open handshake.
func (*ClientOptions) SetKeepAlive
func (o *ClientOptions) SetKeepAlive(k time.Duration) *ClientOptions
SetKeepAlive sets the amount of time (in seconds) a client should wait before sending a PING request to the proxy.This will allow the client to know that the connection to the server has not been lost.
func (*ClientOptions) SetMaxReconnectInterval
func (o *ClientOptions) SetMaxReconnectInterval(t time.Duration) *ClientOptions
SetMaxReconnectInterval sets the maximum time to wait between reconnect attempts when a connection is lost
func (*ClientOptions) SetMessageChannelDepth
func (o *ClientOptions) SetMessageChannelDepth(s uint) *ClientOptions
SetMessageChannelDepth sets the size of the internal queue that holds messages when the client is temporarily offline, allowing applications to publish messages when the client reconnects.This setting is only valid if AutoReconnect is set to true, otherwise it will be ignored.
func (*ClientOptions) SetOnConnectHandler
func (o *ClientOptions) SetOnConnectHandler(onConn OnConnectHandler) *ClientOptions
SetOnConnectHandler sets the function to be called when the client connects.Whether it's during initial connection or during automatic reconnection.
func (*ClientOptions) SetOrderMatters
func (o *ClientOptions) SetOrderMatters(order bool) *ClientOptions
SetOrderMatters will set up message routing to ensure order in 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 that errors may occur.
func (*ClientOptions) SetPassword
func (o *ClientOptions) SetPassword(p string) *ClientOptions
SetPassword will set the password used by this client when connecting to the MQTT proxy.Note: If you do not use SSL/TLS, this information will be sent over the network in clear text.
func (*ClientOptions) SetPingTimeout
func (o *ClientOptions) SetPingTimeout(k time.Duration) *ClientOptions
SetPingTimeout sets the time (in seconds) that the client waits after sending a PING request to the proxy before deciding whether the connection has been lost.The default is 10 seconds.
func (*ClientOptions) SetProtocolVersion
func (o *ClientOptions) SetProtocolVersion(pv uint) *ClientOptions
SetProtocolVersion sets the MQTT version used to connect to the proxy.The current legal value is 3 - MQTT 3.1 or 4 - MQTT 3.1.1
func (*ClientOptions) SetResumeSubs
func (o *ClientOptions) SetResumeSubs(resume bool) *ClientOptions
SetResumeSubs will enable recovery of stored (un) subscription messages on connection, but will not reconnect if CleanSession is false.Otherwise, these messages will be discarded.
func (*ClientOptions) SetStore
func (o *ClientOptions) SetStore(s Store) *ClientOptions
SetStore will set the implementation of the Store interface that provides message persistence when using the QoS level qos_1 or qos_2.If no storage is provided, the client will use MemoryStore by default.
func (*ClientOptions) SetTLSConfig
func (o *ClientOptions) SetTLSConfig(t *tls.Config) *ClientOptions<
Set up the SSL/TLS configuration to use when connecting to the MQTT proxy.
func (*ClientOptions) SetUsername
func (o *ClientOptions) SetUsername(u string) *ClientOptions
SetUsername will set the user name this client uses when connecting to the MQTT proxy.Note: If you do not use SSL/TLS, this information will be sent over the network in clear text.
func (*ClientOptions) SetWill
func (o *ClientOptions) SetWill(topic string, payload string, qos byte, retained bool) *ClientOptions<
SetWill accepts a string will message that will be set.When the client connects, it sends this will message to the proxy, which publishes the provided payload to any client subscribed to the topic provided.
func (*ClientOptions) SetWriteTimeout
func (o *ClientOptions) SetWriteTimeout(t time.Duration) *ClientOptions
SetWriteTimeout limits how long an mqtt publication should block until it releases the block with a timeout error.The duration of 0 will not time out.Default 30 seconds
func (*ClientOptions) UnsetWill
func (o *ClientOptions) UnsetWill() *ClientOptions
UnsetWill will cause any set will messages to be ignored.
type ClientOptionsReader
type ClientOptionsReader struct {
// contains filtered or unexported fields
}
ClientOptionsReader provides an interface for reading ClientOptions after initializing the client.
func (*ClientOptionsReader) AutoReconnect
func (r *ClientOptionsReader) AutoReconnect() bool
func (*ClientOptionsReader) CleanSession
func (r *ClientOptionsReader) CleanSession() bool
func (*ClientOptionsReader) ClientID
func (r *ClientOptionsReader) ClientID() string
func (*ClientOptionsReader) ConnectTimeout
func (r *ClientOptionsReader) ConnectTimeout() time.Duration
func (*ClientOptionsReader) HTTPHeaders
func (r *ClientOptionsReader) HTTPHeaders() http.Header
func (*ClientOptionsReader) KeepAlive
func (r *ClientOptionsReader) KeepAlive() time.Duration
func (*ClientOptionsReader) MaxReconnectInterval
func (r *ClientOptionsReader) MaxReconnectInterval() time.Duration
func (*ClientOptionsReader) MessageChannelDepth
func (r *ClientOptionsReader) MessageChannelDepth() uint
func (*ClientOptionsReader) Order
func (r *ClientOptionsReader) Order() bool
func (*ClientOptionsReader) Password
func (r *ClientOptionsReader) Password() string
func (*ClientOptionsReader) PingTimeout
func (r *ClientOptionsReader) PingTimeout() time.Duration
func (*ClientOptionsReader) ProtocolVersion
func (r *ClientOptionsReader) ProtocolVersion() uint
func (*ClientOptionsReader) ResumeSubs
func (r *ClientOptionsReader) ResumeSubs() bool
ResumeSubs returns true if restore storage (un)sub is enabled
func (*ClientOptionsReader) Servers
func (r ClientOptionsReader) Servers() []url.URL
Servers returns part of the server defined in clientoptions
func (*ClientOptionsReader) TLSConfig
func (r *ClientOptionsReader) TLSConfig() *tls.Config
func (*ClientOptionsReader) Username
func (r *ClientOptionsReader) Username() string
func (*ClientOptionsReader) WillEnabled
func (r *ClientOptionsReader) WillEnabled() bool
func (*ClientOptionsReader) WillPayload
func (r *ClientOptionsReader) WillPayload() []byte
func (*ClientOptionsReader) WillQos
func (r *ClientOptionsReader) WillQos() byte
func (*ClientOptionsReader) WillRetained
func (r *ClientOptionsReader) WillRetained() bool
func (*ClientOptionsReader) WillTopic
func (r *ClientOptionsReader) WillTopic() string
func (*ClientOptionsReader) WriteTimeout
func (r *ClientOptionsReader) WriteTimeout() time.Duration
type ConnectToken
type ConnectToken struct {
// contains filtered or unexported fields
}
onnectToken is a token extension that contains additional fields required to provide information about a Connect() call
func (*ConnectToken) Error
func (b *ConnectToken) Error() error
func (*ConnectToken) ReturnCode
func (c *ConnectToken) ReturnCode() byte
ReturnCode returns acknowlegement code from connack sent in response to Connect()
func (*ConnectToken) SessionPresent
func (c *ConnectToken) SessionPresent() bool
SessionPresent returns a bool representing the value of the session presentation field in the connack that responds to a Connect()
func (*ConnectToken) Wait
func (b *ConnectToken) Wait() bool
Wait will wait indefinitely for the token to complete (send the publication from the proxy and confirm the receipt)
func (*ConnectToken) WaitTimeout
Wait timeout takes time.The duration to wait for the stream associated with the token to complete, returning true if it returns true before the time-out, and false if the time-out occurs.In case of timeout, the token is not set incorrectly in case the caller wants to wait again
type ConnectionLostHandler
ConnectionLostHandler is a callback type that can be set to execute when an accidental disconnect from the MQTT proxy occurs.Disconnect or ForceDisconnect calls that result in a disconnect do not result in the OnConnectionLost callback being executed.
type CredentialsProvider
type CredentialsProvider func() (username string, password string)
CredentialsProvider allows updating user names and passwords before reconnecting.It should return the current user name and password.
type DisconnectToken
type DisconnectToken struct {
// contains filtered or unexported fields
}
DisconnectToken is an extension of the token that contains additional fields required to provide information about calling 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 (send the publication from the proxy and confirm the receipt)
func (*DisconnectToken) WaitTimeout
WaitTimeout takes a time.Duration 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 DummyToken
type DummyToken struct {
// contains filtered or unexported fields
}
func (*DummyToken) Error
func (d *DummyToken) Error() error
func (*DummyToken) Wait
func (d *DummyToken) Wait() bool
func (*DummyToken) WaitTimeout
func (d *DummyToken) WaitTimeout(t time.Duration) bool
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
NewFileStore will create a new FileStore, which will be stored in the directory provided.
func (*FileStore) All
All provides a list of all keys associated with messages currently residing in the file store.
func (*FileStore) Close
func (store *FileStore) Close()
Closing will not allow file storage.
func (*FileStore) Del
Del deletes persistent messages associated with the provided key from the file store.
func (*FileStore) Get
func (store *FileStore) Get(key string) packets.ControlPacket
Get retrieves the message associated with the supplied key value from the store.
func (*FileStore) Open
func (store *FileStore) Open()
Opening will allow the use of file storage.
func (*FileStore) Put
func (store *FileStore) Put(key string, m packets.ControlPacket)
Put puts a message into the store associated with the key value provided.
func (*FileStore) Reset
func (store *FileStore) Reset()
Reset deletes all persistent messages from the file store.
type Logger
type Logger interface {
Println(v ...interface{})
Printf(format string, v ...interface{})
}
The Logger interface allows the implementation to provide any object that implements the methods defined in this package.
var (
ERROR Logger = NOOPLogger{}
CRITICAL Logger = NOOPLogger{}
WARN Logger = NOOPLogger{}
DEBUG Logger = NOOPLogger{}
)
Internal level of Library output, initialized to print nothing but can be overridden by programmers
type MId
type MId uint16
MId is the 16-bit message id specified by the MQTT specification.In general, client applications should not rely on these values.
type MemoryStore
type MemoryStore struct {
sync.RWMutex
// contains filtered or unexported fields
}
MemoryStore implements the store interface to provide a "persistence" mechanism that is fully stored in memory.This is only useful if the client instance exists.
func NewMemoryStore
func NewMemoryStore() *MemoryStore
NewMemoryStore returns a pointer to a new instance of MemoryStore that will not be initialized and ready to use until Open() is called.
func (*MemoryStore) All
func (store *MemoryStore) All() []string
All returns a string fragment containing all the keys currently in memory storage.
func (*MemoryStore) Close
func (store *MemoryStore) Close()
Close will not allow modifications to the stored state.
func (*MemoryStore) Del
func (store *MemoryStore) Del(key string)
Del accepts a key and searches for MemoryStore, and if it is found, deletes the message pointer associated with it.
func (*MemoryStore) Get
func (store *MemoryStore) Get(key string) packets.ControlPacket
Get accepts a key and looks for a matching message in the store, either returning the message pointer or returning nil.
func (*MemoryStore) Open
func (store *MemoryStore) Open()
Open initializes the MemoryStore instance.
func (*MemoryStore) Put
func (store *MemoryStore) Put(key string, message packets.ControlPacket)<
Put accepts keys and pointers to messages and stores them.
func (*MemoryStore) Reset
func (store *MemoryStore) Reset()
Reset eliminates all persistent message data in the store.
type Message
type Message interface {
Duplicate() bool
Qos() byte
Retained() bool
Topic() string
MessageID() uint16
Payload() []byte
Ack()
}
Message defines the exteriors that message implementations must support, which are receiving messages passed to callbacks, not internal messages
type MessageHandler
MessageHandler is a callback type that can be set to execute when messages published to topics subscribed to by clients arrive.
type NOOPLogger
type NOOPLogger struct{}
NOOPLogger implements a logger that does nothing by default.This allows us to effectively discard unwanted messages.
func (NOOPLogger) Printf
func (NOOPLogger) Printf(format string, v ...interface{})
func (NOOPLogger) Println
func (NOOPLogger) Println(v ...interface{})
type OnConnectHandler
type OnConnectHandler func(Client)
OnConnectHandler is a callback function that is invoked when the client state changes from disconnected/disconnected to connected.Whether on initial or reconnect
type PacketAndToken
type PacketAndToken struct {
// contains filtered or unexported fields
}
PacketAndToken is a structure that contains both a control package and a token.This structure is passed through the channel 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 the token, which contains information about Publish()Additional fields required for information invoked
func (*PublishToken) Error
func (b *PublishToken) Error() error
func (*PublishToken) MessageID
func (p *PublishToken) MessageID() uint16
MessageID returns the MQTT message ID assigned to the publishing package when sent to the agent
func (*PublishToken) Wait
func (b *PublishToken) Wait() bool
Wait will wait indefinitely for the token to complete (send the publication from the proxy and confirm the receipt)
func (*PublishToken) WaitTimeout
Wait timeout takes time.The duration to wait for the stream associated with the token to complete, returning true if it returns true before the time-out, and false if the time-out occurs.In case of timeout, the token is not set incorrectly in case the caller wants to wait again
type Store
type Store interface {
Open()
Put(key string, message packets.ControlPacket)
Get(key string) packets.ControlPacket
All() []string
Del(key string)
Close()
Reset()
}
Store is an interface that can be used to provide an implementation of message persistence.Because we may have to store different messages using the same message ID, we need to provide a unique key for each message.This can be achieved by prefixing each message ID with "i." or "o."
type SubscribeToken
type SubscribeToken struct {
// contains filtered or unexported fields
}
SubscribeToken is an extension of the token that contains additional fields required to provide information about the Subscribe() call
func (*SubscribeToken) Error
func (b *SubscribeToken) Error() error</pre>
func (*SubscribeToken) Result
func (s *SubscribeToken) Result() map[string]byte
Result returns a map of the subscribed topic and a matching return code from the proxy.This is either the Qos value of the subscription or the error code.
func (*SubscribeToken) Wait
func (b *SubscribeToken) Wait() bool
Wait will wait indefinitely for the token to complete (send the publication from the proxy and confirm the receipt)
func (*SubscribeToken) WaitTimeout
Wait timeout takes time.The duration to wait for the stream associated with the token to complete, returning true if it returns true before the time-out, and false if the time-out occurs.In case of timeout, the token is not set incorrectly in case the caller wants to wait again
type Token
type Token interface {
Wait() bool
WaitTimeout(time.Duration) bool
Error() error
}
A token defines an interface for a token that indicates when an operation is completed.
type TokenErrorSetter
type TokenErrorSetter interface {
// contains filtered or unexported methods
}
type UnsubscribeToken
type UnsubscribeToken struct {
// contains filtered or unexported fields
}
UnsubscribeToken is an extension of a token that contains additional fields required to provide information about calling 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 (send the publication from the proxy and confirm the receipt)
func (*UnsubscribeToken) WaitTimeout
func (b *UnsubscribeToken) WaitTimeout(d time.Duration) bool
Wait timeout takes time.The duration to wait for the stream associated with the token to complete, returning true if it returns true before the time-out, and false if the time-out occurs.In case of timeout, the token is not set incorrectly in case the caller wants to wait again