Add input_boolean for water heater preparation logic

Refreshed logic to allow users to toggle hot water preparation. Introduced new `input_boolean.boiler_prepare_hot_water` and updated config, services, and tests to ensure water readiness only when required.
This commit is contained in:
Marius
2026-03-16 11:42:49 +02:00
parent 5cc0ab29a6
commit 53eb53539a
13 changed files with 434 additions and 39 deletions
@@ -0,0 +1,130 @@
---
name: Water Heater Preparation Decision
overview: Add a new input_boolean so the user can decide whether to prepare hot water. When ON, the system ensures water is ready by the deadline using cheap intervals. When OFF, preparation is skipped and the boiler is turned off if running.
todos:
- id: add-ha-entity
content: Add input_boolean.boiler_prepare_hot_water to Home Assistant (user config) and regenerate entities
- id: extend-boiler-service
content: Add prepareHotWater parameter to IBoilerControlService and BoilerControlService
- id: update-nordpool-init
content: Read new input_boolean in NordPoolInit and pass to BoilerControlService
- id: update-entity-context
content: Add prepareHotWater to EntityUpdateContext and NordPoolEntityService
- id: unit-tests
content: Add BoilerControlService tests for prepareHotWater false/true
isProject: false
---
# Water Heater Preparation Decision
## Goal
Add a new `input_boolean.boiler_prepare_hot_water` so the user can decide whether to prepare hot water. When **ON**: ensure water is ready by the deadline (current behavior). When **OFF**: skip preparation entirely and turn off the boiler if it is running.
## Current Flow
```mermaid
flowchart LR
subgraph config [Config]
DailyHours[BoilerDailyHours]
PriceCap[BoilerPriceCap]
ReadyBy[BoilerReadyBy]
end
subgraph logic [Logic]
Cheapest[CheapestIntervalsFinder]
BoilerControl[BoilerControlService]
end
subgraph decision [Decision]
isCheap[isNowCheap]
waterReady[waterReady]
end
subgraph action [Action]
TurnOn[Turn On]
TurnOff[Turn Off]
end
DailyHours --> Cheapest
PriceCap --> Cheapest
ReadyBy --> Cheapest
Cheapest --> isCheap
isCheap --> BoilerControl
waterReady --> BoilerControl
BoilerControl --> TurnOn
BoilerControl --> TurnOff
```
## Proposed Changes
### 1. New Home Assistant Entity
**User action:** Add to `configuration.yaml` or via UI:
```yaml
input_boolean:
boiler_prepare_hot_water:
name: "Prepare hot water"
icon: mdi:water-thermometer
```
Then run `dotnet tool run nd-codegen` to regenerate [HomeAssistant.Entities/EntityGeneration/HomeAssistantGenerated.cs](HomeAssistant.Entities/EntityGeneration/HomeAssistantGenerated.cs) so the new entity is available in code.
### 2. Add Prepare Hot Water to NordPoolInit
**File:** [NordPool.Manager/NordPoolInit.cs](NordPool.Manager/NordPoolInit.cs)
- Inject `InputBooleanEntity BoilerPrepareHotWaterEntity` from `entities.InputBoolean.BoilerPrepareHotWater` (after codegen)
- Read `BoilerPrepareHotWaterEntity.State` in `UpdateEntitiesAsync` before calling `BoilerControlService`
- Parse as boolean: `"on"` = true, `"off"` or null = false. For backward compatibility when entity does not exist yet, treat null/unknown as true
- Pass `prepareHotWater` to `DetermineAction`
### 3. Extend BoilerControlService and IBoilerControlService
**Files:** [NordPool.Manager/Interface/IBoilerControlService.cs](NordPool.Manager/Interface/IBoilerControlService.cs), [NordPool.Manager/BoilerControlService.cs](NordPool.Manager/BoilerControlService.cs)
- Add `bool prepareHotWater` as first parameter to `DetermineAction`
- When `prepareHotWater == false`: return `BoilerAction.TurnOff` if boiler is on, else `NoChange`
- When `prepareHotWater == true`: keep current logic (cheap + not water ready)
**Interface change:**
```csharp
BoilerAction DetermineAction(bool prepareHotWater, bool isNowCheap, bool waterReady, string? currentSwitchState);
```
### 4. Update EntityUpdateContext
**File:** [NordPool.Manager/Models/EntityUpdateContext.cs](NordPool.Manager/Models/EntityUpdateContext.cs)
- Add `bool PrepareHotWater { get; init; }` for UI/attributes
### 5. Update NordPoolEntityService
**File:** [NordPool.Manager/NordPoolEntityService.cs](NordPool.Manager/NordPoolEntityService.cs)
- Add `prepare_hot_water` to `sensor.nordpool_cheapest_intervals` attributes so the user can see the decision state in HA
### 6. Unit Tests
**File:** [NordPool.Manager.Tests/BoilerControlServiceTests.cs](NordPool.Manager.Tests/BoilerControlServiceTests.cs)
- Add tests for `prepareHotWater == false`: always TurnOff when on, NoChange when off
- Add tests for `prepareHotWater == true`: existing behavior unchanged
## Logic Summary
| Prepare Hot Water | isNowCheap | waterReady | Switch State | Action |
|------------------|------------|------------|--------------|--------|
| OFF | any | any | on | TurnOff |
| OFF | any | any | off | NoChange |
| ON | true | false | off | TurnOn |
| ON | true | false | on | NoChange |
| ON | false | any | on | TurnOff |
| ON | any | true | on | TurnOff |
## Backward Compatibility
- If `BoilerPrepareHotWaterEntity` does not exist yet (before HA config): use a fallback or skip the entity read
- If state is null or unknown: treat as `true` (prepare hot water) to preserve current behavior until the user adds the entity
@@ -33,7 +33,7 @@
</Target> </Target>
<ItemGroup> <ItemGroup>
<PackageReference Include="AutoMapper" Version="16.0.0" /> <PackageReference Include="AutoMapper" Version="16.1.1" />
<PackageReference Include="NetDaemon.AppModel" Version="26.3.0" /> <PackageReference Include="NetDaemon.AppModel" Version="26.3.0" />
<PackageReference Include="NetDaemon.Runtime" Version="26.3.0" /> <PackageReference Include="NetDaemon.Runtime" Version="26.3.0" />
<PackageReference Include="NetDaemon.HassModel" Version="26.3.0" /> <PackageReference Include="NetDaemon.HassModel" Version="26.3.0" />
-10
View File
@@ -17,16 +17,6 @@
} }
] ]
}, },
"HomeAssistant": {
"UserName": "marius",
"Password": "ExQz1990",
"Host": "192.168.1.206",
"Port": 8123,
"Ssl": false
},
"HomeAssistant": {
"Token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiI5Nzk3MWIzYzQ5Y2Y0NTM0YjEyMzg0MWViMzM3NzIwYiIsImlhdCI6MTc2Mzk5NjIwNSwiZXhwIjoyMDc5MzU2MjA1fQ.J_E1EycKA8_22xc-byHbZn_aJSl3H13beuwlPkCw--4"
},
"NetDaemon": { "NetDaemon": {
"ApplicationConfigurationFolder": "./apps" "ApplicationConfigurationFolder": "./apps"
}, },
+1 -1
View File
@@ -7,7 +7,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="AutoMapper" Version="16.0.0" /> <PackageReference Include="AutoMapper" Version="16.1.1" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
@@ -161,6 +161,23 @@ public class CheapestIntervalsFinderTests
result.Should().OnlyContain(r => r.Price <= 6.0); result.Should().OnlyContain(r => r.Price <= 6.0);
} }
[Fact]
public void FindCheapestIntervals_WithMaxPriceCap_ShouldIncludeAllIntervalsBeforeDeadline()
{
// Arrange: prices 10, 3, 7, 1, 5, 15 - with cap 6.0 only 3 would qualify; with double.MaxValue all qualify
var sut = CreateSut();
var dayStart = new DateTime(2026, 2, 26, 0, 0, 0);
var prices = CreatePricesWithValues(dayStart, 10.0, 3.0, 7.0, 1.0, 5.0, 15.0);
var deadline = dayStart.AddDays(1);
// Act
var result = sut.FindCheapestIntervals(prices, 4, double.MaxValue, deadline);
// Assert: all 6 intervals are eligible, we take 4 cheapest: 1, 3, 5, 7
result.Should().HaveCount(4);
result.Select(r => r.Price).OrderBy(p => p).Should().ContainInOrder(1.0, 3.0, 5.0, 7.0);
}
[Fact] [Fact]
public void FindCheapestIntervals_WithDeadlineAndPriceCap_ShouldApplyBothFilters() public void FindCheapestIntervals_WithDeadlineAndPriceCap_ShouldApplyBothFilters()
{ {
@@ -18,7 +18,7 @@
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="AutoMapper" Version="16.0.0" /> <PackageReference Include="AutoMapper" Version="16.1.1" />
<PackageReference Include="FluentAssertions" Version="8.8.0" /> <PackageReference Include="FluentAssertions" Version="8.8.0" />
<PackageReference Include="Moq" Version="4.20.72" /> <PackageReference Include="Moq" Version="4.20.72" />
</ItemGroup> </ItemGroup>
@@ -31,13 +31,15 @@ public class NordPoolEntityServiceTests
// Assert // Assert
result.Should().NotBeNull(); result.Should().NotBeNull();
result.Should().HaveCount(6); result.Should().HaveCount(8);
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_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 == "sensor.nordpool_boiler_water_ready");
result.Should().Contain(e => e.EntityId == "switch.nordpool_boiler_skip_price_cap");
} }
[Fact] [Fact]
@@ -68,13 +70,15 @@ public class NordPoolEntityServiceTests
} }
[Fact] [Fact]
public void GetInitEntitiesList_AllEntities_ShouldHaveSensorDomain() public void GetInitEntitiesList_ShouldContainExpectedDomains()
{ {
// Act // Act
var result = _sut.GetInitEntitiesList("EUR/kWh"); var result = _sut.GetInitEntitiesList("EUR/kWh");
// Assert // Assert
result.Should().OnlyContain(e => e.Domain == "sensor"); result.Should().Contain(e => e.Domain == "sensor");
result.Should().Contain(e => e.Domain == "switch");
result.Should().OnlyContain(e => e.Domain == "sensor" || e.Domain == "switch");
} }
[Fact] [Fact]
@@ -102,7 +106,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(6)); _entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny<NordPoolEntity>()), Times.Exactly(8));
} }
[Fact] [Fact]
@@ -123,7 +127,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(6)); _entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny<NordPoolEntity>()), Times.Exactly(8));
} }
#endregion #endregion
@@ -145,8 +149,10 @@ public class NordPoolEntityServiceTests
_entityManagerMock.Verify(em => em.RemoveEntity("sensor.nordpool_current_price"), Times.Once); _entityManagerMock.Verify(em => em.RemoveEntity("sensor.nordpool_current_price"), Times.Once);
_entityManagerMock.Verify(em => em.RemoveEntity("sensor.nordpool_today_prices"), Times.Once); _entityManagerMock.Verify(em => em.RemoveEntity("sensor.nordpool_today_prices"), Times.Once);
_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_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("sensor.nordpool_boiler_water_ready"), Times.Once);
_entityManagerMock.Verify(em => em.RemoveEntity("switch.nordpool_boiler_skip_price_cap"), Times.Once);
} }
[Fact] [Fact]
@@ -250,8 +256,10 @@ public class NordPoolEntityServiceTests
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_current_price", "0"), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_current_price", "0"), 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_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("sensor.nordpool_boiler_water_ready", "unknown"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("switch.nordpool_boiler_skip_price_cap", "OFF"), Times.Once);
} }
[Fact] [Fact]
@@ -271,6 +279,7 @@ public class NordPoolEntityServiceTests
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_current_price", It.IsAny<object>()), Times.Once); _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_current_price", It.IsAny<object>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_today_prices", It.IsAny<object>()), Times.Once); _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_today_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_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); _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_boiler_water_ready", It.IsAny<object>()), Times.Once);
} }
@@ -294,9 +303,9 @@ public class NordPoolEntityServiceTests
} }
[Fact] [Fact]
public async Task ResetEntitiesAsync_ShouldCallSetStateTwelveTimesTotal() public async Task ResetEntitiesAsync_ShouldCallSetStateAndAttributesCorrectly()
{ {
// Arrange - 6 entities x (1 state + 1 attributes) = 12 calls total // Arrange - 8 entities get state, 7 entities get attributes (switch has state only)
_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>()))
@@ -306,8 +315,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(6)); _entityManagerMock.Verify(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()), Times.Exactly(8));
_entityManagerMock.Verify(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()), Times.Exactly(6)); _entityManagerMock.Verify(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()), Times.Exactly(7));
} }
#endregion #endregion
@@ -338,6 +347,7 @@ public class NordPoolEntityServiceTests
ConfiguredHours = 1.0, ConfiguredHours = 1.0,
ConfiguredIntervalCount = 4, ConfiguredIntervalCount = 4,
ConfiguredPriceCap = 100.0, ConfiguredPriceCap = 100.0,
SkipPriceCap = false,
ConfiguredReadyBy = "06:00", ConfiguredReadyBy = "06:00",
IsNowCheap = false, IsNowCheap = false,
NextCheapIntervalStart = null, NextCheapIntervalStart = null,
@@ -366,6 +376,7 @@ public class NordPoolEntityServiceTests
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_current_price", "12.50"), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_current_price", "12.50"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_today_prices", "1"), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_today_prices", "1"), Times.Once);
_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_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); _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_boiler_water_ready", It.IsAny<string>()), Times.Once);
} }
@@ -388,6 +399,7 @@ public class NordPoolEntityServiceTests
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_current_price", It.IsAny<object>()), Times.Once); _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_current_price", It.IsAny<object>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_today_prices", It.IsAny<object>()), Times.Once); _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_today_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_tomorrow_prices", It.IsAny<object>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny<object>()), Times.Once);
} }
[Fact] [Fact]
@@ -409,6 +421,112 @@ public class NordPoolEntityServiceTests
// Assert // Assert
_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", It.Is<string>(s =>
s.Length > 0 && s != "0" && s.Contains('-'))),
Times.Once);
}
[Fact]
public async Task UpdateEntitiesAsync_WithTodayAndTomorrowPrices_ShouldUpdateCombinedSensor()
{
// Arrange
var todayStart = new DateTime(2025, 3, 16, 6, 0, 0, DateTimeKind.Utc);
var tomorrowStart = new DateTime(2025, 3, 17, 6, 0, 0, DateTimeKind.Utc);
var todayPrice = new NordPoolPrice
{
Prices =
[
new NordPoolDayPrice { Start = todayStart.AddHours(2), End = todayStart.AddHours(2).AddMinutes(15), Price = 15.0 },
new NordPoolDayPrice { Start = todayStart, End = todayStart.AddMinutes(15), Price = 10.0 }
]
};
var tomorrowPrice = new NordPoolPrice
{
Prices =
[
new NordPoolDayPrice { Start = tomorrowStart, End = tomorrowStart.AddMinutes(15), Price = 20.0 }
]
};
var context = CreateDefaultContext(todayPrice: todayPrice, tomorrowPrice: tomorrowPrice);
_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.UpdateEntitiesAsync(context);
// Assert - state is update time in yyyy-MM-dd HH:mm:ss format
_entityManagerMock.Verify(
em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices", It.Is<string>(s =>
s.Length > 0 && s.Contains('-') && s.Contains(':') && s != "0" && s != "3")),
Times.Once);
// Assert - attributes contain merged, sorted prices (today 06:00, today 08:00, tomorrow 06:00)
_entityManagerMock.Verify(
em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.Is<object>(o =>
o.GetType().GetProperty("prices_count")!.GetValue(o)!.Equals(3))),
Times.Once);
}
[Fact]
public async Task UpdateEntitiesAsync_WithOnlyTodayPrices_ShouldUpdateCombinedSensor()
{
// Arrange
var todayPrice = new NordPoolPrice
{
Prices = [new NordPoolDayPrice { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddMinutes(15), Price = 12.0 }]
};
var context = CreateDefaultContext(todayPrice: todayPrice, tomorrowPrice: new NordPoolPrice { Prices = [] });
_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.UpdateEntitiesAsync(context);
// Assert
_entityManagerMock.Verify(
em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices", It.Is<string>(s =>
s.Length > 0 && s.Contains('-') && s != "0")),
Times.Once);
_entityManagerMock.Verify(
em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.Is<object>(o =>
o.GetType().GetProperty("prices_count")!.GetValue(o)!.Equals(1))),
Times.Once);
}
[Fact]
public async Task UpdateEntitiesAsync_WithOnlyTomorrowPrices_ShouldUpdateCombinedSensor()
{
// Arrange
var tomorrowPrice = new NordPoolPrice
{
Prices = [new NordPoolDayPrice { Start = DateTime.UtcNow.AddDays(1), End = DateTime.UtcNow.AddDays(1).AddMinutes(15), Price = 18.0 }]
};
var context = CreateDefaultContext(todayPrice: new NordPoolPrice { Prices = [] }, tomorrowPrice: tomorrowPrice);
_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.UpdateEntitiesAsync(context);
// Assert
_entityManagerMock.Verify(
em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices", It.Is<string>(s =>
s.Length > 0 && s.Contains('-') && s != "0")),
Times.Once);
_entityManagerMock.Verify(
em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.Is<object>(o =>
o.GetType().GetProperty("prices_count")!.GetValue(o)!.Equals(1))),
Times.Once);
} }
#endregion #endregion
@@ -37,6 +37,7 @@ public class NordPoolInitTests
{ {
return new NordPoolInit( return new NordPoolInit(
_entities, _entities,
_haContextMock.Object,
_loggerMock.Object, _loggerMock.Object,
_priceServiceMock.Object, _priceServiceMock.Object,
_entityServiceMock.Object, _entityServiceMock.Object,
+2 -1
View File
@@ -1,8 +1,9 @@
namespace NordPoolManager.Models; namespace NordPoolManager.Models;
public class BoilerConfig public class BoilerConfig
{ {
public int IntervalCount { get; set; } public int IntervalCount { get; set; }
public double PriceCap { get; set; } public double PriceCap { get; set; }
public DateTime Deadline { get; set; } public DateTime Deadline { get; set; }
public bool SkipPriceCap { get; set; }
} }
@@ -15,6 +15,7 @@ public record EntityUpdateContext
public required double ConfiguredHours { get; init; } public required double ConfiguredHours { get; init; }
public required int ConfiguredIntervalCount { get; init; } public required int ConfiguredIntervalCount { get; init; }
public required double ConfiguredPriceCap { get; init; } public required double ConfiguredPriceCap { get; init; }
public required bool SkipPriceCap { get; init; }
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; }
+1 -1
View File
@@ -19,7 +19,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="AutoMapper" Version="16.0.0" /> <PackageReference Include="AutoMapper" Version="16.1.1" />
</ItemGroup> </ItemGroup>
</Project> </Project>
+61 -3
View File
@@ -14,8 +14,10 @@ public class NordPoolEntityService(IEntityManager entityManager, ILogger<NordPoo
private const string CurrentPriceEntityId = "sensor.nordpool_current_price"; 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 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 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 =
[ [
@@ -23,8 +25,10 @@ public class NordPoolEntityService(IEntityManager entityManager, ILogger<NordPoo
CurrentPriceEntityId, CurrentPriceEntityId,
TodayPricesEntityId, TodayPricesEntityId,
TomorrowPricesEntityId, TomorrowPricesEntityId,
TodayTomorrowPricesEntityId,
CheapestIntervalsEntityId, CheapestIntervalsEntityId,
BoilerWaterReadyEntityId BoilerWaterReadyEntityId,
BoilerSkipPriceCapEntityId
]; ];
public async Task CreateEntitiesAsync(string? unitOfMeasurement) public async Task CreateEntitiesAsync(string? unitOfMeasurement)
@@ -54,8 +58,10 @@ public class NordPoolEntityService(IEntityManager entityManager, ILogger<NordPoo
ResetCurrentPriceAsync(), ResetCurrentPriceAsync(),
ResetTodayPricesAsync(), ResetTodayPricesAsync(),
ResetTomorrowPricesAsync(), ResetTomorrowPricesAsync(),
ResetTodayTomorrowPricesAsync(),
ResetCheapestIntervalsAsync(), ResetCheapestIntervalsAsync(),
ResetBoilerWaterReadyAsync() ResetBoilerWaterReadyAsync(),
ResetBoilerSkipPriceCapAsync()
); );
logger.LogInformation("All NordPool entity states reset to defaults"); logger.LogInformation("All NordPool entity states reset to defaults");
@@ -108,6 +114,18 @@ public class NordPoolEntityService(IEntityManager entityManager, ILogger<NordPoo
}); });
} }
private async Task ResetTodayTomorrowPricesAsync()
{
await SetEntityStateSafe(TodayTomorrowPricesEntityId, "unknown");
await SetEntityAttributesSafe(TodayTomorrowPricesEntityId, new
{
prices = Array.Empty<NordPoolDayPrice>(),
prices_count = 0,
friendly_name = "NordPool today and tomorrow prices",
last_updated = (string?)null
});
}
private async Task ResetCheapestIntervalsAsync() private async Task ResetCheapestIntervalsAsync()
{ {
await SetEntityStateSafe(CheapestIntervalsEntityId, "0"); await SetEntityStateSafe(CheapestIntervalsEntityId, "0");
@@ -139,6 +157,11 @@ public class NordPoolEntityService(IEntityManager entityManager, ILogger<NordPoo
}); });
} }
private async Task ResetBoilerSkipPriceCapAsync()
{
await SetEntityStateSafe(BoilerSkipPriceCapEntityId, "OFF");
}
public async Task UpdateEntitiesAsync(EntityUpdateContext ctx) public async Task UpdateEntitiesAsync(EntityUpdateContext ctx)
{ {
var utcNow = DateTime.UtcNow; var utcNow = DateTime.UtcNow;
@@ -185,6 +208,19 @@ public class NordPoolEntityService(IEntityManager entityManager, ILogger<NordPoo
last_updated = timestamp last_updated = timestamp
}); });
var mergedPrices = MergeTodayTomorrowPrices(ctx.TodayNordPoolPrice, ctx.TomorrowNordPoolPrice);
var updateTimeState = utcNow.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss");
logger.LogInformation("Updating sensor.nordpool_today_tomorrow_prices with {Count} merged prices", mergedPrices.Count);
await SetEntityStateSafe(TodayTomorrowPricesEntityId, updateTimeState);
await SetEntityAttributesSafe(TodayTomorrowPricesEntityId, new
{
prices = mergedPrices,
prices_count = mergedPrices.Count,
friendly_name = "NordPool today and tomorrow prices",
last_updated = timestamp
});
var cheapestCount = ctx.CheapestIntervals?.Count ?? 0; var cheapestCount = ctx.CheapestIntervals?.Count ?? 0;
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);
@@ -195,6 +231,7 @@ public class NordPoolEntityService(IEntityManager entityManager, ILogger<NordPoo
configured_hours = ctx.ConfiguredHours, configured_hours = ctx.ConfiguredHours,
configured_interval_count = ctx.ConfiguredIntervalCount, configured_interval_count = ctx.ConfiguredIntervalCount,
configured_price_cap = ctx.ConfiguredPriceCap, configured_price_cap = ctx.ConfiguredPriceCap,
skip_price_cap = ctx.SkipPriceCap,
configured_ready_by = ctx.ConfiguredReadyBy, configured_ready_by = ctx.ConfiguredReadyBy,
total_heating_minutes = cheapestCount * 15, total_heating_minutes = cheapestCount * 15,
is_now_cheap = ctx.IsNowCheap, is_now_cheap = ctx.IsNowCheap,
@@ -257,13 +294,34 @@ public class NordPoolEntityService(IEntityManager entityManager, ILogger<NordPoo
}, },
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_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("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; return entries;
} }
private static IReadOnlyList<NordPoolDayPrice> MergeTodayTomorrowPrices(
NordPoolPrice? today, NordPoolPrice? tomorrow)
{
var todayList = today?.Prices ?? [];
var tomorrowList = tomorrow?.Prices ?? [];
return todayList
.Concat(tomorrowList)
.Where(p => p?.Start != null)
.OrderBy(p => p!.Start!.Value)
.ToList();
}
internal async Task SetEntityStateSafe(string entityId, string state) internal async Task SetEntityStateSafe(string entityId, string state)
{ {
try try
+91 -12
View File
@@ -1,6 +1,7 @@
using System.Reactive.Concurrency; using System.Reactive.Concurrency;
using HomeAssistantGenerated; using HomeAssistantGenerated;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using NetDaemon.HassModel;
using NetDaemon.AppModel; using NetDaemon.AppModel;
using NetDaemon.Extensions.Scheduler; using NetDaemon.Extensions.Scheduler;
using NordPool.Models; using NordPool.Models;
@@ -19,17 +20,21 @@ public class NordPoolInit : INordPoolInit
private readonly ICheapestIntervalsFinder _cheapestIntervalsFinder; private readonly ICheapestIntervalsFinder _cheapestIntervalsFinder;
private readonly IBoilerControlService _boilerControlService; private readonly IBoilerControlService _boilerControlService;
private readonly IScheduler _scheduler; private readonly IScheduler _scheduler;
private readonly IHaContext _haContext;
private InputNumberEntity BoilerDailyHoursEntity { get; } private InputNumberEntity BoilerDailyHoursEntity { get; }
private InputNumberEntity BoilerPriceCapEntity { get; } private InputNumberEntity BoilerPriceCapEntity { get; }
private SwitchEntity BoilerSkipPriceCapEntity { get; }
private InputDatetimeEntity BoilerReadyByEntity { get; } private InputDatetimeEntity BoilerReadyByEntity { get; }
private SwitchEntity BoilerSwitchEntity { get; } private SwitchEntity BoilerSwitchEntity { get; }
private NumericSensorEntity BoilerPowerEntity { 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,
@@ -38,6 +43,7 @@ public class NordPoolInit : INordPoolInit
IBoilerControlService boilerControlService) IBoilerControlService boilerControlService)
{ {
_logger = logger; _logger = logger;
_haContext = haContext;
_priceService = priceService; _priceService = priceService;
_entityService = entityService; _entityService = entityService;
_scheduler = scheduler; _scheduler = scheduler;
@@ -48,6 +54,7 @@ public class NordPoolInit : INordPoolInit
UnitOfMeasurement = nordPoolPriceSensor.EntityState?.Attributes?.UnitOfMeasurement ?? "EUR/kWh"; UnitOfMeasurement = nordPoolPriceSensor.EntityState?.Attributes?.UnitOfMeasurement ?? "EUR/kWh";
BoilerDailyHoursEntity = entities.InputNumber.BoilerDailyHours; BoilerDailyHoursEntity = entities.InputNumber.BoilerDailyHours;
BoilerPriceCapEntity = entities.InputNumber.BoilerPriceCap; BoilerPriceCapEntity = entities.InputNumber.BoilerPriceCap;
BoilerSkipPriceCapEntity = new SwitchEntity(_haContext, "switch.nordpool_boiler_skip_price_cap");
BoilerReadyByEntity = entities.InputDatetime.BoilerReadyBy; BoilerReadyByEntity = entities.InputDatetime.BoilerReadyBy;
BoilerSwitchEntity = entities.Switch.Sonoff1002230e32; BoilerSwitchEntity = entities.Switch.Sonoff1002230e32;
BoilerPowerEntity = entities.Sensor.Sonoff1002230e32Power; BoilerPowerEntity = entities.Sensor.Sonoff1002230e32Power;
@@ -61,6 +68,8 @@ public class NordPoolInit : INordPoolInit
{ {
await InitializeAsync(); await InitializeAsync();
SchedulePeriodicUpdates(); SchedulePeriodicUpdates();
ScheduleEndOfDayReminder();
SubscribeToSkipPriceCapChanges();
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -68,6 +77,59 @@ public class NordPoolInit : INordPoolInit
} }
} }
private void ScheduleEndOfDayReminder()
{
_scheduler.ScheduleCron("0 20 * * *", () =>
{
_ = CheckSkipPriceCapReminderAsync();
});
}
private async Task 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 (intervalCount, priceCap, skipPriceCap) = UpdateCheapestIntervals();
await UpdateEntitiesAsync(intervalCount, priceCap, 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
@@ -90,8 +152,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 (intervalCount, priceCap) = UpdateCheapestIntervals(); var (intervalCount, priceCap, skipPriceCap) = UpdateCheapestIntervals();
await UpdateEntitiesAsync(intervalCount, priceCap); await UpdateEntitiesAsync(intervalCount, priceCap, skipPriceCap);
_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);
} }
@@ -156,8 +218,8 @@ public class NordPoolInit : INordPoolInit
_priceService.UpdateCurrentPrice(); _priceService.UpdateCurrentPrice();
var (intervalCount, priceCap) = UpdateCheapestIntervals(); var (intervalCount, priceCap, skipPriceCap) = UpdateCheapestIntervals();
await UpdateEntitiesAsync(intervalCount, priceCap); await UpdateEntitiesAsync(intervalCount, priceCap, skipPriceCap);
_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);
} }
@@ -172,9 +234,11 @@ public class NordPoolInit : INordPoolInit
await _entityService.CleanupEntitiesAsync(); await _entityService.CleanupEntitiesAsync();
} }
private (int IntervalCount, double PriceCap) UpdateCheapestIntervals() private (int IntervalCount, double PriceCap, bool SkipPriceCap) UpdateCheapestIntervals()
{ {
var boilerConfig = ReadBoilerConfig(); var boilerConfig = ReadBoilerConfig();
var effectivePriceCap = boilerConfig.SkipPriceCap ? double.MaxValue : boilerConfig.PriceCap;
var effectiveIntervalCount = boilerConfig.SkipPriceCap ? 96 : boilerConfig.IntervalCount;
try try
{ {
@@ -182,13 +246,13 @@ 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 (boilerConfig.IntervalCount, boilerConfig.PriceCap); return (boilerConfig.IntervalCount, boilerConfig.PriceCap, boilerConfig.SkipPriceCap);
} }
CheapestIntervals = _cheapestIntervalsFinder.FindCheapestIntervals(_priceService.TodayNordPoolPrice, boilerConfig.IntervalCount, boilerConfig.PriceCap, boilerConfig.Deadline); CheapestIntervals = _cheapestIntervalsFinder.FindCheapestIntervals(_priceService.TodayNordPoolPrice, effectiveIntervalCount, effectivePriceCap, boilerConfig.Deadline);
_logger.LogInformation("Cheapest intervals updated: {Count} intervals (config: {Hours}h / {Intervals} intervals, cap: {Cap}, 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, boilerConfig.IntervalCount, boilerConfig.PriceCap, boilerConfig.Deadline); CheapestIntervals.Count, boilerConfig.IntervalCount / 4.0, effectiveIntervalCount, effectivePriceCap, boilerConfig.SkipPriceCap, boilerConfig.Deadline);
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -196,7 +260,7 @@ public class NordPoolInit : INordPoolInit
CheapestIntervals = []; CheapestIntervals = [];
} }
return (boilerConfig.IntervalCount, boilerConfig.PriceCap); return (boilerConfig.IntervalCount, boilerConfig.PriceCap, boilerConfig.SkipPriceCap);
} }
private BoilerConfig ReadBoilerConfig() private BoilerConfig ReadBoilerConfig()
@@ -232,12 +296,15 @@ public class NordPoolInit : INordPoolInit
boilerConfig.Deadline = deadline; boilerConfig.Deadline = deadline;
_logger.LogDebug("Boiler config: intervals={Intervals}, priceCap={Cap}, deadline={Deadline}", boilerConfig.IntervalCount, boilerConfig.PriceCap, boilerConfig.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; return boilerConfig;
} }
private async Task UpdateEntitiesAsync(int configuredIntervalCount, double configuredPriceCap) 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);
@@ -257,6 +324,17 @@ public class NordPoolInit : INordPoolInit
var boilerPowerWatts = BoilerPowerEntity.State; var boilerPowerWatts = BoilerPowerEntity.State;
var waterReady = _cheapestIntervalsFinder.IsWaterReady(boilerSwitchState, boilerPowerWatts); 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); var boilerAction = _boilerControlService.DetermineAction(isNowCheap, waterReady, boilerSwitchState);
if (boilerAction == TurnOn) if (boilerAction == TurnOn)
@@ -281,6 +359,7 @@ public class NordPoolInit : INordPoolInit
ConfiguredHours = configuredHours, ConfiguredHours = configuredHours,
ConfiguredIntervalCount = configuredIntervalCount, ConfiguredIntervalCount = configuredIntervalCount,
ConfiguredPriceCap = configuredPriceCap, ConfiguredPriceCap = configuredPriceCap,
SkipPriceCap = skipPriceCap,
ConfiguredReadyBy = configuredReadyBy, ConfiguredReadyBy = configuredReadyBy,
IsNowCheap = isNowCheap, IsNowCheap = isNowCheap,
NextCheapIntervalStart = nextCheapInterval?.Start, NextCheapIntervalStart = nextCheapInterval?.Start,