command_add.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package gate_command
  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. "property-device/utils/gate_utils"
  15. )
  16. func checkGateCommandAddParam(req *pb_v1.GateCommandAddRequest) error {
  17. switch {
  18. case req.DeviceId == 0:
  19. return status.Error(10003, "设备id不能为空")
  20. case gate_utils.CommandCodeMap[req.CmdCode] == "":
  21. return status.Error(10003, "不支持的命令代码")
  22. }
  23. return nil
  24. }
  25. func getGateInfo(deviceId int64, sn string, protocol int32) (*dbmodel.TGate, error) {
  26. p := &dbmodel.TGate{}
  27. where := [][2]interface{}{}
  28. if deviceId > 0 {
  29. where = dbmodel.WhereAdd(where, "id", deviceId)
  30. } else {
  31. where = dbmodel.WhereAdd(where, "sn", sn)
  32. where = dbmodel.WhereAdd(where, "protocol", protocol)
  33. }
  34. err := p.Find(database.DB(), where)
  35. if err != nil && err != gorm.ErrRecordNotFound {
  36. return nil, errors.DataBaseError
  37. }
  38. if p.ID == 0 {
  39. return nil, errors.ErrRecordNotFound
  40. }
  41. return p, nil
  42. }
  43. func GateCommandAdd(ctx context.Context, req *pb_v1.GateCommandAddRequest) (reply *pb_v1.GateCommandAddReply, err error) {
  44. reply = &pb_v1.GateCommandAddReply{}
  45. // 捕获各个task中的异常并返回给调用者
  46. defer func() {
  47. if r := recover(); r != nil {
  48. err = fmt.Errorf("%+v", r)
  49. e := &status.Status{}
  50. if er := json.Unmarshal([]byte(err.Error()), e); er != nil {
  51. logger.Error("err",
  52. zap.String("system_err", err.Error()),
  53. zap.Stack("stacktrace"))
  54. }
  55. }
  56. }()
  57. err = checkGateCommandAddParam(req)
  58. if err != nil {
  59. return nil, err
  60. }
  61. gateInfo, err := getGateInfo(req.DeviceId, "", 0)
  62. if err != nil {
  63. return nil, err
  64. }
  65. commander := NewCommander(gateInfo)
  66. if commander == nil {
  67. return nil, status.Error(10003, "不支持的协议")
  68. }
  69. switch req.CmdCode {
  70. case gate_utils.OpenCommand:
  71. err = commander.Open()
  72. case gate_utils.RebootCommand:
  73. err = commander.Reboot()
  74. default:
  75. return nil, status.Error(10003, "暂不支持该命令")
  76. }
  77. if err != nil {
  78. return nil, err
  79. }
  80. if commander.Command() {
  81. gate_utils.CommandCacheIncrease(gateInfo.Sn, gateInfo.Protocol)
  82. }
  83. return reply, nil
  84. }