sub.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. package mqtt
  2. import (
  3. "fmt"
  4. "kpt-pasture/config"
  5. "kpt-pasture/model"
  6. "kpt-pasture/util"
  7. "strconv"
  8. "strings"
  9. "sync"
  10. "time"
  11. pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
  12. "gitee.com/xuyiping_admin/pkg/logger/zaplog"
  13. golangMqtt "github.com/eclipse/paho.mqtt.golang"
  14. "go.uber.org/zap"
  15. )
  16. var messagePubHandler golangMqtt.MessageHandler = func(client golangMqtt.Client, msg golangMqtt.Message) {
  17. zaplog.Info("messagePubHandlerReceived", zap.Any("message", string(msg.Payload())), zap.Any("topic", msg.Topic()))
  18. }
  19. var connectHandler golangMqtt.OnConnectHandler = func(client golangMqtt.Client) {
  20. zaplog.Info("connectedClient", zap.Any("client", client))
  21. }
  22. var connectLostHandler golangMqtt.ConnectionLostHandler = func(client golangMqtt.Client, err error) {
  23. zaplog.Info("connectLost", zap.Any("err", err.Error()))
  24. }
  25. func (d *DataEventEntry) NewMqtt(conf config.MqttSetting) golangMqtt.Client {
  26. opts := golangMqtt.NewClientOptions()
  27. opts.AddBroker(fmt.Sprintf("tcp://%s:%d", conf.Broker, conf.Port))
  28. opts.SetClientID(conf.ClientId)
  29. opts.SetCleanSession(false)
  30. opts.SetUsername(conf.UserName)
  31. opts.SetPassword(conf.Password)
  32. opts.SetAutoReconnect(conf.AutoReconnect)
  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. var bufferPool = sync.Pool{
  43. New: func() interface{} {
  44. return make([]byte, 1024) // 根据实际情况调整缓冲区大小
  45. },
  46. }
  47. func (d *DataEventEntry) SubMsg(conf config.MqttSetting, client golangMqtt.Client) {
  48. var subMsgChan = make(chan []byte, 2*conf.WorkNumber)
  49. if token := client.Subscribe(conf.Topic, byte(conf.Qos), func(client golangMqtt.Client, msg golangMqtt.Message) {
  50. buffer := bufferPool.Get().([]byte)
  51. copy(buffer, msg.Payload())
  52. subMsgChan <- buffer[:len(msg.Payload())]
  53. }); token.Wait() && token.Error() != nil {
  54. close(subMsgChan)
  55. zaplog.Error("SubMsg", zap.Any("configOption", conf), zap.Any("err", token.Error()))
  56. return
  57. }
  58. defer close(subMsgChan)
  59. select {
  60. case msg := <-subMsgChan:
  61. bufferPool.Put(msg)
  62. d.ProcessMessages(msg)
  63. }
  64. }
  65. func (d *DataEventEntry) ProcessMessages(msg []byte) {
  66. neckRingOriginalData, err := d.MsgDataFormat(msg)
  67. if err != nil {
  68. zaplog.Error("MsgDataFormat", zap.Any("err", err), zap.Any("msg", string(msg)))
  69. return
  70. }
  71. if neckRingOriginalData == nil {
  72. return
  73. }
  74. if neckRingOriginalData.Imei == "" {
  75. zaplog.Info("neckRingOriginalData", zap.Any("msg", string(msg)), zap.Any("neckRingOriginalData", neckRingOriginalData))
  76. return
  77. }
  78. defer func() {
  79. if time.Now().Day()%15 == 0 {
  80. d.DB.Model(new(model.NeckRingOriginalData)).
  81. Where("created_at < ?", time.Now().AddDate(-2, 0, 0).Unix()).
  82. Delete(new(model.NeckRingOriginalData))
  83. return
  84. }
  85. }()
  86. // 计算牛只实际活动时间
  87. nowDayTime := time.Now()
  88. currHour := nowDayTime.Hour() + 2
  89. frameIdHour := neckRingOriginalData.FrameId * 2
  90. frameDayTime := fmt.Sprintf("%s %s:00:00", nowDayTime.Format(model.LayoutDate2), fmt.Sprintf("%02d", frameIdHour))
  91. if frameIdHour > int64(currHour) {
  92. frameDayTime = fmt.Sprintf("%s %s:00:00", nowDayTime.AddDate(0, 0, -1).Format(model.LayoutDate2), fmt.Sprintf("%02d", frameIdHour))
  93. }
  94. neckRingOriginalData.ActiveTime = frameDayTime
  95. if err = d.DB.Create(neckRingOriginalData).Error; err != nil {
  96. zaplog.Error("ProcessMessages", zap.Any("err", err), zap.Any("neckRingOriginalData", neckRingOriginalData))
  97. }
  98. // 更新脖环数据状态
  99. neckRingStatus := pasturePb.NeckRingStatus_Normal
  100. errorReason := ""
  101. if neckRingOriginalData.FrameId >= 11 || neckRingOriginalData.FrameId < 0 {
  102. neckRingStatus = pasturePb.NeckRingStatus_Error
  103. errorReason = "数据异常"
  104. }
  105. d.DB.Model(new(model.NeckRingLog)).
  106. Where("number = ?", neckRingOriginalData.Imei).
  107. Updates(map[string]interface{}{
  108. "status": neckRingStatus,
  109. "error_reason": errorReason,
  110. })
  111. }
  112. func (d *DataEventEntry) MsgDataFormat(msg []byte) (*model.NeckRingOriginalData, error) {
  113. msgData := make(map[string]interface{})
  114. pairs := strings.Split(util.MsgFormat(string(msg)), " ")
  115. for _, pair := range pairs {
  116. parts := strings.SplitN(pair, ":", 2)
  117. if len(parts) != 2 {
  118. continue
  119. }
  120. key, value := parts[0], parts[1]
  121. if len(key) == 0 {
  122. continue
  123. }
  124. msgData[key] = value
  125. }
  126. softVer := int64(0)
  127. if softVerInter, ok := msgData["SOFT_VER"]; ok {
  128. if softVerstr, ok := softVerInter.(string); ok {
  129. softVer, _ = strconv.ParseInt(softVerstr, 10, 64)
  130. }
  131. }
  132. uuid := ""
  133. if uuidInter, ok := msgData["uuid"]; ok {
  134. if uuidStr, ok := uuidInter.(string); ok {
  135. uuid = uuidStr
  136. }
  137. }
  138. frameId := int64(0)
  139. if frameIdInter, ok := msgData["frameid"]; ok {
  140. if frameId64, ok := frameIdInter.(string); ok {
  141. frameId, _ = strconv.ParseInt(frameId64, 10, 64)
  142. }
  143. }
  144. cowId := ""
  145. if cowIdInter, ok := msgData["cowid"]; ok {
  146. if cowIdStr, ok := cowIdInter.(string); ok {
  147. cowId = cowIdStr
  148. }
  149. }
  150. csq := int64(0)
  151. if csqInter, ok := msgData["csq"]; ok {
  152. if csq32, ok := csqInter.(string); ok {
  153. csq, _ = strconv.ParseInt(csq32, 10, 64)
  154. }
  155. }
  156. temp := float64(0)
  157. if tempInter, ok := msgData["Temp"]; ok {
  158. if tempFloat, ok := tempInter.(string); ok {
  159. temp, _ = strconv.ParseFloat(tempFloat, 64)
  160. }
  161. }
  162. imei := ""
  163. if imeiInter, ok := msgData["imei"]; ok {
  164. if imeiStr, ok := imeiInter.(string); ok {
  165. imei = imeiStr
  166. }
  167. }
  168. active := int64(0)
  169. if activeInter, ok := msgData["active"]; ok {
  170. if active32, ok := activeInter.(string); ok {
  171. active, _ = strconv.ParseInt(active32, 10, 64)
  172. }
  173. }
  174. inAction := int64(0)
  175. if inActionInter, ok := msgData["inactive"]; ok {
  176. if inAction32, ok := inActionInter.(string); ok {
  177. inAction, _ = strconv.ParseInt(inAction32, 10, 64)
  178. }
  179. }
  180. ruMina := int64(0)
  181. if ruMinaInter, ok := msgData["Rumina"]; ok {
  182. if ruMina32, ok := ruMinaInter.(string); ok {
  183. ruMina, _ = strconv.ParseInt(ruMina32, 10, 64)
  184. }
  185. }
  186. intake := int64(0)
  187. if intakeInter, ok := msgData["Intake"]; ok {
  188. if intake32, ok := intakeInter.(string); ok {
  189. intake, _ = strconv.ParseInt(intake32, 10, 64)
  190. }
  191. }
  192. gasp := int64(0)
  193. if gaspInter, ok := msgData["gasp"]; ok {
  194. if gasp32, ok := gaspInter.(string); ok {
  195. gasp, _ = strconv.ParseInt(gasp32, 10, 64)
  196. }
  197. }
  198. other := int64(0)
  199. if otherInter, ok := msgData["other"]; ok {
  200. if other32, ok := otherInter.(string); ok {
  201. other, _ = strconv.ParseInt(other32, 10, 64)
  202. }
  203. }
  204. reMain := int64(0)
  205. if reMainInter, ok := msgData["Remain"]; ok {
  206. if reMain32, ok := reMainInter.(string); ok {
  207. reMain, _ = strconv.ParseInt(reMain32, 10, 64)
  208. }
  209. }
  210. return &model.NeckRingOriginalData{
  211. SoftVer: softVer,
  212. Uuid: uuid,
  213. FrameId: frameId,
  214. CowId: cowId,
  215. Csq: csq,
  216. Temp: int64(temp * 100),
  217. Imei: imei,
  218. Active: int32(active),
  219. InActive: int32(inAction),
  220. RuMina: int32(ruMina),
  221. Intake: int32(intake),
  222. Gasp: int32(gasp),
  223. Other: int32(other),
  224. ReMain: int32(reMain),
  225. IsShow: pasturePb.IsShow_No,
  226. }, nil
  227. }