client.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. package mqtt_reporter
  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. MqttQos0 byte = 0 //// 消息最多送达一次
  13. MqttQos1 byte = 1 //// 消息至少送达一次
  14. MqttQos2 byte = 2 //// 消息恰好送达一次
  15. fastInterval = 1 * time.Second //// 快速检测时间间隔
  16. slowInterval = 5 * time.Second //// 慢速检测时间间隔
  17. )
  18. var (
  19. ErrNotStarted = errors.New("mqtt client not started")
  20. ErrNotConnected = errors.New("mqtt client not connected")
  21. ErrClosed = errors.New("mqtt client is closed, cannot perform operation")
  22. ErrBrokerEmpty = errors.New("mqtt broker is empty")
  23. ErrTopicEmpty = errors.New("mqtt topic is empty")
  24. ErrInvalidQoS = errors.New("mqtt qos is invalid")
  25. ErrNilHandler = errors.New("mqtt message handler is nil")
  26. )
  27. type ClientConfig struct {
  28. Broker string ////////// 连接服务器的地址
  29. BrokerName string ////////// 连接服务器的名字
  30. ClientID string ////////// 客户端的唯一标识
  31. Username string ////////// 登录服务器的用户
  32. Password string ////////// 登录服务器的密码
  33. Qos byte ////////// 传输消息质量等级
  34. Topics map[string]string ////////// 消息主题名和地址
  35. WillPayload string ////////// 遗嘱消息发送内容
  36. }
  37. type subscription struct {
  38. qos byte
  39. handler mqtt.MessageHandler //////////// 订阅主题消息处理
  40. }
  41. type MessageHandler func(client *Client, msg mqtt.Message)
  42. type Client struct {
  43. client mqtt.Client
  44. config ClientConfig
  45. ctx context.Context
  46. cancel context.CancelFunc
  47. done chan struct{}
  48. mu sync.Mutex
  49. subMu sync.Mutex
  50. subs map[string]subscription ////// 订阅主题与处理回调
  51. started bool
  52. closed bool
  53. }
  54. func NewClient(config ClientConfig, ctx context.Context) (*Client, error) {
  55. if config.Broker == "" {
  56. return nil, ErrBrokerEmpty
  57. }
  58. if ctx == nil {
  59. ctx = context.Background()
  60. }
  61. ctx, cancel := context.WithCancel(ctx)
  62. opts := mqtt.NewClientOptions().
  63. AddBroker(config.Broker).
  64. SetUsername(config.Username).SetPassword(config.Password).SetClientID(config.ClientID).
  65. SetConnectRetry(false).SetAutoReconnect(false).SetCleanSession(true).
  66. SetKeepAlive(10 * time.Second).SetPingTimeout(5 * time.Second). // 保活超时&Ping心跳间隔
  67. // 下面的设置使得回调独立 goroutine 执行, 避免阻塞 MQTT 网络处理 /////////////////////////
  68. SetOrderMatters(false)
  69. if willTopic := config.Topics["Offline"]; willTopic != "" { // 设置遗嘱消息
  70. if config.Qos != MqttQos0 && config.Qos != MqttQos1 && config.Qos != MqttQos2 {
  71. cancel()
  72. return nil, ErrInvalidQoS
  73. }
  74. opts = opts.SetWill(willTopic, config.WillPayload, config.Qos, false)
  75. }
  76. opts.OnConnect = func(c mqtt.Client) {
  77. baseapp.Logger.Infof("[%s] MQTT服务器 %s 连接成功", MODULE_NAME, config.BrokerName)
  78. }
  79. opts.OnConnectionLost = func(c mqtt.Client, err error) {
  80. baseapp.Logger.Warnf("[%s] MQTT服务器 %s 连接丢失: %v!", MODULE_NAME, config.BrokerName, err)
  81. }
  82. return &Client{
  83. client: mqtt.NewClient(opts),
  84. config: config,
  85. ctx: ctx,
  86. cancel: cancel,
  87. done: make(chan struct{}),
  88. subs: make(map[string]subscription),
  89. }, nil
  90. }
  91. func (c *Client) Start() error {
  92. c.mu.Lock()
  93. defer c.mu.Unlock()
  94. if c.closed {
  95. return ErrClosed
  96. }
  97. if c.started {
  98. return nil
  99. }
  100. c.started = true
  101. go c.run()
  102. return nil
  103. }
  104. func (c *Client) run() {
  105. defer func() {
  106. if c.client.IsConnected() {
  107. c.client.Disconnect(250)
  108. }
  109. close(c.done)
  110. }()
  111. for {
  112. // 1, 是否退出
  113. if c.ctx.Err() != nil {
  114. return
  115. }
  116. // 2, 已连接时
  117. if c.client.IsConnected() {
  118. if !c.waitInterval(fastInterval) {
  119. return
  120. }
  121. continue
  122. }
  123. // 3, 尝试连接
  124. baseapp.Logger.Infof("[%s] 尝试连接MQTT服务器: %s %s ...",
  125. MODULE_NAME, c.config.BrokerName, c.config.Broker)
  126. if err := c.connect(); err != nil {
  127. if c.ctx.Err() != nil {
  128. return
  129. }
  130. baseapp.Logger.Errorf("[%s] MQTT服务器 %s 连接失败: %v!!", MODULE_NAME, c.config.BrokerName, err)
  131. if !c.waitInterval(slowInterval) {
  132. return
  133. }
  134. continue
  135. }
  136. // 4, 重新订阅
  137. if err := c.resubscribe(); err != nil {
  138. if c.ctx.Err() != nil {
  139. return
  140. }
  141. baseapp.Logger.Errorf("[%s] MQTT服务器 %s 订阅失败: %v!!", MODULE_NAME, c.config.BrokerName, err)
  142. c.client.Disconnect(0)
  143. if !c.waitInterval(slowInterval) {
  144. return
  145. }
  146. continue
  147. }
  148. }
  149. }
  150. func (c *Client) waitInterval(d time.Duration) bool {
  151. timer := time.NewTimer(d)
  152. defer timer.Stop()
  153. select {
  154. case <-c.ctx.Done():
  155. return false
  156. case <-timer.C:
  157. return true
  158. }
  159. }
  160. func (c *Client) waitToken(token mqtt.Token) error {
  161. select {
  162. case <-c.ctx.Done():
  163. return c.ctx.Err()
  164. case <-token.Done():
  165. return token.Error()
  166. }
  167. }
  168. func (c *Client) connect() error {
  169. return c.waitToken(c.client.Connect())
  170. }
  171. func (c *Client) resubscribe() error {
  172. c.subMu.Lock()
  173. defer c.subMu.Unlock()
  174. c.mu.Lock()
  175. subs := make(map[string]subscription, len(c.subs))
  176. maps.Copy(subs, c.subs)
  177. c.mu.Unlock()
  178. for topic, sub := range subs {
  179. if c.ctx.Err() != nil {
  180. return c.ctx.Err()
  181. }
  182. if err := c.waitToken(c.client.Subscribe(topic, sub.qos, sub.handler)); err != nil {
  183. return err
  184. }
  185. }
  186. return nil
  187. }
  188. func (c *Client) IsConnected() bool {
  189. c.mu.Lock()
  190. defer c.mu.Unlock()
  191. return !c.closed && c.ctx.Err() == nil && c.client.IsConnected()
  192. }
  193. func (c *Client) WaitConnected() error {
  194. ticker := time.NewTicker(fastInterval)
  195. defer ticker.Stop()
  196. for {
  197. if c.IsConnected() {
  198. return nil
  199. }
  200. c.mu.Lock()
  201. err := c.checkStateLocked()
  202. c.mu.Unlock()
  203. if err != nil {
  204. return err
  205. }
  206. select {
  207. case <-c.ctx.Done():
  208. return c.ctx.Err()
  209. case <-ticker.C:
  210. }
  211. }
  212. }
  213. func (c *Client) checkStateLocked() error {
  214. switch {
  215. case c.closed:
  216. return ErrClosed
  217. case !c.started:
  218. return ErrNotStarted
  219. case c.ctx.Err() != nil:
  220. return c.ctx.Err()
  221. default:
  222. return nil
  223. }
  224. }
  225. func (c *Client) Publish(topic string, qos byte, retained bool, payload any) error {
  226. if topic == "" {
  227. return ErrTopicEmpty
  228. }
  229. if qos != MqttQos0 && qos != MqttQos1 && qos != MqttQos2 {
  230. return ErrInvalidQoS
  231. }
  232. c.mu.Lock()
  233. if err := c.checkStateLocked(); err != nil {
  234. c.mu.Unlock()
  235. return err
  236. }
  237. if !c.client.IsConnected() {
  238. c.mu.Unlock()
  239. return ErrNotConnected
  240. }
  241. token := c.client.Publish(topic, qos, retained, payload)
  242. c.mu.Unlock()
  243. return c.waitToken(token)
  244. }
  245. func (c *Client) Subscribe(topic string, qos byte, handler MessageHandler) error {
  246. if topic == "" {
  247. return ErrTopicEmpty
  248. }
  249. if qos != MqttQos0 && qos != MqttQos1 && qos != MqttQos2 {
  250. return ErrInvalidQoS
  251. }
  252. if handler == nil {
  253. return ErrNilHandler
  254. }
  255. c.subMu.Lock()
  256. defer c.subMu.Unlock()
  257. c.mu.Lock()
  258. if err := c.checkStateLocked(); err != nil {
  259. c.mu.Unlock()
  260. return err
  261. }
  262. wrappedHandler := func(_ mqtt.Client, msg mqtt.Message) {
  263. handler(c, msg)
  264. }
  265. c.subs[topic] = subscription{qos: qos, handler: wrappedHandler}
  266. if !c.client.IsConnected() {
  267. c.mu.Unlock()
  268. return nil
  269. }
  270. token := c.client.Subscribe(topic, qos, wrappedHandler)
  271. c.mu.Unlock()
  272. return c.waitToken(token)
  273. }
  274. func (c *Client) Close() {
  275. c.mu.Lock()
  276. if !c.closed {
  277. c.closed = true
  278. c.cancel()
  279. }
  280. started := c.started
  281. c.mu.Unlock()
  282. if started {
  283. <-c.done
  284. }
  285. }