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);
}
}