Compare commits

...

2 Commits

Author SHA1 Message Date
gitea_admin a9f329ffcd Remove the MCP server and split NordPool today/tomorrow fetch decisions
- Drop the HomeAssistant.McpServer wiring from opencode.json along with the
  Cursor live-validation hook, rule and skill; update AGENTS.md and README
- Rename ShouldFetchNewPrices to ShouldFetchTodaysPrices and add a separate
  ShouldFetchTomorrowPrice that waits until the CET publish hour
  (TomorrowPricesPublishHour)
- Inject TimeProvider into NordPoolPriceService, use the CET zone for the
  current date and record fetch timestamps from it
- Rework the NordPool tests around FakeTimeProvider and cover fetching only
  today before the publish hour
2026-12-01 13:46:19 +02:00
gitea_admin f919d6b25b Apply code formatting cleanup across the monitor projects
- Wrap using directives in `#region` blocks across the Battery, Boiler and NordPool sources and tests
- Expand single-statement guards and loops into braced blocks
- Realign wrapped method arguments, chained calls and continuations
- Replace target-typed `new()` with explicit generic construction and empty string literals with `string.Empty`
- Flatten the boiler config expression and reindent the remaining touched files
2026-12-01 12:33:31 +02:00
124 changed files with 3223 additions and 2273 deletions
-10
View File
@@ -1,10 +0,0 @@
{
"version": 1,
"hooks": {
"afterShellExecution": [
{
"command": "powershell -ExecutionPolicy Bypass -File .cursor/hooks/scripts/after-build-validate.ps1"
}
]
}
}
@@ -1,24 +0,0 @@
$input = [Console]::In.ReadToEnd()
$context = $input | ConvertFrom-Json
$command = $context.command
if (-not $command) { exit 0 }
$buildPatterns = @('dotnet build', 'dotnet run', 'dotnet publish')
$isBuildCommand = $false
foreach ($pattern in $buildPatterns) {
if ($command -match [regex]::Escape($pattern)) {
$isBuildCommand = $true
break
}
}
if (-not $isBuildCommand) { exit 0 }
$response = @{
message = "[Live Validation] Build command detected. Run live environment validation using the homeassistant MCP tools: 1) check_api to verify HA is reachable, 2) RunSmokeTest for a full health check, 3) ValidateEntities for the critical entities of the changed service."
} | ConvertTo-Json -Compress
Write-Output $response
exit 0
-46
View File
@@ -1,46 +0,0 @@
---
description: Require live environment validation after modifying monitor services
globs:
- "BoilerMonitor.Manager/**/*.cs"
- "BoilerMonitor.Models/**/*.cs"
- "LightMonitor.Manager/**/*.cs"
- "LightMonitor.Models/**/*.cs"
- "NordPool.Manager/**/*.cs"
- "NordPool.Models/**/*.cs"
- "PowerMonitor.Manager/**/*.cs"
- "PowerMonitor.Models/**/*.cs"
- "ShowerMonitor.Manager/**/*.cs"
- "ShowerMonitor.Models/**/*.cs"
- "HomeAssistant.McpServer/**/*.cs"
alwaysApply: false
---
# Live Validation Required
After modifying any Monitor service, Manager, or Models code, the agent MUST validate the change works in the live Home Assistant environment before considering the task complete.
## Mandatory Steps
1. **Build** — run `dotnet build` on the affected project to confirm compilation.
2. **Smoke test** — use the `RunSmokeTest` MCP tool (from the `homeassistant` MCP server) with domains relevant to the changed service.
3. **Entity check** — use `ValidateEntities` to confirm critical entities for the changed service are not `unavailable` or `unknown`.
## Domain Mapping
| Service Changed | MCP Domains to Check |
|---|---|
| BoilerMonitor | `switch,sensor,binary_sensor` |
| LightMonitor | `light,person,sun` |
| NordPool | `sensor` |
| PowerMonitor | `sensor` |
| ShowerMonitor | `sensor,switch` |
## When to Skip
- If the Home Assistant instance is offline (check via `check_api` first)
- If changes are purely to unit tests, documentation, or non-runtime code
- If the user explicitly says to skip validation
## On Failure
Report the specific entities that failed validation and their current states. Do not silently proceed.
-96
View File
@@ -1,96 +0,0 @@
# Live Environment Validation
Validate that code changes work correctly against the live Home Assistant instance using MCP tools.
## Triggers
Use when:
- The user says "validate", "check live", "smoke test", "verify live environment"
- After deploying or restarting the app daemon
- After modifying any Monitor/Manager service and wanting to confirm it works
- When the live-validation rule fires (after editing monitor service files)
## Prerequisites
- The Home Assistant instance must be running and reachable
- The `homeassistant` MCP server must be connected in Cursor
## Validation Workflow
### Step 1: Build Verification
Run `dotnet build` for the solution or affected project to confirm compilation succeeds.
```
dotnet build HomeAssistantSDK.sln --no-restore
```
If the build fails, stop and fix compilation errors before proceeding.
### Step 2: API Health Check
Use the `homeassistant` MCP tool `check_api` to verify the HA instance is reachable.
If the API is unreachable, report the failure and stop — no further validation is possible.
### Step 3: Smoke Test
Use the `homeassistant` MCP tool `RunSmokeTest` to run a full environment check:
- Pass the relevant domains based on what was changed
- Check the `overall` field for PASS/FAIL
- Review any unhealthy entities
Domain mapping for changed services:
- **BoilerMonitor** → `switch,sensor,binary_sensor,number,text`
- **LightMonitor** → `light,person,sun`
- **NordPool** → `sensor`
- **PowerMonitor** → `sensor`
- **ShowerMonitor** → `sensor,switch`
### Step 4: Entity-Specific Validation
Based on which service was changed, validate its critical entities using the `ValidateEntities` MCP tool:
**BoilerMonitor entities:**
- `sensor.boilermonitor_status`
- `sensor.boilermonitor_water_ready`
- `sensor.boilermonitor_estimated_temperature`
- `sensor.boilermonitor_heating_percentage`
**LightMonitor entities:**
- `light.sonoff_1002214d40`
- `sun.sun`
- `person.marius`, `person.erika`
**NordPool entities:**
- `sensor.nordpool_current_price`
**PowerMonitor entities:**
- Power sensor entities configured in the system
### Step 5: Behavioral Validation (Optional)
For deeper validation, use the `get_logbook` MCP tool filtered to the relevant entity with a 30-minute window to confirm the service is producing expected state changes.
Use `get_entity_history` for trend validation — verify values are within expected ranges.
### Step 6: Report
Summarize results:
1. Build status (pass/fail)
2. API health (reachable/unreachable)
3. Smoke test result (PASS/FAIL with details)
4. Entity validation results (list any failures)
5. Logbook activity summary (if performed)
If everything passes, confirm with a brief "Live validation passed" message.
If anything fails, list specific failures with entity IDs and current states.
## Browser Validation (HistoryReplay UI)
If the `HomeAssistant.HistoryReplay` Blazor app is running, use the `cursor-ide-browser` MCP to:
1. Navigate to the dashboard URL
2. Take a screenshot to verify charts render correctly
3. Check console for JavaScript errors
This is optional and only applies when HistoryReplay changes are involved.
+3 -32
View File
@@ -13,9 +13,8 @@ before editing; it only records things that are easy to get wrong.
## Stack
- .NET 10 / C# 14 (`LangVersion=14.0`, set per-csproj in the three
executable projects — `HomeAssistant.Server`, `HomeAssistant.McpServer`,
`HomeAssistant.HistoryReplay`; no `Directory.Build.props`). `global.json`
- .NET 10 / C# 14 (`LangVersion=14.0`, set in `HomeAssistant.Server.csproj`;
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
@@ -69,12 +68,6 @@ before editing; it only records things that are easy to get wrong.
(`GlobalMappingProfile`, `NordPoolMappingProfile` + `DateTimeTypeConverter`)
referenced by `HomeAssistant.Server`; wired in `program.cs` via
`config.AddProfile<…>()`. AutoMapper 16.1.1.
- `HomeAssistant.McpServer` is a separate stdio MCP server
(ModelContextProtocol NuGet 1.2.0) exposing HA tools. It is **not**
referenced by the host; it runs standalone via
`dotnet run --project HomeAssistant.McpServer`. It is wired as the
`homeassistant` MCP server in both `.cursor/mcp.json` (git-ignored) and
the committed `opencode.json` at the repo root.
- `HomeAssistant.HistoryReplay` is a Blazor debug web app that replays HA
history through monitor business logic with no side effects. It
references a subset of monitors (Boiler, NordPool, Power, Shower, Light —
@@ -115,23 +108,6 @@ Singletons are only safe for services that take **no** scoped dependency
(pure calculators, trackers with no `IHaContext`). When unsure, register
scoped.
## Live validation after monitor edits
`.cursor/rules/live-validation.mdc` (globs: all `*.Manager`/`*.Models` of
Boiler, Light, NordPool, Power, Shower, plus `HomeAssistant.McpServer` —
**not** Battery or Leak) requires, after editing monitor runtime code:
1. `dotnet build` the affected project.
2. `RunSmokeTest` MCP tool from the `homeassistant` MCP server.
3. `ValidateEntities` for the changed service's critical entities.
Domain → entity mapping is in the rule file. Skip when HA is offline (check
via `check_api`), when changes are tests/docs/non-runtime, or when the user
says to skip. On failure, report the failing entities + states; do not
silently proceed. This rule is Cursor-specific but the intent applies to
OpenCode sessions too — if you have the `homeassistant` MCP server
available, follow the same flow.
## Commands
Build everything:
@@ -152,10 +128,6 @@ Run the host (needs HA reachable + token in `appsettings.Development.json`):
```
dotnet run --project HomeAssistant.Server
```
Run the MCP server standalone:
```
dotnet run --project HomeAssistant.McpServer
```
Run the history replay web app:
```
dotnet run --project HomeAssistant.HistoryReplay
@@ -187,8 +159,7 @@ prints the reminder after publish.
replay tool requires a new project reference there too.
- The repository folder name is misspelled `homeassistant-app-deamon`
(should be `daemon`). This is intentional/legacy — do not "fix" it in
paths; `opencode.json` and `.cursor/mcp.json` reference the workspace
folder by macro.
paths.
- 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
@@ -1,3 +1,5 @@
#region
using System.Globalization;
using System.Text.Json;
using BatteryMonitor.Models;
@@ -5,6 +7,8 @@ using Moq;
using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
#endregion
namespace BatteryMonitor.Manager.Tests;
/// <summary>
@@ -20,7 +24,7 @@ internal static class BatteryMonitorTestData
/// (threshold, state, expected) rows straddling the strict <c>level &lt; threshold</c>
/// boundary, including zero/negative thresholds and int min/max thresholds.
/// </summary>
public static TheoryData<int, string, bool> ThresholdBoundaryRows { get; } = new()
public static TheoryData<int, string, bool> ThresholdBoundaryRows { get; } = new TheoryData<int, string, bool>
{
{ 5, "4", true },
{ 5, "5", false },
@@ -59,7 +63,7 @@ internal static class BatteryMonitorTestData
"unknown",
"UNAVAILABLE",
"UNKNOWN",
"",
string.Empty,
" ",
"\t",
"not_a_number",
@@ -85,7 +89,9 @@ internal static class BatteryMonitorTestData
}
/// <summary>A sensor with an arbitrary (or missing) device class.</summary>
public static EntitySpec Sensor(string entityId, string? deviceClass, string? state,
public static EntitySpec Sensor(string entityId,
string? deviceClass,
string? state,
string? friendlyName = DefaultFriendlyName)
{
return new EntitySpec
@@ -101,9 +107,15 @@ internal static class BatteryMonitorTestData
{
var attributes = new Dictionary<string, object?>(StringComparer.Ordinal);
if (spec.DeviceClass is not null) attributes["device_class"] = spec.DeviceClass;
if (spec.DeviceClass is not null)
{
attributes["device_class"] = spec.DeviceClass;
}
if (spec.FriendlyName is not null) attributes["friendly_name"] = spec.FriendlyName;
if (spec.FriendlyName is not null)
{
attributes["friendly_name"] = spec.FriendlyName;
}
return new EntityState
{
@@ -122,7 +134,10 @@ internal static class BatteryMonitorTestData
foreach (var spec in entities)
{
if (spec.HasState) haContextMock.Setup(h => h.GetState(spec.EntityId)).Returns(CreateEntityState(spec));
if (spec.HasState)
{
haContextMock.Setup(h => h.GetState(spec.EntityId)).Returns(CreateEntityState(spec));
}
entityList.Add(new Entity(haContextMock.Object, spec.EntityId));
}
@@ -202,7 +217,7 @@ internal static class BatteryMonitorTestData
data.Add("sensor.boiler_temp_battery", false);
data.Add("sensor.aquarium_leak_sensor_battery", false);
data.Add("sensor.temperature", false);
data.Add("", false);
data.Add(string.Empty, false);
data.Add(" ", false);
return data;
@@ -1,3 +1,5 @@
#region
using System.Text.Json;
using BatteryMonitor.Models;
using BatteryMonitorManager;
@@ -8,12 +10,14 @@ using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
using static BatteryMonitor.Manager.Tests.BatteryMonitorTestData;
#endregion
namespace BatteryMonitor.Manager.Tests;
public class BatteryNotificationServiceTests
{
private readonly Mock<IHaContext> _haContextMock = new();
private readonly Mock<ILogger<BatteryNotificationService>> _loggerMock = new();
private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
private readonly Mock<ILogger<BatteryNotificationService>> _loggerMock = new Mock<ILogger<BatteryNotificationService>>();
private BatteryNotificationService CreateSut()
{
@@ -65,6 +69,7 @@ public class BatteryNotificationServiceTests
It.IsAny<string>(),
It.IsAny<ServiceTarget?>(),
It.IsAny<object?>()), Times.Never);
_loggerMock.Invocations.Should().BeEmpty();
}
@@ -72,6 +77,7 @@ public class BatteryNotificationServiceTests
public void NotifyLowBattery_ShouldSendTitleNotificationIdAndDeviceSummary()
{
object? payload = null;
_haContextMock
.Setup(h => h.CallService(
BatteryMonitorConsts.PersistentNotificationDomain,
@@ -81,6 +87,7 @@ public class BatteryNotificationServiceTests
.Callback<string, string, ServiceTarget?, object?>((_, _, _, data) => payload = data);
var sut = CreateSut();
sut.NotifyLowBattery(CreateSensorInfos(
("sensor.a", "Device A", 4),
("sensor.b", "Device B", 1)));
@@ -101,6 +108,7 @@ public class BatteryNotificationServiceTests
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));
@@ -110,7 +118,9 @@ public class BatteryNotificationServiceTests
var logInvocation = _loggerMock.Invocations
.Where(invocation => invocation.Method.Name == nameof(ILogger.Log))
.Should().ContainSingle().Subject;
.Should()
.ContainSingle()
.Subject;
logInvocation.Arguments[0].Should().Be(LogLevel.Information);
logInvocation.Arguments[2].Should().NotBeNull();
@@ -139,7 +149,10 @@ public class BatteryNotificationServiceTests
{
var sut = CreateSut();
for (var i = 0; i < calls; i++) sut.DismissNotification();
for (var i = 0; i < calls; i++)
{
sut.DismissNotification();
}
VerifyCallService(BatteryMonitorConsts.PersistentNotificationDismissService, Times.Exactly(calls));
VerifyCallService(BatteryMonitorConsts.PersistentNotificationCreateService, Times.Never());
@@ -219,7 +232,8 @@ public class BatteryNotificationServiceTests
[InlineData("Full Battery", 100, "- **Full Battery**: 100%")]
[InlineData("", 5, "- ****: 5%")]
[InlineData(" ", 4, "- ** **: 4%")]
public void BuildNotificationMessage_ShouldFormatDeviceLine(string friendlyName, double batteryLevel,
public void BuildNotificationMessage_ShouldFormatDeviceLine(string friendlyName,
double batteryLevel,
string expectedLine)
{
var devices = CreateSensorInfos(("sensor.a", friendlyName, batteryLevel));
@@ -1,3 +1,5 @@
#region
using System.Globalization;
using BatteryMonitor.Models;
using BatteryMonitorManager;
@@ -8,12 +10,14 @@ using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
using static BatteryMonitor.Manager.Tests.BatteryMonitorTestData;
#endregion
namespace BatteryMonitor.Manager.Tests;
public class BatterySensorDiscoveryServiceTests
{
private readonly Mock<IHaContext> _haContextMock = new();
private readonly Mock<ILogger<BatterySensorDiscoveryService>> _loggerMock = new();
private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
private readonly Mock<ILogger<BatterySensorDiscoveryService>> _loggerMock = new Mock<ILogger<BatterySensorDiscoveryService>>();
private BatterySensorDiscoveryService CreateSut()
{
@@ -137,7 +141,8 @@ public class BatterySensorDiscoveryServiceTests
[Theory]
[MemberData(nameof(ThresholdBoundaryRows), MemberType = typeof(BatteryMonitorTestData))]
public void DiscoverLowBatterySensors_ShouldApplyStrictThresholdBoundary(int thresholdPercent, string state,
public void DiscoverLowBatterySensors_ShouldApplyStrictThresholdBoundary(int thresholdPercent,
string state,
bool expectedIncluded)
{
SetupEntities(Battery("sensor.boundary_battery", state, "Boundary Battery"));
@@ -147,7 +152,10 @@ public class BatterySensorDiscoveryServiceTests
result.Should().HaveCount(expectedIncluded ? 1 : 0);
if (!expectedIncluded) return;
if (!expectedIncluded)
{
return;
}
result[0].EntityId.Should().Be("sensor.boundary_battery");
result[0].BatteryLevel.Should().Be(double.Parse(state, CultureInfo.InvariantCulture));
@@ -250,7 +258,9 @@ public class BatterySensorDiscoveryServiceTests
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()
result.Select(s => s.FriendlyName)
.Should()
.OnlyContain(name => name.StartsWith("Generated Battery", StringComparison.Ordinal));
}
@@ -1,3 +1,5 @@
#region
using System.Reactive.Concurrency;
using BatteryMonitor.Models;
using BatteryMonitorManager.Interface;
@@ -7,6 +9,8 @@ using Microsoft.Extensions.Options;
using NetDaemon.AppModel;
using NetDaemon.Extensions.Scheduler;
#endregion
namespace BatteryMonitorManager;
[NetDaemonApp]
@@ -64,6 +68,7 @@ public sealed class BatteryMonitorInit
catch (Exception ex)
{
_logger.LogError(ex, "Error initializing BatteryMonitor");
throw;
}
}
@@ -1,9 +1,13 @@
#region
using BatteryMonitorManager.Interface;
using BatteryMonitorManager.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using NetDaemon.AppModel;
#endregion
namespace BatteryMonitorManager;
public static class BatteryMonitorServiceRegistration
@@ -12,9 +16,13 @@ public static class BatteryMonitorServiceRegistration
{
var options = configuration
.GetSection(BatteryMonitorOptions.SectionName)
.Get<BatteryMonitorOptions>() ?? new BatteryMonitorOptions();
.Get<BatteryMonitorOptions>() ??
new BatteryMonitorOptions();
if (!options.Enabled) return services;
if (!options.Enabled)
{
return services;
}
services
.AddNetDaemonApp<BatteryMonitorInit>()
@@ -1,9 +1,13 @@
#region
using System.Text;
using BatteryMonitor.Models;
using BatteryMonitorManager.Interface;
using Microsoft.Extensions.Logging;
using NetDaemon.HassModel;
#endregion
namespace BatteryMonitorManager;
public sealed class BatteryNotificationService(
@@ -12,7 +16,10 @@ public sealed class BatteryNotificationService(
{
public void NotifyLowBattery(IReadOnlyList<BatterySensorInfo> lowBatteryDevices)
{
if (lowBatteryDevices.Count == 0) return;
if (lowBatteryDevices.Count == 0)
{
return;
}
var message = BuildNotificationMessage(lowBatteryDevices);
@@ -54,7 +61,9 @@ public sealed class BatteryNotificationService(
sb.AppendLine();
foreach (var device in devices.OrderBy(d => d.BatteryLevel))
{
sb.AppendLine($"- **{device.FriendlyName}**: {device.BatteryLevel:F0}%");
}
return sb.ToString().TrimEnd();
}
@@ -1,3 +1,5 @@
#region
using System.Globalization;
using System.Text.Json;
using BatteryMonitor.Models;
@@ -6,6 +8,8 @@ using Microsoft.Extensions.Logging;
using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
#endregion
namespace BatteryMonitorManager;
public sealed class BatterySensorDiscoveryService(
@@ -79,10 +83,12 @@ public sealed class BatterySensorDiscoveryService(
return null;
}
if (batteryLevel >= thresholdPercent) return null;
if (batteryLevel >= thresholdPercent)
{
return null;
}
var friendlyName = GetJsonStringProperty(entity.EntityState?.AttributesJson, "friendly_name")
?? entity.EntityId;
var friendlyName = GetJsonStringProperty(entity.EntityState?.AttributesJson, "friendly_name") ?? entity.EntityId;
return new BatterySensorInfo
{
@@ -94,7 +100,10 @@ public sealed class BatterySensorDiscoveryService(
private static string? GetJsonStringProperty(JsonElement? element, string propertyName)
{
if (element is null) return null;
if (element is null)
{
return null;
}
return element.Value.TryGetProperty(propertyName, out var value)
? value.GetString()
@@ -1,5 +1,9 @@
#region
using BatteryMonitor.Models;
#endregion
namespace BatteryMonitorManager.Interface;
public interface IBatteryNotificationService
@@ -1,5 +1,9 @@
#region
using BatteryMonitor.Models;
#endregion
namespace BatteryMonitorManager.Interface;
public interface IBatterySensorDiscoveryService
@@ -1,5 +1,9 @@
#region
using BatteryMonitor.Models;
#endregion
namespace BatteryMonitorManager.Models;
public sealed class BatteryMonitorOptions
@@ -1,14 +1,18 @@
#region
using BoilerMonitor.Models.Enums;
using BoilerMonitorManager;
using FluentAssertions;
using Microsoft.Extensions.Logging;
using Moq;
#endregion
namespace BoilerMonitor.Manager.Tests;
public class BoilerControlServiceTests
{
private readonly Mock<ILogger<BoilerControlService>> _loggerMock = new();
private readonly Mock<ILogger<BoilerControlService>> _loggerMock = new Mock<ILogger<BoilerControlService>>();
private BoilerControlService CreateSut()
{
@@ -34,7 +38,8 @@ public class BoilerControlServiceTests
bool budgetExhausted,
bool budgetOverride)
{
var result = CreateSut().DetermineAction(
var result = CreateSut()
.DetermineAction(
isNowCheap, waterReady, switchState, budgetExhausted, budgetOverride);
result.Should().Be(BoilerAction.NoChange);
@@ -57,7 +62,8 @@ public class BoilerControlServiceTests
[InlineData("0")]
public void DetermineAction_WhenCheapAndWaterNotReadyAndBudgetAvailable_ShouldReturnTurnOn(string? switchState)
{
var result = CreateSut().DetermineAction(
var result = CreateSut()
.DetermineAction(
true, false, switchState,
false, false);
@@ -75,7 +81,8 @@ public class BoilerControlServiceTests
string? switchState,
BoilerAction expectedAction)
{
var result = CreateSut().DetermineAction(
var result = CreateSut()
.DetermineAction(
true, false, switchState,
true, true);
@@ -93,7 +100,8 @@ public class BoilerControlServiceTests
[InlineData("oN")]
public void DetermineAction_WhenNotCheapAndSwitchIsOn_ShouldReturnTurnOff(string switchState)
{
var result = CreateSut().DetermineAction(
var result = CreateSut()
.DetermineAction(
false, false, switchState,
false, false);
@@ -109,7 +117,8 @@ public class BoilerControlServiceTests
bool budgetExhausted,
bool budgetOverride)
{
var result = CreateSut().DetermineAction(
var result = CreateSut()
.DetermineAction(
true, waterReady, "on",
budgetExhausted, budgetOverride);
@@ -124,7 +133,7 @@ public class BoilerControlServiceTests
/// 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()
public static TheoryData<bool, bool, bool, bool, BoilerAction> SwitchOnActionMatrix => new TheoryData<bool, bool, bool, bool, BoilerAction>
{
{ false, false, false, false, BoilerAction.TurnOff },
{ false, false, false, true, BoilerAction.TurnOff },
@@ -153,7 +162,8 @@ public class BoilerControlServiceTests
bool budgetOverride,
BoilerAction expectedAction)
{
var result = CreateSut().DetermineAction(
var result = CreateSut()
.DetermineAction(
isNowCheap, waterReady, "on", budgetExhausted, budgetOverride);
result.Should().Be(expectedAction);
@@ -163,7 +173,7 @@ public class BoilerControlServiceTests
/// 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()
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 },
@@ -192,7 +202,8 @@ public class BoilerControlServiceTests
bool budgetOverride,
BoilerAction expectedAction)
{
var result = CreateSut().DetermineAction(
var result = CreateSut()
.DetermineAction(
isNowCheap, waterReady, "off", budgetExhausted, budgetOverride);
result.Should().Be(expectedAction);
@@ -1,5 +1,9 @@
#region
using FluentAssertions;
#endregion
namespace BoilerMonitor.Manager.Tests;
public class BoilerMonitorConfigTests
@@ -7,7 +11,7 @@ public class BoilerMonitorConfigTests
private const string PowerEntityId = BoilerMonitorTestData.PowerEntityId;
private const string SwitchEntityId = BoilerMonitorTestData.SwitchEntityId;
public static TheoryData<string, string?, string?, int?, double?, bool> ConfigurationCases => new()
public static TheoryData<string, string?, string?, int?, double?, bool> ConfigurationCases => new TheoryData<string, string?, string?, int?, double?, bool>
{
{ "fully configured", PowerEntityId, SwitchEntityId, 30, 5.0, true },
{ "minimum valid poll interval and threshold", PowerEntityId, SwitchEntityId, 5, 1.0, true },
@@ -18,11 +22,11 @@ public class BoilerMonitorConfigTests
{ "infinite threshold", PowerEntityId, SwitchEntityId, 30, double.PositiveInfinity, true },
{ "power entity id null", null, SwitchEntityId, 30, 5.0, false },
{ "power entity id empty", "", 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, "", 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 },
@@ -1,3 +1,5 @@
#region
using System.Text.Json;
using BoilerMonitorManager;
using FluentAssertions;
@@ -8,6 +10,8 @@ using Moq;
using NetDaemon.HassModel;
using static BoilerMonitor.Models.BoilerMonitorConsts;
#endregion
namespace BoilerMonitor.Manager.Tests;
public class BoilerMonitorEntityServiceTests
@@ -31,18 +35,21 @@ public class BoilerMonitorEntityServiceTests
AutoManagementEntityId
];
private readonly Mock<IEntityManager> _entityManagerMock = new();
private readonly Mock<IHaContext> _haContextMock = new();
private readonly Mock<ILogger<BoilerMonitorEntityService>> _loggerMock = new();
private readonly Mock<IEntityManager> _entityManagerMock = new Mock<IEntityManager>();
private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
private readonly Mock<ILogger<BoilerMonitorEntityService>> _loggerMock = new Mock<ILogger<BoilerMonitorEntityService>>();
public BoilerMonitorEntityServiceTests()
{
_entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny<EntityCreateModel>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.RemoveEntity(It.IsAny<string>()))
.Returns(Task.CompletedTask);
}
@@ -71,6 +78,7 @@ public class BoilerMonitorEntityServiceTests
if (expectedRunTime is null)
{
result.Should().BeNull();
return;
}
@@ -93,6 +101,7 @@ public class BoilerMonitorEntityServiceTests
if (expectedSessionCount is null)
{
result.Should().BeNull();
return;
}
@@ -151,6 +160,7 @@ public class BoilerMonitorEntityServiceTests
public void ReadPersistedCooldownTimestamp_WithValidIsoString_ShouldReturnTimestamp()
{
var cooldownSince = BoilerMonitorTestData.BaseTime - TimeSpan.FromMinutes(30);
_haContextMock.SetupEntityState(
WaterReadyEntityId,
BoilerMonitorTestData.CreateWaterReadyEntityStateWithCooldown(cooldownSince.ToString("O")));
@@ -164,6 +174,7 @@ public class BoilerMonitorEntityServiceTests
public void ReadPersistedCooldownTimestamp_WithUtcDesignator_ShouldReturnTimestamp()
{
var cooldownSince = new DateTimeOffset(2026, 3, 31, 9, 15, 0, TimeSpan.Zero);
_haContextMock.SetupEntityState(
WaterReadyEntityId,
BoilerMonitorTestData.CreateWaterReadyEntityStateWithCooldown("2026-03-31T09:15:00Z"));
@@ -260,6 +271,7 @@ public class BoilerMonitorEntityServiceTests
_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));
}
@@ -276,7 +288,8 @@ public class BoilerMonitorEntityServiceTests
double budgetPercentage,
string expectedState)
{
await CreateSut().UpdateEntitiesAsync(
await CreateSut()
.UpdateEntitiesAsync(
BoilerMonitorTestData.CreateUpdateContext(budgetPercentage: budgetPercentage));
_entityManagerMock.Verify(
@@ -291,7 +304,8 @@ public class BoilerMonitorEntityServiceTests
[InlineData(3600, "3600")]
public async Task UpdateEntitiesAsync_ShouldClampAndTruncateRemainingTime(int seconds, string expectedState)
{
await CreateSut().UpdateEntitiesAsync(
await CreateSut()
.UpdateEntitiesAsync(
BoilerMonitorTestData.CreateUpdateContext(remainingTime: TimeSpan.FromSeconds(seconds)));
_entityManagerMock.Verify(em => em.SetEntityState(RemainingTimeEntityId, expectedState), Times.Once);
@@ -305,7 +319,8 @@ public class BoilerMonitorEntityServiceTests
[InlineData(86_400.0, "86400")]
public async Task UpdateEntitiesAsync_ShouldTruncateTodayRunTimeToWholeSeconds(double seconds, string expectedState)
{
await CreateSut().UpdateEntitiesAsync(
await CreateSut()
.UpdateEntitiesAsync(
BoilerMonitorTestData.CreateUpdateContext(TimeSpan.FromSeconds(seconds)));
_entityManagerMock.Verify(em => em.SetEntityState(TodayRuntimeEntityId, expectedState), Times.Once);
@@ -315,12 +330,14 @@ public class BoilerMonitorEntityServiceTests
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(
await CreateSut()
.UpdateEntitiesAsync(BoilerMonitorTestData.CreateUpdateContext(
waterReady: false,
boilerSwitchState: null,
boilerPowerWatts: 1234.5));
@@ -338,12 +355,14 @@ public class BoilerMonitorEntityServiceTests
{
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(
await CreateSut()
.UpdateEntitiesAsync(
BoilerMonitorTestData.CreateUpdateContext(cooldownSince: cooldownSince));
var attributes = JsonSerializer.SerializeToElement(capturedAttributes!);
@@ -358,6 +377,7 @@ public class BoilerMonitorEntityServiceTests
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))
@@ -366,7 +386,9 @@ public class BoilerMonitorEntityServiceTests
await CreateSut().CreateEntitiesAsync();
createdEntityIds.Should().HaveCount(15).And.OnlyHaveUniqueItems();
createdEntityIds.Should().Contain(
createdEntityIds.Should()
.Contain(
[
ConfigPowerEntityId,
ConfigSwitchEntityId,
@@ -391,16 +413,18 @@ public class BoilerMonitorEntityServiceTests
var act = () => CreateSut().CreateEntitiesAsync();
await act.Should().NotThrowAsync();
_entityManagerMock.Invocations
.Count(invocation => invocation.Method.Name == nameof(IEntityManager.CreateEntityAsync))
.Should().Be(15);
.Should()
.Be(15);
}
#endregion
#region ResetEntitiesAsync
public static TheoryData<string, string> ResetEntityStates => new()
public static TheoryData<string, string> ResetEntityStates => new TheoryData<string, string>
{
{ StatusEntityId, StatusAwaitingConfiguration },
{ WaterReadyEntityId, "unknown" },
@@ -422,6 +446,7 @@ public class BoilerMonitorEntityServiceTests
_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));
}
@@ -486,7 +511,9 @@ public class BoilerMonitorEntityServiceTests
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));
@@ -536,6 +563,7 @@ public class BoilerMonitorEntityServiceTests
{
var canceledToken = new CancellationToken(true);
var sut = CreateSut();
Func<Task> act = operation switch
{
CancelableOperation.CreateEntities => () => sut.CreateEntitiesAsync(canceledToken),
@@ -1,6 +1,10 @@
#region
using BoilerMonitorManager.Models;
using FluentAssertions;
#endregion
namespace BoilerMonitor.Manager.Tests;
public class BoilerMonitorOptionsTests
@@ -1,3 +1,5 @@
#region
using System.Text.Json;
using BoilerMonitorManager.Models;
using Microsoft.Extensions.Time.Testing;
@@ -6,6 +8,8 @@ using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
using static BoilerMonitor.Models.BoilerMonitorConsts;
#endregion
namespace BoilerMonitor.Manager.Tests;
/// <summary>
@@ -19,7 +23,7 @@ internal static class BoilerMonitorTestData
public const string SwitchEntityId = "switch.sonoff_1002230e32";
/// <summary>Fixed "now" (UTC) used by every time based test.</summary>
public static readonly DateTimeOffset BaseTime = new(2026, 3, 31, 12, 0, 0, TimeSpan.Zero);
public static readonly DateTimeOffset BaseTime = new DateTimeOffset(2026, 3, 31, 12, 0, 0, TimeSpan.Zero);
public static FakeTimeProvider CreateTimeProvider(DateTimeOffset? utcNow = null)
{
@@ -147,7 +151,7 @@ internal static class BoilerMonitorTestData
data.Add("1e9", TimeSpan.FromSeconds(1e9));
data.Add(null, null);
data.Add("", null);
data.Add(string.Empty, null);
data.Add(" ", null);
data.Add("\t", null);
data.Add("unavailable", null);
@@ -159,6 +163,7 @@ internal static class BoilerMonitorTestData
data.Add("1e308", null);
data.Add("-1", null);
data.Add("-0.001", null);
return data;
}
@@ -175,7 +180,7 @@ internal static class BoilerMonitorTestData
data.Add("2147483647", int.MaxValue);
data.Add(null, null);
data.Add("", null);
data.Add(string.Empty, null);
data.Add(" ", null);
data.Add("\t", null);
data.Add("unavailable", null);
@@ -185,6 +190,7 @@ internal static class BoilerMonitorTestData
data.Add("-1", null);
data.Add("2147483648", null);
data.Add("1e3", null);
return data;
}
@@ -204,6 +210,7 @@ internal static class BoilerMonitorTestData
data.Add("actively heating", 2_150.0, false);
data.Add("maximum", double.MaxValue, false);
data.Add("not-a-number", double.NaN, true);
return data;
}
@@ -222,6 +229,7 @@ internal static class BoilerMonitorTestData
data.Add(TimeSpan.FromHours(25));
data.Add(TimeSpan.FromHours(48));
data.Add(TimeSpan.FromHours(168));
return data;
}
@@ -251,6 +259,7 @@ internal static class BoilerMonitorTestData
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)),
@@ -273,6 +282,7 @@ internal static class BoilerMonitorTestData
new DateTimeOffset(2026, 3, 31, 23, 59, 59, TimeSpan.Zero),
false
);
return data;
}
@@ -1,3 +1,5 @@
#region
using BoilerMonitor.Models;
using BoilerMonitorManager;
using FluentAssertions;
@@ -5,6 +7,8 @@ using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Time.Testing;
using Moq;
#endregion
namespace BoilerMonitor.Manager.Tests;
public class WaterReadyServiceTests
@@ -13,7 +17,7 @@ public class WaterReadyServiceTests
private const double HighPowerWatts = 2150.0;
private const int RequiredReadings = BoilerMonitorConsts.ConsecutiveReadingsRequired;
private readonly Mock<ILogger<WaterReadyService>> _loggerMock = new();
private readonly Mock<ILogger<WaterReadyService>> _loggerMock = new Mock<ILogger<WaterReadyService>>();
private readonly FakeTimeProvider _timeProvider = BoilerMonitorTestData.CreateTimeProvider();
private WaterReadyService CreateSut()
@@ -25,6 +29,7 @@ public class WaterReadyServiceTests
{
var sut = CreateSut();
sut.RecordHeatingObserved();
return sut;
}
@@ -36,7 +41,11 @@ public class WaterReadyServiceTests
double heatingThresholdWatts = Threshold)
{
var result = false;
for (var i = 0; i < count; i++) result = sut.IsWaterReady(switchState, powerWatts, heatingThresholdWatts);
for (var i = 0; i < count; i++)
{
result = sut.IsWaterReady(switchState, powerWatts, heatingThresholdWatts);
}
return result;
}
@@ -119,7 +128,9 @@ public class WaterReadyServiceTests
sut.ResetCooldown();
FeedReadings(sut, RequiredReadings).Should().BeTrue(
FeedReadings(sut, RequiredReadings)
.Should()
.BeTrue(
"ResetCooldown clears the cooldown and counter, not the heating observation");
}
@@ -261,7 +272,8 @@ public class WaterReadyServiceTests
var result = FeedReadings(sut, RequiredReadings, powerWatts: powerWatts);
result.Should().Be(
result.Should()
.Be(
expectedBelowThreshold,
$"{scenario}: readings below {Threshold}W are counted as 'not heating'");
}
@@ -320,8 +332,12 @@ public class WaterReadyServiceTests
_timeProvider.Advance(elapsed);
sut.IsInCooldown.Should().BeTrue();
sut.IsWaterReady("off", 0.0, Threshold).Should().BeTrue(
sut.IsWaterReady("off", 0.0, Threshold)
.Should()
.BeTrue(
"cooldown only clears via explicit ResetCooldown, not by elapsed time");
sut.WaterReadySince.Should().Be(triggeredAt);
}
+10 -1
View File
@@ -1,3 +1,5 @@
#region
using System.Globalization;
using BoilerMonitor.Models;
using Microsoft.Extensions.Logging;
@@ -5,6 +7,8 @@ using NetDaemon.HassModel;
using static BoilerMonitor.Models.BoilerMonitorConsts;
using static NordPool.Models.NordPoolConsts;
#endregion
namespace BoilerMonitorManager;
public sealed class BoilerConfigReader(IHaContext haContext, ILogger<BoilerConfigReader> logger) : IBoilerConfigReader
@@ -14,15 +18,20 @@ public sealed class BoilerConfigReader(IHaContext haContext, ILogger<BoilerConfi
public BoilerConfig ReadConfig()
{
var dailyHoursState = haContext.GetState(BoilerDailyHoursEntityId)?.State;
var dailyHours = double.TryParse(dailyHoursState, NumberStyles.Any, CultureInfo.InvariantCulture, out var dh)
? dh
: DefaultDailyHours;
var intervalCount = (int)(dailyHours * IntervalsPerHour);
if (intervalCount <= 0) intervalCount = IntervalsPerHour;
if (intervalCount <= 0)
{
intervalCount = IntervalsPerHour;
}
var priceCapState = haContext.GetState(BoilerPriceCapEntityId)?.State;
var priceCap =
double.TryParse(priceCapState, NumberStyles.Any, CultureInfo.InvariantCulture, out var pc) && pc > 0
? pc
@@ -1,7 +1,11 @@
#region
using BoilerMonitor.Models.Enums;
using BoilerMonitorManager.Interface;
using Microsoft.Extensions.Logging;
#endregion
namespace BoilerMonitorManager;
public sealed class BoilerControlService(ILogger<BoilerControlService> logger) : IBoilerControlService
@@ -58,7 +62,10 @@ public sealed class BoilerControlService(ILogger<BoilerControlService> logger) :
private static string GetTurnOffReason(bool waterReady, bool effectiveBudgetExhausted)
{
if (waterReady) return "water is already ready";
if (waterReady)
{
return "water is already ready";
}
return effectiveBudgetExhausted
? "daily budget is exhausted"
@@ -1,3 +1,5 @@
#region
using System.Globalization;
using System.Text.Json;
using BoilerMonitor.Models;
@@ -9,6 +11,8 @@ using NetDaemon.Extensions.MqttEntityManager;
using NetDaemon.HassModel;
using static BoilerMonitor.Models.BoilerMonitorConsts;
#endregion
namespace BoilerMonitorManager;
public sealed class BoilerMonitorEntityService(
@@ -77,7 +81,8 @@ public sealed class BoilerMonitorEntityService(
ResetSessionCountAsync(),
ResetBudgetOverrideAsync(),
ResetAutoManagementAsync()
).ConfigureAwait(false);
)
.ConfigureAwait(false);
logger.LogInformation("All BoilerMonitor runtime entity states reset to defaults");
}
@@ -118,6 +123,7 @@ public sealed class BoilerMonitorEntityService(
catch (Exception ex)
{
logger.LogError(ex, "Error cleaning up BoilerMonitor entities");
throw;
}
}
@@ -131,7 +137,8 @@ public sealed class BoilerMonitorEntityService(
await Task.WhenAll(
ResetStatusAsync(),
ResetWaterReadyAsync()
).ConfigureAwait(false);
)
.ConfigureAwait(false);
}
public PersistedBoilerState? ReadPersistedState()
@@ -177,6 +184,7 @@ public sealed class BoilerMonitorEntityService(
catch (Exception ex)
{
logger.LogError(ex, "Error reading persisted BoilerMonitor state from HA entities");
return null;
}
}
@@ -191,9 +199,16 @@ public sealed class BoilerMonitorEntityService(
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;
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
{
@@ -237,10 +252,7 @@ public sealed class BoilerMonitorEntityService(
private static bool TryParseEntitySeconds(string? state, out double seconds)
{
seconds = 0;
var tryParseEntitySeconds = !string.IsNullOrWhiteSpace(state)
&& state is not ("unavailable" or "unknown")
&& double.TryParse(state, CultureInfo.InvariantCulture, out seconds)
&& seconds >= 0;
var tryParseEntitySeconds = !string.IsNullOrWhiteSpace(state) && state is not ("unavailable" or "unknown") && double.TryParse(state, CultureInfo.InvariantCulture, out seconds) && seconds >= 0;
return tryParseEntitySeconds;
}
@@ -248,10 +260,7 @@ public sealed class BoilerMonitorEntityService(
private static bool TryParseEntityInt(string? state, out int value)
{
value = 0;
var tryParseEntityInt = !string.IsNullOrWhiteSpace(state)
&& state is not ("unavailable" or "unknown")
&& int.TryParse(state, CultureInfo.InvariantCulture, out value)
&& value >= 0;
var tryParseEntityInt = !string.IsNullOrWhiteSpace(state) && state is not ("unavailable" or "unknown") && int.TryParse(state, CultureInfo.InvariantCulture, out value) && value >= 0;
return tryParseEntityInt;
}
@@ -362,6 +371,7 @@ public sealed class BoilerMonitorEntityService(
private async Task ResetWaterReadyAsync()
{
await SetEntityStateSafe(WaterReadyEntityId, "unknown").ConfigureAwait(false);
await SetEntityAttributesSafe(WaterReadyEntityId, new
{
boiler_switch_state = "unknown",
@@ -369,7 +379,8 @@ public sealed class BoilerMonitorEntityService(
power_threshold_watts = DefaultHeatingPowerThresholdWatts,
friendly_name = "Boiler water ready",
last_updated = (string?)null
}).ConfigureAwait(false);
})
.ConfigureAwait(false);
}
private async Task ResetSkipPriceCapAsync()
@@ -380,35 +391,41 @@ public sealed class BoilerMonitorEntityService(
private async Task ResetTodayRuntimeAsync()
{
await SetEntityStateSafe(TodayRuntimeEntityId, "0").ConfigureAwait(false);
await SetEntityAttributesSafe(TodayRuntimeEntityId, new
{
formatted = "0h 0m",
friendly_name = "Today runtime",
last_updated = (string?)null
}).ConfigureAwait(false);
})
.ConfigureAwait(false);
}
private async Task ResetRemainingTimeAsync()
{
await SetEntityStateSafe(RemainingTimeEntityId, "0").ConfigureAwait(false);
await SetEntityAttributesSafe(RemainingTimeEntityId, new
{
formatted = "0h 0m",
budget_hours = 0.0,
friendly_name = "Remaining budget time",
last_updated = (string?)null
}).ConfigureAwait(false);
})
.ConfigureAwait(false);
}
private async Task ResetBudgetPercentageAsync()
{
await SetEntityStateSafe(BudgetPercentageEntityId, "0").ConfigureAwait(false);
await SetEntityAttributesSafe(BudgetPercentageEntityId, new
{
unit_of_measurement = "%",
friendly_name = "Budget usage",
last_updated = (string?)null
}).ConfigureAwait(false);
})
.ConfigureAwait(false);
}
private async Task ResetBudgetExhaustedAsync()
@@ -419,11 +436,13 @@ public sealed class BoilerMonitorEntityService(
private async Task ResetSessionCountAsync()
{
await SetEntityStateSafe(SessionCountEntityId, "0").ConfigureAwait(false);
await SetEntityAttributesSafe(SessionCountEntityId, new
{
friendly_name = "Heating sessions today",
last_updated = (string?)null
}).ConfigureAwait(false);
})
.ConfigureAwait(false);
}
private async Task ResetBudgetOverrideAsync()
@@ -439,6 +458,7 @@ public sealed class BoilerMonitorEntityService(
private async Task UpdateWaterReadyAsync(BoilerMonitorUpdateContext ctx, string timestamp)
{
await SetEntityStateSafe(WaterReadyEntityId, ctx.WaterReady ? "yes" : "no").ConfigureAwait(false);
await SetEntityAttributesSafe(WaterReadyEntityId, new
{
boiler_switch_state = ctx.BoilerSwitchState ?? "unknown",
@@ -446,47 +466,60 @@ public sealed class BoilerMonitorEntityService(
cooldown_since = ctx.CooldownSince?.ToString("O", CultureInfo.InvariantCulture),
friendly_name = "Boiler water ready",
last_updated = timestamp
}).ConfigureAwait(false);
})
.ConfigureAwait(false);
}
private async Task UpdateTodayRuntimeAsync(TimeSpan runTime, string formatted, string timestamp)
{
await SetEntityStateSafe(TodayRuntimeEntityId,
((int)runTime.TotalSeconds).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
((int)runTime.TotalSeconds).ToString(CultureInfo.InvariantCulture))
.ConfigureAwait(false);
await SetEntityAttributesSafe(TodayRuntimeEntityId, new
{
formatted,
friendly_name = "Today runtime",
last_updated = timestamp
}).ConfigureAwait(false);
})
.ConfigureAwait(false);
}
private async Task UpdateRemainingTimeAsync(TimeSpan remaining, string formatted, double budgetHours,
private async Task UpdateRemainingTimeAsync(TimeSpan remaining,
string formatted,
double budgetHours,
string timestamp)
{
var remainingSeconds = Math.Max(0, (int)remaining.TotalSeconds);
await SetEntityStateSafe(RemainingTimeEntityId, remainingSeconds.ToString(CultureInfo.InvariantCulture))
.ConfigureAwait(false);
await SetEntityAttributesSafe(RemainingTimeEntityId, new
{
formatted,
budget_hours = budgetHours,
friendly_name = "Remaining budget time",
last_updated = timestamp
}).ConfigureAwait(false);
})
.ConfigureAwait(false);
}
private async Task UpdateBudgetPercentageAsync(double percentage, string timestamp)
{
var clampedPercentage = Math.Clamp(percentage, 0, 100);
await SetEntityStateSafe(BudgetPercentageEntityId,
((int)clampedPercentage).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
((int)clampedPercentage).ToString(CultureInfo.InvariantCulture))
.ConfigureAwait(false);
await SetEntityAttributesSafe(BudgetPercentageEntityId, new
{
unit_of_measurement = "%",
friendly_name = "Budget usage",
last_updated = timestamp
}).ConfigureAwait(false);
})
.ConfigureAwait(false);
}
private async Task UpdateBudgetExhaustedAsync(bool exhausted)
@@ -498,11 +531,13 @@ public sealed class BoilerMonitorEntityService(
{
await SetEntityStateSafe(SessionCountEntityId, sessionCount.ToString(CultureInfo.InvariantCulture))
.ConfigureAwait(false);
await SetEntityAttributesSafe(SessionCountEntityId, new
{
friendly_name = "Heating sessions today",
last_updated = timestamp
}).ConfigureAwait(false);
})
.ConfigureAwait(false);
}
private async Task SetEntityStateSafe(string entityId, string state)
@@ -510,6 +545,7 @@ public sealed class BoilerMonitorEntityService(
try
{
await entityManager.SetEntityState(entityId, state).ConfigureAwait(false);
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("Successfully set state for {EntityId}: {State}", entityId, state);
@@ -526,6 +562,7 @@ public sealed class BoilerMonitorEntityService(
try
{
await entityManager.SetEntityAttributes(entityId, attributes).ConfigureAwait(false);
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("Successfully set attributes for {EntityId}", entityId);
+74 -18
View File
@@ -1,3 +1,5 @@
#region
using System.Globalization;
using System.Reactive.Concurrency;
using System.Text.Json;
@@ -13,6 +15,8 @@ using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
using static BoilerMonitor.Models.BoilerMonitorConsts;
#endregion
namespace BoilerMonitorManager;
[NetDaemonApp]
@@ -83,7 +87,10 @@ public sealed class BoilerMonitorInit
_options = options.Value;
_timeProvider = timeProvider;
if (startBackgroundScheduling) _ = InitializeAndScheduleAsync();
if (startBackgroundScheduling)
{
_ = InitializeAndScheduleAsync();
}
}
private async Task InitializeAndScheduleAsync()
@@ -130,9 +137,13 @@ public sealed class BoilerMonitorInit
{
_tracker.RestoreFromSnapshot();
if (persistedCooldown.HasValue) _waterReadyService.RestoreCooldownState(persistedCooldown.Value);
if (persistedCooldown.HasValue)
{
_waterReadyService.RestoreCooldownState(persistedCooldown.Value);
}
await _entityService.ResetTransientEntitiesAsync();
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation(
@@ -156,6 +167,7 @@ public sealed class BoilerMonitorInit
catch (Exception ex)
{
_logger.LogError(ex, "Error initializing BoilerMonitor");
throw;
}
}
@@ -204,13 +216,18 @@ public sealed class BoilerMonitorInit
try
{
var switchState = _haContext.GetState(SkipPriceCapEntityId);
if (!string.Equals(switchState?.State, SwitchOnState, StringComparison.OrdinalIgnoreCase)) return;
if (!string.Equals(switchState?.State, SwitchOnState, StringComparison.OrdinalIgnoreCase))
{
return;
}
_haContext.CallService("notify", "mobile_app_marius_phone", null, new
{
message = "Remember to turn off 'Skip price cap, heat until ready' if you're done heating.",
title = "Boiler reminder"
});
_logger.LogInformation("End-of-day reminder sent: skip price cap switch is still ON");
}
catch (Exception ex)
@@ -223,10 +240,14 @@ public sealed class BoilerMonitorInit
private void SubscribeToSkipPriceCapChanges()
{
var skipPriceCapSwitch = new Entity(_haContext, SkipPriceCapEntityId);
skipPriceCapSwitch.StateChanges()
.Subscribe(e =>
{
if (e.Old?.State == e.New?.State) return;
if (e.Old?.State == e.New?.State)
{
return;
}
_logger.LogInformation("Skip price cap switch changed, triggering poll");
_ = PollAndUpdateAsync();
@@ -236,10 +257,14 @@ public sealed class BoilerMonitorInit
private void SubscribeToAutoManagementChanges()
{
var autoManagementSwitch = new Entity(_haContext, AutoManagementEntityId);
autoManagementSwitch.StateChanges()
.Subscribe(e =>
{
if (e.Old?.State == e.New?.State) return;
if (e.Old?.State == e.New?.State)
{
return;
}
_logger.LogInformation("Automatic boiler control switch changed, triggering poll");
_ = PollAndUpdateAsync();
@@ -249,12 +274,19 @@ public sealed class BoilerMonitorInit
private void SubscribeToShowerState()
{
var showerStateSensor = new Entity(_haContext, ShowerStateEntityId);
showerStateSensor.StateChanges()
.Subscribe(e =>
{
if (!string.Equals(e.New?.State, ShowerActiveState, StringComparison.OrdinalIgnoreCase)) return;
if (!string.Equals(e.New?.State, ShowerActiveState, StringComparison.OrdinalIgnoreCase))
{
return;
}
if (!_waterReadyService.IsInCooldown) return;
if (!_waterReadyService.IsInCooldown)
{
return;
}
_logger.LogInformation("Shower detected as active, resetting water ready cooldown");
_waterReadyService.ResetCooldown();
@@ -264,6 +296,7 @@ public sealed class BoilerMonitorInit
private void SubscribeToCleanupButton()
{
var cleanupButton = new Entity(_haContext, CleanupButtonEntityId);
cleanupButton.StateChanges()
.Subscribe(_ =>
{
@@ -359,6 +392,7 @@ public sealed class BoilerMonitorInit
if (_cleanedUp)
{
_logger.LogDebug("BoilerMonitor is cleaned up, skipping poll");
return;
}
@@ -369,6 +403,7 @@ public sealed class BoilerMonitorInit
if (!config.IsFullyConfigured)
{
await _entityService.SetStatusAsync(StatusAwaitingConfiguration);
_logger.LogWarning(
"BoilerMonitor not fully configured (power={Power}, switch={Switch}, interval={Interval}, threshold={Threshold}). Awaiting configuration",
config.BoilerPowerEntityId, config.BoilerSwitchEntityId,
@@ -379,11 +414,16 @@ public sealed class BoilerMonitorInit
var boilerPowerWatts = ReadSensorDouble(config.BoilerPowerEntityId!);
var boilerSwitchState = _haContext.GetState(config.BoilerSwitchEntityId!)?.State;
var isHeating = boilerPowerWatts.HasValue &&
boilerPowerWatts.Value >= config.HeatingPowerThresholdWatts!.Value;
_tracker.RecordPollResult();
if (isHeating) _waterReadyService.RecordHeatingObserved();
if (isHeating)
{
_waterReadyService.RecordHeatingObserved();
}
var cheapestIntervalsState = _haContext.GetState(NordPoolCheapestIntervalsEntityId);
var isNowCheap = ReadAttributeBool(cheapestIntervalsState, "is_now_cheap");
@@ -406,6 +446,7 @@ public sealed class BoilerMonitorInit
message = "Hot water is ready.",
title = "Boiler"
});
_lastWaterReadyNotificationSentAt = _timeProvider.GetUtcNow();
_logger.LogInformation("Water ready notification sent");
}
@@ -416,7 +457,10 @@ public sealed class BoilerMonitorInit
var budgetTimeSpan = TimeSpan.FromHours(dailyHours);
var remainingTime = budgetTimeSpan - snapshot.AccumulatedRunTime;
if (remainingTime < TimeSpan.Zero) remainingTime = TimeSpan.Zero;
if (remainingTime < TimeSpan.Zero)
{
remainingTime = TimeSpan.Zero;
}
var budgetPercentage = budgetTimeSpan.TotalSeconds > 0
? snapshot.AccumulatedRunTime.TotalSeconds / budgetTimeSpan.TotalSeconds * 100.0
@@ -434,6 +478,7 @@ public sealed class BoilerMonitorInit
budgetOverride);
var autoManagementState = _haContext.GetState(AutoManagementEntityId)?.State;
var autoManagementEnabled =
!string.Equals(autoManagementState, SwitchOffState, StringComparison.OrdinalIgnoreCase);
@@ -485,12 +530,17 @@ public sealed class BoilerMonitorInit
case BoilerAction.TurnOn:
_haContext.CallService("switch", "turn_on", ServiceTarget.FromEntity(switchEntityId));
_waterReadyService.NotifyTurnedOn();
break;
case BoilerAction.TurnOff:
_haContext.CallService("switch", "turn_off", ServiceTarget.FromEntity(switchEntityId));
break;
case BoilerAction.NoChange:
break;
default:
throw new ArgumentOutOfRangeException(nameof(action), action, null);
}
@@ -504,9 +554,7 @@ public sealed class BoilerMonitorInit
int? pollInterval = null;
var pollIntervalState = _haContext.GetState(ConfigPollIntervalEntityId)?.State;
if (!string.IsNullOrWhiteSpace(pollIntervalState)
&& double.TryParse(pollIntervalState, CultureInfo.InvariantCulture, out var pollIntervalValue)
&& pollIntervalValue > 0)
if (!string.IsNullOrWhiteSpace(pollIntervalState) && double.TryParse(pollIntervalState, CultureInfo.InvariantCulture, out var pollIntervalValue) && pollIntervalValue > 0)
{
pollInterval = (int)pollIntervalValue;
}
@@ -514,9 +562,7 @@ public sealed class BoilerMonitorInit
double? heatingThreshold = null;
var thresholdState = _haContext.GetState(ConfigHeatingThresholdEntityId)?.State;
if (!string.IsNullOrWhiteSpace(thresholdState)
&& double.TryParse(thresholdState, CultureInfo.InvariantCulture, out var thresholdValue)
&& thresholdValue > 0)
if (!string.IsNullOrWhiteSpace(thresholdState) && double.TryParse(thresholdState, CultureInfo.InvariantCulture, out var thresholdValue) && thresholdValue > 0)
{
heatingThreshold = thresholdValue;
}
@@ -534,14 +580,20 @@ public sealed class BoilerMonitorInit
{
var state = _haContext.GetState(entityId);
if (state?.State is null or "unavailable" or "unknown") return null;
if (state?.State is null or "unavailable" or "unknown")
{
return null;
}
return double.TryParse(state.State, CultureInfo.InvariantCulture, out var value) ? value : null;
}
private static bool ReadAttributeBool(EntityState? entityState, string attributeName)
{
if (entityState?.Attributes is not IDictionary<string, object> attributes) return false;
if (entityState?.Attributes is not IDictionary<string, object> attributes)
{
return false;
}
try
{
@@ -569,9 +621,13 @@ public sealed class BoilerMonitorInit
private bool IsWithinNotificationCooldown()
{
if (_lastWaterReadyNotificationSentAt is null) return false;
if (_lastWaterReadyNotificationSentAt is null)
{
return false;
}
var elapsed = _timeProvider.GetUtcNow() - _lastWaterReadyNotificationSentAt.Value;
return elapsed < WaterReadyNotificationCooldown;
}
}
@@ -1,9 +1,13 @@
#region
using BoilerMonitorManager.Interface;
using BoilerMonitorManager.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using NetDaemon.AppModel;
#endregion
namespace BoilerMonitorManager;
public static class BoilerMonitorServiceRegistration
@@ -12,9 +16,13 @@ public static class BoilerMonitorServiceRegistration
{
var options = configuration
.GetSection(BoilerMonitorOptions.SectionName)
.Get<BoilerMonitorOptions>() ?? new BoilerMonitorOptions();
.Get<BoilerMonitorOptions>() ??
new BoilerMonitorOptions();
if (!options.Enabled) return services;
if (!options.Enabled)
{
return services;
}
services
.AddNetDaemonApp<BoilerMonitorInit>()
@@ -1,6 +1,10 @@
#region
using BoilerMonitorManager.Interface;
using BoilerMonitorManager.Models;
#endregion
namespace BoilerMonitorManager;
public class BoilerRunTimeTracker : IBoilerRunTimeTracker
@@ -1,5 +1,9 @@
#region
using BoilerMonitor.Models.Enums;
#endregion
namespace BoilerMonitorManager.Interface;
public interface IBoilerControlService
@@ -1,5 +1,9 @@
#region
using BoilerMonitorManager.Models;
#endregion
namespace BoilerMonitorManager.Interface;
public interface IBoilerMonitorEntityService
@@ -1,5 +1,9 @@
#region
using BoilerMonitorManager.Models;
#endregion
namespace BoilerMonitorManager.Interface;
public interface IBoilerRunTimeTracker
@@ -7,8 +7,7 @@ public record BoilerMonitorConfig
public int? PollIntervalSeconds { get; init; }
public double? HeatingPowerThresholdWatts { get; init; }
public bool IsFullyConfigured =>
!string.IsNullOrWhiteSpace(BoilerPowerEntityId) &&
public bool IsFullyConfigured => !string.IsNullOrWhiteSpace(BoilerPowerEntityId) &&
!string.IsNullOrWhiteSpace(BoilerSwitchEntityId) &&
PollIntervalSeconds is > 0 &&
HeatingPowerThresholdWatts is > 0;
+20 -4
View File
@@ -1,13 +1,17 @@
#region
using BoilerMonitor.Models;
using BoilerMonitorManager.Interface;
using Microsoft.Extensions.Logging;
#endregion
namespace BoilerMonitorManager;
public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimeProvider timeProvider) : IWaterReadyService
{
private const string SwitchOnState = "on";
private readonly Lock _lock = new();
private readonly Lock _lock = new Lock();
private int _consecutiveBelowThresholdCount;
private bool _hasObservedHeating;
private DateTimeOffset? _waterReadySince;
@@ -50,9 +54,15 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
}
}
if (switchState is null || powerWatts is null) return false;
if (switchState is null || powerWatts is null)
{
return false;
}
if (!string.Equals(switchState, SwitchOnState, StringComparison.OrdinalIgnoreCase)) return false;
if (!string.Equals(switchState, SwitchOnState, StringComparison.OrdinalIgnoreCase))
{
return false;
}
lock (_lock)
{
@@ -70,6 +80,7 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
if (powerWatts.Value >= heatingThresholdWatts)
{
_consecutiveBelowThresholdCount = 0;
return false;
}
@@ -117,7 +128,10 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
{
lock (_lock)
{
if (_hasObservedHeating) return;
if (_hasObservedHeating)
{
return;
}
_hasObservedHeating = true;
}
@@ -141,6 +155,7 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
lock (_lock)
{
var todayMidnightUtc = new DateTimeOffset(timeProvider.GetUtcNow().Date, TimeSpan.Zero);
if (waterReadySince < todayMidnightUtc)
{
if (logger.IsEnabled(LogLevel.Information))
@@ -153,6 +168,7 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
}
_waterReadySince = waterReadySince;
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation("Restored water ready cooldown from {Since}", waterReadySince);
@@ -1,6 +1,10 @@
#region
using HomeAssistant.Models;
using NetDaemon.Extensions.MqttEntityManager;
#endregion
namespace BoilerMonitor.Models;
public class BoilerMonitorEntity : EntityCreateModel
+8 -1
View File
@@ -1,10 +1,14 @@
using HomeAssistant.Entities.Interfaces;
#region
using HomeAssistant.Entities.Interfaces;
using HomeAssistant.Models;
using HomeAssistantGenerated;
using Microsoft.Extensions.Options;
using NetDaemon.Extensions.MqttEntityManager;
using NetDaemon.HassModel;
#endregion
namespace HomeAssistant.Entities;
public class EntityManager(
@@ -53,12 +57,14 @@ public class EntityManager(
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;
@@ -67,6 +73,7 @@ public class EntityManager(
private static string BuildRootTopic(string entityId, string discoveryPrefix)
{
var separatorIndex = entityId.IndexOf('.');
if (separatorIndex <= 0 || separatorIndex == entityId.Length - 1)
{
throw new ArgumentException(
@@ -1,4 +1,8 @@
using HomeAssistant.Models;
#region
using HomeAssistant.Models;
#endregion
namespace HomeAssistant.Entities.Interfaces;
+6 -2
View File
@@ -1,10 +1,14 @@
using NetDaemon.Extensions.MqttEntityManager;
#region
using NetDaemon.Extensions.MqttEntityManager;
#endregion
namespace HomeAssistant.Models;
public class EntityCreateModel
{
public string? EntityId { get; protected init; }
public EntityCreationOptions? Options { get; init; } = new();
public EntityCreationOptions? Options { get; init; } = new EntityCreationOptions();
public object? AdditionalConfig { get; init; }
}
@@ -1,8 +1,12 @@
#region
using System;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Serilog;
#endregion
namespace HomeAssistantServer;
public static class CustomLoggingProvider
+17 -4
View File
@@ -1,3 +1,5 @@
#region
using System;
using System.Collections.Generic;
using System.Text.Json;
@@ -13,6 +15,8 @@ using NordPoolManager.Interface;
using PowerMonitorManager.Interface;
using ShowerMonitorManager.Interface;
#endregion
namespace HomeAssistantServer;
[NetDaemonApp]
@@ -66,7 +70,8 @@ public sealed class MqttRecreateApp
model = "AppDaemon",
manufacturer = "HomeAssistant App Daemon"
}
}).ConfigureAwait(false);
})
.ConfigureAwait(false);
if (_logger.IsEnabled(LogLevel.Information))
{
@@ -74,6 +79,7 @@ public sealed class MqttRecreateApp
}
var button = new Entity(_haContext, RecreateButtonEntityId);
button.StateChanges()
.Subscribe(_ =>
{
@@ -107,9 +113,11 @@ public sealed class MqttRecreateApp
private async Task RecreateNordPoolAsync()
{
var entityService = _serviceProvider.GetService<INordPoolEntityService>();
if (entityService is null)
{
_logger.LogDebug("NordPool entity service not registered (disabled), skipping");
return;
}
@@ -132,9 +140,11 @@ public sealed class MqttRecreateApp
private async Task RecreateBoilerMonitorAsync()
{
var entityService = _serviceProvider.GetService<IBoilerMonitorEntityService>();
if (entityService is null)
{
_logger.LogDebug("BoilerMonitor entity service not registered (disabled), skipping");
return;
}
@@ -155,9 +165,11 @@ public sealed class MqttRecreateApp
private async Task RecreateShowerMonitorAsync()
{
var entityService = _serviceProvider.GetService<IShowerMonitorEntityService>();
if (entityService is null)
{
_logger.LogDebug("ShowerMonitor entity service not registered (disabled), skipping");
return;
}
@@ -177,9 +189,11 @@ public sealed class MqttRecreateApp
private async Task RecreatePowerMonitorAsync()
{
var entityService = _serviceProvider.GetService<IPowerMonitorEntityService>();
if (entityService is null)
{
_logger.LogDebug("PowerMonitor entity service not registered (disabled), skipping");
return;
}
@@ -202,14 +216,13 @@ public sealed class MqttRecreateApp
try
{
var state = _haContext.GetState(NordPoolPriceEntityId);
if (state?.Attributes is IDictionary<string, object> attributes &&
attributes.TryGetValue("unit_of_measurement", out var value))
{
return value switch
{
string s => s,
JsonElement { ValueKind: JsonValueKind.String } je => je.GetString(),
_ => null
string s => s, JsonElement { ValueKind: JsonValueKind.String } je => je.GetString(), _ => null
};
}
}
+5
View File
@@ -1,3 +1,5 @@
#region
using System;
using System.Reflection;
using BatteryMonitorManager;
@@ -28,6 +30,8 @@ using PowerMonitorManager.Models;
using ShowerMonitorManager;
using ShowerMonitorManager.Models;
#endregion
try
{
var app = Host.CreateDefaultBuilder(args)
@@ -47,6 +51,7 @@ try
{
config.LicenseKey =
"eyJhbGciOiJSUzI1NiIsImtpZCI6Ikx1Y2t5UGVubnlTb2Z0d2FyZUxpY2Vuc2VLZXkvYmJiMTNhY2I1OTkwNGQ4OWI0Y2IxYzg1ZjA4OGNjZjkiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL2x1Y2t5cGVubnlzb2Z0d2FyZS5jb20iLCJhdWQiOiJMdWNreVBlbm55U29mdHdhcmUiLCJleHAiOiIxODMwMDM4NDAwIiwiaWF0IjoiMTc2NDAwNTE3OSIsImFjY291bnRfaWQiOiIwMTlhYjZlNjFjZWM3ZjhhYWQzMjE4ZmQ0ODdkYTgwNiIsImN1c3RvbWVyX2lkIjoiMDE5YWI2ZTYxY2VjN2Y4YWFkMzIxOGZkNDg3ZGE4MDYiLCJzdWJfaWQiOiItIiwiZWRpdGlvbiI6IjAiLCJ0eXBlIjoiMiIsInRlcm1fZW5kIjoiMTgyNzQ0NjQwMCJ9.VgEgdxh9xBudubLZr90mUiCORAhLx00Fz7lw1bUMhLWICjBposFrBWrgccKb_irFis_6qUyi567VbsmbjTDxAp9-f0QI0VW4_Zr9wcNeCrDzE0U-DKdcWoMpHoJYUf62tMscGcgVJEKgMX27KLWWqAQzcJm8X-O072A7pW1_x_xkAorFOIfahKXdECnUUdHpPUdrClUbxfWS-wkkKBP0AnrnYY1N2FGlqsJj5_ro1Mmcpijx0sxUKSl1FKaHmx6pOHq-rvJEF7Vvi35vO4HQYFnyP-hN2fQSkgK-Eg8LG6BqBLDXK33VlI6WMO0nOUG62KWAI7jXPSZhrSjBZfxy0g";
config.AddProfile<NordPoolMappingProfile>();
config.AddProfile<GlobalMappingProfile>();
})
@@ -1,3 +1,5 @@
#region
using FluentAssertions;
using LeakMonitor.Models;
using LeakMonitorManager;
@@ -9,14 +11,16 @@ using Moq;
using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
#endregion
namespace LeakMonitor.Manager.Tests;
public class LeakMonitorInitTests
{
private readonly Mock<IHaContext> _haContextMock = new();
private readonly Mock<ILogger<LeakMonitorInit>> _loggerMock = new();
private readonly Mock<ILeakNotificationService> _notificationServiceMock = new();
private readonly LeakMonitorTestData.TrackingObservable<StateChange> _stateChanges = new();
private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
private readonly Mock<ILogger<LeakMonitorInit>> _loggerMock = new Mock<ILogger<LeakMonitorInit>>();
private readonly Mock<ILeakNotificationService> _notificationServiceMock = new Mock<ILeakNotificationService>();
private readonly LeakMonitorTestData.TrackingObservable<StateChange> _stateChanges = new LeakMonitorTestData.TrackingObservable<StateChange>();
public LeakMonitorInitTests()
{
@@ -56,6 +60,7 @@ public class LeakMonitorInitTests
public void HandleStateChange_WhenWaterDetected_ShouldSendLeakAlert(string sensorEntityId, string? newState)
{
var sut = CreateSut();
var change = LeakMonitorTestData.CreateStateChange(
_haContextMock.Object,
sensorEntityId,
@@ -73,6 +78,7 @@ public class LeakMonitorInitTests
public void HandleStateChange_WhenWaterCleared_ShouldDismissLeakAlert(string sensorEntityId, string? newState)
{
var sut = CreateSut();
var change = LeakMonitorTestData.CreateStateChange(
_haContextMock.Object,
sensorEntityId,
@@ -90,6 +96,7 @@ public class LeakMonitorInitTests
public void HandleStateChange_WhenStateIsNotActionable_ShouldNotNotify(string? newState)
{
var sut = CreateSut();
var change = LeakMonitorTestData.CreateStateChange(
_haContextMock.Object,
LeakMonitorTestData.AquariumSensorId,
@@ -107,6 +114,7 @@ public class LeakMonitorInitTests
// Deduplication is the notification service's job (cooldown); the init handler
// forwards each "on" event it receives.
var sut = CreateSut();
var change = LeakMonitorTestData.CreateStateChange(
_haContextMock.Object,
LeakMonitorTestData.AquariumSensorId,
@@ -119,6 +127,7 @@ public class LeakMonitorInitTests
_notificationServiceMock.Verify(
n => n.SendLeakAlert(LeakMonitorTestData.AquariumSensorId),
Times.Exactly(2));
_notificationServiceMock.Verify(n => n.DismissLeakAlert(It.IsAny<string>()), Times.Never());
}
@@ -127,6 +136,7 @@ public class LeakMonitorInitTests
public void HandleStateChange_WithBlankSensorId_ShouldForwardTheIdVerbatim(string sensorEntityId)
{
var sut = CreateSut();
var change = LeakMonitorTestData.CreateStateChange(
_haContextMock.Object,
sensorEntityId,
@@ -160,6 +170,7 @@ public class LeakMonitorInitTests
CreateSut();
_stateChanges.SubscriptionCount.Should().Be(LeakMonitorTestData.DefaultSensorIds.Length);
_haContextMock.Verify(
h => h.StateAllChanges(),
Times.Exactly(LeakMonitorTestData.DefaultSensorIds.Length));
@@ -199,6 +210,7 @@ public class LeakMonitorInitTests
_notificationServiceMock.Verify(
n => n.SendLeakAlert(LeakMonitorTestData.BoilerSensorId),
Times.Once());
_notificationServiceMock.Verify(
n => n.SendLeakAlert(LeakMonitorTestData.AquariumSensorId),
Times.Never());
@@ -219,6 +231,7 @@ public class LeakMonitorInitTests
newState));
_notificationServiceMock.Verify(n => n.SendLeakAlert(sensorEntityId), Times.Once());
_notificationServiceMock.Verify(
n => n.SendLeakAlert(It.Is<string>(id => id != sensorEntityId)),
Times.Never());
@@ -294,11 +307,14 @@ public class LeakMonitorInitTests
_haContextMock.Object,
LeakMonitorTestData.AquariumSensorId,
LeakMonitorTestData.DetectionSequence))
{
_stateChanges.Publish(change);
}
_notificationServiceMock.Verify(
n => n.SendLeakAlert(LeakMonitorTestData.AquariumSensorId),
Times.Exactly(2));
_notificationServiceMock.Verify(
n => n.DismissLeakAlert(LeakMonitorTestData.AquariumSensorId),
Times.Exactly(2));
@@ -1,3 +1,5 @@
#region
using System.Text.Json;
using LeakMonitor.Models;
using LeakMonitorManager.Models;
@@ -5,6 +7,8 @@ using Moq;
using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
#endregion
namespace LeakMonitor.Manager.Tests;
/// <summary>
@@ -20,12 +24,12 @@ internal static class LeakMonitorTestData
public static readonly string[] DefaultSensorIds = [AquariumSensorId, BoilerSensorId];
private static readonly DateTimeOffset DefaultStart = new(2026, 1, 15, 12, 0, 0, TimeSpan.Zero);
private static readonly DateTimeOffset DefaultStart = new DateTimeOffset(2026, 1, 15, 12, 0, 0, TimeSpan.Zero);
/// <summary>
/// Every casing of the "water detected" state, across both configured sensors.
/// </summary>
public static TheoryData<string, string?> WaterDetectedCases { get; } = new()
public static TheoryData<string, string?> WaterDetectedCases { get; } = new TheoryData<string, string?>
{
{ AquariumSensorId, LeakMonitorConsts.WaterDetectedState },
{ AquariumSensorId, "ON" },
@@ -37,7 +41,7 @@ internal static class LeakMonitorTestData
/// <summary>
/// Every casing of the "water cleared" state, across both configured sensors.
/// </summary>
public static TheoryData<string, string?> WaterClearedCases { get; } = new()
public static TheoryData<string, string?> WaterClearedCases { get; } = new TheoryData<string, string?>
{
{ AquariumSensorId, LeakMonitorConsts.WaterClearedState },
{ AquariumSensorId, "OFF" },
@@ -83,7 +87,7 @@ internal static class LeakMonitorTestData
/// (sensor id, expected notification id) rows for the id sanitising rules:
/// dots become underscores, other characters and blanks are preserved.
/// </summary>
public static TheoryData<string, string> NotificationIdCases { get; } = new()
public static TheoryData<string, string> NotificationIdCases { get; } = new TheoryData<string, string>
{
{ AquariumSensorId, "leak_monitor_binary_sensor_aquarium_leak_sensor" },
{ BoilerSensorId, "leak_monitor_binary_sensor_boiler_moisture" },
@@ -100,7 +104,7 @@ internal static class LeakMonitorTestData
/// rows straddling the strict <c>elapsed &lt; cooldown</c> boundary, plus zero, negative
/// and int-max cooldowns.
/// </summary>
public static TheoryData<int, int, int> CooldownBoundaryCases { get; } = new()
public static TheoryData<int, int, int> CooldownBoundaryCases { get; } = new TheoryData<int, int, int>
{
{ 5, 0, 1 },
{ 5, 299, 1 },
@@ -258,7 +262,10 @@ internal static class LeakMonitorTestData
public void Publish(T value)
{
foreach (var observer in _observers.ToArray()) observer.OnNext(value);
foreach (var observer in _observers.ToArray())
{
observer.OnNext(value);
}
}
private sealed class Subscription(List<IObserver<T>> observers, IObserver<T> observer) : IDisposable
@@ -1,3 +1,5 @@
#region
using FluentAssertions;
using LeakMonitor.Models;
using LeakMonitorManager;
@@ -8,13 +10,15 @@ using Moq;
using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
#endregion
namespace LeakMonitor.Manager.Tests;
public class LeakNotificationServiceTests
{
private readonly Mock<IHaContext> _haContextMock = new();
private readonly Mock<ILogger<LeakNotificationService>> _loggerMock = new();
private readonly LeakMonitorTestData.ManualTimeProvider _timeProvider = new();
private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
private readonly Mock<ILogger<LeakNotificationService>> _loggerMock = new Mock<ILogger<LeakNotificationService>>();
private readonly LeakMonitorTestData.ManualTimeProvider _timeProvider = new LeakMonitorTestData.ManualTimeProvider();
private LeakNotificationService CreateSut(LeakMonitorOptions? options = null)
{
@@ -60,7 +64,7 @@ public class LeakNotificationServiceTests
#region SendLeakAlert
public static TheoryData<string, string> SendAlertServiceCalls { get; } = new()
public static TheoryData<string, string> SendAlertServiceCalls { get; } = new TheoryData<string, string>
{
{ LeakMonitorConsts.NotifyDomain, LeakMonitorConsts.MobileAppService },
{ LeakMonitorConsts.PersistentNotificationDomain, LeakMonitorConsts.PersistentNotificationCreateService }
@@ -110,7 +114,10 @@ public class LeakNotificationServiceTests
var persistentPayload = LeakMonitorTestData.SerializePayload(persistentCall.Data);
persistentPayload.GetProperty("title").GetString().Should().Be(LeakMonitorConsts.NotificationTitle);
persistentPayload.GetProperty("message").GetString().Should().Be(expectedMessage);
persistentPayload.GetProperty("notification_id").GetString().Should()
persistentPayload.GetProperty("notification_id")
.GetString()
.Should()
.Be(LeakNotificationService.BuildNotificationId(sensorId));
}
@@ -156,7 +163,10 @@ public class LeakNotificationServiceTests
var sut = CreateSut();
const string sensorId = LeakMonitorTestData.AquariumSensorId;
for (var i = 0; i < repeats; i++) sut.SendLeakAlert(sensorId);
for (var i = 0; i < repeats; i++)
{
sut.SendLeakAlert(sensorId);
}
VerifyMobilePush(Times.Once());
VerifyPersistentCreate(Times.Once());
@@ -169,7 +179,10 @@ public class LeakNotificationServiceTests
var sut = CreateSut(LeakMonitorTestData.CreateOptions(notificationCooldownMinutes: 0));
const string sensorId = LeakMonitorTestData.AquariumSensorId;
for (var i = 0; i < repeats; i++) sut.SendLeakAlert(sensorId);
for (var i = 0; i < repeats; i++)
{
sut.SendLeakAlert(sensorId);
}
VerifyMobilePush(Times.Exactly(repeats));
VerifyPersistentCreate(Times.Exactly(repeats));
@@ -214,7 +227,10 @@ public class LeakNotificationServiceTests
{
var sut = CreateSut();
foreach (var sensorId in LeakMonitorTestData.DefaultSensorIds) sut.SendLeakAlert(sensorId);
foreach (var sensorId in LeakMonitorTestData.DefaultSensorIds)
{
sut.SendLeakAlert(sensorId);
}
VerifyMobilePush(Times.Exactly(LeakMonitorTestData.DefaultSensorIds.Length));
VerifyPersistentCreate(Times.Exactly(LeakMonitorTestData.DefaultSensorIds.Length));
@@ -286,6 +302,7 @@ public class LeakNotificationServiceTests
dismissCall.Domain.Should().Be(LeakMonitorConsts.PersistentNotificationDomain);
dismissCall.Service.Should().Be(LeakMonitorConsts.PersistentNotificationDismissService);
dismissCall.Target.Should().BeNull();
LeakMonitorTestData.SerializePayload(dismissCall.Data)
.GetProperty("notification_id")
.GetString()
+8 -1
View File
@@ -1,3 +1,5 @@
#region
using LeakMonitor.Models;
using LeakMonitorManager.Interface;
using LeakMonitorManager.Models;
@@ -7,6 +9,8 @@ using NetDaemon.AppModel;
using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
#endregion
namespace LeakMonitorManager;
[NetDaemonApp]
@@ -42,7 +46,10 @@ public sealed class LeakMonitorInit
return Task.CompletedTask;
}
foreach (var sensorEntityId in _options.SensorEntityIds) SubscribeToLeakSensor(sensorEntityId);
foreach (var sensorEntityId in _options.SensorEntityIds)
{
SubscribeToLeakSensor(sensorEntityId);
}
if (_logger.IsEnabled(LogLevel.Information))
{
@@ -1,9 +1,13 @@
#region
using LeakMonitorManager.Interface;
using LeakMonitorManager.Models;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using NetDaemon.AppModel;
#endregion
namespace LeakMonitorManager;
public static class LeakMonitorServiceRegistration
@@ -12,9 +16,13 @@ public static class LeakMonitorServiceRegistration
{
var options = configuration
.GetSection(LeakMonitorOptions.SectionName)
.Get<LeakMonitorOptions>() ?? new LeakMonitorOptions();
.Get<LeakMonitorOptions>() ??
new LeakMonitorOptions();
if (!options.Enabled) return;
if (!options.Enabled)
{
return;
}
services.AddNetDaemonApp<LeakMonitorInit>().AddScoped<ILeakNotificationService, LeakNotificationService>();
}
+11 -2
View File
@@ -1,3 +1,5 @@
#region
using System.Collections.Concurrent;
using LeakMonitor.Models;
using LeakMonitorManager.Interface;
@@ -6,6 +8,8 @@ using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NetDaemon.HassModel;
#endregion
namespace LeakMonitorManager;
public sealed class LeakNotificationService(
@@ -14,7 +18,7 @@ public sealed class LeakNotificationService(
IOptions<LeakMonitorOptions> options,
TimeProvider timeProvider) : ILeakNotificationService
{
private readonly ConcurrentDictionary<string, DateTimeOffset> _lastNotificationTimes = new();
private readonly ConcurrentDictionary<string, DateTimeOffset> _lastNotificationTimes = new ConcurrentDictionary<string, DateTimeOffset>();
private readonly LeakMonitorOptions _options = options.Value;
public void SendLeakAlert(string sensorEntityId)
@@ -95,15 +99,20 @@ public sealed class LeakNotificationService(
private bool IsWithinCooldown(string sensorEntityId)
{
if (!_lastNotificationTimes.TryGetValue(sensorEntityId, out var lastTime)) return false;
if (!_lastNotificationTimes.TryGetValue(sensorEntityId, out var lastTime))
{
return false;
}
var cooldown = TimeSpan.FromMinutes(_options.NotificationCooldownMinutes);
return timeProvider.GetUtcNow() - lastTime < cooldown;
}
internal static string BuildNotificationId(string sensorEntityId)
{
var sanitized = sensorEntityId.Replace('.', '_');
return $"{LeakMonitorConsts.NotificationIdPrefix}{sanitized}";
}
}
@@ -1,5 +1,9 @@
#region
using LeakMonitor.Models;
#endregion
namespace LeakMonitorManager.Models;
public sealed class LeakMonitorOptions
@@ -1,3 +1,5 @@
#region
using LightMonitor.Models;
using LightMonitorManager;
using Microsoft.Extensions.Logging;
@@ -6,6 +8,8 @@ using Moq;
using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
#endregion
namespace LightMonitor.Manager.Tests;
public class LightControlServiceTests
@@ -15,7 +19,7 @@ public class LightControlServiceTests
private readonly LightMonitorOptions _defaultOptions = LightMonitorTestData.CreateOptions();
private readonly Mock<IHaContext> _haContextMock = new();
private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
private LightControlService CreateService(LightMonitorOptions? options = null)
{
@@ -1,3 +1,5 @@
#region
using System.Reactive.Subjects;
using FluentAssertions;
using LightMonitor.Models;
@@ -9,6 +11,8 @@ using Moq;
using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
#endregion
namespace LightMonitor.Manager.Tests;
public class LightMonitorInitTests
@@ -18,10 +22,10 @@ public class LightMonitorInitTests
private readonly LightMonitorOptions _defaultOptions = LightMonitorTestData.CreateOptions();
private readonly Mock<IHaContext> _haContextMock = new();
private readonly Mock<ILightControlService> _lightControlServiceMock = new();
private readonly Mock<IPresenceService> _presenceServiceMock = new();
private readonly Subject<StateChange> _stateChangesSubject = new();
private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
private readonly Mock<ILightControlService> _lightControlServiceMock = new Mock<ILightControlService>();
private readonly Mock<IPresenceService> _presenceServiceMock = new Mock<IPresenceService>();
private readonly Subject<StateChange> _stateChangesSubject = new Subject<StateChange>();
private LightMonitorInit CreateSut(LightMonitorOptions? options = null, Exception? subscriptionException = null)
{
@@ -182,6 +186,7 @@ public class LightMonitorInitTests
_presenceServiceMock.SetupSequence(x => x.IsAnyoneHome())
.Throws(new InvalidOperationException("presence failed"))
.Returns(true);
CreateSut();
var act = () => EmitStateChange(
@@ -202,6 +207,7 @@ public class LightMonitorInitTests
_lightControlServiceMock.SetupSequence(x => x.TurnOnLight())
.Throws(new InvalidOperationException("light failed"))
.Pass();
CreateSut();
var act = () => EmitStateChange(PersonEntityId, "not_home", LightMonitorConsts.PersonHomeState);
@@ -1,6 +1,10 @@
#region
using LightMonitor.Models;
using NetDaemon.HassModel.Entities;
#endregion
namespace LightMonitor.Manager.Tests;
/// <summary>
@@ -37,7 +41,7 @@ internal static class LightMonitorTestData
/// "below_horizon" is compared case-insensitively; unavailable, unknown, blank and
/// missing states must never turn the light on.
/// </summary>
public static TheoryData<string?, bool> SunStateTurnOnCases { get; } = new()
public static TheoryData<string?, bool> SunStateTurnOnCases { get; } = new TheoryData<string?, bool>
{
{ LightMonitorConsts.SunBelowHorizon, true },
{ LightMonitorConsts.SunBelowHorizon.ToUpperInvariant(), true },
@@ -55,7 +59,7 @@ internal static class LightMonitorTestData
/// Light states evaluated while the sun is below the horizon. Only "on" (any casing)
/// suppresses the turn on call; everything else, including missing state, turns it on.
/// </summary>
public static TheoryData<string?, bool> LightStateTurnOnCases { get; } = new()
public static TheoryData<string?, bool> LightStateTurnOnCases { get; } = new TheoryData<string?, bool>
{
{ LightMonitorConsts.LightOnState, false },
{ LightMonitorConsts.LightOnState.ToUpperInvariant(), false },
@@ -73,7 +77,7 @@ internal static class LightMonitorTestData
/// Person states checked against the "arrived home" transition.
/// Only "home" in any casing counts.
/// </summary>
public static TheoryData<string?, bool> PersonNewStateCases { get; } = new()
public static TheoryData<string?, bool> PersonNewStateCases { get; } = new TheoryData<string?, bool>
{
{ LightMonitorConsts.PersonHomeState, true },
{ "HOME", true },
@@ -92,7 +96,7 @@ internal static class LightMonitorTestData
/// Old person states for a transition to "home". Recovery from unavailable, unknown or
/// missing state must be ignored; every other old state is a real arrival.
/// </summary>
public static TheoryData<string?, bool> PersonArrivalTransitions { get; } = new()
public static TheoryData<string?, bool> PersonArrivalTransitions { get; } = new TheoryData<string?, bool>
{
{ "not_home", true },
{ "work", true },
@@ -106,7 +110,7 @@ internal static class LightMonitorTestData
/// Old sun states for a transition to "below_horizon". Recovery from unavailable, unknown
/// or missing state must be ignored.
/// </summary>
public static TheoryData<string?, bool> SunBelowHorizonTransitions { get; } = new()
public static TheoryData<string?, bool> SunBelowHorizonTransitions { get; } = new TheoryData<string?, bool>
{
{ LightMonitorConsts.SunAboveHorizon, true },
{ string.Empty, true },
@@ -171,9 +175,15 @@ internal static class LightMonitorTestData
var matrix = new TheoryData<string?[]>();
foreach (var first in PresenceStates)
{
foreach (var second in PresenceStates)
{
foreach (var third in PresenceStates)
{
matrix.Add([first, second, third]);
}
}
}
return matrix;
}
@@ -1,3 +1,5 @@
#region
using FluentAssertions;
using LightMonitor.Models;
using LightMonitorManager;
@@ -6,12 +8,14 @@ using Microsoft.Extensions.Options;
using Moq;
using NetDaemon.HassModel;
#endregion
namespace LightMonitor.Manager.Tests;
public class PresenceServiceTests
{
private readonly LightMonitorOptions _defaultOptions = LightMonitorTestData.CreateOptions();
private readonly Mock<IHaContext> _haContextMock = new();
private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
private PresenceService CreateService(LightMonitorOptions? options = null)
{
@@ -95,8 +99,10 @@ public class PresenceServiceTests
CreateService().IsAnyoneHome().Should().BeFalse();
foreach (var personEntityId in LightMonitorTestData.PersonEntityIds)
{
_haContextMock.Verify(x => x.GetState(personEntityId), Times.Once);
}
}
[Fact]
public void IsAnyoneHome_ShouldIgnorePersonsThatAreNotConfigured()
@@ -120,6 +126,8 @@ public class PresenceServiceTests
service.IsAnyoneHome().Should().BeFalse();
foreach (var personEntityId in LightMonitorConsts.DefaultPersonEntityIds)
{
_haContextMock.Verify(x => x.GetState(personEntityId), Times.Once);
}
}
}
@@ -1,3 +1,5 @@
#region
using LightMonitor.Models;
using LightMonitorManager.Interface;
using Microsoft.Extensions.Logging;
@@ -5,6 +7,8 @@ using Microsoft.Extensions.Options;
using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
#endregion
namespace LightMonitorManager;
public sealed class LightControlService(
+10 -1
View File
@@ -1,3 +1,5 @@
#region
using LightMonitor.Models;
using LightMonitorManager.Interface;
using Microsoft.Extensions.Logging;
@@ -6,6 +8,8 @@ using NetDaemon.AppModel;
using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
#endregion
namespace LightMonitorManager;
[NetDaemonApp]
@@ -57,6 +61,7 @@ public sealed class LightMonitorInit
private void SubscribeToSunStateChanges()
{
var sunEntity = new Entity(_haContext, _options.SunEntityId);
sunEntity.StateChanges()
.Subscribe(e =>
{
@@ -80,7 +85,10 @@ public sealed class LightMonitorInit
_logger.LogInformation("Sun went below horizon, checking if anyone is home");
if (_presenceService.IsAnyoneHome()) _lightControlService.TurnOnLight();
if (_presenceService.IsAnyoneHome())
{
_lightControlService.TurnOnLight();
}
}
catch (Exception ex)
{
@@ -94,6 +102,7 @@ public sealed class LightMonitorInit
foreach (var personEntityId in _options.PersonEntityIds)
{
var personEntity = new Entity(_haContext, personEntityId);
personEntity.StateChanges()
.Subscribe(e =>
{
@@ -1,9 +1,13 @@
#region
using LightMonitor.Models;
using LightMonitorManager.Interface;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using NetDaemon.AppModel;
#endregion
namespace LightMonitorManager;
public static class LightMonitorServiceRegistration
@@ -12,9 +16,13 @@ public static class LightMonitorServiceRegistration
{
var options = configuration
.GetSection(LightMonitorOptions.SectionName)
.Get<LightMonitorOptions>() ?? new LightMonitorOptions();
.Get<LightMonitorOptions>() ??
new LightMonitorOptions();
if (!options.Enabled) return services;
if (!options.Enabled)
{
return services;
}
services.AddNetDaemonApp<LightMonitorInit>()
.AddScoped<IPresenceService, PresenceService>()
+8 -1
View File
@@ -1,9 +1,13 @@
#region
using LightMonitor.Models;
using LightMonitorManager.Interface;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NetDaemon.HassModel;
#endregion
namespace LightMonitorManager;
public sealed class PresenceService(
@@ -30,7 +34,10 @@ public sealed class PresenceService(
continue;
}
if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("Person {EntityId} is home", personEntityId);
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("Person {EntityId} is home", personEntityId);
}
return true;
}
@@ -1,5 +1,9 @@
#region
using static LightMonitor.Models.LightMonitorConsts;
#endregion
namespace LightMonitor.Models;
public sealed class LightMonitorOptions
+5 -1
View File
@@ -1,6 +1,10 @@
using System.Globalization;
#region
using System.Globalization;
using AutoMapper;
#endregion
namespace Mappings.Converters;
public class DateTimeTypeConverter : ITypeConverter<string, DateTime>
+5 -1
View File
@@ -1,6 +1,10 @@
using AutoMapper;
#region
using AutoMapper;
using Mappings.Converters;
#endregion
namespace Mappings;
public class GlobalMappingProfile : Profile
+6 -1
View File
@@ -1,7 +1,11 @@
using AutoMapper;
#region
using AutoMapper;
using NordPool.Models;
using NordPool.Models.Dtos;
#endregion
namespace Mappings;
public class NordPoolMappingProfile : Profile
@@ -10,6 +14,7 @@ public class NordPoolMappingProfile : Profile
{
CreateMap<NordPoolDayPriceDto, NordPoolDayPrice>()
.ForMember(destination => destination.Price, options => options.MapFrom(source => source.Price));
CreateMap<NordPoolPriceResultDto, NordPoolPrice>();
}
}
@@ -1,9 +1,13 @@
#region
using FluentAssertions;
using Microsoft.Extensions.Logging;
using Moq;
using NordPool.Models;
using NordPoolManager;
#endregion
namespace NordPool.Manager.Tests;
public class CheapestIntervalsFinderTests
@@ -13,7 +17,7 @@ public class CheapestIntervalsFinderTests
private static readonly DateTime DayStart = NordPoolTestData.DayStart;
private static readonly DateTime DeadlineEndOfDay = DayStart.AddDays(1);
private readonly Mock<ILogger<CheapestIntervalsFinder>> _loggerMock = new();
private readonly Mock<ILogger<CheapestIntervalsFinder>> _loggerMock = new Mock<ILogger<CheapestIntervalsFinder>>();
private CheapestIntervalsFinder CreateSut()
{
@@ -55,7 +59,7 @@ public class CheapestIntervalsFinderTests
#region FindCheapestIntervals
public static TheoryData<string, double[], int, double, double, int> FilteringCases => new()
public static TheoryData<string, double[], int, double, double, int> FilteringCases => new TheoryData<string, double[], int, double, double, int>
{
{ "deadline includes interval ending exactly at it", [4.93, 5.63, 6.20], 10, double.MaxValue, 1_800.0, 2 },
{ "deadline excludes interval ending one second late", [4.93, 5.63, 6.20], 10, double.MaxValue, 1_799.0, 1 },
@@ -236,12 +240,13 @@ public class CheapestIntervalsFinderTests
{
// Arrange — duplicate payload entries are not deduplicated
var sut = CreateSut();
var prices = new NordPoolPrice
{
Prices = new List<NordPoolDayPrice>
{
new() { Start = DayStart, End = DayStart.AddMinutes(15), Price = 6.20 },
new() { Start = DayStart, End = DayStart.AddMinutes(15), Price = 6.20 }
new NordPoolDayPrice { Start = DayStart, End = DayStart.AddMinutes(15), Price = 6.20 },
new NordPoolDayPrice { Start = DayStart, End = DayStart.AddMinutes(15), Price = 6.20 }
}
};
@@ -258,15 +263,16 @@ public class CheapestIntervalsFinderTests
{
// Arrange
var sut = CreateSut();
var prices = new NordPoolPrice
{
Prices = new List<NordPoolDayPrice>
{
new() { Start = DayStart, End = DayStart.AddMinutes(15), Price = 8.96 },
new() { Start = DayStart.AddMinutes(15), End = DayStart.AddMinutes(30), Price = null },
new() { Start = DayStart.AddMinutes(30), End = DayStart.AddMinutes(45), Price = 6.20 },
new() { Start = null, End = DayStart.AddMinutes(60), Price = 4.93 },
new() { Start = DayStart.AddMinutes(60), End = null, Price = 5.63 }
new NordPoolDayPrice { Start = DayStart, End = DayStart.AddMinutes(15), Price = 8.96 },
new NordPoolDayPrice { Start = DayStart.AddMinutes(15), End = DayStart.AddMinutes(30), Price = null },
new NordPoolDayPrice { Start = DayStart.AddMinutes(30), End = DayStart.AddMinutes(45), Price = 6.20 },
new NordPoolDayPrice { Start = null, End = DayStart.AddMinutes(60), Price = 4.93 },
new NordPoolDayPrice { Start = DayStart.AddMinutes(60), End = null, Price = 5.63 }
}
};
@@ -315,6 +321,7 @@ public class CheapestIntervalsFinderTests
{
// Arrange - xUnit cannot serialize CheapestIntervalResult rows, so the matrix is exercised in one test
var sut = CreateSut();
(string Scenario, int NowSeconds, CheapestIntervalResult[] Intervals, bool Expected)[] cases =
[
("inside interval", 10 * Hour + 7 * 60, [Interval(10 * Hour, 10 * Hour + Quarter)], true),
@@ -1,21 +1,25 @@
#region
using System.Text;
using System.Text.Json;
using FluentAssertions;
using NordPool.Models;
using static NordPool.Models.NordPoolConsts;
#endregion
namespace NordPool.Manager.Tests;
public class CompactNordPoolDayPriceTests
{
private const int IntervalDurationSeconds = MinutesPerInterval * 60;
private static readonly DateTime TestStart = new(2026, 3, 31, 10, 0, 0, DateTimeKind.Utc);
private static readonly DateTime TestStart = new DateTime(2026, 3, 31, 10, 0, 0, DateTimeKind.Utc);
private static readonly DateTime TestEnd = TestStart.AddMinutes(MinutesPerInterval);
private static readonly long TestStartEpoch = new DateTimeOffset(TestStart).ToUnixTimeSeconds();
private static readonly long TestEndEpoch = new DateTimeOffset(TestEnd).ToUnixTimeSeconds();
public static TheoryData<string, string> InvalidJsonPayloads => new()
public static TheoryData<string, string> InvalidJsonPayloads => new TheoryData<string, string>
{
{ "empty array", "[]" },
{ "too few elements", "[1,2]" },
@@ -157,8 +161,8 @@ public class CompactNordPoolDayPriceTests
{
var prices = new List<CompactNordPoolDayPrice>
{
new() { Start = TestStartEpoch, End = TestEndEpoch, Price = 12.50 },
new() { Start = TestEndEpoch, End = TestEndEpoch + IntervalDurationSeconds, Price = 13.26 }
new CompactNordPoolDayPrice { Start = TestStartEpoch, End = TestEndEpoch, Price = 12.50 },
new CompactNordPoolDayPrice { Start = TestEndEpoch, End = TestEndEpoch + IntervalDurationSeconds, Price = 13.26 }
};
var json = JsonSerializer.Serialize(prices);
@@ -198,8 +202,8 @@ public class CompactNordPoolDayPriceTests
{
var prices = new List<NordPoolDayPrice>
{
new() { Start = TestStart, End = TestEnd, Price = 12.50 },
new() { Start = TestEnd, End = TestEnd.AddMinutes(MinutesPerInterval), Price = 13.26 }
new NordPoolDayPrice { Start = TestStart, End = TestEnd, Price = 12.50 },
new NordPoolDayPrice { Start = TestEnd, End = TestEnd.AddMinutes(MinutesPerInterval), Price = 13.26 }
};
var result = prices.ToCompact();
@@ -240,7 +244,10 @@ public class CompactNordPoolDayPriceTests
result.Should().HaveCount(96);
result.Should().BeInAscendingOrder(p => p.Start);
result[0].Start.Should().Be(new DateTimeOffset(NordPoolTestData.DayStart).ToUnixTimeSeconds());
result[95].Start.Should().Be(new DateTimeOffset(NordPoolTestData.DayStart.AddMinutes(95 * MinutesPerInterval))
result[95]
.Start.Should()
.Be(new DateTimeOffset(NordPoolTestData.DayStart.AddMinutes(95 * MinutesPerInterval))
.ToUnixTimeSeconds());
}
@@ -262,7 +269,7 @@ public class CompactNordPoolDayPriceTests
{
var prices = new List<NordPoolDayPrice>
{
new() { Start = null, End = null, Price = null }
new NordPoolDayPrice { Start = null, End = null, Price = null }
};
var result = prices.ToCompact();
@@ -280,6 +287,7 @@ public class CompactNordPoolDayPriceTests
var prices = NordPoolTestData.CreateIntervals(MaxExpectedPriceEntries, i => 4.93 + i * 0.22);
var compactPrices = prices.ToCompact();
var attributePayload = new
{
prices = compactPrices,
@@ -287,10 +295,12 @@ public class CompactNordPoolDayPriceTests
friendly_name = "NordPool today and tomorrow prices",
last_updated = DateTime.UtcNow.ToString("O")
};
var json = JsonSerializer.Serialize(attributePayload);
var byteCount = Encoding.UTF8.GetByteCount(json);
byteCount.Should().BeLessThan(haAttributeByteLimitBytes,
byteCount.Should()
.BeLessThan(haAttributeByteLimitBytes,
$"serialized attribute payload is {byteCount} bytes, exceeding HA's {haAttributeByteLimitBytes}-byte limit");
}
}
@@ -21,6 +21,7 @@
<PackageReference Include="AutoMapper" Version="17.0.0"/>
<PackageReference Include="FluentAssertions" Version="8.11.0"/>
<PackageReference Include="Moq" Version="4.21.0"/>
<PackageReference Include="Microsoft.Extensions.TimeProvider.Testing" Version="11.0.1"/>
</ItemGroup>
<ItemGroup>
@@ -1,3 +1,5 @@
#region
using System.Text;
using System.Text.Json;
using FluentAssertions;
@@ -8,6 +10,8 @@ using NordPool.Models;
using NordPoolManager;
using NordPoolManager.Models;
#endregion
namespace NordPool.Manager.Tests;
public class NordPoolEntityServiceTests
@@ -113,10 +117,12 @@ public class NordPoolEntityServiceTests
{
// Arrange
var callCount = 0;
_entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny<NordPoolEntity>()))
.Returns(() =>
{
callCount++;
return callCount == 2
? throw new InvalidOperationException("Entity creation failed")
: Task.CompletedTask;
@@ -222,6 +228,7 @@ public class NordPoolEntityServiceTests
{
// Arrange
var attributes = new { unit_of_measurement = "EUR/kWh" };
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask);
@@ -237,6 +244,7 @@ public class NordPoolEntityServiceTests
{
// Arrange
var attributes = new { unit_of_measurement = "EUR/kWh" };
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.ThrowsAsync(new InvalidOperationException("Attributes update failed"));
@@ -257,6 +265,7 @@ public class NordPoolEntityServiceTests
// Arrange
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask);
@@ -265,11 +274,13 @@ public class NordPoolEntityServiceTests
// Assert
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_last_update_time", "unknown"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_current_price", ""), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_current_price", string.Empty), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_today_prices", "0"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_tomorrow_prices", "0"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices", "unknown"),
Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_cheapest_intervals", "0"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("button.nordpool_fetch_prices", "unknown"), Times.Once);
}
@@ -280,6 +291,7 @@ public class NordPoolEntityServiceTests
// Arrange
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask);
@@ -289,16 +301,22 @@ public class NordPoolEntityServiceTests
// Assert
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_last_update_time", It.IsAny<object>()),
Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_current_price", It.IsAny<object>()),
Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_today_prices", It.IsAny<object>()),
Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_tomorrow_prices", It.IsAny<object>()),
Times.Once);
_entityManagerMock.Verify(
em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny<object>()), Times.Once);
_entityManagerMock.Verify(
em => em.SetEntityAttributes("sensor.nordpool_cheapest_intervals", It.IsAny<object>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("button.nordpool_fetch_prices", It.IsAny<object>()),
Times.Once);
}
@@ -309,9 +327,11 @@ public class NordPoolEntityServiceTests
// Arrange
_entityManagerMock.Setup(em => em.SetEntityState("sensor.nordpool_current_price", It.IsAny<string>()))
.ThrowsAsync(new InvalidOperationException("State update failed"));
_entityManagerMock.Setup(em =>
em.SetEntityState(It.Is<string>(id => id != "sensor.nordpool_current_price"), It.IsAny<string>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask);
@@ -328,6 +348,7 @@ public class NordPoolEntityServiceTests
// Arrange - 7 entities get state and attributes
_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);
@@ -336,6 +357,7 @@ public class NordPoolEntityServiceTests
// Assert
_entityManagerMock.Verify(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()), Times.Exactly(7));
_entityManagerMock.Verify(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()),
Times.Exactly(7));
}
@@ -356,13 +378,15 @@ public class NordPoolEntityServiceTests
DayQuartersIndex = 5,
LastApiUpdateDate = DateTime.UtcNow,
UsingCachedData = false,
TodayNordPoolPrice = todayPrice ?? new NordPoolPrice
TodayNordPoolPrice = todayPrice ??
new NordPoolPrice
{
Prices = new List<NordPoolDayPrice> { new() { Price = 12.50 } }
Prices = new List<NordPoolDayPrice> { new NordPoolDayPrice { Price = 12.50 } }
},
TomorrowNordPoolPrice = tomorrowPrice ?? new NordPoolPrice
TomorrowNordPoolPrice = tomorrowPrice ??
new NordPoolPrice
{
Prices = new List<NordPoolDayPrice> { new() { Price = 18.71 } }
Prices = new List<NordPoolDayPrice> { new NordPoolDayPrice { Price = 18.71 } }
},
CheapestIntervals = [],
ConfiguredHours = 2.0,
@@ -383,6 +407,7 @@ public class NordPoolEntityServiceTests
_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);
@@ -392,12 +417,15 @@ public class NordPoolEntityServiceTests
// Assert
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_last_update_time", It.IsAny<string>()),
Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_current_price", "17.91"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_today_prices", "1"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_tomorrow_prices", "1"), Times.Once);
_entityManagerMock.Verify(
em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices",
It.Is<string>(s => s.Contains('-') && s.Contains(':'))), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_cheapest_intervals", It.IsAny<string>()),
Times.Once);
}
@@ -410,6 +438,7 @@ public class NordPoolEntityServiceTests
_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);
@@ -419,10 +448,13 @@ public class NordPoolEntityServiceTests
// Assert
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_current_price", It.IsAny<object>()),
Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_today_prices", It.IsAny<object>()),
Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_tomorrow_prices", It.IsAny<object>()),
Times.Once);
_entityManagerMock.Verify(
em => em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny<object>()), Times.Once);
}
@@ -437,6 +469,7 @@ public class NordPoolEntityServiceTests
_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);
@@ -446,13 +479,13 @@ public class NordPoolEntityServiceTests
// Assert
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_today_prices", "0"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_tomorrow_prices", "0"), Times.Once);
_entityManagerMock.Verify(
em => em.SetEntityState("sensor.nordpool_today_tomorrow_prices", It.Is<string>(s =>
s.Length > 0 && s != "0" && s.Contains('-'))),
Times.Once);
}
[Fact]
public async Task UpdateEntitiesAsync_WithMergedPriceScenarios_ShouldPublishSortedFilteredPrices()
{
@@ -519,12 +552,15 @@ public class NordPoolEntityServiceTests
{
// Arrange
object? capturedAttributes = null;
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em =>
em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny<object>()))
.Callback<string, object>((_, attrs) => capturedAttributes = attrs)
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em =>
em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_today_tomorrow_prices"),
It.IsAny<object>()))
@@ -566,10 +602,12 @@ public class NordPoolEntityServiceTests
}
]
};
var context = CreateDefaultContext(todayPrice: todayPrice, tomorrowPrice: new NordPoolPrice { Prices = [] });
_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);
@@ -592,27 +630,34 @@ public class NordPoolEntityServiceTests
var todayStart = new DateTime(2026, 3, 31, 0, 0, 0, DateTimeKind.Utc);
var tomorrowStart = new DateTime(2026, 4, 1, 0, 0, 0, DateTimeKind.Utc);
var todayPrices = Enumerable.Range(0, intervalsPerDay).Select(i => new NordPoolDayPrice
var todayPrices = Enumerable.Range(0, intervalsPerDay)
.Select(i => new NordPoolDayPrice
{
Start = todayStart.AddMinutes(i * NordPoolConsts.MinutesPerInterval),
End = todayStart.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval),
Price = 4.93 + i * 0.22
}).ToList();
})
.ToList();
var tomorrowPrices = Enumerable.Range(0, intervalsPerDay).Select(i => new NordPoolDayPrice
var tomorrowPrices = Enumerable.Range(0, intervalsPerDay)
.Select(i => new NordPoolDayPrice
{
Start = tomorrowStart.AddMinutes(i * NordPoolConsts.MinutesPerInterval),
End = tomorrowStart.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval),
Price = 5.50 + i * 0.22
}).ToList();
})
.ToList();
object? capturedAttributes = null;
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em =>
em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny<object>()))
.Callback<string, object>((_, attrs) => capturedAttributes = attrs)
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em =>
em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_today_tomorrow_prices"),
It.IsAny<object>()))
@@ -629,7 +674,9 @@ public class NordPoolEntityServiceTests
capturedAttributes.Should().NotBeNull();
var json = JsonSerializer.Serialize(capturedAttributes);
var byteCount = Encoding.UTF8.GetByteCount(json);
byteCount.Should().BeLessThan(haAttributeByteLimitBytes,
byteCount.Should()
.BeLessThan(haAttributeByteLimitBytes,
$"today+tomorrow attribute payload is {byteCount} bytes, exceeding HA's {haAttributeByteLimitBytes}-byte limit");
}
@@ -647,6 +694,7 @@ public class NordPoolEntityServiceTests
_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);
@@ -662,11 +710,14 @@ public class NordPoolEntityServiceTests
{
// Arrange
object? capturedAttributes = null;
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_current_price", It.IsAny<object>()))
.Callback<string, object>((_, attrs) => capturedAttributes = attrs)
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em =>
em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_current_price"), It.IsAny<object>()))
.Returns(Task.CompletedTask);
@@ -700,11 +751,14 @@ public class NordPoolEntityServiceTests
{
// Arrange
object? capturedAttributes = null;
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_cheapest_intervals", It.IsAny<object>()))
.Callback<string, object>((_, attrs) => capturedAttributes = attrs)
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em =>
em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_cheapest_intervals"),
It.IsAny<object>()))
@@ -717,6 +771,7 @@ public class NordPoolEntityServiceTests
Price = 4.93,
Rank = 1
};
var second = new CheapestIntervalResult
{
Start = new DateTime(2026, 3, 31, 23, 0, 0, DateTimeKind.Utc),
@@ -746,8 +801,10 @@ public class NordPoolEntityServiceTests
capturedAttributes.Should().NotBeNull();
var attributes = capturedAttributes!;
var type = attributes.GetType();
((IEnumerable<CheapestIntervalResult>)type.GetProperty("intervals")!.GetValue(attributes)!).Should()
.HaveCount(2);
type.GetProperty("total_heating_minutes")!.GetValue(attributes).Should().Be(30);
type.GetProperty("is_now_cheap")!.GetValue(attributes).Should().Be(true);
type.GetProperty("next_cheap_interval")!.GetValue(attributes).Should().Be(first.Start.ToString("O"));
@@ -763,11 +820,14 @@ public class NordPoolEntityServiceTests
{
// Arrange
object? capturedAttributes = null;
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes("sensor.nordpool_cheapest_intervals", It.IsAny<object>()))
.Callback<string, object>((_, attrs) => capturedAttributes = attrs)
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em =>
em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_cheapest_intervals"),
It.IsAny<object>()))
@@ -794,18 +854,22 @@ public class NordPoolEntityServiceTests
{
// Arrange
object? capturedAttributes = null;
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em =>
em.SetEntityAttributes("sensor.nordpool_today_tomorrow_prices", It.IsAny<object>()))
.Callback<string, object>((_, attrs) => capturedAttributes = attrs)
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em =>
em.SetEntityAttributes(It.Is<string>(id => id != "sensor.nordpool_today_tomorrow_prices"),
It.IsAny<object>()))
.Returns(Task.CompletedTask);
var dayStart = new DateTime(2026, 3, 31, 0, 0, 0, DateTimeKind.Utc);
var todayPrice = new NordPoolPrice
{
Prices =
@@ -815,6 +879,7 @@ public class NordPoolEntityServiceTests
new NordPoolDayPrice { Start = null, End = dayStart.AddHours(3).AddMinutes(15), Price = 1.0 }
]
};
var tomorrowPrice = new NordPoolPrice
{
Prices =
@@ -823,6 +888,7 @@ public class NordPoolEntityServiceTests
{ Start = dayStart.AddHours(0.5), End = dayStart.AddHours(0.5).AddMinutes(15), Price = 18.71 }
]
};
var context = CreateDefaultContext(todayPrice: todayPrice, tomorrowPrice: tomorrowPrice);
// Act
@@ -844,23 +910,30 @@ public class NordPoolEntityServiceTests
// Arrange
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask);
var todayStart = new DateTime(2026, 3, 31, 0, 0, 0, DateTimeKind.Utc);
var tomorrowStart = new DateTime(2026, 4, 1, 0, 0, 0, DateTimeKind.Utc);
var todayPrices = Enumerable.Range(0, 100).Select(i => new NordPoolDayPrice
var todayPrices = Enumerable.Range(0, 100)
.Select(i => new NordPoolDayPrice
{
Start = todayStart.AddMinutes(i * NordPoolConsts.MinutesPerInterval),
End = todayStart.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval),
Price = 10.0
}).ToList();
var tomorrowPrices = Enumerable.Range(0, 100).Select(i => new NordPoolDayPrice
})
.ToList();
var tomorrowPrices = Enumerable.Range(0, 100)
.Select(i => new NordPoolDayPrice
{
Start = tomorrowStart.AddMinutes(i * NordPoolConsts.MinutesPerInterval),
End = tomorrowStart.AddMinutes((i + 1) * NordPoolConsts.MinutesPerInterval),
Price = 10.0
}).ToList();
})
.ToList();
var context = CreateDefaultContext(
todayPrice: new NordPoolPrice { Prices = todayPrices },
@@ -895,6 +968,7 @@ public class NordPoolEntityServiceTests
data.Add("reset entities", sut => sut.ResetEntitiesAsync(cancelled));
data.Add("update entities", sut => sut.UpdateEntitiesAsync(context, cancelled));
data.Add("cleanup entities", sut => sut.CleanupEntitiesAsync(cancelled));
return data;
}
+18 -2
View File
@@ -1,3 +1,5 @@
#region
using System.Reactive.Concurrency;
using BoilerMonitor.Models;
using FluentAssertions;
@@ -11,6 +13,8 @@ using NordPoolManager;
using NordPoolManager.Interface;
using NordPoolManager.Models;
#endregion
namespace NordPool.Manager.Tests;
public class NordPoolInitTests
@@ -41,24 +45,31 @@ public class NordPoolInitTests
_priceServiceMock
.Setup(p => p.FetchPricesAsync(It.IsAny<Func<DateOnly, Task<NordPoolPrice>>>()))
.Returns(Task.CompletedTask);
_entityServiceMock.Setup(e => e.CleanupEntitiesAsync(It.IsAny<CancellationToken>()))
.Returns(Task.CompletedTask);
_entityServiceMock.Setup(e => e.CreateEntitiesAsync(It.IsAny<string>())).Returns(Task.CompletedTask);
_entityServiceMock.Setup(e => e.ResetEntitiesAsync()).Returns(Task.CompletedTask);
_entityServiceMock.Setup(e => e.UpdateEntitiesAsync(It.IsAny<EntityUpdateContext>()))
.Returns(Task.CompletedTask);
_priceServiceMock.Setup(p => p.GetCurrentPrice()).Returns(0.0);
_priceServiceMock.Setup(p => p.ShouldFetchNewPrices(It.IsAny<DateOnly>())).Returns(false);
_priceServiceMock.Setup(p => p.ShouldFetchTodaysPrices(It.IsAny<DateOnly>())).Returns(false);
_priceServiceMock.SetupGet(p => p.DayQuartersIndex).Returns(0);
_priceServiceMock.SetupGet(p => p.TodayNordPoolPrice).Returns((NordPoolPrice?)null);
_priceServiceMock.SetupGet(p => p.TomorrowNordPoolPrice).Returns((NordPoolPrice?)null);
_priceServiceMock.SetupGet(p => p.CurrentPrice).Returns(0.0);
_priceServiceMock.SetupGet(p => p.LastUpdatedDate).Returns((DateTime?)null);
_cheapestIntervalsFinderMock
.Setup(c => c.IsCurrentIntervalCheap(It.IsAny<IReadOnlyList<CheapestIntervalResult>>(),
It.IsAny<DateTime>()))
.Returns(false);
_boilerConfigProviderMock.Setup(b => b.GetCurrentConfiguration()).Returns(new BoilerConfig
_boilerConfigProviderMock.Setup(b => b.GetCurrentConfiguration())
.Returns(new BoilerConfig
{
IntervalCount = 4,
PriceCap = double.MaxValue,
@@ -109,9 +120,12 @@ public class NordPoolInitTests
_entityServiceMock.Verify(
es => es.CleanupEntitiesAsync(It.IsAny<CancellationToken>()),
cleanupEntitiesOnStartup ? Times.AtLeastOnce() : Times.Never());
_entityServiceMock.Verify(es => es.CreateEntitiesAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()),
Times.AtLeastOnce);
_entityServiceMock.Verify(es => es.ResetEntitiesAsync(It.IsAny<CancellationToken>()), Times.AtLeastOnce);
_entityServiceMock.Verify(
es => es.UpdateEntitiesAsync(It.IsAny<EntityUpdateContext>(), It.IsAny<CancellationToken>()),
Times.AtLeastOnce);
@@ -121,6 +135,7 @@ public class NordPoolInitTests
public async Task InitializeAsync_WhenCreatingEntitiesFails_ShouldRethrow()
{
var sut = CreateSut(new NordPoolOptions { CleanupEntitiesOnStartup = false });
_entityServiceMock
.Setup(es => es.CreateEntitiesAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()))
.ThrowsAsync(new InvalidOperationException("create failed"));
@@ -129,6 +144,7 @@ public class NordPoolInitTests
await act.Should().ThrowAsync<InvalidOperationException>().WithMessage("create failed");
_entityServiceMock.Verify(es => es.ResetEntitiesAsync(It.IsAny<CancellationToken>()), Times.Never);
_entityServiceMock.Verify(
es => es.UpdateEntitiesAsync(It.IsAny<EntityUpdateContext>(), It.IsAny<CancellationToken>()), Times.Never);
}
@@ -1,26 +1,34 @@
using System.Globalization;
#region
using System.Globalization;
using System.Text.Json;
using AutoMapper;
using FluentAssertions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Time.Testing;
using Moq;
using NordPool.Models;
using NordPool.Models.Dtos;
using NordPoolManager;
#endregion
namespace NordPool.Manager.Tests;
public class NordPoolPriceServiceTests
{
private readonly Mock<IMapper> _mapperMock;
private readonly NordPoolPriceService _sut;
private readonly FakeTimeProvider _timeProvider;
public NordPoolPriceServiceTests()
{
_mapperMock = new Mock<IMapper>();
var loggerMock = new Mock<ILogger<NordPoolPriceService>>();
_sut = new NordPoolPriceService(_mapperMock.Object, loggerMock.Object);
// 2026-12-01 10:00 UTC = 11:00 CET — before tomorrow's prices are published
_timeProvider = new FakeTimeProvider(new DateTimeOffset(2026, 12, 1, 10, 0, 0, TimeSpan.Zero));
_sut = new NordPoolPriceService(_mapperMock.Object, loggerMock.Object, _timeProvider);
}
#region GetTimeQuarterIndex
@@ -110,13 +118,16 @@ public class NordPoolPriceServiceTests
{
// Arrange & Act — iterate over a full UTC day; CET conversion produces 96 unique quarter indices
var indices = new HashSet<int>();
for (var hour = 0; hour < 24; hour++)
{
for (var minute = 0; minute < 60; minute += 15)
{
var date = new DateTime(2026, 3, 31, hour, minute, 0, DateTimeKind.Utc);
var index = NordPoolPriceService.GetTimeQuarterIndex(date);
indices.Add(index);
}
}
// Assert
indices.Should().HaveCount(96);
@@ -127,8 +138,12 @@ public class NordPoolPriceServiceTests
[Theory]
[InlineData(2026, 1, 15, 8, 0, 36)] // CET winter (UTC+1): UTC 08:00 = CET 09:00 -> index 36
[InlineData(2026, 7, 15, 8, 0, 40)] // CEST summer (UTC+2): UTC 08:00 = CEST 10:00 -> index 40
public void GetTimeQuarterIndex_ShouldHandleDaylightSavingTimeCorrectly(int year, int month, int day, int hour,
int minute, int expectedIndex)
public void GetTimeQuarterIndex_ShouldHandleDaylightSavingTimeCorrectly(int year,
int month,
int day,
int hour,
int minute,
int expectedIndex)
{
// Arrange
var testDate = new DateTime(year, month, day, hour, minute, 0, DateTimeKind.Utc);
@@ -245,7 +260,7 @@ public class NordPoolPriceServiceTests
{
Prices = new List<NordPoolDayPrice>
{
new()
new NordPoolDayPrice
{
Start = DateTime.Parse(dto.Prices[0].Start!, CultureInfo.InvariantCulture),
End = DateTime.Parse(dto.Prices[0].End!, CultureInfo.InvariantCulture), Price = 100.0
@@ -322,9 +337,9 @@ public class NordPoolPriceServiceTests
{
Prices = new List<NordPoolDayPrice>
{
new() { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = 81.0 },
new() { Start = DateTime.UtcNow.AddHours(1), End = DateTime.UtcNow.AddHours(2), Price = 148.0 },
new() { Start = DateTime.UtcNow.AddHours(2), End = DateTime.UtcNow.AddHours(3), Price = 215.0 }
new NordPoolDayPrice { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = 81.0 },
new NordPoolDayPrice { Start = DateTime.UtcNow.AddHours(1), End = DateTime.UtcNow.AddHours(2), Price = 148.0 },
new NordPoolDayPrice { Start = DateTime.UtcNow.AddHours(2), End = DateTime.UtcNow.AddHours(3), Price = 215.0 }
}
};
@@ -347,9 +362,9 @@ public class NordPoolPriceServiceTests
{
Prices = new List<NordPoolDayPrice>
{
new() { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = 81.0 },
new() { Start = DateTime.UtcNow.AddHours(1), End = DateTime.UtcNow.AddHours(2), Price = null },
new() { Start = DateTime.UtcNow.AddHours(2), End = DateTime.UtcNow.AddHours(3), Price = 215.0 }
new NordPoolDayPrice { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = 81.0 },
new NordPoolDayPrice { Start = DateTime.UtcNow.AddHours(1), End = DateTime.UtcNow.AddHours(2), Price = null },
new NordPoolDayPrice { Start = DateTime.UtcNow.AddHours(2), End = DateTime.UtcNow.AddHours(3), Price = 215.0 }
}
};
@@ -388,7 +403,7 @@ public class NordPoolPriceServiceTests
{
Prices = new List<NordPoolDayPrice>
{
new() { Start = startTime, End = endTime, Price = 81.0 }
new NordPoolDayPrice { Start = startTime, End = endTime, Price = 81.0 }
}
};
@@ -424,8 +439,8 @@ public class NordPoolPriceServiceTests
{
Prices = new List<NordPoolDayPrice>
{
new() { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = null },
new() { Start = DateTime.UtcNow.AddHours(1), End = DateTime.UtcNow.AddHours(2), Price = null }
new NordPoolDayPrice { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = null },
new NordPoolDayPrice { Start = DateTime.UtcNow.AddHours(1), End = DateTime.UtcNow.AddHours(2), Price = null }
}
};
@@ -445,7 +460,7 @@ public class NordPoolPriceServiceTests
{
Prices = new List<NordPoolDayPrice>
{
new() { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = 81.0 }
new NordPoolDayPrice { Start = DateTime.UtcNow, End = DateTime.UtcNow.AddHours(1), Price = 81.0 }
}
};
@@ -469,12 +484,14 @@ public class NordPoolPriceServiceTests
var prices = new List<NordPoolDayPrice>();
for (var i = 0; i < 96; i++)
{
prices.Add(new NordPoolDayPrice
{
Start = now.AddMinutes(i * 15),
End = now.AddMinutes((i + 1) * 15),
Price = 5.0 + i * 0.22
});
}
_sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices };
@@ -529,11 +546,14 @@ public class NordPoolPriceServiceTests
public void UpdateCurrentPrice_WhenSameQuarterIndex_ShouldReturnCachedPrice()
{
// Arrange
var expectedIndex = NordPoolPriceService.GetTimeQuarterIndex(DateTime.UtcNow);
var expectedIndex = NordPoolPriceService.GetTimeQuarterIndex(_timeProvider.GetUtcNow().UtcDateTime);
var prices = new List<NordPoolDayPrice>();
for (var i = 0; i < 96; i++)
{
prices.Add(new NordPoolDayPrice { Price = 4.0 + i * 0.23 });
}
_sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices };
_sut.DayQuartersIndex = expectedIndex;
@@ -552,8 +572,11 @@ public class NordPoolPriceServiceTests
{
// Arrange
var prices = new List<NordPoolDayPrice>();
for (var i = 0; i < 96; i++)
{
prices.Add(new NordPoolDayPrice { Price = null });
}
_sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices };
_sut.CurrentPrice = 17.91;
@@ -572,8 +595,11 @@ public class NordPoolPriceServiceTests
{
// Arrange
var prices = new List<NordPoolDayPrice>();
for (var i = 0; i < 96; i++)
{
prices.Add(new NordPoolDayPrice { Price = 5.0 + i * 0.22 });
}
_sut.TodayNordPoolPrice = new NordPoolPrice { Prices = prices };
_sut.DayQuartersIndex = -1;
@@ -594,7 +620,8 @@ public class NordPoolPriceServiceTests
public void UpdateCurrentPrice_WhenCurrentQuarterHasPrice_ShouldStoreThatPrice(double expectedPrice)
{
// Arrange — negative and zero spot prices are valid NordPool scenarios
var index = NordPoolPriceService.GetTimeQuarterIndex(DateTime.UtcNow);
var index = NordPoolPriceService.GetTimeQuarterIndex(_timeProvider.GetUtcNow().UtcDateTime);
var prices = NordPoolTestData.CreateIntervals(
NordPoolConsts.MaxDailyIntervals,
i => i == index ? expectedPrice : 10.0);
@@ -615,7 +642,8 @@ public class NordPoolPriceServiceTests
public void UpdateCurrentPrice_WhenCurrentIndexIsOutsidePricesRange_ShouldKeepPreviousPriceButAdvanceIndex()
{
// Arrange — fewer prices than the current quarter index (e.g. partial day payload)
var index = NordPoolPriceService.GetTimeQuarterIndex(DateTime.UtcNow);
var index = NordPoolPriceService.GetTimeQuarterIndex(_timeProvider.GetUtcNow().UtcDateTime);
var prices = Enumerable.Range(0, index)
.Select(i => new NordPoolDayPrice { Price = 10.0 + i })
.ToList();
@@ -636,7 +664,8 @@ public class NordPoolPriceServiceTests
public void UpdateCurrentPrice_WhenQuarterIndexUnchangedButPricesChanged_ShouldKeepCachedPrice()
{
// Arrange
var index = NordPoolPriceService.GetTimeQuarterIndex(DateTime.UtcNow);
var index = NordPoolPriceService.GetTimeQuarterIndex(_timeProvider.GetUtcNow().UtcDateTime);
var prices = Enumerable.Range(0, NordPoolConsts.MaxDailyIntervals)
.Select(_ => new NordPoolDayPrice { Price = 99.0 })
.ToList();
@@ -657,7 +686,8 @@ public class NordPoolPriceServiceTests
public void UpdateCurrentPrice_WhenOnlyCurrentQuarterPriceIsNull_ShouldKeepPreviousPriceAndAdvanceIndex()
{
// Arrange
var index = NordPoolPriceService.GetTimeQuarterIndex(DateTime.UtcNow);
var index = NordPoolPriceService.GetTimeQuarterIndex(_timeProvider.GetUtcNow().UtcDateTime);
var prices = Enumerable.Range(0, NordPoolConsts.MaxDailyIntervals)
.Select(i => new NordPoolDayPrice { Price = i == index ? null : 10.0 })
.ToList();
@@ -679,14 +709,15 @@ public class NordPoolPriceServiceTests
#region FetchPricesAsync
[Fact]
public async Task FetchPricesAsync_WhenNoCachedPrices_ShouldFetchTodayAndTomorrowViaDelegate()
public async Task FetchPricesAsync_WhenNoCachedPricesBeforePublishHour_ShouldOnlyFetchToday()
{
// Arrange
// Arrange — 11:00 CET, tomorrow's prices are not published yet
var requestedDates = new List<DateOnly>();
Task<NordPoolPrice> Fetch(DateOnly date)
{
requestedDates.Add(date);
return Task.FromResult(CreatePrices(1.5));
}
@@ -694,32 +725,74 @@ public class NordPoolPriceServiceTests
await _sut.FetchPricesAsync(Fetch);
// Assert
requestedDates.Should().HaveCount(2);
requestedDates[1].Should().Be(requestedDates[0].AddDays(1));
_sut.TodayNordPoolPrice.Should().NotBeNull();
_sut.TomorrowNordPoolPrice.Should().NotBeNull();
requestedDates.Should().ContainSingle().Which.Should().Be(new DateOnly(2026, 12, 1));
_sut.TodayNordPoolPrice!.Prices![0].Price.Should().Be(1.5);
_sut.TomorrowNordPoolPrice.Should().BeNull();
_sut.LastFetchedDate.Should().Be(new DateOnly(2026, 12, 1));
_sut.LastUpdatedDate.Should().Be(_timeProvider.GetUtcNow().UtcDateTime);
}
[Fact]
public async Task FetchPricesAsync_WhenNoCachedPricesAfterPublishHour_ShouldFetchTodayAndTomorrow()
{
// Arrange — 13:30 CET, tomorrow's prices are published
_timeProvider.SetUtcNow(new DateTimeOffset(2026, 12, 1, 12, 30, 0, TimeSpan.Zero));
var requestedDates = new List<DateOnly>();
Task<NordPoolPrice> Fetch(DateOnly date)
{
requestedDates.Add(date);
return Task.FromResult(CreatePrices(1.5));
}
// Act
await _sut.FetchPricesAsync(Fetch);
// Assert
requestedDates.Should().Equal(new DateOnly(2026, 12, 1), new DateOnly(2026, 12, 2));
_sut.TodayNordPoolPrice!.Prices![0].Price.Should().Be(1.5);
_sut.TomorrowNordPoolPrice!.Prices![0].Price.Should().Be(1.5);
_sut.LastFetchedDate.Should().Be(requestedDates[0]);
_sut.LastUpdatedDate.Should().NotBeNull();
_sut.LastFetchedDate.Should().Be(new DateOnly(2026, 12, 1));
_sut.LastUpdatedDate.Should().Be(_timeProvider.GetUtcNow().UtcDateTime);
}
[Fact]
public async Task FetchPricesAsync_WhenTomorrowPricesMissingBeforePublishHour_ShouldKeepTodayAndSkipTomorrow()
{
// Arrange — today is cached, tomorrow is not published yet
_sut.TodayNordPoolPrice = CreatePrices(1.0);
_sut.LastFetchedDate = new DateOnly(2026, 12, 1);
var requestedDates = new List<DateOnly>();
// Act
await _sut.FetchPricesAsync(date =>
{
requestedDates.Add(date);
return Task.FromResult(CreatePrices(3.0));
});
// Assert
requestedDates.Should().BeEmpty();
_sut.TodayNordPoolPrice!.Prices![0].Price.Should().Be(1.0);
_sut.TomorrowNordPoolPrice.Should().BeNull();
}
[Fact]
public async Task FetchPricesAsync_WhenCachedPricesAlreadyPresent_ShouldNotCallDelegate()
{
// Arrange
var cetTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
var todayCet = DateOnly.FromDateTime(TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, cetTimeZone));
_sut.TodayNordPoolPrice = CreatePrices(1.0);
_sut.TomorrowNordPoolPrice = CreatePrices(2.0);
_sut.LastFetchedDate = todayCet;
_sut.LastFetchedDate = new DateOnly(2026, 12, 1);
var delegateCalled = false;
// Act
await _sut.FetchPricesAsync(_ =>
{
delegateCalled = true;
return Task.FromResult(CreatePrices(3.0));
});
@@ -731,7 +804,7 @@ public class NordPoolPriceServiceTests
#endregion
#region ShouldFetchNewPrices
#region ShouldFetchTodaysPrices
private static NordPoolPrice CreatePrices(params double?[] values)
{
@@ -742,38 +815,33 @@ public class NordPoolPriceServiceTests
}
/// <summary>
/// Scenarios that do not depend on the time of day (tomorrow's prices are published after 13:00,
/// so the "tomorrow missing" cases are covered separately below). xUnit cannot serialize
/// <see cref="NordPoolPrice" /> rows, so the matrix runs inside a single test.
/// xUnit cannot serialize <see cref="NordPoolPrice" /> rows, so the matrix runs inside a single test.
/// </summary>
[Fact]
public void ShouldFetchNewPrices_ShouldMatchScenario()
public void ShouldFetchTodaysPrices_ShouldMatchScenario()
{
var today = DateOnly.FromDateTime(DateTime.Now);
var today = DateOnly.FromDateTime(_timeProvider.GetUtcNow().UtcDateTime);
(string Scenario, DateOnly? LastFetchedDate, NordPoolPrice? TodayPrice, NordPoolPrice? TomorrowPrice, bool
Expected)[] cases =
(string Scenario, DateOnly? LastFetchedDate, NordPoolPrice? TodayPrice, bool Expected)[] cases =
[
("no fetch date yet", null, CreatePrices(12.50), CreatePrices(18.71), true),
("last fetch was yesterday", today.AddDays(-1), CreatePrices(12.50), CreatePrices(18.71), true),
("last fetch date is in the future", today.AddDays(1), CreatePrices(12.50), CreatePrices(18.71), false),
("today prices are null", today, new NordPoolPrice { Prices = null }, CreatePrices(18.71), true),
("today prices are empty", today, new NordPoolPrice { Prices = [] }, CreatePrices(18.71), true),
("today and tomorrow prices present", today, CreatePrices(12.50), CreatePrices(18.71), false),
("price values are null but entries exist", today, CreatePrices((double?)null),
CreatePrices((double?)null), false),
("all price payloads are null", today, null, null, true)
("no fetch date yet", null, CreatePrices(12.50), true),
("last fetch was yesterday", today.AddDays(-1), CreatePrices(12.50), true),
("last fetch date is in the future", today.AddDays(1), CreatePrices(12.50), false),
("today prices are null", today, new NordPoolPrice { Prices = null }, true),
("today prices are empty", today, new NordPoolPrice { Prices = [] }, true),
("today prices present", today, CreatePrices(12.50), false),
("price values are null but entries exist", today, CreatePrices((double?)null), false),
("all price payloads are null", today, null, true)
];
foreach (var (scenario, lastFetchedDate, todayPrice, tomorrowPrice, expected) in cases)
foreach (var (scenario, lastFetchedDate, todayPrice, expected) in cases)
{
// Arrange
_sut.LastFetchedDate = lastFetchedDate;
_sut.TodayNordPoolPrice = todayPrice;
_sut.TomorrowNordPoolPrice = tomorrowPrice;
// Act
var result = _sut.ShouldFetchNewPrices(DateOnly.FromDateTime(DateTime.Now));
var result = _sut.ShouldFetchTodaysPrices(today);
// Assert
result.Should().Be(expected, $"scenario: {scenario}");
@@ -781,41 +849,19 @@ public class NordPoolPriceServiceTests
}
[Fact]
public void ShouldFetchNewPrices_WhenTomorrowPricesAreNull_ShouldDependOnHourOfDay()
public void ShouldFetchTodaysPrices_WhenTomorrowPricesAreMissing_ShouldNotDependOnTomorrowState()
{
// Arrange — tomorrow's prices are not published before 13:00, so cached data is acceptable until then
var today = DateOnly.FromDateTime(DateTime.Now);
// Arrange — tomorrow's prices are irrelevant to today's fetch decision
var today = new DateOnly(2026, 12, 1);
_sut.LastFetchedDate = today;
_sut.TodayNordPoolPrice = new NordPoolPrice
{
Prices = new List<NordPoolDayPrice> { new() { Price = 12.50 } }
};
_sut.TodayNordPoolPrice = CreatePrices(12.50);
_sut.TomorrowNordPoolPrice = new NordPoolPrice { Prices = null };
// Act
var result = _sut.ShouldFetchNewPrices(today);
var result = _sut.ShouldFetchTodaysPrices(today);
// Assert
result.Should().Be(DateTime.Now.Hour >= 13);
}
[Fact]
public void ShouldFetchNewPrices_WhenTomorrowPricesAreEmpty_ShouldDependOnHourOfDay()
{
// Arrange
var today = DateOnly.FromDateTime(DateTime.Now);
_sut.LastFetchedDate = today;
_sut.TodayNordPoolPrice = new NordPoolPrice
{
Prices = new List<NordPoolDayPrice> { new() { Price = 12.50 } }
};
_sut.TomorrowNordPoolPrice = new NordPoolPrice { Prices = new List<NordPoolDayPrice>() };
// Act
var result = _sut.ShouldFetchNewPrices(today);
// Assert
result.Should().Be(DateTime.Now.Hour >= 13);
result.Should().BeFalse();
}
#endregion
@@ -828,13 +874,14 @@ public class NordPoolPriceServiceTests
// Arrange
var tomorrow = new NordPoolPrice
{
Prices = new List<NordPoolDayPrice> { new() { Price = 18.71 } }
Prices = new List<NordPoolDayPrice> { new NordPoolDayPrice { Price = 18.71 } }
};
_sut.TodayNordPoolPrice = new NordPoolPrice
{
Prices = new List<NordPoolDayPrice> { new() { Price = 12.50 } }
Prices = new List<NordPoolDayPrice> { new NordPoolDayPrice { Price = 12.50 } }
};
_sut.TomorrowNordPoolPrice = tomorrow;
_sut.DayQuartersIndex = 48;
var today = new DateOnly(2026, 4, 1);
@@ -855,7 +902,7 @@ public class NordPoolPriceServiceTests
[Fact]
public void RollOverPrices_WithoutUsableTomorrowPrices_ShouldResetTodayToEmptyPrice()
{
NordPoolPrice?[] unusablePrices = [null, new() { Prices = null }, new() { Prices = [] }];
NordPoolPrice?[] unusablePrices = [null, new NordPoolPrice { Prices = null }, new NordPoolPrice { Prices = [] }];
foreach (var tomorrow in unusablePrices)
{
@@ -900,11 +947,12 @@ public class NordPoolPriceServiceTests
// Arrange
var previousToday = new NordPoolPrice
{
Prices = new List<NordPoolDayPrice> { new() { Price = 12.50 } }
Prices = new List<NordPoolDayPrice> { new NordPoolDayPrice { Price = 12.50 } }
};
var tomorrow = new NordPoolPrice
{
Prices = new List<NordPoolDayPrice> { new() { Price = 18.71 } }
Prices = new List<NordPoolDayPrice> { new NordPoolDayPrice { Price = 18.71 } }
};
_sut.TodayNordPoolPrice = previousToday;
+5 -1
View File
@@ -1,5 +1,9 @@
#region
using NordPool.Models;
#endregion
namespace NordPool.Manager.Tests;
/// <summary>
@@ -8,7 +12,7 @@ namespace NordPool.Manager.Tests;
/// </summary>
internal static class NordPoolTestData
{
public static readonly DateTime DayStart = new(2026, 3, 31, 0, 0, 0, DateTimeKind.Utc);
public static readonly DateTime DayStart = new DateTime(2026, 3, 31, 0, 0, 0, DateTimeKind.Utc);
/// <summary>
/// Builds a contiguous set of 15-minute intervals starting at <paramref name="dayStart" />.
@@ -1,7 +1,11 @@
#region
using Microsoft.Extensions.Logging;
using NordPool.Models;
using NordPoolManager.Interface;
#endregion
namespace NordPoolManager;
public class CheapestIntervalsFinder(ILogger<CheapestIntervalsFinder> logger) : ICheapestIntervalsFinder
@@ -1,11 +1,17 @@
#region
using NordPool.Models;
#endregion
namespace NordPoolManager.Interface;
public interface ICheapestIntervalsFinder
{
IReadOnlyList<CheapestIntervalResult> FindCheapestIntervals(NordPoolPrice prices, int numberOfIntervals,
double priceCap, DateTime deadline);
IReadOnlyList<CheapestIntervalResult> FindCheapestIntervals(NordPoolPrice prices,
int numberOfIntervals,
double priceCap,
DateTime deadline);
bool IsCurrentIntervalCheap(IReadOnlyList<CheapestIntervalResult> cheapestIntervals, DateTime utcNow);
}
@@ -1,5 +1,9 @@
#region
using BoilerMonitor.Models;
#endregion
namespace NordPoolManager.Interface;
/// <summary>
@@ -1,5 +1,9 @@
#region
using NordPoolManager.Models;
#endregion
namespace NordPoolManager.Interface;
public interface INordPoolEntityService
@@ -1,6 +1,10 @@
#region
using System.Text.Json;
using NordPool.Models;
#endregion
namespace NordPoolManager.Interface;
public interface INordPoolPriceService
@@ -16,6 +20,6 @@ public interface INordPoolPriceService
NordPoolPrice ParseAndAdjust(JsonElement? element);
void UpdateCurrentPrice();
double GetCurrentPrice();
bool ShouldFetchNewPrices(DateOnly dateOnly);
bool ShouldFetchTodaysPrices(DateOnly dateOnly);
void RollOverPrices(DateOnly date);
}
@@ -1,5 +1,9 @@
#region
using NordPool.Models;
#endregion
namespace NordPoolManager.Models;
public record EntityUpdateContext
@@ -1,6 +1,10 @@
#region
using BoilerMonitor.Models;
using NordPoolManager.Interface;
#endregion
namespace NordPoolManager;
/// <summary>
+46 -15
View File
@@ -1,3 +1,5 @@
#region
using System.Globalization;
using HomeAssistant.Entities.Interfaces;
using Microsoft.Extensions.Logging;
@@ -6,6 +8,8 @@ using NordPool.Models;
using NordPoolManager.Interface;
using NordPoolManager.Models;
#endregion
namespace NordPoolManager;
public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<NordPoolEntityService> logger)
@@ -61,7 +65,8 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
ResetTodayTomorrowPricesAsync(),
ResetCheapestIntervalsAsync(),
ResetFetchPricesButtonAsync()
).ConfigureAwait(false);
)
.ConfigureAwait(false);
}
public async Task UpdateEntitiesAsync(EntityUpdateContext ctx, CancellationToken cancellationToken = default)
@@ -117,6 +122,7 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
catch (Exception ex)
{
logger.LogError(ex, "Error cleaning up NordPool entities");
throw;
}
}
@@ -124,15 +130,18 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
private async Task ResetLastUpdateTimeAsync()
{
await SetEntityStateSafe(LastUpdateTimeEntityId, "unknown").ConfigureAwait(false);
await SetEntityAttributesSafe(LastUpdateTimeEntityId, new
{
friendly_name = "NordPool last update time"
}).ConfigureAwait(false);
})
.ConfigureAwait(false);
}
private async Task ResetCurrentPriceAsync()
{
await SetEntityStateSafe(NordPoolConsts.CurrentPriceEntityId, string.Empty).ConfigureAwait(false);
await SetEntityAttributesSafe(NordPoolConsts.CurrentPriceEntityId, new
{
unit_of_measurement = (string?)null,
@@ -143,68 +152,79 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
last_api_fetch = (string?)null,
using_cached_data = false,
current_quarter_index = 0
}).ConfigureAwait(false);
})
.ConfigureAwait(false);
}
private async Task ResetTodayPricesAsync()
{
await SetEntityStateSafe(TodayPricesEntityId, "0").ConfigureAwait(false);
await SetEntityAttributesSafe(TodayPricesEntityId, new
{
prices = Array.Empty<CompactNordPoolDayPrice>(),
friendly_name = "NordPool today prices",
last_updated = (string?)null
}).ConfigureAwait(false);
})
.ConfigureAwait(false);
}
private async Task ResetTomorrowPricesAsync()
{
await SetEntityStateSafe(TomorrowPricesEntityId, "0").ConfigureAwait(false);
await SetEntityAttributesSafe(TomorrowPricesEntityId, new
{
prices = Array.Empty<CompactNordPoolDayPrice>(),
friendly_name = "NordPool tomorrow prices",
last_updated = (string?)null
}).ConfigureAwait(false);
})
.ConfigureAwait(false);
}
private async Task ResetTodayTomorrowPricesAsync()
{
await SetEntityStateSafe(TodayTomorrowPricesEntityId, "unknown").ConfigureAwait(false);
await SetEntityAttributesSafe(TodayTomorrowPricesEntityId, new
{
prices = Array.Empty<CompactNordPoolDayPrice>(),
prices_count = 0,
friendly_name = "NordPool today and tomorrow prices",
last_updated = (string?)null
}).ConfigureAwait(false);
})
.ConfigureAwait(false);
}
private async Task ResetCheapestIntervalsAsync()
{
await SetEntityStateSafe(CheapestIntervalsEntityId, "0").ConfigureAwait(false);
await SetEntityAttributesSafe(CheapestIntervalsEntityId, new
{
intervals = Array.Empty<CheapestIntervalResult>(),
configured_hours = 0.0,
configured_interval_count = 0,
configured_price_cap = 0.0,
configured_ready_by = "",
configured_ready_by = string.Empty,
total_heating_minutes = 0,
is_now_cheap = false,
next_cheap_interval = (string?)null,
friendly_name = "NordPool cheapest boiler intervals",
last_updated = (string?)null
}).ConfigureAwait(false);
})
.ConfigureAwait(false);
}
private async Task ResetFetchPricesButtonAsync()
{
await SetEntityStateSafe(NordPoolConsts.FetchPricesButtonEntityId, "unknown").ConfigureAwait(false);
await SetEntityAttributesSafe(NordPoolConsts.FetchPricesButtonEntityId, new
{
friendly_name = "NordPool fetch prices"
}).ConfigureAwait(false);
})
.ConfigureAwait(false);
}
private async Task UpdateLastUpdateTimeAsync(string updateTimeState)
@@ -215,6 +235,7 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
private async Task UpdateCurrentPriceAsync(string priceValue, EntityUpdateContext ctx, string timestamp)
{
await SetEntityStateSafe(NordPoolConsts.CurrentPriceEntityId, priceValue).ConfigureAwait(false);
await SetEntityAttributesSafe(NordPoolConsts.CurrentPriceEntityId, new
{
unit_of_measurement = ctx.UnitOfMeasurement,
@@ -225,47 +246,56 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
last_api_fetch = ctx.LastApiUpdateDate?.ToString("O", CultureInfo.InvariantCulture),
using_cached_data = ctx.UsingCachedData,
current_quarter_index = ctx.DayQuartersIndex
}).ConfigureAwait(false);
})
.ConfigureAwait(false);
}
private async Task UpdateTodayPricesAsync(EntityUpdateContext ctx, int todayPricesCount, string timestamp)
{
await SetEntityStateSafe(TodayPricesEntityId, todayPricesCount.ToString()).ConfigureAwait(false);
await SetEntityAttributesSafe(TodayPricesEntityId, new
{
prices = (ctx.TodayNordPoolPrice?.Prices).ToCompact(),
friendly_name = "NordPool today prices",
last_updated = timestamp
}).ConfigureAwait(false);
})
.ConfigureAwait(false);
}
private async Task UpdateTomorrowPricesAsync(EntityUpdateContext ctx, int tomorrowPricesCount, string timestamp)
{
await SetEntityStateSafe(TomorrowPricesEntityId, tomorrowPricesCount.ToString()).ConfigureAwait(false);
await SetEntityAttributesSafe(TomorrowPricesEntityId, new
{
prices = (ctx.TomorrowNordPoolPrice?.Prices).ToCompact(),
friendly_name = "NordPool tomorrow prices",
last_updated = timestamp
}).ConfigureAwait(false);
})
.ConfigureAwait(false);
}
private async Task UpdateTodayTomorrowPricesAsync(List<NordPoolDayPrice> mergedPrices, string updateTimeState,
private async Task UpdateTodayTomorrowPricesAsync(List<NordPoolDayPrice> mergedPrices,
string updateTimeState,
string timestamp)
{
await SetEntityStateSafe(TodayTomorrowPricesEntityId, updateTimeState).ConfigureAwait(false);
await SetEntityAttributesSafe(TodayTomorrowPricesEntityId, new
{
prices = mergedPrices.ToCompact(),
prices_count = mergedPrices.Count,
friendly_name = "NordPool today and tomorrow prices",
last_updated = timestamp
}).ConfigureAwait(false);
})
.ConfigureAwait(false);
}
private async Task UpdateCheapestIntervalsAsync(EntityUpdateContext ctx, int cheapestCount, string timestamp)
{
await SetEntityStateSafe(CheapestIntervalsEntityId, cheapestCount.ToString()).ConfigureAwait(false);
await SetEntityAttributesSafe(CheapestIntervalsEntityId, new
{
intervals = ctx.CheapestIntervals ?? [],
@@ -279,7 +309,8 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
next_cheap_interval = ctx.NextCheapIntervalStart?.ToString("O", CultureInfo.InvariantCulture),
friendly_name = "NordPool cheapest boiler intervals",
last_updated = timestamp
}).ConfigureAwait(false);
})
.ConfigureAwait(false);
}
internal static ICollection<NordPoolEntity> GetInitEntitiesList(string? unitOfMeasurement)
+11 -2
View File
@@ -1,3 +1,5 @@
#region
using System.Globalization;
using System.Reactive.Concurrency;
using BoilerMonitor.Models;
@@ -12,6 +14,8 @@ using NordPool.Models;
using NordPoolManager.Interface;
using NordPoolManager.Models;
#endregion
namespace NordPoolManager;
[NetDaemonApp]
@@ -67,7 +71,10 @@ public class NordPoolInit
{
await Task.Delay(TimeSpan.FromSeconds(3));
if (_options.CleanupEntitiesOnStartup) await _entityService.CleanupEntitiesAsync();
if (_options.CleanupEntitiesOnStartup)
{
await _entityService.CleanupEntitiesAsync();
}
await _entityService.CreateEntitiesAsync(UnitOfMeasurement);
await _entityService.ResetEntitiesAsync();
@@ -78,6 +85,7 @@ public class NordPoolInit
catch (Exception ex)
{
_logger.LogError(ex, "Error initializing NordPool prices");
throw;
}
}
@@ -153,6 +161,7 @@ public class NordPoolInit
private void SubscribeToFetchPricesButton()
{
var button = new Entity(_haContext, NordPoolConsts.FetchPricesButtonEntityId);
button.StateChanges()
.Subscribe(_ =>
{
@@ -208,7 +217,7 @@ public class NordPoolInit
UnitOfMeasurement = UnitOfMeasurement,
DayQuartersIndex = _priceService.DayQuartersIndex,
LastApiUpdateDate = _priceService.LastUpdatedDate,
UsingCachedData = !_priceService.ShouldFetchNewPrices(todayCet),
UsingCachedData = !_priceService.ShouldFetchTodaysPrices(todayCet),
TodayNordPoolPrice = _priceService.TodayNordPoolPrice,
TomorrowNordPoolPrice = _priceService.TomorrowNordPoolPrice,
CheapestIntervals = CheapestIntervals,
+54 -22
View File
@@ -1,3 +1,5 @@
#region
using System.Text.Json;
using AutoMapper;
using Microsoft.Extensions.Logging;
@@ -6,6 +8,8 @@ using NordPool.Models.Dtos;
using NordPoolManager.Interface;
using NordPoolManager.Models.Consts;
#endregion
namespace NordPoolManager;
/// <summary>
@@ -13,8 +17,10 @@ namespace NordPoolManager;
/// <c>IHaContext</c>/generated entity dependencies so it can be a singleton.
/// Fetching prices from Home Assistant lives in <see cref="NordPoolInit" />.
/// </summary>
public class NordPoolPriceService(IMapper mapper, ILogger<NordPoolPriceService> logger) : INordPoolPriceService
public class NordPoolPriceService(IMapper mapper, ILogger<NordPoolPriceService> logger, TimeProvider timeProvider) : INordPoolPriceService
{
private static readonly TimeZoneInfo CetTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
public NordPoolPrice? TodayNordPoolPrice { get; internal set; }
public NordPoolPrice? TomorrowNordPoolPrice { get; internal set; }
public double CurrentPrice { get; internal set; }
@@ -24,11 +30,10 @@ public class NordPoolPriceService(IMapper mapper, ILogger<NordPoolPriceService>
public async Task FetchPricesAsync(Func<DateOnly, Task<NordPoolPrice>> fetchPricesForDate)
{
var cetTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
var nowCet = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, cetTimeZone);
var dateNow = DateOnly.FromDateTime(nowCet);
var nowCet = TimeZoneInfo.ConvertTime(timeProvider.GetUtcNow(), CetTimeZone);
var dateNow = DateOnly.FromDateTime(nowCet.DateTime);
if ((TodayNordPoolPrice?.Prices == null || TodayNordPoolPrice.Prices.Count == 0) && ShouldFetchNewPrices(dateNow))
if ((TodayNordPoolPrice?.Prices == null || TodayNordPoolPrice.Prices.Count == 0) && ShouldFetchTodaysPrices(dateNow))
{
if (logger.IsEnabled(LogLevel.Information))
{
@@ -38,7 +43,7 @@ public class NordPoolPriceService(IMapper mapper, ILogger<NordPoolPriceService>
TodayNordPoolPrice = await FetchPricesForDateWithRetryAsync(dateNow, fetchPricesForDate);
}
if ((TomorrowNordPoolPrice?.Prices == null || TomorrowNordPoolPrice.Prices.Count == 0) && ShouldFetchNewPrices(dateNow.AddDays(1)))
if ((TomorrowNordPoolPrice?.Prices == null || TomorrowNordPoolPrice.Prices.Count == 0) && ShouldFetchTomorrowPrice())
{
if (logger.IsEnabled(LogLevel.Information))
{
@@ -48,20 +53,23 @@ public class NordPoolPriceService(IMapper mapper, ILogger<NordPoolPriceService>
TomorrowNordPoolPrice = await FetchPricesForDateWithRetryAsync(dateNow.AddDays(1), fetchPricesForDate);
}
LastUpdatedDate = DateTime.UtcNow;
LastUpdatedDate = timeProvider.GetUtcNow().UtcDateTime;
LastFetchedDate = dateNow;
}
public void UpdateCurrentPrice()
{
var index = GetTimeQuarterIndex(DateTime.UtcNow);
var index = GetTimeQuarterIndex(timeProvider.GetUtcNow().UtcDateTime);
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("Current time quarter index: {Index}, Total prices available: {Count}", index, TodayNordPoolPrice?.Prices?.Count ?? 0);
}
if (DayQuartersIndex == index) return;
if (DayQuartersIndex == index)
{
return;
}
if (TodayNordPoolPrice?.Prices != null && TodayNordPoolPrice.Prices.Count > index)
{
@@ -89,19 +97,19 @@ public class NordPoolPriceService(IMapper mapper, ILogger<NordPoolPriceService>
return CurrentPrice;
}
public bool ShouldFetchNewPrices(DateOnly date)
public bool ShouldFetchTodaysPrices(DateOnly todayDate)
{
if (!LastFetchedDate.HasValue) return true;
if (!LastFetchedDate.HasValue)
{
return true;
}
if (LastFetchedDate.Value < date) return true;
if (LastFetchedDate.Value < todayDate)
{
return true;
}
if (TodayNordPoolPrice?.Prices == null || TodayNordPoolPrice.Prices.Count == 0) return true;
if (TomorrowNordPoolPrice?.Prices is { Count: > 0 }) return false;
var currentHour = DateTime.Now.Hour;
return currentHour >= 13;
return TodayNordPoolPrice?.Prices is not { Count: > 0 };
}
public void RollOverPrices(DateOnly date)
@@ -125,7 +133,10 @@ public class NordPoolPriceService(IMapper mapper, ILogger<NordPoolPriceService>
internal NordPoolPrice ParseNordPoolResult(JsonElement? element)
{
if (!element.HasValue) return new NordPoolPrice();
if (!element.HasValue)
{
return new NordPoolPrice();
}
var priceResult = element.Value.Deserialize<NordPoolPriceResultDto>();
@@ -141,11 +152,17 @@ public class NordPoolPriceService(IMapper mapper, ILogger<NordPoolPriceService>
Prices = new List<NordPoolDayPrice>()
};
if (todayNordPoolPrice.Prices is null) return recalculatedPrice;
if (todayNordPoolPrice.Prices is null)
{
return recalculatedPrice;
}
foreach (var price in todayNordPoolPrice.Prices)
{
if (price.Price is null) continue;
if (price.Price is null)
{
continue;
}
recalculatedPrice.Prices.Add(new NordPoolDayPrice
{
@@ -179,6 +196,7 @@ public class NordPoolPriceService(IMapper mapper, ILogger<NordPoolPriceService>
private async Task<NordPoolPrice> FetchPricesForDateWithRetryAsync(DateOnly date, Func<DateOnly, Task<NordPoolPrice>> fetchPricesForDate)
{
for (var attempt = 1; attempt <= NordPoolConsts.MaxFetchRetryAttempts; attempt++)
{
try
{
return await fetchPricesForDate(date);
@@ -193,11 +211,25 @@ public class NordPoolPriceService(IMapper mapper, ILogger<NordPoolPriceService>
catch (Exception ex)
{
logger.LogError(ex, "Failed to fetch prices for {Date} on attempt {Attempt} with unexpected error", date, attempt);
break;
}
}
logger.LogWarning("All {MaxAttempts} attempts to fetch prices for {Date} exhausted; returning empty prices", NordPoolConsts.MaxFetchRetryAttempts, date);
return new NordPoolPrice();
}
private bool ShouldFetchTomorrowPrice()
{
var cetNow = TimeZoneInfo.ConvertTime(timeProvider.GetUtcNow(), CetTimeZone).DateTime;
if (cetNow.Hour < NordPoolConsts.TomorrowPricesPublishHour)
{
return false;
}
return TomorrowNordPoolPrice?.Prices is not { Count: > 0 };
}
}
@@ -1,7 +1,11 @@
#region
using Microsoft.Extensions.DependencyInjection;
using NetDaemon.AppModel;
using NordPoolManager.Interface;
#endregion
namespace NordPoolManager;
public static class NordPoolServiceRegistration
@@ -10,6 +14,7 @@ public static class NordPoolServiceRegistration
{
services
.AddNetDaemonApp<NordPoolInit>()
// Singleton is safe: NordPoolPriceService holds no IHaContext/generated
// entity dependency. The HA price fetch call lives in NordPoolInit.
.AddSingleton<INordPoolPriceService, NordPoolPriceService>()
+12 -4
View File
@@ -1,14 +1,22 @@
#region
using System.Text.Json.Serialization;
#endregion
namespace NordPool.Models;
public class CheapestIntervalResult
{
[JsonPropertyName("start")] public DateTime Start { get; init; }
[JsonPropertyName("start")]
public DateTime Start { get; init; }
[JsonPropertyName("end")] public DateTime End { get; init; }
[JsonPropertyName("end")]
public DateTime End { get; init; }
[JsonPropertyName("price")] public double Price { get; init; }
[JsonPropertyName("price")]
public double Price { get; init; }
[JsonPropertyName("rank")] public int Rank { get; init; }
[JsonPropertyName("rank")]
public int Rank { get; init; }
}
+10 -2
View File
@@ -1,6 +1,10 @@
#region
using System.Text.Json;
using System.Text.Json.Serialization;
#endregion
namespace NordPool.Models;
[JsonConverter(typeof(CompactNordPoolDayPriceConverter))]
@@ -40,10 +44,14 @@ public readonly struct CompactNordPoolDayPrice
internal sealed class CompactNordPoolDayPriceConverter : JsonConverter<CompactNordPoolDayPrice>
{
public override CompactNordPoolDayPrice Read(ref Utf8JsonReader reader, Type typeToConvert,
public override CompactNordPoolDayPrice Read(ref Utf8JsonReader reader,
Type typeToConvert,
JsonSerializerOptions options)
{
if (reader.TokenType != JsonTokenType.StartArray) throw new JsonException("Expected start of array.");
if (reader.TokenType != JsonTokenType.StartArray)
{
throw new JsonException("Expected start of array.");
}
if (!reader.Read() || reader.TokenType != JsonTokenType.Number)
{
+11 -4
View File
@@ -1,12 +1,19 @@
using System.Text.Json.Serialization;
#region
using System.Text.Json.Serialization;
#endregion
namespace NordPool.Models.Dtos;
public class NordPoolDayPriceDto
{
[JsonPropertyName("start")] public string? Start { get; init; }
[JsonPropertyName("start")]
public string? Start { get; init; }
[JsonPropertyName("end")] public string? End { get; init; }
[JsonPropertyName("end")]
public string? End { get; init; }
[JsonPropertyName("price")] public double? Price { get; init; }
[JsonPropertyName("price")]
public double? Price { get; init; }
}
@@ -1,8 +1,13 @@
using System.Text.Json.Serialization;
#region
using System.Text.Json.Serialization;
#endregion
namespace NordPool.Models.Dtos;
public class NordPoolPriceResultDto
{
[JsonPropertyName("LT")] public List<NordPoolDayPriceDto>? Prices { get; init; }
[JsonPropertyName("LT")]
public List<NordPoolDayPriceDto>? Prices { get; init; }
}
+6
View File
@@ -39,6 +39,12 @@ public static class NordPoolConsts
/// </summary>
public const string FetchPricesButtonEntityId = "button.nordpool_fetch_prices";
/// <summary>
/// NordPool publishes tomorrow's prices in the afternoon; before this CET hour the API
/// has nothing to return for tomorrow, so polling it is pointless.
/// </summary>
public const int TomorrowPricesPublishHour = 13;
/// <summary>
/// Maximum number of retry attempts when fetching prices from the NordPool API.
/// </summary>
+6 -1
View File
@@ -1,6 +1,10 @@
#region
using HomeAssistant.Models;
using NetDaemon.Extensions.MqttEntityManager;
#endregion
namespace NordPool.Models;
public class NordPoolEntity : EntityCreateModel
@@ -39,7 +43,8 @@ public class NordPoolEntity : EntityCreateModel
/// </summary>
public static object CreateAdditionalConfig(object extraProperties)
{
var extras = extraProperties.GetType().GetProperties()
var extras = extraProperties.GetType()
.GetProperties()
.ToDictionary(p => p.Name, p => p.GetValue(extraProperties));
extras["device"] = DeviceBlock;
@@ -1,6 +1,10 @@
#region
using FluentAssertions;
using PowerMonitorManager.Models;
#endregion
namespace PowerMonitor.Manager.Tests;
public class CostAccumulatorTests
@@ -29,7 +33,10 @@ public class CostAccumulatorTests
var tasks = Enumerable.Range(0, threadCount)
.Select(_ => Task.Run(() =>
{
for (var i = 0; i < callsPerThread; i++) sut.AddCost(incrementPerCall, now.AddSeconds(1));
for (var i = 0; i < callsPerThread; i++)
{
sut.AddCost(incrementPerCall, now.AddSeconds(1));
}
}))
.ToArray();
@@ -47,11 +54,7 @@ public class CostAccumulatorTests
{
return window switch
{
CostWindow.FifteenMinutes => snapshot.Cost15Min,
CostWindow.Hour => snapshot.Cost1Hour,
CostWindow.Day => snapshot.CostDaily,
CostWindow.Month => snapshot.CostMonthly,
_ => throw new ArgumentOutOfRangeException(nameof(window))
CostWindow.FifteenMinutes => snapshot.Cost15Min, CostWindow.Hour => snapshot.Cost1Hour, CostWindow.Day => snapshot.CostDaily, CostWindow.Month => snapshot.CostMonthly, _ => throw new ArgumentOutOfRangeException(nameof(window))
};
}
@@ -116,12 +119,16 @@ public class CostAccumulatorTests
// Arrange
var now = PowerMonitorTestData.FixedNow;
var sut = new CostAccumulator(now);
var increments = PowerMonitorTestData.CreatePowerSampleSeries(50)
.Select(watts => watts / 100_000.0)
.ToArray();
// Act
foreach (var increment in increments) sut.AddCost(increment, now.AddSeconds(1));
foreach (var increment in increments)
{
sut.AddCost(increment, now.AddSeconds(1));
}
// Assert
var expected = increments.Sum();
@@ -191,7 +198,7 @@ public class CostAccumulatorTests
#region Window rollovers
public static TheoryData<string, CostWindow, DateTime, DateTime, double, double> WindowRolloverCases => new()
public static TheoryData<string, CostWindow, DateTime, DateTime, double, double> WindowRolloverCases => new TheoryData<string, CostWindow, DateTime, DateTime, double, double>
{
{
"15 minute slot ends", CostWindow.FifteenMinutes, new DateTime(2026, 3, 17, 10, 14, 0),
@@ -323,7 +330,7 @@ public class CostAccumulatorTests
#region Window boundary detection (static methods)
public static TheoryData<string, DateTime, DateTime, bool> FifteenMinuteBoundaryCases => new()
public static TheoryData<string, DateTime, DateTime, bool> FifteenMinuteBoundaryCases => new TheoryData<string, DateTime, DateTime, bool>
{
{ "same slot, first second", new DateTime(2026, 3, 17, 10, 0, 0), new DateTime(2026, 3, 17, 10, 0, 0), false },
{ "same slot, last second", new DateTime(2026, 3, 17, 10, 0, 0), new DateTime(2026, 3, 17, 10, 14, 59), false },
@@ -344,7 +351,7 @@ public class CostAccumulatorTests
CostAccumulator.IsNew15MinWindow(now, lastReset).Should().Be(expected, $"scenario: {scenario}");
}
public static TheoryData<string, DateTime, DateTime, bool> HourBoundaryCases => new()
public static TheoryData<string, DateTime, DateTime, bool> HourBoundaryCases => new TheoryData<string, DateTime, DateTime, bool>
{
{ "same hour, same minute", new DateTime(2026, 3, 17, 10, 0, 0), new DateTime(2026, 3, 17, 10, 0, 0), false },
{
@@ -366,7 +373,7 @@ public class CostAccumulatorTests
CostAccumulator.IsNewHourWindow(now, lastReset).Should().Be(expected, $"scenario: {scenario}");
}
public static TheoryData<string, DateTime, DateTime, bool> DayBoundaryCases => new()
public static TheoryData<string, DateTime, DateTime, bool> DayBoundaryCases => new TheoryData<string, DateTime, DateTime, bool>
{
{ "same timestamp", new DateTime(2026, 3, 17, 0, 0, 0), new DateTime(2026, 3, 17, 0, 0, 0), false },
{ "same day, last second", new DateTime(2026, 3, 17, 0, 0, 0), new DateTime(2026, 3, 17, 23, 59, 59), false },
@@ -385,7 +392,7 @@ public class CostAccumulatorTests
CostAccumulator.IsNewDayWindow(now, lastReset).Should().Be(expected, $"scenario: {scenario}");
}
public static TheoryData<string, DateTime, DateTime, bool> MonthBoundaryCases => new()
public static TheoryData<string, DateTime, DateTime, bool> MonthBoundaryCases => new TheoryData<string, DateTime, DateTime, bool>
{
{ "same month, first day", new DateTime(2026, 3, 1, 0, 0, 0), new DateTime(2026, 3, 1, 0, 0, 0), false },
{ "same month, last day", new DateTime(2026, 3, 1, 0, 0, 0), new DateTime(2026, 3, 31, 23, 59, 59), false },
@@ -1,8 +1,12 @@
#region
using FluentAssertions;
using Microsoft.Extensions.Options;
using PowerMonitorManager;
using PowerMonitorManager.Models;
#endregion
namespace PowerMonitor.Manager.Tests;
public class OtherPowerCalculationServiceTests
@@ -13,12 +17,13 @@ public class OtherPowerCalculationServiceTests
{
SmoothingWindowSize = smoothingWindowSize
});
return new OtherPowerCalculationService(options);
}
#region Basic calculation
public static TheoryData<string, double, double[], double, string> CalculationCases => new()
public static TheoryData<string, double, double[], double, string> CalculationCases => new TheoryData<string, double, double[], double, string>
{
{ "two devices", 341.97, [8.55, 36.93], 296.49, "ok" },
{ "no devices", 341.97, [], 341.97, "ok" },
@@ -42,6 +47,7 @@ public class OtherPowerCalculationServiceTests
{
// Arrange
var sut = CreateSut(1);
var devices = deviceWatts
.Select((watts, index) => (entityId: $"sensor.device{index}_power", watts))
.ToDictionary(entry => entry.entityId, entry => entry.watts);
@@ -166,7 +172,11 @@ public class OtherPowerCalculationServiceTests
// Act
PowerCalculationResult? result = null;
for (var i = 0; i < 200; i++) result = sut.Calculate(200.0, new Dictionary<string, double>());
for (var i = 0; i < 200; i++)
{
result = sut.Calculate(200.0, new Dictionary<string, double>());
}
// Assert
result!.SmoothedOtherPowerWatts.Should().BeApproximately(200.0, 0.1);
@@ -1,7 +1,11 @@
#region
using FluentAssertions;
using PowerMonitorManager;
using PowerMonitorManager.Models.Consts;
#endregion
namespace PowerMonitor.Manager.Tests;
public class PowerCostCalculationServiceTests
@@ -12,7 +16,7 @@ public class PowerCostCalculationServiceTests
Other
}
private readonly PowerCostCalculationService _sut = new();
private readonly PowerCostCalculationService _sut = new PowerCostCalculationService();
#region Snapshot defaults
@@ -52,7 +56,9 @@ public class PowerCostCalculationServiceTests
.Select(_ => Task.Run(() =>
{
for (var i = 0; i < callsPerThread; i++)
{
_sut.RecordCosts(result, PowerMonitorTestData.DefaultPricePerKwh, 15, now.AddSeconds(1));
}
}))
.ToArray();
@@ -73,14 +79,12 @@ public class PowerCostCalculationServiceTests
double pricePerKwh,
int pollIntervalSeconds = PowerMonitorConsts.DefaultPollIntervalSeconds)
{
return powerWatts / PowerMonitorConsts.WattsPerKilowatt
* pricePerKwh
* ((double)pollIntervalSeconds / PowerMonitorConsts.SecondsPerHour);
return powerWatts / PowerMonitorConsts.WattsPerKilowatt * pricePerKwh * ((double)pollIntervalSeconds / PowerMonitorConsts.SecondsPerHour);
}
#region CalculateCostIncrement
public static TheoryData<string, double, double, int, double> CostIncrementCases => new()
public static TheoryData<string, double, double, int, double> CostIncrementCases => new TheoryData<string, double, double, int, double>
{
{ "default polling interval", 341.97, 0.1791, 15, 0.0002551951125 },
{ "one kilowatt for one hour", 1000.0, 1.0, PowerMonitorConsts.SecondsPerHour, 1.0 },
@@ -127,9 +131,12 @@ public class PowerCostCalculationServiceTests
// Assert
costs.Should().BeInAscendingOrder("every generated sample is larger than the previous one");
for (var i = 0; i < samples.Count; i++)
{
costs[i].Should().BeApproximately(samples[i] / 1_000.0 * unitCost, 1e-15);
}
}
#endregion
@@ -149,6 +156,7 @@ public class PowerCostCalculationServiceTests
// Assert
var expectedTotal =
ExpectedCost(PowerMonitorTestData.DefaultTotalWatts, PowerMonitorTestData.DefaultPricePerKwh);
var expectedOther = ExpectedCost(PowerMonitorTestData.DefaultSmoothedOtherWatts,
PowerMonitorTestData.DefaultPricePerKwh);
@@ -218,6 +226,7 @@ public class PowerCostCalculationServiceTests
{
// Arrange
var now = PowerMonitorTestData.FixedNow;
var firstResult = PowerMonitorTestData.CreateCalculation(
deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.sonoff_100215c534_power", 101.0)));
@@ -243,6 +252,7 @@ public class PowerCostCalculationServiceTests
// Act
var singleDeviceResult = PowerMonitorTestData.CreateCalculation(
deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.sonoff_100215c534_power", 101.0)));
_sut.RecordCosts(singleDeviceResult, PowerMonitorTestData.DefaultPricePerKwh, 15, now.AddSeconds(15));
// Assert
@@ -270,6 +280,7 @@ public class PowerCostCalculationServiceTests
{
// Arrange
var now = PowerMonitorTestData.FixedNow;
var result = PowerMonitorTestData.CreateCalculation(
0,
0,
@@ -290,6 +301,7 @@ public class PowerCostCalculationServiceTests
{
// Arrange - a sensor glitch must flow through the pure cost math unchanged.
var now = PowerMonitorTestData.FixedNow;
var result = PowerMonitorTestData.CreateCalculation(
deviceReadings: PowerMonitorTestData.CreateReadings(("sensor.glitch_power", -500.0)));
@@ -382,6 +394,7 @@ public class PowerCostCalculationServiceTests
const double pricePerKwh = 0.2;
var timestamps = PowerMonitorTestData.CreateSampleTimestamps(PowerMonitorTestData.FixedDayStart, 96);
var wattSamples = PowerMonitorTestData.CreatePowerSampleSeries();
var expectedPerSlot = timestamps
.Select((_, index) => ExpectedCost(wattSamples[index], pricePerKwh))
.ToArray();
@@ -393,6 +406,7 @@ public class PowerCostCalculationServiceTests
wattSamples[slot],
wattSamples[slot] / 2,
new Dictionary<string, double>());
_sut.RecordCosts(result, pricePerKwh, PowerMonitorConsts.DefaultPollIntervalSeconds, timestamps[slot]);
}
@@ -416,10 +430,12 @@ public class PowerCostCalculationServiceTests
foreach (var (start, pricePerKwh) in windows)
{
var watts = 500.0 + start.Hour * 125.0;
var result = PowerMonitorTestData.CreateCalculation(
watts,
watts / 4,
PowerMonitorTestData.CreateReadings(("sensor.tv_power", watts / 2)));
_sut.RecordCosts(result, pricePerKwh, pollIntervalSeconds, start);
expectedPerHour.Add(ExpectedCost(watts, pricePerKwh, pollIntervalSeconds));
}
@@ -476,8 +492,10 @@ public class PowerCostCalculationServiceTests
// Assert
_sut.LastKnownPrice.Should().Be(PowerMonitorTestData.DefaultPricePerKwh);
_sut.PriceSource.Should().Be("live");
var expected =
2 * ExpectedCost(PowerMonitorTestData.DefaultTotalWatts, PowerMonitorTestData.DefaultPricePerKwh);
_sut.GetTotalCostSnapshot().CostDaily.Should().BeApproximately(expected, 1e-12);
}
@@ -1,3 +1,5 @@
#region
using System.Globalization;
using FluentAssertions;
using Microsoft.Extensions.Logging;
@@ -9,6 +11,8 @@ using NetDaemon.HassModel.Entities;
using PowerMonitorManager;
using PowerMonitorManager.Models;
#endregion
namespace PowerMonitor.Manager.Tests;
public class PowerLimitEnforcementServiceTests
@@ -16,10 +20,10 @@ public class PowerLimitEnforcementServiceTests
private const string BoilerSwitch = PowerMonitorTestData.BoilerSwitchEntityId;
private const string AutoManagement = PowerMonitorTestData.AutoManagementEntityId;
private readonly Mock<IHaContext> _haContextMock = new();
private readonly Mock<ILogger<PowerLimitEnforcementService>> _loggerMock = new();
private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
private readonly Mock<ILogger<PowerLimitEnforcementService>> _loggerMock = new Mock<ILogger<PowerLimitEnforcementService>>();
private readonly PowerMonitorOptions _options = PowerMonitorTestData.CreateLimitEnforcementOptions();
private readonly FakeTimeProvider _timeProvider = new(PowerMonitorTestData.FixedUtcNow);
private readonly FakeTimeProvider _timeProvider = new FakeTimeProvider(PowerMonitorTestData.FixedUtcNow);
private PowerLimitEnforcementService CreateSut()
{
@@ -131,11 +135,13 @@ public class PowerLimitEnforcementServiceTests
{
// Arrange
var calls = new List<(string domain, string service, string? entityId)>();
_haContextMock
.Setup(x => x.CallService(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ServiceTarget>(),
It.IsAny<object?>()))
.Callback<string, string, ServiceTarget?, object?>((d, s, t, _) =>
calls.Add((d, s, t?.EntityIds?.FirstOrDefault())));
var sut = CreateSut();
// Act
@@ -144,8 +150,12 @@ public class PowerLimitEnforcementServiceTests
// Assert
var turnOffCalls = calls.Where(c => c.service == "turn_off").ToList();
turnOffCalls.Should().HaveCount(2);
turnOffCalls[0].entityId.Should().Be(BoilerSwitch,
turnOffCalls[0]
.entityId.Should()
.Be(BoilerSwitch,
"boiler switch must be turned off before auto_management (race-safe order)");
turnOffCalls[1].entityId.Should().Be(AutoManagement);
}
@@ -156,10 +166,12 @@ public class PowerLimitEnforcementServiceTests
_options.EnforceSwitchOffEntityIds = ["switch.high_load_a", "switch.high_load_b"];
_options.PauseAndRestoreEntityIds = ["switch.monitor_c"];
var calls = new List<string?>();
_haContextMock
.Setup(x => x.CallService(It.IsAny<string>(), "turn_off", It.IsAny<ServiceTarget>(), It.IsAny<object?>()))
.Callback<string, string, ServiceTarget?, object?>((_, _, target, _) =>
calls.Add(target?.EntityIds?.FirstOrDefault()));
var sut = CreateSut();
// Act
@@ -184,6 +196,7 @@ public class PowerLimitEnforcementServiceTests
// Assert
sut.IsLimitActive.Should().BeTrue();
VerifyNotificationCreated(1);
_haContextMock.Verify(
x => x.CallService("switch", It.IsAny<string>(), It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
Times.Never);
@@ -193,7 +206,7 @@ public class PowerLimitEnforcementServiceTests
#region Recovery
public static TheoryData<string, int, double, bool, int> RecoveryCases => new()
public static TheoryData<string, int, double, bool, int> RecoveryCases => new TheoryData<string, int, double, bool, int>
{
{ "not yet due", 300, 3000.0, true, 0 },
{ "one second before due", 599, 3000.0, true, 0 },
@@ -379,9 +392,11 @@ public class PowerLimitEnforcementServiceTests
// Assert
sut.IsLimitActive.Should().BeTrue();
_haContextMock.Verify(
x => x.CallService(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
Times.Exactly(3));
VerifyTurnOff(BoilerSwitch, 1);
VerifyTurnOff(AutoManagement, 1);
VerifyNotificationCreated(1);
@@ -1,3 +1,5 @@
#region
using FluentAssertions;
using HomeAssistant.Entities.Interfaces;
using Microsoft.Extensions.Logging;
@@ -5,6 +7,8 @@ using Moq;
using PowerMonitor.Models;
using PowerMonitorManager;
#endregion
namespace PowerMonitor.Manager.Tests;
public class PowerMonitorEntityServiceTests
@@ -27,18 +31,22 @@ public class PowerMonitorEntityServiceTests
"button.powermonitor_trigger_limit_breach"
];
private readonly Mock<IEntityManager> _entityManagerMock = new();
private readonly Mock<IEntityManager> _entityManagerMock = new Mock<IEntityManager>();
private readonly PowerMonitorEntityService _sut;
public PowerMonitorEntityServiceTests()
{
var loggerMock = new Mock<ILogger<PowerMonitorEntityService>>();
_entityManagerMock.Setup(em => em.CreateEntityAsync(It.IsAny<PowerMonitorEntity>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
.Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.RemoveEntity(It.IsAny<string>())).Returns(Task.CompletedTask);
_sut = new PowerMonitorEntityService(_entityManagerMock.Object, loggerMock.Object);
}
@@ -56,6 +64,7 @@ public class PowerMonitorEntityServiceTests
// Assert
result.Should().HaveCount(4);
string[] expectedEntityIds =
[
$"sensor.powermonitor_{deviceName}_cost_15min",
@@ -63,6 +72,7 @@ public class PowerMonitorEntityServiceTests
$"sensor.powermonitor_{deviceName}_cost_daily",
$"sensor.powermonitor_{deviceName}_cost_monthly"
];
result.Should().BeEquivalentTo(expectedEntityIds);
}
@@ -152,7 +162,7 @@ public class PowerMonitorEntityServiceTests
#region GetPowerDeviceEntitiesNames
public static TheoryData<string, string, string, string> DeviceEntityCases => new()
public static TheoryData<string, string, string, string> DeviceEntityCases => new TheoryData<string, string, string, string>
{
{ "sonoff device", "sensor.sonoff_1002230e32_power", "Sonoff Power", "sonoff_1002230e32" },
{ "simple device", "sensor.tv_power", "TV Power", "tv" },
@@ -176,6 +186,7 @@ public class PowerMonitorEntityServiceTests
// Assert
result.Should().HaveCount(4, $"scenario: {scenario}");
string[] expectedEntityIds =
[
$"sensor.powermonitor_{expectedDeviceName}_cost_15min",
@@ -183,8 +194,10 @@ public class PowerMonitorEntityServiceTests
$"sensor.powermonitor_{expectedDeviceName}_cost_daily",
$"sensor.powermonitor_{expectedDeviceName}_cost_monthly"
];
result.Select(entity => entity.EntityId).Should().BeEquivalentTo(expectedEntityIds, $"scenario: {scenario}");
result.Should().OnlyContain(entity => entity.Domain == "sensor", $"scenario: {scenario}");
string[] expectedNames =
[
$"{friendlyName} cost (15 min)",
@@ -192,6 +205,7 @@ public class PowerMonitorEntityServiceTests
$"{friendlyName} cost (daily)",
$"{friendlyName} cost (monthly)"
];
result.Select(entity => entity.Name).Should().BeEquivalentTo(expectedNames, $"scenario: {scenario}");
}
@@ -405,10 +419,12 @@ public class PowerMonitorEntityServiceTests
// Assert
foreach (var window in new[] { "15min", "1h", "daily", "monthly" })
{
_entityManagerMock.Verify(
em => em.SetEntityState($"sensor.powermonitor_{deviceName}_cost_{window}", It.IsAny<string>()),
Times.Once);
}
}
[Theory]
[InlineData(false, "off")]
@@ -455,8 +471,10 @@ public class PowerMonitorEntityServiceTests
// Assert
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_total_power", "342.0"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_other_power", "128.5"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_total_cost_daily", "1.0000"),
Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_tv_cost_15min", "0.0005"), Times.Once);
}
@@ -467,6 +485,7 @@ public class PowerMonitorEntityServiceTests
_entityManagerMock
.Setup(em => em.SetEntityState("sensor.powermonitor_total_power", It.IsAny<string>()))
.ThrowsAsync(new InvalidOperationException("Failed"));
var context = PowerMonitorTestData.CreateUpdateContext();
// Act
@@ -475,6 +494,7 @@ public class PowerMonitorEntityServiceTests
// Assert
await act.Should().NotThrowAsync();
_entityManagerMock.Verify(em => em.SetEntityState("sensor.powermonitor_status", "ok"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.powermonitor_total_power", It.IsAny<object>()),
Times.Once);
}
@@ -1,7 +1,11 @@
#region
using FluentAssertions;
using PowerMonitorManager.Models;
using PowerMonitorManager.Models.Consts;
#endregion
namespace PowerMonitor.Manager.Tests;
public class PowerMonitorOptionsTests
@@ -1,9 +1,13 @@
#region
using System.Text.Json;
using PowerMonitor.Models;
using PowerMonitorManager;
using PowerMonitorManager.Models;
using PowerMonitorManager.Models.Consts;
#endregion
namespace PowerMonitor.Manager.Tests;
/// <summary>
@@ -21,11 +25,11 @@ internal static class PowerMonitorTestData
public const string AutoManagementEntityId = "switch.boilermonitor_auto_management";
public const string MainMeterEntityId = "sensor.sonoff_100267d63f_power";
public static readonly DateTime FixedNow = new(2026, 3, 17, 10, 0, 0);
public static readonly DateTime FixedNow = new DateTime(2026, 3, 17, 10, 0, 0);
public static readonly DateTime FixedDayStart = new(2026, 3, 17, 0, 0, 0);
public static readonly DateTime FixedDayStart = new DateTime(2026, 3, 17, 0, 0, 0);
public static readonly DateTimeOffset FixedUtcNow = new(2026, 3, 17, 8, 0, 0, TimeSpan.Zero);
public static readonly DateTimeOffset FixedUtcNow = new DateTimeOffset(2026, 3, 17, 8, 0, 0, TimeSpan.Zero);
/// <summary>
/// Two-device reading set used by the cost calculation tests.
@@ -107,6 +111,7 @@ internal static class PowerMonitorTestData
string priceSource = "live")
{
var readings = deviceReadings ?? CreateDeviceReadings();
var deviceCosts = readings
.Select((reading, index) => (reading.Key, Snapshot: CreateCostSnapshot(
0.0005 * (index + 1),
@@ -143,6 +148,7 @@ internal static class PowerMonitorTestData
};
configure?.Invoke(options);
return options;
}
@@ -182,11 +188,20 @@ internal static class PowerMonitorTestData
{
var attributes = new Dictionary<string, object?>();
if (deviceClass is not null) attributes["device_class"] = deviceClass;
if (deviceClass is not null)
{
attributes["device_class"] = deviceClass;
}
if (unitOfMeasurement is not null) attributes["unit_of_measurement"] = unitOfMeasurement;
if (unitOfMeasurement is not null)
{
attributes["unit_of_measurement"] = unitOfMeasurement;
}
if (friendlyName is not null) attributes["friendly_name"] = friendlyName;
if (friendlyName is not null)
{
attributes["friendly_name"] = friendlyName;
}
return JsonSerializer.SerializeToElement(attributes);
}
@@ -1,3 +1,5 @@
#region
using FluentAssertions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
@@ -6,12 +8,14 @@ using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
using PowerMonitorManager;
#endregion
namespace PowerMonitor.Manager.Tests;
public class PowerSensorDiscoveryServiceTests
{
private readonly Mock<IHaContext> _haContextMock = new();
private readonly Mock<ILogger<PowerSensorDiscoveryService>> _loggerMock = new();
private readonly Mock<IHaContext> _haContextMock = new Mock<IHaContext>();
private readonly Mock<ILogger<PowerSensorDiscoveryService>> _loggerMock = new Mock<ILogger<PowerSensorDiscoveryService>>();
private PowerSensorDiscoveryService CreateSut(
string mainMeterEntityId = PowerMonitorTestData.MainMeterEntityId,
@@ -22,6 +26,7 @@ public class PowerSensorDiscoveryServiceTests
option.MainMeterEntityId = mainMeterEntityId;
option.ExcludedSensorPatterns = excludedPatterns ?? ["sensor.nordpool_*", "sensor.powermonitor_*"];
}));
return new PowerSensorDiscoveryService(_haContextMock.Object, options, _loggerMock.Object);
}
@@ -33,6 +38,7 @@ public class PowerSensorDiscoveryServiceTests
};
_haContextMock.Setup(h => h.GetState(entityId)).Returns(entityState);
return new Entity(_haContextMock.Object, entityId);
}
@@ -243,9 +249,10 @@ public class PowerSensorDiscoveryServiceTests
{
// Arrange - HA can report entities whose state has not been published yet.
var tv = SetupEntity("sensor.tv_power", "power", "W", "TV Power");
_haContextMock
.Setup(h => h.GetAllEntities())
.Returns(new List<Entity> { new(_haContextMock.Object, "sensor.ghost_power"), tv });
.Returns(new List<Entity> { new Entity(_haContextMock.Object, "sensor.ghost_power"), tv });
var sut = CreateSut();
@@ -1,5 +1,9 @@
#region
using PowerMonitorManager.Models;
#endregion
namespace PowerMonitorManager.Interface;
public interface IOtherPowerCalculationService
@@ -1,5 +1,9 @@
#region
using PowerMonitorManager.Models;
#endregion
namespace PowerMonitorManager.Interface;
public interface IPowerCostCalculationService
@@ -1,6 +1,10 @@
#region
using PowerMonitor.Models;
using PowerMonitorManager.Models;
#endregion
namespace PowerMonitorManager.Interface;
public interface IPowerMonitorEntityService
@@ -1,5 +1,9 @@
#region
using PowerMonitor.Models;
#endregion
namespace PowerMonitorManager.Interface;
public interface IPowerSensorDiscoveryService
@@ -2,7 +2,7 @@ namespace PowerMonitorManager.Models;
public sealed class CostAccumulator(DateTime now)
{
private readonly Lock _lock = new();
private readonly Lock _lock = new Lock();
private double _cost15Min;
private double _cost1Hour;
@@ -77,7 +77,10 @@ public sealed class CostAccumulator(DateTime now)
_lastDailyReset = now;
}
if (!IsNewMonthWindow(now, _lastMonthlyReset)) return;
if (!IsNewMonthWindow(now, _lastMonthlyReset))
{
return;
}
_previousMonthly = _costMonthly;
_costMonthly = 0;
@@ -88,6 +91,7 @@ public sealed class CostAccumulator(DateTime now)
{
var currentSlot = now.Minute / 15;
var lastSlot = lastReset.Minute / 15;
return now.Date != lastReset.Date || now.Hour != lastReset.Hour || currentSlot != lastSlot;
}
@@ -1,5 +1,9 @@
#region
using PowerMonitorManager.Models.Consts;
#endregion
namespace PowerMonitorManager.Models;
public sealed class PowerMonitorOptions
@@ -1,13 +1,17 @@
#region
using Microsoft.Extensions.Options;
using PowerMonitorManager.Interface;
using PowerMonitorManager.Models;
#endregion
namespace PowerMonitorManager;
public sealed class OtherPowerCalculationService : IOtherPowerCalculationService
{
private readonly double _alpha;
private readonly Lock _lock = new();
private readonly Lock _lock = new Lock();
private double? _previousSmoothed;
public OtherPowerCalculationService(IOptions<PowerMonitorOptions> options)
@@ -29,11 +33,13 @@ public sealed class OtherPowerCalculationService : IOtherPowerCalculationService
}
double smoothed;
lock (_lock)
{
smoothed = _previousSmoothed.HasValue
? _alpha * rawOther + (1 - _alpha) * _previousSmoothed.Value
: rawOther;
_previousSmoothed = smoothed;
}
@@ -1,15 +1,19 @@
#region
using System.Collections.Concurrent;
using PowerMonitorManager.Interface;
using PowerMonitorManager.Models;
using PowerMonitorManager.Models.Consts;
#endregion
namespace PowerMonitorManager;
public sealed class PowerCostCalculationService : IPowerCostCalculationService
{
private readonly Lock _accumulatorLock = new();
private readonly ConcurrentDictionary<string, CostAccumulator> _deviceAccumulators = new();
private readonly Lock _priceLock = new();
private readonly Lock _accumulatorLock = new Lock();
private readonly ConcurrentDictionary<string, CostAccumulator> _deviceAccumulators = new ConcurrentDictionary<string, CostAccumulator>();
private readonly Lock _priceLock = new Lock();
private double _lastKnownPrice;
private CostAccumulator? _otherAccumulator;
@@ -38,7 +42,9 @@ public sealed class PowerCostCalculationService : IPowerCostCalculationService
}
}
public void RecordCosts(PowerCalculationResult calculation, double nordPoolPrice, int pollIntervalSeconds,
public void RecordCosts(PowerCalculationResult calculation,
double nordPoolPrice,
int pollIntervalSeconds,
DateTime now)
{
lock (_priceLock)
@@ -57,6 +63,7 @@ public sealed class PowerCostCalculationService : IPowerCostCalculationService
var otherCost =
CalculateCostIncrement(calculation.SmoothedOtherPowerWatts, effectivePrice, pollIntervalSeconds);
GetOrCreateOtherAccumulator(now).AddCost(otherCost, now);
foreach (var (entityId, powerWatts) in calculation.DevicePowerReadings)
@@ -109,6 +116,7 @@ public sealed class PowerCostCalculationService : IPowerCostCalculationService
internal static double CalculateCostIncrement(double powerWatts, double pricePerKwh, int pollIntervalSeconds)
{
var powerKw = powerWatts / PowerMonitorConsts.WattsPerKilowatt;
return powerKw * pricePerKwh * ((double)pollIntervalSeconds / PowerMonitorConsts.SecondsPerHour);
}
@@ -1,3 +1,5 @@
#region
using System.Globalization;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
@@ -7,6 +9,8 @@ using PowerMonitorManager.Interface;
using PowerMonitorManager.Models;
using PowerMonitorManager.Models.Consts;
#endregion
namespace PowerMonitorManager;
public sealed class PowerLimitEnforcementService(
@@ -25,13 +29,17 @@ public sealed class PowerLimitEnforcementService(
public void EnforceLimit(double currentPowerWatts)
{
if (!_options.EnforceLimitEnabled) return;
if (!_options.EnforceLimitEnabled)
{
return;
}
var now = timeProvider.GetUtcNow();
if (!IsLimitActive)
{
TryEnforce(currentPowerWatts, now);
return;
}
@@ -43,6 +51,7 @@ public sealed class PowerLimitEnforcementService(
if (IsLimitActive)
{
logger.LogInformation("Debug: trigger requested but limit already active");
return;
}
@@ -55,6 +64,7 @@ public sealed class PowerLimitEnforcementService(
if (!IsLimitActive)
{
logger.LogInformation("Debug: reset requested but limit not active");
return;
}
@@ -64,9 +74,15 @@ public sealed class PowerLimitEnforcementService(
private void ExecuteEnforce(double currentPowerWatts)
{
foreach (var entityId in _options.EnforceSwitchOffEntityIds) TurnOff(entityId);
foreach (var entityId in _options.EnforceSwitchOffEntityIds)
{
TurnOff(entityId);
}
foreach (var entityId in _options.PauseAndRestoreEntityIds) TurnOff(entityId);
foreach (var entityId in _options.PauseAndRestoreEntityIds)
{
TurnOff(entityId);
}
NotifyLimitEnforced(currentPowerWatts, _options.PowerLimitWatts);
@@ -78,7 +94,10 @@ public sealed class PowerLimitEnforcementService(
private void ExecuteRecover()
{
foreach (var entityId in _options.PauseAndRestoreEntityIds) TurnOn(entityId);
foreach (var entityId in _options.PauseAndRestoreEntityIds)
{
TurnOn(entityId);
}
DismissLimitNotification();
@@ -88,7 +107,10 @@ public sealed class PowerLimitEnforcementService(
private void TryEnforce(double currentPowerWatts, DateTimeOffset now)
{
if (currentPowerWatts <= _options.PowerLimitWatts) return;
if (currentPowerWatts <= _options.PowerLimitWatts)
{
return;
}
if (now - _lastActionTime < TimeSpan.FromSeconds(_options.LimitCooldownSeconds))
{
@@ -112,12 +134,16 @@ public sealed class PowerLimitEnforcementService(
{
var elapsed = now - _enforcedAt;
if (elapsed < TimeSpan.FromSeconds(_options.RecoverySeconds)) return;
if (elapsed < TimeSpan.FromSeconds(_options.RecoverySeconds))
{
return;
}
if (currentPowerWatts >= _options.PowerLimitWatts)
{
logger.LogWarning("Recovery time reached but power still {Power:F0} W >= {Limit:F0} W, staying enforced",
currentPowerWatts, _options.PowerLimitWatts);
_enforcedAt = now;
return;
@@ -130,7 +156,10 @@ public sealed class PowerLimitEnforcementService(
currentPowerWatts, _options.PowerLimitWatts, (int)elapsed.TotalSeconds);
}
foreach (var entityId in _options.PauseAndRestoreEntityIds) TurnOn(entityId);
foreach (var entityId in _options.PauseAndRestoreEntityIds)
{
TurnOn(entityId);
}
DismissLimitNotification();
@@ -1,3 +1,5 @@
#region
using System.Globalization;
using HomeAssistant.Entities.Interfaces;
using Microsoft.Extensions.Logging;
@@ -6,6 +8,8 @@ using PowerMonitorManager.Interface;
using PowerMonitorManager.Models;
using PowerMonitorManager.Models.Consts;
#endregion
namespace PowerMonitorManager;
public sealed class PowerMonitorEntityService(
@@ -44,6 +48,7 @@ public sealed class PowerMonitorEntityService(
cancellationToken.ThrowIfCancellationRequested();
var entities = GetSystemEntitiesList();
var tasks = entities.Select(async entity =>
{
try
@@ -70,6 +75,7 @@ public sealed class PowerMonitorEntityService(
cancellationToken.ThrowIfCancellationRequested();
var entities = sensors.SelectMany(GetPowerDeviceEntitiesNames).ToList();
var tasks = entities.Select(async entity =>
{
try
@@ -123,12 +129,16 @@ public sealed class PowerMonitorEntityService(
foreach (var (entityId, costSnapshot) in context.DeviceCosts)
{
var deviceName = PowerSensorDiscoveryService.ExtractDeviceName(entityId);
tasks.Add(UpdateCostEntityAsync($"sensor.powermonitor_{deviceName}_cost_15min", costSnapshot.Cost15Min,
costSnapshot, $"{deviceName} cost (15 min)", timestamp));
tasks.Add(UpdateCostEntityAsync($"sensor.powermonitor_{deviceName}_cost_1h", costSnapshot.Cost1Hour,
costSnapshot, $"{deviceName} cost (1h)", timestamp));
tasks.Add(UpdateCostEntityAsync($"sensor.powermonitor_{deviceName}_cost_daily", costSnapshot.CostDaily,
costSnapshot, $"{deviceName} cost (daily)", timestamp));
tasks.Add(UpdateCostEntityAsync($"sensor.powermonitor_{deviceName}_cost_monthly", costSnapshot.CostMonthly,
costSnapshot, $"{deviceName} cost (monthly)", timestamp));
}
@@ -175,6 +185,7 @@ public sealed class PowerMonitorEntityService(
catch (Exception ex)
{
logger.LogError(ex, "Error cleaning up PowerMonitor entities");
throw;
}
}
@@ -192,7 +203,10 @@ public sealed class PowerMonitorEntityService(
{
await entityManager.RemoveEntity(id).ConfigureAwait(false);
if (logger.IsEnabled(LogLevel.Debug)) logger.LogDebug("Entity removed: {EntityId}", id);
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("Entity removed: {EntityId}", id);
}
}
catch (Exception ex)
{
@@ -203,12 +217,11 @@ public sealed class PowerMonitorEntityService(
await Task.WhenAll(tasks).ConfigureAwait(false);
}
internal static ICollection<PowerMonitorEntity> GetSystemEntitiesList()
{
return new List<PowerMonitorEntity>
{
new("sensor", "powermonitor_total_power", "PowerMonitor total power")
new PowerMonitorEntity("sensor", "powermonitor_total_power", "PowerMonitor total power")
{
AdditionalConfig = new
{
@@ -221,7 +234,7 @@ public sealed class PowerMonitorEntityService(
CreateCostEntity("powermonitor_total_cost_1h", "PowerMonitor total cost (1h)"),
CreateCostEntity("powermonitor_total_cost_daily", "PowerMonitor total cost (daily)"),
CreateCostEntity("powermonitor_total_cost_monthly", "PowerMonitor total cost (monthly)"),
new("sensor", "powermonitor_other_power", "PowerMonitor other power")
new PowerMonitorEntity("sensor", "powermonitor_other_power", "PowerMonitor other power")
{
AdditionalConfig = new
{
@@ -234,13 +247,13 @@ public sealed class PowerMonitorEntityService(
CreateCostEntity("powermonitor_other_cost_1h", "PowerMonitor other cost (1h)"),
CreateCostEntity("powermonitor_other_cost_daily", "PowerMonitor other cost (daily)"),
CreateCostEntity("powermonitor_other_cost_monthly", "PowerMonitor other cost (monthly)"),
new("binary_sensor", "powermonitor_anomaly", "PowerMonitor anomaly"),
new("sensor", "powermonitor_status", "PowerMonitor status"),
new("button", "powermonitor_rediscover_sensors", "Rediscover power sensors")
new PowerMonitorEntity("binary_sensor", "powermonitor_anomaly", "PowerMonitor anomaly"),
new PowerMonitorEntity("sensor", "powermonitor_status", "PowerMonitor status"),
new PowerMonitorEntity("button", "powermonitor_rediscover_sensors", "Rediscover power sensors")
{
AdditionalConfig = new { icon = "mdi:refresh" }
},
new("button", "powermonitor_trigger_limit_breach", "Trigger power limit breach (debug)")
new PowerMonitorEntity("button", "powermonitor_trigger_limit_breach", "Trigger power limit breach (debug)")
{
AdditionalConfig = new { icon = "mdi:flash-alert" }
}
@@ -263,6 +276,7 @@ public sealed class PowerMonitorEntityService(
internal static IEnumerable<PowerMonitorEntity> GetPowerDeviceEntitiesNames(PowerSensorInfo sensor)
{
var deviceName = PowerSensorDiscoveryService.ExtractDeviceName(sensor.EntityId);
return
[
CreateCostEntity($"powermonitor_{deviceName}_cost_15min", $"{sensor.FriendlyName} cost (15 min)"),
@@ -287,6 +301,7 @@ public sealed class PowerMonitorEntityService(
{
var value = context.Calculation.TotalPowerWatts.ToString("F1", CultureInfo.InvariantCulture);
await SetEntityStateSafe(TotalPowerEntityId, value).ConfigureAwait(false);
await SetEntityAttributesSafe(TotalPowerEntityId, new
{
unit_of_measurement = PowerMonitorConsts.WattUnit,
@@ -294,13 +309,15 @@ public sealed class PowerMonitorEntityService(
state_class = PowerMonitorConsts.MeasurementStateClass,
friendly_name = "PowerMonitor total power",
last_updated = timestamp
}).ConfigureAwait(false);
})
.ConfigureAwait(false);
}
private async Task UpdateOtherPowerAsync(PowerUpdateContext context, string timestamp)
{
var value = context.Calculation.SmoothedOtherPowerWatts.ToString("F1", CultureInfo.InvariantCulture);
await SetEntityStateSafe(OtherPowerEntityId, value).ConfigureAwait(false);
await SetEntityAttributesSafe(OtherPowerEntityId, new
{
unit_of_measurement = PowerMonitorConsts.WattUnit,
@@ -311,14 +328,19 @@ public sealed class PowerMonitorEntityService(
smoothed_power = context.Calculation.SmoothedOtherPowerWatts,
data_quality = context.Calculation.DataQuality,
last_updated = timestamp
}).ConfigureAwait(false);
})
.ConfigureAwait(false);
}
private async Task UpdateCostEntityAsync(string entityId, double costValue, CostSnapshot snapshot,
string friendlyName, string timestamp)
private async Task UpdateCostEntityAsync(string entityId,
double costValue,
CostSnapshot snapshot,
string friendlyName,
string timestamp)
{
var value = costValue.ToString("F4", CultureInfo.InvariantCulture);
await SetEntityStateSafe(entityId, value).ConfigureAwait(false);
await SetEntityAttributesSafe(entityId, new
{
unit_of_measurement = PowerMonitorConsts.EurUnit,
@@ -327,13 +349,15 @@ public sealed class PowerMonitorEntityService(
friendly_name = friendlyName,
partial_window = snapshot.PartialWindow,
last_updated = timestamp
}).ConfigureAwait(false);
})
.ConfigureAwait(false);
}
private async Task UpdateAnomalyAsync(PowerUpdateContext context, string timestamp)
{
var state = context.IsAnomaly ? "on" : "off";
await SetEntityStateSafe(AnomalyEntityId, state).ConfigureAwait(false);
await SetEntityAttributesSafe(AnomalyEntityId, new
{
friendly_name = "PowerMonitor anomaly",
@@ -341,12 +365,14 @@ public sealed class PowerMonitorEntityService(
threshold = context.AnomalyThresholdWatts,
duration_above = context.AnomalyDuration.TotalSeconds,
last_updated = timestamp
}).ConfigureAwait(false);
})
.ConfigureAwait(false);
}
private async Task UpdateStatusAsync(PowerUpdateContext context, string timestamp)
{
await SetEntityStateSafe(StatusEntityId, context.SystemStatus).ConfigureAwait(false);
await SetEntityAttributesSafe(StatusEntityId, new
{
friendly_name = "PowerMonitor status",
@@ -356,7 +382,8 @@ public sealed class PowerMonitorEntityService(
current_price = context.CurrentNordPoolPrice,
price_unit = context.PriceUnit,
last_updated = timestamp
}).ConfigureAwait(false);
})
.ConfigureAwait(false);
}
internal async Task SetEntityStateSafe(string entityId, string state)

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