forked from evcc-io/evcc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathocpp.go
407 lines (332 loc) · 10.4 KB
/
ocpp.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
package charger
import (
"cmp"
"fmt"
"math"
"slices"
"time"
"github.com/evcc-io/evcc/api"
"github.com/evcc-io/evcc/charger/ocpp"
"github.com/evcc-io/evcc/core/loadpoint"
"github.com/evcc-io/evcc/util"
"github.com/lorenzodonini/ocpp-go/ocpp1.6/core"
"github.com/lorenzodonini/ocpp-go/ocpp1.6/types"
"github.com/samber/lo"
)
// OCPP charger implementation
type OCPP struct {
log *util.Logger
cp *ocpp.CP
conn *ocpp.Connector
phases int
enabled bool
current float64
stackLevelZero bool
lp loadpoint.API
}
const defaultIdTag = "evcc" // RemoteStartTransaction only
func init() {
registry.Add("ocpp", NewOCPPFromConfig)
}
// NewOCPPFromConfig creates a OCPP charger from generic config
func NewOCPPFromConfig(other map[string]interface{}) (api.Charger, error) {
cc := struct {
StationId string
IdTag string
Connector int
MeterInterval time.Duration
MeterValues string
ConnectTimeout time.Duration // Initial Timeout
Timeout time.Duration // TODO deprecated
BootNotification *bool // TODO deprecated
GetConfiguration *bool // TODO deprecated
ChargingRateUnit types.ChargingRateUnitType // TODO deprecated
AutoStart bool // TODO deprecated
NoStop bool // TODO deprecated
StackLevelZero *bool
RemoteStart bool
}{
Connector: 1,
MeterInterval: 10 * time.Second,
ConnectTimeout: 5 * time.Minute,
}
if err := util.DecodeOther(other, &cc); err != nil {
return nil, err
}
stackLevelZero := cc.StackLevelZero != nil && *cc.StackLevelZero
c, err := NewOCPP(cc.StationId, cc.Connector, cc.IdTag,
cc.MeterValues, cc.MeterInterval,
stackLevelZero, cc.RemoteStart,
cc.ConnectTimeout)
if err != nil {
return c, err
}
var (
powerG, totalEnergyG, socG func() (float64, error)
currentsG, voltagesG func() (float64, float64, float64, error)
)
if c.cp.HasMeasurement(types.MeasurandPowerActiveImport) {
powerG = c.conn.CurrentPower
}
if c.cp.HasMeasurement(types.MeasurandEnergyActiveImportRegister) {
totalEnergyG = c.conn.TotalEnergy
}
if c.cp.HasMeasurement(types.MeasurandCurrentImport) {
currentsG = c.conn.Currents
}
if c.cp.HasMeasurement(types.MeasurandVoltage) {
voltagesG = c.conn.Voltages
}
if c.cp.HasMeasurement(types.MeasurandSoC) {
socG = c.conn.Soc
}
var phasesS func(int) error
if c.cp.PhaseSwitching {
phasesS = c.phases1p3p
}
// var currentG func() (float64, error)
// if c.cp.HasMeasurement(types.MeasurandCurrentOffered) {
// currentG = c.conn.GetMaxCurrent
// }
return decorateOCPP(c, powerG, totalEnergyG, currentsG, voltagesG, phasesS, socG), nil
}
//go:generate go run ../cmd/tools/decorate.go -f decorateOCPP -b *OCPP -r api.Charger -t "api.Meter,CurrentPower,func() (float64, error)" -t "api.MeterEnergy,TotalEnergy,func() (float64, error)" -t "api.PhaseCurrents,Currents,func() (float64, float64, float64, error)" -t "api.PhaseVoltages,Voltages,func() (float64, float64, float64, error)" -t "api.PhaseSwitcher,Phases1p3p,func(int) error" -t "api.Battery,Soc,func() (float64, error)"
// NewOCPP creates OCPP charger
func NewOCPP(id string, connector int, idTag string,
meterValues string, meterInterval time.Duration,
stackLevelZero, remoteStart bool,
connectTimeout time.Duration,
) (*OCPP, error) {
unit := "ocpp"
if id != "" {
unit = id
}
unit = fmt.Sprintf("%s-%d", unit, connector)
log := util.NewLogger(unit)
cp, err := ocpp.Instance().ChargepointByID(id)
if err != nil {
cp = ocpp.NewChargePoint(log, id)
// should not error
if err := ocpp.Instance().Register(id, cp); err != nil {
return nil, err
}
log.DEBUG.Printf("waiting for chargepoint: %v", connectTimeout)
select {
case <-time.After(connectTimeout):
return nil, api.ErrTimeout
case <-cp.HasConnected():
}
if err := cp.Setup(meterValues, meterInterval); err != nil {
return nil, err
}
}
if cp.NumberOfConnectors > 0 && connector > cp.NumberOfConnectors {
return nil, fmt.Errorf("invalid connector: %d", connector)
}
if remoteStart {
idTag = lo.CoalesceOrEmpty(idTag, cp.IdTag, defaultIdTag)
}
conn, err := ocpp.NewConnector(log, connector, cp, idTag)
if err != nil {
return nil, err
}
c := &OCPP{
log: log,
cp: cp,
conn: conn,
stackLevelZero: stackLevelZero,
}
if cp.HasRemoteTriggerFeature {
if err := conn.TriggerMessageRequest(core.StatusNotificationFeatureName); err != nil {
c.log.DEBUG.Printf("failed triggering StatusNotification: %v", err)
}
go conn.WatchDog(10 * time.Second)
}
return c, conn.Initialized()
}
// Connector returns the connector instance
func (c *OCPP) Connector() *ocpp.Connector {
return c.conn
}
// Status implements the api.Charger interface
func (c *OCPP) Status() (api.ChargeStatus, error) {
status, err := c.conn.Status()
if err != nil {
return api.StatusNone, err
}
switch status {
case
core.ChargePointStatusAvailable, // "Available"
core.ChargePointStatusUnavailable: // "Unavailable"
return api.StatusA, nil
case
core.ChargePointStatusPreparing, // "Preparing"
core.ChargePointStatusSuspendedEVSE, // "SuspendedEVSE"
core.ChargePointStatusSuspendedEV, // "SuspendedEV"
core.ChargePointStatusFinishing: // "Finishing"
return api.StatusB, nil
case
core.ChargePointStatusCharging: // "Charging"
return api.StatusC, nil
case
core.ChargePointStatusReserved, // "Reserved"
core.ChargePointStatusFaulted: // "Faulted"
return api.StatusF, fmt.Errorf("chargepoint status: %s", status)
default:
return api.StatusNone, fmt.Errorf("invalid chargepoint status: %s", status)
}
}
var _ api.StatusReasoner = (*OCPP)(nil)
func (c *OCPP) StatusReason() (api.Reason, error) {
var res api.Reason
s, err := c.conn.Status()
if err != nil {
return res, err
}
switch {
case c.conn.NeedsAuthentication():
res = api.ReasonWaitingForAuthorization
case s == core.ChargePointStatusFinishing:
res = api.ReasonDisconnectRequired
}
return res, nil
}
// Enabled implements the api.Charger interface
func (c *OCPP) Enabled() (bool, error) {
if s, err := c.conn.Status(); err == nil {
switch s {
case
core.ChargePointStatusSuspendedEVSE:
return false, nil
case
core.ChargePointStatusCharging,
core.ChargePointStatusSuspendedEV:
return true, nil
}
}
// fallback to the "offered" measurands
if c.cp.HasMeasurement(types.MeasurandCurrentOffered) {
if v, err := c.conn.GetMaxCurrent(); err == nil {
return v > 0, nil
}
}
if c.cp.HasMeasurement(types.MeasurandPowerOffered) {
if v, err := c.conn.GetMaxPower(); err == nil {
return v > 0, nil
}
}
// fallback to querying the active charging profile schedule limit
if v, err := c.conn.GetScheduleLimit(60); err == nil {
return v > 0, nil
}
// fallback to cached value as last resort
return c.enabled, nil
}
// Enable implements the api.Charger interface
func (c *OCPP) Enable(enable bool) error {
var current float64
if enable {
current = c.current
}
err := c.setCurrent(current)
if err == nil {
// cache enabled state as last fallback option
c.enabled = enable
}
return err
}
// setCurrent sets the TxDefaultChargingProfile with given current
func (c *OCPP) setCurrent(current float64) error {
err := c.conn.SetChargingProfile(c.createTxDefaultChargingProfile(math.Trunc(10*current) / 10))
if err != nil {
err = fmt.Errorf("set charging profile: %w", err)
}
return err
}
// createTxDefaultChargingProfile returns a TxDefaultChargingProfile with given current
func (c *OCPP) createTxDefaultChargingProfile(current float64) *types.ChargingProfile {
phases := c.phases
period := types.NewChargingSchedulePeriod(0, current)
if c.cp.ChargingRateUnit == types.ChargingRateUnitWatts {
// get (expectedly) active phases from loadpoint
if c.lp != nil {
phases = c.lp.GetPhases()
}
if phases == 0 {
phases = 3
}
period = types.NewChargingSchedulePeriod(0, math.Trunc(230.0*current*float64(phases)))
}
// OCPP assumes phases == 3 if not set
if phases != 0 {
period.NumberPhases = &phases
}
res := &types.ChargingProfile{
ChargingProfileId: c.cp.ChargingProfileId,
ChargingProfilePurpose: types.ChargingProfilePurposeTxDefaultProfile,
ChargingProfileKind: types.ChargingProfileKindAbsolute,
ChargingSchedule: &types.ChargingSchedule{
StartSchedule: types.Now(),
ChargingRateUnit: c.cp.ChargingRateUnit,
ChargingSchedulePeriod: []types.ChargingSchedulePeriod{period},
},
}
if !c.stackLevelZero {
res.StackLevel = c.cp.StackLevel
}
return res
}
// MaxCurrent implements the api.Charger interface
func (c *OCPP) MaxCurrent(current int64) error {
return c.MaxCurrentMillis(float64(current))
}
var _ api.ChargerEx = (*OCPP)(nil)
// MaxCurrentMillis implements the api.ChargerEx interface
func (c *OCPP) MaxCurrentMillis(current float64) error {
err := c.setCurrent(current)
if err == nil {
c.current = current
}
return err
}
// phases1p3p implements the api.PhaseSwitcher interface
func (c *OCPP) phases1p3p(phases int) error {
c.phases = phases
return c.setCurrent(c.current)
}
var _ api.Identifier = (*OCPP)(nil)
// Identify implements the api.Identifier interface
func (c *OCPP) Identify() (string, error) {
return c.conn.IdTag(), nil
}
var _ api.Diagnosis = (*OCPP)(nil)
// Diagnose implements the api.Diagnosis interface
func (c *OCPP) Diagnose() {
fmt.Printf("\tCharge Point ID: %s\n", c.cp.ID())
if c.cp.BootNotificationResult != nil {
fmt.Printf("\tBoot Notification:\n")
fmt.Printf("\t\tChargePointVendor: %s\n", c.cp.BootNotificationResult.ChargePointVendor)
fmt.Printf("\t\tChargePointModel: %s\n", c.cp.BootNotificationResult.ChargePointModel)
fmt.Printf("\t\tChargePointSerialNumber: %s\n", c.cp.BootNotificationResult.ChargePointSerialNumber)
fmt.Printf("\t\tFirmwareVersion: %s\n", c.cp.BootNotificationResult.FirmwareVersion)
}
fmt.Printf("\tConfiguration:\n")
if resp, err := c.cp.GetConfiguration(); err == nil {
// sort configuration keys for printing
slices.SortFunc(resp.ConfigurationKey, func(i, j core.ConfigurationKey) int {
return cmp.Compare(i.Key, j.Key)
})
rw := map[bool]string{false: "r/w", true: "r/o"}
for _, opt := range resp.ConfigurationKey {
if opt.Value == nil {
continue
}
fmt.Printf("\t\t%s (%s): %s\n", opt.Key, rw[opt.Readonly], *opt.Value)
}
}
}
var _ loadpoint.Controller = (*OCPP)(nil)
// LoadpointControl implements loadpoint.Controller
func (c *OCPP) LoadpointControl(lp loadpoint.API) {
c.lp = lp
}