Compare commits
15 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f919d6b25b | |||
| 77458383d1 | |||
| 24729ee267 | |||
| cf8c9434c8 | |||
| 41ac93733e | |||
| 17774b40b8 | |||
| ada3c77778 | |||
| b5e114be14 | |||
| 5777e641f6 | |||
| 1152462765 | |||
| f0bbd4f10b | |||
| f176a1b8fc | |||
| 2706a6b188 | |||
| 7f280bea7b | |||
| e6bf8258bb |
@@ -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.
|
||||||
@@ -112,6 +112,8 @@ appsettings.*.local.json
|
|||||||
|
|
||||||
# Home Assistant long-lived tokens / per-user override files
|
# Home Assistant long-lived tokens / per-user override files
|
||||||
appsettings.development.json
|
appsettings.development.json
|
||||||
|
appsettings.Production.json
|
||||||
|
appsettings.production.json
|
||||||
|
|
||||||
# Cursor MCP config (contains secrets)
|
# Cursor MCP config (contains secrets)
|
||||||
.cursor/mcp.json
|
.cursor/mcp.json
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
{
|
||||||
|
"mcpServers": {
|
||||||
|
"UnoApp": {
|
||||||
|
"command": "dotnet",
|
||||||
|
"args": [
|
||||||
|
"dnx",
|
||||||
|
"-y",
|
||||||
|
"uno.devserver",
|
||||||
|
"--mcp-app"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"UnoDocs": {
|
||||||
|
"url": "https://mcp.platform.uno/v1"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
{
|
||||||
|
"mcpServers": {
|
||||||
|
"UnoApp": {
|
||||||
|
"command": "dotnet",
|
||||||
|
"args": [
|
||||||
|
"dnx",
|
||||||
|
"-y",
|
||||||
|
"uno.devserver",
|
||||||
|
"--mcp-app"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,196 @@
|
|||||||
|
# AGENTS.md
|
||||||
|
|
||||||
|
Compact orientation for OpenCode sessions working in this repo. Read this
|
||||||
|
before editing; it only records things that are easy to get wrong.
|
||||||
|
|
||||||
|
## 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 `&&`. On Linux/bash, `&&` is fine.
|
||||||
|
|
||||||
|
## Stack
|
||||||
|
|
||||||
|
- .NET 10 / C# 14 (`LangVersion=14.0`, set per-csproj in the three
|
||||||
|
executable projects — `HomeAssistant.Server`, `HomeAssistant.McpServer`,
|
||||||
|
`HomeAssistant.HistoryReplay`; no `Directory.Build.props`). `global.json`
|
||||||
|
pins SDK `10.0.0` with `rollForward=latestMajor` and
|
||||||
|
`allowPrerelease=true`.
|
||||||
|
- NetDaemon v5 (NuGet `26.11.0`) apps run inside `HomeAssistant.Server`, the
|
||||||
|
only host / binary-deploy target. Solution file: `HomeAssistantSDK.sln`.
|
||||||
|
- Tests: xUnit + FluentAssertions + Moq. `Microsoft.Extensions.TimeProvider.Testing`
|
||||||
|
is used for time-based tests — prefer `FakeTimeProvider` over real time.
|
||||||
|
- AutoMapper 16.1.1 is used by `HomeAssistant.Server`. **A hardcoded license key
|
||||||
|
is committed in `HomeAssistant.Server/program.cs`** — do not move it to
|
||||||
|
settings, and do not log or echo it.
|
||||||
|
|
||||||
|
## Layout (non-obvious wiring)
|
||||||
|
|
||||||
|
- Each monitor follows a fixed 3-project pattern:
|
||||||
|
- `*.Models` — entity/config interfaces, constants, enums.
|
||||||
|
- `*.Manager` — services, the `[NetDaemonApp]` entry `*Init.cs`, and
|
||||||
|
`*Options` (bound from `appsettings.json` via `IOptions<>`). Note:
|
||||||
|
`*Options` lives in `*.Manager/Models/`, **not** in the separate
|
||||||
|
`*.Models` project, for 6 of 7 monitors. Only `LightMonitor` puts
|
||||||
|
`LightMonitorOptions` in `LightMonitor.Models`.
|
||||||
|
- `*.Manager.Tests` — unit tests for the manager.
|
||||||
|
- Apps are **not** auto-discovered by the host. Each monitor exposes a
|
||||||
|
`Add<Name>Monitor(this IServiceCollection, IConfiguration)` extension in
|
||||||
|
`*ServiceRegistration.cs`; `program.cs` calls them explicitly and in a
|
||||||
|
specific order. Adding a new monitor means: create the 3 projects, add a
|
||||||
|
`*ServiceRegistration.cs`, reference the projects from
|
||||||
|
`HomeAssistant.Server`, and wire `Add<Name>` + `Configure<*Options>` in
|
||||||
|
`program.cs`. **NordPool breaks the naming convention**: its extension is
|
||||||
|
`AddNordPool`, not `AddNordPoolMonitor`. `AddNordPool` and `AddPowerMonitor`
|
||||||
|
take no `IConfiguration` parameter — neither registration reads options
|
||||||
|
(PowerMonitor checks `Enabled` inside `PowerMonitorInit` instead).
|
||||||
|
- `*ServiceRegistration.cs` honors an `Enabled` flag in the options and
|
||||||
|
no-ops (skips `AddNetDaemonApp`) when disabled — for every monitor
|
||||||
|
**except NordPool** (no `Enabled` option, always registers) and
|
||||||
|
**PowerMonitor** (registers unconditionally; `PowerMonitorInit` reads
|
||||||
|
`Enabled` itself). `PowerMonitor` ships disabled by default in
|
||||||
|
`appsettings.json`; all others ship enabled.
|
||||||
|
- `HomeAssistant.Entities` holds the **generated** `HomeAssistantGenerated`
|
||||||
|
code (entity metadata sourced from
|
||||||
|
`HomeAssistant.Server/NetDaemonCodegen/{EntityMetaData,ServicesMetaData}.json`).
|
||||||
|
`program.cs` calls `AddHomeAssistantGenerated()`; the generated entities
|
||||||
|
are transient. Do not hand-edit generated files.
|
||||||
|
- `program.cs` calls `Configure<*Options>` then `Add<Name>…` for each
|
||||||
|
monitor in this order: NordPool, Power, Boiler, Shower, Light, Battery,
|
||||||
|
Leak. Monitor service registrations (except `IBoilerConfigReader`,
|
||||||
|
`IEntityManager`, `TimeProvider.System`, which are in `program.cs`)
|
||||||
|
live inside each `*ServiceRegistration.cs`, not `program.cs`.
|
||||||
|
- `HomeAssistant.Models` is a thin shared model project (one file,
|
||||||
|
`EntityCreateModel.cs`) referenced by `HomeAssistant.Entities`. NetDaemon
|
||||||
|
MQTT extension lives here.
|
||||||
|
- `Mappings` is a class library holding AutoMapper profiles
|
||||||
|
(`GlobalMappingProfile`, `NordPoolMappingProfile` + `DateTimeTypeConverter`)
|
||||||
|
referenced by `HomeAssistant.Server`; wired in `program.cs` via
|
||||||
|
`config.AddProfile<…>()`. AutoMapper 16.1.1.
|
||||||
|
- `HomeAssistant.McpServer` is a separate stdio MCP server
|
||||||
|
(ModelContextProtocol NuGet 1.2.0) exposing HA tools. It is **not**
|
||||||
|
referenced by the host; it runs standalone via
|
||||||
|
`dotnet run --project HomeAssistant.McpServer`. It is wired as the
|
||||||
|
`homeassistant` MCP server in both `.cursor/mcp.json` (git-ignored) and
|
||||||
|
the committed `opencode.json` at the repo root.
|
||||||
|
- `HomeAssistant.HistoryReplay` is a Blazor debug web app that replays HA
|
||||||
|
history through monitor business logic with no side effects. It
|
||||||
|
references a subset of monitors (Boiler, NordPool, Power, Shower, Light —
|
||||||
|
not Battery or Leak). See its own README. Not deployed.
|
||||||
|
|
||||||
|
## Critical DI rule
|
||||||
|
|
||||||
|
NetDaemon registers `IHaContext` as **scoped**. Any service that injects
|
||||||
|
`IHaContext` (or `IMqttEntityManager`, `IEntities`, generated entity
|
||||||
|
collections) must be registered **scoped or transient**, never singleton,
|
||||||
|
or app load fails with:
|
||||||
|
`Cannot resolve scoped service … from root provider`.
|
||||||
|
|
||||||
|
Verified-livable registrations (do not regress these lifetimes; re-check
|
||||||
|
scoped dependencies if changing one):
|
||||||
|
- `Boiler`: `IBoilerMonitorEntityService` transient,
|
||||||
|
`IBoilerControlService`/`IBoilerRunTimeTracker`/`IWaterReadyService`
|
||||||
|
singleton (no HA dep), `IBoilerConfigReader` scoped (registered directly
|
||||||
|
in `program.cs`, the only monitor service outside its
|
||||||
|
`*ServiceRegistration.cs`).
|
||||||
|
- `NordPool`: `INordPoolEntityService` transient, `INordPoolPriceService`
|
||||||
|
singleton (pure state/math, no HA dep — HA fetch call lives in
|
||||||
|
`NordPoolInit`), `INordPoolBoilerConfigProvider` scoped,
|
||||||
|
`ICheapestIntervalsFinder` singleton (no HA dep).
|
||||||
|
- `Power`: `IPowerMonitorEntityService` + `IPowerNotificationService`
|
||||||
|
transient, `IPowerSensorDiscoveryService` scoped. `IOtherPowerCalculationService`
|
||||||
|
+ `IPowerCostCalculationService` are singleton (pure calc, no HA dep).
|
||||||
|
- `Shower`: `IExhaustFanControlService` scoped,
|
||||||
|
`IShowerMonitorEntityService` transient, `IShowerDetectionService` +
|
||||||
|
`IHumidityRateCalculator` singleton (no HA dep).
|
||||||
|
- `Light`: `IPresenceService` + `ILightControlService` scoped.
|
||||||
|
- `Battery`: `IBatterySensorDiscoveryService` +
|
||||||
|
`IBatteryNotificationService` scoped.
|
||||||
|
- `Leak`: `ILeakNotificationService` scoped.
|
||||||
|
- `IEntityManager` is transient in `program.cs`.
|
||||||
|
|
||||||
|
Singletons are only safe for services that take **no** scoped dependency
|
||||||
|
(pure calculators, trackers with no `IHaContext`). When unsure, register
|
||||||
|
scoped.
|
||||||
|
|
||||||
|
## Live validation after monitor edits
|
||||||
|
|
||||||
|
`.cursor/rules/live-validation.mdc` (globs: all `*.Manager`/`*.Models` of
|
||||||
|
Boiler, Light, NordPool, Power, Shower, plus `HomeAssistant.McpServer` —
|
||||||
|
**not** Battery or Leak) requires, after editing monitor runtime code:
|
||||||
|
|
||||||
|
1. `dotnet build` the affected project.
|
||||||
|
2. `RunSmokeTest` MCP tool from the `homeassistant` MCP server.
|
||||||
|
3. `ValidateEntities` for the changed service's critical entities.
|
||||||
|
|
||||||
|
Domain → entity mapping is in the rule file. Skip when HA is offline (check
|
||||||
|
via `check_api`), when changes are tests/docs/non-runtime, or when the user
|
||||||
|
says to skip. On failure, report the failing entities + states; do not
|
||||||
|
silently proceed. This rule is Cursor-specific but the intent applies to
|
||||||
|
OpenCode sessions too — if you have the `homeassistant` MCP server
|
||||||
|
available, follow the same flow.
|
||||||
|
|
||||||
|
## Commands
|
||||||
|
|
||||||
|
Build everything:
|
||||||
|
```
|
||||||
|
dotnet build HomeAssistantSDK.sln
|
||||||
|
```
|
||||||
|
Run all tests:
|
||||||
|
```
|
||||||
|
dotnet test HomeAssistantSDK.sln
|
||||||
|
```
|
||||||
|
Single test project / class / test:
|
||||||
|
```
|
||||||
|
dotnet test BoilerMonitor.Manager.Tests
|
||||||
|
dotnet test BoilerMonitor.Manager.Tests --filter "FullyQualifiedName~BoilerControlServiceTests"
|
||||||
|
dotnet test BoilerMonitor.Manager.Tests --filter "FullyQualifiedName~BoilerControlServiceTests.TurnsOnWhenCheap"
|
||||||
|
```
|
||||||
|
Run the host (needs HA reachable + token in `appsettings.Development.json`):
|
||||||
|
```
|
||||||
|
dotnet run --project HomeAssistant.Server
|
||||||
|
```
|
||||||
|
Run the MCP server standalone:
|
||||||
|
```
|
||||||
|
dotnet run --project HomeAssistant.McpServer
|
||||||
|
```
|
||||||
|
Run the history replay web app:
|
||||||
|
```
|
||||||
|
dotnet run --project HomeAssistant.HistoryReplay
|
||||||
|
```
|
||||||
|
Deploy the host: publish `HomeAssistant.Server` self-contained and copy the
|
||||||
|
output to `/config/netdaemon4` (the NetDaemon add-on folder). The csproj
|
||||||
|
prints the reminder after publish.
|
||||||
|
|
||||||
|
## Configuration & secrets
|
||||||
|
|
||||||
|
- Monitor options live under per-monitor sections in `HomeAssistant.Server/appsettings.json`
|
||||||
|
(e.g. `BoilerMonitor`, `ShowerMonitor`, `LightMonitor`, `BatteryMonitor`,
|
||||||
|
`LeakMonitor`, `PowerMonitor`, `NordPool`). Each `*Options` class has a
|
||||||
|
`SectionName` const used by both `program.cs` and `*ServiceRegistration`.
|
||||||
|
- `appsettings.Development.json` / `appsettings.*.local.json` are git-ignored
|
||||||
|
across the repo — put tokens and local overrides there. Nested keys can
|
||||||
|
be set via env vars using `__` as the separator.
|
||||||
|
- Never commit HA long-lived access tokens.
|
||||||
|
|
||||||
|
## Gotchas
|
||||||
|
|
||||||
|
- Monitor `*Options` are bound **twice**: once in `program.cs`
|
||||||
|
(`Configure<*Options>`) and once inside `*ServiceRegistration` (which reads
|
||||||
|
them again to check `Enabled` and to seed stateless singletons like
|
||||||
|
`HumidityRateCalculator`). Keep both in sync when changing option names.
|
||||||
|
- `HomeAssistant.Server` references every monitor's `*.Manager` and
|
||||||
|
`*.Models` projects directly; `HomeAssistant.HistoryReplay` references a
|
||||||
|
subset (Boiler, NordPool, Power, Shower, Light). Adding a monitor to the
|
||||||
|
replay tool requires a new project reference there too.
|
||||||
|
- The repository folder name is misspelled `homeassistant-app-deamon`
|
||||||
|
(should be `daemon`). This is intentional/legacy — do not "fix" it in
|
||||||
|
paths; `opencode.json` and `.cursor/mcp.json` reference the workspace
|
||||||
|
folder by macro.
|
||||||
|
- Stale untracked folders `NordPool.Comminication/` and
|
||||||
|
`HomeAssistant.Infrastructure/` may appear on disk containing only
|
||||||
|
`obj/` build cruft. They are **not** in the solution, not committed to
|
||||||
|
git, and not referenced by any project. Do not treat them as real
|
||||||
|
projects; safe to delete.
|
||||||
@@ -8,27 +8,27 @@
|
|||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="coverlet.collector" Version="8.0.0">
|
<PackageReference Include="coverlet.collector" Version="10.1.1">
|
||||||
<PrivateAssets>all</PrivateAssets>
|
<PrivateAssets>all</PrivateAssets>
|
||||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
</PackageReference>
|
</PackageReference>
|
||||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.3.0" />
|
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.12.0"/>
|
||||||
<PackageReference Include="xunit" Version="2.9.3" />
|
<PackageReference Include="xunit" Version="2.9.3"/>
|
||||||
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5">
|
<PackageReference Include="xunit.runner.visualstudio" Version="4.0.1">
|
||||||
<PrivateAssets>all</PrivateAssets>
|
<PrivateAssets>all</PrivateAssets>
|
||||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
</PackageReference>
|
</PackageReference>
|
||||||
<PackageReference Include="FluentAssertions" Version="8.8.0" />
|
<PackageReference Include="FluentAssertions" Version="8.11.0"/>
|
||||||
<PackageReference Include="Moq" Version="4.20.72" />
|
<PackageReference Include="Moq" Version="4.21.0"/>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<Using Include="Xunit" />
|
<Using Include="Xunit"/>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\BatteryMonitor.Manager\BatteryMonitor.Manager.csproj" />
|
<ProjectReference Include="..\BatteryMonitor.Manager\BatteryMonitor.Manager.csproj"/>
|
||||||
<ProjectReference Include="..\BatteryMonitor.Models\BatteryMonitor.Models.csproj" />
|
<ProjectReference Include="..\BatteryMonitor.Models\BatteryMonitor.Models.csproj"/>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
@@ -0,0 +1,242 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using System.Globalization;
|
||||||
|
using System.Text.Json;
|
||||||
|
using BatteryMonitor.Models;
|
||||||
|
using Moq;
|
||||||
|
using NetDaemon.HassModel;
|
||||||
|
using NetDaemon.HassModel.Entities;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace BatteryMonitor.Manager.Tests;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Shared, deterministic builders and datasets used by the BatteryMonitor tests.
|
||||||
|
/// Keeping entity/state construction and generated inputs here means the test
|
||||||
|
/// classes only describe the scenario under test.
|
||||||
|
/// </summary>
|
||||||
|
internal static class BatteryMonitorTestData
|
||||||
|
{
|
||||||
|
private const string DefaultFriendlyName = "Battery Device";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// (threshold, state, expected) rows straddling the strict <c>level < threshold</c>
|
||||||
|
/// boundary, including zero/negative thresholds and int min/max thresholds.
|
||||||
|
/// </summary>
|
||||||
|
public static TheoryData<int, string, bool> ThresholdBoundaryRows { get; } = new TheoryData<int, string, bool>
|
||||||
|
{
|
||||||
|
{ 5, "4", true },
|
||||||
|
{ 5, "5", false },
|
||||||
|
{ 5, "6", false },
|
||||||
|
{ 5, "0", true },
|
||||||
|
{ 5, "-3", true },
|
||||||
|
{ 5, "4.9", true },
|
||||||
|
{ 5, "5.0", false },
|
||||||
|
{ 5, "100", false },
|
||||||
|
{ 1, "0.5", true },
|
||||||
|
{ 1, "1", false },
|
||||||
|
{ 20, "19", true },
|
||||||
|
{ 20, "19.99", true },
|
||||||
|
{ 20, "20", false },
|
||||||
|
{ 0, "-1", true },
|
||||||
|
{ 0, "0", false },
|
||||||
|
{ 0, "1", false },
|
||||||
|
{ -5, "-6", true },
|
||||||
|
{ -5, "-5", false },
|
||||||
|
{ -5, "-4", false },
|
||||||
|
{ 100, "99.9", true },
|
||||||
|
{ 100, "100", false },
|
||||||
|
{ 101, "100", true },
|
||||||
|
{ int.MaxValue, "100", true },
|
||||||
|
{ int.MinValue, "-2147483648", false },
|
||||||
|
{ int.MinValue, "-2147483649", true }
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// States that must never produce a <see cref="BatterySensorInfo" />, including
|
||||||
|
/// whitespace/malformed strings and a null state.
|
||||||
|
/// </summary>
|
||||||
|
public static TheoryData<string?> UnusableStateRows { get; } =
|
||||||
|
[
|
||||||
|
"unavailable",
|
||||||
|
"unknown",
|
||||||
|
"UNAVAILABLE",
|
||||||
|
"UNKNOWN",
|
||||||
|
string.Empty,
|
||||||
|
" ",
|
||||||
|
"\t",
|
||||||
|
"not_a_number",
|
||||||
|
"3%",
|
||||||
|
"--1",
|
||||||
|
"low",
|
||||||
|
"1 2",
|
||||||
|
null
|
||||||
|
];
|
||||||
|
|
||||||
|
/// <summary>Device counts used to exercise notification payload generation.</summary>
|
||||||
|
public static TheoryData<int> NotifyDeviceCounts { get; } = [1, 2, 3, 5, 10, 50];
|
||||||
|
|
||||||
|
/// <summary>A battery device-class sensor.</summary>
|
||||||
|
public static EntitySpec Battery(string entityId, string? state, string? friendlyName = DefaultFriendlyName)
|
||||||
|
{
|
||||||
|
return new EntitySpec
|
||||||
|
{
|
||||||
|
EntityId = entityId,
|
||||||
|
State = state,
|
||||||
|
FriendlyName = friendlyName
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A sensor with an arbitrary (or missing) device class.</summary>
|
||||||
|
public static EntitySpec Sensor(string entityId,
|
||||||
|
string? deviceClass,
|
||||||
|
string? state,
|
||||||
|
string? friendlyName = DefaultFriendlyName)
|
||||||
|
{
|
||||||
|
return new EntitySpec
|
||||||
|
{
|
||||||
|
EntityId = entityId,
|
||||||
|
DeviceClass = deviceClass,
|
||||||
|
State = state,
|
||||||
|
FriendlyName = friendlyName
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static EntityState CreateEntityState(EntitySpec spec)
|
||||||
|
{
|
||||||
|
var attributes = new Dictionary<string, object?>(StringComparer.Ordinal);
|
||||||
|
|
||||||
|
if (spec.DeviceClass is not null)
|
||||||
|
{
|
||||||
|
attributes["device_class"] = spec.DeviceClass;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (spec.FriendlyName is not null)
|
||||||
|
{
|
||||||
|
attributes["friendly_name"] = spec.FriendlyName;
|
||||||
|
}
|
||||||
|
|
||||||
|
return new EntityState
|
||||||
|
{
|
||||||
|
State = spec.State,
|
||||||
|
AttributesJson = JsonSerializer.SerializeToElement(attributes)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Wires <see cref="IHaContext.GetState" /> and <see cref="IHaContext.GetAllEntities" />
|
||||||
|
/// on the mock, exposing the entities in declaration order.
|
||||||
|
/// </summary>
|
||||||
|
public static void ConfigureHaContext(Mock<IHaContext> haContextMock, params EntitySpec[] entities)
|
||||||
|
{
|
||||||
|
var entityList = new List<Entity>(entities.Length);
|
||||||
|
|
||||||
|
foreach (var spec in entities)
|
||||||
|
{
|
||||||
|
if (spec.HasState)
|
||||||
|
{
|
||||||
|
haContextMock.Setup(h => h.GetState(spec.EntityId)).Returns(CreateEntityState(spec));
|
||||||
|
}
|
||||||
|
|
||||||
|
entityList.Add(new Entity(haContextMock.Object, spec.EntityId));
|
||||||
|
}
|
||||||
|
|
||||||
|
haContextMock.Setup(h => h.GetAllEntities()).Returns(entityList);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static BatterySensorInfo CreateSensorInfo(string entityId, double batteryLevel, string? friendlyName = null)
|
||||||
|
{
|
||||||
|
return new BatterySensorInfo
|
||||||
|
{
|
||||||
|
EntityId = entityId,
|
||||||
|
FriendlyName = friendlyName ?? entityId,
|
||||||
|
BatteryLevel = batteryLevel
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<BatterySensorInfo> CreateSensorInfos(params (string EntityId, double BatteryLevel)[] sensors)
|
||||||
|
{
|
||||||
|
return [.. sensors.Select(s => CreateSensorInfo(s.EntityId, s.BatteryLevel))];
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<BatterySensorInfo> CreateSensorInfos(
|
||||||
|
params (string EntityId, string FriendlyName, double BatteryLevel)[] sensors)
|
||||||
|
{
|
||||||
|
return [.. sensors.Select(s => CreateSensorInfo(s.EntityId, s.BatteryLevel, s.FriendlyName))];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Generates battery sensors with every integer level in <c>0..count-1</c>.
|
||||||
|
/// </summary>
|
||||||
|
public static EntitySpec[] CreateGeneratedBatteryEntities(int count)
|
||||||
|
{
|
||||||
|
return
|
||||||
|
[
|
||||||
|
.. Enumerable.Range(0, count)
|
||||||
|
.Select(i => Battery(
|
||||||
|
$"sensor.generated_battery_{i:D3}",
|
||||||
|
i.ToString(CultureInfo.InvariantCulture),
|
||||||
|
$"Generated Battery {i:D3}"))
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Generates notification devices with deterministic, non-monotonic levels so
|
||||||
|
/// ordering behaviour is exercised over more than a handful of rows.
|
||||||
|
/// </summary>
|
||||||
|
public static IReadOnlyList<BatterySensorInfo> CreateGeneratedSensorInfos(int count)
|
||||||
|
{
|
||||||
|
return
|
||||||
|
[
|
||||||
|
.. Enumerable.Range(0, count)
|
||||||
|
.Select(i => CreateSensorInfo(
|
||||||
|
$"sensor.generated_{i:D3}",
|
||||||
|
i * 37 % 101,
|
||||||
|
$"Generated Device {i:D3}"))
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Cross-product of every excluded keyword (lower and upper case) plus
|
||||||
|
/// non-excluded look-alikes that must not be filtered.
|
||||||
|
/// </summary>
|
||||||
|
public static TheoryData<string, bool> ExcludedEntityIdRows()
|
||||||
|
{
|
||||||
|
var data = new TheoryData<string, bool>();
|
||||||
|
|
||||||
|
foreach (var keyword in BatteryMonitorConsts.ExcludedKeywords)
|
||||||
|
{
|
||||||
|
data.Add($"sensor.my_{keyword}_battery_level", true);
|
||||||
|
data.Add($"SENSOR.MY_{keyword.ToUpperInvariant()}_BATTERY_LEVEL", true);
|
||||||
|
}
|
||||||
|
|
||||||
|
data.Add("sensor.iphone", true);
|
||||||
|
data.Add("sensor.x_phone_x", true);
|
||||||
|
data.Add("sensor.bathroom_battery", false);
|
||||||
|
data.Add("sensor.boiler_temp_battery", false);
|
||||||
|
data.Add("sensor.aquarium_leak_sensor_battery", false);
|
||||||
|
data.Add("sensor.temperature", false);
|
||||||
|
data.Add(string.Empty, false);
|
||||||
|
data.Add(" ", false);
|
||||||
|
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Describes one entity exposed through <see cref="IHaContext.GetAllEntities" />.
|
||||||
|
/// </summary>
|
||||||
|
public sealed record EntitySpec
|
||||||
|
{
|
||||||
|
public required string EntityId { get; init; }
|
||||||
|
|
||||||
|
public string? State { get; init; } = "50";
|
||||||
|
|
||||||
|
public string? DeviceClass { get; init; } = BatteryMonitorConsts.BatteryDeviceClass;
|
||||||
|
|
||||||
|
public string? FriendlyName { get; init; } = DefaultFriendlyName;
|
||||||
|
|
||||||
|
/// <summary>When false the context returns no <see cref="EntityState" /> for the entity.</summary>
|
||||||
|
public bool HasState { get; init; } = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,54 +1,65 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using System.Text.Json;
|
||||||
|
using BatteryMonitor.Models;
|
||||||
|
using BatteryMonitorManager;
|
||||||
using FluentAssertions;
|
using FluentAssertions;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using Moq;
|
using Moq;
|
||||||
using NetDaemon.HassModel;
|
using NetDaemon.HassModel;
|
||||||
using NetDaemon.HassModel.Entities;
|
using NetDaemon.HassModel.Entities;
|
||||||
using BatteryMonitor.Models;
|
using static BatteryMonitor.Manager.Tests.BatteryMonitorTestData;
|
||||||
using BatteryMonitorManager;
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace BatteryMonitor.Manager.Tests;
|
namespace BatteryMonitor.Manager.Tests;
|
||||||
|
|
||||||
public class BatteryNotificationServiceTests
|
public class BatteryNotificationServiceTests
|
||||||
{
|
{
|
||||||
private readonly Mock<IHaContext> _haContextMock;
|
private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
|
||||||
private readonly Mock<ILogger<BatteryNotificationService>> _loggerMock;
|
private readonly Mock<ILogger<BatteryNotificationService>> _loggerMock = new Mock<ILogger<BatteryNotificationService>>();
|
||||||
|
|
||||||
public BatteryNotificationServiceTests()
|
|
||||||
{
|
|
||||||
_haContextMock = new Mock<IHaContext>();
|
|
||||||
_loggerMock = new Mock<ILogger<BatteryNotificationService>>();
|
|
||||||
}
|
|
||||||
|
|
||||||
private BatteryNotificationService CreateSut()
|
private BatteryNotificationService CreateSut()
|
||||||
{
|
{
|
||||||
return new BatteryNotificationService(_haContextMock.Object, _loggerMock.Object);
|
return new BatteryNotificationService(_haContextMock.Object, _loggerMock.Object);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void VerifyCallService(string service, Times times)
|
||||||
|
{
|
||||||
|
_haContextMock.Verify(h => h.CallService(
|
||||||
|
BatteryMonitorConsts.PersistentNotificationDomain,
|
||||||
|
service,
|
||||||
|
It.IsAny<ServiceTarget?>(),
|
||||||
|
It.IsAny<object?>()), times);
|
||||||
|
}
|
||||||
|
|
||||||
#region NotifyLowBattery
|
#region NotifyLowBattery
|
||||||
|
|
||||||
[Fact]
|
[Theory]
|
||||||
public void NotifyLowBattery_WithDevices_ShouldCallPersistentNotificationCreate()
|
[MemberData(nameof(NotifyDeviceCounts), MemberType = typeof(BatteryMonitorTestData))]
|
||||||
|
public void NotifyLowBattery_WithDevices_ShouldCallPersistentNotificationCreate(int deviceCount)
|
||||||
{
|
{
|
||||||
var devices = new List<BatterySensorInfo>
|
var devices = CreateSensorInfos(
|
||||||
{
|
[
|
||||||
new() { EntityId = "sensor.bathroom_battery", FriendlyName = "Bathroom Battery", BatteryLevel = 3 },
|
.. Enumerable.Range(0, deviceCount)
|
||||||
new() { EntityId = "sensor.bedroom_battery", FriendlyName = "Bedroom Battery", BatteryLevel = 1 }
|
.Select(i => ($"sensor.device_{i:D3}", $"Device {i:D3}", (double)(i % 5)))
|
||||||
};
|
]);
|
||||||
|
|
||||||
var sut = CreateSut();
|
var sut = CreateSut();
|
||||||
sut.NotifyLowBattery(devices);
|
sut.NotifyLowBattery(devices);
|
||||||
|
|
||||||
_haContextMock.Verify(h => h.CallService(
|
VerifyCallService(BatteryMonitorConsts.PersistentNotificationCreateService, Times.Once());
|
||||||
BatteryMonitorConsts.PersistentNotificationDomain,
|
VerifyCallService(BatteryMonitorConsts.PersistentNotificationDismissService, Times.Never());
|
||||||
BatteryMonitorConsts.PersistentNotificationCreateService,
|
|
||||||
It.IsAny<ServiceTarget?>(),
|
|
||||||
It.IsAny<object?>()), Times.Once);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Theory]
|
||||||
public void NotifyLowBattery_WithEmptyList_ShouldNotCallService()
|
[InlineData(false)]
|
||||||
|
[InlineData(true)]
|
||||||
|
public void NotifyLowBattery_WithEmptyList_ShouldNotCallService(bool useArray)
|
||||||
{
|
{
|
||||||
var devices = new List<BatterySensorInfo>();
|
IReadOnlyList<BatterySensorInfo> devices = useArray
|
||||||
|
? Array.Empty<BatterySensorInfo>()
|
||||||
|
: new List<BatterySensorInfo>();
|
||||||
|
|
||||||
var sut = CreateSut();
|
var sut = CreateSut();
|
||||||
sut.NotifyLowBattery(devices);
|
sut.NotifyLowBattery(devices);
|
||||||
@@ -58,6 +69,62 @@ public class BatteryNotificationServiceTests
|
|||||||
It.IsAny<string>(),
|
It.IsAny<string>(),
|
||||||
It.IsAny<ServiceTarget?>(),
|
It.IsAny<ServiceTarget?>(),
|
||||||
It.IsAny<object?>()), Times.Never);
|
It.IsAny<object?>()), Times.Never);
|
||||||
|
|
||||||
|
_loggerMock.Invocations.Should().BeEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void NotifyLowBattery_ShouldSendTitleNotificationIdAndDeviceSummary()
|
||||||
|
{
|
||||||
|
object? payload = null;
|
||||||
|
|
||||||
|
_haContextMock
|
||||||
|
.Setup(h => h.CallService(
|
||||||
|
BatteryMonitorConsts.PersistentNotificationDomain,
|
||||||
|
BatteryMonitorConsts.PersistentNotificationCreateService,
|
||||||
|
It.IsAny<ServiceTarget?>(),
|
||||||
|
It.IsAny<object?>()))
|
||||||
|
.Callback<string, string, ServiceTarget?, object?>((_, _, _, data) => payload = data);
|
||||||
|
|
||||||
|
var sut = CreateSut();
|
||||||
|
|
||||||
|
sut.NotifyLowBattery(CreateSensorInfos(
|
||||||
|
("sensor.a", "Device A", 4),
|
||||||
|
("sensor.b", "Device B", 1)));
|
||||||
|
|
||||||
|
payload.Should().NotBeNull();
|
||||||
|
|
||||||
|
using var document = JsonDocument.Parse(JsonSerializer.Serialize(payload));
|
||||||
|
var root = document.RootElement;
|
||||||
|
root.GetProperty("title").GetString().Should().Be(BatteryMonitorConsts.NotificationTitle);
|
||||||
|
root.GetProperty("notification_id").GetString().Should().Be(BatteryMonitorConsts.NotificationId);
|
||||||
|
|
||||||
|
var message = root.GetProperty("message").GetString();
|
||||||
|
message.Should().Contain("Device A").And.Contain("Device B");
|
||||||
|
message.Should().Contain("1%").And.Contain("4%");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void NotifyLowBattery_WithDevices_ShouldLogDeviceCount()
|
||||||
|
{
|
||||||
|
_loggerMock.Setup(l => l.IsEnabled(LogLevel.Information)).Returns(true);
|
||||||
|
|
||||||
|
var devices = CreateSensorInfos(
|
||||||
|
("sensor.a", "Device A", 2),
|
||||||
|
("sensor.b", "Device B", 3));
|
||||||
|
|
||||||
|
var sut = CreateSut();
|
||||||
|
sut.NotifyLowBattery(devices);
|
||||||
|
|
||||||
|
var logInvocation = _loggerMock.Invocations
|
||||||
|
.Where(invocation => invocation.Method.Name == nameof(ILogger.Log))
|
||||||
|
.Should()
|
||||||
|
.ContainSingle()
|
||||||
|
.Subject;
|
||||||
|
|
||||||
|
logInvocation.Arguments[0].Should().Be(LogLevel.Information);
|
||||||
|
logInvocation.Arguments[2].Should().NotBeNull();
|
||||||
|
logInvocation.Arguments[2]!.ToString().Should().Be("Sent low battery notification for 2 device(s)");
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
@@ -70,11 +137,25 @@ public class BatteryNotificationServiceTests
|
|||||||
var sut = CreateSut();
|
var sut = CreateSut();
|
||||||
sut.DismissNotification();
|
sut.DismissNotification();
|
||||||
|
|
||||||
_haContextMock.Verify(h => h.CallService(
|
VerifyCallService(BatteryMonitorConsts.PersistentNotificationDismissService, Times.Once());
|
||||||
BatteryMonitorConsts.PersistentNotificationDomain,
|
VerifyCallService(BatteryMonitorConsts.PersistentNotificationCreateService, Times.Never());
|
||||||
BatteryMonitorConsts.PersistentNotificationDismissService,
|
}
|
||||||
It.IsAny<ServiceTarget?>(),
|
|
||||||
It.IsAny<object?>()), Times.Once);
|
[Theory]
|
||||||
|
[InlineData(1)]
|
||||||
|
[InlineData(2)]
|
||||||
|
[InlineData(5)]
|
||||||
|
public void DismissNotification_WhenCalledRepeatedly_ShouldDismissEachTime(int calls)
|
||||||
|
{
|
||||||
|
var sut = CreateSut();
|
||||||
|
|
||||||
|
for (var i = 0; i < calls; i++)
|
||||||
|
{
|
||||||
|
sut.DismissNotification();
|
||||||
|
}
|
||||||
|
|
||||||
|
VerifyCallService(BatteryMonitorConsts.PersistentNotificationDismissService, Times.Exactly(calls));
|
||||||
|
VerifyCallService(BatteryMonitorConsts.PersistentNotificationCreateService, Times.Never());
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
@@ -84,41 +165,90 @@ public class BatteryNotificationServiceTests
|
|||||||
[Fact]
|
[Fact]
|
||||||
public void BuildNotificationMessage_ShouldOrderByBatteryLevel()
|
public void BuildNotificationMessage_ShouldOrderByBatteryLevel()
|
||||||
{
|
{
|
||||||
var devices = new List<BatterySensorInfo>
|
var devices = CreateSensorInfos(
|
||||||
{
|
("sensor.a", "Device A", 4),
|
||||||
new() { EntityId = "sensor.a", FriendlyName = "Device A", BatteryLevel = 4 },
|
("sensor.b", "Device B", 1),
|
||||||
new() { EntityId = "sensor.b", FriendlyName = "Device B", BatteryLevel = 1 },
|
("sensor.c", "Device C", 3));
|
||||||
new() { EntityId = "sensor.c", FriendlyName = "Device C", BatteryLevel = 3 }
|
|
||||||
};
|
|
||||||
|
|
||||||
var message = BatteryNotificationService.BuildNotificationMessage(devices);
|
var message = BatteryNotificationService.BuildNotificationMessage(devices);
|
||||||
|
|
||||||
var lines = message.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries);
|
var lines = message.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries);
|
||||||
|
lines.Should().HaveCount(4);
|
||||||
lines[1].Should().Contain("Device B");
|
lines[1].Should().Contain("Device B");
|
||||||
lines[2].Should().Contain("Device C");
|
lines[2].Should().Contain("Device C");
|
||||||
lines[3].Should().Contain("Device A");
|
lines[3].Should().Contain("Device A");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void BuildNotificationMessage_ShouldKeepInsertionOrderForEqualLevels()
|
||||||
|
{
|
||||||
|
var devices = CreateSensorInfos(
|
||||||
|
("sensor.first", "First Device", 4),
|
||||||
|
("sensor.second", "Second Device", 4),
|
||||||
|
("sensor.third", "Third Device", 1));
|
||||||
|
|
||||||
|
var message = BatteryNotificationService.BuildNotificationMessage(devices);
|
||||||
|
|
||||||
|
var lines = message.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries);
|
||||||
|
lines.Should().HaveCount(4);
|
||||||
|
lines[1].Should().Contain("Third Device");
|
||||||
|
lines[2].Should().Contain("First Device");
|
||||||
|
lines[3].Should().Contain("Second Device");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void BuildNotificationMessage_WithGeneratedDevices_ShouldOrderByAscendingLevel()
|
||||||
|
{
|
||||||
|
var devices = CreateGeneratedSensorInfos(50);
|
||||||
|
|
||||||
|
var message = BatteryNotificationService.BuildNotificationMessage(devices);
|
||||||
|
|
||||||
|
var expectedLines = devices
|
||||||
|
.OrderBy(d => d.BatteryLevel)
|
||||||
|
.Select(d => $"- **{d.FriendlyName}**: {d.BatteryLevel:F0}%");
|
||||||
|
|
||||||
|
var lines = message.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries);
|
||||||
|
lines.Should().HaveCount(devices.Count + 1);
|
||||||
|
lines.Skip(1).Should().Equal(expectedLines);
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void BuildNotificationMessage_ShouldContainTitle()
|
public void BuildNotificationMessage_ShouldContainTitle()
|
||||||
{
|
{
|
||||||
var devices = new List<BatterySensorInfo>
|
var devices = CreateSensorInfos(("sensor.a", "Device A", 2));
|
||||||
{
|
|
||||||
new() { EntityId = "sensor.a", FriendlyName = "Device A", BatteryLevel = 2 }
|
|
||||||
};
|
|
||||||
|
|
||||||
var message = BatteryNotificationService.BuildNotificationMessage(devices);
|
var message = BatteryNotificationService.BuildNotificationMessage(devices);
|
||||||
|
|
||||||
message.Should().Contain("low battery");
|
message.Should().Contain("low battery");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("Bathroom Battery", 3, "- **Bathroom Battery**: 3%")]
|
||||||
|
[InlineData("Test Device", 1, "- **Test Device**: 1%")]
|
||||||
|
[InlineData("Empty Battery", 0, "- **Empty Battery**: 0%")]
|
||||||
|
[InlineData("Negative Battery", -7, "- **Negative Battery**: -7%")]
|
||||||
|
[InlineData("Rounded Down", 12.4, "- **Rounded Down**: 12%")]
|
||||||
|
[InlineData("Rounded Up", 12.6, "- **Rounded Up**: 13%")]
|
||||||
|
[InlineData("Full Battery", 100, "- **Full Battery**: 100%")]
|
||||||
|
[InlineData("", 5, "- ****: 5%")]
|
||||||
|
[InlineData(" ", 4, "- ** **: 4%")]
|
||||||
|
public void BuildNotificationMessage_ShouldFormatDeviceLine(string friendlyName,
|
||||||
|
double batteryLevel,
|
||||||
|
string expectedLine)
|
||||||
|
{
|
||||||
|
var devices = CreateSensorInfos(("sensor.a", friendlyName, batteryLevel));
|
||||||
|
|
||||||
|
var message = BatteryNotificationService.BuildNotificationMessage(devices);
|
||||||
|
|
||||||
|
var lines = message.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries);
|
||||||
|
lines.Should().HaveCount(2);
|
||||||
|
lines[1].Should().Be(expectedLine);
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void BuildNotificationMessage_ShouldContainDeviceNameAndLevel()
|
public void BuildNotificationMessage_ShouldContainDeviceNameAndLevel()
|
||||||
{
|
{
|
||||||
var devices = new List<BatterySensorInfo>
|
var devices = CreateSensorInfos(("sensor.a", "Bathroom Battery", 3));
|
||||||
{
|
|
||||||
new() { EntityId = "sensor.a", FriendlyName = "Bathroom Battery", BatteryLevel = 3 }
|
|
||||||
};
|
|
||||||
|
|
||||||
var message = BatteryNotificationService.BuildNotificationMessage(devices);
|
var message = BatteryNotificationService.BuildNotificationMessage(devices);
|
||||||
|
|
||||||
@@ -129,15 +259,36 @@ public class BatteryNotificationServiceTests
|
|||||||
[Fact]
|
[Fact]
|
||||||
public void BuildNotificationMessage_WithSingleDevice_ShouldFormatCorrectly()
|
public void BuildNotificationMessage_WithSingleDevice_ShouldFormatCorrectly()
|
||||||
{
|
{
|
||||||
var devices = new List<BatterySensorInfo>
|
var devices = CreateSensorInfos(("sensor.a", "Test Device", 1));
|
||||||
{
|
|
||||||
new() { EntityId = "sensor.a", FriendlyName = "Test Device", BatteryLevel = 1 }
|
|
||||||
};
|
|
||||||
|
|
||||||
var message = BatteryNotificationService.BuildNotificationMessage(devices);
|
var message = BatteryNotificationService.BuildNotificationMessage(devices);
|
||||||
|
|
||||||
message.Should().Contain("- **Test Device**: 1%");
|
message.Should().Contain("- **Test Device**: 1%");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void BuildNotificationMessage_WithDuplicateDevices_ShouldListEveryDevice()
|
||||||
|
{
|
||||||
|
var devices = CreateSensorInfos(
|
||||||
|
("sensor.duplicate_battery", "Duplicate Battery", 2),
|
||||||
|
("sensor.duplicate_battery", "Duplicate Battery", 2));
|
||||||
|
|
||||||
|
var message = BatteryNotificationService.BuildNotificationMessage(devices);
|
||||||
|
|
||||||
|
var lines = message.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries);
|
||||||
|
lines.Should().HaveCount(3);
|
||||||
|
lines[1].Should().Be("- **Duplicate Battery**: 2%");
|
||||||
|
lines[2].Should().Be("- **Duplicate Battery**: 2%");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void BuildNotificationMessage_WithNoDevices_ShouldContainOnlyHeader()
|
||||||
|
{
|
||||||
|
var message = BatteryNotificationService.BuildNotificationMessage([]);
|
||||||
|
|
||||||
|
message.Should().Be("The following devices have low battery:");
|
||||||
|
message.Should().NotContain("- **");
|
||||||
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
}
|
}
|
||||||
@@ -1,58 +1,44 @@
|
|||||||
using System.Text.Json;
|
#region
|
||||||
|
|
||||||
|
using System.Globalization;
|
||||||
|
using BatteryMonitor.Models;
|
||||||
|
using BatteryMonitorManager;
|
||||||
using FluentAssertions;
|
using FluentAssertions;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using Moq;
|
using Moq;
|
||||||
using NetDaemon.HassModel;
|
using NetDaemon.HassModel;
|
||||||
using NetDaemon.HassModel.Entities;
|
using NetDaemon.HassModel.Entities;
|
||||||
using BatteryMonitorManager;
|
using static BatteryMonitor.Manager.Tests.BatteryMonitorTestData;
|
||||||
using BatteryMonitor.Models;
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace BatteryMonitor.Manager.Tests;
|
namespace BatteryMonitor.Manager.Tests;
|
||||||
|
|
||||||
public class BatterySensorDiscoveryServiceTests
|
public class BatterySensorDiscoveryServiceTests
|
||||||
{
|
{
|
||||||
private readonly Mock<IHaContext> _haContextMock;
|
private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
|
||||||
private readonly Mock<ILogger<BatterySensorDiscoveryService>> _loggerMock;
|
private readonly Mock<ILogger<BatterySensorDiscoveryService>> _loggerMock = new Mock<ILogger<BatterySensorDiscoveryService>>();
|
||||||
|
|
||||||
public BatterySensorDiscoveryServiceTests()
|
|
||||||
{
|
|
||||||
_haContextMock = new Mock<IHaContext>();
|
|
||||||
_loggerMock = new Mock<ILogger<BatterySensorDiscoveryService>>();
|
|
||||||
}
|
|
||||||
|
|
||||||
private BatterySensorDiscoveryService CreateSut()
|
private BatterySensorDiscoveryService CreateSut()
|
||||||
{
|
{
|
||||||
return new BatterySensorDiscoveryService(_haContextMock.Object, _loggerMock.Object);
|
return new BatterySensorDiscoveryService(_haContextMock.Object, _loggerMock.Object);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void SetupEntities(params (string entityId, string? deviceClass, string? state, string? friendlyName)[] entities)
|
private void SetupEntities(params EntitySpec[] entities)
|
||||||
{
|
{
|
||||||
var entityList = new List<Entity>();
|
ConfigureHaContext(_haContextMock, entities);
|
||||||
|
|
||||||
foreach (var (entityId, deviceClass, state, friendlyName) in entities)
|
|
||||||
{
|
|
||||||
var attributes = new Dictionary<string, object?>();
|
|
||||||
if (deviceClass is not null)
|
|
||||||
{
|
|
||||||
attributes["device_class"] = deviceClass;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (friendlyName is not null)
|
#region IsExcludedDevice
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(ExcludedEntityIdRows), MemberType = typeof(BatteryMonitorTestData))]
|
||||||
|
public void IsExcludedDevice_ShouldCorrectlyIdentifyExclusions(string entityId, bool expected)
|
||||||
{
|
{
|
||||||
attributes["friendly_name"] = friendlyName;
|
BatterySensorDiscoveryService.IsExcludedDevice(entityId).Should().Be(expected);
|
||||||
}
|
}
|
||||||
|
|
||||||
var attributesJson = JsonSerializer.SerializeToElement(attributes);
|
#endregion
|
||||||
var entityState = new EntityState { AttributesJson = attributesJson, State = state };
|
|
||||||
|
|
||||||
_haContextMock.Setup(h => h.GetState(entityId)).Returns(entityState);
|
|
||||||
|
|
||||||
var entity = new Entity(_haContextMock.Object, entityId);
|
|
||||||
entityList.Add(entity);
|
|
||||||
}
|
|
||||||
|
|
||||||
_haContextMock.Setup(h => h.GetAllEntities()).Returns(entityList);
|
|
||||||
}
|
|
||||||
|
|
||||||
#region Discovery
|
#region Discovery
|
||||||
|
|
||||||
@@ -60,9 +46,9 @@ public class BatterySensorDiscoveryServiceTests
|
|||||||
public void DiscoverLowBatterySensors_ShouldFindLowBatteryDevices()
|
public void DiscoverLowBatterySensors_ShouldFindLowBatteryDevices()
|
||||||
{
|
{
|
||||||
SetupEntities(
|
SetupEntities(
|
||||||
("sensor.bathroom_battery", "battery", "3", "Bathroom Battery"),
|
Battery("sensor.bathroom_battery", "3", "Bathroom Battery"),
|
||||||
("sensor.bedroom_battery", "battery", "80", "Bedroom Battery"),
|
Battery("sensor.bedroom_battery", "80", "Bedroom Battery"),
|
||||||
("sensor.boiler_temp_battery", "battery", "2", "Boiler Temp Battery")
|
Battery("sensor.boiler_temp_battery", "2", "Boiler Temp Battery")
|
||||||
);
|
);
|
||||||
|
|
||||||
var sut = CreateSut();
|
var sut = CreateSut();
|
||||||
@@ -71,134 +57,116 @@ public class BatterySensorDiscoveryServiceTests
|
|||||||
result.Should().HaveCount(2);
|
result.Should().HaveCount(2);
|
||||||
result.Should().Contain(s => s.EntityId == "sensor.bathroom_battery");
|
result.Should().Contain(s => s.EntityId == "sensor.bathroom_battery");
|
||||||
result.Should().Contain(s => s.EntityId == "sensor.boiler_temp_battery");
|
result.Should().Contain(s => s.EntityId == "sensor.boiler_temp_battery");
|
||||||
|
result.Select(s => s.EntityId).Should().NotContain("sensor.bedroom_battery");
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Theory]
|
||||||
public void DiscoverLowBatterySensors_ShouldExcludePhoneDevices()
|
[InlineData("sensor.erikas_iphone_battery_level", "Erika's iPhone Battery")]
|
||||||
|
[InlineData("sensor.home_phone_battery_state", "Home Phone Battery")]
|
||||||
|
[InlineData("sensor.marius_watch_battery_level", "Marius Watch Battery")]
|
||||||
|
[InlineData("sensor.sm_s936b_battery_level", "Galaxy S24 Battery")]
|
||||||
|
[InlineData("sensor.sm_a536b_battery_level", "Galaxy A53 Battery")]
|
||||||
|
[InlineData("sensor.pixel_8_battery_level", "Pixel 8 Battery")]
|
||||||
|
[InlineData("sensor.oneplus_battery_level", "OnePlus Battery")]
|
||||||
|
[InlineData("sensor.ipad_battery_level", "iPad Battery")]
|
||||||
|
[InlineData("sensor.galaxy_s24_battery", "Galaxy S24 Battery")]
|
||||||
|
[InlineData("SENSOR.SM_S936B_BATTERY_LEVEL", "Galaxy S24 Battery")]
|
||||||
|
public void DiscoverLowBatterySensors_ShouldExcludePersonalDevices(string excludedEntityId, string friendlyName)
|
||||||
{
|
{
|
||||||
SetupEntities(
|
SetupEntities(
|
||||||
("sensor.bathroom_battery", "battery", "2", "Bathroom Battery"),
|
Battery("sensor.bathroom_battery", "2", "Bathroom Battery"),
|
||||||
("sensor.erikas_iphone_battery_level", "battery", "1", "Erika's iPhone Battery"),
|
Battery(excludedEntityId, "1", friendlyName)
|
||||||
("sensor.home_phone_battery_state", "battery", "3", "Home Phone Battery")
|
|
||||||
);
|
);
|
||||||
|
|
||||||
var sut = CreateSut();
|
var sut = CreateSut();
|
||||||
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
||||||
|
|
||||||
result.Should().HaveCount(1);
|
result.Should().ContainSingle();
|
||||||
result.First().EntityId.Should().Be("sensor.bathroom_battery");
|
result[0].EntityId.Should().Be("sensor.bathroom_battery");
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Theory]
|
||||||
public void DiscoverLowBatterySensors_ShouldExcludeWatchDevices()
|
[InlineData("binary_sensor.bathroom_battery", "battery")]
|
||||||
|
[InlineData("sensor.bathroom_temperature", "temperature")]
|
||||||
|
[InlineData("sensor.bathroom_humidity", "humidity")]
|
||||||
|
[InlineData("sensor.no_device_class", null)]
|
||||||
|
[InlineData("sensorx.bathroom_battery", "battery")]
|
||||||
|
[InlineData("switch.bathroom_battery", "battery")]
|
||||||
|
public void DiscoverLowBatterySensors_ShouldIgnoreEntitiesThatAreNotBatterySensors(string entityId,
|
||||||
|
string? deviceClass)
|
||||||
{
|
{
|
||||||
SetupEntities(
|
SetupEntities(
|
||||||
("sensor.bathroom_battery", "battery", "2", "Bathroom Battery"),
|
Sensor(entityId, deviceClass, "2", "Ignored Entity"),
|
||||||
("sensor.marius_watch_battery_level", "battery", "1", "Marius Watch Battery")
|
Battery("sensor.bedroom_battery", "3", "Bedroom Battery")
|
||||||
);
|
);
|
||||||
|
|
||||||
var sut = CreateSut();
|
var sut = CreateSut();
|
||||||
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
||||||
|
|
||||||
result.Should().HaveCount(1);
|
result.Should().ContainSingle();
|
||||||
result.First().EntityId.Should().Be("sensor.bathroom_battery");
|
result[0].EntityId.Should().Be("sensor.bedroom_battery");
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Theory]
|
||||||
public void DiscoverLowBatterySensors_ShouldExcludeGalaxyDevices()
|
[MemberData(nameof(UnusableStateRows), MemberType = typeof(BatteryMonitorTestData))]
|
||||||
|
public void DiscoverLowBatterySensors_ShouldSkipUnusableStates(string? state)
|
||||||
{
|
{
|
||||||
SetupEntities(
|
SetupEntities(
|
||||||
("sensor.bathroom_battery", "battery", "2", "Bathroom Battery"),
|
Battery("sensor.bathroom_battery", state, "Bathroom Battery"),
|
||||||
("sensor.sm_s936b_battery_level", "battery", "1", "Galaxy S24 Battery")
|
Battery("sensor.bedroom_battery", "3", "Bedroom Battery")
|
||||||
);
|
);
|
||||||
|
|
||||||
var sut = CreateSut();
|
var sut = CreateSut();
|
||||||
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
||||||
|
|
||||||
result.Should().HaveCount(1);
|
result.Should().ContainSingle();
|
||||||
result.First().EntityId.Should().Be("sensor.bathroom_battery");
|
result[0].EntityId.Should().Be("sensor.bedroom_battery");
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void DiscoverLowBatterySensors_ShouldIgnoreNonSensorDomain()
|
public void DiscoverLowBatterySensors_WhenEntityStateIsNull_ShouldSkipSensor()
|
||||||
{
|
{
|
||||||
SetupEntities(
|
SetupEntities(
|
||||||
("binary_sensor.bathroom_battery", "battery", "2", "Bathroom Battery"),
|
new EntitySpec
|
||||||
("sensor.bedroom_battery", "battery", "3", "Bedroom Battery")
|
{ EntityId = "sensor.bathroom_battery", FriendlyName = "Bathroom Battery", HasState = false },
|
||||||
|
Battery("sensor.bedroom_battery", "3", "Bedroom Battery")
|
||||||
);
|
);
|
||||||
|
|
||||||
var sut = CreateSut();
|
var sut = CreateSut();
|
||||||
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
||||||
|
|
||||||
result.Should().HaveCount(1);
|
result.Should().ContainSingle();
|
||||||
result.First().EntityId.Should().Be("sensor.bedroom_battery");
|
result[0].EntityId.Should().Be("sensor.bedroom_battery");
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Theory]
|
||||||
public void DiscoverLowBatterySensors_ShouldIgnoreNonBatteryDeviceClass()
|
[MemberData(nameof(ThresholdBoundaryRows), MemberType = typeof(BatteryMonitorTestData))]
|
||||||
|
public void DiscoverLowBatterySensors_ShouldApplyStrictThresholdBoundary(int thresholdPercent,
|
||||||
|
string state,
|
||||||
|
bool expectedIncluded)
|
||||||
{
|
{
|
||||||
SetupEntities(
|
SetupEntities(Battery("sensor.boundary_battery", state, "Boundary Battery"));
|
||||||
("sensor.bathroom_temperature", "temperature", "2", "Bathroom Temperature"),
|
|
||||||
("sensor.bedroom_battery", "battery", "3", "Bedroom Battery")
|
|
||||||
);
|
|
||||||
|
|
||||||
var sut = CreateSut();
|
var sut = CreateSut();
|
||||||
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
var result = sut.DiscoverLowBatterySensors(thresholdPercent);
|
||||||
|
|
||||||
result.Should().HaveCount(1);
|
result.Should().HaveCount(expectedIncluded ? 1 : 0);
|
||||||
result.First().EntityId.Should().Be("sensor.bedroom_battery");
|
|
||||||
|
if (!expectedIncluded)
|
||||||
|
{
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
result[0].EntityId.Should().Be("sensor.boundary_battery");
|
||||||
public void DiscoverLowBatterySensors_ShouldSkipUnavailableState()
|
result[0].BatteryLevel.Should().Be(double.Parse(state, CultureInfo.InvariantCulture));
|
||||||
{
|
|
||||||
SetupEntities(
|
|
||||||
("sensor.bathroom_battery", "battery", "unavailable", "Bathroom Battery"),
|
|
||||||
("sensor.bedroom_battery", "battery", "3", "Bedroom Battery")
|
|
||||||
);
|
|
||||||
|
|
||||||
var sut = CreateSut();
|
|
||||||
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
|
||||||
|
|
||||||
result.Should().HaveCount(1);
|
|
||||||
result.First().EntityId.Should().Be("sensor.bedroom_battery");
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void DiscoverLowBatterySensors_ShouldSkipUnknownState()
|
|
||||||
{
|
|
||||||
SetupEntities(
|
|
||||||
("sensor.bathroom_battery", "battery", "unknown", "Bathroom Battery"),
|
|
||||||
("sensor.bedroom_battery", "battery", "3", "Bedroom Battery")
|
|
||||||
);
|
|
||||||
|
|
||||||
var sut = CreateSut();
|
|
||||||
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
|
||||||
|
|
||||||
result.Should().HaveCount(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void DiscoverLowBatterySensors_ShouldSkipNonParsableState()
|
|
||||||
{
|
|
||||||
SetupEntities(
|
|
||||||
("sensor.bathroom_battery", "battery", "not_a_number", "Bathroom Battery"),
|
|
||||||
("sensor.bedroom_battery", "battery", "3", "Bedroom Battery")
|
|
||||||
);
|
|
||||||
|
|
||||||
var sut = CreateSut();
|
|
||||||
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
|
||||||
|
|
||||||
result.Should().HaveCount(1);
|
|
||||||
result.First().EntityId.Should().Be("sensor.bedroom_battery");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void DiscoverLowBatterySensors_WhenNoBatterySensors_ShouldReturnEmpty()
|
public void DiscoverLowBatterySensors_WhenNoBatterySensors_ShouldReturnEmpty()
|
||||||
{
|
{
|
||||||
SetupEntities(
|
SetupEntities(
|
||||||
("sensor.temperature", "temperature", "22", "Temperature"),
|
Sensor("sensor.temperature", "temperature", "22", "Temperature"),
|
||||||
("switch.some_switch", null, "on", "Switch")
|
Sensor("switch.some_switch", null, "on", "Switch")
|
||||||
);
|
);
|
||||||
|
|
||||||
var sut = CreateSut();
|
var sut = CreateSut();
|
||||||
@@ -211,8 +179,9 @@ public class BatterySensorDiscoveryServiceTests
|
|||||||
public void DiscoverLowBatterySensors_WhenAllAboveThreshold_ShouldReturnEmpty()
|
public void DiscoverLowBatterySensors_WhenAllAboveThreshold_ShouldReturnEmpty()
|
||||||
{
|
{
|
||||||
SetupEntities(
|
SetupEntities(
|
||||||
("sensor.bathroom_battery", "battery", "50", "Bathroom Battery"),
|
Battery("sensor.bathroom_battery", "5", "Bathroom Battery"),
|
||||||
("sensor.bedroom_battery", "battery", "80", "Bedroom Battery")
|
Battery("sensor.bedroom_battery", "50", "Bedroom Battery"),
|
||||||
|
Battery("sensor.boiler_temp_battery", "100", "Boiler Temp Battery")
|
||||||
);
|
);
|
||||||
|
|
||||||
var sut = CreateSut();
|
var sut = CreateSut();
|
||||||
@@ -222,101 +191,114 @@ public class BatterySensorDiscoveryServiceTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void DiscoverLowBatterySensors_ShouldRespectCustomThreshold()
|
public void DiscoverLowBatterySensors_WhenThereAreNoEntities_ShouldReturnEmpty()
|
||||||
{
|
{
|
||||||
SetupEntities(
|
SetupEntities();
|
||||||
("sensor.bathroom_battery", "battery", "15", "Bathroom Battery"),
|
|
||||||
("sensor.bedroom_battery", "battery", "25", "Bedroom Battery")
|
|
||||||
);
|
|
||||||
|
|
||||||
var sut = CreateSut();
|
var sut = CreateSut();
|
||||||
var result = sut.DiscoverLowBatterySensors(20);
|
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
||||||
|
|
||||||
result.Should().HaveCount(1);
|
result.Should().NotBeNull();
|
||||||
result.First().EntityId.Should().Be("sensor.bathroom_battery");
|
result.Should().BeEmpty();
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void DiscoverLowBatterySensors_ShouldPopulateFriendlyName()
|
public void DiscoverLowBatterySensors_WithDuplicateSensorIds_ShouldReportEachOccurrence()
|
||||||
{
|
{
|
||||||
SetupEntities(
|
SetupEntities(
|
||||||
("sensor.bathroom_battery", "battery", "2", "Bathroom Battery")
|
Battery("sensor.duplicate_battery", "2", "Duplicate Battery"),
|
||||||
|
Battery("sensor.duplicate_battery", "2", "Duplicate Battery")
|
||||||
);
|
);
|
||||||
|
|
||||||
var sut = CreateSut();
|
var sut = CreateSut();
|
||||||
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
||||||
|
|
||||||
result.Should().HaveCount(1);
|
result.Should().HaveCount(2);
|
||||||
result.First().FriendlyName.Should().Be("Bathroom Battery");
|
result.Should().OnlyContain(s => s.EntityId == "sensor.duplicate_battery");
|
||||||
result.First().BatteryLevel.Should().Be(2);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Theory]
|
||||||
public void DiscoverLowBatterySensors_ShouldUseEntityIdWhenNoFriendlyName()
|
[InlineData("Bathroom Battery", "Bathroom Battery")]
|
||||||
|
[InlineData("", "")]
|
||||||
|
[InlineData(" ", " ")]
|
||||||
|
[InlineData(null, "sensor.bathroom_battery")]
|
||||||
|
public void DiscoverLowBatterySensors_ShouldResolveFriendlyName(string? friendlyName, string expectedFriendlyName)
|
||||||
{
|
{
|
||||||
SetupEntities(
|
SetupEntities(Battery("sensor.bathroom_battery", "2", friendlyName));
|
||||||
("sensor.bathroom_battery", "battery", "2", null)
|
|
||||||
);
|
|
||||||
|
|
||||||
var sut = CreateSut();
|
var sut = CreateSut();
|
||||||
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
||||||
|
|
||||||
result.Should().HaveCount(1);
|
result.Should().ContainSingle();
|
||||||
result.First().FriendlyName.Should().Be("sensor.bathroom_battery");
|
result[0].EntityId.Should().Be("sensor.bathroom_battery");
|
||||||
|
result[0].FriendlyName.Should().Be(expectedFriendlyName);
|
||||||
|
result[0].BatteryLevel.Should().Be(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void DiscoverLowBatterySensors_ShouldPreserveFractionalBatteryLevel()
|
||||||
|
{
|
||||||
|
SetupEntities(Battery("sensor.bathroom_battery", "2.5", "Bathroom Battery"));
|
||||||
|
|
||||||
|
var sut = CreateSut();
|
||||||
|
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
||||||
|
|
||||||
|
result.Should().ContainSingle();
|
||||||
|
result[0].FriendlyName.Should().Be("Bathroom Battery");
|
||||||
|
result[0].BatteryLevel.Should().Be(2.5);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void DiscoverLowBatterySensors_WithGeneratedSensors_ShouldReturnOnlySensorsBelowThreshold()
|
||||||
|
{
|
||||||
|
SetupEntities(CreateGeneratedBatteryEntities(101));
|
||||||
|
|
||||||
|
var sut = CreateSut();
|
||||||
|
var result = sut.DiscoverLowBatterySensors(7);
|
||||||
|
|
||||||
|
result.Should().HaveCount(7);
|
||||||
|
result.Select(s => s.BatteryLevel).Should().Equal(Enumerable.Range(0, 7).Select(i => (double)i));
|
||||||
|
|
||||||
|
result.Select(s => s.FriendlyName)
|
||||||
|
.Should()
|
||||||
|
.OnlyContain(name => name.StartsWith("Generated Battery", StringComparison.Ordinal));
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
#region IsBatterySensor
|
#region IsBatterySensor
|
||||||
|
|
||||||
[Fact]
|
[Theory]
|
||||||
public void IsBatterySensor_WithBatteryDeviceClass_ShouldReturnTrue()
|
[InlineData("sensor.bathroom_battery", "battery", true)]
|
||||||
|
[InlineData("SENSOR.bathroom_battery", "battery", true)]
|
||||||
|
[InlineData("Sensor.Bathroom_Battery", "BATTERY", true)]
|
||||||
|
[InlineData("sensor.bathroom_battery", "Battery", true)]
|
||||||
|
[InlineData("binary_sensor.bathroom_battery", "battery", false)]
|
||||||
|
[InlineData("binary_sensor.sm_s936b_battery_level", "battery", false)]
|
||||||
|
[InlineData("sensor.bathroom_temperature", "temperature", false)]
|
||||||
|
[InlineData("sensor.no_device_class", null, false)]
|
||||||
|
[InlineData("sensor.bathroom_battery", "", false)]
|
||||||
|
[InlineData("sensorx.bathroom_battery", "battery", false)]
|
||||||
|
[InlineData("sensor", "battery", false)]
|
||||||
|
[InlineData("switch.bathroom_battery", "battery", false)]
|
||||||
|
public void IsBatterySensor_ShouldClassifyEntities(string entityId, string? deviceClass, bool expected)
|
||||||
{
|
{
|
||||||
SetupEntities(("sensor.bathroom_battery", "battery", "50", "Bathroom Battery"));
|
SetupEntities(Sensor(entityId, deviceClass, "50", "Some Entity"));
|
||||||
|
|
||||||
|
var entity = new Entity(_haContextMock.Object, entityId);
|
||||||
|
|
||||||
|
BatterySensorDiscoveryService.IsBatterySensor(entity).Should().Be(expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IsBatterySensor_WhenEntityHasNoState_ShouldReturnFalse()
|
||||||
|
{
|
||||||
|
SetupEntities(new EntitySpec { EntityId = "sensor.bathroom_battery", HasState = false });
|
||||||
|
|
||||||
var entity = new Entity(_haContextMock.Object, "sensor.bathroom_battery");
|
var entity = new Entity(_haContextMock.Object, "sensor.bathroom_battery");
|
||||||
|
|
||||||
BatterySensorDiscoveryService.IsBatterySensor(entity).Should().BeTrue();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void IsBatterySensor_WithNonSensorDomain_ShouldReturnFalse()
|
|
||||||
{
|
|
||||||
SetupEntities(("binary_sensor.bathroom_battery", "battery", "50", "Bathroom Battery"));
|
|
||||||
var entity = new Entity(_haContextMock.Object, "binary_sensor.bathroom_battery");
|
|
||||||
|
|
||||||
BatterySensorDiscoveryService.IsBatterySensor(entity).Should().BeFalse();
|
BatterySensorDiscoveryService.IsBatterySensor(entity).Should().BeFalse();
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void IsBatterySensor_WithNonBatteryDeviceClass_ShouldReturnFalse()
|
|
||||||
{
|
|
||||||
SetupEntities(("sensor.bathroom_temperature", "temperature", "22", "Bathroom Temperature"));
|
|
||||||
var entity = new Entity(_haContextMock.Object, "sensor.bathroom_temperature");
|
|
||||||
|
|
||||||
BatterySensorDiscoveryService.IsBatterySensor(entity).Should().BeFalse();
|
|
||||||
}
|
|
||||||
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
#region IsExcludedDevice
|
|
||||||
|
|
||||||
[Theory]
|
|
||||||
[InlineData("sensor.erikas_iphone_battery_level", true)]
|
|
||||||
[InlineData("sensor.home_phone_battery_state", true)]
|
|
||||||
[InlineData("sensor.marius_watch_battery_level", true)]
|
|
||||||
[InlineData("sensor.sm_s936b_battery_level", true)]
|
|
||||||
[InlineData("sensor.sm_a536b_battery_level", true)]
|
|
||||||
[InlineData("sensor.pixel_8_battery_level", true)]
|
|
||||||
[InlineData("sensor.oneplus_battery_level", true)]
|
|
||||||
[InlineData("sensor.ipad_battery_level", true)]
|
|
||||||
[InlineData("sensor.galaxy_s24_battery", true)]
|
|
||||||
[InlineData("sensor.bathroom_battery", false)]
|
|
||||||
[InlineData("sensor.boiler_temp_battery", false)]
|
|
||||||
[InlineData("sensor.aquarium_leak_sensor_battery", false)]
|
|
||||||
public void IsExcludedDevice_ShouldCorrectlyIdentifyExclusions(string entityId, bool expected)
|
|
||||||
{
|
|
||||||
BatterySensorDiscoveryService.IsExcludedDevice(entityId).Should().Be(expected);
|
|
||||||
}
|
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
}
|
}
|
||||||
@@ -14,14 +14,14 @@
|
|||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\HomeAssistant.Entities\HomeAssistant.Entities.csproj" />
|
<ProjectReference Include="..\HomeAssistant.Entities\HomeAssistant.Entities.csproj"/>
|
||||||
<ProjectReference Include="..\BatteryMonitor.Models\BatteryMonitor.Models.csproj" />
|
<ProjectReference Include="..\BatteryMonitor.Models\BatteryMonitor.Models.csproj"/>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.5" />
|
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="11.0.0"/>
|
||||||
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.11.0" />
|
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.43.1"/>
|
||||||
<PackageReference Include="NetDaemon.HassModel" Version="26.11.0" />
|
<PackageReference Include="NetDaemon.HassModel" Version="26.43.1"/>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
@@ -1,21 +1,26 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
using System.Reactive.Concurrency;
|
using System.Reactive.Concurrency;
|
||||||
|
using BatteryMonitor.Models;
|
||||||
|
using BatteryMonitorManager.Interface;
|
||||||
|
using BatteryMonitorManager.Models;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
using NetDaemon.AppModel;
|
using NetDaemon.AppModel;
|
||||||
using NetDaemon.Extensions.Scheduler;
|
using NetDaemon.Extensions.Scheduler;
|
||||||
using BatteryMonitorManager.Interface;
|
|
||||||
using BatteryMonitorManager.Models;
|
#endregion
|
||||||
|
|
||||||
namespace BatteryMonitorManager;
|
namespace BatteryMonitorManager;
|
||||||
|
|
||||||
[NetDaemonApp]
|
[NetDaemonApp]
|
||||||
public sealed class BatteryMonitorInit : IBatteryMonitorInit
|
public sealed class BatteryMonitorInit
|
||||||
{
|
{
|
||||||
private readonly ILogger<BatteryMonitorInit> _logger;
|
|
||||||
private readonly IScheduler _scheduler;
|
|
||||||
private readonly IBatterySensorDiscoveryService _discoveryService;
|
private readonly IBatterySensorDiscoveryService _discoveryService;
|
||||||
|
private readonly ILogger<BatteryMonitorInit> _logger;
|
||||||
private readonly IBatteryNotificationService _notificationService;
|
private readonly IBatteryNotificationService _notificationService;
|
||||||
private readonly BatteryMonitorOptions _options;
|
private readonly BatteryMonitorOptions _options;
|
||||||
|
private readonly IScheduler _scheduler;
|
||||||
|
|
||||||
public BatteryMonitorInit(
|
public BatteryMonitorInit(
|
||||||
ILogger<BatteryMonitorInit> logger,
|
ILogger<BatteryMonitorInit> logger,
|
||||||
@@ -46,7 +51,7 @@ public sealed class BatteryMonitorInit : IBatteryMonitorInit
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task InitializeAsync()
|
private async Task InitializeAsync()
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
@@ -54,18 +59,23 @@ public sealed class BatteryMonitorInit : IBatteryMonitorInit
|
|||||||
|
|
||||||
CheckAndNotify();
|
CheckAndNotify();
|
||||||
|
|
||||||
_logger.LogInformation("BatteryMonitor initialized with threshold {Threshold}%", _options.BatteryThresholdPercent);
|
if (_logger.IsEnabled(LogLevel.Information))
|
||||||
|
{
|
||||||
|
_logger.LogInformation("BatteryMonitor initialized with threshold {Threshold}%",
|
||||||
|
_options.BatteryThresholdPercent);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
_logger.LogError(ex, "Error initializing BatteryMonitor");
|
_logger.LogError(ex, "Error initializing BatteryMonitor");
|
||||||
|
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void ScheduleDailyCheck()
|
private void ScheduleDailyCheck()
|
||||||
{
|
{
|
||||||
_scheduler.ScheduleCron(BatteryMonitor.Models.BatteryMonitorConsts.DailyCheckCron, () =>
|
_scheduler.ScheduleCron(BatteryMonitorConsts.DailyCheckCron, () =>
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
@@ -81,7 +91,7 @@ public sealed class BatteryMonitorInit : IBatteryMonitorInit
|
|||||||
_logger.LogInformation("Scheduled daily battery check at 08:00");
|
_logger.LogInformation("Scheduled daily battery check at 08:00");
|
||||||
}
|
}
|
||||||
|
|
||||||
internal void CheckAndNotify()
|
private void CheckAndNotify()
|
||||||
{
|
{
|
||||||
var lowBatteryDevices = _discoveryService.DiscoverLowBatterySensors(_options.BatteryThresholdPercent);
|
var lowBatteryDevices = _discoveryService.DiscoverLowBatterySensors(_options.BatteryThresholdPercent);
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,12 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using BatteryMonitorManager.Interface;
|
||||||
|
using BatteryMonitorManager.Models;
|
||||||
using Microsoft.Extensions.Configuration;
|
using Microsoft.Extensions.Configuration;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using NetDaemon.AppModel;
|
using NetDaemon.AppModel;
|
||||||
using BatteryMonitorManager.Interface;
|
|
||||||
using BatteryMonitorManager.Models;
|
#endregion
|
||||||
|
|
||||||
namespace BatteryMonitorManager;
|
namespace BatteryMonitorManager;
|
||||||
|
|
||||||
@@ -12,7 +16,8 @@ public static class BatteryMonitorServiceRegistration
|
|||||||
{
|
{
|
||||||
var options = configuration
|
var options = configuration
|
||||||
.GetSection(BatteryMonitorOptions.SectionName)
|
.GetSection(BatteryMonitorOptions.SectionName)
|
||||||
.Get<BatteryMonitorOptions>() ?? new BatteryMonitorOptions();
|
.Get<BatteryMonitorOptions>() ??
|
||||||
|
new BatteryMonitorOptions();
|
||||||
|
|
||||||
if (!options.Enabled)
|
if (!options.Enabled)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,24 +1,19 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using Microsoft.Extensions.Logging;
|
|
||||||
using NetDaemon.HassModel;
|
|
||||||
using BatteryMonitor.Models;
|
using BatteryMonitor.Models;
|
||||||
using BatteryMonitorManager.Interface;
|
using BatteryMonitorManager.Interface;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using NetDaemon.HassModel;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace BatteryMonitorManager;
|
namespace BatteryMonitorManager;
|
||||||
|
|
||||||
public sealed class BatteryNotificationService : IBatteryNotificationService
|
public sealed class BatteryNotificationService(
|
||||||
{
|
|
||||||
private readonly IHaContext _haContext;
|
|
||||||
private readonly ILogger<BatteryNotificationService> _logger;
|
|
||||||
|
|
||||||
public BatteryNotificationService(
|
|
||||||
IHaContext haContext,
|
IHaContext haContext,
|
||||||
ILogger<BatteryNotificationService> logger)
|
ILogger<BatteryNotificationService> logger) : IBatteryNotificationService
|
||||||
{
|
{
|
||||||
_haContext = haContext;
|
|
||||||
_logger = logger;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void NotifyLowBattery(IReadOnlyList<BatterySensorInfo> lowBatteryDevices)
|
public void NotifyLowBattery(IReadOnlyList<BatterySensorInfo> lowBatteryDevices)
|
||||||
{
|
{
|
||||||
if (lowBatteryDevices.Count == 0)
|
if (lowBatteryDevices.Count == 0)
|
||||||
@@ -28,7 +23,7 @@ public sealed class BatteryNotificationService : IBatteryNotificationService
|
|||||||
|
|
||||||
var message = BuildNotificationMessage(lowBatteryDevices);
|
var message = BuildNotificationMessage(lowBatteryDevices);
|
||||||
|
|
||||||
_haContext.CallService(
|
haContext.CallService(
|
||||||
BatteryMonitorConsts.PersistentNotificationDomain,
|
BatteryMonitorConsts.PersistentNotificationDomain,
|
||||||
BatteryMonitorConsts.PersistentNotificationCreateService,
|
BatteryMonitorConsts.PersistentNotificationCreateService,
|
||||||
data: new
|
data: new
|
||||||
@@ -38,14 +33,17 @@ public sealed class BatteryNotificationService : IBatteryNotificationService
|
|||||||
notification_id = BatteryMonitorConsts.NotificationId
|
notification_id = BatteryMonitorConsts.NotificationId
|
||||||
});
|
});
|
||||||
|
|
||||||
_logger.LogInformation(
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
|
{
|
||||||
|
logger.LogInformation(
|
||||||
"Sent low battery notification for {Count} device(s)",
|
"Sent low battery notification for {Count} device(s)",
|
||||||
lowBatteryDevices.Count);
|
lowBatteryDevices.Count);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public void DismissNotification()
|
public void DismissNotification()
|
||||||
{
|
{
|
||||||
_haContext.CallService(
|
haContext.CallService(
|
||||||
BatteryMonitorConsts.PersistentNotificationDomain,
|
BatteryMonitorConsts.PersistentNotificationDomain,
|
||||||
BatteryMonitorConsts.PersistentNotificationDismissService,
|
BatteryMonitorConsts.PersistentNotificationDismissService,
|
||||||
data: new
|
data: new
|
||||||
@@ -53,7 +51,7 @@ public sealed class BatteryNotificationService : IBatteryNotificationService
|
|||||||
notification_id = BatteryMonitorConsts.NotificationId
|
notification_id = BatteryMonitorConsts.NotificationId
|
||||||
});
|
});
|
||||||
|
|
||||||
_logger.LogDebug("Dismissed low battery notification");
|
logger.LogDebug("Dismissed low battery notification");
|
||||||
}
|
}
|
||||||
|
|
||||||
internal static string BuildNotificationMessage(IReadOnlyList<BatterySensorInfo> devices)
|
internal static string BuildNotificationMessage(IReadOnlyList<BatterySensorInfo> devices)
|
||||||
|
|||||||
@@ -1,29 +1,24 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
using System.Globalization;
|
using System.Globalization;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
|
using BatteryMonitor.Models;
|
||||||
|
using BatteryMonitorManager.Interface;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using NetDaemon.HassModel;
|
using NetDaemon.HassModel;
|
||||||
using NetDaemon.HassModel.Entities;
|
using NetDaemon.HassModel.Entities;
|
||||||
using BatteryMonitor.Models;
|
|
||||||
using BatteryMonitorManager.Interface;
|
#endregion
|
||||||
|
|
||||||
namespace BatteryMonitorManager;
|
namespace BatteryMonitorManager;
|
||||||
|
|
||||||
public sealed class BatterySensorDiscoveryService : IBatterySensorDiscoveryService
|
public sealed class BatterySensorDiscoveryService(
|
||||||
{
|
|
||||||
private readonly IHaContext _haContext;
|
|
||||||
private readonly ILogger<BatterySensorDiscoveryService> _logger;
|
|
||||||
|
|
||||||
public BatterySensorDiscoveryService(
|
|
||||||
IHaContext haContext,
|
IHaContext haContext,
|
||||||
ILogger<BatterySensorDiscoveryService> logger)
|
ILogger<BatterySensorDiscoveryService> logger) : IBatterySensorDiscoveryService
|
||||||
{
|
{
|
||||||
_haContext = haContext;
|
|
||||||
_logger = logger;
|
|
||||||
}
|
|
||||||
|
|
||||||
public IReadOnlyList<BatterySensorInfo> DiscoverLowBatterySensors(int thresholdPercent)
|
public IReadOnlyList<BatterySensorInfo> DiscoverLowBatterySensors(int thresholdPercent)
|
||||||
{
|
{
|
||||||
var allEntities = _haContext.GetAllEntities();
|
var allEntities = haContext.GetAllEntities();
|
||||||
|
|
||||||
var lowBatterySensors = allEntities
|
var lowBatterySensors = allEntities
|
||||||
.Where(IsBatterySensor)
|
.Where(IsBatterySensor)
|
||||||
@@ -32,9 +27,12 @@ public sealed class BatterySensorDiscoveryService : IBatterySensorDiscoveryServi
|
|||||||
.Where(info => info is not null)
|
.Where(info => info is not null)
|
||||||
.ToList();
|
.ToList();
|
||||||
|
|
||||||
_logger.LogInformation(
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
|
{
|
||||||
|
logger.LogInformation(
|
||||||
"Battery check: found {Count} sensors below {Threshold}%",
|
"Battery check: found {Count} sensors below {Threshold}%",
|
||||||
lowBatterySensors.Count, thresholdPercent);
|
lowBatterySensors.Count, thresholdPercent);
|
||||||
|
}
|
||||||
|
|
||||||
return lowBatterySensors!;
|
return lowBatterySensors!;
|
||||||
}
|
}
|
||||||
@@ -65,13 +63,23 @@ public sealed class BatterySensorDiscoveryService : IBatterySensorDiscoveryServi
|
|||||||
|
|
||||||
if (state is null or "unavailable" or "unknown")
|
if (state is null or "unavailable" or "unknown")
|
||||||
{
|
{
|
||||||
_logger.LogDebug("Skipping battery sensor {EntityId}: state is {State}", entity.EntityId, state ?? "null");
|
if (logger.IsEnabled(LogLevel.Debug))
|
||||||
|
{
|
||||||
|
logger.LogDebug("Skipping battery sensor {EntityId}: state is {State}", entity.EntityId,
|
||||||
|
state ?? "null");
|
||||||
|
}
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!double.TryParse(state, CultureInfo.InvariantCulture, out var batteryLevel))
|
if (!double.TryParse(state, CultureInfo.InvariantCulture, out var batteryLevel))
|
||||||
{
|
{
|
||||||
_logger.LogDebug("Skipping battery sensor {EntityId}: unable to parse state '{State}'", entity.EntityId, state);
|
if (logger.IsEnabled(LogLevel.Debug))
|
||||||
|
{
|
||||||
|
logger.LogDebug("Skipping battery sensor {EntityId}: unable to parse state '{State}'", entity.EntityId,
|
||||||
|
state);
|
||||||
|
}
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -80,8 +88,7 @@ public sealed class BatterySensorDiscoveryService : IBatterySensorDiscoveryServi
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
var friendlyName = GetJsonStringProperty(entity.EntityState?.AttributesJson, "friendly_name")
|
var friendlyName = GetJsonStringProperty(entity.EntityState?.AttributesJson, "friendly_name") ?? entity.EntityId;
|
||||||
?? entity.EntityId;
|
|
||||||
|
|
||||||
return new BatterySensorInfo
|
return new BatterySensorInfo
|
||||||
{
|
{
|
||||||
@@ -91,7 +98,7 @@ public sealed class BatterySensorDiscoveryService : IBatterySensorDiscoveryServi
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
internal static string? GetJsonStringProperty(JsonElement? element, string propertyName)
|
private static string? GetJsonStringProperty(JsonElement? element, string propertyName)
|
||||||
{
|
{
|
||||||
if (element is null)
|
if (element is null)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,6 +0,0 @@
|
|||||||
namespace BatteryMonitorManager.Interface;
|
|
||||||
|
|
||||||
public interface IBatteryMonitorInit
|
|
||||||
{
|
|
||||||
Task InitializeAsync();
|
|
||||||
}
|
|
||||||
@@ -1,5 +1,9 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
using BatteryMonitor.Models;
|
using BatteryMonitor.Models;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace BatteryMonitorManager.Interface;
|
namespace BatteryMonitorManager.Interface;
|
||||||
|
|
||||||
public interface IBatteryNotificationService
|
public interface IBatteryNotificationService
|
||||||
|
|||||||
@@ -1,5 +1,9 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
using BatteryMonitor.Models;
|
using BatteryMonitor.Models;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace BatteryMonitorManager.Interface;
|
namespace BatteryMonitorManager.Interface;
|
||||||
|
|
||||||
public interface IBatterySensorDiscoveryService
|
public interface IBatterySensorDiscoveryService
|
||||||
|
|||||||
@@ -1,12 +1,16 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
using BatteryMonitor.Models;
|
using BatteryMonitor.Models;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace BatteryMonitorManager.Models;
|
namespace BatteryMonitorManager.Models;
|
||||||
|
|
||||||
public sealed class BatteryMonitorOptions
|
public sealed class BatteryMonitorOptions
|
||||||
{
|
{
|
||||||
public const string SectionName = "BatteryMonitor";
|
public const string SectionName = "BatteryMonitor";
|
||||||
|
|
||||||
public bool Enabled { get; set; }
|
public bool Enabled { get; init; }
|
||||||
|
|
||||||
public int BatteryThresholdPercent { get; set; } = BatteryMonitorConsts.DefaultBatteryThresholdPercent;
|
public int BatteryThresholdPercent { get; init; } = BatteryMonitorConsts.DefaultBatteryThresholdPercent;
|
||||||
}
|
}
|
||||||
@@ -1,21 +1,52 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
using BoilerMonitor.Models.Enums;
|
using BoilerMonitor.Models.Enums;
|
||||||
|
using BoilerMonitorManager;
|
||||||
using FluentAssertions;
|
using FluentAssertions;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using Moq;
|
using Moq;
|
||||||
using BoilerMonitorManager;
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace BoilerMonitor.Manager.Tests;
|
namespace BoilerMonitor.Manager.Tests;
|
||||||
|
|
||||||
public class BoilerControlServiceTests
|
public class BoilerControlServiceTests
|
||||||
{
|
{
|
||||||
private readonly BoilerControlService _sut;
|
private readonly Mock<ILogger<BoilerControlService>> _loggerMock = new Mock<ILogger<BoilerControlService>>();
|
||||||
|
|
||||||
public BoilerControlServiceTests()
|
private BoilerControlService CreateSut()
|
||||||
{
|
{
|
||||||
var loggerMock = new Mock<ILogger<BoilerControlService>>();
|
return new BoilerControlService(_loggerMock.Object);
|
||||||
_sut = new BoilerControlService(loggerMock.Object);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#region NoChange scenarios
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(true, false, "on", false, false)]
|
||||||
|
[InlineData(false, false, "off", false, false)]
|
||||||
|
[InlineData(false, false, null, false, false)]
|
||||||
|
[InlineData(false, false, "unavailable", false, false)]
|
||||||
|
[InlineData(true, true, "off", false, false)]
|
||||||
|
[InlineData(true, true, null, false, false)]
|
||||||
|
[InlineData(true, false, "off", true, false)]
|
||||||
|
[InlineData(true, false, "off ", true, false)]
|
||||||
|
[InlineData(true, true, "off", true, true)]
|
||||||
|
public void DetermineAction_WhenDesiredStateMatchesCurrentState_ShouldReturnNoChange(
|
||||||
|
bool isNowCheap,
|
||||||
|
bool waterReady,
|
||||||
|
string? switchState,
|
||||||
|
bool budgetExhausted,
|
||||||
|
bool budgetOverride)
|
||||||
|
{
|
||||||
|
var result = CreateSut()
|
||||||
|
.DetermineAction(
|
||||||
|
isNowCheap, waterReady, switchState, budgetExhausted, budgetOverride);
|
||||||
|
|
||||||
|
result.Should().Be(BoilerAction.NoChange);
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
#region TurnOn scenarios
|
#region TurnOn scenarios
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
@@ -23,129 +54,157 @@ public class BoilerControlServiceTests
|
|||||||
[InlineData("OFF")]
|
[InlineData("OFF")]
|
||||||
[InlineData("Off")]
|
[InlineData("Off")]
|
||||||
[InlineData(null)]
|
[InlineData(null)]
|
||||||
|
[InlineData("")]
|
||||||
|
[InlineData(" ")]
|
||||||
|
[InlineData("off ")]
|
||||||
[InlineData("unavailable")]
|
[InlineData("unavailable")]
|
||||||
|
[InlineData("unknown")]
|
||||||
|
[InlineData("0")]
|
||||||
public void DetermineAction_WhenCheapAndWaterNotReadyAndBudgetAvailable_ShouldReturnTurnOn(string? switchState)
|
public void DetermineAction_WhenCheapAndWaterNotReadyAndBudgetAvailable_ShouldReturnTurnOn(string? switchState)
|
||||||
{
|
{
|
||||||
var result = _sut.DetermineAction(
|
var result = CreateSut()
|
||||||
isNowCheap: true, waterReady: false, currentSwitchState: switchState,
|
.DetermineAction(
|
||||||
budgetExhausted: false, budgetOverride: false);
|
true, false, switchState,
|
||||||
|
false, false);
|
||||||
|
|
||||||
result.Should().Be(BoilerAction.TurnOn);
|
result.Should().Be(BoilerAction.TurnOn);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
[InlineData("off")]
|
[InlineData("off", BoilerAction.TurnOn)]
|
||||||
[InlineData(null)]
|
[InlineData(null, BoilerAction.TurnOn)]
|
||||||
public void DetermineAction_WhenBudgetExhaustedButOverrideOn_ShouldReturnTurnOn(string? switchState)
|
[InlineData("unavailable", BoilerAction.TurnOn)]
|
||||||
|
[InlineData("on", BoilerAction.NoChange)]
|
||||||
|
[InlineData("On", BoilerAction.NoChange)]
|
||||||
|
[InlineData("ON", BoilerAction.NoChange)]
|
||||||
|
public void DetermineAction_WhenBudgetExhaustedButOverrideOn_ShouldReturnTurnOnOnlyIfNotAlreadyOn(
|
||||||
|
string? switchState,
|
||||||
|
BoilerAction expectedAction)
|
||||||
{
|
{
|
||||||
var result = _sut.DetermineAction(
|
var result = CreateSut()
|
||||||
isNowCheap: true, waterReady: false, currentSwitchState: switchState,
|
.DetermineAction(
|
||||||
budgetExhausted: true, budgetOverride: true);
|
true, false, switchState,
|
||||||
|
true, true);
|
||||||
|
|
||||||
result.Should().Be(BoilerAction.TurnOn);
|
result.Should().Be(expectedAction);
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
#region TurnOff scenarios
|
#region TurnOff scenarios
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void DetermineAction_WhenNotCheapAndSwitchIsOn_ShouldReturnTurnOff()
|
|
||||||
{
|
|
||||||
var result = _sut.DetermineAction(
|
|
||||||
isNowCheap: false, waterReady: false, currentSwitchState: "on",
|
|
||||||
budgetExhausted: false, budgetOverride: false);
|
|
||||||
|
|
||||||
result.Should().Be(BoilerAction.TurnOff);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void DetermineAction_WhenWaterReadyAndSwitchIsOn_ShouldReturnTurnOff()
|
|
||||||
{
|
|
||||||
var result = _sut.DetermineAction(
|
|
||||||
isNowCheap: true, waterReady: true, currentSwitchState: "on",
|
|
||||||
budgetExhausted: false, budgetOverride: false);
|
|
||||||
|
|
||||||
result.Should().Be(BoilerAction.TurnOff);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void DetermineAction_WhenBudgetExhaustedAndNoOverride_ShouldReturnTurnOff()
|
|
||||||
{
|
|
||||||
var result = _sut.DetermineAction(
|
|
||||||
isNowCheap: true, waterReady: false, currentSwitchState: "on",
|
|
||||||
budgetExhausted: true, budgetOverride: false);
|
|
||||||
|
|
||||||
result.Should().Be(BoilerAction.TurnOff);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
[InlineData("on")]
|
[InlineData("on")]
|
||||||
[InlineData("ON")]
|
[InlineData("ON")]
|
||||||
[InlineData("On")]
|
[InlineData("On")]
|
||||||
public void DetermineAction_WhenNotCheapAndSwitchIsOnCaseInsensitive_ShouldReturnTurnOff(string switchState)
|
[InlineData("oN")]
|
||||||
|
public void DetermineAction_WhenNotCheapAndSwitchIsOn_ShouldReturnTurnOff(string switchState)
|
||||||
{
|
{
|
||||||
var result = _sut.DetermineAction(
|
var result = CreateSut()
|
||||||
isNowCheap: false, waterReady: false, currentSwitchState: switchState,
|
.DetermineAction(
|
||||||
budgetExhausted: false, budgetOverride: false);
|
false, false, switchState,
|
||||||
|
false, false);
|
||||||
|
|
||||||
|
result.Should().Be(BoilerAction.TurnOff);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(true, false, false)] // water ready
|
||||||
|
[InlineData(false, true, false)] // budget exhausted, no override
|
||||||
|
[InlineData(true, true, true)] // water ready wins over the budget override
|
||||||
|
public void DetermineAction_WhenCheapButShouldNotHeatAndSwitchIsOn_ShouldReturnTurnOff(
|
||||||
|
bool waterReady,
|
||||||
|
bool budgetExhausted,
|
||||||
|
bool budgetOverride)
|
||||||
|
{
|
||||||
|
var result = CreateSut()
|
||||||
|
.DetermineAction(
|
||||||
|
true, waterReady, "on",
|
||||||
|
budgetExhausted, budgetOverride);
|
||||||
|
|
||||||
result.Should().Be(BoilerAction.TurnOff);
|
result.Should().Be(BoilerAction.TurnOff);
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
#region NoChange scenarios
|
#region Comprehensive truth tables
|
||||||
|
|
||||||
[Fact]
|
/// <summary>
|
||||||
public void DetermineAction_WhenCheapAndNotReadyAndAlreadyOn_ShouldReturnNoChange()
|
/// Complete truth table for a boiler that is currently ON: it may only stay on when
|
||||||
|
/// it is cheap, water is not ready and the budget is available (or overridden).
|
||||||
|
/// </summary>
|
||||||
|
public static TheoryData<bool, bool, bool, bool, BoilerAction> SwitchOnActionMatrix => new TheoryData<bool, bool, bool, bool, BoilerAction>
|
||||||
{
|
{
|
||||||
var result = _sut.DetermineAction(
|
{ false, false, false, false, BoilerAction.TurnOff },
|
||||||
isNowCheap: true, waterReady: false, currentSwitchState: "on",
|
{ false, false, false, true, BoilerAction.TurnOff },
|
||||||
budgetExhausted: false, budgetOverride: false);
|
{ false, false, true, false, BoilerAction.TurnOff },
|
||||||
|
{ false, false, true, true, BoilerAction.TurnOff },
|
||||||
result.Should().Be(BoilerAction.NoChange);
|
{ false, true, false, false, BoilerAction.TurnOff },
|
||||||
}
|
{ false, true, false, true, BoilerAction.TurnOff },
|
||||||
|
{ false, true, true, false, BoilerAction.TurnOff },
|
||||||
[Fact]
|
{ false, true, true, true, BoilerAction.TurnOff },
|
||||||
public void DetermineAction_WhenNotCheapAndAlreadyOff_ShouldReturnNoChange()
|
{ true, false, false, false, BoilerAction.NoChange },
|
||||||
{
|
{ true, false, false, true, BoilerAction.NoChange },
|
||||||
var result = _sut.DetermineAction(
|
{ true, false, true, false, BoilerAction.TurnOff },
|
||||||
isNowCheap: false, waterReady: false, currentSwitchState: "off",
|
{ true, false, true, true, BoilerAction.NoChange },
|
||||||
budgetExhausted: false, budgetOverride: false);
|
{ true, true, false, false, BoilerAction.TurnOff },
|
||||||
|
{ true, true, false, true, BoilerAction.TurnOff },
|
||||||
result.Should().Be(BoilerAction.NoChange);
|
{ true, true, true, false, BoilerAction.TurnOff },
|
||||||
}
|
{ true, true, true, true, BoilerAction.TurnOff }
|
||||||
|
};
|
||||||
[Fact]
|
|
||||||
public void DetermineAction_WhenBudgetExhaustedAndAlreadyOff_ShouldReturnNoChange()
|
|
||||||
{
|
|
||||||
var result = _sut.DetermineAction(
|
|
||||||
isNowCheap: true, waterReady: false, currentSwitchState: "off",
|
|
||||||
budgetExhausted: true, budgetOverride: false);
|
|
||||||
|
|
||||||
result.Should().Be(BoilerAction.NoChange);
|
|
||||||
}
|
|
||||||
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
#region Comprehensive theory covering all key combinations
|
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
[InlineData(true, false, "off", false, false, BoilerAction.TurnOn)]
|
[MemberData(nameof(SwitchOnActionMatrix))]
|
||||||
[InlineData(true, false, "on", false, false, BoilerAction.NoChange)]
|
public void DetermineAction_AllCombinationsWhileSwitchIsOn_ShouldReturnExpectedAction(
|
||||||
[InlineData(true, true, "on", false, false, BoilerAction.TurnOff)]
|
bool isNowCheap,
|
||||||
[InlineData(true, true, "off", false, false, BoilerAction.NoChange)]
|
bool waterReady,
|
||||||
[InlineData(false, false, "on", false, false, BoilerAction.TurnOff)]
|
bool budgetExhausted,
|
||||||
[InlineData(false, false, "off", false, false, BoilerAction.NoChange)]
|
bool budgetOverride,
|
||||||
[InlineData(true, false, "on", true, false, BoilerAction.TurnOff)]
|
BoilerAction expectedAction)
|
||||||
[InlineData(true, false, "off", true, false, BoilerAction.NoChange)]
|
|
||||||
[InlineData(true, false, "off", true, true, BoilerAction.TurnOn)]
|
|
||||||
[InlineData(true, false, "on", true, true, BoilerAction.NoChange)]
|
|
||||||
public void DetermineAction_AllCombinations_ShouldReturnExpectedAction(
|
|
||||||
bool isNowCheap, bool waterReady, string switchState,
|
|
||||||
bool budgetExhausted, bool budgetOverride, BoilerAction expectedAction)
|
|
||||||
{
|
{
|
||||||
var result = _sut.DetermineAction(isNowCheap, waterReady, switchState, budgetExhausted, budgetOverride);
|
var result = CreateSut()
|
||||||
|
.DetermineAction(
|
||||||
|
isNowCheap, waterReady, "on", budgetExhausted, budgetOverride);
|
||||||
|
|
||||||
|
result.Should().Be(expectedAction);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Complete truth table for a boiler that is currently OFF: it may only turn on when
|
||||||
|
/// it is cheap, water is not ready and the budget is available (or overridden).
|
||||||
|
/// </summary>
|
||||||
|
public static TheoryData<bool, bool, bool, bool, BoilerAction> SwitchOffActionMatrix => new TheoryData<bool, bool, bool, bool, BoilerAction>
|
||||||
|
{
|
||||||
|
{ false, false, false, false, BoilerAction.NoChange },
|
||||||
|
{ false, false, false, true, BoilerAction.NoChange },
|
||||||
|
{ false, false, true, false, BoilerAction.NoChange },
|
||||||
|
{ false, false, true, true, BoilerAction.NoChange },
|
||||||
|
{ false, true, false, false, BoilerAction.NoChange },
|
||||||
|
{ false, true, false, true, BoilerAction.NoChange },
|
||||||
|
{ false, true, true, false, BoilerAction.NoChange },
|
||||||
|
{ false, true, true, true, BoilerAction.NoChange },
|
||||||
|
{ true, false, false, false, BoilerAction.TurnOn },
|
||||||
|
{ true, false, false, true, BoilerAction.TurnOn },
|
||||||
|
{ true, false, true, false, BoilerAction.NoChange },
|
||||||
|
{ true, false, true, true, BoilerAction.TurnOn },
|
||||||
|
{ true, true, false, false, BoilerAction.NoChange },
|
||||||
|
{ true, true, false, true, BoilerAction.NoChange },
|
||||||
|
{ true, true, true, false, BoilerAction.NoChange },
|
||||||
|
{ true, true, true, true, BoilerAction.NoChange }
|
||||||
|
};
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(SwitchOffActionMatrix))]
|
||||||
|
public void DetermineAction_AllCombinationsWhileSwitchIsOff_ShouldReturnExpectedAction(
|
||||||
|
bool isNowCheap,
|
||||||
|
bool waterReady,
|
||||||
|
bool budgetExhausted,
|
||||||
|
bool budgetOverride,
|
||||||
|
BoilerAction expectedAction)
|
||||||
|
{
|
||||||
|
var result = CreateSut()
|
||||||
|
.DetermineAction(
|
||||||
|
isNowCheap, waterReady, "off", budgetExhausted, budgetOverride);
|
||||||
|
|
||||||
result.Should().Be(expectedAction);
|
result.Should().Be(expectedAction);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,28 +8,31 @@
|
|||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="coverlet.collector" Version="8.0.0">
|
<PackageReference Include="coverlet.collector" Version="10.1.1">
|
||||||
<PrivateAssets>all</PrivateAssets>
|
<PrivateAssets>all</PrivateAssets>
|
||||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
</PackageReference>
|
</PackageReference>
|
||||||
<PackageReference Include="Microsoft.Extensions.TimeProvider.Testing" Version="10.4.0" />
|
<PackageReference Include="Microsoft.Extensions.TimeProvider.Testing" Version="11.0.1"/>
|
||||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.3.0" />
|
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.12.0"/>
|
||||||
<PackageReference Include="xunit" Version="2.9.3" />
|
<PackageReference Include="xunit" Version="2.9.3"/>
|
||||||
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5">
|
<PackageReference Include="xunit.runner.visualstudio" Version="4.0.1">
|
||||||
<PrivateAssets>all</PrivateAssets>
|
<PrivateAssets>all</PrivateAssets>
|
||||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
</PackageReference>
|
</PackageReference>
|
||||||
<PackageReference Include="FluentAssertions" Version="8.8.0" />
|
<PackageReference Include="FluentAssertions" Version="8.11.0"/>
|
||||||
<PackageReference Include="Moq" Version="4.20.72" />
|
<PackageReference Include="Moq" Version="4.21.0"/>
|
||||||
|
<PackageReference Include="NetDaemon.Extensions.Mqtt" Version="26.43.1"/>
|
||||||
|
<PackageReference Include="NetDaemon.HassModel" Version="26.43.1"/>
|
||||||
|
<PackageReference Include="System.Reactive" Version="7.0.0"/>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<Using Include="Xunit" />
|
<Using Include="Xunit"/>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\BoilerMonitor.Manager\BoilerMonitor.Manager.csproj" />
|
<ProjectReference Include="..\BoilerMonitor.Manager\BoilerMonitor.Manager.csproj"/>
|
||||||
<ProjectReference Include="..\BoilerMonitor.Models\BoilerMonitor.Models.csproj" />
|
<ProjectReference Include="..\BoilerMonitor.Models\BoilerMonitor.Models.csproj"/>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
@@ -1,133 +1,74 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
using FluentAssertions;
|
using FluentAssertions;
|
||||||
using BoilerMonitorManager.Models;
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace BoilerMonitor.Manager.Tests;
|
namespace BoilerMonitor.Manager.Tests;
|
||||||
|
|
||||||
public class BoilerMonitorConfigTests
|
public class BoilerMonitorConfigTests
|
||||||
{
|
{
|
||||||
[Fact]
|
private const string PowerEntityId = BoilerMonitorTestData.PowerEntityId;
|
||||||
public void IsFullyConfigured_WhenAllFieldsSet_ShouldReturnTrue()
|
private const string SwitchEntityId = BoilerMonitorTestData.SwitchEntityId;
|
||||||
|
|
||||||
|
public static TheoryData<string, string?, string?, int?, double?, bool> ConfigurationCases => new TheoryData<string, string?, string?, int?, double?, bool>
|
||||||
{
|
{
|
||||||
var config = new BoilerMonitorConfig
|
{ "fully configured", PowerEntityId, SwitchEntityId, 30, 5.0, true },
|
||||||
{
|
{ "minimum valid poll interval and threshold", PowerEntityId, SwitchEntityId, 5, 1.0, true },
|
||||||
BoilerPowerEntityId = "sensor.sonoff_1002230e32_power",
|
{ "poll interval of one second", PowerEntityId, SwitchEntityId, 1, 5.0, true },
|
||||||
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
|
{ "maximum poll interval", PowerEntityId, SwitchEntityId, int.MaxValue, 5.0, true },
|
||||||
PollIntervalSeconds = 30,
|
{ "smallest positive threshold", PowerEntityId, SwitchEntityId, 30, double.Epsilon, true },
|
||||||
HeatingPowerThresholdWatts = 5.0
|
{ "maximum threshold", PowerEntityId, SwitchEntityId, 30, double.MaxValue, true },
|
||||||
|
{ "infinite threshold", PowerEntityId, SwitchEntityId, 30, double.PositiveInfinity, true },
|
||||||
|
|
||||||
|
{ "power entity id null", null, SwitchEntityId, 30, 5.0, false },
|
||||||
|
{ "power entity id empty", string.Empty, SwitchEntityId, 30, 5.0, false },
|
||||||
|
{ "power entity id whitespace", " ", SwitchEntityId, 30, 5.0, false },
|
||||||
|
{ "power entity id tabs and newlines", "\t\n", SwitchEntityId, 30, 5.0, false },
|
||||||
|
{ "switch entity id null", PowerEntityId, null, 30, 5.0, false },
|
||||||
|
{ "switch entity id empty", PowerEntityId, string.Empty, 30, 5.0, false },
|
||||||
|
{ "switch entity id whitespace", PowerEntityId, " ", 30, 5.0, false },
|
||||||
|
{ "both entity ids null", null, null, 30, 5.0, false },
|
||||||
|
|
||||||
|
{ "poll interval null", PowerEntityId, SwitchEntityId, null, 5.0, false },
|
||||||
|
{ "poll interval zero", PowerEntityId, SwitchEntityId, 0, 5.0, false },
|
||||||
|
{ "poll interval negative", PowerEntityId, SwitchEntityId, -1, 5.0, false },
|
||||||
|
{ "poll interval minimum value", PowerEntityId, SwitchEntityId, int.MinValue, 5.0, false },
|
||||||
|
|
||||||
|
{ "threshold null", PowerEntityId, SwitchEntityId, 30, null, false },
|
||||||
|
{ "threshold zero", PowerEntityId, SwitchEntityId, 30, 0.0, false },
|
||||||
|
{ "threshold negative", PowerEntityId, SwitchEntityId, 30, -1.0, false },
|
||||||
|
{ "threshold minimum value", PowerEntityId, SwitchEntityId, 30, double.MinValue, false },
|
||||||
|
{ "threshold NaN", PowerEntityId, SwitchEntityId, 30, double.NaN, false },
|
||||||
|
{ "threshold negative infinity", PowerEntityId, SwitchEntityId, 30, double.NegativeInfinity, false }
|
||||||
};
|
};
|
||||||
|
|
||||||
config.IsFullyConfigured.Should().BeTrue();
|
[Theory]
|
||||||
|
[MemberData(nameof(ConfigurationCases))]
|
||||||
|
public void IsFullyConfigured_ShouldValidateEveryRequiredField(
|
||||||
|
string scenario,
|
||||||
|
string? powerEntityId,
|
||||||
|
string? switchEntityId,
|
||||||
|
int? pollIntervalSeconds,
|
||||||
|
double? heatingPowerThresholdWatts,
|
||||||
|
bool expected)
|
||||||
|
{
|
||||||
|
var config = BoilerMonitorTestData.CreateConfig(
|
||||||
|
powerEntityId,
|
||||||
|
switchEntityId,
|
||||||
|
pollIntervalSeconds,
|
||||||
|
heatingPowerThresholdWatts);
|
||||||
|
|
||||||
|
config.IsFullyConfigured.Should().Be(expected, scenario);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void IsFullyConfigured_WhenPowerEntityMissing_ShouldReturnFalse()
|
public void IsFullyConfigured_WhenFullyPopulated_ShouldNotDependOnEntityIdCasingOrPadding()
|
||||||
{
|
{
|
||||||
var config = new BoilerMonitorConfig
|
var config = BoilerMonitorTestData.CreateConfig(
|
||||||
{
|
" sensor.sonoff_1002230e32_power ",
|
||||||
BoilerPowerEntityId = null,
|
"SWITCH.SONOFF_1002230E32");
|
||||||
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
|
|
||||||
PollIntervalSeconds = 30,
|
|
||||||
HeatingPowerThresholdWatts = 5.0
|
|
||||||
};
|
|
||||||
|
|
||||||
config.IsFullyConfigured.Should().BeFalse();
|
config.IsFullyConfigured.Should().BeTrue("entity ids are only checked for non-whitespace content");
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void IsFullyConfigured_WhenSwitchEntityMissing_ShouldReturnFalse()
|
|
||||||
{
|
|
||||||
var config = new BoilerMonitorConfig
|
|
||||||
{
|
|
||||||
BoilerPowerEntityId = "sensor.sonoff_1002230e32_power",
|
|
||||||
BoilerSwitchEntityId = null,
|
|
||||||
PollIntervalSeconds = 30,
|
|
||||||
HeatingPowerThresholdWatts = 5.0
|
|
||||||
};
|
|
||||||
|
|
||||||
config.IsFullyConfigured.Should().BeFalse();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void IsFullyConfigured_WhenPollIntervalMissing_ShouldReturnFalse()
|
|
||||||
{
|
|
||||||
var config = new BoilerMonitorConfig
|
|
||||||
{
|
|
||||||
BoilerPowerEntityId = "sensor.sonoff_1002230e32_power",
|
|
||||||
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
|
|
||||||
PollIntervalSeconds = null,
|
|
||||||
HeatingPowerThresholdWatts = 5.0
|
|
||||||
};
|
|
||||||
|
|
||||||
config.IsFullyConfigured.Should().BeFalse();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void IsFullyConfigured_WhenThresholdMissing_ShouldReturnFalse()
|
|
||||||
{
|
|
||||||
var config = new BoilerMonitorConfig
|
|
||||||
{
|
|
||||||
BoilerPowerEntityId = "sensor.sonoff_1002230e32_power",
|
|
||||||
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
|
|
||||||
PollIntervalSeconds = 30,
|
|
||||||
HeatingPowerThresholdWatts = null
|
|
||||||
};
|
|
||||||
|
|
||||||
config.IsFullyConfigured.Should().BeFalse();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void IsFullyConfigured_WhenPowerEntityIsWhitespace_ShouldReturnFalse()
|
|
||||||
{
|
|
||||||
var config = new BoilerMonitorConfig
|
|
||||||
{
|
|
||||||
BoilerPowerEntityId = " ",
|
|
||||||
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
|
|
||||||
PollIntervalSeconds = 30,
|
|
||||||
HeatingPowerThresholdWatts = 5.0
|
|
||||||
};
|
|
||||||
|
|
||||||
config.IsFullyConfigured.Should().BeFalse();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void IsFullyConfigured_WhenPollIntervalIsZero_ShouldReturnFalse()
|
|
||||||
{
|
|
||||||
var config = new BoilerMonitorConfig
|
|
||||||
{
|
|
||||||
BoilerPowerEntityId = "sensor.sonoff_1002230e32_power",
|
|
||||||
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
|
|
||||||
PollIntervalSeconds = 0,
|
|
||||||
HeatingPowerThresholdWatts = 5.0
|
|
||||||
};
|
|
||||||
|
|
||||||
config.IsFullyConfigured.Should().BeFalse();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void IsFullyConfigured_WhenThresholdIsZero_ShouldReturnFalse()
|
|
||||||
{
|
|
||||||
var config = new BoilerMonitorConfig
|
|
||||||
{
|
|
||||||
BoilerPowerEntityId = "sensor.sonoff_1002230e32_power",
|
|
||||||
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
|
|
||||||
PollIntervalSeconds = 30,
|
|
||||||
HeatingPowerThresholdWatts = 0.0
|
|
||||||
};
|
|
||||||
|
|
||||||
config.IsFullyConfigured.Should().BeFalse();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void IsFullyConfigured_WhenPollIntervalIsNegative_ShouldReturnFalse()
|
|
||||||
{
|
|
||||||
var config = new BoilerMonitorConfig
|
|
||||||
{
|
|
||||||
BoilerPowerEntityId = "sensor.sonoff_1002230e32_power",
|
|
||||||
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
|
|
||||||
PollIntervalSeconds = -1,
|
|
||||||
HeatingPowerThresholdWatts = 5.0
|
|
||||||
};
|
|
||||||
|
|
||||||
config.IsFullyConfigured.Should().BeFalse();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,285 +1,466 @@
|
|||||||
using BoilerMonitor.Models;
|
#region
|
||||||
|
|
||||||
|
using System.Text.Json;
|
||||||
using BoilerMonitorManager;
|
using BoilerMonitorManager;
|
||||||
using BoilerMonitorManager.Models;
|
|
||||||
using FluentAssertions;
|
using FluentAssertions;
|
||||||
using HomeAssistant.Entities.Interfaces;
|
using HomeAssistant.Entities.Interfaces;
|
||||||
|
using HomeAssistant.Models;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using Moq;
|
using Moq;
|
||||||
using NetDaemon.HassModel;
|
using NetDaemon.HassModel;
|
||||||
using NetDaemon.HassModel.Entities;
|
|
||||||
using static BoilerMonitor.Models.BoilerMonitorConsts;
|
using static BoilerMonitor.Models.BoilerMonitorConsts;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace BoilerMonitor.Manager.Tests;
|
namespace BoilerMonitor.Manager.Tests;
|
||||||
|
|
||||||
public class BoilerMonitorEntityServiceTests
|
public class BoilerMonitorEntityServiceTests
|
||||||
{
|
{
|
||||||
private readonly Mock<IEntityManager> _entityManagerMock;
|
/// <summary>Every entity that <c>CleanupEntitiesAsync</c> is expected to remove.</summary>
|
||||||
private readonly Mock<IHaContext> _haContextMock;
|
private static readonly string[] CleanableEntityIds =
|
||||||
private readonly Mock<ILogger<BoilerMonitorEntityService>> _loggerMock;
|
[
|
||||||
private readonly BoilerMonitorEntityService _sut;
|
ConfigPowerEntityId,
|
||||||
|
ConfigSwitchEntityId,
|
||||||
|
ConfigPollIntervalEntityId,
|
||||||
|
ConfigHeatingThresholdEntityId,
|
||||||
|
StatusEntityId,
|
||||||
|
WaterReadyEntityId,
|
||||||
|
SkipPriceCapEntityId,
|
||||||
|
TodayRuntimeEntityId,
|
||||||
|
RemainingTimeEntityId,
|
||||||
|
BudgetPercentageEntityId,
|
||||||
|
BudgetExhaustedEntityId,
|
||||||
|
SessionCountEntityId,
|
||||||
|
BudgetOverrideEntityId,
|
||||||
|
AutoManagementEntityId
|
||||||
|
];
|
||||||
|
|
||||||
|
private readonly Mock<IEntityManager> _entityManagerMock = new Mock<IEntityManager>();
|
||||||
|
private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
|
||||||
|
private readonly Mock<ILogger<BoilerMonitorEntityService>> _loggerMock = new Mock<ILogger<BoilerMonitorEntityService>>();
|
||||||
|
|
||||||
public BoilerMonitorEntityServiceTests()
|
public BoilerMonitorEntityServiceTests()
|
||||||
{
|
{
|
||||||
_entityManagerMock = new Mock<IEntityManager>();
|
_entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny<EntityCreateModel>()))
|
||||||
_haContextMock = new Mock<IHaContext>();
|
.Returns(Task.CompletedTask);
|
||||||
_loggerMock = new Mock<ILogger<BoilerMonitorEntityService>>();
|
|
||||||
_sut = new BoilerMonitorEntityService(
|
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
||||||
|
.Returns(Task.CompletedTask);
|
||||||
|
|
||||||
|
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
|
||||||
|
.Returns(Task.CompletedTask);
|
||||||
|
|
||||||
|
_entityManagerMock.Setup(em => em.RemoveEntity(It.IsAny<string>()))
|
||||||
|
.Returns(Task.CompletedTask);
|
||||||
|
}
|
||||||
|
|
||||||
|
private BoilerMonitorEntityService CreateSut()
|
||||||
|
{
|
||||||
|
return new BoilerMonitorEntityService(
|
||||||
_entityManagerMock.Object,
|
_entityManagerMock.Object,
|
||||||
_haContextMock.Object,
|
_haContextMock.Object,
|
||||||
_loggerMock.Object);
|
_loggerMock.Object);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void SetupEntityState(string entityId, string? state)
|
#region ReadPersistedState
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(BoilerMonitorTestData.RuntimeStateSamples), MemberType = typeof(BoilerMonitorTestData))]
|
||||||
|
public void ReadPersistedState_WhenRuntimeStateVaries_ShouldParseOrReject(
|
||||||
|
string? runtimeState,
|
||||||
|
TimeSpan? expectedRunTime)
|
||||||
{
|
{
|
||||||
if (state is null)
|
_haContextMock.SetupEntityStates(
|
||||||
|
BoilerMonitorTestData.CreatePersistedEntityStates(runtimeState, "2"));
|
||||||
|
|
||||||
|
var result = CreateSut().ReadPersistedState();
|
||||||
|
|
||||||
|
if (expectedRunTime is null)
|
||||||
{
|
{
|
||||||
_haContextMock.Setup(h => h.GetState(entityId)).Returns((EntityState?)null);
|
result.Should().BeNull();
|
||||||
}
|
|
||||||
else
|
return;
|
||||||
{
|
|
||||||
_haContextMock.Setup(h => h.GetState(entityId))
|
|
||||||
.Returns(new EntityState { State = state });
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#region ReadPersistedState
|
result.Should().NotBeNull();
|
||||||
|
result.AccumulatedRunTime.Should().Be(expectedRunTime.Value);
|
||||||
|
result.SessionCount.Should().Be(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(BoilerMonitorTestData.SessionCountStateSamples), MemberType = typeof(BoilerMonitorTestData))]
|
||||||
|
public void ReadPersistedState_WhenSessionCountStateVaries_ShouldParseOrReject(
|
||||||
|
string? sessionCountState,
|
||||||
|
int? expectedSessionCount)
|
||||||
|
{
|
||||||
|
_haContextMock.SetupEntityStates(
|
||||||
|
BoilerMonitorTestData.CreatePersistedEntityStates("3600", sessionCountState));
|
||||||
|
|
||||||
|
var result = CreateSut().ReadPersistedState();
|
||||||
|
|
||||||
|
if (expectedSessionCount is null)
|
||||||
|
{
|
||||||
|
result.Should().BeNull();
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
result.Should().NotBeNull();
|
||||||
|
result.AccumulatedRunTime.Should().Be(TimeSpan.FromHours(1));
|
||||||
|
result.SessionCount.Should().Be(expectedSessionCount.Value);
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ReadPersistedState_WithValidState_ShouldReturnPersistedValues()
|
public void ReadPersistedState_WithValidState_ShouldReturnPersistedValues()
|
||||||
{
|
{
|
||||||
// Arrange
|
_haContextMock.SetupEntityStates(BoilerMonitorTestData.CreatePersistedEntityStates(
|
||||||
SetupEntityState(TodayRuntimeEntityId, "7200");
|
"7200", "3", "ON"));
|
||||||
SetupEntityState(SessionCountEntityId, "3");
|
|
||||||
SetupEntityState(SkipPriceCapEntityId, "ON");
|
|
||||||
SetupEntityState(BudgetOverrideEntityId, "OFF");
|
|
||||||
|
|
||||||
// Act
|
var result = CreateSut().ReadPersistedState();
|
||||||
var result = _sut.ReadPersistedState();
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
result.Should().NotBeNull();
|
result.Should().NotBeNull();
|
||||||
result!.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(7200));
|
result.AccumulatedRunTime.Should().Be(TimeSpan.FromHours(2));
|
||||||
result.SessionCount.Should().Be(3);
|
result.SessionCount.Should().Be(3);
|
||||||
result.SkipPriceCapState.Should().Be("ON");
|
result.SkipPriceCapState.Should().Be("ON");
|
||||||
result.BudgetOverrideState.Should().Be("OFF");
|
result.BudgetOverrideState.Should().Be("OFF");
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Theory]
|
||||||
public void ReadPersistedState_WithZeroRuntime_ShouldReturnZeroValues()
|
[InlineData("ON")]
|
||||||
|
[InlineData("on")]
|
||||||
|
[InlineData(" On ")]
|
||||||
|
[InlineData("")]
|
||||||
|
[InlineData(null)]
|
||||||
|
public void ReadPersistedState_ShouldReturnRawSwitchStates(string? switchState)
|
||||||
{
|
{
|
||||||
// Arrange
|
_haContextMock.SetupEntityStates(BoilerMonitorTestData.CreatePersistedEntityStates(
|
||||||
SetupEntityState(TodayRuntimeEntityId, "0");
|
skipPriceCap: switchState, budgetOverride: switchState));
|
||||||
SetupEntityState(SessionCountEntityId, "0");
|
|
||||||
SetupEntityState(SkipPriceCapEntityId, "OFF");
|
|
||||||
SetupEntityState(BudgetOverrideEntityId, "OFF");
|
|
||||||
|
|
||||||
// Act
|
var result = CreateSut().ReadPersistedState();
|
||||||
var result = _sut.ReadPersistedState();
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
result.Should().NotBeNull();
|
result.Should().NotBeNull();
|
||||||
result!.AccumulatedRunTime.Should().Be(TimeSpan.Zero);
|
result.SkipPriceCapState.Should().Be(switchState);
|
||||||
result.SessionCount.Should().Be(0);
|
result.BudgetOverrideState.Should().Be(switchState);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ReadPersistedState_WhenRuntimeIsUnavailable_ShouldReturnNull()
|
public void ReadPersistedState_WhenBothRuntimeEntitiesDoNotExist_ShouldReturnNull()
|
||||||
{
|
{
|
||||||
// Arrange
|
_haContextMock.SetupEntityStates(
|
||||||
SetupEntityState(TodayRuntimeEntityId, "unavailable");
|
BoilerMonitorTestData.CreatePersistedEntityStates(null, null));
|
||||||
SetupEntityState(SessionCountEntityId, "3");
|
|
||||||
SetupEntityState(SkipPriceCapEntityId, "OFF");
|
|
||||||
SetupEntityState(BudgetOverrideEntityId, "OFF");
|
|
||||||
|
|
||||||
// Act
|
CreateSut().ReadPersistedState().Should().BeNull();
|
||||||
var result = _sut.ReadPersistedState();
|
}
|
||||||
|
|
||||||
// Assert
|
#endregion
|
||||||
result.Should().BeNull();
|
|
||||||
|
#region ReadPersistedCooldownTimestamp
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ReadPersistedCooldownTimestamp_WithValidIsoString_ShouldReturnTimestamp()
|
||||||
|
{
|
||||||
|
var cooldownSince = BoilerMonitorTestData.BaseTime - TimeSpan.FromMinutes(30);
|
||||||
|
|
||||||
|
_haContextMock.SetupEntityState(
|
||||||
|
WaterReadyEntityId,
|
||||||
|
BoilerMonitorTestData.CreateWaterReadyEntityStateWithCooldown(cooldownSince.ToString("O")));
|
||||||
|
|
||||||
|
var result = CreateSut().ReadPersistedCooldownTimestamp();
|
||||||
|
|
||||||
|
result.Should().Be(cooldownSince);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ReadPersistedState_WhenRuntimeIsUnknown_ShouldReturnNull()
|
public void ReadPersistedCooldownTimestamp_WithUtcDesignator_ShouldReturnTimestamp()
|
||||||
{
|
{
|
||||||
// Arrange
|
var cooldownSince = new DateTimeOffset(2026, 3, 31, 9, 15, 0, TimeSpan.Zero);
|
||||||
SetupEntityState(TodayRuntimeEntityId, "unknown");
|
|
||||||
SetupEntityState(SessionCountEntityId, "2");
|
|
||||||
SetupEntityState(SkipPriceCapEntityId, "OFF");
|
|
||||||
SetupEntityState(BudgetOverrideEntityId, "OFF");
|
|
||||||
|
|
||||||
// Act
|
_haContextMock.SetupEntityState(
|
||||||
var result = _sut.ReadPersistedState();
|
WaterReadyEntityId,
|
||||||
|
BoilerMonitorTestData.CreateWaterReadyEntityStateWithCooldown("2026-03-31T09:15:00Z"));
|
||||||
|
|
||||||
// Assert
|
var result = CreateSut().ReadPersistedCooldownTimestamp();
|
||||||
result.Should().BeNull();
|
|
||||||
|
result.Should().Be(cooldownSince);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ReadPersistedState_WhenSessionCountIsUnavailable_ShouldReturnNull()
|
public void ReadPersistedCooldownTimestamp_WhenEntityDoesNotExist_ShouldReturnNull()
|
||||||
{
|
{
|
||||||
// Arrange
|
_haContextMock.SetupEntityState(WaterReadyEntityId, null);
|
||||||
SetupEntityState(TodayRuntimeEntityId, "3600");
|
|
||||||
SetupEntityState(SessionCountEntityId, "unavailable");
|
|
||||||
SetupEntityState(SkipPriceCapEntityId, "OFF");
|
|
||||||
SetupEntityState(BudgetOverrideEntityId, "OFF");
|
|
||||||
|
|
||||||
// Act
|
CreateSut().ReadPersistedCooldownTimestamp().Should().BeNull();
|
||||||
var result = _sut.ReadPersistedState();
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
result.Should().BeNull();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ReadPersistedState_WhenRuntimeEntityDoesNotExist_ShouldReturnNull()
|
public void ReadPersistedCooldownTimestamp_WhenEntityHasNoAttributes_ShouldReturnNull()
|
||||||
{
|
{
|
||||||
// Arrange
|
_haContextMock.SetupEntityState(WaterReadyEntityId, BoilerMonitorTestData.CreateEntityState("yes"));
|
||||||
SetupEntityState(TodayRuntimeEntityId, null);
|
|
||||||
SetupEntityState(SessionCountEntityId, "2");
|
|
||||||
SetupEntityState(SkipPriceCapEntityId, "OFF");
|
|
||||||
SetupEntityState(BudgetOverrideEntityId, "OFF");
|
|
||||||
|
|
||||||
// Act
|
CreateSut().ReadPersistedCooldownTimestamp().Should().BeNull();
|
||||||
var result = _sut.ReadPersistedState();
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
result.Should().BeNull();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ReadPersistedState_WhenSessionCountEntityDoesNotExist_ShouldReturnNull()
|
public void ReadPersistedCooldownTimestamp_WhenAttributeIsMissing_ShouldReturnNull()
|
||||||
{
|
{
|
||||||
// Arrange
|
_haContextMock.SetupEntityState(
|
||||||
SetupEntityState(TodayRuntimeEntityId, "3600");
|
WaterReadyEntityId,
|
||||||
SetupEntityState(SessionCountEntityId, null);
|
BoilerMonitorTestData.CreateEntityStateWithAttributes(
|
||||||
SetupEntityState(SkipPriceCapEntityId, "OFF");
|
new Dictionary<string, object?> { ["friendly_name"] = "Boiler water ready" }));
|
||||||
SetupEntityState(BudgetOverrideEntityId, "OFF");
|
|
||||||
|
|
||||||
// Act
|
CreateSut().ReadPersistedCooldownTimestamp().Should().BeNull();
|
||||||
var result = _sut.ReadPersistedState();
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
result.Should().BeNull();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void ReadPersistedState_WhenRuntimeIsNonNumeric_ShouldReturnNull()
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
SetupEntityState(TodayRuntimeEntityId, "not_a_number");
|
|
||||||
SetupEntityState(SessionCountEntityId, "2");
|
|
||||||
SetupEntityState(SkipPriceCapEntityId, "OFF");
|
|
||||||
SetupEntityState(BudgetOverrideEntityId, "OFF");
|
|
||||||
|
|
||||||
// Act
|
|
||||||
var result = _sut.ReadPersistedState();
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
result.Should().BeNull();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void ReadPersistedState_WhenSessionCountIsNonNumeric_ShouldReturnNull()
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
SetupEntityState(TodayRuntimeEntityId, "3600");
|
|
||||||
SetupEntityState(SessionCountEntityId, "abc");
|
|
||||||
SetupEntityState(SkipPriceCapEntityId, "OFF");
|
|
||||||
SetupEntityState(BudgetOverrideEntityId, "OFF");
|
|
||||||
|
|
||||||
// Act
|
|
||||||
var result = _sut.ReadPersistedState();
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
result.Should().BeNull();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void ReadPersistedState_WhenRuntimeIsNegative_ShouldReturnNull()
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
SetupEntityState(TodayRuntimeEntityId, "-100");
|
|
||||||
SetupEntityState(SessionCountEntityId, "2");
|
|
||||||
SetupEntityState(SkipPriceCapEntityId, "OFF");
|
|
||||||
SetupEntityState(BudgetOverrideEntityId, "OFF");
|
|
||||||
|
|
||||||
// Act
|
|
||||||
var result = _sut.ReadPersistedState();
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
result.Should().BeNull();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void ReadPersistedState_WhenSessionCountIsNegative_ShouldReturnNull()
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
SetupEntityState(TodayRuntimeEntityId, "3600");
|
|
||||||
SetupEntityState(SessionCountEntityId, "-1");
|
|
||||||
SetupEntityState(SkipPriceCapEntityId, "OFF");
|
|
||||||
SetupEntityState(BudgetOverrideEntityId, "OFF");
|
|
||||||
|
|
||||||
// Act
|
|
||||||
var result = _sut.ReadPersistedState();
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
result.Should().BeNull();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void ReadPersistedState_WhenSwitchEntitiesAreNull_ShouldStillReturnWithNullSwitchStates()
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
SetupEntityState(TodayRuntimeEntityId, "1800");
|
|
||||||
SetupEntityState(SessionCountEntityId, "1");
|
|
||||||
SetupEntityState(SkipPriceCapEntityId, null);
|
|
||||||
SetupEntityState(BudgetOverrideEntityId, null);
|
|
||||||
|
|
||||||
// Act
|
|
||||||
var result = _sut.ReadPersistedState();
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
result.Should().NotBeNull();
|
|
||||||
result!.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(1800));
|
|
||||||
result.SessionCount.Should().Be(1);
|
|
||||||
result.SkipPriceCapState.Should().BeNull();
|
|
||||||
result.BudgetOverrideState.Should().BeNull();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
[InlineData("")] // empty string
|
[InlineData(null)]
|
||||||
[InlineData(" ")] // whitespace
|
[InlineData(42)]
|
||||||
public void ReadPersistedState_WhenRuntimeIsEmptyOrWhitespace_ShouldReturnNull(string state)
|
[InlineData(true)]
|
||||||
|
[InlineData("")]
|
||||||
|
[InlineData(" ")]
|
||||||
|
[InlineData("not-a-timestamp")]
|
||||||
|
[InlineData("2026-13-45T99:99:99")]
|
||||||
|
[InlineData("unavailable")]
|
||||||
|
public void ReadPersistedCooldownTimestamp_WhenAttributeIsNotAValidTimestamp_ShouldReturnNull(object? cooldownSince)
|
||||||
{
|
{
|
||||||
// Arrange
|
_haContextMock.SetupEntityState(
|
||||||
SetupEntityState(TodayRuntimeEntityId, state);
|
WaterReadyEntityId,
|
||||||
SetupEntityState(SessionCountEntityId, "2");
|
BoilerMonitorTestData.CreateWaterReadyEntityStateWithCooldown(cooldownSince));
|
||||||
SetupEntityState(SkipPriceCapEntityId, "OFF");
|
|
||||||
SetupEntityState(BudgetOverrideEntityId, "OFF");
|
|
||||||
|
|
||||||
// Act
|
CreateSut().ReadPersistedCooldownTimestamp().Should().BeNull();
|
||||||
var result = _sut.ReadPersistedState();
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
result.Should().BeNull();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ReadPersistedState_WithDecimalRuntime_ShouldParseCorrectly()
|
public void ReadPersistedCooldownTimestamp_WhenHaContextThrows_ShouldReturnNull()
|
||||||
{
|
{
|
||||||
// Arrange
|
_haContextMock.Setup(h => h.GetState(WaterReadyEntityId))
|
||||||
SetupEntityState(TodayRuntimeEntityId, "134.66");
|
.Throws(new InvalidOperationException("Home Assistant unavailable"));
|
||||||
SetupEntityState(SessionCountEntityId, "1");
|
|
||||||
SetupEntityState(SkipPriceCapEntityId, "OFF");
|
|
||||||
SetupEntityState(BudgetOverrideEntityId, "OFF");
|
|
||||||
|
|
||||||
// Act
|
CreateSut().ReadPersistedCooldownTimestamp().Should().BeNull();
|
||||||
var result = _sut.ReadPersistedState();
|
}
|
||||||
|
|
||||||
// Assert
|
#endregion
|
||||||
result.Should().NotBeNull();
|
|
||||||
result!.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(134.66));
|
#region UpdateEntitiesAsync
|
||||||
result.SessionCount.Should().Be(1);
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(true, "yes")]
|
||||||
|
[InlineData(false, "no")]
|
||||||
|
public async Task UpdateEntitiesAsync_ShouldWriteWaterReadyState(bool waterReady, string expectedState)
|
||||||
|
{
|
||||||
|
await CreateSut().UpdateEntitiesAsync(BoilerMonitorTestData.CreateUpdateContext(waterReady: waterReady));
|
||||||
|
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityState(WaterReadyEntityId, expectedState), Times.Once);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task UpdateEntitiesAsync_ShouldWriteAllRuntimeEntitiesWithExpectedFormatting()
|
||||||
|
{
|
||||||
|
var context = BoilerMonitorTestData.CreateUpdateContext(
|
||||||
|
TimeSpan.FromSeconds(3723.9),
|
||||||
|
TimeSpan.FromSeconds(42.9),
|
||||||
|
150.0,
|
||||||
|
true,
|
||||||
|
4,
|
||||||
|
waterReady: true);
|
||||||
|
|
||||||
|
await CreateSut().UpdateEntitiesAsync(context);
|
||||||
|
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityState(StatusEntityId, StatusConfigured), Times.Once);
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityState(TodayRuntimeEntityId, "3723"), Times.Once);
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityState(RemainingTimeEntityId, "42"), Times.Once);
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityState(BudgetPercentageEntityId, "100"), Times.Once);
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityState(BudgetExhaustedEntityId, "on"), Times.Once);
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityState(SessionCountEntityId, "4"), Times.Once);
|
||||||
|
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()),
|
||||||
|
Times.Exactly(5));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(-0.1, "0")]
|
||||||
|
[InlineData(0.0, "0")]
|
||||||
|
[InlineData(49.9, "49")]
|
||||||
|
[InlineData(99.999, "99")]
|
||||||
|
[InlineData(100.0, "100")]
|
||||||
|
[InlineData(100.1, "100")]
|
||||||
|
[InlineData(1_000.0, "100")]
|
||||||
|
public async Task UpdateEntitiesAsync_ShouldClampAndTruncateBudgetPercentage(
|
||||||
|
double budgetPercentage,
|
||||||
|
string expectedState)
|
||||||
|
{
|
||||||
|
await CreateSut()
|
||||||
|
.UpdateEntitiesAsync(
|
||||||
|
BoilerMonitorTestData.CreateUpdateContext(budgetPercentage: budgetPercentage));
|
||||||
|
|
||||||
|
_entityManagerMock.Verify(
|
||||||
|
em => em.SetEntityState(BudgetPercentageEntityId, expectedState), Times.Once);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(-60, "0")]
|
||||||
|
[InlineData(0, "0")]
|
||||||
|
[InlineData(1, "1")]
|
||||||
|
[InlineData(59, "59")]
|
||||||
|
[InlineData(3600, "3600")]
|
||||||
|
public async Task UpdateEntitiesAsync_ShouldClampAndTruncateRemainingTime(int seconds, string expectedState)
|
||||||
|
{
|
||||||
|
await CreateSut()
|
||||||
|
.UpdateEntitiesAsync(
|
||||||
|
BoilerMonitorTestData.CreateUpdateContext(remainingTime: TimeSpan.FromSeconds(seconds)));
|
||||||
|
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityState(RemainingTimeEntityId, expectedState), Times.Once);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(0.0, "0")]
|
||||||
|
[InlineData(0.9, "0")]
|
||||||
|
[InlineData(59.9, "59")]
|
||||||
|
[InlineData(60.0, "60")]
|
||||||
|
[InlineData(86_400.0, "86400")]
|
||||||
|
public async Task UpdateEntitiesAsync_ShouldTruncateTodayRunTimeToWholeSeconds(double seconds, string expectedState)
|
||||||
|
{
|
||||||
|
await CreateSut()
|
||||||
|
.UpdateEntitiesAsync(
|
||||||
|
BoilerMonitorTestData.CreateUpdateContext(TimeSpan.FromSeconds(seconds)));
|
||||||
|
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityState(TodayRuntimeEntityId, expectedState), Times.Once);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task UpdateEntitiesAsync_WhenSwitchStateIsNull_ShouldWriteUnknownWaterReadyAttributes()
|
||||||
|
{
|
||||||
|
object? capturedAttributes = null;
|
||||||
|
|
||||||
|
_entityManagerMock
|
||||||
|
.Setup(em => em.SetEntityAttributes(WaterReadyEntityId, It.IsAny<object>()))
|
||||||
|
.Callback<string, object>((_, attributes) => capturedAttributes = attributes)
|
||||||
|
.Returns(Task.CompletedTask);
|
||||||
|
|
||||||
|
await CreateSut()
|
||||||
|
.UpdateEntitiesAsync(BoilerMonitorTestData.CreateUpdateContext(
|
||||||
|
waterReady: false,
|
||||||
|
boilerSwitchState: null,
|
||||||
|
boilerPowerWatts: 1234.5));
|
||||||
|
|
||||||
|
capturedAttributes.Should().NotBeNull();
|
||||||
|
var attributes = JsonSerializer.SerializeToElement(capturedAttributes!);
|
||||||
|
attributes.GetProperty("boiler_switch_state").GetString().Should().Be("unknown");
|
||||||
|
attributes.GetProperty("boiler_power_watts").GetDouble().Should().Be(1234.5);
|
||||||
|
attributes.GetProperty("cooldown_since").ValueKind.Should().Be(JsonValueKind.Null);
|
||||||
|
attributes.GetProperty("last_updated").GetString().Should().NotBeNullOrEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task UpdateEntitiesAsync_WhenCooldownIsActive_ShouldSerializeCooldownTimestamp()
|
||||||
|
{
|
||||||
|
var cooldownSince = BoilerMonitorTestData.BaseTime - TimeSpan.FromMinutes(15);
|
||||||
|
object? capturedAttributes = null;
|
||||||
|
|
||||||
|
_entityManagerMock
|
||||||
|
.Setup(em => em.SetEntityAttributes(WaterReadyEntityId, It.IsAny<object>()))
|
||||||
|
.Callback<string, object>((_, attributes) => capturedAttributes = attributes)
|
||||||
|
.Returns(Task.CompletedTask);
|
||||||
|
|
||||||
|
await CreateSut()
|
||||||
|
.UpdateEntitiesAsync(
|
||||||
|
BoilerMonitorTestData.CreateUpdateContext(cooldownSince: cooldownSince));
|
||||||
|
|
||||||
|
var attributes = JsonSerializer.SerializeToElement(capturedAttributes!);
|
||||||
|
attributes.GetProperty("cooldown_since").GetString().Should().Be(cooldownSince.ToString("O"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region CreateEntitiesAsync
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task CreateEntitiesAsync_ShouldCreateEveryBoilerMonitorEntityOnce()
|
||||||
|
{
|
||||||
|
var createdEntityIds = new List<string?>();
|
||||||
|
|
||||||
|
_entityManagerMock
|
||||||
|
.Setup(em => em.CreateEntityAsync(It.IsAny<EntityCreateModel>()))
|
||||||
|
.Callback<EntityCreateModel>(entity => createdEntityIds.Add(entity.EntityId))
|
||||||
|
.Returns(Task.CompletedTask);
|
||||||
|
|
||||||
|
await CreateSut().CreateEntitiesAsync();
|
||||||
|
|
||||||
|
createdEntityIds.Should().HaveCount(15).And.OnlyHaveUniqueItems();
|
||||||
|
|
||||||
|
createdEntityIds.Should()
|
||||||
|
.Contain(
|
||||||
|
[
|
||||||
|
ConfigPowerEntityId,
|
||||||
|
ConfigSwitchEntityId,
|
||||||
|
ConfigPollIntervalEntityId,
|
||||||
|
ConfigHeatingThresholdEntityId,
|
||||||
|
CleanupButtonEntityId,
|
||||||
|
WaterReadyEntityId,
|
||||||
|
TodayRuntimeEntityId,
|
||||||
|
BudgetExhaustedEntityId,
|
||||||
|
AutoManagementEntityId
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task CreateEntitiesAsync_WhenOneEntityFails_ShouldStillAttemptEveryEntity()
|
||||||
|
{
|
||||||
|
_entityManagerMock
|
||||||
|
.Setup(em =>
|
||||||
|
em.CreateEntityAsync(It.Is<EntityCreateModel>(entity => entity.EntityId == CleanupButtonEntityId)))
|
||||||
|
.ThrowsAsync(new InvalidOperationException("MQTT unavailable"));
|
||||||
|
|
||||||
|
var act = () => CreateSut().CreateEntitiesAsync();
|
||||||
|
|
||||||
|
await act.Should().NotThrowAsync();
|
||||||
|
|
||||||
|
_entityManagerMock.Invocations
|
||||||
|
.Count(invocation => invocation.Method.Name == nameof(IEntityManager.CreateEntityAsync))
|
||||||
|
.Should()
|
||||||
|
.Be(15);
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region ResetEntitiesAsync
|
||||||
|
|
||||||
|
public static TheoryData<string, string> ResetEntityStates => new TheoryData<string, string>
|
||||||
|
{
|
||||||
|
{ StatusEntityId, StatusAwaitingConfiguration },
|
||||||
|
{ WaterReadyEntityId, "unknown" },
|
||||||
|
{ SkipPriceCapEntityId, "OFF" },
|
||||||
|
{ TodayRuntimeEntityId, "0" },
|
||||||
|
{ RemainingTimeEntityId, "0" },
|
||||||
|
{ BudgetPercentageEntityId, "0" },
|
||||||
|
{ BudgetExhaustedEntityId, "off" },
|
||||||
|
{ SessionCountEntityId, "0" },
|
||||||
|
{ BudgetOverrideEntityId, "OFF" },
|
||||||
|
{ AutoManagementEntityId, "ON" }
|
||||||
|
};
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(ResetEntityStates))]
|
||||||
|
public async Task ResetEntitiesAsync_ShouldWriteExpectedDefaultState(string entityId, string expectedState)
|
||||||
|
{
|
||||||
|
await CreateSut().ResetEntitiesAsync();
|
||||||
|
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityState(entityId, expectedState), Times.Once);
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()), Times.Exactly(10));
|
||||||
|
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()),
|
||||||
|
Times.Exactly(5));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task ResetEntitiesAsync_WhenEntityManagerThrows_ShouldNotThrow()
|
||||||
|
{
|
||||||
|
_entityManagerMock
|
||||||
|
.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
||||||
|
.ThrowsAsync(new InvalidOperationException("MQTT unavailable"));
|
||||||
|
|
||||||
|
var act = () => CreateSut().ResetEntitiesAsync();
|
||||||
|
|
||||||
|
await act.Should().NotThrowAsync();
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
@@ -289,55 +470,112 @@ public class BoilerMonitorEntityServiceTests
|
|||||||
[Fact]
|
[Fact]
|
||||||
public async Task ResetTransientEntitiesAsync_ShouldResetStatusAndWaterReady()
|
public async Task ResetTransientEntitiesAsync_ShouldResetStatusAndWaterReady()
|
||||||
{
|
{
|
||||||
// Arrange
|
await CreateSut().ResetTransientEntitiesAsync();
|
||||||
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
|
||||||
.Returns(Task.CompletedTask);
|
|
||||||
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
|
|
||||||
.Returns(Task.CompletedTask);
|
|
||||||
|
|
||||||
// Act
|
|
||||||
await _sut.ResetTransientEntitiesAsync();
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
_entityManagerMock.Verify(em => em.SetEntityState(StatusEntityId, StatusAwaitingConfiguration), Times.Once);
|
_entityManagerMock.Verify(em => em.SetEntityState(StatusEntityId, StatusAwaitingConfiguration), Times.Once);
|
||||||
_entityManagerMock.Verify(em => em.SetEntityState(WaterReadyEntityId, "unknown"), Times.Once);
|
_entityManagerMock.Verify(em => em.SetEntityState(WaterReadyEntityId, "unknown"), Times.Once);
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityAttributes(WaterReadyEntityId, It.IsAny<object>()), Times.Once);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static TheoryData<string> UntouchedByTransientResetEntityIds =>
|
||||||
|
[
|
||||||
|
TodayRuntimeEntityId,
|
||||||
|
SessionCountEntityId,
|
||||||
|
BudgetPercentageEntityId,
|
||||||
|
BudgetExhaustedEntityId,
|
||||||
|
RemainingTimeEntityId,
|
||||||
|
SkipPriceCapEntityId,
|
||||||
|
BudgetOverrideEntityId,
|
||||||
|
AutoManagementEntityId,
|
||||||
|
ConfigPowerEntityId,
|
||||||
|
ConfigSwitchEntityId
|
||||||
|
];
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(UntouchedByTransientResetEntityIds))]
|
||||||
|
public async Task ResetTransientEntitiesAsync_ShouldNotResetPersistentOrSwitchEntities(string entityId)
|
||||||
|
{
|
||||||
|
await CreateSut().ResetTransientEntitiesAsync();
|
||||||
|
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityState(entityId, It.IsAny<string>()), Times.Never);
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityAttributes(entityId, It.IsAny<object>()), Times.Never);
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region CleanupEntitiesAsync
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task CleanupEntitiesAsync_ShouldRemoveEveryEntityExceptCleanupButton()
|
||||||
|
{
|
||||||
|
await CreateSut().CleanupEntitiesAsync();
|
||||||
|
|
||||||
|
foreach (var entityId in CleanableEntityIds)
|
||||||
|
{
|
||||||
|
_entityManagerMock.Verify(em => em.RemoveEntity(entityId), Times.Once);
|
||||||
|
}
|
||||||
|
|
||||||
|
_entityManagerMock.Verify(em => em.RemoveEntity(CleanupButtonEntityId), Times.Never);
|
||||||
|
_entityManagerMock.Verify(em => em.RemoveEntity(It.IsAny<string>()), Times.Exactly(CleanableEntityIds.Length));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task ResetTransientEntitiesAsync_ShouldNotResetRuntimeEntities()
|
public async Task CleanupEntitiesAsync_WhenRemoveFails_ShouldRethrow()
|
||||||
{
|
{
|
||||||
// Arrange
|
_entityManagerMock
|
||||||
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
.Setup(em => em.RemoveEntity(It.IsAny<string>()))
|
||||||
.Returns(Task.CompletedTask);
|
.Throws(new InvalidOperationException("MQTT unavailable"));
|
||||||
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
|
|
||||||
.Returns(Task.CompletedTask);
|
|
||||||
|
|
||||||
// Act
|
var act = () => CreateSut().CleanupEntitiesAsync();
|
||||||
await _sut.ResetTransientEntitiesAsync();
|
|
||||||
|
|
||||||
// Assert
|
await act.Should().ThrowAsync<InvalidOperationException>();
|
||||||
_entityManagerMock.Verify(em => em.SetEntityState(TodayRuntimeEntityId, It.IsAny<string>()), Times.Never);
|
|
||||||
_entityManagerMock.Verify(em => em.SetEntityState(SessionCountEntityId, It.IsAny<string>()), Times.Never);
|
|
||||||
_entityManagerMock.Verify(em => em.SetEntityState(BudgetPercentageEntityId, It.IsAny<string>()), Times.Never);
|
|
||||||
_entityManagerMock.Verify(em => em.SetEntityState(BudgetExhaustedEntityId, It.IsAny<string>()), Times.Never);
|
|
||||||
_entityManagerMock.Verify(em => em.SetEntityState(RemainingTimeEntityId, It.IsAny<string>()), Times.Never);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region SetStatusAsync and cancellation
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task ResetTransientEntitiesAsync_ShouldNotResetSwitchEntities()
|
public async Task SetStatusAsync_ShouldWriteStatusEntity()
|
||||||
{
|
{
|
||||||
// Arrange
|
await CreateSut().SetStatusAsync(StatusConfigured);
|
||||||
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
|
||||||
.Returns(Task.CompletedTask);
|
|
||||||
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
|
|
||||||
.Returns(Task.CompletedTask);
|
|
||||||
|
|
||||||
// Act
|
_entityManagerMock.Verify(em => em.SetEntityState(StatusEntityId, StatusConfigured), Times.Once);
|
||||||
await _sut.ResetTransientEntitiesAsync();
|
}
|
||||||
|
|
||||||
// Assert
|
public enum CancelableOperation
|
||||||
_entityManagerMock.Verify(em => em.SetEntityState(SkipPriceCapEntityId, It.IsAny<string>()), Times.Never);
|
{
|
||||||
_entityManagerMock.Verify(em => em.SetEntityState(BudgetOverrideEntityId, It.IsAny<string>()), Times.Never);
|
CreateEntities,
|
||||||
|
ResetEntities,
|
||||||
|
UpdateEntities,
|
||||||
|
ResetTransientEntities,
|
||||||
|
CleanupEntities
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(CancelableOperation.CreateEntities)]
|
||||||
|
[InlineData(CancelableOperation.ResetEntities)]
|
||||||
|
[InlineData(CancelableOperation.UpdateEntities)]
|
||||||
|
[InlineData(CancelableOperation.ResetTransientEntities)]
|
||||||
|
[InlineData(CancelableOperation.CleanupEntities)]
|
||||||
|
public async Task Operation_WhenCancellationIsAlreadyRequested_ShouldThrowAndNotTouchEntityManager(
|
||||||
|
CancelableOperation operation)
|
||||||
|
{
|
||||||
|
var canceledToken = new CancellationToken(true);
|
||||||
|
var sut = CreateSut();
|
||||||
|
|
||||||
|
Func<Task> act = operation switch
|
||||||
|
{
|
||||||
|
CancelableOperation.CreateEntities => () => sut.CreateEntitiesAsync(canceledToken),
|
||||||
|
CancelableOperation.ResetEntities => () => sut.ResetEntitiesAsync(canceledToken),
|
||||||
|
CancelableOperation.UpdateEntities => () => sut.UpdateEntitiesAsync(
|
||||||
|
BoilerMonitorTestData.CreateUpdateContext(), canceledToken),
|
||||||
|
CancelableOperation.ResetTransientEntities => () => sut.ResetTransientEntitiesAsync(canceledToken),
|
||||||
|
_ => () => sut.CleanupEntitiesAsync(canceledToken)
|
||||||
|
};
|
||||||
|
|
||||||
|
await act.Should().ThrowAsync<OperationCanceledException>();
|
||||||
|
_entityManagerMock.Invocations.Should().BeEmpty();
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|||||||
@@ -1,5 +1,9 @@
|
|||||||
using FluentAssertions;
|
#region
|
||||||
|
|
||||||
using BoilerMonitorManager.Models;
|
using BoilerMonitorManager.Models;
|
||||||
|
using FluentAssertions;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace BoilerMonitor.Manager.Tests;
|
namespace BoilerMonitor.Manager.Tests;
|
||||||
|
|
||||||
@@ -13,17 +17,47 @@ public class BoilerMonitorOptionsTests
|
|||||||
options.Enabled.Should().BeTrue();
|
options.Enabled.Should().BeTrue();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Defaults_ShouldHaveCleanupEntitiesOnStartupTrue()
|
||||||
|
{
|
||||||
|
var options = new BoilerMonitorOptions();
|
||||||
|
|
||||||
|
options.CleanupEntitiesOnStartup.Should().BeTrue();
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void SectionName_ShouldBeBoilerMonitor()
|
public void SectionName_ShouldBeBoilerMonitor()
|
||||||
{
|
{
|
||||||
BoilerMonitorOptions.SectionName.Should().Be("BoilerMonitor");
|
BoilerMonitorOptions.SectionName.Should().Be("BoilerMonitor");
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Theory]
|
||||||
public void Enabled_WhenSetToFalse_ShouldReturnFalse()
|
[InlineData(false)]
|
||||||
|
[InlineData(true)]
|
||||||
|
public void Enabled_WhenSet_ShouldReturnConfiguredValue(bool enabled)
|
||||||
{
|
{
|
||||||
var options = new BoilerMonitorOptions { Enabled = false };
|
var options = BoilerMonitorTestData.CreateOptions(enabled);
|
||||||
|
|
||||||
|
options.Enabled.Should().Be(enabled);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(false)]
|
||||||
|
[InlineData(true)]
|
||||||
|
public void CleanupEntitiesOnStartup_WhenSet_ShouldReturnConfiguredValue(bool cleanupEntitiesOnStartup)
|
||||||
|
{
|
||||||
|
var options = BoilerMonitorTestData.CreateOptions(cleanupEntitiesOnStartup: cleanupEntitiesOnStartup);
|
||||||
|
|
||||||
|
options.CleanupEntitiesOnStartup.Should().Be(cleanupEntitiesOnStartup);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Options_WhenBothFlagsDisabled_ShouldPreserveEachValueIndependently()
|
||||||
|
{
|
||||||
|
var options = BoilerMonitorTestData.CreateOptions(false, false);
|
||||||
|
|
||||||
options.Enabled.Should().BeFalse();
|
options.Enabled.Should().BeFalse();
|
||||||
|
options.CleanupEntitiesOnStartup.Should().BeFalse();
|
||||||
|
BoilerMonitorOptions.SectionName.Should().Be("BoilerMonitor");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,293 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using System.Text.Json;
|
||||||
|
using BoilerMonitorManager.Models;
|
||||||
|
using Microsoft.Extensions.Time.Testing;
|
||||||
|
using Moq;
|
||||||
|
using NetDaemon.HassModel;
|
||||||
|
using NetDaemon.HassModel.Entities;
|
||||||
|
using static BoilerMonitor.Models.BoilerMonitorConsts;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace BoilerMonitor.Manager.Tests;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Shared, deterministic fixtures used by the BoilerMonitor tests: config/options builders,
|
||||||
|
/// entity-state sets, parse samples and a fixed clock. Keeping them here avoids copy-pasted
|
||||||
|
/// setup and makes every timestamp/DST assertion independent of the real clock.
|
||||||
|
/// </summary>
|
||||||
|
internal static class BoilerMonitorTestData
|
||||||
|
{
|
||||||
|
public const string PowerEntityId = "sensor.sonoff_1002230e32_power";
|
||||||
|
public const string SwitchEntityId = "switch.sonoff_1002230e32";
|
||||||
|
|
||||||
|
/// <summary>Fixed "now" (UTC) used by every time based test.</summary>
|
||||||
|
public static readonly DateTimeOffset BaseTime = new DateTimeOffset(2026, 3, 31, 12, 0, 0, TimeSpan.Zero);
|
||||||
|
|
||||||
|
public static FakeTimeProvider CreateTimeProvider(DateTimeOffset? utcNow = null)
|
||||||
|
{
|
||||||
|
return new FakeTimeProvider(utcNow ?? BaseTime);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static BoilerMonitorConfig CreateConfig(
|
||||||
|
string? boilerPowerEntityId = PowerEntityId,
|
||||||
|
string? boilerSwitchEntityId = SwitchEntityId,
|
||||||
|
int? pollIntervalSeconds = DefaultPollIntervalSeconds,
|
||||||
|
double? heatingPowerThresholdWatts = DefaultHeatingPowerThresholdWatts)
|
||||||
|
{
|
||||||
|
return new BoilerMonitorConfig
|
||||||
|
{
|
||||||
|
BoilerPowerEntityId = boilerPowerEntityId,
|
||||||
|
BoilerSwitchEntityId = boilerSwitchEntityId,
|
||||||
|
PollIntervalSeconds = pollIntervalSeconds,
|
||||||
|
HeatingPowerThresholdWatts = heatingPowerThresholdWatts
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static BoilerMonitorOptions CreateOptions(
|
||||||
|
bool enabled = true,
|
||||||
|
bool cleanupEntitiesOnStartup = true)
|
||||||
|
{
|
||||||
|
return new BoilerMonitorOptions
|
||||||
|
{
|
||||||
|
Enabled = enabled,
|
||||||
|
CleanupEntitiesOnStartup = cleanupEntitiesOnStartup
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static BoilerMonitorUpdateContext CreateUpdateContext(
|
||||||
|
TimeSpan? todayRunTime = null,
|
||||||
|
TimeSpan? remainingTime = null,
|
||||||
|
double budgetPercentage = 50.0,
|
||||||
|
bool budgetExhausted = false,
|
||||||
|
int sessionCount = 1,
|
||||||
|
double budgetHours = 2.0,
|
||||||
|
bool waterReady = false,
|
||||||
|
string? boilerSwitchState = "on",
|
||||||
|
double? boilerPowerWatts = 0.0,
|
||||||
|
DateTimeOffset? cooldownSince = null)
|
||||||
|
{
|
||||||
|
return new BoilerMonitorUpdateContext
|
||||||
|
{
|
||||||
|
TodayRunTime = todayRunTime ?? TimeSpan.FromHours(1),
|
||||||
|
RemainingTime = remainingTime ?? TimeSpan.FromHours(1),
|
||||||
|
BudgetPercentage = budgetPercentage,
|
||||||
|
BudgetExhausted = budgetExhausted,
|
||||||
|
SessionCount = sessionCount,
|
||||||
|
BudgetHours = budgetHours,
|
||||||
|
WaterReady = waterReady,
|
||||||
|
BoilerSwitchState = boilerSwitchState,
|
||||||
|
BoilerPowerWatts = boilerPowerWatts,
|
||||||
|
CooldownSince = cooldownSince
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The four entity states <c>ReadPersistedState</c> reads, with valid defaults.
|
||||||
|
/// A null value means the entity does not exist in Home Assistant.
|
||||||
|
/// </summary>
|
||||||
|
public static Dictionary<string, string?> CreatePersistedEntityStates(
|
||||||
|
string? todayRuntime = "7200",
|
||||||
|
string? sessionCount = "3",
|
||||||
|
string? skipPriceCap = "OFF",
|
||||||
|
string? budgetOverride = "OFF")
|
||||||
|
{
|
||||||
|
return new Dictionary<string, string?>
|
||||||
|
{
|
||||||
|
[TodayRuntimeEntityId] = todayRuntime,
|
||||||
|
[SessionCountEntityId] = sessionCount,
|
||||||
|
[SkipPriceCapEntityId] = skipPriceCap,
|
||||||
|
[BudgetOverrideEntityId] = budgetOverride
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static EntityState CreateEntityState(string state)
|
||||||
|
{
|
||||||
|
return new EntityState { State = state };
|
||||||
|
}
|
||||||
|
|
||||||
|
public static EntityState CreateEntityStateWithAttributes(IReadOnlyDictionary<string, object?> attributes)
|
||||||
|
{
|
||||||
|
return new EntityState { State = "yes", AttributesJson = JsonSerializer.SerializeToElement(attributes) };
|
||||||
|
}
|
||||||
|
|
||||||
|
public static EntityState CreateWaterReadyEntityStateWithCooldown(object? cooldownSince)
|
||||||
|
{
|
||||||
|
return CreateEntityStateWithAttributes(new Dictionary<string, object?> { ["cooldown_since"] = cooldownSince });
|
||||||
|
}
|
||||||
|
|
||||||
|
extension(Mock<IHaContext> haContextMock)
|
||||||
|
{
|
||||||
|
public void SetupEntityStates(IReadOnlyDictionary<string, string?> states)
|
||||||
|
{
|
||||||
|
foreach (var (entityId, state) in states)
|
||||||
|
{
|
||||||
|
var entityState = state is null ? null : CreateEntityState(state);
|
||||||
|
haContextMock.Setup(h => h.GetState(entityId)).Returns(entityState);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void SetupEntityState(string entityId, EntityState? entityState)
|
||||||
|
{
|
||||||
|
haContextMock.Setup(h => h.GetState(entityId)).Returns(entityState);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Entity-state samples for the today-runtime sensor: valid values with the expected
|
||||||
|
/// <see cref="TimeSpan" />, plus unavailable/negative/overflow values that must be rejected.
|
||||||
|
/// </summary>
|
||||||
|
public static TheoryData<string?, TimeSpan?> RuntimeStateSamples()
|
||||||
|
{
|
||||||
|
var data = new TheoryData<string?, TimeSpan?>();
|
||||||
|
data.Add("7200", TimeSpan.FromHours(2));
|
||||||
|
data.Add("0", TimeSpan.Zero);
|
||||||
|
data.Add("134.66", TimeSpan.FromSeconds(134.66));
|
||||||
|
data.Add("1E3", TimeSpan.FromSeconds(1000));
|
||||||
|
data.Add("0.001", TimeSpan.FromSeconds(0.001));
|
||||||
|
data.Add(" 60 ", TimeSpan.FromSeconds(60));
|
||||||
|
data.Add("86400", TimeSpan.FromDays(1));
|
||||||
|
data.Add("1e9", TimeSpan.FromSeconds(1e9));
|
||||||
|
|
||||||
|
data.Add(null, null);
|
||||||
|
data.Add(string.Empty, null);
|
||||||
|
data.Add(" ", null);
|
||||||
|
data.Add("\t", null);
|
||||||
|
data.Add("unavailable", null);
|
||||||
|
data.Add("unknown", null);
|
||||||
|
data.Add("Unavailable", null);
|
||||||
|
data.Add("not_a_number", null);
|
||||||
|
data.Add("NaN", null);
|
||||||
|
data.Add("Infinity", null);
|
||||||
|
data.Add("1e308", null);
|
||||||
|
data.Add("-1", null);
|
||||||
|
data.Add("-0.001", null);
|
||||||
|
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Entity-state samples for the session-count sensor, including the int boundaries.
|
||||||
|
/// </summary>
|
||||||
|
public static TheoryData<string?, int?> SessionCountStateSamples()
|
||||||
|
{
|
||||||
|
var data = new TheoryData<string?, int?>();
|
||||||
|
data.Add("0", 0);
|
||||||
|
data.Add("3", 3);
|
||||||
|
data.Add(" 2 ", 2);
|
||||||
|
data.Add("+4", 4);
|
||||||
|
data.Add("2147483647", int.MaxValue);
|
||||||
|
|
||||||
|
data.Add(null, null);
|
||||||
|
data.Add(string.Empty, null);
|
||||||
|
data.Add(" ", null);
|
||||||
|
data.Add("\t", null);
|
||||||
|
data.Add("unavailable", null);
|
||||||
|
data.Add("unknown", null);
|
||||||
|
data.Add("abc", null);
|
||||||
|
data.Add("1.5", null);
|
||||||
|
data.Add("-1", null);
|
||||||
|
data.Add("2147483648", null);
|
||||||
|
data.Add("1e3", null);
|
||||||
|
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Water-ready detection samples around the heating threshold, including negative,
|
||||||
|
/// zero, exact-boundary, huge and NaN readings.
|
||||||
|
/// </summary>
|
||||||
|
public static TheoryData<string, double, bool> PowerReadingSamples()
|
||||||
|
{
|
||||||
|
var data = new TheoryData<string, double, bool>();
|
||||||
|
data.Add("negative sensor glitch", -1_000.0, true);
|
||||||
|
data.Add("just below zero", -0.001, true);
|
||||||
|
data.Add("zero", 0.0, true);
|
||||||
|
data.Add("just below threshold", 4.999, true);
|
||||||
|
data.Add("exactly at threshold", 5.0, false);
|
||||||
|
data.Add("just above threshold", 5.001, false);
|
||||||
|
data.Add("actively heating", 2_150.0, false);
|
||||||
|
data.Add("maximum", double.MaxValue, false);
|
||||||
|
data.Add("not-a-number", double.NaN, true);
|
||||||
|
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Elapsed-time sweep showing that the water-ready cooldown never expires on its own.
|
||||||
|
/// </summary>
|
||||||
|
public static TheoryData<TimeSpan> GeneratedElapsedTimes()
|
||||||
|
{
|
||||||
|
var data = new TheoryData<TimeSpan>();
|
||||||
|
data.Add(TimeSpan.FromHours(1));
|
||||||
|
data.Add(TimeSpan.FromHours(2));
|
||||||
|
data.Add(TimeSpan.FromHours(6));
|
||||||
|
data.Add(TimeSpan.FromHours(12));
|
||||||
|
data.Add(TimeSpan.FromHours(23));
|
||||||
|
data.Add(TimeSpan.FromHours(24));
|
||||||
|
data.Add(TimeSpan.FromHours(25));
|
||||||
|
data.Add(TimeSpan.FromHours(48));
|
||||||
|
data.Add(TimeSpan.FromHours(168));
|
||||||
|
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Cooldown restore samples around the UTC-midnight cut-off, including DST start/end
|
||||||
|
/// timestamps carrying non-zero offsets.
|
||||||
|
/// </summary>
|
||||||
|
public static TheoryData<string, DateTimeOffset, DateTimeOffset, bool> CooldownRestoreSamples()
|
||||||
|
{
|
||||||
|
var data = new TheoryData<string, DateTimeOffset, DateTimeOffset, bool>();
|
||||||
|
data.Add("30 minutes ago", BaseTime, BaseTime - TimeSpan.FromMinutes(30), true);
|
||||||
|
data.Add("5 hours ago", BaseTime, BaseTime - TimeSpan.FromHours(5), true);
|
||||||
|
data.Add("exactly at today's UTC midnight", BaseTime, TodayMidnight(), true);
|
||||||
|
data.Add("one tick after today's UTC midnight", BaseTime, TodayMidnight().AddTicks(1), true);
|
||||||
|
data.Add("one tick before today's UTC midnight", BaseTime, TodayMidnight().AddTicks(-1), false);
|
||||||
|
data.Add("one second before today's UTC midnight", BaseTime, TodayMidnight().AddSeconds(-1), false);
|
||||||
|
data.Add("yesterday same time", BaseTime, BaseTime.AddDays(-1), false);
|
||||||
|
data.Add("two days ago", BaseTime, BaseTime.AddDays(-2), false);
|
||||||
|
data.Add("future timestamp", BaseTime, BaseTime.AddHours(1), true);
|
||||||
|
data.Add("maximum timestamp", BaseTime, DateTimeOffset.MaxValue, true);
|
||||||
|
|
||||||
|
// Europe DST starts 2026-03-29 02:00 CET → 03:00 CEST.
|
||||||
|
// now = 03:30+02:00 = 01:30Z, so UTC midnight is 2026-03-29T00:00Z.
|
||||||
|
data.Add(
|
||||||
|
"DST spring-forward, same UTC day",
|
||||||
|
new DateTimeOffset(2026, 3, 29, 3, 30, 0, TimeSpan.FromHours(2)),
|
||||||
|
new DateTimeOffset(2026, 3, 29, 1, 30, 0, TimeSpan.FromHours(1)),
|
||||||
|
true
|
||||||
|
);
|
||||||
|
|
||||||
|
data.Add(
|
||||||
|
"DST spring-forward, previous UTC day",
|
||||||
|
new DateTimeOffset(2026, 3, 29, 3, 30, 0, TimeSpan.FromHours(2)),
|
||||||
|
new DateTimeOffset(2026, 3, 28, 23, 30, 0, TimeSpan.FromHours(1)),
|
||||||
|
false
|
||||||
|
);
|
||||||
|
|
||||||
|
// Europe DST ends 2026-10-25 03:00 CEST → 02:00 CET. The 02:30 wall-clock hour occurs twice.
|
||||||
|
// now = 03:30+01:00 = 02:30Z, timestamp 02:30+02:00 = 00:30Z is still "today" in UTC.
|
||||||
|
data.Add(
|
||||||
|
"DST fall-back, ambiguous local hour",
|
||||||
|
new DateTimeOffset(2026, 10, 25, 3, 30, 0, TimeSpan.FromHours(1)),
|
||||||
|
new DateTimeOffset(2026, 10, 25, 2, 30, 0, TimeSpan.FromHours(2)),
|
||||||
|
true
|
||||||
|
);
|
||||||
|
|
||||||
|
data.Add(
|
||||||
|
"crossing midnight between restore and now",
|
||||||
|
new DateTimeOffset(2026, 4, 1, 0, 0, 1, TimeSpan.Zero),
|
||||||
|
new DateTimeOffset(2026, 3, 31, 23, 59, 59, TimeSpan.Zero),
|
||||||
|
false
|
||||||
|
);
|
||||||
|
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static DateTimeOffset TodayMidnight()
|
||||||
|
{
|
||||||
|
return new DateTimeOffset(BaseTime.Date, TimeSpan.Zero);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,254 +0,0 @@
|
|||||||
using FluentAssertions;
|
|
||||||
using BoilerMonitorManager;
|
|
||||||
|
|
||||||
namespace BoilerMonitor.Manager.Tests;
|
|
||||||
|
|
||||||
public class BoilerRunTimeTrackerTests
|
|
||||||
{
|
|
||||||
private readonly BoilerRunTimeTracker _sut = new();
|
|
||||||
|
|
||||||
#region RecordPollResult
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void RecordPollResult_WhenHeating_ShouldAccumulateRunTime()
|
|
||||||
{
|
|
||||||
var interval = TimeSpan.FromSeconds(30);
|
|
||||||
|
|
||||||
_sut.RecordPollResult(true, interval);
|
|
||||||
_sut.RecordPollResult(true, interval);
|
|
||||||
_sut.RecordPollResult(true, interval);
|
|
||||||
|
|
||||||
var snapshot = _sut.GetSnapshot();
|
|
||||||
snapshot.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(90));
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void RecordPollResult_WhenNotHeating_ShouldNotAccumulate()
|
|
||||||
{
|
|
||||||
var interval = TimeSpan.FromSeconds(30);
|
|
||||||
|
|
||||||
_sut.RecordPollResult(false, interval);
|
|
||||||
_sut.RecordPollResult(false, interval);
|
|
||||||
|
|
||||||
var snapshot = _sut.GetSnapshot();
|
|
||||||
snapshot.AccumulatedRunTime.Should().Be(TimeSpan.Zero);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void RecordPollResult_WhenHeatingStarts_ShouldIncrementSessionCount()
|
|
||||||
{
|
|
||||||
var interval = TimeSpan.FromSeconds(30);
|
|
||||||
|
|
||||||
_sut.RecordPollResult(true, interval);
|
|
||||||
|
|
||||||
var snapshot = _sut.GetSnapshot();
|
|
||||||
snapshot.SessionCount.Should().Be(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void RecordPollResult_ContinuousHeating_ShouldCountAsOneSession()
|
|
||||||
{
|
|
||||||
var interval = TimeSpan.FromSeconds(30);
|
|
||||||
|
|
||||||
_sut.RecordPollResult(true, interval);
|
|
||||||
_sut.RecordPollResult(true, interval);
|
|
||||||
_sut.RecordPollResult(true, interval);
|
|
||||||
|
|
||||||
var snapshot = _sut.GetSnapshot();
|
|
||||||
snapshot.SessionCount.Should().Be(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void RecordPollResult_HeatingStopsAndRestarts_ShouldCountAsTwoSessions()
|
|
||||||
{
|
|
||||||
var interval = TimeSpan.FromSeconds(30);
|
|
||||||
|
|
||||||
_sut.RecordPollResult(true, interval);
|
|
||||||
_sut.RecordPollResult(false, interval);
|
|
||||||
_sut.RecordPollResult(true, interval);
|
|
||||||
|
|
||||||
var snapshot = _sut.GetSnapshot();
|
|
||||||
snapshot.SessionCount.Should().Be(2);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void RecordPollResult_MultipleSessions_ShouldAccumulateCorrectly()
|
|
||||||
{
|
|
||||||
var interval = TimeSpan.FromSeconds(30);
|
|
||||||
|
|
||||||
_sut.RecordPollResult(true, interval);
|
|
||||||
_sut.RecordPollResult(true, interval);
|
|
||||||
_sut.RecordPollResult(false, interval);
|
|
||||||
_sut.RecordPollResult(true, interval);
|
|
||||||
|
|
||||||
var snapshot = _sut.GetSnapshot();
|
|
||||||
snapshot.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(90));
|
|
||||||
snapshot.SessionCount.Should().Be(2);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void RecordPollResult_WhenHeating_ShouldSetIsInSessionTrue()
|
|
||||||
{
|
|
||||||
_sut.RecordPollResult(true, TimeSpan.FromSeconds(30));
|
|
||||||
|
|
||||||
var snapshot = _sut.GetSnapshot();
|
|
||||||
snapshot.IsInSession.Should().BeTrue();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void RecordPollResult_WhenNotHeating_ShouldSetIsInSessionFalse()
|
|
||||||
{
|
|
||||||
_sut.RecordPollResult(true, TimeSpan.FromSeconds(30));
|
|
||||||
_sut.RecordPollResult(false, TimeSpan.FromSeconds(30));
|
|
||||||
|
|
||||||
var snapshot = _sut.GetSnapshot();
|
|
||||||
snapshot.IsInSession.Should().BeFalse();
|
|
||||||
}
|
|
||||||
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
#region Reset
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Reset_ShouldClearAllState()
|
|
||||||
{
|
|
||||||
var interval = TimeSpan.FromSeconds(30);
|
|
||||||
_sut.RecordPollResult(true, interval);
|
|
||||||
_sut.RecordPollResult(true, interval);
|
|
||||||
|
|
||||||
_sut.Reset();
|
|
||||||
|
|
||||||
var snapshot = _sut.GetSnapshot();
|
|
||||||
snapshot.AccumulatedRunTime.Should().Be(TimeSpan.Zero);
|
|
||||||
snapshot.SessionCount.Should().Be(0);
|
|
||||||
snapshot.IsInSession.Should().BeFalse();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Reset_AfterReset_ShouldAccumulateFromZero()
|
|
||||||
{
|
|
||||||
var interval = TimeSpan.FromSeconds(30);
|
|
||||||
_sut.RecordPollResult(true, interval);
|
|
||||||
_sut.Reset();
|
|
||||||
_sut.RecordPollResult(true, interval);
|
|
||||||
|
|
||||||
var snapshot = _sut.GetSnapshot();
|
|
||||||
snapshot.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(30));
|
|
||||||
snapshot.SessionCount.Should().Be(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
#region RestoreFromSnapshot
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void RestoreFromSnapshot_ShouldSetAccumulatedRunTimeAndSessionCount()
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
var runTime = TimeSpan.FromMinutes(45);
|
|
||||||
const int sessionCount = 3;
|
|
||||||
|
|
||||||
// Act
|
|
||||||
_sut.RestoreFromSnapshot(runTime, sessionCount);
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
var snapshot = _sut.GetSnapshot();
|
|
||||||
snapshot.AccumulatedRunTime.Should().Be(runTime);
|
|
||||||
snapshot.SessionCount.Should().Be(sessionCount);
|
|
||||||
snapshot.IsInSession.Should().BeFalse();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void RestoreFromSnapshot_ShouldOverwriteExistingState()
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
_sut.RecordPollResult(true, TimeSpan.FromSeconds(30));
|
|
||||||
_sut.RecordPollResult(true, TimeSpan.FromSeconds(30));
|
|
||||||
|
|
||||||
var restoredRunTime = TimeSpan.FromHours(2);
|
|
||||||
const int restoredSessions = 5;
|
|
||||||
|
|
||||||
// Act
|
|
||||||
_sut.RestoreFromSnapshot(restoredRunTime, restoredSessions);
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
var snapshot = _sut.GetSnapshot();
|
|
||||||
snapshot.AccumulatedRunTime.Should().Be(restoredRunTime);
|
|
||||||
snapshot.SessionCount.Should().Be(restoredSessions);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void RestoreFromSnapshot_ShouldAllowFurtherAccumulationFromRestoredState()
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
var restoredRunTime = TimeSpan.FromMinutes(30);
|
|
||||||
const int restoredSessions = 2;
|
|
||||||
var pollInterval = TimeSpan.FromSeconds(30);
|
|
||||||
|
|
||||||
_sut.RestoreFromSnapshot(restoredRunTime, restoredSessions);
|
|
||||||
|
|
||||||
// Act
|
|
||||||
_sut.RecordPollResult(true, pollInterval);
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
var snapshot = _sut.GetSnapshot();
|
|
||||||
snapshot.AccumulatedRunTime.Should().Be(restoredRunTime + pollInterval);
|
|
||||||
snapshot.SessionCount.Should().Be(restoredSessions + 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void RestoreFromSnapshot_WithZeroValues_ShouldSetToZero()
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
_sut.RecordPollResult(true, TimeSpan.FromSeconds(30));
|
|
||||||
|
|
||||||
// Act
|
|
||||||
_sut.RestoreFromSnapshot(TimeSpan.Zero, 0);
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
var snapshot = _sut.GetSnapshot();
|
|
||||||
snapshot.AccumulatedRunTime.Should().Be(TimeSpan.Zero);
|
|
||||||
snapshot.SessionCount.Should().Be(0);
|
|
||||||
}
|
|
||||||
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
#region Thread safety
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task RecordPollResult_ConcurrentCalls_ShouldNotCorruptState()
|
|
||||||
{
|
|
||||||
var interval = TimeSpan.FromSeconds(1);
|
|
||||||
const int iterationsPerThread = 1000;
|
|
||||||
const int threadCount = 4;
|
|
||||||
|
|
||||||
var tasks = Enumerable.Range(0, threadCount).Select(_ => Task.Run(() =>
|
|
||||||
{
|
|
||||||
for (var i = 0; i < iterationsPerThread; i++)
|
|
||||||
{
|
|
||||||
_sut.RecordPollResult(true, interval);
|
|
||||||
}
|
|
||||||
})).ToArray();
|
|
||||||
|
|
||||||
await Task.WhenAll(tasks);
|
|
||||||
|
|
||||||
var snapshot = _sut.GetSnapshot();
|
|
||||||
snapshot.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(iterationsPerThread * threadCount));
|
|
||||||
}
|
|
||||||
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
#region GetSnapshot
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void GetSnapshot_Initial_ShouldReturnZeroState()
|
|
||||||
{
|
|
||||||
var snapshot = _sut.GetSnapshot();
|
|
||||||
|
|
||||||
snapshot.AccumulatedRunTime.Should().Be(TimeSpan.Zero);
|
|
||||||
snapshot.SessionCount.Should().Be(0);
|
|
||||||
snapshot.IsInSession.Should().BeFalse();
|
|
||||||
}
|
|
||||||
|
|
||||||
#endregion
|
|
||||||
}
|
|
||||||
@@ -1,429 +1,494 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
using BoilerMonitor.Models;
|
using BoilerMonitor.Models;
|
||||||
|
using BoilerMonitorManager;
|
||||||
using FluentAssertions;
|
using FluentAssertions;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using Microsoft.Extensions.Time.Testing;
|
using Microsoft.Extensions.Time.Testing;
|
||||||
using Moq;
|
using Moq;
|
||||||
using BoilerMonitorManager;
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace BoilerMonitor.Manager.Tests;
|
namespace BoilerMonitor.Manager.Tests;
|
||||||
|
|
||||||
public class WaterReadyServiceTests
|
public class WaterReadyServiceTests
|
||||||
{
|
{
|
||||||
private readonly Mock<ILogger<WaterReadyService>> _loggerMock;
|
private const double Threshold = BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts;
|
||||||
private readonly FakeTimeProvider _timeProvider;
|
private const double HighPowerWatts = 2150.0;
|
||||||
|
private const int RequiredReadings = BoilerMonitorConsts.ConsecutiveReadingsRequired;
|
||||||
|
|
||||||
public WaterReadyServiceTests()
|
private readonly Mock<ILogger<WaterReadyService>> _loggerMock = new Mock<ILogger<WaterReadyService>>();
|
||||||
{
|
private readonly FakeTimeProvider _timeProvider = BoilerMonitorTestData.CreateTimeProvider();
|
||||||
_loggerMock = new Mock<ILogger<WaterReadyService>>();
|
|
||||||
_timeProvider = new FakeTimeProvider(DateTimeOffset.UtcNow);
|
|
||||||
}
|
|
||||||
|
|
||||||
private WaterReadyService CreateSut()
|
private WaterReadyService CreateSut()
|
||||||
{
|
{
|
||||||
return new WaterReadyService(_loggerMock.Object, _timeProvider);
|
return new WaterReadyService(_loggerMock.Object, _timeProvider);
|
||||||
}
|
}
|
||||||
|
|
||||||
#region IsWaterReady — basic behavior (no grace period active)
|
private WaterReadyService CreateSutWithHeatingObserved()
|
||||||
|
{
|
||||||
[Fact]
|
var sut = CreateSut();
|
||||||
public void IsWaterReady_SwitchOnAndLowPower_ShouldReturnTrue()
|
sut.RecordHeatingObserved();
|
||||||
|
|
||||||
|
return sut;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool FeedReadings(
|
||||||
|
WaterReadyService sut,
|
||||||
|
int count,
|
||||||
|
string? switchState = "on",
|
||||||
|
double? powerWatts = 0.0,
|
||||||
|
double heatingThresholdWatts = Threshold)
|
||||||
|
{
|
||||||
|
var result = false;
|
||||||
|
|
||||||
|
for (var i = 0; i < count; i++)
|
||||||
|
{
|
||||||
|
result = sut.IsWaterReady(switchState, powerWatts, heatingThresholdWatts);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
#region Heating observation prerequisite
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(1)]
|
||||||
|
[InlineData(2)]
|
||||||
|
[InlineData(10)]
|
||||||
|
public void IsWaterReady_WhenHeatingWasNeverObserved_ShouldAlwaysReturnFalse(int readingCount)
|
||||||
{
|
{
|
||||||
// Arrange
|
|
||||||
var sut = CreateSut();
|
var sut = CreateSut();
|
||||||
|
|
||||||
// Act
|
var result = FeedReadings(sut, readingCount);
|
||||||
var result = sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
|
||||||
|
result.Should().BeFalse();
|
||||||
|
sut.IsInCooldown.Should().BeFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IsWaterReady_AfterObservedHeatingAndConsecutiveLowPower_ShouldReturnTrue()
|
||||||
|
{
|
||||||
|
var sut = CreateSutWithHeatingObserved();
|
||||||
|
|
||||||
|
var result = FeedReadings(sut, RequiredReadings);
|
||||||
|
|
||||||
// Assert
|
|
||||||
result.Should().BeTrue();
|
result.Should().BeTrue();
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void IsWaterReady_SwitchOnAndPowerBelowThreshold_ShouldReturnTrue()
|
public void RecordHeatingObserved_ShouldEnableDetection()
|
||||||
{
|
{
|
||||||
// Arrange
|
|
||||||
var sut = CreateSut();
|
var sut = CreateSut();
|
||||||
|
|
||||||
// Act
|
sut.RecordHeatingObserved();
|
||||||
var result = sut.IsWaterReady("on", 4.9, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
|
||||||
|
FeedReadings(sut, RequiredReadings).Should().BeTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void RecordHeatingObserved_WhenCalledRepeatedly_ShouldStayEnabled()
|
||||||
|
{
|
||||||
|
var sut = CreateSut();
|
||||||
|
|
||||||
|
sut.RecordHeatingObserved();
|
||||||
|
sut.RecordHeatingObserved();
|
||||||
|
|
||||||
|
FeedReadings(sut, RequiredReadings).Should().BeTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void NotifyTurnedOn_ShouldResetHasObservedHeating()
|
||||||
|
{
|
||||||
|
var sut = CreateSutWithHeatingObserved();
|
||||||
|
sut.NotifyTurnedOn();
|
||||||
|
|
||||||
|
var result = FeedReadings(sut, 10);
|
||||||
|
|
||||||
|
result.Should().BeFalse("heating observation was reset by NotifyTurnedOn");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void NotifyTurnedOn_ThenObserveHeating_ShouldReEnableDetection()
|
||||||
|
{
|
||||||
|
var sut = CreateSutWithHeatingObserved();
|
||||||
|
sut.NotifyTurnedOn();
|
||||||
|
sut.RecordHeatingObserved();
|
||||||
|
|
||||||
|
var result = FeedReadings(sut, RequiredReadings);
|
||||||
|
|
||||||
// Assert
|
|
||||||
result.Should().BeTrue();
|
result.Should().BeTrue();
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void IsWaterReady_SwitchOnAndPowerAtThreshold_ShouldReturnFalse()
|
public void ResetCooldown_ShouldKeepHeatingObservationEnabled()
|
||||||
{
|
{
|
||||||
// Arrange
|
var sut = CreateSutWithHeatingObserved();
|
||||||
var sut = CreateSut();
|
FeedReadings(sut, RequiredReadings).Should().BeTrue();
|
||||||
|
|
||||||
// Act
|
sut.ResetCooldown();
|
||||||
var result = sut.IsWaterReady("on", 5.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
|
||||||
|
|
||||||
// Assert
|
FeedReadings(sut, RequiredReadings)
|
||||||
result.Should().BeFalse();
|
.Should()
|
||||||
|
.BeTrue(
|
||||||
|
"ResetCooldown clears the cooldown and counter, not the heating observation");
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void IsWaterReady_SwitchOnAndHighPower_ShouldReturnFalse()
|
public void IsWaterReady_AfterResetAndReObservedHeating_ShouldTriggerAgain()
|
||||||
{
|
{
|
||||||
// Arrange
|
var sut = CreateSutWithHeatingObserved();
|
||||||
var sut = CreateSut();
|
FeedReadings(sut, RequiredReadings);
|
||||||
|
sut.ResetCooldown();
|
||||||
|
|
||||||
// Act
|
sut.RecordHeatingObserved();
|
||||||
var result = sut.IsWaterReady("on", 2150.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
var result = FeedReadings(sut, RequiredReadings);
|
||||||
|
|
||||||
// Assert
|
result.Should().BeTrue("detection should work again after reset + new heating observation");
|
||||||
result.Should().BeFalse();
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region Debouncing (consecutive readings)
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(1, false)]
|
||||||
|
[InlineData(2, true)]
|
||||||
|
[InlineData(3, true)]
|
||||||
|
[InlineData(10, true)]
|
||||||
|
public void IsWaterReady_ShouldRequireConsecutiveBelowThresholdReadings(int readingCount, bool expected)
|
||||||
|
{
|
||||||
|
var sut = CreateSutWithHeatingObserved();
|
||||||
|
|
||||||
|
var result = FeedReadings(sut, readingCount);
|
||||||
|
|
||||||
|
result.Should().Be(expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(HighPowerWatts)]
|
||||||
|
[InlineData(Threshold)]
|
||||||
|
[InlineData(double.MaxValue)]
|
||||||
|
public void IsWaterReady_WhenReadingIsAtOrAboveThreshold_ShouldResetConsecutiveCount(double powerWatts)
|
||||||
|
{
|
||||||
|
var sut = CreateSutWithHeatingObserved();
|
||||||
|
FeedReadings(sut, RequiredReadings - 1).Should().BeFalse();
|
||||||
|
|
||||||
|
sut.IsWaterReady("on", powerWatts, Threshold).Should().BeFalse("power is not below the threshold");
|
||||||
|
|
||||||
|
FeedReadings(sut, 1).Should().BeFalse("the counter was reset by the above-threshold reading");
|
||||||
|
FeedReadings(sut, RequiredReadings - 1).Should().BeTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(0)]
|
||||||
|
[InlineData(1)]
|
||||||
|
public void IsWaterReady_NotifyTurnedOn_ShouldResetConsecutiveCount(int belowThresholdBeforeTurnOn)
|
||||||
|
{
|
||||||
|
var sut = CreateSutWithHeatingObserved();
|
||||||
|
FeedReadings(sut, belowThresholdBeforeTurnOn);
|
||||||
|
|
||||||
|
sut.NotifyTurnedOn();
|
||||||
|
sut.RecordHeatingObserved();
|
||||||
|
|
||||||
|
FeedReadings(sut, RequiredReadings - 1).Should().BeFalse("NotifyTurnedOn reset the consecutive counter");
|
||||||
|
FeedReadings(sut, 1).Should().BeTrue();
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void IsWaterReady_SwitchOff_ShouldReturnFalse()
|
public void IsWaterReady_InterleavedReadings_ShouldOnlyTriggerAfterLastConsecutiveLowReading()
|
||||||
{
|
{
|
||||||
// Arrange
|
var sut = CreateSutWithHeatingObserved();
|
||||||
var sut = CreateSut();
|
|
||||||
|
|
||||||
// Act
|
var results = new[]
|
||||||
var result = sut.IsWaterReady("off", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
{
|
||||||
|
sut.IsWaterReady("on", 0.0, Threshold),
|
||||||
|
sut.IsWaterReady("on", HighPowerWatts, Threshold),
|
||||||
|
sut.IsWaterReady("on", 0.0, Threshold),
|
||||||
|
sut.IsWaterReady("on", 0.0, Threshold)
|
||||||
|
};
|
||||||
|
|
||||||
|
results.Should().Equal(false, false, false, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region Basic state checks
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("off")]
|
||||||
|
[InlineData("OFF")]
|
||||||
|
[InlineData(" off")]
|
||||||
|
[InlineData("on ")]
|
||||||
|
[InlineData("unknown")]
|
||||||
|
[InlineData("unavailable")]
|
||||||
|
[InlineData("yes")]
|
||||||
|
[InlineData("1")]
|
||||||
|
public void IsWaterReady_WhenSwitchIsNotOn_ShouldReturnFalse(string switchState)
|
||||||
|
{
|
||||||
|
var sut = CreateSutWithHeatingObserved();
|
||||||
|
|
||||||
|
var result = FeedReadings(sut, 10, switchState);
|
||||||
|
|
||||||
// Assert
|
|
||||||
result.Should().BeFalse();
|
result.Should().BeFalse();
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Theory]
|
||||||
public void IsWaterReady_NullSwitchState_ShouldReturnFalse()
|
[InlineData("on", null)]
|
||||||
|
[InlineData(null, 0.0)]
|
||||||
|
[InlineData(null, null)]
|
||||||
|
[InlineData("", null)]
|
||||||
|
[InlineData("", 0.0)]
|
||||||
|
public void IsWaterReady_WhenSwitchStateOrPowerIsNull_ShouldReturnFalse(string? switchState, double? powerWatts)
|
||||||
{
|
{
|
||||||
// Arrange
|
var sut = CreateSutWithHeatingObserved();
|
||||||
var sut = CreateSut();
|
|
||||||
|
|
||||||
// Act
|
var result = FeedReadings(sut, 10, switchState, powerWatts);
|
||||||
var result = sut.IsWaterReady(null, 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
result.Should().BeFalse();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void IsWaterReady_NullPowerWatts_ShouldReturnFalse()
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
var sut = CreateSut();
|
|
||||||
|
|
||||||
// Act
|
|
||||||
var result = sut.IsWaterReady("on", null, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
result.Should().BeFalse();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void IsWaterReady_BothNull_ShouldReturnFalse()
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
var sut = CreateSut();
|
|
||||||
|
|
||||||
// Act
|
|
||||||
var result = sut.IsWaterReady(null, null, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
result.Should().BeFalse();
|
result.Should().BeFalse();
|
||||||
}
|
}
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
[InlineData("ON")]
|
[InlineData("ON")]
|
||||||
[InlineData("On")]
|
[InlineData("On")]
|
||||||
[InlineData("on")]
|
[InlineData("oN")]
|
||||||
public void IsWaterReady_SwitchOnCaseInsensitive_ShouldReturnTrue(string switchState)
|
public void IsWaterReady_SwitchOnCaseInsensitive_ShouldReturnTrue(string switchState)
|
||||||
{
|
{
|
||||||
// Arrange
|
var sut = CreateSutWithHeatingObserved();
|
||||||
var sut = CreateSut();
|
|
||||||
|
|
||||||
// Act
|
var result = FeedReadings(sut, RequiredReadings, switchState);
|
||||||
var result = sut.IsWaterReady(switchState, 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
result.Should().BeTrue();
|
result.Should().BeTrue();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(BoilerMonitorTestData.PowerReadingSamples), MemberType = typeof(BoilerMonitorTestData))]
|
||||||
|
public void IsWaterReady_PowerAroundThreshold_ShouldFollowThresholdRule(
|
||||||
|
string scenario,
|
||||||
|
double powerWatts,
|
||||||
|
bool expectedBelowThreshold)
|
||||||
|
{
|
||||||
|
var sut = CreateSutWithHeatingObserved();
|
||||||
|
|
||||||
|
var result = FeedReadings(sut, RequiredReadings, powerWatts: powerWatts);
|
||||||
|
|
||||||
|
result.Should()
|
||||||
|
.Be(
|
||||||
|
expectedBelowThreshold,
|
||||||
|
$"{scenario}: readings below {Threshold}W are counted as 'not heating'");
|
||||||
|
}
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
[InlineData(9.9, 10.0, true)]
|
[InlineData(9.9, 10.0, true)]
|
||||||
[InlineData(10.0, 10.0, false)]
|
[InlineData(10.0, 10.0, false)]
|
||||||
[InlineData(10.1, 10.0, false)]
|
[InlineData(10.1, 10.0, false)]
|
||||||
public void IsWaterReady_CustomThreshold_ShouldUseProvidedValue(double powerWatts, double threshold, bool expected)
|
[InlineData(0.0, 0.0, false)]
|
||||||
|
[InlineData(-10.0, -5.0, true)]
|
||||||
|
[InlineData(-0.001, 0.0, true)]
|
||||||
|
[InlineData(0.0, -5.0, false)]
|
||||||
|
[InlineData(10.0, 0.0, false)]
|
||||||
|
public void IsWaterReady_CustomThreshold_ShouldUseProvidedValue(
|
||||||
|
double powerWatts,
|
||||||
|
double heatingThresholdWatts,
|
||||||
|
bool expected)
|
||||||
{
|
{
|
||||||
// Arrange — fresh instance per case to avoid cooldown side-effects
|
var sut = CreateSutWithHeatingObserved();
|
||||||
var sut = CreateSut();
|
|
||||||
|
|
||||||
// Act
|
var result = FeedReadings(sut, RequiredReadings, powerWatts: powerWatts,
|
||||||
var result = sut.IsWaterReady("on", powerWatts, threshold);
|
heatingThresholdWatts: heatingThresholdWatts);
|
||||||
|
|
||||||
// Assert
|
|
||||||
result.Should().Be(expected);
|
result.Should().Be(expected);
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
#region Warm-up grace period
|
#region Cooldown period
|
||||||
|
|
||||||
[Fact]
|
[Theory]
|
||||||
public void IsWaterReady_DuringGracePeriod_ShouldReturnFalse()
|
[InlineData("off", 0.0)]
|
||||||
|
[InlineData("off", null)]
|
||||||
|
[InlineData(null, 0.0)]
|
||||||
|
[InlineData(null, null)]
|
||||||
|
[InlineData("on", HighPowerWatts)]
|
||||||
|
[InlineData("unknown", 12.0)]
|
||||||
|
public void IsWaterReady_DuringCooldown_ShouldReturnTrueRegardlessOfInputs(string? switchState, double? powerWatts)
|
||||||
{
|
{
|
||||||
// Arrange
|
var sut = CreateSutWithHeatingObserved();
|
||||||
var sut = CreateSut();
|
FeedReadings(sut, RequiredReadings).Should().BeTrue();
|
||||||
sut.NotifyTurnedOn();
|
|
||||||
|
|
||||||
// Act — still within grace period, low power should be suppressed
|
var result = sut.IsWaterReady(switchState, powerWatts, Threshold);
|
||||||
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();
|
result.Should().BeTrue();
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Theory]
|
||||||
public void IsWaterReady_DuringGracePeriodWithHighPower_ShouldReturnFalse()
|
[MemberData(nameof(BoilerMonitorTestData.GeneratedElapsedTimes), MemberType = typeof(BoilerMonitorTestData))]
|
||||||
|
public void IsWaterReady_CooldownDoesNotExpireByTime_ShouldStayActive(TimeSpan elapsed)
|
||||||
{
|
{
|
||||||
// Arrange
|
var sut = CreateSutWithHeatingObserved();
|
||||||
var sut = CreateSut();
|
FeedReadings(sut, RequiredReadings);
|
||||||
sut.NotifyTurnedOn();
|
var triggeredAt = sut.WaterReadySince;
|
||||||
|
|
||||||
// Act — high power during grace period is still "not ready" (heating)
|
_timeProvider.Advance(elapsed);
|
||||||
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
|
|
||||||
|
|
||||||
[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);
|
|
||||||
|
|
||||||
// Act — switch is now off, but cooldown should keep reporting ready
|
|
||||||
var result = sut.IsWaterReady("off", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
result.Should().BeTrue();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void IsWaterReady_DuringCooldown_ShouldReturnTrueEvenWithNullState()
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
var sut = CreateSut();
|
|
||||||
sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
|
||||||
|
|
||||||
// Act
|
|
||||||
var result = sut.IsWaterReady(null, null, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
result.Should().BeTrue();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void IsWaterReady_AfterCooldownExpires_ShouldResumeNormalDetection()
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
var sut = CreateSut();
|
|
||||||
sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
|
||||||
_timeProvider.Advance(BoilerMonitorConsts.WaterReadyCooldownPeriod);
|
|
||||||
|
|
||||||
// Act — cooldown expired, switch is off → not ready
|
|
||||||
var result = sut.IsWaterReady("off", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
result.Should().BeFalse();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void IsWaterReady_JustBeforeCooldownExpires_ShouldStillReturnTrue()
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
var sut = CreateSut();
|
|
||||||
sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
|
||||||
_timeProvider.Advance(BoilerMonitorConsts.WaterReadyCooldownPeriod - TimeSpan.FromSeconds(1));
|
|
||||||
|
|
||||||
// Act
|
|
||||||
var result = sut.IsWaterReady("off", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
result.Should().BeTrue();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void IsInCooldown_WhenCooldownActive_ShouldReturnTrue()
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
var sut = CreateSut();
|
|
||||||
sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
|
||||||
|
|
||||||
// Act & Assert
|
|
||||||
sut.IsInCooldown.Should().BeTrue();
|
sut.IsInCooldown.Should().BeTrue();
|
||||||
|
|
||||||
|
sut.IsWaterReady("off", 0.0, Threshold)
|
||||||
|
.Should()
|
||||||
|
.BeTrue(
|
||||||
|
"cooldown only clears via explicit ResetCooldown, not by elapsed time");
|
||||||
|
|
||||||
|
sut.WaterReadySince.Should().Be(triggeredAt);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void IsInCooldown_WhenNoCooldownTriggered_ShouldReturnFalse()
|
public void IsInCooldown_WhenNoCooldownTriggered_ShouldReturnFalse()
|
||||||
{
|
{
|
||||||
// Arrange
|
|
||||||
var sut = CreateSut();
|
var sut = CreateSut();
|
||||||
|
|
||||||
// Act & Assert
|
|
||||||
sut.IsInCooldown.Should().BeFalse();
|
sut.IsInCooldown.Should().BeFalse();
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void IsInCooldown_AfterCooldownExpires_ShouldReturnFalse()
|
public void ResetCooldown_ShouldClearActiveCooldownAndAllowDetectionToResume()
|
||||||
{
|
{
|
||||||
// Arrange
|
var sut = CreateSutWithHeatingObserved();
|
||||||
var sut = CreateSut();
|
FeedReadings(sut, RequiredReadings);
|
||||||
sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
|
||||||
_timeProvider.Advance(BoilerMonitorConsts.WaterReadyCooldownPeriod);
|
|
||||||
|
|
||||||
// Act & Assert
|
|
||||||
sut.IsInCooldown.Should().BeFalse();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void ResetCooldown_ShouldClearActiveCooldown()
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
var sut = CreateSut();
|
|
||||||
sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
|
||||||
sut.IsInCooldown.Should().BeTrue();
|
sut.IsInCooldown.Should().BeTrue();
|
||||||
|
|
||||||
// Act
|
|
||||||
sut.ResetCooldown();
|
sut.ResetCooldown();
|
||||||
|
|
||||||
// Assert
|
|
||||||
sut.IsInCooldown.Should().BeFalse();
|
sut.IsInCooldown.Should().BeFalse();
|
||||||
|
sut.WaterReadySince.Should().BeNull();
|
||||||
|
sut.IsWaterReady("off", 0.0, Threshold).Should().BeFalse();
|
||||||
|
FeedReadings(sut, RequiredReadings - 1).Should().BeFalse();
|
||||||
|
FeedReadings(sut, 1).Should().BeTrue();
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ResetCooldown_ShouldAllowBoilerToTurnOnAgain()
|
public void ResetCooldown_WhenNoCooldownIsActive_ShouldBeANoOp()
|
||||||
{
|
{
|
||||||
// Arrange — water becomes ready, then cooldown is reset (midnight)
|
|
||||||
var sut = CreateSut();
|
var sut = CreateSut();
|
||||||
sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
|
||||||
sut.ResetCooldown();
|
sut.ResetCooldown();
|
||||||
|
|
||||||
// Act — switch is off, no power → not ready (normal detection resumes)
|
sut.IsInCooldown.Should().BeFalse();
|
||||||
var result = sut.IsWaterReady("off", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
sut.WaterReadySince.Should().BeNull();
|
||||||
|
FeedReadings(sut, 10).Should().BeFalse("heating was never observed");
|
||||||
// Assert
|
|
||||||
result.Should().BeFalse();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void IsWaterReady_CooldownOnlySetOnFirstDetection_ShouldNotResetTimestamp()
|
public void IsWaterReady_CooldownOnlySetOnFirstDetection_ShouldNotResetTimestamp()
|
||||||
{
|
{
|
||||||
// Arrange — first detection sets _waterReadySince
|
var sut = CreateSutWithHeatingObserved();
|
||||||
var sut = CreateSut();
|
FeedReadings(sut, RequiredReadings);
|
||||||
sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
var originalTimestamp = sut.WaterReadySince;
|
||||||
|
|
||||||
// Advance halfway through cooldown
|
_timeProvider.Advance(TimeSpan.FromHours(2));
|
||||||
_timeProvider.Advance(BoilerMonitorConsts.WaterReadyCooldownPeriod / 2);
|
sut.IsWaterReady("on", 0.0, Threshold).Should().BeTrue();
|
||||||
|
|
||||||
// Act — second detection during cooldown should NOT reset the timestamp
|
sut.WaterReadySince.Should().Be(originalTimestamp);
|
||||||
sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
}
|
||||||
|
|
||||||
// Advance remaining half
|
[Theory]
|
||||||
_timeProvider.Advance(BoilerMonitorConsts.WaterReadyCooldownPeriod / 2);
|
[InlineData(Threshold)]
|
||||||
|
[InlineData(HighPowerWatts)]
|
||||||
|
[InlineData(double.MaxValue)]
|
||||||
|
public void IsWaterReady_PowerAtOrAboveThreshold_ShouldNotStartCooldown(double powerWatts)
|
||||||
|
{
|
||||||
|
var sut = CreateSutWithHeatingObserved();
|
||||||
|
|
||||||
|
FeedReadings(sut, RequiredReadings, powerWatts: powerWatts).Should().BeFalse();
|
||||||
|
|
||||||
// Assert — cooldown should have expired based on original timestamp
|
|
||||||
sut.IsInCooldown.Should().BeFalse();
|
sut.IsInCooldown.Should().BeFalse();
|
||||||
|
sut.WaterReadySince.Should().BeNull();
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void IsWaterReady_HighPowerDoesNotTriggerCooldown_ShouldReturnFalse()
|
public void NotifyTurnedOn_DuringActiveCooldown_ShouldNotClearCooldown()
|
||||||
|
{
|
||||||
|
var sut = CreateSutWithHeatingObserved();
|
||||||
|
FeedReadings(sut, RequiredReadings);
|
||||||
|
|
||||||
|
sut.NotifyTurnedOn();
|
||||||
|
|
||||||
|
sut.IsInCooldown.Should().BeTrue("NotifyTurnedOn must not clear the cooldown");
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region Cooldown persistence
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(BoilerMonitorTestData.CooldownRestoreSamples), MemberType = typeof(BoilerMonitorTestData))]
|
||||||
|
public void RestoreCooldownState_ShouldRestoreOnlyTimestampsFromTodayUtc(
|
||||||
|
string scenario,
|
||||||
|
DateTimeOffset now,
|
||||||
|
DateTimeOffset cooldownSince,
|
||||||
|
bool expectedRestored)
|
||||||
|
{
|
||||||
|
var timeProvider = BoilerMonitorTestData.CreateTimeProvider(now);
|
||||||
|
var sut = new WaterReadyService(_loggerMock.Object, timeProvider);
|
||||||
|
|
||||||
|
sut.RestoreCooldownState(cooldownSince);
|
||||||
|
|
||||||
|
sut.IsInCooldown.Should().Be(expectedRestored, scenario);
|
||||||
|
sut.WaterReadySince.Should().Be(expectedRestored ? cooldownSince : null, scenario);
|
||||||
|
sut.IsWaterReady("off", 0.0, Threshold).Should().Be(expectedRestored, scenario);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void WaterReadySince_ShouldReturnTimestampWhenCooldownActive()
|
||||||
|
{
|
||||||
|
var sut = CreateSutWithHeatingObserved();
|
||||||
|
var beforeTrigger = _timeProvider.GetUtcNow();
|
||||||
|
|
||||||
|
FeedReadings(sut, RequiredReadings).Should().BeTrue();
|
||||||
|
|
||||||
|
sut.WaterReadySince.Should().Be(beforeTrigger);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void WaterReadySince_ShouldReturnNullWhenNoCooldown()
|
||||||
{
|
{
|
||||||
// Arrange
|
|
||||||
var sut = CreateSut();
|
var sut = CreateSut();
|
||||||
|
|
||||||
// Act — water is not ready (high power), no cooldown should be triggered
|
sut.WaterReadySince.Should().BeNull();
|
||||||
sut.IsWaterReady("on", 2150.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
|
}
|
||||||
|
|
||||||
// Assert
|
#endregion
|
||||||
sut.IsInCooldown.Should().BeFalse();
|
|
||||||
|
#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
|
#endregion
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
using System.Globalization;
|
using System.Globalization;
|
||||||
using BoilerMonitor.Models;
|
using BoilerMonitor.Models;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
@@ -5,6 +7,8 @@ using NetDaemon.HassModel;
|
|||||||
using static BoilerMonitor.Models.BoilerMonitorConsts;
|
using static BoilerMonitor.Models.BoilerMonitorConsts;
|
||||||
using static NordPool.Models.NordPoolConsts;
|
using static NordPool.Models.NordPoolConsts;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace BoilerMonitorManager;
|
namespace BoilerMonitorManager;
|
||||||
|
|
||||||
public sealed class BoilerConfigReader(IHaContext haContext, ILogger<BoilerConfigReader> logger) : IBoilerConfigReader
|
public sealed class BoilerConfigReader(IHaContext haContext, ILogger<BoilerConfigReader> logger) : IBoilerConfigReader
|
||||||
@@ -14,20 +18,30 @@ public sealed class BoilerConfigReader(IHaContext haContext, ILogger<BoilerConfi
|
|||||||
public BoilerConfig ReadConfig()
|
public BoilerConfig ReadConfig()
|
||||||
{
|
{
|
||||||
var dailyHoursState = haContext.GetState(BoilerDailyHoursEntityId)?.State;
|
var dailyHoursState = haContext.GetState(BoilerDailyHoursEntityId)?.State;
|
||||||
var dailyHours = double.TryParse(dailyHoursState, NumberStyles.Any, CultureInfo.InvariantCulture, out var dh) ? dh : DefaultDailyHours;
|
|
||||||
|
var dailyHours = double.TryParse(dailyHoursState, NumberStyles.Any, CultureInfo.InvariantCulture, out var dh)
|
||||||
|
? dh
|
||||||
|
: DefaultDailyHours;
|
||||||
|
|
||||||
var intervalCount = (int)(dailyHours * IntervalsPerHour);
|
var intervalCount = (int)(dailyHours * IntervalsPerHour);
|
||||||
|
|
||||||
if (intervalCount <= 0)
|
if (intervalCount <= 0)
|
||||||
{
|
{
|
||||||
intervalCount = IntervalsPerHour;
|
intervalCount = IntervalsPerHour;
|
||||||
}
|
}
|
||||||
|
|
||||||
var priceCapState = haContext.GetState(BoilerPriceCapEntityId)?.State;
|
var priceCapState = haContext.GetState(BoilerPriceCapEntityId)?.State;
|
||||||
var priceCap = double.TryParse(priceCapState, NumberStyles.Any, CultureInfo.InvariantCulture, out var pc) && pc > 0 ? pc : double.MaxValue;
|
|
||||||
|
var priceCap =
|
||||||
|
double.TryParse(priceCapState, NumberStyles.Any, CultureInfo.InvariantCulture, out var pc) && pc > 0
|
||||||
|
? pc
|
||||||
|
: double.MaxValue;
|
||||||
|
|
||||||
var deadline = DateTime.Today.AddDays(1);
|
var deadline = DateTime.Today.AddDays(1);
|
||||||
var readyByState = haContext.GetState(BoilerReadyByEntityId)?.State;
|
var readyByState = haContext.GetState(BoilerReadyByEntityId)?.State;
|
||||||
if (!string.IsNullOrEmpty(readyByState) && TimeSpan.TryParse(readyByState, out var readyByTime))
|
|
||||||
|
if (!string.IsNullOrEmpty(readyByState) &&
|
||||||
|
TimeSpan.TryParse(readyByState, CultureInfo.InvariantCulture, out var readyByTime))
|
||||||
{
|
{
|
||||||
deadline = DateTime.Today.Add(readyByTime);
|
deadline = DateTime.Today.Add(readyByTime);
|
||||||
}
|
}
|
||||||
@@ -35,15 +49,21 @@ public sealed class BoilerConfigReader(IHaContext haContext, ILogger<BoilerConfi
|
|||||||
var skipPriceCapState = haContext.GetState(SkipPriceCapEntityId)?.State;
|
var skipPriceCapState = haContext.GetState(SkipPriceCapEntityId)?.State;
|
||||||
var skipPriceCap = string.Equals(skipPriceCapState, SwitchOnState, StringComparison.OrdinalIgnoreCase);
|
var skipPriceCap = string.Equals(skipPriceCapState, SwitchOnState, StringComparison.OrdinalIgnoreCase);
|
||||||
|
|
||||||
logger.LogDebug("Boiler config: intervals={Intervals}, priceCap={Cap}, skipPriceCap={Skip}, deadline={Deadline}",
|
if (logger.IsEnabled(LogLevel.Debug))
|
||||||
|
{
|
||||||
|
logger.LogDebug(
|
||||||
|
"Boiler config: intervals={Intervals}, priceCap={Cap}, skipPriceCap={Skip}, deadline={Deadline}",
|
||||||
intervalCount, priceCap, skipPriceCap, deadline);
|
intervalCount, priceCap, skipPriceCap, deadline);
|
||||||
|
}
|
||||||
|
|
||||||
return new BoilerConfig
|
var config = new BoilerConfig
|
||||||
{
|
{
|
||||||
IntervalCount = intervalCount,
|
IntervalCount = intervalCount,
|
||||||
PriceCap = priceCap,
|
PriceCap = priceCap,
|
||||||
Deadline = deadline,
|
Deadline = deadline,
|
||||||
SkipPriceCap = skipPriceCap
|
SkipPriceCap = skipPriceCap
|
||||||
};
|
};
|
||||||
|
|
||||||
|
return config;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,53 +1,74 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
using BoilerMonitor.Models.Enums;
|
using BoilerMonitor.Models.Enums;
|
||||||
using BoilerMonitorManager.Interface;
|
using BoilerMonitorManager.Interface;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace BoilerMonitorManager;
|
namespace BoilerMonitorManager;
|
||||||
|
|
||||||
public class BoilerControlService(ILogger<BoilerControlService> logger) : IBoilerControlService
|
public sealed class BoilerControlService(ILogger<BoilerControlService> logger) : IBoilerControlService
|
||||||
{
|
{
|
||||||
private const string SwitchOnState = "on";
|
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 isCurrentlyOn = string.Equals(currentSwitchState, SwitchOnState, StringComparison.OrdinalIgnoreCase);
|
||||||
var effectiveBudgetExhausted = budgetExhausted && !budgetOverride;
|
var effectiveBudgetExhausted = budgetExhausted && !budgetOverride;
|
||||||
var shouldBeOn = isNowCheap && !waterReady && !effectiveBudgetExhausted;
|
var shouldBeOn = isNowCheap && !waterReady && !effectiveBudgetExhausted;
|
||||||
|
|
||||||
if (shouldBeOn && !isCurrentlyOn)
|
switch (shouldBeOn, isCurrentlyOn)
|
||||||
{
|
{
|
||||||
logger.LogInformation("Boiler should turn ON — cheap interval active, water not ready, budget available (current state: {State})", currentSwitchState);
|
case (true, false):
|
||||||
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
return BoilerAction.TurnOn;
|
{
|
||||||
|
logger.LogInformation(
|
||||||
|
"Boiler should turn ON — cheap interval active, water not ready, budget available (current state: {State})",
|
||||||
|
currentSwitchState);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!shouldBeOn && isCurrentlyOn)
|
return BoilerAction.TurnOn;
|
||||||
{
|
|
||||||
var reason = GetTurnOffReason(waterReady, isNowCheap, effectiveBudgetExhausted);
|
|
||||||
|
|
||||||
logger.LogInformation("Boiler should turn OFF — {Reason} (current state: {State})", reason, currentSwitchState);
|
case (false, true):
|
||||||
|
{
|
||||||
|
var reason = GetTurnOffReason(waterReady, effectiveBudgetExhausted);
|
||||||
|
|
||||||
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
|
{
|
||||||
|
logger.LogInformation("Boiler should turn OFF — {Reason} (current state: {State})", reason,
|
||||||
|
currentSwitchState);
|
||||||
|
}
|
||||||
|
|
||||||
return BoilerAction.TurnOff;
|
return BoilerAction.TurnOff;
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.LogDebug("Boiler state unchanged: {State} (cheap={Cheap}, waterReady={WaterReady}, budgetExhausted={BudgetExhausted})",
|
default:
|
||||||
|
if (logger.IsEnabled(LogLevel.Debug))
|
||||||
|
{
|
||||||
|
logger.LogDebug(
|
||||||
|
"Boiler state unchanged: {State} (cheap={Cheap}, waterReady={WaterReady}, budgetExhausted={BudgetExhausted})",
|
||||||
currentSwitchState, isNowCheap, waterReady, effectiveBudgetExhausted);
|
currentSwitchState, isNowCheap, waterReady, effectiveBudgetExhausted);
|
||||||
|
}
|
||||||
|
|
||||||
return BoilerAction.NoChange;
|
return BoilerAction.NoChange;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private static string GetTurnOffReason(bool waterReady, bool isNowCheap, bool effectiveBudgetExhausted)
|
private static string GetTurnOffReason(bool waterReady, bool effectiveBudgetExhausted)
|
||||||
{
|
{
|
||||||
if (waterReady)
|
if (waterReady)
|
||||||
{
|
{
|
||||||
return "water is already ready";
|
return "water is already ready";
|
||||||
}
|
}
|
||||||
|
|
||||||
if (effectiveBudgetExhausted)
|
return effectiveBudgetExhausted
|
||||||
{
|
? "daily budget is exhausted"
|
||||||
return "daily budget is exhausted";
|
: "not in a cheap interval";
|
||||||
}
|
|
||||||
|
|
||||||
return "not in a cheap interval";
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -14,14 +14,15 @@
|
|||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\HomeAssistant.Entities\HomeAssistant.Entities.csproj" />
|
<ProjectReference Include="..\HomeAssistant.Entities\HomeAssistant.Entities.csproj"/>
|
||||||
<ProjectReference Include="..\BoilerMonitor.Models\BoilerMonitor.Models.csproj" />
|
<ProjectReference Include="..\BoilerMonitor.Models\BoilerMonitor.Models.csproj"/>
|
||||||
<ProjectReference Include="..\NordPool.Models\NordPool.Models.csproj" />
|
<ProjectReference Include="..\NordPool.Models\NordPool.Models.csproj"/>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.5" />
|
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="11.0.0"/>
|
||||||
<PackageReference Include="NetDaemon.HassModel" Version="26.11.0" />
|
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.43.1"/>
|
||||||
|
<PackageReference Include="NetDaemon.HassModel" Version="26.43.1"/>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
using System.Globalization;
|
using System.Globalization;
|
||||||
|
using System.Text.Json;
|
||||||
using BoilerMonitor.Models;
|
using BoilerMonitor.Models;
|
||||||
using BoilerMonitorManager.Interface;
|
using BoilerMonitorManager.Interface;
|
||||||
using BoilerMonitorManager.Models;
|
using BoilerMonitorManager.Models;
|
||||||
@@ -8,6 +11,8 @@ using NetDaemon.Extensions.MqttEntityManager;
|
|||||||
using NetDaemon.HassModel;
|
using NetDaemon.HassModel;
|
||||||
using static BoilerMonitor.Models.BoilerMonitorConsts;
|
using static BoilerMonitor.Models.BoilerMonitorConsts;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace BoilerMonitorManager;
|
namespace BoilerMonitorManager;
|
||||||
|
|
||||||
public sealed class BoilerMonitorEntityService(
|
public sealed class BoilerMonitorEntityService(
|
||||||
@@ -29,17 +34,10 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
BudgetPercentageEntityId,
|
BudgetPercentageEntityId,
|
||||||
BudgetExhaustedEntityId,
|
BudgetExhaustedEntityId,
|
||||||
SessionCountEntityId,
|
SessionCountEntityId,
|
||||||
BudgetOverrideEntityId
|
BudgetOverrideEntityId,
|
||||||
|
AutoManagementEntityId
|
||||||
];
|
];
|
||||||
|
|
||||||
private static object CreateDeviceBlock() => new
|
|
||||||
{
|
|
||||||
identifiers = new[] { DeviceIdentifier },
|
|
||||||
name = DeviceName,
|
|
||||||
model = DeviceName,
|
|
||||||
manufacturer = DeviceManufacturer
|
|
||||||
};
|
|
||||||
|
|
||||||
public async Task CreateEntitiesAsync(CancellationToken cancellationToken = default)
|
public async Task CreateEntitiesAsync(CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
cancellationToken.ThrowIfCancellationRequested();
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
@@ -49,8 +47,12 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
var createTasks = entities.Select(async entity =>
|
var createTasks = entities.Select(async entity =>
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
|
{
|
||||||
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
{
|
{
|
||||||
logger.LogInformation("Creating/re-registering MQTT entity: {EntityId}", entity.EntityId);
|
logger.LogInformation("Creating/re-registering MQTT entity: {EntityId}", entity.EntityId);
|
||||||
|
}
|
||||||
|
|
||||||
await entityManager.CreateEntityAsync(entity).ConfigureAwait(false);
|
await entityManager.CreateEntityAsync(entity).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
@@ -77,8 +79,10 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
ResetBudgetPercentageAsync(),
|
ResetBudgetPercentageAsync(),
|
||||||
ResetBudgetExhaustedAsync(),
|
ResetBudgetExhaustedAsync(),
|
||||||
ResetSessionCountAsync(),
|
ResetSessionCountAsync(),
|
||||||
ResetBudgetOverrideAsync()
|
ResetBudgetOverrideAsync(),
|
||||||
).ConfigureAwait(false);
|
ResetAutoManagementAsync()
|
||||||
|
)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
|
||||||
logger.LogInformation("All BoilerMonitor runtime entity states reset to defaults");
|
logger.LogInformation("All BoilerMonitor runtime entity states reset to defaults");
|
||||||
}
|
}
|
||||||
@@ -91,9 +95,6 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
var formattedRunTime = FormatTimeSpan(ctx.TodayRunTime);
|
var formattedRunTime = FormatTimeSpan(ctx.TodayRunTime);
|
||||||
var formattedRemaining = FormatTimeSpan(ctx.RemainingTime);
|
var formattedRemaining = FormatTimeSpan(ctx.RemainingTime);
|
||||||
|
|
||||||
// logger.LogInformation("Updating BoilerMonitor entities: runtime={RunTime}, remaining={Remaining}, budget={Budget}%, sessions={Sessions}",
|
|
||||||
// formattedRunTime, formattedRemaining, ctx.BudgetPercentage, ctx.SessionCount);
|
|
||||||
|
|
||||||
var updateTasks = new[]
|
var updateTasks = new[]
|
||||||
{
|
{
|
||||||
UpdateStatusAsync(StatusConfigured),
|
UpdateStatusAsync(StatusConfigured),
|
||||||
@@ -114,7 +115,7 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var removeTasks = CleanableEntityIds.Select(entityId => entityManager.RemoveEntity(entityId));
|
var removeTasks = CleanableEntityIds.Select(entityManager.RemoveEntity);
|
||||||
await Task.WhenAll(removeTasks).ConfigureAwait(false);
|
await Task.WhenAll(removeTasks).ConfigureAwait(false);
|
||||||
|
|
||||||
logger.LogInformation("BoilerMonitor entities cleaned up successfully (cleanup button retained)");
|
logger.LogInformation("BoilerMonitor entities cleaned up successfully (cleanup button retained)");
|
||||||
@@ -122,6 +123,7 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
logger.LogError(ex, "Error cleaning up BoilerMonitor entities");
|
logger.LogError(ex, "Error cleaning up BoilerMonitor entities");
|
||||||
|
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -135,7 +137,8 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
await Task.WhenAll(
|
await Task.WhenAll(
|
||||||
ResetStatusAsync(),
|
ResetStatusAsync(),
|
||||||
ResetWaterReadyAsync()
|
ResetWaterReadyAsync()
|
||||||
).ConfigureAwait(false);
|
)
|
||||||
|
.ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
public PersistedBoilerState? ReadPersistedState()
|
public PersistedBoilerState? ReadPersistedState()
|
||||||
@@ -147,11 +150,16 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
var skipPriceCapState = haContext.GetState(SkipPriceCapEntityId)?.State;
|
var skipPriceCapState = haContext.GetState(SkipPriceCapEntityId)?.State;
|
||||||
var budgetOverrideState = haContext.GetState(BudgetOverrideEntityId)?.State;
|
var budgetOverrideState = haContext.GetState(BudgetOverrideEntityId)?.State;
|
||||||
|
|
||||||
if (!TryParseEntitySeconds(runtimeState, out var runtimeSeconds)
|
if (!TryParseEntitySeconds(runtimeState, out var runtimeSeconds) ||
|
||||||
|| !TryParseEntityInt(sessionCountState, out var sessionCount))
|
!TryParseEntityInt(sessionCountState, out var sessionCount))
|
||||||
{
|
{
|
||||||
logger.LogInformation("No valid persisted BoilerMonitor state found in HA entities (runtime={Runtime}, sessions={Sessions})",
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
|
{
|
||||||
|
logger.LogInformation(
|
||||||
|
"No valid persisted BoilerMonitor state found in HA entities (runtime={Runtime}, sessions={Sessions})",
|
||||||
runtimeState, sessionCountState);
|
runtimeState, sessionCountState);
|
||||||
|
}
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -163,14 +171,20 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
BudgetOverrideState = budgetOverrideState
|
BudgetOverrideState = budgetOverrideState
|
||||||
};
|
};
|
||||||
|
|
||||||
logger.LogInformation("Restored persisted BoilerMonitor state: runtime={Runtime}, sessions={Sessions}, skipPriceCap={SkipPriceCap}, budgetOverride={BudgetOverride}",
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
persisted.AccumulatedRunTime, persisted.SessionCount, persisted.SkipPriceCapState, persisted.BudgetOverrideState);
|
{
|
||||||
|
logger.LogInformation(
|
||||||
|
"Restored persisted BoilerMonitor state: runtime={Runtime}, sessions={Sessions}, skipPriceCap={SkipPriceCap}, budgetOverride={BudgetOverride}",
|
||||||
|
persisted.AccumulatedRunTime, persisted.SessionCount, persisted.SkipPriceCapState,
|
||||||
|
persisted.BudgetOverrideState);
|
||||||
|
}
|
||||||
|
|
||||||
return persisted;
|
return persisted;
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
logger.LogError(ex, "Error reading persisted BoilerMonitor state from HA entities");
|
logger.LogError(ex, "Error reading persisted BoilerMonitor state from HA entities");
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -180,25 +194,78 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
await UpdateStatusAsync(status).ConfigureAwait(false);
|
await UpdateStatusAsync(status).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,
|
||||||
|
JsonElement { ValueKind: JsonValueKind.String } jsonElement =>
|
||||||
|
jsonElement.GetString(),
|
||||||
|
_ => null
|
||||||
|
};
|
||||||
|
|
||||||
|
if (stringValue is not null &&
|
||||||
|
DateTimeOffset.TryParse(stringValue, CultureInfo.InvariantCulture,
|
||||||
|
DateTimeStyles.RoundtripKind, out var parsed))
|
||||||
|
{
|
||||||
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
|
{
|
||||||
|
logger.LogInformation("Read persisted cooldown timestamp: {CooldownSince}", parsed);
|
||||||
|
}
|
||||||
|
|
||||||
|
return parsed;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.LogError(ex, "Error reading persisted cooldown timestamp");
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static object CreateDeviceBlock()
|
||||||
|
{
|
||||||
|
return new
|
||||||
|
{
|
||||||
|
identifiers = new[] { DeviceIdentifier },
|
||||||
|
name = DeviceName,
|
||||||
|
model = DeviceName,
|
||||||
|
manufacturer = DeviceManufacturer
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
private static bool TryParseEntitySeconds(string? state, out double seconds)
|
private static bool TryParseEntitySeconds(string? state, out double seconds)
|
||||||
{
|
{
|
||||||
seconds = 0;
|
seconds = 0;
|
||||||
return !string.IsNullOrWhiteSpace(state)
|
var tryParseEntitySeconds = !string.IsNullOrWhiteSpace(state) && state is not ("unavailable" or "unknown") && double.TryParse(state, CultureInfo.InvariantCulture, out seconds) && seconds >= 0;
|
||||||
&& state is not ("unavailable" or "unknown")
|
|
||||||
&& double.TryParse(state, CultureInfo.InvariantCulture, out seconds)
|
return tryParseEntitySeconds;
|
||||||
&& seconds >= 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static bool TryParseEntityInt(string? state, out int value)
|
private static bool TryParseEntityInt(string? state, out int value)
|
||||||
{
|
{
|
||||||
value = 0;
|
value = 0;
|
||||||
return !string.IsNullOrWhiteSpace(state)
|
var tryParseEntityInt = !string.IsNullOrWhiteSpace(state) && state is not ("unavailable" or "unknown") && int.TryParse(state, CultureInfo.InvariantCulture, out value) && value >= 0;
|
||||||
&& state is not ("unavailable" or "unknown")
|
|
||||||
&& int.TryParse(state, CultureInfo.InvariantCulture, out value)
|
return tryParseEntityInt;
|
||||||
&& value >= 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private ICollection<BoilerMonitorEntity> GetAllEntities()
|
private static ICollection<BoilerMonitorEntity> GetAllEntities()
|
||||||
{
|
{
|
||||||
var device = CreateDeviceBlock();
|
var device = CreateDeviceBlock();
|
||||||
|
|
||||||
@@ -224,7 +291,8 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
device
|
device
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
new BoilerMonitorEntity("number", "boilermonitor_config_heating_threshold", "Heating power threshold (watts)")
|
new BoilerMonitorEntity("number", "boilermonitor_config_heating_threshold",
|
||||||
|
"Heating power threshold (watts)")
|
||||||
{
|
{
|
||||||
AdditionalConfig = new
|
AdditionalConfig = new
|
||||||
{
|
{
|
||||||
@@ -254,11 +322,13 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
},
|
},
|
||||||
new BoilerMonitorEntity("sensor", "boilermonitor_today_runtime", "Today runtime")
|
new BoilerMonitorEntity("sensor", "boilermonitor_today_runtime", "Today runtime")
|
||||||
{
|
{
|
||||||
AdditionalConfig = new { unit_of_measurement = "s", icon = "mdi:timer", device_class = "duration", device }
|
AdditionalConfig = new
|
||||||
|
{ unit_of_measurement = "s", icon = "mdi:timer", device_class = "duration", device }
|
||||||
},
|
},
|
||||||
new BoilerMonitorEntity("sensor", "boilermonitor_remaining_time", "Remaining budget time")
|
new BoilerMonitorEntity("sensor", "boilermonitor_remaining_time", "Remaining budget time")
|
||||||
{
|
{
|
||||||
AdditionalConfig = new { unit_of_measurement = "s", icon = "mdi:timer-sand", device_class = "duration", device }
|
AdditionalConfig = new
|
||||||
|
{ unit_of_measurement = "s", icon = "mdi:timer-sand", device_class = "duration", device }
|
||||||
},
|
},
|
||||||
new BoilerMonitorEntity("sensor", "boilermonitor_budget_percentage", "Budget usage")
|
new BoilerMonitorEntity("sensor", "boilermonitor_budget_percentage", "Budget usage")
|
||||||
{
|
{
|
||||||
@@ -280,6 +350,10 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
new BoilerMonitorEntity("switch", "boilermonitor_budget_override", "Override budget enforcement")
|
new BoilerMonitorEntity("switch", "boilermonitor_budget_override", "Override budget enforcement")
|
||||||
{
|
{
|
||||||
AdditionalConfig = new { optimistic = true, icon = "mdi:shield-off-outline", device }
|
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 }
|
||||||
}
|
}
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
@@ -297,6 +371,7 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
private async Task ResetWaterReadyAsync()
|
private async Task ResetWaterReadyAsync()
|
||||||
{
|
{
|
||||||
await SetEntityStateSafe(WaterReadyEntityId, "unknown").ConfigureAwait(false);
|
await SetEntityStateSafe(WaterReadyEntityId, "unknown").ConfigureAwait(false);
|
||||||
|
|
||||||
await SetEntityAttributesSafe(WaterReadyEntityId, new
|
await SetEntityAttributesSafe(WaterReadyEntityId, new
|
||||||
{
|
{
|
||||||
boiler_switch_state = "unknown",
|
boiler_switch_state = "unknown",
|
||||||
@@ -304,7 +379,8 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
power_threshold_watts = DefaultHeatingPowerThresholdWatts,
|
power_threshold_watts = DefaultHeatingPowerThresholdWatts,
|
||||||
friendly_name = "Boiler water ready",
|
friendly_name = "Boiler water ready",
|
||||||
last_updated = (string?)null
|
last_updated = (string?)null
|
||||||
}).ConfigureAwait(false);
|
})
|
||||||
|
.ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task ResetSkipPriceCapAsync()
|
private async Task ResetSkipPriceCapAsync()
|
||||||
@@ -315,35 +391,41 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
private async Task ResetTodayRuntimeAsync()
|
private async Task ResetTodayRuntimeAsync()
|
||||||
{
|
{
|
||||||
await SetEntityStateSafe(TodayRuntimeEntityId, "0").ConfigureAwait(false);
|
await SetEntityStateSafe(TodayRuntimeEntityId, "0").ConfigureAwait(false);
|
||||||
|
|
||||||
await SetEntityAttributesSafe(TodayRuntimeEntityId, new
|
await SetEntityAttributesSafe(TodayRuntimeEntityId, new
|
||||||
{
|
{
|
||||||
formatted = "0h 0m",
|
formatted = "0h 0m",
|
||||||
friendly_name = "Today runtime",
|
friendly_name = "Today runtime",
|
||||||
last_updated = (string?)null
|
last_updated = (string?)null
|
||||||
}).ConfigureAwait(false);
|
})
|
||||||
|
.ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task ResetRemainingTimeAsync()
|
private async Task ResetRemainingTimeAsync()
|
||||||
{
|
{
|
||||||
await SetEntityStateSafe(RemainingTimeEntityId, "0").ConfigureAwait(false);
|
await SetEntityStateSafe(RemainingTimeEntityId, "0").ConfigureAwait(false);
|
||||||
|
|
||||||
await SetEntityAttributesSafe(RemainingTimeEntityId, new
|
await SetEntityAttributesSafe(RemainingTimeEntityId, new
|
||||||
{
|
{
|
||||||
formatted = "0h 0m",
|
formatted = "0h 0m",
|
||||||
budget_hours = 0.0,
|
budget_hours = 0.0,
|
||||||
friendly_name = "Remaining budget time",
|
friendly_name = "Remaining budget time",
|
||||||
last_updated = (string?)null
|
last_updated = (string?)null
|
||||||
}).ConfigureAwait(false);
|
})
|
||||||
|
.ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task ResetBudgetPercentageAsync()
|
private async Task ResetBudgetPercentageAsync()
|
||||||
{
|
{
|
||||||
await SetEntityStateSafe(BudgetPercentageEntityId, "0").ConfigureAwait(false);
|
await SetEntityStateSafe(BudgetPercentageEntityId, "0").ConfigureAwait(false);
|
||||||
|
|
||||||
await SetEntityAttributesSafe(BudgetPercentageEntityId, new
|
await SetEntityAttributesSafe(BudgetPercentageEntityId, new
|
||||||
{
|
{
|
||||||
unit_of_measurement = "%",
|
unit_of_measurement = "%",
|
||||||
friendly_name = "Budget usage",
|
friendly_name = "Budget usage",
|
||||||
last_updated = (string?)null
|
last_updated = (string?)null
|
||||||
}).ConfigureAwait(false);
|
})
|
||||||
|
.ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task ResetBudgetExhaustedAsync()
|
private async Task ResetBudgetExhaustedAsync()
|
||||||
@@ -354,11 +436,13 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
private async Task ResetSessionCountAsync()
|
private async Task ResetSessionCountAsync()
|
||||||
{
|
{
|
||||||
await SetEntityStateSafe(SessionCountEntityId, "0").ConfigureAwait(false);
|
await SetEntityStateSafe(SessionCountEntityId, "0").ConfigureAwait(false);
|
||||||
|
|
||||||
await SetEntityAttributesSafe(SessionCountEntityId, new
|
await SetEntityAttributesSafe(SessionCountEntityId, new
|
||||||
{
|
{
|
||||||
friendly_name = "Heating sessions today",
|
friendly_name = "Heating sessions today",
|
||||||
last_updated = (string?)null
|
last_updated = (string?)null
|
||||||
}).ConfigureAwait(false);
|
})
|
||||||
|
.ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task ResetBudgetOverrideAsync()
|
private async Task ResetBudgetOverrideAsync()
|
||||||
@@ -366,52 +450,76 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
await SetEntityStateSafe(BudgetOverrideEntityId, "OFF").ConfigureAwait(false);
|
await SetEntityStateSafe(BudgetOverrideEntityId, "OFF").ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async Task ResetAutoManagementAsync()
|
||||||
|
{
|
||||||
|
await SetEntityStateSafe(AutoManagementEntityId, "ON").ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
private async Task UpdateWaterReadyAsync(BoilerMonitorUpdateContext ctx, string timestamp)
|
private async Task UpdateWaterReadyAsync(BoilerMonitorUpdateContext ctx, string timestamp)
|
||||||
{
|
{
|
||||||
await SetEntityStateSafe(WaterReadyEntityId, ctx.WaterReady ? "yes" : "no").ConfigureAwait(false);
|
await SetEntityStateSafe(WaterReadyEntityId, ctx.WaterReady ? "yes" : "no").ConfigureAwait(false);
|
||||||
|
|
||||||
await SetEntityAttributesSafe(WaterReadyEntityId, new
|
await SetEntityAttributesSafe(WaterReadyEntityId, new
|
||||||
{
|
{
|
||||||
boiler_switch_state = ctx.BoilerSwitchState ?? "unknown",
|
boiler_switch_state = ctx.BoilerSwitchState ?? "unknown",
|
||||||
boiler_power_watts = ctx.BoilerPowerWatts,
|
boiler_power_watts = ctx.BoilerPowerWatts,
|
||||||
|
cooldown_since = ctx.CooldownSince?.ToString("O", CultureInfo.InvariantCulture),
|
||||||
friendly_name = "Boiler water ready",
|
friendly_name = "Boiler water ready",
|
||||||
last_updated = timestamp
|
last_updated = timestamp
|
||||||
}).ConfigureAwait(false);
|
})
|
||||||
|
.ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task UpdateTodayRuntimeAsync(TimeSpan runTime, string formatted, string timestamp)
|
private async Task UpdateTodayRuntimeAsync(TimeSpan runTime, string formatted, string timestamp)
|
||||||
{
|
{
|
||||||
await SetEntityStateSafe(TodayRuntimeEntityId, ((int)runTime.TotalSeconds).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
|
await SetEntityStateSafe(TodayRuntimeEntityId,
|
||||||
|
((int)runTime.TotalSeconds).ToString(CultureInfo.InvariantCulture))
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
|
||||||
await SetEntityAttributesSafe(TodayRuntimeEntityId, new
|
await SetEntityAttributesSafe(TodayRuntimeEntityId, new
|
||||||
{
|
{
|
||||||
formatted,
|
formatted,
|
||||||
friendly_name = "Today runtime",
|
friendly_name = "Today runtime",
|
||||||
last_updated = timestamp
|
last_updated = timestamp
|
||||||
}).ConfigureAwait(false);
|
})
|
||||||
|
.ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task UpdateRemainingTimeAsync(TimeSpan remaining, string formatted, double budgetHours, string timestamp)
|
private async Task UpdateRemainingTimeAsync(TimeSpan remaining,
|
||||||
|
string formatted,
|
||||||
|
double budgetHours,
|
||||||
|
string timestamp)
|
||||||
{
|
{
|
||||||
var remainingSeconds = Math.Max(0, (int)remaining.TotalSeconds);
|
var remainingSeconds = Math.Max(0, (int)remaining.TotalSeconds);
|
||||||
await SetEntityStateSafe(RemainingTimeEntityId, remainingSeconds.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
|
|
||||||
|
await SetEntityStateSafe(RemainingTimeEntityId, remainingSeconds.ToString(CultureInfo.InvariantCulture))
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
|
||||||
await SetEntityAttributesSafe(RemainingTimeEntityId, new
|
await SetEntityAttributesSafe(RemainingTimeEntityId, new
|
||||||
{
|
{
|
||||||
formatted,
|
formatted,
|
||||||
budget_hours = budgetHours,
|
budget_hours = budgetHours,
|
||||||
friendly_name = "Remaining budget time",
|
friendly_name = "Remaining budget time",
|
||||||
last_updated = timestamp
|
last_updated = timestamp
|
||||||
}).ConfigureAwait(false);
|
})
|
||||||
|
.ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task UpdateBudgetPercentageAsync(double percentage, string timestamp)
|
private async Task UpdateBudgetPercentageAsync(double percentage, string timestamp)
|
||||||
{
|
{
|
||||||
var clampedPercentage = Math.Clamp(percentage, 0, 100);
|
var clampedPercentage = Math.Clamp(percentage, 0, 100);
|
||||||
await SetEntityStateSafe(BudgetPercentageEntityId, ((int)clampedPercentage).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
|
|
||||||
|
await SetEntityStateSafe(BudgetPercentageEntityId,
|
||||||
|
((int)clampedPercentage).ToString(CultureInfo.InvariantCulture))
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
|
||||||
await SetEntityAttributesSafe(BudgetPercentageEntityId, new
|
await SetEntityAttributesSafe(BudgetPercentageEntityId, new
|
||||||
{
|
{
|
||||||
unit_of_measurement = "%",
|
unit_of_measurement = "%",
|
||||||
friendly_name = "Budget usage",
|
friendly_name = "Budget usage",
|
||||||
last_updated = timestamp
|
last_updated = timestamp
|
||||||
}).ConfigureAwait(false);
|
})
|
||||||
|
.ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task UpdateBudgetExhaustedAsync(bool exhausted)
|
private async Task UpdateBudgetExhaustedAsync(bool exhausted)
|
||||||
@@ -421,12 +529,15 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
|
|
||||||
private async Task UpdateSessionCountAsync(int sessionCount, string timestamp)
|
private async Task UpdateSessionCountAsync(int sessionCount, string timestamp)
|
||||||
{
|
{
|
||||||
await SetEntityStateSafe(SessionCountEntityId, sessionCount.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
|
await SetEntityStateSafe(SessionCountEntityId, sessionCount.ToString(CultureInfo.InvariantCulture))
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
|
||||||
await SetEntityAttributesSafe(SessionCountEntityId, new
|
await SetEntityAttributesSafe(SessionCountEntityId, new
|
||||||
{
|
{
|
||||||
friendly_name = "Heating sessions today",
|
friendly_name = "Heating sessions today",
|
||||||
last_updated = timestamp
|
last_updated = timestamp
|
||||||
}).ConfigureAwait(false);
|
})
|
||||||
|
.ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task SetEntityStateSafe(string entityId, string state)
|
private async Task SetEntityStateSafe(string entityId, string state)
|
||||||
@@ -434,8 +545,12 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
await entityManager.SetEntityState(entityId, state).ConfigureAwait(false);
|
await entityManager.SetEntityState(entityId, state).ConfigureAwait(false);
|
||||||
|
|
||||||
|
if (logger.IsEnabled(LogLevel.Debug))
|
||||||
|
{
|
||||||
logger.LogDebug("Successfully set state for {EntityId}: {State}", entityId, state);
|
logger.LogDebug("Successfully set state for {EntityId}: {State}", entityId, state);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
logger.LogError(ex, "Failed to set state for {EntityId} to {State}", entityId, state);
|
logger.LogError(ex, "Failed to set state for {EntityId} to {State}", entityId, state);
|
||||||
@@ -447,8 +562,12 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
await entityManager.SetEntityAttributes(entityId, attributes).ConfigureAwait(false);
|
await entityManager.SetEntityAttributes(entityId, attributes).ConfigureAwait(false);
|
||||||
|
|
||||||
|
if (logger.IsEnabled(LogLevel.Debug))
|
||||||
|
{
|
||||||
logger.LogDebug("Successfully set attributes for {EntityId}", entityId);
|
logger.LogDebug("Successfully set attributes for {EntityId}", entityId);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
logger.LogError(ex, "Failed to set attributes for {EntityId}", entityId);
|
logger.LogError(ex, "Failed to set attributes for {EntityId}", entityId);
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
using System.Globalization;
|
using System.Globalization;
|
||||||
using System.Reactive.Concurrency;
|
using System.Reactive.Concurrency;
|
||||||
|
using System.Text.Json;
|
||||||
using BoilerMonitor.Models.Enums;
|
using BoilerMonitor.Models.Enums;
|
||||||
using BoilerMonitorManager.Interface;
|
using BoilerMonitorManager.Interface;
|
||||||
using BoilerMonitorManager.Models;
|
using BoilerMonitorManager.Models;
|
||||||
@@ -12,23 +15,27 @@ using NetDaemon.HassModel;
|
|||||||
using NetDaemon.HassModel.Entities;
|
using NetDaemon.HassModel.Entities;
|
||||||
using static BoilerMonitor.Models.BoilerMonitorConsts;
|
using static BoilerMonitor.Models.BoilerMonitorConsts;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace BoilerMonitorManager;
|
namespace BoilerMonitorManager;
|
||||||
|
|
||||||
[NetDaemonApp]
|
[NetDaemonApp]
|
||||||
public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
public sealed class BoilerMonitorInit
|
||||||
{
|
{
|
||||||
private readonly ILogger<BoilerMonitorInit> _logger;
|
|
||||||
private readonly IHaContext _haContext;
|
|
||||||
private readonly IScheduler _scheduler;
|
|
||||||
private readonly IMqttEntityManager _mqttEntityManager;
|
|
||||||
private readonly IBoilerControlService _boilerControlService;
|
private readonly IBoilerControlService _boilerControlService;
|
||||||
private readonly IBoilerRunTimeTracker _tracker;
|
|
||||||
private readonly IBoilerMonitorEntityService _entityService;
|
private readonly IBoilerMonitorEntityService _entityService;
|
||||||
private readonly IWaterReadyService _waterReadyService;
|
private readonly IHaContext _haContext;
|
||||||
|
private readonly ILogger<BoilerMonitorInit> _logger;
|
||||||
|
private readonly IMqttEntityManager _mqttEntityManager;
|
||||||
private readonly BoilerMonitorOptions _options;
|
private readonly BoilerMonitorOptions _options;
|
||||||
|
private readonly IScheduler _scheduler;
|
||||||
|
|
||||||
|
private readonly TimeProvider _timeProvider;
|
||||||
|
private readonly IBoilerRunTimeTracker _tracker;
|
||||||
|
private readonly IWaterReadyService _waterReadyService;
|
||||||
|
private volatile bool _cleanedUp;
|
||||||
private bool _lastWaterReady;
|
private bool _lastWaterReady;
|
||||||
private bool _cleanedUp;
|
private DateTimeOffset? _lastWaterReadyNotificationSentAt;
|
||||||
|
|
||||||
public BoilerMonitorInit(
|
public BoilerMonitorInit(
|
||||||
IHaContext haContext,
|
IHaContext haContext,
|
||||||
@@ -39,7 +46,35 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
IBoilerRunTimeTracker tracker,
|
IBoilerRunTimeTracker tracker,
|
||||||
IBoilerMonitorEntityService entityService,
|
IBoilerMonitorEntityService entityService,
|
||||||
IWaterReadyService waterReadyService,
|
IWaterReadyService waterReadyService,
|
||||||
IOptions<BoilerMonitorOptions> options)
|
IOptions<BoilerMonitorOptions> options,
|
||||||
|
TimeProvider timeProvider)
|
||||||
|
: this(
|
||||||
|
haContext,
|
||||||
|
logger,
|
||||||
|
scheduler,
|
||||||
|
mqttEntityManager,
|
||||||
|
boilerControlService,
|
||||||
|
tracker,
|
||||||
|
entityService,
|
||||||
|
waterReadyService,
|
||||||
|
options,
|
||||||
|
timeProvider,
|
||||||
|
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;
|
_haContext = haContext;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
@@ -50,9 +85,13 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
_entityService = entityService;
|
_entityService = entityService;
|
||||||
_waterReadyService = waterReadyService;
|
_waterReadyService = waterReadyService;
|
||||||
_options = options.Value;
|
_options = options.Value;
|
||||||
|
_timeProvider = timeProvider;
|
||||||
|
|
||||||
|
if (startBackgroundScheduling)
|
||||||
|
{
|
||||||
_ = InitializeAndScheduleAsync();
|
_ = InitializeAndScheduleAsync();
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private async Task InitializeAndScheduleAsync()
|
private async Task InitializeAndScheduleAsync()
|
||||||
{
|
{
|
||||||
@@ -65,6 +104,8 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
ScheduleMidnightReset();
|
ScheduleMidnightReset();
|
||||||
ScheduleEndOfDayReminder();
|
ScheduleEndOfDayReminder();
|
||||||
SubscribeToSkipPriceCapChanges();
|
SubscribeToSkipPriceCapChanges();
|
||||||
|
SubscribeToAutoManagementChanges();
|
||||||
|
SubscribeToShowerState();
|
||||||
SubscribeToCleanupButton();
|
SubscribeToCleanupButton();
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
@@ -73,7 +114,7 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task InitializeAsync()
|
private async Task InitializeAsync()
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
@@ -88,19 +129,32 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
else
|
else
|
||||||
{
|
{
|
||||||
var persisted = _entityService.ReadPersistedState();
|
var persisted = _entityService.ReadPersistedState();
|
||||||
|
var persistedCooldown = _entityService.ReadPersistedCooldownTimestamp();
|
||||||
|
|
||||||
await _entityService.CreateEntitiesAsync();
|
await _entityService.CreateEntitiesAsync();
|
||||||
|
|
||||||
if (persisted is not null)
|
if (persisted is not null)
|
||||||
{
|
{
|
||||||
_tracker.RestoreFromSnapshot(persisted.AccumulatedRunTime, persisted.SessionCount);
|
_tracker.RestoreFromSnapshot();
|
||||||
|
|
||||||
|
if (persistedCooldown.HasValue)
|
||||||
|
{
|
||||||
|
_waterReadyService.RestoreCooldownState(persistedCooldown.Value);
|
||||||
|
}
|
||||||
|
|
||||||
await _entityService.ResetTransientEntitiesAsync();
|
await _entityService.ResetTransientEntitiesAsync();
|
||||||
_logger.LogInformation("BoilerMonitor state restored from HA entities: runtime={Runtime}, sessions={Sessions}",
|
|
||||||
|
if (_logger.IsEnabled(LogLevel.Information))
|
||||||
|
{
|
||||||
|
_logger.LogInformation(
|
||||||
|
"BoilerMonitor state restored from HA entities: runtime={Runtime}, sessions={Sessions}",
|
||||||
persisted.AccumulatedRunTime, persisted.SessionCount);
|
persisted.AccumulatedRunTime, persisted.SessionCount);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
await _entityService.ResetEntitiesAsync();
|
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");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -113,15 +167,11 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
_logger.LogError(ex, "Error initializing BoilerMonitor");
|
_logger.LogError(ex, "Error initializing BoilerMonitor");
|
||||||
|
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
await _entityService.CleanupEntitiesAsync(cancellationToken);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void SchedulePeriodicPolling()
|
private void SchedulePeriodicPolling()
|
||||||
{
|
{
|
||||||
var now = DateTime.Now;
|
var now = DateTime.Now;
|
||||||
@@ -130,19 +180,14 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
var delayUntilNext = TimeSpan.FromSeconds(secondsUntilNext);
|
var delayUntilNext = TimeSpan.FromSeconds(secondsUntilNext);
|
||||||
var nextPollTime = now.Add(delayUntilNext);
|
var nextPollTime = now.Add(delayUntilNext);
|
||||||
|
|
||||||
_logger.LogInformation("Scheduling BoilerMonitor polling every {Interval}s, first at {Time}", DefaultPollIntervalSeconds, nextPollTime);
|
if (_logger.IsEnabled(LogLevel.Information))
|
||||||
|
{
|
||||||
|
_logger.LogInformation("Scheduling BoilerMonitor polling every {Interval}s, first at {Time}",
|
||||||
|
DefaultPollIntervalSeconds, nextPollTime);
|
||||||
|
}
|
||||||
|
|
||||||
_scheduler.RunEvery(TimeSpan.FromSeconds(DefaultPollIntervalSeconds), nextPollTime, async void () =>
|
_scheduler.RunEvery(TimeSpan.FromSeconds(DefaultPollIntervalSeconds), nextPollTime,
|
||||||
{
|
() => _ = PollAndUpdateAsync());
|
||||||
try
|
|
||||||
{
|
|
||||||
await PollAndUpdateAsync();
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
_logger.LogError(ex, "Error during BoilerMonitor poll cycle");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void ScheduleMidnightReset()
|
private void ScheduleMidnightReset()
|
||||||
@@ -154,6 +199,7 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
_logger.LogInformation("Midnight reset: clearing boiler run time tracker and water ready cooldown");
|
_logger.LogInformation("Midnight reset: clearing boiler run time tracker and water ready cooldown");
|
||||||
_tracker.Reset();
|
_tracker.Reset();
|
||||||
_waterReadyService.ResetCooldown();
|
_waterReadyService.ResetCooldown();
|
||||||
|
_lastWaterReadyNotificationSentAt = null;
|
||||||
_ = _entityService.ResetEntitiesAsync();
|
_ = _entityService.ResetEntitiesAsync();
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
@@ -170,16 +216,20 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
var switchState = _haContext.GetState(SkipPriceCapEntityId);
|
var switchState = _haContext.GetState(SkipPriceCapEntityId);
|
||||||
if (string.Equals(switchState?.State, SwitchOnState, StringComparison.OrdinalIgnoreCase))
|
|
||||||
|
if (!string.Equals(switchState?.State, SwitchOnState, StringComparison.OrdinalIgnoreCase))
|
||||||
{
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
_haContext.CallService("notify", "mobile_app_marius_phone", null, new
|
_haContext.CallService("notify", "mobile_app_marius_phone", null, new
|
||||||
{
|
{
|
||||||
message = "Remember to turn off 'Skip price cap, heat until ready' if you're done heating.",
|
message = "Remember to turn off 'Skip price cap, heat until ready' if you're done heating.",
|
||||||
title = "Boiler reminder"
|
title = "Boiler reminder"
|
||||||
});
|
});
|
||||||
|
|
||||||
_logger.LogInformation("End-of-day reminder sent: skip price cap switch is still ON");
|
_logger.LogInformation("End-of-day reminder sent: skip price cap switch is still ON");
|
||||||
}
|
}
|
||||||
}
|
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
_logger.LogError(ex, "Error checking skip price cap reminder");
|
_logger.LogError(ex, "Error checking skip price cap reminder");
|
||||||
@@ -190,6 +240,7 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
private void SubscribeToSkipPriceCapChanges()
|
private void SubscribeToSkipPriceCapChanges()
|
||||||
{
|
{
|
||||||
var skipPriceCapSwitch = new Entity(_haContext, SkipPriceCapEntityId);
|
var skipPriceCapSwitch = new Entity(_haContext, SkipPriceCapEntityId);
|
||||||
|
|
||||||
skipPriceCapSwitch.StateChanges()
|
skipPriceCapSwitch.StateChanges()
|
||||||
.Subscribe(e =>
|
.Subscribe(e =>
|
||||||
{
|
{
|
||||||
@@ -203,9 +254,49 @@ 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()
|
private void SubscribeToCleanupButton()
|
||||||
{
|
{
|
||||||
var cleanupButton = new Entity(_haContext, CleanupButtonEntityId);
|
var cleanupButton = new Entity(_haContext, CleanupButtonEntityId);
|
||||||
|
|
||||||
cleanupButton.StateChanges()
|
cleanupButton.StateChanges()
|
||||||
.Subscribe(_ =>
|
.Subscribe(_ =>
|
||||||
{
|
{
|
||||||
@@ -227,19 +318,25 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
foreach (var entityId in configEntityIds)
|
foreach (var entityId in configEntityIds)
|
||||||
{
|
{
|
||||||
var subscription = await _mqttEntityManager.PrepareCommandSubscriptionAsync(entityId).ConfigureAwait(false);
|
var subscription = await _mqttEntityManager.PrepareCommandSubscriptionAsync(entityId).ConfigureAwait(false);
|
||||||
subscription.Subscribe(async void (state) =>
|
subscription.Subscribe(state => _ = HandleConfigCommandAsync(entityId, state));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task HandleConfigCommandAsync(string entityId, string? state)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
|
{
|
||||||
|
if (_logger.IsEnabled(LogLevel.Information))
|
||||||
{
|
{
|
||||||
_logger.LogInformation("Config entity {EntityId} received command: {Value}", entityId, state);
|
_logger.LogInformation("Config entity {EntityId} received command: {Value}", entityId, state);
|
||||||
await _mqttEntityManager.SetStateAsync(entityId, state).ConfigureAwait(false);
|
}
|
||||||
|
|
||||||
|
await _mqttEntityManager.SetStateAsync(entityId, state ?? string.Empty).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
_logger.LogError(e, "Error handling command for entity {EntityId}", entityId);
|
_logger.LogError(e, "Error handling command for entity {EntityId}", entityId);
|
||||||
}
|
}
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task SubscribeToSwitchCommandsAsync()
|
private async Task SubscribeToSwitchCommandsAsync()
|
||||||
@@ -247,25 +344,32 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
var switchEntityIds = new[]
|
var switchEntityIds = new[]
|
||||||
{
|
{
|
||||||
SkipPriceCapEntityId,
|
SkipPriceCapEntityId,
|
||||||
BudgetOverrideEntityId
|
BudgetOverrideEntityId,
|
||||||
|
AutoManagementEntityId
|
||||||
};
|
};
|
||||||
|
|
||||||
foreach (var entityId in switchEntityIds)
|
foreach (var entityId in switchEntityIds)
|
||||||
{
|
{
|
||||||
var subscription = await _mqttEntityManager.PrepareCommandSubscriptionAsync(entityId).ConfigureAwait(false);
|
var subscription = await _mqttEntityManager.PrepareCommandSubscriptionAsync(entityId).ConfigureAwait(false);
|
||||||
subscription.Subscribe(async void (state) =>
|
subscription.Subscribe(state => _ = HandleSwitchCommandAsync(entityId, state));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task HandleSwitchCommandAsync(string entityId, string? state)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
|
{
|
||||||
|
if (_logger.IsEnabled(LogLevel.Information))
|
||||||
{
|
{
|
||||||
_logger.LogInformation("Switch {EntityId} received command: {Value}", entityId, state);
|
_logger.LogInformation("Switch {EntityId} received command: {Value}", entityId, state);
|
||||||
await _mqttEntityManager.SetStateAsync(entityId, state).ConfigureAwait(false);
|
}
|
||||||
|
|
||||||
|
await _mqttEntityManager.SetStateAsync(entityId, state ?? string.Empty).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
_logger.LogError(e, "Error handling command for switch entity {EntityId}", entityId);
|
_logger.LogError(e, "Error handling command for switch entity {EntityId}", entityId);
|
||||||
}
|
}
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task HandleCleanupAsync()
|
private async Task HandleCleanupAsync()
|
||||||
@@ -288,6 +392,7 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
if (_cleanedUp)
|
if (_cleanedUp)
|
||||||
{
|
{
|
||||||
_logger.LogDebug("BoilerMonitor is cleaned up, skipping poll");
|
_logger.LogDebug("BoilerMonitor is cleaned up, skipping poll");
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -298,7 +403,9 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
if (!config.IsFullyConfigured)
|
if (!config.IsFullyConfigured)
|
||||||
{
|
{
|
||||||
await _entityService.SetStatusAsync(StatusAwaitingConfiguration);
|
await _entityService.SetStatusAsync(StatusAwaitingConfiguration);
|
||||||
_logger.LogWarning("BoilerMonitor not fully configured (power={Power}, switch={Switch}, interval={Interval}, threshold={Threshold}). Awaiting configuration",
|
|
||||||
|
_logger.LogWarning(
|
||||||
|
"BoilerMonitor not fully configured (power={Power}, switch={Switch}, interval={Interval}, threshold={Threshold}). Awaiting configuration",
|
||||||
config.BoilerPowerEntityId, config.BoilerSwitchEntityId,
|
config.BoilerPowerEntityId, config.BoilerSwitchEntityId,
|
||||||
config.PollIntervalSeconds, config.HeatingPowerThresholdWatts);
|
config.PollIntervalSeconds, config.HeatingPowerThresholdWatts);
|
||||||
|
|
||||||
@@ -307,14 +414,19 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
|
|
||||||
var boilerPowerWatts = ReadSensorDouble(config.BoilerPowerEntityId!);
|
var boilerPowerWatts = ReadSensorDouble(config.BoilerPowerEntityId!);
|
||||||
var boilerSwitchState = _haContext.GetState(config.BoilerSwitchEntityId!)?.State;
|
var boilerSwitchState = _haContext.GetState(config.BoilerSwitchEntityId!)?.State;
|
||||||
var isHeating = boilerPowerWatts.HasValue && boilerPowerWatts.Value >= config.HeatingPowerThresholdWatts!.Value;
|
|
||||||
var pollInterval = TimeSpan.FromSeconds(config.PollIntervalSeconds!.Value);
|
|
||||||
|
|
||||||
_tracker.RecordPollResult(isHeating, pollInterval);
|
var isHeating = boilerPowerWatts.HasValue &&
|
||||||
|
boilerPowerWatts.Value >= config.HeatingPowerThresholdWatts!.Value;
|
||||||
|
|
||||||
|
_tracker.RecordPollResult();
|
||||||
|
|
||||||
|
if (isHeating)
|
||||||
|
{
|
||||||
|
_waterReadyService.RecordHeatingObserved();
|
||||||
|
}
|
||||||
|
|
||||||
var cheapestIntervalsState = _haContext.GetState(NordPoolCheapestIntervalsEntityId);
|
var cheapestIntervalsState = _haContext.GetState(NordPoolCheapestIntervalsEntityId);
|
||||||
var isNowCheap = ReadAttributeBool(cheapestIntervalsState, "is_now_cheap");
|
var isNowCheap = ReadAttributeBool(cheapestIntervalsState, "is_now_cheap");
|
||||||
var nextCheapInterval = ReadAttributeDateTime(cheapestIntervalsState, "next_cheap_interval");
|
|
||||||
|
|
||||||
var budgetOverrideState = _haContext.GetState(BudgetOverrideEntityId)?.State;
|
var budgetOverrideState = _haContext.GetState(BudgetOverrideEntityId)?.State;
|
||||||
var budgetOverride = string.Equals(budgetOverrideState, SwitchOnState, StringComparison.OrdinalIgnoreCase);
|
var budgetOverride = string.Equals(budgetOverrideState, SwitchOnState, StringComparison.OrdinalIgnoreCase);
|
||||||
@@ -324,17 +436,21 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
|
|
||||||
var dailyHours = ReadSensorDouble(BoilerDailyHoursEntityId) ?? 1.0;
|
var dailyHours = ReadSensorDouble(BoilerDailyHoursEntityId) ?? 1.0;
|
||||||
|
|
||||||
var waterReady = _waterReadyService.IsWaterReady(boilerSwitchState, boilerPowerWatts, config.HeatingPowerThresholdWatts!.Value);
|
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
|
_haContext.CallService("notify", "mobile_app_marius_phone", null, new
|
||||||
{
|
{
|
||||||
message = "Hot water is ready.",
|
message = "Hot water is ready.",
|
||||||
title = "Boiler"
|
title = "Boiler"
|
||||||
});
|
});
|
||||||
|
|
||||||
|
_lastWaterReadyNotificationSentAt = _timeProvider.GetUtcNow();
|
||||||
_logger.LogInformation("Water ready notification sent");
|
_logger.LogInformation("Water ready notification sent");
|
||||||
}
|
}
|
||||||
|
|
||||||
_lastWaterReady = waterReady;
|
_lastWaterReady = waterReady;
|
||||||
|
|
||||||
var snapshot = _tracker.GetSnapshot();
|
var snapshot = _tracker.GetSnapshot();
|
||||||
@@ -347,16 +463,36 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
}
|
}
|
||||||
|
|
||||||
var budgetPercentage = budgetTimeSpan.TotalSeconds > 0
|
var budgetPercentage = budgetTimeSpan.TotalSeconds > 0
|
||||||
? (snapshot.AccumulatedRunTime.TotalSeconds / budgetTimeSpan.TotalSeconds) * 100.0
|
? snapshot.AccumulatedRunTime.TotalSeconds / budgetTimeSpan.TotalSeconds * 100.0
|
||||||
: 0.0;
|
: 0.0;
|
||||||
|
|
||||||
var budgetExhausted = snapshot.AccumulatedRunTime >= budgetTimeSpan;
|
var budgetExhausted = snapshot.AccumulatedRunTime >= budgetTimeSpan;
|
||||||
|
|
||||||
var effectiveIsNowCheap = isNowCheap || skipPriceCap;
|
var effectiveIsNowCheap = isNowCheap || skipPriceCap;
|
||||||
|
|
||||||
var boilerAction = _boilerControlService.DetermineAction(effectiveIsNowCheap, waterReady, boilerSwitchState, budgetExhausted, budgetOverride);
|
var boilerAction = _boilerControlService.DetermineAction(
|
||||||
|
effectiveIsNowCheap,
|
||||||
|
waterReady,
|
||||||
|
boilerSwitchState,
|
||||||
|
budgetExhausted,
|
||||||
|
budgetOverride);
|
||||||
|
|
||||||
|
var autoManagementState = _haContext.GetState(AutoManagementEntityId)?.State;
|
||||||
|
|
||||||
|
var autoManagementEnabled =
|
||||||
|
!string.Equals(autoManagementState, SwitchOffState, StringComparison.OrdinalIgnoreCase);
|
||||||
|
|
||||||
|
if (autoManagementEnabled)
|
||||||
|
{
|
||||||
ExecuteBoilerAction(boilerAction, config.BoilerSwitchEntityId!);
|
ExecuteBoilerAction(boilerAction, config.BoilerSwitchEntityId!);
|
||||||
|
}
|
||||||
|
else if (boilerAction is not BoilerAction.NoChange)
|
||||||
|
{
|
||||||
|
if (_logger.IsEnabled(LogLevel.Information))
|
||||||
|
{
|
||||||
|
_logger.LogInformation("Automatic boiler control is off; skipping boiler switch service call (would have been {Action})", boilerAction);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
var context = new BoilerMonitorUpdateContext
|
var context = new BoilerMonitorUpdateContext
|
||||||
{
|
{
|
||||||
@@ -366,19 +502,21 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
BudgetExhausted = budgetExhausted,
|
BudgetExhausted = budgetExhausted,
|
||||||
SessionCount = snapshot.SessionCount,
|
SessionCount = snapshot.SessionCount,
|
||||||
BudgetHours = dailyHours,
|
BudgetHours = dailyHours,
|
||||||
IsCurrentlyHeating = isHeating,
|
|
||||||
WaterReady = waterReady,
|
WaterReady = waterReady,
|
||||||
BoilerSwitchState = boilerSwitchState,
|
BoilerSwitchState = boilerSwitchState,
|
||||||
BoilerPowerWatts = boilerPowerWatts,
|
BoilerPowerWatts = boilerPowerWatts,
|
||||||
IsNowCheap = effectiveIsNowCheap,
|
CooldownSince = _waterReadyService.WaterReadySince
|
||||||
NextCheapIntervalStart = nextCheapInterval
|
|
||||||
};
|
};
|
||||||
|
|
||||||
await _entityService.UpdateEntitiesAsync(context);
|
await _entityService.UpdateEntitiesAsync(context);
|
||||||
|
|
||||||
_logger.LogDebug("Poll complete: power={Power}W, heating={Heating}, runtime={Runtime}, budget={Budget}%",
|
if (_logger.IsEnabled(LogLevel.Debug))
|
||||||
|
{
|
||||||
|
_logger.LogDebug(
|
||||||
|
"Poll complete: power={Power}W, heating={Heating}, runtime={Runtime}, budget={Budget}%",
|
||||||
boilerPowerWatts, isHeating, snapshot.AccumulatedRunTime, budgetPercentage);
|
boilerPowerWatts, isHeating, snapshot.AccumulatedRunTime, budgetPercentage);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
_logger.LogError(ex, "Error during BoilerMonitor poll and update");
|
_logger.LogError(ex, "Error during BoilerMonitor poll and update");
|
||||||
@@ -392,12 +530,17 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
case BoilerAction.TurnOn:
|
case BoilerAction.TurnOn:
|
||||||
_haContext.CallService("switch", "turn_on", ServiceTarget.FromEntity(switchEntityId));
|
_haContext.CallService("switch", "turn_on", ServiceTarget.FromEntity(switchEntityId));
|
||||||
_waterReadyService.NotifyTurnedOn();
|
_waterReadyService.NotifyTurnedOn();
|
||||||
|
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case BoilerAction.TurnOff:
|
case BoilerAction.TurnOff:
|
||||||
_haContext.CallService("switch", "turn_off", ServiceTarget.FromEntity(switchEntityId));
|
_haContext.CallService("switch", "turn_off", ServiceTarget.FromEntity(switchEntityId));
|
||||||
|
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case BoilerAction.NoChange:
|
case BoilerAction.NoChange:
|
||||||
break;
|
break;
|
||||||
|
|
||||||
default:
|
default:
|
||||||
throw new ArgumentOutOfRangeException(nameof(action), action, null);
|
throw new ArgumentOutOfRangeException(nameof(action), action, null);
|
||||||
}
|
}
|
||||||
@@ -411,9 +554,7 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
int? pollInterval = null;
|
int? pollInterval = null;
|
||||||
var pollIntervalState = _haContext.GetState(ConfigPollIntervalEntityId)?.State;
|
var pollIntervalState = _haContext.GetState(ConfigPollIntervalEntityId)?.State;
|
||||||
|
|
||||||
if (!string.IsNullOrWhiteSpace(pollIntervalState)
|
if (!string.IsNullOrWhiteSpace(pollIntervalState) && double.TryParse(pollIntervalState, CultureInfo.InvariantCulture, out var pollIntervalValue) && pollIntervalValue > 0)
|
||||||
&& double.TryParse(pollIntervalState, CultureInfo.InvariantCulture, out var pollIntervalValue)
|
|
||||||
&& pollIntervalValue > 0)
|
|
||||||
{
|
{
|
||||||
pollInterval = (int)pollIntervalValue;
|
pollInterval = (int)pollIntervalValue;
|
||||||
}
|
}
|
||||||
@@ -421,17 +562,15 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
double? heatingThreshold = null;
|
double? heatingThreshold = null;
|
||||||
var thresholdState = _haContext.GetState(ConfigHeatingThresholdEntityId)?.State;
|
var thresholdState = _haContext.GetState(ConfigHeatingThresholdEntityId)?.State;
|
||||||
|
|
||||||
if (!string.IsNullOrWhiteSpace(thresholdState)
|
if (!string.IsNullOrWhiteSpace(thresholdState) && double.TryParse(thresholdState, CultureInfo.InvariantCulture, out var thresholdValue) && thresholdValue > 0)
|
||||||
&& double.TryParse(thresholdState, CultureInfo.InvariantCulture, out var thresholdValue)
|
|
||||||
&& thresholdValue > 0)
|
|
||||||
{
|
{
|
||||||
heatingThreshold = thresholdValue;
|
heatingThreshold = thresholdValue;
|
||||||
}
|
}
|
||||||
|
|
||||||
return new BoilerMonitorConfig
|
return new BoilerMonitorConfig
|
||||||
{
|
{
|
||||||
BoilerPowerEntityId = string.IsNullOrWhiteSpace(powerEntityId) ? null : powerEntityId,
|
BoilerPowerEntityId = string.IsNullOrWhiteSpace(powerEntityId) ? null : powerEntityId.Trim(),
|
||||||
BoilerSwitchEntityId = string.IsNullOrWhiteSpace(switchEntityId) ? null : switchEntityId,
|
BoilerSwitchEntityId = string.IsNullOrWhiteSpace(switchEntityId) ? null : switchEntityId.Trim(),
|
||||||
PollIntervalSeconds = pollInterval,
|
PollIntervalSeconds = pollInterval,
|
||||||
HeatingPowerThresholdWatts = heatingThreshold
|
HeatingPowerThresholdWatts = heatingThreshold
|
||||||
};
|
};
|
||||||
@@ -451,19 +590,23 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
|
|
||||||
private static bool ReadAttributeBool(EntityState? entityState, string attributeName)
|
private static bool ReadAttributeBool(EntityState? entityState, string attributeName)
|
||||||
{
|
{
|
||||||
if (entityState?.Attributes is null)
|
if (entityState?.Attributes is not IDictionary<string, object> attributes)
|
||||||
{
|
{
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
if (entityState.Attributes is IDictionary<string, object> attributes && attributes.TryGetValue(attributeName, out var value))
|
if (attributes.TryGetValue(attributeName, out var value))
|
||||||
{
|
{
|
||||||
return value switch
|
return value switch
|
||||||
{
|
{
|
||||||
bool b => b,
|
bool b => b,
|
||||||
string s => bool.TryParse(s, out var parsed) && parsed,
|
string s => bool.TryParse(s, out var parsed) && parsed,
|
||||||
|
JsonElement { ValueKind: JsonValueKind.True } => true,
|
||||||
|
JsonElement { ValueKind: JsonValueKind.False } => false,
|
||||||
|
JsonElement { ValueKind: JsonValueKind.String } jsonElement =>
|
||||||
|
bool.TryParse(jsonElement.GetString(), out var jsonParsed) && jsonParsed,
|
||||||
_ => false
|
_ => false
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -476,28 +619,15 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static DateTime? ReadAttributeDateTime(EntityState? entityState, string attributeName)
|
private bool IsWithinNotificationCooldown()
|
||||||
{
|
{
|
||||||
if (entityState?.Attributes is null)
|
if (_lastWaterReadyNotificationSentAt is null)
|
||||||
{
|
{
|
||||||
return null;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
try
|
var elapsed = _timeProvider.GetUtcNow() - _lastWaterReadyNotificationSentAt.Value;
|
||||||
{
|
|
||||||
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))
|
|
||||||
{
|
|
||||||
return parsed;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch
|
|
||||||
{
|
|
||||||
// Attribute not found or not parseable
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
return elapsed < WaterReadyNotificationCooldown;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,10 +1,13 @@
|
|||||||
using BoilerMonitor.Models;
|
#region
|
||||||
|
|
||||||
using BoilerMonitorManager.Interface;
|
using BoilerMonitorManager.Interface;
|
||||||
using BoilerMonitorManager.Models;
|
using BoilerMonitorManager.Models;
|
||||||
using Microsoft.Extensions.Configuration;
|
using Microsoft.Extensions.Configuration;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using NetDaemon.AppModel;
|
using NetDaemon.AppModel;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace BoilerMonitorManager;
|
namespace BoilerMonitorManager;
|
||||||
|
|
||||||
public static class BoilerMonitorServiceRegistration
|
public static class BoilerMonitorServiceRegistration
|
||||||
@@ -13,7 +16,8 @@ public static class BoilerMonitorServiceRegistration
|
|||||||
{
|
{
|
||||||
var options = configuration
|
var options = configuration
|
||||||
.GetSection(BoilerMonitorOptions.SectionName)
|
.GetSection(BoilerMonitorOptions.SectionName)
|
||||||
.Get<BoilerMonitorOptions>() ?? new BoilerMonitorOptions();
|
.Get<BoilerMonitorOptions>() ??
|
||||||
|
new BoilerMonitorOptions();
|
||||||
|
|
||||||
if (!options.Enabled)
|
if (!options.Enabled)
|
||||||
{
|
{
|
||||||
@@ -23,11 +27,9 @@ public static class BoilerMonitorServiceRegistration
|
|||||||
services
|
services
|
||||||
.AddNetDaemonApp<BoilerMonitorInit>()
|
.AddNetDaemonApp<BoilerMonitorInit>()
|
||||||
.AddSingleton<IBoilerControlService, BoilerControlService>()
|
.AddSingleton<IBoilerControlService, BoilerControlService>()
|
||||||
.AddSingleton<IBoilerRunTimeTracker, BoilerRunTimeTracker>()
|
|
||||||
.AddTransient<IBoilerMonitorEntityService, BoilerMonitorEntityService>()
|
.AddTransient<IBoilerMonitorEntityService, BoilerMonitorEntityService>()
|
||||||
.AddSingleton<IWaterReadyService, WaterReadyService>()
|
.AddSingleton<IWaterReadyService, WaterReadyService>()
|
||||||
.AddSingleton(TimeProvider.System)
|
.AddSingleton<IBoilerRunTimeTracker, BoilerRunTimeTracker>();
|
||||||
.AddScoped<IBoilerConfigReader, BoilerConfigReader>();
|
|
||||||
|
|
||||||
return services;
|
return services;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,66 +1,32 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
using BoilerMonitorManager.Interface;
|
using BoilerMonitorManager.Interface;
|
||||||
using BoilerMonitorManager.Models;
|
using BoilerMonitorManager.Models;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace BoilerMonitorManager;
|
namespace BoilerMonitorManager;
|
||||||
|
|
||||||
public class BoilerRunTimeTracker : IBoilerRunTimeTracker
|
public class BoilerRunTimeTracker : IBoilerRunTimeTracker
|
||||||
{
|
{
|
||||||
private readonly Lock _lock = new();
|
public void RecordPollResult()
|
||||||
private TimeSpan _accumulatedRunTime = TimeSpan.Zero;
|
|
||||||
private int _sessionCount;
|
|
||||||
private bool _isInSession;
|
|
||||||
|
|
||||||
public void RecordPollResult(bool isHeating, TimeSpan pollInterval)
|
|
||||||
{
|
{
|
||||||
lock (_lock)
|
|
||||||
{
|
|
||||||
if (isHeating)
|
|
||||||
{
|
|
||||||
_accumulatedRunTime += pollInterval;
|
|
||||||
|
|
||||||
if (!_isInSession)
|
|
||||||
{
|
|
||||||
_sessionCount++;
|
|
||||||
_isInSession = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
_isInSession = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public RunTimeSnapshot GetSnapshot()
|
public RunTimeSnapshot GetSnapshot()
|
||||||
{
|
|
||||||
lock (_lock)
|
|
||||||
{
|
{
|
||||||
return new RunTimeSnapshot
|
return new RunTimeSnapshot
|
||||||
{
|
{
|
||||||
AccumulatedRunTime = _accumulatedRunTime,
|
AccumulatedRunTime = TimeSpan.Zero,
|
||||||
SessionCount = _sessionCount,
|
SessionCount = 0
|
||||||
IsInSession = _isInSession
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
public void Reset()
|
public void Reset()
|
||||||
{
|
{
|
||||||
lock (_lock)
|
|
||||||
{
|
|
||||||
_accumulatedRunTime = TimeSpan.Zero;
|
|
||||||
_sessionCount = 0;
|
|
||||||
_isInSession = false;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void RestoreFromSnapshot(TimeSpan accumulatedRunTime, int sessionCount)
|
public void RestoreFromSnapshot()
|
||||||
{
|
{
|
||||||
lock (_lock)
|
|
||||||
{
|
|
||||||
_accumulatedRunTime = accumulatedRunTime;
|
|
||||||
_sessionCount = sessionCount;
|
|
||||||
_isInSession = false;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,8 +1,17 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
using BoilerMonitor.Models.Enums;
|
using BoilerMonitor.Models.Enums;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace BoilerMonitorManager.Interface;
|
namespace BoilerMonitorManager.Interface;
|
||||||
|
|
||||||
public interface IBoilerControlService
|
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,5 +1,9 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
using BoilerMonitorManager.Models;
|
using BoilerMonitorManager.Models;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace BoilerMonitorManager.Interface;
|
namespace BoilerMonitorManager.Interface;
|
||||||
|
|
||||||
public interface IBoilerMonitorEntityService
|
public interface IBoilerMonitorEntityService
|
||||||
@@ -11,4 +15,5 @@ public interface IBoilerMonitorEntityService
|
|||||||
Task CleanupEntitiesAsync(CancellationToken cancellationToken = default);
|
Task CleanupEntitiesAsync(CancellationToken cancellationToken = default);
|
||||||
Task SetStatusAsync(string status);
|
Task SetStatusAsync(string status);
|
||||||
PersistedBoilerState? ReadPersistedState();
|
PersistedBoilerState? ReadPersistedState();
|
||||||
|
DateTimeOffset? ReadPersistedCooldownTimestamp();
|
||||||
}
|
}
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
namespace BoilerMonitorManager.Interface;
|
|
||||||
|
|
||||||
public interface IBoilerMonitorInit
|
|
||||||
{
|
|
||||||
Task InitializeAsync();
|
|
||||||
Task CleanupEntitiesAsync(CancellationToken cancellationToken = default);
|
|
||||||
}
|
|
||||||
@@ -1,11 +1,15 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
using BoilerMonitorManager.Models;
|
using BoilerMonitorManager.Models;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace BoilerMonitorManager.Interface;
|
namespace BoilerMonitorManager.Interface;
|
||||||
|
|
||||||
public interface IBoilerRunTimeTracker
|
public interface IBoilerRunTimeTracker
|
||||||
{
|
{
|
||||||
void RecordPollResult(bool isHeating, TimeSpan pollInterval);
|
void RecordPollResult();
|
||||||
RunTimeSnapshot GetSnapshot();
|
RunTimeSnapshot GetSnapshot();
|
||||||
void Reset();
|
void Reset();
|
||||||
void RestoreFromSnapshot(TimeSpan accumulatedRunTime, int sessionCount);
|
void RestoreFromSnapshot();
|
||||||
}
|
}
|
||||||
@@ -2,8 +2,11 @@ namespace BoilerMonitorManager.Interface;
|
|||||||
|
|
||||||
public interface IWaterReadyService
|
public interface IWaterReadyService
|
||||||
{
|
{
|
||||||
bool IsWaterReady(string? switchState, double? powerWatts, double heatingThresholdWatts);
|
|
||||||
bool IsInCooldown { get; }
|
bool IsInCooldown { get; }
|
||||||
|
DateTimeOffset? WaterReadySince { get; }
|
||||||
|
bool IsWaterReady(string? switchState, double? powerWatts, double heatingThresholdWatts);
|
||||||
void NotifyTurnedOn();
|
void NotifyTurnedOn();
|
||||||
|
void RecordHeatingObserved();
|
||||||
void ResetCooldown();
|
void ResetCooldown();
|
||||||
|
void RestoreCooldownState(DateTimeOffset waterReadySince);
|
||||||
}
|
}
|
||||||
@@ -7,8 +7,7 @@ public record BoilerMonitorConfig
|
|||||||
public int? PollIntervalSeconds { get; init; }
|
public int? PollIntervalSeconds { get; init; }
|
||||||
public double? HeatingPowerThresholdWatts { get; init; }
|
public double? HeatingPowerThresholdWatts { get; init; }
|
||||||
|
|
||||||
public bool IsFullyConfigured =>
|
public bool IsFullyConfigured => !string.IsNullOrWhiteSpace(BoilerPowerEntityId) &&
|
||||||
!string.IsNullOrWhiteSpace(BoilerPowerEntityId) &&
|
|
||||||
!string.IsNullOrWhiteSpace(BoilerSwitchEntityId) &&
|
!string.IsNullOrWhiteSpace(BoilerSwitchEntityId) &&
|
||||||
PollIntervalSeconds is > 0 &&
|
PollIntervalSeconds is > 0 &&
|
||||||
HeatingPowerThresholdWatts is > 0;
|
HeatingPowerThresholdWatts is > 0;
|
||||||
|
|||||||
@@ -8,10 +8,8 @@ public record BoilerMonitorUpdateContext
|
|||||||
public required bool BudgetExhausted { get; init; }
|
public required bool BudgetExhausted { get; init; }
|
||||||
public required int SessionCount { get; init; }
|
public required int SessionCount { get; init; }
|
||||||
public required double BudgetHours { get; init; }
|
public required double BudgetHours { get; init; }
|
||||||
public required bool IsCurrentlyHeating { get; init; }
|
|
||||||
public required bool WaterReady { get; init; }
|
public required bool WaterReady { get; init; }
|
||||||
public required string? BoilerSwitchState { get; init; }
|
public required string? BoilerSwitchState { get; init; }
|
||||||
public required double? BoilerPowerWatts { get; init; }
|
public required double? BoilerPowerWatts { get; init; }
|
||||||
public required bool IsNowCheap { get; init; }
|
public required DateTimeOffset? CooldownSince { get; init; }
|
||||||
public required DateTime? NextCheapIntervalStart { get; init; }
|
|
||||||
}
|
}
|
||||||
@@ -4,5 +4,4 @@ public record RunTimeSnapshot
|
|||||||
{
|
{
|
||||||
public required TimeSpan AccumulatedRunTime { get; init; }
|
public required TimeSpan AccumulatedRunTime { get; init; }
|
||||||
public required int SessionCount { get; init; }
|
public required int SessionCount { get; init; }
|
||||||
public required bool IsInSession { get; init; }
|
|
||||||
}
|
}
|
||||||
@@ -1,14 +1,19 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
using BoilerMonitor.Models;
|
using BoilerMonitor.Models;
|
||||||
using BoilerMonitorManager.Interface;
|
using BoilerMonitorManager.Interface;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace BoilerMonitorManager;
|
namespace BoilerMonitorManager;
|
||||||
|
|
||||||
public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimeProvider timeProvider) : IWaterReadyService
|
public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimeProvider timeProvider) : IWaterReadyService
|
||||||
{
|
{
|
||||||
private const string SwitchOnState = "on";
|
private const string SwitchOnState = "on";
|
||||||
private readonly Lock _lock = new();
|
private readonly Lock _lock = new Lock();
|
||||||
private DateTimeOffset? _lastTurnedOnAt;
|
private int _consecutiveBelowThresholdCount;
|
||||||
|
private bool _hasObservedHeating;
|
||||||
private DateTimeOffset? _waterReadySince;
|
private DateTimeOffset? _waterReadySince;
|
||||||
|
|
||||||
public bool IsInCooldown
|
public bool IsInCooldown
|
||||||
@@ -22,13 +27,29 @@ 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)
|
public bool IsWaterReady(string? switchState, double? powerWatts, double heatingThresholdWatts)
|
||||||
{
|
{
|
||||||
lock (_lock)
|
lock (_lock)
|
||||||
{
|
{
|
||||||
if (IsWithinCooldownPeriod())
|
if (IsWithinCooldownPeriod())
|
||||||
{
|
{
|
||||||
logger.LogDebug("Water ready cooldown active (since {Since}), suppressing turn-on", _waterReadySince);
|
if (logger.IsEnabled(LogLevel.Debug))
|
||||||
|
{
|
||||||
|
logger.LogDebug("Water ready cooldown active (since {Since}), suppressing turn-on",
|
||||||
|
_waterReadySince);
|
||||||
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -43,39 +64,79 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (IsWithinWarmUpGracePeriod())
|
lock (_lock)
|
||||||
{
|
{
|
||||||
logger.LogDebug(
|
if (!_hasObservedHeating)
|
||||||
"Ignoring low power reading ({PowerWatts}W) during warm-up grace period",
|
{
|
||||||
|
if (logger.IsEnabled(LogLevel.Debug))
|
||||||
|
{
|
||||||
|
logger.LogDebug("Ignoring power reading ({PowerWatts}W) — boiler has not been observed heating yet",
|
||||||
powerWatts.Value);
|
powerWatts.Value);
|
||||||
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
var isReady = powerWatts.Value < heatingThresholdWatts;
|
if (powerWatts.Value >= heatingThresholdWatts)
|
||||||
|
{
|
||||||
|
_consecutiveBelowThresholdCount = 0;
|
||||||
|
|
||||||
if (isReady)
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
_consecutiveBelowThresholdCount++;
|
||||||
|
|
||||||
|
if (_consecutiveBelowThresholdCount < BoilerMonitorConsts.ConsecutiveReadingsRequired)
|
||||||
{
|
{
|
||||||
lock (_lock)
|
if (logger.IsEnabled(LogLevel.Debug))
|
||||||
{
|
{
|
||||||
|
logger.LogDebug(
|
||||||
|
"Below-threshold reading {Count}/{Required} ({PowerWatts}W), waiting for confirmation",
|
||||||
|
_consecutiveBelowThresholdCount, BoilerMonitorConsts.ConsecutiveReadingsRequired,
|
||||||
|
powerWatts.Value);
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
_waterReadySince ??= timeProvider.GetUtcNow();
|
_waterReadySince ??= timeProvider.GetUtcNow();
|
||||||
}
|
|
||||||
|
|
||||||
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
|
{
|
||||||
logger.LogInformation(
|
logger.LogInformation(
|
||||||
"Water detected as ready, cooldown period ({CooldownPeriod}) started",
|
"Water detected as ready after {Count} consecutive readings, cooldown active until shower or midnight reset",
|
||||||
BoilerMonitorConsts.WaterReadyCooldownPeriod);
|
_consecutiveBelowThresholdCount);
|
||||||
}
|
}
|
||||||
|
|
||||||
return isReady;
|
return true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void NotifyTurnedOn()
|
public void NotifyTurnedOn()
|
||||||
{
|
{
|
||||||
lock (_lock)
|
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()
|
public void ResetCooldown()
|
||||||
@@ -83,33 +144,40 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
|
|||||||
lock (_lock)
|
lock (_lock)
|
||||||
{
|
{
|
||||||
_waterReadySince = null;
|
_waterReadySince = null;
|
||||||
|
_consecutiveBelowThresholdCount = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.LogInformation("Water ready cooldown has been reset");
|
logger.LogInformation("Water ready cooldown has been reset");
|
||||||
}
|
}
|
||||||
|
|
||||||
private bool IsWithinCooldownPeriod()
|
public void RestoreCooldownState(DateTimeOffset waterReadySince)
|
||||||
{
|
|
||||||
if (_waterReadySince is null)
|
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
var elapsed = timeProvider.GetUtcNow() - _waterReadySince.Value;
|
|
||||||
return elapsed < BoilerMonitorConsts.WaterReadyCooldownPeriod;
|
|
||||||
}
|
|
||||||
|
|
||||||
private bool IsWithinWarmUpGracePeriod()
|
|
||||||
{
|
{
|
||||||
lock (_lock)
|
lock (_lock)
|
||||||
{
|
{
|
||||||
if (_lastTurnedOnAt is null)
|
var todayMidnightUtc = new DateTimeOffset(timeProvider.GetUtcNow().Date, TimeSpan.Zero);
|
||||||
|
|
||||||
|
if (waterReadySince < todayMidnightUtc)
|
||||||
{
|
{
|
||||||
return false;
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
|
{
|
||||||
|
logger.LogInformation("Persisted cooldown is from a previous day ({Since}), not restoring",
|
||||||
|
waterReadySince);
|
||||||
}
|
}
|
||||||
|
|
||||||
var elapsed = timeProvider.GetUtcNow() - _lastTurnedOnAt.Value;
|
return;
|
||||||
return elapsed < BoilerMonitorConsts.WarmUpGracePeriod;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
_waterReadySince = waterReadySince;
|
||||||
|
|
||||||
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
|
{
|
||||||
|
logger.LogInformation("Restored water ready cooldown from {Since}", waterReadySince);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool IsWithinCooldownPeriod()
|
||||||
|
{
|
||||||
|
return _waterReadySince is not null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -8,11 +8,11 @@
|
|||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\HomeAssistant.Models\HomeAssistant.Models.csproj" />
|
<ProjectReference Include="..\HomeAssistant.Models\HomeAssistant.Models.csproj"/>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="NetDaemon.Extensions.Mqtt" Version="26.11.0" />
|
<PackageReference Include="NetDaemon.Extensions.Mqtt" Version="26.43.1"/>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
@@ -11,18 +11,14 @@ public static class BoilerMonitorConsts
|
|||||||
public const double DefaultHeatingPowerThresholdWatts = 5.0;
|
public const double DefaultHeatingPowerThresholdWatts = 5.0;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Grace period after the boiler switch is turned on, during which
|
/// Number of consecutive below-threshold power readings required before
|
||||||
/// low power readings are ignored for "water ready" detection.
|
/// declaring water as ready. Prevents false positives from transient sensor glitches.
|
||||||
/// This prevents false positives caused by the heating element ramp-up delay.
|
/// At 30s poll interval, a value of 2 means 60s of confirmed low power.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public static readonly TimeSpan WarmUpGracePeriod = TimeSpan.FromMinutes(2);
|
public const int ConsecutiveReadingsRequired = 2;
|
||||||
|
|
||||||
/// <summary>
|
public const string ShowerStateEntityId = "sensor.showermonitor_state";
|
||||||
/// Cooldown period after the water has been detected as ready,
|
public const string ShowerActiveState = "Active";
|
||||||
/// during which the boiler will not be turned back on.
|
|
||||||
/// This prevents wasteful on/off cycling when water is already heated.
|
|
||||||
/// </summary>
|
|
||||||
public static readonly TimeSpan WaterReadyCooldownPeriod = TimeSpan.FromHours(1);
|
|
||||||
|
|
||||||
public const int MinPollIntervalSeconds = 5;
|
public const int MinPollIntervalSeconds = 5;
|
||||||
public const int MaxPollIntervalSeconds = 300;
|
public const int MaxPollIntervalSeconds = 300;
|
||||||
@@ -49,6 +45,12 @@ public static class BoilerMonitorConsts
|
|||||||
public const string SessionCountEntityId = "sensor.boilermonitor_session_count";
|
public const string SessionCountEntityId = "sensor.boilermonitor_session_count";
|
||||||
public const string BudgetOverrideEntityId = "switch.boilermonitor_budget_override";
|
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 NordPoolCheapestIntervalsEntityId = "sensor.nordpool_cheapest_intervals";
|
||||||
|
|
||||||
public const string BoilerDailyHoursEntityId = "input_number.boiler_daily_hours";
|
public const string BoilerDailyHoursEntityId = "input_number.boiler_daily_hours";
|
||||||
@@ -57,11 +59,18 @@ public static class BoilerMonitorConsts
|
|||||||
|
|
||||||
public const string StatusConfigured = "configured";
|
public const string StatusConfigured = "configured";
|
||||||
public const string StatusAwaitingConfiguration = "awaiting_configuration";
|
public const string StatusAwaitingConfiguration = "awaiting_configuration";
|
||||||
public const string StatusCleanedUp = "cleaned_up";
|
|
||||||
|
|
||||||
public const string SwitchOnState = "on";
|
public const string SwitchOnState = "on";
|
||||||
|
|
||||||
|
public const string SwitchOffState = "off";
|
||||||
|
|
||||||
public const string DeviceIdentifier = "boiler_monitor";
|
public const string DeviceIdentifier = "boiler_monitor";
|
||||||
public const string DeviceName = "Boiler Monitor";
|
public const string DeviceName = "Boiler Monitor";
|
||||||
public const string DeviceManufacturer = "HomeAssistant App Daemon";
|
public const string DeviceManufacturer = "HomeAssistant App Daemon";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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 WaterReadyNotificationCooldown = TimeSpan.FromHours(1);
|
||||||
}
|
}
|
||||||
@@ -1,14 +1,14 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
using HomeAssistant.Models;
|
using HomeAssistant.Models;
|
||||||
using NetDaemon.Extensions.MqttEntityManager;
|
using NetDaemon.Extensions.MqttEntityManager;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace BoilerMonitor.Models;
|
namespace BoilerMonitor.Models;
|
||||||
|
|
||||||
public class BoilerMonitorEntity : EntityCreateModel
|
public class BoilerMonitorEntity : EntityCreateModel
|
||||||
{
|
{
|
||||||
public string Domain { get; set; }
|
|
||||||
public string Identifier { get; set; }
|
|
||||||
public string Name { get; set; }
|
|
||||||
|
|
||||||
public BoilerMonitorEntity(string domain, string identifier, string name)
|
public BoilerMonitorEntity(string domain, string identifier, string name)
|
||||||
{
|
{
|
||||||
Domain = domain;
|
Domain = domain;
|
||||||
@@ -22,4 +22,8 @@ public class BoilerMonitorEntity : EntityCreateModel
|
|||||||
Name = Name
|
Name = Name
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private string Domain { get; }
|
||||||
|
private string Identifier { get; }
|
||||||
|
private string Name { get; }
|
||||||
}
|
}
|
||||||
@@ -1321,6 +1321,8 @@ public partial class SwitchEntities
|
|||||||
public SwitchEntity BalkonyLaps => new(_haContext, "switch.balkony_laps");
|
public SwitchEntity BalkonyLaps => new(_haContext, "switch.balkony_laps");
|
||||||
///<summary>Boiler Monitor Override budget enforcement</summary>
|
///<summary>Boiler Monitor Override budget enforcement</summary>
|
||||||
public SwitchEntity BoilermonitorBudgetOverride => new(_haContext, "switch.boilermonitor_budget_override");
|
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>
|
///<summary>Boiler Monitor Skip price cap, heat until ready</summary>
|
||||||
public SwitchEntity BoilermonitorSkipPriceCap => new(_haContext, "switch.boilermonitor_skip_price_cap");
|
public SwitchEntity BoilermonitorSkipPriceCap => new(_haContext, "switch.boilermonitor_skip_price_cap");
|
||||||
///<summary>Dishwasher</summary>
|
///<summary>Dishwasher</summary>
|
||||||
|
|||||||
@@ -1,15 +1,28 @@
|
|||||||
using HomeAssistant.Entities.Interfaces;
|
#region
|
||||||
|
|
||||||
|
using HomeAssistant.Entities.Interfaces;
|
||||||
using HomeAssistant.Models;
|
using HomeAssistant.Models;
|
||||||
|
using HomeAssistantGenerated;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
using NetDaemon.Extensions.MqttEntityManager;
|
using NetDaemon.Extensions.MqttEntityManager;
|
||||||
|
using NetDaemon.HassModel;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace HomeAssistant.Entities;
|
namespace HomeAssistant.Entities;
|
||||||
|
|
||||||
public class EntityManager(IMqttEntityManager entityManager) : IEntityManager
|
public class EntityManager(
|
||||||
|
IMqttEntityManager entityManager,
|
||||||
|
IHaContext haContext,
|
||||||
|
IOptions<MqttConfiguration> mqttConfiguration) : IEntityManager
|
||||||
{
|
{
|
||||||
public async Task CreateEntitiesAsync(ICollection<EntityCreateModel> entities)
|
/// <summary>
|
||||||
{
|
/// Every topic owned by an entity created through <see cref="IMqttEntityManager" />:
|
||||||
await Task.WhenAll(entities.Select(CreateEntityAsync));
|
/// <c>state</c>, <c>attributes</c>, <c>availability</c>, <c>set</c> and <c>config</c>.
|
||||||
}
|
/// The discovery config topic comes last: an empty retained payload on it is what removes the
|
||||||
|
/// entity from Home Assistant.
|
||||||
|
/// </summary>
|
||||||
|
private static readonly string[] CleanupTopicSuffixes = ["state", "attributes", "availability", "set", "config"];
|
||||||
|
|
||||||
public async Task CreateEntityAsync(EntityCreateModel createModel)
|
public async Task CreateEntityAsync(EntityCreateModel createModel)
|
||||||
{
|
{
|
||||||
@@ -29,8 +42,48 @@ public class EntityManager(IMqttEntityManager entityManager) : IEntityManager
|
|||||||
await entityManager.SetAttributesAsync(entityId, attributes);
|
await entityManager.SetAttributesAsync(entityId, attributes);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task RemoveEntity(string entityId)
|
/// <summary>
|
||||||
|
/// Removes the entity from Home Assistant and clears every retained MQTT message it owns at the broker.
|
||||||
|
/// <para>
|
||||||
|
/// <see cref="IMqttEntityManager.RemoveAsync" /> publishes the empty discovery payload without the
|
||||||
|
/// retain flag, so Home Assistant forgets the entity but the broker keeps the retained config and
|
||||||
|
/// re-discovers the entity after a Home Assistant restart or MQTT reload. Publishing an empty
|
||||||
|
/// retained payload through Home Assistant's <c>mqtt.publish</c> service clears the retained
|
||||||
|
/// messages and removes the entity for good.
|
||||||
|
/// </para>
|
||||||
|
/// </summary>
|
||||||
|
public Task RemoveEntity(string entityId)
|
||||||
{
|
{
|
||||||
await entityManager.RemoveAsync(entityId);
|
var rootTopic = BuildRootTopic(entityId, mqttConfiguration.Value.DiscoveryPrefix);
|
||||||
|
|
||||||
|
foreach (var suffix in CleanupTopicSuffixes)
|
||||||
|
{
|
||||||
|
haContext.CallService("mqtt", "publish", null, new MqttPublishParameters
|
||||||
|
{
|
||||||
|
Topic = $"{rootTopic}/{suffix}",
|
||||||
|
Payload = string.Empty,
|
||||||
|
Retain = true
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// IHaContext.CallService is fire-and-forget; the calls are queued in order on the HA websocket.
|
||||||
|
return Task.CompletedTask;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string BuildRootTopic(string entityId, string discoveryPrefix)
|
||||||
|
{
|
||||||
|
var separatorIndex = entityId.IndexOf('.');
|
||||||
|
|
||||||
|
if (separatorIndex <= 0 || separatorIndex == entityId.Length - 1)
|
||||||
|
{
|
||||||
|
throw new ArgumentException(
|
||||||
|
$"Entity id '{entityId}' is not in the 'domain.object_id' format.",
|
||||||
|
nameof(entityId));
|
||||||
|
}
|
||||||
|
|
||||||
|
var domain = entityId[..separatorIndex];
|
||||||
|
var objectId = entityId[(separatorIndex + 1)..];
|
||||||
|
|
||||||
|
return $"{discoveryPrefix}/{domain}/{objectId}";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -7,18 +7,18 @@
|
|||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="NetDaemon.AppModel" Version="26.11.0" />
|
<PackageReference Include="NetDaemon.AppModel" Version="26.43.1"/>
|
||||||
<PackageReference Include="NetDaemon.Extensions.Mqtt" Version="26.11.0" />
|
<PackageReference Include="NetDaemon.Extensions.Mqtt" Version="26.43.1"/>
|
||||||
<PackageReference Include="NetDaemon.Runtime" Version="26.11.0" />
|
<PackageReference Include="NetDaemon.Runtime" Version="26.43.1"/>
|
||||||
<PackageReference Include="NetDaemon.HassModel" Version="26.11.0" />
|
<PackageReference Include="NetDaemon.HassModel" Version="26.43.1"/>
|
||||||
<PackageReference Include="NetDaemon.Client" Version="26.11.0" />
|
<PackageReference Include="NetDaemon.Client" Version="26.43.1"/>
|
||||||
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.11.0" />
|
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.43.1"/>
|
||||||
<PackageReference Include="NetDaemon.Extensions.Logging" Version="26.11.0" />
|
<PackageReference Include="NetDaemon.Extensions.Logging" Version="26.43.1"/>
|
||||||
<PackageReference Include="NetDaemon.Extensions.Tts" Version="26.11.0" />
|
<PackageReference Include="NetDaemon.Extensions.Tts" Version="26.43.1"/>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\HomeAssistant.Models\HomeAssistant.Models.csproj" />
|
<ProjectReference Include="..\HomeAssistant.Models\HomeAssistant.Models.csproj"/>
|
||||||
<ProjectReference Include="..\NordPool.Models\NordPool.Models.csproj" />
|
<ProjectReference Include="..\NordPool.Models\NordPool.Models.csproj"/>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
@@ -1,10 +1,13 @@
|
|||||||
using HomeAssistant.Models;
|
#region
|
||||||
|
|
||||||
|
using HomeAssistant.Models;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace HomeAssistant.Entities.Interfaces;
|
namespace HomeAssistant.Entities.Interfaces;
|
||||||
|
|
||||||
public interface IEntityManager
|
public interface IEntityManager
|
||||||
{
|
{
|
||||||
Task CreateEntitiesAsync(ICollection<EntityCreateModel> entities);
|
|
||||||
Task CreateEntityAsync(EntityCreateModel createModel);
|
Task CreateEntityAsync(EntityCreateModel createModel);
|
||||||
Task SetEntityState(string entityId, string state);
|
Task SetEntityState(string entityId, string state);
|
||||||
Task SetEntityAttributes(string entityId, object attributes);
|
Task SetEntityAttributes(string entityId, object attributes);
|
||||||
|
|||||||
@@ -1,69 +0,0 @@
|
|||||||
using BoilerMonitor.Models;
|
|
||||||
using LightMonitor.Models;
|
|
||||||
using NordPool.Models;
|
|
||||||
using ShowerMonitor.Models;
|
|
||||||
|
|
||||||
namespace HomeAssistant.HistoryReplay.Configuration;
|
|
||||||
|
|
||||||
public static class ReplayEntityMap
|
|
||||||
{
|
|
||||||
public static IReadOnlyList<string> GetNordPoolEntities() =>
|
|
||||||
[
|
|
||||||
"sensor.nordpool_kwh_lt_eur_3_10_0",
|
|
||||||
NordPoolConsts.CurrentPriceEntityId,
|
|
||||||
BoilerMonitorConsts.BoilerDailyHoursEntityId,
|
|
||||||
BoilerMonitorConsts.BoilerPriceCapEntityId,
|
|
||||||
BoilerMonitorConsts.BoilerReadyByEntityId,
|
|
||||||
BoilerMonitorConsts.SkipPriceCapEntityId
|
|
||||||
];
|
|
||||||
|
|
||||||
public static IReadOnlyList<string> GetBoilerEntities(string boilerPowerEntityId, string boilerSwitchEntityId) =>
|
|
||||||
[
|
|
||||||
boilerPowerEntityId,
|
|
||||||
boilerSwitchEntityId,
|
|
||||||
"sensor.nordpool_cheapest_intervals",
|
|
||||||
BoilerMonitorConsts.SkipPriceCapEntityId,
|
|
||||||
BoilerMonitorConsts.BudgetOverrideEntityId,
|
|
||||||
BoilerMonitorConsts.BoilerDailyHoursEntityId
|
|
||||||
];
|
|
||||||
|
|
||||||
public static IReadOnlyList<string> GetShowerEntities(string bathroomHumidityEntityId, string mainHomeHumidityEntityId) =>
|
|
||||||
[
|
|
||||||
bathroomHumidityEntityId,
|
|
||||||
mainHomeHumidityEntityId
|
|
||||||
];
|
|
||||||
|
|
||||||
public static IReadOnlyList<string> GetPowerEntities(string mainMeterEntityId) =>
|
|
||||||
[
|
|
||||||
mainMeterEntityId,
|
|
||||||
NordPoolConsts.CurrentPriceEntityId
|
|
||||||
];
|
|
||||||
|
|
||||||
public static IReadOnlyList<string> GetLightEntities(string sunEntityId, string lightEntityId, string[] personEntityIds)
|
|
||||||
{
|
|
||||||
var entities = new List<string> { sunEntityId, lightEntityId };
|
|
||||||
entities.AddRange(personEntityIds);
|
|
||||||
return entities;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static IReadOnlyList<string> GetAllEntities(
|
|
||||||
string boilerPowerEntityId,
|
|
||||||
string boilerSwitchEntityId,
|
|
||||||
string bathroomHumidityEntityId,
|
|
||||||
string mainHomeHumidityEntityId,
|
|
||||||
string mainMeterEntityId,
|
|
||||||
string sunEntityId,
|
|
||||||
string lightEntityId,
|
|
||||||
string[] personEntityIds)
|
|
||||||
{
|
|
||||||
var all = new HashSet<string>();
|
|
||||||
|
|
||||||
foreach (var e in GetNordPoolEntities()) all.Add(e);
|
|
||||||
foreach (var e in GetBoilerEntities(boilerPowerEntityId, boilerSwitchEntityId)) all.Add(e);
|
|
||||||
foreach (var e in GetShowerEntities(bathroomHumidityEntityId, mainHomeHumidityEntityId)) all.Add(e);
|
|
||||||
foreach (var e in GetPowerEntities(mainMeterEntityId)) all.Add(e);
|
|
||||||
foreach (var e in GetLightEntities(sunEntityId, lightEntityId, personEntityIds)) all.Add(e);
|
|
||||||
|
|
||||||
return [.. all];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
namespace HomeAssistant.HistoryReplay.Configuration;
|
|
||||||
|
|
||||||
public sealed class ReplayOptions
|
|
||||||
{
|
|
||||||
public const string SectionName = "Replay";
|
|
||||||
|
|
||||||
public DateTimeOffset StartTime { get; set; } = DateTimeOffset.UtcNow.AddDays(-1);
|
|
||||||
public DateTimeOffset EndTime { get; set; } = DateTimeOffset.UtcNow;
|
|
||||||
public ReplayMonitorFlags Monitors { get; set; } = new();
|
|
||||||
}
|
|
||||||
|
|
||||||
public sealed class ReplayMonitorFlags
|
|
||||||
{
|
|
||||||
public bool NordPool { get; set; } = true;
|
|
||||||
public bool Boiler { get; set; } = true;
|
|
||||||
public bool Shower { get; set; } = true;
|
|
||||||
public bool Power { get; set; } = true;
|
|
||||||
public bool Light { get; set; } = true;
|
|
||||||
}
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
namespace HomeAssistant.HistoryReplay.HistoryData;
|
|
||||||
|
|
||||||
public sealed class HistoryStateEntry
|
|
||||||
{
|
|
||||||
public required string EntityId { get; init; }
|
|
||||||
public required string? State { get; init; }
|
|
||||||
public required DateTimeOffset LastChanged { get; init; }
|
|
||||||
public IReadOnlyDictionary<string, object>? Attributes { get; init; }
|
|
||||||
}
|
|
||||||
@@ -1,65 +0,0 @@
|
|||||||
namespace HomeAssistant.HistoryReplay.HistoryData;
|
|
||||||
|
|
||||||
public sealed class HistoryTimeline
|
|
||||||
{
|
|
||||||
private readonly Dictionary<string, List<HistoryStateEntry>> _entityTimelines = new(StringComparer.OrdinalIgnoreCase);
|
|
||||||
|
|
||||||
public void AddEntries(string entityId, IEnumerable<HistoryStateEntry> entries)
|
|
||||||
{
|
|
||||||
if (!_entityTimelines.TryGetValue(entityId, out var list))
|
|
||||||
{
|
|
||||||
list = [];
|
|
||||||
_entityTimelines[entityId] = list;
|
|
||||||
}
|
|
||||||
|
|
||||||
list.AddRange(entries);
|
|
||||||
list.Sort((a, b) => a.LastChanged.CompareTo(b.LastChanged));
|
|
||||||
}
|
|
||||||
|
|
||||||
public HistoryStateEntry? GetStateAt(string entityId, DateTimeOffset timestamp)
|
|
||||||
{
|
|
||||||
if (!_entityTimelines.TryGetValue(entityId, out var entries) || entries.Count == 0)
|
|
||||||
{
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
HistoryStateEntry? best = null;
|
|
||||||
foreach (var entry in entries)
|
|
||||||
{
|
|
||||||
if (entry.LastChanged <= timestamp)
|
|
||||||
{
|
|
||||||
best = entry;
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return best;
|
|
||||||
}
|
|
||||||
|
|
||||||
public IReadOnlyList<DateTimeOffset> GetAllTimestamps()
|
|
||||||
{
|
|
||||||
var timestamps = new SortedSet<DateTimeOffset>();
|
|
||||||
|
|
||||||
foreach (var entries in _entityTimelines.Values)
|
|
||||||
{
|
|
||||||
foreach (var entry in entries)
|
|
||||||
{
|
|
||||||
timestamps.Add(entry.LastChanged);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return [.. timestamps];
|
|
||||||
}
|
|
||||||
|
|
||||||
public IReadOnlyList<string> GetEntityIds() => [.. _entityTimelines.Keys];
|
|
||||||
|
|
||||||
public IReadOnlyList<HistoryStateEntry> GetEntityHistory(string entityId)
|
|
||||||
{
|
|
||||||
return _entityTimelines.TryGetValue(entityId, out var entries) ? entries : [];
|
|
||||||
}
|
|
||||||
|
|
||||||
public int TotalEntryCount => _entityTimelines.Values.Sum(e => e.Count);
|
|
||||||
}
|
|
||||||
@@ -1,168 +0,0 @@
|
|||||||
using System.Globalization;
|
|
||||||
using System.Text.Json;
|
|
||||||
using HomeAssistant.HistoryReplay.HomeAssistantClient;
|
|
||||||
using Microsoft.Extensions.Logging;
|
|
||||||
|
|
||||||
namespace HomeAssistant.HistoryReplay.HistoryData;
|
|
||||||
|
|
||||||
public sealed class HomeAssistantHistoryProvider(
|
|
||||||
IHomeAssistantApiClient client,
|
|
||||||
ILogger<HomeAssistantHistoryProvider> logger) : IHistoryDataProvider
|
|
||||||
{
|
|
||||||
private const int MaxEntitiesPerRequest = 10;
|
|
||||||
|
|
||||||
public async Task<HistoryTimeline> FetchHistoryAsync(
|
|
||||||
IReadOnlyList<string> entityIds,
|
|
||||||
DateTimeOffset startTime,
|
|
||||||
DateTimeOffset endTime,
|
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
var timeline = new HistoryTimeline();
|
|
||||||
var batches = ChunkEntities(entityIds, MaxEntitiesPerRequest);
|
|
||||||
|
|
||||||
var tasks = batches.Select(batch => FetchBatchAsync(batch, startTime, endTime, cancellationToken));
|
|
||||||
var results = await Task.WhenAll(tasks).ConfigureAwait(false);
|
|
||||||
|
|
||||||
foreach (var batchTimeline in results)
|
|
||||||
{
|
|
||||||
foreach (var entityId in batchTimeline.GetEntityIds())
|
|
||||||
{
|
|
||||||
timeline.AddEntries(entityId, batchTimeline.GetEntityHistory(entityId));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
logger.LogInformation(
|
|
||||||
"Fetched history for {EntityCount} entities: {EntryCount} total entries ({Start} to {End})",
|
|
||||||
entityIds.Count, timeline.TotalEntryCount, startTime, endTime);
|
|
||||||
|
|
||||||
return timeline;
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task<HistoryTimeline> FetchBatchAsync(
|
|
||||||
IReadOnlyList<string> entityIds,
|
|
||||||
DateTimeOffset startTime,
|
|
||||||
DateTimeOffset endTime,
|
|
||||||
CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
var timeline = new HistoryTimeline();
|
|
||||||
var entityIdsString = string.Join(",", entityIds);
|
|
||||||
|
|
||||||
logger.LogDebug("Fetching history batch for: {Entities}", entityIdsString);
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var result = await client.GetHistoryAsync(
|
|
||||||
entityIdsString, startTime, endTime, minimalResponse: false, cancellationToken)
|
|
||||||
.ConfigureAwait(false);
|
|
||||||
|
|
||||||
ParseHistoryResponse(result, timeline);
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
logger.LogError(ex, "Failed to fetch history for entities: {Entities}", entityIdsString);
|
|
||||||
}
|
|
||||||
|
|
||||||
return timeline;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void ParseHistoryResponse(JsonElement response, HistoryTimeline timeline)
|
|
||||||
{
|
|
||||||
if (response.ValueKind != JsonValueKind.Array)
|
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
foreach (var entityArray in response.EnumerateArray())
|
|
||||||
{
|
|
||||||
if (entityArray.ValueKind != JsonValueKind.Array)
|
|
||||||
{
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
foreach (var stateObj in entityArray.EnumerateArray())
|
|
||||||
{
|
|
||||||
var entry = ParseStateEntry(stateObj);
|
|
||||||
if (entry is not null)
|
|
||||||
{
|
|
||||||
timeline.AddEntries(entry.EntityId, [entry]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private HistoryStateEntry? ParseStateEntry(JsonElement stateObj)
|
|
||||||
{
|
|
||||||
if (!stateObj.TryGetProperty("entity_id", out var entityIdProp))
|
|
||||||
{
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
var entityId = entityIdProp.GetString();
|
|
||||||
if (string.IsNullOrEmpty(entityId))
|
|
||||||
{
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
var state = stateObj.TryGetProperty("state", out var stateProp) ? stateProp.GetString() : null;
|
|
||||||
|
|
||||||
DateTimeOffset lastChanged;
|
|
||||||
if (stateObj.TryGetProperty("last_changed", out var lastChangedProp))
|
|
||||||
{
|
|
||||||
if (!DateTimeOffset.TryParse(lastChangedProp.GetString(), CultureInfo.InvariantCulture,
|
|
||||||
DateTimeStyles.RoundtripKind, out lastChanged))
|
|
||||||
{
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
Dictionary<string, object>? attributes = null;
|
|
||||||
if (stateObj.TryGetProperty("attributes", out var attrProp) && attrProp.ValueKind == JsonValueKind.Object)
|
|
||||||
{
|
|
||||||
attributes = ParseAttributes(attrProp);
|
|
||||||
}
|
|
||||||
|
|
||||||
return new HistoryStateEntry
|
|
||||||
{
|
|
||||||
EntityId = entityId,
|
|
||||||
State = state,
|
|
||||||
LastChanged = lastChanged,
|
|
||||||
Attributes = attributes
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Dictionary<string, object> ParseAttributes(JsonElement attrElement)
|
|
||||||
{
|
|
||||||
var attributes = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
|
|
||||||
|
|
||||||
foreach (var prop in attrElement.EnumerateObject())
|
|
||||||
{
|
|
||||||
attributes[prop.Name] = prop.Value.ValueKind switch
|
|
||||||
{
|
|
||||||
JsonValueKind.String => prop.Value.GetString() ?? string.Empty,
|
|
||||||
JsonValueKind.Number => prop.Value.GetDouble(),
|
|
||||||
JsonValueKind.True => true,
|
|
||||||
JsonValueKind.False => false,
|
|
||||||
_ => prop.Value.GetRawText()
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
return attributes;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static IReadOnlyList<IReadOnlyList<string>> ChunkEntities(IReadOnlyList<string> entities, int chunkSize)
|
|
||||||
{
|
|
||||||
var chunks = new List<IReadOnlyList<string>>();
|
|
||||||
|
|
||||||
for (var i = 0; i < entities.Count; i += chunkSize)
|
|
||||||
{
|
|
||||||
var chunk = entities.Skip(i).Take(chunkSize).ToList();
|
|
||||||
chunks.Add(chunk);
|
|
||||||
}
|
|
||||||
|
|
||||||
return chunks;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
namespace HomeAssistant.HistoryReplay.HistoryData;
|
|
||||||
|
|
||||||
public interface IHistoryDataProvider
|
|
||||||
{
|
|
||||||
Task<HistoryTimeline> FetchHistoryAsync(
|
|
||||||
IReadOnlyList<string> entityIds,
|
|
||||||
DateTimeOffset startTime,
|
|
||||||
DateTimeOffset endTime,
|
|
||||||
CancellationToken cancellationToken = default);
|
|
||||||
}
|
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
|
||||||
|
|
||||||
<PropertyGroup>
|
|
||||||
<OutputType>Exe</OutputType>
|
|
||||||
<TargetFramework>net10.0</TargetFramework>
|
|
||||||
<LangVersion>14.0</LangVersion>
|
|
||||||
<Nullable>enable</Nullable>
|
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
|
||||||
<RootNamespace>HomeAssistant.HistoryReplay</RootNamespace>
|
|
||||||
</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="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>
|
|
||||||
<ProjectReference Include="..\BoilerMonitor.Manager\BoilerMonitor.Manager.csproj" />
|
|
||||||
<ProjectReference Include="..\BoilerMonitor.Models\BoilerMonitor.Models.csproj" />
|
|
||||||
<ProjectReference Include="..\NordPool.Manager\NordPool.Manager.csproj" />
|
|
||||||
<ProjectReference Include="..\NordPool.Models\NordPool.Models.csproj" />
|
|
||||||
<ProjectReference Include="..\PowerMonitor.Manager\PowerMonitor.Manager.csproj" />
|
|
||||||
<ProjectReference Include="..\PowerMonitor.Models\PowerMonitor.Models.csproj" />
|
|
||||||
<ProjectReference Include="..\ShowerMonitor.Manager\ShowerMonitor.Manager.csproj" />
|
|
||||||
<ProjectReference Include="..\ShowerMonitor.Models\ShowerMonitor.Models.csproj" />
|
|
||||||
<ProjectReference Include="..\LightMonitor.Manager\LightMonitor.Manager.csproj" />
|
|
||||||
<ProjectReference Include="..\LightMonitor.Models\LightMonitor.Models.csproj" />
|
|
||||||
<ProjectReference Include="..\HomeAssistant.Entities\HomeAssistant.Entities.csproj" />
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
</Project>
|
|
||||||
@@ -1,50 +0,0 @@
|
|||||||
using System.Net.Http.Headers;
|
|
||||||
using System.Text.Json;
|
|
||||||
using Microsoft.Extensions.Options;
|
|
||||||
|
|
||||||
namespace HomeAssistant.HistoryReplay.HomeAssistantClient;
|
|
||||||
|
|
||||||
public sealed class HomeAssistantApiClient : IHomeAssistantApiClient
|
|
||||||
{
|
|
||||||
private readonly HttpClient _httpClient;
|
|
||||||
|
|
||||||
public HomeAssistantApiClient(HttpClient httpClient, IOptions<HomeAssistantSettings> settings)
|
|
||||||
{
|
|
||||||
_httpClient = httpClient;
|
|
||||||
_httpClient.BaseAddress = settings.Value.BaseUrl;
|
|
||||||
_httpClient.DefaultRequestHeaders.Authorization =
|
|
||||||
new AuthenticationHeaderValue("Bearer", settings.Value.Token);
|
|
||||||
_httpClient.DefaultRequestHeaders.Accept.Add(
|
|
||||||
new MediaTypeWithQualityHeaderValue("application/json"));
|
|
||||||
_httpClient.Timeout = TimeSpan.FromSeconds(HomeAssistantSettings.DefaultTimeoutSeconds);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task<JsonElement> GetHistoryAsync(
|
|
||||||
string entityIds,
|
|
||||||
DateTimeOffset? startTime = null,
|
|
||||||
DateTimeOffset? endTime = null,
|
|
||||||
bool minimalResponse = true,
|
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
var start = startTime ?? DateTimeOffset.UtcNow.AddDays(-1);
|
|
||||||
var path = $"/api/history/period/{start:O}?filter_entity_id={Uri.EscapeDataString(entityIds)}";
|
|
||||||
|
|
||||||
if (endTime.HasValue)
|
|
||||||
path += $"&end_time={Uri.EscapeDataString(endTime.Value.ToString("O"))}";
|
|
||||||
|
|
||||||
if (minimalResponse)
|
|
||||||
path += "&minimal_response";
|
|
||||||
|
|
||||||
return await GetJsonAsync(path, cancellationToken).ConfigureAwait(false);
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task<JsonElement> GetJsonAsync(string path, CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
var response = await _httpClient.GetAsync(path, cancellationToken).ConfigureAwait(false);
|
|
||||||
response.EnsureSuccessStatusCode();
|
|
||||||
|
|
||||||
await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
|
|
||||||
var doc = await JsonDocument.ParseAsync(stream, cancellationToken: cancellationToken).ConfigureAwait(false);
|
|
||||||
return doc.RootElement.Clone();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
namespace HomeAssistant.HistoryReplay.HomeAssistantClient;
|
|
||||||
|
|
||||||
public sealed class HomeAssistantSettings
|
|
||||||
{
|
|
||||||
public const string SectionName = "HomeAssistant";
|
|
||||||
public const int DefaultPort = 8123;
|
|
||||||
public const int DefaultTimeoutSeconds = 30;
|
|
||||||
|
|
||||||
public string Host { get; set; } = string.Empty;
|
|
||||||
public int Port { get; set; } = DefaultPort;
|
|
||||||
public string Token { get; set; } = string.Empty;
|
|
||||||
public bool Ssl { get; set; }
|
|
||||||
|
|
||||||
public Uri BaseUrl => new UriBuilder(Ssl ? "https" : "http", Host, Port).Uri;
|
|
||||||
}
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
using System.Text.Json;
|
|
||||||
|
|
||||||
namespace HomeAssistant.HistoryReplay.HomeAssistantClient;
|
|
||||||
|
|
||||||
public interface IHomeAssistantApiClient
|
|
||||||
{
|
|
||||||
Task<JsonElement> GetHistoryAsync(
|
|
||||||
string entityIds,
|
|
||||||
DateTimeOffset? startTime = null,
|
|
||||||
DateTimeOffset? endTime = null,
|
|
||||||
bool minimalResponse = true,
|
|
||||||
CancellationToken cancellationToken = default);
|
|
||||||
}
|
|
||||||
@@ -1,191 +0,0 @@
|
|||||||
using BoilerMonitorManager;
|
|
||||||
using BoilerMonitorManager.Interface;
|
|
||||||
using BoilerMonitorManager.Models;
|
|
||||||
using HomeAssistant.Entities.Interfaces;
|
|
||||||
using HomeAssistant.HistoryReplay.Configuration;
|
|
||||||
using HomeAssistant.HistoryReplay.HistoryData;
|
|
||||||
using HomeAssistant.HistoryReplay.Replay;
|
|
||||||
using HomeAssistant.HistoryReplay.Reporting;
|
|
||||||
using HomeAssistant.HistoryReplay.Runners;
|
|
||||||
using HomeAssistant.HistoryReplay.HomeAssistantClient;
|
|
||||||
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;
|
|
||||||
using ShowerMonitorManager.Interface;
|
|
||||||
using ShowerMonitorManager.Models;
|
|
||||||
|
|
||||||
Log.Logger = new LoggerConfiguration()
|
|
||||||
.MinimumLevel.Information()
|
|
||||||
.WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
|
|
||||||
.CreateLogger();
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
Log.Information("Starting Home Assistant History Replay");
|
|
||||||
|
|
||||||
var configuration = new ConfigurationBuilder()
|
|
||||||
.SetBasePath(Directory.GetCurrentDirectory())
|
|
||||||
.AddJsonFile("appsettings.json", optional: false)
|
|
||||||
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") ?? "Production"}.json", optional: true)
|
|
||||||
.AddEnvironmentVariables()
|
|
||||||
.Build();
|
|
||||||
|
|
||||||
var services = new ServiceCollection();
|
|
||||||
|
|
||||||
services.AddLogging(builder =>
|
|
||||||
{
|
|
||||||
builder.ClearProviders();
|
|
||||||
builder.AddSerilog(dispose: true);
|
|
||||||
});
|
|
||||||
|
|
||||||
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));
|
|
||||||
|
|
||||||
services.AddHttpClient<IHomeAssistantApiClient, HomeAssistantApiClient>();
|
|
||||||
services.AddSingleton<IHistoryDataProvider, HomeAssistantHistoryProvider>();
|
|
||||||
|
|
||||||
var replayOptions = configuration.GetSection(ReplayOptions.SectionName).Get<ReplayOptions>() ?? new ReplayOptions();
|
|
||||||
|
|
||||||
var replayTimeline = new ReplayTimeline();
|
|
||||||
var replayTimeProvider = new ReplayTimeProvider(replayOptions.StartTime);
|
|
||||||
|
|
||||||
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)
|
|
||||||
{
|
|
||||||
Log.Fatal(ex, "History replay failed");
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
await Log.CloseAndFlushAsync();
|
|
||||||
}
|
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
using HomeAssistant.Entities.Interfaces;
|
|
||||||
using HomeAssistant.Models;
|
|
||||||
using Microsoft.Extensions.Logging;
|
|
||||||
|
|
||||||
namespace HomeAssistant.HistoryReplay.Replay;
|
|
||||||
|
|
||||||
public sealed class NoOpEntityManager(ILogger<NoOpEntityManager> logger) : IEntityManager
|
|
||||||
{
|
|
||||||
public Task CreateEntitiesAsync(ICollection<EntityCreateModel> entities)
|
|
||||||
{
|
|
||||||
logger.LogDebug("[REPLAY] Would create {Count} entities", entities.Count);
|
|
||||||
return Task.CompletedTask;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Task CreateEntityAsync(EntityCreateModel createModel)
|
|
||||||
{
|
|
||||||
logger.LogDebug("[REPLAY] Would create entity: {EntityId}", createModel.EntityId);
|
|
||||||
return Task.CompletedTask;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Task SetEntityState(string entityId, string state)
|
|
||||||
{
|
|
||||||
logger.LogDebug("[REPLAY] Would set state for {EntityId}: {State}", entityId, state);
|
|
||||||
return Task.CompletedTask;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Task SetEntityAttributes(string entityId, object attributes)
|
|
||||||
{
|
|
||||||
logger.LogDebug("[REPLAY] Would set attributes for {EntityId}", entityId);
|
|
||||||
return Task.CompletedTask;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Task RemoveEntity(string entityId)
|
|
||||||
{
|
|
||||||
logger.LogDebug("[REPLAY] Would remove entity: {EntityId}", entityId);
|
|
||||||
return Task.CompletedTask;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,98 +0,0 @@
|
|||||||
using System.Reactive.Linq;
|
|
||||||
using System.Text.Json;
|
|
||||||
using HomeAssistant.HistoryReplay.HistoryData;
|
|
||||||
using HomeAssistant.HistoryReplay.Reporting;
|
|
||||||
using Microsoft.Extensions.Logging;
|
|
||||||
using NetDaemon.HassModel;
|
|
||||||
using NetDaemon.HassModel.Entities;
|
|
||||||
|
|
||||||
namespace HomeAssistant.HistoryReplay.Replay;
|
|
||||||
|
|
||||||
public sealed class ReplayHaContext : IHaContext
|
|
||||||
{
|
|
||||||
private readonly HistoryTimeline _timeline;
|
|
||||||
private readonly ReplayTimeProvider _timeProvider;
|
|
||||||
private readonly ReplayTimeline _replayTimeline;
|
|
||||||
private readonly ILogger<ReplayHaContext> _logger;
|
|
||||||
|
|
||||||
public ReplayHaContext(
|
|
||||||
HistoryTimeline timeline,
|
|
||||||
ReplayTimeProvider timeProvider,
|
|
||||||
ReplayTimeline replayTimeline,
|
|
||||||
ILogger<ReplayHaContext> logger)
|
|
||||||
{
|
|
||||||
_timeline = timeline;
|
|
||||||
_timeProvider = timeProvider;
|
|
||||||
_replayTimeline = replayTimeline;
|
|
||||||
_logger = logger;
|
|
||||||
}
|
|
||||||
|
|
||||||
public EntityState? GetState(string entityId)
|
|
||||||
{
|
|
||||||
var currentTime = _timeProvider.GetUtcNow();
|
|
||||||
var entry = _timeline.GetStateAt(entityId, currentTime);
|
|
||||||
|
|
||||||
if (entry is null)
|
|
||||||
{
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
JsonElement? attributesJson = null;
|
|
||||||
if (entry.Attributes is { Count: > 0 })
|
|
||||||
{
|
|
||||||
attributesJson = JsonSerializer.SerializeToElement(entry.Attributes);
|
|
||||||
}
|
|
||||||
|
|
||||||
return new EntityState
|
|
||||||
{
|
|
||||||
State = entry.State,
|
|
||||||
AttributesJson = attributesJson
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
public IReadOnlyList<Entity> GetAllEntities()
|
|
||||||
{
|
|
||||||
return _timeline.GetEntityIds()
|
|
||||||
.Select(id => new Entity(this, id))
|
|
||||||
.ToList();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void CallService(string domain, string service, ServiceTarget? target = null, object? data = null)
|
|
||||||
{
|
|
||||||
var currentTime = _timeProvider.GetUtcNow();
|
|
||||||
var targetDescription = target?.EntityIds is not null
|
|
||||||
? string.Join(", ", target.EntityIds)
|
|
||||||
: "no target";
|
|
||||||
|
|
||||||
_replayTimeline.AddEvent(new ReplayEvent
|
|
||||||
{
|
|
||||||
Timestamp = currentTime,
|
|
||||||
Monitor = "ServiceCall",
|
|
||||||
EventType = ReplayEventType.ServiceCall,
|
|
||||||
Message = $"Would call {domain}.{service} on {targetDescription}",
|
|
||||||
Details = data is not null ? JsonSerializer.Serialize(data) : null
|
|
||||||
});
|
|
||||||
|
|
||||||
_logger.LogDebug("[REPLAY] {Domain}.{Service} → {Target}", domain, service, targetDescription);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void SendEvent(string eventType, object? data = null)
|
|
||||||
{
|
|
||||||
_logger.LogDebug("[REPLAY] Would send event: {EventType}", eventType);
|
|
||||||
}
|
|
||||||
|
|
||||||
public IObservable<StateChange> StateAllChanges() => Observable.Empty<StateChange>();
|
|
||||||
|
|
||||||
public IObservable<Event> Events => Observable.Empty<Event>();
|
|
||||||
|
|
||||||
public Task<JsonElement?> CallServiceWithResponseAsync(
|
|
||||||
string domain, string service, ServiceTarget? target = null, object? data = null)
|
|
||||||
{
|
|
||||||
CallService(domain, service, target, data);
|
|
||||||
return Task.FromResult<JsonElement?>(null);
|
|
||||||
}
|
|
||||||
|
|
||||||
public Area? GetAreaFromEntityId(string entityId) => null;
|
|
||||||
|
|
||||||
public EntityRegistration? GetEntityRegistration(string entityId) => null;
|
|
||||||
}
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
namespace HomeAssistant.HistoryReplay.Replay;
|
|
||||||
|
|
||||||
public sealed class ReplayTimeProvider : TimeProvider
|
|
||||||
{
|
|
||||||
private readonly Lock _lock = new();
|
|
||||||
private DateTimeOffset _currentUtcTime;
|
|
||||||
private readonly TimeZoneInfo _localTimeZone;
|
|
||||||
|
|
||||||
public ReplayTimeProvider(DateTimeOffset initialTime)
|
|
||||||
{
|
|
||||||
_currentUtcTime = initialTime.ToUniversalTime();
|
|
||||||
_localTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
|
|
||||||
}
|
|
||||||
|
|
||||||
public override DateTimeOffset GetUtcNow()
|
|
||||||
{
|
|
||||||
lock (_lock)
|
|
||||||
{
|
|
||||||
return _currentUtcTime;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public override TimeZoneInfo LocalTimeZone => _localTimeZone;
|
|
||||||
|
|
||||||
public void AdvanceTo(DateTimeOffset utcTime)
|
|
||||||
{
|
|
||||||
lock (_lock)
|
|
||||||
{
|
|
||||||
_currentUtcTime = utcTime.ToUniversalTime();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void AdvanceBy(TimeSpan duration)
|
|
||||||
{
|
|
||||||
lock (_lock)
|
|
||||||
{
|
|
||||||
_currentUtcTime += duration;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,146 +0,0 @@
|
|||||||
using HomeAssistant.HistoryReplay.Configuration;
|
|
||||||
|
|
||||||
namespace HomeAssistant.HistoryReplay.Reporting;
|
|
||||||
|
|
||||||
public sealed class ConsoleReportRenderer
|
|
||||||
{
|
|
||||||
private const string Separator = "═══════════════════════════════════════════════════════════";
|
|
||||||
private const string SectionSeparator = "── {0} ──────────────────────────────────────────────";
|
|
||||||
private const string TimeFormat = "HH:mm:ss";
|
|
||||||
|
|
||||||
public void Render(ReplayTimeline timeline, ReplayOptions options)
|
|
||||||
{
|
|
||||||
Console.WriteLine();
|
|
||||||
WriteColored(Separator, ConsoleColor.DarkCyan);
|
|
||||||
WriteColored($" REPLAY: {options.StartTime:yyyy-MM-dd HH:mm} → {options.EndTime:yyyy-MM-dd HH:mm}", ConsoleColor.White);
|
|
||||||
WriteColored(Separator, ConsoleColor.DarkCyan);
|
|
||||||
Console.WriteLine();
|
|
||||||
|
|
||||||
var monitors = timeline.GetMonitors()
|
|
||||||
.Where(m => !string.Equals(m, "ServiceCall", StringComparison.OrdinalIgnoreCase))
|
|
||||||
.ToList();
|
|
||||||
|
|
||||||
foreach (var monitor in monitors)
|
|
||||||
{
|
|
||||||
RenderMonitorSection(monitor, timeline.GetEventsByMonitor(monitor));
|
|
||||||
}
|
|
||||||
|
|
||||||
RenderServiceCallSection(timeline.GetEventsByMonitor("ServiceCall"));
|
|
||||||
RenderSummary(timeline);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void RenderMonitorSection(string monitor, IReadOnlyList<ReplayEvent> events)
|
|
||||||
{
|
|
||||||
Console.WriteLine();
|
|
||||||
WriteColored(string.Format(SectionSeparator, monitor), ConsoleColor.Yellow);
|
|
||||||
|
|
||||||
if (events.Count == 0)
|
|
||||||
{
|
|
||||||
WriteColored(" No events recorded", ConsoleColor.DarkGray);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
foreach (var evt in events)
|
|
||||||
{
|
|
||||||
var color = GetEventColor(evt.EventType);
|
|
||||||
var prefix = GetEventPrefix(evt.EventType);
|
|
||||||
var timestamp = evt.Timestamp.ToLocalTime().ToString(TimeFormat);
|
|
||||||
|
|
||||||
WriteColored($" {timestamp} {prefix}{evt.Message}", color);
|
|
||||||
|
|
||||||
if (!string.IsNullOrEmpty(evt.Details))
|
|
||||||
{
|
|
||||||
WriteColored($" {evt.Details}", ConsoleColor.DarkGray);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
WriteSectionSummary(events);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void RenderServiceCallSection(IReadOnlyList<ReplayEvent> events)
|
|
||||||
{
|
|
||||||
if (events.Count == 0)
|
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
Console.WriteLine();
|
|
||||||
WriteColored(string.Format(SectionSeparator, "Service Calls"), ConsoleColor.Magenta);
|
|
||||||
|
|
||||||
foreach (var evt in events)
|
|
||||||
{
|
|
||||||
var timestamp = evt.Timestamp.ToLocalTime().ToString(TimeFormat);
|
|
||||||
WriteColored($" {timestamp} → {evt.Message}", ConsoleColor.DarkMagenta);
|
|
||||||
}
|
|
||||||
|
|
||||||
WriteColored($"\n Total: {events.Count} service call(s) would have been made", ConsoleColor.DarkGray);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void RenderSummary(ReplayTimeline timeline)
|
|
||||||
{
|
|
||||||
var allEvents = timeline.GetAllEvents();
|
|
||||||
|
|
||||||
Console.WriteLine();
|
|
||||||
WriteColored(Separator, ConsoleColor.DarkCyan);
|
|
||||||
WriteColored(" REPLAY SUMMARY", ConsoleColor.White);
|
|
||||||
WriteColored(Separator, ConsoleColor.DarkCyan);
|
|
||||||
|
|
||||||
var decisions = allEvents.Count(e => e.EventType == ReplayEventType.Decision);
|
|
||||||
var serviceCalls = allEvents.Count(e => e.EventType == ReplayEventType.ServiceCall);
|
|
||||||
var warnings = allEvents.Count(e => e.EventType == ReplayEventType.Warning);
|
|
||||||
var anomalies = allEvents.Count(e => e.EventType == ReplayEventType.Anomaly);
|
|
||||||
|
|
||||||
WriteColored($" Total events: {allEvents.Count}", ConsoleColor.Gray);
|
|
||||||
WriteColored($" Decisions: {decisions}", ConsoleColor.Cyan);
|
|
||||||
WriteColored($" Service calls: {serviceCalls}", ConsoleColor.Magenta);
|
|
||||||
WriteColored($" Warnings: {warnings}", ConsoleColor.DarkYellow);
|
|
||||||
WriteColored($" Anomalies: {anomalies}", ConsoleColor.Red);
|
|
||||||
Console.WriteLine();
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void WriteSectionSummary(IReadOnlyList<ReplayEvent> events)
|
|
||||||
{
|
|
||||||
var decisions = events.Count(e => e.EventType == ReplayEventType.Decision);
|
|
||||||
var warnings = events.Count(e => e.EventType == ReplayEventType.Warning);
|
|
||||||
var stateChanges = events.Count(e => e.EventType == ReplayEventType.StateChange);
|
|
||||||
|
|
||||||
var parts = new List<string>();
|
|
||||||
if (decisions > 0) parts.Add($"{decisions} decision(s)");
|
|
||||||
if (stateChanges > 0) parts.Add($"{stateChanges} state change(s)");
|
|
||||||
if (warnings > 0) parts.Add($"{warnings} warning(s)");
|
|
||||||
|
|
||||||
if (parts.Count > 0)
|
|
||||||
{
|
|
||||||
WriteColored($"\n Summary: {string.Join(", ", parts)}", ConsoleColor.DarkGray);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static ConsoleColor GetEventColor(ReplayEventType eventType) =>
|
|
||||||
eventType switch
|
|
||||||
{
|
|
||||||
ReplayEventType.Decision => ConsoleColor.Green,
|
|
||||||
ReplayEventType.StateChange => ConsoleColor.Cyan,
|
|
||||||
ReplayEventType.Warning => ConsoleColor.DarkYellow,
|
|
||||||
ReplayEventType.ServiceCall => ConsoleColor.Magenta,
|
|
||||||
ReplayEventType.Anomaly => ConsoleColor.Red,
|
|
||||||
_ => ConsoleColor.Gray
|
|
||||||
};
|
|
||||||
|
|
||||||
private static string GetEventPrefix(ReplayEventType eventType) =>
|
|
||||||
eventType switch
|
|
||||||
{
|
|
||||||
ReplayEventType.Decision => "→ ",
|
|
||||||
ReplayEventType.Warning => "⚠ ",
|
|
||||||
ReplayEventType.Anomaly => "⚠ ANOMALY: ",
|
|
||||||
ReplayEventType.ServiceCall => "⤷ ",
|
|
||||||
_ => ""
|
|
||||||
};
|
|
||||||
|
|
||||||
private static void WriteColored(string text, ConsoleColor color)
|
|
||||||
{
|
|
||||||
var previousColor = Console.ForegroundColor;
|
|
||||||
Console.ForegroundColor = color;
|
|
||||||
Console.WriteLine(text);
|
|
||||||
Console.ForegroundColor = previousColor;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
namespace HomeAssistant.HistoryReplay.Reporting;
|
|
||||||
|
|
||||||
public sealed class ReplayEvent
|
|
||||||
{
|
|
||||||
public required DateTimeOffset Timestamp { get; init; }
|
|
||||||
public required string Monitor { get; init; }
|
|
||||||
public required ReplayEventType EventType { get; init; }
|
|
||||||
public required string Message { get; init; }
|
|
||||||
public string? Details { get; init; }
|
|
||||||
}
|
|
||||||
|
|
||||||
public enum ReplayEventType
|
|
||||||
{
|
|
||||||
Info,
|
|
||||||
Decision,
|
|
||||||
StateChange,
|
|
||||||
Warning,
|
|
||||||
ServiceCall,
|
|
||||||
Anomaly
|
|
||||||
}
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
using System.Collections.Concurrent;
|
|
||||||
|
|
||||||
namespace HomeAssistant.HistoryReplay.Reporting;
|
|
||||||
|
|
||||||
public sealed class ReplayTimeline
|
|
||||||
{
|
|
||||||
private readonly ConcurrentBag<ReplayEvent> _events = [];
|
|
||||||
|
|
||||||
public void AddEvent(ReplayEvent replayEvent)
|
|
||||||
{
|
|
||||||
_events.Add(replayEvent);
|
|
||||||
}
|
|
||||||
|
|
||||||
public IReadOnlyList<ReplayEvent> GetEventsByMonitor(string monitor) =>
|
|
||||||
_events
|
|
||||||
.Where(e => string.Equals(e.Monitor, monitor, StringComparison.OrdinalIgnoreCase))
|
|
||||||
.OrderBy(e => e.Timestamp)
|
|
||||||
.ToList();
|
|
||||||
|
|
||||||
public IReadOnlyList<ReplayEvent> GetAllEvents() =>
|
|
||||||
_events.OrderBy(e => e.Timestamp).ToList();
|
|
||||||
|
|
||||||
public IReadOnlyList<string> GetMonitors() =>
|
|
||||||
_events.Select(e => e.Monitor).Distinct(StringComparer.OrdinalIgnoreCase).Order().ToList();
|
|
||||||
}
|
|
||||||
@@ -1,210 +0,0 @@
|
|||||||
using System.Globalization;
|
|
||||||
using BoilerMonitor.Models;
|
|
||||||
using BoilerMonitor.Models.Enums;
|
|
||||||
using BoilerMonitorManager.Interface;
|
|
||||||
using HomeAssistant.HistoryReplay.Configuration;
|
|
||||||
using HomeAssistant.HistoryReplay.HistoryData;
|
|
||||||
using HomeAssistant.HistoryReplay.Replay;
|
|
||||||
using HomeAssistant.HistoryReplay.Reporting;
|
|
||||||
using Microsoft.Extensions.Logging;
|
|
||||||
using Microsoft.Extensions.Options;
|
|
||||||
using BoilerMonitorManager.Models;
|
|
||||||
|
|
||||||
namespace HomeAssistant.HistoryReplay.Runners;
|
|
||||||
|
|
||||||
public sealed class BoilerReplayRunner : IMonitorReplayRunner
|
|
||||||
{
|
|
||||||
private readonly HistoryTimeline _timeline;
|
|
||||||
private readonly ReplayTimeProvider _timeProvider;
|
|
||||||
private readonly ReplayTimeline _replayTimeline;
|
|
||||||
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;
|
|
||||||
|
|
||||||
public string MonitorName => "Boiler";
|
|
||||||
|
|
||||||
public BoilerReplayRunner(
|
|
||||||
HistoryTimeline timeline,
|
|
||||||
ReplayTimeProvider timeProvider,
|
|
||||||
ReplayTimeline replayTimeline,
|
|
||||||
IBoilerControlService boilerControlService,
|
|
||||||
IBoilerRunTimeTracker tracker,
|
|
||||||
IWaterReadyService waterReadyService,
|
|
||||||
ILogger<BoilerReplayRunner> logger,
|
|
||||||
IOptions<ReplayOptions> replayOptions,
|
|
||||||
IOptions<BoilerMonitorOptions> boilerOptions)
|
|
||||||
{
|
|
||||||
_timeline = timeline;
|
|
||||||
_timeProvider = timeProvider;
|
|
||||||
_replayTimeline = replayTimeline;
|
|
||||||
_boilerControlService = boilerControlService;
|
|
||||||
_tracker = tracker;
|
|
||||||
_waterReadyService = waterReadyService;
|
|
||||||
_logger = logger;
|
|
||||||
_replayOptions = replayOptions.Value;
|
|
||||||
_boilerOptions = boilerOptions.Value;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Task RunAsync(CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
_logger.LogInformation("Starting Boiler replay");
|
|
||||||
|
|
||||||
var currentTime = _replayOptions.StartTime;
|
|
||||||
var pollInterval = TimeSpan.FromSeconds(BoilerMonitorConsts.DefaultPollIntervalSeconds);
|
|
||||||
var heatingThreshold = BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts;
|
|
||||||
BoilerAction? lastAction = null;
|
|
||||||
var lastWaterReady = false;
|
|
||||||
|
|
||||||
var boilerPowerEntityId = 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;
|
|
||||||
}
|
|
||||||
|
|
||||||
while (currentTime <= _replayOptions.EndTime && !cancellationToken.IsCancellationRequested)
|
|
||||||
{
|
|
||||||
_timeProvider.AdvanceTo(currentTime);
|
|
||||||
|
|
||||||
var powerEntry = _timeline.GetStateAt(boilerPowerEntityId, currentTime);
|
|
||||||
var switchEntry = _timeline.GetStateAt(boilerSwitchEntityId, currentTime);
|
|
||||||
var cheapEntry = _timeline.GetStateAt("sensor.nordpool_cheapest_intervals", currentTime);
|
|
||||||
var skipPriceCapEntry = _timeline.GetStateAt(BoilerMonitorConsts.SkipPriceCapEntityId, currentTime);
|
|
||||||
var budgetOverrideEntry = _timeline.GetStateAt(BoilerMonitorConsts.BudgetOverrideEntityId, currentTime);
|
|
||||||
var dailyHoursEntry = _timeline.GetStateAt(BoilerMonitorConsts.BoilerDailyHoursEntityId, currentTime);
|
|
||||||
|
|
||||||
var boilerPowerWatts = ParseDouble(powerEntry?.State);
|
|
||||||
var boilerSwitchState = switchEntry?.State;
|
|
||||||
var isHeating = boilerPowerWatts.HasValue && boilerPowerWatts.Value >= heatingThreshold;
|
|
||||||
|
|
||||||
_tracker.RecordPollResult(isHeating, pollInterval);
|
|
||||||
|
|
||||||
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 dailyHours = ParseDouble(dailyHoursEntry?.State) ?? 1.0;
|
|
||||||
|
|
||||||
var waterReady = _waterReadyService.IsWaterReady(boilerSwitchState, boilerPowerWatts, heatingThreshold);
|
|
||||||
|
|
||||||
if (!lastWaterReady && waterReady)
|
|
||||||
{
|
|
||||||
_replayTimeline.AddEvent(new ReplayEvent
|
|
||||||
{
|
|
||||||
Timestamp = currentTime,
|
|
||||||
Monitor = MonitorName,
|
|
||||||
EventType = ReplayEventType.StateChange,
|
|
||||||
Message = $"Water ready detected (power: {boilerPowerWatts:F1}W, threshold: {heatingThreshold}W)"
|
|
||||||
});
|
|
||||||
}
|
|
||||||
lastWaterReady = waterReady;
|
|
||||||
|
|
||||||
var snapshot = _tracker.GetSnapshot();
|
|
||||||
var budgetTimeSpan = TimeSpan.FromHours(dailyHours);
|
|
||||||
var budgetExhausted = snapshot.AccumulatedRunTime >= budgetTimeSpan;
|
|
||||||
var budgetPercentage = budgetTimeSpan.TotalSeconds > 0
|
|
||||||
? (snapshot.AccumulatedRunTime.TotalSeconds / budgetTimeSpan.TotalSeconds) * 100.0
|
|
||||||
: 0.0;
|
|
||||||
|
|
||||||
var effectiveIsNowCheap = isNowCheap || skipPriceCap;
|
|
||||||
var action = _boilerControlService.DetermineAction(
|
|
||||||
effectiveIsNowCheap, waterReady, boilerSwitchState, budgetExhausted, budgetOverride);
|
|
||||||
|
|
||||||
if (action != BoilerAction.NoChange && action != lastAction)
|
|
||||||
{
|
|
||||||
var actionMessage = action switch
|
|
||||||
{
|
|
||||||
BoilerAction.TurnOn => $"TURN ON (cheap: {effectiveIsNowCheap}, water ready: {waterReady}, budget: {budgetPercentage:F0}%)",
|
|
||||||
BoilerAction.TurnOff => $"TURN OFF (cheap: {effectiveIsNowCheap}, water ready: {waterReady}, budget: {budgetPercentage:F0}%)",
|
|
||||||
_ => action.ToString()
|
|
||||||
};
|
|
||||||
|
|
||||||
_replayTimeline.AddEvent(new ReplayEvent
|
|
||||||
{
|
|
||||||
Timestamp = currentTime,
|
|
||||||
Monitor = MonitorName,
|
|
||||||
EventType = ReplayEventType.Decision,
|
|
||||||
Message = actionMessage,
|
|
||||||
Details = $"Power: {boilerPowerWatts:F1}W, Runtime: {snapshot.AccumulatedRunTime:hh\\:mm\\:ss}, Sessions: {snapshot.SessionCount}"
|
|
||||||
});
|
|
||||||
|
|
||||||
if (action == BoilerAction.TurnOn)
|
|
||||||
{
|
|
||||||
_waterReadyService.NotifyTurnedOn();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
lastAction = action;
|
|
||||||
currentTime = currentTime.Add(pollInterval);
|
|
||||||
}
|
|
||||||
|
|
||||||
var finalSnapshot = _tracker.GetSnapshot();
|
|
||||||
_replayTimeline.AddEvent(new ReplayEvent
|
|
||||||
{
|
|
||||||
Timestamp = _replayOptions.EndTime,
|
|
||||||
Monitor = MonitorName,
|
|
||||||
EventType = ReplayEventType.Info,
|
|
||||||
Message = $"Final: {finalSnapshot.AccumulatedRunTime:hh\\:mm\\:ss} total runtime, {finalSnapshot.SessionCount} session(s)"
|
|
||||||
});
|
|
||||||
|
|
||||||
_logger.LogInformation("Boiler replay complete");
|
|
||||||
return Task.CompletedTask;
|
|
||||||
}
|
|
||||||
|
|
||||||
private 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)
|
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!entry.Attributes.TryGetValue(attributeName, out var value))
|
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return value switch
|
|
||||||
{
|
|
||||||
bool b => b,
|
|
||||||
string s => bool.TryParse(s, out var parsed) && parsed,
|
|
||||||
double d => d != 0,
|
|
||||||
_ => false
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
private static double? ParseDouble(string? value)
|
|
||||||
{
|
|
||||||
if (value is null or "unavailable" or "unknown")
|
|
||||||
{
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return double.TryParse(value, CultureInfo.InvariantCulture, out var result) ? result : null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
namespace HomeAssistant.HistoryReplay.Runners;
|
|
||||||
|
|
||||||
public interface IMonitorReplayRunner
|
|
||||||
{
|
|
||||||
string MonitorName { get; }
|
|
||||||
Task RunAsync(CancellationToken cancellationToken = default);
|
|
||||||
}
|
|
||||||
@@ -1,175 +0,0 @@
|
|||||||
using HomeAssistant.HistoryReplay.Configuration;
|
|
||||||
using HomeAssistant.HistoryReplay.HistoryData;
|
|
||||||
using HomeAssistant.HistoryReplay.Replay;
|
|
||||||
using HomeAssistant.HistoryReplay.Reporting;
|
|
||||||
using LightMonitor.Models;
|
|
||||||
using Microsoft.Extensions.Logging;
|
|
||||||
using Microsoft.Extensions.Options;
|
|
||||||
using LightMonitorManager.Models;
|
|
||||||
|
|
||||||
namespace HomeAssistant.HistoryReplay.Runners;
|
|
||||||
|
|
||||||
public sealed class LightReplayRunner : IMonitorReplayRunner
|
|
||||||
{
|
|
||||||
private readonly HistoryTimeline _timeline;
|
|
||||||
private readonly ReplayTimeProvider _timeProvider;
|
|
||||||
private readonly ReplayTimeline _replayTimeline;
|
|
||||||
private readonly ILogger<LightReplayRunner> _logger;
|
|
||||||
private readonly ReplayOptions _replayOptions;
|
|
||||||
private readonly LightMonitorOptions _lightOptions;
|
|
||||||
|
|
||||||
public string MonitorName => "Light";
|
|
||||||
|
|
||||||
public LightReplayRunner(
|
|
||||||
HistoryTimeline timeline,
|
|
||||||
ReplayTimeProvider timeProvider,
|
|
||||||
ReplayTimeline replayTimeline,
|
|
||||||
ILogger<LightReplayRunner> logger,
|
|
||||||
IOptions<ReplayOptions> replayOptions,
|
|
||||||
IOptions<LightMonitorOptions> lightOptions)
|
|
||||||
{
|
|
||||||
_timeline = timeline;
|
|
||||||
_timeProvider = timeProvider;
|
|
||||||
_replayTimeline = replayTimeline;
|
|
||||||
_logger = logger;
|
|
||||||
_replayOptions = replayOptions.Value;
|
|
||||||
_lightOptions = lightOptions.Value;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Task RunAsync(CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
_logger.LogInformation("Starting Light replay");
|
|
||||||
|
|
||||||
ReplaySunEvents(cancellationToken);
|
|
||||||
ReplayPersonArrivals(cancellationToken);
|
|
||||||
|
|
||||||
_logger.LogInformation("Light replay complete");
|
|
||||||
return Task.CompletedTask;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void ReplaySunEvents(CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
var sunHistory = _timeline.GetEntityHistory(_lightOptions.SunEntityId);
|
|
||||||
string? previousSunState = null;
|
|
||||||
|
|
||||||
foreach (var entry in sunHistory)
|
|
||||||
{
|
|
||||||
if (cancellationToken.IsCancellationRequested) break;
|
|
||||||
|
|
||||||
if (entry.LastChanged < _replayOptions.StartTime || entry.LastChanged > _replayOptions.EndTime)
|
|
||||||
{
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (string.Equals(entry.State, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase) &&
|
|
||||||
!string.Equals(previousSunState, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase))
|
|
||||||
{
|
|
||||||
_timeProvider.AdvanceTo(entry.LastChanged);
|
|
||||||
|
|
||||||
var anyoneHome = IsAnyoneHome(entry.LastChanged);
|
|
||||||
var lightState = _timeline.GetStateAt(_lightOptions.LightEntityId, entry.LastChanged)?.State;
|
|
||||||
var lightAlreadyOn = string.Equals(lightState, LightMonitorConsts.LightOnState, StringComparison.OrdinalIgnoreCase);
|
|
||||||
|
|
||||||
if (anyoneHome && !lightAlreadyOn)
|
|
||||||
{
|
|
||||||
_replayTimeline.AddEvent(new ReplayEvent
|
|
||||||
{
|
|
||||||
Timestamp = entry.LastChanged,
|
|
||||||
Monitor = MonitorName,
|
|
||||||
EventType = ReplayEventType.Decision,
|
|
||||||
Message = "TURN ON light (sun below horizon + someone home)"
|
|
||||||
});
|
|
||||||
}
|
|
||||||
else if (!anyoneHome)
|
|
||||||
{
|
|
||||||
_replayTimeline.AddEvent(new ReplayEvent
|
|
||||||
{
|
|
||||||
Timestamp = entry.LastChanged,
|
|
||||||
Monitor = MonitorName,
|
|
||||||
EventType = ReplayEventType.Info,
|
|
||||||
Message = "Sun below horizon but nobody home — light stays off"
|
|
||||||
});
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
_replayTimeline.AddEvent(new ReplayEvent
|
|
||||||
{
|
|
||||||
Timestamp = entry.LastChanged,
|
|
||||||
Monitor = MonitorName,
|
|
||||||
EventType = ReplayEventType.Info,
|
|
||||||
Message = "Sun below horizon but light already on"
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
previousSunState = entry.State;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void ReplayPersonArrivals(CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
foreach (var personEntityId in _lightOptions.PersonEntityIds)
|
|
||||||
{
|
|
||||||
var personHistory = _timeline.GetEntityHistory(personEntityId);
|
|
||||||
string? previousState = null;
|
|
||||||
|
|
||||||
foreach (var entry in personHistory)
|
|
||||||
{
|
|
||||||
if (cancellationToken.IsCancellationRequested) break;
|
|
||||||
|
|
||||||
if (entry.LastChanged < _replayOptions.StartTime || entry.LastChanged > _replayOptions.EndTime)
|
|
||||||
{
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (string.Equals(entry.State, LightMonitorConsts.PersonHomeState, StringComparison.OrdinalIgnoreCase) &&
|
|
||||||
!string.Equals(previousState, LightMonitorConsts.PersonHomeState, StringComparison.OrdinalIgnoreCase))
|
|
||||||
{
|
|
||||||
_timeProvider.AdvanceTo(entry.LastChanged);
|
|
||||||
|
|
||||||
var sunEntry = _timeline.GetStateAt(_lightOptions.SunEntityId, entry.LastChanged);
|
|
||||||
var isDark = string.Equals(sunEntry?.State, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase);
|
|
||||||
var lightState = _timeline.GetStateAt(_lightOptions.LightEntityId, entry.LastChanged)?.State;
|
|
||||||
var lightAlreadyOn = string.Equals(lightState, LightMonitorConsts.LightOnState, StringComparison.OrdinalIgnoreCase);
|
|
||||||
|
|
||||||
if (isDark && !lightAlreadyOn)
|
|
||||||
{
|
|
||||||
_replayTimeline.AddEvent(new ReplayEvent
|
|
||||||
{
|
|
||||||
Timestamp = entry.LastChanged,
|
|
||||||
Monitor = MonitorName,
|
|
||||||
EventType = ReplayEventType.Decision,
|
|
||||||
Message = $"TURN ON light ({personEntityId} arrived home + dark outside)"
|
|
||||||
});
|
|
||||||
}
|
|
||||||
else if (isDark)
|
|
||||||
{
|
|
||||||
_replayTimeline.AddEvent(new ReplayEvent
|
|
||||||
{
|
|
||||||
Timestamp = entry.LastChanged,
|
|
||||||
Monitor = MonitorName,
|
|
||||||
EventType = ReplayEventType.Info,
|
|
||||||
Message = $"{personEntityId} arrived home (dark) but light already on"
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
previousState = entry.State;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private bool IsAnyoneHome(DateTimeOffset timestamp)
|
|
||||||
{
|
|
||||||
foreach (var personEntityId in _lightOptions.PersonEntityIds)
|
|
||||||
{
|
|
||||||
var entry = _timeline.GetStateAt(personEntityId, timestamp);
|
|
||||||
if (string.Equals(entry?.State, LightMonitorConsts.PersonHomeState, StringComparison.OrdinalIgnoreCase))
|
|
||||||
{
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,171 +0,0 @@
|
|||||||
using System.Globalization;
|
|
||||||
using BoilerMonitor.Models;
|
|
||||||
using HomeAssistant.HistoryReplay.Configuration;
|
|
||||||
using HomeAssistant.HistoryReplay.HistoryData;
|
|
||||||
using HomeAssistant.HistoryReplay.Replay;
|
|
||||||
using HomeAssistant.HistoryReplay.Reporting;
|
|
||||||
using Microsoft.Extensions.Logging;
|
|
||||||
using Microsoft.Extensions.Options;
|
|
||||||
using NordPool.Models;
|
|
||||||
using NordPoolManager.Interface;
|
|
||||||
|
|
||||||
namespace HomeAssistant.HistoryReplay.Runners;
|
|
||||||
|
|
||||||
public sealed class NordPoolReplayRunner : IMonitorReplayRunner
|
|
||||||
{
|
|
||||||
private readonly HistoryTimeline _timeline;
|
|
||||||
private readonly ReplayTimeProvider _timeProvider;
|
|
||||||
private readonly ReplayTimeline _replayTimeline;
|
|
||||||
private readonly ICheapestIntervalsFinder _cheapestIntervalsFinder;
|
|
||||||
private readonly ILogger<NordPoolReplayRunner> _logger;
|
|
||||||
private readonly ReplayOptions _options;
|
|
||||||
|
|
||||||
public string MonitorName => "NordPool";
|
|
||||||
|
|
||||||
public NordPoolReplayRunner(
|
|
||||||
HistoryTimeline timeline,
|
|
||||||
ReplayTimeProvider timeProvider,
|
|
||||||
ReplayTimeline replayTimeline,
|
|
||||||
ICheapestIntervalsFinder cheapestIntervalsFinder,
|
|
||||||
ILogger<NordPoolReplayRunner> logger,
|
|
||||||
IOptions<ReplayOptions> options)
|
|
||||||
{
|
|
||||||
_timeline = timeline;
|
|
||||||
_timeProvider = timeProvider;
|
|
||||||
_replayTimeline = replayTimeline;
|
|
||||||
_cheapestIntervalsFinder = cheapestIntervalsFinder;
|
|
||||||
_logger = logger;
|
|
||||||
_options = options.Value;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Task RunAsync(CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
_logger.LogInformation("Starting NordPool replay");
|
|
||||||
|
|
||||||
var currentTime = _options.StartTime;
|
|
||||||
var interval = TimeSpan.FromMinutes(NordPoolConsts.MinutesPerInterval);
|
|
||||||
double? lastReportedPrice = null;
|
|
||||||
|
|
||||||
while (currentTime <= _options.EndTime && !cancellationToken.IsCancellationRequested)
|
|
||||||
{
|
|
||||||
_timeProvider.AdvanceTo(currentTime);
|
|
||||||
|
|
||||||
var priceEntry = _timeline.GetStateAt(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)
|
|
||||||
{
|
|
||||||
_replayTimeline.AddEvent(new ReplayEvent
|
|
||||||
{
|
|
||||||
Timestamp = currentTime,
|
|
||||||
Monitor = MonitorName,
|
|
||||||
EventType = ReplayEventType.Info,
|
|
||||||
Message = $"Price: {currentPrice:F2} ct/kWh"
|
|
||||||
});
|
|
||||||
lastReportedPrice = currentPrice;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var boilerConfig = ReadBoilerConfig(currentTime);
|
|
||||||
if (boilerConfig is not null)
|
|
||||||
{
|
|
||||||
var prices = BuildNordPoolPriceFromHistory(currentTime);
|
|
||||||
if (prices.Prices is { Count: > 0 })
|
|
||||||
{
|
|
||||||
var effectivePriceCap = boilerConfig.SkipPriceCap ? double.MaxValue : boilerConfig.PriceCap;
|
|
||||||
var effectiveIntervalCount = boilerConfig.SkipPriceCap
|
|
||||||
? NordPoolConsts.MaxDailyIntervals
|
|
||||||
: boilerConfig.IntervalCount;
|
|
||||||
|
|
||||||
var cheapest = _cheapestIntervalsFinder.FindCheapestIntervals(
|
|
||||||
prices, effectiveIntervalCount, effectivePriceCap, boilerConfig.Deadline);
|
|
||||||
|
|
||||||
var isNowCheap = _cheapestIntervalsFinder.IsCurrentIntervalCheap(
|
|
||||||
cheapest, currentTime.LocalDateTime);
|
|
||||||
|
|
||||||
if (isNowCheap)
|
|
||||||
{
|
|
||||||
var currentInterval = cheapest.FirstOrDefault(i =>
|
|
||||||
currentTime.LocalDateTime >= i.Start && currentTime.LocalDateTime < i.End);
|
|
||||||
|
|
||||||
_replayTimeline.AddEvent(new ReplayEvent
|
|
||||||
{
|
|
||||||
Timestamp = currentTime,
|
|
||||||
Monitor = MonitorName,
|
|
||||||
EventType = ReplayEventType.Decision,
|
|
||||||
Message = $"CHEAP interval active (rank #{currentInterval?.Rank}, price: {currentInterval?.Price:F2} ct/kWh)",
|
|
||||||
Details = $"Total cheap intervals: {cheapest.Count}"
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
currentTime = currentTime.Add(interval);
|
|
||||||
}
|
|
||||||
|
|
||||||
_logger.LogInformation("NordPool replay complete");
|
|
||||||
return Task.CompletedTask;
|
|
||||||
}
|
|
||||||
|
|
||||||
private BoilerConfig? ReadBoilerConfig(DateTimeOffset timestamp)
|
|
||||||
{
|
|
||||||
var dailyHoursEntry = _timeline.GetStateAt(BoilerMonitorConsts.BoilerDailyHoursEntityId, timestamp);
|
|
||||||
var priceCapEntry = _timeline.GetStateAt(BoilerMonitorConsts.BoilerPriceCapEntityId, timestamp);
|
|
||||||
var readyByEntry = _timeline.GetStateAt(BoilerMonitorConsts.BoilerReadyByEntityId, timestamp);
|
|
||||||
var skipPriceCapEntry = _timeline.GetStateAt(BoilerMonitorConsts.SkipPriceCapEntityId, timestamp);
|
|
||||||
|
|
||||||
if (dailyHoursEntry?.State is null || priceCapEntry?.State is null || readyByEntry?.State is null)
|
|
||||||
{
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!double.TryParse(dailyHoursEntry.State, CultureInfo.InvariantCulture, out var dailyHours) ||
|
|
||||||
!double.TryParse(priceCapEntry.State, CultureInfo.InvariantCulture, out var priceCap))
|
|
||||||
{
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
var intervalCount = (int)(dailyHours * NordPoolConsts.IntervalsPerHour);
|
|
||||||
|
|
||||||
if (!TimeSpan.TryParse(readyByEntry.State, CultureInfo.InvariantCulture, out var readyByTime))
|
|
||||||
{
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
var deadline = timestamp.LocalDateTime.Date.Add(readyByTime);
|
|
||||||
if (deadline < timestamp.LocalDateTime)
|
|
||||||
{
|
|
||||||
deadline = deadline.AddDays(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
var skipPriceCap = string.Equals(skipPriceCapEntry?.State, "on", StringComparison.OrdinalIgnoreCase);
|
|
||||||
|
|
||||||
return new BoilerConfig
|
|
||||||
{
|
|
||||||
IntervalCount = intervalCount,
|
|
||||||
PriceCap = priceCap,
|
|
||||||
Deadline = deadline,
|
|
||||||
SkipPriceCap = skipPriceCap
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
private NordPoolPrice BuildNordPoolPriceFromHistory(DateTimeOffset timestamp)
|
|
||||||
{
|
|
||||||
var nordPoolSensorEntries = _timeline.GetEntityHistory("sensor.nordpool_kwh_lt_eur_3_10_0");
|
|
||||||
var todayDate = timestamp.LocalDateTime.Date;
|
|
||||||
|
|
||||||
var todayPrices = nordPoolSensorEntries
|
|
||||||
.Where(e => e.LastChanged.LocalDateTime.Date == todayDate)
|
|
||||||
.Where(e => e.State is not null && double.TryParse(e.State, CultureInfo.InvariantCulture, out _))
|
|
||||||
.Select(e => new NordPoolDayPrice
|
|
||||||
{
|
|
||||||
Start = e.LastChanged.LocalDateTime,
|
|
||||||
End = e.LastChanged.LocalDateTime.AddMinutes(NordPoolConsts.MinutesPerInterval),
|
|
||||||
Price = double.Parse(e.State!, CultureInfo.InvariantCulture)
|
|
||||||
})
|
|
||||||
.ToList();
|
|
||||||
|
|
||||||
return new NordPoolPrice { Prices = todayPrices };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,158 +0,0 @@
|
|||||||
using System.Globalization;
|
|
||||||
using HomeAssistant.HistoryReplay.Configuration;
|
|
||||||
using HomeAssistant.HistoryReplay.HistoryData;
|
|
||||||
using HomeAssistant.HistoryReplay.Replay;
|
|
||||||
using HomeAssistant.HistoryReplay.Reporting;
|
|
||||||
using Microsoft.Extensions.Logging;
|
|
||||||
using Microsoft.Extensions.Options;
|
|
||||||
using NordPool.Models;
|
|
||||||
using PowerMonitorManager.Interface;
|
|
||||||
using PowerMonitorManager.Models;
|
|
||||||
using PowerMonitorManager.Models.Consts;
|
|
||||||
|
|
||||||
namespace HomeAssistant.HistoryReplay.Runners;
|
|
||||||
|
|
||||||
public sealed class PowerReplayRunner : IMonitorReplayRunner
|
|
||||||
{
|
|
||||||
private readonly HistoryTimeline _timeline;
|
|
||||||
private readonly ReplayTimeProvider _timeProvider;
|
|
||||||
private readonly ReplayTimeline _replayTimeline;
|
|
||||||
private readonly IOtherPowerCalculationService _calculationService;
|
|
||||||
private readonly IPowerCostCalculationService _costService;
|
|
||||||
private readonly ILogger<PowerReplayRunner> _logger;
|
|
||||||
private readonly ReplayOptions _replayOptions;
|
|
||||||
private readonly PowerMonitorOptions _powerOptions;
|
|
||||||
|
|
||||||
public string MonitorName => "Power";
|
|
||||||
|
|
||||||
public PowerReplayRunner(
|
|
||||||
HistoryTimeline timeline,
|
|
||||||
ReplayTimeProvider timeProvider,
|
|
||||||
ReplayTimeline replayTimeline,
|
|
||||||
IOtherPowerCalculationService calculationService,
|
|
||||||
IPowerCostCalculationService costService,
|
|
||||||
ILogger<PowerReplayRunner> logger,
|
|
||||||
IOptions<ReplayOptions> replayOptions,
|
|
||||||
IOptions<PowerMonitorOptions> powerOptions)
|
|
||||||
{
|
|
||||||
_timeline = timeline;
|
|
||||||
_timeProvider = timeProvider;
|
|
||||||
_replayTimeline = replayTimeline;
|
|
||||||
_calculationService = calculationService;
|
|
||||||
_costService = costService;
|
|
||||||
_logger = logger;
|
|
||||||
_replayOptions = replayOptions.Value;
|
|
||||||
_powerOptions = powerOptions.Value;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Task RunAsync(CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
_logger.LogInformation("Starting Power replay");
|
|
||||||
|
|
||||||
var currentTime = _replayOptions.StartTime;
|
|
||||||
var pollInterval = TimeSpan.FromSeconds(_powerOptions.PollIntervalSeconds);
|
|
||||||
DateTime? anomalyStartTime = null;
|
|
||||||
|
|
||||||
while (currentTime <= _replayOptions.EndTime && !cancellationToken.IsCancellationRequested)
|
|
||||||
{
|
|
||||||
_timeProvider.AdvanceTo(currentTime);
|
|
||||||
|
|
||||||
var mainMeterEntry = _timeline.GetStateAt(_powerOptions.MainMeterEntityId, currentTime);
|
|
||||||
var totalPower = ParseDouble(mainMeterEntry?.State);
|
|
||||||
|
|
||||||
if (!totalPower.HasValue)
|
|
||||||
{
|
|
||||||
currentTime = currentTime.Add(pollInterval);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
var deviceReadings = DiscoverAndReadDevicePower(currentTime);
|
|
||||||
var calculation = _calculationService.Calculate(totalPower.Value, deviceReadings);
|
|
||||||
|
|
||||||
var nordPoolPriceEntry = _timeline.GetStateAt(NordPoolConsts.CurrentPriceEntityId, currentTime);
|
|
||||||
var nordPoolPrice = ParseDouble(nordPoolPriceEntry?.State) ?? 0;
|
|
||||||
|
|
||||||
_costService.RecordCosts(calculation, nordPoolPrice, _powerOptions.PollIntervalSeconds, currentTime.LocalDateTime);
|
|
||||||
|
|
||||||
var isAnomaly = calculation.SmoothedOtherPowerWatts > _powerOptions.AnomalyThresholdWatts;
|
|
||||||
if (isAnomaly && anomalyStartTime is null)
|
|
||||||
{
|
|
||||||
anomalyStartTime = currentTime.LocalDateTime;
|
|
||||||
|
|
||||||
_replayTimeline.AddEvent(new ReplayEvent
|
|
||||||
{
|
|
||||||
Timestamp = currentTime,
|
|
||||||
Monitor = MonitorName,
|
|
||||||
EventType = ReplayEventType.Anomaly,
|
|
||||||
Message = $"Other power {calculation.SmoothedOtherPowerWatts:F0}W exceeds threshold {_powerOptions.AnomalyThresholdWatts}W",
|
|
||||||
Details = $"Total: {calculation.TotalPowerWatts:F0}W, Known: {calculation.KnownDevicesSumWatts:F0}W"
|
|
||||||
});
|
|
||||||
}
|
|
||||||
else if (!isAnomaly && anomalyStartTime is not null)
|
|
||||||
{
|
|
||||||
var duration = currentTime.LocalDateTime - anomalyStartTime.Value;
|
|
||||||
_replayTimeline.AddEvent(new ReplayEvent
|
|
||||||
{
|
|
||||||
Timestamp = currentTime,
|
|
||||||
Monitor = MonitorName,
|
|
||||||
EventType = ReplayEventType.Info,
|
|
||||||
Message = $"Anomaly resolved after {duration:mm\\:ss}"
|
|
||||||
});
|
|
||||||
anomalyStartTime = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
currentTime = currentTime.Add(pollInterval);
|
|
||||||
}
|
|
||||||
|
|
||||||
var totalCost = _costService.GetTotalCostSnapshot();
|
|
||||||
_replayTimeline.AddEvent(new ReplayEvent
|
|
||||||
{
|
|
||||||
Timestamp = _replayOptions.EndTime,
|
|
||||||
Monitor = MonitorName,
|
|
||||||
EventType = ReplayEventType.Info,
|
|
||||||
Message = $"Final: Total daily cost {totalCost.CostDaily:F4} EUR"
|
|
||||||
});
|
|
||||||
|
|
||||||
_logger.LogInformation("Power replay complete");
|
|
||||||
return Task.CompletedTask;
|
|
||||||
}
|
|
||||||
|
|
||||||
private IReadOnlyDictionary<string, double> DiscoverAndReadDevicePower(DateTimeOffset timestamp)
|
|
||||||
{
|
|
||||||
var readings = new Dictionary<string, double>();
|
|
||||||
|
|
||||||
var allEntities = _timeline.GetEntityIds();
|
|
||||||
foreach (var entityId in allEntities)
|
|
||||||
{
|
|
||||||
if (!entityId.StartsWith("sensor.", StringComparison.OrdinalIgnoreCase) ||
|
|
||||||
!entityId.EndsWith("_power", StringComparison.OrdinalIgnoreCase))
|
|
||||||
{
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (string.Equals(entityId, _powerOptions.MainMeterEntityId, StringComparison.OrdinalIgnoreCase))
|
|
||||||
{
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
var entry = _timeline.GetStateAt(entityId, timestamp);
|
|
||||||
var value = ParseDouble(entry?.State);
|
|
||||||
if (value.HasValue)
|
|
||||||
{
|
|
||||||
readings[entityId] = value.Value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return readings;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static double? ParseDouble(string? value)
|
|
||||||
{
|
|
||||||
if (value is null or "unavailable" or "unknown")
|
|
||||||
{
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return double.TryParse(value, CultureInfo.InvariantCulture, out var result) ? result : null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,126 +0,0 @@
|
|||||||
using System.Globalization;
|
|
||||||
using HomeAssistant.HistoryReplay.Configuration;
|
|
||||||
using HomeAssistant.HistoryReplay.HistoryData;
|
|
||||||
using HomeAssistant.HistoryReplay.Replay;
|
|
||||||
using HomeAssistant.HistoryReplay.Reporting;
|
|
||||||
using Microsoft.Extensions.Logging;
|
|
||||||
using Microsoft.Extensions.Options;
|
|
||||||
using ShowerMonitor.Models.Enums;
|
|
||||||
using ShowerMonitorManager.Interface;
|
|
||||||
using ShowerMonitorManager.Models;
|
|
||||||
|
|
||||||
namespace HomeAssistant.HistoryReplay.Runners;
|
|
||||||
|
|
||||||
public sealed class ShowerReplayRunner : IMonitorReplayRunner
|
|
||||||
{
|
|
||||||
private readonly HistoryTimeline _timeline;
|
|
||||||
private readonly ReplayTimeProvider _timeProvider;
|
|
||||||
private readonly ReplayTimeline _replayTimeline;
|
|
||||||
private readonly IShowerDetectionService _detectionService;
|
|
||||||
private readonly IExhaustFanControlService _fanControlService;
|
|
||||||
private readonly ILogger<ShowerReplayRunner> _logger;
|
|
||||||
private readonly ReplayOptions _replayOptions;
|
|
||||||
private readonly ShowerMonitorOptions _showerOptions;
|
|
||||||
|
|
||||||
public string MonitorName => "Shower";
|
|
||||||
|
|
||||||
public ShowerReplayRunner(
|
|
||||||
HistoryTimeline timeline,
|
|
||||||
ReplayTimeProvider timeProvider,
|
|
||||||
ReplayTimeline replayTimeline,
|
|
||||||
IShowerDetectionService detectionService,
|
|
||||||
IExhaustFanControlService fanControlService,
|
|
||||||
ILogger<ShowerReplayRunner> logger,
|
|
||||||
IOptions<ReplayOptions> replayOptions,
|
|
||||||
IOptions<ShowerMonitorOptions> showerOptions)
|
|
||||||
{
|
|
||||||
_timeline = timeline;
|
|
||||||
_timeProvider = timeProvider;
|
|
||||||
_replayTimeline = replayTimeline;
|
|
||||||
_detectionService = detectionService;
|
|
||||||
_fanControlService = fanControlService;
|
|
||||||
_logger = logger;
|
|
||||||
_replayOptions = replayOptions.Value;
|
|
||||||
_showerOptions = showerOptions.Value;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Task RunAsync(CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
_logger.LogInformation("Starting Shower replay");
|
|
||||||
|
|
||||||
var currentTime = _replayOptions.StartTime;
|
|
||||||
var pollInterval = TimeSpan.FromSeconds(_showerOptions.PollIntervalSeconds);
|
|
||||||
var previousState = ShowerState.Idle;
|
|
||||||
|
|
||||||
while (currentTime <= _replayOptions.EndTime && !cancellationToken.IsCancellationRequested)
|
|
||||||
{
|
|
||||||
_timeProvider.AdvanceTo(currentTime);
|
|
||||||
|
|
||||||
var bathroomEntry = _timeline.GetStateAt(_showerOptions.BathroomHumidityEntityId, currentTime);
|
|
||||||
var homeEntry = _timeline.GetStateAt(_showerOptions.MainHomeHumidityEntityId, currentTime);
|
|
||||||
|
|
||||||
var bathroomHumidity = ParseDouble(bathroomEntry?.State);
|
|
||||||
var homeHumidity = ParseDouble(homeEntry?.State);
|
|
||||||
|
|
||||||
if (bathroomHumidity.HasValue && homeHumidity.HasValue)
|
|
||||||
{
|
|
||||||
var state = _detectionService.Evaluate(bathroomHumidity.Value, homeHumidity.Value, currentTime);
|
|
||||||
var differential = bathroomHumidity.Value - homeHumidity.Value;
|
|
||||||
|
|
||||||
_fanControlService.Evaluate(state, currentTime);
|
|
||||||
|
|
||||||
if (state != previousState)
|
|
||||||
{
|
|
||||||
var eventType = state switch
|
|
||||||
{
|
|
||||||
ShowerState.Active => ReplayEventType.Decision,
|
|
||||||
ShowerState.Completed => ReplayEventType.StateChange,
|
|
||||||
_ => ReplayEventType.Info
|
|
||||||
};
|
|
||||||
|
|
||||||
_replayTimeline.AddEvent(new ReplayEvent
|
|
||||||
{
|
|
||||||
Timestamp = currentTime,
|
|
||||||
Monitor = MonitorName,
|
|
||||||
EventType = eventType,
|
|
||||||
Message = $"State: {previousState} → {state} (bathroom: {bathroomHumidity.Value:F1}%, home: {homeHumidity.Value:F1}%, diff: {differential:F1}%)",
|
|
||||||
Details = GetStateChangeDetails(state)
|
|
||||||
});
|
|
||||||
|
|
||||||
previousState = state;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
currentTime = currentTime.Add(pollInterval);
|
|
||||||
}
|
|
||||||
|
|
||||||
_replayTimeline.AddEvent(new ReplayEvent
|
|
||||||
{
|
|
||||||
Timestamp = _replayOptions.EndTime,
|
|
||||||
Monitor = MonitorName,
|
|
||||||
EventType = ReplayEventType.Info,
|
|
||||||
Message = $"Final: {_detectionService.TodaySessionCount} session(s) detected"
|
|
||||||
});
|
|
||||||
|
|
||||||
_logger.LogInformation("Shower replay complete");
|
|
||||||
return Task.CompletedTask;
|
|
||||||
}
|
|
||||||
|
|
||||||
private string? GetStateChangeDetails(ShowerState state) =>
|
|
||||||
state switch
|
|
||||||
{
|
|
||||||
ShowerState.Completed when _detectionService.LastCompletedSession is not null =>
|
|
||||||
$"Duration: {_detectionService.LastCompletedSession.Duration:mm\\:ss}, Peak humidity: {_detectionService.LastCompletedSession.PeakHumidity:F1}%",
|
|
||||||
_ => null
|
|
||||||
};
|
|
||||||
|
|
||||||
private static double? ParseDouble(string? value)
|
|
||||||
{
|
|
||||||
if (value is null or "unavailable" or "unknown")
|
|
||||||
{
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return double.TryParse(value, CultureInfo.InvariantCulture, out var result) ? result : null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,57 +0,0 @@
|
|||||||
{
|
|
||||||
"HomeAssistant": {
|
|
||||||
"Host": "homeassistant.local",
|
|
||||||
"Port": 8123,
|
|
||||||
"Token": "<your-long-lived-access-token>",
|
|
||||||
"Ssl": false
|
|
||||||
},
|
|
||||||
"Replay": {
|
|
||||||
"StartTime": "2026-03-30T00:00:00+02:00",
|
|
||||||
"EndTime": "2026-03-31T00:00:00+02:00",
|
|
||||||
"Monitors": {
|
|
||||||
"NordPool": true,
|
|
||||||
"Boiler": true,
|
|
||||||
"Shower": true,
|
|
||||||
"Power": false,
|
|
||||||
"Light": true
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"BoilerMonitor": {
|
|
||||||
"Enabled": true,
|
|
||||||
"CleanupEntitiesOnStartup": false
|
|
||||||
},
|
|
||||||
"ShowerMonitor": {
|
|
||||||
"Enabled": true,
|
|
||||||
"CleanupEntitiesOnStartup": false,
|
|
||||||
"BathroomHumidityEntityId": "sensor.bathroom_humidity",
|
|
||||||
"MainHomeHumidityEntityId": "sensor.main_home_humidity",
|
|
||||||
"BathroomTemperatureEntityId": "sensor.bathroom_temperature",
|
|
||||||
"ExhaustFanEntityId": "switch.exhaust_fan",
|
|
||||||
"PollIntervalSeconds": 30,
|
|
||||||
"SpikeRateThreshold": 4.0,
|
|
||||||
"MinDifferentialHumidity": 8.0,
|
|
||||||
"PeakHumidityThreshold": 58.0,
|
|
||||||
"ConfirmationWindowMinutes": 2,
|
|
||||||
"RecoveryDifferentialThreshold": 5.0,
|
|
||||||
"MaxShowerDurationMinutes": 60,
|
|
||||||
"FanRunAfterShowerMinutes": 10,
|
|
||||||
"RateWindowSize": 5
|
|
||||||
},
|
|
||||||
"LightMonitor": {
|
|
||||||
"Enabled": true,
|
|
||||||
"LightEntityId": "light.sonoff_1002214d40",
|
|
||||||
"SunEntityId": "sun.sun",
|
|
||||||
"PersonEntityIds": ["person.marius", "person.erika", "person.home_phone"]
|
|
||||||
},
|
|
||||||
"PowerMonitor": {
|
|
||||||
"Enabled": false,
|
|
||||||
"MainMeterEntityId": "sensor.sonoff_100267d63f_power",
|
|
||||||
"PollIntervalSeconds": 1,
|
|
||||||
"SmoothingWindowSize": 10,
|
|
||||||
"AnomalyThresholdWatts": 500,
|
|
||||||
"ExcludedSensorPatterns": [
|
|
||||||
"sensor.nordpool_*",
|
|
||||||
"sensor.powermonitor_*"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
|
||||||
|
|
||||||
<PropertyGroup>
|
|
||||||
<OutputType>Exe</OutputType>
|
|
||||||
<TargetFramework>net10.0</TargetFramework>
|
|
||||||
<LangVersion>14.0</LangVersion>
|
|
||||||
<Nullable>enable</Nullable>
|
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
|
||||||
<RootNamespace>HomeAssistant.McpServer</RootNamespace>
|
|
||||||
</PropertyGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<PackageReference Include="Microsoft.Extensions.Hosting" Version="10.0.5" />
|
|
||||||
<PackageReference Include="Microsoft.Extensions.Http" Version="10.0.5" />
|
|
||||||
<PackageReference Include="ModelContextProtocol" Version="1.2.0" />
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
</Project>
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
using HomeAssistant.McpServer.Services;
|
|
||||||
using HomeAssistant.McpServer.Settings;
|
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
|
||||||
using Microsoft.Extensions.Hosting;
|
|
||||||
using Microsoft.Extensions.Logging;
|
|
||||||
using ModelContextProtocol.Server;
|
|
||||||
|
|
||||||
var builder = Host.CreateApplicationBuilder(args);
|
|
||||||
|
|
||||||
builder.Logging.AddConsole(options =>
|
|
||||||
{
|
|
||||||
options.LogToStandardErrorThreshold = LogLevel.Trace;
|
|
||||||
});
|
|
||||||
|
|
||||||
builder.Services
|
|
||||||
.Configure<HomeAssistantSettings>(
|
|
||||||
builder.Configuration.GetSection(HomeAssistantSettings.SectionName))
|
|
||||||
.AddHttpClient<IHomeAssistantApiClient, HomeAssistantApiClient>();
|
|
||||||
|
|
||||||
builder.Services
|
|
||||||
.AddMcpServer()
|
|
||||||
.WithStdioServerTransport()
|
|
||||||
.WithToolsFromAssembly();
|
|
||||||
|
|
||||||
await builder.Build().RunAsync();
|
|
||||||
@@ -1,107 +0,0 @@
|
|||||||
using System.Net.Http.Headers;
|
|
||||||
using System.Net.Http.Json;
|
|
||||||
using System.Text.Json;
|
|
||||||
using HomeAssistant.McpServer.Settings;
|
|
||||||
using Microsoft.Extensions.Options;
|
|
||||||
|
|
||||||
namespace HomeAssistant.McpServer.Services;
|
|
||||||
|
|
||||||
public sealed class HomeAssistantApiClient : IHomeAssistantApiClient
|
|
||||||
{
|
|
||||||
private readonly HttpClient _httpClient;
|
|
||||||
|
|
||||||
public HomeAssistantApiClient(HttpClient httpClient, IOptions<HomeAssistantSettings> settings)
|
|
||||||
{
|
|
||||||
_httpClient = httpClient;
|
|
||||||
_httpClient.BaseAddress = settings.Value.BaseUrl;
|
|
||||||
_httpClient.DefaultRequestHeaders.Authorization =
|
|
||||||
new AuthenticationHeaderValue("Bearer", settings.Value.Token);
|
|
||||||
_httpClient.DefaultRequestHeaders.Accept.Add(
|
|
||||||
new MediaTypeWithQualityHeaderValue("application/json"));
|
|
||||||
_httpClient.Timeout = TimeSpan.FromSeconds(HomeAssistantSettings.DefaultTimeoutSeconds);
|
|
||||||
}
|
|
||||||
|
|
||||||
public Task<JsonElement> GetApiStatusAsync(CancellationToken cancellationToken = default) =>
|
|
||||||
GetJsonAsync("/api/", cancellationToken);
|
|
||||||
|
|
||||||
public Task<JsonElement> GetConfigAsync(CancellationToken cancellationToken = default) =>
|
|
||||||
GetJsonAsync("/api/config", cancellationToken);
|
|
||||||
|
|
||||||
public Task<JsonElement> GetAllStatesAsync(CancellationToken cancellationToken = default) =>
|
|
||||||
GetJsonAsync("/api/states", cancellationToken);
|
|
||||||
|
|
||||||
public Task<JsonElement> GetEntityStateAsync(string entityId, CancellationToken cancellationToken = default) =>
|
|
||||||
GetJsonAsync($"/api/states/{Uri.EscapeDataString(entityId)}", cancellationToken);
|
|
||||||
|
|
||||||
public Task<JsonElement> GetServicesAsync(CancellationToken cancellationToken = default) =>
|
|
||||||
GetJsonAsync("/api/services", cancellationToken);
|
|
||||||
|
|
||||||
public Task<JsonElement> GetHistoryAsync(
|
|
||||||
string entityIds,
|
|
||||||
DateTimeOffset? startTime = null,
|
|
||||||
DateTimeOffset? endTime = null,
|
|
||||||
bool minimalResponse = true,
|
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
var start = startTime ?? DateTimeOffset.UtcNow.AddDays(-1);
|
|
||||||
var path = $"/api/history/period/{start:O}?filter_entity_id={Uri.EscapeDataString(entityIds)}";
|
|
||||||
|
|
||||||
if (endTime.HasValue)
|
|
||||||
path += $"&end_time={Uri.EscapeDataString(endTime.Value.ToString("O"))}";
|
|
||||||
|
|
||||||
if (minimalResponse)
|
|
||||||
path += "&minimal_response";
|
|
||||||
|
|
||||||
return GetJsonAsync(path, cancellationToken);
|
|
||||||
}
|
|
||||||
|
|
||||||
public Task<JsonElement> GetLogbookAsync(
|
|
||||||
string? entityId = null,
|
|
||||||
DateTimeOffset? startTime = null,
|
|
||||||
DateTimeOffset? endTime = null,
|
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
var start = startTime ?? DateTimeOffset.UtcNow.AddDays(-1);
|
|
||||||
var path = $"/api/logbook/{start:O}";
|
|
||||||
|
|
||||||
var queryParts = new List<string>();
|
|
||||||
if (!string.IsNullOrWhiteSpace(entityId))
|
|
||||||
queryParts.Add($"entity={Uri.EscapeDataString(entityId)}");
|
|
||||||
if (endTime.HasValue)
|
|
||||||
queryParts.Add($"end_time={Uri.EscapeDataString(endTime.Value.ToString("O"))}");
|
|
||||||
|
|
||||||
if (queryParts.Count > 0)
|
|
||||||
path += "?" + string.Join("&", queryParts);
|
|
||||||
|
|
||||||
return GetJsonAsync(path, cancellationToken);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task<JsonElement> CallServiceAsync(
|
|
||||||
string domain,
|
|
||||||
string service,
|
|
||||||
JsonElement? serviceData = null,
|
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
var url = $"/api/services/{Uri.EscapeDataString(domain)}/{Uri.EscapeDataString(service)}";
|
|
||||||
var content = serviceData.HasValue
|
|
||||||
? JsonContent.Create(serviceData.Value)
|
|
||||||
: JsonContent.Create(new { });
|
|
||||||
|
|
||||||
var response = await _httpClient.PostAsync(url, content, cancellationToken).ConfigureAwait(false);
|
|
||||||
response.EnsureSuccessStatusCode();
|
|
||||||
|
|
||||||
await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
|
|
||||||
var doc = await JsonDocument.ParseAsync(stream, cancellationToken: cancellationToken).ConfigureAwait(false);
|
|
||||||
return doc.RootElement.Clone();
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task<JsonElement> GetJsonAsync(string path, CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
var response = await _httpClient.GetAsync(path, cancellationToken).ConfigureAwait(false);
|
|
||||||
response.EnsureSuccessStatusCode();
|
|
||||||
|
|
||||||
await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
|
|
||||||
var doc = await JsonDocument.ParseAsync(stream, cancellationToken: cancellationToken).ConfigureAwait(false);
|
|
||||||
return doc.RootElement.Clone();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
using System.Text.Json;
|
|
||||||
|
|
||||||
namespace HomeAssistant.McpServer.Services;
|
|
||||||
|
|
||||||
public interface IHomeAssistantApiClient
|
|
||||||
{
|
|
||||||
Task<JsonElement> GetApiStatusAsync(CancellationToken cancellationToken = default);
|
|
||||||
Task<JsonElement> GetConfigAsync(CancellationToken cancellationToken = default);
|
|
||||||
Task<JsonElement> GetAllStatesAsync(CancellationToken cancellationToken = default);
|
|
||||||
Task<JsonElement> GetEntityStateAsync(string entityId, CancellationToken cancellationToken = default);
|
|
||||||
Task<JsonElement> GetServicesAsync(CancellationToken cancellationToken = default);
|
|
||||||
|
|
||||||
Task<JsonElement> GetHistoryAsync(
|
|
||||||
string entityIds,
|
|
||||||
DateTimeOffset? startTime = null,
|
|
||||||
DateTimeOffset? endTime = null,
|
|
||||||
bool minimalResponse = true,
|
|
||||||
CancellationToken cancellationToken = default);
|
|
||||||
|
|
||||||
Task<JsonElement> GetLogbookAsync(
|
|
||||||
string? entityId = null,
|
|
||||||
DateTimeOffset? startTime = null,
|
|
||||||
DateTimeOffset? endTime = null,
|
|
||||||
CancellationToken cancellationToken = default);
|
|
||||||
|
|
||||||
Task<JsonElement> CallServiceAsync(
|
|
||||||
string domain,
|
|
||||||
string service,
|
|
||||||
JsonElement? serviceData = null,
|
|
||||||
CancellationToken cancellationToken = default);
|
|
||||||
}
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
namespace HomeAssistant.McpServer.Settings;
|
|
||||||
|
|
||||||
public sealed class HomeAssistantSettings
|
|
||||||
{
|
|
||||||
public const string SectionName = "HomeAssistant";
|
|
||||||
public const int DefaultPort = 8123;
|
|
||||||
public const int DefaultTimeoutSeconds = 30;
|
|
||||||
|
|
||||||
public string Host { get; set; } = string.Empty;
|
|
||||||
public int Port { get; set; } = DefaultPort;
|
|
||||||
public string Token { get; set; } = string.Empty;
|
|
||||||
public bool Ssl { get; set; }
|
|
||||||
|
|
||||||
public Uri BaseUrl => new UriBuilder(Ssl ? "https" : "http", Host, Port).Uri;
|
|
||||||
}
|
|
||||||
@@ -1,98 +0,0 @@
|
|||||||
using System.ComponentModel;
|
|
||||||
using System.Text.Json;
|
|
||||||
using HomeAssistant.McpServer.Services;
|
|
||||||
using ModelContextProtocol.Server;
|
|
||||||
|
|
||||||
namespace HomeAssistant.McpServer.Tools;
|
|
||||||
|
|
||||||
[McpServerToolType]
|
|
||||||
public sealed class EntityStateTools
|
|
||||||
{
|
|
||||||
private readonly IHomeAssistantApiClient _client;
|
|
||||||
|
|
||||||
public EntityStateTools(IHomeAssistantApiClient client)
|
|
||||||
{
|
|
||||||
_client = client;
|
|
||||||
}
|
|
||||||
|
|
||||||
[McpServerTool, Description(
|
|
||||||
"Get the current state and attributes of a single Home Assistant entity. " +
|
|
||||||
"Provide the full entity_id, e.g. 'sensor.nordpool_kwh_lt_eur_3_10_0' or 'switch.boiler'.")]
|
|
||||||
public async Task<string> GetEntityState(
|
|
||||||
[Description("Full entity ID, e.g. 'sensor.temperature' or 'light.living_room'")] string entityId,
|
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
var result = await _client.GetEntityStateAsync(entityId, cancellationToken).ConfigureAwait(false);
|
|
||||||
return FormatJson(result);
|
|
||||||
}
|
|
||||||
|
|
||||||
[McpServerTool, Description(
|
|
||||||
"Get the current states of all Home Assistant entities. " +
|
|
||||||
"Optionally filter by domain (e.g. 'sensor', 'switch', 'climate', 'light'). " +
|
|
||||||
"Returns entity_id, state, and key attributes for each entity.")]
|
|
||||||
public async Task<string> GetAllStates(
|
|
||||||
[Description("Optional domain filter, e.g. 'sensor', 'switch', 'climate'. Leave empty for all.")] string? domain = null,
|
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
var allStates = await _client.GetAllStatesAsync(cancellationToken).ConfigureAwait(false);
|
|
||||||
|
|
||||||
if (string.IsNullOrWhiteSpace(domain))
|
|
||||||
return FormatJson(allStates);
|
|
||||||
|
|
||||||
var filtered = allStates.EnumerateArray()
|
|
||||||
.Where(e => e.TryGetProperty("entity_id", out var eid) &&
|
|
||||||
eid.GetString()?.StartsWith(domain + ".", StringComparison.OrdinalIgnoreCase) == true)
|
|
||||||
.ToList();
|
|
||||||
|
|
||||||
return JsonSerializer.Serialize(filtered, SerializerOptions);
|
|
||||||
}
|
|
||||||
|
|
||||||
[McpServerTool, Description(
|
|
||||||
"Search Home Assistant entities by partial match on entity_id or friendly_name. " +
|
|
||||||
"Useful for discovering entities related to a topic (e.g. 'nordpool', 'boiler', 'temperature').")]
|
|
||||||
public async Task<string> SearchEntities(
|
|
||||||
[Description("Search term to match against entity_id or friendly_name")] string query,
|
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
var allStates = await _client.GetAllStatesAsync(cancellationToken).ConfigureAwait(false);
|
|
||||||
|
|
||||||
var matches = allStates.EnumerateArray()
|
|
||||||
.Where(e => MatchesQuery(e, query))
|
|
||||||
.Select(e => new
|
|
||||||
{
|
|
||||||
entity_id = e.GetProperty("entity_id").GetString(),
|
|
||||||
state = e.GetProperty("state").GetString(),
|
|
||||||
friendly_name = e.TryGetProperty("attributes", out var attrs) &&
|
|
||||||
attrs.TryGetProperty("friendly_name", out var fn)
|
|
||||||
? fn.GetString()
|
|
||||||
: null
|
|
||||||
})
|
|
||||||
.ToList();
|
|
||||||
|
|
||||||
return JsonSerializer.Serialize(matches, SerializerOptions);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static bool MatchesQuery(JsonElement entity, string query)
|
|
||||||
{
|
|
||||||
var q = query.ToUpperInvariant();
|
|
||||||
|
|
||||||
if (entity.TryGetProperty("entity_id", out var eid) &&
|
|
||||||
(eid.GetString()?.ToUpperInvariant().Contains(q) ?? false))
|
|
||||||
return true;
|
|
||||||
|
|
||||||
if (entity.TryGetProperty("attributes", out var attrs) &&
|
|
||||||
attrs.TryGetProperty("friendly_name", out var fn) &&
|
|
||||||
(fn.GetString()?.ToUpperInvariant().Contains(q) ?? false))
|
|
||||||
return true;
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static string FormatJson(JsonElement element) =>
|
|
||||||
JsonSerializer.Serialize(element, SerializerOptions);
|
|
||||||
|
|
||||||
private static readonly JsonSerializerOptions SerializerOptions = new()
|
|
||||||
{
|
|
||||||
WriteIndented = true
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,46 +0,0 @@
|
|||||||
using System.ComponentModel;
|
|
||||||
using System.Text.Json;
|
|
||||||
using HomeAssistant.McpServer.Services;
|
|
||||||
using ModelContextProtocol.Server;
|
|
||||||
|
|
||||||
namespace HomeAssistant.McpServer.Tools;
|
|
||||||
|
|
||||||
[McpServerToolType]
|
|
||||||
public sealed class HistoryTools
|
|
||||||
{
|
|
||||||
private readonly IHomeAssistantApiClient _client;
|
|
||||||
|
|
||||||
public HistoryTools(IHomeAssistantApiClient client)
|
|
||||||
{
|
|
||||||
_client = client;
|
|
||||||
}
|
|
||||||
|
|
||||||
[McpServerTool, Description(
|
|
||||||
"Get state history for one or more Home Assistant entities over a time period. " +
|
|
||||||
"Returns timestamped state changes. Useful for debugging sensor readings, switch toggling, price changes, etc.")]
|
|
||||||
public async Task<string> GetEntityHistory(
|
|
||||||
[Description("Comma-separated entity IDs, e.g. 'sensor.temperature,sensor.humidity'")] string entityIds,
|
|
||||||
[Description("Start time in ISO 8601 format. Defaults to 24 hours ago. Example: '2026-03-30T00:00:00'")] string? startTime = null,
|
|
||||||
[Description("End time in ISO 8601 format. Defaults to now. Example: '2026-03-31T00:00:00'")] string? endTime = null,
|
|
||||||
[Description("If true, returns minimal data (state + last_changed only). Defaults to true.")] bool minimalResponse = true,
|
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
DateTimeOffset? start = string.IsNullOrWhiteSpace(startTime)
|
|
||||||
? null
|
|
||||||
: DateTimeOffset.Parse(startTime);
|
|
||||||
|
|
||||||
DateTimeOffset? end = string.IsNullOrWhiteSpace(endTime)
|
|
||||||
? null
|
|
||||||
: DateTimeOffset.Parse(endTime);
|
|
||||||
|
|
||||||
var result = await _client.GetHistoryAsync(entityIds, start, end, minimalResponse, cancellationToken)
|
|
||||||
.ConfigureAwait(false);
|
|
||||||
|
|
||||||
return JsonSerializer.Serialize(result, SerializerOptions);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static readonly JsonSerializerOptions SerializerOptions = new()
|
|
||||||
{
|
|
||||||
WriteIndented = true
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
using System.ComponentModel;
|
|
||||||
using System.Text.Json;
|
|
||||||
using HomeAssistant.McpServer.Services;
|
|
||||||
using ModelContextProtocol.Server;
|
|
||||||
|
|
||||||
namespace HomeAssistant.McpServer.Tools;
|
|
||||||
|
|
||||||
[McpServerToolType]
|
|
||||||
public sealed class LogbookTools
|
|
||||||
{
|
|
||||||
private readonly IHomeAssistantApiClient _client;
|
|
||||||
|
|
||||||
public LogbookTools(IHomeAssistantApiClient client)
|
|
||||||
{
|
|
||||||
_client = client;
|
|
||||||
}
|
|
||||||
|
|
||||||
[McpServerTool, Description(
|
|
||||||
"Get Home Assistant logbook entries. Shows state changes and events for entities. " +
|
|
||||||
"Useful for understanding what happened and when. Filter by entity and/or time range.")]
|
|
||||||
public async Task<string> GetLogbook(
|
|
||||||
[Description("Optional entity ID to filter, e.g. 'switch.boiler'. Leave empty for all.")] string? entityId = null,
|
|
||||||
[Description("Start time in ISO 8601 format. Defaults to 24 hours ago.")] string? startTime = null,
|
|
||||||
[Description("End time in ISO 8601 format. Defaults to now.")] string? endTime = null,
|
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
DateTimeOffset? start = string.IsNullOrWhiteSpace(startTime)
|
|
||||||
? null
|
|
||||||
: DateTimeOffset.Parse(startTime);
|
|
||||||
|
|
||||||
DateTimeOffset? end = string.IsNullOrWhiteSpace(endTime)
|
|
||||||
? null
|
|
||||||
: DateTimeOffset.Parse(endTime);
|
|
||||||
|
|
||||||
var result = await _client.GetLogbookAsync(entityId, start, end, cancellationToken)
|
|
||||||
.ConfigureAwait(false);
|
|
||||||
|
|
||||||
return JsonSerializer.Serialize(result, SerializerOptions);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static readonly JsonSerializerOptions SerializerOptions = new()
|
|
||||||
{
|
|
||||||
WriteIndented = true
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,75 +0,0 @@
|
|||||||
using System.ComponentModel;
|
|
||||||
using System.Text.Json;
|
|
||||||
using HomeAssistant.McpServer.Services;
|
|
||||||
using ModelContextProtocol.Server;
|
|
||||||
|
|
||||||
namespace HomeAssistant.McpServer.Tools;
|
|
||||||
|
|
||||||
[McpServerToolType]
|
|
||||||
public sealed class ServiceTools
|
|
||||||
{
|
|
||||||
private readonly IHomeAssistantApiClient _client;
|
|
||||||
|
|
||||||
public ServiceTools(IHomeAssistantApiClient client)
|
|
||||||
{
|
|
||||||
_client = client;
|
|
||||||
}
|
|
||||||
|
|
||||||
[McpServerTool, Description(
|
|
||||||
"List available Home Assistant services. Optionally filter by domain (e.g. 'light', 'climate', 'switch'). " +
|
|
||||||
"Each service shows its domain and available service names.")]
|
|
||||||
public async Task<string> ListServices(
|
|
||||||
[Description("Optional domain filter, e.g. 'light', 'climate'. Leave empty for all.")] string? domain = null,
|
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
var allServices = await _client.GetServicesAsync(cancellationToken).ConfigureAwait(false);
|
|
||||||
|
|
||||||
if (string.IsNullOrWhiteSpace(domain))
|
|
||||||
return FormatJson(allServices);
|
|
||||||
|
|
||||||
var filtered = allServices.EnumerateArray()
|
|
||||||
.Where(s => s.TryGetProperty("domain", out var d) &&
|
|
||||||
string.Equals(d.GetString(), domain, StringComparison.OrdinalIgnoreCase))
|
|
||||||
.ToList();
|
|
||||||
|
|
||||||
return JsonSerializer.Serialize(filtered, SerializerOptions);
|
|
||||||
}
|
|
||||||
|
|
||||||
[McpServerTool, Description(
|
|
||||||
"Call a Home Assistant service. Examples: domain='light', service='turn_on', entityId='light.living_room'. " +
|
|
||||||
"For services requiring extra data, pass it as a JSON string in serviceData.")]
|
|
||||||
public async Task<string> CallService(
|
|
||||||
[Description("Service domain, e.g. 'light', 'climate', 'switch', 'input_boolean'")] string domain,
|
|
||||||
[Description("Service name, e.g. 'turn_on', 'turn_off', 'set_temperature'")] string service,
|
|
||||||
[Description("Optional target entity ID, e.g. 'light.living_room'")] string? entityId = null,
|
|
||||||
[Description("Optional JSON service data, e.g. '{\"brightness\": 255}' or '{\"temperature\": 22}'")] string? serviceData = null,
|
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
JsonElement? data = null;
|
|
||||||
|
|
||||||
if (!string.IsNullOrWhiteSpace(serviceData) || !string.IsNullOrWhiteSpace(entityId))
|
|
||||||
{
|
|
||||||
var dataDict = string.IsNullOrWhiteSpace(serviceData)
|
|
||||||
? new Dictionary<string, object>()
|
|
||||||
: JsonSerializer.Deserialize<Dictionary<string, object>>(serviceData) ?? [];
|
|
||||||
|
|
||||||
if (!string.IsNullOrWhiteSpace(entityId))
|
|
||||||
dataDict["entity_id"] = entityId;
|
|
||||||
|
|
||||||
data = JsonSerializer.SerializeToElement(dataDict);
|
|
||||||
}
|
|
||||||
|
|
||||||
var result = await _client.CallServiceAsync(domain, service, data, cancellationToken)
|
|
||||||
.ConfigureAwait(false);
|
|
||||||
|
|
||||||
return FormatJson(result);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static string FormatJson(JsonElement element) =>
|
|
||||||
JsonSerializer.Serialize(element, SerializerOptions);
|
|
||||||
|
|
||||||
private static readonly JsonSerializerOptions SerializerOptions = new()
|
|
||||||
{
|
|
||||||
WriteIndented = true
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,52 +0,0 @@
|
|||||||
using System.ComponentModel;
|
|
||||||
using System.Text.Json;
|
|
||||||
using HomeAssistant.McpServer.Services;
|
|
||||||
using ModelContextProtocol.Server;
|
|
||||||
|
|
||||||
namespace HomeAssistant.McpServer.Tools;
|
|
||||||
|
|
||||||
[McpServerToolType]
|
|
||||||
public sealed class SystemTools
|
|
||||||
{
|
|
||||||
private readonly IHomeAssistantApiClient _client;
|
|
||||||
|
|
||||||
public SystemTools(IHomeAssistantApiClient client)
|
|
||||||
{
|
|
||||||
_client = client;
|
|
||||||
}
|
|
||||||
|
|
||||||
[McpServerTool, Description(
|
|
||||||
"Get Home Assistant configuration including version, location, components, and unit system. " +
|
|
||||||
"Useful for understanding the HA environment.")]
|
|
||||||
public async Task<string> GetHaConfig(CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
var result = await _client.GetConfigAsync(cancellationToken).ConfigureAwait(false);
|
|
||||||
return JsonSerializer.Serialize(result, SerializerOptions);
|
|
||||||
}
|
|
||||||
|
|
||||||
[McpServerTool, Description(
|
|
||||||
"Check if the Home Assistant API is reachable and responding. " +
|
|
||||||
"Returns the API status message or an error description.")]
|
|
||||||
public async Task<string> CheckApi(CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var result = await _client.GetApiStatusAsync(cancellationToken).ConfigureAwait(false);
|
|
||||||
return JsonSerializer.Serialize(result, SerializerOptions);
|
|
||||||
}
|
|
||||||
catch (HttpRequestException ex)
|
|
||||||
{
|
|
||||||
return JsonSerializer.Serialize(new { status = "error", message = ex.Message }, SerializerOptions);
|
|
||||||
}
|
|
||||||
catch (TaskCanceledException)
|
|
||||||
{
|
|
||||||
return JsonSerializer.Serialize(
|
|
||||||
new { status = "error", message = "Request timed out - HA may be unreachable" }, SerializerOptions);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static readonly JsonSerializerOptions SerializerOptions = new()
|
|
||||||
{
|
|
||||||
WriteIndented = true
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,10 +1,14 @@
|
|||||||
using NetDaemon.Extensions.MqttEntityManager;
|
#region
|
||||||
|
|
||||||
|
using NetDaemon.Extensions.MqttEntityManager;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace HomeAssistant.Models;
|
namespace HomeAssistant.Models;
|
||||||
|
|
||||||
public class EntityCreateModel
|
public class EntityCreateModel
|
||||||
{
|
{
|
||||||
public string? EntityId { get; set; }
|
public string? EntityId { get; protected init; }
|
||||||
public EntityCreationOptions? Options { get; set; } = new();
|
public EntityCreationOptions? Options { get; init; } = new EntityCreationOptions();
|
||||||
public object? AdditionalConfig { get; set; } = null;
|
public object? AdditionalConfig { get; init; }
|
||||||
}
|
}
|
||||||
@@ -7,7 +7,7 @@
|
|||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="NetDaemon.Extensions.Mqtt" Version="26.11.0" />
|
<PackageReference Include="NetDaemon.Extensions.Mqtt" Version="26.43.1"/>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
@@ -1,8 +1,12 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
using System;
|
using System;
|
||||||
using Microsoft.Extensions.Configuration;
|
using Microsoft.Extensions.Configuration;
|
||||||
using Microsoft.Extensions.Hosting;
|
using Microsoft.Extensions.Hosting;
|
||||||
using Serilog;
|
using Serilog;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace HomeAssistantServer;
|
namespace HomeAssistantServer;
|
||||||
|
|
||||||
public static class CustomLoggingProvider
|
public static class CustomLoggingProvider
|
||||||
@@ -11,7 +15,8 @@ public static class CustomLoggingProvider
|
|||||||
{
|
{
|
||||||
var configuration = new ConfigurationBuilder()
|
var configuration = new ConfigurationBuilder()
|
||||||
.AddJsonFile("appsettings.json")
|
.AddJsonFile("appsettings.json")
|
||||||
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") ?? "Production"}.json", optional: true)
|
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") ?? "Production"}.json",
|
||||||
|
true)
|
||||||
.Build();
|
.Build();
|
||||||
|
|
||||||
var logger = new LoggerConfiguration()
|
var logger = new LoggerConfiguration()
|
||||||
|
|||||||
@@ -27,36 +27,41 @@
|
|||||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||||
<CopyToPublishDirectory>Never</CopyToPublishDirectory>
|
<CopyToPublishDirectory>Never</CopyToPublishDirectory>
|
||||||
</None>
|
</None>
|
||||||
|
<None Update="$(MSBuildProjectDir)appsettings.Production.json">
|
||||||
|
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||||
|
<CopyToPublishDirectory>Always</CopyToPublishDirectory>
|
||||||
|
</None>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
<Target Name="AfterPublishMessage" AfterTargets="Publish">
|
<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>
|
</Target>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="AutoMapper" Version="16.1.1" />
|
<PackageReference Include="AutoMapper" Version="17.0.0"/>
|
||||||
<PackageReference Include="NetDaemon.AppModel" Version="26.11.0" />
|
<PackageReference Include="NetDaemon.AppModel" Version="26.43.1"/>
|
||||||
<PackageReference Include="NetDaemon.Runtime" Version="26.11.0" />
|
<PackageReference Include="NetDaemon.Runtime" Version="26.43.1"/>
|
||||||
<PackageReference Include="NetDaemon.HassModel" Version="26.11.0" />
|
<PackageReference Include="NetDaemon.HassModel" Version="26.43.1"/>
|
||||||
<PackageReference Include="NetDaemon.Client" Version="26.11.0" />
|
<PackageReference Include="NetDaemon.Client" Version="26.43.1"/>
|
||||||
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.11.0" />
|
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.43.1"/>
|
||||||
<PackageReference Include="NetDaemon.Extensions.Logging" Version="26.11.0" />
|
<PackageReference Include="NetDaemon.Extensions.Logging" Version="26.43.1"/>
|
||||||
<PackageReference Include="NetDaemon.Extensions.Tts" Version="26.11.0" />
|
<PackageReference Include="NetDaemon.Extensions.Tts" Version="26.43.1"/>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\BoilerMonitor.Manager\BoilerMonitor.Manager.csproj" />
|
<ProjectReference Include="..\BoilerMonitor.Manager\BoilerMonitor.Manager.csproj"/>
|
||||||
<ProjectReference Include="..\BoilerMonitor.Models\BoilerMonitor.Models.csproj" />
|
<ProjectReference Include="..\BoilerMonitor.Models\BoilerMonitor.Models.csproj"/>
|
||||||
<ProjectReference Include="..\HomeAssistant.Entities\HomeAssistant.Entities.csproj" />
|
<ProjectReference Include="..\HomeAssistant.Entities\HomeAssistant.Entities.csproj"/>
|
||||||
<ProjectReference Include="..\Mappings\Mappings.csproj" />
|
<ProjectReference Include="..\Mappings\Mappings.csproj"/>
|
||||||
<ProjectReference Include="..\NordPool.Manager\NordPool.Manager.csproj" />
|
<ProjectReference Include="..\NordPool.Manager\NordPool.Manager.csproj"/>
|
||||||
<ProjectReference Include="..\NordPool.Models\NordPool.Models.csproj" />
|
<ProjectReference Include="..\NordPool.Models\NordPool.Models.csproj"/>
|
||||||
<ProjectReference Include="..\PowerMonitor.Manager\PowerMonitor.Manager.csproj" />
|
<ProjectReference Include="..\PowerMonitor.Manager\PowerMonitor.Manager.csproj"/>
|
||||||
<ProjectReference Include="..\PowerMonitor.Models\PowerMonitor.Models.csproj" />
|
<ProjectReference Include="..\PowerMonitor.Models\PowerMonitor.Models.csproj"/>
|
||||||
<ProjectReference Include="..\ShowerMonitor.Manager\ShowerMonitor.Manager.csproj" />
|
<ProjectReference Include="..\ShowerMonitor.Manager\ShowerMonitor.Manager.csproj"/>
|
||||||
<ProjectReference Include="..\ShowerMonitor.Models\ShowerMonitor.Models.csproj" />
|
<ProjectReference Include="..\ShowerMonitor.Models\ShowerMonitor.Models.csproj"/>
|
||||||
<ProjectReference Include="..\LightMonitor.Manager\LightMonitor.Manager.csproj" />
|
<ProjectReference Include="..\LightMonitor.Manager\LightMonitor.Manager.csproj"/>
|
||||||
<ProjectReference Include="..\LightMonitor.Models\LightMonitor.Models.csproj" />
|
<ProjectReference Include="..\LightMonitor.Models\LightMonitor.Models.csproj"/>
|
||||||
<ProjectReference Include="..\BatteryMonitor.Manager\BatteryMonitor.Manager.csproj" />
|
<ProjectReference Include="..\BatteryMonitor.Manager\BatteryMonitor.Manager.csproj"/>
|
||||||
<ProjectReference Include="..\BatteryMonitor.Models\BatteryMonitor.Models.csproj" />
|
<ProjectReference Include="..\BatteryMonitor.Models\BatteryMonitor.Models.csproj"/>
|
||||||
|
<ProjectReference Include="..\LeakMonitor.Manager\LeakMonitor.Manager.csproj"/>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
@@ -0,0 +1,239 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Text.Json;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using BoilerMonitorManager.Interface;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using NetDaemon.AppModel;
|
||||||
|
using NetDaemon.Extensions.MqttEntityManager;
|
||||||
|
using NetDaemon.HassModel;
|
||||||
|
using NetDaemon.HassModel.Entities;
|
||||||
|
using NordPoolManager.Interface;
|
||||||
|
using PowerMonitorManager.Interface;
|
||||||
|
using ShowerMonitorManager.Interface;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace HomeAssistantServer;
|
||||||
|
|
||||||
|
[NetDaemonApp]
|
||||||
|
public sealed class MqttRecreateApp
|
||||||
|
{
|
||||||
|
private const string RecreateButtonEntityId = "button.appdaemon_recreate_all";
|
||||||
|
private const string NordPoolPriceEntityId = "sensor.nordpool_price";
|
||||||
|
private const string DefaultUnitOfMeasurement = "EUR/kWh";
|
||||||
|
|
||||||
|
private static readonly string[] AppDaemonIdentifiers = ["appdaemon"];
|
||||||
|
|
||||||
|
private readonly IHaContext _haContext;
|
||||||
|
private readonly ILogger<MqttRecreateApp> _logger;
|
||||||
|
private readonly IMqttEntityManager _mqttEntityManager;
|
||||||
|
private readonly IServiceProvider _serviceProvider;
|
||||||
|
|
||||||
|
public MqttRecreateApp(
|
||||||
|
IHaContext haContext,
|
||||||
|
IMqttEntityManager mqttEntityManager,
|
||||||
|
IServiceProvider serviceProvider,
|
||||||
|
ILogger<MqttRecreateApp> logger)
|
||||||
|
{
|
||||||
|
_haContext = haContext;
|
||||||
|
_mqttEntityManager = mqttEntityManager;
|
||||||
|
_serviceProvider = serviceProvider;
|
||||||
|
_logger = logger;
|
||||||
|
|
||||||
|
_ = InitializeAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task InitializeAsync()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await Task.Delay(TimeSpan.FromSeconds(5));
|
||||||
|
|
||||||
|
await _mqttEntityManager.CreateAsync(
|
||||||
|
RecreateButtonEntityId,
|
||||||
|
new EntityCreationOptions
|
||||||
|
{
|
||||||
|
UniqueId = RecreateButtonEntityId,
|
||||||
|
Name = "Recreate all MQTT entities"
|
||||||
|
},
|
||||||
|
new
|
||||||
|
{
|
||||||
|
icon = "mdi:refresh",
|
||||||
|
device = new
|
||||||
|
{
|
||||||
|
identifiers = AppDaemonIdentifiers,
|
||||||
|
name = "AppDaemon",
|
||||||
|
model = "AppDaemon",
|
||||||
|
manufacturer = "HomeAssistant App Daemon"
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
|
||||||
|
if (_logger.IsEnabled(LogLevel.Information))
|
||||||
|
{
|
||||||
|
_logger.LogInformation("Recreate-all button created: {EntityId}", RecreateButtonEntityId);
|
||||||
|
}
|
||||||
|
|
||||||
|
var button = new Entity(_haContext, RecreateButtonEntityId);
|
||||||
|
|
||||||
|
button.StateChanges()
|
||||||
|
.Subscribe(_ =>
|
||||||
|
{
|
||||||
|
_logger.LogInformation("Recreate-all button pressed, recreating all MQTT entities");
|
||||||
|
Task.Run(HandleRecreateAsync);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error initializing MqttRecreateApp");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task HandleRecreateAsync()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await RecreateNordPoolAsync();
|
||||||
|
await RecreateBoilerMonitorAsync();
|
||||||
|
await RecreateShowerMonitorAsync();
|
||||||
|
await RecreatePowerMonitorAsync();
|
||||||
|
|
||||||
|
_logger.LogInformation("All MQTT entities recreated successfully");
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error recreating MQTT entities");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task RecreateNordPoolAsync()
|
||||||
|
{
|
||||||
|
var entityService = _serviceProvider.GetService<INordPoolEntityService>();
|
||||||
|
|
||||||
|
if (entityService is null)
|
||||||
|
{
|
||||||
|
_logger.LogDebug("NordPool entity service not registered (disabled), skipping");
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var unitOfMeasurement = ReadUnitOfMeasurement() ?? DefaultUnitOfMeasurement;
|
||||||
|
|
||||||
|
_logger.LogInformation("Recreating NordPool MQTT entities");
|
||||||
|
await entityService.CleanupEntitiesAsync().ConfigureAwait(false);
|
||||||
|
await Task.Delay(TimeSpan.FromSeconds(1));
|
||||||
|
await entityService.CreateEntitiesAsync(unitOfMeasurement).ConfigureAwait(false);
|
||||||
|
await entityService.ResetEntitiesAsync().ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error recreating NordPool entities");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task RecreateBoilerMonitorAsync()
|
||||||
|
{
|
||||||
|
var entityService = _serviceProvider.GetService<IBoilerMonitorEntityService>();
|
||||||
|
|
||||||
|
if (entityService is null)
|
||||||
|
{
|
||||||
|
_logger.LogDebug("BoilerMonitor entity service not registered (disabled), skipping");
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
_logger.LogInformation("Recreating BoilerMonitor MQTT entities");
|
||||||
|
await entityService.CleanupEntitiesAsync().ConfigureAwait(false);
|
||||||
|
await Task.Delay(TimeSpan.FromSeconds(1));
|
||||||
|
await entityService.CreateEntitiesAsync().ConfigureAwait(false);
|
||||||
|
await entityService.ResetEntitiesAsync().ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error recreating BoilerMonitor entities");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task RecreateShowerMonitorAsync()
|
||||||
|
{
|
||||||
|
var entityService = _serviceProvider.GetService<IShowerMonitorEntityService>();
|
||||||
|
|
||||||
|
if (entityService is null)
|
||||||
|
{
|
||||||
|
_logger.LogDebug("ShowerMonitor entity service not registered (disabled), skipping");
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
_logger.LogInformation("Recreating ShowerMonitor MQTT entities");
|
||||||
|
await entityService.CleanupEntitiesAsync().ConfigureAwait(false);
|
||||||
|
await Task.Delay(TimeSpan.FromSeconds(1));
|
||||||
|
await entityService.CreateEntitiesAsync().ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error recreating ShowerMonitor entities");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task RecreatePowerMonitorAsync()
|
||||||
|
{
|
||||||
|
var entityService = _serviceProvider.GetService<IPowerMonitorEntityService>();
|
||||||
|
|
||||||
|
if (entityService is null)
|
||||||
|
{
|
||||||
|
_logger.LogDebug("PowerMonitor entity service not registered (disabled), skipping");
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
_logger.LogInformation("Recreating PowerMonitor MQTT entities");
|
||||||
|
await entityService.RemoveSystemEntitiesAsync().ConfigureAwait(false);
|
||||||
|
await Task.Delay(TimeSpan.FromSeconds(1));
|
||||||
|
await entityService.CreateSystemEntitiesAsync().ConfigureAwait(false);
|
||||||
|
await entityService.ResetEntitiesAsync().ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error recreating PowerMonitor entities");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private string? ReadUnitOfMeasurement()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var state = _haContext.GetState(NordPoolPriceEntityId);
|
||||||
|
|
||||||
|
if (state?.Attributes is IDictionary<string, object> attributes &&
|
||||||
|
attributes.TryGetValue("unit_of_measurement", out var value))
|
||||||
|
{
|
||||||
|
return value switch
|
||||||
|
{
|
||||||
|
string s => s, JsonElement { ValueKind: JsonValueKind.String } je => je.GetString(), _ => null
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
if (_logger.IsEnabled(LogLevel.Debug))
|
||||||
|
{
|
||||||
|
_logger.LogDebug(ex, "Could not read unit_of_measurement for {EntityId}", NordPoolPriceEntityId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,8 +4,8 @@
|
|||||||
"commandName": "Project",
|
"commandName": "Project",
|
||||||
"workingDirectory": "$(ProjectDir)",
|
"workingDirectory": "$(ProjectDir)",
|
||||||
"environmentVariables": {
|
"environmentVariables": {
|
||||||
"ASPNETCORE_ENVIRONMENT": "Development",
|
"ASPNETCORE_ENVIRONMENT": "development",
|
||||||
"DOTNET_ENVIRONMENT": "Development"
|
"DOTNET_ENVIRONMENT": "development"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,21 +1,28 @@
|
|||||||
# Project template for binary deploy
|
# Project template for binary deploy
|
||||||
|
|
||||||
This is the project template for binary deploy. This allows you to build a binary package and deploy it to NetDaemon.
|
This is the project template for binary deploy. This allows you to build a binary package and deploy it to NetDaemon.
|
||||||
|
|
||||||
This is generated using NetDaemon runtime version 5 and .NET 9.
|
This is generated using NetDaemon runtime version 5 and .NET 9.
|
||||||
|
|
||||||
## Getting started
|
## Getting started
|
||||||
Please see [netdaemon.xyz](https://netdaemon.xyz/docs) more information about getting starting developing apps for Home Assistant using NetDaemon.
|
|
||||||
|
Please see [netdaemon.xyz](https://netdaemon.xyz/docs) more information about getting starting developing apps for Home
|
||||||
|
Assistant using NetDaemon.
|
||||||
|
|
||||||
Please add code generation features in `program.cs` when using code generation features by removing comments!
|
Please add code generation features in `program.cs` when using code generation features by removing comments!
|
||||||
|
|
||||||
## Use the code generator
|
## Use the code generator
|
||||||
|
|
||||||
See https://netdaemon.xyz/docs/hass_model/hass_model_codegen
|
See https://netdaemon.xyz/docs/hass_model/hass_model_codegen
|
||||||
|
|
||||||
## Issues
|
## Issues
|
||||||
|
|
||||||
- If you have issues or suggestions of improvements to this template, please [add an issue](https://github.com/net-daemon/netdaemon-app-template)
|
- If you have issues or suggestions of improvements to this template,
|
||||||
- If you have issues or suggestions of improvements to NetDaemon, please [add an issue](https://github.com/net-daemon/netdaemon/issues)
|
please [add an issue](https://github.com/net-daemon/netdaemon-app-template)
|
||||||
|
- If you have issues or suggestions of improvements to NetDaemon,
|
||||||
|
please [add an issue](https://github.com/net-daemon/netdaemon/issues)
|
||||||
|
|
||||||
## Discuss the NetDaemon
|
## Discuss the NetDaemon
|
||||||
|
|
||||||
Please [join the Discord server](https://discord.gg/K3xwfcX) to get support or if you want to contribute and help others.
|
Please [join the Discord server](https://discord.gg/K3xwfcX) to get support or if you want to contribute and help
|
||||||
|
others.
|
||||||
|
|||||||
@@ -1,24 +1,11 @@
|
|||||||
{
|
{
|
||||||
"Serilog": {
|
"Serilog": {
|
||||||
"MinimumLevel": {
|
"MinimumLevel": {
|
||||||
"Default": "Warning",
|
"Default": "Warning"
|
||||||
"Override": {
|
|
||||||
"System.Net.Http.HttpClient": "Warning",
|
|
||||||
"NordPoolManager": "Information",
|
|
||||||
"PowerMonitorManager": "Information",
|
|
||||||
"BoilerMonitorManager": "Information",
|
|
||||||
"ShowerMonitorManager": "Information",
|
|
||||||
"LightMonitorManager": "Information",
|
|
||||||
"BatteryMonitorManager": "Information"
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
"WriteTo": [
|
"WriteTo": [
|
||||||
{
|
{
|
||||||
"Name": "Console",
|
"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}"
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -28,7 +15,7 @@
|
|||||||
"CodeGeneration": {
|
"CodeGeneration": {
|
||||||
"Namespace": "HomeAssistantGenerated",
|
"Namespace": "HomeAssistantGenerated",
|
||||||
"OutputFile": "HomeAssistantGenerated.cs",
|
"OutputFile": "HomeAssistantGenerated.cs",
|
||||||
"UseAttributeBaseClasses" : "false"
|
"UseAttributeBaseClasses": "false"
|
||||||
},
|
},
|
||||||
"NordPool": {
|
"NordPool": {
|
||||||
"CleanupEntitiesOnStartup": false
|
"CleanupEntitiesOnStartup": false
|
||||||
@@ -44,7 +31,7 @@
|
|||||||
"MainHomeHumidityEntityId": "sensor.main_home_humidity",
|
"MainHomeHumidityEntityId": "sensor.main_home_humidity",
|
||||||
"BathroomTemperatureEntityId": "sensor.bathroom_temperature",
|
"BathroomTemperatureEntityId": "sensor.bathroom_temperature",
|
||||||
"ExhaustFanEntityId": "switch.exhaust_fan",
|
"ExhaustFanEntityId": "switch.exhaust_fan",
|
||||||
"PollIntervalSeconds": 30,
|
"PollIntervalSeconds": 5,
|
||||||
"SpikeRateThreshold": 4.0,
|
"SpikeRateThreshold": 4.0,
|
||||||
"MinDifferentialHumidity": 8.0,
|
"MinDifferentialHumidity": 8.0,
|
||||||
"PeakHumidityThreshold": 58.0,
|
"PeakHumidityThreshold": 58.0,
|
||||||
@@ -58,18 +45,40 @@
|
|||||||
"Enabled": true,
|
"Enabled": true,
|
||||||
"LightEntityId": "light.sonoff_1002214d40",
|
"LightEntityId": "light.sonoff_1002214d40",
|
||||||
"SunEntityId": "sun.sun",
|
"SunEntityId": "sun.sun",
|
||||||
"PersonEntityIds": ["person.marius", "person.erika", "person.home_phone"]
|
"PersonEntityIds": [
|
||||||
|
"person.marius",
|
||||||
|
"person.erika"
|
||||||
|
]
|
||||||
},
|
},
|
||||||
"BatteryMonitor": {
|
"BatteryMonitor": {
|
||||||
"Enabled": true,
|
"Enabled": true,
|
||||||
"BatteryThresholdPercent": 5
|
"BatteryThresholdPercent": 5
|
||||||
},
|
},
|
||||||
|
"LeakMonitor": {
|
||||||
|
"Enabled": true,
|
||||||
|
"SensorEntityIds": [
|
||||||
|
"binary_sensor.aquarium_leak_sensor",
|
||||||
|
"binary_sensor.boiler_moisture"
|
||||||
|
],
|
||||||
|
"NotificationCooldownMinutes": 5
|
||||||
|
},
|
||||||
"PowerMonitor": {
|
"PowerMonitor": {
|
||||||
"Enabled": false,
|
"Enabled": false,
|
||||||
"MainMeterEntityId": "sensor.sonoff_100267d63f_power",
|
"MainMeterEntityId": "sensor.sonoff_100267d63f_power",
|
||||||
"PollIntervalSeconds": 1,
|
"PollIntervalSeconds": 1,
|
||||||
"SmoothingWindowSize": 10,
|
"SmoothingWindowSize": 10,
|
||||||
"AnomalyThresholdWatts": 500,
|
"AnomalyThresholdWatts": 500,
|
||||||
|
"HighPowerThresholdWatts": 6000,
|
||||||
|
"EnforceLimitEnabled": false,
|
||||||
|
"PowerLimitWatts": 5500,
|
||||||
|
"RecoverySeconds": 600,
|
||||||
|
"LimitCooldownSeconds": 30,
|
||||||
|
"EnforceSwitchOffEntityIds": [
|
||||||
|
"switch.sonoff_1002230e32"
|
||||||
|
],
|
||||||
|
"PauseAndRestoreEntityIds": [
|
||||||
|
"switch.boilermonitor_auto_management"
|
||||||
|
],
|
||||||
"ExcludedSensorPatterns": [
|
"ExcludedSensorPatterns": [
|
||||||
"sensor.nordpool_*",
|
"sensor.nordpool_*",
|
||||||
"sensor.powermonitor_*"
|
"sensor.powermonitor_*"
|
||||||
|
|||||||
@@ -1,9 +1,20 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
using System;
|
using System;
|
||||||
using System.Reflection;
|
using System.Reflection;
|
||||||
|
using BatteryMonitorManager;
|
||||||
|
using BatteryMonitorManager.Models;
|
||||||
|
using BoilerMonitor.Models;
|
||||||
|
using BoilerMonitorManager;
|
||||||
|
using BoilerMonitorManager.Models;
|
||||||
using HomeAssistant.Entities;
|
using HomeAssistant.Entities;
|
||||||
using HomeAssistant.Entities.Interfaces;
|
using HomeAssistant.Entities.Interfaces;
|
||||||
using HomeAssistantGenerated;
|
using HomeAssistantGenerated;
|
||||||
using HomeAssistantServer;
|
using HomeAssistantServer;
|
||||||
|
using LeakMonitorManager;
|
||||||
|
using LeakMonitorManager.Models;
|
||||||
|
using LightMonitor.Models;
|
||||||
|
using LightMonitorManager;
|
||||||
using Mappings;
|
using Mappings;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using Microsoft.Extensions.Hosting;
|
using Microsoft.Extensions.Hosting;
|
||||||
@@ -12,51 +23,45 @@ using NetDaemon.Extensions.MqttEntityManager;
|
|||||||
using NetDaemon.Extensions.Scheduler;
|
using NetDaemon.Extensions.Scheduler;
|
||||||
using NetDaemon.Extensions.Tts;
|
using NetDaemon.Extensions.Tts;
|
||||||
using NetDaemon.Runtime;
|
using NetDaemon.Runtime;
|
||||||
using BoilerMonitorManager;
|
|
||||||
using BoilerMonitorManager.Models;
|
|
||||||
using NordPoolManager;
|
using NordPoolManager;
|
||||||
using NordPoolManager.Interface;
|
|
||||||
using NordPoolManager.Models;
|
using NordPoolManager.Models;
|
||||||
using PowerMonitorManager;
|
using PowerMonitorManager;
|
||||||
using PowerMonitorManager.Models;
|
using PowerMonitorManager.Models;
|
||||||
using ShowerMonitorManager;
|
using ShowerMonitorManager;
|
||||||
using ShowerMonitorManager.Models;
|
using ShowerMonitorManager.Models;
|
||||||
using LightMonitorManager;
|
|
||||||
using LightMonitorManager.Models;
|
|
||||||
using BatteryMonitorManager;
|
|
||||||
using BatteryMonitorManager.Models;
|
|
||||||
|
|
||||||
#pragma warning disable CA1812
|
#endregion
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
await Host.CreateDefaultBuilder(args)
|
var app = Host.CreateDefaultBuilder(args)
|
||||||
.UseNetDaemonAppSettings()
|
.UseNetDaemonAppSettings()
|
||||||
.UseCustomLogging()
|
.UseCustomLogging()
|
||||||
.UseNetDaemonRuntime()
|
.UseNetDaemonRuntime()
|
||||||
.UseNetDaemonTextToSpeech()
|
.UseNetDaemonTextToSpeech()
|
||||||
.ConfigureServices((context, services) =>
|
.ConfigureServices((context, services) =>
|
||||||
|
{
|
||||||
services
|
services
|
||||||
.AddNetDaemonMqttEntityManagement()
|
.AddNetDaemonMqttEntityManagement()
|
||||||
.AddAppsFromAssembly(Assembly.GetExecutingAssembly())
|
.AddAppsFromAssembly(Assembly.GetExecutingAssembly())
|
||||||
.AddNetDaemonStateManager()
|
.AddNetDaemonStateManager()
|
||||||
.AddNetDaemonScheduler()
|
.AddNetDaemonScheduler()
|
||||||
.AddHomeAssistantGenerated()
|
.AddHomeAssistantGenerated()
|
||||||
.AddNetDaemonApp<NordPoolInit>()
|
|
||||||
.AddAutoMapper(config =>
|
.AddAutoMapper(config =>
|
||||||
{
|
{
|
||||||
config.LicenseKey =
|
config.LicenseKey =
|
||||||
"eyJhbGciOiJSUzI1NiIsImtpZCI6Ikx1Y2t5UGVubnlTb2Z0d2FyZUxpY2Vuc2VLZXkvYmJiMTNhY2I1OTkwNGQ4OWI0Y2IxYzg1ZjA4OGNjZjkiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL2x1Y2t5cGVubnlzb2Z0d2FyZS5jb20iLCJhdWQiOiJMdWNreVBlbm55U29mdHdhcmUiLCJleHAiOiIxNzk1NDc4NDAwIiwiaWF0IjoiMTc2NDAwNTE3OSIsImFjY291bnRfaWQiOiIwMTlhYjZlNjFjZWM3ZjhhYWQzMjE4ZmQ0ODdkYTgwNiIsImN1c3RvbWVyX2lkIjoiY3RtXzAxa2F2ZWR3ZHJkNzg0dmZ6NWdqMmVuYzRmIiwic3ViX2lkIjoiLSIsImVkaXRpb24iOiIwIiwidHlwZSI6IjIifQ.n1iwRUZXd60e8zM5_242OERaBGi-ZxOVllchr1rfDlkl6iV0cpflZrT2cwpJSha7xYGJ9gfpe1JWATplQeX_RvvUM6ZxkS1BiJdZkCtu8cMLnXZ1Py6A-myFVLBJA06crl6DJkBa3yCGMsQUaoPQbg5AAxYzrx9JfjxArnyRC1HjI4_6ZMn0zxsaRXQAODF7yPo9TNrtyaQ75bLh3nv9ankzHJ6gibKIbNxiq9m-X_5ejd0NHXSst2ckTf5Eyfevv6Rmi45H_Ry5ePXxLdTNkdqHR6MqLbVZ8cpNBt69NajsBTodGy29UfZg0iiwB3s9ztnnobxvSM2KZ4-WsVKAYA";
|
"eyJhbGciOiJSUzI1NiIsImtpZCI6Ikx1Y2t5UGVubnlTb2Z0d2FyZUxpY2Vuc2VLZXkvYmJiMTNhY2I1OTkwNGQ4OWI0Y2IxYzg1ZjA4OGNjZjkiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL2x1Y2t5cGVubnlzb2Z0d2FyZS5jb20iLCJhdWQiOiJMdWNreVBlbm55U29mdHdhcmUiLCJleHAiOiIxODMwMDM4NDAwIiwiaWF0IjoiMTc2NDAwNTE3OSIsImFjY291bnRfaWQiOiIwMTlhYjZlNjFjZWM3ZjhhYWQzMjE4ZmQ0ODdkYTgwNiIsImN1c3RvbWVyX2lkIjoiMDE5YWI2ZTYxY2VjN2Y4YWFkMzIxOGZkNDg3ZGE4MDYiLCJzdWJfaWQiOiItIiwiZWRpdGlvbiI6IjAiLCJ0eXBlIjoiMiIsInRlcm1fZW5kIjoiMTgyNzQ0NjQwMCJ9.VgEgdxh9xBudubLZr90mUiCORAhLx00Fz7lw1bUMhLWICjBposFrBWrgccKb_irFis_6qUyi567VbsmbjTDxAp9-f0QI0VW4_Zr9wcNeCrDzE0U-DKdcWoMpHoJYUf62tMscGcgVJEKgMX27KLWWqAQzcJm8X-O072A7pW1_x_xkAorFOIfahKXdECnUUdHpPUdrClUbxfWS-wkkKBP0AnrnYY1N2FGlqsJj5_ro1Mmcpijx0sxUKSl1FKaHmx6pOHq-rvJEF7Vvi35vO4HQYFnyP-hN2fQSkgK-Eg8LG6BqBLDXK33VlI6WMO0nOUG62KWAI7jXPSZhrSjBZfxy0g";
|
||||||
|
|
||||||
config.AddProfile<NordPoolMappingProfile>();
|
config.AddProfile<NordPoolMappingProfile>();
|
||||||
config.AddProfile<GlobalMappingProfile>();
|
config.AddProfile<GlobalMappingProfile>();
|
||||||
})
|
})
|
||||||
.AddTransient<IEntityManager, EntityManager>()
|
.AddTransient<IEntityManager, EntityManager>()
|
||||||
|
.AddSingleton(TimeProvider.System)
|
||||||
|
.AddScoped<IBoilerConfigReader, BoilerConfigReader>()
|
||||||
.Configure<NordPoolOptions>(context.Configuration.GetSection(NordPoolOptions.SectionName))
|
.Configure<NordPoolOptions>(context.Configuration.GetSection(NordPoolOptions.SectionName))
|
||||||
.AddScoped<INordPoolPriceService, NordPoolPriceService>()
|
.AddNordPool()
|
||||||
.AddTransient<INordPoolEntityService, NordPoolEntityService>()
|
|
||||||
.AddSingleton<ICheapestIntervalsFinder, CheapestIntervalsFinder>()
|
|
||||||
.Configure<PowerMonitorOptions>(context.Configuration.GetSection(PowerMonitorOptions.SectionName))
|
.Configure<PowerMonitorOptions>(context.Configuration.GetSection(PowerMonitorOptions.SectionName))
|
||||||
.AddPowerMonitor(context.Configuration)
|
.AddPowerMonitor()
|
||||||
.Configure<BoilerMonitorOptions>(context.Configuration.GetSection(BoilerMonitorOptions.SectionName))
|
.Configure<BoilerMonitorOptions>(context.Configuration.GetSection(BoilerMonitorOptions.SectionName))
|
||||||
.AddBoilerMonitor(context.Configuration)
|
.AddBoilerMonitor(context.Configuration)
|
||||||
.Configure<ShowerMonitorOptions>(context.Configuration.GetSection(ShowerMonitorOptions.SectionName))
|
.Configure<ShowerMonitorOptions>(context.Configuration.GetSection(ShowerMonitorOptions.SectionName))
|
||||||
@@ -65,10 +70,12 @@ try
|
|||||||
.AddLightMonitor(context.Configuration)
|
.AddLightMonitor(context.Configuration)
|
||||||
.Configure<BatteryMonitorOptions>(context.Configuration.GetSection(BatteryMonitorOptions.SectionName))
|
.Configure<BatteryMonitorOptions>(context.Configuration.GetSection(BatteryMonitorOptions.SectionName))
|
||||||
.AddBatteryMonitor(context.Configuration)
|
.AddBatteryMonitor(context.Configuration)
|
||||||
)
|
.Configure<LeakMonitorOptions>(context.Configuration.GetSection(LeakMonitorOptions.SectionName))
|
||||||
.Build()
|
.AddLeakMonitor(context.Configuration);
|
||||||
.RunAsync()
|
})
|
||||||
.ConfigureAwait(false);
|
.Build();
|
||||||
|
|
||||||
|
await app.RunAsync().ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
|
|||||||
+57
-28
@@ -30,8 +30,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Testing", "Testing", "{95E9
|
|||||||
EndProject
|
EndProject
|
||||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Models", "Models", "{48492269-2B47-43FE-BC14-A901054EE5AE}"
|
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Models", "Models", "{48492269-2B47-43FE-BC14-A901054EE5AE}"
|
||||||
EndProject
|
EndProject
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HomeAssistant.McpServer", "HomeAssistant.McpServer\HomeAssistant.McpServer.csproj", "{AF78DBE2-9DDA-4ABD-934A-97DC9376D371}"
|
|
||||||
EndProject
|
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ShowerMonitor.Models", "ShowerMonitor.Models\ShowerMonitor.Models.csproj", "{DAD0BDF9-2A6D-48AD-B714-38D237E97285}"
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ShowerMonitor.Models", "ShowerMonitor.Models\ShowerMonitor.Models.csproj", "{DAD0BDF9-2A6D-48AD-B714-38D237E97285}"
|
||||||
EndProject
|
EndProject
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ShowerMonitor.Manager", "ShowerMonitor.Manager\ShowerMonitor.Manager.csproj", "{8D05B406-B94B-4D6B-8221-831485AF6702}"
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ShowerMonitor.Manager", "ShowerMonitor.Manager\ShowerMonitor.Manager.csproj", "{8D05B406-B94B-4D6B-8221-831485AF6702}"
|
||||||
@@ -44,14 +42,20 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LightMonitor.Manager", "Lig
|
|||||||
EndProject
|
EndProject
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LightMonitor.Manager.Tests", "LightMonitor.Manager.Tests\LightMonitor.Manager.Tests.csproj", "{B8303C3E-785C-48F0-8F40-D4A9E9D50C92}"
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LightMonitor.Manager.Tests", "LightMonitor.Manager.Tests\LightMonitor.Manager.Tests.csproj", "{B8303C3E-785C-48F0-8F40-D4A9E9D50C92}"
|
||||||
EndProject
|
EndProject
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HomeAssistant.HistoryReplay", "HomeAssistant.HistoryReplay\HomeAssistant.HistoryReplay.csproj", "{EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}"
|
|
||||||
EndProject
|
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BatteryMonitor.Models", "BatteryMonitor.Models\BatteryMonitor.Models.csproj", "{2D27B621-7B92-4014-8FDF-6AD376C97612}"
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BatteryMonitor.Models", "BatteryMonitor.Models\BatteryMonitor.Models.csproj", "{2D27B621-7B92-4014-8FDF-6AD376C97612}"
|
||||||
EndProject
|
EndProject
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BatteryMonitor.Manager", "BatteryMonitor.Manager\BatteryMonitor.Manager.csproj", "{C844BDD9-584D-4D72-8EDE-AEB3E7429FC1}"
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BatteryMonitor.Manager", "BatteryMonitor.Manager\BatteryMonitor.Manager.csproj", "{C844BDD9-584D-4D72-8EDE-AEB3E7429FC1}"
|
||||||
EndProject
|
EndProject
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BatteryMonitor.Manager.Tests", "BatteryMonitor.Manager.Tests\BatteryMonitor.Manager.Tests.csproj", "{2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0}"
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BatteryMonitor.Manager.Tests", "BatteryMonitor.Manager.Tests\BatteryMonitor.Manager.Tests.csproj", "{2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0}"
|
||||||
EndProject
|
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
|
||||||
|
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Managers", "Managers", "{785A4330-F9E1-457E-9080-0F77BC4BC67F}"
|
||||||
|
EndProject
|
||||||
Global
|
Global
|
||||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||||
Debug|Any CPU = Debug|Any CPU
|
Debug|Any CPU = Debug|Any CPU
|
||||||
@@ -218,18 +222,6 @@ Global
|
|||||||
{CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Release|x64.Build.0 = Release|Any CPU
|
{CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Release|x64.Build.0 = Release|Any CPU
|
||||||
{CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Release|x86.ActiveCfg = Release|Any CPU
|
{CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
{CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Release|x86.Build.0 = Release|Any CPU
|
{CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Release|x86.Build.0 = Release|Any CPU
|
||||||
{AF78DBE2-9DDA-4ABD-934A-97DC9376D371}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
|
||||||
{AF78DBE2-9DDA-4ABD-934A-97DC9376D371}.Debug|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.ActiveCfg = Debug|Any CPU
|
||||||
{DAD0BDF9-2A6D-48AD-B714-38D237E97285}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
{DAD0BDF9-2A6D-48AD-B714-38D237E97285}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
{DAD0BDF9-2A6D-48AD-B714-38D237E97285}.Debug|x64.ActiveCfg = Debug|Any CPU
|
{DAD0BDF9-2A6D-48AD-B714-38D237E97285}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||||
@@ -302,18 +294,6 @@ Global
|
|||||||
{B8303C3E-785C-48F0-8F40-D4A9E9D50C92}.Release|x64.Build.0 = Release|Any CPU
|
{B8303C3E-785C-48F0-8F40-D4A9E9D50C92}.Release|x64.Build.0 = Release|Any CPU
|
||||||
{B8303C3E-785C-48F0-8F40-D4A9E9D50C92}.Release|x86.ActiveCfg = Release|Any CPU
|
{B8303C3E-785C-48F0-8F40-D4A9E9D50C92}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
{B8303C3E-785C-48F0-8F40-D4A9E9D50C92}.Release|x86.Build.0 = Release|Any CPU
|
{B8303C3E-785C-48F0-8F40-D4A9E9D50C92}.Release|x86.Build.0 = Release|Any CPU
|
||||||
{EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
|
||||||
{EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
|
||||||
{EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Debug|x64.ActiveCfg = Debug|Any CPU
|
|
||||||
{EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Debug|x64.Build.0 = Debug|Any CPU
|
|
||||||
{EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Debug|x86.ActiveCfg = Debug|Any CPU
|
|
||||||
{EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Debug|x86.Build.0 = Debug|Any CPU
|
|
||||||
{EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
|
||||||
{EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Release|Any CPU.Build.0 = Release|Any CPU
|
|
||||||
{EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Release|x64.ActiveCfg = Release|Any CPU
|
|
||||||
{EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Release|x64.Build.0 = Release|Any CPU
|
|
||||||
{EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Release|x86.ActiveCfg = Release|Any CPU
|
|
||||||
{EC46D52D-BDC2-44F6-A49C-3128D4F42FF9}.Release|x86.Build.0 = Release|Any CPU
|
|
||||||
{2D27B621-7B92-4014-8FDF-6AD376C97612}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
{2D27B621-7B92-4014-8FDF-6AD376C97612}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
{2D27B621-7B92-4014-8FDF-6AD376C97612}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
{2D27B621-7B92-4014-8FDF-6AD376C97612}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
{2D27B621-7B92-4014-8FDF-6AD376C97612}.Debug|x64.ActiveCfg = Debug|Any CPU
|
{2D27B621-7B92-4014-8FDF-6AD376C97612}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||||
@@ -350,6 +330,42 @@ Global
|
|||||||
{2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0}.Release|x64.Build.0 = Release|Any CPU
|
{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.ActiveCfg = Release|Any CPU
|
||||||
{2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0}.Release|x86.Build.0 = 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
|
EndGlobalSection
|
||||||
GlobalSection(SolutionProperties) = preSolution
|
GlobalSection(SolutionProperties) = preSolution
|
||||||
HideSolutionNode = FALSE
|
HideSolutionNode = FALSE
|
||||||
@@ -362,7 +378,20 @@ Global
|
|||||||
{1F613F65-5F3C-41E6-B86B-774301D80E42} = {95E98121-7DA4-4085-A8E3-B0430628452F}
|
{1F613F65-5F3C-41E6-B86B-774301D80E42} = {95E98121-7DA4-4085-A8E3-B0430628452F}
|
||||||
{72331F53-884D-42A1-8EEA-8CC83FFAB623} = {48492269-2B47-43FE-BC14-A901054EE5AE}
|
{72331F53-884D-42A1-8EEA-8CC83FFAB623} = {48492269-2B47-43FE-BC14-A901054EE5AE}
|
||||||
{CFF799B9-A8E7-46C8-B4FD-721B7308FA9C} = {95E98121-7DA4-4085-A8E3-B0430628452F}
|
{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}
|
{B14E51EB-7D5C-44FA-8674-4B4796459978} = {48492269-2B47-43FE-BC14-A901054EE5AE}
|
||||||
{B8303C3E-785C-48F0-8F40-D4A9E9D50C92} = {95E98121-7DA4-4085-A8E3-B0430628452F}
|
{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}
|
||||||
|
{C844BDD9-584D-4D72-8EDE-AEB3E7429FC1} = {785A4330-F9E1-457E-9080-0F77BC4BC67F}
|
||||||
|
{488964A2-C7A2-45C9-9CDB-98515AFD7242} = {785A4330-F9E1-457E-9080-0F77BC4BC67F}
|
||||||
|
{6830DB0A-9D94-4B52-A0A1-7593E4971FF7} = {785A4330-F9E1-457E-9080-0F77BC4BC67F}
|
||||||
|
{9165EDEF-2FE2-4578-849B-B4D4089416DA} = {785A4330-F9E1-457E-9080-0F77BC4BC67F}
|
||||||
|
{C7470849-2B14-4E4E-AE96-5A509CACA5AA} = {785A4330-F9E1-457E-9080-0F77BC4BC67F}
|
||||||
|
{4DEE2DDD-E964-48AF-B6C2-EF61152845BA} = {785A4330-F9E1-457E-9080-0F77BC4BC67F}
|
||||||
|
{8D05B406-B94B-4D6B-8221-831485AF6702} = {785A4330-F9E1-457E-9080-0F77BC4BC67F}
|
||||||
EndGlobalSection
|
EndGlobalSection
|
||||||
EndGlobal
|
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="10.1.1">
|
||||||
|
<PrivateAssets>all</PrivateAssets>
|
||||||
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
|
</PackageReference>
|
||||||
|
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.12.0"/>
|
||||||
|
<PackageReference Include="xunit" Version="2.9.3"/>
|
||||||
|
<PackageReference Include="xunit.runner.visualstudio" Version="4.0.1">
|
||||||
|
<PrivateAssets>all</PrivateAssets>
|
||||||
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
|
</PackageReference>
|
||||||
|
<PackageReference Include="FluentAssertions" Version="8.11.0"/>
|
||||||
|
<PackageReference Include="Moq" Version="4.21.0"/>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<Using Include="Xunit"/>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\LeakMonitor.Manager\LeakMonitor.Manager.csproj"/>
|
||||||
|
<ProjectReference Include="..\LeakMonitor.Models\LeakMonitor.Models.csproj"/>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user