From 5aafa486251c5c2ee365f9d4db88b7693c55c960 Mon Sep 17 00:00:00 2001 From: walker Date: Fri, 17 Nov 2023 14:12:37 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0MQTT=E5=AE=A2=E6=88=B7?= =?UTF-8?q?=E7=AB=AFid=E7=94=9F=E6=88=90(uuid=E5=90=8E5=E4=BD=8D=E5=8A=A01?= =?UTF-8?q?-3=E4=BD=8D=E9=9A=8F=E6=9C=BA=E6=95=B0)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- mqtt/client.go | 29 ++++++++++++++++++++++++++--- 1 file changed, 26 insertions(+), 3 deletions(-) diff --git a/mqtt/client.go b/mqtt/client.go index be53c20..aab695a 100644 --- a/mqtt/client.go +++ b/mqtt/client.go @@ -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)