weather.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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/server"
  9. "sparrow/pkg/utils"
  10. "sparrow/services/scene-service/internal/service"
  11. "time"
  12. weather "weather-api-sdk"
  13. )
  14. // WeatherSceneConfig 天气监控任务配置
  15. type WeatherSceneConfig struct {
  16. SceneId string `json:"scene_id"` // 任务id
  17. DecisionExpr string `json:"decision_expr"` // 条件表达式 and or
  18. Conditions []*WeatherCondition `json:"conditions"` // 条件
  19. Interval int `json:"interval"` // 检查间隔(分钟)
  20. Actions []*service.Action `json:"actions"` // 执行动作
  21. ticker *time.Ticker `json:"-"` // 定时器
  22. stopChan chan struct{} `json:"-"` // 停止信号通道
  23. }
  24. type WeatherCondition struct {
  25. Location string `json:"location"` // 地点
  26. FieldType int `json:"field_type"` // 字段类型 1字符串 2数值
  27. Operator int `json:"operator"` // 比较类型 数值比较 1 > 2 >= 3 = 4 <= 5 < 6 != 字符串比较 1 相等 2 不相等
  28. Field string `json:"field"` // 字段名
  29. TargetValue string `json:"target_value"` // 目标值
  30. }
  31. type WeatherSceneService struct {
  32. tasks *gmap.HashMap
  33. }
  34. func NewWeatherSceneService() *WeatherSceneService {
  35. return &WeatherSceneService{
  36. tasks: gmap.NewHashMap(true),
  37. }
  38. }
  39. func (w *WeatherSceneService) Add(config string) error {
  40. var c WeatherSceneConfig
  41. err := json.Unmarshal([]byte(config), &c)
  42. if err != nil {
  43. }
  44. if len(c.Conditions) == 0 {
  45. return errors.New("天气监控任务配置错误:判断条件不能为空")
  46. }
  47. // 初始化Ticker和停止通道
  48. c.ticker = time.NewTicker(time.Duration(c.Interval) * time.Minute)
  49. c.stopChan = make(chan struct{})
  50. // 启动监控协程
  51. go w.monitorTask(c)
  52. w.tasks.Set(c.SceneId, c)
  53. return nil
  54. }
  55. // monitorTask 监控任务:使用select监听Ticker和停止信号
  56. func (w *WeatherSceneService) monitorTask(task WeatherSceneConfig) {
  57. for {
  58. select {
  59. case <-task.ticker.C: // 定时触发
  60. result, err := w.checkWeatherCondition(task)
  61. if err != nil {
  62. server.Log.Errorf("compare weather condition error :%s", err.Error())
  63. }
  64. if result {
  65. if err = service.NewTaskExecutor(task.Actions).Do(); err != nil {
  66. server.Log.Errorf("weather do taskid :%s error:%s", task.SceneId, err.Error())
  67. }
  68. }
  69. case <-task.stopChan: // 收到停止信号
  70. task.ticker.Stop()
  71. return
  72. }
  73. }
  74. }
  75. func (w *WeatherSceneService) Update(config string) error {
  76. var c WeatherSceneConfig
  77. err := json.Unmarshal([]byte(config), &c)
  78. if err != nil {
  79. server.Log.Errorf("config to timerConfig error :%s", err.Error())
  80. }
  81. _ = w.Stop(c.SceneId)
  82. // 初始化Ticker和停止通道
  83. c.ticker = time.NewTicker(time.Duration(c.Interval) * time.Minute)
  84. c.stopChan = make(chan struct{})
  85. // 启动监控协程
  86. go w.monitorTask(c)
  87. w.tasks.Set(c.SceneId, c)
  88. server.Log.Debugf("UpdateWeatherScene :%s", config)
  89. return nil
  90. }
  91. func (w *WeatherSceneService) Remove(config string) error {
  92. var c WeatherSceneConfig
  93. err := json.Unmarshal([]byte(config), &c)
  94. if err != nil {
  95. server.Log.Errorf("config to timerConfig error :%s", err.Error())
  96. }
  97. w.tasks.Remove(c.SceneId)
  98. server.Log.Debugf("RemoveTimeScene :%s", c.SceneId)
  99. return nil
  100. }
  101. // Start 停止任务
  102. func (w *WeatherSceneService) Start(id string) error {
  103. if !w.tasks.Contains(id) {
  104. return errors.New("任务不存在")
  105. }
  106. task := w.tasks.Get(id)
  107. c := task.(WeatherSceneConfig)
  108. go w.monitorTask(c)
  109. return nil
  110. }
  111. // Stop 停止任务
  112. func (w *WeatherSceneService) Stop(id string) error {
  113. if !w.tasks.Contains(id) {
  114. return errors.New("任务不存在")
  115. }
  116. task := w.tasks.Get(id)
  117. c := task.(WeatherSceneConfig)
  118. c.stopChan <- struct{}{}
  119. return nil
  120. }
  121. // checkWeatherCondition 检查天气
  122. func (w *WeatherSceneService) checkWeatherCondition(config WeatherSceneConfig) (bool, error) {
  123. results := make([]bool, len(config.Conditions))
  124. for _, condition := range config.Conditions {
  125. // 获取天气数据
  126. weatherInfo, err := getWeatherInfo(condition.Location)
  127. fmt.Printf("任务 %s: 获取天气数据成功: %v\n", config.SceneId, weatherInfo)
  128. if err != nil {
  129. fmt.Printf("任务 %s: 获取天气数据失败: %v\n", config.SceneId, err)
  130. return false, err
  131. }
  132. results = append(results, utils.CheckValue(condition.TargetValue, weatherInfo[condition.Field], condition.FieldType, condition.Operator))
  133. }
  134. switch config.DecisionExpr {
  135. case "and":
  136. for _, v := range results {
  137. if !v {
  138. return false, nil
  139. }
  140. }
  141. case "or":
  142. for _, v := range results {
  143. if v {
  144. return true, nil
  145. }
  146. }
  147. }
  148. return true, nil
  149. }
  150. func getWeatherInfo(location string) (map[string]interface{}, error) {
  151. weatherInfo, err := weather.GetWeatherInfo(location, "SgqF9ZGBUj7R0dLAb")
  152. if err != nil {
  153. return nil, err
  154. }
  155. return gjson.New(weatherInfo).Map(), nil
  156. }