Apply code formatting cleanup across monitor projects

- Reindent appsettings.json and the MSBuild project files
- Collapse single-statement guard blocks and tidy using and member order
- Normalize XML doc indentation and file endings
- Reorder BatteryMonitor test-data helpers and move the exclusion tests into
  their own region
- Carry the same formatting through the boiler config, control, entity and
  test files
This commit is contained in:
2026-11-30 11:52:06 +02:00
parent cf8c9434c8
commit 24729ee267
165 changed files with 2513 additions and 2470 deletions
+47 -97
View File
@@ -18,19 +18,19 @@ namespace BoilerMonitorManager;
[NetDaemonApp]
public sealed class BoilerMonitorInit
{
private readonly ILogger<BoilerMonitorInit> _logger;
private readonly IHaContext _haContext;
private readonly IScheduler _scheduler;
private readonly IMqttEntityManager _mqttEntityManager;
private readonly IBoilerControlService _boilerControlService;
private readonly IBoilerRunTimeTracker _tracker;
private readonly IBoilerMonitorEntityService _entityService;
private readonly IWaterReadyService _waterReadyService;
private readonly IHaContext _haContext;
private readonly ILogger<BoilerMonitorInit> _logger;
private readonly IMqttEntityManager _mqttEntityManager;
private readonly BoilerMonitorOptions _options;
private readonly IScheduler _scheduler;
private readonly TimeProvider _timeProvider;
private bool _lastWaterReady;
private readonly IBoilerRunTimeTracker _tracker;
private readonly IWaterReadyService _waterReadyService;
private volatile bool _cleanedUp;
private bool _lastWaterReady;
private DateTimeOffset? _lastWaterReadyNotificationSentAt;
public BoilerMonitorInit(
@@ -55,7 +55,7 @@ public sealed class BoilerMonitorInit
waterReadyService,
options,
timeProvider,
startBackgroundScheduling: true)
true)
{
}
@@ -83,10 +83,7 @@ public sealed class BoilerMonitorInit
_options = options.Value;
_timeProvider = timeProvider;
if (startBackgroundScheduling)
{
_ = InitializeAndScheduleAsync();
}
if (startBackgroundScheduling) _ = InitializeAndScheduleAsync();
}
private async Task InitializeAndScheduleAsync()
@@ -133,17 +130,13 @@ public sealed class BoilerMonitorInit
{
_tracker.RestoreFromSnapshot();
if (persistedCooldown.HasValue)
{
_waterReadyService.RestoreCooldownState(persistedCooldown.Value);
}
if (persistedCooldown.HasValue) _waterReadyService.RestoreCooldownState(persistedCooldown.Value);
await _entityService.ResetTransientEntitiesAsync();
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("BoilerMonitor state restored from HA entities: runtime={Runtime}, sessions={Sessions}",
_logger.LogInformation(
"BoilerMonitor state restored from HA entities: runtime={Runtime}, sessions={Sessions}",
persisted.AccumulatedRunTime, persisted.SessionCount);
}
}
else
{
@@ -174,11 +167,11 @@ 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);
}
_logger.LogInformation("Scheduling BoilerMonitor polling every {Interval}s, first at {Time}",
DefaultPollIntervalSeconds, nextPollTime);
_scheduler.RunEvery(TimeSpan.FromSeconds(DefaultPollIntervalSeconds), nextPollTime, () => _ = PollAndUpdateAsync());
_scheduler.RunEvery(TimeSpan.FromSeconds(DefaultPollIntervalSeconds), nextPollTime,
() => _ = PollAndUpdateAsync());
}
private void ScheduleMidnightReset()
@@ -207,10 +200,7 @@ public sealed class BoilerMonitorInit
try
{
var switchState = _haContext.GetState(SkipPriceCapEntityId);
if (!string.Equals(switchState?.State, SwitchOnState, StringComparison.OrdinalIgnoreCase))
{
return;
}
if (!string.Equals(switchState?.State, SwitchOnState, StringComparison.OrdinalIgnoreCase)) return;
_haContext.CallService("notify", "mobile_app_marius_phone", null, new
{
@@ -232,10 +222,7 @@ public sealed class BoilerMonitorInit
skipPriceCapSwitch.StateChanges()
.Subscribe(e =>
{
if (e.Old?.State == e.New?.State)
{
return;
}
if (e.Old?.State == e.New?.State) return;
_logger.LogInformation("Skip price cap switch changed, triggering poll");
_ = PollAndUpdateAsync();
@@ -248,10 +235,7 @@ public sealed class BoilerMonitorInit
autoManagementSwitch.StateChanges()
.Subscribe(e =>
{
if (e.Old?.State == e.New?.State)
{
return;
}
if (e.Old?.State == e.New?.State) return;
_logger.LogInformation("Automatic boiler control switch changed, triggering poll");
_ = PollAndUpdateAsync();
@@ -264,15 +248,9 @@ public sealed class BoilerMonitorInit
showerStateSensor.StateChanges()
.Subscribe(e =>
{
if (!string.Equals(e.New?.State, ShowerActiveState, StringComparison.OrdinalIgnoreCase))
{
return;
}
if (!string.Equals(e.New?.State, ShowerActiveState, StringComparison.OrdinalIgnoreCase)) return;
if (!_waterReadyService.IsInCooldown)
{
return;
}
if (!_waterReadyService.IsInCooldown) return;
_logger.LogInformation("Shower detected as active, resetting water ready cooldown");
_waterReadyService.ResetCooldown();
@@ -312,9 +290,7 @@ 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)
@@ -344,9 +320,7 @@ 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)
@@ -385,22 +359,21 @@ public sealed class BoilerMonitorInit
if (!config.IsFullyConfigured)
{
await _entityService.SetStatusAsync(StatusAwaitingConfiguration);
_logger.LogWarning("BoilerMonitor not fully configured (power={Power}, switch={Switch}, interval={Interval}, threshold={Threshold}). Awaiting configuration",
_logger.LogWarning(
"BoilerMonitor not fully configured (power={Power}, switch={Switch}, interval={Interval}, threshold={Threshold}). Awaiting configuration",
config.BoilerPowerEntityId, config.BoilerSwitchEntityId,
config.PollIntervalSeconds, config.HeatingPowerThresholdWatts);
return;
}
var boilerPowerWatts = ReadSensorDouble(config.BoilerPowerEntityId!);
var boilerSwitchState = _haContext.GetState(config.BoilerSwitchEntityId!)?.State;
var isHeating = boilerPowerWatts.HasValue && boilerPowerWatts.Value >= config.HeatingPowerThresholdWatts!.Value;
var isHeating = boilerPowerWatts.HasValue &&
boilerPowerWatts.Value >= config.HeatingPowerThresholdWatts!.Value;
_tracker.RecordPollResult();
if (isHeating)
{
_waterReadyService.RecordHeatingObserved();
}
if (isHeating) _waterReadyService.RecordHeatingObserved();
var cheapestIntervalsState = _haContext.GetState(NordPoolCheapestIntervalsEntityId);
var isNowCheap = ReadAttributeBool(cheapestIntervalsState, "is_now_cheap");
@@ -413,7 +386,8 @@ public sealed class BoilerMonitorInit
var dailyHours = ReadSensorDouble(BoilerDailyHoursEntityId) ?? 1.0;
var waterReady = _waterReadyService.IsWaterReady(boilerSwitchState, boilerPowerWatts, config.HeatingPowerThresholdWatts!.Value);
var waterReady = _waterReadyService.IsWaterReady(boilerSwitchState, boilerPowerWatts,
config.HeatingPowerThresholdWatts!.Value);
if (!_lastWaterReady && waterReady && !IsWithinNotificationCooldown())
{
@@ -425,16 +399,14 @@ public sealed class BoilerMonitorInit
_lastWaterReadyNotificationSentAt = _timeProvider.GetUtcNow();
_logger.LogInformation("Water ready notification sent");
}
_lastWaterReady = waterReady;
var snapshot = _tracker.GetSnapshot();
var budgetTimeSpan = TimeSpan.FromHours(dailyHours);
var remainingTime = budgetTimeSpan - snapshot.AccumulatedRunTime;
if (remainingTime < TimeSpan.Zero)
{
remainingTime = TimeSpan.Zero;
}
if (remainingTime < TimeSpan.Zero) remainingTime = TimeSpan.Zero;
var budgetPercentage = budgetTimeSpan.TotalSeconds > 0
? snapshot.AccumulatedRunTime.TotalSeconds / budgetTimeSpan.TotalSeconds * 100.0
@@ -452,21 +424,16 @@ public sealed class BoilerMonitorInit
budgetOverride);
var autoManagementState = _haContext.GetState(AutoManagementEntityId)?.State;
var autoManagementEnabled = !string.Equals(autoManagementState, SwitchOffState, StringComparison.OrdinalIgnoreCase);
var autoManagementEnabled =
!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);
}
}
var context = new BoilerMonitorUpdateContext
{
@@ -479,16 +446,15 @@ public sealed class BoilerMonitorInit
WaterReady = waterReady,
BoilerSwitchState = boilerSwitchState,
BoilerPowerWatts = boilerPowerWatts,
CooldownSince = _waterReadyService.WaterReadySince,
CooldownSince = _waterReadyService.WaterReadySince
};
await _entityService.UpdateEntitiesAsync(context);
if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.LogDebug("Poll complete: power={Power}W, heating={Heating}, runtime={Runtime}, budget={Budget}%",
_logger.LogDebug(
"Poll complete: power={Power}W, heating={Heating}, runtime={Runtime}, budget={Budget}%",
boilerPowerWatts, isHeating, snapshot.AccumulatedRunTime, budgetPercentage);
}
}
catch (Exception ex)
{
@@ -522,22 +488,18 @@ public sealed class BoilerMonitorInit
int? pollInterval = null;
var pollIntervalState = _haContext.GetState(ConfigPollIntervalEntityId)?.State;
if (!string.IsNullOrWhiteSpace(pollIntervalState)
&& double.TryParse(pollIntervalState, CultureInfo.InvariantCulture, out var pollIntervalValue)
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;
if (!string.IsNullOrWhiteSpace(thresholdState)
&& double.TryParse(thresholdState, CultureInfo.InvariantCulture, out var thresholdValue)
if (!string.IsNullOrWhiteSpace(thresholdState)
&& double.TryParse(thresholdState, CultureInfo.InvariantCulture, out var thresholdValue)
&& thresholdValue > 0)
{
heatingThreshold = thresholdValue;
}
return new BoilerMonitorConfig
{
@@ -551,26 +513,19 @@ public sealed class BoilerMonitorInit
private double? ReadSensorDouble(string entityId)
{
var state = _haContext.GetState(entityId);
if (state?.State is null or "unavailable" or "unknown")
{
return null;
}
if (state?.State is null or "unavailable" or "unknown") return null;
return double.TryParse(state.State, CultureInfo.InvariantCulture, out var value) ? value : null;
}
private static bool ReadAttributeBool(EntityState? entityState, string attributeName)
{
if (entityState?.Attributes is not IDictionary<string, object> attributes)
{
return false;
}
if (entityState?.Attributes is not IDictionary<string, object> attributes) return false;
try
{
if (attributes.TryGetValue(attributeName, out var value))
{
return value switch
{
bool b => b,
@@ -581,7 +536,6 @@ public sealed class BoilerMonitorInit
bool.TryParse(jsonElement.GetString(), out var jsonParsed) && jsonParsed,
_ => false
};
}
}
catch
{
@@ -593,13 +547,9 @@ public sealed class BoilerMonitorInit
private bool IsWithinNotificationCooldown()
{
if (_lastWaterReadyNotificationSentAt is null)
{
return false;
}
if (_lastWaterReadyNotificationSentAt is null) return false;
var elapsed = _timeProvider.GetUtcNow() - _lastWaterReadyNotificationSentAt.Value;
return elapsed < WaterReadyNotificationCooldown;
}
}
}