info.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. "fmt"
  7. "smart-auth/consts"
  8. "smart-auth/errors"
  9. "smart-auth/model"
  10. "smart-auth/pb/v1"
  11. "sync"
  12. "github.com/jaryhe/gopkgs/database"
  13. "github.com/jinzhu/gorm"
  14. )
  15. var snKey map[string]*v1.DeviceInfoReply
  16. var deviceMutex sync.Mutex
  17. // 初始化map
  18. func Init() {
  19. snKey = make(map[string]*v1.DeviceInfoReply)
  20. idKey = make(map[int64]*v1.DeviceInfoByIdReply)
  21. }
  22. func GetDeviceInfoFromMem(sn string, deviceCode int32) *v1.DeviceInfoReply {
  23. deviceMutex.Lock()
  24. defer deviceMutex.Unlock()
  25. key := fmt.Sprintf("%s-%d", sn, deviceCode)
  26. if value, ok := snKey[key]; ok {
  27. return value
  28. }
  29. return nil
  30. }
  31. func SetDeviceInfoToMem(sn string, deviceCode int32, deviceInfo *v1.DeviceInfoReply) {
  32. deviceMutex.Lock()
  33. defer deviceMutex.Unlock()
  34. key := fmt.Sprintf("%s-%d", sn, deviceCode)
  35. snKey[key] = deviceInfo
  36. }
  37. func DeleteDeviceInfoFromMem(sn string, deviceCode int32) {
  38. deviceMutex.Lock()
  39. defer deviceMutex.Unlock()
  40. key := fmt.Sprintf("%s-%d", sn, deviceCode)
  41. delete(snKey, key)
  42. }
  43. func DeviceInfo(ctx context.Context, req *v1.DeviceInfoRequest) (reply *v1.DeviceInfoReply, err error) {
  44. if req.Sn == "" {
  45. return nil, errors.ParamsError
  46. }
  47. // 从本地内存获取
  48. deviceInfo := GetDeviceInfoFromMem(req.Sn, req.DeviceCode)
  49. if deviceInfo != nil {
  50. return deviceInfo, nil
  51. }
  52. // 从数据库中获取
  53. p := model.TDevice{}
  54. where := map[string]interface{}{
  55. "sn": req.Sn,
  56. "device_code": req.DeviceCode,
  57. "verify_status": consts.DeviceApprove,
  58. }
  59. err = p.Query(database.DB(), where)
  60. if err != nil {
  61. if err == gorm.ErrRecordNotFound {
  62. return nil, errors.DeviceNotExistError
  63. }
  64. return nil, errors.DataBaseError
  65. }
  66. if p.Id == 0 {
  67. return nil, errors.DeviceNotExistError
  68. }
  69. // 赋值,只取需要的字段
  70. reply = &v1.DeviceInfoReply{}
  71. reply.Sn = req.Sn
  72. reply.ProjectId = p.ProjectId
  73. reply.Name = p.Name
  74. reply.DeviceCode = p.DeviceCode
  75. reply.Key = p.Key
  76. reply.Id = int64(p.Id)
  77. // 放到内存中
  78. SetDeviceInfoToMem(req.Sn, req.DeviceCode, reply)
  79. return reply, nil
  80. }