223 lines
7.6 KiB
C#
223 lines
7.6 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;
|
|
|
|
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)
|
|
{
|
|
logger.LogInformation("Fetching today's prices from API for CET date: {Today}", today);
|
|
TodayNordPoolPrice = await GetNordPoolPriceAsync(today);
|
|
}
|
|
else
|
|
{
|
|
logger.LogDebug("Using existing today's prices (already have {Count} prices)", TodayNordPoolPrice.Prices.Count);
|
|
}
|
|
|
|
if (TomorrowNordPoolPrice?.Prices == null || TomorrowNordPoolPrice.Prices.Count == 0)
|
|
{
|
|
logger.LogInformation("Fetching tomorrow's prices from API for CET date: {Tomorrow}", today.AddDays(1));
|
|
TomorrowNordPoolPrice = await GetNordPoolPriceAsync(today.AddDays(1));
|
|
}
|
|
else
|
|
{
|
|
logger.LogDebug("Already have tomorrow's prices ({Count} prices)", TomorrowNordPoolPrice.Prices.Count);
|
|
}
|
|
|
|
LastUpdatedDate = DateTime.UtcNow;
|
|
LastFetchedDate = today;
|
|
|
|
logger.LogInformation(
|
|
"Prices ready for today ({Today}). Today prices count: {TodayCount}, Tomorrow prices count: {TomorrowCount}",
|
|
today, TodayNordPoolPrice?.Prices?.Count ?? 0, TomorrowNordPoolPrice?.Prices?.Count ?? 0);
|
|
}
|
|
|
|
public double 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;
|
|
logger.LogInformation("Current price updated to: {Price} for quarter index {Index}", CurrentPrice, index);
|
|
}
|
|
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;
|
|
}
|
|
|
|
logger.LogDebug("Returning current price: {Price}", CurrentPrice);
|
|
|
|
return CurrentPrice;
|
|
}
|
|
|
|
public bool ShouldFetchNewPrices(DateOnly today)
|
|
{
|
|
if (!LastFetchedDate.HasValue)
|
|
{
|
|
logger.LogDebug("No cached prices, need to fetch");
|
|
|
|
return true;
|
|
}
|
|
|
|
if (LastFetchedDate.Value < today)
|
|
{
|
|
logger.LogDebug("New day detected, need to fetch fresh prices");
|
|
|
|
return true;
|
|
}
|
|
|
|
if (TodayNordPoolPrice?.Prices == null || TodayNordPoolPrice.Prices.Count == 0)
|
|
{
|
|
logger.LogDebug("Today's prices are missing, need to fetch");
|
|
|
|
return true;
|
|
}
|
|
|
|
if (TomorrowNordPoolPrice?.Prices == null || TomorrowNordPoolPrice.Prices.Count == 0)
|
|
{
|
|
var currentHour = DateTime.Now.Hour;
|
|
|
|
if (currentHour >= 13)
|
|
{
|
|
logger.LogDebug("Checking for tomorrow's prices (after 13:00)");
|
|
|
|
return true;
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
public void RollOverPrices(DateOnly today)
|
|
{
|
|
logger.LogInformation("New day detected in CET timezone! Rolling over tomorrow's prices to today. Previous date: {PreviousDate}, Current date: {CurrentDate}", LastFetchedDate, today);
|
|
|
|
if (TomorrowNordPoolPrice?.Prices is { Count: > 0 })
|
|
{
|
|
TodayNordPoolPrice = TomorrowNordPoolPrice;
|
|
logger.LogInformation("Moved tomorrow's prices ({Count} prices) to today", TodayNordPoolPrice?.Prices?.Count ?? 0);
|
|
}
|
|
else
|
|
{
|
|
TodayNordPoolPrice = new NordPoolPrice();
|
|
logger.LogWarning("Tomorrow's prices were not available during rollover, clearing stale today's prices to trigger re-fetch");
|
|
}
|
|
|
|
TomorrowNordPoolPrice = null;
|
|
logger.LogInformation("Cleared tomorrow's prices");
|
|
|
|
DayQuartersIndex = -1;
|
|
LastFetchedDate = today;
|
|
}
|
|
|
|
internal 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 date)
|
|
{
|
|
var relativeHour = (date.Hour + 1) % 24;
|
|
var totalMinutes = (relativeHour * 60) + date.Minute;
|
|
|
|
return totalMinutes / 15;
|
|
}
|
|
}
|