-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_energy_prices.go
130 lines (103 loc) · 2.55 KB
/
get_energy_prices.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
package internal
import (
"encoding/json"
"errors"
"io"
"log"
"math"
"net/http"
"net/url"
"time"
"github.com/heyajulia/energieprijzen/internal/fp"
)
var ErrStatus = errors.New("status code is not 200")
type energyPrices struct {
Prices []struct {
Price float64 `json:"price"`
ReadingDate time.Time `json:"readingDate"`
} `json:"Prices"`
IntervalType int `json:"intervalType"`
Average float64 `json:"average"`
FromDate time.Time `json:"fromDate"`
TillDate time.Time `json:"tillDate"`
}
type Price struct {
Hour int
Price float64
}
type EnergyPrices struct {
Prices []Price
Average float64
AverageHours []int
High float64
HighHours []int
Low float64
LowHours []int
}
func GetEnergyPrices() (*EnergyPrices, error) {
r, err := getEnergyPrices()
if err != nil {
return nil, err
}
var prices []Price
for i, price := range r.Prices {
hour := i
prices = append(prices, Price{hour, price.Price})
}
var e EnergyPrices
average := r.Average
low := min(prices)
high := max(prices)
priceIs := func(target float64) func(p Price) bool {
return func(p Price) bool {
return p.Price == target
}
}
e.Prices = prices
e.Average = average
e.AverageHours = fp.Pluck[Price, int]("Hour", fp.Where(priceIs(average), prices))
e.Low = low
e.LowHours = fp.Pluck[Price, int]("Hour", fp.Where(priceIs(low), prices))
e.High = high
e.HighHours = fp.Pluck[Price, int]("Hour", fp.Where(priceIs(high), prices))
return &e, nil
}
func getEnergyPrices() (*energyPrices, error) {
baseURL := "https://api.energyzero.nl/v1/energyprices"
queryParams := PrepareQueryParameters()
requestURL, err := url.Parse(baseURL)
if err != nil {
return nil, err
}
requestURL.RawQuery = queryParams
request, err := http.NewRequest("GET", requestURL.String(), nil)
if err != nil {
return nil, err
}
client := &http.Client{}
response, err := client.Do(request)
if err != nil {
return nil, err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return nil, ErrStatus
}
body, err := io.ReadAll(response.Body)
if err != nil {
return nil, err
}
log.Printf("status code %d, body: %#v\n", response.StatusCode, string(body))
var e energyPrices
err = json.Unmarshal(body, &e)
if err != nil {
return nil, err
}
return &e, nil
}
func min(prices []Price) float64 {
return fp.Reduce(math.Min, math.Inf(1), fp.Pluck[Price, float64]("Price", prices))
}
func max(prices []Price) float64 {
return fp.Reduce(math.Max, math.Inf(-1), fp.Pluck[Price, float64]("Price", prices))
}