forked from project-chip/connectedhomeip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDeviceEnergyManagementDelegateImpl.cpp
996 lines (846 loc) · 32.9 KB
/
DeviceEnergyManagementDelegateImpl.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
/*
*
* 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 "DeviceEnergyManagementDelegateImpl.h"
#include "DEMManufacturerDelegate.h"
#include "EnergyTimeUtils.h"
#include <app/EventLogging.h>
#include <protocols/interaction_model/StatusCode.h>
using namespace chip;
using namespace chip::app;
using namespace chip::app::Clusters;
using namespace chip::app::Clusters::DeviceEnergyManagement;
using namespace chip::app::Clusters::DeviceEnergyManagement::Attributes;
using chip::Protocols::InteractionModel::Status;
using chip::Optional;
using CostsList = DataModel::List<const Structs::CostStruct::Type>;
DeviceEnergyManagementDelegate::DeviceEnergyManagementDelegate() :
mpDEMManufacturerDelegate(nullptr), mEsaType(ESATypeEnum::kEvse), mEsaCanGenerate(false), mEsaState(ESAStateEnum::kOffline),
mAbsMinPowerMw(0), mAbsMaxPowerMw(0), mOptOutState(OptOutStateEnum::kNoOptOut), mPowerAdjustmentInProgress(false),
mPowerAdjustmentStartTimeUtc(0), mPauseRequestInProgress(false)
{}
void DeviceEnergyManagementDelegate::SetDeviceEnergyManagementInstance(DeviceEnergyManagement::Instance & instance)
{
mpDEMInstance = &instance;
}
uint32_t DeviceEnergyManagementDelegate::HasFeature(Feature feature) const
{
bool hasFeature = false;
if (mpDEMInstance != nullptr)
{
hasFeature = mpDEMInstance->HasFeature(feature);
}
return hasFeature;
}
void DeviceEnergyManagementDelegate::SetDEMManufacturerDelegate(
DEMManufacturerDelegate & deviceEnergyManagementManufacturerDelegate)
{
mpDEMManufacturerDelegate = &deviceEnergyManagementManufacturerDelegate;
}
/**
* @brief Delegate handler for PowerAdjustRequest
*
* Note: checking of the validity of the PowerAdjustRequest has been done by the lower layer
*
* This function needs to notify the appliance that it should apply a new power setting.
* It should:
* 1) notify the appliance - if the appliance hardware cannot be adjusted, then return Failure
* 2) start a timer (or restart the existing PowerAdjust timer) for duration seconds
* 3) generate a PowerAdjustStart event (if there is not an existing PowerAdjustRequest running)
* 4) if appropriate, update the forecast with the new expected end time
*
* and when the timer expires:
* 5) notify the appliance's that it can resume its intended power setting (or go idle)
* 6) generate a PowerAdjustEnd event with cause NormalCompletion
* 7) if necessary, update the forecast with new expected end time
*/
Status DeviceEnergyManagementDelegate::PowerAdjustRequest(const int64_t powerMw, const uint32_t durationS,
AdjustmentCauseEnum cause)
{
bool generateEvent = false;
// If a timer is running, cancel it so we can start it with the new duration
if (mPowerAdjustmentInProgress)
{
DeviceLayer::SystemLayer().CancelTimer(PowerAdjustTimerExpiry, this);
}
else
{
// Going to start a new power adjustment so will need to generate an event
generateEvent = true;
// Record when this PowerAdjustment starts. Note if we do not set this value if a PowerAdjustment is in progress
CHIP_ERROR err = GetEpochTS(mPowerAdjustmentStartTimeUtc);
if (err != CHIP_NO_ERROR)
{
ChipLogError(AppServer, "Unable to get time: %" CHIP_ERROR_FORMAT, err.Format());
return Status::Failure;
}
}
// Update the forecast with the new expected end time
if (mpDEMManufacturerDelegate != nullptr)
{
CHIP_ERROR err = mpDEMManufacturerDelegate->HandleDeviceEnergyManagementPowerAdjustRequest(powerMw, durationS, cause);
if (err != CHIP_NO_ERROR)
{
return Status::Failure;
}
}
SetESAState(ESAStateEnum::kPowerAdjustActive);
// mPowerAdjustCapabilityStruct is guaranteed to have a value as validated in Instance::HandlePowerAdjustRequest.
// If it did not have a value, this method would not have been called.
switch (cause)
{
case AdjustmentCauseEnum::kLocalOptimization:
mPowerAdjustCapabilityStruct.Value().cause = PowerAdjustReasonEnum::kLocalOptimizationAdjustment;
break;
case AdjustmentCauseEnum::kGridOptimization:
mPowerAdjustCapabilityStruct.Value().cause = PowerAdjustReasonEnum::kGridOptimizationAdjustment;
break;
default:
HandlePowerAdjustRequestFailure();
return Status::Failure;
}
// Remember we have a timer running so we don't generate a PowerAdjustStart event should another request come
// in before this timer expires
mPowerAdjustmentInProgress = true;
CHIP_ERROR err = DeviceLayer::SystemLayer().StartTimer(System::Clock::Seconds32(durationS), PowerAdjustTimerExpiry, this);
if (err != CHIP_NO_ERROR)
{
// TODO: Note: should the PowerAdjust just initiated be cancelled because an Event could not be logged?
ChipLogError(AppServer, "Unable to start a PowerAdjustStart timer: %" CHIP_ERROR_FORMAT, err.Format());
HandlePowerAdjustRequestFailure();
return Status::Failure;
}
if (generateEvent)
{
Events::PowerAdjustStart::Type event;
EventNumber eventNumber;
err = LogEvent(event, mEndpointId, eventNumber);
if (CHIP_NO_ERROR != err)
{
// TODO: Note: should the PowerAdjust just initiated be cancelled because an Event could not be logged?
ChipLogError(AppServer, "Unable to generate PowerAdjustStart event: %" CHIP_ERROR_FORMAT, err.Format());
HandlePowerAdjustRequestFailure();
return Status::Failure;
}
}
return Status::Success;
}
/**
* @brief Handle a PowerAdjustRequest failing
*
* Cleans up the PowerAdjust state should the request fail
*/
void DeviceEnergyManagementDelegate::HandlePowerAdjustRequestFailure()
{
DeviceLayer::SystemLayer().CancelTimer(PowerAdjustTimerExpiry, this);
SetESAState(ESAStateEnum::kOnline);
mPowerAdjustmentInProgress = false;
mPowerAdjustCapabilityStruct.Value().cause = PowerAdjustReasonEnum::kNoAdjustment;
// TODO
// Should we inform the mpDEMManufacturerDelegate that PowerAdjustRequest has failed?
}
/**
* @brief Timer for handling the PowerAdjustRequest
*
* This static function calls the non-static HandlePowerAdjustTimerExpiry method.
*/
void DeviceEnergyManagementDelegate::PowerAdjustTimerExpiry(System::Layer * systemLayer, void * delegate)
{
DeviceEnergyManagementDelegate * dg = reinterpret_cast<DeviceEnergyManagementDelegate *>(delegate);
dg->HandlePowerAdjustTimerExpiry();
}
/**
* @brief Timer for handling the completion of a PowerAdjustRequest
*
* When the timer expires:
* 1) notify the appliance's that it can resume its intended power setting (or go idle)
* 2) generate a PowerAdjustEnd event with cause NormalCompletion
* 3) if necessary, update the forecast with new expected end time
*/
void DeviceEnergyManagementDelegate::HandlePowerAdjustTimerExpiry()
{
ChipLogError(AppServer, "DeviceEnergyManagementDelegate::HandlePowerAdjustTimerExpiry");
// The PowerAdjustment is no longer in progress
mPowerAdjustmentInProgress = false;
SetESAState(ESAStateEnum::kOnline);
mPowerAdjustCapabilityStruct.Value().cause = PowerAdjustReasonEnum::kNoAdjustment;
// Generate a PowerAdjustEnd event
GeneratePowerAdjustEndEvent(CauseEnum::kNormalCompletion);
// Update the forecast with new expected end time
if (mpDEMManufacturerDelegate != nullptr)
{
mpDEMManufacturerDelegate->HandleDeviceEnergyManagementPowerAdjustCompletion();
}
}
/**
* @brief Delegate handler for CancelPowerAdjustRequest
*
* Note: checking of the validity of the CancelPowerAdjustRequest has been done by the lower layer
*
* This function needs to notify the appliance that it should resume its intended power setting (or go idle).
*
* It should:
* 1) notify the appliance's that it can resume its intended power setting (or go idle)
* 2) generate a PowerAdjustEnd event with cause code Cancelled
* 3) if necessary, update the forecast with new expected end time
*/
Status DeviceEnergyManagementDelegate::CancelPowerAdjustRequest()
{
Status status = Status::Success;
CHIP_ERROR err = CancelPowerAdjustRequestAndGenerateEvent(DeviceEnergyManagement::CauseEnum::kCancelled);
if (CHIP_NO_ERROR != err)
{
status = Status::Failure;
}
return status;
}
/**
* @brief Handles the cancelation of a PowerAdjust operation
*
* This function needs to notify the appliance that it should resume its intended power setting (or go idle).
*
* It should:
* 1) notify the appliance's that it can resume its intended power setting (or go idle)
* 2) generate a PowerAdjustEnd event with cause code Cancelled
* 3) if necessary, update the forecast with new expected end time
*/
CHIP_ERROR DeviceEnergyManagementDelegate::CancelPowerAdjustRequestAndGenerateEvent(CauseEnum cause)
{
DeviceLayer::SystemLayer().CancelTimer(PowerAdjustTimerExpiry, this);
SetESAState(ESAStateEnum::kOnline);
mPowerAdjustmentInProgress = false;
mPowerAdjustCapabilityStruct.Value().cause = PowerAdjustReasonEnum::kNoAdjustment;
CHIP_ERROR err = GeneratePowerAdjustEndEvent(cause);
// Notify the appliance's that it can resume its intended power setting (or go idle)
if (mpDEMManufacturerDelegate != nullptr)
{
// It is expected the mpDEMManufacturerDelegate will update the forecast with new expected end time
// as a consequence of the cancel request.
err = mpDEMManufacturerDelegate->HandleDeviceEnergyManagementCancelPowerAdjustRequest(cause);
}
return err;
}
/**
* @brief Generate a PowerAdjustEvent
*
*/
CHIP_ERROR DeviceEnergyManagementDelegate::GeneratePowerAdjustEndEvent(CauseEnum cause)
{
Events::PowerAdjustEnd::Type event;
EventNumber eventNumber;
event.cause = cause;
uint32_t timeNowUtc;
CHIP_ERROR err = GetEpochTS(timeNowUtc);
if (err == CHIP_NO_ERROR)
{
event.duration = timeNowUtc - mPowerAdjustmentStartTimeUtc;
}
else
{
ChipLogError(AppServer, "Unable to get time: %" CHIP_ERROR_FORMAT, err.Format());
return err;
}
if (mpDEMManufacturerDelegate != nullptr)
{
event.energyUse = mpDEMManufacturerDelegate->GetApproxEnergyDuringSession();
}
else
{
event.energyUse = 0;
}
err = LogEvent(event, mEndpointId, eventNumber);
if (CHIP_NO_ERROR != err)
{
ChipLogError(AppServer, "Unable to generate PowerAdjustEnd event: %" CHIP_ERROR_FORMAT, err.Format());
return err;
}
return err;
}
/**
* @brief Delegate handler for StartTimeAdjustRequest
*
* Note: checking of the validity of the StartTimeAdjustRequest has been done by the lower layer
*
* This function needs to notify the appliance that the forecast has been updated by a client.
*
* It should:
* 1) update the forecast attribute with the revised start time
* 2) send a callback notification to the appliance so it can refresh its internal schedule
*/
Status DeviceEnergyManagementDelegate::StartTimeAdjustRequest(const uint32_t requestedStartTimeUtc, AdjustmentCauseEnum cause)
{
if (mForecast.IsNull())
{
return Status::Failure;
}
switch (cause)
{
case AdjustmentCauseEnum::kLocalOptimization:
mForecast.Value().forecastUpdateReason = ForecastUpdateReasonEnum::kLocalOptimization;
break;
case AdjustmentCauseEnum::kGridOptimization:
mForecast.Value().forecastUpdateReason = ForecastUpdateReasonEnum::kGridOptimization;
break;
default:
ChipLogDetail(AppServer, "Bad cause %d", to_underlying(cause));
return Status::Failure;
break;
}
mForecast.Value().forecastID++;
uint32_t durationS = mForecast.Value().endTime - mForecast.Value().startTime; // the current entire forecast duration
// Save the start and end time in case there is an issue with the mpDEMManufacturerDelegate handling this
// startTimeAdjustment request
uint32_t savedStartTime = mForecast.Value().startTime;
uint32_t savedEndTime = mForecast.Value().endTime;
/* Modify start time and end time */
mForecast.Value().startTime = requestedStartTimeUtc;
mForecast.Value().endTime = requestedStartTimeUtc + durationS;
if (mpDEMManufacturerDelegate != nullptr)
{
CHIP_ERROR err =
mpDEMManufacturerDelegate->HandleDeviceEnergyManagementStartTimeAdjustRequest(requestedStartTimeUtc, cause);
if (err != CHIP_NO_ERROR)
{
// Reset state
mForecast.Value().forecastUpdateReason = ForecastUpdateReasonEnum::kInternalOptimization;
mForecast.Value().startTime = savedStartTime;
mForecast.Value().endTime = savedEndTime;
return Status::Failure;
}
}
return Status::Success;
}
/**
* @brief Delegate handler for Pause Request
*
* Note: checking of the validity of the Pause Request has been done by the lower layer
*
* This function needs to notify the appliance that it should now pause.
* It should:
* 1) pause the appliance - if the appliance hardware cannot be paused, then return Failure
* 2) start a timer for duration seconds
* 3) generate a Paused event
* 4) update the forecast with the new expected end time
*
* and when the timer expires:
* 5) restore the appliance's operational state
* 6) generate a Resumed event
* 7) if necessary, update the forecast with new expected end time
*/
Status DeviceEnergyManagementDelegate::PauseRequest(const uint32_t durationS, AdjustmentCauseEnum cause)
{
bool generateEvent = false;
// If a timer is running, cancel it so we can start it with the new duration
if (mPauseRequestInProgress)
{
DeviceLayer::SystemLayer().CancelTimer(PauseRequestTimerExpiry, this);
}
else
{
generateEvent = true;
// Remember we have a timer running so we don't generate a Paused event should another request come
// in before this timer expires
mPauseRequestInProgress = true;
}
CHIP_ERROR err = DeviceLayer::SystemLayer().StartTimer(System::Clock::Seconds32(durationS), PauseRequestTimerExpiry, this);
if (err != CHIP_NO_ERROR)
{
HandlePauseRequestFailure();
return Status::Failure;
}
// Pause the appliance
if (mpDEMManufacturerDelegate != nullptr)
{
// It is expected that the mpDEMManufacturerDelegate will update the forecast with the new expected end time
err = mpDEMManufacturerDelegate->HandleDeviceEnergyManagementPauseRequest(durationS, cause);
if (err != CHIP_NO_ERROR)
{
HandlePauseRequestFailure();
return Status::Failure;
}
}
if (generateEvent)
{
Events::Paused::Type event;
EventNumber eventNumber;
err = LogEvent(event, mEndpointId, eventNumber);
if (CHIP_NO_ERROR != err)
{
ChipLogError(AppServer, "Unable to generate Paused event: %" CHIP_ERROR_FORMAT, err.Format());
HandlePauseRequestFailure();
return Status::Failure;
}
}
SetESAState(ESAStateEnum::kPaused);
// Update the forecaseUpdateReason based on the AdjustmentCause
if (cause == AdjustmentCauseEnum::kLocalOptimization)
{
mForecast.Value().forecastUpdateReason = ForecastUpdateReasonEnum::kLocalOptimization;
}
else if (cause == AdjustmentCauseEnum::kGridOptimization)
{
mForecast.Value().forecastUpdateReason = ForecastUpdateReasonEnum::kGridOptimization;
}
return Status::Success;
}
/**
* @brief Handle a PauseRequest failing
*
* Cleans up the state should the PauseRequest fail
*/
void DeviceEnergyManagementDelegate::HandlePauseRequestFailure()
{
DeviceLayer::SystemLayer().CancelTimer(PowerAdjustTimerExpiry, this);
SetESAState(ESAStateEnum::kOnline);
mPauseRequestInProgress = false;
// TODO
// Should we inform the mpDEMManufacturerDelegate that PauseRequest has failed?
}
/**
* @brief Timer for handling the PauseRequest
*
* This static function calls the non-static HandlePauseRequestTimerExpiry method.
*/
void DeviceEnergyManagementDelegate::PauseRequestTimerExpiry(System::Layer * systemLayer, void * delegate)
{
DeviceEnergyManagementDelegate * dg = reinterpret_cast<DeviceEnergyManagementDelegate *>(delegate);
dg->HandlePauseRequestTimerExpiry();
}
/**
* @brief Timer for handling the completion of a PauseRequest
*
* When the timer expires:
* 1) restore the appliance's operational state
* 2) generate a Resumed event
* 3) if necessary, update the forecast with new expected end time
*/
void DeviceEnergyManagementDelegate::HandlePauseRequestTimerExpiry()
{
// The PauseRequestment is no longer in progress
mPauseRequestInProgress = false;
SetESAState(ESAStateEnum::kOnline);
// Generate a Resumed event
GenerateResumedEvent(CauseEnum::kNormalCompletion);
// It is expected the mpDEMManufacturerDelegate will update the forecast with new expected end time
if (mpDEMManufacturerDelegate != nullptr)
{
mpDEMManufacturerDelegate->HandleDeviceEnergyManagementPauseCompletion();
}
}
/**
* @brief Handles the cancelation of a pause operation
*
* This function needs to notify the appliance that it should resume its intended power setting (or go idle).
*
* It should:
* 1) notify the appliance's that it can resume its intended power setting (or go idle)
* 2) generate a PowerAdjustEnd event with cause code Cancelled
* 3) if necessary, update the forecast with new expected end time
*/
CHIP_ERROR DeviceEnergyManagementDelegate::CancelPauseRequestAndGenerateEvent(CauseEnum cause)
{
mPauseRequestInProgress = false;
SetESAState(ESAStateEnum::kOnline);
DeviceLayer::SystemLayer().CancelTimer(PauseRequestTimerExpiry, this);
CHIP_ERROR err = GenerateResumedEvent(cause);
CHIP_ERROR err2 = CHIP_NO_ERROR;
// Notify the appliance's that it can resume its intended power setting (or go idle)
if (mpDEMManufacturerDelegate != nullptr)
{
// It is expected that the mpDEMManufacturerDelegate will update the forecast with new expected end time
err2 = mpDEMManufacturerDelegate->HandleDeviceEnergyManagementCancelPauseRequest(cause);
}
// Need to pick one of the error codes two return...
if (err == CHIP_NO_ERROR && err2 == CHIP_NO_ERROR)
{
return CHIP_NO_ERROR;
}
if (err2 != CHIP_NO_ERROR)
{
return err2;
}
return err;
}
/**
* @brief Generate a Resumed event
*
*/
CHIP_ERROR DeviceEnergyManagementDelegate::GenerateResumedEvent(CauseEnum cause)
{
Events::Resumed::Type event;
EventNumber eventNumber;
event.cause = cause;
CHIP_ERROR err = LogEvent(event, mEndpointId, eventNumber);
if (CHIP_NO_ERROR != err)
{
ChipLogError(AppServer, "Unable to generate Resumed event: %" CHIP_ERROR_FORMAT, err.Format());
}
return err;
}
/**
* @brief Delegate handler for ResumeRequest
*
* Note: checking of the validity of the ResumeRequest has been done by the lower layer
*
* This function needs to notify the appliance that it should now resume operation
*
* It should:
* 1) restore the appliance's operational state
* 2) generate a Resumed event
* 3) update the forecast with new expected end time (given that the pause duration was shorter than originally requested)
*
*/
Status DeviceEnergyManagementDelegate::ResumeRequest()
{
Status status = Status::Failure;
if (mPauseRequestInProgress)
{
CHIP_ERROR err = CancelPauseRequestAndGenerateEvent(CauseEnum::kCancelled);
if (err == CHIP_NO_ERROR)
{
status = Status::Success;
}
}
return status;
}
/**
* @brief Delegate handler for ModifyForecastRequest
*
* Note: Only basic checking of the validity of the ModifyForecastRequest has been
* done by the lower layer. This is a more complex use-case and requires higher-level
* work by the delegate.
*
* It should:
* 1) determine if the new forecast adjustments are acceptable to the appliance
* - if not return Failure. For example, if it may cause the home to be too hot
* or too cold, or a battery to be insufficiently charged
* 2) if the slot adjustments are acceptable, then update the forecast
* 3) notify the appliance to follow the revised schedule
*/
Status DeviceEnergyManagementDelegate::ModifyForecastRequest(
const uint32_t forecastID, const DataModel::DecodableList<Structs::SlotAdjustmentStruct::DecodableType> & slotAdjustments,
AdjustmentCauseEnum cause)
{
Status status = Status::Success;
if (mForecast.IsNull())
{
status = Status::Failure;
}
else if (mForecast.Value().forecastID != forecastID)
{
status = Status::Failure;
}
else if (mpDEMManufacturerDelegate != nullptr)
{
// Determine if the new forecast adjustments are acceptable to the appliance
CHIP_ERROR err = mpDEMManufacturerDelegate->HandleModifyForecastRequest(forecastID, slotAdjustments, cause);
if (err != CHIP_NO_ERROR)
{
status = Status::Failure;
}
}
if (status == Status::Success)
{
switch (cause)
{
case AdjustmentCauseEnum::kLocalOptimization:
mForecast.Value().forecastUpdateReason = ForecastUpdateReasonEnum::kLocalOptimization;
break;
case AdjustmentCauseEnum::kGridOptimization:
mForecast.Value().forecastUpdateReason = ForecastUpdateReasonEnum::kGridOptimization;
break;
default:
// Already checked in chip::app::Clusters::DeviceEnergyManagement::Instance::HandleModifyForecastRequest
break;
}
mForecast.Value().forecastID++;
}
return status;
}
/**
* @brief Delegate handler for RequestConstraintBasedForecast
*
* Note: Only basic checking of the validity of the RequestConstraintBasedForecast has been
* done by the lower layer. This is a more complex use-case and requires higher-level
* work by the delegate.
*
* It should:
* 1) perform a higher level optimization (e.g. using tariff information, and user preferences)
* 2) if a solution can be found, then update the forecast, else return Failure
* 3) notify the appliance to follow the revised schedule
*/
Status DeviceEnergyManagementDelegate::RequestConstraintBasedForecast(
const DataModel::DecodableList<Structs::ConstraintsStruct::DecodableType> & constraints, AdjustmentCauseEnum cause)
{
Status status = Status::Success;
if (mForecast.IsNull())
{
status = Status::Failure;
}
else if (mpDEMManufacturerDelegate != nullptr)
{
// Determine if the new forecast adjustments are acceptable to the appliance
CHIP_ERROR err = mpDEMManufacturerDelegate->RequestConstraintBasedForecast(constraints, cause);
if (err != CHIP_NO_ERROR)
{
status = Status::Failure;
}
}
if (status == Status::Success)
{
switch (cause)
{
case AdjustmentCauseEnum::kLocalOptimization:
mForecast.Value().forecastUpdateReason = ForecastUpdateReasonEnum::kLocalOptimization;
break;
case AdjustmentCauseEnum::kGridOptimization:
mForecast.Value().forecastUpdateReason = ForecastUpdateReasonEnum::kGridOptimization;
break;
default:
// Already checked in chip::app::Clusters::DeviceEnergyManagement::Instance::HandleModifyForecastRequest
break;
}
mForecast.Value().forecastID++;
status = Status::Success;
}
return status;
}
/**
* @brief Delegate handler for CancelRequest
*
* Note: This is a more complex use-case and requires higher-level work by the delegate.
*
* It SHALL:
* 1) Check if the forecastUpdateReason was already InternalOptimization (and reject the command)
* 2) Update its forecast (based on its optimization strategy) ignoring previous requests
* 3) Update its Forecast attribute to match its new intended operation, and update the
* ForecastStruct.ForecastUpdateReason to `Internal Optimization`.
*/
Status DeviceEnergyManagementDelegate::CancelRequest()
{
Status status = Status::Success;
mForecast.Value().forecastUpdateReason = ForecastUpdateReasonEnum::kInternalOptimization;
/* It is expected the mpDEMManufacturerDelegate will cancel the effects of any previous adjustment
* request commands, and re-evaluate its forecast for intended operation ignoring those previous
* requests.
*/
if (mpDEMManufacturerDelegate != nullptr)
{
CHIP_ERROR error = mpDEMManufacturerDelegate->HandleDeviceEnergyManagementCancelRequest();
if (error != CHIP_NO_ERROR)
{
status = Status::Failure;
}
}
return status;
}
// ------------------------------------------------------------------
// Get attribute methods
ESATypeEnum DeviceEnergyManagementDelegate::GetESAType()
{
return mEsaType;
}
bool DeviceEnergyManagementDelegate::GetESACanGenerate()
{
return mEsaCanGenerate;
}
ESAStateEnum DeviceEnergyManagementDelegate::GetESAState()
{
return mEsaState;
}
int64_t DeviceEnergyManagementDelegate::GetAbsMinPower()
{
return mAbsMinPowerMw;
}
int64_t DeviceEnergyManagementDelegate::GetAbsMaxPower()
{
return mAbsMaxPowerMw;
}
const DataModel::Nullable<Structs::PowerAdjustCapabilityStruct::Type> &
DeviceEnergyManagementDelegate::GetPowerAdjustmentCapability()
{
return mPowerAdjustCapabilityStruct;
}
const DataModel::Nullable<Structs::ForecastStruct::Type> & DeviceEnergyManagementDelegate::GetForecast()
{
ChipLogDetail(Zcl, "DeviceEnergyManagementDelegate::GetForecast");
return mForecast;
}
OptOutStateEnum DeviceEnergyManagementDelegate::GetOptOutState()
{
ChipLogDetail(AppServer, "mOptOutState %d", static_cast<int>(mOptOutState));
return mOptOutState;
}
// ------------------------------------------------------------------
// Set attribute methods
CHIP_ERROR DeviceEnergyManagementDelegate::SetESAType(ESATypeEnum newValue)
{
ESATypeEnum oldValue = mEsaType;
if (newValue >= ESATypeEnum::kUnknownEnumValue)
{
return CHIP_IM_GLOBAL_STATUS(ConstraintError);
}
mEsaType = newValue;
if (oldValue != newValue)
{
ChipLogDetail(AppServer, "mEsaType updated to %d", static_cast<int>(mEsaType));
MatterReportingAttributeChangeCallback(mEndpointId, DeviceEnergyManagement::Id, ESAType::Id);
}
return CHIP_NO_ERROR;
}
CHIP_ERROR DeviceEnergyManagementDelegate::SetESACanGenerate(bool newValue)
{
bool oldValue = mEsaCanGenerate;
mEsaCanGenerate = newValue;
if (oldValue != newValue)
{
ChipLogDetail(AppServer, "mEsaCanGenerate updated to %d", static_cast<int>(mEsaCanGenerate));
MatterReportingAttributeChangeCallback(mEndpointId, DeviceEnergyManagement::Id, ESACanGenerate::Id);
}
return CHIP_NO_ERROR;
}
CHIP_ERROR DeviceEnergyManagementDelegate::SetESAState(ESAStateEnum newValue)
{
ESAStateEnum oldValue = mEsaState;
if (newValue >= ESAStateEnum::kUnknownEnumValue)
{
return CHIP_IM_GLOBAL_STATUS(ConstraintError);
}
mEsaState = newValue;
if (oldValue != newValue)
{
ChipLogDetail(AppServer, "mEsaState updated to %d", static_cast<int>(mEsaState));
MatterReportingAttributeChangeCallback(mEndpointId, DeviceEnergyManagement::Id, ESAState::Id);
}
return CHIP_NO_ERROR;
}
CHIP_ERROR DeviceEnergyManagementDelegate::SetAbsMinPower(int64_t newValueMw)
{
int64_t oldValueMw = mAbsMinPowerMw;
mAbsMinPowerMw = newValueMw;
if (oldValueMw != newValueMw)
{
ChipLogDetail(AppServer, "mAbsMinPower updated to %d", static_cast<int>(mAbsMinPowerMw));
MatterReportingAttributeChangeCallback(mEndpointId, DeviceEnergyManagement::Id, AbsMinPower::Id);
}
return CHIP_NO_ERROR;
}
CHIP_ERROR DeviceEnergyManagementDelegate::SetAbsMaxPower(int64_t newValueMw)
{
int64_t oldValueMw = mAbsMaxPowerMw;
mAbsMaxPowerMw = newValueMw;
if (oldValueMw != newValueMw)
{
ChipLogDetail(AppServer, "mAbsMaxPower updated to %d", static_cast<int>(mAbsMaxPowerMw));
MatterReportingAttributeChangeCallback(mEndpointId, DeviceEnergyManagement::Id, AbsMaxPower::Id);
}
return CHIP_NO_ERROR;
}
CHIP_ERROR
DeviceEnergyManagementDelegate::SetPowerAdjustmentCapability(
const DataModel::Nullable<Structs::PowerAdjustCapabilityStruct::Type> & powerAdjustCapabilityStruct)
{
assertChipStackLockedByCurrentThread();
mPowerAdjustCapabilityStruct = powerAdjustCapabilityStruct;
MatterReportingAttributeChangeCallback(mEndpointId, DeviceEnergyManagement::Id, PowerAdjustmentCapability::Id);
return CHIP_NO_ERROR;
}
CHIP_ERROR DeviceEnergyManagementDelegate::SetForecast(const DataModel::Nullable<Structs::ForecastStruct::Type> & forecast)
{
assertChipStackLockedByCurrentThread();
// TODO see Issue #31147
mForecast = forecast;
MatterReportingAttributeChangeCallback(mEndpointId, DeviceEnergyManagement::Id, Forecast::Id);
return CHIP_NO_ERROR;
}
CHIP_ERROR DeviceEnergyManagementDelegate::SetOptOutState(OptOutStateEnum newValue)
{
CHIP_ERROR err = CHIP_NO_ERROR;
OptOutStateEnum oldValue = mOptOutState;
// The OptOutState is cumulative
if ((oldValue == OptOutStateEnum::kGridOptOut && newValue == OptOutStateEnum::kLocalOptOut) ||
(oldValue == OptOutStateEnum::kLocalOptOut && newValue == OptOutStateEnum::kGridOptOut))
{
mOptOutState = OptOutStateEnum::kOptOut;
}
else
{
mOptOutState = newValue;
}
if (oldValue != newValue)
{
ChipLogDetail(AppServer, "mOptOutState updated to %d mPowerAdjustmentInProgress %d", to_underlying(mOptOutState),
mPowerAdjustmentInProgress);
MatterReportingAttributeChangeCallback(mEndpointId, DeviceEnergyManagement::Id, OptOutState::Id);
}
// Cancel any outstanding PowerAdjustment if necessary
if (mPowerAdjustmentInProgress)
{
if ((newValue == OptOutStateEnum::kLocalOptOut &&
mPowerAdjustCapabilityStruct.Value().cause == PowerAdjustReasonEnum::kLocalOptimizationAdjustment) ||
(newValue == OptOutStateEnum::kGridOptOut &&
mPowerAdjustCapabilityStruct.Value().cause == PowerAdjustReasonEnum::kGridOptimizationAdjustment) ||
newValue == OptOutStateEnum::kOptOut)
{
err = CancelPowerAdjustRequestAndGenerateEvent(DeviceEnergyManagement::CauseEnum::kUserOptOut);
}
}
// Cancel any outstanding PauseRequest if necessary
if (mPauseRequestInProgress)
{
// Cancel any outstanding PauseRequest
if ((newValue == OptOutStateEnum::kLocalOptOut &&
mForecast.Value().forecastUpdateReason == ForecastUpdateReasonEnum::kLocalOptimization) ||
(newValue == OptOutStateEnum::kGridOptOut &&
mForecast.Value().forecastUpdateReason == ForecastUpdateReasonEnum::kGridOptimization) ||
newValue == OptOutStateEnum::kOptOut)
{
err = CancelPauseRequestAndGenerateEvent(DeviceEnergyManagement::CauseEnum::kUserOptOut);
}
}
if (!mForecast.IsNull())
{
switch (mForecast.Value().forecastUpdateReason)
{
case ForecastUpdateReasonEnum::kInternalOptimization:
// We don't need to redo a forecast since its internal already
break;
case ForecastUpdateReasonEnum::kLocalOptimization:
if ((mOptOutState == OptOutStateEnum::kOptOut) || (mOptOutState == OptOutStateEnum::kLocalOptOut))
{
mForecast.Value().forecastUpdateReason = ForecastUpdateReasonEnum::kInternalOptimization;
// Generate a new forecast with Internal Optimization
// TODO
}
break;
case ForecastUpdateReasonEnum::kGridOptimization:
if ((mOptOutState == OptOutStateEnum::kOptOut) || (mOptOutState == OptOutStateEnum::kGridOptOut))
{
mForecast.Value().forecastUpdateReason = ForecastUpdateReasonEnum::kInternalOptimization;
// Generate a new forecast with Internal Optimization
// TODO
}
break;
default:
ChipLogDetail(AppServer, "Bad ForecastUpdateReasonEnum value of %d",
static_cast<int>(mForecast.Value().forecastUpdateReason));
return CHIP_ERROR_BAD_REQUEST;
break;
}
}
return err;
}