forked from evcc-io/evcc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloadpoint.go
1754 lines (1448 loc) Β· 52.5 KB
/
loadpoint.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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package core
import (
"errors"
"fmt"
"math"
"reflect"
"strings"
"sync"
"testing"
"time"
evbus "github.com/asaskevich/EventBus"
"github.com/benbjohnson/clock"
"github.com/cenkalti/backoff/v4"
"github.com/evcc-io/evcc/api"
"github.com/evcc-io/evcc/core/coordinator"
"github.com/evcc-io/evcc/core/keys"
"github.com/evcc-io/evcc/core/loadpoint"
"github.com/evcc-io/evcc/core/planner"
"github.com/evcc-io/evcc/core/session"
"github.com/evcc-io/evcc/core/soc"
"github.com/evcc-io/evcc/core/vehicle"
"github.com/evcc-io/evcc/core/wrapper"
"github.com/evcc-io/evcc/provider"
"github.com/evcc-io/evcc/push"
"github.com/evcc-io/evcc/util"
"github.com/evcc-io/evcc/util/config"
"github.com/evcc-io/evcc/util/telemetry"
)
const (
evChargeStart = "start" // update chargeTimer
evChargeStop = "stop" // update chargeTimer
evChargeCurrent = "current" // update fakeChargeMeter
evChargePower = "power" // update chargeRater
evVehicleConnect = "connect" // vehicle connected
evVehicleDisconnect = "disconnect" // vehicle disconnected
evVehicleSoc = "soc" // vehicle soc progress
evVehicleUnidentified = "guest" // vehicle unidentified
pvTimer = "pv"
pvEnable = "enable"
pvDisable = "disable"
phaseTimer = "phase"
phaseScale1p = "scale1p"
phaseScale3p = "scale3p"
timerInactive = "inactive"
minActiveCurrent = 1.0 // minimum current at which a phase is treated as active
minActiveVoltage = 207 // minimum voltage at which a phase is treated as active
chargerSwitchDuration = 60 * time.Second // allow out of sync during this timespan
phaseSwitchDuration = 60 * time.Second // allow out of sync and do not measure phases during this timespan
)
// elapsed is the time an expired timer will be set to
var elapsed = time.Unix(0, 1)
// PollConfig defines the vehicle polling mode and interval
type PollConfig struct {
Mode string `mapstructure:"mode"` // polling mode charging (default), connected, always
Interval time.Duration `mapstructure:"interval"` // interval when not charging
}
// SocConfig defines soc settings, estimation and update behavior
type SocConfig struct {
Poll PollConfig `mapstructure:"poll"`
Estimate *bool `mapstructure:"estimate"`
}
// Poll modes
const (
pollCharging = "charging"
pollConnected = "connected"
pollAlways = "always"
pollInterval = 60 * time.Minute
)
// ThresholdConfig defines enable/disable hysteresis parameters
type ThresholdConfig struct {
Delay time.Duration
Threshold float64
}
// Task is the task type
type Task = func()
// Loadpoint is responsible for controlling charge depending on
// Soc needs and power availability.
type Loadpoint struct {
clock clock.Clock // mockable time
bus evbus.Bus // event bus
pushChan chan<- push.Event // notifications
uiChan chan<- util.Param // client push messages
lpChan chan<- *Loadpoint // update requests
log *util.Logger
// exposed public configuration
sync.RWMutex // guard status
vmu sync.RWMutex // guard vehicle
Mode_ api.ChargeMode `mapstructure:"mode"` // Default charge mode, used for disconnect
Title_ string `mapstructure:"title"` // UI title
Priority_ int `mapstructure:"priority"` // Priority
CircuitRef string `mapstructure:"circuit"` // Circuit reference
ChargerRef string `mapstructure:"charger"` // Charger reference
VehicleRef string `mapstructure:"vehicle"` // Vehicle reference
MeterRef string `mapstructure:"meter"` // Charge meter reference
Soc SocConfig
Enable, Disable ThresholdConfig
// TODO deprecated
GuardDuration_ time.Duration `mapstructure:"guardduration"` // charger enable/disable minimum holding time
ConfiguredPhases_ int `mapstructure:"phases"`
MinCurrent_ float64 `mapstructure:"minCurrent"`
MaxCurrent_ float64 `mapstructure:"maxCurrent"`
minCurrent float64 // PV mode: start current Min+PV mode: min current
maxCurrent float64 // Max allowed current. Physically ensured by the charger
configuredPhases int // Charger configured phase mode 0/1/3
limitSoc int // Session limit for soc
limitEnergy float64 // Session limit for energy
smartCostLimit float64 // always charge if cost is below this value
mode api.ChargeMode
enabled bool // Charger enabled state
phases int // Charger enabled phases, guarded by mutex
measuredPhases int // Charger physically measured phases
chargeCurrent float64 // Charger current limit
socUpdated time.Time // Soc updated timestamp (poll: connected)
vehicleDetect time.Time // Vehicle connected timestamp
chargerSwitched time.Time // Charger enabled/disabled timestamp
phasesSwitched time.Time // Phase switch timestamp
vehicleDetectTicker *clock.Ticker
vehicleIdentifier string
charger api.Charger
chargeTimer api.ChargeTimer
chargeRater api.ChargeRater
chargedAtStartup float64 // session energy at startup
circuit api.Circuit // Circuit
chargeMeter api.Meter // Charger usage meter
vehicle api.Vehicle // Currently active vehicle
defaultVehicle api.Vehicle // Default vehicle (disables detection)
coordinator coordinator.API
socEstimator *soc.Estimator
// charge planning
planner *planner.Planner
planTime time.Time // time goal
planEnergy float64 // Plan charge energy in kWh (dumb vehicles)
planSlotEnd time.Time // current plan slot end time
planActive bool // charge plan exists and has a currently active slot
// cached state
status api.ChargeStatus // Charger status
remoteDemand loadpoint.RemoteDemand // External status demand
chargePower float64 // Charging power
chargeCurrents []float64 // Phase currents
connectedTime time.Time // Time when vehicle was connected
pvTimer time.Time // PV enabled/disable timer
phaseTimer time.Time // 1p3p switch timer
wakeUpTimer *Timer // Vehicle wake-up timeout
// charge progress
vehicleSoc float64 // Vehicle Soc
chargeDuration time.Duration // Charge duration
sessionEnergy *EnergyMetrics // Stats for charged energy by session
chargeRemainingDuration time.Duration // Remaining charge duration
chargeRemainingEnergy float64 // Remaining charge energy in Wh
progress *Progress // Step-wise progress indicator
// session log
db *session.DB
session *session.Session
settings *Settings
tasks *util.Queue[Task] // tasks to be executed
}
// NewLoadpointFromConfig creates a new loadpoint
func NewLoadpointFromConfig(log *util.Logger, settings *Settings, other map[string]interface{}) (*Loadpoint, error) {
lp := NewLoadpoint(log, settings)
if err := util.DecodeOther(other, lp); err != nil {
return nil, err
}
// set vehicle polling mode
switch lp.Soc.Poll.Mode = strings.ToLower(lp.Soc.Poll.Mode); lp.Soc.Poll.Mode {
case pollCharging:
case pollConnected, pollAlways:
lp.log.WARN.Printf("poll mode '%s' may deplete your battery or lead to API misuse. USE AT YOUR OWN RISK.", lp.Soc.Poll)
default:
if lp.Soc.Poll.Mode != "" {
lp.log.WARN.Printf("invalid poll mode: %s", lp.Soc.Poll.Mode)
}
lp.Soc.Poll.Mode = pollCharging
}
if lp.CircuitRef != "" {
dev, err := config.Circuits().ByName(lp.CircuitRef)
if err != nil {
return nil, err
}
lp.circuit = dev.Instance()
}
if lp.MeterRef != "" {
dev, err := config.Meters().ByName(lp.MeterRef)
if err != nil {
return nil, err
}
lp.chargeMeter = dev.Instance()
}
// default vehicle
if lp.VehicleRef != "" {
dev, err := config.Vehicles().ByName(lp.VehicleRef)
if err != nil {
return nil, err
}
lp.defaultVehicle = dev.Instance()
}
if lp.ChargerRef == "" {
return nil, errors.New("missing charger")
}
dev, err := config.Chargers().ByName(lp.ChargerRef)
if err != nil {
return nil, err
}
lp.charger = dev.Instance()
lp.configureChargerType(lp.charger)
// phase switching defaults based on charger capabilities
if !lp.hasPhaseSwitching() {
lp.configuredPhases = 3
lp.phases = 3
}
// TODO deprecated
if lp.MinCurrent_ > 0 {
lp.log.WARN.Println("deprecated: mincurrent setting is ignored, please remove")
if _, err := lp.settings.Float(keys.MinCurrent); err != nil {
lp.settings.SetFloat(keys.MinCurrent, lp.MinCurrent_)
}
}
if lp.MaxCurrent_ > 0 {
lp.log.WARN.Println("deprecated: maxcurrent setting is ignored, please remove")
if _, err := lp.settings.Float(keys.MaxCurrent); err != nil {
lp.settings.SetFloat(keys.MaxCurrent, lp.MaxCurrent_)
}
}
if lp.ConfiguredPhases_ > 0 {
lp.log.WARN.Println("deprecated: phases setting is ignored, please remove")
if _, err := lp.settings.Int(keys.PhasesConfigured); err != nil {
lp.settings.SetInt(keys.PhasesConfigured, int64(lp.ConfiguredPhases_))
}
}
// validate thresholds
if lp.Enable.Threshold > lp.Disable.Threshold {
lp.log.WARN.Printf("PV mode enable threshold (%.0fW) is larger than disable threshold (%.0fW)", lp.Enable.Threshold, lp.Disable.Threshold)
} else if lp.Enable.Threshold > 0 {
lp.log.WARN.Printf("PV mode enable threshold %.0fW > 0 will start PV charging on grid power consumption. Did you mean -%.0f?", lp.Enable.Threshold, lp.Enable.Threshold)
}
// choose sane default if mode is not set
if lp.mode = lp.Mode_; lp.mode == "" {
lp.mode = api.ModeOff
}
return lp, nil
}
// NewLoadpoint creates a Loadpoint with sane defaults
func NewLoadpoint(log *util.Logger, settings *Settings) *Loadpoint {
clock := clock.New()
bus := evbus.New()
lp := &Loadpoint{
log: log, // logger
settings: settings, // settings
clock: clock, // mockable time
bus: bus, // event bus
mode: api.ModeOff,
status: api.StatusNone,
minCurrent: 6, // A
maxCurrent: 16, // A
Soc: SocConfig{
Poll: PollConfig{
Interval: pollInterval,
Mode: pollCharging,
},
},
Enable: ThresholdConfig{Delay: time.Minute, Threshold: 0}, // t, W
Disable: ThresholdConfig{Delay: 3 * time.Minute, Threshold: 0}, // t, W
sessionEnergy: NewEnergyMetrics(),
progress: NewProgress(0, 10), // soc progress indicator
coordinator: coordinator.NewDummy(), // dummy vehicle coordinator
tasks: util.NewQueue[Task](), // task queue
}
return lp
}
// restoreSettings restores loadpoint settings
func (lp *Loadpoint) restoreSettings() {
if testing.Testing() {
return
}
if v, err := lp.settings.String(keys.Mode); err == nil && v != "" {
lp.setMode(api.ChargeMode(v))
}
if v, err := lp.settings.Int(keys.PhasesConfigured); err == nil && (v > 0 || lp.hasPhaseSwitching()) {
lp.setConfiguredPhases(int(v))
lp.phases = lp.configuredPhases
}
if v, err := lp.settings.Float(keys.MinCurrent); err == nil && v > 0 {
lp.setMinCurrent(v)
}
if v, err := lp.settings.Float(keys.MaxCurrent); err == nil && v > 0 {
lp.setMaxCurrent(v)
}
if v, err := lp.settings.Int(keys.LimitSoc); err == nil && v > 0 {
lp.setLimitSoc(int(v))
}
if v, err := lp.settings.Float(keys.LimitEnergy); err == nil && v > 0 {
lp.setLimitEnergy(v)
}
if v, err := lp.settings.Float(keys.SmartCostLimit); err == nil {
lp.SetSmartCostLimit(v)
}
t, err1 := lp.settings.Time(keys.PlanTime)
v, err2 := lp.settings.Float(keys.PlanEnergy)
if err1 == nil && err2 == nil {
lp.setPlanEnergy(t, v)
}
}
// requestUpdate requests site to update this loadpoint
func (lp *Loadpoint) requestUpdate() {
select {
case lp.lpChan <- lp: // request loadpoint update
default:
}
}
// configureChargerType ensures that chargeMeter, Rate and Timer can use charger capabilities
func (lp *Loadpoint) configureChargerType(charger api.Charger) {
var integrated bool
// ensure charge meter exists
if lp.chargeMeter == nil {
integrated = true
if mt, ok := charger.(api.Meter); ok {
lp.chargeMeter = mt
} else {
mt := new(wrapper.ChargeMeter)
_ = lp.bus.Subscribe(evChargeCurrent, lp.evChargeCurrentWrappedMeterHandler)
_ = lp.bus.Subscribe(evChargeStop, func() { mt.SetPower(0) })
lp.chargeMeter = mt
}
}
// ensure charge rater exists
// measurement are obtained from separate charge meter if defined
// (https://github.com/evcc-io/evcc/issues/2469)
if rt, ok := charger.(api.ChargeRater); ok && integrated {
lp.chargeRater = rt
// when restarting in the middle of charging session, use this as negative offset
if f, err := rt.ChargedEnergy(); err == nil {
lp.chargedAtStartup = f
}
} else {
rt := wrapper.NewChargeRater(lp.log, lp.chargeMeter)
_ = lp.bus.Subscribe(evChargePower, rt.SetChargePower)
_ = lp.bus.Subscribe(evVehicleConnect, func() { rt.StartCharge(false) })
_ = lp.bus.Subscribe(evChargeStart, func() { rt.StartCharge(true) })
_ = lp.bus.Subscribe(evChargeStop, rt.StopCharge)
lp.chargeRater = rt
}
// ensure charge timer exists
if ct, ok := charger.(api.ChargeTimer); ok {
lp.chargeTimer = ct
} else {
ct := wrapper.NewChargeTimer()
_ = lp.bus.Subscribe(evVehicleConnect, func() { ct.StartCharge(false) })
_ = lp.bus.Subscribe(evChargeStart, func() { ct.StartCharge(true) })
_ = lp.bus.Subscribe(evChargeStop, ct.StopCharge)
lp.chargeTimer = ct
}
// add wakeup timer
lp.wakeUpTimer = NewTimer()
}
// pushEvent sends push messages to clients
func (lp *Loadpoint) pushEvent(event string) {
lp.pushChan <- push.Event{Event: event}
}
// publish sends values to UI and databases
func (lp *Loadpoint) publish(key string, val interface{}) {
// test helper
if lp.uiChan == nil {
return
}
lp.uiChan <- util.Param{Key: key, Val: val}
}
// evChargeStartHandler sends external start event
func (lp *Loadpoint) evChargeStartHandler() {
lp.log.INFO.Println("start charging ->")
lp.pushEvent(evChargeStart)
lp.stopWakeUpTimer()
// soc update reset
lp.socUpdated = time.Time{}
// set created when first charging session segment starts
lp.updateSession(func(session *session.Session) {
if session.Created.IsZero() {
session.Created = lp.clock.Now()
}
})
}
// evChargeStopHandler sends external stop event
func (lp *Loadpoint) evChargeStopHandler() {
lp.log.INFO.Println("stop charging <-")
lp.pushEvent(evChargeStop)
if lp.enabled {
lp.startWakeUpTimer()
}
// soc update reset
provider.ResetCached()
lp.socUpdated = time.Time{}
// reset pv enable/disable timer
// https://github.com/evcc-io/evcc/issues/2289
if !lp.pvTimer.Equal(elapsed) {
lp.resetPVTimer()
}
lp.stopSession()
}
// evVehicleConnectHandler sends external start event
func (lp *Loadpoint) evVehicleConnectHandler() {
lp.log.INFO.Printf("car connected")
// energy
lp.sessionEnergy.Reset()
lp.sessionEnergy.Publish("session", lp)
lp.publish(keys.ChargedEnergy, lp.getChargedEnergy())
// duration
lp.connectedTime = lp.clock.Now()
lp.publish(keys.ConnectedDuration, time.Duration(0))
// soc update reset
lp.socUpdated = time.Time{}
// soc update reset on car change
if lp.socEstimator != nil {
lp.socEstimator.Reset()
}
// set default or start detection
if !lp.chargerHasFeature(api.IntegratedDevice) {
lp.vehicleDefaultOrDetect()
}
// immediately allow pv mode activity
lp.elapsePVTimer()
// create charging session
lp.createSession()
}
// evVehicleDisconnectHandler sends external start event
func (lp *Loadpoint) evVehicleDisconnectHandler() {
lp.log.INFO.Println("car disconnected")
// session is persisted during evChargeStopHandler which runs before
lp.clearSession()
// phases are unknown when vehicle disconnects
lp.resetMeasuredPhases()
// energy and duration
lp.sessionEnergy.Publish("session", lp)
lp.publish(keys.ChargedEnergy, lp.getChargedEnergy())
lp.publish(keys.ConnectedDuration, lp.clock.Since(lp.connectedTime).Round(time.Second))
// forget startup energy offset
lp.chargedAtStartup = 0
// remove charger vehicle id and stop potential detection
lp.setVehicleIdentifier("")
lp.stopVehicleDetection()
// set default mode on disconnect
lp.defaultMode()
// set default vehicle (may be nil)
lp.setActiveVehicle(lp.defaultVehicle)
// soc update reset
lp.socUpdated = time.Time{}
// reset session
lp.SetLimitSoc(0)
lp.SetLimitEnergy(0)
// mark plan slot as inactive
// this will force a deletion of an outdated plan once plan time is expired in GetPlan()
lp.setPlanActive(false)
}
// evVehicleSocProgressHandler sends external start event
func (lp *Loadpoint) evVehicleSocProgressHandler(soc float64) {
if lp.progress.NextStep(soc) {
lp.pushEvent(evVehicleSoc)
}
}
// evChargeCurrentHandler publishes the charge current
func (lp *Loadpoint) evChargeCurrentHandler(current float64) {
if !lp.enabled {
current = 0
}
lp.publish(keys.ChargeCurrent, current)
}
// evChargeCurrentWrappedMeterHandler updates the dummy charge meter's charge power.
// This simplifies the main flow where the charge meter can always be treated as present.
// It assumes that the charge meter cannot consume more than total household consumption.
// If physical charge meter is present this handler is not used.
// The actual value is published by the evChargeCurrentHandler
func (lp *Loadpoint) evChargeCurrentWrappedMeterHandler(current float64) {
power := current * float64(lp.ActivePhases()) * Voltage
// if disabled we cannot be charging
if !lp.enabled || !lp.charging() {
power = 0
}
// handler only called if charge meter was replaced by dummy
lp.chargeMeter.(*wrapper.ChargeMeter).SetPower(power)
}
// defaultMode executes the action
func (lp *Loadpoint) defaultMode() {
lp.RLock()
mode := lp.Mode_
lp.RUnlock()
if mode != "" && mode != lp.GetMode() {
lp.SetMode(mode)
}
}
// Prepare loadpoint configuration by adding missing helper elements
func (lp *Loadpoint) Prepare(uiChan chan<- util.Param, pushChan chan<- push.Event, lpChan chan<- *Loadpoint) {
lp.uiChan = uiChan
lp.pushChan = pushChan
lp.lpChan = lpChan
// event handlers
_ = lp.bus.Subscribe(evChargeStart, lp.evChargeStartHandler)
_ = lp.bus.Subscribe(evChargeStop, lp.evChargeStopHandler)
_ = lp.bus.Subscribe(evVehicleConnect, lp.evVehicleConnectHandler)
_ = lp.bus.Subscribe(evVehicleDisconnect, lp.evVehicleDisconnectHandler)
_ = lp.bus.Subscribe(evChargeCurrent, lp.evChargeCurrentHandler)
_ = lp.bus.Subscribe(evVehicleSoc, lp.evVehicleSocProgressHandler)
// restore settings
lp.restoreSettings()
// publish initial values
lp.publish(keys.Title, lp.Title())
lp.publish(keys.Mode, lp.GetMode())
lp.publish(keys.Priority, lp.GetPriority())
lp.publish(keys.MinCurrent, lp.GetMinCurrent())
lp.publish(keys.MaxCurrent, lp.GetMaxCurrent())
lp.publish(keys.EnableThreshold, lp.Enable.Threshold)
lp.publish(keys.DisableThreshold, lp.Disable.Threshold)
lp.publish(keys.PhasesConfigured, lp.configuredPhases)
lp.publish(keys.ChargerPhases1p3p, lp.hasPhaseSwitching())
lp.publish(keys.PhasesEnabled, lp.phases)
lp.publish(keys.PhasesActive, lp.ActivePhases())
lp.publishTimer(phaseTimer, 0, timerInactive)
lp.publishTimer(pvTimer, 0, timerInactive)
if phases := lp.getChargerPhysicalPhases(); phases != 0 {
lp.publish(keys.ChargerPhysicalPhases, phases)
} else {
lp.publish(keys.ChargerPhysicalPhases, nil)
}
// charger features
for _, f := range []api.Feature{api.IntegratedDevice, api.Heating} {
lp.publishChargerFeature(f)
}
// charger icon
if c, ok := lp.charger.(api.IconDescriber); ok {
lp.publish(keys.ChargerIcon, c.Icon())
} else {
lp.publish(keys.ChargerIcon, nil)
}
// vehicle
lp.publish(keys.VehicleName, "")
lp.publish(keys.VehicleOdometer, 0.0)
// assign and publish default vehicle
if lp.defaultVehicle != nil {
lp.setActiveVehicle(lp.defaultVehicle)
}
// reset detection state
lp.publish(keys.VehicleDetectionActive, false)
// restored settings
lp.publish(keys.PlanTime, lp.planTime)
lp.publish(keys.PlanEnergy, lp.planEnergy)
lp.publish(keys.LimitSoc, lp.limitSoc)
lp.publish(keys.LimitEnergy, lp.limitEnergy)
// read initial charger state to prevent immediately disabling charger
if enabled, err := lp.charger.Enabled(); err == nil {
if lp.enabled = enabled; enabled {
// set defined current for use by pv mode
_ = lp.setLimit(lp.effectiveMinCurrent())
}
} else {
lp.log.ERROR.Printf("charger enabled: %v", err)
}
// allow charger to access loadpoint
if ctrl, ok := lp.charger.(loadpoint.Controller); ok {
ctrl.LoadpointControl(lp)
}
}
func (lp *Loadpoint) setAndPublishEnabled(enabled bool) {
if enabled != lp.enabled {
lp.log.DEBUG.Printf("charger %s", status[enabled])
lp.enabled = enabled
}
lp.publish(keys.Enabled, enabled)
}
// syncCharger updates charger status and synchronizes it with expectations
func (lp *Loadpoint) syncCharger() error {
enabled, err := lp.charger.Enabled()
if err != nil {
return fmt.Errorf("charger enabled: %w", err)
}
shouldBeConsistent := lp.shouldBeConsistent()
if shouldBeConsistent {
defer func() {
lp.setAndPublishEnabled(enabled)
}()
}
// #1: check charger logic, fix charger state if necessary (for chargers that start charging while being disabled)
if !enabled && lp.charging() {
lp.log.WARN.Println("charger logic error: disabled but charging")
// treat as enabled when charging for further validations
enabled = true
if shouldBeConsistent {
if err := lp.charger.Enable(true); err != nil { // also enable charger to correct internal state
return fmt.Errorf("charger enable: %w", err)
}
lp.elapsePVTimer() // elapse PV timer so loadpoint can immediately switch charger if necessary
return nil
}
}
// #2: sync charger
switch {
case enabled && lp.enabled:
// sync max current
var (
current float64
err error
)
// use chargers actual set current if available
cg, isCg := lp.charger.(api.CurrentGetter)
if isCg {
if current, err = cg.GetMaxCurrent(); err == nil {
// smallest adjustment most PWM-Controllers can do is: 100%Γ·256Γ0,6A = 0.234A
if math.Abs(lp.chargeCurrent-current) > 0.23 {
if shouldBeConsistent {
lp.log.WARN.Printf("charger logic error: current mismatch (got %.3gA, expected %.3gA)", current, lp.chargeCurrent)
}
lp.chargeCurrent = current
lp.bus.Publish(evChargeCurrent, lp.chargeCurrent)
}
} else if !errors.Is(err, api.ErrNotAvailable) {
return fmt.Errorf("charger get max current: %w", err)
}
}
// use measured phase currents as fallback if charger does not provide max current or does not currently relay from vehicle (TWC3)
if !isCg || errors.Is(err, api.ErrNotAvailable) {
// validate if current too high by more than 1A (https://github.com/evcc-io/evcc/issues/14731)
if current := lp.GetMaxPhaseCurrent(); current > lp.chargeCurrent+1.0 {
if shouldBeConsistent {
lp.log.WARN.Printf("charger logic error: current mismatch (got %.3gA measured, expected %.3gA)", current, lp.chargeCurrent)
}
lp.chargeCurrent = current
lp.bus.Publish(evChargeCurrent, lp.chargeCurrent)
}
}
// sync phases
_, isPs := lp.charger.(api.PhaseSwitcher)
if phases := lp.GetPhases(); isPs && shouldBeConsistent && phases > 0 {
// fallback to active phases from measured phases
chargerPhases := lp.measuredPhases
if chargerPhases == 2 {
chargerPhases = 3
}
pg, isPg := lp.charger.(api.PhaseGetter)
if isPg {
if chargerPhases, err = pg.GetPhases(); err == nil {
if chargerPhases > 0 && chargerPhases != phases {
lp.log.WARN.Printf("charger logic error: phases mismatch (got %d, expected %d)", chargerPhases, phases)
lp.setPhases(chargerPhases)
}
} else {
if errors.Is(err, api.ErrNotAvailable) {
return nil
}
return fmt.Errorf("charger get phases: %w", err)
}
}
// use measured phase currents for active phases as fallback if charger does not provide phases
if !isPg || errors.Is(err, api.ErrNotAvailable) {
if chargerPhases > phases {
lp.log.WARN.Printf("charger logic error: phases mismatch (got %d measured, expected %d)", chargerPhases, phases)
lp.setPhases(chargerPhases)
}
}
}
case enabled == lp.enabled:
// sync disabled state
case !enabled && !lp.phaseSwitchCompleted():
// some chargers (i.E. Easee in some configurations) disable themselves to be able to switch phases
// -> enable charger
if err := lp.charger.Enable(true); err != nil {
return fmt.Errorf("charger enable: %w", err)
}
case shouldBeConsistent && (enabled || lp.connected()):
// ignore disabled state if vehicle was disconnected (!lp.enabled && !lp.connected)
lp.log.WARN.Printf("charger out of sync: expected %vd, got %vd", status[lp.enabled], status[enabled])
}
return nil
}
// roundedCurrent rounds current down to full amps if charger or vehicle require it
func (lp *Loadpoint) roundedCurrent(chargeCurrent float64) float64 {
// full amps only?
if _, ok := lp.charger.(api.ChargerEx); !ok || lp.vehicleHasFeature(api.CoarseCurrent) {
chargeCurrent = math.Trunc(chargeCurrent)
}
return chargeCurrent
}
// setLimit applies charger current limits and enables/disables accordingly
func (lp *Loadpoint) setLimit(chargeCurrent float64) error {
chargeCurrent = lp.roundedCurrent(chargeCurrent)
// apply circuit limits
if lp.circuit != nil {
currentLimit := lp.circuit.ValidateCurrent(lp.chargeCurrent, chargeCurrent)
activePhases := lp.ActivePhases()
powerLimit := lp.circuit.ValidatePower(lp.chargePower, currentToPower(chargeCurrent, activePhases))
currentLimitViaPower := powerToCurrent(powerLimit, activePhases)
chargeCurrent = lp.roundedCurrent(min(currentLimit, currentLimitViaPower))
}
// set current
if chargeCurrent != lp.chargeCurrent && chargeCurrent >= lp.effectiveMinCurrent() {
var err error
if charger, ok := lp.charger.(api.ChargerEx); ok {
err = charger.MaxCurrentMillis(chargeCurrent)
} else {
err = lp.charger.MaxCurrent(int64(chargeCurrent))
}
if err != nil {
v := lp.GetVehicle()
if vv, ok := v.(api.Resurrector); ok && errors.Is(err, api.ErrAsleep) {
// https://github.com/evcc-io/evcc/issues/8254
// wakeup vehicle
lp.log.DEBUG.Printf("max charge current: waking up vehicle")
if err := vv.WakeUp(); err != nil {
return fmt.Errorf("wake-up vehicle: %w", err)
}
}
return fmt.Errorf("max charge current %.3gA: %w", chargeCurrent, err)
}
lp.log.DEBUG.Printf("max charge current: %.3gA", chargeCurrent)
lp.chargeCurrent = chargeCurrent
lp.bus.Publish(evChargeCurrent, chargeCurrent)
}
// set enabled/disabled
if enabled := chargeCurrent >= lp.effectiveMinCurrent(); enabled != lp.enabled {
if err := lp.charger.Enable(enabled); err != nil {
v := lp.GetVehicle()
if vv, ok := v.(api.Resurrector); enabled && ok && errors.Is(err, api.ErrAsleep) {
// https://github.com/evcc-io/evcc/issues/8254
// wakeup vehicle
lp.log.DEBUG.Printf("charger %s: waking up vehicle", status[enabled])
if err := vv.WakeUp(); err != nil {
return fmt.Errorf("wake-up vehicle: %w", err)
}
}
return fmt.Errorf("charger %s: %w", status[enabled], err)
}
lp.setAndPublishEnabled(enabled)
lp.chargerSwitched = lp.clock.Now()
lp.bus.Publish(evChargeCurrent, chargeCurrent)
// start/stop vehicle wake-up timer
if enabled {
lp.startWakeUpTimer()
} else {
lp.stopWakeUpTimer()
}
}
return nil
}
// connected returns the EVs connection state
func (lp *Loadpoint) connected() bool {
status := lp.GetStatus()
return status == api.StatusB || status == api.StatusC
}
// charging returns the EVs charging state
func (lp *Loadpoint) charging() bool {
return lp.GetStatus() == api.StatusC
}
// charging returns the EVs charging state
func (lp *Loadpoint) setStatus(status api.ChargeStatus) {
lp.Lock()
defer lp.Unlock()
lp.status = status
}
// socBasedPlanning returns true if vehicle soc (optionally from charger) and capacity are available
func (lp *Loadpoint) socBasedPlanning() bool {
v := lp.GetVehicle()
return (v != nil && v.Capacity() > 0) && (lp.vehicleHasSoc() || lp.vehicleSoc > 0)
}
// vehicleHasSoc returns true if active vehicle supports returning soc, i.e. it is not an offline vehicle
func (lp *Loadpoint) vehicleHasSoc() bool {
return lp.GetVehicle() != nil && !lp.vehicleHasFeature(api.Offline)
}
// remainingLimitEnergy returns missing energy amount in kWh if vehicle has a valid energy target
func (lp *Loadpoint) remainingLimitEnergy() (float64, bool) {
limit := lp.GetLimitEnergy()
return max(0, limit-lp.getChargedEnergy()/1e3),
limit > 0 && !lp.socBasedPlanning()
}
// limitEnergyReached checks if target is configured and reached
func (lp *Loadpoint) limitEnergyReached() bool {
f, ok := lp.remainingLimitEnergy()
return ok && f <= 0
}
// limitSocReached returns true if the effective limit has been reached
func (lp *Loadpoint) limitSocReached() bool {
limit := lp.effectiveLimitSoc()
return limit > 0 && limit < 100 && lp.vehicleSoc >= float64(limit)
}
// minSocNotReached checks if minimum is configured and not reached.
// If vehicle is not configured this will always return false
func (lp *Loadpoint) minSocNotReached() bool {
v := lp.GetVehicle()
if v == nil {
return false
}
minSoc := vehicle.Settings(lp.log, v).GetMinSoc()
if minSoc == 0 {
return false
}
if lp.vehicleSoc != 0 {
active := lp.vehicleSoc < float64(minSoc)
if active {
lp.log.DEBUG.Printf("forced charging at vehicle soc %.0f%% (< %.0f%% min soc)", lp.vehicleSoc, float64(minSoc))
}
return active
}
minEnergy := v.Capacity() * float64(minSoc) / 100 / soc.ChargeEfficiency
return minEnergy > 0 && lp.getChargedEnergy() < minEnergy
}
// disableUnlessClimater disables the charger unless climate is active
func (lp *Loadpoint) disableUnlessClimater() error {
var current float64 // zero disables
if lp.vehicleClimateActive() {
current = lp.effectiveMinCurrent()
}
return lp.setLimit(current)
}
// remoteControlled returns true if remote control status is active
func (lp *Loadpoint) remoteControlled(demand loadpoint.RemoteDemand) bool {
lp.Lock()
defer lp.Unlock()
return lp.remoteDemand == demand
}
// statusEvents converts the observed charger status change into a logical sequence of events
func statusEvents(prevStatus, status api.ChargeStatus) []string {
res := make([]string, 0, 2)
// changed from A - connected
if prevStatus == api.StatusA || (status != api.StatusA && prevStatus == api.StatusNone) {
res = append(res, evVehicleConnect)
}
// changed to C - start charging
if status == api.StatusC {
res = append(res, evChargeStart)
}
// changed from C - stop charging
if prevStatus == api.StatusC {
res = append(res, evChargeStop)
}
// changed to A - disconnected
if status == api.StatusA {
res = append(res, evVehicleDisconnect)
}
return res
}
// updateChargerStatus updates charger status and detects car connected/disconnected events
func (lp *Loadpoint) updateChargerStatus() error {
status, err := lp.charger.Status()
if err != nil {
return fmt.Errorf("charger status: %w", err)
}