Files
HomeAssistant/PowerMonitor.Manager/PowerLimitEnforcementService.cs
T
gitea_admin 77458383d1 Add braces to single-statement guards and refactor NordPool price fetching
- Expand inline guard, return and logger blocks across the monitor services, init classes and tests
- Have INordPoolPriceService take a per-date fetch delegate and expose ParseAndAdjust, moving the HA fetch call into NordPoolInit so the service can be registered singleton
- Record the NordPool and boiler service lifetimes in AGENTS.md
- Drop the unused persisted-state argument from the boiler test data helper
2026-12-01 11:59:31 +02:00

186 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 DateTimeOffset _enforcedAt;
private DateTimeOffset _lastActionTime;
public bool IsLimitActive { get; private set; }
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))
{
if (logger.IsEnabled(LogLevel.Debug))
{
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;
}
if (logger.IsEnabled(LogLevel.Information))
{
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);
}
}