gomqtt

package module
v1.0.5 Latest Latest
Warning

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

Go to latest
Published: Jul 4, 2021 License: MIT Imports: 9 Imported by: 0

README

mqtt

Latest Tag

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

安装
go get -u gitee.com/welinks/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.")
	})
	if err := gomqtt.Init(opts); err != nil {
		glog.Fatal("MQTT initialization failed.")
	} else {
		glog.Info("MQTT initialized successfully.")
	}
}

Documentation

Overview

* @Description : * @Date : 2020-04-16 11:35:43 * @LastEditors : Hu * @LastEditTime : 2021-07-04 11:58:40 * @FilePath : \gomqtt\publisher.go

* @Description : * @Date : 2020-04-16 11:35:43 * @LastEditors : Hu * @LastEditTime : 2021-07-04 11:52:25 * @FilePath : \gomqtt\status_changed.go

* @Description : * @Date : 2020-04-16 11:35:43 * @LastEditors : Hu * @LastEditTime : 2021-07-04 11:50:45 * @FilePath : \gomqtt\subscriber.go

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetClient

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

获取MQTT连接

func GetClientOptions

func GetClientOptions(conf *Config) *mqtt.ClientOptions

获取MQTT连接配置项

func Init

func Init(opts *mqtt.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   mqtt.MessageHandler
	RetryTimes int // 为0表示无限重试
}

Jump to

Keyboard shortcuts

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