Update
This commit is contained in:
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"version": 1,
|
||||
"hooks": {
|
||||
"afterShellExecution": [
|
||||
{
|
||||
"command": "powershell -ExecutionPolicy Bypass -File .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
|
||||
@@ -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"
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"version": 1,
|
||||
"lastRunAtMs": 1776455702656,
|
||||
"turnsSinceLastRun": 8,
|
||||
"lastTranscriptMtimeMs": 1776455701006.4348,
|
||||
"lastProcessedGenerationId": "13996b20-c9b1-41f3-bafc-5738130c07ac",
|
||||
"trialStartedAtMs": null
|
||||
}
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -21,6 +21,9 @@
|
||||
</PackageReference>
|
||||
<PackageReference Include="FluentAssertions" Version="8.8.0" />
|
||||
<PackageReference Include="Moq" Version="4.20.72" />
|
||||
<PackageReference Include="NetDaemon.Extensions.Mqtt" Version="26.11.0" />
|
||||
<PackageReference Include="NetDaemon.HassModel" Version="26.11.0" />
|
||||
<PackageReference Include="System.Reactive" Version="6.1.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -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<ILogger<WaterReadyService>> _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
|
||||
|
||||
@@ -8,7 +8,12 @@ public class BoilerControlService(ILogger<BoilerControlService> 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<BoilerControlService> 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<BoilerControlService> 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;
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.5" />
|
||||
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.11.0" />
|
||||
<PackageReference Include="NetDaemon.HassModel" Version="26.11.0" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
@@ -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<string, object> 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
|
||||
|
||||
@@ -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<BoilerMonitorOptions> options)
|
||||
IOptions<BoilerMonitorOptions> options,
|
||||
TimeProvider timeProvider)
|
||||
: this(
|
||||
haContext,
|
||||
logger,
|
||||
scheduler,
|
||||
mqttEntityManager,
|
||||
boilerControlService,
|
||||
tracker,
|
||||
entityService,
|
||||
waterReadyService,
|
||||
options,
|
||||
timeProvider,
|
||||
startBackgroundScheduling: true)
|
||||
{
|
||||
}
|
||||
|
||||
internal BoilerMonitorInit(
|
||||
IHaContext haContext,
|
||||
ILogger<BoilerMonitorInit> logger,
|
||||
IScheduler scheduler,
|
||||
IMqttEntityManager mqttEntityManager,
|
||||
IBoilerControlService boilerControlService,
|
||||
IBoilerRunTimeTracker tracker,
|
||||
IBoilerMonitorEntityService entityService,
|
||||
IWaterReadyService waterReadyService,
|
||||
IOptions<BoilerMonitorOptions> 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<string, object> 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;
|
||||
}
|
||||
|
||||
@@ -15,6 +15,10 @@ public static class BoilerMonitorServiceRegistration
|
||||
.GetSection(BoilerMonitorOptions.SectionName)
|
||||
.Get<BoilerMonitorOptions>() ?? 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<IBoilerConfigReader, BoilerConfigReader>();
|
||||
|
||||
if (!options.Enabled)
|
||||
{
|
||||
return services;
|
||||
@@ -26,8 +30,7 @@ public static class BoilerMonitorServiceRegistration
|
||||
.AddSingleton<IBoilerRunTimeTracker, BoilerRunTimeTracker>()
|
||||
.AddTransient<IBoilerMonitorEntityService, BoilerMonitorEntityService>()
|
||||
.AddSingleton<IWaterReadyService, WaterReadyService>()
|
||||
.AddSingleton(TimeProvider.System)
|
||||
.AddScoped<IBoilerConfigReader, BoilerConfigReader>();
|
||||
.AddSingleton(TimeProvider.System);
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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; }
|
||||
}
|
||||
|
||||
@@ -8,8 +8,9 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> 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<WaterReadyService> 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<WaterReadyService> 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<WaterReadyService> 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;
|
||||
}
|
||||
|
||||
@@ -11,18 +11,20 @@ public static class BoilerMonitorConsts
|
||||
public const double DefaultHeatingPowerThresholdWatts = 5.0;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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";
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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";
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
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";
|
||||
|
||||
@@ -1321,6 +1321,8 @@ public partial class SwitchEntities
|
||||
public SwitchEntity BalkonyLaps => new(_haContext, "switch.balkony_laps");
|
||||
///<summary>Boiler Monitor Override budget enforcement</summary>
|
||||
public SwitchEntity BoilermonitorBudgetOverride => new(_haContext, "switch.boilermonitor_budget_override");
|
||||
///<summary>Boiler Monitor Automatic boiler control</summary>
|
||||
public SwitchEntity BoilermonitorAutoManagement => new(_haContext, "switch.boilermonitor_auto_management");
|
||||
///<summary>Boiler Monitor Skip price cap, heat until ready</summary>
|
||||
public SwitchEntity BoilermonitorSkipPriceCap => new(_haContext, "switch.boilermonitor_skip_price_cap");
|
||||
///<summary>Dishwasher</summary>
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en" data-bs-theme="dark">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>HA History Replay</title>
|
||||
<base href="/" />
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" />
|
||||
<link href="css/app.css" rel="stylesheet" />
|
||||
<HeadOutlet @rendermode="InteractiveServer" />
|
||||
</head>
|
||||
<body>
|
||||
<Routes @rendermode="InteractiveServer" />
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
|
||||
<script src="_framework/blazor.web.js"></script>
|
||||
<script src="_content/Blazor-ApexCharts/js/apexcharts.esm.js" type="module"></script>
|
||||
<script src="_content/Blazor-ApexCharts/js/blazor-apexcharts.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,44 @@
|
||||
@code {
|
||||
[Parameter] public ReplayDataSeries? DataSeries { get; set; }
|
||||
|
||||
private List<ReplayDataPoint> PowerData => DataSeries?.GetSeries("Boiler", "PowerWatts").ToList() ?? [];
|
||||
private List<ReplayDataPoint> BudgetData => DataSeries?.GetSeries("Boiler", "BudgetPercent").ToList() ?? [];
|
||||
private List<ReplayDataPoint> SwitchData => DataSeries?.GetSeries("Boiler", "SwitchState").ToList() ?? [];
|
||||
|
||||
private ApexChartOptions<ReplayDataPoint> ChartOptions => new()
|
||||
{
|
||||
Chart = new Chart { Background = "transparent", ForeColor = "#adb5bd" },
|
||||
Theme = new Theme { Mode = Mode.Dark },
|
||||
Stroke = new Stroke { Width = 2 },
|
||||
Xaxis = new XAxis { Type = XAxisType.Datetime },
|
||||
Yaxis =
|
||||
[
|
||||
new YAxis { Title = new AxisTitle { Text = "Watts" }, SeriesName = "Power (W)", DecimalsInFloat = 0 },
|
||||
new YAxis { Title = new AxisTitle { Text = "%" }, SeriesName = "Budget %", Opposite = true, Max = 100, DecimalsInFloat = 0 }
|
||||
],
|
||||
Tooltip = new Tooltip { X = new TooltipX { Format = "HH:mm" } },
|
||||
Grid = new Grid { BorderColor = "#343a40" }
|
||||
};
|
||||
}
|
||||
|
||||
@if (PowerData.Count > 0)
|
||||
{
|
||||
<ApexChart TItem="ReplayDataPoint" Options="ChartOptions" Height="300">
|
||||
<ApexPointSeries TItem="ReplayDataPoint"
|
||||
Items="PowerData"
|
||||
SeriesType="SeriesType.Area"
|
||||
Name="Power (W)"
|
||||
XValue="p => p.Timestamp.ToLocalTime().DateTime"
|
||||
YValue="p => (decimal)p.Value" />
|
||||
<ApexPointSeries TItem="ReplayDataPoint"
|
||||
Items="BudgetData"
|
||||
SeriesType="SeriesType.Line"
|
||||
Name="Budget %"
|
||||
XValue="p => p.Timestamp.ToLocalTime().DateTime"
|
||||
YValue="p => (decimal)p.Value" />
|
||||
</ApexChart>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="text-muted text-center py-4">No boiler data available</div>
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
@code {
|
||||
[Parameter] public ReplayTimeline? Timeline { get; set; }
|
||||
|
||||
private IReadOnlyList<ReplayEvent> LightEvents =>
|
||||
Timeline?.GetEventsByMonitor("Light") ?? [];
|
||||
}
|
||||
|
||||
<div class="card bg-dark">
|
||||
<div class="card-body">
|
||||
@if (LightEvents.Count > 0)
|
||||
{
|
||||
<div class="d-flex flex-column gap-2">
|
||||
@foreach (var evt in LightEvents)
|
||||
{
|
||||
var iconClass = evt.EventType == ReplayEventType.Decision ? "text-warning" : "text-muted";
|
||||
var icon = evt.EventType == ReplayEventType.Decision ? "☀" : "•";
|
||||
<div class="d-flex align-items-start gap-2">
|
||||
<span class="font-monospace small text-nowrap">@evt.Timestamp.ToLocalTime().ToString("HH:mm")</span>
|
||||
<span class="@iconClass">@((MarkupString)icon)</span>
|
||||
<span class="small">@evt.Message</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="text-muted text-center py-4">No light events</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,32 @@
|
||||
@code {
|
||||
[Parameter] public ReplayDataSeries? DataSeries { get; set; }
|
||||
|
||||
private List<ReplayDataPoint> PriceData => DataSeries?.GetSeries("NordPool", "Price").ToList() ?? [];
|
||||
|
||||
private ApexChartOptions<ReplayDataPoint> ChartOptions => new()
|
||||
{
|
||||
Chart = new Chart { Background = "transparent", ForeColor = "#adb5bd" },
|
||||
Theme = new Theme { Mode = Mode.Dark },
|
||||
Stroke = new Stroke { Curve = Curve.Smooth, Width = 2 },
|
||||
Xaxis = new XAxis { Type = XAxisType.Datetime },
|
||||
Yaxis = [new YAxis { Title = new AxisTitle { Text = "ct/kWh" }, DecimalsInFloat = 2 }],
|
||||
Tooltip = new Tooltip { X = new TooltipX { Format = "HH:mm" } },
|
||||
Grid = new Grid { BorderColor = "#343a40" }
|
||||
};
|
||||
}
|
||||
|
||||
@if (PriceData.Count > 0)
|
||||
{
|
||||
<ApexChart TItem="ReplayDataPoint" Options="ChartOptions" Height="300">
|
||||
<ApexPointSeries TItem="ReplayDataPoint"
|
||||
Items="PriceData"
|
||||
SeriesType="SeriesType.Area"
|
||||
Name="Price (ct/kWh)"
|
||||
XValue="p => p.Timestamp.ToLocalTime().DateTime"
|
||||
YValue="p => (decimal)p.Value" />
|
||||
</ApexChart>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="text-muted text-center py-4">No price data available</div>
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
@code {
|
||||
[Parameter] public ReplayDataSeries? DataSeries { get; set; }
|
||||
|
||||
private List<ReplayDataPoint> TotalData => DataSeries?.GetSeries("Power", "TotalPower").ToList() ?? [];
|
||||
private List<ReplayDataPoint> KnownData => DataSeries?.GetSeries("Power", "KnownDevices").ToList() ?? [];
|
||||
private List<ReplayDataPoint> OtherData => DataSeries?.GetSeries("Power", "OtherPower").ToList() ?? [];
|
||||
|
||||
private ApexChartOptions<ReplayDataPoint> ChartOptions => new()
|
||||
{
|
||||
Chart = new Chart { Background = "transparent", ForeColor = "#adb5bd", Stacked = true },
|
||||
Theme = new Theme { Mode = Mode.Dark },
|
||||
Stroke = new Stroke { Width = 1 },
|
||||
Xaxis = new XAxis { Type = XAxisType.Datetime },
|
||||
Yaxis = [new YAxis { Title = new AxisTitle { Text = "Watts" }, DecimalsInFloat = 0 }],
|
||||
Tooltip = new Tooltip { X = new TooltipX { Format = "HH:mm:ss" } },
|
||||
Grid = new Grid { BorderColor = "#343a40" }
|
||||
};
|
||||
}
|
||||
|
||||
@if (TotalData.Count > 0)
|
||||
{
|
||||
<ApexChart TItem="ReplayDataPoint" Options="ChartOptions" Height="300">
|
||||
<ApexPointSeries TItem="ReplayDataPoint"
|
||||
Items="KnownData"
|
||||
SeriesType="SeriesType.Area"
|
||||
Name="Known Devices"
|
||||
XValue="p => p.Timestamp.ToLocalTime().DateTime"
|
||||
YValue="p => (decimal)p.Value" />
|
||||
<ApexPointSeries TItem="ReplayDataPoint"
|
||||
Items="OtherData"
|
||||
SeriesType="SeriesType.Area"
|
||||
Name="Other Power"
|
||||
XValue="p => p.Timestamp.ToLocalTime().DateTime"
|
||||
YValue="p => (decimal)p.Value" />
|
||||
</ApexChart>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="text-muted text-center py-4">No power data available</div>
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
@code {
|
||||
[Parameter] public ReplayDataSeries? DataSeries { get; set; }
|
||||
|
||||
private List<ReplayDataPoint> BathroomData => DataSeries?.GetSeries("Shower", "BathroomHumidity").ToList() ?? [];
|
||||
private List<ReplayDataPoint> HomeData => DataSeries?.GetSeries("Shower", "HomeHumidity").ToList() ?? [];
|
||||
private List<ReplayDataPoint> DiffData => DataSeries?.GetSeries("Shower", "Differential").ToList() ?? [];
|
||||
|
||||
private ApexChartOptions<ReplayDataPoint> ChartOptions => new()
|
||||
{
|
||||
Chart = new Chart { Background = "transparent", ForeColor = "#adb5bd" },
|
||||
Theme = new Theme { Mode = Mode.Dark },
|
||||
Stroke = new Stroke { Curve = Curve.Smooth, Width = 2 },
|
||||
Xaxis = new XAxis { Type = XAxisType.Datetime },
|
||||
Yaxis = [new YAxis { Title = new AxisTitle { Text = "Humidity %" }, DecimalsInFloat = 1 }],
|
||||
Tooltip = new Tooltip { X = new TooltipX { Format = "HH:mm" } },
|
||||
Grid = new Grid { BorderColor = "#343a40" }
|
||||
};
|
||||
}
|
||||
|
||||
@if (BathroomData.Count > 0)
|
||||
{
|
||||
<ApexChart TItem="ReplayDataPoint" Options="ChartOptions" Height="300">
|
||||
<ApexPointSeries TItem="ReplayDataPoint"
|
||||
Items="BathroomData"
|
||||
SeriesType="SeriesType.Line"
|
||||
Name="Bathroom Humidity"
|
||||
XValue="p => p.Timestamp.ToLocalTime().DateTime"
|
||||
YValue="p => (decimal)p.Value" />
|
||||
<ApexPointSeries TItem="ReplayDataPoint"
|
||||
Items="HomeData"
|
||||
SeriesType="SeriesType.Line"
|
||||
Name="Home Humidity"
|
||||
XValue="p => p.Timestamp.ToLocalTime().DateTime"
|
||||
YValue="p => (decimal)p.Value" />
|
||||
<ApexPointSeries TItem="ReplayDataPoint"
|
||||
Items="DiffData"
|
||||
SeriesType="SeriesType.Area"
|
||||
Name="Differential"
|
||||
XValue="p => p.Timestamp.ToLocalTime().DateTime"
|
||||
YValue="p => (decimal)p.Value" />
|
||||
</ApexChart>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="text-muted text-center py-4">No shower data available</div>
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
@inherits LayoutComponentBase
|
||||
|
||||
<div class="d-flex flex-column min-vh-100">
|
||||
<nav class="navbar navbar-dark bg-dark border-bottom border-secondary px-3">
|
||||
<span class="navbar-brand mb-0 h1">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" class="bi bi-house-door me-2" viewBox="0 0 16 16">
|
||||
<path d="M8.354 1.146a.5.5 0 0 0-.708 0l-6 6A.5.5 0 0 0 1.5 7.5v7a.5.5 0 0 0 .5.5h4.5a.5.5 0 0 0 .5-.5v-4h2v4a.5.5 0 0 0 .5.5H14a.5.5 0 0 0 .5-.5v-7a.5.5 0 0 0-.146-.354L13 5.793V2.5a.5.5 0 0 0-.5-.5h-1a.5.5 0 0 0-.5.5v1.293zM2.5 14V7.707l5.5-5.5 5.5 5.5V14H10v-4a.5.5 0 0 0-.5-.5h-3a.5.5 0 0 0-.5.5v4z"/>
|
||||
</svg>
|
||||
HA History Replay
|
||||
</span>
|
||||
<span class="text-muted small">Debug Dashboard</span>
|
||||
</nav>
|
||||
|
||||
<main class="flex-grow-1 p-3">
|
||||
@Body
|
||||
</main>
|
||||
</div>
|
||||
@@ -0,0 +1,240 @@
|
||||
@page "/"
|
||||
@inject ReplayOrchestrationService Replay
|
||||
@implements IDisposable
|
||||
|
||||
<h4 class="mb-3">History Replay Dashboard</h4>
|
||||
|
||||
<div class="card mb-3">
|
||||
<div class="card-body">
|
||||
<div class="row g-3 align-items-end">
|
||||
<div class="col-md-3">
|
||||
<label class="form-label small">Start Time</label>
|
||||
<input type="datetime-local" class="form-control form-control-sm"
|
||||
@bind="_startTime" />
|
||||
</div>
|
||||
<div class="col-md-3">
|
||||
<label class="form-label small">End Time</label>
|
||||
<input type="datetime-local" class="form-control form-control-sm"
|
||||
@bind="_endTime" />
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<label class="form-label small">Monitors</label>
|
||||
<div class="d-flex gap-3 flex-wrap">
|
||||
<div class="form-check form-check-inline">
|
||||
<input class="form-check-input" type="checkbox" @bind="_monitors.NordPool" id="chkNord" />
|
||||
<label class="form-check-label small" for="chkNord">NordPool</label>
|
||||
</div>
|
||||
<div class="form-check form-check-inline">
|
||||
<input class="form-check-input" type="checkbox" @bind="_monitors.Boiler" id="chkBoiler" />
|
||||
<label class="form-check-label small" for="chkBoiler">Boiler</label>
|
||||
</div>
|
||||
<div class="form-check form-check-inline">
|
||||
<input class="form-check-input" type="checkbox" @bind="_monitors.Shower" id="chkShower" />
|
||||
<label class="form-check-label small" for="chkShower">Shower</label>
|
||||
</div>
|
||||
<div class="form-check form-check-inline">
|
||||
<input class="form-check-input" type="checkbox" @bind="_monitors.Power" id="chkPower" />
|
||||
<label class="form-check-label small" for="chkPower">Power</label>
|
||||
</div>
|
||||
<div class="form-check form-check-inline">
|
||||
<input class="form-check-input" type="checkbox" @bind="_monitors.Light" id="chkLight" />
|
||||
<label class="form-check-label small" for="chkLight">Light</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-2">
|
||||
<button class="btn btn-primary w-100" @onclick="RunReplay"
|
||||
disabled="@(_isRunning)">
|
||||
@if (_isRunning)
|
||||
{
|
||||
<span class="spinner-border spinner-border-sm me-1" role="status"></span>
|
||||
}
|
||||
Run Replay
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="status-bar mb-3">
|
||||
@switch (Replay.Status)
|
||||
{
|
||||
case ReplayStatus.FetchingHistory:
|
||||
<div class="alert alert-info py-2 mb-0 d-flex align-items-center">
|
||||
<span class="spinner-border spinner-border-sm me-2"></span>
|
||||
@(Replay.ProgressMessage ?? "Fetching history data from Home Assistant...")
|
||||
</div>
|
||||
break;
|
||||
case ReplayStatus.Running:
|
||||
<div class="alert alert-info py-2 mb-0 d-flex align-items-center">
|
||||
<span class="spinner-border spinner-border-sm me-2"></span>
|
||||
@(Replay.ProgressMessage ?? "Running replay...")
|
||||
</div>
|
||||
break;
|
||||
case ReplayStatus.Completed:
|
||||
<div class="alert alert-success py-2 mb-0">
|
||||
Replay completed -- @Replay.Timeline.GetAllEvents().Count event(s)
|
||||
</div>
|
||||
break;
|
||||
case ReplayStatus.Failed:
|
||||
<div class="alert alert-danger py-2 mb-0">
|
||||
Replay failed: @Replay.ErrorMessage
|
||||
</div>
|
||||
break;
|
||||
}
|
||||
</div>
|
||||
|
||||
@if (Replay.Status == ReplayStatus.Completed)
|
||||
{
|
||||
<SummaryCards Timeline="Replay.Timeline" />
|
||||
|
||||
<ul class="nav nav-tabs mb-3" role="tablist">
|
||||
@foreach (var monitor in _enabledMonitors)
|
||||
{
|
||||
var tab = monitor;
|
||||
<li class="nav-item" role="presentation">
|
||||
<button class="nav-link @(tab == _activeTab ? "active" : "")"
|
||||
@onclick="() => SetActiveTab(tab)">
|
||||
@tab
|
||||
</button>
|
||||
</li>
|
||||
}
|
||||
<li class="nav-item" role="presentation">
|
||||
<button class="nav-link @(_activeTab == ServiceCallsTab ? "active" : "")"
|
||||
@onclick="() => SetActiveTab(ServiceCallsTab)">
|
||||
Service Calls
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
<div class="tab-content">
|
||||
@if (_activeTab == NordPoolTab)
|
||||
{
|
||||
<div class="card mb-3">
|
||||
<div class="card-header">NordPool Price Timeline</div>
|
||||
<div class="card-body"><NordPoolChart DataSeries="Replay.DataSeries" /></div>
|
||||
</div>
|
||||
<EventTable Events="GetMonitorEvents(NordPoolTab)" />
|
||||
}
|
||||
else if (_activeTab == BoilerTab)
|
||||
{
|
||||
<div class="card mb-3">
|
||||
<div class="card-header">Boiler Power and Budget</div>
|
||||
<div class="card-body"><BoilerChart DataSeries="Replay.DataSeries" /></div>
|
||||
</div>
|
||||
<EventTable Events="GetMonitorEvents(BoilerTab)" />
|
||||
}
|
||||
else if (_activeTab == ShowerTab)
|
||||
{
|
||||
<div class="card mb-3">
|
||||
<div class="card-header">Humidity and Shower Detection</div>
|
||||
<div class="card-body"><ShowerChart DataSeries="Replay.DataSeries" /></div>
|
||||
</div>
|
||||
<EventTable Events="GetMonitorEvents(ShowerTab)" />
|
||||
}
|
||||
else if (_activeTab == PowerTab)
|
||||
{
|
||||
<div class="card mb-3">
|
||||
<div class="card-header">Power Breakdown</div>
|
||||
<div class="card-body"><PowerChart DataSeries="Replay.DataSeries" /></div>
|
||||
</div>
|
||||
<EventTable Events="GetMonitorEvents(PowerTab)" />
|
||||
}
|
||||
else if (_activeTab == LightTab)
|
||||
{
|
||||
<div class="card mb-3">
|
||||
<div class="card-header">Light Control Events</div>
|
||||
<div class="card-body"><LightChart Timeline="Replay.Timeline" /></div>
|
||||
</div>
|
||||
<EventTable Events="GetMonitorEvents(LightTab)" />
|
||||
}
|
||||
else if (_activeTab == ServiceCallsTab)
|
||||
{
|
||||
<EventTable Events="GetMonitorEvents(ServiceCallMonitor)" />
|
||||
}
|
||||
</div>
|
||||
}
|
||||
|
||||
@code {
|
||||
private const string NordPoolTab = "NordPool";
|
||||
private const string BoilerTab = "Boiler";
|
||||
private const string ShowerTab = "Shower";
|
||||
private const string PowerTab = "Power";
|
||||
private const string LightTab = "Light";
|
||||
private const string ServiceCallsTab = "ServiceCalls";
|
||||
private const string ServiceCallMonitor = "ServiceCall";
|
||||
|
||||
private DateTime _startTime = DateTime.Today.AddDays(-1);
|
||||
private DateTime _endTime = DateTime.Today.AddHours(23).AddMinutes(59);
|
||||
private readonly ReplayMonitorFlags _monitors = new();
|
||||
private bool _isRunning;
|
||||
private string _activeTab = NordPoolTab;
|
||||
private IReadOnlyList<string> _enabledMonitors = [];
|
||||
|
||||
protected override void OnInitialized()
|
||||
{
|
||||
Replay.OnStateChanged += HandleStateChanged;
|
||||
}
|
||||
|
||||
private IReadOnlyList<ReplayEvent> GetMonitorEvents(string monitor) =>
|
||||
Replay.Timeline.GetEventsByMonitor(monitor);
|
||||
|
||||
private void SetActiveTab(string tab)
|
||||
{
|
||||
_activeTab = tab;
|
||||
StateHasChanged();
|
||||
}
|
||||
|
||||
private async Task RunReplay()
|
||||
{
|
||||
_isRunning = true;
|
||||
_enabledMonitors = BuildEnabledMonitors();
|
||||
_activeTab = _enabledMonitors.FirstOrDefault() ?? NordPoolTab;
|
||||
|
||||
var start = new DateTimeOffset(_startTime, TimeZoneInfo.Local.GetUtcOffset(_startTime));
|
||||
var end = new DateTimeOffset(_endTime, TimeZoneInfo.Local.GetUtcOffset(_endTime));
|
||||
|
||||
try
|
||||
{
|
||||
await Task.Run(async () =>
|
||||
await Replay.RunReplayAsync(start, end, _monitors));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Replay.SetError(ex.Message);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_isRunning = false;
|
||||
await InvokeAsync(StateHasChanged);
|
||||
}
|
||||
}
|
||||
|
||||
private IReadOnlyList<string> BuildEnabledMonitors()
|
||||
{
|
||||
var list = new List<string>();
|
||||
if (_monitors.NordPool) list.Add(NordPoolTab);
|
||||
if (_monitors.Boiler) list.Add(BoilerTab);
|
||||
if (_monitors.Shower) list.Add(ShowerTab);
|
||||
if (_monitors.Power) list.Add(PowerTab);
|
||||
if (_monitors.Light) list.Add(LightTab);
|
||||
return list;
|
||||
}
|
||||
|
||||
private async void HandleStateChanged()
|
||||
{
|
||||
try
|
||||
{
|
||||
await InvokeAsync(StateHasChanged);
|
||||
}
|
||||
catch (ObjectDisposedException)
|
||||
{
|
||||
// Component was disposed while an update was in flight
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Replay.OnStateChanged -= HandleStateChanged;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
<Router AppAssembly="typeof(Program).Assembly">
|
||||
<Found Context="routeData">
|
||||
<RouteView RouteData="routeData" DefaultLayout="typeof(Layout.MainLayout)" />
|
||||
<FocusOnNavigate RouteData="routeData" Selector="h1" />
|
||||
</Found>
|
||||
</Router>
|
||||
@@ -0,0 +1,54 @@
|
||||
@code {
|
||||
[Parameter] public IReadOnlyList<ReplayEvent> Events { get; set; } = [];
|
||||
[Parameter] public int MaxRows { get; set; } = 200;
|
||||
|
||||
private string GetBadgeClass(ReplayEventType type) => type switch
|
||||
{
|
||||
ReplayEventType.Decision => "badge-decision",
|
||||
ReplayEventType.StateChange => "badge-statechange",
|
||||
ReplayEventType.Warning => "badge-warning",
|
||||
ReplayEventType.Anomaly => "badge-anomaly",
|
||||
ReplayEventType.ServiceCall => "badge-servicecall",
|
||||
_ => "badge-info"
|
||||
};
|
||||
}
|
||||
|
||||
@if (Events.Count == 0)
|
||||
{
|
||||
<div class="text-muted text-center py-4">No events recorded for this monitor.</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="table-responsive" style="max-height: 400px; overflow-y: auto;">
|
||||
<table class="table table-sm table-hover align-middle mb-0">
|
||||
<thead class="sticky-top" style="background-color: #2b3035;">
|
||||
<tr>
|
||||
<th style="width: 100px;">Time</th>
|
||||
<th style="width: 100px;">Type</th>
|
||||
<th>Message</th>
|
||||
<th>Details</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var evt in Events.Take(MaxRows))
|
||||
{
|
||||
<tr>
|
||||
<td class="text-nowrap font-monospace small">
|
||||
@evt.Timestamp.ToLocalTime().ToString("HH:mm:ss")
|
||||
</td>
|
||||
<td>
|
||||
<span class="badge @GetBadgeClass(evt.EventType)">@evt.EventType</span>
|
||||
</td>
|
||||
<td class="small">@evt.Message</td>
|
||||
<td class="text-muted small">@evt.Details</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
@if (Events.Count > MaxRows)
|
||||
{
|
||||
<div class="text-muted small mt-1">Showing @MaxRows of @Events.Count events</div>
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
@code {
|
||||
[Parameter] public ReplayTimeline? Timeline { get; set; }
|
||||
|
||||
private IReadOnlyList<ReplayEvent> AllEvents => Timeline?.GetAllEvents() ?? [];
|
||||
private int TotalEvents => AllEvents.Count;
|
||||
private int Decisions => AllEvents.Count(e => e.EventType == ReplayEventType.Decision);
|
||||
private int ServiceCalls => AllEvents.Count(e => e.EventType == ReplayEventType.ServiceCall);
|
||||
private int Warnings => AllEvents.Count(e => e.EventType == ReplayEventType.Warning);
|
||||
private int Anomalies => AllEvents.Count(e => e.EventType == ReplayEventType.Anomaly);
|
||||
}
|
||||
|
||||
<div class="row g-3 mb-4">
|
||||
<div class="col">
|
||||
<div class="card stat-card">
|
||||
<div class="card-body">
|
||||
<div class="display-6">@TotalEvents</div>
|
||||
<div class="text-muted small">Total Events</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col">
|
||||
<div class="card stat-card border-success">
|
||||
<div class="card-body">
|
||||
<div class="display-6 text-success">@Decisions</div>
|
||||
<div class="text-muted small">Decisions</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col">
|
||||
<div class="card stat-card border-info">
|
||||
<div class="card-body">
|
||||
<div class="display-6 text-info">@ServiceCalls</div>
|
||||
<div class="text-muted small">Service Calls</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col">
|
||||
<div class="card stat-card border-warning">
|
||||
<div class="card-body">
|
||||
<div class="display-6 text-warning">@Warnings</div>
|
||||
<div class="text-muted small">Warnings</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col">
|
||||
<div class="card stat-card border-danger">
|
||||
<div class="card-body">
|
||||
<div class="display-6 text-danger">@Anomalies</div>
|
||||
<div class="text-muted small">Anomalies</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,15 @@
|
||||
@using System.Net.Http
|
||||
@using Microsoft.AspNetCore.Components.Forms
|
||||
@using Microsoft.AspNetCore.Components.Routing
|
||||
@using Microsoft.AspNetCore.Components.Web
|
||||
@using static Microsoft.AspNetCore.Components.Web.RenderMode
|
||||
@using Microsoft.AspNetCore.Components.Web.Virtualization
|
||||
@using Microsoft.JSInterop
|
||||
@using ApexCharts
|
||||
@using HomeAssistant.HistoryReplay.Components
|
||||
@using HomeAssistant.HistoryReplay.Components.Layout
|
||||
@using HomeAssistant.HistoryReplay.Components.Shared
|
||||
@using HomeAssistant.HistoryReplay.Components.Charts
|
||||
@using HomeAssistant.HistoryReplay.Reporting
|
||||
@using HomeAssistant.HistoryReplay.Services
|
||||
@using HomeAssistant.HistoryReplay.Configuration
|
||||
@@ -24,6 +24,7 @@ public static class ReplayEntityMap
|
||||
"sensor.nordpool_cheapest_intervals",
|
||||
BoilerMonitorConsts.SkipPriceCapEntityId,
|
||||
BoilerMonitorConsts.BudgetOverrideEntityId,
|
||||
BoilerMonitorConsts.AutoManagementEntityId,
|
||||
BoilerMonitorConsts.BoilerDailyHoursEntityId
|
||||
];
|
||||
|
||||
@@ -46,6 +47,11 @@ public static class ReplayEntityMap
|
||||
return entities;
|
||||
}
|
||||
|
||||
public static IReadOnlyList<string> GetEntitiesRequiringAttributes() =>
|
||||
[
|
||||
"sensor.nordpool_cheapest_intervals"
|
||||
];
|
||||
|
||||
public static IReadOnlyList<string> GetAllEntities(
|
||||
string boilerPowerEntityId,
|
||||
string boilerSwitchEntityId,
|
||||
@@ -66,4 +72,38 @@ public static class ReplayEntityMap
|
||||
|
||||
return [.. all];
|
||||
}
|
||||
|
||||
public static (IReadOnlyList<string> MinimalEntities, IReadOnlyList<string> FullEntities) GetPartitionedEntities(
|
||||
string boilerPowerEntityId,
|
||||
string boilerSwitchEntityId,
|
||||
string bathroomHumidityEntityId,
|
||||
string mainHomeHumidityEntityId,
|
||||
string mainMeterEntityId,
|
||||
string sunEntityId,
|
||||
string lightEntityId,
|
||||
string[] personEntityIds)
|
||||
{
|
||||
var allEntities = GetAllEntities(
|
||||
boilerPowerEntityId, boilerSwitchEntityId,
|
||||
bathroomHumidityEntityId, mainHomeHumidityEntityId,
|
||||
mainMeterEntityId, sunEntityId, lightEntityId, personEntityIds);
|
||||
|
||||
var fullSet = new HashSet<string>(GetEntitiesRequiringAttributes(), StringComparer.OrdinalIgnoreCase);
|
||||
var minimal = new List<string>();
|
||||
var full = new List<string>();
|
||||
|
||||
foreach (var entity in allEntities)
|
||||
{
|
||||
if (fullSet.Contains(entity))
|
||||
{
|
||||
full.Add(entity);
|
||||
}
|
||||
else
|
||||
{
|
||||
minimal.Add(entity);
|
||||
}
|
||||
}
|
||||
|
||||
return (minimal, full);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ namespace HomeAssistant.HistoryReplay.HistoryData;
|
||||
public sealed class HistoryTimeline
|
||||
{
|
||||
private readonly Dictionary<string, List<HistoryStateEntry>> _entityTimelines = new(StringComparer.OrdinalIgnoreCase);
|
||||
private bool _sorted;
|
||||
|
||||
public void AddEntries(string entityId, IEnumerable<HistoryStateEntry> entries)
|
||||
{
|
||||
@@ -13,7 +14,41 @@ public sealed class HistoryTimeline
|
||||
}
|
||||
|
||||
list.AddRange(entries);
|
||||
list.Sort((a, b) => a.LastChanged.CompareTo(b.LastChanged));
|
||||
_sorted = false;
|
||||
}
|
||||
|
||||
public void AddEntriesBulk(string entityId, List<HistoryStateEntry> entries)
|
||||
{
|
||||
if (entries.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!_entityTimelines.TryGetValue(entityId, out var list))
|
||||
{
|
||||
_entityTimelines[entityId] = entries;
|
||||
}
|
||||
else
|
||||
{
|
||||
list.AddRange(entries);
|
||||
}
|
||||
|
||||
_sorted = false;
|
||||
}
|
||||
|
||||
public void FinalizeSort()
|
||||
{
|
||||
if (_sorted)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var entries in _entityTimelines.Values)
|
||||
{
|
||||
entries.Sort((a, b) => a.LastChanged.CompareTo(b.LastChanged));
|
||||
}
|
||||
|
||||
_sorted = true;
|
||||
}
|
||||
|
||||
public HistoryStateEntry? GetStateAt(string entityId, DateTimeOffset timestamp)
|
||||
@@ -23,20 +58,8 @@ public sealed class HistoryTimeline
|
||||
return null;
|
||||
}
|
||||
|
||||
HistoryStateEntry? best = null;
|
||||
foreach (var entry in entries)
|
||||
{
|
||||
if (entry.LastChanged <= timestamp)
|
||||
{
|
||||
best = entry;
|
||||
}
|
||||
else
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return best;
|
||||
var index = BinarySearchFloor(entries, timestamp);
|
||||
return index >= 0 ? entries[index] : null;
|
||||
}
|
||||
|
||||
public IReadOnlyList<DateTimeOffset> GetAllTimestamps()
|
||||
@@ -62,4 +85,34 @@ public sealed class HistoryTimeline
|
||||
}
|
||||
|
||||
public int TotalEntryCount => _entityTimelines.Values.Sum(e => e.Count);
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
_entityTimelines.Clear();
|
||||
_sorted = false;
|
||||
}
|
||||
|
||||
private static int BinarySearchFloor(List<HistoryStateEntry> entries, DateTimeOffset timestamp)
|
||||
{
|
||||
var lo = 0;
|
||||
var hi = entries.Count - 1;
|
||||
var result = -1;
|
||||
|
||||
while (lo <= hi)
|
||||
{
|
||||
var mid = lo + (hi - lo) / 2;
|
||||
|
||||
if (entries[mid].LastChanged <= timestamp)
|
||||
{
|
||||
result = mid;
|
||||
lo = mid + 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
hi = mid - 1;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,63 +9,230 @@ public sealed class HomeAssistantHistoryProvider(
|
||||
IHomeAssistantApiClient client,
|
||||
ILogger<HomeAssistantHistoryProvider> logger) : IHistoryDataProvider
|
||||
{
|
||||
private const int MaxEntitiesPerRequest = 10;
|
||||
private const int MaxEntitiesPerBatch = 5;
|
||||
private const int MaxConcurrentRequests = 20;
|
||||
private const int MaxRetryAttempts = 3;
|
||||
private static readonly TimeSpan InitialRetryDelay = TimeSpan.FromSeconds(2);
|
||||
|
||||
public async Task<HistoryTimeline> FetchHistoryAsync(
|
||||
public Task<HistoryTimeline> FetchHistoryAsync(
|
||||
IReadOnlyList<string> entityIds,
|
||||
DateTimeOffset startTime,
|
||||
DateTimeOffset endTime,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
return FetchHistoryAsync(
|
||||
minimalEntityIds: entityIds,
|
||||
fullEntityIds: [],
|
||||
startTime, endTime, cancellationToken);
|
||||
}
|
||||
|
||||
public async Task<HistoryTimeline> FetchHistoryAsync(
|
||||
IReadOnlyList<string> minimalEntityIds,
|
||||
IReadOnlyList<string> fullEntityIds,
|
||||
DateTimeOffset startTime,
|
||||
DateTimeOffset endTime,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var timeline = new HistoryTimeline();
|
||||
var batches = ChunkEntities(entityIds, MaxEntitiesPerRequest);
|
||||
var allEntityCount = minimalEntityIds.Count + fullEntityIds.Count;
|
||||
|
||||
var tasks = batches.Select(batch => FetchBatchAsync(batch, startTime, endTime, cancellationToken));
|
||||
var results = await Task.WhenAll(tasks).ConfigureAwait(false);
|
||||
var minimalBatches = ChunkEntities(minimalEntityIds, MaxEntitiesPerBatch);
|
||||
var fullBatches = ChunkEntities(fullEntityIds, MaxEntitiesPerBatch);
|
||||
|
||||
foreach (var batchTimeline in results)
|
||||
logger.LogInformation(
|
||||
"Fetching history in {MinBatchCount}+{FullBatchCount} batch(es) for {MinCount} minimal + {FullCount} full entities",
|
||||
minimalBatches.Count, fullBatches.Count, minimalEntityIds.Count, fullEntityIds.Count);
|
||||
|
||||
var failedEntities = new List<string>();
|
||||
using var semaphore = new SemaphoreSlim(MaxConcurrentRequests);
|
||||
|
||||
var minimalTasks = minimalBatches.Select(batch => FetchBatchThrottledAsync(
|
||||
batch, startTime, endTime, minimalResponse: true, semaphore, cancellationToken));
|
||||
|
||||
var fullTasks = fullBatches.Select(batch => FetchBatchThrottledAsync(
|
||||
batch, startTime, endTime, minimalResponse: false, semaphore, cancellationToken));
|
||||
|
||||
var results = await Task.WhenAll(minimalTasks.Concat(fullTasks)).ConfigureAwait(false);
|
||||
|
||||
foreach (var batchResult in results)
|
||||
{
|
||||
foreach (var entityId in batchTimeline.GetEntityIds())
|
||||
foreach (var (entityId, entries) in batchResult.Entries)
|
||||
{
|
||||
timeline.AddEntries(entityId, batchTimeline.GetEntityHistory(entityId));
|
||||
timeline.AddEntriesBulk(entityId, entries);
|
||||
}
|
||||
|
||||
failedEntities.AddRange(batchResult.FailedEntityIds);
|
||||
}
|
||||
|
||||
if (failedEntities.Count > 0)
|
||||
{
|
||||
logger.LogWarning("Retrying {Count} failed entities individually: {Entities}", failedEntities.Count, string.Join(", ", failedEntities));
|
||||
|
||||
var individualResults = await FetchEntitiesIndividuallyAsync(failedEntities, startTime, endTime, cancellationToken);
|
||||
|
||||
foreach (var (entityId, entries) in individualResults)
|
||||
{
|
||||
timeline.AddEntriesBulk(entityId, entries);
|
||||
}
|
||||
}
|
||||
|
||||
timeline.FinalizeSort();
|
||||
|
||||
logger.LogInformation(
|
||||
"Fetched history for {EntityCount} entities: {EntryCount} total entries ({Start} to {End})",
|
||||
entityIds.Count, timeline.TotalEntryCount, startTime, endTime);
|
||||
allEntityCount, timeline.TotalEntryCount, startTime, endTime);
|
||||
|
||||
return timeline;
|
||||
}
|
||||
|
||||
private async Task<HistoryTimeline> FetchBatchAsync(
|
||||
private async Task<BatchFetchResult> FetchBatchThrottledAsync(
|
||||
IReadOnlyList<string> batch,
|
||||
DateTimeOffset startTime,
|
||||
DateTimeOffset endTime,
|
||||
bool minimalResponse,
|
||||
SemaphoreSlim semaphore,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
await semaphore.WaitAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
return await FetchBatchWithRetryAsync(batch, startTime, endTime, minimalResponse, cancellationToken);
|
||||
}
|
||||
finally
|
||||
{
|
||||
semaphore.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<BatchFetchResult> FetchBatchWithRetryAsync(
|
||||
IReadOnlyList<string> entityIds,
|
||||
DateTimeOffset startTime,
|
||||
DateTimeOffset endTime,
|
||||
bool minimalResponse,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var entityIdsString = string.Join(",", entityIds);
|
||||
|
||||
for (var attempt = 1; attempt <= MaxRetryAttempts; attempt++)
|
||||
{
|
||||
logger.LogDebug("Fetching history batch (attempt {Attempt}/{MaxAttempts}, minimal={Minimal}) for: {Entities}",
|
||||
attempt, MaxRetryAttempts, minimalResponse, entityIdsString);
|
||||
|
||||
try
|
||||
{
|
||||
var response = await client.GetHistoryAsync(
|
||||
entityIdsString, startTime, endTime, minimalResponse, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
var entries = new List<(string, List<HistoryStateEntry>)>();
|
||||
ParseHistoryResponse(response, entries);
|
||||
return new BatchFetchResult(entries, []);
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex) when (IsTransientFailure(ex) && attempt < MaxRetryAttempts)
|
||||
{
|
||||
var delay = InitialRetryDelay * Math.Pow(2, attempt - 1);
|
||||
logger.LogWarning(ex,
|
||||
"Transient failure fetching batch (attempt {Attempt}/{MaxAttempts}), retrying in {Delay}s: {Entities}",
|
||||
attempt, MaxRetryAttempts, delay.TotalSeconds, entityIdsString);
|
||||
await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex,
|
||||
"Failed to fetch history batch after {Attempt} attempt(s): {Entities}",
|
||||
attempt, entityIdsString);
|
||||
return new BatchFetchResult([], entityIds.ToList());
|
||||
}
|
||||
}
|
||||
|
||||
return new BatchFetchResult([], entityIds.ToList());
|
||||
}
|
||||
|
||||
private async Task<List<(string EntityId, List<HistoryStateEntry> Entries)>> FetchEntitiesIndividuallyAsync(
|
||||
IReadOnlyList<string> entityIds,
|
||||
DateTimeOffset startTime,
|
||||
DateTimeOffset endTime,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var timeline = new HistoryTimeline();
|
||||
var entityIdsString = string.Join(",", entityIds);
|
||||
var allEntries = new List<(string, List<HistoryStateEntry>)>();
|
||||
using var semaphore = new SemaphoreSlim(MaxConcurrentRequests);
|
||||
|
||||
logger.LogDebug("Fetching history batch for: {Entities}", entityIdsString);
|
||||
|
||||
try
|
||||
var tasks = entityIds.Select(async entityId =>
|
||||
{
|
||||
var result = await client.GetHistoryAsync(
|
||||
entityIdsString, startTime, endTime, minimalResponse: false, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
await semaphore.WaitAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
return await FetchSingleEntityWithRetryAsync(entityId, startTime, endTime, cancellationToken);
|
||||
}
|
||||
finally
|
||||
{
|
||||
semaphore.Release();
|
||||
}
|
||||
});
|
||||
|
||||
ParseHistoryResponse(result, timeline);
|
||||
}
|
||||
catch (Exception ex)
|
||||
var results = await Task.WhenAll(tasks).ConfigureAwait(false);
|
||||
|
||||
foreach (var result in results)
|
||||
{
|
||||
logger.LogError(ex, "Failed to fetch history for entities: {Entities}", entityIdsString);
|
||||
allEntries.AddRange(result);
|
||||
}
|
||||
|
||||
return timeline;
|
||||
return allEntries;
|
||||
}
|
||||
|
||||
private void ParseHistoryResponse(JsonElement response, HistoryTimeline timeline)
|
||||
private async Task<List<(string EntityId, List<HistoryStateEntry> Entries)>> FetchSingleEntityWithRetryAsync(
|
||||
string entityId,
|
||||
DateTimeOffset startTime,
|
||||
DateTimeOffset endTime,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
for (var attempt = 1; attempt <= MaxRetryAttempts; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
var response = await client.GetHistoryAsync(
|
||||
entityId, startTime, endTime, minimalResponse: false, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
var entries = new List<(string, List<HistoryStateEntry>)>();
|
||||
ParseHistoryResponse(response, entries);
|
||||
return entries;
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex) when (IsTransientFailure(ex) && attempt < MaxRetryAttempts)
|
||||
{
|
||||
var delay = InitialRetryDelay * Math.Pow(2, attempt - 1);
|
||||
logger.LogWarning(ex,
|
||||
"Transient failure fetching {EntityId} (attempt {Attempt}/{MaxAttempts}), retrying in {Delay}s",
|
||||
entityId, attempt, MaxRetryAttempts, delay.TotalSeconds);
|
||||
await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex,
|
||||
"Failed to fetch history for entity {EntityId} after {Attempt} attempt(s)",
|
||||
entityId, attempt);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
private static bool IsTransientFailure(Exception ex) =>
|
||||
ex is HttpRequestException or TaskCanceledException or TimeoutException
|
||||
or IOException;
|
||||
|
||||
private static void ParseHistoryResponse(
|
||||
JsonElement response,
|
||||
List<(string EntityId, List<HistoryStateEntry> Entries)> result)
|
||||
{
|
||||
if (response.ValueKind != JsonValueKind.Array)
|
||||
{
|
||||
@@ -79,25 +246,37 @@ public sealed class HomeAssistantHistoryProvider(
|
||||
continue;
|
||||
}
|
||||
|
||||
string? currentEntityId = null;
|
||||
var entries = new List<HistoryStateEntry>();
|
||||
|
||||
foreach (var stateObj in entityArray.EnumerateArray())
|
||||
{
|
||||
var entry = ParseStateEntry(stateObj);
|
||||
if (entry is not null)
|
||||
var entry = ParseStateEntry(stateObj, currentEntityId);
|
||||
if (entry is null)
|
||||
{
|
||||
timeline.AddEntries(entry.EntityId, [entry]);
|
||||
continue;
|
||||
}
|
||||
|
||||
currentEntityId ??= entry.EntityId;
|
||||
entries.Add(entry);
|
||||
}
|
||||
|
||||
if (currentEntityId is not null && entries.Count > 0)
|
||||
{
|
||||
result.Add((currentEntityId, entries));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private HistoryStateEntry? ParseStateEntry(JsonElement stateObj)
|
||||
private static HistoryStateEntry? ParseStateEntry(JsonElement stateObj, string? fallbackEntityId)
|
||||
{
|
||||
if (!stateObj.TryGetProperty("entity_id", out var entityIdProp))
|
||||
string? entityId = null;
|
||||
if (stateObj.TryGetProperty("entity_id", out var entityIdProp))
|
||||
{
|
||||
return null;
|
||||
entityId = entityIdProp.GetString();
|
||||
}
|
||||
|
||||
var entityId = entityIdProp.GetString();
|
||||
entityId ??= fallbackEntityId;
|
||||
if (string.IsNullOrEmpty(entityId))
|
||||
{
|
||||
return null;
|
||||
@@ -105,16 +284,13 @@ public sealed class HomeAssistantHistoryProvider(
|
||||
|
||||
var state = stateObj.TryGetProperty("state", out var stateProp) ? stateProp.GetString() : null;
|
||||
|
||||
DateTimeOffset lastChanged;
|
||||
if (stateObj.TryGetProperty("last_changed", out var lastChangedProp))
|
||||
if (!stateObj.TryGetProperty("last_changed", out var lastChangedProp))
|
||||
{
|
||||
if (!DateTimeOffset.TryParse(lastChangedProp.GetString(), CultureInfo.InvariantCulture,
|
||||
DateTimeStyles.RoundtripKind, out lastChanged))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
else
|
||||
|
||||
if (!DateTimeOffset.TryParse(lastChangedProp.GetString(), CultureInfo.InvariantCulture,
|
||||
DateTimeStyles.RoundtripKind, out var lastChanged))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
@@ -159,10 +335,13 @@ public sealed class HomeAssistantHistoryProvider(
|
||||
|
||||
for (var i = 0; i < entities.Count; i += chunkSize)
|
||||
{
|
||||
var chunk = entities.Skip(i).Take(chunkSize).ToList();
|
||||
chunks.Add(chunk);
|
||||
chunks.Add(entities.Skip(i).Take(chunkSize).ToList());
|
||||
}
|
||||
|
||||
return chunks;
|
||||
}
|
||||
|
||||
private sealed record BatchFetchResult(
|
||||
List<(string EntityId, List<HistoryStateEntry> Entries)> Entries,
|
||||
List<string> FailedEntityIds);
|
||||
}
|
||||
|
||||
@@ -7,4 +7,11 @@ public interface IHistoryDataProvider
|
||||
DateTimeOffset startTime,
|
||||
DateTimeOffset endTime,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
Task<HistoryTimeline> FetchHistoryAsync(
|
||||
IReadOnlyList<string> minimalEntityIds,
|
||||
IReadOnlyList<string> fullEntityIds,
|
||||
DateTimeOffset startTime,
|
||||
DateTimeOffset endTime,
|
||||
CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<LangVersion>14.0</LangVersion>
|
||||
<Nullable>enable</Nullable>
|
||||
@@ -10,22 +9,10 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Update="appsettings.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="appsettings.development.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
<CopyToPublishDirectory>Never</CopyToPublishDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting" Version="10.0.5" />
|
||||
<PackageReference Include="Microsoft.Extensions.Http" Version="10.0.5" />
|
||||
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.5" />
|
||||
<PackageReference Include="Blazor-ApexCharts" Version="4.0.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.App.Internal.Assets" Version="10.0.5" />
|
||||
<PackageReference Include="NetDaemon.HassModel" Version="26.11.0" />
|
||||
<PackageReference Include="Serilog.Extensions.Hosting" Version="10.0.0" />
|
||||
<PackageReference Include="Serilog.Sinks.Console" Version="6.1.1" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -12,10 +12,8 @@ public sealed class HomeAssistantApiClient : IHomeAssistantApiClient
|
||||
{
|
||||
_httpClient = httpClient;
|
||||
_httpClient.BaseAddress = settings.Value.BaseUrl;
|
||||
_httpClient.DefaultRequestHeaders.Authorization =
|
||||
new AuthenticationHeaderValue("Bearer", settings.Value.Token);
|
||||
_httpClient.DefaultRequestHeaders.Accept.Add(
|
||||
new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", settings.Value.Token);
|
||||
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
_httpClient.Timeout = TimeSpan.FromSeconds(HomeAssistantSettings.DefaultTimeoutSeconds);
|
||||
}
|
||||
|
||||
@@ -30,10 +28,14 @@ public sealed class HomeAssistantApiClient : IHomeAssistantApiClient
|
||||
var path = $"/api/history/period/{start:O}?filter_entity_id={Uri.EscapeDataString(entityIds)}";
|
||||
|
||||
if (endTime.HasValue)
|
||||
{
|
||||
path += $"&end_time={Uri.EscapeDataString(endTime.Value.ToString("O"))}";
|
||||
}
|
||||
|
||||
if (minimalResponse)
|
||||
{
|
||||
path += "&minimal_response";
|
||||
}
|
||||
|
||||
return await GetJsonAsync(path, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
@@ -45,6 +47,7 @@ public sealed class HomeAssistantApiClient : IHomeAssistantApiClient
|
||||
|
||||
await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
|
||||
var doc = await JsonDocument.ParseAsync(stream, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return doc.RootElement.Clone();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ public sealed class HomeAssistantSettings
|
||||
{
|
||||
public const string SectionName = "HomeAssistant";
|
||||
public const int DefaultPort = 8123;
|
||||
public const int DefaultTimeoutSeconds = 30;
|
||||
public const int DefaultTimeoutSeconds = 3600;
|
||||
|
||||
public string Host { get; set; } = string.Empty;
|
||||
public int Port { get; set; } = DefaultPort;
|
||||
|
||||
@@ -2,21 +2,14 @@ using BoilerMonitorManager;
|
||||
using BoilerMonitorManager.Interface;
|
||||
using BoilerMonitorManager.Models;
|
||||
using HomeAssistant.Entities.Interfaces;
|
||||
using HomeAssistant.HistoryReplay.Configuration;
|
||||
using HomeAssistant.HistoryReplay.Components;
|
||||
using HomeAssistant.HistoryReplay.HistoryData;
|
||||
using HomeAssistant.HistoryReplay.Replay;
|
||||
using HomeAssistant.HistoryReplay.Reporting;
|
||||
using HomeAssistant.HistoryReplay.Runners;
|
||||
using HomeAssistant.HistoryReplay.HomeAssistantClient;
|
||||
using HomeAssistant.HistoryReplay.Replay;
|
||||
using HomeAssistant.HistoryReplay.Services;
|
||||
using LightMonitorManager.Models;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NordPoolManager;
|
||||
using NordPoolManager.Interface;
|
||||
using PowerMonitorManager;
|
||||
using PowerMonitorManager.Interface;
|
||||
using PowerMonitorManager.Models;
|
||||
using Serilog;
|
||||
using ShowerMonitorManager;
|
||||
@@ -25,167 +18,60 @@ using ShowerMonitorManager.Models;
|
||||
|
||||
Log.Logger = new LoggerConfiguration()
|
||||
.MinimumLevel.Information()
|
||||
.WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
|
||||
.WriteTo.Console()
|
||||
.CreateLogger();
|
||||
|
||||
try
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
builder.WebHost.UseStaticWebAssets();
|
||||
|
||||
builder.Services.AddLogging(logging =>
|
||||
{
|
||||
Log.Information("Starting Home Assistant History Replay");
|
||||
logging.ClearProviders();
|
||||
logging.AddSerilog(dispose: true);
|
||||
});
|
||||
|
||||
var configuration = new ConfigurationBuilder()
|
||||
.SetBasePath(Directory.GetCurrentDirectory())
|
||||
.AddJsonFile("appsettings.json", optional: false)
|
||||
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") ?? "Production"}.json", optional: true)
|
||||
.AddEnvironmentVariables()
|
||||
.Build();
|
||||
builder.Services.AddRazorComponents()
|
||||
.AddInteractiveServerComponents();
|
||||
|
||||
var services = new ServiceCollection();
|
||||
builder.Services.Configure<HomeAssistantSettings>(
|
||||
builder.Configuration.GetSection(HomeAssistantSettings.SectionName));
|
||||
builder.Services.Configure<BoilerMonitorOptions>(
|
||||
builder.Configuration.GetSection(BoilerMonitorOptions.SectionName));
|
||||
builder.Services.Configure<ShowerMonitorOptions>(
|
||||
builder.Configuration.GetSection(ShowerMonitorOptions.SectionName));
|
||||
builder.Services.Configure<PowerMonitorOptions>(
|
||||
builder.Configuration.GetSection(PowerMonitorOptions.SectionName));
|
||||
builder.Services.Configure<LightMonitorOptions>(
|
||||
builder.Configuration.GetSection(LightMonitorOptions.SectionName));
|
||||
|
||||
services.AddLogging(builder =>
|
||||
{
|
||||
builder.ClearProviders();
|
||||
builder.AddSerilog(dispose: true);
|
||||
});
|
||||
builder.Services.AddHttpClient<IHomeAssistantApiClient, HomeAssistantApiClient>();
|
||||
builder.Services.AddSingleton<IHistoryDataProvider, HomeAssistantHistoryProvider>();
|
||||
|
||||
services.Configure<HomeAssistantSettings>(configuration.GetSection(HomeAssistantSettings.SectionName));
|
||||
services.Configure<ReplayOptions>(configuration.GetSection(ReplayOptions.SectionName));
|
||||
services.Configure<BoilerMonitorOptions>(configuration.GetSection(BoilerMonitorOptions.SectionName));
|
||||
services.Configure<ShowerMonitorOptions>(configuration.GetSection(ShowerMonitorOptions.SectionName));
|
||||
services.Configure<PowerMonitorOptions>(configuration.GetSection(PowerMonitorOptions.SectionName));
|
||||
services.Configure<LightMonitorOptions>(configuration.GetSection(LightMonitorOptions.SectionName));
|
||||
builder.Services.AddSingleton<IEntityManager, NoOpEntityManager>();
|
||||
builder.Services.AddSingleton<ICheapestIntervalsFinder, CheapestIntervalsFinder>();
|
||||
builder.Services.AddSingleton<IBoilerControlService, BoilerControlService>();
|
||||
|
||||
services.AddHttpClient<IHomeAssistantApiClient, HomeAssistantApiClient>();
|
||||
services.AddSingleton<IHistoryDataProvider, HomeAssistantHistoryProvider>();
|
||||
var showerOpts = builder.Configuration
|
||||
.GetSection(ShowerMonitorOptions.SectionName)
|
||||
.Get<ShowerMonitorOptions>() ?? new ShowerMonitorOptions();
|
||||
builder.Services.AddSingleton<IHumidityRateCalculator>(_ => new HumidityRateCalculator(showerOpts.RateWindowSize));
|
||||
|
||||
var replayOptions = configuration.GetSection(ReplayOptions.SectionName).Get<ReplayOptions>() ?? new ReplayOptions();
|
||||
builder.Services.AddSingleton<ReplayOrchestrationService>();
|
||||
|
||||
var replayTimeline = new ReplayTimeline();
|
||||
var replayTimeProvider = new ReplayTimeProvider(replayOptions.StartTime);
|
||||
var app = builder.Build();
|
||||
|
||||
services.AddSingleton(replayTimeline);
|
||||
services.AddSingleton(replayTimeProvider);
|
||||
services.AddSingleton<TimeProvider>(replayTimeProvider);
|
||||
|
||||
services.AddSingleton<IEntityManager, NoOpEntityManager>();
|
||||
|
||||
services.AddSingleton<ICheapestIntervalsFinder, CheapestIntervalsFinder>();
|
||||
services.AddSingleton<IBoilerControlService, BoilerControlService>();
|
||||
services.AddSingleton<IBoilerRunTimeTracker, BoilerRunTimeTracker>();
|
||||
services.AddSingleton<IWaterReadyService, WaterReadyService>();
|
||||
services.AddSingleton<IOtherPowerCalculationService, OtherPowerCalculationService>();
|
||||
services.AddSingleton<IPowerCostCalculationService, PowerCostCalculationService>();
|
||||
|
||||
var showerOptions = configuration.GetSection(ShowerMonitorOptions.SectionName).Get<ShowerMonitorOptions>() ?? new ShowerMonitorOptions();
|
||||
services.AddSingleton<IHumidityRateCalculator>(_ => new HumidityRateCalculator(showerOptions.RateWindowSize));
|
||||
services.AddSingleton<IShowerDetectionService, ShowerDetectionService>();
|
||||
|
||||
services.AddSingleton<ConsoleReportRenderer>();
|
||||
|
||||
var provider = services.BuildServiceProvider();
|
||||
|
||||
var historyProvider = provider.GetRequiredService<IHistoryDataProvider>();
|
||||
var logger = provider.GetRequiredService<ILogger<Program>>();
|
||||
|
||||
var boilerOpts = provider.GetRequiredService<IOptions<BoilerMonitorOptions>>().Value;
|
||||
var showerOpts = provider.GetRequiredService<IOptions<ShowerMonitorOptions>>().Value;
|
||||
var powerOpts = provider.GetRequiredService<IOptions<PowerMonitorOptions>>().Value;
|
||||
var lightOpts = provider.GetRequiredService<IOptions<LightMonitorOptions>>().Value;
|
||||
|
||||
logger.LogInformation("Replay period: {Start} to {End}", replayOptions.StartTime, replayOptions.EndTime);
|
||||
|
||||
var allEntityIds = ReplayEntityMap.GetAllEntities(
|
||||
boilerPowerEntityId: "sensor.boiler_power",
|
||||
boilerSwitchEntityId: "switch.boiler",
|
||||
bathroomHumidityEntityId: showerOpts.BathroomHumidityEntityId,
|
||||
mainHomeHumidityEntityId: showerOpts.MainHomeHumidityEntityId,
|
||||
mainMeterEntityId: powerOpts.MainMeterEntityId,
|
||||
sunEntityId: lightOpts.SunEntityId,
|
||||
lightEntityId: lightOpts.LightEntityId,
|
||||
personEntityIds: lightOpts.PersonEntityIds);
|
||||
|
||||
logger.LogInformation("Fetching history for {Count} entities...", allEntityIds.Count);
|
||||
|
||||
var timeline = await historyProvider.FetchHistoryAsync(
|
||||
allEntityIds, replayOptions.StartTime, replayOptions.EndTime);
|
||||
|
||||
var replayHaContext = new ReplayHaContext(
|
||||
timeline,
|
||||
replayTimeProvider,
|
||||
replayTimeline,
|
||||
provider.GetRequiredService<ILogger<ReplayHaContext>>());
|
||||
|
||||
var fanControlService = new ExhaustFanControlService(
|
||||
replayHaContext,
|
||||
provider.GetRequiredService<ILogger<ExhaustFanControlService>>(),
|
||||
provider.GetRequiredService<IOptions<ShowerMonitorOptions>>());
|
||||
|
||||
var runners = new List<IMonitorReplayRunner>();
|
||||
|
||||
if (replayOptions.Monitors.NordPool)
|
||||
{
|
||||
runners.Add(new NordPoolReplayRunner(
|
||||
timeline, replayTimeProvider, replayTimeline,
|
||||
provider.GetRequiredService<ICheapestIntervalsFinder>(),
|
||||
provider.GetRequiredService<ILogger<NordPoolReplayRunner>>(),
|
||||
provider.GetRequiredService<IOptions<ReplayOptions>>()));
|
||||
}
|
||||
|
||||
if (replayOptions.Monitors.Boiler)
|
||||
{
|
||||
runners.Add(new BoilerReplayRunner(
|
||||
timeline, replayTimeProvider, replayTimeline,
|
||||
provider.GetRequiredService<IBoilerControlService>(),
|
||||
provider.GetRequiredService<IBoilerRunTimeTracker>(),
|
||||
provider.GetRequiredService<IWaterReadyService>(),
|
||||
provider.GetRequiredService<ILogger<BoilerReplayRunner>>(),
|
||||
provider.GetRequiredService<IOptions<ReplayOptions>>(),
|
||||
provider.GetRequiredService<IOptions<BoilerMonitorOptions>>()));
|
||||
}
|
||||
|
||||
if (replayOptions.Monitors.Shower)
|
||||
{
|
||||
runners.Add(new ShowerReplayRunner(
|
||||
timeline, replayTimeProvider, replayTimeline,
|
||||
provider.GetRequiredService<IShowerDetectionService>(),
|
||||
fanControlService,
|
||||
provider.GetRequiredService<ILogger<ShowerReplayRunner>>(),
|
||||
provider.GetRequiredService<IOptions<ReplayOptions>>(),
|
||||
provider.GetRequiredService<IOptions<ShowerMonitorOptions>>()));
|
||||
}
|
||||
|
||||
if (replayOptions.Monitors.Power)
|
||||
{
|
||||
runners.Add(new PowerReplayRunner(
|
||||
timeline, replayTimeProvider, replayTimeline,
|
||||
provider.GetRequiredService<IOtherPowerCalculationService>(),
|
||||
provider.GetRequiredService<IPowerCostCalculationService>(),
|
||||
provider.GetRequiredService<ILogger<PowerReplayRunner>>(),
|
||||
provider.GetRequiredService<IOptions<ReplayOptions>>(),
|
||||
provider.GetRequiredService<IOptions<PowerMonitorOptions>>()));
|
||||
}
|
||||
|
||||
if (replayOptions.Monitors.Light)
|
||||
{
|
||||
runners.Add(new LightReplayRunner(
|
||||
timeline, replayTimeProvider, replayTimeline,
|
||||
provider.GetRequiredService<ILogger<LightReplayRunner>>(),
|
||||
provider.GetRequiredService<IOptions<ReplayOptions>>(),
|
||||
provider.GetRequiredService<IOptions<LightMonitorOptions>>()));
|
||||
}
|
||||
|
||||
logger.LogInformation("Running {Count} monitor replay(s) in parallel...", runners.Count);
|
||||
|
||||
var replayTasks = runners.Select(r => Task.Run(() => r.RunAsync()));
|
||||
await Task.WhenAll(replayTasks);
|
||||
|
||||
var renderer = provider.GetRequiredService<ConsoleReportRenderer>();
|
||||
renderer.Render(replayTimeline, replayOptions);
|
||||
}
|
||||
catch (Exception ex)
|
||||
if (!app.Environment.IsDevelopment())
|
||||
{
|
||||
Log.Fatal(ex, "History replay failed");
|
||||
}
|
||||
finally
|
||||
{
|
||||
await Log.CloseAndFlushAsync();
|
||||
app.UseHsts();
|
||||
}
|
||||
|
||||
app.MapStaticAssets();
|
||||
app.UseAntiforgery();
|
||||
|
||||
app.MapRazorComponents<App>()
|
||||
.AddInteractiveServerRenderMode();
|
||||
|
||||
Log.Information("History Replay Dashboard running at {Urls}", string.Join(", ", app.Urls));
|
||||
|
||||
app.Run();
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"profiles": {
|
||||
"HomeAssistant.HistoryReplay": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": false,
|
||||
"applicationUrl": "http://localhost:5000",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
# HomeAssistant.HistoryReplay
|
||||
|
||||
A debugging tool that fetches real historical data from your Home Assistant instance and replays it through the monitor business logic to verify decisions without side effects.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- .NET 10 SDK
|
||||
- A running Home Assistant instance with the History API enabled
|
||||
- A [long-lived access token](https://www.home-assistant.io/docs/authentication/#your-account-profile) from Home Assistant
|
||||
|
||||
## Quick Start
|
||||
|
||||
### 1. Configure the connection
|
||||
|
||||
Edit `appsettings.json` (or create `appsettings.development.json` for local overrides):
|
||||
|
||||
```json
|
||||
{
|
||||
"HomeAssistant": {
|
||||
"Host": "homeassistant.local",
|
||||
"Port": 8123,
|
||||
"Token": "<your-long-lived-access-token>",
|
||||
"Ssl": false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> **Security note:** Never commit your access token. Use `appsettings.development.json` (already in `.gitignore`) or environment variables instead.
|
||||
|
||||
### 2. Set the replay time range
|
||||
|
||||
```json
|
||||
{
|
||||
"Replay": {
|
||||
"StartTime": "2026-03-30T00:00:00+02:00",
|
||||
"EndTime": "2026-03-31T00:00:00+02:00"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Times are in ISO 8601 format with timezone offset. The tool fetches all entity history within this window from the HA REST API (`/api/history/period`).
|
||||
|
||||
### 3. Enable or disable monitors
|
||||
|
||||
```json
|
||||
{
|
||||
"Replay": {
|
||||
"Monitors": {
|
||||
"NordPool": true,
|
||||
"Boiler": true,
|
||||
"Shower": true,
|
||||
"Power": false,
|
||||
"Light": true
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Set any monitor to `false` to skip it during replay.
|
||||
|
||||
### 4. Run
|
||||
|
||||
```bash
|
||||
dotnet run --project HomeAssistant.HistoryReplay
|
||||
```
|
||||
|
||||
Or from the project directory:
|
||||
|
||||
```bash
|
||||
cd HomeAssistant.HistoryReplay
|
||||
dotnet run
|
||||
```
|
||||
|
||||
## What It Does
|
||||
|
||||
The tool replays historical entity states through the **real business logic services** from each monitor project:
|
||||
|
||||
| Monitor | Services Used | What It Shows |
|
||||
|---------|--------------|---------------|
|
||||
| **NordPool** | `CheapestIntervalsFinder` | Price changes, cheap interval identification |
|
||||
| **Boiler** | `BoilerControlService`, `WaterReadyService`, `BoilerRunTimeTracker` | Turn on/off decisions, water-ready detection, runtime tracking, budget usage |
|
||||
| **Shower** | `ShowerDetectionService`, `ExhaustFanControlService`, `HumidityRateCalculator` | Shower state transitions (Idle/Suspected/Active/Declining/Completed), fan control |
|
||||
| **Power** | `OtherPowerCalculationService`, `PowerCostCalculationService` | Power breakdown, cost accumulation, anomaly detection |
|
||||
| **Light** | Event-driven replay of sun/person state changes | Light-on decisions based on sunset and person arrivals |
|
||||
|
||||
### No side effects
|
||||
|
||||
- **No MQTT entities** are created or updated
|
||||
- **No HA service calls** are executed (they are logged as "would call" events)
|
||||
- **No NetDaemon runtime** is required
|
||||
- The tool only reads from the HA History API
|
||||
|
||||
## Console Output
|
||||
|
||||
The tool produces a colored timeline report:
|
||||
|
||||
```
|
||||
═══════════════════════════════════════════════════════════
|
||||
REPLAY: 2026-03-30 00:00 -> 2026-03-31 00:00
|
||||
═══════════════════════════════════════════════════════════
|
||||
|
||||
-- NordPool ──────────────────────────────────────────────
|
||||
00:00 Price: 3.21 ct/kWh
|
||||
00:15 Price: 3.18 ct/kWh
|
||||
00:15 -> CHEAP interval active (rank #2, price: 3.18 ct/kWh)
|
||||
|
||||
-- Boiler ────────────────────────────────────────────────
|
||||
00:15 -> TURN ON (cheap: True, water ready: False, budget: 0%)
|
||||
01:30 Water ready detected (power: 3.2W, threshold: 5.0W)
|
||||
01:30 -> TURN OFF (cheap: True, water ready: True, budget: 42%)
|
||||
23:59 Final: 01:15:00 total runtime, 2 session(s)
|
||||
|
||||
-- Shower ────────────────────────────────────────────────
|
||||
07:12 State: Idle -> Suspected (bathroom: 62.1%, home: 53.0%, diff: 9.1%)
|
||||
07:14 State: Suspected -> Active (bathroom: 65.3%, home: 53.0%, diff: 12.3%)
|
||||
07:35 State: Declining -> Completed (bathroom: 58.2%, home: 54.1%, diff: 4.1%)
|
||||
|
||||
-- Service Calls ─────────────────────────────────────────
|
||||
00:15 -> Would call switch.turn_on on switch.boiler
|
||||
01:30 -> Would call switch.turn_off on switch.boiler
|
||||
|
||||
═══════════════════════════════════════════════════════════
|
||||
REPLAY SUMMARY
|
||||
═══════════════════════════════════════════════════════════
|
||||
Total events: 24
|
||||
Decisions: 5
|
||||
Service calls: 4
|
||||
Warnings: 0
|
||||
Anomalies: 0
|
||||
```
|
||||
|
||||
## Configuration Reference
|
||||
|
||||
### Monitor-specific settings
|
||||
|
||||
The monitor sections (`BoilerMonitor`, `ShowerMonitor`, `PowerMonitor`, `LightMonitor`) use the **same options classes** as the production `HomeAssistant.Server` project. This means thresholds, entity IDs, and poll intervals match what runs in production.
|
||||
|
||||
#### ShowerMonitor
|
||||
|
||||
| Setting | Default | Description |
|
||||
|---------|---------|-------------|
|
||||
| `BathroomHumidityEntityId` | `sensor.bathroom_humidity` | Bathroom humidity sensor |
|
||||
| `MainHomeHumidityEntityId` | `sensor.main_home_humidity` | Reference home humidity sensor |
|
||||
| `PollIntervalSeconds` | `30` | Replay step interval |
|
||||
| `SpikeRateThreshold` | `4.0` | Humidity rate (%/min) to trigger suspected state |
|
||||
| `MinDifferentialHumidity` | `8.0` | Minimum bathroom-vs-home humidity difference |
|
||||
| `PeakHumidityThreshold` | `58.0` | Humidity to confirm active shower |
|
||||
|
||||
#### PowerMonitor
|
||||
|
||||
| Setting | Default | Description |
|
||||
|---------|---------|-------------|
|
||||
| `MainMeterEntityId` | *(required)* | Main power meter entity |
|
||||
| `PollIntervalSeconds` | `1` | Replay step interval |
|
||||
| `AnomalyThresholdWatts` | `500` | "Other" power threshold for anomaly detection |
|
||||
| `SmoothingWindowSize` | `10` | EMA window for smoothing |
|
||||
|
||||
#### LightMonitor
|
||||
|
||||
| Setting | Default | Description |
|
||||
|---------|---------|-------------|
|
||||
| `LightEntityId` | `light.sonoff_1002214d40` | The light entity to control |
|
||||
| `SunEntityId` | `sun.sun` | Sun entity for below-horizon detection |
|
||||
| `PersonEntityIds` | `[...]` | Person entities for presence detection |
|
||||
|
||||
### Environment-based configuration
|
||||
|
||||
You can override any setting via environment variables using the `__` separator:
|
||||
|
||||
```bash
|
||||
set Replay__StartTime=2026-03-29T00:00:00+02:00
|
||||
set HomeAssistant__Token=your_token_here
|
||||
dotnet run --project HomeAssistant.HistoryReplay
|
||||
```
|
||||
|
||||
## Project Architecture
|
||||
|
||||
```
|
||||
HomeAssistant.HistoryReplay/
|
||||
├── Program.cs Entry point, DI wiring, orchestration
|
||||
├── HomeAssistantClient/ Self-contained HA REST API client
|
||||
│ ├── IHomeAssistantApiClient.cs
|
||||
│ ├── HomeAssistantApiClient.cs
|
||||
│ └── HomeAssistantSettings.cs
|
||||
├── Configuration/
|
||||
│ ├── ReplayOptions.cs Time range and monitor flags
|
||||
│ └── ReplayEntityMap.cs Maps monitors to required HA entity IDs
|
||||
├── HistoryData/
|
||||
│ ├── IHistoryDataProvider.cs Abstraction for fetching history
|
||||
│ ├── HomeAssistantHistoryProvider.cs Fetches from /api/history/period
|
||||
│ ├── HistoryTimeline.cs Sorted timeline of entity states
|
||||
│ └── HistoryStateEntry.cs Single entity state snapshot
|
||||
├── Replay/
|
||||
│ ├── ReplayHaContext.cs IHaContext backed by historical data
|
||||
│ ├── ReplayTimeProvider.cs TimeProvider that steps through time
|
||||
│ └── NoOpEntityManager.cs IEntityManager that logs but does nothing
|
||||
├── Runners/
|
||||
│ ├── IMonitorReplayRunner.cs Common runner interface
|
||||
│ ├── NordPoolReplayRunner.cs Price + cheapest interval replay
|
||||
│ ├── BoilerReplayRunner.cs Boiler control decision replay
|
||||
│ ├── ShowerReplayRunner.cs Shower detection state machine replay
|
||||
│ ├── PowerReplayRunner.cs Power calculation + cost replay
|
||||
│ └── LightReplayRunner.cs Sun/person event-driven replay
|
||||
├── Reporting/
|
||||
│ ├── ReplayEvent.cs Single decision/event during replay
|
||||
│ ├── ReplayTimeline.cs Collected events across all monitors
|
||||
│ └── ConsoleReportRenderer.cs Colored console output
|
||||
└── appsettings.json Configuration
|
||||
```
|
||||
|
||||
### Key design: real services, fake infrastructure
|
||||
|
||||
The replay instantiates **actual production business logic** (e.g., `BoilerControlService.DetermineAction()`, `ShowerDetectionService.Evaluate()`) but replaces infrastructure with replay stubs:
|
||||
|
||||
- `ReplayHaContext` implements `IHaContext` by returning historical state at the current replay timestamp
|
||||
- `ReplayTimeProvider` extends `TimeProvider` for time-dependent logic (e.g., `WaterReadyService` cooldown periods)
|
||||
- `NoOpEntityManager` implements `IEntityManager` and logs all calls without side effects
|
||||
- Service calls via `IHaContext.CallService()` are captured as replay events
|
||||
|
||||
All five monitors run their replays **in parallel** via `Task.WhenAll`.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### "History replay failed" with HTTP errors
|
||||
|
||||
- Verify your HA host, port, and token in `appsettings.json`
|
||||
- Ensure the HA History API is enabled (it is by default)
|
||||
- Check that the token has sufficient permissions
|
||||
|
||||
### No events in the output for a monitor
|
||||
|
||||
- The entity IDs in the monitor config must match your actual HA entities
|
||||
- Check that history data exists for the configured time range (HA purges old history based on the recorder settings)
|
||||
- Verify the monitor is enabled in `Replay.Monitors`
|
||||
|
||||
### Shower monitor shows no sessions
|
||||
|
||||
- Confirm `BathroomHumidityEntityId` and `MainHomeHumidityEntityId` have data in the replay period
|
||||
- Adjust `SpikeRateThreshold` and `MinDifferentialHumidity` if your bathroom has different humidity characteristics
|
||||
|
||||
### Boiler shows "not configured"
|
||||
|
||||
- The boiler replay reads config entity states (`text.boilermonitor_config_power_entity_id`, `text.boilermonitor_config_switch_entity_id`) from history. These must have been set in HA during the replay period.
|
||||
@@ -105,9 +105,20 @@ public sealed class ConsoleReportRenderer
|
||||
var stateChanges = events.Count(e => e.EventType == ReplayEventType.StateChange);
|
||||
|
||||
var parts = new List<string>();
|
||||
if (decisions > 0) parts.Add($"{decisions} decision(s)");
|
||||
if (stateChanges > 0) parts.Add($"{stateChanges} state change(s)");
|
||||
if (warnings > 0) parts.Add($"{warnings} warning(s)");
|
||||
if (decisions > 0)
|
||||
{
|
||||
parts.Add($"{decisions} decision(s)");
|
||||
}
|
||||
|
||||
if (stateChanges > 0)
|
||||
{
|
||||
parts.Add($"{stateChanges} state change(s)");
|
||||
}
|
||||
|
||||
if (warnings > 0)
|
||||
{
|
||||
parts.Add($"{warnings} warning(s)");
|
||||
}
|
||||
|
||||
if (parts.Count > 0)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace HomeAssistant.HistoryReplay.Reporting;
|
||||
|
||||
public sealed class ReplayDataPoint
|
||||
{
|
||||
public required DateTimeOffset Timestamp { get; init; }
|
||||
public required string Monitor { get; init; }
|
||||
public required string Series { get; init; }
|
||||
public required double Value { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
using System.Collections.Concurrent;
|
||||
|
||||
namespace HomeAssistant.HistoryReplay.Reporting;
|
||||
|
||||
public sealed class ReplayDataSeries
|
||||
{
|
||||
private readonly ConcurrentBag<ReplayDataPoint> _points = [];
|
||||
|
||||
public void AddPoint(ReplayDataPoint point)
|
||||
{
|
||||
_points.Add(point);
|
||||
}
|
||||
|
||||
public void AddPoint(string monitor, string series, DateTimeOffset timestamp, double value)
|
||||
{
|
||||
_points.Add(new ReplayDataPoint
|
||||
{
|
||||
Monitor = monitor,
|
||||
Series = series,
|
||||
Timestamp = timestamp,
|
||||
Value = value
|
||||
});
|
||||
}
|
||||
|
||||
public IReadOnlyList<ReplayDataPoint> GetSeries(string monitor, string series) =>
|
||||
_points
|
||||
.Where(p => string.Equals(p.Monitor, monitor, StringComparison.OrdinalIgnoreCase)
|
||||
&& string.Equals(p.Series, series, StringComparison.OrdinalIgnoreCase))
|
||||
.OrderBy(p => p.Timestamp)
|
||||
.ToList();
|
||||
|
||||
public IReadOnlyList<ReplayDataPoint> GetAllForMonitor(string monitor) =>
|
||||
_points
|
||||
.Where(p => string.Equals(p.Monitor, monitor, StringComparison.OrdinalIgnoreCase))
|
||||
.OrderBy(p => p.Timestamp)
|
||||
.ToList();
|
||||
|
||||
public IReadOnlyList<string> GetSeriesNames(string monitor) =>
|
||||
_points
|
||||
.Where(p => string.Equals(p.Monitor, monitor, StringComparison.OrdinalIgnoreCase))
|
||||
.Select(p => p.Series)
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.Order()
|
||||
.ToList();
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
_points.Clear();
|
||||
}
|
||||
}
|
||||
@@ -22,4 +22,9 @@ public sealed class ReplayTimeline
|
||||
|
||||
public IReadOnlyList<string> GetMonitors() =>
|
||||
_events.Select(e => e.Monitor).Distinct(StringComparer.OrdinalIgnoreCase).Order().ToList();
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
_events.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,6 @@ using HomeAssistant.HistoryReplay.Replay;
|
||||
using HomeAssistant.HistoryReplay.Reporting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using BoilerMonitorManager.Models;
|
||||
|
||||
namespace HomeAssistant.HistoryReplay.Runners;
|
||||
|
||||
@@ -17,12 +16,14 @@ public sealed class BoilerReplayRunner : IMonitorReplayRunner
|
||||
private readonly HistoryTimeline _timeline;
|
||||
private readonly ReplayTimeProvider _timeProvider;
|
||||
private readonly ReplayTimeline _replayTimeline;
|
||||
private readonly ReplayDataSeries _dataSeries;
|
||||
private readonly IBoilerControlService _boilerControlService;
|
||||
private readonly IBoilerRunTimeTracker _tracker;
|
||||
private readonly IWaterReadyService _waterReadyService;
|
||||
private readonly ILogger<BoilerReplayRunner> _logger;
|
||||
private readonly ReplayOptions _replayOptions;
|
||||
private readonly BoilerMonitorOptions _boilerOptions;
|
||||
private readonly string _boilerPowerEntityId;
|
||||
private readonly string _boilerSwitchEntityId;
|
||||
|
||||
public string MonitorName => "Boiler";
|
||||
|
||||
@@ -30,22 +31,26 @@ public sealed class BoilerReplayRunner : IMonitorReplayRunner
|
||||
HistoryTimeline timeline,
|
||||
ReplayTimeProvider timeProvider,
|
||||
ReplayTimeline replayTimeline,
|
||||
ReplayDataSeries dataSeries,
|
||||
IBoilerControlService boilerControlService,
|
||||
IBoilerRunTimeTracker tracker,
|
||||
IWaterReadyService waterReadyService,
|
||||
ILogger<BoilerReplayRunner> logger,
|
||||
IOptions<ReplayOptions> replayOptions,
|
||||
IOptions<BoilerMonitorOptions> boilerOptions)
|
||||
string boilerPowerEntityId,
|
||||
string boilerSwitchEntityId)
|
||||
{
|
||||
_timeline = timeline;
|
||||
_timeProvider = timeProvider;
|
||||
_replayTimeline = replayTimeline;
|
||||
_dataSeries = dataSeries;
|
||||
_boilerControlService = boilerControlService;
|
||||
_tracker = tracker;
|
||||
_waterReadyService = waterReadyService;
|
||||
_logger = logger;
|
||||
_replayOptions = replayOptions.Value;
|
||||
_boilerOptions = boilerOptions.Value;
|
||||
_boilerPowerEntityId = boilerPowerEntityId;
|
||||
_boilerSwitchEntityId = boilerSwitchEntityId;
|
||||
}
|
||||
|
||||
public Task RunAsync(CancellationToken cancellationToken = default)
|
||||
@@ -58,30 +63,8 @@ public sealed class BoilerReplayRunner : IMonitorReplayRunner
|
||||
BoilerAction? lastAction = null;
|
||||
var lastWaterReady = false;
|
||||
|
||||
var boilerPowerEntityId = ReadConfigEntityState(
|
||||
BoilerMonitorConsts.ConfigPowerEntityId, _replayOptions.StartTime);
|
||||
var boilerSwitchEntityId = ReadConfigEntityState(
|
||||
BoilerMonitorConsts.ConfigSwitchEntityId, _replayOptions.StartTime);
|
||||
|
||||
if (string.IsNullOrEmpty(boilerPowerEntityId) || string.IsNullOrEmpty(boilerSwitchEntityId))
|
||||
{
|
||||
_replayTimeline.AddEvent(new ReplayEvent
|
||||
{
|
||||
Timestamp = currentTime,
|
||||
Monitor = MonitorName,
|
||||
EventType = ReplayEventType.Warning,
|
||||
Message = "Boiler not configured (missing power/switch entity IDs), skipping replay"
|
||||
});
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
var configThresholdState = ReadConfigEntityState(
|
||||
BoilerMonitorConsts.ConfigHeatingThresholdEntityId, _replayOptions.StartTime);
|
||||
if (!string.IsNullOrEmpty(configThresholdState) &&
|
||||
double.TryParse(configThresholdState, CultureInfo.InvariantCulture, out var configuredThreshold))
|
||||
{
|
||||
heatingThreshold = configuredThreshold;
|
||||
}
|
||||
var boilerPowerEntityId = _boilerPowerEntityId;
|
||||
var boilerSwitchEntityId = _boilerSwitchEntityId;
|
||||
|
||||
while (currentTime <= _replayOptions.EndTime && !cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
@@ -92,6 +75,7 @@ public sealed class BoilerReplayRunner : IMonitorReplayRunner
|
||||
var cheapEntry = _timeline.GetStateAt("sensor.nordpool_cheapest_intervals", currentTime);
|
||||
var skipPriceCapEntry = _timeline.GetStateAt(BoilerMonitorConsts.SkipPriceCapEntityId, currentTime);
|
||||
var budgetOverrideEntry = _timeline.GetStateAt(BoilerMonitorConsts.BudgetOverrideEntityId, currentTime);
|
||||
var autoManagementEntry = _timeline.GetStateAt(BoilerMonitorConsts.AutoManagementEntityId, currentTime);
|
||||
var dailyHoursEntry = _timeline.GetStateAt(BoilerMonitorConsts.BoilerDailyHoursEntityId, currentTime);
|
||||
|
||||
var boilerPowerWatts = ParseDouble(powerEntry?.State);
|
||||
@@ -100,9 +84,20 @@ public sealed class BoilerReplayRunner : IMonitorReplayRunner
|
||||
|
||||
_tracker.RecordPollResult(isHeating, pollInterval);
|
||||
|
||||
if (isHeating)
|
||||
{
|
||||
_waterReadyService.RecordHeatingObserved();
|
||||
}
|
||||
|
||||
if (boilerPowerWatts.HasValue)
|
||||
{
|
||||
_dataSeries.AddPoint(MonitorName, "PowerWatts", currentTime, boilerPowerWatts.Value);
|
||||
}
|
||||
|
||||
var isNowCheap = ReadAttributeBool(cheapEntry, "is_now_cheap");
|
||||
var skipPriceCap = string.Equals(skipPriceCapEntry?.State, "on", StringComparison.OrdinalIgnoreCase);
|
||||
var budgetOverride = string.Equals(budgetOverrideEntry?.State, "on", StringComparison.OrdinalIgnoreCase);
|
||||
var autoManagementEnabled = !string.Equals(autoManagementEntry?.State, BoilerMonitorConsts.SwitchOffState, StringComparison.OrdinalIgnoreCase);
|
||||
var dailyHours = ParseDouble(dailyHoursEntry?.State) ?? 1.0;
|
||||
|
||||
var waterReady = _waterReadyService.IsWaterReady(boilerSwitchState, boilerPowerWatts, heatingThreshold);
|
||||
@@ -126,9 +121,17 @@ public sealed class BoilerReplayRunner : IMonitorReplayRunner
|
||||
? (snapshot.AccumulatedRunTime.TotalSeconds / budgetTimeSpan.TotalSeconds) * 100.0
|
||||
: 0.0;
|
||||
|
||||
_dataSeries.AddPoint(MonitorName, "BudgetPercent", currentTime, budgetPercentage);
|
||||
_dataSeries.AddPoint(MonitorName, "SwitchState", currentTime,
|
||||
string.Equals(boilerSwitchState, "on", StringComparison.OrdinalIgnoreCase) ? 1.0 : 0.0);
|
||||
|
||||
var effectiveIsNowCheap = isNowCheap || skipPriceCap;
|
||||
var action = _boilerControlService.DetermineAction(
|
||||
effectiveIsNowCheap, waterReady, boilerSwitchState, budgetExhausted, budgetOverride);
|
||||
effectiveIsNowCheap,
|
||||
waterReady,
|
||||
boilerSwitchState,
|
||||
budgetExhausted,
|
||||
budgetOverride);
|
||||
|
||||
if (action != BoilerAction.NoChange && action != lastAction)
|
||||
{
|
||||
@@ -139,18 +142,32 @@ public sealed class BoilerReplayRunner : IMonitorReplayRunner
|
||||
_ => action.ToString()
|
||||
};
|
||||
|
||||
_replayTimeline.AddEvent(new ReplayEvent
|
||||
if (autoManagementEnabled)
|
||||
{
|
||||
Timestamp = currentTime,
|
||||
Monitor = MonitorName,
|
||||
EventType = ReplayEventType.Decision,
|
||||
Message = actionMessage,
|
||||
Details = $"Power: {boilerPowerWatts:F1}W, Runtime: {snapshot.AccumulatedRunTime:hh\\:mm\\:ss}, Sessions: {snapshot.SessionCount}"
|
||||
});
|
||||
_replayTimeline.AddEvent(new ReplayEvent
|
||||
{
|
||||
Timestamp = currentTime,
|
||||
Monitor = MonitorName,
|
||||
EventType = ReplayEventType.Decision,
|
||||
Message = actionMessage,
|
||||
Details = $"Power: {boilerPowerWatts:F1}W, Runtime: {snapshot.AccumulatedRunTime:hh\\:mm\\:ss}, Sessions: {snapshot.SessionCount}"
|
||||
});
|
||||
|
||||
if (action == BoilerAction.TurnOn)
|
||||
if (action == BoilerAction.TurnOn)
|
||||
{
|
||||
_waterReadyService.NotifyTurnedOn();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
_waterReadyService.NotifyTurnedOn();
|
||||
_replayTimeline.AddEvent(new ReplayEvent
|
||||
{
|
||||
Timestamp = currentTime,
|
||||
Monitor = MonitorName,
|
||||
EventType = ReplayEventType.Decision,
|
||||
Message = $"SUPPRESSED (auto control off): {actionMessage}",
|
||||
Details = $"Power: {boilerPowerWatts:F1}W, Runtime: {snapshot.AccumulatedRunTime:hh\\:mm\\:ss}, Sessions: {snapshot.SessionCount}"
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -171,12 +188,6 @@ public sealed class BoilerReplayRunner : IMonitorReplayRunner
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private string? ReadConfigEntityState(string entityId, DateTimeOffset timestamp)
|
||||
{
|
||||
var entry = _timeline.GetStateAt(entityId, timestamp);
|
||||
return entry?.State;
|
||||
}
|
||||
|
||||
private static bool ReadAttributeBool(HistoryStateEntry? entry, string attributeName)
|
||||
{
|
||||
if (entry?.Attributes is null)
|
||||
|
||||
@@ -14,6 +14,7 @@ public sealed class LightReplayRunner : IMonitorReplayRunner
|
||||
private readonly HistoryTimeline _timeline;
|
||||
private readonly ReplayTimeProvider _timeProvider;
|
||||
private readonly ReplayTimeline _replayTimeline;
|
||||
private readonly ReplayDataSeries _dataSeries;
|
||||
private readonly ILogger<LightReplayRunner> _logger;
|
||||
private readonly ReplayOptions _replayOptions;
|
||||
private readonly LightMonitorOptions _lightOptions;
|
||||
@@ -24,6 +25,7 @@ public sealed class LightReplayRunner : IMonitorReplayRunner
|
||||
HistoryTimeline timeline,
|
||||
ReplayTimeProvider timeProvider,
|
||||
ReplayTimeline replayTimeline,
|
||||
ReplayDataSeries dataSeries,
|
||||
ILogger<LightReplayRunner> logger,
|
||||
IOptions<ReplayOptions> replayOptions,
|
||||
IOptions<LightMonitorOptions> lightOptions)
|
||||
@@ -31,6 +33,7 @@ public sealed class LightReplayRunner : IMonitorReplayRunner
|
||||
_timeline = timeline;
|
||||
_timeProvider = timeProvider;
|
||||
_replayTimeline = replayTimeline;
|
||||
_dataSeries = dataSeries;
|
||||
_logger = logger;
|
||||
_replayOptions = replayOptions.Value;
|
||||
_lightOptions = lightOptions.Value;
|
||||
@@ -54,14 +57,20 @@ public sealed class LightReplayRunner : IMonitorReplayRunner
|
||||
|
||||
foreach (var entry in sunHistory)
|
||||
{
|
||||
if (cancellationToken.IsCancellationRequested) break;
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
if (entry.LastChanged < _replayOptions.StartTime || entry.LastChanged > _replayOptions.EndTime)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (string.Equals(entry.State, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase) &&
|
||||
var isBelowHorizon = string.Equals(entry.State, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase);
|
||||
_dataSeries.AddPoint(MonitorName, "SunBelowHorizon", entry.LastChanged, isBelowHorizon ? 1.0 : 0.0);
|
||||
|
||||
if (isBelowHorizon &&
|
||||
!string.Equals(previousSunState, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
_timeProvider.AdvanceTo(entry.LastChanged);
|
||||
@@ -72,6 +81,7 @@ public sealed class LightReplayRunner : IMonitorReplayRunner
|
||||
|
||||
if (anyoneHome && !lightAlreadyOn)
|
||||
{
|
||||
_dataSeries.AddPoint(MonitorName, "LightOn", entry.LastChanged, 1.0);
|
||||
_replayTimeline.AddEvent(new ReplayEvent
|
||||
{
|
||||
Timestamp = entry.LastChanged,
|
||||
@@ -87,7 +97,7 @@ public sealed class LightReplayRunner : IMonitorReplayRunner
|
||||
Timestamp = entry.LastChanged,
|
||||
Monitor = MonitorName,
|
||||
EventType = ReplayEventType.Info,
|
||||
Message = "Sun below horizon but nobody home — light stays off"
|
||||
Message = "Sun below horizon but nobody home -- light stays off"
|
||||
});
|
||||
}
|
||||
else
|
||||
@@ -115,7 +125,10 @@ public sealed class LightReplayRunner : IMonitorReplayRunner
|
||||
|
||||
foreach (var entry in personHistory)
|
||||
{
|
||||
if (cancellationToken.IsCancellationRequested) break;
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
if (entry.LastChanged < _replayOptions.StartTime || entry.LastChanged > _replayOptions.EndTime)
|
||||
{
|
||||
@@ -134,6 +147,7 @@ public sealed class LightReplayRunner : IMonitorReplayRunner
|
||||
|
||||
if (isDark && !lightAlreadyOn)
|
||||
{
|
||||
_dataSeries.AddPoint(MonitorName, "LightOn", entry.LastChanged, 1.0);
|
||||
_replayTimeline.AddEvent(new ReplayEvent
|
||||
{
|
||||
Timestamp = entry.LastChanged,
|
||||
@@ -169,7 +183,6 @@ public sealed class LightReplayRunner : IMonitorReplayRunner
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,16 +16,20 @@ public sealed class NordPoolReplayRunner : IMonitorReplayRunner
|
||||
private readonly HistoryTimeline _timeline;
|
||||
private readonly ReplayTimeProvider _timeProvider;
|
||||
private readonly ReplayTimeline _replayTimeline;
|
||||
private readonly ReplayDataSeries _dataSeries;
|
||||
private readonly ICheapestIntervalsFinder _cheapestIntervalsFinder;
|
||||
private readonly ILogger<NordPoolReplayRunner> _logger;
|
||||
private readonly ReplayOptions _options;
|
||||
|
||||
private const string NordPoolHaSensorId = "sensor.nordpool_kwh_lt_eur_3_10_0";
|
||||
|
||||
public string MonitorName => "NordPool";
|
||||
|
||||
public NordPoolReplayRunner(
|
||||
HistoryTimeline timeline,
|
||||
ReplayTimeProvider timeProvider,
|
||||
ReplayTimeline replayTimeline,
|
||||
ReplayDataSeries dataSeries,
|
||||
ICheapestIntervalsFinder cheapestIntervalsFinder,
|
||||
ILogger<NordPoolReplayRunner> logger,
|
||||
IOptions<ReplayOptions> options)
|
||||
@@ -33,6 +37,7 @@ public sealed class NordPoolReplayRunner : IMonitorReplayRunner
|
||||
_timeline = timeline;
|
||||
_timeProvider = timeProvider;
|
||||
_replayTimeline = replayTimeline;
|
||||
_dataSeries = dataSeries;
|
||||
_cheapestIntervalsFinder = cheapestIntervalsFinder;
|
||||
_logger = logger;
|
||||
_options = options.Value;
|
||||
@@ -50,11 +55,15 @@ public sealed class NordPoolReplayRunner : IMonitorReplayRunner
|
||||
{
|
||||
_timeProvider.AdvanceTo(currentTime);
|
||||
|
||||
var priceEntry = _timeline.GetStateAt(NordPoolConsts.CurrentPriceEntityId, currentTime);
|
||||
var priceEntry = _timeline.GetStateAt(NordPoolHaSensorId, currentTime)
|
||||
?? _timeline.GetStateAt(NordPoolConsts.CurrentPriceEntityId, currentTime);
|
||||
|
||||
if (priceEntry?.State is not null &&
|
||||
double.TryParse(priceEntry.State, CultureInfo.InvariantCulture, out var currentPrice))
|
||||
{
|
||||
if (lastReportedPrice is null || Math.Abs(currentPrice - lastReportedPrice.Value) > 0.001)
|
||||
_dataSeries.AddPoint(MonitorName, "Price", currentTime, currentPrice);
|
||||
|
||||
if (lastReportedPrice is null || Math.Abs(currentPrice - lastReportedPrice.Value) > 0.01)
|
||||
{
|
||||
_replayTimeline.AddEvent(new ReplayEvent
|
||||
{
|
||||
@@ -84,6 +93,8 @@ public sealed class NordPoolReplayRunner : IMonitorReplayRunner
|
||||
var isNowCheap = _cheapestIntervalsFinder.IsCurrentIntervalCheap(
|
||||
cheapest, currentTime.LocalDateTime);
|
||||
|
||||
_dataSeries.AddPoint(MonitorName, "IsCheap", currentTime, isNowCheap ? 1.0 : 0.0);
|
||||
|
||||
if (isNowCheap)
|
||||
{
|
||||
var currentInterval = cheapest.FirstOrDefault(i =>
|
||||
|
||||
@@ -8,7 +8,6 @@ using Microsoft.Extensions.Options;
|
||||
using NordPool.Models;
|
||||
using PowerMonitorManager.Interface;
|
||||
using PowerMonitorManager.Models;
|
||||
using PowerMonitorManager.Models.Consts;
|
||||
|
||||
namespace HomeAssistant.HistoryReplay.Runners;
|
||||
|
||||
@@ -17,6 +16,7 @@ public sealed class PowerReplayRunner : IMonitorReplayRunner
|
||||
private readonly HistoryTimeline _timeline;
|
||||
private readonly ReplayTimeProvider _timeProvider;
|
||||
private readonly ReplayTimeline _replayTimeline;
|
||||
private readonly ReplayDataSeries _dataSeries;
|
||||
private readonly IOtherPowerCalculationService _calculationService;
|
||||
private readonly IPowerCostCalculationService _costService;
|
||||
private readonly ILogger<PowerReplayRunner> _logger;
|
||||
@@ -29,6 +29,7 @@ public sealed class PowerReplayRunner : IMonitorReplayRunner
|
||||
HistoryTimeline timeline,
|
||||
ReplayTimeProvider timeProvider,
|
||||
ReplayTimeline replayTimeline,
|
||||
ReplayDataSeries dataSeries,
|
||||
IOtherPowerCalculationService calculationService,
|
||||
IPowerCostCalculationService costService,
|
||||
ILogger<PowerReplayRunner> logger,
|
||||
@@ -38,6 +39,7 @@ public sealed class PowerReplayRunner : IMonitorReplayRunner
|
||||
_timeline = timeline;
|
||||
_timeProvider = timeProvider;
|
||||
_replayTimeline = replayTimeline;
|
||||
_dataSeries = dataSeries;
|
||||
_calculationService = calculationService;
|
||||
_costService = costService;
|
||||
_logger = logger;
|
||||
@@ -69,6 +71,10 @@ public sealed class PowerReplayRunner : IMonitorReplayRunner
|
||||
var deviceReadings = DiscoverAndReadDevicePower(currentTime);
|
||||
var calculation = _calculationService.Calculate(totalPower.Value, deviceReadings);
|
||||
|
||||
_dataSeries.AddPoint(MonitorName, "TotalPower", currentTime, calculation.TotalPowerWatts);
|
||||
_dataSeries.AddPoint(MonitorName, "KnownDevices", currentTime, calculation.KnownDevicesSumWatts);
|
||||
_dataSeries.AddPoint(MonitorName, "OtherPower", currentTime, calculation.SmoothedOtherPowerWatts);
|
||||
|
||||
var nordPoolPriceEntry = _timeline.GetStateAt(NordPoolConsts.CurrentPriceEntityId, currentTime);
|
||||
var nordPoolPrice = ParseDouble(nordPoolPriceEntry?.State) ?? 0;
|
||||
|
||||
@@ -78,7 +84,6 @@ public sealed class PowerReplayRunner : IMonitorReplayRunner
|
||||
if (isAnomaly && anomalyStartTime is null)
|
||||
{
|
||||
anomalyStartTime = currentTime.LocalDateTime;
|
||||
|
||||
_replayTimeline.AddEvent(new ReplayEvent
|
||||
{
|
||||
Timestamp = currentTime,
|
||||
@@ -120,8 +125,8 @@ public sealed class PowerReplayRunner : IMonitorReplayRunner
|
||||
private IReadOnlyDictionary<string, double> DiscoverAndReadDevicePower(DateTimeOffset timestamp)
|
||||
{
|
||||
var readings = new Dictionary<string, double>();
|
||||
|
||||
var allEntities = _timeline.GetEntityIds();
|
||||
|
||||
foreach (var entityId in allEntities)
|
||||
{
|
||||
if (!entityId.StartsWith("sensor.", StringComparison.OrdinalIgnoreCase) ||
|
||||
|
||||
@@ -5,6 +5,7 @@ using HomeAssistant.HistoryReplay.Replay;
|
||||
using HomeAssistant.HistoryReplay.Reporting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NetDaemon.HassModel;
|
||||
using ShowerMonitor.Models.Enums;
|
||||
using ShowerMonitorManager.Interface;
|
||||
using ShowerMonitorManager.Models;
|
||||
@@ -16,8 +17,10 @@ public sealed class ShowerReplayRunner : IMonitorReplayRunner
|
||||
private readonly HistoryTimeline _timeline;
|
||||
private readonly ReplayTimeProvider _timeProvider;
|
||||
private readonly ReplayTimeline _replayTimeline;
|
||||
private readonly ReplayDataSeries _dataSeries;
|
||||
private readonly IShowerDetectionService _detectionService;
|
||||
private readonly IExhaustFanControlService _fanControlService;
|
||||
private readonly IHaContext _haContext;
|
||||
private readonly ILogger<ShowerReplayRunner> _logger;
|
||||
private readonly ReplayOptions _replayOptions;
|
||||
private readonly ShowerMonitorOptions _showerOptions;
|
||||
@@ -28,8 +31,10 @@ public sealed class ShowerReplayRunner : IMonitorReplayRunner
|
||||
HistoryTimeline timeline,
|
||||
ReplayTimeProvider timeProvider,
|
||||
ReplayTimeline replayTimeline,
|
||||
ReplayDataSeries dataSeries,
|
||||
IShowerDetectionService detectionService,
|
||||
IExhaustFanControlService fanControlService,
|
||||
IHaContext haContext,
|
||||
ILogger<ShowerReplayRunner> logger,
|
||||
IOptions<ReplayOptions> replayOptions,
|
||||
IOptions<ShowerMonitorOptions> showerOptions)
|
||||
@@ -37,8 +42,10 @@ public sealed class ShowerReplayRunner : IMonitorReplayRunner
|
||||
_timeline = timeline;
|
||||
_timeProvider = timeProvider;
|
||||
_replayTimeline = replayTimeline;
|
||||
_dataSeries = dataSeries;
|
||||
_detectionService = detectionService;
|
||||
_fanControlService = fanControlService;
|
||||
_haContext = haContext;
|
||||
_logger = logger;
|
||||
_replayOptions = replayOptions.Value;
|
||||
_showerOptions = showerOptions.Value;
|
||||
@@ -64,10 +71,16 @@ public sealed class ShowerReplayRunner : IMonitorReplayRunner
|
||||
|
||||
if (bathroomHumidity.HasValue && homeHumidity.HasValue)
|
||||
{
|
||||
_dataSeries.AddPoint(MonitorName, "BathroomHumidity", currentTime, bathroomHumidity.Value);
|
||||
_dataSeries.AddPoint(MonitorName, "HomeHumidity", currentTime, homeHumidity.Value);
|
||||
_dataSeries.AddPoint(MonitorName, "Differential", currentTime, bathroomHumidity.Value - homeHumidity.Value);
|
||||
|
||||
var state = _detectionService.Evaluate(bathroomHumidity.Value, homeHumidity.Value, currentTime);
|
||||
var differential = bathroomHumidity.Value - homeHumidity.Value;
|
||||
|
||||
_fanControlService.Evaluate(state, currentTime);
|
||||
_dataSeries.AddPoint(MonitorName, "State", currentTime, (double)state);
|
||||
|
||||
_fanControlService.Evaluate(state, currentTime, _haContext);
|
||||
|
||||
if (state != previousState)
|
||||
{
|
||||
@@ -83,7 +96,7 @@ public sealed class ShowerReplayRunner : IMonitorReplayRunner
|
||||
Timestamp = currentTime,
|
||||
Monitor = MonitorName,
|
||||
EventType = eventType,
|
||||
Message = $"State: {previousState} → {state} (bathroom: {bathroomHumidity.Value:F1}%, home: {homeHumidity.Value:F1}%, diff: {differential:F1}%)",
|
||||
Message = $"State: {previousState} -> {state} (bathroom: {bathroomHumidity.Value:F1}%, home: {homeHumidity.Value:F1}%, diff: {differential:F1}%)",
|
||||
Details = GetStateChangeDetails(state)
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
using BoilerMonitorManager;
|
||||
using BoilerMonitorManager.Interface;
|
||||
using PowerMonitorManager;
|
||||
using ShowerMonitorManager;
|
||||
using HomeAssistant.HistoryReplay.Configuration;
|
||||
using HomeAssistant.HistoryReplay.HistoryData;
|
||||
using HomeAssistant.HistoryReplay.Replay;
|
||||
using HomeAssistant.HistoryReplay.Reporting;
|
||||
using HomeAssistant.HistoryReplay.Runners;
|
||||
using LightMonitorManager.Models;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NordPoolManager.Interface;
|
||||
using PowerMonitorManager.Interface;
|
||||
using PowerMonitorManager.Models;
|
||||
using ShowerMonitorManager.Interface;
|
||||
using ShowerMonitorManager.Models;
|
||||
|
||||
namespace HomeAssistant.HistoryReplay.Services;
|
||||
|
||||
public sealed class ReplayOrchestrationService
|
||||
{
|
||||
private readonly IHistoryDataProvider _historyProvider;
|
||||
private readonly IServiceProvider _serviceProvider;
|
||||
private readonly ILogger<ReplayOrchestrationService> _logger;
|
||||
|
||||
public ReplayTimeline Timeline { get; } = new();
|
||||
public ReplayDataSeries DataSeries { get; } = new();
|
||||
public ReplayStatus Status { get; private set; } = ReplayStatus.Idle;
|
||||
public string? ErrorMessage { get; private set; }
|
||||
public string? ProgressMessage { get; private set; }
|
||||
|
||||
public event Action? OnStateChanged;
|
||||
|
||||
public void SetError(string message)
|
||||
{
|
||||
ErrorMessage = message;
|
||||
Status = ReplayStatus.Failed;
|
||||
NotifyStateChanged();
|
||||
}
|
||||
|
||||
public ReplayOrchestrationService(
|
||||
IHistoryDataProvider historyProvider,
|
||||
IServiceProvider serviceProvider,
|
||||
ILogger<ReplayOrchestrationService> logger)
|
||||
{
|
||||
_historyProvider = historyProvider;
|
||||
_serviceProvider = serviceProvider;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task RunReplayAsync(
|
||||
DateTimeOffset startTime,
|
||||
DateTimeOffset endTime,
|
||||
ReplayMonitorFlags monitors,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
Timeline.Clear();
|
||||
DataSeries.Clear();
|
||||
ErrorMessage = null;
|
||||
ProgressMessage = null;
|
||||
|
||||
Status = ReplayStatus.FetchingHistory;
|
||||
ProgressMessage = "Connecting to Home Assistant...";
|
||||
NotifyStateChanged();
|
||||
|
||||
var showerOpts = _serviceProvider.GetRequiredService<IOptions<ShowerMonitorOptions>>().Value;
|
||||
var powerOpts = _serviceProvider.GetRequiredService<IOptions<PowerMonitorOptions>>().Value;
|
||||
var lightOpts = _serviceProvider.GetRequiredService<IOptions<LightMonitorOptions>>().Value;
|
||||
|
||||
const string boilerPowerEntityId = "sensor.boiler_power";
|
||||
const string boilerSwitchEntityId = "switch.boiler";
|
||||
|
||||
var (minimalEntities, fullEntities) = ReplayEntityMap.GetPartitionedEntities(
|
||||
boilerPowerEntityId,
|
||||
boilerSwitchEntityId,
|
||||
bathroomHumidityEntityId: showerOpts.BathroomHumidityEntityId,
|
||||
mainHomeHumidityEntityId: showerOpts.MainHomeHumidityEntityId,
|
||||
mainMeterEntityId: powerOpts.MainMeterEntityId,
|
||||
sunEntityId: lightOpts.SunEntityId,
|
||||
lightEntityId: lightOpts.LightEntityId,
|
||||
personEntityIds: lightOpts.PersonEntityIds);
|
||||
|
||||
var totalEntityCount = minimalEntities.Count + fullEntities.Count;
|
||||
_logger.LogInformation(
|
||||
"Fetching history for {MinCount} minimal + {FullCount} full entities ({Start} to {End})",
|
||||
minimalEntities.Count, fullEntities.Count, startTime, endTime);
|
||||
|
||||
ProgressMessage = $"Fetching history for {totalEntityCount} entities...";
|
||||
NotifyStateChanged();
|
||||
|
||||
var historyTimeline = await _historyProvider.FetchHistoryAsync(
|
||||
minimalEntities, fullEntities, startTime, endTime, cancellationToken);
|
||||
|
||||
ProgressMessage = $"Loaded {historyTimeline.TotalEntryCount} data points. Running replay...";
|
||||
Status = ReplayStatus.Running;
|
||||
NotifyStateChanged();
|
||||
|
||||
var replayOptions = new ReplayOptions
|
||||
{
|
||||
StartTime = startTime,
|
||||
EndTime = endTime,
|
||||
Monitors = monitors
|
||||
};
|
||||
var replayOptionsWrapper = Options.Create(replayOptions);
|
||||
|
||||
var timeProvider = new ReplayTimeProvider(startTime);
|
||||
|
||||
var replayHaContext = new ReplayHaContext(
|
||||
historyTimeline, timeProvider, Timeline,
|
||||
_serviceProvider.GetRequiredService<ILogger<ReplayHaContext>>());
|
||||
|
||||
var runners = BuildRunners(
|
||||
historyTimeline, timeProvider, replayHaContext, replayOptionsWrapper, monitors,
|
||||
boilerPowerEntityId, boilerSwitchEntityId);
|
||||
|
||||
_logger.LogInformation("Running {Count} monitor replay(s) in parallel", runners.Count);
|
||||
|
||||
var tasks = runners.Select(r => Task.Run(() => r.RunAsync(cancellationToken), cancellationToken));
|
||||
await Task.WhenAll(tasks);
|
||||
|
||||
Status = ReplayStatus.Completed;
|
||||
_logger.LogInformation("Replay completed with {Count} events", Timeline.GetAllEvents().Count);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Replay failed");
|
||||
ErrorMessage = ex.Message;
|
||||
Status = ReplayStatus.Failed;
|
||||
}
|
||||
finally
|
||||
{
|
||||
NotifyStateChanged();
|
||||
}
|
||||
}
|
||||
|
||||
private List<IMonitorReplayRunner> BuildRunners(
|
||||
HistoryTimeline historyTimeline,
|
||||
ReplayTimeProvider timeProvider,
|
||||
ReplayHaContext replayHaContext,
|
||||
IOptions<ReplayOptions> replayOptions,
|
||||
ReplayMonitorFlags monitors,
|
||||
string boilerPowerEntityId,
|
||||
string boilerSwitchEntityId)
|
||||
{
|
||||
var runners = new List<IMonitorReplayRunner>();
|
||||
|
||||
if (monitors.NordPool)
|
||||
{
|
||||
runners.Add(new NordPoolReplayRunner(
|
||||
historyTimeline, timeProvider, Timeline, DataSeries,
|
||||
_serviceProvider.GetRequiredService<ICheapestIntervalsFinder>(),
|
||||
_serviceProvider.GetRequiredService<ILogger<NordPoolReplayRunner>>(),
|
||||
replayOptions));
|
||||
}
|
||||
|
||||
if (monitors.Boiler)
|
||||
{
|
||||
runners.Add(new BoilerReplayRunner(
|
||||
historyTimeline, timeProvider, Timeline, DataSeries,
|
||||
_serviceProvider.GetRequiredService<IBoilerControlService>(),
|
||||
new BoilerRunTimeTracker(),
|
||||
new WaterReadyService(
|
||||
_serviceProvider.GetRequiredService<ILogger<WaterReadyService>>(), timeProvider),
|
||||
_serviceProvider.GetRequiredService<ILogger<BoilerReplayRunner>>(),
|
||||
replayOptions,
|
||||
boilerPowerEntityId,
|
||||
boilerSwitchEntityId));
|
||||
}
|
||||
|
||||
if (monitors.Shower)
|
||||
{
|
||||
var showerOpts = _serviceProvider.GetRequiredService<IOptions<ShowerMonitorOptions>>();
|
||||
var rateCalc = new ShowerMonitorManager.HumidityRateCalculator(showerOpts.Value.RateWindowSize);
|
||||
var detection = new ShowerMonitorManager.ShowerDetectionService(
|
||||
rateCalc,
|
||||
showerOpts);
|
||||
var fan = new ExhaustFanControlService(showerOpts);
|
||||
|
||||
runners.Add(new ShowerReplayRunner(
|
||||
historyTimeline, timeProvider, Timeline, DataSeries,
|
||||
detection, fan, replayHaContext,
|
||||
_serviceProvider.GetRequiredService<ILogger<ShowerReplayRunner>>(),
|
||||
replayOptions, showerOpts));
|
||||
}
|
||||
|
||||
if (monitors.Power)
|
||||
{
|
||||
runners.Add(new PowerReplayRunner(
|
||||
historyTimeline, timeProvider, Timeline, DataSeries,
|
||||
new OtherPowerCalculationService(
|
||||
_serviceProvider.GetRequiredService<IOptions<PowerMonitorOptions>>()),
|
||||
new PowerCostCalculationService(),
|
||||
_serviceProvider.GetRequiredService<ILogger<PowerReplayRunner>>(),
|
||||
replayOptions,
|
||||
_serviceProvider.GetRequiredService<IOptions<PowerMonitorOptions>>()));
|
||||
}
|
||||
|
||||
if (monitors.Light)
|
||||
{
|
||||
runners.Add(new LightReplayRunner(
|
||||
historyTimeline, timeProvider, Timeline, DataSeries,
|
||||
_serviceProvider.GetRequiredService<ILogger<LightReplayRunner>>(),
|
||||
replayOptions,
|
||||
_serviceProvider.GetRequiredService<IOptions<LightMonitorOptions>>()));
|
||||
}
|
||||
|
||||
return runners;
|
||||
}
|
||||
|
||||
private void NotifyStateChanged() => OnStateChanged?.Invoke();
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace HomeAssistant.HistoryReplay.Services;
|
||||
|
||||
public enum ReplayStatus
|
||||
{
|
||||
Idle,
|
||||
FetchingHistory,
|
||||
Running,
|
||||
Completed,
|
||||
Failed
|
||||
}
|
||||
@@ -6,13 +6,13 @@
|
||||
"Ssl": false
|
||||
},
|
||||
"Replay": {
|
||||
"StartTime": "2026-03-30T00:00:00+02:00",
|
||||
"StartTime": "2026-03-01T00:00:00+02:00",
|
||||
"EndTime": "2026-03-31T00:00:00+02:00",
|
||||
"Monitors": {
|
||||
"NordPool": true,
|
||||
"Boiler": true,
|
||||
"Shower": true,
|
||||
"Power": false,
|
||||
"Power": true,
|
||||
"Light": true
|
||||
}
|
||||
},
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
body {
|
||||
background-color: #1a1d21;
|
||||
color: #e0e0e0;
|
||||
}
|
||||
|
||||
.card {
|
||||
background-color: #212529;
|
||||
border-color: #343a40;
|
||||
}
|
||||
|
||||
.card-header {
|
||||
background-color: #2b3035;
|
||||
border-bottom-color: #343a40;
|
||||
}
|
||||
|
||||
.stat-card {
|
||||
text-align: center;
|
||||
transition: transform 0.15s;
|
||||
}
|
||||
|
||||
.stat-card:hover {
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
|
||||
.stat-card .display-6 {
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.badge-decision { background-color: #198754; }
|
||||
.badge-statechange { background-color: #0dcaf0; color: #000; }
|
||||
.badge-warning { background-color: #ffc107; color: #000; }
|
||||
.badge-anomaly { background-color: #dc3545; }
|
||||
.badge-servicecall { background-color: #6f42c1; }
|
||||
.badge-info { background-color: #6c757d; }
|
||||
|
||||
.nav-tabs .nav-link {
|
||||
color: #adb5bd;
|
||||
}
|
||||
|
||||
.nav-tabs .nav-link.active {
|
||||
background-color: #212529;
|
||||
border-color: #495057 #495057 #212529;
|
||||
color: #e0e0e0;
|
||||
}
|
||||
|
||||
.table {
|
||||
--bs-table-bg: transparent;
|
||||
--bs-table-color: #e0e0e0;
|
||||
}
|
||||
|
||||
.status-bar {
|
||||
min-height: 40px;
|
||||
}
|
||||
|
||||
.apexcharts-canvas {
|
||||
background: transparent !important;
|
||||
}
|
||||
@@ -10,6 +10,13 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Content Include="appsettings.json">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</Content>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="10.0.5" />
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting" Version="10.0.5" />
|
||||
<PackageReference Include="Microsoft.Extensions.Http" Version="10.0.5" />
|
||||
<PackageReference Include="ModelContextProtocol" Version="1.2.0" />
|
||||
|
||||
@@ -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 =>
|
||||
{
|
||||
|
||||
@@ -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<string>();
|
||||
if (!string.IsNullOrWhiteSpace(entityId))
|
||||
{
|
||||
queryParts.Add($"entity={Uri.EscapeDataString(entityId)}");
|
||||
}
|
||||
|
||||
if (endTime.HasValue)
|
||||
{
|
||||
queryParts.Add($"end_time={Uri.EscapeDataString(endTime.Value.ToString("O"))}");
|
||||
}
|
||||
|
||||
if (queryParts.Count > 0)
|
||||
{
|
||||
path += "?" + string.Join("&", queryParts);
|
||||
}
|
||||
|
||||
return GetJsonAsync(path, cancellationToken);
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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<Dictionary<string, object>>(serviceData) ?? [];
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(entityId))
|
||||
{
|
||||
dataDict["entity_id"] = entityId;
|
||||
}
|
||||
|
||||
data = JsonSerializer.SerializeToElement(dataDict);
|
||||
}
|
||||
|
||||
@@ -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<string> RunSmokeTest(
|
||||
[Description(
|
||||
"Comma-separated domains to check, e.g. 'switch,sensor,light'. " +
|
||||
"Leave empty to check all critical domains (sensor, switch, binary_sensor, light).")]
|
||||
string? domains = null,
|
||||
[Description(
|
||||
"Minutes of logbook history to scan for activity. Defaults to 30.")]
|
||||
int? logbookWindowMinutes = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var targetDomains = ParseDomains(domains);
|
||||
var windowMinutes = logbookWindowMinutes ?? DefaultLogbookWindowMinutes;
|
||||
|
||||
var apiHealthTask = CheckApiHealthAsync(cancellationToken);
|
||||
var entityCheckTask = CheckEntitiesAsync(targetDomains, cancellationToken);
|
||||
var logbookCheckTask = CheckRecentActivityAsync(windowMinutes, cancellationToken);
|
||||
|
||||
await Task.WhenAll(apiHealthTask, entityCheckTask, logbookCheckTask).ConfigureAwait(false);
|
||||
|
||||
var report = new
|
||||
{
|
||||
timestamp = DateTimeOffset.UtcNow,
|
||||
apiHealth = await apiHealthTask.ConfigureAwait(false),
|
||||
entityCheck = await entityCheckTask.ConfigureAwait(false),
|
||||
recentActivity = await logbookCheckTask.ConfigureAwait(false),
|
||||
overall = DetermineOverallStatus(
|
||||
await apiHealthTask.ConfigureAwait(false),
|
||||
await entityCheckTask.ConfigureAwait(false))
|
||||
};
|
||||
|
||||
return JsonSerializer.Serialize(report, SerializerOptions);
|
||||
}
|
||||
|
||||
[McpServerTool, Description(
|
||||
"Assert that a specific Home Assistant entity has an expected state value. " +
|
||||
"Returns a pass/fail result with the actual vs expected values and entity attributes.")]
|
||||
public async Task<string> AssertEntityState(
|
||||
[Description("Full entity ID, e.g. 'switch.boiler' or 'sensor.nordpool_current_price'")] string entityId,
|
||||
[Description("Expected state value, e.g. 'on', 'off', '22.5'")] string expectedState,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var entity = await _client.GetEntityStateAsync(entityId, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
var actualState = entity.TryGetProperty("state", out var stateProp)
|
||||
? stateProp.GetString() ?? string.Empty
|
||||
: string.Empty;
|
||||
|
||||
var passed = string.Equals(actualState, expectedState, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
var result = new
|
||||
{
|
||||
entityId,
|
||||
expectedState,
|
||||
actualState,
|
||||
passed,
|
||||
lastChanged = entity.TryGetProperty("last_changed", out var lc) ? lc.GetString() : null,
|
||||
lastUpdated = entity.TryGetProperty("last_updated", out var lu) ? lu.GetString() : null
|
||||
};
|
||||
|
||||
return JsonSerializer.Serialize(result, SerializerOptions);
|
||||
}
|
||||
|
||||
[McpServerTool, Description(
|
||||
"Validate multiple Home Assistant entities in parallel. " +
|
||||
"Checks that each entity exists, is reachable, and is not in unavailable/unknown state. " +
|
||||
"Optionally assert expected state values.")]
|
||||
public async Task<string> ValidateEntities(
|
||||
[Description(
|
||||
"Comma-separated entity IDs to validate, e.g. 'switch.boiler,sensor.nordpool_current_price'")]
|
||||
string entityIds,
|
||||
[Description(
|
||||
"Optional comma-separated expected states matching the entity IDs order. " +
|
||||
"Use empty string to skip assertion for an entity, e.g. 'on,,42.5'")]
|
||||
string? expectedStates = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var ids = entityIds.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||||
var states = expectedStates?.Split(',') ?? [];
|
||||
|
||||
var results = new ConcurrentBag<object>();
|
||||
var parallelOptions = new ParallelOptions
|
||||
{
|
||||
MaxDegreeOfParallelism = MaxDegreeOfParallelism,
|
||||
CancellationToken = cancellationToken
|
||||
};
|
||||
|
||||
await Parallel.ForEachAsync(
|
||||
ids.Select((id, index) => (id, index)),
|
||||
parallelOptions,
|
||||
async (item, ct) =>
|
||||
{
|
||||
var expectedState = item.index < states.Length
|
||||
? states[item.index]?.Trim()
|
||||
: null;
|
||||
|
||||
var result = await ValidateSingleEntityAsync(item.id, expectedState, ct).ConfigureAwait(false);
|
||||
results.Add(result);
|
||||
}).ConfigureAwait(false);
|
||||
|
||||
var ordered = results.Cast<dynamic>()
|
||||
.OrderBy(r => (string)r.entityId)
|
||||
.ToList();
|
||||
|
||||
var allPassed = ordered.All(r => (bool)r.passed);
|
||||
|
||||
var report = new
|
||||
{
|
||||
timestamp = DateTimeOffset.UtcNow,
|
||||
passed = allPassed,
|
||||
total = ordered.Count,
|
||||
failed = ordered.Count(r => !(bool)r.passed),
|
||||
entities = ordered
|
||||
};
|
||||
|
||||
return JsonSerializer.Serialize(report, SerializerOptions);
|
||||
}
|
||||
|
||||
private static string[] ParseDomains(string? domains) =>
|
||||
string.IsNullOrWhiteSpace(domains)
|
||||
? CriticalDomains
|
||||
: domains.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||||
|
||||
private async Task<object> CheckApiHealthAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var status = await _client.GetApiStatusAsync(cancellationToken).ConfigureAwait(false);
|
||||
var message = status.TryGetProperty("message", out var msg) ? msg.GetString() : "unknown";
|
||||
return new { status = "healthy", message };
|
||||
}
|
||||
catch (HttpRequestException ex)
|
||||
{
|
||||
return new { status = "unreachable", message = ex.Message };
|
||||
}
|
||||
catch (TaskCanceledException)
|
||||
{
|
||||
return new { status = "timeout", message = "Home Assistant API did not respond in time" };
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<object> CheckEntitiesAsync(string[] targetDomains, CancellationToken cancellationToken)
|
||||
{
|
||||
var allStates = await _client.GetAllStatesAsync(cancellationToken).ConfigureAwait(false);
|
||||
var domainSet = new HashSet<string>(targetDomains, StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
var unhealthy = new ConcurrentBag<object>();
|
||||
var totalChecked = 0;
|
||||
|
||||
foreach (var entity in allStates.EnumerateArray())
|
||||
{
|
||||
if (!entity.TryGetProperty("entity_id", out var eidProp))
|
||||
continue;
|
||||
|
||||
var entityId = eidProp.GetString() ?? string.Empty;
|
||||
var entityDomain = entityId.Split('.').FirstOrDefault() ?? string.Empty;
|
||||
|
||||
if (!domainSet.Contains(entityDomain))
|
||||
continue;
|
||||
|
||||
Interlocked.Increment(ref totalChecked);
|
||||
|
||||
if (!entity.TryGetProperty("state", out var stateProp))
|
||||
continue;
|
||||
|
||||
var state = stateProp.GetString();
|
||||
if (string.Equals(state, UnavailableState, StringComparison.OrdinalIgnoreCase) ||
|
||||
string.Equals(state, UnknownState, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
unhealthy.Add(new
|
||||
{
|
||||
entityId,
|
||||
state,
|
||||
lastChanged = entity.TryGetProperty("last_changed", out var lc) ? lc.GetString() : null
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return new
|
||||
{
|
||||
passed = unhealthy.IsEmpty,
|
||||
totalChecked,
|
||||
unhealthyCount = unhealthy.Count,
|
||||
unhealthyEntities = unhealthy.OrderBy(e => e.ToString()).ToList()
|
||||
};
|
||||
}
|
||||
|
||||
private async Task<object> CheckRecentActivityAsync(int windowMinutes, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var startTime = DateTimeOffset.UtcNow.AddMinutes(-windowMinutes);
|
||||
var logbook = await _client.GetLogbookAsync(
|
||||
entityId: null,
|
||||
startTime: startTime,
|
||||
endTime: null,
|
||||
cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
|
||||
var entryCount = logbook.ValueKind == JsonValueKind.Array ? logbook.GetArrayLength() : 0;
|
||||
return new
|
||||
{
|
||||
windowMinutes,
|
||||
entryCount,
|
||||
hasActivity = entryCount > 0
|
||||
};
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return new
|
||||
{
|
||||
windowMinutes,
|
||||
entryCount = 0,
|
||||
hasActivity = false,
|
||||
error = ex.Message
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private static string DetermineOverallStatus(object apiHealth, object entityCheck)
|
||||
{
|
||||
var apiJson = JsonSerializer.SerializeToElement(apiHealth);
|
||||
var entityJson = JsonSerializer.SerializeToElement(entityCheck);
|
||||
|
||||
var apiHealthy = apiJson.TryGetProperty("status", out var s) &&
|
||||
string.Equals(s.GetString(), "healthy", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
var entitiesHealthy = entityJson.TryGetProperty("passed", out var p) && p.GetBoolean();
|
||||
|
||||
return apiHealthy && entitiesHealthy ? "PASS" : "FAIL";
|
||||
}
|
||||
|
||||
private async Task<object> ValidateSingleEntityAsync(
|
||||
string entityId,
|
||||
string? expectedState,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var entity = await _client.GetEntityStateAsync(entityId, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
var actualState = entity.TryGetProperty("state", out var stateProp)
|
||||
? stateProp.GetString() ?? string.Empty
|
||||
: string.Empty;
|
||||
|
||||
var isAvailable = !string.Equals(actualState, UnavailableState, StringComparison.OrdinalIgnoreCase) &&
|
||||
!string.Equals(actualState, UnknownState, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
var stateMatch = string.IsNullOrEmpty(expectedState) ||
|
||||
string.Equals(actualState, expectedState, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
return new
|
||||
{
|
||||
entityId,
|
||||
actualState,
|
||||
expectedState = expectedState ?? "(any)",
|
||||
isAvailable,
|
||||
stateMatch,
|
||||
passed = isAvailable && stateMatch,
|
||||
lastChanged = entity.TryGetProperty("last_changed", out var lc) ? lc.GetString() : null
|
||||
};
|
||||
}
|
||||
catch (HttpRequestException)
|
||||
{
|
||||
return new
|
||||
{
|
||||
entityId,
|
||||
actualState = "error",
|
||||
expectedState = expectedState ?? "(any)",
|
||||
isAvailable = false,
|
||||
stateMatch = false,
|
||||
passed = false,
|
||||
lastChanged = (string?)null
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
{
|
||||
}
|
||||
@@ -29,7 +29,7 @@
|
||||
</None>
|
||||
</ItemGroup>
|
||||
<Target Name="AfterPublishMessage" AfterTargets="Publish">
|
||||
<Message Text="Publish done! Copy all content in directory: $(PublishDir) to the `/config/netdaemon4' folder for add-on or your custom folder to deploy." Importance="high"/>
|
||||
<Message Text="Publish done! Copy all content in directory: $(PublishDir) to the `/config/netdaemon4' folder for add-on or your custom folder to deploy." Importance="high" />
|
||||
</Target>
|
||||
|
||||
<ItemGroup>
|
||||
@@ -58,5 +58,6 @@
|
||||
<ProjectReference Include="..\LightMonitor.Models\LightMonitor.Models.csproj" />
|
||||
<ProjectReference Include="..\BatteryMonitor.Manager\BatteryMonitor.Manager.csproj" />
|
||||
<ProjectReference Include="..\BatteryMonitor.Models\BatteryMonitor.Models.csproj" />
|
||||
<ProjectReference Include="..\LeakMonitor.Manager\LeakMonitor.Manager.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
||||
@@ -4,8 +4,8 @@
|
||||
"commandName": "Project",
|
||||
"workingDirectory": "$(ProjectDir)",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development",
|
||||
"DOTNET_ENVIRONMENT": "Development"
|
||||
"ASPNETCORE_ENVIRONMENT": "development",
|
||||
"DOTNET_ENVIRONMENT": "development"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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} <s:{SourceContext}>{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_*"
|
||||
|
||||
@@ -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<INordPoolPriceService, NordPoolPriceService>()
|
||||
.AddTransient<INordPoolEntityService, NordPoolEntityService>()
|
||||
.AddSingleton<ICheapestIntervalsFinder, CheapestIntervalsFinder>()
|
||||
.AddScoped<INordPoolBoilerConfigProvider, NordPoolBoilerConfigProvider>()
|
||||
.Configure<PowerMonitorOptions>(context.Configuration.GetSection(PowerMonitorOptions.SectionName))
|
||||
.AddPowerMonitor(context.Configuration)
|
||||
.Configure<BoilerMonitorOptions>(context.Configuration.GetSection(BoilerMonitorOptions.SectionName))
|
||||
@@ -65,10 +67,12 @@ try
|
||||
.AddLightMonitor(context.Configuration)
|
||||
.Configure<BatteryMonitorOptions>(context.Configuration.GetSection(BatteryMonitorOptions.SectionName))
|
||||
.AddBatteryMonitor(context.Configuration)
|
||||
)
|
||||
.Build()
|
||||
.RunAsync()
|
||||
.ConfigureAwait(false);
|
||||
.Configure<LeakMonitorOptions>(context.Configuration.GetSection(LeakMonitorOptions.SectionName))
|
||||
.AddLeakMonitor(context.Configuration);
|
||||
})
|
||||
.Build();
|
||||
|
||||
await app.RunAsync().ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
|
||||
+48
-6
@@ -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
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<IsPackable>false</IsPackable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="coverlet.collector" Version="8.0.0">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.3.0" />
|
||||
<PackageReference Include="xunit" Version="2.9.3" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="FluentAssertions" Version="8.8.0" />
|
||||
<PackageReference Include="Moq" Version="4.20.72" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Using Include="Xunit" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\LeakMonitor.Manager\LeakMonitor.Manager.csproj" />
|
||||
<ProjectReference Include="..\LeakMonitor.Models\LeakMonitor.Models.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -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<IHaContext> _haContextMock;
|
||||
private readonly Mock<ILeakNotificationService> _notificationServiceMock;
|
||||
private readonly Mock<ILogger<LeakMonitorInit>> _loggerMock;
|
||||
private readonly LeakMonitorOptions _options;
|
||||
|
||||
public LeakMonitorInitTests()
|
||||
{
|
||||
_haContextMock = new Mock<IHaContext>();
|
||||
_notificationServiceMock = new Mock<ILeakNotificationService>();
|
||||
_loggerMock = new Mock<ILogger<LeakMonitorInit>>();
|
||||
_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<string>()),
|
||||
Times.Never);
|
||||
_notificationServiceMock.Verify(
|
||||
n => n.DismissLeakAlert(It.IsAny<string>()),
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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<IHaContext> _haContextMock;
|
||||
private readonly Mock<ILogger<LeakNotificationService>> _loggerMock;
|
||||
private readonly LeakMonitorOptions _options;
|
||||
|
||||
public LeakNotificationServiceTests()
|
||||
{
|
||||
_haContextMock = new Mock<IHaContext>();
|
||||
_loggerMock = new Mock<ILogger<LeakNotificationService>>();
|
||||
_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<ServiceTarget?>(),
|
||||
It.IsAny<object?>()), 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<ServiceTarget?>(),
|
||||
It.IsAny<object?>()), 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<ServiceTarget?>(),
|
||||
It.IsAny<object?>()), 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<ServiceTarget?>(),
|
||||
It.IsAny<object?>()), 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<ServiceTarget?>(),
|
||||
It.IsAny<object?>()), 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<ServiceTarget?>(),
|
||||
It.IsAny<object?>()), 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
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
namespace LeakMonitorManager.Interface;
|
||||
|
||||
public interface ILeakMonitorInit
|
||||
{
|
||||
Task InitializeAsync();
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace LeakMonitorManager.Interface;
|
||||
|
||||
public interface ILeakNotificationService
|
||||
{
|
||||
void SendLeakAlert(string sensorEntityId);
|
||||
|
||||
void DismissLeakAlert(string sensorEntityId);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<RootNamespace>LeakMonitorManager</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
|
||||
<_Parameter1>LeakMonitor.Manager.Tests</_Parameter1>
|
||||
</AssemblyAttribute>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\HomeAssistant.Entities\HomeAssistant.Entities.csproj" />
|
||||
<ProjectReference Include="..\LeakMonitor.Models\LeakMonitor.Models.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.5" />
|
||||
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.11.0" />
|
||||
<PackageReference Include="NetDaemon.HassModel" Version="26.11.0" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -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<LeakMonitorInit> _logger;
|
||||
private readonly LeakMonitorOptions _options;
|
||||
|
||||
public LeakMonitorInit(
|
||||
IHaContext haContext,
|
||||
ILeakNotificationService notificationService,
|
||||
ILogger<LeakMonitorInit> logger,
|
||||
IOptions<LeakMonitorOptions> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<LeakMonitorOptions>() ?? new LeakMonitorOptions();
|
||||
|
||||
if (!options.Enabled)
|
||||
{
|
||||
return services;
|
||||
}
|
||||
|
||||
services
|
||||
.AddNetDaemonApp<LeakMonitorInit>()
|
||||
.AddScoped<ILeakNotificationService, LeakNotificationService>();
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
@@ -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<LeakNotificationService> _logger;
|
||||
private readonly LeakMonitorOptions _options;
|
||||
private readonly ConcurrentDictionary<string, DateTimeOffset> _lastNotificationTimes = new();
|
||||
|
||||
public LeakNotificationService(
|
||||
IHaContext haContext,
|
||||
ILogger<LeakNotificationService> logger,
|
||||
IOptions<LeakMonitorOptions> 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}";
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<RootNamespace>LeakMonitor.Models</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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<IHaContext> _haContextMock = new();
|
||||
private readonly Mock<IPresenceService> _presenceServiceMock = new();
|
||||
private readonly Mock<ILightControlService> _lightControlServiceMock = new();
|
||||
private readonly Subject<StateChange> _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<ILogger<LightMonitorInit>>(),
|
||||
_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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -19,10 +19,9 @@ public static class LightMonitorServiceRegistration
|
||||
return services;
|
||||
}
|
||||
|
||||
services
|
||||
.AddNetDaemonApp<LightMonitorInit>()
|
||||
.AddScoped<IPresenceService, PresenceService>()
|
||||
.AddScoped<ILightControlService, LightControlService>();
|
||||
services.AddNetDaemonApp<LightMonitorInit>()
|
||||
.AddScoped<IPresenceService, PresenceService>()
|
||||
.AddScoped<ILightControlService, LightControlService>();
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
@@ -7,42 +7,32 @@ using LightMonitorManager.Models;
|
||||
|
||||
namespace LightMonitorManager;
|
||||
|
||||
public sealed class PresenceService : IPresenceService
|
||||
public sealed class PresenceService(
|
||||
IHaContext haContext,
|
||||
ILogger<PresenceService> logger,
|
||||
IOptions<LightMonitorOptions> options) : IPresenceService
|
||||
{
|
||||
private readonly IHaContext _haContext;
|
||||
private readonly ILogger<PresenceService> _logger;
|
||||
private readonly LightMonitorOptions _options;
|
||||
|
||||
public PresenceService(
|
||||
IHaContext haContext,
|
||||
ILogger<PresenceService> logger,
|
||||
IOptions<LightMonitorOptions> 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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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";
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ public class NordPoolInitTests
|
||||
private readonly Mock<INordPoolEntityService> _entityServiceMock;
|
||||
private readonly Mock<IScheduler> _schedulerMock;
|
||||
private readonly Mock<ICheapestIntervalsFinder> _cheapestIntervalsFinderMock;
|
||||
private readonly Mock<IBoilerConfigReader> _boilerConfigReaderMock;
|
||||
private readonly Mock<INordPoolBoilerConfigProvider> _boilerConfigProviderMock;
|
||||
private readonly Mock<IHaContext> _haContextMock;
|
||||
private readonly Entities _entities;
|
||||
|
||||
@@ -32,7 +32,7 @@ public class NordPoolInitTests
|
||||
_schedulerMock = new Mock<IScheduler>();
|
||||
_schedulerMock.Setup(s => s.Now).Returns(DateTimeOffset.UtcNow);
|
||||
_cheapestIntervalsFinderMock = new Mock<ICheapestIntervalsFinder>();
|
||||
_boilerConfigReaderMock = new Mock<IBoilerConfigReader>();
|
||||
_boilerConfigProviderMock = new Mock<INordPoolBoilerConfigProvider>();
|
||||
_haContextMock = new Mock<IHaContext>();
|
||||
_entities = new Entities(_haContextMock.Object);
|
||||
|
||||
@@ -51,7 +51,7 @@ public class NordPoolInitTests
|
||||
_cheapestIntervalsFinderMock
|
||||
.Setup(c => c.IsCurrentIntervalCheap(It.IsAny<IReadOnlyList<CheapestIntervalResult>>(), It.IsAny<DateTime>()))
|
||||
.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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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<int>();
|
||||
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
|
||||
|
||||
@@ -43,8 +43,6 @@ public class CheapestIntervalsFinder(ILogger<CheapestIntervalsFinder> 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;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
using BoilerMonitor.Models;
|
||||
|
||||
namespace NordPoolManager.Interface;
|
||||
|
||||
/// <summary>
|
||||
/// Supplies boiler scheduling configuration for NordPool cheapest-interval logic.
|
||||
/// </summary>
|
||||
public interface INordPoolBoilerConfigProvider
|
||||
{
|
||||
BoilerConfig GetCurrentConfiguration();
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
using BoilerMonitor.Models;
|
||||
using NordPoolManager.Interface;
|
||||
|
||||
namespace NordPoolManager;
|
||||
|
||||
/// <summary>
|
||||
/// Resolves boiler configuration from Home Assistant state for NordPool scheduling.
|
||||
/// </summary>
|
||||
public sealed class NordPoolBoilerConfigProvider(IBoilerConfigReader boilerConfigReader) : INordPoolBoilerConfigProvider
|
||||
{
|
||||
public BoilerConfig GetCurrentConfiguration() => boilerConfigReader.ReadConfig();
|
||||
}
|
||||
@@ -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)
|
||||
{
|
||||
|
||||
@@ -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<NordPoolOptions> 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)
|
||||
|
||||
@@ -29,28 +29,17 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
|
||||
if (TodayNordPoolPrice?.Prices == null || TodayNordPoolPrice.Prices.Count == 0)
|
||||
{
|
||||
logger.LogInformation("Fetching today's prices from API for CET date: {Today}", today);
|
||||
TodayNordPoolPrice = await GetNordPoolPriceAsync(today);
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.LogDebug("Using existing today's prices (already have {Count} prices)", TodayNordPoolPrice.Prices.Count);
|
||||
TodayNordPoolPrice = await FetchPricesForDateWithRetryAsync(today, "today");
|
||||
}
|
||||
|
||||
if (TomorrowNordPoolPrice?.Prices == null || TomorrowNordPoolPrice.Prices.Count == 0)
|
||||
{
|
||||
logger.LogInformation("Fetching tomorrow's prices from API for CET date: {Tomorrow}", today.AddDays(1));
|
||||
TomorrowNordPoolPrice = await GetNordPoolPriceAsync(today.AddDays(1));
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.LogDebug("Already have tomorrow's prices ({Count} prices)", TomorrowNordPoolPrice.Prices.Count);
|
||||
TomorrowNordPoolPrice = await FetchPricesForDateWithRetryAsync(today.AddDays(1), "tomorrow");
|
||||
}
|
||||
|
||||
LastUpdatedDate = DateTime.UtcNow;
|
||||
LastFetchedDate = today;
|
||||
|
||||
logger.LogInformation("Prices ready for today ({Today}). Today prices count: {TodayCount}, Tomorrow prices count: {TomorrowCount}",
|
||||
today, TodayNordPoolPrice?.Prices?.Count ?? 0, TomorrowNordPoolPrice?.Prices?.Count ?? 0);
|
||||
}
|
||||
|
||||
public double UpdateCurrentPrice()
|
||||
@@ -68,7 +57,6 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
|
||||
if (price.HasValue)
|
||||
{
|
||||
CurrentPrice = price.Value;
|
||||
logger.LogInformation("Current price updated to: {Price} for quarter index {Index}", CurrentPrice, index);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -82,8 +70,6 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
|
||||
|
||||
DayQuartersIndex = index;
|
||||
}
|
||||
|
||||
logger.LogDebug("Returning current price: {Price}", CurrentPrice);
|
||||
|
||||
return CurrentPrice;
|
||||
}
|
||||
@@ -92,22 +78,16 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
|
||||
{
|
||||
if (!LastFetchedDate.HasValue)
|
||||
{
|
||||
logger.LogDebug("No cached prices, need to fetch");
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
if (LastFetchedDate.Value < today)
|
||||
{
|
||||
logger.LogDebug("New day detected, need to fetch fresh prices");
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
if (TodayNordPoolPrice?.Prices == null || TodayNordPoolPrice.Prices.Count == 0)
|
||||
{
|
||||
logger.LogDebug("Today's prices are missing, need to fetch");
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -117,8 +97,6 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
|
||||
|
||||
if (currentHour >= 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<Nor
|
||||
|
||||
public void RollOverPrices(DateOnly today)
|
||||
{
|
||||
logger.LogInformation("New day detected in CET timezone! Rolling over tomorrow's prices to today. Previous date: {PreviousDate}, Current date: {CurrentDate}", LastFetchedDate, today);
|
||||
|
||||
if (TomorrowNordPoolPrice?.Prices is { Count: > 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<NordPoolPrice> 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<NordPoolPrice> GetNordPoolPriceAsync(DateOnly date)
|
||||
{
|
||||
var nordPoolPricesDto = await _nordPoolServices.GetPricesForDateAsync(
|
||||
@@ -160,7 +160,7 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
|
||||
});
|
||||
|
||||
var nordPoolResult = ParseNordPoolResult(nordPoolPricesDto);
|
||||
|
||||
|
||||
return AdjustedNordPoolPrice(nordPoolResult);
|
||||
}
|
||||
|
||||
@@ -211,11 +211,12 @@ public class NordPoolPriceService(Services services, IMapper mapper, ILogger<Nor
|
||||
return Math.Round(cntPrice, ConversionConsts.PriceDecimalPlaces);
|
||||
}
|
||||
|
||||
internal static int GetTimeQuarterIndex(DateTime date)
|
||||
internal static int GetTimeQuarterIndex(DateTime utcDate)
|
||||
{
|
||||
var relativeHour = (date.Hour + 1) % 24;
|
||||
var totalMinutes = (relativeHour * 60) + date.Minute;
|
||||
|
||||
return totalMinutes / 15;
|
||||
var cetTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
|
||||
var cetDate = TimeZoneInfo.ConvertTimeFromUtc(utcDate, cetTimeZone);
|
||||
var totalMinutes = (cetDate.Hour * 60) + cetDate.Minute;
|
||||
|
||||
return totalMinutes / NordPoolConsts.MinutesPerInterval;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,4 +33,14 @@ public static class NordPoolConsts
|
||||
/// Home Assistant entity id for the Nord Pool current price sensor published by this integration.
|
||||
/// </summary>
|
||||
public const string CurrentPriceEntityId = "sensor.nordpool_current_price";
|
||||
|
||||
/// <summary>
|
||||
/// Maximum number of retry attempts when fetching prices from the NordPool API.
|
||||
/// </summary>
|
||||
public const int MaxFetchRetryAttempts = 3;
|
||||
|
||||
/// <summary>
|
||||
/// Base delay in seconds between retry attempts (used with exponential backoff).
|
||||
/// </summary>
|
||||
public const int RetryBaseDelaySeconds = 5;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace PowerMonitorManager.Interface;
|
||||
|
||||
public interface IPowerNotificationService
|
||||
{
|
||||
void NotifyHighPowerUsage(double currentPowerWatts, double thresholdWatts);
|
||||
|
||||
void DismissHighPowerNotification();
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user