|
@@ -12,7 +12,9 @@ import (
|
|
|
)
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
const (
|
|
|
- mqttQos1 byte = 1 //// 消息至少送达一次
|
|
|
|
|
|
|
+ MqttQos0 byte = 0 //// 消息最多送达一次
|
|
|
|
|
+ MqttQos1 byte = 1 //// 消息至少送达一次
|
|
|
|
|
+ MqttQos2 byte = 2 //// 消息恰好送达一次
|
|
|
fastInterval = 1 * time.Second //// 快速检测时间间隔
|
|
fastInterval = 1 * time.Second //// 快速检测时间间隔
|
|
|
slowInterval = 5 * time.Second //// 慢速检测时间间隔
|
|
slowInterval = 5 * time.Second //// 慢速检测时间间隔
|
|
|
)
|
|
)
|
|
@@ -21,6 +23,10 @@ var (
|
|
|
ErrNotStarted = errors.New("mqtt client not started")
|
|
ErrNotStarted = errors.New("mqtt client not started")
|
|
|
ErrNotConnected = errors.New("mqtt client not connected")
|
|
ErrNotConnected = errors.New("mqtt client not connected")
|
|
|
ErrClosed = errors.New("mqtt client is closed, cannot perform operation")
|
|
ErrClosed = errors.New("mqtt client is closed, cannot perform operation")
|
|
|
|
|
+ ErrBrokerEmpty = errors.New("mqtt broker is empty")
|
|
|
|
|
+ ErrTopicEmpty = errors.New("mqtt topic is empty")
|
|
|
|
|
+ ErrInvalidQoS = errors.New("mqtt qos is invalid")
|
|
|
|
|
+ ErrNilHandler = errors.New("mqtt message handler is nil")
|
|
|
)
|
|
)
|
|
|
|
|
|
|
|
type ClientConfig struct {
|
|
type ClientConfig struct {
|
|
@@ -30,10 +36,12 @@ type ClientConfig struct {
|
|
|
Password string //////////////////// 登录服务器的密码
|
|
Password string //////////////////// 登录服务器的密码
|
|
|
WillTopic string //////////////////// 遗嘱消息发送主题
|
|
WillTopic string //////////////////// 遗嘱消息发送主题
|
|
|
WillPayload string //////////////////// 遗嘱消息发送内容
|
|
WillPayload string //////////////////// 遗嘱消息发送内容
|
|
|
|
|
+ WillQos byte //////////////////// 遗嘱消息质量等级
|
|
|
WillRetained bool //////////////////// 遗嘱消息是否保留
|
|
WillRetained bool //////////////////// 遗嘱消息是否保留
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
type subscription struct {
|
|
type subscription struct {
|
|
|
|
|
+ qos byte
|
|
|
handler mqtt.MessageHandler //////////// 订阅主题消息处理
|
|
handler mqtt.MessageHandler //////////// 订阅主题消息处理
|
|
|
}
|
|
}
|
|
|
|
|
|
|
@@ -48,7 +56,10 @@ type Client struct {
|
|
|
closed bool
|
|
closed bool
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
-func NewClient(config ClientConfig, ctx context.Context) *Client {
|
|
|
|
|
|
|
+func NewClient(config ClientConfig, ctx context.Context) (*Client, error) {
|
|
|
|
|
+ if config.Broker == "" {
|
|
|
|
|
+ return nil, ErrBrokerEmpty
|
|
|
|
|
+ }
|
|
|
if ctx == nil {
|
|
if ctx == nil {
|
|
|
ctx = context.Background()
|
|
ctx = context.Background()
|
|
|
}
|
|
}
|
|
@@ -57,19 +68,22 @@ func NewClient(config ClientConfig, ctx context.Context) *Client {
|
|
|
|
|
|
|
|
opts := mqtt.NewClientOptions().
|
|
opts := mqtt.NewClientOptions().
|
|
|
AddBroker(config.Broker).
|
|
AddBroker(config.Broker).
|
|
|
- SetUsername(config.Username).SetPassword(config.Password).
|
|
|
|
|
|
|
+ SetUsername(config.Username).SetPassword(config.Password).SetClientID(config.ClientID).
|
|
|
SetConnectRetry(false).SetAutoReconnect(false).SetCleanSession(true).
|
|
SetConnectRetry(false).SetAutoReconnect(false).SetCleanSession(true).
|
|
|
SetKeepAlive(10 * time.Second).SetPingTimeout(5 * time.Second). // Ping心跳间隔, 超时时间
|
|
SetKeepAlive(10 * time.Second).SetPingTimeout(5 * time.Second). // Ping心跳间隔, 超时时间
|
|
|
SetOrderMatters(false)
|
|
SetOrderMatters(false)
|
|
|
|
|
|
|
|
- if config.WillTopic != "" { // 设置遗嘱消息
|
|
|
|
|
- opts = opts.SetWill(config.WillTopic, config.WillPayload, mqttQos1, config.WillRetained)
|
|
|
|
|
|
|
+ if config.WillTopic != "" { //////////////////////////////////////// 设置遗嘱消息 /////////
|
|
|
|
|
+ if config.WillQos != MqttQos0 && config.WillQos != MqttQos1 && config.WillQos != MqttQos2 {
|
|
|
|
|
+ cancel()
|
|
|
|
|
+ return nil, ErrInvalidQoS
|
|
|
|
|
+ }
|
|
|
|
|
+ opts = opts.SetWill(config.WillTopic, config.WillPayload, config.WillQos, config.WillRetained)
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
opts.OnConnect = func(c mqtt.Client) {
|
|
opts.OnConnect = func(c mqtt.Client) {
|
|
|
baseapp.Logger.Infof("[%s] 服务器连接成功", MODULE_NAME)
|
|
baseapp.Logger.Infof("[%s] 服务器连接成功", MODULE_NAME)
|
|
|
}
|
|
}
|
|
|
-
|
|
|
|
|
opts.OnConnectionLost = func(c mqtt.Client, err error) {
|
|
opts.OnConnectionLost = func(c mqtt.Client, err error) {
|
|
|
baseapp.Logger.Warnf("[%s] 服务器连接丢失: %v!", MODULE_NAME, err)
|
|
baseapp.Logger.Warnf("[%s] 服务器连接丢失: %v!", MODULE_NAME, err)
|
|
|
}
|
|
}
|
|
@@ -80,7 +94,7 @@ func NewClient(config ClientConfig, ctx context.Context) *Client {
|
|
|
cancel: cancel,
|
|
cancel: cancel,
|
|
|
done: make(chan struct{}),
|
|
done: make(chan struct{}),
|
|
|
subs: make(map[string]subscription),
|
|
subs: make(map[string]subscription),
|
|
|
- }
|
|
|
|
|
|
|
+ }, nil
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
func (c *Client) Start() error {
|
|
func (c *Client) Start() error {
|
|
@@ -115,7 +129,7 @@ func (c *Client) run() {
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
if c.client.IsConnected() { // 已连接
|
|
if c.client.IsConnected() { // 已连接
|
|
|
- if !c.waitTime(fastInterval) {
|
|
|
|
|
|
|
+ if !c.waitInterval(fastInterval) {
|
|
|
return
|
|
return
|
|
|
}
|
|
}
|
|
|
continue
|
|
continue
|
|
@@ -126,7 +140,7 @@ func (c *Client) run() {
|
|
|
return
|
|
return
|
|
|
}
|
|
}
|
|
|
baseapp.Logger.Errorf("[%s] 服务器连接失败: %v!!", MODULE_NAME, err)
|
|
baseapp.Logger.Errorf("[%s] 服务器连接失败: %v!!", MODULE_NAME, err)
|
|
|
- if !c.waitTime(slowInterval) {
|
|
|
|
|
|
|
+ if !c.waitInterval(slowInterval) {
|
|
|
return
|
|
return
|
|
|
}
|
|
}
|
|
|
continue
|
|
continue
|
|
@@ -138,14 +152,15 @@ func (c *Client) run() {
|
|
|
}
|
|
}
|
|
|
baseapp.Logger.Errorf("[%s] 恢复订阅失败了: %v!!", MODULE_NAME, err)
|
|
baseapp.Logger.Errorf("[%s] 恢复订阅失败了: %v!!", MODULE_NAME, err)
|
|
|
c.client.Disconnect(0)
|
|
c.client.Disconnect(0)
|
|
|
- if !c.waitTime(slowInterval) {
|
|
|
|
|
|
|
+ if !c.waitInterval(slowInterval) {
|
|
|
return
|
|
return
|
|
|
}
|
|
}
|
|
|
|
|
+ continue
|
|
|
}
|
|
}
|
|
|
}
|
|
}
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
-func (c *Client) waitTime(d time.Duration) bool {
|
|
|
|
|
|
|
+func (c *Client) waitInterval(d time.Duration) bool {
|
|
|
timer := time.NewTimer(d)
|
|
timer := time.NewTimer(d)
|
|
|
defer timer.Stop()
|
|
defer timer.Stop()
|
|
|
|
|
|
|
@@ -180,7 +195,7 @@ func (c *Client) resubscribe() error {
|
|
|
if c.ctx.Err() != nil {
|
|
if c.ctx.Err() != nil {
|
|
|
return c.ctx.Err()
|
|
return c.ctx.Err()
|
|
|
}
|
|
}
|
|
|
- if err := c.waitToken(c.client.Subscribe(topic, mqttQos1, sub.handler)); err != nil {
|
|
|
|
|
|
|
+ if err := c.waitToken(c.client.Subscribe(topic, sub.qos, sub.handler)); err != nil {
|
|
|
return err
|
|
return err
|
|
|
}
|
|
}
|
|
|
}
|
|
}
|
|
@@ -195,12 +210,67 @@ func (c *Client) IsConnected() bool {
|
|
|
return !c.closed && c.ctx.Err() == nil && c.client.IsConnected()
|
|
return !c.closed && c.ctx.Err() == nil && c.client.IsConnected()
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
-func (c *Client) Publish(topic string, payload any) error {
|
|
|
|
|
- return nil
|
|
|
|
|
|
|
+func (c *Client) checkStateLocked() error {
|
|
|
|
|
+ switch {
|
|
|
|
|
+ case c.closed:
|
|
|
|
|
+ return ErrClosed
|
|
|
|
|
+ case !c.started:
|
|
|
|
|
+ return ErrNotStarted
|
|
|
|
|
+ case c.ctx.Err() != nil:
|
|
|
|
|
+ return c.ctx.Err()
|
|
|
|
|
+ default:
|
|
|
|
|
+ return nil
|
|
|
|
|
+ }
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
-func (c *Client) Subscribe(topic string, handler mqtt.MessageHandler) error {
|
|
|
|
|
- return nil
|
|
|
|
|
|
|
+func (c *Client) Publish(topic string, qos byte, retained bool, payload any) error {
|
|
|
|
|
+ if topic == "" {
|
|
|
|
|
+ return ErrTopicEmpty
|
|
|
|
|
+ }
|
|
|
|
|
+ if qos != MqttQos0 && qos != MqttQos1 && qos != MqttQos2 {
|
|
|
|
|
+ return ErrInvalidQoS
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ c.mu.Lock()
|
|
|
|
|
+ if err := c.checkStateLocked(); err != nil {
|
|
|
|
|
+ c.mu.Unlock()
|
|
|
|
|
+ return err
|
|
|
|
|
+ }
|
|
|
|
|
+ if !c.client.IsConnected() {
|
|
|
|
|
+ c.mu.Unlock()
|
|
|
|
|
+ return ErrNotConnected
|
|
|
|
|
+ }
|
|
|
|
|
+ token := c.client.Publish(topic, qos, retained, payload)
|
|
|
|
|
+ c.mu.Unlock()
|
|
|
|
|
+
|
|
|
|
|
+ return c.waitToken(token)
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+func (c *Client) Subscribe(topic string, qos byte, handler mqtt.MessageHandler) error {
|
|
|
|
|
+ if topic == "" {
|
|
|
|
|
+ return ErrTopicEmpty
|
|
|
|
|
+ }
|
|
|
|
|
+ if qos != MqttQos0 && qos != MqttQos1 && qos != MqttQos2 {
|
|
|
|
|
+ return ErrInvalidQoS
|
|
|
|
|
+ }
|
|
|
|
|
+ if handler == nil {
|
|
|
|
|
+ return ErrNilHandler
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ c.mu.Lock()
|
|
|
|
|
+ if err := c.checkStateLocked(); err != nil {
|
|
|
|
|
+ c.mu.Unlock()
|
|
|
|
|
+ return err
|
|
|
|
|
+ }
|
|
|
|
|
+ c.subs[topic] = subscription{qos: qos, handler: handler} // 注意: 断线时也允许先登记订阅
|
|
|
|
|
+ if !c.client.IsConnected() {
|
|
|
|
|
+ c.mu.Unlock()
|
|
|
|
|
+ return nil
|
|
|
|
|
+ }
|
|
|
|
|
+ token := c.client.Subscribe(topic, qos, handler)
|
|
|
|
|
+ c.mu.Unlock()
|
|
|
|
|
+
|
|
|
|
|
+ return c.waitToken(token)
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
func (c *Client) Close() {
|
|
func (c *Client) Close() {
|