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 { private readonly INordPoolBoilerConfigProvider _boilerConfigProvider; private readonly ICheapestIntervalsFinder _cheapestIntervalsFinder; private readonly INordPoolEntityService _entityService; private readonly IHaContext _haContext; private readonly ILogger _logger; private readonly NordPoolOptions _options; private readonly INordPoolPriceService _priceService; private readonly IScheduler _scheduler; private readonly TimeProvider _timeProvider; public NordPoolInit( Entities entities, IHaContext haContext, ILogger logger, INordPoolPriceService priceService, INordPoolEntityService entityService, IScheduler scheduler, ICheapestIntervalsFinder cheapestIntervalsFinder, INordPoolBoilerConfigProvider boilerConfigProvider, IOptions 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 string? UnitOfMeasurement { get; } private IReadOnlyList? CheapestIntervals { get; set; } public async Task InitializeAsync() { try { await Task.Delay(TimeSpan.FromSeconds(3)); if (_options.CleanupEntitiesOnStartup) await _entityService.CleanupEntitiesAsync(); await _entityService.CreateEntitiesAsync(UnitOfMeasurement); await _entityService.ResetEntitiesAsync(); await Task.Delay(TimeSpan.FromSeconds(10)); await UpdatePricesAsync(); } catch (Exception ex) { _logger.LogError(ex, "Error initializing NordPool prices"); throw; } } private async Task InitializeAndScheduleAsync() { try { await InitializeAsync(); SubscribeToFetchPricesButton(); SchedulePeriodicUpdates(); } catch (Exception ex) { _logger.LogError(ex, "Error during initialization and scheduling"); } } 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(UpdatePricesAsync); }); } 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 currentDateTime = TimeZoneInfo.ConvertTime(_timeProvider.GetUtcNow(), cetTimeZone).DateTime; var todayCet = DateOnly.FromDateTime(currentDateTime); 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); } }