jl-iot/mqtt/config.go

62 lines
1.8 KiB
Go

package mqtt
import (
"fmt"
"log/slog"
"net/url"
"time"
"github.com/eclipse/paho.golang/autopaho"
"github.com/eclipse/paho.golang/paho"
)
type ClientManageConfig struct {
BrokerUrl string // Broker地址
ClientId string // 客户端ID
Username string // 用户名
Password string // 密码
KeepAlive uint16 // 保活时间间隔,单位s,默认为60
ConnectRetryDelay uint16 // 连接重试延时,单位s,默认为3
ConnectTimeout uint16 // 连接操作超时,单位s,默认为3
OnConnectionUp func(*autopaho.ConnectionManager, *paho.Connack)
}
func (c *ClientManageConfig) tryInto() (*autopaho.ClientConfig, error) {
addr, err := url.Parse(c.BrokerUrl)
if err != nil {
return nil, fmt.Errorf("Mqtt.Address格式错误, %s: %w", c.BrokerUrl, err)
}
if c.KeepAlive == 0 {
c.KeepAlive = 60
}
if c.ConnectRetryDelay == 0 {
c.ConnectRetryDelay = 3
}
if c.ConnectTimeout == 0 {
c.ConnectTimeout = 3
}
cc := &autopaho.ClientConfig{
BrokerUrls: []*url.URL{
addr,
},
KeepAlive: c.KeepAlive,
ConnectRetryDelay: time.Duration(c.ConnectRetryDelay) * time.Second,
ConnectTimeout: time.Duration(c.ConnectTimeout) * time.Second,
OnConnectionUp: c.OnConnectionUp,
OnConnectError: func(err error) {
slog.Error("MQTT连接失败", "error", err)
},
ClientConfig: paho.ClientConfig{
ClientID: c.ClientId,
Router: paho.NewStandardRouter(),
OnClientError: func(err error) { fmt.Printf("%s Mqtt客户端发生错误: %s\n", c.ClientId, err) },
OnServerDisconnect: func(d *paho.Disconnect) {
fmt.Printf("%s 连接断开; reason code: %d,properties: %v\n", c.ClientId, d.ReasonCode, d.Properties)
},
},
}
cc.SetUsernamePassword(c.Username, []byte(c.Password))
cc.SetWillMessage(GetIotServiceStateTopic(), []byte("离线"), 1, true)
return cc, nil
}