using System.Globalization; using System.Reactive.Concurrency; 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 : IBoilerMonitorInit { 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 bool _lastWaterReady; private bool _cleanedUp; public BoilerMonitorInit( IHaContext haContext, ILogger logger, IScheduler scheduler, IMqttEntityManager mqttEntityManager, IBoilerControlService boilerControlService, IBoilerRunTimeTracker tracker, IBoilerMonitorEntityService entityService, IWaterReadyService waterReadyService, IOptions options) { _haContext = haContext; _logger = logger; _scheduler = scheduler; _mqttEntityManager = mqttEntityManager; _boilerControlService = boilerControlService; _tracker = tracker; _entityService = entityService; _waterReadyService = waterReadyService; _options = options.Value; _ = InitializeAndScheduleAsync(); } private async Task InitializeAndScheduleAsync() { try { await InitializeAsync(); await SubscribeToConfigCommandsAsync(); await SubscribeToSwitchCommandsAsync(); SchedulePeriodicPolling(); ScheduleMidnightReset(); ScheduleEndOfDayReminder(); SubscribeToSkipPriceCapChanges(); SubscribeToCleanupButton(); } catch (Exception ex) { _logger.LogError(ex, "Error during BoilerMonitor initialization and scheduling"); } } public 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(); await _entityService.CreateEntitiesAsync(); if (persisted is not null) { _tracker.RestoreFromSnapshot(persisted.AccumulatedRunTime, persisted.SessionCount); await _entityService.ResetTransientEntitiesAsync(); _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, 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; } } public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default) { await _entityService.CleanupEntitiesAsync(cancellationToken); } 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); _logger.LogInformation("Scheduling BoilerMonitor polling every {Interval}s, first at {Time}", DefaultPollIntervalSeconds, nextPollTime); _scheduler.RunEvery(TimeSpan.FromSeconds(DefaultPollIntervalSeconds), nextPollTime, async void () => { try { await PollAndUpdateAsync(); } catch (Exception ex) { _logger.LogError(ex, "Error during BoilerMonitor poll cycle"); } }); } 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(); _ = _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)) { _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 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(async void (state) => { try { _logger.LogInformation("Config entity {EntityId} received command: {Value}", entityId, state); await _mqttEntityManager.SetStateAsync(entityId, state).ConfigureAwait(false); } catch (Exception e) { _logger.LogError(e, "Error handling command for entity {EntityId}", entityId); } }); } } private async Task SubscribeToSwitchCommandsAsync() { var switchEntityIds = new[] { SkipPriceCapEntityId, BudgetOverrideEntityId }; foreach (var entityId in switchEntityIds) { var subscription = await _mqttEntityManager.PrepareCommandSubscriptionAsync(entityId).ConfigureAwait(false); subscription.Subscribe(async void (state) => { try { _logger.LogInformation("Switch {EntityId} received command: {Value}", entityId, state); await _mqttEntityManager.SetStateAsync(entityId, state).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; var pollInterval = TimeSpan.FromSeconds(config.PollIntervalSeconds!.Value); _tracker.RecordPollResult(isHeating, pollInterval); var cheapestIntervalsState = _haContext.GetState(NordPoolCheapestIntervalsEntityId); var isNowCheap = ReadAttributeBool(cheapestIntervalsState, "is_now_cheap"); var nextCheapInterval = ReadAttributeDateTime(cheapestIntervalsState, "next_cheap_interval"); 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) { _haContext.CallService("notify", "mobile_app_marius_phone", null, new { message = "Hot water is ready.", title = "Boiler" }); _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); ExecuteBoilerAction(boilerAction, config.BoilerSwitchEntityId!); var context = new BoilerMonitorUpdateContext { TodayRunTime = snapshot.AccumulatedRunTime, RemainingTime = remainingTime, BudgetPercentage = budgetPercentage, BudgetExhausted = budgetExhausted, SessionCount = snapshot.SessionCount, BudgetHours = dailyHours, IsCurrentlyHeating = isHeating, WaterReady = waterReady, BoilerSwitchState = boilerSwitchState, BoilerPowerWatts = boilerPowerWatts, IsNowCheap = effectiveIsNowCheap, NextCheapIntervalStart = nextCheapInterval }; await _entityService.UpdateEntitiesAsync(context); _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, BoilerSwitchEntityId = string.IsNullOrWhiteSpace(switchEntityId) ? null : switchEntityId, 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 null) { return false; } try { if (entityState.Attributes is IDictionary attributes && attributes.TryGetValue(attributeName, out var value)) { return value switch { bool b => b, string s => bool.TryParse(s, out var parsed) && parsed, _ => false }; } } catch { // Attribute not found or not parseable } return false; } 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)) { if (value is string s && DateTime.TryParse(s, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out var parsed)) { return parsed; } } } catch { // Attribute not found or not parseable } return null; } }