mqtt

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Apr 16, 2020 License: MIT Imports: 7 Imported by: 0

README

mqtt

Latest Tag

管理MQTT的连接,以及消息的订阅。

安装
go get -u github.com/lwhu2015/gomqtt
使用
// 初始化MQTT
func initMQTT() {
	// 消息订阅
	for _, sub := range SubTopics {
		gomqtt.Subscribe(gomqtt.SubscribeType{Topic: sub.Topic, Qos: 0, Callback: sub.CallBack, RetryTimes: 0})
	}
	// MQTT配置
	opts := gomqtt.GetClientOptions(&gomqtt.Config{
		Broker:   g.Cfg().GetString("mqtt.broker"),
		Username: g.Cfg().GetString("mqtt.username"),
		Password: g.Cfg().GetString("mqtt.password"),
		CACert:   g.Cfg().GetString("mqtt.cacert"),
		ClientID: guuid.New().String(),
	})

	opts.SetOnConnectHandler(func(client mqtt.Client) {
		glog.Info("MQTT OnConnect.")
	}) // 设置自定义的连接后处理方法
	opts.SetConnectionLostHandler(func(client mqtt.Client, error error) {
		glog.Info("MQTT ConnectionLost.")
	}) // 设置自定义的断开连接后处理方法
	if err := gomqtt.Init(opts); err != nil {
		glog.Fatal("MQTT initialization failed.")
	} else {
		glog.Info("MQTT initialized successfully.")
	}
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetClient

func GetClient(opts *gomqtt.ClientOptions) (client gomqtt.Client, err error)

获取MQTT连接

func GetClientOptions

func GetClientOptions(conf *Config) *gomqtt.ClientOptions

获取MQTT连接配置项

func Init

func Init(opts *gomqtt.ClientOptions) (err error)

初始化监听器

func Publish

func Publish(topic string, payload interface{}, qos byte, retained bool) (err error)

通用发布消息接口

func Subscribe

func Subscribe(item SubscribeType)

注册订阅消息

Types

type Config

type Config struct {
	Broker     string // Broker地址,例如tcp://127.0.0.1:1883或ssl://127.0.0.1:8883. 如果配置ssl,则必须配置CACert
	Username   string // 用户名,可选
	Password   string // 密码,可选
	CACert     string // CA证书,单向认证只需要配置此文件即可,无需ClientCert和ClientKey,可选
	ClientCert string // ClientCert,可选
	ClientKey  string // ClientKey,可选
	ClientID   string // ClientID,可选
}

MQTT的配置信息格式

type SubscribeType

type SubscribeType struct {
	Topic      string
	Qos        byte
	Callback   gomqtt.MessageHandler
	RetryTimes int // 为0表示无限重试
}

Jump to

Keyboard shortcuts

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