sub.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. package mqtt
  2. import (
  3. "fmt"
  4. "gitee.com/xuyiping_admin/pkg/logger/zaplog"
  5. golangMqtt "github.com/eclipse/paho.mqtt.golang"
  6. "go.uber.org/zap"
  7. "kpt-temporary-mqtt/config"
  8. "kpt-temporary-mqtt/model"
  9. "kpt-temporary-mqtt/util"
  10. "os"
  11. "os/signal"
  12. "strconv"
  13. "strings"
  14. "sync"
  15. "syscall"
  16. "time"
  17. )
  18. var golangMqttClient golangMqtt.Client
  19. var messagePubHandler golangMqtt.MessageHandler = func(client golangMqtt.Client, msg golangMqtt.Message) {
  20. zaplog.Info("messagePubHandlerReceived", zap.Any("message", string(msg.Payload())), zap.Any("topic", msg.Topic()))
  21. }
  22. var connectHandler golangMqtt.OnConnectHandler = func(client golangMqtt.Client) {
  23. zaplog.Info("connectedClient", zap.Any("client", client))
  24. }
  25. // 连接丢失处理
  26. var connectLostHandler golangMqtt.ConnectionLostHandler = func(client golangMqtt.Client, err error) {
  27. zaplog.Error("connectLost", zap.Any("err", err.Error()))
  28. ConnectionRetry()
  29. }
  30. // ConnectionRetry 尝试重新连接
  31. func ConnectionRetry() {
  32. options := config.Options()
  33. opts := golangMqtt.NewClientOptions().
  34. AddBroker(fmt.Sprintf("tcp://%s:%d", options.Broker, options.Port)).
  35. SetClientID(util.RandString(12)).
  36. SetUsername(options.UserName).
  37. SetPassword(options.Password).
  38. SetDefaultPublishHandler(messagePubHandler)
  39. opts.SetMaxReconnectInterval(5 * time.Minute)
  40. opts.SetKeepAlive(2 * time.Minute)
  41. opts.SetAutoReconnect(true)
  42. opts.SetConnectRetry(true)
  43. newClient := golangMqtt.NewClient(opts)
  44. if token := newClient.Connect(); token.Wait() && token.Error() == nil {
  45. // 成功重连,更新全局客户端实例
  46. golangMqttClient = newClient
  47. return // 退出重连循环
  48. } else {
  49. zaplog.Error("ConnectionRetry", zap.Any("err", token.Error()))
  50. }
  51. }
  52. func (d *DataEventEntry) NewMqtt(configOption *config.AppConfig) {
  53. opts := golangMqtt.NewClientOptions()
  54. opts.AddBroker(fmt.Sprintf("tcp://%s:%d", configOption.Broker, configOption.Port))
  55. opts.SetClientID(util.RandString(12))
  56. opts.SetUsername(configOption.UserName)
  57. opts.SetPassword(configOption.Password)
  58. opts.SetKeepAlive(2 * time.Minute)
  59. opts.SetAutoReconnect(true)
  60. opts.SetConnectRetry(true)
  61. opts.SetDefaultPublishHandler(messagePubHandler)
  62. opts.OnConnect = connectHandler
  63. opts.OnConnectionLost = connectLostHandler
  64. client := golangMqtt.NewClient(opts)
  65. if token := client.Connect(); token.Wait() && token.Error() != nil {
  66. panic(token.Error())
  67. }
  68. golangMqttClient = client
  69. }
  70. type DataInsertSubMsgLog struct {
  71. SubMsgLogList []*model.SubMsgLog
  72. Mx *sync.RWMutex
  73. }
  74. func (d *DataEventEntry) SubMsgLog(configOption *config.AppConfig) {
  75. var subMsgChan = make(chan []byte, configOption.WorkNumber)
  76. golangMqttClient.Subscribe(configOption.SubTopName, 1, func(client golangMqtt.Client, msg golangMqtt.Message) {
  77. subMsgChan <- msg.Payload()
  78. })
  79. DSMLog := DataInsertSubMsgLog{
  80. SubMsgLogList: make([]*model.SubMsgLog, 0),
  81. Mx: &sync.RWMutex{},
  82. }
  83. batchSize := 5
  84. batchList := make([]*model.SubMsgLog, 0, batchSize)
  85. sc := make(chan os.Signal, 1)
  86. signal.Notify(sc, os.Kill, os.Interrupt, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
  87. // 设置2分钟超时
  88. tc := time.After(2 * time.Minute)
  89. go func() {
  90. for {
  91. select {
  92. case <-tc:
  93. if !golangMqttClient.IsConnectionOpen() || !golangMqttClient.IsConnected() {
  94. zaplog.Info("IsConnectionOpen")
  95. ConnectionRetry()
  96. }
  97. }
  98. }
  99. }()
  100. //for i := 0; i < int(configOption.WorkNumber); i++ {
  101. //go func() {
  102. for {
  103. select {
  104. case msg := <-subMsgChan:
  105. subMsLog := d.CreatMsgLog(msg)
  106. batchList = append(batchList, subMsLog)
  107. if len(batchList) >= batchSize {
  108. DSMLog.Mx.Lock()
  109. DSMLog.SubMsgLogList = append(DSMLog.SubMsgLogList, batchList...)
  110. if len(DSMLog.SubMsgLogList) >= 10 {
  111. if err := d.DB.Create(DSMLog.SubMsgLogList).Error; err != nil {
  112. zaplog.Error("subMsgChan-info", zap.Any("err", err), zap.Any("subMsgLog", DSMLog.SubMsgLogList))
  113. }
  114. DSMLog.SubMsgLogList = make([]*model.SubMsgLog, 0)
  115. }
  116. DSMLog.Mx.Unlock()
  117. batchList = batchList[:0]
  118. }
  119. // 优雅退出
  120. case <-sc:
  121. if len(DSMLog.SubMsgLogList) > 0 {
  122. DSMLog.Mx.Lock()
  123. if err := d.DB.Create(DSMLog.SubMsgLogList).Error; err != nil {
  124. zaplog.Error("subMsgChan-os", zap.Any("err", err), zap.Any("subMsgLog", DSMLog.SubMsgLogList))
  125. }
  126. zaplog.Info("subMsgChan-os", zap.Any("success", DSMLog.SubMsgLogList))
  127. DSMLog.SubMsgLogList = make([]*model.SubMsgLog, 0)
  128. DSMLog.Mx.Unlock()
  129. }
  130. close(subMsgChan)
  131. case <-tc:
  132. if len(DSMLog.SubMsgLogList) > 0 {
  133. DSMLog.Mx.Lock()
  134. if err := d.DB.Create(DSMLog.SubMsgLogList).Error; err != nil {
  135. zaplog.Error("subMsgChan-os", zap.Any("err", err), zap.Any("subMsgLog", DSMLog.SubMsgLogList))
  136. }
  137. zaplog.Info("subMsgChan-os", zap.Any("success", DSMLog.SubMsgLogList))
  138. DSMLog.SubMsgLogList = make([]*model.SubMsgLog, 0)
  139. DSMLog.Mx.Unlock()
  140. }
  141. }
  142. }
  143. //}()
  144. //}
  145. }
  146. func (d *DataEventEntry) CreatMsgLog(msg []byte) *model.SubMsgLog {
  147. defer func() {
  148. if time.Now().Day()%15 == 0 {
  149. d.DB.Model(new(model.SubMsgLog)).Where("created_at < ?", time.Now().AddDate(0, 0, -15).Unix()).Delete(new(model.SubMsgLog))
  150. return
  151. }
  152. }()
  153. subMsgLog, err := d.MsgDataFormat(msg)
  154. if err != nil {
  155. zaplog.Error("CreatMsgLog", zap.Any("err", err), zap.Any("msg", string(msg)))
  156. }
  157. if subMsgLog == nil {
  158. return nil
  159. }
  160. if subMsgLog.Imei == "" {
  161. zaplog.Info("CreatMsgLog", zap.Any("msg", string(msg)), zap.Any("subMsgLog", subMsgLog))
  162. return nil
  163. }
  164. return subMsgLog
  165. }
  166. func (d *DataEventEntry) MsgDataFormat(msg []byte) (*model.SubMsgLog, error) {
  167. msgData := make(map[string]interface{})
  168. pairs := strings.Split(util.MsgFormat(string(msg)), " ")
  169. for _, pair := range pairs {
  170. parts := strings.SplitN(pair, ":", 2)
  171. if len(parts) != 2 {
  172. continue
  173. }
  174. key, value := parts[0], parts[1]
  175. if len(key) == 0 {
  176. continue
  177. }
  178. msgData[key] = value
  179. }
  180. softVer := int64(0)
  181. if softVerInter, ok := msgData["SOFT_VER"]; ok {
  182. if softVerstr, ok := softVerInter.(string); ok {
  183. softVer, _ = strconv.ParseInt(softVerstr, 10, 64)
  184. }
  185. }
  186. uuid := ""
  187. if uuidInter, ok := msgData["uuid"]; ok {
  188. if uuidStr, ok := uuidInter.(string); ok {
  189. uuid = uuidStr
  190. }
  191. }
  192. frameId := int64(0)
  193. if frameIdInter, ok := msgData["frameid"]; ok {
  194. if frameId64, ok := frameIdInter.(string); ok {
  195. frameId, _ = strconv.ParseInt(frameId64, 10, 64)
  196. }
  197. }
  198. cowId := ""
  199. if cowIdInter, ok := msgData["cowid"]; ok {
  200. if cowIdStr, ok := cowIdInter.(string); ok {
  201. cowId = cowIdStr
  202. }
  203. }
  204. csq := int64(0)
  205. if csqInter, ok := msgData["csq"]; ok {
  206. if csq32, ok := csqInter.(string); ok {
  207. csq, _ = strconv.ParseInt(csq32, 10, 64)
  208. }
  209. }
  210. temp := float64(0)
  211. if tempInter, ok := msgData["Temp"]; ok {
  212. if tempFloat, ok := tempInter.(string); ok {
  213. temp, _ = strconv.ParseFloat(tempFloat, 64)
  214. }
  215. }
  216. imei := ""
  217. if imeiInter, ok := msgData["imei"]; ok {
  218. if imeiStr, ok := imeiInter.(string); ok {
  219. imei = imeiStr
  220. }
  221. }
  222. active := int64(0)
  223. if activeInter, ok := msgData["active"]; ok {
  224. if active32, ok := activeInter.(string); ok {
  225. active, _ = strconv.ParseInt(active32, 10, 64)
  226. }
  227. }
  228. inAction := int64(0)
  229. if inActionInter, ok := msgData["inactive"]; ok {
  230. if inAction32, ok := inActionInter.(string); ok {
  231. inAction, _ = strconv.ParseInt(inAction32, 10, 64)
  232. }
  233. }
  234. ruMina := int64(0)
  235. if ruMinaInter, ok := msgData["Rumina"]; ok {
  236. if ruMina32, ok := ruMinaInter.(string); ok {
  237. ruMina, _ = strconv.ParseInt(ruMina32, 10, 64)
  238. }
  239. }
  240. intake := int64(0)
  241. if intakeInter, ok := msgData["Intake"]; ok {
  242. if intake32, ok := intakeInter.(string); ok {
  243. intake, _ = strconv.ParseInt(intake32, 10, 64)
  244. }
  245. }
  246. gasp := int64(0)
  247. if gaspInter, ok := msgData["gasp"]; ok {
  248. if gasp32, ok := gaspInter.(string); ok {
  249. gasp, _ = strconv.ParseInt(gasp32, 10, 64)
  250. }
  251. }
  252. other := int64(0)
  253. if otherInter, ok := msgData["other"]; ok {
  254. if other32, ok := otherInter.(string); ok {
  255. other, _ = strconv.ParseInt(other32, 10, 64)
  256. }
  257. }
  258. reMain := int64(0)
  259. if reMainInter, ok := msgData["Remain"]; ok {
  260. if reMain32, ok := reMainInter.(string); ok {
  261. reMain, _ = strconv.ParseInt(reMain32, 10, 64)
  262. }
  263. }
  264. return &model.SubMsgLog{
  265. SoftVer: softVer,
  266. Uuid: uuid,
  267. FrameId: frameId,
  268. CowId: cowId,
  269. Csq: csq,
  270. Temp: int64(temp * 100),
  271. Imei: imei,
  272. Active: int32(active),
  273. InActive: int32(inAction),
  274. RuMina: int32(ruMina),
  275. Intake: int32(intake),
  276. Gasp: int32(gasp),
  277. Other: int32(other),
  278. ReMain: int32(reMain),
  279. }, nil
  280. }