Apply code formatting cleanup across monitor projects
- Reindent appsettings.json and the MSBuild project files - Collapse single-statement guard blocks and tidy using and member order - Normalize XML doc indentation and file endings - Reorder BatteryMonitor test-data helpers and move the exclusion tests into their own region - Carry the same formatting through the boiler config, control, entity and test files
This commit is contained in:
@@ -6,19 +6,20 @@ namespace NordPoolManager;
|
||||
|
||||
public class CheapestIntervalsFinder(ILogger<CheapestIntervalsFinder> logger) : ICheapestIntervalsFinder
|
||||
{
|
||||
public IReadOnlyList<CheapestIntervalResult> FindCheapestIntervals(NordPoolPrice prices, int numberOfIntervals, double priceCap, DateTime deadline)
|
||||
public IReadOnlyList<CheapestIntervalResult> FindCheapestIntervals(NordPoolPrice prices, int numberOfIntervals,
|
||||
double priceCap, DateTime deadline)
|
||||
{
|
||||
if (prices.Prices is not { Count: > 0 })
|
||||
{
|
||||
logger.LogWarning("No prices available for cheapest interval calculation");
|
||||
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
if (numberOfIntervals <= 0)
|
||||
{
|
||||
logger.LogWarning("Number of intervals requested is {Count}, returning empty", numberOfIntervals);
|
||||
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
@@ -49,4 +50,4 @@ public class CheapestIntervalsFinder(ILogger<CheapestIntervalsFinder> logger) :
|
||||
{
|
||||
return cheapestIntervals.Any(interval => utcNow >= interval.Start && utcNow < interval.End);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,8 @@ namespace NordPoolManager.Interface;
|
||||
|
||||
public interface ICheapestIntervalsFinder
|
||||
{
|
||||
IReadOnlyList<CheapestIntervalResult> FindCheapestIntervals(NordPoolPrice prices, int numberOfIntervals, double priceCap, DateTime deadline);
|
||||
IReadOnlyList<CheapestIntervalResult> FindCheapestIntervals(NordPoolPrice prices, int numberOfIntervals,
|
||||
double priceCap, DateTime deadline);
|
||||
|
||||
bool IsCurrentIntervalCheap(IReadOnlyList<CheapestIntervalResult> cheapestIntervals, DateTime utcNow);
|
||||
}
|
||||
}
|
||||
@@ -3,9 +3,9 @@ using BoilerMonitor.Models;
|
||||
namespace NordPoolManager.Interface;
|
||||
|
||||
/// <summary>
|
||||
/// Supplies boiler scheduling configuration for NordPool cheapest-interval logic.
|
||||
/// Supplies boiler scheduling configuration for NordPool cheapest-interval logic.
|
||||
/// </summary>
|
||||
public interface INordPoolBoilerConfigProvider
|
||||
{
|
||||
BoilerConfig GetCurrentConfiguration();
|
||||
}
|
||||
}
|
||||
@@ -8,4 +8,4 @@ public interface INordPoolEntityService
|
||||
Task ResetEntitiesAsync(CancellationToken cancellationToken = default);
|
||||
Task UpdateEntitiesAsync(EntityUpdateContext context, CancellationToken cancellationToken = default);
|
||||
Task CleanupEntitiesAsync(CancellationToken cancellationToken = default);
|
||||
}
|
||||
}
|
||||
@@ -16,4 +16,4 @@ public interface INordPoolPriceService
|
||||
double GetCurrentPrice();
|
||||
bool ShouldFetchNewPrices(DateOnly today);
|
||||
void RollOverPrices(DateOnly today);
|
||||
}
|
||||
}
|
||||
@@ -19,4 +19,4 @@ public record EntityUpdateContext
|
||||
public required string? ConfiguredReadyBy { get; init; }
|
||||
public required bool IsNowCheap { get; init; }
|
||||
public required DateTime? NextCheapIntervalStart { get; init; }
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@ public sealed class NordPoolOptions
|
||||
public const string SectionName = "NordPool";
|
||||
|
||||
/// <summary>
|
||||
/// When true, removes existing NordPool MQTT entities before recreating them on app startup.
|
||||
/// When true, removes existing NordPool MQTT entities before recreating them on app startup.
|
||||
/// </summary>
|
||||
public bool CleanupEntitiesOnStartup { get; init; } = true;
|
||||
}
|
||||
}
|
||||
@@ -8,22 +8,22 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
|
||||
<_Parameter1>NordPool.Manager.Tests</_Parameter1>
|
||||
</AssemblyAttribute>
|
||||
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
|
||||
<_Parameter1>NordPool.Manager.Tests</_Parameter1>
|
||||
</AssemblyAttribute>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\BoilerMonitor.Models\BoilerMonitor.Models.csproj" />
|
||||
<ProjectReference Include="..\HomeAssistant.Entities\HomeAssistant.Entities.csproj" />
|
||||
<ProjectReference Include="..\NordPool.Models\NordPool.Models.csproj" />
|
||||
<ProjectReference Include="..\BoilerMonitor.Models\BoilerMonitor.Models.csproj"/>
|
||||
<ProjectReference Include="..\HomeAssistant.Entities\HomeAssistant.Entities.csproj"/>
|
||||
<ProjectReference Include="..\NordPool.Models\NordPool.Models.csproj"/>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<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" />
|
||||
<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>
|
||||
|
||||
@@ -4,9 +4,12 @@ using NordPoolManager.Interface;
|
||||
namespace NordPoolManager;
|
||||
|
||||
/// <summary>
|
||||
/// Resolves boiler configuration from Home Assistant state for NordPool scheduling.
|
||||
/// Resolves boiler configuration from Home Assistant state for NordPool scheduling.
|
||||
/// </summary>
|
||||
public sealed class NordPoolBoilerConfigProvider(IBoilerConfigReader boilerConfigReader) : INordPoolBoilerConfigProvider
|
||||
{
|
||||
public BoilerConfig GetCurrentConfiguration() => boilerConfigReader.ReadConfig();
|
||||
}
|
||||
public BoilerConfig GetCurrentConfiguration()
|
||||
{
|
||||
return boilerConfigReader.ReadConfig();
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,8 @@ using NordPoolManager.Models;
|
||||
|
||||
namespace NordPoolManager;
|
||||
|
||||
public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<NordPoolEntityService> logger) : INordPoolEntityService
|
||||
public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<NordPoolEntityService> logger)
|
||||
: INordPoolEntityService
|
||||
{
|
||||
private const string LastUpdateTimeEntityId = "sensor.nordpool_last_update_time";
|
||||
private const string TodayPricesEntityId = "sensor.nordpool_today_prices";
|
||||
@@ -51,7 +52,7 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
|
||||
public async Task ResetEntitiesAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
|
||||
await Task.WhenAll(
|
||||
ResetLastUpdateTimeAsync(),
|
||||
ResetCurrentPriceAsync(),
|
||||
@@ -63,6 +64,59 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
|
||||
).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async Task UpdateEntitiesAsync(EntityUpdateContext ctx, CancellationToken cancellationToken = default)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
var utcNow = DateTime.UtcNow;
|
||||
var timestamp = utcNow.ToString("O");
|
||||
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;
|
||||
var mergedPrices = MergeTodayTomorrowPrices(ctx.TodayNordPoolPrice, ctx.TomorrowNordPoolPrice);
|
||||
|
||||
if (mergedPrices.Count > NordPoolConsts.MaxExpectedPriceEntries)
|
||||
logger.LogWarning(
|
||||
"Merged price count ({Count}) exceeds expected maximum ({Max}). Attribute payload may be oversized",
|
||||
mergedPrices.Count, NordPoolConsts.MaxExpectedPriceEntries);
|
||||
|
||||
var cheapestCount = ctx.CheapestIntervals?.Count ?? 0;
|
||||
|
||||
if (logger.IsEnabled(LogLevel.Information))
|
||||
logger.LogInformation(
|
||||
"Updating sensor.nordpool_cheapest_intervals with {Count} intervals, is_now_cheap={IsNow}",
|
||||
cheapestCount, ctx.IsNowCheap);
|
||||
|
||||
var updateTasks = new[]
|
||||
{
|
||||
UpdateLastUpdateTimeAsync(updateTimeState),
|
||||
UpdateCurrentPriceAsync(priceValue, ctx, timestamp),
|
||||
UpdateTodayPricesAsync(ctx, todayPricesCount, timestamp),
|
||||
UpdateTomorrowPricesAsync(ctx, tomorrowPricesCount, timestamp),
|
||||
UpdateTodayTomorrowPricesAsync(mergedPrices, updateTimeState, timestamp),
|
||||
UpdateCheapestIntervalsAsync(ctx, cheapestCount, timestamp)
|
||||
};
|
||||
|
||||
await Task.WhenAll(updateTasks).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
try
|
||||
{
|
||||
var removeTasks = AllEntityIds.Select(entityManager.RemoveEntity);
|
||||
await Task.WhenAll(removeTasks).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Error cleaning up NordPool entities");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ResetLastUpdateTimeAsync()
|
||||
{
|
||||
await SetEntityStateSafe(LastUpdateTimeEntityId, "unknown").ConfigureAwait(false);
|
||||
@@ -149,43 +203,6 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
|
||||
}).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async Task UpdateEntitiesAsync(EntityUpdateContext ctx, CancellationToken cancellationToken = default)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
var utcNow = DateTime.UtcNow;
|
||||
var timestamp = utcNow.ToString("O");
|
||||
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;
|
||||
var mergedPrices = MergeTodayTomorrowPrices(ctx.TodayNordPoolPrice, ctx.TomorrowNordPoolPrice);
|
||||
|
||||
if (mergedPrices.Count > NordPoolConsts.MaxExpectedPriceEntries)
|
||||
{
|
||||
logger.LogWarning("Merged price count ({Count}) exceeds expected maximum ({Max}). Attribute payload may be oversized", mergedPrices.Count, NordPoolConsts.MaxExpectedPriceEntries);
|
||||
}
|
||||
|
||||
var cheapestCount = ctx.CheapestIntervals?.Count ?? 0;
|
||||
|
||||
if (logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
logger.LogInformation("Updating sensor.nordpool_cheapest_intervals with {Count} intervals, is_now_cheap={IsNow}", cheapestCount, ctx.IsNowCheap);
|
||||
}
|
||||
|
||||
var updateTasks = new[]
|
||||
{
|
||||
UpdateLastUpdateTimeAsync(updateTimeState),
|
||||
UpdateCurrentPriceAsync(priceValue, ctx, timestamp),
|
||||
UpdateTodayPricesAsync(ctx, todayPricesCount, timestamp),
|
||||
UpdateTomorrowPricesAsync(ctx, tomorrowPricesCount, timestamp),
|
||||
UpdateTodayTomorrowPricesAsync(mergedPrices, updateTimeState, timestamp),
|
||||
UpdateCheapestIntervalsAsync(ctx, cheapestCount, timestamp)
|
||||
};
|
||||
|
||||
await Task.WhenAll(updateTasks).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task UpdateLastUpdateTimeAsync(string updateTimeState)
|
||||
{
|
||||
await SetEntityStateSafe(LastUpdateTimeEntityId, updateTimeState).ConfigureAwait(false);
|
||||
@@ -229,7 +246,8 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
|
||||
}).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task UpdateTodayTomorrowPricesAsync(List<NordPoolDayPrice> mergedPrices, string updateTimeState, string timestamp)
|
||||
private async Task UpdateTodayTomorrowPricesAsync(List<NordPoolDayPrice> mergedPrices, string updateTimeState,
|
||||
string timestamp)
|
||||
{
|
||||
await SetEntityStateSafe(TodayTomorrowPricesEntityId, updateTimeState).ConfigureAwait(false);
|
||||
await SetEntityAttributesSafe(TodayTomorrowPricesEntityId, new
|
||||
@@ -260,22 +278,6 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
|
||||
}).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
try
|
||||
{
|
||||
var removeTasks = AllEntityIds.Select(entityManager.RemoveEntity);
|
||||
await Task.WhenAll(removeTasks).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Error cleaning up NordPool entities");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
internal static ICollection<NordPoolEntity> GetInitEntitiesList(string? unitOfMeasurement)
|
||||
{
|
||||
const string currentPriceEntityId = NordPoolConsts.CurrentPriceEntityId;
|
||||
@@ -344,4 +346,4 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
|
||||
logger.LogError(ex, "Failed to set attributes for {EntityId}", entityId);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,19 +17,16 @@ namespace NordPoolManager;
|
||||
[NetDaemonApp]
|
||||
public class NordPoolInit
|
||||
{
|
||||
private readonly ILogger<NordPoolInit> _logger;
|
||||
private readonly IHaContext _haContext;
|
||||
private readonly INordPoolPriceService _priceService;
|
||||
private readonly INordPoolEntityService _entityService;
|
||||
private readonly ICheapestIntervalsFinder _cheapestIntervalsFinder;
|
||||
private readonly INordPoolBoilerConfigProvider _boilerConfigProvider;
|
||||
private readonly IScheduler _scheduler;
|
||||
private readonly ICheapestIntervalsFinder _cheapestIntervalsFinder;
|
||||
private readonly INordPoolEntityService _entityService;
|
||||
private readonly IHaContext _haContext;
|
||||
private readonly ILogger<NordPoolInit> _logger;
|
||||
private readonly NordPoolOptions _options;
|
||||
private readonly INordPoolPriceService _priceService;
|
||||
private readonly IScheduler _scheduler;
|
||||
private readonly TimeProvider _timeProvider;
|
||||
|
||||
private string? UnitOfMeasurement { get; }
|
||||
private IReadOnlyList<CheapestIntervalResult>? CheapestIntervals { get; set; }
|
||||
|
||||
public NordPoolInit(
|
||||
Entities entities,
|
||||
IHaContext haContext,
|
||||
@@ -57,22 +54,22 @@ public class NordPoolInit
|
||||
|
||||
_ = InitializeAndScheduleAsync();
|
||||
}
|
||||
|
||||
|
||||
private string? UnitOfMeasurement { get; }
|
||||
private IReadOnlyList<CheapestIntervalResult>? CheapestIntervals { get; set; }
|
||||
|
||||
public async Task InitializeAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromSeconds(3));
|
||||
|
||||
if (_options.CleanupEntitiesOnStartup)
|
||||
{
|
||||
await _entityService.CleanupEntitiesAsync();
|
||||
}
|
||||
if (_options.CleanupEntitiesOnStartup) await _entityService.CleanupEntitiesAsync();
|
||||
|
||||
await _entityService.CreateEntitiesAsync(UnitOfMeasurement);
|
||||
await _entityService.ResetEntitiesAsync();
|
||||
await Task.Delay(TimeSpan.FromSeconds(10));
|
||||
|
||||
|
||||
await UpdatePricesAsync();
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -81,7 +78,7 @@ public class NordPoolInit
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private async Task InitializeAndScheduleAsync()
|
||||
{
|
||||
try
|
||||
@@ -118,14 +115,9 @@ public class NordPoolInit
|
||||
var today = DateOnly.FromDateTime(nowCet);
|
||||
|
||||
if (_priceService.LastFetchedDate.HasValue && _priceService.LastFetchedDate.Value < today)
|
||||
{
|
||||
_priceService.RollOverPrices(today);
|
||||
}
|
||||
|
||||
if (_priceService.ShouldFetchNewPrices(today))
|
||||
{
|
||||
await _priceService.FetchPricesAsync();
|
||||
}
|
||||
if (_priceService.ShouldFetchNewPrices(today)) await _priceService.FetchPricesAsync();
|
||||
|
||||
_priceService.UpdateCurrentPrice();
|
||||
|
||||
@@ -161,11 +153,12 @@ public class NordPoolInit
|
||||
{
|
||||
_logger.LogDebug("No today prices available, skipping cheapest intervals calculation");
|
||||
CheapestIntervals = [];
|
||||
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
CheapestIntervals = _cheapestIntervalsFinder.FindCheapestIntervals(_priceService.TodayNordPoolPrice, effectiveIntervalCount, effectivePriceCap, config.Deadline);
|
||||
CheapestIntervals = _cheapestIntervalsFinder.FindCheapestIntervals(_priceService.TodayNordPoolPrice,
|
||||
effectiveIntervalCount, effectivePriceCap, config.Deadline);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -183,8 +176,9 @@ public class NordPoolInit
|
||||
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)
|
||||
@@ -211,4 +205,4 @@ public class NordPoolInit
|
||||
|
||||
await _entityService.UpdateEntitiesAsync(context);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,8 @@ using NordPoolManager.Models.Consts;
|
||||
|
||||
namespace NordPoolManager;
|
||||
|
||||
public class NordPoolPriceService(Services services, IMapper mapper, ILogger<NordPoolPriceService> logger) : INordPoolPriceService
|
||||
public class NordPoolPriceService(Services services, IMapper mapper, ILogger<NordPoolPriceService> logger)
|
||||
: INordPoolPriceService
|
||||
{
|
||||
private readonly NordpoolServices _nordPoolServices = services.Nordpool;
|
||||
|
||||
@@ -29,19 +30,16 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
|
||||
if ((TodayNordPoolPrice?.Prices == null || TodayNordPoolPrice.Prices.Count == 0) && ShouldFetchNewPrices(today))
|
||||
{
|
||||
if (logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
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) && ShouldFetchNewPrices(today.AddDays(1)))
|
||||
if ((TomorrowNordPoolPrice?.Prices == null || TomorrowNordPoolPrice.Prices.Count == 0) &&
|
||||
ShouldFetchNewPrices(today.AddDays(1)))
|
||||
{
|
||||
if (logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
logger.LogInformation("Fetching tomorrow's prices from API for CET date: {Tomorrow}", today.AddDays(1));
|
||||
}
|
||||
|
||||
TomorrowNordPoolPrice = await FetchPricesForDateWithRetryAsync(today.AddDays(1), "tomorrow");
|
||||
}
|
||||
@@ -55,31 +53,24 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
|
||||
var index = GetTimeQuarterIndex(DateTime.UtcNow);
|
||||
|
||||
if (logger.IsEnabled(LogLevel.Debug))
|
||||
{
|
||||
logger.LogDebug("Current time quarter index: {Index}, Total prices available: {Count}", index, TodayNordPoolPrice?.Prices?.Count ?? 0);
|
||||
}
|
||||
logger.LogDebug("Current time quarter index: {Index}, Total prices available: {Count}", index,
|
||||
TodayNordPoolPrice?.Prices?.Count ?? 0);
|
||||
|
||||
if (DayQuartersIndex == index)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (DayQuartersIndex == index) return;
|
||||
|
||||
if (TodayNordPoolPrice?.Prices != null && TodayNordPoolPrice.Prices.Count > index)
|
||||
{
|
||||
var price = TodayNordPoolPrice.Prices[index].Price;
|
||||
|
||||
if (price.HasValue)
|
||||
{
|
||||
CurrentPrice = price.Value;
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.LogWarning("Price at index {Index} is null", index);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.LogWarning("Cannot get price for index {Index}. Prices is null: {IsNull}, Prices count: {Count}", index, TodayNordPoolPrice?.Prices == null, TodayNordPoolPrice?.Prices?.Count ?? 0);
|
||||
logger.LogWarning("Cannot get price for index {Index}. Prices is null: {IsNull}, Prices count: {Count}",
|
||||
index, TodayNordPoolPrice?.Prices == null, TodayNordPoolPrice?.Prices?.Count ?? 0);
|
||||
}
|
||||
|
||||
DayQuartersIndex = index;
|
||||
@@ -92,25 +83,13 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
|
||||
|
||||
public bool ShouldFetchNewPrices(DateOnly today)
|
||||
{
|
||||
if (!LastFetchedDate.HasValue)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
if (!LastFetchedDate.HasValue) return true;
|
||||
|
||||
if (LastFetchedDate.Value < today)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
if (LastFetchedDate.Value < today) return true;
|
||||
|
||||
if (TodayNordPoolPrice?.Prices == null || TodayNordPoolPrice.Prices.Count == 0)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
if (TodayNordPoolPrice?.Prices == null || TodayNordPoolPrice.Prices.Count == 0) return true;
|
||||
|
||||
if (TomorrowNordPoolPrice?.Prices is { Count: > 0 })
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (TomorrowNordPoolPrice?.Prices is { Count: > 0 }) return false;
|
||||
|
||||
var currentHour = DateTime.Now.Hour;
|
||||
|
||||
@@ -119,7 +98,9 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
|
||||
|
||||
public void RollOverPrices(DateOnly today)
|
||||
{
|
||||
TodayNordPoolPrice = TomorrowNordPoolPrice?.Prices is { Count: > 0 } ? TomorrowNordPoolPrice : new NordPoolPrice();
|
||||
TodayNordPoolPrice = TomorrowNordPoolPrice?.Prices is { Count: > 0 }
|
||||
? TomorrowNordPoolPrice
|
||||
: new NordPoolPrice();
|
||||
|
||||
TomorrowNordPoolPrice = null;
|
||||
|
||||
@@ -130,7 +111,6 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
|
||||
private async Task<NordPoolPrice> FetchPricesForDateWithRetryAsync(DateOnly date, string label)
|
||||
{
|
||||
for (var attempt = 1; attempt <= NordPoolConsts.MaxFetchRetryAttempts; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await GetNordPoolPriceAsync(date);
|
||||
@@ -138,18 +118,23 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
|
||||
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);
|
||||
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);
|
||||
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);
|
||||
logger.LogWarning(
|
||||
"All {MaxAttempts} attempts to fetch {Label} prices for {Date} exhausted; returning empty prices",
|
||||
NordPoolConsts.MaxFetchRetryAttempts, label, date);
|
||||
|
||||
return new NordPoolPrice();
|
||||
}
|
||||
@@ -172,14 +157,13 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
|
||||
|
||||
internal NordPoolPrice ParseNordPoolResult(JsonElement? element)
|
||||
{
|
||||
if (element == null)
|
||||
{
|
||||
return new NordPoolPrice();
|
||||
}
|
||||
if (element == null) return new NordPoolPrice();
|
||||
|
||||
var priceResult = element.Value.Deserialize<NordPoolPriceResultDto>();
|
||||
|
||||
return priceResult != null ? mapper.Map<NordPoolPriceResultDto, NordPoolPrice>(priceResult) : new NordPoolPrice();
|
||||
return priceResult != null
|
||||
? mapper.Map<NordPoolPriceResultDto, NordPoolPrice>(priceResult)
|
||||
: new NordPoolPrice();
|
||||
}
|
||||
|
||||
internal static NordPoolPrice AdjustedNordPoolPrice(NordPoolPrice todayNordPoolPrice)
|
||||
@@ -189,17 +173,11 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
|
||||
Prices = new List<NordPoolDayPrice>()
|
||||
};
|
||||
|
||||
if (todayNordPoolPrice.Prices is null)
|
||||
{
|
||||
return recalculatedPrice;
|
||||
}
|
||||
if (todayNordPoolPrice.Prices is null) return recalculatedPrice;
|
||||
|
||||
foreach (var price in todayNordPoolPrice.Prices)
|
||||
{
|
||||
if (price.Price is null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if (price.Price is null) continue;
|
||||
|
||||
recalculatedPrice.Prices.Add(new NordPoolDayPrice
|
||||
{
|
||||
@@ -229,4 +207,4 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
|
||||
|
||||
return totalMinutes / NordPoolConsts.MinutesPerInterval;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user