Files
HomeAssistant/NordPool.Manager/NordPoolPriceService.cs
T
gitea_admin 41ac93733e Clear Qodana findings in monitor runtime code
- Guard logger calls with IsEnabled so value-type arguments are not boxed
  when the level is disabled
- Make helper members static, narrow write-only properties to init or
  private get, and delete members no call site reaches
- Flatten nested conditionals and convert if/else chains into switch and
  ternary form
- Drop the unused *MonitorInit interfaces; NetDaemon instantiates the
  concrete app classes
- Drop the unused IConfiguration parameter from AddNordPool and
  AddPowerMonitor, and the unused IEntityManager.CreateEntitiesAsync
- Remove the ignored parameters of the boiler run-time tracker stub
- Pin the NordPool DTO price mapping explicitly so the getter use is
  visible to static analysis
- Fail Qodana on any finding and record the registration changes in
  AGENTS.md
2026-11-29 21:42:47 +02:00

233 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.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))
{
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 (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");
}
LastUpdatedDate = DateTime.UtcNow;
LastFetchedDate = today;
}
public void UpdateCurrentPrice()
{
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);
}
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);
}
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 is { Count: > 0 })
{
return false;
}
var currentHour = DateTime.Now.Hour;
return currentHour >= 13;
}
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 static NordPoolPrice AdjustedNordPoolPrice(NordPoolPrice todayNordPoolPrice)
{
var recalculatedPrice = new NordPoolPrice
{
Prices = new List<NordPoolDayPrice>()
};
if (todayNordPoolPrice.Prices is null)
{
return recalculatedPrice;
}
foreach (var price in todayNordPoolPrice.Prices)
{
if (price.Price is null)
{
continue;
}
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;
}
}