sub.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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. if subMsLog != nil {
  107. batchList = append(batchList, subMsLog)
  108. }
  109. if len(batchList) >= batchSize {
  110. DSMLog.Mx.Lock()
  111. DSMLog.SubMsgLogList = append(DSMLog.SubMsgLogList, batchList...)
  112. if len(DSMLog.SubMsgLogList) >= 10 {
  113. if err := d.DB.Create(DSMLog.SubMsgLogList).Error; err != nil {
  114. zaplog.Error("subMsgChan-info", zap.Any("err", err), zap.Any("subMsgLog", DSMLog.SubMsgLogList))
  115. }
  116. DSMLog.SubMsgLogList = make([]*model.SubMsgLog, 0)
  117. }
  118. DSMLog.Mx.Unlock()
  119. batchList = batchList[:0]
  120. }
  121. // 优雅退出
  122. case <-sc:
  123. if len(DSMLog.SubMsgLogList) > 0 {
  124. DSMLog.Mx.Lock()
  125. if err := d.DB.Create(DSMLog.SubMsgLogList).Error; err != nil {
  126. zaplog.Error("subMsgChan-os", zap.Any("err", err), zap.Any("subMsgLog", DSMLog.SubMsgLogList))
  127. }
  128. zaplog.Info("subMsgChan-os", zap.Any("success", DSMLog.SubMsgLogList))
  129. DSMLog.SubMsgLogList = make([]*model.SubMsgLog, 0)
  130. DSMLog.Mx.Unlock()
  131. }
  132. close(subMsgChan)
  133. case <-tc:
  134. if len(DSMLog.SubMsgLogList) > 0 {
  135. DSMLog.Mx.Lock()
  136. if err := d.DB.Create(DSMLog.SubMsgLogList).Error; err != nil {
  137. zaplog.Error("subMsgChan-os", zap.Any("err", err), zap.Any("subMsgLog", DSMLog.SubMsgLogList))
  138. }
  139. zaplog.Info("subMsgChan-os", zap.Any("success", DSMLog.SubMsgLogList))
  140. DSMLog.SubMsgLogList = make([]*model.SubMsgLog, 0)
  141. DSMLog.Mx.Unlock()
  142. }
  143. }
  144. }
  145. //}()
  146. //}
  147. }
  148. func (d *DataEventEntry) CreatMsgLog(msg []byte) *model.SubMsgLog {
  149. defer func() {
  150. if time.Now().Day()%15 == 0 {
  151. d.DB.Model(new(model.SubMsgLog)).Where("created_at < ?", time.Now().AddDate(0, 0, -15).Unix()).Delete(new(model.SubMsgLog))
  152. return
  153. }
  154. }()
  155. subMsgLog, err := d.MsgDataFormat(msg)
  156. if err != nil {
  157. zaplog.Error("CreatMsgLog", zap.Any("err", err), zap.Any("msg", string(msg)))
  158. }
  159. if subMsgLog == nil {
  160. return nil
  161. }
  162. if subMsgLog.Imei == "" {
  163. zaplog.Info("CreatMsgLog", zap.Any("msg", string(msg)), zap.Any("subMsgLog", subMsgLog))
  164. return nil
  165. }
  166. return subMsgLog
  167. }
  168. func (d *DataEventEntry) MsgDataFormat(msg []byte) (*model.SubMsgLog, error) {
  169. msgData := make(map[string]interface{})
  170. pairs := strings.Split(util.MsgFormat(string(msg)), " ")
  171. for _, pair := range pairs {
  172. parts := strings.SplitN(pair, ":", 2)
  173. if len(parts) != 2 {
  174. continue
  175. }
  176. key, value := parts[0], parts[1]
  177. if len(key) == 0 {
  178. continue
  179. }
  180. msgData[key] = value
  181. }
  182. softVer := int64(0)
  183. if softVerInter, ok := msgData["SOFT_VER"]; ok {
  184. if softVerstr, ok := softVerInter.(string); ok {
  185. softVer, _ = strconv.ParseInt(softVerstr, 10, 64)
  186. }
  187. }
  188. uuid := ""
  189. if uuidInter, ok := msgData["uuid"]; ok {
  190. if uuidStr, ok := uuidInter.(string); ok {
  191. uuid = uuidStr
  192. }
  193. }
  194. frameId := int64(0)
  195. if frameIdInter, ok := msgData["frameid"]; ok {
  196. if frameId64, ok := frameIdInter.(string); ok {
  197. frameId, _ = strconv.ParseInt(frameId64, 10, 64)
  198. }
  199. }
  200. cowId := ""
  201. if cowIdInter, ok := msgData["cowid"]; ok {
  202. if cowIdStr, ok := cowIdInter.(string); ok {
  203. cowId = cowIdStr
  204. }
  205. }
  206. csq := int64(0)
  207. if csqInter, ok := msgData["csq"]; ok {
  208. if csq32, ok := csqInter.(string); ok {
  209. csq, _ = strconv.ParseInt(csq32, 10, 64)
  210. }
  211. }
  212. temp := float64(0)
  213. if tempInter, ok := msgData["Temp"]; ok {
  214. if tempFloat, ok := tempInter.(string); ok {
  215. temp, _ = strconv.ParseFloat(tempFloat, 64)
  216. }
  217. }
  218. imei := ""
  219. if imeiInter, ok := msgData["imei"]; ok {
  220. if imeiStr, ok := imeiInter.(string); ok {
  221. imei = imeiStr
  222. }
  223. }
  224. active := int64(0)
  225. if activeInter, ok := msgData["active"]; ok {
  226. if active32, ok := activeInter.(string); ok {
  227. active, _ = strconv.ParseInt(active32, 10, 64)
  228. }
  229. }
  230. inAction := int64(0)
  231. if inActionInter, ok := msgData["inactive"]; ok {
  232. if inAction32, ok := inActionInter.(string); ok {
  233. inAction, _ = strconv.ParseInt(inAction32, 10, 64)
  234. }
  235. }
  236. ruMina := int64(0)
  237. if ruMinaInter, ok := msgData["Rumina"]; ok {
  238. if ruMina32, ok := ruMinaInter.(string); ok {
  239. ruMina, _ = strconv.ParseInt(ruMina32, 10, 64)
  240. }
  241. }
  242. intake := int64(0)
  243. if intakeInter, ok := msgData["Intake"]; ok {
  244. if intake32, ok := intakeInter.(string); ok {
  245. intake, _ = strconv.ParseInt(intake32, 10, 64)
  246. }
  247. }
  248. gasp := int64(0)
  249. if gaspInter, ok := msgData["gasp"]; ok {
  250. if gasp32, ok := gaspInter.(string); ok {
  251. gasp, _ = strconv.ParseInt(gasp32, 10, 64)
  252. }
  253. }
  254. other := int64(0)
  255. if otherInter, ok := msgData["other"]; ok {
  256. if other32, ok := otherInter.(string); ok {
  257. other, _ = strconv.ParseInt(other32, 10, 64)
  258. }
  259. }
  260. reMain := int64(0)
  261. if reMainInter, ok := msgData["Remain"]; ok {
  262. if reMain32, ok := reMainInter.(string); ok {
  263. reMain, _ = strconv.ParseInt(reMain32, 10, 64)
  264. }
  265. }
  266. return &model.SubMsgLog{
  267. SoftVer: softVer,
  268. Uuid: uuid,
  269. FrameId: frameId,
  270. CowId: cowId,
  271. Csq: csq,
  272. Temp: int64(temp * 100),
  273. Imei: imei,
  274. Active: int32(active),
  275. InActive: int32(inAction),
  276. RuMina: int32(ruMina),
  277. Intake: int32(intake),
  278. Gasp: int32(gasp),
  279. Other: int32(other),
  280. ReMain: int32(reMain),
  281. }, nil
  282. }