mqtt_handle.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. package mqtt
  2. import (
  3. "encoding/json"
  4. "kpt-pasture/model"
  5. "kpt-pasture/util"
  6. "strconv"
  7. "strings"
  8. "sync"
  9. "time"
  10. "github.com/jinzhu/copier"
  11. "gitee.com/xuyiping_admin/pkg/logger/zaplog"
  12. "gitee.com/xuyiping_admin/pkg/xerr"
  13. "go.uber.org/zap"
  14. "gorm.io/gorm"
  15. )
  16. type DataInsertNeckRingLog struct {
  17. NeckRingOriginalData []*model.NeckRingOriginal
  18. NeckRingErrorData []*model.NeckRingError
  19. }
  20. var (
  21. DSMLog = &DataInsertNeckRingLog{
  22. NeckRingOriginalData: make([]*model.NeckRingOriginal, 0),
  23. NeckRingErrorData: make([]*model.NeckRingError, 0),
  24. }
  25. mu sync.Mutex
  26. receiverMap map[string]int64 // 接收器数据
  27. receiverMutex sync.Mutex
  28. )
  29. // InitReceiverMapUpdater 2小时更新接收器数据
  30. func (e *Entry) InitReceiverMapUpdater() {
  31. ticker := time.NewTicker(2 * time.Hour)
  32. defer ticker.Stop()
  33. for {
  34. select {
  35. case <-ticker.C:
  36. receiverMutex.Lock()
  37. receiverMap = e.FindAppPastureReceiver()
  38. receiverMutex.Unlock()
  39. zaplog.Info("ReceiverMap updated successfully")
  40. }
  41. }
  42. }
  43. func (e *Entry) NeckRingHandle(data []byte) {
  44. if len(receiverMap) <= 0 {
  45. receiverMutex.Lock()
  46. receiverMap = e.FindAppPastureReceiver()
  47. receiverMutex.Unlock()
  48. }
  49. newReceiverMap := receiverMap
  50. newData := e.MsgDataFormat2(data, newReceiverMap)
  51. if newData == nil {
  52. return
  53. }
  54. if len(newData.NeckRingErrorData) > 0 || len(newData.NeckRingOriginalData) > 0 {
  55. // 写入数据
  56. if err := e.CreatedData(newData, data); err != nil {
  57. zaplog.Error("Failed to create data", zap.Any("err", err), zap.Any("dataList", newData))
  58. }
  59. }
  60. }
  61. func (e *Entry) FindAppPastureReceiver() map[string]int64 {
  62. appPastureReceiverList := make([]*model.AppPastureReceiver, 0)
  63. if err := e.DB.Model(new(model.AppPastureReceiver)).
  64. Find(&appPastureReceiverList).Error; err != nil {
  65. zaplog.Error("FindAppPastureReceiver", zap.Any("err", err))
  66. }
  67. newReceiverMap := make(map[string]int64)
  68. for _, v := range appPastureReceiverList {
  69. newReceiverMap[v.ReceiverNumber] = v.PastureId
  70. }
  71. return newReceiverMap
  72. }
  73. // 处理批量数据
  74. func (e *Entry) processBatch(batchList []*model.NeckRingOriginal) {
  75. // 初始化分类数据
  76. var (
  77. errorData []*model.NeckRingError
  78. originalData []*model.NeckRingOriginal
  79. )
  80. // 分类数据
  81. for _, batch := range batchList {
  82. // 异常脖环数据
  83. if ok := util.IsValidFrameId(batch.Frameid); !ok {
  84. var ed model.NeckRingError
  85. err := copier.Copy(&ed, &batch)
  86. if err != nil {
  87. zaplog.Error("processBatch", zap.Any("copier", err), zap.Any("data", batch))
  88. continue
  89. }
  90. errorData = append(errorData, &ed)
  91. } else {
  92. originalData = append(originalData, batch)
  93. }
  94. }
  95. // 更新日志
  96. DSMLog.NeckRingErrorData = append(DSMLog.NeckRingErrorData, errorData...)
  97. DSMLog.NeckRingOriginalData = append(DSMLog.NeckRingOriginalData, originalData...)
  98. // 写入数据
  99. if err := e.CreatedData(DSMLog, []byte{}); err != nil {
  100. zaplog.Error("Failed to create data", zap.Any("err", err), zap.Any("dataList", DSMLog))
  101. }
  102. // 清空日志
  103. DSMLog.NeckRingErrorData = DSMLog.NeckRingErrorData[:0]
  104. DSMLog.NeckRingOriginalData = DSMLog.NeckRingOriginalData[:0]
  105. }
  106. func (e *Entry) CreatedData(DSMLog *DataInsertNeckRingLog, originalData []byte) error {
  107. if err := e.DB.Transaction(func(tx *gorm.DB) error {
  108. if len(DSMLog.NeckRingErrorData) > 0 {
  109. if err := e.DB.Model(new(model.NeckRingError)).
  110. Create(DSMLog.NeckRingErrorData).Error; err != nil {
  111. return xerr.WithStack(err)
  112. }
  113. }
  114. if len(DSMLog.NeckRingOriginalData) > 0 {
  115. // 批量写入数据
  116. if err := e.DB.Model(new(model.NeckRingOriginal)).
  117. Create(DSMLog.NeckRingOriginalData).Error; err != nil {
  118. return xerr.WithStack(err)
  119. }
  120. }
  121. return nil
  122. }); err != nil {
  123. return xerr.WithStack(err)
  124. }
  125. return nil
  126. }
  127. func (e *Entry) MsgDataFormat2(msg []byte, receiverMap map[string]int64) *DataInsertNeckRingLog {
  128. mu.Lock()
  129. defer mu.Unlock()
  130. // 深拷贝 msg,防止底层数据被修改
  131. msgCopy := make([]byte, len(msg))
  132. copy(msgCopy, msg)
  133. neckLogList := &model.NeckRingWrapper{}
  134. if err := json.Unmarshal(msgCopy, neckLogList); err != nil {
  135. zaplog.Error("MsgDataFormat", zap.Any("err", err), zap.Any("msg", string(msgCopy)))
  136. return nil
  137. }
  138. if neckLogList.Type == "heartbeat" {
  139. return nil
  140. }
  141. normalOriginal := make([]*model.NeckRingOriginal, 0)
  142. errorOriginal := make([]*model.NeckRingError, 0)
  143. for _, neckLog := range neckLogList.NeckRing.NeckPck {
  144. pastureId, ok := receiverMap[neckLog.Imei]
  145. if !ok {
  146. continue
  147. }
  148. newOriginal := model.NewNeckRingOriginal(neckLog, pastureId)
  149. if ok = util.IsValidFrameId(neckLog.Frameid); !ok {
  150. var ed model.NeckRingError
  151. if err := copier.Copy(&ed, &newOriginal); err != nil {
  152. zaplog.Error("MsgDataFormat2", zap.Any("copier", err), zap.Any("neckLog", neckLog))
  153. continue
  154. }
  155. errorOriginal = append(errorOriginal, &ed)
  156. } else {
  157. activeDate, hours := util.GetNeckRingActiveTimer(neckLog.Frameid)
  158. newOriginal.ActiveDate = activeDate
  159. newOriginal.Hours = int32(hours)
  160. normalOriginal = append(normalOriginal, newOriginal)
  161. }
  162. }
  163. return &DataInsertNeckRingLog{
  164. NeckRingErrorData: errorOriginal,
  165. NeckRingOriginalData: normalOriginal,
  166. }
  167. }
  168. func (e *Entry) MsgDataFormat(msg []byte) []*model.NeckRingOriginal {
  169. msgData := make(map[string]interface{})
  170. pairs := strings.Split(util.MsgFormat(string(msg)), " ")
  171. for _, pair := range pairs {
  172. parts := strings.SplitN(pair, ":", 2)
  173. if len(parts) != 2 {
  174. continue
  175. }
  176. key, value := parts[0], parts[1]
  177. if len(key) == 0 {
  178. continue
  179. }
  180. msgData[key] = value
  181. }
  182. softVer := int64(0)
  183. if softVerInter, ok := msgData["SOFT_VER"]; ok {
  184. if softVerstr, ok := softVerInter.(string); ok {
  185. softVer, _ = strconv.ParseInt(softVerstr, 10, 64)
  186. }
  187. }
  188. if softVer <= 0 {
  189. if softVerInter, ok := msgData["soft_ver"]; ok {
  190. if softVerstr, ok := softVerInter.(string); ok {
  191. softVer, _ = strconv.ParseInt(softVerstr, 10, 64)
  192. }
  193. }
  194. }
  195. uuid := ""
  196. if uuidInter, ok := msgData["uuid"]; ok {
  197. if uuidStr, ok := uuidInter.(string); ok {
  198. uuid = uuidStr
  199. }
  200. }
  201. frameId := int64(0)
  202. if frameIdInter, ok := msgData["frameid"]; ok {
  203. if frameId64, ok := frameIdInter.(string); ok {
  204. frameId, _ = strconv.ParseInt(frameId64, 10, 64)
  205. }
  206. }
  207. temp := float64(0)
  208. if tempInter, ok := msgData["Temp"]; ok {
  209. if tempFloat, ok := tempInter.(string); ok {
  210. temp, _ = strconv.ParseFloat(tempFloat, 64)
  211. }
  212. }
  213. if temp <= 0 {
  214. if tempInter, ok := msgData["temp"]; ok {
  215. if tempFloat, ok := tempInter.(string); ok {
  216. temp, _ = strconv.ParseFloat(tempFloat, 64)
  217. }
  218. }
  219. }
  220. imei := ""
  221. if imeiInter, ok := msgData["imei"]; ok {
  222. if imeiStr, ok := imeiInter.(string); ok {
  223. imei = imeiStr
  224. }
  225. }
  226. active := int64(0)
  227. if activeInter, ok := msgData["active"]; ok {
  228. if active32, ok := activeInter.(string); ok {
  229. active, _ = strconv.ParseInt(active32, 10, 64)
  230. }
  231. }
  232. inAction := int64(0)
  233. if inActionInter, ok := msgData["inactive"]; ok {
  234. if inAction32, ok := inActionInter.(string); ok {
  235. inAction, _ = strconv.ParseInt(inAction32, 10, 64)
  236. }
  237. }
  238. ruMina := int64(0)
  239. if ruMinaInter, ok := msgData["Rumina"]; ok {
  240. if ruMina32, ok := ruMinaInter.(string); ok {
  241. ruMina, _ = strconv.ParseInt(ruMina32, 10, 64)
  242. }
  243. }
  244. if ruMina <= 0 {
  245. if ruMinaInter, ok := msgData["rumina"]; ok {
  246. if ruMina32, ok := ruMinaInter.(string); ok {
  247. ruMina, _ = strconv.ParseInt(ruMina32, 10, 64)
  248. }
  249. }
  250. }
  251. intake := int64(0)
  252. if intakeInter, ok := msgData["Intake"]; ok {
  253. if intake32, ok := intakeInter.(string); ok {
  254. intake, _ = strconv.ParseInt(intake32, 10, 64)
  255. }
  256. }
  257. if intake <= 0 {
  258. if intakeInter, ok := msgData["intake"]; ok {
  259. if intake32, ok := intakeInter.(string); ok {
  260. intake, _ = strconv.ParseInt(intake32, 10, 64)
  261. }
  262. }
  263. }
  264. gasp := int64(0)
  265. if gaspInter, ok := msgData["gasp"]; ok {
  266. if gasp32, ok := gaspInter.(string); ok {
  267. gasp, _ = strconv.ParseInt(gasp32, 10, 64)
  268. }
  269. }
  270. reMain := int64(0)
  271. if reMainInter, ok := msgData["Remain"]; ok {
  272. if reMain32, ok := reMainInter.(string); ok {
  273. reMain, _ = strconv.ParseInt(reMain32, 10, 64)
  274. }
  275. }
  276. if ruMina <= 0 {
  277. if reMainInter, ok := msgData["remain"]; ok {
  278. if reMain32, ok := reMainInter.(string); ok {
  279. reMain, _ = strconv.ParseInt(reMain32, 10, 64)
  280. }
  281. }
  282. }
  283. /*cowId := ""
  284. if cowIdInter, ok := msgData["cowid"]; ok {
  285. if cowIdStr, ok := cowIdInter.(string); ok {
  286. cowId = cowIdStr
  287. }
  288. }
  289. csq := int64(0)
  290. if csqInter, ok := msgData["csq"]; ok {
  291. if csq32, ok := csqInter.(string); ok {
  292. csq, _ = strconv.ParseInt(csq32, 10, 64)
  293. }
  294. }
  295. other := int64(0)
  296. if otherInter, ok := msgData["other"]; ok {
  297. if other32, ok := otherInter.(string); ok {
  298. other, _ = strconv.ParseInt(other32, 10, 64)
  299. }
  300. }
  301. nccId := ""
  302. if nccIdInter, ok := msgData["nccid"]; ok {
  303. if nccIdStr, ok := nccIdInter.(string); ok {
  304. nccId = nccIdStr
  305. }
  306. }
  307. */
  308. return []*model.NeckRingOriginal{
  309. {
  310. FirmwareVersion: int32(softVer),
  311. Uuid: uuid,
  312. Frameid: int32(frameId),
  313. ReceiveNumber: imei,
  314. Active: int32(active),
  315. Inactive: int32(inAction),
  316. Rumina: int32(ruMina),
  317. Intake: int32(intake),
  318. Gasp: int32(gasp),
  319. Remain: int32(reMain),
  320. },
  321. }
  322. }