Clear Qodana findings in monitor runtime code
- Guard logger calls with IsEnabled so value-type arguments are not boxed when the level is disabled - Make helper members static, narrow write-only properties to init or private get, and delete members no call site reaches - Flatten nested conditionals and convert if/else chains into switch and ternary form - Drop the unused *MonitorInit interfaces; NetDaemon instantiates the concrete app classes - Drop the unused IConfiguration parameter from AddNordPool and AddPowerMonitor, and the unused IEntityManager.CreateEntitiesAsync - Remove the ignored parameters of the boiler run-time tracker stub - Pin the NordPool DTO price mapping explicitly so the getter use is visible to static analysis - Fail Qodana on any finding and record the registration changes in AGENTS.md
This commit is contained in:
@@ -5,5 +5,4 @@ namespace PowerMonitorManager.Interface;
|
||||
public interface IOtherPowerCalculationService
|
||||
{
|
||||
PowerCalculationResult Calculate(double totalPowerWatts, IReadOnlyDictionary<string, double> deviceReadings);
|
||||
void Reset();
|
||||
}
|
||||
|
||||
@@ -7,9 +7,7 @@ public interface IPowerCostCalculationService
|
||||
void RecordCosts(PowerCalculationResult calculation, double nordPoolPrice, int pollIntervalSeconds, DateTime now);
|
||||
CostSnapshot GetTotalCostSnapshot();
|
||||
CostSnapshot GetOtherCostSnapshot();
|
||||
CostSnapshot GetDeviceCostSnapshot(string entityId);
|
||||
IReadOnlyDictionary<string, CostSnapshot> GetAllDeviceCostSnapshots();
|
||||
double LastKnownPrice { get; }
|
||||
string PriceSource { get; }
|
||||
void SetPrice(double price);
|
||||
}
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
namespace PowerMonitorManager.Interface;
|
||||
|
||||
public interface IPowerMonitorInit
|
||||
{
|
||||
Task InitializeAsync();
|
||||
Task CleanupEntitiesAsync(CancellationToken cancellationToken = default);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
namespace PowerMonitorManager.Models;
|
||||
|
||||
public sealed class CostAccumulator
|
||||
public sealed class CostAccumulator(DateTime now)
|
||||
{
|
||||
private readonly Lock _lock = new();
|
||||
|
||||
@@ -14,21 +14,13 @@ public sealed class CostAccumulator
|
||||
private double _previousDaily;
|
||||
private double _previousMonthly;
|
||||
|
||||
private DateTime _last15MinReset;
|
||||
private DateTime _last1HourReset;
|
||||
private DateTime _lastDailyReset;
|
||||
private DateTime _lastMonthlyReset;
|
||||
private DateTime _last15MinReset = now;
|
||||
private DateTime _last1HourReset = now;
|
||||
private DateTime _lastDailyReset = now;
|
||||
private DateTime _lastMonthlyReset = now;
|
||||
|
||||
private bool _partialWindow = true;
|
||||
|
||||
public CostAccumulator(DateTime now)
|
||||
{
|
||||
_last15MinReset = now;
|
||||
_last1HourReset = now;
|
||||
_lastDailyReset = now;
|
||||
_lastMonthlyReset = now;
|
||||
}
|
||||
|
||||
public void AddCost(double costIncrement, DateTime now)
|
||||
{
|
||||
lock (_lock)
|
||||
@@ -85,12 +77,14 @@ public sealed class CostAccumulator
|
||||
_lastDailyReset = now;
|
||||
}
|
||||
|
||||
if (IsNewMonthWindow(now, _lastMonthlyReset))
|
||||
if (!IsNewMonthWindow(now, _lastMonthlyReset))
|
||||
{
|
||||
_previousMonthly = _costMonthly;
|
||||
_costMonthly = 0;
|
||||
_lastMonthlyReset = now;
|
||||
return;
|
||||
}
|
||||
|
||||
_previousMonthly = _costMonthly;
|
||||
_costMonthly = 0;
|
||||
_lastMonthlyReset = now;
|
||||
}
|
||||
|
||||
internal static bool IsNew15MinWindow(DateTime now, DateTime lastReset)
|
||||
|
||||
@@ -6,13 +6,13 @@ public sealed class PowerMonitorOptions
|
||||
{
|
||||
public const string SectionName = "PowerMonitor";
|
||||
|
||||
public bool Enabled { get; set; }
|
||||
public bool Enabled { get; init; }
|
||||
public string MainMeterEntityId { get; set; } = string.Empty;
|
||||
public int PollIntervalSeconds { get; set; } = PowerMonitorConsts.DefaultPollIntervalSeconds;
|
||||
public int SmoothingWindowSize { get; set; } = PowerMonitorConsts.DefaultSmoothingWindowSize;
|
||||
public double AnomalyThresholdWatts { get; set; } = PowerMonitorConsts.DefaultAnomalyThresholdWatts;
|
||||
public int PollIntervalSeconds { get; init; } = PowerMonitorConsts.DefaultPollIntervalSeconds;
|
||||
public int SmoothingWindowSize { get; init; } = PowerMonitorConsts.DefaultSmoothingWindowSize;
|
||||
public double AnomalyThresholdWatts { get; init; } = PowerMonitorConsts.DefaultAnomalyThresholdWatts;
|
||||
public string[] ExcludedSensorPatterns { get; set; } = [];
|
||||
public double HighPowerThresholdWatts { get; set; } = PowerMonitorConsts.DefaultHighPowerThresholdWatts;
|
||||
public double HighPowerThresholdWatts { get; init; } = PowerMonitorConsts.DefaultHighPowerThresholdWatts;
|
||||
|
||||
public bool EnforceLimitEnabled { get; set; } = true;
|
||||
public double PowerLimitWatts { get; set; } = PowerMonitorConsts.DefaultPowerLimitWatts;
|
||||
|
||||
@@ -32,7 +32,7 @@ public sealed class OtherPowerCalculationService : IOtherPowerCalculationService
|
||||
lock (_lock)
|
||||
{
|
||||
smoothed = _previousSmoothed.HasValue
|
||||
? (_alpha * rawOther) + ((1 - _alpha) * _previousSmoothed.Value)
|
||||
? _alpha * rawOther + (1 - _alpha) * _previousSmoothed.Value
|
||||
: rawOther;
|
||||
_previousSmoothed = smoothed;
|
||||
}
|
||||
|
||||
@@ -18,11 +18,10 @@ public sealed class PowerLimitEnforcementService(
|
||||
{
|
||||
private readonly PowerMonitorOptions _options = options.Value;
|
||||
|
||||
private bool _isLimitActive;
|
||||
private DateTimeOffset _enforcedAt;
|
||||
private DateTimeOffset _lastActionTime;
|
||||
|
||||
public bool IsLimitActive => _isLimitActive;
|
||||
public bool IsLimitActive { get; private set; }
|
||||
|
||||
public void EnforceLimit(double currentPowerWatts)
|
||||
{
|
||||
@@ -33,7 +32,7 @@ public sealed class PowerLimitEnforcementService(
|
||||
|
||||
var now = timeProvider.GetUtcNow();
|
||||
|
||||
if (!_isLimitActive)
|
||||
if (!IsLimitActive)
|
||||
{
|
||||
TryEnforce(currentPowerWatts, now);
|
||||
return;
|
||||
@@ -44,7 +43,7 @@ public sealed class PowerLimitEnforcementService(
|
||||
|
||||
public void TriggerLimitBreach()
|
||||
{
|
||||
if (_isLimitActive)
|
||||
if (IsLimitActive)
|
||||
{
|
||||
logger.LogInformation("Debug: trigger requested but limit already active");
|
||||
return;
|
||||
@@ -56,7 +55,7 @@ public sealed class PowerLimitEnforcementService(
|
||||
|
||||
public void ResetLimitBreach()
|
||||
{
|
||||
if (!_isLimitActive)
|
||||
if (!IsLimitActive)
|
||||
{
|
||||
logger.LogInformation("Debug: reset requested but limit not active");
|
||||
return;
|
||||
@@ -80,7 +79,7 @@ public sealed class PowerLimitEnforcementService(
|
||||
|
||||
NotifyLimitEnforced(currentPowerWatts, _options.PowerLimitWatts);
|
||||
|
||||
_isLimitActive = true;
|
||||
IsLimitActive = true;
|
||||
var now = timeProvider.GetUtcNow();
|
||||
_enforcedAt = now;
|
||||
_lastActionTime = now;
|
||||
@@ -95,7 +94,7 @@ public sealed class PowerLimitEnforcementService(
|
||||
|
||||
DismissLimitNotification();
|
||||
|
||||
_isLimitActive = false;
|
||||
IsLimitActive = false;
|
||||
_lastActionTime = timeProvider.GetUtcNow();
|
||||
}
|
||||
|
||||
@@ -108,8 +107,11 @@ public sealed class PowerLimitEnforcementService(
|
||||
|
||||
if (now - _lastActionTime < TimeSpan.FromSeconds(_options.LimitCooldownSeconds))
|
||||
{
|
||||
logger.LogDebug("Power limit breach detected ({Power:F0} W > {Limit:F0} W) but cooldown active, skipping", currentPowerWatts, _options.PowerLimitWatts);
|
||||
|
||||
if (logger.IsEnabled(LogLevel.Debug))
|
||||
{
|
||||
logger.LogDebug("Power limit breach detected ({Power:F0} W > {Limit:F0} W) but cooldown active, skipping", currentPowerWatts, _options.PowerLimitWatts);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -135,7 +137,10 @@ public sealed class PowerLimitEnforcementService(
|
||||
return;
|
||||
}
|
||||
|
||||
logger.LogInformation("Power recovered to {Power:F0} W (< {Limit:F0} W) after {Seconds}s, restoring paused monitors", currentPowerWatts, _options.PowerLimitWatts, (int)elapsed.TotalSeconds);
|
||||
if (logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
logger.LogInformation("Power recovered to {Power:F0} W (< {Limit:F0} W) after {Seconds}s, restoring paused monitors", currentPowerWatts, _options.PowerLimitWatts, (int)elapsed.TotalSeconds);
|
||||
}
|
||||
|
||||
foreach (var entityId in _options.PauseAndRestoreEntityIds)
|
||||
{
|
||||
@@ -144,7 +149,7 @@ public sealed class PowerLimitEnforcementService(
|
||||
|
||||
DismissLimitNotification();
|
||||
|
||||
_isLimitActive = false;
|
||||
IsLimitActive = false;
|
||||
_lastActionTime = now;
|
||||
}
|
||||
|
||||
|
||||
@@ -48,7 +48,11 @@ public sealed class PowerMonitorEntityService(
|
||||
{
|
||||
try
|
||||
{
|
||||
logger.LogInformation("Creating MQTT entity: {EntityId}", entity.EntityId);
|
||||
if (logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
logger.LogInformation("Creating MQTT entity: {EntityId}", entity.EntityId);
|
||||
}
|
||||
|
||||
await entityManager.CreateEntityAsync(entity).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -69,7 +73,11 @@ public sealed class PowerMonitorEntityService(
|
||||
{
|
||||
try
|
||||
{
|
||||
logger.LogInformation("Creating device cost entity: {EntityId}", entity.EntityId);
|
||||
if (logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
logger.LogInformation("Creating device cost entity: {EntityId}", entity.EntityId);
|
||||
}
|
||||
|
||||
await entityManager.CreateEntityAsync(entity).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -169,8 +177,11 @@ public sealed class PowerMonitorEntityService(
|
||||
try
|
||||
{
|
||||
await entityManager.RemoveEntity(id).ConfigureAwait(false);
|
||||
|
||||
logger.LogDebug("Entity removed: {EntityId}", id);
|
||||
|
||||
if (logger.IsEnabled(LogLevel.Debug))
|
||||
{
|
||||
logger.LogDebug("Entity removed: {EntityId}", id);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -182,7 +193,7 @@ public sealed class PowerMonitorEntityService(
|
||||
}
|
||||
|
||||
|
||||
internal ICollection<PowerMonitorEntity> GetSystemEntitiesList()
|
||||
internal static ICollection<PowerMonitorEntity> GetSystemEntitiesList()
|
||||
{
|
||||
return new List<PowerMonitorEntity>
|
||||
{
|
||||
|
||||
@@ -13,7 +13,7 @@ using PowerMonitorManager.Models.Consts;
|
||||
namespace PowerMonitorManager;
|
||||
|
||||
[NetDaemonApp]
|
||||
public sealed class PowerMonitorInit : IPowerMonitorInit
|
||||
public sealed class PowerMonitorInit
|
||||
{
|
||||
private readonly ILogger<PowerMonitorInit> _logger;
|
||||
private readonly IHaContext _haContext;
|
||||
@@ -84,7 +84,7 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
|
||||
}
|
||||
}
|
||||
|
||||
public async Task InitializeAsync()
|
||||
private async Task InitializeAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
@@ -98,7 +98,10 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
|
||||
var sensors = GetPowerSensorEntitiesNames();
|
||||
await _entityService.CreateDeviceEntitiesAsync(sensors);
|
||||
|
||||
_logger.LogInformation("PowerMonitor initialized with {SensorCount} tracked sensors", sensors.Count);
|
||||
if (_logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
_logger.LogInformation("PowerMonitor initialized with {SensorCount} tracked sensors", sensors.Count);
|
||||
}
|
||||
|
||||
await PollAndUpdateAsync();
|
||||
}
|
||||
@@ -116,7 +119,7 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
|
||||
return sensors;
|
||||
}
|
||||
|
||||
public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default)
|
||||
private async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
await _entityService.RemoveSystemEntitiesAsync(cancellationToken);
|
||||
}
|
||||
@@ -141,7 +144,10 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
|
||||
_ = PollAndUpdateAsync();
|
||||
});
|
||||
|
||||
_logger.LogInformation("PowerMonitor subscribed to state changes of {MeterId}", _options.MainMeterEntityId);
|
||||
if (_logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
_logger.LogInformation("PowerMonitor subscribed to state changes of {MeterId}", _options.MainMeterEntityId);
|
||||
}
|
||||
}
|
||||
|
||||
private void SubscribeToRediscoverButton()
|
||||
@@ -190,7 +196,10 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
|
||||
if (added.Count > 0)
|
||||
{
|
||||
await _entityService.CreateDeviceEntitiesAsync(added);
|
||||
_logger.LogInformation("Created entities for {Count} new sensors", added.Count);
|
||||
if (_logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
_logger.LogInformation("Created entities for {Count} new sensors", added.Count);
|
||||
}
|
||||
}
|
||||
|
||||
if (removed.Count > 0)
|
||||
@@ -198,7 +207,10 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
|
||||
await RemoreDevicePriceEntities(removed);
|
||||
}
|
||||
|
||||
_logger.LogInformation("Re-discovery complete: {Total} sensors ({Added} added, {Removed} removed)", newSensors.Count, added.Count, removed.Count);
|
||||
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)
|
||||
{
|
||||
@@ -211,7 +223,10 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
|
||||
var removedNames = removed.Select(s => s.DeviceName).ToList();
|
||||
await _entityService.RemoveDeviceEntitiesAsync(removedNames);
|
||||
|
||||
_logger.LogInformation("Removed entities for {Count} sensors", removed.Count);
|
||||
if (_logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
_logger.LogInformation("Removed entities for {Count} sensors", removed.Count);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task PollAndUpdateAsync()
|
||||
@@ -247,15 +262,13 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
|
||||
_costService.RecordCosts(calculation, nordPoolPrice, (int)Math.Max(1, elapsedSeconds), now.LocalDateTime);
|
||||
|
||||
var isAnomaly = calculation.SmoothedOtherPowerWatts > _options.AnomalyThresholdWatts;
|
||||
|
||||
if (isAnomaly && _anomalyStartTime is null)
|
||||
|
||||
_anomalyStartTime = isAnomaly switch
|
||||
{
|
||||
_anomalyStartTime = now;
|
||||
}
|
||||
else if (!isAnomaly)
|
||||
{
|
||||
_anomalyStartTime = null;
|
||||
}
|
||||
true when _anomalyStartTime is null => now,
|
||||
false => null,
|
||||
_ => _anomalyStartTime
|
||||
};
|
||||
|
||||
var anomalyDuration = _anomalyStartTime.HasValue
|
||||
? now - _anomalyStartTime.Value
|
||||
@@ -288,8 +301,11 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
|
||||
|
||||
_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);
|
||||
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)
|
||||
{
|
||||
@@ -312,7 +328,10 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
|
||||
return price;
|
||||
}
|
||||
|
||||
_logger.LogDebug("NordPool price entity returned non-positive value: {State}", state.State);
|
||||
if (_logger.IsEnabled(LogLevel.Debug))
|
||||
{
|
||||
_logger.LogDebug("NordPool price entity returned non-positive value: {State}", state.State);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -321,15 +340,17 @@ public sealed class PowerMonitorInit : IPowerMonitorInit
|
||||
{
|
||||
var isAboveThreshold = totalPowerWatts > _options.HighPowerThresholdWatts;
|
||||
|
||||
if (isAboveThreshold && !_highPowerNotificationActive)
|
||||
switch (isAboveThreshold, _highPowerNotificationActive)
|
||||
{
|
||||
_notificationService.NotifyHighPowerUsage(totalPowerWatts, _options.HighPowerThresholdWatts);
|
||||
_highPowerNotificationActive = true;
|
||||
}
|
||||
else if (!isAboveThreshold && _highPowerNotificationActive)
|
||||
{
|
||||
_notificationService.DismissHighPowerNotification();
|
||||
_highPowerNotificationActive = false;
|
||||
case (true, false):
|
||||
_notificationService.NotifyHighPowerUsage(totalPowerWatts, _options.HighPowerThresholdWatts);
|
||||
_highPowerNotificationActive = true;
|
||||
break;
|
||||
|
||||
case (false, true):
|
||||
_notificationService.DismissHighPowerNotification();
|
||||
_highPowerNotificationActive = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,19 +1,13 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using NetDaemon.AppModel;
|
||||
using PowerMonitorManager.Interface;
|
||||
using PowerMonitorManager.Models;
|
||||
|
||||
namespace PowerMonitorManager;
|
||||
|
||||
public static class PowerMonitorServiceRegistration
|
||||
{
|
||||
public static IServiceCollection AddPowerMonitor(this IServiceCollection services, IConfiguration configuration)
|
||||
public static IServiceCollection AddPowerMonitor(this IServiceCollection services)
|
||||
{
|
||||
var options = configuration
|
||||
.GetSection(PowerMonitorOptions.SectionName)
|
||||
.Get<PowerMonitorOptions>() ?? new PowerMonitorOptions();
|
||||
|
||||
services
|
||||
.AddNetDaemonApp<PowerMonitorInit>()
|
||||
.AddScoped<IPowerSensorDiscoveryService, PowerSensorDiscoveryService>()
|
||||
|
||||
@@ -30,9 +30,7 @@ public sealed class PowerSensorDiscoveryService : IPowerSensorDiscoveryService
|
||||
_haContext = haContext;
|
||||
_options = options.Value;
|
||||
_logger = logger;
|
||||
_exclusionPatterns = _options.ExcludedSensorPatterns
|
||||
.Select(GlobToRegex)
|
||||
.ToArray();
|
||||
_exclusionPatterns = [.. _options.ExcludedSensorPatterns.Select(GlobToRegex)];
|
||||
}
|
||||
|
||||
public IReadOnlyList<PowerSensorInfo> DiscoverDeviceSensors()
|
||||
@@ -54,13 +52,16 @@ public sealed class PowerSensorDiscoveryService : IPowerSensorDiscoveryService
|
||||
|
||||
_currentDeviceSensors = powerSensors;
|
||||
|
||||
_logger.LogInformation("Discovered {Count} power sensors (excluded main meter: {MainMeter}, exclusion patterns: {PatternCount})",
|
||||
powerSensors.Count, _options.MainMeterEntityId, _exclusionPatterns.Length);
|
||||
if (_logger.IsEnabled(LogLevel.Information))
|
||||
{
|
||||
_logger.LogInformation("Discovered {Count} power sensors (excluded main meter: {MainMeter}, exclusion patterns: {PatternCount})",
|
||||
powerSensors.Count, _options.MainMeterEntityId, _exclusionPatterns.Length);
|
||||
}
|
||||
|
||||
return powerSensors;
|
||||
}
|
||||
|
||||
internal bool IsPowerSensor(Entity entity)
|
||||
internal static bool IsPowerSensor(Entity entity)
|
||||
{
|
||||
if (!entity.EntityId.StartsWith("sensor.", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user