From 2706a6b1887d5e616f46426ba1b8fdb954249303 Mon Sep 17 00:00:00 2001 From: ExQz Date: Fri, 3 Jul 2026 12:15:44 +0300 Subject: [PATCH] Refactor services to use DI for IHaContext and TimeProvider --- BoilerMonitor.Manager/BoilerControlService.cs | 2 +- BoilerMonitor.Manager/BoilerMonitorInit.cs | 66 ++++---- .../BoilerMonitorServiceRegistration.cs | 7 +- BoilerMonitor.Manager/BoilerRunTimeTracker.cs | 2 +- .../Runners/ShowerReplayRunner.cs | 5 +- .../Services/ReplayOrchestrationService.cs | 4 +- HomeAssistant.Server/program.cs | 8 +- .../LeakNotificationServiceTests.cs | 3 +- .../LeakNotificationService.cs | 9 +- NordPool.Manager.Tests/FIXES_APPLIED.md | 141 ------------------ NordPool.Manager.Tests/NordPoolInitTests.cs | 3 +- NordPool.Manager.Tests/README.md | 93 ------------ NordPool.Manager/CheapestIntervalsFinder.cs | 3 +- NordPool.Manager/NordPoolInit.cs | 25 ++-- .../NordPoolServiceRegistration.cs | 22 +++ .../PowerCostCalculationService.cs | 21 ++- PowerMonitor.Manager/PowerMonitorInit.cs | 29 ++-- .../ExhaustFanControlServiceTests.cs | 24 +-- .../ExhaustFanControlService.cs | 18 ++- .../Interface/IExhaustFanControlService.cs | 4 +- ShowerMonitor.Manager/ShowerMonitorInit.cs | 27 ++-- .../ShowerMonitorServiceRegistration.cs | 2 +- global.json | 2 +- 23 files changed, 146 insertions(+), 374 deletions(-) delete mode 100644 NordPool.Manager.Tests/FIXES_APPLIED.md delete mode 100644 NordPool.Manager.Tests/README.md create mode 100644 NordPool.Manager/NordPoolServiceRegistration.cs diff --git a/BoilerMonitor.Manager/BoilerControlService.cs b/BoilerMonitor.Manager/BoilerControlService.cs index 152c58d..83e03f0 100644 --- a/BoilerMonitor.Manager/BoilerControlService.cs +++ b/BoilerMonitor.Manager/BoilerControlService.cs @@ -4,7 +4,7 @@ using Microsoft.Extensions.Logging; namespace BoilerMonitorManager; -public class BoilerControlService(ILogger logger) : IBoilerControlService +public sealed class BoilerControlService(ILogger logger) : IBoilerControlService { private const string SwitchOnState = "on"; diff --git a/BoilerMonitor.Manager/BoilerMonitorInit.cs b/BoilerMonitor.Manager/BoilerMonitorInit.cs index 3bf7f32..b0c7acb 100644 --- a/BoilerMonitor.Manager/BoilerMonitorInit.cs +++ b/BoilerMonitor.Manager/BoilerMonitorInit.cs @@ -31,7 +31,7 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit private readonly TimeProvider _timeProvider; private bool _lastWaterReady; - private bool _cleanedUp; + private volatile bool _cleanedUp; private DateTimeOffset? _lastWaterReadyNotificationSentAt; public BoilerMonitorInit( @@ -178,17 +178,7 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit _logger.LogInformation("Scheduling BoilerMonitor polling every {Interval}s, first at {Time}", DefaultPollIntervalSeconds, nextPollTime); - _scheduler.RunEvery(TimeSpan.FromSeconds(DefaultPollIntervalSeconds), nextPollTime, async void () => - { - try - { - await PollAndUpdateAsync(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Error during BoilerMonitor poll cycle"); - } - }); + _scheduler.RunEvery(TimeSpan.FromSeconds(DefaultPollIntervalSeconds), nextPollTime, () => _ = PollAndUpdateAsync()); } private void ScheduleMidnightReset() @@ -311,18 +301,20 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit foreach (var entityId in configEntityIds) { var subscription = await _mqttEntityManager.PrepareCommandSubscriptionAsync(entityId).ConfigureAwait(false); - subscription.Subscribe(async void (state) => - { - try - { - _logger.LogInformation("Config entity {EntityId} received command: {Value}", entityId, state); - await _mqttEntityManager.SetStateAsync(entityId, state).ConfigureAwait(false); - } - catch (Exception e) - { - _logger.LogError(e, "Error handling command for entity {EntityId}", entityId); - } - }); + subscription.Subscribe(state => _ = HandleConfigCommandAsync(entityId, state)); + } + } + + private async Task HandleConfigCommandAsync(string entityId, string? state) + { + try + { + _logger.LogInformation("Config entity {EntityId} received command: {Value}", entityId, state); + await _mqttEntityManager.SetStateAsync(entityId, state ?? string.Empty).ConfigureAwait(false); + } + catch (Exception e) + { + _logger.LogError(e, "Error handling command for entity {EntityId}", entityId); } } @@ -338,18 +330,20 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit foreach (var entityId in switchEntityIds) { var subscription = await _mqttEntityManager.PrepareCommandSubscriptionAsync(entityId).ConfigureAwait(false); - subscription.Subscribe(async void (state) => - { - try - { - _logger.LogInformation("Switch {EntityId} received command: {Value}", entityId, state); - await _mqttEntityManager.SetStateAsync(entityId, state).ConfigureAwait(false); - } - catch (Exception e) - { - _logger.LogError(e, "Error handling command for switch entity {EntityId}", entityId); - } - }); + subscription.Subscribe(state => _ = HandleSwitchCommandAsync(entityId, state)); + } + } + + private async Task HandleSwitchCommandAsync(string entityId, string? state) + { + try + { + _logger.LogInformation("Switch {EntityId} received command: {Value}", entityId, state); + await _mqttEntityManager.SetStateAsync(entityId, state ?? string.Empty).ConfigureAwait(false); + } + catch (Exception e) + { + _logger.LogError(e, "Error handling command for switch entity {EntityId}", entityId); } } diff --git a/BoilerMonitor.Manager/BoilerMonitorServiceRegistration.cs b/BoilerMonitor.Manager/BoilerMonitorServiceRegistration.cs index 9a63d28..277025d 100644 --- a/BoilerMonitor.Manager/BoilerMonitorServiceRegistration.cs +++ b/BoilerMonitor.Manager/BoilerMonitorServiceRegistration.cs @@ -15,10 +15,6 @@ public static class BoilerMonitorServiceRegistration .GetSection(BoilerMonitorOptions.SectionName) .Get() ?? new BoilerMonitorOptions(); - // Always register: NordPool and other features resolve boiler tuning from HA entity state - // even when the BoilerMonitor app itself is disabled. - services.AddScoped(); - if (!options.Enabled) { return services; @@ -29,8 +25,7 @@ public static class BoilerMonitorServiceRegistration .AddSingleton() .AddSingleton() .AddTransient() - .AddSingleton() - .AddSingleton(TimeProvider.System); + .AddSingleton(); return services; } diff --git a/BoilerMonitor.Manager/BoilerRunTimeTracker.cs b/BoilerMonitor.Manager/BoilerRunTimeTracker.cs index 46fb83c..bfad6fc 100644 --- a/BoilerMonitor.Manager/BoilerRunTimeTracker.cs +++ b/BoilerMonitor.Manager/BoilerRunTimeTracker.cs @@ -3,7 +3,7 @@ using BoilerMonitorManager.Models; namespace BoilerMonitorManager; -public class BoilerRunTimeTracker : IBoilerRunTimeTracker +public sealed class BoilerRunTimeTracker : IBoilerRunTimeTracker { private readonly Lock _lock = new(); private TimeSpan _accumulatedRunTime = TimeSpan.Zero; diff --git a/HomeAssistant.HistoryReplay/Runners/ShowerReplayRunner.cs b/HomeAssistant.HistoryReplay/Runners/ShowerReplayRunner.cs index c819378..2b76145 100644 --- a/HomeAssistant.HistoryReplay/Runners/ShowerReplayRunner.cs +++ b/HomeAssistant.HistoryReplay/Runners/ShowerReplayRunner.cs @@ -20,7 +20,6 @@ public sealed class ShowerReplayRunner : IMonitorReplayRunner private readonly ReplayDataSeries _dataSeries; private readonly IShowerDetectionService _detectionService; private readonly IExhaustFanControlService _fanControlService; - private readonly IHaContext _haContext; private readonly ILogger _logger; private readonly ReplayOptions _replayOptions; private readonly ShowerMonitorOptions _showerOptions; @@ -34,7 +33,6 @@ public sealed class ShowerReplayRunner : IMonitorReplayRunner ReplayDataSeries dataSeries, IShowerDetectionService detectionService, IExhaustFanControlService fanControlService, - IHaContext haContext, ILogger logger, IOptions replayOptions, IOptions showerOptions) @@ -45,7 +43,6 @@ public sealed class ShowerReplayRunner : IMonitorReplayRunner _dataSeries = dataSeries; _detectionService = detectionService; _fanControlService = fanControlService; - _haContext = haContext; _logger = logger; _replayOptions = replayOptions.Value; _showerOptions = showerOptions.Value; @@ -80,7 +77,7 @@ public sealed class ShowerReplayRunner : IMonitorReplayRunner _dataSeries.AddPoint(MonitorName, "State", currentTime, (double)state); - _fanControlService.Evaluate(state, currentTime, _haContext); + _fanControlService.Evaluate(state, currentTime); if (state != previousState) { diff --git a/HomeAssistant.HistoryReplay/Services/ReplayOrchestrationService.cs b/HomeAssistant.HistoryReplay/Services/ReplayOrchestrationService.cs index 0aa3d32..dd14de6 100644 --- a/HomeAssistant.HistoryReplay/Services/ReplayOrchestrationService.cs +++ b/HomeAssistant.HistoryReplay/Services/ReplayOrchestrationService.cs @@ -177,11 +177,11 @@ public sealed class ReplayOrchestrationService var detection = new ShowerMonitorManager.ShowerDetectionService( rateCalc, showerOpts); - var fan = new ExhaustFanControlService(showerOpts); + var fan = new ExhaustFanControlService(replayHaContext, showerOpts); runners.Add(new ShowerReplayRunner( historyTimeline, timeProvider, Timeline, DataSeries, - detection, fan, replayHaContext, + detection, fan, _serviceProvider.GetRequiredService>(), replayOptions, showerOpts)); } diff --git a/HomeAssistant.Server/program.cs b/HomeAssistant.Server/program.cs index 163c2e5..0595b91 100644 --- a/HomeAssistant.Server/program.cs +++ b/HomeAssistant.Server/program.cs @@ -43,7 +43,6 @@ try .AddNetDaemonStateManager() .AddNetDaemonScheduler() .AddHomeAssistantGenerated() - .AddNetDaemonApp() .AddAutoMapper(config => { config.LicenseKey = @@ -52,11 +51,10 @@ try config.AddProfile(); }) .AddTransient() + .AddSingleton(TimeProvider.System) + .AddScoped() .Configure(context.Configuration.GetSection(NordPoolOptions.SectionName)) - .AddScoped() - .AddTransient() - .AddSingleton() - .AddScoped() + .AddNordPool(context.Configuration) .Configure(context.Configuration.GetSection(PowerMonitorOptions.SectionName)) .AddPowerMonitor(context.Configuration) .Configure(context.Configuration.GetSection(BoilerMonitorOptions.SectionName)) diff --git a/LeakMonitor.Manager.Tests/LeakNotificationServiceTests.cs b/LeakMonitor.Manager.Tests/LeakNotificationServiceTests.cs index 1f6e48a..1b2009b 100644 --- a/LeakMonitor.Manager.Tests/LeakNotificationServiceTests.cs +++ b/LeakMonitor.Manager.Tests/LeakNotificationServiceTests.cs @@ -32,7 +32,8 @@ public class LeakNotificationServiceTests return new LeakNotificationService( _haContextMock.Object, _loggerMock.Object, - Options.Create(_options)); + Options.Create(_options), + TimeProvider.System); } #region SendLeakAlert diff --git a/LeakMonitor.Manager/LeakNotificationService.cs b/LeakMonitor.Manager/LeakNotificationService.cs index 6406762..4ee84c0 100644 --- a/LeakMonitor.Manager/LeakNotificationService.cs +++ b/LeakMonitor.Manager/LeakNotificationService.cs @@ -13,16 +13,19 @@ public sealed class LeakNotificationService : ILeakNotificationService private readonly IHaContext _haContext; private readonly ILogger _logger; private readonly LeakMonitorOptions _options; + private readonly TimeProvider _timeProvider; private readonly ConcurrentDictionary _lastNotificationTimes = new(); public LeakNotificationService( IHaContext haContext, ILogger logger, - IOptions options) + IOptions options, + TimeProvider timeProvider) { _haContext = haContext; _logger = logger; _options = options.Value; + _timeProvider = timeProvider; } public void SendLeakAlert(string sensorEntityId) @@ -35,7 +38,7 @@ public sealed class LeakNotificationService : ILeakNotificationService return; } - _lastNotificationTimes[sensorEntityId] = DateTimeOffset.UtcNow; + _lastNotificationTimes[sensorEntityId] = _timeProvider.GetUtcNow(); var notificationId = BuildNotificationId(sensorEntityId); var message = $"Water detected by {sensorEntityId}! Check immediately."; @@ -102,7 +105,7 @@ public sealed class LeakNotificationService : ILeakNotificationService } var cooldown = TimeSpan.FromMinutes(_options.NotificationCooldownMinutes); - return DateTimeOffset.UtcNow - lastTime < cooldown; + return _timeProvider.GetUtcNow() - lastTime < cooldown; } internal static string BuildNotificationId(string sensorEntityId) diff --git a/NordPool.Manager.Tests/FIXES_APPLIED.md b/NordPool.Manager.Tests/FIXES_APPLIED.md deleted file mode 100644 index 6b9239c..0000000 --- a/NordPool.Manager.Tests/FIXES_APPLIED.md +++ /dev/null @@ -1,141 +0,0 @@ -# Test Fixes Applied - -## Issues Encountered - -### Issue 1: Entities.Sensor Property (Moq Limitation) -``` -System.NotSupportedException: Unsupported expression: e => e.Sensor -Non-overridable members (here: Entities.get_Sensor) may not be used in setup / verification expressions. -``` - -### Issue 2: Entity.EntityId Property (Moq Limitation) -``` -System.NotSupportedException: Unsupported expression: e => e.EntityId -Non-overridable members (here: Entity.get_EntityId) may not be used in setup / verification expressions. -``` - -### Issue 3: NullReferenceException (Reflection Error) -``` -System.NullReferenceException: Object reference not set to an instance of an object. -at field!.SetValue(sut, nordPoolPrice) -``` -**Cause**: Used `GetField` instead of `GetProperty` - `NordPoolPrice` is a property, not a field. - -## Root Cause -The Home Assistant code generator creates `Entities`, `Services`, and `Entity` classes with **non-virtual properties**. Moq (the mocking framework) requires properties to be virtual to create mock setups. This is a common limitation when working with generated code. - -## Solution Applied - -### Before (Broken) -```csharp -private readonly Mock _entitiesMock; -private readonly Mock _servicesMock; - -public NordPoolInitTests() -{ - _entitiesMock = new Mock(_haContextMock.Object); - _servicesMock = new Mock(_haContextMock.Object); -} - -private NordPoolInit CreateSut() -{ - // This fails because Entities.Sensor is not virtual - _entitiesMock.Setup(e => e.Sensor) - .Returns(new SensorEntities(_haContextMock.Object)); - //... -} -``` - -### After (Fixed) - -#### Fix 1: Use Real Instances for Entities and Services -```csharp -private Entities _entities; -private Services _services; - -public NordPoolInitTests() -{ - // Use REAL instances of generated classes - _entities = new Entities(_haContextMock.Object); - _services = new Services(_haContextMock.Object); -} - -private NordPoolInit CreateSut() -{ - return new NordPoolInit( - _haContextMock.Object, - _entities, // Real instance - _services, // Real instance - _loggerMock.Object, - _mapperMock.Object, - _entityManagerMock.Object - ); -} -``` - -#### Fix 2: Use Real Entity Instance in Tests -```csharp -// Before (Broken) -var existingEntity = new Mock(_haContextMock.Object, "sensor.test_sensor"); -existingEntity.Setup(e => e.EntityId).Returns("sensor.test_sensor"); - -// After (Fixed) -// Use a real Entity instance (can't mock because EntityId is not virtual) -var existingEntity = new NumericSensorEntity(_haContextMock.Object, "sensor.test_sensor"); -``` - -#### Fix 3: Use GetProperty Instead of GetField -```csharp -// Before (Broken) - NordPoolPrice is a property, not a field -var field = typeof(NordPoolInit).GetField("NordPoolPrice", - System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); -field!.SetValue(sut, nordPoolPrice); // field is null! - -// After (Fixed) -var property = typeof(NordPoolInit).GetProperty("NordPoolPrice", - System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); -property!.SetValue(sut, nordPoolPrice); -``` - -## Trade-offs - -### ✅ Advantages -- Tests now work with generated Home Assistant classes -- More realistic testing since we're using actual instances -- No need to mock non-virtual properties - -### ⚠️ Limitations -- Cannot mock service method calls (e.g., `GetPricesForDateAsync`) -- Full integration test for `InitializeAsync` was removed -- Tests rely on the generated classes behaving consistently - -## Test Suite Status - -### ✅ Working Tests (18 total) -- ✅ All price calculation tests -- ✅ All time quarter index tests -- ✅ All entity management tests -- ✅ All data parsing tests -- ✅ Constructor and GetCurrentPrice tests - -### ⚠️ Removed Test -- ❌ `InitializeAsync_ShouldCallAllNecessaryMethods` - Requires mocking generated service classes - -## Alternative Solutions (Future) - -1. **Integration Tests**: Create integration tests that run against a real Home Assistant test instance -2. **Interface Wrapper**: Wrap generated classes in interfaces that can be mocked -3. **Partial Testing**: Test individual methods that make up `InitializeAsync` separately (current approach) - -## Recommendations - -The current solution is pragmatic and works well for unit testing. For comprehensive testing of the full initialization flow, consider: - -1. **Add integration tests** with a real Home Assistant instance in Docker -2. **Test individual methods** that `InitializeAsync` calls (GetPricesAsync, EnsureNordPoolEntityExistsAsync, etc.) -3. **Use manual testing** for the full flow during development - ---- - -**Status**: ✅ All tests compile and are ready to run in Rider -**Build Status**: 0 Errors, 0 Warnings diff --git a/NordPool.Manager.Tests/NordPoolInitTests.cs b/NordPool.Manager.Tests/NordPoolInitTests.cs index 642fa85..e56b1b2 100644 --- a/NordPool.Manager.Tests/NordPoolInitTests.cs +++ b/NordPool.Manager.Tests/NordPoolInitTests.cs @@ -73,7 +73,8 @@ public class NordPoolInitTests _schedulerMock.Object, _cheapestIntervalsFinderMock.Object, _boilerConfigProviderMock.Object, - options); + options, + TimeProvider.System); } [Fact] diff --git a/NordPool.Manager.Tests/README.md b/NordPool.Manager.Tests/README.md deleted file mode 100644 index e368875..0000000 --- a/NordPool.Manager.Tests/README.md +++ /dev/null @@ -1,93 +0,0 @@ -# NordPool.Manager.Tests - -This project contains comprehensive unit tests for the `NordPoolInit` class. - -## Test Coverage - -### Price Calculation Tests -- **PriceCorrection_ShouldCalculateCorrectPrice**: Tests the price conversion from MW/h to cents/kWh with various inputs -- **PriceCorrection_ShouldApplyVatAndConversion**: Validates the full calculation chain (MW to kW, VAT application, Euro to cents conversion) -- **AdjustedNordPoolPrice_ShouldApplyPriceCorrectionToAllPrices**: Ensures price correction is applied to all price entries -- **AdjustedNordPoolPrice_WithNullPriceValue_ShouldSkipThatPrice**: Tests handling of null prices in the list -- **AdjustedNordPoolPrice_WithNullPricesList_ShouldReturnEmptyPricesList**: Tests handling of null price lists -- **AdjustedNordPoolPrice_ShouldPreserveDateTimes**: Ensures start/end times are preserved during price adjustment - -### Time Quarter Index Tests -- **GetTimeQuarterIndex_ShouldReturnCorrectIndex**: Tests quarter calculation for various times -- **GetTimeQuarterIndex_ShouldHandleAllHoursCorrectly**: Validates all hours including edge cases (midnight, 23:00, etc.) - -### Entity Management Tests -- **GetInitEntitiesList_ShouldReturnFourEntities**: Validates that all required entities are created -- **GetInitEntitiesList_ShouldHaveCorrectEntityProperties**: Ensures entities have correct domain, identifier, and names -- **EnsureNordPoolEntityExistsAsync_WhenEntityDoesNotExist_ShouldCreateEntity**: Tests entity creation when entity is missing -- **EnsureNordPoolEntityExistsAsync_WhenEntityExists_ShouldNotCreateEntity**: Ensures no duplicate entities are created - -### Data Parsing Tests -- **ParseNordPoolResult_WithNullElement_ShouldReturnEmptyNordPoolPrice**: Tests null handling -- **ParseNordPoolResult_WithValidElement_ShouldMapCorrectly**: Validates JSON deserialization and mapping - -### Integration Tests -- **InitializeAsync_ShouldCallAllNecessaryMethods**: Tests the full initialization flow -- **GetCurrentPrice_WithValidPriceAtIndex_ShouldReturnCorrectPrice**: Tests current price retrieval logic - -## Test Framework and Libraries - -- **xUnit**: Primary testing framework -- **Moq**: Mocking framework for dependencies -- **FluentAssertions**: Fluent assertion library for readable tests -- **AutoMapper**: Used in the actual implementation, mocked in tests - -## Running the Tests - -### Using .NET CLI -```bash -dotnet test -``` - -### Using Rider or Visual Studio -Run tests through the built-in test explorer. - -### With Coverage -```bash -dotnet test --collect:"XPlat Code Coverage" -``` - -## Test Organization - -Tests are organized by functionality: -1. **Constructor Tests**: Basic initialization -2. **Calculation Tests**: Price conversion and adjustments -3. **Time Tests**: Quarter index calculations -4. **Entity Tests**: Entity creation and management -5. **Parsing Tests**: JSON parsing and data mapping -6. **Integration Tests**: Full workflow tests - -## Mocking Strategy - -The tests use Moq to mock all external dependencies: -- `ILogger`: Logging functionality -- `IMapper`: AutoMapper for DTO to model mapping -- `IEntityManager`: Entity management in Home Assistant -- `IHaContext`: Home Assistant context -- `Entities` and `Services`: Home Assistant generated entities and services - -## Constants Used in Production Code - -The tests validate these constants: -- `MegawattToKilowattDivisor = 1000.0` -- `VatRate = 1.21` (21% VAT) -- `EuroToCentsMultiplier = 100.0` -- `PriceDecimalPlaces = 2` - -## Private Method Testing - -Some private methods are tested using reflection to ensure internal logic correctness: -- `GetTimeQuarterIndex` -- `PriceCorrection` -- `AdjustedNordPoolPrice` -- `ParseNordPoolResult` -- `GetInitEntitiesList` -- `GetCurrentPrice` -- `EnsureNordPoolEntityExistsAsync` - -This approach ensures comprehensive coverage of the business logic while maintaining encapsulation. diff --git a/NordPool.Manager/CheapestIntervalsFinder.cs b/NordPool.Manager/CheapestIntervalsFinder.cs index 3ef695f..ee273c1 100644 --- a/NordPool.Manager/CheapestIntervalsFinder.cs +++ b/NordPool.Manager/CheapestIntervalsFinder.cs @@ -23,7 +23,6 @@ public class CheapestIntervalsFinder(ILogger logger) : } var eligible = prices.Prices - .AsParallel() .Where(p => p is { Start: not null, End: not null, Price: not null }) .Where(p => p.End!.Value <= deadline) .Where(p => p.Price!.Value <= priceCap) @@ -48,6 +47,6 @@ public class CheapestIntervalsFinder(ILogger logger) : public bool IsCurrentIntervalCheap(IReadOnlyList cheapestIntervals, DateTime utcNow) { - return cheapestIntervals.AsParallel().Any(interval => utcNow >= interval.Start && utcNow < interval.End); + return cheapestIntervals.Any(interval => utcNow >= interval.Start && utcNow < interval.End); } } diff --git a/NordPool.Manager/NordPoolInit.cs b/NordPool.Manager/NordPoolInit.cs index 34d8e90..a84b2d6 100644 --- a/NordPool.Manager/NordPoolInit.cs +++ b/NordPool.Manager/NordPoolInit.cs @@ -22,6 +22,7 @@ public class NordPoolInit : INordPoolInit private readonly INordPoolBoilerConfigProvider _boilerConfigProvider; private readonly IScheduler _scheduler; private readonly NordPoolOptions _options; + private readonly TimeProvider _timeProvider; private string? UnitOfMeasurement { get; } private IReadOnlyList? CheapestIntervals { get; set; } @@ -34,7 +35,8 @@ public class NordPoolInit : INordPoolInit IScheduler scheduler, ICheapestIntervalsFinder cheapestIntervalsFinder, INordPoolBoilerConfigProvider boilerConfigProvider, - IOptions options) + IOptions options, + TimeProvider timeProvider) { _logger = logger; _priceService = priceService; @@ -43,6 +45,7 @@ public class NordPoolInit : INordPoolInit _cheapestIntervalsFinder = cheapestIntervalsFinder; _boilerConfigProvider = boilerConfigProvider; _options = options.Value; + _timeProvider = timeProvider; var nordPoolPriceSensor = entities.Sensor.NordpoolPrice; UnitOfMeasurement = nordPoolPriceSensor.EntityState?.Attributes?.UnitOfMeasurement ?? "EUR/kWh"; @@ -100,7 +103,7 @@ public class NordPoolInit : INordPoolInit private void SchedulePeriodicUpdates() { - var now = DateTime.Now; + var now = _timeProvider.GetLocalNow(); var currentMinute = now.Minute; var currentSecond = now.Second; @@ -108,17 +111,7 @@ public class NordPoolInit : INordPoolInit var delayUntilNext15 = TimeSpan.FromMinutes(minutesUntilNext15) - TimeSpan.FromSeconds(currentSecond); var nextUpdateTime = now.Add(delayUntilNext15); - _scheduler.RunEvery(TimeSpan.FromMinutes(15), nextUpdateTime, async void () => - { - try - { - await UpdatePricesAsync(); - } - catch (Exception e) - { - _logger.LogError(e, "Error updating NordPool prices"); - } - }); + _scheduler.RunEvery(TimeSpan.FromMinutes(15), nextUpdateTime, () => _ = UpdatePricesAsync()); } private async Task UpdatePricesAsync() @@ -126,7 +119,7 @@ public class NordPoolInit : INordPoolInit try { var cetTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time"); - var nowCet = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, cetTimeZone); + var nowCet = TimeZoneInfo.ConvertTime(_timeProvider.GetUtcNow(), cetTimeZone).DateTime; var today = DateOnly.FromDateTime(nowCet); if (_priceService.LastFetchedDate.HasValue && _priceService.LastFetchedDate.Value < today) @@ -184,9 +177,9 @@ public class NordPoolInit : INordPoolInit private async Task UpdateEntitiesAsync(BoilerConfig boilerConfig) { var cetTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time"); - var nowCet = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, cetTimeZone); + var nowCet = TimeZoneInfo.ConvertTime(_timeProvider.GetUtcNow(), cetTimeZone).DateTime; var todayCet = DateOnly.FromDateTime(nowCet); - var currentDateTime = DateTime.Now; + var currentDateTime = nowCet; var configuredHours = (double)boilerConfig.IntervalCount / NordPoolConsts.IntervalsPerHour; var configuredReadyBy = boilerConfig.Deadline.TimeOfDay.ToString(@"hh\:mm", CultureInfo.InvariantCulture); diff --git a/NordPool.Manager/NordPoolServiceRegistration.cs b/NordPool.Manager/NordPoolServiceRegistration.cs new file mode 100644 index 0000000..c720e77 --- /dev/null +++ b/NordPool.Manager/NordPoolServiceRegistration.cs @@ -0,0 +1,22 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using NetDaemon.AppModel; +using NordPoolManager.Interface; +using NordPoolManager.Models; + +namespace NordPoolManager; + +public static class NordPoolServiceRegistration +{ + public static IServiceCollection AddNordPool(this IServiceCollection services, IConfiguration configuration) + { + services + .AddNetDaemonApp() + .AddScoped() + .AddTransient() + .AddSingleton() + .AddScoped(); + + return services; + } +} \ No newline at end of file diff --git a/PowerMonitor.Manager/PowerCostCalculationService.cs b/PowerMonitor.Manager/PowerCostCalculationService.cs index 2837198..40c05aa 100644 --- a/PowerMonitor.Manager/PowerCostCalculationService.cs +++ b/PowerMonitor.Manager/PowerCostCalculationService.cs @@ -10,6 +10,7 @@ public sealed class PowerCostCalculationService : IPowerCostCalculationService private readonly ConcurrentDictionary _deviceAccumulators = new(); private CostAccumulator? _totalAccumulator; private CostAccumulator? _otherAccumulator; + private readonly object _accumulatorLock = new(); private double _lastKnownPrice; private string _priceSource = "live"; @@ -63,12 +64,18 @@ public sealed class PowerCostCalculationService : IPowerCostCalculationService public CostSnapshot GetTotalCostSnapshot() { - return _totalAccumulator?.GetSnapshot() ?? CreateEmptySnapshot(); + lock (_accumulatorLock) + { + return _totalAccumulator?.GetSnapshot() ?? CreateEmptySnapshot(); + } } public CostSnapshot GetOtherCostSnapshot() { - return _otherAccumulator?.GetSnapshot() ?? CreateEmptySnapshot(); + lock (_accumulatorLock) + { + return _otherAccumulator?.GetSnapshot() ?? CreateEmptySnapshot(); + } } public CostSnapshot GetDeviceCostSnapshot(string entityId) @@ -93,12 +100,18 @@ public sealed class PowerCostCalculationService : IPowerCostCalculationService private CostAccumulator GetOrCreateTotalAccumulator(DateTime now) { - return _totalAccumulator ??= new CostAccumulator(now); + lock (_accumulatorLock) + { + return _totalAccumulator ??= new CostAccumulator(now); + } } private CostAccumulator GetOrCreateOtherAccumulator(DateTime now) { - return _otherAccumulator ??= new CostAccumulator(now); + lock (_accumulatorLock) + { + return _otherAccumulator ??= new CostAccumulator(now); + } } private static CostSnapshot CreateEmptySnapshot() diff --git a/PowerMonitor.Manager/PowerMonitorInit.cs b/PowerMonitor.Manager/PowerMonitorInit.cs index 39cf9c7..3db26c7 100644 --- a/PowerMonitor.Manager/PowerMonitorInit.cs +++ b/PowerMonitor.Manager/PowerMonitorInit.cs @@ -25,9 +25,10 @@ public sealed class PowerMonitorInit : IPowerMonitorInit private readonly IPowerCostCalculationService _costService; private readonly IPowerMonitorEntityService _entityService; private readonly IPowerNotificationService _notificationService; + private readonly TimeProvider _timeProvider; private int _mainMeterConsecutiveFailures; - private DateTime? _anomalyStartTime; + private DateTimeOffset? _anomalyStartTime; private bool _highPowerNotificationActive; public PowerMonitorInit( @@ -39,7 +40,8 @@ public sealed class PowerMonitorInit : IPowerMonitorInit IOtherPowerCalculationService calculationService, IPowerCostCalculationService costService, IPowerMonitorEntityService entityService, - IPowerNotificationService notificationService) + IPowerNotificationService notificationService, + TimeProvider timeProvider) { _haContext = haContext; _logger = logger; @@ -50,6 +52,7 @@ public sealed class PowerMonitorInit : IPowerMonitorInit _costService = costService; _entityService = entityService; _notificationService = notificationService; + _timeProvider = timeProvider; _ = InitializeAndScheduleAsync(); } @@ -100,7 +103,7 @@ public sealed class PowerMonitorInit : IPowerMonitorInit private void SchedulePeriodicPolling() { - var now = DateTime.Now; + var now = _timeProvider.GetLocalNow(); var intervalSeconds = _options.PollIntervalSeconds; var currentSecondInInterval = (now.Minute * 60 + now.Second) % intervalSeconds; var secondsUntilNext = intervalSeconds - currentSecondInInterval; @@ -111,17 +114,7 @@ public sealed class PowerMonitorInit : IPowerMonitorInit "Scheduling PowerMonitor polling every {Interval}s, first at {Time}", intervalSeconds, nextPollTime); - _scheduler.RunEvery(TimeSpan.FromSeconds(intervalSeconds), nextPollTime, async void () => - { - try - { - await PollAndUpdateAsync(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Error during PowerMonitor poll cycle"); - } - }); + _scheduler.RunEvery(TimeSpan.FromSeconds(intervalSeconds), nextPollTime, () => _ = PollAndUpdateAsync()); } private void SubscribeToRediscoverButton() @@ -195,12 +188,14 @@ public sealed class PowerMonitorInit : IPowerMonitorInit var priceSource = nordPoolPrice > 0 ? "live" : _costService.PriceSource; var effectivePrice = nordPoolPrice > 0 ? nordPoolPrice : _costService.LastKnownPrice; - _costService.RecordCosts(calculation, nordPoolPrice, _options.PollIntervalSeconds, DateTime.Now); + var now = _timeProvider.GetLocalNow(); + + _costService.RecordCosts(calculation, nordPoolPrice, _options.PollIntervalSeconds, now.LocalDateTime); var isAnomaly = calculation.SmoothedOtherPowerWatts > _options.AnomalyThresholdWatts; if (isAnomaly && _anomalyStartTime is null) { - _anomalyStartTime = DateTime.Now; + _anomalyStartTime = now; } else if (!isAnomaly) { @@ -208,7 +203,7 @@ public sealed class PowerMonitorInit : IPowerMonitorInit } var anomalyDuration = _anomalyStartTime.HasValue - ? DateTime.Now - _anomalyStartTime.Value + ? now - _anomalyStartTime.Value : TimeSpan.Zero; var systemStatus = _mainMeterConsecutiveFailures >= PowerMonitorConsts.MainMeterMaxConsecutiveFailures diff --git a/ShowerMonitor.Manager.Tests/ExhaustFanControlServiceTests.cs b/ShowerMonitor.Manager.Tests/ExhaustFanControlServiceTests.cs index 5b3567b..c18f092 100644 --- a/ShowerMonitor.Manager.Tests/ExhaustFanControlServiceTests.cs +++ b/ShowerMonitor.Manager.Tests/ExhaustFanControlServiceTests.cs @@ -23,7 +23,7 @@ public class ExhaustFanControlServiceTests private ExhaustFanControlService CreateService(ShowerMonitorOptions? options = null) { - return new ExhaustFanControlService(Options.Create(options ?? _defaultOptions)); + return new ExhaustFanControlService(_haContextMock.Object, Options.Create(options ?? _defaultOptions)); } [Fact] @@ -33,7 +33,7 @@ public class ExhaustFanControlServiceTests _haContextMock.Setup(x => x.GetState(FanEntityId)).Returns(entityState); var service = CreateService(); - service.Evaluate(ShowerState.Active, DateTimeOffset.UtcNow, _haContextMock.Object); + service.Evaluate(ShowerState.Active, DateTimeOffset.UtcNow); _haContextMock.Verify(x => x.CallService("switch", "turn_on", It.IsAny(), It.IsAny()), Times.Once); @@ -46,7 +46,7 @@ public class ExhaustFanControlServiceTests _haContextMock.Setup(x => x.GetState(FanEntityId)).Returns(entityState); var service = CreateService(); - service.Evaluate(ShowerState.Active, DateTimeOffset.UtcNow, _haContextMock.Object); + service.Evaluate(ShowerState.Active, DateTimeOffset.UtcNow); _haContextMock.Verify(x => x.CallService("switch", "turn_on", It.IsAny(), It.IsAny()), Times.Never); @@ -61,9 +61,9 @@ public class ExhaustFanControlServiceTests var service = CreateService(); var now = DateTimeOffset.UtcNow; - service.Evaluate(ShowerState.Active, now, _haContextMock.Object); - service.Evaluate(ShowerState.Completed, now.AddMinutes(5), _haContextMock.Object); - service.Evaluate(ShowerState.Idle, now.AddMinutes(16), _haContextMock.Object); + service.Evaluate(ShowerState.Active, now); + service.Evaluate(ShowerState.Completed, now.AddMinutes(5)); + service.Evaluate(ShowerState.Idle, now.AddMinutes(16)); _haContextMock.Verify(x => x.CallService("switch", "turn_off", It.IsAny(), It.IsAny()), Times.Once); @@ -78,9 +78,9 @@ public class ExhaustFanControlServiceTests var service = CreateService(); var now = DateTimeOffset.UtcNow; - service.Evaluate(ShowerState.Active, now, _haContextMock.Object); - service.Evaluate(ShowerState.Completed, now.AddMinutes(5), _haContextMock.Object); - service.Evaluate(ShowerState.Idle, now.AddMinutes(8), _haContextMock.Object); + service.Evaluate(ShowerState.Active, now); + service.Evaluate(ShowerState.Completed, now.AddMinutes(5)); + service.Evaluate(ShowerState.Idle, now.AddMinutes(8)); _haContextMock.Verify(x => x.CallService("switch", "turn_off", It.IsAny(), It.IsAny()), Times.Never); @@ -93,12 +93,12 @@ public class ExhaustFanControlServiceTests _haContextMock.Setup(x => x.GetState(FanEntityId)).Returns(entityState); var service = CreateService(); - service.Evaluate(ShowerState.Active, DateTimeOffset.UtcNow, _haContextMock.Object); + service.Evaluate(ShowerState.Active, DateTimeOffset.UtcNow); var fanOnState = new EntityState { State = "on" }; _haContextMock.Setup(x => x.GetState(FanEntityId)).Returns(fanOnState); - service.Reset(_haContextMock.Object); + service.Reset(); _haContextMock.Verify(x => x.CallService("switch", "turn_off", It.IsAny(), It.IsAny()), Times.Once); @@ -108,7 +108,7 @@ public class ExhaustFanControlServiceTests public void Reset_WhenFanWasNotTurnedOnByUs_DoesNotTurnFanOff() { var service = CreateService(); - service.Reset(_haContextMock.Object); + service.Reset(); _haContextMock.Verify(x => x.CallService("switch", "turn_off", It.IsAny(), It.IsAny()), Times.Never); diff --git a/ShowerMonitor.Manager/ExhaustFanControlService.cs b/ShowerMonitor.Manager/ExhaustFanControlService.cs index 65be634..aa9ef87 100644 --- a/ShowerMonitor.Manager/ExhaustFanControlService.cs +++ b/ShowerMonitor.Manager/ExhaustFanControlService.cs @@ -7,7 +7,9 @@ using ShowerMonitorManager.Models; namespace ShowerMonitorManager; -public sealed class ExhaustFanControlService(IOptions options) : IExhaustFanControlService +public sealed class ExhaustFanControlService( + IHaContext haContext, + IOptions options) : IExhaustFanControlService { private readonly ShowerMonitorOptions _options = options.Value; private readonly Lock _lock = new(); @@ -15,7 +17,7 @@ public sealed class ExhaustFanControlService(IOptions opti private bool _fanTurnedOnByUs; private DateTimeOffset? _showerEndedAt; - public void Evaluate(ShowerState state, DateTimeOffset timestamp, IHaContext haContext) + public void Evaluate(ShowerState state, DateTimeOffset timestamp) { lock (_lock) { @@ -23,24 +25,24 @@ public sealed class ExhaustFanControlService(IOptions opti { case ShowerState.Active: case ShowerState.Suspected: - TurnOnFanIfNeeded(haContext); + TurnOnFanIfNeeded(); _showerEndedAt = null; break; case ShowerState.Declining: case ShowerState.Completed: _showerEndedAt ??= timestamp; - EvaluatePostShowerFanOff(timestamp, haContext); + EvaluatePostShowerFanOff(timestamp); break; case ShowerState.Idle: - EvaluatePostShowerFanOff(timestamp, haContext); + EvaluatePostShowerFanOff(timestamp); break; } } } - public void Reset(IHaContext haContext) + public void Reset() { lock (_lock) { @@ -58,7 +60,7 @@ public sealed class ExhaustFanControlService(IOptions opti } } - private void TurnOnFanIfNeeded(IHaContext haContext) + private void TurnOnFanIfNeeded() { if (_fanTurnedOnByUs) { @@ -75,7 +77,7 @@ public sealed class ExhaustFanControlService(IOptions opti _fanTurnedOnByUs = true; } - private void EvaluatePostShowerFanOff(DateTimeOffset timestamp, IHaContext haContext) + private void EvaluatePostShowerFanOff(DateTimeOffset timestamp) { if (!_fanTurnedOnByUs || !_showerEndedAt.HasValue) { diff --git a/ShowerMonitor.Manager/Interface/IExhaustFanControlService.cs b/ShowerMonitor.Manager/Interface/IExhaustFanControlService.cs index 68628ab..02c1a1c 100644 --- a/ShowerMonitor.Manager/Interface/IExhaustFanControlService.cs +++ b/ShowerMonitor.Manager/Interface/IExhaustFanControlService.cs @@ -5,6 +5,6 @@ namespace ShowerMonitorManager.Interface; public interface IExhaustFanControlService { - void Evaluate(ShowerState state, DateTimeOffset timestamp, IHaContext haContext); - void Reset(IHaContext haContext); + void Evaluate(ShowerState state, DateTimeOffset timestamp); + void Reset(); } diff --git a/ShowerMonitor.Manager/ShowerMonitorInit.cs b/ShowerMonitor.Manager/ShowerMonitorInit.cs index fc1476a..423f4ad 100644 --- a/ShowerMonitor.Manager/ShowerMonitorInit.cs +++ b/ShowerMonitor.Manager/ShowerMonitorInit.cs @@ -23,8 +23,9 @@ public sealed class ShowerMonitorInit : IShowerMonitorInit private readonly IExhaustFanControlService _fanControlService; private readonly IShowerMonitorEntityService _entityService; private readonly ShowerMonitorOptions _options; + private readonly TimeProvider _timeProvider; - private bool _cleanedUp; + private volatile bool _cleanedUp; public ShowerMonitorInit( IHaContext haContext, @@ -33,7 +34,8 @@ public sealed class ShowerMonitorInit : IShowerMonitorInit IShowerDetectionService detectionService, IExhaustFanControlService fanControlService, IShowerMonitorEntityService entityService, - IOptions options) + IOptions options, + TimeProvider timeProvider) { _haContext = haContext; _logger = logger; @@ -42,6 +44,7 @@ public sealed class ShowerMonitorInit : IShowerMonitorInit _fanControlService = fanControlService; _entityService = entityService; _options = options.Value; + _timeProvider = timeProvider; _ = InitializeAndScheduleAsync(); } @@ -94,22 +97,12 @@ public sealed class ShowerMonitorInit : IShowerMonitorInit private void SchedulePeriodicPolling() { var pollInterval = TimeSpan.FromSeconds(_options.PollIntervalSeconds); - var now = DateTime.Now; + var now = _timeProvider.GetLocalNow(); var currentSecondInInterval = (now.Minute * 60 + now.Second) % _options.PollIntervalSeconds; var secondsUntilNext = _options.PollIntervalSeconds - currentSecondInInterval; var nextPollTime = now.Add(TimeSpan.FromSeconds(secondsUntilNext)); - _scheduler.RunEvery(pollInterval, nextPollTime, async void () => - { - try - { - await PollAndUpdateAsync(); - } - catch (Exception ex) - { - _logger.LogError(ex, "Error during ShowerMonitor poll cycle"); - } - }); + _scheduler.RunEvery(pollInterval, nextPollTime, () => _ = PollAndUpdateAsync()); } private void ScheduleMidnightReset() @@ -146,7 +139,7 @@ public sealed class ShowerMonitorInit : IShowerMonitorInit await _entityService.CleanupEntitiesAsync(); _cleanedUp = true; _detectionService.ResetDailyCounters(); - _fanControlService.Reset(_haContext); + _fanControlService.Reset(); _logger.LogDebug("ShowerMonitor cleanup complete"); } catch (Exception ex) @@ -174,11 +167,11 @@ public sealed class ShowerMonitorInit : IShowerMonitorInit return; } - var timestamp = DateTimeOffset.UtcNow; + var timestamp = _timeProvider.GetUtcNow(); var state = _detectionService.Evaluate(bathroomHumidity.Value, mainHomeHumidity.Value, timestamp); var differential = bathroomHumidity.Value - mainHomeHumidity.Value; - _fanControlService.Evaluate(state, timestamp, _haContext); + _fanControlService.Evaluate(state, timestamp); var context = new ShowerMonitorUpdateContext { diff --git a/ShowerMonitor.Manager/ShowerMonitorServiceRegistration.cs b/ShowerMonitor.Manager/ShowerMonitorServiceRegistration.cs index 4db6c90..9954afc 100644 --- a/ShowerMonitor.Manager/ShowerMonitorServiceRegistration.cs +++ b/ShowerMonitor.Manager/ShowerMonitorServiceRegistration.cs @@ -24,7 +24,7 @@ public static class ShowerMonitorServiceRegistration .AddNetDaemonApp() .AddSingleton(_ => new HumidityRateCalculator(options.RateWindowSize)) .AddSingleton() - .AddSingleton() + .AddScoped() .AddTransient(); return services; diff --git a/global.json b/global.json index f4fd385..a11f48e 100644 --- a/global.json +++ b/global.json @@ -1,6 +1,6 @@ { "sdk": { - "version": "9.0.0", + "version": "10.0.0", "rollForward": "latestMajor", "allowPrerelease": true }