1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- // Copyright 2019 github.com. All rights reserved.
- // Use of this source code is governed by github.com.
- package device
- import (
- "context"
- "fmt"
- "smart-auth/consts"
- "smart-auth/errors"
- "smart-auth/model"
- "smart-auth/pb/v1"
- "sync"
- "github.com/jaryhe/gopkgs/database"
- "github.com/jinzhu/gorm"
- )
- var snKey map[string]*v1.DeviceInfoReply
- var deviceMutex sync.Mutex
- // 初始化map
- func Init() {
- snKey = make(map[string]*v1.DeviceInfoReply)
- idKey = make(map[int64]*v1.DeviceInfoByIdReply)
- }
- func GetDeviceInfoFromMem(sn string, deviceCode int32) *v1.DeviceInfoReply {
- deviceMutex.Lock()
- defer deviceMutex.Unlock()
- key := fmt.Sprintf("%s-%d", sn, deviceCode)
- if value, ok := snKey[key]; ok {
- return value
- }
- return nil
- }
- func SetDeviceInfoToMem(sn string, deviceCode int32, deviceInfo *v1.DeviceInfoReply) {
- deviceMutex.Lock()
- defer deviceMutex.Unlock()
- key := fmt.Sprintf("%s-%d", sn, deviceCode)
- snKey[key] = deviceInfo
- }
- func DeleteDeviceInfoFromMem(sn string, deviceCode int32) {
- deviceMutex.Lock()
- defer deviceMutex.Unlock()
- key := fmt.Sprintf("%s-%d", sn, deviceCode)
- delete(snKey, key)
- }
- func DeviceInfo(ctx context.Context, req *v1.DeviceInfoRequest) (reply *v1.DeviceInfoReply, err error) {
- if req.Sn == "" {
- return nil, errors.ParamsError
- }
- // 从本地内存获取
- deviceInfo := GetDeviceInfoFromMem(req.Sn, req.DeviceCode)
- if deviceInfo != nil {
- return deviceInfo, nil
- }
- // 从数据库中获取
- p := model.TDevice{}
- where := map[string]interface{}{
- "sn": req.Sn,
- "device_code": req.DeviceCode,
- "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.DeviceInfoReply{}
- reply.Sn = req.Sn
- reply.ProjectId = p.ProjectId
- reply.Name = p.Name
- reply.DeviceCode = p.DeviceCode
- reply.Key = p.Key
- reply.Id = int64(p.Id)
- // 放到内存中
- SetDeviceInfoToMem(req.Sn, req.DeviceCode, reply)
- return reply, nil
- }
|