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
+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
{