feat: add BatteryMonitor implementation with discovery, notification, and scheduling services

This commit is contained in:
Marius
2026-04-01 10:55:33 +03:00
parent 11c2574235
commit 6e4d684359
114 changed files with 22820 additions and 527 deletions
@@ -0,0 +1,106 @@
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
using ShowerMonitor.Models.Enums;
using ShowerMonitorManager.Interface;
using ShowerMonitorManager.Models;
namespace ShowerMonitorManager;
public sealed class ExhaustFanControlService : IExhaustFanControlService
{
private readonly ILogger<ExhaustFanControlService> _logger;
private readonly ShowerMonitorOptions _options;
private readonly Lock _lock = new();
private bool _fanTurnedOnByUs;
private DateTimeOffset? _showerEndedAt;
public ExhaustFanControlService(
ILogger<ExhaustFanControlService> logger,
IOptions<ShowerMonitorOptions> options)
{
_logger = logger;
_options = options.Value;
}
public void Evaluate(ShowerState state, DateTimeOffset timestamp, IHaContext haContext)
{
lock (_lock)
{
switch (state)
{
case ShowerState.Active:
case ShowerState.Suspected:
TurnOnFanIfNeeded(haContext);
_showerEndedAt = null;
break;
case ShowerState.Declining:
case ShowerState.Completed:
_showerEndedAt ??= timestamp;
EvaluatePostShowerFanOff(timestamp, haContext);
break;
case ShowerState.Idle:
EvaluatePostShowerFanOff(timestamp, haContext);
break;
}
}
}
public void Reset(IHaContext haContext)
{
lock (_lock)
{
if (_fanTurnedOnByUs)
{
haContext.CallService("switch", "turn_off", ServiceTarget.FromEntity(_options.ExhaustFanEntityId));
_logger.LogInformation("Exhaust fan turned OFF during reset (was turned on by shower detection)");
}
_fanTurnedOnByUs = false;
_showerEndedAt = null;
}
}
private void TurnOnFanIfNeeded(IHaContext haContext)
{
if (_fanTurnedOnByUs)
{
return;
}
var fanState = haContext.GetState(_options.ExhaustFanEntityId)?.State;
if (string.Equals(fanState, "on", StringComparison.OrdinalIgnoreCase))
{
return;
}
haContext.CallService("switch", "turn_on", ServiceTarget.FromEntity(_options.ExhaustFanEntityId));
_fanTurnedOnByUs = true;
_logger.LogInformation("Exhaust fan turned ON by shower detection");
}
private void EvaluatePostShowerFanOff(DateTimeOffset timestamp, IHaContext haContext)
{
if (!_fanTurnedOnByUs || !_showerEndedAt.HasValue)
{
return;
}
var elapsed = timestamp - _showerEndedAt.Value;
var runAfterDuration = TimeSpan.FromMinutes(_options.FanRunAfterShowerMinutes);
if (elapsed < runAfterDuration)
{
return;
}
haContext.CallService("switch", "turn_off", ServiceTarget.FromEntity(_options.ExhaustFanEntityId));
_fanTurnedOnByUs = false;
_showerEndedAt = null;
_logger.LogInformation("Exhaust fan turned OFF after post-shower run period ({Duration})", runAfterDuration);
}
}
@@ -0,0 +1,52 @@
using ShowerMonitorManager.Interface;
namespace ShowerMonitorManager;
public sealed class HumidityRateCalculator(int windowSize) : IHumidityRateCalculator
{
private readonly Lock _lock = new();
private readonly Queue<(double Humidity, DateTimeOffset Timestamp)> _readings = new();
public void RecordReading(double humidity, DateTimeOffset timestamp)
{
lock (_lock)
{
_readings.Enqueue((humidity, timestamp));
while (_readings.Count > windowSize)
{
_readings.Dequeue();
}
}
}
public double GetRatePerMinute()
{
lock (_lock)
{
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;
}
return (newest.Humidity - oldest.Humidity) / elapsedMinutes;
}
}
public void Reset()
{
lock (_lock)
{
_readings.Clear();
}
}
}
@@ -0,0 +1,10 @@
using NetDaemon.HassModel;
using ShowerMonitor.Models.Enums;
namespace ShowerMonitorManager.Interface;
public interface IExhaustFanControlService
{
void Evaluate(ShowerState state, DateTimeOffset timestamp, IHaContext haContext);
void Reset(IHaContext haContext);
}
@@ -0,0 +1,8 @@
namespace ShowerMonitorManager.Interface;
public interface IHumidityRateCalculator
{
void RecordReading(double humidity, DateTimeOffset timestamp);
double GetRatePerMinute();
void Reset();
}
@@ -0,0 +1,15 @@
using ShowerMonitor.Models;
using ShowerMonitor.Models.Enums;
namespace ShowerMonitorManager.Interface;
public interface IShowerDetectionService
{
ShowerState CurrentState { get; }
ShowerSession? CurrentSession { get; }
ShowerSession? LastCompletedSession { get; }
int TodaySessionCount { get; }
ShowerState Evaluate(double bathroomHumidity, double mainHomeHumidity, DateTimeOffset timestamp);
void ResetDailyCounters();
}
@@ -0,0 +1,11 @@
using ShowerMonitorManager.Models;
namespace ShowerMonitorManager.Interface;
public interface IShowerMonitorEntityService
{
Task CreateEntitiesAsync(CancellationToken cancellationToken = default);
Task UpdateEntitiesAsync(ShowerMonitorUpdateContext context, CancellationToken cancellationToken = default);
Task ResetEntitiesAsync(CancellationToken cancellationToken = default);
Task CleanupEntitiesAsync(CancellationToken cancellationToken = default);
}
@@ -0,0 +1,7 @@
namespace ShowerMonitorManager.Interface;
public interface IShowerMonitorInit
{
Task InitializeAsync();
Task CleanupEntitiesAsync(CancellationToken cancellationToken = default);
}
@@ -0,0 +1,24 @@
using ShowerMonitor.Models;
namespace ShowerMonitorManager.Models;
public sealed class ShowerMonitorOptions
{
public const string SectionName = "ShowerMonitor";
public bool Enabled { get; set; }
public bool CleanupEntitiesOnStartup { get; set; }
public string BathroomHumidityEntityId { get; set; } = ShowerMonitorConsts.BathroomHumidityEntityId;
public string MainHomeHumidityEntityId { get; set; } = ShowerMonitorConsts.MainHomeHumidityEntityId;
public string BathroomTemperatureEntityId { get; set; } = ShowerMonitorConsts.BathroomTemperatureEntityId;
public string ExhaustFanEntityId { get; set; } = ShowerMonitorConsts.ExhaustFanEntityId;
public int PollIntervalSeconds { get; set; } = ShowerMonitorConsts.DefaultPollIntervalSeconds;
public double SpikeRateThreshold { get; set; } = ShowerMonitorConsts.DefaultSpikeRateThreshold;
public double MinDifferentialHumidity { get; set; } = ShowerMonitorConsts.DefaultMinDifferentialHumidity;
public double PeakHumidityThreshold { get; set; } = ShowerMonitorConsts.DefaultPeakHumidityThreshold;
public int ConfirmationWindowMinutes { get; set; } = ShowerMonitorConsts.DefaultConfirmationWindowMinutes;
public double RecoveryDifferentialThreshold { get; set; } = ShowerMonitorConsts.DefaultRecoveryDifferentialThreshold;
public int MaxShowerDurationMinutes { get; set; } = (int)ShowerMonitorConsts.DefaultMaxShowerDuration.TotalMinutes;
public int FanRunAfterShowerMinutes { get; set; } = (int)ShowerMonitorConsts.DefaultFanRunAfterShower.TotalMinutes;
public int RateWindowSize { get; set; } = ShowerMonitorConsts.DefaultRateWindowSize;
}
@@ -0,0 +1,16 @@
using ShowerMonitor.Models;
using ShowerMonitor.Models.Enums;
namespace ShowerMonitorManager.Models;
public sealed class ShowerMonitorUpdateContext
{
public required ShowerState State { get; init; }
public required double BathroomHumidity { get; init; }
public required double MainHomeHumidity { get; init; }
public required double Differential { get; init; }
public required double HumidityRate { get; init; }
public required int TodaySessionCount { get; init; }
public ShowerSession? LastCompletedSession { get; init; }
public ShowerSession? CurrentSession { get; init; }
}
@@ -0,0 +1,218 @@
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using ShowerMonitor.Models;
using ShowerMonitor.Models.Enums;
using ShowerMonitorManager.Interface;
using ShowerMonitorManager.Models;
namespace ShowerMonitorManager;
public sealed class ShowerDetectionService : IShowerDetectionService
{
private readonly IHumidityRateCalculator _rateCalculator;
private readonly ILogger<ShowerDetectionService> _logger;
private readonly ShowerMonitorOptions _options;
private readonly Lock _lock = new();
private ShowerState _currentState = ShowerState.Idle;
private ShowerSession? _currentSession;
private ShowerSession? _lastCompletedSession;
private int _todaySessionCount;
private DateTimeOffset? _suspectedSince;
public ShowerDetectionService(
IHumidityRateCalculator rateCalculator,
ILogger<ShowerDetectionService> logger,
IOptions<ShowerMonitorOptions> options)
{
_rateCalculator = rateCalculator;
_logger = logger;
_options = options.Value;
}
public ShowerState CurrentState
{
get { lock (_lock) { return _currentState; } }
}
public ShowerSession? CurrentSession
{
get { lock (_lock) { return _currentSession; } }
}
public ShowerSession? LastCompletedSession
{
get { lock (_lock) { return _lastCompletedSession; } }
}
public int TodaySessionCount
{
get { lock (_lock) { return _todaySessionCount; } }
}
public ShowerState Evaluate(double bathroomHumidity, double mainHomeHumidity, DateTimeOffset timestamp)
{
_rateCalculator.RecordReading(bathroomHumidity, timestamp);
var rate = _rateCalculator.GetRatePerMinute();
var differential = bathroomHumidity - mainHomeHumidity;
lock (_lock)
{
var previousState = _currentState;
_currentState = _currentState switch
{
ShowerState.Idle => EvaluateIdle(rate, differential, bathroomHumidity, timestamp),
ShowerState.Suspected => EvaluateSuspected(rate, differential, bathroomHumidity, timestamp),
ShowerState.Active => EvaluateActive(rate, differential, bathroomHumidity, timestamp),
ShowerState.Declining => EvaluateDeclining(differential, timestamp),
ShowerState.Completed => TransitionToIdle(),
_ => _currentState
};
if (_currentState != previousState)
{
_logger.LogInformation(
"Shower state transition: {Previous} -> {Current} (humidity={Humidity}%, differential={Diff}%, rate={Rate}%/min)",
previousState, _currentState, bathroomHumidity, Math.Round(differential, 1), Math.Round(rate, 2));
}
return _currentState;
}
}
public void ResetDailyCounters()
{
lock (_lock)
{
_todaySessionCount = 0;
_lastCompletedSession = null;
_logger.LogInformation("Shower monitor daily counters reset");
}
}
private ShowerState EvaluateIdle(double rate, double differential, double humidity, DateTimeOffset timestamp)
{
if (rate >= _options.SpikeRateThreshold && differential >= _options.MinDifferentialHumidity)
{
_suspectedSince = timestamp;
_currentSession = new ShowerSession
{
StartTime = timestamp,
PreEventHumidity = humidity - (rate > 0 ? rate : 0),
PeakHumidity = humidity,
PeakTime = timestamp
};
_logger.LogInformation("Shower suspected: rate={Rate}%/min, differential={Diff}%", Math.Round(rate, 2), Math.Round(differential, 1));
return ShowerState.Suspected;
}
return ShowerState.Idle;
}
private ShowerState EvaluateSuspected(double rate, double differential, double humidity, DateTimeOffset timestamp)
{
if (_currentSession is not null && humidity > _currentSession.PeakHumidity)
{
_currentSession.PeakHumidity = humidity;
_currentSession.PeakTime = timestamp;
}
var confirmationWindow = TimeSpan.FromMinutes(_options.ConfirmationWindowMinutes);
if (_suspectedSince.HasValue && (timestamp - _suspectedSince.Value) >= confirmationWindow
&& humidity >= _options.PeakHumidityThreshold
&& differential >= _options.MinDifferentialHumidity)
{
_logger.LogInformation("Shower confirmed: peak={Peak}%, differential={Diff}%", humidity, Math.Round(differential, 1));
return ShowerState.Active;
}
if (rate < 0 && differential < _options.MinDifferentialHumidity)
{
_logger.LogInformation("Shower suspicion cleared: differential dropped below threshold");
CompleteSessionCleanup();
return ShowerState.Idle;
}
return ShowerState.Suspected;
}
private ShowerState EvaluateActive(double rate, double differential, double humidity, DateTimeOffset timestamp)
{
if (_currentSession is not null && humidity > _currentSession.PeakHumidity)
{
_currentSession.PeakHumidity = humidity;
_currentSession.PeakTime = timestamp;
}
var maxDuration = TimeSpan.FromMinutes(_options.MaxShowerDurationMinutes);
if (_currentSession is not null && _currentSession.Duration >= maxDuration)
{
_logger.LogWarning("Shower exceeded max duration ({MaxDuration}), completing", maxDuration);
return TransitionToDeclining(timestamp);
}
if (rate < 0 && differential < _options.PeakHumidityThreshold - _options.RecoveryDifferentialThreshold)
{
return TransitionToDeclining(timestamp);
}
return ShowerState.Active;
}
private ShowerState EvaluateDeclining(double differential, DateTimeOffset timestamp)
{
if (differential <= _options.RecoveryDifferentialThreshold)
{
CompleteSession(timestamp);
return ShowerState.Completed;
}
var maxDuration = TimeSpan.FromMinutes(_options.MaxShowerDurationMinutes);
if (_currentSession is not null && _currentSession.Duration >= maxDuration)
{
_logger.LogWarning("Shower declining phase exceeded max duration, completing");
CompleteSession(timestamp);
return ShowerState.Completed;
}
return ShowerState.Declining;
}
private ShowerState TransitionToDeclining(DateTimeOffset timestamp)
{
_logger.LogInformation("Shower entering decline phase at {Time}", timestamp);
return ShowerState.Declining;
}
private ShowerState TransitionToIdle()
{
_rateCalculator.Reset();
return ShowerState.Idle;
}
private void CompleteSession(DateTimeOffset endTime)
{
if (_currentSession is null)
{
return;
}
_currentSession.EndTime = endTime;
_lastCompletedSession = _currentSession;
_todaySessionCount++;
_logger.LogInformation(
"Shower session completed: duration={Duration}, peak={Peak}%, sessions today={Count}",
_currentSession.Duration, _currentSession.PeakHumidity, _todaySessionCount);
_currentSession = null;
_suspectedSince = null;
}
private void CompleteSessionCleanup()
{
_currentSession = null;
_suspectedSince = null;
}
}
@@ -0,0 +1,27 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<RootNamespace>ShowerMonitorManager</RootNamespace>
</PropertyGroup>
<ItemGroup>
<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" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.5" />
<PackageReference Include="NetDaemon.Extensions.Scheduling" Version="26.11.0" />
<PackageReference Include="NetDaemon.HassModel" Version="26.11.0" />
</ItemGroup>
</Project>
@@ -0,0 +1,240 @@
using System.Globalization;
using HomeAssistant.Entities.Interfaces;
using Microsoft.Extensions.Logging;
using ShowerMonitor.Models;
using ShowerMonitor.Models.Enums;
using ShowerMonitorManager.Interface;
using ShowerMonitorManager.Models;
using static ShowerMonitor.Models.ShowerMonitorConsts;
namespace ShowerMonitorManager;
public sealed class ShowerMonitorEntityService(
IEntityManager entityManager,
ILogger<ShowerMonitorEntityService> logger) : IShowerMonitorEntityService
{
private static readonly string[] CleanableEntityIds =
[
ActiveEntityId,
StateEntityId,
DifferentialEntityId,
HumidityRateEntityId,
TodaySessionCountEntityId,
LastShowerDurationEntityId,
LastShowerTimeEntityId,
CleanupButtonEntityId
];
private static object CreateDeviceBlock() => new
{
identifiers = new[] { DeviceIdentifier },
name = DeviceName,
model = DeviceName,
manufacturer = DeviceManufacturer
};
public async Task CreateEntitiesAsync(CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
var entities = GetAllEntities();
var createTasks = entities.Select(async entity =>
{
try
{
logger.LogInformation("Creating MQTT entity: {EntityId}", entity.EntityId);
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);
}
public async Task UpdateEntitiesAsync(ShowerMonitorUpdateContext ctx, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
var timestamp = DateTime.UtcNow.ToString("O");
var isActive = ctx.State is ShowerState.Active or ShowerState.Suspected;
var updateTasks = new[]
{
SetEntityStateSafe(ActiveEntityId, isActive ? "on" : "off"),
SetEntityStateSafe(StateEntityId, ctx.State.ToString().ToLowerInvariant()),
UpdateDifferentialAsync(ctx.Differential, timestamp),
UpdateHumidityRateAsync(ctx.HumidityRate, timestamp),
UpdateTodaySessionCountAsync(ctx.TodaySessionCount, timestamp),
UpdateLastShowerAsync(ctx.LastCompletedSession, timestamp)
};
await Task.WhenAll(updateTasks).ConfigureAwait(false);
}
public async Task ResetEntitiesAsync(CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
logger.LogInformation("Resetting ShowerMonitor entity states to defaults");
await Task.WhenAll(
SetEntityStateSafe(ActiveEntityId, "off"),
SetEntityStateSafe(StateEntityId, ShowerState.Idle.ToString().ToLowerInvariant()),
SetEntityStateSafe(DifferentialEntityId, "0"),
SetEntityStateSafe(HumidityRateEntityId, "0"),
SetEntityStateSafe(TodaySessionCountEntityId, "0"),
SetEntityStateSafe(LastShowerDurationEntityId, "0"),
SetEntityStateSafe(LastShowerTimeEntityId, "unknown")
).ConfigureAwait(false);
}
public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
try
{
var removeTasks = CleanableEntityIds.Select(entityId => entityManager.RemoveEntity(entityId));
await Task.WhenAll(removeTasks).ConfigureAwait(false);
logger.LogInformation("ShowerMonitor entities cleaned up successfully");
}
catch (Exception ex)
{
logger.LogError(ex, "Error cleaning up ShowerMonitor entities");
throw;
}
}
private static ICollection<ShowerMonitorEntity> GetAllEntities()
{
var device = CreateDeviceBlock();
return
[
new ShowerMonitorEntity("binary_sensor", "showermonitor_active", "Shower active")
{
AdditionalConfig = new { icon = "mdi:shower-head", device }
},
new ShowerMonitorEntity("sensor", "showermonitor_state", "Shower detection state")
{
AdditionalConfig = new { icon = "mdi:state-machine", device }
},
new ShowerMonitorEntity("sensor", "showermonitor_differential_humidity", "Bathroom differential humidity")
{
AdditionalConfig = new { unit_of_measurement = "%", icon = "mdi:water-percent", device_class = "humidity", device }
},
new ShowerMonitorEntity("sensor", "showermonitor_humidity_rate", "Humidity rate of change")
{
AdditionalConfig = new { unit_of_measurement = "%/min", icon = "mdi:chart-line", device }
},
new ShowerMonitorEntity("sensor", "showermonitor_today_session_count", "Showers today")
{
AdditionalConfig = new { icon = "mdi:counter", device }
},
new ShowerMonitorEntity("sensor", "showermonitor_last_shower_duration", "Last shower duration")
{
AdditionalConfig = new { unit_of_measurement = "s", icon = "mdi:timer", device_class = "duration", device }
},
new ShowerMonitorEntity("sensor", "showermonitor_last_shower_time", "Last shower time")
{
AdditionalConfig = new { icon = "mdi:clock-outline", device }
},
new ShowerMonitorEntity("button", "showermonitor_cleanup", "Cleanup all entities")
{
AdditionalConfig = new { icon = "mdi:delete-sweep", device }
}
];
}
private async Task UpdateDifferentialAsync(double differential, string timestamp)
{
await SetEntityStateSafe(DifferentialEntityId, 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);
}
private async Task UpdateHumidityRateAsync(double rate, string timestamp)
{
await SetEntityStateSafe(HumidityRateEntityId, Math.Round(rate, 2).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
await SetEntityAttributesSafe(HumidityRateEntityId, new
{
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);
await SetEntityAttributesSafe(TodaySessionCountEntityId, new
{
friendly_name = "Showers today",
last_updated = timestamp
}).ConfigureAwait(false);
}
private async Task UpdateLastShowerAsync(ShowerSession? session, string timestamp)
{
if (session is null)
{
return;
}
var durationSeconds = (int)session.Duration.TotalSeconds;
await SetEntityStateSafe(LastShowerDurationEntityId, durationSeconds.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
await SetEntityAttributesSafe(LastShowerDurationEntityId, new
{
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")).ConfigureAwait(false);
await SetEntityAttributesSafe(LastShowerTimeEntityId, new
{
friendly_name = "Last shower time",
last_updated = timestamp
}).ConfigureAwait(false);
}
private async Task SetEntityStateSafe(string entityId, string state)
{
try
{
await entityManager.SetEntityState(entityId, state).ConfigureAwait(false);
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to set state for {EntityId} to {State}", entityId, state);
}
}
private async Task SetEntityAttributesSafe(string entityId, object attributes)
{
try
{
await entityManager.SetEntityAttributes(entityId, attributes).ConfigureAwait(false);
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to set attributes for {EntityId}", entityId);
}
}
private static string FormatDuration(TimeSpan ts)
{
var totalMinutes = (int)ts.TotalMinutes;
var seconds = ts.Seconds;
return $"{totalMinutes}m {seconds}s";
}
}
+224
View File
@@ -0,0 +1,224 @@
using System.Globalization;
using System.Reactive.Concurrency;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NetDaemon.AppModel;
using NetDaemon.Extensions.Scheduler;
using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
using ShowerMonitor.Models.Enums;
using ShowerMonitorManager.Interface;
using ShowerMonitorManager.Models;
using static ShowerMonitor.Models.ShowerMonitorConsts;
namespace ShowerMonitorManager;
[NetDaemonApp]
public sealed class ShowerMonitorInit : IShowerMonitorInit
{
private readonly ILogger<ShowerMonitorInit> _logger;
private readonly IHaContext _haContext;
private readonly IScheduler _scheduler;
private readonly IShowerDetectionService _detectionService;
private readonly IHumidityRateCalculator _rateCalculator;
private readonly IExhaustFanControlService _fanControlService;
private readonly IShowerMonitorEntityService _entityService;
private readonly ShowerMonitorOptions _options;
private bool _cleanedUp;
public ShowerMonitorInit(
IHaContext haContext,
ILogger<ShowerMonitorInit> logger,
IScheduler scheduler,
IShowerDetectionService detectionService,
IHumidityRateCalculator rateCalculator,
IExhaustFanControlService fanControlService,
IShowerMonitorEntityService entityService,
IOptions<ShowerMonitorOptions> options)
{
_haContext = haContext;
_logger = logger;
_scheduler = scheduler;
_detectionService = detectionService;
_rateCalculator = rateCalculator;
_fanControlService = fanControlService;
_entityService = entityService;
_options = options.Value;
_ = InitializeAndScheduleAsync();
}
private async Task InitializeAndScheduleAsync()
{
try
{
await InitializeAsync();
SchedulePeriodicPolling();
ScheduleMidnightReset();
SubscribeToCleanupButton();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error during ShowerMonitor initialization and scheduling");
}
}
public async Task InitializeAsync()
{
try
{
await Task.Delay(TimeSpan.FromSeconds(3));
if (_options.CleanupEntitiesOnStartup)
{
await _entityService.CleanupEntitiesAsync();
}
await _entityService.CreateEntitiesAsync();
await _entityService.ResetEntitiesAsync();
await Task.Delay(TimeSpan.FromSeconds(2));
await PollAndUpdateAsync();
_logger.LogInformation("ShowerMonitor initialized");
}
catch (Exception ex)
{
_logger.LogError(ex, "Error initializing ShowerMonitor");
throw;
}
}
public async Task CleanupEntitiesAsync(CancellationToken cancellationToken = default)
{
await _entityService.CleanupEntitiesAsync(cancellationToken);
}
private void SchedulePeriodicPolling()
{
var pollInterval = TimeSpan.FromSeconds(_options.PollIntervalSeconds);
var now = DateTime.Now;
var currentSecondInInterval = (now.Minute * 60 + now.Second) % _options.PollIntervalSeconds;
var secondsUntilNext = _options.PollIntervalSeconds - currentSecondInInterval;
var nextPollTime = now.Add(TimeSpan.FromSeconds(secondsUntilNext));
_logger.LogInformation("Scheduling ShowerMonitor polling every {Interval}s, first at {Time}", _options.PollIntervalSeconds, nextPollTime);
_scheduler.RunEvery(pollInterval, nextPollTime, async void () =>
{
try
{
await PollAndUpdateAsync();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error during ShowerMonitor poll cycle");
}
});
}
private void ScheduleMidnightReset()
{
_scheduler.ScheduleCron("0 0 * * *", () =>
{
try
{
_logger.LogInformation("Midnight reset: clearing shower session counters");
_detectionService.ResetDailyCounters();
_ = _entityService.ResetEntitiesAsync();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error during midnight reset");
}
});
}
private void SubscribeToCleanupButton()
{
var cleanupButton = new Entity(_haContext, CleanupButtonEntityId);
cleanupButton.StateChanges()
.Subscribe(_ =>
{
_logger.LogInformation("Cleanup button pressed, removing all ShowerMonitor entities");
Task.Run(HandleCleanupAsync);
});
}
private async Task HandleCleanupAsync()
{
try
{
await _entityService.CleanupEntitiesAsync();
_cleanedUp = true;
_detectionService.ResetDailyCounters();
_fanControlService.Reset(_haContext);
_logger.LogInformation("ShowerMonitor cleanup complete");
}
catch (Exception ex)
{
_logger.LogError(ex, "Error during ShowerMonitor cleanup");
}
}
private async Task PollAndUpdateAsync()
{
if (_cleanedUp)
{
_logger.LogDebug("ShowerMonitor is cleaned up, skipping poll");
return;
}
try
{
var bathroomHumidity = ReadSensorDouble(_options.BathroomHumidityEntityId);
var mainHomeHumidity = ReadSensorDouble(_options.MainHomeHumidityEntityId);
if (!bathroomHumidity.HasValue || !mainHomeHumidity.HasValue)
{
_logger.LogDebug("Humidity sensor data unavailable (bathroom={Bathroom}, home={Home})", bathroomHumidity, mainHomeHumidity);
return;
}
var timestamp = DateTimeOffset.UtcNow;
var state = _detectionService.Evaluate(bathroomHumidity.Value, mainHomeHumidity.Value, timestamp);
var differential = bathroomHumidity.Value - mainHomeHumidity.Value;
_fanControlService.Evaluate(state, timestamp, _haContext);
var context = new ShowerMonitorUpdateContext
{
State = state,
BathroomHumidity = bathroomHumidity.Value,
MainHomeHumidity = mainHomeHumidity.Value,
Differential = differential,
HumidityRate = _rateCalculator.GetRatePerMinute(),
TodaySessionCount = _detectionService.TodaySessionCount,
LastCompletedSession = _detectionService.LastCompletedSession,
CurrentSession = _detectionService.CurrentSession
};
await _entityService.UpdateEntitiesAsync(context);
_logger.LogDebug("Poll: bathroom={Bath}%, home={Home}%, diff={Diff}%, state={State}",
bathroomHumidity.Value, mainHomeHumidity.Value, Math.Round(differential, 1), state);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error during ShowerMonitor poll");
}
}
private double? ReadSensorDouble(string entityId)
{
var state = _haContext.GetState(entityId);
if (state?.State is null or "unavailable" or "unknown")
{
return null;
}
return double.TryParse(state.State, CultureInfo.InvariantCulture, out var value) ? value : null;
}
}
@@ -0,0 +1,32 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using NetDaemon.AppModel;
using ShowerMonitorManager.Interface;
using ShowerMonitorManager.Models;
using static ShowerMonitor.Models.ShowerMonitorConsts;
namespace ShowerMonitorManager;
public static class ShowerMonitorServiceRegistration
{
public static IServiceCollection AddShowerMonitor(this IServiceCollection services, IConfiguration configuration)
{
var options = configuration
.GetSection(ShowerMonitorOptions.SectionName)
.Get<ShowerMonitorOptions>() ?? new ShowerMonitorOptions();
if (!options.Enabled)
{
return services;
}
services
.AddNetDaemonApp<ShowerMonitorInit>()
.AddSingleton<IHumidityRateCalculator>(_ => new HumidityRateCalculator(options.RateWindowSize))
.AddSingleton<IShowerDetectionService, ShowerDetectionService>()
.AddSingleton<IExhaustFanControlService, ExhaustFanControlService>()
.AddTransient<IShowerMonitorEntityService, ShowerMonitorEntityService>();
return services;
}
}