From b97a5e415a12f45ffec829cf140c03fe4fdf6a89 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tim=20H=C3=A5rek=20Andreassen?= Date: Thu, 26 Sep 2024 10:07:10 +0200 Subject: [PATCH] feat: Add yr package MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Tim HĂ„rek Andreassen --- cmd/yr.go | 26 ++++++++-------------- yr.go | 65 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+), 17 deletions(-) create mode 100644 yr.go diff --git a/cmd/yr.go b/cmd/yr.go index 4ae4fb7..c8dc428 100644 --- a/cmd/yr.go +++ b/cmd/yr.go @@ -1,29 +1,21 @@ package main import ( - "encoding/json" "fmt" - "git.sr.ht/~timharek/yr-go/internal/met" + "git.sr.ht/~timharek/yr-go" ) func main() { - m, err := met.New("git.sr.ht/~timharek/yr-go") + y, err := yr.New() if err != nil { - fmt.Println(err) - return + panic(err) + } + now, err := y.Now("bergen") + if err != nil { + panic(err) } - forecast, err := m.Forecast(60.389444, 5.33, nil) - if err != nil { - fmt.Println(err) - return - } - - f, err := json.Marshal(forecast) - if err != nil { - fmt.Println(err) - return - } - fmt.Printf("%s", f) + fmt.Printf("Temp: %.4f\n", now.Temperature) + fmt.Printf("Rain: %.4f\n", now.Percipitation) } diff --git a/yr.go b/yr.go new file mode 100644 index 0000000..498436e --- /dev/null +++ b/yr.go @@ -0,0 +1,65 @@ +package yr + +import ( + "cmp" + "fmt" + "slices" + + "git.sr.ht/~timharek/yr-go/internal/met" + "git.sr.ht/~timharek/yr-go/internal/nominatim" +) + +type Client struct { + met met.Met + nom nominatim.Nominatim +} + +func New() (*Client, error) { + siteName := "git.sr.ht/~timharek/yr-go" + met, err := met.New(siteName) + if err != nil { + return nil, err + } + nom, err := nominatim.New(siteName) + if err != nil { + return nil, err + } + + return &Client{met: *met, nom: *nom}, nil +} + +type NowForecast struct { + Temperature float64 + Percipitation float64 +} + +func (c *Client) Now(q string) (*NowForecast, error) { + coords, err := c.nom.Lookup(q) + if err != nil { + return nil, err + } + + f, err := c.met.Forecast(coords.Latitude, coords.Longitude, nil) + if err != nil { + return nil, err + } + + ts := f.Properties.Timeseries + + if len(ts) == 0 { + return nil, fmt.Errorf("Forecast unavailable") + } + + slices.SortFunc(ts, sortTimeSeries) + + latest := ts[0].Data + + return &NowForecast{ + Temperature: latest.Instant.Details.AirTemperature, + Percipitation: latest.Next1_Hours.Details.PrecipitationAmount, + }, nil +} + +func sortTimeSeries(a, b met.Timeseries) int { + return cmp.Compare(a.Time.Unix(), b.Time.Unix()) +}