using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using NetDaemon.AppModel; using NetDaemon.HassModel; using NetDaemon.HassModel.Entities; using LightMonitor.Models; using LightMonitorManager.Interface; using LightMonitorManager.Models; namespace LightMonitorManager; [NetDaemonApp] public sealed class LightMonitorInit : ILightMonitorInit { private readonly IHaContext _haContext; private readonly ILogger _logger; private readonly IPresenceService _presenceService; private readonly ILightControlService _lightControlService; private readonly LightMonitorOptions _options; public LightMonitorInit( IHaContext haContext, ILogger logger, IPresenceService presenceService, ILightControlService lightControlService, IOptions options) { _haContext = haContext; _logger = logger; _presenceService = presenceService; _lightControlService = lightControlService; _options = options.Value; _ = InitializeAsync(); } public Task InitializeAsync() { try { SubscribeToSunStateChanges(); SubscribeToPersonStateChanges(); _logger.LogInformation("LightMonitor initialized with {PersonCount} tracked persons", _options.PersonEntityIds.Length); } catch (Exception ex) { _logger.LogError(ex, "Error during LightMonitor initialization"); } return Task.CompletedTask; } private void SubscribeToSunStateChanges() { var sunEntity = new Entity(_haContext, _options.SunEntityId); sunEntity.StateChanges() .Subscribe(e => { try { if (!string.Equals(e.New?.State, LightMonitorConsts.SunBelowHorizon, StringComparison.OrdinalIgnoreCase)) { return; } if (IsRecoveryTransition(e.Old?.State)) { _logger.LogInformation("Sun state recovered from {OldState}, ignoring", e.Old?.State); return; } _logger.LogInformation("Sun went below horizon, checking if anyone is home"); if (_presenceService.IsAnyoneHome()) { _lightControlService.TurnOnLight(); } } catch (Exception ex) { _logger.LogError(ex, "Error handling sun state change"); } }); } private void SubscribeToPersonStateChanges() { foreach (var personEntityId in _options.PersonEntityIds) { var personEntity = new Entity(_haContext, personEntityId); personEntity.StateChanges() .Subscribe(e => { try { if (!string.Equals(e.New?.State, LightMonitorConsts.PersonHomeState, StringComparison.OrdinalIgnoreCase)) { return; } if (IsRecoveryTransition(e.Old?.State)) { _logger.LogInformation("Person {EntityId} state recovered from {OldState}, ignoring", personEntityId, e.Old?.State); return; } _logger.LogInformation("Person {EntityId} arrived home, checking if it is dark", personEntityId); _lightControlService.TurnOnLight(); } catch (Exception ex) { _logger.LogError(ex, "Error handling person state change for {EntityId}", personEntityId); } }); } } private static bool IsRecoveryTransition(string? oldState) => oldState is null or LightMonitorConsts.UnavailableState or LightMonitorConsts.UnknownState; }