2025-09-21 03:51:25 +08:00

59 lines
1.7 KiB
Go

package radarfetch
import (
"encoding/json"
"fmt"
"net/http"
"time"
)
// Caiyun token and endpoint (fixed per user instruction)
const caiyunToken = "ZAcZq49qzibr10F0"
type caiyunRealtimeResp struct {
Status string `json:"status"`
Result struct {
Realtime struct {
Temperature float64 `json:"temperature"`
Humidity float64 `json:"humidity"`
Pressure float64 `json:"pressure"`
Wind struct {
Speed float64 `json:"speed"`
Direction float64 `json:"direction"`
} `json:"wind"`
} `json:"realtime"`
} `json:"result"`
}
// FetchCaiyunRealtime fetches 10m wind plus T/RH/P for given lon,lat.
// Returns: speed(m/s), dir_from(deg), tempC, humidity(0-1), pressurePa
func FetchCaiyunRealtime(lon, lat float64) (float64, float64, float64, float64, float64, error) {
url := fmt.Sprintf("https://api.caiyunapp.com/v2.6/%s/%.6f,%.6f/realtime?unit=metric", caiyunToken, lon, lat)
req, _ := http.NewRequest("GET", url, nil)
req.Header.Set("Accept", "application/json")
cli := &http.Client{Timeout: 8 * time.Second}
resp, err := cli.Do(req)
if err != nil {
return 0, 0, 0, 0, 0, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return 0, 0, 0, 0, 0, fmt.Errorf("caiyun http %d", resp.StatusCode)
}
var rr caiyunRealtimeResp
if err := json.NewDecoder(resp.Body).Decode(&rr); err != nil {
return 0, 0, 0, 0, 0, err
}
if rr.Status != "ok" {
return 0, 0, 0, 0, 0, fmt.Errorf("caiyun status %s", rr.Status)
}
rt := rr.Result.Realtime
return rt.Wind.Speed, rt.Wind.Direction, rt.Temperature, rt.Humidity, rt.Pressure, nil
}
// Backward-compatible wrapper (wind only)
func FetchCaiyunWind(lon, lat float64) (float64, float64, error) {
s, d, _, _, _, err := FetchCaiyunRealtime(lon, lat)
return s, d, err
}