GO之MQTT使用中文文档

英文文档: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]   "
)

调试输出的组件名称

Variables

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

ErrInvalidQos是当发送一个包的Qos值无效时返回的错误

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

ErrInvalidTopicEmptyString是传递长度为0的主题字符串时返回的错误

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

ErrInvalidTopicMultilevel是传递主题字符串时返回的错误,该字符串除最后一个位置外的任何位置都有多级通配符

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

ErrNotConnected是在客户机未连接到代理时执行的函数调用返回的错误

func DefaultConnectionLostHandler

func DefaultConnectionLostHandler(client Client, reason error)

DefaultConnectionLostHandler是一个函数的定义,它只是向调试日志报告客户机丢失连接的原因。

type Client

    // 判断是否连接成功
    IsConnected() bool

    // 判断是否与代理处于连接状态
    IsConnectionOpen() bool

    // 创建一个连接到消息代理,如果失败,默认会重连x次
    Connect() Token

    // 等待指定的毫秒数以及等待现有工作完成之后,断开连接
    Disconnect(quiesce uint)

    // 发布一个带特定Qos标识和内容的消息给一个特定topic,返回一个Token用于跟踪消息传递到代理的情况
    Publish(topic string, qos byte, retained bool, payload interface{}) Token

    // 订阅一个主题,当这个主题有消息时,执行消息处理函数,如果为nil则进行默认处理
    Subscribe(topic string, qos byte, callback MessageHandler) Token

    // 可订阅多个主题,当其中一个主题来消息时,执行消息处理函数,如果为空则进行默认处理
    SubscribeMultiple(filters map[string] byte, callback MessageHandler) Token

    // 取消订阅将会结束接收从别的client发行过来的消息
    Unsubscribe(topics ...string) Token

    // 允许为一个没有订阅的topic添加一个消息处理函数
    AddRoute(topic string, callback MessageHandler)

    // 返回一个正在使用的client端的选项
    OptionsReader() ClientOptionsReader
}

客户端是这个库使用的客户端的接口定义,该接口主要用于允许模拟测试。应用程序可以使用以下方法连接到MQTT服务器:

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

要在MQTT规范中描述的服务质量级别上确保消息交付,必须使用消息持久性机制。这是通过提供一个实现Store接口的类型来实现的。为了方便起见,FileStore和MemoryStore提供的实现应该足以满足大多数用例。更多信息可以在他们各自的文档中找到。可以通过配置a然后提供ClientOptions类型来指定许多连接选项。

func NewClient

func NewClient(o *ClientOptions) Client

NewClient将使用提供的ClientOptions中指定的所有选项创建MQTT客户端。客户端必须在使用Connect方法之前调用该方法。这是为了确保在应用程序实际准备好之前创建资源(比如网络连接)。

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包含客户机的可配置选项。

func NewClientOptions

func NewClientOptions() *ClientOptions

创建一个带有一些默认值的新ClientClientOptions类型。

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将代理URI添加到要使用的代理列表中。格式应该是scheme://host:port,其中“scheme”是“tcp”、“ssl”或“ws”之一,“host”是ip地址(或主机名),“port”是代理接受连接的端口。默认是tcp://127.0.0.1

func (*ClientOptions) SetAutoReconnect

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

SetAutoReconnect设置当连接丢失时是否应该使用自动重连接逻辑,即使禁用了ConnectionLostHandler仍然被调用

func (*ClientOptions) SetBinaryWill

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

SetBinaryWill接受一个将要设置的[]字节的will消息。当客户端连接时,它将把这个will消息发送给代理,代理将把所提供的有效负载(will)发布给订阅了所提供主题的任何客户端。

func (*ClientOptions) SetCleanSession

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

设置清除session标志,当设置清除标志时,代理不会存储你发送的消息,将会直接转发给对应的topic

func (*ClientOptions) SetClientID

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

SetClientID将设置客户机id,以便在连接到MQTT代理时由该客户机使用。根据MQTT 规范,客户机id必须不超过23个字符。

func (*ClientOptions) SetConnectTimeout

func (o *ClientOptions) SetConnectTimeout(t time.Duration) *ClientOptions/pre>

