forked from project-chip/connectedhomeip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWhmDelegateImpl.cpp
520 lines (421 loc) · 18.8 KB
/
WhmDelegateImpl.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
/*
*
* Copyright (c) 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 <app/clusters/water-heater-management-server/water-heater-management-server.h>
#include <WhmDelegate.h>
#include <WhmManufacturer.h>
#include <water-heater-mode.h>
#include <algorithm>
using namespace chip;
using namespace chip::app;
using namespace chip::app::Clusters;
using namespace chip::app::Clusters::WaterHeaterManagement;
using Protocols::InteractionModel::Status;
WaterHeaterManagementDelegate::WaterHeaterManagementDelegate(EndpointId clustersEndpoint) :
mpWhmInstance(nullptr), mpWhmManufacturer(nullptr), mTargetWaterTemperature(0), mWaterTemperature(0), mColdWaterTemperature(0),
mBoostTargetTemperatureReached(false), mTankVolume(0), mEstimatedHeatRequired(0), mTankPercentage(0),
mBoostState(BoostStateEnum::kInactive)
{}
void WaterHeaterManagementDelegate::SetWaterHeaterManagementInstance(WaterHeaterManagement::Instance & instance)
{
mpWhmInstance = &instance;
}
void WaterHeaterManagementDelegate::SetWhmManufacturer(WhmManufacturer & whmManufacturer)
{
mpWhmManufacturer = &whmManufacturer;
}
/*********************************************************************************
*
* Methods implementing the WaterHeaterManagement::Delegate interace
*
*********************************************************************************/
BitMask<WaterHeaterHeatSourceBitmap> WaterHeaterManagementDelegate::GetHeaterTypes()
{
return mHeaterTypes;
}
BitMask<WaterHeaterHeatSourceBitmap> WaterHeaterManagementDelegate::GetHeatDemand()
{
return mHeatDemand;
}
uint16_t WaterHeaterManagementDelegate::GetTankVolume()
{
return mTankVolume;
}
int64_t WaterHeaterManagementDelegate::GetEstimatedHeatRequired()
{
return mEstimatedHeatRequired;
}
Percent WaterHeaterManagementDelegate::GetTankPercentage()
{
return mTankPercentage;
}
BoostStateEnum WaterHeaterManagementDelegate::GetBoostState()
{
return mBoostState;
}
void WaterHeaterManagementDelegate::SetHeaterTypes(BitMask<WaterHeaterHeatSourceBitmap> heaterTypes)
{
if (mHeaterTypes != heaterTypes)
{
mHeaterTypes = heaterTypes;
MatterReportingAttributeChangeCallback(mEndpointId, WaterHeaterManagement::Id, Attributes::HeaterTypes::Id);
}
}
void WaterHeaterManagementDelegate::SetHeatDemand(BitMask<WaterHeaterHeatSourceBitmap> heatDemand)
{
if (mHeatDemand != heatDemand)
{
mHeatDemand = heatDemand;
MatterReportingAttributeChangeCallback(mEndpointId, WaterHeaterManagement::Id, Attributes::HeatDemand::Id);
}
}
void WaterHeaterManagementDelegate::SetTankVolume(uint16_t tankVolume)
{
if (mTankVolume != tankVolume)
{
mTankVolume = tankVolume;
MatterReportingAttributeChangeCallback(mEndpointId, WaterHeaterManagement::Id, Attributes::TankVolume::Id);
}
}
void WaterHeaterManagementDelegate::SetEstimatedHeatRequired(int64_t estimatedHeatRequired)
{
if (mEstimatedHeatRequired != estimatedHeatRequired)
{
mEstimatedHeatRequired = estimatedHeatRequired;
MatterReportingAttributeChangeCallback(mEndpointId, WaterHeaterManagement::Id, Attributes::EstimatedHeatRequired::Id);
}
}
void WaterHeaterManagementDelegate::SetTankPercentage(Percent tankPercentage)
{
if (mpWhmInstance != nullptr && mpWhmInstance->HasFeature(Feature::kTankPercent))
{
if (mTankPercentage != tankPercentage)
{
mTankPercentage = tankPercentage;
MatterReportingAttributeChangeCallback(mEndpointId, WaterHeaterManagement::Id, Attributes::TankPercentage::Id);
}
}
}
void WaterHeaterManagementDelegate::SetBoostState(BoostStateEnum boostState)
{
if (mBoostState != boostState)
{
mBoostState = boostState;
MatterReportingAttributeChangeCallback(mEndpointId, WaterHeaterManagement::Id, Attributes::BoostState::Id);
}
}
/**
* @brief Handles the boost command
*
* Upon receipt, the Water Heater SHALL transition into the BOOST state, which SHALL cause the water in the tank (or
* the TargetPercentage of the water, if included) to be heated towards the set point (or the TemporarySetpoint, if
* included), which in turn may cause a call for heat, even if the mode is OFF, or is TIMED and it is during one of
* the Off periods.
*/
Status WaterHeaterManagementDelegate::HandleBoost(uint32_t durationS, Optional<bool> oneShot, Optional<bool> emergencyBoost,
Optional<int16_t> temporarySetpoint, Optional<Percent> targetPercentage,
Optional<Percent> targetReheat)
{
Status status = Status::Success;
ChipLogProgress(AppServer, "HandleBoost");
// Keep track of the boost command parameters
mBoostOneShot = oneShot;
mBoostEmergencyBoost = emergencyBoost;
mBoostTemporarySetpoint = temporarySetpoint;
mBoostTargetPercentage = targetPercentage;
mBoostTargetReheat = targetReheat;
mBoostTargetTemperatureReached = false;
// If a timer is running, cancel it so we can start a new boost command with the new duration
if (mBoostState == BoostStateEnum::kActive)
{
DeviceLayer::SystemLayer().CancelTimer(BoostTimerExpiry, this);
}
CHIP_ERROR err = DeviceLayer::SystemLayer().StartTimer(System::Clock::Seconds32(durationS), BoostTimerExpiry, this);
if (err != CHIP_NO_ERROR)
{
ChipLogError(AppServer, "HandleBoost: Unable to start a Boost timer: %" CHIP_ERROR_FORMAT, err.Format());
// Not a lot we can do -> just set the boost state to inactive
SetBoostState(BoostStateEnum::kInactive);
return Status::Failure;
}
// Now running a boost command
SetBoostState(BoostStateEnum::kActive);
if (mpWhmManufacturer != nullptr)
{
status = mpWhmManufacturer->BoostCommandStarted(durationS, oneShot, emergencyBoost, temporarySetpoint, targetPercentage,
targetReheat);
}
else
{
status = Status::InvalidInState;
ChipLogError(AppServer, "HandleBoost: mpWhmManufacturer == nullptr");
}
VerifyOrReturnValue(status == Status::Success, status);
// See if the heat needs to be turned on or off as a result of this boost command
status = ChangeHeatingIfNecessary();
VerifyOrReturnValue(status == Status::Success, status);
// Now generate a BoostStarted event
err = GenerateBoostStartedEvent(durationS, oneShot, emergencyBoost, temporarySetpoint, targetPercentage, targetReheat);
if (err != CHIP_NO_ERROR)
{
ChipLogError(AppServer, "HandleBoost: Failed to send BoostStarted event: %" CHIP_ERROR_FORMAT, err.Format());
return Status::Failure;
}
return Status::Success;
}
void WaterHeaterManagementDelegate::BoostTimerExpiry(System::Layer * systemLayer, void * delegate)
{
WaterHeaterManagementDelegate * dg = static_cast<WaterHeaterManagementDelegate *>(delegate);
dg->HandleBoostTimerExpiry();
}
/**
* @brief Timer for handling the completion of a boost command
*/
void WaterHeaterManagementDelegate::HandleBoostTimerExpiry()
{
ChipLogError(AppServer, "HandleBoostTimerExpiry");
// The PowerAdjustment is no longer in progress
SetBoostState(BoostStateEnum::kInactive);
if (mpWhmManufacturer != nullptr)
{
mpWhmManufacturer->BoostCommandFinished();
}
else
{
ChipLogError(AppServer, "HandleBoostTimerExpiry: mpWhmManufacturer == nullptr");
}
// Note ChangeHeatingIfNecessary can generate a BoostEnded event but only if the boost state is kActive
// which it cannot be when called from here.
ChangeHeatingIfNecessary();
CHIP_ERROR err = GenerateBoostEndedEvent();
if (err != CHIP_NO_ERROR)
{
ChipLogError(AppServer, "HandleBoostTimerExpiry: Failed to send BoostEnded event: %" CHIP_ERROR_FORMAT, err.Format());
}
}
/**
* @brief Cancels a boost command
*
* Upon receipt, the Water Heater SHALL transition back from the BOOST state to the previous mode (e.g. OFF, MANUAL or TIMED).
*/
Status WaterHeaterManagementDelegate::HandleCancelBoost()
{
ChipLogProgress(AppServer, "HandleCancelBoost");
if (mBoostState == BoostStateEnum::kActive)
{
SetBoostState(BoostStateEnum::kInactive);
mBoostEmergencyBoost.ClearValue();
DeviceLayer::SystemLayer().CancelTimer(BoostTimerExpiry, this);
VerifyOrReturnValue(mpWhmManufacturer != nullptr, Status::InvalidInState);
Status status = mpWhmManufacturer->BoostCommandCancelled();
VerifyOrReturnValue(status == Status::Success, status);
// Note ChangeHeatingIfNecessary can generate a BoostEnded event but only if the boost state is kActive
// which it cannot be when called from here.
status = ChangeHeatingIfNecessary();
VerifyOrReturnValue(status == Status::Success, status);
CHIP_ERROR err = GenerateBoostEndedEvent();
if (err != CHIP_NO_ERROR)
{
ChipLogError(AppServer, "HandleCancelBoost: Failed to send BoostEnded event: %" CHIP_ERROR_FORMAT, err.Format());
return Status::Failure;
}
}
return Status::Success;
}
/*********************************************************************************
*
* WaterHeaterManagementDelegate specific methods
*
*********************************************************************************/
uint16_t WaterHeaterManagementDelegate::GetActiveTargetWaterTemperature() const
{
// Determine the target temperature. If a boost command is in progress and has a mBoostTemporarySetpoint value use that as the
// target temperature.
// Note, in practise the actual heating is likely to be controlled by the thermostat's occupiedHeatingSetpoint most of the
// time, and the TemporarySetpoint (if not null) would be overiding the thermostat's occupiedHeatingSetpoint.
// However, this code doesn't rely upon the thermostat cluster.
uint16_t targetTemperature = (mBoostState == BoostStateEnum::kActive && mBoostTemporarySetpoint.HasValue())
? static_cast<uint16_t>(mBoostTemporarySetpoint.Value())
: mTargetWaterTemperature;
return targetTemperature;
}
uint8_t WaterHeaterManagementDelegate::CalculateTankPercentage() const
{
int32_t tankPercentage = 100 * (static_cast<int32_t>(mWaterTemperature) - static_cast<int32_t>(mColdWaterTemperature)) /
(static_cast<int32_t>(GetActiveTargetWaterTemperature()) - static_cast<int32_t>(mColdWaterTemperature));
tankPercentage = std::min(tankPercentage, static_cast<int32_t>(100));
tankPercentage = std::max(tankPercentage, static_cast<int32_t>(0));
return static_cast<uint8_t>(tankPercentage);
}
void WaterHeaterManagementDelegate::SetColdWaterTemperature(uint16_t coldWaterTemperature)
{
mColdWaterTemperature = coldWaterTemperature;
}
void WaterHeaterManagementDelegate::SetWaterTemperature(uint16_t waterTemperature)
{
mWaterTemperature = waterTemperature;
if (mpWhmInstance != nullptr && mpWhmInstance->HasFeature(Feature::kTankPercent))
{
// Recalculate the tankPercentage as the waterTemperature has changed
SetTankPercentage(CalculateTankPercentage());
}
// See if the heat needs to be turned on or off
ChangeHeatingIfNecessary();
}
void WaterHeaterManagementDelegate::SetTargetWaterTemperature(uint16_t targetWaterTemperature)
{
mTargetWaterTemperature = targetWaterTemperature;
// See if the heat needs to be turned on or off
ChangeHeatingIfNecessary();
}
void WaterHeaterManagementDelegate::DrawOffHotWater(Percent percentageReplaced, uint16_t replacedWaterTemperature)
{
// First calculate the new average water temperature
mWaterTemperature =
static_cast<uint16_t>(mWaterTemperature * (100 - percentageReplaced) + replacedWaterTemperature * percentageReplaced) / 100;
// Replaces percentageReplaced% of the water in the tank with water of a temperature replacedWaterTemperature
// Only supported if the kTankPercent feature is supported.
if (mpWhmInstance != nullptr && mpWhmInstance->HasFeature(Feature::kTankPercent))
{
SetTankPercentage(CalculateTankPercentage());
ChangeHeatingIfNecessary();
}
}
bool WaterHeaterManagementDelegate::HasWaterTemperatureReachedTarget() const
{
uint16_t targetTemperature = GetActiveTargetWaterTemperature();
if (mBoostState == BoostStateEnum::kActive)
{
if (mBoostTargetTemperatureReached && mBoostTargetReheat.HasValue())
{
// If the tank supports the TankPercent feature, and the heating by this Boost command has ceased because the
// TargetPercentage of the water in the tank has been heated to the set point (or TemporarySetpoint if included),
// mBoostTargetReheat indicates the percentage to which the hot water in the tank SHALL be allowed to fall before
// again beginning to reheat it.
//
// For example if the TargetPercentage was 80%, and the TargetReheat was 40%, then after initial heating to 80% hot
// water, the tank may have hot water drawn off until only 40% hot water remains. At this point the heater will begin to
// heat back up to 80% of hot water. If this field and the OneShot field were both omitted, heating would begin again
// after any water draw which reduced the TankPercentage below 80%.
// If this field is included then the TargetPercentage field SHALL also be included, and the OneShot excluded.
VerifyOrReturnValue(mTankPercentage >= mBoostTargetReheat.Value(), false);
}
else if (mBoostTargetPercentage.HasValue())
{
// If tank percentage is supported AND the targetPercentage.HasValue() then use target percentage to heat up.
VerifyOrReturnValue(mTankPercentage >= mBoostTargetPercentage.Value(), false);
}
else
{
VerifyOrReturnValue(mWaterTemperature >= targetTemperature, false);
}
}
else
{
// Just relying on mWaterTemperature to determine whether the temperature is at the target temperature
VerifyOrReturnValue(mWaterTemperature >= targetTemperature, false);
}
// Must have reached the right temperature
return true;
}
Status WaterHeaterManagementDelegate::ChangeHeatingIfNecessary()
{
VerifyOrReturnError(mpWhmManufacturer != nullptr, Status::InvalidInState);
HeatingOp heatingOp = HeatingOp::LeaveHeatingUnchanged;
Status status = DetermineIfChangingHeatingState(heatingOp);
VerifyOrReturnError(status == Status::Success, status);
if (heatingOp == HeatingOp::TurnHeatingOn)
{
status = mpWhmManufacturer->TurnHeatingOn(mBoostEmergencyBoost.HasValue() ? mBoostEmergencyBoost.Value() : false);
}
else if (heatingOp == HeatingOp::TurnHeatingOff)
{
// If running a boost command with the oneShot parameter and turning heat off, then must have
// reached the boost command target temperature -> that's the boost command complete.
if (mBoostState == BoostStateEnum::kActive && mBoostOneShot.HasValue() && mBoostOneShot.Value())
{
SetBoostState(BoostStateEnum::kInactive);
DeviceLayer::SystemLayer().CancelTimer(BoostTimerExpiry, this);
mBoostEmergencyBoost.ClearValue();
status = mpWhmManufacturer->BoostCommandCancelled();
CHIP_ERROR err = GenerateBoostEndedEvent();
if (err != CHIP_NO_ERROR)
{
ChipLogError(AppServer, "ChangeHeatingIfNecessary: Failed to send BoostEnded event: %" CHIP_ERROR_FORMAT,
err.Format());
}
}
// Turn the heating off
status = mpWhmManufacturer->TurnHeatingOff();
}
return status;
}
Status WaterHeaterManagementDelegate::DetermineIfChangingHeatingState(HeatingOp & heatingOp)
{
heatingOp = LeaveHeatingUnchanged;
if (!HasWaterTemperatureReachedTarget())
{
VerifyOrReturnError(WaterHeaterMode::Instance() != nullptr, Status::InvalidInState);
uint8_t mode = WaterHeaterMode::Instance()->GetCurrentMode();
// The water in the tank is not at the target temperature. See if heating is currently off
if (mHeatDemand.Raw() == 0)
{
// Need to track whether the water temperature has reached the target temperature for the boost
// command when a oneShot option has been applied.
if (mBoostState == BoostStateEnum::kActive)
{
mBoostTargetTemperatureReached = false;
}
// If a boost command is in progress or in manual mode, find a heating source and "turn it on".
if (mBoostState == BoostStateEnum::kActive || mode == WaterHeaterMode::kModeManual)
{
heatingOp = HeatingOp::TurnHeatingOn;
}
}
else if (mBoostState == BoostStateEnum::kInactive && mode == WaterHeaterMode::kModeOff)
{
// The water temperature is not at the target temperature but there is no boost command in progress and the mode is Off
// so need to ensure the heating is turned off.
ChipLogError(AppServer, "DetermineIfChangingHeatingState turning heating off due to no boost cmd and kModeOff");
heatingOp = HeatingOp::TurnHeatingOff;
}
}
else if (mHeatDemand.Raw() != 0)
{
// The water in the tank has reached the target temperature - need to turn the heating off
heatingOp = HeatingOp::TurnHeatingOff;
// If a boost command is in progress, record that the target temperature has been reached.
mBoostTargetTemperatureReached = (mBoostState == BoostStateEnum::kActive);
}
return Status::Success;
}
Status WaterHeaterManagementDelegate::SetWaterHeaterMode(uint8_t modeValue)
{
VerifyOrReturnError(WaterHeaterMode::Instance() != nullptr, Status::InvalidInState);
if (!WaterHeaterMode::Instance()->IsSupportedMode(modeValue))
{
ChipLogError(AppServer, "SetWaterHeaterMode bad mode");
return Status::ConstraintError;
}
Status status = WaterHeaterMode::Instance()->UpdateCurrentMode(modeValue);
if (status != Status::Success)
{
ChipLogError(AppServer, "SetWaterHeaterMode updateMode failed 0x%02x", to_underlying(status));
return status;
}
return ChangeHeatingIfNecessary();
}