using System.Reactive.Concurrency; using HomeAssistantGenerated; using Microsoft.Extensions.Logging; using NetDaemon.HassModel; using NetDaemon.AppModel; using NetDaemon.Extensions.Scheduler; using NordPool.Models; using NordPoolManager.Interface; using NordPoolManager.Models; using NordPoolManager.Models.Consts; using static NordPoolManager.Models.Enums.BoilerAction; namespace NordPoolManager; [NetDaemonApp] public class NordPoolInit : INordPoolInit { private readonly ILogger _logger; private readonly INordPoolPriceService _priceService; private readonly INordPoolEntityService _entityService; private readonly ICheapestIntervalsFinder _cheapestIntervalsFinder; private readonly IBoilerControlService _boilerControlService; private readonly IScheduler _scheduler; private readonly IHaContext _haContext; private InputNumberEntity BoilerDailyHoursEntity { get; } private InputNumberEntity BoilerPriceCapEntity { get; } private SwitchEntity BoilerSkipPriceCapEntity { get; } private InputDatetimeEntity BoilerReadyByEntity { get; } private SwitchEntity BoilerSwitchEntity { get; } private NumericSensorEntity BoilerPowerEntity { get; } private string? UnitOfMeasurement { get; } private IReadOnlyList? CheapestIntervals { get; set; } private bool _lastWaterReady; public NordPoolInit( Entities entities, IHaContext haContext, ILogger logger, INordPoolPriceService priceService, INordPoolEntityService entityService, IScheduler scheduler, ICheapestIntervalsFinder cheapestIntervalsFinder, IBoilerControlService boilerControlService) { _logger = logger; _haContext = haContext; _priceService = priceService; _entityService = entityService; _scheduler = scheduler; _cheapestIntervalsFinder = cheapestIntervalsFinder; _boilerControlService = boilerControlService; var nordPoolPriceSensor = entities.Sensor.NordpoolPrice; UnitOfMeasurement = nordPoolPriceSensor.EntityState?.Attributes?.UnitOfMeasurement ?? "EUR/kWh"; BoilerDailyHoursEntity = entities.InputNumber.BoilerDailyHours; BoilerPriceCapEntity = entities.InputNumber.BoilerPriceCap; BoilerSkipPriceCapEntity = new SwitchEntity(_haContext, "switch.nordpool_boiler_skip_price_cap"); BoilerReadyByEntity = entities.InputDatetime.BoilerReadyBy; BoilerSwitchEntity = entities.Switch.Sonoff1002230e32; BoilerPowerEntity = entities.Sensor.Sonoff1002230e32Power; _ = InitializeAndScheduleAsync(); } private async Task InitializeAndScheduleAsync() { try { await InitializeAsync(); SchedulePeriodicUpdates(); ScheduleEndOfDayReminder(); SubscribeToSkipPriceCapChanges(); } catch (Exception ex) { _logger.LogError(ex, "Error during initialization and scheduling"); } } private void ScheduleEndOfDayReminder() { _scheduler.ScheduleCron("0 20 * * *", CheckSkipPriceCapReminderAsync); } private void CheckSkipPriceCapReminderAsync() { try { var switchState = BoilerSkipPriceCapEntity.State; if (string.Equals(switchState, "on", StringComparison.OrdinalIgnoreCase)) { _haContext.CallService("notify", "mobile_app_marius_phone", null, new { message = "Remember to turn off 'Skip price cap, heat until ready' if you're done heating.", title = "Boiler reminder" }); _logger.LogInformation("End-of-day reminder sent: skip price cap switch is still ON"); } } catch (Exception ex) { _logger.LogError(ex, "Error checking skip price cap reminder"); } } private void SubscribeToSkipPriceCapChanges() { BoilerSkipPriceCapEntity.StateChanges() .Subscribe(e => { if (e.Old?.State == e.New?.State) { return; } _logger.LogInformation("Skip price cap switch changed, recalculating cheapest intervals"); _ = RecalculateOnConfigChangeAsync(); }); } private async Task RecalculateOnConfigChangeAsync() { try { var result = UpdateCheapestIntervals(); await UpdateEntitiesAsync(result.IntervalCount, result.PriceCap, result.SkipPriceCap); } catch (Exception ex) { _logger.LogError(ex, "Error recalculating on skip price cap switch change"); } } public async Task InitializeAsync() { try { await Task.Delay(TimeSpan.FromSeconds(3)); await _priceService.FetchPricesAsync(); await _entityService.CreateEntitiesAsync(UnitOfMeasurement); await _entityService.ResetEntitiesAsync(); await Task.Delay(TimeSpan.FromSeconds(10)); var currentPrice = _priceService.UpdateCurrentPrice(); _logger.LogInformation("Retrieved current price: {Price}, DayQuartersIndex: {Index}", currentPrice, _priceService.DayQuartersIndex); if (currentPrice == 0) { _logger.LogWarning("Current price is 0, which may indicate an issue with price retrieval"); } var result = UpdateCheapestIntervals(); await UpdateEntitiesAsync(result.IntervalCount, result.PriceCap, result.SkipPriceCap); _logger.LogInformation("NordPool price initialized with current price: {CurrentPrice} {Unit}", _priceService.CurrentPrice, UnitOfMeasurement); } catch (Exception ex) { _logger.LogError(ex, "Error initializing NordPool prices"); throw; } } private void SchedulePeriodicUpdates() { var now = DateTime.Now; 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); _logger.LogInformation("Scheduling first NordPool update at {Time} (in {Delay})", nextUpdateTime, delayUntilNext15); _scheduler.RunEvery(TimeSpan.FromMinutes(15), nextUpdateTime, async void () => { try { await UpdatePricesAsync(); } catch (Exception e) { _logger.LogError(e, "Error updating NordPool prices"); } }); } private async Task UpdatePricesAsync() { try { _logger.LogInformation("Starting periodic NordPool price update"); var cetTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time"); var nowCet = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, cetTimeZone); var today = DateOnly.FromDateTime(nowCet); _logger.LogDebug("Current CET time: {CetTime}, Today in CET: {Today}", nowCet, today); if (_priceService.LastFetchedDate.HasValue && _priceService.LastFetchedDate.Value < today) { _priceService.RollOverPrices(today); } if (_priceService.ShouldFetchNewPrices(today)) { _logger.LogInformation("Fetching new prices from NordPool API"); await _priceService.FetchPricesAsync(); } else { _logger.LogDebug("Using cached prices, no need to fetch from API"); } _priceService.UpdateCurrentPrice(); var result = UpdateCheapestIntervals(); await UpdateEntitiesAsync(result.IntervalCount, result.PriceCap, result.SkipPriceCap); _logger.LogInformation("NordPool prices updated successfully. Current price: {CurrentPrice} {Unit}", _priceService.CurrentPrice, UnitOfMeasurement); } catch (Exception ex) { _logger.LogError(ex, "Error updating NordPool prices"); } } public async Task CleanupEntitiesAsync() { await _entityService.CleanupEntitiesAsync(); } private CheapestIntervalsUpdateResult UpdateCheapestIntervals() { var boilerConfig = ReadBoilerConfig(); var effectivePriceCap = boilerConfig.SkipPriceCap ? double.MaxValue : boilerConfig.PriceCap; var effectiveIntervalCount = boilerConfig.SkipPriceCap ? PriceConsts.MaxDailyIntervals : boilerConfig.IntervalCount; try { if (_priceService.TodayNordPoolPrice?.Prices is not { Count: > 0 }) { _logger.LogDebug("No today prices available, skipping cheapest intervals calculation"); CheapestIntervals = []; return new CheapestIntervalsUpdateResult { IntervalCount = boilerConfig.IntervalCount, PriceCap = boilerConfig.PriceCap, SkipPriceCap = boilerConfig.SkipPriceCap }; } CheapestIntervals = _cheapestIntervalsFinder.FindCheapestIntervals(_priceService.TodayNordPoolPrice, effectiveIntervalCount, effectivePriceCap, boilerConfig.Deadline); _logger.LogInformation("Cheapest intervals updated: {Count} intervals (config: {Hours}h / {Intervals} intervals, cap: {Cap}, skipPriceCap: {Skip}, deadline: {Deadline})", CheapestIntervals.Count, boilerConfig.IntervalCount / 4.0, effectiveIntervalCount, effectivePriceCap, boilerConfig.SkipPriceCap, boilerConfig.Deadline); } catch (Exception ex) { _logger.LogError(ex, "Error calculating cheapest intervals"); CheapestIntervals = []; } return new CheapestIntervalsUpdateResult { IntervalCount = boilerConfig.IntervalCount, PriceCap = boilerConfig.PriceCap, SkipPriceCap = boilerConfig.SkipPriceCap }; } private BoilerConfig ReadBoilerConfig() { var boilerConfig = new BoilerConfig(); var dailyHours = BoilerDailyHoursEntity.State ?? 1.0; var intervalCount = (int)(dailyHours * PriceConsts.IntervalsPerHour); if (intervalCount <= 0) { intervalCount = PriceConsts.IntervalsPerHour; } boilerConfig.IntervalCount = intervalCount; var priceCap = BoilerPriceCapEntity.State ?? double.MaxValue; if (priceCap <= 0) { priceCap = double.MaxValue; } boilerConfig.PriceCap = priceCap; var deadline = DateTime.Today.AddDays(1); var readyByState = BoilerReadyByEntity.State; if (!string.IsNullOrEmpty(readyByState) && TimeSpan.TryParse(readyByState, out var readyByTime)) { deadline = DateTime.Today.Add(readyByTime); } boilerConfig.Deadline = deadline; var skipPriceCapState = BoilerSkipPriceCapEntity.State; boilerConfig.SkipPriceCap = string.Equals(skipPriceCapState, "on", StringComparison.OrdinalIgnoreCase); _logger.LogDebug("Boiler config: intervals={Intervals}, priceCap={Cap}, skipPriceCap={Skip}, deadline={Deadline}", boilerConfig.IntervalCount, boilerConfig.PriceCap, boilerConfig.SkipPriceCap, boilerConfig.Deadline); return boilerConfig; } private async Task UpdateEntitiesAsync(int configuredIntervalCount, double configuredPriceCap, bool skipPriceCap) { var cetTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time"); var nowCet = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, cetTimeZone); var todayCet = DateOnly.FromDateTime(nowCet); var currentDateTime = DateTime.Now; var configuredHours = BoilerDailyHoursEntity.State ?? 1.0; var configuredReadyBy = BoilerReadyByEntity.State ?? ""; var isNowCheap = CheapestIntervals != null && _cheapestIntervalsFinder.IsCurrentIntervalCheap(CheapestIntervals, currentDateTime); var nextCheapInterval = CheapestIntervals? .Where(i => i.Start > currentDateTime) .OrderBy(i => i.Start) .FirstOrDefault(); var boilerSwitchState = BoilerSwitchEntity.State; var boilerPowerWatts = BoilerPowerEntity.State; var waterReady = _cheapestIntervalsFinder.IsWaterReady(boilerSwitchState, boilerPowerWatts); if (!_lastWaterReady && waterReady) { _haContext.CallService("notify", "mobile_app_marius_phone", null, new { message = "Hot water is ready.", title = "Boiler" }); _logger.LogInformation("Water ready notification sent to mobile_app_marius_phone"); } _lastWaterReady = waterReady; var boilerAction = _boilerControlService.DetermineAction(isNowCheap, waterReady, boilerSwitchState); switch (boilerAction) { case TurnOn: BoilerSwitchEntity.TurnOn(); break; case TurnOff: BoilerSwitchEntity.TurnOff(); break; case NoChange: break; default: throw new ArgumentOutOfRangeException(); } 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 = configuredIntervalCount, ConfiguredPriceCap = configuredPriceCap, SkipPriceCap = skipPriceCap, ConfiguredReadyBy = configuredReadyBy, IsNowCheap = isNowCheap, NextCheapIntervalStart = nextCheapInterval?.Start, WaterReady = waterReady, BoilerSwitchState = boilerSwitchState, BoilerPowerWatts = boilerPowerWatts }; await _entityService.UpdateEntitiesAsync(context); } }