Made-with: Cursor
18 KiB
Boiler Anti-Cycling & Debug Diagnostic Entity — Implementation Plan
For Claude: REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
Goal: Eliminate rapid boiler on/off cycling caused by thermostat power fluctuations and add a diagnostic HA entity exposing every decision input in real time.
Architecture: Three layered changes — (1) WaterReadyService gets consecutive-count confirmation, (2) BoilerControlService gets minimum hold-time guards with TimeProvider, (3) a new sensor.boilermonitor_debug MQTT entity publishes all decision inputs each poll. A new BoilerActionResult record replaces the bare BoilerAction return from DetermineAction.
Tech Stack: C# / .NET 10, xUnit 2.9, FluentAssertions 8.8, Moq 4.20, FakeTimeProvider, NetDaemon MQTT entity manager.
Task 1: Add New Constants to BoilerMonitorConsts
Files:
- Modify:
BoilerMonitor.Models/BoilerMonitorConsts.cs
Step 1: Add constants
Add these constants to BoilerMonitorConsts:
public const int DefaultWaterReadyConsecutiveCount = 3;
public const int DefaultMinOnHoldSeconds = 600;
public const int DefaultMinOffHoldSeconds = 300;
public const string DebugEntityId = "sensor.boilermonitor_debug";
Add DebugEntityId to the list of entity IDs referenced in cleanup and creation flows.
Step 2: Commit
git add BoilerMonitor.Models/BoilerMonitorConsts.cs
git commit -m "feat: add anti-cycling and debug entity constants to BoilerMonitorConsts"
Task 2: Add BoilerActionResult Record
Files:
- Create:
BoilerMonitor.Manager/Models/BoilerActionResult.cs
Step 1: Create the record
using BoilerMonitor.Models.Enums;
namespace BoilerMonitorManager.Models;
public record BoilerActionResult
{
public required BoilerAction Action { get; init; }
public required string Reason { get; init; }
public required bool HoldSuppressed { get; init; }
public required TimeSpan HoldTimeRemaining { get; init; }
}
Step 2: Commit
git add BoilerMonitor.Manager/Models/BoilerActionResult.cs
git commit -m "feat: add BoilerActionResult record for richer control decisions"
Task 3: Sustained Water-Ready Confirmation — Tests First
Files:
- Modify:
BoilerMonitor.Manager/Interface/IWaterReadyService.cs - Modify:
BoilerMonitor.Manager/WaterReadyService.cs - Modify:
BoilerMonitor.Manager.Tests/WaterReadyServiceTests.cs
Step 1: Write failing tests
Add these tests to WaterReadyServiceTests.cs in a new #region Consecutive low-power confirmation:
#region Consecutive low-power confirmation
[Fact]
public void IsWaterReady_SingleLowPowerReading_ShouldReturnFalse()
{
var sut = CreateSut();
var result = sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
result.Should().BeFalse();
}
[Fact]
public void IsWaterReady_ConsecutiveLowPowerReadingsReachingThreshold_ShouldReturnTrue()
{
var sut = CreateSut();
for (var i = 0; i < BoilerMonitorConsts.DefaultWaterReadyConsecutiveCount - 1; i++)
{
sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts).Should().BeFalse();
}
var result = sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
result.Should().BeTrue();
}
[Fact]
public void IsWaterReady_HighPowerReadingResetsConsecutiveCount()
{
var sut = CreateSut();
sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
sut.IsWaterReady("on", 2000.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
for (var i = 0; i < BoilerMonitorConsts.DefaultWaterReadyConsecutiveCount - 1; i++)
{
sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts).Should().BeFalse();
}
sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts).Should().BeTrue();
}
[Fact]
public void IsWaterReady_NotifyTurnedOnResetsConsecutiveCount()
{
var sut = CreateSut();
sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
sut.NotifyTurnedOn();
_timeProvider.Advance(BoilerMonitorConsts.WarmUpGracePeriod);
for (var i = 0; i < BoilerMonitorConsts.DefaultWaterReadyConsecutiveCount - 1; i++)
{
sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts).Should().BeFalse();
}
sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts).Should().BeTrue();
}
[Fact]
public void ConsecutiveLowPowerCount_ShouldReflectCurrentCount()
{
var sut = CreateSut();
sut.ConsecutiveLowPowerCount.Should().Be(0);
sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
sut.ConsecutiveLowPowerCount.Should().Be(1);
sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
sut.ConsecutiveLowPowerCount.Should().Be(2);
sut.IsWaterReady("on", 2000.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
sut.ConsecutiveLowPowerCount.Should().Be(0);
}
#endregion
Step 2: Run tests to verify they fail
Run: dotnet test BoilerMonitor.Manager.Tests --filter "ClassName=WaterReadyServiceTests" --no-build
Expected: compilation error or test failures (property and behavior don't exist yet).
Step 3: Update IWaterReadyService interface
In BoilerMonitor.Manager/Interface/IWaterReadyService.cs, add:
int ConsecutiveLowPowerCount { get; }
Step 4: Implement consecutive confirmation in WaterReadyService
In WaterReadyService.cs:
- Add
private int _consecutiveLowPowerCount;field. - Add public property
public int ConsecutiveLowPowerCountthat reads under_lock. - In
IsWaterReady: after the grace period check, if power < threshold increment_consecutiveLowPowerCount(under lock), else reset to 0. Returntrueonly when_consecutiveLowPowerCount >= DefaultWaterReadyConsecutiveCount. - In
NotifyTurnedOn: reset_consecutiveLowPowerCount = 0(already under lock).
Step 5: Update existing tests that now fail
The tests IsWaterReady_SwitchOnAndLowPower_ShouldReturnTrue, IsWaterReady_SwitchOnAndPowerBelowThreshold_ShouldReturnTrue, IsWaterReady_SwitchOnCaseInsensitive_ShouldReturnTrue, IsWaterReady_CustomThreshold_ShouldUseProvidedValue, IsWaterReady_AfterGracePeriodExpires_ShouldReturnTrue, and IsWaterReady_WithoutNotifyTurnedOn_ShouldNotApplyGracePeriod all expect true from a single call. They must be updated to call IsWaterReady DefaultWaterReadyConsecutiveCount times to reach the threshold.
Step 6: Run all WaterReadyService tests
Run: dotnet test BoilerMonitor.Manager.Tests --filter "ClassName=WaterReadyServiceTests" -v n
Expected: all PASS.
Step 7: Commit
git add BoilerMonitor.Manager/Interface/IWaterReadyService.cs BoilerMonitor.Manager/WaterReadyService.cs BoilerMonitor.Manager.Tests/WaterReadyServiceTests.cs
git commit -m "feat: require consecutive low-power readings before declaring water ready"
Task 4: Minimum Hold Time — Tests First
Files:
- Modify:
BoilerMonitor.Manager/Interface/IBoilerControlService.cs - Modify:
BoilerMonitor.Manager/BoilerControlService.cs - Modify:
BoilerMonitor.Manager.Tests/BoilerControlServiceTests.cs
Step 1: Write failing tests
Update BoilerControlServiceTests.cs:
- Change
CreateSut()to acceptFakeTimeProvider(add field likeWaterReadyServiceTests). - All existing tests must be updated:
DetermineActionnow returnsBoilerActionResult— assert on.Actionproperty instead of the bare enum. - Add new test region
#region Hold time enforcement:
#region Hold time enforcement
[Fact]
public void DetermineAction_TurnOnThenImmediateTurnOff_ShouldBeSuppressed()
{
// First action: turn on
var result1 = _sut.DetermineAction(
isNowCheap: true, waterReady: false, currentSwitchState: "off",
budgetExhausted: false, budgetOverride: false);
result1.Action.Should().Be(BoilerAction.TurnOn);
// Immediate turn off attempt — should be suppressed by on-hold
var result2 = _sut.DetermineAction(
isNowCheap: false, waterReady: false, currentSwitchState: "on",
budgetExhausted: false, budgetOverride: false);
result2.Action.Should().Be(BoilerAction.NoChange);
result2.HoldSuppressed.Should().BeTrue();
result2.HoldTimeRemaining.Should().BeGreaterThan(TimeSpan.Zero);
}
[Fact]
public void DetermineAction_TurnOnThenTurnOffAfterHoldExpires_ShouldAllow()
{
var result1 = _sut.DetermineAction(
isNowCheap: true, waterReady: false, currentSwitchState: "off",
budgetExhausted: false, budgetOverride: false);
result1.Action.Should().Be(BoilerAction.TurnOn);
_timeProvider.Advance(TimeSpan.FromSeconds(BoilerMonitorConsts.DefaultMinOnHoldSeconds));
var result2 = _sut.DetermineAction(
isNowCheap: false, waterReady: false, currentSwitchState: "on",
budgetExhausted: false, budgetOverride: false);
result2.Action.Should().Be(BoilerAction.TurnOff);
result2.HoldSuppressed.Should().BeFalse();
}
[Fact]
public void DetermineAction_TurnOffThenImmediateTurnOn_ShouldBeSuppressed()
{
// First: turn on
_sut.DetermineAction(
isNowCheap: true, waterReady: false, currentSwitchState: "off",
budgetExhausted: false, budgetOverride: false);
_timeProvider.Advance(TimeSpan.FromSeconds(BoilerMonitorConsts.DefaultMinOnHoldSeconds));
// Then: turn off
_sut.DetermineAction(
isNowCheap: false, waterReady: false, currentSwitchState: "on",
budgetExhausted: false, budgetOverride: false);
// Immediate turn on attempt — should be suppressed by off-hold
var result = _sut.DetermineAction(
isNowCheap: true, waterReady: false, currentSwitchState: "off",
budgetExhausted: false, budgetOverride: false);
result.Action.Should().Be(BoilerAction.NoChange);
result.HoldSuppressed.Should().BeTrue();
}
[Fact]
public void DetermineAction_TurnOffThenTurnOnAfterOffHoldExpires_ShouldAllow()
{
_sut.DetermineAction(
isNowCheap: true, waterReady: false, currentSwitchState: "off",
budgetExhausted: false, budgetOverride: false);
_timeProvider.Advance(TimeSpan.FromSeconds(BoilerMonitorConsts.DefaultMinOnHoldSeconds));
_sut.DetermineAction(
isNowCheap: false, waterReady: false, currentSwitchState: "on",
budgetExhausted: false, budgetOverride: false);
_timeProvider.Advance(TimeSpan.FromSeconds(BoilerMonitorConsts.DefaultMinOffHoldSeconds));
var result = _sut.DetermineAction(
isNowCheap: true, waterReady: false, currentSwitchState: "off",
budgetExhausted: false, budgetOverride: false);
result.Action.Should().Be(BoilerAction.TurnOn);
result.HoldSuppressed.Should().BeFalse();
}
[Fact]
public void DetermineAction_NoChangeDoesNotAffectHoldTime()
{
_sut.DetermineAction(
isNowCheap: true, waterReady: false, currentSwitchState: "off",
budgetExhausted: false, budgetOverride: false);
// NoChange call should not reset hold
var noChange = _sut.DetermineAction(
isNowCheap: true, waterReady: false, currentSwitchState: "on",
budgetExhausted: false, budgetOverride: false);
noChange.Action.Should().Be(BoilerAction.NoChange);
noChange.HoldSuppressed.Should().BeFalse();
// Turn off still suppressed
var suppressed = _sut.DetermineAction(
isNowCheap: false, waterReady: false, currentSwitchState: "on",
budgetExhausted: false, budgetOverride: false);
suppressed.Action.Should().Be(BoilerAction.NoChange);
suppressed.HoldSuppressed.Should().BeTrue();
}
#endregion
Step 2: Run tests to verify they fail
Run: dotnet test BoilerMonitor.Manager.Tests --filter "ClassName=BoilerControlServiceTests" --no-build
Expected: compilation errors (return type changed, TimeProvider not wired).
Step 3: Update IBoilerControlService interface
Change return type to BoilerActionResult:
using BoilerMonitorManager.Models;
BoilerActionResult DetermineAction(bool isNowCheap, bool waterReady, string? currentSwitchState, bool budgetExhausted, bool budgetOverride);
Step 4: Implement hold time logic in BoilerControlService
- Add
TimeProvider timeProviderto constructor (primary constructor pattern matching existinglogger). - Add fields:
private readonly Lock _lock = new();,private DateTimeOffset? _lastTransitionAt;,private BoilerAction? _lastTransitionAction;. - In
DetermineAction:- Compute
shouldBeOn(existing logic). - Determine desired action (TurnOn, TurnOff, or NoChange) using existing logic.
- If desired action is TurnOn or TurnOff, check hold: if
_lastTransitionAtis set and hold time hasn't elapsed, returnNoChangewithHoldSuppressed = trueand remaining time. - If action proceeds (TurnOn or TurnOff), record
_lastTransitionAtand_lastTransitionAction. - Return
BoilerActionResultwith action, reason, hold info.
- Compute
Step 5: Update existing tests for new return type
All existing tests assert result.Should().Be(BoilerAction.X) — change to result.Action.Should().Be(BoilerAction.X).
Update CreateSut() to pass FakeTimeProvider.
Step 6: Run all BoilerControlService tests
Run: dotnet test BoilerMonitor.Manager.Tests --filter "ClassName=BoilerControlServiceTests" -v n
Expected: all PASS.
Step 7: Commit
git add BoilerMonitor.Manager/Interface/IBoilerControlService.cs BoilerMonitor.Manager/BoilerControlService.cs BoilerMonitor.Manager.Tests/BoilerControlServiceTests.cs
git commit -m "feat: add minimum hold time to BoilerControlService to prevent rapid cycling"
Task 5: Debug Diagnostic Entity
Files:
- Modify:
BoilerMonitor.Models/BoilerMonitorConsts.cs(add to CleanableEntityIds) - Modify:
BoilerMonitor.Manager/Models/BoilerMonitorUpdateContext.cs(add debug fields) - Modify:
BoilerMonitor.Manager/Interface/IBoilerMonitorEntityService.cs(if needed) - Modify:
BoilerMonitor.Manager/BoilerMonitorEntityService.cs(create, reset, update, cleanup debug entity)
Step 1: Add debug fields to BoilerMonitorUpdateContext
Add these properties:
public required string LastAction { get; init; }
public required string LastActionReason { get; init; }
public required bool HoldSuppressed { get; init; }
public required int HoldTimeRemainingSeconds { get; init; }
public required string HoldType { get; init; }
public required int WaterReadyConsecutiveCount { get; init; }
public required int WaterReadyConsecutiveThreshold { get; init; }
public required bool SkipPriceCap { get; init; }
public required double HeatingThresholdWatts { get; init; }
Step 2: Add debug entity to BoilerMonitorEntityService
- Add
DebugEntityIdtoCleanableEntityIdsarray. - Add debug entity definition in
GetAllEntities():
new BoilerMonitorEntity("sensor", "boilermonitor_debug", "Boiler Monitor debug")
{
AdditionalConfig = new { icon = "mdi:bug-outline", device }
}
- Add
ResetDebugAsync()method (state = "idle", empty attributes). - Add
UpdateDebugEntityAsync(BoilerMonitorUpdateContext ctx, string timestamp)method that sets state toctx.LastActionand attributes to all debug fields. - Call reset in
ResetEntitiesAsync()and update inUpdateEntitiesAsync().
Step 3: Run existing entity service tests
Run: dotnet test BoilerMonitor.Manager.Tests --filter "ClassName=BoilerMonitorEntityServiceTests" -v n
Expected: PASS (existing tests should still pass).
Step 4: Commit
git add BoilerMonitor.Manager/Models/BoilerMonitorUpdateContext.cs BoilerMonitor.Manager/BoilerMonitorEntityService.cs BoilerMonitor.Models/BoilerMonitorConsts.cs
git commit -m "feat: add debug diagnostic MQTT entity with full decision attributes"
Task 6: Wire Everything Together in BoilerMonitorInit
Files:
- Modify:
BoilerMonitor.Manager/BoilerMonitorInit.cs
Step 1: Update PollAndUpdateAsync
DetermineActionnow returnsBoilerActionResult— extract.ActionforExecuteBoilerAction.- Read
_waterReadyService.ConsecutiveLowPowerCountfor debug context. - Compute
holdType: ifactionResult.HoldSuppressedthen"on_hold"or"off_hold"based on what was suppressed, else"none". - Populate the new fields in
BoilerMonitorUpdateContext:LastAction = actionResult.Action.ToString()LastActionReason = actionResult.ReasonHoldSuppressed = actionResult.HoldSuppressedHoldTimeRemainingSeconds = (int)actionResult.HoldTimeRemaining.TotalSecondsHoldType = holdTypeWaterReadyConsecutiveCount = _waterReadyService.ConsecutiveLowPowerCountWaterReadyConsecutiveThreshold = BoilerMonitorConsts.DefaultWaterReadyConsecutiveCountSkipPriceCap = skipPriceCapHeatingThresholdWatts = config.HeatingPowerThresholdWatts!.Value
Step 2: Update BoilerMonitorServiceRegistration (DI)
If BoilerControlService now requires TimeProvider, register TimeProvider.System in the DI container (or ensure it's already registered). Check BoilerMonitorServiceRegistration.cs for the registration pattern.
Step 3: Build and run all tests
Run: dotnet build then dotnet test BoilerMonitor.Manager.Tests -v n
Expected: all PASS.
Step 4: Commit
git add BoilerMonitor.Manager/BoilerMonitorInit.cs BoilerMonitor.Manager/BoilerMonitorServiceRegistration.cs
git commit -m "feat: wire anti-cycling guards and debug entity into BoilerMonitorInit"
Task 7: Final Verification
Step 1: Full solution build
Run: dotnet build HomeAssistantSDK.sln
Expected: 0 errors, 0 warnings (or only pre-existing warnings).
Step 2: Full test suite
Run: dotnet test HomeAssistantSDK.sln -v n
Expected: all PASS.
Step 3: Commit any remaining fixes
If any fixes were needed, commit them.