This commit is contained in:
2026-06-28 14:22:13 +03:00
parent e6bf8258bb
commit 7f280bea7b
10 changed files with 54 additions and 17 deletions
@@ -95,6 +95,9 @@ public class ExhaustFanControlServiceTests
var service = CreateService();
service.Evaluate(ShowerState.Active, DateTimeOffset.UtcNow, _haContextMock.Object);
var fanOnState = new EntityState { State = "on" };
_haContextMock.Setup(x => x.GetState(FanEntityId)).Returns(fanOnState);
service.Reset(_haContextMock.Object);
_haContextMock.Verify(x => x.CallService("switch", "turn_off",
@@ -46,7 +46,11 @@ public sealed class ExhaustFanControlService(IOptions<ShowerMonitorOptions> opti
{
if (_fanTurnedOnByUs)
{
haContext.CallService("switch", "turn_off", ServiceTarget.FromEntity(_options.ExhaustFanEntityId));
var fanState = haContext.GetState(_options.ExhaustFanEntityId)?.State;
if (string.Equals(fanState, "on", StringComparison.OrdinalIgnoreCase))
{
haContext.CallService("switch", "turn_off", ServiceTarget.FromEntity(_options.ExhaustFanEntityId));
}
}
_fanTurnedOnByUs = false;
@@ -6,12 +6,19 @@ public sealed class HumidityRateCalculator(int windowSize) : IHumidityRateCalcul
{
private readonly Lock _lock = new();
private readonly Queue<(double Humidity, DateTimeOffset Timestamp)> _readings = new();
private double? _previousReading;
public double? PreviousReading
{
get { lock (_lock) { return _previousReading; } }
}
public void RecordReading(double humidity, DateTimeOffset timestamp)
{
lock (_lock)
{
_readings.Enqueue((humidity, timestamp));
_previousReading = humidity;
while (_readings.Count > windowSize)
{
@@ -47,6 +54,7 @@ public sealed class HumidityRateCalculator(int windowSize) : IHumidityRateCalcul
lock (_lock)
{
_readings.Clear();
_previousReading = null;
}
}
}
@@ -5,4 +5,5 @@ public interface IHumidityRateCalculator
void RecordReading(double humidity, DateTimeOffset timestamp);
double GetRatePerMinute();
void Reset();
double? PreviousReading { get; }
}
@@ -9,6 +9,7 @@ public interface IShowerDetectionService
ShowerSession? CurrentSession { get; }
ShowerSession? LastCompletedSession { get; }
int TodaySessionCount { get; }
double LastRate { get; }
ShowerState Evaluate(double bathroomHumidity, double mainHomeHumidity, DateTimeOffset timestamp);
void ResetDailyCounters();
@@ -19,6 +19,7 @@ public sealed class ShowerDetectionService(
private ShowerSession? _lastCompletedSession;
private int _todaySessionCount;
private DateTimeOffset? _suspectedSince;
private double _lastRate;
public ShowerState CurrentState
{
@@ -40,6 +41,11 @@ public sealed class ShowerDetectionService(
get { lock (_lock) { return _todaySessionCount; } }
}
public double LastRate
{
get { lock (_lock) { return _lastRate; } }
}
public ShowerState Evaluate(double bathroomHumidity, double mainHomeHumidity, DateTimeOffset timestamp)
{
rateCalculator.RecordReading(bathroomHumidity, timestamp);
@@ -48,6 +54,7 @@ public sealed class ShowerDetectionService(
lock (_lock)
{
_lastRate = rate;
_currentState = _currentState switch
{
ShowerState.Idle => EvaluateIdle(rate, differential, bathroomHumidity, timestamp),
@@ -79,7 +86,7 @@ public sealed class ShowerDetectionService(
_currentSession = new ShowerSession
{
StartTime = timestamp,
PreEventHumidity = humidity - (rate > 0 ? rate : 0),
PreEventHumidity = rateCalculator.PreviousReading ?? humidity,
PeakHumidity = humidity,
PeakTime = timestamp
};
@@ -125,15 +132,15 @@ public sealed class ShowerDetectionService(
}
var maxDuration = TimeSpan.FromMinutes(_options.MaxShowerDurationMinutes);
if (_currentSession is not null && _currentSession.Duration >= maxDuration)
if (_currentSession is not null && _currentSession.GetDuration(timestamp) >= maxDuration)
{
return TransitionToDeclining(timestamp);
return TransitionToDeclining();
}
if (rate < 0 && differential < _options.PeakHumidityThreshold - _options.RecoveryDifferentialThreshold)
if (rate < 0 && differential < _options.MinDifferentialHumidity)
{
return TransitionToDeclining(timestamp);
return TransitionToDeclining();
}
return ShowerState.Active;
@@ -148,8 +155,8 @@ public sealed class ShowerDetectionService(
}
var maxDuration = TimeSpan.FromMinutes(_options.MaxShowerDurationMinutes);
if (_currentSession is not null && _currentSession.Duration >= maxDuration)
if (_currentSession is not null && _currentSession.GetDuration(timestamp) >= maxDuration)
{
CompleteSession(timestamp);
return ShowerState.Completed;
@@ -158,7 +165,7 @@ public sealed class ShowerDetectionService(
return ShowerState.Declining;
}
private ShowerState TransitionToDeclining(DateTimeOffset timestamp)
private ShowerState TransitionToDeclining()
{
return ShowerState.Declining;
}
@@ -21,6 +21,7 @@ public sealed class ShowerMonitorEntityService(
HumidityRateEntityId,
LastShowerDurationEntityId,
LastShowerTimeEntityId,
TodaySessionCountEntityId,
CleanupButtonEntityId
];
@@ -65,6 +66,7 @@ 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)
};
@@ -152,6 +154,16 @@ 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)
+1 -4
View File
@@ -20,7 +20,6 @@ public sealed class ShowerMonitorInit : IShowerMonitorInit
private readonly IHaContext _haContext;
private readonly IScheduler _scheduler;
private readonly IShowerDetectionService _detectionService;
private readonly IHumidityRateCalculator _rateCalculator;
private readonly IExhaustFanControlService _fanControlService;
private readonly IShowerMonitorEntityService _entityService;
private readonly ShowerMonitorOptions _options;
@@ -32,7 +31,6 @@ public sealed class ShowerMonitorInit : IShowerMonitorInit
ILogger<ShowerMonitorInit> logger,
IScheduler scheduler,
IShowerDetectionService detectionService,
IHumidityRateCalculator rateCalculator,
IExhaustFanControlService fanControlService,
IShowerMonitorEntityService entityService,
IOptions<ShowerMonitorOptions> options)
@@ -41,7 +39,6 @@ public sealed class ShowerMonitorInit : IShowerMonitorInit
_logger = logger;
_scheduler = scheduler;
_detectionService = detectionService;
_rateCalculator = rateCalculator;
_fanControlService = fanControlService;
_entityService = entityService;
_options = options.Value;
@@ -189,7 +186,7 @@ public sealed class ShowerMonitorInit : IShowerMonitorInit
BathroomHumidity = bathroomHumidity.Value,
MainHomeHumidity = mainHomeHumidity.Value,
Differential = differential,
HumidityRate = _rateCalculator.GetRatePerMinute(),
HumidityRate = _detectionService.LastRate,
TodaySessionCount = _detectionService.TodaySessionCount,
LastCompletedSession = _detectionService.LastCompletedSession,
CurrentSession = _detectionService.CurrentSession
@@ -25,6 +25,7 @@ public static class ShowerMonitorConsts
public const string HumidityRateEntityId = "sensor.showermonitor_humidity_rate";
public const string LastShowerDurationEntityId = "sensor.showermonitor_last_shower_duration";
public const string LastShowerTimeEntityId = "sensor.showermonitor_last_shower_time";
public const string TodaySessionCountEntityId = "sensor.showermonitor_today_session_count";
public const string CleanupButtonEntityId = "button.showermonitor_cleanup";
public const string DeviceIdentifier = "shower_monitor";
+6 -3
View File
@@ -8,7 +8,10 @@ public sealed class ShowerSession
public double PeakHumidity { get; set; }
public DateTimeOffset? PeakTime { get; set; }
public TimeSpan Duration => EndTime.HasValue
? EndTime.Value - StartTime
: DateTimeOffset.UtcNow - StartTime;
public TimeSpan Duration => GetDuration(DateTimeOffset.UtcNow);
public TimeSpan GetDuration(DateTimeOffset asOf)
{
return (EndTime ?? asOf) - StartTime;
}
}