diff --git a/.cursor/hooks/hooks.json b/.cursor/hooks/hooks.json deleted file mode 100644 index a023c09..0000000 --- a/.cursor/hooks/hooks.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "version": 1, - "hooks": { - "afterShellExecution": [ - { - "command": "powershell -ExecutionPolicy Bypass -File .cursor/hooks/scripts/after-build-validate.ps1" - } - ] - } -} diff --git a/.cursor/hooks/scripts/after-build-validate.ps1 b/.cursor/hooks/scripts/after-build-validate.ps1 deleted file mode 100644 index 6c3bc23..0000000 --- a/.cursor/hooks/scripts/after-build-validate.ps1 +++ /dev/null @@ -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 diff --git a/.cursor/rules/live-validation.mdc b/.cursor/rules/live-validation.mdc deleted file mode 100644 index ae14cc5..0000000 --- a/.cursor/rules/live-validation.mdc +++ /dev/null @@ -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. diff --git a/.cursor/skills/live-validation/SKILL.md b/.cursor/skills/live-validation/SKILL.md deleted file mode 100644 index 1b3ca8c..0000000 --- a/.cursor/skills/live-validation/SKILL.md +++ /dev/null @@ -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. diff --git a/AGENTS.md b/AGENTS.md index 26ac7d0..0640c9d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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 diff --git a/NordPool.Manager.Tests/NordPool.Manager.Tests.csproj b/NordPool.Manager.Tests/NordPool.Manager.Tests.csproj index 48ded57..ff8f833 100644 --- a/NordPool.Manager.Tests/NordPool.Manager.Tests.csproj +++ b/NordPool.Manager.Tests/NordPool.Manager.Tests.csproj @@ -21,6 +21,7 @@ + diff --git a/NordPool.Manager.Tests/NordPoolInitTests.cs b/NordPool.Manager.Tests/NordPoolInitTests.cs index 2a39fb3..470dd1d 100644 --- a/NordPool.Manager.Tests/NordPoolInitTests.cs +++ b/NordPool.Manager.Tests/NordPoolInitTests.cs @@ -56,7 +56,7 @@ public class NordPoolInitTests .Returns(Task.CompletedTask); _priceServiceMock.Setup(p => p.GetCurrentPrice()).Returns(0.0); - _priceServiceMock.Setup(p => p.ShouldFetchNewPrices(It.IsAny())).Returns(false); + _priceServiceMock.Setup(p => p.ShouldFetchTodaysPrices(It.IsAny())).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); diff --git a/NordPool.Manager.Tests/NordPoolPriceServiceTests.cs b/NordPool.Manager.Tests/NordPoolPriceServiceTests.cs index afcc0d4..d0e106e 100644 --- a/NordPool.Manager.Tests/NordPoolPriceServiceTests.cs +++ b/NordPool.Manager.Tests/NordPoolPriceServiceTests.cs @@ -5,6 +5,7 @@ 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; @@ -18,13 +19,16 @@ public class NordPoolPriceServiceTests { private readonly Mock _mapperMock; private readonly NordPoolPriceService _sut; + private readonly FakeTimeProvider _timeProvider; public NordPoolPriceServiceTests() { _mapperMock = new Mock(); var loggerMock = new Mock>(); - _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 @@ -542,7 +546,7 @@ 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(); @@ -616,7 +620,7 @@ 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, @@ -638,7 +642,7 @@ 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 }) @@ -660,7 +664,7 @@ 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 }) @@ -682,7 +686,7 @@ 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 }) @@ -705,9 +709,9 @@ 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(); Task Fetch(DateOnly date) @@ -721,26 +725,67 @@ 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(); + + Task 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(); + + // 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 @@ -759,7 +804,7 @@ public class NordPoolPriceServiceTests #endregion - #region ShouldFetchNewPrices + #region ShouldFetchTodaysPrices private static NordPoolPrice CreatePrices(params double?[] values) { @@ -770,38 +815,33 @@ public class NordPoolPriceServiceTests } /// - /// 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 - /// rows, so the matrix runs inside a single test. + /// xUnit cannot serialize rows, so the matrix runs inside a single test. /// [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}"); @@ -809,45 +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 { new NordPoolDayPrice { 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 { new NordPoolDayPrice { Price = 12.50 } } - }; - - _sut.TomorrowNordPoolPrice = new NordPoolPrice { Prices = new List() }; - - // Act - var result = _sut.ShouldFetchNewPrices(today); - - // Assert - result.Should().Be(DateTime.Now.Hour >= 13); + result.Should().BeFalse(); } #endregion diff --git a/NordPool.Manager/Interface/INordPoolPriceService.cs b/NordPool.Manager/Interface/INordPoolPriceService.cs index b9e172f..0b44b68 100644 --- a/NordPool.Manager/Interface/INordPoolPriceService.cs +++ b/NordPool.Manager/Interface/INordPoolPriceService.cs @@ -20,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); } \ No newline at end of file diff --git a/NordPool.Manager/NordPoolInit.cs b/NordPool.Manager/NordPoolInit.cs index 9122af7..64acca3 100644 --- a/NordPool.Manager/NordPoolInit.cs +++ b/NordPool.Manager/NordPoolInit.cs @@ -217,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, diff --git a/NordPool.Manager/NordPoolPriceService.cs b/NordPool.Manager/NordPoolPriceService.cs index e7c0319..beb2028 100644 --- a/NordPool.Manager/NordPoolPriceService.cs +++ b/NordPool.Manager/NordPoolPriceService.cs @@ -17,8 +17,10 @@ namespace NordPoolManager; /// IHaContext/generated entity dependencies so it can be a singleton. /// Fetching prices from Home Assistant lives in . /// -public class NordPoolPriceService(IMapper mapper, ILogger logger) : INordPoolPriceService +public class NordPoolPriceService(IMapper mapper, ILogger 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; } @@ -28,11 +30,10 @@ public class NordPoolPriceService(IMapper mapper, ILogger public async Task FetchPricesAsync(Func> 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)) { @@ -42,7 +43,7 @@ public class NordPoolPriceService(IMapper mapper, ILogger 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)) { @@ -52,13 +53,13 @@ public class NordPoolPriceService(IMapper mapper, ILogger 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)) { @@ -96,31 +97,19 @@ public class NordPoolPriceService(IMapper mapper, ILogger return CurrentPrice; } - public bool ShouldFetchNewPrices(DateOnly date) + public bool ShouldFetchTodaysPrices(DateOnly todayDate) { if (!LastFetchedDate.HasValue) { return true; } - if (LastFetchedDate.Value < date) + 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) @@ -231,4 +220,16 @@ public class NordPoolPriceService(IMapper mapper, ILogger return new NordPoolPrice(); } -} \ No newline at end of file + + 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 }; + } +} diff --git a/NordPool.Models/NordPoolConsts.cs b/NordPool.Models/NordPoolConsts.cs index 96f636c..7bf009e 100644 --- a/NordPool.Models/NordPoolConsts.cs +++ b/NordPool.Models/NordPoolConsts.cs @@ -39,6 +39,12 @@ public static class NordPoolConsts /// public const string FetchPricesButtonEntityId = "button.nordpool_fetch_prices"; + /// + /// 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. + /// + public const int TomorrowPricesPublishHour = 13; + /// /// Maximum number of retry attempts when fetching prices from the NordPool API. /// diff --git a/README.md b/README.md index f5da101..4a67c77 100644 --- a/README.md +++ b/README.md @@ -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.Entities` | Generated HA entity metadata + `IEntityManager` abstraction. | | `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. | ### Monitor apps diff --git a/opencode.json b/opencode.json index c21a48c..720ece5 100644 --- a/opencode.json +++ b/opencode.json @@ -1,24 +1,3 @@ { - "$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" - } - } - } -} \ No newline at end of file + "$schema": "https://opencode.ai/config.json" +}