sub.go 6.9 KB

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