SetConnectTimeout限制了客户机在超时并错误尝试之前尝试打开到MQTT服务器的连接时等待的时间。0的持续时间不会超时。默认30秒。目前只能在TCP/TLS连接上运行。

func (*ClientOptions) SetConnectionLostHandler

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

SetConnectionLostHandler将设置OnConnectionLost回调函数,以便在客户机意外丢失与MQTT代理的连接时执行。

func (*ClientOptions) SetCredentialsProvider

func (o *ClientOptions) SetCredentialsProvider(p CredentialsProvider) *ClientOptions

SetCredentialsProvider将设置此客户机在连接到提供当前用户名和密码的MQTT代理时要调用的方法。注意:如果不使用SSL/TLS,此信息将以明文形式通过网络发送。

func (*ClientOptions) SetDefaultPublishHandler

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

SetDefaultPublishHandler设置当接收到不匹配任何已知订阅的消息时将调用的MessageHandler。

func (*ClientOptions) SetHTTPHeaders

func (o *ClientOptions) SetHTTPHeaders(h http.Header) *ClientOptions

SetHTTPHeaders设置将在WebSocket打开握手中发送的附加HTTP头。

func (*ClientOptions) SetKeepAlive

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

SetKeepAlive将设置客户机在向代理发送PING请求之前应该等待的时间(以秒为单位)。这将允许客户端知道与服务器的连接没有丢失。

func (*ClientOptions) SetMaxReconnectInterval

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

SetMaxReconnectInterval设置连接丢失时,在重新连接尝试之间等待的最大时间

func (*ClientOptions) SetMessageChannelDepth

func (o *ClientOptions) SetMessageChannelDepth(s uint) *ClientOptions

SetMessageChannelDepth设置在客户端暂时脱机时保存消息的内部队列的大小,允许应用程序在客户端重新连接时发布消息。此设置仅在AutoReconnect设置为true时有效,否则将忽略该设置。

func (*ClientOptions) SetOnConnectHandler

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

SetOnConnectHandler设置客户机连接时要调用的函数。无论是在初始连接时还是在自动重新连接时。

func (*ClientOptions) SetOrderMatters

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

SetOrderMatters将设置消息路由以保证每个QoS级别中的顺序。默认情况下,该值为true。如果设置为false,则此标志指示消息可以异步地从客户机传递到应用程序,并且可能出现错误。

func (*ClientOptions) SetPassword

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

SetPassword将设置此客户机在连接到MQTT代理时使用的密码。注意:如果不使用SSL/TLS,此信息将以明文形式通过网络发送。

func (*ClientOptions) SetPingTimeout

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

SetPingTimeout将设置客户机在向代理发送PING请求之后等待的时间(以秒为单位),然后再决定连接是否已经丢失。默认为10秒。

func (*ClientOptions) SetProtocolVersion

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

SetProtocolVersion设置用于连接到代理的MQTT版本。当前合法值为3 - MQTT 3.1或4 - MQTT 3.1.1

func (*ClientOptions) SetResumeSubs

func (o *ClientOptions) SetResumeSubs(resume bool) *ClientOptions

SetResumeSubs将在连接时启用已存储(un)订阅消息的恢复功能,但如果CleanSession为false,则不会重新连接。否则这些消息将被丢弃。

func (*ClientOptions) SetStore

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

SetStore将设置用于在使用QoS级别qos_1或qos_2的情况下提供消息持久性的Store接口的实现。如果没有提供存储,那么客户端将默认使用MemoryStore。

func (*ClientOptions) SetTLSConfig

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

设置SSL/TLS配置,以便在连接到MQTT代理时使用。

func (*ClientOptions) SetUsername

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

SetUsername将设置此客户机在连接到MQTT代理时使用的用户名。注意:如果不使用SSL/TLS,此信息将以明文形式通过网络发送。

func (*ClientOptions) SetWill

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

SetWill接受一个将要设置的字符串will消息。当客户端连接时,它将把这个will消息发送给代理,代理将把提供的有效负载(will)发布给订阅了提供主题的任何客户端。

func (*ClientOptions) SetWriteTimeout

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

SetWriteTimeout限制mqtt发布应该阻塞多长时间,直到它释放带有超时错误的阻塞为止。0的持续时间不会超时。默认30秒

