enable.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package gate
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "git.getensh.com/common/gopkgs/database"
  7. "git.getensh.com/common/gopkgs/logger"
  8. "go.uber.org/zap"
  9. "google.golang.org/grpc/status"
  10. "gorm.io/gorm"
  11. "property-device/errors"
  12. dbmodel "property-device/model"
  13. pb_v1 "property-device/pb/v1"
  14. "time"
  15. )
  16. func checkGateEnableParam(req *pb_v1.GateEnableRequest) error {
  17. switch {
  18. case req.DeviceId == 0:
  19. return status.Error(10003, "设备id不能为空")
  20. case req.GardenId == 0:
  21. return status.Error(10003, "小区id不能为空")
  22. }
  23. return nil
  24. }
  25. func GateEnable(ctx context.Context, req *pb_v1.GateEnableRequest) (reply *pb_v1.GateEnableReply, err error) {
  26. reply = &pb_v1.GateEnableReply{}
  27. // 捕获各个task中的异常并返回给调用者
  28. defer func() {
  29. if r := recover(); r != nil {
  30. err = fmt.Errorf("%+v", r)
  31. e := &status.Status{}
  32. if er := json.Unmarshal([]byte(err.Error()), e); er != nil {
  33. logger.Error("err",
  34. zap.String("system_err", err.Error()),
  35. zap.Stack("stacktrace"))
  36. }
  37. }
  38. }()
  39. err = checkGateEnableParam(req)
  40. if err != nil {
  41. return nil, err
  42. }
  43. p := &dbmodel.TGate{}
  44. where := [][2]interface{}{}
  45. where = dbmodel.WhereAdd(where, "id", req.DeviceId)
  46. where = dbmodel.WhereAdd(where, "garden_id", req.GardenId)
  47. err = p.Find(database.DB(), where)
  48. if err != nil && err != gorm.ErrRecordNotFound {
  49. return nil, errors.DataBaseError
  50. }
  51. if p.ID == 0 {
  52. return nil, errors.ErrRecordNotFound
  53. }
  54. enable := int32(1)
  55. if !req.Enable {
  56. enable = 2
  57. }
  58. now := time.Now()
  59. values := map[string]interface{}{
  60. "enable": enable,
  61. "updated_at": now,
  62. }
  63. err = p.Update(database.DB(), where, values)
  64. if err != nil {
  65. return nil, errors.DataBaseError
  66. }
  67. delGateInfoFromRedis(req.DeviceId, "", 0)
  68. delGateInfoFromRedis(0, p.Sn, p.Protocol)
  69. return reply, nil
  70. }