Files
HomeAssistant/NordPool.Manager/NordPoolInit.cs
T

253 lines
9.0 KiB
C#

using System.Globalization;
using System.Reactive.Concurrency;
using BoilerMonitor.Models;
using HomeAssistantGenerated;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NetDaemon.AppModel;
using NetDaemon.Extensions.Scheduler;
using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
using NordPool.Models;
using NordPoolManager.Interface;
using NordPoolManager.Models;
namespace NordPoolManager;
[NetDaemonApp]
public class NordPoolInit : INordPoolInit
{
private readonly ILogger<NordPoolInit> _logger;
private readonly IHaContext _haContext;
private readonly INordPoolPriceService _priceService;
private readonly INordPoolEntityService _entityService;
private readonly ICheapestIntervalsFinder _cheapestIntervalsFinder;
private readonly INordPoolBoilerConfigProvider _boilerConfigProvider;
private readonly IScheduler _scheduler;
private readonly NordPoolOptions _options;
private readonly TimeProvider _timeProvider;
private string? UnitOfMeasurement { get; }
private IReadOnlyList<CheapestIntervalResult>? CheapestIntervals { get; set; }
public NordPoolInit(
Entities entities,
IHaContext haContext,
ILogger<NordPoolInit> logger,
INordPoolPriceService priceService,
INordPoolEntityService entityService,
IScheduler scheduler,
ICheapestIntervalsFinder cheapestIntervalsFinder,
INordPoolBoilerConfigProvider boilerConfigProvider,
IOptions<NordPoolOptions> options,
TimeProvider timeProvider)
{
_logger = logger;
_haContext = haContext;
_priceService = priceService;
_entityService = entityService;
_scheduler = scheduler;
_cheapestIntervalsFinder = cheapestIntervalsFinder;
_boilerConfigProvider = boilerConfigProvider;
_options = options.Value;
_timeProvider = timeProvider;
var nordPoolPriceSensor = entities.Sensor.NordpoolPrice;
UnitOfMeasurement = nordPoolPriceSensor.EntityState?.Attributes?.UnitOfMeasurement ?? "EUR/kWh";
_ = InitializeAndScheduleAsync();
}
private async Task InitializeAndScheduleAsync()
{
try
{
await InitializeAsync();
SubscribeToFetchPricesButton();
SchedulePeriodicUpdates();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error during initialization and scheduling");
}
}
public async Task InitializeAsync()
{
try
{
await Task.Delay(TimeSpan.FromSeconds(3));
await _priceService.FetchPricesAsync();
if (_options.CleanupEntitiesOnStartup)
{
await _entityService.CleanupEntitiesAsync();
}
await _entityService.CreateEntitiesAsync(UnitOfMeasurement);
await _entityService.ResetEntitiesAsync();
await Task.Delay(TimeSpan.FromSeconds(10));
var currentPrice = _priceService.UpdateCurrentPrice();
if (currentPrice == 0)
{
_logger.LogWarning("Current price is 0, which may indicate an issue with price retrieval");
}
var boilerConfig = _boilerConfigProvider.GetCurrentConfiguration();
UpdateCheapestIntervals(boilerConfig);
await UpdateEntitiesAsync(boilerConfig);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error initializing NordPool prices");
throw;
}
}
private void SchedulePeriodicUpdates()
{
var now = _timeProvider.GetLocalNow();
var currentMinute = now.Minute;
var currentSecond = now.Second;
var minutesUntilNext15 = 15 - currentMinute % 15;
var delayUntilNext15 = TimeSpan.FromMinutes(minutesUntilNext15) - TimeSpan.FromSeconds(currentSecond);
var nextUpdateTime = now.Add(delayUntilNext15);
_scheduler.RunEvery(TimeSpan.FromMinutes(15), nextUpdateTime, () => _ = UpdatePricesAsync());
}
private async Task UpdatePricesAsync()
{
try
{
var cetTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
var nowCet = TimeZoneInfo.ConvertTime(_timeProvider.GetUtcNow(), cetTimeZone).DateTime;
var today = DateOnly.FromDateTime(nowCet);
if (_priceService.LastFetchedDate.HasValue && _priceService.LastFetchedDate.Value < today)
{
_priceService.RollOverPrices(today);
}
if (_priceService.ShouldFetchNewPrices(today))
{
await _priceService.FetchPricesAsync();
}
_priceService.UpdateCurrentPrice();
var boilerConfig = _boilerConfigProvider.GetCurrentConfiguration();
UpdateCheapestIntervals(boilerConfig);
await UpdateEntitiesAsync(boilerConfig);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error updating NordPool prices");
}
}
private void SubscribeToFetchPricesButton()
{
var button = new Entity(_haContext, NordPoolConsts.FetchPricesButtonEntityId);
button.StateChanges()
.Subscribe(_ =>
{
_logger.LogInformation("Fetch prices button pressed, triggering manual NordPool price update");
Task.Run(HandleFetchPricesAsync);
});
}
private async Task HandleFetchPricesAsync()
{
try
{
_logger.LogInformation("Manual fetch: forcing fresh NordPool price retrieval");
await _priceService.FetchPricesAsync();
_priceService.UpdateCurrentPrice();
var boilerConfig = _boilerConfigProvider.GetCurrentConfiguration();
UpdateCheapestIntervals(boilerConfig);
await UpdateEntitiesAsync(boilerConfig);
_logger.LogInformation("Manual fetch and update completed");
}
catch (Exception ex)
{
_logger.LogError(ex, "Error during manual NordPool price fetch");
}
}
public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default)
{
await _entityService.CleanupEntitiesAsync(cancellationToken);
}
private void UpdateCheapestIntervals(BoilerConfig config)
{
var effectivePriceCap = config.SkipPriceCap ? double.MaxValue : config.PriceCap;
var effectiveIntervalCount = config.SkipPriceCap ? NordPoolConsts.MaxDailyIntervals : config.IntervalCount;
try
{
if (_priceService.TodayNordPoolPrice?.Prices is not { Count: > 0 })
{
_logger.LogDebug("No today prices available, skipping cheapest intervals calculation");
CheapestIntervals = [];
return;
}
CheapestIntervals = _cheapestIntervalsFinder.FindCheapestIntervals(_priceService.TodayNordPoolPrice, effectiveIntervalCount, effectivePriceCap, config.Deadline);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error calculating cheapest intervals");
CheapestIntervals = [];
}
}
private async Task UpdateEntitiesAsync(BoilerConfig boilerConfig)
{
var cetTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
var nowCet = TimeZoneInfo.ConvertTime(_timeProvider.GetUtcNow(), cetTimeZone).DateTime;
var todayCet = DateOnly.FromDateTime(nowCet);
var currentDateTime = nowCet;
var configuredHours = (double)boilerConfig.IntervalCount / NordPoolConsts.IntervalsPerHour;
var configuredReadyBy = boilerConfig.Deadline.TimeOfDay.ToString(@"hh\:mm", CultureInfo.InvariantCulture);
var isNowCheap = CheapestIntervals != null && _cheapestIntervalsFinder.IsCurrentIntervalCheap(CheapestIntervals, currentDateTime);
var nextCheapInterval = CheapestIntervals?
.Where(i => i.Start > currentDateTime)
.OrderBy(i => i.Start)
.FirstOrDefault();
var context = new EntityUpdateContext
{
CurrentPrice = _priceService.CurrentPrice,
UnitOfMeasurement = UnitOfMeasurement,
DayQuartersIndex = _priceService.DayQuartersIndex,
LastApiUpdateDate = _priceService.LastUpdatedDate,
UsingCachedData = !_priceService.ShouldFetchNewPrices(todayCet),
TodayNordPoolPrice = _priceService.TodayNordPoolPrice,
TomorrowNordPoolPrice = _priceService.TomorrowNordPoolPrice,
CheapestIntervals = CheapestIntervals,
ConfiguredHours = configuredHours,
ConfiguredIntervalCount = boilerConfig.IntervalCount,
ConfiguredPriceCap = boilerConfig.PriceCap,
SkipPriceCap = boilerConfig.SkipPriceCap,
ConfiguredReadyBy = configuredReadyBy,
IsNowCheap = isNowCheap,
NextCheapIntervalStart = nextCheapInterval?.Start
};
await _entityService.UpdateEntitiesAsync(context);
}
}