sub.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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. //for i := 0; i < int(configOption.WorkNumber); i++ {
  60. //go func() {
  61. for {
  62. select {
  63. case msg := <-subMsgChan:
  64. subMsLog := d.CreatMsgLog(msg)
  65. batchList = append(batchList, subMsLog)
  66. if len(batchList) >= batchSize {
  67. DSMLog.Mx.Lock()
  68. DSMLog.SubMsgLogList = append(DSMLog.SubMsgLogList, batchList...)
  69. if len(DSMLog.SubMsgLogList) >= 10 {
  70. if err := d.DB.Create(DSMLog.SubMsgLogList).Error; err != nil {
  71. zaplog.Error("subMsgChan-info", zap.Any("err", err), zap.Any("subMsgLog", DSMLog.SubMsgLogList))
  72. }
  73. DSMLog.SubMsgLogList = make([]*model.SubMsgLog, 0)
  74. }
  75. DSMLog.Mx.Unlock()
  76. batchList = batchList[:0]
  77. }
  78. // 优雅退出
  79. case <-sc:
  80. if len(DSMLog.SubMsgLogList) > 0 {
  81. DSMLog.Mx.Lock()
  82. if err := d.DB.Create(DSMLog.SubMsgLogList).Error; err != nil {
  83. zaplog.Error("subMsgChan-os", zap.Any("err", err), zap.Any("subMsgLog", DSMLog.SubMsgLogList))
  84. }
  85. zaplog.Info("subMsgChan-os", zap.Any("success", DSMLog.SubMsgLogList))
  86. DSMLog.SubMsgLogList = make([]*model.SubMsgLog, 0)
  87. DSMLog.Mx.Unlock()
  88. }
  89. close(subMsgChan)
  90. }
  91. }
  92. //}()
  93. //}
  94. }
  95. func (d *DataEventEntry) CreatMsgLog(msg []byte) *model.SubMsgLog {
  96. defer func() {
  97. if time.Now().Day()%15 == 0 {
  98. d.DB.Model(new(model.SubMsgLog)).Where("created_at < ?", time.Now().AddDate(0, 0, -15).Unix()).Delete(new(model.SubMsgLog))
  99. return
  100. }
  101. }()
  102. subMsgLog, err := d.MsgDataFormat(msg)
  103. if err != nil {
  104. zaplog.Error("CreatMsgLog", zap.Any("err", err), zap.Any("msg", string(msg)))
  105. }
  106. if subMsgLog == nil {
  107. return nil
  108. }
  109. if subMsgLog.Imei == "" {
  110. zaplog.Info("CreatMsgLog", zap.Any("msg", string(msg)), zap.Any("subMsgLog", subMsgLog))
  111. return nil
  112. }
  113. return subMsgLog
  114. }
  115. func (d *DataEventEntry) MsgDataFormat(msg []byte) (*model.SubMsgLog, error) {
  116. msgData := make(map[string]interface{})
  117. pairs := strings.Split(util.MsgFormat(string(msg)), " ")
  118. for _, pair := range pairs {
  119. parts := strings.SplitN(pair, ":", 2)
  120. if len(parts) != 2 {
  121. continue
  122. }
  123. key, value := parts[0], parts[1]
  124. if len(key) == 0 {
  125. continue
  126. }
  127. msgData[key] = value
  128. }
  129. softVer := int64(0)
  130. if softVerInter, ok := msgData["SOFT_VER"]; ok {
  131. if softVerstr, ok := softVerInter.(string); ok {
  132. softVer, _ = strconv.ParseInt(softVerstr, 10, 64)
  133. }
  134. }
  135. uuid := ""
  136. if uuidInter, ok := msgData["uuid"]; ok {
  137. if uuidStr, ok := uuidInter.(string); ok {
  138. uuid = uuidStr
  139. }
  140. }
  141. frameId := int64(0)
  142. if frameIdInter, ok := msgData["frameid"]; ok {
  143. if frameId64, ok := frameIdInter.(string); ok {
  144. frameId, _ = strconv.ParseInt(frameId64, 10, 64)
  145. }
  146. }
  147. cowId := ""
  148. if cowIdInter, ok := msgData["cowid"]; ok {
  149. if cowIdStr, ok := cowIdInter.(string); ok {
  150. cowId = cowIdStr
  151. }
  152. }
  153. csq := int64(0)
  154. if csqInter, ok := msgData["csq"]; ok {
  155. if csq32, ok := csqInter.(string); ok {
  156. csq, _ = strconv.ParseInt(csq32, 10, 64)
  157. }
  158. }
  159. temp := float64(0)
  160. if tempInter, ok := msgData["Temp"]; ok {
  161. if tempFloat, ok := tempInter.(string); ok {
  162. temp, _ = strconv.ParseFloat(tempFloat, 64)
  163. }
  164. }
  165. imei := ""
  166. if imeiInter, ok := msgData["imei"]; ok {
  167. if imeiStr, ok := imeiInter.(string); ok {
  168. imei = imeiStr
  169. }
  170. }
  171. active := int64(0)
  172. if activeInter, ok := msgData["active"]; ok {
  173. if active32, ok := activeInter.(string); ok {
  174. active, _ = strconv.ParseInt(active32, 10, 64)
  175. }
  176. }
  177. inAction := int64(0)
  178. if inActionInter, ok := msgData["inactive"]; ok {
  179. if inAction32, ok := inActionInter.(string); ok {
  180. inAction, _ = strconv.ParseInt(inAction32, 10, 64)
  181. }
  182. }
  183. ruMina := int64(0)
  184. if ruMinaInter, ok := msgData["Rumina"]; ok {
  185. if ruMina32, ok := ruMinaInter.(string); ok {
  186. ruMina, _ = strconv.ParseInt(ruMina32, 10, 64)
  187. }
  188. }
  189. intake := int64(0)
  190. if intakeInter, ok := msgData["Intake"]; ok {
  191. if intake32, ok := intakeInter.(string); ok {
  192. intake, _ = strconv.ParseInt(intake32, 10, 64)
  193. }
  194. }
  195. gasp := int64(0)
  196. if gaspInter, ok := msgData["gasp"]; ok {
  197. if gasp32, ok := gaspInter.(string); ok {
  198. gasp, _ = strconv.ParseInt(gasp32, 10, 64)
  199. }
  200. }
  201. other := int64(0)
  202. if otherInter, ok := msgData["other"]; ok {
  203. if other32, ok := otherInter.(string); ok {
  204. other, _ = strconv.ParseInt(other32, 10, 64)
  205. }
  206. }
  207. reMain := int64(0)
  208. if reMainInter, ok := msgData["Remain"]; ok {
  209. if reMain32, ok := reMainInter.(string); ok {
  210. reMain, _ = strconv.ParseInt(reMain32, 10, 64)
  211. }
  212. }
  213. return &model.SubMsgLog{
  214. SoftVer: softVer,
  215. Uuid: uuid,
  216. FrameId: frameId,
  217. CowId: cowId,
  218. Csq: csq,
  219. Temp: int64(temp * 100),
  220. Imei: imei,
  221. Active: int32(active),
  222. InActive: int32(inAction),
  223. RuMina: int32(ruMina),
  224. Intake: int32(intake),
  225. Gasp: int32(gasp),
  226. Other: int32(other),
  227. ReMain: int32(reMain),
  228. }, nil
  229. }