merge_handle.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. package mqtt
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "kpt-pasture/model"
  6. "kpt-pasture/util"
  7. "strconv"
  8. "strings"
  9. "time"
  10. pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
  11. "github.com/jinzhu/copier"
  12. "gitee.com/xuyiping_admin/pkg/logger/zaplog"
  13. "gitee.com/xuyiping_admin/pkg/xerr"
  14. "go.uber.org/zap"
  15. "gorm.io/gorm"
  16. )
  17. type DataInsertNeckRingLog struct {
  18. NeckRingOriginalData []*model.NeckRingOriginal
  19. NeckRingErrorData []*model.NeckRingError
  20. }
  21. var (
  22. batchSize = 10
  23. batchList = make([]*model.NeckRingOriginal, 0, batchSize)
  24. defaultLimit = int32(1000)
  25. DSMLog = &DataInsertNeckRingLog{
  26. NeckRingOriginalData: make([]*model.NeckRingOriginal, 0),
  27. NeckRingErrorData: make([]*model.NeckRingError, 0),
  28. }
  29. isDelete bool
  30. pastureMqttMap = make(map[string]int64)
  31. isFindPastureMqttMap bool
  32. )
  33. func (e *Entry) NeckRingHandle(data []byte) {
  34. newData := e.MsgDataFormat2(data)
  35. if newData == nil {
  36. return
  37. }
  38. if len(newData.NeckRingErrorData) > 0 || len(newData.NeckRingOriginalData) > 0 {
  39. // 写入数据
  40. if err := e.CreatedData(newData); err != nil {
  41. zaplog.Error("Failed to create data", zap.Any("err", err), zap.Any("dataList", newData))
  42. }
  43. }
  44. return
  45. }
  46. // NeckRingOriginalMergeData 把脖环数据合并成2个小时的
  47. func (e *Entry) NeckRingOriginalMergeData() {
  48. var err error
  49. limit := e.Cfg.NeckRingLimit
  50. if limit <= 0 {
  51. limit = defaultLimit
  52. }
  53. mergeDataMaxId := e.GetSystemConfigure(model.UpdateOriginalMax).Value
  54. newTime := time.Now()
  55. createdAt := newTime.Add(-1 * time.Hour)
  56. neckRingList := make([]*model.NeckRingOriginal, 0)
  57. if err = e.DB.Model(new(model.NeckRingOriginal)).
  58. Where("is_show <= ?", pasturePb.IsShow_No).
  59. Where("created_at <= ?", createdAt.Unix()).
  60. Order("neck_ring_number,active_date,frameid").
  61. Limit(int(limit)).Find(&neckRingList).Error; err != nil {
  62. return
  63. }
  64. if len(neckRingList) <= 0 {
  65. return
  66. }
  67. if neckRingList[len(neckRingList)-1].Id <= mergeDataMaxId {
  68. return
  69. }
  70. defer func() {
  71. newMergeDataMaxId := neckRingList[len(neckRingList)-1].Id
  72. if newMergeDataMaxId > 0 && newMergeDataMaxId > mergeDataMaxId {
  73. e.DB.Model(new(model.SystemConfigure)).
  74. Where("name = ?", model.UpdateOriginalMax).
  75. Update("value", newMergeDataMaxId)
  76. e.DB.Model(new(model.NeckRingOriginal)).
  77. Where("id BETWEEN ? AND ?", mergeDataMaxId, newMergeDataMaxId).
  78. Update("is_show", pasturePb.IsShow_Ok)
  79. }
  80. if newTime.Day()%15 == 0 && !isDelete {
  81. // 原始数据删除15天前的
  82. e.DB.Model(new(model.NeckRingOriginal)).
  83. Where("created_at < ?", newTime.AddDate(0, 0, -15).Unix()).
  84. Delete(new(model.NeckRingOriginal))
  85. // 活动数据删除6个月前的数据
  86. e.DB.Model(new(model.NeckActiveHabit)).
  87. Where("created_at < ?", newTime.AddDate(0, -6, 0).Unix()).
  88. Delete(new(model.NeckActiveHabit))
  89. isDelete = true
  90. }
  91. }()
  92. // 计算合并
  93. neckActiveHabitList := e.recalculate(neckRingList)
  94. if len(neckActiveHabitList) <= 0 {
  95. return
  96. }
  97. if err = e.DB.Transaction(func(tx *gorm.DB) error {
  98. for _, neckActiveHabit := range neckActiveHabitList {
  99. //更新脖环牛只相关信息 新数据直接插入
  100. historyNeckActiveHabit, ct := e.IsExistNeckActiveHabit(neckActiveHabit.NeckRingNumber, neckActiveHabit.HeatDate, neckActiveHabit.Frameid)
  101. if ct <= 0 {
  102. // 过滤牛只未绑定的脖环的数据
  103. cowInfo := e.GetCowInfoByNeckRingNumber(neckActiveHabit.PastureId, neckActiveHabit.NeckRingNumber)
  104. if cowInfo == nil || cowInfo.Id <= 0 {
  105. continue
  106. }
  107. neckActiveHabit.CowId = cowInfo.Id
  108. neckActiveHabit.Lact = cowInfo.Lact
  109. neckActiveHabit.CalvingAge = int32(cowInfo.CalvingAge)
  110. if err = tx.Create(neckActiveHabit).Error; err != nil {
  111. return xerr.WithStack(err)
  112. }
  113. newNeckRingProcess := model.NewNeckRingProcess(neckActiveHabit)
  114. if err = tx.Create(newNeckRingProcess).Error; err != nil {
  115. return xerr.WithStack(err)
  116. }
  117. if err = e.UpdateNeckRingOriginalIsShow(neckActiveHabit); err != nil {
  118. zaplog.Error("UpdateNeckRingOriginalIsShow", zap.Any("err", err), zap.Any("neckActiveHabit", neckActiveHabit))
  119. }
  120. continue
  121. }
  122. if historyNeckActiveHabit == nil || historyNeckActiveHabit.Id <= 0 {
  123. zaplog.Error("NeckRingOriginalMergeData", zap.Any("historyNeckActiveHabit", historyNeckActiveHabit), zap.Any("ct", ct), zap.Any("neckActiveHabit", neckActiveHabit))
  124. continue
  125. }
  126. // 重新计算
  127. newNeckActiveHabit := e.againRecalculate(historyNeckActiveHabit)
  128. if newNeckActiveHabit != nil {
  129. if err = tx.Model(new(model.NeckActiveHabit)).
  130. Select("rumina", "intake", "inactive", "gasp", "other", "high", "active").
  131. Where("id = ?", historyNeckActiveHabit.Id).
  132. Updates(newNeckActiveHabit).Error; err != nil {
  133. return xerr.WithStack(err)
  134. }
  135. }
  136. }
  137. return nil
  138. }); err != nil {
  139. zaplog.Error("NeckRingOriginalMergeData", zap.Any("transaction", err))
  140. return
  141. }
  142. }
  143. func (e *Entry) FindPastureMqttMap() map[string]int64 {
  144. if isFindPastureMqttMap {
  145. return pastureMqttMap
  146. }
  147. appMqttList := make([]*model.AppMqtt, 0)
  148. if err := e.DB.Model(new(model.AppMqtt)).Find(&appMqttList).Error; err != nil {
  149. zaplog.Error("FindPastureMqttMap", zap.Any("err", err))
  150. }
  151. for _, v := range appMqttList {
  152. pastureMqttMap[v.ReceiveNumber] = v.PastureId
  153. }
  154. isFindPastureMqttMap = true
  155. return pastureMqttMap
  156. }
  157. // 处理批量数据
  158. func (e *Entry) processBatch(batchList []*model.NeckRingOriginal) {
  159. // 初始化分类数据
  160. var (
  161. errorData []*model.NeckRingError
  162. originalData []*model.NeckRingOriginal
  163. )
  164. // 分类数据
  165. for _, batch := range batchList {
  166. // 异常脖环数据
  167. if ok := util.IsValidFrameId(batch.Frameid); !ok {
  168. var ed model.NeckRingError
  169. err := copier.Copy(&ed, &batch)
  170. if err != nil {
  171. zaplog.Error("processBatch", zap.Any("copier", err), zap.Any("data", batch))
  172. continue
  173. }
  174. errorData = append(errorData, &ed)
  175. } else {
  176. originalData = append(originalData, batch)
  177. }
  178. }
  179. // 更新日志
  180. DSMLog.NeckRingErrorData = append(DSMLog.NeckRingErrorData, errorData...)
  181. DSMLog.NeckRingOriginalData = append(DSMLog.NeckRingOriginalData, originalData...)
  182. // 写入数据
  183. if err := e.CreatedData(DSMLog); err != nil {
  184. zaplog.Error("Failed to create data", zap.Any("err", err), zap.Any("dataList", DSMLog))
  185. }
  186. // 清空日志
  187. DSMLog.NeckRingErrorData = DSMLog.NeckRingErrorData[:0]
  188. DSMLog.NeckRingOriginalData = DSMLog.NeckRingOriginalData[:0]
  189. }
  190. func (e *Entry) CreatedData(DSMLog *DataInsertNeckRingLog) error {
  191. if err := e.DB.Transaction(func(tx *gorm.DB) error {
  192. if len(DSMLog.NeckRingErrorData) > 0 {
  193. if err := e.DB.Model(new(model.NeckRingError)).Create(DSMLog.NeckRingErrorData).Error; err != nil {
  194. return xerr.WithStack(err)
  195. }
  196. }
  197. if len(DSMLog.NeckRingOriginalData) > 0 {
  198. if err := e.DB.Model(new(model.NeckRingOriginal)).Create(DSMLog.NeckRingOriginalData).Error; err != nil {
  199. return xerr.WithStack(err)
  200. }
  201. }
  202. return nil
  203. }); err != nil {
  204. return xerr.WithStack(err)
  205. }
  206. return nil
  207. }
  208. func (e *Entry) MsgDataFormat2(msg []byte) *DataInsertNeckRingLog {
  209. neckLogList := &model.NeckRingWrapper{}
  210. if err := json.Unmarshal(msg, neckLogList); err != nil {
  211. zaplog.Error("MsgDataFormat", zap.Any("err", err), zap.Any("msg", string(msg)))
  212. return nil
  213. }
  214. if neckLogList.Type == "heartbeat" {
  215. return nil
  216. }
  217. normalOriginal := make([]*model.NeckRingOriginal, 0)
  218. errorOriginal := make([]*model.NeckRingError, 0)
  219. pastureMqttMap = e.FindPastureMqttMap()
  220. for _, neckLog := range neckLogList.NeckRing.NeckPck {
  221. newOriginal := model.NewNeckRingOriginal(neckLog, pastureMqttMap)
  222. if ok := util.IsValidFrameId(neckLog.Frameid); !ok {
  223. var ed model.NeckRingError
  224. if err := copier.Copy(&ed, &newOriginal); err != nil {
  225. zaplog.Error("MsgDataFormat2", zap.Any("copier", err), zap.Any("neckLog", neckLog))
  226. continue
  227. }
  228. errorOriginal = append(errorOriginal, &ed)
  229. } else {
  230. activeDate, hours := util.GetNeckRingActiveTimer(neckLog.Frameid)
  231. newOriginal.ActiveDate = activeDate
  232. newOriginal.Hours = int32(hours)
  233. normalOriginal = append(normalOriginal, newOriginal)
  234. }
  235. }
  236. return &DataInsertNeckRingLog{
  237. NeckRingErrorData: errorOriginal,
  238. NeckRingOriginalData: normalOriginal,
  239. }
  240. }
  241. // recalculate 合并计算
  242. func (e *Entry) recalculate(neckRingList []*model.NeckRingOriginal) []*model.NeckActiveHabit {
  243. originalMapData := make(map[string]*model.NeckRingOriginalMerge)
  244. // 合并成2个小时的
  245. for _, v := range neckRingList {
  246. xframeId := util.XFrameId(v.Frameid)
  247. mapKey := fmt.Sprintf("%s%s%s%s%d", v.NeckRingNumber, model.JoinKey, v.ActiveDate, model.JoinKey, xframeId) // 0001/2023-12-04/0 0001/2023-12-03/4
  248. if originalMapData[mapKey] == nil {
  249. originalMapData[mapKey] = new(model.NeckRingOriginalMerge)
  250. }
  251. originalMapData[mapKey].IsMageData(v, xframeId)
  252. }
  253. // 算平均值
  254. for k, v := range originalMapData {
  255. // 过滤掉合并后不满6条数据
  256. if v.RecordCount != 6 {
  257. maxFrameId := e.CurrentMaxXFrameId(v.NeckRingNumber, v.ActiveDate)
  258. currXframeId := util.XFrameId(maxFrameId)
  259. if currXframeId-v.XframeId <= 1 {
  260. delete(originalMapData, k)
  261. }
  262. }
  263. v.SumAvg()
  264. }
  265. return model.NeckRingOriginalMap(originalMapData).ForMatData()
  266. }
  267. func (e *Entry) againRecalculate(data *model.NeckActiveHabit) *model.NeckActiveHabit {
  268. originalList := make([]*model.NeckRingOriginal, 0)
  269. frameIds := util.FrameIds(data.Frameid)
  270. if err := e.DB.Model(new(model.NeckRingOriginal)).
  271. Where("neck_ring_number = ?", data.NeckRingNumber).
  272. Where("active_date = ?", data.HeatDate).
  273. Where("frameid IN (?)", frameIds).
  274. Find(&originalList).Error; err != nil {
  275. return nil
  276. }
  277. newDataList := e.recalculate(originalList)
  278. if len(newDataList) != 1 {
  279. return nil
  280. }
  281. return newDataList[0]
  282. }
  283. // CurrentMaxXFrameId 当前最大frameid
  284. func (e *Entry) CurrentMaxXFrameId(neckRingNumber, activeDate string) (frameid int32) {
  285. type Fm struct {
  286. Frameid int32
  287. }
  288. maxFx := &Fm{}
  289. if err := e.DB.Model(new(model.NeckRingOriginal)).
  290. Select("frameid").
  291. Where("neck_ring_number = ?", neckRingNumber).
  292. Where("active_date = ?", activeDate).
  293. Order("frameid DESC").First(maxFx).Error; err != nil {
  294. zaplog.Error("CurrentMaxXFrameId", zap.Any("err", err))
  295. return 0
  296. }
  297. return maxFx.Frameid
  298. }
  299. func (e *Entry) UpdateNeckRingOriginalIsShow(neckRingList *model.NeckActiveHabit) error {
  300. if err := e.DB.Model(new(model.NeckRingOriginal)).
  301. Where("neck_ring_number = ?", neckRingList.NeckRingNumber).
  302. Where("active_date = ?", neckRingList.HeatDate).
  303. Where("frameid IN (?)", util.FrameIds(neckRingList.Frameid)).
  304. Update("is_show", pasturePb.IsShow_Ok).Error; err != nil {
  305. return xerr.WithStack(err)
  306. }
  307. return nil
  308. }
  309. func (e *Entry) MsgDataFormat(msg []byte) []*model.NeckRingOriginal {
  310. msgData := make(map[string]interface{})
  311. pairs := strings.Split(util.MsgFormat(string(msg)), " ")
  312. for _, pair := range pairs {
  313. parts := strings.SplitN(pair, ":", 2)
  314. if len(parts) != 2 {
  315. continue
  316. }
  317. key, value := parts[0], parts[1]
  318. if len(key) == 0 {
  319. continue
  320. }
  321. msgData[key] = value
  322. }
  323. softVer := int64(0)
  324. if softVerInter, ok := msgData["SOFT_VER"]; ok {
  325. if softVerstr, ok := softVerInter.(string); ok {
  326. softVer, _ = strconv.ParseInt(softVerstr, 10, 64)
  327. }
  328. }
  329. if softVer <= 0 {
  330. if softVerInter, ok := msgData["soft_ver"]; ok {
  331. if softVerstr, ok := softVerInter.(string); ok {
  332. softVer, _ = strconv.ParseInt(softVerstr, 10, 64)
  333. }
  334. }
  335. }
  336. uuid := ""
  337. if uuidInter, ok := msgData["uuid"]; ok {
  338. if uuidStr, ok := uuidInter.(string); ok {
  339. uuid = uuidStr
  340. }
  341. }
  342. frameId := int64(0)
  343. if frameIdInter, ok := msgData["frameid"]; ok {
  344. if frameId64, ok := frameIdInter.(string); ok {
  345. frameId, _ = strconv.ParseInt(frameId64, 10, 64)
  346. }
  347. }
  348. temp := float64(0)
  349. if tempInter, ok := msgData["Temp"]; ok {
  350. if tempFloat, ok := tempInter.(string); ok {
  351. temp, _ = strconv.ParseFloat(tempFloat, 64)
  352. }
  353. }
  354. if temp <= 0 {
  355. if tempInter, ok := msgData["temp"]; ok {
  356. if tempFloat, ok := tempInter.(string); ok {
  357. temp, _ = strconv.ParseFloat(tempFloat, 64)
  358. }
  359. }
  360. }
  361. imei := ""
  362. if imeiInter, ok := msgData["imei"]; ok {
  363. if imeiStr, ok := imeiInter.(string); ok {
  364. imei = imeiStr
  365. }
  366. }
  367. active := int64(0)
  368. if activeInter, ok := msgData["active"]; ok {
  369. if active32, ok := activeInter.(string); ok {
  370. active, _ = strconv.ParseInt(active32, 10, 64)
  371. }
  372. }
  373. inAction := int64(0)
  374. if inActionInter, ok := msgData["inactive"]; ok {
  375. if inAction32, ok := inActionInter.(string); ok {
  376. inAction, _ = strconv.ParseInt(inAction32, 10, 64)
  377. }
  378. }
  379. ruMina := int64(0)
  380. if ruMinaInter, ok := msgData["Rumina"]; ok {
  381. if ruMina32, ok := ruMinaInter.(string); ok {
  382. ruMina, _ = strconv.ParseInt(ruMina32, 10, 64)
  383. }
  384. }
  385. if ruMina <= 0 {
  386. if ruMinaInter, ok := msgData["rumina"]; ok {
  387. if ruMina32, ok := ruMinaInter.(string); ok {
  388. ruMina, _ = strconv.ParseInt(ruMina32, 10, 64)
  389. }
  390. }
  391. }
  392. intake := int64(0)
  393. if intakeInter, ok := msgData["Intake"]; ok {
  394. if intake32, ok := intakeInter.(string); ok {
  395. intake, _ = strconv.ParseInt(intake32, 10, 64)
  396. }
  397. }
  398. if intake <= 0 {
  399. if intakeInter, ok := msgData["intake"]; ok {
  400. if intake32, ok := intakeInter.(string); ok {
  401. intake, _ = strconv.ParseInt(intake32, 10, 64)
  402. }
  403. }
  404. }
  405. gasp := int64(0)
  406. if gaspInter, ok := msgData["gasp"]; ok {
  407. if gasp32, ok := gaspInter.(string); ok {
  408. gasp, _ = strconv.ParseInt(gasp32, 10, 64)
  409. }
  410. }
  411. reMain := int64(0)
  412. if reMainInter, ok := msgData["Remain"]; ok {
  413. if reMain32, ok := reMainInter.(string); ok {
  414. reMain, _ = strconv.ParseInt(reMain32, 10, 64)
  415. }
  416. }
  417. if ruMina <= 0 {
  418. if reMainInter, ok := msgData["remain"]; ok {
  419. if reMain32, ok := reMainInter.(string); ok {
  420. reMain, _ = strconv.ParseInt(reMain32, 10, 64)
  421. }
  422. }
  423. }
  424. /*cowId := ""
  425. if cowIdInter, ok := msgData["cowid"]; ok {
  426. if cowIdStr, ok := cowIdInter.(string); ok {
  427. cowId = cowIdStr
  428. }
  429. }
  430. csq := int64(0)
  431. if csqInter, ok := msgData["csq"]; ok {
  432. if csq32, ok := csqInter.(string); ok {
  433. csq, _ = strconv.ParseInt(csq32, 10, 64)
  434. }
  435. }
  436. other := int64(0)
  437. if otherInter, ok := msgData["other"]; ok {
  438. if other32, ok := otherInter.(string); ok {
  439. other, _ = strconv.ParseInt(other32, 10, 64)
  440. }
  441. }
  442. nccId := ""
  443. if nccIdInter, ok := msgData["nccid"]; ok {
  444. if nccIdStr, ok := nccIdInter.(string); ok {
  445. nccId = nccIdStr
  446. }
  447. }
  448. */
  449. return []*model.NeckRingOriginal{
  450. {
  451. FirmwareVersion: int32(softVer),
  452. Uuid: uuid,
  453. Frameid: int32(frameId),
  454. ReceiveNumber: imei,
  455. Active: int32(active),
  456. Inactive: int32(inAction),
  457. Rumina: int32(ruMina),
  458. Intake: int32(intake),
  459. Gasp: int32(gasp),
  460. Remain: int32(reMain),
  461. },
  462. }
  463. }