client.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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. SetOrderMatters(false)
  68. if willTopic := config.Topics["Offline"]; willTopic != "" { // 设置遗嘱消息
  69. if config.Qos != MqttQos0 && config.Qos != MqttQos1 && config.Qos != MqttQos2 {
  70. cancel()
  71. return nil, ErrInvalidQoS
  72. }
  73. opts = opts.SetWill(willTopic, config.WillPayload, config.Qos, false)
  74. }
  75. opts.OnConnect = func(c mqtt.Client) {
  76. baseapp.Logger.Infof("[%s] MQTT服务器 %s 连接成功", MODULE_NAME, config.BrokerName)
  77. }
  78. opts.OnConnectionLost = func(c mqtt.Client, err error) {
  79. baseapp.Logger.Warnf("[%s] MQTT服务器 %s 连接丢失: %v!", MODULE_NAME, config.BrokerName, err)
  80. }
  81. return &Client{
  82. client: mqtt.NewClient(opts),
  83. config: config,
  84. ctx: ctx,
  85. cancel: cancel,
  86. done: make(chan struct{}),
  87. subs: make(map[string]subscription),
  88. }, nil
  89. }
  90. func (c *Client) Start() error {
  91. c.mu.Lock()
  92. defer c.mu.Unlock()
  93. if c.closed {
  94. return ErrClosed
  95. }
  96. if c.started {
  97. return nil
  98. }
  99. c.started = true
  100. go c.run()
  101. return nil
  102. }
  103. func (c *Client) run() {
  104. defer func() {
  105. if c.client.IsConnected() {
  106. c.client.Disconnect(250)
  107. }
  108. close(c.done)
  109. }()
  110. for {
  111. // 1, 是否退出
  112. if c.ctx.Err() != nil {
  113. return
  114. }
  115. // 2, 已连接时
  116. if c.client.IsConnected() {
  117. if !c.waitInterval(fastInterval) {
  118. return
  119. }
  120. continue
  121. }
  122. // 3, 尝试连接
  123. baseapp.Logger.Infof("[%s] 尝试连接MQTT服务器: %s %s ...",
  124. MODULE_NAME, c.config.BrokerName, c.config.Broker)
  125. if err := c.connect(); err != nil {
  126. if c.ctx.Err() != nil {
  127. return
  128. }
  129. baseapp.Logger.Errorf("[%s] MQTT服务器 %s 连接失败: %v!!", MODULE_NAME, c.config.BrokerName, err)
  130. if !c.waitInterval(slowInterval) {
  131. return
  132. }
  133. continue
  134. }
  135. // 4, 重新订阅
  136. if err := c.resubscribe(); err != nil {
  137. if c.ctx.Err() != nil {
  138. return
  139. }
  140. baseapp.Logger.Errorf("[%s] MQTT服务器 %s 订阅失败: %v!!", MODULE_NAME, c.config.BrokerName, err)
  141. c.client.Disconnect(0)
  142. if !c.waitInterval(slowInterval) {
  143. return
  144. }
  145. continue
  146. }
  147. }
  148. }
  149. func (c *Client) waitInterval(d time.Duration) bool {
  150. timer := time.NewTimer(d)
  151. defer timer.Stop()
  152. select {
  153. case <-c.ctx.Done():
  154. return false
  155. case <-timer.C:
  156. return true
  157. }
  158. }
  159. func (c *Client) waitToken(token mqtt.Token) error {
  160. select {
  161. case <-c.ctx.Done():
  162. return c.ctx.Err()
  163. case <-token.Done():
  164. return token.Error()
  165. }
  166. }
  167. func (c *Client) connect() error {
  168. return c.waitToken(c.client.Connect())
  169. }
  170. func (c *Client) resubscribe() error {
  171. c.subMu.Lock()
  172. defer c.subMu.Unlock()
  173. c.mu.Lock()
  174. subs := make(map[string]subscription, len(c.subs))
  175. maps.Copy(subs, c.subs)
  176. c.mu.Unlock()
  177. for topic, sub := range subs {
  178. if c.ctx.Err() != nil {
  179. return c.ctx.Err()
  180. }
  181. if err := c.waitToken(c.client.Subscribe(topic, sub.qos, sub.handler)); err != nil {
  182. return err
  183. }
  184. }
  185. return nil
  186. }
  187. func (c *Client) IsConnected() bool {
  188. c.mu.Lock()
  189. defer c.mu.Unlock()
  190. return !c.closed && c.ctx.Err() == nil && c.client.IsConnected()
  191. }
  192. func (c *Client) WaitConnected() error {
  193. ticker := time.NewTicker(fastInterval)
  194. defer ticker.Stop()
  195. for {
  196. if c.IsConnected() {
  197. return nil
  198. }
  199. c.mu.Lock()
  200. err := c.checkStateLocked()
  201. c.mu.Unlock()
  202. if err != nil {
  203. return err
  204. }
  205. select {
  206. case <-c.ctx.Done():
  207. return c.ctx.Err()
  208. case <-ticker.C:
  209. }
  210. }
  211. }
  212. func (c *Client) checkStateLocked() error {
  213. switch {
  214. case c.closed:
  215. return ErrClosed
  216. case !c.started:
  217. return ErrNotStarted
  218. case c.ctx.Err() != nil:
  219. return c.ctx.Err()
  220. default:
  221. return nil
  222. }
  223. }
  224. func (c *Client) Publish(topic string, qos byte, retained bool, payload any) error {
  225. if topic == "" {
  226. return ErrTopicEmpty
  227. }
  228. if qos != MqttQos0 && qos != MqttQos1 && qos != MqttQos2 {
  229. return ErrInvalidQoS
  230. }
  231. c.mu.Lock()
  232. if err := c.checkStateLocked(); err != nil {
  233. c.mu.Unlock()
  234. return err
  235. }
  236. if !c.client.IsConnected() {
  237. c.mu.Unlock()
  238. return ErrNotConnected
  239. }
  240. token := c.client.Publish(topic, qos, retained, payload)
  241. c.mu.Unlock()
  242. return c.waitToken(token)
  243. }
  244. /*
  245. 消息回调需支持并发调用,并尽快返回,尽量避免耗时或阻塞操作, 此类类任务应交由独立的goroutine或通
  246. 过消息队列来处理,避免阻塞mqtt底层的消息处理。
  247. */
  248. func (c *Client) Subscribe(topic string, qos byte, handler MessageHandler) error {
  249. if topic == "" {
  250. return ErrTopicEmpty
  251. }
  252. if qos != MqttQos0 && qos != MqttQos1 && qos != MqttQos2 {
  253. return ErrInvalidQoS
  254. }
  255. if handler == nil {
  256. return ErrNilHandler
  257. }
  258. c.subMu.Lock()
  259. defer c.subMu.Unlock()
  260. c.mu.Lock()
  261. if err := c.checkStateLocked(); err != nil {
  262. c.mu.Unlock()
  263. return err
  264. }
  265. wrappedHandler := func(_ mqtt.Client, msg mqtt.Message) {
  266. handler(c, msg)
  267. }
  268. c.subs[topic] = subscription{qos: qos, handler: wrappedHandler}
  269. if !c.client.IsConnected() {
  270. c.mu.Unlock()
  271. return nil
  272. }
  273. token := c.client.Subscribe(topic, qos, wrappedHandler)
  274. c.mu.Unlock()
  275. return c.waitToken(token)
  276. }
  277. func (c *Client) Close() {
  278. c.mu.Lock()
  279. if !c.closed {
  280. c.closed = true
  281. c.cancel()
  282. }
  283. started := c.started
  284. c.mu.Unlock()
  285. if started {
  286. <-c.done
  287. }
  288. }