#region using System.Globalization; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using NetDaemon.AppModel; using NetDaemon.HassModel; using NetDaemon.HassModel.Entities; using NordPool.Models; using PowerMonitor.Models; using PowerMonitorManager.Interface; using PowerMonitorManager.Models; using PowerMonitorManager.Models.Consts; #endregion namespace PowerMonitorManager; [NetDaemonApp] public sealed class PowerMonitorInit { private readonly IOtherPowerCalculationService _calculationService; private readonly IPowerCostCalculationService _costService; private readonly IPowerSensorDiscoveryService _discoveryService; private readonly IPowerLimitEnforcementService _enforcementService; private readonly IPowerMonitorEntityService _entityService; private readonly IHaContext _haContext; private readonly ILogger _logger; private readonly IPowerNotificationService _notificationService; private readonly PowerMonitorOptions _options; private readonly TimeProvider _timeProvider; private DateTimeOffset? _anomalyStartTime; private bool _highPowerNotificationActive; private DateTimeOffset? _lastPollTimestamp; private int _mainMeterConsecutiveFailures; public PowerMonitorInit( IHaContext haContext, ILogger logger, IOptions options, IPowerSensorDiscoveryService discoveryService, IOtherPowerCalculationService calculationService, IPowerCostCalculationService costService, IPowerMonitorEntityService entityService, IPowerNotificationService notificationService, IPowerLimitEnforcementService enforcementService, TimeProvider timeProvider) { _haContext = haContext; _logger = logger; _options = options.Value; _discoveryService = discoveryService; _calculationService = calculationService; _costService = costService; _entityService = entityService; _notificationService = notificationService; _enforcementService = enforcementService; _timeProvider = timeProvider; _ = InitializeAndScheduleAsync(); } private async Task InitializeAndScheduleAsync() { try { if (_options.Enabled) { await InitializeAsync(); SubscribeToMainMeterChanges(); SubscribeToRediscoverButton(); SubscribeToLimitBreachDebugButton(); } else { await CleanupEntitiesAsync(); var sensoresToRemove = GetPowerSensorEntitiesNames(); await _entityService.RemoveDeviceEntitiesAsync([.. sensoresToRemove.Select(s => s.DeviceName)]); await _entityService.RemoveSystemEntitiesAsync(); } } catch (Exception ex) { _logger.LogError(ex, "Error during PowerMonitor initialization"); } } private async Task InitializeAsync() { try { await Task.Delay(TimeSpan.FromSeconds(3)); await _entityService.CreateSystemEntitiesAsync(); await _entityService.ResetEntitiesAsync(); await Task.Delay(TimeSpan.FromSeconds(5)); var sensors = GetPowerSensorEntitiesNames(); await _entityService.CreateDeviceEntitiesAsync(sensors); if (_logger.IsEnabled(LogLevel.Information)) { _logger.LogInformation("PowerMonitor initialized with {SensorCount} tracked sensors", sensors.Count); } await PollAndUpdateAsync(); } catch (Exception ex) { _logger.LogError(ex, "Error initializing PowerMonitor"); throw; } } private IReadOnlyList GetPowerSensorEntitiesNames() { var sensors = _discoveryService.DiscoverDeviceSensors(); return sensors; } private async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default) { await _entityService.RemoveSystemEntitiesAsync(cancellationToken); } private void SubscribeToMainMeterChanges() { if (string.IsNullOrWhiteSpace(_options.MainMeterEntityId)) { _logger.LogWarning("MainMeterEntityId not configured, PowerMonitor will not react to power changes"); return; } var meter = new Entity(_haContext, _options.MainMeterEntityId); meter.StateChanges() .Subscribe(e => { if (e.Old?.State == e.New?.State) { return; } _ = PollAndUpdateAsync(); }); if (_logger.IsEnabled(LogLevel.Information)) { _logger.LogInformation("PowerMonitor subscribed to state changes of {MeterId}", _options.MainMeterEntityId); } } private void SubscribeToRediscoverButton() { var button = new Entity(_haContext, "button.powermonitor_rediscover_sensors"); button.StateChanges() .Subscribe(change => { _logger.LogInformation("Re-discovery button pressed, scanning for power sensors"); _ = HandleRediscoveryAsync(); }); } private void SubscribeToLimitBreachDebugButton() { var button = new Entity(_haContext, "button.powermonitor_trigger_limit_breach"); button.StateChanges() .Subscribe(_ => { if (_enforcementService.IsLimitActive) { _logger.LogInformation("Limit breach debug button pressed while active, resetting breach"); _enforcementService.ResetLimitBreach(); } else { _logger.LogInformation("Limit breach debug button pressed, triggering fake breach"); _enforcementService.TriggerLimitBreach(); } }); } private async Task HandleRediscoveryAsync() { try { var previousSensors = _discoveryService.CurrentDeviceSensors; var newSensors = _discoveryService.DiscoverDeviceSensors(); var previousIds = previousSensors.Select(s => s.DeviceName).ToHashSet(); var currentIds = newSensors.Select(s => s.DeviceName).ToHashSet(); var added = newSensors.Where(s => !previousIds.Contains(s.DeviceName)).ToList(); var removed = previousSensors.Where(s => !currentIds.Contains(s.DeviceName)).ToList(); if (added.Count > 0) { await _entityService.CreateDeviceEntitiesAsync(added); if (_logger.IsEnabled(LogLevel.Information)) { _logger.LogInformation("Created entities for {Count} new sensors", added.Count); } } if (removed.Count > 0) { await RemoreDevicePriceEntities(removed); } if (_logger.IsEnabled(LogLevel.Information)) { _logger.LogInformation("Re-discovery complete: {Total} sensors ({Added} added, {Removed} removed)", newSensors.Count, added.Count, removed.Count); } } catch (Exception ex) { _logger.LogError(ex, "Error during sensor re-discovery"); } } private async Task RemoreDevicePriceEntities(List removed) { var removedNames = removed.Select(s => s.DeviceName).ToList(); await _entityService.RemoveDeviceEntitiesAsync(removedNames); if (_logger.IsEnabled(LogLevel.Information)) { _logger.LogInformation("Removed entities for {Count} sensors", removed.Count); } } private async Task PollAndUpdateAsync() { try { var totalPower = ReadMainMeterPower(); if (totalPower is null) { _mainMeterConsecutiveFailures++; _logger.LogWarning("Main meter unavailable ({Failures}/{Max})", _mainMeterConsecutiveFailures, PowerMonitorConsts.MainMeterMaxConsecutiveFailures); return; } _mainMeterConsecutiveFailures = 0; var (deviceReadings, degradedSensors) = ReadDeviceSensors(); var calculation = _calculationService.Calculate(totalPower.Value, deviceReadings); var nordPoolPrice = ReadNordPoolPrice(); var priceSource = nordPoolPrice > 0 ? "live" : _costService.PriceSource; var effectivePrice = nordPoolPrice > 0 ? nordPoolPrice : _costService.LastKnownPrice; var now = _timeProvider.GetLocalNow(); var elapsedSeconds = _lastPollTimestamp.HasValue ? Math.Min((now - _lastPollTimestamp.Value).TotalSeconds, _options.PollIntervalSeconds * 10) : _options.PollIntervalSeconds; _lastPollTimestamp = now; _costService.RecordCosts(calculation, nordPoolPrice, (int)Math.Max(1, elapsedSeconds), now.LocalDateTime); var isAnomaly = calculation.SmoothedOtherPowerWatts > _options.AnomalyThresholdWatts; _anomalyStartTime = isAnomaly switch { true when _anomalyStartTime is null => now, false => null, _ => _anomalyStartTime }; var anomalyDuration = _anomalyStartTime.HasValue ? now - _anomalyStartTime.Value : TimeSpan.Zero; var systemStatus = _mainMeterConsecutiveFailures >= PowerMonitorConsts.MainMeterMaxConsecutiveFailures ? "warning" : "ok"; var context = new PowerUpdateContext { Calculation = calculation, CurrentNordPoolPrice = effectivePrice, PriceUnit = "EUR/kWh", PriceSource = priceSource, DeviceCosts = _costService.GetAllDeviceCostSnapshots(), TotalCost = _costService.GetTotalCostSnapshot(), OtherCost = _costService.GetOtherCostSnapshot(), IsAnomaly = isAnomaly, AnomalyDuration = anomalyDuration, AnomalyThresholdWatts = _options.AnomalyThresholdWatts, TrackedSensorCount = _discoveryService.CurrentDeviceSensors.Count, DegradedSensors = degradedSensors, SystemStatus = systemStatus }; await _entityService.UpdateEntitiesAsync(context); EvaluateHighPowerNotification(calculation.TotalPowerWatts); _enforcementService.EnforceLimit(calculation.TotalPowerWatts); if (_logger.IsEnabled(LogLevel.Debug)) { _logger.LogDebug( "Poll complete: total={Total}W, other={Other}W (smoothed), devices={Devices}, price={Price}", calculation.TotalPowerWatts, calculation.SmoothedOtherPowerWatts, deviceReadings.Count, effectivePrice); } } catch (Exception ex) { _logger.LogError(ex, "Error during PowerMonitor poll and update"); } } private double ReadNordPoolPrice() { var state = _haContext.GetState(NordPoolConsts.CurrentPriceEntityId); if (state?.State is null or "unavailable" or "unknown") { _logger.LogDebug("NordPool price entity unavailable, using last known price"); return 0; } if (double.TryParse(state.State, CultureInfo.InvariantCulture, out var price) && price > 0) { return price; } if (_logger.IsEnabled(LogLevel.Debug)) { _logger.LogDebug("NordPool price entity returned non-positive value: {State}", state.State); } return 0; } private void EvaluateHighPowerNotification(double totalPowerWatts) { var isAboveThreshold = totalPowerWatts > _options.HighPowerThresholdWatts; switch (isAboveThreshold, _highPowerNotificationActive) { case (true, false): _notificationService.NotifyHighPowerUsage(totalPowerWatts, _options.HighPowerThresholdWatts); _highPowerNotificationActive = true; break; case (false, true): _notificationService.DismissHighPowerNotification(); _highPowerNotificationActive = false; break; } } private double? ReadMainMeterPower() { var state = _haContext.GetState(_options.MainMeterEntityId); if (state?.State is null or "unavailable" or "unknown") { return null; } return double.TryParse(state.State, CultureInfo.InvariantCulture, out var value) ? value : null; } private (IReadOnlyDictionary readings, List degraded) ReadDeviceSensors() { var readings = new Dictionary(); var degraded = new List(); foreach (var sensor in _discoveryService.CurrentDeviceSensors) { var state = _haContext.GetState(sensor.EntityId); if (state?.State is null or "unavailable" or "unknown") { readings[sensor.EntityId] = 0; degraded.Add(sensor.EntityId); continue; } if (double.TryParse(state.State, CultureInfo.InvariantCulture, out var value)) { var powerWatts = string.Equals(sensor.UnitOfMeasurement, PowerMonitorConsts.KilowattUnit, StringComparison.OrdinalIgnoreCase) ? value * PowerMonitorConsts.WattsPerKilowatt : value; readings[sensor.EntityId] = powerWatts; } else { readings[sensor.EntityId] = 0; degraded.Add(sensor.EntityId); } } return (readings, degraded); } }