client.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. package mqttreporter
  2. import (
  3. "context"
  4. "errors"
  5. "maps"
  6. "sync"
  7. "time"
  8. mqtt "github.com/eclipse/paho.mqtt.golang"
  9. "hnyfkj.com.cn/rtu/linux/baseapp"
  10. )
  11. const (
  12. mqttQos1 byte = 1 //// 消息至少送达一次
  13. fastInterval = 1 * time.Second //// 快速检测时间间隔
  14. slowInterval = 5 * time.Second //// 慢速检测时间间隔
  15. )
  16. var (
  17. ErrNotStarted = errors.New("mqtt client not started")
  18. ErrNotConnected = errors.New("mqtt client not connected")
  19. ErrClosed = errors.New("mqtt client is closed, cannot perform operation")
  20. )
  21. type ClientConfig struct {
  22. Broker string //////////////////// 连接服务器的地址
  23. ClientID string //////////////////// 客户端的唯一标识
  24. Username string //////////////////// 登录服务器的用户
  25. Password string //////////////////// 登录服务器的密码
  26. WillTopic string //////////////////// 遗嘱消息发送主题
  27. WillPayload string //////////////////// 遗嘱消息发送内容
  28. WillRetained bool //////////////////// 遗嘱消息是否保留
  29. }
  30. type subscription struct {
  31. handler mqtt.MessageHandler //////////// 订阅主题消息处理
  32. }
  33. type Client struct {
  34. client mqtt.Client
  35. ctx context.Context
  36. cancel context.CancelFunc
  37. done chan struct{}
  38. mu sync.Mutex
  39. subs map[string]subscription ////// 订阅主题与处理回调
  40. started bool
  41. closed bool
  42. }
  43. func NewClient(config ClientConfig, ctx context.Context) *Client {
  44. if ctx == nil {
  45. ctx = context.Background()
  46. }
  47. ctx, cancel := context.WithCancel(ctx)
  48. opts := mqtt.NewClientOptions().
  49. AddBroker(config.Broker).
  50. SetUsername(config.Username).SetPassword(config.Password).
  51. SetConnectRetry(false).SetAutoReconnect(false).SetCleanSession(true).
  52. SetKeepAlive(10 * time.Second).SetPingTimeout(5 * time.Second). // Ping心跳间隔, 超时时间
  53. SetOrderMatters(false)
  54. if config.WillTopic != "" { // 设置遗嘱消息
  55. opts = opts.SetWill(config.WillTopic, config.WillPayload, mqttQos1, config.WillRetained)
  56. }
  57. opts.OnConnect = func(c mqtt.Client) {
  58. baseapp.Logger.Infof("[%s] 服务器连接成功", MODULE_NAME)
  59. }
  60. opts.OnConnectionLost = func(c mqtt.Client, err error) {
  61. baseapp.Logger.Warnf("[%s] 服务器连接丢失: %v!", MODULE_NAME, err)
  62. }
  63. return &Client{
  64. client: mqtt.NewClient(opts),
  65. ctx: ctx,
  66. cancel: cancel,
  67. done: make(chan struct{}),
  68. subs: make(map[string]subscription),
  69. }
  70. }
  71. func (c *Client) Start() error {
  72. c.mu.Lock()
  73. defer c.mu.Unlock()
  74. if c.closed {
  75. return ErrClosed
  76. }
  77. if c.started {
  78. return nil
  79. }
  80. c.started = true
  81. go c.run()
  82. return nil
  83. }
  84. func (c *Client) run() {
  85. defer func() {
  86. if c.client.IsConnected() {
  87. c.client.Disconnect(250)
  88. }
  89. close(c.done)
  90. }()
  91. for {
  92. if c.ctx.Err() != nil {
  93. return
  94. }
  95. if c.client.IsConnected() { // 已连接
  96. if !c.waitTime(fastInterval) {
  97. return
  98. }
  99. continue
  100. }
  101. if err := c.connect(); err != nil {
  102. if c.ctx.Err() != nil {
  103. return
  104. }
  105. baseapp.Logger.Errorf("[%s] 服务器连接失败: %v!!", MODULE_NAME, err)
  106. if !c.waitTime(slowInterval) {
  107. return
  108. }
  109. continue
  110. }
  111. if err := c.resubscribe(); err != nil {
  112. if c.ctx.Err() != nil {
  113. return
  114. }
  115. baseapp.Logger.Errorf("[%s] 恢复订阅失败了: %v!!", MODULE_NAME, err)
  116. c.client.Disconnect(0)
  117. if !c.waitTime(slowInterval) {
  118. return
  119. }
  120. }
  121. }
  122. }
  123. func (c *Client) waitTime(d time.Duration) bool {
  124. timer := time.NewTimer(d)
  125. defer timer.Stop()
  126. select {
  127. case <-c.ctx.Done():
  128. return false
  129. case <-timer.C:
  130. return true
  131. }
  132. }
  133. func (c *Client) waitToken(token mqtt.Token) error {
  134. select {
  135. case <-c.ctx.Done():
  136. return c.ctx.Err()
  137. case <-token.Done():
  138. return token.Error()
  139. }
  140. }
  141. func (c *Client) connect() error {
  142. return c.waitToken(c.client.Connect())
  143. }
  144. func (c *Client) resubscribe() error {
  145. c.mu.Lock()
  146. subs := make(map[string]subscription, len(c.subs))
  147. maps.Copy(subs, c.subs)
  148. c.mu.Unlock()
  149. for topic, sub := range subs {
  150. if c.ctx.Err() != nil {
  151. return c.ctx.Err()
  152. }
  153. if err := c.waitToken(c.client.Subscribe(topic, mqttQos1, sub.handler)); err != nil {
  154. return err
  155. }
  156. }
  157. return nil
  158. }
  159. func (c *Client) IsConnected() bool {
  160. c.mu.Lock()
  161. defer c.mu.Unlock()
  162. return !c.closed && c.ctx.Err() == nil && c.client.IsConnected()
  163. }
  164. func (c *Client) Close() {
  165. c.mu.Lock()
  166. if c.closed {
  167. started := c.started
  168. c.mu.Unlock()
  169. if started {
  170. <-c.done
  171. }
  172. return
  173. }
  174. c.closed = true
  175. c.cancel()
  176. started := c.started
  177. c.mu.Unlock()
  178. if started {
  179. <-c.done
  180. }
  181. }