using System.Globalization; using System.Reactive.Concurrency; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using NetDaemon.AppModel; using NetDaemon.Extensions.Scheduler; using NetDaemon.HassModel; using NetDaemon.HassModel.Entities; using NordPool.Models; using PowerMonitorManager.Interface; using PowerMonitorManager.Models; using PowerMonitorManager.Models.Consts; namespace PowerMonitorManager; [NetDaemonApp] public sealed class PowerMonitorInit : IPowerMonitorInit { private readonly ILogger _logger; private readonly IHaContext _haContext; private readonly IScheduler _scheduler; private readonly PowerMonitorOptions _options; private readonly IPowerSensorDiscoveryService _discoveryService; private readonly IOtherPowerCalculationService _calculationService; private readonly IPowerCostCalculationService _costService; private readonly IPowerMonitorEntityService _entityService; private readonly IPowerNotificationService _notificationService; private readonly TimeProvider _timeProvider; private int _mainMeterConsecutiveFailures; private DateTimeOffset? _anomalyStartTime; private bool _highPowerNotificationActive; public PowerMonitorInit( IHaContext haContext, ILogger logger, IScheduler scheduler, IOptions options, IPowerSensorDiscoveryService discoveryService, IOtherPowerCalculationService calculationService, IPowerCostCalculationService costService, IPowerMonitorEntityService entityService, IPowerNotificationService notificationService, TimeProvider timeProvider) { _haContext = haContext; _logger = logger; _scheduler = scheduler; _options = options.Value; _discoveryService = discoveryService; _calculationService = calculationService; _costService = costService; _entityService = entityService; _notificationService = notificationService; _timeProvider = timeProvider; _ = InitializeAndScheduleAsync(); } private async Task InitializeAndScheduleAsync() { try { await InitializeAsync(); SchedulePeriodicPolling(); SubscribeToRediscoverButton(); } catch (Exception ex) { _logger.LogError(ex, "Error during PowerMonitor initialization"); } } public async Task InitializeAsync() { try { await Task.Delay(TimeSpan.FromSeconds(3)); await _entityService.CreateSystemEntitiesAsync(); await _entityService.ResetEntitiesAsync(); await Task.Delay(TimeSpan.FromSeconds(5)); var sensors = _discoveryService.DiscoverDeviceSensors(); await _entityService.CreateDeviceEntitiesAsync(sensors); _logger.LogInformation("PowerMonitor initialized with {SensorCount} tracked sensors", sensors.Count); await PollAndUpdateAsync(); } catch (Exception ex) { _logger.LogError(ex, "Error initializing PowerMonitor"); throw; } } public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default) { await _entityService.CleanupEntitiesAsync(cancellationToken); } private void SchedulePeriodicPolling() { var now = _timeProvider.GetLocalNow(); var intervalSeconds = _options.PollIntervalSeconds; var currentSecondInInterval = (now.Minute * 60 + now.Second) % intervalSeconds; var secondsUntilNext = intervalSeconds - currentSecondInInterval; var delayUntilNext = TimeSpan.FromSeconds(secondsUntilNext); var nextPollTime = now.Add(delayUntilNext); _logger.LogInformation( "Scheduling PowerMonitor polling every {Interval}s, first at {Time}", intervalSeconds, nextPollTime); _scheduler.RunEvery(TimeSpan.FromSeconds(intervalSeconds), nextPollTime, () => _ = PollAndUpdateAsync()); } 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 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); _logger.LogInformation("Created entities for {Count} new sensors", added.Count); } if (removed.Count > 0) { var removedNames = removed.Select(s => s.DeviceName).ToList(); await _entityService.CleanupDeviceEntitiesAsync(removedNames); _logger.LogInformation("Removed entities for {Count} sensors", removed.Count); } _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 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(); _costService.RecordCosts(calculation, nordPoolPrice, _options.PollIntervalSeconds, now.LocalDateTime); var isAnomaly = calculation.SmoothedOtherPowerWatts > _options.AnomalyThresholdWatts; if (isAnomaly && _anomalyStartTime is null) { _anomalyStartTime = now; } else if (!isAnomaly) { _anomalyStartTime = null; } 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); _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 || state.State == "unavailable" || state.State == "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; } _logger.LogDebug("NordPool price entity returned non-positive value: {State}", state.State); return 0; } private void EvaluateHighPowerNotification(double totalPowerWatts) { var isAboveThreshold = totalPowerWatts > _options.HighPowerThresholdWatts; if (isAboveThreshold && !_highPowerNotificationActive) { _notificationService.NotifyHighPowerUsage(totalPowerWatts, _options.HighPowerThresholdWatts); _highPowerNotificationActive = true; } else if (!isAboveThreshold && _highPowerNotificationActive) { _notificationService.DismissHighPowerNotification(); _highPowerNotificationActive = false; } } private double? ReadMainMeterPower() { var state = _haContext.GetState(_options.MainMeterEntityId); if (state?.State is null || state.State == "unavailable" || state.State == "unknown") { return null; } return double.TryParse(state.State, System.Globalization.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 || state.State == "unavailable" || state.State == "unknown") { readings[sensor.EntityId] = 0; degraded.Add(sensor.EntityId); continue; } if (double.TryParse(state.State, System.Globalization.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); } }