feat: migrate boiler control implementation to BoilerMonitor namespace and add budget handling logic
This commit is contained in:
Vendored
+7
@@ -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": []
|
||||||
|
}
|
||||||
@@ -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<ILogger<BoilerControlService>>();
|
||||||
|
_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
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<IsPackable>false</IsPackable>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="coverlet.collector" Version="8.0.0">
|
||||||
|
<PrivateAssets>all</PrivateAssets>
|
||||||
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
|
</PackageReference>
|
||||||
|
<PackageReference Include="Microsoft.Extensions.TimeProvider.Testing" Version="10.4.0" />
|
||||||
|
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.3.0" />
|
||||||
|
<PackageReference Include="xunit" Version="2.9.3" />
|
||||||
|
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5">
|
||||||
|
<PrivateAssets>all</PrivateAssets>
|
||||||
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
|
</PackageReference>
|
||||||
|
<PackageReference Include="FluentAssertions" Version="8.8.0" />
|
||||||
|
<PackageReference Include="Moq" Version="4.20.72" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<Using Include="Xunit" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\BoilerMonitor.Manager\BoilerMonitor.Manager.csproj" />
|
||||||
|
<ProjectReference Include="..\BoilerMonitor.Models\BoilerMonitor.Models.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<IEntityManager> _entityManagerMock;
|
||||||
|
private readonly Mock<IHaContext> _haContextMock;
|
||||||
|
private readonly Mock<ILogger<BoilerMonitorEntityService>> _loggerMock;
|
||||||
|
private readonly BoilerMonitorEntityService _sut;
|
||||||
|
|
||||||
|
public BoilerMonitorEntityServiceTests()
|
||||||
|
{
|
||||||
|
_entityManagerMock = new Mock<IEntityManager>();
|
||||||
|
_haContextMock = new Mock<IHaContext>();
|
||||||
|
_loggerMock = new Mock<ILogger<BoilerMonitorEntityService>>();
|
||||||
|
_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<string>(), It.IsAny<string>()))
|
||||||
|
.Returns(Task.CompletedTask);
|
||||||
|
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
|
||||||
|
.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<string>(), It.IsAny<string>()))
|
||||||
|
.Returns(Task.CompletedTask);
|
||||||
|
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
|
||||||
|
.Returns(Task.CompletedTask);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
await _sut.ResetTransientEntitiesAsync();
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityState(TodayRuntimeEntityId, It.IsAny<string>()), Times.Never);
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityState(SessionCountEntityId, It.IsAny<string>()), Times.Never);
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityState(BudgetPercentageEntityId, It.IsAny<string>()), Times.Never);
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityState(BudgetExhaustedEntityId, It.IsAny<string>()), Times.Never);
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityState(RemainingTimeEntityId, It.IsAny<string>()), Times.Never);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task ResetTransientEntitiesAsync_ShouldNotResetSwitchEntities()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
||||||
|
.Returns(Task.CompletedTask);
|
||||||
|
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
|
||||||
|
.Returns(Task.CompletedTask);
|
||||||
|
|
||||||
|
// Act
|
||||||
|
await _sut.ResetTransientEntitiesAsync();
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityState(SkipPriceCapEntityId, It.IsAny<string>()), Times.Never);
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityState(BudgetOverrideEntityId, It.IsAny<string>()), Times.Never);
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
}
|
||||||
@@ -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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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<ILogger<WaterReadyService>> _loggerMock;
|
||||||
|
private readonly FakeTimeProvider _timeProvider;
|
||||||
|
|
||||||
|
public WaterReadyServiceTests()
|
||||||
|
{
|
||||||
|
_loggerMock = new Mock<ILogger<WaterReadyService>>();
|
||||||
|
_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
|
||||||
|
}
|
||||||
@@ -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<BoilerConfigReader> 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
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
using BoilerMonitor.Models.Enums;
|
||||||
|
using BoilerMonitorManager.Interface;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
|
namespace BoilerMonitorManager;
|
||||||
|
|
||||||
|
public class BoilerControlService(ILogger<BoilerControlService> 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";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<RootNamespace>BoilerMonitorManager</RootNamespace>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
|
||||||
|
<_Parameter1>BoilerMonitor.Manager.Tests</_Parameter1>
|
||||||
|
</AssemblyAttribute>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\HomeAssistant.Entities\HomeAssistant.Entities.csproj" />
|
||||||
|
<ProjectReference Include="..\BoilerMonitor.Models\BoilerMonitor.Models.csproj" />
|
||||||
|
<ProjectReference Include="..\NordPool.Models\NordPool.Models.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.2" />
|
||||||
|
<PackageReference Include="NetDaemon.HassModel" Version="26.3.0" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -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<BoilerMonitorEntityService> 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<BoilerMonitorEntity> 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";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<BoilerMonitorInit> _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<BoilerMonitorInit> logger,
|
||||||
|
IScheduler scheduler,
|
||||||
|
IMqttEntityManager mqttEntityManager,
|
||||||
|
IBoilerControlService boilerControlService,
|
||||||
|
IBoilerRunTimeTracker tracker,
|
||||||
|
IBoilerMonitorEntityService entityService,
|
||||||
|
IWaterReadyService waterReadyService,
|
||||||
|
IOptions<BoilerMonitorOptions> 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<string, object> 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<string, object> 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<BoilerMonitorOptions>() ?? new BoilerMonitorOptions();
|
||||||
|
|
||||||
|
if (!options.Enabled)
|
||||||
|
{
|
||||||
|
return services;
|
||||||
|
}
|
||||||
|
|
||||||
|
services
|
||||||
|
.AddNetDaemonApp<BoilerMonitorInit>()
|
||||||
|
.AddSingleton<IBoilerControlService, BoilerControlService>()
|
||||||
|
.AddSingleton<IBoilerRunTimeTracker, BoilerRunTimeTracker>()
|
||||||
|
.AddTransient<IBoilerMonitorEntityService, BoilerMonitorEntityService>()
|
||||||
|
.AddSingleton<IWaterReadyService, WaterReadyService>()
|
||||||
|
.AddSingleton(TimeProvider.System)
|
||||||
|
.AddScoped<IBoilerConfigReader, BoilerConfigReader>();
|
||||||
|
|
||||||
|
return services;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
@@ -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();
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
namespace BoilerMonitorManager.Interface;
|
||||||
|
|
||||||
|
public interface IBoilerMonitorInit
|
||||||
|
{
|
||||||
|
Task InitializeAsync();
|
||||||
|
Task CleanupEntitiesAsync(CancellationToken cancellationToken = default);
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
@@ -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();
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
namespace BoilerMonitorManager.Models;
|
||||||
|
|
||||||
|
public sealed class BoilerMonitorOptions
|
||||||
|
{
|
||||||
|
public const string SectionName = "BoilerMonitor";
|
||||||
|
|
||||||
|
public bool Enabled { get; init; } = true;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// When true, removes existing BoilerMonitor MQTT entities before recreating them on app startup.
|
||||||
|
/// Manual cleanup (e.g. HA button) is not affected.
|
||||||
|
/// </summary>
|
||||||
|
public bool CleanupEntitiesOnStartup { get; init; } = true;
|
||||||
|
}
|
||||||
@@ -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; }
|
||||||
|
}
|
||||||
@@ -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; }
|
||||||
|
}
|
||||||
@@ -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; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
using BoilerMonitor.Models;
|
||||||
|
using BoilerMonitorManager.Interface;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
|
namespace BoilerMonitorManager;
|
||||||
|
|
||||||
|
public sealed class WaterReadyService(ILogger<WaterReadyService> 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
namespace BoilerMonitor.Models;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Boiler scheduling configuration read from Home Assistant entity state.
|
||||||
|
/// </summary>
|
||||||
|
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; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<RootNamespace>BoilerMonitor.Models</RootNamespace>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\HomeAssistant.Models\HomeAssistant.Models.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="NetDaemon.Extensions.Mqtt" Version="26.3.0" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
namespace BoilerMonitor.Models;
|
||||||
|
|
||||||
|
public static class BoilerMonitorConsts
|
||||||
|
{
|
||||||
|
public const int DefaultPollIntervalSeconds = 30;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
public const double DefaultHeatingPowerThresholdWatts = 5.0;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
public static readonly TimeSpan WarmUpGracePeriod = TimeSpan.FromMinutes(2);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
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";
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
namespace NordPoolManager.Models.Enums;
|
namespace BoilerMonitor.Models.Enums;
|
||||||
|
|
||||||
public enum BoilerAction
|
public enum BoilerAction
|
||||||
{
|
{
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
namespace BoilerMonitor.Models;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Reads the boiler scheduling configuration from Home Assistant entity state.
|
||||||
|
/// </summary>
|
||||||
|
public interface IBoilerConfigReader
|
||||||
|
{
|
||||||
|
BoilerConfig ReadConfig();
|
||||||
|
}
|
||||||
@@ -44,6 +44,8 @@
|
|||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\BoilerMonitor.Manager\BoilerMonitor.Manager.csproj" />
|
||||||
|
<ProjectReference Include="..\BoilerMonitor.Models\BoilerMonitor.Models.csproj" />
|
||||||
<ProjectReference Include="..\HomeAssistant.Entities\HomeAssistant.Entities.csproj" />
|
<ProjectReference Include="..\HomeAssistant.Entities\HomeAssistant.Entities.csproj" />
|
||||||
<ProjectReference Include="..\Mappings\Mappings.csproj" />
|
<ProjectReference Include="..\Mappings\Mappings.csproj" />
|
||||||
<ProjectReference Include="..\NordPool.Manager\NordPool.Manager.csproj" />
|
<ProjectReference Include="..\NordPool.Manager\NordPool.Manager.csproj" />
|
||||||
|
|||||||
@@ -5,7 +5,8 @@
|
|||||||
"Override": {
|
"Override": {
|
||||||
"System.Net.Http.HttpClient": "Warning",
|
"System.Net.Http.HttpClient": "Warning",
|
||||||
"NordPoolManager": "Information",
|
"NordPoolManager": "Information",
|
||||||
"PowerMonitorManager": "Information"
|
"PowerMonitorManager": "Information",
|
||||||
|
"BoilerMonitorManager": "Information"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"WriteTo": [
|
"WriteTo": [
|
||||||
@@ -26,6 +27,13 @@
|
|||||||
"OutputFile": "HomeAssistantGenerated.cs",
|
"OutputFile": "HomeAssistantGenerated.cs",
|
||||||
"UseAttributeBaseClasses" : "false"
|
"UseAttributeBaseClasses" : "false"
|
||||||
},
|
},
|
||||||
|
"NordPool": {
|
||||||
|
"CleanupEntitiesOnStartup": false
|
||||||
|
},
|
||||||
|
"BoilerMonitor": {
|
||||||
|
"Enabled": true,
|
||||||
|
"CleanupEntitiesOnStartup": false
|
||||||
|
},
|
||||||
"PowerMonitor": {
|
"PowerMonitor": {
|
||||||
"Enabled": false,
|
"Enabled": false,
|
||||||
"MainMeterEntityId": "sensor.sonoff_100267d63f_power",
|
"MainMeterEntityId": "sensor.sonoff_100267d63f_power",
|
||||||
|
|||||||
@@ -12,8 +12,11 @@ using NetDaemon.Extensions.MqttEntityManager;
|
|||||||
using NetDaemon.Extensions.Scheduler;
|
using NetDaemon.Extensions.Scheduler;
|
||||||
using NetDaemon.Extensions.Tts;
|
using NetDaemon.Extensions.Tts;
|
||||||
using NetDaemon.Runtime;
|
using NetDaemon.Runtime;
|
||||||
|
using BoilerMonitorManager;
|
||||||
|
using BoilerMonitorManager.Models;
|
||||||
using NordPoolManager;
|
using NordPoolManager;
|
||||||
using NordPoolManager.Interface;
|
using NordPoolManager.Interface;
|
||||||
|
using NordPoolManager.Models;
|
||||||
using PowerMonitorManager;
|
using PowerMonitorManager;
|
||||||
using PowerMonitorManager.Models;
|
using PowerMonitorManager.Models;
|
||||||
|
|
||||||
@@ -42,13 +45,14 @@ try
|
|||||||
config.AddProfile<GlobalMappingProfile>();
|
config.AddProfile<GlobalMappingProfile>();
|
||||||
})
|
})
|
||||||
.AddTransient<IEntityManager, EntityManager>()
|
.AddTransient<IEntityManager, EntityManager>()
|
||||||
|
.Configure<NordPoolOptions>(context.Configuration.GetSection(NordPoolOptions.SectionName))
|
||||||
.AddScoped<INordPoolPriceService, NordPoolPriceService>()
|
.AddScoped<INordPoolPriceService, NordPoolPriceService>()
|
||||||
.AddTransient<INordPoolEntityService, NordPoolEntityService>()
|
.AddTransient<INordPoolEntityService, NordPoolEntityService>()
|
||||||
.AddSingleton<ICheapestIntervalsFinder, CheapestIntervalsFinder>()
|
.AddSingleton<ICheapestIntervalsFinder, CheapestIntervalsFinder>()
|
||||||
.AddSingleton<IBoilerControlService, BoilerControlService>()
|
.Configure<PowerMonitorOptions>(context.Configuration.GetSection(PowerMonitorOptions.SectionName))
|
||||||
.Configure<PowerMonitorOptions>(
|
|
||||||
context.Configuration.GetSection(PowerMonitorOptions.SectionName))
|
|
||||||
.AddPowerMonitor(context.Configuration)
|
.AddPowerMonitor(context.Configuration)
|
||||||
|
.Configure<BoilerMonitorOptions>(context.Configuration.GetSection(BoilerMonitorOptions.SectionName))
|
||||||
|
.AddBoilerMonitor(context.Configuration)
|
||||||
)
|
)
|
||||||
.Build()
|
.Build()
|
||||||
.RunAsync()
|
.RunAsync()
|
||||||
|
|||||||
@@ -20,6 +20,16 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PowerMonitor.Manager", "Pow
|
|||||||
EndProject
|
EndProject
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PowerMonitor.Manager.Tests", "PowerMonitor.Manager.Tests\PowerMonitor.Manager.Tests.csproj", "{1F613F65-5F3C-41E6-B86B-774301D80E42}"
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PowerMonitor.Manager.Tests", "PowerMonitor.Manager.Tests\PowerMonitor.Manager.Tests.csproj", "{1F613F65-5F3C-41E6-B86B-774301D80E42}"
|
||||||
EndProject
|
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
|
Global
|
||||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||||
Debug|Any CPU = Debug|Any CPU
|
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|x64.Build.0 = Release|Any CPU
|
||||||
{1F613F65-5F3C-41E6-B86B-774301D80E42}.Release|x86.ActiveCfg = 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
|
{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
|
EndGlobalSection
|
||||||
GlobalSection(SolutionProperties) = preSolution
|
GlobalSection(SolutionProperties) = preSolution
|
||||||
HideSolutionNode = FALSE
|
HideSolutionNode = FALSE
|
||||||
EndGlobalSection
|
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
|
EndGlobal
|
||||||
|
|||||||
@@ -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<ILogger<BoilerControlService>>();
|
|
||||||
_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
|
|
||||||
}
|
|
||||||
@@ -441,128 +441,4 @@ public class CheapestIntervalsFinderTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#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
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<TargetFramework>net10.0</TargetFramework>
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
@@ -28,6 +28,7 @@
|
|||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\BoilerMonitor.Models\BoilerMonitor.Models.csproj" />
|
||||||
<ProjectReference Include="..\NordPool.Manager\NordPool.Manager.csproj" />
|
<ProjectReference Include="..\NordPool.Manager\NordPool.Manager.csproj" />
|
||||||
<ProjectReference Include="..\NordPool.Models\NordPool.Models.csproj" />
|
<ProjectReference Include="..\NordPool.Models\NordPool.Models.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|||||||
@@ -31,15 +31,13 @@ public class NordPoolEntityServiceTests
|
|||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
result.Should().NotBeNull();
|
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_last_update_time");
|
||||||
result.Should().Contain(e => e.EntityId == "sensor.nordpool_current_price");
|
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_today_prices");
|
||||||
result.Should().Contain(e => e.EntityId == "sensor.nordpool_tomorrow_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_today_tomorrow_prices");
|
||||||
result.Should().Contain(e => e.EntityId == "sensor.nordpool_cheapest_intervals");
|
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]
|
[Fact]
|
||||||
@@ -76,9 +74,7 @@ public class NordPoolEntityServiceTests
|
|||||||
var result = _sut.GetInitEntitiesList("EUR/kWh");
|
var result = _sut.GetInitEntitiesList("EUR/kWh");
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
result.Should().Contain(e => e.Domain == "sensor");
|
result.Should().OnlyContain(e => e.Domain == "sensor");
|
||||||
result.Should().Contain(e => e.Domain == "switch");
|
|
||||||
result.Should().OnlyContain(e => e.Domain == "sensor" || e.Domain == "switch");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -106,7 +102,7 @@ public class NordPoolEntityServiceTests
|
|||||||
await _sut.CreateEntitiesAsync("EUR/kWh");
|
await _sut.CreateEntitiesAsync("EUR/kWh");
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
_entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny<NordPoolEntity>()), Times.Exactly(8));
|
_entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny<NordPoolEntity>()), Times.Exactly(6));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -130,7 +126,7 @@ public class NordPoolEntityServiceTests
|
|||||||
await _sut.CreateEntitiesAsync("EUR/kWh");
|
await _sut.CreateEntitiesAsync("EUR/kWh");
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
_entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny<NordPoolEntity>()), Times.Exactly(8));
|
_entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny<NordPoolEntity>()), Times.Exactly(6));
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#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_tomorrow_prices"), Times.Once);
|
||||||
_entityManagerMock.Verify(em => em.RemoveEntity("sensor.nordpool_today_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_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]
|
[Fact]
|
||||||
@@ -256,13 +250,11 @@ public class NordPoolEntityServiceTests
|
|||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_last_update_time", "unknown"), Times.Once);
|
_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_today_prices", "0"), Times.Once);
|
||||||
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_tomorrow_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_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_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]
|
[Fact]
|
||||||
@@ -284,7 +276,6 @@ public class NordPoolEntityServiceTests
|
|||||||
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_tomorrow_prices", It.IsAny<object>()), Times.Once);
|
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_tomorrow_prices", It.IsAny<object>()), Times.Once);
|
||||||
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny<object>()), Times.Once);
|
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny<object>()), Times.Once);
|
||||||
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_cheapest_intervals", It.IsAny<object>()), Times.Once);
|
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_cheapest_intervals", It.IsAny<object>()), Times.Once);
|
||||||
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_boiler_water_ready", It.IsAny<object>()), Times.Once);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -308,7 +299,7 @@ public class NordPoolEntityServiceTests
|
|||||||
[Fact]
|
[Fact]
|
||||||
public async Task ResetEntitiesAsync_ShouldCallSetStateAndAttributesCorrectly()
|
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<string>(), It.IsAny<string>()))
|
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
||||||
.Returns(Task.CompletedTask);
|
.Returns(Task.CompletedTask);
|
||||||
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
|
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
|
||||||
@@ -318,8 +309,8 @@ public class NordPoolEntityServiceTests
|
|||||||
await _sut.ResetEntitiesAsync();
|
await _sut.ResetEntitiesAsync();
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
_entityManagerMock.Verify(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()), Times.Exactly(8));
|
_entityManagerMock.Verify(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()), Times.Exactly(6));
|
||||||
_entityManagerMock.Verify(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()), Times.Exactly(7));
|
_entityManagerMock.Verify(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()), Times.Exactly(6));
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
@@ -353,10 +344,7 @@ public class NordPoolEntityServiceTests
|
|||||||
SkipPriceCap = false,
|
SkipPriceCap = false,
|
||||||
ConfiguredReadyBy = "06:00",
|
ConfiguredReadyBy = "06:00",
|
||||||
IsNowCheap = false,
|
IsNowCheap = false,
|
||||||
NextCheapIntervalStart = null,
|
NextCheapIntervalStart = null
|
||||||
WaterReady = false,
|
|
||||||
BoilerSwitchState = "off",
|
|
||||||
BoilerPowerWatts = 0.0
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -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_tomorrow_prices", "1"), Times.Once);
|
||||||
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices", It.Is<string>(s => s.Contains('-') && s.Contains(':'))), Times.Once);
|
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices", It.Is<string>(s => s.Contains('-') && s.Contains(':'))), Times.Once);
|
||||||
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_cheapest_intervals", It.IsAny<string>()), Times.Once);
|
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_cheapest_intervals", It.IsAny<string>()), Times.Once);
|
||||||
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_boiler_water_ready", It.IsAny<string>()), Times.Once);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
|
|||||||
@@ -1,11 +1,15 @@
|
|||||||
using System.Reactive.Concurrency;
|
using System.Reactive.Concurrency;
|
||||||
|
using BoilerMonitor.Models;
|
||||||
using FluentAssertions;
|
using FluentAssertions;
|
||||||
using HomeAssistantGenerated;
|
using HomeAssistantGenerated;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
using Moq;
|
using Moq;
|
||||||
using NetDaemon.HassModel;
|
using NetDaemon.HassModel;
|
||||||
|
using NordPool.Models;
|
||||||
using NordPoolManager;
|
using NordPoolManager;
|
||||||
using NordPoolManager.Interface;
|
using NordPoolManager.Interface;
|
||||||
|
using NordPoolManager.Models;
|
||||||
|
|
||||||
namespace NordPool.Manager.Tests;
|
namespace NordPool.Manager.Tests;
|
||||||
|
|
||||||
@@ -16,7 +20,7 @@ public class NordPoolInitTests
|
|||||||
private readonly Mock<INordPoolEntityService> _entityServiceMock;
|
private readonly Mock<INordPoolEntityService> _entityServiceMock;
|
||||||
private readonly Mock<IScheduler> _schedulerMock;
|
private readonly Mock<IScheduler> _schedulerMock;
|
||||||
private readonly Mock<ICheapestIntervalsFinder> _cheapestIntervalsFinderMock;
|
private readonly Mock<ICheapestIntervalsFinder> _cheapestIntervalsFinderMock;
|
||||||
private readonly Mock<IBoilerControlService> _boilerControlServiceMock;
|
private readonly Mock<IBoilerConfigReader> _boilerConfigReaderMock;
|
||||||
private readonly Mock<IHaContext> _haContextMock;
|
private readonly Mock<IHaContext> _haContextMock;
|
||||||
private readonly Entities _entities;
|
private readonly Entities _entities;
|
||||||
|
|
||||||
@@ -28,23 +32,48 @@ public class NordPoolInitTests
|
|||||||
_schedulerMock = new Mock<IScheduler>();
|
_schedulerMock = new Mock<IScheduler>();
|
||||||
_schedulerMock.Setup(s => s.Now).Returns(DateTimeOffset.UtcNow);
|
_schedulerMock.Setup(s => s.Now).Returns(DateTimeOffset.UtcNow);
|
||||||
_cheapestIntervalsFinderMock = new Mock<ICheapestIntervalsFinder>();
|
_cheapestIntervalsFinderMock = new Mock<ICheapestIntervalsFinder>();
|
||||||
_boilerControlServiceMock = new Mock<IBoilerControlService>();
|
_boilerConfigReaderMock = new Mock<IBoilerConfigReader>();
|
||||||
_haContextMock = new Mock<IHaContext>();
|
_haContextMock = new Mock<IHaContext>();
|
||||||
_entities = new Entities(_haContextMock.Object);
|
_entities = new Entities(_haContextMock.Object);
|
||||||
|
|
||||||
|
_priceServiceMock.Setup(p => p.FetchPricesAsync()).Returns(Task.CompletedTask);
|
||||||
|
_entityServiceMock.Setup(e => e.CleanupEntitiesAsync(It.IsAny<CancellationToken>())).Returns(Task.CompletedTask);
|
||||||
|
_entityServiceMock.Setup(e => e.CreateEntitiesAsync(It.IsAny<string>())).Returns(Task.CompletedTask);
|
||||||
|
_entityServiceMock.Setup(e => e.ResetEntitiesAsync()).Returns(Task.CompletedTask);
|
||||||
|
_entityServiceMock.Setup(e => e.UpdateEntitiesAsync(It.IsAny<EntityUpdateContext>())).Returns(Task.CompletedTask);
|
||||||
|
_priceServiceMock.Setup(p => p.UpdateCurrentPrice()).Returns(0.0);
|
||||||
|
_priceServiceMock.Setup(p => p.ShouldFetchNewPrices(It.IsAny<DateOnly>())).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<IReadOnlyList<CheapestIntervalResult>>(), It.IsAny<DateTime>()))
|
||||||
|
.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(
|
return new NordPoolInit(
|
||||||
_entities,
|
_entities,
|
||||||
_haContextMock.Object,
|
|
||||||
_loggerMock.Object,
|
_loggerMock.Object,
|
||||||
_priceServiceMock.Object,
|
_priceServiceMock.Object,
|
||||||
_entityServiceMock.Object,
|
_entityServiceMock.Object,
|
||||||
_schedulerMock.Object,
|
_schedulerMock.Object,
|
||||||
_cheapestIntervalsFinderMock.Object,
|
_cheapestIntervalsFinderMock.Object,
|
||||||
_boilerControlServiceMock.Object
|
_boilerConfigReaderMock.Object,
|
||||||
);
|
options);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -71,4 +100,24 @@ public class NordPoolInitTests
|
|||||||
// Assert
|
// Assert
|
||||||
_entityServiceMock.Verify(es => es.CleanupEntitiesAsync(It.IsAny<CancellationToken>()), Times.Once);
|
_entityServiceMock.Verify(es => es.CleanupEntitiesAsync(It.IsAny<CancellationToken>()), 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<CancellationToken>()), 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<CancellationToken>()), Times.Never);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -209,7 +209,7 @@ public class NordPoolPriceServiceTests
|
|||||||
// Arrange
|
// Arrange
|
||||||
var dto = new NordPoolPriceResultDto
|
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);
|
var jsonString = JsonSerializer.Serialize(dto);
|
||||||
@@ -241,7 +241,7 @@ public class NordPoolPriceServiceTests
|
|||||||
// Arrange
|
// Arrange
|
||||||
var dto = new NordPoolPriceResultDto
|
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);
|
var jsonString = JsonSerializer.Serialize(dto);
|
||||||
|
|||||||
@@ -1,36 +0,0 @@
|
|||||||
using Microsoft.Extensions.Logging;
|
|
||||||
using NordPoolManager.Interface;
|
|
||||||
using NordPoolManager.Models.Enums;
|
|
||||||
|
|
||||||
namespace NordPoolManager;
|
|
||||||
|
|
||||||
public class BoilerControlService(ILogger<BoilerControlService> 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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -6,8 +6,6 @@ namespace NordPoolManager;
|
|||||||
|
|
||||||
public class CheapestIntervalsFinder(ILogger<CheapestIntervalsFinder> logger) : ICheapestIntervalsFinder
|
public class CheapestIntervalsFinder(ILogger<CheapestIntervalsFinder> logger) : ICheapestIntervalsFinder
|
||||||
{
|
{
|
||||||
private const string SwitchOnState = "on";
|
|
||||||
|
|
||||||
public IReadOnlyList<CheapestIntervalResult> FindCheapestIntervals(NordPoolPrice prices, int numberOfIntervals, double priceCap, DateTime deadline)
|
public IReadOnlyList<CheapestIntervalResult> FindCheapestIntervals(NordPoolPrice prices, int numberOfIntervals, double priceCap, DateTime deadline)
|
||||||
{
|
{
|
||||||
if (prices.Prices is not { Count: > 0 })
|
if (prices.Prices is not { Count: > 0 })
|
||||||
@@ -54,14 +52,4 @@ public class CheapestIntervalsFinder(ILogger<CheapestIntervalsFinder> logger) :
|
|||||||
{
|
{
|
||||||
return cheapestIntervals.AsParallel().Any(interval => utcNow >= interval.Start && utcNow < interval.End);
|
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;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +0,0 @@
|
|||||||
using NordPoolManager.Models.Enums;
|
|
||||||
|
|
||||||
namespace NordPoolManager.Interface;
|
|
||||||
|
|
||||||
public interface IBoilerControlService
|
|
||||||
{
|
|
||||||
BoilerAction DetermineAction(bool isNowCheap, bool waterReady, string? currentSwitchState);
|
|
||||||
}
|
|
||||||
@@ -7,6 +7,4 @@ public interface ICheapestIntervalsFinder
|
|||||||
IReadOnlyList<CheapestIntervalResult> FindCheapestIntervals(NordPoolPrice prices, int numberOfIntervals, double priceCap, DateTime deadline);
|
IReadOnlyList<CheapestIntervalResult> FindCheapestIntervals(NordPoolPrice prices, int numberOfIntervals, double priceCap, DateTime deadline);
|
||||||
|
|
||||||
bool IsCurrentIntervalCheap(IReadOnlyList<CheapestIntervalResult> cheapestIntervals, DateTime utcNow);
|
bool IsCurrentIntervalCheap(IReadOnlyList<CheapestIntervalResult> cheapestIntervals, DateTime utcNow);
|
||||||
|
|
||||||
bool IsWaterReady(string? switchState, double? powerWatts);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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; }
|
|
||||||
}
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
namespace NordPoolManager.Models.Consts;
|
|
||||||
|
|
||||||
public static class PriceConsts
|
|
||||||
{
|
|
||||||
public const int MaxDailyIntervals = 96;
|
|
||||||
public const int IntervalsPerHour = 4;
|
|
||||||
}
|
|
||||||
@@ -19,7 +19,4 @@ public record EntityUpdateContext
|
|||||||
public required string? ConfiguredReadyBy { get; init; }
|
public required string? ConfiguredReadyBy { get; init; }
|
||||||
public required bool IsNowCheap { get; init; }
|
public required bool IsNowCheap { get; init; }
|
||||||
public required DateTime? NextCheapIntervalStart { 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; }
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
namespace NordPoolManager.Models;
|
||||||
|
|
||||||
|
public sealed class NordPoolOptions
|
||||||
|
{
|
||||||
|
public const string SectionName = "NordPool";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// When true, removes existing NordPool MQTT entities before recreating them on app startup.
|
||||||
|
/// </summary>
|
||||||
|
public bool CleanupEntitiesOnStartup { get; init; } = true;
|
||||||
|
}
|
||||||
@@ -14,12 +14,15 @@
|
|||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\BoilerMonitor.Models\BoilerMonitor.Models.csproj" />
|
||||||
<ProjectReference Include="..\HomeAssistant.Entities\HomeAssistant.Entities.csproj" />
|
<ProjectReference Include="..\HomeAssistant.Entities\HomeAssistant.Entities.csproj" />
|
||||||
<ProjectReference Include="..\NordPool.Models\NordPool.Models.csproj" />
|
<ProjectReference Include="..\NordPool.Models\NordPool.Models.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="AutoMapper" Version="16.1.1" />
|
<PackageReference Include="AutoMapper" Version="16.1.1" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Options" Version="10.0.2" />
|
||||||
|
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.3.0" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
@@ -11,24 +11,19 @@ namespace NordPoolManager;
|
|||||||
public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<NordPoolEntityService> logger) : INordPoolEntityService
|
public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<NordPoolEntityService> logger) : INordPoolEntityService
|
||||||
{
|
{
|
||||||
private const string LastUpdateTimeEntityId = "sensor.nordpool_last_update_time";
|
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 TodayPricesEntityId = "sensor.nordpool_today_prices";
|
||||||
private const string TomorrowPricesEntityId = "sensor.nordpool_tomorrow_prices";
|
private const string TomorrowPricesEntityId = "sensor.nordpool_tomorrow_prices";
|
||||||
private const string TodayTomorrowPricesEntityId = "sensor.nordpool_today_tomorrow_prices";
|
private const string TodayTomorrowPricesEntityId = "sensor.nordpool_today_tomorrow_prices";
|
||||||
private const string CheapestIntervalsEntityId = "sensor.nordpool_cheapest_intervals";
|
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 =
|
private static readonly string[] AllEntityIds =
|
||||||
[
|
[
|
||||||
LastUpdateTimeEntityId,
|
LastUpdateTimeEntityId,
|
||||||
CurrentPriceEntityId,
|
NordPoolConsts.CurrentPriceEntityId,
|
||||||
TodayPricesEntityId,
|
TodayPricesEntityId,
|
||||||
TomorrowPricesEntityId,
|
TomorrowPricesEntityId,
|
||||||
TodayTomorrowPricesEntityId,
|
TodayTomorrowPricesEntityId,
|
||||||
CheapestIntervalsEntityId,
|
CheapestIntervalsEntityId
|
||||||
BoilerWaterReadyEntityId,
|
|
||||||
BoilerSkipPriceCapEntityId
|
|
||||||
];
|
];
|
||||||
|
|
||||||
public async Task CreateEntitiesAsync(string? unitOfMeasurement, CancellationToken cancellationToken = default)
|
public async Task CreateEntitiesAsync(string? unitOfMeasurement, CancellationToken cancellationToken = default)
|
||||||
@@ -65,9 +60,7 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
|
|||||||
ResetTodayPricesAsync(),
|
ResetTodayPricesAsync(),
|
||||||
ResetTomorrowPricesAsync(),
|
ResetTomorrowPricesAsync(),
|
||||||
ResetTodayTomorrowPricesAsync(),
|
ResetTodayTomorrowPricesAsync(),
|
||||||
ResetCheapestIntervalsAsync(),
|
ResetCheapestIntervalsAsync()
|
||||||
ResetBoilerWaterReadyAsync(),
|
|
||||||
ResetBoilerSkipPriceCapAsync()
|
|
||||||
).ConfigureAwait(false);
|
).ConfigureAwait(false);
|
||||||
|
|
||||||
logger.LogInformation("All NordPool entity states reset to defaults");
|
logger.LogInformation("All NordPool entity states reset to defaults");
|
||||||
@@ -84,8 +77,8 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
|
|||||||
|
|
||||||
private async Task ResetCurrentPriceAsync()
|
private async Task ResetCurrentPriceAsync()
|
||||||
{
|
{
|
||||||
await SetEntityStateSafe(CurrentPriceEntityId, string.Empty).ConfigureAwait(false);
|
await SetEntityStateSafe(NordPoolConsts.CurrentPriceEntityId, string.Empty).ConfigureAwait(false);
|
||||||
await SetEntityAttributesSafe(CurrentPriceEntityId, new
|
await SetEntityAttributesSafe(NordPoolConsts.CurrentPriceEntityId, new
|
||||||
{
|
{
|
||||||
unit_of_measurement = (string?)null,
|
unit_of_measurement = (string?)null,
|
||||||
device_class = "monetary",
|
device_class = "monetary",
|
||||||
@@ -150,24 +143,6 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
|
|||||||
}).ConfigureAwait(false);
|
}).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)
|
public async Task UpdateEntitiesAsync(EntityUpdateContext ctx, CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
cancellationToken.ThrowIfCancellationRequested();
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
@@ -182,8 +157,7 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
|
|||||||
|
|
||||||
if (mergedPrices.Count > NordPoolConsts.MaxExpectedPriceEntries)
|
if (mergedPrices.Count > NordPoolConsts.MaxExpectedPriceEntries)
|
||||||
{
|
{
|
||||||
logger.LogWarning(
|
logger.LogWarning("Merged price count ({Count}) exceeds expected maximum ({Max}). Attribute payload may be oversized",
|
||||||
"Merged price count ({Count}) exceeds expected maximum ({Max}). Attribute payload may be oversized",
|
|
||||||
mergedPrices.Count, NordPoolConsts.MaxExpectedPriceEntries);
|
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_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_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_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[]
|
var updateTasks = new[]
|
||||||
{
|
{
|
||||||
@@ -203,8 +176,7 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
|
|||||||
UpdateTodayPricesAsync(ctx, todayPricesCount, timestamp),
|
UpdateTodayPricesAsync(ctx, todayPricesCount, timestamp),
|
||||||
UpdateTomorrowPricesAsync(ctx, tomorrowPricesCount, timestamp),
|
UpdateTomorrowPricesAsync(ctx, tomorrowPricesCount, timestamp),
|
||||||
UpdateTodayTomorrowPricesAsync(mergedPrices, updateTimeState, timestamp),
|
UpdateTodayTomorrowPricesAsync(mergedPrices, updateTimeState, timestamp),
|
||||||
UpdateCheapestIntervalsAsync(ctx, cheapestCount, timestamp),
|
UpdateCheapestIntervalsAsync(ctx, cheapestCount, timestamp)
|
||||||
UpdateBoilerWaterReadyAsync(ctx, timestamp)
|
|
||||||
};
|
};
|
||||||
|
|
||||||
await Task.WhenAll(updateTasks).ConfigureAwait(false);
|
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)
|
private async Task UpdateCurrentPriceAsync(string priceValue, EntityUpdateContext ctx, string timestamp)
|
||||||
{
|
{
|
||||||
await SetEntityStateSafe(CurrentPriceEntityId, priceValue).ConfigureAwait(false);
|
await SetEntityStateSafe(NordPoolConsts.CurrentPriceEntityId, priceValue).ConfigureAwait(false);
|
||||||
await SetEntityAttributesSafe(CurrentPriceEntityId, new
|
await SetEntityAttributesSafe(NordPoolConsts.CurrentPriceEntityId, new
|
||||||
{
|
{
|
||||||
unit_of_measurement = ctx.UnitOfMeasurement,
|
unit_of_measurement = ctx.UnitOfMeasurement,
|
||||||
device_class = "monetary",
|
device_class = "monetary",
|
||||||
@@ -286,26 +258,13 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
|
|||||||
}).ConfigureAwait(false);
|
}).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)
|
public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
cancellationToken.ThrowIfCancellationRequested();
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var removeTasks = AllEntityIds.Select(entityId => entityManager.RemoveEntity(entityId));
|
var removeTasks = AllEntityIds.Select(entityManager.RemoveEntity);
|
||||||
await Task.WhenAll(removeTasks).ConfigureAwait(false);
|
await Task.WhenAll(removeTasks).ConfigureAwait(false);
|
||||||
|
|
||||||
logger.LogInformation("NordPool entities cleaned up successfully");
|
logger.LogInformation("NordPool entities cleaned up successfully");
|
||||||
@@ -319,39 +278,32 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
|
|||||||
|
|
||||||
internal ICollection<NordPoolEntity> GetInitEntitiesList(string? unitOfMeasurement)
|
internal ICollection<NordPoolEntity> GetInitEntitiesList(string? unitOfMeasurement)
|
||||||
{
|
{
|
||||||
var entries = new List<NordPoolEntity>();
|
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_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
|
Options = new EntityCreationOptions
|
||||||
{
|
{
|
||||||
UniqueId = CurrentPriceEntityId,
|
UniqueId = currentPriceEntityId,
|
||||||
Name = "NordPool current price"
|
Name = "NordPool current price"
|
||||||
},
|
},
|
||||||
AdditionalConfig = new
|
AdditionalConfig = NordPoolEntity.CreateAdditionalConfig(new
|
||||||
{
|
{
|
||||||
unit_of_measurement = unitOfMeasurement,
|
unit_of_measurement = unitOfMeasurement,
|
||||||
state_class = "measurement"
|
state_class = "measurement"
|
||||||
}
|
})
|
||||||
},
|
},
|
||||||
new NordPoolEntity("sensor", "nordpool_today_prices", "NordPool today prices"),
|
new NordPoolEntity("sensor", "nordpool_today_prices", "NordPool today prices"),
|
||||||
new NordPoolEntity("sensor", "nordpool_tomorrow_prices", "NordPool tomorrow 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_today_tomorrow_prices", "NordPool today and tomorrow prices"),
|
||||||
new NordPoolEntity("sensor", "nordpool_cheapest_intervals", "NordPool cheapest boiler intervals"),
|
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;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static List<NordPoolDayPrice> MergeTodayTomorrowPrices(NordPoolPrice? today, NordPoolPrice? tomorrow)
|
private static List<NordPoolDayPrice> MergeTodayTomorrowPrices(NordPoolPrice? today, NordPoolPrice? tomorrow)
|
||||||
|
|||||||
@@ -1,14 +1,14 @@
|
|||||||
|
using System.Globalization;
|
||||||
using System.Reactive.Concurrency;
|
using System.Reactive.Concurrency;
|
||||||
|
using BoilerMonitor.Models;
|
||||||
using HomeAssistantGenerated;
|
using HomeAssistantGenerated;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using NetDaemon.HassModel;
|
using Microsoft.Extensions.Options;
|
||||||
using NetDaemon.AppModel;
|
using NetDaemon.AppModel;
|
||||||
using NetDaemon.Extensions.Scheduler;
|
using NetDaemon.Extensions.Scheduler;
|
||||||
using NordPool.Models;
|
using NordPool.Models;
|
||||||
using NordPoolManager.Interface;
|
using NordPoolManager.Interface;
|
||||||
using NordPoolManager.Models;
|
using NordPoolManager.Models;
|
||||||
using NordPoolManager.Models.Consts;
|
|
||||||
using static NordPoolManager.Models.Enums.BoilerAction;
|
|
||||||
|
|
||||||
namespace NordPoolManager;
|
namespace NordPoolManager;
|
||||||
|
|
||||||
@@ -19,46 +19,33 @@ public class NordPoolInit : INordPoolInit
|
|||||||
private readonly INordPoolPriceService _priceService;
|
private readonly INordPoolPriceService _priceService;
|
||||||
private readonly INordPoolEntityService _entityService;
|
private readonly INordPoolEntityService _entityService;
|
||||||
private readonly ICheapestIntervalsFinder _cheapestIntervalsFinder;
|
private readonly ICheapestIntervalsFinder _cheapestIntervalsFinder;
|
||||||
private readonly IBoilerControlService _boilerControlService;
|
private readonly IBoilerConfigReader _boilerConfigReader;
|
||||||
private readonly IScheduler _scheduler;
|
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 string? UnitOfMeasurement { get; }
|
||||||
private IReadOnlyList<CheapestIntervalResult>? CheapestIntervals { get; set; }
|
private IReadOnlyList<CheapestIntervalResult>? CheapestIntervals { get; set; }
|
||||||
private bool _lastWaterReady;
|
|
||||||
|
|
||||||
public NordPoolInit(
|
public NordPoolInit(
|
||||||
Entities entities,
|
Entities entities,
|
||||||
IHaContext haContext,
|
|
||||||
ILogger<NordPoolInit> logger,
|
ILogger<NordPoolInit> logger,
|
||||||
INordPoolPriceService priceService,
|
INordPoolPriceService priceService,
|
||||||
INordPoolEntityService entityService,
|
INordPoolEntityService entityService,
|
||||||
IScheduler scheduler,
|
IScheduler scheduler,
|
||||||
ICheapestIntervalsFinder cheapestIntervalsFinder,
|
ICheapestIntervalsFinder cheapestIntervalsFinder,
|
||||||
IBoilerControlService boilerControlService)
|
IBoilerConfigReader boilerConfigReader,
|
||||||
|
IOptions<NordPoolOptions> options)
|
||||||
{
|
{
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
_haContext = haContext;
|
|
||||||
_priceService = priceService;
|
_priceService = priceService;
|
||||||
_entityService = entityService;
|
_entityService = entityService;
|
||||||
_scheduler = scheduler;
|
_scheduler = scheduler;
|
||||||
_cheapestIntervalsFinder = cheapestIntervalsFinder;
|
_cheapestIntervalsFinder = cheapestIntervalsFinder;
|
||||||
_boilerControlService = boilerControlService;
|
_boilerConfigReader = boilerConfigReader;
|
||||||
|
_options = options.Value;
|
||||||
|
|
||||||
var nordPoolPriceSensor = entities.Sensor.NordpoolPrice;
|
var nordPoolPriceSensor = entities.Sensor.NordpoolPrice;
|
||||||
UnitOfMeasurement = nordPoolPriceSensor.EntityState?.Attributes?.UnitOfMeasurement ?? "EUR/kWh";
|
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();
|
_ = InitializeAndScheduleAsync();
|
||||||
}
|
}
|
||||||
@@ -69,8 +56,6 @@ public class NordPoolInit : INordPoolInit
|
|||||||
{
|
{
|
||||||
await InitializeAsync();
|
await InitializeAsync();
|
||||||
SchedulePeriodicUpdates();
|
SchedulePeriodicUpdates();
|
||||||
ScheduleEndOfDayReminder();
|
|
||||||
SubscribeToSkipPriceCapChanges();
|
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
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()
|
public async Task InitializeAsync()
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
@@ -140,6 +71,15 @@ public class NordPoolInit : INordPoolInit
|
|||||||
|
|
||||||
await _priceService.FetchPricesAsync();
|
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.CreateEntitiesAsync(UnitOfMeasurement);
|
||||||
|
|
||||||
await _entityService.ResetEntitiesAsync();
|
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");
|
_logger.LogWarning("Current price is 0, which may indicate an issue with price retrieval");
|
||||||
}
|
}
|
||||||
|
|
||||||
var result = UpdateCheapestIntervals();
|
var (_, boilerConfig) = UpdateCheapestIntervals();
|
||||||
await UpdateEntitiesAsync(result.IntervalCount, result.PriceCap, result.SkipPriceCap);
|
await UpdateEntitiesAsync(boilerConfig);
|
||||||
|
|
||||||
_logger.LogInformation("NordPool price initialized with current price: {CurrentPrice} {Unit}", _priceService.CurrentPrice, UnitOfMeasurement);
|
_logger.LogInformation("NordPool price initialized with current price: {CurrentPrice} {Unit}", _priceService.CurrentPrice, UnitOfMeasurement);
|
||||||
}
|
}
|
||||||
@@ -220,8 +160,8 @@ public class NordPoolInit : INordPoolInit
|
|||||||
|
|
||||||
_priceService.UpdateCurrentPrice();
|
_priceService.UpdateCurrentPrice();
|
||||||
|
|
||||||
var result = UpdateCheapestIntervals();
|
var (_, boilerConfig) = UpdateCheapestIntervals();
|
||||||
await UpdateEntitiesAsync(result.IntervalCount, result.PriceCap, result.SkipPriceCap);
|
await UpdateEntitiesAsync(boilerConfig);
|
||||||
|
|
||||||
_logger.LogInformation("NordPool prices updated successfully. Current price: {CurrentPrice} {Unit}", _priceService.CurrentPrice, UnitOfMeasurement);
|
_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);
|
await _entityService.CleanupEntitiesAsync(cancellationToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
private CheapestIntervalsUpdateResult UpdateCheapestIntervals()
|
private (CheapestIntervalsUpdateResult Result, BoilerConfig Config) UpdateCheapestIntervals()
|
||||||
{
|
{
|
||||||
var boilerConfig = ReadBoilerConfig();
|
var config = _boilerConfigReader.ReadConfig();
|
||||||
var effectivePriceCap = boilerConfig.SkipPriceCap ? double.MaxValue : boilerConfig.PriceCap;
|
var effectivePriceCap = config.SkipPriceCap ? double.MaxValue : config.PriceCap;
|
||||||
var effectiveIntervalCount = boilerConfig.SkipPriceCap ? PriceConsts.MaxDailyIntervals : boilerConfig.IntervalCount;
|
var effectiveIntervalCount = config.SkipPriceCap ? NordPoolConsts.MaxDailyIntervals : config.IntervalCount;
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
@@ -248,18 +188,18 @@ public class NordPoolInit : INordPoolInit
|
|||||||
{
|
{
|
||||||
_logger.LogDebug("No today prices available, skipping cheapest intervals calculation");
|
_logger.LogDebug("No today prices available, skipping cheapest intervals calculation");
|
||||||
CheapestIntervals = [];
|
CheapestIntervals = [];
|
||||||
return new CheapestIntervalsUpdateResult
|
return (new CheapestIntervalsUpdateResult
|
||||||
{
|
{
|
||||||
IntervalCount = boilerConfig.IntervalCount,
|
IntervalCount = config.IntervalCount,
|
||||||
PriceCap = boilerConfig.PriceCap,
|
PriceCap = config.PriceCap,
|
||||||
SkipPriceCap = boilerConfig.SkipPriceCap
|
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})",
|
_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)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
@@ -267,65 +207,24 @@ public class NordPoolInit : INordPoolInit
|
|||||||
CheapestIntervals = [];
|
CheapestIntervals = [];
|
||||||
}
|
}
|
||||||
|
|
||||||
return new CheapestIntervalsUpdateResult
|
return (new CheapestIntervalsUpdateResult
|
||||||
{
|
{
|
||||||
IntervalCount = boilerConfig.IntervalCount,
|
IntervalCount = config.IntervalCount,
|
||||||
PriceCap = boilerConfig.PriceCap,
|
PriceCap = config.PriceCap,
|
||||||
SkipPriceCap = boilerConfig.SkipPriceCap
|
SkipPriceCap = config.SkipPriceCap
|
||||||
};
|
}, config);
|
||||||
}
|
}
|
||||||
|
|
||||||
private BoilerConfig ReadBoilerConfig()
|
private async Task UpdateEntitiesAsync(BoilerConfig boilerConfig)
|
||||||
{
|
|
||||||
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)
|
|
||||||
{
|
{
|
||||||
var cetTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
|
var cetTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
|
||||||
var nowCet = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, cetTimeZone);
|
var nowCet = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, cetTimeZone);
|
||||||
var todayCet = DateOnly.FromDateTime(nowCet);
|
var todayCet = DateOnly.FromDateTime(nowCet);
|
||||||
var currentDateTime = DateTime.Now;
|
var currentDateTime = DateTime.Now;
|
||||||
|
|
||||||
var configuredHours = BoilerDailyHoursEntity.State ?? 1.0;
|
var configuredHours = (double)boilerConfig.IntervalCount / NordPoolConsts.IntervalsPerHour;
|
||||||
var configuredReadyBy = BoilerReadyByEntity.State ?? "";
|
var configuredReadyBy = boilerConfig.Deadline.TimeOfDay.ToString(@"hh\:mm", CultureInfo.InvariantCulture);
|
||||||
|
|
||||||
var isNowCheap = CheapestIntervals != null &&
|
var isNowCheap = CheapestIntervals != null &&
|
||||||
_cheapestIntervalsFinder.IsCurrentIntervalCheap(CheapestIntervals, currentDateTime);
|
_cheapestIntervalsFinder.IsCurrentIntervalCheap(CheapestIntervals, currentDateTime);
|
||||||
var nextCheapInterval = CheapestIntervals?
|
var nextCheapInterval = CheapestIntervals?
|
||||||
@@ -333,39 +232,6 @@ public class NordPoolInit : INordPoolInit
|
|||||||
.OrderBy(i => i.Start)
|
.OrderBy(i => i.Start)
|
||||||
.FirstOrDefault();
|
.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
|
var context = new EntityUpdateContext
|
||||||
{
|
{
|
||||||
CurrentPrice = _priceService.CurrentPrice,
|
CurrentPrice = _priceService.CurrentPrice,
|
||||||
@@ -377,15 +243,12 @@ public class NordPoolInit : INordPoolInit
|
|||||||
TomorrowNordPoolPrice = _priceService.TomorrowNordPoolPrice,
|
TomorrowNordPoolPrice = _priceService.TomorrowNordPoolPrice,
|
||||||
CheapestIntervals = CheapestIntervals,
|
CheapestIntervals = CheapestIntervals,
|
||||||
ConfiguredHours = configuredHours,
|
ConfiguredHours = configuredHours,
|
||||||
ConfiguredIntervalCount = configuredIntervalCount,
|
ConfiguredIntervalCount = boilerConfig.IntervalCount,
|
||||||
ConfiguredPriceCap = configuredPriceCap,
|
ConfiguredPriceCap = boilerConfig.PriceCap,
|
||||||
SkipPriceCap = skipPriceCap,
|
SkipPriceCap = boilerConfig.SkipPriceCap,
|
||||||
ConfiguredReadyBy = configuredReadyBy,
|
ConfiguredReadyBy = configuredReadyBy,
|
||||||
IsNowCheap = isNowCheap,
|
IsNowCheap = isNowCheap,
|
||||||
NextCheapIntervalStart = nextCheapInterval?.Start,
|
NextCheapIntervalStart = nextCheapInterval?.Start
|
||||||
WaterReady = waterReady,
|
|
||||||
BoilerSwitchState = boilerSwitchState,
|
|
||||||
BoilerPowerWatts = boilerPowerWatts
|
|
||||||
};
|
};
|
||||||
|
|
||||||
await _entityService.UpdateEntitiesAsync(context);
|
await _entityService.UpdateEntitiesAsync(context);
|
||||||
|
|||||||
@@ -43,23 +43,36 @@ internal sealed class CompactNordPoolDayPriceConverter : JsonConverter<CompactNo
|
|||||||
public override CompactNordPoolDayPrice Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
public override CompactNordPoolDayPrice Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
||||||
{
|
{
|
||||||
if (reader.TokenType != JsonTokenType.StartArray)
|
if (reader.TokenType != JsonTokenType.StartArray)
|
||||||
|
{
|
||||||
throw new JsonException("Expected start of array.");
|
throw new JsonException("Expected start of array.");
|
||||||
|
}
|
||||||
|
|
||||||
if (!reader.Read() || reader.TokenType != JsonTokenType.Number)
|
if (!reader.Read() || reader.TokenType != JsonTokenType.Number)
|
||||||
|
{
|
||||||
throw new JsonException("Expected number for Start at position 0.");
|
throw new JsonException("Expected number for Start at position 0.");
|
||||||
|
}
|
||||||
|
|
||||||
var start = reader.GetInt64();
|
var start = reader.GetInt64();
|
||||||
|
|
||||||
if (!reader.Read() || reader.TokenType != JsonTokenType.Number)
|
if (!reader.Read() || reader.TokenType != JsonTokenType.Number)
|
||||||
|
{
|
||||||
throw new JsonException("Expected number for End at position 1.");
|
throw new JsonException("Expected number for End at position 1.");
|
||||||
|
}
|
||||||
|
|
||||||
var end = reader.GetInt64();
|
var end = reader.GetInt64();
|
||||||
|
|
||||||
if (!reader.Read() || (reader.TokenType != JsonTokenType.Number && reader.TokenType != JsonTokenType.Null))
|
if (!reader.Read() || (reader.TokenType != JsonTokenType.Number && reader.TokenType != JsonTokenType.Null))
|
||||||
|
{
|
||||||
throw new JsonException("Expected number or null for Price at position 2.");
|
throw new JsonException("Expected number or null for Price at position 2.");
|
||||||
|
}
|
||||||
|
|
||||||
double? price = reader.TokenType == JsonTokenType.Null ? null : reader.GetDouble();
|
double? price = reader.TokenType == JsonTokenType.Null ? null : reader.GetDouble();
|
||||||
|
|
||||||
reader.Read();
|
reader.Read();
|
||||||
if (reader.TokenType != JsonTokenType.EndArray)
|
if (reader.TokenType != JsonTokenType.EndArray)
|
||||||
|
{
|
||||||
throw new JsonException("Expected end of array.");
|
throw new JsonException("Expected end of array.");
|
||||||
|
}
|
||||||
|
|
||||||
return new CompactNordPoolDayPrice { Start = start, End = end, Price = price };
|
return new CompactNordPoolDayPrice { Start = start, End = end, Price = price };
|
||||||
}
|
}
|
||||||
@@ -71,9 +84,13 @@ internal sealed class CompactNordPoolDayPriceConverter : JsonConverter<CompactNo
|
|||||||
writer.WriteNumberValue(value.End);
|
writer.WriteNumberValue(value.End);
|
||||||
|
|
||||||
if (value.Price.HasValue)
|
if (value.Price.HasValue)
|
||||||
|
{
|
||||||
writer.WriteNumberValue(value.Price.Value);
|
writer.WriteNumberValue(value.Price.Value);
|
||||||
|
}
|
||||||
else
|
else
|
||||||
|
{
|
||||||
writer.WriteNullValue();
|
writer.WriteNullValue();
|
||||||
|
}
|
||||||
|
|
||||||
writer.WriteEndArray();
|
writer.WriteEndArray();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,14 +9,28 @@ public static class NordPoolConsts
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public const int MinutesPerInterval = 15;
|
public const int MinutesPerInterval = 15;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Number of 15-minute intervals in one hour.
|
||||||
|
/// </summary>
|
||||||
|
public const int IntervalsPerHour = 4;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Maximum number of 15-minute intervals in a single day (96 = 24h * 4).
|
||||||
|
/// </summary>
|
||||||
|
public const int MaxDailyIntervals = 96;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Maximum expected price entries when today and tomorrow are both available
|
/// 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.
|
/// (96 intervals per day x 2 days). Used for logging a warning if exceeded.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public const int MaxExpectedPriceEntries = 192;
|
public const int MaxExpectedPriceEntries = 192;
|
||||||
|
|
||||||
|
public const string DeviceIdentifier = "nordpool";
|
||||||
|
public const string DeviceName = "NordPool";
|
||||||
|
public const string DeviceManufacturer = "HomeAssistant App Daemon";
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 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.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public const double WaterReadyPowerThresholdWatts = 5.0;
|
public const string CurrentPriceEntityId = "sensor.nordpool_current_price";
|
||||||
}
|
}
|
||||||
@@ -1,15 +1,8 @@
|
|||||||
using System.Text.Json.Serialization;
|
|
||||||
|
|
||||||
namespace NordPool.Models;
|
namespace NordPool.Models;
|
||||||
|
|
||||||
public class NordPoolDayPrice
|
public class NordPoolDayPrice
|
||||||
{
|
{
|
||||||
[JsonPropertyName("start")]
|
public DateTime? Start { get; init; }
|
||||||
public DateTime? Start { get; set; }
|
public DateTime? End { get; init; }
|
||||||
|
public double? Price { get; init; }
|
||||||
[JsonPropertyName("end")]
|
|
||||||
public DateTime? End { get; set; }
|
|
||||||
|
|
||||||
[JsonPropertyName("price")]
|
|
||||||
public double? Price { get; set; }
|
|
||||||
}
|
}
|
||||||
@@ -5,7 +5,9 @@ public static class NordPoolDayPriceExtensions
|
|||||||
public static List<CompactNordPoolDayPrice> ToCompact(this IEnumerable<NordPoolDayPrice>? prices)
|
public static List<CompactNordPoolDayPrice> ToCompact(this IEnumerable<NordPoolDayPrice>? prices)
|
||||||
{
|
{
|
||||||
if (prices is null)
|
if (prices is null)
|
||||||
|
{
|
||||||
return [];
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
return prices.Select(CompactNordPoolDayPrice.FromDayPrice).ToList();
|
return prices.Select(CompactNordPoolDayPrice.FromDayPrice).ToList();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +1,21 @@
|
|||||||
using HomeAssistant.Models;
|
using HomeAssistant.Models;
|
||||||
using NetDaemon.Extensions.MqttEntityManager;
|
using NetDaemon.Extensions.MqttEntityManager;
|
||||||
|
|
||||||
namespace NordPool.Models;
|
namespace NordPool.Models;
|
||||||
|
|
||||||
public class NordPoolEntity : EntityCreateModel
|
public class NordPoolEntity : EntityCreateModel
|
||||||
{
|
{
|
||||||
public string Domain { get; set; } // example: sensor
|
private static readonly object DeviceBlock = new
|
||||||
public string Identifier { get; set; } // example: name of the sensor
|
{
|
||||||
public string Name { get; set; } // friendly name for UI
|
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)
|
public NordPoolEntity(string domain, string identifier, string name)
|
||||||
{
|
{
|
||||||
@@ -20,7 +28,22 @@ public class NordPoolEntity : EntityCreateModel
|
|||||||
{
|
{
|
||||||
UniqueId = EntityId,
|
UniqueId = EntityId,
|
||||||
Name = Name
|
Name = Name
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
AdditionalConfig = new { device = DeviceBlock };
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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.
|
||||||
|
/// </summary>
|
||||||
|
public static object CreateAdditionalConfig(object extraProperties)
|
||||||
|
{
|
||||||
|
var extras = extraProperties.GetType().GetProperties()
|
||||||
|
.ToDictionary(p => p.Name, p => p.GetValue(extraProperties));
|
||||||
|
|
||||||
|
extras["device"] = DeviceBlock;
|
||||||
|
|
||||||
|
return extras;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -40,9 +40,20 @@ public class PowerSensorDiscoveryServiceTests
|
|||||||
foreach (var (entityId, deviceClass, unit, friendlyName) in entities)
|
foreach (var (entityId, deviceClass, unit, friendlyName) in entities)
|
||||||
{
|
{
|
||||||
var attributes = new Dictionary<string, object?>();
|
var attributes = new Dictionary<string, object?>();
|
||||||
if (deviceClass is not null) attributes["device_class"] = deviceClass;
|
if (deviceClass is not null)
|
||||||
if (unit is not null) attributes["unit_of_measurement"] = unit;
|
{
|
||||||
if (friendlyName is not null) attributes["friendly_name"] = friendlyName;
|
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 attributesJson = JsonSerializer.SerializeToElement(attributes);
|
||||||
var entityState = new EntityState { AttributesJson = attributesJson };
|
var entityState = new EntityState { AttributesJson = attributesJson };
|
||||||
|
|||||||
@@ -15,6 +15,7 @@
|
|||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\HomeAssistant.Entities\HomeAssistant.Entities.csproj" />
|
<ProjectReference Include="..\HomeAssistant.Entities\HomeAssistant.Entities.csproj" />
|
||||||
|
<ProjectReference Include="..\NordPool.Models\NordPool.Models.csproj" />
|
||||||
<ProjectReference Include="..\PowerMonitor.Models\PowerMonitor.Models.csproj" />
|
<ProjectReference Include="..\PowerMonitor.Models\PowerMonitor.Models.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ using NetDaemon.AppModel;
|
|||||||
using NetDaemon.Extensions.Scheduler;
|
using NetDaemon.Extensions.Scheduler;
|
||||||
using NetDaemon.HassModel;
|
using NetDaemon.HassModel;
|
||||||
using NetDaemon.HassModel.Entities;
|
using NetDaemon.HassModel.Entities;
|
||||||
|
using NordPool.Models;
|
||||||
using PowerMonitorManager.Interface;
|
using PowerMonitorManager.Interface;
|
||||||
using PowerMonitorManager.Models;
|
using PowerMonitorManager.Models;
|
||||||
using PowerMonitorManager.Models.Consts;
|
using PowerMonitorManager.Models.Consts;
|
||||||
@@ -24,8 +25,6 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
|
|||||||
private readonly IPowerCostCalculationService _costService;
|
private readonly IPowerCostCalculationService _costService;
|
||||||
private readonly IPowerMonitorEntityService _entityService;
|
private readonly IPowerMonitorEntityService _entityService;
|
||||||
|
|
||||||
private const string NordPoolCurrentPriceEntityId = "sensor.nordpool_current_price";
|
|
||||||
|
|
||||||
private int _mainMeterConsecutiveFailures;
|
private int _mainMeterConsecutiveFailures;
|
||||||
private DateTime? _anomalyStartTime;
|
private DateTime? _anomalyStartTime;
|
||||||
|
|
||||||
@@ -246,7 +245,7 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
|
|||||||
|
|
||||||
private double ReadNordPoolPrice()
|
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")
|
if (state?.State is null || state.State == "unavailable" || state.State == "unknown")
|
||||||
{
|
{
|
||||||
_logger.LogDebug("NordPool price entity unavailable, using last known price");
|
_logger.LogDebug("NordPool price entity unavailable, using last known price");
|
||||||
|
|||||||
Reference in New Issue
Block a user