From 28eddc5dc0295fed1a4745171dfa9080c921e6d5 Mon Sep 17 00:00:00 2001 From: Marius Date: Mon, 16 Mar 2026 12:13:19 +0200 Subject: [PATCH] Add cancellation token support across NordPool services and update constants for reuse - Introduced `CancellationToken` to service methods for improved task cancellation handling. - Centralized reusable constants (`MinutesPerInterval`, `WaterReadyPowerThresholdWatts`) in `NordPoolConsts`. - Refactored `ConfigureAwait` usage and improved logging within `NordPoolEntityService`. - Adjusted tests to accommodate cancellation token changes. --- NordPool.Manager.Tests/NordPoolInitTests.cs | 4 +- NordPool.Manager/CheapestIntervalsFinder.cs | 3 +- .../Interface/INordPoolEntityService.cs | 8 +- NordPool.Manager/Interface/INordPoolInit.cs | 4 +- NordPool.Manager/NordPoolEntityService.cs | 177 +++++++++++------- NordPool.Manager/NordPoolInit.cs | 4 +- NordPool.Models/NordPoolConsts.cs | 12 +- 7 files changed, 128 insertions(+), 84 deletions(-) diff --git a/NordPool.Manager.Tests/NordPoolInitTests.cs b/NordPool.Manager.Tests/NordPoolInitTests.cs index c4c2e1b..b378ca7 100644 --- a/NordPool.Manager.Tests/NordPoolInitTests.cs +++ b/NordPool.Manager.Tests/NordPoolInitTests.cs @@ -62,13 +62,13 @@ public class NordPoolInitTests { // Arrange var sut = CreateSut(); - _entityServiceMock.Setup(es => es.CleanupEntitiesAsync()) + _entityServiceMock.Setup(es => es.CleanupEntitiesAsync(It.IsAny())) .Returns(Task.CompletedTask); // Act await sut.CleanupEntitiesAsync(); // Assert - _entityServiceMock.Verify(es => es.CleanupEntitiesAsync(), Times.Once); + _entityServiceMock.Verify(es => es.CleanupEntitiesAsync(It.IsAny()), Times.Once); } } diff --git a/NordPool.Manager/CheapestIntervalsFinder.cs b/NordPool.Manager/CheapestIntervalsFinder.cs index 3d1bfaa..06156a6 100644 --- a/NordPool.Manager/CheapestIntervalsFinder.cs +++ b/NordPool.Manager/CheapestIntervalsFinder.cs @@ -6,7 +6,6 @@ namespace NordPoolManager; public class CheapestIntervalsFinder(ILogger logger) : ICheapestIntervalsFinder { - private const double WaterReadyPowerThresholdWatts = 5.0; private const string SwitchOnState = "on"; public IReadOnlyList FindCheapestIntervals(NordPoolPrice prices, int numberOfIntervals, double priceCap, DateTime deadline) @@ -63,6 +62,6 @@ public class CheapestIntervalsFinder(ILogger logger) : return false; } - return string.Equals(switchState, SwitchOnState, StringComparison.OrdinalIgnoreCase) && powerWatts.Value < WaterReadyPowerThresholdWatts; + return string.Equals(switchState, SwitchOnState, StringComparison.OrdinalIgnoreCase) && powerWatts.Value < NordPoolConsts.WaterReadyPowerThresholdWatts; } } diff --git a/NordPool.Manager/Interface/INordPoolEntityService.cs b/NordPool.Manager/Interface/INordPoolEntityService.cs index 10f37a1..1ac23bf 100644 --- a/NordPool.Manager/Interface/INordPoolEntityService.cs +++ b/NordPool.Manager/Interface/INordPoolEntityService.cs @@ -4,8 +4,8 @@ namespace NordPoolManager.Interface; public interface INordPoolEntityService { - Task CreateEntitiesAsync(string? unitOfMeasurement); - Task ResetEntitiesAsync(); - Task UpdateEntitiesAsync(EntityUpdateContext context); - Task CleanupEntitiesAsync(); + Task CreateEntitiesAsync(string? unitOfMeasurement, CancellationToken cancellationToken = default); + Task ResetEntitiesAsync(CancellationToken cancellationToken = default); + Task UpdateEntitiesAsync(EntityUpdateContext context, CancellationToken cancellationToken = default); + Task CleanupEntitiesAsync(CancellationToken cancellationToken = default); } diff --git a/NordPool.Manager/Interface/INordPoolInit.cs b/NordPool.Manager/Interface/INordPoolInit.cs index eeb9a94..8f8076a 100644 --- a/NordPool.Manager/Interface/INordPoolInit.cs +++ b/NordPool.Manager/Interface/INordPoolInit.cs @@ -1,7 +1,7 @@ -namespace NordPoolManager.Interface; +namespace NordPoolManager.Interface; public interface INordPoolInit { Task InitializeAsync(); - Task CleanupEntitiesAsync(); + Task CleanupEntitiesAsync(CancellationToken cancellationToken = default); } \ No newline at end of file diff --git a/NordPool.Manager/NordPoolEntityService.cs b/NordPool.Manager/NordPoolEntityService.cs index ad0e6d5..35f862e 100644 --- a/NordPool.Manager/NordPoolEntityService.cs +++ b/NordPool.Manager/NordPoolEntityService.cs @@ -8,7 +8,7 @@ using NordPoolManager.Models; namespace NordPoolManager; -public class NordPoolEntityService(IEntityManager entityManager, ILogger logger) : INordPoolEntityService +public sealed class NordPoolEntityService(IEntityManager entityManager, ILogger logger) : INordPoolEntityService { private const string LastUpdateTimeEntityId = "sensor.nordpool_last_update_time"; private const string CurrentPriceEntityId = "sensor.nordpool_current_price"; @@ -31,27 +31,32 @@ public class NordPoolEntityService(IEntityManager entityManager, ILogger { try { logger.LogInformation("Creating/re-registering MQTT entity: {EntityId}", nordPoolEntity.EntityId); - - await entityManager.CreateEntityAsync(nordPoolEntity); + await entityManager.CreateEntityAsync(nordPoolEntity).ConfigureAwait(false); } catch (Exception ex) { logger.LogError(ex, "Failed to create MQTT entity: {EntityId}", nordPoolEntity.EntityId); } - } + }); + + await Task.WhenAll(createTasks).ConfigureAwait(false); } - public async Task ResetEntitiesAsync() + public async Task ResetEntitiesAsync(CancellationToken cancellationToken = default) { + cancellationToken.ThrowIfCancellationRequested(); + logger.LogInformation("Resetting all NordPool entity states to defaults"); await Task.WhenAll( @@ -63,23 +68,23 @@ public class NordPoolEntityService(IEntityManager entityManager, ILogger(), friendly_name = "NordPool today prices", last_updated = (string?)null - }); + }).ConfigureAwait(false); } private async Task ResetTomorrowPricesAsync() { - await SetEntityStateSafe(TomorrowPricesEntityId, "0"); + await SetEntityStateSafe(TomorrowPricesEntityId, "0").ConfigureAwait(false); await SetEntityAttributesSafe(TomorrowPricesEntityId, new { prices = Array.Empty(), friendly_name = "NordPool tomorrow prices", last_updated = (string?)null - }); + }).ConfigureAwait(false); } private async Task ResetTodayTomorrowPricesAsync() { - await SetEntityStateSafe(TodayTomorrowPricesEntityId, "unknown"); + await SetEntityStateSafe(TodayTomorrowPricesEntityId, "unknown").ConfigureAwait(false); await SetEntityAttributesSafe(TodayTomorrowPricesEntityId, new { prices = Array.Empty(), prices_count = 0, friendly_name = "NordPool today and tomorrow prices", last_updated = (string?)null - }); + }).ConfigureAwait(false); } private async Task ResetCheapestIntervalsAsync() { - await SetEntityStateSafe(CheapestIntervalsEntityId, "0"); + await SetEntityStateSafe(CheapestIntervalsEntityId, "0").ConfigureAwait(false); await SetEntityAttributesSafe(CheapestIntervalsEntityId, new { intervals = Array.Empty(), @@ -142,39 +147,71 @@ public class NordPoolEntityService(IEntityManager entityManager, ILogger(), friendly_name = "NordPool today prices", last_updated = timestamp - }); + }).ConfigureAwait(false); + } - var tomorrowPricesCount = ctx.TomorrowNordPoolPrice?.Prices?.Count ?? 0; - logger.LogInformation("Updating sensor.nordpool_tomorrow_prices with {Count} prices", tomorrowPricesCount); - - await SetEntityStateSafe(TomorrowPricesEntityId, tomorrowPricesCount.ToString()); + private async Task UpdateTomorrowPricesAsync(EntityUpdateContext ctx, int tomorrowPricesCount, string timestamp) + { + await SetEntityStateSafe(TomorrowPricesEntityId, tomorrowPricesCount.ToString()).ConfigureAwait(false); await SetEntityAttributesSafe(TomorrowPricesEntityId, new { prices = ctx.TomorrowNordPoolPrice?.Prices ?? Array.Empty(), friendly_name = "NordPool tomorrow prices", last_updated = timestamp - }); + }).ConfigureAwait(false); + } - var mergedPrices = MergeTodayTomorrowPrices(ctx.TodayNordPoolPrice, ctx.TomorrowNordPoolPrice); - var updateTimeState = utcNow.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss"); - logger.LogInformation("Updating sensor.nordpool_today_tomorrow_prices with {Count} merged prices", mergedPrices.Count); - - await SetEntityStateSafe(TodayTomorrowPricesEntityId, updateTimeState); + private async Task UpdateTodayTomorrowPricesAsync(List mergedPrices, string updateTimeState, string timestamp) + { + await SetEntityStateSafe(TodayTomorrowPricesEntityId, updateTimeState).ConfigureAwait(false); await SetEntityAttributesSafe(TodayTomorrowPricesEntityId, new { prices = mergedPrices, prices_count = mergedPrices.Count, friendly_name = "NordPool today and tomorrow prices", last_updated = timestamp - }); + }).ConfigureAwait(false); + } - var cheapestCount = ctx.CheapestIntervals?.Count ?? 0; - logger.LogInformation("Updating sensor.nordpool_cheapest_intervals with {Count} intervals, is_now_cheap={IsNow}", cheapestCount, ctx.IsNowCheap); - - await SetEntityStateSafe(CheapestIntervalsEntityId, cheapestCount.ToString()); + private async Task UpdateCheapestIntervalsAsync(EntityUpdateContext ctx, int cheapestCount, string timestamp) + { + await SetEntityStateSafe(CheapestIntervalsEntityId, cheapestCount.ToString()).ConfigureAwait(false); await SetEntityAttributesSafe(CheapestIntervalsEntityId, new { intervals = ctx.CheapestIntervals ?? [], @@ -234,36 +270,35 @@ public class NordPoolEntityService(IEntityManager entityManager, ILogger entityManager.RemoveEntity(entityId)); + await Task.WhenAll(removeTasks).ConfigureAwait(false); logger.LogInformation("NordPool entities cleaned up successfully"); } @@ -315,11 +350,11 @@ public class NordPoolEntityService(IEntityManager entityManager, ILogger p?.Start != null) - .OrderBy(p => p!.Start!.Value) + .Where(p => p is { Start: not null }) + .OrderBy(p => p.Start!.Value) .ToList(); } @@ -327,7 +362,7 @@ public class NordPoolEntityService(IEntityManager entityManager, ILogger + /// NordPool electricity market uses 15-minute trading intervals. + /// + public const int MinutesPerInterval = 15; + + /// + /// Power threshold in watts below which the boiler is considered to have finished heating (water ready). + /// + public const double WaterReadyPowerThresholdWatts = 5.0; } \ No newline at end of file