device_status.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. package manager
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "github.com/gogf/gf/container/gmap"
  7. "github.com/gogf/gf/encoding/gjson"
  8. "sparrow/pkg/rpcs"
  9. "sparrow/pkg/server"
  10. "sparrow/pkg/utils"
  11. "time"
  12. )
  13. type DeviceSceneConfig struct {
  14. SceneId string `json:"scene_id"`
  15. DecisionExpr string `json:"decision_expr"` // 条件表达式 and or
  16. Conditions []*DeviceCondition `json:"conditions"` // 条件
  17. Actions []*Action `json:"actions"` // 执行动作
  18. Interval int `json:"interval"` // 检查间隔(秒)
  19. ticker *time.Ticker `json:"-"` // 定时器
  20. stopChan chan struct{} `json:"-"` // 停止信号通道
  21. }
  22. // DeviceCondition 设备场景配置
  23. type DeviceCondition struct {
  24. ConditionId string `json:"condition_id"` // 条件id
  25. Key string `json:"key"` // redis key
  26. DeviceType string `json:"device_type"` // 设备类型
  27. DeviceId string `json:"device_id"` // 设备id
  28. SubDeviceId string `json:"sub_device_id"` // 子设备id
  29. FieldName string `json:"field_name"` // 字段名称
  30. FieldType int `json:"field_type"` // 字段类型 1字符串 2数值
  31. Field string `json:"field"` // 字段名
  32. TargetValue string `json:"target_value"` // 值
  33. Operator int `json:"operator"` // 比较类型 数值比较 1 > 2 >= 3 = 4 <= 5 < 6 !=
  34. }
  35. type DeviceSceneService struct {
  36. tasks *gmap.HashMap
  37. }
  38. func NewDeviceSceneService() *DeviceSceneService {
  39. return &DeviceSceneService{
  40. tasks: gmap.New(true),
  41. }
  42. }
  43. func (d *DeviceSceneService) Add(config string) error {
  44. var c DeviceSceneConfig
  45. err := json.Unmarshal([]byte(config), &c)
  46. if err != nil {
  47. }
  48. if len(c.Conditions) == 0 {
  49. return errors.New("设备状态监控任务配置错误:判断条件不能为空")
  50. }
  51. // 初始化Ticker和停止通道
  52. c.ticker = time.NewTicker(600 * time.Second)
  53. c.stopChan = make(chan struct{})
  54. // 启动监控协程
  55. go d.monitorTask(c)
  56. fmt.Printf("保存设备状态监控任务成功:%s\n", gjson.New(c).MustToJsonString())
  57. d.tasks.Set(c.SceneId, c)
  58. return nil
  59. }
  60. func (d *DeviceSceneService) Update(config string) error {
  61. var c DeviceSceneConfig
  62. err := json.Unmarshal([]byte(config), &c)
  63. if err != nil {
  64. server.Log.Errorf("config to timerConfig error :%s", err.Error())
  65. }
  66. _ = d.Stop(c.SceneId)
  67. // 初始化Ticker和停止通道
  68. c.ticker = time.NewTicker(600 * time.Second)
  69. c.stopChan = make(chan struct{})
  70. // 启动监控协程
  71. go d.monitorTask(c)
  72. d.tasks.Set(c.SceneId, c)
  73. server.Log.Debugf("UpdateWeatherScene :%s", config)
  74. return nil
  75. }
  76. func (d *DeviceSceneService) Remove(id string) error {
  77. scene := d.tasks.Get(id)
  78. if scene == nil {
  79. return nil
  80. }
  81. c := scene.(DeviceSceneConfig)
  82. c.stopChan <- struct{}{}
  83. d.tasks.Remove(c.SceneId)
  84. return nil
  85. }
  86. // Start 停止任务
  87. func (d *DeviceSceneService) Start(id string) error {
  88. if !d.tasks.Contains(id) {
  89. return errors.New("任务不存在")
  90. }
  91. task := d.tasks.Get(id)
  92. c := task.(DeviceSceneConfig)
  93. go d.monitorTask(c)
  94. return nil
  95. }
  96. // Stop 停止任务
  97. func (d *DeviceSceneService) Stop(id string) error {
  98. if !d.tasks.Contains(id) {
  99. return errors.New("任务不存在")
  100. }
  101. task := d.tasks.Get(id)
  102. c := task.(DeviceSceneConfig)
  103. c.stopChan <- struct{}{}
  104. return nil
  105. }
  106. // monitorTask 监控任务:使用select监听Ticker和停止信号
  107. func (d *DeviceSceneService) monitorTask(config DeviceSceneConfig) {
  108. for {
  109. select {
  110. case <-config.ticker.C: // 定时触发
  111. result, err := d.checkDeviceCondition(config)
  112. if err != nil {
  113. server.Log.Errorf("compare weather condition error :%s", err.Error())
  114. }
  115. if result.Result {
  116. taskExecutor := NewTaskExecutor(config.Actions)
  117. if err = taskExecutor.Do(config.SceneId); err != nil {
  118. server.Log.Errorf("device_status do taskid :%s error:%s", config.SceneId, err.Error())
  119. }
  120. _ = taskExecutor.saveHis(config.SceneId, result.ConditionId)
  121. }
  122. case <-config.stopChan: // 收到停止信号
  123. config.ticker.Stop()
  124. return
  125. }
  126. }
  127. }
  128. func (d *DeviceSceneService) checkDeviceCondition(config DeviceSceneConfig) (CheckResult, error) {
  129. var results []bool
  130. var checkResult CheckResult
  131. var err error
  132. for _, v := range config.Conditions {
  133. var args rpcs.ArgsGetStatus
  134. args.Key = v.Key
  135. var reply rpcs.ReplyStatus
  136. err := server.RPCCallByName(nil, rpcs.DeviceManagerName, "DeviceManager.GetDeviceStatusByKey", args, &reply)
  137. if err != nil {
  138. server.Log.Errorf("设备状态数据获取失败:%v", err)
  139. return checkResult, err
  140. }
  141. j := gjson.New(reply.Status)
  142. // 判断是否满足条件并填入到result
  143. result := utils.CheckValue(v.TargetValue, j.Get(v.Field), v.FieldType, v.Operator)
  144. if result {
  145. checkResult.ConditionId = append(checkResult.ConditionId, v.ConditionId)
  146. }
  147. results = append(results, result)
  148. }
  149. switch config.DecisionExpr {
  150. case "and":
  151. for _, v := range results {
  152. if !v {
  153. checkResult.Result = false
  154. }
  155. }
  156. checkResult.Result = true
  157. case "or":
  158. for _, v := range results {
  159. if v {
  160. checkResult.Result = true
  161. }
  162. }
  163. default:
  164. err = errors.New("无效的判断逻辑")
  165. }
  166. return checkResult, err
  167. }