2023-12-15 18:08:06 +08:00
|
|
|
package mqtt
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"log/slog"
|
|
|
|
"net/url"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/eclipse/paho.golang/autopaho"
|
|
|
|
"github.com/eclipse/paho.golang/paho"
|
|
|
|
)
|
|
|
|
|
2023-12-18 15:34:10 +08:00
|
|
|
type IotMqttConfig struct {
|
|
|
|
AppId string // 所属应用编号
|
2023-12-15 18:08:06 +08:00
|
|
|
BrokerUrl string // Broker地址
|
|
|
|
ClientId string // 客户端ID
|
|
|
|
Username string // 用户名
|
|
|
|
Password string // 密码
|
|
|
|
KeepAlive uint16 // 保活时间间隔,单位s,默认为60
|
|
|
|
ConnectRetryDelay uint16 // 连接重试延时,单位s,默认为3
|
|
|
|
ConnectTimeout uint16 // 连接操作超时,单位s,默认为3
|
|
|
|
}
|
|
|
|
|
2023-12-18 15:34:10 +08:00
|
|
|
func (c *IotMqttConfig) tryInto() (*autopaho.ClientConfig, error) {
|
2023-12-15 18:08:06 +08:00
|
|
|
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,
|
2023-12-18 15:34:10 +08:00
|
|
|
OnConnectionUp: func(*autopaho.ConnectionManager, *paho.Connack) {
|
2023-12-21 17:13:05 +08:00
|
|
|
slog.Info("MQTT连接成功", "url", c.BrokerUrl)
|
2023-12-18 15:34:10 +08:00
|
|
|
subIotQc()
|
|
|
|
},
|
2023-12-15 18:08:06 +08:00
|
|
|
OnConnectError: func(err error) {
|
2023-12-21 17:13:05 +08:00
|
|
|
slog.Error("MQTT连接失败", "url", c.BrokerUrl, "error", err)
|
2023-12-15 18:08:06 +08:00
|
|
|
},
|
|
|
|
ClientConfig: paho.ClientConfig{
|
|
|
|
ClientID: c.ClientId,
|
|
|
|
Router: paho.NewStandardRouter(),
|
2023-12-21 17:13:05 +08:00
|
|
|
OnClientError: func(err error) { slog.Error("MQTT客户端发生错误", "clientId", c.ClientId, "err", err) },
|
2023-12-15 18:08:06 +08:00
|
|
|
OnServerDisconnect: func(d *paho.Disconnect) {
|
2023-12-21 17:13:05 +08:00
|
|
|
slog.Error("MQTT连接断开", "clientId", c.ClientId, "reasonCode", d.ReasonCode, "properties", d.Properties)
|
2023-12-15 18:08:06 +08:00
|
|
|
},
|
|
|
|
},
|
|
|
|
}
|
|
|
|
cc.SetUsernamePassword(c.Username, []byte(c.Password))
|
|
|
|
return cc, nil
|
|
|
|
}
|