123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- // Copyright 2019 github.com. All rights reserved.
- // Use of this source code is governed by github.com.
- package device
- import (
- "context"
- "smart-auth/consts"
- "smart-auth/errors"
- "smart-auth/model"
- "smart-auth/pb/v1"
- "sync"
- "github.com/jaryhe/gopkgs/database"
- "github.com/jinzhu/gorm"
- )
- var idKey map[int64]*v1.DeviceInfoByIdReply
- var deviceByIdMutex sync.Mutex
- func GetDeviceInfoByIdFromMem(id int64) *v1.DeviceInfoByIdReply {
- deviceByIdMutex.Lock()
- defer deviceByIdMutex.Unlock()
- key := id
- if value, ok := idKey[key]; ok {
- return value
- }
- return nil
- }
- func SetDeviceInfoByIdToMem(id int64, deviceInfo *v1.DeviceInfoByIdReply) {
- deviceByIdMutex.Lock()
- defer deviceByIdMutex.Unlock()
- key := id
- idKey[key] = deviceInfo
- }
- func DeleteDeviceInfoByIdFromMem(sn string, deviceCode int32) {
- deviceByIdMutex.Lock()
- defer deviceByIdMutex.Unlock()
- key := int64(0)
- for _, v := range idKey {
- if v.Sn == sn && v.DeviceCode == deviceCode {
- key = v.Id
- }
- }
- if key == 0 {
- return
- }
- delete(idKey, key)
- }
- func DeviceInfoById(ctx context.Context, req *v1.DeviceInfoByIdRequest) (reply *v1.DeviceInfoByIdReply, err error) {
- if req.Id == 0 {
- return nil, errors.ParamsError
- }
- // 从本地内存获取
- deviceInfo := GetDeviceInfoByIdFromMem(req.Id)
- if deviceInfo != nil {
- return deviceInfo, nil
- }
- // 从数据库中获取
- p := model.TDevice{}
- where := map[string]interface{}{
- "id": req.Id,
- "verify_status": consts.DeviceApprove,
- }
- err = p.Query(database.DB(), where)
- if err != nil {
- if err == gorm.ErrRecordNotFound {
- return nil, errors.DeviceNotExistError
- }
- return nil, errors.DataBaseError
- }
- if p.Id == 0 {
- return nil, errors.DeviceNotExistError
- }
- // 赋值,只取需要的字段
- reply = &v1.DeviceInfoByIdReply{}
- reply.Sn = p.Sn
- reply.ProjectId = p.ProjectId
- reply.Name = p.Name
- reply.DeviceCode = p.DeviceCode
- reply.Key = p.Key
- reply.Id = int64(p.Id)
- // 放到内存中
- SetDeviceInfoByIdToMem(req.Id, reply)
- return reply, nil
- }
|