diff --git a/.cursor/hooks/hooks.json b/.cursor/hooks/hooks.json new file mode 100644 index 0000000..a023c09 --- /dev/null +++ b/.cursor/hooks/hooks.json @@ -0,0 +1,10 @@ +{ + "version": 1, + "hooks": { + "afterShellExecution": [ + { + "command": "powershell -ExecutionPolicy Bypass -File .cursor/hooks/scripts/after-build-validate.ps1" + } + ] + } +} diff --git a/.cursor/hooks/scripts/after-build-validate.ps1 b/.cursor/hooks/scripts/after-build-validate.ps1 new file mode 100644 index 0000000..6c3bc23 --- /dev/null +++ b/.cursor/hooks/scripts/after-build-validate.ps1 @@ -0,0 +1,24 @@ +$input = [Console]::In.ReadToEnd() +$context = $input | ConvertFrom-Json + +$command = $context.command +if (-not $command) { exit 0 } + +$buildPatterns = @('dotnet build', 'dotnet run', 'dotnet publish') +$isBuildCommand = $false + +foreach ($pattern in $buildPatterns) { + if ($command -match [regex]::Escape($pattern)) { + $isBuildCommand = $true + break + } +} + +if (-not $isBuildCommand) { exit 0 } + +$response = @{ + message = "[Live Validation] Build command detected. Run live environment validation using the homeassistant MCP tools: 1) check_api to verify HA is reachable, 2) RunSmokeTest for a full health check, 3) ValidateEntities for the critical entities of the changed service." +} | ConvertTo-Json -Compress + +Write-Output $response +exit 0 diff --git a/.cursor/hooks/state/continual-learning-index.json b/.cursor/hooks/state/continual-learning-index.json new file mode 100644 index 0000000..c3445b5 --- /dev/null +++ b/.cursor/hooks/state/continual-learning-index.json @@ -0,0 +1,8 @@ +{ + "5994a9f8-5bd6-407e-b7e1-88c9a7360592\\5994a9f8-5bd6-407e-b7e1-88c9a7360592.jsonl": "2026-04-14T08:01:31.8660776Z", + "6e38db72-7218-41a2-80da-8091c601738c\\6e38db72-7218-41a2-80da-8091c601738c.jsonl": "2026-04-14T10:19:17.9717677Z", + "84ed688d-ec2b-42ff-b324-7d8a1b0b1e53\\84ed688d-ec2b-42ff-b324-7d8a1b0b1e53.jsonl": "2026-04-17T19:55:06.7428782Z", + "84ed688d-ec2b-42ff-b324-7d8a1b0b1e53\\subagents\\d19fc0d0-4036-49fe-b85c-28f06fb3ed96.jsonl": "2026-04-17T19:55:20.0402239Z", + "947d0c4b-410b-4ca2-b813-2b9abb0b171d\\947d0c4b-410b-4ca2-b813-2b9abb0b171d.jsonl": "2026-04-14T08:23:40.4290937Z", + "a9ef1795-de24-4fe6-937d-1ff01dc8091d\\a9ef1795-de24-4fe6-937d-1ff01dc8091d.jsonl": "2026-04-14T08:48:55.5467377Z" +} diff --git a/.cursor/hooks/state/continual-learning.json b/.cursor/hooks/state/continual-learning.json new file mode 100644 index 0000000..7ca484c --- /dev/null +++ b/.cursor/hooks/state/continual-learning.json @@ -0,0 +1,8 @@ +{ + "version": 1, + "lastRunAtMs": 1776455702656, + "turnsSinceLastRun": 8, + "lastTranscriptMtimeMs": 1776455701006.4348, + "lastProcessedGenerationId": "13996b20-c9b1-41f3-bafc-5738130c07ac", + "trialStartedAtMs": null +} diff --git a/.cursor/rules/caveman-always.mdc b/.cursor/rules/caveman-always.mdc new file mode 100644 index 0000000..374b9cb --- /dev/null +++ b/.cursor/rules/caveman-always.mdc @@ -0,0 +1,23 @@ +--- +description: Auto-enable caveman (ultra-compressed) replies every chat unless user opts out +alwaysApply: true +--- + +# Caveman default (every chat) + +Treat **caveman full** as active for all assistant prose unless user says `stop caveman` or `normal mode`. User may switch with `/caveman lite|full|ultra` (same semantics as caveman skill). + +## Style + +- Drop filler, hedging, pleasantries; fragments OK; technical terms exact; code fences unchanged. +- **lite**: tight professional prose, keep articles. +- **full** (default): drop most articles; short synonyms; terse lines. +- **ultra**: abbrev where clear (e.g. req/res/config), arrows for flow (→), minimal words. + +## Exceptions + +Use normal clarity (not caveman) for: irreversible or destructive ops, security warnings, multi-step instructions where terseness risks misread, or when user explicitly asks for fuller explanation. Resume caveman after that block. + +## Code / commits + +Implementation code, tests, and commit messages: normal quality bar (readable names, complete sentences in commits if repo expects it). Caveman applies mainly to **explanatory chat text**, not to lowering code standards. diff --git a/.cursor/rules/live-validation.mdc b/.cursor/rules/live-validation.mdc new file mode 100644 index 0000000..ae14cc5 --- /dev/null +++ b/.cursor/rules/live-validation.mdc @@ -0,0 +1,46 @@ +--- +description: Require live environment validation after modifying monitor services +globs: + - "BoilerMonitor.Manager/**/*.cs" + - "BoilerMonitor.Models/**/*.cs" + - "LightMonitor.Manager/**/*.cs" + - "LightMonitor.Models/**/*.cs" + - "NordPool.Manager/**/*.cs" + - "NordPool.Models/**/*.cs" + - "PowerMonitor.Manager/**/*.cs" + - "PowerMonitor.Models/**/*.cs" + - "ShowerMonitor.Manager/**/*.cs" + - "ShowerMonitor.Models/**/*.cs" + - "HomeAssistant.McpServer/**/*.cs" +alwaysApply: false +--- + +# Live Validation Required + +After modifying any Monitor service, Manager, or Models code, the agent MUST validate the change works in the live Home Assistant environment before considering the task complete. + +## Mandatory Steps + +1. **Build** — run `dotnet build` on the affected project to confirm compilation. +2. **Smoke test** — use the `RunSmokeTest` MCP tool (from the `homeassistant` MCP server) with domains relevant to the changed service. +3. **Entity check** — use `ValidateEntities` to confirm critical entities for the changed service are not `unavailable` or `unknown`. + +## Domain Mapping + +| Service Changed | MCP Domains to Check | +|---|---| +| BoilerMonitor | `switch,sensor,binary_sensor` | +| LightMonitor | `light,person,sun` | +| NordPool | `sensor` | +| PowerMonitor | `sensor` | +| ShowerMonitor | `sensor,switch` | + +## When to Skip + +- If the Home Assistant instance is offline (check via `check_api` first) +- If changes are purely to unit tests, documentation, or non-runtime code +- If the user explicitly says to skip validation + +## On Failure + +Report the specific entities that failed validation and their current states. Do not silently proceed. diff --git a/.cursor/skills/live-validation/SKILL.md b/.cursor/skills/live-validation/SKILL.md new file mode 100644 index 0000000..1b3ca8c --- /dev/null +++ b/.cursor/skills/live-validation/SKILL.md @@ -0,0 +1,96 @@ +# Live Environment Validation + +Validate that code changes work correctly against the live Home Assistant instance using MCP tools. + +## Triggers + +Use when: +- The user says "validate", "check live", "smoke test", "verify live environment" +- After deploying or restarting the app daemon +- After modifying any Monitor/Manager service and wanting to confirm it works +- When the live-validation rule fires (after editing monitor service files) + +## Prerequisites + +- The Home Assistant instance must be running and reachable +- The `homeassistant` MCP server must be connected in Cursor + +## Validation Workflow + +### Step 1: Build Verification + +Run `dotnet build` for the solution or affected project to confirm compilation succeeds. + +``` +dotnet build HomeAssistantSDK.sln --no-restore +``` + +If the build fails, stop and fix compilation errors before proceeding. + +### Step 2: API Health Check + +Use the `homeassistant` MCP tool `check_api` to verify the HA instance is reachable. + +If the API is unreachable, report the failure and stop — no further validation is possible. + +### Step 3: Smoke Test + +Use the `homeassistant` MCP tool `RunSmokeTest` to run a full environment check: +- Pass the relevant domains based on what was changed +- Check the `overall` field for PASS/FAIL +- Review any unhealthy entities + +Domain mapping for changed services: +- **BoilerMonitor** → `switch,sensor,binary_sensor,number,text` +- **LightMonitor** → `light,person,sun` +- **NordPool** → `sensor` +- **PowerMonitor** → `sensor` +- **ShowerMonitor** → `sensor,switch` + +### Step 4: Entity-Specific Validation + +Based on which service was changed, validate its critical entities using the `ValidateEntities` MCP tool: + +**BoilerMonitor entities:** +- `sensor.boilermonitor_status` +- `sensor.boilermonitor_water_ready` +- `sensor.boilermonitor_estimated_temperature` +- `sensor.boilermonitor_heating_percentage` + +**LightMonitor entities:** +- `light.sonoff_1002214d40` +- `sun.sun` +- `person.marius`, `person.erika` + +**NordPool entities:** +- `sensor.nordpool_current_price` + +**PowerMonitor entities:** +- Power sensor entities configured in the system + +### Step 5: Behavioral Validation (Optional) + +For deeper validation, use the `get_logbook` MCP tool filtered to the relevant entity with a 30-minute window to confirm the service is producing expected state changes. + +Use `get_entity_history` for trend validation — verify values are within expected ranges. + +### Step 6: Report + +Summarize results: +1. Build status (pass/fail) +2. API health (reachable/unreachable) +3. Smoke test result (PASS/FAIL with details) +4. Entity validation results (list any failures) +5. Logbook activity summary (if performed) + +If everything passes, confirm with a brief "Live validation passed" message. +If anything fails, list specific failures with entity IDs and current states. + +## Browser Validation (HistoryReplay UI) + +If the `HomeAssistant.HistoryReplay` Blazor app is running, use the `cursor-ide-browser` MCP to: +1. Navigate to the dashboard URL +2. Take a screenshot to verify charts render correctly +3. Check console for JavaScript errors + +This is optional and only applies when HistoryReplay changes are involved. diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..4589199 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,10 @@ +## Learned User Preferences + +- Default assistant tone: **caveman full** every new chat (see `.cursor/rules/caveman-always.mdc`). Opt out: say `stop caveman` / `normal mode`. +- When giving shell examples or running commands for this repo on Windows, chain with PowerShell using `;` instead of `&&`. + +## Learned Workspace Facts + +- The solution is .NET 10 and targets Home Assistant integration via NetDaemon. +- NetDaemon registers `IHaContext` as scoped; any app service that injects it must be registered scoped or transient, not singleton, or app load fails with “Cannot resolve scoped service … from root provider.” +- Cursor agent transcripts for this workspace are stored under the long project folder `...-homeassistant-app-deamon-homeassistant-app-deamon-code-workspace\agent-transcripts\`; the shorter `...\homeassistant-app-deamon\agent-transcripts` path may be absent. diff --git a/BoilerMonitor.Manager.Tests/BoilerMonitor.Manager.Tests.csproj b/BoilerMonitor.Manager.Tests/BoilerMonitor.Manager.Tests.csproj index 2e9c980..0d09cbf 100644 --- a/BoilerMonitor.Manager.Tests/BoilerMonitor.Manager.Tests.csproj +++ b/BoilerMonitor.Manager.Tests/BoilerMonitor.Manager.Tests.csproj @@ -21,6 +21,9 @@ + + + diff --git a/BoilerMonitor.Manager.Tests/WaterReadyServiceTests.cs b/BoilerMonitor.Manager.Tests/WaterReadyServiceTests.cs index d7401d3..bb4d06e 100644 --- a/BoilerMonitor.Manager.Tests/WaterReadyServiceTests.cs +++ b/BoilerMonitor.Manager.Tests/WaterReadyServiceTests.cs @@ -9,6 +9,9 @@ namespace BoilerMonitor.Manager.Tests; public class WaterReadyServiceTests { + private const double Threshold = BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts; + private const double HighPowerWatts = 2150.0; + private readonly Mock> _loggerMock; private readonly FakeTimeProvider _timeProvider; @@ -18,114 +21,205 @@ public class WaterReadyServiceTests _timeProvider = new FakeTimeProvider(DateTimeOffset.UtcNow); } - private WaterReadyService CreateSut() + private WaterReadyService CreateSut() => new(_loggerMock.Object, _timeProvider); + + private WaterReadyService CreateSutWithHeatingObserved() { - return new WaterReadyService(_loggerMock.Object, _timeProvider); + var sut = CreateSut(); + sut.RecordHeatingObserved(); + return sut; } - #region IsWaterReady — basic behavior (no grace period active) + private static bool TriggerWaterReady(WaterReadyService sut, double powerWatts = 0.0) + { + var result = false; + for (var i = 0; i < BoilerMonitorConsts.ConsecutiveReadingsRequired; i++) + { + result = sut.IsWaterReady("on", powerWatts, Threshold); + } + return result; + } + + #region Heating observation prerequisite [Fact] - public void IsWaterReady_SwitchOnAndLowPower_ShouldReturnTrue() + public void IsWaterReady_SwitchOnLowPowerButNeverObservedHeating_ShouldReturnFalse() { - // Arrange var sut = CreateSut(); - // Act - var result = sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + var result = sut.IsWaterReady("on", 0.0, Threshold); + + result.Should().BeFalse(); + } + + [Fact] + public void IsWaterReady_AfterObservedHeatingAndConsecutiveLowPower_ShouldReturnTrue() + { + var sut = CreateSutWithHeatingObserved(); + + var result = TriggerWaterReady(sut); - // Assert result.Should().BeTrue(); } [Fact] - public void IsWaterReady_SwitchOnAndPowerBelowThreshold_ShouldReturnTrue() + public void RecordHeatingObserved_ShouldEnableDetection() { - // Arrange var sut = CreateSut(); + sut.RecordHeatingObserved(); - // Act - var result = sut.IsWaterReady("on", 4.9, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + var result = TriggerWaterReady(sut); - // Assert result.Should().BeTrue(); } + [Fact] + public void NotifyTurnedOn_ShouldResetHasObservedHeating() + { + var sut = CreateSutWithHeatingObserved(); + sut.NotifyTurnedOn(); + + var result = sut.IsWaterReady("on", 0.0, Threshold); + + result.Should().BeFalse("heating observation was reset by NotifyTurnedOn"); + } + + [Fact] + public void NotifyTurnedOn_ThenObserveHeating_ShouldReEnableDetection() + { + var sut = CreateSutWithHeatingObserved(); + sut.NotifyTurnedOn(); + sut.RecordHeatingObserved(); + + var result = TriggerWaterReady(sut); + + result.Should().BeTrue(); + } + + [Fact] + public void IsWaterReady_AfterResetAndReObservedHeating_ShouldTriggerAgain() + { + var sut = CreateSutWithHeatingObserved(); + TriggerWaterReady(sut); + sut.ResetCooldown(); + + sut.RecordHeatingObserved(); + var result = TriggerWaterReady(sut); + + result.Should().BeTrue("detection should work again after reset + new heating observation"); + } + + #endregion + + #region Debouncing (consecutive readings) + + [Fact] + public void IsWaterReady_SingleBelowThresholdReading_ShouldReturnFalse() + { + var sut = CreateSutWithHeatingObserved(); + + var result = sut.IsWaterReady("on", 0.0, Threshold); + + result.Should().BeFalse("only 1 consecutive reading, need {0}", + BoilerMonitorConsts.ConsecutiveReadingsRequired); + } + + [Fact] + public void IsWaterReady_ConsecutiveBelowThresholdReadings_ShouldReturnTrue() + { + var sut = CreateSutWithHeatingObserved(); + + var result = TriggerWaterReady(sut); + + result.Should().BeTrue(); + } + + [Fact] + public void IsWaterReady_BelowThresholdResetByAboveThreshold_ShouldRequireConsecutiveAgain() + { + var sut = CreateSutWithHeatingObserved(); + + sut.IsWaterReady("on", 0.0, Threshold); + sut.IsWaterReady("on", HighPowerWatts, Threshold); + var result = sut.IsWaterReady("on", 0.0, Threshold); + + result.Should().BeFalse("counter was reset by above-threshold reading"); + } + + [Fact] + public void IsWaterReady_NotifyTurnedOn_ShouldResetConsecutiveCount() + { + var sut = CreateSutWithHeatingObserved(); + + sut.IsWaterReady("on", 0.0, Threshold); + sut.NotifyTurnedOn(); + sut.RecordHeatingObserved(); + var result = sut.IsWaterReady("on", 0.0, Threshold); + + result.Should().BeFalse("NotifyTurnedOn reset the consecutive counter"); + } + + #endregion + + #region Basic state checks + [Fact] public void IsWaterReady_SwitchOnAndPowerAtThreshold_ShouldReturnFalse() { - // Arrange - var sut = CreateSut(); + var sut = CreateSutWithHeatingObserved(); - // Act - var result = sut.IsWaterReady("on", 5.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + var result = sut.IsWaterReady("on", Threshold, Threshold); - // Assert result.Should().BeFalse(); } [Fact] public void IsWaterReady_SwitchOnAndHighPower_ShouldReturnFalse() { - // Arrange - var sut = CreateSut(); + var sut = CreateSutWithHeatingObserved(); - // Act - var result = sut.IsWaterReady("on", 2150.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + var result = sut.IsWaterReady("on", HighPowerWatts, Threshold); - // Assert result.Should().BeFalse(); } [Fact] public void IsWaterReady_SwitchOff_ShouldReturnFalse() { - // Arrange - var sut = CreateSut(); + var sut = CreateSutWithHeatingObserved(); - // Act - var result = sut.IsWaterReady("off", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + var result = sut.IsWaterReady("off", 0.0, Threshold); - // Assert result.Should().BeFalse(); } [Fact] public void IsWaterReady_NullSwitchState_ShouldReturnFalse() { - // Arrange - var sut = CreateSut(); + var sut = CreateSutWithHeatingObserved(); - // Act - var result = sut.IsWaterReady(null, 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + var result = sut.IsWaterReady(null, 0.0, Threshold); - // Assert result.Should().BeFalse(); } [Fact] public void IsWaterReady_NullPowerWatts_ShouldReturnFalse() { - // Arrange - var sut = CreateSut(); + var sut = CreateSutWithHeatingObserved(); - // Act - var result = sut.IsWaterReady("on", null, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + var result = sut.IsWaterReady("on", null, Threshold); - // Assert result.Should().BeFalse(); } [Fact] public void IsWaterReady_BothNull_ShouldReturnFalse() { - // Arrange var sut = CreateSut(); - // Act - var result = sut.IsWaterReady(null, null, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + var result = sut.IsWaterReady(null, null, Threshold); - // Assert result.Should().BeFalse(); } @@ -135,13 +229,14 @@ public class WaterReadyServiceTests [InlineData("on")] public void IsWaterReady_SwitchOnCaseInsensitive_ShouldReturnTrue(string switchState) { - // Arrange - var sut = CreateSut(); + var sut = CreateSutWithHeatingObserved(); - // Act - var result = sut.IsWaterReady(switchState, 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + var result = false; + for (var i = 0; i < BoilerMonitorConsts.ConsecutiveReadingsRequired; i++) + { + result = sut.IsWaterReady(switchState, 0.0, Threshold); + } - // Assert result.Should().BeTrue(); } @@ -151,279 +246,265 @@ public class WaterReadyServiceTests [InlineData(10.1, 10.0, false)] public void IsWaterReady_CustomThreshold_ShouldUseProvidedValue(double powerWatts, double threshold, bool expected) { - // Arrange — fresh instance per case to avoid cooldown side-effects - var sut = CreateSut(); + var sut = CreateSutWithHeatingObserved(); - // Act - var result = sut.IsWaterReady("on", powerWatts, threshold); + var result = false; + for (var i = 0; i < BoilerMonitorConsts.ConsecutiveReadingsRequired; i++) + { + result = sut.IsWaterReady("on", powerWatts, threshold); + } - // Assert result.Should().Be(expected); } #endregion - #region Warm-up grace period - - [Fact] - public void IsWaterReady_DuringGracePeriod_ShouldReturnFalse() - { - // Arrange - var sut = CreateSut(); - sut.NotifyTurnedOn(); - - // Act — still within grace period, low power should be suppressed - var result = sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); - - // Assert - result.Should().BeFalse(); - } - - [Fact] - public void IsWaterReady_AfterGracePeriodExpires_ShouldReturnTrue() - { - // Arrange - var sut = CreateSut(); - sut.NotifyTurnedOn(); - _timeProvider.Advance(BoilerMonitorConsts.WarmUpGracePeriod); - - // Act — grace period has elapsed, low power means water is ready - var result = sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); - - // Assert - result.Should().BeTrue(); - } - - [Fact] - public void IsWaterReady_DuringGracePeriodWithHighPower_ShouldReturnFalse() - { - // Arrange - var sut = CreateSut(); - sut.NotifyTurnedOn(); - - // Act — high power during grace period is still "not ready" (heating) - var result = sut.IsWaterReady("on", 2150.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); - - // Assert - result.Should().BeFalse(); - } - - [Fact] - public void IsWaterReady_JustBeforeGracePeriodExpires_ShouldReturnFalse() - { - // Arrange - var sut = CreateSut(); - sut.NotifyTurnedOn(); - _timeProvider.Advance(BoilerMonitorConsts.WarmUpGracePeriod - TimeSpan.FromSeconds(1)); - - // Act - var result = sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); - - // Assert - result.Should().BeFalse(); - } - - [Fact] - public void IsWaterReady_WithoutNotifyTurnedOn_ShouldNotApplyGracePeriod() - { - // Arrange — no NotifyTurnedOn call, so no grace period should be active - var sut = CreateSut(); - - // Act - var result = sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); - - // Assert - result.Should().BeTrue(); - } - - [Fact] - public void IsWaterReady_MultipleTurnOns_ShouldResetGracePeriod() - { - // Arrange - var sut = CreateSut(); - sut.NotifyTurnedOn(); - _timeProvider.Advance(BoilerMonitorConsts.WarmUpGracePeriod - TimeSpan.FromSeconds(10)); - - // Act — second turn-on resets the grace period - sut.NotifyTurnedOn(); - _timeProvider.Advance(TimeSpan.FromSeconds(10)); - - var result = sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); - - // Assert — still within the new grace period - result.Should().BeFalse(); - } - - [Fact] - public void IsWaterReady_SwitchOffDuringGracePeriod_ShouldReturnFalse() - { - // Arrange - var sut = CreateSut(); - sut.NotifyTurnedOn(); - - // Act — switch is off, so not ready regardless of grace period - var result = sut.IsWaterReady("off", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); - - // Assert - result.Should().BeFalse(); - } - - #endregion - - #region Water ready cooldown period + #region Cooldown period [Fact] public void IsWaterReady_DuringCooldown_ShouldReturnTrueRegardlessOfSwitchState() { - // Arrange — trigger water ready detection, then turn switch off - var sut = CreateSut(); - sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + var sut = CreateSutWithHeatingObserved(); + TriggerWaterReady(sut); - // Act — switch is now off, but cooldown should keep reporting ready - var result = sut.IsWaterReady("off", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + var result = sut.IsWaterReady("off", 0.0, Threshold); - // Assert result.Should().BeTrue(); } [Fact] public void IsWaterReady_DuringCooldown_ShouldReturnTrueEvenWithNullState() { - // Arrange - var sut = CreateSut(); - sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + var sut = CreateSutWithHeatingObserved(); + TriggerWaterReady(sut); - // Act - var result = sut.IsWaterReady(null, null, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + var result = sut.IsWaterReady(null, null, Threshold); - // Assert result.Should().BeTrue(); } [Fact] - public void IsWaterReady_AfterCooldownExpires_ShouldResumeNormalDetection() + public void IsWaterReady_CooldownDoesNotExpireByTime_ShouldStayActiveAfterHours() { - // Arrange - var sut = CreateSut(); - sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); - _timeProvider.Advance(BoilerMonitorConsts.WaterReadyCooldownPeriod); + var sut = CreateSutWithHeatingObserved(); + TriggerWaterReady(sut); + _timeProvider.Advance(TimeSpan.FromHours(12)); - // Act — cooldown expired, switch is off → not ready - var result = sut.IsWaterReady("off", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + var result = sut.IsWaterReady("off", 0.0, Threshold); - // Assert - result.Should().BeFalse(); + result.Should().BeTrue("cooldown only clears via explicit ResetCooldown, not by elapsed time"); } [Fact] - public void IsWaterReady_JustBeforeCooldownExpires_ShouldStillReturnTrue() + public void IsWaterReady_CooldownClearedOnlyByExplicitReset_ShouldResumeAfterReset() { - // Arrange - var sut = CreateSut(); - sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); - _timeProvider.Advance(BoilerMonitorConsts.WaterReadyCooldownPeriod - TimeSpan.FromSeconds(1)); + var sut = CreateSutWithHeatingObserved(); + TriggerWaterReady(sut); + _timeProvider.Advance(TimeSpan.FromHours(5)); + sut.IsInCooldown.Should().BeTrue(); - // Act - var result = sut.IsWaterReady("off", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + sut.ResetCooldown(); - // Assert - result.Should().BeTrue(); + sut.IsWaterReady("off", 0.0, Threshold).Should().BeFalse(); } [Fact] public void IsInCooldown_WhenCooldownActive_ShouldReturnTrue() { - // Arrange - var sut = CreateSut(); - sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + var sut = CreateSutWithHeatingObserved(); + TriggerWaterReady(sut); - // Act & Assert sut.IsInCooldown.Should().BeTrue(); } [Fact] public void IsInCooldown_WhenNoCooldownTriggered_ShouldReturnFalse() { - // Arrange var sut = CreateSut(); - // Act & Assert sut.IsInCooldown.Should().BeFalse(); } [Fact] - public void IsInCooldown_AfterCooldownExpires_ShouldReturnFalse() + public void IsInCooldown_DoesNotExpireByTime_ShouldRemainTrueAfterHours() { - // Arrange - var sut = CreateSut(); - sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); - _timeProvider.Advance(BoilerMonitorConsts.WaterReadyCooldownPeriod); + var sut = CreateSutWithHeatingObserved(); + TriggerWaterReady(sut); + _timeProvider.Advance(TimeSpan.FromHours(8)); - // Act & Assert - sut.IsInCooldown.Should().BeFalse(); + sut.IsInCooldown.Should().BeTrue(); } [Fact] public void ResetCooldown_ShouldClearActiveCooldown() { - // Arrange - var sut = CreateSut(); - sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + var sut = CreateSutWithHeatingObserved(); + TriggerWaterReady(sut); sut.IsInCooldown.Should().BeTrue(); - // Act sut.ResetCooldown(); - // Assert sut.IsInCooldown.Should().BeFalse(); } [Fact] - public void ResetCooldown_ShouldAllowBoilerToTurnOnAgain() + public void ResetCooldown_ShouldAllowNormalDetectionToResume() { - // Arrange — water becomes ready, then cooldown is reset (midnight) - var sut = CreateSut(); - sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + var sut = CreateSutWithHeatingObserved(); + TriggerWaterReady(sut); sut.ResetCooldown(); - // Act — switch is off, no power → not ready (normal detection resumes) - var result = sut.IsWaterReady("off", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + var result = sut.IsWaterReady("off", 0.0, Threshold); - // Assert result.Should().BeFalse(); } [Fact] public void IsWaterReady_CooldownOnlySetOnFirstDetection_ShouldNotResetTimestamp() { - // Arrange — first detection sets _waterReadySince - var sut = CreateSut(); - sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + var sut = CreateSutWithHeatingObserved(); + TriggerWaterReady(sut); + var originalTimestamp = sut.WaterReadySince; - // Advance halfway through cooldown - _timeProvider.Advance(BoilerMonitorConsts.WaterReadyCooldownPeriod / 2); + _timeProvider.Advance(TimeSpan.FromHours(2)); + sut.IsWaterReady("on", 0.0, Threshold); - // Act — second detection during cooldown should NOT reset the timestamp - sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); - - // Advance remaining half - _timeProvider.Advance(BoilerMonitorConsts.WaterReadyCooldownPeriod / 2); - - // Assert — cooldown should have expired based on original timestamp - sut.IsInCooldown.Should().BeFalse(); + sut.WaterReadySince.Should().Be(originalTimestamp); } [Fact] public void IsWaterReady_HighPowerDoesNotTriggerCooldown_ShouldReturnFalse() { - // Arrange + var sut = CreateSutWithHeatingObserved(); + + sut.IsWaterReady("on", HighPowerWatts, Threshold); + + sut.IsInCooldown.Should().BeFalse(); + } + + [Fact] + public void NotifyTurnedOn_DuringActiveCooldown_ShouldNotClearCooldown() + { + var sut = CreateSutWithHeatingObserved(); + TriggerWaterReady(sut); + + sut.NotifyTurnedOn(); + + sut.IsInCooldown.Should().BeTrue("NotifyTurnedOn must not clear the cooldown"); + } + + #endregion + + #region Cooldown persistence + + [Fact] + public void RestoreCooldownState_ShouldResumeActiveCooldown() + { + var sut = CreateSut(); + var cooldownStart = _timeProvider.GetUtcNow() - TimeSpan.FromMinutes(30); + + sut.RestoreCooldownState(cooldownStart); + + sut.IsInCooldown.Should().BeTrue(); + sut.IsWaterReady("off", 0.0, Threshold).Should().BeTrue(); + } + + [Fact] + public void RestoreCooldownState_WithYesterdayTimestamp_ShouldNotActivateCooldown() + { + var sut = CreateSut(); + var yesterday = _timeProvider.GetUtcNow().AddDays(-1); + + sut.RestoreCooldownState(yesterday); + + sut.IsInCooldown.Should().BeFalse(); + } + + [Fact] + public void RestoreCooldownState_WithTodayTimestamp_ShouldRestoreCooldown() + { + var sut = CreateSut(); + var earlierToday = _timeProvider.GetUtcNow() - TimeSpan.FromHours(5); + + sut.RestoreCooldownState(earlierToday); + + sut.IsInCooldown.Should().BeTrue(); + } + + [Fact] + public void RestoreCooldownState_WithExactlyMidnightTimestamp_ShouldRestoreCooldown() + { + var sut = CreateSut(); + var todayMidnight = new DateTimeOffset(_timeProvider.GetUtcNow().Date, TimeSpan.Zero); + + sut.RestoreCooldownState(todayMidnight); + + sut.IsInCooldown.Should().BeTrue("timestamp at today's midnight is not before today"); + } + + [Fact] + public void RestoreCooldownState_ShouldPreserveOriginalTimestamp() + { + var sut = CreateSut(); + var cooldownStart = _timeProvider.GetUtcNow() - TimeSpan.FromMinutes(30); + + sut.RestoreCooldownState(cooldownStart); + + sut.WaterReadySince.Should().Be(cooldownStart); + } + + [Fact] + public void WaterReadySince_ShouldReturnTimestampWhenCooldownActive() + { + var sut = CreateSutWithHeatingObserved(); + var beforeTrigger = _timeProvider.GetUtcNow(); + + TriggerWaterReady(sut); + + sut.WaterReadySince.Should().Be(beforeTrigger); + } + + [Fact] + public void WaterReadySince_ShouldReturnNullWhenNoCooldown() + { var sut = CreateSut(); - // Act — water is not ready (high power), no cooldown should be triggered - sut.IsWaterReady("on", 2150.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts); + sut.WaterReadySince.Should().BeNull(); + } - // Assert - sut.IsInCooldown.Should().BeFalse(); + #endregion + + #region False positive scenario (the bug this fix addresses) + + [Fact] + public void IsWaterReady_BoilerJustTurnedOnPowerStillZero_ShouldNotTriggerFalsePositive() + { + var sut = CreateSut(); + sut.NotifyTurnedOn(); + + for (var i = 0; i < 10; i++) + { + var result = sut.IsWaterReady("on", 0.0, Threshold); + result.Should().BeFalse("boiler was never observed heating — this is a ramp-up delay, not 'water ready'"); + } + } + + [Fact] + public void IsWaterReady_FullHeatingCycle_ShouldDetectWaterReadyCorrectly() + { + var sut = CreateSut(); + sut.NotifyTurnedOn(); + + sut.IsWaterReady("on", 0.0, Threshold).Should().BeFalse("ramp-up, no heating observed yet"); + + sut.RecordHeatingObserved(); + sut.IsWaterReady("on", HighPowerWatts, Threshold).Should().BeFalse("actively heating"); + sut.IsWaterReady("on", HighPowerWatts - 50, Threshold).Should().BeFalse("still heating"); + + sut.IsWaterReady("on", 0.0, Threshold).Should().BeFalse("first below-threshold reading, needs confirmation"); + sut.IsWaterReady("on", 0.0, Threshold).Should().BeTrue("second consecutive below-threshold → water ready"); + + sut.IsInCooldown.Should().BeTrue(); } #endregion diff --git a/BoilerMonitor.Manager/BoilerControlService.cs b/BoilerMonitor.Manager/BoilerControlService.cs index 52bf7c6..152c58d 100644 --- a/BoilerMonitor.Manager/BoilerControlService.cs +++ b/BoilerMonitor.Manager/BoilerControlService.cs @@ -8,7 +8,12 @@ public class BoilerControlService(ILogger logger) : IBoile { private const string SwitchOnState = "on"; - public BoilerAction DetermineAction(bool isNowCheap, bool waterReady, string? currentSwitchState, bool budgetExhausted, bool budgetOverride) + public BoilerAction DetermineAction( + bool isNowCheap, + bool waterReady, + string? currentSwitchState, + bool budgetExhausted, + bool budgetOverride) { var isCurrentlyOn = string.Equals(currentSwitchState, SwitchOnState, StringComparison.OrdinalIgnoreCase); var effectiveBudgetExhausted = budgetExhausted && !budgetOverride; @@ -16,7 +21,9 @@ public class BoilerControlService(ILogger logger) : IBoile 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; } @@ -30,8 +37,12 @@ public class BoilerControlService(ILogger logger) : IBoile 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/BoilerMonitor.Manager.csproj b/BoilerMonitor.Manager/BoilerMonitor.Manager.csproj index ea89ee3..d347f01 100644 --- a/BoilerMonitor.Manager/BoilerMonitor.Manager.csproj +++ b/BoilerMonitor.Manager/BoilerMonitor.Manager.csproj @@ -21,6 +21,7 @@ + diff --git a/BoilerMonitor.Manager/BoilerMonitorEntityService.cs b/BoilerMonitor.Manager/BoilerMonitorEntityService.cs index 97f2590..3261d0b 100644 --- a/BoilerMonitor.Manager/BoilerMonitorEntityService.cs +++ b/BoilerMonitor.Manager/BoilerMonitorEntityService.cs @@ -29,7 +29,8 @@ public sealed class BoilerMonitorEntityService( BudgetPercentageEntityId, BudgetExhaustedEntityId, SessionCountEntityId, - BudgetOverrideEntityId + BudgetOverrideEntityId, + AutoManagementEntityId ]; private static object CreateDeviceBlock() => new @@ -77,7 +78,8 @@ public sealed class BoilerMonitorEntityService( ResetBudgetPercentageAsync(), ResetBudgetExhaustedAsync(), ResetSessionCountAsync(), - ResetBudgetOverrideAsync() + ResetBudgetOverrideAsync(), + ResetAutoManagementAsync() ).ConfigureAwait(false); logger.LogInformation("All BoilerMonitor runtime entity states reset to defaults"); @@ -280,6 +282,10 @@ public sealed class BoilerMonitorEntityService( new BoilerMonitorEntity("switch", "boilermonitor_budget_override", "Override budget enforcement") { AdditionalConfig = new { optimistic = true, icon = "mdi:shield-off-outline", device } + }, + new BoilerMonitorEntity("switch", "boilermonitor_auto_management", "Automatic boiler control") + { + AdditionalConfig = new { optimistic = true, icon = "mdi:robot-outline", device } } ]; } @@ -366,6 +372,11 @@ public sealed class BoilerMonitorEntityService( await SetEntityStateSafe(BudgetOverrideEntityId, "OFF").ConfigureAwait(false); } + private async Task ResetAutoManagementAsync() + { + await SetEntityStateSafe(AutoManagementEntityId, "ON").ConfigureAwait(false); + } + private async Task UpdateWaterReadyAsync(BoilerMonitorUpdateContext ctx, string timestamp) { await SetEntityStateSafe(WaterReadyEntityId, ctx.WaterReady ? "yes" : "no").ConfigureAwait(false); @@ -373,6 +384,7 @@ public sealed class BoilerMonitorEntityService( { boiler_switch_state = ctx.BoilerSwitchState ?? "unknown", boiler_power_watts = ctx.BoilerPowerWatts, + cooldown_since = ctx.CooldownSince?.ToString("O"), friendly_name = "Boiler water ready", last_updated = timestamp }).ConfigureAwait(false); @@ -429,6 +441,45 @@ public sealed class BoilerMonitorEntityService( }).ConfigureAwait(false); } + public DateTimeOffset? ReadPersistedCooldownTimestamp() + { + try + { + var entity = haContext.GetState(WaterReadyEntityId); + if (entity?.Attributes is not IDictionary attributes) + { + return null; + } + + if (!attributes.TryGetValue("cooldown_since", out var value)) + { + return null; + } + + var stringValue = value switch + { + string s => s, + System.Text.Json.JsonElement { ValueKind: System.Text.Json.JsonValueKind.String } jsonElement => + jsonElement.GetString(), + _ => null + }; + + if (stringValue is not null && + DateTimeOffset.TryParse(stringValue, CultureInfo.InvariantCulture, + DateTimeStyles.RoundtripKind, out var parsed)) + { + logger.LogInformation("Read persisted cooldown timestamp: {CooldownSince}", parsed); + return parsed; + } + } + catch (Exception ex) + { + logger.LogError(ex, "Error reading persisted cooldown timestamp"); + } + + return null; + } + private async Task SetEntityStateSafe(string entityId, string state) { try diff --git a/BoilerMonitor.Manager/BoilerMonitorInit.cs b/BoilerMonitor.Manager/BoilerMonitorInit.cs index ee857ee..3bf7f32 100644 --- a/BoilerMonitor.Manager/BoilerMonitorInit.cs +++ b/BoilerMonitor.Manager/BoilerMonitorInit.cs @@ -1,5 +1,7 @@ using System.Globalization; using System.Reactive.Concurrency; +using System.Text.Json; +using BoilerMonitor.Models; using BoilerMonitor.Models.Enums; using BoilerMonitorManager.Interface; using BoilerMonitorManager.Models; @@ -27,8 +29,10 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit private readonly IWaterReadyService _waterReadyService; private readonly BoilerMonitorOptions _options; + private readonly TimeProvider _timeProvider; private bool _lastWaterReady; private bool _cleanedUp; + private DateTimeOffset? _lastWaterReadyNotificationSentAt; public BoilerMonitorInit( IHaContext haContext, @@ -39,7 +43,35 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit IBoilerRunTimeTracker tracker, IBoilerMonitorEntityService entityService, IWaterReadyService waterReadyService, - IOptions options) + IOptions options, + TimeProvider timeProvider) + : this( + haContext, + logger, + scheduler, + mqttEntityManager, + boilerControlService, + tracker, + entityService, + waterReadyService, + options, + timeProvider, + startBackgroundScheduling: true) + { + } + + internal BoilerMonitorInit( + IHaContext haContext, + ILogger logger, + IScheduler scheduler, + IMqttEntityManager mqttEntityManager, + IBoilerControlService boilerControlService, + IBoilerRunTimeTracker tracker, + IBoilerMonitorEntityService entityService, + IWaterReadyService waterReadyService, + IOptions options, + TimeProvider timeProvider, + bool startBackgroundScheduling) { _haContext = haContext; _logger = logger; @@ -50,8 +82,12 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit _entityService = entityService; _waterReadyService = waterReadyService; _options = options.Value; + _timeProvider = timeProvider; - _ = InitializeAndScheduleAsync(); + if (startBackgroundScheduling) + { + _ = InitializeAndScheduleAsync(); + } } private async Task InitializeAndScheduleAsync() @@ -65,6 +101,8 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit ScheduleMidnightReset(); ScheduleEndOfDayReminder(); SubscribeToSkipPriceCapChanges(); + SubscribeToAutoManagementChanges(); + SubscribeToShowerState(); SubscribeToCleanupButton(); } catch (Exception ex) @@ -88,11 +126,19 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit else { var persisted = _entityService.ReadPersistedState(); + var persistedCooldown = _entityService.ReadPersistedCooldownTimestamp(); + await _entityService.CreateEntitiesAsync(); if (persisted is not null) { _tracker.RestoreFromSnapshot(persisted.AccumulatedRunTime, persisted.SessionCount); + + if (persistedCooldown.HasValue) + { + _waterReadyService.RestoreCooldownState(persistedCooldown.Value); + } + await _entityService.ResetTransientEntitiesAsync(); _logger.LogInformation("BoilerMonitor state restored from HA entities: runtime={Runtime}, sessions={Sessions}", persisted.AccumulatedRunTime, persisted.SessionCount); @@ -100,7 +146,7 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit else { await _entityService.ResetEntitiesAsync(); - _logger.LogInformation("No persisted state found, performing full entity reset"); + _logger.LogInformation("No persisted state found in HA entities, performing full entity reset"); } } @@ -154,6 +200,7 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit _logger.LogInformation("Midnight reset: clearing boiler run time tracker and water ready cooldown"); _tracker.Reset(); _waterReadyService.ResetCooldown(); + _lastWaterReadyNotificationSentAt = null; _ = _entityService.ResetEntitiesAsync(); } catch (Exception ex) @@ -203,6 +250,43 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit }); } + private void SubscribeToAutoManagementChanges() + { + var autoManagementSwitch = new Entity(_haContext, AutoManagementEntityId); + autoManagementSwitch.StateChanges() + .Subscribe(e => + { + if (e.Old?.State == e.New?.State) + { + return; + } + + _logger.LogInformation("Automatic boiler control switch changed, triggering poll"); + _ = PollAndUpdateAsync(); + }); + } + + private void SubscribeToShowerState() + { + var showerStateSensor = new Entity(_haContext, ShowerStateEntityId); + showerStateSensor.StateChanges() + .Subscribe(e => + { + if (!string.Equals(e.New?.State, ShowerActiveState, StringComparison.OrdinalIgnoreCase)) + { + return; + } + + if (!_waterReadyService.IsInCooldown) + { + return; + } + + _logger.LogInformation("Shower detected as active, resetting water ready cooldown"); + _waterReadyService.ResetCooldown(); + }); + } + private void SubscribeToCleanupButton() { var cleanupButton = new Entity(_haContext, CleanupButtonEntityId); @@ -247,7 +331,8 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit var switchEntityIds = new[] { SkipPriceCapEntityId, - BudgetOverrideEntityId + BudgetOverrideEntityId, + AutoManagementEntityId }; foreach (var entityId in switchEntityIds) @@ -312,6 +397,11 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit _tracker.RecordPollResult(isHeating, pollInterval); + if (isHeating) + { + _waterReadyService.RecordHeatingObserved(); + } + var cheapestIntervalsState = _haContext.GetState(NordPoolCheapestIntervalsEntityId); var isNowCheap = ReadAttributeBool(cheapestIntervalsState, "is_now_cheap"); var nextCheapInterval = ReadAttributeDateTime(cheapestIntervalsState, "next_cheap_interval"); @@ -326,13 +416,14 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit var waterReady = _waterReadyService.IsWaterReady(boilerSwitchState, boilerPowerWatts, config.HeatingPowerThresholdWatts!.Value); - if (!_lastWaterReady && waterReady) + if (!_lastWaterReady && waterReady && !IsWithinNotificationCooldown()) { _haContext.CallService("notify", "mobile_app_marius_phone", null, new { message = "Hot water is ready.", title = "Boiler" }); + _lastWaterReadyNotificationSentAt = _timeProvider.GetUtcNow(); _logger.LogInformation("Water ready notification sent"); } _lastWaterReady = waterReady; @@ -354,9 +445,26 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit var effectiveIsNowCheap = isNowCheap || skipPriceCap; - var boilerAction = _boilerControlService.DetermineAction(effectiveIsNowCheap, waterReady, boilerSwitchState, budgetExhausted, budgetOverride); + var boilerAction = _boilerControlService.DetermineAction( + effectiveIsNowCheap, + waterReady, + boilerSwitchState, + budgetExhausted, + budgetOverride); - ExecuteBoilerAction(boilerAction, config.BoilerSwitchEntityId!); + var autoManagementState = _haContext.GetState(AutoManagementEntityId)?.State; + var autoManagementEnabled = !string.Equals(autoManagementState, SwitchOffState, StringComparison.OrdinalIgnoreCase); + + if (autoManagementEnabled) + { + ExecuteBoilerAction(boilerAction, config.BoilerSwitchEntityId!); + } + else if (boilerAction is not BoilerAction.NoChange) + { + _logger.LogInformation( + "Automatic boiler control is off; skipping boiler switch service call (would have been {Action})", + boilerAction); + } var context = new BoilerMonitorUpdateContext { @@ -370,6 +478,7 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit WaterReady = waterReady, BoilerSwitchState = boilerSwitchState, BoilerPowerWatts = boilerPowerWatts, + CooldownSince = _waterReadyService.WaterReadySince, IsNowCheap = effectiveIsNowCheap, NextCheapIntervalStart = nextCheapInterval }; @@ -464,6 +573,10 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit { bool b => b, string s => bool.TryParse(s, out var parsed) && parsed, + JsonElement { ValueKind: JsonValueKind.True } => true, + JsonElement { ValueKind: JsonValueKind.False } => false, + JsonElement jsonElement when jsonElement.ValueKind == JsonValueKind.String => + bool.TryParse(jsonElement.GetString(), out var jsonParsed) && jsonParsed, _ => false }; } @@ -476,6 +589,17 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit return false; } + private bool IsWithinNotificationCooldown() + { + if (_lastWaterReadyNotificationSentAt is null) + { + return false; + } + + var elapsed = _timeProvider.GetUtcNow() - _lastWaterReadyNotificationSentAt.Value; + return elapsed < WaterReadyNotificationCooldown; + } + private static DateTime? ReadAttributeDateTime(EntityState? entityState, string attributeName) { if (entityState?.Attributes is null) @@ -487,7 +611,14 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit { if (entityState.Attributes is IDictionary attributes && attributes.TryGetValue(attributeName, out var value)) { - if (value is string s && DateTime.TryParse(s, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var parsed)) + var stringValue = value switch + { + string s => s, + JsonElement { ValueKind: JsonValueKind.String } jsonElement => jsonElement.GetString(), + _ => null + }; + + if (stringValue is not null && DateTime.TryParse(stringValue, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var parsed)) { return parsed; } diff --git a/BoilerMonitor.Manager/BoilerMonitorServiceRegistration.cs b/BoilerMonitor.Manager/BoilerMonitorServiceRegistration.cs index c3c3365..9a63d28 100644 --- a/BoilerMonitor.Manager/BoilerMonitorServiceRegistration.cs +++ b/BoilerMonitor.Manager/BoilerMonitorServiceRegistration.cs @@ -15,6 +15,10 @@ public static class BoilerMonitorServiceRegistration .GetSection(BoilerMonitorOptions.SectionName) .Get() ?? new BoilerMonitorOptions(); + // Always register: NordPool and other features resolve boiler tuning from HA entity state + // even when the BoilerMonitor app itself is disabled. + services.AddScoped(); + if (!options.Enabled) { return services; @@ -26,8 +30,7 @@ public static class BoilerMonitorServiceRegistration .AddSingleton() .AddTransient() .AddSingleton() - .AddSingleton(TimeProvider.System) - .AddScoped(); + .AddSingleton(TimeProvider.System); return services; } diff --git a/BoilerMonitor.Manager/Interface/IBoilerControlService.cs b/BoilerMonitor.Manager/Interface/IBoilerControlService.cs index 3d08e0c..e8c5e2a 100644 --- a/BoilerMonitor.Manager/Interface/IBoilerControlService.cs +++ b/BoilerMonitor.Manager/Interface/IBoilerControlService.cs @@ -4,5 +4,10 @@ namespace BoilerMonitorManager.Interface; public interface IBoilerControlService { - BoilerAction DetermineAction(bool isNowCheap, bool waterReady, string? currentSwitchState, bool budgetExhausted, bool budgetOverride); + BoilerAction DetermineAction( + bool isNowCheap, + bool waterReady, + string? currentSwitchState, + bool budgetExhausted, + bool budgetOverride); } diff --git a/BoilerMonitor.Manager/Interface/IBoilerMonitorEntityService.cs b/BoilerMonitor.Manager/Interface/IBoilerMonitorEntityService.cs index 9c6931b..f269d60 100644 --- a/BoilerMonitor.Manager/Interface/IBoilerMonitorEntityService.cs +++ b/BoilerMonitor.Manager/Interface/IBoilerMonitorEntityService.cs @@ -1,3 +1,4 @@ +using BoilerMonitor.Models; using BoilerMonitorManager.Models; namespace BoilerMonitorManager.Interface; @@ -11,4 +12,5 @@ public interface IBoilerMonitorEntityService Task CleanupEntitiesAsync(CancellationToken cancellationToken = default); Task SetStatusAsync(string status); PersistedBoilerState? ReadPersistedState(); + DateTimeOffset? ReadPersistedCooldownTimestamp(); } diff --git a/BoilerMonitor.Manager/Interface/IWaterReadyService.cs b/BoilerMonitor.Manager/Interface/IWaterReadyService.cs index c2881e4..11f93ed 100644 --- a/BoilerMonitor.Manager/Interface/IWaterReadyService.cs +++ b/BoilerMonitor.Manager/Interface/IWaterReadyService.cs @@ -4,6 +4,9 @@ public interface IWaterReadyService { bool IsWaterReady(string? switchState, double? powerWatts, double heatingThresholdWatts); bool IsInCooldown { get; } + DateTimeOffset? WaterReadySince { get; } void NotifyTurnedOn(); + void RecordHeatingObserved(); void ResetCooldown(); + void RestoreCooldownState(DateTimeOffset waterReadySince); } diff --git a/BoilerMonitor.Manager/Models/BoilerMonitorUpdateContext.cs b/BoilerMonitor.Manager/Models/BoilerMonitorUpdateContext.cs index 9f94a54..66083ce 100644 --- a/BoilerMonitor.Manager/Models/BoilerMonitorUpdateContext.cs +++ b/BoilerMonitor.Manager/Models/BoilerMonitorUpdateContext.cs @@ -12,6 +12,7 @@ public record BoilerMonitorUpdateContext public required bool WaterReady { get; init; } public required string? BoilerSwitchState { get; init; } public required double? BoilerPowerWatts { get; init; } + public required DateTimeOffset? CooldownSince { get; init; } public required bool IsNowCheap { get; init; } public required DateTime? NextCheapIntervalStart { get; init; } } diff --git a/BoilerMonitor.Manager/WaterReadyService.cs b/BoilerMonitor.Manager/WaterReadyService.cs index 4c10443..d10366d 100644 --- a/BoilerMonitor.Manager/WaterReadyService.cs +++ b/BoilerMonitor.Manager/WaterReadyService.cs @@ -8,8 +8,9 @@ public sealed class WaterReadyService(ILogger logger, TimePro { private const string SwitchOnState = "on"; private readonly Lock _lock = new(); - private DateTimeOffset? _lastTurnedOnAt; private DateTimeOffset? _waterReadySince; + private bool _hasObservedHeating; + private int _consecutiveBelowThresholdCount; public bool IsInCooldown { @@ -22,6 +23,17 @@ public sealed class WaterReadyService(ILogger logger, TimePro } } + public DateTimeOffset? WaterReadySince + { + get + { + lock (_lock) + { + return _waterReadySince; + } + } + } + public bool IsWaterReady(string? switchState, double? powerWatts, double heatingThresholdWatts) { lock (_lock) @@ -43,39 +55,68 @@ public sealed class WaterReadyService(ILogger logger, TimePro return false; } - if (IsWithinWarmUpGracePeriod()) + lock (_lock) { - logger.LogDebug( - "Ignoring low power reading ({PowerWatts}W) during warm-up grace period", - powerWatts.Value); - return false; - } - - var isReady = powerWatts.Value < heatingThresholdWatts; - - if (isReady) - { - lock (_lock) + if (!_hasObservedHeating) { - _waterReadySince ??= timeProvider.GetUtcNow(); + logger.LogDebug( + "Ignoring power reading ({PowerWatts}W) — boiler has not been observed heating yet", + powerWatts.Value); + return false; } - logger.LogInformation( - "Water detected as ready, cooldown period ({CooldownPeriod}) started", - BoilerMonitorConsts.WaterReadyCooldownPeriod); - } + if (powerWatts.Value >= heatingThresholdWatts) + { + _consecutiveBelowThresholdCount = 0; + return false; + } - return isReady; + _consecutiveBelowThresholdCount++; + + if (_consecutiveBelowThresholdCount < BoilerMonitorConsts.ConsecutiveReadingsRequired) + { + 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); + + return true; + } } public void NotifyTurnedOn() { lock (_lock) { - _lastTurnedOnAt = timeProvider.GetUtcNow(); + _hasObservedHeating = false; + _consecutiveBelowThresholdCount = 0; } - logger.LogDebug("Boiler turn-on recorded, warm-up grace period started ({GracePeriod})", BoilerMonitorConsts.WarmUpGracePeriod); + logger.LogDebug("Boiler turn-on recorded, awaiting first heating observation before water ready detection is enabled"); + } + + public void RecordHeatingObserved() + { + lock (_lock) + { + if (_hasObservedHeating) + { + return; + } + + _hasObservedHeating = true; + } + + logger.LogDebug("Heating observed, water ready detection is now enabled"); } public void ResetCooldown() @@ -83,33 +124,28 @@ public sealed class WaterReadyService(ILogger logger, TimePro lock (_lock) { _waterReadySince = null; + _consecutiveBelowThresholdCount = 0; } logger.LogInformation("Water ready cooldown has been reset"); } - private bool IsWithinCooldownPeriod() - { - if (_waterReadySince is null) - { - return false; - } - - var elapsed = timeProvider.GetUtcNow() - _waterReadySince.Value; - return elapsed < BoilerMonitorConsts.WaterReadyCooldownPeriod; - } - - private bool IsWithinWarmUpGracePeriod() + public void RestoreCooldownState(DateTimeOffset waterReadySince) { lock (_lock) { - if (_lastTurnedOnAt is null) + var todayMidnightUtc = new DateTimeOffset(timeProvider.GetUtcNow().Date, TimeSpan.Zero); + if (waterReadySince < todayMidnightUtc) { - return false; + logger.LogInformation( + "Persisted cooldown is from a previous day ({Since}), not restoring", waterReadySince); + return; } - var elapsed = timeProvider.GetUtcNow() - _lastTurnedOnAt.Value; - return elapsed < BoilerMonitorConsts.WarmUpGracePeriod; + _waterReadySince = waterReadySince; + logger.LogInformation("Restored water ready cooldown from {Since}", waterReadySince); } } + + private bool IsWithinCooldownPeriod() => _waterReadySince is not null; } diff --git a/BoilerMonitor.Models/BoilerMonitorConsts.cs b/BoilerMonitor.Models/BoilerMonitorConsts.cs index 0f24d45..b222db5 100644 --- a/BoilerMonitor.Models/BoilerMonitorConsts.cs +++ b/BoilerMonitor.Models/BoilerMonitorConsts.cs @@ -11,18 +11,20 @@ public static class BoilerMonitorConsts public const double DefaultHeatingPowerThresholdWatts = 5.0; /// - /// Grace period after the boiler switch is turned on, during which - /// low power readings are ignored for "water ready" detection. - /// This prevents false positives caused by the heating element ramp-up delay. + /// Number of consecutive below-threshold power readings required before + /// declaring water as ready. Prevents false positives from transient sensor glitches. + /// At 30s poll interval, a value of 2 means 60s of confirmed low power. /// - public static readonly TimeSpan WarmUpGracePeriod = TimeSpan.FromMinutes(2); + public const int ConsecutiveReadingsRequired = 2; + + public const string ShowerStateEntityId = "sensor.showermonitor_state"; + public const string ShowerActiveState = "Active"; /// - /// Cooldown period after the water has been detected as ready, - /// during which the boiler will not be turned back on. - /// This prevents wasteful on/off cycling when water is already heated. + /// Minimum interval between "hot water is ready" push notifications. + /// Prevents notification spam when power readings fluctuate around the heating threshold. /// - public static readonly TimeSpan WaterReadyCooldownPeriod = TimeSpan.FromHours(1); + public static readonly TimeSpan WaterReadyNotificationCooldown = TimeSpan.FromHours(1); public const int MinPollIntervalSeconds = 5; public const int MaxPollIntervalSeconds = 300; @@ -49,6 +51,12 @@ public static class BoilerMonitorConsts public const string SessionCountEntityId = "sensor.boilermonitor_session_count"; public const string BudgetOverrideEntityId = "switch.boilermonitor_budget_override"; + /// + /// When on, the daemon may call the configured boiler switch per price/budget/water-ready logic. + /// When off, monitoring continues but automatic turn_on/turn_off calls are suppressed (manual control). + /// + public const string AutoManagementEntityId = "switch.boilermonitor_auto_management"; + public const string NordPoolCheapestIntervalsEntityId = "sensor.nordpool_cheapest_intervals"; public const string BoilerDailyHoursEntityId = "input_number.boiler_daily_hours"; @@ -61,6 +69,8 @@ public static class BoilerMonitorConsts public const string SwitchOnState = "on"; + public const string SwitchOffState = "off"; + public const string DeviceIdentifier = "boiler_monitor"; public const string DeviceName = "Boiler Monitor"; public const string DeviceManufacturer = "HomeAssistant App Daemon"; diff --git a/HomeAssistant.Entities/EntityGeneration/HomeAssistantGenerated.cs b/HomeAssistant.Entities/EntityGeneration/HomeAssistantGenerated.cs index ff2591e..5564ca7 100644 --- a/HomeAssistant.Entities/EntityGeneration/HomeAssistantGenerated.cs +++ b/HomeAssistant.Entities/EntityGeneration/HomeAssistantGenerated.cs @@ -1321,6 +1321,8 @@ public partial class SwitchEntities public SwitchEntity BalkonyLaps => new(_haContext, "switch.balkony_laps"); ///Boiler Monitor Override budget enforcement public SwitchEntity BoilermonitorBudgetOverride => new(_haContext, "switch.boilermonitor_budget_override"); + ///Boiler Monitor Automatic boiler control + public SwitchEntity BoilermonitorAutoManagement => new(_haContext, "switch.boilermonitor_auto_management"); ///Boiler Monitor Skip price cap, heat until ready public SwitchEntity BoilermonitorSkipPriceCap => new(_haContext, "switch.boilermonitor_skip_price_cap"); ///Dishwasher diff --git a/HomeAssistant.HistoryReplay/Components/App.razor b/HomeAssistant.HistoryReplay/Components/App.razor new file mode 100644 index 0000000..77d6762 --- /dev/null +++ b/HomeAssistant.HistoryReplay/Components/App.razor @@ -0,0 +1,19 @@ + + + + + + HA History Replay + + + + + + + + + + + + + diff --git a/HomeAssistant.HistoryReplay/Components/Charts/BoilerChart.razor b/HomeAssistant.HistoryReplay/Components/Charts/BoilerChart.razor new file mode 100644 index 0000000..3360918 --- /dev/null +++ b/HomeAssistant.HistoryReplay/Components/Charts/BoilerChart.razor @@ -0,0 +1,44 @@ +@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 new file mode 100644 index 0000000..9773970 --- /dev/null +++ b/HomeAssistant.HistoryReplay/Components/Charts/LightChart.razor @@ -0,0 +1,30 @@ +@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 new file mode 100644 index 0000000..f0210dd --- /dev/null +++ b/HomeAssistant.HistoryReplay/Components/Charts/NordPoolChart.razor @@ -0,0 +1,32 @@ +@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 new file mode 100644 index 0000000..7129b93 --- /dev/null +++ b/HomeAssistant.HistoryReplay/Components/Charts/PowerChart.razor @@ -0,0 +1,40 @@ +@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 new file mode 100644 index 0000000..878a9c8 --- /dev/null +++ b/HomeAssistant.HistoryReplay/Components/Charts/ShowerChart.razor @@ -0,0 +1,46 @@ +@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 new file mode 100644 index 0000000..6713df2 --- /dev/null +++ b/HomeAssistant.HistoryReplay/Components/Layout/MainLayout.razor @@ -0,0 +1,17 @@ +@inherits LayoutComponentBase + +
+ + +
+ @Body +
+
diff --git a/HomeAssistant.HistoryReplay/Components/Pages/Dashboard.razor b/HomeAssistant.HistoryReplay/Components/Pages/Dashboard.razor new file mode 100644 index 0000000..07c5f61 --- /dev/null +++ b/HomeAssistant.HistoryReplay/Components/Pages/Dashboard.razor @@ -0,0 +1,240 @@ +@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 new file mode 100644 index 0000000..faa2a8c --- /dev/null +++ b/HomeAssistant.HistoryReplay/Components/Routes.razor @@ -0,0 +1,6 @@ + + + + + + diff --git a/HomeAssistant.HistoryReplay/Components/Shared/EventTable.razor b/HomeAssistant.HistoryReplay/Components/Shared/EventTable.razor new file mode 100644 index 0000000..50ea9b2 --- /dev/null +++ b/HomeAssistant.HistoryReplay/Components/Shared/EventTable.razor @@ -0,0 +1,54 @@ +@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 new file mode 100644 index 0000000..804a376 --- /dev/null +++ b/HomeAssistant.HistoryReplay/Components/Shared/SummaryCards.razor @@ -0,0 +1,53 @@ +@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 new file mode 100644 index 0000000..448c811 --- /dev/null +++ b/HomeAssistant.HistoryReplay/Components/_Imports.razor @@ -0,0 +1,15 @@ +@using System.Net.Http +@using Microsoft.AspNetCore.Components.Forms +@using Microsoft.AspNetCore.Components.Routing +@using Microsoft.AspNetCore.Components.Web +@using static Microsoft.AspNetCore.Components.Web.RenderMode +@using Microsoft.AspNetCore.Components.Web.Virtualization +@using Microsoft.JSInterop +@using ApexCharts +@using HomeAssistant.HistoryReplay.Components +@using HomeAssistant.HistoryReplay.Components.Layout +@using HomeAssistant.HistoryReplay.Components.Shared +@using HomeAssistant.HistoryReplay.Components.Charts +@using HomeAssistant.HistoryReplay.Reporting +@using HomeAssistant.HistoryReplay.Services +@using HomeAssistant.HistoryReplay.Configuration diff --git a/HomeAssistant.HistoryReplay/Configuration/ReplayEntityMap.cs b/HomeAssistant.HistoryReplay/Configuration/ReplayEntityMap.cs index e56b966..bbde841 100644 --- a/HomeAssistant.HistoryReplay/Configuration/ReplayEntityMap.cs +++ b/HomeAssistant.HistoryReplay/Configuration/ReplayEntityMap.cs @@ -24,6 +24,7 @@ public static class ReplayEntityMap "sensor.nordpool_cheapest_intervals", BoilerMonitorConsts.SkipPriceCapEntityId, BoilerMonitorConsts.BudgetOverrideEntityId, + BoilerMonitorConsts.AutoManagementEntityId, BoilerMonitorConsts.BoilerDailyHoursEntityId ]; @@ -46,6 +47,11 @@ public static class ReplayEntityMap return entities; } + public static IReadOnlyList GetEntitiesRequiringAttributes() => + [ + "sensor.nordpool_cheapest_intervals" + ]; + public static IReadOnlyList GetAllEntities( string boilerPowerEntityId, string boilerSwitchEntityId, @@ -66,4 +72,38 @@ public static class ReplayEntityMap 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/HistoryData/HistoryTimeline.cs b/HomeAssistant.HistoryReplay/HistoryData/HistoryTimeline.cs index 420afb4..d017c27 100644 --- a/HomeAssistant.HistoryReplay/HistoryData/HistoryTimeline.cs +++ b/HomeAssistant.HistoryReplay/HistoryData/HistoryTimeline.cs @@ -3,6 +3,7 @@ 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) { @@ -13,7 +14,41 @@ public sealed class HistoryTimeline } list.AddRange(entries); - list.Sort((a, b) => a.LastChanged.CompareTo(b.LastChanged)); + _sorted = false; + } + + public void AddEntriesBulk(string entityId, List entries) + { + if (entries.Count == 0) + { + return; + } + + if (!_entityTimelines.TryGetValue(entityId, out var list)) + { + _entityTimelines[entityId] = entries; + } + else + { + list.AddRange(entries); + } + + _sorted = false; + } + + public void FinalizeSort() + { + if (_sorted) + { + return; + } + + foreach (var entries in _entityTimelines.Values) + { + entries.Sort((a, b) => a.LastChanged.CompareTo(b.LastChanged)); + } + + _sorted = true; } public HistoryStateEntry? GetStateAt(string entityId, DateTimeOffset timestamp) @@ -23,20 +58,8 @@ public sealed class HistoryTimeline return null; } - HistoryStateEntry? best = null; - foreach (var entry in entries) - { - if (entry.LastChanged <= timestamp) - { - best = entry; - } - else - { - break; - } - } - - return best; + var index = BinarySearchFloor(entries, timestamp); + return index >= 0 ? entries[index] : null; } public IReadOnlyList GetAllTimestamps() @@ -62,4 +85,34 @@ public sealed class HistoryTimeline } public int TotalEntryCount => _entityTimelines.Values.Sum(e => e.Count); + + public void Clear() + { + _entityTimelines.Clear(); + _sorted = false; + } + + private static int BinarySearchFloor(List 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 index ce03853..7f399d7 100644 --- a/HomeAssistant.HistoryReplay/HistoryData/HomeAssistantHistoryProvider.cs +++ b/HomeAssistant.HistoryReplay/HistoryData/HomeAssistantHistoryProvider.cs @@ -9,63 +9,230 @@ public sealed class HomeAssistantHistoryProvider( IHomeAssistantApiClient client, ILogger logger) : IHistoryDataProvider { - private const int MaxEntitiesPerRequest = 10; + private const int MaxEntitiesPerBatch = 5; + private const int MaxConcurrentRequests = 20; + private const int MaxRetryAttempts = 3; + private static readonly TimeSpan InitialRetryDelay = TimeSpan.FromSeconds(2); - public async Task FetchHistoryAsync( + 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 batches = ChunkEntities(entityIds, MaxEntitiesPerRequest); + var allEntityCount = minimalEntityIds.Count + fullEntityIds.Count; - var tasks = batches.Select(batch => FetchBatchAsync(batch, startTime, endTime, cancellationToken)); - var results = await Task.WhenAll(tasks).ConfigureAwait(false); + var minimalBatches = ChunkEntities(minimalEntityIds, MaxEntitiesPerBatch); + var fullBatches = ChunkEntities(fullEntityIds, MaxEntitiesPerBatch); - foreach (var batchTimeline in results) + logger.LogInformation( + "Fetching history in {MinBatchCount}+{FullBatchCount} batch(es) for {MinCount} minimal + {FullCount} full entities", + minimalBatches.Count, fullBatches.Count, minimalEntityIds.Count, fullEntityIds.Count); + + var failedEntities = new List(); + using var semaphore = new SemaphoreSlim(MaxConcurrentRequests); + + var minimalTasks = minimalBatches.Select(batch => FetchBatchThrottledAsync( + batch, startTime, endTime, minimalResponse: true, semaphore, cancellationToken)); + + var fullTasks = fullBatches.Select(batch => FetchBatchThrottledAsync( + batch, startTime, endTime, minimalResponse: false, semaphore, cancellationToken)); + + var results = await Task.WhenAll(minimalTasks.Concat(fullTasks)).ConfigureAwait(false); + + foreach (var batchResult in results) { - foreach (var entityId in batchTimeline.GetEntityIds()) + foreach (var (entityId, entries) in batchResult.Entries) { - timeline.AddEntries(entityId, batchTimeline.GetEntityHistory(entityId)); + timeline.AddEntriesBulk(entityId, entries); + } + + failedEntities.AddRange(batchResult.FailedEntityIds); + } + + if (failedEntities.Count > 0) + { + logger.LogWarning("Retrying {Count} failed entities individually: {Entities}", failedEntities.Count, string.Join(", ", failedEntities)); + + var individualResults = await FetchEntitiesIndividuallyAsync(failedEntities, startTime, endTime, cancellationToken); + + foreach (var (entityId, entries) in individualResults) + { + timeline.AddEntriesBulk(entityId, entries); } } + timeline.FinalizeSort(); + logger.LogInformation( "Fetched history for {EntityCount} entities: {EntryCount} total entries ({Start} to {End})", - entityIds.Count, timeline.TotalEntryCount, startTime, endTime); + allEntityCount, timeline.TotalEntryCount, startTime, endTime); return timeline; } - private async Task FetchBatchAsync( + 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 timeline = new HistoryTimeline(); - var entityIdsString = string.Join(",", entityIds); + var allEntries = new List<(string, List)>(); + using var semaphore = new SemaphoreSlim(MaxConcurrentRequests); - logger.LogDebug("Fetching history batch for: {Entities}", entityIdsString); - - try + var tasks = entityIds.Select(async entityId => { - var result = await client.GetHistoryAsync( - entityIdsString, startTime, endTime, minimalResponse: false, cancellationToken) - .ConfigureAwait(false); + await semaphore.WaitAsync(cancellationToken); + try + { + return await FetchSingleEntityWithRetryAsync(entityId, startTime, endTime, cancellationToken); + } + finally + { + semaphore.Release(); + } + }); - ParseHistoryResponse(result, timeline); - } - catch (Exception ex) + var results = await Task.WhenAll(tasks).ConfigureAwait(false); + + foreach (var result in results) { - logger.LogError(ex, "Failed to fetch history for entities: {Entities}", entityIdsString); + allEntries.AddRange(result); } - return timeline; + return allEntries; } - private void ParseHistoryResponse(JsonElement response, HistoryTimeline timeline) + private async Task 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) { @@ -79,25 +246,37 @@ public sealed class HomeAssistantHistoryProvider( continue; } + string? currentEntityId = null; + var entries = new List(); + foreach (var stateObj in entityArray.EnumerateArray()) { - var entry = ParseStateEntry(stateObj); - if (entry is not null) + var entry = ParseStateEntry(stateObj, currentEntityId); + if (entry is null) { - timeline.AddEntries(entry.EntityId, [entry]); + continue; } + + currentEntityId ??= entry.EntityId; + entries.Add(entry); + } + + if (currentEntityId is not null && entries.Count > 0) + { + result.Add((currentEntityId, entries)); } } } - private HistoryStateEntry? ParseStateEntry(JsonElement stateObj) + private static HistoryStateEntry? ParseStateEntry(JsonElement stateObj, string? fallbackEntityId) { - if (!stateObj.TryGetProperty("entity_id", out var entityIdProp)) + string? entityId = null; + if (stateObj.TryGetProperty("entity_id", out var entityIdProp)) { - return null; + entityId = entityIdProp.GetString(); } - var entityId = entityIdProp.GetString(); + entityId ??= fallbackEntityId; if (string.IsNullOrEmpty(entityId)) { return null; @@ -105,16 +284,13 @@ public sealed class HomeAssistantHistoryProvider( var state = stateObj.TryGetProperty("state", out var stateProp) ? stateProp.GetString() : null; - DateTimeOffset lastChanged; - if (stateObj.TryGetProperty("last_changed", out var lastChangedProp)) + if (!stateObj.TryGetProperty("last_changed", out var lastChangedProp)) { - if (!DateTimeOffset.TryParse(lastChangedProp.GetString(), CultureInfo.InvariantCulture, - DateTimeStyles.RoundtripKind, out lastChanged)) - { - return null; - } + return null; } - else + + if (!DateTimeOffset.TryParse(lastChangedProp.GetString(), CultureInfo.InvariantCulture, + DateTimeStyles.RoundtripKind, out var lastChanged)) { return null; } @@ -159,10 +335,13 @@ public sealed class HomeAssistantHistoryProvider( for (var i = 0; i < entities.Count; i += chunkSize) { - var chunk = entities.Skip(i).Take(chunkSize).ToList(); - chunks.Add(chunk); + chunks.Add(entities.Skip(i).Take(chunkSize).ToList()); } return chunks; } + + private sealed record BatchFetchResult( + List<(string EntityId, List Entries)> Entries, + List FailedEntityIds); } diff --git a/HomeAssistant.HistoryReplay/HistoryData/IHistoryDataProvider.cs b/HomeAssistant.HistoryReplay/HistoryData/IHistoryDataProvider.cs index a901b03..a61ff65 100644 --- a/HomeAssistant.HistoryReplay/HistoryData/IHistoryDataProvider.cs +++ b/HomeAssistant.HistoryReplay/HistoryData/IHistoryDataProvider.cs @@ -7,4 +7,11 @@ public interface IHistoryDataProvider 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 index 0caf4b2..1b3c934 100644 --- a/HomeAssistant.HistoryReplay/HomeAssistant.HistoryReplay.csproj +++ b/HomeAssistant.HistoryReplay/HomeAssistant.HistoryReplay.csproj @@ -1,7 +1,6 @@ - + - Exe net10.0 14.0 enable @@ -10,22 +9,10 @@ - - Always - - - Always - Never - - - - - - - + + - diff --git a/HomeAssistant.HistoryReplay/HomeAssistantClient/HomeAssistantApiClient.cs b/HomeAssistant.HistoryReplay/HomeAssistantClient/HomeAssistantApiClient.cs index 2b30f42..3127d17 100644 --- a/HomeAssistant.HistoryReplay/HomeAssistantClient/HomeAssistantApiClient.cs +++ b/HomeAssistant.HistoryReplay/HomeAssistantClient/HomeAssistantApiClient.cs @@ -12,10 +12,8 @@ public sealed class HomeAssistantApiClient : IHomeAssistantApiClient { _httpClient = httpClient; _httpClient.BaseAddress = settings.Value.BaseUrl; - _httpClient.DefaultRequestHeaders.Authorization = - new AuthenticationHeaderValue("Bearer", settings.Value.Token); - _httpClient.DefaultRequestHeaders.Accept.Add( - new MediaTypeWithQualityHeaderValue("application/json")); + _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", settings.Value.Token); + _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); _httpClient.Timeout = TimeSpan.FromSeconds(HomeAssistantSettings.DefaultTimeoutSeconds); } @@ -30,10 +28,14 @@ public sealed class HomeAssistantApiClient : IHomeAssistantApiClient var path = $"/api/history/period/{start:O}?filter_entity_id={Uri.EscapeDataString(entityIds)}"; if (endTime.HasValue) + { path += $"&end_time={Uri.EscapeDataString(endTime.Value.ToString("O"))}"; + } if (minimalResponse) + { path += "&minimal_response"; + } return await GetJsonAsync(path, cancellationToken).ConfigureAwait(false); } @@ -45,6 +47,7 @@ public sealed class HomeAssistantApiClient : IHomeAssistantApiClient await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); var doc = await JsonDocument.ParseAsync(stream, cancellationToken: cancellationToken).ConfigureAwait(false); + return doc.RootElement.Clone(); } } diff --git a/HomeAssistant.HistoryReplay/HomeAssistantClient/HomeAssistantSettings.cs b/HomeAssistant.HistoryReplay/HomeAssistantClient/HomeAssistantSettings.cs index 2e99ba5..687ee64 100644 --- a/HomeAssistant.HistoryReplay/HomeAssistantClient/HomeAssistantSettings.cs +++ b/HomeAssistant.HistoryReplay/HomeAssistantClient/HomeAssistantSettings.cs @@ -4,7 +4,7 @@ public sealed class HomeAssistantSettings { public const string SectionName = "HomeAssistant"; public const int DefaultPort = 8123; - public const int DefaultTimeoutSeconds = 30; + public const int DefaultTimeoutSeconds = 3600; public string Host { get; set; } = string.Empty; public int Port { get; set; } = DefaultPort; diff --git a/HomeAssistant.HistoryReplay/Program.cs b/HomeAssistant.HistoryReplay/Program.cs index 0f88476..b3a4092 100644 --- a/HomeAssistant.HistoryReplay/Program.cs +++ b/HomeAssistant.HistoryReplay/Program.cs @@ -2,21 +2,14 @@ using BoilerMonitorManager; using BoilerMonitorManager.Interface; using BoilerMonitorManager.Models; using HomeAssistant.Entities.Interfaces; -using HomeAssistant.HistoryReplay.Configuration; +using HomeAssistant.HistoryReplay.Components; using HomeAssistant.HistoryReplay.HistoryData; -using HomeAssistant.HistoryReplay.Replay; -using HomeAssistant.HistoryReplay.Reporting; -using HomeAssistant.HistoryReplay.Runners; using HomeAssistant.HistoryReplay.HomeAssistantClient; +using HomeAssistant.HistoryReplay.Replay; +using HomeAssistant.HistoryReplay.Services; using LightMonitorManager.Models; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; using NordPoolManager; using NordPoolManager.Interface; -using PowerMonitorManager; -using PowerMonitorManager.Interface; using PowerMonitorManager.Models; using Serilog; using ShowerMonitorManager; @@ -25,167 +18,60 @@ using ShowerMonitorManager.Models; Log.Logger = new LoggerConfiguration() .MinimumLevel.Information() - .WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}") + .WriteTo.Console() .CreateLogger(); -try +var builder = WebApplication.CreateBuilder(args); + +builder.WebHost.UseStaticWebAssets(); + +builder.Services.AddLogging(logging => { - Log.Information("Starting Home Assistant History Replay"); + logging.ClearProviders(); + logging.AddSerilog(dispose: true); +}); - var configuration = new ConfigurationBuilder() - .SetBasePath(Directory.GetCurrentDirectory()) - .AddJsonFile("appsettings.json", optional: false) - .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") ?? "Production"}.json", optional: true) - .AddEnvironmentVariables() - .Build(); +builder.Services.AddRazorComponents() + .AddInteractiveServerComponents(); - var services = new ServiceCollection(); +builder.Services.Configure( + 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)); - services.AddLogging(builder => - { - builder.ClearProviders(); - builder.AddSerilog(dispose: true); - }); +builder.Services.AddHttpClient(); +builder.Services.AddSingleton(); - services.Configure(configuration.GetSection(HomeAssistantSettings.SectionName)); - services.Configure(configuration.GetSection(ReplayOptions.SectionName)); - services.Configure(configuration.GetSection(BoilerMonitorOptions.SectionName)); - services.Configure(configuration.GetSection(ShowerMonitorOptions.SectionName)); - services.Configure(configuration.GetSection(PowerMonitorOptions.SectionName)); - services.Configure(configuration.GetSection(LightMonitorOptions.SectionName)); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); +builder.Services.AddSingleton(); - services.AddHttpClient(); - services.AddSingleton(); +var showerOpts = builder.Configuration + .GetSection(ShowerMonitorOptions.SectionName) + .Get() ?? new ShowerMonitorOptions(); +builder.Services.AddSingleton(_ => new HumidityRateCalculator(showerOpts.RateWindowSize)); - var replayOptions = configuration.GetSection(ReplayOptions.SectionName).Get() ?? new ReplayOptions(); +builder.Services.AddSingleton(); - var replayTimeline = new ReplayTimeline(); - var replayTimeProvider = new ReplayTimeProvider(replayOptions.StartTime); +var app = builder.Build(); - services.AddSingleton(replayTimeline); - services.AddSingleton(replayTimeProvider); - services.AddSingleton(replayTimeProvider); - - services.AddSingleton(); - - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); - - var showerOptions = configuration.GetSection(ShowerMonitorOptions.SectionName).Get() ?? new ShowerMonitorOptions(); - services.AddSingleton(_ => new HumidityRateCalculator(showerOptions.RateWindowSize)); - services.AddSingleton(); - - services.AddSingleton(); - - var provider = services.BuildServiceProvider(); - - var historyProvider = provider.GetRequiredService(); - var logger = provider.GetRequiredService>(); - - var boilerOpts = provider.GetRequiredService>().Value; - var showerOpts = provider.GetRequiredService>().Value; - var powerOpts = provider.GetRequiredService>().Value; - var lightOpts = provider.GetRequiredService>().Value; - - logger.LogInformation("Replay period: {Start} to {End}", replayOptions.StartTime, replayOptions.EndTime); - - var allEntityIds = ReplayEntityMap.GetAllEntities( - boilerPowerEntityId: "sensor.boiler_power", - boilerSwitchEntityId: "switch.boiler", - bathroomHumidityEntityId: showerOpts.BathroomHumidityEntityId, - mainHomeHumidityEntityId: showerOpts.MainHomeHumidityEntityId, - mainMeterEntityId: powerOpts.MainMeterEntityId, - sunEntityId: lightOpts.SunEntityId, - lightEntityId: lightOpts.LightEntityId, - personEntityIds: lightOpts.PersonEntityIds); - - logger.LogInformation("Fetching history for {Count} entities...", allEntityIds.Count); - - var timeline = await historyProvider.FetchHistoryAsync( - allEntityIds, replayOptions.StartTime, replayOptions.EndTime); - - var replayHaContext = new ReplayHaContext( - timeline, - replayTimeProvider, - replayTimeline, - provider.GetRequiredService>()); - - var fanControlService = new ExhaustFanControlService( - replayHaContext, - provider.GetRequiredService>(), - provider.GetRequiredService>()); - - var runners = new List(); - - if (replayOptions.Monitors.NordPool) - { - runners.Add(new NordPoolReplayRunner( - timeline, replayTimeProvider, replayTimeline, - provider.GetRequiredService(), - provider.GetRequiredService>(), - provider.GetRequiredService>())); - } - - if (replayOptions.Monitors.Boiler) - { - runners.Add(new BoilerReplayRunner( - timeline, replayTimeProvider, replayTimeline, - provider.GetRequiredService(), - provider.GetRequiredService(), - provider.GetRequiredService(), - provider.GetRequiredService>(), - provider.GetRequiredService>(), - provider.GetRequiredService>())); - } - - if (replayOptions.Monitors.Shower) - { - runners.Add(new ShowerReplayRunner( - timeline, replayTimeProvider, replayTimeline, - provider.GetRequiredService(), - fanControlService, - provider.GetRequiredService>(), - provider.GetRequiredService>(), - provider.GetRequiredService>())); - } - - if (replayOptions.Monitors.Power) - { - runners.Add(new PowerReplayRunner( - timeline, replayTimeProvider, replayTimeline, - provider.GetRequiredService(), - provider.GetRequiredService(), - provider.GetRequiredService>(), - provider.GetRequiredService>(), - provider.GetRequiredService>())); - } - - if (replayOptions.Monitors.Light) - { - runners.Add(new LightReplayRunner( - timeline, replayTimeProvider, replayTimeline, - provider.GetRequiredService>(), - provider.GetRequiredService>(), - provider.GetRequiredService>())); - } - - logger.LogInformation("Running {Count} monitor replay(s) in parallel...", runners.Count); - - var replayTasks = runners.Select(r => Task.Run(() => r.RunAsync())); - await Task.WhenAll(replayTasks); - - var renderer = provider.GetRequiredService(); - renderer.Render(replayTimeline, replayOptions); -} -catch (Exception ex) +if (!app.Environment.IsDevelopment()) { - Log.Fatal(ex, "History replay failed"); -} -finally -{ - await Log.CloseAndFlushAsync(); + app.UseHsts(); } + +app.MapStaticAssets(); +app.UseAntiforgery(); + +app.MapRazorComponents() + .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 new file mode 100644 index 0000000..92164df --- /dev/null +++ b/HomeAssistant.HistoryReplay/Properties/launchSettings.json @@ -0,0 +1,13 @@ +{ + "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 new file mode 100644 index 0000000..9b1f60e --- /dev/null +++ b/HomeAssistant.HistoryReplay/README.md @@ -0,0 +1,243 @@ +# HomeAssistant.HistoryReplay + +A debugging tool that fetches real historical data from your Home Assistant instance and replays it through the monitor business logic to verify decisions without side effects. + +## Prerequisites + +- .NET 10 SDK +- A running Home Assistant instance with the History API enabled +- A [long-lived access token](https://www.home-assistant.io/docs/authentication/#your-account-profile) from Home Assistant + +## Quick Start + +### 1. Configure the connection + +Edit `appsettings.json` (or create `appsettings.development.json` for local overrides): + +```json +{ + "HomeAssistant": { + "Host": "homeassistant.local", + "Port": 8123, + "Token": "", + "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/Reporting/ConsoleReportRenderer.cs b/HomeAssistant.HistoryReplay/Reporting/ConsoleReportRenderer.cs index 7227fb1..b30f9ce 100644 --- a/HomeAssistant.HistoryReplay/Reporting/ConsoleReportRenderer.cs +++ b/HomeAssistant.HistoryReplay/Reporting/ConsoleReportRenderer.cs @@ -105,9 +105,20 @@ public sealed class ConsoleReportRenderer 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 (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) { diff --git a/HomeAssistant.HistoryReplay/Reporting/ReplayDataPoint.cs b/HomeAssistant.HistoryReplay/Reporting/ReplayDataPoint.cs new file mode 100644 index 0000000..aae4971 --- /dev/null +++ b/HomeAssistant.HistoryReplay/Reporting/ReplayDataPoint.cs @@ -0,0 +1,9 @@ +namespace HomeAssistant.HistoryReplay.Reporting; + +public sealed class ReplayDataPoint +{ + public required DateTimeOffset Timestamp { get; init; } + public required string Monitor { get; init; } + public required string Series { get; init; } + public required double Value { get; init; } +} diff --git a/HomeAssistant.HistoryReplay/Reporting/ReplayDataSeries.cs b/HomeAssistant.HistoryReplay/Reporting/ReplayDataSeries.cs new file mode 100644 index 0000000..0039a4e --- /dev/null +++ b/HomeAssistant.HistoryReplay/Reporting/ReplayDataSeries.cs @@ -0,0 +1,50 @@ +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/ReplayTimeline.cs b/HomeAssistant.HistoryReplay/Reporting/ReplayTimeline.cs index 0ed9d83..c4046e6 100644 --- a/HomeAssistant.HistoryReplay/Reporting/ReplayTimeline.cs +++ b/HomeAssistant.HistoryReplay/Reporting/ReplayTimeline.cs @@ -22,4 +22,9 @@ public sealed class ReplayTimeline 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 index 0ed3c5e..6d222ea 100644 --- a/HomeAssistant.HistoryReplay/Runners/BoilerReplayRunner.cs +++ b/HomeAssistant.HistoryReplay/Runners/BoilerReplayRunner.cs @@ -8,7 +8,6 @@ using HomeAssistant.HistoryReplay.Replay; using HomeAssistant.HistoryReplay.Reporting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using BoilerMonitorManager.Models; namespace HomeAssistant.HistoryReplay.Runners; @@ -17,12 +16,14 @@ public sealed class BoilerReplayRunner : IMonitorReplayRunner private readonly HistoryTimeline _timeline; private readonly ReplayTimeProvider _timeProvider; private readonly ReplayTimeline _replayTimeline; + private readonly ReplayDataSeries _dataSeries; private readonly IBoilerControlService _boilerControlService; private readonly IBoilerRunTimeTracker _tracker; private readonly IWaterReadyService _waterReadyService; private readonly ILogger _logger; private readonly ReplayOptions _replayOptions; - private readonly BoilerMonitorOptions _boilerOptions; + private readonly string _boilerPowerEntityId; + private readonly string _boilerSwitchEntityId; public string MonitorName => "Boiler"; @@ -30,22 +31,26 @@ public sealed class BoilerReplayRunner : IMonitorReplayRunner HistoryTimeline timeline, ReplayTimeProvider timeProvider, ReplayTimeline replayTimeline, + ReplayDataSeries dataSeries, IBoilerControlService boilerControlService, IBoilerRunTimeTracker tracker, IWaterReadyService waterReadyService, ILogger logger, IOptions replayOptions, - IOptions boilerOptions) + string boilerPowerEntityId, + string boilerSwitchEntityId) { _timeline = timeline; _timeProvider = timeProvider; _replayTimeline = replayTimeline; + _dataSeries = dataSeries; _boilerControlService = boilerControlService; _tracker = tracker; _waterReadyService = waterReadyService; _logger = logger; _replayOptions = replayOptions.Value; - _boilerOptions = boilerOptions.Value; + _boilerPowerEntityId = boilerPowerEntityId; + _boilerSwitchEntityId = boilerSwitchEntityId; } public Task RunAsync(CancellationToken cancellationToken = default) @@ -58,30 +63,8 @@ public sealed class BoilerReplayRunner : IMonitorReplayRunner BoilerAction? lastAction = null; var lastWaterReady = false; - var boilerPowerEntityId = ReadConfigEntityState( - BoilerMonitorConsts.ConfigPowerEntityId, _replayOptions.StartTime); - var boilerSwitchEntityId = ReadConfigEntityState( - BoilerMonitorConsts.ConfigSwitchEntityId, _replayOptions.StartTime); - - if (string.IsNullOrEmpty(boilerPowerEntityId) || string.IsNullOrEmpty(boilerSwitchEntityId)) - { - _replayTimeline.AddEvent(new ReplayEvent - { - Timestamp = currentTime, - Monitor = MonitorName, - EventType = ReplayEventType.Warning, - Message = "Boiler not configured (missing power/switch entity IDs), skipping replay" - }); - return Task.CompletedTask; - } - - var configThresholdState = ReadConfigEntityState( - BoilerMonitorConsts.ConfigHeatingThresholdEntityId, _replayOptions.StartTime); - if (!string.IsNullOrEmpty(configThresholdState) && - double.TryParse(configThresholdState, CultureInfo.InvariantCulture, out var configuredThreshold)) - { - heatingThreshold = configuredThreshold; - } + var boilerPowerEntityId = _boilerPowerEntityId; + var boilerSwitchEntityId = _boilerSwitchEntityId; while (currentTime <= _replayOptions.EndTime && !cancellationToken.IsCancellationRequested) { @@ -92,6 +75,7 @@ public sealed class BoilerReplayRunner : IMonitorReplayRunner var cheapEntry = _timeline.GetStateAt("sensor.nordpool_cheapest_intervals", currentTime); var skipPriceCapEntry = _timeline.GetStateAt(BoilerMonitorConsts.SkipPriceCapEntityId, currentTime); var budgetOverrideEntry = _timeline.GetStateAt(BoilerMonitorConsts.BudgetOverrideEntityId, currentTime); + var autoManagementEntry = _timeline.GetStateAt(BoilerMonitorConsts.AutoManagementEntityId, currentTime); var dailyHoursEntry = _timeline.GetStateAt(BoilerMonitorConsts.BoilerDailyHoursEntityId, currentTime); var boilerPowerWatts = ParseDouble(powerEntry?.State); @@ -100,9 +84,20 @@ public sealed class BoilerReplayRunner : IMonitorReplayRunner _tracker.RecordPollResult(isHeating, pollInterval); + if (isHeating) + { + _waterReadyService.RecordHeatingObserved(); + } + + if (boilerPowerWatts.HasValue) + { + _dataSeries.AddPoint(MonitorName, "PowerWatts", currentTime, boilerPowerWatts.Value); + } + var isNowCheap = ReadAttributeBool(cheapEntry, "is_now_cheap"); var skipPriceCap = string.Equals(skipPriceCapEntry?.State, "on", StringComparison.OrdinalIgnoreCase); var budgetOverride = string.Equals(budgetOverrideEntry?.State, "on", StringComparison.OrdinalIgnoreCase); + var autoManagementEnabled = !string.Equals(autoManagementEntry?.State, BoilerMonitorConsts.SwitchOffState, StringComparison.OrdinalIgnoreCase); var dailyHours = ParseDouble(dailyHoursEntry?.State) ?? 1.0; var waterReady = _waterReadyService.IsWaterReady(boilerSwitchState, boilerPowerWatts, heatingThreshold); @@ -126,9 +121,17 @@ public sealed class BoilerReplayRunner : IMonitorReplayRunner ? (snapshot.AccumulatedRunTime.TotalSeconds / budgetTimeSpan.TotalSeconds) * 100.0 : 0.0; + _dataSeries.AddPoint(MonitorName, "BudgetPercent", currentTime, budgetPercentage); + _dataSeries.AddPoint(MonitorName, "SwitchState", currentTime, + string.Equals(boilerSwitchState, "on", StringComparison.OrdinalIgnoreCase) ? 1.0 : 0.0); + var effectiveIsNowCheap = isNowCheap || skipPriceCap; var action = _boilerControlService.DetermineAction( - effectiveIsNowCheap, waterReady, boilerSwitchState, budgetExhausted, budgetOverride); + effectiveIsNowCheap, + waterReady, + boilerSwitchState, + budgetExhausted, + budgetOverride); if (action != BoilerAction.NoChange && action != lastAction) { @@ -139,18 +142,32 @@ public sealed class BoilerReplayRunner : IMonitorReplayRunner _ => action.ToString() }; - _replayTimeline.AddEvent(new ReplayEvent + if (autoManagementEnabled) { - Timestamp = currentTime, - Monitor = MonitorName, - EventType = ReplayEventType.Decision, - Message = actionMessage, - Details = $"Power: {boilerPowerWatts:F1}W, Runtime: {snapshot.AccumulatedRunTime:hh\\:mm\\:ss}, Sessions: {snapshot.SessionCount}" - }); + _replayTimeline.AddEvent(new ReplayEvent + { + Timestamp = currentTime, + Monitor = MonitorName, + EventType = ReplayEventType.Decision, + Message = actionMessage, + Details = $"Power: {boilerPowerWatts:F1}W, Runtime: {snapshot.AccumulatedRunTime:hh\\:mm\\:ss}, Sessions: {snapshot.SessionCount}" + }); - if (action == BoilerAction.TurnOn) + if (action == BoilerAction.TurnOn) + { + _waterReadyService.NotifyTurnedOn(); + } + } + else { - _waterReadyService.NotifyTurnedOn(); + _replayTimeline.AddEvent(new ReplayEvent + { + Timestamp = currentTime, + Monitor = MonitorName, + EventType = ReplayEventType.Decision, + Message = $"SUPPRESSED (auto control off): {actionMessage}", + Details = $"Power: {boilerPowerWatts:F1}W, Runtime: {snapshot.AccumulatedRunTime:hh\\:mm\\:ss}, Sessions: {snapshot.SessionCount}" + }); } } @@ -171,12 +188,6 @@ public sealed class BoilerReplayRunner : IMonitorReplayRunner return Task.CompletedTask; } - private string? ReadConfigEntityState(string entityId, DateTimeOffset timestamp) - { - var entry = _timeline.GetStateAt(entityId, timestamp); - return entry?.State; - } - private static bool ReadAttributeBool(HistoryStateEntry? entry, string attributeName) { if (entry?.Attributes is null) diff --git a/HomeAssistant.HistoryReplay/Runners/LightReplayRunner.cs b/HomeAssistant.HistoryReplay/Runners/LightReplayRunner.cs index 307c3c2..acdcb6b 100644 --- a/HomeAssistant.HistoryReplay/Runners/LightReplayRunner.cs +++ b/HomeAssistant.HistoryReplay/Runners/LightReplayRunner.cs @@ -14,6 +14,7 @@ public sealed class LightReplayRunner : IMonitorReplayRunner private readonly HistoryTimeline _timeline; private readonly ReplayTimeProvider _timeProvider; private readonly ReplayTimeline _replayTimeline; + private readonly ReplayDataSeries _dataSeries; private readonly ILogger _logger; private readonly ReplayOptions _replayOptions; private readonly LightMonitorOptions _lightOptions; @@ -24,6 +25,7 @@ public sealed class LightReplayRunner : IMonitorReplayRunner HistoryTimeline timeline, ReplayTimeProvider timeProvider, ReplayTimeline replayTimeline, + ReplayDataSeries dataSeries, ILogger logger, IOptions replayOptions, IOptions lightOptions) @@ -31,6 +33,7 @@ public sealed class LightReplayRunner : IMonitorReplayRunner _timeline = timeline; _timeProvider = timeProvider; _replayTimeline = replayTimeline; + _dataSeries = dataSeries; _logger = logger; _replayOptions = replayOptions.Value; _lightOptions = lightOptions.Value; @@ -54,14 +57,20 @@ public sealed class LightReplayRunner : IMonitorReplayRunner foreach (var entry in sunHistory) { - if (cancellationToken.IsCancellationRequested) break; + if (cancellationToken.IsCancellationRequested) + { + break; + } if (entry.LastChanged < _replayOptions.StartTime || entry.LastChanged > _replayOptions.EndTime) { continue; } - if (string.Equals(entry.State, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase) && + var isBelowHorizon = string.Equals(entry.State, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase); + _dataSeries.AddPoint(MonitorName, "SunBelowHorizon", entry.LastChanged, isBelowHorizon ? 1.0 : 0.0); + + if (isBelowHorizon && !string.Equals(previousSunState, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase)) { _timeProvider.AdvanceTo(entry.LastChanged); @@ -72,6 +81,7 @@ public sealed class LightReplayRunner : IMonitorReplayRunner if (anyoneHome && !lightAlreadyOn) { + _dataSeries.AddPoint(MonitorName, "LightOn", entry.LastChanged, 1.0); _replayTimeline.AddEvent(new ReplayEvent { Timestamp = entry.LastChanged, @@ -87,7 +97,7 @@ public sealed class LightReplayRunner : IMonitorReplayRunner Timestamp = entry.LastChanged, Monitor = MonitorName, EventType = ReplayEventType.Info, - Message = "Sun below horizon but nobody home — light stays off" + Message = "Sun below horizon but nobody home -- light stays off" }); } else @@ -115,7 +125,10 @@ public sealed class LightReplayRunner : IMonitorReplayRunner foreach (var entry in personHistory) { - if (cancellationToken.IsCancellationRequested) break; + if (cancellationToken.IsCancellationRequested) + { + break; + } if (entry.LastChanged < _replayOptions.StartTime || entry.LastChanged > _replayOptions.EndTime) { @@ -134,6 +147,7 @@ public sealed class LightReplayRunner : IMonitorReplayRunner if (isDark && !lightAlreadyOn) { + _dataSeries.AddPoint(MonitorName, "LightOn", entry.LastChanged, 1.0); _replayTimeline.AddEvent(new ReplayEvent { Timestamp = entry.LastChanged, @@ -169,7 +183,6 @@ public sealed class LightReplayRunner : IMonitorReplayRunner return true; } } - return false; } } diff --git a/HomeAssistant.HistoryReplay/Runners/NordPoolReplayRunner.cs b/HomeAssistant.HistoryReplay/Runners/NordPoolReplayRunner.cs index 52c9bb5..38f8370 100644 --- a/HomeAssistant.HistoryReplay/Runners/NordPoolReplayRunner.cs +++ b/HomeAssistant.HistoryReplay/Runners/NordPoolReplayRunner.cs @@ -16,16 +16,20 @@ public sealed class NordPoolReplayRunner : IMonitorReplayRunner private readonly HistoryTimeline _timeline; private readonly ReplayTimeProvider _timeProvider; private readonly ReplayTimeline _replayTimeline; + private readonly ReplayDataSeries _dataSeries; private readonly ICheapestIntervalsFinder _cheapestIntervalsFinder; private readonly ILogger _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) @@ -33,6 +37,7 @@ public sealed class NordPoolReplayRunner : IMonitorReplayRunner _timeline = timeline; _timeProvider = timeProvider; _replayTimeline = replayTimeline; + _dataSeries = dataSeries; _cheapestIntervalsFinder = cheapestIntervalsFinder; _logger = logger; _options = options.Value; @@ -50,11 +55,15 @@ public sealed class NordPoolReplayRunner : IMonitorReplayRunner { _timeProvider.AdvanceTo(currentTime); - var priceEntry = _timeline.GetStateAt(NordPoolConsts.CurrentPriceEntityId, currentTime); + var priceEntry = _timeline.GetStateAt(NordPoolHaSensorId, currentTime) + ?? _timeline.GetStateAt(NordPoolConsts.CurrentPriceEntityId, currentTime); + if (priceEntry?.State is not null && double.TryParse(priceEntry.State, CultureInfo.InvariantCulture, out var currentPrice)) { - if (lastReportedPrice is null || Math.Abs(currentPrice - lastReportedPrice.Value) > 0.001) + _dataSeries.AddPoint(MonitorName, "Price", currentTime, currentPrice); + + if (lastReportedPrice is null || Math.Abs(currentPrice - lastReportedPrice.Value) > 0.01) { _replayTimeline.AddEvent(new ReplayEvent { @@ -84,6 +93,8 @@ public sealed class NordPoolReplayRunner : IMonitorReplayRunner var isNowCheap = _cheapestIntervalsFinder.IsCurrentIntervalCheap( cheapest, currentTime.LocalDateTime); + _dataSeries.AddPoint(MonitorName, "IsCheap", currentTime, isNowCheap ? 1.0 : 0.0); + if (isNowCheap) { var currentInterval = cheapest.FirstOrDefault(i => diff --git a/HomeAssistant.HistoryReplay/Runners/PowerReplayRunner.cs b/HomeAssistant.HistoryReplay/Runners/PowerReplayRunner.cs index f871b38..49730d7 100644 --- a/HomeAssistant.HistoryReplay/Runners/PowerReplayRunner.cs +++ b/HomeAssistant.HistoryReplay/Runners/PowerReplayRunner.cs @@ -8,7 +8,6 @@ using Microsoft.Extensions.Options; using NordPool.Models; using PowerMonitorManager.Interface; using PowerMonitorManager.Models; -using PowerMonitorManager.Models.Consts; namespace HomeAssistant.HistoryReplay.Runners; @@ -17,6 +16,7 @@ public sealed class PowerReplayRunner : IMonitorReplayRunner private readonly HistoryTimeline _timeline; private readonly ReplayTimeProvider _timeProvider; private readonly ReplayTimeline _replayTimeline; + private readonly ReplayDataSeries _dataSeries; private readonly IOtherPowerCalculationService _calculationService; private readonly IPowerCostCalculationService _costService; private readonly ILogger _logger; @@ -29,6 +29,7 @@ public sealed class PowerReplayRunner : IMonitorReplayRunner HistoryTimeline timeline, ReplayTimeProvider timeProvider, ReplayTimeline replayTimeline, + ReplayDataSeries dataSeries, IOtherPowerCalculationService calculationService, IPowerCostCalculationService costService, ILogger logger, @@ -38,6 +39,7 @@ public sealed class PowerReplayRunner : IMonitorReplayRunner _timeline = timeline; _timeProvider = timeProvider; _replayTimeline = replayTimeline; + _dataSeries = dataSeries; _calculationService = calculationService; _costService = costService; _logger = logger; @@ -69,6 +71,10 @@ public sealed class PowerReplayRunner : IMonitorReplayRunner var deviceReadings = DiscoverAndReadDevicePower(currentTime); var calculation = _calculationService.Calculate(totalPower.Value, deviceReadings); + _dataSeries.AddPoint(MonitorName, "TotalPower", currentTime, calculation.TotalPowerWatts); + _dataSeries.AddPoint(MonitorName, "KnownDevices", currentTime, calculation.KnownDevicesSumWatts); + _dataSeries.AddPoint(MonitorName, "OtherPower", currentTime, calculation.SmoothedOtherPowerWatts); + var nordPoolPriceEntry = _timeline.GetStateAt(NordPoolConsts.CurrentPriceEntityId, currentTime); var nordPoolPrice = ParseDouble(nordPoolPriceEntry?.State) ?? 0; @@ -78,7 +84,6 @@ public sealed class PowerReplayRunner : IMonitorReplayRunner if (isAnomaly && anomalyStartTime is null) { anomalyStartTime = currentTime.LocalDateTime; - _replayTimeline.AddEvent(new ReplayEvent { Timestamp = currentTime, @@ -120,8 +125,8 @@ public sealed class PowerReplayRunner : IMonitorReplayRunner private IReadOnlyDictionary DiscoverAndReadDevicePower(DateTimeOffset timestamp) { var readings = new Dictionary(); - var allEntities = _timeline.GetEntityIds(); + foreach (var entityId in allEntities) { if (!entityId.StartsWith("sensor.", StringComparison.OrdinalIgnoreCase) || diff --git a/HomeAssistant.HistoryReplay/Runners/ShowerReplayRunner.cs b/HomeAssistant.HistoryReplay/Runners/ShowerReplayRunner.cs index b489bba..c819378 100644 --- a/HomeAssistant.HistoryReplay/Runners/ShowerReplayRunner.cs +++ b/HomeAssistant.HistoryReplay/Runners/ShowerReplayRunner.cs @@ -5,6 +5,7 @@ using HomeAssistant.HistoryReplay.Replay; using HomeAssistant.HistoryReplay.Reporting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; +using NetDaemon.HassModel; using ShowerMonitor.Models.Enums; using ShowerMonitorManager.Interface; using ShowerMonitorManager.Models; @@ -16,8 +17,10 @@ public sealed class ShowerReplayRunner : IMonitorReplayRunner private readonly HistoryTimeline _timeline; private readonly ReplayTimeProvider _timeProvider; private readonly ReplayTimeline _replayTimeline; + private readonly ReplayDataSeries _dataSeries; private readonly IShowerDetectionService _detectionService; private readonly IExhaustFanControlService _fanControlService; + private readonly IHaContext _haContext; private readonly ILogger _logger; private readonly ReplayOptions _replayOptions; private readonly ShowerMonitorOptions _showerOptions; @@ -28,8 +31,10 @@ public sealed class ShowerReplayRunner : IMonitorReplayRunner HistoryTimeline timeline, ReplayTimeProvider timeProvider, ReplayTimeline replayTimeline, + ReplayDataSeries dataSeries, IShowerDetectionService detectionService, IExhaustFanControlService fanControlService, + IHaContext haContext, ILogger logger, IOptions replayOptions, IOptions showerOptions) @@ -37,8 +42,10 @@ public sealed class ShowerReplayRunner : IMonitorReplayRunner _timeline = timeline; _timeProvider = timeProvider; _replayTimeline = replayTimeline; + _dataSeries = dataSeries; _detectionService = detectionService; _fanControlService = fanControlService; + _haContext = haContext; _logger = logger; _replayOptions = replayOptions.Value; _showerOptions = showerOptions.Value; @@ -64,10 +71,16 @@ public sealed class ShowerReplayRunner : IMonitorReplayRunner if (bathroomHumidity.HasValue && homeHumidity.HasValue) { + _dataSeries.AddPoint(MonitorName, "BathroomHumidity", currentTime, bathroomHumidity.Value); + _dataSeries.AddPoint(MonitorName, "HomeHumidity", currentTime, homeHumidity.Value); + _dataSeries.AddPoint(MonitorName, "Differential", currentTime, bathroomHumidity.Value - homeHumidity.Value); + var state = _detectionService.Evaluate(bathroomHumidity.Value, homeHumidity.Value, currentTime); var differential = bathroomHumidity.Value - homeHumidity.Value; - _fanControlService.Evaluate(state, currentTime); + _dataSeries.AddPoint(MonitorName, "State", currentTime, (double)state); + + _fanControlService.Evaluate(state, currentTime, _haContext); if (state != previousState) { @@ -83,7 +96,7 @@ public sealed class ShowerReplayRunner : IMonitorReplayRunner Timestamp = currentTime, Monitor = MonitorName, EventType = eventType, - Message = $"State: {previousState} → {state} (bathroom: {bathroomHumidity.Value:F1}%, home: {homeHumidity.Value:F1}%, diff: {differential:F1}%)", + Message = $"State: {previousState} -> {state} (bathroom: {bathroomHumidity.Value:F1}%, home: {homeHumidity.Value:F1}%, diff: {differential:F1}%)", Details = GetStateChangeDetails(state) }); diff --git a/HomeAssistant.HistoryReplay/Services/ReplayOrchestrationService.cs b/HomeAssistant.HistoryReplay/Services/ReplayOrchestrationService.cs new file mode 100644 index 0000000..0aa3d32 --- /dev/null +++ b/HomeAssistant.HistoryReplay/Services/ReplayOrchestrationService.cs @@ -0,0 +1,214 @@ +using BoilerMonitorManager; +using BoilerMonitorManager.Interface; +using PowerMonitorManager; +using ShowerMonitorManager; +using HomeAssistant.HistoryReplay.Configuration; +using HomeAssistant.HistoryReplay.HistoryData; +using HomeAssistant.HistoryReplay.Replay; +using HomeAssistant.HistoryReplay.Reporting; +using HomeAssistant.HistoryReplay.Runners; +using LightMonitorManager.Models; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using NordPoolManager.Interface; +using PowerMonitorManager.Interface; +using PowerMonitorManager.Models; +using ShowerMonitorManager.Interface; +using ShowerMonitorManager.Models; + +namespace HomeAssistant.HistoryReplay.Services; + +public sealed class ReplayOrchestrationService +{ + private readonly IHistoryDataProvider _historyProvider; + private readonly IServiceProvider _serviceProvider; + private readonly ILogger _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(showerOpts); + + runners.Add(new ShowerReplayRunner( + historyTimeline, timeProvider, Timeline, DataSeries, + detection, fan, replayHaContext, + _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 new file mode 100644 index 0000000..a0e622d --- /dev/null +++ b/HomeAssistant.HistoryReplay/Services/ReplayStatus.cs @@ -0,0 +1,10 @@ +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 index 4ec67a5..0360eec 100644 --- a/HomeAssistant.HistoryReplay/appsettings.json +++ b/HomeAssistant.HistoryReplay/appsettings.json @@ -6,13 +6,13 @@ "Ssl": false }, "Replay": { - "StartTime": "2026-03-30T00:00:00+02:00", + "StartTime": "2026-03-01T00:00:00+02:00", "EndTime": "2026-03-31T00:00:00+02:00", "Monitors": { "NordPool": true, "Boiler": true, "Shower": true, - "Power": false, + "Power": true, "Light": true } }, diff --git a/HomeAssistant.HistoryReplay/wwwroot/css/app.css b/HomeAssistant.HistoryReplay/wwwroot/css/app.css new file mode 100644 index 0000000..e6469ff --- /dev/null +++ b/HomeAssistant.HistoryReplay/wwwroot/css/app.css @@ -0,0 +1,57 @@ +body { + background-color: #1a1d21; + color: #e0e0e0; +} + +.card { + background-color: #212529; + border-color: #343a40; +} + +.card-header { + background-color: #2b3035; + border-bottom-color: #343a40; +} + +.stat-card { + text-align: center; + transition: transform 0.15s; +} + +.stat-card:hover { + transform: translateY(-2px); +} + +.stat-card .display-6 { + font-weight: 700; +} + +.badge-decision { background-color: #198754; } +.badge-statechange { background-color: #0dcaf0; color: #000; } +.badge-warning { background-color: #ffc107; color: #000; } +.badge-anomaly { background-color: #dc3545; } +.badge-servicecall { background-color: #6f42c1; } +.badge-info { background-color: #6c757d; } + +.nav-tabs .nav-link { + color: #adb5bd; +} + +.nav-tabs .nav-link.active { + background-color: #212529; + border-color: #495057 #495057 #212529; + color: #e0e0e0; +} + +.table { + --bs-table-bg: transparent; + --bs-table-color: #e0e0e0; +} + +.status-bar { + min-height: 40px; +} + +.apexcharts-canvas { + background: transparent !important; +} diff --git a/HomeAssistant.McpServer/HomeAssistant.McpServer.csproj b/HomeAssistant.McpServer/HomeAssistant.McpServer.csproj index 8e302aa..4596d92 100644 --- a/HomeAssistant.McpServer/HomeAssistant.McpServer.csproj +++ b/HomeAssistant.McpServer/HomeAssistant.McpServer.csproj @@ -10,6 +10,13 @@ + + PreserveNewest + + + + + diff --git a/HomeAssistant.McpServer/Program.cs b/HomeAssistant.McpServer/Program.cs index cddc8f5..95ae288 100644 --- a/HomeAssistant.McpServer/Program.cs +++ b/HomeAssistant.McpServer/Program.cs @@ -3,9 +3,12 @@ using HomeAssistant.McpServer.Settings; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; -using ModelContextProtocol.Server; -var builder = Host.CreateApplicationBuilder(args); +var builder = Host.CreateApplicationBuilder(new HostApplicationBuilderSettings +{ + Args = args, + ContentRootPath = AppContext.BaseDirectory +}); builder.Logging.AddConsole(options => { diff --git a/HomeAssistant.McpServer/Services/HomeAssistantApiClient.cs b/HomeAssistant.McpServer/Services/HomeAssistantApiClient.cs index c574ecc..3b3bdec 100644 --- a/HomeAssistant.McpServer/Services/HomeAssistantApiClient.cs +++ b/HomeAssistant.McpServer/Services/HomeAssistantApiClient.cs @@ -47,10 +47,14 @@ public sealed class HomeAssistantApiClient : IHomeAssistantApiClient var path = $"/api/history/period/{start:O}?filter_entity_id={Uri.EscapeDataString(entityIds)}"; if (endTime.HasValue) + { path += $"&end_time={Uri.EscapeDataString(endTime.Value.ToString("O"))}"; + } if (minimalResponse) + { path += "&minimal_response"; + } return GetJsonAsync(path, cancellationToken); } @@ -66,12 +70,19 @@ public sealed class HomeAssistantApiClient : IHomeAssistantApiClient 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); } diff --git a/HomeAssistant.McpServer/Tools/EntityStateTools.cs b/HomeAssistant.McpServer/Tools/EntityStateTools.cs index 9cac3e7..687a25a 100644 --- a/HomeAssistant.McpServer/Tools/EntityStateTools.cs +++ b/HomeAssistant.McpServer/Tools/EntityStateTools.cs @@ -37,7 +37,9 @@ public sealed class EntityStateTools 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) && @@ -78,12 +80,16 @@ public sealed class EntityStateTools 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; } diff --git a/HomeAssistant.McpServer/Tools/ServiceTools.cs b/HomeAssistant.McpServer/Tools/ServiceTools.cs index 4b47642..b8091c3 100644 --- a/HomeAssistant.McpServer/Tools/ServiceTools.cs +++ b/HomeAssistant.McpServer/Tools/ServiceTools.cs @@ -25,7 +25,9 @@ public sealed class ServiceTools 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) && @@ -54,7 +56,9 @@ public sealed class ServiceTools : JsonSerializer.Deserialize>(serviceData) ?? []; if (!string.IsNullOrWhiteSpace(entityId)) + { dataDict["entity_id"] = entityId; + } data = JsonSerializer.SerializeToElement(dataDict); } diff --git a/HomeAssistant.McpServer/Tools/ValidationTools.cs b/HomeAssistant.McpServer/Tools/ValidationTools.cs new file mode 100644 index 0000000..5d40748 --- /dev/null +++ b/HomeAssistant.McpServer/Tools/ValidationTools.cs @@ -0,0 +1,310 @@ +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 new file mode 100644 index 0000000..2c63c08 --- /dev/null +++ b/HomeAssistant.McpServer/appsettings.json @@ -0,0 +1,2 @@ +{ +} diff --git a/HomeAssistant.Server/HomeAssistant.Server.csproj b/HomeAssistant.Server/HomeAssistant.Server.csproj index 6eeb889..e4654cd 100644 --- a/HomeAssistant.Server/HomeAssistant.Server.csproj +++ b/HomeAssistant.Server/HomeAssistant.Server.csproj @@ -29,7 +29,7 @@ - + @@ -58,5 +58,6 @@ + diff --git a/HomeAssistant.Server/Properties/launchSettings.json b/HomeAssistant.Server/Properties/launchSettings.json index 94dd7ff..ca20e8a 100644 --- a/HomeAssistant.Server/Properties/launchSettings.json +++ b/HomeAssistant.Server/Properties/launchSettings.json @@ -4,8 +4,8 @@ "commandName": "Project", "workingDirectory": "$(ProjectDir)", "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development", - "DOTNET_ENVIRONMENT": "Development" + "ASPNETCORE_ENVIRONMENT": "development", + "DOTNET_ENVIRONMENT": "development" } } } diff --git a/HomeAssistant.Server/appsettings.json b/HomeAssistant.Server/appsettings.json index 773d9a2..a5b55ea 100644 --- a/HomeAssistant.Server/appsettings.json +++ b/HomeAssistant.Server/appsettings.json @@ -9,16 +9,13 @@ "BoilerMonitorManager": "Information", "ShowerMonitorManager": "Information", "LightMonitorManager": "Information", - "BatteryMonitorManager": "Information" + "BatteryMonitorManager": "Information", + "LeakMonitorManager": "Information" } }, "WriteTo": [ { - "Name": "Console", - "Args": { - "theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Code, Serilog.Sinks.Console", - "outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} {NewLine}{Exception}" - } + "Name": "Console" } ] }, @@ -58,18 +55,27 @@ "Enabled": true, "LightEntityId": "light.sonoff_1002214d40", "SunEntityId": "sun.sun", - "PersonEntityIds": ["person.marius", "person.erika", "person.home_phone"] + "PersonEntityIds": ["person.marius", "person.erika"] }, "BatteryMonitor": { "Enabled": true, "BatteryThresholdPercent": 5 }, + "LeakMonitor": { + "Enabled": true, + "SensorEntityIds": [ + "binary_sensor.aquarium_leak_sensor", + "binary_sensor.boiler_moisture" + ], + "NotificationCooldownMinutes": 5 + }, "PowerMonitor": { "Enabled": false, "MainMeterEntityId": "sensor.sonoff_100267d63f_power", "PollIntervalSeconds": 1, "SmoothingWindowSize": 10, - "AnomalyThresholdWatts": 500, + "AnomalyThresholdWatts": 500, + "HighPowerThresholdWatts": 6000, "ExcludedSensorPatterns": [ "sensor.nordpool_*", "sensor.powermonitor_*" diff --git a/HomeAssistant.Server/program.cs b/HomeAssistant.Server/program.cs index 565c88b..163c2e5 100644 --- a/HomeAssistant.Server/program.cs +++ b/HomeAssistant.Server/program.cs @@ -25,17 +25,18 @@ using LightMonitorManager; using LightMonitorManager.Models; using BatteryMonitorManager; using BatteryMonitorManager.Models; - -#pragma warning disable CA1812 +using LeakMonitorManager; +using LeakMonitorManager.Models; try { - await Host.CreateDefaultBuilder(args) + var app = Host.CreateDefaultBuilder(args) .UseNetDaemonAppSettings() .UseCustomLogging() .UseNetDaemonRuntime() .UseNetDaemonTextToSpeech() .ConfigureServices((context, services) => + { services .AddNetDaemonMqttEntityManagement() .AddAppsFromAssembly(Assembly.GetExecutingAssembly()) @@ -55,6 +56,7 @@ try .AddScoped() .AddTransient() .AddSingleton() + .AddScoped() .Configure(context.Configuration.GetSection(PowerMonitorOptions.SectionName)) .AddPowerMonitor(context.Configuration) .Configure(context.Configuration.GetSection(BoilerMonitorOptions.SectionName)) @@ -65,10 +67,12 @@ try .AddLightMonitor(context.Configuration) .Configure(context.Configuration.GetSection(BatteryMonitorOptions.SectionName)) .AddBatteryMonitor(context.Configuration) - ) - .Build() - .RunAsync() - .ConfigureAwait(false); + .Configure(context.Configuration.GetSection(LeakMonitorOptions.SectionName)) + .AddLeakMonitor(context.Configuration); + }) + .Build(); + + await app.RunAsync().ConfigureAwait(false); } catch (Exception e) { diff --git a/HomeAssistantSDK.sln b/HomeAssistantSDK.sln index 1fbb38c..f239f73 100644 --- a/HomeAssistantSDK.sln +++ b/HomeAssistantSDK.sln @@ -52,6 +52,12 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BatteryMonitor.Manager", "B EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BatteryMonitor.Manager.Tests", "BatteryMonitor.Manager.Tests\BatteryMonitor.Manager.Tests.csproj", "{2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LeakMonitor.Models", "LeakMonitor.Models\LeakMonitor.Models.csproj", "{590B5855-07CB-4D04-8602-04ECE53D2A2B}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LeakMonitor.Manager", "LeakMonitor.Manager\LeakMonitor.Manager.csproj", "{6830DB0A-9D94-4B52-A0A1-7593E4971FF7}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LeakMonitor.Manager.Tests", "LeakMonitor.Manager.Tests\LeakMonitor.Manager.Tests.csproj", "{D56BE1F2-830C-43DB-87A8-A659192984FC}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -219,17 +225,11 @@ Global {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|Any CPU.Build.0 = Debug|Any CPU {AF78DBE2-9DDA-4ABD-934A-97DC9376D371}.Debug|x64.ActiveCfg = Debug|Any CPU - {AF78DBE2-9DDA-4ABD-934A-97DC9376D371}.Debug|x64.Build.0 = Debug|Any CPU {AF78DBE2-9DDA-4ABD-934A-97DC9376D371}.Debug|x86.ActiveCfg = Debug|Any CPU - {AF78DBE2-9DDA-4ABD-934A-97DC9376D371}.Debug|x86.Build.0 = Debug|Any CPU {AF78DBE2-9DDA-4ABD-934A-97DC9376D371}.Release|Any CPU.ActiveCfg = Release|Any CPU - {AF78DBE2-9DDA-4ABD-934A-97DC9376D371}.Release|Any CPU.Build.0 = Release|Any CPU {AF78DBE2-9DDA-4ABD-934A-97DC9376D371}.Release|x64.ActiveCfg = Release|Any CPU - {AF78DBE2-9DDA-4ABD-934A-97DC9376D371}.Release|x64.Build.0 = Release|Any CPU {AF78DBE2-9DDA-4ABD-934A-97DC9376D371}.Release|x86.ActiveCfg = Release|Any CPU - {AF78DBE2-9DDA-4ABD-934A-97DC9376D371}.Release|x86.Build.0 = 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 @@ -350,6 +350,42 @@ Global {2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0}.Release|x64.Build.0 = Release|Any CPU {2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0}.Release|x86.ActiveCfg = Release|Any CPU {2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0}.Release|x86.Build.0 = Release|Any CPU + {590B5855-07CB-4D04-8602-04ECE53D2A2B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {590B5855-07CB-4D04-8602-04ECE53D2A2B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {590B5855-07CB-4D04-8602-04ECE53D2A2B}.Debug|x64.ActiveCfg = Debug|Any CPU + {590B5855-07CB-4D04-8602-04ECE53D2A2B}.Debug|x64.Build.0 = Debug|Any CPU + {590B5855-07CB-4D04-8602-04ECE53D2A2B}.Debug|x86.ActiveCfg = Debug|Any CPU + {590B5855-07CB-4D04-8602-04ECE53D2A2B}.Debug|x86.Build.0 = Debug|Any CPU + {590B5855-07CB-4D04-8602-04ECE53D2A2B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {590B5855-07CB-4D04-8602-04ECE53D2A2B}.Release|Any CPU.Build.0 = Release|Any CPU + {590B5855-07CB-4D04-8602-04ECE53D2A2B}.Release|x64.ActiveCfg = Release|Any CPU + {590B5855-07CB-4D04-8602-04ECE53D2A2B}.Release|x64.Build.0 = Release|Any CPU + {590B5855-07CB-4D04-8602-04ECE53D2A2B}.Release|x86.ActiveCfg = Release|Any CPU + {590B5855-07CB-4D04-8602-04ECE53D2A2B}.Release|x86.Build.0 = Release|Any CPU + {6830DB0A-9D94-4B52-A0A1-7593E4971FF7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6830DB0A-9D94-4B52-A0A1-7593E4971FF7}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6830DB0A-9D94-4B52-A0A1-7593E4971FF7}.Debug|x64.ActiveCfg = Debug|Any CPU + {6830DB0A-9D94-4B52-A0A1-7593E4971FF7}.Debug|x64.Build.0 = Debug|Any CPU + {6830DB0A-9D94-4B52-A0A1-7593E4971FF7}.Debug|x86.ActiveCfg = Debug|Any CPU + {6830DB0A-9D94-4B52-A0A1-7593E4971FF7}.Debug|x86.Build.0 = Debug|Any CPU + {6830DB0A-9D94-4B52-A0A1-7593E4971FF7}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6830DB0A-9D94-4B52-A0A1-7593E4971FF7}.Release|Any CPU.Build.0 = Release|Any CPU + {6830DB0A-9D94-4B52-A0A1-7593E4971FF7}.Release|x64.ActiveCfg = Release|Any CPU + {6830DB0A-9D94-4B52-A0A1-7593E4971FF7}.Release|x64.Build.0 = Release|Any CPU + {6830DB0A-9D94-4B52-A0A1-7593E4971FF7}.Release|x86.ActiveCfg = Release|Any CPU + {6830DB0A-9D94-4B52-A0A1-7593E4971FF7}.Release|x86.Build.0 = Release|Any CPU + {D56BE1F2-830C-43DB-87A8-A659192984FC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D56BE1F2-830C-43DB-87A8-A659192984FC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D56BE1F2-830C-43DB-87A8-A659192984FC}.Debug|x64.ActiveCfg = Debug|Any CPU + {D56BE1F2-830C-43DB-87A8-A659192984FC}.Debug|x64.Build.0 = Debug|Any CPU + {D56BE1F2-830C-43DB-87A8-A659192984FC}.Debug|x86.ActiveCfg = Debug|Any CPU + {D56BE1F2-830C-43DB-87A8-A659192984FC}.Debug|x86.Build.0 = Debug|Any CPU + {D56BE1F2-830C-43DB-87A8-A659192984FC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D56BE1F2-830C-43DB-87A8-A659192984FC}.Release|Any CPU.Build.0 = Release|Any CPU + {D56BE1F2-830C-43DB-87A8-A659192984FC}.Release|x64.ActiveCfg = Release|Any CPU + {D56BE1F2-830C-43DB-87A8-A659192984FC}.Release|x64.Build.0 = Release|Any CPU + {D56BE1F2-830C-43DB-87A8-A659192984FC}.Release|x86.ActiveCfg = Release|Any CPU + {D56BE1F2-830C-43DB-87A8-A659192984FC}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -362,7 +398,13 @@ Global {1F613F65-5F3C-41E6-B86B-774301D80E42} = {95E98121-7DA4-4085-A8E3-B0430628452F} {72331F53-884D-42A1-8EEA-8CC83FFAB623} = {48492269-2B47-43FE-BC14-A901054EE5AE} {CFF799B9-A8E7-46C8-B4FD-721B7308FA9C} = {95E98121-7DA4-4085-A8E3-B0430628452F} + {DAD0BDF9-2A6D-48AD-B714-38D237E97285} = {48492269-2B47-43FE-BC14-A901054EE5AE} + {A9DFB47D-7736-428C-9459-22AFC5CF3A38} = {95E98121-7DA4-4085-A8E3-B0430628452F} {B14E51EB-7D5C-44FA-8674-4B4796459978} = {48492269-2B47-43FE-BC14-A901054EE5AE} {B8303C3E-785C-48F0-8F40-D4A9E9D50C92} = {95E98121-7DA4-4085-A8E3-B0430628452F} + {2D27B621-7B92-4014-8FDF-6AD376C97612} = {48492269-2B47-43FE-BC14-A901054EE5AE} + {2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0} = {95E98121-7DA4-4085-A8E3-B0430628452F} + {590B5855-07CB-4D04-8602-04ECE53D2A2B} = {48492269-2B47-43FE-BC14-A901054EE5AE} + {D56BE1F2-830C-43DB-87A8-A659192984FC} = {95E98121-7DA4-4085-A8E3-B0430628452F} EndGlobalSection EndGlobal diff --git a/LeakMonitor.Manager.Tests/LeakMonitor.Manager.Tests.csproj b/LeakMonitor.Manager.Tests/LeakMonitor.Manager.Tests.csproj new file mode 100644 index 0000000..b254b3c --- /dev/null +++ b/LeakMonitor.Manager.Tests/LeakMonitor.Manager.Tests.csproj @@ -0,0 +1,34 @@ + + + + net10.0 + enable + enable + false + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + + + diff --git a/LeakMonitor.Manager.Tests/LeakMonitorInitTests.cs b/LeakMonitor.Manager.Tests/LeakMonitorInitTests.cs new file mode 100644 index 0000000..e28285a --- /dev/null +++ b/LeakMonitor.Manager.Tests/LeakMonitorInitTests.cs @@ -0,0 +1,112 @@ +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using Moq; +using NetDaemon.HassModel; +using NetDaemon.HassModel.Entities; +using LeakMonitor.Models; +using LeakMonitorManager; +using LeakMonitorManager.Interface; +using LeakMonitorManager.Models; + +namespace LeakMonitor.Manager.Tests; + +public class LeakMonitorInitTests +{ + private readonly Mock _haContextMock; + private readonly Mock _notificationServiceMock; + private readonly Mock> _loggerMock; + private readonly LeakMonitorOptions _options; + + public LeakMonitorInitTests() + { + _haContextMock = new Mock(); + _notificationServiceMock = new Mock(); + _loggerMock = new Mock>(); + _options = new LeakMonitorOptions + { + Enabled = true, + SensorEntityIds = ["binary_sensor.aquarium_leak_sensor", "binary_sensor.boiler_moisture"] + }; + } + + private LeakMonitorInit CreateSut() + { + return new LeakMonitorInit( + _haContextMock.Object, + _notificationServiceMock.Object, + _loggerMock.Object, + Options.Create(_options)); + } + + #region HandleStateChange + + [Fact] + public void HandleStateChange_WaterDetected_ShouldSendLeakAlert() + { + var sut = CreateSut(); + var change = CreateStateChange("off", LeakMonitorConsts.WaterDetectedState); + + sut.HandleStateChange("binary_sensor.aquarium_leak_sensor", change); + + _notificationServiceMock.Verify( + n => n.SendLeakAlert("binary_sensor.aquarium_leak_sensor"), + Times.Once); + } + + [Fact] + public void HandleStateChange_WaterCleared_ShouldDismissLeakAlert() + { + var sut = CreateSut(); + var change = CreateStateChange("on", LeakMonitorConsts.WaterClearedState); + + sut.HandleStateChange("binary_sensor.aquarium_leak_sensor", change); + + _notificationServiceMock.Verify( + n => n.DismissLeakAlert("binary_sensor.aquarium_leak_sensor"), + Times.Once); + } + + [Fact] + public void HandleStateChange_UnknownState_ShouldNotNotify() + { + var sut = CreateSut(); + var change = CreateStateChange("off", "unavailable"); + + sut.HandleStateChange("binary_sensor.aquarium_leak_sensor", change); + + _notificationServiceMock.Verify( + n => n.SendLeakAlert(It.IsAny()), + Times.Never); + _notificationServiceMock.Verify( + n => n.DismissLeakAlert(It.IsAny()), + Times.Never); + } + + [Fact] + public void HandleStateChange_CaseInsensitive_ShouldDetectWater() + { + var sut = CreateSut(); + var change = CreateStateChange("off", "ON"); + + sut.HandleStateChange("binary_sensor.boiler_moisture", change); + + _notificationServiceMock.Verify( + n => n.SendLeakAlert("binary_sensor.boiler_moisture"), + Times.Once); + } + + #endregion + + private StateChange CreateStateChange(string? oldState, string? newState) + { + var entity = new Entity(_haContextMock.Object, "binary_sensor.test"); + var oldEntityState = oldState is not null + ? new EntityState { State = oldState } + : null; + var newEntityState = newState is not null + ? new EntityState { State = newState } + : null; + + return new StateChange(entity, oldEntityState, newEntityState); + } +} diff --git a/LeakMonitor.Manager.Tests/LeakNotificationServiceTests.cs b/LeakMonitor.Manager.Tests/LeakNotificationServiceTests.cs new file mode 100644 index 0000000..1f6e48a --- /dev/null +++ b/LeakMonitor.Manager.Tests/LeakNotificationServiceTests.cs @@ -0,0 +1,155 @@ +using FluentAssertions; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using Moq; +using NetDaemon.HassModel; +using NetDaemon.HassModel.Entities; +using LeakMonitor.Models; +using LeakMonitorManager; +using LeakMonitorManager.Models; + +namespace LeakMonitor.Manager.Tests; + +public class LeakNotificationServiceTests +{ + private readonly Mock _haContextMock; + private readonly Mock> _loggerMock; + private readonly LeakMonitorOptions _options; + + public LeakNotificationServiceTests() + { + _haContextMock = new Mock(); + _loggerMock = new Mock>(); + _options = new LeakMonitorOptions + { + Enabled = true, + NotificationCooldownMinutes = LeakMonitorConsts.DefaultNotificationCooldownMinutes + }; + } + + private LeakNotificationService CreateSut() + { + return new LeakNotificationService( + _haContextMock.Object, + _loggerMock.Object, + Options.Create(_options)); + } + + #region SendLeakAlert + + [Fact] + public void SendLeakAlert_ShouldCallMobileNotifyService() + { + var sut = CreateSut(); + + sut.SendLeakAlert("binary_sensor.aquarium_leak_sensor"); + + _haContextMock.Verify(h => h.CallService( + LeakMonitorConsts.NotifyDomain, + LeakMonitorConsts.MobileAppService, + It.IsAny(), + It.IsAny()), Times.Once); + } + + [Fact] + public void SendLeakAlert_ShouldCallPersistentNotificationCreate() + { + var sut = CreateSut(); + + sut.SendLeakAlert("binary_sensor.aquarium_leak_sensor"); + + _haContextMock.Verify(h => h.CallService( + LeakMonitorConsts.PersistentNotificationDomain, + LeakMonitorConsts.PersistentNotificationCreateService, + It.IsAny(), + It.IsAny()), Times.Once); + } + + [Fact] + public void SendLeakAlert_CalledTwiceWithinCooldown_ShouldOnlyNotifyOnce() + { + var sut = CreateSut(); + const string sensorId = "binary_sensor.aquarium_leak_sensor"; + + sut.SendLeakAlert(sensorId); + sut.SendLeakAlert(sensorId); + + _haContextMock.Verify(h => h.CallService( + LeakMonitorConsts.NotifyDomain, + LeakMonitorConsts.MobileAppService, + It.IsAny(), + It.IsAny()), Times.Once); + } + + [Fact] + public void SendLeakAlert_DifferentSensors_ShouldNotifyForEach() + { + var sut = CreateSut(); + + sut.SendLeakAlert("binary_sensor.aquarium_leak_sensor"); + sut.SendLeakAlert("binary_sensor.boiler_moisture"); + + _haContextMock.Verify(h => h.CallService( + LeakMonitorConsts.NotifyDomain, + LeakMonitorConsts.MobileAppService, + It.IsAny(), + It.IsAny()), Times.Exactly(2)); + } + + [Fact] + public void SendLeakAlert_WithZeroCooldown_ShouldAlwaysNotify() + { + _options.NotificationCooldownMinutes = 0; + var sut = CreateSut(); + const string sensorId = "binary_sensor.aquarium_leak_sensor"; + + sut.SendLeakAlert(sensorId); + sut.SendLeakAlert(sensorId); + + _haContextMock.Verify(h => h.CallService( + LeakMonitorConsts.NotifyDomain, + LeakMonitorConsts.MobileAppService, + It.IsAny(), + It.IsAny()), Times.Exactly(2)); + } + + #endregion + + #region DismissLeakAlert + + [Fact] + public void DismissLeakAlert_ShouldCallPersistentNotificationDismiss() + { + var sut = CreateSut(); + + sut.DismissLeakAlert("binary_sensor.aquarium_leak_sensor"); + + _haContextMock.Verify(h => h.CallService( + LeakMonitorConsts.PersistentNotificationDomain, + LeakMonitorConsts.PersistentNotificationDismissService, + It.IsAny(), + It.IsAny()), Times.Once); + } + + #endregion + + #region BuildNotificationId + + [Fact] + public void BuildNotificationId_ShouldReplaceDotsWithUnderscores() + { + var result = LeakNotificationService.BuildNotificationId("binary_sensor.aquarium_leak_sensor"); + + result.Should().Be("leak_monitor_binary_sensor_aquarium_leak_sensor"); + } + + [Fact] + public void BuildNotificationId_ShouldStartWithPrefix() + { + var result = LeakNotificationService.BuildNotificationId("binary_sensor.boiler_moisture"); + + result.Should().StartWith(LeakMonitorConsts.NotificationIdPrefix); + } + + #endregion +} diff --git a/LeakMonitor.Manager/Interface/ILeakMonitorInit.cs b/LeakMonitor.Manager/Interface/ILeakMonitorInit.cs new file mode 100644 index 0000000..631d898 --- /dev/null +++ b/LeakMonitor.Manager/Interface/ILeakMonitorInit.cs @@ -0,0 +1,6 @@ +namespace LeakMonitorManager.Interface; + +public interface ILeakMonitorInit +{ + Task InitializeAsync(); +} diff --git a/LeakMonitor.Manager/Interface/ILeakNotificationService.cs b/LeakMonitor.Manager/Interface/ILeakNotificationService.cs new file mode 100644 index 0000000..57bdd0c --- /dev/null +++ b/LeakMonitor.Manager/Interface/ILeakNotificationService.cs @@ -0,0 +1,8 @@ +namespace LeakMonitorManager.Interface; + +public interface ILeakNotificationService +{ + void SendLeakAlert(string sensorEntityId); + + void DismissLeakAlert(string sensorEntityId); +} diff --git a/LeakMonitor.Manager/LeakMonitor.Manager.csproj b/LeakMonitor.Manager/LeakMonitor.Manager.csproj new file mode 100644 index 0000000..dd8b140 --- /dev/null +++ b/LeakMonitor.Manager/LeakMonitor.Manager.csproj @@ -0,0 +1,27 @@ + + + + net10.0 + enable + enable + LeakMonitorManager + + + + + <_Parameter1>LeakMonitor.Manager.Tests + + + + + + + + + + + + + + + diff --git a/LeakMonitor.Manager/LeakMonitorInit.cs b/LeakMonitor.Manager/LeakMonitorInit.cs new file mode 100644 index 0000000..c185de3 --- /dev/null +++ b/LeakMonitor.Manager/LeakMonitorInit.cs @@ -0,0 +1,96 @@ +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using NetDaemon.AppModel; +using NetDaemon.HassModel; +using NetDaemon.HassModel.Entities; +using LeakMonitor.Models; +using LeakMonitorManager.Interface; +using LeakMonitorManager.Models; + +namespace LeakMonitorManager; + +[NetDaemonApp] +public sealed class LeakMonitorInit : ILeakMonitorInit +{ + private readonly IHaContext _haContext; + private readonly ILeakNotificationService _notificationService; + private readonly ILogger _logger; + private readonly LeakMonitorOptions _options; + + public LeakMonitorInit( + IHaContext haContext, + ILeakNotificationService notificationService, + ILogger logger, + IOptions options) + { + _haContext = haContext; + _notificationService = notificationService; + _logger = logger; + _options = options.Value; + + _ = InitializeAsync(); + } + + public Task InitializeAsync() + { + try + { + if (_options.SensorEntityIds.Length == 0) + { + _logger.LogWarning("LeakMonitor enabled but no sensor entity IDs configured"); + return Task.CompletedTask; + } + + foreach (var sensorEntityId in _options.SensorEntityIds) + { + SubscribeToLeakSensor(sensorEntityId); + } + + _logger.LogInformation( + "LeakMonitor initialized, monitoring {Count} sensor(s)", + _options.SensorEntityIds.Length); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error during LeakMonitor initialization"); + } + + return Task.CompletedTask; + } + + private void SubscribeToLeakSensor(string sensorEntityId) + { + var entity = new Entity(_haContext, sensorEntityId); + + entity.StateChanges() + .Subscribe(change => + { + try + { + HandleStateChange(sensorEntityId, change); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error handling state change for {SensorId}", sensorEntityId); + } + }); + + _logger.LogInformation("Subscribed to leak sensor {SensorId}", sensorEntityId); + } + + internal void HandleStateChange(string sensorEntityId, StateChange change) + { + var newState = change.New?.State; + + 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 new file mode 100644 index 0000000..9f5338c --- /dev/null +++ b/LeakMonitor.Manager/LeakMonitorServiceRegistration.cs @@ -0,0 +1,28 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using NetDaemon.AppModel; +using LeakMonitorManager.Interface; +using LeakMonitorManager.Models; + +namespace LeakMonitorManager; + +public static class LeakMonitorServiceRegistration +{ + public static IServiceCollection AddLeakMonitor(this IServiceCollection services, IConfiguration configuration) + { + var options = configuration + .GetSection(LeakMonitorOptions.SectionName) + .Get() ?? new LeakMonitorOptions(); + + if (!options.Enabled) + { + return services; + } + + services + .AddNetDaemonApp() + .AddScoped(); + + return services; + } +} diff --git a/LeakMonitor.Manager/LeakNotificationService.cs b/LeakMonitor.Manager/LeakNotificationService.cs new file mode 100644 index 0000000..6406762 --- /dev/null +++ b/LeakMonitor.Manager/LeakNotificationService.cs @@ -0,0 +1,113 @@ +using System.Collections.Concurrent; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using NetDaemon.HassModel; +using LeakMonitor.Models; +using LeakMonitorManager.Interface; +using LeakMonitorManager.Models; + +namespace LeakMonitorManager; + +public sealed class LeakNotificationService : ILeakNotificationService +{ + private readonly IHaContext _haContext; + private readonly ILogger _logger; + private readonly LeakMonitorOptions _options; + private readonly ConcurrentDictionary _lastNotificationTimes = new(); + + public LeakNotificationService( + IHaContext haContext, + ILogger logger, + IOptions options) + { + _haContext = haContext; + _logger = logger; + _options = options.Value; + } + + public void SendLeakAlert(string sensorEntityId) + { + if (IsWithinCooldown(sensorEntityId)) + { + _logger.LogDebug( + "Skipping leak notification for {SensorId} -- within cooldown period", + sensorEntityId); + return; + } + + _lastNotificationTimes[sensorEntityId] = DateTimeOffset.UtcNow; + + var notificationId = BuildNotificationId(sensorEntityId); + var message = $"Water detected by {sensorEntityId}! Check immediately."; + + SendMobilePushNotification(message); + CreatePersistentNotification(notificationId, message); + + _logger.LogWarning("Leak alert sent for sensor {SensorId}", sensorEntityId); + } + + public void DismissLeakAlert(string sensorEntityId) + { + var notificationId = BuildNotificationId(sensorEntityId); + + _haContext.CallService( + LeakMonitorConsts.PersistentNotificationDomain, + LeakMonitorConsts.PersistentNotificationDismissService, + data: new { notification_id = notificationId }); + + _logger.LogInformation("Leak alert dismissed for sensor {SensorId}", sensorEntityId); + } + + private void SendMobilePushNotification(string message) + { + _haContext.CallService( + LeakMonitorConsts.NotifyDomain, + LeakMonitorConsts.MobileAppService, + data: new + { + message, + title = LeakMonitorConsts.NotificationTitle, + data = new + { + push = new + { + sound = new + { + critical = 1, + volume = 1.0 + } + } + } + }); + } + + private void CreatePersistentNotification(string notificationId, string message) + { + _haContext.CallService( + LeakMonitorConsts.PersistentNotificationDomain, + LeakMonitorConsts.PersistentNotificationCreateService, + data: new + { + title = LeakMonitorConsts.NotificationTitle, + message, + notification_id = notificationId + }); + } + + private bool IsWithinCooldown(string sensorEntityId) + { + if (!_lastNotificationTimes.TryGetValue(sensorEntityId, out var lastTime)) + { + return false; + } + + var cooldown = TimeSpan.FromMinutes(_options.NotificationCooldownMinutes); + return DateTimeOffset.UtcNow - lastTime < cooldown; + } + + internal static string BuildNotificationId(string sensorEntityId) + { + var sanitized = sensorEntityId.Replace('.', '_'); + return $"{LeakMonitorConsts.NotificationIdPrefix}{sanitized}"; + } +} diff --git a/LeakMonitor.Manager/Models/LeakMonitorOptions.cs b/LeakMonitor.Manager/Models/LeakMonitorOptions.cs new file mode 100644 index 0000000..00fb037 --- /dev/null +++ b/LeakMonitor.Manager/Models/LeakMonitorOptions.cs @@ -0,0 +1,14 @@ +using LeakMonitor.Models; + +namespace LeakMonitorManager.Models; + +public sealed class LeakMonitorOptions +{ + public const string SectionName = "LeakMonitor"; + + public bool Enabled { get; set; } + + public string[] SensorEntityIds { get; set; } = []; + + public int NotificationCooldownMinutes { get; set; } = LeakMonitorConsts.DefaultNotificationCooldownMinutes; +} diff --git a/LeakMonitor.Models/LeakMonitor.Models.csproj b/LeakMonitor.Models/LeakMonitor.Models.csproj new file mode 100644 index 0000000..35fad31 --- /dev/null +++ b/LeakMonitor.Models/LeakMonitor.Models.csproj @@ -0,0 +1,10 @@ + + + + net10.0 + enable + enable + LeakMonitor.Models + + + diff --git a/LeakMonitor.Models/LeakMonitorConsts.cs b/LeakMonitor.Models/LeakMonitorConsts.cs new file mode 100644 index 0000000..982a8c8 --- /dev/null +++ b/LeakMonitor.Models/LeakMonitorConsts.cs @@ -0,0 +1,26 @@ +namespace LeakMonitor.Models; + +public static class LeakMonitorConsts +{ + public const string WaterDetectedState = "on"; + + public const string WaterClearedState = "off"; + + public const string NotifyDomain = "notify"; + + public const string MobileAppService = "mobile_app_marius_phone"; + + public const string PersistentNotificationDomain = "persistent_notification"; + + public const string PersistentNotificationCreateService = "create"; + + public const string PersistentNotificationDismissService = "dismiss"; + + public const string NotificationIdPrefix = "leak_monitor_"; + + public const string NotificationTitle = "Water Leak Detected!"; + + public const string DismissTitle = "Water Leak Cleared"; + + public const int DefaultNotificationCooldownMinutes = 5; +} diff --git a/LightMonitor.Manager.Tests/LightMonitorInitTests.cs b/LightMonitor.Manager.Tests/LightMonitorInitTests.cs new file mode 100644 index 0000000..5ec39af --- /dev/null +++ b/LightMonitor.Manager.Tests/LightMonitorInitTests.cs @@ -0,0 +1,167 @@ +using System.Reactive.Subjects; +using LightMonitor.Models; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using Moq; +using NetDaemon.HassModel; +using NetDaemon.HassModel.Entities; +using LightMonitorManager; +using LightMonitorManager.Interface; +using LightMonitorManager.Models; + +namespace LightMonitor.Manager.Tests; + +public class LightMonitorInitTests +{ + private const string SunEntityId = "sun.sun"; + private const string PersonEntityId = "person.marius"; + + private readonly Mock _haContextMock = new(); + private readonly Mock _presenceServiceMock = new(); + private readonly Mock _lightControlServiceMock = new(); + private readonly Subject _stateChangesSubject = new(); + + private readonly LightMonitorOptions _defaultOptions = new() + { + Enabled = true, + SunEntityId = SunEntityId, + PersonEntityIds = [PersonEntityId] + }; + + private LightMonitorInit CreateSut(LightMonitorOptions? options = null) + { + _haContextMock.Setup(x => x.StateAllChanges()) + .Returns(_stateChangesSubject); + + return new LightMonitorInit( + _haContextMock.Object, + Mock.Of>(), + _presenceServiceMock.Object, + _lightControlServiceMock.Object, + Options.Create(options ?? _defaultOptions)); + } + + private void EmitStateChange(string entityId, string? oldState, string? newState) + { + var entity = new Entity(_haContextMock.Object, entityId); + var old = oldState is not null ? new EntityState { State = oldState } : null; + var @new = newState is not null ? new EntityState { State = newState } : null; + + _stateChangesSubject.OnNext(new StateChange(entity, old, @new)); + } + + [Fact] + public void PersonStateChange_FromNotHomeToHome_ShouldCallTurnOnLight() + { + CreateSut(); + + EmitStateChange(PersonEntityId, "not_home", LightMonitorConsts.PersonHomeState); + + _lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Once); + } + + [Fact] + public void PersonStateChange_FromUnavailableToHome_ShouldNotCallTurnOnLight() + { + CreateSut(); + + EmitStateChange(PersonEntityId, LightMonitorConsts.UnavailableState, LightMonitorConsts.PersonHomeState); + + _lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Never); + } + + [Fact] + public void PersonStateChange_FromUnknownToHome_ShouldNotCallTurnOnLight() + { + CreateSut(); + + EmitStateChange(PersonEntityId, LightMonitorConsts.UnknownState, LightMonitorConsts.PersonHomeState); + + _lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Never); + } + + [Fact] + public void PersonStateChange_FromNullToHome_ShouldNotCallTurnOnLight() + { + CreateSut(); + + EmitStateChange(PersonEntityId, null, LightMonitorConsts.PersonHomeState); + + _lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Never); + } + + [Fact] + public void PersonStateChange_FromNotHomeToNotHome_ShouldNotCallTurnOnLight() + { + CreateSut(); + + EmitStateChange(PersonEntityId, "not_home", "not_home"); + + _lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Never); + } + + [Fact] + public void SunStateChange_FromAboveHorizonToBelowHorizon_WhenSomeoneIsHome_ShouldCallTurnOnLight() + { + _presenceServiceMock.Setup(x => x.IsAnyoneHome()).Returns(true); + CreateSut(); + + EmitStateChange(SunEntityId, LightMonitorConsts.SunAboveHorizon, LightMonitorConsts.SunBelowHorizon); + + _lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Once); + } + + [Fact] + public void SunStateChange_FromAboveHorizonToBelowHorizon_WhenNoOneIsHome_ShouldNotCallTurnOnLight() + { + _presenceServiceMock.Setup(x => x.IsAnyoneHome()).Returns(false); + CreateSut(); + + EmitStateChange(SunEntityId, LightMonitorConsts.SunAboveHorizon, LightMonitorConsts.SunBelowHorizon); + + _lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Never); + } + + [Fact] + public void SunStateChange_FromUnavailableToBelowHorizon_ShouldNotCallTurnOnLight() + { + _presenceServiceMock.Setup(x => x.IsAnyoneHome()).Returns(true); + CreateSut(); + + EmitStateChange(SunEntityId, LightMonitorConsts.UnavailableState, LightMonitorConsts.SunBelowHorizon); + + _lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Never); + } + + [Fact] + public void SunStateChange_FromUnknownToBelowHorizon_ShouldNotCallTurnOnLight() + { + _presenceServiceMock.Setup(x => x.IsAnyoneHome()).Returns(true); + CreateSut(); + + EmitStateChange(SunEntityId, LightMonitorConsts.UnknownState, LightMonitorConsts.SunBelowHorizon); + + _lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Never); + } + + [Fact] + public void SunStateChange_FromNullToBelowHorizon_ShouldNotCallTurnOnLight() + { + _presenceServiceMock.Setup(x => x.IsAnyoneHome()).Returns(true); + CreateSut(); + + EmitStateChange(SunEntityId, null, LightMonitorConsts.SunBelowHorizon); + + _lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Never); + } + + [Fact] + public void SunStateChange_FromBelowHorizonToAboveHorizon_ShouldNotCallTurnOnLight() + { + CreateSut(); + + EmitStateChange(SunEntityId, LightMonitorConsts.SunBelowHorizon, LightMonitorConsts.SunAboveHorizon); + + _lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Never); + } +} diff --git a/LightMonitor.Manager/LightControlService.cs b/LightMonitor.Manager/LightControlService.cs index caa5471..c5cac4b 100644 --- a/LightMonitor.Manager/LightControlService.cs +++ b/LightMonitor.Manager/LightControlService.cs @@ -31,6 +31,7 @@ public sealed class LightControlService : ILightControlService if (!string.Equals(sunState, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase)) { _logger.LogDebug("Sun is not below horizon (state={SunState}), skipping light turn on", sunState); + return; } @@ -39,6 +40,7 @@ public sealed class LightControlService : ILightControlService if (string.Equals(lightState, LightMonitorConsts.LightOnState, StringComparison.OrdinalIgnoreCase)) { _logger.LogDebug("Light {EntityId} is already on, skipping", _options.LightEntityId); + return; } diff --git a/LightMonitor.Manager/LightMonitorInit.cs b/LightMonitor.Manager/LightMonitorInit.cs index c296016..ef43763 100644 --- a/LightMonitor.Manager/LightMonitorInit.cs +++ b/LightMonitor.Manager/LightMonitorInit.cs @@ -63,6 +63,13 @@ public sealed class LightMonitorInit : ILightMonitorInit return; } + if (IsRecoveryTransition(e.Old?.State)) + { + _logger.LogInformation("Sun state recovered from {OldState}, ignoring", e.Old?.State); + + return; + } + _logger.LogInformation("Sun went below horizon, checking if anyone is home"); if (_presenceService.IsAnyoneHome()) @@ -92,6 +99,12 @@ public sealed class LightMonitorInit : ILightMonitorInit return; } + if (IsRecoveryTransition(e.Old?.State)) + { + _logger.LogInformation("Person {EntityId} state recovered from {OldState}, ignoring", personEntityId, e.Old?.State); + return; + } + _logger.LogInformation("Person {EntityId} arrived home, checking if it is dark", personEntityId); _lightControlService.TurnOnLight(); } @@ -102,4 +115,6 @@ public sealed class LightMonitorInit : ILightMonitorInit }); } } + + private static bool IsRecoveryTransition(string? oldState) => oldState is null or LightMonitorConsts.UnavailableState or LightMonitorConsts.UnknownState; } diff --git a/LightMonitor.Manager/LightMonitorServiceRegistration.cs b/LightMonitor.Manager/LightMonitorServiceRegistration.cs index 1f4a875..6669c0f 100644 --- a/LightMonitor.Manager/LightMonitorServiceRegistration.cs +++ b/LightMonitor.Manager/LightMonitorServiceRegistration.cs @@ -19,10 +19,9 @@ public static class LightMonitorServiceRegistration return services; } - services - .AddNetDaemonApp() - .AddScoped() - .AddScoped(); + services.AddNetDaemonApp() + .AddScoped() + .AddScoped(); return services; } diff --git a/LightMonitor.Manager/PresenceService.cs b/LightMonitor.Manager/PresenceService.cs index c0da4ce..038684c 100644 --- a/LightMonitor.Manager/PresenceService.cs +++ b/LightMonitor.Manager/PresenceService.cs @@ -7,42 +7,32 @@ using LightMonitorManager.Models; namespace LightMonitorManager; -public sealed class PresenceService : IPresenceService +public sealed class PresenceService( + IHaContext haContext, + ILogger logger, + IOptions options) : IPresenceService { - private readonly IHaContext _haContext; - private readonly ILogger _logger; - private readonly LightMonitorOptions _options; - - public PresenceService( - IHaContext haContext, - ILogger logger, - IOptions options) - { - _haContext = haContext; - _logger = logger; - _options = options.Value; - } + private readonly LightMonitorOptions _options = options.Value; public bool IsAnyoneHome() { foreach (var personEntityId in _options.PersonEntityIds) { - var state = _haContext.GetState(personEntityId); + var state = haContext.GetState(personEntityId); - if (state?.State is null or "unavailable" or "unknown") + if (state?.State is null or LightMonitorConsts.UnavailableState or LightMonitorConsts.UnknownState) { - _logger.LogDebug("Person entity {EntityId} state unavailable", personEntityId); continue; } if (string.Equals(state.State, LightMonitorConsts.PersonHomeState, StringComparison.OrdinalIgnoreCase)) { - _logger.LogDebug("Person {EntityId} is home", personEntityId); + logger.LogDebug("Person {EntityId} is home", personEntityId); return true; } } - - _logger.LogDebug("No person is currently home"); + + return false; } } diff --git a/LightMonitor.Models/LightMonitorConsts.cs b/LightMonitor.Models/LightMonitorConsts.cs index 508f3ea..5c85875 100644 --- a/LightMonitor.Models/LightMonitorConsts.cs +++ b/LightMonitor.Models/LightMonitorConsts.cs @@ -16,4 +16,6 @@ public static class LightMonitorConsts public const string SunAboveHorizon = "above_horizon"; public const string PersonHomeState = "home"; public const string LightOnState = "on"; + public const string UnavailableState = "unavailable"; + public const string UnknownState = "unknown"; } diff --git a/LightMonitor.Manager/Models/LightMonitorOptions.cs b/LightMonitor.Models/LightMonitorOptions.cs similarity index 100% rename from LightMonitor.Manager/Models/LightMonitorOptions.cs rename to LightMonitor.Models/LightMonitorOptions.cs diff --git a/NordPool.Manager.Tests/NordPoolInitTests.cs b/NordPool.Manager.Tests/NordPoolInitTests.cs index 49c58b7..642fa85 100644 --- a/NordPool.Manager.Tests/NordPoolInitTests.cs +++ b/NordPool.Manager.Tests/NordPoolInitTests.cs @@ -20,7 +20,7 @@ public class NordPoolInitTests private readonly Mock _entityServiceMock; private readonly Mock _schedulerMock; private readonly Mock _cheapestIntervalsFinderMock; - private readonly Mock _boilerConfigReaderMock; + private readonly Mock _boilerConfigProviderMock; private readonly Mock _haContextMock; private readonly Entities _entities; @@ -32,7 +32,7 @@ public class NordPoolInitTests _schedulerMock = new Mock(); _schedulerMock.Setup(s => s.Now).Returns(DateTimeOffset.UtcNow); _cheapestIntervalsFinderMock = new Mock(); - _boilerConfigReaderMock = new Mock(); + _boilerConfigProviderMock = new Mock(); _haContextMock = new Mock(); _entities = new Entities(_haContextMock.Object); @@ -51,7 +51,7 @@ public class NordPoolInitTests _cheapestIntervalsFinderMock .Setup(c => c.IsCurrentIntervalCheap(It.IsAny>(), It.IsAny())) .Returns(false); - _boilerConfigReaderMock.Setup(b => b.ReadConfig()).Returns(new BoilerConfig + _boilerConfigProviderMock.Setup(b => b.GetCurrentConfiguration()).Returns(new BoilerConfig { IntervalCount = 4, PriceCap = double.MaxValue, @@ -72,7 +72,7 @@ public class NordPoolInitTests _entityServiceMock.Object, _schedulerMock.Object, _cheapestIntervalsFinderMock.Object, - _boilerConfigReaderMock.Object, + _boilerConfigProviderMock.Object, options); } diff --git a/NordPool.Manager.Tests/NordPoolPriceServiceTests.cs b/NordPool.Manager.Tests/NordPoolPriceServiceTests.cs index 37f7916..77f65a0 100644 --- a/NordPool.Manager.Tests/NordPoolPriceServiceTests.cs +++ b/NordPool.Manager.Tests/NordPoolPriceServiceTests.cs @@ -29,17 +29,17 @@ public class NordPoolPriceServiceTests #region GetTimeQuarterIndex [Theory] - [InlineData(0, 0, 4)] - [InlineData(1, 0, 8)] - [InlineData(6, 0, 28)] - [InlineData(12, 0, 52)] - [InlineData(23, 0, 0)] - [InlineData(23, 15, 1)] - [InlineData(23, 30, 2)] - [InlineData(23, 45, 3)] + [InlineData(0, 0, 8)] // UTC 00:00 = CEST 02:00 + [InlineData(1, 0, 12)] // UTC 01:00 = CEST 03:00 + [InlineData(6, 0, 32)] // UTC 06:00 = CEST 08:00 + [InlineData(12, 0, 56)] // UTC 12:00 = CEST 14:00 + [InlineData(22, 0, 0)] // UTC 22:00 = CEST 00:00 (next day start) + [InlineData(22, 15, 1)] // UTC 22:15 = CEST 00:15 + [InlineData(22, 30, 2)] // UTC 22:30 = CEST 00:30 + [InlineData(22, 45, 3)] // UTC 22:45 = CEST 00:45 public void GetTimeQuarterIndex_ShouldReturnCorrectIndex(int hour, int minute, int expectedIndex) { - // Arrange + // Arrange — 2026-03-31 is in CEST (UTC+2) var testDate = new DateTime(2026, 3, 31, hour, minute, 0, DateTimeKind.Utc); // Act @@ -50,14 +50,14 @@ public class NordPoolPriceServiceTests } [Theory] - [InlineData(0, 15, 5)] - [InlineData(1, 30, 10)] - [InlineData(12, 0, 52)] - [InlineData(23, 0, 0)] - [InlineData(23, 59, 3)] + [InlineData(0, 15, 9)] // UTC 00:15 = CEST 02:15 + [InlineData(1, 30, 14)] // UTC 01:30 = CEST 03:30 + [InlineData(12, 0, 56)] // UTC 12:00 = CEST 14:00 + [InlineData(22, 0, 0)] // UTC 22:00 = CEST 00:00 + [InlineData(22, 59, 3)] // UTC 22:59 = CEST 00:59 public void GetTimeQuarterIndex_ShouldHandleAllHoursCorrectly(int hour, int minute, int expectedIndex) { - // Arrange + // Arrange — 2026-03-31 is in CEST (UTC+2) var testDate = new DateTime(2026, 3, 31, hour, minute, 0, DateTimeKind.Utc); // Act @@ -68,23 +68,23 @@ public class NordPoolPriceServiceTests } [Fact] - public void GetTimeQuarterIndex_AtExactMidnight_ShouldReturnIndex4() + public void GetTimeQuarterIndex_AtUtcMidnight_ShouldReturnCestOffset() { - // Arrange + // Arrange — UTC 00:00 = CEST 02:00 -> index 8 var testDate = new DateTime(2026, 3, 31, 0, 0, 0, DateTimeKind.Utc); // Act var result = NordPoolPriceService.GetTimeQuarterIndex(testDate); // Assert - result.Should().Be(4); + result.Should().Be(8); } [Fact] - public void GetTimeQuarterIndex_AtEndOfDay_ShouldReturnIndex95() + public void GetTimeQuarterIndex_AtEndOfCestDay_ShouldReturnIndex95() { - // Arrange - var testDate = new DateTime(2026, 3, 31, 22, 45, 0, DateTimeKind.Utc); + // Arrange — CEST 23:45 = UTC 21:45 -> index 95 + var testDate = new DateTime(2026, 3, 31, 21, 45, 0, DateTimeKind.Utc); // Act var result = NordPoolPriceService.GetTimeQuarterIndex(testDate); @@ -111,7 +111,7 @@ public class NordPoolPriceServiceTests [Fact] public void GetTimeQuarterIndex_ShouldReturn96UniqueQuartersPerDay() { - // Arrange & Act + // Arrange & Act — iterate over a full UTC day; CET conversion produces 96 unique quarter indices var indices = new HashSet(); for (var hour = 0; hour < 24; hour++) { @@ -129,6 +129,21 @@ public class NordPoolPriceServiceTests indices.Max().Should().Be(95); } + [Theory] + [InlineData(2026, 1, 15, 8, 0, 36)] // CET winter (UTC+1): UTC 08:00 = CET 09:00 -> index 36 + [InlineData(2026, 7, 15, 8, 0, 40)] // CEST summer (UTC+2): UTC 08:00 = CEST 10:00 -> index 40 + public void GetTimeQuarterIndex_ShouldHandleDaylightSavingTimeCorrectly(int year, int month, int day, int hour, int minute, int expectedIndex) + { + // Arrange + var testDate = new DateTime(year, month, day, hour, minute, 0, DateTimeKind.Utc); + + // Act + var result = NordPoolPriceService.GetTimeQuarterIndex(testDate); + + // Assert + result.Should().Be(expectedIndex); + } + #endregion #region PriceCorrection diff --git a/NordPool.Manager/CheapestIntervalsFinder.cs b/NordPool.Manager/CheapestIntervalsFinder.cs index 58e799b..3ef695f 100644 --- a/NordPool.Manager/CheapestIntervalsFinder.cs +++ b/NordPool.Manager/CheapestIntervalsFinder.cs @@ -43,8 +43,6 @@ public class CheapestIntervalsFinder(ILogger logger) : .OrderBy(r => r.Start) .ToList(); - logger.LogInformation("Found {Count} cheapest intervals out of {Requested} requested (deadline: {Deadline}, price cap: {Cap})", ranked.Count, numberOfIntervals, deadline, priceCap); - return ranked; } diff --git a/NordPool.Manager/Interface/INordPoolBoilerConfigProvider.cs b/NordPool.Manager/Interface/INordPoolBoilerConfigProvider.cs new file mode 100644 index 0000000..e41dbaa --- /dev/null +++ b/NordPool.Manager/Interface/INordPoolBoilerConfigProvider.cs @@ -0,0 +1,11 @@ +using BoilerMonitor.Models; + +namespace NordPoolManager.Interface; + +/// +/// Supplies boiler scheduling configuration for NordPool cheapest-interval logic. +/// +public interface INordPoolBoilerConfigProvider +{ + BoilerConfig GetCurrentConfiguration(); +} diff --git a/NordPool.Manager/NordPoolBoilerConfigProvider.cs b/NordPool.Manager/NordPoolBoilerConfigProvider.cs new file mode 100644 index 0000000..899737e --- /dev/null +++ b/NordPool.Manager/NordPoolBoilerConfigProvider.cs @@ -0,0 +1,12 @@ +using BoilerMonitor.Models; +using NordPoolManager.Interface; + +namespace NordPoolManager; + +/// +/// Resolves boiler configuration from Home Assistant state for NordPool scheduling. +/// +public sealed class NordPoolBoilerConfigProvider(IBoilerConfigReader boilerConfigReader) : INordPoolBoilerConfigProvider +{ + public BoilerConfig GetCurrentConfiguration() => boilerConfigReader.ReadConfig(); +} diff --git a/NordPool.Manager/NordPoolEntityService.cs b/NordPool.Manager/NordPoolEntityService.cs index 33e497d..d403393 100644 --- a/NordPool.Manager/NordPoolEntityService.cs +++ b/NordPool.Manager/NordPoolEntityService.cs @@ -36,7 +36,6 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger< { try { - logger.LogInformation("Creating/re-registering MQTT entity: {EntityId}", nordPoolEntity.EntityId); await entityManager.CreateEntityAsync(nordPoolEntity).ConfigureAwait(false); } catch (Exception ex) @@ -51,9 +50,7 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger< public async Task ResetEntitiesAsync(CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); - - logger.LogInformation("Resetting all NordPool entity states to defaults"); - + await Task.WhenAll( ResetLastUpdateTimeAsync(), ResetCurrentPriceAsync(), @@ -62,8 +59,6 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger< ResetTodayTomorrowPricesAsync(), ResetCheapestIntervalsAsync() ).ConfigureAwait(false); - - logger.LogInformation("All NordPool entity states reset to defaults"); } private async Task ResetLastUpdateTimeAsync() @@ -162,11 +157,7 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger< } var cheapestCount = ctx.CheapestIntervals?.Count ?? 0; - - logger.LogInformation("Updating nordpool_current_price with value: {Price} {Unit}", priceValue, ctx.UnitOfMeasurement); - logger.LogInformation("Updating sensor.nordpool_today_prices with {Count} prices", todayPricesCount); - logger.LogInformation("Updating sensor.nordpool_tomorrow_prices with {Count} prices", tomorrowPricesCount); - logger.LogInformation("Updating sensor.nordpool_today_tomorrow_prices with {Count} merged prices", mergedPrices.Count); + logger.LogInformation("Updating sensor.nordpool_cheapest_intervals with {Count} intervals, is_now_cheap={IsNow}", cheapestCount, ctx.IsNowCheap); var updateTasks = new[] @@ -180,8 +171,6 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger< }; await Task.WhenAll(updateTasks).ConfigureAwait(false); - - logger.LogInformation("NordPool entities updated successfully. Today prices count: {TodayCount}, Tomorrow prices count: {TomorrowCount}", todayPricesCount, tomorrowPricesCount); } private async Task UpdateLastUpdateTimeAsync(string updateTimeState) @@ -266,8 +255,6 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger< { var removeTasks = AllEntityIds.Select(entityManager.RemoveEntity); await Task.WhenAll(removeTasks).ConfigureAwait(false); - - logger.LogInformation("NordPool entities cleaned up successfully"); } catch (Exception ex) { @@ -323,7 +310,6 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger< try { await entityManager.SetEntityState(entityId, state).ConfigureAwait(false); - logger.LogDebug("Successfully set state for {EntityId}: {State}", entityId, state); } catch (Exception ex) { @@ -336,7 +322,6 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger< try { await entityManager.SetEntityAttributes(entityId, attributes).ConfigureAwait(false); - logger.LogDebug("Successfully set attributes for {EntityId}", entityId); } catch (Exception ex) { diff --git a/NordPool.Manager/NordPoolInit.cs b/NordPool.Manager/NordPoolInit.cs index 6ef6517..34d8e90 100644 --- a/NordPool.Manager/NordPoolInit.cs +++ b/NordPool.Manager/NordPoolInit.cs @@ -19,7 +19,7 @@ public class NordPoolInit : INordPoolInit private readonly INordPoolPriceService _priceService; private readonly INordPoolEntityService _entityService; private readonly ICheapestIntervalsFinder _cheapestIntervalsFinder; - private readonly IBoilerConfigReader _boilerConfigReader; + private readonly INordPoolBoilerConfigProvider _boilerConfigProvider; private readonly IScheduler _scheduler; private readonly NordPoolOptions _options; @@ -33,7 +33,7 @@ public class NordPoolInit : INordPoolInit INordPoolEntityService entityService, IScheduler scheduler, ICheapestIntervalsFinder cheapestIntervalsFinder, - IBoilerConfigReader boilerConfigReader, + INordPoolBoilerConfigProvider boilerConfigProvider, IOptions options) { _logger = logger; @@ -41,7 +41,7 @@ public class NordPoolInit : INordPoolInit _entityService = entityService; _scheduler = scheduler; _cheapestIntervalsFinder = cheapestIntervalsFinder; - _boilerConfigReader = boilerConfigReader; + _boilerConfigProvider = boilerConfigProvider; _options = options.Value; var nordPoolPriceSensor = entities.Sensor.NordpoolPrice; @@ -75,29 +75,21 @@ public class NordPoolInit : INordPoolInit { await _entityService.CleanupEntitiesAsync(); } - else - { - _logger.LogInformation("Skipping NordPool entity cleanup on startup (CleanupEntitiesOnStartup is false)"); - } await _entityService.CreateEntitiesAsync(UnitOfMeasurement); - await _entityService.ResetEntitiesAsync(); - await Task.Delay(TimeSpan.FromSeconds(10)); var currentPrice = _priceService.UpdateCurrentPrice(); - _logger.LogInformation("Retrieved current price: {Price}, DayQuartersIndex: {Index}", currentPrice, _priceService.DayQuartersIndex); - + if (currentPrice == 0) { _logger.LogWarning("Current price is 0, which may indicate an issue with price retrieval"); } - var (_, boilerConfig) = UpdateCheapestIntervals(); + var boilerConfig = _boilerConfigProvider.GetCurrentConfiguration(); + UpdateCheapestIntervals(boilerConfig); await UpdateEntitiesAsync(boilerConfig); - - _logger.LogInformation("NordPool price initialized with current price: {CurrentPrice} {Unit}", _priceService.CurrentPrice, UnitOfMeasurement); } catch (Exception ex) { @@ -112,12 +104,10 @@ public class NordPoolInit : INordPoolInit var currentMinute = now.Minute; var currentSecond = now.Second; - var minutesUntilNext15 = 15 - (currentMinute % 15); + var minutesUntilNext15 = 15 - currentMinute % 15; var delayUntilNext15 = TimeSpan.FromMinutes(minutesUntilNext15) - TimeSpan.FromSeconds(currentSecond); var nextUpdateTime = now.Add(delayUntilNext15); - _logger.LogInformation("Scheduling first NordPool update at {Time} (in {Delay})", nextUpdateTime, delayUntilNext15); - _scheduler.RunEvery(TimeSpan.FromMinutes(15), nextUpdateTime, async void () => { try @@ -135,14 +125,10 @@ public class NordPoolInit : INordPoolInit { try { - _logger.LogInformation("Starting periodic NordPool price update"); - var cetTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time"); var nowCet = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, cetTimeZone); var today = DateOnly.FromDateTime(nowCet); - _logger.LogDebug("Current CET time: {CetTime}, Today in CET: {Today}", nowCet, today); - if (_priceService.LastFetchedDate.HasValue && _priceService.LastFetchedDate.Value < today) { _priceService.RollOverPrices(today); @@ -150,20 +136,15 @@ public class NordPoolInit : INordPoolInit if (_priceService.ShouldFetchNewPrices(today)) { - _logger.LogInformation("Fetching new prices from NordPool API"); await _priceService.FetchPricesAsync(); } - else - { - _logger.LogDebug("Using cached prices, no need to fetch from API"); - } _priceService.UpdateCurrentPrice(); - var (_, boilerConfig) = UpdateCheapestIntervals(); + var boilerConfig = _boilerConfigProvider.GetCurrentConfiguration(); + UpdateCheapestIntervals(boilerConfig); await UpdateEntitiesAsync(boilerConfig); - - _logger.LogInformation("NordPool prices updated successfully. Current price: {CurrentPrice} {Unit}", _priceService.CurrentPrice, UnitOfMeasurement); + } catch (Exception ex) { @@ -176,9 +157,8 @@ public class NordPoolInit : INordPoolInit await _entityService.CleanupEntitiesAsync(cancellationToken); } - private (CheapestIntervalsUpdateResult Result, BoilerConfig Config) UpdateCheapestIntervals() + private void UpdateCheapestIntervals(BoilerConfig config) { - var config = _boilerConfigReader.ReadConfig(); var effectivePriceCap = config.SkipPriceCap ? double.MaxValue : config.PriceCap; var effectiveIntervalCount = config.SkipPriceCap ? NordPoolConsts.MaxDailyIntervals : config.IntervalCount; @@ -188,31 +168,17 @@ public class NordPoolInit : INordPoolInit { _logger.LogDebug("No today prices available, skipping cheapest intervals calculation"); CheapestIntervals = []; - return (new CheapestIntervalsUpdateResult - { - IntervalCount = config.IntervalCount, - PriceCap = config.PriceCap, - SkipPriceCap = config.SkipPriceCap - }, config); + + return; } CheapestIntervals = _cheapestIntervalsFinder.FindCheapestIntervals(_priceService.TodayNordPoolPrice, effectiveIntervalCount, effectivePriceCap, config.Deadline); - - _logger.LogInformation("Cheapest intervals updated: {Count} intervals (config: {Hours}h / {Intervals} intervals, cap: {Cap}, skipPriceCap: {Skip}, deadline: {Deadline})", - CheapestIntervals.Count, config.IntervalCount / 4.0, effectiveIntervalCount, effectivePriceCap, config.SkipPriceCap, config.Deadline); } catch (Exception ex) { _logger.LogError(ex, "Error calculating cheapest intervals"); CheapestIntervals = []; } - - return (new CheapestIntervalsUpdateResult - { - IntervalCount = config.IntervalCount, - PriceCap = config.PriceCap, - SkipPriceCap = config.SkipPriceCap - }, config); } private async Task UpdateEntitiesAsync(BoilerConfig boilerConfig) @@ -225,8 +191,7 @@ public class NordPoolInit : INordPoolInit var configuredHours = (double)boilerConfig.IntervalCount / NordPoolConsts.IntervalsPerHour; var configuredReadyBy = boilerConfig.Deadline.TimeOfDay.ToString(@"hh\:mm", CultureInfo.InvariantCulture); - var isNowCheap = CheapestIntervals != null && - _cheapestIntervalsFinder.IsCurrentIntervalCheap(CheapestIntervals, currentDateTime); + var isNowCheap = CheapestIntervals != null && _cheapestIntervalsFinder.IsCurrentIntervalCheap(CheapestIntervals, currentDateTime); var nextCheapInterval = CheapestIntervals? .Where(i => i.Start > currentDateTime) .OrderBy(i => i.Start) diff --git a/NordPool.Manager/NordPoolPriceService.cs b/NordPool.Manager/NordPoolPriceService.cs index 77b6e15..2228f49 100644 --- a/NordPool.Manager/NordPoolPriceService.cs +++ b/NordPool.Manager/NordPoolPriceService.cs @@ -29,28 +29,17 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger= 13) { - logger.LogDebug("Checking for tomorrow's prices (after 13:00)"); - return true; } } @@ -128,26 +106,48 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger 0 }) { TodayNordPoolPrice = TomorrowNordPoolPrice; - logger.LogInformation("Moved tomorrow's prices ({Count} prices) to today", TodayNordPoolPrice?.Prices?.Count ?? 0); } else { TodayNordPoolPrice = new NordPoolPrice(); - logger.LogWarning("Tomorrow's prices were not available during rollover, clearing stale today's prices to trigger re-fetch"); } TomorrowNordPoolPrice = null; - logger.LogInformation("Cleared tomorrow's prices"); DayQuartersIndex = -1; LastFetchedDate = today; } + private async Task FetchPricesForDateWithRetryAsync(DateOnly date, string label) + { + for (var attempt = 1; attempt <= NordPoolConsts.MaxFetchRetryAttempts; attempt++) + { + try + { + return await GetNordPoolPriceAsync(date); + } + catch (InvalidOperationException ex) when (attempt < NordPoolConsts.MaxFetchRetryAttempts) + { + var delay = TimeSpan.FromSeconds(NordPoolConsts.RetryBaseDelaySeconds * Math.Pow(2, attempt - 1)); + logger.LogWarning(ex, "Attempt {Attempt}/{MaxAttempts} to fetch {Label} prices for {Date} failed. Retrying in {Delay}", attempt, NordPoolConsts.MaxFetchRetryAttempts, label, date, delay); + + await Task.Delay(delay); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to fetch {Label} prices for {Date} on attempt {Attempt} with unexpected error", label, date, attempt); + break; + } + } + + logger.LogWarning("All {MaxAttempts} attempts to fetch {Label} prices for {Date} exhausted; returning empty prices", NordPoolConsts.MaxFetchRetryAttempts, label, date); + + return new NordPoolPrice(); + } + private async Task GetNordPoolPriceAsync(DateOnly date) { var nordPoolPricesDto = await _nordPoolServices.GetPricesForDateAsync( @@ -160,7 +160,7 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger public const string CurrentPriceEntityId = "sensor.nordpool_current_price"; + + /// + /// Maximum number of retry attempts when fetching prices from the NordPool API. + /// + public const int MaxFetchRetryAttempts = 3; + + /// + /// Base delay in seconds between retry attempts (used with exponential backoff). + /// + public const int RetryBaseDelaySeconds = 5; } \ No newline at end of file diff --git a/PowerMonitor.Manager/Interface/IPowerNotificationService.cs b/PowerMonitor.Manager/Interface/IPowerNotificationService.cs new file mode 100644 index 0000000..244ae91 --- /dev/null +++ b/PowerMonitor.Manager/Interface/IPowerNotificationService.cs @@ -0,0 +1,8 @@ +namespace PowerMonitorManager.Interface; + +public interface IPowerNotificationService +{ + void NotifyHighPowerUsage(double currentPowerWatts, double thresholdWatts); + + void DismissHighPowerNotification(); +} diff --git a/PowerMonitor.Manager/Models/Consts/PowerMonitorConsts.cs b/PowerMonitor.Manager/Models/Consts/PowerMonitorConsts.cs index a41e8cf..a5e498e 100644 --- a/PowerMonitor.Manager/Models/Consts/PowerMonitorConsts.cs +++ b/PowerMonitor.Manager/Models/Consts/PowerMonitorConsts.cs @@ -18,6 +18,14 @@ public static class PowerMonitorConsts public const int MainMeterMaxConsecutiveFailures = 5; + public const double DefaultHighPowerThresholdWatts = 6000.0; + + public const string HighPowerNotificationId = "power_monitor_high_power"; + public const string HighPowerNotificationTitle = "High Power Usage Alert"; + 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; } diff --git a/PowerMonitor.Manager/Models/PowerMonitorOptions.cs b/PowerMonitor.Manager/Models/PowerMonitorOptions.cs index 73a9a06..443c0ff 100644 --- a/PowerMonitor.Manager/Models/PowerMonitorOptions.cs +++ b/PowerMonitor.Manager/Models/PowerMonitorOptions.cs @@ -12,4 +12,5 @@ public sealed class PowerMonitorOptions public int SmoothingWindowSize { get; set; } = PowerMonitorConsts.DefaultSmoothingWindowSize; public double AnomalyThresholdWatts { get; set; } = PowerMonitorConsts.DefaultAnomalyThresholdWatts; public string[] ExcludedSensorPatterns { get; set; } = []; + public double HighPowerThresholdWatts { get; set; } = PowerMonitorConsts.DefaultHighPowerThresholdWatts; } diff --git a/PowerMonitor.Manager/PowerMonitorInit.cs b/PowerMonitor.Manager/PowerMonitorInit.cs index 0be59fe..39cf9c7 100644 --- a/PowerMonitor.Manager/PowerMonitorInit.cs +++ b/PowerMonitor.Manager/PowerMonitorInit.cs @@ -24,9 +24,11 @@ public sealed class PowerMonitorInit : IPowerMonitorInit private readonly IOtherPowerCalculationService _calculationService; private readonly IPowerCostCalculationService _costService; private readonly IPowerMonitorEntityService _entityService; + private readonly IPowerNotificationService _notificationService; private int _mainMeterConsecutiveFailures; private DateTime? _anomalyStartTime; + private bool _highPowerNotificationActive; public PowerMonitorInit( IHaContext haContext, @@ -36,7 +38,8 @@ public sealed class PowerMonitorInit : IPowerMonitorInit IPowerSensorDiscoveryService discoveryService, IOtherPowerCalculationService calculationService, IPowerCostCalculationService costService, - IPowerMonitorEntityService entityService) + IPowerMonitorEntityService entityService, + IPowerNotificationService notificationService) { _haContext = haContext; _logger = logger; @@ -46,6 +49,7 @@ public sealed class PowerMonitorInit : IPowerMonitorInit _calculationService = calculationService; _costService = costService; _entityService = entityService; + _notificationService = notificationService; _ = InitializeAndScheduleAsync(); } @@ -230,6 +234,8 @@ public sealed class PowerMonitorInit : IPowerMonitorInit await _entityService.UpdateEntitiesAsync(context); + EvaluateHighPowerNotification(calculation.TotalPowerWatts); + _logger.LogDebug( "Poll complete: total={Total}W, other={Other}W (smoothed), devices={Devices}, price={Price}", calculation.TotalPowerWatts, @@ -261,6 +267,22 @@ public sealed class PowerMonitorInit : IPowerMonitorInit return 0; } + private void EvaluateHighPowerNotification(double totalPowerWatts) + { + var isAboveThreshold = totalPowerWatts > _options.HighPowerThresholdWatts; + + if (isAboveThreshold && !_highPowerNotificationActive) + { + _notificationService.NotifyHighPowerUsage(totalPowerWatts, _options.HighPowerThresholdWatts); + _highPowerNotificationActive = true; + } + else if (!isAboveThreshold && _highPowerNotificationActive) + { + _notificationService.DismissHighPowerNotification(); + _highPowerNotificationActive = false; + } + } + private double? ReadMainMeterPower() { var state = _haContext.GetState(_options.MainMeterEntityId); diff --git a/PowerMonitor.Manager/PowerMonitorServiceRegistration.cs b/PowerMonitor.Manager/PowerMonitorServiceRegistration.cs index 77d6e43..59853b8 100644 --- a/PowerMonitor.Manager/PowerMonitorServiceRegistration.cs +++ b/PowerMonitor.Manager/PowerMonitorServiceRegistration.cs @@ -24,7 +24,8 @@ public static class PowerMonitorServiceRegistration .AddScoped() .AddSingleton() .AddSingleton() - .AddTransient(); + .AddTransient() + .AddTransient(); return services; } diff --git a/PowerMonitor.Manager/PowerNotificationService.cs b/PowerMonitor.Manager/PowerNotificationService.cs new file mode 100644 index 0000000..2354993 --- /dev/null +++ b/PowerMonitor.Manager/PowerNotificationService.cs @@ -0,0 +1,64 @@ +using System.Globalization; +using Microsoft.Extensions.Logging; +using NetDaemon.HassModel; +using PowerMonitorManager.Interface; +using PowerMonitorManager.Models.Consts; + +namespace PowerMonitorManager; + +public sealed class PowerNotificationService : 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( + PowerMonitorConsts.PersistentNotificationDomain, + PowerMonitorConsts.PersistentNotificationCreateService, + data: new + { + title = PowerMonitorConsts.HighPowerNotificationTitle, + message, + notification_id = PowerMonitorConsts.HighPowerNotificationId + }); + + _logger.LogWarning( + "High power usage notification sent: {CurrentKw:F2} kW (threshold: {ThresholdKw:F1} kW)", + currentKw, thresholdKw); + } + + public void DismissHighPowerNotification() + { + _haContext.CallService( + PowerMonitorConsts.PersistentNotificationDomain, + PowerMonitorConsts.PersistentNotificationDismissService, + data: new + { + notification_id = PowerMonitorConsts.HighPowerNotificationId + }); + + _logger.LogDebug("Dismissed high power usage notification"); + } + + internal static string BuildHighPowerMessage(double currentKw, double thresholdKw) + { + return string.Format( + CultureInfo.InvariantCulture, + "Total home power usage is **{0:F2} kW**, which exceeds the threshold of **{1:F1} kW**.\n\nConsider turning off high-power appliances to reduce consumption.", + currentKw, + thresholdKw); + } +} diff --git a/README.md b/README.md new file mode 100644 index 0000000..f5da101 --- /dev/null +++ b/README.md @@ -0,0 +1,100 @@ +# Home Assistant App Daemon + +A .NET 10 solution that runs a collection of NetDaemon apps for Home Assistant. +Each app is a self-contained monitor that observes entity state from Home +Assistant, applies business logic, and drives switches / sensors / notifications +back into HA via the NetDaemon `IHaContext` and MQTT entity manager. + +## Requirements + +- .NET 10 SDK (see `global.json`; rolls forward to latest major) +- A running Home Assistant instance +- [NetDaemon](https://netdaemon.xyz) runtime v5 (the `HomeAssistant.Server` + project is the binary-deploy host) +- A long-lived Home Assistant access token + +## Solution layout + +The solution file is `HomeAssistantSDK.sln`. Projects are grouped by concern: + +### Host / infrastructure + +| Project | Role | +|---------|------| +| `HomeAssistant.Server` | NetDaemon host. Binary-deploy target that loads all apps. | +| `HomeAssistant.Entities` | Generated HA entity metadata + `IEntityManager` abstraction. | +| `HomeAssistant.Models` | Shared HA DTOs (`EntityCreateModel`, etc.). | +| `HomeAssistant.Infrastructure` | Cross-cutting infrastructure shared by apps. | +| `HomeAssistant.McpServer` | MCP server exposing HA tools (entities, history, logbook, services, system). | +| `Mappings` | Shared mapping helpers. | + +### Monitor apps + +Every monitor follows the same three-project pattern: + +- `*.Models` — constants, enums, options classes, DTOs +- `*.Manager` — business logic, services, and the `[NetDaemonApp]` entry + point (`*Init.cs`) +- `*.Manager.Tests` — unit tests for the manager + +| Monitor | Entry point | What it does | +|---------|-------------|--------------| +| **NordPool** | `NordPool.Manager/NordPoolInit.cs` | Fetches Nord Pool spot prices every 15 min, computes cheapest heating intervals, exposes current/next-cheap price. | +| **Boiler** | `BoilerMonitor.Manager/BoilerMonitorInit.cs` | Turns the boiler on/off based on cheap intervals, water-ready detection, daily runtime budget, and shower state. | +| **Shower** | `ShowerMonitor.Manager/ShowerMonitorInit.cs` | Detects shower state from bathroom vs. home humidity rate and controls the exhaust fan. | +| **Power** | `PowerMonitor.Manager/PowerMonitorInit.cs` | Polls the main meter + device sensors, calculates per-device and "other" power, accumulates costs against Nord Pool price, flags anomalies. | +| **Light** | `LightMonitor.Manager/LightMonitorInit.cs` | Turns a light on at sunset or when a tracked person arrives home. | +| **Battery** | `BatteryMonitor.Manager/BatteryMonitorInit.cs` | Daily scan for low-battery devices and push notification. | +| **Leak** | `LeakMonitor.Manager/LeakMonitorInit.cs` | Subscribes to leak sensors and sends/clears alerts on water-detected transitions. | + +### Tooling + +| Project | Role | +|---------|------| +| `HomeAssistant.HistoryReplay` | Debugging console app that replays real HA history through the monitor business logic with no side effects. See its own [README](HomeAssistant.HistoryReplay/README.md). | + +## Build + +```bash +dotnet build HomeAssistantSDK.sln +``` + +## Run tests + +```bash +dotnet test HomeAssistantSDK.sln +``` + +## Deploy + +`HomeAssistant.Server` is the NetDaemon binary-deploy target. Build it as a +self-contained binary and drop it into your NetDaemon deployment directory. +See `HomeAssistant.Server/README.md` for the upstream template notes. + +> **Scoped services:** NetDaemon registers `IHaContext` as scoped. Any app +> service that injects `IHaContext` must be registered **scoped** or +> **transient**, never singleton, or app load fails with +> _"Cannot resolve scoped service … from root provider."_ + +## Configuration + +Each monitor reads its options from the NetDaemon host configuration +(`appsettings.json` / `appsettings.Development.json`) via +`IOptions<*Options>`. Entity IDs, thresholds, and poll intervals are all +configurable. See the `*Options` classes under each `*.Models` / `*.Manager` +project for the full list of settings. + +Never commit secrets. Use `appsettings.Development.json` (already ignored) or +environment variables, using the `__` separator for nested keys. + +## Documentation + +- `docs/` — brainstorm notes, plans, and design docs +- `HomeAssistant.HistoryReplay/README.md` — history replay tool +- `HomeAssistant.Server/README.md` — NetDaemon host template notes +- [NetDaemon docs](https://netdaemon.xyz/docs) + +## License + +Personal project; no license granted for redistribution. See repository +history for authorship. \ No newline at end of file diff --git a/ShowerMonitor.Manager.Tests/ExhaustFanControlServiceTests.cs b/ShowerMonitor.Manager.Tests/ExhaustFanControlServiceTests.cs index 9c7116a..ee158d3 100644 --- a/ShowerMonitor.Manager.Tests/ExhaustFanControlServiceTests.cs +++ b/ShowerMonitor.Manager.Tests/ExhaustFanControlServiceTests.cs @@ -1,5 +1,4 @@ using FluentAssertions; -using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Moq; using NetDaemon.HassModel; @@ -24,9 +23,7 @@ public class ExhaustFanControlServiceTests private ExhaustFanControlService CreateService(ShowerMonitorOptions? options = null) { - return new ExhaustFanControlService( - Mock.Of>(), - Options.Create(options ?? _defaultOptions)); + return new ExhaustFanControlService(Options.Create(options ?? _defaultOptions)); } [Fact] diff --git a/ShowerMonitor.Manager.Tests/ShowerDetectionServiceTests.cs b/ShowerMonitor.Manager.Tests/ShowerDetectionServiceTests.cs index 2690d87..36f7031 100644 --- a/ShowerMonitor.Manager.Tests/ShowerDetectionServiceTests.cs +++ b/ShowerMonitor.Manager.Tests/ShowerDetectionServiceTests.cs @@ -1,7 +1,5 @@ using FluentAssertions; -using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; -using Moq; using ShowerMonitor.Models.Enums; using ShowerMonitorManager; using ShowerMonitorManager.Interface; @@ -31,7 +29,6 @@ public class ShowerDetectionServiceTests return new ShowerDetectionService( calculator, - Mock.Of>(), Options.Create(opts)); } diff --git a/ShowerMonitor.Manager/ExhaustFanControlService.cs b/ShowerMonitor.Manager/ExhaustFanControlService.cs index 3356d84..9187f96 100644 --- a/ShowerMonitor.Manager/ExhaustFanControlService.cs +++ b/ShowerMonitor.Manager/ExhaustFanControlService.cs @@ -1,4 +1,3 @@ -using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using NetDaemon.HassModel; using NetDaemon.HassModel.Entities; @@ -8,23 +7,14 @@ using ShowerMonitorManager.Models; namespace ShowerMonitorManager; -public sealed class ExhaustFanControlService : IExhaustFanControlService +public sealed class ExhaustFanControlService(IOptions options) : IExhaustFanControlService { - private readonly ILogger _logger; - private readonly ShowerMonitorOptions _options; + private readonly ShowerMonitorOptions _options = options.Value; private readonly Lock _lock = new(); private bool _fanTurnedOnByUs; private DateTimeOffset? _showerEndedAt; - public ExhaustFanControlService( - ILogger logger, - IOptions options) - { - _logger = logger; - _options = options.Value; - } - public void Evaluate(ShowerState state, DateTimeOffset timestamp, IHaContext haContext) { lock (_lock) @@ -57,7 +47,6 @@ public sealed class ExhaustFanControlService : IExhaustFanControlService if (_fanTurnedOnByUs) { haContext.CallService("switch", "turn_off", ServiceTarget.FromEntity(_options.ExhaustFanEntityId)); - _logger.LogInformation("Exhaust fan turned OFF during reset (was turned on by shower detection)"); } _fanTurnedOnByUs = false; @@ -80,7 +69,6 @@ public sealed class ExhaustFanControlService : IExhaustFanControlService haContext.CallService("switch", "turn_on", ServiceTarget.FromEntity(_options.ExhaustFanEntityId)); _fanTurnedOnByUs = true; - _logger.LogInformation("Exhaust fan turned ON by shower detection"); } private void EvaluatePostShowerFanOff(DateTimeOffset timestamp, IHaContext haContext) @@ -101,6 +89,5 @@ public sealed class ExhaustFanControlService : IExhaustFanControlService haContext.CallService("switch", "turn_off", ServiceTarget.FromEntity(_options.ExhaustFanEntityId)); _fanTurnedOnByUs = false; _showerEndedAt = null; - _logger.LogInformation("Exhaust fan turned OFF after post-shower run period ({Duration})", runAfterDuration); } } diff --git a/ShowerMonitor.Manager/Interface/IShowerMonitorEntityService.cs b/ShowerMonitor.Manager/Interface/IShowerMonitorEntityService.cs index 8d0c9ae..475e201 100644 --- a/ShowerMonitor.Manager/Interface/IShowerMonitorEntityService.cs +++ b/ShowerMonitor.Manager/Interface/IShowerMonitorEntityService.cs @@ -6,6 +6,5 @@ public interface IShowerMonitorEntityService { Task CreateEntitiesAsync(CancellationToken cancellationToken = default); Task UpdateEntitiesAsync(ShowerMonitorUpdateContext context, CancellationToken cancellationToken = default); - Task ResetEntitiesAsync(CancellationToken cancellationToken = default); Task CleanupEntitiesAsync(CancellationToken cancellationToken = default); } diff --git a/ShowerMonitor.Manager/ShowerDetectionService.cs b/ShowerMonitor.Manager/ShowerDetectionService.cs index ebcd3a4..692cf17 100644 --- a/ShowerMonitor.Manager/ShowerDetectionService.cs +++ b/ShowerMonitor.Manager/ShowerDetectionService.cs @@ -1,4 +1,3 @@ -using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using ShowerMonitor.Models; using ShowerMonitor.Models.Enums; @@ -7,11 +6,12 @@ using ShowerMonitorManager.Models; namespace ShowerMonitorManager; -public sealed class ShowerDetectionService : IShowerDetectionService +public sealed class ShowerDetectionService( + IHumidityRateCalculator rateCalculator, + IOptions options) + : IShowerDetectionService { - private readonly IHumidityRateCalculator _rateCalculator; - private readonly ILogger _logger; - private readonly ShowerMonitorOptions _options; + private readonly ShowerMonitorOptions _options = options.Value; private readonly Lock _lock = new(); private ShowerState _currentState = ShowerState.Idle; @@ -20,16 +20,6 @@ public sealed class ShowerDetectionService : IShowerDetectionService private int _todaySessionCount; private DateTimeOffset? _suspectedSince; - public ShowerDetectionService( - IHumidityRateCalculator rateCalculator, - ILogger logger, - IOptions options) - { - _rateCalculator = rateCalculator; - _logger = logger; - _options = options.Value; - } - public ShowerState CurrentState { get { lock (_lock) { return _currentState; } } @@ -52,13 +42,12 @@ public sealed class ShowerDetectionService : IShowerDetectionService public ShowerState Evaluate(double bathroomHumidity, double mainHomeHumidity, DateTimeOffset timestamp) { - _rateCalculator.RecordReading(bathroomHumidity, timestamp); - var rate = _rateCalculator.GetRatePerMinute(); + rateCalculator.RecordReading(bathroomHumidity, timestamp); + var rate = rateCalculator.GetRatePerMinute(); var differential = bathroomHumidity - mainHomeHumidity; lock (_lock) { - var previousState = _currentState; _currentState = _currentState switch { ShowerState.Idle => EvaluateIdle(rate, differential, bathroomHumidity, timestamp), @@ -69,13 +58,6 @@ public sealed class ShowerDetectionService : IShowerDetectionService _ => _currentState }; - if (_currentState != previousState) - { - _logger.LogInformation( - "Shower state transition: {Previous} -> {Current} (humidity={Humidity}%, differential={Diff}%, rate={Rate}%/min)", - previousState, _currentState, bathroomHumidity, Math.Round(differential, 1), Math.Round(rate, 2)); - } - return _currentState; } } @@ -86,7 +68,6 @@ public sealed class ShowerDetectionService : IShowerDetectionService { _todaySessionCount = 0; _lastCompletedSession = null; - _logger.LogInformation("Shower monitor daily counters reset"); } } @@ -103,7 +84,6 @@ public sealed class ShowerDetectionService : IShowerDetectionService PeakTime = timestamp }; - _logger.LogInformation("Shower suspected: rate={Rate}%/min, differential={Diff}%", Math.Round(rate, 2), Math.Round(differential, 1)); return ShowerState.Suspected; } @@ -119,17 +99,16 @@ public sealed class ShowerDetectionService : IShowerDetectionService } var confirmationWindow = TimeSpan.FromMinutes(_options.ConfirmationWindowMinutes); + if (_suspectedSince.HasValue && (timestamp - _suspectedSince.Value) >= confirmationWindow && humidity >= _options.PeakHumidityThreshold && differential >= _options.MinDifferentialHumidity) { - _logger.LogInformation("Shower confirmed: peak={Peak}%, differential={Diff}%", humidity, Math.Round(differential, 1)); return ShowerState.Active; } if (rate < 0 && differential < _options.MinDifferentialHumidity) { - _logger.LogInformation("Shower suspicion cleared: differential dropped below threshold"); CompleteSessionCleanup(); return ShowerState.Idle; } @@ -146,9 +125,9 @@ public sealed class ShowerDetectionService : IShowerDetectionService } var maxDuration = TimeSpan.FromMinutes(_options.MaxShowerDurationMinutes); + if (_currentSession is not null && _currentSession.Duration >= maxDuration) { - _logger.LogWarning("Shower exceeded max duration ({MaxDuration}), completing", maxDuration); return TransitionToDeclining(timestamp); } @@ -169,9 +148,9 @@ public sealed class ShowerDetectionService : IShowerDetectionService } var maxDuration = TimeSpan.FromMinutes(_options.MaxShowerDurationMinutes); + if (_currentSession is not null && _currentSession.Duration >= maxDuration) { - _logger.LogWarning("Shower declining phase exceeded max duration, completing"); CompleteSession(timestamp); return ShowerState.Completed; } @@ -181,13 +160,12 @@ public sealed class ShowerDetectionService : IShowerDetectionService private ShowerState TransitionToDeclining(DateTimeOffset timestamp) { - _logger.LogInformation("Shower entering decline phase at {Time}", timestamp); return ShowerState.Declining; } private ShowerState TransitionToIdle() { - _rateCalculator.Reset(); + rateCalculator.Reset(); return ShowerState.Idle; } @@ -202,10 +180,6 @@ public sealed class ShowerDetectionService : IShowerDetectionService _lastCompletedSession = _currentSession; _todaySessionCount++; - _logger.LogInformation( - "Shower session completed: duration={Duration}, peak={Peak}%, sessions today={Count}", - _currentSession.Duration, _currentSession.PeakHumidity, _todaySessionCount); - _currentSession = null; _suspectedSince = null; } diff --git a/ShowerMonitor.Manager/ShowerMonitorEntityService.cs b/ShowerMonitor.Manager/ShowerMonitorEntityService.cs index a6a519c..9192fde 100644 --- a/ShowerMonitor.Manager/ShowerMonitorEntityService.cs +++ b/ShowerMonitor.Manager/ShowerMonitorEntityService.cs @@ -19,7 +19,6 @@ public sealed class ShowerMonitorEntityService( StateEntityId, DifferentialEntityId, HumidityRateEntityId, - TodaySessionCountEntityId, LastShowerDurationEntityId, LastShowerTimeEntityId, CleanupButtonEntityId @@ -42,7 +41,6 @@ public sealed class ShowerMonitorEntityService( { try { - logger.LogInformation("Creating MQTT entity: {EntityId}", entity.EntityId); await entityManager.CreateEntityAsync(entity).ConfigureAwait(false); } catch (Exception ex) @@ -67,37 +65,19 @@ public sealed class ShowerMonitorEntityService( SetEntityStateSafe(StateEntityId, ctx.State.ToString().ToLowerInvariant()), UpdateDifferentialAsync(ctx.Differential, timestamp), UpdateHumidityRateAsync(ctx.HumidityRate, timestamp), - UpdateTodaySessionCountAsync(ctx.TodaySessionCount, timestamp), UpdateLastShowerAsync(ctx.LastCompletedSession, timestamp) }; await Task.WhenAll(updateTasks).ConfigureAwait(false); } - public async Task ResetEntitiesAsync(CancellationToken cancellationToken = default) - { - cancellationToken.ThrowIfCancellationRequested(); - - logger.LogInformation("Resetting ShowerMonitor entity states to defaults"); - - await Task.WhenAll( - SetEntityStateSafe(ActiveEntityId, "off"), - SetEntityStateSafe(StateEntityId, ShowerState.Idle.ToString().ToLowerInvariant()), - SetEntityStateSafe(DifferentialEntityId, "0"), - SetEntityStateSafe(HumidityRateEntityId, "0"), - SetEntityStateSafe(TodaySessionCountEntityId, "0"), - SetEntityStateSafe(LastShowerDurationEntityId, "0"), - SetEntityStateSafe(LastShowerTimeEntityId, "unknown") - ).ConfigureAwait(false); - } - public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); try { - var removeTasks = CleanableEntityIds.Select(entityId => entityManager.RemoveEntity(entityId)); + var removeTasks = CleanableEntityIds.Select(entityManager.RemoveEntity); await Task.WhenAll(removeTasks).ConfigureAwait(false); logger.LogInformation("ShowerMonitor entities cleaned up successfully"); @@ -172,16 +152,6 @@ public sealed class ShowerMonitorEntityService( }).ConfigureAwait(false); } - private async Task UpdateTodaySessionCountAsync(int count, string timestamp) - { - await SetEntityStateSafe(TodaySessionCountEntityId, count.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false); - await SetEntityAttributesSafe(TodaySessionCountEntityId, new - { - friendly_name = "Showers today", - last_updated = timestamp - }).ConfigureAwait(false); - } - private async Task UpdateLastShowerAsync(ShowerSession? session, string timestamp) { if (session is null) @@ -235,6 +205,7 @@ public sealed class ShowerMonitorEntityService( { var totalMinutes = (int)ts.TotalMinutes; var seconds = ts.Seconds; + return $"{totalMinutes}m {seconds}s"; } } diff --git a/ShowerMonitor.Manager/ShowerMonitorInit.cs b/ShowerMonitor.Manager/ShowerMonitorInit.cs index 66c81cd..3f44565 100644 --- a/ShowerMonitor.Manager/ShowerMonitorInit.cs +++ b/ShowerMonitor.Manager/ShowerMonitorInit.cs @@ -76,7 +76,6 @@ public sealed class ShowerMonitorInit : IShowerMonitorInit } await _entityService.CreateEntitiesAsync(); - await _entityService.ResetEntitiesAsync(); await Task.Delay(TimeSpan.FromSeconds(2)); await PollAndUpdateAsync(); @@ -103,8 +102,6 @@ public sealed class ShowerMonitorInit : IShowerMonitorInit var secondsUntilNext = _options.PollIntervalSeconds - currentSecondInInterval; var nextPollTime = now.Add(TimeSpan.FromSeconds(secondsUntilNext)); - _logger.LogInformation("Scheduling ShowerMonitor polling every {Interval}s, first at {Time}", _options.PollIntervalSeconds, nextPollTime); - _scheduler.RunEvery(pollInterval, nextPollTime, async void () => { try @@ -124,9 +121,8 @@ public sealed class ShowerMonitorInit : IShowerMonitorInit { try { - _logger.LogInformation("Midnight reset: clearing shower session counters"); + _logger.LogDebug("Midnight reset: clearing shower session counters"); _detectionService.ResetDailyCounters(); - _ = _entityService.ResetEntitiesAsync(); } catch (Exception ex) { @@ -141,7 +137,7 @@ public sealed class ShowerMonitorInit : IShowerMonitorInit cleanupButton.StateChanges() .Subscribe(_ => { - _logger.LogInformation("Cleanup button pressed, removing all ShowerMonitor entities"); + _logger.LogDebug("Cleanup button pressed, removing all ShowerMonitor entities"); Task.Run(HandleCleanupAsync); }); } @@ -154,7 +150,7 @@ public sealed class ShowerMonitorInit : IShowerMonitorInit _cleanedUp = true; _detectionService.ResetDailyCounters(); _fanControlService.Reset(_haContext); - _logger.LogInformation("ShowerMonitor cleanup complete"); + _logger.LogDebug("ShowerMonitor cleanup complete"); } catch (Exception ex) { diff --git a/ShowerMonitor.Models/ShowerMonitorConsts.cs b/ShowerMonitor.Models/ShowerMonitorConsts.cs index 85380ad..4cdb979 100644 --- a/ShowerMonitor.Models/ShowerMonitorConsts.cs +++ b/ShowerMonitor.Models/ShowerMonitorConsts.cs @@ -23,7 +23,6 @@ public static class ShowerMonitorConsts public const string StateEntityId = "sensor.showermonitor_state"; public const string DifferentialEntityId = "sensor.showermonitor_differential_humidity"; public const string HumidityRateEntityId = "sensor.showermonitor_humidity_rate"; - public const string TodaySessionCountEntityId = "sensor.showermonitor_today_session_count"; public const string LastShowerDurationEntityId = "sensor.showermonitor_last_shower_duration"; public const string LastShowerTimeEntityId = "sensor.showermonitor_last_shower_time"; public const string CleanupButtonEntityId = "button.showermonitor_cleanup"; diff --git a/docs/superpowers/plans/2026-04-10-water-ready-false-positive-fix.md b/docs/superpowers/plans/2026-04-10-water-ready-false-positive-fix.md new file mode 100644 index 0000000..bd6d012 --- /dev/null +++ b/docs/superpowers/plans/2026-04-10-water-ready-false-positive-fix.md @@ -0,0 +1,182 @@ +# Water Ready False Positive Fix — Implementation Plan + +**Goal:** Eliminate false "water ready" detections caused by stale/zero power readings when the boiler switch is on but hasn't started drawing power yet. + +**Tech Stack:** C# / .NET, NetDaemon, xUnit + Moq + FluentAssertions + +--- + +## Problem Analysis + +### Observed Behavior (Apr 10, 08:32-08:58) + +The `sensor.boilermonitor_water_ready` oscillated `yes`/`no` 10 times in 26 minutes. All entries show `boiler_switch_state=on` and `boiler_power_watts=0W`. The boiler was turned on during a cheap NordPool interval but the power sensor reported 0W, triggering false "water ready" detection. + +### Root Causes + +1. **No "was heating" prerequisite** — `WaterReadyService.IsWaterReady()` triggers on any low-power reading while the switch is on. It doesn't verify that the boiler was actually observed heating first. A legitimate "water ready" event requires the boiler to have been heating (high power) and then power dropped (heating finished). A boiler that was just turned on but hasn't ramped up yet should NOT trigger "water ready". + +2. **Fixed warm-up grace period too short** — The 2-minute `WarmUpGracePeriod` assumes the boiler starts drawing power within 2 minutes. Some boilers take longer, or the power sensor can have reporting delays. Once the grace period expires, 0W readings immediately trigger false detections. + +3. **No debouncing** — A single poll reading below threshold triggers the detection. Transient 0W readings from sensor lag, network hiccups, or reporting gaps cause false positives. + +4. **In-memory cooldown state lost on restart** — `_waterReadySince` is only in memory. When the daemon restarts, the cooldown is lost, allowing immediate re-detection. This causes oscillation when paired with the above issues. + +### Impact + +- False "hot water is ready" push notifications (max 2 per hour due to notification cooldown, but still annoying) +- Rapid boiler on/off cycling: the control service turns the boiler off when water is "ready", then back on next cheap interval, repeating every few minutes +- Wasted energy and potential relay wear on the boiler switch + +--- + +## Solution Design + +### Fix 1: Require "was heating" before detecting water ready + +The most impactful fix. Track whether the boiler has been observed actively heating (power >= threshold) at least once since the last turn-on. Only allow water ready detection after heating has been observed. + +**Why:** A boiler that was just turned on and reads 0W hasn't finished heating — it hasn't started yet. The legitimate "water ready" pattern is: turn on → power rises → power drops → water ready. + +### Fix 2: Debounce water ready detection + +Require N consecutive below-threshold readings before declaring water ready. This filters out transient sensor glitches. + +**Why:** A single 0W reading could be a sensor reporting gap. Requiring consecutive readings confirms the power has genuinely dropped. + +### Fix 3: Replace fixed grace period with dynamic "await first heating" behavior + +Instead of a fixed 2-minute warm-up grace period, keep suppressing water ready detection until the boiler has been observed drawing power at least once. The grace period effectively becomes unbounded until the first high-power reading. + +**Why:** Fix 1 and Fix 3 are complementary. Fix 3 replaces the brittle time-based heuristic with a state-based one. + +### Fix 4: Persist cooldown timestamp + +Store `_waterReadySince` in the HA entity attributes so the cooldown survives daemon restarts. + +**Why:** Prevents re-triggering water ready immediately after a restart within the cooldown window. + +--- + +## File Structure + +| File | Change | +|---|---| +| `BoilerMonitor.Manager/WaterReadyService.cs` | **Modified** — add `_hasObservedHeating`, consecutive reading counter, persist/restore cooldown | +| `BoilerMonitor.Manager/Interface/IWaterReadyService.cs` | **Modified** — add `RecordHeatingObserved()`, `RestoreCooldownState()` | +| `BoilerMonitor.Manager/BoilerMonitorInit.cs` | **Modified** — call `RecordHeatingObserved()` when isHeating=true, restore cooldown on startup | +| `BoilerMonitor.Manager/BoilerMonitorEntityService.cs` | **Modified** — persist/read cooldown timestamp in water ready entity attributes | +| `BoilerMonitor.Manager/Interface/IBoilerMonitorEntityService.cs` | **Modified** — add `ReadPersistedCooldownTimestamp()` | +| `BoilerMonitor.Models/BoilerMonitorConsts.cs` | **Modified** — add `ConsecutiveReadingsRequired` constant | +| `BoilerMonitor.Manager.Tests/WaterReadyServiceTests.cs` | **Modified** — add tests for all new behaviors | + +--- + +## Implementation Steps + +### Step 1: Add "was heating" tracking and debouncing to WaterReadyService + +- [ ] Add `_hasObservedHeating` (bool) field — resets to `false` on `NotifyTurnedOn()`, set to `true` via new `RecordHeatingObserved()` method +- [ ] Add `_consecutiveBelowThresholdCount` (int) field — increments on each below-threshold reading, resets to 0 on above-threshold reading +- [ ] Add `ConsecutiveReadingsRequired` constant to `BoilerMonitorConsts` (value: 2 — at 30s poll interval, this means 60s of confirmed low power) +- [ ] Modify `IsWaterReady()` logic: + - After cooldown check (unchanged) + - After null/switch-off checks (unchanged) + - **Remove** the warm-up grace period check entirely (replaced by `_hasObservedHeating`) + - **New**: if `!_hasObservedHeating`, return `false` (boiler hasn't been seen heating yet) + - **New**: if `powerWatts < threshold`, increment `_consecutiveBelowThresholdCount`; otherwise reset to 0 and return `false` + - **New**: only return `true` when `_consecutiveBelowThresholdCount >= ConsecutiveReadingsRequired` +- [ ] Update `NotifyTurnedOn()` to reset `_hasObservedHeating = false` and `_consecutiveBelowThresholdCount = 0` +- [ ] Add `RecordHeatingObserved()` method that sets `_hasObservedHeating = true` +- [ ] Update `IWaterReadyService` interface with `RecordHeatingObserved()` + +### Step 2: Integrate heating observation into poll loop + +- [ ] In `BoilerMonitorInit.PollAndUpdateAsync()`, after computing `isHeating`: + ``` + if (isHeating) + { + _waterReadyService.RecordHeatingObserved(); + } + ``` +- [ ] Remove the `IsWithinWarmUpGracePeriod()` reference from any documentation/comments (the warm-up grace period is replaced) + +### Step 3: Persist and restore cooldown state + +- [ ] In `BoilerMonitorEntityService.UpdateWaterReadyAsync()`, add `cooldown_since` attribute (ISO 8601 string or null) +- [ ] Add `ReadPersistedCooldownTimestamp()` method to `BoilerMonitorEntityService` — reads `cooldown_since` from the water ready entity attributes +- [ ] Add `RestoreCooldownState(DateTimeOffset? waterReadySince)` method to `WaterReadyService` +- [ ] In `BoilerMonitorInit.InitializeAsync()`, after restoring persisted state, restore cooldown: + ``` + var persistedCooldown = _entityService.ReadPersistedCooldownTimestamp(); + if (persistedCooldown.HasValue) + { + _waterReadyService.RestoreCooldownState(persistedCooldown.Value); + } + ``` +- [ ] Update `IWaterReadyService` interface with `RestoreCooldownState()` +- [ ] Update `IBoilerMonitorEntityService` interface with `ReadPersistedCooldownTimestamp()` + +### Step 4: Update unit tests + +- [ ] **New test:** `IsWaterReady_SwitchOnLowPowerButNeverObservedHeating_ShouldReturnFalse` — switch=on, power=0, but no `RecordHeatingObserved()` call → false +- [ ] **New test:** `IsWaterReady_AfterObservedHeatingAndPowerDrops_ShouldReturnTrue` — switch=on, call `RecordHeatingObserved()`, then power=0 with consecutive readings → true +- [ ] **New test:** `IsWaterReady_SingleBelowThresholdReading_ShouldReturnFalse` — only 1 consecutive low reading, need 2 → false +- [ ] **New test:** `IsWaterReady_ConsecutiveBelowThresholdReadings_ShouldReturnTrue` — 2 consecutive → true +- [ ] **New test:** `IsWaterReady_BelowThresholdResetByAboveThreshold_ShouldRequireConsecutiveAgain` — counter resets on high power +- [ ] **New test:** `NotifyTurnedOn_ShouldResetHasObservedHeating` — verify that `NotifyTurnedOn()` resets the flag +- [ ] **New test:** `RecordHeatingObserved_ShouldEnableDetection` — verify the flag is set +- [ ] **New test:** `RestoreCooldownState_ShouldResumeActiveCooldown` — verify restored cooldown works +- [ ] **New test:** `RestoreCooldownState_WithExpiredTimestamp_ShouldNotActivateCooldown` — expired cooldown doesn't restore +- [ ] **Update existing tests** — remove warm-up grace period tests (replaced by `_hasObservedHeating` tests), update any test that expects immediate detection without `RecordHeatingObserved()` + +### Step 5: Remove deprecated warm-up grace period + +- [ ] Remove `IsWithinWarmUpGracePeriod()` private method from `WaterReadyService` +- [ ] Remove `_lastTurnedOnAt` field (no longer needed — `NotifyTurnedOn` only resets `_hasObservedHeating` and debounce counter) +- [ ] Remove `WarmUpGracePeriod` constant from `BoilerMonitorConsts` (or keep for backwards compatibility with a deprecation comment) +- [ ] Update `NotifyTurnedOn()` to not set `_lastTurnedOnAt` + +--- + +## Detection Logic Before vs After + +### Before (current — buggy) + +``` +IsWaterReady(switch, power, threshold): + if cooldown active → return true + if switch is null or power is null → return false + if switch != "on" → return false + if within 2-minute warm-up grace → return false + return power < threshold +``` + +**Flaw:** After grace period expires, ANY low-power reading triggers detection — even if the boiler was never observed heating. + +### After (fixed) + +``` +IsWaterReady(switch, power, threshold): + if cooldown active → return true + if switch is null or power is null → return false + if switch != "on" → return false + if NOT hasObservedHeating → return false ← NEW: must have seen heating first + if power >= threshold → reset consecutive count, return false + increment consecutive count + if consecutive count < required → return false ← NEW: debounce + start cooldown, return true +``` + +**Result:** Water ready only fires after the boiler was observed actively heating AND power has been consistently below threshold for 2+ consecutive polls (60+ seconds at 30s interval). + +--- + +## Risk Assessment + +| Risk | Mitigation | +|---|---| +| `RecordHeatingObserved()` never called if power sensor is broken | If the sensor never reports high power, water ready never triggers — the boiler control service will still turn off via budget exhaustion or NordPool interval ending | +| Daemon restarts during heating cycle lose `_hasObservedHeating` | Acceptable — after restart, the first high-power poll restores it. At worst, one extra grace cycle before detection resumes | +| `ConsecutiveReadingsRequired = 2` delays legitimate detection by 30s | Acceptable tradeoff — 30s extra delay vs false positive notifications | +| Removing warm-up grace period entirely | The `_hasObservedHeating` flag is strictly stronger — it never expires prematurely like the fixed 2-minute window | diff --git a/global.json b/global.json new file mode 100644 index 0000000..f4fd385 --- /dev/null +++ b/global.json @@ -0,0 +1,7 @@ +{ + "sdk": { + "version": "9.0.0", + "rollForward": "latestMajor", + "allowPrerelease": true + } +} \ No newline at end of file