28eddc5dc0
- Introduced `CancellationToken` to service methods for improved task cancellation handling. - Centralized reusable constants (`MinutesPerInterval`, `WaterReadyPowerThresholdWatts`) in `NordPoolConsts`. - Refactored `ConfigureAwait` usage and improved logging within `NordPoolEntityService`. - Adjusted tests to accommodate cancellation token changes.
68 lines
2.3 KiB
C#
68 lines
2.3 KiB
C#
using Microsoft.Extensions.Logging;
|
|
using NordPool.Models;
|
|
using NordPoolManager.Interface;
|
|
|
|
namespace NordPoolManager;
|
|
|
|
public class CheapestIntervalsFinder(ILogger<CheapestIntervalsFinder> logger) : ICheapestIntervalsFinder
|
|
{
|
|
private const string SwitchOnState = "on";
|
|
|
|
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 [];
|
|
}
|
|
|
|
var eligible = prices.Prices
|
|
.AsParallel()
|
|
.Where(p => p is { Start: not null, End: not null, Price: not null })
|
|
.Where(p => p.End!.Value <= deadline)
|
|
.Where(p => p.Price!.Value <= priceCap)
|
|
.OrderBy(p => p.Price!.Value)
|
|
.ThenBy(p => p.Start!.Value)
|
|
.Take(numberOfIntervals)
|
|
.ToList();
|
|
|
|
var ranked = eligible
|
|
.Select((p, index) => new CheapestIntervalResult
|
|
{
|
|
Start = p.Start!.Value,
|
|
End = p.End!.Value,
|
|
Price = p.Price!.Value,
|
|
Rank = index + 1
|
|
})
|
|
.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;
|
|
}
|
|
|
|
public bool IsCurrentIntervalCheap(IReadOnlyList<CheapestIntervalResult> cheapestIntervals, DateTime utcNow)
|
|
{
|
|
return cheapestIntervals.AsParallel().Any(interval => utcNow >= interval.Start && utcNow < interval.End);
|
|
}
|
|
|
|
public bool IsWaterReady(string? switchState, double? powerWatts)
|
|
{
|
|
if (switchState == null || powerWatts == null)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
return string.Equals(switchState, SwitchOnState, StringComparison.OrdinalIgnoreCase) && powerWatts.Value < NordPoolConsts.WaterReadyPowerThresholdWatts;
|
|
}
|
|
}
|