using System.Globalization; using BoilerMonitor.Models; using HomeAssistant.HistoryReplay.Configuration; using HomeAssistant.HistoryReplay.HistoryData; using HomeAssistant.HistoryReplay.Replay; using HomeAssistant.HistoryReplay.Reporting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using NordPool.Models; using NordPoolManager.Interface; namespace HomeAssistant.HistoryReplay.Runners; public sealed class NordPoolReplayRunner : IMonitorReplayRunner { private readonly HistoryTimeline _timeline; private readonly ReplayTimeProvider _timeProvider; private readonly ReplayTimeline _replayTimeline; private readonly ReplayDataSeries _dataSeries; private readonly ICheapestIntervalsFinder _cheapestIntervalsFinder; private readonly ILogger _logger; private readonly ReplayOptions _options; private const string NordPoolHaSensorId = "sensor.nordpool_kwh_lt_eur_3_10_0"; public string MonitorName => "NordPool"; public NordPoolReplayRunner( HistoryTimeline timeline, ReplayTimeProvider timeProvider, ReplayTimeline replayTimeline, ReplayDataSeries dataSeries, ICheapestIntervalsFinder cheapestIntervalsFinder, ILogger logger, IOptions options) { _timeline = timeline; _timeProvider = timeProvider; _replayTimeline = replayTimeline; _dataSeries = dataSeries; _cheapestIntervalsFinder = cheapestIntervalsFinder; _logger = logger; _options = options.Value; } public Task RunAsync(CancellationToken cancellationToken = default) { _logger.LogInformation("Starting NordPool replay"); var currentTime = _options.StartTime; var interval = TimeSpan.FromMinutes(NordPoolConsts.MinutesPerInterval); double? lastReportedPrice = null; while (currentTime <= _options.EndTime && !cancellationToken.IsCancellationRequested) { _timeProvider.AdvanceTo(currentTime); var priceEntry = _timeline.GetStateAt(NordPoolHaSensorId, currentTime) ?? _timeline.GetStateAt(NordPoolConsts.CurrentPriceEntityId, currentTime); if (priceEntry?.State is not null && double.TryParse(priceEntry.State, CultureInfo.InvariantCulture, out var currentPrice)) { _dataSeries.AddPoint(MonitorName, "Price", currentTime, currentPrice); if (lastReportedPrice is null || Math.Abs(currentPrice - lastReportedPrice.Value) > 0.01) { _replayTimeline.AddEvent(new ReplayEvent { Timestamp = currentTime, Monitor = MonitorName, EventType = ReplayEventType.Info, Message = $"Price: {currentPrice:F2} ct/kWh" }); lastReportedPrice = currentPrice; } } var boilerConfig = ReadBoilerConfig(currentTime); if (boilerConfig is not null) { var prices = BuildNordPoolPriceFromHistory(currentTime); if (prices.Prices is { Count: > 0 }) { var effectivePriceCap = boilerConfig.SkipPriceCap ? double.MaxValue : boilerConfig.PriceCap; var effectiveIntervalCount = boilerConfig.SkipPriceCap ? NordPoolConsts.MaxDailyIntervals : boilerConfig.IntervalCount; var cheapest = _cheapestIntervalsFinder.FindCheapestIntervals( prices, effectiveIntervalCount, effectivePriceCap, boilerConfig.Deadline); var isNowCheap = _cheapestIntervalsFinder.IsCurrentIntervalCheap( cheapest, currentTime.LocalDateTime); _dataSeries.AddPoint(MonitorName, "IsCheap", currentTime, isNowCheap ? 1.0 : 0.0); if (isNowCheap) { var currentInterval = cheapest.FirstOrDefault(i => currentTime.LocalDateTime >= i.Start && currentTime.LocalDateTime < i.End); _replayTimeline.AddEvent(new ReplayEvent { Timestamp = currentTime, Monitor = MonitorName, EventType = ReplayEventType.Decision, Message = $"CHEAP interval active (rank #{currentInterval?.Rank}, price: {currentInterval?.Price:F2} ct/kWh)", Details = $"Total cheap intervals: {cheapest.Count}" }); } } } currentTime = currentTime.Add(interval); } _logger.LogInformation("NordPool replay complete"); return Task.CompletedTask; } private BoilerConfig? ReadBoilerConfig(DateTimeOffset timestamp) { var dailyHoursEntry = _timeline.GetStateAt(BoilerMonitorConsts.BoilerDailyHoursEntityId, timestamp); var priceCapEntry = _timeline.GetStateAt(BoilerMonitorConsts.BoilerPriceCapEntityId, timestamp); var readyByEntry = _timeline.GetStateAt(BoilerMonitorConsts.BoilerReadyByEntityId, timestamp); var skipPriceCapEntry = _timeline.GetStateAt(BoilerMonitorConsts.SkipPriceCapEntityId, timestamp); if (dailyHoursEntry?.State is null || priceCapEntry?.State is null || readyByEntry?.State is null) { return null; } if (!double.TryParse(dailyHoursEntry.State, CultureInfo.InvariantCulture, out var dailyHours) || !double.TryParse(priceCapEntry.State, CultureInfo.InvariantCulture, out var priceCap)) { return null; } var intervalCount = (int)(dailyHours * NordPoolConsts.IntervalsPerHour); if (!TimeSpan.TryParse(readyByEntry.State, CultureInfo.InvariantCulture, out var readyByTime)) { return null; } var deadline = timestamp.LocalDateTime.Date.Add(readyByTime); if (deadline < timestamp.LocalDateTime) { deadline = deadline.AddDays(1); } var skipPriceCap = string.Equals(skipPriceCapEntry?.State, "on", StringComparison.OrdinalIgnoreCase); return new BoilerConfig { IntervalCount = intervalCount, PriceCap = priceCap, Deadline = deadline, SkipPriceCap = skipPriceCap }; } private NordPoolPrice BuildNordPoolPriceFromHistory(DateTimeOffset timestamp) { var nordPoolSensorEntries = _timeline.GetEntityHistory("sensor.nordpool_kwh_lt_eur_3_10_0"); var todayDate = timestamp.LocalDateTime.Date; var todayPrices = nordPoolSensorEntries .Where(e => e.LastChanged.LocalDateTime.Date == todayDate) .Where(e => e.State is not null && double.TryParse(e.State, CultureInfo.InvariantCulture, out _)) .Select(e => new NordPoolDayPrice { Start = e.LastChanged.LocalDateTime, End = e.LastChanged.LocalDateTime.AddMinutes(NordPoolConsts.MinutesPerInterval), Price = double.Parse(e.State!, CultureInfo.InvariantCulture) }) .ToList(); return new NordPoolPrice { Prices = todayPrices }; } }