feat: Add yr package
Signed-off-by: Tim Hårek Andreassen <tim@harek.no>
This commit is contained in:
parent
dd25c4e6cb
commit
b97a5e415a
2 changed files with 74 additions and 17 deletions
26
cmd/yr.go
26
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)
|
||||
}
|
||||
|
|
65
yr.go
Normal file
65
yr.go
Normal 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())
|
||||
}
|
Loading…
Reference in a new issue