device_status.go 4.8 KB

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