mqtt_handle.go 8.5 KB

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