mqttClient.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. package mqttClient
  2. import (
  3. "crypto/tls"
  4. "fmt"
  5. "net/url"
  6. "time"
  7. mqtt "github.com/eclipse/paho.mqtt.golang"
  8. "go.uber.org/zap"
  9. )
  10. type MqttClientOpt struct {
  11. Broker string // 服务端地址
  12. ClientID string // (可选) 客户端名称
  13. TLS *tls.Config
  14. }
  15. type MqttClient struct {
  16. client mqtt.Client
  17. subscribeMap map[string]func(payload []byte)
  18. clientID string // 客户端名称
  19. }
  20. const (
  21. connectTimeout = 30 * time.Second // 30s
  22. subscribeMsgTimeout = 30 * time.Second // 30s
  23. sendMsgTimeout = 30 * time.Second // 30s
  24. )
  25. // 创建客户端
  26. func CreateMqttClient(opt MqttClientOpt) (*MqttClient, error) {
  27. // 创建客户端选项
  28. opts := mqtt.NewClientOptions()
  29. opts.AddBroker(opt.Broker)
  30. clientID := "go_mqtt_client"
  31. if len(opt.ClientID) > 0 {
  32. clientID = opt.ClientID
  33. }
  34. opts.SetClientID(clientID)
  35. opts.SetAutoReconnect(true) // 自动重连
  36. opts.SetCleanSession(true) // 不保留会话
  37. opts.SetTLSConfig(opt.TLS)
  38. mqttClient := MqttClient{
  39. subscribeMap: map[string]func(payload []byte){},
  40. }
  41. // 连接成功回调
  42. opts.OnConnect = func(c mqtt.Client) {
  43. zap.L().Info("Connected to MQTT broker", zap.String("clientID", clientID))
  44. // 重新订阅丢失的 Subscribe
  45. mqttClient.ResumeSubscribe()
  46. }
  47. // 连接丢失回调
  48. opts.OnConnectionLost = func(c mqtt.Client, err error) {
  49. fmt.Printf("%s Connection lost: %s\n", clientID, err.Error())
  50. zap.L().Info("MQTT Connection lost", zap.String("clientID", clientID), zap.String("err", err.Error()))
  51. }
  52. // 重连回调
  53. opts.OnReconnecting = func(c mqtt.Client, opts *mqtt.ClientOptions) {
  54. zap.L().Info("MQTT Reconnecting", zap.String("clientID", clientID))
  55. }
  56. // 尝试连接回调
  57. opts.OnConnectAttempt = func(broker *url.URL, tlsCfg *tls.Config) *tls.Config {
  58. zap.L().Info("MQTT Attempt Connect", zap.String("clientID", clientID), zap.String("Broker", broker.String()))
  59. return tlsCfg
  60. }
  61. // 连接事件回调
  62. opts.OnConnectionNotification = func(c mqtt.Client, cn mqtt.ConnectionNotification) {
  63. zap.L().Info("MQTT Connecting Notification", zap.String("clientID", clientID), zap.Int64("Notification", int64(cn.Type())))
  64. }
  65. // 创建客户端
  66. mqttClient.client = mqtt.NewClient(opts)
  67. return &mqttClient, nil
  68. }
  69. func (c *MqttClient) Connect() error {
  70. if c.client.IsConnected() {
  71. return nil
  72. }
  73. // 连接
  74. token := c.client.Connect()
  75. if !token.WaitTimeout(connectTimeout) {
  76. return fmt.Errorf("connect timeout (%s)", c.clientID)
  77. }
  78. return token.Error()
  79. }
  80. // 断开连接
  81. func (c *MqttClient) Disconnect() {
  82. if !c.client.IsConnected() {
  83. return
  84. }
  85. // 清空订阅
  86. c.CleanSubscribe()
  87. // 安全断开,等待最多 2 秒让队列消息发送完
  88. c.client.Disconnect(2000)
  89. }
  90. // 检查是否连接
  91. func (c *MqttClient) IsConnected() bool {
  92. return c.client.IsConnected()
  93. }
  94. // 恢复订阅消息
  95. func (c *MqttClient) ResumeSubscribe() {
  96. for k, v := range c.subscribeMap {
  97. c.subscribeMessage(k, v)
  98. }
  99. }
  100. // 清空所有订阅
  101. func (c *MqttClient) CleanSubscribe() {
  102. for k := range c.subscribeMap {
  103. delete(c.subscribeMap, k)
  104. }
  105. }
  106. // 订阅消息
  107. func (c *MqttClient) subscribeMessage(topic string, callback func(payload []byte)) error {
  108. if !c.client.IsConnected() {
  109. return fmt.Errorf("subscribe failed. (client not connected)")
  110. }
  111. token := c.client.Subscribe(topic, 1, func(c mqtt.Client, m mqtt.Message) {
  112. callback(m.Payload())
  113. })
  114. if !token.WaitTimeout(subscribeMsgTimeout) {
  115. return fmt.Errorf("subscribe timeout (topic:%s)", topic)
  116. }
  117. err := token.Error()
  118. if err != nil {
  119. return err
  120. }
  121. return nil
  122. }
  123. // 订阅消息
  124. func (c *MqttClient) SubscribeMessage(topic string, callback func(payload []byte)) error {
  125. err := c.subscribeMessage(topic, callback)
  126. if err != nil {
  127. return err
  128. }
  129. // 备份subscribe
  130. c.subscribeMap[topic] = callback
  131. return nil
  132. }
  133. // 取消订阅
  134. func (c *MqttClient) UnSubscribeMessage(topic string) error {
  135. if !c.client.IsConnected() {
  136. return fmt.Errorf("unsubscribe failed. (client not connected)")
  137. }
  138. token := c.client.Unsubscribe(topic)
  139. if !token.WaitTimeout(subscribeMsgTimeout) {
  140. return fmt.Errorf("unsubscribe timeout (topic:%s)", topic)
  141. }
  142. err := token.Error()
  143. if err != nil {
  144. return err
  145. }
  146. delete(c.subscribeMap, topic)
  147. return nil
  148. }
  149. // 发送消息,只尝试一次,不管是否送达
  150. func (c *MqttClient) SendMessageOnce(topic string, msg []byte) error {
  151. if !c.client.IsConnected() {
  152. return fmt.Errorf("send message once failed. (client not connected)")
  153. }
  154. token := c.client.Publish(topic, 0, false, msg)
  155. if !token.WaitTimeout(sendMsgTimeout) {
  156. return fmt.Errorf("send message once timeout (topic:%s, msg:%s)", topic, msg)
  157. }
  158. return token.Error()
  159. }
  160. // 发送消息,没收到 ACK 就重发,至少送到一次,可能收到多次
  161. func (c *MqttClient) SendMessage(topic string, msg []byte, retained bool) error {
  162. if !c.client.IsConnected() {
  163. return fmt.Errorf("send message failed. (client not connected)")
  164. }
  165. token := c.client.Publish(topic, 1, retained, msg)
  166. if !token.WaitTimeout(sendMsgTimeout) {
  167. return fmt.Errorf("send message timeout (topic:%s, msg:%s)", topic, msg)
  168. }
  169. return token.Error()
  170. }
  171. // 发送消息,严格一次,不重复,不丢失
  172. func (c *MqttClient) SendMessageMustOnce(topic string, msg []byte, retained bool) error {
  173. if !c.client.IsConnected() {
  174. return fmt.Errorf("send message must once failed. (client not connected)")
  175. }
  176. token := c.client.Publish(topic, 2, retained, msg)
  177. if !token.WaitTimeout(sendMsgTimeout) {
  178. return fmt.Errorf("send message must once timeout (topic:%s, msg:%s)", topic, msg)
  179. }
  180. return token.Error()
  181. }
  182. // 发送消息,没收到 ACK 就重发,至少送到一次,可能收到多次,并保留消息在Broker,新定义的设备会收到消息
  183. func (c *MqttClient) SendMessageRetained(topic string, msg []byte) error {
  184. if !c.client.IsConnected() {
  185. return fmt.Errorf("send message retained failed. (client not connected)")
  186. }
  187. token := c.client.Publish(topic, 1, true, msg)
  188. if !token.WaitTimeout(sendMsgTimeout) {
  189. return fmt.Errorf("send message retained timeout (topic:%s, msg:%s)", topic, msg)
  190. }
  191. return token.Error()
  192. }
  193. // 清除保留在Broker的消息
  194. func (c *MqttClient) CleanMessageRetained(topic string) error {
  195. if !c.client.IsConnected() {
  196. return fmt.Errorf("clean message retained failed. (client not connected)")
  197. }
  198. token := c.client.Publish(topic, 1, true, nil)
  199. if !token.WaitTimeout(sendMsgTimeout) {
  200. return fmt.Errorf("clean message retained timeout (topic:%s)", topic)
  201. }
  202. return token.Error()
  203. }