forked from project-chip/connectedhomeip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEnergyEvseDelegateImpl.cpp
1593 lines (1380 loc) · 51.2 KB
/
EnergyEvseDelegateImpl.cpp
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
/*
*
* Copyright (c) 2023-2024 Project CHIP Authors
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <EnergyEvseDelegateImpl.h>
#include <app-common/zap-generated/attributes/Accessors.h>
#include <app-common/zap-generated/cluster-objects.h>
#include <app/EventLogging.h>
#include <app/SafeAttributePersistenceProvider.h>
using namespace chip;
using namespace chip::app;
using namespace chip::app::DataModel;
using namespace chip::app::Clusters;
using namespace chip::app::Clusters::EnergyEvse;
using namespace chip::app::Clusters::EnergyEvse::Attributes;
using chip::app::LogEvent;
using chip::Protocols::InteractionModel::Status;
EnergyEvseDelegate::~EnergyEvseDelegate()
{
// TODO Fix this as part of issue #30993 refactoring
if (!mVehicleID.IsNull())
{
ChipLogDetail(AppServer, "Freeing VehicleID");
delete[] mVehicleID.Value().data();
}
}
/**
* @brief Helper function to get current timestamp in Epoch format
*
* @param chipEpoch reference to hold return timestamp
*/
CHIP_ERROR GetEpochTS(uint32_t & chipEpoch);
/**
* @brief Called when EVSE cluster receives Disable command
*/
Status EnergyEvseDelegate::Disable()
{
ChipLogProgress(AppServer, "EnergyEvseDelegate::Disable()");
DataModel::Nullable<uint32_t> disableTime(0);
/* update ChargingEnabledUntil & DischargingEnabledUntil to show 0 */
SetChargingEnabledUntil(disableTime);
SetDischargingEnabledUntil(disableTime);
/* update MinimumChargeCurrent & MaximumChargeCurrent to 0 */
SetMinimumChargeCurrent(0);
SetMaximumChargeCurrent(0);
/* update MaximumDischargeCurrent to 0 */
SetMaximumDischargeCurrent(0);
return HandleStateMachineEvent(EVSEStateMachineEvent::DisabledEvent);
}
/**
* @brief Called when EVSE cluster receives EnableCharging command
*
* @param chargingEnabledUntil (can be null to indefinite charging)
* @param minimumChargeCurrent (in mA)
* @param maximumChargeCurrent (in mA)
*/
Status EnergyEvseDelegate::EnableCharging(const DataModel::Nullable<uint32_t> & chargingEnabledUntil,
const int64_t & minimumChargeCurrent, const int64_t & maximumChargeCurrent)
{
ChipLogProgress(AppServer, "EnergyEvseDelegate::EnableCharging()");
if (maximumChargeCurrent < kMinimumChargeCurrent || maximumChargeCurrent > kMaximumChargeCurrent)
{
ChipLogError(AppServer, "Maximum Current outside limits");
return Status::ConstraintError;
}
if (minimumChargeCurrent < kMinimumChargeCurrent || minimumChargeCurrent > kMaximumChargeCurrent)
{
ChipLogError(AppServer, "Maximum Current outside limits");
return Status::ConstraintError;
}
if (minimumChargeCurrent > maximumChargeCurrent)
{
ChipLogError(AppServer, "Minium Current > Maximum Current!");
return Status::ConstraintError;
}
if (chargingEnabledUntil.IsNull())
{
/* Charging enabled indefinitely */
ChipLogError(AppServer, "Charging enabled indefinitely");
SetChargingEnabledUntil(chargingEnabledUntil);
}
else
{
/* check chargingEnabledUntil is in the future */
ChipLogError(AppServer, "Charging enabled until: %lu", static_cast<long unsigned int>(chargingEnabledUntil.Value()));
SetChargingEnabledUntil(chargingEnabledUntil);
}
/* If it looks ok, store the min & max charging current */
mMaximumChargingCurrentLimitFromCommand = maximumChargeCurrent;
SetMinimumChargeCurrent(minimumChargeCurrent);
// TODO persist these to KVS
ComputeMaxChargeCurrentLimit();
return HandleStateMachineEvent(EVSEStateMachineEvent::ChargingEnabledEvent);
}
/**
* @brief Called when EVSE cluster receives EnableDischarging command
*
* @param dischargingEnabledUntil (can be null to indefinite discharging)
* @param maximumDischargeCurrent (in mA)
*/
Status EnergyEvseDelegate::EnableDischarging(const DataModel::Nullable<uint32_t> & dischargingEnabledUntil,
const int64_t & maximumDischargeCurrent)
{
ChipLogProgress(AppServer, "EnergyEvseDelegate::EnableDischarging() called.");
// TODO save the maxDischarging Current
// TODO Do something with timestamp
return HandleStateMachineEvent(EVSEStateMachineEvent::DischargingEnabledEvent);
}
/**
* @brief Routine to help schedule a timer callback to check if the EVSE should go disabled
*
* If the clock is sync'd we can work out when to call back to check when to disable the EVSE
* automatically. If the clock isn't sync'd the we just set a timer to check once every 30s.
*
* We first check the SupplyState to check if it is EnabledCharging or EnabledDischarging
* Then if the EnabledCharging/DischargingUntil is not Null, then we compute a delay to come
* back and check.
*/
Status EnergyEvseDelegate::ScheduleCheckOnEnabledTimeout()
{
uint32_t chipEpoch = 0;
DataModel::Nullable<uint32_t> enabledUntilTime;
if (mSupplyState == SupplyStateEnum::kChargingEnabled)
{
enabledUntilTime = GetChargingEnabledUntil();
}
else if (mSupplyState == SupplyStateEnum::kDischargingEnabled)
{
enabledUntilTime = GetDischargingEnabledUntil();
}
else
{
// In all other states the EVSE is disabled
return Status::Success;
}
if (enabledUntilTime.IsNull())
{
/* This is enabled indefinitely so don't schedule a callback */
return Status::Success;
}
CHIP_ERROR err = GetEpochTS(chipEpoch);
if (err == CHIP_NO_ERROR)
{
/* time is sync'd */
int32_t delta = static_cast<int32_t>(enabledUntilTime.Value() - chipEpoch);
if (delta > 0)
{
/* The timer hasn't expired yet - set a timer to check in the future */
ChipLogDetail(AppServer, "Setting EVSE Enable check timer for %ld seconds", static_cast<long int>(delta));
DeviceLayer::SystemLayer().StartTimer(System::Clock::Seconds32(delta), EvseCheckTimerExpiry, this);
}
else
{
/* we have gone past the enabledUntilTime - so we need to disable */
ChipLogDetail(AppServer, "EVSE enable time expired, disabling charging");
Disable();
}
}
else if (err == CHIP_ERROR_REAL_TIME_NOT_SYNCED)
{
/* Real time isn't sync'd -lets check again in 30 seconds - otherwise keep the charger enabled */
DeviceLayer::SystemLayer().StartTimer(System::Clock::Seconds32(kPeriodicCheckIntervalRealTimeClockNotSynced),
EvseCheckTimerExpiry, this);
}
return Status::Success;
}
void EnergyEvseDelegate::EvseCheckTimerExpiry(System::Layer * systemLayer, void * delegate)
{
EnergyEvseDelegate * dg = reinterpret_cast<EnergyEvseDelegate *>(delegate);
dg->ScheduleCheckOnEnabledTimeout();
}
/**
* @brief Called when EVSE cluster receives StartDiagnostics command
*
* NOTE: Application code needs to call HwDiagnosticsComplete
* once diagnostics have been completed.
*/
Status EnergyEvseDelegate::StartDiagnostics()
{
/* For EVSE manufacturers to customize */
ChipLogProgress(AppServer, "EnergyEvseDelegate::StartDiagnostics()");
if (mSupplyState != SupplyStateEnum::kDisabled)
{
ChipLogError(AppServer, "EVSE: cannot be put into diagnostics mode if it is not Disabled!");
return Status::Failure;
}
// Update the SupplyState - this will automatically callback the Application StateChanged callback
SetSupplyState(SupplyStateEnum::kDisabledDiagnostics);
return Status::Success;
}
/* ---------------------------------------------------------------------------
* EVSE Hardware interface below
*/
/**
* @brief Called by EVSE Hardware to register a callback handler mechanism
*
* This is normally called at start-up.
*
* @param EVSECallbackFunct - function pointer to call
* @param intptr_t - optional context to provide back to callback handler
*/
Status EnergyEvseDelegate::HwRegisterEvseCallbackHandler(EVSECallbackFunc handler, intptr_t arg)
{
if (mCallbacks.handler != nullptr)
{
ChipLogError(AppServer, "Callback handler already initialized");
return Status::Failure;
}
mCallbacks.handler = handler;
mCallbacks.arg = arg;
return Status::Success;
}
/**
* @brief Called by EVSE Hardware to notify the delegate of the maximum
* current limit supported by the hardware.
*
* This is normally called at start-up.
*
* @param currentmA - Maximum current limit supported by the hardware
*/
Status EnergyEvseDelegate::HwSetMaxHardwareCurrentLimit(int64_t currentmA)
{
if (currentmA < kMinimumChargeCurrent || currentmA > kMaximumChargeCurrent)
{
return Status::ConstraintError;
}
/* there is no attribute to store this so store in private variable */
mMaxHardwareCurrentLimit = currentmA;
return ComputeMaxChargeCurrentLimit();
}
/**
* @brief Called by EVSE Hardware to notify the delegate of maximum electrician
* set current limit.
*
* This is normally called at start-up when reading from DIP-switch
* settings.
*
* @param currentmA - Maximum current limit specified by electrician
*/
Status EnergyEvseDelegate::HwSetCircuitCapacity(int64_t currentmA)
{
if (currentmA < kMinimumChargeCurrent || currentmA > kMaximumChargeCurrent)
{
return Status::ConstraintError;
}
mCircuitCapacity = currentmA;
MatterReportingAttributeChangeCallback(mEndpointId, EnergyEvse::Id, CircuitCapacity::Id);
return ComputeMaxChargeCurrentLimit();
}
/**
* @brief Called by EVSE Hardware to notify the delegate of the cable assembly
* current limit.
*
* This is normally called when the EV is plugged into the EVSE and the
* PP voltage is measured by the EVSE. A pull-up resistor in the cable
* causes a voltage drop. Different current limits can be indicated
* using different resistors, which results in different voltages
* measured by the EVSE.
*
* @param currentmA - Maximum current limit detected from Cable assembly
*/
Status EnergyEvseDelegate::HwSetCableAssemblyLimit(int64_t currentmA)
{
if (currentmA < kMinimumChargeCurrent || currentmA > kMaximumChargeCurrent)
{
return Status::ConstraintError;
}
/* there is no attribute to store this so store in private variable */
mCableAssemblyCurrentLimit = currentmA;
return ComputeMaxChargeCurrentLimit();
}
/**
* @brief Called by EVSE Hardware to indicate if EV is detected
*
* The only allowed states that the EVSE hardware can tell us about are:
* kNotPluggedIn
* kPluggedInNoDemand
* kPluggedInDemand
*
* The actual overall state is more complex and includes faults,
* enable & disable charging or discharging etc.
*
* @param StateEnum - the state of the EV being plugged in and asking for demand etc
*/
Status EnergyEvseDelegate::HwSetState(StateEnum newState)
{
switch (newState)
{
case StateEnum::kNotPluggedIn:
switch (mHwState)
{
case StateEnum::kNotPluggedIn:
// No change
break;
case StateEnum::kPluggedInNoDemand:
case StateEnum::kPluggedInDemand:
/* EVSE has been unplugged now */
mHwState = newState;
HandleStateMachineEvent(EVSEStateMachineEvent::EVNotDetectedEvent);
break;
default:
// invalid value for mHwState
ChipLogError(AppServer, "HwSetState newstate(kNotPluggedIn) - Invalid value for mHwState");
mHwState = newState; // set it to the new state anyway
break;
}
break;
case StateEnum::kPluggedInNoDemand:
switch (mHwState)
{
case StateEnum::kNotPluggedIn:
/* EV was unplugged, now is plugged in */
mHwState = newState;
HandleStateMachineEvent(EVSEStateMachineEvent::EVPluggedInEvent);
break;
case StateEnum::kPluggedInNoDemand:
// No change
break;
case StateEnum::kPluggedInDemand:
/* EV was plugged in and wanted demand, now doesn't want demand */
mHwState = newState;
HandleStateMachineEvent(EVSEStateMachineEvent::EVNoDemandEvent);
break;
default:
// invalid value for mHwState
ChipLogError(AppServer, "HwSetState newstate(kPluggedInNoDemand) - Invalid value for mHwState");
mHwState = newState; // set it to the new state anyway
break;
}
break;
case StateEnum::kPluggedInDemand:
switch (mHwState)
{
case StateEnum::kNotPluggedIn:
/* EV was unplugged, now is plugged in and wants demand */
mHwState = newState;
HandleStateMachineEvent(EVSEStateMachineEvent::EVPluggedInEvent);
HandleStateMachineEvent(EVSEStateMachineEvent::EVDemandEvent);
break;
case StateEnum::kPluggedInNoDemand:
/* EV was plugged in and didn't want demand, now does want demand */
mHwState = newState;
HandleStateMachineEvent(EVSEStateMachineEvent::EVDemandEvent);
break;
case StateEnum::kPluggedInDemand:
// No change
break;
default:
// invalid value for mHwState
ChipLogError(AppServer, "HwSetState newstate(kPluggedInDemand) - Invalid value for mHwState");
mHwState = newState; // set it to the new state anyway
break;
}
break;
default:
/* All other states should be managed by the Delegate */
ChipLogError(AppServer, "HwSetState received invalid enum from caller");
return Status::Failure;
}
return Status::Success;
}
/**
* @brief Called by EVSE Hardware to indicate a fault
*
* @param FaultStateEnum - the fault condition detected
*/
Status EnergyEvseDelegate::HwSetFault(FaultStateEnum newFaultState)
{
ChipLogProgress(AppServer, "EnergyEvseDelegate::Fault()");
if (mFaultState == newFaultState)
{
ChipLogError(AppServer, "No change in fault state, ignoring call");
return Status::Failure;
}
/** Before we do anything we log the fault
* any change in FaultState reports previous fault and new fault
* and the state prior to the fault being raised */
SendFaultEvent(newFaultState);
/* Updated FaultState before we call into the handlers */
SetFaultState(newFaultState);
if (newFaultState == FaultStateEnum::kNoError)
{
/* Fault has been cleared */
HandleStateMachineEvent(EVSEStateMachineEvent::FaultCleared);
}
else
{
/* a new Fault has been raised */
HandleStateMachineEvent(EVSEStateMachineEvent::FaultRaised);
}
return Status::Success;
}
/**
* @brief Called by EVSE Hardware to Send a RFID event
*
* @param ByteSpan RFID tag value (max 10 octets)
*/
Status EnergyEvseDelegate::HwSetRFID(ByteSpan uid)
{
Events::Rfid::Type event{ .uid = uid };
EventNumber eventNumber;
CHIP_ERROR error = LogEvent(event, mEndpointId, eventNumber);
if (CHIP_NO_ERROR != error)
{
ChipLogError(Zcl, "[Notify] Unable to send notify event: %s [endpointId=%d]", error.AsString(), mEndpointId);
return Status::Failure;
}
return Status::Success;
}
/**
* @brief Called by EVSE Hardware to share the VehicleID
*
* This routine will make a copy of the string so the callee doesn't
* have to hold onto it forever.
*
* @param CharSpan containing up to 32 chars.
*/
Status EnergyEvseDelegate::HwSetVehicleID(const CharSpan & newValue)
{
// TODO this code to be refactored - See Issue #30993
if (!mVehicleID.IsNull() && newValue.data_equal(mVehicleID.Value()))
{
return Status::Success;
}
/* create a copy of the string so the callee doesn't have to keep it */
char * destinationBuffer = new char[kMaxVehicleIDBufSize];
MutableCharSpan destinationString(destinationBuffer, kMaxVehicleIDBufSize);
CHIP_ERROR err = CopyCharSpanToMutableCharSpan(newValue, destinationString);
if (err != CHIP_NO_ERROR)
{
ChipLogError(AppServer, "HwSetVehicleID - could not copy vehicleID");
delete[] destinationBuffer;
return Status::Failure;
}
if (!mVehicleID.IsNull())
{
delete[] mVehicleID.Value().data();
}
mVehicleID = MakeNullable(static_cast<CharSpan>(destinationString));
ChipLogDetail(AppServer, "VehicleID updated %.*s", static_cast<int>(mVehicleID.Value().size()), mVehicleID.Value().data());
MatterReportingAttributeChangeCallback(mEndpointId, EnergyEvse::Id, VehicleID::Id);
return Status::Success;
}
/**
* @brief Called by EVSE Hardware to indicate that it has finished its diagnostics test
*/
Status EnergyEvseDelegate::HwDiagnosticsComplete()
{
if (mSupplyState != SupplyStateEnum::kDisabledDiagnostics)
{
ChipLogError(AppServer, "Incorrect state to be completing diagnostics");
return Status::Failure;
}
/* Restore the SupplyState to Disabled (per spec) - client will need to
* re-enable charging or discharging to get out of this state */
SetSupplyState(SupplyStateEnum::kDisabled);
return Status::Success;
}
/* ---------------------------------------------------------------------------
* Functions below are private helper functions internal to the delegate
*/
/**
* @brief Main EVSE state machine
*
* This routine handles state transition events to determine behaviour
*
*
*/
Status EnergyEvseDelegate::HandleStateMachineEvent(EVSEStateMachineEvent event)
{
switch (event)
{
case EVSEStateMachineEvent::EVPluggedInEvent:
ChipLogDetail(AppServer, "EVSE: EV PluggedIn event");
return HandleEVPluggedInEvent();
break;
case EVSEStateMachineEvent::EVNotDetectedEvent:
ChipLogDetail(AppServer, "EVSE: EV NotDetected event");
return HandleEVNotDetectedEvent();
break;
case EVSEStateMachineEvent::EVNoDemandEvent:
ChipLogDetail(AppServer, "EVSE: EV NoDemand event");
return HandleEVNoDemandEvent();
break;
case EVSEStateMachineEvent::EVDemandEvent:
ChipLogDetail(AppServer, "EVSE: EV Demand event");
return HandleEVDemandEvent();
break;
case EVSEStateMachineEvent::ChargingEnabledEvent:
ChipLogDetail(AppServer, "EVSE: ChargingEnabled event");
return HandleChargingEnabledEvent();
break;
case EVSEStateMachineEvent::DischargingEnabledEvent:
ChipLogDetail(AppServer, "EVSE: DischargingEnabled event");
return HandleDischargingEnabledEvent();
break;
case EVSEStateMachineEvent::DisabledEvent:
ChipLogDetail(AppServer, "EVSE: Disabled event");
return HandleDisabledEvent();
break;
case EVSEStateMachineEvent::FaultRaised:
ChipLogDetail(AppServer, "EVSE: FaultRaised event");
return HandleFaultRaised();
break;
case EVSEStateMachineEvent::FaultCleared:
ChipLogDetail(AppServer, "EVSE: FaultCleared event");
return HandleFaultCleared();
break;
default:
return Status::Failure;
}
return Status::Success;
}
Status EnergyEvseDelegate::HandleEVPluggedInEvent()
{
/* check if we are already plugged in or not */
if (mState == StateEnum::kNotPluggedIn)
{
/* EV was not plugged in - start a new session */
// TODO get energy meter readings
mSession.StartSession(0, 0);
SendEVConnectedEvent();
/* Set the state to either PluggedInNoDemand or PluggedInDemand as indicated by mHwState */
SetState(mHwState);
}
// else we are already plugged in - ignore
return Status::Success;
}
Status EnergyEvseDelegate::HandleEVNotDetectedEvent()
{
if (mState == StateEnum::kPluggedInCharging || mState == StateEnum::kPluggedInDischarging)
{
/*
* EV was transferring current - unusual to get to this case without
* first having the state set to kPluggedInNoDemand or kPluggedInDemand
*/
SendEnergyTransferStoppedEvent(EnergyTransferStoppedReasonEnum::kOther);
}
SendEVNotDetectedEvent();
SetState(StateEnum::kNotPluggedIn);
return Status::Success;
}
Status EnergyEvseDelegate::HandleEVNoDemandEvent()
{
if (mState == StateEnum::kPluggedInCharging || mState == StateEnum::kPluggedInDischarging)
{
/*
* EV was transferring current - EV decided to stop
*/
mSession.RecalculateSessionDuration();
SendEnergyTransferStoppedEvent(EnergyTransferStoppedReasonEnum::kEVStopped);
}
/* We must still be plugged in to get here - so no need to check if we are plugged in! */
SetState(StateEnum::kPluggedInNoDemand);
return Status::Success;
}
Status EnergyEvseDelegate::HandleEVDemandEvent()
{
/* Check to see if the supply is enabled for charging / discharging*/
switch (mSupplyState)
{
case SupplyStateEnum::kChargingEnabled:
ComputeMaxChargeCurrentLimit();
SetState(StateEnum::kPluggedInCharging);
SendEnergyTransferStartedEvent();
break;
case SupplyStateEnum::kDischargingEnabled:
// TODO ComputeMaxDischargeCurrentLimit() - Needs to be implemented
SetState(StateEnum::kPluggedInDischarging);
SendEnergyTransferStartedEvent();
break;
case SupplyStateEnum::kDisabled:
case SupplyStateEnum::kDisabledError:
case SupplyStateEnum::kDisabledDiagnostics:
/* We must be plugged in, and the event is asking for demand
* but we can't charge or discharge now - leave it as kPluggedInDemand */
SetState(StateEnum::kPluggedInDemand);
break;
default:
break;
}
return Status::Success;
}
Status EnergyEvseDelegate::CheckFaultOrDiagnostic()
{
if (mFaultState != FaultStateEnum::kNoError)
{
ChipLogError(AppServer, "EVSE: Trying to handle command when fault is present");
return Status::Failure;
}
if (mSupplyState == SupplyStateEnum::kDisabledDiagnostics)
{
ChipLogError(AppServer, "EVSE: Trying to handle command when in diagnostics mode");
return Status::Failure;
}
return Status::Success;
}
Status EnergyEvseDelegate::HandleChargingEnabledEvent()
{
/* Check there is no Fault or Diagnostics condition */
Status status = CheckFaultOrDiagnostic();
if (status != Status::Success)
{
return status;
}
/* update SupplyState to say that charging is now enabled */
SetSupplyState(SupplyStateEnum::kChargingEnabled);
switch (mState)
{
case StateEnum::kNotPluggedIn:
case StateEnum::kPluggedInNoDemand:
break;
case StateEnum::kPluggedInDemand:
ComputeMaxChargeCurrentLimit();
SetState(StateEnum::kPluggedInCharging);
SendEnergyTransferStartedEvent();
break;
case StateEnum::kPluggedInCharging:
break;
case StateEnum::kPluggedInDischarging:
/* Switched from discharging to charging */
SendEnergyTransferStoppedEvent(EnergyTransferStoppedReasonEnum::kEVSEStopped);
ComputeMaxChargeCurrentLimit();
SetState(StateEnum::kPluggedInCharging);
SendEnergyTransferStartedEvent();
break;
default:
break;
}
ScheduleCheckOnEnabledTimeout();
return Status::Success;
}
Status EnergyEvseDelegate::HandleDischargingEnabledEvent()
{
/* Check there is no Fault or Diagnostics condition */
Status status = CheckFaultOrDiagnostic();
if (status != Status::Success)
{
return status;
}
/* update SupplyState to say that charging is now enabled */
SetSupplyState(SupplyStateEnum::kDischargingEnabled);
switch (mState)
{
case StateEnum::kNotPluggedIn:
case StateEnum::kPluggedInNoDemand:
break;
case StateEnum::kPluggedInDemand:
// TODO call ComputeMaxDischargeCurrentLimit()
SetState(StateEnum::kPluggedInDischarging);
SendEnergyTransferStartedEvent();
break;
case StateEnum::kPluggedInCharging:
/* Switched from charging to discharging */
SendEnergyTransferStoppedEvent(EnergyTransferStoppedReasonEnum::kEVSEStopped);
// TODO call ComputeMaxDischargeCurrentLimit()
SetState(StateEnum::kPluggedInDischarging);
SendEnergyTransferStartedEvent();
break;
case StateEnum::kPluggedInDischarging:
default:
break;
}
ScheduleCheckOnEnabledTimeout();
return Status::Success;
}
Status EnergyEvseDelegate::HandleDisabledEvent()
{
/* Check there is no Fault or Diagnostics condition */
Status status = CheckFaultOrDiagnostic();
if (status != Status::Success)
{
return status;
}
/* update SupplyState to say that charging is now enabled */
SetSupplyState(SupplyStateEnum::kDisabled);
switch (mState)
{
case StateEnum::kNotPluggedIn:
case StateEnum::kPluggedInNoDemand:
case StateEnum::kPluggedInDemand:
break;
case StateEnum::kPluggedInCharging:
case StateEnum::kPluggedInDischarging:
SendEnergyTransferStoppedEvent(EnergyTransferStoppedReasonEnum::kEVSEStopped);
SetState(mHwState);
break;
default:
break;
}
return Status::Success;
}
/**
* @brief This handles the new fault
*
* Note that if multiple faults happen and this is called repeatedly
* We only save the previous State and SupplyState if its the first raising
* of the fault, so we can restore the state back once all faults have cleared
)*/
Status EnergyEvseDelegate::HandleFaultRaised()
{
/* Save the current State and SupplyState so we can restore them if the fault clears */
if (mStateBeforeFault == StateEnum::kUnknownEnumValue)
{
/* No existing fault - save this value to restore it later if it clears */
mStateBeforeFault = mState;
}
if (mSupplyStateBeforeFault == SupplyStateEnum::kUnknownEnumValue)
{
/* No existing fault */
mSupplyStateBeforeFault = mSupplyState;
}
/* Update State & SupplyState */
SetState(StateEnum::kFault);
SetSupplyState(SupplyStateEnum::kDisabledError);
return Status::Success;
}
Status EnergyEvseDelegate::HandleFaultCleared()
{
/* Check that something strange hasn't happened */
if ((mStateBeforeFault == StateEnum::kUnknownEnumValue) || (mSupplyStateBeforeFault == SupplyStateEnum::kUnknownEnumValue))
{
ChipLogError(AppServer, "EVSE: Something wrong trying to clear fault");
return Status::Failure;
}
/* Restore the State and SupplyState back to old values once all the faults have cleared
* Changing the State should notify the application, so it can continue charging etc
*/
SetState(mStateBeforeFault);
SetSupplyState(mSupplyStateBeforeFault);
/* put back the sentinel to catch new faults if more are raised */
mStateBeforeFault = StateEnum::kUnknownEnumValue;
mSupplyStateBeforeFault = SupplyStateEnum::kUnknownEnumValue;
return Status::Success;
}
/**
* @brief Called to compute the safe charging current limit
*
* mActualChargingCurrentLimit is the minimum of:
* - MaxHardwareCurrentLimit (of the hardware)
* - CircuitCapacity (set by the electrician - less than the hardware)
* - CableAssemblyLimit (detected when the cable is inserted)
* - MaximumChargeCurrent (from charging command)
* - UserMaximumChargeCurrent (could dynamically change)
*
*/
Status EnergyEvseDelegate::ComputeMaxChargeCurrentLimit()
{
int64_t oldValue;
oldValue = mActualChargingCurrentLimit;
mActualChargingCurrentLimit = mMaxHardwareCurrentLimit;
mActualChargingCurrentLimit = min(mActualChargingCurrentLimit, mCircuitCapacity);
mActualChargingCurrentLimit = min(mActualChargingCurrentLimit, mCableAssemblyCurrentLimit);
mActualChargingCurrentLimit = min(mActualChargingCurrentLimit, mMaximumChargingCurrentLimitFromCommand);
mActualChargingCurrentLimit = min(mActualChargingCurrentLimit, mUserMaximumChargeCurrent);
/* Set the actual max charging current attribute */
mMaximumChargeCurrent = mActualChargingCurrentLimit;
if (oldValue != mMaximumChargeCurrent)
{
ChipLogDetail(AppServer, "MaximumChargeCurrent updated to %ld", static_cast<long>(mMaximumChargeCurrent));
MatterReportingAttributeChangeCallback(mEndpointId, EnergyEvse::Id, MaximumChargeCurrent::Id);
/* Call the EV Charger hardware current limit callback */
NotifyApplicationCurrentLimitChange(mMaximumChargeCurrent);
}
return Status::Success;
}
Status EnergyEvseDelegate::NotifyApplicationCurrentLimitChange(int64_t maximumChargeCurrent)
{
EVSECbInfo cbInfo;
cbInfo.type = EVSECallbackType::ChargeCurrentChanged;
cbInfo.ChargingCurrent.maximumChargeCurrent = maximumChargeCurrent;
if (mCallbacks.handler != nullptr)
{
mCallbacks.handler(&cbInfo, mCallbacks.arg);
}
return Status::Success;
}
Status EnergyEvseDelegate::NotifyApplicationStateChange()
{
EVSECbInfo cbInfo;
cbInfo.type = EVSECallbackType::StateChanged;
cbInfo.StateChange.state = mState;
cbInfo.StateChange.supplyState = mSupplyState;
if (mCallbacks.handler != nullptr)
{
mCallbacks.handler(&cbInfo, mCallbacks.arg);
}
return Status::Success;
}
Status EnergyEvseDelegate::GetEVSEEnergyMeterValue(ChargingDischargingType meterType, int64_t & aMeterValue)
{
EVSECbInfo cbInfo;
cbInfo.type = EVSECallbackType::EnergyMeterReadingRequested;
cbInfo.EnergyMeterReadingRequest.meterType = meterType;
cbInfo.EnergyMeterReadingRequest.energyMeterValuePtr = &aMeterValue;
if (mCallbacks.handler != nullptr)
{
mCallbacks.handler(&cbInfo, mCallbacks.arg);
}
return Status::Success;
}
Status EnergyEvseDelegate::SendEVConnectedEvent()
{
Events::EVConnected::Type event;
EventNumber eventNumber;
if (mSession.mSessionID.IsNull())
{
ChipLogError(AppServer, "SessionID is Null");
return Status::Failure;
}
event.sessionID = mSession.mSessionID.Value();
CHIP_ERROR err = LogEvent(event, mEndpointId, eventNumber);
if (CHIP_NO_ERROR != err)
{
ChipLogError(AppServer, "Unable to send notify event: %" CHIP_ERROR_FORMAT, err.Format());
return Status::Failure;
}
return Status::Success;
}
Status EnergyEvseDelegate::SendEVNotDetectedEvent()
{
Events::EVNotDetected::Type event;
EventNumber eventNumber;
if (mSession.mSessionID.IsNull())
{
ChipLogError(AppServer, "SessionID is Null");
return Status::Failure;
}
event.sessionID = mSession.mSessionID.Value();
event.state = mState;
event.sessionDuration = mSession.mSessionDuration.Value();
event.sessionEnergyCharged = mSession.mSessionEnergyCharged.Value();
event.sessionEnergyDischarged = MakeOptional(mSession.mSessionEnergyDischarged.Value());
CHIP_ERROR err = LogEvent(event, mEndpointId, eventNumber);
if (CHIP_NO_ERROR != err)
{
ChipLogError(AppServer, "Unable to send notify event: %" CHIP_ERROR_FORMAT, err.Format());
return Status::Failure;
}
return Status::Success;
}
Status EnergyEvseDelegate::SendEnergyTransferStartedEvent()
{
Events::EnergyTransferStarted::Type event;
EventNumber eventNumber;
if (mSession.mSessionID.IsNull())
{
ChipLogError(AppServer, "SessionID is Null");
return Status::Failure;
}
event.sessionID = mSession.mSessionID.Value();
event.state = mState;
/**
* A positive value indicates the EV has been enabled for charging and the value is
* taken directly from the MaximumChargeCurrent attribute.
* A negative value indicates that the EV has been enabled for discharging and the value can be taken
* from the MaximumDischargeCurrent attribute with its sign inverted.
*/
if (mState == StateEnum::kPluggedInCharging)
{
/* Sample the energy meter for charging */
GetEVSEEnergyMeterValue(ChargingDischargingType::kCharging, mMeterValueAtEnergyTransferStart);