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:
2026-11-29 21:42:43 +02:00
parent 17774b40b8
commit 41ac93733e
65 changed files with 545 additions and 459 deletions
+44 -35
View File
@@ -16,7 +16,7 @@ using static BoilerMonitor.Models.BoilerMonitorConsts;
namespace BoilerMonitorManager;
[NetDaemonApp]
public sealed class BoilerMonitorInit : IBoilerMonitorInit
public sealed class BoilerMonitorInit
{
private readonly ILogger<BoilerMonitorInit> _logger;
private readonly IHaContext _haContext;
@@ -110,7 +110,7 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
}
}
public async Task InitializeAsync()
private async Task InitializeAsync()
{
try
{
@@ -131,7 +131,7 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
if (persisted is not null)
{
_tracker.RestoreFromSnapshot(persisted.AccumulatedRunTime, persisted.SessionCount);
_tracker.RestoreFromSnapshot();
if (persistedCooldown.HasValue)
{
@@ -139,8 +139,11 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
}
await _entityService.ResetTransientEntitiesAsync();
_logger.LogInformation("BoilerMonitor state restored from HA entities: runtime={Runtime}, sessions={Sessions}",
persisted.AccumulatedRunTime, persisted.SessionCount);
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("BoilerMonitor state restored from HA entities: runtime={Runtime}, sessions={Sessions}",
persisted.AccumulatedRunTime, persisted.SessionCount);
}
}
else
{
@@ -162,11 +165,6 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
}
}
public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default)
{
await _entityService.CleanupEntitiesAsync(cancellationToken);
}
private void SchedulePeriodicPolling()
{
var now = DateTime.Now;
@@ -175,7 +173,10 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
var delayUntilNext = TimeSpan.FromSeconds(secondsUntilNext);
var nextPollTime = now.Add(delayUntilNext);
_logger.LogInformation("Scheduling BoilerMonitor polling every {Interval}s, first at {Time}", DefaultPollIntervalSeconds, nextPollTime);
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("Scheduling BoilerMonitor polling every {Interval}s, first at {Time}", DefaultPollIntervalSeconds, nextPollTime);
}
_scheduler.RunEvery(TimeSpan.FromSeconds(DefaultPollIntervalSeconds), nextPollTime, () => _ = PollAndUpdateAsync());
}
@@ -206,15 +207,17 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
try
{
var switchState = _haContext.GetState(SkipPriceCapEntityId);
if (string.Equals(switchState?.State, SwitchOnState, StringComparison.OrdinalIgnoreCase))
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");
return;
}
_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)
{
@@ -308,7 +311,10 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
{
try
{
_logger.LogInformation("Config entity {EntityId} received command: {Value}", entityId, state);
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("Config entity {EntityId} received command: {Value}", entityId, state);
}
await _mqttEntityManager.SetStateAsync(entityId, state ?? string.Empty).ConfigureAwait(false);
}
catch (Exception e)
@@ -337,7 +343,10 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
{
try
{
_logger.LogInformation("Switch {EntityId} received command: {Value}", entityId, state);
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("Switch {EntityId} received command: {Value}", entityId, state);
}
await _mqttEntityManager.SetStateAsync(entityId, state ?? string.Empty).ConfigureAwait(false);
}
catch (Exception e)
@@ -386,9 +395,7 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
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);
_tracker.RecordPollResult();
if (isHeating)
{
@@ -397,7 +404,6 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
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);
@@ -431,7 +437,7 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
}
var budgetPercentage = budgetTimeSpan.TotalSeconds > 0
? (snapshot.AccumulatedRunTime.TotalSeconds / budgetTimeSpan.TotalSeconds) * 100.0
? snapshot.AccumulatedRunTime.TotalSeconds / budgetTimeSpan.TotalSeconds * 100.0
: 0.0;
var budgetExhausted = snapshot.AccumulatedRunTime >= budgetTimeSpan;
@@ -454,9 +460,12 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
}
else if (boilerAction is not BoilerAction.NoChange)
{
_logger.LogInformation(
"Automatic boiler control is off; skipping boiler switch service call (would have been {Action})",
boilerAction);
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation(
"Automatic boiler control is off; skipping boiler switch service call (would have been {Action})",
boilerAction);
}
}
var context = new BoilerMonitorUpdateContext
@@ -467,19 +476,19 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
BudgetExhausted = budgetExhausted,
SessionCount = snapshot.SessionCount,
BudgetHours = dailyHours,
IsCurrentlyHeating = isHeating,
WaterReady = waterReady,
BoilerSwitchState = boilerSwitchState,
BoilerPowerWatts = boilerPowerWatts,
CooldownSince = _waterReadyService.WaterReadySince,
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);
if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.LogDebug("Poll complete: power={Power}W, heating={Heating}, runtime={Runtime}, budget={Budget}%",
boilerPowerWatts, isHeating, snapshot.AccumulatedRunTime, budgetPercentage);
}
}
catch (Exception ex)
{
@@ -553,14 +562,14 @@ public sealed class BoilerMonitorInit : IBoilerMonitorInit
private static bool ReadAttributeBool(EntityState? entityState, string attributeName)
{
if (entityState?.Attributes is null)
if (entityState?.Attributes is not IDictionary<string, object> attributes)
{
return false;
}
try
{
if (entityState.Attributes is IDictionary<string, object> attributes && attributes.TryGetValue(attributeName, out var value))
if (attributes.TryGetValue(attributeName, out var value))
{
return value switch
{