feat: add BatteryMonitor implementation with discovery, notification, and scheduling services

This commit is contained in:
Marius
2026-04-01 10:55:33 +03:00
parent 11c2574235
commit 6e4d684359
114 changed files with 22820 additions and 527 deletions
@@ -0,0 +1,210 @@
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;
using BoilerMonitorManager.Models;
namespace HomeAssistant.HistoryReplay.Runners;
public sealed class BoilerReplayRunner : IMonitorReplayRunner
{
private readonly HistoryTimeline _timeline;
private readonly ReplayTimeProvider _timeProvider;
private readonly ReplayTimeline _replayTimeline;
private readonly IBoilerControlService _boilerControlService;
private readonly IBoilerRunTimeTracker _tracker;
private readonly IWaterReadyService _waterReadyService;
private readonly ILogger<BoilerReplayRunner> _logger;
private readonly ReplayOptions _replayOptions;
private readonly BoilerMonitorOptions _boilerOptions;
public string MonitorName => "Boiler";
public BoilerReplayRunner(
HistoryTimeline timeline,
ReplayTimeProvider timeProvider,
ReplayTimeline replayTimeline,
IBoilerControlService boilerControlService,
IBoilerRunTimeTracker tracker,
IWaterReadyService waterReadyService,
ILogger<BoilerReplayRunner> logger,
IOptions<ReplayOptions> replayOptions,
IOptions<BoilerMonitorOptions> boilerOptions)
{
_timeline = timeline;
_timeProvider = timeProvider;
_replayTimeline = replayTimeline;
_boilerControlService = boilerControlService;
_tracker = tracker;
_waterReadyService = waterReadyService;
_logger = logger;
_replayOptions = replayOptions.Value;
_boilerOptions = boilerOptions.Value;
}
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 = ReadConfigEntityState(
BoilerMonitorConsts.ConfigPowerEntityId, _replayOptions.StartTime);
var boilerSwitchEntityId = ReadConfigEntityState(
BoilerMonitorConsts.ConfigSwitchEntityId, _replayOptions.StartTime);
if (string.IsNullOrEmpty(boilerPowerEntityId) || string.IsNullOrEmpty(boilerSwitchEntityId))
{
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = currentTime,
Monitor = MonitorName,
EventType = ReplayEventType.Warning,
Message = "Boiler not configured (missing power/switch entity IDs), skipping replay"
});
return Task.CompletedTask;
}
var configThresholdState = ReadConfigEntityState(
BoilerMonitorConsts.ConfigHeatingThresholdEntityId, _replayOptions.StartTime);
if (!string.IsNullOrEmpty(configThresholdState) &&
double.TryParse(configThresholdState, CultureInfo.InvariantCulture, out var configuredThreshold))
{
heatingThreshold = configuredThreshold;
}
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 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);
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 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;
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()
};
_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();
}
}
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 string? ReadConfigEntityState(string entityId, DateTimeOffset timestamp)
{
var entry = _timeline.GetStateAt(entityId, timestamp);
return entry?.State;
}
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;
}
}
@@ -0,0 +1,7 @@
namespace HomeAssistant.HistoryReplay.Runners;
public interface IMonitorReplayRunner
{
string MonitorName { get; }
Task RunAsync(CancellationToken cancellationToken = default);
}
@@ -0,0 +1,175 @@
using HomeAssistant.HistoryReplay.Configuration;
using HomeAssistant.HistoryReplay.HistoryData;
using HomeAssistant.HistoryReplay.Replay;
using HomeAssistant.HistoryReplay.Reporting;
using LightMonitor.Models;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using LightMonitorManager.Models;
namespace HomeAssistant.HistoryReplay.Runners;
public sealed class LightReplayRunner : IMonitorReplayRunner
{
private readonly HistoryTimeline _timeline;
private readonly ReplayTimeProvider _timeProvider;
private readonly ReplayTimeline _replayTimeline;
private readonly ILogger<LightReplayRunner> _logger;
private readonly ReplayOptions _replayOptions;
private readonly LightMonitorOptions _lightOptions;
public string MonitorName => "Light";
public LightReplayRunner(
HistoryTimeline timeline,
ReplayTimeProvider timeProvider,
ReplayTimeline replayTimeline,
ILogger<LightReplayRunner> logger,
IOptions<ReplayOptions> replayOptions,
IOptions<LightMonitorOptions> lightOptions)
{
_timeline = timeline;
_timeProvider = timeProvider;
_replayTimeline = replayTimeline;
_logger = logger;
_replayOptions = replayOptions.Value;
_lightOptions = lightOptions.Value;
}
public Task RunAsync(CancellationToken cancellationToken = default)
{
_logger.LogInformation("Starting Light replay");
ReplaySunEvents(cancellationToken);
ReplayPersonArrivals(cancellationToken);
_logger.LogInformation("Light replay complete");
return Task.CompletedTask;
}
private void ReplaySunEvents(CancellationToken cancellationToken)
{
var sunHistory = _timeline.GetEntityHistory(_lightOptions.SunEntityId);
string? previousSunState = null;
foreach (var entry in sunHistory)
{
if (cancellationToken.IsCancellationRequested) break;
if (entry.LastChanged < _replayOptions.StartTime || entry.LastChanged > _replayOptions.EndTime)
{
continue;
}
if (string.Equals(entry.State, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase) &&
!string.Equals(previousSunState, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase))
{
_timeProvider.AdvanceTo(entry.LastChanged);
var anyoneHome = IsAnyoneHome(entry.LastChanged);
var lightState = _timeline.GetStateAt(_lightOptions.LightEntityId, entry.LastChanged)?.State;
var lightAlreadyOn = string.Equals(lightState, LightMonitorConsts.LightOnState, StringComparison.OrdinalIgnoreCase);
if (anyoneHome && !lightAlreadyOn)
{
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = entry.LastChanged,
Monitor = MonitorName,
EventType = ReplayEventType.Decision,
Message = "TURN ON light (sun below horizon + someone home)"
});
}
else if (!anyoneHome)
{
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = entry.LastChanged,
Monitor = MonitorName,
EventType = ReplayEventType.Info,
Message = "Sun below horizon but nobody home — light stays off"
});
}
else
{
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = entry.LastChanged,
Monitor = MonitorName,
EventType = ReplayEventType.Info,
Message = "Sun below horizon but light already on"
});
}
}
previousSunState = entry.State;
}
}
private void ReplayPersonArrivals(CancellationToken cancellationToken)
{
foreach (var personEntityId in _lightOptions.PersonEntityIds)
{
var personHistory = _timeline.GetEntityHistory(personEntityId);
string? previousState = null;
foreach (var entry in personHistory)
{
if (cancellationToken.IsCancellationRequested) break;
if (entry.LastChanged < _replayOptions.StartTime || entry.LastChanged > _replayOptions.EndTime)
{
continue;
}
if (string.Equals(entry.State, LightMonitorConsts.PersonHomeState, StringComparison.OrdinalIgnoreCase) &&
!string.Equals(previousState, LightMonitorConsts.PersonHomeState, StringComparison.OrdinalIgnoreCase))
{
_timeProvider.AdvanceTo(entry.LastChanged);
var sunEntry = _timeline.GetStateAt(_lightOptions.SunEntityId, entry.LastChanged);
var isDark = string.Equals(sunEntry?.State, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase);
var lightState = _timeline.GetStateAt(_lightOptions.LightEntityId, entry.LastChanged)?.State;
var lightAlreadyOn = string.Equals(lightState, LightMonitorConsts.LightOnState, StringComparison.OrdinalIgnoreCase);
if (isDark && !lightAlreadyOn)
{
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = entry.LastChanged,
Monitor = MonitorName,
EventType = ReplayEventType.Decision,
Message = $"TURN ON light ({personEntityId} arrived home + dark outside)"
});
}
else if (isDark)
{
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = entry.LastChanged,
Monitor = MonitorName,
EventType = ReplayEventType.Info,
Message = $"{personEntityId} arrived home (dark) but light already on"
});
}
}
previousState = entry.State;
}
}
}
private bool IsAnyoneHome(DateTimeOffset timestamp)
{
foreach (var personEntityId in _lightOptions.PersonEntityIds)
{
var entry = _timeline.GetStateAt(personEntityId, timestamp);
if (string.Equals(entry?.State, LightMonitorConsts.PersonHomeState, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
}
@@ -0,0 +1,171 @@
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 ICheapestIntervalsFinder _cheapestIntervalsFinder;
private readonly ILogger<NordPoolReplayRunner> _logger;
private readonly ReplayOptions _options;
public string MonitorName => "NordPool";
public NordPoolReplayRunner(
HistoryTimeline timeline,
ReplayTimeProvider timeProvider,
ReplayTimeline replayTimeline,
ICheapestIntervalsFinder cheapestIntervalsFinder,
ILogger<NordPoolReplayRunner> logger,
IOptions<ReplayOptions> options)
{
_timeline = timeline;
_timeProvider = timeProvider;
_replayTimeline = replayTimeline;
_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(NordPoolConsts.CurrentPriceEntityId, currentTime);
if (priceEntry?.State is not null &&
double.TryParse(priceEntry.State, CultureInfo.InvariantCulture, out var currentPrice))
{
if (lastReportedPrice is null || Math.Abs(currentPrice - lastReportedPrice.Value) > 0.001)
{
_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);
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 };
}
}
@@ -0,0 +1,158 @@
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<PowerReplayRunner> _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<PowerReplayRunner> logger,
IOptions<ReplayOptions> replayOptions,
IOptions<PowerMonitorOptions> 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<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;
}
}
@@ -0,0 +1,126 @@
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 ShowerMonitor.Models.Enums;
using ShowerMonitorManager.Interface;
using ShowerMonitorManager.Models;
namespace HomeAssistant.HistoryReplay.Runners;
public sealed class ShowerReplayRunner : IMonitorReplayRunner
{
private readonly HistoryTimeline _timeline;
private readonly ReplayTimeProvider _timeProvider;
private readonly ReplayTimeline _replayTimeline;
private readonly IShowerDetectionService _detectionService;
private readonly IExhaustFanControlService _fanControlService;
private readonly ILogger<ShowerReplayRunner> _logger;
private readonly ReplayOptions _replayOptions;
private readonly ShowerMonitorOptions _showerOptions;
public string MonitorName => "Shower";
public ShowerReplayRunner(
HistoryTimeline timeline,
ReplayTimeProvider timeProvider,
ReplayTimeline replayTimeline,
IShowerDetectionService detectionService,
IExhaustFanControlService fanControlService,
ILogger<ShowerReplayRunner> logger,
IOptions<ReplayOptions> replayOptions,
IOptions<ShowerMonitorOptions> showerOptions)
{
_timeline = timeline;
_timeProvider = timeProvider;
_replayTimeline = replayTimeline;
_detectionService = detectionService;
_fanControlService = fanControlService;
_logger = logger;
_replayOptions = replayOptions.Value;
_showerOptions = showerOptions.Value;
}
public Task RunAsync(CancellationToken cancellationToken = default)
{
_logger.LogInformation("Starting Shower replay");
var currentTime = _replayOptions.StartTime;
var pollInterval = TimeSpan.FromSeconds(_showerOptions.PollIntervalSeconds);
var previousState = ShowerState.Idle;
while (currentTime <= _replayOptions.EndTime && !cancellationToken.IsCancellationRequested)
{
_timeProvider.AdvanceTo(currentTime);
var bathroomEntry = _timeline.GetStateAt(_showerOptions.BathroomHumidityEntityId, currentTime);
var homeEntry = _timeline.GetStateAt(_showerOptions.MainHomeHumidityEntityId, currentTime);
var bathroomHumidity = ParseDouble(bathroomEntry?.State);
var homeHumidity = ParseDouble(homeEntry?.State);
if (bathroomHumidity.HasValue && homeHumidity.HasValue)
{
var state = _detectionService.Evaluate(bathroomHumidity.Value, homeHumidity.Value, currentTime);
var differential = bathroomHumidity.Value - homeHumidity.Value;
_fanControlService.Evaluate(state, currentTime);
if (state != previousState)
{
var eventType = state switch
{
ShowerState.Active => ReplayEventType.Decision,
ShowerState.Completed => ReplayEventType.StateChange,
_ => ReplayEventType.Info
};
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = currentTime,
Monitor = MonitorName,
EventType = eventType,
Message = $"State: {previousState} → {state} (bathroom: {bathroomHumidity.Value:F1}%, home: {homeHumidity.Value:F1}%, diff: {differential:F1}%)",
Details = GetStateChangeDetails(state)
});
previousState = state;
}
}
currentTime = currentTime.Add(pollInterval);
}
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = _replayOptions.EndTime,
Monitor = MonitorName,
EventType = ReplayEventType.Info,
Message = $"Final: {_detectionService.TodaySessionCount} session(s) detected"
});
_logger.LogInformation("Shower replay complete");
return Task.CompletedTask;
}
private string? GetStateChangeDetails(ShowerState state) =>
state switch
{
ShowerState.Completed when _detectionService.LastCompletedSession is not null =>
$"Duration: {_detectionService.LastCompletedSession.Duration:mm\\:ss}, Peak humidity: {_detectionService.LastCompletedSession.PeakHumidity:F1}%",
_ => null
};
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;
}
}