From f0bbd4f10bf35c5e9bfdb18f2aefc7379ce44457 Mon Sep 17 00:00:00 2001 From: ExQz Date: Sun, 29 Nov 2026 13:58:08 +0200 Subject: [PATCH] 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. --- AGENTS.md | 79 ++-- .../BoilerMonitorEntityServiceTests.cs | 2 - .../BoilerRunTimeTrackerTests.cs | 254 ------------- BoilerMonitor.Manager/BoilerConfigReader.cs | 12 +- BoilerMonitor.Manager/BoilerControlService.cs | 12 +- .../BoilerMonitorEntityService.cs | 28 +- BoilerMonitor.Manager/BoilerMonitorInit.cs | 1 - .../BoilerMonitorServiceRegistration.cs | 2 - BoilerMonitor.Manager/BoilerRunTimeTracker.cs | 66 ---- .../Interface/IBoilerMonitorEntityService.cs | 1 - BoilerMonitor.Manager/WaterReadyService.cs | 21 +- BoilerMonitor.Models/BoilerMonitorConsts.cs | 1 - .../Components/App.razor | 19 - .../Components/Charts/BoilerChart.razor | 44 --- .../Components/Charts/LightChart.razor | 30 -- .../Components/Charts/NordPoolChart.razor | 32 -- .../Components/Charts/PowerChart.razor | 40 -- .../Components/Charts/ShowerChart.razor | 46 --- .../Components/Layout/MainLayout.razor | 17 - .../Components/Pages/Dashboard.razor | 240 ------------ .../Components/Routes.razor | 6 - .../Components/Shared/EventTable.razor | 54 --- .../Components/Shared/SummaryCards.razor | 53 --- .../Components/_Imports.razor | 15 - .../Configuration/ReplayEntityMap.cs | 109 ------ .../Configuration/ReplayOptions.cs | 19 - .../HistoryData/HistoryStateEntry.cs | 9 - .../HistoryData/HistoryTimeline.cs | 118 ------ .../HomeAssistantHistoryProvider.cs | 347 ------------------ .../HistoryData/IHistoryDataProvider.cs | 17 - .../HomeAssistant.HistoryReplay.csproj | 32 -- .../HomeAssistantApiClient.cs | 53 --- .../HomeAssistantSettings.cs | 15 - .../IHomeAssistantApiClient.cs | 13 - HomeAssistant.HistoryReplay/Program.cs | 77 ---- .../Properties/launchSettings.json | 13 - HomeAssistant.HistoryReplay/README.md | 243 ------------ .../Replay/NoOpEntityManager.cs | 38 -- .../Replay/ReplayHaContext.cs | 98 ----- .../Replay/ReplayTimeProvider.cs | 40 -- .../Reporting/ConsoleReportRenderer.cs | 157 -------- .../Reporting/ReplayDataPoint.cs | 9 - .../Reporting/ReplayDataSeries.cs | 50 --- .../Reporting/ReplayEvent.cs | 20 - .../Reporting/ReplayTimeline.cs | 30 -- .../Runners/BoilerReplayRunner.cs | 221 ----------- .../Runners/IMonitorReplayRunner.cs | 7 - .../Runners/LightReplayRunner.cs | 188 ---------- .../Runners/NordPoolReplayRunner.cs | 182 --------- .../Runners/PowerReplayRunner.cs | 163 -------- .../Runners/ShowerReplayRunner.cs | 136 ------- .../Services/ReplayOrchestrationService.cs | 214 ----------- .../Services/ReplayStatus.cs | 10 - HomeAssistant.HistoryReplay/appsettings.json | 57 --- .../wwwroot/css/app.css | 57 --- .../HomeAssistant.McpServer.csproj | 25 -- HomeAssistant.McpServer/Program.cs | 28 -- .../Services/HomeAssistantApiClient.cs | 118 ------ .../Services/IHomeAssistantApiClient.cs | 31 -- .../Settings/HomeAssistantSettings.cs | 15 - .../Tools/EntityStateTools.cs | 104 ------ HomeAssistant.McpServer/Tools/HistoryTools.cs | 46 --- HomeAssistant.McpServer/Tools/LogbookTools.cs | 45 --- HomeAssistant.McpServer/Tools/ServiceTools.cs | 79 ---- HomeAssistant.McpServer/Tools/SystemTools.cs | 52 --- .../Tools/ValidationTools.cs | 310 ---------------- HomeAssistant.McpServer/appsettings.json | 2 - HomeAssistant.Server/appsettings.json | 12 +- HomeAssistant.Server/program.cs | 1 - HomeAssistantSDK.sln | 22 -- LeakMonitor.Manager/LeakMonitorInit.cs | 7 +- .../LeakMonitorServiceRegistration.cs | 4 +- .../LightControlServiceTests.cs | 1 - .../PresenceServiceTests.cs | 1 - LightMonitor.Manager/LightControlService.cs | 33 +- LightMonitor.Manager/PresenceService.cs | 1 + NordPool.Manager/NordPoolEntityService.cs | 15 +- .../NordPoolServiceRegistration.cs | 1 - .../PowerMonitor.Manager.Tests.csproj | 1 + .../PowerMonitorEntityServiceTests.cs | 13 +- .../PowerMonitorOptionsTests.cs | 48 +++ .../Models/Consts/PowerMonitorConsts.cs | 12 +- .../Models/CostAccumulator.cs | 2 +- .../Models/PowerMonitorOptions.cs | 7 + .../OtherPowerCalculationService.cs | 2 +- .../PowerCostCalculationService.cs | 4 +- .../PowerMonitorEntityService.cs | 8 +- PowerMonitor.Manager/PowerMonitorInit.cs | 100 +++-- .../PowerMonitorServiceRegistration.cs | 3 +- .../PowerNotificationService.cs | 28 +- .../PowerSensorDiscoveryService.cs | 7 +- .../ExhaustFanControlServiceTests.cs | 1 - .../ExhaustFanControlService.cs | 1 + .../Interface/IExhaustFanControlService.cs | 1 - .../Models/ShowerMonitorOptions.cs | 30 +- .../ShowerDetectionService.cs | 3 + ShowerMonitor.Manager/ShowerMonitorInit.cs | 1 - .../ShowerMonitorServiceRegistration.cs | 1 - 98 files changed, 306 insertions(+), 4737 deletions(-) delete mode 100644 BoilerMonitor.Manager.Tests/BoilerRunTimeTrackerTests.cs delete mode 100644 BoilerMonitor.Manager/BoilerRunTimeTracker.cs delete mode 100644 HomeAssistant.HistoryReplay/Components/App.razor delete mode 100644 HomeAssistant.HistoryReplay/Components/Charts/BoilerChart.razor delete mode 100644 HomeAssistant.HistoryReplay/Components/Charts/LightChart.razor delete mode 100644 HomeAssistant.HistoryReplay/Components/Charts/NordPoolChart.razor delete mode 100644 HomeAssistant.HistoryReplay/Components/Charts/PowerChart.razor delete mode 100644 HomeAssistant.HistoryReplay/Components/Charts/ShowerChart.razor delete mode 100644 HomeAssistant.HistoryReplay/Components/Layout/MainLayout.razor delete mode 100644 HomeAssistant.HistoryReplay/Components/Pages/Dashboard.razor delete mode 100644 HomeAssistant.HistoryReplay/Components/Routes.razor delete mode 100644 HomeAssistant.HistoryReplay/Components/Shared/EventTable.razor delete mode 100644 HomeAssistant.HistoryReplay/Components/Shared/SummaryCards.razor delete mode 100644 HomeAssistant.HistoryReplay/Components/_Imports.razor delete mode 100644 HomeAssistant.HistoryReplay/Configuration/ReplayEntityMap.cs delete mode 100644 HomeAssistant.HistoryReplay/Configuration/ReplayOptions.cs delete mode 100644 HomeAssistant.HistoryReplay/HistoryData/HistoryStateEntry.cs delete mode 100644 HomeAssistant.HistoryReplay/HistoryData/HistoryTimeline.cs delete mode 100644 HomeAssistant.HistoryReplay/HistoryData/HomeAssistantHistoryProvider.cs delete mode 100644 HomeAssistant.HistoryReplay/HistoryData/IHistoryDataProvider.cs delete mode 100644 HomeAssistant.HistoryReplay/HomeAssistant.HistoryReplay.csproj delete mode 100644 HomeAssistant.HistoryReplay/HomeAssistantClient/HomeAssistantApiClient.cs delete mode 100644 HomeAssistant.HistoryReplay/HomeAssistantClient/HomeAssistantSettings.cs delete mode 100644 HomeAssistant.HistoryReplay/HomeAssistantClient/IHomeAssistantApiClient.cs delete mode 100644 HomeAssistant.HistoryReplay/Program.cs delete mode 100644 HomeAssistant.HistoryReplay/Properties/launchSettings.json delete mode 100644 HomeAssistant.HistoryReplay/README.md delete mode 100644 HomeAssistant.HistoryReplay/Replay/NoOpEntityManager.cs delete mode 100644 HomeAssistant.HistoryReplay/Replay/ReplayHaContext.cs delete mode 100644 HomeAssistant.HistoryReplay/Replay/ReplayTimeProvider.cs delete mode 100644 HomeAssistant.HistoryReplay/Reporting/ConsoleReportRenderer.cs delete mode 100644 HomeAssistant.HistoryReplay/Reporting/ReplayDataPoint.cs delete mode 100644 HomeAssistant.HistoryReplay/Reporting/ReplayDataSeries.cs delete mode 100644 HomeAssistant.HistoryReplay/Reporting/ReplayEvent.cs delete mode 100644 HomeAssistant.HistoryReplay/Reporting/ReplayTimeline.cs delete mode 100644 HomeAssistant.HistoryReplay/Runners/BoilerReplayRunner.cs delete mode 100644 HomeAssistant.HistoryReplay/Runners/IMonitorReplayRunner.cs delete mode 100644 HomeAssistant.HistoryReplay/Runners/LightReplayRunner.cs delete mode 100644 HomeAssistant.HistoryReplay/Runners/NordPoolReplayRunner.cs delete mode 100644 HomeAssistant.HistoryReplay/Runners/PowerReplayRunner.cs delete mode 100644 HomeAssistant.HistoryReplay/Runners/ShowerReplayRunner.cs delete mode 100644 HomeAssistant.HistoryReplay/Services/ReplayOrchestrationService.cs delete mode 100644 HomeAssistant.HistoryReplay/Services/ReplayStatus.cs delete mode 100644 HomeAssistant.HistoryReplay/appsettings.json delete mode 100644 HomeAssistant.HistoryReplay/wwwroot/css/app.css delete mode 100644 HomeAssistant.McpServer/HomeAssistant.McpServer.csproj delete mode 100644 HomeAssistant.McpServer/Program.cs delete mode 100644 HomeAssistant.McpServer/Services/HomeAssistantApiClient.cs delete mode 100644 HomeAssistant.McpServer/Services/IHomeAssistantApiClient.cs delete mode 100644 HomeAssistant.McpServer/Settings/HomeAssistantSettings.cs delete mode 100644 HomeAssistant.McpServer/Tools/EntityStateTools.cs delete mode 100644 HomeAssistant.McpServer/Tools/HistoryTools.cs delete mode 100644 HomeAssistant.McpServer/Tools/LogbookTools.cs delete mode 100644 HomeAssistant.McpServer/Tools/ServiceTools.cs delete mode 100644 HomeAssistant.McpServer/Tools/SystemTools.cs delete mode 100644 HomeAssistant.McpServer/Tools/ValidationTools.cs delete mode 100644 HomeAssistant.McpServer/appsettings.json diff --git a/AGENTS.md b/AGENTS.md index 08712cc..40b830a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -13,22 +13,28 @@ before editing; it only records things that are easy to get wrong. ## Stack -- .NET 10 / C# 14 (`LangVersion=14.0`). `global.json` pins SDK `10.0.0` with - `rollForward=latestMajor` and `allowPrerelease=true`. +- .NET 10 / C# 14 (`LangVersion=14.0`, set per-csproj in the three + 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 only host / binary-deploy target. Solution file: `HomeAssistantSDK.sln`. - Tests: xUnit + FluentAssertions + Moq. `Microsoft.Extensions.TimeProvider.Testing` 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 settings, and do not log or echo it. ## Layout (non-obvious wiring) - Each monitor follows a fixed 3-project pattern: - - `*.Models` — constants, enums, `*Options` (bound from - `appsettings.json` via `IOptions<>`). - - `*.Manager` — services + the `[NetDaemonApp]` entry `*Init.cs`. + - `*.Models` — entity/config interfaces, constants, enums. + - `*.Manager` — services, the `[NetDaemonApp]` entry `*Init.cs`, and + `*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. - Apps are **not** auto-discovered by the host. Each monitor exposes a `AddMonitor(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 `*ServiceRegistration.cs`, reference the projects from `HomeAssistant.Server`, and wire `Add` + `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 - no-ops (skips `AddNetDaemonApp`) when disabled. `PowerMonitor` ships - disabled by default in `appsettings.json`. + no-ops (skips `AddNetDaemonApp`) when disabled — for every monitor + **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` code (entity metadata sourced from `HomeAssistant.Server/NetDaemonCodegen/{EntityMetaData,ServicesMetaData}.json`). `program.cs` calls `AddHomeAssistantGenerated()`; the generated entities are transient. Do not hand-edit generated files. -- `HomeAssistant.McpServer` is a separate stdio MCP server (ModelContextProtocol - NuGet) exposing HA tools. It is **not** referenced by the host; it runs - standalone via `dotnet run --project HomeAssistant.McpServer`. Cursor - wires it up in `.cursor/mcp.json` as the `homeassistant` MCP server. +- `program.cs` calls `Configure<*Options>` then `Add…` for each + monitor in this order: NordPool, Power, Boiler, Shower, Light, Battery, + Leak. Monitor service registrations (except `IBoilerConfigReader`, + `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 - history through monitor business logic with no side effects. See its own - README. Not deployed. -- `NordPool.Comminication` (sic — typo is intentional, keep it) is the - Nord Pool HTTP client project referenced by `NordPool.Manager`. + history through monitor business logic with no side effects. It + references a subset of monitors (Boiler, NordPool, Power, Shower, Light — + not Battery or Leak). See its own README. Not deployed. ## Critical DI rule @@ -65,7 +87,10 @@ or app load fails with: Verified-livable registrations (do not regress these to singleton): - `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` scoped, `INordPoolBoilerConfigProvider` scoped, `ICheapestIntervalsFinder` singleton (no HA dep). @@ -88,8 +113,8 @@ scoped. ## Live validation after monitor edits `.cursor/rules/live-validation.mdc` (globs: all `*.Manager`/`*.Models` of -Boiler, Light, NordPool, Power, Shower, plus `HomeAssistant.McpServer`) -requires, after editing monitor runtime code: +Boiler, Light, NordPool, Power, Shower, plus `HomeAssistant.McpServer` — +**not** Battery or Leak) requires, after editing monitor runtime code: 1. `dotnet build` the affected project. 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. - `HomeAssistant.Server` references every monitor's `*.Manager` and `*.Models` projects directly; `HomeAssistant.HistoryReplay` references a - subset. Adding a monitor to the replay tool requires a new project - reference there too. + subset (Boiler, NordPool, Power, Shower, Light). Adding a monitor to the + replay tool requires a new project reference there too. - The repository folder name is misspelled `homeassistant-app-deamon` (should be `daemon`). This is intentional/legacy — do not "fix" it in - paths; scripts and `.cursor/mcp.json` use `${workspaceFolder}`. -- `NordPool.Comminication` is also misspelled — keep it; the project - reference depends on the exact name. \ No newline at end of file + paths; `opencode.json` and `.cursor/mcp.json` reference the workspace + folder by macro. +- 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. \ No newline at end of file diff --git a/BoilerMonitor.Manager.Tests/BoilerMonitorEntityServiceTests.cs b/BoilerMonitor.Manager.Tests/BoilerMonitorEntityServiceTests.cs index 5df0bce..4f6f697 100644 --- a/BoilerMonitor.Manager.Tests/BoilerMonitorEntityServiceTests.cs +++ b/BoilerMonitor.Manager.Tests/BoilerMonitorEntityServiceTests.cs @@ -1,6 +1,4 @@ -using BoilerMonitor.Models; using BoilerMonitorManager; -using BoilerMonitorManager.Models; using FluentAssertions; using HomeAssistant.Entities.Interfaces; using Microsoft.Extensions.Logging; diff --git a/BoilerMonitor.Manager.Tests/BoilerRunTimeTrackerTests.cs b/BoilerMonitor.Manager.Tests/BoilerRunTimeTrackerTests.cs deleted file mode 100644 index 053232a..0000000 --- a/BoilerMonitor.Manager.Tests/BoilerRunTimeTrackerTests.cs +++ /dev/null @@ -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 -} diff --git a/BoilerMonitor.Manager/BoilerConfigReader.cs b/BoilerMonitor.Manager/BoilerConfigReader.cs index e9f33c2..c12279e 100644 --- a/BoilerMonitor.Manager/BoilerConfigReader.cs +++ b/BoilerMonitor.Manager/BoilerConfigReader.cs @@ -17,6 +17,7 @@ public sealed class BoilerConfigReader(IHaContext haContext, ILogger 0 ? pc : double.MaxValue; - + var deadline = DateTime.Today.AddDays(1); var readyByState = haContext.GetState(BoilerReadyByEntityId)?.State; + if (!string.IsNullOrEmpty(readyByState) && TimeSpan.TryParse(readyByState, out var readyByTime)) { deadline = DateTime.Today.Add(readyByTime); @@ -35,15 +37,17 @@ public sealed class BoilerConfigReader(IHaContext haContext, ILogger logger) : if (shouldBeOn && !isCurrentlyOn) { - logger.LogInformation( - "Boiler should turn ON — cheap interval active, water not ready, budget available (current state: {State})", - currentSwitchState); + logger.LogInformation("Boiler should turn ON — cheap interval active, water not ready, budget available (current state: {State})", currentSwitchState); return BoilerAction.TurnOn; } @@ -37,12 +35,8 @@ public sealed class BoilerControlService(ILogger logger) : return BoilerAction.TurnOff; } - logger.LogDebug( - "Boiler state unchanged: {State} (cheap={Cheap}, waterReady={WaterReady}, budgetExhausted={BudgetExhausted})", - currentSwitchState, - isNowCheap, - waterReady, - effectiveBudgetExhausted); + logger.LogDebug("Boiler state unchanged: {State} (cheap={Cheap}, waterReady={WaterReady}, budgetExhausted={BudgetExhausted})", + currentSwitchState, isNowCheap, waterReady, effectiveBudgetExhausted); return BoilerAction.NoChange; } diff --git a/BoilerMonitor.Manager/BoilerMonitorEntityService.cs b/BoilerMonitor.Manager/BoilerMonitorEntityService.cs index 3261d0b..9eb8845 100644 --- a/BoilerMonitor.Manager/BoilerMonitorEntityService.cs +++ b/BoilerMonitor.Manager/BoilerMonitorEntityService.cs @@ -93,9 +93,6 @@ public sealed class BoilerMonitorEntityService( var formattedRunTime = FormatTimeSpan(ctx.TodayRunTime); 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[] { UpdateStatusAsync(StatusConfigured), @@ -116,7 +113,7 @@ public sealed class BoilerMonitorEntityService( try { - var removeTasks = CleanableEntityIds.Select(entityId => entityManager.RemoveEntity(entityId)); + var removeTasks = CleanableEntityIds.Select(entityManager.RemoveEntity); await Task.WhenAll(removeTasks).ConfigureAwait(false); 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 budgetOverrideState = haContext.GetState(BudgetOverrideEntityId)?.State; - if (!TryParseEntitySeconds(runtimeState, out var runtimeSeconds) - || !TryParseEntityInt(sessionCountState, out var sessionCount)) + if (!TryParseEntitySeconds(runtimeState, out var runtimeSeconds) || !TryParseEntityInt(sessionCountState, out var sessionCount)) { logger.LogInformation("No valid persisted BoilerMonitor state found in HA entities (runtime={Runtime}, sessions={Sessions})", runtimeState, sessionCountState); @@ -185,19 +181,23 @@ public sealed class BoilerMonitorEntityService( private static bool TryParseEntitySeconds(string? state, out double seconds) { seconds = 0; - return !string.IsNullOrWhiteSpace(state) - && state is not ("unavailable" or "unknown") - && double.TryParse(state, CultureInfo.InvariantCulture, out seconds) - && seconds >= 0; + var tryParseEntitySeconds = !string.IsNullOrWhiteSpace(state) + && state is not ("unavailable" or "unknown") + && double.TryParse(state, CultureInfo.InvariantCulture, out seconds) + && seconds >= 0; + + return tryParseEntitySeconds; } private static bool TryParseEntityInt(string? state, out int value) { value = 0; - return !string.IsNullOrWhiteSpace(state) - && state is not ("unavailable" or "unknown") - && int.TryParse(state, CultureInfo.InvariantCulture, out value) - && value >= 0; + var tryParseEntityInt = !string.IsNullOrWhiteSpace(state) + && state is not ("unavailable" or "unknown") + && int.TryParse(state, CultureInfo.InvariantCulture, out value) + && value >= 0; + + return tryParseEntityInt; } private ICollection GetAllEntities() diff --git a/BoilerMonitor.Manager/BoilerMonitorInit.cs b/BoilerMonitor.Manager/BoilerMonitorInit.cs index 8cacd1d..66edab9 100644 --- a/BoilerMonitor.Manager/BoilerMonitorInit.cs +++ b/BoilerMonitor.Manager/BoilerMonitorInit.cs @@ -1,7 +1,6 @@ using System.Globalization; using System.Reactive.Concurrency; using System.Text.Json; -using BoilerMonitor.Models; using BoilerMonitor.Models.Enums; using BoilerMonitorManager.Interface; using BoilerMonitorManager.Models; diff --git a/BoilerMonitor.Manager/BoilerMonitorServiceRegistration.cs b/BoilerMonitor.Manager/BoilerMonitorServiceRegistration.cs index 277025d..39f3c29 100644 --- a/BoilerMonitor.Manager/BoilerMonitorServiceRegistration.cs +++ b/BoilerMonitor.Manager/BoilerMonitorServiceRegistration.cs @@ -1,4 +1,3 @@ -using BoilerMonitor.Models; using BoilerMonitorManager.Interface; using BoilerMonitorManager.Models; using Microsoft.Extensions.Configuration; @@ -23,7 +22,6 @@ public static class BoilerMonitorServiceRegistration services .AddNetDaemonApp() .AddSingleton() - .AddSingleton() .AddTransient() .AddSingleton(); diff --git a/BoilerMonitor.Manager/BoilerRunTimeTracker.cs b/BoilerMonitor.Manager/BoilerRunTimeTracker.cs deleted file mode 100644 index bfad6fc..0000000 --- a/BoilerMonitor.Manager/BoilerRunTimeTracker.cs +++ /dev/null @@ -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; - } - } -} diff --git a/BoilerMonitor.Manager/Interface/IBoilerMonitorEntityService.cs b/BoilerMonitor.Manager/Interface/IBoilerMonitorEntityService.cs index f269d60..d52ba22 100644 --- a/BoilerMonitor.Manager/Interface/IBoilerMonitorEntityService.cs +++ b/BoilerMonitor.Manager/Interface/IBoilerMonitorEntityService.cs @@ -1,4 +1,3 @@ -using BoilerMonitor.Models; using BoilerMonitorManager.Models; namespace BoilerMonitorManager.Interface; diff --git a/BoilerMonitor.Manager/WaterReadyService.cs b/BoilerMonitor.Manager/WaterReadyService.cs index d10366d..138b764 100644 --- a/BoilerMonitor.Manager/WaterReadyService.cs +++ b/BoilerMonitor.Manager/WaterReadyService.cs @@ -59,9 +59,8 @@ public sealed class WaterReadyService(ILogger logger, TimePro { if (!_hasObservedHeating) { - logger.LogDebug( - "Ignoring power reading ({PowerWatts}W) — boiler has not been observed heating yet", - powerWatts.Value); + logger.LogDebug("Ignoring power reading ({PowerWatts}W) — boiler has not been observed heating yet", powerWatts.Value); + return false; } @@ -75,19 +74,15 @@ public sealed class WaterReadyService(ILogger logger, TimePro if (_consecutiveBelowThresholdCount < BoilerMonitorConsts.ConsecutiveReadingsRequired) { - logger.LogDebug( - "Below-threshold reading {Count}/{Required} ({PowerWatts}W), waiting for confirmation", - _consecutiveBelowThresholdCount, - BoilerMonitorConsts.ConsecutiveReadingsRequired, - powerWatts.Value); + logger.LogDebug("Below-threshold reading {Count}/{Required} ({PowerWatts}W), waiting for confirmation", + _consecutiveBelowThresholdCount, BoilerMonitorConsts.ConsecutiveReadingsRequired, powerWatts.Value); + return false; } _waterReadySince ??= timeProvider.GetUtcNow(); - logger.LogInformation( - "Water detected as ready after {Count} consecutive readings, cooldown active until shower or midnight reset", - _consecutiveBelowThresholdCount); + logger.LogInformation("Water detected as ready after {Count} consecutive readings, cooldown active until shower or midnight reset", _consecutiveBelowThresholdCount); return true; } @@ -137,8 +132,8 @@ public sealed class WaterReadyService(ILogger logger, TimePro var todayMidnightUtc = new DateTimeOffset(timeProvider.GetUtcNow().Date, TimeSpan.Zero); if (waterReadySince < todayMidnightUtc) { - logger.LogInformation( - "Persisted cooldown is from a previous day ({Since}), not restoring", waterReadySince); + logger.LogInformation("Persisted cooldown is from a previous day ({Since}), not restoring", waterReadySince); + return; } diff --git a/BoilerMonitor.Models/BoilerMonitorConsts.cs b/BoilerMonitor.Models/BoilerMonitorConsts.cs index b222db5..d0cf828 100644 --- a/BoilerMonitor.Models/BoilerMonitorConsts.cs +++ b/BoilerMonitor.Models/BoilerMonitorConsts.cs @@ -65,7 +65,6 @@ public static class BoilerMonitorConsts public const string StatusConfigured = "configured"; public const string StatusAwaitingConfiguration = "awaiting_configuration"; - public const string StatusCleanedUp = "cleaned_up"; public const string SwitchOnState = "on"; diff --git a/HomeAssistant.HistoryReplay/Components/App.razor b/HomeAssistant.HistoryReplay/Components/App.razor deleted file mode 100644 index 77d6762..0000000 --- a/HomeAssistant.HistoryReplay/Components/App.razor +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - HA History Replay - - - - - - - - - - - - - diff --git a/HomeAssistant.HistoryReplay/Components/Charts/BoilerChart.razor b/HomeAssistant.HistoryReplay/Components/Charts/BoilerChart.razor deleted file mode 100644 index 3360918..0000000 --- a/HomeAssistant.HistoryReplay/Components/Charts/BoilerChart.razor +++ /dev/null @@ -1,44 +0,0 @@ -@code { - [Parameter] public ReplayDataSeries? DataSeries { get; set; } - - private List PowerData => DataSeries?.GetSeries("Boiler", "PowerWatts").ToList() ?? []; - private List BudgetData => DataSeries?.GetSeries("Boiler", "BudgetPercent").ToList() ?? []; - private List SwitchData => DataSeries?.GetSeries("Boiler", "SwitchState").ToList() ?? []; - - private ApexChartOptions 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) -{ - - - - -} -else -{ -
No boiler data available
-} diff --git a/HomeAssistant.HistoryReplay/Components/Charts/LightChart.razor b/HomeAssistant.HistoryReplay/Components/Charts/LightChart.razor deleted file mode 100644 index 9773970..0000000 --- a/HomeAssistant.HistoryReplay/Components/Charts/LightChart.razor +++ /dev/null @@ -1,30 +0,0 @@ -@code { - [Parameter] public ReplayTimeline? Timeline { get; set; } - - private IReadOnlyList LightEvents => - Timeline?.GetEventsByMonitor("Light") ?? []; -} - -
-
- @if (LightEvents.Count > 0) - { -
- @foreach (var evt in LightEvents) - { - var iconClass = evt.EventType == ReplayEventType.Decision ? "text-warning" : "text-muted"; - var icon = evt.EventType == ReplayEventType.Decision ? "☀" : "•"; -
- @evt.Timestamp.ToLocalTime().ToString("HH:mm") - @((MarkupString)icon) - @evt.Message -
- } -
- } - else - { -
No light events
- } -
-
diff --git a/HomeAssistant.HistoryReplay/Components/Charts/NordPoolChart.razor b/HomeAssistant.HistoryReplay/Components/Charts/NordPoolChart.razor deleted file mode 100644 index f0210dd..0000000 --- a/HomeAssistant.HistoryReplay/Components/Charts/NordPoolChart.razor +++ /dev/null @@ -1,32 +0,0 @@ -@code { - [Parameter] public ReplayDataSeries? DataSeries { get; set; } - - private List PriceData => DataSeries?.GetSeries("NordPool", "Price").ToList() ?? []; - - private ApexChartOptions 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) -{ - - - -} -else -{ -
No price data available
-} diff --git a/HomeAssistant.HistoryReplay/Components/Charts/PowerChart.razor b/HomeAssistant.HistoryReplay/Components/Charts/PowerChart.razor deleted file mode 100644 index 7129b93..0000000 --- a/HomeAssistant.HistoryReplay/Components/Charts/PowerChart.razor +++ /dev/null @@ -1,40 +0,0 @@ -@code { - [Parameter] public ReplayDataSeries? DataSeries { get; set; } - - private List TotalData => DataSeries?.GetSeries("Power", "TotalPower").ToList() ?? []; - private List KnownData => DataSeries?.GetSeries("Power", "KnownDevices").ToList() ?? []; - private List OtherData => DataSeries?.GetSeries("Power", "OtherPower").ToList() ?? []; - - private ApexChartOptions 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) -{ - - - - -} -else -{ -
No power data available
-} diff --git a/HomeAssistant.HistoryReplay/Components/Charts/ShowerChart.razor b/HomeAssistant.HistoryReplay/Components/Charts/ShowerChart.razor deleted file mode 100644 index 878a9c8..0000000 --- a/HomeAssistant.HistoryReplay/Components/Charts/ShowerChart.razor +++ /dev/null @@ -1,46 +0,0 @@ -@code { - [Parameter] public ReplayDataSeries? DataSeries { get; set; } - - private List BathroomData => DataSeries?.GetSeries("Shower", "BathroomHumidity").ToList() ?? []; - private List HomeData => DataSeries?.GetSeries("Shower", "HomeHumidity").ToList() ?? []; - private List DiffData => DataSeries?.GetSeries("Shower", "Differential").ToList() ?? []; - - private ApexChartOptions 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) -{ - - - - - -} -else -{ -
No shower data available
-} diff --git a/HomeAssistant.HistoryReplay/Components/Layout/MainLayout.razor b/HomeAssistant.HistoryReplay/Components/Layout/MainLayout.razor deleted file mode 100644 index 6713df2..0000000 --- a/HomeAssistant.HistoryReplay/Components/Layout/MainLayout.razor +++ /dev/null @@ -1,17 +0,0 @@ -@inherits LayoutComponentBase - -
- - -
- @Body -
-
diff --git a/HomeAssistant.HistoryReplay/Components/Pages/Dashboard.razor b/HomeAssistant.HistoryReplay/Components/Pages/Dashboard.razor deleted file mode 100644 index 07c5f61..0000000 --- a/HomeAssistant.HistoryReplay/Components/Pages/Dashboard.razor +++ /dev/null @@ -1,240 +0,0 @@ -@page "/" -@inject ReplayOrchestrationService Replay -@implements IDisposable - -

