handle.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. package mqtt
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "kpt-pasture/model"
  6. "kpt-pasture/util"
  7. "math"
  8. "strconv"
  9. "strings"
  10. "sync"
  11. "time"
  12. "github.com/jinzhu/copier"
  13. pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
  14. "gitee.com/xuyiping_admin/pkg/logger/zaplog"
  15. "gitee.com/xuyiping_admin/pkg/xerr"
  16. "go.uber.org/zap"
  17. "gorm.io/gorm"
  18. )
  19. type DataInsertNeckRingLog struct {
  20. NeckRingOriginalData []*model.NeckRingOriginal
  21. NeckRingErrorData []*model.NeckRingError
  22. NeckRingUnRegisterData []*model.NeckRingUnRegister
  23. Mx *sync.RWMutex
  24. }
  25. var (
  26. batchSize = 10
  27. batchList = make([]*model.NeckRingOriginal, 0, batchSize)
  28. DefaultLimit = int32(10000)
  29. DSMLog = &DataInsertNeckRingLog{
  30. NeckRingOriginalData: make([]*model.NeckRingOriginal, 0),
  31. NeckRingErrorData: make([]*model.NeckRingError, 0),
  32. NeckRingUnRegisterData: make([]*model.NeckRingUnRegister, 0),
  33. Mx: &sync.RWMutex{},
  34. }
  35. )
  36. func (e *Entry) NeckRingHandle(data []byte) {
  37. newData := e.MsgDataFormat2(data)
  38. if newData == nil || len(newData) <= 0 {
  39. return
  40. }
  41. zaplog.Info("NeckRingHandle", zap.Any("data", newData), zap.Any("original", string(data)), zap.Any("time", time.Now().Unix()))
  42. batchList = append(batchList, newData...)
  43. if len(batchList) >= batchSize {
  44. e.processBatch(batchList)
  45. batchList = batchList[:0] // 清空 batchList
  46. }
  47. }
  48. // 处理批量数据
  49. func (e *Entry) processBatch(batchList []*model.NeckRingOriginal) {
  50. // 初始化分类数据
  51. var (
  52. errorData []*model.NeckRingError
  53. originalData []*model.NeckRingOriginal
  54. )
  55. // 分类数据
  56. for _, batch := range batchList {
  57. // 异常脖环数据
  58. if ok := util.IsValidFrameId(batch.Frameid); !ok {
  59. var ed model.NeckRingError
  60. copier.Copy(&ed, &batch)
  61. errorData = append(errorData, &ed)
  62. } else {
  63. originalData = append(originalData, batch)
  64. }
  65. }
  66. // 更新日志
  67. DSMLog.Mx.Lock()
  68. defer DSMLog.Mx.Unlock()
  69. DSMLog.NeckRingErrorData = append(DSMLog.NeckRingErrorData, errorData...)
  70. DSMLog.NeckRingOriginalData = append(DSMLog.NeckRingOriginalData, originalData...)
  71. // 写入数据
  72. if err := e.CreatedData(DSMLog); err != nil {
  73. zaplog.Error("Failed to create data", zap.Any("err", err), zap.Any("dataList", DSMLog))
  74. }
  75. // 清空日志
  76. DSMLog.NeckRingErrorData = DSMLog.NeckRingErrorData[:0]
  77. DSMLog.NeckRingOriginalData = DSMLog.NeckRingOriginalData[:0]
  78. }
  79. func (e *Entry) CreatedData(DSMLog *DataInsertNeckRingLog) error {
  80. if err := e.DB.Transaction(func(tx *gorm.DB) error {
  81. if len(DSMLog.NeckRingErrorData) > 0 {
  82. if err := e.DB.Create(DSMLog.NeckRingErrorData).Error; err != nil {
  83. return xerr.WithStack(err)
  84. }
  85. }
  86. if len(DSMLog.NeckRingOriginalData) > 0 {
  87. if err := e.DB.Create(DSMLog.NeckRingOriginalData).Error; err != nil {
  88. return xerr.WithStack(err)
  89. }
  90. }
  91. return nil
  92. }); err != nil {
  93. return xerr.WithStack(err)
  94. }
  95. return nil
  96. }
  97. func (e *Entry) MsgDataFormat(msg []byte) []*model.NeckRingOriginal {
  98. msgData := make(map[string]interface{})
  99. pairs := strings.Split(util.MsgFormat(string(msg)), " ")
  100. for _, pair := range pairs {
  101. parts := strings.SplitN(pair, ":", 2)
  102. if len(parts) != 2 {
  103. continue
  104. }
  105. key, value := parts[0], parts[1]
  106. if len(key) == 0 {
  107. continue
  108. }
  109. msgData[key] = value
  110. }
  111. softVer := int64(0)
  112. if softVerInter, ok := msgData["SOFT_VER"]; ok {
  113. if softVerstr, ok := softVerInter.(string); ok {
  114. softVer, _ = strconv.ParseInt(softVerstr, 10, 64)
  115. }
  116. }
  117. if softVer <= 0 {
  118. if softVerInter, ok := msgData["soft_ver"]; ok {
  119. if softVerstr, ok := softVerInter.(string); ok {
  120. softVer, _ = strconv.ParseInt(softVerstr, 10, 64)
  121. }
  122. }
  123. }
  124. uuid := ""
  125. if uuidInter, ok := msgData["uuid"]; ok {
  126. if uuidStr, ok := uuidInter.(string); ok {
  127. uuid = uuidStr
  128. }
  129. }
  130. frameId := int64(0)
  131. if frameIdInter, ok := msgData["frameid"]; ok {
  132. if frameId64, ok := frameIdInter.(string); ok {
  133. frameId, _ = strconv.ParseInt(frameId64, 10, 64)
  134. }
  135. }
  136. temp := float64(0)
  137. if tempInter, ok := msgData["Temp"]; ok {
  138. if tempFloat, ok := tempInter.(string); ok {
  139. temp, _ = strconv.ParseFloat(tempFloat, 64)
  140. }
  141. }
  142. if temp <= 0 {
  143. if tempInter, ok := msgData["temp"]; ok {
  144. if tempFloat, ok := tempInter.(string); ok {
  145. temp, _ = strconv.ParseFloat(tempFloat, 64)
  146. }
  147. }
  148. }
  149. imei := ""
  150. if imeiInter, ok := msgData["imei"]; ok {
  151. if imeiStr, ok := imeiInter.(string); ok {
  152. imei = imeiStr
  153. }
  154. }
  155. active := int64(0)
  156. if activeInter, ok := msgData["active"]; ok {
  157. if active32, ok := activeInter.(string); ok {
  158. active, _ = strconv.ParseInt(active32, 10, 64)
  159. }
  160. }
  161. inAction := int64(0)
  162. if inActionInter, ok := msgData["inactive"]; ok {
  163. if inAction32, ok := inActionInter.(string); ok {
  164. inAction, _ = strconv.ParseInt(inAction32, 10, 64)
  165. }
  166. }
  167. ruMina := int64(0)
  168. if ruMinaInter, ok := msgData["Rumina"]; ok {
  169. if ruMina32, ok := ruMinaInter.(string); ok {
  170. ruMina, _ = strconv.ParseInt(ruMina32, 10, 64)
  171. }
  172. }
  173. if ruMina <= 0 {
  174. if ruMinaInter, ok := msgData["rumina"]; ok {
  175. if ruMina32, ok := ruMinaInter.(string); ok {
  176. ruMina, _ = strconv.ParseInt(ruMina32, 10, 64)
  177. }
  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. if intake <= 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. }
  193. gasp := int64(0)
  194. if gaspInter, ok := msgData["gasp"]; ok {
  195. if gasp32, ok := gaspInter.(string); ok {
  196. gasp, _ = strconv.ParseInt(gasp32, 10, 64)
  197. }
  198. }
  199. reMain := int64(0)
  200. if reMainInter, ok := msgData["Remain"]; ok {
  201. if reMain32, ok := reMainInter.(string); ok {
  202. reMain, _ = strconv.ParseInt(reMain32, 10, 64)
  203. }
  204. }
  205. if ruMina <= 0 {
  206. if reMainInter, ok := msgData["remain"]; ok {
  207. if reMain32, ok := reMainInter.(string); ok {
  208. reMain, _ = strconv.ParseInt(reMain32, 10, 64)
  209. }
  210. }
  211. }
  212. /*cowId := ""
  213. if cowIdInter, ok := msgData["cowid"]; ok {
  214. if cowIdStr, ok := cowIdInter.(string); ok {
  215. cowId = cowIdStr
  216. }
  217. }
  218. csq := int64(0)
  219. if csqInter, ok := msgData["csq"]; ok {
  220. if csq32, ok := csqInter.(string); ok {
  221. csq, _ = strconv.ParseInt(csq32, 10, 64)
  222. }
  223. }
  224. other := int64(0)
  225. if otherInter, ok := msgData["other"]; ok {
  226. if other32, ok := otherInter.(string); ok {
  227. other, _ = strconv.ParseInt(other32, 10, 64)
  228. }
  229. }
  230. nccId := ""
  231. if nccIdInter, ok := msgData["nccid"]; ok {
  232. if nccIdStr, ok := nccIdInter.(string); ok {
  233. nccId = nccIdStr
  234. }
  235. }
  236. */
  237. return []*model.NeckRingOriginal{
  238. {
  239. FirmwareVersion: int32(softVer),
  240. Uuid: uuid,
  241. Frameid: int32(frameId),
  242. ReceiveNumber: imei,
  243. Active: int32(active),
  244. Inactive: int32(inAction),
  245. Rumina: int32(ruMina),
  246. Intake: int32(intake),
  247. Gasp: int32(gasp),
  248. Remain: int32(reMain),
  249. },
  250. }
  251. }
  252. func (e *Entry) MsgDataFormat2(msg []byte) []*model.NeckRingOriginal {
  253. neckLogList := &NeckRingWrapper{}
  254. if err := json.Unmarshal(msg, neckLogList); err != nil {
  255. zaplog.Error("MsgDataFormat", zap.Any("err", err), zap.Any("msg", string(msg)))
  256. }
  257. res := make([]*model.NeckRingOriginal, 0)
  258. for _, neckLog := range neckLogList.NeckRing.NeckPck {
  259. activeDate, hours := util.GetNeckRingActiveTimer(neckLog.Frameid)
  260. activeDateTimeType := pasturePb.ActiveTimeType_Twenty_Minutes
  261. if neckLog.Frameid%10 == 8 {
  262. activeDateTimeType = pasturePb.ActiveTimeType_Two_Hours
  263. }
  264. res = append(res, &model.NeckRingOriginal{
  265. Uuid: neckLog.UUID,
  266. NeckRingNumber: fmt.Sprintf("%d", neckLog.Ecowid),
  267. ActiveDate: activeDate,
  268. Hours: int32(hours),
  269. Frameid: neckLog.Frameid,
  270. Rumina: neckLog.Rumina,
  271. Intake: neckLog.Intake,
  272. Inactive: neckLog.Inactive,
  273. Gasp: neckLog.Other,
  274. High: neckLog.Activitys,
  275. Active: neckLog.High,
  276. FirmwareVersion: neckLog.Sver,
  277. HardwareVersion: neckLog.Hver,
  278. Remain: neckLog.Remain,
  279. Voltage: neckLog.BAT,
  280. RestartReason: neckLog.STATUS,
  281. Upper: neckLog.UpPer,
  282. Imei: neckLog.Imei,
  283. ReceiveNumber: neckLog.Imei,
  284. ActiveDateType: activeDateTimeType,
  285. IsShow: pasturePb.IsShow_No,
  286. })
  287. }
  288. return res
  289. }
  290. // NeckRingOriginalMergeData 把脖环数据合并成2个小时的
  291. func (e *Entry) NeckRingOriginalMergeData() {
  292. limit := e.Cfg.NeckRingLimit
  293. if limit <= 0 {
  294. limit = DefaultLimit
  295. }
  296. updateOriginalMaxId := e.GetSystemConfigure(model.MaxEstrus).Value
  297. neckRingList := make([]*model.NeckRingOriginal, 0)
  298. if err := e.DB.Model(new(model.NeckRingOriginal)).
  299. Where("id > ?", updateOriginalMaxId).
  300. Order("id asc").Limit(int(limit)).
  301. Find(&neckRingList).Error; err != nil {
  302. return
  303. }
  304. if len(neckRingList) <= 0 {
  305. return
  306. }
  307. originalMapData := make(map[string]*model.NeckRingOriginalMerge)
  308. // 合并成2个小时的
  309. for _, v := range neckRingList {
  310. xframeId := int(math.Floor(float64(v.Frameid)/10) * 2)
  311. 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
  312. if _, ok := originalMapData[mapKey]; !ok {
  313. originalMapData[mapKey] = new(model.NeckRingOriginalMerge)
  314. }
  315. v.IsAvgHours()
  316. originalMapData[mapKey].IsMageData(v)
  317. }
  318. // 算平均值
  319. for _, v := range originalMapData {
  320. v.SumAvg()
  321. }
  322. // 更新脖环牛只相关信息
  323. newNeckActiveHabitList := model.NeckRingOriginalMap(originalMapData).ForMatData()
  324. if err := e.DB.Transaction(func(tx *gorm.DB) error {
  325. // 更新已处理过的id
  326. if err := tx.Model(new(model.SystemConfigure)).
  327. Where("name = ?", model.UpdateOriginalMaxId).
  328. Update("value", neckRingList[len(neckRingList)-1].Id).
  329. Error; err != nil {
  330. return xerr.WithStack(err)
  331. }
  332. for _, neckActiveHabit := range newNeckActiveHabitList {
  333. // 新数据直接插入 todo 待优化
  334. historyNeckActiveHabit, ct := e.IsExistNeckActiveHabit(neckActiveHabit.NeckRingNumber, neckActiveHabit.HeatDate, neckActiveHabit.Frameid)
  335. if ct <= 0 {
  336. if err := tx.Create(neckActiveHabit).Error; err != nil {
  337. return xerr.WithStack(err)
  338. }
  339. continue
  340. }
  341. if historyNeckActiveHabit == nil {
  342. zaplog.Error("NeckRingOriginalMergeData", zap.Any("historyNeckActiveHabit", historyNeckActiveHabit))
  343. continue
  344. }
  345. // 更新数据
  346. historyNeckActiveHabit.MergeData(neckActiveHabit)
  347. if err := tx.Model(new(model.NeckActiveHabit)).
  348. Select("rumina", "intake", "inactive", "gasp", "other", "high", "active").
  349. Where("id = ?", historyNeckActiveHabit.Id).
  350. Updates(historyNeckActiveHabit).Error; err != nil {
  351. return xerr.WithStack(err)
  352. }
  353. }
  354. return nil
  355. }); err != nil {
  356. zaplog.Error("NeckRingOriginalMergeData", zap.Any("transaction", err))
  357. return
  358. }
  359. }