feat: Add yr package

Signed-off-by: Tim Hårek Andreassen <tim@harek.no>
This commit is contained in:
Tim Hårek Andreassen 2024-09-26 10:07:10 +02:00
parent dd25c4e6cb
commit b97a5e415a
No known key found for this signature in database
GPG key ID: E59C7734F0E10EB5
2 changed files with 74 additions and 17 deletions

View file

@ -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)
}

65
yr.go Normal file
View file

@ -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())
}