From 1152462765adca3b47ed3ca8c265d4af30c53319 Mon Sep 17 00:00:00 2001 From: ExQz Date: Sun, 29 Nov 2026 13:58:28 +0200 Subject: [PATCH] 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. --- .junie/mcp/mcp.json | 16 + .junie/mcp/mcp.json.bak | 13 + PLAN.md | 190 ++++++++++ .../PowerLimitEnforcementServiceTests.cs | 345 ++++++++++++++++++ .../IPowerLimitEnforcementService.cs | 12 + .../PowerLimitEnforcementService.cs | 193 ++++++++++ opencode.json | 24 ++ 7 files changed, 793 insertions(+) create mode 100644 .junie/mcp/mcp.json create mode 100644 .junie/mcp/mcp.json.bak create mode 100644 PLAN.md create mode 100644 PowerMonitor.Manager.Tests/PowerLimitEnforcementServiceTests.cs create mode 100644 PowerMonitor.Manager/Interface/IPowerLimitEnforcementService.cs create mode 100644 PowerMonitor.Manager/PowerLimitEnforcementService.cs create mode 100644 opencode.json diff --git a/.junie/mcp/mcp.json b/.junie/mcp/mcp.json new file mode 100644 index 0000000..96c873f --- /dev/null +++ b/.junie/mcp/mcp.json @@ -0,0 +1,16 @@ +{ + "mcpServers": { + "UnoApp": { + "command": "dotnet", + "args": [ + "dnx", + "-y", + "uno.devserver", + "--mcp-app" + ] + }, + "UnoDocs": { + "url": "https://mcp.platform.uno/v1" + } + } +} \ No newline at end of file diff --git a/.junie/mcp/mcp.json.bak b/.junie/mcp/mcp.json.bak new file mode 100644 index 0000000..a7bc519 --- /dev/null +++ b/.junie/mcp/mcp.json.bak @@ -0,0 +1,13 @@ +{ + "mcpServers": { + "UnoApp": { + "command": "dotnet", + "args": [ + "dnx", + "-y", + "uno.devserver", + "--mcp-app" + ] + } + } +} diff --git a/PLAN.md b/PLAN.md new file mode 100644 index 0000000..4c7fc07 --- /dev/null +++ b/PLAN.md @@ -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`). + +## 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` \ No newline at end of file diff --git a/PowerMonitor.Manager.Tests/PowerLimitEnforcementServiceTests.cs b/PowerMonitor.Manager.Tests/PowerLimitEnforcementServiceTests.cs new file mode 100644 index 0000000..2556909 --- /dev/null +++ b/PowerMonitor.Manager.Tests/PowerLimitEnforcementServiceTests.cs @@ -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 _haContextMock; + private readonly Mock> _loggerMock; + private readonly FakeTimeProvider _timeProvider; + private readonly PowerMonitorOptions _options; + + public PowerLimitEnforcementServiceTests() + { + _haContextMock = new Mock(); + _loggerMock = new Mock>(); + _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(), It.IsAny(), It.IsAny(), It.IsAny()), + 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(), It.IsAny(), It.IsAny(), It.IsAny()), + 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(t => t.EntityIds!.Contains(BoilerSwitch)), null), + Times.Once); + _haContextMock.Verify( + x => x.CallService("switch", "turn_off", It.Is(t => t.EntityIds!.Contains(AutoManagement)), null), + Times.Once); + // notification created + _haContextMock.Verify( + x => x.CallService("persistent_notification", "create", It.IsAny(), It.IsAny()), + 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(), It.IsAny(), It.IsAny(), It.IsAny())) + .Callback((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(), It.IsAny(), It.IsAny(), It.IsAny()), + 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(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(t => t.EntityIds!.Contains(BoilerSwitch)), null), + Times.Never); + // notification dismissed + _haContextMock.Verify( + x => x.CallService("persistent_notification", "dismiss", It.IsAny(), It.IsAny()), + 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(), It.IsAny()), + Times.Never); + _haContextMock.Verify( + x => x.CallService("persistent_notification", "dismiss", It.IsAny(), It.IsAny()), + 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(), It.IsAny()), + 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(), It.IsAny()), + 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(), It.IsAny(), It.IsAny(), It.IsAny()), + 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(t => t.EntityIds!.Contains(BoilerSwitch)), null), + Times.Once); + _haContextMock.Verify( + x => x.CallService("switch", "turn_off", It.Is(t => t.EntityIds!.Contains(AutoManagement)), null), + Times.Once); + _haContextMock.Verify( + x => x.CallService("persistent_notification", "create", It.IsAny(), It.IsAny()), + 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(), It.IsAny(), It.IsAny(), It.IsAny()), + 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(t => t.EntityIds!.Contains(AutoManagement)), null), + Times.Once); + _haContextMock.Verify( + x => x.CallService("persistent_notification", "dismiss", It.IsAny(), It.IsAny()), + Times.Once); + // boiler switch should NOT be turned on + _haContextMock.Verify( + x => x.CallService("switch", "turn_on", It.Is(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(), It.IsAny(), It.IsAny(), It.IsAny()), + 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(), It.IsAny()), + Times.AtLeastOnce); + } +} \ No newline at end of file diff --git a/PowerMonitor.Manager/Interface/IPowerLimitEnforcementService.cs b/PowerMonitor.Manager/Interface/IPowerLimitEnforcementService.cs new file mode 100644 index 0000000..26b80b1 --- /dev/null +++ b/PowerMonitor.Manager/Interface/IPowerLimitEnforcementService.cs @@ -0,0 +1,12 @@ +namespace PowerMonitorManager.Interface; + +public interface IPowerLimitEnforcementService +{ + void EnforceLimit(double currentPowerWatts); + + void TriggerLimitBreach(); + + void ResetLimitBreach(); + + bool IsLimitActive { get; } +} \ No newline at end of file diff --git a/PowerMonitor.Manager/PowerLimitEnforcementService.cs b/PowerMonitor.Manager/PowerLimitEnforcementService.cs new file mode 100644 index 0000000..44726ad --- /dev/null +++ b/PowerMonitor.Manager/PowerLimitEnforcementService.cs @@ -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 logger, + IOptions 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); + } +} \ No newline at end of file diff --git a/opencode.json b/opencode.json new file mode 100644 index 0000000..c21a48c --- /dev/null +++ b/opencode.json @@ -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" + } + } + } +} \ No newline at end of file