mosquitto改mqtt

This commit is contained in:
suguo.yao 2023-02-28 11:23:15 +08:00
parent 1ba9b3ab0a
commit ccdcfc4ebc
3 changed files with 10 additions and 8 deletions

View File

@ -1,7 +1,8 @@
package mosquitto
package mqtt
type Config struct {
Host string
Username string
Password string
ClientID string
}

View File

@ -1,4 +1,4 @@
package mosquitto
package mqtt
import (
"fmt"
@ -17,7 +17,7 @@ var connLostHandler MQTT.ConnectionLostHandler = func(client MQTT.Client, err er
fmt.Println(err.Error())
}
//具体业务订阅的处理,此处为示例
// 具体业务订阅的处理,此处为示例
var serviceHandler MQTT.MessageHandler = func(client MQTT.Client, msg MQTT.Message) {
fmt.Println(msg.Topic())
}

View File

@ -1,4 +1,4 @@
package mosquitto
package mqtt
import (
"encoding/json"
@ -26,6 +26,7 @@ func Options() *MQTT.ClientOptions {
opts.AddBroker(config.Host)
opts.Username = config.Username
opts.Password = config.Password
opts.ClientID = config.ClientID
return opts
}
@ -44,7 +45,7 @@ func New() (MQTT.Client, error) {
return clientDistribute, nil
}
//订阅当事件为nil时可获取client
// 订阅当事件为nil时可获取client
func Subscribe(connHandler MQTT.OnConnectHandler, lostHandler MQTT.ConnectionLostHandler) error {
if connHandler == nil {
return errors.New("handler is nil")
@ -69,7 +70,7 @@ func Subscribe(connHandler MQTT.OnConnectHandler, lostHandler MQTT.ConnectionLos
return nil
}
//取消订阅
// 取消订阅
func UnSubscribe(topic string) {
if clientSubscribe == nil {
return
@ -79,7 +80,7 @@ func UnSubscribe(topic string) {
c.Disconnect(250)
}
//分发
// 分发
func Distribute(topic *string, qos int, retained bool, payload *[]byte) error {
c, err := New()
if err != nil {
@ -93,7 +94,7 @@ func Distribute(topic *string, qos int, retained bool, payload *[]byte) error {
return nil
}
//分发Object
// 分发Object
func DistributeObject(topic *string, qos int, retained bool, obj interface{}) error {
payload, err := json.Marshal(obj)
if err != nil {