executer.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. package manager
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "github.com/gogf/gf/util/guid"
  7. "sparrow/pkg/models"
  8. "sparrow/pkg/rpcs"
  9. "sparrow/pkg/server"
  10. "sparrow/pkg/utils"
  11. "strings"
  12. "time"
  13. )
  14. type Action struct {
  15. ActionId string `json:"action_id"` // 动作ID
  16. DeviceID string `json:"device_id"` // 设备ID
  17. SubDeviceId string `json:"sub_device_id"` // 实体子设备Id,如果需要
  18. ActionExecutor string `json:"action_executor"` // 动作对象类型
  19. ExecutorProperty *TaskExecutorProperty `json:"executor_property"` // 动作执行明细
  20. PlcPubMessage *PlcPubMessage `json:"plc_pub_message"` // PLC消息
  21. }
  22. // TaskExecutorProperty 定时任务执行动作执行参数
  23. type TaskExecutorProperty struct {
  24. /*
  25. 指令 code。当 action_executor 是 device_issue 或 device_group_issue 时,此参数必填。
  26. */
  27. FunctionCode string `json:"function_code"`
  28. /*
  29. 指令 value。当 action_executor 是 device_issue 或 device_group_issue 时,此参数必填。
  30. */
  31. FunctionValue map[string]interface{} `json:"function_value"`
  32. /*
  33. 延时时间。当 action_executor 是 delay 时,此参数必填。
  34. */
  35. DelaySeconds int64 `json:"delay_seconds"`
  36. }
  37. type PlcPubMessage struct {
  38. Topic string `json:"topic"`
  39. Payload []byte `json:"payload"`
  40. }
  41. // TaskExecutor 任务执行器,用来执行具体的任务动作
  42. type TaskExecutor struct {
  43. Actions []*Action
  44. client *utils.HttpClient
  45. }
  46. func NewTaskExecutor(actions []*Action) *TaskExecutor {
  47. client := utils.NewHttpClient()
  48. client.SetLogger(server.Log)
  49. return &TaskExecutor{
  50. Actions: actions,
  51. client: client,
  52. }
  53. }
  54. func (a *TaskExecutor) Do(id string) error {
  55. for _, action := range a.Actions {
  56. if err := a.doTask(action); err != nil {
  57. return err
  58. }
  59. }
  60. return nil
  61. }
  62. func (a *TaskExecutor) doTask(action *Action) error {
  63. // 调用设备接入服务
  64. rpchost, err := getAccessRPCHost(action.DeviceID)
  65. if err != nil {
  66. return err
  67. }
  68. reply := &rpcs.ReplyEmptyResult{}
  69. if rpchost != "" {
  70. args := rpcs.ArgsSendCommand{
  71. DeviceId: action.DeviceID,
  72. SubDevice: action.SubDeviceId,
  73. Cmd: action.ExecutorProperty.FunctionCode,
  74. Params: action.ExecutorProperty.FunctionValue,
  75. }
  76. server.Log.Debugf("do Device Issue task args:%v", args)
  77. return server.RPCCallByHost(rpchost, "Access.SendCommand", args, reply)
  78. }
  79. var publishArgs rpcs.ArgsPublishMessage
  80. publishArgs.Topic = action.PlcPubMessage.Topic
  81. publishArgs.Payload = action.PlcPubMessage.Payload
  82. err = server.RPCCallByName(nil, rpcs.EmqxAgentServiceName, "Access.PublishMessage", publishArgs, reply)
  83. if err != nil {
  84. server.Log.Errorf("plc设备发送消息失败:%v", err)
  85. }
  86. fmt.Printf("plc设备发送消息成功:topic:%s,payload:%s", publishArgs.Topic, publishArgs.Payload)
  87. return nil
  88. }
  89. // 执行延时任务
  90. func (a *TaskExecutor) doDelayTask(action *Action) error {
  91. time.Sleep(time.Duration(action.ExecutorProperty.DelaySeconds) * time.Second)
  92. return a.doTask(action)
  93. }
  94. func getAccessRPCHost(deviceid string) (string, error) {
  95. args := rpcs.ArgsGetDeviceOnlineStatus{
  96. Id: deviceid,
  97. }
  98. reply := &rpcs.ReplyGetDeviceOnlineStatus{}
  99. err := server.RPCCallByName(nil, rpcs.DeviceManagerName, "DeviceManager.GetDeviceOnlineStatus", args, reply)
  100. if err != nil {
  101. return "", err
  102. }
  103. return reply.AccessRPCHost, nil
  104. }
  105. func (a *TaskExecutor) saveHis(id string, conditionId []string) error {
  106. // 收集所有动作ID
  107. var actionIds []string
  108. for _, action := range a.Actions {
  109. if action.ActionId != "" {
  110. actionIds = append(actionIds, action.ActionId)
  111. }
  112. }
  113. conditionIdStr := strings.Join(conditionId, ",")
  114. actionIdStr := strings.Join(actionIds, ",")
  115. // 1. 通过 RPC 调用 Registry 同步到本地数据库
  116. sceneHis := models.SceneHis{
  117. RecordId: guid.S(),
  118. SceneID: id,
  119. ConditionId: conditionIdStr,
  120. ActionId: actionIdStr,
  121. }
  122. rpcReply := rpcs.ReplyEmptyResult{}
  123. rpcErr := server.RPCCallByName(nil, rpcs.RegistryServerName, "Registry.CreateSceneHis", &sceneHis, &rpcReply)
  124. if rpcErr != nil {
  125. server.Log.Errorf("RPC保存场景执行历史失败: sceneId=%s, error=%s", id, rpcErr.Error())
  126. }
  127. // 2. 通过 HTTP POST 通知 knowoapi
  128. url := "http://127.0.0.1:8199/iot/v1/scene_history"
  129. body := make(map[string]interface{})
  130. body["scene_id"] = id
  131. if conditionIdStr != "" {
  132. body["condition_id"] = conditionIdStr
  133. }
  134. if actionIdStr != "" {
  135. body["action_id"] = actionIdStr
  136. }
  137. w := new(bytes.Buffer)
  138. if err := json.NewEncoder(w).Encode(body); err != nil {
  139. return err
  140. }
  141. req, err := utils.NewRequest("POST", url, w)
  142. if err != nil {
  143. server.Log.Error(err)
  144. return err
  145. }
  146. req.Header.Add("Content-Type", "application/json")
  147. _, err = a.client.Do(req)
  148. if err != nil {
  149. server.Log.Errorf("HTTP保存场景执行历史失败: sceneId=%s, error=%s", id, err.Error())
  150. }
  151. return err
  152. }