History Replay Dashboard

- -
-
-
-
- - -
-
- - -
-
- -
-
- - -
-
- - -
-
- - -
-
- - -
-
- - -
-
-
-
- -
-
-
-
- -
- @switch (Replay.Status) - { - case ReplayStatus.FetchingHistory: -
- - @(Replay.ProgressMessage ?? "Fetching history data from Home Assistant...") -
- break; - case ReplayStatus.Running: -
- - @(Replay.ProgressMessage ?? "Running replay...") -
- break; - case ReplayStatus.Completed: -
- Replay completed -- @Replay.Timeline.GetAllEvents().Count event(s) -
- break; - case ReplayStatus.Failed: -
- Replay failed: @Replay.ErrorMessage -
- break; - } -
- -@if (Replay.Status == ReplayStatus.Completed) -{ - - - - -
- @if (_activeTab == NordPoolTab) - { -
-
NordPool Price Timeline
-
-
- - } - else if (_activeTab == BoilerTab) - { -
-
Boiler Power and Budget
-
-
- - } - else if (_activeTab == ShowerTab) - { -
-
Humidity and Shower Detection
-
-
- - } - else if (_activeTab == PowerTab) - { -
-
Power Breakdown
-
-
- - } - else if (_activeTab == LightTab) - { -
-
Light Control Events
-
-
- - } - else if (_activeTab == ServiceCallsTab) - { - - } -
-} - -@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 _enabledMonitors = []; - - protected override void OnInitialized() - { - Replay.OnStateChanged += HandleStateChanged; - } - - private IReadOnlyList 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 BuildEnabledMonitors() - { - var list = new List(); - 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; - } -} diff --git a/HomeAssistant.HistoryReplay/Components/Routes.razor b/HomeAssistant.HistoryReplay/Components/Routes.razor deleted file mode 100644 index faa2a8c..0000000 --- a/HomeAssistant.HistoryReplay/Components/Routes.razor +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/HomeAssistant.HistoryReplay/Components/Shared/EventTable.razor b/HomeAssistant.HistoryReplay/Components/Shared/EventTable.razor deleted file mode 100644 index 50ea9b2..0000000 --- a/HomeAssistant.HistoryReplay/Components/Shared/EventTable.razor +++ /dev/null @@ -1,54 +0,0 @@ -@code { - [Parameter] public IReadOnlyList 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) -{ -
No events recorded for this monitor.
-} -else -{ -
- - - - - - - - - - - @foreach (var evt in Events.Take(MaxRows)) - { - - - - - - - } - -
TimeTypeMessageDetails
- @evt.Timestamp.ToLocalTime().ToString("HH:mm:ss") - - @evt.EventType - @evt.Message@evt.Details
-
- - @if (Events.Count > MaxRows) - { -
Showing @MaxRows of @Events.Count events
- } -} diff --git a/HomeAssistant.HistoryReplay/Components/Shared/SummaryCards.razor b/HomeAssistant.HistoryReplay/Components/Shared/SummaryCards.razor deleted file mode 100644 index 804a376..0000000 --- a/HomeAssistant.HistoryReplay/Components/Shared/SummaryCards.razor +++ /dev/null @@ -1,53 +0,0 @@ -@code { - [Parameter] public ReplayTimeline? Timeline { get; set; } - - private IReadOnlyList 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); -} - -
-
-
-
-
@TotalEvents
-
Total Events
-
-
-
-
-
-
-
@Decisions
-
Decisions
-
-
-
-
-
-
-
@ServiceCalls
-
Service Calls
-
-
-
-
-
-
-
@Warnings
-
Warnings
-
-
-
-
-
-
-
@Anomalies
-
Anomalies
-
-
-
-
diff --git a/HomeAssistant.HistoryReplay/Components/_Imports.razor b/HomeAssistant.HistoryReplay/Components/_Imports.razor deleted file mode 100644 index 448c811..0000000 --- a/HomeAssistant.HistoryReplay/Components/_Imports.razor +++ /dev/null @@ -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 diff --git a/HomeAssistant.HistoryReplay/Configuration/ReplayEntityMap.cs b/HomeAssistant.HistoryReplay/Configuration/ReplayEntityMap.cs deleted file mode 100644 index bbde841..0000000 --- a/HomeAssistant.HistoryReplay/Configuration/ReplayEntityMap.cs +++ /dev/null @@ -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 GetNordPoolEntities() => - [ - "sensor.nordpool_kwh_lt_eur_3_10_0", - NordPoolConsts.CurrentPriceEntityId, - BoilerMonitorConsts.BoilerDailyHoursEntityId, - BoilerMonitorConsts.BoilerPriceCapEntityId, - BoilerMonitorConsts.BoilerReadyByEntityId, - BoilerMonitorConsts.SkipPriceCapEntityId - ]; - - public static IReadOnlyList GetBoilerEntities(string boilerPowerEntityId, string boilerSwitchEntityId) => - [ - boilerPowerEntityId, - boilerSwitchEntityId, - "sensor.nordpool_cheapest_intervals", - BoilerMonitorConsts.SkipPriceCapEntityId, - BoilerMonitorConsts.BudgetOverrideEntityId, - BoilerMonitorConsts.AutoManagementEntityId, - BoilerMonitorConsts.BoilerDailyHoursEntityId - ]; - - public static IReadOnlyList GetShowerEntities(string bathroomHumidityEntityId, string mainHomeHumidityEntityId) => - [ - bathroomHumidityEntityId, - mainHomeHumidityEntityId - ]; - - public static IReadOnlyList GetPowerEntities(string mainMeterEntityId) => - [ - mainMeterEntityId, - NordPoolConsts.CurrentPriceEntityId - ]; - - public static IReadOnlyList GetLightEntities(string sunEntityId, string lightEntityId, string[] personEntityIds) - { - var entities = new List { sunEntityId, lightEntityId }; - entities.AddRange(personEntityIds); - return entities; - } - - public static IReadOnlyList GetEntitiesRequiringAttributes() => - [ - "sensor.nordpool_cheapest_intervals" - ]; - - public static IReadOnlyList GetAllEntities( - string boilerPowerEntityId, - string boilerSwitchEntityId, - string bathroomHumidityEntityId, - string mainHomeHumidityEntityId, - string mainMeterEntityId, - string sunEntityId, - string lightEntityId, - string[] personEntityIds) - { - var all = new HashSet(); - - 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 MinimalEntities, IReadOnlyList 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(GetEntitiesRequiringAttributes(), StringComparer.OrdinalIgnoreCase); - var minimal = new List(); - var full = new List(); - - foreach (var entity in allEntities) - { - if (fullSet.Contains(entity)) - { - full.Add(entity); - } - else - { - minimal.Add(entity); - } - } - - return (minimal, full); - } -} diff --git a/HomeAssistant.HistoryReplay/Configuration/ReplayOptions.cs b/HomeAssistant.HistoryReplay/Configuration/ReplayOptions.cs deleted file mode 100644 index ff2a7a2..0000000 --- a/HomeAssistant.HistoryReplay/Configuration/ReplayOptions.cs +++ /dev/null @@ -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; -} diff --git a/HomeAssistant.HistoryReplay/HistoryData/HistoryStateEntry.cs b/HomeAssistant.HistoryReplay/HistoryData/HistoryStateEntry.cs deleted file mode 100644 index e750663..0000000 --- a/HomeAssistant.HistoryReplay/HistoryData/HistoryStateEntry.cs +++ /dev/null @@ -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? Attributes { get; init; } -} diff --git a/HomeAssistant.HistoryReplay/HistoryData/HistoryTimeline.cs b/HomeAssistant.HistoryReplay/HistoryData/HistoryTimeline.cs deleted file mode 100644 index d017c27..0000000 --- a/HomeAssistant.HistoryReplay/HistoryData/HistoryTimeline.cs +++ /dev/null @@ -1,118 +0,0 @@ -namespace HomeAssistant.HistoryReplay.HistoryData; - -public sealed class HistoryTimeline -{ - private readonly Dictionary> _entityTimelines = new(StringComparer.OrdinalIgnoreCase); - private bool _sorted; - - public void AddEntries(string entityId, IEnumerable entries) - { - if (!_entityTimelines.TryGetValue(entityId, out var list)) - { - list = []; - _entityTimelines[entityId] = list; - } - - list.AddRange(entries); - _sorted = false; - } - - public void AddEntriesBulk(string entityId, List 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 GetAllTimestamps() - { - var timestamps = new SortedSet(); - - foreach (var entries in _entityTimelines.Values) - { - foreach (var entry in entries) - { - timestamps.Add(entry.LastChanged); - } - } - - return [.. timestamps]; - } - - public IReadOnlyList GetEntityIds() => [.. _entityTimelines.Keys]; - - public IReadOnlyList 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 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; - } -} diff --git a/HomeAssistant.HistoryReplay/HistoryData/HomeAssistantHistoryProvider.cs b/HomeAssistant.HistoryReplay/HistoryData/HomeAssistantHistoryProvider.cs deleted file mode 100644 index 7f399d7..0000000 --- a/HomeAssistant.HistoryReplay/HistoryData/HomeAssistantHistoryProvider.cs +++ /dev/null @@ -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 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 FetchHistoryAsync( - IReadOnlyList entityIds, - DateTimeOffset startTime, - DateTimeOffset endTime, - CancellationToken cancellationToken = default) - { - return FetchHistoryAsync( - minimalEntityIds: entityIds, - fullEntityIds: [], - startTime, endTime, cancellationToken); - } - - public async Task FetchHistoryAsync( - IReadOnlyList minimalEntityIds, - IReadOnlyList 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(); - 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 FetchBatchThrottledAsync( - IReadOnlyList 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 FetchBatchWithRetryAsync( - IReadOnlyList 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)>(); - 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 Entries)>> FetchEntitiesIndividuallyAsync( - IReadOnlyList entityIds, - DateTimeOffset startTime, - DateTimeOffset endTime, - CancellationToken cancellationToken) - { - var allEntries = new List<(string, List)>(); - 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 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)>(); - 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 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(); - - 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? 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 ParseAttributes(JsonElement attrElement) - { - var attributes = new Dictionary(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> ChunkEntities(IReadOnlyList entities, int chunkSize) - { - var chunks = new List>(); - - 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 Entries)> Entries, - List FailedEntityIds); -} diff --git a/HomeAssistant.HistoryReplay/HistoryData/IHistoryDataProvider.cs b/HomeAssistant.HistoryReplay/HistoryData/IHistoryDataProvider.cs deleted file mode 100644 index a61ff65..0000000 --- a/HomeAssistant.HistoryReplay/HistoryData/IHistoryDataProvider.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace HomeAssistant.HistoryReplay.HistoryData; - -public interface IHistoryDataProvider -{ - Task FetchHistoryAsync( - IReadOnlyList entityIds, - DateTimeOffset startTime, - DateTimeOffset endTime, - CancellationToken cancellationToken = default); - - Task FetchHistoryAsync( - IReadOnlyList minimalEntityIds, - IReadOnlyList fullEntityIds, - DateTimeOffset startTime, - DateTimeOffset endTime, - CancellationToken cancellationToken = default); -} diff --git a/HomeAssistant.HistoryReplay/HomeAssistant.HistoryReplay.csproj b/HomeAssistant.HistoryReplay/HomeAssistant.HistoryReplay.csproj deleted file mode 100644 index 1b3c934..0000000 --- a/HomeAssistant.HistoryReplay/HomeAssistant.HistoryReplay.csproj +++ /dev/null @@ -1,32 +0,0 @@ - - - - net10.0 - 14.0 - enable - enable - HomeAssistant.HistoryReplay - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/HomeAssistant.HistoryReplay/HomeAssistantClient/HomeAssistantApiClient.cs b/HomeAssistant.HistoryReplay/HomeAssistantClient/HomeAssistantApiClient.cs deleted file mode 100644 index 3127d17..0000000 --- a/HomeAssistant.HistoryReplay/HomeAssistantClient/HomeAssistantApiClient.cs +++ /dev/null @@ -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 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 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 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(); - } -} diff --git a/HomeAssistant.HistoryReplay/HomeAssistantClient/HomeAssistantSettings.cs b/HomeAssistant.HistoryReplay/HomeAssistantClient/HomeAssistantSettings.cs deleted file mode 100644 index 687ee64..0000000 --- a/HomeAssistant.HistoryReplay/HomeAssistantClient/HomeAssistantSettings.cs +++ /dev/null @@ -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; -} diff --git a/HomeAssistant.HistoryReplay/HomeAssistantClient/IHomeAssistantApiClient.cs b/HomeAssistant.HistoryReplay/HomeAssistantClient/IHomeAssistantApiClient.cs deleted file mode 100644 index b1c9579..0000000 --- a/HomeAssistant.HistoryReplay/HomeAssistantClient/IHomeAssistantApiClient.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System.Text.Json; - -namespace HomeAssistant.HistoryReplay.HomeAssistantClient; - -public interface IHomeAssistantApiClient -{ - Task GetHistoryAsync( - string entityIds, - DateTimeOffset? startTime = null, - DateTimeOffset? endTime = null, - bool minimalResponse = true, - CancellationToken cancellationToken = default); -} diff --git a/HomeAssistant.HistoryReplay/Program.cs b/HomeAssistant.HistoryReplay/Program.cs deleted file mode 100644 index b3a4092..0000000 --- a/HomeAssistant.HistoryReplay/Program.cs +++ /dev/null @@ -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( - builder.Configuration.GetSection(HomeAssistantSettings.SectionName)); -builder.Services.Configure( - builder.Configuration.GetSection(BoilerMonitorOptions.SectionName)); -builder.Services.Configure( - builder.Configuration.GetSection(ShowerMonitorOptions.SectionName)); -builder.Services.Configure( - builder.Configuration.GetSection(PowerMonitorOptions.SectionName)); -builder.Services.Configure( - builder.Configuration.GetSection(LightMonitorOptions.SectionName)); - -builder.Services.AddHttpClient(); -builder.Services.AddSingleton(); - -builder.Services.AddSingleton(); -builder.Services.AddSingleton(); -builder.Services.AddSingleton(); - -var showerOpts = builder.Configuration - .GetSection(ShowerMonitorOptions.SectionName) - .Get() ?? new ShowerMonitorOptions(); -builder.Services.AddSingleton(_ => new HumidityRateCalculator(showerOpts.RateWindowSize)); - -builder.Services.AddSingleton(); - -var app = builder.Build(); - -if (!app.Environment.IsDevelopment()) -{ - app.UseHsts(); -} - -app.MapStaticAssets(); -app.UseAntiforgery(); - -app.MapRazorComponents() - .AddInteractiveServerRenderMode(); - -Log.Information("History Replay Dashboard running at {Urls}", string.Join(", ", app.Urls)); - -app.Run(); diff --git a/HomeAssistant.HistoryReplay/Properties/launchSettings.json b/HomeAssistant.HistoryReplay/Properties/launchSettings.json deleted file mode 100644 index 92164df..0000000 --- a/HomeAssistant.HistoryReplay/Properties/launchSettings.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "profiles": { - "HomeAssistant.HistoryReplay": { - "commandName": "Project", - "dotnetRunMessages": true, - "launchBrowser": false, - "applicationUrl": "http://localhost:5000", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - } - } -} diff --git a/HomeAssistant.HistoryReplay/README.md b/HomeAssistant.HistoryReplay/README.md deleted file mode 100644 index 9b1f60e..0000000 --- a/HomeAssistant.HistoryReplay/README.md +++ /dev/null @@ -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": "", - "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. diff --git a/HomeAssistant.HistoryReplay/Replay/NoOpEntityManager.cs b/HomeAssistant.HistoryReplay/Replay/NoOpEntityManager.cs deleted file mode 100644 index 4d71e51..0000000 --- a/HomeAssistant.HistoryReplay/Replay/NoOpEntityManager.cs +++ /dev/null @@ -1,38 +0,0 @@ -using HomeAssistant.Entities.Interfaces; -using HomeAssistant.Models; -using Microsoft.Extensions.Logging; - -namespace HomeAssistant.HistoryReplay.Replay; - -public sealed class NoOpEntityManager(ILogger logger) : IEntityManager -{ - public Task CreateEntitiesAsync(ICollection 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; - } -} diff --git a/HomeAssistant.HistoryReplay/Replay/ReplayHaContext.cs b/HomeAssistant.HistoryReplay/Replay/ReplayHaContext.cs deleted file mode 100644 index 5d79762..0000000 --- a/HomeAssistant.HistoryReplay/Replay/ReplayHaContext.cs +++ /dev/null @@ -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 _logger; - - public ReplayHaContext( - HistoryTimeline timeline, - ReplayTimeProvider timeProvider, - ReplayTimeline replayTimeline, - ILogger 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 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 StateAllChanges() => Observable.Empty(); - - public IObservable Events => Observable.Empty(); - - public Task CallServiceWithResponseAsync( - string domain, string service, ServiceTarget? target = null, object? data = null) - { - CallService(domain, service, target, data); - return Task.FromResult(null); - } - - public Area? GetAreaFromEntityId(string entityId) => null; - - public EntityRegistration? GetEntityRegistration(string entityId) => null; -} diff --git a/HomeAssistant.HistoryReplay/Replay/ReplayTimeProvider.cs b/HomeAssistant.HistoryReplay/Replay/ReplayTimeProvider.cs deleted file mode 100644 index 6847249..0000000 --- a/HomeAssistant.HistoryReplay/Replay/ReplayTimeProvider.cs +++ /dev/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; - } - } -} diff --git a/HomeAssistant.HistoryReplay/Reporting/ConsoleReportRenderer.cs b/HomeAssistant.HistoryReplay/Reporting/ConsoleReportRenderer.cs deleted file mode 100644 index b30f9ce..0000000 --- a/HomeAssistant.HistoryReplay/Reporting/ConsoleReportRenderer.cs +++ /dev/null @@ -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 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 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 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(); - 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; - } -} diff --git a/HomeAssistant.HistoryReplay/Reporting/ReplayDataPoint.cs b/HomeAssistant.HistoryReplay/Reporting/ReplayDataPoint.cs deleted file mode 100644 index aae4971..0000000 --- a/HomeAssistant.HistoryReplay/Reporting/ReplayDataPoint.cs +++ /dev/null @@ -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; } -} diff --git a/HomeAssistant.HistoryReplay/Reporting/ReplayDataSeries.cs b/HomeAssistant.HistoryReplay/Reporting/ReplayDataSeries.cs deleted file mode 100644 index 0039a4e..0000000 --- a/HomeAssistant.HistoryReplay/Reporting/ReplayDataSeries.cs +++ /dev/null @@ -1,50 +0,0 @@ -using System.Collections.Concurrent; - -namespace HomeAssistant.HistoryReplay.Reporting; - -public sealed class ReplayDataSeries -{ - private readonly ConcurrentBag _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 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 GetAllForMonitor(string monitor) => - _points - .Where(p => string.Equals(p.Monitor, monitor, StringComparison.OrdinalIgnoreCase)) - .OrderBy(p => p.Timestamp) - .ToList(); - - public IReadOnlyList 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(); - } -} diff --git a/HomeAssistant.HistoryReplay/Reporting/ReplayEvent.cs b/HomeAssistant.HistoryReplay/Reporting/ReplayEvent.cs deleted file mode 100644 index 463e2f0..0000000 --- a/HomeAssistant.HistoryReplay/Reporting/ReplayEvent.cs +++ /dev/null @@ -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 -} diff --git a/HomeAssistant.HistoryReplay/Reporting/ReplayTimeline.cs b/HomeAssistant.HistoryReplay/Reporting/ReplayTimeline.cs deleted file mode 100644 index c4046e6..0000000 --- a/HomeAssistant.HistoryReplay/Reporting/ReplayTimeline.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System.Collections.Concurrent; - -namespace HomeAssistant.HistoryReplay.Reporting; - -public sealed class ReplayTimeline -{ - private readonly ConcurrentBag _events = []; - - public void AddEvent(ReplayEvent replayEvent) - { - _events.Add(replayEvent); - } - - public IReadOnlyList GetEventsByMonitor(string monitor) => - _events - .Where(e => string.Equals(e.Monitor, monitor, StringComparison.OrdinalIgnoreCase)) - .OrderBy(e => e.Timestamp) - .ToList(); - - public IReadOnlyList GetAllEvents() => - _events.OrderBy(e => e.Timestamp).ToList(); - - public IReadOnlyList GetMonitors() => - _events.Select(e => e.Monitor).Distinct(StringComparer.OrdinalIgnoreCase).Order().ToList(); - - public void Clear() - { - _events.Clear(); - } -} diff --git a/HomeAssistant.HistoryReplay/Runners/BoilerReplayRunner.cs b/HomeAssistant.HistoryReplay/Runners/BoilerReplayRunner.cs deleted file mode 100644 index 6d222ea..0000000 --- a/HomeAssistant.HistoryReplay/Runners/BoilerReplayRunner.cs +++ /dev/null @@ -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 _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 logger, - IOptions 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; - } -} diff --git a/HomeAssistant.HistoryReplay/Runners/IMonitorReplayRunner.cs b/HomeAssistant.HistoryReplay/Runners/IMonitorReplayRunner.cs deleted file mode 100644 index c757120..0000000 --- a/HomeAssistant.HistoryReplay/Runners/IMonitorReplayRunner.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace HomeAssistant.HistoryReplay.Runners; - -public interface IMonitorReplayRunner -{ - string MonitorName { get; } - Task RunAsync(CancellationToken cancellationToken = default); -} diff --git a/HomeAssistant.HistoryReplay/Runners/LightReplayRunner.cs b/HomeAssistant.HistoryReplay/Runners/LightReplayRunner.cs deleted file mode 100644 index acdcb6b..0000000 --- a/HomeAssistant.HistoryReplay/Runners/LightReplayRunner.cs +++ /dev/null @@ -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 _logger; - private readonly ReplayOptions _replayOptions; - private readonly LightMonitorOptions _lightOptions; - - public string MonitorName => "Light"; - - public LightReplayRunner( - HistoryTimeline timeline, - ReplayTimeProvider timeProvider, - ReplayTimeline replayTimeline, - ReplayDataSeries dataSeries, - ILogger logger, - IOptions replayOptions, - IOptions 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; - } -} diff --git a/HomeAssistant.HistoryReplay/Runners/NordPoolReplayRunner.cs b/HomeAssistant.HistoryReplay/Runners/NordPoolReplayRunner.cs deleted file mode 100644 index 38f8370..0000000 --- a/HomeAssistant.HistoryReplay/Runners/NordPoolReplayRunner.cs +++ /dev/null @@ -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 _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 logger, - IOptions 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 }; - } -} diff --git a/HomeAssistant.HistoryReplay/Runners/PowerReplayRunner.cs b/HomeAssistant.HistoryReplay/Runners/PowerReplayRunner.cs deleted file mode 100644 index 49730d7..0000000 --- a/HomeAssistant.HistoryReplay/Runners/PowerReplayRunner.cs +++ /dev/null @@ -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 _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 logger, - IOptions replayOptions, - IOptions 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 DiscoverAndReadDevicePower(DateTimeOffset timestamp) - { - var readings = new Dictionary(); - 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; - } -} diff --git a/HomeAssistant.HistoryReplay/Runners/ShowerReplayRunner.cs b/HomeAssistant.HistoryReplay/Runners/ShowerReplayRunner.cs deleted file mode 100644 index 2b76145..0000000 --- a/HomeAssistant.HistoryReplay/Runners/ShowerReplayRunner.cs +++ /dev/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 _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 logger, - IOptions replayOptions, - IOptions 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; - } -} diff --git a/HomeAssistant.HistoryReplay/Services/ReplayOrchestrationService.cs b/HomeAssistant.HistoryReplay/Services/ReplayOrchestrationService.cs deleted file mode 100644 index dd14de6..0000000 --- a/HomeAssistant.HistoryReplay/Services/ReplayOrchestrationService.cs +++ /dev/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 _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 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>().Value; - var powerOpts = _serviceProvider.GetRequiredService>().Value; - var lightOpts = _serviceProvider.GetRequiredService>().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>()); - - 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 BuildRunners( - HistoryTimeline historyTimeline, - ReplayTimeProvider timeProvider, - ReplayHaContext replayHaContext, - IOptions replayOptions, - ReplayMonitorFlags monitors, - string boilerPowerEntityId, - string boilerSwitchEntityId) - { - var runners = new List(); - - if (monitors.NordPool) - { - runners.Add(new NordPoolReplayRunner( - historyTimeline, timeProvider, Timeline, DataSeries, - _serviceProvider.GetRequiredService(), - _serviceProvider.GetRequiredService>(), - replayOptions)); - } - - if (monitors.Boiler) - { - runners.Add(new BoilerReplayRunner( - historyTimeline, timeProvider, Timeline, DataSeries, - _serviceProvider.GetRequiredService(), - new BoilerRunTimeTracker(), - new WaterReadyService( - _serviceProvider.GetRequiredService>(), timeProvider), - _serviceProvider.GetRequiredService>(), - replayOptions, - boilerPowerEntityId, - boilerSwitchEntityId)); - } - - if (monitors.Shower) - { - var showerOpts = _serviceProvider.GetRequiredService>(); - 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>(), - replayOptions, showerOpts)); - } - - if (monitors.Power) - { - runners.Add(new PowerReplayRunner( - historyTimeline, timeProvider, Timeline, DataSeries, - new OtherPowerCalculationService( - _serviceProvider.GetRequiredService>()), - new PowerCostCalculationService(), - _serviceProvider.GetRequiredService>(), - replayOptions, - _serviceProvider.GetRequiredService>())); - } - - if (monitors.Light) - { - runners.Add(new LightReplayRunner( - historyTimeline, timeProvider, Timeline, DataSeries, - _serviceProvider.GetRequiredService>(), - replayOptions, - _serviceProvider.GetRequiredService>())); - } - - return runners; - } - - private void NotifyStateChanged() => OnStateChanged?.Invoke(); -} diff --git a/HomeAssistant.HistoryReplay/Services/ReplayStatus.cs b/HomeAssistant.HistoryReplay/Services/ReplayStatus.cs deleted file mode 100644 index a0e622d..0000000 --- a/HomeAssistant.HistoryReplay/Services/ReplayStatus.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace HomeAssistant.HistoryReplay.Services; - -public enum ReplayStatus -{ - Idle, - FetchingHistory, - Running, - Completed, - Failed -} \ No newline at end of file diff --git a/HomeAssistant.HistoryReplay/appsettings.json b/HomeAssistant.HistoryReplay/appsettings.json deleted file mode 100644 index 0360eec..0000000 --- a/HomeAssistant.HistoryReplay/appsettings.json +++ /dev/null @@ -1,57 +0,0 @@ -{ - "HomeAssistant": { - "Host": "homeassistant.local", - "Port": 8123, - "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_*" - ] - } -} diff --git a/HomeAssistant.HistoryReplay/wwwroot/css/app.css b/HomeAssistant.HistoryReplay/wwwroot/css/app.css deleted file mode 100644 index e6469ff..0000000 --- a/HomeAssistant.HistoryReplay/wwwroot/css/app.css +++ /dev/null @@ -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; -} diff --git a/HomeAssistant.McpServer/HomeAssistant.McpServer.csproj b/HomeAssistant.McpServer/HomeAssistant.McpServer.csproj deleted file mode 100644 index 4596d92..0000000 --- a/HomeAssistant.McpServer/HomeAssistant.McpServer.csproj +++ /dev/null @@ -1,25 +0,0 @@ - - - - Exe - net10.0 - 14.0 - enable - enable - HomeAssistant.McpServer - - - - - PreserveNewest - - - - - - - - - - - diff --git a/HomeAssistant.McpServer/Program.cs b/HomeAssistant.McpServer/Program.cs deleted file mode 100644 index 95ae288..0000000 --- a/HomeAssistant.McpServer/Program.cs +++ /dev/null @@ -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( - builder.Configuration.GetSection(HomeAssistantSettings.SectionName)) - .AddHttpClient(); - -builder.Services - .AddMcpServer() - .WithStdioServerTransport() - .WithToolsFromAssembly(); - -await builder.Build().RunAsync(); diff --git a/HomeAssistant.McpServer/Services/HomeAssistantApiClient.cs b/HomeAssistant.McpServer/Services/HomeAssistantApiClient.cs deleted file mode 100644 index 3b3bdec..0000000 --- a/HomeAssistant.McpServer/Services/HomeAssistantApiClient.cs +++ /dev/null @@ -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 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 GetApiStatusAsync(CancellationToken cancellationToken = default) => - GetJsonAsync("/api/", cancellationToken); - - public Task GetConfigAsync(CancellationToken cancellationToken = default) => - GetJsonAsync("/api/config", cancellationToken); - - public Task GetAllStatesAsync(CancellationToken cancellationToken = default) => - GetJsonAsync("/api/states", cancellationToken); - - public Task GetEntityStateAsync(string entityId, CancellationToken cancellationToken = default) => - GetJsonAsync($"/api/states/{Uri.EscapeDataString(entityId)}", cancellationToken); - - public Task GetServicesAsync(CancellationToken cancellationToken = default) => - GetJsonAsync("/api/services", cancellationToken); - - public Task 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 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(); - 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 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 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(); - } -} diff --git a/HomeAssistant.McpServer/Services/IHomeAssistantApiClient.cs b/HomeAssistant.McpServer/Services/IHomeAssistantApiClient.cs deleted file mode 100644 index e8abb1f..0000000 --- a/HomeAssistant.McpServer/Services/IHomeAssistantApiClient.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System.Text.Json; - -namespace HomeAssistant.McpServer.Services; - -public interface IHomeAssistantApiClient -{ - Task GetApiStatusAsync(CancellationToken cancellationToken = default); - Task GetConfigAsync(CancellationToken cancellationToken = default); - Task GetAllStatesAsync(CancellationToken cancellationToken = default); - Task GetEntityStateAsync(string entityId, CancellationToken cancellationToken = default); - Task GetServicesAsync(CancellationToken cancellationToken = default); - - Task GetHistoryAsync( - string entityIds, - DateTimeOffset? startTime = null, - DateTimeOffset? endTime = null, - bool minimalResponse = true, - CancellationToken cancellationToken = default); - - Task GetLogbookAsync( - string? entityId = null, - DateTimeOffset? startTime = null, - DateTimeOffset? endTime = null, - CancellationToken cancellationToken = default); - - Task CallServiceAsync( - string domain, - string service, - JsonElement? serviceData = null, - CancellationToken cancellationToken = default); -} diff --git a/HomeAssistant.McpServer/Settings/HomeAssistantSettings.cs b/HomeAssistant.McpServer/Settings/HomeAssistantSettings.cs deleted file mode 100644 index b41ca09..0000000 --- a/HomeAssistant.McpServer/Settings/HomeAssistantSettings.cs +++ /dev/null @@ -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; -} diff --git a/HomeAssistant.McpServer/Tools/EntityStateTools.cs b/HomeAssistant.McpServer/Tools/EntityStateTools.cs deleted file mode 100644 index 687a25a..0000000 --- a/HomeAssistant.McpServer/Tools/EntityStateTools.cs +++ /dev/null @@ -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 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 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 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 - }; -} diff --git a/HomeAssistant.McpServer/Tools/HistoryTools.cs b/HomeAssistant.McpServer/Tools/HistoryTools.cs deleted file mode 100644 index e934a94..0000000 --- a/HomeAssistant.McpServer/Tools/HistoryTools.cs +++ /dev/null @@ -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 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 - }; -} diff --git a/HomeAssistant.McpServer/Tools/LogbookTools.cs b/HomeAssistant.McpServer/Tools/LogbookTools.cs deleted file mode 100644 index fb2b0c3..0000000 --- a/HomeAssistant.McpServer/Tools/LogbookTools.cs +++ /dev/null @@ -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 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 - }; -} diff --git a/HomeAssistant.McpServer/Tools/ServiceTools.cs b/HomeAssistant.McpServer/Tools/ServiceTools.cs deleted file mode 100644 index b8091c3..0000000 --- a/HomeAssistant.McpServer/Tools/ServiceTools.cs +++ /dev/null @@ -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 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 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() - : JsonSerializer.Deserialize>(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 - }; -} diff --git a/HomeAssistant.McpServer/Tools/SystemTools.cs b/HomeAssistant.McpServer/Tools/SystemTools.cs deleted file mode 100644 index 4acd222..0000000 --- a/HomeAssistant.McpServer/Tools/SystemTools.cs +++ /dev/null @@ -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 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 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 - }; -} diff --git a/HomeAssistant.McpServer/Tools/ValidationTools.cs b/HomeAssistant.McpServer/Tools/ValidationTools.cs deleted file mode 100644 index 5d40748..0000000 --- a/HomeAssistant.McpServer/Tools/ValidationTools.cs +++ /dev/null @@ -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 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 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 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(); - 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() - .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 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 CheckEntitiesAsync(string[] targetDomains, CancellationToken cancellationToken) - { - var allStates = await _client.GetAllStatesAsync(cancellationToken).ConfigureAwait(false); - var domainSet = new HashSet(targetDomains, StringComparer.OrdinalIgnoreCase); - - var unhealthy = new ConcurrentBag(); - 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 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 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 - }; - } - } -} diff --git a/HomeAssistant.McpServer/appsettings.json b/HomeAssistant.McpServer/appsettings.json deleted file mode 100644 index 2c63c08..0000000 --- a/HomeAssistant.McpServer/appsettings.json +++ /dev/null @@ -1,2 +0,0 @@ -{ -} diff --git a/HomeAssistant.Server/appsettings.json b/HomeAssistant.Server/appsettings.json index a5b55ea..da9b965 100644 --- a/HomeAssistant.Server/appsettings.json +++ b/HomeAssistant.Server/appsettings.json @@ -70,12 +70,22 @@ "NotificationCooldownMinutes": 5 }, "PowerMonitor": { - "Enabled": false, + "Enabled": true, "MainMeterEntityId": "sensor.sonoff_100267d63f_power", "PollIntervalSeconds": 1, "SmoothingWindowSize": 10, "AnomalyThresholdWatts": 500, "HighPowerThresholdWatts": 6000, + "EnforceLimitEnabled": true, + "PowerLimitWatts": 5500, + "RecoverySeconds": 600, + "LimitCooldownSeconds": 30, + "EnforceSwitchOffEntityIds": [ + "switch.sonoff_1002230e32" + ], + "PauseAndRestoreEntityIds": [ + "switch.boilermonitor_auto_management" + ], "ExcludedSensorPatterns": [ "sensor.nordpool_*", "sensor.powermonitor_*" diff --git a/HomeAssistant.Server/program.cs b/HomeAssistant.Server/program.cs index 0595b91..0e6b696 100644 --- a/HomeAssistant.Server/program.cs +++ b/HomeAssistant.Server/program.cs @@ -15,7 +15,6 @@ using NetDaemon.Runtime; using BoilerMonitorManager; using BoilerMonitorManager.Models; using NordPoolManager; -using NordPoolManager.Interface; using NordPoolManager.Models; using PowerMonitorManager; using PowerMonitorManager.Models; diff --git a/HomeAssistantSDK.sln b/HomeAssistantSDK.sln index f239f73..7d7ab10 100644 --- a/HomeAssistantSDK.sln +++ b/HomeAssistantSDK.sln @@ -30,8 +30,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Testing", "Testing", "{95E9 EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Models", "Models", "{48492269-2B47-43FE-BC14-A901054EE5AE}" 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}" EndProject 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 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LightMonitor.Manager.Tests", "LightMonitor.Manager.Tests\LightMonitor.Manager.Tests.csproj", "{B8303C3E-785C-48F0-8F40-D4A9E9D50C92}" 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}" EndProject 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|x86.ActiveCfg = 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.Build.0 = 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|x86.ActiveCfg = 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.Build.0 = Debug|Any CPU {2D27B621-7B92-4014-8FDF-6AD376C97612}.Debug|x64.ActiveCfg = Debug|Any CPU diff --git a/LeakMonitor.Manager/LeakMonitorInit.cs b/LeakMonitor.Manager/LeakMonitorInit.cs index c185de3..21c959e 100644 --- a/LeakMonitor.Manager/LeakMonitorInit.cs +++ b/LeakMonitor.Manager/LeakMonitorInit.cs @@ -38,6 +38,7 @@ public sealed class LeakMonitorInit : ILeakMonitorInit if (_options.SensorEntityIds.Length == 0) { _logger.LogWarning("LeakMonitor enabled but no sensor entity IDs configured"); + return Task.CompletedTask; } @@ -46,9 +47,7 @@ public sealed class LeakMonitorInit : ILeakMonitorInit SubscribeToLeakSensor(sensorEntityId); } - _logger.LogInformation( - "LeakMonitor initialized, monitoring {Count} sensor(s)", - _options.SensorEntityIds.Length); + _logger.LogInformation("LeakMonitor initialized, monitoring {Count} sensor(s)", _options.SensorEntityIds.Length); } catch (Exception ex) { @@ -85,11 +84,13 @@ public sealed class LeakMonitorInit : ILeakMonitorInit if (string.Equals(newState, LeakMonitorConsts.WaterDetectedState, StringComparison.OrdinalIgnoreCase)) { _logger.LogWarning("Water leak detected by {SensorId}!", sensorEntityId); + _notificationService.SendLeakAlert(sensorEntityId); } else if (string.Equals(newState, LeakMonitorConsts.WaterClearedState, StringComparison.OrdinalIgnoreCase)) { _logger.LogInformation("Water leak cleared by {SensorId}", sensorEntityId); + _notificationService.DismissLeakAlert(sensorEntityId); } } diff --git a/LeakMonitor.Manager/LeakMonitorServiceRegistration.cs b/LeakMonitor.Manager/LeakMonitorServiceRegistration.cs index 9f5338c..0c1e693 100644 --- a/LeakMonitor.Manager/LeakMonitorServiceRegistration.cs +++ b/LeakMonitor.Manager/LeakMonitorServiceRegistration.cs @@ -19,9 +19,7 @@ public static class LeakMonitorServiceRegistration return services; } - services - .AddNetDaemonApp() - .AddScoped(); + services.AddNetDaemonApp().AddScoped(); return services; } diff --git a/LightMonitor.Manager.Tests/LightControlServiceTests.cs b/LightMonitor.Manager.Tests/LightControlServiceTests.cs index 8afde48..1b06219 100644 --- a/LightMonitor.Manager.Tests/LightControlServiceTests.cs +++ b/LightMonitor.Manager.Tests/LightControlServiceTests.cs @@ -1,4 +1,3 @@ -using FluentAssertions; using LightMonitor.Models; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; diff --git a/LightMonitor.Manager.Tests/PresenceServiceTests.cs b/LightMonitor.Manager.Tests/PresenceServiceTests.cs index 7fc7c4b..05463a0 100644 --- a/LightMonitor.Manager.Tests/PresenceServiceTests.cs +++ b/LightMonitor.Manager.Tests/PresenceServiceTests.cs @@ -1,5 +1,4 @@ using FluentAssertions; -using LightMonitor.Models; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Moq; diff --git a/LightMonitor.Manager/LightControlService.cs b/LightMonitor.Manager/LightControlService.cs index c5cac4b..ceaf386 100644 --- a/LightMonitor.Manager/LightControlService.cs +++ b/LightMonitor.Manager/LightControlService.cs @@ -8,43 +8,36 @@ using LightMonitorManager.Models; namespace LightMonitorManager; -public sealed class LightControlService : ILightControlService +public sealed class LightControlService( + IHaContext haContext, + ILogger logger, + IOptions options) + : ILightControlService { - private readonly IHaContext _haContext; - private readonly ILogger _logger; - private readonly LightMonitorOptions _options; - - public LightControlService( - IHaContext haContext, - ILogger logger, - IOptions options) - { - _haContext = haContext; - _logger = logger; - _options = options.Value; - } + private readonly LightMonitorOptions _options = options.Value; 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)) { - _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; } - var lightState = _haContext.GetState(_options.LightEntityId)?.State; + var lightState = haContext.GetState(_options.LightEntityId)?.State; 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; } - _haContext.CallService("light", "turn_on", ServiceTarget.FromEntity(_options.LightEntityId)); - _logger.LogInformation("Light {EntityId} turned ON (dark outside + person home)", _options.LightEntityId); + haContext.CallService("light", "turn_on", ServiceTarget.FromEntity(_options.LightEntityId)); + + logger.LogInformation("Light {EntityId} turned ON (dark outside + person home)", _options.LightEntityId); } } diff --git a/LightMonitor.Manager/PresenceService.cs b/LightMonitor.Manager/PresenceService.cs index 038684c..696357f 100644 --- a/LightMonitor.Manager/PresenceService.cs +++ b/LightMonitor.Manager/PresenceService.cs @@ -28,6 +28,7 @@ public sealed class PresenceService( if (string.Equals(state.State, LightMonitorConsts.PersonHomeState, StringComparison.OrdinalIgnoreCase)) { logger.LogDebug("Person {EntityId} is home", personEntityId); + return true; } } diff --git a/NordPool.Manager/NordPoolEntityService.cs b/NordPool.Manager/NordPoolEntityService.cs index ea23f7f..9c9e8b7 100644 --- a/NordPool.Manager/NordPoolEntityService.cs +++ b/NordPool.Manager/NordPoolEntityService.cs @@ -163,8 +163,7 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger< if (mergedPrices.Count > NordPoolConsts.MaxExpectedPriceEntries) { - logger.LogWarning("Merged price count ({Count}) exceeds expected maximum ({Max}). Attribute payload may be oversized", - mergedPrices.Count, NordPoolConsts.MaxExpectedPriceEntries); + logger.LogWarning("Merged price count ({Count}) exceeds expected maximum ({Max}). Attribute payload may be oversized", mergedPrices.Count, NordPoolConsts.MaxExpectedPriceEntries); } var cheapestCount = ctx.CheapestIntervals?.Count ?? 0; @@ -310,11 +309,13 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger< var todayList = today?.Prices ?? []; var tomorrowList = tomorrow?.Prices ?? []; - return todayList - .Concat(tomorrowList) - .Where(p => p is { Start: not null }) - .OrderBy(p => p.Start!.Value) - .ToList(); + return + [ + .. todayList + .Concat(tomorrowList) + .Where(p => p is { Start: not null }) + .OrderBy(p => p.Start!.Value) + ]; } internal async Task SetEntityStateSafe(string entityId, string state) diff --git a/NordPool.Manager/NordPoolServiceRegistration.cs b/NordPool.Manager/NordPoolServiceRegistration.cs index c720e77..65ab90a 100644 --- a/NordPool.Manager/NordPoolServiceRegistration.cs +++ b/NordPool.Manager/NordPoolServiceRegistration.cs @@ -2,7 +2,6 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using NetDaemon.AppModel; using NordPoolManager.Interface; -using NordPoolManager.Models; namespace NordPoolManager; diff --git a/PowerMonitor.Manager.Tests/PowerMonitor.Manager.Tests.csproj b/PowerMonitor.Manager.Tests/PowerMonitor.Manager.Tests.csproj index 9a4409f..5bbe0f3 100644 --- a/PowerMonitor.Manager.Tests/PowerMonitor.Manager.Tests.csproj +++ b/PowerMonitor.Manager.Tests/PowerMonitor.Manager.Tests.csproj @@ -20,6 +20,7 @@ + diff --git a/PowerMonitor.Manager.Tests/PowerMonitorEntityServiceTests.cs b/PowerMonitor.Manager.Tests/PowerMonitorEntityServiceTests.cs index 7f69e57..e1e2ac8 100644 --- a/PowerMonitor.Manager.Tests/PowerMonitorEntityServiceTests.cs +++ b/PowerMonitor.Manager.Tests/PowerMonitorEntityServiceTests.cs @@ -24,11 +24,11 @@ public class PowerMonitorEntityServiceTests #region GetSystemEntitiesList [Fact] - public void GetSystemEntitiesList_ShouldReturnAll13SystemEntities() + public void GetSystemEntitiesList_ShouldReturnAll14SystemEntities() { var result = _sut.GetSystemEntitiesList(); - result.Should().HaveCount(13); + result.Should().HaveCount(14); } [Fact] @@ -49,6 +49,7 @@ public class PowerMonitorEntityServiceTests 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 == "button.powermonitor_rediscover_sensors"); + result.Should().Contain(e => e.EntityId == "button.powermonitor_trigger_limit_breach"); } [Fact] @@ -103,14 +104,14 @@ public class PowerMonitorEntityServiceTests #region CreateSystemEntitiesAsync [Fact] - public async Task CreateSystemEntitiesAsync_ShouldCreateAll13Entities() + public async Task CreateSystemEntitiesAsync_ShouldCreateAll14Entities() { _entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny())) .Returns(Task.CompletedTask); await _sut.CreateSystemEntitiesAsync(); - _entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny()), Times.Exactly(13)); + _entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny()), Times.Exactly(14)); } [Fact] @@ -131,7 +132,7 @@ public class PowerMonitorEntityServiceTests await _sut.CreateSystemEntitiesAsync(); - _entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny()), Times.Exactly(13)); + _entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny()), Times.Exactly(14)); } #endregion @@ -186,7 +187,7 @@ public class PowerMonitorEntityServiceTests await _sut.CleanupEntitiesAsync(); - _entityManagerMock.Verify(em => em.RemoveEntity(It.IsAny()), Times.Exactly(13)); + _entityManagerMock.Verify(em => em.RemoveEntity(It.IsAny()), Times.Exactly(14)); } #endregion diff --git a/PowerMonitor.Manager.Tests/PowerMonitorOptionsTests.cs b/PowerMonitor.Manager.Tests/PowerMonitorOptionsTests.cs index 92b3196..b6658a9 100644 --- a/PowerMonitor.Manager.Tests/PowerMonitorOptionsTests.cs +++ b/PowerMonitor.Manager.Tests/PowerMonitorOptionsTests.cs @@ -67,4 +67,52 @@ public class PowerMonitorOptionsTests 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(); + } } diff --git a/PowerMonitor.Manager/Models/Consts/PowerMonitorConsts.cs b/PowerMonitor.Manager/Models/Consts/PowerMonitorConsts.cs index a5e498e..ec1e8cd 100644 --- a/PowerMonitor.Manager/Models/Consts/PowerMonitorConsts.cs +++ b/PowerMonitor.Manager/Models/Consts/PowerMonitorConsts.cs @@ -20,12 +20,18 @@ public static class PowerMonitorConsts 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 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 PersistentNotificationCreateService = "create"; public const string PersistentNotificationDismissService = "dismiss"; - - public const int MinutesPerQuarterHour = 15; - public const int MinutesPerHour = 60; + public const string SwitchDomain = "switch"; + public const string TurnOnService = "turn_on"; + public const string TurnOffService = "turn_off"; } diff --git a/PowerMonitor.Manager/Models/CostAccumulator.cs b/PowerMonitor.Manager/Models/CostAccumulator.cs index 7e17d2a..271cbea 100644 --- a/PowerMonitor.Manager/Models/CostAccumulator.cs +++ b/PowerMonitor.Manager/Models/CostAccumulator.cs @@ -2,7 +2,7 @@ namespace PowerMonitorManager.Models; public sealed class CostAccumulator { - private readonly object _lock = new(); + private readonly Lock _lock = new(); private double _cost15Min; private double _cost1Hour; diff --git a/PowerMonitor.Manager/Models/PowerMonitorOptions.cs b/PowerMonitor.Manager/Models/PowerMonitorOptions.cs index 443c0ff..3a554be 100644 --- a/PowerMonitor.Manager/Models/PowerMonitorOptions.cs +++ b/PowerMonitor.Manager/Models/PowerMonitorOptions.cs @@ -13,4 +13,11 @@ public sealed class PowerMonitorOptions public double AnomalyThresholdWatts { get; set; } = PowerMonitorConsts.DefaultAnomalyThresholdWatts; public string[] ExcludedSensorPatterns { get; set; } = []; 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; } = []; } diff --git a/PowerMonitor.Manager/OtherPowerCalculationService.cs b/PowerMonitor.Manager/OtherPowerCalculationService.cs index db6d07b..3261336 100644 --- a/PowerMonitor.Manager/OtherPowerCalculationService.cs +++ b/PowerMonitor.Manager/OtherPowerCalculationService.cs @@ -8,7 +8,7 @@ public sealed class OtherPowerCalculationService : IOtherPowerCalculationService { private readonly double _alpha; private double? _previousSmoothed; - private readonly object _lock = new(); + private readonly Lock _lock = new(); public OtherPowerCalculationService(IOptions options) { diff --git a/PowerMonitor.Manager/PowerCostCalculationService.cs b/PowerMonitor.Manager/PowerCostCalculationService.cs index 40c05aa..1e099e4 100644 --- a/PowerMonitor.Manager/PowerCostCalculationService.cs +++ b/PowerMonitor.Manager/PowerCostCalculationService.cs @@ -10,11 +10,11 @@ public sealed class PowerCostCalculationService : IPowerCostCalculationService private readonly ConcurrentDictionary _deviceAccumulators = new(); private CostAccumulator? _totalAccumulator; private CostAccumulator? _otherAccumulator; - private readonly object _accumulatorLock = new(); + private readonly Lock _accumulatorLock = new(); private double _lastKnownPrice; private string _priceSource = "live"; - private readonly object _priceLock = new(); + private readonly Lock _priceLock = new(); public double LastKnownPrice { diff --git a/PowerMonitor.Manager/PowerMonitorEntityService.cs b/PowerMonitor.Manager/PowerMonitorEntityService.cs index 01824ca..3d90f09 100644 --- a/PowerMonitor.Manager/PowerMonitorEntityService.cs +++ b/PowerMonitor.Manager/PowerMonitorEntityService.cs @@ -25,6 +25,7 @@ public sealed class PowerMonitorEntityService( private const string AnomalyEntityId = "binary_sensor.powermonitor_anomaly"; private const string StatusEntityId = "sensor.powermonitor_status"; private const string RediscoverButtonEntityId = "button.powermonitor_rediscover_sensors"; + private const string TriggerLimitBreachButtonEntityId = "button.powermonitor_trigger_limit_breach"; private static readonly string[] SystemEntityIds = [ @@ -34,7 +35,8 @@ public sealed class PowerMonitorEntityService( OtherCost15MinEntityId, OtherCost1HEntityId, OtherCostDailyEntityId, OtherCostMonthlyEntityId, AnomalyEntityId, StatusEntityId, - RediscoverButtonEntityId + RediscoverButtonEntityId, + TriggerLimitBreachButtonEntityId ]; public async Task CreateSystemEntitiesAsync(CancellationToken cancellationToken = default) @@ -199,6 +201,10 @@ public sealed class PowerMonitorEntityService( new("button", "powermonitor_rediscover_sensors", "Rediscover power sensors") { AdditionalConfig = new { icon = "mdi:refresh" } + }, + new("button", "powermonitor_trigger_limit_breach", "Trigger power limit breach (debug)") + { + AdditionalConfig = new { icon = "mdi:flash-alert" } } }; } diff --git a/PowerMonitor.Manager/PowerMonitorInit.cs b/PowerMonitor.Manager/PowerMonitorInit.cs index 3db26c7..d3692ce 100644 --- a/PowerMonitor.Manager/PowerMonitorInit.cs +++ b/PowerMonitor.Manager/PowerMonitorInit.cs @@ -1,9 +1,7 @@ using System.Globalization; -using System.Reactive.Concurrency; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using NetDaemon.AppModel; -using NetDaemon.Extensions.Scheduler; using NetDaemon.HassModel; using NetDaemon.HassModel.Entities; using NordPool.Models; @@ -18,40 +16,41 @@ public sealed class PowerMonitorInit : IPowerMonitorInit { private readonly ILogger _logger; private readonly IHaContext _haContext; - private readonly IScheduler _scheduler; private readonly PowerMonitorOptions _options; private readonly IPowerSensorDiscoveryService _discoveryService; private readonly IOtherPowerCalculationService _calculationService; private readonly IPowerCostCalculationService _costService; private readonly IPowerMonitorEntityService _entityService; private readonly IPowerNotificationService _notificationService; + private readonly IPowerLimitEnforcementService _enforcementService; private readonly TimeProvider _timeProvider; private int _mainMeterConsecutiveFailures; private DateTimeOffset? _anomalyStartTime; + private DateTimeOffset? _lastPollTimestamp; private bool _highPowerNotificationActive; public PowerMonitorInit( IHaContext haContext, ILogger logger, - IScheduler scheduler, IOptions options, IPowerSensorDiscoveryService discoveryService, IOtherPowerCalculationService calculationService, IPowerCostCalculationService costService, IPowerMonitorEntityService entityService, IPowerNotificationService notificationService, + IPowerLimitEnforcementService enforcementService, TimeProvider timeProvider) { _haContext = haContext; _logger = logger; - _scheduler = scheduler; _options = options.Value; _discoveryService = discoveryService; _calculationService = calculationService; _costService = costService; _entityService = entityService; _notificationService = notificationService; + _enforcementService = enforcementService; _timeProvider = timeProvider; _ = InitializeAndScheduleAsync(); @@ -62,8 +61,9 @@ public sealed class PowerMonitorInit : IPowerMonitorInit try { await InitializeAsync(); - SchedulePeriodicPolling(); + SubscribeToMainMeterChanges(); SubscribeToRediscoverButton(); + SubscribeToLimitBreachDebugButton(); } catch (Exception ex) { @@ -101,20 +101,27 @@ public sealed class PowerMonitorInit : IPowerMonitorInit await _entityService.CleanupEntitiesAsync(cancellationToken); } - private void SchedulePeriodicPolling() + private void SubscribeToMainMeterChanges() { - var now = _timeProvider.GetLocalNow(); - var intervalSeconds = _options.PollIntervalSeconds; - var currentSecondInInterval = (now.Minute * 60 + now.Second) % intervalSeconds; - var secondsUntilNext = intervalSeconds - currentSecondInInterval; - var delayUntilNext = TimeSpan.FromSeconds(secondsUntilNext); - var nextPollTime = now.Add(delayUntilNext); + if (string.IsNullOrWhiteSpace(_options.MainMeterEntityId)) + { + _logger.LogWarning("MainMeterEntityId not configured, PowerMonitor will not react to power changes"); + return; + } - _logger.LogInformation( - "Scheduling PowerMonitor polling every {Interval}s, first at {Time}", - intervalSeconds, nextPollTime); + var meter = new Entity(_haContext, _options.MainMeterEntityId); + meter.StateChanges() + .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() @@ -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() { try @@ -154,9 +180,7 @@ public sealed class PowerMonitorInit : IPowerMonitorInit _logger.LogInformation("Removed entities for {Count} sensors", removed.Count); } - _logger.LogInformation( - "Re-discovery complete: {Total} sensors ({Added} added, {Removed} removed)", - newSensors.Count, added.Count, removed.Count); + _logger.LogInformation("Re-discovery complete: {Total} sensors ({Added} added, {Removed} removed)", newSensors.Count, added.Count, removed.Count); } catch (Exception ex) { @@ -172,9 +196,8 @@ public sealed class PowerMonitorInit : IPowerMonitorInit if (totalPower is null) { _mainMeterConsecutiveFailures++; - _logger.LogWarning( - "Main meter unavailable ({Failures}/{Max})", - _mainMeterConsecutiveFailures, PowerMonitorConsts.MainMeterMaxConsecutiveFailures); + _logger.LogWarning("Main meter unavailable ({Failures}/{Max})", _mainMeterConsecutiveFailures, PowerMonitorConsts.MainMeterMaxConsecutiveFailures); + return; } @@ -190,9 +213,15 @@ public sealed class PowerMonitorInit : IPowerMonitorInit 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; + if (isAnomaly && _anomalyStartTime is null) { _anomalyStartTime = now; @@ -231,12 +260,10 @@ public sealed class PowerMonitorInit : IPowerMonitorInit EvaluateHighPowerNotification(calculation.TotalPowerWatts); - _logger.LogDebug( - "Poll complete: total={Total}W, other={Other}W (smoothed), devices={Devices}, price={Price}", - calculation.TotalPowerWatts, - calculation.SmoothedOtherPowerWatts, - deviceReadings.Count, - effectivePrice); + _enforcementService.EnforceLimit(calculation.TotalPowerWatts); + + _logger.LogDebug("Poll complete: total={Total}W, other={Other}W (smoothed), devices={Devices}, price={Price}", + calculation.TotalPowerWatts, calculation.SmoothedOtherPowerWatts, deviceReadings.Count, effectivePrice); } catch (Exception ex) { @@ -247,7 +274,8 @@ public sealed class PowerMonitorInit : IPowerMonitorInit private double ReadNordPoolPrice() { 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"); return 0; @@ -259,6 +287,7 @@ public sealed class PowerMonitorInit : IPowerMonitorInit } _logger.LogDebug("NordPool price entity returned non-positive value: {State}", state.State); + return 0; } @@ -281,12 +310,12 @@ public sealed class PowerMonitorInit : IPowerMonitorInit private double? ReadMainMeterPower() { 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 double.TryParse(state.State, System.Globalization.CultureInfo.InvariantCulture, out var value) + return double.TryParse(state.State, CultureInfo.InvariantCulture, out var value) ? value : null; } @@ -299,18 +328,19 @@ public sealed class PowerMonitorInit : IPowerMonitorInit foreach (var sensor in _discoveryService.CurrentDeviceSensors) { 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; degraded.Add(sensor.EntityId); 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) ? value * PowerMonitorConsts.WattsPerKilowatt : value; + readings[sensor.EntityId] = powerWatts; } else diff --git a/PowerMonitor.Manager/PowerMonitorServiceRegistration.cs b/PowerMonitor.Manager/PowerMonitorServiceRegistration.cs index 59853b8..2d82bc7 100644 --- a/PowerMonitor.Manager/PowerMonitorServiceRegistration.cs +++ b/PowerMonitor.Manager/PowerMonitorServiceRegistration.cs @@ -25,7 +25,8 @@ public static class PowerMonitorServiceRegistration .AddSingleton() .AddSingleton() .AddTransient() - .AddTransient(); + .AddTransient() + .AddTransient(); return services; } diff --git a/PowerMonitor.Manager/PowerNotificationService.cs b/PowerMonitor.Manager/PowerNotificationService.cs index 2354993..23e3879 100644 --- a/PowerMonitor.Manager/PowerNotificationService.cs +++ b/PowerMonitor.Manager/PowerNotificationService.cs @@ -6,26 +6,18 @@ using PowerMonitorManager.Models.Consts; namespace PowerMonitorManager; -public sealed class PowerNotificationService : IPowerNotificationService +public sealed class PowerNotificationService( + IHaContext haContext, + ILogger logger) + : IPowerNotificationService { - private readonly IHaContext _haContext; - private readonly ILogger _logger; - - public PowerNotificationService( - IHaContext haContext, - ILogger logger) - { - _haContext = haContext; - _logger = logger; - } - public void NotifyHighPowerUsage(double currentPowerWatts, double thresholdWatts) { var currentKw = currentPowerWatts / PowerMonitorConsts.WattsPerKilowatt; var thresholdKw = thresholdWatts / PowerMonitorConsts.WattsPerKilowatt; var message = BuildHighPowerMessage(currentKw, thresholdKw); - _haContext.CallService( + haContext.CallService( PowerMonitorConsts.PersistentNotificationDomain, PowerMonitorConsts.PersistentNotificationCreateService, data: new @@ -35,14 +27,12 @@ public sealed class PowerNotificationService : IPowerNotificationService notification_id = PowerMonitorConsts.HighPowerNotificationId }); - _logger.LogWarning( - "High power usage notification sent: {CurrentKw:F2} kW (threshold: {ThresholdKw:F1} kW)", - currentKw, thresholdKw); + logger.LogWarning("High power usage notification sent: {CurrentKw:F2} kW (threshold: {ThresholdKw:F1} kW)", currentKw, thresholdKw); } public void DismissHighPowerNotification() { - _haContext.CallService( + haContext.CallService( PowerMonitorConsts.PersistentNotificationDomain, PowerMonitorConsts.PersistentNotificationDismissService, data: new @@ -50,10 +40,10 @@ public sealed class PowerNotificationService : IPowerNotificationService 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( CultureInfo.InvariantCulture, diff --git a/PowerMonitor.Manager/PowerSensorDiscoveryService.cs b/PowerMonitor.Manager/PowerSensorDiscoveryService.cs index f3248f2..54e1168 100644 --- a/PowerMonitor.Manager/PowerSensorDiscoveryService.cs +++ b/PowerMonitor.Manager/PowerSensorDiscoveryService.cs @@ -54,8 +54,7 @@ public sealed class PowerSensorDiscoveryService : IPowerSensorDiscoveryService _currentDeviceSensors = powerSensors; - _logger.LogInformation( - "Discovered {Count} power sensors (excluded main meter: {MainMeter}, exclusion patterns: {PatternCount})", + _logger.LogInformation("Discovered {Count} power sensors (excluded main meter: {MainMeter}, exclusion patterns: {PatternCount})", powerSensors.Count, _options.MainMeterEntityId, _exclusionPatterns.Length); return powerSensors; @@ -82,12 +81,12 @@ public sealed class PowerSensorDiscoveryService : IPowerSensorDiscoveryService 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); } - internal bool IsExcluded(string entityId) + private bool IsExcluded(string entityId) { return _exclusionPatterns.Any(pattern => pattern.IsMatch(entityId)); } diff --git a/ShowerMonitor.Manager.Tests/ExhaustFanControlServiceTests.cs b/ShowerMonitor.Manager.Tests/ExhaustFanControlServiceTests.cs index c18f092..b026f49 100644 --- a/ShowerMonitor.Manager.Tests/ExhaustFanControlServiceTests.cs +++ b/ShowerMonitor.Manager.Tests/ExhaustFanControlServiceTests.cs @@ -1,4 +1,3 @@ -using FluentAssertions; using Microsoft.Extensions.Options; using Moq; using NetDaemon.HassModel; diff --git a/ShowerMonitor.Manager/ExhaustFanControlService.cs b/ShowerMonitor.Manager/ExhaustFanControlService.cs index aa9ef87..75740ec 100644 --- a/ShowerMonitor.Manager/ExhaustFanControlService.cs +++ b/ShowerMonitor.Manager/ExhaustFanControlService.cs @@ -49,6 +49,7 @@ public sealed class ExhaustFanControlService( if (_fanTurnedOnByUs) { var fanState = haContext.GetState(_options.ExhaustFanEntityId)?.State; + if (string.Equals(fanState, "on", StringComparison.OrdinalIgnoreCase)) { haContext.CallService("switch", "turn_off", ServiceTarget.FromEntity(_options.ExhaustFanEntityId)); diff --git a/ShowerMonitor.Manager/Interface/IExhaustFanControlService.cs b/ShowerMonitor.Manager/Interface/IExhaustFanControlService.cs index 02c1a1c..6b6195c 100644 --- a/ShowerMonitor.Manager/Interface/IExhaustFanControlService.cs +++ b/ShowerMonitor.Manager/Interface/IExhaustFanControlService.cs @@ -1,4 +1,3 @@ -using NetDaemon.HassModel; using ShowerMonitor.Models.Enums; namespace ShowerMonitorManager.Interface; diff --git a/ShowerMonitor.Manager/Models/ShowerMonitorOptions.cs b/ShowerMonitor.Manager/Models/ShowerMonitorOptions.cs index 3f5295a..21301b9 100644 --- a/ShowerMonitor.Manager/Models/ShowerMonitorOptions.cs +++ b/ShowerMonitor.Manager/Models/ShowerMonitorOptions.cs @@ -6,19 +6,19 @@ public sealed class ShowerMonitorOptions { public const string SectionName = "ShowerMonitor"; - public bool Enabled { get; set; } - public bool CleanupEntitiesOnStartup { get; set; } - public string BathroomHumidityEntityId { get; set; } = ShowerMonitorConsts.BathroomHumidityEntityId; - public string MainHomeHumidityEntityId { get; set; } = ShowerMonitorConsts.MainHomeHumidityEntityId; - public string BathroomTemperatureEntityId { get; set; } = ShowerMonitorConsts.BathroomTemperatureEntityId; - public string ExhaustFanEntityId { get; set; } = ShowerMonitorConsts.ExhaustFanEntityId; - public int PollIntervalSeconds { get; set; } = ShowerMonitorConsts.DefaultPollIntervalSeconds; - public double SpikeRateThreshold { get; set; } = ShowerMonitorConsts.DefaultSpikeRateThreshold; - public double MinDifferentialHumidity { get; set; } = ShowerMonitorConsts.DefaultMinDifferentialHumidity; - public double PeakHumidityThreshold { get; set; } = ShowerMonitorConsts.DefaultPeakHumidityThreshold; - public int ConfirmationWindowMinutes { get; set; } = ShowerMonitorConsts.DefaultConfirmationWindowMinutes; - public double RecoveryDifferentialThreshold { get; set; } = ShowerMonitorConsts.DefaultRecoveryDifferentialThreshold; - public int MaxShowerDurationMinutes { get; set; } = (int)ShowerMonitorConsts.DefaultMaxShowerDuration.TotalMinutes; - public int FanRunAfterShowerMinutes { get; set; } = (int)ShowerMonitorConsts.DefaultFanRunAfterShower.TotalMinutes; - public int RateWindowSize { get; set; } = ShowerMonitorConsts.DefaultRateWindowSize; + public bool Enabled { get; init; } + public bool CleanupEntitiesOnStartup { get; init; } + public string BathroomHumidityEntityId { get; init; } = ShowerMonitorConsts.BathroomHumidityEntityId; + public string MainHomeHumidityEntityId { get; init; } = ShowerMonitorConsts.MainHomeHumidityEntityId; + public string BathroomTemperatureEntityId { get; init; } = ShowerMonitorConsts.BathroomTemperatureEntityId; + public string ExhaustFanEntityId { get; init; } = ShowerMonitorConsts.ExhaustFanEntityId; + public int PollIntervalSeconds { get; init; } = ShowerMonitorConsts.DefaultPollIntervalSeconds; + public double SpikeRateThreshold { get; init; } = ShowerMonitorConsts.DefaultSpikeRateThreshold; + public double MinDifferentialHumidity { get; init; } = ShowerMonitorConsts.DefaultMinDifferentialHumidity; + public double PeakHumidityThreshold { get; init; } = ShowerMonitorConsts.DefaultPeakHumidityThreshold; + public int ConfirmationWindowMinutes { get; init; } = ShowerMonitorConsts.DefaultConfirmationWindowMinutes; + public double RecoveryDifferentialThreshold { get; init; } = ShowerMonitorConsts.DefaultRecoveryDifferentialThreshold; + public int MaxShowerDurationMinutes { get; init; } = (int)ShowerMonitorConsts.DefaultMaxShowerDuration.TotalMinutes; + public int FanRunAfterShowerMinutes { get; init; } = (int)ShowerMonitorConsts.DefaultFanRunAfterShower.TotalMinutes; + public int RateWindowSize { get; init; } = ShowerMonitorConsts.DefaultRateWindowSize; } diff --git a/ShowerMonitor.Manager/ShowerDetectionService.cs b/ShowerMonitor.Manager/ShowerDetectionService.cs index 704e8e6..ce1b44b 100644 --- a/ShowerMonitor.Manager/ShowerDetectionService.cs +++ b/ShowerMonitor.Manager/ShowerDetectionService.cs @@ -151,6 +151,7 @@ public sealed class ShowerDetectionService( if (differential <= _options.RecoveryDifferentialThreshold) { CompleteSession(timestamp); + return ShowerState.Completed; } @@ -159,6 +160,7 @@ public sealed class ShowerDetectionService( if (_currentSession is not null && _currentSession.GetDuration(timestamp) >= maxDuration) { CompleteSession(timestamp); + return ShowerState.Completed; } @@ -173,6 +175,7 @@ public sealed class ShowerDetectionService( private ShowerState TransitionToIdle() { rateCalculator.Reset(); + return ShowerState.Idle; } diff --git a/ShowerMonitor.Manager/ShowerMonitorInit.cs b/ShowerMonitor.Manager/ShowerMonitorInit.cs index 423f4ad..1649ded 100644 --- a/ShowerMonitor.Manager/ShowerMonitorInit.cs +++ b/ShowerMonitor.Manager/ShowerMonitorInit.cs @@ -6,7 +6,6 @@ using NetDaemon.AppModel; using NetDaemon.Extensions.Scheduler; using NetDaemon.HassModel; using NetDaemon.HassModel.Entities; -using ShowerMonitor.Models.Enums; using ShowerMonitorManager.Interface; using ShowerMonitorManager.Models; using static ShowerMonitor.Models.ShowerMonitorConsts; diff --git a/ShowerMonitor.Manager/ShowerMonitorServiceRegistration.cs b/ShowerMonitor.Manager/ShowerMonitorServiceRegistration.cs index 9954afc..aeb4c78 100644 --- a/ShowerMonitor.Manager/ShowerMonitorServiceRegistration.cs +++ b/ShowerMonitor.Manager/ShowerMonitorServiceRegistration.cs @@ -3,7 +3,6 @@ using Microsoft.Extensions.DependencyInjection; using NetDaemon.AppModel; using ShowerMonitorManager.Interface; using ShowerMonitorManager.Models; -using static ShowerMonitor.Models.ShowerMonitorConsts; namespace ShowerMonitorManager;