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 ShowerMonitor.Models.Enums; using ShowerMonitorManager.Interface; using ShowerMonitorManager.Models; using static ShowerMonitor.Models.ShowerMonitorConsts; namespace ShowerMonitorManager; [NetDaemonApp] public sealed class ShowerMonitorInit : IShowerMonitorInit { private readonly ILogger _logger; 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; private bool _cleanedUp; public ShowerMonitorInit( IHaContext haContext, ILogger logger, IScheduler scheduler, IShowerDetectionService detectionService, IHumidityRateCalculator rateCalculator, IExhaustFanControlService fanControlService, IShowerMonitorEntityService entityService, IOptions options) { _haContext = haContext; _logger = logger; _scheduler = scheduler; _detectionService = detectionService; _rateCalculator = rateCalculator; _fanControlService = fanControlService; _entityService = entityService; _options = options.Value; _ = InitializeAndScheduleAsync(); } private async Task InitializeAndScheduleAsync() { try { await InitializeAsync(); SchedulePeriodicPolling(); ScheduleMidnightReset(); SubscribeToCleanupButton(); } catch (Exception ex) { _logger.LogError(ex, "Error during ShowerMonitor initialization and scheduling"); } } public 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; } } public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default) { await _entityService.CleanupEntitiesAsync(cancellationToken); } private void SchedulePeriodicPolling() { var pollInterval = TimeSpan.FromSeconds(_options.PollIntervalSeconds); var now = DateTime.Now; 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"); } }); } 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(_haContext); _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) { _logger.LogDebug("Humidity sensor data unavailable (bathroom={Bathroom}, home={Home})", bathroomHumidity, mainHomeHumidity); return; } var timestamp = DateTimeOffset.UtcNow; var state = _detectionService.Evaluate(bathroomHumidity.Value, mainHomeHumidity.Value, timestamp); var differential = bathroomHumidity.Value - mainHomeHumidity.Value; _fanControlService.Evaluate(state, timestamp, _haContext); var context = new ShowerMonitorUpdateContext { State = state, BathroomHumidity = bathroomHumidity.Value, MainHomeHumidity = mainHomeHumidity.Value, Differential = differential, HumidityRate = _rateCalculator.GetRatePerMinute(), TodaySessionCount = _detectionService.TodaySessionCount, LastCompletedSession = _detectionService.LastCompletedSession, CurrentSession = _detectionService.CurrentSession }; await _entityService.UpdateEntitiesAsync(context); _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; } }