5777e641f6
- Extract per-monitor *TestData helper classes and rework tests to use them - Add boiler run-time tracker abstraction (implementation pending) - Drop unused NordPool init/update-result types and stale PLAN.md - Add qodana.yaml with the inspection set to keep the analysis focused
382 lines
13 KiB
C#
382 lines
13 KiB
C#
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;
|
|
|
|
namespace PowerMonitorManager;
|
|
|
|
[NetDaemonApp]
|
|
public sealed class PowerMonitorInit : IPowerMonitorInit
|
|
{
|
|
private readonly ILogger<PowerMonitorInit> _logger;
|
|
private readonly IHaContext _haContext;
|
|
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 IPowerLimitEnforcementService _enforcementService;
|
|
private readonly TimeProvider _timeProvider;
|
|
|
|
private int _mainMeterConsecutiveFailures;
|
|
private DateTimeOffset? _anomalyStartTime;
|
|
private DateTimeOffset? _lastPollTimestamp;
|
|
private bool _highPowerNotificationActive;
|
|
|
|
public PowerMonitorInit(
|
|
IHaContext haContext,
|
|
ILogger<PowerMonitorInit> logger,
|
|
IOptions<PowerMonitorOptions> 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");
|
|
}
|
|
}
|
|
|
|
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 = GetPowerSensorEntitiesNames();
|
|
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;
|
|
}
|
|
}
|
|
|
|
private IReadOnlyList<PowerSensorInfo> GetPowerSensorEntitiesNames()
|
|
{
|
|
var sensors = _discoveryService.DiscoverDeviceSensors();
|
|
|
|
return sensors;
|
|
}
|
|
|
|
public 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();
|
|
});
|
|
|
|
_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);
|
|
_logger.LogInformation("Created entities for {Count} new sensors", added.Count);
|
|
}
|
|
|
|
if (removed.Count > 0)
|
|
{
|
|
await RemoreDevicePriceEntities(removed);
|
|
}
|
|
|
|
_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<PowerSensorInfo> removed)
|
|
{
|
|
var removedNames = removed.Select(s => s.DeviceName).ToList();
|
|
await _entityService.RemoveDeviceEntitiesAsync(removedNames);
|
|
|
|
_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;
|
|
|
|
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);
|
|
|
|
_enforcementService.EnforceLimit(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 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;
|
|
}
|
|
|
|
_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 or "unavailable" or "unknown")
|
|
{
|
|
return null;
|
|
}
|
|
|
|
return double.TryParse(state.State, CultureInfo.InvariantCulture, out var value)
|
|
? value
|
|
: null;
|
|
}
|
|
|
|
private (IReadOnlyDictionary<string, double> readings, List<string> degraded) ReadDeviceSensors()
|
|
{
|
|
var readings = new Dictionary<string, double>();
|
|
var degraded = new List<string>();
|
|
|
|
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);
|
|
}
|
|
}
|