# 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`). ## 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` + `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() ``` 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 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`