merge_handle.go 13 KB

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