Add shared test data builders and Qodana configuration

- Extract per-monitor *TestData helper classes and rework tests to use them
- Add boiler run-time tracker abstraction (implementation pending)
- Drop unused NordPool init/update-result types and stale PLAN.md
- Add qodana.yaml with the inspection set to keep the analysis focused
This commit is contained in:
2026-11-29 21:30:13 +02:00
parent 1152462765
commit 5777e641f6
79 changed files with 7162 additions and 3196 deletions
@@ -1,7 +0,0 @@
namespace NordPoolManager.Interface;
public interface INordPoolInit
{
Task InitializeAsync();
Task CleanupEntitiesAsync(CancellationToken cancellationToken = default);
}
@@ -12,7 +12,8 @@ public interface INordPoolPriceService
DateOnly? LastFetchedDate { get; }
Task FetchPricesAsync();
double UpdateCurrentPrice();
void UpdateCurrentPrice();
double GetCurrentPrice();
bool ShouldFetchNewPrices(DateOnly today);
void RollOverPrices(DateOnly today);
}
@@ -1,11 +0,0 @@
namespace NordPoolManager.Models;
/// <summary>
/// Result of updating cheapest intervals, containing the effective configuration used for the update.
/// </summary>
public class CheapestIntervalsUpdateResult
{
public int IntervalCount { get; init; }
public double PriceCap { get; init; }
public bool SkipPriceCap { get; init; }
}
+4 -4
View File
@@ -20,10 +20,10 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="AutoMapper" Version="16.1.1" />
<PackageReference Include="Microsoft.Extensions.Options" Version="10.0.5" />
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.11.0" />
<PackageReference Include="NetDaemon.HassModel" Version="26.11.0" />
<PackageReference Include="AutoMapper" Version="17.0.0" />
<PackageReference Include="Microsoft.Extensions.Options" Version="11.0.0" />
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.43.1" />
<PackageReference Include="NetDaemon.HassModel" Version="26.43.1" />
</ItemGroup>
</Project>
+3 -3
View File
@@ -155,7 +155,7 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
var utcNow = DateTime.UtcNow;
var timestamp = utcNow.ToString("O");
var updateTimeState = utcNow.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss");
var updateTimeState = utcNow.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
var priceValue = ctx.CurrentPrice.ToString("F2", CultureInfo.InvariantCulture);
var todayPricesCount = ctx.TodayNordPoolPrice?.Prices?.Count ?? 0;
var tomorrowPricesCount = ctx.TomorrowNordPoolPrice?.Prices?.Count ?? 0;
@@ -198,7 +198,7 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
state_class = "measurement",
friendly_name = "NordPool current price",
last_updated = timestamp,
last_api_fetch = ctx.LastApiUpdateDate?.ToString("O"),
last_api_fetch = ctx.LastApiUpdateDate?.ToString("O", CultureInfo.InvariantCulture),
using_cached_data = ctx.UsingCachedData,
current_quarter_index = ctx.DayQuartersIndex
}).ConfigureAwait(false);
@@ -251,7 +251,7 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
configured_ready_by = ctx.ConfiguredReadyBy,
total_heating_minutes = cheapestCount * NordPoolConsts.MinutesPerInterval,
is_now_cheap = ctx.IsNowCheap,
next_cheap_interval = ctx.NextCheapIntervalStart?.ToString("O"),
next_cheap_interval = ctx.NextCheapIntervalStart?.ToString("O", CultureInfo.InvariantCulture),
friendly_name = "NordPool cheapest boiler intervals",
last_updated = timestamp
}).ConfigureAwait(false);
+29 -67
View File
@@ -15,7 +15,7 @@ using NordPoolManager.Models;
namespace NordPoolManager;
[NetDaemonApp]
public class NordPoolInit : INordPoolInit
public class NordPoolInit
{
private readonly ILogger<NordPoolInit> _logger;
private readonly IHaContext _haContext;
@@ -57,7 +57,31 @@ public class NordPoolInit : INordPoolInit
_ = InitializeAndScheduleAsync();
}
public async Task InitializeAsync()
{
try
{
await Task.Delay(TimeSpan.FromSeconds(3));
if (_options.CleanupEntitiesOnStartup)
{
await _entityService.CleanupEntitiesAsync();
}
await _entityService.CreateEntitiesAsync(UnitOfMeasurement);
await _entityService.ResetEntitiesAsync();
await Task.Delay(TimeSpan.FromSeconds(10));
await UpdatePricesAsync();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error initializing NordPool prices");
throw;
}
}
private async Task InitializeAndScheduleAsync()
{
try
@@ -72,41 +96,6 @@ public class NordPoolInit : INordPoolInit
}
}
public async Task InitializeAsync()
{
try
{
await Task.Delay(TimeSpan.FromSeconds(3));
await _priceService.FetchPricesAsync();
if (_options.CleanupEntitiesOnStartup)
{
await _entityService.CleanupEntitiesAsync();
}
await _entityService.CreateEntitiesAsync(UnitOfMeasurement);
await _entityService.ResetEntitiesAsync();
await Task.Delay(TimeSpan.FromSeconds(10));
var currentPrice = _priceService.UpdateCurrentPrice();
if (currentPrice == 0)
{
_logger.LogWarning("Current price is 0, which may indicate an issue with price retrieval");
}
var boilerConfig = _boilerConfigProvider.GetCurrentConfiguration();
UpdateCheapestIntervals(boilerConfig);
await UpdateEntitiesAsync(boilerConfig);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error initializing NordPool prices");
throw;
}
}
private void SchedulePeriodicUpdates()
{
var now = _timeProvider.GetLocalNow();
@@ -143,7 +132,6 @@ public class NordPoolInit : INordPoolInit
var boilerConfig = _boilerConfigProvider.GetCurrentConfiguration();
UpdateCheapestIntervals(boilerConfig);
await UpdateEntitiesAsync(boilerConfig);
}
catch (Exception ex)
{
@@ -158,36 +146,10 @@ public class NordPoolInit : INordPoolInit
.Subscribe(_ =>
{
_logger.LogInformation("Fetch prices button pressed, triggering manual NordPool price update");
Task.Run(HandleFetchPricesAsync);
Task.Run(UpdatePricesAsync);
});
}
private async Task HandleFetchPricesAsync()
{
try
{
_logger.LogInformation("Manual fetch: forcing fresh NordPool price retrieval");
await _priceService.FetchPricesAsync();
_priceService.UpdateCurrentPrice();
var boilerConfig = _boilerConfigProvider.GetCurrentConfiguration();
UpdateCheapestIntervals(boilerConfig);
await UpdateEntitiesAsync(boilerConfig);
_logger.LogInformation("Manual fetch and update completed");
}
catch (Exception ex)
{
_logger.LogError(ex, "Error during manual NordPool price fetch");
}
}
public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default)
{
await _entityService.CleanupEntitiesAsync(cancellationToken);
}
private void UpdateCheapestIntervals(BoilerConfig config)
{
var effectivePriceCap = config.SkipPriceCap ? double.MaxValue : config.PriceCap;
@@ -215,14 +177,14 @@ public class NordPoolInit : INordPoolInit
private async Task UpdateEntitiesAsync(BoilerConfig boilerConfig)
{
var cetTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
var nowCet = TimeZoneInfo.ConvertTime(_timeProvider.GetUtcNow(), cetTimeZone).DateTime;
var todayCet = DateOnly.FromDateTime(nowCet);
var currentDateTime = nowCet;
var currentDateTime = TimeZoneInfo.ConvertTime(_timeProvider.GetUtcNow(), cetTimeZone).DateTime;
var todayCet = DateOnly.FromDateTime(currentDateTime);
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 nextCheapInterval = CheapestIntervals?
.Where(i => i.Start > currentDateTime)
.OrderBy(i => i.Start)
+9 -13
View File
@@ -26,13 +26,13 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
var nowCet = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, cetTimeZone);
var today = DateOnly.FromDateTime(nowCet);
if (TodayNordPoolPrice?.Prices == null || TodayNordPoolPrice.Prices.Count == 0)
if ((TodayNordPoolPrice?.Prices == null || TodayNordPoolPrice.Prices.Count == 0) && ShouldFetchNewPrices(today))
{
logger.LogInformation("Fetching today's prices from API for CET date: {Today}", today);
TodayNordPoolPrice = await FetchPricesForDateWithRetryAsync(today, "today");
}
if (TomorrowNordPoolPrice?.Prices == null || TomorrowNordPoolPrice.Prices.Count == 0)
if ((TomorrowNordPoolPrice?.Prices == null || TomorrowNordPoolPrice.Prices.Count == 0) && ShouldFetchNewPrices(today.AddDays(1)))
{
logger.LogInformation("Fetching tomorrow's prices from API for CET date: {Tomorrow}", today.AddDays(1));
TomorrowNordPoolPrice = await FetchPricesForDateWithRetryAsync(today.AddDays(1), "tomorrow");
@@ -42,7 +42,7 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
LastFetchedDate = today;
}
public double UpdateCurrentPrice()
public void UpdateCurrentPrice()
{
var index = GetTimeQuarterIndex(DateTime.UtcNow);
@@ -70,7 +70,10 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
DayQuartersIndex = index;
}
}
public double GetCurrentPrice()
{
return CurrentPrice;
}
@@ -106,14 +109,7 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
public void RollOverPrices(DateOnly today)
{
if (TomorrowNordPoolPrice?.Prices is { Count: > 0 })
{
TodayNordPoolPrice = TomorrowNordPoolPrice;
}
else
{
TodayNordPoolPrice = new NordPoolPrice();
}
TodayNordPoolPrice = TomorrowNordPoolPrice?.Prices is { Count: > 0 } ? TomorrowNordPoolPrice : new NordPoolPrice();
TomorrowNordPoolPrice = null;
@@ -215,7 +211,7 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
{
var cetTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
var cetDate = TimeZoneInfo.ConvertTimeFromUtc(utcDate, cetTimeZone);
var totalMinutes = (cetDate.Hour * 60) + cetDate.Minute;
var totalMinutes = cetDate.Hour * 60 + cetDate.Minute;
return totalMinutes / NordPoolConsts.MinutesPerInterval;
}