From 11c2574235fd6908d6b06479a465050985379cd7 Mon Sep 17 00:00:00 2001 From: Marius Date: Tue, 24 Mar 2026 15:29:59 +0200 Subject: [PATCH] feat: migrate boiler control implementation to `BoilerMonitor` namespace and add budget handling logic --- .vscode/launch.json | 7 + .../BoilerControlServiceTests.cs | 154 ++++++ .../BoilerMonitor.Manager.Tests.csproj | 35 ++ .../BoilerMonitorConfigTests.cs | 133 +++++ .../BoilerMonitorEntityServiceTests.cs | 343 ++++++++++++ .../BoilerMonitorOptionsTests.cs | 29 + .../BoilerRunTimeTrackerTests.cs | 254 +++++++++ .../WaterReadyServiceTests.cs | 430 +++++++++++++++ BoilerMonitor.Manager/BoilerConfigReader.cs | 49 ++ BoilerMonitor.Manager/BoilerControlService.cs | 53 ++ .../BoilerMonitor.Manager.csproj | 27 + .../BoilerMonitorEntityService.cs | 465 ++++++++++++++++ BoilerMonitor.Manager/BoilerMonitorInit.cs | 503 ++++++++++++++++++ .../BoilerMonitorServiceRegistration.cs | 34 ++ BoilerMonitor.Manager/BoilerRunTimeTracker.cs | 66 +++ .../Interface/IBoilerControlService.cs | 8 + .../Interface/IBoilerMonitorEntityService.cs | 14 + .../Interface/IBoilerMonitorInit.cs | 7 + .../Interface/IBoilerRunTimeTracker.cs | 11 + .../Interface/IWaterReadyService.cs | 9 + .../Models/BoilerMonitorConfig.cs | 15 + .../Models/BoilerMonitorOptions.cs | 14 + .../Models/BoilerMonitorUpdateContext.cs | 17 + .../Models/PersistedBoilerState.cs | 9 + .../Models/RunTimeSnapshot.cs | 8 + BoilerMonitor.Manager/WaterReadyService.cs | 115 ++++ BoilerMonitor.Models/BoilerConfig.cs | 15 + .../BoilerMonitor.Models.csproj | 18 + BoilerMonitor.Models/BoilerMonitorConsts.cs | 67 +++ BoilerMonitor.Models/BoilerMonitorEntity.cs | 25 + .../Enums/BoilerAction.cs | 2 +- BoilerMonitor.Models/IBoilerConfigReader.cs | 9 + .../HomeAssistant.Server.csproj | 2 + HomeAssistant.Server/appsettings.json | 10 +- HomeAssistant.Server/program.cs | 10 +- HomeAssistantSDK.sln | 55 ++ .../BoilerControlServiceTests.cs | 215 -------- .../CheapestIntervalsFinderTests.cs | 124 ----- .../NordPool.Manager.Tests.csproj | 3 +- .../NordPoolEntityServiceTests.cs | 31 +- NordPool.Manager.Tests/NordPoolInitTests.cs | 61 ++- .../NordPoolPriceServiceTests.cs | 4 +- NordPool.Manager/BoilerControlService.cs | 36 -- NordPool.Manager/CheapestIntervalsFinder.cs | 12 - .../Interface/IBoilerControlService.cs | 8 - .../Interface/ICheapestIntervalsFinder.cs | 2 - NordPool.Manager/Models/BoilerConfig.cs | 9 - NordPool.Manager/Models/Consts/PriceConsts.cs | 7 - .../Models/EntityUpdateContext.cs | 3 - NordPool.Manager/Models/NordPoolOptions.cs | 11 + NordPool.Manager/NordPool.Manager.csproj | 3 + NordPool.Manager/NordPoolEntityService.cs | 92 +--- NordPool.Manager/NordPoolInit.cs | 229 ++------ NordPool.Models/CompactNordPoolDayPrice.cs | 17 + NordPool.Models/NordPoolConsts.cs | 18 +- NordPool.Models/NordPoolDayPrice.cs | 13 +- NordPool.Models/NordPoolDayPriceExtensions.cs | 2 + NordPool.Models/NordPoolEntities.cs | 33 +- .../PowerSensorDiscoveryServiceTests.cs | 17 +- .../PowerMonitor.Manager.csproj | 1 + PowerMonitor.Manager/PowerMonitorInit.cs | 5 +- 61 files changed, 3250 insertions(+), 728 deletions(-) create mode 100644 .vscode/launch.json create mode 100644 BoilerMonitor.Manager.Tests/BoilerControlServiceTests.cs create mode 100644 BoilerMonitor.Manager.Tests/BoilerMonitor.Manager.Tests.csproj create mode 100644 BoilerMonitor.Manager.Tests/BoilerMonitorConfigTests.cs create mode 100644 BoilerMonitor.Manager.Tests/BoilerMonitorEntityServiceTests.cs create mode 100644 BoilerMonitor.Manager.Tests/BoilerMonitorOptionsTests.cs create mode 100644 BoilerMonitor.Manager.Tests/BoilerRunTimeTrackerTests.cs create mode 100644 BoilerMonitor.Manager.Tests/WaterReadyServiceTests.cs create mode 100644 BoilerMonitor.Manager/BoilerConfigReader.cs create mode 100644 BoilerMonitor.Manager/BoilerControlService.cs create mode 100644 BoilerMonitor.Manager/BoilerMonitor.Manager.csproj create mode 100644 BoilerMonitor.Manager/BoilerMonitorEntityService.cs create mode 100644 BoilerMonitor.Manager/BoilerMonitorInit.cs create mode 100644 BoilerMonitor.Manager/BoilerMonitorServiceRegistration.cs create mode 100644 BoilerMonitor.Manager/BoilerRunTimeTracker.cs create mode 100644 BoilerMonitor.Manager/Interface/IBoilerControlService.cs create mode 100644 BoilerMonitor.Manager/Interface/IBoilerMonitorEntityService.cs create mode 100644 BoilerMonitor.Manager/Interface/IBoilerMonitorInit.cs create mode 100644 BoilerMonitor.Manager/Interface/IBoilerRunTimeTracker.cs create mode 100644 BoilerMonitor.Manager/Interface/IWaterReadyService.cs create mode 100644 BoilerMonitor.Manager/Models/BoilerMonitorConfig.cs create mode 100644 BoilerMonitor.Manager/Models/BoilerMonitorOptions.cs create mode 100644 BoilerMonitor.Manager/Models/BoilerMonitorUpdateContext.cs create mode 100644 BoilerMonitor.Manager/Models/PersistedBoilerState.cs create mode 100644 BoilerMonitor.Manager/Models/RunTimeSnapshot.cs create mode 100644 BoilerMonitor.Manager/WaterReadyService.cs create mode 100644 BoilerMonitor.Models/BoilerConfig.cs create mode 100644 BoilerMonitor.Models/BoilerMonitor.Models.csproj create mode 100644 BoilerMonitor.Models/BoilerMonitorConsts.cs create mode 100644 BoilerMonitor.Models/BoilerMonitorEntity.cs rename {NordPool.Manager/Models => BoilerMonitor.Models}/Enums/BoilerAction.cs (62%) create mode 100644 BoilerMonitor.Models/IBoilerConfigReader.cs delete mode 100644 NordPool.Manager.Tests/BoilerControlServiceTests.cs delete mode 100644 NordPool.Manager/BoilerControlService.cs delete mode 100644 NordPool.Manager/Interface/IBoilerControlService.cs delete mode 100644 NordPool.Manager/Models/BoilerConfig.cs delete mode 100644 NordPool.Manager/Models/Consts/PriceConsts.cs create mode 100644 NordPool.Manager/Models/NordPoolOptions.cs diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..5c7247b --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,7 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [] +} \ No newline at end of file diff --git a/BoilerMonitor.Manager.Tests/BoilerControlServiceTests.cs b/BoilerMonitor.Manager.Tests/BoilerControlServiceTests.cs new file mode 100644 index 0000000..ae70aeb --- /dev/null +++ b/BoilerMonitor.Manager.Tests/BoilerControlServiceTests.cs @@ -0,0 +1,154 @@ +using BoilerMonitor.Models.Enums; +using FluentAssertions; +using Microsoft.Extensions.Logging; +using Moq; +using BoilerMonitorManager; + +namespace BoilerMonitor.Manager.Tests; + +public class BoilerControlServiceTests +{ + private readonly BoilerControlService _sut; + + public BoilerControlServiceTests() + { + var loggerMock = new Mock>(); + _sut = new BoilerControlService(loggerMock.Object); + } + + #region TurnOn scenarios + + [Theory] + [InlineData("off")] + [InlineData("OFF")] + [InlineData("Off")] + [InlineData(null)] + [InlineData("unavailable")] + public void DetermineAction_WhenCheapAndWaterNotReadyAndBudgetAvailable_ShouldReturnTurnOn(string? switchState) + { + var result = _sut.DetermineAction( + isNowCheap: true, waterReady: false, currentSwitchState: switchState, + budgetExhausted: false, budgetOverride: false); + + result.Should().Be(BoilerAction.TurnOn); + } + + [Theory] + [InlineData("off")] + [InlineData(null)] + public void DetermineAction_WhenBudgetExhaustedButOverrideOn_ShouldReturnTurnOn(string? switchState) + { + var result = _sut.DetermineAction( + isNowCheap: true, waterReady: false, currentSwitchState: switchState, + budgetExhausted: true, budgetOverride: true); + + result.Should().Be(BoilerAction.TurnOn); + } + + #endregion + + #region TurnOff scenarios + + [Fact] + public void DetermineAction_WhenNotCheapAndSwitchIsOn_ShouldReturnTurnOff() + { + var result = _sut.DetermineAction( + isNowCheap: false, waterReady: false, currentSwitchState: "on", + budgetExhausted: false, budgetOverride: false); + + result.Should().Be(BoilerAction.TurnOff); + } + + [Fact] + public void DetermineAction_WhenWaterReadyAndSwitchIsOn_ShouldReturnTurnOff() + { + var result = _sut.DetermineAction( + isNowCheap: true, waterReady: true, currentSwitchState: "on", + budgetExhausted: false, budgetOverride: false); + + result.Should().Be(BoilerAction.TurnOff); + } + + [Fact] + public void DetermineAction_WhenBudgetExhaustedAndNoOverride_ShouldReturnTurnOff() + { + var result = _sut.DetermineAction( + isNowCheap: true, waterReady: false, currentSwitchState: "on", + budgetExhausted: true, budgetOverride: false); + + result.Should().Be(BoilerAction.TurnOff); + } + + [Theory] + [InlineData("on")] + [InlineData("ON")] + [InlineData("On")] + public void DetermineAction_WhenNotCheapAndSwitchIsOnCaseInsensitive_ShouldReturnTurnOff(string switchState) + { + var result = _sut.DetermineAction( + isNowCheap: false, waterReady: false, currentSwitchState: switchState, + budgetExhausted: false, budgetOverride: false); + + result.Should().Be(BoilerAction.TurnOff); + } + + #endregion + + #region NoChange scenarios + + [Fact] + public void DetermineAction_WhenCheapAndNotReadyAndAlreadyOn_ShouldReturnNoChange() + { + var result = _sut.DetermineAction( + isNowCheap: true, waterReady: false, currentSwitchState: "on", + budgetExhausted: false, budgetOverride: false); + + result.Should().Be(BoilerAction.NoChange); + } + + [Fact] + public void DetermineAction_WhenNotCheapAndAlreadyOff_ShouldReturnNoChange() + { + var result = _sut.DetermineAction( + isNowCheap: false, waterReady: false, currentSwitchState: "off", + budgetExhausted: false, budgetOverride: false); + + result.Should().Be(BoilerAction.NoChange); + } + + [Fact] + public void DetermineAction_WhenBudgetExhaustedAndAlreadyOff_ShouldReturnNoChange() + { + var result = _sut.DetermineAction( + isNowCheap: true, waterReady: false, currentSwitchState: "off", + budgetExhausted: true, budgetOverride: false); + + result.Should().Be(BoilerAction.NoChange); + } + + #endregion + + #region Comprehensive theory covering all key combinations + + [Theory] + [InlineData(true, false, "off", false, false, BoilerAction.TurnOn)] + [InlineData(true, false, "on", false, false, BoilerAction.NoChange)] + [InlineData(true, true, "on", false, false, BoilerAction.TurnOff)] + [InlineData(true, true, "off", false, false, BoilerAction.NoChange)] + [InlineData(false, false, "on", false, false, BoilerAction.TurnOff)] + [InlineData(false, false, "off", false, false, BoilerAction.NoChange)] + [InlineData(true, false, "on", true, false, BoilerAction.TurnOff)] + [InlineData(true, false, "off", true, false, BoilerAction.NoChange)] + [InlineData(true, false, "off", true, true, BoilerAction.TurnOn)] + [InlineData(true, false, "on", true, true, BoilerAction.NoChange)] + public void DetermineAction_AllCombinations_ShouldReturnExpectedAction( + bool isNowCheap, bool waterReady, string switchState, + bool budgetExhausted, bool budgetOverride, BoilerAction expectedAction) + { + var result = _sut.DetermineAction(isNowCheap, waterReady, switchState, budgetExhausted, budgetOverride); + + result.Should().Be(expectedAction); + } + + #endregion +} diff --git a/BoilerMonitor.Manager.Tests/BoilerMonitor.Manager.Tests.csproj b/BoilerMonitor.Manager.Tests/BoilerMonitor.Manager.Tests.csproj new file mode 100644 index 0000000..2e9c980 --- /dev/null +++ b/BoilerMonitor.Manager.Tests/BoilerMonitor.Manager.Tests.csproj @@ -0,0 +1,35 @@ + + + + net10.0 + enable + enable + false + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + + + diff --git a/BoilerMonitor.Manager.Tests/BoilerMonitorConfigTests.cs b/BoilerMonitor.Manager.Tests/BoilerMonitorConfigTests.cs new file mode 100644 index 0000000..c295c48 --- /dev/null +++ b/BoilerMonitor.Manager.Tests/BoilerMonitorConfigTests.cs @@ -0,0 +1,133 @@ +using FluentAssertions; +using BoilerMonitorManager.Models; + +namespace BoilerMonitor.Manager.Tests; + +public class BoilerMonitorConfigTests +{ + [Fact] + public void IsFullyConfigured_WhenAllFieldsSet_ShouldReturnTrue() + { + var config = new BoilerMonitorConfig + { + BoilerPowerEntityId = "sensor.power", + BoilerSwitchEntityId = "switch.boiler", + PollIntervalSeconds = 30, + HeatingPowerThresholdWatts = 5.0 + }; + + config.IsFullyConfigured.Should().BeTrue(); + } + + [Fact] + public void IsFullyConfigured_WhenPowerEntityMissing_ShouldReturnFalse() + { + var config = new BoilerMonitorConfig + { + BoilerPowerEntityId = null, + BoilerSwitchEntityId = "switch.boiler", + PollIntervalSeconds = 30, + HeatingPowerThresholdWatts = 5.0 + }; + + config.IsFullyConfigured.Should().BeFalse(); + } + + [Fact] + public void IsFullyConfigured_WhenSwitchEntityMissing_ShouldReturnFalse() + { + var config = new BoilerMonitorConfig + { + BoilerPowerEntityId = "sensor.power", + BoilerSwitchEntityId = null, + PollIntervalSeconds = 30, + HeatingPowerThresholdWatts = 5.0 + }; + + config.IsFullyConfigured.Should().BeFalse(); + } + + [Fact] + public void IsFullyConfigured_WhenPollIntervalMissing_ShouldReturnFalse() + { + var config = new BoilerMonitorConfig + { + BoilerPowerEntityId = "sensor.power", + BoilerSwitchEntityId = "switch.boiler", + PollIntervalSeconds = null, + HeatingPowerThresholdWatts = 5.0 + }; + + config.IsFullyConfigured.Should().BeFalse(); + } + + [Fact] + public void IsFullyConfigured_WhenThresholdMissing_ShouldReturnFalse() + { + var config = new BoilerMonitorConfig + { + BoilerPowerEntityId = "sensor.power", + BoilerSwitchEntityId = "switch.boiler", + PollIntervalSeconds = 30, + HeatingPowerThresholdWatts = null + }; + + config.IsFullyConfigured.Should().BeFalse(); + } + + [Fact] + public void IsFullyConfigured_WhenPowerEntityIsWhitespace_ShouldReturnFalse() + { + var config = new BoilerMonitorConfig + { + BoilerPowerEntityId = " ", + BoilerSwitchEntityId = "switch.boiler", + PollIntervalSeconds = 30, + HeatingPowerThresholdWatts = 5.0 + }; + + config.IsFullyConfigured.Should().BeFalse(); + } + + [Fact] + public void IsFullyConfigured_WhenPollIntervalIsZero_ShouldReturnFalse() + { + var config = new BoilerMonitorConfig + { + BoilerPowerEntityId = "sensor.power", + BoilerSwitchEntityId = "switch.boiler", + PollIntervalSeconds = 0, + HeatingPowerThresholdWatts = 5.0 + }; + + config.IsFullyConfigured.Should().BeFalse(); + } + + [Fact] + public void IsFullyConfigured_WhenThresholdIsZero_ShouldReturnFalse() + { + var config = new BoilerMonitorConfig + { + BoilerPowerEntityId = "sensor.power", + BoilerSwitchEntityId = "switch.boiler", + PollIntervalSeconds = 30, + HeatingPowerThresholdWatts = 0.0 + }; + + config.IsFullyConfigured.Should().BeFalse(); + } + + [Fact] + public void IsFullyConfigured_WhenPollIntervalIsNegative_ShouldReturnFalse() + { + var config = new BoilerMonitorConfig + { + BoilerPowerEntityId = "sensor.power", + BoilerSwitchEntityId = "switch.boiler", + PollIntervalSeconds = -1, + HeatingPowerThresholdWatts = 5.0 + }; + + config.IsFullyConfigured.Should().BeFalse(); + } +} diff --git a/BoilerMonitor.Manager.Tests/BoilerMonitorEntityServiceTests.cs b/BoilerMonitor.Manager.Tests/BoilerMonitorEntityServiceTests.cs new file mode 100644 index 0000000..7f3a88a --- /dev/null +++ b/BoilerMonitor.Manager.Tests/BoilerMonitorEntityServiceTests.cs @@ -0,0 +1,343 @@ +using BoilerMonitor.Models; +using BoilerMonitorManager; +using BoilerMonitorManager.Models; +using FluentAssertions; +using HomeAssistant.Entities.Interfaces; +using Microsoft.Extensions.Logging; +using Moq; +using NetDaemon.HassModel; +using NetDaemon.HassModel.Entities; +using static BoilerMonitor.Models.BoilerMonitorConsts; + +namespace BoilerMonitor.Manager.Tests; + +public class BoilerMonitorEntityServiceTests +{ + private readonly Mock _entityManagerMock; + private readonly Mock _haContextMock; + private readonly Mock> _loggerMock; + private readonly BoilerMonitorEntityService _sut; + + public BoilerMonitorEntityServiceTests() + { + _entityManagerMock = new Mock(); + _haContextMock = new Mock(); + _loggerMock = new Mock>(); + _sut = new BoilerMonitorEntityService( + _entityManagerMock.Object, + _haContextMock.Object, + _loggerMock.Object); + } + + private void SetupEntityState(string entityId, string? state) + { + if (state is null) + { + _haContextMock.Setup(h => h.GetState(entityId)).Returns((EntityState?)null); + } + else + { + _haContextMock.Setup(h => h.GetState(entityId)) + .Returns(new EntityState { State = state }); + } + } + + #region ReadPersistedState + + [Fact] + public void ReadPersistedState_WithValidState_ShouldReturnPersistedValues() + { + // Arrange + SetupEntityState(TodayRuntimeEntityId, "3600"); + SetupEntityState(SessionCountEntityId, "5"); + SetupEntityState(SkipPriceCapEntityId, "ON"); + SetupEntityState(BudgetOverrideEntityId, "OFF"); + + // Act + var result = _sut.ReadPersistedState(); + + // Assert + result.Should().NotBeNull(); + result!.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(3600)); + result.SessionCount.Should().Be(5); + result.SkipPriceCapState.Should().Be("ON"); + result.BudgetOverrideState.Should().Be("OFF"); + } + + [Fact] + public void ReadPersistedState_WithZeroRuntime_ShouldReturnZeroValues() + { + // Arrange + SetupEntityState(TodayRuntimeEntityId, "0"); + SetupEntityState(SessionCountEntityId, "0"); + SetupEntityState(SkipPriceCapEntityId, "OFF"); + SetupEntityState(BudgetOverrideEntityId, "OFF"); + + // Act + var result = _sut.ReadPersistedState(); + + // Assert + result.Should().NotBeNull(); + result!.AccumulatedRunTime.Should().Be(TimeSpan.Zero); + result.SessionCount.Should().Be(0); + } + + [Fact] + public void ReadPersistedState_WhenRuntimeIsUnavailable_ShouldReturnNull() + { + // Arrange + SetupEntityState(TodayRuntimeEntityId, "unavailable"); + SetupEntityState(SessionCountEntityId, "5"); + SetupEntityState(SkipPriceCapEntityId, "OFF"); + SetupEntityState(BudgetOverrideEntityId, "OFF"); + + // Act + var result = _sut.ReadPersistedState(); + + // Assert + result.Should().BeNull(); + } + + [Fact] + public void ReadPersistedState_WhenRuntimeIsUnknown_ShouldReturnNull() + { + // Arrange + SetupEntityState(TodayRuntimeEntityId, "unknown"); + SetupEntityState(SessionCountEntityId, "3"); + SetupEntityState(SkipPriceCapEntityId, "OFF"); + SetupEntityState(BudgetOverrideEntityId, "OFF"); + + // Act + var result = _sut.ReadPersistedState(); + + // Assert + result.Should().BeNull(); + } + + [Fact] + public void ReadPersistedState_WhenSessionCountIsUnavailable_ShouldReturnNull() + { + // Arrange + SetupEntityState(TodayRuntimeEntityId, "1800"); + SetupEntityState(SessionCountEntityId, "unavailable"); + SetupEntityState(SkipPriceCapEntityId, "OFF"); + SetupEntityState(BudgetOverrideEntityId, "OFF"); + + // Act + var result = _sut.ReadPersistedState(); + + // Assert + result.Should().BeNull(); + } + + [Fact] + public void ReadPersistedState_WhenRuntimeEntityDoesNotExist_ShouldReturnNull() + { + // Arrange + SetupEntityState(TodayRuntimeEntityId, null); + SetupEntityState(SessionCountEntityId, "3"); + SetupEntityState(SkipPriceCapEntityId, "OFF"); + SetupEntityState(BudgetOverrideEntityId, "OFF"); + + // Act + var result = _sut.ReadPersistedState(); + + // Assert + result.Should().BeNull(); + } + + [Fact] + public void ReadPersistedState_WhenSessionCountEntityDoesNotExist_ShouldReturnNull() + { + // Arrange + SetupEntityState(TodayRuntimeEntityId, "1800"); + SetupEntityState(SessionCountEntityId, null); + SetupEntityState(SkipPriceCapEntityId, "OFF"); + SetupEntityState(BudgetOverrideEntityId, "OFF"); + + // Act + var result = _sut.ReadPersistedState(); + + // Assert + result.Should().BeNull(); + } + + [Fact] + public void ReadPersistedState_WhenRuntimeIsNonNumeric_ShouldReturnNull() + { + // Arrange + SetupEntityState(TodayRuntimeEntityId, "not_a_number"); + SetupEntityState(SessionCountEntityId, "3"); + SetupEntityState(SkipPriceCapEntityId, "OFF"); + SetupEntityState(BudgetOverrideEntityId, "OFF"); + + // Act + var result = _sut.ReadPersistedState(); + + // Assert + result.Should().BeNull(); + } + + [Fact] + public void ReadPersistedState_WhenSessionCountIsNonNumeric_ShouldReturnNull() + { + // Arrange + SetupEntityState(TodayRuntimeEntityId, "1800"); + SetupEntityState(SessionCountEntityId, "abc"); + SetupEntityState(SkipPriceCapEntityId, "OFF"); + SetupEntityState(BudgetOverrideEntityId, "OFF"); + + // Act + var result = _sut.ReadPersistedState(); + + // Assert + result.Should().BeNull(); + } + + [Fact] + public void ReadPersistedState_WhenRuntimeIsNegative_ShouldReturnNull() + { + // Arrange + SetupEntityState(TodayRuntimeEntityId, "-100"); + SetupEntityState(SessionCountEntityId, "3"); + SetupEntityState(SkipPriceCapEntityId, "OFF"); + SetupEntityState(BudgetOverrideEntityId, "OFF"); + + // Act + var result = _sut.ReadPersistedState(); + + // Assert + result.Should().BeNull(); + } + + [Fact] + public void ReadPersistedState_WhenSessionCountIsNegative_ShouldReturnNull() + { + // Arrange + SetupEntityState(TodayRuntimeEntityId, "1800"); + SetupEntityState(SessionCountEntityId, "-1"); + SetupEntityState(SkipPriceCapEntityId, "OFF"); + SetupEntityState(BudgetOverrideEntityId, "OFF"); + + // Act + var result = _sut.ReadPersistedState(); + + // Assert + result.Should().BeNull(); + } + + [Fact] + public void ReadPersistedState_WhenSwitchEntitiesAreNull_ShouldStillReturnWithNullSwitchStates() + { + // Arrange + SetupEntityState(TodayRuntimeEntityId, "900"); + SetupEntityState(SessionCountEntityId, "2"); + SetupEntityState(SkipPriceCapEntityId, null); + SetupEntityState(BudgetOverrideEntityId, null); + + // Act + var result = _sut.ReadPersistedState(); + + // Assert + result.Should().NotBeNull(); + result!.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(900)); + result.SessionCount.Should().Be(2); + result.SkipPriceCapState.Should().BeNull(); + result.BudgetOverrideState.Should().BeNull(); + } + + [Theory] + [InlineData("")] // empty string + [InlineData(" ")] // whitespace + public void ReadPersistedState_WhenRuntimeIsEmptyOrWhitespace_ShouldReturnNull(string state) + { + // Arrange + SetupEntityState(TodayRuntimeEntityId, state); + SetupEntityState(SessionCountEntityId, "3"); + SetupEntityState(SkipPriceCapEntityId, "OFF"); + SetupEntityState(BudgetOverrideEntityId, "OFF"); + + // Act + var result = _sut.ReadPersistedState(); + + // Assert + result.Should().BeNull(); + } + + [Fact] + public void ReadPersistedState_WithDecimalRuntime_ShouldParseCorrectly() + { + // Arrange + SetupEntityState(TodayRuntimeEntityId, "1800.5"); + SetupEntityState(SessionCountEntityId, "2"); + SetupEntityState(SkipPriceCapEntityId, "OFF"); + SetupEntityState(BudgetOverrideEntityId, "OFF"); + + // Act + var result = _sut.ReadPersistedState(); + + // Assert + result.Should().NotBeNull(); + result!.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(1800.5)); + } + + #endregion + + #region ResetTransientEntitiesAsync + + [Fact] + public async Task ResetTransientEntitiesAsync_ShouldResetStatusAndWaterReady() + { + // Arrange + _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) + .Returns(Task.CompletedTask); + + // Act + await _sut.ResetTransientEntitiesAsync(); + + // Assert + _entityManagerMock.Verify(em => em.SetEntityState(StatusEntityId, StatusAwaitingConfiguration), Times.Once); + _entityManagerMock.Verify(em => em.SetEntityState(WaterReadyEntityId, "unknown"), Times.Once); + } + + [Fact] + public async Task ResetTransientEntitiesAsync_ShouldNotResetRuntimeEntities() + { + // Arrange + _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) + .Returns(Task.CompletedTask); + + // Act + await _sut.ResetTransientEntitiesAsync(); + + // Assert + _entityManagerMock.Verify(em => em.SetEntityState(TodayRuntimeEntityId, It.IsAny()), Times.Never); + _entityManagerMock.Verify(em => em.SetEntityState(SessionCountEntityId, It.IsAny()), Times.Never); + _entityManagerMock.Verify(em => em.SetEntityState(BudgetPercentageEntityId, It.IsAny()), Times.Never); + _entityManagerMock.Verify(em => em.SetEntityState(BudgetExhaustedEntityId, It.IsAny()), Times.Never); + _entityManagerMock.Verify(em => em.SetEntityState(RemainingTimeEntityId, It.IsAny()), Times.Never); + } + + [Fact] + public async Task ResetTransientEntitiesAsync_ShouldNotResetSwitchEntities() + { + // Arrange + _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) + .Returns(Task.CompletedTask); + + // Act + await _sut.ResetTransientEntitiesAsync(); + + // Assert + _entityManagerMock.Verify(em => em.SetEntityState(SkipPriceCapEntityId, It.IsAny()), Times.Never); + _entityManagerMock.Verify(em => em.SetEntityState(BudgetOverrideEntityId, It.IsAny()), Times.Never); + } + + #endregion +} diff --git a/BoilerMonitor.Manager.Tests/BoilerMonitorOptionsTests.cs b/BoilerMonitor.Manager.Tests/BoilerMonitorOptionsTests.cs new file mode 100644 index 0000000..853e5e2 --- /dev/null +++ b/BoilerMonitor.Manager.Tests/BoilerMonitorOptionsTests.cs @@ -0,0 +1,29 @@ +using FluentAssertions; +using BoilerMonitorManager.Models; + +namespace BoilerMonitor.Manager.Tests; + +public class BoilerMonitorOptionsTests +{ + [Fact] + public void Defaults_ShouldHaveEnabledTrue() + { + var options = new BoilerMonitorOptions(); + + options.Enabled.Should().BeTrue(); + } + + [Fact] + public void SectionName_ShouldBeBoilerMonitor() + { + BoilerMonitorOptions.SectionName.Should().Be("BoilerMonitor"); + } + + [Fact] + public void Enabled_WhenSetToFalse_ShouldReturnFalse() + { + var options = new BoilerMonitorOptions { Enabled = false }; + + options.Enabled.Should().BeFalse(); + } +} diff --git a/BoilerMonitor.Manager.Tests/BoilerRunTimeTrackerTests.cs b/BoilerMonitor.Manager.Tests/BoilerRunTimeTrackerTests.cs new file mode 100644 index 0000000..053232a --- /dev/null +++ b/BoilerMonitor.Manager.Tests/BoilerRunTimeTrackerTests.cs @@ -0,0 +1,254 @@ +using FluentAssertions; +using BoilerMonitorManager; + +namespace BoilerMonitor.Manager.Tests; + +public class BoilerRunTimeTrackerTests +{ + private readonly BoilerRunTimeTracker _sut = new(); + + #region RecordPollResult + + [Fact] + public void RecordPollResult_WhenHeating_ShouldAccumulateRunTime() + { + var interval = TimeSpan.FromSeconds(30); + + _sut.RecordPollResult(true, interval); + _sut.RecordPollResult(true, interval); + _sut.RecordPollResult(true, interval); + + var snapshot = _sut.GetSnapshot(); + snapshot.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(90)); + } + + [Fact] + public void RecordPollResult_WhenNotHeating_ShouldNotAccumulate() + { + var interval = TimeSpan.FromSeconds(30); + + _sut.RecordPollResult(false, interval); + _sut.RecordPollResult(false, interval); + + var snapshot = _sut.GetSnapshot(); + snapshot.AccumulatedRunTime.Should().Be(TimeSpan.Zero); + } + + [Fact] + public void RecordPollResult_WhenHeatingStarts_ShouldIncrementSessionCount() + { + var interval = TimeSpan.FromSeconds(30); + + _sut.RecordPollResult(true, interval); + + var snapshot = _sut.GetSnapshot(); + snapshot.SessionCount.Should().Be(1); + } + + [Fact] + public void RecordPollResult_ContinuousHeating_ShouldCountAsOneSession() + { + var interval = TimeSpan.FromSeconds(30); + + _sut.RecordPollResult(true, interval); + _sut.RecordPollResult(true, interval); + _sut.RecordPollResult(true, interval); + + var snapshot = _sut.GetSnapshot(); + snapshot.SessionCount.Should().Be(1); + } + + [Fact] + public void RecordPollResult_HeatingStopsAndRestarts_ShouldCountAsTwoSessions() + { + var interval = TimeSpan.FromSeconds(30); + + _sut.RecordPollResult(true, interval); + _sut.RecordPollResult(false, interval); + _sut.RecordPollResult(true, interval); + + var snapshot = _sut.GetSnapshot(); + snapshot.SessionCount.Should().Be(2); + } + + [Fact] + public void RecordPollResult_MultipleSessions_ShouldAccumulateCorrectly() + { + var interval = TimeSpan.FromSeconds(30); + + _sut.RecordPollResult(true, interval); + _sut.RecordPollResult(true, interval); + _sut.RecordPollResult(false, interval); + _sut.RecordPollResult(true, interval); + + var snapshot = _sut.GetSnapshot(); + snapshot.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(90)); + snapshot.SessionCount.Should().Be(2); + } + + [Fact] + public void RecordPollResult_WhenHeating_ShouldSetIsInSessionTrue() + { + _sut.RecordPollResult(true, TimeSpan.FromSeconds(30)); + + var snapshot = _sut.GetSnapshot(); + snapshot.IsInSession.Should().BeTrue(); + } + + [Fact] + public void RecordPollResult_WhenNotHeating_ShouldSetIsInSessionFalse() + { + _sut.RecordPollResult(true, TimeSpan.FromSeconds(30)); + _sut.RecordPollResult(false, TimeSpan.FromSeconds(30)); + + var snapshot = _sut.GetSnapshot(); + snapshot.IsInSession.Should().BeFalse(); + } + + #endregion + + #region Reset + + [Fact] + public void Reset_ShouldClearAllState() + { + var interval = TimeSpan.FromSeconds(30); + _sut.RecordPollResult(true, interval); + _sut.RecordPollResult(true, interval); + + _sut.Reset(); + + var snapshot = _sut.GetSnapshot(); + snapshot.AccumulatedRunTime.Should().Be(TimeSpan.Zero); + snapshot.SessionCount.Should().Be(0); + snapshot.IsInSession.Should().BeFalse(); + } + + [Fact] + public void Reset_AfterReset_ShouldAccumulateFromZero() + { + var interval = TimeSpan.FromSeconds(30); + _sut.RecordPollResult(true, interval); + _sut.Reset(); + _sut.RecordPollResult(true, interval); + + var snapshot = _sut.GetSnapshot(); + snapshot.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(30)); + snapshot.SessionCount.Should().Be(1); + } + + #endregion + + #region RestoreFromSnapshot + + [Fact] + public void RestoreFromSnapshot_ShouldSetAccumulatedRunTimeAndSessionCount() + { + // Arrange + var runTime = TimeSpan.FromMinutes(45); + const int sessionCount = 3; + + // Act + _sut.RestoreFromSnapshot(runTime, sessionCount); + + // Assert + var snapshot = _sut.GetSnapshot(); + snapshot.AccumulatedRunTime.Should().Be(runTime); + snapshot.SessionCount.Should().Be(sessionCount); + snapshot.IsInSession.Should().BeFalse(); + } + + [Fact] + public void RestoreFromSnapshot_ShouldOverwriteExistingState() + { + // Arrange + _sut.RecordPollResult(true, TimeSpan.FromSeconds(30)); + _sut.RecordPollResult(true, TimeSpan.FromSeconds(30)); + + var restoredRunTime = TimeSpan.FromHours(2); + const int restoredSessions = 5; + + // Act + _sut.RestoreFromSnapshot(restoredRunTime, restoredSessions); + + // Assert + var snapshot = _sut.GetSnapshot(); + snapshot.AccumulatedRunTime.Should().Be(restoredRunTime); + snapshot.SessionCount.Should().Be(restoredSessions); + } + + [Fact] + public void RestoreFromSnapshot_ShouldAllowFurtherAccumulationFromRestoredState() + { + // Arrange + var restoredRunTime = TimeSpan.FromMinutes(30); + const int restoredSessions = 2; + var pollInterval = TimeSpan.FromSeconds(30); + + _sut.RestoreFromSnapshot(restoredRunTime, restoredSessions); + + // Act + _sut.RecordPollResult(true, pollInterval); + + // Assert + var snapshot = _sut.GetSnapshot(); + snapshot.AccumulatedRunTime.Should().Be(restoredRunTime + pollInterval); + snapshot.SessionCount.Should().Be(restoredSessions + 1); + } + + [Fact] + public void RestoreFromSnapshot_WithZeroValues_ShouldSetToZero() + { + // Arrange + _sut.RecordPollResult(true, TimeSpan.FromSeconds(30)); + + // Act + _sut.RestoreFromSnapshot(TimeSpan.Zero, 0); + + // Assert + var snapshot = _sut.GetSnapshot(); + snapshot.AccumulatedRunTime.Should().Be(TimeSpan.Zero); + snapshot.SessionCount.Should().Be(0); + } + + #endregion + + #region Thread safety + + [Fact] + public async Task RecordPollResult_ConcurrentCalls_ShouldNotCorruptState() + { + var interval = TimeSpan.FromSeconds(1); + const int iterationsPerThread = 1000; + const int threadCount = 4; + + var tasks = Enumerable.Range(0, threadCount).Select(_ => Task.Run(() => + { + for (var i = 0; i < iterationsPerThread; i++) + { + _sut.RecordPollResult(true, interval); + } + })).ToArray(); + + await Task.WhenAll(tasks); + + var snapshot = _sut.GetSnapshot(); + snapshot.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(iterationsPerThread * threadCount)); + } + + #endregion + + #region GetSnapshot + + [Fact] + public void GetSnapshot_Initial_ShouldReturnZeroState() + { + var snapshot = _sut.GetSnapshot(); + + snapshot.AccumulatedRunTime.Should().Be(TimeSpan.Zero); + snapshot.SessionCount.Should().Be(0); + snapshot.IsInSession.Should().BeFalse(); + } + + #endregion +} diff --git a/BoilerMonitor.Manager.Tests/WaterReadyServiceTests.cs b/BoilerMonitor.Manager.Tests/WaterReadyServiceTests.cs new file mode 100644 index 0000000..1657a59 --- /dev/null +++ b/BoilerMonitor.Manager.Tests/WaterReadyServiceTests.cs @@ -0,0 +1,430 @@ +using BoilerMonitor.Models; +using FluentAssertions; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Time.Testing; +using Moq; +using BoilerMonitorManager; + +namespace BoilerMonitor.Manager.Tests; + +public class WaterReadyServiceTests +{ + private readonly Mock> _loggerMock; + private readonly FakeTimeProvider _timeProvider; + + public WaterReadyServiceTests() + { + _loggerMock = new Mock>(); + _timeProvider = new FakeTimeProvider(DateTimeOffset.UtcNow); + } + + private WaterReadyService CreateSut() + { + return new WaterReadyService(_loggerMock.Object, _timeProvider); + } + + #region IsWaterReady — basic behavior (no grace period active) + + [Fact] + public void IsWaterReady_SwitchOnAndLowPower_ShouldReturnTrue() + { + // Arrange + var sut = CreateSut(); + + // Act + var result = sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + + // Assert + result.Should().BeTrue(); + } + + [Fact] + public void IsWaterReady_SwitchOnAndPowerBelowThreshold_ShouldReturnTrue() + { + // Arrange + var sut = CreateSut(); + + // Act + var result = sut.IsWaterReady("on", 4.9, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + + // Assert + result.Should().BeTrue(); + } + + [Fact] + public void IsWaterReady_SwitchOnAndPowerAtThreshold_ShouldReturnFalse() + { + // Arrange + var sut = CreateSut(); + + // Act + var result = sut.IsWaterReady("on", 5.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + + // Assert + result.Should().BeFalse(); + } + + [Fact] + public void IsWaterReady_SwitchOnAndHighPower_ShouldReturnFalse() + { + // Arrange + var sut = CreateSut(); + + // Act + var result = sut.IsWaterReady("on", 2000.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + + // Assert + result.Should().BeFalse(); + } + + [Fact] + public void IsWaterReady_SwitchOff_ShouldReturnFalse() + { + // Arrange + var sut = CreateSut(); + + // Act + var result = sut.IsWaterReady("off", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + + // Assert + result.Should().BeFalse(); + } + + [Fact] + public void IsWaterReady_NullSwitchState_ShouldReturnFalse() + { + // Arrange + var sut = CreateSut(); + + // Act + var result = sut.IsWaterReady(null, 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + + // Assert + result.Should().BeFalse(); + } + + [Fact] + public void IsWaterReady_NullPowerWatts_ShouldReturnFalse() + { + // Arrange + var sut = CreateSut(); + + // Act + var result = sut.IsWaterReady("on", null, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + + // Assert + result.Should().BeFalse(); + } + + [Fact] + public void IsWaterReady_BothNull_ShouldReturnFalse() + { + // Arrange + var sut = CreateSut(); + + // Act + var result = sut.IsWaterReady(null, null, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + + // Assert + result.Should().BeFalse(); + } + + [Theory] + [InlineData("ON")] + [InlineData("On")] + [InlineData("on")] + public void IsWaterReady_SwitchOnCaseInsensitive_ShouldReturnTrue(string switchState) + { + // Arrange + var sut = CreateSut(); + + // Act + var result = sut.IsWaterReady(switchState, 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + + // Assert + result.Should().BeTrue(); + } + + [Theory] + [InlineData(9.9, 10.0, true)] + [InlineData(10.0, 10.0, false)] + [InlineData(10.1, 10.0, false)] + public void IsWaterReady_CustomThreshold_ShouldUseProvidedValue(double powerWatts, double threshold, bool expected) + { + // Arrange — fresh instance per case to avoid cooldown side-effects + var sut = CreateSut(); + + // Act + var result = sut.IsWaterReady("on", powerWatts, threshold); + + // Assert + result.Should().Be(expected); + } + + #endregion + + #region Warm-up grace period + + [Fact] + public void IsWaterReady_DuringGracePeriod_ShouldReturnFalse() + { + // Arrange + var sut = CreateSut(); + sut.NotifyTurnedOn(); + + // Act — still within grace period, low power should be suppressed + var result = sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + + // Assert + result.Should().BeFalse(); + } + + [Fact] + public void IsWaterReady_AfterGracePeriodExpires_ShouldReturnTrue() + { + // Arrange + var sut = CreateSut(); + sut.NotifyTurnedOn(); + _timeProvider.Advance(BoilerMonitorConsts.WarmUpGracePeriod); + + // Act — grace period has elapsed, low power means water is ready + var result = sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + + // Assert + result.Should().BeTrue(); + } + + [Fact] + public void IsWaterReady_DuringGracePeriodWithHighPower_ShouldReturnFalse() + { + // Arrange + var sut = CreateSut(); + sut.NotifyTurnedOn(); + + // Act — high power during grace period is still "not ready" (heating) + var result = sut.IsWaterReady("on", 2000.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + + // Assert + result.Should().BeFalse(); + } + + [Fact] + public void IsWaterReady_JustBeforeGracePeriodExpires_ShouldReturnFalse() + { + // Arrange + var sut = CreateSut(); + sut.NotifyTurnedOn(); + _timeProvider.Advance(BoilerMonitorConsts.WarmUpGracePeriod - TimeSpan.FromSeconds(1)); + + // Act + var result = sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + + // Assert + result.Should().BeFalse(); + } + + [Fact] + public void IsWaterReady_WithoutNotifyTurnedOn_ShouldNotApplyGracePeriod() + { + // Arrange — no NotifyTurnedOn call, so no grace period should be active + var sut = CreateSut(); + + // Act + var result = sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + + // Assert + result.Should().BeTrue(); + } + + [Fact] + public void IsWaterReady_MultipleTurnOns_ShouldResetGracePeriod() + { + // Arrange + var sut = CreateSut(); + sut.NotifyTurnedOn(); + _timeProvider.Advance(BoilerMonitorConsts.WarmUpGracePeriod - TimeSpan.FromSeconds(10)); + + // Act — second turn-on resets the grace period + sut.NotifyTurnedOn(); + _timeProvider.Advance(TimeSpan.FromSeconds(10)); + + var result = sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + + // Assert — still within the new grace period + result.Should().BeFalse(); + } + + [Fact] + public void IsWaterReady_SwitchOffDuringGracePeriod_ShouldReturnFalse() + { + // Arrange + var sut = CreateSut(); + sut.NotifyTurnedOn(); + + // Act — switch is off, so not ready regardless of grace period + var result = sut.IsWaterReady("off", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + + // Assert + result.Should().BeFalse(); + } + + #endregion + + #region Water ready cooldown period + + [Fact] + public void IsWaterReady_DuringCooldown_ShouldReturnTrueRegardlessOfSwitchState() + { + // Arrange — trigger water ready detection, then turn switch off + var sut = CreateSut(); + sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + + // Act — switch is now off, but cooldown should keep reporting ready + var result = sut.IsWaterReady("off", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + + // Assert + result.Should().BeTrue(); + } + + [Fact] + public void IsWaterReady_DuringCooldown_ShouldReturnTrueEvenWithNullState() + { + // Arrange + var sut = CreateSut(); + sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + + // Act + var result = sut.IsWaterReady(null, null, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + + // Assert + result.Should().BeTrue(); + } + + [Fact] + public void IsWaterReady_AfterCooldownExpires_ShouldResumeNormalDetection() + { + // Arrange + var sut = CreateSut(); + sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + _timeProvider.Advance(BoilerMonitorConsts.WaterReadyCooldownPeriod); + + // Act — cooldown expired, switch is off → not ready + var result = sut.IsWaterReady("off", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + + // Assert + result.Should().BeFalse(); + } + + [Fact] + public void IsWaterReady_JustBeforeCooldownExpires_ShouldStillReturnTrue() + { + // Arrange + var sut = CreateSut(); + sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + _timeProvider.Advance(BoilerMonitorConsts.WaterReadyCooldownPeriod - TimeSpan.FromSeconds(1)); + + // Act + var result = sut.IsWaterReady("off", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + + // Assert + result.Should().BeTrue(); + } + + [Fact] + public void IsInCooldown_WhenCooldownActive_ShouldReturnTrue() + { + // Arrange + var sut = CreateSut(); + sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + + // Act & Assert + sut.IsInCooldown.Should().BeTrue(); + } + + [Fact] + public void IsInCooldown_WhenNoCooldownTriggered_ShouldReturnFalse() + { + // Arrange + var sut = CreateSut(); + + // Act & Assert + sut.IsInCooldown.Should().BeFalse(); + } + + [Fact] + public void IsInCooldown_AfterCooldownExpires_ShouldReturnFalse() + { + // Arrange + var sut = CreateSut(); + sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + _timeProvider.Advance(BoilerMonitorConsts.WaterReadyCooldownPeriod); + + // Act & Assert + sut.IsInCooldown.Should().BeFalse(); + } + + [Fact] + public void ResetCooldown_ShouldClearActiveCooldown() + { + // Arrange + var sut = CreateSut(); + sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + sut.IsInCooldown.Should().BeTrue(); + + // Act + sut.ResetCooldown(); + + // Assert + sut.IsInCooldown.Should().BeFalse(); + } + + [Fact] + public void ResetCooldown_ShouldAllowBoilerToTurnOnAgain() + { + // Arrange — water becomes ready, then cooldown is reset (midnight) + var sut = CreateSut(); + sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + sut.ResetCooldown(); + + // Act — switch is off, no power → not ready (normal detection resumes) + var result = sut.IsWaterReady("off", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + + // Assert + result.Should().BeFalse(); + } + + [Fact] + public void IsWaterReady_CooldownOnlySetOnFirstDetection_ShouldNotResetTimestamp() + { + // Arrange — first detection sets _waterReadySince + var sut = CreateSut(); + sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + + // Advance halfway through cooldown + _timeProvider.Advance(BoilerMonitorConsts.WaterReadyCooldownPeriod / 2); + + // Act — second detection during cooldown should NOT reset the timestamp + sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + + // Advance remaining half + _timeProvider.Advance(BoilerMonitorConsts.WaterReadyCooldownPeriod / 2); + + // Assert — cooldown should have expired based on original timestamp + sut.IsInCooldown.Should().BeFalse(); + } + + [Fact] + public void IsWaterReady_HighPowerDoesNotTriggerCooldown_ShouldReturnFalse() + { + // Arrange + var sut = CreateSut(); + + // Act — water is not ready (high power), no cooldown should be triggered + sut.IsWaterReady("on", 2000.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + + // Assert + sut.IsInCooldown.Should().BeFalse(); + } + + #endregion +} diff --git a/BoilerMonitor.Manager/BoilerConfigReader.cs b/BoilerMonitor.Manager/BoilerConfigReader.cs new file mode 100644 index 0000000..e9f33c2 --- /dev/null +++ b/BoilerMonitor.Manager/BoilerConfigReader.cs @@ -0,0 +1,49 @@ +using System.Globalization; +using BoilerMonitor.Models; +using Microsoft.Extensions.Logging; +using NetDaemon.HassModel; +using static BoilerMonitor.Models.BoilerMonitorConsts; +using static NordPool.Models.NordPoolConsts; + +namespace BoilerMonitorManager; + +public sealed class BoilerConfigReader(IHaContext haContext, ILogger logger) : IBoilerConfigReader +{ + private const double DefaultDailyHours = 1.0; + + public BoilerConfig ReadConfig() + { + var dailyHoursState = haContext.GetState(BoilerDailyHoursEntityId)?.State; + var dailyHours = double.TryParse(dailyHoursState, NumberStyles.Any, CultureInfo.InvariantCulture, out var dh) ? dh : DefaultDailyHours; + + var intervalCount = (int)(dailyHours * IntervalsPerHour); + if (intervalCount <= 0) + { + intervalCount = IntervalsPerHour; + } + + var priceCapState = haContext.GetState(BoilerPriceCapEntityId)?.State; + var priceCap = double.TryParse(priceCapState, NumberStyles.Any, CultureInfo.InvariantCulture, out var pc) && pc > 0 ? pc : double.MaxValue; + + var deadline = DateTime.Today.AddDays(1); + var readyByState = haContext.GetState(BoilerReadyByEntityId)?.State; + if (!string.IsNullOrEmpty(readyByState) && TimeSpan.TryParse(readyByState, out var readyByTime)) + { + deadline = DateTime.Today.Add(readyByTime); + } + + var skipPriceCapState = haContext.GetState(SkipPriceCapEntityId)?.State; + var skipPriceCap = string.Equals(skipPriceCapState, SwitchOnState, StringComparison.OrdinalIgnoreCase); + + logger.LogDebug("Boiler config: intervals={Intervals}, priceCap={Cap}, skipPriceCap={Skip}, deadline={Deadline}", + intervalCount, priceCap, skipPriceCap, deadline); + + return new BoilerConfig + { + IntervalCount = intervalCount, + PriceCap = priceCap, + Deadline = deadline, + SkipPriceCap = skipPriceCap + }; + } +} diff --git a/BoilerMonitor.Manager/BoilerControlService.cs b/BoilerMonitor.Manager/BoilerControlService.cs new file mode 100644 index 0000000..52bf7c6 --- /dev/null +++ b/BoilerMonitor.Manager/BoilerControlService.cs @@ -0,0 +1,53 @@ +using BoilerMonitor.Models.Enums; +using BoilerMonitorManager.Interface; +using Microsoft.Extensions.Logging; + +namespace BoilerMonitorManager; + +public class BoilerControlService(ILogger logger) : IBoilerControlService +{ + private const string SwitchOnState = "on"; + + public BoilerAction DetermineAction(bool isNowCheap, bool waterReady, string? currentSwitchState, bool budgetExhausted, bool budgetOverride) + { + var isCurrentlyOn = string.Equals(currentSwitchState, SwitchOnState, StringComparison.OrdinalIgnoreCase); + var effectiveBudgetExhausted = budgetExhausted && !budgetOverride; + var shouldBeOn = isNowCheap && !waterReady && !effectiveBudgetExhausted; + + if (shouldBeOn && !isCurrentlyOn) + { + logger.LogInformation("Boiler should turn ON — cheap interval active, water not ready, budget available (current state: {State})", currentSwitchState); + + return BoilerAction.TurnOn; + } + + if (!shouldBeOn && isCurrentlyOn) + { + var reason = GetTurnOffReason(waterReady, isNowCheap, effectiveBudgetExhausted); + + logger.LogInformation("Boiler should turn OFF — {Reason} (current state: {State})", reason, currentSwitchState); + + return BoilerAction.TurnOff; + } + + logger.LogDebug("Boiler state unchanged: {State} (cheap={Cheap}, waterReady={WaterReady}, budgetExhausted={BudgetExhausted})", + currentSwitchState, isNowCheap, waterReady, effectiveBudgetExhausted); + + return BoilerAction.NoChange; + } + + private static string GetTurnOffReason(bool waterReady, bool isNowCheap, bool effectiveBudgetExhausted) + { + if (waterReady) + { + return "water is already ready"; + } + + if (effectiveBudgetExhausted) + { + return "daily budget is exhausted"; + } + + return "not in a cheap interval"; + } +} diff --git a/BoilerMonitor.Manager/BoilerMonitor.Manager.csproj b/BoilerMonitor.Manager/BoilerMonitor.Manager.csproj new file mode 100644 index 0000000..6f5297d --- /dev/null +++ b/BoilerMonitor.Manager/BoilerMonitor.Manager.csproj @@ -0,0 +1,27 @@ + + + + net10.0 + enable + enable + BoilerMonitorManager + + + + + <_Parameter1>BoilerMonitor.Manager.Tests + + + + + + + + + + + + + + + diff --git a/BoilerMonitor.Manager/BoilerMonitorEntityService.cs b/BoilerMonitor.Manager/BoilerMonitorEntityService.cs new file mode 100644 index 0000000..97f2590 --- /dev/null +++ b/BoilerMonitor.Manager/BoilerMonitorEntityService.cs @@ -0,0 +1,465 @@ +using System.Globalization; +using BoilerMonitor.Models; +using BoilerMonitorManager.Interface; +using BoilerMonitorManager.Models; +using HomeAssistant.Entities.Interfaces; +using Microsoft.Extensions.Logging; +using NetDaemon.Extensions.MqttEntityManager; +using NetDaemon.HassModel; +using static BoilerMonitor.Models.BoilerMonitorConsts; + +namespace BoilerMonitorManager; + +public sealed class BoilerMonitorEntityService( + IEntityManager entityManager, + IHaContext haContext, + ILogger logger) : IBoilerMonitorEntityService +{ + private static readonly string[] CleanableEntityIds = + [ + ConfigPowerEntityId, + ConfigSwitchEntityId, + ConfigPollIntervalEntityId, + ConfigHeatingThresholdEntityId, + StatusEntityId, + WaterReadyEntityId, + SkipPriceCapEntityId, + TodayRuntimeEntityId, + RemainingTimeEntityId, + BudgetPercentageEntityId, + BudgetExhaustedEntityId, + SessionCountEntityId, + BudgetOverrideEntityId + ]; + + private static object CreateDeviceBlock() => new + { + identifiers = new[] { DeviceIdentifier }, + name = DeviceName, + model = DeviceName, + manufacturer = DeviceManufacturer + }; + + public async Task CreateEntitiesAsync(CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + + var entities = GetAllEntities(); + + var createTasks = entities.Select(async entity => + { + try + { + logger.LogInformation("Creating/re-registering MQTT entity: {EntityId}", entity.EntityId); + await entityManager.CreateEntityAsync(entity).ConfigureAwait(false); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to create MQTT entity: {EntityId}", entity.EntityId); + } + }); + + await Task.WhenAll(createTasks).ConfigureAwait(false); + } + + public async Task ResetEntitiesAsync(CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + + logger.LogInformation("Resetting all BoilerMonitor runtime entity states to defaults"); + + await Task.WhenAll( + ResetStatusAsync(), + ResetWaterReadyAsync(), + ResetSkipPriceCapAsync(), + ResetTodayRuntimeAsync(), + ResetRemainingTimeAsync(), + ResetBudgetPercentageAsync(), + ResetBudgetExhaustedAsync(), + ResetSessionCountAsync(), + ResetBudgetOverrideAsync() + ).ConfigureAwait(false); + + logger.LogInformation("All BoilerMonitor runtime entity states reset to defaults"); + } + + public async Task UpdateEntitiesAsync(BoilerMonitorUpdateContext ctx, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + + var timestamp = DateTime.UtcNow.ToString("O"); + var formattedRunTime = FormatTimeSpan(ctx.TodayRunTime); + var formattedRemaining = FormatTimeSpan(ctx.RemainingTime); + + // logger.LogInformation("Updating BoilerMonitor entities: runtime={RunTime}, remaining={Remaining}, budget={Budget}%, sessions={Sessions}", + // formattedRunTime, formattedRemaining, ctx.BudgetPercentage, ctx.SessionCount); + + var updateTasks = new[] + { + UpdateStatusAsync(StatusConfigured), + UpdateWaterReadyAsync(ctx, timestamp), + UpdateTodayRuntimeAsync(ctx.TodayRunTime, formattedRunTime, timestamp), + UpdateRemainingTimeAsync(ctx.RemainingTime, formattedRemaining, ctx.BudgetHours, timestamp), + UpdateBudgetPercentageAsync(ctx.BudgetPercentage, timestamp), + UpdateBudgetExhaustedAsync(ctx.BudgetExhausted), + UpdateSessionCountAsync(ctx.SessionCount, timestamp) + }; + + await Task.WhenAll(updateTasks).ConfigureAwait(false); + } + + public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + + try + { + var removeTasks = CleanableEntityIds.Select(entityId => entityManager.RemoveEntity(entityId)); + await Task.WhenAll(removeTasks).ConfigureAwait(false); + + logger.LogInformation("BoilerMonitor entities cleaned up successfully (cleanup button retained)"); + } + catch (Exception ex) + { + logger.LogError(ex, "Error cleaning up BoilerMonitor entities"); + throw; + } + } + + public async Task ResetTransientEntitiesAsync(CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + + logger.LogInformation("Resetting transient BoilerMonitor entity states (status, water ready)"); + + await Task.WhenAll( + ResetStatusAsync(), + ResetWaterReadyAsync() + ).ConfigureAwait(false); + } + + public PersistedBoilerState? ReadPersistedState() + { + try + { + var runtimeState = haContext.GetState(TodayRuntimeEntityId)?.State; + var sessionCountState = haContext.GetState(SessionCountEntityId)?.State; + var skipPriceCapState = haContext.GetState(SkipPriceCapEntityId)?.State; + var budgetOverrideState = haContext.GetState(BudgetOverrideEntityId)?.State; + + if (!TryParseEntitySeconds(runtimeState, out var runtimeSeconds) + || !TryParseEntityInt(sessionCountState, out var sessionCount)) + { + logger.LogInformation("No valid persisted BoilerMonitor state found in HA entities (runtime={Runtime}, sessions={Sessions})", + runtimeState, sessionCountState); + return null; + } + + var persisted = new PersistedBoilerState + { + AccumulatedRunTime = TimeSpan.FromSeconds(runtimeSeconds), + SessionCount = sessionCount, + SkipPriceCapState = skipPriceCapState, + BudgetOverrideState = budgetOverrideState + }; + + logger.LogInformation("Restored persisted BoilerMonitor state: runtime={Runtime}, sessions={Sessions}, skipPriceCap={SkipPriceCap}, budgetOverride={BudgetOverride}", + persisted.AccumulatedRunTime, persisted.SessionCount, persisted.SkipPriceCapState, persisted.BudgetOverrideState); + + return persisted; + } + catch (Exception ex) + { + logger.LogError(ex, "Error reading persisted BoilerMonitor state from HA entities"); + return null; + } + } + + public async Task SetStatusAsync(string status) + { + await UpdateStatusAsync(status).ConfigureAwait(false); + } + + private static bool TryParseEntitySeconds(string? state, out double seconds) + { + seconds = 0; + return !string.IsNullOrWhiteSpace(state) + && state is not ("unavailable" or "unknown") + && double.TryParse(state, CultureInfo.InvariantCulture, out seconds) + && seconds >= 0; + } + + private static bool TryParseEntityInt(string? state, out int value) + { + value = 0; + return !string.IsNullOrWhiteSpace(state) + && state is not ("unavailable" or "unknown") + && int.TryParse(state, CultureInfo.InvariantCulture, out value) + && value >= 0; + } + + private ICollection GetAllEntities() + { + var device = CreateDeviceBlock(); + + return + [ + new BoilerMonitorEntity("text", "boilermonitor_config_power_entity_id", "Boiler power entity ID") + { + AdditionalConfig = new { icon = "mdi:flash", device } + }, + new BoilerMonitorEntity("text", "boilermonitor_config_switch_entity_id", "Boiler switch entity ID") + { + AdditionalConfig = new { icon = "mdi:toggle-switch", device } + }, + new BoilerMonitorEntity("number", "boilermonitor_config_poll_interval", "Poll interval (seconds)") + { + AdditionalConfig = new + { + min = (double)MinPollIntervalSeconds, + max = (double)MaxPollIntervalSeconds, + step = (double)PollIntervalStepSeconds, + unit_of_measurement = "s", + icon = "mdi:timer-outline", + device + } + }, + new BoilerMonitorEntity("number", "boilermonitor_config_heating_threshold", "Heating power threshold (watts)") + { + AdditionalConfig = new + { + min = MinHeatingThresholdWatts, + max = MaxHeatingThresholdWatts, + step = HeatingThresholdStepWatts, + unit_of_measurement = "W", + icon = "mdi:thermometer", + device + } + }, + new BoilerMonitorEntity("button", "boilermonitor_cleanup", "Cleanup all entities") + { + AdditionalConfig = new { icon = "mdi:delete-sweep", device } + }, + new BoilerMonitorEntity("sensor", "boilermonitor_status", "Boiler Monitor status") + { + AdditionalConfig = new { icon = "mdi:information-outline", device } + }, + new BoilerMonitorEntity("sensor", "boilermonitor_water_ready", "Boiler water ready") + { + AdditionalConfig = new { icon = "mdi:water-thermometer", device } + }, + new BoilerMonitorEntity("switch", "boilermonitor_skip_price_cap", "Skip price cap, heat until ready") + { + AdditionalConfig = new { optimistic = true, icon = "mdi:water-thermometer-outline", device } + }, + new BoilerMonitorEntity("sensor", "boilermonitor_today_runtime", "Today runtime") + { + AdditionalConfig = new { unit_of_measurement = "s", icon = "mdi:timer", device_class = "duration", device } + }, + new BoilerMonitorEntity("sensor", "boilermonitor_remaining_time", "Remaining budget time") + { + AdditionalConfig = new { unit_of_measurement = "s", icon = "mdi:timer-sand", device_class = "duration", device } + }, + new BoilerMonitorEntity("sensor", "boilermonitor_budget_percentage", "Budget usage") + { + AdditionalConfig = new { unit_of_measurement = "%", icon = "mdi:percent", device } + }, + new BoilerMonitorEntity("binary_sensor", "boilermonitor_budget_exhausted", "Budget exhausted") + { + Options = new EntityCreationOptions + { + UniqueId = BudgetExhaustedEntityId, + Name = "Budget exhausted" + }, + AdditionalConfig = new { icon = "mdi:battery-alert", device } + }, + new BoilerMonitorEntity("sensor", "boilermonitor_session_count", "Heating sessions today") + { + AdditionalConfig = new { icon = "mdi:counter", device } + }, + new BoilerMonitorEntity("switch", "boilermonitor_budget_override", "Override budget enforcement") + { + AdditionalConfig = new { optimistic = true, icon = "mdi:shield-off-outline", device } + } + ]; + } + + private async Task UpdateStatusAsync(string status) + { + await SetEntityStateSafe(StatusEntityId, status).ConfigureAwait(false); + } + + private async Task ResetStatusAsync() + { + await SetEntityStateSafe(StatusEntityId, StatusAwaitingConfiguration).ConfigureAwait(false); + } + + private async Task ResetWaterReadyAsync() + { + await SetEntityStateSafe(WaterReadyEntityId, "unknown").ConfigureAwait(false); + await SetEntityAttributesSafe(WaterReadyEntityId, new + { + boiler_switch_state = "unknown", + boiler_power_watts = 0.0, + power_threshold_watts = DefaultHeatingPowerThresholdWatts, + friendly_name = "Boiler water ready", + last_updated = (string?)null + }).ConfigureAwait(false); + } + + private async Task ResetSkipPriceCapAsync() + { + await SetEntityStateSafe(SkipPriceCapEntityId, "OFF").ConfigureAwait(false); + } + + private async Task ResetTodayRuntimeAsync() + { + await SetEntityStateSafe(TodayRuntimeEntityId, "0").ConfigureAwait(false); + await SetEntityAttributesSafe(TodayRuntimeEntityId, new + { + formatted = "0h 0m", + friendly_name = "Today runtime", + last_updated = (string?)null + }).ConfigureAwait(false); + } + + private async Task ResetRemainingTimeAsync() + { + await SetEntityStateSafe(RemainingTimeEntityId, "0").ConfigureAwait(false); + await SetEntityAttributesSafe(RemainingTimeEntityId, new + { + formatted = "0h 0m", + budget_hours = 0.0, + friendly_name = "Remaining budget time", + last_updated = (string?)null + }).ConfigureAwait(false); + } + + private async Task ResetBudgetPercentageAsync() + { + await SetEntityStateSafe(BudgetPercentageEntityId, "0").ConfigureAwait(false); + await SetEntityAttributesSafe(BudgetPercentageEntityId, new + { + unit_of_measurement = "%", + friendly_name = "Budget usage", + last_updated = (string?)null + }).ConfigureAwait(false); + } + + private async Task ResetBudgetExhaustedAsync() + { + await SetEntityStateSafe(BudgetExhaustedEntityId, "off").ConfigureAwait(false); + } + + private async Task ResetSessionCountAsync() + { + await SetEntityStateSafe(SessionCountEntityId, "0").ConfigureAwait(false); + await SetEntityAttributesSafe(SessionCountEntityId, new + { + friendly_name = "Heating sessions today", + last_updated = (string?)null + }).ConfigureAwait(false); + } + + private async Task ResetBudgetOverrideAsync() + { + await SetEntityStateSafe(BudgetOverrideEntityId, "OFF").ConfigureAwait(false); + } + + private async Task UpdateWaterReadyAsync(BoilerMonitorUpdateContext ctx, string timestamp) + { + await SetEntityStateSafe(WaterReadyEntityId, ctx.WaterReady ? "yes" : "no").ConfigureAwait(false); + await SetEntityAttributesSafe(WaterReadyEntityId, new + { + boiler_switch_state = ctx.BoilerSwitchState ?? "unknown", + boiler_power_watts = ctx.BoilerPowerWatts, + friendly_name = "Boiler water ready", + last_updated = timestamp + }).ConfigureAwait(false); + } + + private async Task UpdateTodayRuntimeAsync(TimeSpan runTime, string formatted, string timestamp) + { + await SetEntityStateSafe(TodayRuntimeEntityId, ((int)runTime.TotalSeconds).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false); + await SetEntityAttributesSafe(TodayRuntimeEntityId, new + { + formatted, + friendly_name = "Today runtime", + last_updated = timestamp + }).ConfigureAwait(false); + } + + private async Task UpdateRemainingTimeAsync(TimeSpan remaining, string formatted, double budgetHours, string timestamp) + { + var remainingSeconds = Math.Max(0, (int)remaining.TotalSeconds); + await SetEntityStateSafe(RemainingTimeEntityId, remainingSeconds.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false); + await SetEntityAttributesSafe(RemainingTimeEntityId, new + { + formatted, + budget_hours = budgetHours, + friendly_name = "Remaining budget time", + last_updated = timestamp + }).ConfigureAwait(false); + } + + private async Task UpdateBudgetPercentageAsync(double percentage, string timestamp) + { + var clampedPercentage = Math.Clamp(percentage, 0, 100); + await SetEntityStateSafe(BudgetPercentageEntityId, ((int)clampedPercentage).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false); + await SetEntityAttributesSafe(BudgetPercentageEntityId, new + { + unit_of_measurement = "%", + friendly_name = "Budget usage", + last_updated = timestamp + }).ConfigureAwait(false); + } + + private async Task UpdateBudgetExhaustedAsync(bool exhausted) + { + await SetEntityStateSafe(BudgetExhaustedEntityId, exhausted ? "on" : "off").ConfigureAwait(false); + } + + private async Task UpdateSessionCountAsync(int sessionCount, string timestamp) + { + await SetEntityStateSafe(SessionCountEntityId, sessionCount.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false); + await SetEntityAttributesSafe(SessionCountEntityId, new + { + friendly_name = "Heating sessions today", + last_updated = timestamp + }).ConfigureAwait(false); + } + + private async Task SetEntityStateSafe(string entityId, string state) + { + try + { + await entityManager.SetEntityState(entityId, state).ConfigureAwait(false); + logger.LogDebug("Successfully set state for {EntityId}: {State}", entityId, state); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to set state for {EntityId} to {State}", entityId, state); + } + } + + private async Task SetEntityAttributesSafe(string entityId, object attributes) + { + try + { + await entityManager.SetEntityAttributes(entityId, attributes).ConfigureAwait(false); + logger.LogDebug("Successfully set attributes for {EntityId}", entityId); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to set attributes for {EntityId}", entityId); + } + } + + private static string FormatTimeSpan(TimeSpan ts) + { + var totalHours = (int)ts.TotalHours; + var minutes = ts.Minutes; + + return $"{totalHours}h {minutes}m"; + } +} diff --git a/BoilerMonitor.Manager/BoilerMonitorInit.cs b/BoilerMonitor.Manager/BoilerMonitorInit.cs new file mode 100644 index 0000000..ee857ee --- /dev/null +++ b/BoilerMonitor.Manager/BoilerMonitorInit.cs @@ -0,0 +1,503 @@ +using System.Globalization; +using System.Reactive.Concurrency; +using BoilerMonitor.Models.Enums; +using BoilerMonitorManager.Interface; +using BoilerMonitorManager.Models; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using NetDaemon.AppModel; +using NetDaemon.Extensions.MqttEntityManager; +using NetDaemon.Extensions.Scheduler; +using NetDaemon.HassModel; +using NetDaemon.HassModel.Entities; +using static BoilerMonitor.Models.BoilerMonitorConsts; + +namespace BoilerMonitorManager; + +[NetDaemonApp] +public sealed class BoilerMonitorInit : IBoilerMonitorInit +{ + private readonly ILogger _logger; + private readonly IHaContext _haContext; + private readonly IScheduler _scheduler; + private readonly IMqttEntityManager _mqttEntityManager; + private readonly IBoilerControlService _boilerControlService; + private readonly IBoilerRunTimeTracker _tracker; + private readonly IBoilerMonitorEntityService _entityService; + private readonly IWaterReadyService _waterReadyService; + private readonly BoilerMonitorOptions _options; + + private bool _lastWaterReady; + private bool _cleanedUp; + + public BoilerMonitorInit( + IHaContext haContext, + ILogger logger, + IScheduler scheduler, + IMqttEntityManager mqttEntityManager, + IBoilerControlService boilerControlService, + IBoilerRunTimeTracker tracker, + IBoilerMonitorEntityService entityService, + IWaterReadyService waterReadyService, + IOptions options) + { + _haContext = haContext; + _logger = logger; + _scheduler = scheduler; + _mqttEntityManager = mqttEntityManager; + _boilerControlService = boilerControlService; + _tracker = tracker; + _entityService = entityService; + _waterReadyService = waterReadyService; + _options = options.Value; + + _ = InitializeAndScheduleAsync(); + } + + private async Task InitializeAndScheduleAsync() + { + try + { + await InitializeAsync(); + await SubscribeToConfigCommandsAsync(); + await SubscribeToSwitchCommandsAsync(); + SchedulePeriodicPolling(); + ScheduleMidnightReset(); + ScheduleEndOfDayReminder(); + SubscribeToSkipPriceCapChanges(); + SubscribeToCleanupButton(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error during BoilerMonitor initialization and scheduling"); + } + } + + public async Task InitializeAsync() + { + try + { + await Task.Delay(TimeSpan.FromSeconds(3)); + + if (_options.CleanupEntitiesOnStartup) + { + await _entityService.CleanupEntitiesAsync(); + await _entityService.CreateEntitiesAsync(); + await _entityService.ResetEntitiesAsync(); + } + else + { + var persisted = _entityService.ReadPersistedState(); + await _entityService.CreateEntitiesAsync(); + + if (persisted is not null) + { + _tracker.RestoreFromSnapshot(persisted.AccumulatedRunTime, persisted.SessionCount); + await _entityService.ResetTransientEntitiesAsync(); + _logger.LogInformation("BoilerMonitor state restored from HA entities: runtime={Runtime}, sessions={Sessions}", + persisted.AccumulatedRunTime, persisted.SessionCount); + } + else + { + await _entityService.ResetEntitiesAsync(); + _logger.LogInformation("No persisted state found, performing full entity reset"); + } + } + + await Task.Delay(TimeSpan.FromSeconds(5)); + + await PollAndUpdateAsync(); + + _logger.LogInformation("BoilerMonitor initialized"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error initializing BoilerMonitor"); + throw; + } + } + + public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default) + { + await _entityService.CleanupEntitiesAsync(cancellationToken); + } + + private void SchedulePeriodicPolling() + { + var now = DateTime.Now; + var currentSecondInInterval = (now.Minute * 60 + now.Second) % DefaultPollIntervalSeconds; + var secondsUntilNext = DefaultPollIntervalSeconds - currentSecondInInterval; + var delayUntilNext = TimeSpan.FromSeconds(secondsUntilNext); + var nextPollTime = now.Add(delayUntilNext); + + _logger.LogInformation("Scheduling BoilerMonitor polling every {Interval}s, first at {Time}", DefaultPollIntervalSeconds, nextPollTime); + + _scheduler.RunEvery(TimeSpan.FromSeconds(DefaultPollIntervalSeconds), nextPollTime, async void () => + { + try + { + await PollAndUpdateAsync(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error during BoilerMonitor poll cycle"); + } + }); + } + + private void ScheduleMidnightReset() + { + _scheduler.ScheduleCron("0 0 * * *", () => + { + try + { + _logger.LogInformation("Midnight reset: clearing boiler run time tracker and water ready cooldown"); + _tracker.Reset(); + _waterReadyService.ResetCooldown(); + _ = _entityService.ResetEntitiesAsync(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error during midnight reset"); + } + }); + } + + private void ScheduleEndOfDayReminder() + { + _scheduler.ScheduleCron("0 22 * * *", () => + { + try + { + var switchState = _haContext.GetState(SkipPriceCapEntityId); + if (string.Equals(switchState?.State, SwitchOnState, StringComparison.OrdinalIgnoreCase)) + { + _haContext.CallService("notify", "mobile_app_marius_phone", null, new + { + message = "Remember to turn off 'Skip price cap, heat until ready' if you're done heating.", + title = "Boiler reminder" + }); + _logger.LogInformation("End-of-day reminder sent: skip price cap switch is still ON"); + } + } + catch (Exception ex) + { + _logger.LogError(ex, "Error checking skip price cap reminder"); + } + }); + } + + private void SubscribeToSkipPriceCapChanges() + { + var skipPriceCapSwitch = new Entity(_haContext, SkipPriceCapEntityId); + skipPriceCapSwitch.StateChanges() + .Subscribe(e => + { + if (e.Old?.State == e.New?.State) + { + return; + } + + _logger.LogInformation("Skip price cap switch changed, triggering poll"); + _ = PollAndUpdateAsync(); + }); + } + + private void SubscribeToCleanupButton() + { + var cleanupButton = new Entity(_haContext, CleanupButtonEntityId); + cleanupButton.StateChanges() + .Subscribe(_ => + { + _logger.LogInformation("Cleanup button pressed, removing all BoilerMonitor entities"); + Task.Run(HandleCleanupAsync); + }); + } + + private async Task SubscribeToConfigCommandsAsync() + { + var configEntityIds = new[] + { + ConfigPowerEntityId, + ConfigSwitchEntityId, + ConfigPollIntervalEntityId, + ConfigHeatingThresholdEntityId + }; + + foreach (var entityId in configEntityIds) + { + var subscription = await _mqttEntityManager.PrepareCommandSubscriptionAsync(entityId).ConfigureAwait(false); + subscription.Subscribe(async void (state) => + { + try + { + _logger.LogInformation("Config entity {EntityId} received command: {Value}", entityId, state); + await _mqttEntityManager.SetStateAsync(entityId, state).ConfigureAwait(false); + } + catch (Exception e) + { + _logger.LogError(e, "Error handling command for entity {EntityId}", entityId); + } + }); + } + } + + private async Task SubscribeToSwitchCommandsAsync() + { + var switchEntityIds = new[] + { + SkipPriceCapEntityId, + BudgetOverrideEntityId + }; + + foreach (var entityId in switchEntityIds) + { + var subscription = await _mqttEntityManager.PrepareCommandSubscriptionAsync(entityId).ConfigureAwait(false); + subscription.Subscribe(async void (state) => + { + try + { + _logger.LogInformation("Switch {EntityId} received command: {Value}", entityId, state); + await _mqttEntityManager.SetStateAsync(entityId, state).ConfigureAwait(false); + } + catch (Exception e) + { + _logger.LogError(e, "Error handling command for switch entity {EntityId}", entityId); + } + }); + } + } + + private async Task HandleCleanupAsync() + { + try + { + await _entityService.CleanupEntitiesAsync(); + _cleanedUp = true; + _tracker.Reset(); + _logger.LogInformation("BoilerMonitor cleanup complete. Entities removed, monitoring stopped"); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error during BoilerMonitor cleanup"); + } + } + + private async Task PollAndUpdateAsync() + { + if (_cleanedUp) + { + _logger.LogDebug("BoilerMonitor is cleaned up, skipping poll"); + return; + } + + try + { + var config = ReadConfigFromHaEntities(); + + if (!config.IsFullyConfigured) + { + await _entityService.SetStatusAsync(StatusAwaitingConfiguration); + _logger.LogWarning("BoilerMonitor not fully configured (power={Power}, switch={Switch}, interval={Interval}, threshold={Threshold}). Awaiting configuration", + config.BoilerPowerEntityId, config.BoilerSwitchEntityId, + config.PollIntervalSeconds, config.HeatingPowerThresholdWatts); + + return; + } + + var boilerPowerWatts = ReadSensorDouble(config.BoilerPowerEntityId!); + var boilerSwitchState = _haContext.GetState(config.BoilerSwitchEntityId!)?.State; + var isHeating = boilerPowerWatts.HasValue && boilerPowerWatts.Value >= config.HeatingPowerThresholdWatts!.Value; + var pollInterval = TimeSpan.FromSeconds(config.PollIntervalSeconds!.Value); + + _tracker.RecordPollResult(isHeating, pollInterval); + + var cheapestIntervalsState = _haContext.GetState(NordPoolCheapestIntervalsEntityId); + var isNowCheap = ReadAttributeBool(cheapestIntervalsState, "is_now_cheap"); + var nextCheapInterval = ReadAttributeDateTime(cheapestIntervalsState, "next_cheap_interval"); + + var budgetOverrideState = _haContext.GetState(BudgetOverrideEntityId)?.State; + var budgetOverride = string.Equals(budgetOverrideState, SwitchOnState, StringComparison.OrdinalIgnoreCase); + + var skipPriceCapState = _haContext.GetState(SkipPriceCapEntityId)?.State; + var skipPriceCap = string.Equals(skipPriceCapState, SwitchOnState, StringComparison.OrdinalIgnoreCase); + + var dailyHours = ReadSensorDouble(BoilerDailyHoursEntityId) ?? 1.0; + + var waterReady = _waterReadyService.IsWaterReady(boilerSwitchState, boilerPowerWatts, config.HeatingPowerThresholdWatts!.Value); + + if (!_lastWaterReady && waterReady) + { + _haContext.CallService("notify", "mobile_app_marius_phone", null, new + { + message = "Hot water is ready.", + title = "Boiler" + }); + _logger.LogInformation("Water ready notification sent"); + } + _lastWaterReady = waterReady; + + var snapshot = _tracker.GetSnapshot(); + var budgetTimeSpan = TimeSpan.FromHours(dailyHours); + var remainingTime = budgetTimeSpan - snapshot.AccumulatedRunTime; + + if (remainingTime < TimeSpan.Zero) + { + remainingTime = TimeSpan.Zero; + } + + var budgetPercentage = budgetTimeSpan.TotalSeconds > 0 + ? (snapshot.AccumulatedRunTime.TotalSeconds / budgetTimeSpan.TotalSeconds) * 100.0 + : 0.0; + + var budgetExhausted = snapshot.AccumulatedRunTime >= budgetTimeSpan; + + var effectiveIsNowCheap = isNowCheap || skipPriceCap; + + var boilerAction = _boilerControlService.DetermineAction(effectiveIsNowCheap, waterReady, boilerSwitchState, budgetExhausted, budgetOverride); + + ExecuteBoilerAction(boilerAction, config.BoilerSwitchEntityId!); + + var context = new BoilerMonitorUpdateContext + { + TodayRunTime = snapshot.AccumulatedRunTime, + RemainingTime = remainingTime, + BudgetPercentage = budgetPercentage, + BudgetExhausted = budgetExhausted, + SessionCount = snapshot.SessionCount, + BudgetHours = dailyHours, + IsCurrentlyHeating = isHeating, + WaterReady = waterReady, + BoilerSwitchState = boilerSwitchState, + BoilerPowerWatts = boilerPowerWatts, + IsNowCheap = effectiveIsNowCheap, + NextCheapIntervalStart = nextCheapInterval + }; + + await _entityService.UpdateEntitiesAsync(context); + + _logger.LogDebug("Poll complete: power={Power}W, heating={Heating}, runtime={Runtime}, budget={Budget}%", + boilerPowerWatts, isHeating, snapshot.AccumulatedRunTime, budgetPercentage); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error during BoilerMonitor poll and update"); + } + } + + private void ExecuteBoilerAction(BoilerAction action, string switchEntityId) + { + switch (action) + { + case BoilerAction.TurnOn: + _haContext.CallService("switch", "turn_on", ServiceTarget.FromEntity(switchEntityId)); + _waterReadyService.NotifyTurnedOn(); + break; + case BoilerAction.TurnOff: + _haContext.CallService("switch", "turn_off", ServiceTarget.FromEntity(switchEntityId)); + break; + case BoilerAction.NoChange: + break; + default: + throw new ArgumentOutOfRangeException(nameof(action), action, null); + } + } + + private BoilerMonitorConfig ReadConfigFromHaEntities() + { + var powerEntityId = _haContext.GetState(ConfigPowerEntityId)?.State; + var switchEntityId = _haContext.GetState(ConfigSwitchEntityId)?.State; + + int? pollInterval = null; + var pollIntervalState = _haContext.GetState(ConfigPollIntervalEntityId)?.State; + + if (!string.IsNullOrWhiteSpace(pollIntervalState) + && double.TryParse(pollIntervalState, CultureInfo.InvariantCulture, out var pollIntervalValue) + && pollIntervalValue > 0) + { + pollInterval = (int)pollIntervalValue; + } + + double? heatingThreshold = null; + var thresholdState = _haContext.GetState(ConfigHeatingThresholdEntityId)?.State; + + if (!string.IsNullOrWhiteSpace(thresholdState) + && double.TryParse(thresholdState, CultureInfo.InvariantCulture, out var thresholdValue) + && thresholdValue > 0) + { + heatingThreshold = thresholdValue; + } + + return new BoilerMonitorConfig + { + BoilerPowerEntityId = string.IsNullOrWhiteSpace(powerEntityId) ? null : powerEntityId, + BoilerSwitchEntityId = string.IsNullOrWhiteSpace(switchEntityId) ? null : switchEntityId, + PollIntervalSeconds = pollInterval, + HeatingPowerThresholdWatts = heatingThreshold + }; + } + + private double? ReadSensorDouble(string entityId) + { + var state = _haContext.GetState(entityId); + + if (state?.State is null or "unavailable" or "unknown") + { + return null; + } + + return double.TryParse(state.State, CultureInfo.InvariantCulture, out var value) ? value : null; + } + + private static bool ReadAttributeBool(EntityState? entityState, string attributeName) + { + if (entityState?.Attributes is null) + { + return false; + } + + try + { + if (entityState.Attributes is IDictionary attributes && attributes.TryGetValue(attributeName, out var value)) + { + return value switch + { + bool b => b, + string s => bool.TryParse(s, out var parsed) && parsed, + _ => false + }; + } + } + catch + { + // Attribute not found or not parseable + } + + return false; + } + + private static DateTime? ReadAttributeDateTime(EntityState? entityState, string attributeName) + { + if (entityState?.Attributes is null) + { + return null; + } + + try + { + if (entityState.Attributes is IDictionary attributes && attributes.TryGetValue(attributeName, out var value)) + { + if (value is string s && DateTime.TryParse(s, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var parsed)) + { + return parsed; + } + } + } + catch + { + // Attribute not found or not parseable + } + + return null; + } +} diff --git a/BoilerMonitor.Manager/BoilerMonitorServiceRegistration.cs b/BoilerMonitor.Manager/BoilerMonitorServiceRegistration.cs new file mode 100644 index 0000000..c3c3365 --- /dev/null +++ b/BoilerMonitor.Manager/BoilerMonitorServiceRegistration.cs @@ -0,0 +1,34 @@ +using BoilerMonitor.Models; +using BoilerMonitorManager.Interface; +using BoilerMonitorManager.Models; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using NetDaemon.AppModel; + +namespace BoilerMonitorManager; + +public static class BoilerMonitorServiceRegistration +{ + public static IServiceCollection AddBoilerMonitor(this IServiceCollection services, IConfiguration configuration) + { + var options = configuration + .GetSection(BoilerMonitorOptions.SectionName) + .Get() ?? new BoilerMonitorOptions(); + + if (!options.Enabled) + { + return services; + } + + services + .AddNetDaemonApp() + .AddSingleton() + .AddSingleton() + .AddTransient() + .AddSingleton() + .AddSingleton(TimeProvider.System) + .AddScoped(); + + return services; + } +} diff --git a/BoilerMonitor.Manager/BoilerRunTimeTracker.cs b/BoilerMonitor.Manager/BoilerRunTimeTracker.cs new file mode 100644 index 0000000..46fb83c --- /dev/null +++ b/BoilerMonitor.Manager/BoilerRunTimeTracker.cs @@ -0,0 +1,66 @@ +using BoilerMonitorManager.Interface; +using BoilerMonitorManager.Models; + +namespace BoilerMonitorManager; + +public class BoilerRunTimeTracker : IBoilerRunTimeTracker +{ + private readonly Lock _lock = new(); + private TimeSpan _accumulatedRunTime = TimeSpan.Zero; + private int _sessionCount; + private bool _isInSession; + + public void RecordPollResult(bool isHeating, TimeSpan pollInterval) + { + lock (_lock) + { + if (isHeating) + { + _accumulatedRunTime += pollInterval; + + if (!_isInSession) + { + _sessionCount++; + _isInSession = true; + } + } + else + { + _isInSession = false; + } + } + } + + public RunTimeSnapshot GetSnapshot() + { + lock (_lock) + { + return new RunTimeSnapshot + { + AccumulatedRunTime = _accumulatedRunTime, + SessionCount = _sessionCount, + IsInSession = _isInSession + }; + } + } + + public void Reset() + { + lock (_lock) + { + _accumulatedRunTime = TimeSpan.Zero; + _sessionCount = 0; + _isInSession = false; + } + } + + public void RestoreFromSnapshot(TimeSpan accumulatedRunTime, int sessionCount) + { + lock (_lock) + { + _accumulatedRunTime = accumulatedRunTime; + _sessionCount = sessionCount; + _isInSession = false; + } + } +} diff --git a/BoilerMonitor.Manager/Interface/IBoilerControlService.cs b/BoilerMonitor.Manager/Interface/IBoilerControlService.cs new file mode 100644 index 0000000..3d08e0c --- /dev/null +++ b/BoilerMonitor.Manager/Interface/IBoilerControlService.cs @@ -0,0 +1,8 @@ +using BoilerMonitor.Models.Enums; + +namespace BoilerMonitorManager.Interface; + +public interface IBoilerControlService +{ + BoilerAction DetermineAction(bool isNowCheap, bool waterReady, string? currentSwitchState, bool budgetExhausted, bool budgetOverride); +} diff --git a/BoilerMonitor.Manager/Interface/IBoilerMonitorEntityService.cs b/BoilerMonitor.Manager/Interface/IBoilerMonitorEntityService.cs new file mode 100644 index 0000000..9c6931b --- /dev/null +++ b/BoilerMonitor.Manager/Interface/IBoilerMonitorEntityService.cs @@ -0,0 +1,14 @@ +using BoilerMonitorManager.Models; + +namespace BoilerMonitorManager.Interface; + +public interface IBoilerMonitorEntityService +{ + Task CreateEntitiesAsync(CancellationToken cancellationToken = default); + Task ResetEntitiesAsync(CancellationToken cancellationToken = default); + Task ResetTransientEntitiesAsync(CancellationToken cancellationToken = default); + Task UpdateEntitiesAsync(BoilerMonitorUpdateContext context, CancellationToken cancellationToken = default); + Task CleanupEntitiesAsync(CancellationToken cancellationToken = default); + Task SetStatusAsync(string status); + PersistedBoilerState? ReadPersistedState(); +} diff --git a/BoilerMonitor.Manager/Interface/IBoilerMonitorInit.cs b/BoilerMonitor.Manager/Interface/IBoilerMonitorInit.cs new file mode 100644 index 0000000..fc3f482 --- /dev/null +++ b/BoilerMonitor.Manager/Interface/IBoilerMonitorInit.cs @@ -0,0 +1,7 @@ +namespace BoilerMonitorManager.Interface; + +public interface IBoilerMonitorInit +{ + Task InitializeAsync(); + Task CleanupEntitiesAsync(CancellationToken cancellationToken = default); +} diff --git a/BoilerMonitor.Manager/Interface/IBoilerRunTimeTracker.cs b/BoilerMonitor.Manager/Interface/IBoilerRunTimeTracker.cs new file mode 100644 index 0000000..a8fdb81 --- /dev/null +++ b/BoilerMonitor.Manager/Interface/IBoilerRunTimeTracker.cs @@ -0,0 +1,11 @@ +using BoilerMonitorManager.Models; + +namespace BoilerMonitorManager.Interface; + +public interface IBoilerRunTimeTracker +{ + void RecordPollResult(bool isHeating, TimeSpan pollInterval); + RunTimeSnapshot GetSnapshot(); + void Reset(); + void RestoreFromSnapshot(TimeSpan accumulatedRunTime, int sessionCount); +} diff --git a/BoilerMonitor.Manager/Interface/IWaterReadyService.cs b/BoilerMonitor.Manager/Interface/IWaterReadyService.cs new file mode 100644 index 0000000..c2881e4 --- /dev/null +++ b/BoilerMonitor.Manager/Interface/IWaterReadyService.cs @@ -0,0 +1,9 @@ +namespace BoilerMonitorManager.Interface; + +public interface IWaterReadyService +{ + bool IsWaterReady(string? switchState, double? powerWatts, double heatingThresholdWatts); + bool IsInCooldown { get; } + void NotifyTurnedOn(); + void ResetCooldown(); +} diff --git a/BoilerMonitor.Manager/Models/BoilerMonitorConfig.cs b/BoilerMonitor.Manager/Models/BoilerMonitorConfig.cs new file mode 100644 index 0000000..aa1ff0c --- /dev/null +++ b/BoilerMonitor.Manager/Models/BoilerMonitorConfig.cs @@ -0,0 +1,15 @@ +namespace BoilerMonitorManager.Models; + +public record BoilerMonitorConfig +{ + public string? BoilerPowerEntityId { get; init; } + public string? BoilerSwitchEntityId { get; init; } + public int? PollIntervalSeconds { get; init; } + public double? HeatingPowerThresholdWatts { get; init; } + + public bool IsFullyConfigured => + !string.IsNullOrWhiteSpace(BoilerPowerEntityId) && + !string.IsNullOrWhiteSpace(BoilerSwitchEntityId) && + PollIntervalSeconds is > 0 && + HeatingPowerThresholdWatts is > 0; +} diff --git a/BoilerMonitor.Manager/Models/BoilerMonitorOptions.cs b/BoilerMonitor.Manager/Models/BoilerMonitorOptions.cs new file mode 100644 index 0000000..556d9af --- /dev/null +++ b/BoilerMonitor.Manager/Models/BoilerMonitorOptions.cs @@ -0,0 +1,14 @@ +namespace BoilerMonitorManager.Models; + +public sealed class BoilerMonitorOptions +{ + public const string SectionName = "BoilerMonitor"; + + public bool Enabled { get; init; } = true; + + /// + /// When true, removes existing BoilerMonitor MQTT entities before recreating them on app startup. + /// Manual cleanup (e.g. HA button) is not affected. + /// + public bool CleanupEntitiesOnStartup { get; init; } = true; +} diff --git a/BoilerMonitor.Manager/Models/BoilerMonitorUpdateContext.cs b/BoilerMonitor.Manager/Models/BoilerMonitorUpdateContext.cs new file mode 100644 index 0000000..9f94a54 --- /dev/null +++ b/BoilerMonitor.Manager/Models/BoilerMonitorUpdateContext.cs @@ -0,0 +1,17 @@ +namespace BoilerMonitorManager.Models; + +public record BoilerMonitorUpdateContext +{ + public required TimeSpan TodayRunTime { get; init; } + public required TimeSpan RemainingTime { get; init; } + public required double BudgetPercentage { get; init; } + public required bool BudgetExhausted { get; init; } + public required int SessionCount { get; init; } + public required double BudgetHours { get; init; } + public required bool IsCurrentlyHeating { get; init; } + public required bool WaterReady { get; init; } + public required string? BoilerSwitchState { get; init; } + public required double? BoilerPowerWatts { get; init; } + public required bool IsNowCheap { get; init; } + public required DateTime? NextCheapIntervalStart { get; init; } +} diff --git a/BoilerMonitor.Manager/Models/PersistedBoilerState.cs b/BoilerMonitor.Manager/Models/PersistedBoilerState.cs new file mode 100644 index 0000000..58d563c --- /dev/null +++ b/BoilerMonitor.Manager/Models/PersistedBoilerState.cs @@ -0,0 +1,9 @@ +namespace BoilerMonitorManager.Models; + +public record PersistedBoilerState +{ + public required TimeSpan AccumulatedRunTime { get; init; } + public required int SessionCount { get; init; } + public required string? SkipPriceCapState { get; init; } + public required string? BudgetOverrideState { get; init; } +} diff --git a/BoilerMonitor.Manager/Models/RunTimeSnapshot.cs b/BoilerMonitor.Manager/Models/RunTimeSnapshot.cs new file mode 100644 index 0000000..8ba7d84 --- /dev/null +++ b/BoilerMonitor.Manager/Models/RunTimeSnapshot.cs @@ -0,0 +1,8 @@ +namespace BoilerMonitorManager.Models; + +public record RunTimeSnapshot +{ + public required TimeSpan AccumulatedRunTime { get; init; } + public required int SessionCount { get; init; } + public required bool IsInSession { get; init; } +} diff --git a/BoilerMonitor.Manager/WaterReadyService.cs b/BoilerMonitor.Manager/WaterReadyService.cs new file mode 100644 index 0000000..4c10443 --- /dev/null +++ b/BoilerMonitor.Manager/WaterReadyService.cs @@ -0,0 +1,115 @@ +using BoilerMonitor.Models; +using BoilerMonitorManager.Interface; +using Microsoft.Extensions.Logging; + +namespace BoilerMonitorManager; + +public sealed class WaterReadyService(ILogger logger, TimeProvider timeProvider) : IWaterReadyService +{ + private const string SwitchOnState = "on"; + private readonly Lock _lock = new(); + private DateTimeOffset? _lastTurnedOnAt; + private DateTimeOffset? _waterReadySince; + + public bool IsInCooldown + { + get + { + lock (_lock) + { + return IsWithinCooldownPeriod(); + } + } + } + + public bool IsWaterReady(string? switchState, double? powerWatts, double heatingThresholdWatts) + { + lock (_lock) + { + if (IsWithinCooldownPeriod()) + { + logger.LogDebug("Water ready cooldown active (since {Since}), suppressing turn-on", _waterReadySince); + return true; + } + } + + if (switchState is null || powerWatts is null) + { + return false; + } + + if (!string.Equals(switchState, SwitchOnState, StringComparison.OrdinalIgnoreCase)) + { + return false; + } + + if (IsWithinWarmUpGracePeriod()) + { + logger.LogDebug( + "Ignoring low power reading ({PowerWatts}W) during warm-up grace period", + powerWatts.Value); + return false; + } + + var isReady = powerWatts.Value < heatingThresholdWatts; + + if (isReady) + { + lock (_lock) + { + _waterReadySince ??= timeProvider.GetUtcNow(); + } + + logger.LogInformation( + "Water detected as ready, cooldown period ({CooldownPeriod}) started", + BoilerMonitorConsts.WaterReadyCooldownPeriod); + } + + return isReady; + } + + public void NotifyTurnedOn() + { + lock (_lock) + { + _lastTurnedOnAt = timeProvider.GetUtcNow(); + } + + logger.LogDebug("Boiler turn-on recorded, warm-up grace period started ({GracePeriod})", BoilerMonitorConsts.WarmUpGracePeriod); + } + + public void ResetCooldown() + { + lock (_lock) + { + _waterReadySince = null; + } + + logger.LogInformation("Water ready cooldown has been reset"); + } + + private bool IsWithinCooldownPeriod() + { + if (_waterReadySince is null) + { + return false; + } + + var elapsed = timeProvider.GetUtcNow() - _waterReadySince.Value; + return elapsed < BoilerMonitorConsts.WaterReadyCooldownPeriod; + } + + private bool IsWithinWarmUpGracePeriod() + { + lock (_lock) + { + if (_lastTurnedOnAt is null) + { + return false; + } + + var elapsed = timeProvider.GetUtcNow() - _lastTurnedOnAt.Value; + return elapsed < BoilerMonitorConsts.WarmUpGracePeriod; + } + } +} diff --git a/BoilerMonitor.Models/BoilerConfig.cs b/BoilerMonitor.Models/BoilerConfig.cs new file mode 100644 index 0000000..03d9966 --- /dev/null +++ b/BoilerMonitor.Models/BoilerConfig.cs @@ -0,0 +1,15 @@ +namespace BoilerMonitor.Models; + +/// +/// Boiler scheduling configuration read from Home Assistant entity state. +/// +public sealed class BoilerConfig +{ + public required int IntervalCount { get; init; } + + public required double PriceCap { get; init; } + + public required DateTime Deadline { get; init; } + + public required bool SkipPriceCap { get; init; } +} diff --git a/BoilerMonitor.Models/BoilerMonitor.Models.csproj b/BoilerMonitor.Models/BoilerMonitor.Models.csproj new file mode 100644 index 0000000..cb7cd05 --- /dev/null +++ b/BoilerMonitor.Models/BoilerMonitor.Models.csproj @@ -0,0 +1,18 @@ + + + + net10.0 + enable + enable + BoilerMonitor.Models + + + + + + + + + + + diff --git a/BoilerMonitor.Models/BoilerMonitorConsts.cs b/BoilerMonitor.Models/BoilerMonitorConsts.cs new file mode 100644 index 0000000..0f24d45 --- /dev/null +++ b/BoilerMonitor.Models/BoilerMonitorConsts.cs @@ -0,0 +1,67 @@ +namespace BoilerMonitor.Models; + +public static class BoilerMonitorConsts +{ + public const int DefaultPollIntervalSeconds = 30; + + /// + /// Power threshold in watts below which the boiler is considered to have finished heating (water ready). + /// Also used as the default threshold above which the boiler is considered actively heating. + /// + public const double DefaultHeatingPowerThresholdWatts = 5.0; + + /// + /// Grace period after the boiler switch is turned on, during which + /// low power readings are ignored for "water ready" detection. + /// This prevents false positives caused by the heating element ramp-up delay. + /// + public static readonly TimeSpan WarmUpGracePeriod = TimeSpan.FromMinutes(2); + + /// + /// Cooldown period after the water has been detected as ready, + /// during which the boiler will not be turned back on. + /// This prevents wasteful on/off cycling when water is already heated. + /// + public static readonly TimeSpan WaterReadyCooldownPeriod = TimeSpan.FromHours(1); + + public const int MinPollIntervalSeconds = 5; + public const int MaxPollIntervalSeconds = 300; + public const int PollIntervalStepSeconds = 5; + + public const double MinHeatingThresholdWatts = 1.0; + public const double MaxHeatingThresholdWatts = 100.0; + public const double HeatingThresholdStepWatts = 0.5; + + public const string ConfigPowerEntityId = "text.boilermonitor_config_power_entity_id"; + public const string ConfigSwitchEntityId = "text.boilermonitor_config_switch_entity_id"; + public const string ConfigPollIntervalEntityId = "number.boilermonitor_config_poll_interval"; + public const string ConfigHeatingThresholdEntityId = "number.boilermonitor_config_heating_threshold"; + + public const string CleanupButtonEntityId = "button.boilermonitor_cleanup"; + public const string StatusEntityId = "sensor.boilermonitor_status"; + + public const string WaterReadyEntityId = "sensor.boilermonitor_water_ready"; + public const string SkipPriceCapEntityId = "switch.boilermonitor_skip_price_cap"; + public const string TodayRuntimeEntityId = "sensor.boilermonitor_today_runtime"; + public const string RemainingTimeEntityId = "sensor.boilermonitor_remaining_time"; + public const string BudgetPercentageEntityId = "sensor.boilermonitor_budget_percentage"; + public const string BudgetExhaustedEntityId = "binary_sensor.boilermonitor_budget_exhausted"; + public const string SessionCountEntityId = "sensor.boilermonitor_session_count"; + public const string BudgetOverrideEntityId = "switch.boilermonitor_budget_override"; + + public const string NordPoolCheapestIntervalsEntityId = "sensor.nordpool_cheapest_intervals"; + + public const string BoilerDailyHoursEntityId = "input_number.boiler_daily_hours"; + public const string BoilerPriceCapEntityId = "input_number.boiler_price_cap"; + public const string BoilerReadyByEntityId = "input_datetime.boiler_ready_by"; + + public const string StatusConfigured = "configured"; + public const string StatusAwaitingConfiguration = "awaiting_configuration"; + public const string StatusCleanedUp = "cleaned_up"; + + public const string SwitchOnState = "on"; + + public const string DeviceIdentifier = "boiler_monitor"; + public const string DeviceName = "Boiler Monitor"; + public const string DeviceManufacturer = "HomeAssistant App Daemon"; +} diff --git a/BoilerMonitor.Models/BoilerMonitorEntity.cs b/BoilerMonitor.Models/BoilerMonitorEntity.cs new file mode 100644 index 0000000..8561efd --- /dev/null +++ b/BoilerMonitor.Models/BoilerMonitorEntity.cs @@ -0,0 +1,25 @@ +using HomeAssistant.Models; +using NetDaemon.Extensions.MqttEntityManager; + +namespace BoilerMonitor.Models; + +public class BoilerMonitorEntity : EntityCreateModel +{ + public string Domain { get; set; } + public string Identifier { get; set; } + public string Name { get; set; } + + public BoilerMonitorEntity(string domain, string identifier, string name) + { + Domain = domain; + Identifier = identifier; + EntityId = $"{Domain}.{Identifier}"; + Name = string.IsNullOrWhiteSpace(name) ? identifier : name; + + Options = new EntityCreationOptions + { + UniqueId = EntityId, + Name = Name + }; + } +} diff --git a/NordPool.Manager/Models/Enums/BoilerAction.cs b/BoilerMonitor.Models/Enums/BoilerAction.cs similarity index 62% rename from NordPool.Manager/Models/Enums/BoilerAction.cs rename to BoilerMonitor.Models/Enums/BoilerAction.cs index b210042..157caf0 100644 --- a/NordPool.Manager/Models/Enums/BoilerAction.cs +++ b/BoilerMonitor.Models/Enums/BoilerAction.cs @@ -1,4 +1,4 @@ -namespace NordPoolManager.Models.Enums; +namespace BoilerMonitor.Models.Enums; public enum BoilerAction { diff --git a/BoilerMonitor.Models/IBoilerConfigReader.cs b/BoilerMonitor.Models/IBoilerConfigReader.cs new file mode 100644 index 0000000..b917d97 --- /dev/null +++ b/BoilerMonitor.Models/IBoilerConfigReader.cs @@ -0,0 +1,9 @@ +namespace BoilerMonitor.Models; + +/// +/// Reads the boiler scheduling configuration from Home Assistant entity state. +/// +public interface IBoilerConfigReader +{ + BoilerConfig ReadConfig(); +} diff --git a/HomeAssistant.Server/HomeAssistant.Server.csproj b/HomeAssistant.Server/HomeAssistant.Server.csproj index b87d3b2..5f24375 100644 --- a/HomeAssistant.Server/HomeAssistant.Server.csproj +++ b/HomeAssistant.Server/HomeAssistant.Server.csproj @@ -44,6 +44,8 @@ + + diff --git a/HomeAssistant.Server/appsettings.json b/HomeAssistant.Server/appsettings.json index b92d072..49722cf 100644 --- a/HomeAssistant.Server/appsettings.json +++ b/HomeAssistant.Server/appsettings.json @@ -5,7 +5,8 @@ "Override": { "System.Net.Http.HttpClient": "Warning", "NordPoolManager": "Information", - "PowerMonitorManager": "Information" + "PowerMonitorManager": "Information", + "BoilerMonitorManager": "Information" } }, "WriteTo": [ @@ -26,6 +27,13 @@ "OutputFile": "HomeAssistantGenerated.cs", "UseAttributeBaseClasses" : "false" }, + "NordPool": { + "CleanupEntitiesOnStartup": false + }, + "BoilerMonitor": { + "Enabled": true, + "CleanupEntitiesOnStartup": false + }, "PowerMonitor": { "Enabled": false, "MainMeterEntityId": "sensor.sonoff_100267d63f_power", diff --git a/HomeAssistant.Server/program.cs b/HomeAssistant.Server/program.cs index 36edf97..9887b6d 100644 --- a/HomeAssistant.Server/program.cs +++ b/HomeAssistant.Server/program.cs @@ -12,8 +12,11 @@ using NetDaemon.Extensions.MqttEntityManager; using NetDaemon.Extensions.Scheduler; using NetDaemon.Extensions.Tts; using NetDaemon.Runtime; +using BoilerMonitorManager; +using BoilerMonitorManager.Models; using NordPoolManager; using NordPoolManager.Interface; +using NordPoolManager.Models; using PowerMonitorManager; using PowerMonitorManager.Models; @@ -42,13 +45,14 @@ try config.AddProfile(); }) .AddTransient() + .Configure(context.Configuration.GetSection(NordPoolOptions.SectionName)) .AddScoped() .AddTransient() .AddSingleton() - .AddSingleton() - .Configure( - context.Configuration.GetSection(PowerMonitorOptions.SectionName)) + .Configure(context.Configuration.GetSection(PowerMonitorOptions.SectionName)) .AddPowerMonitor(context.Configuration) + .Configure(context.Configuration.GetSection(BoilerMonitorOptions.SectionName)) + .AddBoilerMonitor(context.Configuration) ) .Build() .RunAsync() diff --git a/HomeAssistantSDK.sln b/HomeAssistantSDK.sln index 83524b6..5858ef8 100644 --- a/HomeAssistantSDK.sln +++ b/HomeAssistantSDK.sln @@ -20,6 +20,16 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PowerMonitor.Manager", "Pow EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PowerMonitor.Manager.Tests", "PowerMonitor.Manager.Tests\PowerMonitor.Manager.Tests.csproj", "{1F613F65-5F3C-41E6-B86B-774301D80E42}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BoilerMonitor.Models", "BoilerMonitor.Models\BoilerMonitor.Models.csproj", "{72331F53-884D-42A1-8EEA-8CC83FFAB623}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BoilerMonitor.Manager", "BoilerMonitor.Manager\BoilerMonitor.Manager.csproj", "{488964A2-C7A2-45C9-9CDB-98515AFD7242}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BoilerMonitor.Manager.Tests", "BoilerMonitor.Manager.Tests\BoilerMonitor.Manager.Tests.csproj", "{CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Testing", "Testing", "{95E98121-7DA4-4085-A8E3-B0430628452F}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Models", "Models", "{48492269-2B47-43FE-BC14-A901054EE5AE}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -150,8 +160,53 @@ Global {1F613F65-5F3C-41E6-B86B-774301D80E42}.Release|x64.Build.0 = Release|Any CPU {1F613F65-5F3C-41E6-B86B-774301D80E42}.Release|x86.ActiveCfg = Release|Any CPU {1F613F65-5F3C-41E6-B86B-774301D80E42}.Release|x86.Build.0 = Release|Any CPU + {72331F53-884D-42A1-8EEA-8CC83FFAB623}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {72331F53-884D-42A1-8EEA-8CC83FFAB623}.Debug|Any CPU.Build.0 = Debug|Any CPU + {72331F53-884D-42A1-8EEA-8CC83FFAB623}.Debug|x64.ActiveCfg = Debug|Any CPU + {72331F53-884D-42A1-8EEA-8CC83FFAB623}.Debug|x64.Build.0 = Debug|Any CPU + {72331F53-884D-42A1-8EEA-8CC83FFAB623}.Debug|x86.ActiveCfg = Debug|Any CPU + {72331F53-884D-42A1-8EEA-8CC83FFAB623}.Debug|x86.Build.0 = Debug|Any CPU + {72331F53-884D-42A1-8EEA-8CC83FFAB623}.Release|Any CPU.ActiveCfg = Release|Any CPU + {72331F53-884D-42A1-8EEA-8CC83FFAB623}.Release|Any CPU.Build.0 = Release|Any CPU + {72331F53-884D-42A1-8EEA-8CC83FFAB623}.Release|x64.ActiveCfg = Release|Any CPU + {72331F53-884D-42A1-8EEA-8CC83FFAB623}.Release|x64.Build.0 = Release|Any CPU + {72331F53-884D-42A1-8EEA-8CC83FFAB623}.Release|x86.ActiveCfg = Release|Any CPU + {72331F53-884D-42A1-8EEA-8CC83FFAB623}.Release|x86.Build.0 = Release|Any CPU + {488964A2-C7A2-45C9-9CDB-98515AFD7242}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {488964A2-C7A2-45C9-9CDB-98515AFD7242}.Debug|Any CPU.Build.0 = Debug|Any CPU + {488964A2-C7A2-45C9-9CDB-98515AFD7242}.Debug|x64.ActiveCfg = Debug|Any CPU + {488964A2-C7A2-45C9-9CDB-98515AFD7242}.Debug|x64.Build.0 = Debug|Any CPU + {488964A2-C7A2-45C9-9CDB-98515AFD7242}.Debug|x86.ActiveCfg = Debug|Any CPU + {488964A2-C7A2-45C9-9CDB-98515AFD7242}.Debug|x86.Build.0 = Debug|Any CPU + {488964A2-C7A2-45C9-9CDB-98515AFD7242}.Release|Any CPU.ActiveCfg = Release|Any CPU + {488964A2-C7A2-45C9-9CDB-98515AFD7242}.Release|Any CPU.Build.0 = Release|Any CPU + {488964A2-C7A2-45C9-9CDB-98515AFD7242}.Release|x64.ActiveCfg = Release|Any CPU + {488964A2-C7A2-45C9-9CDB-98515AFD7242}.Release|x64.Build.0 = Release|Any CPU + {488964A2-C7A2-45C9-9CDB-98515AFD7242}.Release|x86.ActiveCfg = Release|Any CPU + {488964A2-C7A2-45C9-9CDB-98515AFD7242}.Release|x86.Build.0 = Release|Any CPU + {CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Debug|x64.ActiveCfg = Debug|Any CPU + {CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Debug|x64.Build.0 = Debug|Any CPU + {CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Debug|x86.ActiveCfg = Debug|Any CPU + {CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Debug|x86.Build.0 = Debug|Any CPU + {CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Release|Any CPU.Build.0 = Release|Any CPU + {CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Release|x64.ActiveCfg = Release|Any CPU + {CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Release|x64.Build.0 = Release|Any CPU + {CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Release|x86.ActiveCfg = Release|Any CPU + {CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {CFF799B9-A8E7-46C8-B4FD-721B7308FA9C} = {95E98121-7DA4-4085-A8E3-B0430628452F} + {8A3B7C9E-1D4F-4E5A-9B2C-3D5E6F7A8B9C} = {95E98121-7DA4-4085-A8E3-B0430628452F} + {1F613F65-5F3C-41E6-B86B-774301D80E42} = {95E98121-7DA4-4085-A8E3-B0430628452F} + {D1FDF2F0-E8D2-4F00-95CA-1759047EA205} = {48492269-2B47-43FE-BC14-A901054EE5AE} + {D916F3F0-561B-4BC5-BEC2-B4C2B9CCFF7E} = {48492269-2B47-43FE-BC14-A901054EE5AE} + {2C0E9D45-3E34-4A60-A6B5-1E89B935419D} = {48492269-2B47-43FE-BC14-A901054EE5AE} + {72331F53-884D-42A1-8EEA-8CC83FFAB623} = {48492269-2B47-43FE-BC14-A901054EE5AE} + EndGlobalSection EndGlobal diff --git a/NordPool.Manager.Tests/BoilerControlServiceTests.cs b/NordPool.Manager.Tests/BoilerControlServiceTests.cs deleted file mode 100644 index 0d9daf7..0000000 --- a/NordPool.Manager.Tests/BoilerControlServiceTests.cs +++ /dev/null @@ -1,215 +0,0 @@ -using FluentAssertions; -using Microsoft.Extensions.Logging; -using Moq; -using NordPoolManager; -using NordPoolManager.Models.Enums; - -namespace NordPool.Manager.Tests; - -public class BoilerControlServiceTests -{ - private readonly BoilerControlService _sut; - - public BoilerControlServiceTests() - { - var loggerMock = new Mock>(); - _sut = new BoilerControlService(loggerMock.Object); - } - - #region TurnOn scenarios - - [Theory] - [InlineData("off")] - [InlineData("OFF")] - [InlineData("Off")] - [InlineData(null)] - [InlineData("unavailable")] - public void DetermineAction_WhenCheapAndWaterNotReady_ShouldReturnTurnOn(string? switchState) - { - // Arrange - const bool isNowCheap = true; - const bool waterReady = false; - - // Act - var result = _sut.DetermineAction(isNowCheap, waterReady, switchState); - - // Assert - result.Should().Be(BoilerAction.TurnOn); - } - - #endregion - - #region TurnOff scenarios - - [Fact] - public void DetermineAction_WhenNotCheapAndSwitchIsOn_ShouldReturnTurnOff() - { - // Arrange - const bool isNowCheap = false; - const bool waterReady = false; - - // Act - var result = _sut.DetermineAction(isNowCheap, waterReady, "on"); - - // Assert - result.Should().Be(BoilerAction.TurnOff); - } - - [Fact] - public void DetermineAction_WhenWaterReadyAndSwitchIsOn_ShouldReturnTurnOff() - { - // Arrange - const bool isNowCheap = true; - const bool waterReady = true; - - // Act - var result = _sut.DetermineAction(isNowCheap, waterReady, "on"); - - // Assert - result.Should().Be(BoilerAction.TurnOff); - } - - [Fact] - public void DetermineAction_WhenNotCheapAndWaterReadyAndSwitchIsOn_ShouldReturnTurnOff() - { - // Arrange - const bool isNowCheap = false; - const bool waterReady = true; - - // Act - var result = _sut.DetermineAction(isNowCheap, waterReady, "on"); - - // Assert - result.Should().Be(BoilerAction.TurnOff); - } - - [Theory] - [InlineData("on")] - [InlineData("ON")] - [InlineData("On")] - public void DetermineAction_WhenNotCheapAndSwitchIsOnCaseInsensitive_ShouldReturnTurnOff(string switchState) - { - // Arrange - const bool isNowCheap = false; - const bool waterReady = false; - - // Act - var result = _sut.DetermineAction(isNowCheap, waterReady, switchState); - - // Assert - result.Should().Be(BoilerAction.TurnOff); - } - - #endregion - - #region NoChange scenarios - - [Fact] - public void DetermineAction_WhenCheapAndNotReadyAndAlreadyOn_ShouldReturnNoChange() - { - // Arrange - const bool isNowCheap = true; - const bool waterReady = false; - - // Act - var result = _sut.DetermineAction(isNowCheap, waterReady, "on"); - - // Assert - result.Should().Be(BoilerAction.NoChange); - } - - [Fact] - public void DetermineAction_WhenNotCheapAndAlreadyOff_ShouldReturnNoChange() - { - // Arrange - const bool isNowCheap = false; - const bool waterReady = false; - - // Act - var result = _sut.DetermineAction(isNowCheap, waterReady, "off"); - - // Assert - result.Should().Be(BoilerAction.NoChange); - } - - [Fact] - public void DetermineAction_WhenWaterReadyAndAlreadyOff_ShouldReturnNoChange() - { - // Arrange - const bool isNowCheap = true; - const bool waterReady = true; - - // Act - var result = _sut.DetermineAction(isNowCheap, waterReady, "off"); - - // Assert - result.Should().Be(BoilerAction.NoChange); - } - - [Fact] - public void DetermineAction_WhenNotCheapAndWaterReadyAndAlreadyOff_ShouldReturnNoChange() - { - // Arrange - const bool isNowCheap = false; - const bool waterReady = true; - - // Act - var result = _sut.DetermineAction(isNowCheap, waterReady, "off"); - - // Assert - result.Should().Be(BoilerAction.NoChange); - } - - [Fact] - public void DetermineAction_WhenNotCheapAndSwitchStateIsNull_ShouldReturnNoChange() - { - // Arrange - const bool isNowCheap = false; - const bool waterReady = false; - - // Act - var result = _sut.DetermineAction(isNowCheap, waterReady, null); - - // Assert - result.Should().Be(BoilerAction.NoChange); - } - - [Fact] - public void DetermineAction_WhenNotCheapAndSwitchStateIsUnavailable_ShouldReturnNoChange() - { - // Arrange - const bool isNowCheap = false; - const bool waterReady = false; - - // Act - var result = _sut.DetermineAction(isNowCheap, waterReady, "unavailable"); - - // Assert - result.Should().Be(BoilerAction.NoChange); - } - - #endregion - - #region Comprehensive theory covering all combinations - - [Theory] - [InlineData(true, false, "off", BoilerAction.TurnOn)] // cheap, not ready, off → turn on - [InlineData(true, false, "on", BoilerAction.NoChange)] // cheap, not ready, already on → no change - [InlineData(true, true, "on", BoilerAction.TurnOff)] // cheap, ready, on → turn off (water heated) - [InlineData(true, true, "off", BoilerAction.NoChange)] // cheap, ready, off → no change - [InlineData(false, false, "on", BoilerAction.TurnOff)] // not cheap, not ready, on → turn off - [InlineData(false, false, "off", BoilerAction.NoChange)] // not cheap, not ready, off → no change - [InlineData(false, true, "on", BoilerAction.TurnOff)] // not cheap, ready, on → turn off - [InlineData(false, true, "off", BoilerAction.NoChange)] // not cheap, ready, off → no change - public void DetermineAction_AllCombinations_ShouldReturnExpectedAction( - bool isNowCheap, bool waterReady, string switchState, BoilerAction expectedAction) - { - // Act - var result = _sut.DetermineAction(isNowCheap, waterReady, switchState); - - // Assert - result.Should().Be(expectedAction); - } - - #endregion -} diff --git a/NordPool.Manager.Tests/CheapestIntervalsFinderTests.cs b/NordPool.Manager.Tests/CheapestIntervalsFinderTests.cs index 837eec0..3b5885c 100644 --- a/NordPool.Manager.Tests/CheapestIntervalsFinderTests.cs +++ b/NordPool.Manager.Tests/CheapestIntervalsFinderTests.cs @@ -441,128 +441,4 @@ public class CheapestIntervalsFinderTests } #endregion - - #region IsWaterReady - - [Fact] - public void IsWaterReady_SwitchOnAndLowPower_ShouldReturnTrue() - { - // Arrange - var sut = CreateSut(); - - // Act - var result = sut.IsWaterReady("on", 0.0); - - // Assert - result.Should().BeTrue(); - } - - [Fact] - public void IsWaterReady_SwitchOnAndPowerBelowThreshold_ShouldReturnTrue() - { - // Arrange - var sut = CreateSut(); - - // Act - var result = sut.IsWaterReady("on", 4.9); - - // Assert - result.Should().BeTrue(); - } - - [Fact] - public void IsWaterReady_SwitchOnAndPowerAtThreshold_ShouldReturnFalse() - { - // Arrange - var sut = CreateSut(); - - // Act - var result = sut.IsWaterReady("on", 5.0); - - // Assert - result.Should().BeFalse(); - } - - [Fact] - public void IsWaterReady_SwitchOnAndHighPower_ShouldReturnFalse() - { - // Arrange - var sut = CreateSut(); - - // Act - var result = sut.IsWaterReady("on", 2000.0); - - // Assert - result.Should().BeFalse(); - } - - [Fact] - public void IsWaterReady_SwitchOff_ShouldReturnFalse() - { - // Arrange - var sut = CreateSut(); - - // Act - var result = sut.IsWaterReady("off", 0.0); - - // Assert - result.Should().BeFalse(); - } - - [Fact] - public void IsWaterReady_NullSwitchState_ShouldReturnFalse() - { - // Arrange - var sut = CreateSut(); - - // Act - var result = sut.IsWaterReady(null, 0.0); - - // Assert - result.Should().BeFalse(); - } - - [Fact] - public void IsWaterReady_NullPowerWatts_ShouldReturnFalse() - { - // Arrange - var sut = CreateSut(); - - // Act - var result = sut.IsWaterReady("on", null); - - // Assert - result.Should().BeFalse(); - } - - [Fact] - public void IsWaterReady_BothNull_ShouldReturnFalse() - { - // Arrange - var sut = CreateSut(); - - // Act - var result = sut.IsWaterReady(null, null); - - // Assert - result.Should().BeFalse(); - } - - [Theory] - [InlineData("ON")] // uppercase - [InlineData("On")] // mixed case - [InlineData("on")] // lowercase - public void IsWaterReady_SwitchOnCaseInsensitive_ShouldReturnTrue(string switchState) - { - // Arrange - var sut = CreateSut(); - - // Act - var result = sut.IsWaterReady(switchState, 0.0); - - // Assert - result.Should().BeTrue(); - } - - #endregion } diff --git a/NordPool.Manager.Tests/NordPool.Manager.Tests.csproj b/NordPool.Manager.Tests/NordPool.Manager.Tests.csproj index c2bdbd9..68cf51c 100644 --- a/NordPool.Manager.Tests/NordPool.Manager.Tests.csproj +++ b/NordPool.Manager.Tests/NordPool.Manager.Tests.csproj @@ -1,4 +1,4 @@ - + net10.0 @@ -28,6 +28,7 @@ + diff --git a/NordPool.Manager.Tests/NordPoolEntityServiceTests.cs b/NordPool.Manager.Tests/NordPoolEntityServiceTests.cs index 104e610..34dfa81 100644 --- a/NordPool.Manager.Tests/NordPoolEntityServiceTests.cs +++ b/NordPool.Manager.Tests/NordPoolEntityServiceTests.cs @@ -31,15 +31,13 @@ public class NordPoolEntityServiceTests // Assert result.Should().NotBeNull(); - result.Should().HaveCount(8); + result.Should().HaveCount(6); result.Should().Contain(e => e.EntityId == "sensor.nordpool_last_update_time"); result.Should().Contain(e => e.EntityId == "sensor.nordpool_current_price"); result.Should().Contain(e => e.EntityId == "sensor.nordpool_today_prices"); result.Should().Contain(e => e.EntityId == "sensor.nordpool_tomorrow_prices"); result.Should().Contain(e => e.EntityId == "sensor.nordpool_today_tomorrow_prices"); result.Should().Contain(e => e.EntityId == "sensor.nordpool_cheapest_intervals"); - result.Should().Contain(e => e.EntityId == "sensor.nordpool_boiler_water_ready"); - result.Should().Contain(e => e.EntityId == "switch.nordpool_boiler_skip_price_cap"); } [Fact] @@ -76,9 +74,7 @@ public class NordPoolEntityServiceTests var result = _sut.GetInitEntitiesList("EUR/kWh"); // Assert - result.Should().Contain(e => e.Domain == "sensor"); - result.Should().Contain(e => e.Domain == "switch"); - result.Should().OnlyContain(e => e.Domain == "sensor" || e.Domain == "switch"); + result.Should().OnlyContain(e => e.Domain == "sensor"); } [Fact] @@ -106,7 +102,7 @@ public class NordPoolEntityServiceTests await _sut.CreateEntitiesAsync("EUR/kWh"); // Assert - _entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny()), Times.Exactly(8)); + _entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny()), Times.Exactly(6)); } [Fact] @@ -130,7 +126,7 @@ public class NordPoolEntityServiceTests await _sut.CreateEntitiesAsync("EUR/kWh"); // Assert - _entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny()), Times.Exactly(8)); + _entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny()), Times.Exactly(6)); } #endregion @@ -154,8 +150,6 @@ public class NordPoolEntityServiceTests _entityManagerMock.Verify(em => em.RemoveEntity("sensor.nordpool_tomorrow_prices"), Times.Once); _entityManagerMock.Verify(em => em.RemoveEntity("sensor.nordpool_today_tomorrow_prices"), Times.Once); _entityManagerMock.Verify(em => em.RemoveEntity("sensor.nordpool_cheapest_intervals"), Times.Once); - _entityManagerMock.Verify(em => em.RemoveEntity("sensor.nordpool_boiler_water_ready"), Times.Once); - _entityManagerMock.Verify(em => em.RemoveEntity("switch.nordpool_boiler_skip_price_cap"), Times.Once); } [Fact] @@ -256,13 +250,11 @@ public class NordPoolEntityServiceTests // Assert _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_last_update_time", "unknown"), Times.Once); - _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_current_price", "0"), Times.Once); + _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_current_price", ""), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_today_prices", "0"), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_tomorrow_prices", "0"), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices", "unknown"), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_cheapest_intervals", "0"), Times.Once); - _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_boiler_water_ready", "unknown"), Times.Once); - _entityManagerMock.Verify(em => em.SetEntityState("switch.nordpool_boiler_skip_price_cap", "OFF"), Times.Once); } [Fact] @@ -284,7 +276,6 @@ public class NordPoolEntityServiceTests _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_tomorrow_prices", It.IsAny()), Times.Once); _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny()), Times.Once); _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_cheapest_intervals", It.IsAny()), Times.Once); - _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_boiler_water_ready", It.IsAny()), Times.Once); } [Fact] @@ -308,7 +299,7 @@ public class NordPoolEntityServiceTests [Fact] public async Task ResetEntitiesAsync_ShouldCallSetStateAndAttributesCorrectly() { - // Arrange - 8 entities get state, 7 entities get attributes (switch has state only) + // Arrange - 6 entities get state and attributes _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny(), It.IsAny())) .Returns(Task.CompletedTask); _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) @@ -318,8 +309,8 @@ public class NordPoolEntityServiceTests await _sut.ResetEntitiesAsync(); // Assert - _entityManagerMock.Verify(em => em.SetEntityState(It.IsAny(), It.IsAny()), Times.Exactly(8)); - _entityManagerMock.Verify(em => em.SetEntityAttributes(It.IsAny(), It.IsAny()), Times.Exactly(7)); + _entityManagerMock.Verify(em => em.SetEntityState(It.IsAny(), It.IsAny()), Times.Exactly(6)); + _entityManagerMock.Verify(em => em.SetEntityAttributes(It.IsAny(), It.IsAny()), Times.Exactly(6)); } #endregion @@ -353,10 +344,7 @@ public class NordPoolEntityServiceTests SkipPriceCap = false, ConfiguredReadyBy = "06:00", IsNowCheap = false, - NextCheapIntervalStart = null, - WaterReady = false, - BoilerSwitchState = "off", - BoilerPowerWatts = 0.0 + NextCheapIntervalStart = null }; } @@ -381,7 +369,6 @@ public class NordPoolEntityServiceTests _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_tomorrow_prices", "1"), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices", It.Is(s => s.Contains('-') && s.Contains(':'))), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_cheapest_intervals", It.IsAny()), Times.Once); - _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_boiler_water_ready", It.IsAny()), Times.Once); } [Fact] diff --git a/NordPool.Manager.Tests/NordPoolInitTests.cs b/NordPool.Manager.Tests/NordPoolInitTests.cs index b378ca7..49c58b7 100644 --- a/NordPool.Manager.Tests/NordPoolInitTests.cs +++ b/NordPool.Manager.Tests/NordPoolInitTests.cs @@ -1,11 +1,15 @@ using System.Reactive.Concurrency; +using BoilerMonitor.Models; using FluentAssertions; using HomeAssistantGenerated; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; using Moq; using NetDaemon.HassModel; +using NordPool.Models; using NordPoolManager; using NordPoolManager.Interface; +using NordPoolManager.Models; namespace NordPool.Manager.Tests; @@ -16,7 +20,7 @@ public class NordPoolInitTests private readonly Mock _entityServiceMock; private readonly Mock _schedulerMock; private readonly Mock _cheapestIntervalsFinderMock; - private readonly Mock _boilerControlServiceMock; + private readonly Mock _boilerConfigReaderMock; private readonly Mock _haContextMock; private readonly Entities _entities; @@ -28,23 +32,48 @@ public class NordPoolInitTests _schedulerMock = new Mock(); _schedulerMock.Setup(s => s.Now).Returns(DateTimeOffset.UtcNow); _cheapestIntervalsFinderMock = new Mock(); - _boilerControlServiceMock = new Mock(); + _boilerConfigReaderMock = new Mock(); _haContextMock = new Mock(); _entities = new Entities(_haContextMock.Object); + + _priceServiceMock.Setup(p => p.FetchPricesAsync()).Returns(Task.CompletedTask); + _entityServiceMock.Setup(e => e.CleanupEntitiesAsync(It.IsAny())).Returns(Task.CompletedTask); + _entityServiceMock.Setup(e => e.CreateEntitiesAsync(It.IsAny())).Returns(Task.CompletedTask); + _entityServiceMock.Setup(e => e.ResetEntitiesAsync()).Returns(Task.CompletedTask); + _entityServiceMock.Setup(e => e.UpdateEntitiesAsync(It.IsAny())).Returns(Task.CompletedTask); + _priceServiceMock.Setup(p => p.UpdateCurrentPrice()).Returns(0.0); + _priceServiceMock.Setup(p => p.ShouldFetchNewPrices(It.IsAny())).Returns(false); + _priceServiceMock.SetupGet(p => p.DayQuartersIndex).Returns(0); + _priceServiceMock.SetupGet(p => p.TodayNordPoolPrice).Returns((NordPoolPrice?)null); + _priceServiceMock.SetupGet(p => p.TomorrowNordPoolPrice).Returns((NordPoolPrice?)null); + _priceServiceMock.SetupGet(p => p.CurrentPrice).Returns(0.0); + _priceServiceMock.SetupGet(p => p.LastUpdatedDate).Returns((DateTime?)null); + _cheapestIntervalsFinderMock + .Setup(c => c.IsCurrentIntervalCheap(It.IsAny>(), It.IsAny())) + .Returns(false); + _boilerConfigReaderMock.Setup(b => b.ReadConfig()).Returns(new BoilerConfig + { + IntervalCount = 4, + PriceCap = double.MaxValue, + Deadline = DateTime.Today.AddDays(1), + SkipPriceCap = false + }); } - private NordPoolInit CreateSut() + private NordPoolInit CreateSut(NordPoolOptions? nordPoolOptions = null) { + var options = Options.Create( + nordPoolOptions ?? new NordPoolOptions { CleanupEntitiesOnStartup = false }); + return new NordPoolInit( _entities, - _haContextMock.Object, _loggerMock.Object, _priceServiceMock.Object, _entityServiceMock.Object, _schedulerMock.Object, _cheapestIntervalsFinderMock.Object, - _boilerControlServiceMock.Object - ); + _boilerConfigReaderMock.Object, + options); } [Fact] @@ -71,4 +100,24 @@ public class NordPoolInitTests // Assert _entityServiceMock.Verify(es => es.CleanupEntitiesAsync(It.IsAny()), Times.Once); } + + [Fact] + public async Task InitializeAsync_WhenCleanupEntitiesOnStartupIsTrue_ShouldCallEntityCleanup() + { + var sut = CreateSut(new NordPoolOptions { CleanupEntitiesOnStartup = true }); + + await sut.InitializeAsync(); + + _entityServiceMock.Verify(es => es.CleanupEntitiesAsync(It.IsAny()), Times.AtLeastOnce); + } + + [Fact] + public async Task InitializeAsync_WhenCleanupEntitiesOnStartupIsFalse_ShouldNotCallEntityCleanup() + { + var sut = CreateSut(new NordPoolOptions { CleanupEntitiesOnStartup = false }); + + await sut.InitializeAsync(); + + _entityServiceMock.Verify(es => es.CleanupEntitiesAsync(It.IsAny()), Times.Never); + } } diff --git a/NordPool.Manager.Tests/NordPoolPriceServiceTests.cs b/NordPool.Manager.Tests/NordPoolPriceServiceTests.cs index eefcac8..53413f7 100644 --- a/NordPool.Manager.Tests/NordPoolPriceServiceTests.cs +++ b/NordPool.Manager.Tests/NordPoolPriceServiceTests.cs @@ -209,7 +209,7 @@ public class NordPoolPriceServiceTests // Arrange var dto = new NordPoolPriceResultDto { - Prices = [new() { Start = DateTime.UtcNow.ToString("o"), End = DateTime.UtcNow.AddHours(1).ToString("o"), Price = 100.0 }] + Prices = [new NordPoolDayPriceDto { Start = DateTime.UtcNow.ToString("o"), End = DateTime.UtcNow.AddHours(1).ToString("o"), Price = 100.0 }] }; var jsonString = JsonSerializer.Serialize(dto); @@ -241,7 +241,7 @@ public class NordPoolPriceServiceTests // Arrange var dto = new NordPoolPriceResultDto { - Prices = [new() { Start = DateTime.UtcNow.ToString("o"), End = DateTime.UtcNow.AddHours(1).ToString("o"), Price = 100.0 }] + Prices = [new NordPoolDayPriceDto { Start = DateTime.UtcNow.ToString("o"), End = DateTime.UtcNow.AddHours(1).ToString("o"), Price = 100.0 }] }; var jsonString = JsonSerializer.Serialize(dto); diff --git a/NordPool.Manager/BoilerControlService.cs b/NordPool.Manager/BoilerControlService.cs deleted file mode 100644 index 85cc206..0000000 --- a/NordPool.Manager/BoilerControlService.cs +++ /dev/null @@ -1,36 +0,0 @@ -using Microsoft.Extensions.Logging; -using NordPoolManager.Interface; -using NordPoolManager.Models.Enums; - -namespace NordPoolManager; - -public class BoilerControlService(ILogger logger) : IBoilerControlService -{ - private const string SwitchOnState = "on"; - - public BoilerAction DetermineAction(bool isNowCheap, bool waterReady, string? currentSwitchState) - { - var isCurrentlyOn = string.Equals(currentSwitchState, SwitchOnState, StringComparison.OrdinalIgnoreCase); - var shouldBeOn = isNowCheap && !waterReady; - - if (shouldBeOn && !isCurrentlyOn) - { - logger.LogInformation("Boiler should turn ON — cheap interval active, water not ready (current state: {State})", currentSwitchState); - - return BoilerAction.TurnOn; - } - - if (!shouldBeOn && isCurrentlyOn) - { - var reason = waterReady ? "water is already ready" : "not in a cheap interval"; - - logger.LogInformation("Boiler should turn OFF — {Reason} (current state: {State})", reason, currentSwitchState); - - return BoilerAction.TurnOff; - } - - logger.LogDebug("Boiler state unchanged: {State} (cheap={Cheap}, waterReady={WaterReady})", currentSwitchState, isNowCheap, waterReady); - - return BoilerAction.NoChange; - } -} diff --git a/NordPool.Manager/CheapestIntervalsFinder.cs b/NordPool.Manager/CheapestIntervalsFinder.cs index 06156a6..58e799b 100644 --- a/NordPool.Manager/CheapestIntervalsFinder.cs +++ b/NordPool.Manager/CheapestIntervalsFinder.cs @@ -6,8 +6,6 @@ namespace NordPoolManager; public class CheapestIntervalsFinder(ILogger logger) : ICheapestIntervalsFinder { - private const string SwitchOnState = "on"; - public IReadOnlyList FindCheapestIntervals(NordPoolPrice prices, int numberOfIntervals, double priceCap, DateTime deadline) { if (prices.Prices is not { Count: > 0 }) @@ -54,14 +52,4 @@ public class CheapestIntervalsFinder(ILogger logger) : { return cheapestIntervals.AsParallel().Any(interval => utcNow >= interval.Start && utcNow < interval.End); } - - public bool IsWaterReady(string? switchState, double? powerWatts) - { - if (switchState == null || powerWatts == null) - { - return false; - } - - return string.Equals(switchState, SwitchOnState, StringComparison.OrdinalIgnoreCase) && powerWatts.Value < NordPoolConsts.WaterReadyPowerThresholdWatts; - } } diff --git a/NordPool.Manager/Interface/IBoilerControlService.cs b/NordPool.Manager/Interface/IBoilerControlService.cs deleted file mode 100644 index a079a3c..0000000 --- a/NordPool.Manager/Interface/IBoilerControlService.cs +++ /dev/null @@ -1,8 +0,0 @@ -using NordPoolManager.Models.Enums; - -namespace NordPoolManager.Interface; - -public interface IBoilerControlService -{ - BoilerAction DetermineAction(bool isNowCheap, bool waterReady, string? currentSwitchState); -} diff --git a/NordPool.Manager/Interface/ICheapestIntervalsFinder.cs b/NordPool.Manager/Interface/ICheapestIntervalsFinder.cs index e01b3a4..90d3a01 100644 --- a/NordPool.Manager/Interface/ICheapestIntervalsFinder.cs +++ b/NordPool.Manager/Interface/ICheapestIntervalsFinder.cs @@ -7,6 +7,4 @@ public interface ICheapestIntervalsFinder IReadOnlyList FindCheapestIntervals(NordPoolPrice prices, int numberOfIntervals, double priceCap, DateTime deadline); bool IsCurrentIntervalCheap(IReadOnlyList cheapestIntervals, DateTime utcNow); - - bool IsWaterReady(string? switchState, double? powerWatts); } diff --git a/NordPool.Manager/Models/BoilerConfig.cs b/NordPool.Manager/Models/BoilerConfig.cs deleted file mode 100644 index 2dbacf1..0000000 --- a/NordPool.Manager/Models/BoilerConfig.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace NordPoolManager.Models; - -public class BoilerConfig -{ - public int IntervalCount { get; set; } - public double PriceCap { get; set; } - public DateTime Deadline { get; set; } - public bool SkipPriceCap { get; set; } -} diff --git a/NordPool.Manager/Models/Consts/PriceConsts.cs b/NordPool.Manager/Models/Consts/PriceConsts.cs deleted file mode 100644 index 825c896..0000000 --- a/NordPool.Manager/Models/Consts/PriceConsts.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace NordPoolManager.Models.Consts; - -public static class PriceConsts -{ - public const int MaxDailyIntervals = 96; - public const int IntervalsPerHour = 4; -} \ No newline at end of file diff --git a/NordPool.Manager/Models/EntityUpdateContext.cs b/NordPool.Manager/Models/EntityUpdateContext.cs index 5b27ef7..4775208 100644 --- a/NordPool.Manager/Models/EntityUpdateContext.cs +++ b/NordPool.Manager/Models/EntityUpdateContext.cs @@ -19,7 +19,4 @@ public record EntityUpdateContext public required string? ConfiguredReadyBy { get; init; } public required bool IsNowCheap { get; init; } public required DateTime? NextCheapIntervalStart { get; init; } - public required bool WaterReady { get; init; } - public required string? BoilerSwitchState { get; init; } - public required double? BoilerPowerWatts { get; init; } } diff --git a/NordPool.Manager/Models/NordPoolOptions.cs b/NordPool.Manager/Models/NordPoolOptions.cs new file mode 100644 index 0000000..e5f1dfe --- /dev/null +++ b/NordPool.Manager/Models/NordPoolOptions.cs @@ -0,0 +1,11 @@ +namespace NordPoolManager.Models; + +public sealed class NordPoolOptions +{ + public const string SectionName = "NordPool"; + + /// + /// When true, removes existing NordPool MQTT entities before recreating them on app startup. + /// + public bool CleanupEntitiesOnStartup { get; init; } = true; +} diff --git a/NordPool.Manager/NordPool.Manager.csproj b/NordPool.Manager/NordPool.Manager.csproj index 1bb7f44..d312c73 100644 --- a/NordPool.Manager/NordPool.Manager.csproj +++ b/NordPool.Manager/NordPool.Manager.csproj @@ -14,12 +14,15 @@ + + + diff --git a/NordPool.Manager/NordPoolEntityService.cs b/NordPool.Manager/NordPoolEntityService.cs index 92201ff..33e497d 100644 --- a/NordPool.Manager/NordPoolEntityService.cs +++ b/NordPool.Manager/NordPoolEntityService.cs @@ -11,24 +11,19 @@ namespace NordPoolManager; public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger logger) : INordPoolEntityService { private const string LastUpdateTimeEntityId = "sensor.nordpool_last_update_time"; - private const string CurrentPriceEntityId = "sensor.nordpool_current_price"; private const string TodayPricesEntityId = "sensor.nordpool_today_prices"; private const string TomorrowPricesEntityId = "sensor.nordpool_tomorrow_prices"; private const string TodayTomorrowPricesEntityId = "sensor.nordpool_today_tomorrow_prices"; private const string CheapestIntervalsEntityId = "sensor.nordpool_cheapest_intervals"; - private const string BoilerWaterReadyEntityId = "sensor.nordpool_boiler_water_ready"; - private const string BoilerSkipPriceCapEntityId = "switch.nordpool_boiler_skip_price_cap"; private static readonly string[] AllEntityIds = [ LastUpdateTimeEntityId, - CurrentPriceEntityId, + NordPoolConsts.CurrentPriceEntityId, TodayPricesEntityId, TomorrowPricesEntityId, TodayTomorrowPricesEntityId, - CheapestIntervalsEntityId, - BoilerWaterReadyEntityId, - BoilerSkipPriceCapEntityId + CheapestIntervalsEntityId ]; public async Task CreateEntitiesAsync(string? unitOfMeasurement, CancellationToken cancellationToken = default) @@ -65,9 +60,7 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger< ResetTodayPricesAsync(), ResetTomorrowPricesAsync(), ResetTodayTomorrowPricesAsync(), - ResetCheapestIntervalsAsync(), - ResetBoilerWaterReadyAsync(), - ResetBoilerSkipPriceCapAsync() + ResetCheapestIntervalsAsync() ).ConfigureAwait(false); logger.LogInformation("All NordPool entity states reset to defaults"); @@ -84,8 +77,8 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger< private async Task ResetCurrentPriceAsync() { - await SetEntityStateSafe(CurrentPriceEntityId, string.Empty).ConfigureAwait(false); - await SetEntityAttributesSafe(CurrentPriceEntityId, new + await SetEntityStateSafe(NordPoolConsts.CurrentPriceEntityId, string.Empty).ConfigureAwait(false); + await SetEntityAttributesSafe(NordPoolConsts.CurrentPriceEntityId, new { unit_of_measurement = (string?)null, device_class = "monetary", @@ -150,24 +143,6 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger< }).ConfigureAwait(false); } - private async Task ResetBoilerWaterReadyAsync() - { - await SetEntityStateSafe(BoilerWaterReadyEntityId, "unknown").ConfigureAwait(false); - await SetEntityAttributesSafe(BoilerWaterReadyEntityId, new - { - boiler_switch_state = "unknown", - boiler_power_watts = 0.0, - power_threshold_watts = NordPoolConsts.WaterReadyPowerThresholdWatts, - friendly_name = "Boiler water ready", - last_updated = (string?)null - }).ConfigureAwait(false); - } - - private async Task ResetBoilerSkipPriceCapAsync() - { - await SetEntityStateSafe(BoilerSkipPriceCapEntityId, "OFF").ConfigureAwait(false); - } - public async Task UpdateEntitiesAsync(EntityUpdateContext ctx, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); @@ -182,8 +157,7 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger< if (mergedPrices.Count > NordPoolConsts.MaxExpectedPriceEntries) { - logger.LogWarning( - "Merged price count ({Count}) exceeds expected maximum ({Max}). Attribute payload may be oversized", + logger.LogWarning("Merged price count ({Count}) exceeds expected maximum ({Max}). Attribute payload may be oversized", mergedPrices.Count, NordPoolConsts.MaxExpectedPriceEntries); } @@ -194,7 +168,6 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger< logger.LogInformation("Updating sensor.nordpool_tomorrow_prices with {Count} prices", tomorrowPricesCount); logger.LogInformation("Updating sensor.nordpool_today_tomorrow_prices with {Count} merged prices", mergedPrices.Count); logger.LogInformation("Updating sensor.nordpool_cheapest_intervals with {Count} intervals, is_now_cheap={IsNow}", cheapestCount, ctx.IsNowCheap); - logger.LogInformation("Updating sensor.nordpool_boiler_water_ready: {WaterReady} (switch={Switch}, power={Power}W)", ctx.WaterReady, ctx.BoilerSwitchState, ctx.BoilerPowerWatts); var updateTasks = new[] { @@ -203,8 +176,7 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger< UpdateTodayPricesAsync(ctx, todayPricesCount, timestamp), UpdateTomorrowPricesAsync(ctx, tomorrowPricesCount, timestamp), UpdateTodayTomorrowPricesAsync(mergedPrices, updateTimeState, timestamp), - UpdateCheapestIntervalsAsync(ctx, cheapestCount, timestamp), - UpdateBoilerWaterReadyAsync(ctx, timestamp) + UpdateCheapestIntervalsAsync(ctx, cheapestCount, timestamp) }; await Task.WhenAll(updateTasks).ConfigureAwait(false); @@ -219,8 +191,8 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger< private async Task UpdateCurrentPriceAsync(string priceValue, EntityUpdateContext ctx, string timestamp) { - await SetEntityStateSafe(CurrentPriceEntityId, priceValue).ConfigureAwait(false); - await SetEntityAttributesSafe(CurrentPriceEntityId, new + await SetEntityStateSafe(NordPoolConsts.CurrentPriceEntityId, priceValue).ConfigureAwait(false); + await SetEntityAttributesSafe(NordPoolConsts.CurrentPriceEntityId, new { unit_of_measurement = ctx.UnitOfMeasurement, device_class = "monetary", @@ -286,26 +258,13 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger< }).ConfigureAwait(false); } - private async Task UpdateBoilerWaterReadyAsync(EntityUpdateContext ctx, string timestamp) - { - await SetEntityStateSafe(BoilerWaterReadyEntityId, ctx.WaterReady ? "yes" : "no").ConfigureAwait(false); - await SetEntityAttributesSafe(BoilerWaterReadyEntityId, new - { - boiler_switch_state = ctx.BoilerSwitchState ?? "unknown", - boiler_power_watts = ctx.BoilerPowerWatts, - power_threshold_watts = NordPoolConsts.WaterReadyPowerThresholdWatts, - friendly_name = "Boiler water ready", - last_updated = timestamp - }).ConfigureAwait(false); - } - public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); try { - var removeTasks = AllEntityIds.Select(entityId => entityManager.RemoveEntity(entityId)); + var removeTasks = AllEntityIds.Select(entityManager.RemoveEntity); await Task.WhenAll(removeTasks).ConfigureAwait(false); logger.LogInformation("NordPool entities cleaned up successfully"); @@ -319,39 +278,32 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger< internal ICollection GetInitEntitiesList(string? unitOfMeasurement) { - var entries = new List(); + var currentPriceEntityId = NordPoolConsts.CurrentPriceEntityId; + var currentPriceDomainSeparator = currentPriceEntityId.IndexOf('.', StringComparison.Ordinal); + var currentPriceDomain = currentPriceEntityId[..currentPriceDomainSeparator]; + var currentPriceObjectId = currentPriceEntityId[(currentPriceDomainSeparator + 1)..]; - entries.AddRange([ + return + [ new NordPoolEntity("sensor", "nordpool_last_update_time", "NordPool last update time"), - new NordPoolEntity("sensor", "nordpool_current_price", "NordPool current price") + new NordPoolEntity(currentPriceDomain, currentPriceObjectId, "NordPool current price") { Options = new EntityCreationOptions { - UniqueId = CurrentPriceEntityId, + UniqueId = currentPriceEntityId, Name = "NordPool current price" }, - AdditionalConfig = new + AdditionalConfig = NordPoolEntity.CreateAdditionalConfig(new { unit_of_measurement = unitOfMeasurement, state_class = "measurement" - } + }) }, new NordPoolEntity("sensor", "nordpool_today_prices", "NordPool today prices"), new NordPoolEntity("sensor", "nordpool_tomorrow_prices", "NordPool tomorrow prices"), new NordPoolEntity("sensor", "nordpool_today_tomorrow_prices", "NordPool today and tomorrow prices"), - new NordPoolEntity("sensor", "nordpool_cheapest_intervals", "NordPool cheapest boiler intervals"), - new NordPoolEntity("sensor", "nordpool_boiler_water_ready", "Boiler water ready"), - new NordPoolEntity("switch", "nordpool_boiler_skip_price_cap", "Skip price cap, heat until ready") - { - AdditionalConfig = new - { - optimistic = true, - icon = "mdi:water-thermometer-outline" - } - } - ]); - - return entries; + new NordPoolEntity("sensor", "nordpool_cheapest_intervals", "NordPool cheapest boiler intervals") + ]; } private static List MergeTodayTomorrowPrices(NordPoolPrice? today, NordPoolPrice? tomorrow) diff --git a/NordPool.Manager/NordPoolInit.cs b/NordPool.Manager/NordPoolInit.cs index 15b489b..6ef6517 100644 --- a/NordPool.Manager/NordPoolInit.cs +++ b/NordPool.Manager/NordPoolInit.cs @@ -1,14 +1,14 @@ +using System.Globalization; using System.Reactive.Concurrency; +using BoilerMonitor.Models; using HomeAssistantGenerated; using Microsoft.Extensions.Logging; -using NetDaemon.HassModel; +using Microsoft.Extensions.Options; using NetDaemon.AppModel; using NetDaemon.Extensions.Scheduler; using NordPool.Models; using NordPoolManager.Interface; using NordPoolManager.Models; -using NordPoolManager.Models.Consts; -using static NordPoolManager.Models.Enums.BoilerAction; namespace NordPoolManager; @@ -19,46 +19,33 @@ public class NordPoolInit : INordPoolInit private readonly INordPoolPriceService _priceService; private readonly INordPoolEntityService _entityService; private readonly ICheapestIntervalsFinder _cheapestIntervalsFinder; - private readonly IBoilerControlService _boilerControlService; + private readonly IBoilerConfigReader _boilerConfigReader; private readonly IScheduler _scheduler; - private readonly IHaContext _haContext; + private readonly NordPoolOptions _options; - private InputNumberEntity BoilerDailyHoursEntity { get; } - private InputNumberEntity BoilerPriceCapEntity { get; } - private SwitchEntity BoilerSkipPriceCapEntity { get; } - private InputDatetimeEntity BoilerReadyByEntity { get; } - private SwitchEntity BoilerSwitchEntity { get; } - private NumericSensorEntity BoilerPowerEntity { get; } private string? UnitOfMeasurement { get; } private IReadOnlyList? CheapestIntervals { get; set; } - private bool _lastWaterReady; public NordPoolInit( Entities entities, - IHaContext haContext, ILogger logger, INordPoolPriceService priceService, INordPoolEntityService entityService, IScheduler scheduler, ICheapestIntervalsFinder cheapestIntervalsFinder, - IBoilerControlService boilerControlService) + IBoilerConfigReader boilerConfigReader, + IOptions options) { _logger = logger; - _haContext = haContext; _priceService = priceService; _entityService = entityService; _scheduler = scheduler; _cheapestIntervalsFinder = cheapestIntervalsFinder; - _boilerControlService = boilerControlService; + _boilerConfigReader = boilerConfigReader; + _options = options.Value; var nordPoolPriceSensor = entities.Sensor.NordpoolPrice; UnitOfMeasurement = nordPoolPriceSensor.EntityState?.Attributes?.UnitOfMeasurement ?? "EUR/kWh"; - BoilerDailyHoursEntity = entities.InputNumber.BoilerDailyHours; - BoilerPriceCapEntity = entities.InputNumber.BoilerPriceCap; - BoilerSkipPriceCapEntity = new SwitchEntity(_haContext, "switch.nordpool_boiler_skip_price_cap"); - BoilerReadyByEntity = entities.InputDatetime.BoilerReadyBy; - BoilerSwitchEntity = entities.Switch.Sonoff1002230e32; - BoilerPowerEntity = entities.Sensor.Sonoff1002230e32Power; _ = InitializeAndScheduleAsync(); } @@ -69,8 +56,6 @@ public class NordPoolInit : INordPoolInit { await InitializeAsync(); SchedulePeriodicUpdates(); - ScheduleEndOfDayReminder(); - SubscribeToSkipPriceCapChanges(); } catch (Exception ex) { @@ -78,60 +63,6 @@ public class NordPoolInit : INordPoolInit } } - private void ScheduleEndOfDayReminder() - { - _scheduler.ScheduleCron("0 20 * * *", CheckSkipPriceCapReminderAsync); - } - - private void CheckSkipPriceCapReminderAsync() - { - try - { - var switchState = BoilerSkipPriceCapEntity.State; - if (string.Equals(switchState, "on", StringComparison.OrdinalIgnoreCase)) - { - _haContext.CallService("notify", "mobile_app_marius_phone", null, new - { - message = "Remember to turn off 'Skip price cap, heat until ready' if you're done heating.", - title = "Boiler reminder" - }); - _logger.LogInformation("End-of-day reminder sent: skip price cap switch is still ON"); - } - } - catch (Exception ex) - { - _logger.LogError(ex, "Error checking skip price cap reminder"); - } - } - - private void SubscribeToSkipPriceCapChanges() - { - BoilerSkipPriceCapEntity.StateChanges() - .Subscribe(e => - { - if (e.Old?.State == e.New?.State) - { - return; - } - - _logger.LogInformation("Skip price cap switch changed, recalculating cheapest intervals"); - _ = RecalculateOnConfigChangeAsync(); - }); - } - - private async Task RecalculateOnConfigChangeAsync() - { - try - { - var result = UpdateCheapestIntervals(); - await UpdateEntitiesAsync(result.IntervalCount, result.PriceCap, result.SkipPriceCap); - } - catch (Exception ex) - { - _logger.LogError(ex, "Error recalculating on skip price cap switch change"); - } - } - public async Task InitializeAsync() { try @@ -140,6 +71,15 @@ public class NordPoolInit : INordPoolInit await _priceService.FetchPricesAsync(); + if (_options.CleanupEntitiesOnStartup) + { + await _entityService.CleanupEntitiesAsync(); + } + else + { + _logger.LogInformation("Skipping NordPool entity cleanup on startup (CleanupEntitiesOnStartup is false)"); + } + await _entityService.CreateEntitiesAsync(UnitOfMeasurement); await _entityService.ResetEntitiesAsync(); @@ -154,8 +94,8 @@ public class NordPoolInit : INordPoolInit _logger.LogWarning("Current price is 0, which may indicate an issue with price retrieval"); } - var result = UpdateCheapestIntervals(); - await UpdateEntitiesAsync(result.IntervalCount, result.PriceCap, result.SkipPriceCap); + var (_, boilerConfig) = UpdateCheapestIntervals(); + await UpdateEntitiesAsync(boilerConfig); _logger.LogInformation("NordPool price initialized with current price: {CurrentPrice} {Unit}", _priceService.CurrentPrice, UnitOfMeasurement); } @@ -220,8 +160,8 @@ public class NordPoolInit : INordPoolInit _priceService.UpdateCurrentPrice(); - var result = UpdateCheapestIntervals(); - await UpdateEntitiesAsync(result.IntervalCount, result.PriceCap, result.SkipPriceCap); + var (_, boilerConfig) = UpdateCheapestIntervals(); + await UpdateEntitiesAsync(boilerConfig); _logger.LogInformation("NordPool prices updated successfully. Current price: {CurrentPrice} {Unit}", _priceService.CurrentPrice, UnitOfMeasurement); } @@ -236,11 +176,11 @@ public class NordPoolInit : INordPoolInit await _entityService.CleanupEntitiesAsync(cancellationToken); } - private CheapestIntervalsUpdateResult UpdateCheapestIntervals() + private (CheapestIntervalsUpdateResult Result, BoilerConfig Config) UpdateCheapestIntervals() { - var boilerConfig = ReadBoilerConfig(); - var effectivePriceCap = boilerConfig.SkipPriceCap ? double.MaxValue : boilerConfig.PriceCap; - var effectiveIntervalCount = boilerConfig.SkipPriceCap ? PriceConsts.MaxDailyIntervals : boilerConfig.IntervalCount; + var config = _boilerConfigReader.ReadConfig(); + var effectivePriceCap = config.SkipPriceCap ? double.MaxValue : config.PriceCap; + var effectiveIntervalCount = config.SkipPriceCap ? NordPoolConsts.MaxDailyIntervals : config.IntervalCount; try { @@ -248,18 +188,18 @@ public class NordPoolInit : INordPoolInit { _logger.LogDebug("No today prices available, skipping cheapest intervals calculation"); CheapestIntervals = []; - return new CheapestIntervalsUpdateResult + return (new CheapestIntervalsUpdateResult { - IntervalCount = boilerConfig.IntervalCount, - PriceCap = boilerConfig.PriceCap, - SkipPriceCap = boilerConfig.SkipPriceCap - }; + IntervalCount = config.IntervalCount, + PriceCap = config.PriceCap, + SkipPriceCap = config.SkipPriceCap + }, config); } - CheapestIntervals = _cheapestIntervalsFinder.FindCheapestIntervals(_priceService.TodayNordPoolPrice, effectiveIntervalCount, effectivePriceCap, boilerConfig.Deadline); + CheapestIntervals = _cheapestIntervalsFinder.FindCheapestIntervals(_priceService.TodayNordPoolPrice, effectiveIntervalCount, effectivePriceCap, config.Deadline); _logger.LogInformation("Cheapest intervals updated: {Count} intervals (config: {Hours}h / {Intervals} intervals, cap: {Cap}, skipPriceCap: {Skip}, deadline: {Deadline})", - CheapestIntervals.Count, boilerConfig.IntervalCount / 4.0, effectiveIntervalCount, effectivePriceCap, boilerConfig.SkipPriceCap, boilerConfig.Deadline); + CheapestIntervals.Count, config.IntervalCount / 4.0, effectiveIntervalCount, effectivePriceCap, config.SkipPriceCap, config.Deadline); } catch (Exception ex) { @@ -267,65 +207,24 @@ public class NordPoolInit : INordPoolInit CheapestIntervals = []; } - return new CheapestIntervalsUpdateResult + return (new CheapestIntervalsUpdateResult { - IntervalCount = boilerConfig.IntervalCount, - PriceCap = boilerConfig.PriceCap, - SkipPriceCap = boilerConfig.SkipPriceCap - }; + IntervalCount = config.IntervalCount, + PriceCap = config.PriceCap, + SkipPriceCap = config.SkipPriceCap + }, config); } - private BoilerConfig ReadBoilerConfig() - { - var boilerConfig = new BoilerConfig(); - - var dailyHours = BoilerDailyHoursEntity.State ?? 1.0; - - var intervalCount = (int)(dailyHours * PriceConsts.IntervalsPerHour); - - if (intervalCount <= 0) - { - intervalCount = PriceConsts.IntervalsPerHour; - } - - boilerConfig.IntervalCount = intervalCount; - - var priceCap = BoilerPriceCapEntity.State ?? double.MaxValue; - - if (priceCap <= 0) - { - priceCap = double.MaxValue; - } - - boilerConfig.PriceCap = priceCap; - - var deadline = DateTime.Today.AddDays(1); - var readyByState = BoilerReadyByEntity.State; - - if (!string.IsNullOrEmpty(readyByState) && TimeSpan.TryParse(readyByState, out var readyByTime)) - { - deadline = DateTime.Today.Add(readyByTime); - } - - boilerConfig.Deadline = deadline; - - var skipPriceCapState = BoilerSkipPriceCapEntity.State; - boilerConfig.SkipPriceCap = string.Equals(skipPriceCapState, "on", StringComparison.OrdinalIgnoreCase); - - _logger.LogDebug("Boiler config: intervals={Intervals}, priceCap={Cap}, skipPriceCap={Skip}, deadline={Deadline}", boilerConfig.IntervalCount, boilerConfig.PriceCap, boilerConfig.SkipPriceCap, boilerConfig.Deadline); - - return boilerConfig; - } - - private async Task UpdateEntitiesAsync(int configuredIntervalCount, double configuredPriceCap, bool skipPriceCap) + private async Task UpdateEntitiesAsync(BoilerConfig boilerConfig) { var cetTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time"); var nowCet = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, cetTimeZone); var todayCet = DateOnly.FromDateTime(nowCet); var currentDateTime = DateTime.Now; - var configuredHours = BoilerDailyHoursEntity.State ?? 1.0; - var configuredReadyBy = BoilerReadyByEntity.State ?? ""; + var configuredHours = (double)boilerConfig.IntervalCount / NordPoolConsts.IntervalsPerHour; + var configuredReadyBy = boilerConfig.Deadline.TimeOfDay.ToString(@"hh\:mm", CultureInfo.InvariantCulture); + var isNowCheap = CheapestIntervals != null && _cheapestIntervalsFinder.IsCurrentIntervalCheap(CheapestIntervals, currentDateTime); var nextCheapInterval = CheapestIntervals? @@ -333,39 +232,6 @@ public class NordPoolInit : INordPoolInit .OrderBy(i => i.Start) .FirstOrDefault(); - var boilerSwitchState = BoilerSwitchEntity.State; - var boilerPowerWatts = BoilerPowerEntity.State; - var waterReady = _cheapestIntervalsFinder.IsWaterReady(boilerSwitchState, boilerPowerWatts); - - if (!_lastWaterReady && waterReady) - { - _haContext.CallService("notify", "mobile_app_marius_phone", null, new - { - message = "Hot water is ready.", - title = "Boiler" - }); - _logger.LogInformation("Water ready notification sent to mobile_app_marius_phone"); - } - _lastWaterReady = waterReady; - - var boilerAction = _boilerControlService.DetermineAction(isNowCheap, waterReady, boilerSwitchState); - - switch (boilerAction) - { - case TurnOn: - BoilerSwitchEntity.TurnOn(); - - break; - case TurnOff: - BoilerSwitchEntity.TurnOff(); - - break; - case NoChange: - break; - default: - throw new ArgumentOutOfRangeException(); - } - var context = new EntityUpdateContext { CurrentPrice = _priceService.CurrentPrice, @@ -377,15 +243,12 @@ public class NordPoolInit : INordPoolInit TomorrowNordPoolPrice = _priceService.TomorrowNordPoolPrice, CheapestIntervals = CheapestIntervals, ConfiguredHours = configuredHours, - ConfiguredIntervalCount = configuredIntervalCount, - ConfiguredPriceCap = configuredPriceCap, - SkipPriceCap = skipPriceCap, + ConfiguredIntervalCount = boilerConfig.IntervalCount, + ConfiguredPriceCap = boilerConfig.PriceCap, + SkipPriceCap = boilerConfig.SkipPriceCap, ConfiguredReadyBy = configuredReadyBy, IsNowCheap = isNowCheap, - NextCheapIntervalStart = nextCheapInterval?.Start, - WaterReady = waterReady, - BoilerSwitchState = boilerSwitchState, - BoilerPowerWatts = boilerPowerWatts + NextCheapIntervalStart = nextCheapInterval?.Start }; await _entityService.UpdateEntitiesAsync(context); diff --git a/NordPool.Models/CompactNordPoolDayPrice.cs b/NordPool.Models/CompactNordPoolDayPrice.cs index 07153a6..caf92ba 100644 --- a/NordPool.Models/CompactNordPoolDayPrice.cs +++ b/NordPool.Models/CompactNordPoolDayPrice.cs @@ -43,23 +43,36 @@ internal sealed class CompactNordPoolDayPriceConverter : JsonConverter public const int MinutesPerInterval = 15; + /// + /// Number of 15-minute intervals in one hour. + /// + public const int IntervalsPerHour = 4; + + /// + /// Maximum number of 15-minute intervals in a single day (96 = 24h * 4). + /// + public const int MaxDailyIntervals = 96; + /// /// Maximum expected price entries when today and tomorrow are both available /// (96 intervals per day x 2 days). Used for logging a warning if exceeded. /// public const int MaxExpectedPriceEntries = 192; + public const string DeviceIdentifier = "nordpool"; + public const string DeviceName = "NordPool"; + public const string DeviceManufacturer = "HomeAssistant App Daemon"; + /// - /// Power threshold in watts below which the boiler is considered to have finished heating (water ready). + /// Home Assistant entity id for the Nord Pool current price sensor published by this integration. /// - public const double WaterReadyPowerThresholdWatts = 5.0; + public const string CurrentPriceEntityId = "sensor.nordpool_current_price"; } \ No newline at end of file diff --git a/NordPool.Models/NordPoolDayPrice.cs b/NordPool.Models/NordPoolDayPrice.cs index 166d41c..f71f636 100644 --- a/NordPool.Models/NordPoolDayPrice.cs +++ b/NordPool.Models/NordPoolDayPrice.cs @@ -1,15 +1,8 @@ -using System.Text.Json.Serialization; - namespace NordPool.Models; public class NordPoolDayPrice { - [JsonPropertyName("start")] - public DateTime? Start { get; set; } - - [JsonPropertyName("end")] - public DateTime? End { get; set; } - - [JsonPropertyName("price")] - public double? Price { get; set; } + public DateTime? Start { get; init; } + public DateTime? End { get; init; } + public double? Price { get; init; } } \ No newline at end of file diff --git a/NordPool.Models/NordPoolDayPriceExtensions.cs b/NordPool.Models/NordPoolDayPriceExtensions.cs index 4ea53d3..147c520 100644 --- a/NordPool.Models/NordPoolDayPriceExtensions.cs +++ b/NordPool.Models/NordPoolDayPriceExtensions.cs @@ -5,7 +5,9 @@ public static class NordPoolDayPriceExtensions public static List ToCompact(this IEnumerable? prices) { if (prices is null) + { return []; + } return prices.Select(CompactNordPoolDayPrice.FromDayPrice).ToList(); } diff --git a/NordPool.Models/NordPoolEntities.cs b/NordPool.Models/NordPoolEntities.cs index 8c19792..f430629 100644 --- a/NordPool.Models/NordPoolEntities.cs +++ b/NordPool.Models/NordPoolEntities.cs @@ -1,13 +1,21 @@ -using HomeAssistant.Models; +using HomeAssistant.Models; using NetDaemon.Extensions.MqttEntityManager; namespace NordPool.Models; public class NordPoolEntity : EntityCreateModel { - public string Domain { get; set; } // example: sensor - public string Identifier { get; set; } // example: name of the sensor - public string Name { get; set; } // friendly name for UI + private static readonly object DeviceBlock = new + { + identifiers = new[] { NordPoolConsts.DeviceIdentifier }, + name = NordPoolConsts.DeviceName, + model = NordPoolConsts.DeviceName, + manufacturer = NordPoolConsts.DeviceManufacturer + }; + + public string Domain { get; set; } + public string Identifier { get; set; } + public string Name { get; set; } public NordPoolEntity(string domain, string identifier, string name) { @@ -20,7 +28,22 @@ public class NordPoolEntity : EntityCreateModel { UniqueId = EntityId, Name = Name - }; + + AdditionalConfig = new { device = DeviceBlock }; + } + + /// + /// Creates an AdditionalConfig that merges custom properties with the NordPool device block. + /// Use this when an entity needs extra config beyond the default device assignment. + /// + public static object CreateAdditionalConfig(object extraProperties) + { + var extras = extraProperties.GetType().GetProperties() + .ToDictionary(p => p.Name, p => p.GetValue(extraProperties)); + + extras["device"] = DeviceBlock; + + return extras; } } \ No newline at end of file diff --git a/PowerMonitor.Manager.Tests/PowerSensorDiscoveryServiceTests.cs b/PowerMonitor.Manager.Tests/PowerSensorDiscoveryServiceTests.cs index 16071b1..8a0f407 100644 --- a/PowerMonitor.Manager.Tests/PowerSensorDiscoveryServiceTests.cs +++ b/PowerMonitor.Manager.Tests/PowerSensorDiscoveryServiceTests.cs @@ -40,9 +40,20 @@ public class PowerSensorDiscoveryServiceTests foreach (var (entityId, deviceClass, unit, friendlyName) in entities) { var attributes = new Dictionary(); - if (deviceClass is not null) attributes["device_class"] = deviceClass; - if (unit is not null) attributes["unit_of_measurement"] = unit; - if (friendlyName is not null) attributes["friendly_name"] = friendlyName; + if (deviceClass is not null) + { + attributes["device_class"] = deviceClass; + } + + if (unit is not null) + { + attributes["unit_of_measurement"] = unit; + } + + if (friendlyName is not null) + { + attributes["friendly_name"] = friendlyName; + } var attributesJson = JsonSerializer.SerializeToElement(attributes); var entityState = new EntityState { AttributesJson = attributesJson }; diff --git a/PowerMonitor.Manager/PowerMonitor.Manager.csproj b/PowerMonitor.Manager/PowerMonitor.Manager.csproj index 8c4e2bb..aa4d7c5 100644 --- a/PowerMonitor.Manager/PowerMonitor.Manager.csproj +++ b/PowerMonitor.Manager/PowerMonitor.Manager.csproj @@ -15,6 +15,7 @@ + diff --git a/PowerMonitor.Manager/PowerMonitorInit.cs b/PowerMonitor.Manager/PowerMonitorInit.cs index 6c0a492..0be59fe 100644 --- a/PowerMonitor.Manager/PowerMonitorInit.cs +++ b/PowerMonitor.Manager/PowerMonitorInit.cs @@ -6,6 +6,7 @@ using NetDaemon.AppModel; using NetDaemon.Extensions.Scheduler; using NetDaemon.HassModel; using NetDaemon.HassModel.Entities; +using NordPool.Models; using PowerMonitorManager.Interface; using PowerMonitorManager.Models; using PowerMonitorManager.Models.Consts; @@ -24,8 +25,6 @@ public sealed class PowerMonitorInit : IPowerMonitorInit private readonly IPowerCostCalculationService _costService; private readonly IPowerMonitorEntityService _entityService; - private const string NordPoolCurrentPriceEntityId = "sensor.nordpool_current_price"; - private int _mainMeterConsecutiveFailures; private DateTime? _anomalyStartTime; @@ -246,7 +245,7 @@ public sealed class PowerMonitorInit : IPowerMonitorInit private double ReadNordPoolPrice() { - var state = _haContext.GetState(NordPoolCurrentPriceEntityId); + var state = _haContext.GetState(NordPoolConsts.CurrentPriceEntityId); if (state?.State is null || state.State == "unavailable" || state.State == "unknown") { _logger.LogDebug("NordPool price entity unavailable, using last known price");