using System.Globalization; using System.Reactive.Concurrency; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using NetDaemon.AppModel; using NetDaemon.Extensions.Scheduler; using NetDaemon.HassModel; using NetDaemon.HassModel.Entities; using ShowerMonitorManager.Interface; using ShowerMonitorManager.Models; using static ShowerMonitor.Models.ShowerMonitorConsts; namespace ShowerMonitorManager; [NetDaemonApp] public sealed class ShowerMonitorInit { private readonly IShowerDetectionService _detectionService; private readonly IShowerMonitorEntityService _entityService; private readonly IExhaustFanControlService _fanControlService; private readonly IHaContext _haContext; private readonly ILogger _logger; private readonly ShowerMonitorOptions _options; private readonly IScheduler _scheduler; private readonly TimeProvider _timeProvider; private volatile bool _cleanedUp; public ShowerMonitorInit( IHaContext haContext, ILogger logger, IScheduler scheduler, IShowerDetectionService detectionService, IExhaustFanControlService fanControlService, IShowerMonitorEntityService entityService, IOptions options, TimeProvider timeProvider) { _haContext = haContext; _logger = logger; _scheduler = scheduler; _detectionService = detectionService; _fanControlService = fanControlService; _entityService = entityService; _options = options.Value; _timeProvider = timeProvider; _ = InitializeAndScheduleAsync(); } private async Task InitializeAndScheduleAsync() { try { await InitializeAsync(); SchedulePeriodicPolling(); ScheduleMidnightReset(); SubscribeToCleanupButton(); } catch (Exception ex) { _logger.LogError(ex, "Error during ShowerMonitor initialization and scheduling"); } } private async Task InitializeAsync() { try { await Task.Delay(TimeSpan.FromSeconds(3)); if (_options.CleanupEntitiesOnStartup) await _entityService.CleanupEntitiesAsync(); await _entityService.CreateEntitiesAsync(); await Task.Delay(TimeSpan.FromSeconds(2)); await PollAndUpdateAsync(); _logger.LogInformation("ShowerMonitor initialized"); } catch (Exception ex) { _logger.LogError(ex, "Error initializing ShowerMonitor"); throw; } } private void SchedulePeriodicPolling() { var pollInterval = TimeSpan.FromSeconds(_options.PollIntervalSeconds); 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, () => _ = PollAndUpdateAsync()); } private void ScheduleMidnightReset() { _scheduler.ScheduleCron("0 0 * * *", () => { try { _logger.LogDebug("Midnight reset: clearing shower session counters"); _detectionService.ResetDailyCounters(); } catch (Exception ex) { _logger.LogError(ex, "Error during midnight reset"); } }); } private void SubscribeToCleanupButton() { var cleanupButton = new Entity(_haContext, CleanupButtonEntityId); cleanupButton.StateChanges() .Subscribe(_ => { _logger.LogDebug("Cleanup button pressed, removing all ShowerMonitor entities"); Task.Run(HandleCleanupAsync); }); } private async Task HandleCleanupAsync() { try { await _entityService.CleanupEntitiesAsync(); _cleanedUp = true; _detectionService.ResetDailyCounters(); _fanControlService.Reset(); _logger.LogDebug("ShowerMonitor cleanup complete"); } catch (Exception ex) { _logger.LogError(ex, "Error during ShowerMonitor cleanup"); } } private async Task PollAndUpdateAsync() { if (_cleanedUp) { _logger.LogDebug("ShowerMonitor is cleaned up, skipping poll"); return; } try { var bathroomHumidity = ReadSensorDouble(_options.BathroomHumidityEntityId); var mainHomeHumidity = ReadSensorDouble(_options.MainHomeHumidityEntityId); if (!bathroomHumidity.HasValue || !mainHomeHumidity.HasValue) { if (_logger.IsEnabled(LogLevel.Debug)) _logger.LogDebug("Humidity sensor data unavailable (bathroom={Bathroom}, home={Home})", bathroomHumidity, mainHomeHumidity); return; } var timestamp = _timeProvider.GetUtcNow(); var state = _detectionService.Evaluate(bathroomHumidity.Value, mainHomeHumidity.Value, timestamp); var differential = bathroomHumidity.Value - mainHomeHumidity.Value; _fanControlService.Evaluate(state, timestamp); var context = new ShowerMonitorUpdateContext { State = state, Differential = differential, HumidityRate = _detectionService.LastRate, TodaySessionCount = _detectionService.TodaySessionCount, LastCompletedSession = _detectionService.LastCompletedSession }; await _entityService.UpdateEntitiesAsync(context); if (_logger.IsEnabled(LogLevel.Debug)) _logger.LogDebug("Poll: bathroom={Bath}%, home={Home}%, diff={Diff}%, state={State}", bathroomHumidity.Value, mainHomeHumidity.Value, Math.Round(differential, 1), state); } catch (Exception ex) { _logger.LogError(ex, "Error during ShowerMonitor poll"); } } private double? ReadSensorDouble(string entityId) { var state = _haContext.GetState(entityId); if (state?.State is null or "unavailable" or "unknown") return null; return double.TryParse(state.State, CultureInfo.InvariantCulture, out var value) ? value : null; } }