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
This commit is contained in:
2026-12-01 13:46:19 +02:00
parent f919d6b25b
commit a9f329ffcd
14 changed files with 124 additions and 330 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 ## Stack
- .NET 10 / C# 14 (`LangVersion=14.0`, set per-csproj in the three - .NET 10 / C# 14 (`LangVersion=14.0`, set in `HomeAssistant.Server.csproj`;
executable projects — `HomeAssistant.Server`, `HomeAssistant.McpServer`, no `Directory.Build.props`). `global.json`
`HomeAssistant.HistoryReplay`; no `Directory.Build.props`). `global.json`
pins SDK `10.0.0` with `rollForward=latestMajor` and pins SDK `10.0.0` with `rollForward=latestMajor` and
`allowPrerelease=true`. `allowPrerelease=true`.
- NetDaemon v5 (NuGet `26.11.0`) apps run inside `HomeAssistant.Server`, the - NetDaemon v5 (NuGet `26.11.0`) apps run inside `HomeAssistant.Server`, the
@@ -69,12 +68,6 @@ before editing; it only records things that are easy to get wrong.
(`GlobalMappingProfile`, `NordPoolMappingProfile` + `DateTimeTypeConverter`) (`GlobalMappingProfile`, `NordPoolMappingProfile` + `DateTimeTypeConverter`)
referenced by `HomeAssistant.Server`; wired in `program.cs` via referenced by `HomeAssistant.Server`; wired in `program.cs` via
`config.AddProfile<…>()`. AutoMapper 16.1.1. `config.AddProfile<…>()`. AutoMapper 16.1.1.
- `HomeAssistant.McpServer` is a separate stdio MCP server
(ModelContextProtocol NuGet 1.2.0) exposing HA tools. It is **not**
referenced by the host; it runs standalone via
`dotnet run --project HomeAssistant.McpServer`. It is wired as the
`homeassistant` MCP server in both `.cursor/mcp.json` (git-ignored) and
the committed `opencode.json` at the repo root.
- `HomeAssistant.HistoryReplay` is a Blazor debug web app that replays HA - `HomeAssistant.HistoryReplay` is a Blazor debug web app that replays HA
history through monitor business logic with no side effects. It history through monitor business logic with no side effects. It
references a subset of monitors (Boiler, NordPool, Power, Shower, Light — 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 (pure calculators, trackers with no `IHaContext`). When unsure, register
scoped. 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 ## Commands
Build everything: Build everything:
@@ -152,10 +128,6 @@ Run the host (needs HA reachable + token in `appsettings.Development.json`):
``` ```
dotnet run --project HomeAssistant.Server dotnet run --project HomeAssistant.Server
``` ```
Run the MCP server standalone:
```
dotnet run --project HomeAssistant.McpServer
```
Run the history replay web app: Run the history replay web app:
``` ```
dotnet run --project HomeAssistant.HistoryReplay dotnet run --project HomeAssistant.HistoryReplay
@@ -187,8 +159,7 @@ prints the reminder after publish.
replay tool requires a new project reference there too. replay tool requires a new project reference there too.
- The repository folder name is misspelled `homeassistant-app-deamon` - The repository folder name is misspelled `homeassistant-app-deamon`
(should be `daemon`). This is intentional/legacy — do not "fix" it in (should be `daemon`). This is intentional/legacy — do not "fix" it in
paths; `opencode.json` and `.cursor/mcp.json` reference the workspace paths.
folder by macro.
- Stale untracked folders `NordPool.Comminication/` and - Stale untracked folders `NordPool.Comminication/` and
`HomeAssistant.Infrastructure/` may appear on disk containing only `HomeAssistant.Infrastructure/` may appear on disk containing only
`obj/` build cruft. They are **not** in the solution, not committed to `obj/` build cruft. They are **not** in the solution, not committed to
@@ -21,6 +21,7 @@
<PackageReference Include="AutoMapper" Version="17.0.0"/> <PackageReference Include="AutoMapper" Version="17.0.0"/>
<PackageReference Include="FluentAssertions" Version="8.11.0"/> <PackageReference Include="FluentAssertions" Version="8.11.0"/>
<PackageReference Include="Moq" Version="4.21.0"/> <PackageReference Include="Moq" Version="4.21.0"/>
<PackageReference Include="Microsoft.Extensions.TimeProvider.Testing" Version="11.0.1"/>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
+1 -1
View File
@@ -56,7 +56,7 @@ public class NordPoolInitTests
.Returns(Task.CompletedTask); .Returns(Task.CompletedTask);
_priceServiceMock.Setup(p => p.GetCurrentPrice()).Returns(0.0); _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.DayQuartersIndex).Returns(0);
_priceServiceMock.SetupGet(p => p.TodayNordPoolPrice).Returns((NordPoolPrice?)null); _priceServiceMock.SetupGet(p => p.TodayNordPoolPrice).Returns((NordPoolPrice?)null);
_priceServiceMock.SetupGet(p => p.TomorrowNordPoolPrice).Returns((NordPoolPrice?)null); _priceServiceMock.SetupGet(p => p.TomorrowNordPoolPrice).Returns((NordPoolPrice?)null);
@@ -5,6 +5,7 @@ using System.Text.Json;
using AutoMapper; using AutoMapper;
using FluentAssertions; using FluentAssertions;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Time.Testing;
using Moq; using Moq;
using NordPool.Models; using NordPool.Models;
using NordPool.Models.Dtos; using NordPool.Models.Dtos;
@@ -18,13 +19,16 @@ public class NordPoolPriceServiceTests
{ {
private readonly Mock<IMapper> _mapperMock; private readonly Mock<IMapper> _mapperMock;
private readonly NordPoolPriceService _sut; private readonly NordPoolPriceService _sut;
private readonly FakeTimeProvider _timeProvider;
public NordPoolPriceServiceTests() public NordPoolPriceServiceTests()
{ {
_mapperMock = new Mock<IMapper>(); _mapperMock = new Mock<IMapper>();
var loggerMock = new Mock<ILogger<NordPoolPriceService>>(); 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 #region GetTimeQuarterIndex
@@ -542,7 +546,7 @@ public class NordPoolPriceServiceTests
public void UpdateCurrentPrice_WhenSameQuarterIndex_ShouldReturnCachedPrice() public void UpdateCurrentPrice_WhenSameQuarterIndex_ShouldReturnCachedPrice()
{ {
// Arrange // Arrange
var expectedIndex = NordPoolPriceService.GetTimeQuarterIndex(DateTime.UtcNow); var expectedIndex = NordPoolPriceService.GetTimeQuarterIndex(_timeProvider.GetUtcNow().UtcDateTime);
var prices = new List<NordPoolDayPrice>(); var prices = new List<NordPoolDayPrice>();
@@ -616,7 +620,7 @@ public class NordPoolPriceServiceTests
public void UpdateCurrentPrice_WhenCurrentQuarterHasPrice_ShouldStoreThatPrice(double expectedPrice) public void UpdateCurrentPrice_WhenCurrentQuarterHasPrice_ShouldStoreThatPrice(double expectedPrice)
{ {
// Arrange — negative and zero spot prices are valid NordPool scenarios // 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( var prices = NordPoolTestData.CreateIntervals(
NordPoolConsts.MaxDailyIntervals, NordPoolConsts.MaxDailyIntervals,
@@ -638,7 +642,7 @@ public class NordPoolPriceServiceTests
public void UpdateCurrentPrice_WhenCurrentIndexIsOutsidePricesRange_ShouldKeepPreviousPriceButAdvanceIndex() public void UpdateCurrentPrice_WhenCurrentIndexIsOutsidePricesRange_ShouldKeepPreviousPriceButAdvanceIndex()
{ {
// Arrange — fewer prices than the current quarter index (e.g. partial day payload) // 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) var prices = Enumerable.Range(0, index)
.Select(i => new NordPoolDayPrice { Price = 10.0 + i }) .Select(i => new NordPoolDayPrice { Price = 10.0 + i })
@@ -660,7 +664,7 @@ public class NordPoolPriceServiceTests
public void UpdateCurrentPrice_WhenQuarterIndexUnchangedButPricesChanged_ShouldKeepCachedPrice() public void UpdateCurrentPrice_WhenQuarterIndexUnchangedButPricesChanged_ShouldKeepCachedPrice()
{ {
// Arrange // Arrange
var index = NordPoolPriceService.GetTimeQuarterIndex(DateTime.UtcNow); var index = NordPoolPriceService.GetTimeQuarterIndex(_timeProvider.GetUtcNow().UtcDateTime);
var prices = Enumerable.Range(0, NordPoolConsts.MaxDailyIntervals) var prices = Enumerable.Range(0, NordPoolConsts.MaxDailyIntervals)
.Select(_ => new NordPoolDayPrice { Price = 99.0 }) .Select(_ => new NordPoolDayPrice { Price = 99.0 })
@@ -682,7 +686,7 @@ public class NordPoolPriceServiceTests
public void UpdateCurrentPrice_WhenOnlyCurrentQuarterPriceIsNull_ShouldKeepPreviousPriceAndAdvanceIndex() public void UpdateCurrentPrice_WhenOnlyCurrentQuarterPriceIsNull_ShouldKeepPreviousPriceAndAdvanceIndex()
{ {
// Arrange // Arrange
var index = NordPoolPriceService.GetTimeQuarterIndex(DateTime.UtcNow); var index = NordPoolPriceService.GetTimeQuarterIndex(_timeProvider.GetUtcNow().UtcDateTime);
var prices = Enumerable.Range(0, NordPoolConsts.MaxDailyIntervals) var prices = Enumerable.Range(0, NordPoolConsts.MaxDailyIntervals)
.Select(i => new NordPoolDayPrice { Price = i == index ? null : 10.0 }) .Select(i => new NordPoolDayPrice { Price = i == index ? null : 10.0 })
@@ -705,9 +709,9 @@ public class NordPoolPriceServiceTests
#region FetchPricesAsync #region FetchPricesAsync
[Fact] [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>(); var requestedDates = new List<DateOnly>();
Task<NordPoolPrice> Fetch(DateOnly date) Task<NordPoolPrice> Fetch(DateOnly date)
@@ -721,26 +725,67 @@ public class NordPoolPriceServiceTests
await _sut.FetchPricesAsync(Fetch); await _sut.FetchPricesAsync(Fetch);
// Assert // Assert
requestedDates.Should().HaveCount(2); requestedDates.Should().ContainSingle().Which.Should().Be(new DateOnly(2026, 12, 1));
requestedDates[1].Should().Be(requestedDates[0].AddDays(1)); _sut.TodayNordPoolPrice!.Prices![0].Price.Should().Be(1.5);
_sut.TodayNordPoolPrice.Should().NotBeNull(); _sut.TomorrowNordPoolPrice.Should().BeNull();
_sut.TomorrowNordPoolPrice.Should().NotBeNull(); _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.TodayNordPoolPrice!.Prices![0].Price.Should().Be(1.5);
_sut.TomorrowNordPoolPrice!.Prices![0].Price.Should().Be(1.5); _sut.TomorrowNordPoolPrice!.Prices![0].Price.Should().Be(1.5);
_sut.LastFetchedDate.Should().Be(requestedDates[0]); _sut.LastFetchedDate.Should().Be(new DateOnly(2026, 12, 1));
_sut.LastUpdatedDate.Should().NotBeNull(); _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] [Fact]
public async Task FetchPricesAsync_WhenCachedPricesAlreadyPresent_ShouldNotCallDelegate() public async Task FetchPricesAsync_WhenCachedPricesAlreadyPresent_ShouldNotCallDelegate()
{ {
// Arrange // Arrange
var cetTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
var todayCet = DateOnly.FromDateTime(TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, cetTimeZone));
_sut.TodayNordPoolPrice = CreatePrices(1.0); _sut.TodayNordPoolPrice = CreatePrices(1.0);
_sut.TomorrowNordPoolPrice = CreatePrices(2.0); _sut.TomorrowNordPoolPrice = CreatePrices(2.0);
_sut.LastFetchedDate = todayCet; _sut.LastFetchedDate = new DateOnly(2026, 12, 1);
var delegateCalled = false; var delegateCalled = false;
// Act // Act
@@ -759,7 +804,7 @@ public class NordPoolPriceServiceTests
#endregion #endregion
#region ShouldFetchNewPrices #region ShouldFetchTodaysPrices
private static NordPoolPrice CreatePrices(params double?[] values) private static NordPoolPrice CreatePrices(params double?[] values)
{ {
@@ -770,38 +815,33 @@ public class NordPoolPriceServiceTests
} }
/// <summary> /// <summary>
/// Scenarios that do not depend on the time of day (tomorrow's prices are published after 13:00, /// xUnit cannot serialize <see cref="NordPoolPrice" /> rows, so the matrix runs inside a single test.
/// so the "tomorrow missing" cases are covered separately below). xUnit cannot serialize
/// <see cref="NordPoolPrice" /> rows, so the matrix runs inside a single test.
/// </summary> /// </summary>
[Fact] [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 (string Scenario, DateOnly? LastFetchedDate, NordPoolPrice? TodayPrice, bool Expected)[] cases =
Expected)[] cases =
[ [
("no fetch date yet", null, CreatePrices(12.50), CreatePrices(18.71), true), ("no fetch date yet", null, CreatePrices(12.50), true),
("last fetch was yesterday", today.AddDays(-1), CreatePrices(12.50), CreatePrices(18.71), 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), CreatePrices(18.71), false), ("last fetch date is in the future", today.AddDays(1), CreatePrices(12.50), false),
("today prices are null", today, new NordPoolPrice { Prices = null }, CreatePrices(18.71), true), ("today prices are null", today, new NordPoolPrice { Prices = null }, true),
("today prices are empty", today, new NordPoolPrice { Prices = [] }, CreatePrices(18.71), true), ("today prices are empty", today, new NordPoolPrice { Prices = [] }, true),
("today and tomorrow prices present", today, CreatePrices(12.50), CreatePrices(18.71), false), ("today prices present", today, CreatePrices(12.50), false),
("price values are null but entries exist", today, CreatePrices((double?)null), ("price values are null but entries exist", today, CreatePrices((double?)null), false),
CreatePrices((double?)null), false), ("all price payloads are null", today, null, true)
("all price payloads are null", today, null, null, true)
]; ];
foreach (var (scenario, lastFetchedDate, todayPrice, tomorrowPrice, expected) in cases) foreach (var (scenario, lastFetchedDate, todayPrice, expected) in cases)
{ {
// Arrange // Arrange
_sut.LastFetchedDate = lastFetchedDate; _sut.LastFetchedDate = lastFetchedDate;
_sut.TodayNordPoolPrice = todayPrice; _sut.TodayNordPoolPrice = todayPrice;
_sut.TomorrowNordPoolPrice = tomorrowPrice;
// Act // Act
var result = _sut.ShouldFetchNewPrices(DateOnly.FromDateTime(DateTime.Now)); var result = _sut.ShouldFetchTodaysPrices(today);
// Assert // Assert
result.Should().Be(expected, $"scenario: {scenario}"); result.Should().Be(expected, $"scenario: {scenario}");
@@ -809,45 +849,19 @@ public class NordPoolPriceServiceTests
} }
[Fact] [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 // Arrange — tomorrow's prices are irrelevant to today's fetch decision
var today = DateOnly.FromDateTime(DateTime.Now); var today = new DateOnly(2026, 12, 1);
_sut.LastFetchedDate = today; _sut.LastFetchedDate = today;
_sut.TodayNordPoolPrice = CreatePrices(12.50);
_sut.TodayNordPoolPrice = new NordPoolPrice
{
Prices = new List<NordPoolDayPrice> { new NordPoolDayPrice { Price = 12.50 } }
};
_sut.TomorrowNordPoolPrice = new NordPoolPrice { Prices = null }; _sut.TomorrowNordPoolPrice = new NordPoolPrice { Prices = null };
// Act // Act
var result = _sut.ShouldFetchNewPrices(today); var result = _sut.ShouldFetchTodaysPrices(today);
// Assert // Assert
result.Should().Be(DateTime.Now.Hour >= 13); result.Should().BeFalse();
}
[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 NordPoolDayPrice { 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);
} }
#endregion #endregion
@@ -20,6 +20,6 @@ public interface INordPoolPriceService
NordPoolPrice ParseAndAdjust(JsonElement? element); NordPoolPrice ParseAndAdjust(JsonElement? element);
void UpdateCurrentPrice(); void UpdateCurrentPrice();
double GetCurrentPrice(); double GetCurrentPrice();
bool ShouldFetchNewPrices(DateOnly dateOnly); bool ShouldFetchTodaysPrices(DateOnly dateOnly);
void RollOverPrices(DateOnly date); void RollOverPrices(DateOnly date);
} }
+1 -1
View File
@@ -217,7 +217,7 @@ public class NordPoolInit
UnitOfMeasurement = UnitOfMeasurement, UnitOfMeasurement = UnitOfMeasurement,
DayQuartersIndex = _priceService.DayQuartersIndex, DayQuartersIndex = _priceService.DayQuartersIndex,
LastApiUpdateDate = _priceService.LastUpdatedDate, LastApiUpdateDate = _priceService.LastUpdatedDate,
UsingCachedData = !_priceService.ShouldFetchNewPrices(todayCet), UsingCachedData = !_priceService.ShouldFetchTodaysPrices(todayCet),
TodayNordPoolPrice = _priceService.TodayNordPoolPrice, TodayNordPoolPrice = _priceService.TodayNordPoolPrice,
TomorrowNordPoolPrice = _priceService.TomorrowNordPoolPrice, TomorrowNordPoolPrice = _priceService.TomorrowNordPoolPrice,
CheapestIntervals = CheapestIntervals, CheapestIntervals = CheapestIntervals,
+25 -24
View File
@@ -17,8 +17,10 @@ namespace NordPoolManager;
/// <c>IHaContext</c>/generated entity dependencies so it can be a singleton. /// <c>IHaContext</c>/generated entity dependencies so it can be a singleton.
/// Fetching prices from Home Assistant lives in <see cref="NordPoolInit" />. /// Fetching prices from Home Assistant lives in <see cref="NordPoolInit" />.
/// </summary> /// </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? TodayNordPoolPrice { get; internal set; }
public NordPoolPrice? TomorrowNordPoolPrice { get; internal set; } public NordPoolPrice? TomorrowNordPoolPrice { get; internal set; }
public double CurrentPrice { get; internal set; } public double CurrentPrice { get; internal set; }
@@ -28,11 +30,10 @@ public class NordPoolPriceService(IMapper mapper, ILogger<NordPoolPriceService>
public async Task FetchPricesAsync(Func<DateOnly, Task<NordPoolPrice>> fetchPricesForDate) public async Task FetchPricesAsync(Func<DateOnly, Task<NordPoolPrice>> fetchPricesForDate)
{ {
var cetTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time"); var nowCet = TimeZoneInfo.ConvertTime(timeProvider.GetUtcNow(), CetTimeZone);
var nowCet = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, cetTimeZone); var dateNow = DateOnly.FromDateTime(nowCet.DateTime);
var dateNow = DateOnly.FromDateTime(nowCet);
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)) if (logger.IsEnabled(LogLevel.Information))
{ {
@@ -42,7 +43,7 @@ public class NordPoolPriceService(IMapper mapper, ILogger<NordPoolPriceService>
TodayNordPoolPrice = await FetchPricesForDateWithRetryAsync(dateNow, fetchPricesForDate); 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)) if (logger.IsEnabled(LogLevel.Information))
{ {
@@ -52,13 +53,13 @@ public class NordPoolPriceService(IMapper mapper, ILogger<NordPoolPriceService>
TomorrowNordPoolPrice = await FetchPricesForDateWithRetryAsync(dateNow.AddDays(1), fetchPricesForDate); TomorrowNordPoolPrice = await FetchPricesForDateWithRetryAsync(dateNow.AddDays(1), fetchPricesForDate);
} }
LastUpdatedDate = DateTime.UtcNow; LastUpdatedDate = timeProvider.GetUtcNow().UtcDateTime;
LastFetchedDate = dateNow; LastFetchedDate = dateNow;
} }
public void UpdateCurrentPrice() public void UpdateCurrentPrice()
{ {
var index = GetTimeQuarterIndex(DateTime.UtcNow); var index = GetTimeQuarterIndex(timeProvider.GetUtcNow().UtcDateTime);
if (logger.IsEnabled(LogLevel.Debug)) if (logger.IsEnabled(LogLevel.Debug))
{ {
@@ -96,31 +97,19 @@ public class NordPoolPriceService(IMapper mapper, ILogger<NordPoolPriceService>
return CurrentPrice; return CurrentPrice;
} }
public bool ShouldFetchNewPrices(DateOnly date) public bool ShouldFetchTodaysPrices(DateOnly todayDate)
{ {
if (!LastFetchedDate.HasValue) if (!LastFetchedDate.HasValue)
{ {
return true; return true;
} }
if (LastFetchedDate.Value < date) if (LastFetchedDate.Value < todayDate)
{ {
return true; return true;
} }
if (TodayNordPoolPrice?.Prices == null || TodayNordPoolPrice.Prices.Count == 0) return TodayNordPoolPrice?.Prices is not { Count: > 0 };
{
return true;
}
if (TomorrowNordPoolPrice?.Prices is { Count: > 0 })
{
return false;
}
var currentHour = DateTime.Now.Hour;
return currentHour >= 13;
} }
public void RollOverPrices(DateOnly date) public void RollOverPrices(DateOnly date)
@@ -231,4 +220,16 @@ public class NordPoolPriceService(IMapper mapper, ILogger<NordPoolPriceService>
return new NordPoolPrice(); 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 };
}
}
+6
View File
@@ -39,6 +39,12 @@ public static class NordPoolConsts
/// </summary> /// </summary>
public const string FetchPricesButtonEntityId = "button.nordpool_fetch_prices"; 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> /// <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>
-2
View File
@@ -24,8 +24,6 @@ The solution file is `HomeAssistantSDK.sln`. Projects are grouped by concern:
| `HomeAssistant.Server` | NetDaemon host. Binary-deploy target that loads all apps. | | `HomeAssistant.Server` | NetDaemon host. Binary-deploy target that loads all apps. |
| `HomeAssistant.Entities` | Generated HA entity metadata + `IEntityManager` abstraction. | | `HomeAssistant.Entities` | Generated HA entity metadata + `IEntityManager` abstraction. |
| `HomeAssistant.Models` | Shared HA DTOs (`EntityCreateModel`, etc.). | | `HomeAssistant.Models` | Shared HA DTOs (`EntityCreateModel`, etc.). |
| `HomeAssistant.Infrastructure` | Cross-cutting infrastructure shared by apps. |
| `HomeAssistant.McpServer` | MCP server exposing HA tools (entities, history, logbook, services, system). |
| `Mappings` | Shared mapping helpers. | | `Mappings` | Shared mapping helpers. |
### Monitor apps ### Monitor apps
+2 -23
View File
@@ -1,24 +1,3 @@
{ {
"$schema": "https://opencode.ai/config.json", "$schema": "https://opencode.ai/config.json"
"mcp": { }
"homeassistant": {
"type": "local",
"command": [
"dotnet",
"run",
"--project",
"HomeAssistant.McpServer/HomeAssistant.McpServer.csproj",
"--configuration",
"Debug",
"--verbosity",
"quiet"
],
"enabled": true,
"timeout": 60000,
"environment": {
"DOTNET_NO_LOGO": "1",
"DOTNET_ENVIRONMENT": "Development"
}
}
}
}