feat: add BatteryMonitor implementation with discovery, notification, and scheduling services
This commit is contained in:
@@ -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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user