From 53eb53539ae06e67c00fb4f4511a1638e073184b Mon Sep 17 00:00:00 2001 From: Marius Date: Mon, 16 Mar 2026 11:42:49 +0200 Subject: [PATCH] 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. --- .../water_heater_preparation_decision.plan.md | 130 +++++++++++++++++ .../HomeAssistant.Server.csproj | 2 +- HomeAssistant.Server/appsettings.json | 10 -- Mappings/Mappings.csproj | 2 +- .../CheapestIntervalsFinderTests.cs | 17 +++ .../NordPool.Manager.Tests.csproj | 2 +- .../NordPoolEntityServiceTests.cs | 136 ++++++++++++++++-- NordPool.Manager.Tests/NordPoolInitTests.cs | 1 + NordPool.Manager/Models/BoilerConfig.cs | 3 +- .../Models/EntityUpdateContext.cs | 1 + NordPool.Manager/NordPool.Manager.csproj | 2 +- NordPool.Manager/NordPoolEntityService.cs | 64 ++++++++- NordPool.Manager/NordPoolInit.cs | 103 +++++++++++-- 13 files changed, 434 insertions(+), 39 deletions(-) create mode 100644 .cursor/plans/water_heater_preparation_decision.plan.md diff --git a/.cursor/plans/water_heater_preparation_decision.plan.md b/.cursor/plans/water_heater_preparation_decision.plan.md new file mode 100644 index 0000000..38d6763 --- /dev/null +++ b/.cursor/plans/water_heater_preparation_decision.plan.md @@ -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 diff --git a/HomeAssistant.Server/HomeAssistant.Server.csproj b/HomeAssistant.Server/HomeAssistant.Server.csproj index 6daf638..08a1a9a 100644 --- a/HomeAssistant.Server/HomeAssistant.Server.csproj +++ b/HomeAssistant.Server/HomeAssistant.Server.csproj @@ -33,7 +33,7 @@ - + diff --git a/HomeAssistant.Server/appsettings.json b/HomeAssistant.Server/appsettings.json index 7beac8a..48704ab 100644 --- a/HomeAssistant.Server/appsettings.json +++ b/HomeAssistant.Server/appsettings.json @@ -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": { "ApplicationConfigurationFolder": "./apps" }, diff --git a/Mappings/Mappings.csproj b/Mappings/Mappings.csproj index 0a44594..fd262b8 100644 --- a/Mappings/Mappings.csproj +++ b/Mappings/Mappings.csproj @@ -7,7 +7,7 @@ - + diff --git a/NordPool.Manager.Tests/CheapestIntervalsFinderTests.cs b/NordPool.Manager.Tests/CheapestIntervalsFinderTests.cs index 3fbd1af..837eec0 100644 --- a/NordPool.Manager.Tests/CheapestIntervalsFinderTests.cs +++ b/NordPool.Manager.Tests/CheapestIntervalsFinderTests.cs @@ -161,6 +161,23 @@ public class CheapestIntervalsFinderTests 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] public void FindCheapestIntervals_WithDeadlineAndPriceCap_ShouldApplyBothFilters() { diff --git a/NordPool.Manager.Tests/NordPool.Manager.Tests.csproj b/NordPool.Manager.Tests/NordPool.Manager.Tests.csproj index ff5ca0a..c2bdbd9 100644 --- a/NordPool.Manager.Tests/NordPool.Manager.Tests.csproj +++ b/NordPool.Manager.Tests/NordPool.Manager.Tests.csproj @@ -18,7 +18,7 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive - + diff --git a/NordPool.Manager.Tests/NordPoolEntityServiceTests.cs b/NordPool.Manager.Tests/NordPoolEntityServiceTests.cs index 7407dd8..45b7437 100644 --- a/NordPool.Manager.Tests/NordPoolEntityServiceTests.cs +++ b/NordPool.Manager.Tests/NordPoolEntityServiceTests.cs @@ -31,13 +31,15 @@ public class NordPoolEntityServiceTests // Assert 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_current_price"); result.Should().Contain(e => e.EntityId == "sensor.nordpool_today_prices"); result.Should().Contain(e => e.EntityId == "sensor.nordpool_tomorrow_prices"); + result.Should().Contain(e => e.EntityId == "sensor.nordpool_today_tomorrow_prices"); result.Should().Contain(e => e.EntityId == "sensor.nordpool_cheapest_intervals"); result.Should().Contain(e => e.EntityId == "sensor.nordpool_boiler_water_ready"); + result.Should().Contain(e => e.EntityId == "switch.nordpool_boiler_skip_price_cap"); } [Fact] @@ -68,13 +70,15 @@ public class NordPoolEntityServiceTests } [Fact] - public void GetInitEntitiesList_AllEntities_ShouldHaveSensorDomain() + public void GetInitEntitiesList_ShouldContainExpectedDomains() { // Act var result = _sut.GetInitEntitiesList("EUR/kWh"); // 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] @@ -102,7 +106,7 @@ public class NordPoolEntityServiceTests await _sut.CreateEntitiesAsync("EUR/kWh"); // Assert - _entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny()), Times.Exactly(6)); + _entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny()), Times.Exactly(8)); } [Fact] @@ -123,7 +127,7 @@ public class NordPoolEntityServiceTests await _sut.CreateEntitiesAsync("EUR/kWh"); // Assert - _entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny()), Times.Exactly(6)); + _entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny()), Times.Exactly(8)); } #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_today_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_boiler_water_ready"), Times.Once); + _entityManagerMock.Verify(em => em.RemoveEntity("switch.nordpool_boiler_skip_price_cap"), Times.Once); } [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_today_prices", "0"), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_tomorrow_prices", "0"), Times.Once); + _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices", "unknown"), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_cheapest_intervals", "0"), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_boiler_water_ready", "unknown"), Times.Once); + _entityManagerMock.Verify(em => em.SetEntityState("switch.nordpool_boiler_skip_price_cap", "OFF"), Times.Once); } [Fact] @@ -271,6 +279,7 @@ public class NordPoolEntityServiceTests _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_current_price", It.IsAny()), Times.Once); _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_today_prices", It.IsAny()), Times.Once); _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_tomorrow_prices", It.IsAny()), Times.Once); + _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny()), Times.Once); _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_cheapest_intervals", It.IsAny()), Times.Once); _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_boiler_water_ready", It.IsAny()), Times.Once); } @@ -294,9 +303,9 @@ public class NordPoolEntityServiceTests } [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(), It.IsAny())) .Returns(Task.CompletedTask); _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) @@ -306,8 +315,8 @@ public class NordPoolEntityServiceTests await _sut.ResetEntitiesAsync(); // Assert - _entityManagerMock.Verify(em => em.SetEntityState(It.IsAny(), It.IsAny()), Times.Exactly(6)); - _entityManagerMock.Verify(em => em.SetEntityAttributes(It.IsAny(), It.IsAny()), Times.Exactly(6)); + _entityManagerMock.Verify(em => em.SetEntityState(It.IsAny(), It.IsAny()), Times.Exactly(8)); + _entityManagerMock.Verify(em => em.SetEntityAttributes(It.IsAny(), It.IsAny()), Times.Exactly(7)); } #endregion @@ -338,6 +347,7 @@ public class NordPoolEntityServiceTests ConfiguredHours = 1.0, ConfiguredIntervalCount = 4, ConfiguredPriceCap = 100.0, + SkipPriceCap = false, ConfiguredReadyBy = "06:00", IsNowCheap = false, 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_today_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(s => s.Contains('-') && s.Contains(':'))), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_cheapest_intervals", It.IsAny()), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_boiler_water_ready", It.IsAny()), Times.Once); } @@ -388,6 +399,7 @@ public class NordPoolEntityServiceTests _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_current_price", It.IsAny()), Times.Once); _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_today_prices", It.IsAny()), Times.Once); _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_tomorrow_prices", It.IsAny()), Times.Once); + _entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny()), Times.Once); } [Fact] @@ -409,6 +421,112 @@ public class NordPoolEntityServiceTests // Assert _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_today_prices", "0"), Times.Once); _entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_tomorrow_prices", "0"), Times.Once); + _entityManagerMock.Verify( + em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices", It.Is(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(), It.IsAny())) + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) + .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(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(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(), It.IsAny())) + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) + .Returns(Task.CompletedTask); + + // Act + await _sut.UpdateEntitiesAsync(context); + + // Assert + _entityManagerMock.Verify( + em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices", It.Is(s => + s.Length > 0 && s.Contains('-') && s != "0")), + Times.Once); + _entityManagerMock.Verify( + em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.Is(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(), It.IsAny())) + .Returns(Task.CompletedTask); + _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny(), It.IsAny())) + .Returns(Task.CompletedTask); + + // Act + await _sut.UpdateEntitiesAsync(context); + + // Assert + _entityManagerMock.Verify( + em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices", It.Is(s => + s.Length > 0 && s.Contains('-') && s != "0")), + Times.Once); + _entityManagerMock.Verify( + em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.Is(o => + o.GetType().GetProperty("prices_count")!.GetValue(o)!.Equals(1))), + Times.Once); } #endregion diff --git a/NordPool.Manager.Tests/NordPoolInitTests.cs b/NordPool.Manager.Tests/NordPoolInitTests.cs index e8dfcd3..c4c2e1b 100644 --- a/NordPool.Manager.Tests/NordPoolInitTests.cs +++ b/NordPool.Manager.Tests/NordPoolInitTests.cs @@ -37,6 +37,7 @@ public class NordPoolInitTests { return new NordPoolInit( _entities, + _haContextMock.Object, _loggerMock.Object, _priceServiceMock.Object, _entityServiceMock.Object, diff --git a/NordPool.Manager/Models/BoilerConfig.cs b/NordPool.Manager/Models/BoilerConfig.cs index dd9f382..2dbacf1 100644 --- a/NordPool.Manager/Models/BoilerConfig.cs +++ b/NordPool.Manager/Models/BoilerConfig.cs @@ -1,8 +1,9 @@ -namespace NordPoolManager.Models; +namespace NordPoolManager.Models; public class BoilerConfig { public int IntervalCount { get; set; } public double PriceCap { get; set; } public DateTime Deadline { get; set; } + public bool SkipPriceCap { get; set; } } diff --git a/NordPool.Manager/Models/EntityUpdateContext.cs b/NordPool.Manager/Models/EntityUpdateContext.cs index dd59e07..5b27ef7 100644 --- a/NordPool.Manager/Models/EntityUpdateContext.cs +++ b/NordPool.Manager/Models/EntityUpdateContext.cs @@ -15,6 +15,7 @@ public record EntityUpdateContext public required double ConfiguredHours { get; init; } public required int ConfiguredIntervalCount { get; init; } public required double ConfiguredPriceCap { get; init; } + public required bool SkipPriceCap { get; init; } public required string? ConfiguredReadyBy { get; init; } public required bool IsNowCheap { get; init; } public required DateTime? NextCheapIntervalStart { get; init; } diff --git a/NordPool.Manager/NordPool.Manager.csproj b/NordPool.Manager/NordPool.Manager.csproj index 301c064..1bb7f44 100644 --- a/NordPool.Manager/NordPool.Manager.csproj +++ b/NordPool.Manager/NordPool.Manager.csproj @@ -19,7 +19,7 @@ - + diff --git a/NordPool.Manager/NordPoolEntityService.cs b/NordPool.Manager/NordPoolEntityService.cs index 9737bf0..7839dca 100644 --- a/NordPool.Manager/NordPoolEntityService.cs +++ b/NordPool.Manager/NordPoolEntityService.cs @@ -14,8 +14,10 @@ public class NordPoolEntityService(IEntityManager entityManager, ILogger(), + prices_count = 0, + friendly_name = "NordPool today and tomorrow prices", + last_updated = (string?)null + }); + } + private async Task ResetCheapestIntervalsAsync() { await SetEntityStateSafe(CheapestIntervalsEntityId, "0"); @@ -139,6 +157,11 @@ public class NordPoolEntityService(IEntityManager entityManager, ILogger 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) { try diff --git a/NordPool.Manager/NordPoolInit.cs b/NordPool.Manager/NordPoolInit.cs index a30df0d..7347f51 100644 --- a/NordPool.Manager/NordPoolInit.cs +++ b/NordPool.Manager/NordPoolInit.cs @@ -1,6 +1,7 @@ using System.Reactive.Concurrency; using HomeAssistantGenerated; using Microsoft.Extensions.Logging; +using NetDaemon.HassModel; using NetDaemon.AppModel; using NetDaemon.Extensions.Scheduler; using NordPool.Models; @@ -19,17 +20,21 @@ public class NordPoolInit : INordPoolInit private readonly ICheapestIntervalsFinder _cheapestIntervalsFinder; private readonly IBoilerControlService _boilerControlService; private readonly IScheduler _scheduler; + private readonly IHaContext _haContext; private InputNumberEntity BoilerDailyHoursEntity { get; } private InputNumberEntity BoilerPriceCapEntity { get; } + private SwitchEntity BoilerSkipPriceCapEntity { get; } private InputDatetimeEntity BoilerReadyByEntity { get; } private SwitchEntity BoilerSwitchEntity { get; } private NumericSensorEntity BoilerPowerEntity { get; } private string? UnitOfMeasurement { get; } private IReadOnlyList? CheapestIntervals { get; set; } + private bool _lastWaterReady; public NordPoolInit( Entities entities, + IHaContext haContext, ILogger logger, INordPoolPriceService priceService, INordPoolEntityService entityService, @@ -38,6 +43,7 @@ public class NordPoolInit : INordPoolInit IBoilerControlService boilerControlService) { _logger = logger; + _haContext = haContext; _priceService = priceService; _entityService = entityService; _scheduler = scheduler; @@ -48,6 +54,7 @@ public class NordPoolInit : INordPoolInit 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; @@ -61,6 +68,8 @@ public class NordPoolInit : INordPoolInit { await InitializeAsync(); SchedulePeriodicUpdates(); + ScheduleEndOfDayReminder(); + SubscribeToSkipPriceCapChanges(); } 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() { try @@ -90,8 +152,8 @@ public class NordPoolInit : INordPoolInit _logger.LogWarning("Current price is 0, which may indicate an issue with price retrieval"); } - var (intervalCount, priceCap) = UpdateCheapestIntervals(); - await UpdateEntitiesAsync(intervalCount, priceCap); + var (intervalCount, priceCap, skipPriceCap) = UpdateCheapestIntervals(); + await UpdateEntitiesAsync(intervalCount, priceCap, skipPriceCap); _logger.LogInformation("NordPool price initialized with current price: {CurrentPrice} {Unit}", _priceService.CurrentPrice, UnitOfMeasurement); } @@ -156,8 +218,8 @@ public class NordPoolInit : INordPoolInit _priceService.UpdateCurrentPrice(); - var (intervalCount, priceCap) = UpdateCheapestIntervals(); - await UpdateEntitiesAsync(intervalCount, priceCap); + var (intervalCount, priceCap, skipPriceCap) = UpdateCheapestIntervals(); + await UpdateEntitiesAsync(intervalCount, priceCap, skipPriceCap); _logger.LogInformation("NordPool prices updated successfully. Current price: {CurrentPrice} {Unit}", _priceService.CurrentPrice, UnitOfMeasurement); } @@ -172,9 +234,11 @@ public class NordPoolInit : INordPoolInit await _entityService.CleanupEntitiesAsync(); } - private (int IntervalCount, double PriceCap) UpdateCheapestIntervals() + private (int IntervalCount, double PriceCap, bool SkipPriceCap) UpdateCheapestIntervals() { var boilerConfig = ReadBoilerConfig(); + var effectivePriceCap = boilerConfig.SkipPriceCap ? double.MaxValue : boilerConfig.PriceCap; + var effectiveIntervalCount = boilerConfig.SkipPriceCap ? 96 : boilerConfig.IntervalCount; try { @@ -182,13 +246,13 @@ public class NordPoolInit : INordPoolInit { _logger.LogDebug("No today prices available, skipping cheapest intervals calculation"); 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})", - CheapestIntervals.Count, boilerConfig.IntervalCount / 4.0, boilerConfig.IntervalCount, boilerConfig.PriceCap, boilerConfig.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); } catch (Exception ex) { @@ -196,7 +260,7 @@ public class NordPoolInit : INordPoolInit CheapestIntervals = []; } - return (boilerConfig.IntervalCount, boilerConfig.PriceCap); + return (boilerConfig.IntervalCount, boilerConfig.PriceCap, boilerConfig.SkipPriceCap); } private BoilerConfig ReadBoilerConfig() @@ -232,12 +296,15 @@ public class NordPoolInit : INordPoolInit 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; } - 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 nowCet = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, cetTimeZone); @@ -257,6 +324,17 @@ public class NordPoolInit : INordPoolInit 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); if (boilerAction == TurnOn) @@ -281,6 +359,7 @@ public class NordPoolInit : INordPoolInit ConfiguredHours = configuredHours, ConfiguredIntervalCount = configuredIntervalCount, ConfiguredPriceCap = configuredPriceCap, + SkipPriceCap = skipPriceCap, ConfiguredReadyBy = configuredReadyBy, IsNowCheap = isNowCheap, NextCheapIntervalStart = nextCheapInterval?.Start,