|
|
@@ -1,6 +1,21 @@
|
|
|
package mqttreporter
|
|
|
|
|
|
-import "errors"
|
|
|
+import (
|
|
|
+ "context"
|
|
|
+ "errors"
|
|
|
+ "maps"
|
|
|
+ "sync"
|
|
|
+ "time"
|
|
|
+
|
|
|
+ mqtt "github.com/eclipse/paho.mqtt.golang"
|
|
|
+ "hnyfkj.com.cn/rtu/linux/baseapp"
|
|
|
+)
|
|
|
+
|
|
|
+const (
|
|
|
+ mqttQos1 byte = 1 //// 消息至少送达一次
|
|
|
+ fastInterval = 1 * time.Second //// 快速检测时间间隔
|
|
|
+ slowInterval = 5 * time.Second //// 慢速检测时间间隔
|
|
|
+)
|
|
|
|
|
|
var (
|
|
|
ErrNotStarted = errors.New("mqtt client not started")
|
|
|
@@ -9,8 +24,173 @@ var (
|
|
|
)
|
|
|
|
|
|
type ClientConfig struct {
|
|
|
- Broker string
|
|
|
- ClientID string
|
|
|
- Username string
|
|
|
- Password string
|
|
|
+ Broker string //////////////////// 连接服务器的地址
|
|
|
+ ClientID string //////////////////// 客户端的唯一标识
|
|
|
+ Username string //////////////////// 登录服务器的用户
|
|
|
+ Password string //////////////////// 登录服务器的密码
|
|
|
+ WillTopic string //////////////////// 遗嘱消息发送主题
|
|
|
+ WillPayload string //////////////////// 遗嘱消息发送内容
|
|
|
+ WillRetained bool //////////////////// 遗嘱消息是否保留
|
|
|
+}
|
|
|
+
|
|
|
+type subscription struct {
|
|
|
+ handler mqtt.MessageHandler //////////// 订阅主题消息处理
|
|
|
+}
|
|
|
+
|
|
|
+type Client struct {
|
|
|
+ client mqtt.Client
|
|
|
+ ctx context.Context
|
|
|
+ cancel context.CancelFunc
|
|
|
+ done chan struct{}
|
|
|
+ mu sync.Mutex
|
|
|
+ subs map[string]subscription ////// 订阅主题与处理回调
|
|
|
+ started bool
|
|
|
+ closed bool
|
|
|
+}
|
|
|
+
|
|
|
+func NewClient(config ClientConfig, ctx context.Context) *Client {
|
|
|
+ if ctx == nil {
|
|
|
+ ctx = context.Background()
|
|
|
+ }
|
|
|
+
|
|
|
+ ctx, cancel := context.WithCancel(ctx)
|
|
|
+
|
|
|
+ opts := mqtt.NewClientOptions().
|
|
|
+ AddBroker(config.Broker).
|
|
|
+ SetUsername(config.Username).SetPassword(config.Password).
|
|
|
+ SetConnectRetry(false).SetAutoReconnect(false).SetCleanSession(true).
|
|
|
+ SetKeepAlive(10 * time.Second).SetPingTimeout(5 * time.Second). // Ping心跳间隔, 超时时间
|
|
|
+ SetOrderMatters(false)
|
|
|
+
|
|
|
+ if config.WillTopic != "" { // 设置遗嘱消息
|
|
|
+ opts = opts.SetWill(config.WillTopic, config.WillPayload, mqttQos1, config.WillRetained)
|
|
|
+ }
|
|
|
+
|
|
|
+ opts.OnConnect = func(c mqtt.Client) {
|
|
|
+ baseapp.Logger.Infof("[%s] 服务器连接成功", MODULE_NAME)
|
|
|
+ }
|
|
|
+
|
|
|
+ opts.OnConnectionLost = func(c mqtt.Client, err error) {
|
|
|
+ baseapp.Logger.Warnf("[%s] 服务器连接丢失: %v!", MODULE_NAME, err)
|
|
|
+ }
|
|
|
+
|
|
|
+ return &Client{
|
|
|
+ client: mqtt.NewClient(opts),
|
|
|
+ ctx: ctx,
|
|
|
+ cancel: cancel,
|
|
|
+ done: make(chan struct{}),
|
|
|
+ subs: make(map[string]subscription),
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+func (c *Client) Start() error {
|
|
|
+ c.mu.Lock()
|
|
|
+ defer c.mu.Unlock()
|
|
|
+
|
|
|
+ if c.closed {
|
|
|
+ return ErrClosed
|
|
|
+ }
|
|
|
+
|
|
|
+ if c.started {
|
|
|
+ return nil
|
|
|
+ }
|
|
|
+
|
|
|
+ c.started = true
|
|
|
+ go c.run()
|
|
|
+
|
|
|
+ return nil
|
|
|
+}
|
|
|
+
|
|
|
+func (c *Client) run() {
|
|
|
+ defer func() {
|
|
|
+ if c.client.IsConnected() {
|
|
|
+ c.client.Disconnect(250)
|
|
|
+ }
|
|
|
+ close(c.done)
|
|
|
+ }()
|
|
|
+
|
|
|
+ for {
|
|
|
+ if c.ctx.Err() != nil {
|
|
|
+ return
|
|
|
+ }
|
|
|
+
|
|
|
+ if c.client.IsConnected() { // 已连接
|
|
|
+ if !c.waitTime(fastInterval) {
|
|
|
+ return
|
|
|
+ }
|
|
|
+ continue
|
|
|
+ }
|
|
|
+
|
|
|
+ if err := c.connect(); err != nil {
|
|
|
+ if c.ctx.Err() != nil {
|
|
|
+ return
|
|
|
+ }
|
|
|
+ baseapp.Logger.Errorf("[%s] 服务器连接失败: %v!!", MODULE_NAME, err)
|
|
|
+ if !c.waitTime(slowInterval) {
|
|
|
+ return
|
|
|
+ }
|
|
|
+ continue
|
|
|
+ }
|
|
|
+
|
|
|
+ if err := c.resubscribe(); err != nil {
|
|
|
+ if c.ctx.Err() != nil {
|
|
|
+ return
|
|
|
+ }
|
|
|
+ baseapp.Logger.Errorf("[%s] 恢复订阅失败了: %v!!", MODULE_NAME, err)
|
|
|
+ c.client.Disconnect(0)
|
|
|
+ if !c.waitTime(slowInterval) {
|
|
|
+ return
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+func (c *Client) waitTime(d time.Duration) bool {
|
|
|
+ timer := time.NewTimer(d)
|
|
|
+ defer timer.Stop()
|
|
|
+
|
|
|
+ select {
|
|
|
+ case <-c.ctx.Done():
|
|
|
+ return false
|
|
|
+ case <-timer.C:
|
|
|
+ return true
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+func (c *Client) waitToken(token mqtt.Token) error {
|
|
|
+ select {
|
|
|
+ case <-c.ctx.Done():
|
|
|
+ return c.ctx.Err()
|
|
|
+ case <-token.Done():
|
|
|
+ return token.Error()
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+func (c *Client) connect() error {
|
|
|
+ return c.waitToken(c.client.Connect())
|
|
|
+}
|
|
|
+
|
|
|
+func (c *Client) resubscribe() error {
|
|
|
+ c.mu.Lock()
|
|
|
+ subs := make(map[string]subscription, len(c.subs))
|
|
|
+ maps.Copy(subs, c.subs)
|
|
|
+ c.mu.Unlock()
|
|
|
+
|
|
|
+ for topic, sub := range subs {
|
|
|
+ if c.ctx.Err() != nil {
|
|
|
+ return c.ctx.Err()
|
|
|
+ }
|
|
|
+ if err := c.waitToken(c.client.Subscribe(topic, mqttQos1, sub.handler)); err != nil {
|
|
|
+ return err
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ return nil
|
|
|
+}
|
|
|
+
|
|
|
+func (c *Client) IsConnected() bool {
|
|
|
+ c.mu.Lock()
|
|
|
+ defer c.mu.Unlock()
|
|
|
+
|
|
|
+ return !c.closed && c.ctx.Err() == nil && c.client.IsConnected()
|
|
|
}
|