Enable PowerMonitor limit enforcement and prune unused boiler/replay code

PowerMonitor now ships enabled with power-limit enforcement settings: watt limit, recovery and cooldown windows, and switch-off plus pause/restore entity lists.

Remove the unused BoilerRunTimeTracker, its DI registration and tests, the StatusCleanedUp constant, and the boiler replay runner; simplify BoilerConfigReader, control-service logging and entity parsing. Switch CostAccumulator to System.Threading.Lock, update the Shower exhaust fan service and tests, drop the legacy HistoryReplay/McpServer sources and reporting tooling, and expand AGENTS.md with the current project wiring and DI notes.
This commit is contained in:
2026-11-29 13:58:08 +02:00
parent f176a1b8fc
commit f0bbd4f10b
98 changed files with 306 additions and 4737 deletions
+54 -25
View File
@@ -13,22 +13,28 @@ before editing; it only records things that are easy to get wrong.
## Stack ## Stack
- .NET 10 / C# 14 (`LangVersion=14.0`). `global.json` pins SDK `10.0.0` with - .NET 10 / C# 14 (`LangVersion=14.0`, set per-csproj in the three
`rollForward=latestMajor` and `allowPrerelease=true`. executable projects — `HomeAssistant.Server`, `HomeAssistant.McpServer`,
`HomeAssistant.HistoryReplay`; no `Directory.Build.props`). `global.json`
pins SDK `10.0.0` with `rollForward=latestMajor` and
`allowPrerelease=true`.
- NetDaemon v5 (NuGet `26.11.0`) apps run inside `HomeAssistant.Server`, the - NetDaemon v5 (NuGet `26.11.0`) apps run inside `HomeAssistant.Server`, the
only host / binary-deploy target. Solution file: `HomeAssistantSDK.sln`. only host / binary-deploy target. Solution file: `HomeAssistantSDK.sln`.
- Tests: xUnit + FluentAssertions + Moq. `Microsoft.Extensions.TimeProvider.Testing` - Tests: xUnit + FluentAssertions + Moq. `Microsoft.Extensions.TimeProvider.Testing`
is used for time-based tests — prefer `FakeTimeProvider` over real time. is used for time-based tests — prefer `FakeTimeProvider` over real time.
- AutoMapper 16 is used by `HomeAssistant.Server`. **A hardcoded license key - AutoMapper 16.1.1 is used by `HomeAssistant.Server`. **A hardcoded license key
is committed in `HomeAssistant.Server/program.cs`** — do not move it to is committed in `HomeAssistant.Server/program.cs`** — do not move it to
settings, and do not log or echo it. settings, and do not log or echo it.
## Layout (non-obvious wiring) ## Layout (non-obvious wiring)
- Each monitor follows a fixed 3-project pattern: - Each monitor follows a fixed 3-project pattern:
- `*.Models` — constants, enums, `*Options` (bound from - `*.Models` — entity/config interfaces, constants, enums.
`appsettings.json` via `IOptions<>`). - `*.Manager` — services, the `[NetDaemonApp]` entry `*Init.cs`, and
- `*.Manager` — services + the `[NetDaemonApp]` entry `*Init.cs`. `*Options` (bound from `appsettings.json` via `IOptions<>`). Note:
`*Options` lives in `*.Manager/Models/`, **not** in the separate
`*.Models` project, for 6 of 7 monitors. Only `LightMonitor` puts
`LightMonitorOptions` in `LightMonitor.Models`.
- `*.Manager.Tests` — unit tests for the manager. - `*.Manager.Tests` — unit tests for the manager.
- Apps are **not** auto-discovered by the host. Each monitor exposes a - Apps are **not** auto-discovered by the host. Each monitor exposes a
`Add<Name>Monitor(this IServiceCollection, IConfiguration)` extension in `Add<Name>Monitor(this IServiceCollection, IConfiguration)` extension in
@@ -36,24 +42,40 @@ before editing; it only records things that are easy to get wrong.
specific order. Adding a new monitor means: create the 3 projects, add a specific order. Adding a new monitor means: create the 3 projects, add a
`*ServiceRegistration.cs`, reference the projects from `*ServiceRegistration.cs`, reference the projects from
`HomeAssistant.Server`, and wire `Add<Name>` + `Configure<*Options>` in `HomeAssistant.Server`, and wire `Add<Name>` + `Configure<*Options>` in
`program.cs`. `program.cs`. **NordPool breaks the naming convention**: its extension is
`AddNordPool`, not `AddNordPoolMonitor`.
- `*ServiceRegistration.cs` honors an `Enabled` flag in the options and - `*ServiceRegistration.cs` honors an `Enabled` flag in the options and
no-ops (skips `AddNetDaemonApp`) when disabled. `PowerMonitor` ships no-ops (skips `AddNetDaemonApp`) when disabled — for every monitor
disabled by default in `appsettings.json`. **except NordPool**, which has no `Enabled` option and always registers.
`PowerMonitor` ships disabled by default in `appsettings.json`; all
others ship enabled.
- `HomeAssistant.Entities` holds the **generated** `HomeAssistantGenerated` - `HomeAssistant.Entities` holds the **generated** `HomeAssistantGenerated`
code (entity metadata sourced from code (entity metadata sourced from
`HomeAssistant.Server/NetDaemonCodegen/{EntityMetaData,ServicesMetaData}.json`). `HomeAssistant.Server/NetDaemonCodegen/{EntityMetaData,ServicesMetaData}.json`).
`program.cs` calls `AddHomeAssistantGenerated()`; the generated entities `program.cs` calls `AddHomeAssistantGenerated()`; the generated entities
are transient. Do not hand-edit generated files. are transient. Do not hand-edit generated files.
- `HomeAssistant.McpServer` is a separate stdio MCP server (ModelContextProtocol - `program.cs` calls `Configure<*Options>` then `Add<Name>…` for each
NuGet) exposing HA tools. It is **not** referenced by the host; it runs monitor in this order: NordPool, Power, Boiler, Shower, Light, Battery,
standalone via `dotnet run --project HomeAssistant.McpServer`. Cursor Leak. Monitor service registrations (except `IBoilerConfigReader`,
wires it up in `.cursor/mcp.json` as the `homeassistant` MCP server. `IEntityManager`, `TimeProvider.System`, which are in `program.cs`)
live inside each `*ServiceRegistration.cs`, not `program.cs`.
- `HomeAssistant.Models` is a thin shared model project (one file,
`EntityCreateModel.cs`) referenced by `HomeAssistant.Entities`. NetDaemon
MQTT extension lives here.
- `Mappings` is a class library holding AutoMapper profiles
(`GlobalMappingProfile`, `NordPoolMappingProfile` + `DateTimeTypeConverter`)
referenced by `HomeAssistant.Server`; wired in `program.cs` via
`config.AddProfile<…>()`. AutoMapper 16.1.1.
- `HomeAssistant.McpServer` is a separate stdio MCP server
(ModelContextProtocol NuGet 1.2.0) exposing HA tools. It is **not**
referenced by the host; it runs standalone via
`dotnet run --project HomeAssistant.McpServer`. It is wired as the
`homeassistant` MCP server in both `.cursor/mcp.json` (git-ignored) and
the committed `opencode.json` at the repo root.
- `HomeAssistant.HistoryReplay` is a Blazor debug web app that replays HA - `HomeAssistant.HistoryReplay` is a Blazor debug web app that replays HA
history through monitor business logic with no side effects. See its own history through monitor business logic with no side effects. It
README. Not deployed. references a subset of monitors (Boiler, NordPool, Power, Shower, Light —
- `NordPool.Comminication` (sic — typo is intentional, keep it) is the not Battery or Leak). See its own README. Not deployed.
Nord Pool HTTP client project referenced by `NordPool.Manager`.
## Critical DI rule ## Critical DI rule
@@ -65,7 +87,10 @@ or app load fails with:
Verified-livable registrations (do not regress these to singleton): Verified-livable registrations (do not regress these to singleton):
- `Boiler`: `IBoilerMonitorEntityService` transient, - `Boiler`: `IBoilerMonitorEntityService` transient,
`IBoilerConfigReader` scoped (in `program.cs`). `IBoilerControlService`/`IBoilerRunTimeTracker`/`IWaterReadyService`
singleton (no HA dep), `IBoilerConfigReader` scoped (registered directly
in `program.cs`, the only monitor service outside its
`*ServiceRegistration.cs`).
- `NordPool`: `INordPoolEntityService` transient, `INordPoolPriceService` - `NordPool`: `INordPoolEntityService` transient, `INordPoolPriceService`
scoped, `INordPoolBoilerConfigProvider` scoped, scoped, `INordPoolBoilerConfigProvider` scoped,
`ICheapestIntervalsFinder` singleton (no HA dep). `ICheapestIntervalsFinder` singleton (no HA dep).
@@ -88,8 +113,8 @@ scoped.
## Live validation after monitor edits ## Live validation after monitor edits
`.cursor/rules/live-validation.mdc` (globs: all `*.Manager`/`*.Models` of `.cursor/rules/live-validation.mdc` (globs: all `*.Manager`/`*.Models` of
Boiler, Light, NordPool, Power, Shower, plus `HomeAssistant.McpServer`) Boiler, Light, NordPool, Power, Shower, plus `HomeAssistant.McpServer` —
requires, after editing monitor runtime code: **not** Battery or Leak) requires, after editing monitor runtime code:
1. `dotnet build` the affected project. 1. `dotnet build` the affected project.
2. `RunSmokeTest` MCP tool from the `homeassistant` MCP server. 2. `RunSmokeTest` MCP tool from the `homeassistant` MCP server.
@@ -153,10 +178,14 @@ prints the reminder after publish.
`HumidityRateCalculator`). Keep both in sync when changing option names. `HumidityRateCalculator`). Keep both in sync when changing option names.
- `HomeAssistant.Server` references every monitor's `*.Manager` and - `HomeAssistant.Server` references every monitor's `*.Manager` and
`*.Models` projects directly; `HomeAssistant.HistoryReplay` references a `*.Models` projects directly; `HomeAssistant.HistoryReplay` references a
subset. Adding a monitor to the replay tool requires a new project subset (Boiler, NordPool, Power, Shower, Light). Adding a monitor to the
reference there too. replay tool requires a new project reference there too.
- The repository folder name is misspelled `homeassistant-app-deamon` - The repository folder name is misspelled `homeassistant-app-deamon`
(should be `daemon`). This is intentional/legacy — do not "fix" it in (should be `daemon`). This is intentional/legacy — do not "fix" it in
paths; scripts and `.cursor/mcp.json` use `${workspaceFolder}`. paths; `opencode.json` and `.cursor/mcp.json` reference the workspace
- `NordPool.Comminication` is also misspelled — keep it; the project folder by macro.
reference depends on the exact name. - Stale untracked folders `NordPool.Comminication/` and
`HomeAssistant.Infrastructure/` may appear on disk containing only
`obj/` build cruft. They are **not** in the solution, not committed to
git, and not referenced by any project. Do not treat them as real
projects; safe to delete.
@@ -1,6 +1,4 @@
using BoilerMonitor.Models;
using BoilerMonitorManager; using BoilerMonitorManager;
using BoilerMonitorManager.Models;
using FluentAssertions; using FluentAssertions;
using HomeAssistant.Entities.Interfaces; using HomeAssistant.Entities.Interfaces;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
@@ -1,254 +0,0 @@
using FluentAssertions;
using BoilerMonitorManager;
namespace BoilerMonitor.Manager.Tests;
public class BoilerRunTimeTrackerTests
{
private readonly BoilerRunTimeTracker _sut = new();
#region RecordPollResult
[Fact]
public void RecordPollResult_WhenHeating_ShouldAccumulateRunTime()
{
var interval = TimeSpan.FromSeconds(30);
_sut.RecordPollResult(true, interval);
_sut.RecordPollResult(true, interval);
_sut.RecordPollResult(true, interval);
var snapshot = _sut.GetSnapshot();
snapshot.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(90));
}
[Fact]
public void RecordPollResult_WhenNotHeating_ShouldNotAccumulate()
{
var interval = TimeSpan.FromSeconds(30);
_sut.RecordPollResult(false, interval);
_sut.RecordPollResult(false, interval);
var snapshot = _sut.GetSnapshot();
snapshot.AccumulatedRunTime.Should().Be(TimeSpan.Zero);
}
[Fact]
public void RecordPollResult_WhenHeatingStarts_ShouldIncrementSessionCount()
{
var interval = TimeSpan.FromSeconds(30);
_sut.RecordPollResult(true, interval);
var snapshot = _sut.GetSnapshot();
snapshot.SessionCount.Should().Be(1);
}
[Fact]
public void RecordPollResult_ContinuousHeating_ShouldCountAsOneSession()
{
var interval = TimeSpan.FromSeconds(30);
_sut.RecordPollResult(true, interval);
_sut.RecordPollResult(true, interval);
_sut.RecordPollResult(true, interval);
var snapshot = _sut.GetSnapshot();
snapshot.SessionCount.Should().Be(1);
}
[Fact]
public void RecordPollResult_HeatingStopsAndRestarts_ShouldCountAsTwoSessions()
{
var interval = TimeSpan.FromSeconds(30);
_sut.RecordPollResult(true, interval);
_sut.RecordPollResult(false, interval);
_sut.RecordPollResult(true, interval);
var snapshot = _sut.GetSnapshot();
snapshot.SessionCount.Should().Be(2);
}
[Fact]
public void RecordPollResult_MultipleSessions_ShouldAccumulateCorrectly()
{
var interval = TimeSpan.FromSeconds(30);
_sut.RecordPollResult(true, interval);
_sut.RecordPollResult(true, interval);
_sut.RecordPollResult(false, interval);
_sut.RecordPollResult(true, interval);
var snapshot = _sut.GetSnapshot();
snapshot.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(90));
snapshot.SessionCount.Should().Be(2);
}
[Fact]
public void RecordPollResult_WhenHeating_ShouldSetIsInSessionTrue()
{
_sut.RecordPollResult(true, TimeSpan.FromSeconds(30));
var snapshot = _sut.GetSnapshot();
snapshot.IsInSession.Should().BeTrue();
}
[Fact]
public void RecordPollResult_WhenNotHeating_ShouldSetIsInSessionFalse()
{
_sut.RecordPollResult(true, TimeSpan.FromSeconds(30));
_sut.RecordPollResult(false, TimeSpan.FromSeconds(30));
var snapshot = _sut.GetSnapshot();
snapshot.IsInSession.Should().BeFalse();
}
#endregion
#region Reset
[Fact]
public void Reset_ShouldClearAllState()
{
var interval = TimeSpan.FromSeconds(30);
_sut.RecordPollResult(true, interval);
_sut.RecordPollResult(true, interval);
_sut.Reset();
var snapshot = _sut.GetSnapshot();
snapshot.AccumulatedRunTime.Should().Be(TimeSpan.Zero);
snapshot.SessionCount.Should().Be(0);
snapshot.IsInSession.Should().BeFalse();
}
[Fact]
public void Reset_AfterReset_ShouldAccumulateFromZero()
{
var interval = TimeSpan.FromSeconds(30);
_sut.RecordPollResult(true, interval);
_sut.Reset();
_sut.RecordPollResult(true, interval);
var snapshot = _sut.GetSnapshot();
snapshot.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(30));
snapshot.SessionCount.Should().Be(1);
}
#endregion
#region RestoreFromSnapshot
[Fact]
public void RestoreFromSnapshot_ShouldSetAccumulatedRunTimeAndSessionCount()
{
// Arrange
var runTime = TimeSpan.FromMinutes(45);
const int sessionCount = 3;
// Act
_sut.RestoreFromSnapshot(runTime, sessionCount);
// Assert
var snapshot = _sut.GetSnapshot();
snapshot.AccumulatedRunTime.Should().Be(runTime);
snapshot.SessionCount.Should().Be(sessionCount);
snapshot.IsInSession.Should().BeFalse();
}
[Fact]
public void RestoreFromSnapshot_ShouldOverwriteExistingState()
{
// Arrange
_sut.RecordPollResult(true, TimeSpan.FromSeconds(30));
_sut.RecordPollResult(true, TimeSpan.FromSeconds(30));
var restoredRunTime = TimeSpan.FromHours(2);
const int restoredSessions = 5;
// Act
_sut.RestoreFromSnapshot(restoredRunTime, restoredSessions);
// Assert
var snapshot = _sut.GetSnapshot();
snapshot.AccumulatedRunTime.Should().Be(restoredRunTime);
snapshot.SessionCount.Should().Be(restoredSessions);
}
[Fact]
public void RestoreFromSnapshot_ShouldAllowFurtherAccumulationFromRestoredState()
{
// Arrange
var restoredRunTime = TimeSpan.FromMinutes(30);
const int restoredSessions = 2;
var pollInterval = TimeSpan.FromSeconds(30);
_sut.RestoreFromSnapshot(restoredRunTime, restoredSessions);
// Act
_sut.RecordPollResult(true, pollInterval);
// Assert
var snapshot = _sut.GetSnapshot();
snapshot.AccumulatedRunTime.Should().Be(restoredRunTime + pollInterval);
snapshot.SessionCount.Should().Be(restoredSessions + 1);
}
[Fact]
public void RestoreFromSnapshot_WithZeroValues_ShouldSetToZero()
{
// Arrange
_sut.RecordPollResult(true, TimeSpan.FromSeconds(30));
// Act
_sut.RestoreFromSnapshot(TimeSpan.Zero, 0);
// Assert
var snapshot = _sut.GetSnapshot();
snapshot.AccumulatedRunTime.Should().Be(TimeSpan.Zero);
snapshot.SessionCount.Should().Be(0);
}
#endregion
#region Thread safety
[Fact]
public async Task RecordPollResult_ConcurrentCalls_ShouldNotCorruptState()
{
var interval = TimeSpan.FromSeconds(1);
const int iterationsPerThread = 1000;
const int threadCount = 4;
var tasks = Enumerable.Range(0, threadCount).Select(_ => Task.Run(() =>
{
for (var i = 0; i < iterationsPerThread; i++)
{
_sut.RecordPollResult(true, interval);
}
})).ToArray();
await Task.WhenAll(tasks);
var snapshot = _sut.GetSnapshot();
snapshot.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(iterationsPerThread * threadCount));
}
#endregion
#region GetSnapshot
[Fact]
public void GetSnapshot_Initial_ShouldReturnZeroState()
{
var snapshot = _sut.GetSnapshot();
snapshot.AccumulatedRunTime.Should().Be(TimeSpan.Zero);
snapshot.SessionCount.Should().Be(0);
snapshot.IsInSession.Should().BeFalse();
}
#endregion
}
+7 -3
View File
@@ -17,6 +17,7 @@ public sealed class BoilerConfigReader(IHaContext haContext, ILogger<BoilerConfi
var dailyHours = double.TryParse(dailyHoursState, NumberStyles.Any, CultureInfo.InvariantCulture, out var dh) ? dh : DefaultDailyHours; var dailyHours = double.TryParse(dailyHoursState, NumberStyles.Any, CultureInfo.InvariantCulture, out var dh) ? dh : DefaultDailyHours;
var intervalCount = (int)(dailyHours * IntervalsPerHour); var intervalCount = (int)(dailyHours * IntervalsPerHour);
if (intervalCount <= 0) if (intervalCount <= 0)
{ {
intervalCount = IntervalsPerHour; intervalCount = IntervalsPerHour;
@@ -27,6 +28,7 @@ public sealed class BoilerConfigReader(IHaContext haContext, ILogger<BoilerConfi
var deadline = DateTime.Today.AddDays(1); var deadline = DateTime.Today.AddDays(1);
var readyByState = haContext.GetState(BoilerReadyByEntityId)?.State; var readyByState = haContext.GetState(BoilerReadyByEntityId)?.State;
if (!string.IsNullOrEmpty(readyByState) && TimeSpan.TryParse(readyByState, out var readyByTime)) if (!string.IsNullOrEmpty(readyByState) && TimeSpan.TryParse(readyByState, out var readyByTime))
{ {
deadline = DateTime.Today.Add(readyByTime); deadline = DateTime.Today.Add(readyByTime);
@@ -35,15 +37,17 @@ public sealed class BoilerConfigReader(IHaContext haContext, ILogger<BoilerConfi
var skipPriceCapState = haContext.GetState(SkipPriceCapEntityId)?.State; var skipPriceCapState = haContext.GetState(SkipPriceCapEntityId)?.State;
var skipPriceCap = string.Equals(skipPriceCapState, SwitchOnState, StringComparison.OrdinalIgnoreCase); var skipPriceCap = string.Equals(skipPriceCapState, SwitchOnState, StringComparison.OrdinalIgnoreCase);
logger.LogDebug("Boiler config: intervals={Intervals}, priceCap={Cap}, skipPriceCap={Skip}, deadline={Deadline}", logger.LogDebug("Boiler config: intervals={Intervals}, priceCap={Cap}, skipPriceCap={Skip}, deadline={Deadline}", intervalCount, priceCap, skipPriceCap, deadline);
intervalCount, priceCap, skipPriceCap, deadline);
return new BoilerConfig var config = new BoilerConfig
{ {
IntervalCount = intervalCount, IntervalCount = intervalCount,
PriceCap = priceCap, PriceCap = priceCap,
Deadline = deadline, Deadline = deadline,
SkipPriceCap = skipPriceCap SkipPriceCap = skipPriceCap
}; };
return config;
} }
} }
@@ -21,9 +21,7 @@ public sealed class BoilerControlService(ILogger<BoilerControlService> logger) :
if (shouldBeOn && !isCurrentlyOn) if (shouldBeOn && !isCurrentlyOn)
{ {
logger.LogInformation( logger.LogInformation("Boiler should turn ON — cheap interval active, water not ready, budget available (current state: {State})", currentSwitchState);
"Boiler should turn ON — cheap interval active, water not ready, budget available (current state: {State})",
currentSwitchState);
return BoilerAction.TurnOn; return BoilerAction.TurnOn;
} }
@@ -37,12 +35,8 @@ public sealed class BoilerControlService(ILogger<BoilerControlService> logger) :
return BoilerAction.TurnOff; return BoilerAction.TurnOff;
} }
logger.LogDebug( logger.LogDebug("Boiler state unchanged: {State} (cheap={Cheap}, waterReady={WaterReady}, budgetExhausted={BudgetExhausted})",
"Boiler state unchanged: {State} (cheap={Cheap}, waterReady={WaterReady}, budgetExhausted={BudgetExhausted})", currentSwitchState, isNowCheap, waterReady, effectiveBudgetExhausted);
currentSwitchState,
isNowCheap,
waterReady,
effectiveBudgetExhausted);
return BoilerAction.NoChange; return BoilerAction.NoChange;
} }
@@ -93,9 +93,6 @@ public sealed class BoilerMonitorEntityService(
var formattedRunTime = FormatTimeSpan(ctx.TodayRunTime); var formattedRunTime = FormatTimeSpan(ctx.TodayRunTime);
var formattedRemaining = FormatTimeSpan(ctx.RemainingTime); var formattedRemaining = FormatTimeSpan(ctx.RemainingTime);
// logger.LogInformation("Updating BoilerMonitor entities: runtime={RunTime}, remaining={Remaining}, budget={Budget}%, sessions={Sessions}",
// formattedRunTime, formattedRemaining, ctx.BudgetPercentage, ctx.SessionCount);
var updateTasks = new[] var updateTasks = new[]
{ {
UpdateStatusAsync(StatusConfigured), UpdateStatusAsync(StatusConfigured),
@@ -116,7 +113,7 @@ public sealed class BoilerMonitorEntityService(
try try
{ {
var removeTasks = CleanableEntityIds.Select(entityId => entityManager.RemoveEntity(entityId)); var removeTasks = CleanableEntityIds.Select(entityManager.RemoveEntity);
await Task.WhenAll(removeTasks).ConfigureAwait(false); await Task.WhenAll(removeTasks).ConfigureAwait(false);
logger.LogInformation("BoilerMonitor entities cleaned up successfully (cleanup button retained)"); logger.LogInformation("BoilerMonitor entities cleaned up successfully (cleanup button retained)");
@@ -149,8 +146,7 @@ public sealed class BoilerMonitorEntityService(
var skipPriceCapState = haContext.GetState(SkipPriceCapEntityId)?.State; var skipPriceCapState = haContext.GetState(SkipPriceCapEntityId)?.State;
var budgetOverrideState = haContext.GetState(BudgetOverrideEntityId)?.State; var budgetOverrideState = haContext.GetState(BudgetOverrideEntityId)?.State;
if (!TryParseEntitySeconds(runtimeState, out var runtimeSeconds) if (!TryParseEntitySeconds(runtimeState, out var runtimeSeconds) || !TryParseEntityInt(sessionCountState, out var sessionCount))
|| !TryParseEntityInt(sessionCountState, out var sessionCount))
{ {
logger.LogInformation("No valid persisted BoilerMonitor state found in HA entities (runtime={Runtime}, sessions={Sessions})", logger.LogInformation("No valid persisted BoilerMonitor state found in HA entities (runtime={Runtime}, sessions={Sessions})",
runtimeState, sessionCountState); runtimeState, sessionCountState);
@@ -185,19 +181,23 @@ public sealed class BoilerMonitorEntityService(
private static bool TryParseEntitySeconds(string? state, out double seconds) private static bool TryParseEntitySeconds(string? state, out double seconds)
{ {
seconds = 0; seconds = 0;
return !string.IsNullOrWhiteSpace(state) var tryParseEntitySeconds = !string.IsNullOrWhiteSpace(state)
&& state is not ("unavailable" or "unknown") && state is not ("unavailable" or "unknown")
&& double.TryParse(state, CultureInfo.InvariantCulture, out seconds) && double.TryParse(state, CultureInfo.InvariantCulture, out seconds)
&& seconds >= 0; && seconds >= 0;
return tryParseEntitySeconds;
} }
private static bool TryParseEntityInt(string? state, out int value) private static bool TryParseEntityInt(string? state, out int value)
{ {
value = 0; value = 0;
return !string.IsNullOrWhiteSpace(state) var tryParseEntityInt = !string.IsNullOrWhiteSpace(state)
&& state is not ("unavailable" or "unknown") && state is not ("unavailable" or "unknown")
&& int.TryParse(state, CultureInfo.InvariantCulture, out value) && int.TryParse(state, CultureInfo.InvariantCulture, out value)
&& value >= 0; && value >= 0;
return tryParseEntityInt;
} }
private ICollection<BoilerMonitorEntity> GetAllEntities() private ICollection<BoilerMonitorEntity> GetAllEntities()
@@ -1,7 +1,6 @@
using System.Globalization; using System.Globalization;
using System.Reactive.Concurrency; using System.Reactive.Concurrency;
using System.Text.Json; using System.Text.Json;
using BoilerMonitor.Models;
using BoilerMonitor.Models.Enums; using BoilerMonitor.Models.Enums;
using BoilerMonitorManager.Interface; using BoilerMonitorManager.Interface;
using BoilerMonitorManager.Models; using BoilerMonitorManager.Models;
@@ -1,4 +1,3 @@
using BoilerMonitor.Models;
using BoilerMonitorManager.Interface; using BoilerMonitorManager.Interface;
using BoilerMonitorManager.Models; using BoilerMonitorManager.Models;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
@@ -23,7 +22,6 @@ public static class BoilerMonitorServiceRegistration
services services
.AddNetDaemonApp<BoilerMonitorInit>() .AddNetDaemonApp<BoilerMonitorInit>()
.AddSingleton<IBoilerControlService, BoilerControlService>() .AddSingleton<IBoilerControlService, BoilerControlService>()
.AddSingleton<IBoilerRunTimeTracker, BoilerRunTimeTracker>()
.AddTransient<IBoilerMonitorEntityService, BoilerMonitorEntityService>() .AddTransient<IBoilerMonitorEntityService, BoilerMonitorEntityService>()
.AddSingleton<IWaterReadyService, WaterReadyService>(); .AddSingleton<IWaterReadyService, WaterReadyService>();
@@ -1,66 +0,0 @@
using BoilerMonitorManager.Interface;
using BoilerMonitorManager.Models;
namespace BoilerMonitorManager;
public sealed class BoilerRunTimeTracker : IBoilerRunTimeTracker
{
private readonly Lock _lock = new();
private TimeSpan _accumulatedRunTime = TimeSpan.Zero;
private int _sessionCount;
private bool _isInSession;
public void RecordPollResult(bool isHeating, TimeSpan pollInterval)
{
lock (_lock)
{
if (isHeating)
{
_accumulatedRunTime += pollInterval;
if (!_isInSession)
{
_sessionCount++;
_isInSession = true;
}
}
else
{
_isInSession = false;
}
}
}
public RunTimeSnapshot GetSnapshot()
{
lock (_lock)
{
return new RunTimeSnapshot
{
AccumulatedRunTime = _accumulatedRunTime,
SessionCount = _sessionCount,
IsInSession = _isInSession
};
}
}
public void Reset()
{
lock (_lock)
{
_accumulatedRunTime = TimeSpan.Zero;
_sessionCount = 0;
_isInSession = false;
}
}
public void RestoreFromSnapshot(TimeSpan accumulatedRunTime, int sessionCount)
{
lock (_lock)
{
_accumulatedRunTime = accumulatedRunTime;
_sessionCount = sessionCount;
_isInSession = false;
}
}
}
@@ -1,4 +1,3 @@
using BoilerMonitor.Models;
using BoilerMonitorManager.Models; using BoilerMonitorManager.Models;
namespace BoilerMonitorManager.Interface; namespace BoilerMonitorManager.Interface;
+8 -13
View File
@@ -59,9 +59,8 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
{ {
if (!_hasObservedHeating) if (!_hasObservedHeating)
{ {
logger.LogDebug( logger.LogDebug("Ignoring power reading ({PowerWatts}W) — boiler has not been observed heating yet", powerWatts.Value);
"Ignoring power reading ({PowerWatts}W) — boiler has not been observed heating yet",
powerWatts.Value);
return false; return false;
} }
@@ -75,19 +74,15 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
if (_consecutiveBelowThresholdCount < BoilerMonitorConsts.ConsecutiveReadingsRequired) if (_consecutiveBelowThresholdCount < BoilerMonitorConsts.ConsecutiveReadingsRequired)
{ {
logger.LogDebug( logger.LogDebug("Below-threshold reading {Count}/{Required} ({PowerWatts}W), waiting for confirmation",
"Below-threshold reading {Count}/{Required} ({PowerWatts}W), waiting for confirmation", _consecutiveBelowThresholdCount, BoilerMonitorConsts.ConsecutiveReadingsRequired, powerWatts.Value);
_consecutiveBelowThresholdCount,
BoilerMonitorConsts.ConsecutiveReadingsRequired,
powerWatts.Value);
return false; return false;
} }
_waterReadySince ??= timeProvider.GetUtcNow(); _waterReadySince ??= timeProvider.GetUtcNow();
logger.LogInformation( logger.LogInformation("Water detected as ready after {Count} consecutive readings, cooldown active until shower or midnight reset", _consecutiveBelowThresholdCount);
"Water detected as ready after {Count} consecutive readings, cooldown active until shower or midnight reset",
_consecutiveBelowThresholdCount);
return true; return true;
} }
@@ -137,8 +132,8 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
var todayMidnightUtc = new DateTimeOffset(timeProvider.GetUtcNow().Date, TimeSpan.Zero); var todayMidnightUtc = new DateTimeOffset(timeProvider.GetUtcNow().Date, TimeSpan.Zero);
if (waterReadySince < todayMidnightUtc) if (waterReadySince < todayMidnightUtc)
{ {
logger.LogInformation( logger.LogInformation("Persisted cooldown is from a previous day ({Since}), not restoring", waterReadySince);
"Persisted cooldown is from a previous day ({Since}), not restoring", waterReadySince);
return; return;
} }
@@ -65,7 +65,6 @@ public static class BoilerMonitorConsts
public const string StatusConfigured = "configured"; public const string StatusConfigured = "configured";
public const string StatusAwaitingConfiguration = "awaiting_configuration"; public const string StatusAwaitingConfiguration = "awaiting_configuration";
public const string StatusCleanedUp = "cleaned_up";
public const string SwitchOnState = "on"; public const string SwitchOnState = "on";
@@ -1,19 +0,0 @@
<!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>
@@ -1,44 +0,0 @@
@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>
}
@@ -1,30 +0,0 @@
@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>
@@ -1,32 +0,0 @@
@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>
}
@@ -1,40 +0,0 @@
@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>
}
@@ -1,46 +0,0 @@
@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>
}
@@ -1,17 +0,0 @@
@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>
@@ -1,240 +0,0 @@
@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;
}
}
@@ -1,6 +0,0 @@
<Router AppAssembly="typeof(Program).Assembly">
<Found Context="routeData">
<RouteView RouteData="routeData" DefaultLayout="typeof(Layout.MainLayout)" />
<FocusOnNavigate RouteData="routeData" Selector="h1" />
</Found>
</Router>
@@ -1,54 +0,0 @@
@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>
}
}
@@ -1,53 +0,0 @@
@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>
@@ -1,15 +0,0 @@
@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
@@ -1,109 +0,0 @@
using BoilerMonitor.Models;
using LightMonitor.Models;
using NordPool.Models;
using ShowerMonitor.Models;
namespace HomeAssistant.HistoryReplay.Configuration;
public static class ReplayEntityMap
{
public static IReadOnlyList<string> GetNordPoolEntities() =>
[
"sensor.nordpool_kwh_lt_eur_3_10_0",
NordPoolConsts.CurrentPriceEntityId,
BoilerMonitorConsts.BoilerDailyHoursEntityId,
BoilerMonitorConsts.BoilerPriceCapEntityId,
BoilerMonitorConsts.BoilerReadyByEntityId,
BoilerMonitorConsts.SkipPriceCapEntityId
];
public static IReadOnlyList<string> GetBoilerEntities(string boilerPowerEntityId, string boilerSwitchEntityId) =>
[
boilerPowerEntityId,
boilerSwitchEntityId,
"sensor.nordpool_cheapest_intervals",
BoilerMonitorConsts.SkipPriceCapEntityId,
BoilerMonitorConsts.BudgetOverrideEntityId,
BoilerMonitorConsts.AutoManagementEntityId,
BoilerMonitorConsts.BoilerDailyHoursEntityId
];
public static IReadOnlyList<string> GetShowerEntities(string bathroomHumidityEntityId, string mainHomeHumidityEntityId) =>
[
bathroomHumidityEntityId,
mainHomeHumidityEntityId
];
public static IReadOnlyList<string> GetPowerEntities(string mainMeterEntityId) =>
[
mainMeterEntityId,
NordPoolConsts.CurrentPriceEntityId
];
public static IReadOnlyList<string> GetLightEntities(string sunEntityId, string lightEntityId, string[] personEntityIds)
{
var entities = new List<string> { sunEntityId, lightEntityId };
entities.AddRange(personEntityIds);
return entities;
}
public static IReadOnlyList<string> GetEntitiesRequiringAttributes() =>
[
"sensor.nordpool_cheapest_intervals"
];
public static IReadOnlyList<string> GetAllEntities(
string boilerPowerEntityId,
string boilerSwitchEntityId,
string bathroomHumidityEntityId,
string mainHomeHumidityEntityId,
string mainMeterEntityId,
string sunEntityId,
string lightEntityId,
string[] personEntityIds)
{
var all = new HashSet<string>();
foreach (var e in GetNordPoolEntities()) all.Add(e);
foreach (var e in GetBoilerEntities(boilerPowerEntityId, boilerSwitchEntityId)) all.Add(e);
foreach (var e in GetShowerEntities(bathroomHumidityEntityId, mainHomeHumidityEntityId)) all.Add(e);
foreach (var e in GetPowerEntities(mainMeterEntityId)) all.Add(e);
foreach (var e in GetLightEntities(sunEntityId, lightEntityId, personEntityIds)) all.Add(e);
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);
}
}
@@ -1,19 +0,0 @@
namespace HomeAssistant.HistoryReplay.Configuration;
public sealed class ReplayOptions
{
public const string SectionName = "Replay";
public DateTimeOffset StartTime { get; set; } = DateTimeOffset.UtcNow.AddDays(-1);
public DateTimeOffset EndTime { get; set; } = DateTimeOffset.UtcNow;
public ReplayMonitorFlags Monitors { get; set; } = new();
}
public sealed class ReplayMonitorFlags
{
public bool NordPool { get; set; } = true;
public bool Boiler { get; set; } = true;
public bool Shower { get; set; } = true;
public bool Power { get; set; } = true;
public bool Light { get; set; } = true;
}
@@ -1,9 +0,0 @@
namespace HomeAssistant.HistoryReplay.HistoryData;
public sealed class HistoryStateEntry
{
public required string EntityId { get; init; }
public required string? State { get; init; }
public required DateTimeOffset LastChanged { get; init; }
public IReadOnlyDictionary<string, object>? Attributes { get; init; }
}
@@ -1,118 +0,0 @@
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)
{
if (!_entityTimelines.TryGetValue(entityId, out var list))
{
list = [];
_entityTimelines[entityId] = list;
}
list.AddRange(entries);
_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)
{
if (!_entityTimelines.TryGetValue(entityId, out var entries) || entries.Count == 0)
{
return null;
}
var index = BinarySearchFloor(entries, timestamp);
return index >= 0 ? entries[index] : null;
}
public IReadOnlyList<DateTimeOffset> GetAllTimestamps()
{
var timestamps = new SortedSet<DateTimeOffset>();
foreach (var entries in _entityTimelines.Values)
{
foreach (var entry in entries)
{
timestamps.Add(entry.LastChanged);
}
}
return [.. timestamps];
}
public IReadOnlyList<string> GetEntityIds() => [.. _entityTimelines.Keys];
public IReadOnlyList<HistoryStateEntry> GetEntityHistory(string entityId)
{
return _entityTimelines.TryGetValue(entityId, out var entries) ? entries : [];
}
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;
}
}
@@ -1,347 +0,0 @@
using System.Globalization;
using System.Text.Json;
using HomeAssistant.HistoryReplay.HomeAssistantClient;
using Microsoft.Extensions.Logging;
namespace HomeAssistant.HistoryReplay.HistoryData;
public sealed class HomeAssistantHistoryProvider(
IHomeAssistantApiClient client,
ILogger<HomeAssistantHistoryProvider> logger) : IHistoryDataProvider
{
private const int MaxEntitiesPerBatch = 5;
private const int MaxConcurrentRequests = 20;
private const int MaxRetryAttempts = 3;
private static readonly TimeSpan InitialRetryDelay = TimeSpan.FromSeconds(2);
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 allEntityCount = minimalEntityIds.Count + fullEntityIds.Count;
var minimalBatches = ChunkEntities(minimalEntityIds, MaxEntitiesPerBatch);
var fullBatches = ChunkEntities(fullEntityIds, MaxEntitiesPerBatch);
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, entries) in batchResult.Entries)
{
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})",
allEntityCount, timeline.TotalEntryCount, startTime, endTime);
return timeline;
}
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 allEntries = new List<(string, List<HistoryStateEntry>)>();
using var semaphore = new SemaphoreSlim(MaxConcurrentRequests);
var tasks = entityIds.Select(async entityId =>
{
await semaphore.WaitAsync(cancellationToken);
try
{
return await FetchSingleEntityWithRetryAsync(entityId, startTime, endTime, cancellationToken);
}
finally
{
semaphore.Release();
}
});
var results = await Task.WhenAll(tasks).ConfigureAwait(false);
foreach (var result in results)
{
allEntries.AddRange(result);
}
return allEntries;
}
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)
{
return;
}
foreach (var entityArray in response.EnumerateArray())
{
if (entityArray.ValueKind != JsonValueKind.Array)
{
continue;
}
string? currentEntityId = null;
var entries = new List<HistoryStateEntry>();
foreach (var stateObj in entityArray.EnumerateArray())
{
var entry = ParseStateEntry(stateObj, currentEntityId);
if (entry is null)
{
continue;
}
currentEntityId ??= entry.EntityId;
entries.Add(entry);
}
if (currentEntityId is not null && entries.Count > 0)
{
result.Add((currentEntityId, entries));
}
}
}
private static HistoryStateEntry? ParseStateEntry(JsonElement stateObj, string? fallbackEntityId)
{
string? entityId = null;
if (stateObj.TryGetProperty("entity_id", out var entityIdProp))
{
entityId = entityIdProp.GetString();
}
entityId ??= fallbackEntityId;
if (string.IsNullOrEmpty(entityId))
{
return null;
}
var state = stateObj.TryGetProperty("state", out var stateProp) ? stateProp.GetString() : null;
if (!stateObj.TryGetProperty("last_changed", out var lastChangedProp))
{
return null;
}
if (!DateTimeOffset.TryParse(lastChangedProp.GetString(), CultureInfo.InvariantCulture,
DateTimeStyles.RoundtripKind, out var lastChanged))
{
return null;
}
Dictionary<string, object>? attributes = null;
if (stateObj.TryGetProperty("attributes", out var attrProp) && attrProp.ValueKind == JsonValueKind.Object)
{
attributes = ParseAttributes(attrProp);
}
return new HistoryStateEntry
{
EntityId = entityId,
State = state,
LastChanged = lastChanged,
Attributes = attributes
};
}
private static Dictionary<string, object> ParseAttributes(JsonElement attrElement)
{
var attributes = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
foreach (var prop in attrElement.EnumerateObject())
{
attributes[prop.Name] = prop.Value.ValueKind switch
{
JsonValueKind.String => prop.Value.GetString() ?? string.Empty,
JsonValueKind.Number => prop.Value.GetDouble(),
JsonValueKind.True => true,
JsonValueKind.False => false,
_ => prop.Value.GetRawText()
};
}
return attributes;
}
private static IReadOnlyList<IReadOnlyList<string>> ChunkEntities(IReadOnlyList<string> entities, int chunkSize)
{
var chunks = new List<IReadOnlyList<string>>();
for (var i = 0; i < entities.Count; i += chunkSize)
{
chunks.Add(entities.Skip(i).Take(chunkSize).ToList());
}
return chunks;
}
private sealed record BatchFetchResult(
List<(string EntityId, List<HistoryStateEntry> Entries)> Entries,
List<string> FailedEntityIds);
}
@@ -1,17 +0,0 @@
namespace HomeAssistant.HistoryReplay.HistoryData;
public interface IHistoryDataProvider
{
Task<HistoryTimeline> FetchHistoryAsync(
IReadOnlyList<string> entityIds,
DateTimeOffset startTime,
DateTimeOffset endTime,
CancellationToken cancellationToken = default);
Task<HistoryTimeline> FetchHistoryAsync(
IReadOnlyList<string> minimalEntityIds,
IReadOnlyList<string> fullEntityIds,
DateTimeOffset startTime,
DateTimeOffset endTime,
CancellationToken cancellationToken = default);
}
@@ -1,32 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>14.0</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>HomeAssistant.HistoryReplay</RootNamespace>
</PropertyGroup>
<ItemGroup>
<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" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BoilerMonitor.Manager\BoilerMonitor.Manager.csproj" />
<ProjectReference Include="..\BoilerMonitor.Models\BoilerMonitor.Models.csproj" />
<ProjectReference Include="..\NordPool.Manager\NordPool.Manager.csproj" />
<ProjectReference Include="..\NordPool.Models\NordPool.Models.csproj" />
<ProjectReference Include="..\PowerMonitor.Manager\PowerMonitor.Manager.csproj" />
<ProjectReference Include="..\PowerMonitor.Models\PowerMonitor.Models.csproj" />
<ProjectReference Include="..\ShowerMonitor.Manager\ShowerMonitor.Manager.csproj" />
<ProjectReference Include="..\ShowerMonitor.Models\ShowerMonitor.Models.csproj" />
<ProjectReference Include="..\LightMonitor.Manager\LightMonitor.Manager.csproj" />
<ProjectReference Include="..\LightMonitor.Models\LightMonitor.Models.csproj" />
<ProjectReference Include="..\HomeAssistant.Entities\HomeAssistant.Entities.csproj" />
</ItemGroup>
</Project>
@@ -1,53 +0,0 @@
using System.Net.Http.Headers;
using System.Text.Json;
using Microsoft.Extensions.Options;
namespace HomeAssistant.HistoryReplay.HomeAssistantClient;
public sealed class HomeAssistantApiClient : IHomeAssistantApiClient
{
private readonly HttpClient _httpClient;
public HomeAssistantApiClient(HttpClient httpClient, IOptions<HomeAssistantSettings> settings)
{
_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.Timeout = TimeSpan.FromSeconds(HomeAssistantSettings.DefaultTimeoutSeconds);
}
public async Task<JsonElement> GetHistoryAsync(
string entityIds,
DateTimeOffset? startTime = null,
DateTimeOffset? endTime = null,
bool minimalResponse = true,
CancellationToken cancellationToken = default)
{
var start = startTime ?? DateTimeOffset.UtcNow.AddDays(-1);
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);
}
private async Task<JsonElement> GetJsonAsync(string path, CancellationToken cancellationToken)
{
var response = await _httpClient.GetAsync(path, cancellationToken).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
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();
}
}
@@ -1,15 +0,0 @@
namespace HomeAssistant.HistoryReplay.HomeAssistantClient;
public sealed class HomeAssistantSettings
{
public const string SectionName = "HomeAssistant";
public const int DefaultPort = 8123;
public const int DefaultTimeoutSeconds = 3600;
public string Host { get; set; } = string.Empty;
public int Port { get; set; } = DefaultPort;
public string Token { get; set; } = string.Empty;
public bool Ssl { get; set; }
public Uri BaseUrl => new UriBuilder(Ssl ? "https" : "http", Host, Port).Uri;
}
@@ -1,13 +0,0 @@
using System.Text.Json;
namespace HomeAssistant.HistoryReplay.HomeAssistantClient;
public interface IHomeAssistantApiClient
{
Task<JsonElement> GetHistoryAsync(
string entityIds,
DateTimeOffset? startTime = null,
DateTimeOffset? endTime = null,
bool minimalResponse = true,
CancellationToken cancellationToken = default);
}
-77
View File
@@ -1,77 +0,0 @@
using BoilerMonitorManager;
using BoilerMonitorManager.Interface;
using BoilerMonitorManager.Models;
using HomeAssistant.Entities.Interfaces;
using HomeAssistant.HistoryReplay.Components;
using HomeAssistant.HistoryReplay.HistoryData;
using HomeAssistant.HistoryReplay.HomeAssistantClient;
using HomeAssistant.HistoryReplay.Replay;
using HomeAssistant.HistoryReplay.Services;
using LightMonitorManager.Models;
using NordPoolManager;
using NordPoolManager.Interface;
using PowerMonitorManager.Models;
using Serilog;
using ShowerMonitorManager;
using ShowerMonitorManager.Interface;
using ShowerMonitorManager.Models;
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Information()
.WriteTo.Console()
.CreateLogger();
var builder = WebApplication.CreateBuilder(args);
builder.WebHost.UseStaticWebAssets();
builder.Services.AddLogging(logging =>
{
logging.ClearProviders();
logging.AddSerilog(dispose: true);
});
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents();
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));
builder.Services.AddHttpClient<IHomeAssistantApiClient, HomeAssistantApiClient>();
builder.Services.AddSingleton<IHistoryDataProvider, HomeAssistantHistoryProvider>();
builder.Services.AddSingleton<IEntityManager, NoOpEntityManager>();
builder.Services.AddSingleton<ICheapestIntervalsFinder, CheapestIntervalsFinder>();
builder.Services.AddSingleton<IBoilerControlService, BoilerControlService>();
var showerOpts = builder.Configuration
.GetSection(ShowerMonitorOptions.SectionName)
.Get<ShowerMonitorOptions>() ?? new ShowerMonitorOptions();
builder.Services.AddSingleton<IHumidityRateCalculator>(_ => new HumidityRateCalculator(showerOpts.RateWindowSize));
builder.Services.AddSingleton<ReplayOrchestrationService>();
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseHsts();
}
app.MapStaticAssets();
app.UseAntiforgery();
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode();
Log.Information("History Replay Dashboard running at {Urls}", string.Join(", ", app.Urls));
app.Run();
@@ -1,13 +0,0 @@
{
"profiles": {
"HomeAssistant.HistoryReplay": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": false,
"applicationUrl": "http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
-243
View File
@@ -1,243 +0,0 @@
# 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.
@@ -1,38 +0,0 @@
using HomeAssistant.Entities.Interfaces;
using HomeAssistant.Models;
using Microsoft.Extensions.Logging;
namespace HomeAssistant.HistoryReplay.Replay;
public sealed class NoOpEntityManager(ILogger<NoOpEntityManager> logger) : IEntityManager
{
public Task CreateEntitiesAsync(ICollection<EntityCreateModel> entities)
{
logger.LogDebug("[REPLAY] Would create {Count} entities", entities.Count);
return Task.CompletedTask;
}
public Task CreateEntityAsync(EntityCreateModel createModel)
{
logger.LogDebug("[REPLAY] Would create entity: {EntityId}", createModel.EntityId);
return Task.CompletedTask;
}
public Task SetEntityState(string entityId, string state)
{
logger.LogDebug("[REPLAY] Would set state for {EntityId}: {State}", entityId, state);
return Task.CompletedTask;
}
public Task SetEntityAttributes(string entityId, object attributes)
{
logger.LogDebug("[REPLAY] Would set attributes for {EntityId}", entityId);
return Task.CompletedTask;
}
public Task RemoveEntity(string entityId)
{
logger.LogDebug("[REPLAY] Would remove entity: {EntityId}", entityId);
return Task.CompletedTask;
}
}
@@ -1,98 +0,0 @@
using System.Reactive.Linq;
using System.Text.Json;
using HomeAssistant.HistoryReplay.HistoryData;
using HomeAssistant.HistoryReplay.Reporting;
using Microsoft.Extensions.Logging;
using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
namespace HomeAssistant.HistoryReplay.Replay;
public sealed class ReplayHaContext : IHaContext
{
private readonly HistoryTimeline _timeline;
private readonly ReplayTimeProvider _timeProvider;
private readonly ReplayTimeline _replayTimeline;
private readonly ILogger<ReplayHaContext> _logger;
public ReplayHaContext(
HistoryTimeline timeline,
ReplayTimeProvider timeProvider,
ReplayTimeline replayTimeline,
ILogger<ReplayHaContext> logger)
{
_timeline = timeline;
_timeProvider = timeProvider;
_replayTimeline = replayTimeline;
_logger = logger;
}
public EntityState? GetState(string entityId)
{
var currentTime = _timeProvider.GetUtcNow();
var entry = _timeline.GetStateAt(entityId, currentTime);
if (entry is null)
{
return null;
}
JsonElement? attributesJson = null;
if (entry.Attributes is { Count: > 0 })
{
attributesJson = JsonSerializer.SerializeToElement(entry.Attributes);
}
return new EntityState
{
State = entry.State,
AttributesJson = attributesJson
};
}
public IReadOnlyList<Entity> GetAllEntities()
{
return _timeline.GetEntityIds()
.Select(id => new Entity(this, id))
.ToList();
}
public void CallService(string domain, string service, ServiceTarget? target = null, object? data = null)
{
var currentTime = _timeProvider.GetUtcNow();
var targetDescription = target?.EntityIds is not null
? string.Join(", ", target.EntityIds)
: "no target";
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = currentTime,
Monitor = "ServiceCall",
EventType = ReplayEventType.ServiceCall,
Message = $"Would call {domain}.{service} on {targetDescription}",
Details = data is not null ? JsonSerializer.Serialize(data) : null
});
_logger.LogDebug("[REPLAY] {Domain}.{Service} → {Target}", domain, service, targetDescription);
}
public void SendEvent(string eventType, object? data = null)
{
_logger.LogDebug("[REPLAY] Would send event: {EventType}", eventType);
}
public IObservable<StateChange> StateAllChanges() => Observable.Empty<StateChange>();
public IObservable<Event> Events => Observable.Empty<Event>();
public Task<JsonElement?> CallServiceWithResponseAsync(
string domain, string service, ServiceTarget? target = null, object? data = null)
{
CallService(domain, service, target, data);
return Task.FromResult<JsonElement?>(null);
}
public Area? GetAreaFromEntityId(string entityId) => null;
public EntityRegistration? GetEntityRegistration(string entityId) => null;
}
@@ -1,40 +0,0 @@
namespace HomeAssistant.HistoryReplay.Replay;
public sealed class ReplayTimeProvider : TimeProvider
{
private readonly Lock _lock = new();
private DateTimeOffset _currentUtcTime;
private readonly TimeZoneInfo _localTimeZone;
public ReplayTimeProvider(DateTimeOffset initialTime)
{
_currentUtcTime = initialTime.ToUniversalTime();
_localTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
}
public override DateTimeOffset GetUtcNow()
{
lock (_lock)
{
return _currentUtcTime;
}
}
public override TimeZoneInfo LocalTimeZone => _localTimeZone;
public void AdvanceTo(DateTimeOffset utcTime)
{
lock (_lock)
{
_currentUtcTime = utcTime.ToUniversalTime();
}
}
public void AdvanceBy(TimeSpan duration)
{
lock (_lock)
{
_currentUtcTime += duration;
}
}
}
@@ -1,157 +0,0 @@
using HomeAssistant.HistoryReplay.Configuration;
namespace HomeAssistant.HistoryReplay.Reporting;
public sealed class ConsoleReportRenderer
{
private const string Separator = "═══════════════════════════════════════════════════════════";
private const string SectionSeparator = "── {0} ──────────────────────────────────────────────";
private const string TimeFormat = "HH:mm:ss";
public void Render(ReplayTimeline timeline, ReplayOptions options)
{
Console.WriteLine();
WriteColored(Separator, ConsoleColor.DarkCyan);
WriteColored($" REPLAY: {options.StartTime:yyyy-MM-dd HH:mm} → {options.EndTime:yyyy-MM-dd HH:mm}", ConsoleColor.White);
WriteColored(Separator, ConsoleColor.DarkCyan);
Console.WriteLine();
var monitors = timeline.GetMonitors()
.Where(m => !string.Equals(m, "ServiceCall", StringComparison.OrdinalIgnoreCase))
.ToList();
foreach (var monitor in monitors)
{
RenderMonitorSection(monitor, timeline.GetEventsByMonitor(monitor));
}
RenderServiceCallSection(timeline.GetEventsByMonitor("ServiceCall"));
RenderSummary(timeline);
}
private static void RenderMonitorSection(string monitor, IReadOnlyList<ReplayEvent> events)
{
Console.WriteLine();
WriteColored(string.Format(SectionSeparator, monitor), ConsoleColor.Yellow);
if (events.Count == 0)
{
WriteColored(" No events recorded", ConsoleColor.DarkGray);
return;
}
foreach (var evt in events)
{
var color = GetEventColor(evt.EventType);
var prefix = GetEventPrefix(evt.EventType);
var timestamp = evt.Timestamp.ToLocalTime().ToString(TimeFormat);
WriteColored($" {timestamp} {prefix}{evt.Message}", color);
if (!string.IsNullOrEmpty(evt.Details))
{
WriteColored($" {evt.Details}", ConsoleColor.DarkGray);
}
}
WriteSectionSummary(events);
}
private static void RenderServiceCallSection(IReadOnlyList<ReplayEvent> events)
{
if (events.Count == 0)
{
return;
}
Console.WriteLine();
WriteColored(string.Format(SectionSeparator, "Service Calls"), ConsoleColor.Magenta);
foreach (var evt in events)
{
var timestamp = evt.Timestamp.ToLocalTime().ToString(TimeFormat);
WriteColored($" {timestamp} → {evt.Message}", ConsoleColor.DarkMagenta);
}
WriteColored($"\n Total: {events.Count} service call(s) would have been made", ConsoleColor.DarkGray);
}
private static void RenderSummary(ReplayTimeline timeline)
{
var allEvents = timeline.GetAllEvents();
Console.WriteLine();
WriteColored(Separator, ConsoleColor.DarkCyan);
WriteColored(" REPLAY SUMMARY", ConsoleColor.White);
WriteColored(Separator, ConsoleColor.DarkCyan);
var decisions = allEvents.Count(e => e.EventType == ReplayEventType.Decision);
var serviceCalls = allEvents.Count(e => e.EventType == ReplayEventType.ServiceCall);
var warnings = allEvents.Count(e => e.EventType == ReplayEventType.Warning);
var anomalies = allEvents.Count(e => e.EventType == ReplayEventType.Anomaly);
WriteColored($" Total events: {allEvents.Count}", ConsoleColor.Gray);
WriteColored($" Decisions: {decisions}", ConsoleColor.Cyan);
WriteColored($" Service calls: {serviceCalls}", ConsoleColor.Magenta);
WriteColored($" Warnings: {warnings}", ConsoleColor.DarkYellow);
WriteColored($" Anomalies: {anomalies}", ConsoleColor.Red);
Console.WriteLine();
}
private static void WriteSectionSummary(IReadOnlyList<ReplayEvent> events)
{
var decisions = events.Count(e => e.EventType == ReplayEventType.Decision);
var warnings = events.Count(e => e.EventType == ReplayEventType.Warning);
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 (parts.Count > 0)
{
WriteColored($"\n Summary: {string.Join(", ", parts)}", ConsoleColor.DarkGray);
}
}
private static ConsoleColor GetEventColor(ReplayEventType eventType) =>
eventType switch
{
ReplayEventType.Decision => ConsoleColor.Green,
ReplayEventType.StateChange => ConsoleColor.Cyan,
ReplayEventType.Warning => ConsoleColor.DarkYellow,
ReplayEventType.ServiceCall => ConsoleColor.Magenta,
ReplayEventType.Anomaly => ConsoleColor.Red,
_ => ConsoleColor.Gray
};
private static string GetEventPrefix(ReplayEventType eventType) =>
eventType switch
{
ReplayEventType.Decision => "→ ",
ReplayEventType.Warning => "⚠ ",
ReplayEventType.Anomaly => "⚠ ANOMALY: ",
ReplayEventType.ServiceCall => "⤷ ",
_ => ""
};
private static void WriteColored(string text, ConsoleColor color)
{
var previousColor = Console.ForegroundColor;
Console.ForegroundColor = color;
Console.WriteLine(text);
Console.ForegroundColor = previousColor;
}
}
@@ -1,9 +0,0 @@
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; }
}
@@ -1,50 +0,0 @@
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();
}
}
@@ -1,20 +0,0 @@
namespace HomeAssistant.HistoryReplay.Reporting;
public sealed class ReplayEvent
{
public required DateTimeOffset Timestamp { get; init; }
public required string Monitor { get; init; }
public required ReplayEventType EventType { get; init; }
public required string Message { get; init; }
public string? Details { get; init; }
}
public enum ReplayEventType
{
Info,
Decision,
StateChange,
Warning,
ServiceCall,
Anomaly
}
@@ -1,30 +0,0 @@
using System.Collections.Concurrent;
namespace HomeAssistant.HistoryReplay.Reporting;
public sealed class ReplayTimeline
{
private readonly ConcurrentBag<ReplayEvent> _events = [];
public void AddEvent(ReplayEvent replayEvent)
{
_events.Add(replayEvent);
}
public IReadOnlyList<ReplayEvent> GetEventsByMonitor(string monitor) =>
_events
.Where(e => string.Equals(e.Monitor, monitor, StringComparison.OrdinalIgnoreCase))
.OrderBy(e => e.Timestamp)
.ToList();
public IReadOnlyList<ReplayEvent> GetAllEvents() =>
_events.OrderBy(e => e.Timestamp).ToList();
public IReadOnlyList<string> GetMonitors() =>
_events.Select(e => e.Monitor).Distinct(StringComparer.OrdinalIgnoreCase).Order().ToList();
public void Clear()
{
_events.Clear();
}
}
@@ -1,221 +0,0 @@
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;
namespace HomeAssistant.HistoryReplay.Runners;
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 string _boilerPowerEntityId;
private readonly string _boilerSwitchEntityId;
public string MonitorName => "Boiler";
public BoilerReplayRunner(
HistoryTimeline timeline,
ReplayTimeProvider timeProvider,
ReplayTimeline replayTimeline,
ReplayDataSeries dataSeries,
IBoilerControlService boilerControlService,
IBoilerRunTimeTracker tracker,
IWaterReadyService waterReadyService,
ILogger<BoilerReplayRunner> logger,
IOptions<ReplayOptions> replayOptions,
string boilerPowerEntityId,
string boilerSwitchEntityId)
{
_timeline = timeline;
_timeProvider = timeProvider;
_replayTimeline = replayTimeline;
_dataSeries = dataSeries;
_boilerControlService = boilerControlService;
_tracker = tracker;
_waterReadyService = waterReadyService;
_logger = logger;
_replayOptions = replayOptions.Value;
_boilerPowerEntityId = boilerPowerEntityId;
_boilerSwitchEntityId = boilerSwitchEntityId;
}
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 = _boilerPowerEntityId;
var boilerSwitchEntityId = _boilerSwitchEntityId;
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 autoManagementEntry = _timeline.GetStateAt(BoilerMonitorConsts.AutoManagementEntityId, 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);
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);
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;
_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);
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()
};
if (autoManagementEnabled)
{
_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();
}
}
else
{
_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}"
});
}
}
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 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;
}
}
@@ -1,7 +0,0 @@
namespace HomeAssistant.HistoryReplay.Runners;
public interface IMonitorReplayRunner
{
string MonitorName { get; }
Task RunAsync(CancellationToken cancellationToken = default);
}
@@ -1,188 +0,0 @@
using HomeAssistant.HistoryReplay.Configuration;
using HomeAssistant.HistoryReplay.HistoryData;
using HomeAssistant.HistoryReplay.Replay;
using HomeAssistant.HistoryReplay.Reporting;
using LightMonitor.Models;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using LightMonitorManager.Models;
namespace HomeAssistant.HistoryReplay.Runners;
public sealed class LightReplayRunner : IMonitorReplayRunner
{
private readonly HistoryTimeline _timeline;
private readonly ReplayTimeProvider _timeProvider;
private readonly ReplayTimeline _replayTimeline;
private readonly ReplayDataSeries _dataSeries;
private readonly ILogger<LightReplayRunner> _logger;
private readonly ReplayOptions _replayOptions;
private readonly LightMonitorOptions _lightOptions;
public string MonitorName => "Light";
public LightReplayRunner(
HistoryTimeline timeline,
ReplayTimeProvider timeProvider,
ReplayTimeline replayTimeline,
ReplayDataSeries dataSeries,
ILogger<LightReplayRunner> logger,
IOptions<ReplayOptions> replayOptions,
IOptions<LightMonitorOptions> lightOptions)
{
_timeline = timeline;
_timeProvider = timeProvider;
_replayTimeline = replayTimeline;
_dataSeries = dataSeries;
_logger = logger;
_replayOptions = replayOptions.Value;
_lightOptions = lightOptions.Value;
}
public Task RunAsync(CancellationToken cancellationToken = default)
{
_logger.LogInformation("Starting Light replay");
ReplaySunEvents(cancellationToken);
ReplayPersonArrivals(cancellationToken);
_logger.LogInformation("Light replay complete");
return Task.CompletedTask;
}
private void ReplaySunEvents(CancellationToken cancellationToken)
{
var sunHistory = _timeline.GetEntityHistory(_lightOptions.SunEntityId);
string? previousSunState = null;
foreach (var entry in sunHistory)
{
if (cancellationToken.IsCancellationRequested)
{
break;
}
if (entry.LastChanged < _replayOptions.StartTime || entry.LastChanged > _replayOptions.EndTime)
{
continue;
}
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);
var anyoneHome = IsAnyoneHome(entry.LastChanged);
var lightState = _timeline.GetStateAt(_lightOptions.LightEntityId, entry.LastChanged)?.State;
var lightAlreadyOn = string.Equals(lightState, LightMonitorConsts.LightOnState, StringComparison.OrdinalIgnoreCase);
if (anyoneHome && !lightAlreadyOn)
{
_dataSeries.AddPoint(MonitorName, "LightOn", entry.LastChanged, 1.0);
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = entry.LastChanged,
Monitor = MonitorName,
EventType = ReplayEventType.Decision,
Message = "TURN ON light (sun below horizon + someone home)"
});
}
else if (!anyoneHome)
{
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = entry.LastChanged,
Monitor = MonitorName,
EventType = ReplayEventType.Info,
Message = "Sun below horizon but nobody home -- light stays off"
});
}
else
{
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = entry.LastChanged,
Monitor = MonitorName,
EventType = ReplayEventType.Info,
Message = "Sun below horizon but light already on"
});
}
}
previousSunState = entry.State;
}
}
private void ReplayPersonArrivals(CancellationToken cancellationToken)
{
foreach (var personEntityId in _lightOptions.PersonEntityIds)
{
var personHistory = _timeline.GetEntityHistory(personEntityId);
string? previousState = null;
foreach (var entry in personHistory)
{
if (cancellationToken.IsCancellationRequested)
{
break;
}
if (entry.LastChanged < _replayOptions.StartTime || entry.LastChanged > _replayOptions.EndTime)
{
continue;
}
if (string.Equals(entry.State, LightMonitorConsts.PersonHomeState, StringComparison.OrdinalIgnoreCase) &&
!string.Equals(previousState, LightMonitorConsts.PersonHomeState, StringComparison.OrdinalIgnoreCase))
{
_timeProvider.AdvanceTo(entry.LastChanged);
var sunEntry = _timeline.GetStateAt(_lightOptions.SunEntityId, entry.LastChanged);
var isDark = string.Equals(sunEntry?.State, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase);
var lightState = _timeline.GetStateAt(_lightOptions.LightEntityId, entry.LastChanged)?.State;
var lightAlreadyOn = string.Equals(lightState, LightMonitorConsts.LightOnState, StringComparison.OrdinalIgnoreCase);
if (isDark && !lightAlreadyOn)
{
_dataSeries.AddPoint(MonitorName, "LightOn", entry.LastChanged, 1.0);
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = entry.LastChanged,
Monitor = MonitorName,
EventType = ReplayEventType.Decision,
Message = $"TURN ON light ({personEntityId} arrived home + dark outside)"
});
}
else if (isDark)
{
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = entry.LastChanged,
Monitor = MonitorName,
EventType = ReplayEventType.Info,
Message = $"{personEntityId} arrived home (dark) but light already on"
});
}
}
previousState = entry.State;
}
}
}
private bool IsAnyoneHome(DateTimeOffset timestamp)
{
foreach (var personEntityId in _lightOptions.PersonEntityIds)
{
var entry = _timeline.GetStateAt(personEntityId, timestamp);
if (string.Equals(entry?.State, LightMonitorConsts.PersonHomeState, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
}
@@ -1,182 +0,0 @@
using System.Globalization;
using BoilerMonitor.Models;
using HomeAssistant.HistoryReplay.Configuration;
using HomeAssistant.HistoryReplay.HistoryData;
using HomeAssistant.HistoryReplay.Replay;
using HomeAssistant.HistoryReplay.Reporting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NordPool.Models;
using NordPoolManager.Interface;
namespace HomeAssistant.HistoryReplay.Runners;
public sealed class NordPoolReplayRunner : IMonitorReplayRunner
{
private readonly HistoryTimeline _timeline;
private readonly ReplayTimeProvider _timeProvider;
private readonly ReplayTimeline _replayTimeline;
private readonly 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)
{
_timeline = timeline;
_timeProvider = timeProvider;
_replayTimeline = replayTimeline;
_dataSeries = dataSeries;
_cheapestIntervalsFinder = cheapestIntervalsFinder;
_logger = logger;
_options = options.Value;
}
public Task RunAsync(CancellationToken cancellationToken = default)
{
_logger.LogInformation("Starting NordPool replay");
var currentTime = _options.StartTime;
var interval = TimeSpan.FromMinutes(NordPoolConsts.MinutesPerInterval);
double? lastReportedPrice = null;
while (currentTime <= _options.EndTime && !cancellationToken.IsCancellationRequested)
{
_timeProvider.AdvanceTo(currentTime);
var priceEntry = _timeline.GetStateAt(NordPoolHaSensorId, currentTime)
?? _timeline.GetStateAt(NordPoolConsts.CurrentPriceEntityId, currentTime);
if (priceEntry?.State is not null &&
double.TryParse(priceEntry.State, CultureInfo.InvariantCulture, out var currentPrice))
{
_dataSeries.AddPoint(MonitorName, "Price", currentTime, currentPrice);
if (lastReportedPrice is null || Math.Abs(currentPrice - lastReportedPrice.Value) > 0.01)
{
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = currentTime,
Monitor = MonitorName,
EventType = ReplayEventType.Info,
Message = $"Price: {currentPrice:F2} ct/kWh"
});
lastReportedPrice = currentPrice;
}
}
var boilerConfig = ReadBoilerConfig(currentTime);
if (boilerConfig is not null)
{
var prices = BuildNordPoolPriceFromHistory(currentTime);
if (prices.Prices is { Count: > 0 })
{
var effectivePriceCap = boilerConfig.SkipPriceCap ? double.MaxValue : boilerConfig.PriceCap;
var effectiveIntervalCount = boilerConfig.SkipPriceCap
? NordPoolConsts.MaxDailyIntervals
: boilerConfig.IntervalCount;
var cheapest = _cheapestIntervalsFinder.FindCheapestIntervals(
prices, effectiveIntervalCount, effectivePriceCap, boilerConfig.Deadline);
var isNowCheap = _cheapestIntervalsFinder.IsCurrentIntervalCheap(
cheapest, currentTime.LocalDateTime);
_dataSeries.AddPoint(MonitorName, "IsCheap", currentTime, isNowCheap ? 1.0 : 0.0);
if (isNowCheap)
{
var currentInterval = cheapest.FirstOrDefault(i =>
currentTime.LocalDateTime >= i.Start && currentTime.LocalDateTime < i.End);
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = currentTime,
Monitor = MonitorName,
EventType = ReplayEventType.Decision,
Message = $"CHEAP interval active (rank #{currentInterval?.Rank}, price: {currentInterval?.Price:F2} ct/kWh)",
Details = $"Total cheap intervals: {cheapest.Count}"
});
}
}
}
currentTime = currentTime.Add(interval);
}
_logger.LogInformation("NordPool replay complete");
return Task.CompletedTask;
}
private BoilerConfig? ReadBoilerConfig(DateTimeOffset timestamp)
{
var dailyHoursEntry = _timeline.GetStateAt(BoilerMonitorConsts.BoilerDailyHoursEntityId, timestamp);
var priceCapEntry = _timeline.GetStateAt(BoilerMonitorConsts.BoilerPriceCapEntityId, timestamp);
var readyByEntry = _timeline.GetStateAt(BoilerMonitorConsts.BoilerReadyByEntityId, timestamp);
var skipPriceCapEntry = _timeline.GetStateAt(BoilerMonitorConsts.SkipPriceCapEntityId, timestamp);
if (dailyHoursEntry?.State is null || priceCapEntry?.State is null || readyByEntry?.State is null)
{
return null;
}
if (!double.TryParse(dailyHoursEntry.State, CultureInfo.InvariantCulture, out var dailyHours) ||
!double.TryParse(priceCapEntry.State, CultureInfo.InvariantCulture, out var priceCap))
{
return null;
}
var intervalCount = (int)(dailyHours * NordPoolConsts.IntervalsPerHour);
if (!TimeSpan.TryParse(readyByEntry.State, CultureInfo.InvariantCulture, out var readyByTime))
{
return null;
}
var deadline = timestamp.LocalDateTime.Date.Add(readyByTime);
if (deadline < timestamp.LocalDateTime)
{
deadline = deadline.AddDays(1);
}
var skipPriceCap = string.Equals(skipPriceCapEntry?.State, "on", StringComparison.OrdinalIgnoreCase);
return new BoilerConfig
{
IntervalCount = intervalCount,
PriceCap = priceCap,
Deadline = deadline,
SkipPriceCap = skipPriceCap
};
}
private NordPoolPrice BuildNordPoolPriceFromHistory(DateTimeOffset timestamp)
{
var nordPoolSensorEntries = _timeline.GetEntityHistory("sensor.nordpool_kwh_lt_eur_3_10_0");
var todayDate = timestamp.LocalDateTime.Date;
var todayPrices = nordPoolSensorEntries
.Where(e => e.LastChanged.LocalDateTime.Date == todayDate)
.Where(e => e.State is not null && double.TryParse(e.State, CultureInfo.InvariantCulture, out _))
.Select(e => new NordPoolDayPrice
{
Start = e.LastChanged.LocalDateTime,
End = e.LastChanged.LocalDateTime.AddMinutes(NordPoolConsts.MinutesPerInterval),
Price = double.Parse(e.State!, CultureInfo.InvariantCulture)
})
.ToList();
return new NordPoolPrice { Prices = todayPrices };
}
}
@@ -1,163 +0,0 @@
using System.Globalization;
using HomeAssistant.HistoryReplay.Configuration;
using HomeAssistant.HistoryReplay.HistoryData;
using HomeAssistant.HistoryReplay.Replay;
using HomeAssistant.HistoryReplay.Reporting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NordPool.Models;
using PowerMonitorManager.Interface;
using PowerMonitorManager.Models;
namespace HomeAssistant.HistoryReplay.Runners;
public sealed class PowerReplayRunner : IMonitorReplayRunner
{
private readonly HistoryTimeline _timeline;
private readonly ReplayTimeProvider _timeProvider;
private readonly ReplayTimeline _replayTimeline;
private readonly ReplayDataSeries _dataSeries;
private readonly IOtherPowerCalculationService _calculationService;
private readonly IPowerCostCalculationService _costService;
private readonly ILogger<PowerReplayRunner> _logger;
private readonly ReplayOptions _replayOptions;
private readonly PowerMonitorOptions _powerOptions;
public string MonitorName => "Power";
public PowerReplayRunner(
HistoryTimeline timeline,
ReplayTimeProvider timeProvider,
ReplayTimeline replayTimeline,
ReplayDataSeries dataSeries,
IOtherPowerCalculationService calculationService,
IPowerCostCalculationService costService,
ILogger<PowerReplayRunner> logger,
IOptions<ReplayOptions> replayOptions,
IOptions<PowerMonitorOptions> powerOptions)
{
_timeline = timeline;
_timeProvider = timeProvider;
_replayTimeline = replayTimeline;
_dataSeries = dataSeries;
_calculationService = calculationService;
_costService = costService;
_logger = logger;
_replayOptions = replayOptions.Value;
_powerOptions = powerOptions.Value;
}
public Task RunAsync(CancellationToken cancellationToken = default)
{
_logger.LogInformation("Starting Power replay");
var currentTime = _replayOptions.StartTime;
var pollInterval = TimeSpan.FromSeconds(_powerOptions.PollIntervalSeconds);
DateTime? anomalyStartTime = null;
while (currentTime <= _replayOptions.EndTime && !cancellationToken.IsCancellationRequested)
{
_timeProvider.AdvanceTo(currentTime);
var mainMeterEntry = _timeline.GetStateAt(_powerOptions.MainMeterEntityId, currentTime);
var totalPower = ParseDouble(mainMeterEntry?.State);
if (!totalPower.HasValue)
{
currentTime = currentTime.Add(pollInterval);
continue;
}
var deviceReadings = DiscoverAndReadDevicePower(currentTime);
var calculation = _calculationService.Calculate(totalPower.Value, deviceReadings);
_dataSeries.AddPoint(MonitorName, "TotalPower", currentTime, calculation.TotalPowerWatts);
_dataSeries.AddPoint(MonitorName, "KnownDevices", currentTime, calculation.KnownDevicesSumWatts);
_dataSeries.AddPoint(MonitorName, "OtherPower", currentTime, calculation.SmoothedOtherPowerWatts);
var nordPoolPriceEntry = _timeline.GetStateAt(NordPoolConsts.CurrentPriceEntityId, currentTime);
var nordPoolPrice = ParseDouble(nordPoolPriceEntry?.State) ?? 0;
_costService.RecordCosts(calculation, nordPoolPrice, _powerOptions.PollIntervalSeconds, currentTime.LocalDateTime);
var isAnomaly = calculation.SmoothedOtherPowerWatts > _powerOptions.AnomalyThresholdWatts;
if (isAnomaly && anomalyStartTime is null)
{
anomalyStartTime = currentTime.LocalDateTime;
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = currentTime,
Monitor = MonitorName,
EventType = ReplayEventType.Anomaly,
Message = $"Other power {calculation.SmoothedOtherPowerWatts:F0}W exceeds threshold {_powerOptions.AnomalyThresholdWatts}W",
Details = $"Total: {calculation.TotalPowerWatts:F0}W, Known: {calculation.KnownDevicesSumWatts:F0}W"
});
}
else if (!isAnomaly && anomalyStartTime is not null)
{
var duration = currentTime.LocalDateTime - anomalyStartTime.Value;
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = currentTime,
Monitor = MonitorName,
EventType = ReplayEventType.Info,
Message = $"Anomaly resolved after {duration:mm\\:ss}"
});
anomalyStartTime = null;
}
currentTime = currentTime.Add(pollInterval);
}
var totalCost = _costService.GetTotalCostSnapshot();
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = _replayOptions.EndTime,
Monitor = MonitorName,
EventType = ReplayEventType.Info,
Message = $"Final: Total daily cost {totalCost.CostDaily:F4} EUR"
});
_logger.LogInformation("Power replay complete");
return Task.CompletedTask;
}
private IReadOnlyDictionary<string, double> DiscoverAndReadDevicePower(DateTimeOffset timestamp)
{
var readings = new Dictionary<string, double>();
var allEntities = _timeline.GetEntityIds();
foreach (var entityId in allEntities)
{
if (!entityId.StartsWith("sensor.", StringComparison.OrdinalIgnoreCase) ||
!entityId.EndsWith("_power", StringComparison.OrdinalIgnoreCase))
{
continue;
}
if (string.Equals(entityId, _powerOptions.MainMeterEntityId, StringComparison.OrdinalIgnoreCase))
{
continue;
}
var entry = _timeline.GetStateAt(entityId, timestamp);
var value = ParseDouble(entry?.State);
if (value.HasValue)
{
readings[entityId] = value.Value;
}
}
return readings;
}
private static double? ParseDouble(string? value)
{
if (value is null or "unavailable" or "unknown")
{
return null;
}
return double.TryParse(value, CultureInfo.InvariantCulture, out var result) ? result : null;
}
}
@@ -1,136 +0,0 @@
using System.Globalization;
using HomeAssistant.HistoryReplay.Configuration;
using HomeAssistant.HistoryReplay.HistoryData;
using HomeAssistant.HistoryReplay.Replay;
using HomeAssistant.HistoryReplay.Reporting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NetDaemon.HassModel;
using ShowerMonitor.Models.Enums;
using ShowerMonitorManager.Interface;
using ShowerMonitorManager.Models;
namespace HomeAssistant.HistoryReplay.Runners;
public sealed class ShowerReplayRunner : IMonitorReplayRunner
{
private readonly HistoryTimeline _timeline;
private readonly ReplayTimeProvider _timeProvider;
private readonly ReplayTimeline _replayTimeline;
private readonly ReplayDataSeries _dataSeries;
private readonly IShowerDetectionService _detectionService;
private readonly IExhaustFanControlService _fanControlService;
private readonly ILogger<ShowerReplayRunner> _logger;
private readonly ReplayOptions _replayOptions;
private readonly ShowerMonitorOptions _showerOptions;
public string MonitorName => "Shower";
public ShowerReplayRunner(
HistoryTimeline timeline,
ReplayTimeProvider timeProvider,
ReplayTimeline replayTimeline,
ReplayDataSeries dataSeries,
IShowerDetectionService detectionService,
IExhaustFanControlService fanControlService,
ILogger<ShowerReplayRunner> logger,
IOptions<ReplayOptions> replayOptions,
IOptions<ShowerMonitorOptions> showerOptions)
{
_timeline = timeline;
_timeProvider = timeProvider;
_replayTimeline = replayTimeline;
_dataSeries = dataSeries;
_detectionService = detectionService;
_fanControlService = fanControlService;
_logger = logger;
_replayOptions = replayOptions.Value;
_showerOptions = showerOptions.Value;
}
public Task RunAsync(CancellationToken cancellationToken = default)
{
_logger.LogInformation("Starting Shower replay");
var currentTime = _replayOptions.StartTime;
var pollInterval = TimeSpan.FromSeconds(_showerOptions.PollIntervalSeconds);
var previousState = ShowerState.Idle;
while (currentTime <= _replayOptions.EndTime && !cancellationToken.IsCancellationRequested)
{
_timeProvider.AdvanceTo(currentTime);
var bathroomEntry = _timeline.GetStateAt(_showerOptions.BathroomHumidityEntityId, currentTime);
var homeEntry = _timeline.GetStateAt(_showerOptions.MainHomeHumidityEntityId, currentTime);
var bathroomHumidity = ParseDouble(bathroomEntry?.State);
var homeHumidity = ParseDouble(homeEntry?.State);
if (bathroomHumidity.HasValue && homeHumidity.HasValue)
{
_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;
_dataSeries.AddPoint(MonitorName, "State", currentTime, (double)state);
_fanControlService.Evaluate(state, currentTime);
if (state != previousState)
{
var eventType = state switch
{
ShowerState.Active => ReplayEventType.Decision,
ShowerState.Completed => ReplayEventType.StateChange,
_ => ReplayEventType.Info
};
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = currentTime,
Monitor = MonitorName,
EventType = eventType,
Message = $"State: {previousState} -> {state} (bathroom: {bathroomHumidity.Value:F1}%, home: {homeHumidity.Value:F1}%, diff: {differential:F1}%)",
Details = GetStateChangeDetails(state)
});
previousState = state;
}
}
currentTime = currentTime.Add(pollInterval);
}
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = _replayOptions.EndTime,
Monitor = MonitorName,
EventType = ReplayEventType.Info,
Message = $"Final: {_detectionService.TodaySessionCount} session(s) detected"
});
_logger.LogInformation("Shower replay complete");
return Task.CompletedTask;
}
private string? GetStateChangeDetails(ShowerState state) =>
state switch
{
ShowerState.Completed when _detectionService.LastCompletedSession is not null =>
$"Duration: {_detectionService.LastCompletedSession.Duration:mm\\:ss}, Peak humidity: {_detectionService.LastCompletedSession.PeakHumidity:F1}%",
_ => null
};
private static double? ParseDouble(string? value)
{
if (value is null or "unavailable" or "unknown")
{
return null;
}
return double.TryParse(value, CultureInfo.InvariantCulture, out var result) ? result : null;
}
}
@@ -1,214 +0,0 @@
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(replayHaContext, showerOpts);
runners.Add(new ShowerReplayRunner(
historyTimeline, timeProvider, Timeline, DataSeries,
detection, fan,
_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();
}
@@ -1,10 +0,0 @@
namespace HomeAssistant.HistoryReplay.Services;
public enum ReplayStatus
{
Idle,
FetchingHistory,
Running,
Completed,
Failed
}
@@ -1,57 +0,0 @@
{
"HomeAssistant": {
"Host": "homeassistant.local",
"Port": 8123,
"Token": "<your-long-lived-access-token>",
"Ssl": false
},
"Replay": {
"StartTime": "2026-03-01T00:00:00+02:00",
"EndTime": "2026-03-31T00:00:00+02:00",
"Monitors": {
"NordPool": true,
"Boiler": true,
"Shower": true,
"Power": true,
"Light": true
}
},
"BoilerMonitor": {
"Enabled": true,
"CleanupEntitiesOnStartup": false
},
"ShowerMonitor": {
"Enabled": true,
"CleanupEntitiesOnStartup": false,
"BathroomHumidityEntityId": "sensor.bathroom_humidity",
"MainHomeHumidityEntityId": "sensor.main_home_humidity",
"BathroomTemperatureEntityId": "sensor.bathroom_temperature",
"ExhaustFanEntityId": "switch.exhaust_fan",
"PollIntervalSeconds": 30,
"SpikeRateThreshold": 4.0,
"MinDifferentialHumidity": 8.0,
"PeakHumidityThreshold": 58.0,
"ConfirmationWindowMinutes": 2,
"RecoveryDifferentialThreshold": 5.0,
"MaxShowerDurationMinutes": 60,
"FanRunAfterShowerMinutes": 10,
"RateWindowSize": 5
},
"LightMonitor": {
"Enabled": true,
"LightEntityId": "light.sonoff_1002214d40",
"SunEntityId": "sun.sun",
"PersonEntityIds": ["person.marius", "person.erika", "person.home_phone"]
},
"PowerMonitor": {
"Enabled": false,
"MainMeterEntityId": "sensor.sonoff_100267d63f_power",
"PollIntervalSeconds": 1,
"SmoothingWindowSize": 10,
"AnomalyThresholdWatts": 500,
"ExcludedSensorPatterns": [
"sensor.nordpool_*",
"sensor.powermonitor_*"
]
}
}
@@ -1,57 +0,0 @@
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;
}
@@ -1,25 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>14.0</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>HomeAssistant.McpServer</RootNamespace>
</PropertyGroup>
<ItemGroup>
<Content Include="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="10.0.5" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="10.0.5" />
<PackageReference Include="Microsoft.Extensions.Http" Version="10.0.5" />
<PackageReference Include="ModelContextProtocol" Version="1.2.0" />
</ItemGroup>
</Project>
-28
View File
@@ -1,28 +0,0 @@
using HomeAssistant.McpServer.Services;
using HomeAssistant.McpServer.Settings;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
var builder = Host.CreateApplicationBuilder(new HostApplicationBuilderSettings
{
Args = args,
ContentRootPath = AppContext.BaseDirectory
});
builder.Logging.AddConsole(options =>
{
options.LogToStandardErrorThreshold = LogLevel.Trace;
});
builder.Services
.Configure<HomeAssistantSettings>(
builder.Configuration.GetSection(HomeAssistantSettings.SectionName))
.AddHttpClient<IHomeAssistantApiClient, HomeAssistantApiClient>();
builder.Services
.AddMcpServer()
.WithStdioServerTransport()
.WithToolsFromAssembly();
await builder.Build().RunAsync();
@@ -1,118 +0,0 @@
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using HomeAssistant.McpServer.Settings;
using Microsoft.Extensions.Options;
namespace HomeAssistant.McpServer.Services;
public sealed class HomeAssistantApiClient : IHomeAssistantApiClient
{
private readonly HttpClient _httpClient;
public HomeAssistantApiClient(HttpClient httpClient, IOptions<HomeAssistantSettings> settings)
{
_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.Timeout = TimeSpan.FromSeconds(HomeAssistantSettings.DefaultTimeoutSeconds);
}
public Task<JsonElement> GetApiStatusAsync(CancellationToken cancellationToken = default) =>
GetJsonAsync("/api/", cancellationToken);
public Task<JsonElement> GetConfigAsync(CancellationToken cancellationToken = default) =>
GetJsonAsync("/api/config", cancellationToken);
public Task<JsonElement> GetAllStatesAsync(CancellationToken cancellationToken = default) =>
GetJsonAsync("/api/states", cancellationToken);
public Task<JsonElement> GetEntityStateAsync(string entityId, CancellationToken cancellationToken = default) =>
GetJsonAsync($"/api/states/{Uri.EscapeDataString(entityId)}", cancellationToken);
public Task<JsonElement> GetServicesAsync(CancellationToken cancellationToken = default) =>
GetJsonAsync("/api/services", cancellationToken);
public Task<JsonElement> GetHistoryAsync(
string entityIds,
DateTimeOffset? startTime = null,
DateTimeOffset? endTime = null,
bool minimalResponse = true,
CancellationToken cancellationToken = default)
{
var start = startTime ?? DateTimeOffset.UtcNow.AddDays(-1);
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 GetJsonAsync(path, cancellationToken);
}
public Task<JsonElement> GetLogbookAsync(
string? entityId = null,
DateTimeOffset? startTime = null,
DateTimeOffset? endTime = null,
CancellationToken cancellationToken = default)
{
var start = startTime ?? DateTimeOffset.UtcNow.AddDays(-1);
var path = $"/api/logbook/{start:O}";
var queryParts = new List<string>();
if (!string.IsNullOrWhiteSpace(entityId))
{
queryParts.Add($"entity={Uri.EscapeDataString(entityId)}");
}
if (endTime.HasValue)
{
queryParts.Add($"end_time={Uri.EscapeDataString(endTime.Value.ToString("O"))}");
}
if (queryParts.Count > 0)
{
path += "?" + string.Join("&", queryParts);
}
return GetJsonAsync(path, cancellationToken);
}
public async Task<JsonElement> CallServiceAsync(
string domain,
string service,
JsonElement? serviceData = null,
CancellationToken cancellationToken = default)
{
var url = $"/api/services/{Uri.EscapeDataString(domain)}/{Uri.EscapeDataString(service)}";
var content = serviceData.HasValue
? JsonContent.Create(serviceData.Value)
: JsonContent.Create(new { });
var response = await _httpClient.PostAsync(url, content, cancellationToken).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
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();
}
private async Task<JsonElement> GetJsonAsync(string path, CancellationToken cancellationToken)
{
var response = await _httpClient.GetAsync(path, cancellationToken).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
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();
}
}
@@ -1,31 +0,0 @@
using System.Text.Json;
namespace HomeAssistant.McpServer.Services;
public interface IHomeAssistantApiClient
{
Task<JsonElement> GetApiStatusAsync(CancellationToken cancellationToken = default);
Task<JsonElement> GetConfigAsync(CancellationToken cancellationToken = default);
Task<JsonElement> GetAllStatesAsync(CancellationToken cancellationToken = default);
Task<JsonElement> GetEntityStateAsync(string entityId, CancellationToken cancellationToken = default);
Task<JsonElement> GetServicesAsync(CancellationToken cancellationToken = default);
Task<JsonElement> GetHistoryAsync(
string entityIds,
DateTimeOffset? startTime = null,
DateTimeOffset? endTime = null,
bool minimalResponse = true,
CancellationToken cancellationToken = default);
Task<JsonElement> GetLogbookAsync(
string? entityId = null,
DateTimeOffset? startTime = null,
DateTimeOffset? endTime = null,
CancellationToken cancellationToken = default);
Task<JsonElement> CallServiceAsync(
string domain,
string service,
JsonElement? serviceData = null,
CancellationToken cancellationToken = default);
}
@@ -1,15 +0,0 @@
namespace HomeAssistant.McpServer.Settings;
public sealed class HomeAssistantSettings
{
public const string SectionName = "HomeAssistant";
public const int DefaultPort = 8123;
public const int DefaultTimeoutSeconds = 30;
public string Host { get; set; } = string.Empty;
public int Port { get; set; } = DefaultPort;
public string Token { get; set; } = string.Empty;
public bool Ssl { get; set; }
public Uri BaseUrl => new UriBuilder(Ssl ? "https" : "http", Host, Port).Uri;
}
@@ -1,104 +0,0 @@
using System.ComponentModel;
using System.Text.Json;
using HomeAssistant.McpServer.Services;
using ModelContextProtocol.Server;
namespace HomeAssistant.McpServer.Tools;
[McpServerToolType]
public sealed class EntityStateTools
{
private readonly IHomeAssistantApiClient _client;
public EntityStateTools(IHomeAssistantApiClient client)
{
_client = client;
}
[McpServerTool, Description(
"Get the current state and attributes of a single Home Assistant entity. " +
"Provide the full entity_id, e.g. 'sensor.nordpool_kwh_lt_eur_3_10_0' or 'switch.boiler'.")]
public async Task<string> GetEntityState(
[Description("Full entity ID, e.g. 'sensor.temperature' or 'light.living_room'")] string entityId,
CancellationToken cancellationToken = default)
{
var result = await _client.GetEntityStateAsync(entityId, cancellationToken).ConfigureAwait(false);
return FormatJson(result);
}
[McpServerTool, Description(
"Get the current states of all Home Assistant entities. " +
"Optionally filter by domain (e.g. 'sensor', 'switch', 'climate', 'light'). " +
"Returns entity_id, state, and key attributes for each entity.")]
public async Task<string> GetAllStates(
[Description("Optional domain filter, e.g. 'sensor', 'switch', 'climate'. Leave empty for all.")] string? domain = null,
CancellationToken cancellationToken = default)
{
var allStates = await _client.GetAllStatesAsync(cancellationToken).ConfigureAwait(false);
if (string.IsNullOrWhiteSpace(domain))
{
return FormatJson(allStates);
}
var filtered = allStates.EnumerateArray()
.Where(e => e.TryGetProperty("entity_id", out var eid) &&
eid.GetString()?.StartsWith(domain + ".", StringComparison.OrdinalIgnoreCase) == true)
.ToList();
return JsonSerializer.Serialize(filtered, SerializerOptions);
}
[McpServerTool, Description(
"Search Home Assistant entities by partial match on entity_id or friendly_name. " +
"Useful for discovering entities related to a topic (e.g. 'nordpool', 'boiler', 'temperature').")]
public async Task<string> SearchEntities(
[Description("Search term to match against entity_id or friendly_name")] string query,
CancellationToken cancellationToken = default)
{
var allStates = await _client.GetAllStatesAsync(cancellationToken).ConfigureAwait(false);
var matches = allStates.EnumerateArray()
.Where(e => MatchesQuery(e, query))
.Select(e => new
{
entity_id = e.GetProperty("entity_id").GetString(),
state = e.GetProperty("state").GetString(),
friendly_name = e.TryGetProperty("attributes", out var attrs) &&
attrs.TryGetProperty("friendly_name", out var fn)
? fn.GetString()
: null
})
.ToList();
return JsonSerializer.Serialize(matches, SerializerOptions);
}
private static bool MatchesQuery(JsonElement entity, string query)
{
var q = query.ToUpperInvariant();
if (entity.TryGetProperty("entity_id", out var eid) &&
(eid.GetString()?.ToUpperInvariant().Contains(q) ?? false))
{
return true;
}
if (entity.TryGetProperty("attributes", out var attrs) &&
attrs.TryGetProperty("friendly_name", out var fn) &&
(fn.GetString()?.ToUpperInvariant().Contains(q) ?? false))
{
return true;
}
return false;
}
private static string FormatJson(JsonElement element) =>
JsonSerializer.Serialize(element, SerializerOptions);
private static readonly JsonSerializerOptions SerializerOptions = new()
{
WriteIndented = true
};
}
@@ -1,46 +0,0 @@
using System.ComponentModel;
using System.Text.Json;
using HomeAssistant.McpServer.Services;
using ModelContextProtocol.Server;
namespace HomeAssistant.McpServer.Tools;
[McpServerToolType]
public sealed class HistoryTools
{
private readonly IHomeAssistantApiClient _client;
public HistoryTools(IHomeAssistantApiClient client)
{
_client = client;
}
[McpServerTool, Description(
"Get state history for one or more Home Assistant entities over a time period. " +
"Returns timestamped state changes. Useful for debugging sensor readings, switch toggling, price changes, etc.")]
public async Task<string> GetEntityHistory(
[Description("Comma-separated entity IDs, e.g. 'sensor.temperature,sensor.humidity'")] string entityIds,
[Description("Start time in ISO 8601 format. Defaults to 24 hours ago. Example: '2026-03-30T00:00:00'")] string? startTime = null,
[Description("End time in ISO 8601 format. Defaults to now. Example: '2026-03-31T00:00:00'")] string? endTime = null,
[Description("If true, returns minimal data (state + last_changed only). Defaults to true.")] bool minimalResponse = true,
CancellationToken cancellationToken = default)
{
DateTimeOffset? start = string.IsNullOrWhiteSpace(startTime)
? null
: DateTimeOffset.Parse(startTime);
DateTimeOffset? end = string.IsNullOrWhiteSpace(endTime)
? null
: DateTimeOffset.Parse(endTime);
var result = await _client.GetHistoryAsync(entityIds, start, end, minimalResponse, cancellationToken)
.ConfigureAwait(false);
return JsonSerializer.Serialize(result, SerializerOptions);
}
private static readonly JsonSerializerOptions SerializerOptions = new()
{
WriteIndented = true
};
}
@@ -1,45 +0,0 @@
using System.ComponentModel;
using System.Text.Json;
using HomeAssistant.McpServer.Services;
using ModelContextProtocol.Server;
namespace HomeAssistant.McpServer.Tools;
[McpServerToolType]
public sealed class LogbookTools
{
private readonly IHomeAssistantApiClient _client;
public LogbookTools(IHomeAssistantApiClient client)
{
_client = client;
}
[McpServerTool, Description(
"Get Home Assistant logbook entries. Shows state changes and events for entities. " +
"Useful for understanding what happened and when. Filter by entity and/or time range.")]
public async Task<string> GetLogbook(
[Description("Optional entity ID to filter, e.g. 'switch.boiler'. Leave empty for all.")] string? entityId = null,
[Description("Start time in ISO 8601 format. Defaults to 24 hours ago.")] string? startTime = null,
[Description("End time in ISO 8601 format. Defaults to now.")] string? endTime = null,
CancellationToken cancellationToken = default)
{
DateTimeOffset? start = string.IsNullOrWhiteSpace(startTime)
? null
: DateTimeOffset.Parse(startTime);
DateTimeOffset? end = string.IsNullOrWhiteSpace(endTime)
? null
: DateTimeOffset.Parse(endTime);
var result = await _client.GetLogbookAsync(entityId, start, end, cancellationToken)
.ConfigureAwait(false);
return JsonSerializer.Serialize(result, SerializerOptions);
}
private static readonly JsonSerializerOptions SerializerOptions = new()
{
WriteIndented = true
};
}
@@ -1,79 +0,0 @@
using System.ComponentModel;
using System.Text.Json;
using HomeAssistant.McpServer.Services;
using ModelContextProtocol.Server;
namespace HomeAssistant.McpServer.Tools;
[McpServerToolType]
public sealed class ServiceTools
{
private readonly IHomeAssistantApiClient _client;
public ServiceTools(IHomeAssistantApiClient client)
{
_client = client;
}
[McpServerTool, Description(
"List available Home Assistant services. Optionally filter by domain (e.g. 'light', 'climate', 'switch'). " +
"Each service shows its domain and available service names.")]
public async Task<string> ListServices(
[Description("Optional domain filter, e.g. 'light', 'climate'. Leave empty for all.")] string? domain = null,
CancellationToken cancellationToken = default)
{
var allServices = await _client.GetServicesAsync(cancellationToken).ConfigureAwait(false);
if (string.IsNullOrWhiteSpace(domain))
{
return FormatJson(allServices);
}
var filtered = allServices.EnumerateArray()
.Where(s => s.TryGetProperty("domain", out var d) &&
string.Equals(d.GetString(), domain, StringComparison.OrdinalIgnoreCase))
.ToList();
return JsonSerializer.Serialize(filtered, SerializerOptions);
}
[McpServerTool, Description(
"Call a Home Assistant service. Examples: domain='light', service='turn_on', entityId='light.living_room'. " +
"For services requiring extra data, pass it as a JSON string in serviceData.")]
public async Task<string> CallService(
[Description("Service domain, e.g. 'light', 'climate', 'switch', 'input_boolean'")] string domain,
[Description("Service name, e.g. 'turn_on', 'turn_off', 'set_temperature'")] string service,
[Description("Optional target entity ID, e.g. 'light.living_room'")] string? entityId = null,
[Description("Optional JSON service data, e.g. '{\"brightness\": 255}' or '{\"temperature\": 22}'")] string? serviceData = null,
CancellationToken cancellationToken = default)
{
JsonElement? data = null;
if (!string.IsNullOrWhiteSpace(serviceData) || !string.IsNullOrWhiteSpace(entityId))
{
var dataDict = string.IsNullOrWhiteSpace(serviceData)
? new Dictionary<string, object>()
: JsonSerializer.Deserialize<Dictionary<string, object>>(serviceData) ?? [];
if (!string.IsNullOrWhiteSpace(entityId))
{
dataDict["entity_id"] = entityId;
}
data = JsonSerializer.SerializeToElement(dataDict);
}
var result = await _client.CallServiceAsync(domain, service, data, cancellationToken)
.ConfigureAwait(false);
return FormatJson(result);
}
private static string FormatJson(JsonElement element) =>
JsonSerializer.Serialize(element, SerializerOptions);
private static readonly JsonSerializerOptions SerializerOptions = new()
{
WriteIndented = true
};
}
@@ -1,52 +0,0 @@
using System.ComponentModel;
using System.Text.Json;
using HomeAssistant.McpServer.Services;
using ModelContextProtocol.Server;
namespace HomeAssistant.McpServer.Tools;
[McpServerToolType]
public sealed class SystemTools
{
private readonly IHomeAssistantApiClient _client;
public SystemTools(IHomeAssistantApiClient client)
{
_client = client;
}
[McpServerTool, Description(
"Get Home Assistant configuration including version, location, components, and unit system. " +
"Useful for understanding the HA environment.")]
public async Task<string> GetHaConfig(CancellationToken cancellationToken = default)
{
var result = await _client.GetConfigAsync(cancellationToken).ConfigureAwait(false);
return JsonSerializer.Serialize(result, SerializerOptions);
}
[McpServerTool, Description(
"Check if the Home Assistant API is reachable and responding. " +
"Returns the API status message or an error description.")]
public async Task<string> CheckApi(CancellationToken cancellationToken = default)
{
try
{
var result = await _client.GetApiStatusAsync(cancellationToken).ConfigureAwait(false);
return JsonSerializer.Serialize(result, SerializerOptions);
}
catch (HttpRequestException ex)
{
return JsonSerializer.Serialize(new { status = "error", message = ex.Message }, SerializerOptions);
}
catch (TaskCanceledException)
{
return JsonSerializer.Serialize(
new { status = "error", message = "Request timed out - HA may be unreachable" }, SerializerOptions);
}
}
private static readonly JsonSerializerOptions SerializerOptions = new()
{
WriteIndented = true
};
}
@@ -1,310 +0,0 @@
using System.Collections.Concurrent;
using System.ComponentModel;
using System.Text.Json;
using HomeAssistant.McpServer.Services;
using ModelContextProtocol.Server;
namespace HomeAssistant.McpServer.Tools;
[McpServerToolType]
public sealed class ValidationTools
{
private const string UnavailableState = "unavailable";
private const string UnknownState = "unknown";
private const int DefaultLogbookWindowMinutes = 30;
private const int MaxDegreeOfParallelism = 4;
private static readonly string[] CriticalDomains = ["sensor", "switch", "binary_sensor", "light"];
private static readonly JsonSerializerOptions SerializerOptions = new()
{
WriteIndented = true
};
private readonly IHomeAssistantApiClient _client;
public ValidationTools(IHomeAssistantApiClient client)
{
_client = client;
}
[McpServerTool, Description(
"Run a smoke test against the live Home Assistant environment. " +
"Checks API health, validates that critical entities are not unavailable/unknown, " +
"and verifies recent logbook activity for specified domains. " +
"Returns a structured pass/fail report.")]
public async Task<string> RunSmokeTest(
[Description(
"Comma-separated domains to check, e.g. 'switch,sensor,light'. " +
"Leave empty to check all critical domains (sensor, switch, binary_sensor, light).")]
string? domains = null,
[Description(
"Minutes of logbook history to scan for activity. Defaults to 30.")]
int? logbookWindowMinutes = null,
CancellationToken cancellationToken = default)
{
var targetDomains = ParseDomains(domains);
var windowMinutes = logbookWindowMinutes ?? DefaultLogbookWindowMinutes;
var apiHealthTask = CheckApiHealthAsync(cancellationToken);
var entityCheckTask = CheckEntitiesAsync(targetDomains, cancellationToken);
var logbookCheckTask = CheckRecentActivityAsync(windowMinutes, cancellationToken);
await Task.WhenAll(apiHealthTask, entityCheckTask, logbookCheckTask).ConfigureAwait(false);
var report = new
{
timestamp = DateTimeOffset.UtcNow,
apiHealth = await apiHealthTask.ConfigureAwait(false),
entityCheck = await entityCheckTask.ConfigureAwait(false),
recentActivity = await logbookCheckTask.ConfigureAwait(false),
overall = DetermineOverallStatus(
await apiHealthTask.ConfigureAwait(false),
await entityCheckTask.ConfigureAwait(false))
};
return JsonSerializer.Serialize(report, SerializerOptions);
}
[McpServerTool, Description(
"Assert that a specific Home Assistant entity has an expected state value. " +
"Returns a pass/fail result with the actual vs expected values and entity attributes.")]
public async Task<string> AssertEntityState(
[Description("Full entity ID, e.g. 'switch.boiler' or 'sensor.nordpool_current_price'")] string entityId,
[Description("Expected state value, e.g. 'on', 'off', '22.5'")] string expectedState,
CancellationToken cancellationToken = default)
{
var entity = await _client.GetEntityStateAsync(entityId, cancellationToken).ConfigureAwait(false);
var actualState = entity.TryGetProperty("state", out var stateProp)
? stateProp.GetString() ?? string.Empty
: string.Empty;
var passed = string.Equals(actualState, expectedState, StringComparison.OrdinalIgnoreCase);
var result = new
{
entityId,
expectedState,
actualState,
passed,
lastChanged = entity.TryGetProperty("last_changed", out var lc) ? lc.GetString() : null,
lastUpdated = entity.TryGetProperty("last_updated", out var lu) ? lu.GetString() : null
};
return JsonSerializer.Serialize(result, SerializerOptions);
}
[McpServerTool, Description(
"Validate multiple Home Assistant entities in parallel. " +
"Checks that each entity exists, is reachable, and is not in unavailable/unknown state. " +
"Optionally assert expected state values.")]
public async Task<string> ValidateEntities(
[Description(
"Comma-separated entity IDs to validate, e.g. 'switch.boiler,sensor.nordpool_current_price'")]
string entityIds,
[Description(
"Optional comma-separated expected states matching the entity IDs order. " +
"Use empty string to skip assertion for an entity, e.g. 'on,,42.5'")]
string? expectedStates = null,
CancellationToken cancellationToken = default)
{
var ids = entityIds.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
var states = expectedStates?.Split(',') ?? [];
var results = new ConcurrentBag<object>();
var parallelOptions = new ParallelOptions
{
MaxDegreeOfParallelism = MaxDegreeOfParallelism,
CancellationToken = cancellationToken
};
await Parallel.ForEachAsync(
ids.Select((id, index) => (id, index)),
parallelOptions,
async (item, ct) =>
{
var expectedState = item.index < states.Length
? states[item.index]?.Trim()
: null;
var result = await ValidateSingleEntityAsync(item.id, expectedState, ct).ConfigureAwait(false);
results.Add(result);
}).ConfigureAwait(false);
var ordered = results.Cast<dynamic>()
.OrderBy(r => (string)r.entityId)
.ToList();
var allPassed = ordered.All(r => (bool)r.passed);
var report = new
{
timestamp = DateTimeOffset.UtcNow,
passed = allPassed,
total = ordered.Count,
failed = ordered.Count(r => !(bool)r.passed),
entities = ordered
};
return JsonSerializer.Serialize(report, SerializerOptions);
}
private static string[] ParseDomains(string? domains) =>
string.IsNullOrWhiteSpace(domains)
? CriticalDomains
: domains.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
private async Task<object> CheckApiHealthAsync(CancellationToken cancellationToken)
{
try
{
var status = await _client.GetApiStatusAsync(cancellationToken).ConfigureAwait(false);
var message = status.TryGetProperty("message", out var msg) ? msg.GetString() : "unknown";
return new { status = "healthy", message };
}
catch (HttpRequestException ex)
{
return new { status = "unreachable", message = ex.Message };
}
catch (TaskCanceledException)
{
return new { status = "timeout", message = "Home Assistant API did not respond in time" };
}
}
private async Task<object> CheckEntitiesAsync(string[] targetDomains, CancellationToken cancellationToken)
{
var allStates = await _client.GetAllStatesAsync(cancellationToken).ConfigureAwait(false);
var domainSet = new HashSet<string>(targetDomains, StringComparer.OrdinalIgnoreCase);
var unhealthy = new ConcurrentBag<object>();
var totalChecked = 0;
foreach (var entity in allStates.EnumerateArray())
{
if (!entity.TryGetProperty("entity_id", out var eidProp))
continue;
var entityId = eidProp.GetString() ?? string.Empty;
var entityDomain = entityId.Split('.').FirstOrDefault() ?? string.Empty;
if (!domainSet.Contains(entityDomain))
continue;
Interlocked.Increment(ref totalChecked);
if (!entity.TryGetProperty("state", out var stateProp))
continue;
var state = stateProp.GetString();
if (string.Equals(state, UnavailableState, StringComparison.OrdinalIgnoreCase) ||
string.Equals(state, UnknownState, StringComparison.OrdinalIgnoreCase))
{
unhealthy.Add(new
{
entityId,
state,
lastChanged = entity.TryGetProperty("last_changed", out var lc) ? lc.GetString() : null
});
}
}
return new
{
passed = unhealthy.IsEmpty,
totalChecked,
unhealthyCount = unhealthy.Count,
unhealthyEntities = unhealthy.OrderBy(e => e.ToString()).ToList()
};
}
private async Task<object> CheckRecentActivityAsync(int windowMinutes, CancellationToken cancellationToken)
{
try
{
var startTime = DateTimeOffset.UtcNow.AddMinutes(-windowMinutes);
var logbook = await _client.GetLogbookAsync(
entityId: null,
startTime: startTime,
endTime: null,
cancellationToken: cancellationToken).ConfigureAwait(false);
var entryCount = logbook.ValueKind == JsonValueKind.Array ? logbook.GetArrayLength() : 0;
return new
{
windowMinutes,
entryCount,
hasActivity = entryCount > 0
};
}
catch (Exception ex)
{
return new
{
windowMinutes,
entryCount = 0,
hasActivity = false,
error = ex.Message
};
}
}
private static string DetermineOverallStatus(object apiHealth, object entityCheck)
{
var apiJson = JsonSerializer.SerializeToElement(apiHealth);
var entityJson = JsonSerializer.SerializeToElement(entityCheck);
var apiHealthy = apiJson.TryGetProperty("status", out var s) &&
string.Equals(s.GetString(), "healthy", StringComparison.OrdinalIgnoreCase);
var entitiesHealthy = entityJson.TryGetProperty("passed", out var p) && p.GetBoolean();
return apiHealthy && entitiesHealthy ? "PASS" : "FAIL";
}
private async Task<object> ValidateSingleEntityAsync(
string entityId,
string? expectedState,
CancellationToken cancellationToken)
{
try
{
var entity = await _client.GetEntityStateAsync(entityId, cancellationToken).ConfigureAwait(false);
var actualState = entity.TryGetProperty("state", out var stateProp)
? stateProp.GetString() ?? string.Empty
: string.Empty;
var isAvailable = !string.Equals(actualState, UnavailableState, StringComparison.OrdinalIgnoreCase) &&
!string.Equals(actualState, UnknownState, StringComparison.OrdinalIgnoreCase);
var stateMatch = string.IsNullOrEmpty(expectedState) ||
string.Equals(actualState, expectedState, StringComparison.OrdinalIgnoreCase);
return new
{
entityId,
actualState,
expectedState = expectedState ?? "(any)",
isAvailable,
stateMatch,
passed = isAvailable && stateMatch,
lastChanged = entity.TryGetProperty("last_changed", out var lc) ? lc.GetString() : null
};
}
catch (HttpRequestException)
{
return new
{
entityId,
actualState = "error",
expectedState = expectedState ?? "(any)",
isAvailable = false,
stateMatch = false,
passed = false,
lastChanged = (string?)null
};
}
}
}
-2
View File
@@ -1,2 +0,0 @@
{
}
+11 -1
View File
@@ -70,12 +70,22 @@
"NotificationCooldownMinutes": 5 "NotificationCooldownMinutes": 5
}, },
"PowerMonitor": { "PowerMonitor": {
"Enabled": false, "Enabled": true,
"MainMeterEntityId": "sensor.sonoff_100267d63f_power", "MainMeterEntityId": "sensor.sonoff_100267d63f_power",
"PollIntervalSeconds": 1, "PollIntervalSeconds": 1,
"SmoothingWindowSize": 10, "SmoothingWindowSize": 10,
"AnomalyThresholdWatts": 500, "AnomalyThresholdWatts": 500,
"HighPowerThresholdWatts": 6000, "HighPowerThresholdWatts": 6000,
"EnforceLimitEnabled": true,
"PowerLimitWatts": 5500,
"RecoverySeconds": 600,
"LimitCooldownSeconds": 30,
"EnforceSwitchOffEntityIds": [
"switch.sonoff_1002230e32"
],
"PauseAndRestoreEntityIds": [
"switch.boilermonitor_auto_management"
],
"ExcludedSensorPatterns": [ "ExcludedSensorPatterns": [
"sensor.nordpool_*", "sensor.nordpool_*",
"sensor.powermonitor_*" "sensor.powermonitor_*"
-1
View File
@@ -15,7 +15,6 @@ using NetDaemon.Runtime;
using BoilerMonitorManager; using BoilerMonitorManager;
using BoilerMonitorManager.Models; using BoilerMonitorManager.Models;
using NordPoolManager; using NordPoolManager;
using NordPoolManager.Interface;
using NordPoolManager.Models; using NordPoolManager.Models;
using PowerMonitorManager; using PowerMonitorManager;
using PowerMonitorManager.Models; using PowerMonitorManager.Models;
-22
View File
@@ -30,8 +30,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Testing", "Testing", "{95E9
EndProject EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Models", "Models", "{48492269-2B47-43FE-BC14-A901054EE5AE}" Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Models", "Models", "{48492269-2B47-43FE-BC14-A901054EE5AE}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HomeAssistant.McpServer", "HomeAssistant.McpServer\HomeAssistant.McpServer.csproj", "{AF78DBE2-9DDA-4ABD-934A-97DC9376D371}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ShowerMonitor.Models", "ShowerMonitor.Models\ShowerMonitor.Models.csproj", "{DAD0BDF9-2A6D-48AD-B714-38D237E97285}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ShowerMonitor.Models", "ShowerMonitor.Models\ShowerMonitor.Models.csproj", "{DAD0BDF9-2A6D-48AD-B714-38D237E97285}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ShowerMonitor.Manager", "ShowerMonitor.Manager\ShowerMonitor.Manager.csproj", "{8D05B406-B94B-4D6B-8221-831485AF6702}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ShowerMonitor.Manager", "ShowerMonitor.Manager\ShowerMonitor.Manager.csproj", "{8D05B406-B94B-4D6B-8221-831485AF6702}"
@@ -44,8 +42,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LightMonitor.Manager", "Lig
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LightMonitor.Manager.Tests", "LightMonitor.Manager.Tests\LightMonitor.Manager.Tests.csproj", "{B8303C3E-785C-48F0-8F40-D4A9E9D50C92}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LightMonitor.Manager.Tests", "LightMonitor.Manager.Tests\LightMonitor.Manager.Tests.csproj", "{B8303C3E-785C-48F0-8F40-D4A9E9D50C92}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HomeAssistant.HistoryReplay", "HomeAssistant.HistoryReplay\HomeAssistant.HistoryReplay.csproj", "{EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BatteryMonitor.Models", "BatteryMonitor.Models\BatteryMonitor.Models.csproj", "{2D27B621-7B92-4014-8FDF-6AD376C97612}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BatteryMonitor.Models", "BatteryMonitor.Models\BatteryMonitor.Models.csproj", "{2D27B621-7B92-4014-8FDF-6AD376C97612}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BatteryMonitor.Manager", "BatteryMonitor.Manager\BatteryMonitor.Manager.csproj", "{C844BDD9-584D-4D72-8EDE-AEB3E7429FC1}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BatteryMonitor.Manager", "BatteryMonitor.Manager\BatteryMonitor.Manager.csproj", "{C844BDD9-584D-4D72-8EDE-AEB3E7429FC1}"
@@ -224,12 +220,6 @@ Global
{CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Release|x64.Build.0 = Release|Any CPU {CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Release|x64.Build.0 = Release|Any CPU
{CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Release|x86.ActiveCfg = Release|Any CPU {CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Release|x86.ActiveCfg = Release|Any CPU
{CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Release|x86.Build.0 = Release|Any CPU {CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Release|x86.Build.0 = Release|Any CPU
{AF78DBE2-9DDA-4ABD-934A-97DC9376D371}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{AF78DBE2-9DDA-4ABD-934A-97DC9376D371}.Debug|x64.ActiveCfg = Debug|Any CPU
{AF78DBE2-9DDA-4ABD-934A-97DC9376D371}.Debug|x86.ActiveCfg = Debug|Any CPU
{AF78DBE2-9DDA-4ABD-934A-97DC9376D371}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AF78DBE2-9DDA-4ABD-934A-97DC9376D371}.Release|x64.ActiveCfg = Release|Any CPU
{AF78DBE2-9DDA-4ABD-934A-97DC9376D371}.Release|x86.ActiveCfg = Release|Any CPU
{DAD0BDF9-2A6D-48AD-B714-38D237E97285}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {DAD0BDF9-2A6D-48AD-B714-38D237E97285}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{DAD0BDF9-2A6D-48AD-B714-38D237E97285}.Debug|Any CPU.Build.0 = Debug|Any CPU {DAD0BDF9-2A6D-48AD-B714-38D237E97285}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DAD0BDF9-2A6D-48AD-B714-38D237E97285}.Debug|x64.ActiveCfg = Debug|Any CPU {DAD0BDF9-2A6D-48AD-B714-38D237E97285}.Debug|x64.ActiveCfg = Debug|Any CPU
@@ -302,18 +292,6 @@ Global
{B8303C3E-785C-48F0-8F40-D4A9E9D50C92}.Release|x64.Build.0 = Release|Any CPU {B8303C3E-785C-48F0-8F40-D4A9E9D50C92}.Release|x64.Build.0 = Release|Any CPU
{B8303C3E-785C-48F0-8F40-D4A9E9D50C92}.Release|x86.ActiveCfg = Release|Any CPU {B8303C3E-785C-48F0-8F40-D4A9E9D50C92}.Release|x86.ActiveCfg = Release|Any CPU
{B8303C3E-785C-48F0-8F40-D4A9E9D50C92}.Release|x86.Build.0 = Release|Any CPU {B8303C3E-785C-48F0-8F40-D4A9E9D50C92}.Release|x86.Build.0 = Release|Any CPU
{EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Debug|x64.ActiveCfg = Debug|Any CPU
{EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Debug|x64.Build.0 = Debug|Any CPU
{EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Debug|x86.ActiveCfg = Debug|Any CPU
{EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Debug|x86.Build.0 = Debug|Any CPU
{EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Release|Any CPU.Build.0 = Release|Any CPU
{EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Release|x64.ActiveCfg = Release|Any CPU
{EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Release|x64.Build.0 = Release|Any CPU
{EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Release|x86.ActiveCfg = Release|Any CPU
{EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Release|x86.Build.0 = Release|Any CPU
{2D27B621-7B92-4014-8FDF-6AD376C97612}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2D27B621-7B92-4014-8FDF-6AD376C97612}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2D27B621-7B92-4014-8FDF-6AD376C97612}.Debug|Any CPU.Build.0 = Debug|Any CPU {2D27B621-7B92-4014-8FDF-6AD376C97612}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2D27B621-7B92-4014-8FDF-6AD376C97612}.Debug|x64.ActiveCfg = Debug|Any CPU {2D27B621-7B92-4014-8FDF-6AD376C97612}.Debug|x64.ActiveCfg = Debug|Any CPU
+4 -3
View File
@@ -38,6 +38,7 @@ public sealed class LeakMonitorInit : ILeakMonitorInit
if (_options.SensorEntityIds.Length == 0) if (_options.SensorEntityIds.Length == 0)
{ {
_logger.LogWarning("LeakMonitor enabled but no sensor entity IDs configured"); _logger.LogWarning("LeakMonitor enabled but no sensor entity IDs configured");
return Task.CompletedTask; return Task.CompletedTask;
} }
@@ -46,9 +47,7 @@ public sealed class LeakMonitorInit : ILeakMonitorInit
SubscribeToLeakSensor(sensorEntityId); SubscribeToLeakSensor(sensorEntityId);
} }
_logger.LogInformation( _logger.LogInformation("LeakMonitor initialized, monitoring {Count} sensor(s)", _options.SensorEntityIds.Length);
"LeakMonitor initialized, monitoring {Count} sensor(s)",
_options.SensorEntityIds.Length);
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -85,11 +84,13 @@ public sealed class LeakMonitorInit : ILeakMonitorInit
if (string.Equals(newState, LeakMonitorConsts.WaterDetectedState, StringComparison.OrdinalIgnoreCase)) if (string.Equals(newState, LeakMonitorConsts.WaterDetectedState, StringComparison.OrdinalIgnoreCase))
{ {
_logger.LogWarning("Water leak detected by {SensorId}!", sensorEntityId); _logger.LogWarning("Water leak detected by {SensorId}!", sensorEntityId);
_notificationService.SendLeakAlert(sensorEntityId); _notificationService.SendLeakAlert(sensorEntityId);
} }
else if (string.Equals(newState, LeakMonitorConsts.WaterClearedState, StringComparison.OrdinalIgnoreCase)) else if (string.Equals(newState, LeakMonitorConsts.WaterClearedState, StringComparison.OrdinalIgnoreCase))
{ {
_logger.LogInformation("Water leak cleared by {SensorId}", sensorEntityId); _logger.LogInformation("Water leak cleared by {SensorId}", sensorEntityId);
_notificationService.DismissLeakAlert(sensorEntityId); _notificationService.DismissLeakAlert(sensorEntityId);
} }
} }
@@ -19,9 +19,7 @@ public static class LeakMonitorServiceRegistration
return services; return services;
} }
services services.AddNetDaemonApp<LeakMonitorInit>().AddScoped<ILeakNotificationService, LeakNotificationService>();
.AddNetDaemonApp<LeakMonitorInit>()
.AddScoped<ILeakNotificationService, LeakNotificationService>();
return services; return services;
} }
@@ -1,4 +1,3 @@
using FluentAssertions;
using LightMonitor.Models; using LightMonitor.Models;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
@@ -1,5 +1,4 @@
using FluentAssertions; using FluentAssertions;
using LightMonitor.Models;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Moq; using Moq;
+13 -20
View File
@@ -8,43 +8,36 @@ using LightMonitorManager.Models;
namespace LightMonitorManager; namespace LightMonitorManager;
public sealed class LightControlService : ILightControlService public sealed class LightControlService(
IHaContext haContext,
ILogger<LightControlService> logger,
IOptions<LightMonitorOptions> options)
: ILightControlService
{ {
private readonly IHaContext _haContext; private readonly LightMonitorOptions _options = options.Value;
private readonly ILogger<LightControlService> _logger;
private readonly LightMonitorOptions _options;
public LightControlService(
IHaContext haContext,
ILogger<LightControlService> logger,
IOptions<LightMonitorOptions> options)
{
_haContext = haContext;
_logger = logger;
_options = options.Value;
}
public void TurnOnLight() public void TurnOnLight()
{ {
var sunState = _haContext.GetState(_options.SunEntityId)?.State; var sunState = haContext.GetState(_options.SunEntityId)?.State;
if (!string.Equals(sunState, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase)) if (!string.Equals(sunState, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase))
{ {
_logger.LogDebug("Sun is not below horizon (state={SunState}), skipping light turn on", sunState); logger.LogDebug("Sun is not below horizon (state={SunState}), skipping light turn on", sunState);
return; return;
} }
var lightState = _haContext.GetState(_options.LightEntityId)?.State; var lightState = haContext.GetState(_options.LightEntityId)?.State;
if (string.Equals(lightState, LightMonitorConsts.LightOnState, StringComparison.OrdinalIgnoreCase)) if (string.Equals(lightState, LightMonitorConsts.LightOnState, StringComparison.OrdinalIgnoreCase))
{ {
_logger.LogDebug("Light {EntityId} is already on, skipping", _options.LightEntityId); logger.LogDebug("Light {EntityId} is already on, skipping", _options.LightEntityId);
return; return;
} }
_haContext.CallService("light", "turn_on", ServiceTarget.FromEntity(_options.LightEntityId)); haContext.CallService("light", "turn_on", ServiceTarget.FromEntity(_options.LightEntityId));
_logger.LogInformation("Light {EntityId} turned ON (dark outside + person home)", _options.LightEntityId);
logger.LogInformation("Light {EntityId} turned ON (dark outside + person home)", _options.LightEntityId);
} }
} }
+1
View File
@@ -28,6 +28,7 @@ public sealed class PresenceService(
if (string.Equals(state.State, LightMonitorConsts.PersonHomeState, StringComparison.OrdinalIgnoreCase)) if (string.Equals(state.State, LightMonitorConsts.PersonHomeState, StringComparison.OrdinalIgnoreCase))
{ {
logger.LogDebug("Person {EntityId} is home", personEntityId); logger.LogDebug("Person {EntityId} is home", personEntityId);
return true; return true;
} }
} }
+8 -7
View File
@@ -163,8 +163,7 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
if (mergedPrices.Count > NordPoolConsts.MaxExpectedPriceEntries) if (mergedPrices.Count > NordPoolConsts.MaxExpectedPriceEntries)
{ {
logger.LogWarning("Merged price count ({Count}) exceeds expected maximum ({Max}). Attribute payload may be oversized", logger.LogWarning("Merged price count ({Count}) exceeds expected maximum ({Max}). Attribute payload may be oversized", mergedPrices.Count, NordPoolConsts.MaxExpectedPriceEntries);
mergedPrices.Count, NordPoolConsts.MaxExpectedPriceEntries);
} }
var cheapestCount = ctx.CheapestIntervals?.Count ?? 0; var cheapestCount = ctx.CheapestIntervals?.Count ?? 0;
@@ -310,11 +309,13 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
var todayList = today?.Prices ?? []; var todayList = today?.Prices ?? [];
var tomorrowList = tomorrow?.Prices ?? []; var tomorrowList = tomorrow?.Prices ?? [];
return todayList return
.Concat(tomorrowList) [
.Where(p => p is { Start: not null }) .. todayList
.OrderBy(p => p.Start!.Value) .Concat(tomorrowList)
.ToList(); .Where(p => p is { Start: not null })
.OrderBy(p => p.Start!.Value)
];
} }
internal async Task SetEntityStateSafe(string entityId, string state) internal async Task SetEntityStateSafe(string entityId, string state)
@@ -2,7 +2,6 @@ using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using NetDaemon.AppModel; using NetDaemon.AppModel;
using NordPoolManager.Interface; using NordPoolManager.Interface;
using NordPoolManager.Models;
namespace NordPoolManager; namespace NordPoolManager;
@@ -20,6 +20,7 @@
</PackageReference> </PackageReference>
<PackageReference Include="FluentAssertions" Version="8.8.0" /> <PackageReference Include="FluentAssertions" Version="8.8.0" />
<PackageReference Include="Moq" Version="4.20.72" /> <PackageReference Include="Moq" Version="4.20.72" />
<PackageReference Include="Microsoft.Extensions.TimeProvider.Testing" Version="10.4.0" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
@@ -24,11 +24,11 @@ public class PowerMonitorEntityServiceTests
#region GetSystemEntitiesList #region GetSystemEntitiesList
[Fact] [Fact]
public void GetSystemEntitiesList_ShouldReturnAll13SystemEntities() public void GetSystemEntitiesList_ShouldReturnAll14SystemEntities()
{ {
var result = _sut.GetSystemEntitiesList(); var result = _sut.GetSystemEntitiesList();
result.Should().HaveCount(13); result.Should().HaveCount(14);
} }
[Fact] [Fact]
@@ -49,6 +49,7 @@ public class PowerMonitorEntityServiceTests
result.Should().Contain(e => e.EntityId == "binary_sensor.powermonitor_anomaly"); result.Should().Contain(e => e.EntityId == "binary_sensor.powermonitor_anomaly");
result.Should().Contain(e => e.EntityId == "sensor.powermonitor_status"); result.Should().Contain(e => e.EntityId == "sensor.powermonitor_status");
result.Should().Contain(e => e.EntityId == "button.powermonitor_rediscover_sensors"); result.Should().Contain(e => e.EntityId == "button.powermonitor_rediscover_sensors");
result.Should().Contain(e => e.EntityId == "button.powermonitor_trigger_limit_breach");
} }
[Fact] [Fact]
@@ -103,14 +104,14 @@ public class PowerMonitorEntityServiceTests
#region CreateSystemEntitiesAsync #region CreateSystemEntitiesAsync
[Fact] [Fact]
public async Task CreateSystemEntitiesAsync_ShouldCreateAll13Entities() public async Task CreateSystemEntitiesAsync_ShouldCreateAll14Entities()
{ {
_entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>())) _entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>()))
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
await _sut.CreateSystemEntitiesAsync(); await _sut.CreateSystemEntitiesAsync();
_entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>()), Times.Exactly(13)); _entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>()), Times.Exactly(14));
} }
[Fact] [Fact]
@@ -131,7 +132,7 @@ public class PowerMonitorEntityServiceTests
await _sut.CreateSystemEntitiesAsync(); await _sut.CreateSystemEntitiesAsync();
_entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>()), Times.Exactly(13)); _entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>()), Times.Exactly(14));
} }
#endregion #endregion
@@ -186,7 +187,7 @@ public class PowerMonitorEntityServiceTests
await _sut.CleanupEntitiesAsync(); await _sut.CleanupEntitiesAsync();
_entityManagerMock.Verify(em => em.RemoveEntity(It.IsAny<string>()), Times.Exactly(13)); _entityManagerMock.Verify(em => em.RemoveEntity(It.IsAny<string>()), Times.Exactly(14));
} }
#endregion #endregion
@@ -67,4 +67,52 @@ public class PowerMonitorOptionsTests
options.Enabled.Should().BeFalse(); options.Enabled.Should().BeFalse();
} }
[Fact]
public void Defaults_ShouldHaveEnforceLimitEnabledTrue()
{
var options = new PowerMonitorOptions();
options.EnforceLimitEnabled.Should().BeTrue();
}
[Fact]
public void Defaults_ShouldHaveExpectedPowerLimitWatts()
{
var options = new PowerMonitorOptions();
options.PowerLimitWatts.Should().Be(PowerMonitorConsts.DefaultPowerLimitWatts);
}
[Fact]
public void Defaults_ShouldHaveExpectedRecoverySeconds()
{
var options = new PowerMonitorOptions();
options.RecoverySeconds.Should().Be(PowerMonitorConsts.DefaultRecoverySeconds);
}
[Fact]
public void Defaults_ShouldHaveExpectedLimitCooldownSeconds()
{
var options = new PowerMonitorOptions();
options.LimitCooldownSeconds.Should().Be(PowerMonitorConsts.DefaultLimitCooldownSeconds);
}
[Fact]
public void Defaults_ShouldHaveEmptyEnforceSwitchOffEntityIds()
{
var options = new PowerMonitorOptions();
options.EnforceSwitchOffEntityIds.Should().BeEmpty();
}
[Fact]
public void Defaults_ShouldHaveEmptyPauseAndRestoreEntityIds()
{
var options = new PowerMonitorOptions();
options.PauseAndRestoreEntityIds.Should().BeEmpty();
}
} }
@@ -20,12 +20,18 @@ public static class PowerMonitorConsts
public const double DefaultHighPowerThresholdWatts = 6000.0; public const double DefaultHighPowerThresholdWatts = 6000.0;
public const double DefaultPowerLimitWatts = 5500.0;
public const int DefaultRecoverySeconds = 600;
public const int DefaultLimitCooldownSeconds = 30;
public const string HighPowerNotificationId = "power_monitor_high_power"; public const string HighPowerNotificationId = "power_monitor_high_power";
public const string HighPowerNotificationTitle = "High Power Usage Alert"; public const string HighPowerNotificationTitle = "High Power Usage Alert";
public const string PowerLimitNotificationId = "power_monitor_power_limit";
public const string PowerLimitNotificationTitle = "Power Limit Enforced";
public const string PersistentNotificationDomain = "persistent_notification"; public const string PersistentNotificationDomain = "persistent_notification";
public const string PersistentNotificationCreateService = "create"; public const string PersistentNotificationCreateService = "create";
public const string PersistentNotificationDismissService = "dismiss"; public const string PersistentNotificationDismissService = "dismiss";
public const string SwitchDomain = "switch";
public const int MinutesPerQuarterHour = 15; public const string TurnOnService = "turn_on";
public const int MinutesPerHour = 60; public const string TurnOffService = "turn_off";
} }
@@ -2,7 +2,7 @@ namespace PowerMonitorManager.Models;
public sealed class CostAccumulator public sealed class CostAccumulator
{ {
private readonly object _lock = new(); private readonly Lock _lock = new();
private double _cost15Min; private double _cost15Min;
private double _cost1Hour; private double _cost1Hour;
@@ -13,4 +13,11 @@ public sealed class PowerMonitorOptions
public double AnomalyThresholdWatts { get; set; } = PowerMonitorConsts.DefaultAnomalyThresholdWatts; public double AnomalyThresholdWatts { get; set; } = PowerMonitorConsts.DefaultAnomalyThresholdWatts;
public string[] ExcludedSensorPatterns { get; set; } = []; public string[] ExcludedSensorPatterns { get; set; } = [];
public double HighPowerThresholdWatts { get; set; } = PowerMonitorConsts.DefaultHighPowerThresholdWatts; public double HighPowerThresholdWatts { get; set; } = PowerMonitorConsts.DefaultHighPowerThresholdWatts;
public bool EnforceLimitEnabled { get; set; } = true;
public double PowerLimitWatts { get; set; } = PowerMonitorConsts.DefaultPowerLimitWatts;
public int RecoverySeconds { get; set; } = PowerMonitorConsts.DefaultRecoverySeconds;
public int LimitCooldownSeconds { get; set; } = PowerMonitorConsts.DefaultLimitCooldownSeconds;
public string[] EnforceSwitchOffEntityIds { get; set; } = [];
public string[] PauseAndRestoreEntityIds { get; set; } = [];
} }
@@ -8,7 +8,7 @@ public sealed class OtherPowerCalculationService : IOtherPowerCalculationService
{ {
private readonly double _alpha; private readonly double _alpha;
private double? _previousSmoothed; private double? _previousSmoothed;
private readonly object _lock = new(); private readonly Lock _lock = new();
public OtherPowerCalculationService(IOptions<PowerMonitorOptions> options) public OtherPowerCalculationService(IOptions<PowerMonitorOptions> options)
{ {
@@ -10,11 +10,11 @@ public sealed class PowerCostCalculationService : IPowerCostCalculationService
private readonly ConcurrentDictionary<string, CostAccumulator> _deviceAccumulators = new(); private readonly ConcurrentDictionary<string, CostAccumulator> _deviceAccumulators = new();
private CostAccumulator? _totalAccumulator; private CostAccumulator? _totalAccumulator;
private CostAccumulator? _otherAccumulator; private CostAccumulator? _otherAccumulator;
private readonly object _accumulatorLock = new(); private readonly Lock _accumulatorLock = new();
private double _lastKnownPrice; private double _lastKnownPrice;
private string _priceSource = "live"; private string _priceSource = "live";
private readonly object _priceLock = new(); private readonly Lock _priceLock = new();
public double LastKnownPrice public double LastKnownPrice
{ {
@@ -25,6 +25,7 @@ public sealed class PowerMonitorEntityService(
private const string AnomalyEntityId = "binary_sensor.powermonitor_anomaly"; private const string AnomalyEntityId = "binary_sensor.powermonitor_anomaly";
private const string StatusEntityId = "sensor.powermonitor_status"; private const string StatusEntityId = "sensor.powermonitor_status";
private const string RediscoverButtonEntityId = "button.powermonitor_rediscover_sensors"; private const string RediscoverButtonEntityId = "button.powermonitor_rediscover_sensors";
private const string TriggerLimitBreachButtonEntityId = "button.powermonitor_trigger_limit_breach";
private static readonly string[] SystemEntityIds = private static readonly string[] SystemEntityIds =
[ [
@@ -34,7 +35,8 @@ public sealed class PowerMonitorEntityService(
OtherCost15MinEntityId, OtherCost1HEntityId, OtherCostDailyEntityId, OtherCostMonthlyEntityId, OtherCost15MinEntityId, OtherCost1HEntityId, OtherCostDailyEntityId, OtherCostMonthlyEntityId,
AnomalyEntityId, AnomalyEntityId,
StatusEntityId, StatusEntityId,
RediscoverButtonEntityId RediscoverButtonEntityId,
TriggerLimitBreachButtonEntityId
]; ];
public async Task CreateSystemEntitiesAsync(CancellationToken cancellationToken = default) public async Task CreateSystemEntitiesAsync(CancellationToken cancellationToken = default)
@@ -199,6 +201,10 @@ public sealed class PowerMonitorEntityService(
new("button", "powermonitor_rediscover_sensors", "Rediscover power sensors") new("button", "powermonitor_rediscover_sensors", "Rediscover power sensors")
{ {
AdditionalConfig = new { icon = "mdi:refresh" } AdditionalConfig = new { icon = "mdi:refresh" }
},
new("button", "powermonitor_trigger_limit_breach", "Trigger power limit breach (debug)")
{
AdditionalConfig = new { icon = "mdi:flash-alert" }
} }
}; };
} }
+65 -35
View File
@@ -1,9 +1,7 @@
using System.Globalization; using System.Globalization;
using System.Reactive.Concurrency;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using NetDaemon.AppModel; using NetDaemon.AppModel;
using NetDaemon.Extensions.Scheduler;
using NetDaemon.HassModel; using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities; using NetDaemon.HassModel.Entities;
using NordPool.Models; using NordPool.Models;
@@ -18,40 +16,41 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
{ {
private readonly ILogger<PowerMonitorInit> _logger; private readonly ILogger<PowerMonitorInit> _logger;
private readonly IHaContext _haContext; private readonly IHaContext _haContext;
private readonly IScheduler _scheduler;
private readonly PowerMonitorOptions _options; private readonly PowerMonitorOptions _options;
private readonly IPowerSensorDiscoveryService _discoveryService; private readonly IPowerSensorDiscoveryService _discoveryService;
private readonly IOtherPowerCalculationService _calculationService; private readonly IOtherPowerCalculationService _calculationService;
private readonly IPowerCostCalculationService _costService; private readonly IPowerCostCalculationService _costService;
private readonly IPowerMonitorEntityService _entityService; private readonly IPowerMonitorEntityService _entityService;
private readonly IPowerNotificationService _notificationService; private readonly IPowerNotificationService _notificationService;
private readonly IPowerLimitEnforcementService _enforcementService;
private readonly TimeProvider _timeProvider; private readonly TimeProvider _timeProvider;
private int _mainMeterConsecutiveFailures; private int _mainMeterConsecutiveFailures;
private DateTimeOffset? _anomalyStartTime; private DateTimeOffset? _anomalyStartTime;
private DateTimeOffset? _lastPollTimestamp;
private bool _highPowerNotificationActive; private bool _highPowerNotificationActive;
public PowerMonitorInit( public PowerMonitorInit(
IHaContext haContext, IHaContext haContext,
ILogger<PowerMonitorInit> logger, ILogger<PowerMonitorInit> logger,
IScheduler scheduler,
IOptions<PowerMonitorOptions> options, IOptions<PowerMonitorOptions> options,
IPowerSensorDiscoveryService discoveryService, IPowerSensorDiscoveryService discoveryService,
IOtherPowerCalculationService calculationService, IOtherPowerCalculationService calculationService,
IPowerCostCalculationService costService, IPowerCostCalculationService costService,
IPowerMonitorEntityService entityService, IPowerMonitorEntityService entityService,
IPowerNotificationService notificationService, IPowerNotificationService notificationService,
IPowerLimitEnforcementService enforcementService,
TimeProvider timeProvider) TimeProvider timeProvider)
{ {
_haContext = haContext; _haContext = haContext;
_logger = logger; _logger = logger;
_scheduler = scheduler;
_options = options.Value; _options = options.Value;
_discoveryService = discoveryService; _discoveryService = discoveryService;
_calculationService = calculationService; _calculationService = calculationService;
_costService = costService; _costService = costService;
_entityService = entityService; _entityService = entityService;
_notificationService = notificationService; _notificationService = notificationService;
_enforcementService = enforcementService;
_timeProvider = timeProvider; _timeProvider = timeProvider;
_ = InitializeAndScheduleAsync(); _ = InitializeAndScheduleAsync();
@@ -62,8 +61,9 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
try try
{ {
await InitializeAsync(); await InitializeAsync();
SchedulePeriodicPolling(); SubscribeToMainMeterChanges();
SubscribeToRediscoverButton(); SubscribeToRediscoverButton();
SubscribeToLimitBreachDebugButton();
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -101,20 +101,27 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
await _entityService.CleanupEntitiesAsync(cancellationToken); await _entityService.CleanupEntitiesAsync(cancellationToken);
} }
private void SchedulePeriodicPolling() private void SubscribeToMainMeterChanges()
{ {
var now = _timeProvider.GetLocalNow(); if (string.IsNullOrWhiteSpace(_options.MainMeterEntityId))
var intervalSeconds = _options.PollIntervalSeconds; {
var currentSecondInInterval = (now.Minute * 60 + now.Second) % intervalSeconds; _logger.LogWarning("MainMeterEntityId not configured, PowerMonitor will not react to power changes");
var secondsUntilNext = intervalSeconds - currentSecondInInterval; return;
var delayUntilNext = TimeSpan.FromSeconds(secondsUntilNext); }
var nextPollTime = now.Add(delayUntilNext);
_logger.LogInformation( var meter = new Entity(_haContext, _options.MainMeterEntityId);
"Scheduling PowerMonitor polling every {Interval}s, first at {Time}", meter.StateChanges()
intervalSeconds, nextPollTime); .Subscribe(e =>
{
if (e.Old?.State == e.New?.State)
{
return;
}
_scheduler.RunEvery(TimeSpan.FromSeconds(intervalSeconds), nextPollTime, () => _ = PollAndUpdateAsync()); _ = PollAndUpdateAsync();
});
_logger.LogInformation("PowerMonitor subscribed to state changes of {MeterId}", _options.MainMeterEntityId);
} }
private void SubscribeToRediscoverButton() private void SubscribeToRediscoverButton()
@@ -128,6 +135,25 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
}); });
} }
private void SubscribeToLimitBreachDebugButton()
{
var button = new Entity(_haContext, "button.powermonitor_trigger_limit_breach");
button.StateChanges()
.Subscribe(_ =>
{
if (_enforcementService.IsLimitActive)
{
_logger.LogInformation("Limit breach debug button pressed while active, resetting breach");
_enforcementService.ResetLimitBreach();
}
else
{
_logger.LogInformation("Limit breach debug button pressed, triggering fake breach");
_enforcementService.TriggerLimitBreach();
}
});
}
private async Task HandleRediscoveryAsync() private async Task HandleRediscoveryAsync()
{ {
try try
@@ -154,9 +180,7 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
_logger.LogInformation("Removed entities for {Count} sensors", removed.Count); _logger.LogInformation("Removed entities for {Count} sensors", removed.Count);
} }
_logger.LogInformation( _logger.LogInformation("Re-discovery complete: {Total} sensors ({Added} added, {Removed} removed)", newSensors.Count, added.Count, removed.Count);
"Re-discovery complete: {Total} sensors ({Added} added, {Removed} removed)",
newSensors.Count, added.Count, removed.Count);
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -172,9 +196,8 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
if (totalPower is null) if (totalPower is null)
{ {
_mainMeterConsecutiveFailures++; _mainMeterConsecutiveFailures++;
_logger.LogWarning( _logger.LogWarning("Main meter unavailable ({Failures}/{Max})", _mainMeterConsecutiveFailures, PowerMonitorConsts.MainMeterMaxConsecutiveFailures);
"Main meter unavailable ({Failures}/{Max})",
_mainMeterConsecutiveFailures, PowerMonitorConsts.MainMeterMaxConsecutiveFailures);
return; return;
} }
@@ -190,9 +213,15 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
var now = _timeProvider.GetLocalNow(); var now = _timeProvider.GetLocalNow();
_costService.RecordCosts(calculation, nordPoolPrice, _options.PollIntervalSeconds, now.LocalDateTime); var elapsedSeconds = _lastPollTimestamp.HasValue
? Math.Min((now - _lastPollTimestamp.Value).TotalSeconds, _options.PollIntervalSeconds * 10)
: _options.PollIntervalSeconds;
_lastPollTimestamp = now;
_costService.RecordCosts(calculation, nordPoolPrice, (int)Math.Max(1, elapsedSeconds), now.LocalDateTime);
var isAnomaly = calculation.SmoothedOtherPowerWatts > _options.AnomalyThresholdWatts; var isAnomaly = calculation.SmoothedOtherPowerWatts > _options.AnomalyThresholdWatts;
if (isAnomaly && _anomalyStartTime is null) if (isAnomaly && _anomalyStartTime is null)
{ {
_anomalyStartTime = now; _anomalyStartTime = now;
@@ -231,12 +260,10 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
EvaluateHighPowerNotification(calculation.TotalPowerWatts); EvaluateHighPowerNotification(calculation.TotalPowerWatts);
_logger.LogDebug( _enforcementService.EnforceLimit(calculation.TotalPowerWatts);
"Poll complete: total={Total}W, other={Other}W (smoothed), devices={Devices}, price={Price}",
calculation.TotalPowerWatts, _logger.LogDebug("Poll complete: total={Total}W, other={Other}W (smoothed), devices={Devices}, price={Price}",
calculation.SmoothedOtherPowerWatts, calculation.TotalPowerWatts, calculation.SmoothedOtherPowerWatts, deviceReadings.Count, effectivePrice);
deviceReadings.Count,
effectivePrice);
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -247,7 +274,8 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
private double ReadNordPoolPrice() private double ReadNordPoolPrice()
{ {
var state = _haContext.GetState(NordPoolConsts.CurrentPriceEntityId); var state = _haContext.GetState(NordPoolConsts.CurrentPriceEntityId);
if (state?.State is null || state.State == "unavailable" || state.State == "unknown")
if (state?.State is null or "unavailable" or "unknown")
{ {
_logger.LogDebug("NordPool price entity unavailable, using last known price"); _logger.LogDebug("NordPool price entity unavailable, using last known price");
return 0; return 0;
@@ -259,6 +287,7 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
} }
_logger.LogDebug("NordPool price entity returned non-positive value: {State}", state.State); _logger.LogDebug("NordPool price entity returned non-positive value: {State}", state.State);
return 0; return 0;
} }
@@ -281,12 +310,12 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
private double? ReadMainMeterPower() private double? ReadMainMeterPower()
{ {
var state = _haContext.GetState(_options.MainMeterEntityId); var state = _haContext.GetState(_options.MainMeterEntityId);
if (state?.State is null || state.State == "unavailable" || state.State == "unknown") if (state?.State is null or "unavailable" or "unknown")
{ {
return null; return null;
} }
return double.TryParse(state.State, System.Globalization.CultureInfo.InvariantCulture, out var value) return double.TryParse(state.State, CultureInfo.InvariantCulture, out var value)
? value ? value
: null; : null;
} }
@@ -299,18 +328,19 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
foreach (var sensor in _discoveryService.CurrentDeviceSensors) foreach (var sensor in _discoveryService.CurrentDeviceSensors)
{ {
var state = _haContext.GetState(sensor.EntityId); var state = _haContext.GetState(sensor.EntityId);
if (state?.State is null || state.State == "unavailable" || state.State == "unknown") if (state?.State is null or "unavailable" or "unknown")
{ {
readings[sensor.EntityId] = 0; readings[sensor.EntityId] = 0;
degraded.Add(sensor.EntityId); degraded.Add(sensor.EntityId);
continue; continue;
} }
if (double.TryParse(state.State, System.Globalization.CultureInfo.InvariantCulture, out var value)) if (double.TryParse(state.State, CultureInfo.InvariantCulture, out var value))
{ {
var powerWatts = string.Equals(sensor.UnitOfMeasurement, PowerMonitorConsts.KilowattUnit, StringComparison.OrdinalIgnoreCase) var powerWatts = string.Equals(sensor.UnitOfMeasurement, PowerMonitorConsts.KilowattUnit, StringComparison.OrdinalIgnoreCase)
? value * PowerMonitorConsts.WattsPerKilowatt ? value * PowerMonitorConsts.WattsPerKilowatt
: value; : value;
readings[sensor.EntityId] = powerWatts; readings[sensor.EntityId] = powerWatts;
} }
else else
@@ -25,7 +25,8 @@ public static class PowerMonitorServiceRegistration
.AddSingleton<IOtherPowerCalculationService, OtherPowerCalculationService>() .AddSingleton<IOtherPowerCalculationService, OtherPowerCalculationService>()
.AddSingleton<IPowerCostCalculationService, PowerCostCalculationService>() .AddSingleton<IPowerCostCalculationService, PowerCostCalculationService>()
.AddTransient<IPowerMonitorEntityService, PowerMonitorEntityService>() .AddTransient<IPowerMonitorEntityService, PowerMonitorEntityService>()
.AddTransient<IPowerNotificationService, PowerNotificationService>(); .AddTransient<IPowerNotificationService, PowerNotificationService>()
.AddTransient<IPowerLimitEnforcementService, PowerLimitEnforcementService>();
return services; return services;
} }
@@ -6,26 +6,18 @@ using PowerMonitorManager.Models.Consts;
namespace PowerMonitorManager; namespace PowerMonitorManager;
public sealed class PowerNotificationService : IPowerNotificationService public sealed class PowerNotificationService(
IHaContext haContext,
ILogger<PowerNotificationService> logger)
: IPowerNotificationService
{ {
private readonly IHaContext _haContext;
private readonly ILogger<PowerNotificationService> _logger;
public PowerNotificationService(
IHaContext haContext,
ILogger<PowerNotificationService> logger)
{
_haContext = haContext;
_logger = logger;
}
public void NotifyHighPowerUsage(double currentPowerWatts, double thresholdWatts) public void NotifyHighPowerUsage(double currentPowerWatts, double thresholdWatts)
{ {
var currentKw = currentPowerWatts / PowerMonitorConsts.WattsPerKilowatt; var currentKw = currentPowerWatts / PowerMonitorConsts.WattsPerKilowatt;
var thresholdKw = thresholdWatts / PowerMonitorConsts.WattsPerKilowatt; var thresholdKw = thresholdWatts / PowerMonitorConsts.WattsPerKilowatt;
var message = BuildHighPowerMessage(currentKw, thresholdKw); var message = BuildHighPowerMessage(currentKw, thresholdKw);
_haContext.CallService( haContext.CallService(
PowerMonitorConsts.PersistentNotificationDomain, PowerMonitorConsts.PersistentNotificationDomain,
PowerMonitorConsts.PersistentNotificationCreateService, PowerMonitorConsts.PersistentNotificationCreateService,
data: new data: new
@@ -35,14 +27,12 @@ public sealed class PowerNotificationService : IPowerNotificationService
notification_id = PowerMonitorConsts.HighPowerNotificationId notification_id = PowerMonitorConsts.HighPowerNotificationId
}); });
_logger.LogWarning( logger.LogWarning("High power usage notification sent: {CurrentKw:F2} kW (threshold: {ThresholdKw:F1} kW)", currentKw, thresholdKw);
"High power usage notification sent: {CurrentKw:F2} kW (threshold: {ThresholdKw:F1} kW)",
currentKw, thresholdKw);
} }
public void DismissHighPowerNotification() public void DismissHighPowerNotification()
{ {
_haContext.CallService( haContext.CallService(
PowerMonitorConsts.PersistentNotificationDomain, PowerMonitorConsts.PersistentNotificationDomain,
PowerMonitorConsts.PersistentNotificationDismissService, PowerMonitorConsts.PersistentNotificationDismissService,
data: new data: new
@@ -50,10 +40,10 @@ public sealed class PowerNotificationService : IPowerNotificationService
notification_id = PowerMonitorConsts.HighPowerNotificationId notification_id = PowerMonitorConsts.HighPowerNotificationId
}); });
_logger.LogDebug("Dismissed high power usage notification"); logger.LogDebug("Dismissed high power usage notification");
} }
internal static string BuildHighPowerMessage(double currentKw, double thresholdKw) private static string BuildHighPowerMessage(double currentKw, double thresholdKw)
{ {
return string.Format( return string.Format(
CultureInfo.InvariantCulture, CultureInfo.InvariantCulture,
@@ -54,8 +54,7 @@ public sealed class PowerSensorDiscoveryService : IPowerSensorDiscoveryService
_currentDeviceSensors = powerSensors; _currentDeviceSensors = powerSensors;
_logger.LogInformation( _logger.LogInformation("Discovered {Count} power sensors (excluded main meter: {MainMeter}, exclusion patterns: {PatternCount})",
"Discovered {Count} power sensors (excluded main meter: {MainMeter}, exclusion patterns: {PatternCount})",
powerSensors.Count, _options.MainMeterEntityId, _exclusionPatterns.Length); powerSensors.Count, _options.MainMeterEntityId, _exclusionPatterns.Length);
return powerSensors; return powerSensors;
@@ -82,12 +81,12 @@ public sealed class PowerSensorDiscoveryService : IPowerSensorDiscoveryService
string.Equals(unit, PowerMonitorConsts.KilowattUnit, StringComparison.OrdinalIgnoreCase)); string.Equals(unit, PowerMonitorConsts.KilowattUnit, StringComparison.OrdinalIgnoreCase));
} }
internal bool IsMainMeter(string entityId) private bool IsMainMeter(string entityId)
{ {
return string.Equals(entityId, _options.MainMeterEntityId, StringComparison.OrdinalIgnoreCase); return string.Equals(entityId, _options.MainMeterEntityId, StringComparison.OrdinalIgnoreCase);
} }
internal bool IsExcluded(string entityId) private bool IsExcluded(string entityId)
{ {
return _exclusionPatterns.Any(pattern => pattern.IsMatch(entityId)); return _exclusionPatterns.Any(pattern => pattern.IsMatch(entityId));
} }
@@ -1,4 +1,3 @@
using FluentAssertions;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Moq; using Moq;
using NetDaemon.HassModel; using NetDaemon.HassModel;
@@ -49,6 +49,7 @@ public sealed class ExhaustFanControlService(
if (_fanTurnedOnByUs) if (_fanTurnedOnByUs)
{ {
var fanState = haContext.GetState(_options.ExhaustFanEntityId)?.State; var fanState = haContext.GetState(_options.ExhaustFanEntityId)?.State;
if (string.Equals(fanState, "on", StringComparison.OrdinalIgnoreCase)) if (string.Equals(fanState, "on", StringComparison.OrdinalIgnoreCase))
{ {
haContext.CallService("switch", "turn_off", ServiceTarget.FromEntity(_options.ExhaustFanEntityId)); haContext.CallService("switch", "turn_off", ServiceTarget.FromEntity(_options.ExhaustFanEntityId));
@@ -1,4 +1,3 @@
using NetDaemon.HassModel;
using ShowerMonitor.Models.Enums; using ShowerMonitor.Models.Enums;
namespace ShowerMonitorManager.Interface; namespace ShowerMonitorManager.Interface;
@@ -6,19 +6,19 @@ public sealed class ShowerMonitorOptions
{ {
public const string SectionName = "ShowerMonitor"; public const string SectionName = "ShowerMonitor";
public bool Enabled { get; set; } public bool Enabled { get; init; }
public bool CleanupEntitiesOnStartup { get; set; } public bool CleanupEntitiesOnStartup { get; init; }
public string BathroomHumidityEntityId { get; set; } = ShowerMonitorConsts.BathroomHumidityEntityId; public string BathroomHumidityEntityId { get; init; } = ShowerMonitorConsts.BathroomHumidityEntityId;
public string MainHomeHumidityEntityId { get; set; } = ShowerMonitorConsts.MainHomeHumidityEntityId; public string MainHomeHumidityEntityId { get; init; } = ShowerMonitorConsts.MainHomeHumidityEntityId;
public string BathroomTemperatureEntityId { get; set; } = ShowerMonitorConsts.BathroomTemperatureEntityId; public string BathroomTemperatureEntityId { get; init; } = ShowerMonitorConsts.BathroomTemperatureEntityId;
public string ExhaustFanEntityId { get; set; } = ShowerMonitorConsts.ExhaustFanEntityId; public string ExhaustFanEntityId { get; init; } = ShowerMonitorConsts.ExhaustFanEntityId;
public int PollIntervalSeconds { get; set; } = ShowerMonitorConsts.DefaultPollIntervalSeconds; public int PollIntervalSeconds { get; init; } = ShowerMonitorConsts.DefaultPollIntervalSeconds;
public double SpikeRateThreshold { get; set; } = ShowerMonitorConsts.DefaultSpikeRateThreshold; public double SpikeRateThreshold { get; init; } = ShowerMonitorConsts.DefaultSpikeRateThreshold;
public double MinDifferentialHumidity { get; set; } = ShowerMonitorConsts.DefaultMinDifferentialHumidity; public double MinDifferentialHumidity { get; init; } = ShowerMonitorConsts.DefaultMinDifferentialHumidity;
public double PeakHumidityThreshold { get; set; } = ShowerMonitorConsts.DefaultPeakHumidityThreshold; public double PeakHumidityThreshold { get; init; } = ShowerMonitorConsts.DefaultPeakHumidityThreshold;
public int ConfirmationWindowMinutes { get; set; } = ShowerMonitorConsts.DefaultConfirmationWindowMinutes; public int ConfirmationWindowMinutes { get; init; } = ShowerMonitorConsts.DefaultConfirmationWindowMinutes;
public double RecoveryDifferentialThreshold { get; set; } = ShowerMonitorConsts.DefaultRecoveryDifferentialThreshold; public double RecoveryDifferentialThreshold { get; init; } = ShowerMonitorConsts.DefaultRecoveryDifferentialThreshold;
public int MaxShowerDurationMinutes { get; set; } = (int)ShowerMonitorConsts.DefaultMaxShowerDuration.TotalMinutes; public int MaxShowerDurationMinutes { get; init; } = (int)ShowerMonitorConsts.DefaultMaxShowerDuration.TotalMinutes;
public int FanRunAfterShowerMinutes { get; set; } = (int)ShowerMonitorConsts.DefaultFanRunAfterShower.TotalMinutes; public int FanRunAfterShowerMinutes { get; init; } = (int)ShowerMonitorConsts.DefaultFanRunAfterShower.TotalMinutes;
public int RateWindowSize { get; set; } = ShowerMonitorConsts.DefaultRateWindowSize; public int RateWindowSize { get; init; } = ShowerMonitorConsts.DefaultRateWindowSize;
} }
@@ -151,6 +151,7 @@ public sealed class ShowerDetectionService(
if (differential <= _options.RecoveryDifferentialThreshold) if (differential <= _options.RecoveryDifferentialThreshold)
{ {
CompleteSession(timestamp); CompleteSession(timestamp);
return ShowerState.Completed; return ShowerState.Completed;
} }
@@ -159,6 +160,7 @@ public sealed class ShowerDetectionService(
if (_currentSession is not null && _currentSession.GetDuration(timestamp) >= maxDuration) if (_currentSession is not null && _currentSession.GetDuration(timestamp) >= maxDuration)
{ {
CompleteSession(timestamp); CompleteSession(timestamp);
return ShowerState.Completed; return ShowerState.Completed;
} }
@@ -173,6 +175,7 @@ public sealed class ShowerDetectionService(
private ShowerState TransitionToIdle() private ShowerState TransitionToIdle()
{ {
rateCalculator.Reset(); rateCalculator.Reset();
return ShowerState.Idle; return ShowerState.Idle;
} }
@@ -6,7 +6,6 @@ using NetDaemon.AppModel;
using NetDaemon.Extensions.Scheduler; using NetDaemon.Extensions.Scheduler;
using NetDaemon.HassModel; using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities; using NetDaemon.HassModel.Entities;
using ShowerMonitor.Models.Enums;
using ShowerMonitorManager.Interface; using ShowerMonitorManager.Interface;
using ShowerMonitorManager.Models; using ShowerMonitorManager.Models;
using static ShowerMonitor.Models.ShowerMonitorConsts; using static ShowerMonitor.Models.ShowerMonitorConsts;
@@ -3,7 +3,6 @@ using Microsoft.Extensions.DependencyInjection;
using NetDaemon.AppModel; using NetDaemon.AppModel;
using ShowerMonitorManager.Interface; using ShowerMonitorManager.Interface;
using ShowerMonitorManager.Models; using ShowerMonitorManager.Models;
using static ShowerMonitor.Models.ShowerMonitorConsts;
namespace ShowerMonitorManager; namespace ShowerMonitorManager;