using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using ShowerMonitor.Models; using ShowerMonitor.Models.Enums; using ShowerMonitorManager.Interface; using ShowerMonitorManager.Models; namespace ShowerMonitorManager; public sealed class ShowerDetectionService : IShowerDetectionService { private readonly IHumidityRateCalculator _rateCalculator; private readonly ILogger _logger; private readonly ShowerMonitorOptions _options; private readonly Lock _lock = new(); private ShowerState _currentState = ShowerState.Idle; private ShowerSession? _currentSession; private ShowerSession? _lastCompletedSession; private int _todaySessionCount; private DateTimeOffset? _suspectedSince; public ShowerDetectionService( IHumidityRateCalculator rateCalculator, ILogger logger, IOptions options) { _rateCalculator = rateCalculator; _logger = logger; _options = options.Value; } public ShowerState CurrentState { get { lock (_lock) { return _currentState; } } } public ShowerSession? CurrentSession { get { lock (_lock) { return _currentSession; } } } public ShowerSession? LastCompletedSession { get { lock (_lock) { return _lastCompletedSession; } } } public int TodaySessionCount { get { lock (_lock) { return _todaySessionCount; } } } public ShowerState Evaluate(double bathroomHumidity, double mainHomeHumidity, DateTimeOffset timestamp) { _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), ShowerState.Suspected => EvaluateSuspected(rate, differential, bathroomHumidity, timestamp), ShowerState.Active => EvaluateActive(rate, differential, bathroomHumidity, timestamp), ShowerState.Declining => EvaluateDeclining(differential, timestamp), ShowerState.Completed => TransitionToIdle(), _ => _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; } } public void ResetDailyCounters() { lock (_lock) { _todaySessionCount = 0; _lastCompletedSession = null; _logger.LogInformation("Shower monitor daily counters reset"); } } private ShowerState EvaluateIdle(double rate, double differential, double humidity, DateTimeOffset timestamp) { if (rate >= _options.SpikeRateThreshold && differential >= _options.MinDifferentialHumidity) { _suspectedSince = timestamp; _currentSession = new ShowerSession { StartTime = timestamp, PreEventHumidity = humidity - (rate > 0 ? rate : 0), PeakHumidity = humidity, PeakTime = timestamp }; _logger.LogInformation("Shower suspected: rate={Rate}%/min, differential={Diff}%", Math.Round(rate, 2), Math.Round(differential, 1)); return ShowerState.Suspected; } return ShowerState.Idle; } private ShowerState EvaluateSuspected(double rate, double differential, double humidity, DateTimeOffset timestamp) { if (_currentSession is not null && humidity > _currentSession.PeakHumidity) { _currentSession.PeakHumidity = humidity; _currentSession.PeakTime = timestamp; } 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; } return ShowerState.Suspected; } private ShowerState EvaluateActive(double rate, double differential, double humidity, DateTimeOffset timestamp) { if (_currentSession is not null && humidity > _currentSession.PeakHumidity) { _currentSession.PeakHumidity = humidity; _currentSession.PeakTime = timestamp; } 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); } if (rate < 0 && differential < _options.PeakHumidityThreshold - _options.RecoveryDifferentialThreshold) { return TransitionToDeclining(timestamp); } return ShowerState.Active; } private ShowerState EvaluateDeclining(double differential, DateTimeOffset timestamp) { if (differential <= _options.RecoveryDifferentialThreshold) { CompleteSession(timestamp); return ShowerState.Completed; } 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; } return ShowerState.Declining; } private ShowerState TransitionToDeclining(DateTimeOffset timestamp) { _logger.LogInformation("Shower entering decline phase at {Time}", timestamp); return ShowerState.Declining; } private ShowerState TransitionToIdle() { _rateCalculator.Reset(); return ShowerState.Idle; } private void CompleteSession(DateTimeOffset endTime) { if (_currentSession is null) { return; } _currentSession.EndTime = endTime; _lastCompletedSession = _currentSession; _todaySessionCount++; _logger.LogInformation( "Shower session completed: duration={Duration}, peak={Peak}%, sessions today={Count}", _currentSession.Duration, _currentSession.PeakHumidity, _todaySessionCount); _currentSession = null; _suspectedSince = null; } private void CompleteSessionCleanup() { _currentSession = null; _suspectedSince = null; } }