package gate 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" "property-device/pb" pb_v1 "property-device/pb/v1" "property-device/utils/gate_utils" "time" ) func checkGateOutParam(req *pb_v1.GateOutRequest) error { switch { case req.DeviceId == 0: return status.Error(10003, "设备id不能为空") case req.GardenId == 0: return status.Error(10003, "小区不能为空") case req.OutUser == "": return status.Error(10003, "出库人不能为空") } return nil } func GateOut(ctx context.Context, req *pb_v1.GateOutRequest) (reply *pb_v1.GateOutReply, err error) { reply = &pb_v1.GateOutReply{} // 捕获各个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 = checkGateOutParam(req) if err != nil { return nil, err } now := time.Now() p := &dbmodel.TGate{} where := [][2]interface{}{} where = dbmodel.WhereAdd(where, "id", req.DeviceId) err = p.Find(database.DB(), where) if err != nil && err != gorm.ErrRecordNotFound { return nil, errors.DataBaseError } if p.ID == 0 { return nil, errors.ErrRecordNotFound } if p.GardenId > 0 { return nil, status.Error(10003, "该设备已出库") } values := map[string]interface{}{ "garden_id": req.GardenId, "enable": 1, "updated_at": now, "out_time": now.Unix(), "out_user": req.OutUser, } db := database.DB().Begin() err = p.Update(db, where, values) if err != nil { db.Rollback() return nil, errors.DataBaseError } if p.Protocol == gate_utils.GateProtocolSaiboMqttV1 { mreq := pb_v1.NewMqttDeviceRequest{Sn: p.Sn} _, err = pb.Mqtt.NewMqttDevice(ctx, &mreq) if err != nil { db.Rollback() return nil, status.Error(10003, "mqtt订阅失败请检查mqtt服务") } } db.Commit() return reply, nil }