using System.Globalization; 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 PowerMonitorManager.Interface; using PowerMonitorManager.Models; using PowerMonitorManager.Models.Consts; namespace HomeAssistant.HistoryReplay.Runners; public sealed class PowerReplayRunner : IMonitorReplayRunner { private readonly HistoryTimeline _timeline; private readonly ReplayTimeProvider _timeProvider; private readonly ReplayTimeline _replayTimeline; private readonly IOtherPowerCalculationService _calculationService; private readonly IPowerCostCalculationService _costService; private readonly ILogger _logger; private readonly ReplayOptions _replayOptions; private readonly PowerMonitorOptions _powerOptions; public string MonitorName => "Power"; public PowerReplayRunner( HistoryTimeline timeline, ReplayTimeProvider timeProvider, ReplayTimeline replayTimeline, IOtherPowerCalculationService calculationService, IPowerCostCalculationService costService, ILogger logger, IOptions replayOptions, IOptions powerOptions) { _timeline = timeline; _timeProvider = timeProvider; _replayTimeline = replayTimeline; _calculationService = calculationService; _costService = costService; _logger = logger; _replayOptions = replayOptions.Value; _powerOptions = powerOptions.Value; } public Task RunAsync(CancellationToken cancellationToken = default) { _logger.LogInformation("Starting Power replay"); var currentTime = _replayOptions.StartTime; var pollInterval = TimeSpan.FromSeconds(_powerOptions.PollIntervalSeconds); DateTime? anomalyStartTime = null; while (currentTime <= _replayOptions.EndTime && !cancellationToken.IsCancellationRequested) { _timeProvider.AdvanceTo(currentTime); var mainMeterEntry = _timeline.GetStateAt(_powerOptions.MainMeterEntityId, currentTime); var totalPower = ParseDouble(mainMeterEntry?.State); if (!totalPower.HasValue) { currentTime = currentTime.Add(pollInterval); continue; } var deviceReadings = DiscoverAndReadDevicePower(currentTime); var calculation = _calculationService.Calculate(totalPower.Value, deviceReadings); var nordPoolPriceEntry = _timeline.GetStateAt(NordPoolConsts.CurrentPriceEntityId, currentTime); var nordPoolPrice = ParseDouble(nordPoolPriceEntry?.State) ?? 0; _costService.RecordCosts(calculation, nordPoolPrice, _powerOptions.PollIntervalSeconds, currentTime.LocalDateTime); var isAnomaly = calculation.SmoothedOtherPowerWatts > _powerOptions.AnomalyThresholdWatts; if (isAnomaly && anomalyStartTime is null) { anomalyStartTime = currentTime.LocalDateTime; _replayTimeline.AddEvent(new ReplayEvent { Timestamp = currentTime, Monitor = MonitorName, EventType = ReplayEventType.Anomaly, Message = $"Other power {calculation.SmoothedOtherPowerWatts:F0}W exceeds threshold {_powerOptions.AnomalyThresholdWatts}W", Details = $"Total: {calculation.TotalPowerWatts:F0}W, Known: {calculation.KnownDevicesSumWatts:F0}W" }); } else if (!isAnomaly && anomalyStartTime is not null) { var duration = currentTime.LocalDateTime - anomalyStartTime.Value; _replayTimeline.AddEvent(new ReplayEvent { Timestamp = currentTime, Monitor = MonitorName, EventType = ReplayEventType.Info, Message = $"Anomaly resolved after {duration:mm\\:ss}" }); anomalyStartTime = null; } currentTime = currentTime.Add(pollInterval); } var totalCost = _costService.GetTotalCostSnapshot(); _replayTimeline.AddEvent(new ReplayEvent { Timestamp = _replayOptions.EndTime, Monitor = MonitorName, EventType = ReplayEventType.Info, Message = $"Final: Total daily cost {totalCost.CostDaily:F4} EUR" }); _logger.LogInformation("Power replay complete"); return Task.CompletedTask; } private IReadOnlyDictionary DiscoverAndReadDevicePower(DateTimeOffset timestamp) { var readings = new Dictionary(); var allEntities = _timeline.GetEntityIds(); foreach (var entityId in allEntities) { if (!entityId.StartsWith("sensor.", StringComparison.OrdinalIgnoreCase) || !entityId.EndsWith("_power", StringComparison.OrdinalIgnoreCase)) { continue; } if (string.Equals(entityId, _powerOptions.MainMeterEntityId, StringComparison.OrdinalIgnoreCase)) { continue; } var entry = _timeline.GetStateAt(entityId, timestamp); var value = ParseDouble(entry?.State); if (value.HasValue) { readings[entityId] = value.Value; } } return readings; } 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; } }