using System.Globalization; using System.Reactive.Concurrency; using System.Text.Json; using BoilerMonitor.Models.Enums; using BoilerMonitorManager.Interface; using BoilerMonitorManager.Models; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using NetDaemon.AppModel; using NetDaemon.Extensions.MqttEntityManager; using NetDaemon.Extensions.Scheduler; using NetDaemon.HassModel; using NetDaemon.HassModel.Entities; using static BoilerMonitor.Models.BoilerMonitorConsts; namespace BoilerMonitorManager; [NetDaemonApp] public sealed class BoilerMonitorInit { private readonly ILogger _logger; private readonly IHaContext _haContext; private readonly IScheduler _scheduler; private readonly IMqttEntityManager _mqttEntityManager; private readonly IBoilerControlService _boilerControlService; private readonly IBoilerRunTimeTracker _tracker; private readonly IBoilerMonitorEntityService _entityService; private readonly IWaterReadyService _waterReadyService; private readonly BoilerMonitorOptions _options; private readonly TimeProvider _timeProvider; private bool _lastWaterReady; private volatile bool _cleanedUp; private DateTimeOffset? _lastWaterReadyNotificationSentAt; public BoilerMonitorInit( IHaContext haContext, ILogger logger, IScheduler scheduler, IMqttEntityManager mqttEntityManager, IBoilerControlService boilerControlService, IBoilerRunTimeTracker tracker, IBoilerMonitorEntityService entityService, IWaterReadyService waterReadyService, IOptions options, TimeProvider timeProvider) : this( haContext, logger, scheduler, mqttEntityManager, boilerControlService, tracker, entityService, waterReadyService, options, timeProvider, startBackgroundScheduling: true) { } internal BoilerMonitorInit( IHaContext haContext, ILogger logger, IScheduler scheduler, IMqttEntityManager mqttEntityManager, IBoilerControlService boilerControlService, IBoilerRunTimeTracker tracker, IBoilerMonitorEntityService entityService, IWaterReadyService waterReadyService, IOptions options, TimeProvider timeProvider, bool startBackgroundScheduling) { _haContext = haContext; _logger = logger; _scheduler = scheduler; _mqttEntityManager = mqttEntityManager; _boilerControlService = boilerControlService; _tracker = tracker; _entityService = entityService; _waterReadyService = waterReadyService; _options = options.Value; _timeProvider = timeProvider; if (startBackgroundScheduling) { _ = InitializeAndScheduleAsync(); } } private async Task InitializeAndScheduleAsync() { try { await InitializeAsync(); await SubscribeToConfigCommandsAsync(); await SubscribeToSwitchCommandsAsync(); SchedulePeriodicPolling(); ScheduleMidnightReset(); ScheduleEndOfDayReminder(); SubscribeToSkipPriceCapChanges(); SubscribeToAutoManagementChanges(); SubscribeToShowerState(); SubscribeToCleanupButton(); } catch (Exception ex) { _logger.LogError(ex, "Error during BoilerMonitor initialization and scheduling"); } } private async Task InitializeAsync() { try { await Task.Delay(TimeSpan.FromSeconds(3)); if (_options.CleanupEntitiesOnStartup) { await _entityService.CleanupEntitiesAsync(); await _entityService.CreateEntitiesAsync(); await _entityService.ResetEntitiesAsync(); } else { var persisted = _entityService.ReadPersistedState(); var persistedCooldown = _entityService.ReadPersistedCooldownTimestamp(); await _entityService.CreateEntitiesAsync(); if (persisted is not null) { _tracker.RestoreFromSnapshot(); if (persistedCooldown.HasValue) { _waterReadyService.RestoreCooldownState(persistedCooldown.Value); } await _entityService.ResetTransientEntitiesAsync(); if (_logger.IsEnabled(LogLevel.Information)) { _logger.LogInformation("BoilerMonitor state restored from HA entities: runtime={Runtime}, sessions={Sessions}", persisted.AccumulatedRunTime, persisted.SessionCount); } } else { await _entityService.ResetEntitiesAsync(); _logger.LogInformation("No persisted state found in HA entities, performing full entity reset"); } } await Task.Delay(TimeSpan.FromSeconds(5)); await PollAndUpdateAsync(); _logger.LogInformation("BoilerMonitor initialized"); } catch (Exception ex) { _logger.LogError(ex, "Error initializing BoilerMonitor"); throw; } } private void SchedulePeriodicPolling() { var now = DateTime.Now; var currentSecondInInterval = (now.Minute * 60 + now.Second) % DefaultPollIntervalSeconds; var secondsUntilNext = DefaultPollIntervalSeconds - currentSecondInInterval; var delayUntilNext = TimeSpan.FromSeconds(secondsUntilNext); var nextPollTime = now.Add(delayUntilNext); if (_logger.IsEnabled(LogLevel.Information)) { _logger.LogInformation("Scheduling BoilerMonitor polling every {Interval}s, first at {Time}", DefaultPollIntervalSeconds, nextPollTime); } _scheduler.RunEvery(TimeSpan.FromSeconds(DefaultPollIntervalSeconds), nextPollTime, () => _ = PollAndUpdateAsync()); } private void ScheduleMidnightReset() { _scheduler.ScheduleCron("0 0 * * *", () => { try { _logger.LogInformation("Midnight reset: clearing boiler run time tracker and water ready cooldown"); _tracker.Reset(); _waterReadyService.ResetCooldown(); _lastWaterReadyNotificationSentAt = null; _ = _entityService.ResetEntitiesAsync(); } catch (Exception ex) { _logger.LogError(ex, "Error during midnight reset"); } }); } private void ScheduleEndOfDayReminder() { _scheduler.ScheduleCron("0 22 * * *", () => { try { var switchState = _haContext.GetState(SkipPriceCapEntityId); if (!string.Equals(switchState?.State, SwitchOnState, StringComparison.OrdinalIgnoreCase)) { return; } _haContext.CallService("notify", "mobile_app_marius_phone", null, new { message = "Remember to turn off 'Skip price cap, heat until ready' if you're done heating.", title = "Boiler reminder" }); _logger.LogInformation("End-of-day reminder sent: skip price cap switch is still ON"); } catch (Exception ex) { _logger.LogError(ex, "Error checking skip price cap reminder"); } }); } private void SubscribeToSkipPriceCapChanges() { var skipPriceCapSwitch = new Entity(_haContext, SkipPriceCapEntityId); skipPriceCapSwitch.StateChanges() .Subscribe(e => { if (e.Old?.State == e.New?.State) { return; } _logger.LogInformation("Skip price cap switch changed, triggering poll"); _ = PollAndUpdateAsync(); }); } private void SubscribeToAutoManagementChanges() { var autoManagementSwitch = new Entity(_haContext, AutoManagementEntityId); autoManagementSwitch.StateChanges() .Subscribe(e => { if (e.Old?.State == e.New?.State) { return; } _logger.LogInformation("Automatic boiler control switch changed, triggering poll"); _ = PollAndUpdateAsync(); }); } private void SubscribeToShowerState() { var showerStateSensor = new Entity(_haContext, ShowerStateEntityId); showerStateSensor.StateChanges() .Subscribe(e => { if (!string.Equals(e.New?.State, ShowerActiveState, StringComparison.OrdinalIgnoreCase)) { return; } if (!_waterReadyService.IsInCooldown) { return; } _logger.LogInformation("Shower detected as active, resetting water ready cooldown"); _waterReadyService.ResetCooldown(); }); } private void SubscribeToCleanupButton() { var cleanupButton = new Entity(_haContext, CleanupButtonEntityId); cleanupButton.StateChanges() .Subscribe(_ => { _logger.LogInformation("Cleanup button pressed, removing all BoilerMonitor entities"); Task.Run(HandleCleanupAsync); }); } private async Task SubscribeToConfigCommandsAsync() { var configEntityIds = new[] { ConfigPowerEntityId, ConfigSwitchEntityId, ConfigPollIntervalEntityId, ConfigHeatingThresholdEntityId }; foreach (var entityId in configEntityIds) { var subscription = await _mqttEntityManager.PrepareCommandSubscriptionAsync(entityId).ConfigureAwait(false); subscription.Subscribe(state => _ = HandleConfigCommandAsync(entityId, state)); } } private async Task HandleConfigCommandAsync(string entityId, string? state) { try { if (_logger.IsEnabled(LogLevel.Information)) { _logger.LogInformation("Config entity {EntityId} received command: {Value}", entityId, state); } await _mqttEntityManager.SetStateAsync(entityId, state ?? string.Empty).ConfigureAwait(false); } catch (Exception e) { _logger.LogError(e, "Error handling command for entity {EntityId}", entityId); } } private async Task SubscribeToSwitchCommandsAsync() { var switchEntityIds = new[] { SkipPriceCapEntityId, BudgetOverrideEntityId, AutoManagementEntityId }; foreach (var entityId in switchEntityIds) { var subscription = await _mqttEntityManager.PrepareCommandSubscriptionAsync(entityId).ConfigureAwait(false); subscription.Subscribe(state => _ = HandleSwitchCommandAsync(entityId, state)); } } private async Task HandleSwitchCommandAsync(string entityId, string? state) { try { if (_logger.IsEnabled(LogLevel.Information)) { _logger.LogInformation("Switch {EntityId} received command: {Value}", entityId, state); } await _mqttEntityManager.SetStateAsync(entityId, state ?? string.Empty).ConfigureAwait(false); } catch (Exception e) { _logger.LogError(e, "Error handling command for switch entity {EntityId}", entityId); } } private async Task HandleCleanupAsync() { try { await _entityService.CleanupEntitiesAsync(); _cleanedUp = true; _tracker.Reset(); _logger.LogInformation("BoilerMonitor cleanup complete. Entities removed, monitoring stopped"); } catch (Exception ex) { _logger.LogError(ex, "Error during BoilerMonitor cleanup"); } } private async Task PollAndUpdateAsync() { if (_cleanedUp) { _logger.LogDebug("BoilerMonitor is cleaned up, skipping poll"); return; } try { var config = ReadConfigFromHaEntities(); if (!config.IsFullyConfigured) { await _entityService.SetStatusAsync(StatusAwaitingConfiguration); _logger.LogWarning("BoilerMonitor not fully configured (power={Power}, switch={Switch}, interval={Interval}, threshold={Threshold}). Awaiting configuration", config.BoilerPowerEntityId, config.BoilerSwitchEntityId, config.PollIntervalSeconds, config.HeatingPowerThresholdWatts); return; } var boilerPowerWatts = ReadSensorDouble(config.BoilerPowerEntityId!); var boilerSwitchState = _haContext.GetState(config.BoilerSwitchEntityId!)?.State; var isHeating = boilerPowerWatts.HasValue && boilerPowerWatts.Value >= config.HeatingPowerThresholdWatts!.Value; _tracker.RecordPollResult(); if (isHeating) { _waterReadyService.RecordHeatingObserved(); } var cheapestIntervalsState = _haContext.GetState(NordPoolCheapestIntervalsEntityId); var isNowCheap = ReadAttributeBool(cheapestIntervalsState, "is_now_cheap"); var budgetOverrideState = _haContext.GetState(BudgetOverrideEntityId)?.State; var budgetOverride = string.Equals(budgetOverrideState, SwitchOnState, StringComparison.OrdinalIgnoreCase); var skipPriceCapState = _haContext.GetState(SkipPriceCapEntityId)?.State; var skipPriceCap = string.Equals(skipPriceCapState, SwitchOnState, StringComparison.OrdinalIgnoreCase); var dailyHours = ReadSensorDouble(BoilerDailyHoursEntityId) ?? 1.0; var waterReady = _waterReadyService.IsWaterReady(boilerSwitchState, boilerPowerWatts, config.HeatingPowerThresholdWatts!.Value); if (!_lastWaterReady && waterReady && !IsWithinNotificationCooldown()) { _haContext.CallService("notify", "mobile_app_marius_phone", null, new { message = "Hot water is ready.", title = "Boiler" }); _lastWaterReadyNotificationSentAt = _timeProvider.GetUtcNow(); _logger.LogInformation("Water ready notification sent"); } _lastWaterReady = waterReady; var snapshot = _tracker.GetSnapshot(); var budgetTimeSpan = TimeSpan.FromHours(dailyHours); var remainingTime = budgetTimeSpan - snapshot.AccumulatedRunTime; if (remainingTime < TimeSpan.Zero) { remainingTime = TimeSpan.Zero; } var budgetPercentage = budgetTimeSpan.TotalSeconds > 0 ? snapshot.AccumulatedRunTime.TotalSeconds / budgetTimeSpan.TotalSeconds * 100.0 : 0.0; var budgetExhausted = snapshot.AccumulatedRunTime >= budgetTimeSpan; var effectiveIsNowCheap = isNowCheap || skipPriceCap; var boilerAction = _boilerControlService.DetermineAction( effectiveIsNowCheap, waterReady, boilerSwitchState, budgetExhausted, budgetOverride); var autoManagementState = _haContext.GetState(AutoManagementEntityId)?.State; var autoManagementEnabled = !string.Equals(autoManagementState, SwitchOffState, StringComparison.OrdinalIgnoreCase); if (autoManagementEnabled) { ExecuteBoilerAction(boilerAction, config.BoilerSwitchEntityId!); } else if (boilerAction is not BoilerAction.NoChange) { if (_logger.IsEnabled(LogLevel.Information)) { _logger.LogInformation( "Automatic boiler control is off; skipping boiler switch service call (would have been {Action})", boilerAction); } } var context = new BoilerMonitorUpdateContext { TodayRunTime = snapshot.AccumulatedRunTime, RemainingTime = remainingTime, BudgetPercentage = budgetPercentage, BudgetExhausted = budgetExhausted, SessionCount = snapshot.SessionCount, BudgetHours = dailyHours, WaterReady = waterReady, BoilerSwitchState = boilerSwitchState, BoilerPowerWatts = boilerPowerWatts, CooldownSince = _waterReadyService.WaterReadySince, }; await _entityService.UpdateEntitiesAsync(context); if (_logger.IsEnabled(LogLevel.Debug)) { _logger.LogDebug("Poll complete: power={Power}W, heating={Heating}, runtime={Runtime}, budget={Budget}%", boilerPowerWatts, isHeating, snapshot.AccumulatedRunTime, budgetPercentage); } } catch (Exception ex) { _logger.LogError(ex, "Error during BoilerMonitor poll and update"); } } private void ExecuteBoilerAction(BoilerAction action, string switchEntityId) { switch (action) { case BoilerAction.TurnOn: _haContext.CallService("switch", "turn_on", ServiceTarget.FromEntity(switchEntityId)); _waterReadyService.NotifyTurnedOn(); break; case BoilerAction.TurnOff: _haContext.CallService("switch", "turn_off", ServiceTarget.FromEntity(switchEntityId)); break; case BoilerAction.NoChange: break; default: throw new ArgumentOutOfRangeException(nameof(action), action, null); } } private BoilerMonitorConfig ReadConfigFromHaEntities() { var powerEntityId = _haContext.GetState(ConfigPowerEntityId)?.State; var switchEntityId = _haContext.GetState(ConfigSwitchEntityId)?.State; int? pollInterval = null; var pollIntervalState = _haContext.GetState(ConfigPollIntervalEntityId)?.State; if (!string.IsNullOrWhiteSpace(pollIntervalState) && double.TryParse(pollIntervalState, CultureInfo.InvariantCulture, out var pollIntervalValue) && pollIntervalValue > 0) { pollInterval = (int)pollIntervalValue; } double? heatingThreshold = null; var thresholdState = _haContext.GetState(ConfigHeatingThresholdEntityId)?.State; if (!string.IsNullOrWhiteSpace(thresholdState) && double.TryParse(thresholdState, CultureInfo.InvariantCulture, out var thresholdValue) && thresholdValue > 0) { heatingThreshold = thresholdValue; } return new BoilerMonitorConfig { BoilerPowerEntityId = string.IsNullOrWhiteSpace(powerEntityId) ? null : powerEntityId.Trim(), BoilerSwitchEntityId = string.IsNullOrWhiteSpace(switchEntityId) ? null : switchEntityId.Trim(), PollIntervalSeconds = pollInterval, HeatingPowerThresholdWatts = heatingThreshold }; } 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; } private static bool ReadAttributeBool(EntityState? entityState, string attributeName) { if (entityState?.Attributes is not IDictionary attributes) { return false; } try { if (attributes.TryGetValue(attributeName, out var value)) { return value switch { bool b => b, string s => bool.TryParse(s, out var parsed) && parsed, JsonElement { ValueKind: JsonValueKind.True } => true, JsonElement { ValueKind: JsonValueKind.False } => false, JsonElement jsonElement when jsonElement.ValueKind == JsonValueKind.String => bool.TryParse(jsonElement.GetString(), out var jsonParsed) && jsonParsed, _ => false }; } } catch { // Attribute not found or not parseable } return false; } private bool IsWithinNotificationCooldown() { if (_lastWaterReadyNotificationSentAt is null) { return false; } var elapsed = _timeProvider.GetUtcNow() - _lastWaterReadyNotificationSentAt.Value; return elapsed < WaterReadyNotificationCooldown; } private static DateTime? ReadAttributeDateTime(EntityState? entityState, string attributeName) { if (entityState?.Attributes is null) { return null; } try { if (entityState.Attributes is IDictionary attributes && attributes.TryGetValue(attributeName, out var value)) { var stringValue = value switch { string s => s, JsonElement { ValueKind: JsonValueKind.String } jsonElement => jsonElement.GetString(), _ => null }; if (stringValue is not null && DateTime.TryParse(stringValue, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var parsed)) { return parsed; } } } catch { // Attribute not found or not parseable } return null; } }