Compare commits
25 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f919d6b25b | |||
| 77458383d1 | |||
| 24729ee267 | |||
| cf8c9434c8 | |||
| 41ac93733e | |||
| 17774b40b8 | |||
| ada3c77778 | |||
| b5e114be14 | |||
| 5777e641f6 | |||
| 1152462765 | |||
| f0bbd4f10b | |||
| f176a1b8fc | |||
| 2706a6b188 | |||
| 7f280bea7b | |||
| e6bf8258bb | |||
| 8f45028715 | |||
| 6e4d684359 | |||
| 11c2574235 | |||
| c4015277a3 | |||
| c9bf646f81 | |||
| a14fb65be3 | |||
| 4a8eb30304 | |||
| 4c6b6938e8 | |||
| cd5f9d0352 | |||
| 411611215a |
@@ -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.
|
||||||
+12
-3
@@ -105,6 +105,15 @@ UpgradeLog*.htm
|
|||||||
ServiceFabricBackup/
|
ServiceFabricBackup/
|
||||||
*.rptproj.bak
|
*.rptproj.bak
|
||||||
|
|
||||||
# Sensitive / local config (uncomment if you use appsettings.local.json etc.)
|
# Sensitive / local config
|
||||||
# appsettings.*.local.json
|
appsettings.Development.json
|
||||||
# *.local.json
|
appsettings.*.local.json
|
||||||
|
*.local.json
|
||||||
|
|
||||||
|
# Home Assistant long-lived tokens / per-user override files
|
||||||
|
appsettings.development.json
|
||||||
|
appsettings.Production.json
|
||||||
|
appsettings.production.json
|
||||||
|
|
||||||
|
# Cursor MCP config (contains secrets)
|
||||||
|
.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"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Vendored
+7
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
// Use IntelliSense to learn about possible attributes.
|
||||||
|
// Hover to view descriptions of existing attributes.
|
||||||
|
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
|
||||||
|
"version": "0.2.0",
|
||||||
|
"configurations": []
|
||||||
|
}
|
||||||
@@ -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.
|
||||||
@@ -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="..\BatteryMonitor.Manager\BatteryMonitor.Manager.csproj"/>
|
||||||
|
<ProjectReference Include="..\BatteryMonitor.Models\BatteryMonitor.Models.csproj"/>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,294 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using System.Text.Json;
|
||||||
|
using BatteryMonitor.Models;
|
||||||
|
using BatteryMonitorManager;
|
||||||
|
using FluentAssertions;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Moq;
|
||||||
|
using NetDaemon.HassModel;
|
||||||
|
using NetDaemon.HassModel.Entities;
|
||||||
|
using static BatteryMonitor.Manager.Tests.BatteryMonitorTestData;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace BatteryMonitor.Manager.Tests;
|
||||||
|
|
||||||
|
public class BatteryNotificationServiceTests
|
||||||
|
{
|
||||||
|
private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
|
||||||
|
private readonly Mock<ILogger<BatteryNotificationService>> _loggerMock = new Mock<ILogger<BatteryNotificationService>>();
|
||||||
|
|
||||||
|
private BatteryNotificationService CreateSut()
|
||||||
|
{
|
||||||
|
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
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(NotifyDeviceCounts), MemberType = typeof(BatteryMonitorTestData))]
|
||||||
|
public void NotifyLowBattery_WithDevices_ShouldCallPersistentNotificationCreate(int deviceCount)
|
||||||
|
{
|
||||||
|
var devices = CreateSensorInfos(
|
||||||
|
[
|
||||||
|
.. Enumerable.Range(0, deviceCount)
|
||||||
|
.Select(i => ($"sensor.device_{i:D3}", $"Device {i:D3}", (double)(i % 5)))
|
||||||
|
]);
|
||||||
|
|
||||||
|
var sut = CreateSut();
|
||||||
|
sut.NotifyLowBattery(devices);
|
||||||
|
|
||||||
|
VerifyCallService(BatteryMonitorConsts.PersistentNotificationCreateService, Times.Once());
|
||||||
|
VerifyCallService(BatteryMonitorConsts.PersistentNotificationDismissService, Times.Never());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(false)]
|
||||||
|
[InlineData(true)]
|
||||||
|
public void NotifyLowBattery_WithEmptyList_ShouldNotCallService(bool useArray)
|
||||||
|
{
|
||||||
|
IReadOnlyList<BatterySensorInfo> devices = useArray
|
||||||
|
? Array.Empty<BatterySensorInfo>()
|
||||||
|
: new List<BatterySensorInfo>();
|
||||||
|
|
||||||
|
var sut = CreateSut();
|
||||||
|
sut.NotifyLowBattery(devices);
|
||||||
|
|
||||||
|
_haContextMock.Verify(h => h.CallService(
|
||||||
|
It.IsAny<string>(),
|
||||||
|
It.IsAny<string>(),
|
||||||
|
It.IsAny<ServiceTarget?>(),
|
||||||
|
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
|
||||||
|
|
||||||
|
#region DismissNotification
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void DismissNotification_ShouldCallPersistentNotificationDismiss()
|
||||||
|
{
|
||||||
|
var sut = CreateSut();
|
||||||
|
sut.DismissNotification();
|
||||||
|
|
||||||
|
VerifyCallService(BatteryMonitorConsts.PersistentNotificationDismissService, Times.Once());
|
||||||
|
VerifyCallService(BatteryMonitorConsts.PersistentNotificationCreateService, Times.Never());
|
||||||
|
}
|
||||||
|
|
||||||
|
[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
|
||||||
|
|
||||||
|
#region BuildNotificationMessage
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void BuildNotificationMessage_ShouldOrderByBatteryLevel()
|
||||||
|
{
|
||||||
|
var devices = CreateSensorInfos(
|
||||||
|
("sensor.a", "Device A", 4),
|
||||||
|
("sensor.b", "Device B", 1),
|
||||||
|
("sensor.c", "Device C", 3));
|
||||||
|
|
||||||
|
var message = BatteryNotificationService.BuildNotificationMessage(devices);
|
||||||
|
|
||||||
|
var lines = message.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries);
|
||||||
|
lines.Should().HaveCount(4);
|
||||||
|
lines[1].Should().Contain("Device B");
|
||||||
|
lines[2].Should().Contain("Device C");
|
||||||
|
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]
|
||||||
|
public void BuildNotificationMessage_ShouldContainTitle()
|
||||||
|
{
|
||||||
|
var devices = CreateSensorInfos(("sensor.a", "Device A", 2));
|
||||||
|
|
||||||
|
var message = BatteryNotificationService.BuildNotificationMessage(devices);
|
||||||
|
|
||||||
|
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]
|
||||||
|
public void BuildNotificationMessage_ShouldContainDeviceNameAndLevel()
|
||||||
|
{
|
||||||
|
var devices = CreateSensorInfos(("sensor.a", "Bathroom Battery", 3));
|
||||||
|
|
||||||
|
var message = BatteryNotificationService.BuildNotificationMessage(devices);
|
||||||
|
|
||||||
|
message.Should().Contain("Bathroom Battery");
|
||||||
|
message.Should().Contain("3%");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void BuildNotificationMessage_WithSingleDevice_ShouldFormatCorrectly()
|
||||||
|
{
|
||||||
|
var devices = CreateSensorInfos(("sensor.a", "Test Device", 1));
|
||||||
|
|
||||||
|
var message = BatteryNotificationService.BuildNotificationMessage(devices);
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
@@ -0,0 +1,304 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using System.Globalization;
|
||||||
|
using BatteryMonitor.Models;
|
||||||
|
using BatteryMonitorManager;
|
||||||
|
using FluentAssertions;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Moq;
|
||||||
|
using NetDaemon.HassModel;
|
||||||
|
using NetDaemon.HassModel.Entities;
|
||||||
|
using static BatteryMonitor.Manager.Tests.BatteryMonitorTestData;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace BatteryMonitor.Manager.Tests;
|
||||||
|
|
||||||
|
public class BatterySensorDiscoveryServiceTests
|
||||||
|
{
|
||||||
|
private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
|
||||||
|
private readonly Mock<ILogger<BatterySensorDiscoveryService>> _loggerMock = new Mock<ILogger<BatterySensorDiscoveryService>>();
|
||||||
|
|
||||||
|
private BatterySensorDiscoveryService CreateSut()
|
||||||
|
{
|
||||||
|
return new BatterySensorDiscoveryService(_haContextMock.Object, _loggerMock.Object);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void SetupEntities(params EntitySpec[] entities)
|
||||||
|
{
|
||||||
|
ConfigureHaContext(_haContextMock, entities);
|
||||||
|
}
|
||||||
|
|
||||||
|
#region IsExcludedDevice
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(ExcludedEntityIdRows), MemberType = typeof(BatteryMonitorTestData))]
|
||||||
|
public void IsExcludedDevice_ShouldCorrectlyIdentifyExclusions(string entityId, bool expected)
|
||||||
|
{
|
||||||
|
BatterySensorDiscoveryService.IsExcludedDevice(entityId).Should().Be(expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region Discovery
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void DiscoverLowBatterySensors_ShouldFindLowBatteryDevices()
|
||||||
|
{
|
||||||
|
SetupEntities(
|
||||||
|
Battery("sensor.bathroom_battery", "3", "Bathroom Battery"),
|
||||||
|
Battery("sensor.bedroom_battery", "80", "Bedroom Battery"),
|
||||||
|
Battery("sensor.boiler_temp_battery", "2", "Boiler Temp Battery")
|
||||||
|
);
|
||||||
|
|
||||||
|
var sut = CreateSut();
|
||||||
|
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
||||||
|
|
||||||
|
result.Should().HaveCount(2);
|
||||||
|
result.Should().Contain(s => s.EntityId == "sensor.bathroom_battery");
|
||||||
|
result.Should().Contain(s => s.EntityId == "sensor.boiler_temp_battery");
|
||||||
|
result.Select(s => s.EntityId).Should().NotContain("sensor.bedroom_battery");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[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(
|
||||||
|
Battery("sensor.bathroom_battery", "2", "Bathroom Battery"),
|
||||||
|
Battery(excludedEntityId, "1", friendlyName)
|
||||||
|
);
|
||||||
|
|
||||||
|
var sut = CreateSut();
|
||||||
|
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
||||||
|
|
||||||
|
result.Should().ContainSingle();
|
||||||
|
result[0].EntityId.Should().Be("sensor.bathroom_battery");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[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(
|
||||||
|
Sensor(entityId, deviceClass, "2", "Ignored Entity"),
|
||||||
|
Battery("sensor.bedroom_battery", "3", "Bedroom Battery")
|
||||||
|
);
|
||||||
|
|
||||||
|
var sut = CreateSut();
|
||||||
|
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
||||||
|
|
||||||
|
result.Should().ContainSingle();
|
||||||
|
result[0].EntityId.Should().Be("sensor.bedroom_battery");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(UnusableStateRows), MemberType = typeof(BatteryMonitorTestData))]
|
||||||
|
public void DiscoverLowBatterySensors_ShouldSkipUnusableStates(string? state)
|
||||||
|
{
|
||||||
|
SetupEntities(
|
||||||
|
Battery("sensor.bathroom_battery", state, "Bathroom Battery"),
|
||||||
|
Battery("sensor.bedroom_battery", "3", "Bedroom Battery")
|
||||||
|
);
|
||||||
|
|
||||||
|
var sut = CreateSut();
|
||||||
|
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
||||||
|
|
||||||
|
result.Should().ContainSingle();
|
||||||
|
result[0].EntityId.Should().Be("sensor.bedroom_battery");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void DiscoverLowBatterySensors_WhenEntityStateIsNull_ShouldSkipSensor()
|
||||||
|
{
|
||||||
|
SetupEntities(
|
||||||
|
new EntitySpec
|
||||||
|
{ EntityId = "sensor.bathroom_battery", FriendlyName = "Bathroom Battery", HasState = false },
|
||||||
|
Battery("sensor.bedroom_battery", "3", "Bedroom Battery")
|
||||||
|
);
|
||||||
|
|
||||||
|
var sut = CreateSut();
|
||||||
|
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
||||||
|
|
||||||
|
result.Should().ContainSingle();
|
||||||
|
result[0].EntityId.Should().Be("sensor.bedroom_battery");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(ThresholdBoundaryRows), MemberType = typeof(BatteryMonitorTestData))]
|
||||||
|
public void DiscoverLowBatterySensors_ShouldApplyStrictThresholdBoundary(int thresholdPercent,
|
||||||
|
string state,
|
||||||
|
bool expectedIncluded)
|
||||||
|
{
|
||||||
|
SetupEntities(Battery("sensor.boundary_battery", state, "Boundary Battery"));
|
||||||
|
|
||||||
|
var sut = CreateSut();
|
||||||
|
var result = sut.DiscoverLowBatterySensors(thresholdPercent);
|
||||||
|
|
||||||
|
result.Should().HaveCount(expectedIncluded ? 1 : 0);
|
||||||
|
|
||||||
|
if (!expectedIncluded)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
result[0].EntityId.Should().Be("sensor.boundary_battery");
|
||||||
|
result[0].BatteryLevel.Should().Be(double.Parse(state, CultureInfo.InvariantCulture));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void DiscoverLowBatterySensors_WhenNoBatterySensors_ShouldReturnEmpty()
|
||||||
|
{
|
||||||
|
SetupEntities(
|
||||||
|
Sensor("sensor.temperature", "temperature", "22", "Temperature"),
|
||||||
|
Sensor("switch.some_switch", null, "on", "Switch")
|
||||||
|
);
|
||||||
|
|
||||||
|
var sut = CreateSut();
|
||||||
|
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
||||||
|
|
||||||
|
result.Should().BeEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void DiscoverLowBatterySensors_WhenAllAboveThreshold_ShouldReturnEmpty()
|
||||||
|
{
|
||||||
|
SetupEntities(
|
||||||
|
Battery("sensor.bathroom_battery", "5", "Bathroom Battery"),
|
||||||
|
Battery("sensor.bedroom_battery", "50", "Bedroom Battery"),
|
||||||
|
Battery("sensor.boiler_temp_battery", "100", "Boiler Temp Battery")
|
||||||
|
);
|
||||||
|
|
||||||
|
var sut = CreateSut();
|
||||||
|
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
||||||
|
|
||||||
|
result.Should().BeEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void DiscoverLowBatterySensors_WhenThereAreNoEntities_ShouldReturnEmpty()
|
||||||
|
{
|
||||||
|
SetupEntities();
|
||||||
|
|
||||||
|
var sut = CreateSut();
|
||||||
|
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
||||||
|
|
||||||
|
result.Should().NotBeNull();
|
||||||
|
result.Should().BeEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void DiscoverLowBatterySensors_WithDuplicateSensorIds_ShouldReportEachOccurrence()
|
||||||
|
{
|
||||||
|
SetupEntities(
|
||||||
|
Battery("sensor.duplicate_battery", "2", "Duplicate Battery"),
|
||||||
|
Battery("sensor.duplicate_battery", "2", "Duplicate Battery")
|
||||||
|
);
|
||||||
|
|
||||||
|
var sut = CreateSut();
|
||||||
|
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
||||||
|
|
||||||
|
result.Should().HaveCount(2);
|
||||||
|
result.Should().OnlyContain(s => s.EntityId == "sensor.duplicate_battery");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("Bathroom Battery", "Bathroom Battery")]
|
||||||
|
[InlineData("", "")]
|
||||||
|
[InlineData(" ", " ")]
|
||||||
|
[InlineData(null, "sensor.bathroom_battery")]
|
||||||
|
public void DiscoverLowBatterySensors_ShouldResolveFriendlyName(string? friendlyName, string expectedFriendlyName)
|
||||||
|
{
|
||||||
|
SetupEntities(Battery("sensor.bathroom_battery", "2", friendlyName));
|
||||||
|
|
||||||
|
var sut = CreateSut();
|
||||||
|
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
||||||
|
|
||||||
|
result.Should().ContainSingle();
|
||||||
|
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
|
||||||
|
|
||||||
|
#region IsBatterySensor
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[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(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");
|
||||||
|
|
||||||
|
BatterySensorDiscoveryService.IsBatterySensor(entity).Should().BeFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<RootNamespace>BatteryMonitorManager</RootNamespace>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
|
||||||
|
<_Parameter1>BatteryMonitor.Manager.Tests</_Parameter1>
|
||||||
|
</AssemblyAttribute>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\HomeAssistant.Entities\HomeAssistant.Entities.csproj"/>
|
||||||
|
<ProjectReference Include="..\BatteryMonitor.Models\BatteryMonitor.Models.csproj"/>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="11.0.0"/>
|
||||||
|
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.43.1"/>
|
||||||
|
<PackageReference Include="NetDaemon.HassModel" Version="26.43.1"/>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using System.Reactive.Concurrency;
|
||||||
|
using BatteryMonitor.Models;
|
||||||
|
using BatteryMonitorManager.Interface;
|
||||||
|
using BatteryMonitorManager.Models;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
using NetDaemon.AppModel;
|
||||||
|
using NetDaemon.Extensions.Scheduler;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace BatteryMonitorManager;
|
||||||
|
|
||||||
|
[NetDaemonApp]
|
||||||
|
public sealed class BatteryMonitorInit
|
||||||
|
{
|
||||||
|
private readonly IBatterySensorDiscoveryService _discoveryService;
|
||||||
|
private readonly ILogger<BatteryMonitorInit> _logger;
|
||||||
|
private readonly IBatteryNotificationService _notificationService;
|
||||||
|
private readonly BatteryMonitorOptions _options;
|
||||||
|
private readonly IScheduler _scheduler;
|
||||||
|
|
||||||
|
public BatteryMonitorInit(
|
||||||
|
ILogger<BatteryMonitorInit> logger,
|
||||||
|
IScheduler scheduler,
|
||||||
|
IBatterySensorDiscoveryService discoveryService,
|
||||||
|
IBatteryNotificationService notificationService,
|
||||||
|
IOptions<BatteryMonitorOptions> options)
|
||||||
|
{
|
||||||
|
_logger = logger;
|
||||||
|
_scheduler = scheduler;
|
||||||
|
_discoveryService = discoveryService;
|
||||||
|
_notificationService = notificationService;
|
||||||
|
_options = options.Value;
|
||||||
|
|
||||||
|
_ = InitializeAndScheduleAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task InitializeAndScheduleAsync()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await InitializeAsync();
|
||||||
|
ScheduleDailyCheck();
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error during BatteryMonitor initialization and scheduling");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task InitializeAsync()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await Task.Delay(TimeSpan.FromSeconds(3));
|
||||||
|
|
||||||
|
CheckAndNotify();
|
||||||
|
|
||||||
|
if (_logger.IsEnabled(LogLevel.Information))
|
||||||
|
{
|
||||||
|
_logger.LogInformation("BatteryMonitor initialized with threshold {Threshold}%",
|
||||||
|
_options.BatteryThresholdPercent);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error initializing BatteryMonitor");
|
||||||
|
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ScheduleDailyCheck()
|
||||||
|
{
|
||||||
|
_scheduler.ScheduleCron(BatteryMonitorConsts.DailyCheckCron, () =>
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
_logger.LogInformation("Running scheduled daily battery check");
|
||||||
|
CheckAndNotify();
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error during scheduled battery check");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
_logger.LogInformation("Scheduled daily battery check at 08:00");
|
||||||
|
}
|
||||||
|
|
||||||
|
private void CheckAndNotify()
|
||||||
|
{
|
||||||
|
var lowBatteryDevices = _discoveryService.DiscoverLowBatterySensors(_options.BatteryThresholdPercent);
|
||||||
|
|
||||||
|
if (lowBatteryDevices.Count > 0)
|
||||||
|
{
|
||||||
|
_notificationService.NotifyLowBattery(lowBatteryDevices);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_notificationService.DismissNotification();
|
||||||
|
_logger.LogDebug("No low battery devices found");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using BatteryMonitorManager.Interface;
|
||||||
|
using BatteryMonitorManager.Models;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using NetDaemon.AppModel;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace BatteryMonitorManager;
|
||||||
|
|
||||||
|
public static class BatteryMonitorServiceRegistration
|
||||||
|
{
|
||||||
|
public static IServiceCollection AddBatteryMonitor(this IServiceCollection services, IConfiguration configuration)
|
||||||
|
{
|
||||||
|
var options = configuration
|
||||||
|
.GetSection(BatteryMonitorOptions.SectionName)
|
||||||
|
.Get<BatteryMonitorOptions>() ??
|
||||||
|
new BatteryMonitorOptions();
|
||||||
|
|
||||||
|
if (!options.Enabled)
|
||||||
|
{
|
||||||
|
return services;
|
||||||
|
}
|
||||||
|
|
||||||
|
services
|
||||||
|
.AddNetDaemonApp<BatteryMonitorInit>()
|
||||||
|
.AddScoped<IBatterySensorDiscoveryService, BatterySensorDiscoveryService>()
|
||||||
|
.AddScoped<IBatteryNotificationService, BatteryNotificationService>();
|
||||||
|
|
||||||
|
return services;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using System.Text;
|
||||||
|
using BatteryMonitor.Models;
|
||||||
|
using BatteryMonitorManager.Interface;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using NetDaemon.HassModel;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace BatteryMonitorManager;
|
||||||
|
|
||||||
|
public sealed class BatteryNotificationService(
|
||||||
|
IHaContext haContext,
|
||||||
|
ILogger<BatteryNotificationService> logger) : IBatteryNotificationService
|
||||||
|
{
|
||||||
|
public void NotifyLowBattery(IReadOnlyList<BatterySensorInfo> lowBatteryDevices)
|
||||||
|
{
|
||||||
|
if (lowBatteryDevices.Count == 0)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var message = BuildNotificationMessage(lowBatteryDevices);
|
||||||
|
|
||||||
|
haContext.CallService(
|
||||||
|
BatteryMonitorConsts.PersistentNotificationDomain,
|
||||||
|
BatteryMonitorConsts.PersistentNotificationCreateService,
|
||||||
|
data: new
|
||||||
|
{
|
||||||
|
title = BatteryMonitorConsts.NotificationTitle,
|
||||||
|
message,
|
||||||
|
notification_id = BatteryMonitorConsts.NotificationId
|
||||||
|
});
|
||||||
|
|
||||||
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
|
{
|
||||||
|
logger.LogInformation(
|
||||||
|
"Sent low battery notification for {Count} device(s)",
|
||||||
|
lowBatteryDevices.Count);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void DismissNotification()
|
||||||
|
{
|
||||||
|
haContext.CallService(
|
||||||
|
BatteryMonitorConsts.PersistentNotificationDomain,
|
||||||
|
BatteryMonitorConsts.PersistentNotificationDismissService,
|
||||||
|
data: new
|
||||||
|
{
|
||||||
|
notification_id = BatteryMonitorConsts.NotificationId
|
||||||
|
});
|
||||||
|
|
||||||
|
logger.LogDebug("Dismissed low battery notification");
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static string BuildNotificationMessage(IReadOnlyList<BatterySensorInfo> devices)
|
||||||
|
{
|
||||||
|
var sb = new StringBuilder();
|
||||||
|
sb.AppendLine("The following devices have low battery:");
|
||||||
|
sb.AppendLine();
|
||||||
|
|
||||||
|
foreach (var device in devices.OrderBy(d => d.BatteryLevel))
|
||||||
|
{
|
||||||
|
sb.AppendLine($"- **{device.FriendlyName}**: {device.BatteryLevel:F0}%");
|
||||||
|
}
|
||||||
|
|
||||||
|
return sb.ToString().TrimEnd();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using System.Globalization;
|
||||||
|
using System.Text.Json;
|
||||||
|
using BatteryMonitor.Models;
|
||||||
|
using BatteryMonitorManager.Interface;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using NetDaemon.HassModel;
|
||||||
|
using NetDaemon.HassModel.Entities;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace BatteryMonitorManager;
|
||||||
|
|
||||||
|
public sealed class BatterySensorDiscoveryService(
|
||||||
|
IHaContext haContext,
|
||||||
|
ILogger<BatterySensorDiscoveryService> logger) : IBatterySensorDiscoveryService
|
||||||
|
{
|
||||||
|
public IReadOnlyList<BatterySensorInfo> DiscoverLowBatterySensors(int thresholdPercent)
|
||||||
|
{
|
||||||
|
var allEntities = haContext.GetAllEntities();
|
||||||
|
|
||||||
|
var lowBatterySensors = allEntities
|
||||||
|
.Where(IsBatterySensor)
|
||||||
|
.Where(e => !IsExcludedDevice(e.EntityId))
|
||||||
|
.Select(e => TryCreateSensorInfo(e, thresholdPercent))
|
||||||
|
.Where(info => info is not null)
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
|
{
|
||||||
|
logger.LogInformation(
|
||||||
|
"Battery check: found {Count} sensors below {Threshold}%",
|
||||||
|
lowBatterySensors.Count, thresholdPercent);
|
||||||
|
}
|
||||||
|
|
||||||
|
return lowBatterySensors!;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static bool IsBatterySensor(Entity entity)
|
||||||
|
{
|
||||||
|
if (!entity.EntityId.StartsWith(BatteryMonitorConsts.SensorDomainPrefix, StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
var deviceClass = GetJsonStringProperty(entity.EntityState?.AttributesJson, "device_class");
|
||||||
|
|
||||||
|
return string.Equals(deviceClass, BatteryMonitorConsts.BatteryDeviceClass, StringComparison.OrdinalIgnoreCase);
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static bool IsExcludedDevice(string entityId)
|
||||||
|
{
|
||||||
|
var lowerEntityId = entityId.ToLowerInvariant();
|
||||||
|
|
||||||
|
return BatteryMonitorConsts.ExcludedKeywords
|
||||||
|
.Any(keyword => lowerEntityId.Contains(keyword, StringComparison.OrdinalIgnoreCase));
|
||||||
|
}
|
||||||
|
|
||||||
|
private BatterySensorInfo? TryCreateSensorInfo(Entity entity, int thresholdPercent)
|
||||||
|
{
|
||||||
|
var state = entity.EntityState?.State;
|
||||||
|
|
||||||
|
if (state is null or "unavailable" or "unknown")
|
||||||
|
{
|
||||||
|
if (logger.IsEnabled(LogLevel.Debug))
|
||||||
|
{
|
||||||
|
logger.LogDebug("Skipping battery sensor {EntityId}: state is {State}", entity.EntityId,
|
||||||
|
state ?? "null");
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!double.TryParse(state, CultureInfo.InvariantCulture, out var batteryLevel))
|
||||||
|
{
|
||||||
|
if (logger.IsEnabled(LogLevel.Debug))
|
||||||
|
{
|
||||||
|
logger.LogDebug("Skipping battery sensor {EntityId}: unable to parse state '{State}'", entity.EntityId,
|
||||||
|
state);
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (batteryLevel >= thresholdPercent)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var friendlyName = GetJsonStringProperty(entity.EntityState?.AttributesJson, "friendly_name") ?? entity.EntityId;
|
||||||
|
|
||||||
|
return new BatterySensorInfo
|
||||||
|
{
|
||||||
|
EntityId = entity.EntityId,
|
||||||
|
FriendlyName = friendlyName,
|
||||||
|
BatteryLevel = batteryLevel
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string? GetJsonStringProperty(JsonElement? element, string propertyName)
|
||||||
|
{
|
||||||
|
if (element is null)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return element.Value.TryGetProperty(propertyName, out var value)
|
||||||
|
? value.GetString()
|
||||||
|
: null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using BatteryMonitor.Models;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace BatteryMonitorManager.Interface;
|
||||||
|
|
||||||
|
public interface IBatteryNotificationService
|
||||||
|
{
|
||||||
|
void NotifyLowBattery(IReadOnlyList<BatterySensorInfo> lowBatteryDevices);
|
||||||
|
|
||||||
|
void DismissNotification();
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using BatteryMonitor.Models;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace BatteryMonitorManager.Interface;
|
||||||
|
|
||||||
|
public interface IBatterySensorDiscoveryService
|
||||||
|
{
|
||||||
|
IReadOnlyList<BatterySensorInfo> DiscoverLowBatterySensors(int thresholdPercent);
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using BatteryMonitor.Models;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace BatteryMonitorManager.Models;
|
||||||
|
|
||||||
|
public sealed class BatteryMonitorOptions
|
||||||
|
{
|
||||||
|
public const string SectionName = "BatteryMonitor";
|
||||||
|
|
||||||
|
public bool Enabled { get; init; }
|
||||||
|
|
||||||
|
public int BatteryThresholdPercent { get; init; } = BatteryMonitorConsts.DefaultBatteryThresholdPercent;
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<RootNamespace>BatteryMonitor.Models</RootNamespace>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
namespace BatteryMonitor.Models;
|
||||||
|
|
||||||
|
public static class BatteryMonitorConsts
|
||||||
|
{
|
||||||
|
public const int DefaultBatteryThresholdPercent = 5;
|
||||||
|
|
||||||
|
public const string BatteryDeviceClass = "battery";
|
||||||
|
|
||||||
|
public const string SensorDomainPrefix = "sensor.";
|
||||||
|
|
||||||
|
public const string NotificationId = "battery_monitor_low_battery";
|
||||||
|
|
||||||
|
public const string NotificationTitle = "Low Battery Alert";
|
||||||
|
|
||||||
|
public const string PersistentNotificationDomain = "persistent_notification";
|
||||||
|
|
||||||
|
public const string PersistentNotificationCreateService = "create";
|
||||||
|
|
||||||
|
public const string PersistentNotificationDismissService = "dismiss";
|
||||||
|
|
||||||
|
public const string DailyCheckCron = "0 8 * * *";
|
||||||
|
|
||||||
|
public static readonly string[] ExcludedKeywords =
|
||||||
|
[
|
||||||
|
"iphone",
|
||||||
|
"phone",
|
||||||
|
"watch",
|
||||||
|
"galaxy",
|
||||||
|
"sm_s",
|
||||||
|
"sm_a",
|
||||||
|
"pixel",
|
||||||
|
"oneplus",
|
||||||
|
"ipad"
|
||||||
|
];
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
namespace BatteryMonitor.Models;
|
||||||
|
|
||||||
|
public sealed class BatterySensorInfo
|
||||||
|
{
|
||||||
|
public required string EntityId { get; init; }
|
||||||
|
|
||||||
|
public required string FriendlyName { get; init; }
|
||||||
|
|
||||||
|
public required double BatteryLevel { get; init; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,213 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using BoilerMonitor.Models.Enums;
|
||||||
|
using BoilerMonitorManager;
|
||||||
|
using FluentAssertions;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Moq;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace BoilerMonitor.Manager.Tests;
|
||||||
|
|
||||||
|
public class BoilerControlServiceTests
|
||||||
|
{
|
||||||
|
private readonly Mock<ILogger<BoilerControlService>> _loggerMock = new Mock<ILogger<BoilerControlService>>();
|
||||||
|
|
||||||
|
private BoilerControlService CreateSut()
|
||||||
|
{
|
||||||
|
return 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
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("off")]
|
||||||
|
[InlineData("OFF")]
|
||||||
|
[InlineData("Off")]
|
||||||
|
[InlineData(null)]
|
||||||
|
[InlineData("")]
|
||||||
|
[InlineData(" ")]
|
||||||
|
[InlineData("off ")]
|
||||||
|
[InlineData("unavailable")]
|
||||||
|
[InlineData("unknown")]
|
||||||
|
[InlineData("0")]
|
||||||
|
public void DetermineAction_WhenCheapAndWaterNotReadyAndBudgetAvailable_ShouldReturnTurnOn(string? switchState)
|
||||||
|
{
|
||||||
|
var result = CreateSut()
|
||||||
|
.DetermineAction(
|
||||||
|
true, false, switchState,
|
||||||
|
false, false);
|
||||||
|
|
||||||
|
result.Should().Be(BoilerAction.TurnOn);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("off", BoilerAction.TurnOn)]
|
||||||
|
[InlineData(null, BoilerAction.TurnOn)]
|
||||||
|
[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 = CreateSut()
|
||||||
|
.DetermineAction(
|
||||||
|
true, false, switchState,
|
||||||
|
true, true);
|
||||||
|
|
||||||
|
result.Should().Be(expectedAction);
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region TurnOff scenarios
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("on")]
|
||||||
|
[InlineData("ON")]
|
||||||
|
[InlineData("On")]
|
||||||
|
[InlineData("oN")]
|
||||||
|
public void DetermineAction_WhenNotCheapAndSwitchIsOn_ShouldReturnTurnOff(string switchState)
|
||||||
|
{
|
||||||
|
var result = CreateSut()
|
||||||
|
.DetermineAction(
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region Comprehensive truth tables
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 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>
|
||||||
|
{
|
||||||
|
{ false, false, false, false, BoilerAction.TurnOff },
|
||||||
|
{ false, false, false, true, BoilerAction.TurnOff },
|
||||||
|
{ false, false, true, false, BoilerAction.TurnOff },
|
||||||
|
{ false, false, true, true, BoilerAction.TurnOff },
|
||||||
|
{ false, true, false, false, BoilerAction.TurnOff },
|
||||||
|
{ false, true, false, true, BoilerAction.TurnOff },
|
||||||
|
{ false, true, true, false, BoilerAction.TurnOff },
|
||||||
|
{ false, true, true, true, BoilerAction.TurnOff },
|
||||||
|
{ true, false, false, false, BoilerAction.NoChange },
|
||||||
|
{ true, false, false, true, BoilerAction.NoChange },
|
||||||
|
{ true, false, true, false, BoilerAction.TurnOff },
|
||||||
|
{ true, false, true, true, BoilerAction.NoChange },
|
||||||
|
{ true, true, false, false, BoilerAction.TurnOff },
|
||||||
|
{ true, true, false, true, BoilerAction.TurnOff },
|
||||||
|
{ true, true, true, false, BoilerAction.TurnOff },
|
||||||
|
{ true, true, true, true, BoilerAction.TurnOff }
|
||||||
|
};
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(SwitchOnActionMatrix))]
|
||||||
|
public void DetermineAction_AllCombinationsWhileSwitchIsOn_ShouldReturnExpectedAction(
|
||||||
|
bool isNowCheap,
|
||||||
|
bool waterReady,
|
||||||
|
bool budgetExhausted,
|
||||||
|
bool budgetOverride,
|
||||||
|
BoilerAction expectedAction)
|
||||||
|
{
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
<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.Extensions.TimeProvider.Testing" Version="11.0.1"/>
|
||||||
|
<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"/>
|
||||||
|
<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>
|
||||||
|
<Using Include="Xunit"/>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\BoilerMonitor.Manager\BoilerMonitor.Manager.csproj"/>
|
||||||
|
<ProjectReference Include="..\BoilerMonitor.Models\BoilerMonitor.Models.csproj"/>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using FluentAssertions;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace BoilerMonitor.Manager.Tests;
|
||||||
|
|
||||||
|
public class BoilerMonitorConfigTests
|
||||||
|
{
|
||||||
|
private const string PowerEntityId = BoilerMonitorTestData.PowerEntityId;
|
||||||
|
private const string SwitchEntityId = BoilerMonitorTestData.SwitchEntityId;
|
||||||
|
|
||||||
|
public static TheoryData<string, string?, string?, int?, double?, bool> ConfigurationCases => new TheoryData<string, string?, string?, int?, double?, bool>
|
||||||
|
{
|
||||||
|
{ "fully configured", PowerEntityId, SwitchEntityId, 30, 5.0, true },
|
||||||
|
{ "minimum valid poll interval and threshold", PowerEntityId, SwitchEntityId, 5, 1.0, true },
|
||||||
|
{ "poll interval of one second", PowerEntityId, SwitchEntityId, 1, 5.0, true },
|
||||||
|
{ "maximum poll interval", PowerEntityId, SwitchEntityId, int.MaxValue, 5.0, true },
|
||||||
|
{ "smallest positive threshold", PowerEntityId, SwitchEntityId, 30, double.Epsilon, true },
|
||||||
|
{ "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 }
|
||||||
|
};
|
||||||
|
|
||||||
|
[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]
|
||||||
|
public void IsFullyConfigured_WhenFullyPopulated_ShouldNotDependOnEntityIdCasingOrPadding()
|
||||||
|
{
|
||||||
|
var config = BoilerMonitorTestData.CreateConfig(
|
||||||
|
" sensor.sonoff_1002230e32_power ",
|
||||||
|
"SWITCH.SONOFF_1002230E32");
|
||||||
|
|
||||||
|
config.IsFullyConfigured.Should().BeTrue("entity ids are only checked for non-whitespace content");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,582 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using System.Text.Json;
|
||||||
|
using BoilerMonitorManager;
|
||||||
|
using FluentAssertions;
|
||||||
|
using HomeAssistant.Entities.Interfaces;
|
||||||
|
using HomeAssistant.Models;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Moq;
|
||||||
|
using NetDaemon.HassModel;
|
||||||
|
using static BoilerMonitor.Models.BoilerMonitorConsts;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace BoilerMonitor.Manager.Tests;
|
||||||
|
|
||||||
|
public class BoilerMonitorEntityServiceTests
|
||||||
|
{
|
||||||
|
/// <summary>Every entity that <c>CleanupEntitiesAsync</c> is expected to remove.</summary>
|
||||||
|
private static readonly string[] CleanableEntityIds =
|
||||||
|
[
|
||||||
|
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()
|
||||||
|
{
|
||||||
|
_entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny<EntityCreateModel>()))
|
||||||
|
.Returns(Task.CompletedTask);
|
||||||
|
|
||||||
|
_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,
|
||||||
|
_haContextMock.Object,
|
||||||
|
_loggerMock.Object);
|
||||||
|
}
|
||||||
|
|
||||||
|
#region ReadPersistedState
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(BoilerMonitorTestData.RuntimeStateSamples), MemberType = typeof(BoilerMonitorTestData))]
|
||||||
|
public void ReadPersistedState_WhenRuntimeStateVaries_ShouldParseOrReject(
|
||||||
|
string? runtimeState,
|
||||||
|
TimeSpan? expectedRunTime)
|
||||||
|
{
|
||||||
|
_haContextMock.SetupEntityStates(
|
||||||
|
BoilerMonitorTestData.CreatePersistedEntityStates(runtimeState, "2"));
|
||||||
|
|
||||||
|
var result = CreateSut().ReadPersistedState();
|
||||||
|
|
||||||
|
if (expectedRunTime is null)
|
||||||
|
{
|
||||||
|
result.Should().BeNull();
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
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]
|
||||||
|
public void ReadPersistedState_WithValidState_ShouldReturnPersistedValues()
|
||||||
|
{
|
||||||
|
_haContextMock.SetupEntityStates(BoilerMonitorTestData.CreatePersistedEntityStates(
|
||||||
|
"7200", "3", "ON"));
|
||||||
|
|
||||||
|
var result = CreateSut().ReadPersistedState();
|
||||||
|
|
||||||
|
result.Should().NotBeNull();
|
||||||
|
result.AccumulatedRunTime.Should().Be(TimeSpan.FromHours(2));
|
||||||
|
result.SessionCount.Should().Be(3);
|
||||||
|
result.SkipPriceCapState.Should().Be("ON");
|
||||||
|
result.BudgetOverrideState.Should().Be("OFF");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("ON")]
|
||||||
|
[InlineData("on")]
|
||||||
|
[InlineData(" On ")]
|
||||||
|
[InlineData("")]
|
||||||
|
[InlineData(null)]
|
||||||
|
public void ReadPersistedState_ShouldReturnRawSwitchStates(string? switchState)
|
||||||
|
{
|
||||||
|
_haContextMock.SetupEntityStates(BoilerMonitorTestData.CreatePersistedEntityStates(
|
||||||
|
skipPriceCap: switchState, budgetOverride: switchState));
|
||||||
|
|
||||||
|
var result = CreateSut().ReadPersistedState();
|
||||||
|
|
||||||
|
result.Should().NotBeNull();
|
||||||
|
result.SkipPriceCapState.Should().Be(switchState);
|
||||||
|
result.BudgetOverrideState.Should().Be(switchState);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ReadPersistedState_WhenBothRuntimeEntitiesDoNotExist_ShouldReturnNull()
|
||||||
|
{
|
||||||
|
_haContextMock.SetupEntityStates(
|
||||||
|
BoilerMonitorTestData.CreatePersistedEntityStates(null, null));
|
||||||
|
|
||||||
|
CreateSut().ReadPersistedState().Should().BeNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#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]
|
||||||
|
public void ReadPersistedCooldownTimestamp_WithUtcDesignator_ShouldReturnTimestamp()
|
||||||
|
{
|
||||||
|
var cooldownSince = new DateTimeOffset(2026, 3, 31, 9, 15, 0, TimeSpan.Zero);
|
||||||
|
|
||||||
|
_haContextMock.SetupEntityState(
|
||||||
|
WaterReadyEntityId,
|
||||||
|
BoilerMonitorTestData.CreateWaterReadyEntityStateWithCooldown("2026-03-31T09:15:00Z"));
|
||||||
|
|
||||||
|
var result = CreateSut().ReadPersistedCooldownTimestamp();
|
||||||
|
|
||||||
|
result.Should().Be(cooldownSince);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ReadPersistedCooldownTimestamp_WhenEntityDoesNotExist_ShouldReturnNull()
|
||||||
|
{
|
||||||
|
_haContextMock.SetupEntityState(WaterReadyEntityId, null);
|
||||||
|
|
||||||
|
CreateSut().ReadPersistedCooldownTimestamp().Should().BeNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ReadPersistedCooldownTimestamp_WhenEntityHasNoAttributes_ShouldReturnNull()
|
||||||
|
{
|
||||||
|
_haContextMock.SetupEntityState(WaterReadyEntityId, BoilerMonitorTestData.CreateEntityState("yes"));
|
||||||
|
|
||||||
|
CreateSut().ReadPersistedCooldownTimestamp().Should().BeNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ReadPersistedCooldownTimestamp_WhenAttributeIsMissing_ShouldReturnNull()
|
||||||
|
{
|
||||||
|
_haContextMock.SetupEntityState(
|
||||||
|
WaterReadyEntityId,
|
||||||
|
BoilerMonitorTestData.CreateEntityStateWithAttributes(
|
||||||
|
new Dictionary<string, object?> { ["friendly_name"] = "Boiler water ready" }));
|
||||||
|
|
||||||
|
CreateSut().ReadPersistedCooldownTimestamp().Should().BeNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(null)]
|
||||||
|
[InlineData(42)]
|
||||||
|
[InlineData(true)]
|
||||||
|
[InlineData("")]
|
||||||
|
[InlineData(" ")]
|
||||||
|
[InlineData("not-a-timestamp")]
|
||||||
|
[InlineData("2026-13-45T99:99:99")]
|
||||||
|
[InlineData("unavailable")]
|
||||||
|
public void ReadPersistedCooldownTimestamp_WhenAttributeIsNotAValidTimestamp_ShouldReturnNull(object? cooldownSince)
|
||||||
|
{
|
||||||
|
_haContextMock.SetupEntityState(
|
||||||
|
WaterReadyEntityId,
|
||||||
|
BoilerMonitorTestData.CreateWaterReadyEntityStateWithCooldown(cooldownSince));
|
||||||
|
|
||||||
|
CreateSut().ReadPersistedCooldownTimestamp().Should().BeNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ReadPersistedCooldownTimestamp_WhenHaContextThrows_ShouldReturnNull()
|
||||||
|
{
|
||||||
|
_haContextMock.Setup(h => h.GetState(WaterReadyEntityId))
|
||||||
|
.Throws(new InvalidOperationException("Home Assistant unavailable"));
|
||||||
|
|
||||||
|
CreateSut().ReadPersistedCooldownTimestamp().Should().BeNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region UpdateEntitiesAsync
|
||||||
|
|
||||||
|
[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
|
||||||
|
|
||||||
|
#region ResetTransientEntitiesAsync
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task ResetTransientEntitiesAsync_ShouldResetStatusAndWaterReady()
|
||||||
|
{
|
||||||
|
await CreateSut().ResetTransientEntitiesAsync();
|
||||||
|
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityState(StatusEntityId, StatusAwaitingConfiguration), 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]
|
||||||
|
public async Task CleanupEntitiesAsync_WhenRemoveFails_ShouldRethrow()
|
||||||
|
{
|
||||||
|
_entityManagerMock
|
||||||
|
.Setup(em => em.RemoveEntity(It.IsAny<string>()))
|
||||||
|
.Throws(new InvalidOperationException("MQTT unavailable"));
|
||||||
|
|
||||||
|
var act = () => CreateSut().CleanupEntitiesAsync();
|
||||||
|
|
||||||
|
await act.Should().ThrowAsync<InvalidOperationException>();
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region SetStatusAsync and cancellation
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task SetStatusAsync_ShouldWriteStatusEntity()
|
||||||
|
{
|
||||||
|
await CreateSut().SetStatusAsync(StatusConfigured);
|
||||||
|
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityState(StatusEntityId, StatusConfigured), Times.Once);
|
||||||
|
}
|
||||||
|
|
||||||
|
public enum CancelableOperation
|
||||||
|
{
|
||||||
|
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
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using BoilerMonitorManager.Models;
|
||||||
|
using FluentAssertions;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace BoilerMonitor.Manager.Tests;
|
||||||
|
|
||||||
|
public class BoilerMonitorOptionsTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public void Defaults_ShouldHaveEnabledTrue()
|
||||||
|
{
|
||||||
|
var options = new BoilerMonitorOptions();
|
||||||
|
|
||||||
|
options.Enabled.Should().BeTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Defaults_ShouldHaveCleanupEntitiesOnStartupTrue()
|
||||||
|
{
|
||||||
|
var options = new BoilerMonitorOptions();
|
||||||
|
|
||||||
|
options.CleanupEntitiesOnStartup.Should().BeTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void SectionName_ShouldBeBoilerMonitor()
|
||||||
|
{
|
||||||
|
BoilerMonitorOptions.SectionName.Should().Be("BoilerMonitor");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(false)]
|
||||||
|
[InlineData(true)]
|
||||||
|
public void Enabled_WhenSet_ShouldReturnConfiguredValue(bool enabled)
|
||||||
|
{
|
||||||
|
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.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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,495 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using BoilerMonitor.Models;
|
||||||
|
using BoilerMonitorManager;
|
||||||
|
using FluentAssertions;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Microsoft.Extensions.Time.Testing;
|
||||||
|
using Moq;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace BoilerMonitor.Manager.Tests;
|
||||||
|
|
||||||
|
public class WaterReadyServiceTests
|
||||||
|
{
|
||||||
|
private const double Threshold = BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts;
|
||||||
|
private const double HighPowerWatts = 2150.0;
|
||||||
|
private const int RequiredReadings = BoilerMonitorConsts.ConsecutiveReadingsRequired;
|
||||||
|
|
||||||
|
private readonly Mock<ILogger<WaterReadyService>> _loggerMock = new Mock<ILogger<WaterReadyService>>();
|
||||||
|
private readonly FakeTimeProvider _timeProvider = BoilerMonitorTestData.CreateTimeProvider();
|
||||||
|
|
||||||
|
private WaterReadyService CreateSut()
|
||||||
|
{
|
||||||
|
return new WaterReadyService(_loggerMock.Object, _timeProvider);
|
||||||
|
}
|
||||||
|
|
||||||
|
private WaterReadyService CreateSutWithHeatingObserved()
|
||||||
|
{
|
||||||
|
var sut = CreateSut();
|
||||||
|
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)
|
||||||
|
{
|
||||||
|
var sut = CreateSut();
|
||||||
|
|
||||||
|
var result = FeedReadings(sut, readingCount);
|
||||||
|
|
||||||
|
result.Should().BeFalse();
|
||||||
|
sut.IsInCooldown.Should().BeFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IsWaterReady_AfterObservedHeatingAndConsecutiveLowPower_ShouldReturnTrue()
|
||||||
|
{
|
||||||
|
var sut = CreateSutWithHeatingObserved();
|
||||||
|
|
||||||
|
var result = FeedReadings(sut, RequiredReadings);
|
||||||
|
|
||||||
|
result.Should().BeTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void RecordHeatingObserved_ShouldEnableDetection()
|
||||||
|
{
|
||||||
|
var sut = CreateSut();
|
||||||
|
|
||||||
|
sut.RecordHeatingObserved();
|
||||||
|
|
||||||
|
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);
|
||||||
|
|
||||||
|
result.Should().BeTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ResetCooldown_ShouldKeepHeatingObservationEnabled()
|
||||||
|
{
|
||||||
|
var sut = CreateSutWithHeatingObserved();
|
||||||
|
FeedReadings(sut, RequiredReadings).Should().BeTrue();
|
||||||
|
|
||||||
|
sut.ResetCooldown();
|
||||||
|
|
||||||
|
FeedReadings(sut, RequiredReadings)
|
||||||
|
.Should()
|
||||||
|
.BeTrue(
|
||||||
|
"ResetCooldown clears the cooldown and counter, not the heating observation");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IsWaterReady_AfterResetAndReObservedHeating_ShouldTriggerAgain()
|
||||||
|
{
|
||||||
|
var sut = CreateSutWithHeatingObserved();
|
||||||
|
FeedReadings(sut, RequiredReadings);
|
||||||
|
sut.ResetCooldown();
|
||||||
|
|
||||||
|
sut.RecordHeatingObserved();
|
||||||
|
var result = FeedReadings(sut, RequiredReadings);
|
||||||
|
|
||||||
|
result.Should().BeTrue("detection should work again after reset + new heating observation");
|
||||||
|
}
|
||||||
|
|
||||||
|
#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]
|
||||||
|
public void IsWaterReady_InterleavedReadings_ShouldOnlyTriggerAfterLastConsecutiveLowReading()
|
||||||
|
{
|
||||||
|
var sut = CreateSutWithHeatingObserved();
|
||||||
|
|
||||||
|
var results = new[]
|
||||||
|
{
|
||||||
|
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);
|
||||||
|
|
||||||
|
result.Should().BeFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("on", null)]
|
||||||
|
[InlineData(null, 0.0)]
|
||||||
|
[InlineData(null, null)]
|
||||||
|
[InlineData("", null)]
|
||||||
|
[InlineData("", 0.0)]
|
||||||
|
public void IsWaterReady_WhenSwitchStateOrPowerIsNull_ShouldReturnFalse(string? switchState, double? powerWatts)
|
||||||
|
{
|
||||||
|
var sut = CreateSutWithHeatingObserved();
|
||||||
|
|
||||||
|
var result = FeedReadings(sut, 10, switchState, powerWatts);
|
||||||
|
|
||||||
|
result.Should().BeFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("ON")]
|
||||||
|
[InlineData("On")]
|
||||||
|
[InlineData("oN")]
|
||||||
|
public void IsWaterReady_SwitchOnCaseInsensitive_ShouldReturnTrue(string switchState)
|
||||||
|
{
|
||||||
|
var sut = CreateSutWithHeatingObserved();
|
||||||
|
|
||||||
|
var result = FeedReadings(sut, RequiredReadings, switchState);
|
||||||
|
|
||||||
|
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]
|
||||||
|
[InlineData(9.9, 10.0, true)]
|
||||||
|
[InlineData(10.0, 10.0, false)]
|
||||||
|
[InlineData(10.1, 10.0, false)]
|
||||||
|
[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)
|
||||||
|
{
|
||||||
|
var sut = CreateSutWithHeatingObserved();
|
||||||
|
|
||||||
|
var result = FeedReadings(sut, RequiredReadings, powerWatts: powerWatts,
|
||||||
|
heatingThresholdWatts: heatingThresholdWatts);
|
||||||
|
|
||||||
|
result.Should().Be(expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region Cooldown period
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[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)
|
||||||
|
{
|
||||||
|
var sut = CreateSutWithHeatingObserved();
|
||||||
|
FeedReadings(sut, RequiredReadings).Should().BeTrue();
|
||||||
|
|
||||||
|
var result = sut.IsWaterReady(switchState, powerWatts, Threshold);
|
||||||
|
|
||||||
|
result.Should().BeTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(BoilerMonitorTestData.GeneratedElapsedTimes), MemberType = typeof(BoilerMonitorTestData))]
|
||||||
|
public void IsWaterReady_CooldownDoesNotExpireByTime_ShouldStayActive(TimeSpan elapsed)
|
||||||
|
{
|
||||||
|
var sut = CreateSutWithHeatingObserved();
|
||||||
|
FeedReadings(sut, RequiredReadings);
|
||||||
|
var triggeredAt = sut.WaterReadySince;
|
||||||
|
|
||||||
|
_timeProvider.Advance(elapsed);
|
||||||
|
|
||||||
|
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]
|
||||||
|
public void IsInCooldown_WhenNoCooldownTriggered_ShouldReturnFalse()
|
||||||
|
{
|
||||||
|
var sut = CreateSut();
|
||||||
|
|
||||||
|
sut.IsInCooldown.Should().BeFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ResetCooldown_ShouldClearActiveCooldownAndAllowDetectionToResume()
|
||||||
|
{
|
||||||
|
var sut = CreateSutWithHeatingObserved();
|
||||||
|
FeedReadings(sut, RequiredReadings);
|
||||||
|
sut.IsInCooldown.Should().BeTrue();
|
||||||
|
|
||||||
|
sut.ResetCooldown();
|
||||||
|
|
||||||
|
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]
|
||||||
|
public void ResetCooldown_WhenNoCooldownIsActive_ShouldBeANoOp()
|
||||||
|
{
|
||||||
|
var sut = CreateSut();
|
||||||
|
|
||||||
|
sut.ResetCooldown();
|
||||||
|
|
||||||
|
sut.IsInCooldown.Should().BeFalse();
|
||||||
|
sut.WaterReadySince.Should().BeNull();
|
||||||
|
FeedReadings(sut, 10).Should().BeFalse("heating was never observed");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IsWaterReady_CooldownOnlySetOnFirstDetection_ShouldNotResetTimestamp()
|
||||||
|
{
|
||||||
|
var sut = CreateSutWithHeatingObserved();
|
||||||
|
FeedReadings(sut, RequiredReadings);
|
||||||
|
var originalTimestamp = sut.WaterReadySince;
|
||||||
|
|
||||||
|
_timeProvider.Advance(TimeSpan.FromHours(2));
|
||||||
|
sut.IsWaterReady("on", 0.0, Threshold).Should().BeTrue();
|
||||||
|
|
||||||
|
sut.WaterReadySince.Should().Be(originalTimestamp);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(Threshold)]
|
||||||
|
[InlineData(HighPowerWatts)]
|
||||||
|
[InlineData(double.MaxValue)]
|
||||||
|
public void IsWaterReady_PowerAtOrAboveThreshold_ShouldNotStartCooldown(double powerWatts)
|
||||||
|
{
|
||||||
|
var sut = CreateSutWithHeatingObserved();
|
||||||
|
|
||||||
|
FeedReadings(sut, RequiredReadings, powerWatts: powerWatts).Should().BeFalse();
|
||||||
|
|
||||||
|
sut.IsInCooldown.Should().BeFalse();
|
||||||
|
sut.WaterReadySince.Should().BeNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
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()
|
||||||
|
{
|
||||||
|
var sut = CreateSut();
|
||||||
|
|
||||||
|
sut.WaterReadySince.Should().BeNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region False positive scenario (the bug this fix addresses)
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IsWaterReady_BoilerJustTurnedOnPowerStillZero_ShouldNotTriggerFalsePositive()
|
||||||
|
{
|
||||||
|
var sut = CreateSut();
|
||||||
|
sut.NotifyTurnedOn();
|
||||||
|
|
||||||
|
for (var i = 0; i < 10; i++)
|
||||||
|
{
|
||||||
|
var result = sut.IsWaterReady("on", 0.0, Threshold);
|
||||||
|
result.Should().BeFalse("boiler was never observed heating — this is a ramp-up delay, not 'water ready'");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IsWaterReady_FullHeatingCycle_ShouldDetectWaterReadyCorrectly()
|
||||||
|
{
|
||||||
|
var sut = CreateSut();
|
||||||
|
sut.NotifyTurnedOn();
|
||||||
|
|
||||||
|
sut.IsWaterReady("on", 0.0, Threshold).Should().BeFalse("ramp-up, no heating observed yet");
|
||||||
|
|
||||||
|
sut.RecordHeatingObserved();
|
||||||
|
sut.IsWaterReady("on", HighPowerWatts, Threshold).Should().BeFalse("actively heating");
|
||||||
|
sut.IsWaterReady("on", HighPowerWatts - 50, Threshold).Should().BeFalse("still heating");
|
||||||
|
|
||||||
|
sut.IsWaterReady("on", 0.0, Threshold).Should().BeFalse("first below-threshold reading, needs confirmation");
|
||||||
|
sut.IsWaterReady("on", 0.0, Threshold).Should().BeTrue("second consecutive below-threshold → water ready");
|
||||||
|
|
||||||
|
sut.IsInCooldown.Should().BeTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using System.Globalization;
|
||||||
|
using BoilerMonitor.Models;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using NetDaemon.HassModel;
|
||||||
|
using static BoilerMonitor.Models.BoilerMonitorConsts;
|
||||||
|
using static NordPool.Models.NordPoolConsts;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace BoilerMonitorManager;
|
||||||
|
|
||||||
|
public sealed class BoilerConfigReader(IHaContext haContext, ILogger<BoilerConfigReader> logger) : IBoilerConfigReader
|
||||||
|
{
|
||||||
|
private const double DefaultDailyHours = 1.0;
|
||||||
|
|
||||||
|
public BoilerConfig ReadConfig()
|
||||||
|
{
|
||||||
|
var dailyHoursState = haContext.GetState(BoilerDailyHoursEntityId)?.State;
|
||||||
|
|
||||||
|
var dailyHours = double.TryParse(dailyHoursState, NumberStyles.Any, CultureInfo.InvariantCulture, out var dh)
|
||||||
|
? dh
|
||||||
|
: DefaultDailyHours;
|
||||||
|
|
||||||
|
var intervalCount = (int)(dailyHours * IntervalsPerHour);
|
||||||
|
|
||||||
|
if (intervalCount <= 0)
|
||||||
|
{
|
||||||
|
intervalCount = IntervalsPerHour;
|
||||||
|
}
|
||||||
|
|
||||||
|
var priceCapState = haContext.GetState(BoilerPriceCapEntityId)?.State;
|
||||||
|
|
||||||
|
var priceCap =
|
||||||
|
double.TryParse(priceCapState, NumberStyles.Any, CultureInfo.InvariantCulture, out var pc) && pc > 0
|
||||||
|
? pc
|
||||||
|
: double.MaxValue;
|
||||||
|
|
||||||
|
var deadline = DateTime.Today.AddDays(1);
|
||||||
|
var readyByState = haContext.GetState(BoilerReadyByEntityId)?.State;
|
||||||
|
|
||||||
|
if (!string.IsNullOrEmpty(readyByState) &&
|
||||||
|
TimeSpan.TryParse(readyByState, CultureInfo.InvariantCulture, out var readyByTime))
|
||||||
|
{
|
||||||
|
deadline = DateTime.Today.Add(readyByTime);
|
||||||
|
}
|
||||||
|
|
||||||
|
var skipPriceCapState = haContext.GetState(SkipPriceCapEntityId)?.State;
|
||||||
|
var skipPriceCap = string.Equals(skipPriceCapState, SwitchOnState, StringComparison.OrdinalIgnoreCase);
|
||||||
|
|
||||||
|
if (logger.IsEnabled(LogLevel.Debug))
|
||||||
|
{
|
||||||
|
logger.LogDebug(
|
||||||
|
"Boiler config: intervals={Intervals}, priceCap={Cap}, skipPriceCap={Skip}, deadline={Deadline}",
|
||||||
|
intervalCount, priceCap, skipPriceCap, deadline);
|
||||||
|
}
|
||||||
|
|
||||||
|
var config = new BoilerConfig
|
||||||
|
{
|
||||||
|
IntervalCount = intervalCount,
|
||||||
|
PriceCap = priceCap,
|
||||||
|
Deadline = deadline,
|
||||||
|
SkipPriceCap = skipPriceCap
|
||||||
|
};
|
||||||
|
|
||||||
|
return config;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using BoilerMonitor.Models.Enums;
|
||||||
|
using BoilerMonitorManager.Interface;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace BoilerMonitorManager;
|
||||||
|
|
||||||
|
public sealed class BoilerControlService(ILogger<BoilerControlService> logger) : IBoilerControlService
|
||||||
|
{
|
||||||
|
private const string SwitchOnState = "on";
|
||||||
|
|
||||||
|
public BoilerAction DetermineAction(
|
||||||
|
bool isNowCheap,
|
||||||
|
bool waterReady,
|
||||||
|
string? currentSwitchState,
|
||||||
|
bool budgetExhausted,
|
||||||
|
bool budgetOverride)
|
||||||
|
{
|
||||||
|
var isCurrentlyOn = string.Equals(currentSwitchState, SwitchOnState, StringComparison.OrdinalIgnoreCase);
|
||||||
|
var effectiveBudgetExhausted = budgetExhausted && !budgetOverride;
|
||||||
|
var shouldBeOn = isNowCheap && !waterReady && !effectiveBudgetExhausted;
|
||||||
|
|
||||||
|
switch (shouldBeOn, isCurrentlyOn)
|
||||||
|
{
|
||||||
|
case (true, false):
|
||||||
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
|
{
|
||||||
|
logger.LogInformation(
|
||||||
|
"Boiler should turn ON — cheap interval active, water not ready, budget available (current state: {State})",
|
||||||
|
currentSwitchState);
|
||||||
|
}
|
||||||
|
|
||||||
|
return BoilerAction.TurnOn;
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
default:
|
||||||
|
if (logger.IsEnabled(LogLevel.Debug))
|
||||||
|
{
|
||||||
|
logger.LogDebug(
|
||||||
|
"Boiler state unchanged: {State} (cheap={Cheap}, waterReady={WaterReady}, budgetExhausted={BudgetExhausted})",
|
||||||
|
currentSwitchState, isNowCheap, waterReady, effectiveBudgetExhausted);
|
||||||
|
}
|
||||||
|
|
||||||
|
return BoilerAction.NoChange;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string GetTurnOffReason(bool waterReady, bool effectiveBudgetExhausted)
|
||||||
|
{
|
||||||
|
if (waterReady)
|
||||||
|
{
|
||||||
|
return "water is already ready";
|
||||||
|
}
|
||||||
|
|
||||||
|
return effectiveBudgetExhausted
|
||||||
|
? "daily budget is exhausted"
|
||||||
|
: "not in a cheap interval";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<RootNamespace>BoilerMonitorManager</RootNamespace>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
|
||||||
|
<_Parameter1>BoilerMonitor.Manager.Tests</_Parameter1>
|
||||||
|
</AssemblyAttribute>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\HomeAssistant.Entities\HomeAssistant.Entities.csproj"/>
|
||||||
|
<ProjectReference Include="..\BoilerMonitor.Models\BoilerMonitor.Models.csproj"/>
|
||||||
|
<ProjectReference Include="..\NordPool.Models\NordPool.Models.csproj"/>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="11.0.0"/>
|
||||||
|
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.43.1"/>
|
||||||
|
<PackageReference Include="NetDaemon.HassModel" Version="26.43.1"/>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,584 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using System.Globalization;
|
||||||
|
using System.Text.Json;
|
||||||
|
using BoilerMonitor.Models;
|
||||||
|
using BoilerMonitorManager.Interface;
|
||||||
|
using BoilerMonitorManager.Models;
|
||||||
|
using HomeAssistant.Entities.Interfaces;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using NetDaemon.Extensions.MqttEntityManager;
|
||||||
|
using NetDaemon.HassModel;
|
||||||
|
using static BoilerMonitor.Models.BoilerMonitorConsts;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace BoilerMonitorManager;
|
||||||
|
|
||||||
|
public sealed class BoilerMonitorEntityService(
|
||||||
|
IEntityManager entityManager,
|
||||||
|
IHaContext haContext,
|
||||||
|
ILogger<BoilerMonitorEntityService> logger) : IBoilerMonitorEntityService
|
||||||
|
{
|
||||||
|
private static readonly string[] CleanableEntityIds =
|
||||||
|
[
|
||||||
|
ConfigPowerEntityId,
|
||||||
|
ConfigSwitchEntityId,
|
||||||
|
ConfigPollIntervalEntityId,
|
||||||
|
ConfigHeatingThresholdEntityId,
|
||||||
|
StatusEntityId,
|
||||||
|
WaterReadyEntityId,
|
||||||
|
SkipPriceCapEntityId,
|
||||||
|
TodayRuntimeEntityId,
|
||||||
|
RemainingTimeEntityId,
|
||||||
|
BudgetPercentageEntityId,
|
||||||
|
BudgetExhaustedEntityId,
|
||||||
|
SessionCountEntityId,
|
||||||
|
BudgetOverrideEntityId,
|
||||||
|
AutoManagementEntityId
|
||||||
|
];
|
||||||
|
|
||||||
|
public async Task CreateEntitiesAsync(CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
|
|
||||||
|
var entities = GetAllEntities();
|
||||||
|
|
||||||
|
var createTasks = entities.Select(async entity =>
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
|
{
|
||||||
|
logger.LogInformation("Creating/re-registering MQTT entity: {EntityId}", entity.EntityId);
|
||||||
|
}
|
||||||
|
|
||||||
|
await entityManager.CreateEntityAsync(entity).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.LogError(ex, "Failed to create MQTT entity: {EntityId}", entity.EntityId);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
await Task.WhenAll(createTasks).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task ResetEntitiesAsync(CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
|
|
||||||
|
logger.LogInformation("Resetting all BoilerMonitor runtime entity states to defaults");
|
||||||
|
|
||||||
|
await Task.WhenAll(
|
||||||
|
ResetStatusAsync(),
|
||||||
|
ResetWaterReadyAsync(),
|
||||||
|
ResetSkipPriceCapAsync(),
|
||||||
|
ResetTodayRuntimeAsync(),
|
||||||
|
ResetRemainingTimeAsync(),
|
||||||
|
ResetBudgetPercentageAsync(),
|
||||||
|
ResetBudgetExhaustedAsync(),
|
||||||
|
ResetSessionCountAsync(),
|
||||||
|
ResetBudgetOverrideAsync(),
|
||||||
|
ResetAutoManagementAsync()
|
||||||
|
)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
|
||||||
|
logger.LogInformation("All BoilerMonitor runtime entity states reset to defaults");
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task UpdateEntitiesAsync(BoilerMonitorUpdateContext ctx, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
|
|
||||||
|
var timestamp = DateTime.UtcNow.ToString("O");
|
||||||
|
var formattedRunTime = FormatTimeSpan(ctx.TodayRunTime);
|
||||||
|
var formattedRemaining = FormatTimeSpan(ctx.RemainingTime);
|
||||||
|
|
||||||
|
var updateTasks = new[]
|
||||||
|
{
|
||||||
|
UpdateStatusAsync(StatusConfigured),
|
||||||
|
UpdateWaterReadyAsync(ctx, timestamp),
|
||||||
|
UpdateTodayRuntimeAsync(ctx.TodayRunTime, formattedRunTime, timestamp),
|
||||||
|
UpdateRemainingTimeAsync(ctx.RemainingTime, formattedRemaining, ctx.BudgetHours, timestamp),
|
||||||
|
UpdateBudgetPercentageAsync(ctx.BudgetPercentage, timestamp),
|
||||||
|
UpdateBudgetExhaustedAsync(ctx.BudgetExhausted),
|
||||||
|
UpdateSessionCountAsync(ctx.SessionCount, timestamp)
|
||||||
|
};
|
||||||
|
|
||||||
|
await Task.WhenAll(updateTasks).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var removeTasks = CleanableEntityIds.Select(entityManager.RemoveEntity);
|
||||||
|
await Task.WhenAll(removeTasks).ConfigureAwait(false);
|
||||||
|
|
||||||
|
logger.LogInformation("BoilerMonitor entities cleaned up successfully (cleanup button retained)");
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.LogError(ex, "Error cleaning up BoilerMonitor entities");
|
||||||
|
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task ResetTransientEntitiesAsync(CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
|
|
||||||
|
logger.LogInformation("Resetting transient BoilerMonitor entity states (status, water ready)");
|
||||||
|
|
||||||
|
await Task.WhenAll(
|
||||||
|
ResetStatusAsync(),
|
||||||
|
ResetWaterReadyAsync()
|
||||||
|
)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
public PersistedBoilerState? ReadPersistedState()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var runtimeState = haContext.GetState(TodayRuntimeEntityId)?.State;
|
||||||
|
var sessionCountState = haContext.GetState(SessionCountEntityId)?.State;
|
||||||
|
var skipPriceCapState = haContext.GetState(SkipPriceCapEntityId)?.State;
|
||||||
|
var budgetOverrideState = haContext.GetState(BudgetOverrideEntityId)?.State;
|
||||||
|
|
||||||
|
if (!TryParseEntitySeconds(runtimeState, out var runtimeSeconds) ||
|
||||||
|
!TryParseEntityInt(sessionCountState, out var sessionCount))
|
||||||
|
{
|
||||||
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
|
{
|
||||||
|
logger.LogInformation(
|
||||||
|
"No valid persisted BoilerMonitor state found in HA entities (runtime={Runtime}, sessions={Sessions})",
|
||||||
|
runtimeState, sessionCountState);
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var persisted = new PersistedBoilerState
|
||||||
|
{
|
||||||
|
AccumulatedRunTime = TimeSpan.FromSeconds(runtimeSeconds),
|
||||||
|
SessionCount = sessionCount,
|
||||||
|
SkipPriceCapState = skipPriceCapState,
|
||||||
|
BudgetOverrideState = budgetOverrideState
|
||||||
|
};
|
||||||
|
|
||||||
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
|
{
|
||||||
|
logger.LogInformation(
|
||||||
|
"Restored persisted BoilerMonitor state: runtime={Runtime}, sessions={Sessions}, skipPriceCap={SkipPriceCap}, budgetOverride={BudgetOverride}",
|
||||||
|
persisted.AccumulatedRunTime, persisted.SessionCount, persisted.SkipPriceCapState,
|
||||||
|
persisted.BudgetOverrideState);
|
||||||
|
}
|
||||||
|
|
||||||
|
return persisted;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.LogError(ex, "Error reading persisted BoilerMonitor state from HA entities");
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task SetStatusAsync(string status)
|
||||||
|
{
|
||||||
|
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)
|
||||||
|
{
|
||||||
|
seconds = 0;
|
||||||
|
var tryParseEntitySeconds = !string.IsNullOrWhiteSpace(state) && state is not ("unavailable" or "unknown") && double.TryParse(state, CultureInfo.InvariantCulture, out seconds) && seconds >= 0;
|
||||||
|
|
||||||
|
return tryParseEntitySeconds;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool TryParseEntityInt(string? state, out int value)
|
||||||
|
{
|
||||||
|
value = 0;
|
||||||
|
var tryParseEntityInt = !string.IsNullOrWhiteSpace(state) && state is not ("unavailable" or "unknown") && int.TryParse(state, CultureInfo.InvariantCulture, out value) && value >= 0;
|
||||||
|
|
||||||
|
return tryParseEntityInt;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static ICollection<BoilerMonitorEntity> GetAllEntities()
|
||||||
|
{
|
||||||
|
var device = CreateDeviceBlock();
|
||||||
|
|
||||||
|
return
|
||||||
|
[
|
||||||
|
new BoilerMonitorEntity("text", "boilermonitor_config_power_entity_id", "Boiler power entity ID")
|
||||||
|
{
|
||||||
|
AdditionalConfig = new { icon = "mdi:flash", device }
|
||||||
|
},
|
||||||
|
new BoilerMonitorEntity("text", "boilermonitor_config_switch_entity_id", "Boiler switch entity ID")
|
||||||
|
{
|
||||||
|
AdditionalConfig = new { icon = "mdi:toggle-switch", device }
|
||||||
|
},
|
||||||
|
new BoilerMonitorEntity("number", "boilermonitor_config_poll_interval", "Poll interval (seconds)")
|
||||||
|
{
|
||||||
|
AdditionalConfig = new
|
||||||
|
{
|
||||||
|
min = (double)MinPollIntervalSeconds,
|
||||||
|
max = (double)MaxPollIntervalSeconds,
|
||||||
|
step = (double)PollIntervalStepSeconds,
|
||||||
|
unit_of_measurement = "s",
|
||||||
|
icon = "mdi:timer-outline",
|
||||||
|
device
|
||||||
|
}
|
||||||
|
},
|
||||||
|
new BoilerMonitorEntity("number", "boilermonitor_config_heating_threshold",
|
||||||
|
"Heating power threshold (watts)")
|
||||||
|
{
|
||||||
|
AdditionalConfig = new
|
||||||
|
{
|
||||||
|
min = MinHeatingThresholdWatts,
|
||||||
|
max = MaxHeatingThresholdWatts,
|
||||||
|
step = HeatingThresholdStepWatts,
|
||||||
|
unit_of_measurement = "W",
|
||||||
|
icon = "mdi:thermometer",
|
||||||
|
device
|
||||||
|
}
|
||||||
|
},
|
||||||
|
new BoilerMonitorEntity("button", "boilermonitor_cleanup", "Cleanup all entities")
|
||||||
|
{
|
||||||
|
AdditionalConfig = new { icon = "mdi:delete-sweep", device }
|
||||||
|
},
|
||||||
|
new BoilerMonitorEntity("sensor", "boilermonitor_status", "Boiler Monitor status")
|
||||||
|
{
|
||||||
|
AdditionalConfig = new { icon = "mdi:information-outline", device }
|
||||||
|
},
|
||||||
|
new BoilerMonitorEntity("sensor", "boilermonitor_water_ready", "Boiler water ready")
|
||||||
|
{
|
||||||
|
AdditionalConfig = new { icon = "mdi:water-thermometer", device }
|
||||||
|
},
|
||||||
|
new BoilerMonitorEntity("switch", "boilermonitor_skip_price_cap", "Skip price cap, heat until ready")
|
||||||
|
{
|
||||||
|
AdditionalConfig = new { optimistic = true, icon = "mdi:water-thermometer-outline", device }
|
||||||
|
},
|
||||||
|
new BoilerMonitorEntity("sensor", "boilermonitor_today_runtime", "Today runtime")
|
||||||
|
{
|
||||||
|
AdditionalConfig = new
|
||||||
|
{ unit_of_measurement = "s", icon = "mdi:timer", device_class = "duration", device }
|
||||||
|
},
|
||||||
|
new BoilerMonitorEntity("sensor", "boilermonitor_remaining_time", "Remaining budget time")
|
||||||
|
{
|
||||||
|
AdditionalConfig = new
|
||||||
|
{ unit_of_measurement = "s", icon = "mdi:timer-sand", device_class = "duration", device }
|
||||||
|
},
|
||||||
|
new BoilerMonitorEntity("sensor", "boilermonitor_budget_percentage", "Budget usage")
|
||||||
|
{
|
||||||
|
AdditionalConfig = new { unit_of_measurement = "%", icon = "mdi:percent", device }
|
||||||
|
},
|
||||||
|
new BoilerMonitorEntity("binary_sensor", "boilermonitor_budget_exhausted", "Budget exhausted")
|
||||||
|
{
|
||||||
|
Options = new EntityCreationOptions
|
||||||
|
{
|
||||||
|
UniqueId = BudgetExhaustedEntityId,
|
||||||
|
Name = "Budget exhausted"
|
||||||
|
},
|
||||||
|
AdditionalConfig = new { icon = "mdi:battery-alert", device }
|
||||||
|
},
|
||||||
|
new BoilerMonitorEntity("sensor", "boilermonitor_session_count", "Heating sessions today")
|
||||||
|
{
|
||||||
|
AdditionalConfig = new { icon = "mdi:counter", device }
|
||||||
|
},
|
||||||
|
new BoilerMonitorEntity("switch", "boilermonitor_budget_override", "Override budget enforcement")
|
||||||
|
{
|
||||||
|
AdditionalConfig = new { optimistic = true, icon = "mdi:shield-off-outline", device }
|
||||||
|
},
|
||||||
|
new BoilerMonitorEntity("switch", "boilermonitor_auto_management", "Automatic boiler control")
|
||||||
|
{
|
||||||
|
AdditionalConfig = new { optimistic = true, icon = "mdi:robot-outline", device }
|
||||||
|
}
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task UpdateStatusAsync(string status)
|
||||||
|
{
|
||||||
|
await SetEntityStateSafe(StatusEntityId, status).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task ResetStatusAsync()
|
||||||
|
{
|
||||||
|
await SetEntityStateSafe(StatusEntityId, StatusAwaitingConfiguration).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task ResetWaterReadyAsync()
|
||||||
|
{
|
||||||
|
await SetEntityStateSafe(WaterReadyEntityId, "unknown").ConfigureAwait(false);
|
||||||
|
|
||||||
|
await SetEntityAttributesSafe(WaterReadyEntityId, new
|
||||||
|
{
|
||||||
|
boiler_switch_state = "unknown",
|
||||||
|
boiler_power_watts = 0.0,
|
||||||
|
power_threshold_watts = DefaultHeatingPowerThresholdWatts,
|
||||||
|
friendly_name = "Boiler water ready",
|
||||||
|
last_updated = (string?)null
|
||||||
|
})
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task ResetSkipPriceCapAsync()
|
||||||
|
{
|
||||||
|
await SetEntityStateSafe(SkipPriceCapEntityId, "OFF").ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task ResetTodayRuntimeAsync()
|
||||||
|
{
|
||||||
|
await SetEntityStateSafe(TodayRuntimeEntityId, "0").ConfigureAwait(false);
|
||||||
|
|
||||||
|
await SetEntityAttributesSafe(TodayRuntimeEntityId, new
|
||||||
|
{
|
||||||
|
formatted = "0h 0m",
|
||||||
|
friendly_name = "Today runtime",
|
||||||
|
last_updated = (string?)null
|
||||||
|
})
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task ResetRemainingTimeAsync()
|
||||||
|
{
|
||||||
|
await SetEntityStateSafe(RemainingTimeEntityId, "0").ConfigureAwait(false);
|
||||||
|
|
||||||
|
await SetEntityAttributesSafe(RemainingTimeEntityId, new
|
||||||
|
{
|
||||||
|
formatted = "0h 0m",
|
||||||
|
budget_hours = 0.0,
|
||||||
|
friendly_name = "Remaining budget time",
|
||||||
|
last_updated = (string?)null
|
||||||
|
})
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task ResetBudgetPercentageAsync()
|
||||||
|
{
|
||||||
|
await SetEntityStateSafe(BudgetPercentageEntityId, "0").ConfigureAwait(false);
|
||||||
|
|
||||||
|
await SetEntityAttributesSafe(BudgetPercentageEntityId, new
|
||||||
|
{
|
||||||
|
unit_of_measurement = "%",
|
||||||
|
friendly_name = "Budget usage",
|
||||||
|
last_updated = (string?)null
|
||||||
|
})
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task ResetBudgetExhaustedAsync()
|
||||||
|
{
|
||||||
|
await SetEntityStateSafe(BudgetExhaustedEntityId, "off").ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task ResetSessionCountAsync()
|
||||||
|
{
|
||||||
|
await SetEntityStateSafe(SessionCountEntityId, "0").ConfigureAwait(false);
|
||||||
|
|
||||||
|
await SetEntityAttributesSafe(SessionCountEntityId, new
|
||||||
|
{
|
||||||
|
friendly_name = "Heating sessions today",
|
||||||
|
last_updated = (string?)null
|
||||||
|
})
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task ResetBudgetOverrideAsync()
|
||||||
|
{
|
||||||
|
await SetEntityStateSafe(BudgetOverrideEntityId, "OFF").ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task ResetAutoManagementAsync()
|
||||||
|
{
|
||||||
|
await SetEntityStateSafe(AutoManagementEntityId, "ON").ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task UpdateWaterReadyAsync(BoilerMonitorUpdateContext ctx, string timestamp)
|
||||||
|
{
|
||||||
|
await SetEntityStateSafe(WaterReadyEntityId, ctx.WaterReady ? "yes" : "no").ConfigureAwait(false);
|
||||||
|
|
||||||
|
await SetEntityAttributesSafe(WaterReadyEntityId, new
|
||||||
|
{
|
||||||
|
boiler_switch_state = ctx.BoilerSwitchState ?? "unknown",
|
||||||
|
boiler_power_watts = ctx.BoilerPowerWatts,
|
||||||
|
cooldown_since = ctx.CooldownSince?.ToString("O", CultureInfo.InvariantCulture),
|
||||||
|
friendly_name = "Boiler water ready",
|
||||||
|
last_updated = timestamp
|
||||||
|
})
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task UpdateTodayRuntimeAsync(TimeSpan runTime, string formatted, string timestamp)
|
||||||
|
{
|
||||||
|
await SetEntityStateSafe(TodayRuntimeEntityId,
|
||||||
|
((int)runTime.TotalSeconds).ToString(CultureInfo.InvariantCulture))
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
|
||||||
|
await SetEntityAttributesSafe(TodayRuntimeEntityId, new
|
||||||
|
{
|
||||||
|
formatted,
|
||||||
|
friendly_name = "Today runtime",
|
||||||
|
last_updated = timestamp
|
||||||
|
})
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task UpdateRemainingTimeAsync(TimeSpan remaining,
|
||||||
|
string formatted,
|
||||||
|
double budgetHours,
|
||||||
|
string timestamp)
|
||||||
|
{
|
||||||
|
var remainingSeconds = Math.Max(0, (int)remaining.TotalSeconds);
|
||||||
|
|
||||||
|
await SetEntityStateSafe(RemainingTimeEntityId, remainingSeconds.ToString(CultureInfo.InvariantCulture))
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
|
||||||
|
await SetEntityAttributesSafe(RemainingTimeEntityId, new
|
||||||
|
{
|
||||||
|
formatted,
|
||||||
|
budget_hours = budgetHours,
|
||||||
|
friendly_name = "Remaining budget time",
|
||||||
|
last_updated = timestamp
|
||||||
|
})
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task UpdateBudgetPercentageAsync(double percentage, string timestamp)
|
||||||
|
{
|
||||||
|
var clampedPercentage = Math.Clamp(percentage, 0, 100);
|
||||||
|
|
||||||
|
await SetEntityStateSafe(BudgetPercentageEntityId,
|
||||||
|
((int)clampedPercentage).ToString(CultureInfo.InvariantCulture))
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
|
||||||
|
await SetEntityAttributesSafe(BudgetPercentageEntityId, new
|
||||||
|
{
|
||||||
|
unit_of_measurement = "%",
|
||||||
|
friendly_name = "Budget usage",
|
||||||
|
last_updated = timestamp
|
||||||
|
})
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task UpdateBudgetExhaustedAsync(bool exhausted)
|
||||||
|
{
|
||||||
|
await SetEntityStateSafe(BudgetExhaustedEntityId, exhausted ? "on" : "off").ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task UpdateSessionCountAsync(int sessionCount, string timestamp)
|
||||||
|
{
|
||||||
|
await SetEntityStateSafe(SessionCountEntityId, sessionCount.ToString(CultureInfo.InvariantCulture))
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
|
||||||
|
await SetEntityAttributesSafe(SessionCountEntityId, new
|
||||||
|
{
|
||||||
|
friendly_name = "Heating sessions today",
|
||||||
|
last_updated = timestamp
|
||||||
|
})
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task SetEntityStateSafe(string entityId, string state)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await entityManager.SetEntityState(entityId, state).ConfigureAwait(false);
|
||||||
|
|
||||||
|
if (logger.IsEnabled(LogLevel.Debug))
|
||||||
|
{
|
||||||
|
logger.LogDebug("Successfully set state for {EntityId}: {State}", entityId, state);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.LogError(ex, "Failed to set state for {EntityId} to {State}", entityId, state);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task SetEntityAttributesSafe(string entityId, object attributes)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await entityManager.SetEntityAttributes(entityId, attributes).ConfigureAwait(false);
|
||||||
|
|
||||||
|
if (logger.IsEnabled(LogLevel.Debug))
|
||||||
|
{
|
||||||
|
logger.LogDebug("Successfully set attributes for {EntityId}", entityId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.LogError(ex, "Failed to set attributes for {EntityId}", entityId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string FormatTimeSpan(TimeSpan ts)
|
||||||
|
{
|
||||||
|
var totalHours = (int)ts.TotalHours;
|
||||||
|
var minutes = ts.Minutes;
|
||||||
|
|
||||||
|
return $"{totalHours}h {minutes}m";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,633 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using System.Globalization;
|
||||||
|
using System.Reactive.Concurrency;
|
||||||
|
using System.Text.Json;
|
||||||
|
using BoilerMonitor.Models.Enums;
|
||||||
|
using BoilerMonitorManager.Interface;
|
||||||
|
using BoilerMonitorManager.Models;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
using NetDaemon.AppModel;
|
||||||
|
using NetDaemon.Extensions.MqttEntityManager;
|
||||||
|
using NetDaemon.Extensions.Scheduler;
|
||||||
|
using NetDaemon.HassModel;
|
||||||
|
using NetDaemon.HassModel.Entities;
|
||||||
|
using static BoilerMonitor.Models.BoilerMonitorConsts;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace BoilerMonitorManager;
|
||||||
|
|
||||||
|
[NetDaemonApp]
|
||||||
|
public sealed class BoilerMonitorInit
|
||||||
|
{
|
||||||
|
private readonly IBoilerControlService _boilerControlService;
|
||||||
|
private readonly IBoilerMonitorEntityService _entityService;
|
||||||
|
private readonly IHaContext _haContext;
|
||||||
|
private readonly ILogger<BoilerMonitorInit> _logger;
|
||||||
|
private readonly IMqttEntityManager _mqttEntityManager;
|
||||||
|
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 DateTimeOffset? _lastWaterReadyNotificationSentAt;
|
||||||
|
|
||||||
|
public BoilerMonitorInit(
|
||||||
|
IHaContext haContext,
|
||||||
|
ILogger<BoilerMonitorInit> logger,
|
||||||
|
IScheduler scheduler,
|
||||||
|
IMqttEntityManager mqttEntityManager,
|
||||||
|
IBoilerControlService boilerControlService,
|
||||||
|
IBoilerRunTimeTracker tracker,
|
||||||
|
IBoilerMonitorEntityService entityService,
|
||||||
|
IWaterReadyService waterReadyService,
|
||||||
|
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;
|
||||||
|
_logger = logger;
|
||||||
|
_scheduler = scheduler;
|
||||||
|
_mqttEntityManager = mqttEntityManager;
|
||||||
|
_boilerControlService = boilerControlService;
|
||||||
|
_tracker = tracker;
|
||||||
|
_entityService = entityService;
|
||||||
|
_waterReadyService = waterReadyService;
|
||||||
|
_options = options.Value;
|
||||||
|
_timeProvider = timeProvider;
|
||||||
|
|
||||||
|
if (startBackgroundScheduling)
|
||||||
|
{
|
||||||
|
_ = InitializeAndScheduleAsync();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task InitializeAndScheduleAsync()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await InitializeAsync();
|
||||||
|
await SubscribeToConfigCommandsAsync();
|
||||||
|
await SubscribeToSwitchCommandsAsync();
|
||||||
|
SchedulePeriodicPolling();
|
||||||
|
ScheduleMidnightReset();
|
||||||
|
ScheduleEndOfDayReminder();
|
||||||
|
SubscribeToSkipPriceCapChanges();
|
||||||
|
SubscribeToAutoManagementChanges();
|
||||||
|
SubscribeToShowerState();
|
||||||
|
SubscribeToCleanupButton();
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error during BoilerMonitor initialization and scheduling");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task InitializeAsync()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await Task.Delay(TimeSpan.FromSeconds(3));
|
||||||
|
|
||||||
|
if (_options.CleanupEntitiesOnStartup)
|
||||||
|
{
|
||||||
|
await _entityService.CleanupEntitiesAsync();
|
||||||
|
await _entityService.CreateEntitiesAsync();
|
||||||
|
await _entityService.ResetEntitiesAsync();
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
var persisted = _entityService.ReadPersistedState();
|
||||||
|
var persistedCooldown = _entityService.ReadPersistedCooldownTimestamp();
|
||||||
|
|
||||||
|
await _entityService.CreateEntitiesAsync();
|
||||||
|
|
||||||
|
if (persisted is not null)
|
||||||
|
{
|
||||||
|
_tracker.RestoreFromSnapshot();
|
||||||
|
|
||||||
|
if (persistedCooldown.HasValue)
|
||||||
|
{
|
||||||
|
_waterReadyService.RestoreCooldownState(persistedCooldown.Value);
|
||||||
|
}
|
||||||
|
|
||||||
|
await _entityService.ResetTransientEntitiesAsync();
|
||||||
|
|
||||||
|
if (_logger.IsEnabled(LogLevel.Information))
|
||||||
|
{
|
||||||
|
_logger.LogInformation(
|
||||||
|
"BoilerMonitor state restored from HA entities: runtime={Runtime}, sessions={Sessions}",
|
||||||
|
persisted.AccumulatedRunTime, persisted.SessionCount);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
await _entityService.ResetEntitiesAsync();
|
||||||
|
_logger.LogInformation("No persisted state found in HA entities, performing full entity reset");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await Task.Delay(TimeSpan.FromSeconds(5));
|
||||||
|
|
||||||
|
await PollAndUpdateAsync();
|
||||||
|
|
||||||
|
_logger.LogInformation("BoilerMonitor initialized");
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error initializing BoilerMonitor");
|
||||||
|
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void SchedulePeriodicPolling()
|
||||||
|
{
|
||||||
|
var now = DateTime.Now;
|
||||||
|
var currentSecondInInterval = (now.Minute * 60 + now.Second) % DefaultPollIntervalSeconds;
|
||||||
|
var secondsUntilNext = DefaultPollIntervalSeconds - currentSecondInInterval;
|
||||||
|
var delayUntilNext = TimeSpan.FromSeconds(secondsUntilNext);
|
||||||
|
var nextPollTime = now.Add(delayUntilNext);
|
||||||
|
|
||||||
|
if (_logger.IsEnabled(LogLevel.Information))
|
||||||
|
{
|
||||||
|
_logger.LogInformation("Scheduling BoilerMonitor polling every {Interval}s, first at {Time}",
|
||||||
|
DefaultPollIntervalSeconds, nextPollTime);
|
||||||
|
}
|
||||||
|
|
||||||
|
_scheduler.RunEvery(TimeSpan.FromSeconds(DefaultPollIntervalSeconds), nextPollTime,
|
||||||
|
() => _ = PollAndUpdateAsync());
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ScheduleMidnightReset()
|
||||||
|
{
|
||||||
|
_scheduler.ScheduleCron("0 0 * * *", () =>
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
_logger.LogInformation("Midnight reset: clearing boiler run time tracker and water ready cooldown");
|
||||||
|
_tracker.Reset();
|
||||||
|
_waterReadyService.ResetCooldown();
|
||||||
|
_lastWaterReadyNotificationSentAt = null;
|
||||||
|
_ = _entityService.ResetEntitiesAsync();
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error during midnight reset");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ScheduleEndOfDayReminder()
|
||||||
|
{
|
||||||
|
_scheduler.ScheduleCron("0 22 * * *", () =>
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var switchState = _haContext.GetState(SkipPriceCapEntityId);
|
||||||
|
|
||||||
|
if (!string.Equals(switchState?.State, SwitchOnState, StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_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.",
|
||||||
|
title = "Boiler reminder"
|
||||||
|
});
|
||||||
|
|
||||||
|
_logger.LogInformation("End-of-day reminder sent: skip price cap switch is still ON");
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error checking skip price cap reminder");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private void SubscribeToSkipPriceCapChanges()
|
||||||
|
{
|
||||||
|
var skipPriceCapSwitch = new Entity(_haContext, SkipPriceCapEntityId);
|
||||||
|
|
||||||
|
skipPriceCapSwitch.StateChanges()
|
||||||
|
.Subscribe(e =>
|
||||||
|
{
|
||||||
|
if (e.Old?.State == e.New?.State)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_logger.LogInformation("Skip price cap switch changed, triggering poll");
|
||||||
|
_ = PollAndUpdateAsync();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private void SubscribeToAutoManagementChanges()
|
||||||
|
{
|
||||||
|
var autoManagementSwitch = new Entity(_haContext, AutoManagementEntityId);
|
||||||
|
|
||||||
|
autoManagementSwitch.StateChanges()
|
||||||
|
.Subscribe(e =>
|
||||||
|
{
|
||||||
|
if (e.Old?.State == e.New?.State)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_logger.LogInformation("Automatic boiler control switch changed, triggering poll");
|
||||||
|
_ = PollAndUpdateAsync();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private void SubscribeToShowerState()
|
||||||
|
{
|
||||||
|
var showerStateSensor = new Entity(_haContext, ShowerStateEntityId);
|
||||||
|
|
||||||
|
showerStateSensor.StateChanges()
|
||||||
|
.Subscribe(e =>
|
||||||
|
{
|
||||||
|
if (!string.Equals(e.New?.State, ShowerActiveState, StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!_waterReadyService.IsInCooldown)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_logger.LogInformation("Shower detected as active, resetting water ready cooldown");
|
||||||
|
_waterReadyService.ResetCooldown();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private void SubscribeToCleanupButton()
|
||||||
|
{
|
||||||
|
var cleanupButton = new Entity(_haContext, CleanupButtonEntityId);
|
||||||
|
|
||||||
|
cleanupButton.StateChanges()
|
||||||
|
.Subscribe(_ =>
|
||||||
|
{
|
||||||
|
_logger.LogInformation("Cleanup button pressed, removing all BoilerMonitor entities");
|
||||||
|
Task.Run(HandleCleanupAsync);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task SubscribeToConfigCommandsAsync()
|
||||||
|
{
|
||||||
|
var configEntityIds = new[]
|
||||||
|
{
|
||||||
|
ConfigPowerEntityId,
|
||||||
|
ConfigSwitchEntityId,
|
||||||
|
ConfigPollIntervalEntityId,
|
||||||
|
ConfigHeatingThresholdEntityId
|
||||||
|
};
|
||||||
|
|
||||||
|
foreach (var entityId in configEntityIds)
|
||||||
|
{
|
||||||
|
var subscription = await _mqttEntityManager.PrepareCommandSubscriptionAsync(entityId).ConfigureAwait(false);
|
||||||
|
subscription.Subscribe(state => _ = HandleConfigCommandAsync(entityId, state));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task HandleConfigCommandAsync(string entityId, string? state)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (_logger.IsEnabled(LogLevel.Information))
|
||||||
|
{
|
||||||
|
_logger.LogInformation("Config entity {EntityId} received command: {Value}", entityId, state);
|
||||||
|
}
|
||||||
|
|
||||||
|
await _mqttEntityManager.SetStateAsync(entityId, state ?? string.Empty).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError(e, "Error handling command for entity {EntityId}", entityId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task SubscribeToSwitchCommandsAsync()
|
||||||
|
{
|
||||||
|
var switchEntityIds = new[]
|
||||||
|
{
|
||||||
|
SkipPriceCapEntityId,
|
||||||
|
BudgetOverrideEntityId,
|
||||||
|
AutoManagementEntityId
|
||||||
|
};
|
||||||
|
|
||||||
|
foreach (var entityId in switchEntityIds)
|
||||||
|
{
|
||||||
|
var subscription = await _mqttEntityManager.PrepareCommandSubscriptionAsync(entityId).ConfigureAwait(false);
|
||||||
|
subscription.Subscribe(state => _ = HandleSwitchCommandAsync(entityId, state));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task HandleSwitchCommandAsync(string entityId, string? state)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (_logger.IsEnabled(LogLevel.Information))
|
||||||
|
{
|
||||||
|
_logger.LogInformation("Switch {EntityId} received command: {Value}", entityId, state);
|
||||||
|
}
|
||||||
|
|
||||||
|
await _mqttEntityManager.SetStateAsync(entityId, state ?? string.Empty).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
_logger.LogError(e, "Error handling command for switch entity {EntityId}", entityId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task HandleCleanupAsync()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await _entityService.CleanupEntitiesAsync();
|
||||||
|
_cleanedUp = true;
|
||||||
|
_tracker.Reset();
|
||||||
|
_logger.LogInformation("BoilerMonitor cleanup complete. Entities removed, monitoring stopped");
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error during BoilerMonitor cleanup");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task PollAndUpdateAsync()
|
||||||
|
{
|
||||||
|
if (_cleanedUp)
|
||||||
|
{
|
||||||
|
_logger.LogDebug("BoilerMonitor is cleaned up, skipping poll");
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var config = ReadConfigFromHaEntities();
|
||||||
|
|
||||||
|
if (!config.IsFullyConfigured)
|
||||||
|
{
|
||||||
|
await _entityService.SetStatusAsync(StatusAwaitingConfiguration);
|
||||||
|
|
||||||
|
_logger.LogWarning(
|
||||||
|
"BoilerMonitor not fully configured (power={Power}, switch={Switch}, interval={Interval}, threshold={Threshold}). Awaiting configuration",
|
||||||
|
config.BoilerPowerEntityId, config.BoilerSwitchEntityId,
|
||||||
|
config.PollIntervalSeconds, config.HeatingPowerThresholdWatts);
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var boilerPowerWatts = ReadSensorDouble(config.BoilerPowerEntityId!);
|
||||||
|
var boilerSwitchState = _haContext.GetState(config.BoilerSwitchEntityId!)?.State;
|
||||||
|
|
||||||
|
var isHeating = boilerPowerWatts.HasValue &&
|
||||||
|
boilerPowerWatts.Value >= config.HeatingPowerThresholdWatts!.Value;
|
||||||
|
|
||||||
|
_tracker.RecordPollResult();
|
||||||
|
|
||||||
|
if (isHeating)
|
||||||
|
{
|
||||||
|
_waterReadyService.RecordHeatingObserved();
|
||||||
|
}
|
||||||
|
|
||||||
|
var cheapestIntervalsState = _haContext.GetState(NordPoolCheapestIntervalsEntityId);
|
||||||
|
var isNowCheap = ReadAttributeBool(cheapestIntervalsState, "is_now_cheap");
|
||||||
|
|
||||||
|
var budgetOverrideState = _haContext.GetState(BudgetOverrideEntityId)?.State;
|
||||||
|
var budgetOverride = string.Equals(budgetOverrideState, SwitchOnState, StringComparison.OrdinalIgnoreCase);
|
||||||
|
|
||||||
|
var skipPriceCapState = _haContext.GetState(SkipPriceCapEntityId)?.State;
|
||||||
|
var skipPriceCap = string.Equals(skipPriceCapState, SwitchOnState, StringComparison.OrdinalIgnoreCase);
|
||||||
|
|
||||||
|
var dailyHours = ReadSensorDouble(BoilerDailyHoursEntityId) ?? 1.0;
|
||||||
|
|
||||||
|
var waterReady = _waterReadyService.IsWaterReady(boilerSwitchState, boilerPowerWatts,
|
||||||
|
config.HeatingPowerThresholdWatts!.Value);
|
||||||
|
|
||||||
|
if (!_lastWaterReady && waterReady && !IsWithinNotificationCooldown())
|
||||||
|
{
|
||||||
|
_haContext.CallService("notify", "mobile_app_marius_phone", null, new
|
||||||
|
{
|
||||||
|
message = "Hot water is ready.",
|
||||||
|
title = "Boiler"
|
||||||
|
});
|
||||||
|
|
||||||
|
_lastWaterReadyNotificationSentAt = _timeProvider.GetUtcNow();
|
||||||
|
_logger.LogInformation("Water ready notification sent");
|
||||||
|
}
|
||||||
|
|
||||||
|
_lastWaterReady = waterReady;
|
||||||
|
|
||||||
|
var snapshot = _tracker.GetSnapshot();
|
||||||
|
var budgetTimeSpan = TimeSpan.FromHours(dailyHours);
|
||||||
|
var remainingTime = budgetTimeSpan - snapshot.AccumulatedRunTime;
|
||||||
|
|
||||||
|
if (remainingTime < TimeSpan.Zero)
|
||||||
|
{
|
||||||
|
remainingTime = TimeSpan.Zero;
|
||||||
|
}
|
||||||
|
|
||||||
|
var budgetPercentage = budgetTimeSpan.TotalSeconds > 0
|
||||||
|
? snapshot.AccumulatedRunTime.TotalSeconds / budgetTimeSpan.TotalSeconds * 100.0
|
||||||
|
: 0.0;
|
||||||
|
|
||||||
|
var budgetExhausted = snapshot.AccumulatedRunTime >= budgetTimeSpan;
|
||||||
|
|
||||||
|
var effectiveIsNowCheap = isNowCheap || skipPriceCap;
|
||||||
|
|
||||||
|
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!);
|
||||||
|
}
|
||||||
|
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
|
||||||
|
{
|
||||||
|
TodayRunTime = snapshot.AccumulatedRunTime,
|
||||||
|
RemainingTime = remainingTime,
|
||||||
|
BudgetPercentage = budgetPercentage,
|
||||||
|
BudgetExhausted = budgetExhausted,
|
||||||
|
SessionCount = snapshot.SessionCount,
|
||||||
|
BudgetHours = dailyHours,
|
||||||
|
WaterReady = waterReady,
|
||||||
|
BoilerSwitchState = boilerSwitchState,
|
||||||
|
BoilerPowerWatts = boilerPowerWatts,
|
||||||
|
CooldownSince = _waterReadyService.WaterReadySince
|
||||||
|
};
|
||||||
|
|
||||||
|
await _entityService.UpdateEntitiesAsync(context);
|
||||||
|
|
||||||
|
if (_logger.IsEnabled(LogLevel.Debug))
|
||||||
|
{
|
||||||
|
_logger.LogDebug(
|
||||||
|
"Poll complete: power={Power}W, heating={Heating}, runtime={Runtime}, budget={Budget}%",
|
||||||
|
boilerPowerWatts, isHeating, snapshot.AccumulatedRunTime, budgetPercentage);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error during BoilerMonitor poll and update");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ExecuteBoilerAction(BoilerAction action, string switchEntityId)
|
||||||
|
{
|
||||||
|
switch (action)
|
||||||
|
{
|
||||||
|
case BoilerAction.TurnOn:
|
||||||
|
_haContext.CallService("switch", "turn_on", ServiceTarget.FromEntity(switchEntityId));
|
||||||
|
_waterReadyService.NotifyTurnedOn();
|
||||||
|
|
||||||
|
break;
|
||||||
|
|
||||||
|
case BoilerAction.TurnOff:
|
||||||
|
_haContext.CallService("switch", "turn_off", ServiceTarget.FromEntity(switchEntityId));
|
||||||
|
|
||||||
|
break;
|
||||||
|
|
||||||
|
case BoilerAction.NoChange:
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
throw new ArgumentOutOfRangeException(nameof(action), action, null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private BoilerMonitorConfig ReadConfigFromHaEntities()
|
||||||
|
{
|
||||||
|
var powerEntityId = _haContext.GetState(ConfigPowerEntityId)?.State;
|
||||||
|
var switchEntityId = _haContext.GetState(ConfigSwitchEntityId)?.State;
|
||||||
|
|
||||||
|
int? pollInterval = null;
|
||||||
|
var pollIntervalState = _haContext.GetState(ConfigPollIntervalEntityId)?.State;
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(pollIntervalState) && double.TryParse(pollIntervalState, CultureInfo.InvariantCulture, out var pollIntervalValue) && pollIntervalValue > 0)
|
||||||
|
{
|
||||||
|
pollInterval = (int)pollIntervalValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
double? heatingThreshold = null;
|
||||||
|
var thresholdState = _haContext.GetState(ConfigHeatingThresholdEntityId)?.State;
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(thresholdState) && double.TryParse(thresholdState, CultureInfo.InvariantCulture, out var thresholdValue) && thresholdValue > 0)
|
||||||
|
{
|
||||||
|
heatingThreshold = thresholdValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
return new BoilerMonitorConfig
|
||||||
|
{
|
||||||
|
BoilerPowerEntityId = string.IsNullOrWhiteSpace(powerEntityId) ? null : powerEntityId.Trim(),
|
||||||
|
BoilerSwitchEntityId = string.IsNullOrWhiteSpace(switchEntityId) ? null : switchEntityId.Trim(),
|
||||||
|
PollIntervalSeconds = pollInterval,
|
||||||
|
HeatingPowerThresholdWatts = heatingThreshold
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private double? ReadSensorDouble(string entityId)
|
||||||
|
{
|
||||||
|
var state = _haContext.GetState(entityId);
|
||||||
|
|
||||||
|
if (state?.State is null or "unavailable" or "unknown")
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return double.TryParse(state.State, CultureInfo.InvariantCulture, out var value) ? value : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool ReadAttributeBool(EntityState? entityState, string attributeName)
|
||||||
|
{
|
||||||
|
if (entityState?.Attributes is not IDictionary<string, object> attributes)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (attributes.TryGetValue(attributeName, out var value))
|
||||||
|
{
|
||||||
|
return value switch
|
||||||
|
{
|
||||||
|
bool b => b,
|
||||||
|
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
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
// Attribute not found or not parseable
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool IsWithinNotificationCooldown()
|
||||||
|
{
|
||||||
|
if (_lastWaterReadyNotificationSentAt is null)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
var elapsed = _timeProvider.GetUtcNow() - _lastWaterReadyNotificationSentAt.Value;
|
||||||
|
|
||||||
|
return elapsed < WaterReadyNotificationCooldown;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using BoilerMonitorManager.Interface;
|
||||||
|
using BoilerMonitorManager.Models;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using NetDaemon.AppModel;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace BoilerMonitorManager;
|
||||||
|
|
||||||
|
public static class BoilerMonitorServiceRegistration
|
||||||
|
{
|
||||||
|
public static IServiceCollection AddBoilerMonitor(this IServiceCollection services, IConfiguration configuration)
|
||||||
|
{
|
||||||
|
var options = configuration
|
||||||
|
.GetSection(BoilerMonitorOptions.SectionName)
|
||||||
|
.Get<BoilerMonitorOptions>() ??
|
||||||
|
new BoilerMonitorOptions();
|
||||||
|
|
||||||
|
if (!options.Enabled)
|
||||||
|
{
|
||||||
|
return services;
|
||||||
|
}
|
||||||
|
|
||||||
|
services
|
||||||
|
.AddNetDaemonApp<BoilerMonitorInit>()
|
||||||
|
.AddSingleton<IBoilerControlService, BoilerControlService>()
|
||||||
|
.AddTransient<IBoilerMonitorEntityService, BoilerMonitorEntityService>()
|
||||||
|
.AddSingleton<IWaterReadyService, WaterReadyService>()
|
||||||
|
.AddSingleton<IBoilerRunTimeTracker, BoilerRunTimeTracker>();
|
||||||
|
|
||||||
|
return services;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using BoilerMonitorManager.Interface;
|
||||||
|
using BoilerMonitorManager.Models;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace BoilerMonitorManager;
|
||||||
|
|
||||||
|
public class BoilerRunTimeTracker : IBoilerRunTimeTracker
|
||||||
|
{
|
||||||
|
public void RecordPollResult()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public RunTimeSnapshot GetSnapshot()
|
||||||
|
{
|
||||||
|
return new RunTimeSnapshot
|
||||||
|
{
|
||||||
|
AccumulatedRunTime = TimeSpan.Zero,
|
||||||
|
SessionCount = 0
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Reset()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public void RestoreFromSnapshot()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using BoilerMonitor.Models.Enums;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace BoilerMonitorManager.Interface;
|
||||||
|
|
||||||
|
public interface IBoilerControlService
|
||||||
|
{
|
||||||
|
BoilerAction DetermineAction(
|
||||||
|
bool isNowCheap,
|
||||||
|
bool waterReady,
|
||||||
|
string? currentSwitchState,
|
||||||
|
bool budgetExhausted,
|
||||||
|
bool budgetOverride);
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using BoilerMonitorManager.Models;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace BoilerMonitorManager.Interface;
|
||||||
|
|
||||||
|
public interface IBoilerMonitorEntityService
|
||||||
|
{
|
||||||
|
Task CreateEntitiesAsync(CancellationToken cancellationToken = default);
|
||||||
|
Task ResetEntitiesAsync(CancellationToken cancellationToken = default);
|
||||||
|
Task ResetTransientEntitiesAsync(CancellationToken cancellationToken = default);
|
||||||
|
Task UpdateEntitiesAsync(BoilerMonitorUpdateContext context, CancellationToken cancellationToken = default);
|
||||||
|
Task CleanupEntitiesAsync(CancellationToken cancellationToken = default);
|
||||||
|
Task SetStatusAsync(string status);
|
||||||
|
PersistedBoilerState? ReadPersistedState();
|
||||||
|
DateTimeOffset? ReadPersistedCooldownTimestamp();
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using BoilerMonitorManager.Models;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace BoilerMonitorManager.Interface;
|
||||||
|
|
||||||
|
public interface IBoilerRunTimeTracker
|
||||||
|
{
|
||||||
|
void RecordPollResult();
|
||||||
|
RunTimeSnapshot GetSnapshot();
|
||||||
|
void Reset();
|
||||||
|
void RestoreFromSnapshot();
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
namespace BoilerMonitorManager.Interface;
|
||||||
|
|
||||||
|
public interface IWaterReadyService
|
||||||
|
{
|
||||||
|
bool IsInCooldown { get; }
|
||||||
|
DateTimeOffset? WaterReadySince { get; }
|
||||||
|
bool IsWaterReady(string? switchState, double? powerWatts, double heatingThresholdWatts);
|
||||||
|
void NotifyTurnedOn();
|
||||||
|
void RecordHeatingObserved();
|
||||||
|
void ResetCooldown();
|
||||||
|
void RestoreCooldownState(DateTimeOffset waterReadySince);
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
namespace BoilerMonitorManager.Models;
|
||||||
|
|
||||||
|
public record BoilerMonitorConfig
|
||||||
|
{
|
||||||
|
public string? BoilerPowerEntityId { get; init; }
|
||||||
|
public string? BoilerSwitchEntityId { get; init; }
|
||||||
|
public int? PollIntervalSeconds { get; init; }
|
||||||
|
public double? HeatingPowerThresholdWatts { get; init; }
|
||||||
|
|
||||||
|
public bool IsFullyConfigured => !string.IsNullOrWhiteSpace(BoilerPowerEntityId) &&
|
||||||
|
!string.IsNullOrWhiteSpace(BoilerSwitchEntityId) &&
|
||||||
|
PollIntervalSeconds is > 0 &&
|
||||||
|
HeatingPowerThresholdWatts is > 0;
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
namespace BoilerMonitorManager.Models;
|
||||||
|
|
||||||
|
public sealed class BoilerMonitorOptions
|
||||||
|
{
|
||||||
|
public const string SectionName = "BoilerMonitor";
|
||||||
|
|
||||||
|
public bool Enabled { get; init; } = true;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// When true, removes existing BoilerMonitor MQTT entities before recreating them on app startup.
|
||||||
|
/// Manual cleanup (e.g. HA button) is not affected.
|
||||||
|
/// </summary>
|
||||||
|
public bool CleanupEntitiesOnStartup { get; init; } = true;
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
namespace BoilerMonitorManager.Models;
|
||||||
|
|
||||||
|
public record BoilerMonitorUpdateContext
|
||||||
|
{
|
||||||
|
public required TimeSpan TodayRunTime { get; init; }
|
||||||
|
public required TimeSpan RemainingTime { get; init; }
|
||||||
|
public required double BudgetPercentage { get; init; }
|
||||||
|
public required bool BudgetExhausted { get; init; }
|
||||||
|
public required int SessionCount { get; init; }
|
||||||
|
public required double BudgetHours { get; init; }
|
||||||
|
public required bool WaterReady { get; init; }
|
||||||
|
public required string? BoilerSwitchState { get; init; }
|
||||||
|
public required double? BoilerPowerWatts { get; init; }
|
||||||
|
public required DateTimeOffset? CooldownSince { get; init; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
namespace BoilerMonitorManager.Models;
|
||||||
|
|
||||||
|
public record PersistedBoilerState
|
||||||
|
{
|
||||||
|
public required TimeSpan AccumulatedRunTime { get; init; }
|
||||||
|
public required int SessionCount { get; init; }
|
||||||
|
public required string? SkipPriceCapState { get; init; }
|
||||||
|
public required string? BudgetOverrideState { get; init; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
namespace BoilerMonitorManager.Models;
|
||||||
|
|
||||||
|
public record RunTimeSnapshot
|
||||||
|
{
|
||||||
|
public required TimeSpan AccumulatedRunTime { get; init; }
|
||||||
|
public required int SessionCount { get; init; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,183 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using BoilerMonitor.Models;
|
||||||
|
using BoilerMonitorManager.Interface;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace BoilerMonitorManager;
|
||||||
|
|
||||||
|
public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimeProvider timeProvider) : IWaterReadyService
|
||||||
|
{
|
||||||
|
private const string SwitchOnState = "on";
|
||||||
|
private readonly Lock _lock = new Lock();
|
||||||
|
private int _consecutiveBelowThresholdCount;
|
||||||
|
private bool _hasObservedHeating;
|
||||||
|
private DateTimeOffset? _waterReadySince;
|
||||||
|
|
||||||
|
public bool IsInCooldown
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
return IsWithinCooldownPeriod();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public DateTimeOffset? WaterReadySince
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
return _waterReadySince;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool IsWaterReady(string? switchState, double? powerWatts, double heatingThresholdWatts)
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
if (IsWithinCooldownPeriod())
|
||||||
|
{
|
||||||
|
if (logger.IsEnabled(LogLevel.Debug))
|
||||||
|
{
|
||||||
|
logger.LogDebug("Water ready cooldown active (since {Since}), suppressing turn-on",
|
||||||
|
_waterReadySince);
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (switchState is null || powerWatts is null)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!string.Equals(switchState, SwitchOnState, StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
if (!_hasObservedHeating)
|
||||||
|
{
|
||||||
|
if (logger.IsEnabled(LogLevel.Debug))
|
||||||
|
{
|
||||||
|
logger.LogDebug("Ignoring power reading ({PowerWatts}W) — boiler has not been observed heating yet",
|
||||||
|
powerWatts.Value);
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (powerWatts.Value >= heatingThresholdWatts)
|
||||||
|
{
|
||||||
|
_consecutiveBelowThresholdCount = 0;
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
_consecutiveBelowThresholdCount++;
|
||||||
|
|
||||||
|
if (_consecutiveBelowThresholdCount < BoilerMonitorConsts.ConsecutiveReadingsRequired)
|
||||||
|
{
|
||||||
|
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();
|
||||||
|
|
||||||
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
|
{
|
||||||
|
logger.LogInformation(
|
||||||
|
"Water detected as ready after {Count} consecutive readings, cooldown active until shower or midnight reset",
|
||||||
|
_consecutiveBelowThresholdCount);
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void NotifyTurnedOn()
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
_hasObservedHeating = false;
|
||||||
|
_consecutiveBelowThresholdCount = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
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()
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
_waterReadySince = null;
|
||||||
|
_consecutiveBelowThresholdCount = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.LogInformation("Water ready cooldown has been reset");
|
||||||
|
}
|
||||||
|
|
||||||
|
public void RestoreCooldownState(DateTimeOffset waterReadySince)
|
||||||
|
{
|
||||||
|
lock (_lock)
|
||||||
|
{
|
||||||
|
var todayMidnightUtc = new DateTimeOffset(timeProvider.GetUtcNow().Date, TimeSpan.Zero);
|
||||||
|
|
||||||
|
if (waterReadySince < todayMidnightUtc)
|
||||||
|
{
|
||||||
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
|
{
|
||||||
|
logger.LogInformation("Persisted cooldown is from a previous day ({Since}), not restoring",
|
||||||
|
waterReadySince);
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_waterReadySince = waterReadySince;
|
||||||
|
|
||||||
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
|
{
|
||||||
|
logger.LogInformation("Restored water ready cooldown from {Since}", waterReadySince);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool IsWithinCooldownPeriod()
|
||||||
|
{
|
||||||
|
return _waterReadySince is not null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
namespace BoilerMonitor.Models;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Boiler scheduling configuration read from Home Assistant entity state.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class BoilerConfig
|
||||||
|
{
|
||||||
|
public required int IntervalCount { get; init; }
|
||||||
|
|
||||||
|
public required double PriceCap { get; init; }
|
||||||
|
|
||||||
|
public required DateTime Deadline { get; init; }
|
||||||
|
|
||||||
|
public required bool SkipPriceCap { get; init; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<RootNamespace>BoilerMonitor.Models</RootNamespace>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\HomeAssistant.Models\HomeAssistant.Models.csproj"/>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="NetDaemon.Extensions.Mqtt" Version="26.43.1"/>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
namespace BoilerMonitor.Models;
|
||||||
|
|
||||||
|
public static class BoilerMonitorConsts
|
||||||
|
{
|
||||||
|
public const int DefaultPollIntervalSeconds = 30;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Power threshold in watts below which the boiler is considered to have finished heating (water ready).
|
||||||
|
/// Also used as the default threshold above which the boiler is considered actively heating.
|
||||||
|
/// </summary>
|
||||||
|
public const double DefaultHeatingPowerThresholdWatts = 5.0;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Number of consecutive below-threshold power readings required before
|
||||||
|
/// declaring water as ready. Prevents false positives from transient sensor glitches.
|
||||||
|
/// At 30s poll interval, a value of 2 means 60s of confirmed low power.
|
||||||
|
/// </summary>
|
||||||
|
public const int ConsecutiveReadingsRequired = 2;
|
||||||
|
|
||||||
|
public const string ShowerStateEntityId = "sensor.showermonitor_state";
|
||||||
|
public const string ShowerActiveState = "Active";
|
||||||
|
|
||||||
|
public const int MinPollIntervalSeconds = 5;
|
||||||
|
public const int MaxPollIntervalSeconds = 300;
|
||||||
|
public const int PollIntervalStepSeconds = 5;
|
||||||
|
|
||||||
|
public const double MinHeatingThresholdWatts = 1.0;
|
||||||
|
public const double MaxHeatingThresholdWatts = 100.0;
|
||||||
|
public const double HeatingThresholdStepWatts = 0.5;
|
||||||
|
|
||||||
|
public const string ConfigPowerEntityId = "text.boilermonitor_config_power_entity_id";
|
||||||
|
public const string ConfigSwitchEntityId = "text.boilermonitor_config_switch_entity_id";
|
||||||
|
public const string ConfigPollIntervalEntityId = "number.boilermonitor_config_poll_interval";
|
||||||
|
public const string ConfigHeatingThresholdEntityId = "number.boilermonitor_config_heating_threshold";
|
||||||
|
|
||||||
|
public const string CleanupButtonEntityId = "button.boilermonitor_cleanup";
|
||||||
|
public const string StatusEntityId = "sensor.boilermonitor_status";
|
||||||
|
|
||||||
|
public const string WaterReadyEntityId = "sensor.boilermonitor_water_ready";
|
||||||
|
public const string SkipPriceCapEntityId = "switch.boilermonitor_skip_price_cap";
|
||||||
|
public const string TodayRuntimeEntityId = "sensor.boilermonitor_today_runtime";
|
||||||
|
public const string RemainingTimeEntityId = "sensor.boilermonitor_remaining_time";
|
||||||
|
public const string BudgetPercentageEntityId = "sensor.boilermonitor_budget_percentage";
|
||||||
|
public const string BudgetExhaustedEntityId = "binary_sensor.boilermonitor_budget_exhausted";
|
||||||
|
public const string SessionCountEntityId = "sensor.boilermonitor_session_count";
|
||||||
|
public const string BudgetOverrideEntityId = "switch.boilermonitor_budget_override";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// When on, the daemon may call the configured boiler switch per price/budget/water-ready logic.
|
||||||
|
/// When off, monitoring continues but automatic turn_on/turn_off calls are suppressed (manual control).
|
||||||
|
/// </summary>
|
||||||
|
public const string AutoManagementEntityId = "switch.boilermonitor_auto_management";
|
||||||
|
|
||||||
|
public const string NordPoolCheapestIntervalsEntityId = "sensor.nordpool_cheapest_intervals";
|
||||||
|
|
||||||
|
public const string BoilerDailyHoursEntityId = "input_number.boiler_daily_hours";
|
||||||
|
public const string BoilerPriceCapEntityId = "input_number.boiler_price_cap";
|
||||||
|
public const string BoilerReadyByEntityId = "input_datetime.boiler_ready_by";
|
||||||
|
|
||||||
|
public const string StatusConfigured = "configured";
|
||||||
|
public const string StatusAwaitingConfiguration = "awaiting_configuration";
|
||||||
|
|
||||||
|
public const string SwitchOnState = "on";
|
||||||
|
|
||||||
|
public const string SwitchOffState = "off";
|
||||||
|
|
||||||
|
public const string DeviceIdentifier = "boiler_monitor";
|
||||||
|
public const string DeviceName = "Boiler Monitor";
|
||||||
|
public const string DeviceManufacturer = "HomeAssistant App Daemon";
|
||||||
|
|
||||||
|
/// <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);
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using HomeAssistant.Models;
|
||||||
|
using NetDaemon.Extensions.MqttEntityManager;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace BoilerMonitor.Models;
|
||||||
|
|
||||||
|
public class BoilerMonitorEntity : EntityCreateModel
|
||||||
|
{
|
||||||
|
public BoilerMonitorEntity(string domain, string identifier, string name)
|
||||||
|
{
|
||||||
|
Domain = domain;
|
||||||
|
Identifier = identifier;
|
||||||
|
EntityId = $"{Domain}.{Identifier}";
|
||||||
|
Name = string.IsNullOrWhiteSpace(name) ? identifier : name;
|
||||||
|
|
||||||
|
Options = new EntityCreationOptions
|
||||||
|
{
|
||||||
|
UniqueId = EntityId,
|
||||||
|
Name = Name
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private string Domain { get; }
|
||||||
|
private string Identifier { get; }
|
||||||
|
private string Name { get; }
|
||||||
|
}
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
namespace NordPoolManager.Models.Enums;
|
namespace BoilerMonitor.Models.Enums;
|
||||||
|
|
||||||
public enum BoilerAction
|
public enum BoilerAction
|
||||||
{
|
{
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
namespace BoilerMonitor.Models;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Reads the boiler scheduling configuration from Home Assistant entity state.
|
||||||
|
/// </summary>
|
||||||
|
public interface IBoilerConfigReader
|
||||||
|
{
|
||||||
|
BoilerConfig ReadConfig();
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -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}";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<TargetFramework>net10.0</TargetFramework>
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
@@ -7,14 +7,14 @@
|
|||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="NetDaemon.AppModel" Version="26.3.0" />
|
<PackageReference Include="NetDaemon.AppModel" Version="26.43.1"/>
|
||||||
<PackageReference Include="NetDaemon.Extensions.Mqtt" Version="26.3.0" />
|
<PackageReference Include="NetDaemon.Extensions.Mqtt" Version="26.43.1"/>
|
||||||
<PackageReference Include="NetDaemon.Runtime" Version="26.3.0" />
|
<PackageReference Include="NetDaemon.Runtime" Version="26.43.1"/>
|
||||||
<PackageReference Include="NetDaemon.HassModel" Version="26.3.0" />
|
<PackageReference Include="NetDaemon.HassModel" Version="26.43.1"/>
|
||||||
<PackageReference Include="NetDaemon.Client" Version="26.3.0" />
|
<PackageReference Include="NetDaemon.Client" Version="26.43.1"/>
|
||||||
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.3.0" />
|
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.43.1"/>
|
||||||
<PackageReference Include="NetDaemon.Extensions.Logging" Version="26.3.0" />
|
<PackageReference Include="NetDaemon.Extensions.Logging" Version="26.43.1"/>
|
||||||
<PackageReference Include="NetDaemon.Extensions.Tts" Version="26.3.0" />
|
<PackageReference Include="NetDaemon.Extensions.Tts" Version="26.43.1"/>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
|||||||
@@ -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,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; }
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<TargetFramework>net10.0</TargetFramework>
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
@@ -7,7 +7,7 @@
|
|||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="NetDaemon.Extensions.Mqtt" Version="26.3.0" />
|
<PackageReference Include="NetDaemon.Extensions.Mqtt" Version="26.43.1"/>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
"isRoot": true,
|
"isRoot": true,
|
||||||
"tools": {
|
"tools": {
|
||||||
"netdaemon.hassmodel.codegen": {
|
"netdaemon.hassmodel.codegen": {
|
||||||
"version": "26.3.0",
|
"version": "26.11.0",
|
||||||
"commands": [
|
"commands": [
|
||||||
"nd-codegen"
|
"nd-codegen"
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -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,28 +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.3.0" />
|
<PackageReference Include="NetDaemon.AppModel" Version="26.43.1"/>
|
||||||
<PackageReference Include="NetDaemon.Runtime" Version="26.3.0" />
|
<PackageReference Include="NetDaemon.Runtime" Version="26.43.1"/>
|
||||||
<PackageReference Include="NetDaemon.HassModel" Version="26.3.0" />
|
<PackageReference Include="NetDaemon.HassModel" Version="26.43.1"/>
|
||||||
<PackageReference Include="NetDaemon.Client" Version="26.3.0" />
|
<PackageReference Include="NetDaemon.Client" Version="26.43.1"/>
|
||||||
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.3.0" />
|
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.43.1"/>
|
||||||
<PackageReference Include="NetDaemon.Extensions.Logging" Version="26.3.0" />
|
<PackageReference Include="NetDaemon.Extensions.Logging" Version="26.43.1"/>
|
||||||
<PackageReference Include="NetDaemon.Extensions.Tts" Version="26.3.0" />
|
<PackageReference Include="NetDaemon.Extensions.Tts" Version="26.43.1"/>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\BoilerMonitor.Manager\BoilerMonitor.Manager.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.Models\ShowerMonitor.Models.csproj"/>
|
||||||
|
<ProjectReference Include="..\LightMonitor.Manager\LightMonitor.Manager.csproj"/>
|
||||||
|
<ProjectReference Include="..\LightMonitor.Models\LightMonitor.Models.csproj"/>
|
||||||
|
<ProjectReference Include="..\BatteryMonitor.Manager\BatteryMonitor.Manager.csproj"/>
|
||||||
|
<ProjectReference Include="..\BatteryMonitor.Models\BatteryMonitor.Models.csproj"/>
|
||||||
|
<ProjectReference Include="..\LeakMonitor.Manager\LeakMonitor.Manager.csproj"/>
|
||||||
</ItemGroup>
|
</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;
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -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,20 +1,11 @@
|
|||||||
{
|
{
|
||||||
"Serilog": {
|
"Serilog": {
|
||||||
"MinimumLevel": {
|
"MinimumLevel": {
|
||||||
"Default": "Warning",
|
"Default": "Warning"
|
||||||
"Override": {
|
|
||||||
"System.Net.Http.HttpClient": "Warning",
|
|
||||||
"NordPoolManager": "Information",
|
|
||||||
"PowerMonitorManager": "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}"
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@@ -26,11 +17,68 @@
|
|||||||
"OutputFile": "HomeAssistantGenerated.cs",
|
"OutputFile": "HomeAssistantGenerated.cs",
|
||||||
"UseAttributeBaseClasses": "false"
|
"UseAttributeBaseClasses": "false"
|
||||||
},
|
},
|
||||||
|
"NordPool": {
|
||||||
|
"CleanupEntitiesOnStartup": false
|
||||||
|
},
|
||||||
|
"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": 5,
|
||||||
|
"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"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"BatteryMonitor": {
|
||||||
|
"Enabled": true,
|
||||||
|
"BatteryThresholdPercent": 5
|
||||||
|
},
|
||||||
|
"LeakMonitor": {
|
||||||
|
"Enabled": true,
|
||||||
|
"SensorEntityIds": [
|
||||||
|
"binary_sensor.aquarium_leak_sensor",
|
||||||
|
"binary_sensor.boiler_moisture"
|
||||||
|
],
|
||||||
|
"NotificationCooldownMinutes": 5
|
||||||
|
},
|
||||||
"PowerMonitor": {
|
"PowerMonitor": {
|
||||||
|
"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;
|
||||||
@@ -13,51 +24,58 @@ using NetDaemon.Extensions.Scheduler;
|
|||||||
using NetDaemon.Extensions.Tts;
|
using NetDaemon.Extensions.Tts;
|
||||||
using NetDaemon.Runtime;
|
using NetDaemon.Runtime;
|
||||||
using NordPoolManager;
|
using NordPoolManager;
|
||||||
using NordPoolManager.Interface;
|
using NordPoolManager.Models;
|
||||||
using PowerMonitorManager;
|
using PowerMonitorManager;
|
||||||
using PowerMonitorManager.Interface;
|
|
||||||
using PowerMonitorManager.Models;
|
using PowerMonitorManager.Models;
|
||||||
|
using ShowerMonitorManager;
|
||||||
|
using ShowerMonitorManager.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>()
|
||||||
.AddScoped<INordPoolPriceService, NordPoolPriceService>()
|
.AddSingleton(TimeProvider.System)
|
||||||
.AddTransient<INordPoolEntityService, NordPoolEntityService>()
|
.AddScoped<IBoilerConfigReader, BoilerConfigReader>()
|
||||||
.AddSingleton<ICheapestIntervalsFinder, CheapestIntervalsFinder>()
|
.Configure<NordPoolOptions>(context.Configuration.GetSection(NordPoolOptions.SectionName))
|
||||||
.AddSingleton<IBoilerControlService, BoilerControlService>()
|
.AddNordPool()
|
||||||
.Configure<PowerMonitorOptions>(
|
.Configure<PowerMonitorOptions>(context.Configuration.GetSection(PowerMonitorOptions.SectionName))
|
||||||
context.Configuration.GetSection(PowerMonitorOptions.SectionName))
|
.AddPowerMonitor()
|
||||||
.AddNetDaemonApp<PowerMonitorInit>()
|
.Configure<BoilerMonitorOptions>(context.Configuration.GetSection(BoilerMonitorOptions.SectionName))
|
||||||
.AddScoped<IPowerSensorDiscoveryService, PowerSensorDiscoveryService>()
|
.AddBoilerMonitor(context.Configuration)
|
||||||
.AddSingleton<IOtherPowerCalculationService, OtherPowerCalculationService>()
|
.Configure<ShowerMonitorOptions>(context.Configuration.GetSection(ShowerMonitorOptions.SectionName))
|
||||||
.AddSingleton<IPowerCostCalculationService, PowerCostCalculationService>()
|
.AddShowerMonitor(context.Configuration)
|
||||||
.AddTransient<IPowerMonitorEntityService, PowerMonitorEntityService>()
|
.Configure<LightMonitorOptions>(context.Configuration.GetSection(LightMonitorOptions.SectionName))
|
||||||
)
|
.AddLightMonitor(context.Configuration)
|
||||||
.Build()
|
.Configure<BatteryMonitorOptions>(context.Configuration.GetSection(BatteryMonitorOptions.SectionName))
|
||||||
.RunAsync()
|
.AddBatteryMonitor(context.Configuration)
|
||||||
.ConfigureAwait(false);
|
.Configure<LeakMonitorOptions>(context.Configuration.GetSection(LeakMonitorOptions.SectionName))
|
||||||
|
.AddLeakMonitor(context.Configuration);
|
||||||
|
})
|
||||||
|
.Build();
|
||||||
|
|
||||||
|
await app.RunAsync().ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -20,6 +20,42 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PowerMonitor.Manager", "Pow
|
|||||||
EndProject
|
EndProject
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PowerMonitor.Manager.Tests", "PowerMonitor.Manager.Tests\PowerMonitor.Manager.Tests.csproj", "{1F613F65-5F3C-41E6-B86B-774301D80E42}"
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PowerMonitor.Manager.Tests", "PowerMonitor.Manager.Tests\PowerMonitor.Manager.Tests.csproj", "{1F613F65-5F3C-41E6-B86B-774301D80E42}"
|
||||||
EndProject
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BoilerMonitor.Models", "BoilerMonitor.Models\BoilerMonitor.Models.csproj", "{72331F53-884D-42A1-8EEA-8CC83FFAB623}"
|
||||||
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BoilerMonitor.Manager", "BoilerMonitor.Manager\BoilerMonitor.Manager.csproj", "{488964A2-C7A2-45C9-9CDB-98515AFD7242}"
|
||||||
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BoilerMonitor.Manager.Tests", "BoilerMonitor.Manager.Tests\BoilerMonitor.Manager.Tests.csproj", "{CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}"
|
||||||
|
EndProject
|
||||||
|
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Testing", "Testing", "{95E98121-7DA4-4085-A8E3-B0430628452F}"
|
||||||
|
EndProject
|
||||||
|
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Models", "Models", "{48492269-2B47-43FE-BC14-A901054EE5AE}"
|
||||||
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ShowerMonitor.Models", "ShowerMonitor.Models\ShowerMonitor.Models.csproj", "{DAD0BDF9-2A6D-48AD-B714-38D237E97285}"
|
||||||
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ShowerMonitor.Manager", "ShowerMonitor.Manager\ShowerMonitor.Manager.csproj", "{8D05B406-B94B-4D6B-8221-831485AF6702}"
|
||||||
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ShowerMonitor.Manager.Tests", "ShowerMonitor.Manager.Tests\ShowerMonitor.Manager.Tests.csproj", "{A9DFB47D-7736-428C-9459-22AFC5CF3A38}"
|
||||||
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LightMonitor.Models", "LightMonitor.Models\LightMonitor.Models.csproj", "{B14E51EB-7D5C-44FA-8674-4B4796459978}"
|
||||||
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LightMonitor.Manager", "LightMonitor.Manager\LightMonitor.Manager.csproj", "{9165EDEF-2FE2-4578-849B-B4D4089416DA}"
|
||||||
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LightMonitor.Manager.Tests", "LightMonitor.Manager.Tests\LightMonitor.Manager.Tests.csproj", "{B8303C3E-785C-48F0-8F40-D4A9E9D50C92}"
|
||||||
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BatteryMonitor.Models", "BatteryMonitor.Models\BatteryMonitor.Models.csproj", "{2D27B621-7B92-4014-8FDF-6AD376C97612}"
|
||||||
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BatteryMonitor.Manager", "BatteryMonitor.Manager\BatteryMonitor.Manager.csproj", "{C844BDD9-584D-4D72-8EDE-AEB3E7429FC1}"
|
||||||
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BatteryMonitor.Manager.Tests", "BatteryMonitor.Manager.Tests\BatteryMonitor.Manager.Tests.csproj", "{2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0}"
|
||||||
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LeakMonitor.Models", "LeakMonitor.Models\LeakMonitor.Models.csproj", "{590B5855-07CB-4D04-8602-04ECE53D2A2B}"
|
||||||
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LeakMonitor.Manager", "LeakMonitor.Manager\LeakMonitor.Manager.csproj", "{6830DB0A-9D94-4B52-A0A1-7593E4971FF7}"
|
||||||
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LeakMonitor.Manager.Tests", "LeakMonitor.Manager.Tests\LeakMonitor.Manager.Tests.csproj", "{D56BE1F2-830C-43DB-87A8-A659192984FC}"
|
||||||
|
EndProject
|
||||||
|
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
|
||||||
@@ -150,8 +186,212 @@ Global
|
|||||||
{1F613F65-5F3C-41E6-B86B-774301D80E42}.Release|x64.Build.0 = Release|Any CPU
|
{1F613F65-5F3C-41E6-B86B-774301D80E42}.Release|x64.Build.0 = Release|Any CPU
|
||||||
{1F613F65-5F3C-41E6-B86B-774301D80E42}.Release|x86.ActiveCfg = Release|Any CPU
|
{1F613F65-5F3C-41E6-B86B-774301D80E42}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
{1F613F65-5F3C-41E6-B86B-774301D80E42}.Release|x86.Build.0 = Release|Any CPU
|
{1F613F65-5F3C-41E6-B86B-774301D80E42}.Release|x86.Build.0 = Release|Any CPU
|
||||||
|
{72331F53-884D-42A1-8EEA-8CC83FFAB623}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{72331F53-884D-42A1-8EEA-8CC83FFAB623}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{72331F53-884D-42A1-8EEA-8CC83FFAB623}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||||
|
{72331F53-884D-42A1-8EEA-8CC83FFAB623}.Debug|x64.Build.0 = Debug|Any CPU
|
||||||
|
{72331F53-884D-42A1-8EEA-8CC83FFAB623}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||||
|
{72331F53-884D-42A1-8EEA-8CC83FFAB623}.Debug|x86.Build.0 = Debug|Any CPU
|
||||||
|
{72331F53-884D-42A1-8EEA-8CC83FFAB623}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{72331F53-884D-42A1-8EEA-8CC83FFAB623}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{72331F53-884D-42A1-8EEA-8CC83FFAB623}.Release|x64.ActiveCfg = Release|Any CPU
|
||||||
|
{72331F53-884D-42A1-8EEA-8CC83FFAB623}.Release|x64.Build.0 = Release|Any CPU
|
||||||
|
{72331F53-884D-42A1-8EEA-8CC83FFAB623}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
|
{72331F53-884D-42A1-8EEA-8CC83FFAB623}.Release|x86.Build.0 = Release|Any CPU
|
||||||
|
{488964A2-C7A2-45C9-9CDB-98515AFD7242}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{488964A2-C7A2-45C9-9CDB-98515AFD7242}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{488964A2-C7A2-45C9-9CDB-98515AFD7242}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||||
|
{488964A2-C7A2-45C9-9CDB-98515AFD7242}.Debug|x64.Build.0 = Debug|Any CPU
|
||||||
|
{488964A2-C7A2-45C9-9CDB-98515AFD7242}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||||
|
{488964A2-C7A2-45C9-9CDB-98515AFD7242}.Debug|x86.Build.0 = Debug|Any CPU
|
||||||
|
{488964A2-C7A2-45C9-9CDB-98515AFD7242}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{488964A2-C7A2-45C9-9CDB-98515AFD7242}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{488964A2-C7A2-45C9-9CDB-98515AFD7242}.Release|x64.ActiveCfg = Release|Any CPU
|
||||||
|
{488964A2-C7A2-45C9-9CDB-98515AFD7242}.Release|x64.Build.0 = Release|Any CPU
|
||||||
|
{488964A2-C7A2-45C9-9CDB-98515AFD7242}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
|
{488964A2-C7A2-45C9-9CDB-98515AFD7242}.Release|x86.Build.0 = Release|Any CPU
|
||||||
|
{CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||||
|
{CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Debug|x64.Build.0 = Debug|Any CPU
|
||||||
|
{CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||||
|
{CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Debug|x86.Build.0 = Debug|Any CPU
|
||||||
|
{CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{CFF799B9-A8E7-46C8-B4FD-721B7308FA9C}.Release|x64.ActiveCfg = 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.Build.0 = Release|Any CPU
|
||||||
|
{DAD0BDF9-2A6D-48AD-B714-38D237E97285}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{DAD0BDF9-2A6D-48AD-B714-38D237E97285}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{DAD0BDF9-2A6D-48AD-B714-38D237E97285}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||||
|
{DAD0BDF9-2A6D-48AD-B714-38D237E97285}.Debug|x64.Build.0 = Debug|Any CPU
|
||||||
|
{DAD0BDF9-2A6D-48AD-B714-38D237E97285}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||||
|
{DAD0BDF9-2A6D-48AD-B714-38D237E97285}.Debug|x86.Build.0 = Debug|Any CPU
|
||||||
|
{DAD0BDF9-2A6D-48AD-B714-38D237E97285}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{DAD0BDF9-2A6D-48AD-B714-38D237E97285}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{DAD0BDF9-2A6D-48AD-B714-38D237E97285}.Release|x64.ActiveCfg = Release|Any CPU
|
||||||
|
{DAD0BDF9-2A6D-48AD-B714-38D237E97285}.Release|x64.Build.0 = Release|Any CPU
|
||||||
|
{DAD0BDF9-2A6D-48AD-B714-38D237E97285}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
|
{DAD0BDF9-2A6D-48AD-B714-38D237E97285}.Release|x86.Build.0 = Release|Any CPU
|
||||||
|
{8D05B406-B94B-4D6B-8221-831485AF6702}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{8D05B406-B94B-4D6B-8221-831485AF6702}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{8D05B406-B94B-4D6B-8221-831485AF6702}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||||
|
{8D05B406-B94B-4D6B-8221-831485AF6702}.Debug|x64.Build.0 = Debug|Any CPU
|
||||||
|
{8D05B406-B94B-4D6B-8221-831485AF6702}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||||
|
{8D05B406-B94B-4D6B-8221-831485AF6702}.Debug|x86.Build.0 = Debug|Any CPU
|
||||||
|
{8D05B406-B94B-4D6B-8221-831485AF6702}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{8D05B406-B94B-4D6B-8221-831485AF6702}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{8D05B406-B94B-4D6B-8221-831485AF6702}.Release|x64.ActiveCfg = Release|Any CPU
|
||||||
|
{8D05B406-B94B-4D6B-8221-831485AF6702}.Release|x64.Build.0 = Release|Any CPU
|
||||||
|
{8D05B406-B94B-4D6B-8221-831485AF6702}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
|
{8D05B406-B94B-4D6B-8221-831485AF6702}.Release|x86.Build.0 = Release|Any CPU
|
||||||
|
{A9DFB47D-7736-428C-9459-22AFC5CF3A38}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{A9DFB47D-7736-428C-9459-22AFC5CF3A38}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{A9DFB47D-7736-428C-9459-22AFC5CF3A38}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||||
|
{A9DFB47D-7736-428C-9459-22AFC5CF3A38}.Debug|x64.Build.0 = Debug|Any CPU
|
||||||
|
{A9DFB47D-7736-428C-9459-22AFC5CF3A38}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||||
|
{A9DFB47D-7736-428C-9459-22AFC5CF3A38}.Debug|x86.Build.0 = Debug|Any CPU
|
||||||
|
{A9DFB47D-7736-428C-9459-22AFC5CF3A38}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{A9DFB47D-7736-428C-9459-22AFC5CF3A38}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{A9DFB47D-7736-428C-9459-22AFC5CF3A38}.Release|x64.ActiveCfg = Release|Any CPU
|
||||||
|
{A9DFB47D-7736-428C-9459-22AFC5CF3A38}.Release|x64.Build.0 = Release|Any CPU
|
||||||
|
{A9DFB47D-7736-428C-9459-22AFC5CF3A38}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
|
{A9DFB47D-7736-428C-9459-22AFC5CF3A38}.Release|x86.Build.0 = Release|Any CPU
|
||||||
|
{B14E51EB-7D5C-44FA-8674-4B4796459978}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{B14E51EB-7D5C-44FA-8674-4B4796459978}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{B14E51EB-7D5C-44FA-8674-4B4796459978}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||||
|
{B14E51EB-7D5C-44FA-8674-4B4796459978}.Debug|x64.Build.0 = Debug|Any CPU
|
||||||
|
{B14E51EB-7D5C-44FA-8674-4B4796459978}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||||
|
{B14E51EB-7D5C-44FA-8674-4B4796459978}.Debug|x86.Build.0 = Debug|Any CPU
|
||||||
|
{B14E51EB-7D5C-44FA-8674-4B4796459978}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{B14E51EB-7D5C-44FA-8674-4B4796459978}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{B14E51EB-7D5C-44FA-8674-4B4796459978}.Release|x64.ActiveCfg = Release|Any CPU
|
||||||
|
{B14E51EB-7D5C-44FA-8674-4B4796459978}.Release|x64.Build.0 = Release|Any CPU
|
||||||
|
{B14E51EB-7D5C-44FA-8674-4B4796459978}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
|
{B14E51EB-7D5C-44FA-8674-4B4796459978}.Release|x86.Build.0 = Release|Any CPU
|
||||||
|
{9165EDEF-2FE2-4578-849B-B4D4089416DA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{9165EDEF-2FE2-4578-849B-B4D4089416DA}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{9165EDEF-2FE2-4578-849B-B4D4089416DA}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||||
|
{9165EDEF-2FE2-4578-849B-B4D4089416DA}.Debug|x64.Build.0 = Debug|Any CPU
|
||||||
|
{9165EDEF-2FE2-4578-849B-B4D4089416DA}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||||
|
{9165EDEF-2FE2-4578-849B-B4D4089416DA}.Debug|x86.Build.0 = Debug|Any CPU
|
||||||
|
{9165EDEF-2FE2-4578-849B-B4D4089416DA}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{9165EDEF-2FE2-4578-849B-B4D4089416DA}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{9165EDEF-2FE2-4578-849B-B4D4089416DA}.Release|x64.ActiveCfg = Release|Any CPU
|
||||||
|
{9165EDEF-2FE2-4578-849B-B4D4089416DA}.Release|x64.Build.0 = Release|Any CPU
|
||||||
|
{9165EDEF-2FE2-4578-849B-B4D4089416DA}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
|
{9165EDEF-2FE2-4578-849B-B4D4089416DA}.Release|x86.Build.0 = Release|Any CPU
|
||||||
|
{B8303C3E-785C-48F0-8F40-D4A9E9D50C92}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{B8303C3E-785C-48F0-8F40-D4A9E9D50C92}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{B8303C3E-785C-48F0-8F40-D4A9E9D50C92}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||||
|
{B8303C3E-785C-48F0-8F40-D4A9E9D50C92}.Debug|x64.Build.0 = Debug|Any CPU
|
||||||
|
{B8303C3E-785C-48F0-8F40-D4A9E9D50C92}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||||
|
{B8303C3E-785C-48F0-8F40-D4A9E9D50C92}.Debug|x86.Build.0 = Debug|Any CPU
|
||||||
|
{B8303C3E-785C-48F0-8F40-D4A9E9D50C92}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{B8303C3E-785C-48F0-8F40-D4A9E9D50C92}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{B8303C3E-785C-48F0-8F40-D4A9E9D50C92}.Release|x64.ActiveCfg = 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.Build.0 = Release|Any CPU
|
||||||
|
{2D27B621-7B92-4014-8FDF-6AD376C97612}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{2D27B621-7B92-4014-8FDF-6AD376C97612}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{2D27B621-7B92-4014-8FDF-6AD376C97612}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||||
|
{2D27B621-7B92-4014-8FDF-6AD376C97612}.Debug|x64.Build.0 = Debug|Any CPU
|
||||||
|
{2D27B621-7B92-4014-8FDF-6AD376C97612}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||||
|
{2D27B621-7B92-4014-8FDF-6AD376C97612}.Debug|x86.Build.0 = Debug|Any CPU
|
||||||
|
{2D27B621-7B92-4014-8FDF-6AD376C97612}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{2D27B621-7B92-4014-8FDF-6AD376C97612}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{2D27B621-7B92-4014-8FDF-6AD376C97612}.Release|x64.ActiveCfg = Release|Any CPU
|
||||||
|
{2D27B621-7B92-4014-8FDF-6AD376C97612}.Release|x64.Build.0 = Release|Any CPU
|
||||||
|
{2D27B621-7B92-4014-8FDF-6AD376C97612}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
|
{2D27B621-7B92-4014-8FDF-6AD376C97612}.Release|x86.Build.0 = Release|Any CPU
|
||||||
|
{C844BDD9-584D-4D72-8EDE-AEB3E7429FC1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{C844BDD9-584D-4D72-8EDE-AEB3E7429FC1}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{C844BDD9-584D-4D72-8EDE-AEB3E7429FC1}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||||
|
{C844BDD9-584D-4D72-8EDE-AEB3E7429FC1}.Debug|x64.Build.0 = Debug|Any CPU
|
||||||
|
{C844BDD9-584D-4D72-8EDE-AEB3E7429FC1}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||||
|
{C844BDD9-584D-4D72-8EDE-AEB3E7429FC1}.Debug|x86.Build.0 = Debug|Any CPU
|
||||||
|
{C844BDD9-584D-4D72-8EDE-AEB3E7429FC1}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{C844BDD9-584D-4D72-8EDE-AEB3E7429FC1}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{C844BDD9-584D-4D72-8EDE-AEB3E7429FC1}.Release|x64.ActiveCfg = Release|Any CPU
|
||||||
|
{C844BDD9-584D-4D72-8EDE-AEB3E7429FC1}.Release|x64.Build.0 = Release|Any CPU
|
||||||
|
{C844BDD9-584D-4D72-8EDE-AEB3E7429FC1}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
|
{C844BDD9-584D-4D72-8EDE-AEB3E7429FC1}.Release|x86.Build.0 = Release|Any CPU
|
||||||
|
{2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||||
|
{2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0}.Debug|x64.Build.0 = Debug|Any CPU
|
||||||
|
{2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||||
|
{2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0}.Debug|x86.Build.0 = Debug|Any CPU
|
||||||
|
{2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0}.Release|x64.ActiveCfg = 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.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
|
||||||
EndGlobalSection
|
EndGlobalSection
|
||||||
|
GlobalSection(NestedProjects) = preSolution
|
||||||
|
{D916F3F0-561B-4BC5-BEC2-B4C2B9CCFF7E} = {48492269-2B47-43FE-BC14-A901054EE5AE}
|
||||||
|
{D1FDF2F0-E8D2-4F00-95CA-1759047EA205} = {48492269-2B47-43FE-BC14-A901054EE5AE}
|
||||||
|
{8A3B7C9E-1D4F-4E5A-9B2C-3D5E6F7A8B9C} = {95E98121-7DA4-4085-A8E3-B0430628452F}
|
||||||
|
{2C0E9D45-3E34-4A60-A6B5-1E89B935419D} = {48492269-2B47-43FE-BC14-A901054EE5AE}
|
||||||
|
{1F613F65-5F3C-41E6-B86B-774301D80E42} = {95E98121-7DA4-4085-A8E3-B0430628452F}
|
||||||
|
{72331F53-884D-42A1-8EEA-8CC83FFAB623} = {48492269-2B47-43FE-BC14-A901054EE5AE}
|
||||||
|
{CFF799B9-A8E7-46C8-B4FD-721B7308FA9C} = {95E98121-7DA4-4085-A8E3-B0430628452F}
|
||||||
|
{DAD0BDF9-2A6D-48AD-B714-38D237E97285} = {48492269-2B47-43FE-BC14-A901054EE5AE}
|
||||||
|
{A9DFB47D-7736-428C-9459-22AFC5CF3A38} = {95E98121-7DA4-4085-A8E3-B0430628452F}
|
||||||
|
{B14E51EB-7D5C-44FA-8674-4B4796459978} = {48492269-2B47-43FE-BC14-A901054EE5AE}
|
||||||
|
{B8303C3E-785C-48F0-8F40-D4A9E9D50C92} = {95E98121-7DA4-4085-A8E3-B0430628452F}
|
||||||
|
{2D27B621-7B92-4014-8FDF-6AD376C97612} = {48492269-2B47-43FE-BC14-A901054EE5AE}
|
||||||
|
{2DC70C9C-6B29-4AED-B5A2-6ADE0B64C8E0} = {95E98121-7DA4-4085-A8E3-B0430628452F}
|
||||||
|
{590B5855-07CB-4D04-8602-04ECE53D2A2B} = {48492269-2B47-43FE-BC14-A901054EE5AE}
|
||||||
|
{D56BE1F2-830C-43DB-87A8-A659192984FC} = {95E98121-7DA4-4085-A8E3-B0430628452F}
|
||||||
|
{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
|
||||||
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>
|
||||||
@@ -0,0 +1,369 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using FluentAssertions;
|
||||||
|
using LeakMonitor.Models;
|
||||||
|
using LeakMonitorManager;
|
||||||
|
using LeakMonitorManager.Interface;
|
||||||
|
using LeakMonitorManager.Models;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
using Moq;
|
||||||
|
using NetDaemon.HassModel;
|
||||||
|
using NetDaemon.HassModel.Entities;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace LeakMonitor.Manager.Tests;
|
||||||
|
|
||||||
|
public class LeakMonitorInitTests
|
||||||
|
{
|
||||||
|
private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
|
||||||
|
private readonly Mock<ILogger<LeakMonitorInit>> _loggerMock = new Mock<ILogger<LeakMonitorInit>>();
|
||||||
|
private readonly Mock<ILeakNotificationService> _notificationServiceMock = new Mock<ILeakNotificationService>();
|
||||||
|
private readonly LeakMonitorTestData.TrackingObservable<StateChange> _stateChanges = new LeakMonitorTestData.TrackingObservable<StateChange>();
|
||||||
|
|
||||||
|
public LeakMonitorInitTests()
|
||||||
|
{
|
||||||
|
_haContextMock.Setup(h => h.StateAllChanges()).Returns(_stateChanges);
|
||||||
|
_loggerMock.Setup(l => l.IsEnabled(It.IsAny<LogLevel>())).Returns(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
private LeakMonitorInit CreateSut(LeakMonitorOptions? options = null)
|
||||||
|
{
|
||||||
|
return new LeakMonitorInit(
|
||||||
|
_haContextMock.Object,
|
||||||
|
_notificationServiceMock.Object,
|
||||||
|
_loggerMock.Object,
|
||||||
|
Options.Create(options ?? LeakMonitorTestData.CreateOptions()));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void VerifyNotifications(Times expected)
|
||||||
|
{
|
||||||
|
_notificationServiceMock.Verify(n => n.SendLeakAlert(It.IsAny<string>()), expected);
|
||||||
|
_notificationServiceMock.Verify(n => n.DismissLeakAlert(It.IsAny<string>()), expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void VerifyLogged(LogLevel level, Times times)
|
||||||
|
{
|
||||||
|
var logCount = _loggerMock.Invocations.Count(invocation =>
|
||||||
|
invocation.Method.Name == nameof(ILogger.Log) &&
|
||||||
|
invocation.Arguments[0] is LogLevel loggedLevel &&
|
||||||
|
loggedLevel == level);
|
||||||
|
|
||||||
|
times.Validate(logCount);
|
||||||
|
}
|
||||||
|
|
||||||
|
#region HandleStateChange
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(LeakMonitorTestData.WaterDetectedCases), MemberType = typeof(LeakMonitorTestData))]
|
||||||
|
public void HandleStateChange_WhenWaterDetected_ShouldSendLeakAlert(string sensorEntityId, string? newState)
|
||||||
|
{
|
||||||
|
var sut = CreateSut();
|
||||||
|
|
||||||
|
var change = LeakMonitorTestData.CreateStateChange(
|
||||||
|
_haContextMock.Object,
|
||||||
|
sensorEntityId,
|
||||||
|
LeakMonitorConsts.WaterClearedState,
|
||||||
|
newState);
|
||||||
|
|
||||||
|
sut.HandleStateChange(sensorEntityId, change);
|
||||||
|
|
||||||
|
_notificationServiceMock.Verify(n => n.SendLeakAlert(sensorEntityId), Times.Once());
|
||||||
|
_notificationServiceMock.Verify(n => n.DismissLeakAlert(It.IsAny<string>()), Times.Never());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(LeakMonitorTestData.WaterClearedCases), MemberType = typeof(LeakMonitorTestData))]
|
||||||
|
public void HandleStateChange_WhenWaterCleared_ShouldDismissLeakAlert(string sensorEntityId, string? newState)
|
||||||
|
{
|
||||||
|
var sut = CreateSut();
|
||||||
|
|
||||||
|
var change = LeakMonitorTestData.CreateStateChange(
|
||||||
|
_haContextMock.Object,
|
||||||
|
sensorEntityId,
|
||||||
|
LeakMonitorConsts.WaterDetectedState,
|
||||||
|
newState);
|
||||||
|
|
||||||
|
sut.HandleStateChange(sensorEntityId, change);
|
||||||
|
|
||||||
|
_notificationServiceMock.Verify(n => n.DismissLeakAlert(sensorEntityId), Times.Once());
|
||||||
|
_notificationServiceMock.Verify(n => n.SendLeakAlert(It.IsAny<string>()), Times.Never());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(LeakMonitorTestData.NonActionableStateCases), MemberType = typeof(LeakMonitorTestData))]
|
||||||
|
public void HandleStateChange_WhenStateIsNotActionable_ShouldNotNotify(string? newState)
|
||||||
|
{
|
||||||
|
var sut = CreateSut();
|
||||||
|
|
||||||
|
var change = LeakMonitorTestData.CreateStateChange(
|
||||||
|
_haContextMock.Object,
|
||||||
|
LeakMonitorTestData.AquariumSensorId,
|
||||||
|
LeakMonitorConsts.WaterDetectedState,
|
||||||
|
newState);
|
||||||
|
|
||||||
|
sut.HandleStateChange(LeakMonitorTestData.AquariumSensorId, change);
|
||||||
|
|
||||||
|
VerifyNotifications(Times.Never());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void HandleStateChange_WhenDetectionRepeats_ShouldForwardEveryDetection()
|
||||||
|
{
|
||||||
|
// Deduplication is the notification service's job (cooldown); the init handler
|
||||||
|
// forwards each "on" event it receives.
|
||||||
|
var sut = CreateSut();
|
||||||
|
|
||||||
|
var change = LeakMonitorTestData.CreateStateChange(
|
||||||
|
_haContextMock.Object,
|
||||||
|
LeakMonitorTestData.AquariumSensorId,
|
||||||
|
LeakMonitorConsts.WaterDetectedState,
|
||||||
|
LeakMonitorConsts.WaterDetectedState);
|
||||||
|
|
||||||
|
sut.HandleStateChange(LeakMonitorTestData.AquariumSensorId, change);
|
||||||
|
sut.HandleStateChange(LeakMonitorTestData.AquariumSensorId, change);
|
||||||
|
|
||||||
|
_notificationServiceMock.Verify(
|
||||||
|
n => n.SendLeakAlert(LeakMonitorTestData.AquariumSensorId),
|
||||||
|
Times.Exactly(2));
|
||||||
|
|
||||||
|
_notificationServiceMock.Verify(n => n.DismissLeakAlert(It.IsAny<string>()), Times.Never());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(LeakMonitorTestData.BlankSensorIds), MemberType = typeof(LeakMonitorTestData))]
|
||||||
|
public void HandleStateChange_WithBlankSensorId_ShouldForwardTheIdVerbatim(string sensorEntityId)
|
||||||
|
{
|
||||||
|
var sut = CreateSut();
|
||||||
|
|
||||||
|
var change = LeakMonitorTestData.CreateStateChange(
|
||||||
|
_haContextMock.Object,
|
||||||
|
sensorEntityId,
|
||||||
|
LeakMonitorConsts.WaterClearedState,
|
||||||
|
LeakMonitorConsts.WaterDetectedState);
|
||||||
|
|
||||||
|
sut.HandleStateChange(sensorEntityId, change);
|
||||||
|
|
||||||
|
_notificationServiceMock.Verify(n => n.SendLeakAlert(sensorEntityId), Times.Once());
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region InitializeAsync
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void InitializeAsync_WhenNoSensorsConfigured_ShouldNotSubscribeAndLogWarning()
|
||||||
|
{
|
||||||
|
var sut = CreateSut(LeakMonitorTestData.CreateOptions([]));
|
||||||
|
|
||||||
|
sut.Should().NotBeNull();
|
||||||
|
_stateChanges.SubscriptionCount.Should().Be(0);
|
||||||
|
_haContextMock.Verify(h => h.StateAllChanges(), Times.Never());
|
||||||
|
VerifyNotifications(Times.Never());
|
||||||
|
VerifyLogged(LogLevel.Warning, Times.Once());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void InitializeAsync_WhenSensorsConfigured_ShouldSubscribeToEachSensor()
|
||||||
|
{
|
||||||
|
CreateSut();
|
||||||
|
|
||||||
|
_stateChanges.SubscriptionCount.Should().Be(LeakMonitorTestData.DefaultSensorIds.Length);
|
||||||
|
|
||||||
|
_haContextMock.Verify(
|
||||||
|
h => h.StateAllChanges(),
|
||||||
|
Times.Exactly(LeakMonitorTestData.DefaultSensorIds.Length));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(LeakMonitorTestData.BlankSensorIds), MemberType = typeof(LeakMonitorTestData))]
|
||||||
|
public void InitializeAsync_WithBlankSensorId_ShouldStillSubscribeAndForward(string sensorEntityId)
|
||||||
|
{
|
||||||
|
CreateSut(LeakMonitorTestData.CreateOptions([sensorEntityId]));
|
||||||
|
|
||||||
|
_stateChanges.SubscriptionCount.Should().Be(1);
|
||||||
|
|
||||||
|
_stateChanges.Publish(LeakMonitorTestData.CreateStateChange(
|
||||||
|
_haContextMock.Object,
|
||||||
|
sensorEntityId,
|
||||||
|
LeakMonitorConsts.WaterClearedState,
|
||||||
|
LeakMonitorConsts.WaterDetectedState));
|
||||||
|
|
||||||
|
_notificationServiceMock.Verify(n => n.SendLeakAlert(sensorEntityId), Times.Once());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void InitializeAsync_WithNullSensorEntry_ShouldStillSubscribeRemainingSensors()
|
||||||
|
{
|
||||||
|
CreateSut(LeakMonitorTestData.CreateOptions(
|
||||||
|
[null!, LeakMonitorTestData.BoilerSensorId]));
|
||||||
|
|
||||||
|
_stateChanges.SubscriptionCount.Should().Be(2);
|
||||||
|
|
||||||
|
_stateChanges.Publish(LeakMonitorTestData.CreateStateChange(
|
||||||
|
_haContextMock.Object,
|
||||||
|
LeakMonitorTestData.BoilerSensorId,
|
||||||
|
LeakMonitorConsts.WaterClearedState,
|
||||||
|
LeakMonitorConsts.WaterDetectedState));
|
||||||
|
|
||||||
|
_notificationServiceMock.Verify(
|
||||||
|
n => n.SendLeakAlert(LeakMonitorTestData.BoilerSensorId),
|
||||||
|
Times.Once());
|
||||||
|
|
||||||
|
_notificationServiceMock.Verify(
|
||||||
|
n => n.SendLeakAlert(LeakMonitorTestData.AquariumSensorId),
|
||||||
|
Times.Never());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(LeakMonitorTestData.WaterDetectedCases), MemberType = typeof(LeakMonitorTestData))]
|
||||||
|
public void InitializeAsync_WhenSubscribedSensorDetectsWater_ShouldSendLeakAlert(
|
||||||
|
string sensorEntityId,
|
||||||
|
string? newState)
|
||||||
|
{
|
||||||
|
CreateSut();
|
||||||
|
|
||||||
|
_stateChanges.Publish(LeakMonitorTestData.CreateStateChange(
|
||||||
|
_haContextMock.Object,
|
||||||
|
sensorEntityId,
|
||||||
|
LeakMonitorConsts.WaterClearedState,
|
||||||
|
newState));
|
||||||
|
|
||||||
|
_notificationServiceMock.Verify(n => n.SendLeakAlert(sensorEntityId), Times.Once());
|
||||||
|
|
||||||
|
_notificationServiceMock.Verify(
|
||||||
|
n => n.SendLeakAlert(It.Is<string>(id => id != sensorEntityId)),
|
||||||
|
Times.Never());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(LeakMonitorTestData.WaterClearedCases), MemberType = typeof(LeakMonitorTestData))]
|
||||||
|
public void InitializeAsync_WhenSubscribedSensorClearsWater_ShouldDismissLeakAlert(
|
||||||
|
string sensorEntityId,
|
||||||
|
string? newState)
|
||||||
|
{
|
||||||
|
CreateSut();
|
||||||
|
|
||||||
|
_stateChanges.Publish(LeakMonitorTestData.CreateStateChange(
|
||||||
|
_haContextMock.Object,
|
||||||
|
sensorEntityId,
|
||||||
|
LeakMonitorConsts.WaterDetectedState,
|
||||||
|
newState));
|
||||||
|
|
||||||
|
_notificationServiceMock.Verify(n => n.DismissLeakAlert(sensorEntityId), Times.Once());
|
||||||
|
_notificationServiceMock.Verify(n => n.SendLeakAlert(It.IsAny<string>()), Times.Never());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(LeakMonitorTestData.NonActionableStateCases), MemberType = typeof(LeakMonitorTestData))]
|
||||||
|
public void InitializeAsync_WhenSubscribedSensorReportsNonActionableState_ShouldNotNotify(string? newState)
|
||||||
|
{
|
||||||
|
CreateSut();
|
||||||
|
|
||||||
|
_stateChanges.Publish(LeakMonitorTestData.CreateStateChange(
|
||||||
|
_haContextMock.Object,
|
||||||
|
LeakMonitorTestData.AquariumSensorId,
|
||||||
|
LeakMonitorConsts.WaterDetectedState,
|
||||||
|
newState));
|
||||||
|
|
||||||
|
VerifyNotifications(Times.Never());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void InitializeAsync_WhenStateIsUnchanged_ShouldNotNotify()
|
||||||
|
{
|
||||||
|
CreateSut();
|
||||||
|
|
||||||
|
_stateChanges.Publish(LeakMonitorTestData.CreateStateChange(
|
||||||
|
_haContextMock.Object,
|
||||||
|
LeakMonitorTestData.AquariumSensorId,
|
||||||
|
LeakMonitorConsts.WaterDetectedState,
|
||||||
|
LeakMonitorConsts.WaterDetectedState));
|
||||||
|
|
||||||
|
VerifyNotifications(Times.Never());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void InitializeAsync_WhenUnrelatedEntityChanges_ShouldNotNotify()
|
||||||
|
{
|
||||||
|
CreateSut();
|
||||||
|
|
||||||
|
_stateChanges.Publish(LeakMonitorTestData.CreateStateChange(
|
||||||
|
_haContextMock.Object,
|
||||||
|
"binary_sensor.unrelated_motion",
|
||||||
|
LeakMonitorConsts.WaterClearedState,
|
||||||
|
LeakMonitorConsts.WaterDetectedState));
|
||||||
|
|
||||||
|
VerifyNotifications(Times.Never());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void InitializeAsync_WhenDetectionSequenceArrives_ShouldNotifyPerTransition()
|
||||||
|
{
|
||||||
|
CreateSut();
|
||||||
|
|
||||||
|
foreach (var change in LeakMonitorTestData.CreateStateChangeSequence(
|
||||||
|
_haContextMock.Object,
|
||||||
|
LeakMonitorTestData.AquariumSensorId,
|
||||||
|
LeakMonitorTestData.DetectionSequence))
|
||||||
|
{
|
||||||
|
_stateChanges.Publish(change);
|
||||||
|
}
|
||||||
|
|
||||||
|
_notificationServiceMock.Verify(
|
||||||
|
n => n.SendLeakAlert(LeakMonitorTestData.AquariumSensorId),
|
||||||
|
Times.Exactly(2));
|
||||||
|
|
||||||
|
_notificationServiceMock.Verify(
|
||||||
|
n => n.DismissLeakAlert(LeakMonitorTestData.AquariumSensorId),
|
||||||
|
Times.Exactly(2));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void InitializeAsync_WhenNotificationServiceThrows_ShouldLogErrorAndKeepMonitoring()
|
||||||
|
{
|
||||||
|
_notificationServiceMock
|
||||||
|
.Setup(n => n.SendLeakAlert(It.IsAny<string>()))
|
||||||
|
.Throws(new InvalidOperationException("notification failed"));
|
||||||
|
|
||||||
|
CreateSut();
|
||||||
|
|
||||||
|
var act = () => _stateChanges.Publish(LeakMonitorTestData.CreateStateChange(
|
||||||
|
_haContextMock.Object,
|
||||||
|
LeakMonitorTestData.AquariumSensorId,
|
||||||
|
LeakMonitorConsts.WaterClearedState,
|
||||||
|
LeakMonitorConsts.WaterDetectedState));
|
||||||
|
|
||||||
|
act.Should().NotThrow();
|
||||||
|
VerifyLogged(LogLevel.Error, Times.Once());
|
||||||
|
|
||||||
|
// The failed event must not tear down the subscription.
|
||||||
|
_stateChanges.Publish(LeakMonitorTestData.CreateStateChange(
|
||||||
|
_haContextMock.Object,
|
||||||
|
LeakMonitorTestData.AquariumSensorId,
|
||||||
|
LeakMonitorConsts.WaterDetectedState,
|
||||||
|
LeakMonitorConsts.WaterClearedState));
|
||||||
|
|
||||||
|
_notificationServiceMock.Verify(
|
||||||
|
n => n.DismissLeakAlert(LeakMonitorTestData.AquariumSensorId),
|
||||||
|
Times.Once());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void InitializeAsync_WhenSubscriptionFails_ShouldSwallowAndLogError()
|
||||||
|
{
|
||||||
|
_haContextMock
|
||||||
|
.Setup(h => h.StateAllChanges())
|
||||||
|
.Throws(new InvalidOperationException("home assistant offline"));
|
||||||
|
|
||||||
|
var act = () => CreateSut();
|
||||||
|
|
||||||
|
act.Should().NotThrow();
|
||||||
|
_stateChanges.SubscriptionCount.Should().Be(0);
|
||||||
|
VerifyNotifications(Times.Never());
|
||||||
|
VerifyLogged(LogLevel.Error, Times.Once());
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
}
|
||||||
@@ -0,0 +1,279 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using System.Text.Json;
|
||||||
|
using LeakMonitor.Models;
|
||||||
|
using LeakMonitorManager.Models;
|
||||||
|
using Moq;
|
||||||
|
using NetDaemon.HassModel;
|
||||||
|
using NetDaemon.HassModel.Entities;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace LeakMonitor.Manager.Tests;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Shared, deterministic builders and datasets used by the LeakMonitor tests.
|
||||||
|
/// Keeping entity/state construction, notification payload capture and generated
|
||||||
|
/// input rows here means the test classes only describe the scenario under test.
|
||||||
|
/// </summary>
|
||||||
|
internal static class LeakMonitorTestData
|
||||||
|
{
|
||||||
|
public const string AquariumSensorId = "binary_sensor.aquarium_leak_sensor";
|
||||||
|
|
||||||
|
public const string BoilerSensorId = "binary_sensor.boiler_moisture";
|
||||||
|
|
||||||
|
public static readonly string[] DefaultSensorIds = [AquariumSensorId, BoilerSensorId];
|
||||||
|
|
||||||
|
private static readonly DateTimeOffset DefaultStart = new DateTimeOffset(2026, 1, 15, 12, 0, 0, TimeSpan.Zero);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Every casing of the "water detected" state, across both configured sensors.
|
||||||
|
/// </summary>
|
||||||
|
public static TheoryData<string, string?> WaterDetectedCases { get; } = new TheoryData<string, string?>
|
||||||
|
{
|
||||||
|
{ AquariumSensorId, LeakMonitorConsts.WaterDetectedState },
|
||||||
|
{ AquariumSensorId, "ON" },
|
||||||
|
{ AquariumSensorId, "On" },
|
||||||
|
{ AquariumSensorId, "oN" },
|
||||||
|
{ BoilerSensorId, LeakMonitorConsts.WaterDetectedState }
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Every casing of the "water cleared" state, across both configured sensors.
|
||||||
|
/// </summary>
|
||||||
|
public static TheoryData<string, string?> WaterClearedCases { get; } = new TheoryData<string, string?>
|
||||||
|
{
|
||||||
|
{ AquariumSensorId, LeakMonitorConsts.WaterClearedState },
|
||||||
|
{ AquariumSensorId, "OFF" },
|
||||||
|
{ AquariumSensorId, "Off" },
|
||||||
|
{ BoilerSensorId, "oFf" }
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// States that must never send or dismiss a leak notification. Covers unavailable,
|
||||||
|
/// unknown, blank, null and near-miss strings (the comparison is exact apart from casing).
|
||||||
|
/// </summary>
|
||||||
|
public static TheoryData<string?> NonActionableStateCases { get; } =
|
||||||
|
[
|
||||||
|
"unavailable",
|
||||||
|
"UNAVAILABLE",
|
||||||
|
"unknown",
|
||||||
|
"UNKNOWN",
|
||||||
|
string.Empty,
|
||||||
|
" ",
|
||||||
|
"\t",
|
||||||
|
"open",
|
||||||
|
"idle",
|
||||||
|
"detected",
|
||||||
|
"ON ",
|
||||||
|
" off",
|
||||||
|
"1",
|
||||||
|
"true",
|
||||||
|
null
|
||||||
|
];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Blank but non-null sensor ids. Production does not validate ids, so these are
|
||||||
|
/// subscribed and forwarded verbatim.
|
||||||
|
/// </summary>
|
||||||
|
public static TheoryData<string> BlankSensorIds { get; } =
|
||||||
|
[
|
||||||
|
string.Empty,
|
||||||
|
" ",
|
||||||
|
"\t"
|
||||||
|
];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// (sensor id, expected notification id) rows for the id sanitising rules:
|
||||||
|
/// dots become underscores, other characters and blanks are preserved.
|
||||||
|
/// </summary>
|
||||||
|
public static TheoryData<string, string> NotificationIdCases { get; } = new TheoryData<string, string>
|
||||||
|
{
|
||||||
|
{ AquariumSensorId, "leak_monitor_binary_sensor_aquarium_leak_sensor" },
|
||||||
|
{ BoilerSensorId, "leak_monitor_binary_sensor_boiler_moisture" },
|
||||||
|
{ "sensor.a.b.c", "leak_monitor_sensor_a_b_c" },
|
||||||
|
{ "no_dots", "leak_monitor_no_dots" },
|
||||||
|
{ "binary_sensor.already_snake_case", "leak_monitor_binary_sensor_already_snake_case" },
|
||||||
|
{ "binary_sensor.dash-and-dot.", "leak_monitor_binary_sensor_dash-and-dot_" },
|
||||||
|
{ string.Empty, "leak_monitor_" },
|
||||||
|
{ " ", "leak_monitor_ " }
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// (cooldown minutes, elapsed seconds before the second alert, expected notification count)
|
||||||
|
/// rows straddling the strict <c>elapsed < cooldown</c> boundary, plus zero, negative
|
||||||
|
/// and int-max cooldowns.
|
||||||
|
/// </summary>
|
||||||
|
public static TheoryData<int, int, int> CooldownBoundaryCases { get; } = new TheoryData<int, int, int>
|
||||||
|
{
|
||||||
|
{ 5, 0, 1 },
|
||||||
|
{ 5, 299, 1 },
|
||||||
|
{ 5, 300, 2 },
|
||||||
|
{ 5, 301, 2 },
|
||||||
|
{ 10, 599, 1 },
|
||||||
|
{ 10, 600, 2 },
|
||||||
|
{ 1, 59, 1 },
|
||||||
|
{ 1, 60, 2 },
|
||||||
|
{ 0, 0, 2 },
|
||||||
|
{ -5, 0, 2 },
|
||||||
|
{ int.MaxValue, 600, 1 }
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Repetition counts used to exercise duplicate suppression and zero-cooldown behaviour.
|
||||||
|
/// </summary>
|
||||||
|
public static TheoryData<int> RepeatedNotificationCounts { get; } =
|
||||||
|
[
|
||||||
|
2,
|
||||||
|
3,
|
||||||
|
5,
|
||||||
|
10
|
||||||
|
];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A deterministic detection/recovery sequence. The repeated "on" transition is filtered
|
||||||
|
/// out downstream, so the expected totals are two alerts and two dismissals.
|
||||||
|
/// </summary>
|
||||||
|
public static (string? OldState, string? NewState)[] DetectionSequence { get; } =
|
||||||
|
[
|
||||||
|
("off", "on"),
|
||||||
|
("on", "on"),
|
||||||
|
("on", "off"),
|
||||||
|
("off", "unavailable"),
|
||||||
|
("unavailable", "on"),
|
||||||
|
("on", "off")
|
||||||
|
];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Builds leak monitor options with production-compatible defaults.
|
||||||
|
/// Pass <c>[]</c> for no sensors; omit the argument for the shared sensor set.
|
||||||
|
/// </summary>
|
||||||
|
public static LeakMonitorOptions CreateOptions(
|
||||||
|
IEnumerable<string>? sensorEntityIds = null,
|
||||||
|
int notificationCooldownMinutes = LeakMonitorConsts.DefaultNotificationCooldownMinutes,
|
||||||
|
bool enabled = true)
|
||||||
|
{
|
||||||
|
return new LeakMonitorOptions
|
||||||
|
{
|
||||||
|
Enabled = enabled,
|
||||||
|
SensorEntityIds = sensorEntityIds?.ToArray() ?? [.. DefaultSensorIds],
|
||||||
|
NotificationCooldownMinutes = notificationCooldownMinutes
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Builds an <see cref="EntityState" />, or <c>null</c> when the entity has no state at all.
|
||||||
|
/// </summary>
|
||||||
|
private static EntityState? CreateOptionalState(string? state)
|
||||||
|
{
|
||||||
|
return state is null ? null : new EntityState { State = state };
|
||||||
|
}
|
||||||
|
|
||||||
|
public static StateChange CreateStateChange(
|
||||||
|
IHaContext haContext,
|
||||||
|
string entityId,
|
||||||
|
string? oldState,
|
||||||
|
string? newState)
|
||||||
|
{
|
||||||
|
return new StateChange(new Entity(haContext, entityId), CreateOptionalState(oldState),
|
||||||
|
CreateOptionalState(newState));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static IReadOnlyList<StateChange> CreateStateChangeSequence(
|
||||||
|
IHaContext haContext,
|
||||||
|
string entityId,
|
||||||
|
params (string? OldState, string? NewState)[] transitions)
|
||||||
|
{
|
||||||
|
return
|
||||||
|
[
|
||||||
|
.. transitions.Select(transition =>
|
||||||
|
CreateStateChange(haContext, entityId, transition.OldState, transition.NewState))
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Wires <see cref="IHaContext.CallService" /> on the mock and returns the captured calls
|
||||||
|
/// in invocation order.
|
||||||
|
/// </summary>
|
||||||
|
public static List<ServiceCall> CaptureServiceCalls(Mock<IHaContext> haContextMock)
|
||||||
|
{
|
||||||
|
var calls = new List<ServiceCall>();
|
||||||
|
|
||||||
|
haContextMock
|
||||||
|
.Setup(h => h.CallService(
|
||||||
|
It.IsAny<string>(),
|
||||||
|
It.IsAny<string>(),
|
||||||
|
It.IsAny<ServiceTarget?>(),
|
||||||
|
It.IsAny<object?>()))
|
||||||
|
.Callback<string, string, ServiceTarget?, object?>((domain, service, target, data) =>
|
||||||
|
calls.Add(new ServiceCall(domain, service, target, data)));
|
||||||
|
|
||||||
|
return calls;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Serialises a captured service-call payload so tests can assert on it.</summary>
|
||||||
|
public static JsonElement SerializePayload(object? data)
|
||||||
|
{
|
||||||
|
return JsonSerializer.SerializeToElement(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>One captured <c>IHaContext.CallService</c> invocation.</summary>
|
||||||
|
public sealed record ServiceCall(string Domain, string Service, ServiceTarget? Target, object? Data);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Deterministic clock so cooldown boundaries can be crossed without real waiting.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class ManualTimeProvider(DateTimeOffset? start = null) : TimeProvider
|
||||||
|
{
|
||||||
|
private DateTimeOffset _utcNow = start ?? DefaultStart;
|
||||||
|
|
||||||
|
public override DateTimeOffset GetUtcNow()
|
||||||
|
{
|
||||||
|
return _utcNow;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Advance(TimeSpan duration)
|
||||||
|
{
|
||||||
|
_utcNow += duration;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void AdvanceSeconds(int seconds)
|
||||||
|
{
|
||||||
|
Advance(TimeSpan.FromSeconds(seconds));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Observable that records subscriptions and lets tests push state changes through the
|
||||||
|
/// same pipeline the NetDaemon runtime uses.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class TrackingObservable<T> : IObservable<T>
|
||||||
|
{
|
||||||
|
private readonly List<IObserver<T>> _observers = [];
|
||||||
|
|
||||||
|
public int SubscriptionCount => _observers.Count;
|
||||||
|
|
||||||
|
public IDisposable Subscribe(IObserver<T> observer)
|
||||||
|
{
|
||||||
|
_observers.Add(observer);
|
||||||
|
|
||||||
|
return new Subscription(_observers, observer);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Publish(T value)
|
||||||
|
{
|
||||||
|
foreach (var observer in _observers.ToArray())
|
||||||
|
{
|
||||||
|
observer.OnNext(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class Subscription(List<IObserver<T>> observers, IObserver<T> observer) : IDisposable
|
||||||
|
{
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
observers.Remove(observer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,365 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using FluentAssertions;
|
||||||
|
using LeakMonitor.Models;
|
||||||
|
using LeakMonitorManager;
|
||||||
|
using LeakMonitorManager.Models;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
using Moq;
|
||||||
|
using NetDaemon.HassModel;
|
||||||
|
using NetDaemon.HassModel.Entities;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace LeakMonitor.Manager.Tests;
|
||||||
|
|
||||||
|
public class LeakNotificationServiceTests
|
||||||
|
{
|
||||||
|
private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
|
||||||
|
private readonly Mock<ILogger<LeakNotificationService>> _loggerMock = new Mock<ILogger<LeakNotificationService>>();
|
||||||
|
private readonly LeakMonitorTestData.ManualTimeProvider _timeProvider = new LeakMonitorTestData.ManualTimeProvider();
|
||||||
|
|
||||||
|
private LeakNotificationService CreateSut(LeakMonitorOptions? options = null)
|
||||||
|
{
|
||||||
|
return new LeakNotificationService(
|
||||||
|
_haContextMock.Object,
|
||||||
|
_loggerMock.Object,
|
||||||
|
Options.Create(options ?? LeakMonitorTestData.CreateOptions()),
|
||||||
|
_timeProvider);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void VerifyMobilePush(Times times)
|
||||||
|
{
|
||||||
|
_haContextMock.Verify(
|
||||||
|
h => h.CallService(
|
||||||
|
LeakMonitorConsts.NotifyDomain,
|
||||||
|
LeakMonitorConsts.MobileAppService,
|
||||||
|
It.IsAny<ServiceTarget?>(),
|
||||||
|
It.IsAny<object?>()),
|
||||||
|
times);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void VerifyPersistentCreate(Times times)
|
||||||
|
{
|
||||||
|
_haContextMock.Verify(
|
||||||
|
h => h.CallService(
|
||||||
|
LeakMonitorConsts.PersistentNotificationDomain,
|
||||||
|
LeakMonitorConsts.PersistentNotificationCreateService,
|
||||||
|
It.IsAny<ServiceTarget?>(),
|
||||||
|
It.IsAny<object?>()),
|
||||||
|
times);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void VerifyPersistentDismiss(Times times)
|
||||||
|
{
|
||||||
|
_haContextMock.Verify(
|
||||||
|
h => h.CallService(
|
||||||
|
LeakMonitorConsts.PersistentNotificationDomain,
|
||||||
|
LeakMonitorConsts.PersistentNotificationDismissService,
|
||||||
|
It.IsAny<ServiceTarget?>(),
|
||||||
|
It.IsAny<object?>()),
|
||||||
|
times);
|
||||||
|
}
|
||||||
|
|
||||||
|
#region SendLeakAlert
|
||||||
|
|
||||||
|
public static TheoryData<string, string> SendAlertServiceCalls { get; } = new TheoryData<string, string>
|
||||||
|
{
|
||||||
|
{ LeakMonitorConsts.NotifyDomain, LeakMonitorConsts.MobileAppService },
|
||||||
|
{ LeakMonitorConsts.PersistentNotificationDomain, LeakMonitorConsts.PersistentNotificationCreateService }
|
||||||
|
};
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(SendAlertServiceCalls))]
|
||||||
|
public void SendLeakAlert_ShouldCallExpectedService(string domain, string service)
|
||||||
|
{
|
||||||
|
var sut = CreateSut();
|
||||||
|
|
||||||
|
sut.SendLeakAlert(LeakMonitorTestData.AquariumSensorId);
|
||||||
|
|
||||||
|
_haContextMock.Verify(
|
||||||
|
h => h.CallService(domain, service, It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
|
||||||
|
Times.Once());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void SendLeakAlert_ShouldIncludeSensorDetailsInPayloads()
|
||||||
|
{
|
||||||
|
var calls = LeakMonitorTestData.CaptureServiceCalls(_haContextMock);
|
||||||
|
var sut = CreateSut();
|
||||||
|
const string sensorId = LeakMonitorTestData.AquariumSensorId;
|
||||||
|
const string expectedMessage = $"Water detected by {sensorId}! Check immediately.";
|
||||||
|
|
||||||
|
sut.SendLeakAlert(sensorId);
|
||||||
|
|
||||||
|
calls.Should().HaveCount(2);
|
||||||
|
|
||||||
|
var mobileCall = calls.Single(c => c.Service == LeakMonitorConsts.MobileAppService);
|
||||||
|
mobileCall.Domain.Should().Be(LeakMonitorConsts.NotifyDomain);
|
||||||
|
mobileCall.Target.Should().BeNull();
|
||||||
|
|
||||||
|
var mobilePayload = LeakMonitorTestData.SerializePayload(mobileCall.Data);
|
||||||
|
mobilePayload.GetProperty("title").GetString().Should().Be(LeakMonitorConsts.NotificationTitle);
|
||||||
|
mobilePayload.GetProperty("message").GetString().Should().Be(expectedMessage);
|
||||||
|
|
||||||
|
var sound = mobilePayload.GetProperty("data").GetProperty("push").GetProperty("sound");
|
||||||
|
sound.GetProperty("critical").GetInt32().Should().Be(1);
|
||||||
|
sound.GetProperty("volume").GetDouble().Should().Be(1.0);
|
||||||
|
|
||||||
|
var persistentCall = calls.Single(c => c.Service == LeakMonitorConsts.PersistentNotificationCreateService);
|
||||||
|
persistentCall.Domain.Should().Be(LeakMonitorConsts.PersistentNotificationDomain);
|
||||||
|
persistentCall.Target.Should().BeNull();
|
||||||
|
|
||||||
|
var persistentPayload = LeakMonitorTestData.SerializePayload(persistentCall.Data);
|
||||||
|
persistentPayload.GetProperty("title").GetString().Should().Be(LeakMonitorConsts.NotificationTitle);
|
||||||
|
persistentPayload.GetProperty("message").GetString().Should().Be(expectedMessage);
|
||||||
|
|
||||||
|
persistentPayload.GetProperty("notification_id")
|
||||||
|
.GetString()
|
||||||
|
.Should()
|
||||||
|
.Be(LeakNotificationService.BuildNotificationId(sensorId));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void SendLeakAlert_ShouldNotDismissNotification()
|
||||||
|
{
|
||||||
|
var sut = CreateSut();
|
||||||
|
|
||||||
|
sut.SendLeakAlert(LeakMonitorTestData.AquariumSensorId);
|
||||||
|
|
||||||
|
VerifyMobilePush(Times.Once());
|
||||||
|
VerifyPersistentCreate(Times.Once());
|
||||||
|
VerifyPersistentDismiss(Times.Never());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(LeakMonitorTestData.NotificationIdCases), MemberType = typeof(LeakMonitorTestData))]
|
||||||
|
public void SendLeakAlert_ShouldUseExpectedNotificationId(string sensorId, string expectedNotificationId)
|
||||||
|
{
|
||||||
|
var calls = LeakMonitorTestData.CaptureServiceCalls(_haContextMock);
|
||||||
|
var sut = CreateSut();
|
||||||
|
|
||||||
|
sut.SendLeakAlert(sensorId);
|
||||||
|
|
||||||
|
var persistentCall = calls.Single(c =>
|
||||||
|
c is
|
||||||
|
{
|
||||||
|
Domain: LeakMonitorConsts.PersistentNotificationDomain,
|
||||||
|
Service: LeakMonitorConsts.PersistentNotificationCreateService
|
||||||
|
});
|
||||||
|
|
||||||
|
LeakMonitorTestData.SerializePayload(persistentCall.Data)
|
||||||
|
.GetProperty("notification_id")
|
||||||
|
.GetString()
|
||||||
|
.Should()
|
||||||
|
.Be(expectedNotificationId);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(LeakMonitorTestData.RepeatedNotificationCounts), MemberType = typeof(LeakMonitorTestData))]
|
||||||
|
public void SendLeakAlert_RepeatedWithinCooldown_ShouldOnlyNotifyOnce(int repeats)
|
||||||
|
{
|
||||||
|
var sut = CreateSut();
|
||||||
|
const string sensorId = LeakMonitorTestData.AquariumSensorId;
|
||||||
|
|
||||||
|
for (var i = 0; i < repeats; i++)
|
||||||
|
{
|
||||||
|
sut.SendLeakAlert(sensorId);
|
||||||
|
}
|
||||||
|
|
||||||
|
VerifyMobilePush(Times.Once());
|
||||||
|
VerifyPersistentCreate(Times.Once());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(LeakMonitorTestData.RepeatedNotificationCounts), MemberType = typeof(LeakMonitorTestData))]
|
||||||
|
public void SendLeakAlert_RepeatedWithZeroCooldown_ShouldAlwaysNotify(int repeats)
|
||||||
|
{
|
||||||
|
var sut = CreateSut(LeakMonitorTestData.CreateOptions(notificationCooldownMinutes: 0));
|
||||||
|
const string sensorId = LeakMonitorTestData.AquariumSensorId;
|
||||||
|
|
||||||
|
for (var i = 0; i < repeats; i++)
|
||||||
|
{
|
||||||
|
sut.SendLeakAlert(sensorId);
|
||||||
|
}
|
||||||
|
|
||||||
|
VerifyMobilePush(Times.Exactly(repeats));
|
||||||
|
VerifyPersistentCreate(Times.Exactly(repeats));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(LeakMonitorTestData.CooldownBoundaryCases), MemberType = typeof(LeakMonitorTestData))]
|
||||||
|
public void SendLeakAlert_ShouldRespectCooldownBoundaries(
|
||||||
|
int cooldownMinutes,
|
||||||
|
int elapsedSeconds,
|
||||||
|
int expectedNotificationCount)
|
||||||
|
{
|
||||||
|
var sut = CreateSut(LeakMonitorTestData.CreateOptions(notificationCooldownMinutes: cooldownMinutes));
|
||||||
|
const string sensorId = LeakMonitorTestData.AquariumSensorId;
|
||||||
|
|
||||||
|
sut.SendLeakAlert(sensorId);
|
||||||
|
_timeProvider.AdvanceSeconds(elapsedSeconds);
|
||||||
|
sut.SendLeakAlert(sensorId);
|
||||||
|
|
||||||
|
VerifyMobilePush(Times.Exactly(expectedNotificationCount));
|
||||||
|
VerifyPersistentCreate(Times.Exactly(expectedNotificationCount));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void SendLeakAlert_AfterEachCooldownExpires_ShouldNotifyEveryTime()
|
||||||
|
{
|
||||||
|
var sut = CreateSut();
|
||||||
|
const string sensorId = LeakMonitorTestData.AquariumSensorId;
|
||||||
|
|
||||||
|
sut.SendLeakAlert(sensorId);
|
||||||
|
_timeProvider.Advance(TimeSpan.FromMinutes(LeakMonitorConsts.DefaultNotificationCooldownMinutes));
|
||||||
|
sut.SendLeakAlert(sensorId);
|
||||||
|
_timeProvider.Advance(TimeSpan.FromMinutes(LeakMonitorConsts.DefaultNotificationCooldownMinutes));
|
||||||
|
sut.SendLeakAlert(sensorId);
|
||||||
|
|
||||||
|
VerifyMobilePush(Times.Exactly(3));
|
||||||
|
VerifyPersistentCreate(Times.Exactly(3));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void SendLeakAlert_DifferentSensors_ShouldNotifyForEach()
|
||||||
|
{
|
||||||
|
var sut = CreateSut();
|
||||||
|
|
||||||
|
foreach (var sensorId in LeakMonitorTestData.DefaultSensorIds)
|
||||||
|
{
|
||||||
|
sut.SendLeakAlert(sensorId);
|
||||||
|
}
|
||||||
|
|
||||||
|
VerifyMobilePush(Times.Exactly(LeakMonitorTestData.DefaultSensorIds.Length));
|
||||||
|
VerifyPersistentCreate(Times.Exactly(LeakMonitorTestData.DefaultSensorIds.Length));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void SendLeakAlert_CooldownShouldBeTrackedPerSensor()
|
||||||
|
{
|
||||||
|
var calls = LeakMonitorTestData.CaptureServiceCalls(_haContextMock);
|
||||||
|
var sut = CreateSut();
|
||||||
|
|
||||||
|
sut.SendLeakAlert(LeakMonitorTestData.AquariumSensorId);
|
||||||
|
_timeProvider.AdvanceSeconds(60);
|
||||||
|
|
||||||
|
// A first-ever alert for a different sensor is not suppressed by the first sensor's cooldown.
|
||||||
|
sut.SendLeakAlert(LeakMonitorTestData.BoilerSensorId);
|
||||||
|
sut.SendLeakAlert(LeakMonitorTestData.AquariumSensorId);
|
||||||
|
|
||||||
|
VerifyMobilePush(Times.Exactly(2));
|
||||||
|
|
||||||
|
var boilerNotifications = calls
|
||||||
|
.Where(c => c.Domain == LeakMonitorConsts.NotifyDomain)
|
||||||
|
.Where(c => LeakMonitorTestData.SerializePayload(c.Data)
|
||||||
|
.GetProperty("message")
|
||||||
|
.GetString()!
|
||||||
|
.Contains(LeakMonitorTestData.BoilerSensorId, StringComparison.Ordinal));
|
||||||
|
|
||||||
|
boilerNotifications.Should().ContainSingle();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void SendLeakAlert_WithNullSensorId_ShouldThrowAndNotNotify()
|
||||||
|
{
|
||||||
|
var sut = CreateSut();
|
||||||
|
|
||||||
|
var act = () => sut.SendLeakAlert(null!);
|
||||||
|
|
||||||
|
act.Should().Throw<ArgumentNullException>();
|
||||||
|
VerifyMobilePush(Times.Never());
|
||||||
|
VerifyPersistentCreate(Times.Never());
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region DismissLeakAlert
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void DismissLeakAlert_ShouldCallPersistentNotificationDismiss()
|
||||||
|
{
|
||||||
|
var sut = CreateSut();
|
||||||
|
|
||||||
|
sut.DismissLeakAlert(LeakMonitorTestData.AquariumSensorId);
|
||||||
|
|
||||||
|
VerifyPersistentDismiss(Times.Once());
|
||||||
|
VerifyMobilePush(Times.Never());
|
||||||
|
VerifyPersistentCreate(Times.Never());
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(LeakMonitorTestData.NotificationIdCases), MemberType = typeof(LeakMonitorTestData))]
|
||||||
|
public void DismissLeakAlert_ShouldUseExpectedNotificationId(string sensorId, string expectedNotificationId)
|
||||||
|
{
|
||||||
|
var calls = LeakMonitorTestData.CaptureServiceCalls(_haContextMock);
|
||||||
|
var sut = CreateSut();
|
||||||
|
|
||||||
|
sut.DismissLeakAlert(sensorId);
|
||||||
|
|
||||||
|
var dismissCall = calls.Should().ContainSingle().Which;
|
||||||
|
dismissCall.Domain.Should().Be(LeakMonitorConsts.PersistentNotificationDomain);
|
||||||
|
dismissCall.Service.Should().Be(LeakMonitorConsts.PersistentNotificationDismissService);
|
||||||
|
dismissCall.Target.Should().BeNull();
|
||||||
|
|
||||||
|
LeakMonitorTestData.SerializePayload(dismissCall.Data)
|
||||||
|
.GetProperty("notification_id")
|
||||||
|
.GetString()
|
||||||
|
.Should()
|
||||||
|
.Be(expectedNotificationId);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void DismissLeakAlert_CalledRepeatedly_ShouldDismissEachTime()
|
||||||
|
{
|
||||||
|
var sut = CreateSut();
|
||||||
|
const string sensorId = LeakMonitorTestData.AquariumSensorId;
|
||||||
|
|
||||||
|
sut.DismissLeakAlert(sensorId);
|
||||||
|
sut.DismissLeakAlert(sensorId);
|
||||||
|
|
||||||
|
VerifyPersistentDismiss(Times.Exactly(2));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void DismissLeakAlert_ShouldNotResetCooldown()
|
||||||
|
{
|
||||||
|
var sut = CreateSut();
|
||||||
|
const string sensorId = LeakMonitorTestData.AquariumSensorId;
|
||||||
|
|
||||||
|
sut.SendLeakAlert(sensorId);
|
||||||
|
sut.DismissLeakAlert(sensorId);
|
||||||
|
_timeProvider.AdvanceSeconds(60);
|
||||||
|
sut.SendLeakAlert(sensorId);
|
||||||
|
|
||||||
|
VerifyMobilePush(Times.Once());
|
||||||
|
VerifyPersistentCreate(Times.Once());
|
||||||
|
VerifyPersistentDismiss(Times.Once());
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region BuildNotificationId
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(LeakMonitorTestData.NotificationIdCases), MemberType = typeof(LeakMonitorTestData))]
|
||||||
|
public void BuildNotificationId_ShouldSanitizeSensorId(string sensorEntityId, string expected)
|
||||||
|
{
|
||||||
|
var result = LeakNotificationService.BuildNotificationId(sensorEntityId);
|
||||||
|
|
||||||
|
result.Should().Be(expected);
|
||||||
|
result.Should().StartWith(LeakMonitorConsts.NotificationIdPrefix);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void BuildNotificationId_WithNullSensorId_ShouldThrow()
|
||||||
|
{
|
||||||
|
// Production has no null guard; the string.Replace call fails before any prefix is built.
|
||||||
|
var act = () => LeakNotificationService.BuildNotificationId(null!);
|
||||||
|
|
||||||
|
act.Should().Throw<NullReferenceException>();
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
namespace LeakMonitorManager.Interface;
|
||||||
|
|
||||||
|
public interface ILeakNotificationService
|
||||||
|
{
|
||||||
|
void SendLeakAlert(string sensorEntityId);
|
||||||
|
|
||||||
|
void DismissLeakAlert(string sensorEntityId);
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<RootNamespace>LeakMonitorManager</RootNamespace>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
|
||||||
|
<_Parameter1>LeakMonitor.Manager.Tests</_Parameter1>
|
||||||
|
</AssemblyAttribute>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\HomeAssistant.Entities\HomeAssistant.Entities.csproj"/>
|
||||||
|
<ProjectReference Include="..\LeakMonitor.Models\LeakMonitor.Models.csproj"/>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="11.0.0"/>
|
||||||
|
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.43.1"/>
|
||||||
|
<PackageReference Include="NetDaemon.HassModel" Version="26.43.1"/>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using LeakMonitor.Models;
|
||||||
|
using LeakMonitorManager.Interface;
|
||||||
|
using LeakMonitorManager.Models;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
using NetDaemon.AppModel;
|
||||||
|
using NetDaemon.HassModel;
|
||||||
|
using NetDaemon.HassModel.Entities;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace LeakMonitorManager;
|
||||||
|
|
||||||
|
[NetDaemonApp]
|
||||||
|
public sealed class LeakMonitorInit
|
||||||
|
{
|
||||||
|
private readonly IHaContext _haContext;
|
||||||
|
private readonly ILogger<LeakMonitorInit> _logger;
|
||||||
|
private readonly ILeakNotificationService _notificationService;
|
||||||
|
private readonly LeakMonitorOptions _options;
|
||||||
|
|
||||||
|
public LeakMonitorInit(
|
||||||
|
IHaContext haContext,
|
||||||
|
ILeakNotificationService notificationService,
|
||||||
|
ILogger<LeakMonitorInit> logger,
|
||||||
|
IOptions<LeakMonitorOptions> options)
|
||||||
|
{
|
||||||
|
_haContext = haContext;
|
||||||
|
_notificationService = notificationService;
|
||||||
|
_logger = logger;
|
||||||
|
_options = options.Value;
|
||||||
|
|
||||||
|
_ = InitializeAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
private Task InitializeAsync()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (_options.SensorEntityIds.Length == 0)
|
||||||
|
{
|
||||||
|
_logger.LogWarning("LeakMonitor enabled but no sensor entity IDs configured");
|
||||||
|
|
||||||
|
return Task.CompletedTask;
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (var sensorEntityId in _options.SensorEntityIds)
|
||||||
|
{
|
||||||
|
SubscribeToLeakSensor(sensorEntityId);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_logger.IsEnabled(LogLevel.Information))
|
||||||
|
{
|
||||||
|
_logger.LogInformation("LeakMonitor initialized, monitoring {Count} sensor(s)",
|
||||||
|
_options.SensorEntityIds.Length);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error during LeakMonitor initialization");
|
||||||
|
}
|
||||||
|
|
||||||
|
return Task.CompletedTask;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void SubscribeToLeakSensor(string sensorEntityId)
|
||||||
|
{
|
||||||
|
var entity = new Entity(_haContext, sensorEntityId);
|
||||||
|
|
||||||
|
entity.StateChanges()
|
||||||
|
.Subscribe(change =>
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
HandleStateChange(sensorEntityId, change);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error handling state change for {SensorId}", sensorEntityId);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (_logger.IsEnabled(LogLevel.Information))
|
||||||
|
{
|
||||||
|
_logger.LogInformation("Subscribed to leak sensor {SensorId}", sensorEntityId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal void HandleStateChange(string sensorEntityId, StateChange change)
|
||||||
|
{
|
||||||
|
var newState = change.New?.State;
|
||||||
|
|
||||||
|
if (string.Equals(newState, LeakMonitorConsts.WaterDetectedState, StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
_logger.LogWarning("Water leak detected by {SensorId}!", sensorEntityId);
|
||||||
|
|
||||||
|
_notificationService.SendLeakAlert(sensorEntityId);
|
||||||
|
}
|
||||||
|
else if (string.Equals(newState, LeakMonitorConsts.WaterClearedState, StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
if (_logger.IsEnabled(LogLevel.Information))
|
||||||
|
{
|
||||||
|
_logger.LogInformation("Water leak cleared by {SensorId}", sensorEntityId);
|
||||||
|
}
|
||||||
|
|
||||||
|
_notificationService.DismissLeakAlert(sensorEntityId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using LeakMonitorManager.Interface;
|
||||||
|
using LeakMonitorManager.Models;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using NetDaemon.AppModel;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace LeakMonitorManager;
|
||||||
|
|
||||||
|
public static class LeakMonitorServiceRegistration
|
||||||
|
{
|
||||||
|
public static void AddLeakMonitor(this IServiceCollection services, IConfiguration configuration)
|
||||||
|
{
|
||||||
|
var options = configuration
|
||||||
|
.GetSection(LeakMonitorOptions.SectionName)
|
||||||
|
.Get<LeakMonitorOptions>() ??
|
||||||
|
new LeakMonitorOptions();
|
||||||
|
|
||||||
|
if (!options.Enabled)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
services.AddNetDaemonApp<LeakMonitorInit>().AddScoped<ILeakNotificationService, LeakNotificationService>();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using System.Collections.Concurrent;
|
||||||
|
using LeakMonitor.Models;
|
||||||
|
using LeakMonitorManager.Interface;
|
||||||
|
using LeakMonitorManager.Models;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
using NetDaemon.HassModel;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace LeakMonitorManager;
|
||||||
|
|
||||||
|
public sealed class LeakNotificationService(
|
||||||
|
IHaContext haContext,
|
||||||
|
ILogger<LeakNotificationService> logger,
|
||||||
|
IOptions<LeakMonitorOptions> options,
|
||||||
|
TimeProvider timeProvider) : ILeakNotificationService
|
||||||
|
{
|
||||||
|
private readonly ConcurrentDictionary<string, DateTimeOffset> _lastNotificationTimes = new ConcurrentDictionary<string, DateTimeOffset>();
|
||||||
|
private readonly LeakMonitorOptions _options = options.Value;
|
||||||
|
|
||||||
|
public void SendLeakAlert(string sensorEntityId)
|
||||||
|
{
|
||||||
|
if (IsWithinCooldown(sensorEntityId))
|
||||||
|
{
|
||||||
|
if (logger.IsEnabled(LogLevel.Debug))
|
||||||
|
{
|
||||||
|
logger.LogDebug(
|
||||||
|
"Skipping leak notification for {SensorId} -- within cooldown period",
|
||||||
|
sensorEntityId);
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_lastNotificationTimes[sensorEntityId] = timeProvider.GetUtcNow();
|
||||||
|
|
||||||
|
var notificationId = BuildNotificationId(sensorEntityId);
|
||||||
|
var message = $"Water detected by {sensorEntityId}! Check immediately.";
|
||||||
|
|
||||||
|
SendMobilePushNotification(message);
|
||||||
|
CreatePersistentNotification(notificationId, message);
|
||||||
|
|
||||||
|
logger.LogWarning("Leak alert sent for sensor {SensorId}", sensorEntityId);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void DismissLeakAlert(string sensorEntityId)
|
||||||
|
{
|
||||||
|
var notificationId = BuildNotificationId(sensorEntityId);
|
||||||
|
|
||||||
|
haContext.CallService(
|
||||||
|
LeakMonitorConsts.PersistentNotificationDomain,
|
||||||
|
LeakMonitorConsts.PersistentNotificationDismissService,
|
||||||
|
data: new { notification_id = notificationId });
|
||||||
|
|
||||||
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
|
{
|
||||||
|
logger.LogInformation("Leak alert dismissed for sensor {SensorId}", sensorEntityId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void SendMobilePushNotification(string message)
|
||||||
|
{
|
||||||
|
haContext.CallService(
|
||||||
|
LeakMonitorConsts.NotifyDomain,
|
||||||
|
LeakMonitorConsts.MobileAppService,
|
||||||
|
data: new
|
||||||
|
{
|
||||||
|
message,
|
||||||
|
title = LeakMonitorConsts.NotificationTitle,
|
||||||
|
data = new
|
||||||
|
{
|
||||||
|
push = new
|
||||||
|
{
|
||||||
|
sound = new
|
||||||
|
{
|
||||||
|
critical = 1,
|
||||||
|
volume = 1.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private void CreatePersistentNotification(string notificationId, string message)
|
||||||
|
{
|
||||||
|
haContext.CallService(
|
||||||
|
LeakMonitorConsts.PersistentNotificationDomain,
|
||||||
|
LeakMonitorConsts.PersistentNotificationCreateService,
|
||||||
|
data: new
|
||||||
|
{
|
||||||
|
title = LeakMonitorConsts.NotificationTitle,
|
||||||
|
message,
|
||||||
|
notification_id = notificationId
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private bool IsWithinCooldown(string sensorEntityId)
|
||||||
|
{
|
||||||
|
if (!_lastNotificationTimes.TryGetValue(sensorEntityId, out var lastTime))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
var cooldown = TimeSpan.FromMinutes(_options.NotificationCooldownMinutes);
|
||||||
|
|
||||||
|
return timeProvider.GetUtcNow() - lastTime < cooldown;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static string BuildNotificationId(string sensorEntityId)
|
||||||
|
{
|
||||||
|
var sanitized = sensorEntityId.Replace('.', '_');
|
||||||
|
|
||||||
|
return $"{LeakMonitorConsts.NotificationIdPrefix}{sanitized}";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using LeakMonitor.Models;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace LeakMonitorManager.Models;
|
||||||
|
|
||||||
|
public sealed class LeakMonitorOptions
|
||||||
|
{
|
||||||
|
public const string SectionName = "LeakMonitor";
|
||||||
|
|
||||||
|
public bool Enabled { get; init; }
|
||||||
|
|
||||||
|
public string[] SensorEntityIds { get; init; } = [];
|
||||||
|
|
||||||
|
public int NotificationCooldownMinutes { get; init; } = LeakMonitorConsts.DefaultNotificationCooldownMinutes;
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<RootNamespace>LeakMonitor.Models</RootNamespace>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
namespace LeakMonitor.Models;
|
||||||
|
|
||||||
|
public static class LeakMonitorConsts
|
||||||
|
{
|
||||||
|
public const string WaterDetectedState = "on";
|
||||||
|
|
||||||
|
public const string WaterClearedState = "off";
|
||||||
|
|
||||||
|
public const string NotifyDomain = "notify";
|
||||||
|
|
||||||
|
public const string MobileAppService = "mobile_app_marius_phone";
|
||||||
|
|
||||||
|
public const string PersistentNotificationDomain = "persistent_notification";
|
||||||
|
|
||||||
|
public const string PersistentNotificationCreateService = "create";
|
||||||
|
|
||||||
|
public const string PersistentNotificationDismissService = "dismiss";
|
||||||
|
|
||||||
|
public const string NotificationIdPrefix = "leak_monitor_";
|
||||||
|
|
||||||
|
public const string NotificationTitle = "Water Leak Detected!";
|
||||||
|
|
||||||
|
public const int DefaultNotificationCooldownMinutes = 5;
|
||||||
|
}
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using LightMonitor.Models;
|
||||||
|
using LightMonitorManager;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
using Moq;
|
||||||
|
using NetDaemon.HassModel;
|
||||||
|
using NetDaemon.HassModel.Entities;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace LightMonitor.Manager.Tests;
|
||||||
|
|
||||||
|
public class LightControlServiceTests
|
||||||
|
{
|
||||||
|
private const string LightEntityId = LightMonitorTestData.LightEntityId;
|
||||||
|
private const string SunEntityId = LightMonitorTestData.SunEntityId;
|
||||||
|
|
||||||
|
private readonly LightMonitorOptions _defaultOptions = LightMonitorTestData.CreateOptions();
|
||||||
|
|
||||||
|
private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
|
||||||
|
|
||||||
|
private LightControlService CreateService(LightMonitorOptions? options = null)
|
||||||
|
{
|
||||||
|
return new LightControlService(
|
||||||
|
_haContextMock.Object,
|
||||||
|
Mock.Of<ILogger<LightControlService>>(),
|
||||||
|
Options.Create(options ?? _defaultOptions));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void SetupState(string entityId, string? state)
|
||||||
|
{
|
||||||
|
_haContextMock.Setup(x => x.GetState(entityId))
|
||||||
|
.Returns(LightMonitorTestData.CreateOptionalState(state));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void VerifyTurnOn(string entityId, bool shouldTurnOn)
|
||||||
|
{
|
||||||
|
if (!shouldTurnOn)
|
||||||
|
{
|
||||||
|
_haContextMock.Verify(x => x.CallService(
|
||||||
|
It.IsAny<string>(), It.IsAny<string>(),
|
||||||
|
It.IsAny<ServiceTarget>(), It.IsAny<object?>()),
|
||||||
|
Times.Never);
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_haContextMock.Verify(x => x.CallService("light", "turn_on",
|
||||||
|
It.Is<ServiceTarget>(target => target.EntityIds != null && target.EntityIds.Contains(entityId)),
|
||||||
|
It.IsAny<object?>()),
|
||||||
|
Times.Once);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(LightMonitorTestData.SunStateTurnOnCases), MemberType = typeof(LightMonitorTestData))]
|
||||||
|
public void TurnOnLight_ShouldOnlyTurnOnWhenSunIsBelowHorizon(string? sunState, bool shouldTurnOn)
|
||||||
|
{
|
||||||
|
SetupState(SunEntityId, sunState);
|
||||||
|
SetupState(LightEntityId, "off");
|
||||||
|
|
||||||
|
CreateService().TurnOnLight();
|
||||||
|
|
||||||
|
VerifyTurnOn(LightEntityId, shouldTurnOn);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(LightMonitorTestData.LightStateTurnOnCases), MemberType = typeof(LightMonitorTestData))]
|
||||||
|
public void TurnOnLight_WhenSunIsBelowHorizon_ShouldOnlyTurnOnWhenLightIsNotAlreadyOn(
|
||||||
|
string? lightState,
|
||||||
|
bool shouldTurnOn)
|
||||||
|
{
|
||||||
|
SetupState(SunEntityId, LightMonitorConsts.SunBelowHorizon);
|
||||||
|
SetupState(LightEntityId, lightState);
|
||||||
|
|
||||||
|
CreateService().TurnOnLight();
|
||||||
|
|
||||||
|
VerifyTurnOn(LightEntityId, shouldTurnOn);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void TurnOnLight_ShouldTargetTheConfiguredLightEntity()
|
||||||
|
{
|
||||||
|
const string customLightEntityId = "light.kitchen_ceiling";
|
||||||
|
var options = LightMonitorTestData.CreateOptions(customLightEntityId);
|
||||||
|
|
||||||
|
SetupState(SunEntityId, LightMonitorConsts.SunBelowHorizon);
|
||||||
|
SetupState(customLightEntityId, "off");
|
||||||
|
|
||||||
|
CreateService(options).TurnOnLight();
|
||||||
|
|
||||||
|
VerifyTurnOn(customLightEntityId, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void TurnOnLight_WithDefaultOptions_ShouldTargetTheDefaultLightEntity()
|
||||||
|
{
|
||||||
|
var options = new LightMonitorOptions();
|
||||||
|
|
||||||
|
SetupState(LightMonitorConsts.DefaultSunEntityId, LightMonitorConsts.SunBelowHorizon);
|
||||||
|
SetupState(LightMonitorConsts.DefaultLightEntityId, null);
|
||||||
|
|
||||||
|
CreateService(options).TurnOnLight();
|
||||||
|
|
||||||
|
VerifyTurnOn(LightMonitorConsts.DefaultLightEntityId, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void TurnOnLight_WhenSunIsAboveHorizon_ShouldNotReadTheLightState()
|
||||||
|
{
|
||||||
|
SetupState(SunEntityId, LightMonitorConsts.SunAboveHorizon);
|
||||||
|
|
||||||
|
CreateService().TurnOnLight();
|
||||||
|
|
||||||
|
_haContextMock.Verify(x => x.GetState(LightEntityId), Times.Never);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("")]
|
||||||
|
[InlineData(" ")]
|
||||||
|
public void TurnOnLight_WhenSunEntityIdIsBlank_ShouldNotTurnOnLight(string sunEntityId)
|
||||||
|
{
|
||||||
|
var options = LightMonitorTestData.CreateOptions(sunEntityId: sunEntityId);
|
||||||
|
SetupState(LightEntityId, "off");
|
||||||
|
|
||||||
|
CreateService(options).TurnOnLight();
|
||||||
|
|
||||||
|
VerifyTurnOn(LightEntityId, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void TurnOnLight_ShouldReadEachStateAtMostOnce()
|
||||||
|
{
|
||||||
|
SetupState(SunEntityId, LightMonitorConsts.SunBelowHorizon);
|
||||||
|
SetupState(LightEntityId, LightMonitorConsts.LightOnState);
|
||||||
|
|
||||||
|
CreateService().TurnOnLight();
|
||||||
|
|
||||||
|
_haContextMock.Verify(x => x.GetState(SunEntityId), Times.Once);
|
||||||
|
_haContextMock.Verify(x => x.GetState(LightEntityId), Times.Once);
|
||||||
|
VerifyTurnOn(LightEntityId, false);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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="..\LightMonitor.Manager\LightMonitor.Manager.csproj"/>
|
||||||
|
<ProjectReference Include="..\LightMonitor.Models\LightMonitor.Models.csproj"/>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,272 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using System.Reactive.Subjects;
|
||||||
|
using FluentAssertions;
|
||||||
|
using LightMonitor.Models;
|
||||||
|
using LightMonitorManager;
|
||||||
|
using LightMonitorManager.Interface;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
using Moq;
|
||||||
|
using NetDaemon.HassModel;
|
||||||
|
using NetDaemon.HassModel.Entities;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace LightMonitor.Manager.Tests;
|
||||||
|
|
||||||
|
public class LightMonitorInitTests
|
||||||
|
{
|
||||||
|
private const string SunEntityId = LightMonitorTestData.SunEntityId;
|
||||||
|
private const string PersonEntityId = LightMonitorTestData.PrimaryPersonEntityId;
|
||||||
|
|
||||||
|
private readonly LightMonitorOptions _defaultOptions = LightMonitorTestData.CreateOptions();
|
||||||
|
|
||||||
|
private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
|
||||||
|
private readonly Mock<ILightControlService> _lightControlServiceMock = new Mock<ILightControlService>();
|
||||||
|
private readonly Mock<IPresenceService> _presenceServiceMock = new Mock<IPresenceService>();
|
||||||
|
private readonly Subject<StateChange> _stateChangesSubject = new Subject<StateChange>();
|
||||||
|
|
||||||
|
private LightMonitorInit CreateSut(LightMonitorOptions? options = null, Exception? subscriptionException = null)
|
||||||
|
{
|
||||||
|
if (subscriptionException is null)
|
||||||
|
{
|
||||||
|
_haContextMock.Setup(x => x.StateAllChanges())
|
||||||
|
.Returns(_stateChangesSubject);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_haContextMock.Setup(x => x.StateAllChanges())
|
||||||
|
.Throws(subscriptionException);
|
||||||
|
}
|
||||||
|
|
||||||
|
return new LightMonitorInit(
|
||||||
|
_haContextMock.Object,
|
||||||
|
Mock.Of<ILogger<LightMonitorInit>>(),
|
||||||
|
_presenceServiceMock.Object,
|
||||||
|
_lightControlServiceMock.Object,
|
||||||
|
Options.Create(options ?? _defaultOptions));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void EmitStateChange(string entityId, string? oldState, string? newState)
|
||||||
|
{
|
||||||
|
var entity = new Entity(_haContextMock.Object, entityId);
|
||||||
|
|
||||||
|
_stateChangesSubject.OnNext(new StateChange(
|
||||||
|
entity,
|
||||||
|
LightMonitorTestData.CreateOptionalState(oldState),
|
||||||
|
LightMonitorTestData.CreateOptionalState(newState)));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void VerifyTurnOn(bool shouldTurnOn)
|
||||||
|
{
|
||||||
|
if (shouldTurnOn)
|
||||||
|
{
|
||||||
|
_lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Once);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Never);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(LightMonitorTestData.PersonNewStateCases), MemberType = typeof(LightMonitorTestData))]
|
||||||
|
public void PersonStateChange_ShouldTurnOnLightOnlyWhenNewStateIsHome(string? newState, bool shouldTurnOn)
|
||||||
|
{
|
||||||
|
CreateSut();
|
||||||
|
|
||||||
|
EmitStateChange(PersonEntityId, "not_home", newState);
|
||||||
|
|
||||||
|
VerifyTurnOn(shouldTurnOn);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(LightMonitorTestData.PersonArrivalTransitions), MemberType = typeof(LightMonitorTestData))]
|
||||||
|
public void PersonStateChange_ToHome_ShouldIgnoreOnlyRecoveryTransitions(string? oldState, bool shouldTurnOn)
|
||||||
|
{
|
||||||
|
CreateSut();
|
||||||
|
|
||||||
|
EmitStateChange(PersonEntityId, oldState, LightMonitorConsts.PersonHomeState);
|
||||||
|
|
||||||
|
VerifyTurnOn(shouldTurnOn);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(LightMonitorTestData.PrimaryPersonEntityId)]
|
||||||
|
[InlineData(LightMonitorTestData.SecondaryPersonEntityId)]
|
||||||
|
[InlineData(LightMonitorTestData.PhonePersonEntityId)]
|
||||||
|
public void PersonStateChange_ShouldTurnOnLightForEveryConfiguredPerson(string personEntityId)
|
||||||
|
{
|
||||||
|
CreateSut();
|
||||||
|
|
||||||
|
EmitStateChange(personEntityId, "not_home", LightMonitorConsts.PersonHomeState);
|
||||||
|
|
||||||
|
VerifyTurnOn(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void PersonStateChange_ForUnconfiguredPerson_ShouldNotTurnOnLight()
|
||||||
|
{
|
||||||
|
CreateSut(LightMonitorTestData.CreateOptions(personEntityIds: [PersonEntityId]));
|
||||||
|
|
||||||
|
EmitStateChange(
|
||||||
|
LightMonitorTestData.SecondaryPersonEntityId,
|
||||||
|
"not_home",
|
||||||
|
LightMonitorConsts.PersonHomeState);
|
||||||
|
|
||||||
|
VerifyTurnOn(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void PersonStateChange_ShouldNotConsultThePresenceService()
|
||||||
|
{
|
||||||
|
CreateSut();
|
||||||
|
|
||||||
|
EmitStateChange(PersonEntityId, "not_home", LightMonitorConsts.PersonHomeState);
|
||||||
|
|
||||||
|
VerifyTurnOn(true);
|
||||||
|
_presenceServiceMock.Verify(x => x.IsAnyoneHome(), Times.Never);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(LightMonitorTestData.SunStateTurnOnCases), MemberType = typeof(LightMonitorTestData))]
|
||||||
|
public void SunStateChange_ShouldTurnOnLightOnlyWhenNewStateIsBelowHorizon(string? newState, bool shouldTurnOn)
|
||||||
|
{
|
||||||
|
_presenceServiceMock.Setup(x => x.IsAnyoneHome()).Returns(true);
|
||||||
|
CreateSut();
|
||||||
|
|
||||||
|
EmitStateChange(SunEntityId, LightMonitorConsts.SunAboveHorizon, newState);
|
||||||
|
|
||||||
|
VerifyTurnOn(shouldTurnOn);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(LightMonitorTestData.SunBelowHorizonTransitions), MemberType = typeof(LightMonitorTestData))]
|
||||||
|
public void SunStateChange_ToBelowHorizon_ShouldIgnoreOnlyRecoveryTransitions(
|
||||||
|
string? oldState,
|
||||||
|
bool shouldTurnOn)
|
||||||
|
{
|
||||||
|
_presenceServiceMock.Setup(x => x.IsAnyoneHome()).Returns(true);
|
||||||
|
CreateSut();
|
||||||
|
|
||||||
|
EmitStateChange(SunEntityId, oldState, LightMonitorConsts.SunBelowHorizon);
|
||||||
|
|
||||||
|
VerifyTurnOn(shouldTurnOn);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(true)]
|
||||||
|
[InlineData(false)]
|
||||||
|
public void SunStateChange_ToBelowHorizon_ShouldTurnOnLightOnlyWhenSomeoneIsHome(bool anyoneHome)
|
||||||
|
{
|
||||||
|
_presenceServiceMock.Setup(x => x.IsAnyoneHome()).Returns(anyoneHome);
|
||||||
|
CreateSut();
|
||||||
|
|
||||||
|
EmitStateChange(SunEntityId, LightMonitorConsts.SunAboveHorizon, LightMonitorConsts.SunBelowHorizon);
|
||||||
|
|
||||||
|
VerifyTurnOn(anyoneHome);
|
||||||
|
_presenceServiceMock.Verify(x => x.IsAnyoneHome(), Times.Once);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void SunStateChange_WithNoConfiguredPersons_ShouldStillReactToTheSun()
|
||||||
|
{
|
||||||
|
_presenceServiceMock.Setup(x => x.IsAnyoneHome()).Returns(true);
|
||||||
|
CreateSut(LightMonitorTestData.CreateOptions(personEntityIds: []));
|
||||||
|
|
||||||
|
EmitStateChange(SunEntityId, LightMonitorConsts.SunAboveHorizon, LightMonitorConsts.SunBelowHorizon);
|
||||||
|
|
||||||
|
VerifyTurnOn(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void SunStateChange_WhenPresenceCheckThrows_ShouldKeepListening()
|
||||||
|
{
|
||||||
|
_presenceServiceMock.SetupSequence(x => x.IsAnyoneHome())
|
||||||
|
.Throws(new InvalidOperationException("presence failed"))
|
||||||
|
.Returns(true);
|
||||||
|
|
||||||
|
CreateSut();
|
||||||
|
|
||||||
|
var act = () => EmitStateChange(
|
||||||
|
SunEntityId,
|
||||||
|
LightMonitorConsts.SunAboveHorizon,
|
||||||
|
LightMonitorConsts.SunBelowHorizon);
|
||||||
|
|
||||||
|
act.Should().NotThrow();
|
||||||
|
VerifyTurnOn(false);
|
||||||
|
|
||||||
|
EmitStateChange(SunEntityId, LightMonitorConsts.SunAboveHorizon, LightMonitorConsts.SunBelowHorizon);
|
||||||
|
VerifyTurnOn(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void PersonStateChange_WhenTurnOnLightThrows_ShouldKeepListening()
|
||||||
|
{
|
||||||
|
_lightControlServiceMock.SetupSequence(x => x.TurnOnLight())
|
||||||
|
.Throws(new InvalidOperationException("light failed"))
|
||||||
|
.Pass();
|
||||||
|
|
||||||
|
CreateSut();
|
||||||
|
|
||||||
|
var act = () => EmitStateChange(PersonEntityId, "not_home", LightMonitorConsts.PersonHomeState);
|
||||||
|
|
||||||
|
act.Should().NotThrow();
|
||||||
|
_lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Once);
|
||||||
|
|
||||||
|
EmitStateChange(PersonEntityId, "not_home", LightMonitorConsts.PersonHomeState);
|
||||||
|
_lightControlServiceMock.Verify(x => x.TurnOnLight(), Times.Exactly(2));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Constructor_WhenStateSubscriptionThrows_ShouldNotThrow()
|
||||||
|
{
|
||||||
|
var act = () => CreateSut(subscriptionException: new InvalidOperationException("state stream failed"));
|
||||||
|
|
||||||
|
act.Should().NotThrow();
|
||||||
|
VerifyTurnOn(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task InitializeAsync_ShouldCompleteWithoutThrowing()
|
||||||
|
{
|
||||||
|
var sut = CreateSut();
|
||||||
|
|
||||||
|
var act = sut.InitializeAsync;
|
||||||
|
|
||||||
|
await act.Should().NotThrowAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void StateChange_ForUnrelatedEntity_ShouldNotTurnOnLight()
|
||||||
|
{
|
||||||
|
CreateSut();
|
||||||
|
|
||||||
|
EmitStateChange("sensor.sun_next_dawn", LightMonitorConsts.UnavailableState,
|
||||||
|
LightMonitorConsts.SunBelowHorizon);
|
||||||
|
|
||||||
|
VerifyTurnOn(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void SunStateChange_WhenStateDoesNotActuallyChange_ShouldNotTurnOnLight()
|
||||||
|
{
|
||||||
|
_presenceServiceMock.Setup(x => x.IsAnyoneHome()).Returns(true);
|
||||||
|
CreateSut();
|
||||||
|
|
||||||
|
EmitStateChange(SunEntityId, LightMonitorConsts.SunBelowHorizon, LightMonitorConsts.SunBelowHorizon);
|
||||||
|
|
||||||
|
VerifyTurnOn(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void PersonStateChange_WhenStateDoesNotActuallyChange_ShouldNotTurnOnLight()
|
||||||
|
{
|
||||||
|
CreateSut();
|
||||||
|
|
||||||
|
EmitStateChange(PersonEntityId, LightMonitorConsts.PersonHomeState, LightMonitorConsts.PersonHomeState);
|
||||||
|
|
||||||
|
VerifyTurnOn(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,190 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using LightMonitor.Models;
|
||||||
|
using NetDaemon.HassModel.Entities;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace LightMonitor.Manager.Tests;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Deterministic, reusable fixtures for the LightMonitor tests.
|
||||||
|
/// Keeping the option builder, state builders and generated state tables here
|
||||||
|
/// avoids copy-pasted setup across the test classes.
|
||||||
|
/// </summary>
|
||||||
|
internal static class LightMonitorTestData
|
||||||
|
{
|
||||||
|
public const string LightEntityId = "light.sonoff_1002214d40";
|
||||||
|
public const string SunEntityId = "sun.sun";
|
||||||
|
|
||||||
|
public const string PrimaryPersonEntityId = "person.marius";
|
||||||
|
public const string SecondaryPersonEntityId = "person.erika";
|
||||||
|
public const string PhonePersonEntityId = "person.home_phone";
|
||||||
|
|
||||||
|
public static readonly string[] PersonEntityIds =
|
||||||
|
[
|
||||||
|
PrimaryPersonEntityId,
|
||||||
|
SecondaryPersonEntityId,
|
||||||
|
PhonePersonEntityId
|
||||||
|
];
|
||||||
|
|
||||||
|
private static readonly string?[] PresenceStates =
|
||||||
|
[
|
||||||
|
LightMonitorConsts.PersonHomeState,
|
||||||
|
"not_home",
|
||||||
|
LightMonitorConsts.UnavailableState,
|
||||||
|
null
|
||||||
|
];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Sun states that should (<c>true</c>) or should not (<c>false</c>) cause a light turn on.
|
||||||
|
/// "below_horizon" is compared case-insensitively; unavailable, unknown, blank and
|
||||||
|
/// missing states must never turn the light on.
|
||||||
|
/// </summary>
|
||||||
|
public static TheoryData<string?, bool> SunStateTurnOnCases { get; } = new TheoryData<string?, bool>
|
||||||
|
{
|
||||||
|
{ LightMonitorConsts.SunBelowHorizon, true },
|
||||||
|
{ LightMonitorConsts.SunBelowHorizon.ToUpperInvariant(), true },
|
||||||
|
{ "Below_Horizon", true },
|
||||||
|
{ LightMonitorConsts.SunAboveHorizon, false },
|
||||||
|
{ LightMonitorConsts.SunAboveHorizon.ToUpperInvariant(), false },
|
||||||
|
{ LightMonitorConsts.UnavailableState, false },
|
||||||
|
{ LightMonitorConsts.UnknownState, false },
|
||||||
|
{ string.Empty, false },
|
||||||
|
{ " ", false },
|
||||||
|
{ null, false }
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Light states evaluated while the sun is below the horizon. Only "on" (any casing)
|
||||||
|
/// suppresses the turn on call; everything else, including missing state, turns it on.
|
||||||
|
/// </summary>
|
||||||
|
public static TheoryData<string?, bool> LightStateTurnOnCases { get; } = new TheoryData<string?, bool>
|
||||||
|
{
|
||||||
|
{ LightMonitorConsts.LightOnState, false },
|
||||||
|
{ LightMonitorConsts.LightOnState.ToUpperInvariant(), false },
|
||||||
|
{ "On", false },
|
||||||
|
{ "off", true },
|
||||||
|
{ "OFF", true },
|
||||||
|
{ LightMonitorConsts.UnavailableState, true },
|
||||||
|
{ LightMonitorConsts.UnknownState, true },
|
||||||
|
{ string.Empty, true },
|
||||||
|
{ " ", true },
|
||||||
|
{ null, true }
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Person states checked against the "arrived home" transition.
|
||||||
|
/// Only "home" in any casing counts.
|
||||||
|
/// </summary>
|
||||||
|
public static TheoryData<string?, bool> PersonNewStateCases { get; } = new TheoryData<string?, bool>
|
||||||
|
{
|
||||||
|
{ LightMonitorConsts.PersonHomeState, true },
|
||||||
|
{ "HOME", true },
|
||||||
|
{ "Home", true },
|
||||||
|
{ "hOmE", true },
|
||||||
|
{ "not_home", false },
|
||||||
|
{ "not_home ", false },
|
||||||
|
{ LightMonitorConsts.UnavailableState, false },
|
||||||
|
{ LightMonitorConsts.UnknownState, false },
|
||||||
|
{ string.Empty, false },
|
||||||
|
{ " ", false },
|
||||||
|
{ null, false }
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Old person states for a transition to "home". Recovery from unavailable, unknown or
|
||||||
|
/// missing state must be ignored; every other old state is a real arrival.
|
||||||
|
/// </summary>
|
||||||
|
public static TheoryData<string?, bool> PersonArrivalTransitions { get; } = new TheoryData<string?, bool>
|
||||||
|
{
|
||||||
|
{ "not_home", true },
|
||||||
|
{ "work", true },
|
||||||
|
{ string.Empty, true },
|
||||||
|
{ LightMonitorConsts.UnavailableState, false },
|
||||||
|
{ LightMonitorConsts.UnknownState, false },
|
||||||
|
{ null, false }
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Old sun states for a transition to "below_horizon". Recovery from unavailable, unknown
|
||||||
|
/// or missing state must be ignored.
|
||||||
|
/// </summary>
|
||||||
|
public static TheoryData<string?, bool> SunBelowHorizonTransitions { get; } = new TheoryData<string?, bool>
|
||||||
|
{
|
||||||
|
{ LightMonitorConsts.SunAboveHorizon, true },
|
||||||
|
{ string.Empty, true },
|
||||||
|
{ LightMonitorConsts.UnavailableState, false },
|
||||||
|
{ LightMonitorConsts.UnknownState, false },
|
||||||
|
{ null, false }
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Every 4^3 = 64 combination of home / not_home / unavailable / missing state across the
|
||||||
|
/// three configured person entities.
|
||||||
|
/// </summary>
|
||||||
|
public static TheoryData<string?[]> PresenceStateMatrix { get; } = CreatePresenceStateMatrix();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Person id configurations that resolve to "nobody tracked".
|
||||||
|
/// </summary>
|
||||||
|
public static TheoryData<string[]> NoPersonEntityIdSets { get; } =
|
||||||
|
[
|
||||||
|
[],
|
||||||
|
[string.Empty],
|
||||||
|
[" "]
|
||||||
|
];
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Builds light monitor options with production-compatible defaults.
|
||||||
|
/// </summary>
|
||||||
|
public static LightMonitorOptions CreateOptions(
|
||||||
|
string lightEntityId = LightEntityId,
|
||||||
|
string sunEntityId = SunEntityId,
|
||||||
|
IEnumerable<string>? personEntityIds = null,
|
||||||
|
bool enabled = true)
|
||||||
|
{
|
||||||
|
return new LightMonitorOptions
|
||||||
|
{
|
||||||
|
Enabled = enabled,
|
||||||
|
LightEntityId = lightEntityId,
|
||||||
|
SunEntityId = sunEntityId,
|
||||||
|
PersonEntityIds = personEntityIds?.ToArray() ?? [.. PersonEntityIds]
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Builds an <see cref="EntityState" /> carrying <paramref name="state" />.
|
||||||
|
/// </summary>
|
||||||
|
public static EntityState CreateState(string? state)
|
||||||
|
{
|
||||||
|
return new EntityState { State = state };
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Builds an <see cref="EntityState" />, or <c>null</c> when the entity has no state at all
|
||||||
|
/// (as returned by <c>IHaContext.GetState</c> for a missing entity).
|
||||||
|
/// </summary>
|
||||||
|
public static EntityState? CreateOptionalState(string? state)
|
||||||
|
{
|
||||||
|
return state is null ? null : CreateState(state);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static TheoryData<string?[]> CreatePresenceStateMatrix()
|
||||||
|
{
|
||||||
|
var matrix = new TheoryData<string?[]>();
|
||||||
|
|
||||||
|
foreach (var first in PresenceStates)
|
||||||
|
{
|
||||||
|
foreach (var second in PresenceStates)
|
||||||
|
{
|
||||||
|
foreach (var third in PresenceStates)
|
||||||
|
{
|
||||||
|
matrix.Add([first, second, third]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return matrix;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using FluentAssertions;
|
||||||
|
using LightMonitor.Models;
|
||||||
|
using LightMonitorManager;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
using Moq;
|
||||||
|
using NetDaemon.HassModel;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace LightMonitor.Manager.Tests;
|
||||||
|
|
||||||
|
public class PresenceServiceTests
|
||||||
|
{
|
||||||
|
private readonly LightMonitorOptions _defaultOptions = LightMonitorTestData.CreateOptions();
|
||||||
|
private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
|
||||||
|
|
||||||
|
private PresenceService CreateService(LightMonitorOptions? options = null)
|
||||||
|
{
|
||||||
|
return new PresenceService(
|
||||||
|
_haContextMock.Object,
|
||||||
|
Mock.Of<ILogger<PresenceService>>(),
|
||||||
|
Options.Create(options ?? _defaultOptions));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void SetupStates(string?[] personStates)
|
||||||
|
{
|
||||||
|
for (var index = 0; index < personStates.Length; index++)
|
||||||
|
{
|
||||||
|
var entityId = LightMonitorTestData.PersonEntityIds[index];
|
||||||
|
var state = LightMonitorTestData.CreateOptionalState(personStates[index]);
|
||||||
|
|
||||||
|
_haContextMock.Setup(x => x.GetState(entityId))
|
||||||
|
.Returns(state);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(LightMonitorTestData.PresenceStateMatrix), MemberType = typeof(LightMonitorTestData))]
|
||||||
|
public void IsAnyoneHome_ForEveryPresenceCombination_ShouldReturnTrueOnlyWhenSomeoneIsHome(string?[] personStates)
|
||||||
|
{
|
||||||
|
SetupStates(personStates);
|
||||||
|
|
||||||
|
var expected = personStates.Any(state =>
|
||||||
|
string.Equals(state, LightMonitorConsts.PersonHomeState, StringComparison.OrdinalIgnoreCase));
|
||||||
|
|
||||||
|
CreateService().IsAnyoneHome().Should().Be(expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(LightMonitorTestData.PersonNewStateCases), MemberType = typeof(LightMonitorTestData))]
|
||||||
|
public void IsAnyoneHome_ShouldOnlyTreatHomeStateAsPresent(string? state, bool expected)
|
||||||
|
{
|
||||||
|
_haContextMock.Setup(x => x.GetState(LightMonitorTestData.PrimaryPersonEntityId))
|
||||||
|
.Returns(LightMonitorTestData.CreateOptionalState(state));
|
||||||
|
|
||||||
|
var options = LightMonitorTestData.CreateOptions(
|
||||||
|
personEntityIds: [LightMonitorTestData.PrimaryPersonEntityId]);
|
||||||
|
|
||||||
|
CreateService(options).IsAnyoneHome().Should().Be(expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(LightMonitorTestData.NoPersonEntityIdSets), MemberType = typeof(LightMonitorTestData))]
|
||||||
|
public void IsAnyoneHome_WithNoUsablePersonEntityIds_ShouldReturnFalse(string[] personEntityIds)
|
||||||
|
{
|
||||||
|
var options = LightMonitorTestData.CreateOptions(personEntityIds: personEntityIds);
|
||||||
|
|
||||||
|
CreateService(options).IsAnyoneHome().Should().BeFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IsAnyoneHome_WithEmptyPersonList_ShouldNotQueryAnyEntity()
|
||||||
|
{
|
||||||
|
var options = LightMonitorTestData.CreateOptions(personEntityIds: []);
|
||||||
|
|
||||||
|
CreateService(options).IsAnyoneHome().Should().BeFalse();
|
||||||
|
|
||||||
|
_haContextMock.Verify(x => x.GetState(It.IsAny<string>()), Times.Never);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IsAnyoneHome_ShouldStopCheckingAfterTheFirstHomePerson()
|
||||||
|
{
|
||||||
|
_haContextMock.Setup(x => x.GetState(LightMonitorTestData.PrimaryPersonEntityId))
|
||||||
|
.Returns(LightMonitorTestData.CreateState(LightMonitorConsts.PersonHomeState));
|
||||||
|
|
||||||
|
CreateService().IsAnyoneHome().Should().BeTrue();
|
||||||
|
|
||||||
|
_haContextMock.Verify(x => x.GetState(LightMonitorTestData.SecondaryPersonEntityId), Times.Never);
|
||||||
|
_haContextMock.Verify(x => x.GetState(LightMonitorTestData.PhonePersonEntityId), Times.Never);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IsAnyoneHome_ShouldCheckEveryConfiguredPersonWhenNobodyIsHome()
|
||||||
|
{
|
||||||
|
CreateService().IsAnyoneHome().Should().BeFalse();
|
||||||
|
|
||||||
|
foreach (var personEntityId in LightMonitorTestData.PersonEntityIds)
|
||||||
|
{
|
||||||
|
_haContextMock.Verify(x => x.GetState(personEntityId), Times.Once);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IsAnyoneHome_ShouldIgnorePersonsThatAreNotConfigured()
|
||||||
|
{
|
||||||
|
_haContextMock.Setup(x => x.GetState(LightMonitorTestData.SecondaryPersonEntityId))
|
||||||
|
.Returns(LightMonitorTestData.CreateState(LightMonitorConsts.PersonHomeState));
|
||||||
|
|
||||||
|
var options = LightMonitorTestData.CreateOptions(
|
||||||
|
personEntityIds: [LightMonitorTestData.PrimaryPersonEntityId]);
|
||||||
|
|
||||||
|
CreateService(options).IsAnyoneHome().Should().BeFalse();
|
||||||
|
|
||||||
|
_haContextMock.Verify(x => x.GetState(LightMonitorTestData.SecondaryPersonEntityId), Times.Never);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IsAnyoneHome_WithDefaultOptions_ShouldQueryAllDefaultPersonEntities()
|
||||||
|
{
|
||||||
|
var service = CreateService(new LightMonitorOptions());
|
||||||
|
|
||||||
|
service.IsAnyoneHome().Should().BeFalse();
|
||||||
|
|
||||||
|
foreach (var personEntityId in LightMonitorConsts.DefaultPersonEntityIds)
|
||||||
|
{
|
||||||
|
_haContextMock.Verify(x => x.GetState(personEntityId), Times.Once);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
namespace LightMonitorManager.Interface;
|
||||||
|
|
||||||
|
public interface ILightControlService
|
||||||
|
{
|
||||||
|
void TurnOnLight();
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
namespace LightMonitorManager.Interface;
|
||||||
|
|
||||||
|
public interface IPresenceService
|
||||||
|
{
|
||||||
|
bool IsAnyoneHome();
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using LightMonitor.Models;
|
||||||
|
using LightMonitorManager.Interface;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
using NetDaemon.HassModel;
|
||||||
|
using NetDaemon.HassModel.Entities;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace LightMonitorManager;
|
||||||
|
|
||||||
|
public sealed class LightControlService(
|
||||||
|
IHaContext haContext,
|
||||||
|
ILogger<LightControlService> logger,
|
||||||
|
IOptions<LightMonitorOptions> options)
|
||||||
|
: ILightControlService
|
||||||
|
{
|
||||||
|
private readonly LightMonitorOptions _options = options.Value;
|
||||||
|
|
||||||
|
public void TurnOnLight()
|
||||||
|
{
|
||||||
|
var sunState = haContext.GetState(_options.SunEntityId)?.State;
|
||||||
|
|
||||||
|
if (!string.Equals(sunState, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
if (logger.IsEnabled(LogLevel.Debug))
|
||||||
|
{
|
||||||
|
logger.LogDebug("Sun is not below horizon (state={SunState}), skipping light turn on", sunState);
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var lightState = haContext.GetState(_options.LightEntityId)?.State;
|
||||||
|
|
||||||
|
if (string.Equals(lightState, LightMonitorConsts.LightOnState, StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
if (logger.IsEnabled(LogLevel.Debug))
|
||||||
|
{
|
||||||
|
logger.LogDebug("Light {EntityId} is already on, skipping", _options.LightEntityId);
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
haContext.CallService("light", "turn_on", ServiceTarget.FromEntity(_options.LightEntityId));
|
||||||
|
|
||||||
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
|
{
|
||||||
|
logger.LogInformation("Light {EntityId} turned ON (dark outside + person home)", _options.LightEntityId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<RootNamespace>LightMonitorManager</RootNamespace>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
|
||||||
|
<_Parameter1>LightMonitor.Manager.Tests</_Parameter1>
|
||||||
|
</AssemblyAttribute>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\HomeAssistant.Entities\HomeAssistant.Entities.csproj"/>
|
||||||
|
<ProjectReference Include="..\LightMonitor.Models\LightMonitor.Models.csproj"/>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="11.0.0"/>
|
||||||
|
<PackageReference Include="NetDaemon.HassModel" Version="26.43.1"/>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,148 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using LightMonitor.Models;
|
||||||
|
using LightMonitorManager.Interface;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
using NetDaemon.AppModel;
|
||||||
|
using NetDaemon.HassModel;
|
||||||
|
using NetDaemon.HassModel.Entities;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace LightMonitorManager;
|
||||||
|
|
||||||
|
[NetDaemonApp]
|
||||||
|
public sealed class LightMonitorInit
|
||||||
|
{
|
||||||
|
private readonly IHaContext _haContext;
|
||||||
|
private readonly ILightControlService _lightControlService;
|
||||||
|
private readonly ILogger<LightMonitorInit> _logger;
|
||||||
|
private readonly LightMonitorOptions _options;
|
||||||
|
private readonly IPresenceService _presenceService;
|
||||||
|
|
||||||
|
public LightMonitorInit(
|
||||||
|
IHaContext haContext,
|
||||||
|
ILogger<LightMonitorInit> logger,
|
||||||
|
IPresenceService presenceService,
|
||||||
|
ILightControlService lightControlService,
|
||||||
|
IOptions<LightMonitorOptions> options)
|
||||||
|
{
|
||||||
|
_haContext = haContext;
|
||||||
|
_logger = logger;
|
||||||
|
_presenceService = presenceService;
|
||||||
|
_lightControlService = lightControlService;
|
||||||
|
_options = options.Value;
|
||||||
|
|
||||||
|
_ = InitializeAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task InitializeAsync()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
SubscribeToSunStateChanges();
|
||||||
|
SubscribeToPersonStateChanges();
|
||||||
|
|
||||||
|
if (_logger.IsEnabled(LogLevel.Information))
|
||||||
|
{
|
||||||
|
_logger.LogInformation("LightMonitor initialized with {PersonCount} tracked persons",
|
||||||
|
_options.PersonEntityIds.Length);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error during LightMonitor initialization");
|
||||||
|
}
|
||||||
|
|
||||||
|
return Task.CompletedTask;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void SubscribeToSunStateChanges()
|
||||||
|
{
|
||||||
|
var sunEntity = new Entity(_haContext, _options.SunEntityId);
|
||||||
|
|
||||||
|
sunEntity.StateChanges()
|
||||||
|
.Subscribe(e =>
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (!string.Equals(e.New?.State, LightMonitorConsts.SunBelowHorizon,
|
||||||
|
StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (IsRecoveryTransition(e.Old?.State))
|
||||||
|
{
|
||||||
|
if (_logger.IsEnabled(LogLevel.Information))
|
||||||
|
{
|
||||||
|
_logger.LogInformation("Sun state recovered from {OldState}, ignoring", e.Old?.State);
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_logger.LogInformation("Sun went below horizon, checking if anyone is home");
|
||||||
|
|
||||||
|
if (_presenceService.IsAnyoneHome())
|
||||||
|
{
|
||||||
|
_lightControlService.TurnOnLight();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error handling sun state change");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private void SubscribeToPersonStateChanges()
|
||||||
|
{
|
||||||
|
foreach (var personEntityId in _options.PersonEntityIds)
|
||||||
|
{
|
||||||
|
var personEntity = new Entity(_haContext, personEntityId);
|
||||||
|
|
||||||
|
personEntity.StateChanges()
|
||||||
|
.Subscribe(e =>
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (!string.Equals(e.New?.State, LightMonitorConsts.PersonHomeState,
|
||||||
|
StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (IsRecoveryTransition(e.Old?.State))
|
||||||
|
{
|
||||||
|
if (_logger.IsEnabled(LogLevel.Information))
|
||||||
|
{
|
||||||
|
_logger.LogInformation("Person {EntityId} state recovered from {OldState}, ignoring",
|
||||||
|
personEntityId, e.Old?.State);
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_logger.IsEnabled(LogLevel.Information))
|
||||||
|
{
|
||||||
|
_logger.LogInformation("Person {EntityId} arrived home, checking if it is dark",
|
||||||
|
personEntityId);
|
||||||
|
}
|
||||||
|
|
||||||
|
_lightControlService.TurnOnLight();
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error handling person state change for {EntityId}", personEntityId);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsRecoveryTransition(string? oldState)
|
||||||
|
{
|
||||||
|
return oldState is null or LightMonitorConsts.UnavailableState or LightMonitorConsts.UnknownState;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using LightMonitor.Models;
|
||||||
|
using LightMonitorManager.Interface;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using NetDaemon.AppModel;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace LightMonitorManager;
|
||||||
|
|
||||||
|
public static class LightMonitorServiceRegistration
|
||||||
|
{
|
||||||
|
public static IServiceCollection AddLightMonitor(this IServiceCollection services, IConfiguration configuration)
|
||||||
|
{
|
||||||
|
var options = configuration
|
||||||
|
.GetSection(LightMonitorOptions.SectionName)
|
||||||
|
.Get<LightMonitorOptions>() ??
|
||||||
|
new LightMonitorOptions();
|
||||||
|
|
||||||
|
if (!options.Enabled)
|
||||||
|
{
|
||||||
|
return services;
|
||||||
|
}
|
||||||
|
|
||||||
|
services.AddNetDaemonApp<LightMonitorInit>()
|
||||||
|
.AddScoped<IPresenceService, PresenceService>()
|
||||||
|
.AddScoped<ILightControlService, LightControlService>();
|
||||||
|
|
||||||
|
return services;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using LightMonitor.Models;
|
||||||
|
using LightMonitorManager.Interface;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
using NetDaemon.HassModel;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace LightMonitorManager;
|
||||||
|
|
||||||
|
public sealed class PresenceService(
|
||||||
|
IHaContext haContext,
|
||||||
|
ILogger<PresenceService> logger,
|
||||||
|
IOptions<LightMonitorOptions> options) : IPresenceService
|
||||||
|
{
|
||||||
|
private readonly LightMonitorOptions _options = options.Value;
|
||||||
|
|
||||||
|
public bool IsAnyoneHome()
|
||||||
|
{
|
||||||
|
foreach (var personEntityId in _options.PersonEntityIds)
|
||||||
|
{
|
||||||
|
var state = haContext.GetState(personEntityId);
|
||||||
|
|
||||||
|
if (state?.State is null or LightMonitorConsts.UnavailableState or LightMonitorConsts.UnknownState)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!string.Equals(state.State, LightMonitorConsts.PersonHomeState,
|
||||||
|
StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (logger.IsEnabled(LogLevel.Debug))
|
||||||
|
{
|
||||||
|
logger.LogDebug("Person {EntityId} is home", personEntityId);
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<RootNamespace>LightMonitor.Models</RootNamespace>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\HomeAssistant.Models\HomeAssistant.Models.csproj"/>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="NetDaemon.Extensions.Mqtt" Version="26.43.1"/>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
namespace LightMonitor.Models;
|
||||||
|
|
||||||
|
public static class LightMonitorConsts
|
||||||
|
{
|
||||||
|
public const string DefaultLightEntityId = "light.sonoff_1002214d40";
|
||||||
|
public const string DefaultSunEntityId = "sun.sun";
|
||||||
|
|
||||||
|
public const string SunBelowHorizon = "below_horizon";
|
||||||
|
public const string SunAboveHorizon = "above_horizon";
|
||||||
|
public const string PersonHomeState = "home";
|
||||||
|
public const string LightOnState = "on";
|
||||||
|
public const string UnavailableState = "unavailable";
|
||||||
|
public const string UnknownState = "unknown";
|
||||||
|
|
||||||
|
public static readonly string[] DefaultPersonEntityIds =
|
||||||
|
[
|
||||||
|
"person.marius",
|
||||||
|
"person.erika",
|
||||||
|
"person.home_phone"
|
||||||
|
];
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user