Compare commits

...

16 Commits

Author SHA1 Message Date
gitea_admin 635e9625ea Merge pull request 'Apply code formatting cleanup across the monitor projects' (#1) from fix-style into main
Reviewed-on: #1
2026-12-01 10:40:57 +00:00
gitea_admin f919d6b25b Apply code formatting cleanup across the monitor projects
- Wrap using directives in `#region` blocks across the Battery, Boiler and NordPool sources and tests
- Expand single-statement guards and loops into braced blocks
- Realign wrapped method arguments, chained calls and continuations
- Replace target-typed `new()` with explicit generic construction and empty string literals with `string.Empty`
- Flatten the boiler config expression and reindent the remaining touched files
2026-12-01 12:33:31 +02:00
gitea_admin 77458383d1 Add braces to single-statement guards and refactor NordPool price fetching
- Expand inline guard, return and logger blocks across the monitor services, init classes and tests
- Have INordPoolPriceService take a per-date fetch delegate and expose ParseAndAdjust, moving the HA fetch call into NordPoolInit so the service can be registered singleton
- Record the NordPool and boiler service lifetimes in AGENTS.md
- Drop the unused persisted-state argument from the boiler test data helper
2026-12-01 11:59:31 +02:00
gitea_admin 24729ee267 Apply code formatting cleanup across monitor projects
- Reindent appsettings.json and the MSBuild project files
- Collapse single-statement guard blocks and tidy using and member order
- Normalize XML doc indentation and file endings
- Reorder BatteryMonitor test-data helpers and move the exclusion tests into
  their own region
- Carry the same formatting through the boiler config, control, entity and
  test files
2026-11-30 11:52:06 +02:00
gitea_admin cf8c9434c8 Clear the residual Qodana findings
- Drop the leftover unused using, parameter and date-time attribute reader
- Merge the remaining enum guard into its pattern
- Make the NordPool price DTO init-only
- Replace the four non-serializable theory matrices with single tests that
  iterate the same rows, so xUnit can still report them
- Replace Array.Empty with collection expressions and drop unused locals,
  redundant default arguments and duplicated tuple names
- Throw from the unreachable shower default instead of an empty section
- Cover the configurable PowerMonitor option overrides in a test so the
  init setters have a caller
2026-11-29 21:49:21 +02:00
gitea_admin 41ac93733e Clear Qodana findings in monitor runtime code
- Guard logger calls with IsEnabled so value-type arguments are not boxed
  when the level is disabled
- Make helper members static, narrow write-only properties to init or
  private get, and delete members no call site reaches
- Flatten nested conditionals and convert if/else chains into switch and
  ternary form
- Drop the unused *MonitorInit interfaces; NetDaemon instantiates the
  concrete app classes
- Drop the unused IConfiguration parameter from AddNordPool and
  AddPowerMonitor, and the unused IEntityManager.CreateEntitiesAsync
- Remove the ignored parameters of the boiler run-time tracker stub
- Pin the NordPool DTO price mapping explicitly so the getter use is
  visible to static analysis
- Fail Qodana on any finding and record the registration changes in
  AGENTS.md
2026-11-29 21:42:47 +02:00
gitea_admin 17774b40b8 Convert test data sources to typed TheoryData
Replace untyped MemberData sources with TheoryData<...>, use collection
expressions for array and list literals, drop redundant casts and null
suppressions, and give log-assertion helpers an IsEnabled setup so guarded
log calls stay verifiable.
2026-11-29 21:42:41 +02:00
gitea_admin ada3c77778 Fix culture-sensitive parsing, log swallowing and closure capture
- DateTimeTypeConverter parses with the invariant culture instead of the
  ambient one (NordPool timestamps arrive as ISO-8601)
- Shower last-shower-time state is formatted with the invariant culture
- PresenceServiceTests no longer captures the loop variable in a Moq setup
- CheapestIntervalsFinderTests compare prices with a tolerance instead of
  floating-point equality
- MqttRecreateApp logs the unit_of_measurement read failure instead of
  silently swallowing every exception
- LightMonitorOptions moves to LightMonitor.Models so the namespace matches
  the project and file location
2026-11-29 21:31:45 +02:00
gitea_admin b5e114be14 Exclude NetDaemon generated entities from Qodana analysis
The EntityGeneration folder is regenerated by nd-codegen and must not be
edited by hand, so its doc-comment findings are noise. Scope the analysis to
hand-written code instead of suppressing findings one by one.
2026-11-29 21:31:42 +02:00
gitea_admin 5777e641f6 Add shared test data builders and Qodana configuration
- Extract per-monitor *TestData helper classes and rework tests to use them
- Add boiler run-time tracker abstraction (implementation pending)
- Drop unused NordPool init/update-result types and stale PLAN.md
- Add qodana.yaml with the inspection set to keep the analysis focused
2026-11-29 21:30:13 +02:00
gitea_admin 1152462765 Add PowerMonitor power limit enforcement service
Introduce IPowerLimitEnforcementService and its implementation: turn off configured high-power switches and pause/restore entities when the limit is exceeded, notify via persistent_notification, and restore control after the recovery window once power drops below the limit. Includes cooldown handling and manual TriggerLimitBreach/ResetLimitBreach hooks, with FakeTimeProvider-based tests covering enforcement, recovery, cooldown and debug paths.

Add opencode.json wiring the HomeAssistant MCP server, the .junie MCP config files, and the implementation plan in PLAN.md.
2026-11-29 13:58:28 +02:00
gitea_admin f0bbd4f10b Enable PowerMonitor limit enforcement and prune unused boiler/replay code
PowerMonitor now ships enabled with power-limit enforcement settings: watt limit, recovery and cooldown windows, and switch-off plus pause/restore entity lists.

Remove the unused BoilerRunTimeTracker, its DI registration and tests, the StatusCleanedUp constant, and the boiler replay runner; simplify BoilerConfigReader, control-service logging and entity parsing. Switch CostAccumulator to System.Threading.Lock, update the Shower exhaust fan service and tests, drop the legacy HistoryReplay/McpServer sources and reporting tooling, and expand AGENTS.md with the current project wiring and DI notes.
2026-11-29 13:58:08 +02:00
gitea_admin f176a1b8fc Add manual MQTT recreation and NordPool price fetch buttons 2026-07-08 16:56:32 +03:00
gitea_admin 2706a6b188 Refactor services to use DI for IHaContext and TimeProvider 2026-07-03 12:15:44 +03:00
gitea_admin 7f280bea7b Fix bugs 2026-06-28 14:22:13 +03:00
gitea_admin e6bf8258bb Update 2026-06-28 13:58:35 +03:00
235 changed files with 13722 additions and 8205 deletions
+10
View File
@@ -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
}
+23
View File
@@ -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.
+46
View File
@@ -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.
+96
View File
@@ -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.
+2
View File
@@ -112,6 +112,8 @@ appsettings.*.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
+16
View File
@@ -0,0 +1,16 @@
{
"mcpServers": {
"UnoApp": {
"command": "dotnet",
"args": [
"dnx",
"-y",
"uno.devserver",
"--mcp-app"
]
},
"UnoDocs": {
"url": "https://mcp.platform.uno/v1"
}
}
}
+13
View File
@@ -0,0 +1,13 @@
{
"mcpServers": {
"UnoApp": {
"command": "dotnet",
"args": [
"dnx",
"-y",
"uno.devserver",
"--mcp-app"
]
}
}
}
+196
View File
@@ -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.
@@ -1,34 +1,34 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="8.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.3.0" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="FluentAssertions" Version="8.8.0" />
<PackageReference Include="Moq" Version="4.20.72" />
</ItemGroup>
<ItemGroup>
<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>
<Using Include="Xunit"/>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BatteryMonitor.Manager\BatteryMonitor.Manager.csproj" />
<ProjectReference Include="..\BatteryMonitor.Models\BatteryMonitor.Models.csproj" />
</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 &lt; threshold</c>
/// boundary, including zero/negative thresholds and int min/max thresholds.
/// </summary>
public static TheoryData<int, string, bool> ThresholdBoundaryRows { get; } = new TheoryData<int, string, bool>
{
{ 5, "4", true },
{ 5, "5", false },
{ 5, "6", false },
{ 5, "0", true },
{ 5, "-3", true },
{ 5, "4.9", true },
{ 5, "5.0", false },
{ 5, "100", false },
{ 1, "0.5", true },
{ 1, "1", false },
{ 20, "19", true },
{ 20, "19.99", true },
{ 20, "20", false },
{ 0, "-1", true },
{ 0, "0", false },
{ 0, "1", false },
{ -5, "-6", true },
{ -5, "-5", false },
{ -5, "-4", false },
{ 100, "99.9", true },
{ 100, "100", false },
{ 101, "100", true },
{ int.MaxValue, "100", true },
{ int.MinValue, "-2147483648", false },
{ int.MinValue, "-2147483649", true }
};
/// <summary>
/// States that must never produce a <see cref="BatterySensorInfo" />, including
/// whitespace/malformed strings and a null state.
/// </summary>
public static TheoryData<string?> UnusableStateRows { get; } =
[
"unavailable",
"unknown",
"UNAVAILABLE",
"UNKNOWN",
string.Empty,
" ",
"\t",
"not_a_number",
"3%",
"--1",
"low",
"1 2",
null
];
/// <summary>Device counts used to exercise notification payload generation.</summary>
public static TheoryData<int> NotifyDeviceCounts { get; } = [1, 2, 3, 5, 10, 50];
/// <summary>A battery device-class sensor.</summary>
public static EntitySpec Battery(string entityId, string? state, string? friendlyName = DefaultFriendlyName)
{
return new EntitySpec
{
EntityId = entityId,
State = state,
FriendlyName = friendlyName
};
}
/// <summary>A sensor with an arbitrary (or missing) device class.</summary>
public static EntitySpec Sensor(string entityId,
string? deviceClass,
string? state,
string? friendlyName = DefaultFriendlyName)
{
return new EntitySpec
{
EntityId = entityId,
DeviceClass = deviceClass,
State = state,
FriendlyName = friendlyName
};
}
public static EntityState CreateEntityState(EntitySpec spec)
{
var attributes = new Dictionary<string, object?>(StringComparer.Ordinal);
if (spec.DeviceClass is not null)
{
attributes["device_class"] = spec.DeviceClass;
}
if (spec.FriendlyName is not null)
{
attributes["friendly_name"] = spec.FriendlyName;
}
return new EntityState
{
State = spec.State,
AttributesJson = JsonSerializer.SerializeToElement(attributes)
};
}
/// <summary>
/// Wires <see cref="IHaContext.GetState" /> and <see cref="IHaContext.GetAllEntities" />
/// on the mock, exposing the entities in declaration order.
/// </summary>
public static void ConfigureHaContext(Mock<IHaContext> haContextMock, params EntitySpec[] entities)
{
var entityList = new List<Entity>(entities.Length);
foreach (var spec in entities)
{
if (spec.HasState)
{
haContextMock.Setup(h => h.GetState(spec.EntityId)).Returns(CreateEntityState(spec));
}
entityList.Add(new Entity(haContextMock.Object, spec.EntityId));
}
haContextMock.Setup(h => h.GetAllEntities()).Returns(entityList);
}
public static BatterySensorInfo CreateSensorInfo(string entityId, double batteryLevel, string? friendlyName = null)
{
return new BatterySensorInfo
{
EntityId = entityId,
FriendlyName = friendlyName ?? entityId,
BatteryLevel = batteryLevel
};
}
public static List<BatterySensorInfo> CreateSensorInfos(params (string EntityId, double BatteryLevel)[] sensors)
{
return [.. sensors.Select(s => CreateSensorInfo(s.EntityId, s.BatteryLevel))];
}
public static List<BatterySensorInfo> CreateSensorInfos(
params (string EntityId, string FriendlyName, double BatteryLevel)[] sensors)
{
return [.. sensors.Select(s => CreateSensorInfo(s.EntityId, s.BatteryLevel, s.FriendlyName))];
}
/// <summary>
/// Generates battery sensors with every integer level in <c>0..count-1</c>.
/// </summary>
public static EntitySpec[] CreateGeneratedBatteryEntities(int count)
{
return
[
.. Enumerable.Range(0, count)
.Select(i => Battery(
$"sensor.generated_battery_{i:D3}",
i.ToString(CultureInfo.InvariantCulture),
$"Generated Battery {i:D3}"))
];
}
/// <summary>
/// Generates notification devices with deterministic, non-monotonic levels so
/// ordering behaviour is exercised over more than a handful of rows.
/// </summary>
public static IReadOnlyList<BatterySensorInfo> CreateGeneratedSensorInfos(int count)
{
return
[
.. Enumerable.Range(0, count)
.Select(i => CreateSensorInfo(
$"sensor.generated_{i:D3}",
i * 37 % 101,
$"Generated Device {i:D3}"))
];
}
/// <summary>
/// Cross-product of every excluded keyword (lower and upper case) plus
/// non-excluded look-alikes that must not be filtered.
/// </summary>
public static TheoryData<string, bool> ExcludedEntityIdRows()
{
var data = new TheoryData<string, bool>();
foreach (var keyword in BatteryMonitorConsts.ExcludedKeywords)
{
data.Add($"sensor.my_{keyword}_battery_level", true);
data.Add($"SENSOR.MY_{keyword.ToUpperInvariant()}_BATTERY_LEVEL", true);
}
data.Add("sensor.iphone", true);
data.Add("sensor.x_phone_x", true);
data.Add("sensor.bathroom_battery", false);
data.Add("sensor.boiler_temp_battery", false);
data.Add("sensor.aquarium_leak_sensor_battery", false);
data.Add("sensor.temperature", false);
data.Add(string.Empty, false);
data.Add(" ", false);
return data;
}
/// <summary>
/// Describes one entity exposed through <see cref="IHaContext.GetAllEntities" />.
/// </summary>
public sealed record EntitySpec
{
public required string EntityId { get; init; }
public string? State { get; init; } = "50";
public string? DeviceClass { get; init; } = BatteryMonitorConsts.BatteryDeviceClass;
public string? FriendlyName { get; init; } = DefaultFriendlyName;
/// <summary>When false the context returns no <see cref="EntityState" /> for the entity.</summary>
public bool HasState { get; init; } = true;
}
}
@@ -1,63 +1,130 @@
#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 BatteryMonitor.Models;
using BatteryMonitorManager;
using static BatteryMonitor.Manager.Tests.BatteryMonitorTestData;
#endregion
namespace BatteryMonitor.Manager.Tests;
public class BatteryNotificationServiceTests
{
private readonly Mock<IHaContext> _haContextMock;
private readonly Mock<ILogger<BatteryNotificationService>> _loggerMock;
public BatteryNotificationServiceTests()
{
_haContextMock = new Mock<IHaContext>();
_loggerMock = new Mock<ILogger<BatteryNotificationService>>();
}
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
[Fact]
public void NotifyLowBattery_WithDevices_ShouldCallPersistentNotificationCreate()
[Theory]
[MemberData(nameof(NotifyDeviceCounts), MemberType = typeof(BatteryMonitorTestData))]
public void NotifyLowBattery_WithDevices_ShouldCallPersistentNotificationCreate(int deviceCount)
{
var devices = new List<BatterySensorInfo>
{
new() { EntityId = "sensor.bathroom_battery", FriendlyName = "Bathroom Battery", BatteryLevel = 3 },
new() { EntityId = "sensor.bedroom_battery", FriendlyName = "Bedroom Battery", BatteryLevel = 1 }
};
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(
BatteryMonitorConsts.PersistentNotificationDomain,
BatteryMonitorConsts.PersistentNotificationCreateService,
It.IsAny<ServiceTarget?>(),
It.IsAny<object?>()), Times.Once);
It.IsAny<string>(),
It.IsAny<string>(),
It.IsAny<ServiceTarget?>(),
It.IsAny<object?>()), Times.Never);
_loggerMock.Invocations.Should().BeEmpty();
}
[Fact]
public void NotifyLowBattery_WithEmptyList_ShouldNotCallService()
public void NotifyLowBattery_ShouldSendTitleNotificationIdAndDeviceSummary()
{
var devices = new List<BatterySensorInfo>();
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);
_haContextMock.Verify(h => h.CallService(
It.IsAny<string>(),
It.IsAny<string>(),
It.IsAny<ServiceTarget?>(),
It.IsAny<object?>()), Times.Never);
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
@@ -70,11 +137,25 @@ public class BatteryNotificationServiceTests
var sut = CreateSut();
sut.DismissNotification();
_haContextMock.Verify(h => h.CallService(
BatteryMonitorConsts.PersistentNotificationDomain,
BatteryMonitorConsts.PersistentNotificationDismissService,
It.IsAny<ServiceTarget?>(),
It.IsAny<object?>()), Times.Once);
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
@@ -84,41 +165,90 @@ public class BatteryNotificationServiceTests
[Fact]
public void BuildNotificationMessage_ShouldOrderByBatteryLevel()
{
var devices = new List<BatterySensorInfo>
{
new() { EntityId = "sensor.a", FriendlyName = "Device A", BatteryLevel = 4 },
new() { EntityId = "sensor.b", FriendlyName = "Device B", BatteryLevel = 1 },
new() { EntityId = "sensor.c", FriendlyName = "Device C", BatteryLevel = 3 }
};
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 = new List<BatterySensorInfo>
{
new() { EntityId = "sensor.a", FriendlyName = "Device A", BatteryLevel = 2 }
};
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 = new List<BatterySensorInfo>
{
new() { EntityId = "sensor.a", FriendlyName = "Bathroom Battery", BatteryLevel = 3 }
};
var devices = CreateSensorInfos(("sensor.a", "Bathroom Battery", 3));
var message = BatteryNotificationService.BuildNotificationMessage(devices);
@@ -129,15 +259,36 @@ public class BatteryNotificationServiceTests
[Fact]
public void BuildNotificationMessage_WithSingleDevice_ShouldFormatCorrectly()
{
var devices = new List<BatterySensorInfo>
{
new() { EntityId = "sensor.a", FriendlyName = "Test Device", BatteryLevel = 1 }
};
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
}
}
@@ -1,69 +1,55 @@
using System.Text.Json;
#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 BatteryMonitorManager;
using BatteryMonitor.Models;
using static BatteryMonitor.Manager.Tests.BatteryMonitorTestData;
#endregion
namespace BatteryMonitor.Manager.Tests;
public class BatterySensorDiscoveryServiceTests
{
private readonly Mock<IHaContext> _haContextMock;
private readonly Mock<ILogger<BatterySensorDiscoveryService>> _loggerMock;
public BatterySensorDiscoveryServiceTests()
{
_haContextMock = new Mock<IHaContext>();
_loggerMock = new Mock<ILogger<BatterySensorDiscoveryService>>();
}
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 (string entityId, string? deviceClass, string? state, string? friendlyName)[] entities)
private void SetupEntities(params EntitySpec[] entities)
{
var entityList = new List<Entity>();
foreach (var (entityId, deviceClass, state, friendlyName) in entities)
{
var attributes = new Dictionary<string, object?>();
if (deviceClass is not null)
{
attributes["device_class"] = deviceClass;
}
if (friendlyName is not null)
{
attributes["friendly_name"] = friendlyName;
}
var attributesJson = JsonSerializer.SerializeToElement(attributes);
var entityState = new EntityState { AttributesJson = attributesJson, State = state };
_haContextMock.Setup(h => h.GetState(entityId)).Returns(entityState);
var entity = new Entity(_haContextMock.Object, entityId);
entityList.Add(entity);
}
_haContextMock.Setup(h => h.GetAllEntities()).Returns(entityList);
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(
("sensor.bathroom_battery", "battery", "3", "Bathroom Battery"),
("sensor.bedroom_battery", "battery", "80", "Bedroom Battery"),
("sensor.boiler_temp_battery", "battery", "2", "Boiler Temp Battery")
);
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);
@@ -71,135 +57,117 @@ public class BatterySensorDiscoveryServiceTests
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");
}
[Fact]
public void DiscoverLowBatterySensors_ShouldExcludePhoneDevices()
[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(
("sensor.bathroom_battery", "battery", "2", "Bathroom Battery"),
("sensor.erikas_iphone_battery_level", "battery", "1", "Erika's iPhone Battery"),
("sensor.home_phone_battery_state", "battery", "3", "Home Phone Battery")
);
Battery("sensor.bathroom_battery", "2", "Bathroom Battery"),
Battery(excludedEntityId, "1", friendlyName)
);
var sut = CreateSut();
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
result.Should().HaveCount(1);
result.First().EntityId.Should().Be("sensor.bathroom_battery");
result.Should().ContainSingle();
result[0].EntityId.Should().Be("sensor.bathroom_battery");
}
[Fact]
public void DiscoverLowBatterySensors_ShouldExcludeWatchDevices()
[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.bathroom_battery", "battery", "2", "Bathroom Battery"),
("sensor.marius_watch_battery_level", "battery", "1", "Marius Watch Battery")
);
Sensor(entityId, deviceClass, "2", "Ignored Entity"),
Battery("sensor.bedroom_battery", "3", "Bedroom Battery")
);
var sut = CreateSut();
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
result.Should().HaveCount(1);
result.First().EntityId.Should().Be("sensor.bathroom_battery");
result.Should().ContainSingle();
result[0].EntityId.Should().Be("sensor.bedroom_battery");
}
[Fact]
public void DiscoverLowBatterySensors_ShouldExcludeGalaxyDevices()
[Theory]
[MemberData(nameof(UnusableStateRows), MemberType = typeof(BatteryMonitorTestData))]
public void DiscoverLowBatterySensors_ShouldSkipUnusableStates(string? state)
{
SetupEntities(
("sensor.bathroom_battery", "battery", "2", "Bathroom Battery"),
("sensor.sm_s936b_battery_level", "battery", "1", "Galaxy S24 Battery")
);
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().HaveCount(1);
result.First().EntityId.Should().Be("sensor.bathroom_battery");
result.Should().ContainSingle();
result[0].EntityId.Should().Be("sensor.bedroom_battery");
}
[Fact]
public void DiscoverLowBatterySensors_ShouldIgnoreNonSensorDomain()
public void DiscoverLowBatterySensors_WhenEntityStateIsNull_ShouldSkipSensor()
{
SetupEntities(
("binary_sensor.bathroom_battery", "battery", "2", "Bathroom Battery"),
("sensor.bedroom_battery", "battery", "3", "Bedroom Battery")
);
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().HaveCount(1);
result.First().EntityId.Should().Be("sensor.bedroom_battery");
result.Should().ContainSingle();
result[0].EntityId.Should().Be("sensor.bedroom_battery");
}
[Fact]
public void DiscoverLowBatterySensors_ShouldIgnoreNonBatteryDeviceClass()
[Theory]
[MemberData(nameof(ThresholdBoundaryRows), MemberType = typeof(BatteryMonitorTestData))]
public void DiscoverLowBatterySensors_ShouldApplyStrictThresholdBoundary(int thresholdPercent,
string state,
bool expectedIncluded)
{
SetupEntities(
("sensor.bathroom_temperature", "temperature", "2", "Bathroom Temperature"),
("sensor.bedroom_battery", "battery", "3", "Bedroom Battery")
);
SetupEntities(Battery("sensor.boundary_battery", state, "Boundary Battery"));
var sut = CreateSut();
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
var result = sut.DiscoverLowBatterySensors(thresholdPercent);
result.Should().HaveCount(1);
result.First().EntityId.Should().Be("sensor.bedroom_battery");
}
result.Should().HaveCount(expectedIncluded ? 1 : 0);
[Fact]
public void DiscoverLowBatterySensors_ShouldSkipUnavailableState()
{
SetupEntities(
("sensor.bathroom_battery", "battery", "unavailable", "Bathroom Battery"),
("sensor.bedroom_battery", "battery", "3", "Bedroom Battery")
);
if (!expectedIncluded)
{
return;
}
var sut = CreateSut();
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
result.Should().HaveCount(1);
result.First().EntityId.Should().Be("sensor.bedroom_battery");
}
[Fact]
public void DiscoverLowBatterySensors_ShouldSkipUnknownState()
{
SetupEntities(
("sensor.bathroom_battery", "battery", "unknown", "Bathroom Battery"),
("sensor.bedroom_battery", "battery", "3", "Bedroom Battery")
);
var sut = CreateSut();
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
result.Should().HaveCount(1);
}
[Fact]
public void DiscoverLowBatterySensors_ShouldSkipNonParsableState()
{
SetupEntities(
("sensor.bathroom_battery", "battery", "not_a_number", "Bathroom Battery"),
("sensor.bedroom_battery", "battery", "3", "Bedroom Battery")
);
var sut = CreateSut();
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
result.Should().HaveCount(1);
result.First().EntityId.Should().Be("sensor.bedroom_battery");
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.temperature", "temperature", "22", "Temperature"),
("switch.some_switch", null, "on", "Switch")
);
Sensor("sensor.temperature", "temperature", "22", "Temperature"),
Sensor("switch.some_switch", null, "on", "Switch")
);
var sut = CreateSut();
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
@@ -211,9 +179,10 @@ public class BatterySensorDiscoveryServiceTests
public void DiscoverLowBatterySensors_WhenAllAboveThreshold_ShouldReturnEmpty()
{
SetupEntities(
("sensor.bathroom_battery", "battery", "50", "Bathroom Battery"),
("sensor.bedroom_battery", "battery", "80", "Bedroom Battery")
);
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);
@@ -222,101 +191,114 @@ public class BatterySensorDiscoveryServiceTests
}
[Fact]
public void DiscoverLowBatterySensors_ShouldRespectCustomThreshold()
public void DiscoverLowBatterySensors_WhenThereAreNoEntities_ShouldReturnEmpty()
{
SetupEntities(
("sensor.bathroom_battery", "battery", "15", "Bathroom Battery"),
("sensor.bedroom_battery", "battery", "25", "Bedroom Battery")
);
var sut = CreateSut();
var result = sut.DiscoverLowBatterySensors(20);
result.Should().HaveCount(1);
result.First().EntityId.Should().Be("sensor.bathroom_battery");
}
[Fact]
public void DiscoverLowBatterySensors_ShouldPopulateFriendlyName()
{
SetupEntities(
("sensor.bathroom_battery", "battery", "2", "Bathroom Battery")
);
SetupEntities();
var sut = CreateSut();
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
result.Should().HaveCount(1);
result.First().FriendlyName.Should().Be("Bathroom Battery");
result.First().BatteryLevel.Should().Be(2);
result.Should().NotBeNull();
result.Should().BeEmpty();
}
[Fact]
public void DiscoverLowBatterySensors_ShouldUseEntityIdWhenNoFriendlyName()
public void DiscoverLowBatterySensors_WithDuplicateSensorIds_ShouldReportEachOccurrence()
{
SetupEntities(
("sensor.bathroom_battery", "battery", "2", null)
);
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(1);
result.First().FriendlyName.Should().Be("sensor.bathroom_battery");
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
[Fact]
public void IsBatterySensor_WithBatteryDeviceClass_ShouldReturnTrue()
[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.bathroom_battery", "battery", "50", "Bathroom Battery"));
SetupEntities(Sensor(entityId, deviceClass, "50", "Some Entity"));
var entity = new Entity(_haContextMock.Object, entityId);
BatterySensorDiscoveryService.IsBatterySensor(entity).Should().Be(expected);
}
[Fact]
public void IsBatterySensor_WhenEntityHasNoState_ShouldReturnFalse()
{
SetupEntities(new EntitySpec { EntityId = "sensor.bathroom_battery", HasState = false });
var entity = new Entity(_haContextMock.Object, "sensor.bathroom_battery");
BatterySensorDiscoveryService.IsBatterySensor(entity).Should().BeTrue();
}
[Fact]
public void IsBatterySensor_WithNonSensorDomain_ShouldReturnFalse()
{
SetupEntities(("binary_sensor.bathroom_battery", "battery", "50", "Bathroom Battery"));
var entity = new Entity(_haContextMock.Object, "binary_sensor.bathroom_battery");
BatterySensorDiscoveryService.IsBatterySensor(entity).Should().BeFalse();
}
[Fact]
public void IsBatterySensor_WithNonBatteryDeviceClass_ShouldReturnFalse()
{
SetupEntities(("sensor.bathroom_temperature", "temperature", "22", "Bathroom Temperature"));
var entity = new Entity(_haContextMock.Object, "sensor.bathroom_temperature");
BatterySensorDiscoveryService.IsBatterySensor(entity).Should().BeFalse();
}
#endregion
#region IsExcludedDevice
[Theory]
[InlineData("sensor.erikas_iphone_battery_level", true)]
[InlineData("sensor.home_phone_battery_state", true)]
[InlineData("sensor.marius_watch_battery_level", true)]
[InlineData("sensor.sm_s936b_battery_level", true)]
[InlineData("sensor.sm_a536b_battery_level", true)]
[InlineData("sensor.pixel_8_battery_level", true)]
[InlineData("sensor.oneplus_battery_level", true)]
[InlineData("sensor.ipad_battery_level", true)]
[InlineData("sensor.galaxy_s24_battery", true)]
[InlineData("sensor.bathroom_battery", false)]
[InlineData("sensor.boiler_temp_battery", false)]
[InlineData("sensor.aquarium_leak_sensor_battery", false)]
public void IsExcludedDevice_ShouldCorrectlyIdentifyExclusions(string entityId, bool expected)
{
BatterySensorDiscoveryService.IsExcludedDevice(entityId).Should().Be(expected);
}
#endregion
}
}
@@ -8,20 +8,20 @@
</PropertyGroup>
<ItemGroup>
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
<_Parameter1>BatteryMonitor.Manager.Tests</_Parameter1>
</AssemblyAttribute>
<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" />
<ProjectReference Include="..\HomeAssistant.Entities\HomeAssistant.Entities.csproj"/>
<ProjectReference Include="..\BatteryMonitor.Models\BatteryMonitor.Models.csproj"/>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.5" />
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.11.0" />
<PackageReference Include="NetDaemon.HassModel" Version="26.11.0" />
<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>
+31 -21
View File
@@ -1,21 +1,26 @@
#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;
using BatteryMonitorManager.Interface;
using BatteryMonitorManager.Models;
#endregion
namespace BatteryMonitorManager;
[NetDaemonApp]
public sealed class BatteryMonitorInit : IBatteryMonitorInit
public sealed class BatteryMonitorInit
{
private readonly ILogger<BatteryMonitorInit> _logger;
private readonly IScheduler _scheduler;
private readonly IBatterySensorDiscoveryService _discoveryService;
private readonly ILogger<BatteryMonitorInit> _logger;
private readonly IBatteryNotificationService _notificationService;
private readonly BatteryMonitorOptions _options;
private readonly IScheduler _scheduler;
public BatteryMonitorInit(
ILogger<BatteryMonitorInit> logger,
@@ -46,7 +51,7 @@ public sealed class BatteryMonitorInit : IBatteryMonitorInit
}
}
public async Task InitializeAsync()
private async Task InitializeAsync()
{
try
{
@@ -54,34 +59,39 @@ public sealed class BatteryMonitorInit : IBatteryMonitorInit
CheckAndNotify();
_logger.LogInformation("BatteryMonitor initialized with threshold {Threshold}%", _options.BatteryThresholdPercent);
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("BatteryMonitor initialized with threshold {Threshold}%",
_options.BatteryThresholdPercent);
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error initializing BatteryMonitor");
throw;
}
}
private void ScheduleDailyCheck()
{
_scheduler.ScheduleCron(BatteryMonitor.Models.BatteryMonitorConsts.DailyCheckCron, () =>
{
try
{
_logger.LogInformation("Running scheduled daily battery check");
CheckAndNotify();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error during scheduled battery check");
}
});
_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");
}
internal void CheckAndNotify()
private void CheckAndNotify()
{
var lowBatteryDevices = _discoveryService.DiscoverLowBatterySensors(_options.BatteryThresholdPercent);
@@ -95,4 +105,4 @@ public sealed class BatteryMonitorInit : IBatteryMonitorInit
_logger.LogDebug("No low battery devices found");
}
}
}
}
@@ -1,8 +1,12 @@
#region
using BatteryMonitorManager.Interface;
using BatteryMonitorManager.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using NetDaemon.AppModel;
using BatteryMonitorManager.Interface;
using BatteryMonitorManager.Models;
#endregion
namespace BatteryMonitorManager;
@@ -11,8 +15,9 @@ public static class BatteryMonitorServiceRegistration
public static IServiceCollection AddBatteryMonitor(this IServiceCollection services, IConfiguration configuration)
{
var options = configuration
.GetSection(BatteryMonitorOptions.SectionName)
.Get<BatteryMonitorOptions>() ?? new BatteryMonitorOptions();
.GetSection(BatteryMonitorOptions.SectionName)
.Get<BatteryMonitorOptions>() ??
new BatteryMonitorOptions();
if (!options.Enabled)
{
@@ -20,10 +25,10 @@ public static class BatteryMonitorServiceRegistration
}
services
.AddNetDaemonApp<BatteryMonitorInit>()
.AddScoped<IBatterySensorDiscoveryService, BatterySensorDiscoveryService>()
.AddScoped<IBatteryNotificationService, BatteryNotificationService>();
.AddNetDaemonApp<BatteryMonitorInit>()
.AddScoped<IBatterySensorDiscoveryService, BatterySensorDiscoveryService>()
.AddScoped<IBatteryNotificationService, BatteryNotificationService>();
return services;
}
}
}
@@ -1,24 +1,19 @@
#region
using System.Text;
using Microsoft.Extensions.Logging;
using NetDaemon.HassModel;
using BatteryMonitor.Models;
using BatteryMonitorManager.Interface;
using Microsoft.Extensions.Logging;
using NetDaemon.HassModel;
#endregion
namespace BatteryMonitorManager;
public sealed class BatteryNotificationService : IBatteryNotificationService
public sealed class BatteryNotificationService(
IHaContext haContext,
ILogger<BatteryNotificationService> logger) : IBatteryNotificationService
{
private readonly IHaContext _haContext;
private readonly ILogger<BatteryNotificationService> _logger;
public BatteryNotificationService(
IHaContext haContext,
ILogger<BatteryNotificationService> logger)
{
_haContext = haContext;
_logger = logger;
}
public void NotifyLowBattery(IReadOnlyList<BatterySensorInfo> lowBatteryDevices)
{
if (lowBatteryDevices.Count == 0)
@@ -28,32 +23,35 @@ public sealed class BatteryNotificationService : IBatteryNotificationService
var message = BuildNotificationMessage(lowBatteryDevices);
_haContext.CallService(
BatteryMonitorConsts.PersistentNotificationDomain,
BatteryMonitorConsts.PersistentNotificationCreateService,
data: new
{
title = BatteryMonitorConsts.NotificationTitle,
message,
notification_id = BatteryMonitorConsts.NotificationId
});
haContext.CallService(
BatteryMonitorConsts.PersistentNotificationDomain,
BatteryMonitorConsts.PersistentNotificationCreateService,
data: new
{
title = BatteryMonitorConsts.NotificationTitle,
message,
notification_id = BatteryMonitorConsts.NotificationId
});
_logger.LogInformation(
"Sent low battery notification for {Count} device(s)",
lowBatteryDevices.Count);
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
});
haContext.CallService(
BatteryMonitorConsts.PersistentNotificationDomain,
BatteryMonitorConsts.PersistentNotificationDismissService,
data: new
{
notification_id = BatteryMonitorConsts.NotificationId
});
_logger.LogDebug("Dismissed low battery notification");
logger.LogDebug("Dismissed low battery notification");
}
internal static string BuildNotificationMessage(IReadOnlyList<BatterySensorInfo> devices)
@@ -69,4 +67,4 @@ public sealed class BatteryNotificationService : IBatteryNotificationService
return sb.ToString().TrimEnd();
}
}
}
@@ -1,40 +1,38 @@
#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;
using BatteryMonitor.Models;
using BatteryMonitorManager.Interface;
#endregion
namespace BatteryMonitorManager;
public sealed class BatterySensorDiscoveryService : IBatterySensorDiscoveryService
public sealed class BatterySensorDiscoveryService(
IHaContext haContext,
ILogger<BatterySensorDiscoveryService> logger) : IBatterySensorDiscoveryService
{
private readonly IHaContext _haContext;
private readonly ILogger<BatterySensorDiscoveryService> _logger;
public BatterySensorDiscoveryService(
IHaContext haContext,
ILogger<BatterySensorDiscoveryService> logger)
{
_haContext = haContext;
_logger = logger;
}
public IReadOnlyList<BatterySensorInfo> DiscoverLowBatterySensors(int thresholdPercent)
{
var allEntities = _haContext.GetAllEntities();
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();
.Where(IsBatterySensor)
.Where(e => !IsExcludedDevice(e.EntityId))
.Select(e => TryCreateSensorInfo(e, thresholdPercent))
.Where(info => info is not null)
.ToList();
_logger.LogInformation(
"Battery check: found {Count} sensors below {Threshold}%",
lowBatterySensors.Count, thresholdPercent);
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation(
"Battery check: found {Count} sensors below {Threshold}%",
lowBatterySensors.Count, thresholdPercent);
}
return lowBatterySensors!;
}
@@ -56,7 +54,7 @@ public sealed class BatterySensorDiscoveryService : IBatterySensorDiscoveryServi
var lowerEntityId = entityId.ToLowerInvariant();
return BatteryMonitorConsts.ExcludedKeywords
.Any(keyword => lowerEntityId.Contains(keyword, StringComparison.OrdinalIgnoreCase));
.Any(keyword => lowerEntityId.Contains(keyword, StringComparison.OrdinalIgnoreCase));
}
private BatterySensorInfo? TryCreateSensorInfo(Entity entity, int thresholdPercent)
@@ -65,13 +63,23 @@ public sealed class BatterySensorDiscoveryService : IBatterySensorDiscoveryServi
if (state is null or "unavailable" or "unknown")
{
_logger.LogDebug("Skipping battery sensor {EntityId}: state is {State}", entity.EntityId, state ?? "null");
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("Skipping battery sensor {EntityId}: state is {State}", entity.EntityId,
state ?? "null");
}
return null;
}
if (!double.TryParse(state, CultureInfo.InvariantCulture, out var batteryLevel))
{
_logger.LogDebug("Skipping battery sensor {EntityId}: unable to parse state '{State}'", entity.EntityId, state);
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("Skipping battery sensor {EntityId}: unable to parse state '{State}'", entity.EntityId,
state);
}
return null;
}
@@ -80,8 +88,7 @@ public sealed class BatterySensorDiscoveryService : IBatterySensorDiscoveryServi
return null;
}
var friendlyName = GetJsonStringProperty(entity.EntityState?.AttributesJson, "friendly_name")
?? entity.EntityId;
var friendlyName = GetJsonStringProperty(entity.EntityState?.AttributesJson, "friendly_name") ?? entity.EntityId;
return new BatterySensorInfo
{
@@ -91,7 +98,7 @@ public sealed class BatterySensorDiscoveryService : IBatterySensorDiscoveryServi
};
}
internal static string? GetJsonStringProperty(JsonElement? element, string propertyName)
private static string? GetJsonStringProperty(JsonElement? element, string propertyName)
{
if (element is null)
{
@@ -99,7 +106,7 @@ public sealed class BatterySensorDiscoveryService : IBatterySensorDiscoveryServi
}
return element.Value.TryGetProperty(propertyName, out var value)
? value.GetString()
: null;
? value.GetString()
: null;
}
}
}
@@ -1,6 +0,0 @@
namespace BatteryMonitorManager.Interface;
public interface IBatteryMonitorInit
{
Task InitializeAsync();
}
@@ -1,5 +1,9 @@
#region
using BatteryMonitor.Models;
#endregion
namespace BatteryMonitorManager.Interface;
public interface IBatteryNotificationService
@@ -7,4 +11,4 @@ public interface IBatteryNotificationService
void NotifyLowBattery(IReadOnlyList<BatterySensorInfo> lowBatteryDevices);
void DismissNotification();
}
}
@@ -1,8 +1,12 @@
#region
using BatteryMonitor.Models;
#endregion
namespace BatteryMonitorManager.Interface;
public interface IBatterySensorDiscoveryService
{
IReadOnlyList<BatterySensorInfo> DiscoverLowBatterySensors(int thresholdPercent);
}
}
@@ -1,12 +1,16 @@
#region
using BatteryMonitor.Models;
#endregion
namespace BatteryMonitorManager.Models;
public sealed class BatteryMonitorOptions
{
public const string SectionName = "BatteryMonitor";
public bool Enabled { get; set; }
public bool Enabled { get; init; }
public int BatteryThresholdPercent { get; set; } = BatteryMonitorConsts.DefaultBatteryThresholdPercent;
}
public int BatteryThresholdPercent { get; init; } = BatteryMonitorConsts.DefaultBatteryThresholdPercent;
}
@@ -32,4 +32,4 @@ public static class BatteryMonitorConsts
"oneplus",
"ipad"
];
}
}
+1 -1
View File
@@ -7,4 +7,4 @@ public sealed class BatterySensorInfo
public required string FriendlyName { get; init; }
public required double BatteryLevel { get; init; }
}
}
@@ -1,21 +1,52 @@
#region
using BoilerMonitor.Models.Enums;
using BoilerMonitorManager;
using FluentAssertions;
using Microsoft.Extensions.Logging;
using Moq;
using BoilerMonitorManager;
#endregion
namespace BoilerMonitor.Manager.Tests;
public class BoilerControlServiceTests
{
private readonly BoilerControlService _sut;
private readonly Mock<ILogger<BoilerControlService>> _loggerMock = new Mock<ILogger<BoilerControlService>>();
public BoilerControlServiceTests()
private BoilerControlService CreateSut()
{
var loggerMock = new Mock<ILogger<BoilerControlService>>();
_sut = new BoilerControlService(loggerMock.Object);
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]
@@ -23,132 +54,160 @@ public class BoilerControlServiceTests
[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 = _sut.DetermineAction(
isNowCheap: true, waterReady: false, currentSwitchState: switchState,
budgetExhausted: false, budgetOverride: false);
var result = CreateSut()
.DetermineAction(
true, false, switchState,
false, false);
result.Should().Be(BoilerAction.TurnOn);
}
[Theory]
[InlineData("off")]
[InlineData(null)]
public void DetermineAction_WhenBudgetExhaustedButOverrideOn_ShouldReturnTurnOn(string? switchState)
[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 = _sut.DetermineAction(
isNowCheap: true, waterReady: false, currentSwitchState: switchState,
budgetExhausted: true, budgetOverride: true);
var result = CreateSut()
.DetermineAction(
true, false, switchState,
true, true);
result.Should().Be(BoilerAction.TurnOn);
result.Should().Be(expectedAction);
}
#endregion
#region TurnOff scenarios
[Fact]
public void DetermineAction_WhenNotCheapAndSwitchIsOn_ShouldReturnTurnOff()
{
var result = _sut.DetermineAction(
isNowCheap: false, waterReady: false, currentSwitchState: "on",
budgetExhausted: false, budgetOverride: false);
result.Should().Be(BoilerAction.TurnOff);
}
[Fact]
public void DetermineAction_WhenWaterReadyAndSwitchIsOn_ShouldReturnTurnOff()
{
var result = _sut.DetermineAction(
isNowCheap: true, waterReady: true, currentSwitchState: "on",
budgetExhausted: false, budgetOverride: false);
result.Should().Be(BoilerAction.TurnOff);
}
[Fact]
public void DetermineAction_WhenBudgetExhaustedAndNoOverride_ShouldReturnTurnOff()
{
var result = _sut.DetermineAction(
isNowCheap: true, waterReady: false, currentSwitchState: "on",
budgetExhausted: true, budgetOverride: false);
result.Should().Be(BoilerAction.TurnOff);
}
[Theory]
[InlineData("on")]
[InlineData("ON")]
[InlineData("On")]
public void DetermineAction_WhenNotCheapAndSwitchIsOnCaseInsensitive_ShouldReturnTurnOff(string switchState)
[InlineData("oN")]
public void DetermineAction_WhenNotCheapAndSwitchIsOn_ShouldReturnTurnOff(string switchState)
{
var result = _sut.DetermineAction(
isNowCheap: false, waterReady: false, currentSwitchState: switchState,
budgetExhausted: false, budgetOverride: false);
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 NoChange scenarios
#region Comprehensive truth tables
[Fact]
public void DetermineAction_WhenCheapAndNotReadyAndAlreadyOn_ShouldReturnNoChange()
/// <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>
{
var result = _sut.DetermineAction(
isNowCheap: true, waterReady: false, currentSwitchState: "on",
budgetExhausted: false, budgetOverride: false);
result.Should().Be(BoilerAction.NoChange);
}
[Fact]
public void DetermineAction_WhenNotCheapAndAlreadyOff_ShouldReturnNoChange()
{
var result = _sut.DetermineAction(
isNowCheap: false, waterReady: false, currentSwitchState: "off",
budgetExhausted: false, budgetOverride: false);
result.Should().Be(BoilerAction.NoChange);
}
[Fact]
public void DetermineAction_WhenBudgetExhaustedAndAlreadyOff_ShouldReturnNoChange()
{
var result = _sut.DetermineAction(
isNowCheap: true, waterReady: false, currentSwitchState: "off",
budgetExhausted: true, budgetOverride: false);
result.Should().Be(BoilerAction.NoChange);
}
#endregion
#region Comprehensive theory covering all key combinations
{ 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]
[InlineData(true, false, "off", false, false, BoilerAction.TurnOn)]
[InlineData(true, false, "on", false, false, BoilerAction.NoChange)]
[InlineData(true, true, "on", false, false, BoilerAction.TurnOff)]
[InlineData(true, true, "off", false, false, BoilerAction.NoChange)]
[InlineData(false, false, "on", false, false, BoilerAction.TurnOff)]
[InlineData(false, false, "off", false, false, BoilerAction.NoChange)]
[InlineData(true, false, "on", true, false, BoilerAction.TurnOff)]
[InlineData(true, false, "off", true, false, BoilerAction.NoChange)]
[InlineData(true, false, "off", true, true, BoilerAction.TurnOn)]
[InlineData(true, false, "on", true, true, BoilerAction.NoChange)]
public void DetermineAction_AllCombinations_ShouldReturnExpectedAction(
bool isNowCheap, bool waterReady, string switchState,
bool budgetExhausted, bool budgetOverride, BoilerAction expectedAction)
[MemberData(nameof(SwitchOnActionMatrix))]
public void DetermineAction_AllCombinationsWhileSwitchIsOn_ShouldReturnExpectedAction(
bool isNowCheap,
bool waterReady,
bool budgetExhausted,
bool budgetOverride,
BoilerAction expectedAction)
{
var result = _sut.DetermineAction(isNowCheap, waterReady, switchState, budgetExhausted, budgetOverride);
var result = CreateSut()
.DetermineAction(
isNowCheap, waterReady, "on", budgetExhausted, budgetOverride);
result.Should().Be(expectedAction);
}
/// <summary>
/// Complete truth table for a boiler that is currently OFF: it may only turn on when
/// it is cheap, water is not ready and the budget is available (or overridden).
/// </summary>
public static TheoryData<bool, bool, bool, bool, BoilerAction> SwitchOffActionMatrix => new TheoryData<bool, bool, bool, bool, BoilerAction>
{
{ false, false, false, false, BoilerAction.NoChange },
{ false, false, false, true, BoilerAction.NoChange },
{ false, false, true, false, BoilerAction.NoChange },
{ false, false, true, true, BoilerAction.NoChange },
{ false, true, false, false, BoilerAction.NoChange },
{ false, true, false, true, BoilerAction.NoChange },
{ false, true, true, false, BoilerAction.NoChange },
{ false, true, true, true, BoilerAction.NoChange },
{ true, false, false, false, BoilerAction.TurnOn },
{ true, false, false, true, BoilerAction.TurnOn },
{ true, false, true, false, BoilerAction.NoChange },
{ true, false, true, true, BoilerAction.TurnOn },
{ true, true, false, false, BoilerAction.NoChange },
{ true, true, false, true, BoilerAction.NoChange },
{ true, true, true, false, BoilerAction.NoChange },
{ true, true, true, true, BoilerAction.NoChange }
};
[Theory]
[MemberData(nameof(SwitchOffActionMatrix))]
public void DetermineAction_AllCombinationsWhileSwitchIsOff_ShouldReturnExpectedAction(
bool isNowCheap,
bool waterReady,
bool budgetExhausted,
bool budgetOverride,
BoilerAction expectedAction)
{
var result = CreateSut()
.DetermineAction(
isNowCheap, waterReady, "off", budgetExhausted, budgetOverride);
result.Should().Be(expectedAction);
}
#endregion
}
}
@@ -1,35 +1,38 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="8.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.TimeProvider.Testing" Version="10.4.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.3.0" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="FluentAssertions" Version="8.8.0" />
<PackageReference Include="Moq" Version="4.20.72" />
</ItemGroup>
<ItemGroup>
<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>
<Using Include="Xunit"/>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BoilerMonitor.Manager\BoilerMonitor.Manager.csproj" />
<ProjectReference Include="..\BoilerMonitor.Models\BoilerMonitor.Models.csproj" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BoilerMonitor.Manager\BoilerMonitor.Manager.csproj"/>
<ProjectReference Include="..\BoilerMonitor.Models\BoilerMonitor.Models.csproj"/>
</ItemGroup>
</Project>
@@ -1,133 +1,74 @@
#region
using FluentAssertions;
using BoilerMonitorManager.Models;
#endregion
namespace BoilerMonitor.Manager.Tests;
public class BoilerMonitorConfigTests
{
[Fact]
public void IsFullyConfigured_WhenAllFieldsSet_ShouldReturnTrue()
{
var config = new BoilerMonitorConfig
{
BoilerPowerEntityId = "sensor.sonoff_1002230e32_power",
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
PollIntervalSeconds = 30,
HeatingPowerThresholdWatts = 5.0
};
private const string PowerEntityId = BoilerMonitorTestData.PowerEntityId;
private const string SwitchEntityId = BoilerMonitorTestData.SwitchEntityId;
config.IsFullyConfigured.Should().BeTrue();
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_WhenPowerEntityMissing_ShouldReturnFalse()
public void IsFullyConfigured_WhenFullyPopulated_ShouldNotDependOnEntityIdCasingOrPadding()
{
var config = new BoilerMonitorConfig
{
BoilerPowerEntityId = null,
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
PollIntervalSeconds = 30,
HeatingPowerThresholdWatts = 5.0
};
var config = BoilerMonitorTestData.CreateConfig(
" sensor.sonoff_1002230e32_power ",
"SWITCH.SONOFF_1002230E32");
config.IsFullyConfigured.Should().BeFalse();
config.IsFullyConfigured.Should().BeTrue("entity ids are only checked for non-whitespace content");
}
[Fact]
public void IsFullyConfigured_WhenSwitchEntityMissing_ShouldReturnFalse()
{
var config = new BoilerMonitorConfig
{
BoilerPowerEntityId = "sensor.sonoff_1002230e32_power",
BoilerSwitchEntityId = null,
PollIntervalSeconds = 30,
HeatingPowerThresholdWatts = 5.0
};
config.IsFullyConfigured.Should().BeFalse();
}
[Fact]
public void IsFullyConfigured_WhenPollIntervalMissing_ShouldReturnFalse()
{
var config = new BoilerMonitorConfig
{
BoilerPowerEntityId = "sensor.sonoff_1002230e32_power",
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
PollIntervalSeconds = null,
HeatingPowerThresholdWatts = 5.0
};
config.IsFullyConfigured.Should().BeFalse();
}
[Fact]
public void IsFullyConfigured_WhenThresholdMissing_ShouldReturnFalse()
{
var config = new BoilerMonitorConfig
{
BoilerPowerEntityId = "sensor.sonoff_1002230e32_power",
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
PollIntervalSeconds = 30,
HeatingPowerThresholdWatts = null
};
config.IsFullyConfigured.Should().BeFalse();
}
[Fact]
public void IsFullyConfigured_WhenPowerEntityIsWhitespace_ShouldReturnFalse()
{
var config = new BoilerMonitorConfig
{
BoilerPowerEntityId = " ",
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
PollIntervalSeconds = 30,
HeatingPowerThresholdWatts = 5.0
};
config.IsFullyConfigured.Should().BeFalse();
}
[Fact]
public void IsFullyConfigured_WhenPollIntervalIsZero_ShouldReturnFalse()
{
var config = new BoilerMonitorConfig
{
BoilerPowerEntityId = "sensor.sonoff_1002230e32_power",
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
PollIntervalSeconds = 0,
HeatingPowerThresholdWatts = 5.0
};
config.IsFullyConfigured.Should().BeFalse();
}
[Fact]
public void IsFullyConfigured_WhenThresholdIsZero_ShouldReturnFalse()
{
var config = new BoilerMonitorConfig
{
BoilerPowerEntityId = "sensor.sonoff_1002230e32_power",
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
PollIntervalSeconds = 30,
HeatingPowerThresholdWatts = 0.0
};
config.IsFullyConfigured.Should().BeFalse();
}
[Fact]
public void IsFullyConfigured_WhenPollIntervalIsNegative_ShouldReturnFalse()
{
var config = new BoilerMonitorConfig
{
BoilerPowerEntityId = "sensor.sonoff_1002230e32_power",
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
PollIntervalSeconds = -1,
HeatingPowerThresholdWatts = 5.0
};
config.IsFullyConfigured.Should().BeFalse();
}
}
}
@@ -1,285 +1,466 @@
using BoilerMonitor.Models;
#region
using System.Text.Json;
using BoilerMonitorManager;
using BoilerMonitorManager.Models;
using FluentAssertions;
using HomeAssistant.Entities.Interfaces;
using HomeAssistant.Models;
using Microsoft.Extensions.Logging;
using Moq;
using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
using static BoilerMonitor.Models.BoilerMonitorConsts;
#endregion
namespace BoilerMonitor.Manager.Tests;
public class BoilerMonitorEntityServiceTests
{
private readonly Mock<IEntityManager> _entityManagerMock;
private readonly Mock<IHaContext> _haContextMock;
private readonly Mock<ILogger<BoilerMonitorEntityService>> _loggerMock;
private readonly BoilerMonitorEntityService _sut;
/// <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 = new Mock<IEntityManager>();
_haContextMock = new Mock<IHaContext>();
_loggerMock = new Mock<ILogger<BoilerMonitorEntityService>>();
_sut = new BoilerMonitorEntityService(
_entityManagerMock.Object,
_haContextMock.Object,
_loggerMock.Object);
_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 void SetupEntityState(string entityId, string? state)
private BoilerMonitorEntityService CreateSut()
{
if (state is null)
{
_haContextMock.Setup(h => h.GetState(entityId)).Returns((EntityState?)null);
}
else
{
_haContextMock.Setup(h => h.GetState(entityId))
.Returns(new EntityState { State = state });
}
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()
{
// Arrange
SetupEntityState(TodayRuntimeEntityId, "7200");
SetupEntityState(SessionCountEntityId, "3");
SetupEntityState(SkipPriceCapEntityId, "ON");
SetupEntityState(BudgetOverrideEntityId, "OFF");
_haContextMock.SetupEntityStates(BoilerMonitorTestData.CreatePersistedEntityStates(
"7200", "3", "ON"));
// Act
var result = _sut.ReadPersistedState();
var result = CreateSut().ReadPersistedState();
// Assert
result.Should().NotBeNull();
result!.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(7200));
result.AccumulatedRunTime.Should().Be(TimeSpan.FromHours(2));
result.SessionCount.Should().Be(3);
result.SkipPriceCapState.Should().Be("ON");
result.BudgetOverrideState.Should().Be("OFF");
}
[Fact]
public void ReadPersistedState_WithZeroRuntime_ShouldReturnZeroValues()
[Theory]
[InlineData("ON")]
[InlineData("on")]
[InlineData(" On ")]
[InlineData("")]
[InlineData(null)]
public void ReadPersistedState_ShouldReturnRawSwitchStates(string? switchState)
{
// Arrange
SetupEntityState(TodayRuntimeEntityId, "0");
SetupEntityState(SessionCountEntityId, "0");
SetupEntityState(SkipPriceCapEntityId, "OFF");
SetupEntityState(BudgetOverrideEntityId, "OFF");
_haContextMock.SetupEntityStates(BoilerMonitorTestData.CreatePersistedEntityStates(
skipPriceCap: switchState, budgetOverride: switchState));
// Act
var result = _sut.ReadPersistedState();
var result = CreateSut().ReadPersistedState();
// Assert
result.Should().NotBeNull();
result!.AccumulatedRunTime.Should().Be(TimeSpan.Zero);
result.SessionCount.Should().Be(0);
result.SkipPriceCapState.Should().Be(switchState);
result.BudgetOverrideState.Should().Be(switchState);
}
[Fact]
public void ReadPersistedState_WhenRuntimeIsUnavailable_ShouldReturnNull()
public void ReadPersistedState_WhenBothRuntimeEntitiesDoNotExist_ShouldReturnNull()
{
// Arrange
SetupEntityState(TodayRuntimeEntityId, "unavailable");
SetupEntityState(SessionCountEntityId, "3");
SetupEntityState(SkipPriceCapEntityId, "OFF");
SetupEntityState(BudgetOverrideEntityId, "OFF");
_haContextMock.SetupEntityStates(
BoilerMonitorTestData.CreatePersistedEntityStates(null, null));
// Act
var result = _sut.ReadPersistedState();
CreateSut().ReadPersistedState().Should().BeNull();
}
// Assert
result.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 ReadPersistedState_WhenRuntimeIsUnknown_ShouldReturnNull()
public void ReadPersistedCooldownTimestamp_WithUtcDesignator_ShouldReturnTimestamp()
{
// Arrange
SetupEntityState(TodayRuntimeEntityId, "unknown");
SetupEntityState(SessionCountEntityId, "2");
SetupEntityState(SkipPriceCapEntityId, "OFF");
SetupEntityState(BudgetOverrideEntityId, "OFF");
var cooldownSince = new DateTimeOffset(2026, 3, 31, 9, 15, 0, TimeSpan.Zero);
// Act
var result = _sut.ReadPersistedState();
_haContextMock.SetupEntityState(
WaterReadyEntityId,
BoilerMonitorTestData.CreateWaterReadyEntityStateWithCooldown("2026-03-31T09:15:00Z"));
// Assert
result.Should().BeNull();
var result = CreateSut().ReadPersistedCooldownTimestamp();
result.Should().Be(cooldownSince);
}
[Fact]
public void ReadPersistedState_WhenSessionCountIsUnavailable_ShouldReturnNull()
public void ReadPersistedCooldownTimestamp_WhenEntityDoesNotExist_ShouldReturnNull()
{
// Arrange
SetupEntityState(TodayRuntimeEntityId, "3600");
SetupEntityState(SessionCountEntityId, "unavailable");
SetupEntityState(SkipPriceCapEntityId, "OFF");
SetupEntityState(BudgetOverrideEntityId, "OFF");
_haContextMock.SetupEntityState(WaterReadyEntityId, null);
// Act
var result = _sut.ReadPersistedState();
// Assert
result.Should().BeNull();
CreateSut().ReadPersistedCooldownTimestamp().Should().BeNull();
}
[Fact]
public void ReadPersistedState_WhenRuntimeEntityDoesNotExist_ShouldReturnNull()
public void ReadPersistedCooldownTimestamp_WhenEntityHasNoAttributes_ShouldReturnNull()
{
// Arrange
SetupEntityState(TodayRuntimeEntityId, null);
SetupEntityState(SessionCountEntityId, "2");
SetupEntityState(SkipPriceCapEntityId, "OFF");
SetupEntityState(BudgetOverrideEntityId, "OFF");
_haContextMock.SetupEntityState(WaterReadyEntityId, BoilerMonitorTestData.CreateEntityState("yes"));
// Act
var result = _sut.ReadPersistedState();
// Assert
result.Should().BeNull();
CreateSut().ReadPersistedCooldownTimestamp().Should().BeNull();
}
[Fact]
public void ReadPersistedState_WhenSessionCountEntityDoesNotExist_ShouldReturnNull()
public void ReadPersistedCooldownTimestamp_WhenAttributeIsMissing_ShouldReturnNull()
{
// Arrange
SetupEntityState(TodayRuntimeEntityId, "3600");
SetupEntityState(SessionCountEntityId, null);
SetupEntityState(SkipPriceCapEntityId, "OFF");
SetupEntityState(BudgetOverrideEntityId, "OFF");
_haContextMock.SetupEntityState(
WaterReadyEntityId,
BoilerMonitorTestData.CreateEntityStateWithAttributes(
new Dictionary<string, object?> { ["friendly_name"] = "Boiler water ready" }));
// Act
var result = _sut.ReadPersistedState();
// Assert
result.Should().BeNull();
}
[Fact]
public void ReadPersistedState_WhenRuntimeIsNonNumeric_ShouldReturnNull()
{
// Arrange
SetupEntityState(TodayRuntimeEntityId, "not_a_number");
SetupEntityState(SessionCountEntityId, "2");
SetupEntityState(SkipPriceCapEntityId, "OFF");
SetupEntityState(BudgetOverrideEntityId, "OFF");
// Act
var result = _sut.ReadPersistedState();
// Assert
result.Should().BeNull();
}
[Fact]
public void ReadPersistedState_WhenSessionCountIsNonNumeric_ShouldReturnNull()
{
// Arrange
SetupEntityState(TodayRuntimeEntityId, "3600");
SetupEntityState(SessionCountEntityId, "abc");
SetupEntityState(SkipPriceCapEntityId, "OFF");
SetupEntityState(BudgetOverrideEntityId, "OFF");
// Act
var result = _sut.ReadPersistedState();
// Assert
result.Should().BeNull();
}
[Fact]
public void ReadPersistedState_WhenRuntimeIsNegative_ShouldReturnNull()
{
// Arrange
SetupEntityState(TodayRuntimeEntityId, "-100");
SetupEntityState(SessionCountEntityId, "2");
SetupEntityState(SkipPriceCapEntityId, "OFF");
SetupEntityState(BudgetOverrideEntityId, "OFF");
// Act
var result = _sut.ReadPersistedState();
// Assert
result.Should().BeNull();
}
[Fact]
public void ReadPersistedState_WhenSessionCountIsNegative_ShouldReturnNull()
{
// Arrange
SetupEntityState(TodayRuntimeEntityId, "3600");
SetupEntityState(SessionCountEntityId, "-1");
SetupEntityState(SkipPriceCapEntityId, "OFF");
SetupEntityState(BudgetOverrideEntityId, "OFF");
// Act
var result = _sut.ReadPersistedState();
// Assert
result.Should().BeNull();
}
[Fact]
public void ReadPersistedState_WhenSwitchEntitiesAreNull_ShouldStillReturnWithNullSwitchStates()
{
// Arrange
SetupEntityState(TodayRuntimeEntityId, "1800");
SetupEntityState(SessionCountEntityId, "1");
SetupEntityState(SkipPriceCapEntityId, null);
SetupEntityState(BudgetOverrideEntityId, null);
// Act
var result = _sut.ReadPersistedState();
// Assert
result.Should().NotBeNull();
result!.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(1800));
result.SessionCount.Should().Be(1);
result.SkipPriceCapState.Should().BeNull();
result.BudgetOverrideState.Should().BeNull();
CreateSut().ReadPersistedCooldownTimestamp().Should().BeNull();
}
[Theory]
[InlineData("")] // empty string
[InlineData(" ")] // whitespace
public void ReadPersistedState_WhenRuntimeIsEmptyOrWhitespace_ShouldReturnNull(string state)
[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)
{
// Arrange
SetupEntityState(TodayRuntimeEntityId, state);
SetupEntityState(SessionCountEntityId, "2");
SetupEntityState(SkipPriceCapEntityId, "OFF");
SetupEntityState(BudgetOverrideEntityId, "OFF");
_haContextMock.SetupEntityState(
WaterReadyEntityId,
BoilerMonitorTestData.CreateWaterReadyEntityStateWithCooldown(cooldownSince));
// Act
var result = _sut.ReadPersistedState();
// Assert
result.Should().BeNull();
CreateSut().ReadPersistedCooldownTimestamp().Should().BeNull();
}
[Fact]
public void ReadPersistedState_WithDecimalRuntime_ShouldParseCorrectly()
public void ReadPersistedCooldownTimestamp_WhenHaContextThrows_ShouldReturnNull()
{
// Arrange
SetupEntityState(TodayRuntimeEntityId, "134.66");
SetupEntityState(SessionCountEntityId, "1");
SetupEntityState(SkipPriceCapEntityId, "OFF");
SetupEntityState(BudgetOverrideEntityId, "OFF");
_haContextMock.Setup(h => h.GetState(WaterReadyEntityId))
.Throws(new InvalidOperationException("Home Assistant unavailable"));
// Act
var result = _sut.ReadPersistedState();
CreateSut().ReadPersistedCooldownTimestamp().Should().BeNull();
}
// Assert
result.Should().NotBeNull();
result!.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(134.66));
result.SessionCount.Should().Be(1);
#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
@@ -289,56 +470,113 @@ public class BoilerMonitorEntityServiceTests
[Fact]
public async Task ResetTransientEntitiesAsync_ShouldResetStatusAndWaterReady()
{
// Arrange
_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);
await CreateSut().ResetTransientEntitiesAsync();
// Act
await _sut.ResetTransientEntitiesAsync();
// Assert
_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);
}
[Fact]
public async Task ResetTransientEntitiesAsync_ShouldNotResetRuntimeEntities()
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)
{
// Arrange
_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);
await CreateSut().ResetTransientEntitiesAsync();
// Act
await _sut.ResetTransientEntitiesAsync();
// Assert
_entityManagerMock.Verify(em => em.SetEntityState(TodayRuntimeEntityId, It.IsAny<string>()), Times.Never);
_entityManagerMock.Verify(em => em.SetEntityState(SessionCountEntityId, It.IsAny<string>()), Times.Never);
_entityManagerMock.Verify(em => em.SetEntityState(BudgetPercentageEntityId, It.IsAny<string>()), Times.Never);
_entityManagerMock.Verify(em => em.SetEntityState(BudgetExhaustedEntityId, It.IsAny<string>()), Times.Never);
_entityManagerMock.Verify(em => em.SetEntityState(RemainingTimeEntityId, It.IsAny<string>()), Times.Never);
}
[Fact]
public async Task ResetTransientEntitiesAsync_ShouldNotResetSwitchEntities()
{
// Arrange
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask);
// Act
await _sut.ResetTransientEntitiesAsync();
// Assert
_entityManagerMock.Verify(em => em.SetEntityState(SkipPriceCapEntityId, It.IsAny<string>()), Times.Never);
_entityManagerMock.Verify(em => em.SetEntityState(BudgetOverrideEntityId, It.IsAny<string>()), Times.Never);
_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
}
@@ -1,5 +1,9 @@
using FluentAssertions;
#region
using BoilerMonitorManager.Models;
using FluentAssertions;
#endregion
namespace BoilerMonitor.Manager.Tests;
@@ -13,17 +17,47 @@ public class BoilerMonitorOptionsTests
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");
}
[Fact]
public void Enabled_WhenSetToFalse_ShouldReturnFalse()
[Theory]
[InlineData(false)]
[InlineData(true)]
public void Enabled_WhenSet_ShouldReturnConfiguredValue(bool enabled)
{
var options = new BoilerMonitorOptions { Enabled = false };
var options = BoilerMonitorTestData.CreateOptions(enabled);
options.Enabled.Should().Be(enabled);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void CleanupEntitiesOnStartup_WhenSet_ShouldReturnConfiguredValue(bool cleanupEntitiesOnStartup)
{
var options = BoilerMonitorTestData.CreateOptions(cleanupEntitiesOnStartup: cleanupEntitiesOnStartup);
options.CleanupEntitiesOnStartup.Should().Be(cleanupEntitiesOnStartup);
}
[Fact]
public void Options_WhenBothFlagsDisabled_ShouldPreserveEachValueIndependently()
{
var options = BoilerMonitorTestData.CreateOptions(false, false);
options.Enabled.Should().BeFalse();
options.CleanupEntitiesOnStartup.Should().BeFalse();
BoilerMonitorOptions.SectionName.Should().Be("BoilerMonitor");
}
}
}
@@ -0,0 +1,293 @@
#region
using System.Text.Json;
using BoilerMonitorManager.Models;
using Microsoft.Extensions.Time.Testing;
using Moq;
using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
using static BoilerMonitor.Models.BoilerMonitorConsts;
#endregion
namespace BoilerMonitor.Manager.Tests;
/// <summary>
/// Shared, deterministic fixtures used by the BoilerMonitor tests: config/options builders,
/// entity-state sets, parse samples and a fixed clock. Keeping them here avoids copy-pasted
/// setup and makes every timestamp/DST assertion independent of the real clock.
/// </summary>
internal static class BoilerMonitorTestData
{
public const string PowerEntityId = "sensor.sonoff_1002230e32_power";
public const string SwitchEntityId = "switch.sonoff_1002230e32";
/// <summary>Fixed "now" (UTC) used by every time based test.</summary>
public static readonly DateTimeOffset BaseTime = new DateTimeOffset(2026, 3, 31, 12, 0, 0, TimeSpan.Zero);
public static FakeTimeProvider CreateTimeProvider(DateTimeOffset? utcNow = null)
{
return new FakeTimeProvider(utcNow ?? BaseTime);
}
public static BoilerMonitorConfig CreateConfig(
string? boilerPowerEntityId = PowerEntityId,
string? boilerSwitchEntityId = SwitchEntityId,
int? pollIntervalSeconds = DefaultPollIntervalSeconds,
double? heatingPowerThresholdWatts = DefaultHeatingPowerThresholdWatts)
{
return new BoilerMonitorConfig
{
BoilerPowerEntityId = boilerPowerEntityId,
BoilerSwitchEntityId = boilerSwitchEntityId,
PollIntervalSeconds = pollIntervalSeconds,
HeatingPowerThresholdWatts = heatingPowerThresholdWatts
};
}
public static BoilerMonitorOptions CreateOptions(
bool enabled = true,
bool cleanupEntitiesOnStartup = true)
{
return new BoilerMonitorOptions
{
Enabled = enabled,
CleanupEntitiesOnStartup = cleanupEntitiesOnStartup
};
}
public static BoilerMonitorUpdateContext CreateUpdateContext(
TimeSpan? todayRunTime = null,
TimeSpan? remainingTime = null,
double budgetPercentage = 50.0,
bool budgetExhausted = false,
int sessionCount = 1,
double budgetHours = 2.0,
bool waterReady = false,
string? boilerSwitchState = "on",
double? boilerPowerWatts = 0.0,
DateTimeOffset? cooldownSince = null)
{
return new BoilerMonitorUpdateContext
{
TodayRunTime = todayRunTime ?? TimeSpan.FromHours(1),
RemainingTime = remainingTime ?? TimeSpan.FromHours(1),
BudgetPercentage = budgetPercentage,
BudgetExhausted = budgetExhausted,
SessionCount = sessionCount,
BudgetHours = budgetHours,
WaterReady = waterReady,
BoilerSwitchState = boilerSwitchState,
BoilerPowerWatts = boilerPowerWatts,
CooldownSince = cooldownSince
};
}
/// <summary>
/// The four entity states <c>ReadPersistedState</c> reads, with valid defaults.
/// A null value means the entity does not exist in Home Assistant.
/// </summary>
public static Dictionary<string, string?> CreatePersistedEntityStates(
string? todayRuntime = "7200",
string? sessionCount = "3",
string? skipPriceCap = "OFF",
string? budgetOverride = "OFF")
{
return new Dictionary<string, string?>
{
[TodayRuntimeEntityId] = todayRuntime,
[SessionCountEntityId] = sessionCount,
[SkipPriceCapEntityId] = skipPriceCap,
[BudgetOverrideEntityId] = budgetOverride
};
}
public static EntityState CreateEntityState(string state)
{
return new EntityState { State = state };
}
public static EntityState CreateEntityStateWithAttributes(IReadOnlyDictionary<string, object?> attributes)
{
return new EntityState { State = "yes", AttributesJson = JsonSerializer.SerializeToElement(attributes) };
}
public static EntityState CreateWaterReadyEntityStateWithCooldown(object? cooldownSince)
{
return CreateEntityStateWithAttributes(new Dictionary<string, object?> { ["cooldown_since"] = cooldownSince });
}
extension(Mock<IHaContext> haContextMock)
{
public void SetupEntityStates(IReadOnlyDictionary<string, string?> states)
{
foreach (var (entityId, state) in states)
{
var entityState = state is null ? null : CreateEntityState(state);
haContextMock.Setup(h => h.GetState(entityId)).Returns(entityState);
}
}
public void SetupEntityState(string entityId, EntityState? entityState)
{
haContextMock.Setup(h => h.GetState(entityId)).Returns(entityState);
}
}
/// <summary>
/// Entity-state samples for the today-runtime sensor: valid values with the expected
/// <see cref="TimeSpan" />, plus unavailable/negative/overflow values that must be rejected.
/// </summary>
public static TheoryData<string?, TimeSpan?> RuntimeStateSamples()
{
var data = new TheoryData<string?, TimeSpan?>();
data.Add("7200", TimeSpan.FromHours(2));
data.Add("0", TimeSpan.Zero);
data.Add("134.66", TimeSpan.FromSeconds(134.66));
data.Add("1E3", TimeSpan.FromSeconds(1000));
data.Add("0.001", TimeSpan.FromSeconds(0.001));
data.Add(" 60 ", TimeSpan.FromSeconds(60));
data.Add("86400", TimeSpan.FromDays(1));
data.Add("1e9", TimeSpan.FromSeconds(1e9));
data.Add(null, null);
data.Add(string.Empty, null);
data.Add(" ", null);
data.Add("\t", null);
data.Add("unavailable", null);
data.Add("unknown", null);
data.Add("Unavailable", null);
data.Add("not_a_number", null);
data.Add("NaN", null);
data.Add("Infinity", null);
data.Add("1e308", null);
data.Add("-1", null);
data.Add("-0.001", null);
return data;
}
/// <summary>
/// Entity-state samples for the session-count sensor, including the int boundaries.
/// </summary>
public static TheoryData<string?, int?> SessionCountStateSamples()
{
var data = new TheoryData<string?, int?>();
data.Add("0", 0);
data.Add("3", 3);
data.Add(" 2 ", 2);
data.Add("+4", 4);
data.Add("2147483647", int.MaxValue);
data.Add(null, null);
data.Add(string.Empty, null);
data.Add(" ", null);
data.Add("\t", null);
data.Add("unavailable", null);
data.Add("unknown", null);
data.Add("abc", null);
data.Add("1.5", null);
data.Add("-1", null);
data.Add("2147483648", null);
data.Add("1e3", null);
return data;
}
/// <summary>
/// Water-ready detection samples around the heating threshold, including negative,
/// zero, exact-boundary, huge and NaN readings.
/// </summary>
public static TheoryData<string, double, bool> PowerReadingSamples()
{
var data = new TheoryData<string, double, bool>();
data.Add("negative sensor glitch", -1_000.0, true);
data.Add("just below zero", -0.001, true);
data.Add("zero", 0.0, true);
data.Add("just below threshold", 4.999, true);
data.Add("exactly at threshold", 5.0, false);
data.Add("just above threshold", 5.001, false);
data.Add("actively heating", 2_150.0, false);
data.Add("maximum", double.MaxValue, false);
data.Add("not-a-number", double.NaN, true);
return data;
}
/// <summary>
/// Elapsed-time sweep showing that the water-ready cooldown never expires on its own.
/// </summary>
public static TheoryData<TimeSpan> GeneratedElapsedTimes()
{
var data = new TheoryData<TimeSpan>();
data.Add(TimeSpan.FromHours(1));
data.Add(TimeSpan.FromHours(2));
data.Add(TimeSpan.FromHours(6));
data.Add(TimeSpan.FromHours(12));
data.Add(TimeSpan.FromHours(23));
data.Add(TimeSpan.FromHours(24));
data.Add(TimeSpan.FromHours(25));
data.Add(TimeSpan.FromHours(48));
data.Add(TimeSpan.FromHours(168));
return data;
}
/// <summary>
/// Cooldown restore samples around the UTC-midnight cut-off, including DST start/end
/// timestamps carrying non-zero offsets.
/// </summary>
public static TheoryData<string, DateTimeOffset, DateTimeOffset, bool> CooldownRestoreSamples()
{
var data = new TheoryData<string, DateTimeOffset, DateTimeOffset, bool>();
data.Add("30 minutes ago", BaseTime, BaseTime - TimeSpan.FromMinutes(30), true);
data.Add("5 hours ago", BaseTime, BaseTime - TimeSpan.FromHours(5), true);
data.Add("exactly at today's UTC midnight", BaseTime, TodayMidnight(), true);
data.Add("one tick after today's UTC midnight", BaseTime, TodayMidnight().AddTicks(1), true);
data.Add("one tick before today's UTC midnight", BaseTime, TodayMidnight().AddTicks(-1), false);
data.Add("one second before today's UTC midnight", BaseTime, TodayMidnight().AddSeconds(-1), false);
data.Add("yesterday same time", BaseTime, BaseTime.AddDays(-1), false);
data.Add("two days ago", BaseTime, BaseTime.AddDays(-2), false);
data.Add("future timestamp", BaseTime, BaseTime.AddHours(1), true);
data.Add("maximum timestamp", BaseTime, DateTimeOffset.MaxValue, true);
// Europe DST starts 2026-03-29 02:00 CET → 03:00 CEST.
// now = 03:30+02:00 = 01:30Z, so UTC midnight is 2026-03-29T00:00Z.
data.Add(
"DST spring-forward, same UTC day",
new DateTimeOffset(2026, 3, 29, 3, 30, 0, TimeSpan.FromHours(2)),
new DateTimeOffset(2026, 3, 29, 1, 30, 0, TimeSpan.FromHours(1)),
true
);
data.Add(
"DST spring-forward, previous UTC day",
new DateTimeOffset(2026, 3, 29, 3, 30, 0, TimeSpan.FromHours(2)),
new DateTimeOffset(2026, 3, 28, 23, 30, 0, TimeSpan.FromHours(1)),
false
);
// Europe DST ends 2026-10-25 03:00 CEST → 02:00 CET. The 02:30 wall-clock hour occurs twice.
// now = 03:30+01:00 = 02:30Z, timestamp 02:30+02:00 = 00:30Z is still "today" in UTC.
data.Add(
"DST fall-back, ambiguous local hour",
new DateTimeOffset(2026, 10, 25, 3, 30, 0, TimeSpan.FromHours(1)),
new DateTimeOffset(2026, 10, 25, 2, 30, 0, TimeSpan.FromHours(2)),
true
);
data.Add(
"crossing midnight between restore and now",
new DateTimeOffset(2026, 4, 1, 0, 0, 1, TimeSpan.Zero),
new DateTimeOffset(2026, 3, 31, 23, 59, 59, TimeSpan.Zero),
false
);
return data;
}
private static DateTimeOffset TodayMidnight()
{
return new DateTimeOffset(BaseTime.Date, TimeSpan.Zero);
}
}
@@ -1,254 +0,0 @@
using FluentAssertions;
using BoilerMonitorManager;
namespace BoilerMonitor.Manager.Tests;
public class BoilerRunTimeTrackerTests
{
private readonly BoilerRunTimeTracker _sut = new();
#region RecordPollResult
[Fact]
public void RecordPollResult_WhenHeating_ShouldAccumulateRunTime()
{
var interval = TimeSpan.FromSeconds(30);
_sut.RecordPollResult(true, interval);
_sut.RecordPollResult(true, interval);
_sut.RecordPollResult(true, interval);
var snapshot = _sut.GetSnapshot();
snapshot.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(90));
}
[Fact]
public void RecordPollResult_WhenNotHeating_ShouldNotAccumulate()
{
var interval = TimeSpan.FromSeconds(30);
_sut.RecordPollResult(false, interval);
_sut.RecordPollResult(false, interval);
var snapshot = _sut.GetSnapshot();
snapshot.AccumulatedRunTime.Should().Be(TimeSpan.Zero);
}
[Fact]
public void RecordPollResult_WhenHeatingStarts_ShouldIncrementSessionCount()
{
var interval = TimeSpan.FromSeconds(30);
_sut.RecordPollResult(true, interval);
var snapshot = _sut.GetSnapshot();
snapshot.SessionCount.Should().Be(1);
}
[Fact]
public void RecordPollResult_ContinuousHeating_ShouldCountAsOneSession()
{
var interval = TimeSpan.FromSeconds(30);
_sut.RecordPollResult(true, interval);
_sut.RecordPollResult(true, interval);
_sut.RecordPollResult(true, interval);
var snapshot = _sut.GetSnapshot();
snapshot.SessionCount.Should().Be(1);
}
[Fact]
public void RecordPollResult_HeatingStopsAndRestarts_ShouldCountAsTwoSessions()
{
var interval = TimeSpan.FromSeconds(30);
_sut.RecordPollResult(true, interval);
_sut.RecordPollResult(false, interval);
_sut.RecordPollResult(true, interval);
var snapshot = _sut.GetSnapshot();
snapshot.SessionCount.Should().Be(2);
}
[Fact]
public void RecordPollResult_MultipleSessions_ShouldAccumulateCorrectly()
{
var interval = TimeSpan.FromSeconds(30);
_sut.RecordPollResult(true, interval);
_sut.RecordPollResult(true, interval);
_sut.RecordPollResult(false, interval);
_sut.RecordPollResult(true, interval);
var snapshot = _sut.GetSnapshot();
snapshot.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(90));
snapshot.SessionCount.Should().Be(2);
}
[Fact]
public void RecordPollResult_WhenHeating_ShouldSetIsInSessionTrue()
{
_sut.RecordPollResult(true, TimeSpan.FromSeconds(30));
var snapshot = _sut.GetSnapshot();
snapshot.IsInSession.Should().BeTrue();
}
[Fact]
public void RecordPollResult_WhenNotHeating_ShouldSetIsInSessionFalse()
{
_sut.RecordPollResult(true, TimeSpan.FromSeconds(30));
_sut.RecordPollResult(false, TimeSpan.FromSeconds(30));
var snapshot = _sut.GetSnapshot();
snapshot.IsInSession.Should().BeFalse();
}
#endregion
#region Reset
[Fact]
public void Reset_ShouldClearAllState()
{
var interval = TimeSpan.FromSeconds(30);
_sut.RecordPollResult(true, interval);
_sut.RecordPollResult(true, interval);
_sut.Reset();
var snapshot = _sut.GetSnapshot();
snapshot.AccumulatedRunTime.Should().Be(TimeSpan.Zero);
snapshot.SessionCount.Should().Be(0);
snapshot.IsInSession.Should().BeFalse();
}
[Fact]
public void Reset_AfterReset_ShouldAccumulateFromZero()
{
var interval = TimeSpan.FromSeconds(30);
_sut.RecordPollResult(true, interval);
_sut.Reset();
_sut.RecordPollResult(true, interval);
var snapshot = _sut.GetSnapshot();
snapshot.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(30));
snapshot.SessionCount.Should().Be(1);
}
#endregion
#region RestoreFromSnapshot
[Fact]
public void RestoreFromSnapshot_ShouldSetAccumulatedRunTimeAndSessionCount()
{
// Arrange
var runTime = TimeSpan.FromMinutes(45);
const int sessionCount = 3;
// Act
_sut.RestoreFromSnapshot(runTime, sessionCount);
// Assert
var snapshot = _sut.GetSnapshot();
snapshot.AccumulatedRunTime.Should().Be(runTime);
snapshot.SessionCount.Should().Be(sessionCount);
snapshot.IsInSession.Should().BeFalse();
}
[Fact]
public void RestoreFromSnapshot_ShouldOverwriteExistingState()
{
// Arrange
_sut.RecordPollResult(true, TimeSpan.FromSeconds(30));
_sut.RecordPollResult(true, TimeSpan.FromSeconds(30));
var restoredRunTime = TimeSpan.FromHours(2);
const int restoredSessions = 5;
// Act
_sut.RestoreFromSnapshot(restoredRunTime, restoredSessions);
// Assert
var snapshot = _sut.GetSnapshot();
snapshot.AccumulatedRunTime.Should().Be(restoredRunTime);
snapshot.SessionCount.Should().Be(restoredSessions);
}
[Fact]
public void RestoreFromSnapshot_ShouldAllowFurtherAccumulationFromRestoredState()
{
// Arrange
var restoredRunTime = TimeSpan.FromMinutes(30);
const int restoredSessions = 2;
var pollInterval = TimeSpan.FromSeconds(30);
_sut.RestoreFromSnapshot(restoredRunTime, restoredSessions);
// Act
_sut.RecordPollResult(true, pollInterval);
// Assert
var snapshot = _sut.GetSnapshot();
snapshot.AccumulatedRunTime.Should().Be(restoredRunTime + pollInterval);
snapshot.SessionCount.Should().Be(restoredSessions + 1);
}
[Fact]
public void RestoreFromSnapshot_WithZeroValues_ShouldSetToZero()
{
// Arrange
_sut.RecordPollResult(true, TimeSpan.FromSeconds(30));
// Act
_sut.RestoreFromSnapshot(TimeSpan.Zero, 0);
// Assert
var snapshot = _sut.GetSnapshot();
snapshot.AccumulatedRunTime.Should().Be(TimeSpan.Zero);
snapshot.SessionCount.Should().Be(0);
}
#endregion
#region Thread safety
[Fact]
public async Task RecordPollResult_ConcurrentCalls_ShouldNotCorruptState()
{
var interval = TimeSpan.FromSeconds(1);
const int iterationsPerThread = 1000;
const int threadCount = 4;
var tasks = Enumerable.Range(0, threadCount).Select(_ => Task.Run(() =>
{
for (var i = 0; i < iterationsPerThread; i++)
{
_sut.RecordPollResult(true, interval);
}
})).ToArray();
await Task.WhenAll(tasks);
var snapshot = _sut.GetSnapshot();
snapshot.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(iterationsPerThread * threadCount));
}
#endregion
#region GetSnapshot
[Fact]
public void GetSnapshot_Initial_ShouldReturnZeroState()
{
var snapshot = _sut.GetSnapshot();
snapshot.AccumulatedRunTime.Should().Be(TimeSpan.Zero);
snapshot.SessionCount.Should().Be(0);
snapshot.IsInSession.Should().BeFalse();
}
#endregion
}
@@ -1,430 +1,495 @@
#region
using BoilerMonitor.Models;
using BoilerMonitorManager;
using FluentAssertions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Time.Testing;
using Moq;
using BoilerMonitorManager;
#endregion
namespace BoilerMonitor.Manager.Tests;
public class WaterReadyServiceTests
{
private readonly Mock<ILogger<WaterReadyService>> _loggerMock;
private readonly FakeTimeProvider _timeProvider;
private const double Threshold = BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts;
private const double HighPowerWatts = 2150.0;
private const int RequiredReadings = BoilerMonitorConsts.ConsecutiveReadingsRequired;
public WaterReadyServiceTests()
{
_loggerMock = new Mock<ILogger<WaterReadyService>>();
_timeProvider = new FakeTimeProvider(DateTimeOffset.UtcNow);
}
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);
}
#region IsWaterReady — basic behavior (no grace period active)
[Fact]
public void IsWaterReady_SwitchOnAndLowPower_ShouldReturnTrue()
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)
{
// Arrange
var sut = CreateSut();
// Act
var result = sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
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);
// Assert
result.Should().BeTrue();
}
[Fact]
public void IsWaterReady_SwitchOnAndPowerBelowThreshold_ShouldReturnTrue()
public void RecordHeatingObserved_ShouldEnableDetection()
{
// Arrange
var sut = CreateSut();
// Act
var result = sut.IsWaterReady("on", 4.9, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
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);
// Assert
result.Should().BeTrue();
}
[Fact]
public void IsWaterReady_SwitchOnAndPowerAtThreshold_ShouldReturnFalse()
public void ResetCooldown_ShouldKeepHeatingObservationEnabled()
{
// Arrange
var sut = CreateSut();
var sut = CreateSutWithHeatingObserved();
FeedReadings(sut, RequiredReadings).Should().BeTrue();
// Act
var result = sut.IsWaterReady("on", 5.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
sut.ResetCooldown();
// Assert
result.Should().BeFalse();
FeedReadings(sut, RequiredReadings)
.Should()
.BeTrue(
"ResetCooldown clears the cooldown and counter, not the heating observation");
}
[Fact]
public void IsWaterReady_SwitchOnAndHighPower_ShouldReturnFalse()
public void IsWaterReady_AfterResetAndReObservedHeating_ShouldTriggerAgain()
{
// Arrange
var sut = CreateSut();
var sut = CreateSutWithHeatingObserved();
FeedReadings(sut, RequiredReadings);
sut.ResetCooldown();
// Act
var result = sut.IsWaterReady("on", 2150.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
sut.RecordHeatingObserved();
var result = FeedReadings(sut, RequiredReadings);
// Assert
result.Should().BeFalse();
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_SwitchOff_ShouldReturnFalse()
public void IsWaterReady_InterleavedReadings_ShouldOnlyTriggerAfterLastConsecutiveLowReading()
{
// Arrange
var sut = CreateSut();
var sut = CreateSutWithHeatingObserved();
// Act
var result = sut.IsWaterReady("off", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
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);
// Assert
result.Should().BeFalse();
}
[Fact]
public void IsWaterReady_NullSwitchState_ShouldReturnFalse()
[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)
{
// Arrange
var sut = CreateSut();
var sut = CreateSutWithHeatingObserved();
// Act
var result = sut.IsWaterReady(null, 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
var result = FeedReadings(sut, 10, switchState, powerWatts);
// Assert
result.Should().BeFalse();
}
[Fact]
public void IsWaterReady_NullPowerWatts_ShouldReturnFalse()
{
// Arrange
var sut = CreateSut();
// Act
var result = sut.IsWaterReady("on", null, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
// Assert
result.Should().BeFalse();
}
[Fact]
public void IsWaterReady_BothNull_ShouldReturnFalse()
{
// Arrange
var sut = CreateSut();
// Act
var result = sut.IsWaterReady(null, null, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
// Assert
result.Should().BeFalse();
}
[Theory]
[InlineData("ON")]
[InlineData("On")]
[InlineData("on")]
[InlineData("oN")]
public void IsWaterReady_SwitchOnCaseInsensitive_ShouldReturnTrue(string switchState)
{
// Arrange
var sut = CreateSut();
var sut = CreateSutWithHeatingObserved();
// Act
var result = sut.IsWaterReady(switchState, 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
var result = FeedReadings(sut, RequiredReadings, switchState);
// Assert
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)]
public void IsWaterReady_CustomThreshold_ShouldUseProvidedValue(double powerWatts, double threshold, bool expected)
[InlineData(0.0, 0.0, false)]
[InlineData(-10.0, -5.0, true)]
[InlineData(-0.001, 0.0, true)]
[InlineData(0.0, -5.0, false)]
[InlineData(10.0, 0.0, false)]
public void IsWaterReady_CustomThreshold_ShouldUseProvidedValue(
double powerWatts,
double heatingThresholdWatts,
bool expected)
{
// Arrange — fresh instance per case to avoid cooldown side-effects
var sut = CreateSut();
var sut = CreateSutWithHeatingObserved();
// Act
var result = sut.IsWaterReady("on", powerWatts, threshold);
var result = FeedReadings(sut, RequiredReadings, powerWatts: powerWatts,
heatingThresholdWatts: heatingThresholdWatts);
// Assert
result.Should().Be(expected);
}
#endregion
#region Warm-up grace period
#region Cooldown period
[Fact]
public void IsWaterReady_DuringGracePeriod_ShouldReturnFalse()
[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)
{
// Arrange
var sut = CreateSut();
sut.NotifyTurnedOn();
var sut = CreateSutWithHeatingObserved();
FeedReadings(sut, RequiredReadings).Should().BeTrue();
// Act — still within grace period, low power should be suppressed
var result = sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
var result = sut.IsWaterReady(switchState, powerWatts, Threshold);
// Assert
result.Should().BeFalse();
}
[Fact]
public void IsWaterReady_AfterGracePeriodExpires_ShouldReturnTrue()
{
// Arrange
var sut = CreateSut();
sut.NotifyTurnedOn();
_timeProvider.Advance(BoilerMonitorConsts.WarmUpGracePeriod);
// Act — grace period has elapsed, low power means water is ready
var result = sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
// Assert
result.Should().BeTrue();
}
[Fact]
public void IsWaterReady_DuringGracePeriodWithHighPower_ShouldReturnFalse()
[Theory]
[MemberData(nameof(BoilerMonitorTestData.GeneratedElapsedTimes), MemberType = typeof(BoilerMonitorTestData))]
public void IsWaterReady_CooldownDoesNotExpireByTime_ShouldStayActive(TimeSpan elapsed)
{
// Arrange
var sut = CreateSut();
sut.NotifyTurnedOn();
var sut = CreateSutWithHeatingObserved();
FeedReadings(sut, RequiredReadings);
var triggeredAt = sut.WaterReadySince;
// Act — high power during grace period is still "not ready" (heating)
var result = sut.IsWaterReady("on", 2150.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
_timeProvider.Advance(elapsed);
// Assert
result.Should().BeFalse();
}
[Fact]
public void IsWaterReady_JustBeforeGracePeriodExpires_ShouldReturnFalse()
{
// Arrange
var sut = CreateSut();
sut.NotifyTurnedOn();
_timeProvider.Advance(BoilerMonitorConsts.WarmUpGracePeriod - TimeSpan.FromSeconds(1));
// Act
var result = sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
// Assert
result.Should().BeFalse();
}
[Fact]
public void IsWaterReady_WithoutNotifyTurnedOn_ShouldNotApplyGracePeriod()
{
// Arrange — no NotifyTurnedOn call, so no grace period should be active
var sut = CreateSut();
// Act
var result = sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
// Assert
result.Should().BeTrue();
}
[Fact]
public void IsWaterReady_MultipleTurnOns_ShouldResetGracePeriod()
{
// Arrange
var sut = CreateSut();
sut.NotifyTurnedOn();
_timeProvider.Advance(BoilerMonitorConsts.WarmUpGracePeriod - TimeSpan.FromSeconds(10));
// Act — second turn-on resets the grace period
sut.NotifyTurnedOn();
_timeProvider.Advance(TimeSpan.FromSeconds(10));
var result = sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
// Assert — still within the new grace period
result.Should().BeFalse();
}
[Fact]
public void IsWaterReady_SwitchOffDuringGracePeriod_ShouldReturnFalse()
{
// Arrange
var sut = CreateSut();
sut.NotifyTurnedOn();
// Act — switch is off, so not ready regardless of grace period
var result = sut.IsWaterReady("off", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
// Assert
result.Should().BeFalse();
}
#endregion
#region Water ready cooldown period
[Fact]
public void IsWaterReady_DuringCooldown_ShouldReturnTrueRegardlessOfSwitchState()
{
// Arrange — trigger water ready detection, then turn switch off
var sut = CreateSut();
sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
// Act — switch is now off, but cooldown should keep reporting ready
var result = sut.IsWaterReady("off", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
// Assert
result.Should().BeTrue();
}
[Fact]
public void IsWaterReady_DuringCooldown_ShouldReturnTrueEvenWithNullState()
{
// Arrange
var sut = CreateSut();
sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
// Act
var result = sut.IsWaterReady(null, null, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
// Assert
result.Should().BeTrue();
}
[Fact]
public void IsWaterReady_AfterCooldownExpires_ShouldResumeNormalDetection()
{
// Arrange
var sut = CreateSut();
sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
_timeProvider.Advance(BoilerMonitorConsts.WaterReadyCooldownPeriod);
// Act — cooldown expired, switch is off → not ready
var result = sut.IsWaterReady("off", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
// Assert
result.Should().BeFalse();
}
[Fact]
public void IsWaterReady_JustBeforeCooldownExpires_ShouldStillReturnTrue()
{
// Arrange
var sut = CreateSut();
sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
_timeProvider.Advance(BoilerMonitorConsts.WaterReadyCooldownPeriod - TimeSpan.FromSeconds(1));
// Act
var result = sut.IsWaterReady("off", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
// Assert
result.Should().BeTrue();
}
[Fact]
public void IsInCooldown_WhenCooldownActive_ShouldReturnTrue()
{
// Arrange
var sut = CreateSut();
sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
// Act & Assert
sut.IsInCooldown.Should().BeTrue();
sut.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()
{
// Arrange
var sut = CreateSut();
// Act & Assert
sut.IsInCooldown.Should().BeFalse();
}
[Fact]
public void IsInCooldown_AfterCooldownExpires_ShouldReturnFalse()
public void ResetCooldown_ShouldClearActiveCooldownAndAllowDetectionToResume()
{
// Arrange
var sut = CreateSut();
sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
_timeProvider.Advance(BoilerMonitorConsts.WaterReadyCooldownPeriod);
// Act & Assert
sut.IsInCooldown.Should().BeFalse();
}
[Fact]
public void ResetCooldown_ShouldClearActiveCooldown()
{
// Arrange
var sut = CreateSut();
sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
var sut = CreateSutWithHeatingObserved();
FeedReadings(sut, RequiredReadings);
sut.IsInCooldown.Should().BeTrue();
// Act
sut.ResetCooldown();
// Assert
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_ShouldAllowBoilerToTurnOnAgain()
public void ResetCooldown_WhenNoCooldownIsActive_ShouldBeANoOp()
{
// Arrange — water becomes ready, then cooldown is reset (midnight)
var sut = CreateSut();
sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
sut.ResetCooldown();
// Act — switch is off, no power → not ready (normal detection resumes)
var result = sut.IsWaterReady("off", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
// Assert
result.Should().BeFalse();
sut.IsInCooldown.Should().BeFalse();
sut.WaterReadySince.Should().BeNull();
FeedReadings(sut, 10).Should().BeFalse("heating was never observed");
}
[Fact]
public void IsWaterReady_CooldownOnlySetOnFirstDetection_ShouldNotResetTimestamp()
{
// Arrange — first detection sets _waterReadySince
var sut = CreateSut();
sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
var sut = CreateSutWithHeatingObserved();
FeedReadings(sut, RequiredReadings);
var originalTimestamp = sut.WaterReadySince;
// Advance halfway through cooldown
_timeProvider.Advance(BoilerMonitorConsts.WaterReadyCooldownPeriod / 2);
_timeProvider.Advance(TimeSpan.FromHours(2));
sut.IsWaterReady("on", 0.0, Threshold).Should().BeTrue();
// Act — second detection during cooldown should NOT reset the timestamp
sut.IsWaterReady("on", 0.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
sut.WaterReadySince.Should().Be(originalTimestamp);
}
// Advance remaining half
_timeProvider.Advance(BoilerMonitorConsts.WaterReadyCooldownPeriod / 2);
[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();
// Assert — cooldown should have expired based on original timestamp
sut.IsInCooldown.Should().BeFalse();
sut.WaterReadySince.Should().BeNull();
}
[Fact]
public void IsWaterReady_HighPowerDoesNotTriggerCooldown_ShouldReturnFalse()
public void NotifyTurnedOn_DuringActiveCooldown_ShouldNotClearCooldown()
{
// Arrange
var sut = CreateSut();
var sut = CreateSutWithHeatingObserved();
FeedReadings(sut, RequiredReadings);
// Act — water is not ready (high power), no cooldown should be triggered
sut.IsWaterReady("on", 2150.0, BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts);
sut.NotifyTurnedOn();
// Assert
sut.IsInCooldown.Should().BeFalse();
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
}
+27 -7
View File
@@ -1,3 +1,5 @@
#region
using System.Globalization;
using BoilerMonitor.Models;
using Microsoft.Extensions.Logging;
@@ -5,6 +7,8 @@ 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
@@ -14,20 +18,30 @@ public sealed class BoilerConfigReader(IHaContext haContext, ILogger<BoilerConfi
public BoilerConfig ReadConfig()
{
var dailyHoursState = haContext.GetState(BoilerDailyHoursEntityId)?.State;
var dailyHours = double.TryParse(dailyHoursState, NumberStyles.Any, CultureInfo.InvariantCulture, out var dh) ? dh : DefaultDailyHours;
var dailyHours = double.TryParse(dailyHoursState, NumberStyles.Any, CultureInfo.InvariantCulture, out var dh)
? dh
: DefaultDailyHours;
var intervalCount = (int)(dailyHours * IntervalsPerHour);
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 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, out var readyByTime))
if (!string.IsNullOrEmpty(readyByState) &&
TimeSpan.TryParse(readyByState, CultureInfo.InvariantCulture, out var readyByTime))
{
deadline = DateTime.Today.Add(readyByTime);
}
@@ -35,15 +49,21 @@ public sealed class BoilerConfigReader(IHaContext haContext, ILogger<BoilerConfi
var skipPriceCapState = haContext.GetState(SkipPriceCapEntityId)?.State;
var skipPriceCap = string.Equals(skipPriceCapState, SwitchOnState, StringComparison.OrdinalIgnoreCase);
logger.LogDebug("Boiler config: intervals={Intervals}, priceCap={Cap}, skipPriceCap={Skip}, deadline={Deadline}",
intervalCount, priceCap, skipPriceCap, deadline);
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug(
"Boiler config: intervals={Intervals}, priceCap={Cap}, skipPriceCap={Skip}, deadline={Deadline}",
intervalCount, priceCap, skipPriceCap, deadline);
}
return new BoilerConfig
var config = new BoilerConfig
{
IntervalCount = intervalCount,
PriceCap = priceCap,
Deadline = deadline,
SkipPriceCap = skipPriceCap
};
return config;
}
}
}
+48 -27
View File
@@ -1,53 +1,74 @@
#region
using BoilerMonitor.Models.Enums;
using BoilerMonitorManager.Interface;
using Microsoft.Extensions.Logging;
#endregion
namespace BoilerMonitorManager;
public class BoilerControlService(ILogger<BoilerControlService> logger) : IBoilerControlService
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)
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;
if (shouldBeOn && !isCurrentlyOn)
switch (shouldBeOn, isCurrentlyOn)
{
logger.LogInformation("Boiler should turn ON — cheap interval active, water not ready, budget available (current state: {State})", currentSwitchState);
case (true, false):
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation(
"Boiler should turn ON — cheap interval active, water not ready, budget available (current state: {State})",
currentSwitchState);
}
return BoilerAction.TurnOn;
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;
}
if (!shouldBeOn && isCurrentlyOn)
{
var reason = GetTurnOffReason(waterReady, isNowCheap, effectiveBudgetExhausted);
logger.LogInformation("Boiler should turn OFF — {Reason} (current state: {State})", reason, currentSwitchState);
return BoilerAction.TurnOff;
}
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 isNowCheap, bool effectiveBudgetExhausted)
private static string GetTurnOffReason(bool waterReady, bool effectiveBudgetExhausted)
{
if (waterReady)
{
return "water is already ready";
}
if (effectiveBudgetExhausted)
{
return "daily budget is exhausted";
}
return "not in a cheap interval";
return effectiveBudgetExhausted
? "daily budget is exhausted"
: "not in a cheap interval";
}
}
}
@@ -8,20 +8,21 @@
</PropertyGroup>
<ItemGroup>
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
<_Parameter1>BoilerMonitor.Manager.Tests</_Parameter1>
</AssemblyAttribute>
<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" />
<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="10.0.5" />
<PackageReference Include="NetDaemon.HassModel" Version="26.11.0" />
<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>
@@ -1,4 +1,7 @@
#region
using System.Globalization;
using System.Text.Json;
using BoilerMonitor.Models;
using BoilerMonitorManager.Interface;
using BoilerMonitorManager.Models;
@@ -8,6 +11,8 @@ using NetDaemon.Extensions.MqttEntityManager;
using NetDaemon.HassModel;
using static BoilerMonitor.Models.BoilerMonitorConsts;
#endregion
namespace BoilerMonitorManager;
public sealed class BoilerMonitorEntityService(
@@ -29,17 +34,10 @@ public sealed class BoilerMonitorEntityService(
BudgetPercentageEntityId,
BudgetExhaustedEntityId,
SessionCountEntityId,
BudgetOverrideEntityId
BudgetOverrideEntityId,
AutoManagementEntityId
];
private static object CreateDeviceBlock() => new
{
identifiers = new[] { DeviceIdentifier },
name = DeviceName,
model = DeviceName,
manufacturer = DeviceManufacturer
};
public async Task CreateEntitiesAsync(CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
@@ -47,17 +45,21 @@ public sealed class BoilerMonitorEntityService(
var entities = GetAllEntities();
var createTasks = entities.Select(async entity =>
{
try
{
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);
}
});
{
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);
}
@@ -69,16 +71,18 @@ public sealed class BoilerMonitorEntityService(
logger.LogInformation("Resetting all BoilerMonitor runtime entity states to defaults");
await Task.WhenAll(
ResetStatusAsync(),
ResetWaterReadyAsync(),
ResetSkipPriceCapAsync(),
ResetTodayRuntimeAsync(),
ResetRemainingTimeAsync(),
ResetBudgetPercentageAsync(),
ResetBudgetExhaustedAsync(),
ResetSessionCountAsync(),
ResetBudgetOverrideAsync()
).ConfigureAwait(false);
ResetStatusAsync(),
ResetWaterReadyAsync(),
ResetSkipPriceCapAsync(),
ResetTodayRuntimeAsync(),
ResetRemainingTimeAsync(),
ResetBudgetPercentageAsync(),
ResetBudgetExhaustedAsync(),
ResetSessionCountAsync(),
ResetBudgetOverrideAsync(),
ResetAutoManagementAsync()
)
.ConfigureAwait(false);
logger.LogInformation("All BoilerMonitor runtime entity states reset to defaults");
}
@@ -91,9 +95,6 @@ public sealed class BoilerMonitorEntityService(
var formattedRunTime = FormatTimeSpan(ctx.TodayRunTime);
var formattedRemaining = FormatTimeSpan(ctx.RemainingTime);
// logger.LogInformation("Updating BoilerMonitor entities: runtime={RunTime}, remaining={Remaining}, budget={Budget}%, sessions={Sessions}",
// formattedRunTime, formattedRemaining, ctx.BudgetPercentage, ctx.SessionCount);
var updateTasks = new[]
{
UpdateStatusAsync(StatusConfigured),
@@ -114,7 +115,7 @@ public sealed class BoilerMonitorEntityService(
try
{
var removeTasks = CleanableEntityIds.Select(entityId => entityManager.RemoveEntity(entityId));
var removeTasks = CleanableEntityIds.Select(entityManager.RemoveEntity);
await Task.WhenAll(removeTasks).ConfigureAwait(false);
logger.LogInformation("BoilerMonitor entities cleaned up successfully (cleanup button retained)");
@@ -122,6 +123,7 @@ public sealed class BoilerMonitorEntityService(
catch (Exception ex)
{
logger.LogError(ex, "Error cleaning up BoilerMonitor entities");
throw;
}
}
@@ -133,9 +135,10 @@ public sealed class BoilerMonitorEntityService(
logger.LogInformation("Resetting transient BoilerMonitor entity states (status, water ready)");
await Task.WhenAll(
ResetStatusAsync(),
ResetWaterReadyAsync()
).ConfigureAwait(false);
ResetStatusAsync(),
ResetWaterReadyAsync()
)
.ConfigureAwait(false);
}
public PersistedBoilerState? ReadPersistedState()
@@ -147,11 +150,16 @@ public sealed class BoilerMonitorEntityService(
var skipPriceCapState = haContext.GetState(SkipPriceCapEntityId)?.State;
var budgetOverrideState = haContext.GetState(BudgetOverrideEntityId)?.State;
if (!TryParseEntitySeconds(runtimeState, out var runtimeSeconds)
|| !TryParseEntityInt(sessionCountState, out var sessionCount))
if (!TryParseEntitySeconds(runtimeState, out var runtimeSeconds) ||
!TryParseEntityInt(sessionCountState, out var sessionCount))
{
logger.LogInformation("No valid persisted BoilerMonitor state found in HA entities (runtime={Runtime}, sessions={Sessions})",
runtimeState, sessionCountState);
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation(
"No valid persisted BoilerMonitor state found in HA entities (runtime={Runtime}, sessions={Sessions})",
runtimeState, sessionCountState);
}
return null;
}
@@ -163,14 +171,20 @@ public sealed class BoilerMonitorEntityService(
BudgetOverrideState = budgetOverrideState
};
logger.LogInformation("Restored persisted BoilerMonitor state: runtime={Runtime}, sessions={Sessions}, skipPriceCap={SkipPriceCap}, budgetOverride={BudgetOverride}",
persisted.AccumulatedRunTime, persisted.SessionCount, persisted.SkipPriceCapState, persisted.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;
}
}
@@ -180,25 +194,78 @@ public sealed class BoilerMonitorEntityService(
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;
return !string.IsNullOrWhiteSpace(state)
&& state is not ("unavailable" or "unknown")
&& double.TryParse(state, CultureInfo.InvariantCulture, out seconds)
&& seconds >= 0;
var tryParseEntitySeconds = !string.IsNullOrWhiteSpace(state) && state is not ("unavailable" or "unknown") && double.TryParse(state, CultureInfo.InvariantCulture, out seconds) && seconds >= 0;
return tryParseEntitySeconds;
}
private static bool TryParseEntityInt(string? state, out int value)
{
value = 0;
return !string.IsNullOrWhiteSpace(state)
&& state is not ("unavailable" or "unknown")
&& int.TryParse(state, CultureInfo.InvariantCulture, out value)
&& value >= 0;
var tryParseEntityInt = !string.IsNullOrWhiteSpace(state) && state is not ("unavailable" or "unknown") && int.TryParse(state, CultureInfo.InvariantCulture, out value) && value >= 0;
return tryParseEntityInt;
}
private ICollection<BoilerMonitorEntity> GetAllEntities()
private static ICollection<BoilerMonitorEntity> GetAllEntities()
{
var device = CreateDeviceBlock();
@@ -224,7 +291,8 @@ public sealed class BoilerMonitorEntityService(
device
}
},
new BoilerMonitorEntity("number", "boilermonitor_config_heating_threshold", "Heating power threshold (watts)")
new BoilerMonitorEntity("number", "boilermonitor_config_heating_threshold",
"Heating power threshold (watts)")
{
AdditionalConfig = new
{
@@ -254,11 +322,13 @@ public sealed class BoilerMonitorEntityService(
},
new BoilerMonitorEntity("sensor", "boilermonitor_today_runtime", "Today runtime")
{
AdditionalConfig = new { unit_of_measurement = "s", icon = "mdi:timer", device_class = "duration", device }
AdditionalConfig = new
{ unit_of_measurement = "s", icon = "mdi:timer", device_class = "duration", device }
},
new BoilerMonitorEntity("sensor", "boilermonitor_remaining_time", "Remaining budget time")
{
AdditionalConfig = new { unit_of_measurement = "s", icon = "mdi:timer-sand", device_class = "duration", device }
AdditionalConfig = new
{ unit_of_measurement = "s", icon = "mdi:timer-sand", device_class = "duration", device }
},
new BoilerMonitorEntity("sensor", "boilermonitor_budget_percentage", "Budget usage")
{
@@ -280,6 +350,10 @@ public sealed class BoilerMonitorEntityService(
new BoilerMonitorEntity("switch", "boilermonitor_budget_override", "Override budget enforcement")
{
AdditionalConfig = new { optimistic = true, icon = "mdi:shield-off-outline", device }
},
new BoilerMonitorEntity("switch", "boilermonitor_auto_management", "Automatic boiler control")
{
AdditionalConfig = new { optimistic = true, icon = "mdi:robot-outline", device }
}
];
}
@@ -297,14 +371,16 @@ public sealed class BoilerMonitorEntityService(
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);
{
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()
@@ -315,35 +391,41 @@ public sealed class BoilerMonitorEntityService(
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);
{
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);
{
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);
{
unit_of_measurement = "%",
friendly_name = "Budget usage",
last_updated = (string?)null
})
.ConfigureAwait(false);
}
private async Task ResetBudgetExhaustedAsync()
@@ -354,11 +436,13 @@ public sealed class BoilerMonitorEntityService(
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);
{
friendly_name = "Heating sessions today",
last_updated = (string?)null
})
.ConfigureAwait(false);
}
private async Task ResetBudgetOverrideAsync()
@@ -366,52 +450,76 @@ public sealed class BoilerMonitorEntityService(
await SetEntityStateSafe(BudgetOverrideEntityId, "OFF").ConfigureAwait(false);
}
private async Task ResetAutoManagementAsync()
{
await SetEntityStateSafe(AutoManagementEntityId, "ON").ConfigureAwait(false);
}
private async Task UpdateWaterReadyAsync(BoilerMonitorUpdateContext ctx, string timestamp)
{
await SetEntityStateSafe(WaterReadyEntityId, ctx.WaterReady ? "yes" : "no").ConfigureAwait(false);
await SetEntityAttributesSafe(WaterReadyEntityId, new
{
boiler_switch_state = ctx.BoilerSwitchState ?? "unknown",
boiler_power_watts = ctx.BoilerPowerWatts,
friendly_name = "Boiler water ready",
last_updated = timestamp
}).ConfigureAwait(false);
{
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 SetEntityStateSafe(TodayRuntimeEntityId,
((int)runTime.TotalSeconds).ToString(CultureInfo.InvariantCulture))
.ConfigureAwait(false);
await SetEntityAttributesSafe(TodayRuntimeEntityId, new
{
formatted,
friendly_name = "Today runtime",
last_updated = timestamp
}).ConfigureAwait(false);
{
formatted,
friendly_name = "Today runtime",
last_updated = timestamp
})
.ConfigureAwait(false);
}
private async Task UpdateRemainingTimeAsync(TimeSpan remaining, string formatted, double budgetHours, string timestamp)
private async Task UpdateRemainingTimeAsync(TimeSpan remaining,
string formatted,
double budgetHours,
string timestamp)
{
var remainingSeconds = Math.Max(0, (int)remaining.TotalSeconds);
await SetEntityStateSafe(RemainingTimeEntityId, remainingSeconds.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
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);
{
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 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);
{
unit_of_measurement = "%",
friendly_name = "Budget usage",
last_updated = timestamp
})
.ConfigureAwait(false);
}
private async Task UpdateBudgetExhaustedAsync(bool exhausted)
@@ -421,12 +529,15 @@ public sealed class BoilerMonitorEntityService(
private async Task UpdateSessionCountAsync(int sessionCount, string timestamp)
{
await SetEntityStateSafe(SessionCountEntityId, sessionCount.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
await SetEntityStateSafe(SessionCountEntityId, sessionCount.ToString(CultureInfo.InvariantCulture))
.ConfigureAwait(false);
await SetEntityAttributesSafe(SessionCountEntityId, new
{
friendly_name = "Heating sessions today",
last_updated = timestamp
}).ConfigureAwait(false);
{
friendly_name = "Heating sessions today",
last_updated = timestamp
})
.ConfigureAwait(false);
}
private async Task SetEntityStateSafe(string entityId, string state)
@@ -434,7 +545,11 @@ public sealed class BoilerMonitorEntityService(
try
{
await entityManager.SetEntityState(entityId, state).ConfigureAwait(false);
logger.LogDebug("Successfully set state for {EntityId}: {State}", entityId, state);
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("Successfully set state for {EntityId}: {State}", entityId, state);
}
}
catch (Exception ex)
{
@@ -447,7 +562,11 @@ public sealed class BoilerMonitorEntityService(
try
{
await entityManager.SetEntityAttributes(entityId, attributes).ConfigureAwait(false);
logger.LogDebug("Successfully set attributes for {EntityId}", entityId);
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("Successfully set attributes for {EntityId}", entityId);
}
}
catch (Exception ex)
{
@@ -459,7 +578,7 @@ public sealed class BoilerMonitorEntityService(
{
var totalHours = (int)ts.TotalHours;
var minutes = ts.Minutes;
return $"{totalHours}h {minutes}m";
}
}
}
+283 -153
View File
@@ -1,5 +1,8 @@
#region
using System.Globalization;
using System.Reactive.Concurrency;
using System.Text.Json;
using BoilerMonitor.Models.Enums;
using BoilerMonitorManager.Interface;
using BoilerMonitorManager.Models;
@@ -12,23 +15,27 @@ using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
using static BoilerMonitor.Models.BoilerMonitorConsts;
#endregion
namespace BoilerMonitorManager;
[NetDaemonApp]
public sealed class BoilerMonitorInit : IBoilerMonitorInit
public sealed class BoilerMonitorInit
{
private readonly ILogger<BoilerMonitorInit> _logger;
private readonly IHaContext _haContext;
private readonly IScheduler _scheduler;
private readonly IMqttEntityManager _mqttEntityManager;
private readonly IBoilerControlService _boilerControlService;
private readonly IBoilerRunTimeTracker _tracker;
private readonly IBoilerMonitorEntityService _entityService;
private readonly IWaterReadyService _waterReadyService;
private readonly IHaContext _haContext;
private readonly ILogger<BoilerMonitorInit> _logger;
private readonly IMqttEntityManager _mqttEntityManager;
private readonly BoilerMonitorOptions _options;
private readonly IScheduler _scheduler;
private readonly TimeProvider _timeProvider;
private readonly IBoilerRunTimeTracker _tracker;
private readonly IWaterReadyService _waterReadyService;
private volatile bool _cleanedUp;
private bool _lastWaterReady;
private bool _cleanedUp;
private DateTimeOffset? _lastWaterReadyNotificationSentAt;
public BoilerMonitorInit(
IHaContext haContext,
@@ -39,7 +46,35 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
IBoilerRunTimeTracker tracker,
IBoilerMonitorEntityService entityService,
IWaterReadyService waterReadyService,
IOptions<BoilerMonitorOptions> options)
IOptions<BoilerMonitorOptions> options,
TimeProvider timeProvider)
: this(
haContext,
logger,
scheduler,
mqttEntityManager,
boilerControlService,
tracker,
entityService,
waterReadyService,
options,
timeProvider,
true)
{
}
internal BoilerMonitorInit(
IHaContext haContext,
ILogger<BoilerMonitorInit> logger,
IScheduler scheduler,
IMqttEntityManager mqttEntityManager,
IBoilerControlService boilerControlService,
IBoilerRunTimeTracker tracker,
IBoilerMonitorEntityService entityService,
IWaterReadyService waterReadyService,
IOptions<BoilerMonitorOptions> options,
TimeProvider timeProvider,
bool startBackgroundScheduling)
{
_haContext = haContext;
_logger = logger;
@@ -50,8 +85,12 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
_entityService = entityService;
_waterReadyService = waterReadyService;
_options = options.Value;
_timeProvider = timeProvider;
_ = InitializeAndScheduleAsync();
if (startBackgroundScheduling)
{
_ = InitializeAndScheduleAsync();
}
}
private async Task InitializeAndScheduleAsync()
@@ -65,6 +104,8 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
ScheduleMidnightReset();
ScheduleEndOfDayReminder();
SubscribeToSkipPriceCapChanges();
SubscribeToAutoManagementChanges();
SubscribeToShowerState();
SubscribeToCleanupButton();
}
catch (Exception ex)
@@ -73,7 +114,7 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
}
}
public async Task InitializeAsync()
private async Task InitializeAsync()
{
try
{
@@ -88,19 +129,32 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
else
{
var persisted = _entityService.ReadPersistedState();
var persistedCooldown = _entityService.ReadPersistedCooldownTimestamp();
await _entityService.CreateEntitiesAsync();
if (persisted is not null)
{
_tracker.RestoreFromSnapshot(persisted.AccumulatedRunTime, persisted.SessionCount);
_tracker.RestoreFromSnapshot();
if (persistedCooldown.HasValue)
{
_waterReadyService.RestoreCooldownState(persistedCooldown.Value);
}
await _entityService.ResetTransientEntitiesAsync();
_logger.LogInformation("BoilerMonitor state restored from HA entities: runtime={Runtime}, sessions={Sessions}",
persisted.AccumulatedRunTime, persisted.SessionCount);
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, performing full entity reset");
_logger.LogInformation("No persisted state found in HA entities, performing full entity reset");
}
}
@@ -113,15 +167,11 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
catch (Exception ex)
{
_logger.LogError(ex, "Error initializing BoilerMonitor");
throw;
}
}
public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default)
{
await _entityService.CleanupEntitiesAsync(cancellationToken);
}
private void SchedulePeriodicPolling()
{
var now = DateTime.Now;
@@ -130,88 +180,129 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
var delayUntilNext = TimeSpan.FromSeconds(secondsUntilNext);
var nextPollTime = now.Add(delayUntilNext);
_logger.LogInformation("Scheduling BoilerMonitor polling every {Interval}s, first at {Time}", DefaultPollIntervalSeconds, nextPollTime);
_scheduler.RunEvery(TimeSpan.FromSeconds(DefaultPollIntervalSeconds), nextPollTime, async void () =>
if (_logger.IsEnabled(LogLevel.Information))
{
try
{
await PollAndUpdateAsync();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error during BoilerMonitor poll cycle");
}
});
_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();
_ = _entityService.ResetEntitiesAsync();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error during midnight reset");
}
});
{
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))
{
_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");
}
});
{
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();
});
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);
});
.Subscribe(_ =>
{
_logger.LogInformation("Cleanup button pressed, removing all BoilerMonitor entities");
Task.Run(HandleCleanupAsync);
});
}
private async Task SubscribeToConfigCommandsAsync()
@@ -227,18 +318,24 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
foreach (var entityId in configEntityIds)
{
var subscription = await _mqttEntityManager.PrepareCommandSubscriptionAsync(entityId).ConfigureAwait(false);
subscription.Subscribe(async void (state) =>
subscription.Subscribe(state => _ = HandleConfigCommandAsync(entityId, state));
}
}
private async Task HandleConfigCommandAsync(string entityId, string? state)
{
try
{
if (_logger.IsEnabled(LogLevel.Information))
{
try
{
_logger.LogInformation("Config entity {EntityId} received command: {Value}", entityId, state);
await _mqttEntityManager.SetStateAsync(entityId, state).ConfigureAwait(false);
}
catch (Exception e)
{
_logger.LogError(e, "Error handling command for entity {EntityId}", entityId);
}
});
_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);
}
}
@@ -247,24 +344,31 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
var switchEntityIds = new[]
{
SkipPriceCapEntityId,
BudgetOverrideEntityId
BudgetOverrideEntityId,
AutoManagementEntityId
};
foreach (var entityId in switchEntityIds)
{
var subscription = await _mqttEntityManager.PrepareCommandSubscriptionAsync(entityId).ConfigureAwait(false);
subscription.Subscribe(async void (state) =>
subscription.Subscribe(state => _ = HandleSwitchCommandAsync(entityId, state));
}
}
private async Task HandleSwitchCommandAsync(string entityId, string? state)
{
try
{
if (_logger.IsEnabled(LogLevel.Information))
{
try
{
_logger.LogInformation("Switch {EntityId} received command: {Value}", entityId, state);
await _mqttEntityManager.SetStateAsync(entityId, state).ConfigureAwait(false);
}
catch (Exception e)
{
_logger.LogError(e, "Error handling command for switch entity {EntityId}", entityId);
}
});
_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);
}
}
@@ -288,6 +392,7 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
if (_cleanedUp)
{
_logger.LogDebug("BoilerMonitor is cleaned up, skipping poll");
return;
}
@@ -298,23 +403,30 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
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);
_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;
var pollInterval = TimeSpan.FromSeconds(config.PollIntervalSeconds!.Value);
_tracker.RecordPollResult(isHeating, pollInterval);
var isHeating = boilerPowerWatts.HasValue &&
boilerPowerWatts.Value >= config.HeatingPowerThresholdWatts!.Value;
_tracker.RecordPollResult();
if (isHeating)
{
_waterReadyService.RecordHeatingObserved();
}
var cheapestIntervalsState = _haContext.GetState(NordPoolCheapestIntervalsEntityId);
var isNowCheap = ReadAttributeBool(cheapestIntervalsState, "is_now_cheap");
var nextCheapInterval = ReadAttributeDateTime(cheapestIntervalsState, "next_cheap_interval");
var budgetOverrideState = _haContext.GetState(BudgetOverrideEntityId)?.State;
var budgetOverride = string.Equals(budgetOverrideState, SwitchOnState, StringComparison.OrdinalIgnoreCase);
@@ -324,39 +436,63 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
var dailyHours = ReadSensorDouble(BoilerDailyHoursEntityId) ?? 1.0;
var waterReady = _waterReadyService.IsWaterReady(boilerSwitchState, boilerPowerWatts, config.HeatingPowerThresholdWatts!.Value);
var waterReady = _waterReadyService.IsWaterReady(boilerSwitchState, boilerPowerWatts,
config.HeatingPowerThresholdWatts!.Value);
if (!_lastWaterReady && waterReady)
if (!_lastWaterReady && waterReady && !IsWithinNotificationCooldown())
{
_haContext.CallService("notify", "mobile_app_marius_phone", null, new
{
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;
? 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 boilerAction = _boilerControlService.DetermineAction(
effectiveIsNowCheap,
waterReady,
boilerSwitchState,
budgetExhausted,
budgetOverride);
ExecuteBoilerAction(boilerAction, config.BoilerSwitchEntityId!);
var autoManagementState = _haContext.GetState(AutoManagementEntityId)?.State;
var autoManagementEnabled =
!string.Equals(autoManagementState, SwitchOffState, StringComparison.OrdinalIgnoreCase);
if (autoManagementEnabled)
{
ExecuteBoilerAction(boilerAction, config.BoilerSwitchEntityId!);
}
else if (boilerAction is not BoilerAction.NoChange)
{
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
{
@@ -366,18 +502,20 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
BudgetExhausted = budgetExhausted,
SessionCount = snapshot.SessionCount,
BudgetHours = dailyHours,
IsCurrentlyHeating = isHeating,
WaterReady = waterReady,
BoilerSwitchState = boilerSwitchState,
BoilerPowerWatts = boilerPowerWatts,
IsNowCheap = effectiveIsNowCheap,
NextCheapIntervalStart = nextCheapInterval
CooldownSince = _waterReadyService.WaterReadySince
};
await _entityService.UpdateEntitiesAsync(context);
_logger.LogDebug("Poll complete: power={Power}W, heating={Heating}, runtime={Runtime}, budget={Budget}%",
boilerPowerWatts, isHeating, snapshot.AccumulatedRunTime, budgetPercentage);
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)
{
@@ -392,12 +530,17 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
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);
}
@@ -411,27 +554,23 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
int? pollInterval = null;
var pollIntervalState = _haContext.GetState(ConfigPollIntervalEntityId)?.State;
if (!string.IsNullOrWhiteSpace(pollIntervalState)
&& double.TryParse(pollIntervalState, CultureInfo.InvariantCulture, out var pollIntervalValue)
&& pollIntervalValue > 0)
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)
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,
BoilerSwitchEntityId = string.IsNullOrWhiteSpace(switchEntityId) ? null : switchEntityId,
BoilerPowerEntityId = string.IsNullOrWhiteSpace(powerEntityId) ? null : powerEntityId.Trim(),
BoilerSwitchEntityId = string.IsNullOrWhiteSpace(switchEntityId) ? null : switchEntityId.Trim(),
PollIntervalSeconds = pollInterval,
HeatingPowerThresholdWatts = heatingThreshold
};
@@ -440,7 +579,7 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
private double? ReadSensorDouble(string entityId)
{
var state = _haContext.GetState(entityId);
if (state?.State is null or "unavailable" or "unknown")
{
return null;
@@ -451,19 +590,23 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
private static bool ReadAttributeBool(EntityState? entityState, string attributeName)
{
if (entityState?.Attributes is null)
if (entityState?.Attributes is not IDictionary<string, object> attributes)
{
return false;
}
try
{
if (entityState.Attributes is IDictionary<string, object> attributes && attributes.TryGetValue(attributeName, out var value))
if (attributes.TryGetValue(attributeName, out var value))
{
return value switch
{
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
};
}
@@ -476,28 +619,15 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
return false;
}
private static DateTime? ReadAttributeDateTime(EntityState? entityState, string attributeName)
private bool IsWithinNotificationCooldown()
{
if (entityState?.Attributes is null)
if (_lastWaterReadyNotificationSentAt is null)
{
return null;
return false;
}
try
{
if (entityState.Attributes is IDictionary<string, object> attributes && attributes.TryGetValue(attributeName, out var value))
{
if (value is string s && DateTime.TryParse(s, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var parsed))
{
return parsed;
}
}
}
catch
{
// Attribute not found or not parseable
}
var elapsed = _timeProvider.GetUtcNow() - _lastWaterReadyNotificationSentAt.Value;
return null;
return elapsed < WaterReadyNotificationCooldown;
}
}
}
@@ -1,10 +1,13 @@
using BoilerMonitor.Models;
#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
@@ -12,8 +15,9 @@ public static class BoilerMonitorServiceRegistration
public static IServiceCollection AddBoilerMonitor(this IServiceCollection services, IConfiguration configuration)
{
var options = configuration
.GetSection(BoilerMonitorOptions.SectionName)
.Get<BoilerMonitorOptions>() ?? new BoilerMonitorOptions();
.GetSection(BoilerMonitorOptions.SectionName)
.Get<BoilerMonitorOptions>() ??
new BoilerMonitorOptions();
if (!options.Enabled)
{
@@ -21,14 +25,12 @@ public static class BoilerMonitorServiceRegistration
}
services
.AddNetDaemonApp<BoilerMonitorInit>()
.AddSingleton<IBoilerControlService, BoilerControlService>()
.AddSingleton<IBoilerRunTimeTracker, BoilerRunTimeTracker>()
.AddTransient<IBoilerMonitorEntityService, BoilerMonitorEntityService>()
.AddSingleton<IWaterReadyService, WaterReadyService>()
.AddSingleton(TimeProvider.System)
.AddScoped<IBoilerConfigReader, BoilerConfigReader>();
.AddNetDaemonApp<BoilerMonitorInit>()
.AddSingleton<IBoilerControlService, BoilerControlService>()
.AddTransient<IBoilerMonitorEntityService, BoilerMonitorEntityService>()
.AddSingleton<IWaterReadyService, WaterReadyService>()
.AddSingleton<IBoilerRunTimeTracker, BoilerRunTimeTracker>();
return services;
}
}
}
+11 -45
View File
@@ -1,66 +1,32 @@
#region
using BoilerMonitorManager.Interface;
using BoilerMonitorManager.Models;
#endregion
namespace BoilerMonitorManager;
public class BoilerRunTimeTracker : IBoilerRunTimeTracker
{
private readonly Lock _lock = new();
private TimeSpan _accumulatedRunTime = TimeSpan.Zero;
private int _sessionCount;
private bool _isInSession;
public void RecordPollResult(bool isHeating, TimeSpan pollInterval)
public void RecordPollResult()
{
lock (_lock)
{
if (isHeating)
{
_accumulatedRunTime += pollInterval;
if (!_isInSession)
{
_sessionCount++;
_isInSession = true;
}
}
else
{
_isInSession = false;
}
}
}
public RunTimeSnapshot GetSnapshot()
{
lock (_lock)
return new RunTimeSnapshot
{
return new RunTimeSnapshot
{
AccumulatedRunTime = _accumulatedRunTime,
SessionCount = _sessionCount,
IsInSession = _isInSession
};
}
AccumulatedRunTime = TimeSpan.Zero,
SessionCount = 0
};
}
public void Reset()
{
lock (_lock)
{
_accumulatedRunTime = TimeSpan.Zero;
_sessionCount = 0;
_isInSession = false;
}
}
public void RestoreFromSnapshot(TimeSpan accumulatedRunTime, int sessionCount)
public void RestoreFromSnapshot()
{
lock (_lock)
{
_accumulatedRunTime = accumulatedRunTime;
_sessionCount = sessionCount;
_isInSession = false;
}
}
}
}
@@ -1,8 +1,17 @@
#region
using BoilerMonitor.Models.Enums;
#endregion
namespace BoilerMonitorManager.Interface;
public interface IBoilerControlService
{
BoilerAction DetermineAction(bool isNowCheap, bool waterReady, string? currentSwitchState, bool budgetExhausted, bool budgetOverride);
}
BoilerAction DetermineAction(
bool isNowCheap,
bool waterReady,
string? currentSwitchState,
bool budgetExhausted,
bool budgetOverride);
}
@@ -1,5 +1,9 @@
#region
using BoilerMonitorManager.Models;
#endregion
namespace BoilerMonitorManager.Interface;
public interface IBoilerMonitorEntityService
@@ -11,4 +15,5 @@ public interface IBoilerMonitorEntityService
Task CleanupEntitiesAsync(CancellationToken cancellationToken = default);
Task SetStatusAsync(string status);
PersistedBoilerState? ReadPersistedState();
}
DateTimeOffset? ReadPersistedCooldownTimestamp();
}
@@ -1,7 +0,0 @@
namespace BoilerMonitorManager.Interface;
public interface IBoilerMonitorInit
{
Task InitializeAsync();
Task CleanupEntitiesAsync(CancellationToken cancellationToken = default);
}
@@ -1,11 +1,15 @@
#region
using BoilerMonitorManager.Models;
#endregion
namespace BoilerMonitorManager.Interface;
public interface IBoilerRunTimeTracker
{
void RecordPollResult(bool isHeating, TimeSpan pollInterval);
void RecordPollResult();
RunTimeSnapshot GetSnapshot();
void Reset();
void RestoreFromSnapshot(TimeSpan accumulatedRunTime, int sessionCount);
}
void RestoreFromSnapshot();
}
@@ -2,8 +2,11 @@ namespace BoilerMonitorManager.Interface;
public interface IWaterReadyService
{
bool IsWaterReady(string? switchState, double? powerWatts, double heatingThresholdWatts);
bool IsInCooldown { get; }
DateTimeOffset? WaterReadySince { get; }
bool IsWaterReady(string? switchState, double? powerWatts, double heatingThresholdWatts);
void NotifyTurnedOn();
void RecordHeatingObserved();
void ResetCooldown();
}
void RestoreCooldownState(DateTimeOffset waterReadySince);
}
@@ -7,9 +7,8 @@ public record BoilerMonitorConfig
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;
}
public bool IsFullyConfigured => !string.IsNullOrWhiteSpace(BoilerPowerEntityId) &&
!string.IsNullOrWhiteSpace(BoilerSwitchEntityId) &&
PollIntervalSeconds is > 0 &&
HeatingPowerThresholdWatts is > 0;
}
@@ -7,8 +7,8 @@ public sealed class BoilerMonitorOptions
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.
/// 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;
}
}
@@ -8,10 +8,8 @@ public record BoilerMonitorUpdateContext
public required bool BudgetExhausted { get; init; }
public required int SessionCount { get; init; }
public required double BudgetHours { get; init; }
public required bool IsCurrentlyHeating { get; init; }
public required bool WaterReady { get; init; }
public required string? BoilerSwitchState { get; init; }
public required double? BoilerPowerWatts { get; init; }
public required bool IsNowCheap { get; init; }
public required DateTime? NextCheapIntervalStart { get; init; }
}
public required DateTimeOffset? CooldownSince { get; init; }
}
@@ -6,4 +6,4 @@ public record PersistedBoilerState
public required int SessionCount { get; init; }
public required string? SkipPriceCapState { get; init; }
public required string? BudgetOverrideState { get; init; }
}
}
@@ -4,5 +4,4 @@ public record RunTimeSnapshot
{
public required TimeSpan AccumulatedRunTime { get; init; }
public required int SessionCount { get; init; }
public required bool IsInSession { get; init; }
}
}
+108 -40
View File
@@ -1,14 +1,19 @@
#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();
private DateTimeOffset? _lastTurnedOnAt;
private readonly Lock _lock = new Lock();
private int _consecutiveBelowThresholdCount;
private bool _hasObservedHeating;
private DateTimeOffset? _waterReadySince;
public bool IsInCooldown
@@ -22,13 +27,29 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
}
}
public DateTimeOffset? WaterReadySince
{
get
{
lock (_lock)
{
return _waterReadySince;
}
}
}
public bool IsWaterReady(string? switchState, double? powerWatts, double heatingThresholdWatts)
{
lock (_lock)
{
if (IsWithinCooldownPeriod())
{
logger.LogDebug("Water ready cooldown active (since {Since}), suppressing turn-on", _waterReadySince);
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("Water ready cooldown active (since {Since}), suppressing turn-on",
_waterReadySince);
}
return true;
}
}
@@ -43,39 +64,79 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
return false;
}
if (IsWithinWarmUpGracePeriod())
lock (_lock)
{
logger.LogDebug(
"Ignoring low power reading ({PowerWatts}W) during warm-up grace period",
powerWatts.Value);
return false;
}
var isReady = powerWatts.Value < heatingThresholdWatts;
if (isReady)
{
lock (_lock)
if (!_hasObservedHeating)
{
_waterReadySince ??= timeProvider.GetUtcNow();
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("Ignoring power reading ({PowerWatts}W) — boiler has not been observed heating yet",
powerWatts.Value);
}
return false;
}
logger.LogInformation(
"Water detected as ready, cooldown period ({CooldownPeriod}) started",
BoilerMonitorConsts.WaterReadyCooldownPeriod);
}
if (powerWatts.Value >= heatingThresholdWatts)
{
_consecutiveBelowThresholdCount = 0;
return isReady;
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)
{
_lastTurnedOnAt = timeProvider.GetUtcNow();
_hasObservedHeating = false;
_consecutiveBelowThresholdCount = 0;
}
logger.LogDebug("Boiler turn-on recorded, warm-up grace period started ({GracePeriod})", BoilerMonitorConsts.WarmUpGracePeriod);
logger.LogDebug(
"Boiler turn-on recorded, awaiting first heating observation before water ready detection is enabled");
}
public void RecordHeatingObserved()
{
lock (_lock)
{
if (_hasObservedHeating)
{
return;
}
_hasObservedHeating = true;
}
logger.LogDebug("Heating observed, water ready detection is now enabled");
}
public void ResetCooldown()
@@ -83,33 +144,40 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
lock (_lock)
{
_waterReadySince = null;
_consecutiveBelowThresholdCount = 0;
}
logger.LogInformation("Water ready cooldown has been reset");
}
private bool IsWithinCooldownPeriod()
{
if (_waterReadySince is null)
{
return false;
}
var elapsed = timeProvider.GetUtcNow() - _waterReadySince.Value;
return elapsed < BoilerMonitorConsts.WaterReadyCooldownPeriod;
}
private bool IsWithinWarmUpGracePeriod()
public void RestoreCooldownState(DateTimeOffset waterReadySince)
{
lock (_lock)
{
if (_lastTurnedOnAt is null)
var todayMidnightUtc = new DateTimeOffset(timeProvider.GetUtcNow().Date, TimeSpan.Zero);
if (waterReadySince < todayMidnightUtc)
{
return false;
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation("Persisted cooldown is from a previous day ({Since}), not restoring",
waterReadySince);
}
return;
}
var elapsed = timeProvider.GetUtcNow() - _lastTurnedOnAt.Value;
return elapsed < BoilerMonitorConsts.WarmUpGracePeriod;
_waterReadySince = waterReadySince;
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation("Restored water ready cooldown from {Since}", waterReadySince);
}
}
}
}
private bool IsWithinCooldownPeriod()
{
return _waterReadySince is not null;
}
}
+2 -2
View File
@@ -1,7 +1,7 @@
namespace BoilerMonitor.Models;
/// <summary>
/// Boiler scheduling configuration read from Home Assistant entity state.
/// Boiler scheduling configuration read from Home Assistant entity state.
/// </summary>
public sealed class BoilerConfig
{
@@ -12,4 +12,4 @@ public sealed class BoilerConfig
public required DateTime Deadline { get; init; }
public required bool SkipPriceCap { get; init; }
}
}
@@ -8,11 +8,11 @@
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\HomeAssistant.Models\HomeAssistant.Models.csproj" />
<ProjectReference Include="..\HomeAssistant.Models\HomeAssistant.Models.csproj"/>
</ItemGroup>
<ItemGroup>
<PackageReference Include="NetDaemon.Extensions.Mqtt" Version="26.11.0" />
<PackageReference Include="NetDaemon.Extensions.Mqtt" Version="26.43.1"/>
</ItemGroup>
</Project>
+23 -14
View File
@@ -5,24 +5,20 @@ 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.
/// 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>
/// Grace period after the boiler switch is turned on, during which
/// low power readings are ignored for "water ready" detection.
/// This prevents false positives caused by the heating element ramp-up delay.
/// Number of consecutive below-threshold power readings required before
/// declaring water as ready. Prevents false positives from transient sensor glitches.
/// At 30s poll interval, a value of 2 means 60s of confirmed low power.
/// </summary>
public static readonly TimeSpan WarmUpGracePeriod = TimeSpan.FromMinutes(2);
public const int ConsecutiveReadingsRequired = 2;
/// <summary>
/// Cooldown period after the water has been detected as ready,
/// during which the boiler will not be turned back on.
/// This prevents wasteful on/off cycling when water is already heated.
/// </summary>
public static readonly TimeSpan WaterReadyCooldownPeriod = TimeSpan.FromHours(1);
public const string ShowerStateEntityId = "sensor.showermonitor_state";
public const string ShowerActiveState = "Active";
public const int MinPollIntervalSeconds = 5;
public const int MaxPollIntervalSeconds = 300;
@@ -49,6 +45,12 @@ public static class BoilerMonitorConsts
public const string SessionCountEntityId = "sensor.boilermonitor_session_count";
public const string BudgetOverrideEntityId = "switch.boilermonitor_budget_override";
/// <summary>
/// When on, the daemon may call the configured boiler switch per price/budget/water-ready logic.
/// When off, monitoring continues but automatic turn_on/turn_off calls are suppressed (manual control).
/// </summary>
public const string AutoManagementEntityId = "switch.boilermonitor_auto_management";
public const string NordPoolCheapestIntervalsEntityId = "sensor.nordpool_cheapest_intervals";
public const string BoilerDailyHoursEntityId = "input_number.boiler_daily_hours";
@@ -57,11 +59,18 @@ public static class BoilerMonitorConsts
public const string StatusConfigured = "configured";
public const string StatusAwaitingConfiguration = "awaiting_configuration";
public const string StatusCleanedUp = "cleaned_up";
public const string SwitchOnState = "on";
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);
}
+9 -5
View File
@@ -1,14 +1,14 @@
#region
using HomeAssistant.Models;
using NetDaemon.Extensions.MqttEntityManager;
#endregion
namespace BoilerMonitor.Models;
public class BoilerMonitorEntity : EntityCreateModel
{
public string Domain { get; set; }
public string Identifier { get; set; }
public string Name { get; set; }
public BoilerMonitorEntity(string domain, string identifier, string name)
{
Domain = domain;
@@ -22,4 +22,8 @@ public class BoilerMonitorEntity : EntityCreateModel
Name = Name
};
}
}
private string Domain { get; }
private string Identifier { get; }
private string Name { get; }
}
+1 -1
View File
@@ -5,4 +5,4 @@ public enum BoilerAction
NoChange,
TurnOn,
TurnOff
}
}
+2 -2
View File
@@ -1,9 +1,9 @@
namespace BoilerMonitor.Models;
/// <summary>
/// Reads the boiler scheduling configuration from Home Assistant entity state.
/// Reads the boiler scheduling configuration from Home Assistant entity state.
/// </summary>
public interface IBoilerConfigReader
{
BoilerConfig ReadConfig();
}
}
@@ -1321,6 +1321,8 @@ public partial class SwitchEntities
public SwitchEntity BalkonyLaps => new(_haContext, "switch.balkony_laps");
///<summary>Boiler Monitor Override budget enforcement</summary>
public SwitchEntity BoilermonitorBudgetOverride => new(_haContext, "switch.boilermonitor_budget_override");
///<summary>Boiler Monitor Automatic boiler control</summary>
public SwitchEntity BoilermonitorAutoManagement => new(_haContext, "switch.boilermonitor_auto_management");
///<summary>Boiler Monitor Skip price cap, heat until ready</summary>
public SwitchEntity BoilermonitorSkipPriceCap => new(_haContext, "switch.boilermonitor_skip_price_cap");
///<summary>Dishwasher</summary>
+63 -10
View File
@@ -1,16 +1,29 @@
using HomeAssistant.Entities.Interfaces;
#region
using HomeAssistant.Entities.Interfaces;
using HomeAssistant.Models;
using HomeAssistantGenerated;
using Microsoft.Extensions.Options;
using NetDaemon.Extensions.MqttEntityManager;
using NetDaemon.HassModel;
#endregion
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)
{
await Task.WhenAll(entities.Select(CreateEntityAsync));
}
/// <summary>
/// Every topic owned by an entity created through <see cref="IMqttEntityManager" />:
/// <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)
{
if (createModel.EntityId != null)
@@ -23,14 +36,54 @@ public class EntityManager(IMqttEntityManager entityManager) : IEntityManager
{
await entityManager.SetStateAsync(entityId, state);
}
public async Task SetEntityAttributes(string entityId, object attributes)
{
await entityManager.SetAttributesAsync(entityId, attributes);
}
public async Task RemoveEntity(string entityId)
/// <summary>
/// Removes the entity from Home Assistant and clears every retained MQTT message it owns at the broker.
/// <para>
/// <see cref="IMqttEntityManager.RemoveAsync" /> publishes the empty discovery payload without the
/// retain flag, so Home Assistant forgets the entity but the broker keeps the retained config and
/// re-discovers the entity after a Home Assistant restart or MQTT reload. Publishing an empty
/// retained payload through Home Assistant's <c>mqtt.publish</c> service clears the retained
/// messages and removes the entity for good.
/// </para>
/// </summary>
public Task RemoveEntity(string entityId)
{
await entityManager.RemoveAsync(entityId);
var rootTopic = BuildRootTopic(entityId, mqttConfiguration.Value.DiscoveryPrefix);
foreach (var suffix in CleanupTopicSuffixes)
{
haContext.CallService("mqtt", "publish", null, new MqttPublishParameters
{
Topic = $"{rootTopic}/{suffix}",
Payload = string.Empty,
Retain = true
});
}
// IHaContext.CallService is fire-and-forget; the calls are queued in order on the HA websocket.
return Task.CompletedTask;
}
private static string BuildRootTopic(string entityId, string discoveryPrefix)
{
var separatorIndex = entityId.IndexOf('.');
if (separatorIndex <= 0 || separatorIndex == entityId.Length - 1)
{
throw new ArgumentException(
$"Entity id '{entityId}' is not in the 'domain.object_id' format.",
nameof(entityId));
}
var domain = entityId[..separatorIndex];
var objectId = entityId[(separatorIndex + 1)..];
return $"{discoveryPrefix}/{domain}/{objectId}";
}
}
@@ -7,18 +7,18 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="NetDaemon.AppModel" Version="26.11.0" />
<PackageReference Include="NetDaemon.Extensions.Mqtt" Version="26.11.0" />
<PackageReference Include="NetDaemon.Runtime" Version="26.11.0" />
<PackageReference Include="NetDaemon.HassModel" Version="26.11.0" />
<PackageReference Include="NetDaemon.Client" Version="26.11.0" />
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.11.0" />
<PackageReference Include="NetDaemon.Extensions.Logging" Version="26.11.0" />
<PackageReference Include="NetDaemon.Extensions.Tts" Version="26.11.0" />
<PackageReference Include="NetDaemon.AppModel" Version="26.43.1"/>
<PackageReference Include="NetDaemon.Extensions.Mqtt" Version="26.43.1"/>
<PackageReference Include="NetDaemon.Runtime" Version="26.43.1"/>
<PackageReference Include="NetDaemon.HassModel" Version="26.43.1"/>
<PackageReference Include="NetDaemon.Client" Version="26.43.1"/>
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.43.1"/>
<PackageReference Include="NetDaemon.Extensions.Logging" Version="26.43.1"/>
<PackageReference Include="NetDaemon.Extensions.Tts" Version="26.43.1"/>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\HomeAssistant.Models\HomeAssistant.Models.csproj" />
<ProjectReference Include="..\NordPool.Models\NordPool.Models.csproj" />
<ProjectReference Include="..\HomeAssistant.Models\HomeAssistant.Models.csproj"/>
<ProjectReference Include="..\NordPool.Models\NordPool.Models.csproj"/>
</ItemGroup>
</Project>
@@ -1,10 +1,13 @@
using HomeAssistant.Models;
#region
using HomeAssistant.Models;
#endregion
namespace HomeAssistant.Entities.Interfaces;
public interface IEntityManager
{
Task CreateEntitiesAsync(ICollection<EntityCreateModel> entities);
Task CreateEntityAsync(EntityCreateModel createModel);
Task SetEntityState(string entityId, string state);
Task SetEntityAttributes(string entityId, object attributes);
@@ -1,69 +0,0 @@
using BoilerMonitor.Models;
using LightMonitor.Models;
using NordPool.Models;
using ShowerMonitor.Models;
namespace HomeAssistant.HistoryReplay.Configuration;
public static class ReplayEntityMap
{
public static IReadOnlyList<string> GetNordPoolEntities() =>
[
"sensor.nordpool_kwh_lt_eur_3_10_0",
NordPoolConsts.CurrentPriceEntityId,
BoilerMonitorConsts.BoilerDailyHoursEntityId,
BoilerMonitorConsts.BoilerPriceCapEntityId,
BoilerMonitorConsts.BoilerReadyByEntityId,
BoilerMonitorConsts.SkipPriceCapEntityId
];
public static IReadOnlyList<string> GetBoilerEntities(string boilerPowerEntityId, string boilerSwitchEntityId) =>
[
boilerPowerEntityId,
boilerSwitchEntityId,
"sensor.nordpool_cheapest_intervals",
BoilerMonitorConsts.SkipPriceCapEntityId,
BoilerMonitorConsts.BudgetOverrideEntityId,
BoilerMonitorConsts.BoilerDailyHoursEntityId
];
public static IReadOnlyList<string> GetShowerEntities(string bathroomHumidityEntityId, string mainHomeHumidityEntityId) =>
[
bathroomHumidityEntityId,
mainHomeHumidityEntityId
];
public static IReadOnlyList<string> GetPowerEntities(string mainMeterEntityId) =>
[
mainMeterEntityId,
NordPoolConsts.CurrentPriceEntityId
];
public static IReadOnlyList<string> GetLightEntities(string sunEntityId, string lightEntityId, string[] personEntityIds)
{
var entities = new List<string> { sunEntityId, lightEntityId };
entities.AddRange(personEntityIds);
return entities;
}
public static IReadOnlyList<string> GetAllEntities(
string boilerPowerEntityId,
string boilerSwitchEntityId,
string bathroomHumidityEntityId,
string mainHomeHumidityEntityId,
string mainMeterEntityId,
string sunEntityId,
string lightEntityId,
string[] personEntityIds)
{
var all = new HashSet<string>();
foreach (var e in GetNordPoolEntities()) all.Add(e);
foreach (var e in GetBoilerEntities(boilerPowerEntityId, boilerSwitchEntityId)) all.Add(e);
foreach (var e in GetShowerEntities(bathroomHumidityEntityId, mainHomeHumidityEntityId)) all.Add(e);
foreach (var e in GetPowerEntities(mainMeterEntityId)) all.Add(e);
foreach (var e in GetLightEntities(sunEntityId, lightEntityId, personEntityIds)) all.Add(e);
return [.. all];
}
}
@@ -1,19 +0,0 @@
namespace HomeAssistant.HistoryReplay.Configuration;
public sealed class ReplayOptions
{
public const string SectionName = "Replay";
public DateTimeOffset StartTime { get; set; } = DateTimeOffset.UtcNow.AddDays(-1);
public DateTimeOffset EndTime { get; set; } = DateTimeOffset.UtcNow;
public ReplayMonitorFlags Monitors { get; set; } = new();
}
public sealed class ReplayMonitorFlags
{
public bool NordPool { get; set; } = true;
public bool Boiler { get; set; } = true;
public bool Shower { get; set; } = true;
public bool Power { get; set; } = true;
public bool Light { get; set; } = true;
}
@@ -1,9 +0,0 @@
namespace HomeAssistant.HistoryReplay.HistoryData;
public sealed class HistoryStateEntry
{
public required string EntityId { get; init; }
public required string? State { get; init; }
public required DateTimeOffset LastChanged { get; init; }
public IReadOnlyDictionary<string, object>? Attributes { get; init; }
}
@@ -1,65 +0,0 @@
namespace HomeAssistant.HistoryReplay.HistoryData;
public sealed class HistoryTimeline
{
private readonly Dictionary<string, List<HistoryStateEntry>> _entityTimelines = new(StringComparer.OrdinalIgnoreCase);
public void AddEntries(string entityId, IEnumerable<HistoryStateEntry> entries)
{
if (!_entityTimelines.TryGetValue(entityId, out var list))
{
list = [];
_entityTimelines[entityId] = list;
}
list.AddRange(entries);
list.Sort((a, b) => a.LastChanged.CompareTo(b.LastChanged));
}
public HistoryStateEntry? GetStateAt(string entityId, DateTimeOffset timestamp)
{
if (!_entityTimelines.TryGetValue(entityId, out var entries) || entries.Count == 0)
{
return null;
}
HistoryStateEntry? best = null;
foreach (var entry in entries)
{
if (entry.LastChanged <= timestamp)
{
best = entry;
}
else
{
break;
}
}
return best;
}
public IReadOnlyList<DateTimeOffset> GetAllTimestamps()
{
var timestamps = new SortedSet<DateTimeOffset>();
foreach (var entries in _entityTimelines.Values)
{
foreach (var entry in entries)
{
timestamps.Add(entry.LastChanged);
}
}
return [.. timestamps];
}
public IReadOnlyList<string> GetEntityIds() => [.. _entityTimelines.Keys];
public IReadOnlyList<HistoryStateEntry> GetEntityHistory(string entityId)
{
return _entityTimelines.TryGetValue(entityId, out var entries) ? entries : [];
}
public int TotalEntryCount => _entityTimelines.Values.Sum(e => e.Count);
}
@@ -1,168 +0,0 @@
using System.Globalization;
using System.Text.Json;
using HomeAssistant.HistoryReplay.HomeAssistantClient;
using Microsoft.Extensions.Logging;
namespace HomeAssistant.HistoryReplay.HistoryData;
public sealed class HomeAssistantHistoryProvider(
IHomeAssistantApiClient client,
ILogger<HomeAssistantHistoryProvider> logger) : IHistoryDataProvider
{
private const int MaxEntitiesPerRequest = 10;
public async Task<HistoryTimeline> FetchHistoryAsync(
IReadOnlyList<string> entityIds,
DateTimeOffset startTime,
DateTimeOffset endTime,
CancellationToken cancellationToken = default)
{
var timeline = new HistoryTimeline();
var batches = ChunkEntities(entityIds, MaxEntitiesPerRequest);
var tasks = batches.Select(batch => FetchBatchAsync(batch, startTime, endTime, cancellationToken));
var results = await Task.WhenAll(tasks).ConfigureAwait(false);
foreach (var batchTimeline in results)
{
foreach (var entityId in batchTimeline.GetEntityIds())
{
timeline.AddEntries(entityId, batchTimeline.GetEntityHistory(entityId));
}
}
logger.LogInformation(
"Fetched history for {EntityCount} entities: {EntryCount} total entries ({Start} to {End})",
entityIds.Count, timeline.TotalEntryCount, startTime, endTime);
return timeline;
}
private async Task<HistoryTimeline> FetchBatchAsync(
IReadOnlyList<string> entityIds,
DateTimeOffset startTime,
DateTimeOffset endTime,
CancellationToken cancellationToken)
{
var timeline = new HistoryTimeline();
var entityIdsString = string.Join(",", entityIds);
logger.LogDebug("Fetching history batch for: {Entities}", entityIdsString);
try
{
var result = await client.GetHistoryAsync(
entityIdsString, startTime, endTime, minimalResponse: false, cancellationToken)
.ConfigureAwait(false);
ParseHistoryResponse(result, timeline);
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to fetch history for entities: {Entities}", entityIdsString);
}
return timeline;
}
private void ParseHistoryResponse(JsonElement response, HistoryTimeline timeline)
{
if (response.ValueKind != JsonValueKind.Array)
{
return;
}
foreach (var entityArray in response.EnumerateArray())
{
if (entityArray.ValueKind != JsonValueKind.Array)
{
continue;
}
foreach (var stateObj in entityArray.EnumerateArray())
{
var entry = ParseStateEntry(stateObj);
if (entry is not null)
{
timeline.AddEntries(entry.EntityId, [entry]);
}
}
}
}
private HistoryStateEntry? ParseStateEntry(JsonElement stateObj)
{
if (!stateObj.TryGetProperty("entity_id", out var entityIdProp))
{
return null;
}
var entityId = entityIdProp.GetString();
if (string.IsNullOrEmpty(entityId))
{
return null;
}
var state = stateObj.TryGetProperty("state", out var stateProp) ? stateProp.GetString() : null;
DateTimeOffset lastChanged;
if (stateObj.TryGetProperty("last_changed", out var lastChangedProp))
{
if (!DateTimeOffset.TryParse(lastChangedProp.GetString(), CultureInfo.InvariantCulture,
DateTimeStyles.RoundtripKind, out lastChanged))
{
return null;
}
}
else
{
return null;
}
Dictionary<string, object>? attributes = null;
if (stateObj.TryGetProperty("attributes", out var attrProp) && attrProp.ValueKind == JsonValueKind.Object)
{
attributes = ParseAttributes(attrProp);
}
return new HistoryStateEntry
{
EntityId = entityId,
State = state,
LastChanged = lastChanged,
Attributes = attributes
};
}
private static Dictionary<string, object> ParseAttributes(JsonElement attrElement)
{
var attributes = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
foreach (var prop in attrElement.EnumerateObject())
{
attributes[prop.Name] = prop.Value.ValueKind switch
{
JsonValueKind.String => prop.Value.GetString() ?? string.Empty,
JsonValueKind.Number => prop.Value.GetDouble(),
JsonValueKind.True => true,
JsonValueKind.False => false,
_ => prop.Value.GetRawText()
};
}
return attributes;
}
private static IReadOnlyList<IReadOnlyList<string>> ChunkEntities(IReadOnlyList<string> entities, int chunkSize)
{
var chunks = new List<IReadOnlyList<string>>();
for (var i = 0; i < entities.Count; i += chunkSize)
{
var chunk = entities.Skip(i).Take(chunkSize).ToList();
chunks.Add(chunk);
}
return chunks;
}
}
@@ -1,10 +0,0 @@
namespace HomeAssistant.HistoryReplay.HistoryData;
public interface IHistoryDataProvider
{
Task<HistoryTimeline> FetchHistoryAsync(
IReadOnlyList<string> entityIds,
DateTimeOffset startTime,
DateTimeOffset endTime,
CancellationToken cancellationToken = default);
}
@@ -1,45 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>14.0</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>HomeAssistant.HistoryReplay</RootNamespace>
</PropertyGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="appsettings.development.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
<CopyToPublishDirectory>Never</CopyToPublishDirectory>
</None>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="10.0.5" />
<PackageReference Include="Microsoft.Extensions.Http" Version="10.0.5" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.5" />
<PackageReference Include="NetDaemon.HassModel" Version="26.11.0" />
<PackageReference Include="Serilog.Extensions.Hosting" Version="10.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.1.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BoilerMonitor.Manager\BoilerMonitor.Manager.csproj" />
<ProjectReference Include="..\BoilerMonitor.Models\BoilerMonitor.Models.csproj" />
<ProjectReference Include="..\NordPool.Manager\NordPool.Manager.csproj" />
<ProjectReference Include="..\NordPool.Models\NordPool.Models.csproj" />
<ProjectReference Include="..\PowerMonitor.Manager\PowerMonitor.Manager.csproj" />
<ProjectReference Include="..\PowerMonitor.Models\PowerMonitor.Models.csproj" />
<ProjectReference Include="..\ShowerMonitor.Manager\ShowerMonitor.Manager.csproj" />
<ProjectReference Include="..\ShowerMonitor.Models\ShowerMonitor.Models.csproj" />
<ProjectReference Include="..\LightMonitor.Manager\LightMonitor.Manager.csproj" />
<ProjectReference Include="..\LightMonitor.Models\LightMonitor.Models.csproj" />
<ProjectReference Include="..\HomeAssistant.Entities\HomeAssistant.Entities.csproj" />
</ItemGroup>
</Project>
@@ -1,50 +0,0 @@
using System.Net.Http.Headers;
using System.Text.Json;
using Microsoft.Extensions.Options;
namespace HomeAssistant.HistoryReplay.HomeAssistantClient;
public sealed class HomeAssistantApiClient : IHomeAssistantApiClient
{
private readonly HttpClient _httpClient;
public HomeAssistantApiClient(HttpClient httpClient, IOptions<HomeAssistantSettings> settings)
{
_httpClient = httpClient;
_httpClient.BaseAddress = settings.Value.BaseUrl;
_httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", settings.Value.Token);
_httpClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
_httpClient.Timeout = TimeSpan.FromSeconds(HomeAssistantSettings.DefaultTimeoutSeconds);
}
public async Task<JsonElement> GetHistoryAsync(
string entityIds,
DateTimeOffset? startTime = null,
DateTimeOffset? endTime = null,
bool minimalResponse = true,
CancellationToken cancellationToken = default)
{
var start = startTime ?? DateTimeOffset.UtcNow.AddDays(-1);
var path = $"/api/history/period/{start:O}?filter_entity_id={Uri.EscapeDataString(entityIds)}";
if (endTime.HasValue)
path += $"&end_time={Uri.EscapeDataString(endTime.Value.ToString("O"))}";
if (minimalResponse)
path += "&minimal_response";
return await GetJsonAsync(path, cancellationToken).ConfigureAwait(false);
}
private async Task<JsonElement> GetJsonAsync(string path, CancellationToken cancellationToken)
{
var response = await _httpClient.GetAsync(path, cancellationToken).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
var doc = await JsonDocument.ParseAsync(stream, cancellationToken: cancellationToken).ConfigureAwait(false);
return doc.RootElement.Clone();
}
}
@@ -1,15 +0,0 @@
namespace HomeAssistant.HistoryReplay.HomeAssistantClient;
public sealed class HomeAssistantSettings
{
public const string SectionName = "HomeAssistant";
public const int DefaultPort = 8123;
public const int DefaultTimeoutSeconds = 30;
public string Host { get; set; } = string.Empty;
public int Port { get; set; } = DefaultPort;
public string Token { get; set; } = string.Empty;
public bool Ssl { get; set; }
public Uri BaseUrl => new UriBuilder(Ssl ? "https" : "http", Host, Port).Uri;
}
@@ -1,13 +0,0 @@
using System.Text.Json;
namespace HomeAssistant.HistoryReplay.HomeAssistantClient;
public interface IHomeAssistantApiClient
{
Task<JsonElement> GetHistoryAsync(
string entityIds,
DateTimeOffset? startTime = null,
DateTimeOffset? endTime = null,
bool minimalResponse = true,
CancellationToken cancellationToken = default);
}
-191
View File
@@ -1,191 +0,0 @@
using BoilerMonitorManager;
using BoilerMonitorManager.Interface;
using BoilerMonitorManager.Models;
using HomeAssistant.Entities.Interfaces;
using HomeAssistant.HistoryReplay.Configuration;
using HomeAssistant.HistoryReplay.HistoryData;
using HomeAssistant.HistoryReplay.Replay;
using HomeAssistant.HistoryReplay.Reporting;
using HomeAssistant.HistoryReplay.Runners;
using HomeAssistant.HistoryReplay.HomeAssistantClient;
using LightMonitorManager.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NordPoolManager;
using NordPoolManager.Interface;
using PowerMonitorManager;
using PowerMonitorManager.Interface;
using PowerMonitorManager.Models;
using Serilog;
using ShowerMonitorManager;
using ShowerMonitorManager.Interface;
using ShowerMonitorManager.Models;
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Information()
.WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
.CreateLogger();
try
{
Log.Information("Starting Home Assistant History Replay");
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false)
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") ?? "Production"}.json", optional: true)
.AddEnvironmentVariables()
.Build();
var services = new ServiceCollection();
services.AddLogging(builder =>
{
builder.ClearProviders();
builder.AddSerilog(dispose: true);
});
services.Configure<HomeAssistantSettings>(configuration.GetSection(HomeAssistantSettings.SectionName));
services.Configure<ReplayOptions>(configuration.GetSection(ReplayOptions.SectionName));
services.Configure<BoilerMonitorOptions>(configuration.GetSection(BoilerMonitorOptions.SectionName));
services.Configure<ShowerMonitorOptions>(configuration.GetSection(ShowerMonitorOptions.SectionName));
services.Configure<PowerMonitorOptions>(configuration.GetSection(PowerMonitorOptions.SectionName));
services.Configure<LightMonitorOptions>(configuration.GetSection(LightMonitorOptions.SectionName));
services.AddHttpClient<IHomeAssistantApiClient, HomeAssistantApiClient>();
services.AddSingleton<IHistoryDataProvider, HomeAssistantHistoryProvider>();
var replayOptions = configuration.GetSection(ReplayOptions.SectionName).Get<ReplayOptions>() ?? new ReplayOptions();
var replayTimeline = new ReplayTimeline();
var replayTimeProvider = new ReplayTimeProvider(replayOptions.StartTime);
services.AddSingleton(replayTimeline);
services.AddSingleton(replayTimeProvider);
services.AddSingleton<TimeProvider>(replayTimeProvider);
services.AddSingleton<IEntityManager, NoOpEntityManager>();
services.AddSingleton<ICheapestIntervalsFinder, CheapestIntervalsFinder>();
services.AddSingleton<IBoilerControlService, BoilerControlService>();
services.AddSingleton<IBoilerRunTimeTracker, BoilerRunTimeTracker>();
services.AddSingleton<IWaterReadyService, WaterReadyService>();
services.AddSingleton<IOtherPowerCalculationService, OtherPowerCalculationService>();
services.AddSingleton<IPowerCostCalculationService, PowerCostCalculationService>();
var showerOptions = configuration.GetSection(ShowerMonitorOptions.SectionName).Get<ShowerMonitorOptions>() ?? new ShowerMonitorOptions();
services.AddSingleton<IHumidityRateCalculator>(_ => new HumidityRateCalculator(showerOptions.RateWindowSize));
services.AddSingleton<IShowerDetectionService, ShowerDetectionService>();
services.AddSingleton<ConsoleReportRenderer>();
var provider = services.BuildServiceProvider();
var historyProvider = provider.GetRequiredService<IHistoryDataProvider>();
var logger = provider.GetRequiredService<ILogger<Program>>();
var boilerOpts = provider.GetRequiredService<IOptions<BoilerMonitorOptions>>().Value;
var showerOpts = provider.GetRequiredService<IOptions<ShowerMonitorOptions>>().Value;
var powerOpts = provider.GetRequiredService<IOptions<PowerMonitorOptions>>().Value;
var lightOpts = provider.GetRequiredService<IOptions<LightMonitorOptions>>().Value;
logger.LogInformation("Replay period: {Start} to {End}", replayOptions.StartTime, replayOptions.EndTime);
var allEntityIds = ReplayEntityMap.GetAllEntities(
boilerPowerEntityId: "sensor.boiler_power",
boilerSwitchEntityId: "switch.boiler",
bathroomHumidityEntityId: showerOpts.BathroomHumidityEntityId,
mainHomeHumidityEntityId: showerOpts.MainHomeHumidityEntityId,
mainMeterEntityId: powerOpts.MainMeterEntityId,
sunEntityId: lightOpts.SunEntityId,
lightEntityId: lightOpts.LightEntityId,
personEntityIds: lightOpts.PersonEntityIds);
logger.LogInformation("Fetching history for {Count} entities...", allEntityIds.Count);
var timeline = await historyProvider.FetchHistoryAsync(
allEntityIds, replayOptions.StartTime, replayOptions.EndTime);
var replayHaContext = new ReplayHaContext(
timeline,
replayTimeProvider,
replayTimeline,
provider.GetRequiredService<ILogger<ReplayHaContext>>());
var fanControlService = new ExhaustFanControlService(
replayHaContext,
provider.GetRequiredService<ILogger<ExhaustFanControlService>>(),
provider.GetRequiredService<IOptions<ShowerMonitorOptions>>());
var runners = new List<IMonitorReplayRunner>();
if (replayOptions.Monitors.NordPool)
{
runners.Add(new NordPoolReplayRunner(
timeline, replayTimeProvider, replayTimeline,
provider.GetRequiredService<ICheapestIntervalsFinder>(),
provider.GetRequiredService<ILogger<NordPoolReplayRunner>>(),
provider.GetRequiredService<IOptions<ReplayOptions>>()));
}
if (replayOptions.Monitors.Boiler)
{
runners.Add(new BoilerReplayRunner(
timeline, replayTimeProvider, replayTimeline,
provider.GetRequiredService<IBoilerControlService>(),
provider.GetRequiredService<IBoilerRunTimeTracker>(),
provider.GetRequiredService<IWaterReadyService>(),
provider.GetRequiredService<ILogger<BoilerReplayRunner>>(),
provider.GetRequiredService<IOptions<ReplayOptions>>(),
provider.GetRequiredService<IOptions<BoilerMonitorOptions>>()));
}
if (replayOptions.Monitors.Shower)
{
runners.Add(new ShowerReplayRunner(
timeline, replayTimeProvider, replayTimeline,
provider.GetRequiredService<IShowerDetectionService>(),
fanControlService,
provider.GetRequiredService<ILogger<ShowerReplayRunner>>(),
provider.GetRequiredService<IOptions<ReplayOptions>>(),
provider.GetRequiredService<IOptions<ShowerMonitorOptions>>()));
}
if (replayOptions.Monitors.Power)
{
runners.Add(new PowerReplayRunner(
timeline, replayTimeProvider, replayTimeline,
provider.GetRequiredService<IOtherPowerCalculationService>(),
provider.GetRequiredService<IPowerCostCalculationService>(),
provider.GetRequiredService<ILogger<PowerReplayRunner>>(),
provider.GetRequiredService<IOptions<ReplayOptions>>(),
provider.GetRequiredService<IOptions<PowerMonitorOptions>>()));
}
if (replayOptions.Monitors.Light)
{
runners.Add(new LightReplayRunner(
timeline, replayTimeProvider, replayTimeline,
provider.GetRequiredService<ILogger<LightReplayRunner>>(),
provider.GetRequiredService<IOptions<ReplayOptions>>(),
provider.GetRequiredService<IOptions<LightMonitorOptions>>()));
}
logger.LogInformation("Running {Count} monitor replay(s) in parallel...", runners.Count);
var replayTasks = runners.Select(r => Task.Run(() => r.RunAsync()));
await Task.WhenAll(replayTasks);
var renderer = provider.GetRequiredService<ConsoleReportRenderer>();
renderer.Render(replayTimeline, replayOptions);
}
catch (Exception ex)
{
Log.Fatal(ex, "History replay failed");
}
finally
{
await Log.CloseAndFlushAsync();
}
@@ -1,38 +0,0 @@
using HomeAssistant.Entities.Interfaces;
using HomeAssistant.Models;
using Microsoft.Extensions.Logging;
namespace HomeAssistant.HistoryReplay.Replay;
public sealed class NoOpEntityManager(ILogger<NoOpEntityManager> logger) : IEntityManager
{
public Task CreateEntitiesAsync(ICollection<EntityCreateModel> entities)
{
logger.LogDebug("[REPLAY] Would create {Count} entities", entities.Count);
return Task.CompletedTask;
}
public Task CreateEntityAsync(EntityCreateModel createModel)
{
logger.LogDebug("[REPLAY] Would create entity: {EntityId}", createModel.EntityId);
return Task.CompletedTask;
}
public Task SetEntityState(string entityId, string state)
{
logger.LogDebug("[REPLAY] Would set state for {EntityId}: {State}", entityId, state);
return Task.CompletedTask;
}
public Task SetEntityAttributes(string entityId, object attributes)
{
logger.LogDebug("[REPLAY] Would set attributes for {EntityId}", entityId);
return Task.CompletedTask;
}
public Task RemoveEntity(string entityId)
{
logger.LogDebug("[REPLAY] Would remove entity: {EntityId}", entityId);
return Task.CompletedTask;
}
}
@@ -1,98 +0,0 @@
using System.Reactive.Linq;
using System.Text.Json;
using HomeAssistant.HistoryReplay.HistoryData;
using HomeAssistant.HistoryReplay.Reporting;
using Microsoft.Extensions.Logging;
using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
namespace HomeAssistant.HistoryReplay.Replay;
public sealed class ReplayHaContext : IHaContext
{
private readonly HistoryTimeline _timeline;
private readonly ReplayTimeProvider _timeProvider;
private readonly ReplayTimeline _replayTimeline;
private readonly ILogger<ReplayHaContext> _logger;
public ReplayHaContext(
HistoryTimeline timeline,
ReplayTimeProvider timeProvider,
ReplayTimeline replayTimeline,
ILogger<ReplayHaContext> logger)
{
_timeline = timeline;
_timeProvider = timeProvider;
_replayTimeline = replayTimeline;
_logger = logger;
}
public EntityState? GetState(string entityId)
{
var currentTime = _timeProvider.GetUtcNow();
var entry = _timeline.GetStateAt(entityId, currentTime);
if (entry is null)
{
return null;
}
JsonElement? attributesJson = null;
if (entry.Attributes is { Count: > 0 })
{
attributesJson = JsonSerializer.SerializeToElement(entry.Attributes);
}
return new EntityState
{
State = entry.State,
AttributesJson = attributesJson
};
}
public IReadOnlyList<Entity> GetAllEntities()
{
return _timeline.GetEntityIds()
.Select(id => new Entity(this, id))
.ToList();
}
public void CallService(string domain, string service, ServiceTarget? target = null, object? data = null)
{
var currentTime = _timeProvider.GetUtcNow();
var targetDescription = target?.EntityIds is not null
? string.Join(", ", target.EntityIds)
: "no target";
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = currentTime,
Monitor = "ServiceCall",
EventType = ReplayEventType.ServiceCall,
Message = $"Would call {domain}.{service} on {targetDescription}",
Details = data is not null ? JsonSerializer.Serialize(data) : null
});
_logger.LogDebug("[REPLAY] {Domain}.{Service} → {Target}", domain, service, targetDescription);
}
public void SendEvent(string eventType, object? data = null)
{
_logger.LogDebug("[REPLAY] Would send event: {EventType}", eventType);
}
public IObservable<StateChange> StateAllChanges() => Observable.Empty<StateChange>();
public IObservable<Event> Events => Observable.Empty<Event>();
public Task<JsonElement?> CallServiceWithResponseAsync(
string domain, string service, ServiceTarget? target = null, object? data = null)
{
CallService(domain, service, target, data);
return Task.FromResult<JsonElement?>(null);
}
public Area? GetAreaFromEntityId(string entityId) => null;
public EntityRegistration? GetEntityRegistration(string entityId) => null;
}
@@ -1,40 +0,0 @@
namespace HomeAssistant.HistoryReplay.Replay;
public sealed class ReplayTimeProvider : TimeProvider
{
private readonly Lock _lock = new();
private DateTimeOffset _currentUtcTime;
private readonly TimeZoneInfo _localTimeZone;
public ReplayTimeProvider(DateTimeOffset initialTime)
{
_currentUtcTime = initialTime.ToUniversalTime();
_localTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
}
public override DateTimeOffset GetUtcNow()
{
lock (_lock)
{
return _currentUtcTime;
}
}
public override TimeZoneInfo LocalTimeZone => _localTimeZone;
public void AdvanceTo(DateTimeOffset utcTime)
{
lock (_lock)
{
_currentUtcTime = utcTime.ToUniversalTime();
}
}
public void AdvanceBy(TimeSpan duration)
{
lock (_lock)
{
_currentUtcTime += duration;
}
}
}
@@ -1,146 +0,0 @@
using HomeAssistant.HistoryReplay.Configuration;
namespace HomeAssistant.HistoryReplay.Reporting;
public sealed class ConsoleReportRenderer
{
private const string Separator = "═══════════════════════════════════════════════════════════";
private const string SectionSeparator = "── {0} ──────────────────────────────────────────────";
private const string TimeFormat = "HH:mm:ss";
public void Render(ReplayTimeline timeline, ReplayOptions options)
{
Console.WriteLine();
WriteColored(Separator, ConsoleColor.DarkCyan);
WriteColored($" REPLAY: {options.StartTime:yyyy-MM-dd HH:mm} → {options.EndTime:yyyy-MM-dd HH:mm}", ConsoleColor.White);
WriteColored(Separator, ConsoleColor.DarkCyan);
Console.WriteLine();
var monitors = timeline.GetMonitors()
.Where(m => !string.Equals(m, "ServiceCall", StringComparison.OrdinalIgnoreCase))
.ToList();
foreach (var monitor in monitors)
{
RenderMonitorSection(monitor, timeline.GetEventsByMonitor(monitor));
}
RenderServiceCallSection(timeline.GetEventsByMonitor("ServiceCall"));
RenderSummary(timeline);
}
private static void RenderMonitorSection(string monitor, IReadOnlyList<ReplayEvent> events)
{
Console.WriteLine();
WriteColored(string.Format(SectionSeparator, monitor), ConsoleColor.Yellow);
if (events.Count == 0)
{
WriteColored(" No events recorded", ConsoleColor.DarkGray);
return;
}
foreach (var evt in events)
{
var color = GetEventColor(evt.EventType);
var prefix = GetEventPrefix(evt.EventType);
var timestamp = evt.Timestamp.ToLocalTime().ToString(TimeFormat);
WriteColored($" {timestamp} {prefix}{evt.Message}", color);
if (!string.IsNullOrEmpty(evt.Details))
{
WriteColored($" {evt.Details}", ConsoleColor.DarkGray);
}
}
WriteSectionSummary(events);
}
private static void RenderServiceCallSection(IReadOnlyList<ReplayEvent> events)
{
if (events.Count == 0)
{
return;
}
Console.WriteLine();
WriteColored(string.Format(SectionSeparator, "Service Calls"), ConsoleColor.Magenta);
foreach (var evt in events)
{
var timestamp = evt.Timestamp.ToLocalTime().ToString(TimeFormat);
WriteColored($" {timestamp} → {evt.Message}", ConsoleColor.DarkMagenta);
}
WriteColored($"\n Total: {events.Count} service call(s) would have been made", ConsoleColor.DarkGray);
}
private static void RenderSummary(ReplayTimeline timeline)
{
var allEvents = timeline.GetAllEvents();
Console.WriteLine();
WriteColored(Separator, ConsoleColor.DarkCyan);
WriteColored(" REPLAY SUMMARY", ConsoleColor.White);
WriteColored(Separator, ConsoleColor.DarkCyan);
var decisions = allEvents.Count(e => e.EventType == ReplayEventType.Decision);
var serviceCalls = allEvents.Count(e => e.EventType == ReplayEventType.ServiceCall);
var warnings = allEvents.Count(e => e.EventType == ReplayEventType.Warning);
var anomalies = allEvents.Count(e => e.EventType == ReplayEventType.Anomaly);
WriteColored($" Total events: {allEvents.Count}", ConsoleColor.Gray);
WriteColored($" Decisions: {decisions}", ConsoleColor.Cyan);
WriteColored($" Service calls: {serviceCalls}", ConsoleColor.Magenta);
WriteColored($" Warnings: {warnings}", ConsoleColor.DarkYellow);
WriteColored($" Anomalies: {anomalies}", ConsoleColor.Red);
Console.WriteLine();
}
private static void WriteSectionSummary(IReadOnlyList<ReplayEvent> events)
{
var decisions = events.Count(e => e.EventType == ReplayEventType.Decision);
var warnings = events.Count(e => e.EventType == ReplayEventType.Warning);
var stateChanges = events.Count(e => e.EventType == ReplayEventType.StateChange);
var parts = new List<string>();
if (decisions > 0) parts.Add($"{decisions} decision(s)");
if (stateChanges > 0) parts.Add($"{stateChanges} state change(s)");
if (warnings > 0) parts.Add($"{warnings} warning(s)");
if (parts.Count > 0)
{
WriteColored($"\n Summary: {string.Join(", ", parts)}", ConsoleColor.DarkGray);
}
}
private static ConsoleColor GetEventColor(ReplayEventType eventType) =>
eventType switch
{
ReplayEventType.Decision => ConsoleColor.Green,
ReplayEventType.StateChange => ConsoleColor.Cyan,
ReplayEventType.Warning => ConsoleColor.DarkYellow,
ReplayEventType.ServiceCall => ConsoleColor.Magenta,
ReplayEventType.Anomaly => ConsoleColor.Red,
_ => ConsoleColor.Gray
};
private static string GetEventPrefix(ReplayEventType eventType) =>
eventType switch
{
ReplayEventType.Decision => "→ ",
ReplayEventType.Warning => "⚠ ",
ReplayEventType.Anomaly => "⚠ ANOMALY: ",
ReplayEventType.ServiceCall => "⤷ ",
_ => ""
};
private static void WriteColored(string text, ConsoleColor color)
{
var previousColor = Console.ForegroundColor;
Console.ForegroundColor = color;
Console.WriteLine(text);
Console.ForegroundColor = previousColor;
}
}
@@ -1,20 +0,0 @@
namespace HomeAssistant.HistoryReplay.Reporting;
public sealed class ReplayEvent
{
public required DateTimeOffset Timestamp { get; init; }
public required string Monitor { get; init; }
public required ReplayEventType EventType { get; init; }
public required string Message { get; init; }
public string? Details { get; init; }
}
public enum ReplayEventType
{
Info,
Decision,
StateChange,
Warning,
ServiceCall,
Anomaly
}
@@ -1,25 +0,0 @@
using System.Collections.Concurrent;
namespace HomeAssistant.HistoryReplay.Reporting;
public sealed class ReplayTimeline
{
private readonly ConcurrentBag<ReplayEvent> _events = [];
public void AddEvent(ReplayEvent replayEvent)
{
_events.Add(replayEvent);
}
public IReadOnlyList<ReplayEvent> GetEventsByMonitor(string monitor) =>
_events
.Where(e => string.Equals(e.Monitor, monitor, StringComparison.OrdinalIgnoreCase))
.OrderBy(e => e.Timestamp)
.ToList();
public IReadOnlyList<ReplayEvent> GetAllEvents() =>
_events.OrderBy(e => e.Timestamp).ToList();
public IReadOnlyList<string> GetMonitors() =>
_events.Select(e => e.Monitor).Distinct(StringComparer.OrdinalIgnoreCase).Order().ToList();
}
@@ -1,210 +0,0 @@
using System.Globalization;
using BoilerMonitor.Models;
using BoilerMonitor.Models.Enums;
using BoilerMonitorManager.Interface;
using HomeAssistant.HistoryReplay.Configuration;
using HomeAssistant.HistoryReplay.HistoryData;
using HomeAssistant.HistoryReplay.Replay;
using HomeAssistant.HistoryReplay.Reporting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using BoilerMonitorManager.Models;
namespace HomeAssistant.HistoryReplay.Runners;
public sealed class BoilerReplayRunner : IMonitorReplayRunner
{
private readonly HistoryTimeline _timeline;
private readonly ReplayTimeProvider _timeProvider;
private readonly ReplayTimeline _replayTimeline;
private readonly IBoilerControlService _boilerControlService;
private readonly IBoilerRunTimeTracker _tracker;
private readonly IWaterReadyService _waterReadyService;
private readonly ILogger<BoilerReplayRunner> _logger;
private readonly ReplayOptions _replayOptions;
private readonly BoilerMonitorOptions _boilerOptions;
public string MonitorName => "Boiler";
public BoilerReplayRunner(
HistoryTimeline timeline,
ReplayTimeProvider timeProvider,
ReplayTimeline replayTimeline,
IBoilerControlService boilerControlService,
IBoilerRunTimeTracker tracker,
IWaterReadyService waterReadyService,
ILogger<BoilerReplayRunner> logger,
IOptions<ReplayOptions> replayOptions,
IOptions<BoilerMonitorOptions> boilerOptions)
{
_timeline = timeline;
_timeProvider = timeProvider;
_replayTimeline = replayTimeline;
_boilerControlService = boilerControlService;
_tracker = tracker;
_waterReadyService = waterReadyService;
_logger = logger;
_replayOptions = replayOptions.Value;
_boilerOptions = boilerOptions.Value;
}
public Task RunAsync(CancellationToken cancellationToken = default)
{
_logger.LogInformation("Starting Boiler replay");
var currentTime = _replayOptions.StartTime;
var pollInterval = TimeSpan.FromSeconds(BoilerMonitorConsts.DefaultPollIntervalSeconds);
var heatingThreshold = BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts;
BoilerAction? lastAction = null;
var lastWaterReady = false;
var boilerPowerEntityId = ReadConfigEntityState(
BoilerMonitorConsts.ConfigPowerEntityId, _replayOptions.StartTime);
var boilerSwitchEntityId = ReadConfigEntityState(
BoilerMonitorConsts.ConfigSwitchEntityId, _replayOptions.StartTime);
if (string.IsNullOrEmpty(boilerPowerEntityId) || string.IsNullOrEmpty(boilerSwitchEntityId))
{
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = currentTime,
Monitor = MonitorName,
EventType = ReplayEventType.Warning,
Message = "Boiler not configured (missing power/switch entity IDs), skipping replay"
});
return Task.CompletedTask;
}
var configThresholdState = ReadConfigEntityState(
BoilerMonitorConsts.ConfigHeatingThresholdEntityId, _replayOptions.StartTime);
if (!string.IsNullOrEmpty(configThresholdState) &&
double.TryParse(configThresholdState, CultureInfo.InvariantCulture, out var configuredThreshold))
{
heatingThreshold = configuredThreshold;
}
while (currentTime <= _replayOptions.EndTime && !cancellationToken.IsCancellationRequested)
{
_timeProvider.AdvanceTo(currentTime);
var powerEntry = _timeline.GetStateAt(boilerPowerEntityId, currentTime);
var switchEntry = _timeline.GetStateAt(boilerSwitchEntityId, currentTime);
var cheapEntry = _timeline.GetStateAt("sensor.nordpool_cheapest_intervals", currentTime);
var skipPriceCapEntry = _timeline.GetStateAt(BoilerMonitorConsts.SkipPriceCapEntityId, currentTime);
var budgetOverrideEntry = _timeline.GetStateAt(BoilerMonitorConsts.BudgetOverrideEntityId, currentTime);
var dailyHoursEntry = _timeline.GetStateAt(BoilerMonitorConsts.BoilerDailyHoursEntityId, currentTime);
var boilerPowerWatts = ParseDouble(powerEntry?.State);
var boilerSwitchState = switchEntry?.State;
var isHeating = boilerPowerWatts.HasValue && boilerPowerWatts.Value >= heatingThreshold;
_tracker.RecordPollResult(isHeating, pollInterval);
var isNowCheap = ReadAttributeBool(cheapEntry, "is_now_cheap");
var skipPriceCap = string.Equals(skipPriceCapEntry?.State, "on", StringComparison.OrdinalIgnoreCase);
var budgetOverride = string.Equals(budgetOverrideEntry?.State, "on", StringComparison.OrdinalIgnoreCase);
var dailyHours = ParseDouble(dailyHoursEntry?.State) ?? 1.0;
var waterReady = _waterReadyService.IsWaterReady(boilerSwitchState, boilerPowerWatts, heatingThreshold);
if (!lastWaterReady && waterReady)
{
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = currentTime,
Monitor = MonitorName,
EventType = ReplayEventType.StateChange,
Message = $"Water ready detected (power: {boilerPowerWatts:F1}W, threshold: {heatingThreshold}W)"
});
}
lastWaterReady = waterReady;
var snapshot = _tracker.GetSnapshot();
var budgetTimeSpan = TimeSpan.FromHours(dailyHours);
var budgetExhausted = snapshot.AccumulatedRunTime >= budgetTimeSpan;
var budgetPercentage = budgetTimeSpan.TotalSeconds > 0
? (snapshot.AccumulatedRunTime.TotalSeconds / budgetTimeSpan.TotalSeconds) * 100.0
: 0.0;
var effectiveIsNowCheap = isNowCheap || skipPriceCap;
var action = _boilerControlService.DetermineAction(
effectiveIsNowCheap, waterReady, boilerSwitchState, budgetExhausted, budgetOverride);
if (action != BoilerAction.NoChange && action != lastAction)
{
var actionMessage = action switch
{
BoilerAction.TurnOn => $"TURN ON (cheap: {effectiveIsNowCheap}, water ready: {waterReady}, budget: {budgetPercentage:F0}%)",
BoilerAction.TurnOff => $"TURN OFF (cheap: {effectiveIsNowCheap}, water ready: {waterReady}, budget: {budgetPercentage:F0}%)",
_ => action.ToString()
};
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = currentTime,
Monitor = MonitorName,
EventType = ReplayEventType.Decision,
Message = actionMessage,
Details = $"Power: {boilerPowerWatts:F1}W, Runtime: {snapshot.AccumulatedRunTime:hh\\:mm\\:ss}, Sessions: {snapshot.SessionCount}"
});
if (action == BoilerAction.TurnOn)
{
_waterReadyService.NotifyTurnedOn();
}
}
lastAction = action;
currentTime = currentTime.Add(pollInterval);
}
var finalSnapshot = _tracker.GetSnapshot();
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = _replayOptions.EndTime,
Monitor = MonitorName,
EventType = ReplayEventType.Info,
Message = $"Final: {finalSnapshot.AccumulatedRunTime:hh\\:mm\\:ss} total runtime, {finalSnapshot.SessionCount} session(s)"
});
_logger.LogInformation("Boiler replay complete");
return Task.CompletedTask;
}
private string? ReadConfigEntityState(string entityId, DateTimeOffset timestamp)
{
var entry = _timeline.GetStateAt(entityId, timestamp);
return entry?.State;
}
private static bool ReadAttributeBool(HistoryStateEntry? entry, string attributeName)
{
if (entry?.Attributes is null)
{
return false;
}
if (!entry.Attributes.TryGetValue(attributeName, out var value))
{
return false;
}
return value switch
{
bool b => b,
string s => bool.TryParse(s, out var parsed) && parsed,
double d => d != 0,
_ => false
};
}
private static double? ParseDouble(string? value)
{
if (value is null or "unavailable" or "unknown")
{
return null;
}
return double.TryParse(value, CultureInfo.InvariantCulture, out var result) ? result : null;
}
}
@@ -1,7 +0,0 @@
namespace HomeAssistant.HistoryReplay.Runners;
public interface IMonitorReplayRunner
{
string MonitorName { get; }
Task RunAsync(CancellationToken cancellationToken = default);
}
@@ -1,175 +0,0 @@
using HomeAssistant.HistoryReplay.Configuration;
using HomeAssistant.HistoryReplay.HistoryData;
using HomeAssistant.HistoryReplay.Replay;
using HomeAssistant.HistoryReplay.Reporting;
using LightMonitor.Models;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using LightMonitorManager.Models;
namespace HomeAssistant.HistoryReplay.Runners;
public sealed class LightReplayRunner : IMonitorReplayRunner
{
private readonly HistoryTimeline _timeline;
private readonly ReplayTimeProvider _timeProvider;
private readonly ReplayTimeline _replayTimeline;
private readonly ILogger<LightReplayRunner> _logger;
private readonly ReplayOptions _replayOptions;
private readonly LightMonitorOptions _lightOptions;
public string MonitorName => "Light";
public LightReplayRunner(
HistoryTimeline timeline,
ReplayTimeProvider timeProvider,
ReplayTimeline replayTimeline,
ILogger<LightReplayRunner> logger,
IOptions<ReplayOptions> replayOptions,
IOptions<LightMonitorOptions> lightOptions)
{
_timeline = timeline;
_timeProvider = timeProvider;
_replayTimeline = replayTimeline;
_logger = logger;
_replayOptions = replayOptions.Value;
_lightOptions = lightOptions.Value;
}
public Task RunAsync(CancellationToken cancellationToken = default)
{
_logger.LogInformation("Starting Light replay");
ReplaySunEvents(cancellationToken);
ReplayPersonArrivals(cancellationToken);
_logger.LogInformation("Light replay complete");
return Task.CompletedTask;
}
private void ReplaySunEvents(CancellationToken cancellationToken)
{
var sunHistory = _timeline.GetEntityHistory(_lightOptions.SunEntityId);
string? previousSunState = null;
foreach (var entry in sunHistory)
{
if (cancellationToken.IsCancellationRequested) break;
if (entry.LastChanged < _replayOptions.StartTime || entry.LastChanged > _replayOptions.EndTime)
{
continue;
}
if (string.Equals(entry.State, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase) &&
!string.Equals(previousSunState, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase))
{
_timeProvider.AdvanceTo(entry.LastChanged);
var anyoneHome = IsAnyoneHome(entry.LastChanged);
var lightState = _timeline.GetStateAt(_lightOptions.LightEntityId, entry.LastChanged)?.State;
var lightAlreadyOn = string.Equals(lightState, LightMonitorConsts.LightOnState, StringComparison.OrdinalIgnoreCase);
if (anyoneHome && !lightAlreadyOn)
{
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = entry.LastChanged,
Monitor = MonitorName,
EventType = ReplayEventType.Decision,
Message = "TURN ON light (sun below horizon + someone home)"
});
}
else if (!anyoneHome)
{
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = entry.LastChanged,
Monitor = MonitorName,
EventType = ReplayEventType.Info,
Message = "Sun below horizon but nobody home — light stays off"
});
}
else
{
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = entry.LastChanged,
Monitor = MonitorName,
EventType = ReplayEventType.Info,
Message = "Sun below horizon but light already on"
});
}
}
previousSunState = entry.State;
}
}
private void ReplayPersonArrivals(CancellationToken cancellationToken)
{
foreach (var personEntityId in _lightOptions.PersonEntityIds)
{
var personHistory = _timeline.GetEntityHistory(personEntityId);
string? previousState = null;
foreach (var entry in personHistory)
{
if (cancellationToken.IsCancellationRequested) break;
if (entry.LastChanged < _replayOptions.StartTime || entry.LastChanged > _replayOptions.EndTime)
{
continue;
}
if (string.Equals(entry.State, LightMonitorConsts.PersonHomeState, StringComparison.OrdinalIgnoreCase) &&
!string.Equals(previousState, LightMonitorConsts.PersonHomeState, StringComparison.OrdinalIgnoreCase))
{
_timeProvider.AdvanceTo(entry.LastChanged);
var sunEntry = _timeline.GetStateAt(_lightOptions.SunEntityId, entry.LastChanged);
var isDark = string.Equals(sunEntry?.State, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase);
var lightState = _timeline.GetStateAt(_lightOptions.LightEntityId, entry.LastChanged)?.State;
var lightAlreadyOn = string.Equals(lightState, LightMonitorConsts.LightOnState, StringComparison.OrdinalIgnoreCase);
if (isDark && !lightAlreadyOn)
{
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = entry.LastChanged,
Monitor = MonitorName,
EventType = ReplayEventType.Decision,
Message = $"TURN ON light ({personEntityId} arrived home + dark outside)"
});
}
else if (isDark)
{
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = entry.LastChanged,
Monitor = MonitorName,
EventType = ReplayEventType.Info,
Message = $"{personEntityId} arrived home (dark) but light already on"
});
}
}
previousState = entry.State;
}
}
}
private bool IsAnyoneHome(DateTimeOffset timestamp)
{
foreach (var personEntityId in _lightOptions.PersonEntityIds)
{
var entry = _timeline.GetStateAt(personEntityId, timestamp);
if (string.Equals(entry?.State, LightMonitorConsts.PersonHomeState, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
}
@@ -1,171 +0,0 @@
using System.Globalization;
using BoilerMonitor.Models;
using HomeAssistant.HistoryReplay.Configuration;
using HomeAssistant.HistoryReplay.HistoryData;
using HomeAssistant.HistoryReplay.Replay;
using HomeAssistant.HistoryReplay.Reporting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NordPool.Models;
using NordPoolManager.Interface;
namespace HomeAssistant.HistoryReplay.Runners;
public sealed class NordPoolReplayRunner : IMonitorReplayRunner
{
private readonly HistoryTimeline _timeline;
private readonly ReplayTimeProvider _timeProvider;
private readonly ReplayTimeline _replayTimeline;
private readonly ICheapestIntervalsFinder _cheapestIntervalsFinder;
private readonly ILogger<NordPoolReplayRunner> _logger;
private readonly ReplayOptions _options;
public string MonitorName => "NordPool";
public NordPoolReplayRunner(
HistoryTimeline timeline,
ReplayTimeProvider timeProvider,
ReplayTimeline replayTimeline,
ICheapestIntervalsFinder cheapestIntervalsFinder,
ILogger<NordPoolReplayRunner> logger,
IOptions<ReplayOptions> options)
{
_timeline = timeline;
_timeProvider = timeProvider;
_replayTimeline = replayTimeline;
_cheapestIntervalsFinder = cheapestIntervalsFinder;
_logger = logger;
_options = options.Value;
}
public Task RunAsync(CancellationToken cancellationToken = default)
{
_logger.LogInformation("Starting NordPool replay");
var currentTime = _options.StartTime;
var interval = TimeSpan.FromMinutes(NordPoolConsts.MinutesPerInterval);
double? lastReportedPrice = null;
while (currentTime <= _options.EndTime && !cancellationToken.IsCancellationRequested)
{
_timeProvider.AdvanceTo(currentTime);
var priceEntry = _timeline.GetStateAt(NordPoolConsts.CurrentPriceEntityId, currentTime);
if (priceEntry?.State is not null &&
double.TryParse(priceEntry.State, CultureInfo.InvariantCulture, out var currentPrice))
{
if (lastReportedPrice is null || Math.Abs(currentPrice - lastReportedPrice.Value) > 0.001)
{
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = currentTime,
Monitor = MonitorName,
EventType = ReplayEventType.Info,
Message = $"Price: {currentPrice:F2} ct/kWh"
});
lastReportedPrice = currentPrice;
}
}
var boilerConfig = ReadBoilerConfig(currentTime);
if (boilerConfig is not null)
{
var prices = BuildNordPoolPriceFromHistory(currentTime);
if (prices.Prices is { Count: > 0 })
{
var effectivePriceCap = boilerConfig.SkipPriceCap ? double.MaxValue : boilerConfig.PriceCap;
var effectiveIntervalCount = boilerConfig.SkipPriceCap
? NordPoolConsts.MaxDailyIntervals
: boilerConfig.IntervalCount;
var cheapest = _cheapestIntervalsFinder.FindCheapestIntervals(
prices, effectiveIntervalCount, effectivePriceCap, boilerConfig.Deadline);
var isNowCheap = _cheapestIntervalsFinder.IsCurrentIntervalCheap(
cheapest, currentTime.LocalDateTime);
if (isNowCheap)
{
var currentInterval = cheapest.FirstOrDefault(i =>
currentTime.LocalDateTime >= i.Start && currentTime.LocalDateTime < i.End);
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = currentTime,
Monitor = MonitorName,
EventType = ReplayEventType.Decision,
Message = $"CHEAP interval active (rank #{currentInterval?.Rank}, price: {currentInterval?.Price:F2} ct/kWh)",
Details = $"Total cheap intervals: {cheapest.Count}"
});
}
}
}
currentTime = currentTime.Add(interval);
}
_logger.LogInformation("NordPool replay complete");
return Task.CompletedTask;
}
private BoilerConfig? ReadBoilerConfig(DateTimeOffset timestamp)
{
var dailyHoursEntry = _timeline.GetStateAt(BoilerMonitorConsts.BoilerDailyHoursEntityId, timestamp);
var priceCapEntry = _timeline.GetStateAt(BoilerMonitorConsts.BoilerPriceCapEntityId, timestamp);
var readyByEntry = _timeline.GetStateAt(BoilerMonitorConsts.BoilerReadyByEntityId, timestamp);
var skipPriceCapEntry = _timeline.GetStateAt(BoilerMonitorConsts.SkipPriceCapEntityId, timestamp);
if (dailyHoursEntry?.State is null || priceCapEntry?.State is null || readyByEntry?.State is null)
{
return null;
}
if (!double.TryParse(dailyHoursEntry.State, CultureInfo.InvariantCulture, out var dailyHours) ||
!double.TryParse(priceCapEntry.State, CultureInfo.InvariantCulture, out var priceCap))
{
return null;
}
var intervalCount = (int)(dailyHours * NordPoolConsts.IntervalsPerHour);
if (!TimeSpan.TryParse(readyByEntry.State, CultureInfo.InvariantCulture, out var readyByTime))
{
return null;
}
var deadline = timestamp.LocalDateTime.Date.Add(readyByTime);
if (deadline < timestamp.LocalDateTime)
{
deadline = deadline.AddDays(1);
}
var skipPriceCap = string.Equals(skipPriceCapEntry?.State, "on", StringComparison.OrdinalIgnoreCase);
return new BoilerConfig
{
IntervalCount = intervalCount,
PriceCap = priceCap,
Deadline = deadline,
SkipPriceCap = skipPriceCap
};
}
private NordPoolPrice BuildNordPoolPriceFromHistory(DateTimeOffset timestamp)
{
var nordPoolSensorEntries = _timeline.GetEntityHistory("sensor.nordpool_kwh_lt_eur_3_10_0");
var todayDate = timestamp.LocalDateTime.Date;
var todayPrices = nordPoolSensorEntries
.Where(e => e.LastChanged.LocalDateTime.Date == todayDate)
.Where(e => e.State is not null && double.TryParse(e.State, CultureInfo.InvariantCulture, out _))
.Select(e => new NordPoolDayPrice
{
Start = e.LastChanged.LocalDateTime,
End = e.LastChanged.LocalDateTime.AddMinutes(NordPoolConsts.MinutesPerInterval),
Price = double.Parse(e.State!, CultureInfo.InvariantCulture)
})
.ToList();
return new NordPoolPrice { Prices = todayPrices };
}
}
@@ -1,158 +0,0 @@
using System.Globalization;
using HomeAssistant.HistoryReplay.Configuration;
using HomeAssistant.HistoryReplay.HistoryData;
using HomeAssistant.HistoryReplay.Replay;
using HomeAssistant.HistoryReplay.Reporting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NordPool.Models;
using PowerMonitorManager.Interface;
using PowerMonitorManager.Models;
using PowerMonitorManager.Models.Consts;
namespace HomeAssistant.HistoryReplay.Runners;
public sealed class PowerReplayRunner : IMonitorReplayRunner
{
private readonly HistoryTimeline _timeline;
private readonly ReplayTimeProvider _timeProvider;
private readonly ReplayTimeline _replayTimeline;
private readonly IOtherPowerCalculationService _calculationService;
private readonly IPowerCostCalculationService _costService;
private readonly ILogger<PowerReplayRunner> _logger;
private readonly ReplayOptions _replayOptions;
private readonly PowerMonitorOptions _powerOptions;
public string MonitorName => "Power";
public PowerReplayRunner(
HistoryTimeline timeline,
ReplayTimeProvider timeProvider,
ReplayTimeline replayTimeline,
IOtherPowerCalculationService calculationService,
IPowerCostCalculationService costService,
ILogger<PowerReplayRunner> logger,
IOptions<ReplayOptions> replayOptions,
IOptions<PowerMonitorOptions> powerOptions)
{
_timeline = timeline;
_timeProvider = timeProvider;
_replayTimeline = replayTimeline;
_calculationService = calculationService;
_costService = costService;
_logger = logger;
_replayOptions = replayOptions.Value;
_powerOptions = powerOptions.Value;
}
public Task RunAsync(CancellationToken cancellationToken = default)
{
_logger.LogInformation("Starting Power replay");
var currentTime = _replayOptions.StartTime;
var pollInterval = TimeSpan.FromSeconds(_powerOptions.PollIntervalSeconds);
DateTime? anomalyStartTime = null;
while (currentTime <= _replayOptions.EndTime && !cancellationToken.IsCancellationRequested)
{
_timeProvider.AdvanceTo(currentTime);
var mainMeterEntry = _timeline.GetStateAt(_powerOptions.MainMeterEntityId, currentTime);
var totalPower = ParseDouble(mainMeterEntry?.State);
if (!totalPower.HasValue)
{
currentTime = currentTime.Add(pollInterval);
continue;
}
var deviceReadings = DiscoverAndReadDevicePower(currentTime);
var calculation = _calculationService.Calculate(totalPower.Value, deviceReadings);
var nordPoolPriceEntry = _timeline.GetStateAt(NordPoolConsts.CurrentPriceEntityId, currentTime);
var nordPoolPrice = ParseDouble(nordPoolPriceEntry?.State) ?? 0;
_costService.RecordCosts(calculation, nordPoolPrice, _powerOptions.PollIntervalSeconds, currentTime.LocalDateTime);
var isAnomaly = calculation.SmoothedOtherPowerWatts > _powerOptions.AnomalyThresholdWatts;
if (isAnomaly && anomalyStartTime is null)
{
anomalyStartTime = currentTime.LocalDateTime;
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = currentTime,
Monitor = MonitorName,
EventType = ReplayEventType.Anomaly,
Message = $"Other power {calculation.SmoothedOtherPowerWatts:F0}W exceeds threshold {_powerOptions.AnomalyThresholdWatts}W",
Details = $"Total: {calculation.TotalPowerWatts:F0}W, Known: {calculation.KnownDevicesSumWatts:F0}W"
});
}
else if (!isAnomaly && anomalyStartTime is not null)
{
var duration = currentTime.LocalDateTime - anomalyStartTime.Value;
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = currentTime,
Monitor = MonitorName,
EventType = ReplayEventType.Info,
Message = $"Anomaly resolved after {duration:mm\\:ss}"
});
anomalyStartTime = null;
}
currentTime = currentTime.Add(pollInterval);
}
var totalCost = _costService.GetTotalCostSnapshot();
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = _replayOptions.EndTime,
Monitor = MonitorName,
EventType = ReplayEventType.Info,
Message = $"Final: Total daily cost {totalCost.CostDaily:F4} EUR"
});
_logger.LogInformation("Power replay complete");
return Task.CompletedTask;
}
private IReadOnlyDictionary<string, double> DiscoverAndReadDevicePower(DateTimeOffset timestamp)
{
var readings = new Dictionary<string, double>();
var allEntities = _timeline.GetEntityIds();
foreach (var entityId in allEntities)
{
if (!entityId.StartsWith("sensor.", StringComparison.OrdinalIgnoreCase) ||
!entityId.EndsWith("_power", StringComparison.OrdinalIgnoreCase))
{
continue;
}
if (string.Equals(entityId, _powerOptions.MainMeterEntityId, StringComparison.OrdinalIgnoreCase))
{
continue;
}
var entry = _timeline.GetStateAt(entityId, timestamp);
var value = ParseDouble(entry?.State);
if (value.HasValue)
{
readings[entityId] = value.Value;
}
}
return readings;
}
private static double? ParseDouble(string? value)
{
if (value is null or "unavailable" or "unknown")
{
return null;
}
return double.TryParse(value, CultureInfo.InvariantCulture, out var result) ? result : null;
}
}
@@ -1,126 +0,0 @@
using System.Globalization;
using HomeAssistant.HistoryReplay.Configuration;
using HomeAssistant.HistoryReplay.HistoryData;
using HomeAssistant.HistoryReplay.Replay;
using HomeAssistant.HistoryReplay.Reporting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using ShowerMonitor.Models.Enums;
using ShowerMonitorManager.Interface;
using ShowerMonitorManager.Models;
namespace HomeAssistant.HistoryReplay.Runners;
public sealed class ShowerReplayRunner : IMonitorReplayRunner
{
private readonly HistoryTimeline _timeline;
private readonly ReplayTimeProvider _timeProvider;
private readonly ReplayTimeline _replayTimeline;
private readonly IShowerDetectionService _detectionService;
private readonly IExhaustFanControlService _fanControlService;
private readonly ILogger<ShowerReplayRunner> _logger;
private readonly ReplayOptions _replayOptions;
private readonly ShowerMonitorOptions _showerOptions;
public string MonitorName => "Shower";
public ShowerReplayRunner(
HistoryTimeline timeline,
ReplayTimeProvider timeProvider,
ReplayTimeline replayTimeline,
IShowerDetectionService detectionService,
IExhaustFanControlService fanControlService,
ILogger<ShowerReplayRunner> logger,
IOptions<ReplayOptions> replayOptions,
IOptions<ShowerMonitorOptions> showerOptions)
{
_timeline = timeline;
_timeProvider = timeProvider;
_replayTimeline = replayTimeline;
_detectionService = detectionService;
_fanControlService = fanControlService;
_logger = logger;
_replayOptions = replayOptions.Value;
_showerOptions = showerOptions.Value;
}
public Task RunAsync(CancellationToken cancellationToken = default)
{
_logger.LogInformation("Starting Shower replay");
var currentTime = _replayOptions.StartTime;
var pollInterval = TimeSpan.FromSeconds(_showerOptions.PollIntervalSeconds);
var previousState = ShowerState.Idle;
while (currentTime <= _replayOptions.EndTime && !cancellationToken.IsCancellationRequested)
{
_timeProvider.AdvanceTo(currentTime);
var bathroomEntry = _timeline.GetStateAt(_showerOptions.BathroomHumidityEntityId, currentTime);
var homeEntry = _timeline.GetStateAt(_showerOptions.MainHomeHumidityEntityId, currentTime);
var bathroomHumidity = ParseDouble(bathroomEntry?.State);
var homeHumidity = ParseDouble(homeEntry?.State);
if (bathroomHumidity.HasValue && homeHumidity.HasValue)
{
var state = _detectionService.Evaluate(bathroomHumidity.Value, homeHumidity.Value, currentTime);
var differential = bathroomHumidity.Value - homeHumidity.Value;
_fanControlService.Evaluate(state, currentTime);
if (state != previousState)
{
var eventType = state switch
{
ShowerState.Active => ReplayEventType.Decision,
ShowerState.Completed => ReplayEventType.StateChange,
_ => ReplayEventType.Info
};
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = currentTime,
Monitor = MonitorName,
EventType = eventType,
Message = $"State: {previousState} → {state} (bathroom: {bathroomHumidity.Value:F1}%, home: {homeHumidity.Value:F1}%, diff: {differential:F1}%)",
Details = GetStateChangeDetails(state)
});
previousState = state;
}
}
currentTime = currentTime.Add(pollInterval);
}
_replayTimeline.AddEvent(new ReplayEvent
{
Timestamp = _replayOptions.EndTime,
Monitor = MonitorName,
EventType = ReplayEventType.Info,
Message = $"Final: {_detectionService.TodaySessionCount} session(s) detected"
});
_logger.LogInformation("Shower replay complete");
return Task.CompletedTask;
}
private string? GetStateChangeDetails(ShowerState state) =>
state switch
{
ShowerState.Completed when _detectionService.LastCompletedSession is not null =>
$"Duration: {_detectionService.LastCompletedSession.Duration:mm\\:ss}, Peak humidity: {_detectionService.LastCompletedSession.PeakHumidity:F1}%",
_ => null
};
private static double? ParseDouble(string? value)
{
if (value is null or "unavailable" or "unknown")
{
return null;
}
return double.TryParse(value, CultureInfo.InvariantCulture, out var result) ? result : null;
}
}
@@ -1,57 +0,0 @@
{
"HomeAssistant": {
"Host": "homeassistant.local",
"Port": 8123,
"Token": "<your-long-lived-access-token>",
"Ssl": false
},
"Replay": {
"StartTime": "2026-03-30T00:00:00+02:00",
"EndTime": "2026-03-31T00:00:00+02:00",
"Monitors": {
"NordPool": true,
"Boiler": true,
"Shower": true,
"Power": false,
"Light": true
}
},
"BoilerMonitor": {
"Enabled": true,
"CleanupEntitiesOnStartup": false
},
"ShowerMonitor": {
"Enabled": true,
"CleanupEntitiesOnStartup": false,
"BathroomHumidityEntityId": "sensor.bathroom_humidity",
"MainHomeHumidityEntityId": "sensor.main_home_humidity",
"BathroomTemperatureEntityId": "sensor.bathroom_temperature",
"ExhaustFanEntityId": "switch.exhaust_fan",
"PollIntervalSeconds": 30,
"SpikeRateThreshold": 4.0,
"MinDifferentialHumidity": 8.0,
"PeakHumidityThreshold": 58.0,
"ConfirmationWindowMinutes": 2,
"RecoveryDifferentialThreshold": 5.0,
"MaxShowerDurationMinutes": 60,
"FanRunAfterShowerMinutes": 10,
"RateWindowSize": 5
},
"LightMonitor": {
"Enabled": true,
"LightEntityId": "light.sonoff_1002214d40",
"SunEntityId": "sun.sun",
"PersonEntityIds": ["person.marius", "person.erika", "person.home_phone"]
},
"PowerMonitor": {
"Enabled": false,
"MainMeterEntityId": "sensor.sonoff_100267d63f_power",
"PollIntervalSeconds": 1,
"SmoothingWindowSize": 10,
"AnomalyThresholdWatts": 500,
"ExcludedSensorPatterns": [
"sensor.nordpool_*",
"sensor.powermonitor_*"
]
}
}
@@ -1,18 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>14.0</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>HomeAssistant.McpServer</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="10.0.5" />
<PackageReference Include="Microsoft.Extensions.Http" Version="10.0.5" />
<PackageReference Include="ModelContextProtocol" Version="1.2.0" />
</ItemGroup>
</Project>
-25
View File
@@ -1,25 +0,0 @@
using HomeAssistant.McpServer.Services;
using HomeAssistant.McpServer.Settings;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using ModelContextProtocol.Server;
var builder = Host.CreateApplicationBuilder(args);
builder.Logging.AddConsole(options =>
{
options.LogToStandardErrorThreshold = LogLevel.Trace;
});
builder.Services
.Configure<HomeAssistantSettings>(
builder.Configuration.GetSection(HomeAssistantSettings.SectionName))
.AddHttpClient<IHomeAssistantApiClient, HomeAssistantApiClient>();
builder.Services
.AddMcpServer()
.WithStdioServerTransport()
.WithToolsFromAssembly();
await builder.Build().RunAsync();
@@ -1,107 +0,0 @@
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using HomeAssistant.McpServer.Settings;
using Microsoft.Extensions.Options;
namespace HomeAssistant.McpServer.Services;
public sealed class HomeAssistantApiClient : IHomeAssistantApiClient
{
private readonly HttpClient _httpClient;
public HomeAssistantApiClient(HttpClient httpClient, IOptions<HomeAssistantSettings> settings)
{
_httpClient = httpClient;
_httpClient.BaseAddress = settings.Value.BaseUrl;
_httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", settings.Value.Token);
_httpClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
_httpClient.Timeout = TimeSpan.FromSeconds(HomeAssistantSettings.DefaultTimeoutSeconds);
}
public Task<JsonElement> GetApiStatusAsync(CancellationToken cancellationToken = default) =>
GetJsonAsync("/api/", cancellationToken);
public Task<JsonElement> GetConfigAsync(CancellationToken cancellationToken = default) =>
GetJsonAsync("/api/config", cancellationToken);
public Task<JsonElement> GetAllStatesAsync(CancellationToken cancellationToken = default) =>
GetJsonAsync("/api/states", cancellationToken);
public Task<JsonElement> GetEntityStateAsync(string entityId, CancellationToken cancellationToken = default) =>
GetJsonAsync($"/api/states/{Uri.EscapeDataString(entityId)}", cancellationToken);
public Task<JsonElement> GetServicesAsync(CancellationToken cancellationToken = default) =>
GetJsonAsync("/api/services", cancellationToken);
public Task<JsonElement> GetHistoryAsync(
string entityIds,
DateTimeOffset? startTime = null,
DateTimeOffset? endTime = null,
bool minimalResponse = true,
CancellationToken cancellationToken = default)
{
var start = startTime ?? DateTimeOffset.UtcNow.AddDays(-1);
var path = $"/api/history/period/{start:O}?filter_entity_id={Uri.EscapeDataString(entityIds)}";
if (endTime.HasValue)
path += $"&end_time={Uri.EscapeDataString(endTime.Value.ToString("O"))}";
if (minimalResponse)
path += "&minimal_response";
return GetJsonAsync(path, cancellationToken);
}
public Task<JsonElement> GetLogbookAsync(
string? entityId = null,
DateTimeOffset? startTime = null,
DateTimeOffset? endTime = null,
CancellationToken cancellationToken = default)
{
var start = startTime ?? DateTimeOffset.UtcNow.AddDays(-1);
var path = $"/api/logbook/{start:O}";
var queryParts = new List<string>();
if (!string.IsNullOrWhiteSpace(entityId))
queryParts.Add($"entity={Uri.EscapeDataString(entityId)}");
if (endTime.HasValue)
queryParts.Add($"end_time={Uri.EscapeDataString(endTime.Value.ToString("O"))}");
if (queryParts.Count > 0)
path += "?" + string.Join("&", queryParts);
return GetJsonAsync(path, cancellationToken);
}
public async Task<JsonElement> CallServiceAsync(
string domain,
string service,
JsonElement? serviceData = null,
CancellationToken cancellationToken = default)
{
var url = $"/api/services/{Uri.EscapeDataString(domain)}/{Uri.EscapeDataString(service)}";
var content = serviceData.HasValue
? JsonContent.Create(serviceData.Value)
: JsonContent.Create(new { });
var response = await _httpClient.PostAsync(url, content, cancellationToken).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
var doc = await JsonDocument.ParseAsync(stream, cancellationToken: cancellationToken).ConfigureAwait(false);
return doc.RootElement.Clone();
}
private async Task<JsonElement> GetJsonAsync(string path, CancellationToken cancellationToken)
{
var response = await _httpClient.GetAsync(path, cancellationToken).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
var doc = await JsonDocument.ParseAsync(stream, cancellationToken: cancellationToken).ConfigureAwait(false);
return doc.RootElement.Clone();
}
}
@@ -1,31 +0,0 @@
using System.Text.Json;
namespace HomeAssistant.McpServer.Services;
public interface IHomeAssistantApiClient
{
Task<JsonElement> GetApiStatusAsync(CancellationToken cancellationToken = default);
Task<JsonElement> GetConfigAsync(CancellationToken cancellationToken = default);
Task<JsonElement> GetAllStatesAsync(CancellationToken cancellationToken = default);
Task<JsonElement> GetEntityStateAsync(string entityId, CancellationToken cancellationToken = default);
Task<JsonElement> GetServicesAsync(CancellationToken cancellationToken = default);
Task<JsonElement> GetHistoryAsync(
string entityIds,
DateTimeOffset? startTime = null,
DateTimeOffset? endTime = null,
bool minimalResponse = true,
CancellationToken cancellationToken = default);
Task<JsonElement> GetLogbookAsync(
string? entityId = null,
DateTimeOffset? startTime = null,
DateTimeOffset? endTime = null,
CancellationToken cancellationToken = default);
Task<JsonElement> CallServiceAsync(
string domain,
string service,
JsonElement? serviceData = null,
CancellationToken cancellationToken = default);
}
@@ -1,15 +0,0 @@
namespace HomeAssistant.McpServer.Settings;
public sealed class HomeAssistantSettings
{
public const string SectionName = "HomeAssistant";
public const int DefaultPort = 8123;
public const int DefaultTimeoutSeconds = 30;
public string Host { get; set; } = string.Empty;
public int Port { get; set; } = DefaultPort;
public string Token { get; set; } = string.Empty;
public bool Ssl { get; set; }
public Uri BaseUrl => new UriBuilder(Ssl ? "https" : "http", Host, Port).Uri;
}
@@ -1,98 +0,0 @@
using System.ComponentModel;
using System.Text.Json;
using HomeAssistant.McpServer.Services;
using ModelContextProtocol.Server;
namespace HomeAssistant.McpServer.Tools;
[McpServerToolType]
public sealed class EntityStateTools
{
private readonly IHomeAssistantApiClient _client;
public EntityStateTools(IHomeAssistantApiClient client)
{
_client = client;
}
[McpServerTool, Description(
"Get the current state and attributes of a single Home Assistant entity. " +
"Provide the full entity_id, e.g. 'sensor.nordpool_kwh_lt_eur_3_10_0' or 'switch.boiler'.")]
public async Task<string> GetEntityState(
[Description("Full entity ID, e.g. 'sensor.temperature' or 'light.living_room'")] string entityId,
CancellationToken cancellationToken = default)
{
var result = await _client.GetEntityStateAsync(entityId, cancellationToken).ConfigureAwait(false);
return FormatJson(result);
}
[McpServerTool, Description(
"Get the current states of all Home Assistant entities. " +
"Optionally filter by domain (e.g. 'sensor', 'switch', 'climate', 'light'). " +
"Returns entity_id, state, and key attributes for each entity.")]
public async Task<string> GetAllStates(
[Description("Optional domain filter, e.g. 'sensor', 'switch', 'climate'. Leave empty for all.")] string? domain = null,
CancellationToken cancellationToken = default)
{
var allStates = await _client.GetAllStatesAsync(cancellationToken).ConfigureAwait(false);
if (string.IsNullOrWhiteSpace(domain))
return FormatJson(allStates);
var filtered = allStates.EnumerateArray()
.Where(e => e.TryGetProperty("entity_id", out var eid) &&
eid.GetString()?.StartsWith(domain + ".", StringComparison.OrdinalIgnoreCase) == true)
.ToList();
return JsonSerializer.Serialize(filtered, SerializerOptions);
}
[McpServerTool, Description(
"Search Home Assistant entities by partial match on entity_id or friendly_name. " +
"Useful for discovering entities related to a topic (e.g. 'nordpool', 'boiler', 'temperature').")]
public async Task<string> SearchEntities(
[Description("Search term to match against entity_id or friendly_name")] string query,
CancellationToken cancellationToken = default)
{
var allStates = await _client.GetAllStatesAsync(cancellationToken).ConfigureAwait(false);
var matches = allStates.EnumerateArray()
.Where(e => MatchesQuery(e, query))
.Select(e => new
{
entity_id = e.GetProperty("entity_id").GetString(),
state = e.GetProperty("state").GetString(),
friendly_name = e.TryGetProperty("attributes", out var attrs) &&
attrs.TryGetProperty("friendly_name", out var fn)
? fn.GetString()
: null
})
.ToList();
return JsonSerializer.Serialize(matches, SerializerOptions);
}
private static bool MatchesQuery(JsonElement entity, string query)
{
var q = query.ToUpperInvariant();
if (entity.TryGetProperty("entity_id", out var eid) &&
(eid.GetString()?.ToUpperInvariant().Contains(q) ?? false))
return true;
if (entity.TryGetProperty("attributes", out var attrs) &&
attrs.TryGetProperty("friendly_name", out var fn) &&
(fn.GetString()?.ToUpperInvariant().Contains(q) ?? false))
return true;
return false;
}
private static string FormatJson(JsonElement element) =>
JsonSerializer.Serialize(element, SerializerOptions);
private static readonly JsonSerializerOptions SerializerOptions = new()
{
WriteIndented = true
};
}
@@ -1,46 +0,0 @@
using System.ComponentModel;
using System.Text.Json;
using HomeAssistant.McpServer.Services;
using ModelContextProtocol.Server;
namespace HomeAssistant.McpServer.Tools;
[McpServerToolType]
public sealed class HistoryTools
{
private readonly IHomeAssistantApiClient _client;
public HistoryTools(IHomeAssistantApiClient client)
{
_client = client;
}
[McpServerTool, Description(
"Get state history for one or more Home Assistant entities over a time period. " +
"Returns timestamped state changes. Useful for debugging sensor readings, switch toggling, price changes, etc.")]
public async Task<string> GetEntityHistory(
[Description("Comma-separated entity IDs, e.g. 'sensor.temperature,sensor.humidity'")] string entityIds,
[Description("Start time in ISO 8601 format. Defaults to 24 hours ago. Example: '2026-03-30T00:00:00'")] string? startTime = null,
[Description("End time in ISO 8601 format. Defaults to now. Example: '2026-03-31T00:00:00'")] string? endTime = null,
[Description("If true, returns minimal data (state + last_changed only). Defaults to true.")] bool minimalResponse = true,
CancellationToken cancellationToken = default)
{
DateTimeOffset? start = string.IsNullOrWhiteSpace(startTime)
? null
: DateTimeOffset.Parse(startTime);
DateTimeOffset? end = string.IsNullOrWhiteSpace(endTime)
? null
: DateTimeOffset.Parse(endTime);
var result = await _client.GetHistoryAsync(entityIds, start, end, minimalResponse, cancellationToken)
.ConfigureAwait(false);
return JsonSerializer.Serialize(result, SerializerOptions);
}
private static readonly JsonSerializerOptions SerializerOptions = new()
{
WriteIndented = true
};
}
@@ -1,45 +0,0 @@
using System.ComponentModel;
using System.Text.Json;
using HomeAssistant.McpServer.Services;
using ModelContextProtocol.Server;
namespace HomeAssistant.McpServer.Tools;
[McpServerToolType]
public sealed class LogbookTools
{
private readonly IHomeAssistantApiClient _client;
public LogbookTools(IHomeAssistantApiClient client)
{
_client = client;
}
[McpServerTool, Description(
"Get Home Assistant logbook entries. Shows state changes and events for entities. " +
"Useful for understanding what happened and when. Filter by entity and/or time range.")]
public async Task<string> GetLogbook(
[Description("Optional entity ID to filter, e.g. 'switch.boiler'. Leave empty for all.")] string? entityId = null,
[Description("Start time in ISO 8601 format. Defaults to 24 hours ago.")] string? startTime = null,
[Description("End time in ISO 8601 format. Defaults to now.")] string? endTime = null,
CancellationToken cancellationToken = default)
{
DateTimeOffset? start = string.IsNullOrWhiteSpace(startTime)
? null
: DateTimeOffset.Parse(startTime);
DateTimeOffset? end = string.IsNullOrWhiteSpace(endTime)
? null
: DateTimeOffset.Parse(endTime);
var result = await _client.GetLogbookAsync(entityId, start, end, cancellationToken)
.ConfigureAwait(false);
return JsonSerializer.Serialize(result, SerializerOptions);
}
private static readonly JsonSerializerOptions SerializerOptions = new()
{
WriteIndented = true
};
}
@@ -1,75 +0,0 @@
using System.ComponentModel;
using System.Text.Json;
using HomeAssistant.McpServer.Services;
using ModelContextProtocol.Server;
namespace HomeAssistant.McpServer.Tools;
[McpServerToolType]
public sealed class ServiceTools
{
private readonly IHomeAssistantApiClient _client;
public ServiceTools(IHomeAssistantApiClient client)
{
_client = client;
}
[McpServerTool, Description(
"List available Home Assistant services. Optionally filter by domain (e.g. 'light', 'climate', 'switch'). " +
"Each service shows its domain and available service names.")]
public async Task<string> ListServices(
[Description("Optional domain filter, e.g. 'light', 'climate'. Leave empty for all.")] string? domain = null,
CancellationToken cancellationToken = default)
{
var allServices = await _client.GetServicesAsync(cancellationToken).ConfigureAwait(false);
if (string.IsNullOrWhiteSpace(domain))
return FormatJson(allServices);
var filtered = allServices.EnumerateArray()
.Where(s => s.TryGetProperty("domain", out var d) &&
string.Equals(d.GetString(), domain, StringComparison.OrdinalIgnoreCase))
.ToList();
return JsonSerializer.Serialize(filtered, SerializerOptions);
}
[McpServerTool, Description(
"Call a Home Assistant service. Examples: domain='light', service='turn_on', entityId='light.living_room'. " +
"For services requiring extra data, pass it as a JSON string in serviceData.")]
public async Task<string> CallService(
[Description("Service domain, e.g. 'light', 'climate', 'switch', 'input_boolean'")] string domain,
[Description("Service name, e.g. 'turn_on', 'turn_off', 'set_temperature'")] string service,
[Description("Optional target entity ID, e.g. 'light.living_room'")] string? entityId = null,
[Description("Optional JSON service data, e.g. '{\"brightness\": 255}' or '{\"temperature\": 22}'")] string? serviceData = null,
CancellationToken cancellationToken = default)
{
JsonElement? data = null;
if (!string.IsNullOrWhiteSpace(serviceData) || !string.IsNullOrWhiteSpace(entityId))
{
var dataDict = string.IsNullOrWhiteSpace(serviceData)
? new Dictionary<string, object>()
: JsonSerializer.Deserialize<Dictionary<string, object>>(serviceData) ?? [];
if (!string.IsNullOrWhiteSpace(entityId))
dataDict["entity_id"] = entityId;
data = JsonSerializer.SerializeToElement(dataDict);
}
var result = await _client.CallServiceAsync(domain, service, data, cancellationToken)
.ConfigureAwait(false);
return FormatJson(result);
}
private static string FormatJson(JsonElement element) =>
JsonSerializer.Serialize(element, SerializerOptions);
private static readonly JsonSerializerOptions SerializerOptions = new()
{
WriteIndented = true
};
}
@@ -1,52 +0,0 @@
using System.ComponentModel;
using System.Text.Json;
using HomeAssistant.McpServer.Services;
using ModelContextProtocol.Server;
namespace HomeAssistant.McpServer.Tools;
[McpServerToolType]
public sealed class SystemTools
{
private readonly IHomeAssistantApiClient _client;
public SystemTools(IHomeAssistantApiClient client)
{
_client = client;
}
[McpServerTool, Description(
"Get Home Assistant configuration including version, location, components, and unit system. " +
"Useful for understanding the HA environment.")]
public async Task<string> GetHaConfig(CancellationToken cancellationToken = default)
{
var result = await _client.GetConfigAsync(cancellationToken).ConfigureAwait(false);
return JsonSerializer.Serialize(result, SerializerOptions);
}
[McpServerTool, Description(
"Check if the Home Assistant API is reachable and responding. " +
"Returns the API status message or an error description.")]
public async Task<string> CheckApi(CancellationToken cancellationToken = default)
{
try
{
var result = await _client.GetApiStatusAsync(cancellationToken).ConfigureAwait(false);
return JsonSerializer.Serialize(result, SerializerOptions);
}
catch (HttpRequestException ex)
{
return JsonSerializer.Serialize(new { status = "error", message = ex.Message }, SerializerOptions);
}
catch (TaskCanceledException)
{
return JsonSerializer.Serialize(
new { status = "error", message = "Request timed out - HA may be unreachable" }, SerializerOptions);
}
}
private static readonly JsonSerializerOptions SerializerOptions = new()
{
WriteIndented = true
};
}
+8 -4
View File
@@ -1,10 +1,14 @@
using NetDaemon.Extensions.MqttEntityManager;
#region
using NetDaemon.Extensions.MqttEntityManager;
#endregion
namespace HomeAssistant.Models;
public class EntityCreateModel
{
public string? EntityId { get; set; }
public EntityCreationOptions? Options { get; set; } = new();
public object? AdditionalConfig { get; set; } = null;
public string? EntityId { get; protected init; }
public EntityCreationOptions? Options { get; init; } = new EntityCreationOptions();
public object? AdditionalConfig { get; init; }
}
@@ -7,7 +7,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="NetDaemon.Extensions.Mqtt" Version="26.11.0" />
<PackageReference Include="NetDaemon.Extensions.Mqtt" Version="26.43.1"/>
</ItemGroup>
</Project>
+11 -6
View File
@@ -1,8 +1,12 @@
#region
using System;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Serilog;
#endregion
namespace HomeAssistantServer;
public static class CustomLoggingProvider
@@ -10,14 +14,15 @@ public static class CustomLoggingProvider
public static IHostBuilder UseCustomLogging(this IHostBuilder builder)
{
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") ?? "Production"}.json", optional: true)
.Build();
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") ?? "Production"}.json",
true)
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
.ReadFrom.Configuration(configuration)
.CreateLogger();
return builder.UseSerilog(logger);
}
}
}
@@ -21,11 +21,15 @@
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</None>
<None Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="appsettings.development.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
<CopyToPublishDirectory>Never</CopyToPublishDirectory>
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
<CopyToPublishDirectory>Never</CopyToPublishDirectory>
</None>
<None Update="$(MSBuildProjectDir)appsettings.Production.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
<CopyToPublishDirectory>Always</CopyToPublishDirectory>
</None>
</ItemGroup>
<Target Name="AfterPublishMessage" AfterTargets="Publish">
@@ -33,30 +37,31 @@
</Target>
<ItemGroup>
<PackageReference Include="AutoMapper" Version="16.1.1" />
<PackageReference Include="NetDaemon.AppModel" Version="26.11.0" />
<PackageReference Include="NetDaemon.Runtime" Version="26.11.0" />
<PackageReference Include="NetDaemon.HassModel" Version="26.11.0" />
<PackageReference Include="NetDaemon.Client" Version="26.11.0" />
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.11.0" />
<PackageReference Include="NetDaemon.Extensions.Logging" Version="26.11.0" />
<PackageReference Include="NetDaemon.Extensions.Tts" Version="26.11.0" />
<PackageReference Include="AutoMapper" Version="17.0.0"/>
<PackageReference Include="NetDaemon.AppModel" Version="26.43.1"/>
<PackageReference Include="NetDaemon.Runtime" Version="26.43.1"/>
<PackageReference Include="NetDaemon.HassModel" Version="26.43.1"/>
<PackageReference Include="NetDaemon.Client" Version="26.43.1"/>
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.43.1"/>
<PackageReference Include="NetDaemon.Extensions.Logging" Version="26.43.1"/>
<PackageReference Include="NetDaemon.Extensions.Tts" Version="26.43.1"/>
</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="..\Mappings\Mappings.csproj" />
<ProjectReference Include="..\NordPool.Manager\NordPool.Manager.csproj" />
<ProjectReference Include="..\NordPool.Models\NordPool.Models.csproj" />
<ProjectReference Include="..\PowerMonitor.Manager\PowerMonitor.Manager.csproj" />
<ProjectReference Include="..\PowerMonitor.Models\PowerMonitor.Models.csproj" />
<ProjectReference Include="..\ShowerMonitor.Manager\ShowerMonitor.Manager.csproj" />
<ProjectReference Include="..\ShowerMonitor.Models\ShowerMonitor.Models.csproj" />
<ProjectReference Include="..\LightMonitor.Manager\LightMonitor.Manager.csproj" />
<ProjectReference Include="..\LightMonitor.Models\LightMonitor.Models.csproj" />
<ProjectReference Include="..\BatteryMonitor.Manager\BatteryMonitor.Manager.csproj" />
<ProjectReference Include="..\BatteryMonitor.Models\BatteryMonitor.Models.csproj" />
<ProjectReference Include="..\BoilerMonitor.Manager\BoilerMonitor.Manager.csproj"/>
<ProjectReference Include="..\BoilerMonitor.Models\BoilerMonitor.Models.csproj"/>
<ProjectReference Include="..\HomeAssistant.Entities\HomeAssistant.Entities.csproj"/>
<ProjectReference Include="..\Mappings\Mappings.csproj"/>
<ProjectReference Include="..\NordPool.Manager\NordPool.Manager.csproj"/>
<ProjectReference Include="..\NordPool.Models\NordPool.Models.csproj"/>
<ProjectReference Include="..\PowerMonitor.Manager\PowerMonitor.Manager.csproj"/>
<ProjectReference Include="..\PowerMonitor.Models\PowerMonitor.Models.csproj"/>
<ProjectReference Include="..\ShowerMonitor.Manager\ShowerMonitor.Manager.csproj"/>
<ProjectReference Include="..\ShowerMonitor.Models\ShowerMonitor.Models.csproj"/>
<ProjectReference Include="..\LightMonitor.Manager\LightMonitor.Manager.csproj"/>
<ProjectReference Include="..\LightMonitor.Models\LightMonitor.Models.csproj"/>
<ProjectReference Include="..\BatteryMonitor.Manager\BatteryMonitor.Manager.csproj"/>
<ProjectReference Include="..\BatteryMonitor.Models\BatteryMonitor.Models.csproj"/>
<ProjectReference Include="..\LeakMonitor.Manager\LeakMonitor.Manager.csproj"/>
</ItemGroup>
</Project>

Some files were not shown because too many files have changed in this diff Show More