This commit is contained in:
2026-06-28 13:58:35 +03:00
parent 8f45028715
commit e6bf8258bb
114 changed files with 4365 additions and 874 deletions
@@ -43,8 +43,6 @@ public class CheapestIntervalsFinder(ILogger<CheapestIntervalsFinder> logger) :
.OrderBy(r => r.Start)
.ToList();
logger.LogInformation("Found {Count} cheapest intervals out of {Requested} requested (deadline: {Deadline}, price cap: {Cap})", ranked.Count, numberOfIntervals, deadline, priceCap);
return ranked;
}
@@ -0,0 +1,11 @@
using BoilerMonitor.Models;
namespace NordPoolManager.Interface;
/// <summary>
/// Supplies boiler scheduling configuration for NordPool cheapest-interval logic.
/// </summary>
public interface INordPoolBoilerConfigProvider
{
BoilerConfig GetCurrentConfiguration();
}
@@ -0,0 +1,12 @@
using BoilerMonitor.Models;
using NordPoolManager.Interface;
namespace NordPoolManager;
/// <summary>
/// Resolves boiler configuration from Home Assistant state for NordPool scheduling.
/// </summary>
public sealed class NordPoolBoilerConfigProvider(IBoilerConfigReader boilerConfigReader) : INordPoolBoilerConfigProvider
{
public BoilerConfig GetCurrentConfiguration() => boilerConfigReader.ReadConfig();
}
+2 -17
View File
@@ -36,7 +36,6 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
{
try
{
logger.LogInformation("Creating/re-registering MQTT entity: {EntityId}", nordPoolEntity.EntityId);
await entityManager.CreateEntityAsync(nordPoolEntity).ConfigureAwait(false);
}
catch (Exception ex)
@@ -51,9 +50,7 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
public async Task ResetEntitiesAsync(CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
logger.LogInformation("Resetting all NordPool entity states to defaults");
await Task.WhenAll(
ResetLastUpdateTimeAsync(),
ResetCurrentPriceAsync(),
@@ -62,8 +59,6 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
ResetTodayTomorrowPricesAsync(),
ResetCheapestIntervalsAsync()
).ConfigureAwait(false);
logger.LogInformation("All NordPool entity states reset to defaults");
}
private async Task ResetLastUpdateTimeAsync()
@@ -162,11 +157,7 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
}
var cheapestCount = ctx.CheapestIntervals?.Count ?? 0;
logger.LogInformation("Updating nordpool_current_price with value: {Price} {Unit}", priceValue, ctx.UnitOfMeasurement);
logger.LogInformation("Updating sensor.nordpool_today_prices with {Count} prices", todayPricesCount);
logger.LogInformation("Updating sensor.nordpool_tomorrow_prices with {Count} prices", tomorrowPricesCount);
logger.LogInformation("Updating sensor.nordpool_today_tomorrow_prices with {Count} merged prices", mergedPrices.Count);
logger.LogInformation("Updating sensor.nordpool_cheapest_intervals with {Count} intervals, is_now_cheap={IsNow}", cheapestCount, ctx.IsNowCheap);
var updateTasks = new[]
@@ -180,8 +171,6 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
};
await Task.WhenAll(updateTasks).ConfigureAwait(false);
logger.LogInformation("NordPool entities updated successfully. Today prices count: {TodayCount}, Tomorrow prices count: {TomorrowCount}", todayPricesCount, tomorrowPricesCount);
}
private async Task UpdateLastUpdateTimeAsync(string updateTimeState)
@@ -266,8 +255,6 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
{
var removeTasks = AllEntityIds.Select(entityManager.RemoveEntity);
await Task.WhenAll(removeTasks).ConfigureAwait(false);
logger.LogInformation("NordPool entities cleaned up successfully");
}
catch (Exception ex)
{
@@ -323,7 +310,6 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
try
{
await entityManager.SetEntityState(entityId, state).ConfigureAwait(false);
logger.LogDebug("Successfully set state for {EntityId}: {State}", entityId, state);
}
catch (Exception ex)
{
@@ -336,7 +322,6 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
try
{
await entityManager.SetEntityAttributes(entityId, attributes).ConfigureAwait(false);
logger.LogDebug("Successfully set attributes for {EntityId}", entityId);
}
catch (Exception ex)
{
+14 -49
View File
@@ -19,7 +19,7 @@ public class NordPoolInit : INordPoolInit
private readonly INordPoolPriceService _priceService;
private readonly INordPoolEntityService _entityService;
private readonly ICheapestIntervalsFinder _cheapestIntervalsFinder;
private readonly IBoilerConfigReader _boilerConfigReader;
private readonly INordPoolBoilerConfigProvider _boilerConfigProvider;
private readonly IScheduler _scheduler;
private readonly NordPoolOptions _options;
@@ -33,7 +33,7 @@ public class NordPoolInit : INordPoolInit
INordPoolEntityService entityService,
IScheduler scheduler,
ICheapestIntervalsFinder cheapestIntervalsFinder,
IBoilerConfigReader boilerConfigReader,
INordPoolBoilerConfigProvider boilerConfigProvider,
IOptions<NordPoolOptions> options)
{
_logger = logger;
@@ -41,7 +41,7 @@ public class NordPoolInit : INordPoolInit
_entityService = entityService;
_scheduler = scheduler;
_cheapestIntervalsFinder = cheapestIntervalsFinder;
_boilerConfigReader = boilerConfigReader;
_boilerConfigProvider = boilerConfigProvider;
_options = options.Value;
var nordPoolPriceSensor = entities.Sensor.NordpoolPrice;
@@ -75,29 +75,21 @@ public class NordPoolInit : INordPoolInit
{
await _entityService.CleanupEntitiesAsync();
}
else
{
_logger.LogInformation("Skipping NordPool entity cleanup on startup (CleanupEntitiesOnStartup is false)");
}
await _entityService.CreateEntitiesAsync(UnitOfMeasurement);
await _entityService.ResetEntitiesAsync();
await Task.Delay(TimeSpan.FromSeconds(10));
var currentPrice = _priceService.UpdateCurrentPrice();
_logger.LogInformation("Retrieved current price: {Price}, DayQuartersIndex: {Index}", currentPrice, _priceService.DayQuartersIndex);
if (currentPrice == 0)
{
_logger.LogWarning("Current price is 0, which may indicate an issue with price retrieval");
}
var (_, boilerConfig) = UpdateCheapestIntervals();
var boilerConfig = _boilerConfigProvider.GetCurrentConfiguration();
UpdateCheapestIntervals(boilerConfig);
await UpdateEntitiesAsync(boilerConfig);
_logger.LogInformation("NordPool price initialized with current price: {CurrentPrice} {Unit}", _priceService.CurrentPrice, UnitOfMeasurement);
}
catch (Exception ex)
{
@@ -112,12 +104,10 @@ public class NordPoolInit : INordPoolInit
var currentMinute = now.Minute;
var currentSecond = now.Second;
var minutesUntilNext15 = 15 - (currentMinute % 15);
var minutesUntilNext15 = 15 - currentMinute % 15;
var delayUntilNext15 = TimeSpan.FromMinutes(minutesUntilNext15) - TimeSpan.FromSeconds(currentSecond);
var nextUpdateTime = now.Add(delayUntilNext15);
_logger.LogInformation("Scheduling first NordPool update at {Time} (in {Delay})", nextUpdateTime, delayUntilNext15);
_scheduler.RunEvery(TimeSpan.FromMinutes(15), nextUpdateTime, async void () =>
{
try
@@ -135,14 +125,10 @@ public class NordPoolInit : INordPoolInit
{
try
{
_logger.LogInformation("Starting periodic NordPool price update");
var cetTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
var nowCet = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, cetTimeZone);
var today = DateOnly.FromDateTime(nowCet);
_logger.LogDebug("Current CET time: {CetTime}, Today in CET: {Today}", nowCet, today);
if (_priceService.LastFetchedDate.HasValue && _priceService.LastFetchedDate.Value < today)
{
_priceService.RollOverPrices(today);
@@ -150,20 +136,15 @@ public class NordPoolInit : INordPoolInit
if (_priceService.ShouldFetchNewPrices(today))
{
_logger.LogInformation("Fetching new prices from NordPool API");
await _priceService.FetchPricesAsync();
}
else
{
_logger.LogDebug("Using cached prices, no need to fetch from API");
}
_priceService.UpdateCurrentPrice();
var (_, boilerConfig) = UpdateCheapestIntervals();
var boilerConfig = _boilerConfigProvider.GetCurrentConfiguration();
UpdateCheapestIntervals(boilerConfig);
await UpdateEntitiesAsync(boilerConfig);
_logger.LogInformation("NordPool prices updated successfully. Current price: {CurrentPrice} {Unit}", _priceService.CurrentPrice, UnitOfMeasurement);
}
catch (Exception ex)
{
@@ -176,9 +157,8 @@ public class NordPoolInit : INordPoolInit
await _entityService.CleanupEntitiesAsync(cancellationToken);
}
private (CheapestIntervalsUpdateResult Result, BoilerConfig Config) UpdateCheapestIntervals()
private void UpdateCheapestIntervals(BoilerConfig config)
{
var config = _boilerConfigReader.ReadConfig();
var effectivePriceCap = config.SkipPriceCap ? double.MaxValue : config.PriceCap;
var effectiveIntervalCount = config.SkipPriceCap ? NordPoolConsts.MaxDailyIntervals : config.IntervalCount;
@@ -188,31 +168,17 @@ public class NordPoolInit : INordPoolInit
{
_logger.LogDebug("No today prices available, skipping cheapest intervals calculation");
CheapestIntervals = [];
return (new CheapestIntervalsUpdateResult
{
IntervalCount = config.IntervalCount,
PriceCap = config.PriceCap,
SkipPriceCap = config.SkipPriceCap
}, config);
return;
}
CheapestIntervals = _cheapestIntervalsFinder.FindCheapestIntervals(_priceService.TodayNordPoolPrice, effectiveIntervalCount, effectivePriceCap, config.Deadline);
_logger.LogInformation("Cheapest intervals updated: {Count} intervals (config: {Hours}h / {Intervals} intervals, cap: {Cap}, skipPriceCap: {Skip}, deadline: {Deadline})",
CheapestIntervals.Count, config.IntervalCount / 4.0, effectiveIntervalCount, effectivePriceCap, config.SkipPriceCap, config.Deadline);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error calculating cheapest intervals");
CheapestIntervals = [];
}
return (new CheapestIntervalsUpdateResult
{
IntervalCount = config.IntervalCount,
PriceCap = config.PriceCap,
SkipPriceCap = config.SkipPriceCap
}, config);
}
private async Task UpdateEntitiesAsync(BoilerConfig boilerConfig)
@@ -225,8 +191,7 @@ public class NordPoolInit : INordPoolInit
var configuredHours = (double)boilerConfig.IntervalCount / NordPoolConsts.IntervalsPerHour;
var configuredReadyBy = boilerConfig.Deadline.TimeOfDay.ToString(@"hh\:mm", CultureInfo.InvariantCulture);
var isNowCheap = CheapestIntervals != null &&
_cheapestIntervalsFinder.IsCurrentIntervalCheap(CheapestIntervals, currentDateTime);
var isNowCheap = CheapestIntervals != null && _cheapestIntervalsFinder.IsCurrentIntervalCheap(CheapestIntervals, currentDateTime);
var nextCheapInterval = CheapestIntervals?
.Where(i => i.Start > currentDateTime)
.OrderBy(i => i.Start)
+36 -35
View File
@@ -29,28 +29,17 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
if (TodayNordPoolPrice?.Prices == null || TodayNordPoolPrice.Prices.Count == 0)
{
logger.LogInformation("Fetching today's prices from API for CET date: {Today}", today);
TodayNordPoolPrice = await GetNordPoolPriceAsync(today);
}
else
{
logger.LogDebug("Using existing today's prices (already have {Count} prices)", TodayNordPoolPrice.Prices.Count);
TodayNordPoolPrice = await FetchPricesForDateWithRetryAsync(today, "today");
}
if (TomorrowNordPoolPrice?.Prices == null || TomorrowNordPoolPrice.Prices.Count == 0)
{
logger.LogInformation("Fetching tomorrow's prices from API for CET date: {Tomorrow}", today.AddDays(1));
TomorrowNordPoolPrice = await GetNordPoolPriceAsync(today.AddDays(1));
}
else
{
logger.LogDebug("Already have tomorrow's prices ({Count} prices)", TomorrowNordPoolPrice.Prices.Count);
TomorrowNordPoolPrice = await FetchPricesForDateWithRetryAsync(today.AddDays(1), "tomorrow");
}
LastUpdatedDate = DateTime.UtcNow;
LastFetchedDate = today;
logger.LogInformation("Prices ready for today ({Today}). Today prices count: {TodayCount}, Tomorrow prices count: {TomorrowCount}",
today, TodayNordPoolPrice?.Prices?.Count ?? 0, TomorrowNordPoolPrice?.Prices?.Count ?? 0);
}
public double UpdateCurrentPrice()
@@ -68,7 +57,6 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
if (price.HasValue)
{
CurrentPrice = price.Value;
logger.LogInformation("Current price updated to: {Price} for quarter index {Index}", CurrentPrice, index);
}
else
{
@@ -82,8 +70,6 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
DayQuartersIndex = index;
}
logger.LogDebug("Returning current price: {Price}", CurrentPrice);
return CurrentPrice;
}
@@ -92,22 +78,16 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
{
if (!LastFetchedDate.HasValue)
{
logger.LogDebug("No cached prices, need to fetch");
return true;
}
if (LastFetchedDate.Value < today)
{
logger.LogDebug("New day detected, need to fetch fresh prices");
return true;
}
if (TodayNordPoolPrice?.Prices == null || TodayNordPoolPrice.Prices.Count == 0)
{
logger.LogDebug("Today's prices are missing, need to fetch");
return true;
}
@@ -117,8 +97,6 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
if (currentHour >= 13)
{
logger.LogDebug("Checking for tomorrow's prices (after 13:00)");
return true;
}
}
@@ -128,26 +106,48 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
public void RollOverPrices(DateOnly today)
{
logger.LogInformation("New day detected in CET timezone! Rolling over tomorrow's prices to today. Previous date: {PreviousDate}, Current date: {CurrentDate}", LastFetchedDate, today);
if (TomorrowNordPoolPrice?.Prices is { Count: > 0 })
{
TodayNordPoolPrice = TomorrowNordPoolPrice;
logger.LogInformation("Moved tomorrow's prices ({Count} prices) to today", TodayNordPoolPrice?.Prices?.Count ?? 0);
}
else
{
TodayNordPoolPrice = new NordPoolPrice();
logger.LogWarning("Tomorrow's prices were not available during rollover, clearing stale today's prices to trigger re-fetch");
}
TomorrowNordPoolPrice = null;
logger.LogInformation("Cleared tomorrow's prices");
DayQuartersIndex = -1;
LastFetchedDate = today;
}
private async Task<NordPoolPrice> FetchPricesForDateWithRetryAsync(DateOnly date, string label)
{
for (var attempt = 1; attempt <= NordPoolConsts.MaxFetchRetryAttempts; attempt++)
{
try
{
return await GetNordPoolPriceAsync(date);
}
catch (InvalidOperationException ex) when (attempt < NordPoolConsts.MaxFetchRetryAttempts)
{
var delay = TimeSpan.FromSeconds(NordPoolConsts.RetryBaseDelaySeconds * Math.Pow(2, attempt - 1));
logger.LogWarning(ex, "Attempt {Attempt}/{MaxAttempts} to fetch {Label} prices for {Date} failed. Retrying in {Delay}", attempt, NordPoolConsts.MaxFetchRetryAttempts, label, date, delay);
await Task.Delay(delay);
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to fetch {Label} prices for {Date} on attempt {Attempt} with unexpected error", label, date, attempt);
break;
}
}
logger.LogWarning("All {MaxAttempts} attempts to fetch {Label} prices for {Date} exhausted; returning empty prices", NordPoolConsts.MaxFetchRetryAttempts, label, date);
return new NordPoolPrice();
}
private async Task<NordPoolPrice> GetNordPoolPriceAsync(DateOnly date)
{
var nordPoolPricesDto = await _nordPoolServices.GetPricesForDateAsync(
@@ -160,7 +160,7 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
});
var nordPoolResult = ParseNordPoolResult(nordPoolPricesDto);
return AdjustedNordPoolPrice(nordPoolResult);
}
@@ -211,11 +211,12 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
return Math.Round(cntPrice, ConversionConsts.PriceDecimalPlaces);
}
internal static int GetTimeQuarterIndex(DateTime date)
internal static int GetTimeQuarterIndex(DateTime utcDate)
{
var relativeHour = (date.Hour + 1) % 24;
var totalMinutes = (relativeHour * 60) + date.Minute;
return totalMinutes / 15;
var cetTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
var cetDate = TimeZoneInfo.ConvertTimeFromUtc(utcDate, cetTimeZone);
var totalMinutes = (cetDate.Hour * 60) + cetDate.Minute;
return totalMinutes / NordPoolConsts.MinutesPerInterval;
}
}