rule_action.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package rule
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "sparrow/pkg/models"
  6. "sparrow/pkg/productconfig"
  7. "sparrow/pkg/rpcs"
  8. "sparrow/pkg/server"
  9. "strings"
  10. )
  11. func performRuleAction(target string, action string) error {
  12. server.Log.Infof("trigger rule action: %v, %v", target, action)
  13. parts := strings.Split(target, "/")
  14. if len(parts) != 3 {
  15. return fmt.Errorf("error target format: %v", target)
  16. }
  17. identifier := parts[1]
  18. device := &models.Device{}
  19. err := server.RPCCallByName("registry", "Registry.FindDeviceByIdentifier", identifier, device)
  20. if err != nil {
  21. return err
  22. }
  23. product := &models.Product{}
  24. err = server.RPCCallByName("registry", "Registry.FindProduct", device.ProductID, product)
  25. if err != nil {
  26. return err
  27. }
  28. config, err := productconfig.New(product.ProductConfig)
  29. if err != nil {
  30. return err
  31. }
  32. var args interface{}
  33. err = json.Unmarshal([]byte(action), &args)
  34. if err != nil {
  35. server.Log.Errorf("marshal action error: %v", err)
  36. return err
  37. }
  38. m, ok := args.(map[string]interface{})
  39. if !ok {
  40. server.Log.Errorf("decode action error:%v", err)
  41. return fmt.Errorf("decode action error:%v", err)
  42. }
  43. sendType := parts[2]
  44. switch sendType {
  45. case "command":
  46. command, err := config.MapToCommand(m)
  47. if err != nil {
  48. server.Log.Errorf("action format error: %v", err)
  49. return err
  50. }
  51. cmdargs := rpcs.ArgsSendCommand{
  52. DeviceId: uint64(device.ID),
  53. SubDevice: uint16(command.Head.SubDeviceid),
  54. No: uint16(command.Head.No),
  55. WaitTime: uint32(3000),
  56. Params: command.Params,
  57. }
  58. cmdreply := rpcs.ReplySendCommand{}
  59. err = server.RPCCallByName("controller", "Controller.SendCommand", cmdargs, &cmdreply)
  60. if err != nil {
  61. server.Log.Errorf("send device command error: %v", err)
  62. return err
  63. }
  64. case "status":
  65. status, err := config.MapToStatus(m)
  66. if err != nil {
  67. return err
  68. }
  69. statusargs := rpcs.ArgsSetStatus{
  70. DeviceId: uint64(device.ID),
  71. Status: status,
  72. }
  73. statusreply := rpcs.ReplySetStatus{}
  74. err = server.RPCCallByName("controller", "Controller.SetStatus", statusargs, &statusreply)
  75. if err != nil {
  76. server.Log.Errorf("set devie status error: %v", err)
  77. return err
  78. }
  79. default:
  80. server.Log.Errorf("wrong action %v", action)
  81. }
  82. return nil
  83. }