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
+18 -17
View File
@@ -14,33 +14,34 @@ public sealed class BoilerConfigReader(IHaContext haContext, ILogger<BoilerConfi
public BoilerConfig ReadConfig()
{
var dailyHoursState = haContext.GetState(BoilerDailyHoursEntityId)?.State;
var dailyHours = double.TryParse(dailyHoursState, NumberStyles.Any, CultureInfo.InvariantCulture, out var dh) ? dh : DefaultDailyHours;
var dailyHours = double.TryParse(dailyHoursState, NumberStyles.Any, CultureInfo.InvariantCulture, out var dh)
? dh
: DefaultDailyHours;
var intervalCount = (int)(dailyHours * IntervalsPerHour);
if (intervalCount <= 0)
{
intervalCount = IntervalsPerHour;
}
if (intervalCount <= 0) intervalCount = IntervalsPerHour;
var priceCapState = haContext.GetState(BoilerPriceCapEntityId)?.State;
var priceCap = double.TryParse(priceCapState, NumberStyles.Any, CultureInfo.InvariantCulture, out var pc) && pc > 0 ? pc : double.MaxValue;
var priceCap =
double.TryParse(priceCapState, NumberStyles.Any, CultureInfo.InvariantCulture, out var pc) && pc > 0
? pc
: double.MaxValue;
var deadline = DateTime.Today.AddDays(1);
var readyByState = haContext.GetState(BoilerReadyByEntityId)?.State;
if (!string.IsNullOrEmpty(readyByState) && TimeSpan.TryParse(readyByState, CultureInfo.InvariantCulture, out var readyByTime))
{
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);
}
logger.LogDebug(
"Boiler config: intervals={Intervals}, priceCap={Cap}, skipPriceCap={Skip}, deadline={Deadline}",
intervalCount, priceCap, skipPriceCap, deadline);
var config = new BoilerConfig
{
@@ -49,7 +50,7 @@ public sealed class BoilerConfigReader(IHaContext haContext, ILogger<BoilerConfi
Deadline = deadline,
SkipPriceCap = skipPriceCap
};
return config;
}
}
}
+9 -14
View File
@@ -23,9 +23,9 @@ 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);
}
logger.LogInformation(
"Boiler should turn ON — cheap interval active, water not ready, budget available (current state: {State})",
currentSwitchState);
return BoilerAction.TurnOn;
@@ -34,19 +34,17 @@ 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);
}
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})",
logger.LogDebug(
"Boiler state unchanged: {State} (cheap={Cheap}, waterReady={WaterReady}, budgetExhausted={BudgetExhausted})",
currentSwitchState, isNowCheap, waterReady, effectiveBudgetExhausted);
}
return BoilerAction.NoChange;
}
@@ -54,13 +52,10 @@ public sealed class BoilerControlService(ILogger<BoilerControlService> logger) :
private static string GetTurnOffReason(bool waterReady, bool effectiveBudgetExhausted)
{
if (waterReady)
{
return "water is already ready";
}
if (waterReady) return "water is already ready";
return effectiveBudgetExhausted
? "daily budget is exhausted"
: "not in a cheap interval";
}
}
}
@@ -8,21 +8,21 @@
</PropertyGroup>
<ItemGroup>
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
<_Parameter1>BoilerMonitor.Manager.Tests</_Parameter1>
</AssemblyAttribute>
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
<_Parameter1>BoilerMonitor.Manager.Tests</_Parameter1>
</AssemblyAttribute>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\HomeAssistant.Entities\HomeAssistant.Entities.csproj" />
<ProjectReference Include="..\BoilerMonitor.Models\BoilerMonitor.Models.csproj" />
<ProjectReference Include="..\NordPool.Models\NordPool.Models.csproj" />
<ProjectReference Include="..\HomeAssistant.Entities\HomeAssistant.Entities.csproj"/>
<ProjectReference Include="..\BoilerMonitor.Models\BoilerMonitor.Models.csproj"/>
<ProjectReference Include="..\NordPool.Models\NordPool.Models.csproj"/>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="11.0.0" />
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.43.1" />
<PackageReference Include="NetDaemon.HassModel" Version="26.43.1" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="11.0.0"/>
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.43.1"/>
<PackageReference Include="NetDaemon.HassModel" Version="26.43.1"/>
</ItemGroup>
</Project>
@@ -1,4 +1,5 @@
using System.Globalization;
using System.Text.Json;
using BoilerMonitor.Models;
using BoilerMonitorManager.Interface;
using BoilerMonitorManager.Models;
@@ -33,14 +34,6 @@ public sealed class BoilerMonitorEntityService(
AutoManagementEntityId
];
private static object CreateDeviceBlock() => new
{
identifiers = new[] { DeviceIdentifier },
name = DeviceName,
model = DeviceName,
manufacturer = DeviceManufacturer
};
public async Task CreateEntitiesAsync(CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
@@ -52,9 +45,7 @@ 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)
@@ -149,13 +140,13 @@ public sealed class BoilerMonitorEntityService(
var skipPriceCapState = haContext.GetState(SkipPriceCapEntityId)?.State;
var budgetOverrideState = haContext.GetState(BudgetOverrideEntityId)?.State;
if (!TryParseEntitySeconds(runtimeState, out var runtimeSeconds) || !TryParseEntityInt(sessionCountState, out var sessionCount))
if (!TryParseEntitySeconds(runtimeState, out var runtimeSeconds) ||
!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})",
logger.LogInformation(
"No valid persisted BoilerMonitor state found in HA entities (runtime={Runtime}, sessions={Sessions})",
runtimeState, sessionCountState);
}
return null;
}
@@ -168,10 +159,10 @@ 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);
}
logger.LogInformation(
"Restored persisted BoilerMonitor state: runtime={Runtime}, sessions={Sessions}, skipPriceCap={SkipPriceCap}, budgetOverride={BudgetOverride}",
persisted.AccumulatedRunTime, persisted.SessionCount, persisted.SkipPriceCapState,
persisted.BudgetOverrideState);
return persisted;
}
@@ -187,6 +178,51 @@ public sealed class BoilerMonitorEntityService(
await UpdateStatusAsync(status).ConfigureAwait(false);
}
public DateTimeOffset? ReadPersistedCooldownTimestamp()
{
try
{
var entity = haContext.GetState(WaterReadyEntityId);
if (entity?.Attributes is not IDictionary<string, object> attributes) return null;
if (!attributes.TryGetValue("cooldown_since", out var value)) return null;
var stringValue = value switch
{
string s => s,
JsonElement { ValueKind: JsonValueKind.String } jsonElement =>
jsonElement.GetString(),
_ => null
};
if (stringValue is not null &&
DateTimeOffset.TryParse(stringValue, CultureInfo.InvariantCulture,
DateTimeStyles.RoundtripKind, out var parsed))
{
if (logger.IsEnabled(LogLevel.Information))
logger.LogInformation("Read persisted cooldown timestamp: {CooldownSince}", parsed);
return parsed;
}
}
catch (Exception ex)
{
logger.LogError(ex, "Error reading persisted cooldown timestamp");
}
return null;
}
private static object CreateDeviceBlock()
{
return new
{
identifiers = new[] { DeviceIdentifier },
name = DeviceName,
model = DeviceName,
manufacturer = DeviceManufacturer
};
}
private static bool TryParseEntitySeconds(string? state, out double seconds)
{
seconds = 0;
@@ -194,7 +230,7 @@ public sealed class BoilerMonitorEntityService(
&& state is not ("unavailable" or "unknown")
&& double.TryParse(state, CultureInfo.InvariantCulture, out seconds)
&& seconds >= 0;
return tryParseEntitySeconds;
}
@@ -205,7 +241,7 @@ public sealed class BoilerMonitorEntityService(
&& state is not ("unavailable" or "unknown")
&& int.TryParse(state, CultureInfo.InvariantCulture, out value)
&& value >= 0;
return tryParseEntityInt;
}
@@ -235,7 +271,8 @@ public sealed class BoilerMonitorEntityService(
device
}
},
new BoilerMonitorEntity("number", "boilermonitor_config_heating_threshold", "Heating power threshold (watts)")
new BoilerMonitorEntity("number", "boilermonitor_config_heating_threshold",
"Heating power threshold (watts)")
{
AdditionalConfig = new
{
@@ -265,11 +302,13 @@ public sealed class BoilerMonitorEntityService(
},
new BoilerMonitorEntity("sensor", "boilermonitor_today_runtime", "Today runtime")
{
AdditionalConfig = new { unit_of_measurement = "s", icon = "mdi:timer", device_class = "duration", device }
AdditionalConfig = new
{ unit_of_measurement = "s", icon = "mdi:timer", device_class = "duration", device }
},
new BoilerMonitorEntity("sensor", "boilermonitor_remaining_time", "Remaining budget time")
{
AdditionalConfig = new { unit_of_measurement = "s", icon = "mdi:timer-sand", device_class = "duration", device }
AdditionalConfig = new
{ unit_of_measurement = "s", icon = "mdi:timer-sand", device_class = "duration", device }
},
new BoilerMonitorEntity("sensor", "boilermonitor_budget_percentage", "Budget usage")
{
@@ -401,7 +440,8 @@ public sealed class BoilerMonitorEntityService(
private async Task UpdateTodayRuntimeAsync(TimeSpan runTime, string formatted, string timestamp)
{
await SetEntityStateSafe(TodayRuntimeEntityId, ((int)runTime.TotalSeconds).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
await SetEntityStateSafe(TodayRuntimeEntityId,
((int)runTime.TotalSeconds).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
await SetEntityAttributesSafe(TodayRuntimeEntityId, new
{
formatted,
@@ -410,10 +450,12 @@ public sealed class BoilerMonitorEntityService(
}).ConfigureAwait(false);
}
private async Task UpdateRemainingTimeAsync(TimeSpan remaining, string formatted, double budgetHours, string timestamp)
private async Task UpdateRemainingTimeAsync(TimeSpan remaining, string formatted, double budgetHours,
string timestamp)
{
var remainingSeconds = Math.Max(0, (int)remaining.TotalSeconds);
await SetEntityStateSafe(RemainingTimeEntityId, remainingSeconds.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
await SetEntityStateSafe(RemainingTimeEntityId, remainingSeconds.ToString(CultureInfo.InvariantCulture))
.ConfigureAwait(false);
await SetEntityAttributesSafe(RemainingTimeEntityId, new
{
formatted,
@@ -426,7 +468,8 @@ public sealed class BoilerMonitorEntityService(
private async Task UpdateBudgetPercentageAsync(double percentage, string timestamp)
{
var clampedPercentage = Math.Clamp(percentage, 0, 100);
await SetEntityStateSafe(BudgetPercentageEntityId, ((int)clampedPercentage).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
await SetEntityStateSafe(BudgetPercentageEntityId,
((int)clampedPercentage).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
await SetEntityAttributesSafe(BudgetPercentageEntityId, new
{
unit_of_measurement = "%",
@@ -442,7 +485,8 @@ public sealed class BoilerMonitorEntityService(
private async Task UpdateSessionCountAsync(int sessionCount, string timestamp)
{
await SetEntityStateSafe(SessionCountEntityId, sessionCount.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
await SetEntityStateSafe(SessionCountEntityId, sessionCount.ToString(CultureInfo.InvariantCulture))
.ConfigureAwait(false);
await SetEntityAttributesSafe(SessionCountEntityId, new
{
friendly_name = "Heating sessions today",
@@ -450,57 +494,13 @@ public sealed class BoilerMonitorEntityService(
}).ConfigureAwait(false);
}
public DateTimeOffset? ReadPersistedCooldownTimestamp()
{
try
{
var entity = haContext.GetState(WaterReadyEntityId);
if (entity?.Attributes is not IDictionary<string, object> attributes)
{
return null;
}
if (!attributes.TryGetValue("cooldown_since", out var value))
{
return null;
}
var stringValue = value switch
{
string s => s,
System.Text.Json.JsonElement { ValueKind: System.Text.Json.JsonValueKind.String } jsonElement =>
jsonElement.GetString(),
_ => null
};
if (stringValue is not null &&
DateTimeOffset.TryParse(stringValue, CultureInfo.InvariantCulture,
DateTimeStyles.RoundtripKind, out var parsed))
{
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation("Read persisted cooldown timestamp: {CooldownSince}", parsed);
}
return parsed;
}
}
catch (Exception ex)
{
logger.LogError(ex, "Error reading persisted cooldown timestamp");
}
return null;
}
private async Task SetEntityStateSafe(string entityId, string state)
{
try
{
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,9 +514,7 @@ 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)
{
@@ -528,7 +526,7 @@ public sealed class BoilerMonitorEntityService(
{
var totalHours = (int)ts.TotalHours;
var minutes = ts.Minutes;
return $"{totalHours}h {minutes}m";
}
}
}
+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;
}
}
}
@@ -14,10 +14,7 @@ public static class BoilerMonitorServiceRegistration
.GetSection(BoilerMonitorOptions.SectionName)
.Get<BoilerMonitorOptions>() ?? new BoilerMonitorOptions();
if (!options.Enabled)
{
return services;
}
if (!options.Enabled) return services;
services
.AddNetDaemonApp<BoilerMonitorInit>()
@@ -28,4 +25,4 @@ public static class BoilerMonitorServiceRegistration
return services;
}
}
}
@@ -7,7 +7,6 @@ public class BoilerRunTimeTracker : IBoilerRunTimeTracker
{
public void RecordPollResult()
{
}
public RunTimeSnapshot GetSnapshot()
@@ -21,11 +20,9 @@ public class BoilerRunTimeTracker : IBoilerRunTimeTracker
public void Reset()
{
}
public void RestoreFromSnapshot()
{
}
}
@@ -10,4 +10,4 @@ public interface IBoilerControlService
string? currentSwitchState,
bool budgetExhausted,
bool budgetOverride);
}
}
@@ -12,4 +12,4 @@ public interface IBoilerMonitorEntityService
Task SetStatusAsync(string status);
PersistedBoilerState? ReadPersistedState();
DateTimeOffset? ReadPersistedCooldownTimestamp();
}
}
@@ -8,4 +8,4 @@ public interface IBoilerRunTimeTracker
RunTimeSnapshot GetSnapshot();
void Reset();
void RestoreFromSnapshot();
}
}
@@ -2,11 +2,11 @@ namespace BoilerMonitorManager.Interface;
public interface IWaterReadyService
{
bool IsWaterReady(string? switchState, double? powerWatts, double heatingThresholdWatts);
bool IsInCooldown { get; }
DateTimeOffset? WaterReadySince { get; }
bool IsWaterReady(string? switchState, double? powerWatts, double heatingThresholdWatts);
void NotifyTurnedOn();
void RecordHeatingObserved();
void ResetCooldown();
void RestoreCooldownState(DateTimeOffset waterReadySince);
}
}
@@ -12,4 +12,4 @@ public record BoilerMonitorConfig
!string.IsNullOrWhiteSpace(BoilerSwitchEntityId) &&
PollIntervalSeconds is > 0 &&
HeatingPowerThresholdWatts is > 0;
}
}
@@ -7,8 +7,8 @@ public sealed class BoilerMonitorOptions
public bool Enabled { get; init; } = true;
/// <summary>
/// When true, removes existing BoilerMonitor MQTT entities before recreating them on app startup.
/// Manual cleanup (e.g. HA button) is not affected.
/// When true, removes existing BoilerMonitor MQTT entities before recreating them on app startup.
/// Manual cleanup (e.g. HA button) is not affected.
/// </summary>
public bool CleanupEntitiesOnStartup { get; init; } = true;
}
}
@@ -12,4 +12,4 @@ public record BoilerMonitorUpdateContext
public required string? BoilerSwitchState { get; init; }
public required double? BoilerPowerWatts { get; init; }
public required DateTimeOffset? CooldownSince { get; init; }
}
}
@@ -6,4 +6,4 @@ public record PersistedBoilerState
public required int SessionCount { get; init; }
public required string? SkipPriceCapState { get; init; }
public required string? BudgetOverrideState { get; init; }
}
}
@@ -4,4 +4,4 @@ public record RunTimeSnapshot
{
public required TimeSpan AccumulatedRunTime { get; init; }
public required int SessionCount { get; init; }
}
}
+28 -38
View File
@@ -8,9 +8,9 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
{
private const string SwitchOnState = "on";
private readonly Lock _lock = new();
private DateTimeOffset? _waterReadySince;
private bool _hasObservedHeating;
private int _consecutiveBelowThresholdCount;
private bool _hasObservedHeating;
private DateTimeOffset? _waterReadySince;
public bool IsInCooldown
{
@@ -41,32 +41,24 @@ 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);
}
logger.LogDebug("Water ready cooldown active (since {Since}), suppressing turn-on",
_waterReadySince);
return true;
}
}
if (switchState is null || powerWatts is null)
{
return false;
}
if (switchState is null || powerWatts is null) return false;
if (!string.Equals(switchState, SwitchOnState, StringComparison.OrdinalIgnoreCase))
{
return false;
}
if (!string.Equals(switchState, SwitchOnState, StringComparison.OrdinalIgnoreCase)) return false;
lock (_lock)
{
if (!_hasObservedHeating)
{
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("Ignoring power reading ({PowerWatts}W) — boiler has not been observed heating yet", powerWatts.Value);
}
logger.LogDebug("Ignoring power reading ({PowerWatts}W) — boiler has not been observed heating yet",
powerWatts.Value);
return false;
}
@@ -81,20 +73,20 @@ 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);
}
logger.LogDebug(
"Below-threshold reading {Count}/{Required} ({PowerWatts}W), waiting for confirmation",
_consecutiveBelowThresholdCount, BoilerMonitorConsts.ConsecutiveReadingsRequired,
powerWatts.Value);
return false;
}
_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);
}
logger.LogInformation(
"Water detected as ready after {Count} consecutive readings, cooldown active until shower or midnight reset",
_consecutiveBelowThresholdCount);
return true;
}
@@ -108,17 +100,15 @@ public sealed class WaterReadyService(ILogger<WaterReadyService> logger, TimePro
_consecutiveBelowThresholdCount = 0;
}
logger.LogDebug("Boiler turn-on recorded, awaiting first heating observation before water ready detection is enabled");
logger.LogDebug(
"Boiler turn-on recorded, awaiting first heating observation before water ready detection is enabled");
}
public void RecordHeatingObserved()
{
lock (_lock)
{
if (_hasObservedHeating)
{
return;
}
if (_hasObservedHeating) return;
_hasObservedHeating = true;
}
@@ -145,20 +135,20 @@ 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);
}
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);
}
}
}
private bool IsWithinCooldownPeriod() => _waterReadySince is not null;
}
private bool IsWithinCooldownPeriod()
{
return _waterReadySince is not null;
}
}