1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- package gate_command
- import (
- "context"
- "encoding/json"
- "fmt"
- "git.getensh.com/common/gopkgs/database"
- "git.getensh.com/common/gopkgs/logger"
- "go.uber.org/zap"
- "google.golang.org/grpc/status"
- "gorm.io/gorm"
- "property-device/errors"
- dbmodel "property-device/model"
- pb_v1 "property-device/pb/v1"
- "property-device/utils/gate_utils"
- )
- func checkGateCommandAddParam(req *pb_v1.GateCommandAddRequest) error {
- switch {
- case req.DeviceId == 0:
- return status.Error(10003, "设备id不能为空")
- case gate_utils.CommandCodeMap[req.CmdCode] == "":
- return status.Error(10003, "不支持的命令代码")
- }
- return nil
- }
- func getGateInfo(deviceId int64, sn string, protocol int32) (*dbmodel.TGate, error) {
- p := &dbmodel.TGate{}
- where := [][2]interface{}{}
- if deviceId > 0 {
- where = dbmodel.WhereAdd(where, "id", deviceId)
- } else {
- where = dbmodel.WhereAdd(where, "sn", sn)
- where = dbmodel.WhereAdd(where, "protocol", protocol)
- }
- err := p.Find(database.DB(), where)
- if err != nil && err != gorm.ErrRecordNotFound {
- return nil, errors.DataBaseError
- }
- if p.ID == 0 {
- return nil, errors.ErrRecordNotFound
- }
- return p, nil
- }
- func GateCommandAdd(ctx context.Context, req *pb_v1.GateCommandAddRequest) (reply *pb_v1.GateCommandAddReply, err error) {
- reply = &pb_v1.GateCommandAddReply{}
- // 捕获各个task中的异常并返回给调用者
- defer func() {
- if r := recover(); r != nil {
- err = fmt.Errorf("%+v", r)
- e := &status.Status{}
- if er := json.Unmarshal([]byte(err.Error()), e); er != nil {
- logger.Error("err",
- zap.String("system_err", err.Error()),
- zap.Stack("stacktrace"))
- }
- }
- }()
- err = checkGateCommandAddParam(req)
- if err != nil {
- return nil, err
- }
- gateInfo, err := getGateInfo(req.DeviceId, "", 0)
- if err != nil {
- return nil, err
- }
- commander := NewCommander(gateInfo)
- if commander == nil {
- return nil, status.Error(10003, "不支持的协议")
- }
- switch req.CmdCode {
- case gate_utils.OpenCommand:
- err = commander.Open()
- case gate_utils.RebootCommand:
- err = commander.Reboot()
- default:
- return nil, status.Error(10003, "暂不支持该命令")
- }
- if err != nil {
- return nil, err
- }
- if commander.Command() {
- gate_utils.CommandCacheIncrease(gateInfo.Sn, gateInfo.Protocol)
- }
- return reply, nil
- }
|