Files
HomeAssistant/NordPool.Manager/CheapestIntervalsFinder.cs
T
Marius 861c344832 Init
2026-03-08 19:10:16 +02:00

69 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 double WaterReadyPowerThresholdWatts = 5.0;
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 < WaterReadyPowerThresholdWatts;
}
}