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
+2 -1
View File
@@ -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; }
}
@@ -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; }
+1 -1
View File
@@ -19,7 +19,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="AutoMapper" Version="16.0.0" />
<PackageReference Include="AutoMapper" Version="16.1.1" />
</ItemGroup>
</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 TodayPricesEntityId = "sensor.nordpool_today_prices";
private const string TomorrowPricesEntityId = "sensor.nordpool_tomorrow_prices";
private const string TodayTomorrowPricesEntityId = "sensor.nordpool_today_tomorrow_prices";
private const string CheapestIntervalsEntityId = "sensor.nordpool_cheapest_intervals";
private const string BoilerWaterReadyEntityId = "sensor.nordpool_boiler_water_ready";
private const string BoilerSkipPriceCapEntityId = "switch.nordpool_boiler_skip_price_cap";
private static readonly string[] AllEntityIds =
[
@@ -23,8 +25,10 @@ public class NordPoolEntityService(IEntityManager entityManager, ILogger<NordPoo
CurrentPriceEntityId,
TodayPricesEntityId,
TomorrowPricesEntityId,
TodayTomorrowPricesEntityId,
CheapestIntervalsEntityId,
BoilerWaterReadyEntityId
BoilerWaterReadyEntityId,
BoilerSkipPriceCapEntityId
];
public async Task CreateEntitiesAsync(string? unitOfMeasurement)
@@ -54,8 +58,10 @@ public class NordPoolEntityService(IEntityManager entityManager, ILogger<NordPoo
ResetCurrentPriceAsync(),
ResetTodayPricesAsync(),
ResetTomorrowPricesAsync(),
ResetTodayTomorrowPricesAsync(),
ResetCheapestIntervalsAsync(),
ResetBoilerWaterReadyAsync()
ResetBoilerWaterReadyAsync(),
ResetBoilerSkipPriceCapAsync()
);
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()
{
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)
{
var utcNow = DateTime.UtcNow;
@@ -185,6 +208,19 @@ public class NordPoolEntityService(IEntityManager entityManager, ILogger<NordPoo
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;
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_interval_count = ctx.ConfiguredIntervalCount,
configured_price_cap = ctx.ConfiguredPriceCap,
skip_price_cap = ctx.SkipPriceCap,
configured_ready_by = ctx.ConfiguredReadyBy,
total_heating_minutes = cheapestCount * 15,
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_tomorrow_prices", "NordPool tomorrow prices"),
new NordPoolEntity("sensor", "nordpool_today_tomorrow_prices", "NordPool today and tomorrow prices"),
new NordPoolEntity("sensor", "nordpool_cheapest_intervals", "NordPool cheapest boiler intervals"),
new NordPoolEntity("sensor", "nordpool_boiler_water_ready", "Boiler water ready")
new NordPoolEntity("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 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)
{
try
+91 -12
View File
@@ -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<CheapestIntervalResult>? CheapestIntervals { get; set; }
private bool _lastWaterReady;
public NordPoolInit(
Entities entities,
IHaContext haContext,
ILogger<NordPoolInit> 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,