This commit is contained in:
xzb 2023-11-17 14:37:58 +08:00
commit b111bb5cf0
1 changed files with 26 additions and 3 deletions

View File

@ -1,9 +1,13 @@
package mqtt
import (
"fmt"
"log/slog"
"math/rand"
"time"
mqtt "github.com/eclipse/paho.mqtt.golang"
"github.com/google/uuid"
)
// MQTT客户端连接配置
@ -25,11 +29,12 @@ func NewMqttOptions(address, username, password string) MqttOptions {
}
var messagePubHandler mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
slog.Debug("MQTT收到消息", "topic", msg.Topic(), "msg", msg.Payload())
slog.Debug("MQTT收到消息", "topic", msg.Topic(), "msg", string(msg.Payload()))
}
var connectHandler mqtt.OnConnectHandler = func(client mqtt.Client) {
slog.Info("MQTT连接成功")
or := client.OptionsReader()
slog.Info("MQTT连接成功", "ClientID", or.ClientID())
// subs := make(map[string]byte)
// subs["$SYS/brokers/+/clients/+/+"] = 0
// client.SubscribeMultiple(subs, messagePubHandler)
@ -40,11 +45,29 @@ var connectLostHandler mqtt.ConnectionLostHandler = func(client mqtt.Client, err
}
var mqttClient mqtt.Client
var clientId string
// 初始化MQTT客户端id
func initClientId() {
if clientId == "" {
us := uuid.New().String()
usl := len(us)
sufix5 := us[usl-5 : usl]
clientId = fmt.Sprintf("%s%d", sufix5, rand.New(rand.NewSource(time.Now().UnixNano())).Int()%1000)
}
}
// 获取MQTT客户端id
func GetClientId() string {
return clientId
}
// 启动MQTT
func Startup(options MqttOptions) {
initClientId()
opts := mqtt.NewClientOptions()
opts.AddBroker(options.Broker)
// opts.SetClientID("rtsts_service_3.7")
opts.SetClientID(clientId)
opts.SetUsername(options.Username)
opts.SetPassword(options.Password)
opts.SetDefaultPublishHandler(messagePubHandler)