forked from evcc-io/evcc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloadpoint.go
1536 lines (1258 loc) Β· 43.8 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"
"regexp"
"strings"
"sync"
"time"
"github.com/evcc-io/evcc/api"
"github.com/evcc-io/evcc/core/loadpoint"
"github.com/evcc-io/evcc/core/soc"
"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"
"golang.org/x/exp/slices"
evbus "github.com/asaskevich/EventBus"
"github.com/avast/retry-go/v3"
"github.com/benbjohnson/clock"
"github.com/cjrd/allocate"
)
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
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
vehicleDetectInterval = 3 * time.Minute
vehicleDetectDuration = 10 * time.Minute
guardGracePeriod = 10 * time.Second // allow out of sync 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 behaviour
type SoCConfig struct {
Poll PollConfig `mapstructure:"poll"`
Estimate bool `mapstructure:"estimate"`
Min int `mapstructure:"min"` // Default minimum SoC, guarded by mutex
Target int `mapstructure:"target"` // Default target SoC, guarded by mutex
}
// 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
}
// 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.Mutex // guard status
Mode api.ChargeMode `mapstructure:"mode"` // Charge mode, guarded by mutex
Title string `mapstructure:"title"` // UI title
Phases int `mapstructure:"phases"` // Charger enabled phases
ChargerRef string `mapstructure:"charger"` // Charger reference
VehicleRef string `mapstructure:"vehicle"` // Vehicle reference
VehiclesRef []string `mapstructure:"vehicles"` // Vehicles reference
MeterRef string `mapstructure:"meter"` // Charge meter reference
SoC SoCConfig
Enable, Disable ThresholdConfig
ResetOnDisconnect bool `mapstructure:"resetOnDisconnect"`
onDisconnect api.ActionConfig
MinCurrent float64 // PV mode: start current Min+PV mode: min current
MaxCurrent float64 // Max allowed current. Physically ensured by the charger
GuardDuration time.Duration // charger enable/disable minimum holding time
enabled bool // Charger enabled state
measuredPhases int // Charger physically measured phases
chargeCurrent float64 // Charger current limit
guardUpdated time.Time // Charger enabled/disabled timestamp
socUpdated time.Time // SoC updated timestamp (poll: connected)
vehicleConnected time.Time // Vehicle connected timestamp
vehicleConnectedTicker *clock.Ticker
vehicleID string
charger api.Charger
chargeTimer api.ChargeTimer
chargeRater api.ChargeRater
chargeMeter api.Meter // Charger usage meter
vehicle api.Vehicle // Currently active vehicle
vehicles []api.Vehicle // Assigned vehicles
socEstimator *soc.Estimator
socTimer *soc.Timer
// 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
chargedEnergy float64 // Charged energy while connected in Wh
chargeRemainingDuration time.Duration // Remaining charge duration
chargeRemainingEnergy float64 // Remaining charge energy in Wh
progress *Progress // Step-wise progress indicator
}
// NewLoadPointFromConfig creates a new loadpoint
func NewLoadPointFromConfig(log *util.Logger, cp configProvider, other map[string]interface{}) (*LoadPoint, error) {
lp := NewLoadPoint(log)
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 = pollConnected
}
// set vehicle polling interval
if lp.SoC.Poll.Interval < pollInterval {
if lp.SoC.Poll.Interval == 0 {
lp.SoC.Poll.Interval = pollInterval
} else {
lp.log.WARN.Printf("poll interval '%v' is lower than %v and may deplete your battery or lead to API misuse. USE AT YOUR OWN RISK.", lp.SoC.Poll.Interval, pollInterval)
}
}
if lp.MinCurrent == 0 {
lp.log.WARN.Println("minCurrent must not be zero")
}
if lp.MaxCurrent <= lp.MinCurrent {
lp.log.WARN.Println("maxCurrent must be larger than minCurrent")
}
// store defaults
lp.collectDefaults()
if lp.MeterRef != "" {
lp.chargeMeter = cp.Meter(lp.MeterRef)
}
// multiple vehicles
for _, ref := range lp.VehiclesRef {
vehicle := cp.Vehicle(ref)
lp.vehicles = append(lp.vehicles, vehicle)
}
// single vehicle
if lp.VehicleRef != "" {
if len(lp.vehicles) > 0 {
return nil, errors.New("cannot have vehicle and vehicles both")
}
vehicle := cp.Vehicle(lp.VehicleRef)
lp.vehicles = append(lp.vehicles, vehicle)
}
if lp.ChargerRef == "" {
return nil, errors.New("missing charger")
}
lp.charger = cp.Charger(lp.ChargerRef)
lp.configureChargerType(lp.charger)
// TODO handle delayed scale-down
if _, ok := lp.charger.(api.ChargePhases); ok && lp.GetPhases() != 0 {
lp.log.WARN.Printf("ignoring phases config (%dp) for switchable charger", lp.GetPhases())
lp.setPhases(0)
}
// allow target charge handler to access loadpoint
lp.socTimer = soc.NewTimer(lp.log, &adapter{LoadPoint: lp})
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)
}
return lp, nil
}
// NewLoadPoint creates a LoadPoint with sane defaults
func NewLoadPoint(log *util.Logger) *LoadPoint {
clock := clock.New()
bus := evbus.New()
lp := &LoadPoint{
log: log, // logger
clock: clock, // mockable time
bus: bus, // event bus
Mode: api.ModeOff,
Phases: 3,
status: api.StatusNone,
MinCurrent: 6, // A
MaxCurrent: 16, // A
SoC: SoCConfig{Min: 0, Target: 100}, // %
Enable: ThresholdConfig{Delay: time.Minute, Threshold: 0}, // t, W
Disable: ThresholdConfig{Delay: 3 * time.Minute, Threshold: 0}, // t, W
GuardDuration: 5 * time.Minute,
progress: NewProgress(0, 10), // soc progress indicator
}
return lp
}
// collectDefaults collects default values for use on disconnect
func (lp *LoadPoint) collectDefaults() {
// get reference to action config
actionCfg := &lp.onDisconnect
// allocate action config such that all pointer fields are fully allocated
if err := allocate.Zero(actionCfg); err == nil {
// initialize with default values
*actionCfg.Mode = lp.GetMode()
*actionCfg.MinCurrent = lp.GetMinCurrent()
*actionCfg.MaxCurrent = lp.GetMaxCurrent()
*actionCfg.MinSoC = lp.GetMinSoC()
*actionCfg.TargetSoC = lp.GetTargetSoC()
} else {
lp.log.ERROR.Printf("error allocating action config: %v", err)
}
}
// 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
} 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{}) {
if lp.uiChan != nil {
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.wakeUpTimer.Stop()
// soc update reset
lp.socUpdated = time.Time{}
}
// evChargeStopHandler sends external stop event
func (lp *LoadPoint) evChargeStopHandler() {
lp.log.INFO.Println("stop charging <-")
lp.pushEvent(evChargeStop)
// soc update reset
lp.socUpdated = time.Time{}
// reset pv enable/disable timer
// https://github.com/evcc-io/evcc/issues/2289
if !lp.pvTimer.Equal(elapsed) {
lp.resetPVTimerIfRunning()
}
}
// evVehicleConnectHandler sends external start event
func (lp *LoadPoint) evVehicleConnectHandler() {
lp.log.INFO.Printf("car connected")
// energy
lp.chargedEnergy = 0
lp.publish("chargedEnergy", lp.chargedEnergy)
// duration
lp.connectedTime = lp.clock.Now()
lp.publish("connectedDuration", time.Duration(0))
// soc update reset
lp.socUpdated = time.Time{}
// soc update reset on car change
if lp.socEstimator != nil {
lp.socEstimator.Reset()
}
// flush all vehicles before updating state
lp.log.DEBUG.Println("vehicle api refresh")
provider.ResetCached()
// start detection if we have multiple vehicles
if len(lp.vehicles) > 1 {
lp.startVehicleDetection()
}
// immediately allow pv mode activity
lp.elapsePVTimer()
lp.pushEvent(evVehicleConnect)
}
// evVehicleDisconnectHandler sends external start event
func (lp *LoadPoint) evVehicleDisconnectHandler() {
lp.log.INFO.Println("car disconnected")
// phases are unknown when vehicle disconnects
lp.resetMeasuredPhases()
// energy and duration
lp.publish("chargedEnergy", lp.chargedEnergy)
lp.publish("connectedDuration", lp.clock.Since(lp.connectedTime))
lp.pushEvent(evVehicleDisconnect)
// remove active vehicle if we have multiple vehicles
if len(lp.vehicles) > 1 {
lp.setActiveVehicle(nil)
}
// keep single vehicle to allow poll mode: always
if len(lp.vehicles) == 1 {
// but reset values if poll mode is not always (i.e. connected or charging)
if lp.SoC.Poll.Mode != pollAlways {
lp.unpublishVehicle()
}
}
// set default mode on disconnect
if lp.ResetOnDisconnect {
lp.applyAction(lp.onDisconnect)
}
// soc update reset
lp.socUpdated = time.Time{}
// reset timer when vehicle is removed
lp.socTimer.Reset()
}
// 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("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)
}
// applyAction executes the action
func (lp *LoadPoint) applyAction(actionCfg api.ActionConfig) {
if actionCfg.Mode != nil {
lp.SetMode(*actionCfg.Mode)
}
if actionCfg.MinCurrent != nil {
lp.SetMinCurrent(*actionCfg.MinCurrent)
}
if actionCfg.MaxCurrent != nil {
lp.SetMaxCurrent(*actionCfg.MaxCurrent)
}
if actionCfg.MinSoC != nil {
lp.SetMinSoC(*actionCfg.MinSoC)
}
if actionCfg.TargetSoC != nil {
lp.SetTargetSoC(*actionCfg.TargetSoC)
}
}
// Name returns the human-readable loadpoint title
func (lp *LoadPoint) Name() string {
return lp.Title
}
// 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)
// publish initial values
lp.publish("title", lp.Title)
lp.publish("minCurrent", lp.MinCurrent)
lp.publish("maxCurrent", lp.MaxCurrent)
lp.publish("phases", lp.Phases)
lp.publish("activePhases", lp.activePhases())
lp.publish("hasVehicle", len(lp.vehicles) > 0)
lp.Lock()
lp.publish("mode", lp.Mode)
lp.publish("targetSoC", lp.SoC.Target)
lp.publish("minSoC", lp.SoC.Min)
lp.Unlock()
// always treat single vehicle as attached to allow poll mode: always
if len(lp.vehicles) == 1 {
lp.setActiveVehicle(lp.vehicles[0])
}
// start detection if we have multiple vehicles
if len(lp.vehicles) > 1 {
lp.startVehicleDetection()
}
// read initial charger state to prevent immediately disabling charger
if enabled, err := lp.charger.Enabled(); err == nil {
if lp.enabled = enabled; enabled {
lp.guardUpdated = lp.clock.Now()
// set defined current for use by pv mode
_ = lp.setLimit(lp.GetMinCurrent(), false)
}
} else {
lp.log.ERROR.Printf("charger: %v", err)
}
// allow charger to access loadpoint
if ctrl, ok := lp.charger.(loadpoint.Controller); ok {
ctrl.LoadpointControl(lp)
}
}
// syncCharger updates charger status and synchronizes it with expectations
func (lp *LoadPoint) syncCharger() {
enabled, err := lp.charger.Enabled()
if err == nil {
if enabled != lp.enabled {
if time.Since(lp.guardUpdated) > guardGracePeriod {
lp.log.WARN.Printf("charger out of sync: expected %vd, got %vd", status[lp.enabled], status[enabled])
}
err = lp.charger.Enable(lp.enabled)
}
if !enabled && lp.charging() {
lp.log.WARN.Println("charger logic error: disabled but charging")
}
}
if err != nil {
lp.log.ERROR.Printf("charger: %v", err)
}
}
// setLimit applies charger current limits and enables/disables accordingly
func (lp *LoadPoint) setLimit(chargeCurrent float64, force bool) error {
// set current
if chargeCurrent != lp.chargeCurrent && chargeCurrent >= lp.GetMinCurrent() {
var err error
if charger, ok := lp.charger.(api.ChargerEx); ok {
err = charger.MaxCurrentMillis(chargeCurrent)
} else {
chargeCurrent = math.Trunc(chargeCurrent)
err = lp.charger.MaxCurrent(int64(chargeCurrent))
}
if err != nil {
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.GetMinCurrent(); enabled != lp.enabled {
if remaining := (lp.GuardDuration - lp.clock.Since(lp.guardUpdated)).Truncate(time.Second); remaining > 0 && !force {
lp.log.DEBUG.Printf("charger %s: contactor delay %v", status[enabled], remaining)
return nil
}
// remote stop
// TODO https://github.com/evcc-io/evcc/discussions/1929
// if car, ok := lp.vehicle.(api.VehicleChargeController); !enabled && ok {
// // log but don't propagate
// if err := car.StopCharge(); err != nil {
// lp.log.ERROR.Printf("vehicle remote charge stop: %v", err)
// }
// }
if err := lp.charger.Enable(enabled); err != nil {
return fmt.Errorf("charger %s: %w", status[enabled], err)
}
lp.log.DEBUG.Printf("charger %s", status[enabled])
lp.enabled = enabled
lp.guardUpdated = lp.clock.Now()
lp.bus.Publish(evChargeCurrent, chargeCurrent)
// start/stop vehicle wake-up timer
if enabled {
lp.log.DEBUG.Printf("wake-up timer: start")
lp.wakeUpTimer.Start()
} else {
lp.log.DEBUG.Printf("wake-up timer: stop")
lp.wakeUpTimer.Stop()
}
// remote start
// TODO https://github.com/evcc-io/evcc/discussions/1929
// if car, ok := lp.vehicle.(api.VehicleChargeController); enabled && ok {
// // log but don't propagate
// if err := car.StartCharge(); err != nil {
// lp.log.ERROR.Printf("vehicle remote charge start: %v", err)
// }
// }
}
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
}
// targetSocReached checks if target is configured and reached.
// If vehicle is not configured this will always return false
func (lp *LoadPoint) targetSocReached() bool {
return lp.vehicle != nil &&
lp.SoC.Target > 0 &&
lp.SoC.Target < 100 &&
lp.vehicleSoc >= float64(lp.SoC.Target)
}
// minSocNotReached checks if minimum is configured and not reached.
// If vehicle is not configured this will always return true
func (lp *LoadPoint) minSocNotReached() bool {
return lp.vehicle != nil &&
lp.SoC.Min > 0 &&
lp.vehicleSoc < float64(lp.SoC.Min)
}
// climateActive checks if vehicle has active climate request
func (lp *LoadPoint) climateActive() bool {
if cl, ok := lp.vehicle.(api.VehicleClimater); ok {
active, outsideTemp, targetTemp, err := cl.Climater()
if err == nil {
lp.log.DEBUG.Printf("climater active: %v, target temp: %.1fΒ°C, outside temp: %.1fΒ°C", active, targetTemp, outsideTemp)
status := "off"
if active {
status = "on"
switch {
case outsideTemp < targetTemp:
status = "heating"
case outsideTemp > targetTemp:
status = "cooling"
}
}
lp.publish("climater", status)
return active
}
if !errors.Is(err, api.ErrNotAvailable) {
lp.log.ERROR.Printf("climater: %v", err)
}
}
return false
}
// 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
}
// identifyVehicle reads vehicle identification from charger
func (lp *LoadPoint) identifyVehicle() {
identifier, ok := lp.charger.(api.Identifier)
if !ok {
return
}
id, err := identifier.Identify()
if err != nil {
lp.log.ERROR.Println("charger vehicle id:", err)
return
}
if lp.vehicleID == id {
return
}
// vehicle found or removed
lp.vehicleID = id
lp.log.DEBUG.Println("charger vehicle id:", id)
lp.publish("vehicleIdentity", id)
if id != "" {
if vehicle := lp.selectVehicleByID(id); vehicle != nil {
lp.setActiveVehicle(vehicle)
}
}
}
// selectVehicleByID selects the vehicle with the given ID
func (lp *LoadPoint) selectVehicleByID(id string) api.Vehicle {
// find exact match
for _, vehicle := range lp.vehicles {
if slices.Contains(vehicle.Identifiers(), id) {
return vehicle
}
}
// find placeholder match
for _, vehicle := range lp.vehicles {
for _, vid := range vehicle.Identifiers() {
re, err := regexp.Compile(strings.ReplaceAll(vid, "*", ".*?"))
if err != nil {
lp.log.ERROR.Printf("vehicle id: %v", err)
continue
}
if re.MatchString(id) {
return vehicle
}
}
}
return nil
}
// setActiveVehicle assigns currently active vehicle and configures soc estimator
func (lp *LoadPoint) setActiveVehicle(vehicle api.Vehicle) {
if lp.vehicle == vehicle {
return
}
from := "unknown"
if lp.vehicle != nil {
coordinator.release(lp.vehicle)
from = lp.vehicle.Title()
}
to := "unknown"
if vehicle != nil {
coordinator.acquire(lp, vehicle)
to = vehicle.Title()
}
lp.log.INFO.Printf("vehicle updated: %s -> %s", from, to)
if lp.vehicle = vehicle; vehicle != nil {
lp.socEstimator = soc.NewEstimator(lp.log, lp.charger, vehicle, lp.SoC.Estimate)
lp.publish("vehiclePresent", true)
lp.publish("vehicleTitle", lp.vehicle.Title())
lp.publish("vehicleCapacity", lp.vehicle.Capacity())
// publish odometer once
if vs, ok := lp.vehicle.(api.VehicleOdometer); ok {
if odo, err := vs.Odometer(); err == nil {
lp.log.DEBUG.Printf("vehicle odometer: %.0fkm", odo)
lp.publish("vehicleOdometer", odo)
} else {
lp.log.ERROR.Printf("vehicle odometer: %v", err)
}
}
lp.applyAction(vehicle.OnIdentified())
lp.progress.Reset()
} else {
lp.socEstimator = nil
lp.publish("vehiclePresent", false)
lp.publish("vehicleTitle", "")
lp.publish("vehicleCapacity", int64(0))
lp.publish("vehicleOdometer", 0.0)
}
lp.unpublishVehicle()
}
func (lp *LoadPoint) wakeUpVehicle() {
// charger
if c, ok := lp.charger.(api.AlarmClock); ok {
if err := c.WakeUp(); err != nil {
lp.log.ERROR.Printf("wake-up charger: %v", err)
}
return
}
// vehicle
if lp.vehicle != nil {
if vs, ok := lp.vehicle.(api.AlarmClock); ok {
if err := vs.WakeUp(); err != nil {
lp.log.ERROR.Printf("wake-up vehicle: %v", err)
}
}
}
}
// unpublishVehicle resets published vehicle data
func (lp *LoadPoint) unpublishVehicle() {
lp.vehicleSoc = 0
lp.publish("vehicleSoC", 0.0)
lp.publish("vehicleRange", int64(0))
lp.setRemainingDuration(-1)
}
// startVehicleDetection resets connection timer and starts api refresh timer
func (lp *LoadPoint) startVehicleDetection() {
lp.vehicleConnected = lp.clock.Now()
lp.vehicleConnectedTicker = lp.clock.Ticker(vehicleDetectInterval)
}
// vehicleUnidentified checks if loadpoint has multiple vehicles associated and starts discovery period
func (lp *LoadPoint) vehicleUnidentified() bool {
res := len(lp.vehicles) > 1 && lp.vehicle == nil &&
lp.clock.Since(lp.vehicleConnected) < vehicleDetectDuration
// request vehicle api refresh while waiting to identify
if res {
select {
case <-lp.vehicleConnectedTicker.C:
lp.log.DEBUG.Println("vehicle api refresh")
provider.ResetCached()
default:
}
}
return res
}
// identifyVehicleByStatus validates if the active vehicle is still connected to the loadpoint
func (lp *LoadPoint) identifyVehicleByStatus() {
if len(lp.vehicles) <= 1 {
return
}
if vehicle := coordinator.identifyVehicleByStatus(lp.log, lp, lp.vehicles); vehicle != nil {
lp.setActiveVehicle(vehicle)
return
}
// remove previous vehicle if status was not confirmed
if _, ok := lp.vehicle.(api.ChargeState); ok {
lp.setActiveVehicle(nil)
}
}
// updateChargerStatus updates charger status and detects car connected/disconnected events
func (lp *LoadPoint) updateChargerStatus() error {
status, err := lp.charger.Status()
if err != nil {
return err
}
lp.log.DEBUG.Printf("charger status: %s", status)
if prevStatus := lp.GetStatus(); status != prevStatus {
lp.setStatus(status)
// changed from empty (initial startup) - set connected without sending message
if prevStatus == api.StatusNone {
lp.connectedTime = lp.clock.Now()
lp.publish("connectedDuration", time.Duration(0))
}
// changed from A - connected
if prevStatus == api.StatusA {
lp.bus.Publish(evVehicleConnect)
}
// changed to C - start/stop charging cycle - handle before disconnect to update energy
if lp.charging() {
lp.bus.Publish(evChargeStart)
} else if prevStatus == api.StatusC {
lp.bus.Publish(evChargeStop)
}
// changed to A - disconnected - don't send on startup
if status == api.StatusA && prevStatus != api.StatusNone {
lp.bus.Publish(evVehicleDisconnect)
}
// update whenever there is a state change
lp.bus.Publish(evChargeCurrent, lp.chargeCurrent)
}
return nil
}
// effectiveCurrent returns the currently effective charging current
func (lp *LoadPoint) effectiveCurrent() float64 {
if !lp.charging() {
return 0
}
// adjust actual current for vehicles like Zoe where it remains below target
if lp.chargeCurrents != nil {
cur := lp.chargeCurrents[0]
return math.Min(cur+2.0, lp.chargeCurrent)
}
return lp.chargeCurrent
}
// elapsePVTimer puts the pv enable/disable timer into elapsed state
func (lp *LoadPoint) elapsePVTimer() {
lp.log.DEBUG.Printf("pv timer elapse")
lp.pvTimer = elapsed
lp.guardUpdated = elapsed
lp.publishTimer(pvTimer, 0, timerInactive)
}
// resetPVTimerIfRunning resets the pv enable/disable timer to disabled state
func (lp *LoadPoint) resetPVTimerIfRunning(typ ...string) {
if lp.pvTimer.IsZero() {
return
}
msg := "pv timer reset"
if len(typ) == 1 {
msg = fmt.Sprintf("pv %s timer reset", typ[0])
}
lp.log.DEBUG.Printf(msg)
lp.pvTimer = time.Time{}
lp.publishTimer(pvTimer, 0, timerInactive)
}
// scalePhasesIfAvailable scales if api.ChargePhases is available
func (lp *LoadPoint) scalePhasesIfAvailable(phases int) error {
if _, ok := lp.charger.(api.ChargePhases); ok {
return lp.scalePhases(phases)
}
return nil
}
// setPhases sets the number of enabled phases without modifying the charger
func (lp *LoadPoint) setPhases(phases int) {
if lp.GetPhases() != phases {
lp.Lock()
lp.Phases = phases
lp.phaseTimer = time.Time{}
lp.Unlock()
lp.publish("phases", lp.Phases)
lp.publishTimer(phaseTimer, 0, timerInactive)
lp.resetMeasuredPhases()
}
}
// scalePhases adjusts the number of active phases and returns the appropriate charging current.