using System.Reactive.Concurrency; using BatteryMonitor.Models; using BatteryMonitorManager.Interface; using BatteryMonitorManager.Models; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using NetDaemon.AppModel; using NetDaemon.Extensions.Scheduler; namespace BatteryMonitorManager; [NetDaemonApp] public sealed class BatteryMonitorInit { private readonly IBatterySensorDiscoveryService _discoveryService; private readonly ILogger _logger; private readonly IBatteryNotificationService _notificationService; private readonly BatteryMonitorOptions _options; private readonly IScheduler _scheduler; public BatteryMonitorInit( ILogger logger, IScheduler scheduler, IBatterySensorDiscoveryService discoveryService, IBatteryNotificationService notificationService, IOptions options) { _logger = logger; _scheduler = scheduler; _discoveryService = discoveryService; _notificationService = notificationService; _options = options.Value; _ = InitializeAndScheduleAsync(); } private async Task InitializeAndScheduleAsync() { try { await InitializeAsync(); ScheduleDailyCheck(); } catch (Exception ex) { _logger.LogError(ex, "Error during BatteryMonitor initialization and scheduling"); } } private async Task InitializeAsync() { try { await Task.Delay(TimeSpan.FromSeconds(3)); CheckAndNotify(); if (_logger.IsEnabled(LogLevel.Information)) _logger.LogInformation("BatteryMonitor initialized with threshold {Threshold}%", _options.BatteryThresholdPercent); } catch (Exception ex) { _logger.LogError(ex, "Error initializing BatteryMonitor"); throw; } } private void ScheduleDailyCheck() { _scheduler.ScheduleCron(BatteryMonitorConsts.DailyCheckCron, () => { try { _logger.LogInformation("Running scheduled daily battery check"); CheckAndNotify(); } catch (Exception ex) { _logger.LogError(ex, "Error during scheduled battery check"); } }); _logger.LogInformation("Scheduled daily battery check at 08:00"); } private void CheckAndNotify() { var lowBatteryDevices = _discoveryService.DiscoverLowBatterySensors(_options.BatteryThresholdPercent); if (lowBatteryDevices.Count > 0) { _notificationService.NotifyLowBattery(lowBatteryDevices); } else { _notificationService.DismissNotification(); _logger.LogDebug("No low battery devices found"); } } }