sub.go 7.2 KB

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