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
@@ -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";
}
}
}