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.
This commit is contained in:
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"mcpServers": {
|
||||
"UnoApp": {
|
||||
"command": "dotnet",
|
||||
"args": [
|
||||
"dnx",
|
||||
"-y",
|
||||
"uno.devserver",
|
||||
"--mcp-app"
|
||||
]
|
||||
},
|
||||
"UnoDocs": {
|
||||
"url": "https://mcp.platform.uno/v1"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"mcpServers": {
|
||||
"UnoApp": {
|
||||
"command": "dotnet",
|
||||
"args": [
|
||||
"dnx",
|
||||
"-y",
|
||||
"uno.devserver",
|
||||
"--mcp-app"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
# Power Limit Enforcement — Implementation Plan
|
||||
|
||||
Extend existing (unused) PowerMonitor with power-limit enforcement. Switch from
|
||||
1s polling to main-meter state-change trigger. On breach, turn off boiler
|
||||
switch + `switch.boilermonitor_auto_management`. Recover after 10 min if power
|
||||
dropped. Enable monitor. Default on. Reuse `persistent_notification`.
|
||||
|
||||
## Decisions locked
|
||||
|
||||
1. Extend PowerMonitor (enable + fix), not a new monitor.
|
||||
2. Enforce = turn off boiler physical switch AND `switch.boilermonitor_auto_management`.
|
||||
3. Recovery after 10 min (config `RecoverySeconds`). If power still over limit at
|
||||
recovery check, stay enforced + wait another 10 min.
|
||||
4. Default enabled (`EnforceLimitEnabled=true`, monitor `Enabled=true`).
|
||||
5. Reuse `persistent_notification` for notifications.
|
||||
6. Event-driven (meter state change), NOT periodic poll. Trust meter (no
|
||||
fallback timer).
|
||||
|
||||
## Files
|
||||
|
||||
### New (3)
|
||||
|
||||
- `PowerMonitor.Manager/Interface/IPowerLimitEnforcementService.cs`
|
||||
- `PowerMonitor.Manager/PowerLimitEnforcementService.cs`
|
||||
- `PowerMonitor.Manager.Tests/PowerLimitEnforcementServiceTests.cs`
|
||||
|
||||
### Edit (5)
|
||||
|
||||
- `PowerMonitor.Manager/Models/Consts/PowerMonitorConsts.cs` — 3 new default consts
|
||||
- `PowerMonitor.Manager/Models/PowerMonitorOptions.cs` — 6 new props
|
||||
- `PowerMonitor.Manager/PowerMonitorInit.cs` — replace polling w/ state-change sub;
|
||||
inject enforcement svc; call after high-power notify; fix cost-calc elapsed time
|
||||
- `PowerMonitor.Manager/PowerMonitorServiceRegistration.cs` — register transient
|
||||
- `PowerMonitor.Manager.Tests/PowerMonitorOptionsTests.cs` — new props
|
||||
- `HomeAssistant.Server/appsettings.json` — PowerMonitor `Enabled:true` + new keys
|
||||
|
||||
No `program.cs` change (options already `Configure<PowerMonitorOptions>`).
|
||||
|
||||
## Trigger refactor
|
||||
|
||||
Replace `SchedulePeriodicPolling()` (lines 104-118) with `SubscribeToMainMeterChanges()`:
|
||||
|
||||
```csharp
|
||||
private void SubscribeToMainMeterChanges()
|
||||
{
|
||||
var meter = new Entity(_haContext, _options.MainMeterEntityId);
|
||||
meter.StateChanges()
|
||||
.Subscribe(e =>
|
||||
{
|
||||
if (e.Old?.State == e.New?.State) return;
|
||||
_ = PollAndUpdateAsync();
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
Called from `InitializeAndScheduleAsync()` instead of `SchedulePeriodicPolling()`.
|
||||
Keep initial `PollAndUpdateAsync()` in `InitializeAsync` (line 90). Pattern matches
|
||||
`BoilerMonitorInit.SubscribeToSkipPriceCapChanges:227`.
|
||||
|
||||
## Cost-calc fix (event-driven elapsed time)
|
||||
|
||||
Add `_lastPollTimestamp` field. In `PollAndUpdateAsync`:
|
||||
|
||||
```csharp
|
||||
var now = _timeProvider.GetLocalNow();
|
||||
var elapsed = _lastPollTimestamp.HasValue
|
||||
? Math.Min((now - _lastPollTimestamp.Value).TotalSeconds, _options.PollIntervalSeconds * 10)
|
||||
: _options.PollIntervalSeconds;
|
||||
_lastPollTimestamp = now;
|
||||
_costService.RecordCosts(calculation, nordPoolPrice, (int)Math.Max(1, elapsed), now.LocalDateTime);
|
||||
```
|
||||
|
||||
Cap = `PollInterval x 10` prevents huge cost jumps on meter silence. Min 1 prevents
|
||||
div-by-zero.
|
||||
|
||||
## Options (`PowerMonitorOptions` + `PowerMonitorConsts`)
|
||||
|
||||
| Prop | Type | Const default |
|
||||
|---|---|---|
|
||||
| `EnforceLimitEnabled` | bool | `true` |
|
||||
| `PowerLimitWatts` | double | `DefaultPowerLimitWatts=5500` |
|
||||
| `RecoverySeconds` | int | `DefaultRecoverySeconds=600` |
|
||||
| `LimitCooldownSeconds` | int | `DefaultLimitCooldownSeconds=30` |
|
||||
| `EnforceSwitchOffEntityIds` | string[] | `["switch.sonoff_1002230e32"]` |
|
||||
| `PauseAndRestoreEntityIds` | string[] | `["switch.boilermonitor_auto_management"]` |
|
||||
|
||||
New consts in `PowerMonitorConsts.cs`:
|
||||
- `DefaultPowerLimitWatts = 5500.0`
|
||||
- `DefaultRecoverySeconds = 600`
|
||||
- `DefaultLimitCooldownSeconds = 30`
|
||||
- `PowerLimitNotificationId = "power_monitor_power_limit"`
|
||||
- `PowerLimitNotificationTitle = "Power Limit Enforced"`
|
||||
|
||||
## Service `IPowerLimitEnforcementService` (transient: `IHaContext` + `IOptions<PowerMonitorOptions>` + `TimeProvider`)
|
||||
|
||||
```csharp
|
||||
void EnforceLimit(double currentPowerWatts);
|
||||
bool IsLimitActive { get; }
|
||||
```
|
||||
|
||||
State: `_isLimitActive`, `_enforcedAt`, `_lastActionTime`.
|
||||
|
||||
### Logic per call
|
||||
|
||||
- `!_isLimitActive && power > PowerLimitWatts && now-_lastAction >= Cooldown`:
|
||||
1. `switch.turn_off` each `EnforceSwitchOffEntityIds` (boiler first — race-safe)
|
||||
2. `switch.turn_off` each `PauseAndRestoreEntityIds` (auto_management)
|
||||
3. `persistent_notification.create` "Power Limit Enforced"
|
||||
4. `_isLimitActive=true; _enforcedAt=now; _lastAction=now;`
|
||||
- `_isLimitActive`:
|
||||
- `now-_enforcedAt < RecoverySeconds` -> no-op (waiting)
|
||||
- `power < PowerLimitWatts` -> `switch.turn_on` each `PauseAndRestoreEntityIds`;
|
||||
dismiss notif; `_isLimitActive=false`
|
||||
- `power >= PowerLimitWatts` -> `_enforcedAt=now` (wait another 10 min, keep notif)
|
||||
- else no-op
|
||||
|
||||
Never turn boiler switch back on — BoilerMonitor decides on next cheap interval.
|
||||
|
||||
## Wire into poll loop
|
||||
|
||||
`PowerMonitorInit.PollAndUpdateAsync` after `EvaluateHighPowerNotification(...)` (line 232):
|
||||
|
||||
```csharp
|
||||
if (_options.EnforceLimitEnabled)
|
||||
_enforcementService.EnforceLimit(calculation.TotalPowerWatts);
|
||||
```
|
||||
|
||||
Add `IPowerLimitEnforcementService` to ctor.
|
||||
|
||||
## Register
|
||||
|
||||
`PowerMonitorServiceRegistration.cs`:
|
||||
|
||||
```csharp
|
||||
.AddTransient<IPowerLimitEnforcementService, PowerLimitEnforcementService>()
|
||||
```
|
||||
|
||||
Transient (injects `IHaContext` — AGENTS.md DI rule, never singleton).
|
||||
|
||||
## appsettings.json `PowerMonitor`
|
||||
|
||||
```json
|
||||
"PowerMonitor": {
|
||||
"Enabled": true,
|
||||
"MainMeterEntityId": "sensor.sonoff_100267d63f_power",
|
||||
"PollIntervalSeconds": 1,
|
||||
"SmoothingWindowSize": 10,
|
||||
"AnomalyThresholdWatts": 500,
|
||||
"HighPowerThresholdWatts": 6000,
|
||||
"EnforceLimitEnabled": true,
|
||||
"PowerLimitWatts": 5500,
|
||||
"RecoverySeconds": 600,
|
||||
"LimitCooldownSeconds": 30,
|
||||
"EnforceSwitchOffEntityIds": [ "switch.sonoff_1002230e32" ],
|
||||
"PauseAndRestoreEntityIds": [ "switch.boilermonitor_auto_management" ],
|
||||
"ExcludedSensorPatterns": [
|
||||
"sensor.nordpool_*",
|
||||
"sensor.powermonitor_*"
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
`PollIntervalSeconds` kept = 1 (now used as fallback/default elapsed + cap base).
|
||||
|
||||
## Tests
|
||||
|
||||
### `PowerLimitEnforcementServiceTests` (new)
|
||||
|
||||
- Breach -> turn-off order: boiler switch before auto_management (Moq `CallService`
|
||||
sequence assert)
|
||||
- Recovery at 10min + power<limit -> auto_mgmt on, boiler switch NOT turned on
|
||||
- Recovery at 10min + power still high -> `_enforcedAt` resets, stays enforced
|
||||
- Before 10min -> no-op
|
||||
- Cooldown blocks rapid re-enforce
|
||||
- `EnforceLimitEnabled=false` -> no-op
|
||||
- Use `FakeTimeProvider` for time advance
|
||||
- Add `Microsoft.Extensions.TimeProvider.Testing` package to test csproj
|
||||
|
||||
### `PowerMonitorOptionsTests` (extend)
|
||||
|
||||
- 6 new props defaults + `SectionName=="PowerMonitor"`
|
||||
|
||||
## Verify after implementation
|
||||
|
||||
1. `dotnet build PowerMonitor.Manager`
|
||||
2. `dotnet test PowerMonitor.Manager.Tests`
|
||||
3. `dotnet build HomeAssistantSDK.sln`
|
||||
4. `RunSmokeTest` MCP (homeassistant server)
|
||||
5. `ValidateEntities`: `sensor.sonoff_100267d63f_power`, `switch.sonoff_1002230e32`,
|
||||
`switch.boilermonitor_auto_management`
|
||||
@@ -0,0 +1,345 @@
|
||||
using FluentAssertions;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.Extensions.Time.Testing;
|
||||
using Moq;
|
||||
using NetDaemon.HassModel;
|
||||
using NetDaemon.HassModel.Entities;
|
||||
using PowerMonitorManager;
|
||||
using PowerMonitorManager.Models;
|
||||
|
||||
namespace PowerMonitor.Manager.Tests;
|
||||
|
||||
public class PowerLimitEnforcementServiceTests
|
||||
{
|
||||
private const string BoilerSwitch = "switch.sonoff_1002230e32";
|
||||
private const string AutoManagement = "switch.boilermonitor_auto_management";
|
||||
|
||||
private readonly Mock<IHaContext> _haContextMock;
|
||||
private readonly Mock<ILogger<PowerLimitEnforcementService>> _loggerMock;
|
||||
private readonly FakeTimeProvider _timeProvider;
|
||||
private readonly PowerMonitorOptions _options;
|
||||
|
||||
public PowerLimitEnforcementServiceTests()
|
||||
{
|
||||
_haContextMock = new Mock<IHaContext>();
|
||||
_loggerMock = new Mock<ILogger<PowerLimitEnforcementService>>();
|
||||
_timeProvider = new FakeTimeProvider(DateTimeOffset.UtcNow);
|
||||
_options = new PowerMonitorOptions
|
||||
{
|
||||
EnforceLimitEnabled = true,
|
||||
PowerLimitWatts = 5500,
|
||||
RecoverySeconds = 600,
|
||||
LimitCooldownSeconds = 30,
|
||||
EnforceSwitchOffEntityIds = [BoilerSwitch],
|
||||
PauseAndRestoreEntityIds = [AutoManagement]
|
||||
};
|
||||
}
|
||||
|
||||
private PowerLimitEnforcementService CreateSut() =>
|
||||
new(
|
||||
_haContextMock.Object,
|
||||
_loggerMock.Object,
|
||||
Options.Create(_options),
|
||||
_timeProvider);
|
||||
|
||||
private static bool IsTurnOffCall(string domain, string service, string entityId) =>
|
||||
domain == "switch" && service == "turn_off";
|
||||
|
||||
private static bool IsTurnOnCall(string domain, string service, string entityId) =>
|
||||
domain == "switch" && service == "turn_on";
|
||||
|
||||
[Fact]
|
||||
public void EnforceLimit_WhenDisabled_ShouldNotCallAnyService()
|
||||
{
|
||||
_options.EnforceLimitEnabled = false;
|
||||
var sut = CreateSut();
|
||||
|
||||
sut.EnforceLimit(6000);
|
||||
|
||||
_haContextMock.Verify(
|
||||
x => x.CallService(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ServiceTarget>(), It.IsAny<object?>()),
|
||||
Times.Never);
|
||||
sut.IsLimitActive.Should().BeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EnforceLimit_WhenPowerBelowLimit_ShouldNotEnforce()
|
||||
{
|
||||
var sut = CreateSut();
|
||||
|
||||
sut.EnforceLimit(5000);
|
||||
|
||||
sut.IsLimitActive.Should().BeFalse();
|
||||
_haContextMock.Verify(
|
||||
x => x.CallService(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ServiceTarget>(), It.IsAny<object?>()),
|
||||
Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EnforceLimit_WhenPowerExceedsLimit_ShouldTurnOffSwitchesAndPauseMonitors()
|
||||
{
|
||||
var sut = CreateSut();
|
||||
|
||||
sut.EnforceLimit(6000);
|
||||
|
||||
sut.IsLimitActive.Should().BeTrue();
|
||||
// turn_off called for boiler switch + auto_management
|
||||
_haContextMock.Verify(
|
||||
x => x.CallService("switch", "turn_off", It.Is<ServiceTarget>(t => t.EntityIds!.Contains(BoilerSwitch)), null),
|
||||
Times.Once);
|
||||
_haContextMock.Verify(
|
||||
x => x.CallService("switch", "turn_off", It.Is<ServiceTarget>(t => t.EntityIds!.Contains(AutoManagement)), null),
|
||||
Times.Once);
|
||||
// notification created
|
||||
_haContextMock.Verify(
|
||||
x => x.CallService("persistent_notification", "create", It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
|
||||
Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EnforceLimit_WhenBreached_ShouldTurnOffBoilerBeforeAutoManagement()
|
||||
{
|
||||
var calls = new List<(string domain, string service, string? entityId)>();
|
||||
_haContextMock
|
||||
.Setup(x => x.CallService(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ServiceTarget>(), It.IsAny<object?>()))
|
||||
.Callback<string, string, ServiceTarget?, object?>((d, s, t, _) =>
|
||||
calls.Add((d, s, t?.EntityIds?.FirstOrDefault())));
|
||||
var sut = CreateSut();
|
||||
|
||||
sut.EnforceLimit(6000);
|
||||
|
||||
var turnOffCalls = calls.Where(c => c.service == "turn_off").ToList();
|
||||
turnOffCalls.Should().HaveCount(2);
|
||||
turnOffCalls[0].entityId.Should().Be(BoilerSwitch, "boiler switch must be turned off before auto_management (race-safe order)");
|
||||
turnOffCalls[1].entityId.Should().Be(AutoManagement);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EnforceLimit_WhenAlreadyActiveAndBeforeRecoveryTime_ShouldDoNothing()
|
||||
{
|
||||
var sut = CreateSut();
|
||||
sut.EnforceLimit(6000);
|
||||
_haContextMock.Invocations.Clear();
|
||||
|
||||
// advance less than recovery
|
||||
_timeProvider.Advance(TimeSpan.FromMinutes(5));
|
||||
sut.EnforceLimit(5000);
|
||||
|
||||
sut.IsLimitActive.Should().BeTrue();
|
||||
_haContextMock.Verify(
|
||||
x => x.CallService(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ServiceTarget>(), It.IsAny<object?>()),
|
||||
Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EnforceLimit_WhenRecoveryTimeReachedAndPowerBelowLimit_ShouldRestoreMonitorsAndNotTurnBoilerOn()
|
||||
{
|
||||
var sut = CreateSut();
|
||||
sut.EnforceLimit(6000);
|
||||
_haContextMock.Invocations.Clear();
|
||||
|
||||
_timeProvider.Advance(TimeSpan.FromSeconds(601));
|
||||
sut.EnforceLimit(4000);
|
||||
|
||||
sut.IsLimitActive.Should().BeFalse();
|
||||
// auto_management turned back ON
|
||||
_haContextMock.Verify(
|
||||
x => x.CallService("switch", "turn_on", It.Is<ServiceTarget>(t => t.EntityIds!.Contains(AutoManagement)), null),
|
||||
Times.Once);
|
||||
// boiler switch should NOT be turned back on
|
||||
_haContextMock.Verify(
|
||||
x => x.CallService("switch", "turn_on", It.Is<ServiceTarget>(t => t.EntityIds!.Contains(BoilerSwitch)), null),
|
||||
Times.Never);
|
||||
// notification dismissed
|
||||
_haContextMock.Verify(
|
||||
x => x.CallService("persistent_notification", "dismiss", It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
|
||||
Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EnforceLimit_WhenRecoveryTimeReachedButPowerStillHigh_ShouldStayEnforcedAndResetTimer()
|
||||
{
|
||||
var sut = CreateSut();
|
||||
sut.EnforceLimit(6000);
|
||||
_haContextMock.Invocations.Clear();
|
||||
|
||||
_timeProvider.Advance(TimeSpan.FromSeconds(601));
|
||||
sut.EnforceLimit(5800);
|
||||
|
||||
sut.IsLimitActive.Should().BeTrue();
|
||||
// no restore, no dismiss
|
||||
_haContextMock.Verify(
|
||||
x => x.CallService("switch", "turn_on", It.IsAny<ServiceTarget>(), It.IsAny<object?>()),
|
||||
Times.Never);
|
||||
_haContextMock.Verify(
|
||||
x => x.CallService("persistent_notification", "dismiss", It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
|
||||
Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EnforceLimit_WhenRecoveryTimeReachedButPowerStillHigh_ShouldAllowAnotherRecoveryCheckAfterWait()
|
||||
{
|
||||
var sut = CreateSut();
|
||||
sut.EnforceLimit(6000);
|
||||
|
||||
// first recovery check - still high, timer resets
|
||||
_timeProvider.Advance(TimeSpan.FromSeconds(601));
|
||||
sut.EnforceLimit(5800);
|
||||
sut.IsLimitActive.Should().BeTrue();
|
||||
|
||||
// immediately after - not enough time, no-op
|
||||
sut.EnforceLimit(3000);
|
||||
sut.IsLimitActive.Should().BeTrue();
|
||||
|
||||
// after another full wait - power dropped, recovers
|
||||
_timeProvider.Advance(TimeSpan.FromSeconds(601));
|
||||
sut.EnforceLimit(3000);
|
||||
sut.IsLimitActive.Should().BeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EnforceLimit_WhenCooldownActive_ShouldNotReEnforce()
|
||||
{
|
||||
var sut = CreateSut();
|
||||
sut.EnforceLimit(6000);
|
||||
sut.IsLimitActive.Should().BeTrue();
|
||||
|
||||
// recover so we can re-trigger
|
||||
_timeProvider.Advance(TimeSpan.FromSeconds(601));
|
||||
sut.EnforceLimit(3000);
|
||||
sut.IsLimitActive.Should().BeFalse();
|
||||
|
||||
_haContextMock.Invocations.Clear();
|
||||
|
||||
// immediately breach again - within cooldown, should NOT enforce
|
||||
sut.EnforceLimit(6000);
|
||||
sut.IsLimitActive.Should().BeFalse("cooldown should block immediate re-enforcement");
|
||||
_haContextMock.Verify(
|
||||
x => x.CallService("switch", "turn_off", It.IsAny<ServiceTarget>(), It.IsAny<object?>()),
|
||||
Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EnforceLimit_WhenCooldownPassed_ShouldReEnforce()
|
||||
{
|
||||
var sut = CreateSut();
|
||||
sut.EnforceLimit(6000);
|
||||
_timeProvider.Advance(TimeSpan.FromSeconds(601));
|
||||
sut.EnforceLimit(3000);
|
||||
sut.IsLimitActive.Should().BeFalse();
|
||||
|
||||
// wait past cooldown
|
||||
_timeProvider.Advance(TimeSpan.FromSeconds(31));
|
||||
_haContextMock.Invocations.Clear();
|
||||
|
||||
sut.EnforceLimit(6000);
|
||||
sut.IsLimitActive.Should().BeTrue();
|
||||
_haContextMock.Verify(
|
||||
x => x.CallService("switch", "turn_off", It.IsAny<ServiceTarget>(), It.IsAny<object?>()),
|
||||
Times.AtLeastOnce);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EnforceLimit_WhenExactlyAtLimit_ShouldNotEnforce()
|
||||
{
|
||||
var sut = CreateSut();
|
||||
|
||||
sut.EnforceLimit(5500);
|
||||
|
||||
sut.IsLimitActive.Should().BeFalse("power equal to limit should not trigger (strict greater-than)");
|
||||
_haContextMock.Verify(
|
||||
x => x.CallService(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ServiceTarget>(), It.IsAny<object?>()),
|
||||
Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildLimitMessage_ShouldContainCurrentAndLimitInKw()
|
||||
{
|
||||
var message = PowerLimitEnforcementService.BuildLimitMessage(6.0, 5.5);
|
||||
|
||||
message.Should().Contain("6.00 kW");
|
||||
message.Should().Contain("5.5 kW");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TriggerLimitBreach_WhenNotActive_ShouldEnforceRegardlessOfPower()
|
||||
{
|
||||
var sut = CreateSut();
|
||||
|
||||
sut.TriggerLimitBreach();
|
||||
|
||||
sut.IsLimitActive.Should().BeTrue();
|
||||
_haContextMock.Verify(
|
||||
x => x.CallService("switch", "turn_off", It.Is<ServiceTarget>(t => t.EntityIds!.Contains(BoilerSwitch)), null),
|
||||
Times.Once);
|
||||
_haContextMock.Verify(
|
||||
x => x.CallService("switch", "turn_off", It.Is<ServiceTarget>(t => t.EntityIds!.Contains(AutoManagement)), null),
|
||||
Times.Once);
|
||||
_haContextMock.Verify(
|
||||
x => x.CallService("persistent_notification", "create", It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
|
||||
Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TriggerLimitBreach_WhenAlreadyActive_ShouldDoNothing()
|
||||
{
|
||||
var sut = CreateSut();
|
||||
sut.TriggerLimitBreach();
|
||||
_haContextMock.Invocations.Clear();
|
||||
|
||||
sut.TriggerLimitBreach();
|
||||
|
||||
_haContextMock.Verify(
|
||||
x => x.CallService(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ServiceTarget>(), It.IsAny<object?>()),
|
||||
Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ResetLimitBreach_WhenActive_ShouldRecoverWithoutWaiting()
|
||||
{
|
||||
var sut = CreateSut();
|
||||
sut.TriggerLimitBreach();
|
||||
_haContextMock.Invocations.Clear();
|
||||
|
||||
sut.ResetLimitBreach();
|
||||
|
||||
sut.IsLimitActive.Should().BeFalse();
|
||||
_haContextMock.Verify(
|
||||
x => x.CallService("switch", "turn_on", It.Is<ServiceTarget>(t => t.EntityIds!.Contains(AutoManagement)), null),
|
||||
Times.Once);
|
||||
_haContextMock.Verify(
|
||||
x => x.CallService("persistent_notification", "dismiss", It.IsAny<ServiceTarget?>(), It.IsAny<object?>()),
|
||||
Times.Once);
|
||||
// boiler switch should NOT be turned on
|
||||
_haContextMock.Verify(
|
||||
x => x.CallService("switch", "turn_on", It.Is<ServiceTarget>(t => t.EntityIds!.Contains(BoilerSwitch)), null),
|
||||
Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ResetLimitBreach_WhenNotActive_ShouldDoNothing()
|
||||
{
|
||||
var sut = CreateSut();
|
||||
|
||||
sut.ResetLimitBreach();
|
||||
|
||||
_haContextMock.Verify(
|
||||
x => x.CallService(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<ServiceTarget>(), It.IsAny<object?>()),
|
||||
Times.Never);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void TriggerLimitBreach_WhenDisabled_ShouldStillEnforce()
|
||||
{
|
||||
_options.EnforceLimitEnabled = false;
|
||||
var sut = CreateSut();
|
||||
|
||||
sut.TriggerLimitBreach();
|
||||
|
||||
sut.IsLimitActive.Should().BeTrue("debug trigger bypasses EnforceLimitEnabled so the button always works");
|
||||
_haContextMock.Verify(
|
||||
x => x.CallService("switch", "turn_off", It.IsAny<ServiceTarget>(), It.IsAny<object?>()),
|
||||
Times.AtLeastOnce);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace PowerMonitorManager.Interface;
|
||||
|
||||
public interface IPowerLimitEnforcementService
|
||||
{
|
||||
void EnforceLimit(double currentPowerWatts);
|
||||
|
||||
void TriggerLimitBreach();
|
||||
|
||||
void ResetLimitBreach();
|
||||
|
||||
bool IsLimitActive { get; }
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
"mcp": {
|
||||
"homeassistant": {
|
||||
"type": "local",
|
||||
"command": [
|
||||
"dotnet",
|
||||
"run",
|
||||
"--project",
|
||||
"HomeAssistant.McpServer/HomeAssistant.McpServer.csproj",
|
||||
"--configuration",
|
||||
"Debug",
|
||||
"--verbosity",
|
||||
"quiet"
|
||||
],
|
||||
"enabled": true,
|
||||
"timeout": 60000,
|
||||
"environment": {
|
||||
"DOTNET_NO_LOGO": "1",
|
||||
"DOTNET_ENVIRONMENT": "Development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user