-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoctopusapi.go
248 lines (204 loc) · 6.88 KB
/
octopusapi.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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
package octopusenergyapi
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"github.com/pkg/errors"
)
var postcodeRegex *regexp.Regexp
func init() {
// Compile postcode regexp
postcodeRegex = regexp.MustCompile(`^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$`)
}
// NewClient returns a client
func NewClient(APIkey string, httpClient *http.Client) (*Client, error) {
// Empty APIkey is not permitted
APIkey = strings.TrimSpace(APIkey)
if len(APIkey) == 0 {
return nil, errors.New("API key should not be empty")
}
// Add APIkey as username to base URL
baseURL, err := urlAddUsername(baseURL, APIkey)
if err != nil {
return nil, errors.Errorf("unable to add username to url: %v", err)
}
return &Client{
URL: baseURL,
httpClient: httpClient,
}, nil
}
// GetMeterPoint retrieves an electricity meter point for a given MPAN
// https://developer.octopus.energy/docs/api/#electricity-meter-points
func (c *Client) GetMeterPoint(mpan string) (MeterPoint, error) {
data := struct {
GspID string `json:"gsp"`
MPAN string `json:"mpan"`
ProfileClass int `json:"profile_class"`
}{}
err := c.do(fmt.Sprintf("electricity-meter-points/%s/", mpan), &data)
if err != nil {
return MeterPoint{}, errors.Errorf("error retrieving meterpoint: %v", err)
}
// Mask JSON struct into MeterPoint
mPoint := MeterPoint{
MPAN: data.MPAN,
ProfileClass: data.ProfileClass,
}
for _, gsp := range GSPs {
if gsp.GSPGroupID == data.GspID {
mPoint.GSP = gsp
return mPoint, nil
}
}
return MeterPoint{}, errors.New("no grid supply point found")
}
// GetGridSupplyPoint gets a grid supply point based on postcode
// https://developer.octopus.energy/docs/api/#list-grid-supply-points
func (c *Client) GetGridSupplyPoint(postcode string) (GridSupplyPoint, error) {
// Check if postcode is valid
if !checkPostcode(postcode) {
return GridSupplyPoint{}, errors.Errorf("invalid postcode %s", postcode)
}
// Remove spaces from postcode
postcode = strings.ReplaceAll(postcode, " ", "")
// Struct for JSON unmarshalling
data := struct {
Count int `json:"count"`
Next string `json:"next"`
Previous string `json:"previous"`
Results []struct {
GroupID string `json:"group_id"`
} `json:"results"`
}{}
err := c.do(fmt.Sprintf("industry/grid-supply-points/?postcode=%s", postcode), &data)
if err != nil {
return GridSupplyPoint{}, errors.Errorf("error retrieving grid supply point: %v", err)
}
// Only return data if we are dealing with a single result
if len(data.Results) != 1 {
return GridSupplyPoint{}, errors.New("more than one supply point received")
}
for _, gsp := range GSPs {
if gsp.GSPGroupID == data.Results[0].GroupID {
return gsp, nil
}
}
return GridSupplyPoint{}, errors.New("unknown grid supply point")
}
// GetMeterConsumption retrieves meter consumption
// https://developer.octopus.energy/docs/api/#consumption
func (c *Client) getMeterConsumption(fuel, mpan, serialNo string, options ConsumptionOption) ([]Consumption, error) {
data := struct {
Count int `json:"count"`
NextPage string `json:"next"`
PreviousPage string `json:"previous"`
Results []Consumption `json:"results"`
}{}
apiURL, err := url.Parse(fmt.Sprintf("%s-meter-points/%s/meters/%s/consumption/", fuel, mpan, serialNo))
if err != nil {
return nil, errors.Errorf("unable to parse request url: %v", err)
}
// Add options to URL if they are provided
if options != (ConsumptionOption{}) {
q := apiURL.Query()
if options.PageSize != 0 {
q.Add("page_size", strconv.Itoa(options.PageSize))
}
if options.OrderBy != "" {
q.Add("order_by", options.OrderBy)
}
if options.GroupBy != "" {
q.Add("group_by", options.GroupBy)
}
if !options.From.IsZero() {
q.Add("period_from", options.From.Format(iso8601))
}
if !options.To.IsZero() {
q.Add("period_to", options.To.Format(iso8601))
}
apiURL.RawQuery = q.Encode()
}
err = c.do(apiURL.String(), &data)
if err != nil {
return nil, errors.Errorf("error retrieving meter consumption: %v", err)
}
return data.Results, nil
}
// GetElecMeterConsumption retrieves electricity consumption
// https://developer.octopus.energy/docs/api/#consumption
func (c *Client) GetElecMeterConsumption(mpan, serialNo string, options ConsumptionOption) ([]Consumption, error) {
return c.getMeterConsumption(fuelElectricity, mpan, serialNo, options)
}
// GetGasMeterConsumption retrieves electricity consumption
// https://developer.octopus.energy/docs/api/#consumption
func (c *Client) GetGasMeterConsumption(mpan, serialNo string, options ConsumptionOption) ([]Consumption, error) {
return c.getMeterConsumption(fuelGas, mpan, serialNo, options)
}
// checkPostcode checks if provided string is a valid UK postcode
func checkPostcode(postcode string) bool {
return postcodeRegex.MatchString(postcode)
}
// listProductsPage retrieves products from a single page of JSON data
func (c *Client) listProductsPage(URL string) ([]Product, string, error) {
var data productJSON
err := c.do(URL, &data)
if err != nil {
return nil, "", errors.Errorf("error retrieving: %v", err)
}
return data.Results, strings.TrimPrefix(data.Next, baseURL), nil
}
// ListProducts returns a list of energy products
// https://developer.octopus.energy/docs/api/#list-products
func (c *Client) ListProducts() ([]Product, error) {
var products []Product
URL := "/products/"
for {
pageProducts, url, err := c.listProductsPage(URL)
URL = url
if err != nil {
return nil, errors.Errorf("error retrieving products page: %v", err)
}
products = append(products, pageProducts...)
if URL == "" {
break
}
}
return products, nil
}
// GetProduct retrieves a product based on its name
// https://developer.octopus.energy/docs/api/#retrieve-a-product
func (c *Client) GetProduct(productCode string) (Product, error) {
var product Product
err := c.do(fmt.Sprintf("products/%s/", productCode), &product)
if err != nil {
return Product{}, errors.Errorf("error retrieving the product: %v", err)
}
return product, nil
}
// urlAddUsername adds username to URL
func urlAddUsername(URL, username string) (string, error) {
u, err := url.Parse(URL)
if err != nil {
return "", errors.Errorf("error parsing url: %v", err)
}
u.User = url.UserPassword(username, "")
return u.String(), nil
}
func (c *Client) do(path string, v interface{}) error {
resp, err := c.httpClient.Get(fmt.Sprintf("%s/%s", c.URL, path))
if err != nil {
return errors.Errorf("http get error: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return errors.Errorf("http error - code %d received", resp.StatusCode)
}
if err = json.NewDecoder(resp.Body).Decode(&v); err != nil {
return errors.Errorf("unable to unmarshal json: %v", err)
}
return nil
}