Add braces to single-statement guards and refactor NordPool price fetching

- Expand inline guard, return and logger blocks across the monitor services, init classes and tests
- Have INordPoolPriceService take a per-date fetch delegate and expose ParseAndAdjust, moving the HA fetch call into NordPoolInit so the service can be registered singleton
- Record the NordPool and boiler service lifetimes in AGENTS.md
- Drop the unused persisted-state argument from the boiler test data helper
This commit is contained in:
2026-12-01 11:59:31 +02:00
parent 24729ee267
commit 77458383d1
34 changed files with 336 additions and 93 deletions
@@ -33,15 +33,19 @@ public sealed class BoilerConfigReader(IHaContext haContext, ILogger<BoilerConfi
if (!string.IsNullOrEmpty(readyByState) &&
TimeSpan.TryParse(readyByState, CultureInfo.InvariantCulture, out var readyByTime))
{
deadline = DateTime.Today.Add(readyByTime);
}
var skipPriceCapState = haContext.GetState(SkipPriceCapEntityId)?.State;
var skipPriceCap = string.Equals(skipPriceCapState, SwitchOnState, StringComparison.OrdinalIgnoreCase);
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
{
@@ -23,9 +23,11 @@ public sealed class BoilerControlService(ILogger<BoilerControlService> logger) :
{
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;
@@ -34,17 +36,21 @@ public sealed class BoilerControlService(ILogger<BoilerControlService> logger) :
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;
}
@@ -45,7 +45,10 @@ public sealed class BoilerMonitorEntityService(
try
{
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation("Creating/re-registering MQTT entity: {EntityId}", entity.EntityId);
}
await entityManager.CreateEntityAsync(entity).ConfigureAwait(false);
}
catch (Exception ex)
@@ -144,9 +147,12 @@ public sealed class BoilerMonitorEntityService(
!TryParseEntityInt(sessionCountState, out var sessionCount))
{
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation(
"No valid persisted BoilerMonitor state found in HA entities (runtime={Runtime}, sessions={Sessions})",
runtimeState, sessionCountState);
}
return null;
}
@@ -159,10 +165,12 @@ public sealed class BoilerMonitorEntityService(
};
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 +208,10 @@ public sealed class BoilerMonitorEntityService(
DateTimeStyles.RoundtripKind, out var parsed))
{
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation("Read persisted cooldown timestamp: {CooldownSince}", parsed);
}
return parsed;
}
}
@@ -500,7 +511,9 @@ public sealed class BoilerMonitorEntityService(
{
await entityManager.SetEntityState(entityId, state).ConfigureAwait(false);
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("Successfully set state for {EntityId}: {State}", entityId, state);
}
}
catch (Exception ex)
{
@@ -514,7 +527,9 @@ public sealed class BoilerMonitorEntityService(
{
await entityManager.SetEntityAttributes(entityId, attributes).ConfigureAwait(false);
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("Successfully set attributes for {EntityId}", entityId);
}
}
catch (Exception ex)
{
+25 -3
View File
@@ -134,9 +134,11 @@ public sealed class BoilerMonitorInit
await _entityService.ResetTransientEntitiesAsync();
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation(
"BoilerMonitor state restored from HA entities: runtime={Runtime}, sessions={Sessions}",
persisted.AccumulatedRunTime, persisted.SessionCount);
}
}
else
{
@@ -167,8 +169,10 @@ public sealed class BoilerMonitorInit
var nextPollTime = now.Add(delayUntilNext);
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());
@@ -290,7 +294,10 @@ public sealed class BoilerMonitorInit
try
{
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)
@@ -320,7 +327,10 @@ public sealed class BoilerMonitorInit
try
{
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)
@@ -428,12 +438,16 @@ public sealed class BoilerMonitorInit
!string.Equals(autoManagementState, SwitchOffState, StringComparison.OrdinalIgnoreCase);
if (autoManagementEnabled)
{
ExecuteBoilerAction(boilerAction, config.BoilerSwitchEntityId!);
}
else if (boilerAction is not BoilerAction.NoChange)
{
if (_logger.IsEnabled(LogLevel.Information))
_logger.LogInformation(
"Automatic boiler control is off; skipping boiler switch service call (would have been {Action})",
boilerAction);
{
_logger.LogInformation("Automatic boiler control is off; skipping boiler switch service call (would have been {Action})", boilerAction);
}
}
var context = new BoilerMonitorUpdateContext
{
@@ -452,9 +466,11 @@ public sealed class BoilerMonitorInit
await _entityService.UpdateEntitiesAsync(context);
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)
{
@@ -491,7 +507,9 @@ public sealed class BoilerMonitorInit
if (!string.IsNullOrWhiteSpace(pollIntervalState)
&& double.TryParse(pollIntervalState, CultureInfo.InvariantCulture, out var pollIntervalValue)
&& pollIntervalValue > 0)
{
pollInterval = (int)pollIntervalValue;
}
double? heatingThreshold = null;
var thresholdState = _haContext.GetState(ConfigHeatingThresholdEntityId)?.State;
@@ -499,7 +517,9 @@ public sealed class BoilerMonitorInit
if (!string.IsNullOrWhiteSpace(thresholdState)
&& double.TryParse(thresholdState, CultureInfo.InvariantCulture, out var thresholdValue)
&& thresholdValue > 0)
{
heatingThreshold = thresholdValue;
}
return new BoilerMonitorConfig
{
@@ -526,6 +546,7 @@ public sealed class BoilerMonitorInit
try
{
if (attributes.TryGetValue(attributeName, out var value))
{
return value switch
{
bool b => b,
@@ -536,6 +557,7 @@ public sealed class BoilerMonitorInit
bool.TryParse(jsonElement.GetString(), out var jsonParsed) && jsonParsed,
_ => false
};
}
}
catch
{
@@ -41,8 +41,11 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
if (IsWithinCooldownPeriod())
{
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("Water ready cooldown active (since {Since}), suppressing turn-on",
_waterReadySince);
}
return true;
}
}
@@ -56,8 +59,10 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
if (!_hasObservedHeating)
{
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("Ignoring power reading ({PowerWatts}W) — boiler has not been observed heating yet",
powerWatts.Value);
}
return false;
}
@@ -73,10 +78,12 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
if (_consecutiveBelowThresholdCount < BoilerMonitorConsts.ConsecutiveReadingsRequired)
{
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug(
"Below-threshold reading {Count}/{Required} ({PowerWatts}W), waiting for confirmation",
_consecutiveBelowThresholdCount, BoilerMonitorConsts.ConsecutiveReadingsRequired,
powerWatts.Value);
}
return false;
}
@@ -84,9 +91,11 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
_waterReadySince ??= timeProvider.GetUtcNow();
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;
}
@@ -135,15 +144,19 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
if (waterReadySince < todayMidnightUtc)
{
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation("Persisted cooldown is from a previous day ({Since}), not restoring",
waterReadySince);
}
return;
}
_waterReadySince = waterReadySince;
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation("Restored water ready cooldown from {Since}", waterReadySince);
}
}
}