Compare commits
12 Commits
f176a1b8fc
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 635e9625ea | |||
| f919d6b25b | |||
| 77458383d1 | |||
| 24729ee267 | |||
| cf8c9434c8 | |||
| 41ac93733e | |||
| 17774b40b8 | |||
| ada3c77778 | |||
| b5e114be14 | |||
| 5777e641f6 | |||
| 1152462765 | |||
| f0bbd4f10b |
@@ -0,0 +1,16 @@
|
|||||||
|
{
|
||||||
|
"mcpServers": {
|
||||||
|
"UnoApp": {
|
||||||
|
"command": "dotnet",
|
||||||
|
"args": [
|
||||||
|
"dnx",
|
||||||
|
"-y",
|
||||||
|
"uno.devserver",
|
||||||
|
"--mcp-app"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"UnoDocs": {
|
||||||
|
"url": "https://mcp.platform.uno/v1"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
{
|
||||||
|
"mcpServers": {
|
||||||
|
"UnoApp": {
|
||||||
|
"command": "dotnet",
|
||||||
|
"args": [
|
||||||
|
"dnx",
|
||||||
|
"-y",
|
||||||
|
"uno.devserver",
|
||||||
|
"--mcp-app"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -13,22 +13,28 @@ before editing; it only records things that are easy to get wrong.
|
|||||||
|
|
||||||
## Stack
|
## Stack
|
||||||
|
|
||||||
- .NET 10 / C# 14 (`LangVersion=14.0`). `global.json` pins SDK `10.0.0` with
|
- .NET 10 / C# 14 (`LangVersion=14.0`, set per-csproj in the three
|
||||||
`rollForward=latestMajor` and `allowPrerelease=true`.
|
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
|
- NetDaemon v5 (NuGet `26.11.0`) apps run inside `HomeAssistant.Server`, the
|
||||||
only host / binary-deploy target. Solution file: `HomeAssistantSDK.sln`.
|
only host / binary-deploy target. Solution file: `HomeAssistantSDK.sln`.
|
||||||
- Tests: xUnit + FluentAssertions + Moq. `Microsoft.Extensions.TimeProvider.Testing`
|
- Tests: xUnit + FluentAssertions + Moq. `Microsoft.Extensions.TimeProvider.Testing`
|
||||||
is used for time-based tests — prefer `FakeTimeProvider` over real time.
|
is used for time-based tests — prefer `FakeTimeProvider` over real time.
|
||||||
- AutoMapper 16 is used by `HomeAssistant.Server`. **A hardcoded license key
|
- 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
|
is committed in `HomeAssistant.Server/program.cs`** — do not move it to
|
||||||
settings, and do not log or echo it.
|
settings, and do not log or echo it.
|
||||||
|
|
||||||
## Layout (non-obvious wiring)
|
## Layout (non-obvious wiring)
|
||||||
|
|
||||||
- Each monitor follows a fixed 3-project pattern:
|
- Each monitor follows a fixed 3-project pattern:
|
||||||
- `*.Models` — constants, enums, `*Options` (bound from
|
- `*.Models` — entity/config interfaces, constants, enums.
|
||||||
`appsettings.json` via `IOptions<>`).
|
- `*.Manager` — services, the `[NetDaemonApp]` entry `*Init.cs`, and
|
||||||
- `*.Manager` — services + the `[NetDaemonApp]` entry `*Init.cs`.
|
`*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.
|
- `*.Manager.Tests` — unit tests for the manager.
|
||||||
- Apps are **not** auto-discovered by the host. Each monitor exposes a
|
- Apps are **not** auto-discovered by the host. Each monitor exposes a
|
||||||
`Add<Name>Monitor(this IServiceCollection, IConfiguration)` extension in
|
`Add<Name>Monitor(this IServiceCollection, IConfiguration)` extension in
|
||||||
@@ -36,24 +42,43 @@ before editing; it only records things that are easy to get wrong.
|
|||||||
specific order. Adding a new monitor means: create the 3 projects, add a
|
specific order. Adding a new monitor means: create the 3 projects, add a
|
||||||
`*ServiceRegistration.cs`, reference the projects from
|
`*ServiceRegistration.cs`, reference the projects from
|
||||||
`HomeAssistant.Server`, and wire `Add<Name>` + `Configure<*Options>` in
|
`HomeAssistant.Server`, and wire `Add<Name>` + `Configure<*Options>` in
|
||||||
`program.cs`.
|
`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
|
- `*ServiceRegistration.cs` honors an `Enabled` flag in the options and
|
||||||
no-ops (skips `AddNetDaemonApp`) when disabled. `PowerMonitor` ships
|
no-ops (skips `AddNetDaemonApp`) when disabled — for every monitor
|
||||||
disabled by default in `appsettings.json`.
|
**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`
|
- `HomeAssistant.Entities` holds the **generated** `HomeAssistantGenerated`
|
||||||
code (entity metadata sourced from
|
code (entity metadata sourced from
|
||||||
`HomeAssistant.Server/NetDaemonCodegen/{EntityMetaData,ServicesMetaData}.json`).
|
`HomeAssistant.Server/NetDaemonCodegen/{EntityMetaData,ServicesMetaData}.json`).
|
||||||
`program.cs` calls `AddHomeAssistantGenerated()`; the generated entities
|
`program.cs` calls `AddHomeAssistantGenerated()`; the generated entities
|
||||||
are transient. Do not hand-edit generated files.
|
are transient. Do not hand-edit generated files.
|
||||||
- `HomeAssistant.McpServer` is a separate stdio MCP server (ModelContextProtocol
|
- `program.cs` calls `Configure<*Options>` then `Add<Name>…` for each
|
||||||
NuGet) exposing HA tools. It is **not** referenced by the host; it runs
|
monitor in this order: NordPool, Power, Boiler, Shower, Light, Battery,
|
||||||
standalone via `dotnet run --project HomeAssistant.McpServer`. Cursor
|
Leak. Monitor service registrations (except `IBoilerConfigReader`,
|
||||||
wires it up in `.cursor/mcp.json` as the `homeassistant` MCP server.
|
`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
|
- `HomeAssistant.HistoryReplay` is a Blazor debug web app that replays HA
|
||||||
history through monitor business logic with no side effects. See its own
|
history through monitor business logic with no side effects. It
|
||||||
README. Not deployed.
|
references a subset of monitors (Boiler, NordPool, Power, Shower, Light —
|
||||||
- `NordPool.Comminication` (sic — typo is intentional, keep it) is the
|
not Battery or Leak). See its own README. Not deployed.
|
||||||
Nord Pool HTTP client project referenced by `NordPool.Manager`.
|
|
||||||
|
|
||||||
## Critical DI rule
|
## Critical DI rule
|
||||||
|
|
||||||
@@ -63,11 +88,16 @@ collections) must be registered **scoped or transient**, never singleton,
|
|||||||
or app load fails with:
|
or app load fails with:
|
||||||
`Cannot resolve scoped service … from root provider`.
|
`Cannot resolve scoped service … from root provider`.
|
||||||
|
|
||||||
Verified-livable registrations (do not regress these to singleton):
|
Verified-livable registrations (do not regress these lifetimes; re-check
|
||||||
|
scoped dependencies if changing one):
|
||||||
- `Boiler`: `IBoilerMonitorEntityService` transient,
|
- `Boiler`: `IBoilerMonitorEntityService` transient,
|
||||||
`IBoilerConfigReader` scoped (in `program.cs`).
|
`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`
|
- `NordPool`: `INordPoolEntityService` transient, `INordPoolPriceService`
|
||||||
scoped, `INordPoolBoilerConfigProvider` scoped,
|
singleton (pure state/math, no HA dep — HA fetch call lives in
|
||||||
|
`NordPoolInit`), `INordPoolBoilerConfigProvider` scoped,
|
||||||
`ICheapestIntervalsFinder` singleton (no HA dep).
|
`ICheapestIntervalsFinder` singleton (no HA dep).
|
||||||
- `Power`: `IPowerMonitorEntityService` + `IPowerNotificationService`
|
- `Power`: `IPowerMonitorEntityService` + `IPowerNotificationService`
|
||||||
transient, `IPowerSensorDiscoveryService` scoped. `IOtherPowerCalculationService`
|
transient, `IPowerSensorDiscoveryService` scoped. `IOtherPowerCalculationService`
|
||||||
@@ -88,8 +118,8 @@ scoped.
|
|||||||
## Live validation after monitor edits
|
## Live validation after monitor edits
|
||||||
|
|
||||||
`.cursor/rules/live-validation.mdc` (globs: all `*.Manager`/`*.Models` of
|
`.cursor/rules/live-validation.mdc` (globs: all `*.Manager`/`*.Models` of
|
||||||
Boiler, Light, NordPool, Power, Shower, plus `HomeAssistant.McpServer`)
|
Boiler, Light, NordPool, Power, Shower, plus `HomeAssistant.McpServer` —
|
||||||
requires, after editing monitor runtime code:
|
**not** Battery or Leak) requires, after editing monitor runtime code:
|
||||||
|
|
||||||
1. `dotnet build` the affected project.
|
1. `dotnet build` the affected project.
|
||||||
2. `RunSmokeTest` MCP tool from the `homeassistant` MCP server.
|
2. `RunSmokeTest` MCP tool from the `homeassistant` MCP server.
|
||||||
@@ -153,10 +183,14 @@ prints the reminder after publish.
|
|||||||
`HumidityRateCalculator`). Keep both in sync when changing option names.
|
`HumidityRateCalculator`). Keep both in sync when changing option names.
|
||||||
- `HomeAssistant.Server` references every monitor's `*.Manager` and
|
- `HomeAssistant.Server` references every monitor's `*.Manager` and
|
||||||
`*.Models` projects directly; `HomeAssistant.HistoryReplay` references a
|
`*.Models` projects directly; `HomeAssistant.HistoryReplay` references a
|
||||||
subset. Adding a monitor to the replay tool requires a new project
|
subset (Boiler, NordPool, Power, Shower, Light). Adding a monitor to the
|
||||||
reference there too.
|
replay tool requires a new project reference there too.
|
||||||
- The repository folder name is misspelled `homeassistant-app-deamon`
|
- The repository folder name is misspelled `homeassistant-app-deamon`
|
||||||
(should be `daemon`). This is intentional/legacy — do not "fix" it in
|
(should be `daemon`). This is intentional/legacy — do not "fix" it in
|
||||||
paths; scripts and `.cursor/mcp.json` use `${workspaceFolder}`.
|
paths; `opencode.json` and `.cursor/mcp.json` reference the workspace
|
||||||
- `NordPool.Comminication` is also misspelled — keep it; the project
|
folder by macro.
|
||||||
reference depends on the exact name.
|
- Stale untracked folders `NordPool.Comminication/` and
|
||||||
|
`HomeAssistant.Infrastructure/` may appear on disk containing only
|
||||||
|
`obj/` build cruft. They are **not** in the solution, not committed to
|
||||||
|
git, and not referenced by any project. Do not treat them as real
|
||||||
|
projects; safe to delete.
|
||||||
@@ -8,18 +8,18 @@
|
|||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="coverlet.collector" Version="8.0.0">
|
<PackageReference Include="coverlet.collector" Version="10.1.1">
|
||||||
<PrivateAssets>all</PrivateAssets>
|
<PrivateAssets>all</PrivateAssets>
|
||||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
</PackageReference>
|
</PackageReference>
|
||||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.3.0" />
|
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.12.0"/>
|
||||||
<PackageReference Include="xunit" Version="2.9.3"/>
|
<PackageReference Include="xunit" Version="2.9.3"/>
|
||||||
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5">
|
<PackageReference Include="xunit.runner.visualstudio" Version="4.0.1">
|
||||||
<PrivateAssets>all</PrivateAssets>
|
<PrivateAssets>all</PrivateAssets>
|
||||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
</PackageReference>
|
</PackageReference>
|
||||||
<PackageReference Include="FluentAssertions" Version="8.8.0" />
|
<PackageReference Include="FluentAssertions" Version="8.11.0"/>
|
||||||
<PackageReference Include="Moq" Version="4.20.72" />
|
<PackageReference Include="Moq" Version="4.21.0"/>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
|||||||
@@ -0,0 +1,242 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using System.Globalization;
|
||||||
|
using System.Text.Json;
|
||||||
|
using BatteryMonitor.Models;
|
||||||
|
using Moq;
|
||||||
|
using NetDaemon.HassModel;
|
||||||
|
using NetDaemon.HassModel.Entities;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace BatteryMonitor.Manager.Tests;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Shared, deterministic builders and datasets used by the BatteryMonitor tests.
|
||||||
|
/// Keeping entity/state construction and generated inputs here means the test
|
||||||
|
/// classes only describe the scenario under test.
|
||||||
|
/// </summary>
|
||||||
|
internal static class BatteryMonitorTestData
|
||||||
|
{
|
||||||
|
private const string DefaultFriendlyName = "Battery Device";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// (threshold, state, expected) rows straddling the strict <c>level < threshold</c>
|
||||||
|
/// boundary, including zero/negative thresholds and int min/max thresholds.
|
||||||
|
/// </summary>
|
||||||
|
public static TheoryData<int, string, bool> ThresholdBoundaryRows { get; } = new TheoryData<int, string, bool>
|
||||||
|
{
|
||||||
|
{ 5, "4", true },
|
||||||
|
{ 5, "5", false },
|
||||||
|
{ 5, "6", false },
|
||||||
|
{ 5, "0", true },
|
||||||
|
{ 5, "-3", true },
|
||||||
|
{ 5, "4.9", true },
|
||||||
|
{ 5, "5.0", false },
|
||||||
|
{ 5, "100", false },
|
||||||
|
{ 1, "0.5", true },
|
||||||
|
{ 1, "1", false },
|
||||||
|
{ 20, "19", true },
|
||||||
|
{ 20, "19.99", true },
|
||||||
|
{ 20, "20", false },
|
||||||
|
{ 0, "-1", true },
|
||||||
|
{ 0, "0", false },
|
||||||
|
{ 0, "1", false },
|
||||||
|
{ -5, "-6", true },
|
||||||
|
{ -5, "-5", false },
|
||||||
|
{ -5, "-4", false },
|
||||||
|
{ 100, "99.9", true },
|
||||||
|
{ 100, "100", false },
|
||||||
|
{ 101, "100", true },
|
||||||
|
{ int.MaxValue, "100", true },
|
||||||
|
{ int.MinValue, "-2147483648", false },
|
||||||
|
{ int.MinValue, "-2147483649", true }
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// States that must never produce a <see cref="BatterySensorInfo" />, including
|
||||||
|
/// whitespace/malformed strings and a null state.
|
||||||
|
/// </summary>
|
||||||
|
public static TheoryData<string?> UnusableStateRows { get; } =
|
||||||
|
[
|
||||||
|
"unavailable",
|
||||||
|
"unknown",
|
||||||
|
"UNAVAILABLE",
|
||||||
|
"UNKNOWN",
|
||||||
|
string.Empty,
|
||||||
|
" ",
|
||||||
|
"\t",
|
||||||
|
"not_a_number",
|
||||||
|
"3%",
|
||||||
|
"--1",
|
||||||
|
"low",
|
||||||
|
"1 2",
|
||||||
|
null
|
||||||
|
];
|
||||||
|
|
||||||
|
/// <summary>Device counts used to exercise notification payload generation.</summary>
|
||||||
|
public static TheoryData<int> NotifyDeviceCounts { get; } = [1, 2, 3, 5, 10, 50];
|
||||||
|
|
||||||
|
/// <summary>A battery device-class sensor.</summary>
|
||||||
|
public static EntitySpec Battery(string entityId, string? state, string? friendlyName = DefaultFriendlyName)
|
||||||
|
{
|
||||||
|
return new EntitySpec
|
||||||
|
{
|
||||||
|
EntityId = entityId,
|
||||||
|
State = state,
|
||||||
|
FriendlyName = friendlyName
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A sensor with an arbitrary (or missing) device class.</summary>
|
||||||
|
public static EntitySpec Sensor(string entityId,
|
||||||
|
string? deviceClass,
|
||||||
|
string? state,
|
||||||
|
string? friendlyName = DefaultFriendlyName)
|
||||||
|
{
|
||||||
|
return new EntitySpec
|
||||||
|
{
|
||||||
|
EntityId = entityId,
|
||||||
|
DeviceClass = deviceClass,
|
||||||
|
State = state,
|
||||||
|
FriendlyName = friendlyName
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static EntityState CreateEntityState(EntitySpec spec)
|
||||||
|
{
|
||||||
|
var attributes = new Dictionary<string, object?>(StringComparer.Ordinal);
|
||||||
|
|
||||||
|
if (spec.DeviceClass is not null)
|
||||||
|
{
|
||||||
|
attributes["device_class"] = spec.DeviceClass;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (spec.FriendlyName is not null)
|
||||||
|
{
|
||||||
|
attributes["friendly_name"] = spec.FriendlyName;
|
||||||
|
}
|
||||||
|
|
||||||
|
return new EntityState
|
||||||
|
{
|
||||||
|
State = spec.State,
|
||||||
|
AttributesJson = JsonSerializer.SerializeToElement(attributes)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Wires <see cref="IHaContext.GetState" /> and <see cref="IHaContext.GetAllEntities" />
|
||||||
|
/// on the mock, exposing the entities in declaration order.
|
||||||
|
/// </summary>
|
||||||
|
public static void ConfigureHaContext(Mock<IHaContext> haContextMock, params EntitySpec[] entities)
|
||||||
|
{
|
||||||
|
var entityList = new List<Entity>(entities.Length);
|
||||||
|
|
||||||
|
foreach (var spec in entities)
|
||||||
|
{
|
||||||
|
if (spec.HasState)
|
||||||
|
{
|
||||||
|
haContextMock.Setup(h => h.GetState(spec.EntityId)).Returns(CreateEntityState(spec));
|
||||||
|
}
|
||||||
|
|
||||||
|
entityList.Add(new Entity(haContextMock.Object, spec.EntityId));
|
||||||
|
}
|
||||||
|
|
||||||
|
haContextMock.Setup(h => h.GetAllEntities()).Returns(entityList);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static BatterySensorInfo CreateSensorInfo(string entityId, double batteryLevel, string? friendlyName = null)
|
||||||
|
{
|
||||||
|
return new BatterySensorInfo
|
||||||
|
{
|
||||||
|
EntityId = entityId,
|
||||||
|
FriendlyName = friendlyName ?? entityId,
|
||||||
|
BatteryLevel = batteryLevel
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<BatterySensorInfo> CreateSensorInfos(params (string EntityId, double BatteryLevel)[] sensors)
|
||||||
|
{
|
||||||
|
return [.. sensors.Select(s => CreateSensorInfo(s.EntityId, s.BatteryLevel))];
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<BatterySensorInfo> CreateSensorInfos(
|
||||||
|
params (string EntityId, string FriendlyName, double BatteryLevel)[] sensors)
|
||||||
|
{
|
||||||
|
return [.. sensors.Select(s => CreateSensorInfo(s.EntityId, s.BatteryLevel, s.FriendlyName))];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Generates battery sensors with every integer level in <c>0..count-1</c>.
|
||||||
|
/// </summary>
|
||||||
|
public static EntitySpec[] CreateGeneratedBatteryEntities(int count)
|
||||||
|
{
|
||||||
|
return
|
||||||
|
[
|
||||||
|
.. Enumerable.Range(0, count)
|
||||||
|
.Select(i => Battery(
|
||||||
|
$"sensor.generated_battery_{i:D3}",
|
||||||
|
i.ToString(CultureInfo.InvariantCulture),
|
||||||
|
$"Generated Battery {i:D3}"))
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Generates notification devices with deterministic, non-monotonic levels so
|
||||||
|
/// ordering behaviour is exercised over more than a handful of rows.
|
||||||
|
/// </summary>
|
||||||
|
public static IReadOnlyList<BatterySensorInfo> CreateGeneratedSensorInfos(int count)
|
||||||
|
{
|
||||||
|
return
|
||||||
|
[
|
||||||
|
.. Enumerable.Range(0, count)
|
||||||
|
.Select(i => CreateSensorInfo(
|
||||||
|
$"sensor.generated_{i:D3}",
|
||||||
|
i * 37 % 101,
|
||||||
|
$"Generated Device {i:D3}"))
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Cross-product of every excluded keyword (lower and upper case) plus
|
||||||
|
/// non-excluded look-alikes that must not be filtered.
|
||||||
|
/// </summary>
|
||||||
|
public static TheoryData<string, bool> ExcludedEntityIdRows()
|
||||||
|
{
|
||||||
|
var data = new TheoryData<string, bool>();
|
||||||
|
|
||||||
|
foreach (var keyword in BatteryMonitorConsts.ExcludedKeywords)
|
||||||
|
{
|
||||||
|
data.Add($"sensor.my_{keyword}_battery_level", true);
|
||||||
|
data.Add($"SENSOR.MY_{keyword.ToUpperInvariant()}_BATTERY_LEVEL", true);
|
||||||
|
}
|
||||||
|
|
||||||
|
data.Add("sensor.iphone", true);
|
||||||
|
data.Add("sensor.x_phone_x", true);
|
||||||
|
data.Add("sensor.bathroom_battery", false);
|
||||||
|
data.Add("sensor.boiler_temp_battery", false);
|
||||||
|
data.Add("sensor.aquarium_leak_sensor_battery", false);
|
||||||
|
data.Add("sensor.temperature", false);
|
||||||
|
data.Add(string.Empty, false);
|
||||||
|
data.Add(" ", false);
|
||||||
|
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Describes one entity exposed through <see cref="IHaContext.GetAllEntities" />.
|
||||||
|
/// </summary>
|
||||||
|
public sealed record EntitySpec
|
||||||
|
{
|
||||||
|
public required string EntityId { get; init; }
|
||||||
|
|
||||||
|
public string? State { get; init; } = "50";
|
||||||
|
|
||||||
|
public string? DeviceClass { get; init; } = BatteryMonitorConsts.BatteryDeviceClass;
|
||||||
|
|
||||||
|
public string? FriendlyName { get; init; } = DefaultFriendlyName;
|
||||||
|
|
||||||
|
/// <summary>When false the context returns no <see cref="EntityState" /> for the entity.</summary>
|
||||||
|
public bool HasState { get; init; } = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,54 +1,65 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using System.Text.Json;
|
||||||
|
using BatteryMonitor.Models;
|
||||||
|
using BatteryMonitorManager;
|
||||||
using FluentAssertions;
|
using FluentAssertions;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using Moq;
|
using Moq;
|
||||||
using NetDaemon.HassModel;
|
using NetDaemon.HassModel;
|
||||||
using NetDaemon.HassModel.Entities;
|
using NetDaemon.HassModel.Entities;
|
||||||
using BatteryMonitor.Models;
|
using static BatteryMonitor.Manager.Tests.BatteryMonitorTestData;
|
||||||
using BatteryMonitorManager;
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace BatteryMonitor.Manager.Tests;
|
namespace BatteryMonitor.Manager.Tests;
|
||||||
|
|
||||||
public class BatteryNotificationServiceTests
|
public class BatteryNotificationServiceTests
|
||||||
{
|
{
|
||||||
private readonly Mock<IHaContext> _haContextMock;
|
private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
|
||||||
private readonly Mock<ILogger<BatteryNotificationService>> _loggerMock;
|
private readonly Mock<ILogger<BatteryNotificationService>> _loggerMock = new Mock<ILogger<BatteryNotificationService>>();
|
||||||
|
|
||||||
public BatteryNotificationServiceTests()
|
|
||||||
{
|
|
||||||
_haContextMock = new Mock<IHaContext>();
|
|
||||||
_loggerMock = new Mock<ILogger<BatteryNotificationService>>();
|
|
||||||
}
|
|
||||||
|
|
||||||
private BatteryNotificationService CreateSut()
|
private BatteryNotificationService CreateSut()
|
||||||
{
|
{
|
||||||
return new BatteryNotificationService(_haContextMock.Object, _loggerMock.Object);
|
return new BatteryNotificationService(_haContextMock.Object, _loggerMock.Object);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void VerifyCallService(string service, Times times)
|
||||||
|
{
|
||||||
|
_haContextMock.Verify(h => h.CallService(
|
||||||
|
BatteryMonitorConsts.PersistentNotificationDomain,
|
||||||
|
service,
|
||||||
|
It.IsAny<ServiceTarget?>(),
|
||||||
|
It.IsAny<object?>()), times);
|
||||||
|
}
|
||||||
|
|
||||||
#region NotifyLowBattery
|
#region NotifyLowBattery
|
||||||
|
|
||||||
[Fact]
|
[Theory]
|
||||||
public void NotifyLowBattery_WithDevices_ShouldCallPersistentNotificationCreate()
|
[MemberData(nameof(NotifyDeviceCounts), MemberType = typeof(BatteryMonitorTestData))]
|
||||||
|
public void NotifyLowBattery_WithDevices_ShouldCallPersistentNotificationCreate(int deviceCount)
|
||||||
{
|
{
|
||||||
var devices = new List<BatterySensorInfo>
|
var devices = CreateSensorInfos(
|
||||||
{
|
[
|
||||||
new() { EntityId = "sensor.bathroom_battery", FriendlyName = "Bathroom Battery", BatteryLevel = 3 },
|
.. Enumerable.Range(0, deviceCount)
|
||||||
new() { EntityId = "sensor.bedroom_battery", FriendlyName = "Bedroom Battery", BatteryLevel = 1 }
|
.Select(i => ($"sensor.device_{i:D3}", $"Device {i:D3}", (double)(i % 5)))
|
||||||
};
|
]);
|
||||||
|
|
||||||
var sut = CreateSut();
|
var sut = CreateSut();
|
||||||
sut.NotifyLowBattery(devices);
|
sut.NotifyLowBattery(devices);
|
||||||
|
|
||||||
_haContextMock.Verify(h => h.CallService(
|
VerifyCallService(BatteryMonitorConsts.PersistentNotificationCreateService, Times.Once());
|
||||||
BatteryMonitorConsts.PersistentNotificationDomain,
|
VerifyCallService(BatteryMonitorConsts.PersistentNotificationDismissService, Times.Never());
|
||||||
BatteryMonitorConsts.PersistentNotificationCreateService,
|
|
||||||
It.IsAny<ServiceTarget?>(),
|
|
||||||
It.IsAny<object?>()), Times.Once);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Theory]
|
||||||
public void NotifyLowBattery_WithEmptyList_ShouldNotCallService()
|
[InlineData(false)]
|
||||||
|
[InlineData(true)]
|
||||||
|
public void NotifyLowBattery_WithEmptyList_ShouldNotCallService(bool useArray)
|
||||||
{
|
{
|
||||||
var devices = new List<BatterySensorInfo>();
|
IReadOnlyList<BatterySensorInfo> devices = useArray
|
||||||
|
? Array.Empty<BatterySensorInfo>()
|
||||||
|
: new List<BatterySensorInfo>();
|
||||||
|
|
||||||
var sut = CreateSut();
|
var sut = CreateSut();
|
||||||
sut.NotifyLowBattery(devices);
|
sut.NotifyLowBattery(devices);
|
||||||
@@ -58,6 +69,62 @@ public class BatteryNotificationServiceTests
|
|||||||
It.IsAny<string>(),
|
It.IsAny<string>(),
|
||||||
It.IsAny<ServiceTarget?>(),
|
It.IsAny<ServiceTarget?>(),
|
||||||
It.IsAny<object?>()), Times.Never);
|
It.IsAny<object?>()), Times.Never);
|
||||||
|
|
||||||
|
_loggerMock.Invocations.Should().BeEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void NotifyLowBattery_ShouldSendTitleNotificationIdAndDeviceSummary()
|
||||||
|
{
|
||||||
|
object? payload = null;
|
||||||
|
|
||||||
|
_haContextMock
|
||||||
|
.Setup(h => h.CallService(
|
||||||
|
BatteryMonitorConsts.PersistentNotificationDomain,
|
||||||
|
BatteryMonitorConsts.PersistentNotificationCreateService,
|
||||||
|
It.IsAny<ServiceTarget?>(),
|
||||||
|
It.IsAny<object?>()))
|
||||||
|
.Callback<string, string, ServiceTarget?, object?>((_, _, _, data) => payload = data);
|
||||||
|
|
||||||
|
var sut = CreateSut();
|
||||||
|
|
||||||
|
sut.NotifyLowBattery(CreateSensorInfos(
|
||||||
|
("sensor.a", "Device A", 4),
|
||||||
|
("sensor.b", "Device B", 1)));
|
||||||
|
|
||||||
|
payload.Should().NotBeNull();
|
||||||
|
|
||||||
|
using var document = JsonDocument.Parse(JsonSerializer.Serialize(payload));
|
||||||
|
var root = document.RootElement;
|
||||||
|
root.GetProperty("title").GetString().Should().Be(BatteryMonitorConsts.NotificationTitle);
|
||||||
|
root.GetProperty("notification_id").GetString().Should().Be(BatteryMonitorConsts.NotificationId);
|
||||||
|
|
||||||
|
var message = root.GetProperty("message").GetString();
|
||||||
|
message.Should().Contain("Device A").And.Contain("Device B");
|
||||||
|
message.Should().Contain("1%").And.Contain("4%");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void NotifyLowBattery_WithDevices_ShouldLogDeviceCount()
|
||||||
|
{
|
||||||
|
_loggerMock.Setup(l => l.IsEnabled(LogLevel.Information)).Returns(true);
|
||||||
|
|
||||||
|
var devices = CreateSensorInfos(
|
||||||
|
("sensor.a", "Device A", 2),
|
||||||
|
("sensor.b", "Device B", 3));
|
||||||
|
|
||||||
|
var sut = CreateSut();
|
||||||
|
sut.NotifyLowBattery(devices);
|
||||||
|
|
||||||
|
var logInvocation = _loggerMock.Invocations
|
||||||
|
.Where(invocation => invocation.Method.Name == nameof(ILogger.Log))
|
||||||
|
.Should()
|
||||||
|
.ContainSingle()
|
||||||
|
.Subject;
|
||||||
|
|
||||||
|
logInvocation.Arguments[0].Should().Be(LogLevel.Information);
|
||||||
|
logInvocation.Arguments[2].Should().NotBeNull();
|
||||||
|
logInvocation.Arguments[2]!.ToString().Should().Be("Sent low battery notification for 2 device(s)");
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
@@ -70,11 +137,25 @@ public class BatteryNotificationServiceTests
|
|||||||
var sut = CreateSut();
|
var sut = CreateSut();
|
||||||
sut.DismissNotification();
|
sut.DismissNotification();
|
||||||
|
|
||||||
_haContextMock.Verify(h => h.CallService(
|
VerifyCallService(BatteryMonitorConsts.PersistentNotificationDismissService, Times.Once());
|
||||||
BatteryMonitorConsts.PersistentNotificationDomain,
|
VerifyCallService(BatteryMonitorConsts.PersistentNotificationCreateService, Times.Never());
|
||||||
BatteryMonitorConsts.PersistentNotificationDismissService,
|
}
|
||||||
It.IsAny<ServiceTarget?>(),
|
|
||||||
It.IsAny<object?>()), Times.Once);
|
[Theory]
|
||||||
|
[InlineData(1)]
|
||||||
|
[InlineData(2)]
|
||||||
|
[InlineData(5)]
|
||||||
|
public void DismissNotification_WhenCalledRepeatedly_ShouldDismissEachTime(int calls)
|
||||||
|
{
|
||||||
|
var sut = CreateSut();
|
||||||
|
|
||||||
|
for (var i = 0; i < calls; i++)
|
||||||
|
{
|
||||||
|
sut.DismissNotification();
|
||||||
|
}
|
||||||
|
|
||||||
|
VerifyCallService(BatteryMonitorConsts.PersistentNotificationDismissService, Times.Exactly(calls));
|
||||||
|
VerifyCallService(BatteryMonitorConsts.PersistentNotificationCreateService, Times.Never());
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
@@ -84,41 +165,90 @@ public class BatteryNotificationServiceTests
|
|||||||
[Fact]
|
[Fact]
|
||||||
public void BuildNotificationMessage_ShouldOrderByBatteryLevel()
|
public void BuildNotificationMessage_ShouldOrderByBatteryLevel()
|
||||||
{
|
{
|
||||||
var devices = new List<BatterySensorInfo>
|
var devices = CreateSensorInfos(
|
||||||
{
|
("sensor.a", "Device A", 4),
|
||||||
new() { EntityId = "sensor.a", FriendlyName = "Device A", BatteryLevel = 4 },
|
("sensor.b", "Device B", 1),
|
||||||
new() { EntityId = "sensor.b", FriendlyName = "Device B", BatteryLevel = 1 },
|
("sensor.c", "Device C", 3));
|
||||||
new() { EntityId = "sensor.c", FriendlyName = "Device C", BatteryLevel = 3 }
|
|
||||||
};
|
|
||||||
|
|
||||||
var message = BatteryNotificationService.BuildNotificationMessage(devices);
|
var message = BatteryNotificationService.BuildNotificationMessage(devices);
|
||||||
|
|
||||||
var lines = message.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries);
|
var lines = message.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries);
|
||||||
|
lines.Should().HaveCount(4);
|
||||||
lines[1].Should().Contain("Device B");
|
lines[1].Should().Contain("Device B");
|
||||||
lines[2].Should().Contain("Device C");
|
lines[2].Should().Contain("Device C");
|
||||||
lines[3].Should().Contain("Device A");
|
lines[3].Should().Contain("Device A");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void BuildNotificationMessage_ShouldKeepInsertionOrderForEqualLevels()
|
||||||
|
{
|
||||||
|
var devices = CreateSensorInfos(
|
||||||
|
("sensor.first", "First Device", 4),
|
||||||
|
("sensor.second", "Second Device", 4),
|
||||||
|
("sensor.third", "Third Device", 1));
|
||||||
|
|
||||||
|
var message = BatteryNotificationService.BuildNotificationMessage(devices);
|
||||||
|
|
||||||
|
var lines = message.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries);
|
||||||
|
lines.Should().HaveCount(4);
|
||||||
|
lines[1].Should().Contain("Third Device");
|
||||||
|
lines[2].Should().Contain("First Device");
|
||||||
|
lines[3].Should().Contain("Second Device");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void BuildNotificationMessage_WithGeneratedDevices_ShouldOrderByAscendingLevel()
|
||||||
|
{
|
||||||
|
var devices = CreateGeneratedSensorInfos(50);
|
||||||
|
|
||||||
|
var message = BatteryNotificationService.BuildNotificationMessage(devices);
|
||||||
|
|
||||||
|
var expectedLines = devices
|
||||||
|
.OrderBy(d => d.BatteryLevel)
|
||||||
|
.Select(d => $"- **{d.FriendlyName}**: {d.BatteryLevel:F0}%");
|
||||||
|
|
||||||
|
var lines = message.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries);
|
||||||
|
lines.Should().HaveCount(devices.Count + 1);
|
||||||
|
lines.Skip(1).Should().Equal(expectedLines);
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void BuildNotificationMessage_ShouldContainTitle()
|
public void BuildNotificationMessage_ShouldContainTitle()
|
||||||
{
|
{
|
||||||
var devices = new List<BatterySensorInfo>
|
var devices = CreateSensorInfos(("sensor.a", "Device A", 2));
|
||||||
{
|
|
||||||
new() { EntityId = "sensor.a", FriendlyName = "Device A", BatteryLevel = 2 }
|
|
||||||
};
|
|
||||||
|
|
||||||
var message = BatteryNotificationService.BuildNotificationMessage(devices);
|
var message = BatteryNotificationService.BuildNotificationMessage(devices);
|
||||||
|
|
||||||
message.Should().Contain("low battery");
|
message.Should().Contain("low battery");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("Bathroom Battery", 3, "- **Bathroom Battery**: 3%")]
|
||||||
|
[InlineData("Test Device", 1, "- **Test Device**: 1%")]
|
||||||
|
[InlineData("Empty Battery", 0, "- **Empty Battery**: 0%")]
|
||||||
|
[InlineData("Negative Battery", -7, "- **Negative Battery**: -7%")]
|
||||||
|
[InlineData("Rounded Down", 12.4, "- **Rounded Down**: 12%")]
|
||||||
|
[InlineData("Rounded Up", 12.6, "- **Rounded Up**: 13%")]
|
||||||
|
[InlineData("Full Battery", 100, "- **Full Battery**: 100%")]
|
||||||
|
[InlineData("", 5, "- ****: 5%")]
|
||||||
|
[InlineData(" ", 4, "- ** **: 4%")]
|
||||||
|
public void BuildNotificationMessage_ShouldFormatDeviceLine(string friendlyName,
|
||||||
|
double batteryLevel,
|
||||||
|
string expectedLine)
|
||||||
|
{
|
||||||
|
var devices = CreateSensorInfos(("sensor.a", friendlyName, batteryLevel));
|
||||||
|
|
||||||
|
var message = BatteryNotificationService.BuildNotificationMessage(devices);
|
||||||
|
|
||||||
|
var lines = message.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries);
|
||||||
|
lines.Should().HaveCount(2);
|
||||||
|
lines[1].Should().Be(expectedLine);
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void BuildNotificationMessage_ShouldContainDeviceNameAndLevel()
|
public void BuildNotificationMessage_ShouldContainDeviceNameAndLevel()
|
||||||
{
|
{
|
||||||
var devices = new List<BatterySensorInfo>
|
var devices = CreateSensorInfos(("sensor.a", "Bathroom Battery", 3));
|
||||||
{
|
|
||||||
new() { EntityId = "sensor.a", FriendlyName = "Bathroom Battery", BatteryLevel = 3 }
|
|
||||||
};
|
|
||||||
|
|
||||||
var message = BatteryNotificationService.BuildNotificationMessage(devices);
|
var message = BatteryNotificationService.BuildNotificationMessage(devices);
|
||||||
|
|
||||||
@@ -129,15 +259,36 @@ public class BatteryNotificationServiceTests
|
|||||||
[Fact]
|
[Fact]
|
||||||
public void BuildNotificationMessage_WithSingleDevice_ShouldFormatCorrectly()
|
public void BuildNotificationMessage_WithSingleDevice_ShouldFormatCorrectly()
|
||||||
{
|
{
|
||||||
var devices = new List<BatterySensorInfo>
|
var devices = CreateSensorInfos(("sensor.a", "Test Device", 1));
|
||||||
{
|
|
||||||
new() { EntityId = "sensor.a", FriendlyName = "Test Device", BatteryLevel = 1 }
|
|
||||||
};
|
|
||||||
|
|
||||||
var message = BatteryNotificationService.BuildNotificationMessage(devices);
|
var message = BatteryNotificationService.BuildNotificationMessage(devices);
|
||||||
|
|
||||||
message.Should().Contain("- **Test Device**: 1%");
|
message.Should().Contain("- **Test Device**: 1%");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void BuildNotificationMessage_WithDuplicateDevices_ShouldListEveryDevice()
|
||||||
|
{
|
||||||
|
var devices = CreateSensorInfos(
|
||||||
|
("sensor.duplicate_battery", "Duplicate Battery", 2),
|
||||||
|
("sensor.duplicate_battery", "Duplicate Battery", 2));
|
||||||
|
|
||||||
|
var message = BatteryNotificationService.BuildNotificationMessage(devices);
|
||||||
|
|
||||||
|
var lines = message.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries);
|
||||||
|
lines.Should().HaveCount(3);
|
||||||
|
lines[1].Should().Be("- **Duplicate Battery**: 2%");
|
||||||
|
lines[2].Should().Be("- **Duplicate Battery**: 2%");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void BuildNotificationMessage_WithNoDevices_ShouldContainOnlyHeader()
|
||||||
|
{
|
||||||
|
var message = BatteryNotificationService.BuildNotificationMessage([]);
|
||||||
|
|
||||||
|
message.Should().Be("The following devices have low battery:");
|
||||||
|
message.Should().NotContain("- **");
|
||||||
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
}
|
}
|
||||||
@@ -1,58 +1,44 @@
|
|||||||
using System.Text.Json;
|
#region
|
||||||
|
|
||||||
|
using System.Globalization;
|
||||||
|
using BatteryMonitor.Models;
|
||||||
|
using BatteryMonitorManager;
|
||||||
using FluentAssertions;
|
using FluentAssertions;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using Moq;
|
using Moq;
|
||||||
using NetDaemon.HassModel;
|
using NetDaemon.HassModel;
|
||||||
using NetDaemon.HassModel.Entities;
|
using NetDaemon.HassModel.Entities;
|
||||||
using BatteryMonitorManager;
|
using static BatteryMonitor.Manager.Tests.BatteryMonitorTestData;
|
||||||
using BatteryMonitor.Models;
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace BatteryMonitor.Manager.Tests;
|
namespace BatteryMonitor.Manager.Tests;
|
||||||
|
|
||||||
public class BatterySensorDiscoveryServiceTests
|
public class BatterySensorDiscoveryServiceTests
|
||||||
{
|
{
|
||||||
private readonly Mock<IHaContext> _haContextMock;
|
private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
|
||||||
private readonly Mock<ILogger<BatterySensorDiscoveryService>> _loggerMock;
|
private readonly Mock<ILogger<BatterySensorDiscoveryService>> _loggerMock = new Mock<ILogger<BatterySensorDiscoveryService>>();
|
||||||
|
|
||||||
public BatterySensorDiscoveryServiceTests()
|
|
||||||
{
|
|
||||||
_haContextMock = new Mock<IHaContext>();
|
|
||||||
_loggerMock = new Mock<ILogger<BatterySensorDiscoveryService>>();
|
|
||||||
}
|
|
||||||
|
|
||||||
private BatterySensorDiscoveryService CreateSut()
|
private BatterySensorDiscoveryService CreateSut()
|
||||||
{
|
{
|
||||||
return new BatterySensorDiscoveryService(_haContextMock.Object, _loggerMock.Object);
|
return new BatterySensorDiscoveryService(_haContextMock.Object, _loggerMock.Object);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void SetupEntities(params (string entityId, string? deviceClass, string? state, string? friendlyName)[] entities)
|
private void SetupEntities(params EntitySpec[] entities)
|
||||||
{
|
{
|
||||||
var entityList = new List<Entity>();
|
ConfigureHaContext(_haContextMock, entities);
|
||||||
|
|
||||||
foreach (var (entityId, deviceClass, state, friendlyName) in entities)
|
|
||||||
{
|
|
||||||
var attributes = new Dictionary<string, object?>();
|
|
||||||
if (deviceClass is not null)
|
|
||||||
{
|
|
||||||
attributes["device_class"] = deviceClass;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (friendlyName is not null)
|
#region IsExcludedDevice
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(ExcludedEntityIdRows), MemberType = typeof(BatteryMonitorTestData))]
|
||||||
|
public void IsExcludedDevice_ShouldCorrectlyIdentifyExclusions(string entityId, bool expected)
|
||||||
{
|
{
|
||||||
attributes["friendly_name"] = friendlyName;
|
BatterySensorDiscoveryService.IsExcludedDevice(entityId).Should().Be(expected);
|
||||||
}
|
}
|
||||||
|
|
||||||
var attributesJson = JsonSerializer.SerializeToElement(attributes);
|
#endregion
|
||||||
var entityState = new EntityState { AttributesJson = attributesJson, State = state };
|
|
||||||
|
|
||||||
_haContextMock.Setup(h => h.GetState(entityId)).Returns(entityState);
|
|
||||||
|
|
||||||
var entity = new Entity(_haContextMock.Object, entityId);
|
|
||||||
entityList.Add(entity);
|
|
||||||
}
|
|
||||||
|
|
||||||
_haContextMock.Setup(h => h.GetAllEntities()).Returns(entityList);
|
|
||||||
}
|
|
||||||
|
|
||||||
#region Discovery
|
#region Discovery
|
||||||
|
|
||||||
@@ -60,9 +46,9 @@ public class BatterySensorDiscoveryServiceTests
|
|||||||
public void DiscoverLowBatterySensors_ShouldFindLowBatteryDevices()
|
public void DiscoverLowBatterySensors_ShouldFindLowBatteryDevices()
|
||||||
{
|
{
|
||||||
SetupEntities(
|
SetupEntities(
|
||||||
("sensor.bathroom_battery", "battery", "3", "Bathroom Battery"),
|
Battery("sensor.bathroom_battery", "3", "Bathroom Battery"),
|
||||||
("sensor.bedroom_battery", "battery", "80", "Bedroom Battery"),
|
Battery("sensor.bedroom_battery", "80", "Bedroom Battery"),
|
||||||
("sensor.boiler_temp_battery", "battery", "2", "Boiler Temp Battery")
|
Battery("sensor.boiler_temp_battery", "2", "Boiler Temp Battery")
|
||||||
);
|
);
|
||||||
|
|
||||||
var sut = CreateSut();
|
var sut = CreateSut();
|
||||||
@@ -71,134 +57,116 @@ public class BatterySensorDiscoveryServiceTests
|
|||||||
result.Should().HaveCount(2);
|
result.Should().HaveCount(2);
|
||||||
result.Should().Contain(s => s.EntityId == "sensor.bathroom_battery");
|
result.Should().Contain(s => s.EntityId == "sensor.bathroom_battery");
|
||||||
result.Should().Contain(s => s.EntityId == "sensor.boiler_temp_battery");
|
result.Should().Contain(s => s.EntityId == "sensor.boiler_temp_battery");
|
||||||
|
result.Select(s => s.EntityId).Should().NotContain("sensor.bedroom_battery");
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Theory]
|
||||||
public void DiscoverLowBatterySensors_ShouldExcludePhoneDevices()
|
[InlineData("sensor.erikas_iphone_battery_level", "Erika's iPhone Battery")]
|
||||||
|
[InlineData("sensor.home_phone_battery_state", "Home Phone Battery")]
|
||||||
|
[InlineData("sensor.marius_watch_battery_level", "Marius Watch Battery")]
|
||||||
|
[InlineData("sensor.sm_s936b_battery_level", "Galaxy S24 Battery")]
|
||||||
|
[InlineData("sensor.sm_a536b_battery_level", "Galaxy A53 Battery")]
|
||||||
|
[InlineData("sensor.pixel_8_battery_level", "Pixel 8 Battery")]
|
||||||
|
[InlineData("sensor.oneplus_battery_level", "OnePlus Battery")]
|
||||||
|
[InlineData("sensor.ipad_battery_level", "iPad Battery")]
|
||||||
|
[InlineData("sensor.galaxy_s24_battery", "Galaxy S24 Battery")]
|
||||||
|
[InlineData("SENSOR.SM_S936B_BATTERY_LEVEL", "Galaxy S24 Battery")]
|
||||||
|
public void DiscoverLowBatterySensors_ShouldExcludePersonalDevices(string excludedEntityId, string friendlyName)
|
||||||
{
|
{
|
||||||
SetupEntities(
|
SetupEntities(
|
||||||
("sensor.bathroom_battery", "battery", "2", "Bathroom Battery"),
|
Battery("sensor.bathroom_battery", "2", "Bathroom Battery"),
|
||||||
("sensor.erikas_iphone_battery_level", "battery", "1", "Erika's iPhone Battery"),
|
Battery(excludedEntityId, "1", friendlyName)
|
||||||
("sensor.home_phone_battery_state", "battery", "3", "Home Phone Battery")
|
|
||||||
);
|
);
|
||||||
|
|
||||||
var sut = CreateSut();
|
var sut = CreateSut();
|
||||||
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
||||||
|
|
||||||
result.Should().HaveCount(1);
|
result.Should().ContainSingle();
|
||||||
result.First().EntityId.Should().Be("sensor.bathroom_battery");
|
result[0].EntityId.Should().Be("sensor.bathroom_battery");
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Theory]
|
||||||
public void DiscoverLowBatterySensors_ShouldExcludeWatchDevices()
|
[InlineData("binary_sensor.bathroom_battery", "battery")]
|
||||||
|
[InlineData("sensor.bathroom_temperature", "temperature")]
|
||||||
|
[InlineData("sensor.bathroom_humidity", "humidity")]
|
||||||
|
[InlineData("sensor.no_device_class", null)]
|
||||||
|
[InlineData("sensorx.bathroom_battery", "battery")]
|
||||||
|
[InlineData("switch.bathroom_battery", "battery")]
|
||||||
|
public void DiscoverLowBatterySensors_ShouldIgnoreEntitiesThatAreNotBatterySensors(string entityId,
|
||||||
|
string? deviceClass)
|
||||||
{
|
{
|
||||||
SetupEntities(
|
SetupEntities(
|
||||||
("sensor.bathroom_battery", "battery", "2", "Bathroom Battery"),
|
Sensor(entityId, deviceClass, "2", "Ignored Entity"),
|
||||||
("sensor.marius_watch_battery_level", "battery", "1", "Marius Watch Battery")
|
Battery("sensor.bedroom_battery", "3", "Bedroom Battery")
|
||||||
);
|
);
|
||||||
|
|
||||||
var sut = CreateSut();
|
var sut = CreateSut();
|
||||||
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
||||||
|
|
||||||
result.Should().HaveCount(1);
|
result.Should().ContainSingle();
|
||||||
result.First().EntityId.Should().Be("sensor.bathroom_battery");
|
result[0].EntityId.Should().Be("sensor.bedroom_battery");
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Theory]
|
||||||
public void DiscoverLowBatterySensors_ShouldExcludeGalaxyDevices()
|
[MemberData(nameof(UnusableStateRows), MemberType = typeof(BatteryMonitorTestData))]
|
||||||
|
public void DiscoverLowBatterySensors_ShouldSkipUnusableStates(string? state)
|
||||||
{
|
{
|
||||||
SetupEntities(
|
SetupEntities(
|
||||||
("sensor.bathroom_battery", "battery", "2", "Bathroom Battery"),
|
Battery("sensor.bathroom_battery", state, "Bathroom Battery"),
|
||||||
("sensor.sm_s936b_battery_level", "battery", "1", "Galaxy S24 Battery")
|
Battery("sensor.bedroom_battery", "3", "Bedroom Battery")
|
||||||
);
|
);
|
||||||
|
|
||||||
var sut = CreateSut();
|
var sut = CreateSut();
|
||||||
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
||||||
|
|
||||||
result.Should().HaveCount(1);
|
result.Should().ContainSingle();
|
||||||
result.First().EntityId.Should().Be("sensor.bathroom_battery");
|
result[0].EntityId.Should().Be("sensor.bedroom_battery");
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void DiscoverLowBatterySensors_ShouldIgnoreNonSensorDomain()
|
public void DiscoverLowBatterySensors_WhenEntityStateIsNull_ShouldSkipSensor()
|
||||||
{
|
{
|
||||||
SetupEntities(
|
SetupEntities(
|
||||||
("binary_sensor.bathroom_battery", "battery", "2", "Bathroom Battery"),
|
new EntitySpec
|
||||||
("sensor.bedroom_battery", "battery", "3", "Bedroom Battery")
|
{ EntityId = "sensor.bathroom_battery", FriendlyName = "Bathroom Battery", HasState = false },
|
||||||
|
Battery("sensor.bedroom_battery", "3", "Bedroom Battery")
|
||||||
);
|
);
|
||||||
|
|
||||||
var sut = CreateSut();
|
var sut = CreateSut();
|
||||||
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
||||||
|
|
||||||
result.Should().HaveCount(1);
|
result.Should().ContainSingle();
|
||||||
result.First().EntityId.Should().Be("sensor.bedroom_battery");
|
result[0].EntityId.Should().Be("sensor.bedroom_battery");
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Theory]
|
||||||
public void DiscoverLowBatterySensors_ShouldIgnoreNonBatteryDeviceClass()
|
[MemberData(nameof(ThresholdBoundaryRows), MemberType = typeof(BatteryMonitorTestData))]
|
||||||
|
public void DiscoverLowBatterySensors_ShouldApplyStrictThresholdBoundary(int thresholdPercent,
|
||||||
|
string state,
|
||||||
|
bool expectedIncluded)
|
||||||
{
|
{
|
||||||
SetupEntities(
|
SetupEntities(Battery("sensor.boundary_battery", state, "Boundary Battery"));
|
||||||
("sensor.bathroom_temperature", "temperature", "2", "Bathroom Temperature"),
|
|
||||||
("sensor.bedroom_battery", "battery", "3", "Bedroom Battery")
|
|
||||||
);
|
|
||||||
|
|
||||||
var sut = CreateSut();
|
var sut = CreateSut();
|
||||||
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
var result = sut.DiscoverLowBatterySensors(thresholdPercent);
|
||||||
|
|
||||||
result.Should().HaveCount(1);
|
result.Should().HaveCount(expectedIncluded ? 1 : 0);
|
||||||
result.First().EntityId.Should().Be("sensor.bedroom_battery");
|
|
||||||
|
if (!expectedIncluded)
|
||||||
|
{
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
result[0].EntityId.Should().Be("sensor.boundary_battery");
|
||||||
public void DiscoverLowBatterySensors_ShouldSkipUnavailableState()
|
result[0].BatteryLevel.Should().Be(double.Parse(state, CultureInfo.InvariantCulture));
|
||||||
{
|
|
||||||
SetupEntities(
|
|
||||||
("sensor.bathroom_battery", "battery", "unavailable", "Bathroom Battery"),
|
|
||||||
("sensor.bedroom_battery", "battery", "3", "Bedroom Battery")
|
|
||||||
);
|
|
||||||
|
|
||||||
var sut = CreateSut();
|
|
||||||
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
|
||||||
|
|
||||||
result.Should().HaveCount(1);
|
|
||||||
result.First().EntityId.Should().Be("sensor.bedroom_battery");
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void DiscoverLowBatterySensors_ShouldSkipUnknownState()
|
|
||||||
{
|
|
||||||
SetupEntities(
|
|
||||||
("sensor.bathroom_battery", "battery", "unknown", "Bathroom Battery"),
|
|
||||||
("sensor.bedroom_battery", "battery", "3", "Bedroom Battery")
|
|
||||||
);
|
|
||||||
|
|
||||||
var sut = CreateSut();
|
|
||||||
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
|
||||||
|
|
||||||
result.Should().HaveCount(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void DiscoverLowBatterySensors_ShouldSkipNonParsableState()
|
|
||||||
{
|
|
||||||
SetupEntities(
|
|
||||||
("sensor.bathroom_battery", "battery", "not_a_number", "Bathroom Battery"),
|
|
||||||
("sensor.bedroom_battery", "battery", "3", "Bedroom Battery")
|
|
||||||
);
|
|
||||||
|
|
||||||
var sut = CreateSut();
|
|
||||||
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
|
||||||
|
|
||||||
result.Should().HaveCount(1);
|
|
||||||
result.First().EntityId.Should().Be("sensor.bedroom_battery");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void DiscoverLowBatterySensors_WhenNoBatterySensors_ShouldReturnEmpty()
|
public void DiscoverLowBatterySensors_WhenNoBatterySensors_ShouldReturnEmpty()
|
||||||
{
|
{
|
||||||
SetupEntities(
|
SetupEntities(
|
||||||
("sensor.temperature", "temperature", "22", "Temperature"),
|
Sensor("sensor.temperature", "temperature", "22", "Temperature"),
|
||||||
("switch.some_switch", null, "on", "Switch")
|
Sensor("switch.some_switch", null, "on", "Switch")
|
||||||
);
|
);
|
||||||
|
|
||||||
var sut = CreateSut();
|
var sut = CreateSut();
|
||||||
@@ -211,8 +179,9 @@ public class BatterySensorDiscoveryServiceTests
|
|||||||
public void DiscoverLowBatterySensors_WhenAllAboveThreshold_ShouldReturnEmpty()
|
public void DiscoverLowBatterySensors_WhenAllAboveThreshold_ShouldReturnEmpty()
|
||||||
{
|
{
|
||||||
SetupEntities(
|
SetupEntities(
|
||||||
("sensor.bathroom_battery", "battery", "50", "Bathroom Battery"),
|
Battery("sensor.bathroom_battery", "5", "Bathroom Battery"),
|
||||||
("sensor.bedroom_battery", "battery", "80", "Bedroom Battery")
|
Battery("sensor.bedroom_battery", "50", "Bedroom Battery"),
|
||||||
|
Battery("sensor.boiler_temp_battery", "100", "Boiler Temp Battery")
|
||||||
);
|
);
|
||||||
|
|
||||||
var sut = CreateSut();
|
var sut = CreateSut();
|
||||||
@@ -222,101 +191,114 @@ public class BatterySensorDiscoveryServiceTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void DiscoverLowBatterySensors_ShouldRespectCustomThreshold()
|
public void DiscoverLowBatterySensors_WhenThereAreNoEntities_ShouldReturnEmpty()
|
||||||
{
|
{
|
||||||
SetupEntities(
|
SetupEntities();
|
||||||
("sensor.bathroom_battery", "battery", "15", "Bathroom Battery"),
|
|
||||||
("sensor.bedroom_battery", "battery", "25", "Bedroom Battery")
|
|
||||||
);
|
|
||||||
|
|
||||||
var sut = CreateSut();
|
var sut = CreateSut();
|
||||||
var result = sut.DiscoverLowBatterySensors(20);
|
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
||||||
|
|
||||||
result.Should().HaveCount(1);
|
result.Should().NotBeNull();
|
||||||
result.First().EntityId.Should().Be("sensor.bathroom_battery");
|
result.Should().BeEmpty();
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void DiscoverLowBatterySensors_ShouldPopulateFriendlyName()
|
public void DiscoverLowBatterySensors_WithDuplicateSensorIds_ShouldReportEachOccurrence()
|
||||||
{
|
{
|
||||||
SetupEntities(
|
SetupEntities(
|
||||||
("sensor.bathroom_battery", "battery", "2", "Bathroom Battery")
|
Battery("sensor.duplicate_battery", "2", "Duplicate Battery"),
|
||||||
|
Battery("sensor.duplicate_battery", "2", "Duplicate Battery")
|
||||||
);
|
);
|
||||||
|
|
||||||
var sut = CreateSut();
|
var sut = CreateSut();
|
||||||
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
||||||
|
|
||||||
result.Should().HaveCount(1);
|
result.Should().HaveCount(2);
|
||||||
result.First().FriendlyName.Should().Be("Bathroom Battery");
|
result.Should().OnlyContain(s => s.EntityId == "sensor.duplicate_battery");
|
||||||
result.First().BatteryLevel.Should().Be(2);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Theory]
|
||||||
public void DiscoverLowBatterySensors_ShouldUseEntityIdWhenNoFriendlyName()
|
[InlineData("Bathroom Battery", "Bathroom Battery")]
|
||||||
|
[InlineData("", "")]
|
||||||
|
[InlineData(" ", " ")]
|
||||||
|
[InlineData(null, "sensor.bathroom_battery")]
|
||||||
|
public void DiscoverLowBatterySensors_ShouldResolveFriendlyName(string? friendlyName, string expectedFriendlyName)
|
||||||
{
|
{
|
||||||
SetupEntities(
|
SetupEntities(Battery("sensor.bathroom_battery", "2", friendlyName));
|
||||||
("sensor.bathroom_battery", "battery", "2", null)
|
|
||||||
);
|
|
||||||
|
|
||||||
var sut = CreateSut();
|
var sut = CreateSut();
|
||||||
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
||||||
|
|
||||||
result.Should().HaveCount(1);
|
result.Should().ContainSingle();
|
||||||
result.First().FriendlyName.Should().Be("sensor.bathroom_battery");
|
result[0].EntityId.Should().Be("sensor.bathroom_battery");
|
||||||
|
result[0].FriendlyName.Should().Be(expectedFriendlyName);
|
||||||
|
result[0].BatteryLevel.Should().Be(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void DiscoverLowBatterySensors_ShouldPreserveFractionalBatteryLevel()
|
||||||
|
{
|
||||||
|
SetupEntities(Battery("sensor.bathroom_battery", "2.5", "Bathroom Battery"));
|
||||||
|
|
||||||
|
var sut = CreateSut();
|
||||||
|
var result = sut.DiscoverLowBatterySensors(BatteryMonitorConsts.DefaultBatteryThresholdPercent);
|
||||||
|
|
||||||
|
result.Should().ContainSingle();
|
||||||
|
result[0].FriendlyName.Should().Be("Bathroom Battery");
|
||||||
|
result[0].BatteryLevel.Should().Be(2.5);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void DiscoverLowBatterySensors_WithGeneratedSensors_ShouldReturnOnlySensorsBelowThreshold()
|
||||||
|
{
|
||||||
|
SetupEntities(CreateGeneratedBatteryEntities(101));
|
||||||
|
|
||||||
|
var sut = CreateSut();
|
||||||
|
var result = sut.DiscoverLowBatterySensors(7);
|
||||||
|
|
||||||
|
result.Should().HaveCount(7);
|
||||||
|
result.Select(s => s.BatteryLevel).Should().Equal(Enumerable.Range(0, 7).Select(i => (double)i));
|
||||||
|
|
||||||
|
result.Select(s => s.FriendlyName)
|
||||||
|
.Should()
|
||||||
|
.OnlyContain(name => name.StartsWith("Generated Battery", StringComparison.Ordinal));
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
#region IsBatterySensor
|
#region IsBatterySensor
|
||||||
|
|
||||||
[Fact]
|
[Theory]
|
||||||
public void IsBatterySensor_WithBatteryDeviceClass_ShouldReturnTrue()
|
[InlineData("sensor.bathroom_battery", "battery", true)]
|
||||||
|
[InlineData("SENSOR.bathroom_battery", "battery", true)]
|
||||||
|
[InlineData("Sensor.Bathroom_Battery", "BATTERY", true)]
|
||||||
|
[InlineData("sensor.bathroom_battery", "Battery", true)]
|
||||||
|
[InlineData("binary_sensor.bathroom_battery", "battery", false)]
|
||||||
|
[InlineData("binary_sensor.sm_s936b_battery_level", "battery", false)]
|
||||||
|
[InlineData("sensor.bathroom_temperature", "temperature", false)]
|
||||||
|
[InlineData("sensor.no_device_class", null, false)]
|
||||||
|
[InlineData("sensor.bathroom_battery", "", false)]
|
||||||
|
[InlineData("sensorx.bathroom_battery", "battery", false)]
|
||||||
|
[InlineData("sensor", "battery", false)]
|
||||||
|
[InlineData("switch.bathroom_battery", "battery", false)]
|
||||||
|
public void IsBatterySensor_ShouldClassifyEntities(string entityId, string? deviceClass, bool expected)
|
||||||
{
|
{
|
||||||
SetupEntities(("sensor.bathroom_battery", "battery", "50", "Bathroom Battery"));
|
SetupEntities(Sensor(entityId, deviceClass, "50", "Some Entity"));
|
||||||
|
|
||||||
|
var entity = new Entity(_haContextMock.Object, entityId);
|
||||||
|
|
||||||
|
BatterySensorDiscoveryService.IsBatterySensor(entity).Should().Be(expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IsBatterySensor_WhenEntityHasNoState_ShouldReturnFalse()
|
||||||
|
{
|
||||||
|
SetupEntities(new EntitySpec { EntityId = "sensor.bathroom_battery", HasState = false });
|
||||||
|
|
||||||
var entity = new Entity(_haContextMock.Object, "sensor.bathroom_battery");
|
var entity = new Entity(_haContextMock.Object, "sensor.bathroom_battery");
|
||||||
|
|
||||||
BatterySensorDiscoveryService.IsBatterySensor(entity).Should().BeTrue();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void IsBatterySensor_WithNonSensorDomain_ShouldReturnFalse()
|
|
||||||
{
|
|
||||||
SetupEntities(("binary_sensor.bathroom_battery", "battery", "50", "Bathroom Battery"));
|
|
||||||
var entity = new Entity(_haContextMock.Object, "binary_sensor.bathroom_battery");
|
|
||||||
|
|
||||||
BatterySensorDiscoveryService.IsBatterySensor(entity).Should().BeFalse();
|
|
||||||
}
|
|
||||||
|
|
||||||
[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();
|
BatterySensorDiscoveryService.IsBatterySensor(entity).Should().BeFalse();
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#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
|
|
||||||
}
|
}
|
||||||
@@ -19,9 +19,9 @@
|
|||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.5" />
|
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="11.0.0"/>
|
||||||
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.11.0" />
|
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.43.1"/>
|
||||||
<PackageReference Include="NetDaemon.HassModel" Version="26.11.0" />
|
<PackageReference Include="NetDaemon.HassModel" Version="26.43.1"/>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
@@ -1,21 +1,26 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
using System.Reactive.Concurrency;
|
using System.Reactive.Concurrency;
|
||||||
|
using BatteryMonitor.Models;
|
||||||
|
using BatteryMonitorManager.Interface;
|
||||||
|
using BatteryMonitorManager.Models;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
using NetDaemon.AppModel;
|
using NetDaemon.AppModel;
|
||||||
using NetDaemon.Extensions.Scheduler;
|
using NetDaemon.Extensions.Scheduler;
|
||||||
using BatteryMonitorManager.Interface;
|
|
||||||
using BatteryMonitorManager.Models;
|
#endregion
|
||||||
|
|
||||||
namespace BatteryMonitorManager;
|
namespace BatteryMonitorManager;
|
||||||
|
|
||||||
[NetDaemonApp]
|
[NetDaemonApp]
|
||||||
public sealed class BatteryMonitorInit : IBatteryMonitorInit
|
public sealed class BatteryMonitorInit
|
||||||
{
|
{
|
||||||
private readonly ILogger<BatteryMonitorInit> _logger;
|
|
||||||
private readonly IScheduler _scheduler;
|
|
||||||
private readonly IBatterySensorDiscoveryService _discoveryService;
|
private readonly IBatterySensorDiscoveryService _discoveryService;
|
||||||
|
private readonly ILogger<BatteryMonitorInit> _logger;
|
||||||
private readonly IBatteryNotificationService _notificationService;
|
private readonly IBatteryNotificationService _notificationService;
|
||||||
private readonly BatteryMonitorOptions _options;
|
private readonly BatteryMonitorOptions _options;
|
||||||
|
private readonly IScheduler _scheduler;
|
||||||
|
|
||||||
public BatteryMonitorInit(
|
public BatteryMonitorInit(
|
||||||
ILogger<BatteryMonitorInit> logger,
|
ILogger<BatteryMonitorInit> logger,
|
||||||
@@ -46,7 +51,7 @@ public sealed class BatteryMonitorInit : IBatteryMonitorInit
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task InitializeAsync()
|
private async Task InitializeAsync()
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
@@ -54,18 +59,23 @@ public sealed class BatteryMonitorInit : IBatteryMonitorInit
|
|||||||
|
|
||||||
CheckAndNotify();
|
CheckAndNotify();
|
||||||
|
|
||||||
_logger.LogInformation("BatteryMonitor initialized with threshold {Threshold}%", _options.BatteryThresholdPercent);
|
if (_logger.IsEnabled(LogLevel.Information))
|
||||||
|
{
|
||||||
|
_logger.LogInformation("BatteryMonitor initialized with threshold {Threshold}%",
|
||||||
|
_options.BatteryThresholdPercent);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
_logger.LogError(ex, "Error initializing BatteryMonitor");
|
_logger.LogError(ex, "Error initializing BatteryMonitor");
|
||||||
|
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void ScheduleDailyCheck()
|
private void ScheduleDailyCheck()
|
||||||
{
|
{
|
||||||
_scheduler.ScheduleCron(BatteryMonitor.Models.BatteryMonitorConsts.DailyCheckCron, () =>
|
_scheduler.ScheduleCron(BatteryMonitorConsts.DailyCheckCron, () =>
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
@@ -81,7 +91,7 @@ public sealed class BatteryMonitorInit : IBatteryMonitorInit
|
|||||||
_logger.LogInformation("Scheduled daily battery check at 08:00");
|
_logger.LogInformation("Scheduled daily battery check at 08:00");
|
||||||
}
|
}
|
||||||
|
|
||||||
internal void CheckAndNotify()
|
private void CheckAndNotify()
|
||||||
{
|
{
|
||||||
var lowBatteryDevices = _discoveryService.DiscoverLowBatterySensors(_options.BatteryThresholdPercent);
|
var lowBatteryDevices = _discoveryService.DiscoverLowBatterySensors(_options.BatteryThresholdPercent);
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,12 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using BatteryMonitorManager.Interface;
|
||||||
|
using BatteryMonitorManager.Models;
|
||||||
using Microsoft.Extensions.Configuration;
|
using Microsoft.Extensions.Configuration;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using NetDaemon.AppModel;
|
using NetDaemon.AppModel;
|
||||||
using BatteryMonitorManager.Interface;
|
|
||||||
using BatteryMonitorManager.Models;
|
#endregion
|
||||||
|
|
||||||
namespace BatteryMonitorManager;
|
namespace BatteryMonitorManager;
|
||||||
|
|
||||||
@@ -12,7 +16,8 @@ public static class BatteryMonitorServiceRegistration
|
|||||||
{
|
{
|
||||||
var options = configuration
|
var options = configuration
|
||||||
.GetSection(BatteryMonitorOptions.SectionName)
|
.GetSection(BatteryMonitorOptions.SectionName)
|
||||||
.Get<BatteryMonitorOptions>() ?? new BatteryMonitorOptions();
|
.Get<BatteryMonitorOptions>() ??
|
||||||
|
new BatteryMonitorOptions();
|
||||||
|
|
||||||
if (!options.Enabled)
|
if (!options.Enabled)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,24 +1,19 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using Microsoft.Extensions.Logging;
|
|
||||||
using NetDaemon.HassModel;
|
|
||||||
using BatteryMonitor.Models;
|
using BatteryMonitor.Models;
|
||||||
using BatteryMonitorManager.Interface;
|
using BatteryMonitorManager.Interface;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using NetDaemon.HassModel;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace BatteryMonitorManager;
|
namespace BatteryMonitorManager;
|
||||||
|
|
||||||
public sealed class BatteryNotificationService : IBatteryNotificationService
|
public sealed class BatteryNotificationService(
|
||||||
{
|
|
||||||
private readonly IHaContext _haContext;
|
|
||||||
private readonly ILogger<BatteryNotificationService> _logger;
|
|
||||||
|
|
||||||
public BatteryNotificationService(
|
|
||||||
IHaContext haContext,
|
IHaContext haContext,
|
||||||
ILogger<BatteryNotificationService> logger)
|
ILogger<BatteryNotificationService> logger) : IBatteryNotificationService
|
||||||
{
|
{
|
||||||
_haContext = haContext;
|
|
||||||
_logger = logger;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void NotifyLowBattery(IReadOnlyList<BatterySensorInfo> lowBatteryDevices)
|
public void NotifyLowBattery(IReadOnlyList<BatterySensorInfo> lowBatteryDevices)
|
||||||
{
|
{
|
||||||
if (lowBatteryDevices.Count == 0)
|
if (lowBatteryDevices.Count == 0)
|
||||||
@@ -28,7 +23,7 @@ public sealed class BatteryNotificationService : IBatteryNotificationService
|
|||||||
|
|
||||||
var message = BuildNotificationMessage(lowBatteryDevices);
|
var message = BuildNotificationMessage(lowBatteryDevices);
|
||||||
|
|
||||||
_haContext.CallService(
|
haContext.CallService(
|
||||||
BatteryMonitorConsts.PersistentNotificationDomain,
|
BatteryMonitorConsts.PersistentNotificationDomain,
|
||||||
BatteryMonitorConsts.PersistentNotificationCreateService,
|
BatteryMonitorConsts.PersistentNotificationCreateService,
|
||||||
data: new
|
data: new
|
||||||
@@ -38,14 +33,17 @@ public sealed class BatteryNotificationService : IBatteryNotificationService
|
|||||||
notification_id = BatteryMonitorConsts.NotificationId
|
notification_id = BatteryMonitorConsts.NotificationId
|
||||||
});
|
});
|
||||||
|
|
||||||
_logger.LogInformation(
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
|
{
|
||||||
|
logger.LogInformation(
|
||||||
"Sent low battery notification for {Count} device(s)",
|
"Sent low battery notification for {Count} device(s)",
|
||||||
lowBatteryDevices.Count);
|
lowBatteryDevices.Count);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public void DismissNotification()
|
public void DismissNotification()
|
||||||
{
|
{
|
||||||
_haContext.CallService(
|
haContext.CallService(
|
||||||
BatteryMonitorConsts.PersistentNotificationDomain,
|
BatteryMonitorConsts.PersistentNotificationDomain,
|
||||||
BatteryMonitorConsts.PersistentNotificationDismissService,
|
BatteryMonitorConsts.PersistentNotificationDismissService,
|
||||||
data: new
|
data: new
|
||||||
@@ -53,7 +51,7 @@ public sealed class BatteryNotificationService : IBatteryNotificationService
|
|||||||
notification_id = BatteryMonitorConsts.NotificationId
|
notification_id = BatteryMonitorConsts.NotificationId
|
||||||
});
|
});
|
||||||
|
|
||||||
_logger.LogDebug("Dismissed low battery notification");
|
logger.LogDebug("Dismissed low battery notification");
|
||||||
}
|
}
|
||||||
|
|
||||||
internal static string BuildNotificationMessage(IReadOnlyList<BatterySensorInfo> devices)
|
internal static string BuildNotificationMessage(IReadOnlyList<BatterySensorInfo> devices)
|
||||||
|
|||||||
@@ -1,29 +1,24 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
using System.Globalization;
|
using System.Globalization;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
|
using BatteryMonitor.Models;
|
||||||
|
using BatteryMonitorManager.Interface;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using NetDaemon.HassModel;
|
using NetDaemon.HassModel;
|
||||||
using NetDaemon.HassModel.Entities;
|
using NetDaemon.HassModel.Entities;
|
||||||
using BatteryMonitor.Models;
|
|
||||||
using BatteryMonitorManager.Interface;
|
#endregion
|
||||||
|
|
||||||
namespace BatteryMonitorManager;
|
namespace BatteryMonitorManager;
|
||||||
|
|
||||||
public sealed class BatterySensorDiscoveryService : IBatterySensorDiscoveryService
|
public sealed class BatterySensorDiscoveryService(
|
||||||
{
|
|
||||||
private readonly IHaContext _haContext;
|
|
||||||
private readonly ILogger<BatterySensorDiscoveryService> _logger;
|
|
||||||
|
|
||||||
public BatterySensorDiscoveryService(
|
|
||||||
IHaContext haContext,
|
IHaContext haContext,
|
||||||
ILogger<BatterySensorDiscoveryService> logger)
|
ILogger<BatterySensorDiscoveryService> logger) : IBatterySensorDiscoveryService
|
||||||
{
|
{
|
||||||
_haContext = haContext;
|
|
||||||
_logger = logger;
|
|
||||||
}
|
|
||||||
|
|
||||||
public IReadOnlyList<BatterySensorInfo> DiscoverLowBatterySensors(int thresholdPercent)
|
public IReadOnlyList<BatterySensorInfo> DiscoverLowBatterySensors(int thresholdPercent)
|
||||||
{
|
{
|
||||||
var allEntities = _haContext.GetAllEntities();
|
var allEntities = haContext.GetAllEntities();
|
||||||
|
|
||||||
var lowBatterySensors = allEntities
|
var lowBatterySensors = allEntities
|
||||||
.Where(IsBatterySensor)
|
.Where(IsBatterySensor)
|
||||||
@@ -32,9 +27,12 @@ public sealed class BatterySensorDiscoveryService : IBatterySensorDiscoveryServi
|
|||||||
.Where(info => info is not null)
|
.Where(info => info is not null)
|
||||||
.ToList();
|
.ToList();
|
||||||
|
|
||||||
_logger.LogInformation(
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
|
{
|
||||||
|
logger.LogInformation(
|
||||||
"Battery check: found {Count} sensors below {Threshold}%",
|
"Battery check: found {Count} sensors below {Threshold}%",
|
||||||
lowBatterySensors.Count, thresholdPercent);
|
lowBatterySensors.Count, thresholdPercent);
|
||||||
|
}
|
||||||
|
|
||||||
return lowBatterySensors!;
|
return lowBatterySensors!;
|
||||||
}
|
}
|
||||||
@@ -65,13 +63,23 @@ public sealed class BatterySensorDiscoveryService : IBatterySensorDiscoveryServi
|
|||||||
|
|
||||||
if (state is null or "unavailable" or "unknown")
|
if (state is null or "unavailable" or "unknown")
|
||||||
{
|
{
|
||||||
_logger.LogDebug("Skipping battery sensor {EntityId}: state is {State}", entity.EntityId, state ?? "null");
|
if (logger.IsEnabled(LogLevel.Debug))
|
||||||
|
{
|
||||||
|
logger.LogDebug("Skipping battery sensor {EntityId}: state is {State}", entity.EntityId,
|
||||||
|
state ?? "null");
|
||||||
|
}
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!double.TryParse(state, CultureInfo.InvariantCulture, out var batteryLevel))
|
if (!double.TryParse(state, CultureInfo.InvariantCulture, out var batteryLevel))
|
||||||
{
|
{
|
||||||
_logger.LogDebug("Skipping battery sensor {EntityId}: unable to parse state '{State}'", entity.EntityId, state);
|
if (logger.IsEnabled(LogLevel.Debug))
|
||||||
|
{
|
||||||
|
logger.LogDebug("Skipping battery sensor {EntityId}: unable to parse state '{State}'", entity.EntityId,
|
||||||
|
state);
|
||||||
|
}
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -80,8 +88,7 @@ public sealed class BatterySensorDiscoveryService : IBatterySensorDiscoveryServi
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
var friendlyName = GetJsonStringProperty(entity.EntityState?.AttributesJson, "friendly_name")
|
var friendlyName = GetJsonStringProperty(entity.EntityState?.AttributesJson, "friendly_name") ?? entity.EntityId;
|
||||||
?? entity.EntityId;
|
|
||||||
|
|
||||||
return new BatterySensorInfo
|
return new BatterySensorInfo
|
||||||
{
|
{
|
||||||
@@ -91,7 +98,7 @@ public sealed class BatterySensorDiscoveryService : IBatterySensorDiscoveryServi
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
internal static string? GetJsonStringProperty(JsonElement? element, string propertyName)
|
private static string? GetJsonStringProperty(JsonElement? element, string propertyName)
|
||||||
{
|
{
|
||||||
if (element is null)
|
if (element is null)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,6 +0,0 @@
|
|||||||
namespace BatteryMonitorManager.Interface;
|
|
||||||
|
|
||||||
public interface IBatteryMonitorInit
|
|
||||||
{
|
|
||||||
Task InitializeAsync();
|
|
||||||
}
|
|
||||||
@@ -1,5 +1,9 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
using BatteryMonitor.Models;
|
using BatteryMonitor.Models;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace BatteryMonitorManager.Interface;
|
namespace BatteryMonitorManager.Interface;
|
||||||
|
|
||||||
public interface IBatteryNotificationService
|
public interface IBatteryNotificationService
|
||||||
|
|||||||
@@ -1,5 +1,9 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
using BatteryMonitor.Models;
|
using BatteryMonitor.Models;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace BatteryMonitorManager.Interface;
|
namespace BatteryMonitorManager.Interface;
|
||||||
|
|
||||||
public interface IBatterySensorDiscoveryService
|
public interface IBatterySensorDiscoveryService
|
||||||
|
|||||||
@@ -1,12 +1,16 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
using BatteryMonitor.Models;
|
using BatteryMonitor.Models;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace BatteryMonitorManager.Models;
|
namespace BatteryMonitorManager.Models;
|
||||||
|
|
||||||
public sealed class BatteryMonitorOptions
|
public sealed class BatteryMonitorOptions
|
||||||
{
|
{
|
||||||
public const string SectionName = "BatteryMonitor";
|
public const string SectionName = "BatteryMonitor";
|
||||||
|
|
||||||
public bool Enabled { get; set; }
|
public bool Enabled { get; init; }
|
||||||
|
|
||||||
public int BatteryThresholdPercent { get; set; } = BatteryMonitorConsts.DefaultBatteryThresholdPercent;
|
public int BatteryThresholdPercent { get; init; } = BatteryMonitorConsts.DefaultBatteryThresholdPercent;
|
||||||
}
|
}
|
||||||
@@ -1,21 +1,52 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
using BoilerMonitor.Models.Enums;
|
using BoilerMonitor.Models.Enums;
|
||||||
|
using BoilerMonitorManager;
|
||||||
using FluentAssertions;
|
using FluentAssertions;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using Moq;
|
using Moq;
|
||||||
using BoilerMonitorManager;
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace BoilerMonitor.Manager.Tests;
|
namespace BoilerMonitor.Manager.Tests;
|
||||||
|
|
||||||
public class BoilerControlServiceTests
|
public class BoilerControlServiceTests
|
||||||
{
|
{
|
||||||
private readonly BoilerControlService _sut;
|
private readonly Mock<ILogger<BoilerControlService>> _loggerMock = new Mock<ILogger<BoilerControlService>>();
|
||||||
|
|
||||||
public BoilerControlServiceTests()
|
private BoilerControlService CreateSut()
|
||||||
{
|
{
|
||||||
var loggerMock = new Mock<ILogger<BoilerControlService>>();
|
return new BoilerControlService(_loggerMock.Object);
|
||||||
_sut = new BoilerControlService(loggerMock.Object);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#region NoChange scenarios
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(true, false, "on", false, false)]
|
||||||
|
[InlineData(false, false, "off", false, false)]
|
||||||
|
[InlineData(false, false, null, false, false)]
|
||||||
|
[InlineData(false, false, "unavailable", false, false)]
|
||||||
|
[InlineData(true, true, "off", false, false)]
|
||||||
|
[InlineData(true, true, null, false, false)]
|
||||||
|
[InlineData(true, false, "off", true, false)]
|
||||||
|
[InlineData(true, false, "off ", true, false)]
|
||||||
|
[InlineData(true, true, "off", true, true)]
|
||||||
|
public void DetermineAction_WhenDesiredStateMatchesCurrentState_ShouldReturnNoChange(
|
||||||
|
bool isNowCheap,
|
||||||
|
bool waterReady,
|
||||||
|
string? switchState,
|
||||||
|
bool budgetExhausted,
|
||||||
|
bool budgetOverride)
|
||||||
|
{
|
||||||
|
var result = CreateSut()
|
||||||
|
.DetermineAction(
|
||||||
|
isNowCheap, waterReady, switchState, budgetExhausted, budgetOverride);
|
||||||
|
|
||||||
|
result.Should().Be(BoilerAction.NoChange);
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
#region TurnOn scenarios
|
#region TurnOn scenarios
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
@@ -23,129 +54,157 @@ public class BoilerControlServiceTests
|
|||||||
[InlineData("OFF")]
|
[InlineData("OFF")]
|
||||||
[InlineData("Off")]
|
[InlineData("Off")]
|
||||||
[InlineData(null)]
|
[InlineData(null)]
|
||||||
|
[InlineData("")]
|
||||||
|
[InlineData(" ")]
|
||||||
|
[InlineData("off ")]
|
||||||
[InlineData("unavailable")]
|
[InlineData("unavailable")]
|
||||||
|
[InlineData("unknown")]
|
||||||
|
[InlineData("0")]
|
||||||
public void DetermineAction_WhenCheapAndWaterNotReadyAndBudgetAvailable_ShouldReturnTurnOn(string? switchState)
|
public void DetermineAction_WhenCheapAndWaterNotReadyAndBudgetAvailable_ShouldReturnTurnOn(string? switchState)
|
||||||
{
|
{
|
||||||
var result = _sut.DetermineAction(
|
var result = CreateSut()
|
||||||
isNowCheap: true, waterReady: false, currentSwitchState: switchState,
|
.DetermineAction(
|
||||||
budgetExhausted: false, budgetOverride: false);
|
true, false, switchState,
|
||||||
|
false, false);
|
||||||
|
|
||||||
result.Should().Be(BoilerAction.TurnOn);
|
result.Should().Be(BoilerAction.TurnOn);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
[InlineData("off")]
|
[InlineData("off", BoilerAction.TurnOn)]
|
||||||
[InlineData(null)]
|
[InlineData(null, BoilerAction.TurnOn)]
|
||||||
public void DetermineAction_WhenBudgetExhaustedButOverrideOn_ShouldReturnTurnOn(string? switchState)
|
[InlineData("unavailable", BoilerAction.TurnOn)]
|
||||||
|
[InlineData("on", BoilerAction.NoChange)]
|
||||||
|
[InlineData("On", BoilerAction.NoChange)]
|
||||||
|
[InlineData("ON", BoilerAction.NoChange)]
|
||||||
|
public void DetermineAction_WhenBudgetExhaustedButOverrideOn_ShouldReturnTurnOnOnlyIfNotAlreadyOn(
|
||||||
|
string? switchState,
|
||||||
|
BoilerAction expectedAction)
|
||||||
{
|
{
|
||||||
var result = _sut.DetermineAction(
|
var result = CreateSut()
|
||||||
isNowCheap: true, waterReady: false, currentSwitchState: switchState,
|
.DetermineAction(
|
||||||
budgetExhausted: true, budgetOverride: true);
|
true, false, switchState,
|
||||||
|
true, true);
|
||||||
|
|
||||||
result.Should().Be(BoilerAction.TurnOn);
|
result.Should().Be(expectedAction);
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
#region TurnOff scenarios
|
#region TurnOff scenarios
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void DetermineAction_WhenNotCheapAndSwitchIsOn_ShouldReturnTurnOff()
|
|
||||||
{
|
|
||||||
var result = _sut.DetermineAction(
|
|
||||||
isNowCheap: false, waterReady: false, currentSwitchState: "on",
|
|
||||||
budgetExhausted: false, budgetOverride: false);
|
|
||||||
|
|
||||||
result.Should().Be(BoilerAction.TurnOff);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void DetermineAction_WhenWaterReadyAndSwitchIsOn_ShouldReturnTurnOff()
|
|
||||||
{
|
|
||||||
var result = _sut.DetermineAction(
|
|
||||||
isNowCheap: true, waterReady: true, currentSwitchState: "on",
|
|
||||||
budgetExhausted: false, budgetOverride: false);
|
|
||||||
|
|
||||||
result.Should().Be(BoilerAction.TurnOff);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void DetermineAction_WhenBudgetExhaustedAndNoOverride_ShouldReturnTurnOff()
|
|
||||||
{
|
|
||||||
var result = _sut.DetermineAction(
|
|
||||||
isNowCheap: true, waterReady: false, currentSwitchState: "on",
|
|
||||||
budgetExhausted: true, budgetOverride: false);
|
|
||||||
|
|
||||||
result.Should().Be(BoilerAction.TurnOff);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
[InlineData("on")]
|
[InlineData("on")]
|
||||||
[InlineData("ON")]
|
[InlineData("ON")]
|
||||||
[InlineData("On")]
|
[InlineData("On")]
|
||||||
public void DetermineAction_WhenNotCheapAndSwitchIsOnCaseInsensitive_ShouldReturnTurnOff(string switchState)
|
[InlineData("oN")]
|
||||||
|
public void DetermineAction_WhenNotCheapAndSwitchIsOn_ShouldReturnTurnOff(string switchState)
|
||||||
{
|
{
|
||||||
var result = _sut.DetermineAction(
|
var result = CreateSut()
|
||||||
isNowCheap: false, waterReady: false, currentSwitchState: switchState,
|
.DetermineAction(
|
||||||
budgetExhausted: false, budgetOverride: false);
|
false, false, switchState,
|
||||||
|
false, false);
|
||||||
|
|
||||||
|
result.Should().Be(BoilerAction.TurnOff);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(true, false, false)] // water ready
|
||||||
|
[InlineData(false, true, false)] // budget exhausted, no override
|
||||||
|
[InlineData(true, true, true)] // water ready wins over the budget override
|
||||||
|
public void DetermineAction_WhenCheapButShouldNotHeatAndSwitchIsOn_ShouldReturnTurnOff(
|
||||||
|
bool waterReady,
|
||||||
|
bool budgetExhausted,
|
||||||
|
bool budgetOverride)
|
||||||
|
{
|
||||||
|
var result = CreateSut()
|
||||||
|
.DetermineAction(
|
||||||
|
true, waterReady, "on",
|
||||||
|
budgetExhausted, budgetOverride);
|
||||||
|
|
||||||
result.Should().Be(BoilerAction.TurnOff);
|
result.Should().Be(BoilerAction.TurnOff);
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
#region NoChange scenarios
|
#region Comprehensive truth tables
|
||||||
|
|
||||||
[Fact]
|
/// <summary>
|
||||||
public void DetermineAction_WhenCheapAndNotReadyAndAlreadyOn_ShouldReturnNoChange()
|
/// Complete truth table for a boiler that is currently ON: it may only stay on when
|
||||||
|
/// it is cheap, water is not ready and the budget is available (or overridden).
|
||||||
|
/// </summary>
|
||||||
|
public static TheoryData<bool, bool, bool, bool, BoilerAction> SwitchOnActionMatrix => new TheoryData<bool, bool, bool, bool, BoilerAction>
|
||||||
{
|
{
|
||||||
var result = _sut.DetermineAction(
|
{ false, false, false, false, BoilerAction.TurnOff },
|
||||||
isNowCheap: true, waterReady: false, currentSwitchState: "on",
|
{ false, false, false, true, BoilerAction.TurnOff },
|
||||||
budgetExhausted: false, budgetOverride: false);
|
{ false, false, true, false, BoilerAction.TurnOff },
|
||||||
|
{ false, false, true, true, BoilerAction.TurnOff },
|
||||||
result.Should().Be(BoilerAction.NoChange);
|
{ false, true, false, false, BoilerAction.TurnOff },
|
||||||
}
|
{ false, true, false, true, BoilerAction.TurnOff },
|
||||||
|
{ false, true, true, false, BoilerAction.TurnOff },
|
||||||
[Fact]
|
{ false, true, true, true, BoilerAction.TurnOff },
|
||||||
public void DetermineAction_WhenNotCheapAndAlreadyOff_ShouldReturnNoChange()
|
{ true, false, false, false, BoilerAction.NoChange },
|
||||||
{
|
{ true, false, false, true, BoilerAction.NoChange },
|
||||||
var result = _sut.DetermineAction(
|
{ true, false, true, false, BoilerAction.TurnOff },
|
||||||
isNowCheap: false, waterReady: false, currentSwitchState: "off",
|
{ true, false, true, true, BoilerAction.NoChange },
|
||||||
budgetExhausted: false, budgetOverride: false);
|
{ true, true, false, false, BoilerAction.TurnOff },
|
||||||
|
{ true, true, false, true, BoilerAction.TurnOff },
|
||||||
result.Should().Be(BoilerAction.NoChange);
|
{ true, true, true, false, BoilerAction.TurnOff },
|
||||||
}
|
{ true, true, true, true, BoilerAction.TurnOff }
|
||||||
|
};
|
||||||
[Fact]
|
|
||||||
public void DetermineAction_WhenBudgetExhaustedAndAlreadyOff_ShouldReturnNoChange()
|
|
||||||
{
|
|
||||||
var result = _sut.DetermineAction(
|
|
||||||
isNowCheap: true, waterReady: false, currentSwitchState: "off",
|
|
||||||
budgetExhausted: true, budgetOverride: false);
|
|
||||||
|
|
||||||
result.Should().Be(BoilerAction.NoChange);
|
|
||||||
}
|
|
||||||
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
#region Comprehensive theory covering all key combinations
|
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
[InlineData(true, false, "off", false, false, BoilerAction.TurnOn)]
|
[MemberData(nameof(SwitchOnActionMatrix))]
|
||||||
[InlineData(true, false, "on", false, false, BoilerAction.NoChange)]
|
public void DetermineAction_AllCombinationsWhileSwitchIsOn_ShouldReturnExpectedAction(
|
||||||
[InlineData(true, true, "on", false, false, BoilerAction.TurnOff)]
|
bool isNowCheap,
|
||||||
[InlineData(true, true, "off", false, false, BoilerAction.NoChange)]
|
bool waterReady,
|
||||||
[InlineData(false, false, "on", false, false, BoilerAction.TurnOff)]
|
bool budgetExhausted,
|
||||||
[InlineData(false, false, "off", false, false, BoilerAction.NoChange)]
|
bool budgetOverride,
|
||||||
[InlineData(true, false, "on", true, false, BoilerAction.TurnOff)]
|
BoilerAction expectedAction)
|
||||||
[InlineData(true, false, "off", true, false, BoilerAction.NoChange)]
|
|
||||||
[InlineData(true, false, "off", true, true, BoilerAction.TurnOn)]
|
|
||||||
[InlineData(true, false, "on", true, true, BoilerAction.NoChange)]
|
|
||||||
public void DetermineAction_AllCombinations_ShouldReturnExpectedAction(
|
|
||||||
bool isNowCheap, bool waterReady, string switchState,
|
|
||||||
bool budgetExhausted, bool budgetOverride, BoilerAction expectedAction)
|
|
||||||
{
|
{
|
||||||
var result = _sut.DetermineAction(isNowCheap, waterReady, switchState, budgetExhausted, budgetOverride);
|
var result = CreateSut()
|
||||||
|
.DetermineAction(
|
||||||
|
isNowCheap, waterReady, "on", budgetExhausted, budgetOverride);
|
||||||
|
|
||||||
|
result.Should().Be(expectedAction);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Complete truth table for a boiler that is currently OFF: it may only turn on when
|
||||||
|
/// it is cheap, water is not ready and the budget is available (or overridden).
|
||||||
|
/// </summary>
|
||||||
|
public static TheoryData<bool, bool, bool, bool, BoilerAction> SwitchOffActionMatrix => new TheoryData<bool, bool, bool, bool, BoilerAction>
|
||||||
|
{
|
||||||
|
{ false, false, false, false, BoilerAction.NoChange },
|
||||||
|
{ false, false, false, true, BoilerAction.NoChange },
|
||||||
|
{ false, false, true, false, BoilerAction.NoChange },
|
||||||
|
{ false, false, true, true, BoilerAction.NoChange },
|
||||||
|
{ false, true, false, false, BoilerAction.NoChange },
|
||||||
|
{ false, true, false, true, BoilerAction.NoChange },
|
||||||
|
{ false, true, true, false, BoilerAction.NoChange },
|
||||||
|
{ false, true, true, true, BoilerAction.NoChange },
|
||||||
|
{ true, false, false, false, BoilerAction.TurnOn },
|
||||||
|
{ true, false, false, true, BoilerAction.TurnOn },
|
||||||
|
{ true, false, true, false, BoilerAction.NoChange },
|
||||||
|
{ true, false, true, true, BoilerAction.TurnOn },
|
||||||
|
{ true, true, false, false, BoilerAction.NoChange },
|
||||||
|
{ true, true, false, true, BoilerAction.NoChange },
|
||||||
|
{ true, true, true, false, BoilerAction.NoChange },
|
||||||
|
{ true, true, true, true, BoilerAction.NoChange }
|
||||||
|
};
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(SwitchOffActionMatrix))]
|
||||||
|
public void DetermineAction_AllCombinationsWhileSwitchIsOff_ShouldReturnExpectedAction(
|
||||||
|
bool isNowCheap,
|
||||||
|
bool waterReady,
|
||||||
|
bool budgetExhausted,
|
||||||
|
bool budgetOverride,
|
||||||
|
BoilerAction expectedAction)
|
||||||
|
{
|
||||||
|
var result = CreateSut()
|
||||||
|
.DetermineAction(
|
||||||
|
isNowCheap, waterReady, "off", budgetExhausted, budgetOverride);
|
||||||
|
|
||||||
result.Should().Be(expectedAction);
|
result.Should().Be(expectedAction);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,22 +8,22 @@
|
|||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="coverlet.collector" Version="8.0.0">
|
<PackageReference Include="coverlet.collector" Version="10.1.1">
|
||||||
<PrivateAssets>all</PrivateAssets>
|
<PrivateAssets>all</PrivateAssets>
|
||||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
</PackageReference>
|
</PackageReference>
|
||||||
<PackageReference Include="Microsoft.Extensions.TimeProvider.Testing" Version="10.4.0" />
|
<PackageReference Include="Microsoft.Extensions.TimeProvider.Testing" Version="11.0.1"/>
|
||||||
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.3.0" />
|
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.12.0"/>
|
||||||
<PackageReference Include="xunit" Version="2.9.3"/>
|
<PackageReference Include="xunit" Version="2.9.3"/>
|
||||||
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5">
|
<PackageReference Include="xunit.runner.visualstudio" Version="4.0.1">
|
||||||
<PrivateAssets>all</PrivateAssets>
|
<PrivateAssets>all</PrivateAssets>
|
||||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
</PackageReference>
|
</PackageReference>
|
||||||
<PackageReference Include="FluentAssertions" Version="8.8.0" />
|
<PackageReference Include="FluentAssertions" Version="8.11.0"/>
|
||||||
<PackageReference Include="Moq" Version="4.20.72" />
|
<PackageReference Include="Moq" Version="4.21.0"/>
|
||||||
<PackageReference Include="NetDaemon.Extensions.Mqtt" Version="26.11.0" />
|
<PackageReference Include="NetDaemon.Extensions.Mqtt" Version="26.43.1"/>
|
||||||
<PackageReference Include="NetDaemon.HassModel" Version="26.11.0" />
|
<PackageReference Include="NetDaemon.HassModel" Version="26.43.1"/>
|
||||||
<PackageReference Include="System.Reactive" Version="6.1.0" />
|
<PackageReference Include="System.Reactive" Version="7.0.0"/>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
|||||||
@@ -1,133 +1,74 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
using FluentAssertions;
|
using FluentAssertions;
|
||||||
using BoilerMonitorManager.Models;
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace BoilerMonitor.Manager.Tests;
|
namespace BoilerMonitor.Manager.Tests;
|
||||||
|
|
||||||
public class BoilerMonitorConfigTests
|
public class BoilerMonitorConfigTests
|
||||||
{
|
{
|
||||||
[Fact]
|
private const string PowerEntityId = BoilerMonitorTestData.PowerEntityId;
|
||||||
public void IsFullyConfigured_WhenAllFieldsSet_ShouldReturnTrue()
|
private const string SwitchEntityId = BoilerMonitorTestData.SwitchEntityId;
|
||||||
|
|
||||||
|
public static TheoryData<string, string?, string?, int?, double?, bool> ConfigurationCases => new TheoryData<string, string?, string?, int?, double?, bool>
|
||||||
{
|
{
|
||||||
var config = new BoilerMonitorConfig
|
{ "fully configured", PowerEntityId, SwitchEntityId, 30, 5.0, true },
|
||||||
{
|
{ "minimum valid poll interval and threshold", PowerEntityId, SwitchEntityId, 5, 1.0, true },
|
||||||
BoilerPowerEntityId = "sensor.sonoff_1002230e32_power",
|
{ "poll interval of one second", PowerEntityId, SwitchEntityId, 1, 5.0, true },
|
||||||
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
|
{ "maximum poll interval", PowerEntityId, SwitchEntityId, int.MaxValue, 5.0, true },
|
||||||
PollIntervalSeconds = 30,
|
{ "smallest positive threshold", PowerEntityId, SwitchEntityId, 30, double.Epsilon, true },
|
||||||
HeatingPowerThresholdWatts = 5.0
|
{ "maximum threshold", PowerEntityId, SwitchEntityId, 30, double.MaxValue, true },
|
||||||
|
{ "infinite threshold", PowerEntityId, SwitchEntityId, 30, double.PositiveInfinity, true },
|
||||||
|
|
||||||
|
{ "power entity id null", null, SwitchEntityId, 30, 5.0, false },
|
||||||
|
{ "power entity id empty", string.Empty, SwitchEntityId, 30, 5.0, false },
|
||||||
|
{ "power entity id whitespace", " ", SwitchEntityId, 30, 5.0, false },
|
||||||
|
{ "power entity id tabs and newlines", "\t\n", SwitchEntityId, 30, 5.0, false },
|
||||||
|
{ "switch entity id null", PowerEntityId, null, 30, 5.0, false },
|
||||||
|
{ "switch entity id empty", PowerEntityId, string.Empty, 30, 5.0, false },
|
||||||
|
{ "switch entity id whitespace", PowerEntityId, " ", 30, 5.0, false },
|
||||||
|
{ "both entity ids null", null, null, 30, 5.0, false },
|
||||||
|
|
||||||
|
{ "poll interval null", PowerEntityId, SwitchEntityId, null, 5.0, false },
|
||||||
|
{ "poll interval zero", PowerEntityId, SwitchEntityId, 0, 5.0, false },
|
||||||
|
{ "poll interval negative", PowerEntityId, SwitchEntityId, -1, 5.0, false },
|
||||||
|
{ "poll interval minimum value", PowerEntityId, SwitchEntityId, int.MinValue, 5.0, false },
|
||||||
|
|
||||||
|
{ "threshold null", PowerEntityId, SwitchEntityId, 30, null, false },
|
||||||
|
{ "threshold zero", PowerEntityId, SwitchEntityId, 30, 0.0, false },
|
||||||
|
{ "threshold negative", PowerEntityId, SwitchEntityId, 30, -1.0, false },
|
||||||
|
{ "threshold minimum value", PowerEntityId, SwitchEntityId, 30, double.MinValue, false },
|
||||||
|
{ "threshold NaN", PowerEntityId, SwitchEntityId, 30, double.NaN, false },
|
||||||
|
{ "threshold negative infinity", PowerEntityId, SwitchEntityId, 30, double.NegativeInfinity, false }
|
||||||
};
|
};
|
||||||
|
|
||||||
config.IsFullyConfigured.Should().BeTrue();
|
[Theory]
|
||||||
|
[MemberData(nameof(ConfigurationCases))]
|
||||||
|
public void IsFullyConfigured_ShouldValidateEveryRequiredField(
|
||||||
|
string scenario,
|
||||||
|
string? powerEntityId,
|
||||||
|
string? switchEntityId,
|
||||||
|
int? pollIntervalSeconds,
|
||||||
|
double? heatingPowerThresholdWatts,
|
||||||
|
bool expected)
|
||||||
|
{
|
||||||
|
var config = BoilerMonitorTestData.CreateConfig(
|
||||||
|
powerEntityId,
|
||||||
|
switchEntityId,
|
||||||
|
pollIntervalSeconds,
|
||||||
|
heatingPowerThresholdWatts);
|
||||||
|
|
||||||
|
config.IsFullyConfigured.Should().Be(expected, scenario);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void IsFullyConfigured_WhenPowerEntityMissing_ShouldReturnFalse()
|
public void IsFullyConfigured_WhenFullyPopulated_ShouldNotDependOnEntityIdCasingOrPadding()
|
||||||
{
|
{
|
||||||
var config = new BoilerMonitorConfig
|
var config = BoilerMonitorTestData.CreateConfig(
|
||||||
{
|
" sensor.sonoff_1002230e32_power ",
|
||||||
BoilerPowerEntityId = null,
|
"SWITCH.SONOFF_1002230E32");
|
||||||
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
|
|
||||||
PollIntervalSeconds = 30,
|
|
||||||
HeatingPowerThresholdWatts = 5.0
|
|
||||||
};
|
|
||||||
|
|
||||||
config.IsFullyConfigured.Should().BeFalse();
|
config.IsFullyConfigured.Should().BeTrue("entity ids are only checked for non-whitespace content");
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void IsFullyConfigured_WhenSwitchEntityMissing_ShouldReturnFalse()
|
|
||||||
{
|
|
||||||
var config = new BoilerMonitorConfig
|
|
||||||
{
|
|
||||||
BoilerPowerEntityId = "sensor.sonoff_1002230e32_power",
|
|
||||||
BoilerSwitchEntityId = null,
|
|
||||||
PollIntervalSeconds = 30,
|
|
||||||
HeatingPowerThresholdWatts = 5.0
|
|
||||||
};
|
|
||||||
|
|
||||||
config.IsFullyConfigured.Should().BeFalse();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void IsFullyConfigured_WhenPollIntervalMissing_ShouldReturnFalse()
|
|
||||||
{
|
|
||||||
var config = new BoilerMonitorConfig
|
|
||||||
{
|
|
||||||
BoilerPowerEntityId = "sensor.sonoff_1002230e32_power",
|
|
||||||
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
|
|
||||||
PollIntervalSeconds = null,
|
|
||||||
HeatingPowerThresholdWatts = 5.0
|
|
||||||
};
|
|
||||||
|
|
||||||
config.IsFullyConfigured.Should().BeFalse();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void IsFullyConfigured_WhenThresholdMissing_ShouldReturnFalse()
|
|
||||||
{
|
|
||||||
var config = new BoilerMonitorConfig
|
|
||||||
{
|
|
||||||
BoilerPowerEntityId = "sensor.sonoff_1002230e32_power",
|
|
||||||
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
|
|
||||||
PollIntervalSeconds = 30,
|
|
||||||
HeatingPowerThresholdWatts = null
|
|
||||||
};
|
|
||||||
|
|
||||||
config.IsFullyConfigured.Should().BeFalse();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void IsFullyConfigured_WhenPowerEntityIsWhitespace_ShouldReturnFalse()
|
|
||||||
{
|
|
||||||
var config = new BoilerMonitorConfig
|
|
||||||
{
|
|
||||||
BoilerPowerEntityId = " ",
|
|
||||||
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
|
|
||||||
PollIntervalSeconds = 30,
|
|
||||||
HeatingPowerThresholdWatts = 5.0
|
|
||||||
};
|
|
||||||
|
|
||||||
config.IsFullyConfigured.Should().BeFalse();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void IsFullyConfigured_WhenPollIntervalIsZero_ShouldReturnFalse()
|
|
||||||
{
|
|
||||||
var config = new BoilerMonitorConfig
|
|
||||||
{
|
|
||||||
BoilerPowerEntityId = "sensor.sonoff_1002230e32_power",
|
|
||||||
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
|
|
||||||
PollIntervalSeconds = 0,
|
|
||||||
HeatingPowerThresholdWatts = 5.0
|
|
||||||
};
|
|
||||||
|
|
||||||
config.IsFullyConfigured.Should().BeFalse();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void IsFullyConfigured_WhenThresholdIsZero_ShouldReturnFalse()
|
|
||||||
{
|
|
||||||
var config = new BoilerMonitorConfig
|
|
||||||
{
|
|
||||||
BoilerPowerEntityId = "sensor.sonoff_1002230e32_power",
|
|
||||||
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
|
|
||||||
PollIntervalSeconds = 30,
|
|
||||||
HeatingPowerThresholdWatts = 0.0
|
|
||||||
};
|
|
||||||
|
|
||||||
config.IsFullyConfigured.Should().BeFalse();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void IsFullyConfigured_WhenPollIntervalIsNegative_ShouldReturnFalse()
|
|
||||||
{
|
|
||||||
var config = new BoilerMonitorConfig
|
|
||||||
{
|
|
||||||
BoilerPowerEntityId = "sensor.sonoff_1002230e32_power",
|
|
||||||
BoilerSwitchEntityId = "switch.sonoff_1002230e32",
|
|
||||||
PollIntervalSeconds = -1,
|
|
||||||
HeatingPowerThresholdWatts = 5.0
|
|
||||||
};
|
|
||||||
|
|
||||||
config.IsFullyConfigured.Should().BeFalse();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,285 +1,466 @@
|
|||||||
using BoilerMonitor.Models;
|
#region
|
||||||
|
|
||||||
|
using System.Text.Json;
|
||||||
using BoilerMonitorManager;
|
using BoilerMonitorManager;
|
||||||
using BoilerMonitorManager.Models;
|
|
||||||
using FluentAssertions;
|
using FluentAssertions;
|
||||||
using HomeAssistant.Entities.Interfaces;
|
using HomeAssistant.Entities.Interfaces;
|
||||||
|
using HomeAssistant.Models;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using Moq;
|
using Moq;
|
||||||
using NetDaemon.HassModel;
|
using NetDaemon.HassModel;
|
||||||
using NetDaemon.HassModel.Entities;
|
|
||||||
using static BoilerMonitor.Models.BoilerMonitorConsts;
|
using static BoilerMonitor.Models.BoilerMonitorConsts;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace BoilerMonitor.Manager.Tests;
|
namespace BoilerMonitor.Manager.Tests;
|
||||||
|
|
||||||
public class BoilerMonitorEntityServiceTests
|
public class BoilerMonitorEntityServiceTests
|
||||||
{
|
{
|
||||||
private readonly Mock<IEntityManager> _entityManagerMock;
|
/// <summary>Every entity that <c>CleanupEntitiesAsync</c> is expected to remove.</summary>
|
||||||
private readonly Mock<IHaContext> _haContextMock;
|
private static readonly string[] CleanableEntityIds =
|
||||||
private readonly Mock<ILogger<BoilerMonitorEntityService>> _loggerMock;
|
[
|
||||||
private readonly BoilerMonitorEntityService _sut;
|
ConfigPowerEntityId,
|
||||||
|
ConfigSwitchEntityId,
|
||||||
|
ConfigPollIntervalEntityId,
|
||||||
|
ConfigHeatingThresholdEntityId,
|
||||||
|
StatusEntityId,
|
||||||
|
WaterReadyEntityId,
|
||||||
|
SkipPriceCapEntityId,
|
||||||
|
TodayRuntimeEntityId,
|
||||||
|
RemainingTimeEntityId,
|
||||||
|
BudgetPercentageEntityId,
|
||||||
|
BudgetExhaustedEntityId,
|
||||||
|
SessionCountEntityId,
|
||||||
|
BudgetOverrideEntityId,
|
||||||
|
AutoManagementEntityId
|
||||||
|
];
|
||||||
|
|
||||||
|
private readonly Mock<IEntityManager> _entityManagerMock = new Mock<IEntityManager>();
|
||||||
|
private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
|
||||||
|
private readonly Mock<ILogger<BoilerMonitorEntityService>> _loggerMock = new Mock<ILogger<BoilerMonitorEntityService>>();
|
||||||
|
|
||||||
public BoilerMonitorEntityServiceTests()
|
public BoilerMonitorEntityServiceTests()
|
||||||
{
|
{
|
||||||
_entityManagerMock = new Mock<IEntityManager>();
|
_entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny<EntityCreateModel>()))
|
||||||
_haContextMock = new Mock<IHaContext>();
|
.Returns(Task.CompletedTask);
|
||||||
_loggerMock = new Mock<ILogger<BoilerMonitorEntityService>>();
|
|
||||||
_sut = new BoilerMonitorEntityService(
|
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
||||||
|
.Returns(Task.CompletedTask);
|
||||||
|
|
||||||
|
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
|
||||||
|
.Returns(Task.CompletedTask);
|
||||||
|
|
||||||
|
_entityManagerMock.Setup(em => em.RemoveEntity(It.IsAny<string>()))
|
||||||
|
.Returns(Task.CompletedTask);
|
||||||
|
}
|
||||||
|
|
||||||
|
private BoilerMonitorEntityService CreateSut()
|
||||||
|
{
|
||||||
|
return new BoilerMonitorEntityService(
|
||||||
_entityManagerMock.Object,
|
_entityManagerMock.Object,
|
||||||
_haContextMock.Object,
|
_haContextMock.Object,
|
||||||
_loggerMock.Object);
|
_loggerMock.Object);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void SetupEntityState(string entityId, string? state)
|
#region ReadPersistedState
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(BoilerMonitorTestData.RuntimeStateSamples), MemberType = typeof(BoilerMonitorTestData))]
|
||||||
|
public void ReadPersistedState_WhenRuntimeStateVaries_ShouldParseOrReject(
|
||||||
|
string? runtimeState,
|
||||||
|
TimeSpan? expectedRunTime)
|
||||||
{
|
{
|
||||||
if (state is null)
|
_haContextMock.SetupEntityStates(
|
||||||
|
BoilerMonitorTestData.CreatePersistedEntityStates(runtimeState, "2"));
|
||||||
|
|
||||||
|
var result = CreateSut().ReadPersistedState();
|
||||||
|
|
||||||
|
if (expectedRunTime is null)
|
||||||
{
|
{
|
||||||
_haContextMock.Setup(h => h.GetState(entityId)).Returns((EntityState?)null);
|
result.Should().BeNull();
|
||||||
}
|
|
||||||
else
|
return;
|
||||||
{
|
|
||||||
_haContextMock.Setup(h => h.GetState(entityId))
|
|
||||||
.Returns(new EntityState { State = state });
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#region ReadPersistedState
|
result.Should().NotBeNull();
|
||||||
|
result.AccumulatedRunTime.Should().Be(expectedRunTime.Value);
|
||||||
|
result.SessionCount.Should().Be(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(BoilerMonitorTestData.SessionCountStateSamples), MemberType = typeof(BoilerMonitorTestData))]
|
||||||
|
public void ReadPersistedState_WhenSessionCountStateVaries_ShouldParseOrReject(
|
||||||
|
string? sessionCountState,
|
||||||
|
int? expectedSessionCount)
|
||||||
|
{
|
||||||
|
_haContextMock.SetupEntityStates(
|
||||||
|
BoilerMonitorTestData.CreatePersistedEntityStates("3600", sessionCountState));
|
||||||
|
|
||||||
|
var result = CreateSut().ReadPersistedState();
|
||||||
|
|
||||||
|
if (expectedSessionCount is null)
|
||||||
|
{
|
||||||
|
result.Should().BeNull();
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
result.Should().NotBeNull();
|
||||||
|
result.AccumulatedRunTime.Should().Be(TimeSpan.FromHours(1));
|
||||||
|
result.SessionCount.Should().Be(expectedSessionCount.Value);
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ReadPersistedState_WithValidState_ShouldReturnPersistedValues()
|
public void ReadPersistedState_WithValidState_ShouldReturnPersistedValues()
|
||||||
{
|
{
|
||||||
// Arrange
|
_haContextMock.SetupEntityStates(BoilerMonitorTestData.CreatePersistedEntityStates(
|
||||||
SetupEntityState(TodayRuntimeEntityId, "7200");
|
"7200", "3", "ON"));
|
||||||
SetupEntityState(SessionCountEntityId, "3");
|
|
||||||
SetupEntityState(SkipPriceCapEntityId, "ON");
|
|
||||||
SetupEntityState(BudgetOverrideEntityId, "OFF");
|
|
||||||
|
|
||||||
// Act
|
var result = CreateSut().ReadPersistedState();
|
||||||
var result = _sut.ReadPersistedState();
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
result.Should().NotBeNull();
|
result.Should().NotBeNull();
|
||||||
result!.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(7200));
|
result.AccumulatedRunTime.Should().Be(TimeSpan.FromHours(2));
|
||||||
result.SessionCount.Should().Be(3);
|
result.SessionCount.Should().Be(3);
|
||||||
result.SkipPriceCapState.Should().Be("ON");
|
result.SkipPriceCapState.Should().Be("ON");
|
||||||
result.BudgetOverrideState.Should().Be("OFF");
|
result.BudgetOverrideState.Should().Be("OFF");
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Theory]
|
||||||
public void ReadPersistedState_WithZeroRuntime_ShouldReturnZeroValues()
|
[InlineData("ON")]
|
||||||
|
[InlineData("on")]
|
||||||
|
[InlineData(" On ")]
|
||||||
|
[InlineData("")]
|
||||||
|
[InlineData(null)]
|
||||||
|
public void ReadPersistedState_ShouldReturnRawSwitchStates(string? switchState)
|
||||||
{
|
{
|
||||||
// Arrange
|
_haContextMock.SetupEntityStates(BoilerMonitorTestData.CreatePersistedEntityStates(
|
||||||
SetupEntityState(TodayRuntimeEntityId, "0");
|
skipPriceCap: switchState, budgetOverride: switchState));
|
||||||
SetupEntityState(SessionCountEntityId, "0");
|
|
||||||
SetupEntityState(SkipPriceCapEntityId, "OFF");
|
|
||||||
SetupEntityState(BudgetOverrideEntityId, "OFF");
|
|
||||||
|
|
||||||
// Act
|
var result = CreateSut().ReadPersistedState();
|
||||||
var result = _sut.ReadPersistedState();
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
result.Should().NotBeNull();
|
result.Should().NotBeNull();
|
||||||
result!.AccumulatedRunTime.Should().Be(TimeSpan.Zero);
|
result.SkipPriceCapState.Should().Be(switchState);
|
||||||
result.SessionCount.Should().Be(0);
|
result.BudgetOverrideState.Should().Be(switchState);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ReadPersistedState_WhenRuntimeIsUnavailable_ShouldReturnNull()
|
public void ReadPersistedState_WhenBothRuntimeEntitiesDoNotExist_ShouldReturnNull()
|
||||||
{
|
{
|
||||||
// Arrange
|
_haContextMock.SetupEntityStates(
|
||||||
SetupEntityState(TodayRuntimeEntityId, "unavailable");
|
BoilerMonitorTestData.CreatePersistedEntityStates(null, null));
|
||||||
SetupEntityState(SessionCountEntityId, "3");
|
|
||||||
SetupEntityState(SkipPriceCapEntityId, "OFF");
|
|
||||||
SetupEntityState(BudgetOverrideEntityId, "OFF");
|
|
||||||
|
|
||||||
// Act
|
CreateSut().ReadPersistedState().Should().BeNull();
|
||||||
var result = _sut.ReadPersistedState();
|
}
|
||||||
|
|
||||||
// Assert
|
#endregion
|
||||||
result.Should().BeNull();
|
|
||||||
|
#region ReadPersistedCooldownTimestamp
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ReadPersistedCooldownTimestamp_WithValidIsoString_ShouldReturnTimestamp()
|
||||||
|
{
|
||||||
|
var cooldownSince = BoilerMonitorTestData.BaseTime - TimeSpan.FromMinutes(30);
|
||||||
|
|
||||||
|
_haContextMock.SetupEntityState(
|
||||||
|
WaterReadyEntityId,
|
||||||
|
BoilerMonitorTestData.CreateWaterReadyEntityStateWithCooldown(cooldownSince.ToString("O")));
|
||||||
|
|
||||||
|
var result = CreateSut().ReadPersistedCooldownTimestamp();
|
||||||
|
|
||||||
|
result.Should().Be(cooldownSince);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ReadPersistedState_WhenRuntimeIsUnknown_ShouldReturnNull()
|
public void ReadPersistedCooldownTimestamp_WithUtcDesignator_ShouldReturnTimestamp()
|
||||||
{
|
{
|
||||||
// Arrange
|
var cooldownSince = new DateTimeOffset(2026, 3, 31, 9, 15, 0, TimeSpan.Zero);
|
||||||
SetupEntityState(TodayRuntimeEntityId, "unknown");
|
|
||||||
SetupEntityState(SessionCountEntityId, "2");
|
|
||||||
SetupEntityState(SkipPriceCapEntityId, "OFF");
|
|
||||||
SetupEntityState(BudgetOverrideEntityId, "OFF");
|
|
||||||
|
|
||||||
// Act
|
_haContextMock.SetupEntityState(
|
||||||
var result = _sut.ReadPersistedState();
|
WaterReadyEntityId,
|
||||||
|
BoilerMonitorTestData.CreateWaterReadyEntityStateWithCooldown("2026-03-31T09:15:00Z"));
|
||||||
|
|
||||||
// Assert
|
var result = CreateSut().ReadPersistedCooldownTimestamp();
|
||||||
result.Should().BeNull();
|
|
||||||
|
result.Should().Be(cooldownSince);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ReadPersistedState_WhenSessionCountIsUnavailable_ShouldReturnNull()
|
public void ReadPersistedCooldownTimestamp_WhenEntityDoesNotExist_ShouldReturnNull()
|
||||||
{
|
{
|
||||||
// Arrange
|
_haContextMock.SetupEntityState(WaterReadyEntityId, null);
|
||||||
SetupEntityState(TodayRuntimeEntityId, "3600");
|
|
||||||
SetupEntityState(SessionCountEntityId, "unavailable");
|
|
||||||
SetupEntityState(SkipPriceCapEntityId, "OFF");
|
|
||||||
SetupEntityState(BudgetOverrideEntityId, "OFF");
|
|
||||||
|
|
||||||
// Act
|
CreateSut().ReadPersistedCooldownTimestamp().Should().BeNull();
|
||||||
var result = _sut.ReadPersistedState();
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
result.Should().BeNull();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ReadPersistedState_WhenRuntimeEntityDoesNotExist_ShouldReturnNull()
|
public void ReadPersistedCooldownTimestamp_WhenEntityHasNoAttributes_ShouldReturnNull()
|
||||||
{
|
{
|
||||||
// Arrange
|
_haContextMock.SetupEntityState(WaterReadyEntityId, BoilerMonitorTestData.CreateEntityState("yes"));
|
||||||
SetupEntityState(TodayRuntimeEntityId, null);
|
|
||||||
SetupEntityState(SessionCountEntityId, "2");
|
|
||||||
SetupEntityState(SkipPriceCapEntityId, "OFF");
|
|
||||||
SetupEntityState(BudgetOverrideEntityId, "OFF");
|
|
||||||
|
|
||||||
// Act
|
CreateSut().ReadPersistedCooldownTimestamp().Should().BeNull();
|
||||||
var result = _sut.ReadPersistedState();
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
result.Should().BeNull();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ReadPersistedState_WhenSessionCountEntityDoesNotExist_ShouldReturnNull()
|
public void ReadPersistedCooldownTimestamp_WhenAttributeIsMissing_ShouldReturnNull()
|
||||||
{
|
{
|
||||||
// Arrange
|
_haContextMock.SetupEntityState(
|
||||||
SetupEntityState(TodayRuntimeEntityId, "3600");
|
WaterReadyEntityId,
|
||||||
SetupEntityState(SessionCountEntityId, null);
|
BoilerMonitorTestData.CreateEntityStateWithAttributes(
|
||||||
SetupEntityState(SkipPriceCapEntityId, "OFF");
|
new Dictionary<string, object?> { ["friendly_name"] = "Boiler water ready" }));
|
||||||
SetupEntityState(BudgetOverrideEntityId, "OFF");
|
|
||||||
|
|
||||||
// Act
|
CreateSut().ReadPersistedCooldownTimestamp().Should().BeNull();
|
||||||
var result = _sut.ReadPersistedState();
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
result.Should().BeNull();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void ReadPersistedState_WhenRuntimeIsNonNumeric_ShouldReturnNull()
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
SetupEntityState(TodayRuntimeEntityId, "not_a_number");
|
|
||||||
SetupEntityState(SessionCountEntityId, "2");
|
|
||||||
SetupEntityState(SkipPriceCapEntityId, "OFF");
|
|
||||||
SetupEntityState(BudgetOverrideEntityId, "OFF");
|
|
||||||
|
|
||||||
// Act
|
|
||||||
var result = _sut.ReadPersistedState();
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
result.Should().BeNull();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void ReadPersistedState_WhenSessionCountIsNonNumeric_ShouldReturnNull()
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
SetupEntityState(TodayRuntimeEntityId, "3600");
|
|
||||||
SetupEntityState(SessionCountEntityId, "abc");
|
|
||||||
SetupEntityState(SkipPriceCapEntityId, "OFF");
|
|
||||||
SetupEntityState(BudgetOverrideEntityId, "OFF");
|
|
||||||
|
|
||||||
// Act
|
|
||||||
var result = _sut.ReadPersistedState();
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
result.Should().BeNull();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void ReadPersistedState_WhenRuntimeIsNegative_ShouldReturnNull()
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
SetupEntityState(TodayRuntimeEntityId, "-100");
|
|
||||||
SetupEntityState(SessionCountEntityId, "2");
|
|
||||||
SetupEntityState(SkipPriceCapEntityId, "OFF");
|
|
||||||
SetupEntityState(BudgetOverrideEntityId, "OFF");
|
|
||||||
|
|
||||||
// Act
|
|
||||||
var result = _sut.ReadPersistedState();
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
result.Should().BeNull();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void ReadPersistedState_WhenSessionCountIsNegative_ShouldReturnNull()
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
SetupEntityState(TodayRuntimeEntityId, "3600");
|
|
||||||
SetupEntityState(SessionCountEntityId, "-1");
|
|
||||||
SetupEntityState(SkipPriceCapEntityId, "OFF");
|
|
||||||
SetupEntityState(BudgetOverrideEntityId, "OFF");
|
|
||||||
|
|
||||||
// Act
|
|
||||||
var result = _sut.ReadPersistedState();
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
result.Should().BeNull();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void ReadPersistedState_WhenSwitchEntitiesAreNull_ShouldStillReturnWithNullSwitchStates()
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
SetupEntityState(TodayRuntimeEntityId, "1800");
|
|
||||||
SetupEntityState(SessionCountEntityId, "1");
|
|
||||||
SetupEntityState(SkipPriceCapEntityId, null);
|
|
||||||
SetupEntityState(BudgetOverrideEntityId, null);
|
|
||||||
|
|
||||||
// Act
|
|
||||||
var result = _sut.ReadPersistedState();
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
result.Should().NotBeNull();
|
|
||||||
result!.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(1800));
|
|
||||||
result.SessionCount.Should().Be(1);
|
|
||||||
result.SkipPriceCapState.Should().BeNull();
|
|
||||||
result.BudgetOverrideState.Should().BeNull();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
[InlineData("")] // empty string
|
[InlineData(null)]
|
||||||
[InlineData(" ")] // whitespace
|
[InlineData(42)]
|
||||||
public void ReadPersistedState_WhenRuntimeIsEmptyOrWhitespace_ShouldReturnNull(string state)
|
[InlineData(true)]
|
||||||
|
[InlineData("")]
|
||||||
|
[InlineData(" ")]
|
||||||
|
[InlineData("not-a-timestamp")]
|
||||||
|
[InlineData("2026-13-45T99:99:99")]
|
||||||
|
[InlineData("unavailable")]
|
||||||
|
public void ReadPersistedCooldownTimestamp_WhenAttributeIsNotAValidTimestamp_ShouldReturnNull(object? cooldownSince)
|
||||||
{
|
{
|
||||||
// Arrange
|
_haContextMock.SetupEntityState(
|
||||||
SetupEntityState(TodayRuntimeEntityId, state);
|
WaterReadyEntityId,
|
||||||
SetupEntityState(SessionCountEntityId, "2");
|
BoilerMonitorTestData.CreateWaterReadyEntityStateWithCooldown(cooldownSince));
|
||||||
SetupEntityState(SkipPriceCapEntityId, "OFF");
|
|
||||||
SetupEntityState(BudgetOverrideEntityId, "OFF");
|
|
||||||
|
|
||||||
// Act
|
CreateSut().ReadPersistedCooldownTimestamp().Should().BeNull();
|
||||||
var result = _sut.ReadPersistedState();
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
result.Should().BeNull();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ReadPersistedState_WithDecimalRuntime_ShouldParseCorrectly()
|
public void ReadPersistedCooldownTimestamp_WhenHaContextThrows_ShouldReturnNull()
|
||||||
{
|
{
|
||||||
// Arrange
|
_haContextMock.Setup(h => h.GetState(WaterReadyEntityId))
|
||||||
SetupEntityState(TodayRuntimeEntityId, "134.66");
|
.Throws(new InvalidOperationException("Home Assistant unavailable"));
|
||||||
SetupEntityState(SessionCountEntityId, "1");
|
|
||||||
SetupEntityState(SkipPriceCapEntityId, "OFF");
|
|
||||||
SetupEntityState(BudgetOverrideEntityId, "OFF");
|
|
||||||
|
|
||||||
// Act
|
CreateSut().ReadPersistedCooldownTimestamp().Should().BeNull();
|
||||||
var result = _sut.ReadPersistedState();
|
}
|
||||||
|
|
||||||
// Assert
|
#endregion
|
||||||
result.Should().NotBeNull();
|
|
||||||
result!.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(134.66));
|
#region UpdateEntitiesAsync
|
||||||
result.SessionCount.Should().Be(1);
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(true, "yes")]
|
||||||
|
[InlineData(false, "no")]
|
||||||
|
public async Task UpdateEntitiesAsync_ShouldWriteWaterReadyState(bool waterReady, string expectedState)
|
||||||
|
{
|
||||||
|
await CreateSut().UpdateEntitiesAsync(BoilerMonitorTestData.CreateUpdateContext(waterReady: waterReady));
|
||||||
|
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityState(WaterReadyEntityId, expectedState), Times.Once);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task UpdateEntitiesAsync_ShouldWriteAllRuntimeEntitiesWithExpectedFormatting()
|
||||||
|
{
|
||||||
|
var context = BoilerMonitorTestData.CreateUpdateContext(
|
||||||
|
TimeSpan.FromSeconds(3723.9),
|
||||||
|
TimeSpan.FromSeconds(42.9),
|
||||||
|
150.0,
|
||||||
|
true,
|
||||||
|
4,
|
||||||
|
waterReady: true);
|
||||||
|
|
||||||
|
await CreateSut().UpdateEntitiesAsync(context);
|
||||||
|
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityState(StatusEntityId, StatusConfigured), Times.Once);
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityState(TodayRuntimeEntityId, "3723"), Times.Once);
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityState(RemainingTimeEntityId, "42"), Times.Once);
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityState(BudgetPercentageEntityId, "100"), Times.Once);
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityState(BudgetExhaustedEntityId, "on"), Times.Once);
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityState(SessionCountEntityId, "4"), Times.Once);
|
||||||
|
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()),
|
||||||
|
Times.Exactly(5));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(-0.1, "0")]
|
||||||
|
[InlineData(0.0, "0")]
|
||||||
|
[InlineData(49.9, "49")]
|
||||||
|
[InlineData(99.999, "99")]
|
||||||
|
[InlineData(100.0, "100")]
|
||||||
|
[InlineData(100.1, "100")]
|
||||||
|
[InlineData(1_000.0, "100")]
|
||||||
|
public async Task UpdateEntitiesAsync_ShouldClampAndTruncateBudgetPercentage(
|
||||||
|
double budgetPercentage,
|
||||||
|
string expectedState)
|
||||||
|
{
|
||||||
|
await CreateSut()
|
||||||
|
.UpdateEntitiesAsync(
|
||||||
|
BoilerMonitorTestData.CreateUpdateContext(budgetPercentage: budgetPercentage));
|
||||||
|
|
||||||
|
_entityManagerMock.Verify(
|
||||||
|
em => em.SetEntityState(BudgetPercentageEntityId, expectedState), Times.Once);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(-60, "0")]
|
||||||
|
[InlineData(0, "0")]
|
||||||
|
[InlineData(1, "1")]
|
||||||
|
[InlineData(59, "59")]
|
||||||
|
[InlineData(3600, "3600")]
|
||||||
|
public async Task UpdateEntitiesAsync_ShouldClampAndTruncateRemainingTime(int seconds, string expectedState)
|
||||||
|
{
|
||||||
|
await CreateSut()
|
||||||
|
.UpdateEntitiesAsync(
|
||||||
|
BoilerMonitorTestData.CreateUpdateContext(remainingTime: TimeSpan.FromSeconds(seconds)));
|
||||||
|
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityState(RemainingTimeEntityId, expectedState), Times.Once);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(0.0, "0")]
|
||||||
|
[InlineData(0.9, "0")]
|
||||||
|
[InlineData(59.9, "59")]
|
||||||
|
[InlineData(60.0, "60")]
|
||||||
|
[InlineData(86_400.0, "86400")]
|
||||||
|
public async Task UpdateEntitiesAsync_ShouldTruncateTodayRunTimeToWholeSeconds(double seconds, string expectedState)
|
||||||
|
{
|
||||||
|
await CreateSut()
|
||||||
|
.UpdateEntitiesAsync(
|
||||||
|
BoilerMonitorTestData.CreateUpdateContext(TimeSpan.FromSeconds(seconds)));
|
||||||
|
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityState(TodayRuntimeEntityId, expectedState), Times.Once);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task UpdateEntitiesAsync_WhenSwitchStateIsNull_ShouldWriteUnknownWaterReadyAttributes()
|
||||||
|
{
|
||||||
|
object? capturedAttributes = null;
|
||||||
|
|
||||||
|
_entityManagerMock
|
||||||
|
.Setup(em => em.SetEntityAttributes(WaterReadyEntityId, It.IsAny<object>()))
|
||||||
|
.Callback<string, object>((_, attributes) => capturedAttributes = attributes)
|
||||||
|
.Returns(Task.CompletedTask);
|
||||||
|
|
||||||
|
await CreateSut()
|
||||||
|
.UpdateEntitiesAsync(BoilerMonitorTestData.CreateUpdateContext(
|
||||||
|
waterReady: false,
|
||||||
|
boilerSwitchState: null,
|
||||||
|
boilerPowerWatts: 1234.5));
|
||||||
|
|
||||||
|
capturedAttributes.Should().NotBeNull();
|
||||||
|
var attributes = JsonSerializer.SerializeToElement(capturedAttributes!);
|
||||||
|
attributes.GetProperty("boiler_switch_state").GetString().Should().Be("unknown");
|
||||||
|
attributes.GetProperty("boiler_power_watts").GetDouble().Should().Be(1234.5);
|
||||||
|
attributes.GetProperty("cooldown_since").ValueKind.Should().Be(JsonValueKind.Null);
|
||||||
|
attributes.GetProperty("last_updated").GetString().Should().NotBeNullOrEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task UpdateEntitiesAsync_WhenCooldownIsActive_ShouldSerializeCooldownTimestamp()
|
||||||
|
{
|
||||||
|
var cooldownSince = BoilerMonitorTestData.BaseTime - TimeSpan.FromMinutes(15);
|
||||||
|
object? capturedAttributes = null;
|
||||||
|
|
||||||
|
_entityManagerMock
|
||||||
|
.Setup(em => em.SetEntityAttributes(WaterReadyEntityId, It.IsAny<object>()))
|
||||||
|
.Callback<string, object>((_, attributes) => capturedAttributes = attributes)
|
||||||
|
.Returns(Task.CompletedTask);
|
||||||
|
|
||||||
|
await CreateSut()
|
||||||
|
.UpdateEntitiesAsync(
|
||||||
|
BoilerMonitorTestData.CreateUpdateContext(cooldownSince: cooldownSince));
|
||||||
|
|
||||||
|
var attributes = JsonSerializer.SerializeToElement(capturedAttributes!);
|
||||||
|
attributes.GetProperty("cooldown_since").GetString().Should().Be(cooldownSince.ToString("O"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region CreateEntitiesAsync
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task CreateEntitiesAsync_ShouldCreateEveryBoilerMonitorEntityOnce()
|
||||||
|
{
|
||||||
|
var createdEntityIds = new List<string?>();
|
||||||
|
|
||||||
|
_entityManagerMock
|
||||||
|
.Setup(em => em.CreateEntityAsync(It.IsAny<EntityCreateModel>()))
|
||||||
|
.Callback<EntityCreateModel>(entity => createdEntityIds.Add(entity.EntityId))
|
||||||
|
.Returns(Task.CompletedTask);
|
||||||
|
|
||||||
|
await CreateSut().CreateEntitiesAsync();
|
||||||
|
|
||||||
|
createdEntityIds.Should().HaveCount(15).And.OnlyHaveUniqueItems();
|
||||||
|
|
||||||
|
createdEntityIds.Should()
|
||||||
|
.Contain(
|
||||||
|
[
|
||||||
|
ConfigPowerEntityId,
|
||||||
|
ConfigSwitchEntityId,
|
||||||
|
ConfigPollIntervalEntityId,
|
||||||
|
ConfigHeatingThresholdEntityId,
|
||||||
|
CleanupButtonEntityId,
|
||||||
|
WaterReadyEntityId,
|
||||||
|
TodayRuntimeEntityId,
|
||||||
|
BudgetExhaustedEntityId,
|
||||||
|
AutoManagementEntityId
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task CreateEntitiesAsync_WhenOneEntityFails_ShouldStillAttemptEveryEntity()
|
||||||
|
{
|
||||||
|
_entityManagerMock
|
||||||
|
.Setup(em =>
|
||||||
|
em.CreateEntityAsync(It.Is<EntityCreateModel>(entity => entity.EntityId == CleanupButtonEntityId)))
|
||||||
|
.ThrowsAsync(new InvalidOperationException("MQTT unavailable"));
|
||||||
|
|
||||||
|
var act = () => CreateSut().CreateEntitiesAsync();
|
||||||
|
|
||||||
|
await act.Should().NotThrowAsync();
|
||||||
|
|
||||||
|
_entityManagerMock.Invocations
|
||||||
|
.Count(invocation => invocation.Method.Name == nameof(IEntityManager.CreateEntityAsync))
|
||||||
|
.Should()
|
||||||
|
.Be(15);
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region ResetEntitiesAsync
|
||||||
|
|
||||||
|
public static TheoryData<string, string> ResetEntityStates => new TheoryData<string, string>
|
||||||
|
{
|
||||||
|
{ StatusEntityId, StatusAwaitingConfiguration },
|
||||||
|
{ WaterReadyEntityId, "unknown" },
|
||||||
|
{ SkipPriceCapEntityId, "OFF" },
|
||||||
|
{ TodayRuntimeEntityId, "0" },
|
||||||
|
{ RemainingTimeEntityId, "0" },
|
||||||
|
{ BudgetPercentageEntityId, "0" },
|
||||||
|
{ BudgetExhaustedEntityId, "off" },
|
||||||
|
{ SessionCountEntityId, "0" },
|
||||||
|
{ BudgetOverrideEntityId, "OFF" },
|
||||||
|
{ AutoManagementEntityId, "ON" }
|
||||||
|
};
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(ResetEntityStates))]
|
||||||
|
public async Task ResetEntitiesAsync_ShouldWriteExpectedDefaultState(string entityId, string expectedState)
|
||||||
|
{
|
||||||
|
await CreateSut().ResetEntitiesAsync();
|
||||||
|
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityState(entityId, expectedState), Times.Once);
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()), Times.Exactly(10));
|
||||||
|
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()),
|
||||||
|
Times.Exactly(5));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task ResetEntitiesAsync_WhenEntityManagerThrows_ShouldNotThrow()
|
||||||
|
{
|
||||||
|
_entityManagerMock
|
||||||
|
.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
||||||
|
.ThrowsAsync(new InvalidOperationException("MQTT unavailable"));
|
||||||
|
|
||||||
|
var act = () => CreateSut().ResetEntitiesAsync();
|
||||||
|
|
||||||
|
await act.Should().NotThrowAsync();
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
@@ -289,55 +470,112 @@ public class BoilerMonitorEntityServiceTests
|
|||||||
[Fact]
|
[Fact]
|
||||||
public async Task ResetTransientEntitiesAsync_ShouldResetStatusAndWaterReady()
|
public async Task ResetTransientEntitiesAsync_ShouldResetStatusAndWaterReady()
|
||||||
{
|
{
|
||||||
// Arrange
|
await CreateSut().ResetTransientEntitiesAsync();
|
||||||
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
|
||||||
.Returns(Task.CompletedTask);
|
|
||||||
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
|
|
||||||
.Returns(Task.CompletedTask);
|
|
||||||
|
|
||||||
// Act
|
|
||||||
await _sut.ResetTransientEntitiesAsync();
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
_entityManagerMock.Verify(em => em.SetEntityState(StatusEntityId, StatusAwaitingConfiguration), Times.Once);
|
_entityManagerMock.Verify(em => em.SetEntityState(StatusEntityId, StatusAwaitingConfiguration), Times.Once);
|
||||||
_entityManagerMock.Verify(em => em.SetEntityState(WaterReadyEntityId, "unknown"), Times.Once);
|
_entityManagerMock.Verify(em => em.SetEntityState(WaterReadyEntityId, "unknown"), Times.Once);
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityAttributes(WaterReadyEntityId, It.IsAny<object>()), Times.Once);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static TheoryData<string> UntouchedByTransientResetEntityIds =>
|
||||||
|
[
|
||||||
|
TodayRuntimeEntityId,
|
||||||
|
SessionCountEntityId,
|
||||||
|
BudgetPercentageEntityId,
|
||||||
|
BudgetExhaustedEntityId,
|
||||||
|
RemainingTimeEntityId,
|
||||||
|
SkipPriceCapEntityId,
|
||||||
|
BudgetOverrideEntityId,
|
||||||
|
AutoManagementEntityId,
|
||||||
|
ConfigPowerEntityId,
|
||||||
|
ConfigSwitchEntityId
|
||||||
|
];
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(UntouchedByTransientResetEntityIds))]
|
||||||
|
public async Task ResetTransientEntitiesAsync_ShouldNotResetPersistentOrSwitchEntities(string entityId)
|
||||||
|
{
|
||||||
|
await CreateSut().ResetTransientEntitiesAsync();
|
||||||
|
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityState(entityId, It.IsAny<string>()), Times.Never);
|
||||||
|
_entityManagerMock.Verify(em => em.SetEntityAttributes(entityId, It.IsAny<object>()), Times.Never);
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region CleanupEntitiesAsync
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task CleanupEntitiesAsync_ShouldRemoveEveryEntityExceptCleanupButton()
|
||||||
|
{
|
||||||
|
await CreateSut().CleanupEntitiesAsync();
|
||||||
|
|
||||||
|
foreach (var entityId in CleanableEntityIds)
|
||||||
|
{
|
||||||
|
_entityManagerMock.Verify(em => em.RemoveEntity(entityId), Times.Once);
|
||||||
|
}
|
||||||
|
|
||||||
|
_entityManagerMock.Verify(em => em.RemoveEntity(CleanupButtonEntityId), Times.Never);
|
||||||
|
_entityManagerMock.Verify(em => em.RemoveEntity(It.IsAny<string>()), Times.Exactly(CleanableEntityIds.Length));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task ResetTransientEntitiesAsync_ShouldNotResetRuntimeEntities()
|
public async Task CleanupEntitiesAsync_WhenRemoveFails_ShouldRethrow()
|
||||||
{
|
{
|
||||||
// Arrange
|
_entityManagerMock
|
||||||
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
.Setup(em => em.RemoveEntity(It.IsAny<string>()))
|
||||||
.Returns(Task.CompletedTask);
|
.Throws(new InvalidOperationException("MQTT unavailable"));
|
||||||
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
|
|
||||||
.Returns(Task.CompletedTask);
|
|
||||||
|
|
||||||
// Act
|
var act = () => CreateSut().CleanupEntitiesAsync();
|
||||||
await _sut.ResetTransientEntitiesAsync();
|
|
||||||
|
|
||||||
// Assert
|
await act.Should().ThrowAsync<InvalidOperationException>();
|
||||||
_entityManagerMock.Verify(em => em.SetEntityState(TodayRuntimeEntityId, It.IsAny<string>()), Times.Never);
|
|
||||||
_entityManagerMock.Verify(em => em.SetEntityState(SessionCountEntityId, It.IsAny<string>()), Times.Never);
|
|
||||||
_entityManagerMock.Verify(em => em.SetEntityState(BudgetPercentageEntityId, It.IsAny<string>()), Times.Never);
|
|
||||||
_entityManagerMock.Verify(em => em.SetEntityState(BudgetExhaustedEntityId, It.IsAny<string>()), Times.Never);
|
|
||||||
_entityManagerMock.Verify(em => em.SetEntityState(RemainingTimeEntityId, It.IsAny<string>()), Times.Never);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region SetStatusAsync and cancellation
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task ResetTransientEntitiesAsync_ShouldNotResetSwitchEntities()
|
public async Task SetStatusAsync_ShouldWriteStatusEntity()
|
||||||
{
|
{
|
||||||
// Arrange
|
await CreateSut().SetStatusAsync(StatusConfigured);
|
||||||
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
|
|
||||||
.Returns(Task.CompletedTask);
|
|
||||||
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
|
|
||||||
.Returns(Task.CompletedTask);
|
|
||||||
|
|
||||||
// Act
|
_entityManagerMock.Verify(em => em.SetEntityState(StatusEntityId, StatusConfigured), Times.Once);
|
||||||
await _sut.ResetTransientEntitiesAsync();
|
}
|
||||||
|
|
||||||
// Assert
|
public enum CancelableOperation
|
||||||
_entityManagerMock.Verify(em => em.SetEntityState(SkipPriceCapEntityId, It.IsAny<string>()), Times.Never);
|
{
|
||||||
_entityManagerMock.Verify(em => em.SetEntityState(BudgetOverrideEntityId, It.IsAny<string>()), Times.Never);
|
CreateEntities,
|
||||||
|
ResetEntities,
|
||||||
|
UpdateEntities,
|
||||||
|
ResetTransientEntities,
|
||||||
|
CleanupEntities
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(CancelableOperation.CreateEntities)]
|
||||||
|
[InlineData(CancelableOperation.ResetEntities)]
|
||||||
|
[InlineData(CancelableOperation.UpdateEntities)]
|
||||||
|
[InlineData(CancelableOperation.ResetTransientEntities)]
|
||||||
|
[InlineData(CancelableOperation.CleanupEntities)]
|
||||||
|
public async Task Operation_WhenCancellationIsAlreadyRequested_ShouldThrowAndNotTouchEntityManager(
|
||||||
|
CancelableOperation operation)
|
||||||
|
{
|
||||||
|
var canceledToken = new CancellationToken(true);
|
||||||
|
var sut = CreateSut();
|
||||||
|
|
||||||
|
Func<Task> act = operation switch
|
||||||
|
{
|
||||||
|
CancelableOperation.CreateEntities => () => sut.CreateEntitiesAsync(canceledToken),
|
||||||
|
CancelableOperation.ResetEntities => () => sut.ResetEntitiesAsync(canceledToken),
|
||||||
|
CancelableOperation.UpdateEntities => () => sut.UpdateEntitiesAsync(
|
||||||
|
BoilerMonitorTestData.CreateUpdateContext(), canceledToken),
|
||||||
|
CancelableOperation.ResetTransientEntities => () => sut.ResetTransientEntitiesAsync(canceledToken),
|
||||||
|
_ => () => sut.CleanupEntitiesAsync(canceledToken)
|
||||||
|
};
|
||||||
|
|
||||||
|
await act.Should().ThrowAsync<OperationCanceledException>();
|
||||||
|
_entityManagerMock.Invocations.Should().BeEmpty();
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|||||||
@@ -1,5 +1,9 @@
|
|||||||
using FluentAssertions;
|
#region
|
||||||
|
|
||||||
using BoilerMonitorManager.Models;
|
using BoilerMonitorManager.Models;
|
||||||
|
using FluentAssertions;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace BoilerMonitor.Manager.Tests;
|
namespace BoilerMonitor.Manager.Tests;
|
||||||
|
|
||||||
@@ -13,17 +17,47 @@ public class BoilerMonitorOptionsTests
|
|||||||
options.Enabled.Should().BeTrue();
|
options.Enabled.Should().BeTrue();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Defaults_ShouldHaveCleanupEntitiesOnStartupTrue()
|
||||||
|
{
|
||||||
|
var options = new BoilerMonitorOptions();
|
||||||
|
|
||||||
|
options.CleanupEntitiesOnStartup.Should().BeTrue();
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void SectionName_ShouldBeBoilerMonitor()
|
public void SectionName_ShouldBeBoilerMonitor()
|
||||||
{
|
{
|
||||||
BoilerMonitorOptions.SectionName.Should().Be("BoilerMonitor");
|
BoilerMonitorOptions.SectionName.Should().Be("BoilerMonitor");
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Theory]
|
||||||
public void Enabled_WhenSetToFalse_ShouldReturnFalse()
|
[InlineData(false)]
|
||||||
|
[InlineData(true)]
|
||||||
|
public void Enabled_WhenSet_ShouldReturnConfiguredValue(bool enabled)
|
||||||
{
|
{
|
||||||
var options = new BoilerMonitorOptions { Enabled = false };
|
var options = BoilerMonitorTestData.CreateOptions(enabled);
|
||||||
|
|
||||||
|
options.Enabled.Should().Be(enabled);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(false)]
|
||||||
|
[InlineData(true)]
|
||||||
|
public void CleanupEntitiesOnStartup_WhenSet_ShouldReturnConfiguredValue(bool cleanupEntitiesOnStartup)
|
||||||
|
{
|
||||||
|
var options = BoilerMonitorTestData.CreateOptions(cleanupEntitiesOnStartup: cleanupEntitiesOnStartup);
|
||||||
|
|
||||||
|
options.CleanupEntitiesOnStartup.Should().Be(cleanupEntitiesOnStartup);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Options_WhenBothFlagsDisabled_ShouldPreserveEachValueIndependently()
|
||||||
|
{
|
||||||
|
var options = BoilerMonitorTestData.CreateOptions(false, false);
|
||||||
|
|
||||||
options.Enabled.Should().BeFalse();
|
options.Enabled.Should().BeFalse();
|
||||||
|
options.CleanupEntitiesOnStartup.Should().BeFalse();
|
||||||
|
BoilerMonitorOptions.SectionName.Should().Be("BoilerMonitor");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,293 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
|
using System.Text.Json;
|
||||||
|
using BoilerMonitorManager.Models;
|
||||||
|
using Microsoft.Extensions.Time.Testing;
|
||||||
|
using Moq;
|
||||||
|
using NetDaemon.HassModel;
|
||||||
|
using NetDaemon.HassModel.Entities;
|
||||||
|
using static BoilerMonitor.Models.BoilerMonitorConsts;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
namespace BoilerMonitor.Manager.Tests;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Shared, deterministic fixtures used by the BoilerMonitor tests: config/options builders,
|
||||||
|
/// entity-state sets, parse samples and a fixed clock. Keeping them here avoids copy-pasted
|
||||||
|
/// setup and makes every timestamp/DST assertion independent of the real clock.
|
||||||
|
/// </summary>
|
||||||
|
internal static class BoilerMonitorTestData
|
||||||
|
{
|
||||||
|
public const string PowerEntityId = "sensor.sonoff_1002230e32_power";
|
||||||
|
public const string SwitchEntityId = "switch.sonoff_1002230e32";
|
||||||
|
|
||||||
|
/// <summary>Fixed "now" (UTC) used by every time based test.</summary>
|
||||||
|
public static readonly DateTimeOffset BaseTime = new DateTimeOffset(2026, 3, 31, 12, 0, 0, TimeSpan.Zero);
|
||||||
|
|
||||||
|
public static FakeTimeProvider CreateTimeProvider(DateTimeOffset? utcNow = null)
|
||||||
|
{
|
||||||
|
return new FakeTimeProvider(utcNow ?? BaseTime);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static BoilerMonitorConfig CreateConfig(
|
||||||
|
string? boilerPowerEntityId = PowerEntityId,
|
||||||
|
string? boilerSwitchEntityId = SwitchEntityId,
|
||||||
|
int? pollIntervalSeconds = DefaultPollIntervalSeconds,
|
||||||
|
double? heatingPowerThresholdWatts = DefaultHeatingPowerThresholdWatts)
|
||||||
|
{
|
||||||
|
return new BoilerMonitorConfig
|
||||||
|
{
|
||||||
|
BoilerPowerEntityId = boilerPowerEntityId,
|
||||||
|
BoilerSwitchEntityId = boilerSwitchEntityId,
|
||||||
|
PollIntervalSeconds = pollIntervalSeconds,
|
||||||
|
HeatingPowerThresholdWatts = heatingPowerThresholdWatts
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static BoilerMonitorOptions CreateOptions(
|
||||||
|
bool enabled = true,
|
||||||
|
bool cleanupEntitiesOnStartup = true)
|
||||||
|
{
|
||||||
|
return new BoilerMonitorOptions
|
||||||
|
{
|
||||||
|
Enabled = enabled,
|
||||||
|
CleanupEntitiesOnStartup = cleanupEntitiesOnStartup
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static BoilerMonitorUpdateContext CreateUpdateContext(
|
||||||
|
TimeSpan? todayRunTime = null,
|
||||||
|
TimeSpan? remainingTime = null,
|
||||||
|
double budgetPercentage = 50.0,
|
||||||
|
bool budgetExhausted = false,
|
||||||
|
int sessionCount = 1,
|
||||||
|
double budgetHours = 2.0,
|
||||||
|
bool waterReady = false,
|
||||||
|
string? boilerSwitchState = "on",
|
||||||
|
double? boilerPowerWatts = 0.0,
|
||||||
|
DateTimeOffset? cooldownSince = null)
|
||||||
|
{
|
||||||
|
return new BoilerMonitorUpdateContext
|
||||||
|
{
|
||||||
|
TodayRunTime = todayRunTime ?? TimeSpan.FromHours(1),
|
||||||
|
RemainingTime = remainingTime ?? TimeSpan.FromHours(1),
|
||||||
|
BudgetPercentage = budgetPercentage,
|
||||||
|
BudgetExhausted = budgetExhausted,
|
||||||
|
SessionCount = sessionCount,
|
||||||
|
BudgetHours = budgetHours,
|
||||||
|
WaterReady = waterReady,
|
||||||
|
BoilerSwitchState = boilerSwitchState,
|
||||||
|
BoilerPowerWatts = boilerPowerWatts,
|
||||||
|
CooldownSince = cooldownSince
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The four entity states <c>ReadPersistedState</c> reads, with valid defaults.
|
||||||
|
/// A null value means the entity does not exist in Home Assistant.
|
||||||
|
/// </summary>
|
||||||
|
public static Dictionary<string, string?> CreatePersistedEntityStates(
|
||||||
|
string? todayRuntime = "7200",
|
||||||
|
string? sessionCount = "3",
|
||||||
|
string? skipPriceCap = "OFF",
|
||||||
|
string? budgetOverride = "OFF")
|
||||||
|
{
|
||||||
|
return new Dictionary<string, string?>
|
||||||
|
{
|
||||||
|
[TodayRuntimeEntityId] = todayRuntime,
|
||||||
|
[SessionCountEntityId] = sessionCount,
|
||||||
|
[SkipPriceCapEntityId] = skipPriceCap,
|
||||||
|
[BudgetOverrideEntityId] = budgetOverride
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public static EntityState CreateEntityState(string state)
|
||||||
|
{
|
||||||
|
return new EntityState { State = state };
|
||||||
|
}
|
||||||
|
|
||||||
|
public static EntityState CreateEntityStateWithAttributes(IReadOnlyDictionary<string, object?> attributes)
|
||||||
|
{
|
||||||
|
return new EntityState { State = "yes", AttributesJson = JsonSerializer.SerializeToElement(attributes) };
|
||||||
|
}
|
||||||
|
|
||||||
|
public static EntityState CreateWaterReadyEntityStateWithCooldown(object? cooldownSince)
|
||||||
|
{
|
||||||
|
return CreateEntityStateWithAttributes(new Dictionary<string, object?> { ["cooldown_since"] = cooldownSince });
|
||||||
|
}
|
||||||
|
|
||||||
|
extension(Mock<IHaContext> haContextMock)
|
||||||
|
{
|
||||||
|
public void SetupEntityStates(IReadOnlyDictionary<string, string?> states)
|
||||||
|
{
|
||||||
|
foreach (var (entityId, state) in states)
|
||||||
|
{
|
||||||
|
var entityState = state is null ? null : CreateEntityState(state);
|
||||||
|
haContextMock.Setup(h => h.GetState(entityId)).Returns(entityState);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void SetupEntityState(string entityId, EntityState? entityState)
|
||||||
|
{
|
||||||
|
haContextMock.Setup(h => h.GetState(entityId)).Returns(entityState);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Entity-state samples for the today-runtime sensor: valid values with the expected
|
||||||
|
/// <see cref="TimeSpan" />, plus unavailable/negative/overflow values that must be rejected.
|
||||||
|
/// </summary>
|
||||||
|
public static TheoryData<string?, TimeSpan?> RuntimeStateSamples()
|
||||||
|
{
|
||||||
|
var data = new TheoryData<string?, TimeSpan?>();
|
||||||
|
data.Add("7200", TimeSpan.FromHours(2));
|
||||||
|
data.Add("0", TimeSpan.Zero);
|
||||||
|
data.Add("134.66", TimeSpan.FromSeconds(134.66));
|
||||||
|
data.Add("1E3", TimeSpan.FromSeconds(1000));
|
||||||
|
data.Add("0.001", TimeSpan.FromSeconds(0.001));
|
||||||
|
data.Add(" 60 ", TimeSpan.FromSeconds(60));
|
||||||
|
data.Add("86400", TimeSpan.FromDays(1));
|
||||||
|
data.Add("1e9", TimeSpan.FromSeconds(1e9));
|
||||||
|
|
||||||
|
data.Add(null, null);
|
||||||
|
data.Add(string.Empty, null);
|
||||||
|
data.Add(" ", null);
|
||||||
|
data.Add("\t", null);
|
||||||
|
data.Add("unavailable", null);
|
||||||
|
data.Add("unknown", null);
|
||||||
|
data.Add("Unavailable", null);
|
||||||
|
data.Add("not_a_number", null);
|
||||||
|
data.Add("NaN", null);
|
||||||
|
data.Add("Infinity", null);
|
||||||
|
data.Add("1e308", null);
|
||||||
|
data.Add("-1", null);
|
||||||
|
data.Add("-0.001", null);
|
||||||
|
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Entity-state samples for the session-count sensor, including the int boundaries.
|
||||||
|
/// </summary>
|
||||||
|
public static TheoryData<string?, int?> SessionCountStateSamples()
|
||||||
|
{
|
||||||
|
var data = new TheoryData<string?, int?>();
|
||||||
|
data.Add("0", 0);
|
||||||
|
data.Add("3", 3);
|
||||||
|
data.Add(" 2 ", 2);
|
||||||
|
data.Add("+4", 4);
|
||||||
|
data.Add("2147483647", int.MaxValue);
|
||||||
|
|
||||||
|
data.Add(null, null);
|
||||||
|
data.Add(string.Empty, null);
|
||||||
|
data.Add(" ", null);
|
||||||
|
data.Add("\t", null);
|
||||||
|
data.Add("unavailable", null);
|
||||||
|
data.Add("unknown", null);
|
||||||
|
data.Add("abc", null);
|
||||||
|
data.Add("1.5", null);
|
||||||
|
data.Add("-1", null);
|
||||||
|
data.Add("2147483648", null);
|
||||||
|
data.Add("1e3", null);
|
||||||
|
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Water-ready detection samples around the heating threshold, including negative,
|
||||||
|
/// zero, exact-boundary, huge and NaN readings.
|
||||||
|
/// </summary>
|
||||||
|
public static TheoryData<string, double, bool> PowerReadingSamples()
|
||||||
|
{
|
||||||
|
var data = new TheoryData<string, double, bool>();
|
||||||
|
data.Add("negative sensor glitch", -1_000.0, true);
|
||||||
|
data.Add("just below zero", -0.001, true);
|
||||||
|
data.Add("zero", 0.0, true);
|
||||||
|
data.Add("just below threshold", 4.999, true);
|
||||||
|
data.Add("exactly at threshold", 5.0, false);
|
||||||
|
data.Add("just above threshold", 5.001, false);
|
||||||
|
data.Add("actively heating", 2_150.0, false);
|
||||||
|
data.Add("maximum", double.MaxValue, false);
|
||||||
|
data.Add("not-a-number", double.NaN, true);
|
||||||
|
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Elapsed-time sweep showing that the water-ready cooldown never expires on its own.
|
||||||
|
/// </summary>
|
||||||
|
public static TheoryData<TimeSpan> GeneratedElapsedTimes()
|
||||||
|
{
|
||||||
|
var data = new TheoryData<TimeSpan>();
|
||||||
|
data.Add(TimeSpan.FromHours(1));
|
||||||
|
data.Add(TimeSpan.FromHours(2));
|
||||||
|
data.Add(TimeSpan.FromHours(6));
|
||||||
|
data.Add(TimeSpan.FromHours(12));
|
||||||
|
data.Add(TimeSpan.FromHours(23));
|
||||||
|
data.Add(TimeSpan.FromHours(24));
|
||||||
|
data.Add(TimeSpan.FromHours(25));
|
||||||
|
data.Add(TimeSpan.FromHours(48));
|
||||||
|
data.Add(TimeSpan.FromHours(168));
|
||||||
|
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Cooldown restore samples around the UTC-midnight cut-off, including DST start/end
|
||||||
|
/// timestamps carrying non-zero offsets.
|
||||||
|
/// </summary>
|
||||||
|
public static TheoryData<string, DateTimeOffset, DateTimeOffset, bool> CooldownRestoreSamples()
|
||||||
|
{
|
||||||
|
var data = new TheoryData<string, DateTimeOffset, DateTimeOffset, bool>();
|
||||||
|
data.Add("30 minutes ago", BaseTime, BaseTime - TimeSpan.FromMinutes(30), true);
|
||||||
|
data.Add("5 hours ago", BaseTime, BaseTime - TimeSpan.FromHours(5), true);
|
||||||
|
data.Add("exactly at today's UTC midnight", BaseTime, TodayMidnight(), true);
|
||||||
|
data.Add("one tick after today's UTC midnight", BaseTime, TodayMidnight().AddTicks(1), true);
|
||||||
|
data.Add("one tick before today's UTC midnight", BaseTime, TodayMidnight().AddTicks(-1), false);
|
||||||
|
data.Add("one second before today's UTC midnight", BaseTime, TodayMidnight().AddSeconds(-1), false);
|
||||||
|
data.Add("yesterday same time", BaseTime, BaseTime.AddDays(-1), false);
|
||||||
|
data.Add("two days ago", BaseTime, BaseTime.AddDays(-2), false);
|
||||||
|
data.Add("future timestamp", BaseTime, BaseTime.AddHours(1), true);
|
||||||
|
data.Add("maximum timestamp", BaseTime, DateTimeOffset.MaxValue, true);
|
||||||
|
|
||||||
|
// Europe DST starts 2026-03-29 02:00 CET → 03:00 CEST.
|
||||||
|
// now = 03:30+02:00 = 01:30Z, so UTC midnight is 2026-03-29T00:00Z.
|
||||||
|
data.Add(
|
||||||
|
"DST spring-forward, same UTC day",
|
||||||
|
new DateTimeOffset(2026, 3, 29, 3, 30, 0, TimeSpan.FromHours(2)),
|
||||||
|
new DateTimeOffset(2026, 3, 29, 1, 30, 0, TimeSpan.FromHours(1)),
|
||||||
|
true
|
||||||
|
);
|
||||||
|
|
||||||
|
data.Add(
|
||||||
|
"DST spring-forward, previous UTC day",
|
||||||
|
new DateTimeOffset(2026, 3, 29, 3, 30, 0, TimeSpan.FromHours(2)),
|
||||||
|
new DateTimeOffset(2026, 3, 28, 23, 30, 0, TimeSpan.FromHours(1)),
|
||||||
|
false
|
||||||
|
);
|
||||||
|
|
||||||
|
// Europe DST ends 2026-10-25 03:00 CEST → 02:00 CET. The 02:30 wall-clock hour occurs twice.
|
||||||
|
// now = 03:30+01:00 = 02:30Z, timestamp 02:30+02:00 = 00:30Z is still "today" in UTC.
|
||||||
|
data.Add(
|
||||||
|
"DST fall-back, ambiguous local hour",
|
||||||
|
new DateTimeOffset(2026, 10, 25, 3, 30, 0, TimeSpan.FromHours(1)),
|
||||||
|
new DateTimeOffset(2026, 10, 25, 2, 30, 0, TimeSpan.FromHours(2)),
|
||||||
|
true
|
||||||
|
);
|
||||||
|
|
||||||
|
data.Add(
|
||||||
|
"crossing midnight between restore and now",
|
||||||
|
new DateTimeOffset(2026, 4, 1, 0, 0, 1, TimeSpan.Zero),
|
||||||
|
new DateTimeOffset(2026, 3, 31, 23, 59, 59, TimeSpan.Zero),
|
||||||
|
false
|
||||||
|
);
|
||||||
|
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static DateTimeOffset TodayMidnight()
|
||||||
|
{
|
||||||
|
return new DateTimeOffset(BaseTime.Date, TimeSpan.Zero);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,254 +0,0 @@
|
|||||||
using FluentAssertions;
|
|
||||||
using BoilerMonitorManager;
|
|
||||||
|
|
||||||
namespace BoilerMonitor.Manager.Tests;
|
|
||||||
|
|
||||||
public class BoilerRunTimeTrackerTests
|
|
||||||
{
|
|
||||||
private readonly BoilerRunTimeTracker _sut = new();
|
|
||||||
|
|
||||||
#region RecordPollResult
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void RecordPollResult_WhenHeating_ShouldAccumulateRunTime()
|
|
||||||
{
|
|
||||||
var interval = TimeSpan.FromSeconds(30);
|
|
||||||
|
|
||||||
_sut.RecordPollResult(true, interval);
|
|
||||||
_sut.RecordPollResult(true, interval);
|
|
||||||
_sut.RecordPollResult(true, interval);
|
|
||||||
|
|
||||||
var snapshot = _sut.GetSnapshot();
|
|
||||||
snapshot.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(90));
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void RecordPollResult_WhenNotHeating_ShouldNotAccumulate()
|
|
||||||
{
|
|
||||||
var interval = TimeSpan.FromSeconds(30);
|
|
||||||
|
|
||||||
_sut.RecordPollResult(false, interval);
|
|
||||||
_sut.RecordPollResult(false, interval);
|
|
||||||
|
|
||||||
var snapshot = _sut.GetSnapshot();
|
|
||||||
snapshot.AccumulatedRunTime.Should().Be(TimeSpan.Zero);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void RecordPollResult_WhenHeatingStarts_ShouldIncrementSessionCount()
|
|
||||||
{
|
|
||||||
var interval = TimeSpan.FromSeconds(30);
|
|
||||||
|
|
||||||
_sut.RecordPollResult(true, interval);
|
|
||||||
|
|
||||||
var snapshot = _sut.GetSnapshot();
|
|
||||||
snapshot.SessionCount.Should().Be(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void RecordPollResult_ContinuousHeating_ShouldCountAsOneSession()
|
|
||||||
{
|
|
||||||
var interval = TimeSpan.FromSeconds(30);
|
|
||||||
|
|
||||||
_sut.RecordPollResult(true, interval);
|
|
||||||
_sut.RecordPollResult(true, interval);
|
|
||||||
_sut.RecordPollResult(true, interval);
|
|
||||||
|
|
||||||
var snapshot = _sut.GetSnapshot();
|
|
||||||
snapshot.SessionCount.Should().Be(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void RecordPollResult_HeatingStopsAndRestarts_ShouldCountAsTwoSessions()
|
|
||||||
{
|
|
||||||
var interval = TimeSpan.FromSeconds(30);
|
|
||||||
|
|
||||||
_sut.RecordPollResult(true, interval);
|
|
||||||
_sut.RecordPollResult(false, interval);
|
|
||||||
_sut.RecordPollResult(true, interval);
|
|
||||||
|
|
||||||
var snapshot = _sut.GetSnapshot();
|
|
||||||
snapshot.SessionCount.Should().Be(2);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void RecordPollResult_MultipleSessions_ShouldAccumulateCorrectly()
|
|
||||||
{
|
|
||||||
var interval = TimeSpan.FromSeconds(30);
|
|
||||||
|
|
||||||
_sut.RecordPollResult(true, interval);
|
|
||||||
_sut.RecordPollResult(true, interval);
|
|
||||||
_sut.RecordPollResult(false, interval);
|
|
||||||
_sut.RecordPollResult(true, interval);
|
|
||||||
|
|
||||||
var snapshot = _sut.GetSnapshot();
|
|
||||||
snapshot.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(90));
|
|
||||||
snapshot.SessionCount.Should().Be(2);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void RecordPollResult_WhenHeating_ShouldSetIsInSessionTrue()
|
|
||||||
{
|
|
||||||
_sut.RecordPollResult(true, TimeSpan.FromSeconds(30));
|
|
||||||
|
|
||||||
var snapshot = _sut.GetSnapshot();
|
|
||||||
snapshot.IsInSession.Should().BeTrue();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void RecordPollResult_WhenNotHeating_ShouldSetIsInSessionFalse()
|
|
||||||
{
|
|
||||||
_sut.RecordPollResult(true, TimeSpan.FromSeconds(30));
|
|
||||||
_sut.RecordPollResult(false, TimeSpan.FromSeconds(30));
|
|
||||||
|
|
||||||
var snapshot = _sut.GetSnapshot();
|
|
||||||
snapshot.IsInSession.Should().BeFalse();
|
|
||||||
}
|
|
||||||
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
#region Reset
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Reset_ShouldClearAllState()
|
|
||||||
{
|
|
||||||
var interval = TimeSpan.FromSeconds(30);
|
|
||||||
_sut.RecordPollResult(true, interval);
|
|
||||||
_sut.RecordPollResult(true, interval);
|
|
||||||
|
|
||||||
_sut.Reset();
|
|
||||||
|
|
||||||
var snapshot = _sut.GetSnapshot();
|
|
||||||
snapshot.AccumulatedRunTime.Should().Be(TimeSpan.Zero);
|
|
||||||
snapshot.SessionCount.Should().Be(0);
|
|
||||||
snapshot.IsInSession.Should().BeFalse();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void Reset_AfterReset_ShouldAccumulateFromZero()
|
|
||||||
{
|
|
||||||
var interval = TimeSpan.FromSeconds(30);
|
|
||||||
_sut.RecordPollResult(true, interval);
|
|
||||||
_sut.Reset();
|
|
||||||
_sut.RecordPollResult(true, interval);
|
|
||||||
|
|
||||||
var snapshot = _sut.GetSnapshot();
|
|
||||||
snapshot.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(30));
|
|
||||||
snapshot.SessionCount.Should().Be(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
#region RestoreFromSnapshot
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void RestoreFromSnapshot_ShouldSetAccumulatedRunTimeAndSessionCount()
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
var runTime = TimeSpan.FromMinutes(45);
|
|
||||||
const int sessionCount = 3;
|
|
||||||
|
|
||||||
// Act
|
|
||||||
_sut.RestoreFromSnapshot(runTime, sessionCount);
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
var snapshot = _sut.GetSnapshot();
|
|
||||||
snapshot.AccumulatedRunTime.Should().Be(runTime);
|
|
||||||
snapshot.SessionCount.Should().Be(sessionCount);
|
|
||||||
snapshot.IsInSession.Should().BeFalse();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void RestoreFromSnapshot_ShouldOverwriteExistingState()
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
_sut.RecordPollResult(true, TimeSpan.FromSeconds(30));
|
|
||||||
_sut.RecordPollResult(true, TimeSpan.FromSeconds(30));
|
|
||||||
|
|
||||||
var restoredRunTime = TimeSpan.FromHours(2);
|
|
||||||
const int restoredSessions = 5;
|
|
||||||
|
|
||||||
// Act
|
|
||||||
_sut.RestoreFromSnapshot(restoredRunTime, restoredSessions);
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
var snapshot = _sut.GetSnapshot();
|
|
||||||
snapshot.AccumulatedRunTime.Should().Be(restoredRunTime);
|
|
||||||
snapshot.SessionCount.Should().Be(restoredSessions);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void RestoreFromSnapshot_ShouldAllowFurtherAccumulationFromRestoredState()
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
var restoredRunTime = TimeSpan.FromMinutes(30);
|
|
||||||
const int restoredSessions = 2;
|
|
||||||
var pollInterval = TimeSpan.FromSeconds(30);
|
|
||||||
|
|
||||||
_sut.RestoreFromSnapshot(restoredRunTime, restoredSessions);
|
|
||||||
|
|
||||||
// Act
|
|
||||||
_sut.RecordPollResult(true, pollInterval);
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
var snapshot = _sut.GetSnapshot();
|
|
||||||
snapshot.AccumulatedRunTime.Should().Be(restoredRunTime + pollInterval);
|
|
||||||
snapshot.SessionCount.Should().Be(restoredSessions + 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void RestoreFromSnapshot_WithZeroValues_ShouldSetToZero()
|
|
||||||
{
|
|
||||||
// Arrange
|
|
||||||
_sut.RecordPollResult(true, TimeSpan.FromSeconds(30));
|
|
||||||
|
|
||||||
// Act
|
|
||||||
_sut.RestoreFromSnapshot(TimeSpan.Zero, 0);
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
var snapshot = _sut.GetSnapshot();
|
|
||||||
snapshot.AccumulatedRunTime.Should().Be(TimeSpan.Zero);
|
|
||||||
snapshot.SessionCount.Should().Be(0);
|
|
||||||
}
|
|
||||||
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
#region Thread safety
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public async Task RecordPollResult_ConcurrentCalls_ShouldNotCorruptState()
|
|
||||||
{
|
|
||||||
var interval = TimeSpan.FromSeconds(1);
|
|
||||||
const int iterationsPerThread = 1000;
|
|
||||||
const int threadCount = 4;
|
|
||||||
|
|
||||||
var tasks = Enumerable.Range(0, threadCount).Select(_ => Task.Run(() =>
|
|
||||||
{
|
|
||||||
for (var i = 0; i < iterationsPerThread; i++)
|
|
||||||
{
|
|
||||||
_sut.RecordPollResult(true, interval);
|
|
||||||
}
|
|
||||||
})).ToArray();
|
|
||||||
|
|
||||||
await Task.WhenAll(tasks);
|
|
||||||
|
|
||||||
var snapshot = _sut.GetSnapshot();
|
|
||||||
snapshot.AccumulatedRunTime.Should().Be(TimeSpan.FromSeconds(iterationsPerThread * threadCount));
|
|
||||||
}
|
|
||||||
|
|
||||||
#endregion
|
|
||||||
|
|
||||||
#region GetSnapshot
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void GetSnapshot_Initial_ShouldReturnZeroState()
|
|
||||||
{
|
|
||||||
var snapshot = _sut.GetSnapshot();
|
|
||||||
|
|
||||||
snapshot.AccumulatedRunTime.Should().Be(TimeSpan.Zero);
|
|
||||||
snapshot.SessionCount.Should().Be(0);
|
|
||||||
snapshot.IsInSession.Should().BeFalse();
|
|
||||||
}
|
|
||||||
|
|
||||||
#endregion
|
|
||||||
}
|
|
||||||
@@ -1,9 +1,13 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
using BoilerMonitor.Models;
|
using BoilerMonitor.Models;
|
||||||
|
using BoilerMonitorManager;
|
||||||
using FluentAssertions;
|
using FluentAssertions;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using Microsoft.Extensions.Time.Testing;
|
using Microsoft.Extensions.Time.Testing;
|
||||||
using Moq;
|
using Moq;
|
||||||
using BoilerMonitorManager;
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace BoilerMonitor.Manager.Tests;
|
namespace BoilerMonitor.Manager.Tests;
|
||||||
|
|
||||||
@@ -11,45 +15,55 @@ public class WaterReadyServiceTests
|
|||||||
{
|
{
|
||||||
private const double Threshold = BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts;
|
private const double Threshold = BoilerMonitorConsts.DefaultHeatingPowerThresholdWatts;
|
||||||
private const double HighPowerWatts = 2150.0;
|
private const double HighPowerWatts = 2150.0;
|
||||||
|
private const int RequiredReadings = BoilerMonitorConsts.ConsecutiveReadingsRequired;
|
||||||
|
|
||||||
private readonly Mock<ILogger<WaterReadyService>> _loggerMock;
|
private readonly Mock<ILogger<WaterReadyService>> _loggerMock = new Mock<ILogger<WaterReadyService>>();
|
||||||
private readonly FakeTimeProvider _timeProvider;
|
private readonly FakeTimeProvider _timeProvider = BoilerMonitorTestData.CreateTimeProvider();
|
||||||
|
|
||||||
public WaterReadyServiceTests()
|
private WaterReadyService CreateSut()
|
||||||
{
|
{
|
||||||
_loggerMock = new Mock<ILogger<WaterReadyService>>();
|
return new WaterReadyService(_loggerMock.Object, _timeProvider);
|
||||||
_timeProvider = new FakeTimeProvider(DateTimeOffset.UtcNow);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private WaterReadyService CreateSut() => new(_loggerMock.Object, _timeProvider);
|
|
||||||
|
|
||||||
private WaterReadyService CreateSutWithHeatingObserved()
|
private WaterReadyService CreateSutWithHeatingObserved()
|
||||||
{
|
{
|
||||||
var sut = CreateSut();
|
var sut = CreateSut();
|
||||||
sut.RecordHeatingObserved();
|
sut.RecordHeatingObserved();
|
||||||
|
|
||||||
return sut;
|
return sut;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static bool TriggerWaterReady(WaterReadyService sut, double powerWatts = 0.0)
|
private static bool FeedReadings(
|
||||||
|
WaterReadyService sut,
|
||||||
|
int count,
|
||||||
|
string? switchState = "on",
|
||||||
|
double? powerWatts = 0.0,
|
||||||
|
double heatingThresholdWatts = Threshold)
|
||||||
{
|
{
|
||||||
var result = false;
|
var result = false;
|
||||||
for (var i = 0; i < BoilerMonitorConsts.ConsecutiveReadingsRequired; i++)
|
|
||||||
|
for (var i = 0; i < count; i++)
|
||||||
{
|
{
|
||||||
result = sut.IsWaterReady("on", powerWatts, Threshold);
|
result = sut.IsWaterReady(switchState, powerWatts, heatingThresholdWatts);
|
||||||
}
|
}
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
#region Heating observation prerequisite
|
#region Heating observation prerequisite
|
||||||
|
|
||||||
[Fact]
|
[Theory]
|
||||||
public void IsWaterReady_SwitchOnLowPowerButNeverObservedHeating_ShouldReturnFalse()
|
[InlineData(1)]
|
||||||
|
[InlineData(2)]
|
||||||
|
[InlineData(10)]
|
||||||
|
public void IsWaterReady_WhenHeatingWasNeverObserved_ShouldAlwaysReturnFalse(int readingCount)
|
||||||
{
|
{
|
||||||
var sut = CreateSut();
|
var sut = CreateSut();
|
||||||
|
|
||||||
var result = sut.IsWaterReady("on", 0.0, Threshold);
|
var result = FeedReadings(sut, readingCount);
|
||||||
|
|
||||||
result.Should().BeFalse();
|
result.Should().BeFalse();
|
||||||
|
sut.IsInCooldown.Should().BeFalse();
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -57,7 +71,7 @@ public class WaterReadyServiceTests
|
|||||||
{
|
{
|
||||||
var sut = CreateSutWithHeatingObserved();
|
var sut = CreateSutWithHeatingObserved();
|
||||||
|
|
||||||
var result = TriggerWaterReady(sut);
|
var result = FeedReadings(sut, RequiredReadings);
|
||||||
|
|
||||||
result.Should().BeTrue();
|
result.Should().BeTrue();
|
||||||
}
|
}
|
||||||
@@ -66,11 +80,21 @@ public class WaterReadyServiceTests
|
|||||||
public void RecordHeatingObserved_ShouldEnableDetection()
|
public void RecordHeatingObserved_ShouldEnableDetection()
|
||||||
{
|
{
|
||||||
var sut = CreateSut();
|
var sut = CreateSut();
|
||||||
|
|
||||||
sut.RecordHeatingObserved();
|
sut.RecordHeatingObserved();
|
||||||
|
|
||||||
var result = TriggerWaterReady(sut);
|
FeedReadings(sut, RequiredReadings).Should().BeTrue();
|
||||||
|
}
|
||||||
|
|
||||||
result.Should().BeTrue();
|
[Fact]
|
||||||
|
public void RecordHeatingObserved_WhenCalledRepeatedly_ShouldStayEnabled()
|
||||||
|
{
|
||||||
|
var sut = CreateSut();
|
||||||
|
|
||||||
|
sut.RecordHeatingObserved();
|
||||||
|
sut.RecordHeatingObserved();
|
||||||
|
|
||||||
|
FeedReadings(sut, RequiredReadings).Should().BeTrue();
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -79,7 +103,7 @@ public class WaterReadyServiceTests
|
|||||||
var sut = CreateSutWithHeatingObserved();
|
var sut = CreateSutWithHeatingObserved();
|
||||||
sut.NotifyTurnedOn();
|
sut.NotifyTurnedOn();
|
||||||
|
|
||||||
var result = sut.IsWaterReady("on", 0.0, Threshold);
|
var result = FeedReadings(sut, 10);
|
||||||
|
|
||||||
result.Should().BeFalse("heating observation was reset by NotifyTurnedOn");
|
result.Should().BeFalse("heating observation was reset by NotifyTurnedOn");
|
||||||
}
|
}
|
||||||
@@ -91,20 +115,34 @@ public class WaterReadyServiceTests
|
|||||||
sut.NotifyTurnedOn();
|
sut.NotifyTurnedOn();
|
||||||
sut.RecordHeatingObserved();
|
sut.RecordHeatingObserved();
|
||||||
|
|
||||||
var result = TriggerWaterReady(sut);
|
var result = FeedReadings(sut, RequiredReadings);
|
||||||
|
|
||||||
result.Should().BeTrue();
|
result.Should().BeTrue();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ResetCooldown_ShouldKeepHeatingObservationEnabled()
|
||||||
|
{
|
||||||
|
var sut = CreateSutWithHeatingObserved();
|
||||||
|
FeedReadings(sut, RequiredReadings).Should().BeTrue();
|
||||||
|
|
||||||
|
sut.ResetCooldown();
|
||||||
|
|
||||||
|
FeedReadings(sut, RequiredReadings)
|
||||||
|
.Should()
|
||||||
|
.BeTrue(
|
||||||
|
"ResetCooldown clears the cooldown and counter, not the heating observation");
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void IsWaterReady_AfterResetAndReObservedHeating_ShouldTriggerAgain()
|
public void IsWaterReady_AfterResetAndReObservedHeating_ShouldTriggerAgain()
|
||||||
{
|
{
|
||||||
var sut = CreateSutWithHeatingObserved();
|
var sut = CreateSutWithHeatingObserved();
|
||||||
TriggerWaterReady(sut);
|
FeedReadings(sut, RequiredReadings);
|
||||||
sut.ResetCooldown();
|
sut.ResetCooldown();
|
||||||
|
|
||||||
sut.RecordHeatingObserved();
|
sut.RecordHeatingObserved();
|
||||||
var result = TriggerWaterReady(sut);
|
var result = FeedReadings(sut, RequiredReadings);
|
||||||
|
|
||||||
result.Should().BeTrue("detection should work again after reset + new heating observation");
|
result.Should().BeTrue("detection should work again after reset + new heating observation");
|
||||||
}
|
}
|
||||||
@@ -113,112 +151,99 @@ public class WaterReadyServiceTests
|
|||||||
|
|
||||||
#region Debouncing (consecutive readings)
|
#region Debouncing (consecutive readings)
|
||||||
|
|
||||||
[Fact]
|
[Theory]
|
||||||
public void IsWaterReady_SingleBelowThresholdReading_ShouldReturnFalse()
|
[InlineData(1, false)]
|
||||||
|
[InlineData(2, true)]
|
||||||
|
[InlineData(3, true)]
|
||||||
|
[InlineData(10, true)]
|
||||||
|
public void IsWaterReady_ShouldRequireConsecutiveBelowThresholdReadings(int readingCount, bool expected)
|
||||||
{
|
{
|
||||||
var sut = CreateSutWithHeatingObserved();
|
var sut = CreateSutWithHeatingObserved();
|
||||||
|
|
||||||
var result = sut.IsWaterReady("on", 0.0, Threshold);
|
var result = FeedReadings(sut, readingCount);
|
||||||
|
|
||||||
result.Should().BeFalse("only 1 consecutive reading, need {0}",
|
result.Should().Be(expected);
|
||||||
BoilerMonitorConsts.ConsecutiveReadingsRequired);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Theory]
|
||||||
public void IsWaterReady_ConsecutiveBelowThresholdReadings_ShouldReturnTrue()
|
[InlineData(HighPowerWatts)]
|
||||||
|
[InlineData(Threshold)]
|
||||||
|
[InlineData(double.MaxValue)]
|
||||||
|
public void IsWaterReady_WhenReadingIsAtOrAboveThreshold_ShouldResetConsecutiveCount(double powerWatts)
|
||||||
{
|
{
|
||||||
var sut = CreateSutWithHeatingObserved();
|
var sut = CreateSutWithHeatingObserved();
|
||||||
|
FeedReadings(sut, RequiredReadings - 1).Should().BeFalse();
|
||||||
|
|
||||||
var result = TriggerWaterReady(sut);
|
sut.IsWaterReady("on", powerWatts, Threshold).Should().BeFalse("power is not below the threshold");
|
||||||
|
|
||||||
result.Should().BeTrue();
|
FeedReadings(sut, 1).Should().BeFalse("the counter was reset by the above-threshold reading");
|
||||||
|
FeedReadings(sut, RequiredReadings - 1).Should().BeTrue();
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Theory]
|
||||||
public void IsWaterReady_BelowThresholdResetByAboveThreshold_ShouldRequireConsecutiveAgain()
|
[InlineData(0)]
|
||||||
|
[InlineData(1)]
|
||||||
|
public void IsWaterReady_NotifyTurnedOn_ShouldResetConsecutiveCount(int belowThresholdBeforeTurnOn)
|
||||||
{
|
{
|
||||||
var sut = CreateSutWithHeatingObserved();
|
var sut = CreateSutWithHeatingObserved();
|
||||||
|
FeedReadings(sut, belowThresholdBeforeTurnOn);
|
||||||
|
|
||||||
sut.IsWaterReady("on", 0.0, Threshold);
|
|
||||||
sut.IsWaterReady("on", HighPowerWatts, Threshold);
|
|
||||||
var result = sut.IsWaterReady("on", 0.0, Threshold);
|
|
||||||
|
|
||||||
result.Should().BeFalse("counter was reset by above-threshold reading");
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void IsWaterReady_NotifyTurnedOn_ShouldResetConsecutiveCount()
|
|
||||||
{
|
|
||||||
var sut = CreateSutWithHeatingObserved();
|
|
||||||
|
|
||||||
sut.IsWaterReady("on", 0.0, Threshold);
|
|
||||||
sut.NotifyTurnedOn();
|
sut.NotifyTurnedOn();
|
||||||
sut.RecordHeatingObserved();
|
sut.RecordHeatingObserved();
|
||||||
var result = sut.IsWaterReady("on", 0.0, Threshold);
|
|
||||||
|
|
||||||
result.Should().BeFalse("NotifyTurnedOn reset the consecutive counter");
|
FeedReadings(sut, RequiredReadings - 1).Should().BeFalse("NotifyTurnedOn reset the consecutive counter");
|
||||||
|
FeedReadings(sut, 1).Should().BeTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void IsWaterReady_InterleavedReadings_ShouldOnlyTriggerAfterLastConsecutiveLowReading()
|
||||||
|
{
|
||||||
|
var sut = CreateSutWithHeatingObserved();
|
||||||
|
|
||||||
|
var results = new[]
|
||||||
|
{
|
||||||
|
sut.IsWaterReady("on", 0.0, Threshold),
|
||||||
|
sut.IsWaterReady("on", HighPowerWatts, Threshold),
|
||||||
|
sut.IsWaterReady("on", 0.0, Threshold),
|
||||||
|
sut.IsWaterReady("on", 0.0, Threshold)
|
||||||
|
};
|
||||||
|
|
||||||
|
results.Should().Equal(false, false, false, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
#endregion
|
#endregion
|
||||||
|
|
||||||
#region Basic state checks
|
#region Basic state checks
|
||||||
|
|
||||||
[Fact]
|
[Theory]
|
||||||
public void IsWaterReady_SwitchOnAndPowerAtThreshold_ShouldReturnFalse()
|
[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 sut = CreateSutWithHeatingObserved();
|
||||||
|
|
||||||
var result = sut.IsWaterReady("on", Threshold, Threshold);
|
var result = FeedReadings(sut, 10, switchState);
|
||||||
|
|
||||||
result.Should().BeFalse();
|
result.Should().BeFalse();
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Theory]
|
||||||
public void IsWaterReady_SwitchOnAndHighPower_ShouldReturnFalse()
|
[InlineData("on", null)]
|
||||||
|
[InlineData(null, 0.0)]
|
||||||
|
[InlineData(null, null)]
|
||||||
|
[InlineData("", null)]
|
||||||
|
[InlineData("", 0.0)]
|
||||||
|
public void IsWaterReady_WhenSwitchStateOrPowerIsNull_ShouldReturnFalse(string? switchState, double? powerWatts)
|
||||||
{
|
{
|
||||||
var sut = CreateSutWithHeatingObserved();
|
var sut = CreateSutWithHeatingObserved();
|
||||||
|
|
||||||
var result = sut.IsWaterReady("on", HighPowerWatts, Threshold);
|
var result = FeedReadings(sut, 10, switchState, powerWatts);
|
||||||
|
|
||||||
result.Should().BeFalse();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void IsWaterReady_SwitchOff_ShouldReturnFalse()
|
|
||||||
{
|
|
||||||
var sut = CreateSutWithHeatingObserved();
|
|
||||||
|
|
||||||
var result = sut.IsWaterReady("off", 0.0, Threshold);
|
|
||||||
|
|
||||||
result.Should().BeFalse();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void IsWaterReady_NullSwitchState_ShouldReturnFalse()
|
|
||||||
{
|
|
||||||
var sut = CreateSutWithHeatingObserved();
|
|
||||||
|
|
||||||
var result = sut.IsWaterReady(null, 0.0, Threshold);
|
|
||||||
|
|
||||||
result.Should().BeFalse();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void IsWaterReady_NullPowerWatts_ShouldReturnFalse()
|
|
||||||
{
|
|
||||||
var sut = CreateSutWithHeatingObserved();
|
|
||||||
|
|
||||||
var result = sut.IsWaterReady("on", null, Threshold);
|
|
||||||
|
|
||||||
result.Should().BeFalse();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void IsWaterReady_BothNull_ShouldReturnFalse()
|
|
||||||
{
|
|
||||||
var sut = CreateSut();
|
|
||||||
|
|
||||||
var result = sut.IsWaterReady(null, null, Threshold);
|
|
||||||
|
|
||||||
result.Should().BeFalse();
|
result.Should().BeFalse();
|
||||||
}
|
}
|
||||||
@@ -226,33 +251,51 @@ public class WaterReadyServiceTests
|
|||||||
[Theory]
|
[Theory]
|
||||||
[InlineData("ON")]
|
[InlineData("ON")]
|
||||||
[InlineData("On")]
|
[InlineData("On")]
|
||||||
[InlineData("on")]
|
[InlineData("oN")]
|
||||||
public void IsWaterReady_SwitchOnCaseInsensitive_ShouldReturnTrue(string switchState)
|
public void IsWaterReady_SwitchOnCaseInsensitive_ShouldReturnTrue(string switchState)
|
||||||
{
|
{
|
||||||
var sut = CreateSutWithHeatingObserved();
|
var sut = CreateSutWithHeatingObserved();
|
||||||
|
|
||||||
var result = false;
|
var result = FeedReadings(sut, RequiredReadings, switchState);
|
||||||
for (var i = 0; i < BoilerMonitorConsts.ConsecutiveReadingsRequired; i++)
|
|
||||||
{
|
|
||||||
result = sut.IsWaterReady(switchState, 0.0, Threshold);
|
|
||||||
}
|
|
||||||
|
|
||||||
result.Should().BeTrue();
|
result.Should().BeTrue();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[MemberData(nameof(BoilerMonitorTestData.PowerReadingSamples), MemberType = typeof(BoilerMonitorTestData))]
|
||||||
|
public void IsWaterReady_PowerAroundThreshold_ShouldFollowThresholdRule(
|
||||||
|
string scenario,
|
||||||
|
double powerWatts,
|
||||||
|
bool expectedBelowThreshold)
|
||||||
|
{
|
||||||
|
var sut = CreateSutWithHeatingObserved();
|
||||||
|
|
||||||
|
var result = FeedReadings(sut, RequiredReadings, powerWatts: powerWatts);
|
||||||
|
|
||||||
|
result.Should()
|
||||||
|
.Be(
|
||||||
|
expectedBelowThreshold,
|
||||||
|
$"{scenario}: readings below {Threshold}W are counted as 'not heating'");
|
||||||
|
}
|
||||||
|
|
||||||
[Theory]
|
[Theory]
|
||||||
[InlineData(9.9, 10.0, true)]
|
[InlineData(9.9, 10.0, true)]
|
||||||
[InlineData(10.0, 10.0, false)]
|
[InlineData(10.0, 10.0, false)]
|
||||||
[InlineData(10.1, 10.0, false)]
|
[InlineData(10.1, 10.0, false)]
|
||||||
public void IsWaterReady_CustomThreshold_ShouldUseProvidedValue(double powerWatts, double threshold, bool expected)
|
[InlineData(0.0, 0.0, false)]
|
||||||
|
[InlineData(-10.0, -5.0, true)]
|
||||||
|
[InlineData(-0.001, 0.0, true)]
|
||||||
|
[InlineData(0.0, -5.0, false)]
|
||||||
|
[InlineData(10.0, 0.0, false)]
|
||||||
|
public void IsWaterReady_CustomThreshold_ShouldUseProvidedValue(
|
||||||
|
double powerWatts,
|
||||||
|
double heatingThresholdWatts,
|
||||||
|
bool expected)
|
||||||
{
|
{
|
||||||
var sut = CreateSutWithHeatingObserved();
|
var sut = CreateSutWithHeatingObserved();
|
||||||
|
|
||||||
var result = false;
|
var result = FeedReadings(sut, RequiredReadings, powerWatts: powerWatts,
|
||||||
for (var i = 0; i < BoilerMonitorConsts.ConsecutiveReadingsRequired; i++)
|
heatingThresholdWatts: heatingThresholdWatts);
|
||||||
{
|
|
||||||
result = sut.IsWaterReady("on", powerWatts, threshold);
|
|
||||||
}
|
|
||||||
|
|
||||||
result.Should().Be(expected);
|
result.Should().Be(expected);
|
||||||
}
|
}
|
||||||
@@ -261,60 +304,41 @@ public class WaterReadyServiceTests
|
|||||||
|
|
||||||
#region Cooldown period
|
#region Cooldown period
|
||||||
|
|
||||||
[Fact]
|
[Theory]
|
||||||
public void IsWaterReady_DuringCooldown_ShouldReturnTrueRegardlessOfSwitchState()
|
[InlineData("off", 0.0)]
|
||||||
|
[InlineData("off", null)]
|
||||||
|
[InlineData(null, 0.0)]
|
||||||
|
[InlineData(null, null)]
|
||||||
|
[InlineData("on", HighPowerWatts)]
|
||||||
|
[InlineData("unknown", 12.0)]
|
||||||
|
public void IsWaterReady_DuringCooldown_ShouldReturnTrueRegardlessOfInputs(string? switchState, double? powerWatts)
|
||||||
{
|
{
|
||||||
var sut = CreateSutWithHeatingObserved();
|
var sut = CreateSutWithHeatingObserved();
|
||||||
TriggerWaterReady(sut);
|
FeedReadings(sut, RequiredReadings).Should().BeTrue();
|
||||||
|
|
||||||
var result = sut.IsWaterReady("off", 0.0, Threshold);
|
var result = sut.IsWaterReady(switchState, powerWatts, Threshold);
|
||||||
|
|
||||||
result.Should().BeTrue();
|
result.Should().BeTrue();
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Theory]
|
||||||
public void IsWaterReady_DuringCooldown_ShouldReturnTrueEvenWithNullState()
|
[MemberData(nameof(BoilerMonitorTestData.GeneratedElapsedTimes), MemberType = typeof(BoilerMonitorTestData))]
|
||||||
|
public void IsWaterReady_CooldownDoesNotExpireByTime_ShouldStayActive(TimeSpan elapsed)
|
||||||
{
|
{
|
||||||
var sut = CreateSutWithHeatingObserved();
|
var sut = CreateSutWithHeatingObserved();
|
||||||
TriggerWaterReady(sut);
|
FeedReadings(sut, RequiredReadings);
|
||||||
|
var triggeredAt = sut.WaterReadySince;
|
||||||
|
|
||||||
var result = sut.IsWaterReady(null, null, Threshold);
|
_timeProvider.Advance(elapsed);
|
||||||
|
|
||||||
result.Should().BeTrue();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void IsWaterReady_CooldownDoesNotExpireByTime_ShouldStayActiveAfterHours()
|
|
||||||
{
|
|
||||||
var sut = CreateSutWithHeatingObserved();
|
|
||||||
TriggerWaterReady(sut);
|
|
||||||
_timeProvider.Advance(TimeSpan.FromHours(12));
|
|
||||||
|
|
||||||
var result = sut.IsWaterReady("off", 0.0, Threshold);
|
|
||||||
|
|
||||||
result.Should().BeTrue("cooldown only clears via explicit ResetCooldown, not by elapsed time");
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void IsWaterReady_CooldownClearedOnlyByExplicitReset_ShouldResumeAfterReset()
|
|
||||||
{
|
|
||||||
var sut = CreateSutWithHeatingObserved();
|
|
||||||
TriggerWaterReady(sut);
|
|
||||||
_timeProvider.Advance(TimeSpan.FromHours(5));
|
|
||||||
sut.IsInCooldown.Should().BeTrue();
|
sut.IsInCooldown.Should().BeTrue();
|
||||||
|
|
||||||
sut.ResetCooldown();
|
sut.IsWaterReady("off", 0.0, Threshold)
|
||||||
|
.Should()
|
||||||
|
.BeTrue(
|
||||||
|
"cooldown only clears via explicit ResetCooldown, not by elapsed time");
|
||||||
|
|
||||||
sut.IsWaterReady("off", 0.0, Threshold).Should().BeFalse();
|
sut.WaterReadySince.Should().Be(triggeredAt);
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void IsInCooldown_WhenCooldownActive_ShouldReturnTrue()
|
|
||||||
{
|
|
||||||
var sut = CreateSutWithHeatingObserved();
|
|
||||||
TriggerWaterReady(sut);
|
|
||||||
|
|
||||||
sut.IsInCooldown.Should().BeTrue();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -326,67 +350,65 @@ public class WaterReadyServiceTests
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void IsInCooldown_DoesNotExpireByTime_ShouldRemainTrueAfterHours()
|
public void ResetCooldown_ShouldClearActiveCooldownAndAllowDetectionToResume()
|
||||||
{
|
{
|
||||||
var sut = CreateSutWithHeatingObserved();
|
var sut = CreateSutWithHeatingObserved();
|
||||||
TriggerWaterReady(sut);
|
FeedReadings(sut, RequiredReadings);
|
||||||
_timeProvider.Advance(TimeSpan.FromHours(8));
|
|
||||||
|
|
||||||
sut.IsInCooldown.Should().BeTrue();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void ResetCooldown_ShouldClearActiveCooldown()
|
|
||||||
{
|
|
||||||
var sut = CreateSutWithHeatingObserved();
|
|
||||||
TriggerWaterReady(sut);
|
|
||||||
sut.IsInCooldown.Should().BeTrue();
|
sut.IsInCooldown.Should().BeTrue();
|
||||||
|
|
||||||
sut.ResetCooldown();
|
sut.ResetCooldown();
|
||||||
|
|
||||||
sut.IsInCooldown.Should().BeFalse();
|
sut.IsInCooldown.Should().BeFalse();
|
||||||
|
sut.WaterReadySince.Should().BeNull();
|
||||||
|
sut.IsWaterReady("off", 0.0, Threshold).Should().BeFalse();
|
||||||
|
FeedReadings(sut, RequiredReadings - 1).Should().BeFalse();
|
||||||
|
FeedReadings(sut, 1).Should().BeTrue();
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void ResetCooldown_ShouldAllowNormalDetectionToResume()
|
public void ResetCooldown_WhenNoCooldownIsActive_ShouldBeANoOp()
|
||||||
{
|
{
|
||||||
var sut = CreateSutWithHeatingObserved();
|
var sut = CreateSut();
|
||||||
TriggerWaterReady(sut);
|
|
||||||
sut.ResetCooldown();
|
sut.ResetCooldown();
|
||||||
|
|
||||||
var result = sut.IsWaterReady("off", 0.0, Threshold);
|
sut.IsInCooldown.Should().BeFalse();
|
||||||
|
sut.WaterReadySince.Should().BeNull();
|
||||||
result.Should().BeFalse();
|
FeedReadings(sut, 10).Should().BeFalse("heating was never observed");
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void IsWaterReady_CooldownOnlySetOnFirstDetection_ShouldNotResetTimestamp()
|
public void IsWaterReady_CooldownOnlySetOnFirstDetection_ShouldNotResetTimestamp()
|
||||||
{
|
{
|
||||||
var sut = CreateSutWithHeatingObserved();
|
var sut = CreateSutWithHeatingObserved();
|
||||||
TriggerWaterReady(sut);
|
FeedReadings(sut, RequiredReadings);
|
||||||
var originalTimestamp = sut.WaterReadySince;
|
var originalTimestamp = sut.WaterReadySince;
|
||||||
|
|
||||||
_timeProvider.Advance(TimeSpan.FromHours(2));
|
_timeProvider.Advance(TimeSpan.FromHours(2));
|
||||||
sut.IsWaterReady("on", 0.0, Threshold);
|
sut.IsWaterReady("on", 0.0, Threshold).Should().BeTrue();
|
||||||
|
|
||||||
sut.WaterReadySince.Should().Be(originalTimestamp);
|
sut.WaterReadySince.Should().Be(originalTimestamp);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Theory]
|
||||||
public void IsWaterReady_HighPowerDoesNotTriggerCooldown_ShouldReturnFalse()
|
[InlineData(Threshold)]
|
||||||
|
[InlineData(HighPowerWatts)]
|
||||||
|
[InlineData(double.MaxValue)]
|
||||||
|
public void IsWaterReady_PowerAtOrAboveThreshold_ShouldNotStartCooldown(double powerWatts)
|
||||||
{
|
{
|
||||||
var sut = CreateSutWithHeatingObserved();
|
var sut = CreateSutWithHeatingObserved();
|
||||||
|
|
||||||
sut.IsWaterReady("on", HighPowerWatts, Threshold);
|
FeedReadings(sut, RequiredReadings, powerWatts: powerWatts).Should().BeFalse();
|
||||||
|
|
||||||
sut.IsInCooldown.Should().BeFalse();
|
sut.IsInCooldown.Should().BeFalse();
|
||||||
|
sut.WaterReadySince.Should().BeNull();
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void NotifyTurnedOn_DuringActiveCooldown_ShouldNotClearCooldown()
|
public void NotifyTurnedOn_DuringActiveCooldown_ShouldNotClearCooldown()
|
||||||
{
|
{
|
||||||
var sut = CreateSutWithHeatingObserved();
|
var sut = CreateSutWithHeatingObserved();
|
||||||
TriggerWaterReady(sut);
|
FeedReadings(sut, RequiredReadings);
|
||||||
|
|
||||||
sut.NotifyTurnedOn();
|
sut.NotifyTurnedOn();
|
||||||
|
|
||||||
@@ -397,60 +419,22 @@ public class WaterReadyServiceTests
|
|||||||
|
|
||||||
#region Cooldown persistence
|
#region Cooldown persistence
|
||||||
|
|
||||||
[Fact]
|
[Theory]
|
||||||
public void RestoreCooldownState_ShouldResumeActiveCooldown()
|
[MemberData(nameof(BoilerMonitorTestData.CooldownRestoreSamples), MemberType = typeof(BoilerMonitorTestData))]
|
||||||
|
public void RestoreCooldownState_ShouldRestoreOnlyTimestampsFromTodayUtc(
|
||||||
|
string scenario,
|
||||||
|
DateTimeOffset now,
|
||||||
|
DateTimeOffset cooldownSince,
|
||||||
|
bool expectedRestored)
|
||||||
{
|
{
|
||||||
var sut = CreateSut();
|
var timeProvider = BoilerMonitorTestData.CreateTimeProvider(now);
|
||||||
var cooldownStart = _timeProvider.GetUtcNow() - TimeSpan.FromMinutes(30);
|
var sut = new WaterReadyService(_loggerMock.Object, timeProvider);
|
||||||
|
|
||||||
sut.RestoreCooldownState(cooldownStart);
|
sut.RestoreCooldownState(cooldownSince);
|
||||||
|
|
||||||
sut.IsInCooldown.Should().BeTrue();
|
sut.IsInCooldown.Should().Be(expectedRestored, scenario);
|
||||||
sut.IsWaterReady("off", 0.0, Threshold).Should().BeTrue();
|
sut.WaterReadySince.Should().Be(expectedRestored ? cooldownSince : null, scenario);
|
||||||
}
|
sut.IsWaterReady("off", 0.0, Threshold).Should().Be(expectedRestored, scenario);
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void RestoreCooldownState_WithYesterdayTimestamp_ShouldNotActivateCooldown()
|
|
||||||
{
|
|
||||||
var sut = CreateSut();
|
|
||||||
var yesterday = _timeProvider.GetUtcNow().AddDays(-1);
|
|
||||||
|
|
||||||
sut.RestoreCooldownState(yesterday);
|
|
||||||
|
|
||||||
sut.IsInCooldown.Should().BeFalse();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void RestoreCooldownState_WithTodayTimestamp_ShouldRestoreCooldown()
|
|
||||||
{
|
|
||||||
var sut = CreateSut();
|
|
||||||
var earlierToday = _timeProvider.GetUtcNow() - TimeSpan.FromHours(5);
|
|
||||||
|
|
||||||
sut.RestoreCooldownState(earlierToday);
|
|
||||||
|
|
||||||
sut.IsInCooldown.Should().BeTrue();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void RestoreCooldownState_WithExactlyMidnightTimestamp_ShouldRestoreCooldown()
|
|
||||||
{
|
|
||||||
var sut = CreateSut();
|
|
||||||
var todayMidnight = new DateTimeOffset(_timeProvider.GetUtcNow().Date, TimeSpan.Zero);
|
|
||||||
|
|
||||||
sut.RestoreCooldownState(todayMidnight);
|
|
||||||
|
|
||||||
sut.IsInCooldown.Should().BeTrue("timestamp at today's midnight is not before today");
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact]
|
|
||||||
public void RestoreCooldownState_ShouldPreserveOriginalTimestamp()
|
|
||||||
{
|
|
||||||
var sut = CreateSut();
|
|
||||||
var cooldownStart = _timeProvider.GetUtcNow() - TimeSpan.FromMinutes(30);
|
|
||||||
|
|
||||||
sut.RestoreCooldownState(cooldownStart);
|
|
||||||
|
|
||||||
sut.WaterReadySince.Should().Be(cooldownStart);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
@@ -459,7 +443,7 @@ public class WaterReadyServiceTests
|
|||||||
var sut = CreateSutWithHeatingObserved();
|
var sut = CreateSutWithHeatingObserved();
|
||||||
var beforeTrigger = _timeProvider.GetUtcNow();
|
var beforeTrigger = _timeProvider.GetUtcNow();
|
||||||
|
|
||||||
TriggerWaterReady(sut);
|
FeedReadings(sut, RequiredReadings).Should().BeTrue();
|
||||||
|
|
||||||
sut.WaterReadySince.Should().Be(beforeTrigger);
|
sut.WaterReadySince.Should().Be(beforeTrigger);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
using System.Globalization;
|
using System.Globalization;
|
||||||
using BoilerMonitor.Models;
|
using BoilerMonitor.Models;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
@@ -5,6 +7,8 @@ using NetDaemon.HassModel;
|
|||||||
using static BoilerMonitor.Models.BoilerMonitorConsts;
|
using static BoilerMonitor.Models.BoilerMonitorConsts;
|
||||||
using static NordPool.Models.NordPoolConsts;
|
using static NordPool.Models.NordPoolConsts;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace BoilerMonitorManager;
|
namespace BoilerMonitorManager;
|
||||||
|
|
||||||
public sealed class BoilerConfigReader(IHaContext haContext, ILogger<BoilerConfigReader> logger) : IBoilerConfigReader
|
public sealed class BoilerConfigReader(IHaContext haContext, ILogger<BoilerConfigReader> logger) : IBoilerConfigReader
|
||||||
@@ -14,20 +18,30 @@ public sealed class BoilerConfigReader(IHaContext haContext, ILogger<BoilerConfi
|
|||||||
public BoilerConfig ReadConfig()
|
public BoilerConfig ReadConfig()
|
||||||
{
|
{
|
||||||
var dailyHoursState = haContext.GetState(BoilerDailyHoursEntityId)?.State;
|
var dailyHoursState = haContext.GetState(BoilerDailyHoursEntityId)?.State;
|
||||||
var dailyHours = double.TryParse(dailyHoursState, NumberStyles.Any, CultureInfo.InvariantCulture, out var dh) ? dh : DefaultDailyHours;
|
|
||||||
|
var dailyHours = double.TryParse(dailyHoursState, NumberStyles.Any, CultureInfo.InvariantCulture, out var dh)
|
||||||
|
? dh
|
||||||
|
: DefaultDailyHours;
|
||||||
|
|
||||||
var intervalCount = (int)(dailyHours * IntervalsPerHour);
|
var intervalCount = (int)(dailyHours * IntervalsPerHour);
|
||||||
|
|
||||||
if (intervalCount <= 0)
|
if (intervalCount <= 0)
|
||||||
{
|
{
|
||||||
intervalCount = IntervalsPerHour;
|
intervalCount = IntervalsPerHour;
|
||||||
}
|
}
|
||||||
|
|
||||||
var priceCapState = haContext.GetState(BoilerPriceCapEntityId)?.State;
|
var priceCapState = haContext.GetState(BoilerPriceCapEntityId)?.State;
|
||||||
var priceCap = double.TryParse(priceCapState, NumberStyles.Any, CultureInfo.InvariantCulture, out var pc) && pc > 0 ? pc : double.MaxValue;
|
|
||||||
|
var priceCap =
|
||||||
|
double.TryParse(priceCapState, NumberStyles.Any, CultureInfo.InvariantCulture, out var pc) && pc > 0
|
||||||
|
? pc
|
||||||
|
: double.MaxValue;
|
||||||
|
|
||||||
var deadline = DateTime.Today.AddDays(1);
|
var deadline = DateTime.Today.AddDays(1);
|
||||||
var readyByState = haContext.GetState(BoilerReadyByEntityId)?.State;
|
var readyByState = haContext.GetState(BoilerReadyByEntityId)?.State;
|
||||||
if (!string.IsNullOrEmpty(readyByState) && TimeSpan.TryParse(readyByState, out var readyByTime))
|
|
||||||
|
if (!string.IsNullOrEmpty(readyByState) &&
|
||||||
|
TimeSpan.TryParse(readyByState, CultureInfo.InvariantCulture, out var readyByTime))
|
||||||
{
|
{
|
||||||
deadline = DateTime.Today.Add(readyByTime);
|
deadline = DateTime.Today.Add(readyByTime);
|
||||||
}
|
}
|
||||||
@@ -35,15 +49,21 @@ public sealed class BoilerConfigReader(IHaContext haContext, ILogger<BoilerConfi
|
|||||||
var skipPriceCapState = haContext.GetState(SkipPriceCapEntityId)?.State;
|
var skipPriceCapState = haContext.GetState(SkipPriceCapEntityId)?.State;
|
||||||
var skipPriceCap = string.Equals(skipPriceCapState, SwitchOnState, StringComparison.OrdinalIgnoreCase);
|
var skipPriceCap = string.Equals(skipPriceCapState, SwitchOnState, StringComparison.OrdinalIgnoreCase);
|
||||||
|
|
||||||
logger.LogDebug("Boiler config: intervals={Intervals}, priceCap={Cap}, skipPriceCap={Skip}, deadline={Deadline}",
|
if (logger.IsEnabled(LogLevel.Debug))
|
||||||
|
{
|
||||||
|
logger.LogDebug(
|
||||||
|
"Boiler config: intervals={Intervals}, priceCap={Cap}, skipPriceCap={Skip}, deadline={Deadline}",
|
||||||
intervalCount, priceCap, skipPriceCap, deadline);
|
intervalCount, priceCap, skipPriceCap, deadline);
|
||||||
|
}
|
||||||
|
|
||||||
return new BoilerConfig
|
var config = new BoilerConfig
|
||||||
{
|
{
|
||||||
IntervalCount = intervalCount,
|
IntervalCount = intervalCount,
|
||||||
PriceCap = priceCap,
|
PriceCap = priceCap,
|
||||||
Deadline = deadline,
|
Deadline = deadline,
|
||||||
SkipPriceCap = skipPriceCap
|
SkipPriceCap = skipPriceCap
|
||||||
};
|
};
|
||||||
|
|
||||||
|
return config;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,7 +1,11 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
using BoilerMonitor.Models.Enums;
|
using BoilerMonitor.Models.Enums;
|
||||||
using BoilerMonitorManager.Interface;
|
using BoilerMonitorManager.Interface;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace BoilerMonitorManager;
|
namespace BoilerMonitorManager;
|
||||||
|
|
||||||
public sealed class BoilerControlService(ILogger<BoilerControlService> logger) : IBoilerControlService
|
public sealed class BoilerControlService(ILogger<BoilerControlService> logger) : IBoilerControlService
|
||||||
@@ -19,46 +23,52 @@ public sealed class BoilerControlService(ILogger<BoilerControlService> logger) :
|
|||||||
var effectiveBudgetExhausted = budgetExhausted && !budgetOverride;
|
var effectiveBudgetExhausted = budgetExhausted && !budgetOverride;
|
||||||
var shouldBeOn = isNowCheap && !waterReady && !effectiveBudgetExhausted;
|
var shouldBeOn = isNowCheap && !waterReady && !effectiveBudgetExhausted;
|
||||||
|
|
||||||
if (shouldBeOn && !isCurrentlyOn)
|
switch (shouldBeOn, isCurrentlyOn)
|
||||||
|
{
|
||||||
|
case (true, false):
|
||||||
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
{
|
{
|
||||||
logger.LogInformation(
|
logger.LogInformation(
|
||||||
"Boiler should turn ON — cheap interval active, water not ready, budget available (current state: {State})",
|
"Boiler should turn ON — cheap interval active, water not ready, budget available (current state: {State})",
|
||||||
currentSwitchState);
|
currentSwitchState);
|
||||||
|
|
||||||
return BoilerAction.TurnOn;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!shouldBeOn && isCurrentlyOn)
|
return BoilerAction.TurnOn;
|
||||||
{
|
|
||||||
var reason = GetTurnOffReason(waterReady, isNowCheap, effectiveBudgetExhausted);
|
|
||||||
|
|
||||||
logger.LogInformation("Boiler should turn OFF — {Reason} (current state: {State})", reason, currentSwitchState);
|
case (false, true):
|
||||||
|
{
|
||||||
|
var reason = GetTurnOffReason(waterReady, effectiveBudgetExhausted);
|
||||||
|
|
||||||
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
|
{
|
||||||
|
logger.LogInformation("Boiler should turn OFF — {Reason} (current state: {State})", reason,
|
||||||
|
currentSwitchState);
|
||||||
|
}
|
||||||
|
|
||||||
return BoilerAction.TurnOff;
|
return BoilerAction.TurnOff;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
default:
|
||||||
|
if (logger.IsEnabled(LogLevel.Debug))
|
||||||
|
{
|
||||||
logger.LogDebug(
|
logger.LogDebug(
|
||||||
"Boiler state unchanged: {State} (cheap={Cheap}, waterReady={WaterReady}, budgetExhausted={BudgetExhausted})",
|
"Boiler state unchanged: {State} (cheap={Cheap}, waterReady={WaterReady}, budgetExhausted={BudgetExhausted})",
|
||||||
currentSwitchState,
|
currentSwitchState, isNowCheap, waterReady, effectiveBudgetExhausted);
|
||||||
isNowCheap,
|
}
|
||||||
waterReady,
|
|
||||||
effectiveBudgetExhausted);
|
|
||||||
|
|
||||||
return BoilerAction.NoChange;
|
return BoilerAction.NoChange;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private static string GetTurnOffReason(bool waterReady, bool isNowCheap, bool effectiveBudgetExhausted)
|
private static string GetTurnOffReason(bool waterReady, bool effectiveBudgetExhausted)
|
||||||
{
|
{
|
||||||
if (waterReady)
|
if (waterReady)
|
||||||
{
|
{
|
||||||
return "water is already ready";
|
return "water is already ready";
|
||||||
}
|
}
|
||||||
|
|
||||||
if (effectiveBudgetExhausted)
|
return effectiveBudgetExhausted
|
||||||
{
|
? "daily budget is exhausted"
|
||||||
return "daily budget is exhausted";
|
: "not in a cheap interval";
|
||||||
}
|
|
||||||
|
|
||||||
return "not in a cheap interval";
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -20,9 +20,9 @@
|
|||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.5" />
|
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="11.0.0"/>
|
||||||
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.11.0" />
|
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.43.1"/>
|
||||||
<PackageReference Include="NetDaemon.HassModel" Version="26.11.0" />
|
<PackageReference Include="NetDaemon.HassModel" Version="26.43.1"/>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
using System.Globalization;
|
using System.Globalization;
|
||||||
|
using System.Text.Json;
|
||||||
using BoilerMonitor.Models;
|
using BoilerMonitor.Models;
|
||||||
using BoilerMonitorManager.Interface;
|
using BoilerMonitorManager.Interface;
|
||||||
using BoilerMonitorManager.Models;
|
using BoilerMonitorManager.Models;
|
||||||
@@ -8,6 +11,8 @@ using NetDaemon.Extensions.MqttEntityManager;
|
|||||||
using NetDaemon.HassModel;
|
using NetDaemon.HassModel;
|
||||||
using static BoilerMonitor.Models.BoilerMonitorConsts;
|
using static BoilerMonitor.Models.BoilerMonitorConsts;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace BoilerMonitorManager;
|
namespace BoilerMonitorManager;
|
||||||
|
|
||||||
public sealed class BoilerMonitorEntityService(
|
public sealed class BoilerMonitorEntityService(
|
||||||
@@ -33,14 +38,6 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
AutoManagementEntityId
|
AutoManagementEntityId
|
||||||
];
|
];
|
||||||
|
|
||||||
private static object CreateDeviceBlock() => new
|
|
||||||
{
|
|
||||||
identifiers = new[] { DeviceIdentifier },
|
|
||||||
name = DeviceName,
|
|
||||||
model = DeviceName,
|
|
||||||
manufacturer = DeviceManufacturer
|
|
||||||
};
|
|
||||||
|
|
||||||
public async Task CreateEntitiesAsync(CancellationToken cancellationToken = default)
|
public async Task CreateEntitiesAsync(CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
cancellationToken.ThrowIfCancellationRequested();
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
@@ -50,8 +47,12 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
var createTasks = entities.Select(async entity =>
|
var createTasks = entities.Select(async entity =>
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
|
{
|
||||||
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
{
|
{
|
||||||
logger.LogInformation("Creating/re-registering MQTT entity: {EntityId}", entity.EntityId);
|
logger.LogInformation("Creating/re-registering MQTT entity: {EntityId}", entity.EntityId);
|
||||||
|
}
|
||||||
|
|
||||||
await entityManager.CreateEntityAsync(entity).ConfigureAwait(false);
|
await entityManager.CreateEntityAsync(entity).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
@@ -80,7 +81,8 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
ResetSessionCountAsync(),
|
ResetSessionCountAsync(),
|
||||||
ResetBudgetOverrideAsync(),
|
ResetBudgetOverrideAsync(),
|
||||||
ResetAutoManagementAsync()
|
ResetAutoManagementAsync()
|
||||||
).ConfigureAwait(false);
|
)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
|
||||||
logger.LogInformation("All BoilerMonitor runtime entity states reset to defaults");
|
logger.LogInformation("All BoilerMonitor runtime entity states reset to defaults");
|
||||||
}
|
}
|
||||||
@@ -93,9 +95,6 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
var formattedRunTime = FormatTimeSpan(ctx.TodayRunTime);
|
var formattedRunTime = FormatTimeSpan(ctx.TodayRunTime);
|
||||||
var formattedRemaining = FormatTimeSpan(ctx.RemainingTime);
|
var formattedRemaining = FormatTimeSpan(ctx.RemainingTime);
|
||||||
|
|
||||||
// logger.LogInformation("Updating BoilerMonitor entities: runtime={RunTime}, remaining={Remaining}, budget={Budget}%, sessions={Sessions}",
|
|
||||||
// formattedRunTime, formattedRemaining, ctx.BudgetPercentage, ctx.SessionCount);
|
|
||||||
|
|
||||||
var updateTasks = new[]
|
var updateTasks = new[]
|
||||||
{
|
{
|
||||||
UpdateStatusAsync(StatusConfigured),
|
UpdateStatusAsync(StatusConfigured),
|
||||||
@@ -116,7 +115,7 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var removeTasks = CleanableEntityIds.Select(entityId => entityManager.RemoveEntity(entityId));
|
var removeTasks = CleanableEntityIds.Select(entityManager.RemoveEntity);
|
||||||
await Task.WhenAll(removeTasks).ConfigureAwait(false);
|
await Task.WhenAll(removeTasks).ConfigureAwait(false);
|
||||||
|
|
||||||
logger.LogInformation("BoilerMonitor entities cleaned up successfully (cleanup button retained)");
|
logger.LogInformation("BoilerMonitor entities cleaned up successfully (cleanup button retained)");
|
||||||
@@ -124,6 +123,7 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
logger.LogError(ex, "Error cleaning up BoilerMonitor entities");
|
logger.LogError(ex, "Error cleaning up BoilerMonitor entities");
|
||||||
|
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -137,7 +137,8 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
await Task.WhenAll(
|
await Task.WhenAll(
|
||||||
ResetStatusAsync(),
|
ResetStatusAsync(),
|
||||||
ResetWaterReadyAsync()
|
ResetWaterReadyAsync()
|
||||||
).ConfigureAwait(false);
|
)
|
||||||
|
.ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
public PersistedBoilerState? ReadPersistedState()
|
public PersistedBoilerState? ReadPersistedState()
|
||||||
@@ -149,11 +150,16 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
var skipPriceCapState = haContext.GetState(SkipPriceCapEntityId)?.State;
|
var skipPriceCapState = haContext.GetState(SkipPriceCapEntityId)?.State;
|
||||||
var budgetOverrideState = haContext.GetState(BudgetOverrideEntityId)?.State;
|
var budgetOverrideState = haContext.GetState(BudgetOverrideEntityId)?.State;
|
||||||
|
|
||||||
if (!TryParseEntitySeconds(runtimeState, out var runtimeSeconds)
|
if (!TryParseEntitySeconds(runtimeState, out var runtimeSeconds) ||
|
||||||
|| !TryParseEntityInt(sessionCountState, out var sessionCount))
|
!TryParseEntityInt(sessionCountState, out var sessionCount))
|
||||||
{
|
{
|
||||||
logger.LogInformation("No valid persisted BoilerMonitor state found in HA entities (runtime={Runtime}, sessions={Sessions})",
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
|
{
|
||||||
|
logger.LogInformation(
|
||||||
|
"No valid persisted BoilerMonitor state found in HA entities (runtime={Runtime}, sessions={Sessions})",
|
||||||
runtimeState, sessionCountState);
|
runtimeState, sessionCountState);
|
||||||
|
}
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -165,14 +171,20 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
BudgetOverrideState = budgetOverrideState
|
BudgetOverrideState = budgetOverrideState
|
||||||
};
|
};
|
||||||
|
|
||||||
logger.LogInformation("Restored persisted BoilerMonitor state: runtime={Runtime}, sessions={Sessions}, skipPriceCap={SkipPriceCap}, budgetOverride={BudgetOverride}",
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
persisted.AccumulatedRunTime, persisted.SessionCount, persisted.SkipPriceCapState, persisted.BudgetOverrideState);
|
{
|
||||||
|
logger.LogInformation(
|
||||||
|
"Restored persisted BoilerMonitor state: runtime={Runtime}, sessions={Sessions}, skipPriceCap={SkipPriceCap}, budgetOverride={BudgetOverride}",
|
||||||
|
persisted.AccumulatedRunTime, persisted.SessionCount, persisted.SkipPriceCapState,
|
||||||
|
persisted.BudgetOverrideState);
|
||||||
|
}
|
||||||
|
|
||||||
return persisted;
|
return persisted;
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
logger.LogError(ex, "Error reading persisted BoilerMonitor state from HA entities");
|
logger.LogError(ex, "Error reading persisted BoilerMonitor state from HA entities");
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -182,25 +194,78 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
await UpdateStatusAsync(status).ConfigureAwait(false);
|
await UpdateStatusAsync(status).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public DateTimeOffset? ReadPersistedCooldownTimestamp()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var entity = haContext.GetState(WaterReadyEntityId);
|
||||||
|
|
||||||
|
if (entity?.Attributes is not IDictionary<string, object> attributes)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!attributes.TryGetValue("cooldown_since", out var value))
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var stringValue = value switch
|
||||||
|
{
|
||||||
|
string s => s,
|
||||||
|
JsonElement { ValueKind: JsonValueKind.String } jsonElement =>
|
||||||
|
jsonElement.GetString(),
|
||||||
|
_ => null
|
||||||
|
};
|
||||||
|
|
||||||
|
if (stringValue is not null &&
|
||||||
|
DateTimeOffset.TryParse(stringValue, CultureInfo.InvariantCulture,
|
||||||
|
DateTimeStyles.RoundtripKind, out var parsed))
|
||||||
|
{
|
||||||
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
|
{
|
||||||
|
logger.LogInformation("Read persisted cooldown timestamp: {CooldownSince}", parsed);
|
||||||
|
}
|
||||||
|
|
||||||
|
return parsed;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger.LogError(ex, "Error reading persisted cooldown timestamp");
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static object CreateDeviceBlock()
|
||||||
|
{
|
||||||
|
return new
|
||||||
|
{
|
||||||
|
identifiers = new[] { DeviceIdentifier },
|
||||||
|
name = DeviceName,
|
||||||
|
model = DeviceName,
|
||||||
|
manufacturer = DeviceManufacturer
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
private static bool TryParseEntitySeconds(string? state, out double seconds)
|
private static bool TryParseEntitySeconds(string? state, out double seconds)
|
||||||
{
|
{
|
||||||
seconds = 0;
|
seconds = 0;
|
||||||
return !string.IsNullOrWhiteSpace(state)
|
var tryParseEntitySeconds = !string.IsNullOrWhiteSpace(state) && state is not ("unavailable" or "unknown") && double.TryParse(state, CultureInfo.InvariantCulture, out seconds) && seconds >= 0;
|
||||||
&& state is not ("unavailable" or "unknown")
|
|
||||||
&& double.TryParse(state, CultureInfo.InvariantCulture, out seconds)
|
return tryParseEntitySeconds;
|
||||||
&& seconds >= 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static bool TryParseEntityInt(string? state, out int value)
|
private static bool TryParseEntityInt(string? state, out int value)
|
||||||
{
|
{
|
||||||
value = 0;
|
value = 0;
|
||||||
return !string.IsNullOrWhiteSpace(state)
|
var tryParseEntityInt = !string.IsNullOrWhiteSpace(state) && state is not ("unavailable" or "unknown") && int.TryParse(state, CultureInfo.InvariantCulture, out value) && value >= 0;
|
||||||
&& state is not ("unavailable" or "unknown")
|
|
||||||
&& int.TryParse(state, CultureInfo.InvariantCulture, out value)
|
return tryParseEntityInt;
|
||||||
&& value >= 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private ICollection<BoilerMonitorEntity> GetAllEntities()
|
private static ICollection<BoilerMonitorEntity> GetAllEntities()
|
||||||
{
|
{
|
||||||
var device = CreateDeviceBlock();
|
var device = CreateDeviceBlock();
|
||||||
|
|
||||||
@@ -226,7 +291,8 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
device
|
device
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
new BoilerMonitorEntity("number", "boilermonitor_config_heating_threshold", "Heating power threshold (watts)")
|
new BoilerMonitorEntity("number", "boilermonitor_config_heating_threshold",
|
||||||
|
"Heating power threshold (watts)")
|
||||||
{
|
{
|
||||||
AdditionalConfig = new
|
AdditionalConfig = new
|
||||||
{
|
{
|
||||||
@@ -256,11 +322,13 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
},
|
},
|
||||||
new BoilerMonitorEntity("sensor", "boilermonitor_today_runtime", "Today runtime")
|
new BoilerMonitorEntity("sensor", "boilermonitor_today_runtime", "Today runtime")
|
||||||
{
|
{
|
||||||
AdditionalConfig = new { unit_of_measurement = "s", icon = "mdi:timer", device_class = "duration", device }
|
AdditionalConfig = new
|
||||||
|
{ unit_of_measurement = "s", icon = "mdi:timer", device_class = "duration", device }
|
||||||
},
|
},
|
||||||
new BoilerMonitorEntity("sensor", "boilermonitor_remaining_time", "Remaining budget time")
|
new BoilerMonitorEntity("sensor", "boilermonitor_remaining_time", "Remaining budget time")
|
||||||
{
|
{
|
||||||
AdditionalConfig = new { unit_of_measurement = "s", icon = "mdi:timer-sand", device_class = "duration", device }
|
AdditionalConfig = new
|
||||||
|
{ unit_of_measurement = "s", icon = "mdi:timer-sand", device_class = "duration", device }
|
||||||
},
|
},
|
||||||
new BoilerMonitorEntity("sensor", "boilermonitor_budget_percentage", "Budget usage")
|
new BoilerMonitorEntity("sensor", "boilermonitor_budget_percentage", "Budget usage")
|
||||||
{
|
{
|
||||||
@@ -303,6 +371,7 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
private async Task ResetWaterReadyAsync()
|
private async Task ResetWaterReadyAsync()
|
||||||
{
|
{
|
||||||
await SetEntityStateSafe(WaterReadyEntityId, "unknown").ConfigureAwait(false);
|
await SetEntityStateSafe(WaterReadyEntityId, "unknown").ConfigureAwait(false);
|
||||||
|
|
||||||
await SetEntityAttributesSafe(WaterReadyEntityId, new
|
await SetEntityAttributesSafe(WaterReadyEntityId, new
|
||||||
{
|
{
|
||||||
boiler_switch_state = "unknown",
|
boiler_switch_state = "unknown",
|
||||||
@@ -310,7 +379,8 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
power_threshold_watts = DefaultHeatingPowerThresholdWatts,
|
power_threshold_watts = DefaultHeatingPowerThresholdWatts,
|
||||||
friendly_name = "Boiler water ready",
|
friendly_name = "Boiler water ready",
|
||||||
last_updated = (string?)null
|
last_updated = (string?)null
|
||||||
}).ConfigureAwait(false);
|
})
|
||||||
|
.ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task ResetSkipPriceCapAsync()
|
private async Task ResetSkipPriceCapAsync()
|
||||||
@@ -321,35 +391,41 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
private async Task ResetTodayRuntimeAsync()
|
private async Task ResetTodayRuntimeAsync()
|
||||||
{
|
{
|
||||||
await SetEntityStateSafe(TodayRuntimeEntityId, "0").ConfigureAwait(false);
|
await SetEntityStateSafe(TodayRuntimeEntityId, "0").ConfigureAwait(false);
|
||||||
|
|
||||||
await SetEntityAttributesSafe(TodayRuntimeEntityId, new
|
await SetEntityAttributesSafe(TodayRuntimeEntityId, new
|
||||||
{
|
{
|
||||||
formatted = "0h 0m",
|
formatted = "0h 0m",
|
||||||
friendly_name = "Today runtime",
|
friendly_name = "Today runtime",
|
||||||
last_updated = (string?)null
|
last_updated = (string?)null
|
||||||
}).ConfigureAwait(false);
|
})
|
||||||
|
.ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task ResetRemainingTimeAsync()
|
private async Task ResetRemainingTimeAsync()
|
||||||
{
|
{
|
||||||
await SetEntityStateSafe(RemainingTimeEntityId, "0").ConfigureAwait(false);
|
await SetEntityStateSafe(RemainingTimeEntityId, "0").ConfigureAwait(false);
|
||||||
|
|
||||||
await SetEntityAttributesSafe(RemainingTimeEntityId, new
|
await SetEntityAttributesSafe(RemainingTimeEntityId, new
|
||||||
{
|
{
|
||||||
formatted = "0h 0m",
|
formatted = "0h 0m",
|
||||||
budget_hours = 0.0,
|
budget_hours = 0.0,
|
||||||
friendly_name = "Remaining budget time",
|
friendly_name = "Remaining budget time",
|
||||||
last_updated = (string?)null
|
last_updated = (string?)null
|
||||||
}).ConfigureAwait(false);
|
})
|
||||||
|
.ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task ResetBudgetPercentageAsync()
|
private async Task ResetBudgetPercentageAsync()
|
||||||
{
|
{
|
||||||
await SetEntityStateSafe(BudgetPercentageEntityId, "0").ConfigureAwait(false);
|
await SetEntityStateSafe(BudgetPercentageEntityId, "0").ConfigureAwait(false);
|
||||||
|
|
||||||
await SetEntityAttributesSafe(BudgetPercentageEntityId, new
|
await SetEntityAttributesSafe(BudgetPercentageEntityId, new
|
||||||
{
|
{
|
||||||
unit_of_measurement = "%",
|
unit_of_measurement = "%",
|
||||||
friendly_name = "Budget usage",
|
friendly_name = "Budget usage",
|
||||||
last_updated = (string?)null
|
last_updated = (string?)null
|
||||||
}).ConfigureAwait(false);
|
})
|
||||||
|
.ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task ResetBudgetExhaustedAsync()
|
private async Task ResetBudgetExhaustedAsync()
|
||||||
@@ -360,11 +436,13 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
private async Task ResetSessionCountAsync()
|
private async Task ResetSessionCountAsync()
|
||||||
{
|
{
|
||||||
await SetEntityStateSafe(SessionCountEntityId, "0").ConfigureAwait(false);
|
await SetEntityStateSafe(SessionCountEntityId, "0").ConfigureAwait(false);
|
||||||
|
|
||||||
await SetEntityAttributesSafe(SessionCountEntityId, new
|
await SetEntityAttributesSafe(SessionCountEntityId, new
|
||||||
{
|
{
|
||||||
friendly_name = "Heating sessions today",
|
friendly_name = "Heating sessions today",
|
||||||
last_updated = (string?)null
|
last_updated = (string?)null
|
||||||
}).ConfigureAwait(false);
|
})
|
||||||
|
.ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task ResetBudgetOverrideAsync()
|
private async Task ResetBudgetOverrideAsync()
|
||||||
@@ -380,50 +458,68 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
private async Task UpdateWaterReadyAsync(BoilerMonitorUpdateContext ctx, string timestamp)
|
private async Task UpdateWaterReadyAsync(BoilerMonitorUpdateContext ctx, string timestamp)
|
||||||
{
|
{
|
||||||
await SetEntityStateSafe(WaterReadyEntityId, ctx.WaterReady ? "yes" : "no").ConfigureAwait(false);
|
await SetEntityStateSafe(WaterReadyEntityId, ctx.WaterReady ? "yes" : "no").ConfigureAwait(false);
|
||||||
|
|
||||||
await SetEntityAttributesSafe(WaterReadyEntityId, new
|
await SetEntityAttributesSafe(WaterReadyEntityId, new
|
||||||
{
|
{
|
||||||
boiler_switch_state = ctx.BoilerSwitchState ?? "unknown",
|
boiler_switch_state = ctx.BoilerSwitchState ?? "unknown",
|
||||||
boiler_power_watts = ctx.BoilerPowerWatts,
|
boiler_power_watts = ctx.BoilerPowerWatts,
|
||||||
cooldown_since = ctx.CooldownSince?.ToString("O"),
|
cooldown_since = ctx.CooldownSince?.ToString("O", CultureInfo.InvariantCulture),
|
||||||
friendly_name = "Boiler water ready",
|
friendly_name = "Boiler water ready",
|
||||||
last_updated = timestamp
|
last_updated = timestamp
|
||||||
}).ConfigureAwait(false);
|
})
|
||||||
|
.ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task UpdateTodayRuntimeAsync(TimeSpan runTime, string formatted, string timestamp)
|
private async Task UpdateTodayRuntimeAsync(TimeSpan runTime, string formatted, string timestamp)
|
||||||
{
|
{
|
||||||
await SetEntityStateSafe(TodayRuntimeEntityId, ((int)runTime.TotalSeconds).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
|
await SetEntityStateSafe(TodayRuntimeEntityId,
|
||||||
|
((int)runTime.TotalSeconds).ToString(CultureInfo.InvariantCulture))
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
|
||||||
await SetEntityAttributesSafe(TodayRuntimeEntityId, new
|
await SetEntityAttributesSafe(TodayRuntimeEntityId, new
|
||||||
{
|
{
|
||||||
formatted,
|
formatted,
|
||||||
friendly_name = "Today runtime",
|
friendly_name = "Today runtime",
|
||||||
last_updated = timestamp
|
last_updated = timestamp
|
||||||
}).ConfigureAwait(false);
|
})
|
||||||
|
.ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task UpdateRemainingTimeAsync(TimeSpan remaining, string formatted, double budgetHours, string timestamp)
|
private async Task UpdateRemainingTimeAsync(TimeSpan remaining,
|
||||||
|
string formatted,
|
||||||
|
double budgetHours,
|
||||||
|
string timestamp)
|
||||||
{
|
{
|
||||||
var remainingSeconds = Math.Max(0, (int)remaining.TotalSeconds);
|
var remainingSeconds = Math.Max(0, (int)remaining.TotalSeconds);
|
||||||
await SetEntityStateSafe(RemainingTimeEntityId, remainingSeconds.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
|
|
||||||
|
await SetEntityStateSafe(RemainingTimeEntityId, remainingSeconds.ToString(CultureInfo.InvariantCulture))
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
|
||||||
await SetEntityAttributesSafe(RemainingTimeEntityId, new
|
await SetEntityAttributesSafe(RemainingTimeEntityId, new
|
||||||
{
|
{
|
||||||
formatted,
|
formatted,
|
||||||
budget_hours = budgetHours,
|
budget_hours = budgetHours,
|
||||||
friendly_name = "Remaining budget time",
|
friendly_name = "Remaining budget time",
|
||||||
last_updated = timestamp
|
last_updated = timestamp
|
||||||
}).ConfigureAwait(false);
|
})
|
||||||
|
.ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task UpdateBudgetPercentageAsync(double percentage, string timestamp)
|
private async Task UpdateBudgetPercentageAsync(double percentage, string timestamp)
|
||||||
{
|
{
|
||||||
var clampedPercentage = Math.Clamp(percentage, 0, 100);
|
var clampedPercentage = Math.Clamp(percentage, 0, 100);
|
||||||
await SetEntityStateSafe(BudgetPercentageEntityId, ((int)clampedPercentage).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
|
|
||||||
|
await SetEntityStateSafe(BudgetPercentageEntityId,
|
||||||
|
((int)clampedPercentage).ToString(CultureInfo.InvariantCulture))
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
|
||||||
await SetEntityAttributesSafe(BudgetPercentageEntityId, new
|
await SetEntityAttributesSafe(BudgetPercentageEntityId, new
|
||||||
{
|
{
|
||||||
unit_of_measurement = "%",
|
unit_of_measurement = "%",
|
||||||
friendly_name = "Budget usage",
|
friendly_name = "Budget usage",
|
||||||
last_updated = timestamp
|
last_updated = timestamp
|
||||||
}).ConfigureAwait(false);
|
})
|
||||||
|
.ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task UpdateBudgetExhaustedAsync(bool exhausted)
|
private async Task UpdateBudgetExhaustedAsync(bool exhausted)
|
||||||
@@ -433,51 +529,15 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
|
|
||||||
private async Task UpdateSessionCountAsync(int sessionCount, string timestamp)
|
private async Task UpdateSessionCountAsync(int sessionCount, string timestamp)
|
||||||
{
|
{
|
||||||
await SetEntityStateSafe(SessionCountEntityId, sessionCount.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
|
await SetEntityStateSafe(SessionCountEntityId, sessionCount.ToString(CultureInfo.InvariantCulture))
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
|
||||||
await SetEntityAttributesSafe(SessionCountEntityId, new
|
await SetEntityAttributesSafe(SessionCountEntityId, new
|
||||||
{
|
{
|
||||||
friendly_name = "Heating sessions today",
|
friendly_name = "Heating sessions today",
|
||||||
last_updated = timestamp
|
last_updated = timestamp
|
||||||
}).ConfigureAwait(false);
|
})
|
||||||
}
|
.ConfigureAwait(false);
|
||||||
|
|
||||||
public DateTimeOffset? ReadPersistedCooldownTimestamp()
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var entity = haContext.GetState(WaterReadyEntityId);
|
|
||||||
if (entity?.Attributes is not IDictionary<string, object> attributes)
|
|
||||||
{
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!attributes.TryGetValue("cooldown_since", out var value))
|
|
||||||
{
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
var stringValue = value switch
|
|
||||||
{
|
|
||||||
string s => s,
|
|
||||||
System.Text.Json.JsonElement { ValueKind: System.Text.Json.JsonValueKind.String } jsonElement =>
|
|
||||||
jsonElement.GetString(),
|
|
||||||
_ => null
|
|
||||||
};
|
|
||||||
|
|
||||||
if (stringValue is not null &&
|
|
||||||
DateTimeOffset.TryParse(stringValue, CultureInfo.InvariantCulture,
|
|
||||||
DateTimeStyles.RoundtripKind, out var parsed))
|
|
||||||
{
|
|
||||||
logger.LogInformation("Read persisted cooldown timestamp: {CooldownSince}", parsed);
|
|
||||||
return parsed;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
logger.LogError(ex, "Error reading persisted cooldown timestamp");
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task SetEntityStateSafe(string entityId, string state)
|
private async Task SetEntityStateSafe(string entityId, string state)
|
||||||
@@ -485,8 +545,12 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
await entityManager.SetEntityState(entityId, state).ConfigureAwait(false);
|
await entityManager.SetEntityState(entityId, state).ConfigureAwait(false);
|
||||||
|
|
||||||
|
if (logger.IsEnabled(LogLevel.Debug))
|
||||||
|
{
|
||||||
logger.LogDebug("Successfully set state for {EntityId}: {State}", entityId, state);
|
logger.LogDebug("Successfully set state for {EntityId}: {State}", entityId, state);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
logger.LogError(ex, "Failed to set state for {EntityId} to {State}", entityId, state);
|
logger.LogError(ex, "Failed to set state for {EntityId} to {State}", entityId, state);
|
||||||
@@ -498,8 +562,12 @@ public sealed class BoilerMonitorEntityService(
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
await entityManager.SetEntityAttributes(entityId, attributes).ConfigureAwait(false);
|
await entityManager.SetEntityAttributes(entityId, attributes).ConfigureAwait(false);
|
||||||
|
|
||||||
|
if (logger.IsEnabled(LogLevel.Debug))
|
||||||
|
{
|
||||||
logger.LogDebug("Successfully set attributes for {EntityId}", entityId);
|
logger.LogDebug("Successfully set attributes for {EntityId}", entityId);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
logger.LogError(ex, "Failed to set attributes for {EntityId}", entityId);
|
logger.LogError(ex, "Failed to set attributes for {EntityId}", entityId);
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
using System.Globalization;
|
using System.Globalization;
|
||||||
using System.Reactive.Concurrency;
|
using System.Reactive.Concurrency;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
using BoilerMonitor.Models;
|
|
||||||
using BoilerMonitor.Models.Enums;
|
using BoilerMonitor.Models.Enums;
|
||||||
using BoilerMonitorManager.Interface;
|
using BoilerMonitorManager.Interface;
|
||||||
using BoilerMonitorManager.Models;
|
using BoilerMonitorManager.Models;
|
||||||
@@ -14,24 +15,26 @@ using NetDaemon.HassModel;
|
|||||||
using NetDaemon.HassModel.Entities;
|
using NetDaemon.HassModel.Entities;
|
||||||
using static BoilerMonitor.Models.BoilerMonitorConsts;
|
using static BoilerMonitor.Models.BoilerMonitorConsts;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace BoilerMonitorManager;
|
namespace BoilerMonitorManager;
|
||||||
|
|
||||||
[NetDaemonApp]
|
[NetDaemonApp]
|
||||||
public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
public sealed class BoilerMonitorInit
|
||||||
{
|
{
|
||||||
private readonly ILogger<BoilerMonitorInit> _logger;
|
|
||||||
private readonly IHaContext _haContext;
|
|
||||||
private readonly IScheduler _scheduler;
|
|
||||||
private readonly IMqttEntityManager _mqttEntityManager;
|
|
||||||
private readonly IBoilerControlService _boilerControlService;
|
private readonly IBoilerControlService _boilerControlService;
|
||||||
private readonly IBoilerRunTimeTracker _tracker;
|
|
||||||
private readonly IBoilerMonitorEntityService _entityService;
|
private readonly IBoilerMonitorEntityService _entityService;
|
||||||
private readonly IWaterReadyService _waterReadyService;
|
private readonly IHaContext _haContext;
|
||||||
|
private readonly ILogger<BoilerMonitorInit> _logger;
|
||||||
|
private readonly IMqttEntityManager _mqttEntityManager;
|
||||||
private readonly BoilerMonitorOptions _options;
|
private readonly BoilerMonitorOptions _options;
|
||||||
|
private readonly IScheduler _scheduler;
|
||||||
|
|
||||||
private readonly TimeProvider _timeProvider;
|
private readonly TimeProvider _timeProvider;
|
||||||
private bool _lastWaterReady;
|
private readonly IBoilerRunTimeTracker _tracker;
|
||||||
|
private readonly IWaterReadyService _waterReadyService;
|
||||||
private volatile bool _cleanedUp;
|
private volatile bool _cleanedUp;
|
||||||
|
private bool _lastWaterReady;
|
||||||
private DateTimeOffset? _lastWaterReadyNotificationSentAt;
|
private DateTimeOffset? _lastWaterReadyNotificationSentAt;
|
||||||
|
|
||||||
public BoilerMonitorInit(
|
public BoilerMonitorInit(
|
||||||
@@ -56,7 +59,7 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
waterReadyService,
|
waterReadyService,
|
||||||
options,
|
options,
|
||||||
timeProvider,
|
timeProvider,
|
||||||
startBackgroundScheduling: true)
|
true)
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -111,7 +114,7 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task InitializeAsync()
|
private async Task InitializeAsync()
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
@@ -132,7 +135,7 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
|
|
||||||
if (persisted is not null)
|
if (persisted is not null)
|
||||||
{
|
{
|
||||||
_tracker.RestoreFromSnapshot(persisted.AccumulatedRunTime, persisted.SessionCount);
|
_tracker.RestoreFromSnapshot();
|
||||||
|
|
||||||
if (persistedCooldown.HasValue)
|
if (persistedCooldown.HasValue)
|
||||||
{
|
{
|
||||||
@@ -140,9 +143,14 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
}
|
}
|
||||||
|
|
||||||
await _entityService.ResetTransientEntitiesAsync();
|
await _entityService.ResetTransientEntitiesAsync();
|
||||||
_logger.LogInformation("BoilerMonitor state restored from HA entities: runtime={Runtime}, sessions={Sessions}",
|
|
||||||
|
if (_logger.IsEnabled(LogLevel.Information))
|
||||||
|
{
|
||||||
|
_logger.LogInformation(
|
||||||
|
"BoilerMonitor state restored from HA entities: runtime={Runtime}, sessions={Sessions}",
|
||||||
persisted.AccumulatedRunTime, persisted.SessionCount);
|
persisted.AccumulatedRunTime, persisted.SessionCount);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
await _entityService.ResetEntitiesAsync();
|
await _entityService.ResetEntitiesAsync();
|
||||||
@@ -159,15 +167,11 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
_logger.LogError(ex, "Error initializing BoilerMonitor");
|
_logger.LogError(ex, "Error initializing BoilerMonitor");
|
||||||
|
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
await _entityService.CleanupEntitiesAsync(cancellationToken);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void SchedulePeriodicPolling()
|
private void SchedulePeriodicPolling()
|
||||||
{
|
{
|
||||||
var now = DateTime.Now;
|
var now = DateTime.Now;
|
||||||
@@ -176,9 +180,14 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
var delayUntilNext = TimeSpan.FromSeconds(secondsUntilNext);
|
var delayUntilNext = TimeSpan.FromSeconds(secondsUntilNext);
|
||||||
var nextPollTime = now.Add(delayUntilNext);
|
var nextPollTime = now.Add(delayUntilNext);
|
||||||
|
|
||||||
_logger.LogInformation("Scheduling BoilerMonitor polling every {Interval}s, first at {Time}", DefaultPollIntervalSeconds, nextPollTime);
|
if (_logger.IsEnabled(LogLevel.Information))
|
||||||
|
{
|
||||||
|
_logger.LogInformation("Scheduling BoilerMonitor polling every {Interval}s, first at {Time}",
|
||||||
|
DefaultPollIntervalSeconds, nextPollTime);
|
||||||
|
}
|
||||||
|
|
||||||
_scheduler.RunEvery(TimeSpan.FromSeconds(DefaultPollIntervalSeconds), nextPollTime, () => _ = PollAndUpdateAsync());
|
_scheduler.RunEvery(TimeSpan.FromSeconds(DefaultPollIntervalSeconds), nextPollTime,
|
||||||
|
() => _ = PollAndUpdateAsync());
|
||||||
}
|
}
|
||||||
|
|
||||||
private void ScheduleMidnightReset()
|
private void ScheduleMidnightReset()
|
||||||
@@ -207,16 +216,20 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
var switchState = _haContext.GetState(SkipPriceCapEntityId);
|
var switchState = _haContext.GetState(SkipPriceCapEntityId);
|
||||||
if (string.Equals(switchState?.State, SwitchOnState, StringComparison.OrdinalIgnoreCase))
|
|
||||||
|
if (!string.Equals(switchState?.State, SwitchOnState, StringComparison.OrdinalIgnoreCase))
|
||||||
{
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
_haContext.CallService("notify", "mobile_app_marius_phone", null, new
|
_haContext.CallService("notify", "mobile_app_marius_phone", null, new
|
||||||
{
|
{
|
||||||
message = "Remember to turn off 'Skip price cap, heat until ready' if you're done heating.",
|
message = "Remember to turn off 'Skip price cap, heat until ready' if you're done heating.",
|
||||||
title = "Boiler reminder"
|
title = "Boiler reminder"
|
||||||
});
|
});
|
||||||
|
|
||||||
_logger.LogInformation("End-of-day reminder sent: skip price cap switch is still ON");
|
_logger.LogInformation("End-of-day reminder sent: skip price cap switch is still ON");
|
||||||
}
|
}
|
||||||
}
|
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
_logger.LogError(ex, "Error checking skip price cap reminder");
|
_logger.LogError(ex, "Error checking skip price cap reminder");
|
||||||
@@ -227,6 +240,7 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
private void SubscribeToSkipPriceCapChanges()
|
private void SubscribeToSkipPriceCapChanges()
|
||||||
{
|
{
|
||||||
var skipPriceCapSwitch = new Entity(_haContext, SkipPriceCapEntityId);
|
var skipPriceCapSwitch = new Entity(_haContext, SkipPriceCapEntityId);
|
||||||
|
|
||||||
skipPriceCapSwitch.StateChanges()
|
skipPriceCapSwitch.StateChanges()
|
||||||
.Subscribe(e =>
|
.Subscribe(e =>
|
||||||
{
|
{
|
||||||
@@ -243,6 +257,7 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
private void SubscribeToAutoManagementChanges()
|
private void SubscribeToAutoManagementChanges()
|
||||||
{
|
{
|
||||||
var autoManagementSwitch = new Entity(_haContext, AutoManagementEntityId);
|
var autoManagementSwitch = new Entity(_haContext, AutoManagementEntityId);
|
||||||
|
|
||||||
autoManagementSwitch.StateChanges()
|
autoManagementSwitch.StateChanges()
|
||||||
.Subscribe(e =>
|
.Subscribe(e =>
|
||||||
{
|
{
|
||||||
@@ -259,6 +274,7 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
private void SubscribeToShowerState()
|
private void SubscribeToShowerState()
|
||||||
{
|
{
|
||||||
var showerStateSensor = new Entity(_haContext, ShowerStateEntityId);
|
var showerStateSensor = new Entity(_haContext, ShowerStateEntityId);
|
||||||
|
|
||||||
showerStateSensor.StateChanges()
|
showerStateSensor.StateChanges()
|
||||||
.Subscribe(e =>
|
.Subscribe(e =>
|
||||||
{
|
{
|
||||||
@@ -280,6 +296,7 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
private void SubscribeToCleanupButton()
|
private void SubscribeToCleanupButton()
|
||||||
{
|
{
|
||||||
var cleanupButton = new Entity(_haContext, CleanupButtonEntityId);
|
var cleanupButton = new Entity(_haContext, CleanupButtonEntityId);
|
||||||
|
|
||||||
cleanupButton.StateChanges()
|
cleanupButton.StateChanges()
|
||||||
.Subscribe(_ =>
|
.Subscribe(_ =>
|
||||||
{
|
{
|
||||||
@@ -308,8 +325,12 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
private async Task HandleConfigCommandAsync(string entityId, string? state)
|
private async Task HandleConfigCommandAsync(string entityId, string? state)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
|
{
|
||||||
|
if (_logger.IsEnabled(LogLevel.Information))
|
||||||
{
|
{
|
||||||
_logger.LogInformation("Config entity {EntityId} received command: {Value}", entityId, state);
|
_logger.LogInformation("Config entity {EntityId} received command: {Value}", entityId, state);
|
||||||
|
}
|
||||||
|
|
||||||
await _mqttEntityManager.SetStateAsync(entityId, state ?? string.Empty).ConfigureAwait(false);
|
await _mqttEntityManager.SetStateAsync(entityId, state ?? string.Empty).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
@@ -337,8 +358,12 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
private async Task HandleSwitchCommandAsync(string entityId, string? state)
|
private async Task HandleSwitchCommandAsync(string entityId, string? state)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
|
{
|
||||||
|
if (_logger.IsEnabled(LogLevel.Information))
|
||||||
{
|
{
|
||||||
_logger.LogInformation("Switch {EntityId} received command: {Value}", entityId, state);
|
_logger.LogInformation("Switch {EntityId} received command: {Value}", entityId, state);
|
||||||
|
}
|
||||||
|
|
||||||
await _mqttEntityManager.SetStateAsync(entityId, state ?? string.Empty).ConfigureAwait(false);
|
await _mqttEntityManager.SetStateAsync(entityId, state ?? string.Empty).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
catch (Exception e)
|
catch (Exception e)
|
||||||
@@ -367,6 +392,7 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
if (_cleanedUp)
|
if (_cleanedUp)
|
||||||
{
|
{
|
||||||
_logger.LogDebug("BoilerMonitor is cleaned up, skipping poll");
|
_logger.LogDebug("BoilerMonitor is cleaned up, skipping poll");
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -377,7 +403,9 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
if (!config.IsFullyConfigured)
|
if (!config.IsFullyConfigured)
|
||||||
{
|
{
|
||||||
await _entityService.SetStatusAsync(StatusAwaitingConfiguration);
|
await _entityService.SetStatusAsync(StatusAwaitingConfiguration);
|
||||||
_logger.LogWarning("BoilerMonitor not fully configured (power={Power}, switch={Switch}, interval={Interval}, threshold={Threshold}). Awaiting configuration",
|
|
||||||
|
_logger.LogWarning(
|
||||||
|
"BoilerMonitor not fully configured (power={Power}, switch={Switch}, interval={Interval}, threshold={Threshold}). Awaiting configuration",
|
||||||
config.BoilerPowerEntityId, config.BoilerSwitchEntityId,
|
config.BoilerPowerEntityId, config.BoilerSwitchEntityId,
|
||||||
config.PollIntervalSeconds, config.HeatingPowerThresholdWatts);
|
config.PollIntervalSeconds, config.HeatingPowerThresholdWatts);
|
||||||
|
|
||||||
@@ -386,10 +414,11 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
|
|
||||||
var boilerPowerWatts = ReadSensorDouble(config.BoilerPowerEntityId!);
|
var boilerPowerWatts = ReadSensorDouble(config.BoilerPowerEntityId!);
|
||||||
var boilerSwitchState = _haContext.GetState(config.BoilerSwitchEntityId!)?.State;
|
var boilerSwitchState = _haContext.GetState(config.BoilerSwitchEntityId!)?.State;
|
||||||
var isHeating = boilerPowerWatts.HasValue && boilerPowerWatts.Value >= config.HeatingPowerThresholdWatts!.Value;
|
|
||||||
var pollInterval = TimeSpan.FromSeconds(config.PollIntervalSeconds!.Value);
|
|
||||||
|
|
||||||
_tracker.RecordPollResult(isHeating, pollInterval);
|
var isHeating = boilerPowerWatts.HasValue &&
|
||||||
|
boilerPowerWatts.Value >= config.HeatingPowerThresholdWatts!.Value;
|
||||||
|
|
||||||
|
_tracker.RecordPollResult();
|
||||||
|
|
||||||
if (isHeating)
|
if (isHeating)
|
||||||
{
|
{
|
||||||
@@ -398,7 +427,6 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
|
|
||||||
var cheapestIntervalsState = _haContext.GetState(NordPoolCheapestIntervalsEntityId);
|
var cheapestIntervalsState = _haContext.GetState(NordPoolCheapestIntervalsEntityId);
|
||||||
var isNowCheap = ReadAttributeBool(cheapestIntervalsState, "is_now_cheap");
|
var isNowCheap = ReadAttributeBool(cheapestIntervalsState, "is_now_cheap");
|
||||||
var nextCheapInterval = ReadAttributeDateTime(cheapestIntervalsState, "next_cheap_interval");
|
|
||||||
|
|
||||||
var budgetOverrideState = _haContext.GetState(BudgetOverrideEntityId)?.State;
|
var budgetOverrideState = _haContext.GetState(BudgetOverrideEntityId)?.State;
|
||||||
var budgetOverride = string.Equals(budgetOverrideState, SwitchOnState, StringComparison.OrdinalIgnoreCase);
|
var budgetOverride = string.Equals(budgetOverrideState, SwitchOnState, StringComparison.OrdinalIgnoreCase);
|
||||||
@@ -408,7 +436,8 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
|
|
||||||
var dailyHours = ReadSensorDouble(BoilerDailyHoursEntityId) ?? 1.0;
|
var dailyHours = ReadSensorDouble(BoilerDailyHoursEntityId) ?? 1.0;
|
||||||
|
|
||||||
var waterReady = _waterReadyService.IsWaterReady(boilerSwitchState, boilerPowerWatts, config.HeatingPowerThresholdWatts!.Value);
|
var waterReady = _waterReadyService.IsWaterReady(boilerSwitchState, boilerPowerWatts,
|
||||||
|
config.HeatingPowerThresholdWatts!.Value);
|
||||||
|
|
||||||
if (!_lastWaterReady && waterReady && !IsWithinNotificationCooldown())
|
if (!_lastWaterReady && waterReady && !IsWithinNotificationCooldown())
|
||||||
{
|
{
|
||||||
@@ -417,9 +446,11 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
message = "Hot water is ready.",
|
message = "Hot water is ready.",
|
||||||
title = "Boiler"
|
title = "Boiler"
|
||||||
});
|
});
|
||||||
|
|
||||||
_lastWaterReadyNotificationSentAt = _timeProvider.GetUtcNow();
|
_lastWaterReadyNotificationSentAt = _timeProvider.GetUtcNow();
|
||||||
_logger.LogInformation("Water ready notification sent");
|
_logger.LogInformation("Water ready notification sent");
|
||||||
}
|
}
|
||||||
|
|
||||||
_lastWaterReady = waterReady;
|
_lastWaterReady = waterReady;
|
||||||
|
|
||||||
var snapshot = _tracker.GetSnapshot();
|
var snapshot = _tracker.GetSnapshot();
|
||||||
@@ -432,7 +463,7 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
}
|
}
|
||||||
|
|
||||||
var budgetPercentage = budgetTimeSpan.TotalSeconds > 0
|
var budgetPercentage = budgetTimeSpan.TotalSeconds > 0
|
||||||
? (snapshot.AccumulatedRunTime.TotalSeconds / budgetTimeSpan.TotalSeconds) * 100.0
|
? snapshot.AccumulatedRunTime.TotalSeconds / budgetTimeSpan.TotalSeconds * 100.0
|
||||||
: 0.0;
|
: 0.0;
|
||||||
|
|
||||||
var budgetExhausted = snapshot.AccumulatedRunTime >= budgetTimeSpan;
|
var budgetExhausted = snapshot.AccumulatedRunTime >= budgetTimeSpan;
|
||||||
@@ -447,7 +478,9 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
budgetOverride);
|
budgetOverride);
|
||||||
|
|
||||||
var autoManagementState = _haContext.GetState(AutoManagementEntityId)?.State;
|
var autoManagementState = _haContext.GetState(AutoManagementEntityId)?.State;
|
||||||
var autoManagementEnabled = !string.Equals(autoManagementState, SwitchOffState, StringComparison.OrdinalIgnoreCase);
|
|
||||||
|
var autoManagementEnabled =
|
||||||
|
!string.Equals(autoManagementState, SwitchOffState, StringComparison.OrdinalIgnoreCase);
|
||||||
|
|
||||||
if (autoManagementEnabled)
|
if (autoManagementEnabled)
|
||||||
{
|
{
|
||||||
@@ -455,9 +488,10 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
}
|
}
|
||||||
else if (boilerAction is not BoilerAction.NoChange)
|
else if (boilerAction is not BoilerAction.NoChange)
|
||||||
{
|
{
|
||||||
_logger.LogInformation(
|
if (_logger.IsEnabled(LogLevel.Information))
|
||||||
"Automatic boiler control is off; skipping boiler switch service call (would have been {Action})",
|
{
|
||||||
boilerAction);
|
_logger.LogInformation("Automatic boiler control is off; skipping boiler switch service call (would have been {Action})", boilerAction);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var context = new BoilerMonitorUpdateContext
|
var context = new BoilerMonitorUpdateContext
|
||||||
@@ -468,20 +502,21 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
BudgetExhausted = budgetExhausted,
|
BudgetExhausted = budgetExhausted,
|
||||||
SessionCount = snapshot.SessionCount,
|
SessionCount = snapshot.SessionCount,
|
||||||
BudgetHours = dailyHours,
|
BudgetHours = dailyHours,
|
||||||
IsCurrentlyHeating = isHeating,
|
|
||||||
WaterReady = waterReady,
|
WaterReady = waterReady,
|
||||||
BoilerSwitchState = boilerSwitchState,
|
BoilerSwitchState = boilerSwitchState,
|
||||||
BoilerPowerWatts = boilerPowerWatts,
|
BoilerPowerWatts = boilerPowerWatts,
|
||||||
CooldownSince = _waterReadyService.WaterReadySince,
|
CooldownSince = _waterReadyService.WaterReadySince
|
||||||
IsNowCheap = effectiveIsNowCheap,
|
|
||||||
NextCheapIntervalStart = nextCheapInterval
|
|
||||||
};
|
};
|
||||||
|
|
||||||
await _entityService.UpdateEntitiesAsync(context);
|
await _entityService.UpdateEntitiesAsync(context);
|
||||||
|
|
||||||
_logger.LogDebug("Poll complete: power={Power}W, heating={Heating}, runtime={Runtime}, budget={Budget}%",
|
if (_logger.IsEnabled(LogLevel.Debug))
|
||||||
|
{
|
||||||
|
_logger.LogDebug(
|
||||||
|
"Poll complete: power={Power}W, heating={Heating}, runtime={Runtime}, budget={Budget}%",
|
||||||
boilerPowerWatts, isHeating, snapshot.AccumulatedRunTime, budgetPercentage);
|
boilerPowerWatts, isHeating, snapshot.AccumulatedRunTime, budgetPercentage);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
_logger.LogError(ex, "Error during BoilerMonitor poll and update");
|
_logger.LogError(ex, "Error during BoilerMonitor poll and update");
|
||||||
@@ -495,12 +530,17 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
case BoilerAction.TurnOn:
|
case BoilerAction.TurnOn:
|
||||||
_haContext.CallService("switch", "turn_on", ServiceTarget.FromEntity(switchEntityId));
|
_haContext.CallService("switch", "turn_on", ServiceTarget.FromEntity(switchEntityId));
|
||||||
_waterReadyService.NotifyTurnedOn();
|
_waterReadyService.NotifyTurnedOn();
|
||||||
|
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case BoilerAction.TurnOff:
|
case BoilerAction.TurnOff:
|
||||||
_haContext.CallService("switch", "turn_off", ServiceTarget.FromEntity(switchEntityId));
|
_haContext.CallService("switch", "turn_off", ServiceTarget.FromEntity(switchEntityId));
|
||||||
|
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case BoilerAction.NoChange:
|
case BoilerAction.NoChange:
|
||||||
break;
|
break;
|
||||||
|
|
||||||
default:
|
default:
|
||||||
throw new ArgumentOutOfRangeException(nameof(action), action, null);
|
throw new ArgumentOutOfRangeException(nameof(action), action, null);
|
||||||
}
|
}
|
||||||
@@ -514,9 +554,7 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
int? pollInterval = null;
|
int? pollInterval = null;
|
||||||
var pollIntervalState = _haContext.GetState(ConfigPollIntervalEntityId)?.State;
|
var pollIntervalState = _haContext.GetState(ConfigPollIntervalEntityId)?.State;
|
||||||
|
|
||||||
if (!string.IsNullOrWhiteSpace(pollIntervalState)
|
if (!string.IsNullOrWhiteSpace(pollIntervalState) && double.TryParse(pollIntervalState, CultureInfo.InvariantCulture, out var pollIntervalValue) && pollIntervalValue > 0)
|
||||||
&& double.TryParse(pollIntervalState, CultureInfo.InvariantCulture, out var pollIntervalValue)
|
|
||||||
&& pollIntervalValue > 0)
|
|
||||||
{
|
{
|
||||||
pollInterval = (int)pollIntervalValue;
|
pollInterval = (int)pollIntervalValue;
|
||||||
}
|
}
|
||||||
@@ -524,9 +562,7 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
double? heatingThreshold = null;
|
double? heatingThreshold = null;
|
||||||
var thresholdState = _haContext.GetState(ConfigHeatingThresholdEntityId)?.State;
|
var thresholdState = _haContext.GetState(ConfigHeatingThresholdEntityId)?.State;
|
||||||
|
|
||||||
if (!string.IsNullOrWhiteSpace(thresholdState)
|
if (!string.IsNullOrWhiteSpace(thresholdState) && double.TryParse(thresholdState, CultureInfo.InvariantCulture, out var thresholdValue) && thresholdValue > 0)
|
||||||
&& double.TryParse(thresholdState, CultureInfo.InvariantCulture, out var thresholdValue)
|
|
||||||
&& thresholdValue > 0)
|
|
||||||
{
|
{
|
||||||
heatingThreshold = thresholdValue;
|
heatingThreshold = thresholdValue;
|
||||||
}
|
}
|
||||||
@@ -554,14 +590,14 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
|
|
||||||
private static bool ReadAttributeBool(EntityState? entityState, string attributeName)
|
private static bool ReadAttributeBool(EntityState? entityState, string attributeName)
|
||||||
{
|
{
|
||||||
if (entityState?.Attributes is null)
|
if (entityState?.Attributes is not IDictionary<string, object> attributes)
|
||||||
{
|
{
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
if (entityState.Attributes is IDictionary<string, object> attributes && attributes.TryGetValue(attributeName, out var value))
|
if (attributes.TryGetValue(attributeName, out var value))
|
||||||
{
|
{
|
||||||
return value switch
|
return value switch
|
||||||
{
|
{
|
||||||
@@ -569,7 +605,7 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
string s => bool.TryParse(s, out var parsed) && parsed,
|
string s => bool.TryParse(s, out var parsed) && parsed,
|
||||||
JsonElement { ValueKind: JsonValueKind.True } => true,
|
JsonElement { ValueKind: JsonValueKind.True } => true,
|
||||||
JsonElement { ValueKind: JsonValueKind.False } => false,
|
JsonElement { ValueKind: JsonValueKind.False } => false,
|
||||||
JsonElement jsonElement when jsonElement.ValueKind == JsonValueKind.String =>
|
JsonElement { ValueKind: JsonValueKind.String } jsonElement =>
|
||||||
bool.TryParse(jsonElement.GetString(), out var jsonParsed) && jsonParsed,
|
bool.TryParse(jsonElement.GetString(), out var jsonParsed) && jsonParsed,
|
||||||
_ => false
|
_ => false
|
||||||
};
|
};
|
||||||
@@ -591,38 +627,7 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
|
|||||||
}
|
}
|
||||||
|
|
||||||
var elapsed = _timeProvider.GetUtcNow() - _lastWaterReadyNotificationSentAt.Value;
|
var elapsed = _timeProvider.GetUtcNow() - _lastWaterReadyNotificationSentAt.Value;
|
||||||
|
|
||||||
return elapsed < WaterReadyNotificationCooldown;
|
return elapsed < WaterReadyNotificationCooldown;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static DateTime? ReadAttributeDateTime(EntityState? entityState, string attributeName)
|
|
||||||
{
|
|
||||||
if (entityState?.Attributes is null)
|
|
||||||
{
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
if (entityState.Attributes is IDictionary<string, object> attributes && attributes.TryGetValue(attributeName, out var value))
|
|
||||||
{
|
|
||||||
var stringValue = value switch
|
|
||||||
{
|
|
||||||
string s => s,
|
|
||||||
JsonElement { ValueKind: JsonValueKind.String } jsonElement => jsonElement.GetString(),
|
|
||||||
_ => null
|
|
||||||
};
|
|
||||||
|
|
||||||
if (stringValue is not null && DateTime.TryParse(stringValue, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var parsed))
|
|
||||||
{
|
|
||||||
return parsed;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
catch
|
|
||||||
{
|
|
||||||
// Attribute not found or not parseable
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -1,10 +1,13 @@
|
|||||||
using BoilerMonitor.Models;
|
#region
|
||||||
|
|
||||||
using BoilerMonitorManager.Interface;
|
using BoilerMonitorManager.Interface;
|
||||||
using BoilerMonitorManager.Models;
|
using BoilerMonitorManager.Models;
|
||||||
using Microsoft.Extensions.Configuration;
|
using Microsoft.Extensions.Configuration;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using NetDaemon.AppModel;
|
using NetDaemon.AppModel;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace BoilerMonitorManager;
|
namespace BoilerMonitorManager;
|
||||||
|
|
||||||
public static class BoilerMonitorServiceRegistration
|
public static class BoilerMonitorServiceRegistration
|
||||||
@@ -13,7 +16,8 @@ public static class BoilerMonitorServiceRegistration
|
|||||||
{
|
{
|
||||||
var options = configuration
|
var options = configuration
|
||||||
.GetSection(BoilerMonitorOptions.SectionName)
|
.GetSection(BoilerMonitorOptions.SectionName)
|
||||||
.Get<BoilerMonitorOptions>() ?? new BoilerMonitorOptions();
|
.Get<BoilerMonitorOptions>() ??
|
||||||
|
new BoilerMonitorOptions();
|
||||||
|
|
||||||
if (!options.Enabled)
|
if (!options.Enabled)
|
||||||
{
|
{
|
||||||
@@ -23,9 +27,9 @@ public static class BoilerMonitorServiceRegistration
|
|||||||
services
|
services
|
||||||
.AddNetDaemonApp<BoilerMonitorInit>()
|
.AddNetDaemonApp<BoilerMonitorInit>()
|
||||||
.AddSingleton<IBoilerControlService, BoilerControlService>()
|
.AddSingleton<IBoilerControlService, BoilerControlService>()
|
||||||
.AddSingleton<IBoilerRunTimeTracker, BoilerRunTimeTracker>()
|
|
||||||
.AddTransient<IBoilerMonitorEntityService, BoilerMonitorEntityService>()
|
.AddTransient<IBoilerMonitorEntityService, BoilerMonitorEntityService>()
|
||||||
.AddSingleton<IWaterReadyService, WaterReadyService>();
|
.AddSingleton<IWaterReadyService, WaterReadyService>()
|
||||||
|
.AddSingleton<IBoilerRunTimeTracker, BoilerRunTimeTracker>();
|
||||||
|
|
||||||
return services;
|
return services;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,66 +1,32 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
using BoilerMonitorManager.Interface;
|
using BoilerMonitorManager.Interface;
|
||||||
using BoilerMonitorManager.Models;
|
using BoilerMonitorManager.Models;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace BoilerMonitorManager;
|
namespace BoilerMonitorManager;
|
||||||
|
|
||||||
public sealed class BoilerRunTimeTracker : IBoilerRunTimeTracker
|
public class BoilerRunTimeTracker : IBoilerRunTimeTracker
|
||||||
{
|
{
|
||||||
private readonly Lock _lock = new();
|
public void RecordPollResult()
|
||||||
private TimeSpan _accumulatedRunTime = TimeSpan.Zero;
|
|
||||||
private int _sessionCount;
|
|
||||||
private bool _isInSession;
|
|
||||||
|
|
||||||
public void RecordPollResult(bool isHeating, TimeSpan pollInterval)
|
|
||||||
{
|
{
|
||||||
lock (_lock)
|
|
||||||
{
|
|
||||||
if (isHeating)
|
|
||||||
{
|
|
||||||
_accumulatedRunTime += pollInterval;
|
|
||||||
|
|
||||||
if (!_isInSession)
|
|
||||||
{
|
|
||||||
_sessionCount++;
|
|
||||||
_isInSession = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
_isInSession = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public RunTimeSnapshot GetSnapshot()
|
public RunTimeSnapshot GetSnapshot()
|
||||||
{
|
|
||||||
lock (_lock)
|
|
||||||
{
|
{
|
||||||
return new RunTimeSnapshot
|
return new RunTimeSnapshot
|
||||||
{
|
{
|
||||||
AccumulatedRunTime = _accumulatedRunTime,
|
AccumulatedRunTime = TimeSpan.Zero,
|
||||||
SessionCount = _sessionCount,
|
SessionCount = 0
|
||||||
IsInSession = _isInSession
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
public void Reset()
|
public void Reset()
|
||||||
{
|
{
|
||||||
lock (_lock)
|
|
||||||
{
|
|
||||||
_accumulatedRunTime = TimeSpan.Zero;
|
|
||||||
_sessionCount = 0;
|
|
||||||
_isInSession = false;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void RestoreFromSnapshot(TimeSpan accumulatedRunTime, int sessionCount)
|
public void RestoreFromSnapshot()
|
||||||
{
|
{
|
||||||
lock (_lock)
|
|
||||||
{
|
|
||||||
_accumulatedRunTime = accumulatedRunTime;
|
|
||||||
_sessionCount = sessionCount;
|
|
||||||
_isInSession = false;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,9 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
using BoilerMonitor.Models.Enums;
|
using BoilerMonitor.Models.Enums;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace BoilerMonitorManager.Interface;
|
namespace BoilerMonitorManager.Interface;
|
||||||
|
|
||||||
public interface IBoilerControlService
|
public interface IBoilerControlService
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
using BoilerMonitor.Models;
|
#region
|
||||||
|
|
||||||
using BoilerMonitorManager.Models;
|
using BoilerMonitorManager.Models;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace BoilerMonitorManager.Interface;
|
namespace BoilerMonitorManager.Interface;
|
||||||
|
|
||||||
public interface IBoilerMonitorEntityService
|
public interface IBoilerMonitorEntityService
|
||||||
|
|||||||
@@ -1,7 +0,0 @@
|
|||||||
namespace BoilerMonitorManager.Interface;
|
|
||||||
|
|
||||||
public interface IBoilerMonitorInit
|
|
||||||
{
|
|
||||||
Task InitializeAsync();
|
|
||||||
Task CleanupEntitiesAsync(CancellationToken cancellationToken = default);
|
|
||||||
}
|
|
||||||
@@ -1,11 +1,15 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
using BoilerMonitorManager.Models;
|
using BoilerMonitorManager.Models;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace BoilerMonitorManager.Interface;
|
namespace BoilerMonitorManager.Interface;
|
||||||
|
|
||||||
public interface IBoilerRunTimeTracker
|
public interface IBoilerRunTimeTracker
|
||||||
{
|
{
|
||||||
void RecordPollResult(bool isHeating, TimeSpan pollInterval);
|
void RecordPollResult();
|
||||||
RunTimeSnapshot GetSnapshot();
|
RunTimeSnapshot GetSnapshot();
|
||||||
void Reset();
|
void Reset();
|
||||||
void RestoreFromSnapshot(TimeSpan accumulatedRunTime, int sessionCount);
|
void RestoreFromSnapshot();
|
||||||
}
|
}
|
||||||
@@ -2,9 +2,9 @@ namespace BoilerMonitorManager.Interface;
|
|||||||
|
|
||||||
public interface IWaterReadyService
|
public interface IWaterReadyService
|
||||||
{
|
{
|
||||||
bool IsWaterReady(string? switchState, double? powerWatts, double heatingThresholdWatts);
|
|
||||||
bool IsInCooldown { get; }
|
bool IsInCooldown { get; }
|
||||||
DateTimeOffset? WaterReadySince { get; }
|
DateTimeOffset? WaterReadySince { get; }
|
||||||
|
bool IsWaterReady(string? switchState, double? powerWatts, double heatingThresholdWatts);
|
||||||
void NotifyTurnedOn();
|
void NotifyTurnedOn();
|
||||||
void RecordHeatingObserved();
|
void RecordHeatingObserved();
|
||||||
void ResetCooldown();
|
void ResetCooldown();
|
||||||
|
|||||||
@@ -7,8 +7,7 @@ public record BoilerMonitorConfig
|
|||||||
public int? PollIntervalSeconds { get; init; }
|
public int? PollIntervalSeconds { get; init; }
|
||||||
public double? HeatingPowerThresholdWatts { get; init; }
|
public double? HeatingPowerThresholdWatts { get; init; }
|
||||||
|
|
||||||
public bool IsFullyConfigured =>
|
public bool IsFullyConfigured => !string.IsNullOrWhiteSpace(BoilerPowerEntityId) &&
|
||||||
!string.IsNullOrWhiteSpace(BoilerPowerEntityId) &&
|
|
||||||
!string.IsNullOrWhiteSpace(BoilerSwitchEntityId) &&
|
!string.IsNullOrWhiteSpace(BoilerSwitchEntityId) &&
|
||||||
PollIntervalSeconds is > 0 &&
|
PollIntervalSeconds is > 0 &&
|
||||||
HeatingPowerThresholdWatts is > 0;
|
HeatingPowerThresholdWatts is > 0;
|
||||||
|
|||||||
@@ -8,11 +8,8 @@ public record BoilerMonitorUpdateContext
|
|||||||
public required bool BudgetExhausted { get; init; }
|
public required bool BudgetExhausted { get; init; }
|
||||||
public required int SessionCount { get; init; }
|
public required int SessionCount { get; init; }
|
||||||
public required double BudgetHours { get; init; }
|
public required double BudgetHours { get; init; }
|
||||||
public required bool IsCurrentlyHeating { get; init; }
|
|
||||||
public required bool WaterReady { get; init; }
|
public required bool WaterReady { get; init; }
|
||||||
public required string? BoilerSwitchState { get; init; }
|
public required string? BoilerSwitchState { get; init; }
|
||||||
public required double? BoilerPowerWatts { get; init; }
|
public required double? BoilerPowerWatts { get; init; }
|
||||||
public required DateTimeOffset? CooldownSince { get; init; }
|
public required DateTimeOffset? CooldownSince { get; init; }
|
||||||
public required bool IsNowCheap { get; init; }
|
|
||||||
public required DateTime? NextCheapIntervalStart { get; init; }
|
|
||||||
}
|
}
|
||||||
@@ -4,5 +4,4 @@ public record RunTimeSnapshot
|
|||||||
{
|
{
|
||||||
public required TimeSpan AccumulatedRunTime { get; init; }
|
public required TimeSpan AccumulatedRunTime { get; init; }
|
||||||
public required int SessionCount { get; init; }
|
public required int SessionCount { get; init; }
|
||||||
public required bool IsInSession { get; init; }
|
|
||||||
}
|
}
|
||||||
@@ -1,16 +1,20 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
using BoilerMonitor.Models;
|
using BoilerMonitor.Models;
|
||||||
using BoilerMonitorManager.Interface;
|
using BoilerMonitorManager.Interface;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace BoilerMonitorManager;
|
namespace BoilerMonitorManager;
|
||||||
|
|
||||||
public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimeProvider timeProvider) : IWaterReadyService
|
public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimeProvider timeProvider) : IWaterReadyService
|
||||||
{
|
{
|
||||||
private const string SwitchOnState = "on";
|
private const string SwitchOnState = "on";
|
||||||
private readonly Lock _lock = new();
|
private readonly Lock _lock = new Lock();
|
||||||
private DateTimeOffset? _waterReadySince;
|
|
||||||
private bool _hasObservedHeating;
|
|
||||||
private int _consecutiveBelowThresholdCount;
|
private int _consecutiveBelowThresholdCount;
|
||||||
|
private bool _hasObservedHeating;
|
||||||
|
private DateTimeOffset? _waterReadySince;
|
||||||
|
|
||||||
public bool IsInCooldown
|
public bool IsInCooldown
|
||||||
{
|
{
|
||||||
@@ -40,7 +44,12 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
|
|||||||
{
|
{
|
||||||
if (IsWithinCooldownPeriod())
|
if (IsWithinCooldownPeriod())
|
||||||
{
|
{
|
||||||
logger.LogDebug("Water ready cooldown active (since {Since}), suppressing turn-on", _waterReadySince);
|
if (logger.IsEnabled(LogLevel.Debug))
|
||||||
|
{
|
||||||
|
logger.LogDebug("Water ready cooldown active (since {Since}), suppressing turn-on",
|
||||||
|
_waterReadySince);
|
||||||
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -59,35 +68,45 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
|
|||||||
{
|
{
|
||||||
if (!_hasObservedHeating)
|
if (!_hasObservedHeating)
|
||||||
{
|
{
|
||||||
logger.LogDebug(
|
if (logger.IsEnabled(LogLevel.Debug))
|
||||||
"Ignoring power reading ({PowerWatts}W) — boiler has not been observed heating yet",
|
{
|
||||||
|
logger.LogDebug("Ignoring power reading ({PowerWatts}W) — boiler has not been observed heating yet",
|
||||||
powerWatts.Value);
|
powerWatts.Value);
|
||||||
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (powerWatts.Value >= heatingThresholdWatts)
|
if (powerWatts.Value >= heatingThresholdWatts)
|
||||||
{
|
{
|
||||||
_consecutiveBelowThresholdCount = 0;
|
_consecutiveBelowThresholdCount = 0;
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
_consecutiveBelowThresholdCount++;
|
_consecutiveBelowThresholdCount++;
|
||||||
|
|
||||||
if (_consecutiveBelowThresholdCount < BoilerMonitorConsts.ConsecutiveReadingsRequired)
|
if (_consecutiveBelowThresholdCount < BoilerMonitorConsts.ConsecutiveReadingsRequired)
|
||||||
|
{
|
||||||
|
if (logger.IsEnabled(LogLevel.Debug))
|
||||||
{
|
{
|
||||||
logger.LogDebug(
|
logger.LogDebug(
|
||||||
"Below-threshold reading {Count}/{Required} ({PowerWatts}W), waiting for confirmation",
|
"Below-threshold reading {Count}/{Required} ({PowerWatts}W), waiting for confirmation",
|
||||||
_consecutiveBelowThresholdCount,
|
_consecutiveBelowThresholdCount, BoilerMonitorConsts.ConsecutiveReadingsRequired,
|
||||||
BoilerMonitorConsts.ConsecutiveReadingsRequired,
|
|
||||||
powerWatts.Value);
|
powerWatts.Value);
|
||||||
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
_waterReadySince ??= timeProvider.GetUtcNow();
|
_waterReadySince ??= timeProvider.GetUtcNow();
|
||||||
|
|
||||||
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
|
{
|
||||||
logger.LogInformation(
|
logger.LogInformation(
|
||||||
"Water detected as ready after {Count} consecutive readings, cooldown active until shower or midnight reset",
|
"Water detected as ready after {Count} consecutive readings, cooldown active until shower or midnight reset",
|
||||||
_consecutiveBelowThresholdCount);
|
_consecutiveBelowThresholdCount);
|
||||||
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -101,7 +120,8 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
|
|||||||
_consecutiveBelowThresholdCount = 0;
|
_consecutiveBelowThresholdCount = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.LogDebug("Boiler turn-on recorded, awaiting first heating observation before water ready detection is enabled");
|
logger.LogDebug(
|
||||||
|
"Boiler turn-on recorded, awaiting first heating observation before water ready detection is enabled");
|
||||||
}
|
}
|
||||||
|
|
||||||
public void RecordHeatingObserved()
|
public void RecordHeatingObserved()
|
||||||
@@ -135,17 +155,29 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
|
|||||||
lock (_lock)
|
lock (_lock)
|
||||||
{
|
{
|
||||||
var todayMidnightUtc = new DateTimeOffset(timeProvider.GetUtcNow().Date, TimeSpan.Zero);
|
var todayMidnightUtc = new DateTimeOffset(timeProvider.GetUtcNow().Date, TimeSpan.Zero);
|
||||||
|
|
||||||
if (waterReadySince < todayMidnightUtc)
|
if (waterReadySince < todayMidnightUtc)
|
||||||
{
|
{
|
||||||
logger.LogInformation(
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
"Persisted cooldown is from a previous day ({Since}), not restoring", waterReadySince);
|
{
|
||||||
|
logger.LogInformation("Persisted cooldown is from a previous day ({Since}), not restoring",
|
||||||
|
waterReadySince);
|
||||||
|
}
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
_waterReadySince = waterReadySince;
|
_waterReadySince = waterReadySince;
|
||||||
|
|
||||||
|
if (logger.IsEnabled(LogLevel.Information))
|
||||||
|
{
|
||||||
logger.LogInformation("Restored water ready cooldown from {Since}", waterReadySince);
|
logger.LogInformation("Restored water ready cooldown from {Since}", waterReadySince);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
private bool IsWithinCooldownPeriod() => _waterReadySince is not null;
|
|
||||||
|
private bool IsWithinCooldownPeriod()
|
||||||
|
{
|
||||||
|
return _waterReadySince is not null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -12,7 +12,7 @@
|
|||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="NetDaemon.Extensions.Mqtt" Version="26.11.0" />
|
<PackageReference Include="NetDaemon.Extensions.Mqtt" Version="26.43.1"/>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
@@ -20,12 +20,6 @@ public static class BoilerMonitorConsts
|
|||||||
public const string ShowerStateEntityId = "sensor.showermonitor_state";
|
public const string ShowerStateEntityId = "sensor.showermonitor_state";
|
||||||
public const string ShowerActiveState = "Active";
|
public const string ShowerActiveState = "Active";
|
||||||
|
|
||||||
/// <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);
|
|
||||||
|
|
||||||
public const int MinPollIntervalSeconds = 5;
|
public const int MinPollIntervalSeconds = 5;
|
||||||
public const int MaxPollIntervalSeconds = 300;
|
public const int MaxPollIntervalSeconds = 300;
|
||||||
public const int PollIntervalStepSeconds = 5;
|
public const int PollIntervalStepSeconds = 5;
|
||||||
@@ -65,7 +59,6 @@ public static class BoilerMonitorConsts
|
|||||||
|
|
||||||
public const string StatusConfigured = "configured";
|
public const string StatusConfigured = "configured";
|
||||||
public const string StatusAwaitingConfiguration = "awaiting_configuration";
|
public const string StatusAwaitingConfiguration = "awaiting_configuration";
|
||||||
public const string StatusCleanedUp = "cleaned_up";
|
|
||||||
|
|
||||||
public const string SwitchOnState = "on";
|
public const string SwitchOnState = "on";
|
||||||
|
|
||||||
@@ -74,4 +67,10 @@ public static class BoilerMonitorConsts
|
|||||||
public const string DeviceIdentifier = "boiler_monitor";
|
public const string DeviceIdentifier = "boiler_monitor";
|
||||||
public const string DeviceName = "Boiler Monitor";
|
public const string DeviceName = "Boiler Monitor";
|
||||||
public const string DeviceManufacturer = "HomeAssistant App Daemon";
|
public const string DeviceManufacturer = "HomeAssistant App Daemon";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Minimum interval between "hot water is ready" push notifications.
|
||||||
|
/// Prevents notification spam when power readings fluctuate around the heating threshold.
|
||||||
|
/// </summary>
|
||||||
|
public static readonly TimeSpan WaterReadyNotificationCooldown = TimeSpan.FromHours(1);
|
||||||
}
|
}
|
||||||
@@ -1,14 +1,14 @@
|
|||||||
|
#region
|
||||||
|
|
||||||
using HomeAssistant.Models;
|
using HomeAssistant.Models;
|
||||||
using NetDaemon.Extensions.MqttEntityManager;
|
using NetDaemon.Extensions.MqttEntityManager;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace BoilerMonitor.Models;
|
namespace BoilerMonitor.Models;
|
||||||
|
|
||||||
public class BoilerMonitorEntity : EntityCreateModel
|
public class BoilerMonitorEntity : EntityCreateModel
|
||||||
{
|
{
|
||||||
public string Domain { get; set; }
|
|
||||||
public string Identifier { get; set; }
|
|
||||||
public string Name { get; set; }
|
|
||||||
|
|
||||||
public BoilerMonitorEntity(string domain, string identifier, string name)
|
public BoilerMonitorEntity(string domain, string identifier, string name)
|
||||||
{
|
{
|
||||||
Domain = domain;
|
Domain = domain;
|
||||||
@@ -22,4 +22,8 @@ public class BoilerMonitorEntity : EntityCreateModel
|
|||||||
Name = Name
|
Name = Name
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private string Domain { get; }
|
||||||
|
private string Identifier { get; }
|
||||||
|
private string Name { get; }
|
||||||
}
|
}
|
||||||
@@ -1,15 +1,28 @@
|
|||||||
using HomeAssistant.Entities.Interfaces;
|
#region
|
||||||
|
|
||||||
|
using HomeAssistant.Entities.Interfaces;
|
||||||
using HomeAssistant.Models;
|
using HomeAssistant.Models;
|
||||||
|
using HomeAssistantGenerated;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
using NetDaemon.Extensions.MqttEntityManager;
|
using NetDaemon.Extensions.MqttEntityManager;
|
||||||
|
using NetDaemon.HassModel;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace HomeAssistant.Entities;
|
namespace HomeAssistant.Entities;
|
||||||
|
|
||||||
public class EntityManager(IMqttEntityManager entityManager) : IEntityManager
|
public class EntityManager(
|
||||||
|
IMqttEntityManager entityManager,
|
||||||
|
IHaContext haContext,
|
||||||
|
IOptions<MqttConfiguration> mqttConfiguration) : IEntityManager
|
||||||
{
|
{
|
||||||
public async Task CreateEntitiesAsync(ICollection<EntityCreateModel> entities)
|
/// <summary>
|
||||||
{
|
/// Every topic owned by an entity created through <see cref="IMqttEntityManager" />:
|
||||||
await Task.WhenAll(entities.Select(CreateEntityAsync));
|
/// <c>state</c>, <c>attributes</c>, <c>availability</c>, <c>set</c> and <c>config</c>.
|
||||||
}
|
/// The discovery config topic comes last: an empty retained payload on it is what removes the
|
||||||
|
/// entity from Home Assistant.
|
||||||
|
/// </summary>
|
||||||
|
private static readonly string[] CleanupTopicSuffixes = ["state", "attributes", "availability", "set", "config"];
|
||||||
|
|
||||||
public async Task CreateEntityAsync(EntityCreateModel createModel)
|
public async Task CreateEntityAsync(EntityCreateModel createModel)
|
||||||
{
|
{
|
||||||
@@ -29,8 +42,48 @@ public class EntityManager(IMqttEntityManager entityManager) : IEntityManager
|
|||||||
await entityManager.SetAttributesAsync(entityId, attributes);
|
await entityManager.SetAttributesAsync(entityId, attributes);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task RemoveEntity(string entityId)
|
/// <summary>
|
||||||
|
/// Removes the entity from Home Assistant and clears every retained MQTT message it owns at the broker.
|
||||||
|
/// <para>
|
||||||
|
/// <see cref="IMqttEntityManager.RemoveAsync" /> publishes the empty discovery payload without the
|
||||||
|
/// retain flag, so Home Assistant forgets the entity but the broker keeps the retained config and
|
||||||
|
/// re-discovers the entity after a Home Assistant restart or MQTT reload. Publishing an empty
|
||||||
|
/// retained payload through Home Assistant's <c>mqtt.publish</c> service clears the retained
|
||||||
|
/// messages and removes the entity for good.
|
||||||
|
/// </para>
|
||||||
|
/// </summary>
|
||||||
|
public Task RemoveEntity(string entityId)
|
||||||
{
|
{
|
||||||
await entityManager.RemoveAsync(entityId);
|
var rootTopic = BuildRootTopic(entityId, mqttConfiguration.Value.DiscoveryPrefix);
|
||||||
|
|
||||||
|
foreach (var suffix in CleanupTopicSuffixes)
|
||||||
|
{
|
||||||
|
haContext.CallService("mqtt", "publish", null, new MqttPublishParameters
|
||||||
|
{
|
||||||
|
Topic = $"{rootTopic}/{suffix}",
|
||||||
|
Payload = string.Empty,
|
||||||
|
Retain = true
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// IHaContext.CallService is fire-and-forget; the calls are queued in order on the HA websocket.
|
||||||
|
return Task.CompletedTask;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string BuildRootTopic(string entityId, string discoveryPrefix)
|
||||||
|
{
|
||||||
|
var separatorIndex = entityId.IndexOf('.');
|
||||||
|
|
||||||
|
if (separatorIndex <= 0 || separatorIndex == entityId.Length - 1)
|
||||||
|
{
|
||||||
|
throw new ArgumentException(
|
||||||
|
$"Entity id '{entityId}' is not in the 'domain.object_id' format.",
|
||||||
|
nameof(entityId));
|
||||||
|
}
|
||||||
|
|
||||||
|
var domain = entityId[..separatorIndex];
|
||||||
|
var objectId = entityId[(separatorIndex + 1)..];
|
||||||
|
|
||||||
|
return $"{discoveryPrefix}/{domain}/{objectId}";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -7,14 +7,14 @@
|
|||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="NetDaemon.AppModel" Version="26.11.0" />
|
<PackageReference Include="NetDaemon.AppModel" Version="26.43.1"/>
|
||||||
<PackageReference Include="NetDaemon.Extensions.Mqtt" Version="26.11.0" />
|
<PackageReference Include="NetDaemon.Extensions.Mqtt" Version="26.43.1"/>
|
||||||
<PackageReference Include="NetDaemon.Runtime" Version="26.11.0" />
|
<PackageReference Include="NetDaemon.Runtime" Version="26.43.1"/>
|
||||||
<PackageReference Include="NetDaemon.HassModel" Version="26.11.0" />
|
<PackageReference Include="NetDaemon.HassModel" Version="26.43.1"/>
|
||||||
<PackageReference Include="NetDaemon.Client" Version="26.11.0" />
|
<PackageReference Include="NetDaemon.Client" Version="26.43.1"/>
|
||||||
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.11.0" />
|
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.43.1"/>
|
||||||
<PackageReference Include="NetDaemon.Extensions.Logging" Version="26.11.0" />
|
<PackageReference Include="NetDaemon.Extensions.Logging" Version="26.43.1"/>
|
||||||
<PackageReference Include="NetDaemon.Extensions.Tts" Version="26.11.0" />
|
<PackageReference Include="NetDaemon.Extensions.Tts" Version="26.43.1"/>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
|||||||
@@ -1,10 +1,13 @@
|
|||||||
using HomeAssistant.Models;
|
#region
|
||||||
|
|
||||||
|
using HomeAssistant.Models;
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
namespace HomeAssistant.Entities.Interfaces;
|
namespace HomeAssistant.Entities.Interfaces;
|
||||||
|
|
||||||
public interface IEntityManager
|
public interface IEntityManager
|
||||||
{
|
{
|
||||||
Task CreateEntitiesAsync(ICollection<EntityCreateModel> entities);
|
|
||||||
Task CreateEntityAsync(EntityCreateModel createModel);
|
Task CreateEntityAsync(EntityCreateModel createModel);
|
||||||
Task SetEntityState(string entityId, string state);
|
Task SetEntityState(string entityId, string state);
|
||||||
Task SetEntityAttributes(string entityId, object attributes);
|
Task SetEntityAttributes(string entityId, object attributes);
|
||||||
|
|||||||
@@ -1,19 +0,0 @@
|
|||||||
<!DOCTYPE html>
|
|
||||||
<html lang="en" data-bs-theme="dark">
|
|
||||||
<head>
|
|
||||||
<meta charset="utf-8" />
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
||||||
<title>HA History Replay</title>
|
|
||||||
<base href="/" />
|
|
||||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" />
|
|
||||||
<link href="css/app.css" rel="stylesheet" />
|
|
||||||
<HeadOutlet @rendermode="InteractiveServer" />
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<Routes @rendermode="InteractiveServer" />
|
|
||||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
|
|
||||||
<script src="_framework/blazor.web.js"></script>
|
|
||||||
<script src="_content/Blazor-ApexCharts/js/apexcharts.esm.js" type="module"></script>
|
|
||||||
<script src="_content/Blazor-ApexCharts/js/blazor-apexcharts.js"></script>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
@@ -1,44 +0,0 @@
|
|||||||
@code {
|
|
||||||
[Parameter] public ReplayDataSeries? DataSeries { get; set; }
|
|
||||||
|
|
||||||
private List<ReplayDataPoint> PowerData => DataSeries?.GetSeries("Boiler", "PowerWatts").ToList() ?? [];
|
|
||||||
private List<ReplayDataPoint> BudgetData => DataSeries?.GetSeries("Boiler", "BudgetPercent").ToList() ?? [];
|
|
||||||
private List<ReplayDataPoint> SwitchData => DataSeries?.GetSeries("Boiler", "SwitchState").ToList() ?? [];
|
|
||||||
|
|
||||||
private ApexChartOptions<ReplayDataPoint> ChartOptions => new()
|
|
||||||
{
|
|
||||||
Chart = new Chart { Background = "transparent", ForeColor = "#adb5bd" },
|
|
||||||
Theme = new Theme { Mode = Mode.Dark },
|
|
||||||
Stroke = new Stroke { Width = 2 },
|
|
||||||
Xaxis = new XAxis { Type = XAxisType.Datetime },
|
|
||||||
Yaxis =
|
|
||||||
[
|
|
||||||
new YAxis { Title = new AxisTitle { Text = "Watts" }, SeriesName = "Power (W)", DecimalsInFloat = 0 },
|
|
||||||
new YAxis { Title = new AxisTitle { Text = "%" }, SeriesName = "Budget %", Opposite = true, Max = 100, DecimalsInFloat = 0 }
|
|
||||||
],
|
|
||||||
Tooltip = new Tooltip { X = new TooltipX { Format = "HH:mm" } },
|
|
||||||
Grid = new Grid { BorderColor = "#343a40" }
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
@if (PowerData.Count > 0)
|
|
||||||
{
|
|
||||||
<ApexChart TItem="ReplayDataPoint" Options="ChartOptions" Height="300">
|
|
||||||
<ApexPointSeries TItem="ReplayDataPoint"
|
|
||||||
Items="PowerData"
|
|
||||||
SeriesType="SeriesType.Area"
|
|
||||||
Name="Power (W)"
|
|
||||||
XValue="p => p.Timestamp.ToLocalTime().DateTime"
|
|
||||||
YValue="p => (decimal)p.Value" />
|
|
||||||
<ApexPointSeries TItem="ReplayDataPoint"
|
|
||||||
Items="BudgetData"
|
|
||||||
SeriesType="SeriesType.Line"
|
|
||||||
Name="Budget %"
|
|
||||||
XValue="p => p.Timestamp.ToLocalTime().DateTime"
|
|
||||||
YValue="p => (decimal)p.Value" />
|
|
||||||
</ApexChart>
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
<div class="text-muted text-center py-4">No boiler data available</div>
|
|
||||||
}
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
@code {
|
|
||||||
[Parameter] public ReplayTimeline? Timeline { get; set; }
|
|
||||||
|
|
||||||
private IReadOnlyList<ReplayEvent> LightEvents =>
|
|
||||||
Timeline?.GetEventsByMonitor("Light") ?? [];
|
|
||||||
}
|
|
||||||
|
|
||||||
<div class="card bg-dark">
|
|
||||||
<div class="card-body">
|
|
||||||
@if (LightEvents.Count > 0)
|
|
||||||
{
|
|
||||||
<div class="d-flex flex-column gap-2">
|
|
||||||
@foreach (var evt in LightEvents)
|
|
||||||
{
|
|
||||||
var iconClass = evt.EventType == ReplayEventType.Decision ? "text-warning" : "text-muted";
|
|
||||||
var icon = evt.EventType == ReplayEventType.Decision ? "☀" : "•";
|
|
||||||
<div class="d-flex align-items-start gap-2">
|
|
||||||
<span class="font-monospace small text-nowrap">@evt.Timestamp.ToLocalTime().ToString("HH:mm")</span>
|
|
||||||
<span class="@iconClass">@((MarkupString)icon)</span>
|
|
||||||
<span class="small">@evt.Message</span>
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
<div class="text-muted text-center py-4">No light events</div>
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
@code {
|
|
||||||
[Parameter] public ReplayDataSeries? DataSeries { get; set; }
|
|
||||||
|
|
||||||
private List<ReplayDataPoint> PriceData => DataSeries?.GetSeries("NordPool", "Price").ToList() ?? [];
|
|
||||||
|
|
||||||
private ApexChartOptions<ReplayDataPoint> ChartOptions => new()
|
|
||||||
{
|
|
||||||
Chart = new Chart { Background = "transparent", ForeColor = "#adb5bd" },
|
|
||||||
Theme = new Theme { Mode = Mode.Dark },
|
|
||||||
Stroke = new Stroke { Curve = Curve.Smooth, Width = 2 },
|
|
||||||
Xaxis = new XAxis { Type = XAxisType.Datetime },
|
|
||||||
Yaxis = [new YAxis { Title = new AxisTitle { Text = "ct/kWh" }, DecimalsInFloat = 2 }],
|
|
||||||
Tooltip = new Tooltip { X = new TooltipX { Format = "HH:mm" } },
|
|
||||||
Grid = new Grid { BorderColor = "#343a40" }
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
@if (PriceData.Count > 0)
|
|
||||||
{
|
|
||||||
<ApexChart TItem="ReplayDataPoint" Options="ChartOptions" Height="300">
|
|
||||||
<ApexPointSeries TItem="ReplayDataPoint"
|
|
||||||
Items="PriceData"
|
|
||||||
SeriesType="SeriesType.Area"
|
|
||||||
Name="Price (ct/kWh)"
|
|
||||||
XValue="p => p.Timestamp.ToLocalTime().DateTime"
|
|
||||||
YValue="p => (decimal)p.Value" />
|
|
||||||
</ApexChart>
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
<div class="text-muted text-center py-4">No price data available</div>
|
|
||||||
}
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
@code {
|
|
||||||
[Parameter] public ReplayDataSeries? DataSeries { get; set; }
|
|
||||||
|
|
||||||
private List<ReplayDataPoint> TotalData => DataSeries?.GetSeries("Power", "TotalPower").ToList() ?? [];
|
|
||||||
private List<ReplayDataPoint> KnownData => DataSeries?.GetSeries("Power", "KnownDevices").ToList() ?? [];
|
|
||||||
private List<ReplayDataPoint> OtherData => DataSeries?.GetSeries("Power", "OtherPower").ToList() ?? [];
|
|
||||||
|
|
||||||
private ApexChartOptions<ReplayDataPoint> ChartOptions => new()
|
|
||||||
{
|
|
||||||
Chart = new Chart { Background = "transparent", ForeColor = "#adb5bd", Stacked = true },
|
|
||||||
Theme = new Theme { Mode = Mode.Dark },
|
|
||||||
Stroke = new Stroke { Width = 1 },
|
|
||||||
Xaxis = new XAxis { Type = XAxisType.Datetime },
|
|
||||||
Yaxis = [new YAxis { Title = new AxisTitle { Text = "Watts" }, DecimalsInFloat = 0 }],
|
|
||||||
Tooltip = new Tooltip { X = new TooltipX { Format = "HH:mm:ss" } },
|
|
||||||
Grid = new Grid { BorderColor = "#343a40" }
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
@if (TotalData.Count > 0)
|
|
||||||
{
|
|
||||||
<ApexChart TItem="ReplayDataPoint" Options="ChartOptions" Height="300">
|
|
||||||
<ApexPointSeries TItem="ReplayDataPoint"
|
|
||||||
Items="KnownData"
|
|
||||||
SeriesType="SeriesType.Area"
|
|
||||||
Name="Known Devices"
|
|
||||||
XValue="p => p.Timestamp.ToLocalTime().DateTime"
|
|
||||||
YValue="p => (decimal)p.Value" />
|
|
||||||
<ApexPointSeries TItem="ReplayDataPoint"
|
|
||||||
Items="OtherData"
|
|
||||||
SeriesType="SeriesType.Area"
|
|
||||||
Name="Other Power"
|
|
||||||
XValue="p => p.Timestamp.ToLocalTime().DateTime"
|
|
||||||
YValue="p => (decimal)p.Value" />
|
|
||||||
</ApexChart>
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
<div class="text-muted text-center py-4">No power data available</div>
|
|
||||||
}
|
|
||||||
@@ -1,46 +0,0 @@
|
|||||||
@code {
|
|
||||||
[Parameter] public ReplayDataSeries? DataSeries { get; set; }
|
|
||||||
|
|
||||||
private List<ReplayDataPoint> BathroomData => DataSeries?.GetSeries("Shower", "BathroomHumidity").ToList() ?? [];
|
|
||||||
private List<ReplayDataPoint> HomeData => DataSeries?.GetSeries("Shower", "HomeHumidity").ToList() ?? [];
|
|
||||||
private List<ReplayDataPoint> DiffData => DataSeries?.GetSeries("Shower", "Differential").ToList() ?? [];
|
|
||||||
|
|
||||||
private ApexChartOptions<ReplayDataPoint> ChartOptions => new()
|
|
||||||
{
|
|
||||||
Chart = new Chart { Background = "transparent", ForeColor = "#adb5bd" },
|
|
||||||
Theme = new Theme { Mode = Mode.Dark },
|
|
||||||
Stroke = new Stroke { Curve = Curve.Smooth, Width = 2 },
|
|
||||||
Xaxis = new XAxis { Type = XAxisType.Datetime },
|
|
||||||
Yaxis = [new YAxis { Title = new AxisTitle { Text = "Humidity %" }, DecimalsInFloat = 1 }],
|
|
||||||
Tooltip = new Tooltip { X = new TooltipX { Format = "HH:mm" } },
|
|
||||||
Grid = new Grid { BorderColor = "#343a40" }
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
@if (BathroomData.Count > 0)
|
|
||||||
{
|
|
||||||
<ApexChart TItem="ReplayDataPoint" Options="ChartOptions" Height="300">
|
|
||||||
<ApexPointSeries TItem="ReplayDataPoint"
|
|
||||||
Items="BathroomData"
|
|
||||||
SeriesType="SeriesType.Line"
|
|
||||||
Name="Bathroom Humidity"
|
|
||||||
XValue="p => p.Timestamp.ToLocalTime().DateTime"
|
|
||||||
YValue="p => (decimal)p.Value" />
|
|
||||||
<ApexPointSeries TItem="ReplayDataPoint"
|
|
||||||
Items="HomeData"
|
|
||||||
SeriesType="SeriesType.Line"
|
|
||||||
Name="Home Humidity"
|
|
||||||
XValue="p => p.Timestamp.ToLocalTime().DateTime"
|
|
||||||
YValue="p => (decimal)p.Value" />
|
|
||||||
<ApexPointSeries TItem="ReplayDataPoint"
|
|
||||||
Items="DiffData"
|
|
||||||
SeriesType="SeriesType.Area"
|
|
||||||
Name="Differential"
|
|
||||||
XValue="p => p.Timestamp.ToLocalTime().DateTime"
|
|
||||||
YValue="p => (decimal)p.Value" />
|
|
||||||
</ApexChart>
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
<div class="text-muted text-center py-4">No shower data available</div>
|
|
||||||
}
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
@inherits LayoutComponentBase
|
|
||||||
|
|
||||||
<div class="d-flex flex-column min-vh-100">
|
|
||||||
<nav class="navbar navbar-dark bg-dark border-bottom border-secondary px-3">
|
|
||||||
<span class="navbar-brand mb-0 h1">
|
|
||||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" class="bi bi-house-door me-2" viewBox="0 0 16 16">
|
|
||||||
<path d="M8.354 1.146a.5.5 0 0 0-.708 0l-6 6A.5.5 0 0 0 1.5 7.5v7a.5.5 0 0 0 .5.5h4.5a.5.5 0 0 0 .5-.5v-4h2v4a.5.5 0 0 0 .5.5H14a.5.5 0 0 0 .5-.5v-7a.5.5 0 0 0-.146-.354L13 5.793V2.5a.5.5 0 0 0-.5-.5h-1a.5.5 0 0 0-.5.5v1.293zM2.5 14V7.707l5.5-5.5 5.5 5.5V14H10v-4a.5.5 0 0 0-.5-.5h-3a.5.5 0 0 0-.5.5v4z"/>
|
|
||||||
</svg>
|
|
||||||
HA History Replay
|
|
||||||
</span>
|
|
||||||
<span class="text-muted small">Debug Dashboard</span>
|
|
||||||
</nav>
|
|
||||||
|
|
||||||
<main class="flex-grow-1 p-3">
|
|
||||||
@Body
|
|
||||||
</main>
|
|
||||||
</div>
|
|
||||||
@@ -1,240 +0,0 @@
|
|||||||
@page "/"
|
|
||||||
@inject ReplayOrchestrationService Replay
|
|
||||||
@implements IDisposable
|
|
||||||
|
|
||||||
<h4 class="mb-3">History Replay Dashboard</h4>
|
|
||||||
|
|
||||||
<div class="card mb-3">
|
|
||||||
<div class="card-body">
|
|
||||||
<div class="row g-3 align-items-end">
|
|
||||||
<div class="col-md-3">
|
|
||||||
<label class="form-label small">Start Time</label>
|
|
||||||
<input type="datetime-local" class="form-control form-control-sm"
|
|
||||||
@bind="_startTime" />
|
|
||||||
</div>
|
|
||||||
<div class="col-md-3">
|
|
||||||
<label class="form-label small">End Time</label>
|
|
||||||
<input type="datetime-local" class="form-control form-control-sm"
|
|
||||||
@bind="_endTime" />
|
|
||||||
</div>
|
|
||||||
<div class="col-md-4">
|
|
||||||
<label class="form-label small">Monitors</label>
|
|
||||||
<div class="d-flex gap-3 flex-wrap">
|
|
||||||
<div class="form-check form-check-inline">
|
|
||||||
<input class="form-check-input" type="checkbox" @bind="_monitors.NordPool" id="chkNord" />
|
|
||||||
<label class="form-check-label small" for="chkNord">NordPool</label>
|
|
||||||
</div>
|
|
||||||
<div class="form-check form-check-inline">
|
|
||||||
<input class="form-check-input" type="checkbox" @bind="_monitors.Boiler" id="chkBoiler" />
|
|
||||||
<label class="form-check-label small" for="chkBoiler">Boiler</label>
|
|
||||||
</div>
|
|
||||||
<div class="form-check form-check-inline">
|
|
||||||
<input class="form-check-input" type="checkbox" @bind="_monitors.Shower" id="chkShower" />
|
|
||||||
<label class="form-check-label small" for="chkShower">Shower</label>
|
|
||||||
</div>
|
|
||||||
<div class="form-check form-check-inline">
|
|
||||||
<input class="form-check-input" type="checkbox" @bind="_monitors.Power" id="chkPower" />
|
|
||||||
<label class="form-check-label small" for="chkPower">Power</label>
|
|
||||||
</div>
|
|
||||||
<div class="form-check form-check-inline">
|
|
||||||
<input class="form-check-input" type="checkbox" @bind="_monitors.Light" id="chkLight" />
|
|
||||||
<label class="form-check-label small" for="chkLight">Light</label>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="col-md-2">
|
|
||||||
<button class="btn btn-primary w-100" @onclick="RunReplay"
|
|
||||||
disabled="@(_isRunning)">
|
|
||||||
@if (_isRunning)
|
|
||||||
{
|
|
||||||
<span class="spinner-border spinner-border-sm me-1" role="status"></span>
|
|
||||||
}
|
|
||||||
Run Replay
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="status-bar mb-3">
|
|
||||||
@switch (Replay.Status)
|
|
||||||
{
|
|
||||||
case ReplayStatus.FetchingHistory:
|
|
||||||
<div class="alert alert-info py-2 mb-0 d-flex align-items-center">
|
|
||||||
<span class="spinner-border spinner-border-sm me-2"></span>
|
|
||||||
@(Replay.ProgressMessage ?? "Fetching history data from Home Assistant...")
|
|
||||||
</div>
|
|
||||||
break;
|
|
||||||
case ReplayStatus.Running:
|
|
||||||
<div class="alert alert-info py-2 mb-0 d-flex align-items-center">
|
|
||||||
<span class="spinner-border spinner-border-sm me-2"></span>
|
|
||||||
@(Replay.ProgressMessage ?? "Running replay...")
|
|
||||||
</div>
|
|
||||||
break;
|
|
||||||
case ReplayStatus.Completed:
|
|
||||||
<div class="alert alert-success py-2 mb-0">
|
|
||||||
Replay completed -- @Replay.Timeline.GetAllEvents().Count event(s)
|
|
||||||
</div>
|
|
||||||
break;
|
|
||||||
case ReplayStatus.Failed:
|
|
||||||
<div class="alert alert-danger py-2 mb-0">
|
|
||||||
Replay failed: @Replay.ErrorMessage
|
|
||||||
</div>
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
@if (Replay.Status == ReplayStatus.Completed)
|
|
||||||
{
|
|
||||||
<SummaryCards Timeline="Replay.Timeline" />
|
|
||||||
|
|
||||||
<ul class="nav nav-tabs mb-3" role="tablist">
|
|
||||||
@foreach (var monitor in _enabledMonitors)
|
|
||||||
{
|
|
||||||
var tab = monitor;
|
|
||||||
<li class="nav-item" role="presentation">
|
|
||||||
<button class="nav-link @(tab == _activeTab ? "active" : "")"
|
|
||||||
@onclick="() => SetActiveTab(tab)">
|
|
||||||
@tab
|
|
||||||
</button>
|
|
||||||
</li>
|
|
||||||
}
|
|
||||||
<li class="nav-item" role="presentation">
|
|
||||||
<button class="nav-link @(_activeTab == ServiceCallsTab ? "active" : "")"
|
|
||||||
@onclick="() => SetActiveTab(ServiceCallsTab)">
|
|
||||||
Service Calls
|
|
||||||
</button>
|
|
||||||
</li>
|
|
||||||
</ul>
|
|
||||||
|
|
||||||
<div class="tab-content">
|
|
||||||
@if (_activeTab == NordPoolTab)
|
|
||||||
{
|
|
||||||
<div class="card mb-3">
|
|
||||||
<div class="card-header">NordPool Price Timeline</div>
|
|
||||||
<div class="card-body"><NordPoolChart DataSeries="Replay.DataSeries" /></div>
|
|
||||||
</div>
|
|
||||||
<EventTable Events="GetMonitorEvents(NordPoolTab)" />
|
|
||||||
}
|
|
||||||
else if (_activeTab == BoilerTab)
|
|
||||||
{
|
|
||||||
<div class="card mb-3">
|
|
||||||
<div class="card-header">Boiler Power and Budget</div>
|
|
||||||
<div class="card-body"><BoilerChart DataSeries="Replay.DataSeries" /></div>
|
|
||||||
</div>
|
|
||||||
<EventTable Events="GetMonitorEvents(BoilerTab)" />
|
|
||||||
}
|
|
||||||
else if (_activeTab == ShowerTab)
|
|
||||||
{
|
|
||||||
<div class="card mb-3">
|
|
||||||
<div class="card-header">Humidity and Shower Detection</div>
|
|
||||||
<div class="card-body"><ShowerChart DataSeries="Replay.DataSeries" /></div>
|
|
||||||
</div>
|
|
||||||
<EventTable Events="GetMonitorEvents(ShowerTab)" />
|
|
||||||
}
|
|
||||||
else if (_activeTab == PowerTab)
|
|
||||||
{
|
|
||||||
<div class="card mb-3">
|
|
||||||
<div class="card-header">Power Breakdown</div>
|
|
||||||
<div class="card-body"><PowerChart DataSeries="Replay.DataSeries" /></div>
|
|
||||||
</div>
|
|
||||||
<EventTable Events="GetMonitorEvents(PowerTab)" />
|
|
||||||
}
|
|
||||||
else if (_activeTab == LightTab)
|
|
||||||
{
|
|
||||||
<div class="card mb-3">
|
|
||||||
<div class="card-header">Light Control Events</div>
|
|
||||||
<div class="card-body"><LightChart Timeline="Replay.Timeline" /></div>
|
|
||||||
</div>
|
|
||||||
<EventTable Events="GetMonitorEvents(LightTab)" />
|
|
||||||
}
|
|
||||||
else if (_activeTab == ServiceCallsTab)
|
|
||||||
{
|
|
||||||
<EventTable Events="GetMonitorEvents(ServiceCallMonitor)" />
|
|
||||||
}
|
|
||||||
</div>
|
|
||||||
}
|
|
||||||
|
|
||||||
@code {
|
|
||||||
private const string NordPoolTab = "NordPool";
|
|
||||||
private const string BoilerTab = "Boiler";
|
|
||||||
private const string ShowerTab = "Shower";
|
|
||||||
private const string PowerTab = "Power";
|
|
||||||
private const string LightTab = "Light";
|
|
||||||
private const string ServiceCallsTab = "ServiceCalls";
|
|
||||||
private const string ServiceCallMonitor = "ServiceCall";
|
|
||||||
|
|
||||||
private DateTime _startTime = DateTime.Today.AddDays(-1);
|
|
||||||
private DateTime _endTime = DateTime.Today.AddHours(23).AddMinutes(59);
|
|
||||||
private readonly ReplayMonitorFlags _monitors = new();
|
|
||||||
private bool _isRunning;
|
|
||||||
private string _activeTab = NordPoolTab;
|
|
||||||
private IReadOnlyList<string> _enabledMonitors = [];
|
|
||||||
|
|
||||||
protected override void OnInitialized()
|
|
||||||
{
|
|
||||||
Replay.OnStateChanged += HandleStateChanged;
|
|
||||||
}
|
|
||||||
|
|
||||||
private IReadOnlyList<ReplayEvent> GetMonitorEvents(string monitor) =>
|
|
||||||
Replay.Timeline.GetEventsByMonitor(monitor);
|
|
||||||
|
|
||||||
private void SetActiveTab(string tab)
|
|
||||||
{
|
|
||||||
_activeTab = tab;
|
|
||||||
StateHasChanged();
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task RunReplay()
|
|
||||||
{
|
|
||||||
_isRunning = true;
|
|
||||||
_enabledMonitors = BuildEnabledMonitors();
|
|
||||||
_activeTab = _enabledMonitors.FirstOrDefault() ?? NordPoolTab;
|
|
||||||
|
|
||||||
var start = new DateTimeOffset(_startTime, TimeZoneInfo.Local.GetUtcOffset(_startTime));
|
|
||||||
var end = new DateTimeOffset(_endTime, TimeZoneInfo.Local.GetUtcOffset(_endTime));
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
await Task.Run(async () =>
|
|
||||||
await Replay.RunReplayAsync(start, end, _monitors));
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
Replay.SetError(ex.Message);
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
_isRunning = false;
|
|
||||||
await InvokeAsync(StateHasChanged);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private IReadOnlyList<string> BuildEnabledMonitors()
|
|
||||||
{
|
|
||||||
var list = new List<string>();
|
|
||||||
if (_monitors.NordPool) list.Add(NordPoolTab);
|
|
||||||
if (_monitors.Boiler) list.Add(BoilerTab);
|
|
||||||
if (_monitors.Shower) list.Add(ShowerTab);
|
|
||||||
if (_monitors.Power) list.Add(PowerTab);
|
|
||||||
if (_monitors.Light) list.Add(LightTab);
|
|
||||||
return list;
|
|
||||||
}
|
|
||||||
|
|
||||||
private async void HandleStateChanged()
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
await InvokeAsync(StateHasChanged);
|
|
||||||
}
|
|
||||||
catch (ObjectDisposedException)
|
|
||||||
{
|
|
||||||
// Component was disposed while an update was in flight
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Dispose()
|
|
||||||
{
|
|
||||||
Replay.OnStateChanged -= HandleStateChanged;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
<Router AppAssembly="typeof(Program).Assembly">
|
|
||||||
<Found Context="routeData">
|
|
||||||
<RouteView RouteData="routeData" DefaultLayout="typeof(Layout.MainLayout)" />
|
|
||||||
<FocusOnNavigate RouteData="routeData" Selector="h1" />
|
|
||||||
</Found>
|
|
||||||
</Router>
|
|
||||||
@@ -1,54 +0,0 @@
|
|||||||
@code {
|
|
||||||
[Parameter] public IReadOnlyList<ReplayEvent> Events { get; set; } = [];
|
|
||||||
[Parameter] public int MaxRows { get; set; } = 200;
|
|
||||||
|
|
||||||
private string GetBadgeClass(ReplayEventType type) => type switch
|
|
||||||
{
|
|
||||||
ReplayEventType.Decision => "badge-decision",
|
|
||||||
ReplayEventType.StateChange => "badge-statechange",
|
|
||||||
ReplayEventType.Warning => "badge-warning",
|
|
||||||
ReplayEventType.Anomaly => "badge-anomaly",
|
|
||||||
ReplayEventType.ServiceCall => "badge-servicecall",
|
|
||||||
_ => "badge-info"
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
@if (Events.Count == 0)
|
|
||||||
{
|
|
||||||
<div class="text-muted text-center py-4">No events recorded for this monitor.</div>
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
<div class="table-responsive" style="max-height: 400px; overflow-y: auto;">
|
|
||||||
<table class="table table-sm table-hover align-middle mb-0">
|
|
||||||
<thead class="sticky-top" style="background-color: #2b3035;">
|
|
||||||
<tr>
|
|
||||||
<th style="width: 100px;">Time</th>
|
|
||||||
<th style="width: 100px;">Type</th>
|
|
||||||
<th>Message</th>
|
|
||||||
<th>Details</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
@foreach (var evt in Events.Take(MaxRows))
|
|
||||||
{
|
|
||||||
<tr>
|
|
||||||
<td class="text-nowrap font-monospace small">
|
|
||||||
@evt.Timestamp.ToLocalTime().ToString("HH:mm:ss")
|
|
||||||
</td>
|
|
||||||
<td>
|
|
||||||
<span class="badge @GetBadgeClass(evt.EventType)">@evt.EventType</span>
|
|
||||||
</td>
|
|
||||||
<td class="small">@evt.Message</td>
|
|
||||||
<td class="text-muted small">@evt.Details</td>
|
|
||||||
</tr>
|
|
||||||
}
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
@if (Events.Count > MaxRows)
|
|
||||||
{
|
|
||||||
<div class="text-muted small mt-1">Showing @MaxRows of @Events.Count events</div>
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,53 +0,0 @@
|
|||||||
@code {
|
|
||||||
[Parameter] public ReplayTimeline? Timeline { get; set; }
|
|
||||||
|
|
||||||
private IReadOnlyList<ReplayEvent> AllEvents => Timeline?.GetAllEvents() ?? [];
|
|
||||||
private int TotalEvents => AllEvents.Count;
|
|
||||||
private int Decisions => AllEvents.Count(e => e.EventType == ReplayEventType.Decision);
|
|
||||||
private int ServiceCalls => AllEvents.Count(e => e.EventType == ReplayEventType.ServiceCall);
|
|
||||||
private int Warnings => AllEvents.Count(e => e.EventType == ReplayEventType.Warning);
|
|
||||||
private int Anomalies => AllEvents.Count(e => e.EventType == ReplayEventType.Anomaly);
|
|
||||||
}
|
|
||||||
|
|
||||||
<div class="row g-3 mb-4">
|
|
||||||
<div class="col">
|
|
||||||
<div class="card stat-card">
|
|
||||||
<div class="card-body">
|
|
||||||
<div class="display-6">@TotalEvents</div>
|
|
||||||
<div class="text-muted small">Total Events</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="col">
|
|
||||||
<div class="card stat-card border-success">
|
|
||||||
<div class="card-body">
|
|
||||||
<div class="display-6 text-success">@Decisions</div>
|
|
||||||
<div class="text-muted small">Decisions</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="col">
|
|
||||||
<div class="card stat-card border-info">
|
|
||||||
<div class="card-body">
|
|
||||||
<div class="display-6 text-info">@ServiceCalls</div>
|
|
||||||
<div class="text-muted small">Service Calls</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="col">
|
|
||||||
<div class="card stat-card border-warning">
|
|
||||||
<div class="card-body">
|
|
||||||
<div class="display-6 text-warning">@Warnings</div>
|
|
||||||
<div class="text-muted small">Warnings</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="col">
|
|
||||||
<div class="card stat-card border-danger">
|
|
||||||
<div class="card-body">
|
|
||||||
<div class="display-6 text-danger">@Anomalies</div>
|
|
||||||
<div class="text-muted small">Anomalies</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
@using System.Net.Http
|
|
||||||
@using Microsoft.AspNetCore.Components.Forms
|
|
||||||
@using Microsoft.AspNetCore.Components.Routing
|
|
||||||
@using Microsoft.AspNetCore.Components.Web
|
|
||||||
@using static Microsoft.AspNetCore.Components.Web.RenderMode
|
|
||||||
@using Microsoft.AspNetCore.Components.Web.Virtualization
|
|
||||||
@using Microsoft.JSInterop
|
|
||||||
@using ApexCharts
|
|
||||||
@using HomeAssistant.HistoryReplay.Components
|
|
||||||
@using HomeAssistant.HistoryReplay.Components.Layout
|
|
||||||
@using HomeAssistant.HistoryReplay.Components.Shared
|
|
||||||
@using HomeAssistant.HistoryReplay.Components.Charts
|
|
||||||
@using HomeAssistant.HistoryReplay.Reporting
|
|
||||||
@using HomeAssistant.HistoryReplay.Services
|
|
||||||
@using HomeAssistant.HistoryReplay.Configuration
|
|
||||||
@@ -1,109 +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.AutoManagementEntityId,
|
|
||||||
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> GetEntitiesRequiringAttributes() =>
|
|
||||||
[
|
|
||||||
"sensor.nordpool_cheapest_intervals"
|
|
||||||
];
|
|
||||||
|
|
||||||
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];
|
|
||||||
}
|
|
||||||
|
|
||||||
public static (IReadOnlyList<string> MinimalEntities, IReadOnlyList<string> FullEntities) GetPartitionedEntities(
|
|
||||||
string boilerPowerEntityId,
|
|
||||||
string boilerSwitchEntityId,
|
|
||||||
string bathroomHumidityEntityId,
|
|
||||||
string mainHomeHumidityEntityId,
|
|
||||||
string mainMeterEntityId,
|
|
||||||
string sunEntityId,
|
|
||||||
string lightEntityId,
|
|
||||||
string[] personEntityIds)
|
|
||||||
{
|
|
||||||
var allEntities = GetAllEntities(
|
|
||||||
boilerPowerEntityId, boilerSwitchEntityId,
|
|
||||||
bathroomHumidityEntityId, mainHomeHumidityEntityId,
|
|
||||||
mainMeterEntityId, sunEntityId, lightEntityId, personEntityIds);
|
|
||||||
|
|
||||||
var fullSet = new HashSet<string>(GetEntitiesRequiringAttributes(), StringComparer.OrdinalIgnoreCase);
|
|
||||||
var minimal = new List<string>();
|
|
||||||
var full = new List<string>();
|
|
||||||
|
|
||||||
foreach (var entity in allEntities)
|
|
||||||
{
|
|
||||||
if (fullSet.Contains(entity))
|
|
||||||
{
|
|
||||||
full.Add(entity);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
minimal.Add(entity);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return (minimal, full);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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,118 +0,0 @@
|
|||||||
namespace HomeAssistant.HistoryReplay.HistoryData;
|
|
||||||
|
|
||||||
public sealed class HistoryTimeline
|
|
||||||
{
|
|
||||||
private readonly Dictionary<string, List<HistoryStateEntry>> _entityTimelines = new(StringComparer.OrdinalIgnoreCase);
|
|
||||||
private bool _sorted;
|
|
||||||
|
|
||||||
public void AddEntries(string entityId, IEnumerable<HistoryStateEntry> entries)
|
|
||||||
{
|
|
||||||
if (!_entityTimelines.TryGetValue(entityId, out var list))
|
|
||||||
{
|
|
||||||
list = [];
|
|
||||||
_entityTimelines[entityId] = list;
|
|
||||||
}
|
|
||||||
|
|
||||||
list.AddRange(entries);
|
|
||||||
_sorted = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void AddEntriesBulk(string entityId, List<HistoryStateEntry> entries)
|
|
||||||
{
|
|
||||||
if (entries.Count == 0)
|
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!_entityTimelines.TryGetValue(entityId, out var list))
|
|
||||||
{
|
|
||||||
_entityTimelines[entityId] = entries;
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
list.AddRange(entries);
|
|
||||||
}
|
|
||||||
|
|
||||||
_sorted = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void FinalizeSort()
|
|
||||||
{
|
|
||||||
if (_sorted)
|
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
foreach (var entries in _entityTimelines.Values)
|
|
||||||
{
|
|
||||||
entries.Sort((a, b) => a.LastChanged.CompareTo(b.LastChanged));
|
|
||||||
}
|
|
||||||
|
|
||||||
_sorted = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
public HistoryStateEntry? GetStateAt(string entityId, DateTimeOffset timestamp)
|
|
||||||
{
|
|
||||||
if (!_entityTimelines.TryGetValue(entityId, out var entries) || entries.Count == 0)
|
|
||||||
{
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
var index = BinarySearchFloor(entries, timestamp);
|
|
||||||
return index >= 0 ? entries[index] : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
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);
|
|
||||||
|
|
||||||
public void Clear()
|
|
||||||
{
|
|
||||||
_entityTimelines.Clear();
|
|
||||||
_sorted = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static int BinarySearchFloor(List<HistoryStateEntry> entries, DateTimeOffset timestamp)
|
|
||||||
{
|
|
||||||
var lo = 0;
|
|
||||||
var hi = entries.Count - 1;
|
|
||||||
var result = -1;
|
|
||||||
|
|
||||||
while (lo <= hi)
|
|
||||||
{
|
|
||||||
var mid = lo + (hi - lo) / 2;
|
|
||||||
|
|
||||||
if (entries[mid].LastChanged <= timestamp)
|
|
||||||
{
|
|
||||||
result = mid;
|
|
||||||
lo = mid + 1;
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
hi = mid - 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,347 +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 MaxEntitiesPerBatch = 5;
|
|
||||||
private const int MaxConcurrentRequests = 20;
|
|
||||||
private const int MaxRetryAttempts = 3;
|
|
||||||
private static readonly TimeSpan InitialRetryDelay = TimeSpan.FromSeconds(2);
|
|
||||||
|
|
||||||
public Task<HistoryTimeline> FetchHistoryAsync(
|
|
||||||
IReadOnlyList<string> entityIds,
|
|
||||||
DateTimeOffset startTime,
|
|
||||||
DateTimeOffset endTime,
|
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
return FetchHistoryAsync(
|
|
||||||
minimalEntityIds: entityIds,
|
|
||||||
fullEntityIds: [],
|
|
||||||
startTime, endTime, cancellationToken);
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task<HistoryTimeline> FetchHistoryAsync(
|
|
||||||
IReadOnlyList<string> minimalEntityIds,
|
|
||||||
IReadOnlyList<string> fullEntityIds,
|
|
||||||
DateTimeOffset startTime,
|
|
||||||
DateTimeOffset endTime,
|
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
var timeline = new HistoryTimeline();
|
|
||||||
var allEntityCount = minimalEntityIds.Count + fullEntityIds.Count;
|
|
||||||
|
|
||||||
var minimalBatches = ChunkEntities(minimalEntityIds, MaxEntitiesPerBatch);
|
|
||||||
var fullBatches = ChunkEntities(fullEntityIds, MaxEntitiesPerBatch);
|
|
||||||
|
|
||||||
logger.LogInformation(
|
|
||||||
"Fetching history in {MinBatchCount}+{FullBatchCount} batch(es) for {MinCount} minimal + {FullCount} full entities",
|
|
||||||
minimalBatches.Count, fullBatches.Count, minimalEntityIds.Count, fullEntityIds.Count);
|
|
||||||
|
|
||||||
var failedEntities = new List<string>();
|
|
||||||
using var semaphore = new SemaphoreSlim(MaxConcurrentRequests);
|
|
||||||
|
|
||||||
var minimalTasks = minimalBatches.Select(batch => FetchBatchThrottledAsync(
|
|
||||||
batch, startTime, endTime, minimalResponse: true, semaphore, cancellationToken));
|
|
||||||
|
|
||||||
var fullTasks = fullBatches.Select(batch => FetchBatchThrottledAsync(
|
|
||||||
batch, startTime, endTime, minimalResponse: false, semaphore, cancellationToken));
|
|
||||||
|
|
||||||
var results = await Task.WhenAll(minimalTasks.Concat(fullTasks)).ConfigureAwait(false);
|
|
||||||
|
|
||||||
foreach (var batchResult in results)
|
|
||||||
{
|
|
||||||
foreach (var (entityId, entries) in batchResult.Entries)
|
|
||||||
{
|
|
||||||
timeline.AddEntriesBulk(entityId, entries);
|
|
||||||
}
|
|
||||||
|
|
||||||
failedEntities.AddRange(batchResult.FailedEntityIds);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (failedEntities.Count > 0)
|
|
||||||
{
|
|
||||||
logger.LogWarning("Retrying {Count} failed entities individually: {Entities}", failedEntities.Count, string.Join(", ", failedEntities));
|
|
||||||
|
|
||||||
var individualResults = await FetchEntitiesIndividuallyAsync(failedEntities, startTime, endTime, cancellationToken);
|
|
||||||
|
|
||||||
foreach (var (entityId, entries) in individualResults)
|
|
||||||
{
|
|
||||||
timeline.AddEntriesBulk(entityId, entries);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
timeline.FinalizeSort();
|
|
||||||
|
|
||||||
logger.LogInformation(
|
|
||||||
"Fetched history for {EntityCount} entities: {EntryCount} total entries ({Start} to {End})",
|
|
||||||
allEntityCount, timeline.TotalEntryCount, startTime, endTime);
|
|
||||||
|
|
||||||
return timeline;
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task<BatchFetchResult> FetchBatchThrottledAsync(
|
|
||||||
IReadOnlyList<string> batch,
|
|
||||||
DateTimeOffset startTime,
|
|
||||||
DateTimeOffset endTime,
|
|
||||||
bool minimalResponse,
|
|
||||||
SemaphoreSlim semaphore,
|
|
||||||
CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
await semaphore.WaitAsync(cancellationToken);
|
|
||||||
try
|
|
||||||
{
|
|
||||||
return await FetchBatchWithRetryAsync(batch, startTime, endTime, minimalResponse, cancellationToken);
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
semaphore.Release();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task<BatchFetchResult> FetchBatchWithRetryAsync(
|
|
||||||
IReadOnlyList<string> entityIds,
|
|
||||||
DateTimeOffset startTime,
|
|
||||||
DateTimeOffset endTime,
|
|
||||||
bool minimalResponse,
|
|
||||||
CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
var entityIdsString = string.Join(",", entityIds);
|
|
||||||
|
|
||||||
for (var attempt = 1; attempt <= MaxRetryAttempts; attempt++)
|
|
||||||
{
|
|
||||||
logger.LogDebug("Fetching history batch (attempt {Attempt}/{MaxAttempts}, minimal={Minimal}) for: {Entities}",
|
|
||||||
attempt, MaxRetryAttempts, minimalResponse, entityIdsString);
|
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var response = await client.GetHistoryAsync(
|
|
||||||
entityIdsString, startTime, endTime, minimalResponse, cancellationToken)
|
|
||||||
.ConfigureAwait(false);
|
|
||||||
|
|
||||||
var entries = new List<(string, List<HistoryStateEntry>)>();
|
|
||||||
ParseHistoryResponse(response, entries);
|
|
||||||
return new BatchFetchResult(entries, []);
|
|
||||||
}
|
|
||||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
|
||||||
{
|
|
||||||
throw;
|
|
||||||
}
|
|
||||||
catch (Exception ex) when (IsTransientFailure(ex) && attempt < MaxRetryAttempts)
|
|
||||||
{
|
|
||||||
var delay = InitialRetryDelay * Math.Pow(2, attempt - 1);
|
|
||||||
logger.LogWarning(ex,
|
|
||||||
"Transient failure fetching batch (attempt {Attempt}/{MaxAttempts}), retrying in {Delay}s: {Entities}",
|
|
||||||
attempt, MaxRetryAttempts, delay.TotalSeconds, entityIdsString);
|
|
||||||
await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
logger.LogError(ex,
|
|
||||||
"Failed to fetch history batch after {Attempt} attempt(s): {Entities}",
|
|
||||||
attempt, entityIdsString);
|
|
||||||
return new BatchFetchResult([], entityIds.ToList());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return new BatchFetchResult([], entityIds.ToList());
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task<List<(string EntityId, List<HistoryStateEntry> Entries)>> FetchEntitiesIndividuallyAsync(
|
|
||||||
IReadOnlyList<string> entityIds,
|
|
||||||
DateTimeOffset startTime,
|
|
||||||
DateTimeOffset endTime,
|
|
||||||
CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
var allEntries = new List<(string, List<HistoryStateEntry>)>();
|
|
||||||
using var semaphore = new SemaphoreSlim(MaxConcurrentRequests);
|
|
||||||
|
|
||||||
var tasks = entityIds.Select(async entityId =>
|
|
||||||
{
|
|
||||||
await semaphore.WaitAsync(cancellationToken);
|
|
||||||
try
|
|
||||||
{
|
|
||||||
return await FetchSingleEntityWithRetryAsync(entityId, startTime, endTime, cancellationToken);
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
semaphore.Release();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
var results = await Task.WhenAll(tasks).ConfigureAwait(false);
|
|
||||||
|
|
||||||
foreach (var result in results)
|
|
||||||
{
|
|
||||||
allEntries.AddRange(result);
|
|
||||||
}
|
|
||||||
|
|
||||||
return allEntries;
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task<List<(string EntityId, List<HistoryStateEntry> Entries)>> FetchSingleEntityWithRetryAsync(
|
|
||||||
string entityId,
|
|
||||||
DateTimeOffset startTime,
|
|
||||||
DateTimeOffset endTime,
|
|
||||||
CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
for (var attempt = 1; attempt <= MaxRetryAttempts; attempt++)
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var response = await client.GetHistoryAsync(
|
|
||||||
entityId, startTime, endTime, minimalResponse: false, cancellationToken)
|
|
||||||
.ConfigureAwait(false);
|
|
||||||
|
|
||||||
var entries = new List<(string, List<HistoryStateEntry>)>();
|
|
||||||
ParseHistoryResponse(response, entries);
|
|
||||||
return entries;
|
|
||||||
}
|
|
||||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
|
||||||
{
|
|
||||||
throw;
|
|
||||||
}
|
|
||||||
catch (Exception ex) when (IsTransientFailure(ex) && attempt < MaxRetryAttempts)
|
|
||||||
{
|
|
||||||
var delay = InitialRetryDelay * Math.Pow(2, attempt - 1);
|
|
||||||
logger.LogWarning(ex,
|
|
||||||
"Transient failure fetching {EntityId} (attempt {Attempt}/{MaxAttempts}), retrying in {Delay}s",
|
|
||||||
entityId, attempt, MaxRetryAttempts, delay.TotalSeconds);
|
|
||||||
await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
logger.LogError(ex,
|
|
||||||
"Failed to fetch history for entity {EntityId} after {Attempt} attempt(s)",
|
|
||||||
entityId, attempt);
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
private static bool IsTransientFailure(Exception ex) =>
|
|
||||||
ex is HttpRequestException or TaskCanceledException or TimeoutException
|
|
||||||
or IOException;
|
|
||||||
|
|
||||||
private static void ParseHistoryResponse(
|
|
||||||
JsonElement response,
|
|
||||||
List<(string EntityId, List<HistoryStateEntry> Entries)> result)
|
|
||||||
{
|
|
||||||
if (response.ValueKind != JsonValueKind.Array)
|
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
foreach (var entityArray in response.EnumerateArray())
|
|
||||||
{
|
|
||||||
if (entityArray.ValueKind != JsonValueKind.Array)
|
|
||||||
{
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
string? currentEntityId = null;
|
|
||||||
var entries = new List<HistoryStateEntry>();
|
|
||||||
|
|
||||||
foreach (var stateObj in entityArray.EnumerateArray())
|
|
||||||
{
|
|
||||||
var entry = ParseStateEntry(stateObj, currentEntityId);
|
|
||||||
if (entry is null)
|
|
||||||
{
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
currentEntityId ??= entry.EntityId;
|
|
||||||
entries.Add(entry);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (currentEntityId is not null && entries.Count > 0)
|
|
||||||
{
|
|
||||||
result.Add((currentEntityId, entries));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static HistoryStateEntry? ParseStateEntry(JsonElement stateObj, string? fallbackEntityId)
|
|
||||||
{
|
|
||||||
string? entityId = null;
|
|
||||||
if (stateObj.TryGetProperty("entity_id", out var entityIdProp))
|
|
||||||
{
|
|
||||||
entityId = entityIdProp.GetString();
|
|
||||||
}
|
|
||||||
|
|
||||||
entityId ??= fallbackEntityId;
|
|
||||||
if (string.IsNullOrEmpty(entityId))
|
|
||||||
{
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
var state = stateObj.TryGetProperty("state", out var stateProp) ? stateProp.GetString() : null;
|
|
||||||
|
|
||||||
if (!stateObj.TryGetProperty("last_changed", out var lastChangedProp))
|
|
||||||
{
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!DateTimeOffset.TryParse(lastChangedProp.GetString(), CultureInfo.InvariantCulture,
|
|
||||||
DateTimeStyles.RoundtripKind, out var lastChanged))
|
|
||||||
{
|
|
||||||
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)
|
|
||||||
{
|
|
||||||
chunks.Add(entities.Skip(i).Take(chunkSize).ToList());
|
|
||||||
}
|
|
||||||
|
|
||||||
return chunks;
|
|
||||||
}
|
|
||||||
|
|
||||||
private sealed record BatchFetchResult(
|
|
||||||
List<(string EntityId, List<HistoryStateEntry> Entries)> Entries,
|
|
||||||
List<string> FailedEntityIds);
|
|
||||||
}
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
namespace HomeAssistant.HistoryReplay.HistoryData;
|
|
||||||
|
|
||||||
public interface IHistoryDataProvider
|
|
||||||
{
|
|
||||||
Task<HistoryTimeline> FetchHistoryAsync(
|
|
||||||
IReadOnlyList<string> entityIds,
|
|
||||||
DateTimeOffset startTime,
|
|
||||||
DateTimeOffset endTime,
|
|
||||||
CancellationToken cancellationToken = default);
|
|
||||||
|
|
||||||
Task<HistoryTimeline> FetchHistoryAsync(
|
|
||||||
IReadOnlyList<string> minimalEntityIds,
|
|
||||||
IReadOnlyList<string> fullEntityIds,
|
|
||||||
DateTimeOffset startTime,
|
|
||||||
DateTimeOffset endTime,
|
|
||||||
CancellationToken cancellationToken = default);
|
|
||||||
}
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
|
||||||
|
|
||||||
<PropertyGroup>
|
|
||||||
<TargetFramework>net10.0</TargetFramework>
|
|
||||||
<LangVersion>14.0</LangVersion>
|
|
||||||
<Nullable>enable</Nullable>
|
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
|
||||||
<RootNamespace>HomeAssistant.HistoryReplay</RootNamespace>
|
|
||||||
</PropertyGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<PackageReference Include="Blazor-ApexCharts" Version="4.0.0" />
|
|
||||||
<PackageReference Include="Microsoft.AspNetCore.App.Internal.Assets" Version="10.0.5" />
|
|
||||||
<PackageReference Include="NetDaemon.HassModel" Version="26.11.0" />
|
|
||||||
<PackageReference Include="Serilog.Extensions.Hosting" Version="10.0.0" />
|
|
||||||
</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,53 +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 = 3600;
|
|
||||||
|
|
||||||
public string Host { get; set; } = string.Empty;
|
|
||||||
public int Port { get; set; } = DefaultPort;
|
|
||||||
public string Token { get; set; } = string.Empty;
|
|
||||||
public bool Ssl { get; set; }
|
|
||||||
|
|
||||||
public Uri BaseUrl => new UriBuilder(Ssl ? "https" : "http", Host, Port).Uri;
|
|
||||||
}
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
using System.Text.Json;
|
|
||||||
|
|
||||||
namespace HomeAssistant.HistoryReplay.HomeAssistantClient;
|
|
||||||
|
|
||||||
public interface IHomeAssistantApiClient
|
|
||||||
{
|
|
||||||
Task<JsonElement> GetHistoryAsync(
|
|
||||||
string entityIds,
|
|
||||||
DateTimeOffset? startTime = null,
|
|
||||||
DateTimeOffset? endTime = null,
|
|
||||||
bool minimalResponse = true,
|
|
||||||
CancellationToken cancellationToken = default);
|
|
||||||
}
|
|
||||||
@@ -1,77 +0,0 @@
|
|||||||
using BoilerMonitorManager;
|
|
||||||
using BoilerMonitorManager.Interface;
|
|
||||||
using BoilerMonitorManager.Models;
|
|
||||||
using HomeAssistant.Entities.Interfaces;
|
|
||||||
using HomeAssistant.HistoryReplay.Components;
|
|
||||||
using HomeAssistant.HistoryReplay.HistoryData;
|
|
||||||
using HomeAssistant.HistoryReplay.HomeAssistantClient;
|
|
||||||
using HomeAssistant.HistoryReplay.Replay;
|
|
||||||
using HomeAssistant.HistoryReplay.Services;
|
|
||||||
using LightMonitorManager.Models;
|
|
||||||
using NordPoolManager;
|
|
||||||
using NordPoolManager.Interface;
|
|
||||||
using PowerMonitorManager.Models;
|
|
||||||
using Serilog;
|
|
||||||
using ShowerMonitorManager;
|
|
||||||
using ShowerMonitorManager.Interface;
|
|
||||||
using ShowerMonitorManager.Models;
|
|
||||||
|
|
||||||
Log.Logger = new LoggerConfiguration()
|
|
||||||
.MinimumLevel.Information()
|
|
||||||
.WriteTo.Console()
|
|
||||||
.CreateLogger();
|
|
||||||
|
|
||||||
var builder = WebApplication.CreateBuilder(args);
|
|
||||||
|
|
||||||
builder.WebHost.UseStaticWebAssets();
|
|
||||||
|
|
||||||
builder.Services.AddLogging(logging =>
|
|
||||||
{
|
|
||||||
logging.ClearProviders();
|
|
||||||
logging.AddSerilog(dispose: true);
|
|
||||||
});
|
|
||||||
|
|
||||||
builder.Services.AddRazorComponents()
|
|
||||||
.AddInteractiveServerComponents();
|
|
||||||
|
|
||||||
builder.Services.Configure<HomeAssistantSettings>(
|
|
||||||
builder.Configuration.GetSection(HomeAssistantSettings.SectionName));
|
|
||||||
builder.Services.Configure<BoilerMonitorOptions>(
|
|
||||||
builder.Configuration.GetSection(BoilerMonitorOptions.SectionName));
|
|
||||||
builder.Services.Configure<ShowerMonitorOptions>(
|
|
||||||
builder.Configuration.GetSection(ShowerMonitorOptions.SectionName));
|
|
||||||
builder.Services.Configure<PowerMonitorOptions>(
|
|
||||||
builder.Configuration.GetSection(PowerMonitorOptions.SectionName));
|
|
||||||
builder.Services.Configure<LightMonitorOptions>(
|
|
||||||
builder.Configuration.GetSection(LightMonitorOptions.SectionName));
|
|
||||||
|
|
||||||
builder.Services.AddHttpClient<IHomeAssistantApiClient, HomeAssistantApiClient>();
|
|
||||||
builder.Services.AddSingleton<IHistoryDataProvider, HomeAssistantHistoryProvider>();
|
|
||||||
|
|
||||||
builder.Services.AddSingleton<IEntityManager, NoOpEntityManager>();
|
|
||||||
builder.Services.AddSingleton<ICheapestIntervalsFinder, CheapestIntervalsFinder>();
|
|
||||||
builder.Services.AddSingleton<IBoilerControlService, BoilerControlService>();
|
|
||||||
|
|
||||||
var showerOpts = builder.Configuration
|
|
||||||
.GetSection(ShowerMonitorOptions.SectionName)
|
|
||||||
.Get<ShowerMonitorOptions>() ?? new ShowerMonitorOptions();
|
|
||||||
builder.Services.AddSingleton<IHumidityRateCalculator>(_ => new HumidityRateCalculator(showerOpts.RateWindowSize));
|
|
||||||
|
|
||||||
builder.Services.AddSingleton<ReplayOrchestrationService>();
|
|
||||||
|
|
||||||
var app = builder.Build();
|
|
||||||
|
|
||||||
if (!app.Environment.IsDevelopment())
|
|
||||||
{
|
|
||||||
app.UseHsts();
|
|
||||||
}
|
|
||||||
|
|
||||||
app.MapStaticAssets();
|
|
||||||
app.UseAntiforgery();
|
|
||||||
|
|
||||||
app.MapRazorComponents<App>()
|
|
||||||
.AddInteractiveServerRenderMode();
|
|
||||||
|
|
||||||
Log.Information("History Replay Dashboard running at {Urls}", string.Join(", ", app.Urls));
|
|
||||||
|
|
||||||
app.Run();
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
{
|
|
||||||
"profiles": {
|
|
||||||
"HomeAssistant.HistoryReplay": {
|
|
||||||
"commandName": "Project",
|
|
||||||
"dotnetRunMessages": true,
|
|
||||||
"launchBrowser": false,
|
|
||||||
"applicationUrl": "http://localhost:5000",
|
|
||||||
"environmentVariables": {
|
|
||||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,243 +0,0 @@
|
|||||||
# HomeAssistant.HistoryReplay
|
|
||||||
|
|
||||||
A debugging tool that fetches real historical data from your Home Assistant instance and replays it through the monitor business logic to verify decisions without side effects.
|
|
||||||
|
|
||||||
## Prerequisites
|
|
||||||
|
|
||||||
- .NET 10 SDK
|
|
||||||
- A running Home Assistant instance with the History API enabled
|
|
||||||
- A [long-lived access token](https://www.home-assistant.io/docs/authentication/#your-account-profile) from Home Assistant
|
|
||||||
|
|
||||||
## Quick Start
|
|
||||||
|
|
||||||
### 1. Configure the connection
|
|
||||||
|
|
||||||
Edit `appsettings.json` (or create `appsettings.development.json` for local overrides):
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"HomeAssistant": {
|
|
||||||
"Host": "homeassistant.local",
|
|
||||||
"Port": 8123,
|
|
||||||
"Token": "<your-long-lived-access-token>",
|
|
||||||
"Ssl": false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
> **Security note:** Never commit your access token. Use `appsettings.development.json` (already in `.gitignore`) or environment variables instead.
|
|
||||||
|
|
||||||
### 2. Set the replay time range
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"Replay": {
|
|
||||||
"StartTime": "2026-03-30T00:00:00+02:00",
|
|
||||||
"EndTime": "2026-03-31T00:00:00+02:00"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Times are in ISO 8601 format with timezone offset. The tool fetches all entity history within this window from the HA REST API (`/api/history/period`).
|
|
||||||
|
|
||||||
### 3. Enable or disable monitors
|
|
||||||
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"Replay": {
|
|
||||||
"Monitors": {
|
|
||||||
"NordPool": true,
|
|
||||||
"Boiler": true,
|
|
||||||
"Shower": true,
|
|
||||||
"Power": false,
|
|
||||||
"Light": true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Set any monitor to `false` to skip it during replay.
|
|
||||||
|
|
||||||
### 4. Run
|
|
||||||
|
|
||||||
```bash
|
|
||||||
dotnet run --project HomeAssistant.HistoryReplay
|
|
||||||
```
|
|
||||||
|
|
||||||
Or from the project directory:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cd HomeAssistant.HistoryReplay
|
|
||||||
dotnet run
|
|
||||||
```
|
|
||||||
|
|
||||||
## What It Does
|
|
||||||
|
|
||||||
The tool replays historical entity states through the **real business logic services** from each monitor project:
|
|
||||||
|
|
||||||
| Monitor | Services Used | What It Shows |
|
|
||||||
|---------|--------------|---------------|
|
|
||||||
| **NordPool** | `CheapestIntervalsFinder` | Price changes, cheap interval identification |
|
|
||||||
| **Boiler** | `BoilerControlService`, `WaterReadyService`, `BoilerRunTimeTracker` | Turn on/off decisions, water-ready detection, runtime tracking, budget usage |
|
|
||||||
| **Shower** | `ShowerDetectionService`, `ExhaustFanControlService`, `HumidityRateCalculator` | Shower state transitions (Idle/Suspected/Active/Declining/Completed), fan control |
|
|
||||||
| **Power** | `OtherPowerCalculationService`, `PowerCostCalculationService` | Power breakdown, cost accumulation, anomaly detection |
|
|
||||||
| **Light** | Event-driven replay of sun/person state changes | Light-on decisions based on sunset and person arrivals |
|
|
||||||
|
|
||||||
### No side effects
|
|
||||||
|
|
||||||
- **No MQTT entities** are created or updated
|
|
||||||
- **No HA service calls** are executed (they are logged as "would call" events)
|
|
||||||
- **No NetDaemon runtime** is required
|
|
||||||
- The tool only reads from the HA History API
|
|
||||||
|
|
||||||
## Console Output
|
|
||||||
|
|
||||||
The tool produces a colored timeline report:
|
|
||||||
|
|
||||||
```
|
|
||||||
═══════════════════════════════════════════════════════════
|
|
||||||
REPLAY: 2026-03-30 00:00 -> 2026-03-31 00:00
|
|
||||||
═══════════════════════════════════════════════════════════
|
|
||||||
|
|
||||||
-- NordPool ──────────────────────────────────────────────
|
|
||||||
00:00 Price: 3.21 ct/kWh
|
|
||||||
00:15 Price: 3.18 ct/kWh
|
|
||||||
00:15 -> CHEAP interval active (rank #2, price: 3.18 ct/kWh)
|
|
||||||
|
|
||||||
-- Boiler ────────────────────────────────────────────────
|
|
||||||
00:15 -> TURN ON (cheap: True, water ready: False, budget: 0%)
|
|
||||||
01:30 Water ready detected (power: 3.2W, threshold: 5.0W)
|
|
||||||
01:30 -> TURN OFF (cheap: True, water ready: True, budget: 42%)
|
|
||||||
23:59 Final: 01:15:00 total runtime, 2 session(s)
|
|
||||||
|
|
||||||
-- Shower ────────────────────────────────────────────────
|
|
||||||
07:12 State: Idle -> Suspected (bathroom: 62.1%, home: 53.0%, diff: 9.1%)
|
|
||||||
07:14 State: Suspected -> Active (bathroom: 65.3%, home: 53.0%, diff: 12.3%)
|
|
||||||
07:35 State: Declining -> Completed (bathroom: 58.2%, home: 54.1%, diff: 4.1%)
|
|
||||||
|
|
||||||
-- Service Calls ─────────────────────────────────────────
|
|
||||||
00:15 -> Would call switch.turn_on on switch.boiler
|
|
||||||
01:30 -> Would call switch.turn_off on switch.boiler
|
|
||||||
|
|
||||||
═══════════════════════════════════════════════════════════
|
|
||||||
REPLAY SUMMARY
|
|
||||||
═══════════════════════════════════════════════════════════
|
|
||||||
Total events: 24
|
|
||||||
Decisions: 5
|
|
||||||
Service calls: 4
|
|
||||||
Warnings: 0
|
|
||||||
Anomalies: 0
|
|
||||||
```
|
|
||||||
|
|
||||||
## Configuration Reference
|
|
||||||
|
|
||||||
### Monitor-specific settings
|
|
||||||
|
|
||||||
The monitor sections (`BoilerMonitor`, `ShowerMonitor`, `PowerMonitor`, `LightMonitor`) use the **same options classes** as the production `HomeAssistant.Server` project. This means thresholds, entity IDs, and poll intervals match what runs in production.
|
|
||||||
|
|
||||||
#### ShowerMonitor
|
|
||||||
|
|
||||||
| Setting | Default | Description |
|
|
||||||
|---------|---------|-------------|
|
|
||||||
| `BathroomHumidityEntityId` | `sensor.bathroom_humidity` | Bathroom humidity sensor |
|
|
||||||
| `MainHomeHumidityEntityId` | `sensor.main_home_humidity` | Reference home humidity sensor |
|
|
||||||
| `PollIntervalSeconds` | `30` | Replay step interval |
|
|
||||||
| `SpikeRateThreshold` | `4.0` | Humidity rate (%/min) to trigger suspected state |
|
|
||||||
| `MinDifferentialHumidity` | `8.0` | Minimum bathroom-vs-home humidity difference |
|
|
||||||
| `PeakHumidityThreshold` | `58.0` | Humidity to confirm active shower |
|
|
||||||
|
|
||||||
#### PowerMonitor
|
|
||||||
|
|
||||||
| Setting | Default | Description |
|
|
||||||
|---------|---------|-------------|
|
|
||||||
| `MainMeterEntityId` | *(required)* | Main power meter entity |
|
|
||||||
| `PollIntervalSeconds` | `1` | Replay step interval |
|
|
||||||
| `AnomalyThresholdWatts` | `500` | "Other" power threshold for anomaly detection |
|
|
||||||
| `SmoothingWindowSize` | `10` | EMA window for smoothing |
|
|
||||||
|
|
||||||
#### LightMonitor
|
|
||||||
|
|
||||||
| Setting | Default | Description |
|
|
||||||
|---------|---------|-------------|
|
|
||||||
| `LightEntityId` | `light.sonoff_1002214d40` | The light entity to control |
|
|
||||||
| `SunEntityId` | `sun.sun` | Sun entity for below-horizon detection |
|
|
||||||
| `PersonEntityIds` | `[...]` | Person entities for presence detection |
|
|
||||||
|
|
||||||
### Environment-based configuration
|
|
||||||
|
|
||||||
You can override any setting via environment variables using the `__` separator:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
set Replay__StartTime=2026-03-29T00:00:00+02:00
|
|
||||||
set HomeAssistant__Token=your_token_here
|
|
||||||
dotnet run --project HomeAssistant.HistoryReplay
|
|
||||||
```
|
|
||||||
|
|
||||||
## Project Architecture
|
|
||||||
|
|
||||||
```
|
|
||||||
HomeAssistant.HistoryReplay/
|
|
||||||
├── Program.cs Entry point, DI wiring, orchestration
|
|
||||||
├── HomeAssistantClient/ Self-contained HA REST API client
|
|
||||||
│ ├── IHomeAssistantApiClient.cs
|
|
||||||
│ ├── HomeAssistantApiClient.cs
|
|
||||||
│ └── HomeAssistantSettings.cs
|
|
||||||
├── Configuration/
|
|
||||||
│ ├── ReplayOptions.cs Time range and monitor flags
|
|
||||||
│ └── ReplayEntityMap.cs Maps monitors to required HA entity IDs
|
|
||||||
├── HistoryData/
|
|
||||||
│ ├── IHistoryDataProvider.cs Abstraction for fetching history
|
|
||||||
│ ├── HomeAssistantHistoryProvider.cs Fetches from /api/history/period
|
|
||||||
│ ├── HistoryTimeline.cs Sorted timeline of entity states
|
|
||||||
│ └── HistoryStateEntry.cs Single entity state snapshot
|
|
||||||
├── Replay/
|
|
||||||
│ ├── ReplayHaContext.cs IHaContext backed by historical data
|
|
||||||
│ ├── ReplayTimeProvider.cs TimeProvider that steps through time
|
|
||||||
│ └── NoOpEntityManager.cs IEntityManager that logs but does nothing
|
|
||||||
├── Runners/
|
|
||||||
│ ├── IMonitorReplayRunner.cs Common runner interface
|
|
||||||
│ ├── NordPoolReplayRunner.cs Price + cheapest interval replay
|
|
||||||
│ ├── BoilerReplayRunner.cs Boiler control decision replay
|
|
||||||
│ ├── ShowerReplayRunner.cs Shower detection state machine replay
|
|
||||||
│ ├── PowerReplayRunner.cs Power calculation + cost replay
|
|
||||||
│ └── LightReplayRunner.cs Sun/person event-driven replay
|
|
||||||
├── Reporting/
|
|
||||||
│ ├── ReplayEvent.cs Single decision/event during replay
|
|
||||||
│ ├── ReplayTimeline.cs Collected events across all monitors
|
|
||||||
│ └── ConsoleReportRenderer.cs Colored console output
|
|
||||||
└── appsettings.json Configuration
|
|
||||||
```
|
|
||||||
|
|
||||||
### Key design: real services, fake infrastructure
|
|
||||||
|
|
||||||
The replay instantiates **actual production business logic** (e.g., `BoilerControlService.DetermineAction()`, `ShowerDetectionService.Evaluate()`) but replaces infrastructure with replay stubs:
|
|
||||||
|
|
||||||
- `ReplayHaContext` implements `IHaContext` by returning historical state at the current replay timestamp
|
|
||||||
- `ReplayTimeProvider` extends `TimeProvider` for time-dependent logic (e.g., `WaterReadyService` cooldown periods)
|
|
||||||
- `NoOpEntityManager` implements `IEntityManager` and logs all calls without side effects
|
|
||||||
- Service calls via `IHaContext.CallService()` are captured as replay events
|
|
||||||
|
|
||||||
All five monitors run their replays **in parallel** via `Task.WhenAll`.
|
|
||||||
|
|
||||||
## Troubleshooting
|
|
||||||
|
|
||||||
### "History replay failed" with HTTP errors
|
|
||||||
|
|
||||||
- Verify your HA host, port, and token in `appsettings.json`
|
|
||||||
- Ensure the HA History API is enabled (it is by default)
|
|
||||||
- Check that the token has sufficient permissions
|
|
||||||
|
|
||||||
### No events in the output for a monitor
|
|
||||||
|
|
||||||
- The entity IDs in the monitor config must match your actual HA entities
|
|
||||||
- Check that history data exists for the configured time range (HA purges old history based on the recorder settings)
|
|
||||||
- Verify the monitor is enabled in `Replay.Monitors`
|
|
||||||
|
|
||||||
### Shower monitor shows no sessions
|
|
||||||
|
|
||||||
- Confirm `BathroomHumidityEntityId` and `MainHomeHumidityEntityId` have data in the replay period
|
|
||||||
- Adjust `SpikeRateThreshold` and `MinDifferentialHumidity` if your bathroom has different humidity characteristics
|
|
||||||
|
|
||||||
### Boiler shows "not configured"
|
|
||||||
|
|
||||||
- The boiler replay reads config entity states (`text.boilermonitor_config_power_entity_id`, `text.boilermonitor_config_switch_entity_id`) from history. These must have been set in HA during the replay period.
|
|
||||||
@@ -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,157 +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,9 +0,0 @@
|
|||||||
namespace HomeAssistant.HistoryReplay.Reporting;
|
|
||||||
|
|
||||||
public sealed class ReplayDataPoint
|
|
||||||
{
|
|
||||||
public required DateTimeOffset Timestamp { get; init; }
|
|
||||||
public required string Monitor { get; init; }
|
|
||||||
public required string Series { get; init; }
|
|
||||||
public required double Value { get; init; }
|
|
||||||
}
|
|
||||||
@@ -1,50 +0,0 @@
|
|||||||
using System.Collections.Concurrent;
|
|
||||||
|
|
||||||
namespace HomeAssistant.HistoryReplay.Reporting;
|
|
||||||
|
|
||||||
public sealed class ReplayDataSeries
|
|
||||||
{
|
|
||||||
private readonly ConcurrentBag<ReplayDataPoint> _points = [];
|
|
||||||
|
|
||||||
public void AddPoint(ReplayDataPoint point)
|
|
||||||
{
|
|
||||||
_points.Add(point);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void AddPoint(string monitor, string series, DateTimeOffset timestamp, double value)
|
|
||||||
{
|
|
||||||
_points.Add(new ReplayDataPoint
|
|
||||||
{
|
|
||||||
Monitor = monitor,
|
|
||||||
Series = series,
|
|
||||||
Timestamp = timestamp,
|
|
||||||
Value = value
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
public IReadOnlyList<ReplayDataPoint> GetSeries(string monitor, string series) =>
|
|
||||||
_points
|
|
||||||
.Where(p => string.Equals(p.Monitor, monitor, StringComparison.OrdinalIgnoreCase)
|
|
||||||
&& string.Equals(p.Series, series, StringComparison.OrdinalIgnoreCase))
|
|
||||||
.OrderBy(p => p.Timestamp)
|
|
||||||
.ToList();
|
|
||||||
|
|
||||||
public IReadOnlyList<ReplayDataPoint> GetAllForMonitor(string monitor) =>
|
|
||||||
_points
|
|
||||||
.Where(p => string.Equals(p.Monitor, monitor, StringComparison.OrdinalIgnoreCase))
|
|
||||||
.OrderBy(p => p.Timestamp)
|
|
||||||
.ToList();
|
|
||||||
|
|
||||||
public IReadOnlyList<string> GetSeriesNames(string monitor) =>
|
|
||||||
_points
|
|
||||||
.Where(p => string.Equals(p.Monitor, monitor, StringComparison.OrdinalIgnoreCase))
|
|
||||||
.Select(p => p.Series)
|
|
||||||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
|
||||||
.Order()
|
|
||||||
.ToList();
|
|
||||||
|
|
||||||
public void Clear()
|
|
||||||
{
|
|
||||||
_points.Clear();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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,30 +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();
|
|
||||||
|
|
||||||
public void Clear()
|
|
||||||
{
|
|
||||||
_events.Clear();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,221 +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;
|
|
||||||
|
|
||||||
namespace HomeAssistant.HistoryReplay.Runners;
|
|
||||||
|
|
||||||
public sealed class BoilerReplayRunner : IMonitorReplayRunner
|
|
||||||
{
|
|
||||||
private readonly HistoryTimeline _timeline;
|
|
||||||
private readonly ReplayTimeProvider _timeProvider;
|
|
||||||
private readonly ReplayTimeline _replayTimeline;
|
|
||||||
private readonly ReplayDataSeries _dataSeries;
|
|
||||||
private readonly IBoilerControlService _boilerControlService;
|
|
||||||
private readonly IBoilerRunTimeTracker _tracker;
|
|
||||||
private readonly IWaterReadyService _waterReadyService;
|
|
||||||
private readonly ILogger<BoilerReplayRunner> _logger;
|
|
||||||
private readonly ReplayOptions _replayOptions;
|
|
||||||
private readonly string _boilerPowerEntityId;
|
|
||||||
private readonly string _boilerSwitchEntityId;
|
|
||||||
|
|
||||||
public string MonitorName => "Boiler";
|
|
||||||
|
|
||||||
public BoilerReplayRunner(
|
|
||||||
HistoryTimeline timeline,
|
|
||||||
ReplayTimeProvider timeProvider,
|
|
||||||
ReplayTimeline replayTimeline,
|
|
||||||
ReplayDataSeries dataSeries,
|
|
||||||
IBoilerControlService boilerControlService,
|
|
||||||
IBoilerRunTimeTracker tracker,
|
|
||||||
IWaterReadyService waterReadyService,
|
|
||||||
ILogger<BoilerReplayRunner> logger,
|
|
||||||
IOptions<ReplayOptions> replayOptions,
|
|
||||||
string boilerPowerEntityId,
|
|
||||||
string boilerSwitchEntityId)
|
|
||||||
{
|
|
||||||
_timeline = timeline;
|
|
||||||
_timeProvider = timeProvider;
|
|
||||||
_replayTimeline = replayTimeline;
|
|
||||||
_dataSeries = dataSeries;
|
|
||||||
_boilerControlService = boilerControlService;
|
|
||||||
_tracker = tracker;
|
|
||||||
_waterReadyService = waterReadyService;
|
|
||||||
_logger = logger;
|
|
||||||
_replayOptions = replayOptions.Value;
|
|
||||||
_boilerPowerEntityId = boilerPowerEntityId;
|
|
||||||
_boilerSwitchEntityId = boilerSwitchEntityId;
|
|
||||||
}
|
|
||||||
|
|
||||||
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 = _boilerPowerEntityId;
|
|
||||||
var boilerSwitchEntityId = _boilerSwitchEntityId;
|
|
||||||
|
|
||||||
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 autoManagementEntry = _timeline.GetStateAt(BoilerMonitorConsts.AutoManagementEntityId, 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);
|
|
||||||
|
|
||||||
if (isHeating)
|
|
||||||
{
|
|
||||||
_waterReadyService.RecordHeatingObserved();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (boilerPowerWatts.HasValue)
|
|
||||||
{
|
|
||||||
_dataSeries.AddPoint(MonitorName, "PowerWatts", currentTime, boilerPowerWatts.Value);
|
|
||||||
}
|
|
||||||
|
|
||||||
var isNowCheap = ReadAttributeBool(cheapEntry, "is_now_cheap");
|
|
||||||
var skipPriceCap = string.Equals(skipPriceCapEntry?.State, "on", StringComparison.OrdinalIgnoreCase);
|
|
||||||
var budgetOverride = string.Equals(budgetOverrideEntry?.State, "on", StringComparison.OrdinalIgnoreCase);
|
|
||||||
var autoManagementEnabled = !string.Equals(autoManagementEntry?.State, BoilerMonitorConsts.SwitchOffState, StringComparison.OrdinalIgnoreCase);
|
|
||||||
var dailyHours = ParseDouble(dailyHoursEntry?.State) ?? 1.0;
|
|
||||||
|
|
||||||
var waterReady = _waterReadyService.IsWaterReady(boilerSwitchState, boilerPowerWatts, heatingThreshold);
|
|
||||||
|
|
||||||
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;
|
|
||||||
|
|
||||||
_dataSeries.AddPoint(MonitorName, "BudgetPercent", currentTime, budgetPercentage);
|
|
||||||
_dataSeries.AddPoint(MonitorName, "SwitchState", currentTime,
|
|
||||||
string.Equals(boilerSwitchState, "on", StringComparison.OrdinalIgnoreCase) ? 1.0 : 0.0);
|
|
||||||
|
|
||||||
var effectiveIsNowCheap = isNowCheap || skipPriceCap;
|
|
||||||
var action = _boilerControlService.DetermineAction(
|
|
||||||
effectiveIsNowCheap,
|
|
||||||
waterReady,
|
|
||||||
boilerSwitchState,
|
|
||||||
budgetExhausted,
|
|
||||||
budgetOverride);
|
|
||||||
|
|
||||||
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()
|
|
||||||
};
|
|
||||||
|
|
||||||
if (autoManagementEnabled)
|
|
||||||
{
|
|
||||||
_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();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
_replayTimeline.AddEvent(new ReplayEvent
|
|
||||||
{
|
|
||||||
Timestamp = currentTime,
|
|
||||||
Monitor = MonitorName,
|
|
||||||
EventType = ReplayEventType.Decision,
|
|
||||||
Message = $"SUPPRESSED (auto control off): {actionMessage}",
|
|
||||||
Details = $"Power: {boilerPowerWatts:F1}W, Runtime: {snapshot.AccumulatedRunTime:hh\\:mm\\:ss}, Sessions: {snapshot.SessionCount}"
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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 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,188 +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 ReplayDataSeries _dataSeries;
|
|
||||||
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,
|
|
||||||
ReplayDataSeries dataSeries,
|
|
||||||
ILogger<LightReplayRunner> logger,
|
|
||||||
IOptions<ReplayOptions> replayOptions,
|
|
||||||
IOptions<LightMonitorOptions> lightOptions)
|
|
||||||
{
|
|
||||||
_timeline = timeline;
|
|
||||||
_timeProvider = timeProvider;
|
|
||||||
_replayTimeline = replayTimeline;
|
|
||||||
_dataSeries = dataSeries;
|
|
||||||
_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;
|
|
||||||
}
|
|
||||||
|
|
||||||
var isBelowHorizon = string.Equals(entry.State, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase);
|
|
||||||
_dataSeries.AddPoint(MonitorName, "SunBelowHorizon", entry.LastChanged, isBelowHorizon ? 1.0 : 0.0);
|
|
||||||
|
|
||||||
if (isBelowHorizon &&
|
|
||||||
!string.Equals(previousSunState, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase))
|
|
||||||
{
|
|
||||||
_timeProvider.AdvanceTo(entry.LastChanged);
|
|
||||||
|
|
||||||
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)
|
|
||||||
{
|
|
||||||
_dataSeries.AddPoint(MonitorName, "LightOn", entry.LastChanged, 1.0);
|
|
||||||
_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)
|
|
||||||
{
|
|
||||||
_dataSeries.AddPoint(MonitorName, "LightOn", entry.LastChanged, 1.0);
|
|
||||||
_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,182 +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 ReplayDataSeries _dataSeries;
|
|
||||||
private readonly ICheapestIntervalsFinder _cheapestIntervalsFinder;
|
|
||||||
private readonly ILogger<NordPoolReplayRunner> _logger;
|
|
||||||
private readonly ReplayOptions _options;
|
|
||||||
|
|
||||||
private const string NordPoolHaSensorId = "sensor.nordpool_kwh_lt_eur_3_10_0";
|
|
||||||
|
|
||||||
public string MonitorName => "NordPool";
|
|
||||||
|
|
||||||
public NordPoolReplayRunner(
|
|
||||||
HistoryTimeline timeline,
|
|
||||||
ReplayTimeProvider timeProvider,
|
|
||||||
ReplayTimeline replayTimeline,
|
|
||||||
ReplayDataSeries dataSeries,
|
|
||||||
ICheapestIntervalsFinder cheapestIntervalsFinder,
|
|
||||||
ILogger<NordPoolReplayRunner> logger,
|
|
||||||
IOptions<ReplayOptions> options)
|
|
||||||
{
|
|
||||||
_timeline = timeline;
|
|
||||||
_timeProvider = timeProvider;
|
|
||||||
_replayTimeline = replayTimeline;
|
|
||||||
_dataSeries = dataSeries;
|
|
||||||
_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(NordPoolHaSensorId, currentTime)
|
|
||||||
?? _timeline.GetStateAt(NordPoolConsts.CurrentPriceEntityId, currentTime);
|
|
||||||
|
|
||||||
if (priceEntry?.State is not null &&
|
|
||||||
double.TryParse(priceEntry.State, CultureInfo.InvariantCulture, out var currentPrice))
|
|
||||||
{
|
|
||||||
_dataSeries.AddPoint(MonitorName, "Price", currentTime, currentPrice);
|
|
||||||
|
|
||||||
if (lastReportedPrice is null || Math.Abs(currentPrice - lastReportedPrice.Value) > 0.01)
|
|
||||||
{
|
|
||||||
_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);
|
|
||||||
|
|
||||||
_dataSeries.AddPoint(MonitorName, "IsCheap", currentTime, isNowCheap ? 1.0 : 0.0);
|
|
||||||
|
|
||||||
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,163 +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;
|
|
||||||
|
|
||||||
namespace HomeAssistant.HistoryReplay.Runners;
|
|
||||||
|
|
||||||
public sealed class PowerReplayRunner : IMonitorReplayRunner
|
|
||||||
{
|
|
||||||
private readonly HistoryTimeline _timeline;
|
|
||||||
private readonly ReplayTimeProvider _timeProvider;
|
|
||||||
private readonly ReplayTimeline _replayTimeline;
|
|
||||||
private readonly ReplayDataSeries _dataSeries;
|
|
||||||
private readonly IOtherPowerCalculationService _calculationService;
|
|
||||||
private readonly IPowerCostCalculationService _costService;
|
|
||||||
private readonly ILogger<PowerReplayRunner> _logger;
|
|
||||||
private readonly ReplayOptions _replayOptions;
|
|
||||||
private readonly PowerMonitorOptions _powerOptions;
|
|
||||||
|
|
||||||
public string MonitorName => "Power";
|
|
||||||
|
|
||||||
public PowerReplayRunner(
|
|
||||||
HistoryTimeline timeline,
|
|
||||||
ReplayTimeProvider timeProvider,
|
|
||||||
ReplayTimeline replayTimeline,
|
|
||||||
ReplayDataSeries dataSeries,
|
|
||||||
IOtherPowerCalculationService calculationService,
|
|
||||||
IPowerCostCalculationService costService,
|
|
||||||
ILogger<PowerReplayRunner> logger,
|
|
||||||
IOptions<ReplayOptions> replayOptions,
|
|
||||||
IOptions<PowerMonitorOptions> powerOptions)
|
|
||||||
{
|
|
||||||
_timeline = timeline;
|
|
||||||
_timeProvider = timeProvider;
|
|
||||||
_replayTimeline = replayTimeline;
|
|
||||||
_dataSeries = dataSeries;
|
|
||||||
_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);
|
|
||||||
|
|
||||||
_dataSeries.AddPoint(MonitorName, "TotalPower", currentTime, calculation.TotalPowerWatts);
|
|
||||||
_dataSeries.AddPoint(MonitorName, "KnownDevices", currentTime, calculation.KnownDevicesSumWatts);
|
|
||||||
_dataSeries.AddPoint(MonitorName, "OtherPower", currentTime, calculation.SmoothedOtherPowerWatts);
|
|
||||||
|
|
||||||
var nordPoolPriceEntry = _timeline.GetStateAt(NordPoolConsts.CurrentPriceEntityId, currentTime);
|
|
||||||
var nordPoolPrice = ParseDouble(nordPoolPriceEntry?.State) ?? 0;
|
|
||||||
|
|
||||||
_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,136 +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 NetDaemon.HassModel;
|
|
||||||
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 ReplayDataSeries _dataSeries;
|
|
||||||
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,
|
|
||||||
ReplayDataSeries dataSeries,
|
|
||||||
IShowerDetectionService detectionService,
|
|
||||||
IExhaustFanControlService fanControlService,
|
|
||||||
ILogger<ShowerReplayRunner> logger,
|
|
||||||
IOptions<ReplayOptions> replayOptions,
|
|
||||||
IOptions<ShowerMonitorOptions> showerOptions)
|
|
||||||
{
|
|
||||||
_timeline = timeline;
|
|
||||||
_timeProvider = timeProvider;
|
|
||||||
_replayTimeline = replayTimeline;
|
|
||||||
_dataSeries = dataSeries;
|
|
||||||
_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)
|
|
||||||
{
|
|
||||||
_dataSeries.AddPoint(MonitorName, "BathroomHumidity", currentTime, bathroomHumidity.Value);
|
|
||||||
_dataSeries.AddPoint(MonitorName, "HomeHumidity", currentTime, homeHumidity.Value);
|
|
||||||
_dataSeries.AddPoint(MonitorName, "Differential", currentTime, bathroomHumidity.Value - homeHumidity.Value);
|
|
||||||
|
|
||||||
var state = _detectionService.Evaluate(bathroomHumidity.Value, homeHumidity.Value, currentTime);
|
|
||||||
var differential = bathroomHumidity.Value - homeHumidity.Value;
|
|
||||||
|
|
||||||
_dataSeries.AddPoint(MonitorName, "State", currentTime, (double)state);
|
|
||||||
|
|
||||||
_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,214 +0,0 @@
|
|||||||
using BoilerMonitorManager;
|
|
||||||
using BoilerMonitorManager.Interface;
|
|
||||||
using PowerMonitorManager;
|
|
||||||
using ShowerMonitorManager;
|
|
||||||
using HomeAssistant.HistoryReplay.Configuration;
|
|
||||||
using HomeAssistant.HistoryReplay.HistoryData;
|
|
||||||
using HomeAssistant.HistoryReplay.Replay;
|
|
||||||
using HomeAssistant.HistoryReplay.Reporting;
|
|
||||||
using HomeAssistant.HistoryReplay.Runners;
|
|
||||||
using LightMonitorManager.Models;
|
|
||||||
using Microsoft.Extensions.Logging;
|
|
||||||
using Microsoft.Extensions.Options;
|
|
||||||
using NordPoolManager.Interface;
|
|
||||||
using PowerMonitorManager.Interface;
|
|
||||||
using PowerMonitorManager.Models;
|
|
||||||
using ShowerMonitorManager.Interface;
|
|
||||||
using ShowerMonitorManager.Models;
|
|
||||||
|
|
||||||
namespace HomeAssistant.HistoryReplay.Services;
|
|
||||||
|
|
||||||
public sealed class ReplayOrchestrationService
|
|
||||||
{
|
|
||||||
private readonly IHistoryDataProvider _historyProvider;
|
|
||||||
private readonly IServiceProvider _serviceProvider;
|
|
||||||
private readonly ILogger<ReplayOrchestrationService> _logger;
|
|
||||||
|
|
||||||
public ReplayTimeline Timeline { get; } = new();
|
|
||||||
public ReplayDataSeries DataSeries { get; } = new();
|
|
||||||
public ReplayStatus Status { get; private set; } = ReplayStatus.Idle;
|
|
||||||
public string? ErrorMessage { get; private set; }
|
|
||||||
public string? ProgressMessage { get; private set; }
|
|
||||||
|
|
||||||
public event Action? OnStateChanged;
|
|
||||||
|
|
||||||
public void SetError(string message)
|
|
||||||
{
|
|
||||||
ErrorMessage = message;
|
|
||||||
Status = ReplayStatus.Failed;
|
|
||||||
NotifyStateChanged();
|
|
||||||
}
|
|
||||||
|
|
||||||
public ReplayOrchestrationService(
|
|
||||||
IHistoryDataProvider historyProvider,
|
|
||||||
IServiceProvider serviceProvider,
|
|
||||||
ILogger<ReplayOrchestrationService> logger)
|
|
||||||
{
|
|
||||||
_historyProvider = historyProvider;
|
|
||||||
_serviceProvider = serviceProvider;
|
|
||||||
_logger = logger;
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task RunReplayAsync(
|
|
||||||
DateTimeOffset startTime,
|
|
||||||
DateTimeOffset endTime,
|
|
||||||
ReplayMonitorFlags monitors,
|
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
Timeline.Clear();
|
|
||||||
DataSeries.Clear();
|
|
||||||
ErrorMessage = null;
|
|
||||||
ProgressMessage = null;
|
|
||||||
|
|
||||||
Status = ReplayStatus.FetchingHistory;
|
|
||||||
ProgressMessage = "Connecting to Home Assistant...";
|
|
||||||
NotifyStateChanged();
|
|
||||||
|
|
||||||
var showerOpts = _serviceProvider.GetRequiredService<IOptions<ShowerMonitorOptions>>().Value;
|
|
||||||
var powerOpts = _serviceProvider.GetRequiredService<IOptions<PowerMonitorOptions>>().Value;
|
|
||||||
var lightOpts = _serviceProvider.GetRequiredService<IOptions<LightMonitorOptions>>().Value;
|
|
||||||
|
|
||||||
const string boilerPowerEntityId = "sensor.boiler_power";
|
|
||||||
const string boilerSwitchEntityId = "switch.boiler";
|
|
||||||
|
|
||||||
var (minimalEntities, fullEntities) = ReplayEntityMap.GetPartitionedEntities(
|
|
||||||
boilerPowerEntityId,
|
|
||||||
boilerSwitchEntityId,
|
|
||||||
bathroomHumidityEntityId: showerOpts.BathroomHumidityEntityId,
|
|
||||||
mainHomeHumidityEntityId: showerOpts.MainHomeHumidityEntityId,
|
|
||||||
mainMeterEntityId: powerOpts.MainMeterEntityId,
|
|
||||||
sunEntityId: lightOpts.SunEntityId,
|
|
||||||
lightEntityId: lightOpts.LightEntityId,
|
|
||||||
personEntityIds: lightOpts.PersonEntityIds);
|
|
||||||
|
|
||||||
var totalEntityCount = minimalEntities.Count + fullEntities.Count;
|
|
||||||
_logger.LogInformation(
|
|
||||||
"Fetching history for {MinCount} minimal + {FullCount} full entities ({Start} to {End})",
|
|
||||||
minimalEntities.Count, fullEntities.Count, startTime, endTime);
|
|
||||||
|
|
||||||
ProgressMessage = $"Fetching history for {totalEntityCount} entities...";
|
|
||||||
NotifyStateChanged();
|
|
||||||
|
|
||||||
var historyTimeline = await _historyProvider.FetchHistoryAsync(
|
|
||||||
minimalEntities, fullEntities, startTime, endTime, cancellationToken);
|
|
||||||
|
|
||||||
ProgressMessage = $"Loaded {historyTimeline.TotalEntryCount} data points. Running replay...";
|
|
||||||
Status = ReplayStatus.Running;
|
|
||||||
NotifyStateChanged();
|
|
||||||
|
|
||||||
var replayOptions = new ReplayOptions
|
|
||||||
{
|
|
||||||
StartTime = startTime,
|
|
||||||
EndTime = endTime,
|
|
||||||
Monitors = monitors
|
|
||||||
};
|
|
||||||
var replayOptionsWrapper = Options.Create(replayOptions);
|
|
||||||
|
|
||||||
var timeProvider = new ReplayTimeProvider(startTime);
|
|
||||||
|
|
||||||
var replayHaContext = new ReplayHaContext(
|
|
||||||
historyTimeline, timeProvider, Timeline,
|
|
||||||
_serviceProvider.GetRequiredService<ILogger<ReplayHaContext>>());
|
|
||||||
|
|
||||||
var runners = BuildRunners(
|
|
||||||
historyTimeline, timeProvider, replayHaContext, replayOptionsWrapper, monitors,
|
|
||||||
boilerPowerEntityId, boilerSwitchEntityId);
|
|
||||||
|
|
||||||
_logger.LogInformation("Running {Count} monitor replay(s) in parallel", runners.Count);
|
|
||||||
|
|
||||||
var tasks = runners.Select(r => Task.Run(() => r.RunAsync(cancellationToken), cancellationToken));
|
|
||||||
await Task.WhenAll(tasks);
|
|
||||||
|
|
||||||
Status = ReplayStatus.Completed;
|
|
||||||
_logger.LogInformation("Replay completed with {Count} events", Timeline.GetAllEvents().Count);
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
_logger.LogError(ex, "Replay failed");
|
|
||||||
ErrorMessage = ex.Message;
|
|
||||||
Status = ReplayStatus.Failed;
|
|
||||||
}
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
NotifyStateChanged();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private List<IMonitorReplayRunner> BuildRunners(
|
|
||||||
HistoryTimeline historyTimeline,
|
|
||||||
ReplayTimeProvider timeProvider,
|
|
||||||
ReplayHaContext replayHaContext,
|
|
||||||
IOptions<ReplayOptions> replayOptions,
|
|
||||||
ReplayMonitorFlags monitors,
|
|
||||||
string boilerPowerEntityId,
|
|
||||||
string boilerSwitchEntityId)
|
|
||||||
{
|
|
||||||
var runners = new List<IMonitorReplayRunner>();
|
|
||||||
|
|
||||||
if (monitors.NordPool)
|
|
||||||
{
|
|
||||||
runners.Add(new NordPoolReplayRunner(
|
|
||||||
historyTimeline, timeProvider, Timeline, DataSeries,
|
|
||||||
_serviceProvider.GetRequiredService<ICheapestIntervalsFinder>(),
|
|
||||||
_serviceProvider.GetRequiredService<ILogger<NordPoolReplayRunner>>(),
|
|
||||||
replayOptions));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (monitors.Boiler)
|
|
||||||
{
|
|
||||||
runners.Add(new BoilerReplayRunner(
|
|
||||||
historyTimeline, timeProvider, Timeline, DataSeries,
|
|
||||||
_serviceProvider.GetRequiredService<IBoilerControlService>(),
|
|
||||||
new BoilerRunTimeTracker(),
|
|
||||||
new WaterReadyService(
|
|
||||||
_serviceProvider.GetRequiredService<ILogger<WaterReadyService>>(), timeProvider),
|
|
||||||
_serviceProvider.GetRequiredService<ILogger<BoilerReplayRunner>>(),
|
|
||||||
replayOptions,
|
|
||||||
boilerPowerEntityId,
|
|
||||||
boilerSwitchEntityId));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (monitors.Shower)
|
|
||||||
{
|
|
||||||
var showerOpts = _serviceProvider.GetRequiredService<IOptions<ShowerMonitorOptions>>();
|
|
||||||
var rateCalc = new ShowerMonitorManager.HumidityRateCalculator(showerOpts.Value.RateWindowSize);
|
|
||||||
var detection = new ShowerMonitorManager.ShowerDetectionService(
|
|
||||||
rateCalc,
|
|
||||||
showerOpts);
|
|
||||||
var fan = new ExhaustFanControlService(replayHaContext, showerOpts);
|
|
||||||
|
|
||||||
runners.Add(new ShowerReplayRunner(
|
|
||||||
historyTimeline, timeProvider, Timeline, DataSeries,
|
|
||||||
detection, fan,
|
|
||||||
_serviceProvider.GetRequiredService<ILogger<ShowerReplayRunner>>(),
|
|
||||||
replayOptions, showerOpts));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (monitors.Power)
|
|
||||||
{
|
|
||||||
runners.Add(new PowerReplayRunner(
|
|
||||||
historyTimeline, timeProvider, Timeline, DataSeries,
|
|
||||||
new OtherPowerCalculationService(
|
|
||||||
_serviceProvider.GetRequiredService<IOptions<PowerMonitorOptions>>()),
|
|
||||||
new PowerCostCalculationService(),
|
|
||||||
_serviceProvider.GetRequiredService<ILogger<PowerReplayRunner>>(),
|
|
||||||
replayOptions,
|
|
||||||
_serviceProvider.GetRequiredService<IOptions<PowerMonitorOptions>>()));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (monitors.Light)
|
|
||||||
{
|
|
||||||
runners.Add(new LightReplayRunner(
|
|
||||||
historyTimeline, timeProvider, Timeline, DataSeries,
|
|
||||||
_serviceProvider.GetRequiredService<ILogger<LightReplayRunner>>(),
|
|
||||||
replayOptions,
|
|
||||||
_serviceProvider.GetRequiredService<IOptions<LightMonitorOptions>>()));
|
|
||||||
}
|
|
||||||
|
|
||||||
return runners;
|
|
||||||
}
|
|
||||||
|
|
||||||
private void NotifyStateChanged() => OnStateChanged?.Invoke();
|
|
||||||
}
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
namespace HomeAssistant.HistoryReplay.Services;
|
|
||||||
|
|
||||||
public enum ReplayStatus
|
|
||||||
{
|
|
||||||
Idle,
|
|
||||||
FetchingHistory,
|
|
||||||
Running,
|
|
||||||
Completed,
|
|
||||||
Failed
|
|
||||||
}
|
|
||||||
@@ -1,57 +0,0 @@
|
|||||||
{
|
|
||||||
"HomeAssistant": {
|
|
||||||
"Host": "homeassistant.local",
|
|
||||||
"Port": 8123,
|
|
||||||
"Token": "<your-long-lived-access-token>",
|
|
||||||
"Ssl": false
|
|
||||||
},
|
|
||||||
"Replay": {
|
|
||||||
"StartTime": "2026-03-01T00:00:00+02:00",
|
|
||||||
"EndTime": "2026-03-31T00:00:00+02:00",
|
|
||||||
"Monitors": {
|
|
||||||
"NordPool": true,
|
|
||||||
"Boiler": true,
|
|
||||||
"Shower": true,
|
|
||||||
"Power": true,
|
|
||||||
"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,57 +0,0 @@
|
|||||||
body {
|
|
||||||
background-color: #1a1d21;
|
|
||||||
color: #e0e0e0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.card {
|
|
||||||
background-color: #212529;
|
|
||||||
border-color: #343a40;
|
|
||||||
}
|
|
||||||
|
|
||||||
.card-header {
|
|
||||||
background-color: #2b3035;
|
|
||||||
border-bottom-color: #343a40;
|
|
||||||
}
|
|
||||||
|
|
||||||
.stat-card {
|
|
||||||
text-align: center;
|
|
||||||
transition: transform 0.15s;
|
|
||||||
}
|
|
||||||
|
|
||||||
.stat-card:hover {
|
|
||||||
transform: translateY(-2px);
|
|
||||||
}
|
|
||||||
|
|
||||||
.stat-card .display-6 {
|
|
||||||
font-weight: 700;
|
|
||||||
}
|
|
||||||
|
|
||||||
.badge-decision { background-color: #198754; }
|
|
||||||
.badge-statechange { background-color: #0dcaf0; color: #000; }
|
|
||||||
.badge-warning { background-color: #ffc107; color: #000; }
|
|
||||||
.badge-anomaly { background-color: #dc3545; }
|
|
||||||
.badge-servicecall { background-color: #6f42c1; }
|
|
||||||
.badge-info { background-color: #6c757d; }
|
|
||||||
|
|
||||||
.nav-tabs .nav-link {
|
|
||||||
color: #adb5bd;
|
|
||||||
}
|
|
||||||
|
|
||||||
.nav-tabs .nav-link.active {
|
|
||||||
background-color: #212529;
|
|
||||||
border-color: #495057 #495057 #212529;
|
|
||||||
color: #e0e0e0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.table {
|
|
||||||
--bs-table-bg: transparent;
|
|
||||||
--bs-table-color: #e0e0e0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.status-bar {
|
|
||||||
min-height: 40px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.apexcharts-canvas {
|
|
||||||
background: transparent !important;
|
|
||||||
}
|
|
||||||
@@ -1,25 +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>
|
|
||||||
<Content Include="appsettings.json">
|
|
||||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
|
||||||
</Content>
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="10.0.5" />
|
|
||||||
<PackageReference Include="Microsoft.Extensions.Hosting" Version="10.0.5" />
|
|
||||||
<PackageReference Include="Microsoft.Extensions.Http" Version="10.0.5" />
|
|
||||||
<PackageReference Include="ModelContextProtocol" Version="1.2.0" />
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
</Project>
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
using HomeAssistant.McpServer.Services;
|
|
||||||
using HomeAssistant.McpServer.Settings;
|
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
|
||||||
using Microsoft.Extensions.Hosting;
|
|
||||||
using Microsoft.Extensions.Logging;
|
|
||||||
|
|
||||||
var builder = Host.CreateApplicationBuilder(new HostApplicationBuilderSettings
|
|
||||||
{
|
|
||||||
Args = args,
|
|
||||||
ContentRootPath = AppContext.BaseDirectory
|
|
||||||
});
|
|
||||||
|
|
||||||
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,118 +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,104 +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,79 +0,0 @@
|
|||||||
using System.ComponentModel;
|
|
||||||
using System.Text.Json;
|
|
||||||
using HomeAssistant.McpServer.Services;
|
|
||||||
using ModelContextProtocol.Server;
|
|
||||||
|
|
||||||
namespace HomeAssistant.McpServer.Tools;
|
|
||||||
|
|
||||||
[McpServerToolType]
|
|
||||||
public sealed class ServiceTools
|
|
||||||
{
|
|
||||||
private readonly IHomeAssistantApiClient _client;
|
|
||||||
|
|
||||||
public ServiceTools(IHomeAssistantApiClient client)
|
|
||||||
{
|
|
||||||
_client = client;
|
|
||||||
}
|
|
||||||
|
|
||||||
[McpServerTool, Description(
|
|
||||||
"List available Home Assistant services. Optionally filter by domain (e.g. 'light', 'climate', 'switch'). " +
|
|
||||||
"Each service shows its domain and available service names.")]
|
|
||||||
public async Task<string> ListServices(
|
|
||||||
[Description("Optional domain filter, e.g. 'light', 'climate'. Leave empty for all.")] string? domain = null,
|
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
var allServices = await _client.GetServicesAsync(cancellationToken).ConfigureAwait(false);
|
|
||||||
|
|
||||||
if (string.IsNullOrWhiteSpace(domain))
|
|
||||||
{
|
|
||||||
return FormatJson(allServices);
|
|
||||||
}
|
|
||||||
|
|
||||||
var filtered = allServices.EnumerateArray()
|
|
||||||
.Where(s => s.TryGetProperty("domain", out var d) &&
|
|
||||||
string.Equals(d.GetString(), domain, StringComparison.OrdinalIgnoreCase))
|
|
||||||
.ToList();
|
|
||||||
|
|
||||||
return JsonSerializer.Serialize(filtered, SerializerOptions);
|
|
||||||
}
|
|
||||||
|
|
||||||
[McpServerTool, Description(
|
|
||||||
"Call a Home Assistant service. Examples: domain='light', service='turn_on', entityId='light.living_room'. " +
|
|
||||||
"For services requiring extra data, pass it as a JSON string in serviceData.")]
|
|
||||||
public async Task<string> CallService(
|
|
||||||
[Description("Service domain, e.g. 'light', 'climate', 'switch', 'input_boolean'")] string domain,
|
|
||||||
[Description("Service name, e.g. 'turn_on', 'turn_off', 'set_temperature'")] string service,
|
|
||||||
[Description("Optional target entity ID, e.g. 'light.living_room'")] string? entityId = null,
|
|
||||||
[Description("Optional JSON service data, e.g. '{\"brightness\": 255}' or '{\"temperature\": 22}'")] string? serviceData = null,
|
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
JsonElement? data = null;
|
|
||||||
|
|
||||||
if (!string.IsNullOrWhiteSpace(serviceData) || !string.IsNullOrWhiteSpace(entityId))
|
|
||||||
{
|
|
||||||
var dataDict = string.IsNullOrWhiteSpace(serviceData)
|
|
||||||
? new Dictionary<string, object>()
|
|
||||||
: JsonSerializer.Deserialize<Dictionary<string, object>>(serviceData) ?? [];
|
|
||||||
|
|
||||||
if (!string.IsNullOrWhiteSpace(entityId))
|
|
||||||
{
|
|
||||||
dataDict["entity_id"] = entityId;
|
|
||||||
}
|
|
||||||
|
|
||||||
data = JsonSerializer.SerializeToElement(dataDict);
|
|
||||||
}
|
|
||||||
|
|
||||||
var result = await _client.CallServiceAsync(domain, service, data, cancellationToken)
|
|
||||||
.ConfigureAwait(false);
|
|
||||||
|
|
||||||
return FormatJson(result);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static string FormatJson(JsonElement element) =>
|
|
||||||
JsonSerializer.Serialize(element, SerializerOptions);
|
|
||||||
|
|
||||||
private static readonly JsonSerializerOptions SerializerOptions = new()
|
|
||||||
{
|
|
||||||
WriteIndented = true
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,52 +0,0 @@
|
|||||||
using System.ComponentModel;
|
|
||||||
using System.Text.Json;
|
|
||||||
using HomeAssistant.McpServer.Services;
|
|
||||||
using ModelContextProtocol.Server;
|
|
||||||
|
|
||||||
namespace HomeAssistant.McpServer.Tools;
|
|
||||||
|
|
||||||
[McpServerToolType]
|
|
||||||
public sealed class SystemTools
|
|
||||||
{
|
|
||||||
private readonly IHomeAssistantApiClient _client;
|
|
||||||
|
|
||||||
public SystemTools(IHomeAssistantApiClient client)
|
|
||||||
{
|
|
||||||
_client = client;
|
|
||||||
}
|
|
||||||
|
|
||||||
[McpServerTool, Description(
|
|
||||||
"Get Home Assistant configuration including version, location, components, and unit system. " +
|
|
||||||
"Useful for understanding the HA environment.")]
|
|
||||||
public async Task<string> GetHaConfig(CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
var result = await _client.GetConfigAsync(cancellationToken).ConfigureAwait(false);
|
|
||||||
return JsonSerializer.Serialize(result, SerializerOptions);
|
|
||||||
}
|
|
||||||
|
|
||||||
[McpServerTool, Description(
|
|
||||||
"Check if the Home Assistant API is reachable and responding. " +
|
|
||||||
"Returns the API status message or an error description.")]
|
|
||||||
public async Task<string> CheckApi(CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var result = await _client.GetApiStatusAsync(cancellationToken).ConfigureAwait(false);
|
|
||||||
return JsonSerializer.Serialize(result, SerializerOptions);
|
|
||||||
}
|
|
||||||
catch (HttpRequestException ex)
|
|
||||||
{
|
|
||||||
return JsonSerializer.Serialize(new { status = "error", message = ex.Message }, SerializerOptions);
|
|
||||||
}
|
|
||||||
catch (TaskCanceledException)
|
|
||||||
{
|
|
||||||
return JsonSerializer.Serialize(
|
|
||||||
new { status = "error", message = "Request timed out - HA may be unreachable" }, SerializerOptions);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static readonly JsonSerializerOptions SerializerOptions = new()
|
|
||||||
{
|
|
||||||
WriteIndented = true
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,310 +0,0 @@
|
|||||||
using System.Collections.Concurrent;
|
|
||||||
using System.ComponentModel;
|
|
||||||
using System.Text.Json;
|
|
||||||
using HomeAssistant.McpServer.Services;
|
|
||||||
using ModelContextProtocol.Server;
|
|
||||||
|
|
||||||
namespace HomeAssistant.McpServer.Tools;
|
|
||||||
|
|
||||||
[McpServerToolType]
|
|
||||||
public sealed class ValidationTools
|
|
||||||
{
|
|
||||||
private const string UnavailableState = "unavailable";
|
|
||||||
private const string UnknownState = "unknown";
|
|
||||||
private const int DefaultLogbookWindowMinutes = 30;
|
|
||||||
private const int MaxDegreeOfParallelism = 4;
|
|
||||||
|
|
||||||
private static readonly string[] CriticalDomains = ["sensor", "switch", "binary_sensor", "light"];
|
|
||||||
|
|
||||||
private static readonly JsonSerializerOptions SerializerOptions = new()
|
|
||||||
{
|
|
||||||
WriteIndented = true
|
|
||||||
};
|
|
||||||
|
|
||||||
private readonly IHomeAssistantApiClient _client;
|
|
||||||
|
|
||||||
public ValidationTools(IHomeAssistantApiClient client)
|
|
||||||
{
|
|
||||||
_client = client;
|
|
||||||
}
|
|
||||||
|
|
||||||
[McpServerTool, Description(
|
|
||||||
"Run a smoke test against the live Home Assistant environment. " +
|
|
||||||
"Checks API health, validates that critical entities are not unavailable/unknown, " +
|
|
||||||
"and verifies recent logbook activity for specified domains. " +
|
|
||||||
"Returns a structured pass/fail report.")]
|
|
||||||
public async Task<string> RunSmokeTest(
|
|
||||||
[Description(
|
|
||||||
"Comma-separated domains to check, e.g. 'switch,sensor,light'. " +
|
|
||||||
"Leave empty to check all critical domains (sensor, switch, binary_sensor, light).")]
|
|
||||||
string? domains = null,
|
|
||||||
[Description(
|
|
||||||
"Minutes of logbook history to scan for activity. Defaults to 30.")]
|
|
||||||
int? logbookWindowMinutes = null,
|
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
var targetDomains = ParseDomains(domains);
|
|
||||||
var windowMinutes = logbookWindowMinutes ?? DefaultLogbookWindowMinutes;
|
|
||||||
|
|
||||||
var apiHealthTask = CheckApiHealthAsync(cancellationToken);
|
|
||||||
var entityCheckTask = CheckEntitiesAsync(targetDomains, cancellationToken);
|
|
||||||
var logbookCheckTask = CheckRecentActivityAsync(windowMinutes, cancellationToken);
|
|
||||||
|
|
||||||
await Task.WhenAll(apiHealthTask, entityCheckTask, logbookCheckTask).ConfigureAwait(false);
|
|
||||||
|
|
||||||
var report = new
|
|
||||||
{
|
|
||||||
timestamp = DateTimeOffset.UtcNow,
|
|
||||||
apiHealth = await apiHealthTask.ConfigureAwait(false),
|
|
||||||
entityCheck = await entityCheckTask.ConfigureAwait(false),
|
|
||||||
recentActivity = await logbookCheckTask.ConfigureAwait(false),
|
|
||||||
overall = DetermineOverallStatus(
|
|
||||||
await apiHealthTask.ConfigureAwait(false),
|
|
||||||
await entityCheckTask.ConfigureAwait(false))
|
|
||||||
};
|
|
||||||
|
|
||||||
return JsonSerializer.Serialize(report, SerializerOptions);
|
|
||||||
}
|
|
||||||
|
|
||||||
[McpServerTool, Description(
|
|
||||||
"Assert that a specific Home Assistant entity has an expected state value. " +
|
|
||||||
"Returns a pass/fail result with the actual vs expected values and entity attributes.")]
|
|
||||||
public async Task<string> AssertEntityState(
|
|
||||||
[Description("Full entity ID, e.g. 'switch.boiler' or 'sensor.nordpool_current_price'")] string entityId,
|
|
||||||
[Description("Expected state value, e.g. 'on', 'off', '22.5'")] string expectedState,
|
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
var entity = await _client.GetEntityStateAsync(entityId, cancellationToken).ConfigureAwait(false);
|
|
||||||
|
|
||||||
var actualState = entity.TryGetProperty("state", out var stateProp)
|
|
||||||
? stateProp.GetString() ?? string.Empty
|
|
||||||
: string.Empty;
|
|
||||||
|
|
||||||
var passed = string.Equals(actualState, expectedState, StringComparison.OrdinalIgnoreCase);
|
|
||||||
|
|
||||||
var result = new
|
|
||||||
{
|
|
||||||
entityId,
|
|
||||||
expectedState,
|
|
||||||
actualState,
|
|
||||||
passed,
|
|
||||||
lastChanged = entity.TryGetProperty("last_changed", out var lc) ? lc.GetString() : null,
|
|
||||||
lastUpdated = entity.TryGetProperty("last_updated", out var lu) ? lu.GetString() : null
|
|
||||||
};
|
|
||||||
|
|
||||||
return JsonSerializer.Serialize(result, SerializerOptions);
|
|
||||||
}
|
|
||||||
|
|
||||||
[McpServerTool, Description(
|
|
||||||
"Validate multiple Home Assistant entities in parallel. " +
|
|
||||||
"Checks that each entity exists, is reachable, and is not in unavailable/unknown state. " +
|
|
||||||
"Optionally assert expected state values.")]
|
|
||||||
public async Task<string> ValidateEntities(
|
|
||||||
[Description(
|
|
||||||
"Comma-separated entity IDs to validate, e.g. 'switch.boiler,sensor.nordpool_current_price'")]
|
|
||||||
string entityIds,
|
|
||||||
[Description(
|
|
||||||
"Optional comma-separated expected states matching the entity IDs order. " +
|
|
||||||
"Use empty string to skip assertion for an entity, e.g. 'on,,42.5'")]
|
|
||||||
string? expectedStates = null,
|
|
||||||
CancellationToken cancellationToken = default)
|
|
||||||
{
|
|
||||||
var ids = entityIds.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
|
||||||
var states = expectedStates?.Split(',') ?? [];
|
|
||||||
|
|
||||||
var results = new ConcurrentBag<object>();
|
|
||||||
var parallelOptions = new ParallelOptions
|
|
||||||
{
|
|
||||||
MaxDegreeOfParallelism = MaxDegreeOfParallelism,
|
|
||||||
CancellationToken = cancellationToken
|
|
||||||
};
|
|
||||||
|
|
||||||
await Parallel.ForEachAsync(
|
|
||||||
ids.Select((id, index) => (id, index)),
|
|
||||||
parallelOptions,
|
|
||||||
async (item, ct) =>
|
|
||||||
{
|
|
||||||
var expectedState = item.index < states.Length
|
|
||||||
? states[item.index]?.Trim()
|
|
||||||
: null;
|
|
||||||
|
|
||||||
var result = await ValidateSingleEntityAsync(item.id, expectedState, ct).ConfigureAwait(false);
|
|
||||||
results.Add(result);
|
|
||||||
}).ConfigureAwait(false);
|
|
||||||
|
|
||||||
var ordered = results.Cast<dynamic>()
|
|
||||||
.OrderBy(r => (string)r.entityId)
|
|
||||||
.ToList();
|
|
||||||
|
|
||||||
var allPassed = ordered.All(r => (bool)r.passed);
|
|
||||||
|
|
||||||
var report = new
|
|
||||||
{
|
|
||||||
timestamp = DateTimeOffset.UtcNow,
|
|
||||||
passed = allPassed,
|
|
||||||
total = ordered.Count,
|
|
||||||
failed = ordered.Count(r => !(bool)r.passed),
|
|
||||||
entities = ordered
|
|
||||||
};
|
|
||||||
|
|
||||||
return JsonSerializer.Serialize(report, SerializerOptions);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static string[] ParseDomains(string? domains) =>
|
|
||||||
string.IsNullOrWhiteSpace(domains)
|
|
||||||
? CriticalDomains
|
|
||||||
: domains.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
|
||||||
|
|
||||||
private async Task<object> CheckApiHealthAsync(CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var status = await _client.GetApiStatusAsync(cancellationToken).ConfigureAwait(false);
|
|
||||||
var message = status.TryGetProperty("message", out var msg) ? msg.GetString() : "unknown";
|
|
||||||
return new { status = "healthy", message };
|
|
||||||
}
|
|
||||||
catch (HttpRequestException ex)
|
|
||||||
{
|
|
||||||
return new { status = "unreachable", message = ex.Message };
|
|
||||||
}
|
|
||||||
catch (TaskCanceledException)
|
|
||||||
{
|
|
||||||
return new { status = "timeout", message = "Home Assistant API did not respond in time" };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task<object> CheckEntitiesAsync(string[] targetDomains, CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
var allStates = await _client.GetAllStatesAsync(cancellationToken).ConfigureAwait(false);
|
|
||||||
var domainSet = new HashSet<string>(targetDomains, StringComparer.OrdinalIgnoreCase);
|
|
||||||
|
|
||||||
var unhealthy = new ConcurrentBag<object>();
|
|
||||||
var totalChecked = 0;
|
|
||||||
|
|
||||||
foreach (var entity in allStates.EnumerateArray())
|
|
||||||
{
|
|
||||||
if (!entity.TryGetProperty("entity_id", out var eidProp))
|
|
||||||
continue;
|
|
||||||
|
|
||||||
var entityId = eidProp.GetString() ?? string.Empty;
|
|
||||||
var entityDomain = entityId.Split('.').FirstOrDefault() ?? string.Empty;
|
|
||||||
|
|
||||||
if (!domainSet.Contains(entityDomain))
|
|
||||||
continue;
|
|
||||||
|
|
||||||
Interlocked.Increment(ref totalChecked);
|
|
||||||
|
|
||||||
if (!entity.TryGetProperty("state", out var stateProp))
|
|
||||||
continue;
|
|
||||||
|
|
||||||
var state = stateProp.GetString();
|
|
||||||
if (string.Equals(state, UnavailableState, StringComparison.OrdinalIgnoreCase) ||
|
|
||||||
string.Equals(state, UnknownState, StringComparison.OrdinalIgnoreCase))
|
|
||||||
{
|
|
||||||
unhealthy.Add(new
|
|
||||||
{
|
|
||||||
entityId,
|
|
||||||
state,
|
|
||||||
lastChanged = entity.TryGetProperty("last_changed", out var lc) ? lc.GetString() : null
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return new
|
|
||||||
{
|
|
||||||
passed = unhealthy.IsEmpty,
|
|
||||||
totalChecked,
|
|
||||||
unhealthyCount = unhealthy.Count,
|
|
||||||
unhealthyEntities = unhealthy.OrderBy(e => e.ToString()).ToList()
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task<object> CheckRecentActivityAsync(int windowMinutes, CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var startTime = DateTimeOffset.UtcNow.AddMinutes(-windowMinutes);
|
|
||||||
var logbook = await _client.GetLogbookAsync(
|
|
||||||
entityId: null,
|
|
||||||
startTime: startTime,
|
|
||||||
endTime: null,
|
|
||||||
cancellationToken: cancellationToken).ConfigureAwait(false);
|
|
||||||
|
|
||||||
var entryCount = logbook.ValueKind == JsonValueKind.Array ? logbook.GetArrayLength() : 0;
|
|
||||||
return new
|
|
||||||
{
|
|
||||||
windowMinutes,
|
|
||||||
entryCount,
|
|
||||||
hasActivity = entryCount > 0
|
|
||||||
};
|
|
||||||
}
|
|
||||||
catch (Exception ex)
|
|
||||||
{
|
|
||||||
return new
|
|
||||||
{
|
|
||||||
windowMinutes,
|
|
||||||
entryCount = 0,
|
|
||||||
hasActivity = false,
|
|
||||||
error = ex.Message
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static string DetermineOverallStatus(object apiHealth, object entityCheck)
|
|
||||||
{
|
|
||||||
var apiJson = JsonSerializer.SerializeToElement(apiHealth);
|
|
||||||
var entityJson = JsonSerializer.SerializeToElement(entityCheck);
|
|
||||||
|
|
||||||
var apiHealthy = apiJson.TryGetProperty("status", out var s) &&
|
|
||||||
string.Equals(s.GetString(), "healthy", StringComparison.OrdinalIgnoreCase);
|
|
||||||
|
|
||||||
var entitiesHealthy = entityJson.TryGetProperty("passed", out var p) && p.GetBoolean();
|
|
||||||
|
|
||||||
return apiHealthy && entitiesHealthy ? "PASS" : "FAIL";
|
|
||||||
}
|
|
||||||
|
|
||||||
private async Task<object> ValidateSingleEntityAsync(
|
|
||||||
string entityId,
|
|
||||||
string? expectedState,
|
|
||||||
CancellationToken cancellationToken)
|
|
||||||
{
|
|
||||||
try
|
|
||||||
{
|
|
||||||
var entity = await _client.GetEntityStateAsync(entityId, cancellationToken).ConfigureAwait(false);
|
|
||||||
|
|
||||||
var actualState = entity.TryGetProperty("state", out var stateProp)
|
|
||||||
? stateProp.GetString() ?? string.Empty
|
|
||||||
: string.Empty;
|
|
||||||
|
|
||||||
var isAvailable = !string.Equals(actualState, UnavailableState, StringComparison.OrdinalIgnoreCase) &&
|
|
||||||
!string.Equals(actualState, UnknownState, StringComparison.OrdinalIgnoreCase);
|
|
||||||
|
|
||||||
var stateMatch = string.IsNullOrEmpty(expectedState) ||
|
|
||||||
string.Equals(actualState, expectedState, StringComparison.OrdinalIgnoreCase);
|
|
||||||
|
|
||||||
return new
|
|
||||||
{
|
|
||||||
entityId,
|
|
||||||
actualState,
|
|
||||||
expectedState = expectedState ?? "(any)",
|
|
||||||
isAvailable,
|
|
||||||
stateMatch,
|
|
||||||
passed = isAvailable && stateMatch,
|
|
||||||
lastChanged = entity.TryGetProperty("last_changed", out var lc) ? lc.GetString() : null
|
|
||||||
};
|
|
||||||
}
|
|
||||||
catch (HttpRequestException)
|
|
||||||
{
|
|
||||||
return new
|
|
||||||
{
|
|
||||||
entityId,
|
|
||||||
actualState = "error",
|
|
||||||
expectedState = expectedState ?? "(any)",
|
|
||||||
isAvailable = false,
|
|
||||||
stateMatch = false,
|
|
||||||
passed = false,
|
|
||||||
lastChanged = (string?)null
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user