-
Notifications
You must be signed in to change notification settings - Fork 0
/
gotoon.go
520 lines (445 loc) · 15.9 KB
/
gotoon.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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
package gotoon
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/url"
"strconv"
"time"
)
const (
authorizeURL = "https://api.toon.eu/authorize"
tokenURL = "https://api.toon.eu/token"
apiBaseURL = "https://api.toon.eu/toon/v3"
)
// jsonTime defines customized JSON marshal and unmarshal functions
// for converting timestamp into Time struct.
type jsonTime time.Time
// MarshalJSON marshals Time struct into timestamp integer in milliseconds.
func (t jsonTime) MarshalJSON() ([]byte, error) {
return []byte(strconv.FormatInt(time.Time(t).Unix(), 10)), nil
}
// UnmarshalJSON unmarshals timestamp integer in milliseconds into Time struct.
func (t *jsonTime) UnmarshalJSON(s []byte) (err error) {
q, err := strconv.ParseInt(string(s), 10, 64)
if err != nil {
return err
}
*(*time.Time)(t) = time.Unix(q/1000, 0)
return
}
func (t jsonTime) String() string { return time.Time(t).String() }
// jsonBool defines customized JSON unmarshal function for converting
// integer into boolean.
type jsonBool bool
// UnmarshalJSON converts input string or integer into a boolean value.
func (b *jsonBool) UnmarshalJSON(s []byte) (err error) {
bs := string(s)
if bs == "0" || bs == "false" {
*b = false
} else if bs == "1" || bs == "true" {
*b = true
} else {
err = fmt.Errorf("Cannot unmarshal value to boolean: %s", bs)
}
return
}
// token holds the data structure of the Toon API access token.
type token struct {
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in,string"`
ExpiresAt time.Time
RefreshToken string `json:"refresh_token"`
RefreshTokenExpiresIn int `json:"refresh_token_expires_in,string"`
RefreshTokenExpiresAt time.Time
}
// Agreement holds the data structure of the Toon API agreement. See https://developer.toon.eu/api-intro.
type Agreement struct {
AgreementID string `json:"agreementId"`
AgreementIDChecksum string `json:"agreementIdChecksum"`
HeatingType string `json:"heatingType"`
DisplayCommonName string `json:"displayCommonName"`
DisplayHardwareVersion string `json:"displayHardwareVersion"`
DisplaySoftwareVersion string `json:"displaySoftwareVersion"`
IsToonSolar bool `json:"isToonSolar"`
IsToonly bool `json:"isToonly"`
}
// ThermostatStates holds the data structure of the last states retrieved from
// the getStatus interface of the Toon API.
type ThermostatStates struct {
State []ThermostatState `json:"state"`
LastUpdatedFromDisplay jsonTime `json:"lastUpdatedFromDisplay,int"`
}
// ThermostatState holds the data structure of a state retrieved from the getStatus
// interface of the Toon API.
type ThermostatState struct {
ID int `json:"id"`
TempValue int `json:"tempValue"`
Dhw int `json:"dhw"`
}
// ThermostatInfo holds the data structure of the thermostat information retrieved
// from the getStatus interface of the Toon API.
type ThermostatInfo struct {
CurrentSetPoint int `json:"currentSetpoint"`
CurrentDisplayTemp int `json:"currentDisplayTemp"`
ProgramState int `json:"programState"`
ActiveState int `json:"activeState"`
NextProgram int `json:"nextProgram"`
NextState int `json:"nextState"`
NextTime int `json:"nextTime"`
NextSetPoint int `json:"nextSetpoint"`
ErrorFound int `json:"errorFound"`
BoilerModuleConnected int `json:"boilerModuleConnected"`
RealSetPoint int `json:"realSetpoint"`
BurnerInfo string `json:"burnerInfo"`
OtCommError string `json:"otCommError"`
CurrentModulationLevel int `json:"currentModulationLevel"`
HaveOTBoiler int `json:"haveOTBoiler"`
LastUpdatedFromDisplay jsonTime `json:"lastUpdatedFromDisplay,int"`
}
// PowerUsage holds the data structure of the current power consumption retrieved from
// the getStatus interface of the Toon API.
type PowerUsage struct {
Value int `json:"value"`
DayCost float32 `json:"dayCost,int"`
ValueProduced int `json:"valueProduced"`
DayCostProduced int `json:"dayCostProduced"`
ValueSolar int `json:"valueSolar"`
MaxSolar int `json:"maxSolar"`
DayCostSolar int `json:"dayCostSolar"`
AvgSolarValue int `json:"avgSolarValue"`
AvgValue float32 `json:"avgValue"`
AvgDayValue float32 `json:"avgDayValue"`
AvgProduValue int `json:"avgProduValue"`
AvgDayProduValue int `json:"avgDayProduValue"`
MeterReading int `json:"meterReading"`
MeterReadingLow int `json:"meterReadingLow"`
MeterReadingProdu int `json:"meterReadingProdu"`
MeterReadingLowProdu int `json:"meterReadingLowProdu"`
DayUsage int `json:"dayUsage"`
DayLowUsage int `json:"dayLowUsage"`
TodayLowestUsage int `json:"todayLowestUsage"`
IsSmart jsonBool `json:"isSmart,int"`
LowestDayValue int `json:"lowestDayValue"`
SolarProducedToday int `json:"solarProducedToday"`
LastUpdatedFromDisplay jsonTime `json:"lastUpdatedFromDisplay,int"`
}
// GasUsage holds the data structure of the current gas consumption retrieved from
// the getStatus interface of the Toon API.
type GasUsage struct {
Value int `json:"value"`
DayCost float32 `json:"dayCost"`
AvgValue float32 `json:"avgValue"`
MeterReading int `json:"meterReading"`
AvgDayValue float32 `json:"avgDayValue"`
DayUsage int `json:"dayUsage"`
IsSmart jsonBool `json:"isSmart,int"`
LastUpdatedFromDisplay jsonTime `json:"lastUpdatedFromDisplay,int"`
}
// Status holds the main data structure of the current Toon device status retrieved
// from the getStatus interface of the Toon API.
type Status struct {
ThermostatStates ThermostatStates `json:"thermostatStates"`
ThermostatInfo ThermostatInfo `json:"thermostatInfo"`
PowerUsage PowerUsage `json:"powerUsage"`
GasUsage GasUsage `json:"gasUsage"`
LastUpdateFromDisplay jsonTime `json:"lastUpdateFromDisplay,int"`
}
// FlowDataPoint holds the data structure of the consumption data points.
type FlowDataPoint struct {
Timestamp jsonTime `json:"timestamp,int"`
Unit string `json:"unit"`
Value float32 `json:"value"`
}
// FlowData holds the data structure of the consumption data.
type FlowData struct {
Hours []FlowDataPoint `json:"hours"`
Days []FlowDataPoint `json:"days"`
Weeks []FlowDataPoint `json:"weeks"`
Months []FlowDataPoint `json:"months"`
Years []FlowDataPoint `json:"years"`
}
// Toon provides interface to access and retrieve data from the Toon device,
// using the Toon RESTful APIs, see https://developer.toon.eu.
type Toon struct {
// Username is the Tenant account name for the Tenant (e.g. the Mijn Eneco account)
Username string
// Password is the password for the Tenant account (e.g. the Mijn Eneco password)
Password string
// TenantID is the tenant ID (e.g. eneco, viesgo)
TenantID string
// ConsumerKey is the consumer key of the Toon API, see https://developer.toon.eu/authentication
ConsumerKey string
// ConsumerSecret is the consumer secret of the Toon API, see https://developer.toon.eu/authentication
ConsumerSecret string
// accessToken is the current Toon API access token, see https://developer.toon.eu/authentication
accessToken token
}
// getAccessToken authorise the user to get the access token for retriving data
// from the Toon device.
func (t *Toon) getAccessToken() (err error) {
c := newHTTPSClient()
// step 1: call https://api.toon.eu/authorize (optionally?)
// with input: client_id, response_type=code, redirect_url=http://127.0.0.1, tenant_id
// This step doesn't seem to be necessary. Comment it out for the moment.
// v := url.Values{}
// v.Set("client_id", t.ConsumerKey)
// v.Set("response_type", "code")
// v.Set("redirect_url", "http://127.0.0.1")
// v.Set("tenant_id", t.TenantID)
// _, err = c.Get(authorizeURL + v.Encode())
// if err != nil {
// return
// }
// step 2: call https://api.toon.eu/authorize/legacy to get "code" from the returned HTTP header
// with input: client_id, tenant_id, username, password, response_type=code,
// state='', scope=''
v := url.Values{}
v.Set("client_id", t.ConsumerKey)
v.Set("tenant_id", t.TenantID)
v.Set("username", t.Username)
v.Set("password", t.Password)
v.Set("response_type", "code")
v.Set("state", "")
v.Set("scope", "")
// disable http redirect
c.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}
r, err := c.PostForm(authorizeURL+"/legacy", v)
if err != nil {
return
}
if r.StatusCode != 302 {
err = errors.New("invalid consumer key")
return
}
// parsing Location header attribute to get value of the "code"
u, err := url.Parse(r.Header.Get("Location"))
if err != nil {
return
}
code := u.Query().Get("code")
if code == "" {
err = fmt.Errorf("fail extracting code, header: +%v", r.Header)
}
// step 3: call https://api.toon.eu/token to get the access token
v = url.Values{}
v.Set("client_id", t.ConsumerKey)
v.Set("client_secret", t.ConsumerSecret)
v.Set("grant_type", "authorization_code")
v.Set("code", code)
// current time
tnow := time.Now()
r, err = c.PostForm(tokenURL, v)
if err != nil {
return
}
bodyBytes, err := ioutil.ReadAll(r.Body)
if err != nil {
return
}
// unmarshal response body to Token struct
if err = json.Unmarshal(bodyBytes, &(t.accessToken)); err != nil {
return
}
// derive ExpiresAt = tnow + (ExpiresIn - 180)s
t.accessToken.ExpiresAt = tnow.Add(time.Second * time.Duration(t.accessToken.ExpiresIn-180))
t.accessToken.RefreshTokenExpiresAt = tnow.Add(time.Second * time.Duration(t.accessToken.RefreshTokenExpiresIn-180))
return
}
// refreshAccessToken retrieved a new token with user credential, using the valid refresh_token.
// The function doesn't check the validity of the refresh_token; thus the caller must ensure it.
//
// Once the token is successfully refreshed, the accessToken is updated.
func (t *Toon) refreshAccessToken() (err error) {
v := url.Values{}
v.Set("client_id", t.ConsumerKey)
v.Set("client_secret", t.ConsumerSecret)
v.Set("grant_type", "refresh_token")
v.Set("refresh_token", t.accessToken.RefreshToken)
c := newHTTPSClient()
r, err := c.PostForm(tokenURL, v)
if err != nil {
return
}
bodyBytes, err := ioutil.ReadAll(r.Body)
if err != nil {
return
}
// unmarshal response body to Token struct
if err = json.Unmarshal(bodyBytes, &(t.accessToken)); err != nil {
return
}
// derive ExpiresAt = tnow + (ExpiresIn - 180)s
tnow := time.Now()
t.accessToken.ExpiresAt = tnow.Add(time.Second * time.Duration(t.accessToken.ExpiresIn-180))
t.accessToken.RefreshTokenExpiresAt = tnow.Add(time.Second * time.Duration(t.accessToken.RefreshTokenExpiresIn-180))
return
}
func (t *Toon) hasValidToken() (isValid bool) {
// the accessToken is not set
if &(t.accessToken) == nil {
isValid = false
return
}
// the refresh token has been expired
if t.accessToken.RefreshTokenExpiresAt.Before(time.Now()) {
isValid = false
return
}
// the token has expired; but we can try to renew the token
if t.accessToken.ExpiresAt.Before(time.Now()) {
// given the refresh token is still valid, try refreshing the access token.
if err := t.refreshAccessToken(); err != nil {
isValid = false
return
}
}
// finally check whether the current/refreshed access token is valid.
isValid = t.accessToken.ExpiresAt.Before(time.Now())
return
}
// GetAgreements gets identifier information of accessible Toon devices.
func (t *Toon) GetAgreements() (agreements []Agreement, err error) {
var bodyBytes []byte
bodyBytes, err = t.apiGet(apiBaseURL+"/agreements", url.Values{})
if err != nil {
return
}
err = json.Unmarshal(bodyBytes, &agreements)
return
}
// GetStatus returns current information about the thermostat status,
// and usages of electricity and gas of a Toon device identified by the
// given Agreement.
//
// The information is retrieved via the Toon API endpoint:
// https://api.toon.eu/toon/v3/{agreement.AgreementID}/status
func (t *Toon) GetStatus(agreement Agreement) (status Status, err error) {
if &(agreement.AgreementID) == nil {
err = fmt.Errorf("Invalid agreement: %+v", agreement)
return
}
var bodyBytes []byte
bodyBytes, err = t.apiGet(apiBaseURL+"/"+agreement.AgreementID+"/status", url.Values{})
if err != nil {
return
}
err = json.Unmarshal(bodyBytes, &status)
return
}
// GetGasFlow retrieves gas consumption information from a given Toon device
// for a given time period in 5-minute intervals. The Toon device is referred
// by the agreement parameter, and the time period is indicated by the from-
// and toTime parameters.
//
// The information is retrieved via the Toon API endpoint:
// https://api.toon.eu/toon/v3/{agreement.AgreementID}/consumption/gas/flows
func (t *Toon) GetGasFlow(agreement Agreement, fromTime, toTime time.Time) (flow FlowData, err error) {
if &(agreement.AgreementID) == nil {
err = fmt.Errorf("Invalid agreement: %+v", agreement)
return
}
v := url.Values{}
if (time.Time{}) != fromTime {
v.Add("fromTime", fmt.Sprintf("%d", 1000*fromTime.Unix()))
}
if (time.Time{}) != toTime {
v.Add("toTime", fmt.Sprintf("%d", 1000*toTime.Unix()))
}
var bodyBytes []byte
bodyBytes, err = t.apiGet(apiBaseURL+"/"+agreement.AgreementID+"/consumption/gas/flows", v)
if err != nil {
return
}
err = json.Unmarshal(bodyBytes, &flow)
return
}
// apiGet is a generic method for making GET request to the given API URL with optional
// query parameters.
// On success (http status code 200), it returns the response body in byte slice; othewise
// the error.
func (t *Toon) apiGet(apiURL string, query url.Values) (httpBodyBytes []byte, err error) {
if !t.hasValidToken() {
if err = t.getAccessToken(); err != nil {
return
}
}
c := newHTTPSClient()
for {
var req *http.Request
var res *http.Response
req, err = http.NewRequest("GET", apiURL, nil)
if err != nil {
return
}
// add query parameter values to the request
req.URL.RawQuery = query.Encode()
// set request header
req.Header.Set("authorization", "Bearer "+t.accessToken.AccessToken)
req.Header.Set("accept", "application/json")
req.Header.Set("cache-control", "no-cache")
req.Header.Set("content-type", "application/json")
// make request
res, err = c.Do(req)
if err != nil {
return
}
// 202 ACCEPTED
if res.StatusCode == 202 {
// request accepted but server is still processing the request.
continue
}
httpBodyBytes, err = ioutil.ReadAll(res.Body)
if err != nil {
return
}
// 200 OK
if res.StatusCode == 200 {
// the HTTP call is successful
break
}
// other code: 4xx, 5xx, etc.
err = fmt.Errorf("GET error: %s", string(httpBodyBytes))
}
return
}
// apiPostForm is a generic method for making Form POST request to the given API URL with provided
// formData.
// On success (http status code 200), it returns the response body in byte slice; othewise
// the error.
func (t *Toon) apiPostForm(apiURL string, formData url.Values) (httpBodyBytes []byte, err error) {
if !t.hasValidToken() {
if err = t.getAccessToken(); err != nil {
return
}
}
c := newHTTPSClient()
res, err := c.PostForm(apiURL, formData)
if err != nil {
return
}
httpBodyBytes, err = ioutil.ReadAll(res.Body)
if err != nil {
return
}
return
}
// internal utility functions
func newHTTPSClient() (client *http.Client) {
transport := &http.Transport{
DialContext: (&net.Dialer{
Timeout: 5 * time.Second,
}).DialContext,
TLSHandshakeTimeout: 5 * time.Second,
}
client = &http.Client{
Timeout: 10 * time.Second,
Transport: transport,
}
return
}