using System.Globalization; using BoilerMonitor.Models; using BoilerMonitor.Models.Enums; using BoilerMonitorManager.Interface; using HomeAssistant.HistoryReplay.Configuration; using HomeAssistant.HistoryReplay.HistoryData; using HomeAssistant.HistoryReplay.Replay; using HomeAssistant.HistoryReplay.Reporting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace HomeAssistant.HistoryReplay.Runners; public sealed class BoilerReplayRunner : IMonitorReplayRunner { private readonly HistoryTimeline _timeline; private readonly ReplayTimeProvider _timeProvider; private readonly ReplayTimeline _replayTimeline; private readonly ReplayDataSeries _dataSeries; private readonly IBoilerControlService _boilerControlService; private readonly IBoilerRunTimeTracker _tracker; private readonly IWaterReadyService _waterReadyService; private readonly ILogger _logger; private readonly ReplayOptions _replayOptions; private readonly string _boilerPowerEntityId; private readonly string _boilerSwitchEntityId; public string MonitorName => "Boiler"; public BoilerReplayRunner( HistoryTimeline timeline, ReplayTimeProvider timeProvider, ReplayTimeline replayTimeline, ReplayDataSeries dataSeries, IBoilerControlService boilerControlService, IBoilerRunTimeTracker tracker, IWaterReadyService waterReadyService, ILogger logger, IOptions replayOptions, string boilerPowerEntityId, string boilerSwitchEntityId) { _timeline = timeline; _timeProvider = timeProvider; _replayTimeline = replayTimeline; _dataSeries = dataSeries; _boilerControlService = boilerControlService; _tracker = tracker; _waterReadyService = waterReadyService; _logger = logger; _replayOptions = replayOptions.Value; _boilerPowerEntityId = boilerPowerEntityId; _boilerSwitchEntityId = boilerSwitchEntityId; } public Task RunAsync(CancellationToken cancellationToken = default) { _logger.LogInformation("Starting Boiler replay"); var currentTime = _replayOptions.StartTime; var pollInterval = TimeSpan.FromSeconds(BoilerMonitorConsts.DefaultPollIntervalSeconds); var heatingThreshold = BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts; BoilerAction? lastAction = null; var lastWaterReady = false; var boilerPowerEntityId = _boilerPowerEntityId; var boilerSwitchEntityId = _boilerSwitchEntityId; while (currentTime <= _replayOptions.EndTime && !cancellationToken.IsCancellationRequested) { _timeProvider.AdvanceTo(currentTime); var powerEntry = _timeline.GetStateAt(boilerPowerEntityId, currentTime); var switchEntry = _timeline.GetStateAt(boilerSwitchEntityId, currentTime); var cheapEntry = _timeline.GetStateAt("sensor.nordpool_cheapest_intervals", currentTime); var skipPriceCapEntry = _timeline.GetStateAt(BoilerMonitorConsts.SkipPriceCapEntityId, currentTime); var budgetOverrideEntry = _timeline.GetStateAt(BoilerMonitorConsts.BudgetOverrideEntityId, currentTime); var autoManagementEntry = _timeline.GetStateAt(BoilerMonitorConsts.AutoManagementEntityId, currentTime); var dailyHoursEntry = _timeline.GetStateAt(BoilerMonitorConsts.BoilerDailyHoursEntityId, currentTime); var boilerPowerWatts = ParseDouble(powerEntry?.State); var boilerSwitchState = switchEntry?.State; var isHeating = boilerPowerWatts.HasValue && boilerPowerWatts.Value >= heatingThreshold; _tracker.RecordPollResult(isHeating, pollInterval); if (isHeating) { _waterReadyService.RecordHeatingObserved(); } if (boilerPowerWatts.HasValue) { _dataSeries.AddPoint(MonitorName, "PowerWatts", currentTime, boilerPowerWatts.Value); } var isNowCheap = ReadAttributeBool(cheapEntry, "is_now_cheap"); var skipPriceCap = string.Equals(skipPriceCapEntry?.State, "on", StringComparison.OrdinalIgnoreCase); var budgetOverride = string.Equals(budgetOverrideEntry?.State, "on", StringComparison.OrdinalIgnoreCase); var autoManagementEnabled = !string.Equals(autoManagementEntry?.State, BoilerMonitorConsts.SwitchOffState, StringComparison.OrdinalIgnoreCase); var dailyHours = ParseDouble(dailyHoursEntry?.State) ?? 1.0; var waterReady = _waterReadyService.IsWaterReady(boilerSwitchState, boilerPowerWatts, heatingThreshold); if (!lastWaterReady && waterReady) { _replayTimeline.AddEvent(new ReplayEvent { Timestamp = currentTime, Monitor = MonitorName, EventType = ReplayEventType.StateChange, Message = $"Water ready detected (power: {boilerPowerWatts:F1}W, threshold: {heatingThreshold}W)" }); } lastWaterReady = waterReady; var snapshot = _tracker.GetSnapshot(); var budgetTimeSpan = TimeSpan.FromHours(dailyHours); var budgetExhausted = snapshot.AccumulatedRunTime >= budgetTimeSpan; var budgetPercentage = budgetTimeSpan.TotalSeconds > 0 ? (snapshot.AccumulatedRunTime.TotalSeconds / budgetTimeSpan.TotalSeconds) * 100.0 : 0.0; _dataSeries.AddPoint(MonitorName, "BudgetPercent", currentTime, budgetPercentage); _dataSeries.AddPoint(MonitorName, "SwitchState", currentTime, string.Equals(boilerSwitchState, "on", StringComparison.OrdinalIgnoreCase) ? 1.0 : 0.0); var effectiveIsNowCheap = isNowCheap || skipPriceCap; var action = _boilerControlService.DetermineAction( effectiveIsNowCheap, waterReady, boilerSwitchState, budgetExhausted, budgetOverride); if (action != BoilerAction.NoChange && action != lastAction) { var actionMessage = action switch { BoilerAction.TurnOn => $"TURN ON (cheap: {effectiveIsNowCheap}, water ready: {waterReady}, budget: {budgetPercentage:F0}%)", BoilerAction.TurnOff => $"TURN OFF (cheap: {effectiveIsNowCheap}, water ready: {waterReady}, budget: {budgetPercentage:F0}%)", _ => action.ToString() }; if (autoManagementEnabled) { _replayTimeline.AddEvent(new ReplayEvent { Timestamp = currentTime, Monitor = MonitorName, EventType = ReplayEventType.Decision, Message = actionMessage, Details = $"Power: {boilerPowerWatts:F1}W, Runtime: {snapshot.AccumulatedRunTime:hh\\:mm\\:ss}, Sessions: {snapshot.SessionCount}" }); if (action == BoilerAction.TurnOn) { _waterReadyService.NotifyTurnedOn(); } } else { _replayTimeline.AddEvent(new ReplayEvent { Timestamp = currentTime, Monitor = MonitorName, EventType = ReplayEventType.Decision, Message = $"SUPPRESSED (auto control off): {actionMessage}", Details = $"Power: {boilerPowerWatts:F1}W, Runtime: {snapshot.AccumulatedRunTime:hh\\:mm\\:ss}, Sessions: {snapshot.SessionCount}" }); } } lastAction = action; currentTime = currentTime.Add(pollInterval); } var finalSnapshot = _tracker.GetSnapshot(); _replayTimeline.AddEvent(new ReplayEvent { Timestamp = _replayOptions.EndTime, Monitor = MonitorName, EventType = ReplayEventType.Info, Message = $"Final: {finalSnapshot.AccumulatedRunTime:hh\\:mm\\:ss} total runtime, {finalSnapshot.SessionCount} session(s)" }); _logger.LogInformation("Boiler replay complete"); return Task.CompletedTask; } private static bool ReadAttributeBool(HistoryStateEntry? entry, string attributeName) { if (entry?.Attributes is null) { return false; } if (!entry.Attributes.TryGetValue(attributeName, out var value)) { return false; } return value switch { bool b => b, string s => bool.TryParse(s, out var parsed) && parsed, double d => d != 0, _ => false }; } private static double? ParseDouble(string? value) { if (value is null or "unavailable" or "unknown") { return null; } return double.TryParse(value, CultureInfo.InvariantCulture, out var result) ? result : null; } }