package main import ( "cicv-data-closedloop/pjisuv_ticker" "encoding/json" "fmt" "io/ioutil" "net/http" "sync" "time" ) // 这个触发器必须保证是工作状态,其他和天气有关的触发器才能生效!!! var ( threshold float64 = 60.0 apiKey = "f9d230f00d9ccdba49a97e043333d410" maxRetries = 5 retryDelay = time.Second * 2 ) type Weather struct { WeatherID []int temperature float64 humidity float64 } // 定时任务触发器固定的 func Topic() string { return pjisuv_ticker.TickerTopic } // ******* 禁止存在下划线_ // 触发器标记 func Label() string { return "WetWeather" } func OpenWeatherAPI(latitude float64, longitude float64) Weather { var data map[string]interface{} var weather = Weather{} for retries := 0; retries < maxRetries; retries++ { url := fmt.Sprintf("https://api.openweathermap.org/data/2.5/weather?lat=%f&lon=%f&appid=%s", latitude, longitude, apiKey) resp, err := http.Get(url) if err != nil { fmt.Println("Error:", err) time.Sleep(retryDelay) continue } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println("Error reading response:", err) time.Sleep(retryDelay) continue } if err := json.Unmarshal(body, &data); err != nil { fmt.Println("Error parsing JSON:", err) time.Sleep(retryDelay) continue } // Successfully retrieved data break } if data == nil { fmt.Println("Failed to retrieve data after maximum retries.") return weather } mainData := data["main"].(map[string]interface{}) weather.temperature = mainData["temp"].(float64) - 273.15 weather.humidity = mainData["humidity"].(float64) for _, w := range data["weather"].([]interface{}) { tianqi := w.(map[string]interface{}) weather.WeatherID = append(weather.WeatherID, int(tianqi["id"].(float64))) } fmt.Printf("当前位置的天气状况/温度/湿度:%v/%.2f/%.2f\n", weather.WeatherID, weather.temperature, weather.humidity) return weather } func Rule(shareVars *sync.Map) { defer func() { if r := recover(); r != nil { fmt.Println("Recovered from panic:", r) } }() // 1 使用goroutine go func(shareVars *sync.Map) { // 2 定义触发器的间隔时间 ticker := time.NewTicker(time.Duration(120) * time.Second) defer ticker.Stop() // 3 运行一个无限循环 for { select { // 定时器触发时执行的代码 case <-ticker.C: FinalCallback(shareVars) } } }(shareVars) } func FinalCallback(shareVars *sync.Map) { OutsideWorkshopFlag, ok := shareVars.Load("OutsideWorkshopFlag") Latitude, ok1 := shareVars.Load("Latitude") Longitude, ok2 := shareVars.Load("Longitude") if ok && ok1 && ok2 && OutsideWorkshopFlag.(bool) == true { NOwWeather := OpenWeatherAPI(Latitude.(float64), Longitude.(float64)) shareVars.Store("Weather", NOwWeather) if NOwWeather.WeatherID != nil { if NOwWeather.humidity > threshold { eventLabel := "WetWeather" fmt.Println(eventLabel) pjisuv_ticker.TickerChan <- pjisuv_ticker.TickInfo{FaultLabel: Label(), FaultHappenTime: pjisuv_ticker.GetNowTimeCustom()} } } } }