This commit is contained in:
2026-06-28 13:58:35 +03:00
parent 8f45028715
commit e6bf8258bb
114 changed files with 4365 additions and 874 deletions
@@ -0,0 +1,19 @@
<!DOCTYPE html>
<html lang="en" data-bs-theme="dark">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>HA History Replay</title>
<base href="/" />
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" />
<link href="css/app.css" rel="stylesheet" />
<HeadOutlet @rendermode="InteractiveServer" />
</head>
<body>
<Routes @rendermode="InteractiveServer" />
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="_framework/blazor.web.js"></script>
<script src="_content/Blazor-ApexCharts/js/apexcharts.esm.js" type="module"></script>
<script src="_content/Blazor-ApexCharts/js/blazor-apexcharts.js"></script>
</body>
</html>
@@ -0,0 +1,44 @@
@code {
[Parameter] public ReplayDataSeries? DataSeries { get; set; }
private List<ReplayDataPoint> PowerData => DataSeries?.GetSeries("Boiler", "PowerWatts").ToList() ?? [];
private List<ReplayDataPoint> BudgetData => DataSeries?.GetSeries("Boiler", "BudgetPercent").ToList() ?? [];
private List<ReplayDataPoint> SwitchData => DataSeries?.GetSeries("Boiler", "SwitchState").ToList() ?? [];
private ApexChartOptions<ReplayDataPoint> ChartOptions => new()
{
Chart = new Chart { Background = "transparent", ForeColor = "#adb5bd" },
Theme = new Theme { Mode = Mode.Dark },
Stroke = new Stroke { Width = 2 },
Xaxis = new XAxis { Type = XAxisType.Datetime },
Yaxis =
[
new YAxis { Title = new AxisTitle { Text = "Watts" }, SeriesName = "Power (W)", DecimalsInFloat = 0 },
new YAxis { Title = new AxisTitle { Text = "%" }, SeriesName = "Budget %", Opposite = true, Max = 100, DecimalsInFloat = 0 }
],
Tooltip = new Tooltip { X = new TooltipX { Format = "HH:mm" } },
Grid = new Grid { BorderColor = "#343a40" }
};
}
@if (PowerData.Count > 0)
{
<ApexChart TItem="ReplayDataPoint" Options="ChartOptions" Height="300">
<ApexPointSeries TItem="ReplayDataPoint"
Items="PowerData"
SeriesType="SeriesType.Area"
Name="Power (W)"
XValue="p => p.Timestamp.ToLocalTime().DateTime"
YValue="p => (decimal)p.Value" />
<ApexPointSeries TItem="ReplayDataPoint"
Items="BudgetData"
SeriesType="SeriesType.Line"
Name="Budget %"
XValue="p => p.Timestamp.ToLocalTime().DateTime"
YValue="p => (decimal)p.Value" />
</ApexChart>
}
else
{
<div class="text-muted text-center py-4">No boiler data available</div>
}
@@ -0,0 +1,30 @@
@code {
[Parameter] public ReplayTimeline? Timeline { get; set; }
private IReadOnlyList<ReplayEvent> LightEvents =>
Timeline?.GetEventsByMonitor("Light") ?? [];
}
<div class="card bg-dark">
<div class="card-body">
@if (LightEvents.Count > 0)
{
<div class="d-flex flex-column gap-2">
@foreach (var evt in LightEvents)
{
var iconClass = evt.EventType == ReplayEventType.Decision ? "text-warning" : "text-muted";
var icon = evt.EventType == ReplayEventType.Decision ? "&#9728;" : "&#8226;";
<div class="d-flex align-items-start gap-2">
<span class="font-monospace small text-nowrap">@evt.Timestamp.ToLocalTime().ToString("HH:mm")</span>
<span class="@iconClass">@((MarkupString)icon)</span>
<span class="small">@evt.Message</span>
</div>
}
</div>
}
else
{
<div class="text-muted text-center py-4">No light events</div>
}
</div>
</div>
@@ -0,0 +1,32 @@
@code {
[Parameter] public ReplayDataSeries? DataSeries { get; set; }
private List<ReplayDataPoint> PriceData => DataSeries?.GetSeries("NordPool", "Price").ToList() ?? [];
private ApexChartOptions<ReplayDataPoint> ChartOptions => new()
{
Chart = new Chart { Background = "transparent", ForeColor = "#adb5bd" },
Theme = new Theme { Mode = Mode.Dark },
Stroke = new Stroke { Curve = Curve.Smooth, Width = 2 },
Xaxis = new XAxis { Type = XAxisType.Datetime },
Yaxis = [new YAxis { Title = new AxisTitle { Text = "ct/kWh" }, DecimalsInFloat = 2 }],
Tooltip = new Tooltip { X = new TooltipX { Format = "HH:mm" } },
Grid = new Grid { BorderColor = "#343a40" }
};
}
@if (PriceData.Count > 0)
{
<ApexChart TItem="ReplayDataPoint" Options="ChartOptions" Height="300">
<ApexPointSeries TItem="ReplayDataPoint"
Items="PriceData"
SeriesType="SeriesType.Area"
Name="Price (ct/kWh)"
XValue="p => p.Timestamp.ToLocalTime().DateTime"
YValue="p => (decimal)p.Value" />
</ApexChart>
}
else
{
<div class="text-muted text-center py-4">No price data available</div>
}
@@ -0,0 +1,40 @@
@code {
[Parameter] public ReplayDataSeries? DataSeries { get; set; }
private List<ReplayDataPoint> TotalData => DataSeries?.GetSeries("Power", "TotalPower").ToList() ?? [];
private List<ReplayDataPoint> KnownData => DataSeries?.GetSeries("Power", "KnownDevices").ToList() ?? [];
private List<ReplayDataPoint> OtherData => DataSeries?.GetSeries("Power", "OtherPower").ToList() ?? [];
private ApexChartOptions<ReplayDataPoint> ChartOptions => new()
{
Chart = new Chart { Background = "transparent", ForeColor = "#adb5bd", Stacked = true },
Theme = new Theme { Mode = Mode.Dark },
Stroke = new Stroke { Width = 1 },
Xaxis = new XAxis { Type = XAxisType.Datetime },
Yaxis = [new YAxis { Title = new AxisTitle { Text = "Watts" }, DecimalsInFloat = 0 }],
Tooltip = new Tooltip { X = new TooltipX { Format = "HH:mm:ss" } },
Grid = new Grid { BorderColor = "#343a40" }
};
}
@if (TotalData.Count > 0)
{
<ApexChart TItem="ReplayDataPoint" Options="ChartOptions" Height="300">
<ApexPointSeries TItem="ReplayDataPoint"
Items="KnownData"
SeriesType="SeriesType.Area"
Name="Known Devices"
XValue="p => p.Timestamp.ToLocalTime().DateTime"
YValue="p => (decimal)p.Value" />
<ApexPointSeries TItem="ReplayDataPoint"
Items="OtherData"
SeriesType="SeriesType.Area"
Name="Other Power"
XValue="p => p.Timestamp.ToLocalTime().DateTime"
YValue="p => (decimal)p.Value" />
</ApexChart>
}
else
{
<div class="text-muted text-center py-4">No power data available</div>
}
@@ -0,0 +1,46 @@
@code {
[Parameter] public ReplayDataSeries? DataSeries { get; set; }
private List<ReplayDataPoint> BathroomData => DataSeries?.GetSeries("Shower", "BathroomHumidity").ToList() ?? [];
private List<ReplayDataPoint> HomeData => DataSeries?.GetSeries("Shower", "HomeHumidity").ToList() ?? [];
private List<ReplayDataPoint> DiffData => DataSeries?.GetSeries("Shower", "Differential").ToList() ?? [];
private ApexChartOptions<ReplayDataPoint> ChartOptions => new()
{
Chart = new Chart { Background = "transparent", ForeColor = "#adb5bd" },
Theme = new Theme { Mode = Mode.Dark },
Stroke = new Stroke { Curve = Curve.Smooth, Width = 2 },
Xaxis = new XAxis { Type = XAxisType.Datetime },
Yaxis = [new YAxis { Title = new AxisTitle { Text = "Humidity %" }, DecimalsInFloat = 1 }],
Tooltip = new Tooltip { X = new TooltipX { Format = "HH:mm" } },
Grid = new Grid { BorderColor = "#343a40" }
};
}
@if (BathroomData.Count > 0)
{
<ApexChart TItem="ReplayDataPoint" Options="ChartOptions" Height="300">
<ApexPointSeries TItem="ReplayDataPoint"
Items="BathroomData"
SeriesType="SeriesType.Line"
Name="Bathroom Humidity"
XValue="p => p.Timestamp.ToLocalTime().DateTime"
YValue="p => (decimal)p.Value" />
<ApexPointSeries TItem="ReplayDataPoint"
Items="HomeData"
SeriesType="SeriesType.Line"
Name="Home Humidity"
XValue="p => p.Timestamp.ToLocalTime().DateTime"
YValue="p => (decimal)p.Value" />
<ApexPointSeries TItem="ReplayDataPoint"
Items="DiffData"
SeriesType="SeriesType.Area"
Name="Differential"
XValue="p => p.Timestamp.ToLocalTime().DateTime"
YValue="p => (decimal)p.Value" />
</ApexChart>
}
else
{
<div class="text-muted text-center py-4">No shower data available</div>
}
@@ -0,0 +1,17 @@
@inherits LayoutComponentBase
<div class="d-flex flex-column min-vh-100">
<nav class="navbar navbar-dark bg-dark border-bottom border-secondary px-3">
<span class="navbar-brand mb-0 h1">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" class="bi bi-house-door me-2" viewBox="0 0 16 16">
<path d="M8.354 1.146a.5.5 0 0 0-.708 0l-6 6A.5.5 0 0 0 1.5 7.5v7a.5.5 0 0 0 .5.5h4.5a.5.5 0 0 0 .5-.5v-4h2v4a.5.5 0 0 0 .5.5H14a.5.5 0 0 0 .5-.5v-7a.5.5 0 0 0-.146-.354L13 5.793V2.5a.5.5 0 0 0-.5-.5h-1a.5.5 0 0 0-.5.5v1.293zM2.5 14V7.707l5.5-5.5 5.5 5.5V14H10v-4a.5.5 0 0 0-.5-.5h-3a.5.5 0 0 0-.5.5v4z"/>
</svg>
HA History Replay
</span>
<span class="text-muted small">Debug Dashboard</span>
</nav>
<main class="flex-grow-1 p-3">
@Body
</main>
</div>
@@ -0,0 +1,240 @@
@page "/"
@inject ReplayOrchestrationService Replay
@implements IDisposable
<h4 class="mb-3">History Replay Dashboard</h4>
<div class="card mb-3">
<div class="card-body">
<div class="row g-3 align-items-end">
<div class="col-md-3">
<label class="form-label small">Start Time</label>
<input type="datetime-local" class="form-control form-control-sm"
@bind="_startTime" />
</div>
<div class="col-md-3">
<label class="form-label small">End Time</label>
<input type="datetime-local" class="form-control form-control-sm"
@bind="_endTime" />
</div>
<div class="col-md-4">
<label class="form-label small">Monitors</label>
<div class="d-flex gap-3 flex-wrap">
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" @bind="_monitors.NordPool" id="chkNord" />
<label class="form-check-label small" for="chkNord">NordPool</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" @bind="_monitors.Boiler" id="chkBoiler" />
<label class="form-check-label small" for="chkBoiler">Boiler</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" @bind="_monitors.Shower" id="chkShower" />
<label class="form-check-label small" for="chkShower">Shower</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" @bind="_monitors.Power" id="chkPower" />
<label class="form-check-label small" for="chkPower">Power</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" @bind="_monitors.Light" id="chkLight" />
<label class="form-check-label small" for="chkLight">Light</label>
</div>
</div>
</div>
<div class="col-md-2">
<button class="btn btn-primary w-100" @onclick="RunReplay"
disabled="@(_isRunning)">
@if (_isRunning)
{
<span class="spinner-border spinner-border-sm me-1" role="status"></span>
}
Run Replay
</button>
</div>
</div>
</div>
</div>
<div class="status-bar mb-3">
@switch (Replay.Status)
{
case ReplayStatus.FetchingHistory:
<div class="alert alert-info py-2 mb-0 d-flex align-items-center">
<span class="spinner-border spinner-border-sm me-2"></span>
@(Replay.ProgressMessage ?? "Fetching history data from Home Assistant...")
</div>
break;
case ReplayStatus.Running:
<div class="alert alert-info py-2 mb-0 d-flex align-items-center">
<span class="spinner-border spinner-border-sm me-2"></span>
@(Replay.ProgressMessage ?? "Running replay...")
</div>
break;
case ReplayStatus.Completed:
<div class="alert alert-success py-2 mb-0">
Replay completed -- @Replay.Timeline.GetAllEvents().Count event(s)
</div>
break;
case ReplayStatus.Failed:
<div class="alert alert-danger py-2 mb-0">
Replay failed: @Replay.ErrorMessage
</div>
break;
}
</div>
@if (Replay.Status == ReplayStatus.Completed)
{
<SummaryCards Timeline="Replay.Timeline" />
<ul class="nav nav-tabs mb-3" role="tablist">
@foreach (var monitor in _enabledMonitors)
{
var tab = monitor;
<li class="nav-item" role="presentation">
<button class="nav-link @(tab == _activeTab ? "active" : "")"
@onclick="() => SetActiveTab(tab)">
@tab
</button>
</li>
}
<li class="nav-item" role="presentation">
<button class="nav-link @(_activeTab == ServiceCallsTab ? "active" : "")"
@onclick="() => SetActiveTab(ServiceCallsTab)">
Service Calls
</button>
</li>
</ul>
<div class="tab-content">
@if (_activeTab == NordPoolTab)
{
<div class="card mb-3">
<div class="card-header">NordPool Price Timeline</div>
<div class="card-body"><NordPoolChart DataSeries="Replay.DataSeries" /></div>
</div>
<EventTable Events="GetMonitorEvents(NordPoolTab)" />
}
else if (_activeTab == BoilerTab)
{
<div class="card mb-3">
<div class="card-header">Boiler Power and Budget</div>
<div class="card-body"><BoilerChart DataSeries="Replay.DataSeries" /></div>
</div>
<EventTable Events="GetMonitorEvents(BoilerTab)" />
}
else if (_activeTab == ShowerTab)
{
<div class="card mb-3">
<div class="card-header">Humidity and Shower Detection</div>
<div class="card-body"><ShowerChart DataSeries="Replay.DataSeries" /></div>
</div>
<EventTable Events="GetMonitorEvents(ShowerTab)" />
}
else if (_activeTab == PowerTab)
{
<div class="card mb-3">
<div class="card-header">Power Breakdown</div>
<div class="card-body"><PowerChart DataSeries="Replay.DataSeries" /></div>
</div>
<EventTable Events="GetMonitorEvents(PowerTab)" />
}
else if (_activeTab == LightTab)
{
<div class="card mb-3">
<div class="card-header">Light Control Events</div>
<div class="card-body"><LightChart Timeline="Replay.Timeline" /></div>
</div>
<EventTable Events="GetMonitorEvents(LightTab)" />
}
else if (_activeTab == ServiceCallsTab)
{
<EventTable Events="GetMonitorEvents(ServiceCallMonitor)" />
}
</div>
}
@code {
private const string NordPoolTab = "NordPool";
private const string BoilerTab = "Boiler";
private const string ShowerTab = "Shower";
private const string PowerTab = "Power";
private const string LightTab = "Light";
private const string ServiceCallsTab = "ServiceCalls";
private const string ServiceCallMonitor = "ServiceCall";
private DateTime _startTime = DateTime.Today.AddDays(-1);
private DateTime _endTime = DateTime.Today.AddHours(23).AddMinutes(59);
private readonly ReplayMonitorFlags _monitors = new();
private bool _isRunning;
private string _activeTab = NordPoolTab;
private IReadOnlyList<string> _enabledMonitors = [];
protected override void OnInitialized()
{
Replay.OnStateChanged += HandleStateChanged;
}
private IReadOnlyList<ReplayEvent> GetMonitorEvents(string monitor) =>
Replay.Timeline.GetEventsByMonitor(monitor);
private void SetActiveTab(string tab)
{
_activeTab = tab;
StateHasChanged();
}
private async Task RunReplay()
{
_isRunning = true;
_enabledMonitors = BuildEnabledMonitors();
_activeTab = _enabledMonitors.FirstOrDefault() ?? NordPoolTab;
var start = new DateTimeOffset(_startTime, TimeZoneInfo.Local.GetUtcOffset(_startTime));
var end = new DateTimeOffset(_endTime, TimeZoneInfo.Local.GetUtcOffset(_endTime));
try
{
await Task.Run(async () =>
await Replay.RunReplayAsync(start, end, _monitors));
}
catch (Exception ex)
{
Replay.SetError(ex.Message);
}
finally
{
_isRunning = false;
await InvokeAsync(StateHasChanged);
}
}
private IReadOnlyList<string> BuildEnabledMonitors()
{
var list = new List<string>();
if (_monitors.NordPool) list.Add(NordPoolTab);
if (_monitors.Boiler) list.Add(BoilerTab);
if (_monitors.Shower) list.Add(ShowerTab);
if (_monitors.Power) list.Add(PowerTab);
if (_monitors.Light) list.Add(LightTab);
return list;
}
private async void HandleStateChanged()
{
try
{
await InvokeAsync(StateHasChanged);
}
catch (ObjectDisposedException)
{
// Component was disposed while an update was in flight
}
}
public void Dispose()
{
Replay.OnStateChanged -= HandleStateChanged;
}
}
@@ -0,0 +1,6 @@
<Router AppAssembly="typeof(Program).Assembly">
<Found Context="routeData">
<RouteView RouteData="routeData" DefaultLayout="typeof(Layout.MainLayout)" />
<FocusOnNavigate RouteData="routeData" Selector="h1" />
</Found>
</Router>
@@ -0,0 +1,54 @@
@code {
[Parameter] public IReadOnlyList<ReplayEvent> Events { get; set; } = [];
[Parameter] public int MaxRows { get; set; } = 200;
private string GetBadgeClass(ReplayEventType type) => type switch
{
ReplayEventType.Decision => "badge-decision",
ReplayEventType.StateChange => "badge-statechange",
ReplayEventType.Warning => "badge-warning",
ReplayEventType.Anomaly => "badge-anomaly",
ReplayEventType.ServiceCall => "badge-servicecall",
_ => "badge-info"
};
}
@if (Events.Count == 0)
{
<div class="text-muted text-center py-4">No events recorded for this monitor.</div>
}
else
{
<div class="table-responsive" style="max-height: 400px; overflow-y: auto;">
<table class="table table-sm table-hover align-middle mb-0">
<thead class="sticky-top" style="background-color: #2b3035;">
<tr>
<th style="width: 100px;">Time</th>
<th style="width: 100px;">Type</th>
<th>Message</th>
<th>Details</th>
</tr>
</thead>
<tbody>
@foreach (var evt in Events.Take(MaxRows))
{
<tr>
<td class="text-nowrap font-monospace small">
@evt.Timestamp.ToLocalTime().ToString("HH:mm:ss")
</td>
<td>
<span class="badge @GetBadgeClass(evt.EventType)">@evt.EventType</span>
</td>
<td class="small">@evt.Message</td>
<td class="text-muted small">@evt.Details</td>
</tr>
}
</tbody>
</table>
</div>
@if (Events.Count > MaxRows)
{
<div class="text-muted small mt-1">Showing @MaxRows of @Events.Count events</div>
}
}
@@ -0,0 +1,53 @@
@code {
[Parameter] public ReplayTimeline? Timeline { get; set; }
private IReadOnlyList<ReplayEvent> AllEvents => Timeline?.GetAllEvents() ?? [];
private int TotalEvents => AllEvents.Count;
private int Decisions => AllEvents.Count(e => e.EventType == ReplayEventType.Decision);
private int ServiceCalls => AllEvents.Count(e => e.EventType == ReplayEventType.ServiceCall);
private int Warnings => AllEvents.Count(e => e.EventType == ReplayEventType.Warning);
private int Anomalies => AllEvents.Count(e => e.EventType == ReplayEventType.Anomaly);
}
<div class="row g-3 mb-4">
<div class="col">
<div class="card stat-card">
<div class="card-body">
<div class="display-6">@TotalEvents</div>
<div class="text-muted small">Total Events</div>
</div>
</div>
</div>
<div class="col">
<div class="card stat-card border-success">
<div class="card-body">
<div class="display-6 text-success">@Decisions</div>
<div class="text-muted small">Decisions</div>
</div>
</div>
</div>
<div class="col">
<div class="card stat-card border-info">
<div class="card-body">
<div class="display-6 text-info">@ServiceCalls</div>
<div class="text-muted small">Service Calls</div>
</div>
</div>
</div>
<div class="col">
<div class="card stat-card border-warning">
<div class="card-body">
<div class="display-6 text-warning">@Warnings</div>
<div class="text-muted small">Warnings</div>
</div>
</div>
</div>
<div class="col">
<div class="card stat-card border-danger">
<div class="card-body">
<div class="display-6 text-danger">@Anomalies</div>
<div class="text-muted small">Anomalies</div>
</div>
</div>
</div>
</div>
@@ -0,0 +1,15 @@
@using System.Net.Http
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using static Microsoft.AspNetCore.Components.Web.RenderMode
@using Microsoft.AspNetCore.Components.Web.Virtualization
@using Microsoft.JSInterop
@using ApexCharts
@using HomeAssistant.HistoryReplay.Components
@using HomeAssistant.HistoryReplay.Components.Layout
@using HomeAssistant.HistoryReplay.Components.Shared
@using HomeAssistant.HistoryReplay.Components.Charts
@using HomeAssistant.HistoryReplay.Reporting
@using HomeAssistant.HistoryReplay.Services
@using HomeAssistant.HistoryReplay.Configuration
@@ -24,6 +24,7 @@ public static class ReplayEntityMap
"sensor.nordpool_cheapest_intervals",
BoilerMonitorConsts.SkipPriceCapEntityId,
BoilerMonitorConsts.BudgetOverrideEntityId,
BoilerMonitorConsts.AutoManagementEntityId,
BoilerMonitorConsts.BoilerDailyHoursEntityId
];
@@ -46,6 +47,11 @@ public static class ReplayEntityMap
return entities;
}
public static IReadOnlyList<string> GetEntitiesRequiringAttributes() =>
[
"sensor.nordpool_cheapest_intervals"
];
public static IReadOnlyList<string> GetAllEntities(
string boilerPowerEntityId,
string boilerSwitchEntityId,
@@ -66,4 +72,38 @@ public static class ReplayEntityMap
return [.. all];
}
public static (IReadOnlyList<string> MinimalEntities, IReadOnlyList<string> FullEntities) GetPartitionedEntities(
string boilerPowerEntityId,
string boilerSwitchEntityId,
string bathroomHumidityEntityId,
string mainHomeHumidityEntityId,
string mainMeterEntityId,
string sunEntityId,
string lightEntityId,
string[] personEntityIds)
{
var allEntities = GetAllEntities(
boilerPowerEntityId, boilerSwitchEntityId,
bathroomHumidityEntityId, mainHomeHumidityEntityId,
mainMeterEntityId, sunEntityId, lightEntityId, personEntityIds);
var fullSet = new HashSet<string>(GetEntitiesRequiringAttributes(), StringComparer.OrdinalIgnoreCase);
var minimal = new List<string>();
var full = new List<string>();
foreach (var entity in allEntities)
{
if (fullSet.Contains(entity))
{
full.Add(entity);
}
else
{
minimal.Add(entity);
}
}
return (minimal, full);
}
}
@@ -3,6 +3,7 @@ namespace HomeAssistant.HistoryReplay.HistoryData;
public sealed class HistoryTimeline
{
private readonly Dictionary<string, List<HistoryStateEntry>> _entityTimelines = new(StringComparer.OrdinalIgnoreCase);
private bool _sorted;
public void AddEntries(string entityId, IEnumerable<HistoryStateEntry> entries)
{
@@ -13,7 +14,41 @@ public sealed class HistoryTimeline
}
list.AddRange(entries);
list.Sort((a, b) => a.LastChanged.CompareTo(b.LastChanged));
_sorted = false;
}
public void AddEntriesBulk(string entityId, List<HistoryStateEntry> entries)
{
if (entries.Count == 0)
{
return;
}
if (!_entityTimelines.TryGetValue(entityId, out var list))
{
_entityTimelines[entityId] = entries;
}
else
{
list.AddRange(entries);
}
_sorted = false;
}
public void FinalizeSort()
{
if (_sorted)
{
return;
}
foreach (var entries in _entityTimelines.Values)
{
entries.Sort((a, b) => a.LastChanged.CompareTo(b.LastChanged));
}
_sorted = true;
}
public HistoryStateEntry? GetStateAt(string entityId, DateTimeOffset timestamp)
@@ -23,20 +58,8 @@ public sealed class HistoryTimeline
return null;
}
HistoryStateEntry? best = null;
foreach (var entry in entries)
{
if (entry.LastChanged <= timestamp)
{
best = entry;
}
else
{
break;
}
}
return best;
var index = BinarySearchFloor(entries, timestamp);
return index >= 0 ? entries[index] : null;
}
public IReadOnlyList<DateTimeOffset> GetAllTimestamps()
@@ -62,4 +85,34 @@ public sealed class HistoryTimeline
}
public int TotalEntryCount => _entityTimelines.Values.Sum(e => e.Count);
public void Clear()
{
_entityTimelines.Clear();
_sorted = false;
}
private static int BinarySearchFloor(List<HistoryStateEntry> entries, DateTimeOffset timestamp)
{
var lo = 0;
var hi = entries.Count - 1;
var result = -1;
while (lo <= hi)
{
var mid = lo + (hi - lo) / 2;
if (entries[mid].LastChanged <= timestamp)
{
result = mid;
lo = mid + 1;
}
else
{
hi = mid - 1;
}
}
return result;
}
}
@@ -9,63 +9,230 @@ public sealed class HomeAssistantHistoryProvider(
IHomeAssistantApiClient client,
ILogger<HomeAssistantHistoryProvider> logger) : IHistoryDataProvider
{
private const int MaxEntitiesPerRequest = 10;
private const int MaxEntitiesPerBatch = 5;
private const int MaxConcurrentRequests = 20;
private const int MaxRetryAttempts = 3;
private static readonly TimeSpan InitialRetryDelay = TimeSpan.FromSeconds(2);
public async Task<HistoryTimeline> FetchHistoryAsync(
public Task<HistoryTimeline> FetchHistoryAsync(
IReadOnlyList<string> entityIds,
DateTimeOffset startTime,
DateTimeOffset endTime,
CancellationToken cancellationToken = default)
{
return FetchHistoryAsync(
minimalEntityIds: entityIds,
fullEntityIds: [],
startTime, endTime, cancellationToken);
}
public async Task<HistoryTimeline> FetchHistoryAsync(
IReadOnlyList<string> minimalEntityIds,
IReadOnlyList<string> fullEntityIds,
DateTimeOffset startTime,
DateTimeOffset endTime,
CancellationToken cancellationToken = default)
{
var timeline = new HistoryTimeline();
var batches = ChunkEntities(entityIds, MaxEntitiesPerRequest);
var allEntityCount = minimalEntityIds.Count + fullEntityIds.Count;
var tasks = batches.Select(batch => FetchBatchAsync(batch, startTime, endTime, cancellationToken));
var results = await Task.WhenAll(tasks).ConfigureAwait(false);
var minimalBatches = ChunkEntities(minimalEntityIds, MaxEntitiesPerBatch);
var fullBatches = ChunkEntities(fullEntityIds, MaxEntitiesPerBatch);
foreach (var batchTimeline in results)
logger.LogInformation(
"Fetching history in {MinBatchCount}+{FullBatchCount} batch(es) for {MinCount} minimal + {FullCount} full entities",
minimalBatches.Count, fullBatches.Count, minimalEntityIds.Count, fullEntityIds.Count);
var failedEntities = new List<string>();
using var semaphore = new SemaphoreSlim(MaxConcurrentRequests);
var minimalTasks = minimalBatches.Select(batch => FetchBatchThrottledAsync(
batch, startTime, endTime, minimalResponse: true, semaphore, cancellationToken));
var fullTasks = fullBatches.Select(batch => FetchBatchThrottledAsync(
batch, startTime, endTime, minimalResponse: false, semaphore, cancellationToken));
var results = await Task.WhenAll(minimalTasks.Concat(fullTasks)).ConfigureAwait(false);
foreach (var batchResult in results)
{
foreach (var entityId in batchTimeline.GetEntityIds())
foreach (var (entityId, entries) in batchResult.Entries)
{
timeline.AddEntries(entityId, batchTimeline.GetEntityHistory(entityId));
timeline.AddEntriesBulk(entityId, entries);
}
failedEntities.AddRange(batchResult.FailedEntityIds);
}
if (failedEntities.Count > 0)
{
logger.LogWarning("Retrying {Count} failed entities individually: {Entities}", failedEntities.Count, string.Join(", ", failedEntities));
var individualResults = await FetchEntitiesIndividuallyAsync(failedEntities, startTime, endTime, cancellationToken);
foreach (var (entityId, entries) in individualResults)
{
timeline.AddEntriesBulk(entityId, entries);
}
}
timeline.FinalizeSort();
logger.LogInformation(
"Fetched history for {EntityCount} entities: {EntryCount} total entries ({Start} to {End})",
entityIds.Count, timeline.TotalEntryCount, startTime, endTime);
allEntityCount, timeline.TotalEntryCount, startTime, endTime);
return timeline;
}
private async Task<HistoryTimeline> FetchBatchAsync(
private async Task<BatchFetchResult> FetchBatchThrottledAsync(
IReadOnlyList<string> batch,
DateTimeOffset startTime,
DateTimeOffset endTime,
bool minimalResponse,
SemaphoreSlim semaphore,
CancellationToken cancellationToken)
{
await semaphore.WaitAsync(cancellationToken);
try
{
return await FetchBatchWithRetryAsync(batch, startTime, endTime, minimalResponse, cancellationToken);
}
finally
{
semaphore.Release();
}
}
private async Task<BatchFetchResult> FetchBatchWithRetryAsync(
IReadOnlyList<string> entityIds,
DateTimeOffset startTime,
DateTimeOffset endTime,
bool minimalResponse,
CancellationToken cancellationToken)
{
var entityIdsString = string.Join(",", entityIds);
for (var attempt = 1; attempt <= MaxRetryAttempts; attempt++)
{
logger.LogDebug("Fetching history batch (attempt {Attempt}/{MaxAttempts}, minimal={Minimal}) for: {Entities}",
attempt, MaxRetryAttempts, minimalResponse, entityIdsString);
try
{
var response = await client.GetHistoryAsync(
entityIdsString, startTime, endTime, minimalResponse, cancellationToken)
.ConfigureAwait(false);
var entries = new List<(string, List<HistoryStateEntry>)>();
ParseHistoryResponse(response, entries);
return new BatchFetchResult(entries, []);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
throw;
}
catch (Exception ex) when (IsTransientFailure(ex) && attempt < MaxRetryAttempts)
{
var delay = InitialRetryDelay * Math.Pow(2, attempt - 1);
logger.LogWarning(ex,
"Transient failure fetching batch (attempt {Attempt}/{MaxAttempts}), retrying in {Delay}s: {Entities}",
attempt, MaxRetryAttempts, delay.TotalSeconds, entityIdsString);
await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
logger.LogError(ex,
"Failed to fetch history batch after {Attempt} attempt(s): {Entities}",
attempt, entityIdsString);
return new BatchFetchResult([], entityIds.ToList());
}
}
return new BatchFetchResult([], entityIds.ToList());
}
private async Task<List<(string EntityId, List<HistoryStateEntry> Entries)>> FetchEntitiesIndividuallyAsync(
IReadOnlyList<string> entityIds,
DateTimeOffset startTime,
DateTimeOffset endTime,
CancellationToken cancellationToken)
{
var timeline = new HistoryTimeline();
var entityIdsString = string.Join(",", entityIds);
var allEntries = new List<(string, List<HistoryStateEntry>)>();
using var semaphore = new SemaphoreSlim(MaxConcurrentRequests);
logger.LogDebug("Fetching history batch for: {Entities}", entityIdsString);
try
var tasks = entityIds.Select(async entityId =>
{
var result = await client.GetHistoryAsync(
entityIdsString, startTime, endTime, minimalResponse: false, cancellationToken)
.ConfigureAwait(false);
await semaphore.WaitAsync(cancellationToken);
try
{
return await FetchSingleEntityWithRetryAsync(entityId, startTime, endTime, cancellationToken);
}
finally
{
semaphore.Release();
}
});
ParseHistoryResponse(result, timeline);
}
catch (Exception ex)
var results = await Task.WhenAll(tasks).ConfigureAwait(false);
foreach (var result in results)
{
logger.LogError(ex, "Failed to fetch history for entities: {Entities}", entityIdsString);
allEntries.AddRange(result);
}
return timeline;
return allEntries;
}
private void ParseHistoryResponse(JsonElement response, HistoryTimeline timeline)
private async Task<List<(string EntityId, List<HistoryStateEntry> Entries)>> FetchSingleEntityWithRetryAsync(
string entityId,
DateTimeOffset startTime,
DateTimeOffset endTime,
CancellationToken cancellationToken)
{
for (var attempt = 1; attempt <= MaxRetryAttempts; attempt++)
{
try
{
var response = await client.GetHistoryAsync(
entityId, startTime, endTime, minimalResponse: false, cancellationToken)
.ConfigureAwait(false);
var entries = new List<(string, List<HistoryStateEntry>)>();
ParseHistoryResponse(response, entries);
return entries;
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
throw;
}
catch (Exception ex) when (IsTransientFailure(ex) && attempt < MaxRetryAttempts)
{
var delay = InitialRetryDelay * Math.Pow(2, attempt - 1);
logger.LogWarning(ex,
"Transient failure fetching {EntityId} (attempt {Attempt}/{MaxAttempts}), retrying in {Delay}s",
entityId, attempt, MaxRetryAttempts, delay.TotalSeconds);
await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
logger.LogError(ex,
"Failed to fetch history for entity {EntityId} after {Attempt} attempt(s)",
entityId, attempt);
return [];
}
}
return [];
}
private static bool IsTransientFailure(Exception ex) =>
ex is HttpRequestException or TaskCanceledException or TimeoutException
or IOException;
private static void ParseHistoryResponse(
JsonElement response,
List<(string EntityId, List<HistoryStateEntry> Entries)> result)
{
if (response.ValueKind != JsonValueKind.Array)
{
@@ -79,25 +246,37 @@ public sealed class HomeAssistantHistoryProvider(
continue;
}
string? currentEntityId = null;
var entries = new List<HistoryStateEntry>();
foreach (var stateObj in entityArray.EnumerateArray())
{
var entry = ParseStateEntry(stateObj);
if (entry is not null)
var entry = ParseStateEntry(stateObj, currentEntityId);
if (entry is null)
{
timeline.AddEntries(entry.EntityId, [entry]);
continue;
}
currentEntityId ??= entry.EntityId;
entries.Add(entry);
}
if (currentEntityId is not null && entries.Count > 0)
{
result.Add((currentEntityId, entries));
}
}
}
private HistoryStateEntry? ParseStateEntry(JsonElement stateObj)
private static HistoryStateEntry? ParseStateEntry(JsonElement stateObj, string? fallbackEntityId)
{
if (!stateObj.TryGetProperty("entity_id", out var entityIdProp))
string? entityId = null;
if (stateObj.TryGetProperty("entity_id", out var entityIdProp))
{
return null;
entityId = entityIdProp.GetString();
}
var entityId = entityIdProp.GetString();
entityId ??= fallbackEntityId;
if (string.IsNullOrEmpty(entityId))
{
return null;
@@ -105,16 +284,13 @@ public sealed class HomeAssistantHistoryProvider(
var state = stateObj.TryGetProperty("state", out var stateProp) ? stateProp.GetString() : null;
DateTimeOffset lastChanged;
if (stateObj.TryGetProperty("last_changed", out var lastChangedProp))
if (!stateObj.TryGetProperty("last_changed", out var lastChangedProp))
{
if (!DateTimeOffset.TryParse(lastChangedProp.GetString(), CultureInfo.InvariantCulture,
DateTimeStyles.RoundtripKind, out lastChanged))
{
return null;
}
return null;
}
else
if (!DateTimeOffset.TryParse(lastChangedProp.GetString(), CultureInfo.InvariantCulture,
DateTimeStyles.RoundtripKind, out var lastChanged))
{
return null;
}
@@ -159,10 +335,13 @@ public sealed class HomeAssistantHistoryProvider(
for (var i = 0; i < entities.Count; i += chunkSize)
{
var chunk = entities.Skip(i).Take(chunkSize).ToList();
chunks.Add(chunk);
chunks.Add(entities.Skip(i).Take(chunkSize).ToList());
}
return chunks;
}
private sealed record BatchFetchResult(
List<(string EntityId, List<HistoryStateEntry> Entries)> Entries,
List<string> FailedEntityIds);
}
@@ -7,4 +7,11 @@ public interface IHistoryDataProvider
DateTimeOffset startTime,
DateTimeOffset endTime,
CancellationToken cancellationToken = default);
Task<HistoryTimeline> FetchHistoryAsync(
IReadOnlyList<string> minimalEntityIds,
IReadOnlyList<string> fullEntityIds,
DateTimeOffset startTime,
DateTimeOffset endTime,
CancellationToken cancellationToken = default);
}
@@ -1,7 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>14.0</LangVersion>
<Nullable>enable</Nullable>
@@ -10,22 +9,10 @@
</PropertyGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="appsettings.development.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
<CopyToPublishDirectory>Never</CopyToPublishDirectory>
</None>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="10.0.5" />
<PackageReference Include="Microsoft.Extensions.Http" Version="10.0.5" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.5" />
<PackageReference Include="Blazor-ApexCharts" Version="4.0.0" />
<PackageReference Include="Microsoft.AspNetCore.App.Internal.Assets" Version="10.0.5" />
<PackageReference Include="NetDaemon.HassModel" Version="26.11.0" />
<PackageReference Include="Serilog.Extensions.Hosting" Version="10.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.1.1" />
</ItemGroup>
<ItemGroup>
@@ -12,10 +12,8 @@ public sealed class HomeAssistantApiClient : IHomeAssistantApiClient
{
_httpClient = httpClient;
_httpClient.BaseAddress = settings.Value.BaseUrl;
_httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", settings.Value.Token);
_httpClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", settings.Value.Token);
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
_httpClient.Timeout = TimeSpan.FromSeconds(HomeAssistantSettings.DefaultTimeoutSeconds);
}
@@ -30,10 +28,14 @@ public sealed class HomeAssistantApiClient : IHomeAssistantApiClient
var path = $"/api/history/period/{start:O}?filter_entity_id={Uri.EscapeDataString(entityIds)}";
if (endTime.HasValue)
{
path += $"&end_time={Uri.EscapeDataString(endTime.Value.ToString("O"))}";
}
if (minimalResponse)
{
path += "&minimal_response";
}
return await GetJsonAsync(path, cancellationToken).ConfigureAwait(false);
}
@@ -45,6 +47,7 @@ public sealed class HomeAssistantApiClient : IHomeAssistantApiClient
await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
var doc = await JsonDocument.ParseAsync(stream, cancellationToken: cancellationToken).ConfigureAwait(false);
return doc.RootElement.Clone();
}
}
@@ -4,7 +4,7 @@ public sealed class HomeAssistantSettings
{
public const string SectionName = "HomeAssistant";
public const int DefaultPort = 8123;
public const int DefaultTimeoutSeconds = 30;
public const int DefaultTimeoutSeconds = 3600;
public string Host { get; set; } = string.Empty;
public int Port { get; set; } = DefaultPort;
+47 -161
View File
@@ -2,21 +2,14 @@ using BoilerMonitorManager;
using BoilerMonitorManager.Interface;
using BoilerMonitorManager.Models;
using HomeAssistant.Entities.Interfaces;
using HomeAssistant.HistoryReplay.Configuration;
using HomeAssistant.HistoryReplay.Components;
using HomeAssistant.HistoryReplay.HistoryData;
using HomeAssistant.HistoryReplay.Replay;
using HomeAssistant.HistoryReplay.Reporting;
using HomeAssistant.HistoryReplay.Runners;
using HomeAssistant.HistoryReplay.HomeAssistantClient;
using HomeAssistant.HistoryReplay.Replay;
using HomeAssistant.HistoryReplay.Services;
using LightMonitorManager.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NordPoolManager;
using NordPoolManager.Interface;
using PowerMonitorManager;
using PowerMonitorManager.Interface;
using PowerMonitorManager.Models;
using Serilog;
using ShowerMonitorManager;
@@ -25,167 +18,60 @@ using ShowerMonitorManager.Models;
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Information()
.WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
.WriteTo.Console()
.CreateLogger();
try
var builder = WebApplication.CreateBuilder(args);
builder.WebHost.UseStaticWebAssets();
builder.Services.AddLogging(logging =>
{
Log.Information("Starting Home Assistant History Replay");
logging.ClearProviders();
logging.AddSerilog(dispose: true);
});
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false)
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") ?? "Production"}.json", optional: true)
.AddEnvironmentVariables()
.Build();
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents();
var services = new ServiceCollection();
builder.Services.Configure<HomeAssistantSettings>(
builder.Configuration.GetSection(HomeAssistantSettings.SectionName));
builder.Services.Configure<BoilerMonitorOptions>(
builder.Configuration.GetSection(BoilerMonitorOptions.SectionName));
builder.Services.Configure<ShowerMonitorOptions>(
builder.Configuration.GetSection(ShowerMonitorOptions.SectionName));
builder.Services.Configure<PowerMonitorOptions>(
builder.Configuration.GetSection(PowerMonitorOptions.SectionName));
builder.Services.Configure<LightMonitorOptions>(
builder.Configuration.GetSection(LightMonitorOptions.SectionName));
services.AddLogging(builder =>
{
builder.ClearProviders();
builder.AddSerilog(dispose: true);
});
builder.Services.AddHttpClient<IHomeAssistantApiClient, HomeAssistantApiClient>();
builder.Services.AddSingleton<IHistoryDataProvider, HomeAssistantHistoryProvider>();
services.Configure<HomeAssistantSettings>(configuration.GetSection(HomeAssistantSettings.SectionName));
services.Configure<ReplayOptions>(configuration.GetSection(ReplayOptions.SectionName));
services.Configure<BoilerMonitorOptions>(configuration.GetSection(BoilerMonitorOptions.SectionName));
services.Configure<ShowerMonitorOptions>(configuration.GetSection(ShowerMonitorOptions.SectionName));
services.Configure<PowerMonitorOptions>(configuration.GetSection(PowerMonitorOptions.SectionName));
services.Configure<LightMonitorOptions>(configuration.GetSection(LightMonitorOptions.SectionName));
builder.Services.AddSingleton<IEntityManager, NoOpEntityManager>();
builder.Services.AddSingleton<ICheapestIntervalsFinder, CheapestIntervalsFinder>();
builder.Services.AddSingleton<IBoilerControlService, BoilerControlService>();
services.AddHttpClient<IHomeAssistantApiClient, HomeAssistantApiClient>();
services.AddSingleton<IHistoryDataProvider, HomeAssistantHistoryProvider>();
var showerOpts = builder.Configuration
.GetSection(ShowerMonitorOptions.SectionName)
.Get<ShowerMonitorOptions>() ?? new ShowerMonitorOptions();
builder.Services.AddSingleton<IHumidityRateCalculator>(_ => new HumidityRateCalculator(showerOpts.RateWindowSize));
var replayOptions = configuration.GetSection(ReplayOptions.SectionName).Get<ReplayOptions>() ?? new ReplayOptions();
builder.Services.AddSingleton<ReplayOrchestrationService>();
var replayTimeline = new ReplayTimeline();
var replayTimeProvider = new ReplayTimeProvider(replayOptions.StartTime);
var app = builder.Build();
services.AddSingleton(replayTimeline);
services.AddSingleton(replayTimeProvider);
services.AddSingleton<TimeProvider>(replayTimeProvider);
services.AddSingleton<IEntityManager, NoOpEntityManager>();
services.AddSingleton<ICheapestIntervalsFinder, CheapestIntervalsFinder>();
services.AddSingleton<IBoilerControlService, BoilerControlService>();
services.AddSingleton<IBoilerRunTimeTracker, BoilerRunTimeTracker>();
services.AddSingleton<IWaterReadyService, WaterReadyService>();
services.AddSingleton<IOtherPowerCalculationService, OtherPowerCalculationService>();
services.AddSingleton<IPowerCostCalculationService, PowerCostCalculationService>();
var showerOptions = configuration.GetSection(ShowerMonitorOptions.SectionName).Get<ShowerMonitorOptions>() ?? new ShowerMonitorOptions();
services.AddSingleton<IHumidityRateCalculator>(_ => new HumidityRateCalculator(showerOptions.RateWindowSize));
services.AddSingleton<IShowerDetectionService, ShowerDetectionService>();
services.AddSingleton<ConsoleReportRenderer>();
var provider = services.BuildServiceProvider();
var historyProvider = provider.GetRequiredService<IHistoryDataProvider>();
var logger = provider.GetRequiredService<ILogger<Program>>();
var boilerOpts = provider.GetRequiredService<IOptions<BoilerMonitorOptions>>().Value;
var showerOpts = provider.GetRequiredService<IOptions<ShowerMonitorOptions>>().Value;
var powerOpts = provider.GetRequiredService<IOptions<PowerMonitorOptions>>().Value;
var lightOpts = provider.GetRequiredService<IOptions<LightMonitorOptions>>().Value;
logger.LogInformation("Replay period: {Start} to {End}", replayOptions.StartTime, replayOptions.EndTime);
var allEntityIds = ReplayEntityMap.GetAllEntities(
boilerPowerEntityId: "sensor.boiler_power",
boilerSwitchEntityId: "switch.boiler",
bathroomHumidityEntityId: showerOpts.BathroomHumidityEntityId,
mainHomeHumidityEntityId: showerOpts.MainHomeHumidityEntityId,
mainMeterEntityId: powerOpts.MainMeterEntityId,
sunEntityId: lightOpts.SunEntityId,
lightEntityId: lightOpts.LightEntityId,
personEntityIds: lightOpts.PersonEntityIds);
logger.LogInformation("Fetching history for {Count} entities...", allEntityIds.Count);
var timeline = await historyProvider.FetchHistoryAsync(
allEntityIds, replayOptions.StartTime, replayOptions.EndTime);
var replayHaContext = new ReplayHaContext(
timeline,
replayTimeProvider,
replayTimeline,
provider.GetRequiredService<ILogger<ReplayHaContext>>());
var fanControlService = new ExhaustFanControlService(
replayHaContext,
provider.GetRequiredService<ILogger<ExhaustFanControlService>>(),
provider.GetRequiredService<IOptions<ShowerMonitorOptions>>());
var runners = new List<IMonitorReplayRunner>();
if (replayOptions.Monitors.NordPool)
{
runners.Add(new NordPoolReplayRunner(
timeline, replayTimeProvider, replayTimeline,
provider.GetRequiredService<ICheapestIntervalsFinder>(),
provider.GetRequiredService<ILogger<NordPoolReplayRunner>>(),
provider.GetRequiredService<IOptions<ReplayOptions>>()));
}
if (replayOptions.Monitors.Boiler)
{
runners.Add(new BoilerReplayRunner(
timeline, replayTimeProvider, replayTimeline,
provider.GetRequiredService<IBoilerControlService>(),
provider.GetRequiredService<IBoilerRunTimeTracker>(),
provider.GetRequiredService<IWaterReadyService>(),
provider.GetRequiredService<ILogger<BoilerReplayRunner>>(),
provider.GetRequiredService<IOptions<ReplayOptions>>(),
provider.GetRequiredService<IOptions<BoilerMonitorOptions>>()));
}
if (replayOptions.Monitors.Shower)
{
runners.Add(new ShowerReplayRunner(
timeline, replayTimeProvider, replayTimeline,
provider.GetRequiredService<IShowerDetectionService>(),
fanControlService,
provider.GetRequiredService<ILogger<ShowerReplayRunner>>(),
provider.GetRequiredService<IOptions<ReplayOptions>>(),
provider.GetRequiredService<IOptions<ShowerMonitorOptions>>()));
}
if (replayOptions.Monitors.Power)
{
runners.Add(new PowerReplayRunner(
timeline, replayTimeProvider, replayTimeline,
provider.GetRequiredService<IOtherPowerCalculationService>(),
provider.GetRequiredService<IPowerCostCalculationService>(),
provider.GetRequiredService<ILogger<PowerReplayRunner>>(),
provider.GetRequiredService<IOptions<ReplayOptions>>(),
provider.GetRequiredService<IOptions<PowerMonitorOptions>>()));
}
if (replayOptions.Monitors.Light)
{
runners.Add(new LightReplayRunner(
timeline, replayTimeProvider, replayTimeline,
provider.GetRequiredService<ILogger<LightReplayRunner>>(),
provider.GetRequiredService<IOptions<ReplayOptions>>(),
provider.GetRequiredService<IOptions<LightMonitorOptions>>()));
}
logger.LogInformation("Running {Count} monitor replay(s) in parallel...", runners.Count);
var replayTasks = runners.Select(r => Task.Run(() => r.RunAsync()));
await Task.WhenAll(replayTasks);
var renderer = provider.GetRequiredService<ConsoleReportRenderer>();
renderer.Render(replayTimeline, replayOptions);
}
catch (Exception ex)
if (!app.Environment.IsDevelopment())
{
Log.Fatal(ex, "History replay failed");
}
finally
{
await Log.CloseAndFlushAsync();
app.UseHsts();
}
app.MapStaticAssets();
app.UseAntiforgery();
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode();
Log.Information("History Replay Dashboard running at {Urls}", string.Join(", ", app.Urls));
app.Run();
@@ -0,0 +1,13 @@
{
"profiles": {
"HomeAssistant.HistoryReplay": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": false,
"applicationUrl": "http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
+243
View File
@@ -0,0 +1,243 @@
# HomeAssistant.HistoryReplay
A debugging tool that fetches real historical data from your Home Assistant instance and replays it through the monitor business logic to verify decisions without side effects.
## Prerequisites
- .NET 10 SDK
- A running Home Assistant instance with the History API enabled
- A [long-lived access token](https://www.home-assistant.io/docs/authentication/#your-account-profile) from Home Assistant
## Quick Start
### 1. Configure the connection
Edit `appsettings.json` (or create `appsettings.development.json` for local overrides):
```json
{
"HomeAssistant": {
"Host": "homeassistant.local",
"Port": 8123,
"Token": "<your-long-lived-access-token>",
"Ssl": false
}
}
```
> **Security note:** Never commit your access token. Use `appsettings.development.json` (already in `.gitignore`) or environment variables instead.
### 2. Set the replay time range
```json
{
"Replay": {
"StartTime": "2026-03-30T00:00:00+02:00",
"EndTime": "2026-03-31T00:00:00+02:00"
}
}
```
Times are in ISO 8601 format with timezone offset. The tool fetches all entity history within this window from the HA REST API (`/api/history/period`).
### 3. Enable or disable monitors
```json
{
"Replay": {
"Monitors": {
"NordPool": true,
"Boiler": true,
"Shower": true,
"Power": false,
"Light": true
}
}
}
```
Set any monitor to `false` to skip it during replay.
### 4. Run
```bash
dotnet run --project HomeAssistant.HistoryReplay
```
Or from the project directory:
```bash
cd HomeAssistant.HistoryReplay
dotnet run
```
## What It Does
The tool replays historical entity states through the **real business logic services** from each monitor project:
| Monitor | Services Used | What It Shows |
|---------|--------------|---------------|
| **NordPool** | `CheapestIntervalsFinder` | Price changes, cheap interval identification |
| **Boiler** | `BoilerControlService`, `WaterReadyService`, `BoilerRunTimeTracker` | Turn on/off decisions, water-ready detection, runtime tracking, budget usage |
| **Shower** | `ShowerDetectionService`, `ExhaustFanControlService`, `HumidityRateCalculator` | Shower state transitions (Idle/Suspected/Active/Declining/Completed), fan control |
| **Power** | `OtherPowerCalculationService`, `PowerCostCalculationService` | Power breakdown, cost accumulation, anomaly detection |
| **Light** | Event-driven replay of sun/person state changes | Light-on decisions based on sunset and person arrivals |
### No side effects
- **No MQTT entities** are created or updated
- **No HA service calls** are executed (they are logged as "would call" events)
- **No NetDaemon runtime** is required
- The tool only reads from the HA History API
## Console Output
The tool produces a colored timeline report:
```
═══════════════════════════════════════════════════════════
REPLAY: 2026-03-30 00:00 -> 2026-03-31 00:00
═══════════════════════════════════════════════════════════
-- NordPool ──────────────────────────────────────────────
00:00 Price: 3.21 ct/kWh
00:15 Price: 3.18 ct/kWh
00:15 -> CHEAP interval active (rank #2, price: 3.18 ct/kWh)
-- Boiler ────────────────────────────────────────────────
00:15 -> TURN ON (cheap: True, water ready: False, budget: 0%)
01:30 Water ready detected (power: 3.2W, threshold: 5.0W)
01:30 -> TURN OFF (cheap: True, water ready: True, budget: 42%)
23:59 Final: 01:15:00 total runtime, 2 session(s)
-- Shower ────────────────────────────────────────────────
07:12 State: Idle -> Suspected (bathroom: 62.1%, home: 53.0%, diff: 9.1%)
07:14 State: Suspected -> Active (bathroom: 65.3%, home: 53.0%, diff: 12.3%)
07:35 State: Declining -> Completed (bathroom: 58.2%, home: 54.1%, diff: 4.1%)
-- Service Calls ─────────────────────────────────────────
00:15 -> Would call switch.turn_on on switch.boiler
01:30 -> Would call switch.turn_off on switch.boiler
═══════════════════════════════════════════════════════════
REPLAY SUMMARY
═══════════════════════════════════════════════════════════
Total events: 24
Decisions: 5
Service calls: 4
Warnings: 0
Anomalies: 0
```
## Configuration Reference
### Monitor-specific settings
The monitor sections (`BoilerMonitor`, `ShowerMonitor`, `PowerMonitor`, `LightMonitor`) use the **same options classes** as the production `HomeAssistant.Server` project. This means thresholds, entity IDs, and poll intervals match what runs in production.
#### ShowerMonitor
| Setting | Default | Description |
|---------|---------|-------------|
| `BathroomHumidityEntityId` | `sensor.bathroom_humidity` | Bathroom humidity sensor |
| `MainHomeHumidityEntityId` | `sensor.main_home_humidity` | Reference home humidity sensor |
| `PollIntervalSeconds` | `30` | Replay step interval |
| `SpikeRateThreshold` | `4.0` | Humidity rate (%/min) to trigger suspected state |
| `MinDifferentialHumidity` | `8.0` | Minimum bathroom-vs-home humidity difference |
| `PeakHumidityThreshold` | `58.0` | Humidity to confirm active shower |
#### PowerMonitor
| Setting | Default | Description |
|---------|---------|-------------|
| `MainMeterEntityId` | *(required)* | Main power meter entity |
| `PollIntervalSeconds` | `1` | Replay step interval |
| `AnomalyThresholdWatts` | `500` | "Other" power threshold for anomaly detection |
| `SmoothingWindowSize` | `10` | EMA window for smoothing |
#### LightMonitor
| Setting | Default | Description |
|---------|---------|-------------|
| `LightEntityId` | `light.sonoff_1002214d40` | The light entity to control |
| `SunEntityId` | `sun.sun` | Sun entity for below-horizon detection |
| `PersonEntityIds` | `[...]` | Person entities for presence detection |
### Environment-based configuration
You can override any setting via environment variables using the `__` separator:
```bash
set Replay__StartTime=2026-03-29T00:00:00+02:00
set HomeAssistant__Token=your_token_here
dotnet run --project HomeAssistant.HistoryReplay
```
## Project Architecture
```
HomeAssistant.HistoryReplay/
├── Program.cs Entry point, DI wiring, orchestration
├── HomeAssistantClient/ Self-contained HA REST API client
│ ├── IHomeAssistantApiClient.cs
│ ├── HomeAssistantApiClient.cs
│ └── HomeAssistantSettings.cs
├── Configuration/
│ ├── ReplayOptions.cs Time range and monitor flags
│ └── ReplayEntityMap.cs Maps monitors to required HA entity IDs
├── HistoryData/
│ ├── IHistoryDataProvider.cs Abstraction for fetching history
│ ├── HomeAssistantHistoryProvider.cs Fetches from /api/history/period
│ ├── HistoryTimeline.cs Sorted timeline of entity states
│ └── HistoryStateEntry.cs Single entity state snapshot
├── Replay/
│ ├── ReplayHaContext.cs IHaContext backed by historical data
│ ├── ReplayTimeProvider.cs TimeProvider that steps through time
│ └── NoOpEntityManager.cs IEntityManager that logs but does nothing
├── Runners/
│ ├── IMonitorReplayRunner.cs Common runner interface
│ ├── NordPoolReplayRunner.cs Price + cheapest interval replay
│ ├── BoilerReplayRunner.cs Boiler control decision replay
│ ├── ShowerReplayRunner.cs Shower detection state machine replay
│ ├── PowerReplayRunner.cs Power calculation + cost replay
│ └── LightReplayRunner.cs Sun/person event-driven replay
├── Reporting/
│ ├── ReplayEvent.cs Single decision/event during replay
│ ├── ReplayTimeline.cs Collected events across all monitors
│ └── ConsoleReportRenderer.cs Colored console output
└── appsettings.json Configuration
```
### Key design: real services, fake infrastructure
The replay instantiates **actual production business logic** (e.g., `BoilerControlService.DetermineAction()`, `ShowerDetectionService.Evaluate()`) but replaces infrastructure with replay stubs:
- `ReplayHaContext` implements `IHaContext` by returning historical state at the current replay timestamp
- `ReplayTimeProvider` extends `TimeProvider` for time-dependent logic (e.g., `WaterReadyService` cooldown periods)
- `NoOpEntityManager` implements `IEntityManager` and logs all calls without side effects
- Service calls via `IHaContext.CallService()` are captured as replay events
All five monitors run their replays **in parallel** via `Task.WhenAll`.
## Troubleshooting
### "History replay failed" with HTTP errors
- Verify your HA host, port, and token in `appsettings.json`
- Ensure the HA History API is enabled (it is by default)
- Check that the token has sufficient permissions
### No events in the output for a monitor
- The entity IDs in the monitor config must match your actual HA entities
- Check that history data exists for the configured time range (HA purges old history based on the recorder settings)
- Verify the monitor is enabled in `Replay.Monitors`
### Shower monitor shows no sessions
- Confirm `BathroomHumidityEntityId` and `MainHomeHumidityEntityId` have data in the replay period
- Adjust `SpikeRateThreshold` and `MinDifferentialHumidity` if your bathroom has different humidity characteristics
### Boiler shows "not configured"
- The boiler replay reads config entity states (`text.boilermonitor_config_power_entity_id`, `text.boilermonitor_config_switch_entity_id`) from history. These must have been set in HA during the replay period.
@@ -105,9 +105,20 @@ public sealed class ConsoleReportRenderer
var stateChanges = events.Count(e => e.EventType == ReplayEventType.StateChange);
var parts = new List<string>();
if (decisions > 0) parts.Add($"{decisions} decision(s)");
if (stateChanges > 0) parts.Add($"{stateChanges} state change(s)");
if (warnings > 0) parts.Add($"{warnings} warning(s)");
if (decisions > 0)
{
parts.Add($"{decisions} decision(s)");
}
if (stateChanges > 0)
{
parts.Add($"{stateChanges} state change(s)");
}
if (warnings > 0)
{
parts.Add($"{warnings} warning(s)");
}
if (parts.Count > 0)
{
@@ -0,0 +1,9 @@
namespace HomeAssistant.HistoryReplay.Reporting;
public sealed class ReplayDataPoint
{
public required DateTimeOffset Timestamp { get; init; }
public required string Monitor { get; init; }
public required string Series { get; init; }
public required double Value { get; init; }
}
@@ -0,0 +1,50 @@
using System.Collections.Concurrent;
namespace HomeAssistant.HistoryReplay.Reporting;
public sealed class ReplayDataSeries
{
private readonly ConcurrentBag<ReplayDataPoint> _points = [];
public void AddPoint(ReplayDataPoint point)
{
_points.Add(point);
}
public void AddPoint(string monitor, string series, DateTimeOffset timestamp, double value)
{
_points.Add(new ReplayDataPoint
{
Monitor = monitor,
Series = series,
Timestamp = timestamp,
Value = value
});
}
public IReadOnlyList<ReplayDataPoint> GetSeries(string monitor, string series) =>
_points
.Where(p => string.Equals(p.Monitor, monitor, StringComparison.OrdinalIgnoreCase)
&& string.Equals(p.Series, series, StringComparison.OrdinalIgnoreCase))
.OrderBy(p => p.Timestamp)
.ToList();
public IReadOnlyList<ReplayDataPoint> GetAllForMonitor(string monitor) =>
_points
.Where(p => string.Equals(p.Monitor, monitor, StringComparison.OrdinalIgnoreCase))
.OrderBy(p => p.Timestamp)
.ToList();
public IReadOnlyList<string> GetSeriesNames(string monitor) =>
_points
.Where(p => string.Equals(p.Monitor, monitor, StringComparison.OrdinalIgnoreCase))
.Select(p => p.Series)
.Distinct(StringComparer.OrdinalIgnoreCase)
.Order()
.ToList();
public void Clear()
{
_points.Clear();
}
}
@@ -22,4 +22,9 @@ public sealed class ReplayTimeline
public IReadOnlyList<string> GetMonitors() =>
_events.Select(e => e.Monitor).Distinct(StringComparer.OrdinalIgnoreCase).Order().ToList();
public void Clear()
{
_events.Clear();
}
}
@@ -8,7 +8,6 @@ using HomeAssistant.HistoryReplay.Replay;
using HomeAssistant.HistoryReplay.Reporting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using BoilerMonitorManager.Models;
namespace HomeAssistant.HistoryReplay.Runners;
@@ -17,12 +16,14 @@ 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<BoilerReplayRunner> _logger;
private readonly ReplayOptions _replayOptions;
private readonly BoilerMonitorOptions _boilerOptions;
private readonly string _boilerPowerEntityId;
private readonly string _boilerSwitchEntityId;
public string MonitorName => "Boiler";
@@ -30,22 +31,26 @@ public sealed class BoilerReplayRunner : IMonitorReplayRunner
HistoryTimeline timeline,
ReplayTimeProvider timeProvider,
ReplayTimeline replayTimeline,
ReplayDataSeries dataSeries,
IBoilerControlService boilerControlService,
IBoilerRunTimeTracker tracker,
IWaterReadyService waterReadyService,
ILogger<BoilerReplayRunner> logger,
IOptions<ReplayOptions> replayOptions,
IOptions<BoilerMonitorOptions> boilerOptions)
string boilerPowerEntityId,
string boilerSwitchEntityId)
{
_timeline = timeline;
_timeProvider = timeProvider;
_replayTimeline = replayTimeline;
_dataSeries = dataSeries;
_boilerControlService = boilerControlService;
_tracker = tracker;
_waterReadyService = waterReadyService;
_logger = logger;
_replayOptions = replayOptions.Value;
_boilerOptions = boilerOptions.Value;
_boilerPowerEntityId = boilerPowerEntityId;
_boilerSwitchEntityId = boilerSwitchEntityId;
}
public Task RunAsync(CancellationToken cancellationToken = default)
@@ -58,30 +63,8 @@ public sealed class BoilerReplayRunner : IMonitorReplayRunner
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;
}
var boilerPowerEntityId = _boilerPowerEntityId;
var boilerSwitchEntityId = _boilerSwitchEntityId;
while (currentTime <= _replayOptions.EndTime && !cancellationToken.IsCancellationRequested)
{
@@ -92,6 +75,7 @@ public sealed class BoilerReplayRunner : IMonitorReplayRunner
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);
@@ -100,9 +84,20 @@ public sealed class BoilerReplayRunner : IMonitorReplayRunner
_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);
@@ -126,9 +121,17 @@ public sealed class BoilerReplayRunner : IMonitorReplayRunner
? (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);
effectiveIsNowCheap,
waterReady,
boilerSwitchState,
budgetExhausted,
budgetOverride);
if (action != BoilerAction.NoChange && action != lastAction)
{
@@ -139,18 +142,32 @@ public sealed class BoilerReplayRunner : IMonitorReplayRunner
_ => action.ToString()
};
_replayTimeline.AddEvent(new ReplayEvent
if (autoManagementEnabled)
{
Timestamp = currentTime,
Monitor = MonitorName,
EventType = ReplayEventType.Decision,
Message = actionMessage,
Details = $"Power: {boilerPowerWatts:F1}W, Runtime: {snapshot.AccumulatedRunTime:hh\\:mm\\:ss}, Sessions: {snapshot.SessionCount}"
});
_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)
if (action == BoilerAction.TurnOn)
{
_waterReadyService.NotifyTurnedOn();
}
}
else
{
_waterReadyService.NotifyTurnedOn();
_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}"
});
}
}
@@ -171,12 +188,6 @@ public sealed class BoilerReplayRunner : IMonitorReplayRunner
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)
@@ -14,6 +14,7 @@ public sealed class LightReplayRunner : IMonitorReplayRunner
private readonly HistoryTimeline _timeline;
private readonly ReplayTimeProvider _timeProvider;
private readonly ReplayTimeline _replayTimeline;
private readonly ReplayDataSeries _dataSeries;
private readonly ILogger<LightReplayRunner> _logger;
private readonly ReplayOptions _replayOptions;
private readonly LightMonitorOptions _lightOptions;
@@ -24,6 +25,7 @@ public sealed class LightReplayRunner : IMonitorReplayRunner
HistoryTimeline timeline,
ReplayTimeProvider timeProvider,
ReplayTimeline replayTimeline,
ReplayDataSeries dataSeries,
ILogger<LightReplayRunner> logger,
IOptions<ReplayOptions> replayOptions,
IOptions<LightMonitorOptions> lightOptions)
@@ -31,6 +33,7 @@ public sealed class LightReplayRunner : IMonitorReplayRunner
_timeline = timeline;
_timeProvider = timeProvider;
_replayTimeline = replayTimeline;
_dataSeries = dataSeries;
_logger = logger;
_replayOptions = replayOptions.Value;
_lightOptions = lightOptions.Value;
@@ -54,14 +57,20 @@ public sealed class LightReplayRunner : IMonitorReplayRunner
foreach (var entry in sunHistory)
{
if (cancellationToken.IsCancellationRequested) break;
if (cancellationToken.IsCancellationRequested)
{
break;
}
if (entry.LastChanged < _replayOptions.StartTime || entry.LastChanged > _replayOptions.EndTime)
{
continue;
}
if (string.Equals(entry.State, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase) &&
var isBelowHorizon = string.Equals(entry.State, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase);
_dataSeries.AddPoint(MonitorName, "SunBelowHorizon", entry.LastChanged, isBelowHorizon ? 1.0 : 0.0);
if (isBelowHorizon &&
!string.Equals(previousSunState, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase))
{
_timeProvider.AdvanceTo(entry.LastChanged);
@@ -72,6 +81,7 @@ public sealed class LightReplayRunner : IMonitorReplayRunner
if (anyoneHome && !lightAlreadyOn)
{
_dataSeries.AddPoint(MonitorName, "LightOn", entry.LastChanged, 1.0);
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = entry.LastChanged,
@@ -87,7 +97,7 @@ public sealed class LightReplayRunner : IMonitorReplayRunner
Timestamp = entry.LastChanged,
Monitor = MonitorName,
EventType = ReplayEventType.Info,
Message = "Sun below horizon but nobody home — light stays off"
Message = "Sun below horizon but nobody home -- light stays off"
});
}
else
@@ -115,7 +125,10 @@ public sealed class LightReplayRunner : IMonitorReplayRunner
foreach (var entry in personHistory)
{
if (cancellationToken.IsCancellationRequested) break;
if (cancellationToken.IsCancellationRequested)
{
break;
}
if (entry.LastChanged < _replayOptions.StartTime || entry.LastChanged > _replayOptions.EndTime)
{
@@ -134,6 +147,7 @@ public sealed class LightReplayRunner : IMonitorReplayRunner
if (isDark && !lightAlreadyOn)
{
_dataSeries.AddPoint(MonitorName, "LightOn", entry.LastChanged, 1.0);
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = entry.LastChanged,
@@ -169,7 +183,6 @@ public sealed class LightReplayRunner : IMonitorReplayRunner
return true;
}
}
return false;
}
}
@@ -16,16 +16,20 @@ public sealed class NordPoolReplayRunner : IMonitorReplayRunner
private readonly HistoryTimeline _timeline;
private readonly ReplayTimeProvider _timeProvider;
private readonly ReplayTimeline _replayTimeline;
private readonly ReplayDataSeries _dataSeries;
private readonly ICheapestIntervalsFinder _cheapestIntervalsFinder;
private readonly ILogger<NordPoolReplayRunner> _logger;
private readonly ReplayOptions _options;
private const string NordPoolHaSensorId = "sensor.nordpool_kwh_lt_eur_3_10_0";
public string MonitorName => "NordPool";
public NordPoolReplayRunner(
HistoryTimeline timeline,
ReplayTimeProvider timeProvider,
ReplayTimeline replayTimeline,
ReplayDataSeries dataSeries,
ICheapestIntervalsFinder cheapestIntervalsFinder,
ILogger<NordPoolReplayRunner> logger,
IOptions<ReplayOptions> options)
@@ -33,6 +37,7 @@ public sealed class NordPoolReplayRunner : IMonitorReplayRunner
_timeline = timeline;
_timeProvider = timeProvider;
_replayTimeline = replayTimeline;
_dataSeries = dataSeries;
_cheapestIntervalsFinder = cheapestIntervalsFinder;
_logger = logger;
_options = options.Value;
@@ -50,11 +55,15 @@ public sealed class NordPoolReplayRunner : IMonitorReplayRunner
{
_timeProvider.AdvanceTo(currentTime);
var priceEntry = _timeline.GetStateAt(NordPoolConsts.CurrentPriceEntityId, currentTime);
var priceEntry = _timeline.GetStateAt(NordPoolHaSensorId, currentTime)
?? _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)
_dataSeries.AddPoint(MonitorName, "Price", currentTime, currentPrice);
if (lastReportedPrice is null || Math.Abs(currentPrice - lastReportedPrice.Value) > 0.01)
{
_replayTimeline.AddEvent(new ReplayEvent
{
@@ -84,6 +93,8 @@ public sealed class NordPoolReplayRunner : IMonitorReplayRunner
var isNowCheap = _cheapestIntervalsFinder.IsCurrentIntervalCheap(
cheapest, currentTime.LocalDateTime);
_dataSeries.AddPoint(MonitorName, "IsCheap", currentTime, isNowCheap ? 1.0 : 0.0);
if (isNowCheap)
{
var currentInterval = cheapest.FirstOrDefault(i =>
@@ -8,7 +8,6 @@ using Microsoft.Extensions.Options;
using NordPool.Models;
using PowerMonitorManager.Interface;
using PowerMonitorManager.Models;
using PowerMonitorManager.Models.Consts;
namespace HomeAssistant.HistoryReplay.Runners;
@@ -17,6 +16,7 @@ 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;
@@ -29,6 +29,7 @@ public sealed class PowerReplayRunner : IMonitorReplayRunner
HistoryTimeline timeline,
ReplayTimeProvider timeProvider,
ReplayTimeline replayTimeline,
ReplayDataSeries dataSeries,
IOtherPowerCalculationService calculationService,
IPowerCostCalculationService costService,
ILogger<PowerReplayRunner> logger,
@@ -38,6 +39,7 @@ public sealed class PowerReplayRunner : IMonitorReplayRunner
_timeline = timeline;
_timeProvider = timeProvider;
_replayTimeline = replayTimeline;
_dataSeries = dataSeries;
_calculationService = calculationService;
_costService = costService;
_logger = logger;
@@ -69,6 +71,10 @@ public sealed class PowerReplayRunner : IMonitorReplayRunner
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;
@@ -78,7 +84,6 @@ public sealed class PowerReplayRunner : IMonitorReplayRunner
if (isAnomaly && anomalyStartTime is null)
{
anomalyStartTime = currentTime.LocalDateTime;
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = currentTime,
@@ -120,8 +125,8 @@ public sealed class PowerReplayRunner : IMonitorReplayRunner
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) ||
@@ -5,6 +5,7 @@ using HomeAssistant.HistoryReplay.Replay;
using HomeAssistant.HistoryReplay.Reporting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NetDaemon.HassModel;
using ShowerMonitor.Models.Enums;
using ShowerMonitorManager.Interface;
using ShowerMonitorManager.Models;
@@ -16,8 +17,10 @@ public sealed class ShowerReplayRunner : IMonitorReplayRunner
private readonly HistoryTimeline _timeline;
private readonly ReplayTimeProvider _timeProvider;
private readonly ReplayTimeline _replayTimeline;
private readonly ReplayDataSeries _dataSeries;
private readonly IShowerDetectionService _detectionService;
private readonly IExhaustFanControlService _fanControlService;
private readonly IHaContext _haContext;
private readonly ILogger<ShowerReplayRunner> _logger;
private readonly ReplayOptions _replayOptions;
private readonly ShowerMonitorOptions _showerOptions;
@@ -28,8 +31,10 @@ public sealed class ShowerReplayRunner : IMonitorReplayRunner
HistoryTimeline timeline,
ReplayTimeProvider timeProvider,
ReplayTimeline replayTimeline,
ReplayDataSeries dataSeries,
IShowerDetectionService detectionService,
IExhaustFanControlService fanControlService,
IHaContext haContext,
ILogger<ShowerReplayRunner> logger,
IOptions<ReplayOptions> replayOptions,
IOptions<ShowerMonitorOptions> showerOptions)
@@ -37,8 +42,10 @@ public sealed class ShowerReplayRunner : IMonitorReplayRunner
_timeline = timeline;
_timeProvider = timeProvider;
_replayTimeline = replayTimeline;
_dataSeries = dataSeries;
_detectionService = detectionService;
_fanControlService = fanControlService;
_haContext = haContext;
_logger = logger;
_replayOptions = replayOptions.Value;
_showerOptions = showerOptions.Value;
@@ -64,10 +71,16 @@ public sealed class ShowerReplayRunner : IMonitorReplayRunner
if (bathroomHumidity.HasValue && homeHumidity.HasValue)
{
_dataSeries.AddPoint(MonitorName, "BathroomHumidity", currentTime, bathroomHumidity.Value);
_dataSeries.AddPoint(MonitorName, "HomeHumidity", currentTime, homeHumidity.Value);
_dataSeries.AddPoint(MonitorName, "Differential", currentTime, bathroomHumidity.Value - homeHumidity.Value);
var state = _detectionService.Evaluate(bathroomHumidity.Value, homeHumidity.Value, currentTime);
var differential = bathroomHumidity.Value - homeHumidity.Value;
_fanControlService.Evaluate(state, currentTime);
_dataSeries.AddPoint(MonitorName, "State", currentTime, (double)state);
_fanControlService.Evaluate(state, currentTime, _haContext);
if (state != previousState)
{
@@ -83,7 +96,7 @@ public sealed class ShowerReplayRunner : IMonitorReplayRunner
Timestamp = currentTime,
Monitor = MonitorName,
EventType = eventType,
Message = $"State: {previousState} → {state} (bathroom: {bathroomHumidity.Value:F1}%, home: {homeHumidity.Value:F1}%, diff: {differential:F1}%)",
Message = $"State: {previousState} -> {state} (bathroom: {bathroomHumidity.Value:F1}%, home: {homeHumidity.Value:F1}%, diff: {differential:F1}%)",
Details = GetStateChangeDetails(state)
});
@@ -0,0 +1,214 @@
using BoilerMonitorManager;
using BoilerMonitorManager.Interface;
using PowerMonitorManager;
using ShowerMonitorManager;
using HomeAssistant.HistoryReplay.Configuration;
using HomeAssistant.HistoryReplay.HistoryData;
using HomeAssistant.HistoryReplay.Replay;
using HomeAssistant.HistoryReplay.Reporting;
using HomeAssistant.HistoryReplay.Runners;
using LightMonitorManager.Models;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NordPoolManager.Interface;
using PowerMonitorManager.Interface;
using PowerMonitorManager.Models;
using ShowerMonitorManager.Interface;
using ShowerMonitorManager.Models;
namespace HomeAssistant.HistoryReplay.Services;
public sealed class ReplayOrchestrationService
{
private readonly IHistoryDataProvider _historyProvider;
private readonly IServiceProvider _serviceProvider;
private readonly ILogger<ReplayOrchestrationService> _logger;
public ReplayTimeline Timeline { get; } = new();
public ReplayDataSeries DataSeries { get; } = new();
public ReplayStatus Status { get; private set; } = ReplayStatus.Idle;
public string? ErrorMessage { get; private set; }
public string? ProgressMessage { get; private set; }
public event Action? OnStateChanged;
public void SetError(string message)
{
ErrorMessage = message;
Status = ReplayStatus.Failed;
NotifyStateChanged();
}
public ReplayOrchestrationService(
IHistoryDataProvider historyProvider,
IServiceProvider serviceProvider,
ILogger<ReplayOrchestrationService> logger)
{
_historyProvider = historyProvider;
_serviceProvider = serviceProvider;
_logger = logger;
}
public async Task RunReplayAsync(
DateTimeOffset startTime,
DateTimeOffset endTime,
ReplayMonitorFlags monitors,
CancellationToken cancellationToken = default)
{
try
{
Timeline.Clear();
DataSeries.Clear();
ErrorMessage = null;
ProgressMessage = null;
Status = ReplayStatus.FetchingHistory;
ProgressMessage = "Connecting to Home Assistant...";
NotifyStateChanged();
var showerOpts = _serviceProvider.GetRequiredService<IOptions<ShowerMonitorOptions>>().Value;
var powerOpts = _serviceProvider.GetRequiredService<IOptions<PowerMonitorOptions>>().Value;
var lightOpts = _serviceProvider.GetRequiredService<IOptions<LightMonitorOptions>>().Value;
const string boilerPowerEntityId = "sensor.boiler_power";
const string boilerSwitchEntityId = "switch.boiler";
var (minimalEntities, fullEntities) = ReplayEntityMap.GetPartitionedEntities(
boilerPowerEntityId,
boilerSwitchEntityId,
bathroomHumidityEntityId: showerOpts.BathroomHumidityEntityId,
mainHomeHumidityEntityId: showerOpts.MainHomeHumidityEntityId,
mainMeterEntityId: powerOpts.MainMeterEntityId,
sunEntityId: lightOpts.SunEntityId,
lightEntityId: lightOpts.LightEntityId,
personEntityIds: lightOpts.PersonEntityIds);
var totalEntityCount = minimalEntities.Count + fullEntities.Count;
_logger.LogInformation(
"Fetching history for {MinCount} minimal + {FullCount} full entities ({Start} to {End})",
minimalEntities.Count, fullEntities.Count, startTime, endTime);
ProgressMessage = $"Fetching history for {totalEntityCount} entities...";
NotifyStateChanged();
var historyTimeline = await _historyProvider.FetchHistoryAsync(
minimalEntities, fullEntities, startTime, endTime, cancellationToken);
ProgressMessage = $"Loaded {historyTimeline.TotalEntryCount} data points. Running replay...";
Status = ReplayStatus.Running;
NotifyStateChanged();
var replayOptions = new ReplayOptions
{
StartTime = startTime,
EndTime = endTime,
Monitors = monitors
};
var replayOptionsWrapper = Options.Create(replayOptions);
var timeProvider = new ReplayTimeProvider(startTime);
var replayHaContext = new ReplayHaContext(
historyTimeline, timeProvider, Timeline,
_serviceProvider.GetRequiredService<ILogger<ReplayHaContext>>());
var runners = BuildRunners(
historyTimeline, timeProvider, replayHaContext, replayOptionsWrapper, monitors,
boilerPowerEntityId, boilerSwitchEntityId);
_logger.LogInformation("Running {Count} monitor replay(s) in parallel", runners.Count);
var tasks = runners.Select(r => Task.Run(() => r.RunAsync(cancellationToken), cancellationToken));
await Task.WhenAll(tasks);
Status = ReplayStatus.Completed;
_logger.LogInformation("Replay completed with {Count} events", Timeline.GetAllEvents().Count);
}
catch (Exception ex)
{
_logger.LogError(ex, "Replay failed");
ErrorMessage = ex.Message;
Status = ReplayStatus.Failed;
}
finally
{
NotifyStateChanged();
}
}
private List<IMonitorReplayRunner> BuildRunners(
HistoryTimeline historyTimeline,
ReplayTimeProvider timeProvider,
ReplayHaContext replayHaContext,
IOptions<ReplayOptions> replayOptions,
ReplayMonitorFlags monitors,
string boilerPowerEntityId,
string boilerSwitchEntityId)
{
var runners = new List<IMonitorReplayRunner>();
if (monitors.NordPool)
{
runners.Add(new NordPoolReplayRunner(
historyTimeline, timeProvider, Timeline, DataSeries,
_serviceProvider.GetRequiredService<ICheapestIntervalsFinder>(),
_serviceProvider.GetRequiredService<ILogger<NordPoolReplayRunner>>(),
replayOptions));
}
if (monitors.Boiler)
{
runners.Add(new BoilerReplayRunner(
historyTimeline, timeProvider, Timeline, DataSeries,
_serviceProvider.GetRequiredService<IBoilerControlService>(),
new BoilerRunTimeTracker(),
new WaterReadyService(
_serviceProvider.GetRequiredService<ILogger<WaterReadyService>>(), timeProvider),
_serviceProvider.GetRequiredService<ILogger<BoilerReplayRunner>>(),
replayOptions,
boilerPowerEntityId,
boilerSwitchEntityId));
}
if (monitors.Shower)
{
var showerOpts = _serviceProvider.GetRequiredService<IOptions<ShowerMonitorOptions>>();
var rateCalc = new ShowerMonitorManager.HumidityRateCalculator(showerOpts.Value.RateWindowSize);
var detection = new ShowerMonitorManager.ShowerDetectionService(
rateCalc,
showerOpts);
var fan = new ExhaustFanControlService(showerOpts);
runners.Add(new ShowerReplayRunner(
historyTimeline, timeProvider, Timeline, DataSeries,
detection, fan, replayHaContext,
_serviceProvider.GetRequiredService<ILogger<ShowerReplayRunner>>(),
replayOptions, showerOpts));
}
if (monitors.Power)
{
runners.Add(new PowerReplayRunner(
historyTimeline, timeProvider, Timeline, DataSeries,
new OtherPowerCalculationService(
_serviceProvider.GetRequiredService<IOptions<PowerMonitorOptions>>()),
new PowerCostCalculationService(),
_serviceProvider.GetRequiredService<ILogger<PowerReplayRunner>>(),
replayOptions,
_serviceProvider.GetRequiredService<IOptions<PowerMonitorOptions>>()));
}
if (monitors.Light)
{
runners.Add(new LightReplayRunner(
historyTimeline, timeProvider, Timeline, DataSeries,
_serviceProvider.GetRequiredService<ILogger<LightReplayRunner>>(),
replayOptions,
_serviceProvider.GetRequiredService<IOptions<LightMonitorOptions>>()));
}
return runners;
}
private void NotifyStateChanged() => OnStateChanged?.Invoke();
}
@@ -0,0 +1,10 @@
namespace HomeAssistant.HistoryReplay.Services;
public enum ReplayStatus
{
Idle,
FetchingHistory,
Running,
Completed,
Failed
}
+2 -2
View File
@@ -6,13 +6,13 @@
"Ssl": false
},
"Replay": {
"StartTime": "2026-03-30T00:00:00+02:00",
"StartTime": "2026-03-01T00:00:00+02:00",
"EndTime": "2026-03-31T00:00:00+02:00",
"Monitors": {
"NordPool": true,
"Boiler": true,
"Shower": true,
"Power": false,
"Power": true,
"Light": true
}
},
@@ -0,0 +1,57 @@
body {
background-color: #1a1d21;
color: #e0e0e0;
}
.card {
background-color: #212529;
border-color: #343a40;
}
.card-header {
background-color: #2b3035;
border-bottom-color: #343a40;
}
.stat-card {
text-align: center;
transition: transform 0.15s;
}
.stat-card:hover {
transform: translateY(-2px);
}
.stat-card .display-6 {
font-weight: 700;
}
.badge-decision { background-color: #198754; }
.badge-statechange { background-color: #0dcaf0; color: #000; }
.badge-warning { background-color: #ffc107; color: #000; }
.badge-anomaly { background-color: #dc3545; }
.badge-servicecall { background-color: #6f42c1; }
.badge-info { background-color: #6c757d; }
.nav-tabs .nav-link {
color: #adb5bd;
}
.nav-tabs .nav-link.active {
background-color: #212529;
border-color: #495057 #495057 #212529;
color: #e0e0e0;
}
.table {
--bs-table-bg: transparent;
--bs-table-color: #e0e0e0;
}
.status-bar {
min-height: 40px;
}
.apexcharts-canvas {
background: transparent !important;
}