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
+4 -1
View File
@@ -37,7 +37,10 @@ public sealed class BoilerConfigReader(IHaContext haContext, ILogger<BoilerConfi
var skipPriceCapState = haContext.GetState(SkipPriceCapEntityId)?.State;
var skipPriceCap = string.Equals(skipPriceCapState, SwitchOnState, StringComparison.OrdinalIgnoreCase);
logger.LogDebug("Boiler config: intervals={Intervals}, priceCap={Cap}, skipPriceCap={Skip}, deadline={Deadline}", intervalCount, priceCap, skipPriceCap, deadline);
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("Boiler config: intervals={Intervals}, priceCap={Cap}, skipPriceCap={Skip}, deadline={Deadline}", intervalCount, priceCap, skipPriceCap, deadline);
}
var config = new BoilerConfig
{
+32 -24
View File
@@ -19,40 +19,48 @@ public sealed class BoilerControlService(ILogger<BoilerControlService> logger) :
var effectiveBudgetExhausted = budgetExhausted && !budgetOverride;
var shouldBeOn = isNowCheap && !waterReady && !effectiveBudgetExhausted;
if (shouldBeOn && !isCurrentlyOn)
switch (shouldBeOn, isCurrentlyOn)
{
logger.LogInformation("Boiler should turn ON — cheap interval active, water not ready, budget available (current state: {State})", currentSwitchState);
case (true, false):
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation("Boiler should turn ON — cheap interval active, water not ready, budget available (current state: {State})", currentSwitchState);
}
return BoilerAction.TurnOn;
return BoilerAction.TurnOn;
case (false, true):
{
var reason = GetTurnOffReason(waterReady, effectiveBudgetExhausted);
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation("Boiler should turn OFF — {Reason} (current state: {State})", reason, currentSwitchState);
}
return BoilerAction.TurnOff;
}
default:
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("Boiler state unchanged: {State} (cheap={Cheap}, waterReady={WaterReady}, budgetExhausted={BudgetExhausted})",
currentSwitchState, isNowCheap, waterReady, effectiveBudgetExhausted);
}
return BoilerAction.NoChange;
}
if (!shouldBeOn && isCurrentlyOn)
{
var reason = GetTurnOffReason(waterReady, isNowCheap, effectiveBudgetExhausted);
logger.LogInformation("Boiler should turn OFF — {Reason} (current state: {State})", reason, currentSwitchState);
return BoilerAction.TurnOff;
}
logger.LogDebug("Boiler state unchanged: {State} (cheap={Cheap}, waterReady={WaterReady}, budgetExhausted={BudgetExhausted})",
currentSwitchState, isNowCheap, waterReady, effectiveBudgetExhausted);
return BoilerAction.NoChange;
}
private static string GetTurnOffReason(bool waterReady, bool isNowCheap, bool effectiveBudgetExhausted)
private static string GetTurnOffReason(bool waterReady, bool effectiveBudgetExhausted)
{
if (waterReady)
{
return "water is already ready";
}
if (effectiveBudgetExhausted)
{
return "daily budget is exhausted";
}
return "not in a cheap interval";
return effectiveBudgetExhausted
? "daily budget is exhausted"
: "not in a cheap interval";
}
}
@@ -51,7 +51,10 @@ public sealed class BoilerMonitorEntityService(
{
try
{
logger.LogInformation("Creating/re-registering MQTT entity: {EntityId}", entity.EntityId);
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation("Creating/re-registering MQTT entity: {EntityId}", entity.EntityId);
}
await entityManager.CreateEntityAsync(entity).ConfigureAwait(false);
}
catch (Exception ex)
@@ -148,8 +151,11 @@ public sealed class BoilerMonitorEntityService(
if (!TryParseEntitySeconds(runtimeState, out var runtimeSeconds) || !TryParseEntityInt(sessionCountState, out var sessionCount))
{
logger.LogInformation("No valid persisted BoilerMonitor state found in HA entities (runtime={Runtime}, sessions={Sessions})",
runtimeState, sessionCountState);
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation("No valid persisted BoilerMonitor state found in HA entities (runtime={Runtime}, sessions={Sessions})",
runtimeState, sessionCountState);
}
return null;
}
@@ -161,8 +167,11 @@ public sealed class BoilerMonitorEntityService(
BudgetOverrideState = budgetOverrideState
};
logger.LogInformation("Restored persisted BoilerMonitor state: runtime={Runtime}, sessions={Sessions}, skipPriceCap={SkipPriceCap}, budgetOverride={BudgetOverride}",
persisted.AccumulatedRunTime, persisted.SessionCount, persisted.SkipPriceCapState, persisted.BudgetOverrideState);
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation("Restored persisted BoilerMonitor state: runtime={Runtime}, sessions={Sessions}, skipPriceCap={SkipPriceCap}, budgetOverride={BudgetOverride}",
persisted.AccumulatedRunTime, persisted.SessionCount, persisted.SkipPriceCapState, persisted.BudgetOverrideState);
}
return persisted;
}
@@ -200,7 +209,7 @@ public sealed class BoilerMonitorEntityService(
return tryParseEntityInt;
}
private ICollection<BoilerMonitorEntity> GetAllEntities()
private static ICollection<BoilerMonitorEntity> GetAllEntities()
{
var device = CreateDeviceBlock();
@@ -468,7 +477,10 @@ public sealed class BoilerMonitorEntityService(
DateTimeOffset.TryParse(stringValue, CultureInfo.InvariantCulture,
DateTimeStyles.RoundtripKind, out var parsed))
{
logger.LogInformation("Read persisted cooldown timestamp: {CooldownSince}", parsed);
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation("Read persisted cooldown timestamp: {CooldownSince}", parsed);
}
return parsed;
}
}
@@ -485,7 +497,10 @@ public sealed class BoilerMonitorEntityService(
try
{
await entityManager.SetEntityState(entityId, state).ConfigureAwait(false);
logger.LogDebug("Successfully set state for {EntityId}: {State}", entityId, state);
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("Successfully set state for {EntityId}: {State}", entityId, state);
}
}
catch (Exception ex)
{
@@ -498,7 +513,10 @@ public sealed class BoilerMonitorEntityService(
try
{
await entityManager.SetEntityAttributes(entityId, attributes).ConfigureAwait(false);
logger.LogDebug("Successfully set attributes for {EntityId}", entityId);
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("Successfully set attributes for {EntityId}", entityId);
}
}
catch (Exception ex)
{
+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
{
@@ -5,7 +5,7 @@ namespace BoilerMonitorManager;
public class BoilerRunTimeTracker : IBoilerRunTimeTracker
{
public void RecordPollResult(bool isHeating, TimeSpan pollInterval)
public void RecordPollResult()
{
}
@@ -15,8 +15,7 @@ public class BoilerRunTimeTracker : IBoilerRunTimeTracker
return new RunTimeSnapshot
{
AccumulatedRunTime = TimeSpan.Zero,
SessionCount = 0,
IsInSession = false
SessionCount = 0
};
}
@@ -25,7 +24,7 @@ public class BoilerRunTimeTracker : IBoilerRunTimeTracker
}
public void RestoreFromSnapshot(TimeSpan accumulatedRunTime, int sessionCount)
public void RestoreFromSnapshot()
{
}
@@ -1,7 +0,0 @@
namespace BoilerMonitorManager.Interface;
public interface IBoilerMonitorInit
{
Task InitializeAsync();
Task CleanupEntitiesAsync(CancellationToken cancellationToken = default);
}
@@ -4,8 +4,8 @@ namespace BoilerMonitorManager.Interface;
public interface IBoilerRunTimeTracker
{
void RecordPollResult(bool isHeating, TimeSpan pollInterval);
void RecordPollResult();
RunTimeSnapshot GetSnapshot();
void Reset();
void RestoreFromSnapshot(TimeSpan accumulatedRunTime, int sessionCount);
void RestoreFromSnapshot();
}
@@ -8,11 +8,8 @@ public record BoilerMonitorUpdateContext
public required bool BudgetExhausted { get; init; }
public required int SessionCount { get; init; }
public required double BudgetHours { get; init; }
public required bool IsCurrentlyHeating { get; init; }
public required bool WaterReady { get; init; }
public required string? BoilerSwitchState { get; init; }
public required double? BoilerPowerWatts { get; init; }
public required DateTimeOffset? CooldownSince { get; init; }
public required bool IsNowCheap { get; init; }
public required DateTime? NextCheapIntervalStart { get; init; }
}
@@ -4,5 +4,4 @@ public record RunTimeSnapshot
{
public required TimeSpan AccumulatedRunTime { get; init; }
public required int SessionCount { get; init; }
public required bool IsInSession { get; init; }
}
+25 -7
View File
@@ -40,7 +40,10 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
{
if (IsWithinCooldownPeriod())
{
logger.LogDebug("Water ready cooldown active (since {Since}), suppressing turn-on", _waterReadySince);
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("Water ready cooldown active (since {Since}), suppressing turn-on", _waterReadySince);
}
return true;
}
}
@@ -59,7 +62,10 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
{
if (!_hasObservedHeating)
{
logger.LogDebug("Ignoring power reading ({PowerWatts}W) — boiler has not been observed heating yet", powerWatts.Value);
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("Ignoring power reading ({PowerWatts}W) — boiler has not been observed heating yet", powerWatts.Value);
}
return false;
}
@@ -74,15 +80,21 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
if (_consecutiveBelowThresholdCount < BoilerMonitorConsts.ConsecutiveReadingsRequired)
{
logger.LogDebug("Below-threshold reading {Count}/{Required} ({PowerWatts}W), waiting for confirmation",
_consecutiveBelowThresholdCount, BoilerMonitorConsts.ConsecutiveReadingsRequired, powerWatts.Value);
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("Below-threshold reading {Count}/{Required} ({PowerWatts}W), waiting for confirmation",
_consecutiveBelowThresholdCount, BoilerMonitorConsts.ConsecutiveReadingsRequired, powerWatts.Value);
}
return false;
}
_waterReadySince ??= timeProvider.GetUtcNow();
logger.LogInformation("Water detected as ready after {Count} consecutive readings, cooldown active until shower or midnight reset", _consecutiveBelowThresholdCount);
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation("Water detected as ready after {Count} consecutive readings, cooldown active until shower or midnight reset", _consecutiveBelowThresholdCount);
}
return true;
}
@@ -132,13 +144,19 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
var todayMidnightUtc = new DateTimeOffset(timeProvider.GetUtcNow().Date, TimeSpan.Zero);
if (waterReadySince < todayMidnightUtc)
{
logger.LogInformation("Persisted cooldown is from a previous day ({Since}), not restoring", waterReadySince);
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation("Persisted cooldown is from a previous day ({Since}), not restoring", waterReadySince);
}
return;
}
_waterReadySince = waterReadySince;
logger.LogInformation("Restored water ready cooldown from {Since}", waterReadySince);
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation("Restored water ready cooldown from {Since}", waterReadySince);
}
}
}