Add manual MQTT recreation and NordPool price fetch buttons

This commit is contained in:
2026-07-08 16:56:32 +03:00
parent 2706a6b188
commit f176a1b8fc
11 changed files with 458 additions and 22 deletions
+2
View File
@@ -112,6 +112,8 @@ appsettings.*.local.json
# Home Assistant long-lived tokens / per-user override files # Home Assistant long-lived tokens / per-user override files
appsettings.development.json appsettings.development.json
appsettings.Production.json
appsettings.production.json
# Cursor MCP config (contains secrets) # Cursor MCP config (contains secrets)
.cursor/mcp.json .cursor/mcp.json
+159 -7
View File
@@ -1,10 +1,162 @@
## Learned User Preferences # AGENTS.md
- Default assistant tone: **caveman full** every new chat (see `.cursor/rules/caveman-always.mdc`). Opt out: say `stop caveman` / `normal mode`. Compact orientation for OpenCode sessions working in this repo. Read this
- When giving shell examples or running commands for this repo on Windows, chain with PowerShell using `;` instead of `&&`. before editing; it only records things that are easy to get wrong.
## Learned Workspace Facts ## User preferences
- The solution is .NET 10 and targets Home Assistant integration via NetDaemon. - Default assistant tone: **caveman full** every new chat
- NetDaemon registers `IHaContext` as scoped; any app service that injects it must be registered scoped or transient, not singleton, or app load fails with “Cannot resolve scoped service … from root provider.” (see `.cursor/rules/caveman-always.mdc`). Opt out: say `stop caveman` /
- Cursor agent transcripts for this workspace are stored under the long project folder `...-homeassistant-app-deamon-homeassistant-app-deamon-code-workspace\agent-transcripts\`; the shorter `...\homeassistant-app-deamon\agent-transcripts` path may be absent. `normal mode`.
- When giving shell examples or running commands for this repo on Windows,
chain with PowerShell using `;` instead of `&&`. On Linux/bash, `&&` is fine.
## Stack
- .NET 10 / C# 14 (`LangVersion=14.0`). `global.json` pins SDK `10.0.0` with
`rollForward=latestMajor` and `allowPrerelease=true`.
- NetDaemon v5 (NuGet `26.11.0`) apps run inside `HomeAssistant.Server`, the
only host / binary-deploy target. Solution file: `HomeAssistantSDK.sln`.
- Tests: xUnit + FluentAssertions + Moq. `Microsoft.Extensions.TimeProvider.Testing`
is used for time-based tests — prefer `FakeTimeProvider` over real time.
- AutoMapper 16 is used by `HomeAssistant.Server`. **A hardcoded license key
is committed in `HomeAssistant.Server/program.cs`** — do not move it to
settings, and do not log or echo it.
## Layout (non-obvious wiring)
- Each monitor follows a fixed 3-project pattern:
- `*.Models` — constants, enums, `*Options` (bound from
`appsettings.json` via `IOptions<>`).
- `*.Manager` — services + the `[NetDaemonApp]` entry `*Init.cs`.
- `*.Manager.Tests` — unit tests for the manager.
- Apps are **not** auto-discovered by the host. Each monitor exposes a
`Add<Name>Monitor(this IServiceCollection, IConfiguration)` extension in
`*ServiceRegistration.cs`; `program.cs` calls them explicitly and in a
specific order. Adding a new monitor means: create the 3 projects, add a
`*ServiceRegistration.cs`, reference the projects from
`HomeAssistant.Server`, and wire `Add<Name>` + `Configure<*Options>` in
`program.cs`.
- `*ServiceRegistration.cs` honors an `Enabled` flag in the options and
no-ops (skips `AddNetDaemonApp`) when disabled. `PowerMonitor` ships
disabled by default in `appsettings.json`.
- `HomeAssistant.Entities` holds the **generated** `HomeAssistantGenerated`
code (entity metadata sourced from
`HomeAssistant.Server/NetDaemonCodegen/{EntityMetaData,ServicesMetaData}.json`).
`program.cs` calls `AddHomeAssistantGenerated()`; the generated entities
are transient. Do not hand-edit generated files.
- `HomeAssistant.McpServer` is a separate stdio MCP server (ModelContextProtocol
NuGet) exposing HA tools. It is **not** referenced by the host; it runs
standalone via `dotnet run --project HomeAssistant.McpServer`. Cursor
wires it up in `.cursor/mcp.json` as the `homeassistant` MCP server.
- `HomeAssistant.HistoryReplay` is a Blazor debug web app that replays HA
history through monitor business logic with no side effects. See its own
README. Not deployed.
- `NordPool.Comminication` (sic — typo is intentional, keep it) is the
Nord Pool HTTP client project referenced by `NordPool.Manager`.
## Critical DI rule
NetDaemon registers `IHaContext` as **scoped**. Any service that injects
`IHaContext` (or `IMqttEntityManager`, `IEntities`, generated entity
collections) must be registered **scoped or transient**, never singleton,
or app load fails with:
`Cannot resolve scoped service … from root provider`.
Verified-livable registrations (do not regress these to singleton):
- `Boiler`: `IBoilerMonitorEntityService` transient,
`IBoilerConfigReader` scoped (in `program.cs`).
- `NordPool`: `INordPoolEntityService` transient, `INordPoolPriceService`
scoped, `INordPoolBoilerConfigProvider` scoped,
`ICheapestIntervalsFinder` singleton (no HA dep).
- `Power`: `IPowerMonitorEntityService` + `IPowerNotificationService`
transient, `IPowerSensorDiscoveryService` scoped. `IOtherPowerCalculationService`
+ `IPowerCostCalculationService` are singleton (pure calc, no HA dep).
- `Shower`: `IExhaustFanControlService` scoped,
`IShowerMonitorEntityService` transient, `IShowerDetectionService` +
`IHumidityRateCalculator` singleton (no HA dep).
- `Light`: `IPresenceService` + `ILightControlService` scoped.
- `Battery`: `IBatterySensorDiscoveryService` +
`IBatteryNotificationService` scoped.
- `Leak`: `ILeakNotificationService` scoped.
- `IEntityManager` is transient in `program.cs`.
Singletons are only safe for services that take **no** scoped dependency
(pure calculators, trackers with no `IHaContext`). When unsure, register
scoped.
## Live validation after monitor edits
`.cursor/rules/live-validation.mdc` (globs: all `*.Manager`/`*.Models` of
Boiler, Light, NordPool, Power, Shower, plus `HomeAssistant.McpServer`)
requires, after editing monitor runtime code:
1. `dotnet build` the affected project.
2. `RunSmokeTest` MCP tool from the `homeassistant` MCP server.
3. `ValidateEntities` for the changed service's critical entities.
Domain → entity mapping is in the rule file. Skip when HA is offline (check
via `check_api`), when changes are tests/docs/non-runtime, or when the user
says to skip. On failure, report the failing entities + states; do not
silently proceed. This rule is Cursor-specific but the intent applies to
OpenCode sessions too — if you have the `homeassistant` MCP server
available, follow the same flow.
## Commands
Build everything:
```
dotnet build HomeAssistantSDK.sln
```
Run all tests:
```
dotnet test HomeAssistantSDK.sln
```
Single test project / class / test:
```
dotnet test BoilerMonitor.Manager.Tests
dotnet test BoilerMonitor.Manager.Tests --filter "FullyQualifiedName~BoilerControlServiceTests"
dotnet test BoilerMonitor.Manager.Tests --filter "FullyQualifiedName~BoilerControlServiceTests.TurnsOnWhenCheap"
```
Run the host (needs HA reachable + token in `appsettings.Development.json`):
```
dotnet run --project HomeAssistant.Server
```
Run the MCP server standalone:
```
dotnet run --project HomeAssistant.McpServer
```
Run the history replay web app:
```
dotnet run --project HomeAssistant.HistoryReplay
```
Deploy the host: publish `HomeAssistant.Server` self-contained and copy the
output to `/config/netdaemon4` (the NetDaemon add-on folder). The csproj
prints the reminder after publish.
## Configuration & secrets
- Monitor options live under per-monitor sections in `HomeAssistant.Server/appsettings.json`
(e.g. `BoilerMonitor`, `ShowerMonitor`, `LightMonitor`, `BatteryMonitor`,
`LeakMonitor`, `PowerMonitor`, `NordPool`). Each `*Options` class has a
`SectionName` const used by both `program.cs` and `*ServiceRegistration`.
- `appsettings.Development.json` / `appsettings.*.local.json` are git-ignored
across the repo — put tokens and local overrides there. Nested keys can
be set via env vars using `__` as the separator.
- Never commit HA long-lived access tokens.
## Gotchas
- Monitor `*Options` are bound **twice**: once in `program.cs`
(`Configure<*Options>`) and once inside `*ServiceRegistration` (which reads
them again to check `Enabled` and to seed stateless singletons like
`HumidityRateCalculator`). Keep both in sync when changing option names.
- `HomeAssistant.Server` references every monitor's `*.Manager` and
`*.Models` projects directly; `HomeAssistant.HistoryReplay` references a
subset. Adding a monitor to the replay tool requires a new project
reference there too.
- The repository folder name is misspelled `homeassistant-app-deamon`
(should be `daemon`). This is intentional/legacy — do not "fix" it in
paths; scripts and `.cursor/mcp.json` use `${workspaceFolder}`.
- `NordPool.Comminication` is also misspelled — keep it; the project
reference depends on the exact name.
+2 -2
View File
@@ -533,8 +533,8 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
return new BoilerMonitorConfig return new BoilerMonitorConfig
{ {
BoilerPowerEntityId = string.IsNullOrWhiteSpace(powerEntityId) ? null : powerEntityId, BoilerPowerEntityId = string.IsNullOrWhiteSpace(powerEntityId) ? null : powerEntityId.Trim(),
BoilerSwitchEntityId = string.IsNullOrWhiteSpace(switchEntityId) ? null : switchEntityId, BoilerSwitchEntityId = string.IsNullOrWhiteSpace(switchEntityId) ? null : switchEntityId.Trim(),
PollIntervalSeconds = pollInterval, PollIntervalSeconds = pollInterval,
HeatingPowerThresholdWatts = heatingThreshold HeatingPowerThresholdWatts = heatingThreshold
}; };
@@ -27,6 +27,10 @@
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>Always</CopyToOutputDirectory>
<CopyToPublishDirectory>Never</CopyToPublishDirectory> <CopyToPublishDirectory>Never</CopyToPublishDirectory>
</None> </None>
<None Update="$(MSBuildProjectDir)appsettings.Production.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
<CopyToPublishDirectory>Always</CopyToPublishDirectory>
</None>
</ItemGroup> </ItemGroup>
<Target Name="AfterPublishMessage" AfterTargets="Publish"> <Target Name="AfterPublishMessage" AfterTargets="Publish">
<Message Text="Publish done! Copy all content in directory: $(PublishDir) to the `/config/netdaemon4' folder for add-on or your custom folder to deploy." Importance="high" /> <Message Text="Publish done! Copy all content in directory: $(PublishDir) to the `/config/netdaemon4' folder for add-on or your custom folder to deploy." Importance="high" />
+217
View File
@@ -0,0 +1,217 @@
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Threading.Tasks;
using BoilerMonitorManager.Interface;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NetDaemon.AppModel;
using NetDaemon.Extensions.MqttEntityManager;
using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
using NordPoolManager.Interface;
using PowerMonitorManager.Interface;
using ShowerMonitorManager.Interface;
namespace HomeAssistantServer;
[NetDaemonApp]
public sealed class MqttRecreateApp
{
private const string RecreateButtonEntityId = "button.appdaemon_recreate_all";
private const string NordPoolPriceEntityId = "sensor.nordpool_price";
private const string DefaultUnitOfMeasurement = "EUR/kWh";
private readonly IHaContext _haContext;
private readonly IMqttEntityManager _mqttEntityManager;
private readonly IServiceProvider _serviceProvider;
private readonly ILogger<MqttRecreateApp> _logger;
public MqttRecreateApp(
IHaContext haContext,
IMqttEntityManager mqttEntityManager,
IServiceProvider serviceProvider,
ILogger<MqttRecreateApp> logger)
{
_haContext = haContext;
_mqttEntityManager = mqttEntityManager;
_serviceProvider = serviceProvider;
_logger = logger;
_ = InitializeAsync();
}
private async Task InitializeAsync()
{
try
{
await Task.Delay(TimeSpan.FromSeconds(5));
await _mqttEntityManager.CreateAsync(
RecreateButtonEntityId,
new EntityCreationOptions
{
UniqueId = RecreateButtonEntityId,
Name = "Recreate all MQTT entities"
},
new
{
icon = "mdi:refresh",
device = new
{
identifiers = new[] { "appdaemon" },
name = "AppDaemon",
model = "AppDaemon",
manufacturer = "HomeAssistant App Daemon"
}
}).ConfigureAwait(false);
_logger.LogInformation("Recreate-all button created: {EntityId}", RecreateButtonEntityId);
var button = new Entity(_haContext, RecreateButtonEntityId);
button.StateChanges()
.Subscribe(_ =>
{
_logger.LogInformation("Recreate-all button pressed, recreating all MQTT entities");
Task.Run(HandleRecreateAsync);
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Error initializing MqttRecreateApp");
}
}
private async Task HandleRecreateAsync()
{
try
{
await RecreateNordPoolAsync();
await RecreateBoilerMonitorAsync();
await RecreateShowerMonitorAsync();
await RecreatePowerMonitorAsync();
_logger.LogInformation("All MQTT entities recreated successfully");
}
catch (Exception ex)
{
_logger.LogError(ex, "Error recreating MQTT entities");
}
}
private async Task RecreateNordPoolAsync()
{
var entityService = _serviceProvider.GetService<INordPoolEntityService>();
if (entityService is null)
{
_logger.LogDebug("NordPool entity service not registered (disabled), skipping");
return;
}
try
{
var unitOfMeasurement = ReadUnitOfMeasurement() ?? DefaultUnitOfMeasurement;
_logger.LogInformation("Recreating NordPool MQTT entities");
await entityService.CleanupEntitiesAsync().ConfigureAwait(false);
await Task.Delay(TimeSpan.FromSeconds(1));
await entityService.CreateEntitiesAsync(unitOfMeasurement).ConfigureAwait(false);
await entityService.ResetEntitiesAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error recreating NordPool entities");
}
}
private async Task RecreateBoilerMonitorAsync()
{
var entityService = _serviceProvider.GetService<IBoilerMonitorEntityService>();
if (entityService is null)
{
_logger.LogDebug("BoilerMonitor entity service not registered (disabled), skipping");
return;
}
try
{
_logger.LogInformation("Recreating BoilerMonitor MQTT entities");
await entityService.CleanupEntitiesAsync().ConfigureAwait(false);
await Task.Delay(TimeSpan.FromSeconds(1));
await entityService.CreateEntitiesAsync().ConfigureAwait(false);
await entityService.ResetEntitiesAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error recreating BoilerMonitor entities");
}
}
private async Task RecreateShowerMonitorAsync()
{
var entityService = _serviceProvider.GetService<IShowerMonitorEntityService>();
if (entityService is null)
{
_logger.LogDebug("ShowerMonitor entity service not registered (disabled), skipping");
return;
}
try
{
_logger.LogInformation("Recreating ShowerMonitor MQTT entities");
await entityService.CleanupEntitiesAsync().ConfigureAwait(false);
await Task.Delay(TimeSpan.FromSeconds(1));
await entityService.CreateEntitiesAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error recreating ShowerMonitor entities");
}
}
private async Task RecreatePowerMonitorAsync()
{
var entityService = _serviceProvider.GetService<IPowerMonitorEntityService>();
if (entityService is null)
{
_logger.LogDebug("PowerMonitor entity service not registered (disabled), skipping");
return;
}
try
{
_logger.LogInformation("Recreating PowerMonitor MQTT entities");
await entityService.CleanupEntitiesAsync().ConfigureAwait(false);
await Task.Delay(TimeSpan.FromSeconds(1));
await entityService.CreateSystemEntitiesAsync().ConfigureAwait(false);
await entityService.ResetEntitiesAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error recreating PowerMonitor entities");
}
}
private string? ReadUnitOfMeasurement()
{
try
{
var state = _haContext.GetState(NordPoolPriceEntityId);
if (state?.Attributes is IDictionary<string, object> attributes &&
attributes.TryGetValue("unit_of_measurement", out var value))
{
return value switch
{
string s => s,
JsonElement { ValueKind: JsonValueKind.String } je => je.GetString(),
_ => null
};
}
}
catch
{
}
return null;
}
}
@@ -31,13 +31,14 @@ public class NordPoolEntityServiceTests
// Assert // Assert
result.Should().NotBeNull(); result.Should().NotBeNull();
result.Should().HaveCount(6); result.Should().HaveCount(7);
result.Should().Contain(e => e.EntityId == "sensor.nordpool_last_update_time"); result.Should().Contain(e => e.EntityId == "sensor.nordpool_last_update_time");
result.Should().Contain(e => e.EntityId == "sensor.nordpool_current_price"); result.Should().Contain(e => e.EntityId == "sensor.nordpool_current_price");
result.Should().Contain(e => e.EntityId == "sensor.nordpool_today_prices"); result.Should().Contain(e => e.EntityId == "sensor.nordpool_today_prices");
result.Should().Contain(e => e.EntityId == "sensor.nordpool_tomorrow_prices"); result.Should().Contain(e => e.EntityId == "sensor.nordpool_tomorrow_prices");
result.Should().Contain(e => e.EntityId == "sensor.nordpool_today_tomorrow_prices"); result.Should().Contain(e => e.EntityId == "sensor.nordpool_today_tomorrow_prices");
result.Should().Contain(e => e.EntityId == "sensor.nordpool_cheapest_intervals"); result.Should().Contain(e => e.EntityId == "sensor.nordpool_cheapest_intervals");
result.Should().Contain(e => e.EntityId == "button.nordpool_fetch_prices");
} }
[Fact] [Fact]
@@ -74,7 +75,7 @@ public class NordPoolEntityServiceTests
var result = _sut.GetInitEntitiesList("EUR/kWh"); var result = _sut.GetInitEntitiesList("EUR/kWh");
// Assert // Assert
result.Should().OnlyContain(e => e.Domain == "sensor"); result.Should().OnlyContain(e => e.Domain == "sensor" || e.Domain == "button");
} }
[Fact] [Fact]
@@ -102,7 +103,7 @@ public class NordPoolEntityServiceTests
await _sut.CreateEntitiesAsync("EUR/kWh"); await _sut.CreateEntitiesAsync("EUR/kWh");
// Assert // Assert
_entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny<NordPoolEntity>()), Times.Exactly(6)); _entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny<NordPoolEntity>()), Times.Exactly(7));
} }
[Fact] [Fact]
@@ -126,7 +127,7 @@ public class NordPoolEntityServiceTests
await _sut.CreateEntitiesAsync("EUR/kWh"); await _sut.CreateEntitiesAsync("EUR/kWh");
// Assert // Assert
_entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny<NordPoolEntity>()), Times.Exactly(6)); _entityManagerMock.Verify(em => em.CreateEntityAsync(It.IsAny<NordPoolEntity>()), Times.Exactly(7));
} }
#endregion #endregion
@@ -150,6 +151,7 @@ public class NordPoolEntityServiceTests
_entityManagerMock.Verify(em => em.RemoveEntity("sensor.nordpool_tomorrow_prices"), Times.Once); _entityManagerMock.Verify(em => em.RemoveEntity("sensor.nordpool_tomorrow_prices"), Times.Once);
_entityManagerMock.Verify(em => em.RemoveEntity("sensor.nordpool_today_tomorrow_prices"), Times.Once); _entityManagerMock.Verify(em => em.RemoveEntity("sensor.nordpool_today_tomorrow_prices"), Times.Once);
_entityManagerMock.Verify(em => em.RemoveEntity("sensor.nordpool_cheapest_intervals"), Times.Once); _entityManagerMock.Verify(em => em.RemoveEntity("sensor.nordpool_cheapest_intervals"), Times.Once);
_entityManagerMock.Verify(em => em.RemoveEntity("button.nordpool_fetch_prices"), Times.Once);
} }
[Fact] [Fact]
@@ -255,6 +257,7 @@ public class NordPoolEntityServiceTests
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_tomorrow_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_today_tomorrow_prices", "unknown"), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityState("sensor.nordpool_cheapest_intervals", "0"), 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);
} }
[Fact] [Fact]
@@ -276,6 +279,7 @@ public class NordPoolEntityServiceTests
_entityManagerMock.Verify(em => em.SetEntityAttributes("sensor.nordpool_tomorrow_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_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("sensor.nordpool_cheapest_intervals", It.IsAny<object>()), Times.Once);
_entityManagerMock.Verify(em => em.SetEntityAttributes("button.nordpool_fetch_prices", It.IsAny<object>()), Times.Once);
} }
[Fact] [Fact]
@@ -299,7 +303,7 @@ public class NordPoolEntityServiceTests
[Fact] [Fact]
public async Task ResetEntitiesAsync_ShouldCallSetStateAndAttributesCorrectly() public async Task ResetEntitiesAsync_ShouldCallSetStateAndAttributesCorrectly()
{ {
// Arrange - 6 entities get state and attributes // Arrange - 7 entities get state and attributes
_entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>())) _entityManagerMock.Setup(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
_entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>())) _entityManagerMock.Setup(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()))
@@ -309,8 +313,8 @@ public class NordPoolEntityServiceTests
await _sut.ResetEntitiesAsync(); await _sut.ResetEntitiesAsync();
// Assert // Assert
_entityManagerMock.Verify(em => em.SetEntityState(It.IsAny<string>(), It.IsAny<string>()), Times.Exactly(6)); _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(6)); _entityManagerMock.Verify(em => em.SetEntityAttributes(It.IsAny<string>(), It.IsAny<object>()), Times.Exactly(7));
} }
#endregion #endregion
@@ -67,6 +67,7 @@ public class NordPoolInitTests
return new NordPoolInit( return new NordPoolInit(
_entities, _entities,
_haContextMock.Object,
_loggerMock.Object, _loggerMock.Object,
_priceServiceMock.Object, _priceServiceMock.Object,
_entityServiceMock.Object, _entityServiceMock.Object,
+4 -3
View File
@@ -20,9 +20,10 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="AutoMapper" Version="16.1.1" /> <PackageReference Include="AutoMapper" Version="16.1.1" />
<PackageReference Include="Microsoft.Extensions.Options" Version="10.0.5" /> <PackageReference Include="Microsoft.Extensions.Options" Version="10.0.5" />
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.11.0" /> <PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.11.0" />
<PackageReference Include="NetDaemon.HassModel" Version="26.11.0" />
</ItemGroup> </ItemGroup>
</Project> </Project>
+15 -3
View File
@@ -23,7 +23,8 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
TodayPricesEntityId, TodayPricesEntityId,
TomorrowPricesEntityId, TomorrowPricesEntityId,
TodayTomorrowPricesEntityId, TodayTomorrowPricesEntityId,
CheapestIntervalsEntityId CheapestIntervalsEntityId,
NordPoolConsts.FetchPricesButtonEntityId
]; ];
public async Task CreateEntitiesAsync(string? unitOfMeasurement, CancellationToken cancellationToken = default) public async Task CreateEntitiesAsync(string? unitOfMeasurement, CancellationToken cancellationToken = default)
@@ -57,7 +58,8 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
ResetTodayPricesAsync(), ResetTodayPricesAsync(),
ResetTomorrowPricesAsync(), ResetTomorrowPricesAsync(),
ResetTodayTomorrowPricesAsync(), ResetTodayTomorrowPricesAsync(),
ResetCheapestIntervalsAsync() ResetCheapestIntervalsAsync(),
ResetFetchPricesButtonAsync()
).ConfigureAwait(false); ).ConfigureAwait(false);
} }
@@ -138,6 +140,15 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
}).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);
}
public async Task UpdateEntitiesAsync(EntityUpdateContext ctx, CancellationToken cancellationToken = default) public async Task UpdateEntitiesAsync(EntityUpdateContext ctx, CancellationToken cancellationToken = default)
{ {
cancellationToken.ThrowIfCancellationRequested(); cancellationToken.ThrowIfCancellationRequested();
@@ -289,7 +300,8 @@ public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger<
new NordPoolEntity("sensor", "nordpool_today_prices", "NordPool today prices"), new NordPoolEntity("sensor", "nordpool_today_prices", "NordPool today prices"),
new NordPoolEntity("sensor", "nordpool_tomorrow_prices", "NordPool tomorrow prices"), new NordPoolEntity("sensor", "nordpool_tomorrow_prices", "NordPool tomorrow prices"),
new NordPoolEntity("sensor", "nordpool_today_tomorrow_prices", "NordPool today and tomorrow prices"), new NordPoolEntity("sensor", "nordpool_today_tomorrow_prices", "NordPool today and tomorrow prices"),
new NordPoolEntity("sensor", "nordpool_cheapest_intervals", "NordPool cheapest boiler intervals") new NordPoolEntity("sensor", "nordpool_cheapest_intervals", "NordPool cheapest boiler intervals"),
new NordPoolEntity("button", "nordpool_fetch_prices", "NordPool fetch prices")
]; ];
} }
+38
View File
@@ -6,6 +6,8 @@ using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using NetDaemon.AppModel; using NetDaemon.AppModel;
using NetDaemon.Extensions.Scheduler; using NetDaemon.Extensions.Scheduler;
using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
using NordPool.Models; using NordPool.Models;
using NordPoolManager.Interface; using NordPoolManager.Interface;
using NordPoolManager.Models; using NordPoolManager.Models;
@@ -16,6 +18,7 @@ namespace NordPoolManager;
public class NordPoolInit : INordPoolInit public class NordPoolInit : INordPoolInit
{ {
private readonly ILogger<NordPoolInit> _logger; private readonly ILogger<NordPoolInit> _logger;
private readonly IHaContext _haContext;
private readonly INordPoolPriceService _priceService; private readonly INordPoolPriceService _priceService;
private readonly INordPoolEntityService _entityService; private readonly INordPoolEntityService _entityService;
private readonly ICheapestIntervalsFinder _cheapestIntervalsFinder; private readonly ICheapestIntervalsFinder _cheapestIntervalsFinder;
@@ -29,6 +32,7 @@ public class NordPoolInit : INordPoolInit
public NordPoolInit( public NordPoolInit(
Entities entities, Entities entities,
IHaContext haContext,
ILogger<NordPoolInit> logger, ILogger<NordPoolInit> logger,
INordPoolPriceService priceService, INordPoolPriceService priceService,
INordPoolEntityService entityService, INordPoolEntityService entityService,
@@ -39,6 +43,7 @@ public class NordPoolInit : INordPoolInit
TimeProvider timeProvider) TimeProvider timeProvider)
{ {
_logger = logger; _logger = logger;
_haContext = haContext;
_priceService = priceService; _priceService = priceService;
_entityService = entityService; _entityService = entityService;
_scheduler = scheduler; _scheduler = scheduler;
@@ -58,6 +63,7 @@ public class NordPoolInit : INordPoolInit
try try
{ {
await InitializeAsync(); await InitializeAsync();
SubscribeToFetchPricesButton();
SchedulePeriodicUpdates(); SchedulePeriodicUpdates();
} }
catch (Exception ex) catch (Exception ex)
@@ -145,6 +151,38 @@ public class NordPoolInit : INordPoolInit
} }
} }
private void SubscribeToFetchPricesButton()
{
var button = new Entity(_haContext, NordPoolConsts.FetchPricesButtonEntityId);
button.StateChanges()
.Subscribe(_ =>
{
_logger.LogInformation("Fetch prices button pressed, triggering manual NordPool price update");
Task.Run(HandleFetchPricesAsync);
});
}
private async Task HandleFetchPricesAsync()
{
try
{
_logger.LogInformation("Manual fetch: forcing fresh NordPool price retrieval");
await _priceService.FetchPricesAsync();
_priceService.UpdateCurrentPrice();
var boilerConfig = _boilerConfigProvider.GetCurrentConfiguration();
UpdateCheapestIntervals(boilerConfig);
await UpdateEntitiesAsync(boilerConfig);
_logger.LogInformation("Manual fetch and update completed");
}
catch (Exception ex)
{
_logger.LogError(ex, "Error during manual NordPool price fetch");
}
}
public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default) public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default)
{ {
await _entityService.CleanupEntitiesAsync(cancellationToken); await _entityService.CleanupEntitiesAsync(cancellationToken);
+5
View File
@@ -34,6 +34,11 @@ public static class NordPoolConsts
/// </summary> /// </summary>
public const string CurrentPriceEntityId = "sensor.nordpool_current_price"; public const string CurrentPriceEntityId = "sensor.nordpool_current_price";
/// <summary>
/// Home Assistant entity id for the button that triggers a manual NordPool price fetch + entity update.
/// </summary>
public const string FetchPricesButtonEntityId = "button.nordpool_fetch_prices";
/// <summary> /// <summary>
/// Maximum number of retry attempts when fetching prices from the NordPool API. /// Maximum number of retry attempts when fetching prices from the NordPool API.
/// </summary> /// </summary>