forked from evcc-io/evcc
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy patheasee.go
498 lines (413 loc) · 12.1 KB
/
easee.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
package charger
// LICENSE
// Copyright (c) 2019-2022 andig
// This module is NOT covered by the MIT license. All rights reserved.
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"strconv"
"sync"
"time"
"github.com/evcc-io/evcc/api"
"github.com/evcc-io/evcc/charger/easee"
"github.com/evcc-io/evcc/util"
"github.com/evcc-io/evcc/util/request"
"github.com/evcc-io/evcc/util/sponsor"
"github.com/philippseith/signalr"
"github.com/thoas/go-funk"
"golang.org/x/oauth2"
)
// Easee charger implementation
type Easee struct {
*request.Helper
charger string
site, circuit int
updated time.Time
chargeStatus api.ChargeStatus
log *util.Logger
mux *sync.Cond
dynamicChargerCurrent float64
current float64
chargerEnabled bool
enabledStatus bool
phaseMode int
currentPower, sessionEnergy,
currentL1, currentL2, currentL3 float64
}
func init() {
registry.Add("easee", NewEaseeFromConfig)
}
// NewEaseeFromConfig creates a go-e charger from generic config
func NewEaseeFromConfig(other map[string]interface{}) (api.Charger, error) {
cc := struct {
User string
Password string
Charger string
Circuit int // deprecated
Cache time.Duration // deprecated
}{}
if err := util.DecodeOther(other, &cc); err != nil {
return nil, err
}
log := util.NewLogger("easee")
if cc.Circuit > 0 {
log.WARN.Println("circuit is deprecated and will be removed in a future release")
}
if cc.Cache > 0 {
log.WARN.Println("cache is deprecated and will be removed in a future release")
}
return NewEasee(cc.User, cc.Password, cc.Charger, cc.Cache)
}
// NewEasee creates Easee charger
func NewEasee(user, password, charger string, cache time.Duration) (*Easee, error) {
log := util.NewLogger("easee").Redact(user, password)
if !sponsor.IsAuthorized() {
return nil, api.ErrSponsorRequired
}
c := &Easee{
Helper: request.NewHelper(log),
charger: charger,
log: log,
mux: sync.NewCond(new(sync.Mutex)),
current: 6, // default current
}
ts, err := easee.TokenSource(log, user, password)
if err != nil {
return c, err
}
// replace client transport with authenticated transport
c.Client.Transport = &oauth2.Transport{
Source: ts,
Base: c.Client.Transport,
}
// find charger
if charger == "" {
chargers, err := c.chargers()
if err != nil {
return c, err
}
if len(chargers) != 1 {
return c, fmt.Errorf("cannot determine charger id, found: %v", funk.Map(chargers, func(c easee.Charger) string { return c.ID }))
}
c.charger = chargers[0].ID
}
// find site
site, err := c.chargerSite(c.charger)
if err != nil {
return nil, err
}
// find single charger per circuit
for _, circuit := range site.Circuits {
if len(circuit.Chargers) > 1 {
continue
}
for _, charger := range circuit.Chargers {
if charger.ID == c.charger {
c.site = site.ID
c.circuit = circuit.ID
break
}
}
}
client, err := signalr.NewClient(context.Background(),
signalr.WithConnector(c.connect(ts)),
signalr.WithReceiver(c),
signalr.Logger(easee.SignalrLogger(c.log.TRACE), false),
)
if err == nil {
c.subscribe(client)
client.Start()
ctx, cancel := context.WithTimeout(context.Background(), request.Timeout)
defer cancel()
err = <-client.WaitForState(ctx, signalr.ClientConnected)
}
// wait for first update
done := make(chan struct{})
go c.waitForInitialUpdate(done)
select {
case <-done:
case <-time.After(request.Timeout):
err = api.ErrTimeout
}
return c, err
}
func (c *Easee) chargerSite(charger string) (easee.Site, error) {
var res easee.Site
uri := fmt.Sprintf("%s/chargers/%s/site", easee.API, charger)
err := c.GetJSON(uri, &res)
return res, err
}
// connect creates an HTTP connection to the signalR hub
func (c *Easee) connect(ts oauth2.TokenSource) func() (signalr.Connection, error) {
return func() (signalr.Connection, error) {
tok, err := ts.Token()
if err != nil {
return nil, err
}
ctx, cancel := context.WithTimeout(context.Background(), request.Timeout)
defer cancel()
return signalr.NewHTTPConnection(ctx, "https://api.easee.cloud/hubs/chargers",
signalr.WithHTTPClient(c.Client),
signalr.WithHTTPHeaders(func() (res http.Header) {
return http.Header{
"Authorization": []string{fmt.Sprintf("Bearer %s", tok.AccessToken)},
}
}),
)
}
}
// subscribe listen to state changes and sends subscription requests when connection is established
func (c *Easee) subscribe(client signalr.Client) {
stateC := make(chan signalr.ClientState, 1)
_ = client.ObserveStateChanged(stateC)
go func() {
for state := range stateC {
if state == signalr.ClientConnected {
if err := <-client.Send("SubscribeWithCurrentState", c.charger, true); err != nil {
c.log.ERROR.Printf("SubscribeWithCurrentState: %v", err)
}
}
}
}()
}
// waitForInitialUpdate waits for observe to trigger the the timestamp updated condition
func (c *Easee) waitForInitialUpdate(done chan struct{}) {
c.mux.L.Lock()
c.mux.Wait()
for c.updated.IsZero() {
c.mux.Wait()
}
c.mux.L.Unlock()
close(done)
}
// observe handles the subscription messages
func (c *Easee) observe(typ string, i json.RawMessage) {
var res easee.Observation
err := json.Unmarshal(i, &res)
if err != nil {
c.log.ERROR.Printf("invalid message: %s %s %v", i, typ, err)
return
}
var value interface{}
switch res.DataType {
case easee.Boolean:
value = res.Value == "1"
case easee.Double:
value, err = strconv.ParseFloat(res.Value, 64)
if err != nil {
c.log.ERROR.Println(err)
return
}
case easee.Integer:
value, err = strconv.Atoi(res.Value)
if err != nil {
c.log.ERROR.Println(err)
return
}
}
c.mux.L.Lock()
defer c.mux.L.Unlock()
if c.updated.IsZero() {
go func() {
<-time.After(3 * time.Second)
c.mux.Broadcast()
}()
}
c.updated = time.Now()
switch res.ID {
case easee.IS_ENABLED:
c.chargerEnabled = value.(bool)
case easee.TOTAL_POWER:
c.currentPower = 1e3 * value.(float64)
case easee.SESSION_ENERGY:
c.sessionEnergy = value.(float64)
case easee.IN_CURRENT_T3:
c.currentL1 = value.(float64)
case easee.IN_CURRENT_T4:
c.currentL2 = value.(float64)
case easee.IN_CURRENT_T5:
c.currentL3 = value.(float64)
case easee.PHASE_MODE:
c.phaseMode = value.(int)
case easee.DYNAMIC_CHARGER_CURRENT:
c.dynamicChargerCurrent = value.(float64)
// ensure that charger current matches evcc's expectation
if c.dynamicChargerCurrent > 0 && c.dynamicChargerCurrent != c.current {
if err = c.MaxCurrent(int64(c.current)); err != nil {
c.log.ERROR.Println(err)
}
}
case easee.CHARGER_OP_MODE:
switch value.(int) {
case easee.ModeDisconnected:
c.chargeStatus = api.StatusA
case easee.ModeAwaitingStart, easee.ModeCompleted, easee.ModeReadyToCharge:
c.chargeStatus = api.StatusB
case easee.ModeCharging:
c.chargeStatus = api.StatusC
case easee.ModeError:
c.chargeStatus = api.StatusF
default:
c.chargeStatus = api.StatusNone
c.log.ERROR.Printf("unknown opmode: %d", value.(int))
}
c.enabledStatus = value.(int) == easee.ModeCharging ||
value.(int) == easee.ModeAwaitingStart ||
value.(int) == easee.ModeCompleted ||
value.(int) == easee.ModeReadyToCharge
}
c.log.TRACE.Printf("%s %s: %s %.4v", typ, res.Mid, res.ID, value)
}
// ProductUpdate implements the signalr receiver
func (c *Easee) ProductUpdate(i json.RawMessage) {
c.observe("ProductUpdate", i)
}
// ChargerUpdate implements the signalr receiver
func (c *Easee) ChargerUpdate(i json.RawMessage) {
// c.observe("ChargerUpdate", i)
}
// CommandResponse implements the signalr receiver
func (c *Easee) CommandResponse(i json.RawMessage) {
// c.observe("CommandResponse", i)
}
func (c *Easee) chargers() ([]easee.Charger, error) {
var res []easee.Charger
uri := fmt.Sprintf("%s/chargers", easee.API)
err := c.GetJSON(uri, &res)
return res, err
}
// Status implements the api.Charger interface
func (c *Easee) Status() (api.ChargeStatus, error) {
c.mux.L.Lock()
defer c.mux.L.Unlock()
return c.chargeStatus, nil
}
// Enabled implements the api.Charger interface
func (c *Easee) Enabled() (bool, error) {
c.mux.L.Lock()
defer c.mux.L.Unlock()
return c.enabledStatus && c.dynamicChargerCurrent > 0, nil
}
// Enable implements the api.Charger interface
func (c *Easee) Enable(enable bool) error {
c.mux.L.Lock()
enablingRequired := enable && !c.chargerEnabled
c.mux.L.Unlock()
// enable charger once if it's switched off
if enablingRequired {
data := easee.ChargerSettings{
Enabled: &enable,
}
uri := fmt.Sprintf("%s/chargers/%s/settings", easee.API, c.charger)
resp, err := c.Post(uri, request.JSONContent, request.MarshalJSON(data))
if err != nil {
return err
}
resp.Body.Close()
}
// resume/stop charger
action := easee.ChargePause
if enable {
action = easee.ChargeResume
}
uri := fmt.Sprintf("%s/chargers/%s/commands/%s", easee.API, c.charger, action)
_, err := c.Post(uri, request.JSONContent, nil)
return err
}
// MaxCurrent implements the api.Charger interface
func (c *Easee) MaxCurrent(current int64) error {
cur := float64(current)
data := easee.ChargerSettings{
DynamicChargerCurrent: &cur,
}
uri := fmt.Sprintf("%s/chargers/%s/settings", easee.API, c.charger)
resp, err := c.Post(uri, request.JSONContent, request.MarshalJSON(data))
if err == nil {
c.current = cur
resp.Body.Close()
}
return err
}
var _ api.ChargePhases = (*Easee)(nil)
// Phases1p3p implements the api.ChargePhases interface
func (c *Easee) Phases1p3p(phases int) error {
var err error
if c.circuit != 0 {
// circuit level
uri := fmt.Sprintf("%s/sites/%d/circuits/%d/settings", easee.API, c.site, c.circuit)
var res easee.CircuitSettings
if err := c.GetJSON(uri, &res); err != nil {
return err
}
if res.MaxCircuitCurrentP1 == nil || res.MaxCircuitCurrentP2 == nil || res.MaxCircuitCurrentP3 == nil {
return errors.New("MaxCircuitCurrent must not be nil")
}
var zero float64
max1 := *res.MaxCircuitCurrentP1
max2 := *res.MaxCircuitCurrentP2
max3 := *res.MaxCircuitCurrentP3
data := easee.CircuitSettings{
DynamicCircuitCurrentP1: &max1,
DynamicCircuitCurrentP2: &zero,
DynamicCircuitCurrentP3: &zero,
}
if phases > 1 {
data.DynamicCircuitCurrentP2 = &max2
data.DynamicCircuitCurrentP3 = &max3
}
var resp *http.Response
if resp, err = c.Post(uri, request.JSONContent, request.MarshalJSON(data)); err == nil {
resp.Body.Close()
}
} else {
// charger level
if phases == 3 {
phases = 2 // mode 2 means 3p
}
// change phaseMode only if necessary
if phases != c.phaseMode {
data := easee.ChargerSettings{
PhaseMode: &phases,
}
uri := fmt.Sprintf("%s/chargers/%s/settings", easee.API, c.charger)
var resp *http.Response
if resp, err = c.Post(uri, request.JSONContent, request.MarshalJSON(data)); err == nil {
resp.Body.Close()
}
}
}
return err
}
var _ api.Meter = (*Easee)(nil)
// CurrentPower implements the api.Meter interface
func (c *Easee) CurrentPower() (float64, error) {
c.mux.L.Lock()
defer c.mux.L.Unlock()
return c.currentPower, nil
}
var _ api.ChargeRater = (*Easee)(nil)
// ChargedEnergy implements the api.ChargeRater interface
func (c *Easee) ChargedEnergy() (float64, error) {
c.mux.L.Lock()
defer c.mux.L.Unlock()
return c.sessionEnergy, nil
}
var _ api.MeterCurrent = (*Easee)(nil)
// Currents implements the api.MeterCurrent interface
func (c *Easee) Currents() (float64, float64, float64, error) {
c.mux.L.Lock()
defer c.mux.L.Unlock()
return c.currentL1, c.currentL2, c.currentL3, nil
}