5777e641f6
- 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
219 lines
7.5 KiB
C#
219 lines
7.5 KiB
C#
using System.Text.Json;
|
|
using AutoMapper;
|
|
using HomeAssistantGenerated;
|
|
using Microsoft.Extensions.Logging;
|
|
using NordPool.Models;
|
|
using NordPool.Models.Dtos;
|
|
using NordPoolManager.Interface;
|
|
using NordPoolManager.Models.Consts;
|
|
|
|
namespace NordPoolManager;
|
|
|
|
public class NordPoolPriceService(Services services, IMapper mapper, ILogger<NordPoolPriceService> logger) : INordPoolPriceService
|
|
{
|
|
private readonly NordpoolServices _nordPoolServices = services.Nordpool;
|
|
|
|
public NordPoolPrice? TodayNordPoolPrice { get; internal set; }
|
|
public NordPoolPrice? TomorrowNordPoolPrice { get; internal set; }
|
|
public double CurrentPrice { get; internal set; }
|
|
public int DayQuartersIndex { get; internal set; } = -1;
|
|
public DateTime? LastUpdatedDate { get; private set; }
|
|
public DateOnly? LastFetchedDate { get; internal set; }
|
|
|
|
public async Task FetchPricesAsync()
|
|
{
|
|
var cetTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
|
|
var nowCet = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, cetTimeZone);
|
|
var today = DateOnly.FromDateTime(nowCet);
|
|
|
|
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) && 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");
|
|
}
|
|
|
|
LastUpdatedDate = DateTime.UtcNow;
|
|
LastFetchedDate = today;
|
|
}
|
|
|
|
public void UpdateCurrentPrice()
|
|
{
|
|
var index = GetTimeQuarterIndex(DateTime.UtcNow);
|
|
|
|
logger.LogDebug("Current time quarter index: {Index}, Total prices available: {Count}", index, TodayNordPoolPrice?.Prices?.Count ?? 0);
|
|
|
|
if (DayQuartersIndex != index)
|
|
{
|
|
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);
|
|
}
|
|
|
|
DayQuartersIndex = index;
|
|
}
|
|
}
|
|
|
|
public double GetCurrentPrice()
|
|
{
|
|
return CurrentPrice;
|
|
}
|
|
|
|
public bool ShouldFetchNewPrices(DateOnly today)
|
|
{
|
|
if (!LastFetchedDate.HasValue)
|
|
{
|
|
return true;
|
|
}
|
|
|
|
if (LastFetchedDate.Value < today)
|
|
{
|
|
return true;
|
|
}
|
|
|
|
if (TodayNordPoolPrice?.Prices == null || TodayNordPoolPrice.Prices.Count == 0)
|
|
{
|
|
return true;
|
|
}
|
|
|
|
if (TomorrowNordPoolPrice?.Prices == null || TomorrowNordPoolPrice.Prices.Count == 0)
|
|
{
|
|
var currentHour = DateTime.Now.Hour;
|
|
|
|
if (currentHour >= 13)
|
|
{
|
|
return true;
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
public void RollOverPrices(DateOnly today)
|
|
{
|
|
TodayNordPoolPrice = TomorrowNordPoolPrice?.Prices is { Count: > 0 } ? TomorrowNordPoolPrice : new NordPoolPrice();
|
|
|
|
TomorrowNordPoolPrice = null;
|
|
|
|
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(
|
|
new NordpoolGetPricesForDateParameters
|
|
{
|
|
Areas = "LT",
|
|
ConfigEntry = NordPoolConsts.ConfigEntry,
|
|
Currency = "EUR",
|
|
Date = date
|
|
});
|
|
|
|
var nordPoolResult = ParseNordPoolResult(nordPoolPricesDto);
|
|
|
|
return AdjustedNordPoolPrice(nordPoolResult);
|
|
}
|
|
|
|
internal NordPoolPrice ParseNordPoolResult(JsonElement? element)
|
|
{
|
|
if (element == null)
|
|
{
|
|
return new NordPoolPrice();
|
|
}
|
|
|
|
var priceResult = element.Value.Deserialize<NordPoolPriceResultDto>();
|
|
|
|
return priceResult != null ? mapper.Map<NordPoolPriceResultDto, NordPoolPrice>(priceResult) : new NordPoolPrice();
|
|
}
|
|
|
|
internal NordPoolPrice AdjustedNordPoolPrice(NordPoolPrice todayNordPoolPrice)
|
|
{
|
|
var recalculatedPrice = new NordPoolPrice
|
|
{
|
|
Prices = new List<NordPoolDayPrice>()
|
|
};
|
|
|
|
if (todayNordPoolPrice.Prices != null)
|
|
{
|
|
foreach (var price in todayNordPoolPrice.Prices)
|
|
{
|
|
if (price.Price != null)
|
|
{
|
|
recalculatedPrice.Prices.Add(new NordPoolDayPrice
|
|
{
|
|
Start = price.Start,
|
|
End = price.End,
|
|
Price = PriceCorrection(price.Price.Value)
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
return recalculatedPrice;
|
|
}
|
|
|
|
internal static double PriceCorrection(double mwPrice)
|
|
{
|
|
var kwPrice = mwPrice / ConversionConsts.MegawattToKilowattDivisor;
|
|
var kwhPrice = kwPrice * ConversionConsts.VatRate;
|
|
var cntPrice = kwhPrice * ConversionConsts.EuroToCentsMultiplier;
|
|
|
|
return Math.Round(cntPrice, ConversionConsts.PriceDecimalPlaces);
|
|
}
|
|
|
|
internal static int GetTimeQuarterIndex(DateTime utcDate)
|
|
{
|
|
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;
|
|
}
|
|
}
|