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
@@ -11,8 +11,8 @@ public sealed class ExhaustFanControlService(
IHaContext haContext,
IOptions<ShowerMonitorOptions> options) : IExhaustFanControlService
{
private readonly ShowerMonitorOptions _options = options.Value;
private readonly Lock _lock = new();
private readonly ShowerMonitorOptions _options = options.Value;
private bool _fanTurnedOnByUs;
private DateTimeOffset? _showerEndedAt;
@@ -53,11 +53,9 @@ public sealed class ExhaustFanControlService(
if (_fanTurnedOnByUs)
{
var fanState = haContext.GetState(_options.ExhaustFanEntityId)?.State;
if (string.Equals(fanState, "on", StringComparison.OrdinalIgnoreCase))
{
haContext.CallService("switch", "turn_off", ServiceTarget.FromEntity(_options.ExhaustFanEntityId));
}
}
_fanTurnedOnByUs = false;
@@ -67,16 +65,10 @@ public sealed class ExhaustFanControlService(
private void TurnOnFanIfNeeded()
{
if (_fanTurnedOnByUs)
{
return;
}
if (_fanTurnedOnByUs) return;
var fanState = haContext.GetState(_options.ExhaustFanEntityId)?.State;
if (string.Equals(fanState, "on", StringComparison.OrdinalIgnoreCase))
{
return;
}
if (string.Equals(fanState, "on", StringComparison.OrdinalIgnoreCase)) return;
haContext.CallService("switch", "turn_on", ServiceTarget.FromEntity(_options.ExhaustFanEntityId));
_fanTurnedOnByUs = true;
@@ -84,21 +76,15 @@ public sealed class ExhaustFanControlService(
private void EvaluatePostShowerFanOff(DateTimeOffset timestamp)
{
if (!_fanTurnedOnByUs || !_showerEndedAt.HasValue)
{
return;
}
if (!_fanTurnedOnByUs || !_showerEndedAt.HasValue) return;
var elapsed = timestamp - _showerEndedAt.Value;
var runAfterDuration = TimeSpan.FromMinutes(_options.FanRunAfterShowerMinutes);
if (elapsed < runAfterDuration)
{
return;
}
if (elapsed < runAfterDuration) return;
haContext.CallService("switch", "turn_off", ServiceTarget.FromEntity(_options.ExhaustFanEntityId));
_fanTurnedOnByUs = false;
_showerEndedAt = null;
}
}
}
+11 -14
View File
@@ -10,7 +10,13 @@ public sealed class HumidityRateCalculator(int windowSize) : IHumidityRateCalcul
public double? PreviousReading
{
get { lock (_lock) { return _previousReading; } }
get
{
lock (_lock)
{
return _previousReading;
}
}
}
public void RecordReading(double humidity, DateTimeOffset timestamp)
@@ -20,10 +26,7 @@ public sealed class HumidityRateCalculator(int windowSize) : IHumidityRateCalcul
_readings.Enqueue((humidity, timestamp));
_previousReading = humidity;
while (_readings.Count > windowSize)
{
_readings.Dequeue();
}
while (_readings.Count > windowSize) _readings.Dequeue();
}
}
@@ -31,19 +34,13 @@ public sealed class HumidityRateCalculator(int windowSize) : IHumidityRateCalcul
{
lock (_lock)
{
if (_readings.Count < 2)
{
return 0.0;
}
if (_readings.Count < 2) return 0.0;
var oldest = _readings.Peek();
var newest = _readings.Last();
var elapsedMinutes = (newest.Timestamp - oldest.Timestamp).TotalMinutes;
if (elapsedMinutes <= 0)
{
return 0.0;
}
if (elapsedMinutes <= 0) return 0.0;
return (newest.Humidity - oldest.Humidity) / elapsedMinutes;
}
@@ -57,4 +54,4 @@ public sealed class HumidityRateCalculator(int windowSize) : IHumidityRateCalcul
_previousReading = null;
}
}
}
}
@@ -6,4 +6,4 @@ public interface IExhaustFanControlService
{
void Evaluate(ShowerState state, DateTimeOffset timestamp);
void Reset();
}
}
@@ -2,8 +2,8 @@ namespace ShowerMonitorManager.Interface;
public interface IHumidityRateCalculator
{
double? PreviousReading { get; }
void RecordReading(double humidity, DateTimeOffset timestamp);
double GetRatePerMinute();
void Reset();
double? PreviousReading { get; }
}
}
@@ -11,4 +11,4 @@ public interface IShowerDetectionService
ShowerState Evaluate(double bathroomHumidity, double mainHomeHumidity, DateTimeOffset timestamp);
void ResetDailyCounters();
}
}
@@ -7,4 +7,4 @@ public interface IShowerMonitorEntityService
Task CreateEntitiesAsync(CancellationToken cancellationToken = default);
Task UpdateEntitiesAsync(ShowerMonitorUpdateContext context, CancellationToken cancellationToken = default);
Task CleanupEntitiesAsync(CancellationToken cancellationToken = default);
}
}
@@ -17,8 +17,11 @@ public sealed class ShowerMonitorOptions
public double MinDifferentialHumidity { get; init; } = ShowerMonitorConsts.DefaultMinDifferentialHumidity;
public double PeakHumidityThreshold { get; init; } = ShowerMonitorConsts.DefaultPeakHumidityThreshold;
public int ConfirmationWindowMinutes { get; init; } = ShowerMonitorConsts.DefaultConfirmationWindowMinutes;
public double RecoveryDifferentialThreshold { get; init; } = ShowerMonitorConsts.DefaultRecoveryDifferentialThreshold;
public double RecoveryDifferentialThreshold { get; init; } =
ShowerMonitorConsts.DefaultRecoveryDifferentialThreshold;
public int MaxShowerDurationMinutes { get; init; } = (int)ShowerMonitorConsts.DefaultMaxShowerDuration.TotalMinutes;
public int FanRunAfterShowerMinutes { get; init; } = (int)ShowerMonitorConsts.DefaultFanRunAfterShower.TotalMinutes;
public int RateWindowSize { get; init; } = ShowerMonitorConsts.DefaultRateWindowSize;
}
}
@@ -10,4 +10,4 @@ public sealed class ShowerMonitorUpdateContext
public required double HumidityRate { get; init; }
public required int TodaySessionCount { get; init; }
public ShowerSession? LastCompletedSession { get; init; }
}
}
+48 -35
View File
@@ -11,39 +11,69 @@ public sealed class ShowerDetectionService(
IOptions<ShowerMonitorOptions> options)
: IShowerDetectionService
{
private readonly ShowerMonitorOptions _options = options.Value;
private readonly Lock _lock = new();
private readonly ShowerMonitorOptions _options = options.Value;
private ShowerSession? _currentSession;
private ShowerState _currentState = ShowerState.Idle;
private ShowerSession? _currentSession;
private ShowerSession? _lastCompletedSession;
private int _todaySessionCount;
private DateTimeOffset? _suspectedSince;
private double _lastRate;
private DateTimeOffset? _suspectedSince;
private int _todaySessionCount;
public ShowerState CurrentState
{
get { lock (_lock) { return _currentState; } }
get
{
lock (_lock)
{
return _currentState;
}
}
}
public ShowerSession? CurrentSession
{
get { lock (_lock) { return _currentSession; } }
get
{
lock (_lock)
{
return _currentSession;
}
}
}
public ShowerSession? LastCompletedSession
{
get { lock (_lock) { return _lastCompletedSession; } }
get
{
lock (_lock)
{
return _lastCompletedSession;
}
}
}
public int TodaySessionCount
{
get { lock (_lock) { return _todaySessionCount; } }
get
{
lock (_lock)
{
return _todaySessionCount;
}
}
}
public double LastRate
{
get { lock (_lock) { return _lastRate; } }
get
{
lock (_lock)
{
return _lastRate;
}
}
}
public ShowerState Evaluate(double bathroomHumidity, double mainHomeHumidity, DateTimeOffset timestamp)
@@ -83,10 +113,7 @@ public sealed class ShowerDetectionService(
var showerSuspected = rate >= _options.SpikeRateThreshold
&& differential >= _options.MinDifferentialHumidity;
if (!showerSuspected)
{
return ShowerState.Idle;
}
if (!showerSuspected) return ShowerState.Idle;
_suspectedSince = timestamp;
_currentSession = new ShowerSession
@@ -111,17 +138,12 @@ public sealed class ShowerDetectionService(
var confirmationWindow = TimeSpan.FromMinutes(_options.ConfirmationWindowMinutes);
if (_suspectedSince.HasValue && timestamp - _suspectedSince.Value >= confirmationWindow
&& humidity >= _options.PeakHumidityThreshold
&& differential >= _options.MinDifferentialHumidity)
{
&& humidity >= _options.PeakHumidityThreshold
&& differential >= _options.MinDifferentialHumidity)
return ShowerState.Active;
}
var showerAbandoned = rate < 0 && differential < _options.MinDifferentialHumidity;
if (!showerAbandoned)
{
return ShowerState.Suspected;
}
if (!showerAbandoned) return ShowerState.Suspected;
CompleteSessionCleanup();
@@ -141,10 +163,7 @@ public sealed class ShowerDetectionService(
&& _currentSession.GetDuration(timestamp) >= maxDuration;
var humidityRecovered = rate < 0 && differential < _options.MinDifferentialHumidity;
if (maxDurationReached || humidityRecovered)
{
return TransitionToDeclining();
}
if (maxDurationReached || humidityRecovered) return TransitionToDeclining();
return ShowerState.Active;
}
@@ -162,10 +181,7 @@ public sealed class ShowerDetectionService(
var maxDurationReached = _currentSession is not null
&& _currentSession.GetDuration(timestamp) >= maxDuration;
if (!maxDurationReached)
{
return ShowerState.Declining;
}
if (!maxDurationReached) return ShowerState.Declining;
CompleteSession(timestamp);
@@ -180,16 +196,13 @@ public sealed class ShowerDetectionService(
private ShowerState TransitionToIdle()
{
rateCalculator.Reset();
return ShowerState.Idle;
}
private void CompleteSession(DateTimeOffset endTime)
{
if (_currentSession is null)
{
return;
}
if (_currentSession is null) return;
_currentSession.EndTime = endTime;
_lastCompletedSession = _currentSession;
@@ -204,4 +217,4 @@ public sealed class ShowerDetectionService(
_currentSession = null;
_suspectedSince = null;
}
}
}
@@ -8,20 +8,20 @@
</PropertyGroup>
<ItemGroup>
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
<_Parameter1>ShowerMonitor.Manager.Tests</_Parameter1>
</AssemblyAttribute>
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
<_Parameter1>ShowerMonitor.Manager.Tests</_Parameter1>
</AssemblyAttribute>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\HomeAssistant.Entities\HomeAssistant.Entities.csproj" />
<ProjectReference Include="..\ShowerMonitor.Models\ShowerMonitor.Models.csproj" />
<ProjectReference Include="..\HomeAssistant.Entities\HomeAssistant.Entities.csproj"/>
<ProjectReference Include="..\ShowerMonitor.Models\ShowerMonitor.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>
@@ -25,14 +25,6 @@ public sealed class ShowerMonitorEntityService(
CleanupButtonEntityId
];
private static object CreateDeviceBlock() => new
{
identifiers = new[] { DeviceIdentifier },
name = DeviceName,
model = DeviceName,
manufacturer = DeviceManufacturer
};
public async Task CreateEntitiesAsync(CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
@@ -91,6 +83,17 @@ public sealed class ShowerMonitorEntityService(
}
}
private static object CreateDeviceBlock()
{
return new
{
identifiers = new[] { DeviceIdentifier },
name = DeviceName,
model = DeviceName,
manufacturer = DeviceManufacturer
};
}
private static ICollection<ShowerMonitorEntity> GetAllEntities()
{
var device = CreateDeviceBlock();
@@ -107,7 +110,8 @@ public sealed class ShowerMonitorEntityService(
},
new ShowerMonitorEntity("sensor", "showermonitor_differential_humidity", "Bathroom differential humidity")
{
AdditionalConfig = new { unit_of_measurement = "%", icon = "mdi:water-percent", device_class = "humidity", device }
AdditionalConfig = new
{ unit_of_measurement = "%", icon = "mdi:water-percent", device_class = "humidity", device }
},
new ShowerMonitorEntity("sensor", "showermonitor_humidity_rate", "Humidity rate of change")
{
@@ -119,7 +123,8 @@ public sealed class ShowerMonitorEntityService(
},
new ShowerMonitorEntity("sensor", "showermonitor_last_shower_duration", "Last shower duration")
{
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 ShowerMonitorEntity("sensor", "showermonitor_last_shower_time", "Last shower time")
{
@@ -134,7 +139,8 @@ public sealed class ShowerMonitorEntityService(
private async Task UpdateDifferentialAsync(double differential, string timestamp)
{
await SetEntityStateSafe(DifferentialEntityId, Math.Round(differential, 1).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
await SetEntityStateSafe(DifferentialEntityId,
Math.Round(differential, 1).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
await SetEntityAttributesSafe(DifferentialEntityId, new
{
unit_of_measurement = "%",
@@ -145,7 +151,8 @@ public sealed class ShowerMonitorEntityService(
private async Task UpdateHumidityRateAsync(double rate, string timestamp)
{
await SetEntityStateSafe(HumidityRateEntityId, Math.Round(rate, 2).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
await SetEntityStateSafe(HumidityRateEntityId, Math.Round(rate, 2).ToString(CultureInfo.InvariantCulture))
.ConfigureAwait(false);
await SetEntityAttributesSafe(HumidityRateEntityId, new
{
unit_of_measurement = "%/min",
@@ -156,7 +163,8 @@ public sealed class ShowerMonitorEntityService(
private async Task UpdateTodaySessionCountAsync(int count, string timestamp)
{
await SetEntityStateSafe(TodaySessionCountEntityId, count.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
await SetEntityStateSafe(TodaySessionCountEntityId, count.ToString(CultureInfo.InvariantCulture))
.ConfigureAwait(false);
await SetEntityAttributesSafe(TodaySessionCountEntityId, new
{
friendly_name = "Showers today",
@@ -166,13 +174,11 @@ public sealed class ShowerMonitorEntityService(
private async Task UpdateLastShowerAsync(ShowerSession? session, string timestamp)
{
if (session is null)
{
return;
}
if (session is null) return;
var durationSeconds = (int)session.Duration.TotalSeconds;
await SetEntityStateSafe(LastShowerDurationEntityId, durationSeconds.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
await SetEntityStateSafe(LastShowerDurationEntityId, durationSeconds.ToString(CultureInfo.InvariantCulture))
.ConfigureAwait(false);
await SetEntityAttributesSafe(LastShowerDurationEntityId, new
{
formatted = FormatDuration(session.Duration),
@@ -181,7 +187,8 @@ public sealed class ShowerMonitorEntityService(
last_updated = timestamp
}).ConfigureAwait(false);
await SetEntityStateSafe(LastShowerTimeEntityId, session.StartTime.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture)).ConfigureAwait(false);
await SetEntityStateSafe(LastShowerTimeEntityId,
session.StartTime.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture)).ConfigureAwait(false);
await SetEntityAttributesSafe(LastShowerTimeEntityId, new
{
friendly_name = "Last shower time",
@@ -217,7 +224,7 @@ public sealed class ShowerMonitorEntityService(
{
var totalMinutes = (int)ts.TotalMinutes;
var seconds = ts.Seconds;
return $"{totalMinutes}m {seconds}s";
}
}
}
+9 -18
View File
@@ -15,13 +15,13 @@ namespace ShowerMonitorManager;
[NetDaemonApp]
public sealed class ShowerMonitorInit
{
private readonly ILogger<ShowerMonitorInit> _logger;
private readonly IHaContext _haContext;
private readonly IScheduler _scheduler;
private readonly IShowerDetectionService _detectionService;
private readonly IExhaustFanControlService _fanControlService;
private readonly IShowerMonitorEntityService _entityService;
private readonly IExhaustFanControlService _fanControlService;
private readonly IHaContext _haContext;
private readonly ILogger<ShowerMonitorInit> _logger;
private readonly ShowerMonitorOptions _options;
private readonly IScheduler _scheduler;
private readonly TimeProvider _timeProvider;
private volatile bool _cleanedUp;
@@ -69,10 +69,7 @@ public sealed class ShowerMonitorInit
{
await Task.Delay(TimeSpan.FromSeconds(3));
if (_options.CleanupEntitiesOnStartup)
{
await _entityService.CleanupEntitiesAsync();
}
if (_options.CleanupEntitiesOnStartup) await _entityService.CleanupEntitiesAsync();
await _entityService.CreateEntitiesAsync();
@@ -158,9 +155,8 @@ public sealed class ShowerMonitorInit
if (!bathroomHumidity.HasValue || !mainHomeHumidity.HasValue)
{
if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.LogDebug("Humidity sensor data unavailable (bathroom={Bathroom}, home={Home})", bathroomHumidity, mainHomeHumidity);
}
_logger.LogDebug("Humidity sensor data unavailable (bathroom={Bathroom}, home={Home})",
bathroomHumidity, mainHomeHumidity);
return;
}
@@ -183,10 +179,8 @@ public sealed class ShowerMonitorInit
await _entityService.UpdateEntitiesAsync(context);
if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.LogDebug("Poll: bathroom={Bath}%, home={Home}%, diff={Diff}%, state={State}",
bathroomHumidity.Value, mainHomeHumidity.Value, Math.Round(differential, 1), state);
}
}
catch (Exception ex)
{
@@ -198,11 +192,8 @@ public sealed class ShowerMonitorInit
{
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;
}
}
}
@@ -14,10 +14,7 @@ public static class ShowerMonitorServiceRegistration
.GetSection(ShowerMonitorOptions.SectionName)
.Get<ShowerMonitorOptions>() ?? new ShowerMonitorOptions();
if (!options.Enabled)
{
return services;
}
if (!options.Enabled) return services;
services
.AddNetDaemonApp<ShowerMonitorInit>()
@@ -28,4 +25,4 @@ public static class ShowerMonitorServiceRegistration
return services;
}
}
}