weather.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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. 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 []*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(20 * time.Second)
  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 = NewTaskExecutor(task.Actions).Do(task.SceneId); 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(id string) error {
  92. scene := w.tasks.Get(id)
  93. if scene == nil {
  94. return nil
  95. }
  96. c := scene.(WeatherSceneConfig)
  97. c.stopChan <- struct{}{}
  98. w.tasks.Remove(c.SceneId)
  99. server.Log.Debugf("RemoveTimeScene :%s", c.SceneId)
  100. return nil
  101. }
  102. // Start 停止任务
  103. func (w *WeatherSceneService) Start(id string) error {
  104. if !w.tasks.Contains(id) {
  105. return errors.New("任务不存在")
  106. }
  107. task := w.tasks.Get(id)
  108. c := task.(WeatherSceneConfig)
  109. go w.monitorTask(c)
  110. return nil
  111. }
  112. // Stop 停止任务
  113. func (w *WeatherSceneService) Stop(id string) error {
  114. if !w.tasks.Contains(id) {
  115. return errors.New("任务不存在")
  116. }
  117. task := w.tasks.Get(id)
  118. c := task.(WeatherSceneConfig)
  119. c.stopChan <- struct{}{}
  120. return nil
  121. }
  122. // checkWeatherCondition 检查天气
  123. func (w *WeatherSceneService) checkWeatherCondition(config WeatherSceneConfig) (bool, error) {
  124. results := make([]bool, len(config.Conditions))
  125. for _, condition := range config.Conditions {
  126. // 获取天气数据
  127. weatherInfo, err := getWeatherInfo(condition.Location)
  128. fmt.Printf("任务 %s: 获取天气数据成功: %v\n", config.SceneId, weatherInfo)
  129. if err != nil {
  130. fmt.Printf("任务 %s: 获取天气数据失败: %v\n", config.SceneId, err)
  131. return false, err
  132. }
  133. results = append(results, utils.CheckValue(condition.TargetValue, weatherInfo[condition.Field], condition.FieldType, condition.Operator))
  134. }
  135. if len(results) == 0 {
  136. return false, nil
  137. }
  138. switch config.DecisionExpr {
  139. case "and":
  140. for _, v := range results {
  141. if !v {
  142. return false, nil
  143. }
  144. }
  145. return true, nil
  146. case "or":
  147. for _, v := range results {
  148. if v {
  149. return true, nil
  150. }
  151. }
  152. return false, nil
  153. default:
  154. return false, errors.New("无效的判断逻辑")
  155. }
  156. }
  157. func getWeatherInfo(location string) (map[string]interface{}, error) {
  158. // redis获取天气数据
  159. args := rpcs.ArgsGetWeather{Location: location}
  160. reply := rpcs.ReplayWeatherInfo{}
  161. err := server.RPCCallByName(nil, rpcs.DeviceManagerName, "DeviceManager.GetWeatherInfo", args, &reply)
  162. if err != nil {
  163. server.Log.Errorf("天气状态获取失败:%v", err)
  164. return nil, err
  165. }
  166. if reply.Info != "" {
  167. info := gjson.New(reply.Info)
  168. // 判断数据是否过期
  169. if !info.GetTime("last_update").Before(time.Now().Add(-time.Minute * 15)) {
  170. return info.Map(), nil
  171. }
  172. }
  173. weatherInfo, err := weather.GetWeatherInfo(location, "SgqF9ZGBUj7R0dLAb")
  174. if err != nil {
  175. return nil, err
  176. }
  177. j := gjson.New(weatherInfo)
  178. err = redisSaveWeatherInfo(location, j.MustToJsonString())
  179. return j.Map(), nil
  180. }
  181. func redisSaveWeatherInfo(location string, info string) error {
  182. args := rpcs.ArgsSetWeather{
  183. Location: location,
  184. Info: info,
  185. }
  186. reply := rpcs.ReplySetStatus{}
  187. err := server.RPCCallByName(nil, rpcs.DeviceManagerName, "DeviceManager.SetWeatherInfo", args, &reply)
  188. if err != nil {
  189. server.Log.Errorf("天气状态获取失败:%v", err)
  190. return err
  191. }
  192. return nil
  193. }