Files
HomeAssistant/HomeAssistant.HistoryReplay/Runners/PowerReplayRunner.cs
T
2026-06-28 13:58:35 +03:00

164 lines
6.3 KiB
C#

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;
namespace HomeAssistant.HistoryReplay.Runners;
public sealed class PowerReplayRunner : IMonitorReplayRunner
{
private readonly HistoryTimeline _timeline;
private readonly ReplayTimeProvider _timeProvider;
private readonly ReplayTimeline _replayTimeline;
private readonly ReplayDataSeries _dataSeries;
private readonly IOtherPowerCalculationService _calculationService;
private readonly IPowerCostCalculationService _costService;
private readonly ILogger<PowerReplayRunner> _logger;
private readonly ReplayOptions _replayOptions;
private readonly PowerMonitorOptions _powerOptions;
public string MonitorName => "Power";
public PowerReplayRunner(
HistoryTimeline timeline,
ReplayTimeProvider timeProvider,
ReplayTimeline replayTimeline,
ReplayDataSeries dataSeries,
IOtherPowerCalculationService calculationService,
IPowerCostCalculationService costService,
ILogger<PowerReplayRunner> logger,
IOptions<ReplayOptions> replayOptions,
IOptions<PowerMonitorOptions> powerOptions)
{
_timeline = timeline;
_timeProvider = timeProvider;
_replayTimeline = replayTimeline;
_dataSeries = dataSeries;
_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);
_dataSeries.AddPoint(MonitorName, "TotalPower", currentTime, calculation.TotalPowerWatts);
_dataSeries.AddPoint(MonitorName, "KnownDevices", currentTime, calculation.KnownDevicesSumWatts);
_dataSeries.AddPoint(MonitorName, "OtherPower", currentTime, calculation.SmoothedOtherPowerWatts);
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<string, double> DiscoverAndReadDevicePower(DateTimeOffset timestamp)
{
var readings = new Dictionary<string, double>();
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;
}
}