Files
HomeAssistant/PowerMonitor.Manager/PowerLimitEnforcementService.cs
T
gitea_admin 1152462765 Add PowerMonitor power limit enforcement service
Introduce IPowerLimitEnforcementService and its implementation: turn off configured high-power switches and pause/restore entities when the limit is exceeded, notify via persistent_notification, and restore control after the recovery window once power drops below the limit. Includes cooldown handling and manual TriggerLimitBreach/ResetLimitBreach hooks, with FakeTimeProvider-based tests covering enforcement, recovery, cooldown and debug paths.

Add opencode.json wiring the HomeAssistant MCP server, the .junie MCP config files, and the implementation plan in PLAN.md.
2026-11-29 13:58:28 +02:00

193 lines
5.9 KiB
C#

using System.Globalization;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NetDaemon.HassModel;
using NetDaemon.HassModel.Entities;
using PowerMonitorManager.Interface;
using PowerMonitorManager.Models;
using PowerMonitorManager.Models.Consts;
namespace PowerMonitorManager;
public sealed class PowerLimitEnforcementService(
IHaContext haContext,
ILogger<PowerLimitEnforcementService> logger,
IOptions<PowerMonitorOptions> options,
TimeProvider timeProvider)
: IPowerLimitEnforcementService
{
private readonly PowerMonitorOptions _options = options.Value;
private bool _isLimitActive;
private DateTimeOffset _enforcedAt;
private DateTimeOffset _lastActionTime;
public bool IsLimitActive => _isLimitActive;
public void EnforceLimit(double currentPowerWatts)
{
if (!_options.EnforceLimitEnabled)
{
return;
}
var now = timeProvider.GetUtcNow();
if (!_isLimitActive)
{
TryEnforce(currentPowerWatts, now);
return;
}
EvaluateRecovery(currentPowerWatts, now);
}
public void TriggerLimitBreach()
{
if (_isLimitActive)
{
logger.LogInformation("Debug: trigger requested but limit already active");
return;
}
logger.LogWarning("Debug: triggering power limit breach manually");
ExecuteEnforce(_options.PowerLimitWatts);
}
public void ResetLimitBreach()
{
if (!_isLimitActive)
{
logger.LogInformation("Debug: reset requested but limit not active");
return;
}
logger.LogWarning("Debug: resetting power limit breach manually");
ExecuteRecover();
}
private void ExecuteEnforce(double currentPowerWatts)
{
foreach (var entityId in _options.EnforceSwitchOffEntityIds)
{
TurnOff(entityId);
}
foreach (var entityId in _options.PauseAndRestoreEntityIds)
{
TurnOff(entityId);
}
NotifyLimitEnforced(currentPowerWatts, _options.PowerLimitWatts);
_isLimitActive = true;
var now = timeProvider.GetUtcNow();
_enforcedAt = now;
_lastActionTime = now;
}
private void ExecuteRecover()
{
foreach (var entityId in _options.PauseAndRestoreEntityIds)
{
TurnOn(entityId);
}
DismissLimitNotification();
_isLimitActive = false;
_lastActionTime = timeProvider.GetUtcNow();
}
private void TryEnforce(double currentPowerWatts, DateTimeOffset now)
{
if (currentPowerWatts <= _options.PowerLimitWatts)
{
return;
}
if (now - _lastActionTime < TimeSpan.FromSeconds(_options.LimitCooldownSeconds))
{
logger.LogDebug("Power limit breach detected ({Power:F0} W > {Limit:F0} W) but cooldown active, skipping", currentPowerWatts, _options.PowerLimitWatts);
return;
}
logger.LogWarning("Power limit exceeded: {Power:F0} W > {Limit:F0} W, enforcing turn-off", currentPowerWatts, _options.PowerLimitWatts);
ExecuteEnforce(currentPowerWatts);
}
private void EvaluateRecovery(double currentPowerWatts, DateTimeOffset now)
{
var elapsed = now - _enforcedAt;
if (elapsed < TimeSpan.FromSeconds(_options.RecoverySeconds))
{
return;
}
if (currentPowerWatts >= _options.PowerLimitWatts)
{
logger.LogWarning("Recovery time reached but power still {Power:F0} W >= {Limit:F0} W, staying enforced", currentPowerWatts, _options.PowerLimitWatts);
_enforcedAt = now;
return;
}
logger.LogInformation("Power recovered to {Power:F0} W (< {Limit:F0} W) after {Seconds}s, restoring paused monitors", currentPowerWatts, _options.PowerLimitWatts, (int)elapsed.TotalSeconds);
foreach (var entityId in _options.PauseAndRestoreEntityIds)
{
TurnOn(entityId);
}
DismissLimitNotification();
_isLimitActive = false;
_lastActionTime = now;
}
private void TurnOff(string entityId)
{
haContext.CallService(PowerMonitorConsts.SwitchDomain, PowerMonitorConsts.TurnOffService, ServiceTarget.FromEntity(entityId));
}
private void TurnOn(string entityId)
{
haContext.CallService(PowerMonitorConsts.SwitchDomain, PowerMonitorConsts.TurnOnService, ServiceTarget.FromEntity(entityId));
}
private void NotifyLimitEnforced(double currentPowerWatts, double limitWatts)
{
var message = BuildLimitMessage(currentPowerWatts / PowerMonitorConsts.WattsPerKilowatt, limitWatts / PowerMonitorConsts.WattsPerKilowatt);
haContext.CallService(
PowerMonitorConsts.PersistentNotificationDomain,
PowerMonitorConsts.PersistentNotificationCreateService,
data: new
{
title = PowerMonitorConsts.PowerLimitNotificationTitle,
message,
notification_id = PowerMonitorConsts.PowerLimitNotificationId
});
}
private void DismissLimitNotification()
{
haContext.CallService(
PowerMonitorConsts.PersistentNotificationDomain,
PowerMonitorConsts.PersistentNotificationDismissService,
data: new
{
notification_id = PowerMonitorConsts.PowerLimitNotificationId
});
}
internal static string BuildLimitMessage(double currentKw, double limitKw)
{
return string.Format(CultureInfo.InvariantCulture,
"Home power usage **{0:F2} kW** exceeded the limit of **{1:F1} kW**.\n\nHigh-power appliances have been turned off and automatic control paused. Normal control resumes after power drops below the limit.",
currentKw, limitKw);
}
}