Apply code formatting cleanup across the monitor projects

- Wrap using directives in `#region` blocks across the Battery, Boiler and NordPool sources and tests
- Expand single-statement guards and loops into braced blocks
- Realign wrapped method arguments, chained calls and continuations
- Replace target-typed `new()` with explicit generic construction and empty string literals with `string.Empty`
- Flatten the boiler config expression and reindent the remaining touched files
This commit is contained in:
2026-12-01 12:33:31 +02:00
parent 77458383d1
commit f919d6b25b
115 changed files with 3115 additions and 1959 deletions
+154 -98
View File
@@ -1,3 +1,5 @@
#region
using System.Globalization;
using System.Reactive.Concurrency;
using System.Text.Json;
@@ -13,6 +15,8 @@ using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
using static BoilerMonitor.Models.BoilerMonitorConsts;
#endregion
namespace BoilerMonitorManager;
[NetDaemonApp]
@@ -45,17 +49,17 @@ public sealed class BoilerMonitorInit
IOptions<BoilerMonitorOptions> options,
TimeProvider timeProvider)
: this(
haContext,
logger,
scheduler,
mqttEntityManager,
boilerControlService,
tracker,
entityService,
waterReadyService,
options,
timeProvider,
true)
haContext,
logger,
scheduler,
mqttEntityManager,
boilerControlService,
tracker,
entityService,
waterReadyService,
options,
timeProvider,
true)
{
}
@@ -83,7 +87,10 @@ public sealed class BoilerMonitorInit
_options = options.Value;
_timeProvider = timeProvider;
if (startBackgroundScheduling) _ = InitializeAndScheduleAsync();
if (startBackgroundScheduling)
{
_ = InitializeAndScheduleAsync();
}
}
private async Task InitializeAndScheduleAsync()
@@ -130,14 +137,18 @@ 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}",
persisted.AccumulatedRunTime, persisted.SessionCount);
"BoilerMonitor state restored from HA entities: runtime={Runtime}, sessions={Sessions}",
persisted.AccumulatedRunTime, persisted.SessionCount);
}
}
else
@@ -156,6 +167,7 @@ public sealed class BoilerMonitorInit
catch (Exception ex)
{
_logger.LogError(ex, "Error initializing BoilerMonitor");
throw;
}
}
@@ -171,105 +183,126 @@ public sealed class BoilerMonitorInit
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("Scheduling BoilerMonitor polling every {Interval}s, first at {Time}",
DefaultPollIntervalSeconds, nextPollTime);
DefaultPollIntervalSeconds, nextPollTime);
}
_scheduler.RunEvery(TimeSpan.FromSeconds(DefaultPollIntervalSeconds), nextPollTime,
() => _ = PollAndUpdateAsync());
() => _ = PollAndUpdateAsync());
}
private void ScheduleMidnightReset()
{
_scheduler.ScheduleCron("0 0 * * *", () =>
{
try
{
_logger.LogInformation("Midnight reset: clearing boiler run time tracker and water ready cooldown");
_tracker.Reset();
_waterReadyService.ResetCooldown();
_lastWaterReadyNotificationSentAt = null;
_ = _entityService.ResetEntitiesAsync();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error during midnight reset");
}
});
{
try
{
_logger.LogInformation("Midnight reset: clearing boiler run time tracker and water ready cooldown");
_tracker.Reset();
_waterReadyService.ResetCooldown();
_lastWaterReadyNotificationSentAt = null;
_ = _entityService.ResetEntitiesAsync();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error during midnight reset");
}
});
}
private void ScheduleEndOfDayReminder()
{
_scheduler.ScheduleCron("0 22 * * *", () =>
{
try
{
var switchState = _haContext.GetState(SkipPriceCapEntityId);
if (!string.Equals(switchState?.State, SwitchOnState, StringComparison.OrdinalIgnoreCase)) return;
{
try
{
var switchState = _haContext.GetState(SkipPriceCapEntityId);
_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)
{
_logger.LogError(ex, "Error checking skip price cap reminder");
}
});
if (!string.Equals(switchState?.State, SwitchOnState, StringComparison.OrdinalIgnoreCase))
{
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)
{
_logger.LogError(ex, "Error checking skip price cap reminder");
}
});
}
private void SubscribeToSkipPriceCapChanges()
{
var skipPriceCapSwitch = new Entity(_haContext, SkipPriceCapEntityId);
skipPriceCapSwitch.StateChanges()
.Subscribe(e =>
{
if (e.Old?.State == e.New?.State) return;
_logger.LogInformation("Skip price cap switch changed, triggering poll");
_ = PollAndUpdateAsync();
});
skipPriceCapSwitch.StateChanges()
.Subscribe(e =>
{
if (e.Old?.State == e.New?.State)
{
return;
}
_logger.LogInformation("Skip price cap switch changed, triggering poll");
_ = PollAndUpdateAsync();
});
}
private void SubscribeToAutoManagementChanges()
{
var autoManagementSwitch = new Entity(_haContext, AutoManagementEntityId);
autoManagementSwitch.StateChanges()
.Subscribe(e =>
{
if (e.Old?.State == e.New?.State) return;
_logger.LogInformation("Automatic boiler control switch changed, triggering poll");
_ = PollAndUpdateAsync();
});
autoManagementSwitch.StateChanges()
.Subscribe(e =>
{
if (e.Old?.State == e.New?.State)
{
return;
}
_logger.LogInformation("Automatic boiler control switch changed, triggering poll");
_ = PollAndUpdateAsync();
});
}
private void SubscribeToShowerState()
{
var showerStateSensor = new Entity(_haContext, ShowerStateEntityId);
showerStateSensor.StateChanges()
.Subscribe(e =>
{
if (!string.Equals(e.New?.State, ShowerActiveState, StringComparison.OrdinalIgnoreCase)) return;
.Subscribe(e =>
{
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();
});
_logger.LogInformation("Shower detected as active, resetting water ready cooldown");
_waterReadyService.ResetCooldown();
});
}
private void SubscribeToCleanupButton()
{
var cleanupButton = new Entity(_haContext, CleanupButtonEntityId);
cleanupButton.StateChanges()
.Subscribe(_ =>
{
_logger.LogInformation("Cleanup button pressed, removing all BoilerMonitor entities");
Task.Run(HandleCleanupAsync);
});
.Subscribe(_ =>
{
_logger.LogInformation("Cleanup button pressed, removing all BoilerMonitor entities");
Task.Run(HandleCleanupAsync);
});
}
private async Task SubscribeToConfigCommandsAsync()
@@ -359,6 +392,7 @@ public sealed class BoilerMonitorInit
if (_cleanedUp)
{
_logger.LogDebug("BoilerMonitor is cleaned up, skipping poll");
return;
}
@@ -369,21 +403,27 @@ 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",
config.BoilerPowerEntityId, config.BoilerSwitchEntityId,
config.PollIntervalSeconds, config.HeatingPowerThresholdWatts);
"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;
_tracker.RecordPollResult();
if (isHeating) _waterReadyService.RecordHeatingObserved();
if (isHeating)
{
_waterReadyService.RecordHeatingObserved();
}
var cheapestIntervalsState = _haContext.GetState(NordPoolCheapestIntervalsEntityId);
var isNowCheap = ReadAttributeBool(cheapestIntervalsState, "is_now_cheap");
@@ -397,7 +437,7 @@ public sealed class BoilerMonitorInit
var dailyHours = ReadSensorDouble(BoilerDailyHoursEntityId) ?? 1.0;
var waterReady = _waterReadyService.IsWaterReady(boilerSwitchState, boilerPowerWatts,
config.HeatingPowerThresholdWatts!.Value);
config.HeatingPowerThresholdWatts!.Value);
if (!_lastWaterReady && waterReady && !IsWithinNotificationCooldown())
{
@@ -406,6 +446,7 @@ public sealed class BoilerMonitorInit
message = "Hot water is ready.",
title = "Boiler"
});
_lastWaterReadyNotificationSentAt = _timeProvider.GetUtcNow();
_logger.LogInformation("Water ready notification sent");
}
@@ -416,24 +457,28 @@ public sealed class BoilerMonitorInit
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
: 0.0;
? snapshot.AccumulatedRunTime.TotalSeconds / budgetTimeSpan.TotalSeconds * 100.0
: 0.0;
var budgetExhausted = snapshot.AccumulatedRunTime >= budgetTimeSpan;
var effectiveIsNowCheap = isNowCheap || skipPriceCap;
var boilerAction = _boilerControlService.DetermineAction(
effectiveIsNowCheap,
waterReady,
boilerSwitchState,
budgetExhausted,
budgetOverride);
effectiveIsNowCheap,
waterReady,
boilerSwitchState,
budgetExhausted,
budgetOverride);
var autoManagementState = _haContext.GetState(AutoManagementEntityId)?.State;
var autoManagementEnabled =
!string.Equals(autoManagementState, SwitchOffState, StringComparison.OrdinalIgnoreCase);
@@ -468,8 +513,8 @@ public sealed class BoilerMonitorInit
if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.LogDebug(
"Poll complete: power={Power}W, heating={Heating}, runtime={Runtime}, budget={Budget}%",
boilerPowerWatts, isHeating, snapshot.AccumulatedRunTime, budgetPercentage);
"Poll complete: power={Power}W, heating={Heating}, runtime={Runtime}, budget={Budget}%",
boilerPowerWatts, isHeating, snapshot.AccumulatedRunTime, budgetPercentage);
}
}
catch (Exception ex)
@@ -485,12 +530,17 @@ public sealed class BoilerMonitorInit
case BoilerAction.TurnOn:
_haContext.CallService("switch", "turn_on", ServiceTarget.FromEntity(switchEntityId));
_waterReadyService.NotifyTurnedOn();
break;
case BoilerAction.TurnOff:
_haContext.CallService("switch", "turn_off", ServiceTarget.FromEntity(switchEntityId));
break;
case BoilerAction.NoChange:
break;
default:
throw new ArgumentOutOfRangeException(nameof(action), action, null);
}
@@ -504,9 +554,7 @@ 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)
&& pollIntervalValue > 0)
if (!string.IsNullOrWhiteSpace(pollIntervalState) && double.TryParse(pollIntervalState, CultureInfo.InvariantCulture, out var pollIntervalValue) && pollIntervalValue > 0)
{
pollInterval = (int)pollIntervalValue;
}
@@ -514,9 +562,7 @@ public sealed class BoilerMonitorInit
double? heatingThreshold = null;
var thresholdState = _haContext.GetState(ConfigHeatingThresholdEntityId)?.State;
if (!string.IsNullOrWhiteSpace(thresholdState)
&& double.TryParse(thresholdState, CultureInfo.InvariantCulture, out var thresholdValue)
&& thresholdValue > 0)
if (!string.IsNullOrWhiteSpace(thresholdState) && double.TryParse(thresholdState, CultureInfo.InvariantCulture, out var thresholdValue) && thresholdValue > 0)
{
heatingThreshold = thresholdValue;
}
@@ -534,14 +580,20 @@ public sealed class BoilerMonitorInit
{
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
{
@@ -569,9 +621,13 @@ 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;
}
}