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