This commit is contained in:
2026-06-28 13:58:35 +03:00
parent 8f45028715
commit e6bf8258bb
114 changed files with 4365 additions and 874 deletions
@@ -1,4 +1,3 @@
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
@@ -8,23 +7,14 @@ using ShowerMonitorManager.Models;
namespace ShowerMonitorManager;
public sealed class ExhaustFanControlService : IExhaustFanControlService
public sealed class ExhaustFanControlService(IOptions<ShowerMonitorOptions> options) : IExhaustFanControlService
{
private readonly ILogger<ExhaustFanControlService> _logger;
private readonly ShowerMonitorOptions _options;
private readonly ShowerMonitorOptions _options = options.Value;
private readonly Lock _lock = new();
private bool _fanTurnedOnByUs;
private DateTimeOffset? _showerEndedAt;
public ExhaustFanControlService(
ILogger<ExhaustFanControlService> logger,
IOptions<ShowerMonitorOptions> options)
{
_logger = logger;
_options = options.Value;
}
public void Evaluate(ShowerState state, DateTimeOffset timestamp, IHaContext haContext)
{
lock (_lock)
@@ -57,7 +47,6 @@ public sealed class ExhaustFanControlService : IExhaustFanControlService
if (_fanTurnedOnByUs)
{
haContext.CallService("switch", "turn_off", ServiceTarget.FromEntity(_options.ExhaustFanEntityId));
_logger.LogInformation("Exhaust fan turned OFF during reset (was turned on by shower detection)");
}
_fanTurnedOnByUs = false;
@@ -80,7 +69,6 @@ public sealed class ExhaustFanControlService : IExhaustFanControlService
haContext.CallService("switch", "turn_on", ServiceTarget.FromEntity(_options.ExhaustFanEntityId));
_fanTurnedOnByUs = true;
_logger.LogInformation("Exhaust fan turned ON by shower detection");
}
private void EvaluatePostShowerFanOff(DateTimeOffset timestamp, IHaContext haContext)
@@ -101,6 +89,5 @@ public sealed class ExhaustFanControlService : IExhaustFanControlService
haContext.CallService("switch", "turn_off", ServiceTarget.FromEntity(_options.ExhaustFanEntityId));
_fanTurnedOnByUs = false;
_showerEndedAt = null;
_logger.LogInformation("Exhaust fan turned OFF after post-shower run period ({Duration})", runAfterDuration);
}
}
@@ -6,6 +6,5 @@ public interface IShowerMonitorEntityService
{
Task CreateEntitiesAsync(CancellationToken cancellationToken = default);
Task UpdateEntitiesAsync(ShowerMonitorUpdateContext context, CancellationToken cancellationToken = default);
Task ResetEntitiesAsync(CancellationToken cancellationToken = default);
Task CleanupEntitiesAsync(CancellationToken cancellationToken = default);
}
+11 -37
View File
@@ -1,4 +1,3 @@
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using ShowerMonitor.Models;
using ShowerMonitor.Models.Enums;
@@ -7,11 +6,12 @@ using ShowerMonitorManager.Models;
namespace ShowerMonitorManager;
public sealed class ShowerDetectionService : IShowerDetectionService
public sealed class ShowerDetectionService(
IHumidityRateCalculator rateCalculator,
IOptions<ShowerMonitorOptions> options)
: IShowerDetectionService
{
private readonly IHumidityRateCalculator _rateCalculator;
private readonly ILogger<ShowerDetectionService> _logger;
private readonly ShowerMonitorOptions _options;
private readonly ShowerMonitorOptions _options = options.Value;
private readonly Lock _lock = new();
private ShowerState _currentState = ShowerState.Idle;
@@ -20,16 +20,6 @@ public sealed class ShowerDetectionService : IShowerDetectionService
private int _todaySessionCount;
private DateTimeOffset? _suspectedSince;
public ShowerDetectionService(
IHumidityRateCalculator rateCalculator,
ILogger<ShowerDetectionService> logger,
IOptions<ShowerMonitorOptions> options)
{
_rateCalculator = rateCalculator;
_logger = logger;
_options = options.Value;
}
public ShowerState CurrentState
{
get { lock (_lock) { return _currentState; } }
@@ -52,13 +42,12 @@ public sealed class ShowerDetectionService : IShowerDetectionService
public ShowerState Evaluate(double bathroomHumidity, double mainHomeHumidity, DateTimeOffset timestamp)
{
_rateCalculator.RecordReading(bathroomHumidity, timestamp);
var rate = _rateCalculator.GetRatePerMinute();
rateCalculator.RecordReading(bathroomHumidity, timestamp);
var rate = rateCalculator.GetRatePerMinute();
var differential = bathroomHumidity - mainHomeHumidity;
lock (_lock)
{
var previousState = _currentState;
_currentState = _currentState switch
{
ShowerState.Idle => EvaluateIdle(rate, differential, bathroomHumidity, timestamp),
@@ -69,13 +58,6 @@ public sealed class ShowerDetectionService : IShowerDetectionService
_ => _currentState
};
if (_currentState != previousState)
{
_logger.LogInformation(
"Shower state transition: {Previous} -> {Current} (humidity={Humidity}%, differential={Diff}%, rate={Rate}%/min)",
previousState, _currentState, bathroomHumidity, Math.Round(differential, 1), Math.Round(rate, 2));
}
return _currentState;
}
}
@@ -86,7 +68,6 @@ public sealed class ShowerDetectionService : IShowerDetectionService
{
_todaySessionCount = 0;
_lastCompletedSession = null;
_logger.LogInformation("Shower monitor daily counters reset");
}
}
@@ -103,7 +84,6 @@ public sealed class ShowerDetectionService : IShowerDetectionService
PeakTime = timestamp
};
_logger.LogInformation("Shower suspected: rate={Rate}%/min, differential={Diff}%", Math.Round(rate, 2), Math.Round(differential, 1));
return ShowerState.Suspected;
}
@@ -119,17 +99,16 @@ public sealed class ShowerDetectionService : IShowerDetectionService
}
var confirmationWindow = TimeSpan.FromMinutes(_options.ConfirmationWindowMinutes);
if (_suspectedSince.HasValue && (timestamp - _suspectedSince.Value) >= confirmationWindow
&& humidity >= _options.PeakHumidityThreshold
&& differential >= _options.MinDifferentialHumidity)
{
_logger.LogInformation("Shower confirmed: peak={Peak}%, differential={Diff}%", humidity, Math.Round(differential, 1));
return ShowerState.Active;
}
if (rate < 0 && differential < _options.MinDifferentialHumidity)
{
_logger.LogInformation("Shower suspicion cleared: differential dropped below threshold");
CompleteSessionCleanup();
return ShowerState.Idle;
}
@@ -146,9 +125,9 @@ public sealed class ShowerDetectionService : IShowerDetectionService
}
var maxDuration = TimeSpan.FromMinutes(_options.MaxShowerDurationMinutes);
if (_currentSession is not null && _currentSession.Duration >= maxDuration)
{
_logger.LogWarning("Shower exceeded max duration ({MaxDuration}), completing", maxDuration);
return TransitionToDeclining(timestamp);
}
@@ -169,9 +148,9 @@ public sealed class ShowerDetectionService : IShowerDetectionService
}
var maxDuration = TimeSpan.FromMinutes(_options.MaxShowerDurationMinutes);
if (_currentSession is not null && _currentSession.Duration >= maxDuration)
{
_logger.LogWarning("Shower declining phase exceeded max duration, completing");
CompleteSession(timestamp);
return ShowerState.Completed;
}
@@ -181,13 +160,12 @@ public sealed class ShowerDetectionService : IShowerDetectionService
private ShowerState TransitionToDeclining(DateTimeOffset timestamp)
{
_logger.LogInformation("Shower entering decline phase at {Time}", timestamp);
return ShowerState.Declining;
}
private ShowerState TransitionToIdle()
{
_rateCalculator.Reset();
rateCalculator.Reset();
return ShowerState.Idle;
}
@@ -202,10 +180,6 @@ public sealed class ShowerDetectionService : IShowerDetectionService
_lastCompletedSession = _currentSession;
_todaySessionCount++;
_logger.LogInformation(
"Shower session completed: duration={Duration}, peak={Peak}%, sessions today={Count}",
_currentSession.Duration, _currentSession.PeakHumidity, _todaySessionCount);
_currentSession = null;
_suspectedSince = null;
}
@@ -19,7 +19,6 @@ public sealed class ShowerMonitorEntityService(
StateEntityId,
DifferentialEntityId,
HumidityRateEntityId,
TodaySessionCountEntityId,
LastShowerDurationEntityId,
LastShowerTimeEntityId,
CleanupButtonEntityId
@@ -42,7 +41,6 @@ public sealed class ShowerMonitorEntityService(
{
try
{
logger.LogInformation("Creating MQTT entity: {EntityId}", entity.EntityId);
await entityManager.CreateEntityAsync(entity).ConfigureAwait(false);
}
catch (Exception ex)
@@ -67,37 +65,19 @@ public sealed class ShowerMonitorEntityService(
SetEntityStateSafe(StateEntityId, ctx.State.ToString().ToLowerInvariant()),
UpdateDifferentialAsync(ctx.Differential, timestamp),
UpdateHumidityRateAsync(ctx.HumidityRate, timestamp),
UpdateTodaySessionCountAsync(ctx.TodaySessionCount, timestamp),
UpdateLastShowerAsync(ctx.LastCompletedSession, timestamp)
};
await Task.WhenAll(updateTasks).ConfigureAwait(false);
}
public async Task ResetEntitiesAsync(CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
logger.LogInformation("Resetting ShowerMonitor entity states to defaults");
await Task.WhenAll(
SetEntityStateSafe(ActiveEntityId, "off"),
SetEntityStateSafe(StateEntityId, ShowerState.Idle.ToString().ToLowerInvariant()),
SetEntityStateSafe(DifferentialEntityId, "0"),
SetEntityStateSafe(HumidityRateEntityId, "0"),
SetEntityStateSafe(TodaySessionCountEntityId, "0"),
SetEntityStateSafe(LastShowerDurationEntityId, "0"),
SetEntityStateSafe(LastShowerTimeEntityId, "unknown")
).ConfigureAwait(false);
}
public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
try
{
var removeTasks = CleanableEntityIds.Select(entityId => entityManager.RemoveEntity(entityId));
var removeTasks = CleanableEntityIds.Select(entityManager.RemoveEntity);
await Task.WhenAll(removeTasks).ConfigureAwait(false);
logger.LogInformation("ShowerMonitor entities cleaned up successfully");
@@ -172,16 +152,6 @@ public sealed class ShowerMonitorEntityService(
}).ConfigureAwait(false);
}
private async Task UpdateTodaySessionCountAsync(int count, string timestamp)
{
await SetEntityStateSafe(TodaySessionCountEntityId, count.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
await SetEntityAttributesSafe(TodaySessionCountEntityId, new
{
friendly_name = "Showers today",
last_updated = timestamp
}).ConfigureAwait(false);
}
private async Task UpdateLastShowerAsync(ShowerSession? session, string timestamp)
{
if (session is null)
@@ -235,6 +205,7 @@ public sealed class ShowerMonitorEntityService(
{
var totalMinutes = (int)ts.TotalMinutes;
var seconds = ts.Seconds;
return $"{totalMinutes}m {seconds}s";
}
}
+3 -7
View File
@@ -76,7 +76,6 @@ public sealed class ShowerMonitorInit : IShowerMonitorInit
}
await _entityService.CreateEntitiesAsync();
await _entityService.ResetEntitiesAsync();
await Task.Delay(TimeSpan.FromSeconds(2));
await PollAndUpdateAsync();
@@ -103,8 +102,6 @@ public sealed class ShowerMonitorInit : IShowerMonitorInit
var secondsUntilNext = _options.PollIntervalSeconds - currentSecondInInterval;
var nextPollTime = now.Add(TimeSpan.FromSeconds(secondsUntilNext));
_logger.LogInformation("Scheduling ShowerMonitor polling every {Interval}s, first at {Time}", _options.PollIntervalSeconds, nextPollTime);
_scheduler.RunEvery(pollInterval, nextPollTime, async void () =>
{
try
@@ -124,9 +121,8 @@ public sealed class ShowerMonitorInit : IShowerMonitorInit
{
try
{
_logger.LogInformation("Midnight reset: clearing shower session counters");
_logger.LogDebug("Midnight reset: clearing shower session counters");
_detectionService.ResetDailyCounters();
_ = _entityService.ResetEntitiesAsync();
}
catch (Exception ex)
{
@@ -141,7 +137,7 @@ public sealed class ShowerMonitorInit : IShowerMonitorInit
cleanupButton.StateChanges()
.Subscribe(_ =>
{
_logger.LogInformation("Cleanup button pressed, removing all ShowerMonitor entities");
_logger.LogDebug("Cleanup button pressed, removing all ShowerMonitor entities");
Task.Run(HandleCleanupAsync);
});
}
@@ -154,7 +150,7 @@ public sealed class ShowerMonitorInit : IShowerMonitorInit
_cleanedUp = true;
_detectionService.ResetDailyCounters();
_fanControlService.Reset(_haContext);
_logger.LogInformation("ShowerMonitor cleanup complete");
_logger.LogDebug("ShowerMonitor cleanup complete");
}
catch (Exception ex)
{