Refactor services to use DI for IHaContext and TimeProvider

This commit is contained in:
2026-07-03 12:15:44 +03:00
parent 7f280bea7b
commit 2706a6b188
23 changed files with 146 additions and 374 deletions
@@ -4,7 +4,7 @@ using Microsoft.Extensions.Logging;
namespace BoilerMonitorManager;
public class BoilerControlService(ILogger<BoilerControlService> logger) : IBoilerControlService
public sealed class BoilerControlService(ILogger<BoilerControlService> logger) : IBoilerControlService
{
private const string SwitchOnState = "on";
+30 -36
View File
@@ -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);
}
}
@@ -15,10 +15,6 @@ public static class BoilerMonitorServiceRegistration
.GetSection(BoilerMonitorOptions.SectionName)
.Get<BoilerMonitorOptions>() ?? 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<IBoilerConfigReader, BoilerConfigReader>();
if (!options.Enabled)
{
return services;
@@ -29,8 +25,7 @@ public static class BoilerMonitorServiceRegistration
.AddSingleton<IBoilerControlService, BoilerControlService>()
.AddSingleton<IBoilerRunTimeTracker, BoilerRunTimeTracker>()
.AddTransient<IBoilerMonitorEntityService, BoilerMonitorEntityService>()
.AddSingleton<IWaterReadyService, WaterReadyService>()
.AddSingleton(TimeProvider.System);
.AddSingleton<IWaterReadyService, WaterReadyService>();
return services;
}
@@ -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;
@@ -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<ShowerReplayRunner> _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<ShowerReplayRunner> logger,
IOptions<ReplayOptions> replayOptions,
IOptions<ShowerMonitorOptions> 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)
{
@@ -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<ILogger<ShowerReplayRunner>>(),
replayOptions, showerOpts));
}
+3 -5
View File
@@ -43,7 +43,6 @@ try
.AddNetDaemonStateManager()
.AddNetDaemonScheduler()
.AddHomeAssistantGenerated()
.AddNetDaemonApp<NordPoolInit>()
.AddAutoMapper(config =>
{
config.LicenseKey =
@@ -52,11 +51,10 @@ try
config.AddProfile<GlobalMappingProfile>();
})
.AddTransient<IEntityManager, EntityManager>()
.AddSingleton(TimeProvider.System)
.AddScoped<BoilerMonitor.Models.IBoilerConfigReader, BoilerConfigReader>()
.Configure<NordPoolOptions>(context.Configuration.GetSection(NordPoolOptions.SectionName))
.AddScoped<INordPoolPriceService, NordPoolPriceService>()
.AddTransient<INordPoolEntityService, NordPoolEntityService>()
.AddSingleton<ICheapestIntervalsFinder, CheapestIntervalsFinder>()
.AddScoped<INordPoolBoilerConfigProvider, NordPoolBoilerConfigProvider>()
.AddNordPool(context.Configuration)
.Configure<PowerMonitorOptions>(context.Configuration.GetSection(PowerMonitorOptions.SectionName))
.AddPowerMonitor(context.Configuration)
.Configure<BoilerMonitorOptions>(context.Configuration.GetSection(BoilerMonitorOptions.SectionName))
@@ -32,7 +32,8 @@ public class LeakNotificationServiceTests
return new LeakNotificationService(
_haContextMock.Object,
_loggerMock.Object,
Options.Create(_options));
Options.Create(_options),
TimeProvider.System);
}
#region SendLeakAlert
@@ -13,16 +13,19 @@ public sealed class LeakNotificationService : ILeakNotificationService
private readonly IHaContext _haContext;
private readonly ILogger<LeakNotificationService> _logger;
private readonly LeakMonitorOptions _options;
private readonly TimeProvider _timeProvider;
private readonly ConcurrentDictionary<string, DateTimeOffset> _lastNotificationTimes = new();
public LeakNotificationService(
IHaContext haContext,
ILogger<LeakNotificationService> logger,
IOptions<LeakMonitorOptions> options)
IOptions<LeakMonitorOptions> 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)
-141
View File
@@ -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<Entities> _entitiesMock;
private readonly Mock<Services> _servicesMock;
public NordPoolInitTests()
{
_entitiesMock = new Mock<Entities>(_haContextMock.Object);
_servicesMock = new Mock<Services>(_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<Entity>(_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
+2 -1
View File
@@ -73,7 +73,8 @@ public class NordPoolInitTests
_schedulerMock.Object,
_cheapestIntervalsFinderMock.Object,
_boilerConfigProviderMock.Object,
options);
options,
TimeProvider.System);
}
[Fact]
-93
View File
@@ -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<NordPoolInit>`: 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.
+1 -2
View File
@@ -23,7 +23,6 @@ public class CheapestIntervalsFinder(ILogger<CheapestIntervalsFinder> 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<CheapestIntervalsFinder> logger) :
public bool IsCurrentIntervalCheap(IReadOnlyList<CheapestIntervalResult> cheapestIntervals, DateTime utcNow)
{
return cheapestIntervals.AsParallel().Any(interval => utcNow >= interval.Start && utcNow < interval.End);
return cheapestIntervals.Any(interval => utcNow >= interval.Start && utcNow < interval.End);
}
}
+9 -16
View File
@@ -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<CheapestIntervalResult>? CheapestIntervals { get; set; }
@@ -34,7 +35,8 @@ public class NordPoolInit : INordPoolInit
IScheduler scheduler,
ICheapestIntervalsFinder cheapestIntervalsFinder,
INordPoolBoilerConfigProvider boilerConfigProvider,
IOptions<NordPoolOptions> options)
IOptions<NordPoolOptions> 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);
@@ -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<NordPoolInit>()
.AddScoped<INordPoolPriceService, NordPoolPriceService>()
.AddTransient<INordPoolEntityService, NordPoolEntityService>()
.AddSingleton<ICheapestIntervalsFinder, CheapestIntervalsFinder>()
.AddScoped<INordPoolBoilerConfigProvider, NordPoolBoilerConfigProvider>();
return services;
}
}
@@ -10,6 +10,7 @@ public sealed class PowerCostCalculationService : IPowerCostCalculationService
private readonly ConcurrentDictionary<string, CostAccumulator> _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()
+12 -17
View File
@@ -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
@@ -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<ServiceTarget>(), It.IsAny<object?>()), 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<ServiceTarget>(), It.IsAny<object?>()), 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<ServiceTarget>(), It.IsAny<object?>()), 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<ServiceTarget>(), It.IsAny<object?>()), 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<ServiceTarget>(), It.IsAny<object?>()), 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<ServiceTarget>(), It.IsAny<object?>()), Times.Never);
@@ -7,7 +7,9 @@ using ShowerMonitorManager.Models;
namespace ShowerMonitorManager;
public sealed class ExhaustFanControlService(IOptions<ShowerMonitorOptions> options) : IExhaustFanControlService
public sealed class ExhaustFanControlService(
IHaContext haContext,
IOptions<ShowerMonitorOptions> options) : IExhaustFanControlService
{
private readonly ShowerMonitorOptions _options = options.Value;
private readonly Lock _lock = new();
@@ -15,7 +17,7 @@ public sealed class ExhaustFanControlService(IOptions<ShowerMonitorOptions> 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<ShowerMonitorOptions> 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<ShowerMonitorOptions> opti
}
}
private void TurnOnFanIfNeeded(IHaContext haContext)
private void TurnOnFanIfNeeded()
{
if (_fanTurnedOnByUs)
{
@@ -75,7 +77,7 @@ public sealed class ExhaustFanControlService(IOptions<ShowerMonitorOptions> opti
_fanTurnedOnByUs = true;
}
private void EvaluatePostShowerFanOff(DateTimeOffset timestamp, IHaContext haContext)
private void EvaluatePostShowerFanOff(DateTimeOffset timestamp)
{
if (!_fanTurnedOnByUs || !_showerEndedAt.HasValue)
{
@@ -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();
}
+10 -17
View File
@@ -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<ShowerMonitorOptions> options)
IOptions<ShowerMonitorOptions> 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
{
@@ -24,7 +24,7 @@ public static class ShowerMonitorServiceRegistration
.AddNetDaemonApp<ShowerMonitorInit>()
.AddSingleton<IHumidityRateCalculator>(_ => new HumidityRateCalculator(options.RateWindowSize))
.AddSingleton<IShowerDetectionService, ShowerDetectionService>()
.AddSingleton<IExhaustFanControlService, ExhaustFanControlService>()
.AddScoped<IExhaustFanControlService, ExhaustFanControlService>()
.AddTransient<IShowerMonitorEntityService, ShowerMonitorEntityService>();
return services;
+1 -1
View File
@@ -1,6 +1,6 @@
{
"sdk": {
"version": "9.0.0",
"version": "10.0.0",
"rollForward": "latestMajor",
"allowPrerelease": true
}