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
@@ -1,3 +1,5 @@
#region
using Microsoft.Extensions.Options;
using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
@@ -5,13 +7,15 @@ using ShowerMonitor.Models.Enums;
using ShowerMonitorManager.Interface;
using ShowerMonitorManager.Models;
#endregion
namespace ShowerMonitorManager;
public sealed class ExhaustFanControlService(
IHaContext haContext,
IOptions<ShowerMonitorOptions> options) : IExhaustFanControlService
{
private readonly Lock _lock = new();
private readonly Lock _lock = new Lock();
private readonly ShowerMonitorOptions _options = options.Value;
private bool _fanTurnedOnByUs;
@@ -27,16 +31,19 @@ public sealed class ExhaustFanControlService(
case ShowerState.Suspected:
TurnOnFanIfNeeded();
_showerEndedAt = null;
break;
case ShowerState.Declining:
case ShowerState.Completed:
_showerEndedAt ??= timestamp;
EvaluatePostShowerFanOff(timestamp);
break;
case ShowerState.Idle:
EvaluatePostShowerFanOff(timestamp);
break;
default:
@@ -67,10 +74,17 @@ 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;
@@ -78,12 +92,18 @@ 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;
@@ -1,11 +1,15 @@
#region
using ShowerMonitorManager.Interface;
#endregion
namespace ShowerMonitorManager;
public sealed class HumidityRateCalculator(int windowSize) : IHumidityRateCalculator
{
private readonly Lock _lock = new();
private readonly Queue<(double Humidity, DateTimeOffset Timestamp)> _readings = new();
private readonly Lock _lock = new Lock();
private readonly Queue<(double Humidity, DateTimeOffset Timestamp)> _readings = new Queue<(double Humidity, DateTimeOffset Timestamp)>();
private double? _previousReading;
public double? PreviousReading
@@ -26,7 +30,10 @@ 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();
}
}
}
@@ -34,13 +41,19 @@ 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;
}
@@ -1,5 +1,9 @@
#region
using ShowerMonitor.Models.Enums;
#endregion
namespace ShowerMonitorManager.Interface;
public interface IExhaustFanControlService
@@ -1,6 +1,10 @@
#region
using ShowerMonitor.Models;
using ShowerMonitor.Models.Enums;
#endregion
namespace ShowerMonitorManager.Interface;
public interface IShowerDetectionService
@@ -1,5 +1,9 @@
#region
using ShowerMonitorManager.Models;
#endregion
namespace ShowerMonitorManager.Interface;
public interface IShowerMonitorEntityService
@@ -1,5 +1,9 @@
#region
using ShowerMonitor.Models;
#endregion
namespace ShowerMonitorManager.Models;
public sealed class ShowerMonitorOptions
@@ -1,6 +1,10 @@
#region
using ShowerMonitor.Models;
using ShowerMonitor.Models.Enums;
#endregion
namespace ShowerMonitorManager.Models;
public sealed class ShowerMonitorUpdateContext
+32 -15
View File
@@ -1,9 +1,13 @@
#region
using Microsoft.Extensions.Options;
using ShowerMonitor.Models;
using ShowerMonitor.Models.Enums;
using ShowerMonitorManager.Interface;
using ShowerMonitorManager.Models;
#endregion
namespace ShowerMonitorManager;
public sealed class ShowerDetectionService(
@@ -11,7 +15,7 @@ public sealed class ShowerDetectionService(
IOptions<ShowerMonitorOptions> options)
: IShowerDetectionService
{
private readonly Lock _lock = new();
private readonly Lock _lock = new Lock();
private readonly ShowerMonitorOptions _options = options.Value;
private ShowerSession? _currentSession;
@@ -85,6 +89,7 @@ public sealed class ShowerDetectionService(
lock (_lock)
{
_lastRate = rate;
_currentState = _currentState switch
{
ShowerState.Idle => EvaluateIdle(rate, differential, bathroomHumidity, timestamp),
@@ -110,12 +115,15 @@ public sealed class ShowerDetectionService(
private ShowerState EvaluateIdle(double rate, double differential, double humidity, DateTimeOffset timestamp)
{
var showerSuspected = rate >= _options.SpikeRateThreshold
&& differential >= _options.MinDifferentialHumidity;
var showerSuspected = rate >= _options.SpikeRateThreshold && differential >= _options.MinDifferentialHumidity;
if (!showerSuspected) return ShowerState.Idle;
if (!showerSuspected)
{
return ShowerState.Idle;
}
_suspectedSince = timestamp;
_currentSession = new ShowerSession
{
StartTime = timestamp,
@@ -137,15 +145,17 @@ public sealed class ShowerDetectionService(
var confirmationWindow = TimeSpan.FromMinutes(_options.ConfirmationWindowMinutes);
if (_suspectedSince.HasValue && timestamp - _suspectedSince.Value >= confirmationWindow
&& humidity >= _options.PeakHumidityThreshold
&& differential >= _options.MinDifferentialHumidity)
if (_suspectedSince.HasValue && timestamp - _suspectedSince.Value >= confirmationWindow && 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();
@@ -161,11 +171,13 @@ public sealed class ShowerDetectionService(
}
var maxDuration = TimeSpan.FromMinutes(_options.MaxShowerDurationMinutes);
var maxDurationReached = _currentSession is not null
&& _currentSession.GetDuration(timestamp) >= maxDuration;
var maxDurationReached = _currentSession is not null && _currentSession.GetDuration(timestamp) >= maxDuration;
var humidityRecovered = rate < 0 && differential < _options.MinDifferentialHumidity;
if (maxDurationReached || humidityRecovered) return TransitionToDeclining();
if (maxDurationReached || humidityRecovered)
{
return TransitionToDeclining();
}
return ShowerState.Active;
}
@@ -180,10 +192,12 @@ public sealed class ShowerDetectionService(
}
var maxDuration = TimeSpan.FromMinutes(_options.MaxShowerDurationMinutes);
var maxDurationReached = _currentSession is not null
&& _currentSession.GetDuration(timestamp) >= maxDuration;
var maxDurationReached = _currentSession is not null && _currentSession.GetDuration(timestamp) >= maxDuration;
if (!maxDurationReached) return ShowerState.Declining;
if (!maxDurationReached)
{
return ShowerState.Declining;
}
CompleteSession(timestamp);
@@ -204,7 +218,10 @@ public sealed class ShowerDetectionService(
private void CompleteSession(DateTimeOffset endTime)
{
if (_currentSession is null) return;
if (_currentSession is null)
{
return;
}
_currentSession.EndTime = endTime;
_lastCompletedSession = _currentSession;
@@ -1,3 +1,5 @@
#region
using System.Globalization;
using HomeAssistant.Entities.Interfaces;
using Microsoft.Extensions.Logging;
@@ -7,6 +9,8 @@ using ShowerMonitorManager.Interface;
using ShowerMonitorManager.Models;
using static ShowerMonitor.Models.ShowerMonitorConsts;
#endregion
namespace ShowerMonitorManager;
public sealed class ShowerMonitorEntityService(
@@ -30,17 +34,18 @@ public sealed class ShowerMonitorEntityService(
cancellationToken.ThrowIfCancellationRequested();
var entities = GetAllEntities();
var createTasks = entities.Select(async entity =>
{
try
{
await entityManager.CreateEntityAsync(entity).ConfigureAwait(false);
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to create MQTT entity: {EntityId}", entity.EntityId);
}
});
{
try
{
await entityManager.CreateEntityAsync(entity).ConfigureAwait(false);
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to create MQTT entity: {EntityId}", entity.EntityId);
}
});
await Task.WhenAll(createTasks).ConfigureAwait(false);
}
@@ -79,6 +84,7 @@ public sealed class ShowerMonitorEntityService(
catch (Exception ex)
{
logger.LogError(ex, "Error cleaning up ShowerMonitor entities");
throw;
}
}
@@ -140,60 +146,76 @@ public sealed class ShowerMonitorEntityService(
private async Task UpdateDifferentialAsync(double differential, string timestamp)
{
await SetEntityStateSafe(DifferentialEntityId,
Math.Round(differential, 1).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
Math.Round(differential, 1).ToString(CultureInfo.InvariantCulture))
.ConfigureAwait(false);
await SetEntityAttributesSafe(DifferentialEntityId, new
{
unit_of_measurement = "%",
friendly_name = "Bathroom differential humidity",
last_updated = timestamp
}).ConfigureAwait(false);
{
unit_of_measurement = "%",
friendly_name = "Bathroom differential humidity",
last_updated = timestamp
})
.ConfigureAwait(false);
}
private async Task UpdateHumidityRateAsync(double rate, string timestamp)
{
await SetEntityStateSafe(HumidityRateEntityId, Math.Round(rate, 2).ToString(CultureInfo.InvariantCulture))
.ConfigureAwait(false);
.ConfigureAwait(false);
await SetEntityAttributesSafe(HumidityRateEntityId, new
{
unit_of_measurement = "%/min",
friendly_name = "Humidity rate of change",
last_updated = timestamp
}).ConfigureAwait(false);
{
unit_of_measurement = "%/min",
friendly_name = "Humidity rate of change",
last_updated = timestamp
})
.ConfigureAwait(false);
}
private async Task UpdateTodaySessionCountAsync(int count, string timestamp)
{
await SetEntityStateSafe(TodaySessionCountEntityId, count.ToString(CultureInfo.InvariantCulture))
.ConfigureAwait(false);
.ConfigureAwait(false);
await SetEntityAttributesSafe(TodaySessionCountEntityId, new
{
friendly_name = "Showers today",
last_updated = timestamp
}).ConfigureAwait(false);
{
friendly_name = "Showers today",
last_updated = timestamp
})
.ConfigureAwait(false);
}
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);
.ConfigureAwait(false);
await SetEntityAttributesSafe(LastShowerDurationEntityId, new
{
formatted = FormatDuration(session.Duration),
peak_humidity = session.PeakHumidity,
friendly_name = "Last shower duration",
last_updated = timestamp
}).ConfigureAwait(false);
{
formatted = FormatDuration(session.Duration),
peak_humidity = session.PeakHumidity,
friendly_name = "Last shower duration",
last_updated = timestamp
})
.ConfigureAwait(false);
await SetEntityStateSafe(LastShowerTimeEntityId,
session.StartTime.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture)).ConfigureAwait(false);
session.StartTime.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture))
.ConfigureAwait(false);
await SetEntityAttributesSafe(LastShowerTimeEntityId, new
{
friendly_name = "Last shower time",
last_updated = timestamp
}).ConfigureAwait(false);
{
friendly_name = "Last shower time",
last_updated = timestamp
})
.ConfigureAwait(false);
}
private async Task SetEntityStateSafe(string entityId, string state)
+33 -20
View File
@@ -1,3 +1,5 @@
#region
using System.Globalization;
using System.Reactive.Concurrency;
using Microsoft.Extensions.Logging;
@@ -10,6 +12,8 @@ using ShowerMonitorManager.Interface;
using ShowerMonitorManager.Models;
using static ShowerMonitor.Models.ShowerMonitorConsts;
#endregion
namespace ShowerMonitorManager;
[NetDaemonApp]
@@ -69,7 +73,10 @@ 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();
@@ -81,6 +88,7 @@ public sealed class ShowerMonitorInit
catch (Exception ex)
{
_logger.LogError(ex, "Error initializing ShowerMonitor");
throw;
}
}
@@ -99,28 +107,29 @@ public sealed class ShowerMonitorInit
private void ScheduleMidnightReset()
{
_scheduler.ScheduleCron("0 0 * * *", () =>
{
try
{
_logger.LogDebug("Midnight reset: clearing shower session counters");
_detectionService.ResetDailyCounters();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error during midnight reset");
}
});
{
try
{
_logger.LogDebug("Midnight reset: clearing shower session counters");
_detectionService.ResetDailyCounters();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error during midnight reset");
}
});
}
private void SubscribeToCleanupButton()
{
var cleanupButton = new Entity(_haContext, CleanupButtonEntityId);
cleanupButton.StateChanges()
.Subscribe(_ =>
{
_logger.LogDebug("Cleanup button pressed, removing all ShowerMonitor entities");
Task.Run(HandleCleanupAsync);
});
.Subscribe(_ =>
{
_logger.LogDebug("Cleanup button pressed, removing all ShowerMonitor entities");
Task.Run(HandleCleanupAsync);
});
}
private async Task HandleCleanupAsync()
@@ -144,6 +153,7 @@ public sealed class ShowerMonitorInit
if (_cleanedUp)
{
_logger.LogDebug("ShowerMonitor is cleaned up, skipping poll");
return;
}
@@ -157,7 +167,7 @@ public sealed class ShowerMonitorInit
if (_logger.IsEnabled(LogLevel.Debug))
{
_logger.LogDebug("Humidity sensor data unavailable (bathroom={Bathroom}, home={Home})",
bathroomHumidity, mainHomeHumidity);
bathroomHumidity, mainHomeHumidity);
}
return;
@@ -183,7 +193,7 @@ public sealed class ShowerMonitorInit
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);
bathroomHumidity.Value, mainHomeHumidity.Value, Math.Round(differential, 1), state);
}
}
catch (Exception ex)
@@ -196,7 +206,10 @@ 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;
}
@@ -1,9 +1,13 @@
#region
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using NetDaemon.AppModel;
using ShowerMonitorManager.Interface;
using ShowerMonitorManager.Models;
#endregion
namespace ShowerMonitorManager;
public static class ShowerMonitorServiceRegistration
@@ -11,17 +15,21 @@ public static class ShowerMonitorServiceRegistration
public static IServiceCollection AddShowerMonitor(this IServiceCollection services, IConfiguration configuration)
{
var options = configuration
.GetSection(ShowerMonitorOptions.SectionName)
.Get<ShowerMonitorOptions>() ?? new ShowerMonitorOptions();
.GetSection(ShowerMonitorOptions.SectionName)
.Get<ShowerMonitorOptions>() ??
new ShowerMonitorOptions();
if (!options.Enabled) return services;
if (!options.Enabled)
{
return services;
}
services
.AddNetDaemonApp<ShowerMonitorInit>()
.AddSingleton<IHumidityRateCalculator>(_ => new HumidityRateCalculator(options.RateWindowSize))
.AddSingleton<IShowerDetectionService, ShowerDetectionService>()
.AddScoped<IExhaustFanControlService, ExhaustFanControlService>()
.AddTransient<IShowerMonitorEntityService, ShowerMonitorEntityService>();
.AddNetDaemonApp<ShowerMonitorInit>()
.AddSingleton<IHumidityRateCalculator>(_ => new HumidityRateCalculator(options.RateWindowSize))
.AddSingleton<IShowerDetectionService, ShowerDetectionService>()
.AddScoped<IExhaustFanControlService, ExhaustFanControlService>()
.AddTransient<IShowerMonitorEntityService, ShowerMonitorEntityService>();
return services;
}