info_by_id.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // Copyright 2019 github.com. All rights reserved.
  2. // Use of this source code is governed by github.com.
  3. package device
  4. import (
  5. "context"
  6. "smart-auth/consts"
  7. "smart-auth/errors"
  8. "smart-auth/model"
  9. "smart-auth/pb/v1"
  10. "sync"
  11. "github.com/jaryhe/gopkgs/database"
  12. "github.com/jinzhu/gorm"
  13. )
  14. var idKey map[int64]*v1.DeviceInfoByIdReply
  15. var deviceByIdMutex sync.Mutex
  16. func GetDeviceInfoByIdFromMem(id int64) *v1.DeviceInfoByIdReply {
  17. deviceByIdMutex.Lock()
  18. defer deviceByIdMutex.Unlock()
  19. key := id
  20. if value, ok := idKey[key]; ok {
  21. return value
  22. }
  23. return nil
  24. }
  25. func SetDeviceInfoByIdToMem(id int64, deviceInfo *v1.DeviceInfoByIdReply) {
  26. deviceByIdMutex.Lock()
  27. defer deviceByIdMutex.Unlock()
  28. key := id
  29. idKey[key] = deviceInfo
  30. }
  31. func DeleteDeviceInfoByIdFromMem(sn string, deviceCode int32) {
  32. deviceByIdMutex.Lock()
  33. defer deviceByIdMutex.Unlock()
  34. key := int64(0)
  35. for _, v := range idKey {
  36. if v.Sn == sn && v.DeviceCode == deviceCode {
  37. key = v.Id
  38. }
  39. }
  40. if key == 0 {
  41. return
  42. }
  43. delete(idKey, key)
  44. }
  45. func DeviceInfoById(ctx context.Context, req *v1.DeviceInfoByIdRequest) (reply *v1.DeviceInfoByIdReply, err error) {
  46. if req.Id == 0 {
  47. return nil, errors.ParamsError
  48. }
  49. // 从本地内存获取
  50. deviceInfo := GetDeviceInfoByIdFromMem(req.Id)
  51. if deviceInfo != nil {
  52. return deviceInfo, nil
  53. }
  54. // 从数据库中获取
  55. p := model.DeviceAll{}
  56. where := map[string]interface{}{
  57. "ID": req.Id,
  58. "VerifyStatus": consts.DeviceApprove,
  59. }
  60. err = p.Query(database.DB(), where)
  61. if err != nil {
  62. if err == gorm.ErrRecordNotFound {
  63. return nil, errors.DeviceNotExistError
  64. }
  65. return nil, errors.DataBaseError
  66. }
  67. if p.ID == 0 {
  68. return nil, errors.DeviceNotExistError
  69. }
  70. // 赋值,只取需要的字段
  71. reply = &v1.DeviceInfoByIdReply{}
  72. reply.Sn = p.SN
  73. reply.ProjectId = p.ProjectId
  74. reply.Name = p.DeviceName
  75. reply.DeviceCode = int32(p.DeviceCode)
  76. reply.Key = p.Key
  77. reply.Id = int64(p.ID)
  78. // 放到内存中
  79. SetDeviceInfoByIdToMem(req.Id, reply)
  80. return reply, nil
  81. }