out.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. "property-device/pb"
  14. pb_v1 "property-device/pb/v1"
  15. "property-device/utils/gate_utils"
  16. "time"
  17. )
  18. func checkGateOutParam(req *pb_v1.GateOutRequest) error {
  19. switch {
  20. case req.DeviceId == 0:
  21. return status.Error(10003, "设备id不能为空")
  22. case req.GardenId == 0:
  23. return status.Error(10003, "小区不能为空")
  24. case req.OutUser == "":
  25. return status.Error(10003, "出库人不能为空")
  26. }
  27. return nil
  28. }
  29. func GateOut(ctx context.Context, req *pb_v1.GateOutRequest) (reply *pb_v1.GateOutReply, err error) {
  30. reply = &pb_v1.GateOutReply{}
  31. // 捕获各个task中的异常并返回给调用者
  32. defer func() {
  33. if r := recover(); r != nil {
  34. err = fmt.Errorf("%+v", r)
  35. e := &status.Status{}
  36. if er := json.Unmarshal([]byte(err.Error()), e); er != nil {
  37. logger.Error("err",
  38. zap.String("system_err", err.Error()),
  39. zap.Stack("stacktrace"))
  40. }
  41. }
  42. }()
  43. err = checkGateOutParam(req)
  44. if err != nil {
  45. return nil, err
  46. }
  47. now := time.Now()
  48. p := &dbmodel.TGate{}
  49. where := [][2]interface{}{}
  50. where = dbmodel.WhereAdd(where, "id", req.DeviceId)
  51. err = p.Find(database.DB(), where)
  52. if err != nil && err != gorm.ErrRecordNotFound {
  53. return nil, errors.DataBaseError
  54. }
  55. if p.ID == 0 {
  56. return nil, errors.ErrRecordNotFound
  57. }
  58. if p.GardenId > 0 {
  59. return nil, status.Error(10003, "该设备已出库")
  60. }
  61. values := map[string]interface{}{
  62. "garden_id": req.GardenId,
  63. "enable": 1,
  64. "updated_at": now,
  65. "out_time": now.Unix(),
  66. "out_user": req.OutUser,
  67. }
  68. db := database.DB().Begin()
  69. err = p.Update(db, where, values)
  70. if err != nil {
  71. db.Rollback()
  72. return nil, errors.DataBaseError
  73. }
  74. if p.Protocol == gate_utils.GateProtocolSaiboMqttV1 {
  75. mreq := pb_v1.NewMqttDeviceRequest{Sn: p.Sn}
  76. _, err = pb.Mqtt.NewMqttDevice(ctx, &mreq)
  77. if err != nil {
  78. db.Rollback()
  79. return nil, status.Error(10003, "mqtt订阅失败请检查mqtt服务")
  80. }
  81. }
  82. db.Commit()
  83. return reply, nil
  84. }