device_status.go 4.9 KB

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