func (*ClientOptions) UnsetWill

func (o *ClientOptions) UnsetWill() *ClientOptions

UnsetWill将导致任何set will消息被忽略。

type ClientOptionsReader

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

ClientOptionsReader提供了一个接口,用于在初始化客户机之后读取ClientOptions。

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返回true,如果已启用了restore stored (un)sub

func (*ClientOptionsReader) Servers

func (r ClientOptionsReader) Servers() []url.URL

Servers返回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是令牌的扩展,包含提供关于Connect()调用的信息所需的额外字段

func (*ConnectToken) Error

func (b *ConnectToken) Error() error

func (*ConnectToken) ReturnCode

func (c *ConnectToken) ReturnCode() byte

ReturnCode返回响应Connect()而发送的connack中的acknowlegement代码

func (*ConnectToken) SessionPresent

func (c *ConnectToken) SessionPresent() bool

SessionPresent返回一个bool,表示响应Connect()发送的connack中会话present字段的值

func (*ConnectToken) Wait

func (b *ConnectToken) Wait() bool

Wait将无限期地等待令牌完成(从代理发送发布并确认收据)

func (*ConnectToken) WaitTimeout

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

等待超时需要时间。等待与令牌关联的流完成的持续时间,如果在超时之前返回true,则返回true;如果超时发生,则返回false。在超时的情况下,令牌不会设置错误,以防调用者希望再次等待

type ConnectionLostHandler

type ConnectionLostHandler func(Client, error)

ConnectionLostHandler是一种回调类型,可以将其设置为在意外断开与MQTT代理的连接时执行。调用Disconnect或ForceDisconnect导致的断开不会导致执行OnConnectionLost回调。

type CredentialsProvider

type CredentialsProvider func() (username string, password string)

CredentialsProvider允许在重新连接之前更新用户名和密码。它应该返回当前用户名和密码。

type DisconnectToken

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

DisconnectToken是令牌的扩展,包含提供有关调用Disconnect()的信息所需的额外字段

func (*DisconnectToken) Error

func (b *DisconnectToken) Error() error

func (*DisconnectToken) Wait

func (b *DisconnectToken) Wait() bool

Wait将无限期地等待令牌完成(从代理发送发布并确认收据)

func (*DisconnectToken) WaitTimeout

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

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

func NewFileStore(directory string) *FileStore

NewFileStore将创建一个新的FileStore,该文件存储在提供的目录中。

func (*FileStore) All

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

All将提供与当前驻留在文件存储中的消息相关联的所有键的列表。

func (*FileStore) Close

func (store *FileStore) Close()

关闭将不允许使用文件存储。

func (*FileStore) Del

func (store *FileStore) Del(key string)

Del将从文件存储中删除与提供的密钥相关联的持久消息。

func (*FileStore) Get

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

Get将从存储中检索与提供的键值相关联的消息。

func (*FileStore) Open

func (store *FileStore) Open()

打开将允许使用文件存储。

func (*FileStore) Put

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

Put将向存储中放入一条与所提供的键值相关联的消息。

func (*FileStore) Reset

func (store *FileStore) Reset()

重置将从文件存储中删除所有持久性消息。

type Logger

type Logger interface {
Println(v ...interface{})
Printf(format string, v ...interface{})
}

Logger接口允许实现向这个包提供任何实现其中定义的方法的对象。

var (
ERROR Logger = NOOPLogger{}
CRITICAL Logger = NOOPLogger{}
WARN Logger = NOOPLogger{}
DEBUG Logger = NOOPLogger{}
)

库输出的内部级别,初始化为不打印任何内容,但可以由程序员重写

type MId

type MId uint16

MId是MQTT规范指定的16位消息id。通常,客户机应用程序不应该依赖这些值。

type MemoryStore

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

MemoryStore实现了store接口,以提供完全存储在内存中的“持久性”机制。这只在客户机实例存在时才有用。

func NewMemoryStore

func NewMemoryStore() *MemoryStore

NewMemoryStore返回指向MemoryStore新实例的指针,在调用Open()之前不会初始化该实例并准备使用它。

func (*MemoryStore) All

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

All返回一个字符串片段,其中包含内存存储中当前的所有键。

func (*MemoryStore) Close

func (store *MemoryStore) Close()

