sub.go 8.6 KB

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