forked from evcc-io/evcc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloadpoint_session.go
106 lines (84 loc) · 2.31 KB
/
loadpoint_session.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
package core
import (
"github.com/evcc-io/evcc/api"
"github.com/evcc-io/evcc/core/session"
)
func (lp *Loadpoint) chargeMeterTotal() float64 {
m, ok := lp.chargeMeter.(api.MeterEnergy)
if !ok {
return 0
}
f, err := m.TotalEnergy()
if err != nil {
lp.log.ERROR.Printf("charge total import: %v", err)
return 0
}
lp.log.DEBUG.Printf("charge total import: %.3fkWh", f)
return f
}
// createSession creates a charging session. The created timestamp is empty until set by evChargeStartHandler.
// The session is not persisted yet. That will only happen when stopSession is called.
func (lp *Loadpoint) createSession() {
// test guard
if lp.db == nil || lp.session != nil {
return
}
lp.session = lp.db.New(lp.chargeMeterTotal())
if vehicle := lp.GetVehicle(); vehicle != nil {
lp.session.Vehicle = vehicle.Title()
}
if c, ok := lp.charger.(api.Identifier); ok {
if id, err := c.Identify(); err == nil {
lp.session.Identifier = id
}
}
}
// stopSession ends a charging session segment and persists the session.
func (lp *Loadpoint) stopSession() {
s := lp.session
// test guard
if lp.db == nil || s == nil {
return
}
// abort the session if charging has never started
if s.Created.IsZero() {
return
}
s.Finished = lp.clock.Now()
if meterStop := lp.chargeMeterTotal(); meterStop > 0 {
s.MeterStop = &meterStop
}
if chargedEnergy := lp.getChargedEnergy() / 1e3; chargedEnergy > s.ChargedEnergy {
lp.sessionEnergy.Update(chargedEnergy)
}
solarPerc := lp.sessionEnergy.SolarPercentage()
s.SolarPercentage = &solarPerc
s.Price = lp.sessionEnergy.Price()
s.PricePerKWh = lp.sessionEnergy.PricePerKWh()
s.Co2PerKWh = lp.sessionEnergy.Co2PerKWh()
s.ChargedEnergy = lp.sessionEnergy.TotalWh() / 1e3
s.ChargeDuration = &lp.chargeDuration
lp.db.Persist(s)
}
type sessionOption func(*session.Session)
// updateSession updates any parameter of a charging session and persists the session.
func (lp *Loadpoint) updateSession(opts ...sessionOption) {
// test guard
if lp.db == nil || lp.session == nil {
return
}
for _, opt := range opts {
opt(lp.session)
}
if !lp.session.Created.IsZero() {
lp.db.Persist(lp.session)
}
}
// clearSession clears the charging session without persisting it.
func (lp *Loadpoint) clearSession() {
// test guard
if lp.db == nil {
return
}
lp.session = nil
}