Close将不允许修改存储的状态。

func (*MemoryStore) Del

func (store *MemoryStore) Del(key string)

Del接受一个键,搜索MemoryStore,如果找到该键,则删除与其关联的消息指针。

func (*MemoryStore) Get

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

Get接受一个键并在存储中查找匹配的消息,该消息要么返回消息指针,要么返回nil。

func (*MemoryStore) Open

func (store *MemoryStore) Open()

Open初始化MemoryStore实例。

func (*MemoryStore) Put

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

Put接受指向消息的键和指针,并存储消息。

func (*MemoryStore) Reset

func (store *MemoryStore) Reset()

重置消除存储中的所有持久消息数据。

type Message

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

Message定义了消息实现必须支持的外部,这些外部是传递给回调的接收消息,而不是内部消息

type MessageHandler

type MessageHandler func(Client, Message)

MessageHandler是一种回调类型,可以将其设置为在发布到客户端订阅的主题的消息到达时执行。

type NOOPLogger

type NOOPLogger struct{}

NOOPLogger实现了默认情况下不执行任何操作的日志记录器。这允许我们有效地丢弃不需要的消息。

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是一个回调函数,当客户机状态从未连接/断开连接更改为已连接时,将调用该回调函数。无论是在初始连接还是在重新连接时

type PacketAndToken

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

PacketAndToken是一个结构体,它同时包含一个控制包和一个令牌。这个结构通过客户机接口代码和负责发送和接收MQTT消息的底层代码之间的通道传递。

type PublishToken

type PublishToken struct {
// contains filtered or unexported fields
}
PublishToken是令牌的扩展,包含提供关于Publish()调用的信息所需的额外字段

func (*PublishToken) Error

func (b *PublishToken) Error() error

func (*PublishToken) MessageID

func (p *PublishToken) MessageID() uint16

MessageID返回发送给代理时分配给发布包的MQTT消息ID

func (*PublishToken) Wait

func (b *PublishToken) Wait() bool

Wait将无限期地等待令牌完成(从代理发送发布并确认收据)

func (*PublishToken) WaitTimeout

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

等待超时需要时间。等待与令牌关联的流完成的持续时间,如果在超时之前返回true,则返回true;如果超时发生,则返回false。在超时的情况下,令牌不会设置错误,以防调用者希望再次等待

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是一个接口,可用于提供消息持久性的实现。因为我们可能必须使用相同的消息ID存储不同的消息,所以我们需要为每个消息提供一个惟一的密钥。这可以通过在每个消息id前加上“i.”或“o.”来实现

type SubscribeToken

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

SubscribeToken是令牌的扩展,包含提供关于Subscribe()调用的信息所需的额外字段

func (*SubscribeToken) Error

func (b *SubscribeToken) Error() error

func (*SubscribeToken) Result

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

Result返回已订阅主题的映射,以及来自代理的匹配返回代码。这要么是订阅的Qos值,要么是错误代码。

func (*SubscribeToken) Wait

func (b *SubscribeToken) Wait() bool

Wait将无限期地等待令牌完成(从代理发送发布并确认收据)

func (*SubscribeToken) WaitTimeout

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

等待超时需要时间。等待与令牌关联的流完成的持续时间,如果在超时之前返回true,则返回true;如果超时发生,则返回false。在超时的情况下,令牌不会设置错误,以防调用者希望再次等待

type Token

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

令牌定义用于指示操作何时完成的令牌的接口。

type TokenErrorSetter

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

type UnsubscribeToken

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

UnsubscribeToken是令牌的扩展,包含提供有关调用Unsubscribe()的信息所需的额外字段

func (*UnsubscribeToken) Error

func (b *UnsubscribeToken) Error() error

func (*UnsubscribeToken) Wait

func (b *UnsubscribeToken) Wait() bool

Wait将无限期地等待令牌完成(从代理发送发布并确认收据)

func (*UnsubscribeToken) WaitTimeout

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

等待超时需要时间。等待与令牌关联的流完成的持续时间,如果在超时之前返回true,则返回true;如果超时发生,则返回false。在超时的情况下,令牌不会设置错误,以防调用者希望再次等待

你可能感兴趣的:(GO之MQTT使用中文文档)